Proyectos de Subversion LeadersLinked - Services

Rev

Rev 584 | Rev 586 | 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,
119 efrain 640
                    'added_on'          => $capsule->added_on,
641
                    'updated_on'        => $capsule->updated_on,
642
                ]);
643
            }
644
 
558 stevensc 645
            // 8. Ordenar
245 efrain 646
 
647
            if($order_field == 'name') {
648
                if($order_direction == 'asc') {
558 stevensc 649
                    usort($capsulesData, function($a, $b) {
245 efrain 650
                        return strcasecmp($a['name'], $b['name']);
651
                    });
652
                } else {
558 stevensc 653
                    usort($capsulesData, function($a, $b) {
245 efrain 654
                        $result = strcasecmp($a['name'], $b['name']);
558 stevensc 655
                        if($result < 0) { return 1; } else if($result > 0) { return -1; } else { return 0; } // Simplificado
245 efrain 656
                    });
119 efrain 657
                }
658
 
245 efrain 659
            }
660
 
661
            if($order_field == 'added_on') {
662
                if($order_direction == 'asc') {
558 stevensc 663
                    usort($capsulesData, function($a, $b) {
245 efrain 664
                        return strcasecmp($a['added_on'], $b['added_on']);
665
                    });
666
                } else {
558 stevensc 667
                    usort($capsulesData, function($a, $b) {
245 efrain 668
                        $result = strcasecmp($a['added_on'], $b['added_on']);
558 stevensc 669
                        if($result < 0) { return 1; } else if($result > 0) { return -1; } else { return 0; } // Simplificado
245 efrain 670
                    });
671
                }
119 efrain 672
 
558 stevensc 673
            }
119 efrain 674
 
558 stevensc 675
            // 9. Retornar
119 efrain 676
            return new JsonModel([
677
                'success' => true,
558 stevensc 678
                'data' => $capsulesData
119 efrain 679
            ]);
680
 
681
 
682
 
683
        }
684
 
685
        return new JsonModel([
686
            'success' => false,
687
            'data' => 'ERROR_METHOD_NOT_ALLOWED'
688
        ]);
689
 
690
    }
691
 
692
    public function capsulesCompletedAction()
693
    {
694
        $request = $this->getRequest();
695
        if($request->isGet()) {
696
            $currentUserPlugin = $this->plugin('currentUserPlugin');
697
            $currentUser = $currentUserPlugin->getUser();
698
 
699
            $name = Functions::sanitizeFilterString($this->params()->fromQuery('name'));
245 efrain 700
            $order_field = Functions::sanitizeFilterString($this->params()->fromQuery('order_field'));
701
            $order_direction = Functions::sanitizeFilterString($this->params()->fromQuery('order_direction'));
119 efrain 702
 
246 efrain 703
            if(!in_array($order_field,['name', 'added_on','last_access_on'] )) {
245 efrain 704
                $order_field = 'name';
705
            }
119 efrain 706
 
245 efrain 707
            if(!in_array( $order_direction,['asc', 'desc'])) {
708
                $order_field = 'asc';
709
            }
710
 
283 www 711
            $userProgressMapper = MicrolearningUserProgressMapper::getInstance($this->adapter);
712
            $capsuleMapper = MicrolearningCapsuleMapper::getInstance($this->adapter);
558 stevensc 713
            $topicCapsuleMapper = MicrolearningTopicCapsuleMapper::getInstance($this->adapter);
714
            $topicMapper = MicrolearningTopicMapper::getInstance($this->adapter);
283 www 715
            $capsuleCommentMapper = MicrolearningCapsuleCommentMapper::getInstance($this->adapter);
119 efrain 716
 
717
            $accessGranted = $this->getAccessGranted();
718
 
558 stevensc 719
            $capsulesData = [];
119 efrain 720
 
333 www 721
            $storage = Storage::getInstance($this->config, $this->adapter);
283 www 722
            $path = $storage->getPathMicrolearningCapsule();
723
 
119 efrain 724
            foreach($accessGranted->capsules as $capsule_id)
725
            {
558 stevensc 726
                // 1. Verificar progreso
119 efrain 727
                $userProgress = $userProgressMapper->fetchOneByUseridAndCapsuleId($currentUser->id, $capsule_id);
728
                if(!$userProgress) {
729
                    continue;
730
                }
731
 
732
                if(!$userProgress->completed) {
733
                    continue;
734
                }
735
 
558 stevensc 736
                // 2. Obtener detalles de la cápsula
119 efrain 737
                $capsule = $capsuleMapper->fetchOne($capsule_id);
558 stevensc 738
                if(!$capsule) {
739
                    continue;
740
                }
119 efrain 741
 
558 stevensc 742
                // 3. Filtrar por nombre
119 efrain 743
                if($name) {
744
                    if(empty($name) || stripos($capsule->name, $name) === false) {
745
                        continue;
746
                    }
747
                }
748
 
558 stevensc 749
                // 4. Obtener Tópico asociado válido
750
                $topic = null;
751
                $topic_uuid_for_links = null;
752
                $relation = $topicCapsuleMapper->fetchOneByCapsuleId($capsule->id);
753
                if ($relation && in_array($relation->topic_id, $accessGranted->topics)) {
754
                    $topic = $topicMapper->fetchOne($relation->topic_id);
755
                    if ($topic) {
756
                        $topic_uuid_for_links = $topic->uuid;
757
                    }
758
                }
759
 
760
                // 5. Obtener datos de comentarios
302 www 761
                $dataCountAndRatingAverage = $capsuleCommentMapper->fetchCountAndRatingAverage($capsule->company_id, $capsule->id);
119 efrain 762
 
558 stevensc 763
                // 6. Construir enlace slides
764
                $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 765
 
558 stevensc 766
                // 7. Añadir al array de resultados
767
                array_push($capsulesData, [
119 efrain 768
                    'uuid'              => $capsule->uuid,
769
                    'name'              => $capsule->name ? $capsule->name : '',
770
                    'description'       => $capsule->description ? $capsule->description : '',
283 www 771
                    'image'             => $capsule->image ? $storage->getGenericImage($path, $capsule->uuid, $capsule->image)  : '',
119 efrain 772
                    'position'          => $capsule->order,
773
                    'link_comments'     => $this->url()->fromRoute('microlearning/capsules-comments', ['capsule_id' => $capsule->uuid], ['force_canonical' => true]),
774
                    'link_comment_add'  => $this->url()->fromRoute('microlearning/capsules-comments/add', ['capsule_id' => $capsule->uuid],['force_canonical' => true]),
558 stevensc 775
                    'link_slides'       => $link_slides,
119 efrain 776
                    'total_comments'    => strval($dataCountAndRatingAverage['total_comments']),
777
                    'total_rating'      => strval($dataCountAndRatingAverage['total_rating']),
145 efrain 778
                    'progress'          => $userProgress->progress,
119 efrain 779
                    'added_on'          => $capsule->added_on,
246 efrain 780
                    'last_access_on'    => $userProgress->updated_on,
119 efrain 781
                    'updated_on'        => $capsule->updated_on,
782
                ]);
783
            }
784
 
558 stevensc 785
            // 8. Ordenar (lógica de ordenación permanece igual, usando $capsulesData)
245 efrain 786
            if($order_field == 'name') {
787
                if($order_direction == 'asc') {
558 stevensc 788
                    usort($capsulesData, function($a, $b) {
245 efrain 789
                        return strcasecmp($a['name'], $b['name']);
790
                    });
791
                } else {
558 stevensc 792
                    usort($capsulesData, function($a, $b) {
245 efrain 793
                        $result = strcasecmp($a['name'], $b['name']);
558 stevensc 794
                        if($result < 0) { return 1; } else if($result > 0) { return -1; } else { return 0; }
245 efrain 795
                    });
119 efrain 796
                }
245 efrain 797
            }
798
 
799
            if($order_field == 'added_on') {
800
                if($order_direction == 'asc') {
558 stevensc 801
                    usort($capsulesData, function($a, $b) {
245 efrain 802
                        return strcasecmp($a['added_on'], $b['added_on']);
803
                    });
804
                } else {
558 stevensc 805
                    usort($capsulesData, function($a, $b) {
245 efrain 806
                        $result = strcasecmp($a['added_on'], $b['added_on']);
558 stevensc 807
                        if($result < 0) { return 1; } else if($result > 0) { return -1; } else { return 0; }
245 efrain 808
                    });
809
                }
810
            }
246 efrain 811
 
812
            if($order_field == 'last_access_on') {
813
                if($order_direction == 'asc') {
558 stevensc 814
                    usort($capsulesData, function($a, $b) {
246 efrain 815
                        return strcasecmp($a['last_access_on'], $b['last_access_on']);
816
                    });
817
                } else {
558 stevensc 818
                    usort($capsulesData, function($a, $b) {
246 efrain 819
                        $result = strcasecmp($a['last_access_on'], $b['last_access_on']);
558 stevensc 820
                        if($result < 0) { return 1; } else if($result > 0) { return -1; } else { return 0; }
246 efrain 821
                    });
822
                }
823
            }
824
 
825
 
826
 
827
 
119 efrain 828
 
829
            return new JsonModel([
830
                'success' => true,
558 stevensc 831
                'data' => $capsulesData
119 efrain 832
            ]);
833
 
834
        }
835
 
836
        return new JsonModel([
837
            'success' => false,
838
            'data' => 'ERROR_METHOD_NOT_ALLOWED'
839
        ]);
840
    }
841
 
842
    public function capsulesInProgressAction()
