Proyectos de Subversion LeadersLinked - Services

Rev

Rev 581 | Rev 585 | Ir a la última revisión | | Comparar con el anterior | Ultima modificación | Ver Log |

Rev Autor Línea Nro. Línea
119 efrain 1
<?php
2
declare(strict_types=1);
3
 
4
namespace LeadersLinked\Controller;
5
 
6
use Laminas\Mvc\Controller\AbstractActionController;
7
use Laminas\View\Model\JsonModel;
8
use LeadersLinked\Library\Functions;
283 www 9
use LeadersLinked\Mapper\MicrolearningCapsuleMapper;
119 efrain 10
use LeadersLinked\Mapper\QueryMapper;
11
use LeadersLinked\Mapper\UserMapper;
12
use Laminas\Db\Sql\Select;
283 www 13
use LeadersLinked\Mapper\MicrolearningCapsuleUserMapper;
14
use LeadersLinked\Mapper\MicrolearningCapsuleCommentMapper;
119 efrain 15
use LeadersLinked\Form\Service\CapsuleCommentForm;
283 www 16
use LeadersLinked\Model\MicrolearningCapsuleComment;
17
use LeadersLinked\Model\MicrolearningCapsuleUser;
18
use LeadersLinked\Model\MicrolearningAnswer;
19
use LeadersLinked\Mapper\MicrolearningUserProgressMapper;
20
use LeadersLinked\Mapper\MicrolearningSlideMapper;
21
use LeadersLinked\Mapper\MicrolearningUserLogMapper;
22
use LeadersLinked\Model\MicrolearningUserLog;
23
use LeadersLinked\Mapper\MicrolearningTopicMapper;
119 efrain 24
use LeadersLinked\Mapper\CompanyMapper;
283 www 25
use LeadersLinked\Model\MicrolearningUserProgress;
26
use LeadersLinked\Mapper\MicrolearningExtendUserMapper;
27
use LeadersLinked\Mapper\MicrolearningExtendUserCompanyMapper;
28
use LeadersLinked\Mapper\MicrolearningExtendUserFunctionMapper;
29
use LeadersLinked\Mapper\MicrolearningExtendUserGroupMapper;
30
use LeadersLinked\Mapper\MicrolearningExtendUserInstitutionMapper;
31
use LeadersLinked\Mapper\MicrolearningExtendUserPartnerMapper;
32
use LeadersLinked\Mapper\MicrolearningExtendUserProgramMapper;
33
use LeadersLinked\Mapper\MicrolearningExtendUserStudentTypeMapper;
34
use LeadersLinked\Mapper\MicrolearningExtendUserSectorMapper;
35
use LeadersLinked\Mapper\MicrolearningQuizMapper;
36
use LeadersLinked\Mapper\MicrolearningQuestionMapper;
37
use LeadersLinked\Mapper\MicrolearningAnswerMapper;
38
use LeadersLinked\Model\MicrolearningSlide;
39
use LeadersLinked\Library\Storage;
302 www 40
use LeadersLinked\Mapper\MicrolearningTopicCapsuleMapper;
119 efrain 41
 
42
 
43
class MicrolearningUserAccessGrantedIds
44
{
45
    public $companies;
46
    public $topics;
47
    public $capsules;
48
 
49
 
50
    public function __construct()
51
    {
52
        $this->companies    = [];
53
        $this->topics       = [];
54
        $this->capsules     = [];
55
    }
56
}
57
 