843
    {
844
        $request = $this->getRequest();
845
        if($request->isGet()) {
846
            $currentUserPlugin = $this->plugin('currentUserPlugin');
847
            $currentUser = $currentUserPlugin->getUser();
848
 
849
            $name = Functions::sanitizeFilterString($this->params()->fromQuery('name'));
245 efrain 850
            $order_field = Functions::sanitizeFilterString($this->params()->fromQuery('order_field'));
851
            $order_direction = Functions::sanitizeFilterString($this->params()->fromQuery('order_direction'));
119 efrain 852
 
246 efrain 853
            if(!in_array($order_field,['name', 'added_on', 'last_access_on'] )) {
245 efrain 854
                $order_field = 'name';
855
            }
119 efrain 856
 
245 efrain 857
            if(!in_array( $order_direction,['asc', 'desc'])) {
558 stevensc 858
                $order_direction = 'asc';
245 efrain 859
            }
860
 
283 www 861
            $userProgressMapper = MicrolearningUserProgressMapper::getInstance($this->adapter);
862
            $capsuleMapper = MicrolearningCapsuleMapper::getInstance($this->adapter);
558 stevensc 863
            $topicCapsuleMapper = MicrolearningTopicCapsuleMapper::getInstance($this->adapter);
864
            $topicMapper = MicrolearningTopicMapper::getInstance($this->adapter);
283 www 865
            $capsuleCommentMapper = MicrolearningCapsuleCommentMapper::getInstance($this->adapter);
119 efrain 866
 
867
            $accessGranted = $this->getAccessGranted();
868
 
558 stevensc 869
            $capsulesData = [];
119 efrain 870
 
333 www 871
            $storage = Storage::getInstance($this->config, $this->adapter);
283 www 872
            $path = $storage->getPathMicrolearningCapsule();
873
 
119 efrain 874
            foreach($accessGranted->capsules as $capsule_id)
875
            {
558 stevensc 876
                // 1. Verificar progreso
119 efrain 877
                $userProgress = $userProgressMapper->fetchOneByUseridAndCapsuleId($currentUser->id, $capsule_id);
558 stevensc 878
                if(!$userProgress || $userProgress->completed) { // Si no hay progreso o ya está completada
119 efrain 879
                    continue;
880
                }
558 stevensc 881
 
882
                // 2. Obtener detalles de la cápsula
883
                $capsule = $capsuleMapper->fetchOne($capsule_id);
884
                if(!$capsule) {
119 efrain 885
                    continue;
886
                }
887
 
558 stevensc 888
                // 3. Filtrar por nombre
119 efrain 889
                if($name) {
890
                    if(empty($name) || stripos($capsule->name, $name) === false) {
891
                        continue;
892
                    }
893
                }
894
 
558 stevensc 895
                // 4. Obtener Tópico asociado válido
896
                $topic = null;
897
                $topic_uuid_for_links = null;
898
                $relation = $topicCapsuleMapper->fetchOneByCapsuleId($capsule->id);
899
                if ($relation && in_array($relation->topic_id, $accessGranted->topics)) {
900
                    $topic = $topicMapper->fetchOne($relation->topic_id);
901
                    if ($topic) {
902
                        $topic_uuid_for_links = $topic->uuid;
903
                    }
904
                }
119 efrain 905
 
558 stevensc 906
                // 5. Obtener datos de comentarios
302 www 907
                $dataCountAndRatingAverage = $capsuleCommentMapper->fetchCountAndRatingAverage($capsule->company_id,  $capsule->id);
119 efrain 908
 
558 stevensc 909
                // 6. Construir enlace slides
910
                $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 911
 
558 stevensc 912
                // 7. Añadir al array de resultados
913
                array_push($capsulesData, [
119 efrain 914
                    'uuid'              => $capsule->uuid,
915
                    'name'              => $capsule->name ? $capsule->name : '',
916
                    'description'       => $capsule->description ? $capsule->description : '',
283 www 917
                    'image'             => $capsule->image ? $storage->getGenericImage($path, $capsule->uuid, $capsule->image)  : '',
119 efrain 918
                    'position'          => $capsule->order,
919
                    'link_comments'     => $this->url()->fromRoute('microlearning/capsules-comments', ['capsule_id' => $capsule->uuid], ['force_canonical' => true]),
920
                    'link_comment_add'  => $this->url()->fromRoute('microlearning/capsules-comments/add', ['capsule_id' => $capsule->uuid],['force_canonical' => true]),
558 stevensc 921
                    'link_slides'       => $link_slides,
119 efrain 922
                    'total_comments'    => strval($dataCountAndRatingAverage['total_comments']),
923
                    'total_rating'      => strval($dataCountAndRatingAverage['total_rating']),
585 stevensc 924
                    'progress'          => $userProgress->progress,
925
                    'last_access_on'    => $userProgress->updated_on,
926
                    'added_on'          => $capsule->added_on,
927
                    'updated_on'        => $capsule->updated_on,
119 efrain 928
                ]);
929
            }
930
 
558 stevensc 931
            // 8. Ordenar (lógica de ordenación permanece igual, usando $capsulesData)
245 efrain 932
            if($order_field == 'name') {
933
                if($order_direction == 'asc') {
558 stevensc 934
                    usort($capsulesData, function($a, $b) {
245 efrain 935
                        return strcasecmp($a['name'], $b['name']);
936
                    });
937
                } else {
558 stevensc 938
                    usort($capsulesData, function($a, $b) {
245 efrain 939
                        $result = strcasecmp($a['name'], $b['name']);
558 stevensc 940
                        if($result < 0) { return 1; } else if($result > 0) { return -1; } else { return 0; }
245 efrain 941
                    });
119 efrain 942
                }
245 efrain 943
            }
944
 
945
            if($order_field == 'added_on') {
946
                if($order_direction == 'asc') {
558 stevensc 947
                    usort($capsulesData, function($a, $b) {
245 efrain 948
                        return strcasecmp($a['added_on'], $b['added_on']);
949
                    });
950
                } else {
558 stevensc 951
                    usort($capsulesData, function($a, $b) {
245 efrain 952
                        $result = strcasecmp($a['added_on'], $b['added_on']);
558 stevensc 953
                        if($result < 0) { return 1; } else if($result > 0) { return -1; } else { return 0; }
245 efrain 954
                    });
955
                }
956
            }
246 efrain 957
 
958
            if($order_field == 'last_access_on') {
959
                if($order_direction == 'asc') {
558 stevensc 960
                    usort($capsulesData, function($a, $b) {
246 efrain 961
                        return strcasecmp($a['last_access_on'], $b['last_access_on']);
962
                    });
963
                } else {
558 stevensc 964
                    usort($capsulesData, function($a, $b) {
246 efrain 965
                        $result = strcasecmp($a['last_access_on'], $b['last_access_on']);
558 stevensc 966
                        if($result < 0) { return 1; } else if($result > 0) { return -1; } else { return 0; }
246 efrain 967
                    });
968
                }
969
            }
245 efrain 970
 
246 efrain 971
 
119 efrain 972
            return new JsonModel([
973
                'success' => true,
558 stevensc 974
                'data' => $capsulesData
119 efrain 975
            ]);
976
        }
977
 
978
        return new JsonModel([
979
            'success' => false,
980
            'data' => 'ERROR_METHOD_NOT_ALLOWED'
981
        ]);
982
    }
983
 
984
 
985
    public function timelineAction()
986
    {
987
 
988
        $request = $this->getRequest();
989
        if($request->isGet()) {
990
            $currentUserPlugin = $this->plugin('currentUserPlugin');
991
            $currentUser = $currentUserPlugin->getUser();
992
 
993
 
994
            $page = intval($this->params()->fromQuery('page'), 10);
995
 
996
            $activities = [
283 www 997
                MicrolearningUserLog::ACTIVITY_SIGNIN            => 'LABEL_MICROLEARNING_ACTIVITY_SIGNIN',
998
                MicrolearningUserLog::ACTIVITY_SIGNOUT           => 'LABEL_MICROLEARNING_ACTIVITY_SIGNOUT',
999
                MicrolearningUserLog::ACTIVITY_START_TOPIC       => 'LABEL_MICROLEARNING_ACTIVITY_START_TOPIC',
1000
                MicrolearningUserLog::ACTIVITY_START_CAPSULE     => 'LABEL_MICROLEARNING_ACTIVITY_START_CAPSULE',
1001
                MicrolearningUserLog::ACTIVITY_VIEW_SLIDE        => 'LABEL_MICROLEARNING_ACTIVITY_VIEW_SLIDE',
1002
                MicrolearningUserLog::ACTIVITY_TAKE_A_TEST       => 'LABEL_MICROLEARNING_ACTIVITY_TAKE_A_TEST',
1003
                MicrolearningUserLog::ACTIVITY_RETAKE_A_TEST     => 'LABEL_MICROLEARNING_ACTIVITY_RETAKE_A_TEST',
1004
                MicrolearningUserLog::ACTIVITY_APPROVED_TEST     => 'LABEL_MICROLEARNING_ACTIVITY_APPROVED_TEST',
1005
                MicrolearningUserLog::ACTIVITY_COMPLETED_CAPSULE => 'LABEL_MICROLEARNING_ACTIVITY_COMPLETED_CAPSULE',
1006
                MicrolearningUserLog::ACTIVITY_COMPLETED_TOPIC   => 'LABEL_MICROLEARNING_ACTIVITY_COMPLETED_TOPIC',
119 efrain 1007
            ];
1008
 
1009
 
1010
 
283 www 1011
            $microlearningUserLogMapper = MicrolearningUserLogMapper::getInstance($this->adapter);
1012
            $paginator = $microlearningUserLogMapper->getAllMessagesPaginatorByUserId($currentUser->id, $page);
119 efrain 1013
 
1014
            $items = [];
1015
            foreach($paginator as $record)
1016
            {
1017
                $dt = \DateTime::createFromFormat('Y-m-d H:i:s', $record->added_on);
1018
 
1019
                array_push($items, [
1020
                    'activity' => $activities[$record->activity],
1021
                    'added_on' => $dt->format('d/m/Y H:i a')
1022
                ]);
1023
            }
1024
 
1025
 
1026
            return new JsonModel([
1027
                'success' => true,
1028
                'data' => [
1029
                    'total' => [
1030
                        'count' => $paginator->getTotalItemCount(),
1031
                        'pages' => $paginator->getPages()->pageCount,
1032
                    ],
1033
                    'current' => [
1034
                        'items'    => $items,
1035
                        'page'     => $paginator->getCurrentPageNumber(),
1036
                        'count'    => $paginator->getCurrentItemCount(),
1037
                    ]
1038
                ]
1039
            ]);
1040
 
1041
 
1042
        } else {
1043
            return new JsonModel([
1044
                'success' => false,
1045
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
1046
            ]);
1047
        }
1048
    }
1049
 
1050
    /**
1051
     * Valores para la generación de los gráficos de progreso
1052
     * Para las repuesta afirmativa
1053
     * [
1054
     *  'success' => true,
1055
     *      'data' => [
1056
     *          'topicTotal' => cantidad total de tópicos,
1057
     *          'topicStarted' => cantidad de tópicos iniciados,
1058
     *          'topicIncompleted' => cantidad de tópicos incompletos,
1059
     *          'topicCompleted' => cantidad de tópicos completos,
1060
     *          'percentCompleted' => % de diapositivas completados ,
1061
     *          'percentIncompleted' => % de diapositivas incompletos ,
1062
     *          'percentWithoutReturning' => % de cápsulas sin retorno después de completada,
1063
     *          'percentWithReturning' => % de cápsulas con retorno después de completada,
558 stevensc 1064
     *      ],
119 efrain 1065
     * ]
1066
     *
1067
     *
1068
     *  En caso contrario
1069
     *  [
1070
     *      'success' => false,
1071
     *      'data' => mensaje de error
1072
     *  ]
1073
     *
1074
     *
1075
     * @return \Laminas\View\Model\JsonModel
1076
     */
1077
    public function progressAction()
1078
    {
1079
 
1080
        $request = $this->getRequest();
1081
        if($request->isGet()) {
1082
            $currentUserPlugin = $this->plugin('currentUserPlugin');
1083
            $currentUser = $currentUserPlugin->getUser();
1084
 
1085
 
1086
            $accessGrantedIds = $this->getAccessGranted();
1087
            $id = $this->params()->fromRoute('id');
1088
 
1089
            $companyMapper = CompanyMapper::getInstance($this->adapter);
1090
            $company = $companyMapper->fetchOneByUuid($id);
1091
 
1092
            if(!$company) {
1093
                $response = [
1094
                    'success' => false,
1095
                    'data' => 'ERROR_COMPANY_NOT_FOUND',
1096
                ];
1097
 
1098
 
1099
                return new JsonModel($response);
1100
            }
1101
 
1102
            if(!in_array($company->id, $accessGrantedIds->companies)) {
1103
                $response = [
1104
                    'success' => false,
1105
                    'data' => 'ERROR_YOU_DO_NOT_HAVE_ACCESS_TO_THIS_COMPANY',
1106
                ];
1107
 
1108
 
1109
                return new JsonModel($response);
1110
            }
1111
 
1112
            $capsuleTotal              = 0;
1113
            $capsuleCompleted          = 0;
1114
            $capsuleWithReturning      = 0;
1115
            $capsuleWithoutReturning   = 0;
1116
            $capsuleStarted            = 0;
1117
            $capsuleToStart            = 0;
1118
            $percentCompleted          = 0;
1119
            $percentIncompleted        = 100;
1120
 
283 www 1121
            $topicMapper = MicrolearningTopicMapper::getInstance($this->adapter);
119 efrain 1122
            $topics = $topicMapper->fetchAllActiveByCompanyIdAndIds($company->id, $accessGrantedIds->topics);
1123
 
302 www 1124
            //$capsuleMapper = MicrolearningCapsuleMapper::getInstance($this->adapter);
283 www 1125
            $progressMapper = MicrolearningUserProgressMapper::getInstance($this->adapter);
119 efrain 1126
 
302 www 1127
            $topicCapsuleMapper = MicrolearningTopicCapsuleMapper::getInstance($this->adapter);
119 efrain 1128
 
302 www 1129
            //$capsuleUserMapper = MicrolearningCapsuleUserMapper::getInstance($this->adapter);
1130
 
1131
 
119 efrain 1132
            foreach($topics as $topic)
1133
            {
302 www 1134
                $resultCount = $topicCapsuleMapper->fetchCountByCompanyIdAndTopicId($company->id, $topic->id);
119 efrain 1135
                $capsuleTotal =  $capsuleTotal + $resultCount;
1136
 
1137
                $resultCount = $progressMapper->fetchCountCapsulesCompletedByIdAndTopicId($currentUser->id, $topic->id);
1138
                $capsuleCompleted = $capsuleCompleted + $resultCount;
1139
 
1140
                $resultCount = $progressMapper->fetchCountCapsulesCompletedWithReturningByIdAndTopicId($currentUser->id, $topic->id);
1141
                $capsuleWithReturning = $capsuleWithReturning + $resultCount;
1142
 
1143
                $resultCount = $progressMapper->fetchCountCapsulesCompletedWithoutReturningByIdAndTopicId($currentUser->id, $topic->id);
1144
                $capsuleWithoutReturning = $capsuleWithoutReturning + $resultCount;
1145
 
1146
                $resultCount = $progressMapper->fetchCountCapsulesCompletedByIdAndTopicId($currentUser->id, $topic->id);
1147
                $capsuleStarted = $capsuleStarted + $resultCount;
1148
            }
1149
 
1150
            $capsuleToStart = $capsuleTotal -  $capsuleStarted;
1151
 
1152
 
1153
            if($capsuleTotal > 0) {
1154
                $percentCompleted = ($capsuleCompleted * 100) /  $capsuleTotal;
1155
                $percentIncompleted = 100 - $percentCompleted;
1156
            }
1157
 
1158
 
1159
 
1160
            return new JsonModel([
1161
                'success' => true,
1162
                'data' => [
1163
                    'capsuleTotal' => $capsuleTotal,
1164
                    'capsuleCompleted' => $capsuleCompleted,
1165
                    'capsuleStarted' => $capsuleStarted,
1166
                    'capsuleToStart' => $capsuleToStart,
1167
                    'percentCompleted' => number_format($percentCompleted, 2, '.', ','),
1168
                    'percentIncompleted' => number_format($percentIncompleted, 2, '.', ','),
1169
                    'capsuleWithReturning' => $capsuleWithReturning,
1170
                    'capsuleWithoutReturning' => $capsuleWithoutReturning,
1171
                ],
1172
            ]);
1173
 
1174
 
1175
        } else {
1176
            return new JsonModel([
1177
                'success' => false,
1178
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
1179
            ]);
1180
        }
1181
    }
1182
 
1183
 
1184
    public function topicsAction()
1185
    {
1186
        $request = $this->getRequest();
1187
        if($request->isGet()) {
1188
            $currentUserPlugin = $this->plugin('currentUserPlugin');
1189
            $currentUser = $currentUserPlugin->getUser();
1190
 
1191
 
1192
            $data = [];
1193
            $accessGrantedIds = $this->getAccessGranted();
1194
 
283 www 1195
            $userProgressMapper = MicrolearningUserProgressMapper::getInstance($this->adapter);
1196
            $topicMapper = MicrolearningTopicMapper::getInstance($this->adapter);
119 efrain 1197
 
333 www 1198
            $storage = Storage::getInstance($this->config, $this->adapter);
283 www 1199
            $path = $storage->getPathMicrolearningTopic();
119 efrain 1200
 
1201
            foreach($accessGrantedIds->topics as $id)
1202
            {
1203
                $topic = $topicMapper->fetchOne($id);
1204
                if(!$topic) {
1205
                    continue;
1206
                }
1207
 
1208
                $userProgress = $userProgressMapper->fetchOneByUserIdAndTopicId($currentUser->id, $id);
1209
                if($userProgress) {
1210
                    $progress = $userProgress->progress;
1211
                    $completed = $userProgress->completed;
1212
                } else {
1213
                    $progress = 0;
1214
                    $completed = 0;
1215
                }
1216
 
1217
 
1218
 
1219
                array_push($data, [
164 efrain 1220
                    'uuid'          => $topic->uuid,
119 efrain 1221
                    'name'          => $topic->name ? $topic->name : '',
1222
                    'description'   => $topic->description ? $topic->description : '',
283 www 1223
                    'image'         => $topic->image ? $storage->getGenericImage($path, $topic->uuid, $topic->image) : '',
119 efrain 1224
                    'progress'      => $progress,
1225
                    'completed'     => $completed,
1226
                    'order'         => $topic->order,
1227
                    'added_on'      => $topic->added_on,
564 stevensc 1228
                    'updated_on'    => $topic->updated_on
119 efrain 1229
                ]);
1230
            }
1231
 
1232
            usort($data, function($a, $b) {
1233
 
1234
                $result =  $a['order'] <=> $b['order'];
1235
                if(0 == $result) {
1236
                    $result = strcasecmp($a['added_on'], $b['added_on']);
1237
                    if(0 == $result) {
1238
                        $result = strcasecmp($a['name'], $b['name']);
1239
                    }
1240
                }
1241
 
1242
                if($result < 0) {
1243
                    return 1;
1244
                } else if($result > 0) {
1245
                    return -1;
1246
                } else  {
1247
                    return  0;
1248
                }
1249
            });
1250
 
1251
 
1252
 
1253
                return new JsonModel([
1254
                    'success' => true,
1255
                    'data' => $data
1256
                ]);
1257
 
1258
        } else {
1259
            return new JsonModel([
1260
                'success' => false,
1261
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
1262
            ]);
1263
        }
1264
    }
1265
 
161 efrain 1266
    public function getTopicAction()
1267
    {
563 stevensc 1268
        // Handle GET request
161 efrain 1269
        $request = $this->getRequest();
1270
        if($request->isGet()) {
563 stevensc 1271
            // Get current user
161 efrain 1272
            $currentUserPlugin = $this->plugin('currentUserPlugin');
1273
            $currentUser = $currentUserPlugin->getUser();
563 stevensc 1274
 
1275
            // Get topic ID from route
161 efrain 1276
            $id = $this->params()->fromRoute('id');
283 www 1277
            $topicMapper = MicrolearningTopicMapper::getInstance($this->adapter);
161 efrain 1278
            $topic = $topicMapper->fetchOneByUuid($id);
563 stevensc 1279
 
1280
            // Return error if topic not found
161 efrain 1281
            if(!$topic) {
1282
                return new JsonModel([
1283
                    'success' => false,
1284
                    'data' => 'ERROR_TOPIC_NOT_FOUND'
1285
                ]);
1286
            }
563 stevensc 1287
 
1288
            // Check if current user has access to the topic
161 efrain 1289
            $accessGrantedIds = $this->getAccessGranted();
1290
            if(!in_array($topic->id, $accessGrantedIds->topics)) {
1291
                return new JsonModel([
1292
                    'success' => false,
1293
                    'data' => 'ERROR_YOU_DO_NOT_HAVE_ACCESS_TO_THIS_TOPIC'
1294
                ]);
1295
            }
563 stevensc 1296
 
1297
            // Get user progress for this topic
283 www 1298
            $userProgressMapper = MicrolearningUserProgressMapper::getInstance($this->adapter);
563 stevensc 1299
            $userProgress = $userProgressMapper->fetchOneByUserIdAndTopicId($currentUser->id, $topic->id);
161 efrain 1300
 
580 stevensc 1301
            $progress = $userProgress->progress ?? 0;
1302
            $completed = $userProgress->completed ?? 0;
563 stevensc 1303
 
1304
            // Initialize storage service to get image paths
333 www 1305
            $storage = Storage::getInstance($this->config, $this->adapter);
563 stevensc 1306
            $pathTopic = $storage->getPathMicrolearningTopic();
1307
 
1308
            // Fetch associated capsules using the private helper method
1309
            $capsulesData = $this->_getCapsulesByTopic($topic, $storage);
1310
 
1311
            // Prepare data for JSON response
161 efrain 1312
            $data = [
165 efrain 1313
                'uuid'          => $topic->uuid,
161 efrain 1314
                'name'          => $topic->name ? $topic->name : '',
1315
                'description'   => $topic->description ? $topic->description : '',
563 stevensc 1316
                'image'         => $topic->image ? $storage->getGenericImage($pathTopic, $topic->uuid, $topic->image) : '',
161 efrain 1317
                'progress'      => $progress,
1318
                'completed'     => $completed,
1319
                'order'         => $topic->order,
1320
                'added_on'      => $topic->added_on,
1321
                'updated_on'    => $topic->updated_on,
563 stevensc 1322
                'total_capsules' => count($capsulesData),
1323
                'capsules'      => $capsulesData,
161 efrain 1324
            ];
563 stevensc 1325
 
161 efrain 1326
            return new JsonModel([
1327
                'success' => true,
1328
                'data' => $data
1329
            ]);
563 stevensc 1330
 
161 efrain 1331
        } else {
563 stevensc 1332
            // Return error if not a GET request
161 efrain 1333
            return new JsonModel([
1334
                'success' => false,
1335
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
1336
            ]);
1337
        }
1338
    }
563 stevensc 1339
 
1340
    /**
580 stevensc 1341
     * @param MicrolearningTopic $topic The topic object.
1342
     * @param Storage $storage The storage object.
1343
     * @return array The capsules data.
563 stevensc 1344
     */
1345
    private function _getCapsulesByTopic($topic, $storage)
1346
    {
578 stevensc 1347
        $data = [];
584 stevensc 1348
        $accessGrantedIds = $this->getAccessGranted();
563 stevensc 1349
 
578 stevensc 1350
        if (!$topic) {
1351
            return $data;
1352
        }
1353
 
584 stevensc 1354
        if (!in_array($topic->id, $accessGrantedIds->topics)) {
578 stevensc 1355
            return $data;
584 stevensc 1356
        }
578 stevensc 1357
 
1358
        $currentUserPlugin = $this->plugin('currentUserPlugin');
1359
        $currentUser = $currentUserPlugin->getUser();
1360
 
1361
        $topicCapsuleMapper = MicrolearningTopicCapsuleMapper::getInstance($this->adapter);
574 stevensc 1362
        $topicCapsuleRelations = $topicCapsuleMapper->fetchAllActiveByTopicId($topic->id);
1363
 
581 stevensc 1364
        $userProgressMapper = MicrolearningUserProgressMapper::getInstance($this->adapter);
1365
        $capsuleCommentMapper = MicrolearningCapsuleCommentMapper::getInstance($this->adapter);
578 stevensc 1366
 
581 stevensc 1367
        $path = $storage->getPathMicrolearningCapsule();
1368
 
578 stevensc 1369
        foreach ($topicCapsuleRelations as $relation) {
584 stevensc 1370
            if(!in_array($relation->capsule_id, $accessGrantedIds->capsules)) {
1371
                continue;
1372
            }
578 stevensc 1373
 
581 stevensc 1374
            $capsuleMapper = MicrolearningCapsuleMapper::getInstance($this->adapter);
1375
            $capsule = $capsuleMapper->fetchOne($relation->capsule_id);
563 stevensc 1376
 
581 stevensc 1377
            if(!$capsule) {
1378
                continue;
1379
            }
1380
 
578 stevensc 1381
            $userProgress = $userProgressMapper->fetchOneByUseridAndCapsuleId($currentUser->id, $capsule->id);
1382
            $progress = $userProgress->progress ?? 0;
1383
            $completed = $userProgress->completed ?? 0;
1384
            $dataCountAndRatingAverage = $capsuleCommentMapper->fetchCountAndRatingAverage($capsule->company_id, $capsule->id);
1385
            $image = $capsule->image ? $storage->getGenericImage($path, $capsule->uuid, $capsule->image) : '';
1386
            $total_comments = strval($dataCountAndRatingAverage['total_comments']);
1387
            $total_rating = strval($dataCountAndRatingAverage['total_rating']);
1388
 
581 stevensc 1389
            array_push($data, [
578 stevensc 1390
                'uuid'              => $capsule->uuid,
1391
                'name'              => $capsule->name ? $capsule->name : '',
1392
                'description'       => $capsule->description ? $capsule->description : '',
1393
                'image'             => $image,
1394
                'total_comments'    => $total_comments,
1395
                'total_rating'      => $total_rating,
1396
                'progress'          => $progress,
1397
                'completed'         => $completed,
1398
                'order'             => $capsule->order,
1399
                'added_on'          => $capsule->added_on,
1400
                'updated_on'        => $capsule->updated_on,
581 stevensc 1401
            ]);
563 stevensc 1402
        }
578 stevensc 1403
 
581 stevensc 1404
        return $data;
563 stevensc 1405
    }
119 efrain 1406
 
1407
    public function capsulesAction()