58
class MicrolearningController extends AbstractActionController
59
{
60
 
61
    /**
62
     *
63
     * @var \Laminas\Db\Adapter\AdapterInterface
64
     */
65
    private $adapter;
66
 
67
    /**
68
     *
69
     * @var \LeadersLinked\Cache\CacheInterface
70
     */
71
    private $cache;
72
 
73
 
74
    /**
75
     *
76
     * @var \Laminas\Log\LoggerInterface
77
     */
78
    private $logger;
79
 
80
    /**
81
     *
82
     * @var array
83
     */
84
    private $config;
85
 
86
 
87
    /**
88
     *
89
     * @var \Laminas\Mvc\I18n\Translator
90
     */
91
    private $translator;
92
 
93
 
94
    /**
95
     *
96
     * @param \Laminas\Db\Adapter\AdapterInterface $adapter
97
     * @param \LeadersLinked\Cache\CacheInterface $cache
98
     * @param \Laminas\Log\LoggerInterface LoggerInterface $logger
99
     * @param array $config
100
     * @param \Laminas\Mvc\I18n\Translator $translator
101
     */
102
    public function __construct($adapter, $cache, $logger, $config, $translator)
103
    {
104
        $this->adapter      = $adapter;
105
        $this->cache        = $cache;
106
        $this->logger       = $logger;
107
        $this->config       = $config;
108
        $this->translator   = $translator;
109
    }
110
 
111
    public function indexAction()
112
    {
113
        $request = $this->getRequest();
114
 
115
        if($request->isGet()) {
116
            return new JsonModel([
117
                'success' => true,
118
                'data' =>  [
119
                    'link_companies' => $this->url()->fromRoute('microlearning/companies',[], ['force_canonical' => true]),
120
                    'link_timeline' => $this->url()->fromRoute('microlearning/timeline',[], ['force_canonical' => true]),
121
                    'link_last_capsule_in_progress' => $this->url()->fromRoute('microlearning/last-capsule-in-progress',[], ['force_canonical' => true]),
122
                    'link_profile' => $this->url()->fromRoute('microlearning/profile',[], ['force_canonical' => true]),
123
                    'link_topics' => $this->url()->fromRoute('microlearning/topics',[], ['force_canonical' => true]),
124
                    'link_capsules_pending' => $this->url()->fromRoute('microlearning/capsules-pending',[], ['force_canonical' => true]),
125
                    'link_capsules_completed' => $this->url()->fromRoute('microlearning/capsules-completed',[], ['force_canonical' => true]),
126
                    'link_capsules_in_progress' => $this->url()->fromRoute('microlearning/capsules-in-progress',[], ['force_canonical' => true]),
127
 
128
 
129
                ]
130
            ]);
131
        }
132
 
133
        return new JsonModel([
134
            'success' => false,
135
            'data' => 'ERROR_METHOD_NOT_ALLOWED'
136
        ]);
137
    }
138
 
139
    public function companiesAction()
140
    {
141
 
142
        $request = $this->getRequest();
143
 
144
        if($request->isGet()) {
145
            $currentNetworkPlugin = $this->plugin('currentNetworkPlugin');
146
            $currentNetwork = $currentNetworkPlugin->getNetwork();
147
 
148
 
149
            $accessGrantedIds = $this->getAccessGranted();
150
            $companyMapper = CompanyMapper::getInstance($this->adapter);
151
            $records = $companyMapper->fetchAllByIdsAndNetworkId($accessGrantedIds->companies, $currentNetwork->id);
152
 
333 www 153
            $storage = Storage::getInstance($this->config, $this->adapter);
119 efrain 154
 
155
            $companies = [];
156
            foreach($records as $record)
157
            {
158
                array_push($companies, [
164 efrain 159
                    'uuid' => $record->uuid,
119 efrain 160
                    'name' => $record->name,
283 www 161
                    'image' => $storage->getCompanyImage($record),
119 efrain 162
                    'link_progress' => $this->url()->fromRoute('microlearning/progress',['id' => $record->uuid], ['force_canonical' => true]),
163
                ]);
164
            }
165
 
166
            return new JsonModel([
167
                'success' => true,
168
                'data' =>  $companies
169
            ]);
170
 
171
 
172
        }
173
        return new JsonModel([
174
            'success' => false,
175
            'data' => 'ERROR_METHOD_NOT_ALLOWED'
176
        ]);
177
    }
178
 
179
 
180
 
181
    public function capsuleCommentsAction()
182
    {
183
 
184
        $request = $this->getRequest();
185
 
186
        if($request->isGet()) {
187
            $serviceDatetimeFormat = $this->config['leaderslinked.services.datetime'];
188
 
189
            $currentUserPlugin = $this->plugin('currentUserPlugin');
190
            $currentUser = $currentUserPlugin->getUser();
191
 
192
            $capsule_id = $this->params()->fromRoute('capsule_id');
193
 
283 www 194
            $capsuleMapper = MicrolearningCapsuleMapper::getInstance($this->adapter);
119 efrain 195
            $capsule = $capsuleMapper->fetchOneByUuid($capsule_id);
196
 
197
            if(!$capsule) {
198
                return new JsonModel([
199
                    'success' => false,
200
                    'data' => 'ERROR_CAPSULE_NOT_FOUND'
201
 
202
                ]);
203
 
204
            }
205
 
283 www 206
            $capsuleUserMapper = MicrolearningCapsuleUserMapper::getInstance($this->adapter);
119 efrain 207
            $capsuleUser = $capsuleUserMapper->fetchOneByUserIdAndCapsuleId($currentUser->id, $capsule->id);
208
            if(! $capsuleUser) {
209
                return new JsonModel([
210
                    'success' => false,
211
                    'data' => 'ERROR_YOU_DO_NOT_HAVE_ACCESS_TO_THIS_CAPSULE',
212
                ]);
213
            }
214
 
215
            $userMapper = UserMapper::getInstance($this->adapter);
216
            $users = [];
217
 
283 www 218
 
333 www 219
            $storage = Storage::getInstance($this->config, $this->adapter);
283 www 220
 
221
            $capsuleCommentMapper = MicrolearningCapsuleCommentMapper::getInstance($this->adapter);
119 efrain 222
            $records = $capsuleCommentMapper->fetchAllByCapsuleId($capsule->id);
223
 
224
            $comments = [];
225
            foreach($records as $record)
226
            {
227
 
228
                if(isset($users[$record->user_id])) {
229
 
230
                    $user = $users[$record->user_id];
231
 
232
                } else {
233
 
234
                    $user = $userMapper->fetchOne($record->user_id);
235
                    if(!$user) {
236
                        continue;
237
                    }
238
 
239
                    $users[$record->user_id] = $user;
240
 
241
 
242
                }
243
 
244
 
245
                $dt = \DateTime::createFromFormat('Y-m-d H:i:s', $record->added_on);
246
 
247
                array_push($comments, [
248
                    'date' => $dt->format($serviceDatetimeFormat),
283 www 249
                    'image' => $storage->getUserImage($user),
119 efrain 250
                    'fullname' => trim(trim($user->first_name) . ' ' . trim($user->last_name)),
251
                    'rating' => strval($record->rating),
252
                    'comment' => $record->comment,
253
                    'link_delete' => $record->user_id == $currentUser->id ? $this->url()->fromRoute('microlearning/capsules-comments/delete', ['capsule_id' => $capsule->uuid, 'comment_id' => $record->uuid], ['force_canonical' => true]) : '',
254
                ]);
255
            }
256
 
302 www 257
            $dataCountAndRatingAverage = $capsuleCommentMapper->fetchCountAndRatingAverage($capsule->company_id, $capsule->id);
119 efrain 258
 
259
            return new JsonModel([
260
                'success' => true,
261
                'data' => [
262
                    'comments' => $comments,
263
                    'capsule' => [
264
                        'total_comments' => strval($dataCountAndRatingAverage['total_comments']),
265
                        'total_rating' => strval($dataCountAndRatingAverage['total_rating'])
266
                    ]
267
                ]
268
 
269
            ]);
270
 
271
        }
272
 
273
        return new JsonModel([
274
            'success' => false,
275
            'data' => 'ERROR_METHOD_NOT_ALLOWED'
276
        ]);
277
    }
278
 
279
 
280
 
281
    public function capsuleDeleteMyCommentAction()
282
    {
283
 
284
        $request = $this->getRequest();
285
 
286
        if($request->isPost()) {
287
 
288
            $currentUserPlugin = $this->plugin('currentUserPlugin');
289
            $currentUser = $currentUserPlugin->getUser();
290
 
291
            $capsule_id = $this->params()->fromRoute('capsule_id');
292
            $comment_id = $this->params()->fromRoute('comment_id');
293
 
283 www 294
            $capsuleMapper = MicrolearningCapsuleMapper::getInstance($this->adapter);
119 efrain 295
            $capsule = $capsuleMapper->fetchOneByUuid($capsule_id);
296
 
297
            if(!$capsule) {
298
                return new JsonModel([
299
                    'success' => false,
300
                    'data' => 'ERROR_CAPSULE_NOT_FOUND'
301
 
302
                ]);
303
 
304
            }
305
 
283 www 306
            $capsuleUserMapper = MicrolearningCapsuleUserMapper::getInstance($this->adapter);
119 efrain 307
            $capsuleUser = $capsuleUserMapper->fetchOneByUserIdAndCapsuleId($currentUser->id, $capsule->id);
308
            if(! $capsuleUser) {
309
                return new JsonModel([
310
                    'success' => false,
311
                    'data' => 'ERROR_YOU_DO_NOT_HAVE_ACCESS_TO_THIS_CAPSULE',
312
                ]);
313
            }
314
 
283 www 315
            $capsuleCommentMapper = MicrolearningCapsuleCommentMapper::getInstance($this->adapter);
119 efrain 316
            $capsuleComment = $capsuleCommentMapper->fetchOneByUuid($comment_id);
317
 
318
            if(!$capsuleComment) {
319
                return new JsonModel([
320
                    'success' => false,
321
                    'data' => 'ERROR_CAPSULE_COMMENT_NOT_FOUND',
322
                ]);
323
            }
324
 
325
            if($capsuleComment->capsule_id != $capsule->id || $capsuleComment->user_id != $currentUser->id) {
326
                return new JsonModel([
327
                    'success' => false,
328
                    'data' => 'ERROR_YOU_DO_NOT_HAVE_ACCESS_TO_THIS_CAPSULE_COMMENT',
329
                ]);
330
            }
331
 
332
 
333
            $result = $capsuleCommentMapper->delete($capsuleComment->id);
334
            if($result) {
302 www 335
                $dataCountAndRatingAverage = $capsuleCommentMapper->fetchCountAndRatingAverage($capsule->company_id, $capsule->id);
119 efrain 336
 
337
 
338
 
339
 
340
                return new JsonModel([
341
                    'success' => true,
342
                    'data' => [
343
                        'message' => 'LABEL_CAPSULE_COMMENT_HAVE_BEEN_SUCCESSFULLY_DELETE',
344
                        'capsule' => [
345
                            'total_comments' => strval($dataCountAndRatingAverage['total_comments']),
346
                            'total_rating' => strval($dataCountAndRatingAverage['total_rating'])
347
                        ]
348
                    ],
349
 
350
                ]);
351
            } else {
352
                return new JsonModel([
353
                    'success' => false,
354
                    'data' => $capsuleCommentMapper->getError()
355
 
356
                ]);
357
            }
358
 
359
 
360
 
361
        }
362
 
363
        return new JsonModel([
364
            'success' => false,
365
            'data' => 'ERROR_METHOD_NOT_ALLOWED'
366
        ]);
367
    }
368
 
369
    public function capsuleAddMyCommentAction()
370
    {
371
 
372
        $request = $this->getRequest();
373
 
374
        if($request->isPost()) {
375
 
376
            $currentUserPlugin = $this->plugin('currentUserPlugin');
377
            $currentUser = $currentUserPlugin->getUser();
378
 
379
            $capsule_id = $this->params()->fromRoute('capsule_id');
380
 
381
 
283 www 382
            $capsuleMapper = MicrolearningCapsuleMapper::getInstance($this->adapter);
119 efrain 383
            $capsule = $capsuleMapper->fetchOneByUuid($capsule_id);
384
 
385
            if(!$capsule) {
386
                return new JsonModel([
387
                    'success' => false,
388
                    'data' => 'ERROR_CAPSULE_NOT_FOUND'
389
 
390
                ]);
391
 
392
            }
393
 
283 www 394
            $capsuleUserMapper = MicrolearningCapsuleUserMapper::getInstance($this->adapter);
119 efrain 395
            $capsuleUser = $capsuleUserMapper->fetchOneByUserIdAndCapsuleId($currentUser->id, $capsule->id);
396
            if(! $capsuleUser) {
397
                return new JsonModel([
398
                    'success' => false,
399
                    'data' => 'ERROR_YOU_DO_NOT_HAVE_ACCESS_TO_THIS_CAPSULE',
400
                ]);
401
            }
402
 
403
            //$rawdata = file_get_contents("php://input");
404
            //  error_log('$rawdata = ' . $rawdata );
405
 
406
 
407
            $form = new  CapsuleCommentForm();
408
            $dataPost = $request->getPost()->toArray();
409
            $dataPost['added_on'] = $capsuleMapper->getDatebaseNow();
410
 
411
 
412
            $form->setData($dataPost);
413
 
414
            if($form->isValid()) {
415
                $dataPost = (array) $form->getData();
416
 
417
 
283 www 418
                $capsuleComment = new MicrolearningCapsuleComment();
119 efrain 419
                $capsuleComment->company_id = $capsule->company_id;
420
                $capsuleComment->capsule_id = $capsule->id;
421
                $capsuleComment->user_id = $currentUser->id;
422
                $capsuleComment->comment = $dataPost['comment'];
423
                $capsuleComment->rating = strval($dataPost['rating']);
424
                $capsuleComment->added_on =  $dataPost['added_on'];
425
 
426
 
283 www 427
                $capsuleCommentMapper = MicrolearningCapsuleCommentMapper::getInstance($this->adapter);
119 efrain 428
                $result = $capsuleCommentMapper->insert($capsuleComment);
429
                if($result) {
430
 
431
                    $capsuleComment = $capsuleCommentMapper->fetchOne($capsuleComment->id);
432
 
302 www 433
                    $dataCountAndRatingAverage = $capsuleCommentMapper->fetchCountAndRatingAverage($capsule->company_id,  $capsule->id);
119 efrain 434
 
435
 
436
 
437
                    return new JsonModel([
438
                        'success' => true,
439
                        'data' => [
440
                            'message' =>'LABEL_CAPSULE_COMMENT_HAVE_BEEN_SUCCESSFULLY_ADDED',
441
 
442
                            'comment' => [
443
                                'comment' => $capsuleComment->comment,
444
                                'rating' => $capsuleComment->rating,
445
                                'link_delete' => $this->url()->fromRoute('microlearning/capsules-comments/delete', ['capsule_id' => $capsule->uuid, 'comment_id' => $capsuleComment->uuid], ['force_canonical' => true])
446
                            ],
447
                            'capsule' => [
448
                                'total_comments' => strval($dataCountAndRatingAverage['total_comments']),
449
                                'total_rating' => strval($dataCountAndRatingAverage['total_rating'])
450
                            ]
451
                        ]
452
 
453
                    ]);
454
                } else {
455
                    return new JsonModel([
456
                        'success' => false,
457
                        'data' => $capsuleCommentMapper->getError()
458
 
459
                    ]);
460
                }
461
 
462
 
463
            } else {
464
                $messages = [];
465
                $form_messages = (array) $form->getMessages();
466
                foreach($form_messages  as $fieldname => $field_messages)
467
                {
468
 
469
                    $messages[$fieldname] = array_values($field_messages);
470
                }
471
 
472
                return new JsonModel([
473
                    'success'   => false,
474
                    'data'   => $messages
475
                ]);
476
            }
477
 
478
 
479
 
480
 
481
        }
482
 
483
        return new JsonModel([
484
            'success' => false,
485
            'data' => 'ERROR_METHOD_NOT_ALLOWED'
486
        ]);
487
    }
488
 
489
    public function lastCapsuleInProgressAction()
490
    {
491
        $request = $this->getRequest();
492
 
493
        if($request->isGet())
494
        {
495
            $currentUserPlugin = $this->plugin('currentUserPlugin');
496
            $currentUser = $currentUserPlugin->getUser();
497
 
498
            $accessGrantedIds = $this->getAccessGranted();
499
 
500
 
283 www 501
            $userProgressMapper = MicrolearningUserProgressMapper::getInstance($this->adapter);
119 efrain 502
            $userProgress = $userProgressMapper->fetchOneLastCapsuleInProgressByUserIdAndCapsuleIds($currentUser->id, $accessGrantedIds->capsules);
283 www 503
            $topicMapper = MicrolearningTopicMapper::getInstance($this->adapter);
119 efrain 504
 
505
            if($userProgress) {
333 www 506
                $storage = Storage::getInstance($this->config, $this->adapter);
283 www 507
                $path = $storage->getPathMicrolearningCapsule();
508
 
509
                $capsuleMapper = MicrolearningCapsuleMapper::getInstance($this->adapter);
119 efrain 510
                $capsule = $capsuleMapper->fetchOne($userProgress->capsule_id);
511
 
301 www 512
                $topic = $topicMapper->fetchOne($userProgress->topic_id);
513
 
283 www 514
                $capsuleCommentMapper = MicrolearningCapsuleCommentMapper::getInstance($this->adapter);
302 www 515
                $dataCountAndRatingAverage = $capsuleCommentMapper->fetchCountAndRatingAverage($capsule->company_id,  $capsule->id);
576 stevensc 516
                $image = $storage->getGenericImage($path, $topic->uuid, $capsule->image);
517
 
119 efrain 518
                $response = [
519
                    'success' => true,
520
                    'data' => [
164 efrain 521
                        'uuid'              => $capsule->uuid,
119 efrain 522
                        'name'              => $capsule->name ? $capsule->name : '',
523
                        'description'       => $capsule->description ? $capsule->description : '',
575 stevensc 524
                        'image'             => ($capsule->image && $topic) ? $storage->getGenericImage($path,  $topic->uuid, $capsule->image )  : '',
119 efrain 525
                        'total_comments'    => strval($dataCountAndRatingAverage['total_comments']),
526
                        'total_rating'      => strval($dataCountAndRatingAverage['total_rating']),
527
                        'completed'         => $userProgress->completed,
145 efrain 528
                        'progress'          => $userProgress->progress,
119 efrain 529
                        'added_on'          => $userProgress->added_on,
530
                        'updated_on'        => $userProgress->updated_on
531
                    ]
532
                ];
533
 
534
 
535
            } else {
536
                $response = [
537
                    'success' => true,
575 stevensc 538
                    'data' => []
119 efrain 539
                ];
540
            }
541
 
542
 
543
        } else {
544
 
545
            $response = [
546
                'success' => false,
547
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
548
            ];
549
 
550
 
551
        }
552
 
553
        return new JsonModel($response);
554
    }
555
 
556
    public function capsulesPendingAction()
557
    {
558
        $request = $this->getRequest();
559
        if($request->isGet()) {
560
            $currentUserPlugin = $this->plugin('currentUserPlugin');
561
            $currentUser = $currentUserPlugin->getUser();
562
 
563
            $name = Functions::sanitizeFilterString($this->params()->fromQuery('name'));
245 efrain 564
            $order_field = Functions::sanitizeFilterString($this->params()->fromQuery('order_field'));
565
            $order_direction = Functions::sanitizeFilterString($this->params()->fromQuery('order_direction'));
119 efrain 566
 
245 efrain 567
            if(!in_array($order_field,['name', 'added_on'] )) {
568
                $order_field = 'name';
569
            }
119 efrain 570
 
245 efrain 571
            if(!in_array( $order_direction,['asc', 'desc'])) {
558 stevensc 572
                $order_direction = 'asc'; // Corregido: asignar a $order_direction
245 efrain 573
            }
574
 
283 www 575
            $userProgressMapper = MicrolearningUserProgressMapper::getInstance($this->adapter);
576
            $capsuleMapper = MicrolearningCapsuleMapper::getInstance($this->adapter);
558 stevensc 577
            $topicCapsuleMapper = MicrolearningTopicCapsuleMapper::getInstance($this->adapter); // Añadido
283 www 578
            $topicMapper = MicrolearningTopicMapper::getInstance($this->adapter);
558 stevensc 579
            $capsuleCommentMapper = MicrolearningCapsuleCommentMapper::getInstance($this->adapter); // Reordenado
119 efrain 580
 
581
            $accessGranted = $this->getAccessGranted();
558 stevensc 582
 
583
            // $topics = []; // Ya no es necesario cachear tópicos aquí
584
            $capsulesData = []; // Renombrado
119 efrain 585
 
333 www 586
            $storage = Storage::getInstance($this->config, $this->adapter);
283 www 587
            $path = $storage->getPathMicrolearningCapsule();
588
 
119 efrain 589
            foreach($accessGranted->capsules as $capsule_id)
590
            {
558 stevensc 591
                // 1. Verificar progreso (debe ser nulo para pendiente)
119 efrain 592
                $userProgress = $userProgressMapper->fetchOneByUseridAndCapsuleId($currentUser->id, $capsule_id);
593
                if($userProgress) {
594
                    continue;
595
                }
558 stevensc 596
 
597
                // 2. Obtener detalles de la cápsula
119 efrain 598
                $capsule = $capsuleMapper->fetchOne($capsule_id);
558 stevensc 599
                if(!$capsule) { // Añadir verificación por si la cápsula no existe
600
                    continue;
601
                }
119 efrain 602
 
558 stevensc 603
                // 3. Filtrar por nombre
119 efrain 604
                if($name) {
605
                    if(empty($name) || stripos($capsule->name, $name) === false) {
606
                        continue;
607
                    }
608
                }
609
 
558 stevensc 610
                // 4. Obtener Tópico asociado válido
611
                $topic = null;
612
                $topic_uuid_for_links = null;
613
                $relation = $topicCapsuleMapper->fetchOneByCapsuleId($capsule->id);
614
                if ($relation && in_array($relation->topic_id, $accessGranted->topics)) {
615
                    $topic = $topicMapper->fetchOne($relation->topic_id);
616
                    if ($topic) {
617
                        $topic_uuid_for_links = $topic->uuid;
618
                    }
619
                }
620
 
621
                // 5. Obtener datos de comentarios
302 www 622
                $dataCountAndRatingAverage = $capsuleCommentMapper->fetchCountAndRatingAverage($capsule->company_id,  $capsule->id);
119 efrain 623
 
558 stevensc 624
                // 6. Construir enlace slides
625
                $link_slides = $topic_uuid_for_links ? $this->url()->fromRoute('microlearning/slides', ['topic_id' => $topic_uuid_for_links,  'capsule_id' => $capsule->uuid], ['force_canonical' => true]) : '';
119 efrain 626
 
558 stevensc 627
                // 7. Añadir al array de resultados
628
                array_push($capsulesData, [
119 efrain 629
                    'uuid'              => $capsule->uuid,
630
                    'name'              => $capsule->name ? $capsule->name : '',
631
                    'description'       => $capsule->description ? $capsule->description : '',
283 www 632
                    'image'             => $capsule->image ? $storage->getGenericImage($path, $capsule->uuid, $capsule->image)  : '',
119 efrain 633
                    'position'          => $capsule->order,
634
                    'link_comments'     => $this->url()->fromRoute('microlearning/capsules-comments', ['capsule_id' => $capsule->uuid], ['force_canonical' => true]),
635
                    'link_comment_add'  => $this->url()->fromRoute('microlearning/capsules-comments/add', ['capsule_id' => $capsule->uuid],['force_canonical' => true]),
558 stevensc 636
                    'link_slides'       => $link_slides, // Usar enlace construido
119 efrain 637
                    'total_comments'    => strval($dataCountAndRatingAverage['total_comments']),
638
                    'total_rating'      => strval($dataCountAndRatingAverage['total_rating']),
191 efrain 639
                    'progress'          => 0,
162 efrain 640
                    'link_get'          => $this->url()->fromRoute('microlearning/get-capsule', ['id' => $capsule->uuid], ['force_canonical' => true]),
119 efrain 641
                    'added_on'          => $capsule->added_on,
642
                    'updated_on'        => $capsule->updated_on,
643
                ]);
644
            }
645
 
558 stevensc 646
            // 8. Ordenar
245 efrain 647
 
648
            if($order_field == 'name') {
649
                if($order_direction == 'asc') {
558 stevensc 650
                    usort($capsulesData, function($a, $b) {
245 efrain 651
                        return strcasecmp($a['name'], $b['name']);
652
                    });
653
                } else {
558 stevensc 654
                    usort($capsulesData, function($a, $b) {
245 efrain 655
                        $result = strcasecmp($a['name'], $b['name']);
558 stevensc 656
                        if($result < 0) { return 1; } else if($result > 0) { return -1; } else { return 0; } // Simplificado
245 efrain 657
                    });
119 efrain 658
                }
659
 
245 efrain 660
            }
661
 
662
            if($order_field == 'added_on') {
663
                if($order_direction == 'asc') {
558 stevensc 664
                    usort($capsulesData, function($a, $b) {
245 efrain 665
                        return strcasecmp($a['added_on'], $b['added_on']);
666
                    });
667
                } else {
558 stevensc 668
                    usort($capsulesData, function($a, $b) {
245 efrain 669
                        $result = strcasecmp($a['added_on'], $b['added_on']);
558 stevensc 670
                        if($result < 0) { return 1; } else if($result > 0) { return -1; } else { return 0; } // Simplificado
245 efrain 671
                    });
672
                }
119 efrain 673
 
558 stevensc 674
            }
119 efrain 675
 
558 stevensc 676
            // 9. Retornar
119 efrain 677
            return new JsonModel([
678
                'success' => true,
558 stevensc 679
                'data' => $capsulesData
119 efrain 680
            ]);
681
 
682
 
683
 
684
        }
685
 
686
        return new JsonModel([
687
            'success' => false,
688
            'data' => 'ERROR_METHOD_NOT_ALLOWED'
689
        ]);
690
 
691
    }
692
 
693
    public function capsulesCompletedAction()
694
    {
695
        $request = $this->getRequest();
696
        if($request->isGet()) {
697
            $currentUserPlugin = $this->plugin('currentUserPlugin');
698
            $currentUser = $currentUserPlugin->getUser();
699
 
700
            $name = Functions::sanitizeFilterString($this->params()->fromQuery('name'));
245 efrain 701
            $order_field = Functions::sanitizeFilterString($this->params()->fromQuery('order_field'));
702
            $order_direction = Functions::sanitizeFilterString($this->params()->fromQuery('order_direction'));
119 efrain 703
 
246 efrain 704
            if(!in_array($order_field,['name', 'added_on','last_access_on'] )) {
245 efrain 705
                $order_field = 'name';
706
            }
119 efrain 707
 
245 efrain 708
            if(!in_array( $order_direction,['asc', 'desc'])) {
709
                $order_field = 'asc';
710
            }
711
 
283 www 712
            $userProgressMapper = MicrolearningUserProgressMapper::getInstance($this->adapter);
713
            $capsuleMapper = MicrolearningCapsuleMapper::getInstance($this->adapter);
558 stevensc 714
            $topicCapsuleMapper = MicrolearningTopicCapsuleMapper::getInstance($this->adapter);
715
            $topicMapper = MicrolearningTopicMapper::getInstance($this->adapter);
283 www 716
            $capsuleCommentMapper = MicrolearningCapsuleCommentMapper::getInstance($this->adapter);
119 efrain 717
 
718
            $accessGranted = $this->getAccessGranted();
719
 
558 stevensc 720
            $capsulesData = [];
119 efrain 721
 
333 www 722
            $storage = Storage::getInstance($this->config, $this->adapter);
283 www 723
            $path = $storage->getPathMicrolearningCapsule();
724
 
119 efrain 725
            foreach($accessGranted->capsules as $capsule_id)
726
            {
558 stevensc 727
                // 1. Verificar progreso
119 efrain 728
                $userProgress = $userProgressMapper->fetchOneByUseridAndCapsuleId($currentUser->id, $capsule_id);
729
                if(!$userProgress) {
730
                    continue;
731
                }
732
 
733
                if(!$userProgress->completed) {
734
                    continue;
735
                }
736
 
558 stevensc 737
                // 2. Obtener detalles de la cápsula
119 efrain 738
                $capsule = $capsuleMapper->fetchOne($capsule_id);
558 stevensc 739
                if(!$capsule) {
740
                    continue;
741
                }
119 efrain 742
 
558 stevensc 743
                // 3. Filtrar por nombre
119 efrain 744
                if($name) {
745
                    if(empty($name) || stripos($capsule->name, $name) === false) {
746
                        continue;
747
                    }
748
                }
749
 
558 stevensc 750
                // 4. Obtener Tópico asociado válido
751
                $topic = null;
752
                $topic_uuid_for_links = null;
753
                $relation = $topicCapsuleMapper->fetchOneByCapsuleId($capsule->id);
754
                if ($relation && in_array($relation->topic_id, $accessGranted->topics)) {
755
                    $topic = $topicMapper->fetchOne($relation->topic_id);
756
                    if ($topic) {
757
                        $topic_uuid_for_links = $topic->uuid;
758
                    }
759
                }
760
 
761
                // 5. Obtener datos de comentarios
302 www 762
                $dataCountAndRatingAverage = $capsuleCommentMapper->fetchCountAndRatingAverage($capsule->company_id, $capsule->id);
119 efrain 763
 
558 stevensc 764
                // 6. Construir enlace slides
765
                $link_slides = $topic_uuid_for_links ? $this->url()->fromRoute('microlearning/slides', ['topic_id' => $topic_uuid_for_links,  'capsule_id' => $capsule->uuid], ['force_canonical' => true]) : '';
119 efrain 766
 
558 stevensc 767
                // 7. Añadir al array de resultados
768
                array_push($capsulesData, [
119 efrain 769
                    'uuid'              => $capsule->uuid,
770
                    'name'              => $capsule->name ? $capsule->name : '',
771
                    'description'       => $capsule->description ? $capsule->description : '',
283 www 772
                    'image'             => $capsule->image ? $storage->getGenericImage($path, $capsule->uuid, $capsule->image)  : '',
119 efrain 773
                    'position'          => $capsule->order,
774
                    'link_comments'     => $this->url()->fromRoute('microlearning/capsules-comments', ['capsule_id' => $capsule->uuid], ['force_canonical' => true]),
775
                    'link_comment_add'  => $this->url()->fromRoute('microlearning/capsules-comments/add', ['capsule_id' => $capsule->uuid],['force_canonical' => true]),
558 stevensc 776
                    'link_slides'       => $link_slides,
119 efrain 777
                    'total_comments'    => strval($dataCountAndRatingAverage['total_comments']),
778
                    'total_rating'      => strval($dataCountAndRatingAverage['total_rating']),
145 efrain 779
                    'progress'          => $userProgress->progress,
162 efrain 780
                    'link_get'          => $this->url()->fromRoute('microlearning/get-capsule', ['id' => $capsule->uuid], ['force_canonical' => true]),
119 efrain 781
                    'added_on'          => $capsule->added_on,
246 efrain 782
                    'last_access_on'    => $userProgress->updated_on,
119 efrain 783
                    'updated_on'        => $capsule->updated_on,
784
                ]);
785
            }
786
 
558 stevensc 787
            // 8. Ordenar (lógica de ordenación permanece igual, usando $capsulesData)
245 efrain 788
            if($order_field == 'name') {
789
                if($order_direction == 'asc') {
558 stevensc 790
                    usort($capsulesData, function($a, $b) {
245 efrain 791
                        return strcasecmp($a['name'], $b['name']);
792
                    });
793
                } else {
558 stevensc 794
                    usort($capsulesData, function($a, $b) {
245 efrain 795
                        $result = strcasecmp($a['name'], $b['name']);
558 stevensc 796
                        if($result < 0) { return 1; } else if($result > 0) { return -1; } else { return 0; }
245 efrain 797
                    });
119 efrain 798
                }
245 efrain 799
            }
800
 
801
            if($order_field == 'added_on') {
802
                if($order_direction == 'asc') {
558 stevensc 803
                    usort($capsulesData, function($a, $b) {
245 efrain 804
                        return strcasecmp($a['added_on'], $b['added_on']);
805
                    });
806
                } else {
558 stevensc 807
                    usort($capsulesData, function($a, $b) {
245 efrain 808
                        $result = strcasecmp($a['added_on'], $b['added_on']);
558 stevensc 809
                        if($result < 0) { return 1; } else if($result > 0) { return -1; } else { return 0; }
245 efrain 810
                    });
811
                }
812
            }
246 efrain 813
 
814
            if($order_field == 'last_access_on') {
815
                if($order_direction == 'asc') {
558 stevensc 816
                    usort($capsulesData, function($a, $b) {
246 efrain 817
                        return strcasecmp($a['last_access_on'], $b['last_access_on']);
818
                    });
819
                } else {
558 stevensc 820
                    usort($capsulesData, function($a, $b) {
246 efrain 821
                        $result = strcasecmp($a['last_access_on'], $b['last_access_on']);
558 stevensc 822
                        if($result < 0) { return 1; } else if($result > 0) { return -1; } else { return 0; }
246 efrain 823
                    });
824
                }
825
            }
826
 
827
 
828
 
829
 
119 efrain 830
 
831
            return new JsonModel([
832
                'success' => true,
558 stevensc 833
                'data' => $capsulesData
119 efrain 834
            ]);
835
 
836
        }
837
 
838
        return new JsonModel([
839
            'success' => false,
840
            'data' => 'ERROR_METHOD_NOT_ALLOWED'
841
        ]);
842
    }
843
 
844
    public function capsulesInProgressAction()
845
    {
846
        $request = $this->getRequest();
847
        if($request->isGet()) {
848
            $currentUserPlugin = $this->plugin('currentUserPlugin');
849
            $currentUser = $currentUserPlugin->getUser();
850
 
851
            $name = Functions::sanitizeFilterString($this->params()->fromQuery('name'));
245 efrain 852
            $order_field = Functions::sanitizeFilterString($this->params()->fromQuery('order_field'));
853
            $order_direction = Functions::sanitizeFilterString($this->params()->fromQuery('order_direction'));
119 efrain 854
 
246 efrain 855
            if(!in_array($order_field,['name', 'added_on', 'last_access_on'] )) {
245 efrain 856
                $order_field = 'name';
857
            }
119 efrain 858
 
245 efrain 859
            if(!in_array( $order_direction,['asc', 'desc'])) {
558 stevensc 860
                $order_direction = 'asc';
245 efrain 861
            }
862
 
283 www 863
            $userProgressMapper = MicrolearningUserProgressMapper::getInstance($this->adapter);
864
            $capsuleMapper = MicrolearningCapsuleMapper::getInstance($this->adapter);
558 stevensc 865
            $topicCapsuleMapper = MicrolearningTopicCapsuleMapper::getInstance($this->adapter);
866
            $topicMapper = MicrolearningTopicMapper::getInstance($this->adapter);
283 www 867
            $capsuleCommentMapper = MicrolearningCapsuleCommentMapper::getInstance($this->adapter);
119 efrain 868
 
869
            $accessGranted = $this->getAccessGranted();
870
 
558 stevensc 871
            $capsulesData = [];
119 efrain 872
 
333 www 873
            $storage = Storage::getInstance($this->config, $this->adapter);
283 www 874
            $path = $storage->getPathMicrolearningCapsule();
875
 
119 efrain 876
            foreach($accessGranted->capsules as $capsule_id)
877
            {
558 stevensc 878
                // 1. Verificar progreso
119 efrain 879
                $userProgress = $userProgressMapper->fetchOneByUseridAndCapsuleId($currentUser->id, $capsule_id);
558 stevensc 880
                if(!$userProgress || $userProgress->completed) { // Si no hay progreso o ya está completada
119 efrain 881
                    continue;
882
                }
558 stevensc 883
 
884
                // 2. Obtener detalles de la cápsula
885
                $capsule = $capsuleMapper->fetchOne($capsule_id);
886
                if(!$capsule) {
119 efrain 887
                    continue;
888
                }
889
 
558 stevensc 890
                // 3. Filtrar por nombre
119 efrain 891
                if($name) {
892
                    if(empty($name) || stripos($capsule->name, $name) === false) {
893
                        continue;
894
                    }
895
                }
896
 
558 stevensc 897
                // 4. Obtener Tópico asociado válido
898
                $topic = null;
899
                $topic_uuid_for_links = null;
900
                $relation = $topicCapsuleMapper->fetchOneByCapsuleId($capsule->id);
901
                if ($relation && in_array($relation->topic_id, $accessGranted->topics)) {
902
                    $topic = $topicMapper->fetchOne($relation->topic_id);
903
                    if ($topic) {
904
                        $topic_uuid_for_links = $topic->uuid;
905
                    }
906
                }
119 efrain 907
 
558 stevensc 908
                // 5. Obtener datos de comentarios
302 www 909
                $dataCountAndRatingAverage = $capsuleCommentMapper->fetchCountAndRatingAverage($capsule->company_id,  $capsule->id);
119 efrain 910
 
558 stevensc 911
                // 6. Construir enlace slides
912
                $link_slides = $topic_uuid_for_links ? $this->url()->fromRoute('microlearning/slides', ['topic_id' => $topic_uuid_for_links,  'capsule_id' => $capsule->uuid], ['force_canonical' => true]) : '';
119 efrain 913
 
558 stevensc 914
                // 7. Añadir al array de resultados
915
                array_push($capsulesData, [
119 efrain 916
                    'uuid'              => $capsule->uuid,
917
                    'name'              => $capsule->name ? $capsule->name : '',
918
                    'description'       => $capsule->description ? $capsule->description : '',
283 www 919
                    'image'             => $capsule->image ? $storage->getGenericImage($path, $capsule->uuid, $capsule->image)  : '',
119 efrain 920
                    'position'          => $capsule->order,
921
                    'link_comments'     => $this->url()->fromRoute('microlearning/capsules-comments', ['capsule_id' => $capsule->uuid], ['force_canonical' => true]),
922
                    'link_comment_add'  => $this->url()->fromRoute('microlearning/capsules-comments/add', ['capsule_id' => $capsule->uuid],['force_canonical' => true]),
558 stevensc 923
                    'link_slides'       => $link_slides,
119 efrain 924
                    'total_comments'    => strval($dataCountAndRatingAverage['total_comments']),
925
                    'total_rating'      => strval($dataCountAndRatingAverage['total_rating']),
558 stevensc 926
                    'progress'          => $userProgress->progress, // Progreso real
162 efrain 927
                    'link_get'          => $this->url()->fromRoute('microlearning/get-capsule', ['id' => $capsule->uuid], ['force_canonical' => true]),
558 stevensc 928
                    'last_access_on'    => $userProgress->updated_on, // Fecha del progreso
929
                    'added_on'          => $capsule->added_on, // Fecha de la cápsula
930
                    'updated_on'        => $capsule->updated_on, // Fecha de la cápsula
119 efrain 931
                ]);
932
            }
933
 
558 stevensc 934
            // 8. Ordenar (lógica de ordenación permanece igual, usando $capsulesData)
245 efrain 935
            if($order_field == 'name') {
936
                if($order_direction == 'asc') {
558 stevensc 937
                    usort($capsulesData, function($a, $b) {
245 efrain 938
                        return strcasecmp($a['name'], $b['name']);
939
                    });
940
                } else {
558 stevensc 941
                    usort($capsulesData, function($a, $b) {
245 efrain 942
                        $result = strcasecmp($a['name'], $b['name']);
558 stevensc 943
                        if($result < 0) { return 1; } else if($result > 0) { return -1; } else { return 0; }
245 efrain 944
                    });
119 efrain 945
                }
245 efrain 946
            }
947
 
948
            if($order_field == 'added_on') {
949
                if($order_direction == 'asc') {
558 stevensc 950
                    usort($capsulesData, function($a, $b) {
245 efrain 951
                        return strcasecmp($a['added_on'], $b['added_on']);
952
                    });
953
                } else {
558 stevensc 954
                    usort($capsulesData, function($a, $b) {
245 efrain 955
                        $result = strcasecmp($a['added_on'], $b['added_on']);
558 stevensc 956
                        if($result < 0) { return 1; } else if($result > 0) { return -1; } else { return 0; }
245 efrain 957
                    });
958
                }
959
            }
246 efrain 960
 
961
            if($order_field == 'last_access_on') {
962
                if($order_direction == 'asc') {
558 stevensc 963
                    usort($capsulesData, function($a, $b) {
246 efrain 964
                        return strcasecmp($a['last_access_on'], $b['last_access_on']);
965
                    });
966
                } else {
558 stevensc 967
                    usort($capsulesData, function($a, $b) {
246 efrain 968
                        $result = strcasecmp($a['last_access_on'], $b['last_access_on']);
558 stevensc 969
                        if($result < 0) { return 1; } else if($result > 0) { return -1; } else { return 0; }
246 efrain 970
                    });
971
                }
972
            }
245 efrain 973
 
246 efrain 974
 
119 efrain 975
            return new JsonModel([
976
                'success' => true,
558 stevensc 977
                'data' => $capsulesData
119 efrain 978
            ]);
979
        }
980
 
981
        return new JsonModel([
982
            'success' => false,
983
            'data' => 'ERROR_METHOD_NOT_ALLOWED'
984
        ]);
985
    }
986
 
987
 
988
    public function timelineAction()
989
    {
990
 
991
        $request = $this->getRequest();
992
        if($request->isGet()) {
993
            $currentUserPlugin = $this->plugin('currentUserPlugin');
994
            $currentUser = $currentUserPlugin->getUser();
995
 
996
 
997
            $page = intval($this->params()->fromQuery('page'), 10);
998
 
999
            $activities = [
283 www 1000
                MicrolearningUserLog::ACTIVITY_SIGNIN            => 'LABEL_MICROLEARNING_ACTIVITY_SIGNIN',
1001
                MicrolearningUserLog::ACTIVITY_SIGNOUT           => 'LABEL_MICROLEARNING_ACTIVITY_SIGNOUT',
1002
                MicrolearningUserLog::ACTIVITY_START_TOPIC       => 'LABEL_MICROLEARNING_ACTIVITY_START_TOPIC',
1003
                MicrolearningUserLog::ACTIVITY_START_CAPSULE     => 'LABEL_MICROLEARNING_ACTIVITY_START_CAPSULE',
1004
                MicrolearningUserLog::ACTIVITY_VIEW_SLIDE        => 'LABEL_MICROLEARNING_ACTIVITY_VIEW_SLIDE',
1005
                MicrolearningUserLog::ACTIVITY_TAKE_A_TEST       => 'LABEL_MICROLEARNING_ACTIVITY_TAKE_A_TEST',
1006
                MicrolearningUserLog::ACTIVITY_RETAKE_A_TEST     => 'LABEL_MICROLEARNING_ACTIVITY_RETAKE_A_TEST',
1007
                MicrolearningUserLog::ACTIVITY_APPROVED_TEST     => 'LABEL_MICROLEARNING_ACTIVITY_APPROVED_TEST',
1008
                MicrolearningUserLog::ACTIVITY_COMPLETED_CAPSULE => 'LABEL_MICROLEARNING_ACTIVITY_COMPLETED_CAPSULE',
1009
                MicrolearningUserLog::ACTIVITY_COMPLETED_TOPIC   => 'LABEL_MICROLEARNING_ACTIVITY_COMPLETED_TOPIC',
119 efrain 1010
            ];
1011
 
1012
 
1013
 
283 www 1014
            $microlearningUserLogMapper = MicrolearningUserLogMapper::getInstance($this->adapter);
1015
            $paginator = $microlearningUserLogMapper->getAllMessagesPaginatorByUserId($currentUser->id, $page);
119 efrain 1016
 
1017
            $items = [];
1018
            foreach($paginator as $record)
1019
            {
1020
                $dt = \DateTime::createFromFormat('Y-m-d H:i:s', $record->added_on);
1021
 
1022
                array_push($items, [
1023
                    'activity' => $activities[$record->activity],
1024
                    'added_on' => $dt->format('d/m/Y H:i a')
1025
                ]);
1026
            }
1027
 
1028
 
1029
            return new JsonModel([
1030
                'success' => true,
1031
                'data' => [
1032
                    'total' => [
1033
                        'count' => $paginator->getTotalItemCount(),
1034
                        'pages' => $paginator->getPages()->pageCount,
1035
                    ],
1036
                    'current' => [
1037
                        'items'    => $items,
1038
                        'page'     => $paginator->getCurrentPageNumber(),
1039
                        'count'    => $paginator->getCurrentItemCount(),
1040
                    ]
1041
                ]
1042
            ]);
1043
 
1044
 
1045
        } else {
1046
            return new JsonModel([
1047
                'success' => false,
1048
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
1049
            ]);
1050
        }
1051
    }
1052
 
1053
    /**
1054
     * Valores para la generación de los gráficos de progreso
1055
     * Para las repuesta afirmativa
1056
     * [
1057
     *  'success' => true,
1058
     *      'data' => [
1059
     *          'topicTotal' => cantidad total de tópicos,
1060
     *          'topicStarted' => cantidad de tópicos iniciados,
1061
     *          'topicIncompleted' => cantidad de tópicos incompletos,
1062
     *          'topicCompleted' => cantidad de tópicos completos,
1063
     *          'percentCompleted' => % de diapositivas completados ,
1064
     *          'percentIncompleted' => % de diapositivas incompletos ,
1065
     *          'percentWithoutReturning' => % de cápsulas sin retorno después de completada,
1066
     *          'percentWithReturning' => % de cápsulas con retorno después de completada,
558 stevensc 1067
     *      ],
119 efrain 1068
     * ]
1069
     *
1070
     *
1071
     *  En caso contrario
1072
     *  [
1073
     *      'success' => false,
1074
     *      'data' => mensaje de error
1075
     *  ]
1076
     *
1077
     *
1078
     * @return \Laminas\View\Model\JsonModel
1079
     */
1080
    public function progressAction()
1081
    {
1082
 
1083
        $request = $this->getRequest();
1084
        if($request->isGet()) {
1085
            $currentUserPlugin = $this->plugin('currentUserPlugin');
1086
            $currentUser = $currentUserPlugin->getUser();
1087
 
1088
 
1089
            $accessGrantedIds = $this->getAccessGranted();
1090
            $id = $this->params()->fromRoute('id');
1091
 
1092
            $companyMapper = CompanyMapper::getInstance($this->adapter);
1093
            $company = $companyMapper->fetchOneByUuid($id);
1094
 
1095
            if(!$company) {
1096
                $response = [
1097
                    'success' => false,
1098
                    'data' => 'ERROR_COMPANY_NOT_FOUND',
1099
                ];
1100
 
1101
 
1102
                return new JsonModel($response);
1103
            }
1104
 
1105
            if(!in_array($company->id, $accessGrantedIds->companies)) {
1106
                $response = [
1107
                    'success' => false,
1108
                    'data' => 'ERROR_YOU_DO_NOT_HAVE_ACCESS_TO_THIS_COMPANY',
1109
                ];
1110
 
1111
 
1112
                return new JsonModel($response);
1113
            }
1114
 
1115
            $capsuleTotal              = 0;
1116
            $capsuleCompleted          = 0;
1117
            $capsuleWithReturning      = 0;
1118
            $capsuleWithoutReturning   = 0;
1119
            $capsuleStarted            = 0;
1120
            $capsuleToStart            = 0;
1121
            $percentCompleted          = 0;
1122
            $percentIncompleted        = 100;
1123
 
283 www 1124
            $topicMapper = MicrolearningTopicMapper::getInstance($this->adapter);
119 efrain 1125
            $topics = $topicMapper->fetchAllActiveByCompanyIdAndIds($company->id, $accessGrantedIds->topics);
1126
 
302 www 1127
            //$capsuleMapper = MicrolearningCapsuleMapper::getInstance($this->adapter);
283 www 1128
            $progressMapper = MicrolearningUserProgressMapper::getInstance($this->adapter);
119 efrain 1129
 
302 www 1130
            $topicCapsuleMapper = MicrolearningTopicCapsuleMapper::getInstance($this->adapter);
119 efrain 1131
 
302 www 1132
            //$capsuleUserMapper = MicrolearningCapsuleUserMapper::getInstance($this->adapter);
1133
 
1134
 
119 efrain 1135
            foreach($topics as $topic)
1136
            {
302 www 1137
                $resultCount = $topicCapsuleMapper->fetchCountByCompanyIdAndTopicId($company->id, $topic->id);
119 efrain 1138
                $capsuleTotal =  $capsuleTotal + $resultCount;
1139
 
1140
                $resultCount = $progressMapper->fetchCountCapsulesCompletedByIdAndTopicId($currentUser->id, $topic->id);
1141
                $capsuleCompleted = $capsuleCompleted + $resultCount;
1142
 
1143
                $resultCount = $progressMapper->fetchCountCapsulesCompletedWithReturningByIdAndTopicId($currentUser->id, $topic->id);
1144
                $capsuleWithReturning = $capsuleWithReturning + $resultCount;
1145
 
1146
                $resultCount = $progressMapper->fetchCountCapsulesCompletedWithoutReturningByIdAndTopicId($currentUser->id, $topic->id);
1147
                $capsuleWithoutReturning = $capsuleWithoutReturning + $resultCount;
1148
 
1149
                $resultCount = $progressMapper->fetchCountCapsulesCompletedByIdAndTopicId($currentUser->id, $topic->id);
1150
                $capsuleStarted = $capsuleStarted + $resultCount;
1151
            }
1152
 
1153
            $capsuleToStart = $capsuleTotal -  $capsuleStarted;
1154
 
1155
 
1156
            if($capsuleTotal > 0) {
1157
                $percentCompleted = ($capsuleCompleted * 100) /  $capsuleTotal;
1158
                $percentIncompleted = 100 - $percentCompleted;
1159
            }
1160
 
1161
 
1162
 
1163
            return new JsonModel([
1164
                'success' => true,
1165
                'data' => [
1166
                    'capsuleTotal' => $capsuleTotal,
1167
                    'capsuleCompleted' => $capsuleCompleted,
1168
                    'capsuleStarted' => $capsuleStarted,
1169
                    'capsuleToStart' => $capsuleToStart,
1170
                    'percentCompleted' => number_format($percentCompleted, 2, '.', ','),
1171
                    'percentIncompleted' => number_format($percentIncompleted, 2, '.', ','),
1172
                    'capsuleWithReturning' => $capsuleWithReturning,
1173
                    'capsuleWithoutReturning' => $capsuleWithoutReturning,
1174
                ],
1175
            ]);
1176
 
1177
 
1178
        } else {
1179
            return new JsonModel([
1180
                'success' => false,
1181
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
1182
            ]);
1183
        }
1184
    }
1185
 
1186
 
1187
    public function topicsAction()
1188
    {
1189
        $request = $this->getRequest();
1190
        if($request->isGet()) {
1191
            $currentUserPlugin = $this->plugin('currentUserPlugin');
1192
            $currentUser = $currentUserPlugin->getUser();
1193
 
1194
 
1195
            $data = [];
1196
            $accessGrantedIds = $this->getAccessGranted();
1197
 
283 www 1198
            $userProgressMapper = MicrolearningUserProgressMapper::getInstance($this->adapter);
1199
            $topicMapper = MicrolearningTopicMapper::getInstance($this->adapter);
119 efrain 1200
 
333 www 1201
            $storage = Storage::getInstance($this->config, $this->adapter);
283 www 1202
            $path = $storage->getPathMicrolearningTopic();
119 efrain 1203
 
1204
            foreach($accessGrantedIds->topics as $id)
1205
            {
1206
                $topic = $topicMapper->fetchOne($id);
1207
                if(!$topic) {
1208
                    continue;
1209
                }
1210
 
1211
                $userProgress = $userProgressMapper->fetchOneByUserIdAndTopicId($currentUser->id, $id);
1212
                if($userProgress) {
1213
                    $progress = $userProgress->progress;
1214
                    $completed = $userProgress->completed;
1215
                } else {
1216
                    $progress = 0;
1217
                    $completed = 0;
1218
                }
1219
 
1220
 
1221
 
1222
                array_push($data, [
164 efrain 1223
                    'uuid'          => $topic->uuid,
119 efrain 1224
                    'name'          => $topic->name ? $topic->name : '',
1225
                    'description'   => $topic->description ? $topic->description : '',
283 www 1226
                    'image'         => $topic->image ? $storage->getGenericImage($path, $topic->uuid, $topic->image) : '',
119 efrain 1227
                    'progress'      => $progress,
1228
                    'completed'     => $completed,
1229
                    'order'         => $topic->order,
1230
                    'added_on'      => $topic->added_on,
564 stevensc 1231
                    'updated_on'    => $topic->updated_on
119 efrain 1232
                ]);
1233
            }
1234
 
1235
            usort($data, function($a, $b) {
1236
 
1237
                $result =  $a['order'] <=> $b['order'];
1238
                if(0 == $result) {
1239
                    $result = strcasecmp($a['added_on'], $b['added_on']);
1240
                    if(0 == $result) {
1241
                        $result = strcasecmp($a['name'], $b['name']);
1242
                    }
1243
                }
1244
 
1245
                if($result < 0) {
1246
                    return 1;
1247
                } else if($result > 0) {
1248
                    return -1;
1249
                } else  {
1250
                    return  0;
1251
                }
1252
            });
1253
 
1254
 
1255
 
1256
                return new JsonModel([
1257
                    'success' => true,
1258
                    'data' => $data
1259
                ]);
1260
 
1261
        } else {
1262
            return new JsonModel([
1263
                'success' => false,
1264
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
1265
            ]);
1266
        }
1267
    }
1268
 
161 efrain 1269
    public function getTopicAction()
1270
    {
563 stevensc 1271
        // Handle GET request
161 efrain 1272
        $request = $this->getRequest();
1273
        if($request->isGet()) {
563 stevensc 1274
            // Get current user
161 efrain 1275
            $currentUserPlugin = $this->plugin('currentUserPlugin');
1276
            $currentUser = $currentUserPlugin->getUser();
563 stevensc 1277
 
1278
            // Get topic ID from route
161 efrain 1279
            $id = $this->params()->fromRoute('id');
283 www 1280
            $topicMapper = MicrolearningTopicMapper::getInstance($this->adapter);
161 efrain 1281
            $topic = $topicMapper->fetchOneByUuid($id);
563 stevensc 1282
 
1283
            // Return error if topic not found
161 efrain 1284
            if(!$topic) {
1285
                return new JsonModel([
1286
                    'success' => false,
1287
                    'data' => 'ERROR_TOPIC_NOT_FOUND'
1288
                ]);
1289
            }
563 stevensc 1290
 
1291
            // Check if current user has access to the topic
161 efrain 1292
            $accessGrantedIds = $this->getAccessGranted();
1293
            if(!in_array($topic->id, $accessGrantedIds->topics)) {
1294
                return new JsonModel([
1295
                    'success' => false,
1296
                    'data' => 'ERROR_YOU_DO_NOT_HAVE_ACCESS_TO_THIS_TOPIC'
1297
                ]);
1298
            }
563 stevensc 1299
 
1300
            // Get user progress for this topic
283 www 1301
            $userProgressMapper = MicrolearningUserProgressMapper::getInstance($this->adapter);
563 stevensc 1302
            $userProgress = $userProgressMapper->fetchOneByUserIdAndTopicId($currentUser->id, $topic->id);
161 efrain 1303
 
580 stevensc 1304
            $progress = $userProgress->progress ?? 0;
1305
            $completed = $userProgress->completed ?? 0;
563 stevensc 1306
 
1307
            // Initialize storage service to get image paths
333 www 1308
            $storage = Storage::getInstance($this->config, $this->adapter);
563 stevensc 1309
            $pathTopic = $storage->getPathMicrolearningTopic();
1310
 
1311
            // Fetch associated capsules using the private helper method
1312
            $capsulesData = $this->_getCapsulesByTopic($topic, $storage);
1313
 
1314
            // Prepare data for JSON response
161 efrain 1315
            $data = [
165 efrain 1316
                'uuid'          => $topic->uuid,
161 efrain 1317
                'name'          => $topic->name ? $topic->name : '',
1318
                'description'   => $topic->description ? $topic->description : '',
563 stevensc 1319
                'image'         => $topic->image ? $storage->getGenericImage($pathTopic, $topic->uuid, $topic->image) : '',
161 efrain 1320
                'progress'      => $progress,
1321
                'completed'     => $completed,
1322
                'order'         => $topic->order,
1323
                'added_on'      => $topic->added_on,
1324
                'updated_on'    => $topic->updated_on,
563 stevensc 1325
                'total_capsules' => count($capsulesData),
1326
                'capsules'      => $capsulesData,
161 efrain 1327
            ];
563 stevensc 1328
 
161 efrain 1329
            return new JsonModel([
1330
                'success' => true,
1331
                'data' => $data
1332
            ]);
563 stevensc 1333
 
161 efrain 1334
        } else {
563 stevensc 1335
            // Return error if not a GET request
161 efrain 1336
            return new JsonModel([
1337
                'success' => false,
1338
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
1339
            ]);
1340
        }
1341
    }
563 stevensc 1342
 
1343
    /**
580 stevensc 1344
     * @param MicrolearningTopic $topic The topic object.
1345
     * @param Storage $storage The storage object.
1346
     * @return array The capsules data.
563 stevensc 1347
     */
1348
    private function _getCapsulesByTopic($topic, $storage)
1349
    {
578 stevensc 1350
        $data = [];
584 stevensc 1351
        $accessGrantedIds = $this->getAccessGranted();
563 stevensc 1352
 
578 stevensc 1353
        if (!$topic) {
1354
            return $data;
1355
        }
1356
 
584 stevensc 1357
        if (!in_array($topic->id, $accessGrantedIds->topics)) {
578 stevensc 1358
            return $data;
584 stevensc 1359
        }
578 stevensc 1360
 
1361
        $currentUserPlugin = $this->plugin('currentUserPlugin');
1362
        $currentUser = $currentUserPlugin->getUser();
1363
 
1364
        $topicCapsuleMapper = MicrolearningTopicCapsuleMapper::getInstance($this->adapter);
574 stevensc 1365
        $topicCapsuleRelations = $topicCapsuleMapper->fetchAllActiveByTopicId($topic->id);
1366
 
581 stevensc 1367
        $userProgressMapper = MicrolearningUserProgressMapper::getInstance($this->adapter);
1368
        $capsuleCommentMapper = MicrolearningCapsuleCommentMapper::getInstance($this->adapter);
578 stevensc 1369
 
581 stevensc 1370
        $path = $storage->getPathMicrolearningCapsule();
1371
 
578 stevensc 1372
        foreach ($topicCapsuleRelations as $relation) {
584 stevensc 1373
            if(!in_array($relation->capsule_id, $accessGrantedIds->capsules)) {
1374
                continue;
1375
            }
578 stevensc 1376
 
581 stevensc 1377
            $capsuleMapper = MicrolearningCapsuleMapper::getInstance($this->adapter);
1378
            $capsule = $capsuleMapper->fetchOne($relation->capsule_id);
563 stevensc 1379
 
581 stevensc 1380
            if(!$capsule) {
1381
                continue;
1382
            }
1383
 
578 stevensc 1384
            $userProgress = $userProgressMapper->fetchOneByUseridAndCapsuleId($currentUser->id, $capsule->id);
1385
            $progress = $userProgress->progress ?? 0;
1386
            $completed = $userProgress->completed ?? 0;
1387
            $dataCountAndRatingAverage = $capsuleCommentMapper->fetchCountAndRatingAverage($capsule->company_id, $capsule->id);
1388
            $image = $capsule->image ? $storage->getGenericImage($path, $capsule->uuid, $capsule->image) : '';
1389
            $total_comments = strval($dataCountAndRatingAverage['total_comments']);
1390
            $total_rating = strval($dataCountAndRatingAverage['total_rating']);
1391
 
581 stevensc 1392
            array_push($data, [
578 stevensc 1393
                'uuid'              => $capsule->uuid,
1394
                'name'              => $capsule->name ? $capsule->name : '',
1395
                'description'       => $capsule->description ? $capsule->description : '',
1396
                'image'             => $image,
1397
                'total_comments'    => $total_comments,
1398
                'total_rating'      => $total_rating,
1399
                'progress'          => $progress,
1400
                'completed'         => $completed,
1401
                'order'             => $capsule->order,
1402
                'added_on'          => $capsule->added_on,
1403
                'updated_on'        => $capsule->updated_on,
581 stevensc 1404
            ]);
563 stevensc 1405
        }
578 stevensc 1406
 
581 stevensc 1407
        return $data;
563 stevensc 1408
    }
119 efrain 1409
 
1410
    public function capsulesAction()
1411
    {
1412
        $request = $this->getRequest();
1413
        if($request->isGet()) {
580 stevensc 1414
            $currentUserPlugin = $this->plugin('currentUserPlugin');
1415
            $currentUser = $currentUserPlugin->getUser();
584 stevensc 1416
 
1417
            $topic_id_param = $this->params()->fromRoute('topic_id');
283 www 1418
            $topicMapper = MicrolearningTopicMapper::getInstance($this->adapter);
580 stevensc 1419
            $topic = $topicMapper->fetchOneByUuid($topic_id_param);
584 stevensc 1420
 
119 efrain 1421
            if(!$topic) {
1422
                return new JsonModel([
1423
                    'success' => false,
1424
                    'data' => 'ERROR_TOPIC_NOT_FOUND'
1425
                ]);
1426
            }
584 stevensc 1427
 
580 stevensc 1428
            $accessGrantedIds = $this->getAccessGranted();
584 stevensc 1429
 
119 efrain 1430
            if(!in_array($topic->id, $accessGrantedIds->topics)) {
1431
                return new JsonModel([
1432
                    'success' => false,
1433
                    'data' => 'ERROR_YOU_DO_NOT_HAVE_ACCESS_TO_THIS_TOPIC'
1434
                ]);
1435
            }
584 stevensc 1436
 
333 www 1437
            $storage = Storage::getInstance($this->config, $this->adapter);
584 stevensc 1438
            // Use the _getCapsulesByTopic method to fetch capsules
1439
            $data = $this->_getCapsulesByTopic($topic, $storage);
580 stevensc 1440
 
584 stevensc 1441
            // The _getCapsulesByTopic method already returns capsules with the required data structure.
1442
            // We just need to sort them.
1443
 
580 stevensc 1444
            usort($data, function($a, $b) {
584 stevensc 1445
 
580 stevensc 1446
                $result =  $a['order'] <=> $b['order'];
1447
                if(0 == $result) {
1448
                    $result = strcasecmp($a['added_on'], $b['added_on']);
1449
                    if(0 == $result) {
1450
                        $result = strcasecmp($a['name'], $b['name']);
1451
                    }
1452
                }
584 stevensc 1453
 
580 stevensc 1454
                if($result < 0) {
1455
                    return 1;
1456
                } else if($result > 0) {
1457
                    return -1;
1458
                } else  {
1459
                    return  0;
1460
                }
1461
            });
584 stevensc 1462
 
1463
            return new JsonModel([
1464
                'success' => true,
1465
                'data' => $data
1466
            ]);
1467
 
119 efrain 1468
        } else {
1469
            return new JsonModel([
1470
                'success' => false,
1471
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
1472
            ]);
1473
        }
1474
    }
1475
 
235 efrain 1476
    public function takeTestAction()
1477
    {
1478
        $request = $this->getRequest();
1479
        if($request->isPost()) {
1480
            $currentUserPlugin = $this->plugin('currentUserPlugin');
1481
            $currentUser = $currentUserPlugin->getUser();
1482
 
1483
            $slide_id = $this->params()->fromRoute('slide_id');
283 www 1484
            $slideMapper = MicrolearningSlideMapper::getInstance($this->adapter);
235 efrain 1485
            $slide = $slideMapper->fetchOneByUuid($slide_id);
1486
 
1487
            if(!$slide) {
1488
                return new JsonModel([
1489
                    'success' => false,
1490
                    'data' => 'ERROR_SLIDE_NOT_FOUND'
1491
                ]);
1492
            }
1493
 
283 www 1494
            if($slide->type != MicrolearningSlide::TYPE_QUIZ) {
235 efrain 1495
                return new JsonModel([
1496
                    'success' => false,
1497
                    'data' => 'ERROR_SLIDE_IS_NOT_QUIZ'
1498
                ]);
1499
            }
1500
 
1501
 
1502
 
283 www 1503
            $capsuleMapper = MicrolearningCapsuleMapper::getInstance($this->adapter);
235 efrain 1504
            $capsule = $capsuleMapper->fetchOne($slide->capsule_id);
1505
 
1506
            if(!$capsule) {
1507
                return new JsonModel([
1508
                    'success' => false,
1509
                    'data' => 'ERROR_CAPSULE_NOT_FOUND'
1510
                ]);
1511
            }
1512
 
1513
            $accessGrantedIds = $this->getAccessGranted();
1514
 
1515
            if(!in_array($capsule->id, $accessGrantedIds->capsules)) {
1516
                return new JsonModel([
1517
                    'success' => false,
1518
                    'data' => 'ERROR_YOU_DO_NOT_HAVE_ACCESS_TO_THIS_CAPSULE'
1519
                ]);
1520
            }
1521
 
283 www 1522
            $userLogMapper = MicrolearningUserLogMapper::getInstance($this->adapter);
235 efrain 1523
            $userLog = $userLogMapper->fetchOneTakeATestByUserIdAndSlideId($currentUser->id, $slide->id);
1524
 
1525
            if($userLog) {
283 www 1526
                $activity = MicrolearningUserLog::ACTIVITY_RETAKE_A_TEST;
235 efrain 1527
            } else {
283 www 1528
                $activity = MicrolearningUserLog::ACTIVITY_TAKE_A_TEST;
235 efrain 1529
            }
1530
 
1531
            $added_on = $userLogMapper->getDatebaseNow();
1532
 
283 www 1533
            $userLog = new MicrolearningUserLog();
235 efrain 1534
            $userLog->activity      = $activity;
1535
            $userLog->user_id       = $currentUser->id;
1536
            $userLog->company_id    = $slide->company_id;
1537
            $userLog->topic_id      = $slide->topic_id;
1538
            $userLog->capsule_id    = $slide->capsule_id;
1539
            $userLog->slide_id      = $slide->id;
1540
            $userLog->added_on      = $added_on;
1541
 
1542
            if($userLogMapper->insert($userLog)) {
1543
                return new JsonModel([
1544
                    'success' => true,
1545
                ]);
1546
            } else {
1547
                return new JsonModel([
1548
                    'success' => false,
1549
                    'data' => $userLogMapper->getError()
1550
                ]);
1551
            }
1552
 
1553
 
1554
 
1555
 
1556
 
1557
 
1558
 
1559
        } else {
1560
            return new JsonModel([
1561
                'success' => false,
1562
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
1563
            ]);
1564
        }
1565
    }
1566
 
161 efrain 1567
    public function getCapsuleAction()
1568
    {
1569
        $request = $this->getRequest();
1570
        if($request->isGet()) {
1571
            $currentUserPlugin = $this->plugin('currentUserPlugin');
1572
            $currentUser = $currentUserPlugin->getUser();
1573
 
1574
 
1575
 
558 stevensc 1576
            $capsule_uuid = $this->params()->fromRoute('id');
283 www 1577
            $capsuleMapper = MicrolearningCapsuleMapper::getInstance($this->adapter);
558 stevensc 1578
            $capsule = $capsuleMapper->fetchOneByUuid($capsule_uuid);
161 efrain 1579
 
1580
            if(!$capsule) {
1581
                return new JsonModel([
1582
                    'success' => false,
1583
                    'data' => 'ERROR_CAPSULE_NOT_FOUND'
1584
                ]);
1585
            }
1586
 
1587
            $accessGrantedIds = $this->getAccessGranted();
1588
 
558 stevensc 1589
            // Verificar si el usuario tiene acceso a esta cápsula específica
161 efrain 1590
            if(!in_array($capsule->id, $accessGrantedIds->capsules)) {
1591
                return new JsonModel([
1592
                    'success' => false,
1593
                    'data' => 'ERROR_YOU_DO_NOT_HAVE_ACCESS_TO_THIS_CAPSULE'
1594
                ]);
1595
            }
1596
 
558 stevensc 1597
            // --- Obtener el Tópico asociado (si existe y es necesario) ---
1598
            $topic = null;
1599
            $topic_uuid_for_links = null; // UUID del tópico para construir enlaces
1600
            $topicCapsuleMapper = MicrolearningTopicCapsuleMapper::getInstance($this->adapter);
1601
            // Asumiendo que una cápsula puede estar asociada a múltiples tópicos (muchos-a-muchos),
1602
            // necesitamos decidir cuál tópico usar como contexto aquí. Usaremos el primero que encontremos.
1603
            // Si una cápsula SIEMPRE pertenece a UN SOLO tópico, la tabla de unión podría tener una restricción UNIQUE(capsule_id).
1604
            $relation = $topicCapsuleMapper->fetchOneByCapsuleId($capsule->id); // Necesitamos un método como este
1605
 
1606
            if ($relation && in_array($relation->topic_id, $accessGrantedIds->topics)) {
1607
                $topicMapper = MicrolearningTopicMapper::getInstance($this->adapter);
1608
                $topic = $topicMapper->fetchOne($relation->topic_id);
1609
                if ($topic) {
1610
                    $topic_uuid_for_links = $topic->uuid;
1611
                }
1612
            }
1613
            // Si no se encontró un tópico asociado o el usuario no tiene acceso a él,
1614
            // algunos enlaces podrían no generarse o la lógica necesitaría ajustarse.
1615
            // Por ahora, si no hay $topic_uuid_for_links, el link_slides será inválido.
1616
            // --------------------------------------------------------------
161 efrain 1617
 
1618
 
283 www 1619
            $userProgressMapper = MicrolearningUserProgressMapper::getInstance($this->adapter);
1620
            $capsuleCommentMapper = MicrolearningCapsuleCommentMapper::getInstance($this->adapter);
161 efrain 1621
 
1622
 
1623
 
1624
            $userProgress = $userProgressMapper->fetchOneByUseridAndCapsuleId($currentUser->id, $capsule->id);
1625
            if($userProgress) {
1626
                $progress = $userProgress->progress;
1627
                $completed = $userProgress->completed;
1628
            } else {
1629
                $progress = 0;
1630
                $completed = 0;
1631
            }
1632
 
302 www 1633
            $dataCountAndRatingAverage = $capsuleCommentMapper->fetchCountAndRatingAverage($capsule->company_id,  $capsule->id);
161 efrain 1634
 
244 efrain 1635
 
283 www 1636
            $slideMapper = MicrolearningSlideMapper::getInstance($this->adapter);
558 stevensc 1637
            // Para contar slides, necesitamos el contexto del tópico.
1638
            $totalSlides = 0;
1639
            if ($topic) { // Solo contar si tenemos un tópico asociado válido
1640
                $totalSlides = $slideMapper->fetchTotalCountByCompanyIdAndTopicIdAndCapsuleId($capsule->company_id, $topic->id, $capsule->id);
1641
            }
244 efrain 1642
 
1643
 
558 stevensc 1644
            $link_first_slide = '';
1645
            $type_first_slide = '';
1646
            if ($topic) { // Solo buscar primer slide si tenemos tópico
1647
                $slide = $slideMapper->fetchFirstByCompanyIdAndTopicIdAndCapsuleId($capsule->company_id, $topic->id, $capsule->id);
1648
                if($slide) {
1649
                    $link_first_slide = $this->url()->fromRoute('microlearning/get-slide', ['id' => $slide->uuid], ['force_canonical' => true]);
1650
                    $type_first_slide = $slide->type;
1651
                }
244 efrain 1652
            }
1653
 
333 www 1654
            $storage = Storage::getInstance($this->config, $this->adapter);
283 www 1655
            $path = $storage->getPathMicrolearningCapsule();
244 efrain 1656
 
1657
 
558 stevensc 1658
            // Construir enlaces usando $topic_uuid_for_links si está disponible
1659
            $link_slides = $topic_uuid_for_links ? $this->url()->fromRoute('microlearning/slides', ['topic_id' => $topic_uuid_for_links,  'capsule_id' => $capsule->uuid], ['force_canonical' => true]) : '';
244 efrain 1660
 
161 efrain 1661
            $data = [
164 efrain 1662
                    'uuid'              => $capsule->uuid,
161 efrain 1663
                    'name'              => $capsule->name ? $capsule->name : '',
1664
                    'description'       => $capsule->description ? $capsule->description : '',
283 www 1665
                    'image'             => $capsule->image ? $storage->getGenericImage($path, $capsule->uuid, $capsule->image)  : '',
161 efrain 1666
                    'link_comments'     => $this->url()->fromRoute('microlearning/capsules-comments', ['capsule_id' => $capsule->uuid], ['force_canonical' => true]),
1667
                    'link_comment_add'  => $this->url()->fromRoute('microlearning/capsules-comments/add', ['capsule_id' => $capsule->uuid],['force_canonical' => true]),
558 stevensc 1668
                    'link_slides'       => $link_slides, // Usar el enlace construido
161 efrain 1669
                    'total_comments'    => strval($dataCountAndRatingAverage['total_comments']),
1670
                    'total_rating'      => strval($dataCountAndRatingAverage['total_rating']),
1671
                    'progress'          => $progress,
1672
                    'completed'         => $completed,
245 efrain 1673
                    'total_slides'      => $totalSlides,
244 efrain 1674
                    'link_first_slide'  => $link_first_slide,
1675
                    'type_first_slide'  => $type_first_slide,
161 efrain 1676
                    'order'             => $capsule->order,
1677
                    'added_on'          => $capsule->added_on,
1678
                    'updated_on'        => $capsule->updated_on,
1679
            ];
1680
 
1681
 
1682
 
1683
            return new JsonModel([
1684
                'success' => true,
1685
                'data' => $data
1686
            ]);
1687
 
1688
        } else {
1689
            return new JsonModel([
1690
                'success' => false,
1691
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
1692
            ]);
1693
        }
1694
    }
1695
 
119 efrain 1696
    public function slidesAction()
1697
    {
1698
        $request = $this->getRequest();
1699
        if($request->isGet()) {
1700
            $currentUserPlugin = $this->plugin('currentUserPlugin');
1701
            $currentUser = $currentUserPlugin->getUser();
1702
 
1703
 
1704
 
1705
            $topic_id = $this->params()->fromRoute('topic_id');
283 www 1706
            $topicMapper = MicrolearningTopicMapper::getInstance($this->adapter);
119 efrain 1707
            $topic = $topicMapper->fetchOneByUuid($topic_id);
1708
 
1709
            if(!$topic) {
1710
                return new JsonModel([
1711
                    'success' => false,
1712
                    'data' => 'ERROR_TOPIC_NOT_FOUND'
1713
                ]);
1714
            }
1715
 
1716
            $accessGrantedIds = $this->getAccessGranted();
1717
 
1718
            if(!in_array($topic->id, $accessGrantedIds->topics)) {
1719
                return new JsonModel([
1720
                    'success' => false,
1721
                    'data' => 'ERROR_YOU_DO_NOT_HAVE_ACCESS_TO_THIS_TOPIC'
1722
                ]);
1723
            }
1724
 
1725
            $capsule_id = $this->params()->fromRoute('capsule_id');
283 www 1726
            $capsuleMapper = MicrolearningCapsuleMapper::getInstance($this->adapter);
119 efrain 1727
            $capsule = $capsuleMapper->fetchOneByUuid($capsule_id);
1728
 
1729
            if(!$capsule) {
1730
                return new JsonModel([
1731
                    'success' => false,
1732
                    'data' => 'ERROR_CAPSULE_NOT_FOUND'
1733
                ]);
1734
            }
1735
 
1736
 
1737
 
1738
            if(!in_array($capsule->id, $accessGrantedIds->capsules)) {
1739
                return new JsonModel([
1740
                    'success' => false,
1741
                    'data' => 'ERROR_YOU_DO_NOT_HAVE_ACCESS_TO_THIS_CAPSULE'
1742
                ]);
1743
            }
1744
 
1745
 
1746
 
1747
            $data = [];
1748
 
283 www 1749
            $quizMapper = MicrolearningQuizMapper::getInstance($this->adapter);
119 efrain 1750
 
283 www 1751
            $slideMapper = MicrolearningSlideMapper::getInstance($this->adapter);
1752
            $userProgressMapper = MicrolearningUserProgressMapper::getInstance($this->adapter);
119 efrain 1753
 
333 www 1754
            $storage = Storage::getInstance($this->config, $this->adapter);
283 www 1755
            $path = $storage->getPathMicrolearningSlide();
119 efrain 1756
 
1757
            $slides = $slideMapper->fetchAllByCompanyIdAndTopicIdAndCapsuleId($capsule->company_id, $capsule->topic_id, $capsule->id);
1758
            foreach($slides as $slide)
1759
            {
1760
 
1761
 
1762
                $userProgress = $userProgressMapper->fetchOneByUserIdAndSlideId($currentUser->id, $slide->id);
1763
                if($userProgress) {
224 efrain 1764
                    $completed =  $userProgress->completed ;
119 efrain 1765
                } else {
1766
                    $completed = 0;
1767
                }
1768
 
235 efrain 1769
 
230 efrain 1770
 
235 efrain 1771
                $link_take_a_test = '';
230 efrain 1772
                if($slide->quiz_id) {
235 efrain 1773
 
283 www 1774
                    $quizMapper = MicrolearningQuizMapper::getInstance($this->adapter);
230 efrain 1775
                    $quiz = $quizMapper->fetchOne($slide->quiz_id);
1776
                    if($quiz) {
1777
                        $quiz_uuid = $quiz->uuid;
235 efrain 1778
                        $quiz_data = $this->getQuiz($slide->quiz_id);
1779
                        $link_take_a_test = $this->url()->fromRoute('microlearning/take-a-test', ['slide_id' => $slide->uuid], ['force_canonical' => true]);
230 efrain 1780
                    }
235 efrain 1781
 
1782
                }
119 efrain 1783
 
1784
 
1785
                array_push($data, [
235 efrain 1786
                    'quiz'                  => $quiz_uuid,
1787
                    'quiz_data'             => $quiz_data,
1788
                    'uuid'                  => $slide->uuid,
1789
                    'name'                  => $slide->name ? $slide->name : '',
1790
                    'description'           => $slide->description ? $slide->description : '',
1791
                    'type'                  => $slide->type,
283 www 1792
                    'background'            => $slide->background ? $storage->getGenericImage($path, $slide->uuid, $slide->background) : '',
1793
                    'file'                  => $slide->file ? $storage->getGenericFile($path, $slide->uuid, $slide->file) : '',
235 efrain 1794
                    'order'                 => $slide->order,
1795
                    'completed'             => $completed,
1796
                    'link_get'              => $this->url()->fromRoute('microlearning/get-slide', ['id' => $slide->uuid], ['force_canonical' => true]),
1797
                    'link_sync'             => $this->url()->fromRoute('microlearning/sync', ['operation' => 'slide-view', 'topic_uuid' => $topic->uuid, 'capsule_uuid' => $capsule->uuid, 'slide_uuid' => $slide->uuid], ['force_canonical' => true]),
236 efrain 1798
                    'link_take_a_test'      => $link_take_a_test,
235 efrain 1799
                    'added_on'              => $slide->added_on,
1800
                    'updated_on'            => $slide->updated_on,
119 efrain 1801
                ]);
1802
 
1803
 
1804
 
1805
            }
1806
 
1807
            usort($data, function($a, $b) {
1808
 
1809
                $result =  $a['order'] <=> $b['order'];
1810
                if(0 == $result) {
1811
                    $result = strcasecmp($a['added_on'], $b['added_on']);
1812
                    if(0 == $result) {
1813
                        $result = strcasecmp($a['name'], $b['name']);
1814
                    }
1815
                }
1816
 
1817
                if($result < 0) {
1818
                    return 1;
1819
                } else if($result > 0) {
1820
                    return -1;
1821
                } else  {
1822
                    return  0;
1823
                }
1824
            });
1825
 
1826
 
1827
 
1828
                return new JsonModel([
1829
                    'success' => true,
1830
                    'data' => $data
1831
                ]);
1832
 
1833
        } else {
1834
            return new JsonModel([
1835
                'success' => false,
1836
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
1837
            ]);
1838
        }
1839
    }
1840
 
229 efrain 1841
    private function getQuiz($id)
1842
    {
1843
        $serviceDatetimeFormat = $this->config['leaderslinked.services.datetime'];
1844
 
1845
        $data = [];
1846
 
283 www 1847
        $quizMapper = MicrolearningQuizMapper::getInstance($this->adapter);
229 efrain 1848
        $quiz = $quizMapper->fetchOne($id);
1849
 
1850
        if(!$quiz) {
1851
            return [];
1852
        }
1853
 
1854
        $companyMapper = CompanyMapper::getInstance($this->adapter);
1855
        $company = $companyMapper->fetchOne($quiz->company_id);
1856
 
283 www 1857
        $questionMapper = MicrolearningQuestionMapper::getInstance($this->adapter);
1858
        $answerMapper = MicrolearningAnswerMapper::getInstance($this->adapter);
229 efrain 1859
 
1860
        $record_questions = [];
1861
        $questions = $questionMapper->fetchAllByQuizId($quiz->id);
1862
        foreach($questions as $question)
1863
        {
1864
            $record_answers = [];
1865
 
1866
            $answers = $answerMapper->fetchAllByQuizIdAndQuestionId($question->quiz_id, $question->id);
1867
            foreach($answers as $answer)
1868
            {
1869
                $dtAddedOn = \DateTime::createFromFormat('Y-m-d H:i:s', $answer->added_on);
1870
                $dtUpdatedOn = \DateTime::createFromFormat('Y-m-d H:i:s', $answer->updated_on);
1871
 
1872
                array_push($record_answers, [
1873
                    'uuid' => $answer->uuid,
1874
                    'text' => trim($answer->text),
1875
                    'correct' => $answer->correct ? $answer->correct  : 0 ,
1876
                    'points' => strval(intval($answer->points, 10)),
1877
                    'added_on'  => $dtAddedOn->format($serviceDatetimeFormat),
1878
                    'updated_on'    => $dtUpdatedOn->format($serviceDatetimeFormat),
1879
                ]);
1880
            }
1881
 
1882
            $dtAddedOn = \DateTime::createFromFormat('Y-m-d H:i:s', $question->added_on);
1883
            $dtUpdatedOn = \DateTime::createFromFormat('Y-m-d H:i:s', $question->updated_on);
1884
 
1885
            array_push($record_questions, [
1886
                'uuid'          => $question->uuid,
1887
                'text'          => trim($question->text),
1888
                'type'          => $question->type,
1889
                'maxlength'     => strval($question->maxlength),
1890
                'points'        => strval($question->points),
1891
                'answers'       => $record_answers,
1892
                'added_on'      => $dtAddedOn->format($serviceDatetimeFormat),
1893
                'updated_on'    => $dtUpdatedOn->format($serviceDatetimeFormat),
1894
            ]);
1895
        }
1896
 
1897
        $dtAddedOn = \DateTime::createFromFormat('Y-m-d H:i:s', $quiz->added_on);
1898
        $dtUpdatedOn = \DateTime::createFromFormat('Y-m-d H:i:s', $quiz->updated_on);
1899
 
1900
        array_push($data, [
1901
            'uuid' => $quiz->uuid,
1902
            'name' => $quiz->name,
1903
            'text' => trim($quiz->text ? $quiz->text : ''),
1904
            'failed' => trim($quiz->failed ? $quiz->failed : ''),
1905
            'points' => strval($quiz->points),
1906
            'minimum_points_required' => strval($quiz->minimum_points_required),
1907
            'max_time' => $quiz->max_time ? $quiz->max_time : 5,
1908
            'company_uuid' => $company->uuid,
1909
            'company_name' => $company->name,
1910
            'company_image' => $this->url()->fromRoute('services/storage',['type' => 'company', 'code' => $company->uuid, 'filename' => $company->image], ['force_canonical' => true]),
1911
            'questions'     => $record_questions,
1912
            'added_on'      => $dtAddedOn->format($serviceDatetimeFormat),
1913
            'updated_on'    => $dtUpdatedOn->format($serviceDatetimeFormat),
1914
        ]);
1915
 
1916
        return $data;
1917
 
1918
    }
161 efrain 1919
 
229 efrain 1920
 
161 efrain 1921
    public function getSlideAction()
1922
    {
1923
        $request = $this->getRequest();
1924
        if($request->isGet()) {
1925
            $currentUserPlugin = $this->plugin('currentUserPlugin');
1926
            $currentUser = $currentUserPlugin->getUser();
1927
 
1928
 
1929
 
1930
            $id = $this->params()->fromRoute('id');
283 www 1931
            $slideMapper = MicrolearningSlideMapper::getInstance($this->adapter);
161 efrain 1932
            $slide = $slideMapper->fetchOneByUuid($id);
1933
 
1934
            if(!$slide) {
1935
                return new JsonModel([
1936
                    'success' => false,
1937
                    'data' => 'ERROR_SLIDE_NOT_FOUND'
1938
                ]);
1939
            }
1940
 
1941
            $accessGrantedIds = $this->getAccessGranted();
1942
 
1943
 
1944
 
1945
            if(!in_array($slide->capsule_id, $accessGrantedIds->capsules)) {
1946
                return new JsonModel([
1947
                    'success' => false,
1948
                    'data' => 'ERROR_YOU_DO_NOT_HAVE_ACCESS_TO_THIS_CAPSULE'
1949
                ]);
1950
            }
1951
 
1952
 
283 www 1953
            $topicMapper = MicrolearningTopicMapper::getInstance($this->adapter);
161 efrain 1954
            $topic = $topicMapper->fetchOne($slide->topic_id);
1955
 
283 www 1956
            $capsuleMapper =  MicrolearningCapsuleMapper::getInstance($this->adapter);
161 efrain 1957
            $capsule = $capsuleMapper->fetchOne($slide->capsule_id);
1958
 
1959
 
1960
 
1961
 
1962
 
283 www 1963
            $slideMapper = MicrolearningSlideMapper::getInstance($this->adapter);
1964
            $userProgressMapper = MicrolearningUserProgressMapper::getInstance($this->adapter);
161 efrain 1965
 
1966
 
1967
            $userProgress = $userProgressMapper->fetchOneByUserIdAndSlideId($currentUser->id, $slide->id);
1968
            if($userProgress) {
1969
                $completed = $userProgress->completed;
1970
            } else {
1971
                $completed = 0;
1972
            }
235 efrain 1973
 
1974
            $quiz_uuid = '';
1975
            $quiz_data = [];
1976
            $link_take_a_test = '';
1977
            if($slide->quiz_id) {
1978
 
283 www 1979
                $quizMapper = MicrolearningQuizMapper::getInstance($this->adapter);
235 efrain 1980
                $quiz = $quizMapper->fetchOne($slide->quiz_id);
1981
                if($quiz) {
1982
                    $quiz_uuid = $quiz->uuid;
1983
                    $quiz_data = $this->getQuiz($slide->quiz_id);
1984
                    $link_take_a_test = $this->url()->fromRoute('microlearning/take-a-test', ['slide_id' => $slide->uuid], ['force_canonical' => true]);
1985
                }
161 efrain 1986
 
235 efrain 1987
            }
161 efrain 1988
 
333 www 1989
            $storage = Storage::getInstance($this->config, $this->adapter);
283 www 1990
            $path = $storage->getPathMicrolearningSlide();
161 efrain 1991
 
1992
            $data =[
235 efrain 1993
                'quiz'              => $quiz_uuid,
1994
                'quiz_data'         => $quiz_data,
1995
                'uuid'              => $slide->uuid,
1996
                'name'              => $slide->name ? $slide->name : '',
1997
                'description'       => $slide->description ? $slide->description : '',
1998
                'type'              => $slide->type,
283 www 1999
                'background'        => $slide->background ? $storage->getGenericImage($path, $slide->uuid, $slide->background) : '',
2000
                'file'              => $slide->file ? $storage->getGenericFile($path, $slide->uuid, $slide->file) : '',
235 efrain 2001
                'order'             => $slide->order,
2002
                'completed'         => $completed,
2003
                'link_sync'         => $this->url()->fromRoute('microlearning/sync', ['operation' => 'slide-view', 'topic_uuid' => $topic->uuid, 'capsule_uuid' => $capsule->uuid, 'slide_uuid' => $slide->uuid], ['force_canonical' => true]),
2004
                'link_take_a_test'  => $link_take_a_test,
2005
                'added_on'          => $slide->added_on,
2006
                'updated_on'        => $slide->updated_on,
161 efrain 2007
            ];
2008
 
2009
 
2010
 
2011
 
2012
            return new JsonModel([
2013
                'success' => true,
2014
                'data' => $data
2015
            ]);
2016
 
2017
        } else {
2018
            return new JsonModel([
2019
                'success' => false,
2020
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
2021
            ]);
2022
        }
2023
    }
2024
 
119 efrain 2025
    public function profileAction()
2026
    {
2027
        $request = $this->getRequest();
2028
        if($request->isGet()) {
2029
            $currentUserPlugin = $this->plugin('currentUserPlugin');
2030
            $currentUser = $currentUserPlugin->getUser();
2031
 
2032
 
2033
            $accessGrantedIds = $this->getAccessGranted();
2034
 
2035
            $companyMapper = CompanyMapper::getInstance($this->adapter);
283 www 2036
            $companyExtendUserMapper = MicrolearningExtendUserMapper::getInstance($this->adapter);
2037
            $companyExtendUserCompanyMapper = MicrolearningExtendUserCompanyMapper::getInstance($this->adapter);
2038
            $companyExtendUserFunctionMapper = MicrolearningExtendUserFunctionMapper::getInstance($this->adapter);
2039
            $companyExtendUserGroupMapper = MicrolearningExtendUserGroupMapper::getInstance($this->adapter);
2040
            $companyExtendUserInstitutionMapper = MicrolearningExtendUserInstitutionMapper::getInstance($this->adapter);
2041
            $companyExtendUserPartnerMapper = MicrolearningExtendUserPartnerMapper::getInstance($this->adapter);
2042
            $companyExtendUserProgramMapper = MicrolearningExtendUserProgramMapper::getInstance($this->adapter);
2043
            $companyExtendUserStudentTypeMapper = MicrolearningExtendUserStudentTypeMapper::getInstance($this->adapter);
2044
            $companyExtendUserSectorMapper = MicrolearningExtendUserSectorMapper::getInstance($this->adapter);
119 efrain 2045
 
333 www 2046
            $storage = Storage::getInstance($this->config, $this->adapter);
283 www 2047
 
119 efrain 2048
 
2049
            $data = [];
2050
            foreach($accessGrantedIds->companies as $company_id)
2051
            {
2052
                $company = $companyMapper->fetchOne($company_id);
2053
                if(!$company) {
2054
                    continue;
2055
                }
2056
 
2057
                $record = [
2058
                    'name' => $company->name,
283 www 2059
                    'image' => $storage->getCompanyImage($company),
119 efrain 2060
                    'details' => [],
2061
                ];
2062
 
2063
                $companyExtendUser = $companyExtendUserMapper->fetchOneByCompanyIdAndUserId($company->id, $currentUser->id);
2064
                if(!$companyExtendUser) {
2065
                    continue;
2066
                }
2067
 
2068
                if($companyExtendUser->extend_company_id) {
2069
 
2070
                    $extendedCompany = $companyExtendUserCompanyMapper->fetchOne($companyExtendUser->company_id);
2071
                    if($extendedCompany) {
2072
                        array_push($record['details'],[
2073
                            'uuid' => $extendedCompany->uuid,
2074
                            'label' => 'LABEL_COMPANY',
2075
                            'value' => $extendedCompany->name
2076
                        ]);
2077
                    }
2078
                }
2079
 
2080
                if($companyExtendUser->extend_function_id) {
2081
                    $extendedFunction = $companyExtendUserFunctionMapper->fetchOne($companyExtendUser->extend_function_id);
2082
                    if($extendedFunction) {
2083
                        array_push($record['details'],[
2084
                            'uuid' => $extendedFunction->uuid,
2085
                            'label' => 'LABEL_FUNCTION',
2086
                            'value' => $extendedFunction->name
2087
                        ]);
2088
                    }
2089
                }
2090
 
2091
                if($companyExtendUser->extend_group_id) {
2092
                    $extendedGroup = $companyExtendUserGroupMapper->fetchOne($companyExtendUser->extend_group_id);
2093
                    if($extendedGroup) {
2094
                        array_push($record['details'],[
2095
                            'uuid' => $extendedGroup->uuid,
2096
                            'label' => 'LABEL_GROUP',
2097
                            'value' => $extendedGroup->name
2098
                        ]);
2099
                    }
2100
                }
2101
 
2102
                if($companyExtendUser->extend_institution_id) {
2103
                    $extendedInstitution= $companyExtendUserInstitutionMapper->fetchOne($companyExtendUser->extend_institution_id);
2104
                    if($extendedInstitution) {
2105
                        array_push($record['details'],[
2106
                            'uuid' => $extendedInstitution->uuid,
2107
                            'label' => 'LABEL_INSTITUTION',
2108
                            'value' => $extendedInstitution->name
2109
                        ]);
2110
                    }
2111
                }
2112
 
2113
                if($companyExtendUser->extend_program_id) {
2114
                    $extendedProgram = $companyExtendUserProgramMapper->fetchOne($companyExtendUser->extend_program_id);
2115
                    if($extendedProgram) {
2116
                        array_push($record['details'],[
2117
                            'uuid' => $extendedProgram->uuid,
2118
                            'label' => 'LABEL_PROGRAM',
2119
                            'value' => $extendedProgram->name
2120
                        ]);
2121
 
2122
                    }
2123
                }
2124
 
2125
                if($companyExtendUser->extend_sector_id) {
2126
                    $extendedSector = $companyExtendUserSectorMapper->fetchOne($companyExtendUser->extend_sector_id);
2127
                    if($extendedSector) {
2128
                        array_push($record['details'],[
2129
                            'uuid' => $extendedSector->uuid,
2130
                            'label' => 'LABEL_SECTOR',
2131
                            'value' => $extendedSector->name
2132
                        ]);
2133
                    }
2134
                }
2135
 
2136
                if($companyExtendUser->extend_partner_id) {
2137
                    $extendedPartner = $companyExtendUserPartnerMapper->fetchOne($companyExtendUser->extend_partner_id);
2138
                    if($extendedPartner) {
2139
                        array_push($record['details'],[
2140
                            'uuid' => $extendedPartner->uuid,
2141
                            'label' => 'LABEL_PARTNER',
2142
                            'value' => $extendedPartner->name
2143
                        ]);
2144
                    }
2145
                }
2146
 
2147
                if($companyExtendUser->extend_student_type_id) {
2148
                    $extendedStudentType = $companyExtendUserStudentTypeMapper->fetchOne($companyExtendUser->extend_student_type_id);
2149
                    if($extendedStudentType) {
2150
                        array_push($record['details'],[
2151
                            'uuid' => $extendedStudentType->uuid,
2152
                            'label' => 'LABEL_TYPE',
2153
                            'value' => $extendedStudentType->name
2154
                        ]);
2155
                    }
2156
                }
2157
 
2158
                array_push($data, $record);
2159
            }
2160
 
2161
            return new JsonModel([
2162
                'success' => true,
2163
                'data' => $data
2164
            ]);
2165
 
2166
        } else {
2167
            return new JsonModel([
2168
                'success' => false,
2169
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
2170
            ]);
2171
        }
2172
    }
2173
 
167 efrain 2174
    public function syncAction()
2175
    {
2176
        $request = $this->getRequest();
168 efrain 2177
        if($request->isPost()) {
167 efrain 2178
            $currentUserPlugin = $this->plugin('currentUserPlugin');
2179
            $currentUser = $currentUserPlugin->getUser();
2180
 
2181
 
2182
            $operation = $this->params()->fromRoute('operation');
2183
            if($operation == 'slide-view' || $operation == 'capsule-close' || $operation == 'topic-close') {
2184
                $accessGrantedIds = $this->getAccessGranted();
2185
 
2186
                $topic_uuid     = $this->params()->fromRoute('topic_uuid');
2187
                $capsule_uuid   = $this->params()->fromRoute('capsule_uuid');
2188
                $slide_uuid     = $this->params()->fromRoute('slide_uuid');
2189
 
2190
                $accessGrantedIds = $this->getAccessGranted();
2191
                if($operation == 'slide-view') {
2192
 
2193
                    if(empty($slide_uuid) || empty($capsule_uuid ) || empty($topic_uuid)) {
2194
                        return new JsonModel([
2195
                            'success' => false,
2196
                            'data' => 'ERROR_INVALID_PARAMETERS'
2197
                        ]);
2198
                    }
2199
 
2200
 
283 www 2201
                    $topicMapper = MicrolearningTopicMapper::getInstance($this->adapter);
167 efrain 2202
                    $topic = $topicMapper->fetchOneByUuid($topic_uuid);
2203
 
2204
                    if(!$topic) {
2205
                        return new JsonModel([
2206
                            'success' => false,
2207
                            'data' => 'ERROR_TOPIC_NOT_FOUND'
2208
                        ]);
2209
                    }
2210
 
2211
 
2212
 
2213
                    if(!in_array($topic->id, $accessGrantedIds->topics)) {
2214
                        return new JsonModel([
2215
                            'success' => false,
2216
                            'data' => 'ERROR_YOU_DO_NOT_HAVE_ACCESS_TO_THIS_TOPIC'
2217
                        ]);
2218
                    }
2219
 
283 www 2220
                    $capsuleMapper = MicrolearningCapsuleMapper::getInstance($this->adapter);
167 efrain 2221
                    $capsule = $capsuleMapper->fetchOneByUuid($capsule_uuid);
2222
 
2223
                    if(!$capsule) {
2224
                        return new JsonModel([
2225
                            'success' => false,
2226
                            'data' => 'ERROR_CAPSULE_NOT_FOUND'
2227
                        ]);
2228
                    }
119 efrain 2229
 
167 efrain 2230
                    if(!in_array($capsule->id, $accessGrantedIds->capsules) || $capsule->topic_id != $topic->id) {
2231
                        return new JsonModel([
2232
                            'success' => false,
2233
                            'data' => 'ERROR_YOU_DO_NOT_HAVE_ACCESS_TO_THIS_CAPSULE'
2234
                        ]);
2235
                    }
2236
 
283 www 2237
                    $slideMapper = MicrolearningSlideMapper::getInstance($this->adapter);
167 efrain 2238
                    $slide = $slideMapper->fetchOneByUuid($slide_uuid);
2239
                    if(!$slide) {
2240
                        return new JsonModel([
2241
                            'success' => false,
2242
                            'data' => 'ERROR_SLIDE_NOT_FOUND'
2243
                        ]);
2244
                    }
2245
 
2246
                    if($slide->capsule_id != $capsule->id && $slide->topic_id != $topic->id) {
2247
                        return new JsonModel([
2248
                            'success' => false,
2249
                            'data' => 'ERROR_SLIDE_NOT_FOUND'
2250
                        ]);
2251
 
2252
                    }
2253
 
2254
 
283 www 2255
                    $userLogMapper = MicrolearningUserLogMapper::getInstance($this->adapter);
167 efrain 2256
 
283 www 2257
                    $userProgressMapper = MicrolearningUserProgressMapper::getInstance($this->adapter);
167 efrain 2258
                    $added_on = $userProgressMapper->getDatebaseNow();
2259
 
2260
 
2261
                    $userProgressTopic = $userProgressMapper->fetchOneByUserIdAndTopicId($currentUser->id, $topic->id);
2262
                    if(!$userProgressTopic) {
2263
 
283 www 2264
                        $userProgressTopic = new MicrolearningUserProgress();
558 stevensc 2265
                        $userProgressTopic->company_id                  = $topic->company_id; // Usar company_id del tópico
2266
                        $userProgressTopic->topic_id                    = $topic->id;        // Usar id del tópico
176 efrain 2267
                        $userProgressTopic->user_id                     = $currentUser->id;
167 efrain 2268
                        $userProgressTopic->progress                    = 0;
2269
                        $userProgressTopic->returning                   = 0;
2270
                        $userProgressTopic->returning_after_completed   = 0;
2271
                        $userProgressTopic->completed                   = 0;
558 stevensc 2272
                        $userProgressTopic->total_slides                = $slideMapper->fetchTotalCountByCompanyIdAndTopicId($topic->company_id, $topic->id);
167 efrain 2273
                        $userProgressTopic->view_slides                 = 0;
283 www 2274
                        $userProgressTopic->type                        = MicrolearningUserProgress::TYPE_TOPIC;
167 efrain 2275
                        $userProgressTopic->added_on                    = $added_on;
2276
                        $userProgressTopic->updated_on                  = $added_on;
2277
 
2278
                        if($userProgressMapper->insert($userProgressTopic)) {
2279
 
283 www 2280
                            $userLog = new MicrolearningUserLog();
2281
                            $userLog->activity      = MicrolearningUserLog::ACTIVITY_START_TOPIC;
167 efrain 2282
                            $userLog->user_id       = $currentUser->id;
558 stevensc 2283
                            $userLog->company_id    = $topic->company_id;
2284
                            $userLog->topic_id      = $topic->id;
167 efrain 2285
                            $userLog->added_on      = $added_on;
2286
 
2287
                            if(!$userLogMapper->insert($userLog)) {
2288
                                return new JsonModel([
2289
                                    'success' => false,
2290
                                    'data' => $userProgressMapper->getError()
2291
                                ]);
2292
                            }
2293
                        } else {
2294
                            return new JsonModel([
2295
                                'success' => false,
2296
                                'data' => $userProgressMapper->getError()
2297
                            ]);
2298
                        }
2299
                    }
2300
 
2301
 
2302
                    $userProgressCapsule = $userProgressMapper->fetchOneByUseridAndCapsuleId($currentUser->id, $capsule->id);
2303
                    if(!$userProgressCapsule) {
2304
 
283 www 2305
                        $userProgressCapsule = new MicrolearningUserProgress();
558 stevensc 2306
                        $userProgressCapsule->company_id                  = $capsule->company_id; // Usar company_id de la cápsula
2307
                        $userProgressCapsule->topic_id                    = $topic->id;         // Usar el id del tópico obtenido previamente
2308
                        $userProgressCapsule->capsule_id                  = $capsule->id;       // Usar id de la cápsula
176 efrain 2309
                        $userProgressCapsule->user_id                     = $currentUser->id;
167 efrain 2310
                        $userProgressCapsule->progress                    = 0;
2311
                        $userProgressCapsule->returning                   = 0;
2312
                        $userProgressCapsule->returning_after_completed   = 0;
2313
                        $userProgressCapsule->completed                   = 0;
558 stevensc 2314
                        $userProgressCapsule->total_slides                = $slideMapper->fetchTotalCountByCompanyIdAndTopicIdAndCapsuleId($capsule->company_id, $topic->id, $capsule->id);
167 efrain 2315
                        $userProgressCapsule->view_slides                 = 0;
2316
                        $userProgressTopic->updated_on                    = $added_on;
2317
 
2318
                        if($userProgressMapper->insert($userProgressCapsule)) {
2319
 
283 www 2320
                            $userLog = new MicrolearningUserLog();
2321
                            $userLog->activity      = MicrolearningUserLog::ACTIVITY_START_CAPSULE;
167 efrain 2322
                            $userLog->user_id       = $currentUser->id;
558 stevensc 2323
                            $userLog->company_id    = $capsule->company_id;
2324
                            $userLog->topic_id      = $topic->id;
2325
                            $userLog->capsule_id    = $capsule->id;
167 efrain 2326
                            $userLog->added_on      = $added_on;
2327
 
2328
                            if(!$userLogMapper->insert($userLog)) {
2329
                                return new JsonModel([
2330
                                    'success' => false,
2331
                                    'data' => $userLogMapper->getError()
2332
                                ]);
2333
                            }
2334
                        } else {
2335
                            return new JsonModel([
2336
                                'success' => false,
2337
                                'data' => $userProgressMapper->getError()
2338
                            ]);
2339
                        }
2340
                    }
2341
 
2342
 
2343
                    $userProgressSlide = $userProgressMapper->fetchOneByUserIdAndSlideId($currentUser->id, $slide->id);
2344
                    if(!$userProgressSlide) {
283 www 2345
                        $userProgressSlide = new MicrolearningUserProgress();
167 efrain 2346
                        $userProgressSlide->company_id                  = $slide->company_id;
2347
                        $userProgressSlide->topic_id                    = $slide->topic_id;
2348
                        $userProgressSlide->capsule_id                  = $slide->capsule_id;
2349
                        $userProgressSlide->slide_id                    = $slide->id;
176 efrain 2350
                        $userProgressSlide->user_id                     = $currentUser->id;
167 efrain 2351
                        $userProgressSlide->progress                    = 0;
2352
                        $userProgressSlide->returning                   = 0;
2353
                        $userProgressSlide->returning_after_completed   = 0;
2354
                        $userProgressSlide->completed                   = 1;
2355
                        $userProgressSlide->total_slides                = 0;
2356
                        $userProgressSlide->view_slides                 = 0;
283 www 2357
                        $userProgressSlide->type                        = MicrolearningUserProgress::TYPE_SLIDE;
167 efrain 2358
                        $userProgressSlide->added_on                    = $added_on;
2359
                        $userProgressSlide->updated_on                  = $added_on;
2360
 
2361
                        if(!$userProgressMapper->insert($userProgressSlide)) {
2362
                            return new JsonModel([
2363
                                'success' => false,
2364
                                'data' => $userProgressMapper->getError()
2365
                            ]);
2366
                        }
2367
                    }
2368
 
283 www 2369
                    $userLog = new MicrolearningUserLog();
2370
                    $userLog->activity      = MicrolearningUserLog::ACTIVITY_VIEW_SLIDE;
167 efrain 2371
                    $userLog->user_id       = $currentUser->id;
2372
                    $userLog->company_id    = $slide->company_id;
2373
                    $userLog->topic_id      = $slide->topic_id;
2374
                    $userLog->capsule_id    = $slide->capsule_id;
2375
                    $userLog->slide_id      = $slide->id;
2376
                    $userLog->added_on      = $added_on;
2377
 
2378
                    if(!$userLogMapper->insert($userLog)) {
2379
                        return new JsonModel([
2380
                            'success' => false,
2381
                            'data' => $userLogMapper->getError()
2382
                        ]);
2383
                    }
2384
 
2385
                    $closeCapsule = false;
2386
 
2387
                    if($userProgressCapsule->completed) {
2388
 
2389
                        $dt = \DateTime::createFromFormat('Y-m-d H:i:s', $added_on);
2390
                        $returning_on = $dt->format('Y-m-d');
2391
 
558 stevensc 2392
                        // Asegurarse que returning_on existe en el objeto antes de comparar
2393
                        $current_returning_on = isset($userProgressCapsule->returning_on) ? $userProgressCapsule->returning_on : null;
2394
 
2395
                        if(!$current_returning_on || $current_returning_on != $returning_on) {
167 efrain 2396
 
2397
                            $userProgressCapsule->returning_on = $returning_on;
558 stevensc 2398
                            // Asegurarse que returning_after_completed existe y es numérico antes de incrementar
2399
                            $userProgressCapsule->returning_after_completed = (isset($userProgressCapsule->returning_after_completed) ? intval($userProgressCapsule->returning_after_completed) : 0) + 1;
167 efrain 2400
 
2401
                            if(!$userProgressMapper->update($userProgressCapsule)) {
2402
                                return new JsonModel([
2403
                                    'success' => false,
2404
                                    'data' => $userProgressMapper->getError()
2405
                                ]);
2406
                            }
2407
                        }
2408
 
2409
                    }  else {
2410
 
558 stevensc 2411
                        // Usar $topic->id para obtener el total de slides de la cápsula en el contexto de este tópico
2412
                        $userProgressCapsule->total_slides = $slideMapper->fetchTotalCountByCompanyIdAndTopicIdAndCapsuleId($capsule->company_id, $topic->id, $capsule->id);
2413
                        $userProgressCapsule->view_slides = $userProgressMapper->fetchCountAllSlideCompletedByUserIdAndCapsuleId($currentUser->id, $capsule->id);
167 efrain 2414
 
2415
                        if($userProgressCapsule->total_slides) {
2416
 
2417
                            $userProgressCapsule->progress = ($userProgressCapsule->view_slides * 100) / $userProgressCapsule->total_slides;
2418
                            $userProgressCapsule->progress = $userProgressCapsule->progress > 100 ? 100 : $userProgressCapsule->progress;
2419
                        }
2420
 
2421
                        if(!$userProgressMapper->update($userProgressCapsule)) {
2422
                            return new JsonModel([
2423
                                'success' => false,
2424
                                'data' => $userProgressMapper->getError()
2425
                            ]);
2426
                        }
2427
 
2428
                        if($userProgressCapsule->progress >= 100) {
2429
                            $closeCapsule = true;
2430
                        }
171 efrain 2431
 
283 www 2432
 
167 efrain 2433
                    }
2434
 
2435
                    $closeTopic = false;
2436
                    if(!$userProgressTopic->completed) {
2437
 
558 stevensc 2438
                        // Usar $topic->id para obtener el total de slides del tópico
2439
                        $userProgressTopic->total_slides = $slideMapper->fetchTotalCountByCompanyIdAndTopicId($topic->company_id, $topic->id);
2440
                        $userProgressTopic->view_slides = $userProgressMapper->fetchCountAllSlideCompletedByUserIdAndTopicId($currentUser->id, $topic->id);
167 efrain 2441
 
2442
                        if($userProgressTopic->total_slides) {
2443
 
2444
                            $userProgressTopic->progress = ($userProgressTopic->view_slides * 100) / $userProgressTopic->total_slides;
2445
                            $userProgressTopic->progress = $userProgressTopic->progress > 100 ? 100 : $userProgressTopic->progress;
2446
                        }
2447
                        if(!$userProgressMapper->update($userProgressTopic)) {
2448
                            return new JsonModel([
2449
                                'success' => false,
2450
                                'data' => $userProgressMapper->getError()
2451
                            ]);
2452
                        }
2453
 
2454
                        if($userProgressTopic->progress >= 100) {
2455
                            $closeTopic = true;
2456
                        }
2457
                    }
2458
 
2459
 
2460
                    $data = [
2461
                        'message' => 'LABEL_THE_USER_PROGRESS_FOR_THIS_SLIDE_HAS_BEEN_COMPLETED',
2462
 
2463
                    ];
2464
 
2465
                    if($closeCapsule) {
173 efrain 2466
                        $data['link_close_capsule'] = $this->url()->fromRoute('microlearning/sync', ['operation' => 'capsule-close', 'topic_uuid' => $topic->uuid, 'capsule_uuid' => $capsule->uuid], ['force_canonical' => true]);
167 efrain 2467
                    }
2468
 
2469
 
2470
                    if($closeTopic) {
173 efrain 2471
                        $data['link_close_topic'] = $this->url()->fromRoute('microlearning/sync', ['operation' => 'topic-close', 'topic_uuid' => $topic->uuid], ['force_canonical' => true]);
167 efrain 2472
                    }
2473
 
2474
 
2475
                    return new JsonModel([
2476
                        'success' => true,
2477
                        'data' => $data
2478
                    ]);
2479
 
2480
 
2481
 
2482
 
2483
                } else if($operation == 'capsule-close') {
2484
 
2485
                    if(empty($capsule_uuid ) || empty($topic_uuid)) {
2486
                        return new JsonModel([
2487
                            'success' => false,
2488
                            'data' => 'ERROR_INVALID_PARAMETERS'
2489
                        ]);
2490
                    }
2491
 
2492
 
283 www 2493
                    $topicMapper = MicrolearningTopicMapper::getInstance($this->adapter);
167 efrain 2494
                    $topic = $topicMapper->fetchOneByUuid($topic_uuid);
2495
 
2496
                    if(!$topic) {
2497
                        return new JsonModel([
2498
                            'success' => false,
2499
                            'data' => 'ERROR_TOPIC_NOT_FOUND'
2500
                        ]);
2501
                    }
2502
 
2503
 
2504
 
2505
                    if(!in_array($topic->id, $accessGrantedIds->topics)) {
2506
                        return new JsonModel([
2507
                            'success' => false,
2508
                            'data' => 'ERROR_YOU_DO_NOT_HAVE_ACCESS_TO_THIS_TOPIC'
2509
                        ]);
2510
                    }
2511
 
283 www 2512
                    $capsuleMapper = MicrolearningCapsuleMapper::getInstance($this->adapter);
167 efrain 2513
                    $capsule = $capsuleMapper->fetchOneByUuid($capsule_uuid);
2514
 
2515
                    if(!$capsule) {
2516
                        return new JsonModel([
2517
                            'success' => false,
2518
                            'data' => 'ERROR_CAPSULE_NOT_FOUND'
2519
                        ]);
2520
                    }
2521
 
2522
                    if(!in_array($capsule->id, $accessGrantedIds->capsules) || $capsule->topic_id != $topic->id) {
2523
                        return new JsonModel([
2524
                            'success' => false,
2525
                            'data' => 'ERROR_YOU_DO_NOT_HAVE_ACCESS_TO_THIS_CAPSULE'
2526
                        ]);
2527
                    }
2528
 
2529
 
283 www 2530
                    $userLogMapper = MicrolearningUserLogMapper::getInstance($this->adapter);
167 efrain 2531
 
283 www 2532
                    $userProgressMapper = MicrolearningUserProgressMapper::getInstance($this->adapter);
167 efrain 2533
                    $updated_on = $userProgressMapper->getDatebaseNow();
2534
 
2535
                    $userProgressCapsule = $userProgressMapper->fetchOneByUseridAndCapsuleId($currentUser->id, $capsule->id);
2536
                    if(!$userProgressCapsule) {
2537
                        return new JsonModel([
2538
                            'success' => false,
2539
                            'data' => 'ERROR_THE_USER_PROGRESS_FOR_THIS_CAPSULE_NOT_FOUND'
2540
                        ]);
2541
                    }
2542
 
2543
                    if($userProgressCapsule->completed) {
2544
                        return new JsonModel([
2545
                            'success' => false,
2546
                            'data' => 'ERROR_THE_USER_PROGRESS_FOR_THIS_CAPSULE_ALREADY_CLOSED'
2547
                        ]);
2548
                    }
2549
 
2550
 
2551
                    $userProgressCapsule->completed = 1;
2552
                    $userProgressCapsule->updated_on = $updated_on;
2553
 
2554
                    if($userProgressMapper->update($userProgressCapsule)) {
225 efrain 2555
 
2556
 
283 www 2557
                        $userLog = new MicrolearningUserLog();
2558
                        $userLog->activity      = MicrolearningUserLog::ACTIVITY_COMPLETED_CAPSULE;
227 efrain 2559
                        $userLog->user_id       = $currentUser->id;
2560
                        $userLog->company_id    = $capsule->company_id;
2561
                        $userLog->topic_id      = $capsule->topic_id;
2562
                        $userLog->capsule_id    = $capsule->id;
2563
                        $userLog->added_on      = $updated_on;
225 efrain 2564
 
2565
                        if(!$userLogMapper->insert($userLog)) {
2566
                            return new JsonModel([
2567
                                'success' => false,
2568
                                'data' => $userProgressMapper->getError()
2569
                            ]);
2570
                        }
2571
 
2572
 
167 efrain 2573
                        return new JsonModel([
2574
                            'success' => true,
2575
                            'data' => 'LABEL_THE_USER_PROGRESS_FOR_THIS_CAPSULE_HAS_BEEN_COMPLETED'
2576
                        ]);
2577
                    } else {
2578
                        return new JsonModel([
2579
                            'success' => false,
2580
                            'data' => 'ERROR_THE_USER_PROGRESS_FOR_THIS_CAPSULE_COULD_NOT_BE_COMPLETED'
2581
                        ]);
2582
                    }
2583
 
2584
 
2585
 
2586
 
2587
 
2588
 
2589
 
2590
                } else if($operation == 'topic-close') {
174 efrain 2591
                    if(empty($topic_uuid)) {
167 efrain 2592
                        return new JsonModel([
2593
                            'success' => false,
2594
                            'data' => 'ERROR_INVALID_PARAMETERS'
2595
                        ]);
2596
                    }
2597
 
2598
 
283 www 2599
                    $topicMapper = MicrolearningTopicMapper::getInstance($this->adapter);
167 efrain 2600
                    $topic = $topicMapper->fetchOneByUuid($topic_uuid);
2601
 
2602
                    if(!$topic) {
2603
                        return new JsonModel([
2604
                            'success' => false,
2605
                            'data' => 'ERROR_TOPIC_NOT_FOUND'
2606
                        ]);
2607
                    }
2608
 
2609
 
2610
 
2611
                    if(!in_array($topic->id, $accessGrantedIds->topics)) {
2612
                        return new JsonModel([
2613
                            'success' => false,
2614
                            'data' => 'ERROR_YOU_DO_NOT_HAVE_ACCESS_TO_THIS_TOPIC'
2615
                        ]);
2616
                    }
2617
 
2618
 
2619
 
2620
 
283 www 2621
                    $userLogMapper = MicrolearningUserLogMapper::getInstance($this->adapter);
167 efrain 2622
 
283 www 2623
                    $userProgressMapper = MicrolearningUserProgressMapper::getInstance($this->adapter);
167 efrain 2624
                    $updated_on = $userProgressMapper->getDatebaseNow();
2625
 
2626
                    $userProgressTopic = $userProgressMapper->fetchOneByUserIdAndTopicId($currentUser->id, $topic->id);
2627
                    if(!$userProgressTopic) {
2628
                        return new JsonModel([
2629
                            'success' => false,
2630
                            'data' => 'ERROR_THE_USER_PROGRESS_FOR_THIS_TOPIC_NOT_FOUND'
2631
                        ]);
2632
                    }
2633
 
2634
                    if($userProgressTopic->completed) {
2635
                        return new JsonModel([
2636
                            'success' => false,
2637
                            'data' => 'ERROR_THE_USER_PROGRESS_FOR_THIS_TOPIC_ALREADY_CLOSED'
2638
                        ]);
2639
                    }
2640
 
2641
 
2642
                    $userProgressTopic->completed = 1;
2643
                    $userProgressTopic->updated_on = $updated_on;
2644
 
2645
                    if($userProgressMapper->update($userProgressTopic)) {
226 efrain 2646
 
283 www 2647
                        $userLog = new MicrolearningUserLog();
2648
                        $userLog->activity      = MicrolearningUserLog::ACTIVITY_COMPLETED_TOPIC;
227 efrain 2649
                        $userLog->user_id       = $currentUser->id;
2650
                        $userLog->company_id    = $topic->company_id;
2651
                        $userLog->topic_id      = $topic->id;
2652
                        $userLog->added_on      = $updated_on;
226 efrain 2653
 
2654
                        if(!$userLogMapper->insert($userLog)) {
2655
                            return new JsonModel([
2656
                                'success' => false,
2657
                                'data' => $userProgressMapper->getError()
2658
                            ]);
2659
                        }
2660
 
167 efrain 2661
                        return new JsonModel([
2662
                            'success' => true,
2663
                            'data' => 'LABEL_THE_USER_PROGRESS_FOR_THIS_TOPIC_HAS_BEEN_COMPLETED'
2664
                        ]);
2665
                    } else {
2666
                        return new JsonModel([
2667
                            'success' => false,
2668
                            'data' => 'ERROR_THE_USER_PROGRESS_FOR_THIS_TOPIC_COULD_NOT_BE_COMPLETED'
2669
                        ]);
2670
                    }
2671
                }
2672
 
2673
 
2674
 
2675
 
2676
            } else {
2677
 
2678
                return new JsonModel([
2679
                    'success' => false,
2680
                    'data' => 'ERROR_OPERATION_UNKNOWN'
2681
                ]);
2682
 
2683
 
2684
            }
2685
 
2686
        } else {
2687
            return new JsonModel([
2688
                'success' => false,
2689
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
2690
            ]);
2691
        }
2692
    }
2693
 
2694
 
302 www 2695
 
2696
 
2697
 
119 efrain 2698
    /**
2699
     *
2700
     * @return \LeadersLinked\Controller\MicrolearningUserAccessGrantedIds
2701
     */
2702
    private function getAccessGranted()
2703
    {
2704
        $currentUserPlugin = $this->plugin('currentUserPlugin');
2705
        $currentUser = $currentUserPlugin->getUser();
2706
 
283 www 2707
        $capsuleUserMapper = MicrolearningCapsuleUserMapper::getInstance($this->adapter);
119 efrain 2708
        $now = $capsuleUserMapper->getDatebaseNow();
2709
 
2710
        $records = $capsuleUserMapper->fetchAllActiveByUserId($currentUser->id);
2711
 
2712
        $accessGrantedIds = new MicrolearningUserAccessGrantedIds();
2713
 
2714
 
2715
        foreach($records as $record)
2716
        {
283 www 2717
            if($record->access != MicrolearningCapsuleUser::ACCESS_UNLIMITED && $record->access != MicrolearningCapsuleUser::ACCESS_PAY_PERIOD) {
119 efrain 2718
                continue;
2719
            }
283 www 2720
            if($record->access == MicrolearningCapsuleUser::ACCESS_PAY_PERIOD) {
119 efrain 2721
                if($now < $record->paid_from || $now > $record->paid_to) {
2722
                    continue;
2723
                }
2724
            }
2725
 
2726
 
2727
            if(!in_array($record->company_id, $accessGrantedIds->companies )) {
2728
                array_push($accessGrantedIds->companies, $record->company_id);
2729
            }
2730
 
2731
            if(!in_array($record->topic_id, $accessGrantedIds->topics )) {
2732
                array_push( $accessGrantedIds->topics, $record->topic_id);
2733
            }
2734
 
2735
            if(!in_array($record->capsule_id, $accessGrantedIds->capsules)) {
2736
                array_push( $accessGrantedIds->capsules, $record->capsule_id);
2737
            }
2738
        }
2739
 
2740
        return $accessGrantedIds;
2741
    }
2742
 
2743
 
2744
}