1408
    {
1409
        $request = $this->getRequest();
1410
        if($request->isGet()) {
580 stevensc 1411
            $currentUserPlugin = $this->plugin('currentUserPlugin');
1412
            $currentUser = $currentUserPlugin->getUser();
584 stevensc 1413
 
1414
            $topic_id_param = $this->params()->fromRoute('topic_id');
283 www 1415
            $topicMapper = MicrolearningTopicMapper::getInstance($this->adapter);
580 stevensc 1416
            $topic = $topicMapper->fetchOneByUuid($topic_id_param);
584 stevensc 1417
 
119 efrain 1418
            if(!$topic) {
1419
                return new JsonModel([
1420
                    'success' => false,
1421
                    'data' => 'ERROR_TOPIC_NOT_FOUND'
1422
                ]);
1423
            }
584 stevensc 1424
 
580 stevensc 1425
            $accessGrantedIds = $this->getAccessGranted();
584 stevensc 1426
 
119 efrain 1427
            if(!in_array($topic->id, $accessGrantedIds->topics)) {
1428
                return new JsonModel([
1429
                    'success' => false,
1430
                    'data' => 'ERROR_YOU_DO_NOT_HAVE_ACCESS_TO_THIS_TOPIC'
1431
                ]);
1432
            }
584 stevensc 1433
 
333 www 1434
            $storage = Storage::getInstance($this->config, $this->adapter);
584 stevensc 1435
            // Use the _getCapsulesByTopic method to fetch capsules
1436
            $data = $this->_getCapsulesByTopic($topic, $storage);
580 stevensc 1437
 
584 stevensc 1438
            // The _getCapsulesByTopic method already returns capsules with the required data structure.
1439
            // We just need to sort them.
1440
 
580 stevensc 1441
            usort($data, function($a, $b) {
584 stevensc 1442
 
580 stevensc 1443
                $result =  $a['order'] <=> $b['order'];
1444
                if(0 == $result) {
1445
                    $result = strcasecmp($a['added_on'], $b['added_on']);
1446
                    if(0 == $result) {
1447
                        $result = strcasecmp($a['name'], $b['name']);
1448
                    }
1449
                }
584 stevensc 1450
 
580 stevensc 1451
                if($result < 0) {
1452
                    return 1;
1453
                } else if($result > 0) {
1454
                    return -1;
1455
                } else  {
1456
                    return  0;
1457
                }
1458
            });
584 stevensc 1459
 
1460
            return new JsonModel([
1461
                'success' => true,
1462
                'data' => $data
1463
            ]);
1464
 
119 efrain 1465
        } else {
1466
            return new JsonModel([
1467
                'success' => false,
1468
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
1469
            ]);
1470
        }
1471
    }
1472
 
235 efrain 1473
    public function takeTestAction()
1474
    {
1475
        $request = $this->getRequest();
1476
        if($request->isPost()) {
1477
            $currentUserPlugin = $this->plugin('currentUserPlugin');
1478
            $currentUser = $currentUserPlugin->getUser();
1479
 
1480
            $slide_id = $this->params()->fromRoute('slide_id');
283 www 1481
            $slideMapper = MicrolearningSlideMapper::getInstance($this->adapter);
235 efrain 1482
            $slide = $slideMapper->fetchOneByUuid($slide_id);
1483
 
1484
            if(!$slide) {
1485
                return new JsonModel([
1486
                    'success' => false,
1487
                    'data' => 'ERROR_SLIDE_NOT_FOUND'
1488
                ]);
1489
            }
1490
 
283 www 1491
            if($slide->type != MicrolearningSlide::TYPE_QUIZ) {
235 efrain 1492
                return new JsonModel([
1493
                    'success' => false,
1494
                    'data' => 'ERROR_SLIDE_IS_NOT_QUIZ'
1495
                ]);
1496
            }
1497
 
1498
 
1499
 
283 www 1500
            $capsuleMapper = MicrolearningCapsuleMapper::getInstance($this->adapter);
235 efrain 1501
            $capsule = $capsuleMapper->fetchOne($slide->capsule_id);
1502
 
1503
            if(!$capsule) {
1504
                return new JsonModel([
1505
                    'success' => false,
1506
                    'data' => 'ERROR_CAPSULE_NOT_FOUND'
1507
                ]);
1508
            }
1509
 
1510
            $accessGrantedIds = $this->getAccessGranted();
1511
 
1512
            if(!in_array($capsule->id, $accessGrantedIds->capsules)) {
1513
                return new JsonModel([
1514
                    'success' => false,
1515
                    'data' => 'ERROR_YOU_DO_NOT_HAVE_ACCESS_TO_THIS_CAPSULE'
1516
                ]);
1517
            }
1518
 
283 www 1519
            $userLogMapper = MicrolearningUserLogMapper::getInstance($this->adapter);
235 efrain 1520
            $userLog = $userLogMapper->fetchOneTakeATestByUserIdAndSlideId($currentUser->id, $slide->id);
1521
 
1522
            if($userLog) {
283 www 1523
                $activity = MicrolearningUserLog::ACTIVITY_RETAKE_A_TEST;
235 efrain 1524
            } else {
283 www 1525
                $activity = MicrolearningUserLog::ACTIVITY_TAKE_A_TEST;
235 efrain 1526
            }
1527
 
1528
            $added_on = $userLogMapper->getDatebaseNow();
1529
 
283 www 1530
            $userLog = new MicrolearningUserLog();
235 efrain 1531
            $userLog->activity      = $activity;
1532
            $userLog->user_id       = $currentUser->id;
1533
            $userLog->company_id    = $slide->company_id;
1534
            $userLog->topic_id      = $slide->topic_id;
1535
            $userLog->capsule_id    = $slide->capsule_id;
1536
            $userLog->slide_id      = $slide->id;
1537
            $userLog->added_on      = $added_on;
1538
 
1539
            if($userLogMapper->insert($userLog)) {
1540
                return new JsonModel([
1541
                    'success' => true,
1542
                ]);
1543
            } else {
1544
                return new JsonModel([
1545
                    'success' => false,
1546
                    'data' => $userLogMapper->getError()
1547
                ]);
1548
            }
1549
 
1550
 
1551
 
1552
 
1553
 
1554
 
1555
 
1556
        } else {
1557
            return new JsonModel([
1558
                'success' => false,
1559
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
1560
            ]);
1561
        }
1562
    }
1563
 
161 efrain 1564
    public function getCapsuleAction()
1565
    {
1566
        $request = $this->getRequest();
1567
        if($request->isGet()) {
1568
            $currentUserPlugin = $this->plugin('currentUserPlugin');
1569
            $currentUser = $currentUserPlugin->getUser();
1570
 
1571
 
1572
 
558 stevensc 1573
            $capsule_uuid = $this->params()->fromRoute('id');
283 www 1574
            $capsuleMapper = MicrolearningCapsuleMapper::getInstance($this->adapter);
558 stevensc 1575
            $capsule = $capsuleMapper->fetchOneByUuid($capsule_uuid);
161 efrain 1576
 
1577
            if(!$capsule) {
1578
                return new JsonModel([
1579
                    'success' => false,
1580
                    'data' => 'ERROR_CAPSULE_NOT_FOUND'
1581
                ]);
1582
            }
1583
 
1584
            $accessGrantedIds = $this->getAccessGranted();
1585
 
558 stevensc 1586
            // Verificar si el usuario tiene acceso a esta cápsula específica
161 efrain 1587
            if(!in_array($capsule->id, $accessGrantedIds->capsules)) {
1588
                return new JsonModel([
1589
                    'success' => false,
1590
                    'data' => 'ERROR_YOU_DO_NOT_HAVE_ACCESS_TO_THIS_CAPSULE'
1591
                ]);
1592
            }
1593
 
558 stevensc 1594
            // --- Obtener el Tópico asociado (si existe y es necesario) ---
1595
            $topic = null;
1596
            $topic_uuid_for_links = null; // UUID del tópico para construir enlaces
1597
            $topicCapsuleMapper = MicrolearningTopicCapsuleMapper::getInstance($this->adapter);
1598
            // Asumiendo que una cápsula puede estar asociada a múltiples tópicos (muchos-a-muchos),
1599
            // necesitamos decidir cuál tópico usar como contexto aquí. Usaremos el primero que encontremos.
1600
            // 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).
1601
            $relation = $topicCapsuleMapper->fetchOneByCapsuleId($capsule->id); // Necesitamos un método como este
1602
 
1603
            if ($relation && in_array($relation->topic_id, $accessGrantedIds->topics)) {
1604
                $topicMapper = MicrolearningTopicMapper::getInstance($this->adapter);
1605
                $topic = $topicMapper->fetchOne($relation->topic_id);
1606
                if ($topic) {
1607
                    $topic_uuid_for_links = $topic->uuid;
1608
                }
1609
            }
1610
            // Si no se encontró un tópico asociado o el usuario no tiene acceso a él,
1611
            // algunos enlaces podrían no generarse o la lógica necesitaría ajustarse.
1612
            // Por ahora, si no hay $topic_uuid_for_links, el link_slides será inválido.
1613
            // --------------------------------------------------------------
161 efrain 1614
 
1615
 
283 www 1616
            $userProgressMapper = MicrolearningUserProgressMapper::getInstance($this->adapter);
1617
            $capsuleCommentMapper = MicrolearningCapsuleCommentMapper::getInstance($this->adapter);
161 efrain 1618
 
1619
 
1620
 
1621
            $userProgress = $userProgressMapper->fetchOneByUseridAndCapsuleId($currentUser->id, $capsule->id);
1622
            if($userProgress) {
1623
                $progress = $userProgress->progress;
1624
                $completed = $userProgress->completed;
1625
            } else {
1626
                $progress = 0;
1627
                $completed = 0;
1628
            }
1629
 
302 www 1630
            $dataCountAndRatingAverage = $capsuleCommentMapper->fetchCountAndRatingAverage($capsule->company_id,  $capsule->id);
161 efrain 1631
 
244 efrain 1632
 
283 www 1633
            $slideMapper = MicrolearningSlideMapper::getInstance($this->adapter);
558 stevensc 1634
            // Para contar slides, necesitamos el contexto del tópico.
1635
            $totalSlides = 0;
1636
            if ($topic) { // Solo contar si tenemos un tópico asociado válido
1637
                $totalSlides = $slideMapper->fetchTotalCountByCompanyIdAndTopicIdAndCapsuleId($capsule->company_id, $topic->id, $capsule->id);
1638
            }
244 efrain 1639
 
1640
 
558 stevensc 1641
            $link_first_slide = '';
1642
            $type_first_slide = '';
1643
            if ($topic) { // Solo buscar primer slide si tenemos tópico
1644
                $slide = $slideMapper->fetchFirstByCompanyIdAndTopicIdAndCapsuleId($capsule->company_id, $topic->id, $capsule->id);
1645
                if($slide) {
1646
                    $link_first_slide = $this->url()->fromRoute('microlearning/get-slide', ['id' => $slide->uuid], ['force_canonical' => true]);
1647
                    $type_first_slide = $slide->type;
1648
                }
244 efrain 1649
            }
1650
 
333 www 1651
            $storage = Storage::getInstance($this->config, $this->adapter);
283 www 1652
            $path = $storage->getPathMicrolearningCapsule();
244 efrain 1653
 
1654
 
558 stevensc 1655
            // Construir enlaces usando $topic_uuid_for_links si está disponible
1656
            $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 1657
 
161 efrain 1658
            $data = [
164 efrain 1659
                    'uuid'              => $capsule->uuid,
161 efrain 1660
                    'name'              => $capsule->name ? $capsule->name : '',
1661
                    'description'       => $capsule->description ? $capsule->description : '',
283 www 1662
                    'image'             => $capsule->image ? $storage->getGenericImage($path, $capsule->uuid, $capsule->image)  : '',
161 efrain 1663
                    'link_comments'     => $this->url()->fromRoute('microlearning/capsules-comments', ['capsule_id' => $capsule->uuid], ['force_canonical' => true]),
1664
                    'link_comment_add'  => $this->url()->fromRoute('microlearning/capsules-comments/add', ['capsule_id' => $capsule->uuid],['force_canonical' => true]),
558 stevensc 1665
                    'link_slides'       => $link_slides, // Usar el enlace construido
161 efrain 1666
                    'total_comments'    => strval($dataCountAndRatingAverage['total_comments']),
1667
                    'total_rating'      => strval($dataCountAndRatingAverage['total_rating']),
1668
                    'progress'          => $progress,
1669
                    'completed'         => $completed,
245 efrain 1670
                    'total_slides'      => $totalSlides,
244 efrain 1671
                    'link_first_slide'  => $link_first_slide,
1672
                    'type_first_slide'  => $type_first_slide,
161 efrain 1673
                    'order'             => $capsule->order,
1674
                    'added_on'          => $capsule->added_on,
1675
                    'updated_on'        => $capsule->updated_on,
1676
            ];
1677
 
1678
 
1679
 
1680
            return new JsonModel([
1681
                'success' => true,
1682
                'data' => $data
1683
            ]);
1684
 
1685
        } else {
1686
            return new JsonModel([
1687
                'success' => false,
1688
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
1689
            ]);
1690
        }
1691
    }
1692
 
119 efrain 1693
    public function slidesAction()
1694
    {
1695
        $request = $this->getRequest();
1696
        if($request->isGet()) {
1697
            $currentUserPlugin = $this->plugin('currentUserPlugin');
1698
            $currentUser = $currentUserPlugin->getUser();
1699
 
1700
 
1701
 
1702
            $topic_id = $this->params()->fromRoute('topic_id');
283 www 1703
            $topicMapper = MicrolearningTopicMapper::getInstance($this->adapter);
119 efrain 1704
            $topic = $topicMapper->fetchOneByUuid($topic_id);
1705
 
1706
            if(!$topic) {
1707
                return new JsonModel([
1708
                    'success' => false,
1709
                    'data' => 'ERROR_TOPIC_NOT_FOUND'
1710
                ]);
1711
            }
1712
 
1713
            $accessGrantedIds = $this->getAccessGranted();
1714
 
1715
            if(!in_array($topic->id, $accessGrantedIds->topics)) {
1716
                return new JsonModel([
1717
                    'success' => false,
1718
                    'data' => 'ERROR_YOU_DO_NOT_HAVE_ACCESS_TO_THIS_TOPIC'
1719
                ]);
1720
            }
1721
 
1722
            $capsule_id = $this->params()->fromRoute('capsule_id');
283 www 1723
            $capsuleMapper = MicrolearningCapsuleMapper::getInstance($this->adapter);
119 efrain 1724
            $capsule = $capsuleMapper->fetchOneByUuid($capsule_id);
1725
 
1726
            if(!$capsule) {
1727
                return new JsonModel([
1728
                    'success' => false,
1729
                    'data' => 'ERROR_CAPSULE_NOT_FOUND'
1730
                ]);
1731
            }
1732
 
1733
 
1734
 
1735
            if(!in_array($capsule->id, $accessGrantedIds->capsules)) {
1736
                return new JsonModel([
1737
                    'success' => false,
1738
                    'data' => 'ERROR_YOU_DO_NOT_HAVE_ACCESS_TO_THIS_CAPSULE'
1739
                ]);
1740
            }
1741
 
1742
 
1743
 
1744
            $data = [];
1745
 
283 www 1746
            $quizMapper = MicrolearningQuizMapper::getInstance($this->adapter);
119 efrain 1747
 
283 www 1748
            $slideMapper = MicrolearningSlideMapper::getInstance($this->adapter);
1749
            $userProgressMapper = MicrolearningUserProgressMapper::getInstance($this->adapter);
119 efrain 1750
 
333 www 1751
            $storage = Storage::getInstance($this->config, $this->adapter);
283 www 1752
            $path = $storage->getPathMicrolearningSlide();
119 efrain 1753
 
1754
            $slides = $slideMapper->fetchAllByCompanyIdAndTopicIdAndCapsuleId($capsule->company_id, $capsule->topic_id, $capsule->id);
1755
            foreach($slides as $slide)
1756
            {
1757
 
1758
 
1759
                $userProgress = $userProgressMapper->fetchOneByUserIdAndSlideId($currentUser->id, $slide->id);
1760
                if($userProgress) {
224 efrain 1761
                    $completed =  $userProgress->completed ;
119 efrain 1762
                } else {
1763
                    $completed = 0;
1764
                }
1765
 
235 efrain 1766
 
230 efrain 1767
 
235 efrain 1768
                $link_take_a_test = '';
230 efrain 1769
                if($slide->quiz_id) {
235 efrain 1770
 
283 www 1771
                    $quizMapper = MicrolearningQuizMapper::getInstance($this->adapter);
230 efrain 1772
                    $quiz = $quizMapper->fetchOne($slide->quiz_id);
1773
                    if($quiz) {
1774
                        $quiz_uuid = $quiz->uuid;
235 efrain 1775
                        $quiz_data = $this->getQuiz($slide->quiz_id);
1776
                        $link_take_a_test = $this->url()->fromRoute('microlearning/take-a-test', ['slide_id' => $slide->uuid], ['force_canonical' => true]);
230 efrain 1777
                    }
235 efrain 1778
 
1779
                }
119 efrain 1780
 
1781
 
1782
                array_push($data, [
235 efrain 1783
                    'quiz'                  => $quiz_uuid,
1784
                    'quiz_data'             => $quiz_data,
1785
                    'uuid'                  => $slide->uuid,
1786
                    'name'                  => $slide->name ? $slide->name : '',
1787
                    'description'           => $slide->description ? $slide->description : '',
1788
                    'type'                  => $slide->type,
283 www 1789
                    'background'            => $slide->background ? $storage->getGenericImage($path, $slide->uuid, $slide->background) : '',
1790
                    'file'                  => $slide->file ? $storage->getGenericFile($path, $slide->uuid, $slide->file) : '',
235 efrain 1791
                    'order'                 => $slide->order,
1792
                    'completed'             => $completed,
1793
                    'link_get'              => $this->url()->fromRoute('microlearning/get-slide', ['id' => $slide->uuid], ['force_canonical' => true]),
1794
                    '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 1795
                    'link_take_a_test'      => $link_take_a_test,
235 efrain 1796
                    'added_on'              => $slide->added_on,
1797
                    'updated_on'            => $slide->updated_on,
119 efrain 1798
                ]);
1799
 
1800
 
1801
 
1802
            }
1803
 
1804
            usort($data, function($a, $b) {
1805
 
1806
                $result =  $a['order'] <=> $b['order'];
1807
                if(0 == $result) {
1808
                    $result = strcasecmp($a['added_on'], $b['added_on']);
1809
                    if(0 == $result) {
1810
                        $result = strcasecmp($a['name'], $b['name']);
1811
                    }
1812
                }
1813
 
1814
                if($result < 0) {
1815
                    return 1;
1816
                } else if($result > 0) {
1817
                    return -1;
1818
                } else  {
1819
                    return  0;
1820
                }
1821
            });
1822
 
1823
 
1824
 
1825
                return new JsonModel([
1826
                    'success' => true,
1827
                    'data' => $data
1828
                ]);
1829
 
1830
        } else {
1831
            return new JsonModel([
1832
                'success' => false,
1833
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
1834
            ]);
1835
        }
1836
    }
1837
 
229 efrain 1838
    private function getQuiz($id)
1839
    {
1840
        $serviceDatetimeFormat = $this->config['leaderslinked.services.datetime'];
1841
 
1842
        $data = [];
1843
 
283 www 1844
        $quizMapper = MicrolearningQuizMapper::getInstance($this->adapter);
229 efrain 1845
        $quiz = $quizMapper->fetchOne($id);
1846
 
1847
        if(!$quiz) {
1848
            return [];
1849
        }
1850
 
1851
        $companyMapper = CompanyMapper::getInstance($this->adapter);
1852
        $company = $companyMapper->fetchOne($quiz->company_id);
1853
 
283 www 1854
        $questionMapper = MicrolearningQuestionMapper::getInstance($this->adapter);
1855
        $answerMapper = MicrolearningAnswerMapper::getInstance($this->adapter);
229 efrain 1856
 
1857
        $record_questions = [];
1858
        $questions = $questionMapper->fetchAllByQuizId($quiz->id);
1859
        foreach($questions as $question)
1860
        {
1861
            $record_answers = [];
1862
 
1863
            $answers = $answerMapper->fetchAllByQuizIdAndQuestionId($question->quiz_id, $question->id);
1864
            foreach($answers as $answer)
1865
            {
1866
                $dtAddedOn = \DateTime::createFromFormat('Y-m-d H:i:s', $answer->added_on);
1867
                $dtUpdatedOn = \DateTime::createFromFormat('Y-m-d H:i:s', $answer->updated_on);
1868
 
1869
                array_push($record_answers, [
1870
                    'uuid' => $answer->uuid,
1871
                    'text' => trim($answer->text),
1872
                    'correct' => $answer->correct ? $answer->correct  : 0 ,
1873
                    'points' => strval(intval($answer->points, 10)),
1874
                    'added_on'  => $dtAddedOn->format($serviceDatetimeFormat),
1875
                    'updated_on'    => $dtUpdatedOn->format($serviceDatetimeFormat),
1876
                ]);
1877
            }
1878
 
1879
            $dtAddedOn = \DateTime::createFromFormat('Y-m-d H:i:s', $question->added_on);
1880
            $dtUpdatedOn = \DateTime::createFromFormat('Y-m-d H:i:s', $question->updated_on);
1881
 
1882
            array_push($record_questions, [
1883
                'uuid'          => $question->uuid,
1884
                'text'          => trim($question->text),
1885
                'type'          => $question->type,
1886
                'maxlength'     => strval($question->maxlength),
1887
                'points'        => strval($question->points),
1888
                'answers'       => $record_answers,
1889
                'added_on'      => $dtAddedOn->format($serviceDatetimeFormat),
1890
                'updated_on'    => $dtUpdatedOn->format($serviceDatetimeFormat),
1891
            ]);
1892
        }
1893
 
1894
        $dtAddedOn = \DateTime::createFromFormat('Y-m-d H:i:s', $quiz->added_on);
1895
        $dtUpdatedOn = \DateTime::createFromFormat('Y-m-d H:i:s', $quiz->updated_on);
1896
 
1897
        array_push($data, [
1898
            'uuid' => $quiz->uuid,
1899
            'name' => $quiz->name,
1900
            'text' => trim($quiz->text ? $quiz->text : ''),
1901
            'failed' => trim($quiz->failed ? $quiz->failed : ''),
1902
            'points' => strval($quiz->points),
1903
            'minimum_points_required' => strval($quiz->minimum_points_required),
1904
            'max_time' => $quiz->max_time ? $quiz->max_time : 5,
1905
            'company_uuid' => $company->uuid,
1906
            'company_name' => $company->name,
1907
            'company_image' => $this->url()->fromRoute('services/storage',['type' => 'company', 'code' => $company->uuid, 'filename' => $company->image], ['force_canonical' => true]),
1908
            'questions'     => $record_questions,
1909
            'added_on'      => $dtAddedOn->format($serviceDatetimeFormat),
1910
            'updated_on'    => $dtUpdatedOn->format($serviceDatetimeFormat),
1911
        ]);
1912
 
1913
        return $data;
1914
 
1915
    }
161 efrain 1916
 
229 efrain 1917
 
161 efrain 1918
    public function getSlideAction()
1919
    {
1920
        $request = $this->getRequest();
1921
        if($request->isGet()) {
1922
            $currentUserPlugin = $this->plugin('currentUserPlugin');
1923
            $currentUser = $currentUserPlugin->getUser();
1924
 
1925
 
1926
 
1927
            $id = $this->params()->fromRoute('id');
283 www 1928
            $slideMapper = MicrolearningSlideMapper::getInstance($this->adapter);
161 efrain 1929
            $slide = $slideMapper->fetchOneByUuid($id);
1930
 
1931
            if(!$slide) {
1932
                return new JsonModel([
1933
                    'success' => false,
1934
                    'data' => 'ERROR_SLIDE_NOT_FOUND'
1935
                ]);
1936
            }
1937
 
1938
            $accessGrantedIds = $this->getAccessGranted();
1939
 
1940
 
1941
 
1942
            if(!in_array($slide->capsule_id, $accessGrantedIds->capsules)) {
1943
                return new JsonModel([
1944
                    'success' => false,
1945
                    'data' => 'ERROR_YOU_DO_NOT_HAVE_ACCESS_TO_THIS_CAPSULE'
1946
                ]);
1947
            }
1948
 
1949
 
283 www 1950
            $topicMapper = MicrolearningTopicMapper::getInstance($this->adapter);
161 efrain 1951
            $topic = $topicMapper->fetchOne($slide->topic_id);
1952
 
283 www 1953
            $capsuleMapper =  MicrolearningCapsuleMapper::getInstance($this->adapter);
161 efrain 1954
            $capsule = $capsuleMapper->fetchOne($slide->capsule_id);
1955
 
1956
 
1957
 
1958
 
1959
 
283 www 1960
            $slideMapper = MicrolearningSlideMapper::getInstance($this->adapter);
1961
            $userProgressMapper = MicrolearningUserProgressMapper::getInstance($this->adapter);
161 efrain 1962
 
1963
 
1964
            $userProgress = $userProgressMapper->fetchOneByUserIdAndSlideId($currentUser->id, $slide->id);
1965
            if($userProgress) {
1966
                $completed = $userProgress->completed;
1967
            } else {
1968
                $completed = 0;
1969
            }
235 efrain 1970
 
1971
            $quiz_uuid = '';
1972
            $quiz_data = [];
1973
            $link_take_a_test = '';
1974
            if($slide->quiz_id) {
1975
 
283 www 1976
                $quizMapper = MicrolearningQuizMapper::getInstance($this->adapter);
235 efrain 1977
                $quiz = $quizMapper->fetchOne($slide->quiz_id);
1978
                if($quiz) {
1979
                    $quiz_uuid = $quiz->uuid;
1980
                    $quiz_data = $this->getQuiz($slide->quiz_id);
1981
                    $link_take_a_test = $this->url()->fromRoute('microlearning/take-a-test', ['slide_id' => $slide->uuid], ['force_canonical' => true]);
1982
                }
161 efrain 1983
 
235 efrain 1984
            }
161 efrain 1985
 
333 www 1986
            $storage = Storage::getInstance($this->config, $this->adapter);
283 www 1987
            $path = $storage->getPathMicrolearningSlide();
161 efrain 1988
 
1989
            $data =[
235 efrain 1990
                'quiz'              => $quiz_uuid,
1991
                'quiz_data'         => $quiz_data,
1992
                'uuid'              => $slide->uuid,
1993
                'name'              => $slide->name ? $slide->name : '',
1994
                'description'       => $slide->description ? $slide->description : '',
1995
                'type'              => $slide->type,
283 www 1996
                'background'        => $slide->background ? $storage->getGenericImage($path, $slide->uuid, $slide->background) : '',
1997
                'file'              => $slide->file ? $storage->getGenericFile($path, $slide->uuid, $slide->file) : '',
235 efrain 1998
                'order'             => $slide->order,
1999
                'completed'         => $completed,
2000
                '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]),
2001
                'link_take_a_test'  => $link_take_a_test,
2002
                'added_on'          => $slide->added_on,
2003
                'updated_on'        => $slide->updated_on,
161 efrain 2004
            ];
2005
 
2006
 
2007
 
2008
 
2009
            return new JsonModel([
2010
                'success' => true,
2011
                'data' => $data
2012
            ]);
2013
 
2014
        } else {
2015
            return new JsonModel([
2016
                'success' => false,
2017
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
2018
            ]);
2019
        }
2020
    }
2021
 
119 efrain 2022
    public function profileAction()
2023
    {
2024
        $request = $this->getRequest();
2025
        if($request->isGet()) {
2026
            $currentUserPlugin = $this->plugin('currentUserPlugin');
2027
            $currentUser = $currentUserPlugin->getUser();
2028
 
2029
 
2030
            $accessGrantedIds = $this->getAccessGranted();
2031
 
2032
            $companyMapper = CompanyMapper::getInstance($this->adapter);
283 www 2033
            $companyExtendUserMapper = MicrolearningExtendUserMapper::getInstance($this->adapter);
2034
            $companyExtendUserCompanyMapper = MicrolearningExtendUserCompanyMapper::getInstance($this->adapter);
2035
            $companyExtendUserFunctionMapper = MicrolearningExtendUserFunctionMapper::getInstance($this->adapter);
2036
            $companyExtendUserGroupMapper = MicrolearningExtendUserGroupMapper::getInstance($this->adapter);
2037
            $companyExtendUserInstitutionMapper = MicrolearningExtendUserInstitutionMapper::getInstance($this->adapter);
2038
            $companyExtendUserPartnerMapper = MicrolearningExtendUserPartnerMapper::getInstance($this->adapter);
2039
            $companyExtendUserProgramMapper = MicrolearningExtendUserProgramMapper::getInstance($this->adapter);
2040
            $companyExtendUserStudentTypeMapper = MicrolearningExtendUserStudentTypeMapper::getInstance($this->adapter);
2041
            $companyExtendUserSectorMapper = MicrolearningExtendUserSectorMapper::getInstance($this->adapter);
119 efrain 2042
 
333 www 2043
            $storage = Storage::getInstance($this->config, $this->adapter);
283 www 2044
 
119 efrain 2045
 
2046
            $data = [];
2047
            foreach($accessGrantedIds->companies as $company_id)
2048
            {
2049
                $company = $companyMapper->fetchOne($company_id);
2050
                if(!$company) {
2051
                    continue;
2052
                }
2053
 
2054
                $record = [
2055
                    'name' => $company->name,
283 www 2056
                    'image' => $storage->getCompanyImage($company),
119 efrain 2057
                    'details' => [],
2058
                ];
2059
 
2060
                $companyExtendUser = $companyExtendUserMapper->fetchOneByCompanyIdAndUserId($company->id, $currentUser->id);
2061
                if(!$companyExtendUser) {
2062
                    continue;
2063
                }
2064
 
2065
                if($companyExtendUser->extend_company_id) {
2066
 
2067
                    $extendedCompany = $companyExtendUserCompanyMapper->fetchOne($companyExtendUser->company_id);
2068
                    if($extendedCompany) {
2069
                        array_push($record['details'],[
2070
                            'uuid' => $extendedCompany->uuid,
2071
                            'label' => 'LABEL_COMPANY',
2072
                            'value' => $extendedCompany->name
2073
                        ]);
2074
                    }
2075
                }
2076
 
2077
                if($companyExtendUser->extend_function_id) {
2078
                    $extendedFunction = $companyExtendUserFunctionMapper->fetchOne($companyExtendUser->extend_function_id);
2079
                    if($extendedFunction) {
2080
                        array_push($record['details'],[
2081
                            'uuid' => $extendedFunction->uuid,
2082
                            'label' => 'LABEL_FUNCTION',
2083
                            'value' => $extendedFunction->name
2084
                        ]);
2085
                    }
2086
                }
2087
 
2088
                if($companyExtendUser->extend_group_id) {
2089
                    $extendedGroup = $companyExtendUserGroupMapper->fetchOne($companyExtendUser->extend_group_id);
2090
                    if($extendedGroup) {
2091
                        array_push($record['details'],[
2092
                            'uuid' => $extendedGroup->uuid,
2093
                            'label' => 'LABEL_GROUP',
2094
                            'value' => $extendedGroup->name
2095
                        ]);
2096
                    }
2097
                }
2098
 
2099
                if($companyExtendUser->extend_institution_id) {
2100
                    $extendedInstitution= $companyExtendUserInstitutionMapper->fetchOne($companyExtendUser->extend_institution_id);
2101
                    if($extendedInstitution) {
2102
                        array_push($record['details'],[
2103
                            'uuid' => $extendedInstitution->uuid,
2104
                            'label' => 'LABEL_INSTITUTION',
2105
                            'value' => $extendedInstitution->name
2106
                        ]);
2107
                    }
2108
                }
2109
 
2110
                if($companyExtendUser->extend_program_id) {
2111
                    $extendedProgram = $companyExtendUserProgramMapper->fetchOne($companyExtendUser->extend_program_id);
2112
                    if($extendedProgram) {
2113
                        array_push($record['details'],[
2114
                            'uuid' => $extendedProgram->uuid,
2115
                            'label' => 'LABEL_PROGRAM',
2116
                            'value' => $extendedProgram->name
2117
                        ]);
2118
 
2119
                    }
2120
                }
2121
 
2122
                if($companyExtendUser->extend_sector_id) {
2123
                    $extendedSector = $companyExtendUserSectorMapper->fetchOne($companyExtendUser->extend_sector_id);
2124
                    if($extendedSector) {
2125
                        array_push($record['details'],[
2126
                            'uuid' => $extendedSector->uuid,
2127
                            'label' => 'LABEL_SECTOR',
2128
                            'value' => $extendedSector->name
2129
                        ]);
2130
                    }
2131
                }
2132
 
2133
                if($companyExtendUser->extend_partner_id) {
2134
                    $extendedPartner = $companyExtendUserPartnerMapper->fetchOne($companyExtendUser->extend_partner_id);
2135
                    if($extendedPartner) {
2136
                        array_push($record['details'],[
2137
                            'uuid' => $extendedPartner->uuid,
2138
                            'label' => 'LABEL_PARTNER',
2139
                            'value' => $extendedPartner->name
2140
                        ]);
2141
                    }
2142
                }
2143
 
2144
                if($companyExtendUser->extend_student_type_id) {
2145
                    $extendedStudentType = $companyExtendUserStudentTypeMapper->fetchOne($companyExtendUser->extend_student_type_id);
2146
                    if($extendedStudentType) {
2147
                        array_push($record['details'],[
2148
                            'uuid' => $extendedStudentType->uuid,
2149
                            'label' => 'LABEL_TYPE',
2150
                            'value' => $extendedStudentType->name
2151
                        ]);
2152
                    }
2153
                }
2154
 
2155
                array_push($data, $record);
2156
            }
2157
 
2158
            return new JsonModel([
2159
                'success' => true,
2160
                'data' => $data
2161
            ]);
2162
 
2163
        } else {
2164
            return new JsonModel([
2165
                'success' => false,
2166
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
2167
            ]);
2168
        }
2169
    }
2170
 
167 efrain 2171
    public function syncAction()
2172
    {
2173
        $request = $this->getRequest();
168 efrain 2174
        if($request->isPost()) {
167 efrain 2175
            $currentUserPlugin = $this->plugin('currentUserPlugin');
2176
            $currentUser = $currentUserPlugin->getUser();
2177
 
2178
 
2179
            $operation = $this->params()->fromRoute('operation');
2180
            if($operation == 'slide-view' || $operation == 'capsule-close' || $operation == 'topic-close') {
2181
                $accessGrantedIds = $this->getAccessGranted();
2182
 
2183
                $topic_uuid     = $this->params()->fromRoute('topic_uuid');
2184
                $capsule_uuid   = $this->params()->fromRoute('capsule_uuid');
2185
                $slide_uuid     = $this->params()->fromRoute('slide_uuid');
2186
 
2187
                $accessGrantedIds = $this->getAccessGranted();
2188
                if($operation == 'slide-view') {
2189
 
2190
                    if(empty($slide_uuid) || empty($capsule_uuid ) || empty($topic_uuid)) {
2191
                        return new JsonModel([
2192
                            'success' => false,
2193
                            'data' => 'ERROR_INVALID_PARAMETERS'
2194
                        ]);
2195
                    }
2196
 
2197
 
283 www 2198
                    $topicMapper = MicrolearningTopicMapper::getInstance($this->adapter);
167 efrain 2199
                    $topic = $topicMapper->fetchOneByUuid($topic_uuid);
2200
 
2201
                    if(!$topic) {
2202
                        return new JsonModel([
2203
                            'success' => false,
2204
                            'data' => 'ERROR_TOPIC_NOT_FOUND'
2205
                        ]);
2206
                    }
2207
 
2208
 
2209
 
2210
                    if(!in_array($topic->id, $accessGrantedIds->topics)) {
2211
                        return new JsonModel([
2212
                            'success' => false,
2213
                            'data' => 'ERROR_YOU_DO_NOT_HAVE_ACCESS_TO_THIS_TOPIC'
2214
                        ]);
2215
                    }
2216
 
283 www 2217
                    $capsuleMapper = MicrolearningCapsuleMapper::getInstance($this->adapter);
167 efrain 2218
                    $capsule = $capsuleMapper->fetchOneByUuid($capsule_uuid);
2219
 
2220
                    if(!$capsule) {
2221
                        return new JsonModel([
2222
                            'success' => false,
2223
                            'data' => 'ERROR_CAPSULE_NOT_FOUND'
2224
                        ]);
2225
                    }
119 efrain 2226
 
167 efrain 2227
                    if(!in_array($capsule->id, $accessGrantedIds->capsules) || $capsule->topic_id != $topic->id) {
2228
                        return new JsonModel([
2229
                            'success' => false,
2230
                            'data' => 'ERROR_YOU_DO_NOT_HAVE_ACCESS_TO_THIS_CAPSULE'
2231
                        ]);
2232
                    }
2233
 
283 www 2234
                    $slideMapper = MicrolearningSlideMapper::getInstance($this->adapter);
167 efrain 2235
                    $slide = $slideMapper->fetchOneByUuid($slide_uuid);
2236
                    if(!$slide) {
2237
                        return new JsonModel([
2238
                            'success' => false,
2239
                            'data' => 'ERROR_SLIDE_NOT_FOUND'
2240
                        ]);
2241
                    }
2242
 
2243
                    if($slide->capsule_id != $capsule->id && $slide->topic_id != $topic->id) {
2244
                        return new JsonModel([
2245
                            'success' => false,
2246
                            'data' => 'ERROR_SLIDE_NOT_FOUND'
2247
                        ]);
2248
 
2249
                    }
2250
 
2251
 
283 www 2252
                    $userLogMapper = MicrolearningUserLogMapper::getInstance($this->adapter);
167 efrain 2253
 
283 www 2254
                    $userProgressMapper = MicrolearningUserProgressMapper::getInstance($this->adapter);
167 efrain 2255
                    $added_on = $userProgressMapper->getDatebaseNow();
2256
 
2257
 
2258
                    $userProgressTopic = $userProgressMapper->fetchOneByUserIdAndTopicId($currentUser->id, $topic->id);
2259
                    if(!$userProgressTopic) {
2260
 
283 www 2261
                        $userProgressTopic = new MicrolearningUserProgress();
558 stevensc 2262
                        $userProgressTopic->company_id                  = $topic->company_id; // Usar company_id del tópico
2263
                        $userProgressTopic->topic_id                    = $topic->id;        // Usar id del tópico
176 efrain 2264
                        $userProgressTopic->user_id                     = $currentUser->id;
167 efrain 2265
                        $userProgressTopic->progress                    = 0;
2266
                        $userProgressTopic->returning                   = 0;
2267
                        $userProgressTopic->returning_after_completed   = 0;
2268
                        $userProgressTopic->completed                   = 0;
558 stevensc 2269
                        $userProgressTopic->total_slides                = $slideMapper->fetchTotalCountByCompanyIdAndTopicId($topic->company_id, $topic->id);
167 efrain 2270
                        $userProgressTopic->view_slides                 = 0;
283 www 2271
                        $userProgressTopic->type                        = MicrolearningUserProgress::TYPE_TOPIC;
167 efrain 2272
                        $userProgressTopic->added_on                    = $added_on;
2273
                        $userProgressTopic->updated_on                  = $added_on;
2274
 
2275
                        if($userProgressMapper->insert($userProgressTopic)) {
2276
 
283 www 2277
                            $userLog = new MicrolearningUserLog();
2278
                            $userLog->activity      = MicrolearningUserLog::ACTIVITY_START_TOPIC;
167 efrain 2279
                            $userLog->user_id       = $currentUser->id;
558 stevensc 2280
                            $userLog->company_id    = $topic->company_id;
2281
                            $userLog->topic_id      = $topic->id;
167 efrain 2282
                            $userLog->added_on      = $added_on;
2283
 
2284
                            if(!$userLogMapper->insert($userLog)) {
2285
                                return new JsonModel([
2286
                                    'success' => false,
2287
                                    'data' => $userProgressMapper->getError()
2288
                                ]);
2289
                            }
2290
                        } else {
2291
                            return new JsonModel([
2292
                                'success' => false,
2293
                                'data' => $userProgressMapper->getError()
2294
                            ]);
2295
                        }
2296
                    }
2297
 
2298
 
2299
                    $userProgressCapsule = $userProgressMapper->fetchOneByUseridAndCapsuleId($currentUser->id, $capsule->id);
2300
                    if(!$userProgressCapsule) {
2301
 
283 www 2302
                        $userProgressCapsule = new MicrolearningUserProgress();
558 stevensc 2303
                        $userProgressCapsule->company_id                  = $capsule->company_id; // Usar company_id de la cápsula
2304
                        $userProgressCapsule->topic_id                    = $topic->id;         // Usar el id del tópico obtenido previamente
2305
                        $userProgressCapsule->capsule_id                  = $capsule->id;       // Usar id de la cápsula
176 efrain 2306
                        $userProgressCapsule->user_id                     = $currentUser->id;
167 efrain 2307
                        $userProgressCapsule->progress                    = 0;
2308
                        $userProgressCapsule->returning                   = 0;
2309
                        $userProgressCapsule->returning_after_completed   = 0;
2310
                        $userProgressCapsule->completed                   = 0;
558 stevensc 2311
                        $userProgressCapsule->total_slides                = $slideMapper->fetchTotalCountByCompanyIdAndTopicIdAndCapsuleId($capsule->company_id, $topic->id, $capsule->id);
167 efrain 2312
                        $userProgressCapsule->view_slides                 = 0;
2313
                        $userProgressTopic->updated_on                    = $added_on;
2314
 
2315
                        if($userProgressMapper->insert($userProgressCapsule)) {
2316
 
283 www 2317
                            $userLog = new MicrolearningUserLog();
2318
                            $userLog->activity      = MicrolearningUserLog::ACTIVITY_START_CAPSULE;
167 efrain 2319
                            $userLog->user_id       = $currentUser->id;
558 stevensc 2320
                            $userLog->company_id    = $capsule->company_id;
2321
                            $userLog->topic_id      = $topic->id;
2322
                            $userLog->capsule_id    = $capsule->id;
167 efrain 2323
                            $userLog->added_on      = $added_on;
2324
 
2325
                            if(!$userLogMapper->insert($userLog)) {
2326
                                return new JsonModel([
2327
                                    'success' => false,
2328
                                    'data' => $userLogMapper->getError()
2329
                                ]);
2330
                            }
2331
                        } else {
2332
                            return new JsonModel([
2333
                                'success' => false,
2334
                                'data' => $userProgressMapper->getError()
2335
                            ]);
2336
                        }
2337
                    }
2338
 
2339
 
2340
                    $userProgressSlide = $userProgressMapper->fetchOneByUserIdAndSlideId($currentUser->id, $slide->id);
2341
                    if(!$userProgressSlide) {
283 www 2342
                        $userProgressSlide = new MicrolearningUserProgress();
167 efrain 2343
                        $userProgressSlide->company_id                  = $slide->company_id;
2344
                        $userProgressSlide->topic_id                    = $slide->topic_id;
2345
                        $userProgressSlide->capsule_id                  = $slide->capsule_id;
2346
                        $userProgressSlide->slide_id                    = $slide->id;
176 efrain 2347
                        $userProgressSlide->user_id                     = $currentUser->id;
167 efrain 2348
                        $userProgressSlide->progress                    = 0;
2349
                        $userProgressSlide->returning                   = 0;
2350
                        $userProgressSlide->returning_after_completed   = 0;
2351
                        $userProgressSlide->completed                   = 1;
2352
                        $userProgressSlide->total_slides                = 0;
2353
                        $userProgressSlide->view_slides                 = 0;
283 www 2354
                        $userProgressSlide->type                        = MicrolearningUserProgress::TYPE_SLIDE;
167 efrain 2355
                        $userProgressSlide->added_on                    = $added_on;
2356
                        $userProgressSlide->updated_on                  = $added_on;
2357
 
2358
                        if(!$userProgressMapper->insert($userProgressSlide)) {
2359
                            return new JsonModel([
2360
                                'success' => false,
2361
                                'data' => $userProgressMapper->getError()
2362
                            ]);
2363
                        }
2364
                    }
2365
 
283 www 2366
                    $userLog = new MicrolearningUserLog();
2367
                    $userLog->activity      = MicrolearningUserLog::ACTIVITY_VIEW_SLIDE;
167 efrain 2368
                    $userLog->user_id       = $currentUser->id;
2369
                    $userLog->company_id    = $slide->company_id;
2370
                    $userLog->topic_id      = $slide->topic_id;
2371
                    $userLog->capsule_id    = $slide->capsule_id;
2372
                    $userLog->slide_id      = $slide->id;
2373
                    $userLog->added_on      = $added_on;
2374
 
2375
                    if(!$userLogMapper->insert($userLog)) {
2376
                        return new JsonModel([
2377
                            'success' => false,
2378
                            'data' => $userLogMapper->getError()
2379
                        ]);
2380
                    }
2381
 
2382
                    $closeCapsule = false;
2383
 
2384
                    if($userProgressCapsule->completed) {
2385
 
2386
                        $dt = \DateTime::createFromFormat('Y-m-d H:i:s', $added_on);
2387
                        $returning_on = $dt->format('Y-m-d');
2388
 
558 stevensc 2389
                        // Asegurarse que returning_on existe en el objeto antes de comparar
2390
                        $current_returning_on = isset($userProgressCapsule->returning_on) ? $userProgressCapsule->returning_on : null;
2391
 
2392
                        if(!$current_returning_on || $current_returning_on != $returning_on) {
167 efrain 2393
 
2394
                            $userProgressCapsule->returning_on = $returning_on;
558 stevensc 2395
                            // Asegurarse que returning_after_completed existe y es numérico antes de incrementar
2396
                            $userProgressCapsule->returning_after_completed = (isset($userProgressCapsule->returning_after_completed) ? intval($userProgressCapsule->returning_after_completed) : 0) + 1;
167 efrain 2397
 
2398
                            if(!$userProgressMapper->update($userProgressCapsule)) {
2399
                                return new JsonModel([
2400
                                    'success' => false,
2401
                                    'data' => $userProgressMapper->getError()
2402
                                ]);
2403
                            }
2404
                        }
2405
 
2406
                    }  else {
2407
 
558 stevensc 2408
                        // Usar $topic->id para obtener el total de slides de la cápsula en el contexto de este tópico
2409
                        $userProgressCapsule->total_slides = $slideMapper->fetchTotalCountByCompanyIdAndTopicIdAndCapsuleId($capsule->company_id, $topic->id, $capsule->id);
2410
                        $userProgressCapsule->view_slides = $userProgressMapper->fetchCountAllSlideCompletedByUserIdAndCapsuleId($currentUser->id, $capsule->id);
167 efrain 2411
 
2412
                        if($userProgressCapsule->total_slides) {
2413
 
2414
                            $userProgressCapsule->progress = ($userProgressCapsule->view_slides * 100) / $userProgressCapsule->total_slides;
2415
                            $userProgressCapsule->progress = $userProgressCapsule->progress > 100 ? 100 : $userProgressCapsule->progress;
2416
                        }
2417
 
2418
                        if(!$userProgressMapper->update($userProgressCapsule)) {
2419
                            return new JsonModel([
2420
                                'success' => false,
2421
                                'data' => $userProgressMapper->getError()
2422
                            ]);
2423
                        }
2424
 
2425
                        if($userProgressCapsule->progress >= 100) {
2426
                            $closeCapsule = true;
2427
                        }
171 efrain 2428
 
283 www 2429
 
167 efrain 2430
                    }
2431
 
2432
                    $closeTopic = false;
2433
                    if(!$userProgressTopic->completed) {
2434
 
558 stevensc 2435
                        // Usar $topic->id para obtener el total de slides del tópico
2436
                        $userProgressTopic->total_slides = $slideMapper->fetchTotalCountByCompanyIdAndTopicId($topic->company_id, $topic->id);
2437
                        $userProgressTopic->view_slides = $userProgressMapper->fetchCountAllSlideCompletedByUserIdAndTopicId($currentUser->id, $topic->id);
167 efrain 2438
 
2439
                        if($userProgressTopic->total_slides) {
2440
 
2441
                            $userProgressTopic->progress = ($userProgressTopic->view_slides * 100) / $userProgressTopic->total_slides;
2442
                            $userProgressTopic->progress = $userProgressTopic->progress > 100 ? 100 : $userProgressTopic->progress;
2443
                        }
2444
                        if(!$userProgressMapper->update($userProgressTopic)) {
2445
                            return new JsonModel([
2446
                                'success' => false,
2447
                                'data' => $userProgressMapper->getError()
2448
                            ]);
2449
                        }
2450
 
2451
                        if($userProgressTopic->progress >= 100) {
2452
                            $closeTopic = true;
2453
                        }
2454
                    }
2455
 
2456
 
2457
                    $data = [
2458
                        'message' => 'LABEL_THE_USER_PROGRESS_FOR_THIS_SLIDE_HAS_BEEN_COMPLETED',
2459
 
2460
                    ];
2461
 
2462
                    if($closeCapsule) {
173 efrain 2463
                        $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 2464
                    }
2465
 
2466
 
2467
                    if($closeTopic) {
173 efrain 2468
                        $data['link_close_topic'] = $this->url()->fromRoute('microlearning/sync', ['operation' => 'topic-close', 'topic_uuid' => $topic->uuid], ['force_canonical' => true]);
167 efrain 2469
                    }
2470
 
2471
 
2472
                    return new JsonModel([
2473
                        'success' => true,
2474
                        'data' => $data
2475
                    ]);
2476
 
2477
 
2478
 
2479
 
2480
                } else if($operation == 'capsule-close') {
2481
 
2482
                    if(empty($capsule_uuid ) || empty($topic_uuid)) {
2483
                        return new JsonModel([
2484
                            'success' => false,
2485
                            'data' => 'ERROR_INVALID_PARAMETERS'
2486
                        ]);
2487
                    }
2488
 
2489
 
283 www 2490
                    $topicMapper = MicrolearningTopicMapper::getInstance($this->adapter);
167 efrain 2491
                    $topic = $topicMapper->fetchOneByUuid($topic_uuid);
2492
 
2493
                    if(!$topic) {
2494
                        return new JsonModel([
2495
                            'success' => false,
2496
                            'data' => 'ERROR_TOPIC_NOT_FOUND'
2497
                        ]);
2498
                    }
2499
 
2500
 
2501
 
2502
                    if(!in_array($topic->id, $accessGrantedIds->topics)) {
2503
                        return new JsonModel([
2504
                            'success' => false,
2505
                            'data' => 'ERROR_YOU_DO_NOT_HAVE_ACCESS_TO_THIS_TOPIC'
2506
                        ]);
2507
                    }
2508
 
283 www 2509
                    $capsuleMapper = MicrolearningCapsuleMapper::getInstance($this->adapter);
167 efrain 2510
                    $capsule = $capsuleMapper->fetchOneByUuid($capsule_uuid);
2511
 
2512
                    if(!$capsule) {
2513
                        return new JsonModel([
2514
                            'success' => false,
2515
                            'data' => 'ERROR_CAPSULE_NOT_FOUND'
2516
                        ]);
2517
                    }
2518
 
2519
                    if(!in_array($capsule->id, $accessGrantedIds->capsules) || $capsule->topic_id != $topic->id) {
2520
                        return new JsonModel([
2521
                            'success' => false,
2522
                            'data' => 'ERROR_YOU_DO_NOT_HAVE_ACCESS_TO_THIS_CAPSULE'
2523
                        ]);
2524
                    }
2525
 
2526
 
283 www 2527
                    $userLogMapper = MicrolearningUserLogMapper::getInstance($this->adapter);
167 efrain 2528
 
283 www 2529
                    $userProgressMapper = MicrolearningUserProgressMapper::getInstance($this->adapter);
167 efrain 2530
                    $updated_on = $userProgressMapper->getDatebaseNow();
2531
 
2532
                    $userProgressCapsule = $userProgressMapper->fetchOneByUseridAndCapsuleId($currentUser->id, $capsule->id);
2533
                    if(!$userProgressCapsule) {
2534
                        return new JsonModel([
2535
                            'success' => false,
2536
                            'data' => 'ERROR_THE_USER_PROGRESS_FOR_THIS_CAPSULE_NOT_FOUND'
2537
                        ]);
2538
                    }
2539
 
2540
                    if($userProgressCapsule->completed) {
2541
                        return new JsonModel([
2542
                            'success' => false,
2543
                            'data' => 'ERROR_THE_USER_PROGRESS_FOR_THIS_CAPSULE_ALREADY_CLOSED'
2544
                        ]);
2545
                    }
2546
 
2547
 
2548
                    $userProgressCapsule->completed = 1;
2549
                    $userProgressCapsule->updated_on = $updated_on;
2550
 
2551
                    if($userProgressMapper->update($userProgressCapsule)) {
225 efrain 2552
 
2553
 
283 www 2554
                        $userLog = new MicrolearningUserLog();
2555
                        $userLog->activity      = MicrolearningUserLog::ACTIVITY_COMPLETED_CAPSULE;
227 efrain 2556
                        $userLog->user_id       = $currentUser->id;
2557
                        $userLog->company_id    = $capsule->company_id;
2558
                        $userLog->topic_id      = $capsule->topic_id;
2559
                        $userLog->capsule_id    = $capsule->id;
2560
                        $userLog->added_on      = $updated_on;
225 efrain 2561
 
2562
                        if(!$userLogMapper->insert($userLog)) {
2563
                            return new JsonModel([
2564
                                'success' => false,
2565
                                'data' => $userProgressMapper->getError()
2566
                            ]);
2567
                        }
2568
 
2569
 
167 efrain 2570
                        return new JsonModel([
2571
                            'success' => true,
2572
                            'data' => 'LABEL_THE_USER_PROGRESS_FOR_THIS_CAPSULE_HAS_BEEN_COMPLETED'
2573
                        ]);
2574
                    } else {
2575
                        return new JsonModel([
2576
                            'success' => false,
2577
                            'data' => 'ERROR_THE_USER_PROGRESS_FOR_THIS_CAPSULE_COULD_NOT_BE_COMPLETED'
2578
                        ]);
2579
                    }
2580
 
2581
 
2582
 
2583
 
2584
 
2585
 
2586
 
2587
                } else if($operation == 'topic-close') {
174 efrain 2588
                    if(empty($topic_uuid)) {
167 efrain 2589
                        return new JsonModel([
2590
                            'success' => false,
2591
                            'data' => 'ERROR_INVALID_PARAMETERS'
2592
                        ]);
2593
                    }
2594
 
2595
 
283 www 2596
                    $topicMapper = MicrolearningTopicMapper::getInstance($this->adapter);
167 efrain 2597
                    $topic = $topicMapper->fetchOneByUuid($topic_uuid);
2598
 
2599
                    if(!$topic) {
2600
                        return new JsonModel([
2601
                            'success' => false,
2602
                            'data' => 'ERROR_TOPIC_NOT_FOUND'
2603
                        ]);
2604
                    }
2605
 
2606
 
2607
 
2608
                    if(!in_array($topic->id, $accessGrantedIds->topics)) {
2609
                        return new JsonModel([
2610
                            'success' => false,
2611
                            'data' => 'ERROR_YOU_DO_NOT_HAVE_ACCESS_TO_THIS_TOPIC'
2612
                        ]);
2613
                    }
2614
 
2615
 
2616
 
2617
 
283 www 2618
                    $userLogMapper = MicrolearningUserLogMapper::getInstance($this->adapter);
167 efrain 2619
 
283 www 2620
                    $userProgressMapper = MicrolearningUserProgressMapper::getInstance($this->adapter);
167 efrain 2621
                    $updated_on = $userProgressMapper->getDatebaseNow();
2622
 
2623
                    $userProgressTopic = $userProgressMapper->fetchOneByUserIdAndTopicId($currentUser->id, $topic->id);
2624
                    if(!$userProgressTopic) {
2625
                        return new JsonModel([
2626
                            'success' => false,
2627
                            'data' => 'ERROR_THE_USER_PROGRESS_FOR_THIS_TOPIC_NOT_FOUND'
2628
                        ]);
2629
                    }
2630
 
2631
                    if($userProgressTopic->completed) {
2632
                        return new JsonModel([
2633
                            'success' => false,
2634
                            'data' => 'ERROR_THE_USER_PROGRESS_FOR_THIS_TOPIC_ALREADY_CLOSED'
2635
                        ]);
2636
                    }
2637
 
2638
 
2639
                    $userProgressTopic->completed = 1;
2640
                    $userProgressTopic->updated_on = $updated_on;
2641
 
2642
                    if($userProgressMapper->update($userProgressTopic)) {
226 efrain 2643
 
283 www 2644
                        $userLog = new MicrolearningUserLog();
2645
                        $userLog->activity      = MicrolearningUserLog::ACTIVITY_COMPLETED_TOPIC;
227 efrain 2646
                        $userLog->user_id       = $currentUser->id;
2647
                        $userLog->company_id    = $topic->company_id;
2648
                        $userLog->topic_id      = $topic->id;
2649
                        $userLog->added_on      = $updated_on;
226 efrain 2650
 
2651
                        if(!$userLogMapper->insert($userLog)) {
2652
                            return new JsonModel([
2653
                                'success' => false,
2654
                                'data' => $userProgressMapper->getError()
2655
                            ]);
2656
                        }
2657
 
167 efrain 2658
                        return new JsonModel([
2659
                            'success' => true,
2660
                            'data' => 'LABEL_THE_USER_PROGRESS_FOR_THIS_TOPIC_HAS_BEEN_COMPLETED'
2661
                        ]);
2662
                    } else {
2663
                        return new JsonModel([
2664
                            'success' => false,
2665
                            'data' => 'ERROR_THE_USER_PROGRESS_FOR_THIS_TOPIC_COULD_NOT_BE_COMPLETED'
2666
                        ]);
2667
                    }
2668
                }
2669
 
2670
 
2671
 
2672
 
2673
            } else {
2674
 
2675
                return new JsonModel([
2676
                    'success' => false,
2677
                    'data' => 'ERROR_OPERATION_UNKNOWN'
2678
                ]);
2679
 
2680
 
2681
            }
2682
 
2683
        } else {
2684
            return new JsonModel([
2685
                'success' => false,
2686
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
2687
            ]);
2688
        }
2689
    }
2690
 
2691
 
302 www 2692
 
2693
 
2694
 
119 efrain 2695
    /**
2696
     *
2697
     * @return \LeadersLinked\Controller\MicrolearningUserAccessGrantedIds
2698
     */
2699
    private function getAccessGranted()
2700
    {
2701
        $currentUserPlugin = $this->plugin('currentUserPlugin');
2702
        $currentUser = $currentUserPlugin->getUser();
2703
 
283 www 2704
        $capsuleUserMapper = MicrolearningCapsuleUserMapper::getInstance($this->adapter);
119 efrain 2705
        $now = $capsuleUserMapper->getDatebaseNow();
2706
 
2707
        $records = $capsuleUserMapper->fetchAllActiveByUserId($currentUser->id);
2708
 
2709
        $accessGrantedIds = new MicrolearningUserAccessGrantedIds();
2710
 
2711
 
2712
        foreach($records as $record)
2713
        {
283 www 2714
            if($record->access != MicrolearningCapsuleUser::ACCESS_UNLIMITED && $record->access != MicrolearningCapsuleUser::ACCESS_PAY_PERIOD) {
119 efrain 2715
                continue;
2716
            }
283 www 2717
            if($record->access == MicrolearningCapsuleUser::ACCESS_PAY_PERIOD) {
119 efrain 2718
                if($now < $record->paid_from || $now > $record->paid_to) {
2719
                    continue;
2720
                }
2721
            }
2722
 
2723
 
2724
            if(!in_array($record->company_id, $accessGrantedIds->companies )) {
2725
                array_push($accessGrantedIds->companies, $record->company_id);
2726
            }
2727
 
2728
            if(!in_array($record->topic_id, $accessGrantedIds->topics )) {
2729
                array_push( $accessGrantedIds->topics, $record->topic_id);
2730
            }
2731
 
2732
            if(!in_array($record->capsule_id, $accessGrantedIds->capsules)) {
2733
                array_push( $accessGrantedIds->capsules, $record->capsule_id);
2734
            }
2735
        }
2736
 
2737
        return $accessGrantedIds;
2738
    }
2739
 
2740
 
2741
}