Proyectos de Subversion LeadersLinked - Services

Rev

Rev 663 | Rev 714 | 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\MicrolearningCapsuleCommentMapper;
119 efrain 14
use LeadersLinked\Form\Service\CapsuleCommentForm;
283 www 15
use LeadersLinked\Model\MicrolearningCapsuleComment;
16
use LeadersLinked\Model\MicrolearningAnswer;
17
use LeadersLinked\Mapper\MicrolearningUserProgressMapper;
18
use LeadersLinked\Mapper\MicrolearningSlideMapper;
19
use LeadersLinked\Mapper\MicrolearningUserLogMapper;
20
use LeadersLinked\Model\MicrolearningUserLog;
21
use LeadersLinked\Mapper\MicrolearningTopicMapper;
119 efrain 22
use LeadersLinked\Mapper\CompanyMapper;
283 www 23
use LeadersLinked\Model\MicrolearningUserProgress;
24
use LeadersLinked\Mapper\MicrolearningExtendUserMapper;
25
use LeadersLinked\Mapper\MicrolearningExtendUserCompanyMapper;
26
use LeadersLinked\Mapper\MicrolearningExtendUserFunctionMapper;
27
use LeadersLinked\Mapper\MicrolearningExtendUserGroupMapper;
28
use LeadersLinked\Mapper\MicrolearningExtendUserInstitutionMapper;
29
use LeadersLinked\Mapper\MicrolearningExtendUserPartnerMapper;
30
use LeadersLinked\Mapper\MicrolearningExtendUserProgramMapper;
31
use LeadersLinked\Mapper\MicrolearningExtendUserStudentTypeMapper;
32
use LeadersLinked\Mapper\MicrolearningExtendUserSectorMapper;
33
use LeadersLinked\Mapper\MicrolearningQuizMapper;
34
use LeadersLinked\Mapper\MicrolearningQuestionMapper;
35
use LeadersLinked\Mapper\MicrolearningAnswerMapper;
36
use LeadersLinked\Model\MicrolearningSlide;
37
use LeadersLinked\Library\Storage;
302 www 38
use LeadersLinked\Mapper\MicrolearningTopicCapsuleMapper;
633 stevensc 39
use LeadersLinked\Mapper\MicrolearningTopicUserMapper;
40
use LeadersLinked\Model\MicrolearningTopicUser;
119 efrain 41
 
42
class MicrolearningUserAccessGrantedIds
43
{
44
    public $companies;
45
    public $topics;
46
    public $capsules;
47
 
48
 
49
    public function __construct()
50
    {
51
        $this->companies    = [];
52
        $this->topics       = [];
53
        $this->capsules     = [];
54
    }
55
}
56
 
57
class MicrolearningController extends AbstractActionController
58
{
59
 
60
    /**
61
     *
62
     * @var \Laminas\Db\Adapter\AdapterInterface
63
     */
64
    private $adapter;
65
 
66
    /**
67
     *
68
     * @var \LeadersLinked\Cache\CacheInterface
69
     */
70
    private $cache;
71
 
72
 
73
    /**
74
     *
75
     * @var \Laminas\Log\LoggerInterface
76
     */
77
    private $logger;
78
 
79
    /**
80
     *
81
     * @var array
82
     */
83
    private $config;
84
 
85
 
86
    /**
87
     *
88
     * @var \Laminas\Mvc\I18n\Translator
89
     */
90
    private $translator;
91
 
92
 
93
    /**
94
     *
95
     * @param \Laminas\Db\Adapter\AdapterInterface $adapter
96
     * @param \LeadersLinked\Cache\CacheInterface $cache
97
     * @param \Laminas\Log\LoggerInterface LoggerInterface $logger
98
     * @param array $config
99
     * @param \Laminas\Mvc\I18n\Translator $translator
100
     */
101
    public function __construct($adapter, $cache, $logger, $config, $translator)
102
    {
103
        $this->adapter      = $adapter;
104
        $this->cache        = $cache;
105
        $this->logger       = $logger;
106
        $this->config       = $config;
107
        $this->translator   = $translator;
108
    }
109
 
110
    public function indexAction()
111
    {
112
        $request = $this->getRequest();
113
 
114
        if($request->isGet()) {
115
            return new JsonModel([
116
                'success' => true,
117
                'data' =>  [
118
                    'link_companies' => $this->url()->fromRoute('microlearning/companies',[], ['force_canonical' => true]),
119
                    'link_timeline' => $this->url()->fromRoute('microlearning/timeline',[], ['force_canonical' => true]),
120
                    'link_last_capsule_in_progress' => $this->url()->fromRoute('microlearning/last-capsule-in-progress',[], ['force_canonical' => true]),
121
                    'link_profile' => $this->url()->fromRoute('microlearning/profile',[], ['force_canonical' => true]),
122
                    'link_topics' => $this->url()->fromRoute('microlearning/topics',[], ['force_canonical' => true]),
123
                    'link_capsules_pending' => $this->url()->fromRoute('microlearning/capsules-pending',[], ['force_canonical' => true]),
124
                    'link_capsules_completed' => $this->url()->fromRoute('microlearning/capsules-completed',[], ['force_canonical' => true]),
125
                    'link_capsules_in_progress' => $this->url()->fromRoute('microlearning/capsules-in-progress',[], ['force_canonical' => true]),
126
                ]
127
            ]);
128
        }
129
 
130
        return new JsonModel([
131
            'success' => false,
132
            'data' => 'ERROR_METHOD_NOT_ALLOWED'
133
        ]);
134
    }
590 stevensc 135
 
119 efrain 136
    public function companiesAction()
137
    {
138
 
139
        $request = $this->getRequest();
140
 
141
        if($request->isGet()) {
142
            $currentNetworkPlugin = $this->plugin('currentNetworkPlugin');
143
            $currentNetwork = $currentNetworkPlugin->getNetwork();
144
 
145
 
146
            $accessGrantedIds = $this->getAccessGranted();
147
            $companyMapper = CompanyMapper::getInstance($this->adapter);
148
            $records = $companyMapper->fetchAllByIdsAndNetworkId($accessGrantedIds->companies, $currentNetwork->id);
149
 
333 www 150
            $storage = Storage::getInstance($this->config, $this->adapter);
119 efrain 151
 
152
            $companies = [];
153
            foreach($records as $record)
154
            {
155
                array_push($companies, [
164 efrain 156
                    'uuid' => $record->uuid,
119 efrain 157
                    'name' => $record->name,
283 www 158
                    'image' => $storage->getCompanyImage($record),
119 efrain 159
                    'link_progress' => $this->url()->fromRoute('microlearning/progress',['id' => $record->uuid], ['force_canonical' => true]),
160
                ]);
161
            }
162
 
163
            return new JsonModel([
164
                'success' => true,
165
                'data' =>  $companies
166
            ]);
167
 
168
 
169
        }
170
        return new JsonModel([
171
            'success' => false,
172
            'data' => 'ERROR_METHOD_NOT_ALLOWED'
173
        ]);
174
    }
590 stevensc 175
 
119 efrain 176
    public function capsuleCommentsAction()
177
    {
178
 
179
        $request = $this->getRequest();
180
 
181
        if($request->isGet()) {
182
            $serviceDatetimeFormat = $this->config['leaderslinked.services.datetime'];
183
 
184
            $currentUserPlugin = $this->plugin('currentUserPlugin');
185
            $currentUser = $currentUserPlugin->getUser();
186
 
187
            $capsule_id = $this->params()->fromRoute('capsule_id');
188
 
283 www 189
            $capsuleMapper = MicrolearningCapsuleMapper::getInstance($this->adapter);
119 efrain 190
            $capsule = $capsuleMapper->fetchOneByUuid($capsule_id);
191
 
192
            if(!$capsule) {
193
                return new JsonModel([
194
                    'success' => false,
195
                    'data' => 'ERROR_CAPSULE_NOT_FOUND'
196
 
197
                ]);
198
            }
199
 
200
            $userMapper = UserMapper::getInstance($this->adapter);
201
            $users = [];
202
 
333 www 203
            $storage = Storage::getInstance($this->config, $this->adapter);
283 www 204
 
205
            $capsuleCommentMapper = MicrolearningCapsuleCommentMapper::getInstance($this->adapter);
119 efrain 206
            $records = $capsuleCommentMapper->fetchAllByCapsuleId($capsule->id);
207
 
208
            $comments = [];
209
            foreach($records as $record)
210
            {
211
 
212
                if(isset($users[$record->user_id])) {
213
 
214
                    $user = $users[$record->user_id];
215
 
216
                } else {
217
 
218
                    $user = $userMapper->fetchOne($record->user_id);
219
                    if(!$user) {
220
                        continue;
221
                    }
222
 
223
                    $users[$record->user_id] = $user;
224
 
225
 
226
                }
227
 
228
 
229
                $dt = \DateTime::createFromFormat('Y-m-d H:i:s', $record->added_on);
230
 
231
                array_push($comments, [
232
                    'date' => $dt->format($serviceDatetimeFormat),
283 www 233
                    'image' => $storage->getUserImage($user),
119 efrain 234
                    'fullname' => trim(trim($user->first_name) . ' ' . trim($user->last_name)),
235
                    'rating' => strval($record->rating),
236
                    'comment' => $record->comment,
237
                    '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]) : '',
238
                ]);
239
            }
240
 
302 www 241
            $dataCountAndRatingAverage = $capsuleCommentMapper->fetchCountAndRatingAverage($capsule->company_id, $capsule->id);
119 efrain 242
 
243
            return new JsonModel([
244
                'success' => true,
245
                'data' => [
246
                    'comments' => $comments,
247
                    'capsule' => [
248
                        'total_comments' => strval($dataCountAndRatingAverage['total_comments']),
249
                        'total_rating' => strval($dataCountAndRatingAverage['total_rating'])
250
                    ]
251
                ]
252
 
253
            ]);
254
 
255
        }
256
 
257
        return new JsonModel([
258
            'success' => false,
259
            'data' => 'ERROR_METHOD_NOT_ALLOWED'
260
        ]);
261
    }
262
 
263
 
264
 
265
    public function capsuleDeleteMyCommentAction()
266
    {
267
 
268
        $request = $this->getRequest();
269
 
270
        if($request->isPost()) {
271
 
272
            $currentUserPlugin = $this->plugin('currentUserPlugin');
273
            $currentUser = $currentUserPlugin->getUser();
274
 
275
            $capsule_id = $this->params()->fromRoute('capsule_id');
276
            $comment_id = $this->params()->fromRoute('comment_id');
277
 
283 www 278
            $capsuleMapper = MicrolearningCapsuleMapper::getInstance($this->adapter);
119 efrain 279
            $capsule = $capsuleMapper->fetchOneByUuid($capsule_id);
280
 
281
            if(!$capsule) {
282
                return new JsonModel([
283
                    'success' => false,
284
                    'data' => 'ERROR_CAPSULE_NOT_FOUND'
285
 
626 stevensc 286
                ]);
119 efrain 287
            }
288
 
283 www 289
            $capsuleCommentMapper = MicrolearningCapsuleCommentMapper::getInstance($this->adapter);
119 efrain 290
            $capsuleComment = $capsuleCommentMapper->fetchOneByUuid($comment_id);
291
 
292
            if(!$capsuleComment) {
293
                return new JsonModel([
294
                    'success' => false,
295
                    'data' => 'ERROR_CAPSULE_COMMENT_NOT_FOUND',
296
                ]);
297
            }
298
 
299
            if($capsuleComment->capsule_id != $capsule->id || $capsuleComment->user_id != $currentUser->id) {
300
                return new JsonModel([
301
                    'success' => false,
302
                    'data' => 'ERROR_YOU_DO_NOT_HAVE_ACCESS_TO_THIS_CAPSULE_COMMENT',
303
                ]);
304
            }
305
 
306
 
307
            $result = $capsuleCommentMapper->delete($capsuleComment->id);
308
            if($result) {
302 www 309
                $dataCountAndRatingAverage = $capsuleCommentMapper->fetchCountAndRatingAverage($capsule->company_id, $capsule->id);
626 stevensc 310
 
119 efrain 311
                return new JsonModel([
312
                    'success' => true,
313
                    'data' => [
314
                        'message' => 'LABEL_CAPSULE_COMMENT_HAVE_BEEN_SUCCESSFULLY_DELETE',
315
                        'capsule' => [
316
                            'total_comments' => strval($dataCountAndRatingAverage['total_comments']),
317
                            'total_rating' => strval($dataCountAndRatingAverage['total_rating'])
318
                        ]
319
                    ],
320
 
321
                ]);
322
            } else {
323
                return new JsonModel([
324
                    'success' => false,
325
                    'data' => $capsuleCommentMapper->getError()
326
 
327
                ]);
328
            }
329
        }
330
 
331
        return new JsonModel([
332
            'success' => false,
333
            'data' => 'ERROR_METHOD_NOT_ALLOWED'
334
        ]);
335
    }
336
 
337
    public function capsuleAddMyCommentAction()
338
    {
339
 
340
        $request = $this->getRequest();
341
 
342
        if($request->isPost()) {
343
 
344
            $currentUserPlugin = $this->plugin('currentUserPlugin');
345
            $currentUser = $currentUserPlugin->getUser();
346
 
347
            $capsule_id = $this->params()->fromRoute('capsule_id');
348
 
349
 
283 www 350
            $capsuleMapper = MicrolearningCapsuleMapper::getInstance($this->adapter);
119 efrain 351
            $capsule = $capsuleMapper->fetchOneByUuid($capsule_id);
352
 
353
            if(!$capsule) {
354
                return new JsonModel([
355
                    'success' => false,
356
                    'data' => 'ERROR_CAPSULE_NOT_FOUND'
357
 
358
                ]);
359
 
360
            }
361
 
362
            $form = new  CapsuleCommentForm();
363
            $dataPost = $request->getPost()->toArray();
364
            $dataPost['added_on'] = $capsuleMapper->getDatebaseNow();
365
 
366
            $form->setData($dataPost);
367
 
368
            if($form->isValid()) {
369
                $dataPost = (array) $form->getData();
370
 
371
 
283 www 372
                $capsuleComment = new MicrolearningCapsuleComment();
119 efrain 373
                $capsuleComment->company_id = $capsule->company_id;
374
                $capsuleComment->capsule_id = $capsule->id;
375
                $capsuleComment->user_id = $currentUser->id;
376
                $capsuleComment->comment = $dataPost['comment'];
377
                $capsuleComment->rating = strval($dataPost['rating']);
378
                $capsuleComment->added_on =  $dataPost['added_on'];
379
 
380
 
283 www 381
                $capsuleCommentMapper = MicrolearningCapsuleCommentMapper::getInstance($this->adapter);
119 efrain 382
                $result = $capsuleCommentMapper->insert($capsuleComment);
383
                if($result) {
384
 
385
                    $capsuleComment = $capsuleCommentMapper->fetchOne($capsuleComment->id);
386
 
302 www 387
                    $dataCountAndRatingAverage = $capsuleCommentMapper->fetchCountAndRatingAverage($capsule->company_id,  $capsule->id);
119 efrain 388
 
389
 
390
 
391
                    return new JsonModel([
392
                        'success' => true,
393
                        'data' => [
394
                            'message' =>'LABEL_CAPSULE_COMMENT_HAVE_BEEN_SUCCESSFULLY_ADDED',
395
 
396
                            'comment' => [
397
                                'comment' => $capsuleComment->comment,
398
                                'rating' => $capsuleComment->rating,
399
                                'link_delete' => $this->url()->fromRoute('microlearning/capsules-comments/delete', ['capsule_id' => $capsule->uuid, 'comment_id' => $capsuleComment->uuid], ['force_canonical' => true])
400
                            ],
401
                            'capsule' => [
402
                                'total_comments' => strval($dataCountAndRatingAverage['total_comments']),
403
                                'total_rating' => strval($dataCountAndRatingAverage['total_rating'])
404
                            ]
405
                        ]
406
 
407
                    ]);
408
                } else {
409
                    return new JsonModel([
410
                        'success' => false,
411
                        'data' => $capsuleCommentMapper->getError()
412
 
413
                    ]);
414
                }
415
 
416
 
417
            } else {
418
                $messages = [];
419
                $form_messages = (array) $form->getMessages();
420
                foreach($form_messages  as $fieldname => $field_messages)
421
                {
422
 
423
                    $messages[$fieldname] = array_values($field_messages);
424
                }
425
 
426
                return new JsonModel([
427
                    'success'   => false,
428
                    'data'   => $messages
429
                ]);
430
            }
431
 
432
 
433
 
434
 
435
        }
436
 
437
        return new JsonModel([
438
            'success' => false,
439
            'data' => 'ERROR_METHOD_NOT_ALLOWED'
440
        ]);
441
    }
442
 
443
    public function lastCapsuleInProgressAction()
444
    {
445
        $request = $this->getRequest();
446
 
447
        if($request->isGet())
448
        {
449
            $currentUserPlugin = $this->plugin('currentUserPlugin');
450
            $currentUser = $currentUserPlugin->getUser();
451
 
452
            $accessGrantedIds = $this->getAccessGranted();
453
 
283 www 454
            $userProgressMapper = MicrolearningUserProgressMapper::getInstance($this->adapter);
636 stevensc 455
            $userProgress = $userProgressMapper->fetchOneLastCapsuleInProgressByUserIdAndTopicIds($currentUser->id, $accessGrantedIds->topics);
119 efrain 456
 
457
            if($userProgress) {
333 www 458
                $storage = Storage::getInstance($this->config, $this->adapter);
283 www 459
                $path = $storage->getPathMicrolearningCapsule();
460
 
461
                $capsuleMapper = MicrolearningCapsuleMapper::getInstance($this->adapter);
119 efrain 462
                $capsule = $capsuleMapper->fetchOne($userProgress->capsule_id);
463
 
283 www 464
                $capsuleCommentMapper = MicrolearningCapsuleCommentMapper::getInstance($this->adapter);
302 www 465
                $dataCountAndRatingAverage = $capsuleCommentMapper->fetchCountAndRatingAverage($capsule->company_id,  $capsule->id);
636 stevensc 466
                $image = $storage->getGenericImage($path, $capsule->uuid, $capsule->image);
576 stevensc 467
 
119 efrain 468
                $response = [
469
                    'success' => true,
470
                    'data' => [
164 efrain 471
                        'uuid'              => $capsule->uuid,
119 efrain 472
                        'name'              => $capsule->name ? $capsule->name : '',
473
                        'description'       => $capsule->description ? $capsule->description : '',
636 stevensc 474
                        'image'             => $image,
119 efrain 475
                        'total_comments'    => strval($dataCountAndRatingAverage['total_comments']),
476
                        'total_rating'      => strval($dataCountAndRatingAverage['total_rating']),
477
                        'completed'         => $userProgress->completed,
145 efrain 478
                        'progress'          => $userProgress->progress,
119 efrain 479
                        'added_on'          => $userProgress->added_on,
480
                        'updated_on'        => $userProgress->updated_on
481
                    ]
482
                ];
483
 
484
 
485
            } else {
486
                $response = [
487
                    'success' => true,
575 stevensc 488
                    'data' => []
119 efrain 489
                ];
490
            }
491
 
492
 
493
        } else {
494
 
495
            $response = [
496
                'success' => false,
497
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
498
            ];
499
 
500
 
501
        }
502
 
503
        return new JsonModel($response);
504
    }
505
 
506
    public function capsulesPendingAction()
507
    {
508
        $request = $this->getRequest();
509
        if($request->isGet()) {
510
            $currentUserPlugin = $this->plugin('currentUserPlugin');
511
            $currentUser = $currentUserPlugin->getUser();
512
 
513
            $name = Functions::sanitizeFilterString($this->params()->fromQuery('name'));
245 efrain 514
            $order_field = Functions::sanitizeFilterString($this->params()->fromQuery('order_field'));
515
            $order_direction = Functions::sanitizeFilterString($this->params()->fromQuery('order_direction'));
119 efrain 516
 
245 efrain 517
            if(!in_array($order_field,['name', 'added_on'] )) {
518
                $order_field = 'name';
519
            }
119 efrain 520
 
245 efrain 521
            if(!in_array( $order_direction,['asc', 'desc'])) {
634 stevensc 522
                $order_direction = 'asc';
245 efrain 523
            }
524
 
283 www 525
            $userProgressMapper = MicrolearningUserProgressMapper::getInstance($this->adapter);
526
            $capsuleMapper = MicrolearningCapsuleMapper::getInstance($this->adapter);
558 stevensc 527
            $topicCapsuleMapper = MicrolearningTopicCapsuleMapper::getInstance($this->adapter); // Añadido
283 www 528
            $topicMapper = MicrolearningTopicMapper::getInstance($this->adapter);
558 stevensc 529
            $capsuleCommentMapper = MicrolearningCapsuleCommentMapper::getInstance($this->adapter); // Reordenado
119 efrain 530
 
531
            $accessGranted = $this->getAccessGranted();
558 stevensc 532
 
634 stevensc 533
            $capsulesData = [];
119 efrain 534
 
333 www 535
            $storage = Storage::getInstance($this->config, $this->adapter);
283 www 536
            $path = $storage->getPathMicrolearningCapsule();
537
 
634 stevensc 538
            foreach($accessGranted->topics as $topic_id)
119 efrain 539
            {
634 stevensc 540
                $topic = $topicMapper->fetchOne($topic_id);
541
                if(!$topic) {
119 efrain 542
                    continue;
543
                }
634 stevensc 544
 
545
                $capsules = $topicCapsuleMapper->fetchAllActiveByTopicId($topic_id) ?? [];
119 efrain 546
 
634 stevensc 547
                foreach($capsules as $capsule) {
548
                    $capsule = $capsuleMapper->fetchOne($capsule->capsule_id);
549
                    if(!$capsule) {
119 efrain 550
                        continue;
551
                    }
634 stevensc 552
 
553
                    $userProgress = $userProgressMapper->fetchOneByUseridAndCapsuleId($currentUser->id, $capsule->id);
554
                    if($userProgress) {
555
                        continue;
558 stevensc 556
                    }
634 stevensc 557
 
558
                    if($name) {
559
                        if(empty($name) || stripos($capsule->name, $name) === false) {
560
                            continue;
561
                        }
562
                    }
563
 
564
                    $dataCountAndRatingAverage = $capsuleCommentMapper->fetchCountAndRatingAverage($capsule->company_id,  $capsule->id);
565
                    $link_slides = $topic->uuid ? $this->url()->fromRoute('microlearning/slides', ['topic_id' => $topic->uuid,  'capsule_id' => $capsule->uuid], ['force_canonical' => true]) : '';
566
 
567
                    array_push($capsulesData, [
568
                        'uuid'              => $capsule->uuid,
569
                        'name'              => $capsule->name ? $capsule->name : '',
570
                        'description'       => $capsule->description ? $capsule->description : '',
571
                        'image'             => $capsule->image ? $storage->getGenericImage($path, $capsule->uuid, $capsule->image)  : '',
572
                        'link_comments'     => $this->url()->fromRoute('microlearning/capsules-comments', ['capsule_id' => $capsule->uuid], ['force_canonical' => true]),
573
                        'link_comment_add'  => $this->url()->fromRoute('microlearning/capsules-comments/add', ['capsule_id' => $capsule->uuid],['force_canonical' => true]),
574
                        'link_slides'       => $link_slides,
575
                        'total_comments'    => strval($dataCountAndRatingAverage['total_comments']),
576
                        'total_rating'      => strval($dataCountAndRatingAverage['total_rating']),
577
                        'progress'          => 0,
578
                        'added_on'          => $capsule->added_on,
579
                        'updated_on'        => $capsule->updated_on,
580
                    ]);
558 stevensc 581
                }
119 efrain 582
            }
583
 
558 stevensc 584
            // 8. Ordenar
245 efrain 585
            if($order_field == 'name') {
586
                if($order_direction == 'asc') {
558 stevensc 587
                    usort($capsulesData, function($a, $b) {
245 efrain 588
                        return strcasecmp($a['name'], $b['name']);
589
                    });
590
                } else {
558 stevensc 591
                    usort($capsulesData, function($a, $b) {
245 efrain 592
                        $result = strcasecmp($a['name'], $b['name']);
558 stevensc 593
                        if($result < 0) { return 1; } else if($result > 0) { return -1; } else { return 0; } // Simplificado
245 efrain 594
                    });
119 efrain 595
                }
596
 
245 efrain 597
            }
598
 
599
            if($order_field == 'added_on') {
600
                if($order_direction == 'asc') {
558 stevensc 601
                    usort($capsulesData, function($a, $b) {
245 efrain 602
                        return strcasecmp($a['added_on'], $b['added_on']);
603
                    });
604
                } else {
558 stevensc 605
                    usort($capsulesData, function($a, $b) {
245 efrain 606
                        $result = strcasecmp($a['added_on'], $b['added_on']);
558 stevensc 607
                        if($result < 0) { return 1; } else if($result > 0) { return -1; } else { return 0; } // Simplificado
245 efrain 608
                    });
609
                }
119 efrain 610
 
558 stevensc 611
            }
119 efrain 612
 
558 stevensc 613
            // 9. Retornar
119 efrain 614
            return new JsonModel([
615
                'success' => true,
558 stevensc 616
                'data' => $capsulesData
634 stevensc 617
            ]);
119 efrain 618
        }
619
 
620
        return new JsonModel([
621
            'success' => false,
622
            'data' => 'ERROR_METHOD_NOT_ALLOWED'
623
        ]);
624
 
625
    }
626
 
627
    public function capsulesCompletedAction()
628
    {
629
        $request = $this->getRequest();
630
        if($request->isGet()) {
631
            $currentUserPlugin = $this->plugin('currentUserPlugin');
632
            $currentUser = $currentUserPlugin->getUser();
633
 
634
            $name = Functions::sanitizeFilterString($this->params()->fromQuery('name'));
245 efrain 635
            $order_field = Functions::sanitizeFilterString($this->params()->fromQuery('order_field'));
636
            $order_direction = Functions::sanitizeFilterString($this->params()->fromQuery('order_direction'));
119 efrain 637
 
246 efrain 638
            if(!in_array($order_field,['name', 'added_on','last_access_on'] )) {
245 efrain 639
                $order_field = 'name';
640
            }
119 efrain 641
 
245 efrain 642
            if(!in_array( $order_direction,['asc', 'desc'])) {
643
                $order_field = 'asc';
644
            }
645
 
283 www 646
            $userProgressMapper = MicrolearningUserProgressMapper::getInstance($this->adapter);
647
            $capsuleMapper = MicrolearningCapsuleMapper::getInstance($this->adapter);
558 stevensc 648
            $topicCapsuleMapper = MicrolearningTopicCapsuleMapper::getInstance($this->adapter);
649
            $topicMapper = MicrolearningTopicMapper::getInstance($this->adapter);
283 www 650
            $capsuleCommentMapper = MicrolearningCapsuleCommentMapper::getInstance($this->adapter);
119 efrain 651
 
652
            $accessGranted = $this->getAccessGranted();
653
 
558 stevensc 654
            $capsulesData = [];
119 efrain 655
 
333 www 656
            $storage = Storage::getInstance($this->config, $this->adapter);
283 www 657
            $path = $storage->getPathMicrolearningCapsule();
658
 
635 stevensc 659
            foreach($accessGranted->topics as $topic_id)
119 efrain 660
            {
635 stevensc 661
                $topic = $topicMapper->fetchOne($topic_id);
662
                if(!$topic) {
119 efrain 663
                    continue;
664
                }
665
 
635 stevensc 666
                $capsules = $topicCapsuleMapper->fetchAllActiveByTopicId($topic_id) ?? [];
119 efrain 667
 
635 stevensc 668
                foreach($capsules as $capsule) {
669
                    $capsule = $capsuleMapper->fetchOne($capsule->capsule_id);
670
                    if(!$capsule) {
119 efrain 671
                        continue;
672
                    }
635 stevensc 673
 
674
                    $userProgress = $userProgressMapper->fetchOneByUseridAndCapsuleId($currentUser->id, $capsule->id);
664 stevensc 675
                    if(!$userProgress) {
635 stevensc 676
                        continue;
558 stevensc 677
                    }
664 stevensc 678
 
679
                    if($userProgress->completed == 0) {
680
                        continue;
681
                    }
635 stevensc 682
 
683
                    if($name) {
684
                        if(empty($name) || stripos($capsule->name, $name) === false) {
685
                            continue;
686
                        }
687
                    }
688
 
689
                    $dataCountAndRatingAverage = $capsuleCommentMapper->fetchCountAndRatingAverage($capsule->company_id,  $capsule->id);
690
                    $link_slides = $topic->uuid ? $this->url()->fromRoute('microlearning/slides', ['topic_id' => $topic->uuid,  'capsule_id' => $capsule->uuid], ['force_canonical' => true]) : '';
691
 
692
                    array_push($capsulesData, [
693
                        'uuid'              => $capsule->uuid,
694
                        'name'              => $capsule->name ? $capsule->name : '',
695
                        'description'       => $capsule->description ? $capsule->description : '',
696
                        'image'             => $capsule->image ? $storage->getGenericImage($path, $capsule->uuid, $capsule->image)  : '',
697
                        'link_comments'     => $this->url()->fromRoute('microlearning/capsules-comments', ['capsule_id' => $capsule->uuid], ['force_canonical' => true]),
698
                        'link_comment_add'  => $this->url()->fromRoute('microlearning/capsules-comments/add', ['capsule_id' => $capsule->uuid],['force_canonical' => true]),
699
                        'link_slides'       => $link_slides,
700
                        'total_comments'    => strval($dataCountAndRatingAverage['total_comments']),
701
                        'total_rating'      => strval($dataCountAndRatingAverage['total_rating']),
702
                        'progress'          => $userProgress->progress,
703
                        'added_on'          => $capsule->added_on,
704
                        'last_access_on'    => $userProgress->updated_on,
705
                        'updated_on'        => $capsule->updated_on,
706
                    ]);
558 stevensc 707
                }
119 efrain 708
            }
709
 
635 stevensc 710
            // 8. Ordenar
245 efrain 711
            if($order_field == 'name') {
712
                if($order_direction == 'asc') {
558 stevensc 713
                    usort($capsulesData, function($a, $b) {
245 efrain 714
                        return strcasecmp($a['name'], $b['name']);
715
                    });
716
                } else {
558 stevensc 717
                    usort($capsulesData, function($a, $b) {
245 efrain 718
                        $result = strcasecmp($a['name'], $b['name']);
558 stevensc 719
                        if($result < 0) { return 1; } else if($result > 0) { return -1; } else { return 0; }
245 efrain 720
                    });
119 efrain 721
                }
245 efrain 722
            }
723
 
724
            if($order_field == 'added_on') {
725
                if($order_direction == 'asc') {
558 stevensc 726
                    usort($capsulesData, function($a, $b) {
245 efrain 727
                        return strcasecmp($a['added_on'], $b['added_on']);
728
                    });
729
                } else {
558 stevensc 730
                    usort($capsulesData, function($a, $b) {
245 efrain 731
                        $result = strcasecmp($a['added_on'], $b['added_on']);
558 stevensc 732
                        if($result < 0) { return 1; } else if($result > 0) { return -1; } else { return 0; }
245 efrain 733
                    });
734
                }
735
            }
246 efrain 736
 
737
            if($order_field == 'last_access_on') {
738
                if($order_direction == 'asc') {
558 stevensc 739
                    usort($capsulesData, function($a, $b) {
246 efrain 740
                        return strcasecmp($a['last_access_on'], $b['last_access_on']);
741
                    });
742
                } else {
558 stevensc 743
                    usort($capsulesData, function($a, $b) {
246 efrain 744
                        $result = strcasecmp($a['last_access_on'], $b['last_access_on']);
558 stevensc 745
                        if($result < 0) { return 1; } else if($result > 0) { return -1; } else { return 0; }
246 efrain 746
                    });
747
                }
748
            }
749
 
119 efrain 750
            return new JsonModel([
751
                'success' => true,
558 stevensc 752
                'data' => $capsulesData
119 efrain 753
            ]);
754
 
755
        }
756
 
757
        return new JsonModel([
758
            'success' => false,
759
            'data' => 'ERROR_METHOD_NOT_ALLOWED'
760
        ]);
761
    }
762
 
763
    public function capsulesInProgressAction()
764
    {
765
        $request = $this->getRequest();
766
        if($request->isGet()) {
767
            $currentUserPlugin = $this->plugin('currentUserPlugin');
768
            $currentUser = $currentUserPlugin->getUser();
769
 
770
            $name = Functions::sanitizeFilterString($this->params()->fromQuery('name'));
245 efrain 771
            $order_field = Functions::sanitizeFilterString($this->params()->fromQuery('order_field'));
772
            $order_direction = Functions::sanitizeFilterString($this->params()->fromQuery('order_direction'));
119 efrain 773
 
246 efrain 774
            if(!in_array($order_field,['name', 'added_on', 'last_access_on'] )) {
245 efrain 775
                $order_field = 'name';
776
            }
119 efrain 777
 
245 efrain 778
            if(!in_array( $order_direction,['asc', 'desc'])) {
558 stevensc 779
                $order_direction = 'asc';
245 efrain 780
            }
781
 
283 www 782
            $userProgressMapper = MicrolearningUserProgressMapper::getInstance($this->adapter);
783
            $capsuleMapper = MicrolearningCapsuleMapper::getInstance($this->adapter);
558 stevensc 784
            $topicCapsuleMapper = MicrolearningTopicCapsuleMapper::getInstance($this->adapter);
785
            $topicMapper = MicrolearningTopicMapper::getInstance($this->adapter);
283 www 786
            $capsuleCommentMapper = MicrolearningCapsuleCommentMapper::getInstance($this->adapter);
119 efrain 787
 
788
            $accessGranted = $this->getAccessGranted();
789
 
558 stevensc 790
            $capsulesData = [];
119 efrain 791
 
333 www 792
            $storage = Storage::getInstance($this->config, $this->adapter);
283 www 793
            $path = $storage->getPathMicrolearningCapsule();
794
 
635 stevensc 795
            foreach($accessGranted->topics as $topic_id)
119 efrain 796
            {
635 stevensc 797
                $topic = $topicMapper->fetchOne($topic_id);
798
                if(!$topic) {
119 efrain 799
                    continue;
800
                }
801
 
635 stevensc 802
                $capsules = $topicCapsuleMapper->fetchAllActiveByTopicId($topic_id) ?? [];
803
 
804
                foreach($capsules as $capsule) {
805
                    $capsule = $capsuleMapper->fetchOne($capsule->capsule_id);
806
                    if(!$capsule) {
119 efrain 807
                        continue;
808
                    }
639 stevensc 809
 
635 stevensc 810
                    $userProgress = $userProgressMapper->fetchOneByUseridAndCapsuleId($currentUser->id, $capsule->id);
664 stevensc 811
                    if(!$userProgress) {
635 stevensc 812
                        continue;
558 stevensc 813
                    }
635 stevensc 814
 
664 stevensc 815
                    if($userProgress->completed == 1) {
816
                        continue;
817
                    }
818
 
635 stevensc 819
                    if($name) {
820
                        if(empty($name) || stripos($capsule->name, $name) === false) {
821
                            continue;
822
                        }
823
                    }
824
 
825
                    $dataCountAndRatingAverage = $capsuleCommentMapper->fetchCountAndRatingAverage($capsule->company_id,  $capsule->id);
826
                    $link_slides = $topic->uuid ? $this->url()->fromRoute('microlearning/slides', ['topic_id' => $topic->uuid,  'capsule_id' => $capsule->uuid], ['force_canonical' => true]) : '';
827
 
828
                    array_push($capsulesData, [
829
                        'uuid'              => $capsule->uuid,
830
                        'name'              => $capsule->name ? $capsule->name : '',
831
                        'description'       => $capsule->description ? $capsule->description : '',
832
                        'image'             => $capsule->image ? $storage->getGenericImage($path, $capsule->uuid, $capsule->image)  : '',
833
                        'link_comments'     => $this->url()->fromRoute('microlearning/capsules-comments', ['capsule_id' => $capsule->uuid], ['force_canonical' => true]),
834
                        'link_comment_add'  => $this->url()->fromRoute('microlearning/capsules-comments/add', ['capsule_id' => $capsule->uuid],['force_canonical' => true]),
835
                        'link_slides'       => $link_slides,
836
                        'total_comments'    => strval($dataCountAndRatingAverage['total_comments']),
837
                        'total_rating'      => strval($dataCountAndRatingAverage['total_rating']),
838
                        'progress'          => $userProgress->progress,
839
                        'added_on'          => $capsule->added_on,
840
                        'last_access_on'    => $userProgress->updated_on,
841
                        'updated_on'        => $capsule->updated_on,
842
                    ]);
558 stevensc 843
                }
119 efrain 844
            }
845
 
635 stevensc 846
            // 8. Ordenar
245 efrain 847
            if($order_field == 'name') {
848
                if($order_direction == 'asc') {
558 stevensc 849
                    usort($capsulesData, function($a, $b) {
245 efrain 850
                        return strcasecmp($a['name'], $b['name']);
851
                    });
852
                } else {
558 stevensc 853
                    usort($capsulesData, function($a, $b) {
245 efrain 854
                        $result = strcasecmp($a['name'], $b['name']);
558 stevensc 855
                        if($result < 0) { return 1; } else if($result > 0) { return -1; } else { return 0; }
245 efrain 856
                    });
119 efrain 857
                }
245 efrain 858
            }
859
 
860
            if($order_field == 'added_on') {
861
                if($order_direction == 'asc') {
558 stevensc 862
                    usort($capsulesData, function($a, $b) {
245 efrain 863
                        return strcasecmp($a['added_on'], $b['added_on']);
864
                    });
865
                } else {
558 stevensc 866
                    usort($capsulesData, function($a, $b) {
245 efrain 867
                        $result = strcasecmp($a['added_on'], $b['added_on']);
558 stevensc 868
                        if($result < 0) { return 1; } else if($result > 0) { return -1; } else { return 0; }
245 efrain 869
                    });
870
                }
871
            }
246 efrain 872
 
873
            if($order_field == 'last_access_on') {
874
                if($order_direction == 'asc') {
558 stevensc 875
                    usort($capsulesData, function($a, $b) {
246 efrain 876
                        return strcasecmp($a['last_access_on'], $b['last_access_on']);
877
                    });
878
                } else {
558 stevensc 879
                    usort($capsulesData, function($a, $b) {
246 efrain 880
                        $result = strcasecmp($a['last_access_on'], $b['last_access_on']);
558 stevensc 881
                        if($result < 0) { return 1; } else if($result > 0) { return -1; } else { return 0; }
246 efrain 882
                    });
883
                }
884
            }
245 efrain 885
 
246 efrain 886
 
119 efrain 887
            return new JsonModel([
888
                'success' => true,
558 stevensc 889
                'data' => $capsulesData
119 efrain 890
            ]);
891
        }
892
 
893
        return new JsonModel([
894
            'success' => false,
895
            'data' => 'ERROR_METHOD_NOT_ALLOWED'
896
        ]);
897
    }
898
 
899
 
900
    public function timelineAction()
901
    {
902
 
903
        $request = $this->getRequest();
904
        if($request->isGet()) {
905
            $currentUserPlugin = $this->plugin('currentUserPlugin');
906
            $currentUser = $currentUserPlugin->getUser();
907
 
908
 
909
            $page = intval($this->params()->fromQuery('page'), 10);
910
 
911
            $activities = [
283 www 912
                MicrolearningUserLog::ACTIVITY_SIGNIN            => 'LABEL_MICROLEARNING_ACTIVITY_SIGNIN',
913
                MicrolearningUserLog::ACTIVITY_SIGNOUT           => 'LABEL_MICROLEARNING_ACTIVITY_SIGNOUT',
914
                MicrolearningUserLog::ACTIVITY_START_TOPIC       => 'LABEL_MICROLEARNING_ACTIVITY_START_TOPIC',
915
                MicrolearningUserLog::ACTIVITY_START_CAPSULE     => 'LABEL_MICROLEARNING_ACTIVITY_START_CAPSULE',
916
                MicrolearningUserLog::ACTIVITY_VIEW_SLIDE        => 'LABEL_MICROLEARNING_ACTIVITY_VIEW_SLIDE',
917
                MicrolearningUserLog::ACTIVITY_TAKE_A_TEST       => 'LABEL_MICROLEARNING_ACTIVITY_TAKE_A_TEST',
918
                MicrolearningUserLog::ACTIVITY_RETAKE_A_TEST     => 'LABEL_MICROLEARNING_ACTIVITY_RETAKE_A_TEST',
919
                MicrolearningUserLog::ACTIVITY_APPROVED_TEST     => 'LABEL_MICROLEARNING_ACTIVITY_APPROVED_TEST',
920
                MicrolearningUserLog::ACTIVITY_COMPLETED_CAPSULE => 'LABEL_MICROLEARNING_ACTIVITY_COMPLETED_CAPSULE',
921
                MicrolearningUserLog::ACTIVITY_COMPLETED_TOPIC   => 'LABEL_MICROLEARNING_ACTIVITY_COMPLETED_TOPIC',
119 efrain 922
            ];
923
 
924
 
925
 
283 www 926
            $microlearningUserLogMapper = MicrolearningUserLogMapper::getInstance($this->adapter);
927
            $paginator = $microlearningUserLogMapper->getAllMessagesPaginatorByUserId($currentUser->id, $page);
119 efrain 928
 
929
            $items = [];
930
            foreach($paginator as $record)
931
            {
932
                $dt = \DateTime::createFromFormat('Y-m-d H:i:s', $record->added_on);
933
 
934
                array_push($items, [
935
                    'activity' => $activities[$record->activity],
936
                    'added_on' => $dt->format('d/m/Y H:i a')
937
                ]);
938
            }
939
 
940
 
941
            return new JsonModel([
942
                'success' => true,
943
                'data' => [
944
                    'total' => [
945
                        'count' => $paginator->getTotalItemCount(),
946
                        'pages' => $paginator->getPages()->pageCount,
947
                    ],
948
                    'current' => [
949
                        'items'    => $items,
950
                        'page'     => $paginator->getCurrentPageNumber(),
951
                        'count'    => $paginator->getCurrentItemCount(),
952
                    ]
953
                ]
954
            ]);
955
 
956
 
957
        } else {
958
            return new JsonModel([
959
                'success' => false,
960
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
961
            ]);
962
        }
963
    }
964
 
965
    /**
966
     * Valores para la generación de los gráficos de progreso
967
     * Para las repuesta afirmativa
968
     * [
969
     *  'success' => true,
970
     *      'data' => [
971
     *          'topicTotal' => cantidad total de tópicos,
972
     *          'topicStarted' => cantidad de tópicos iniciados,
973
     *          'topicIncompleted' => cantidad de tópicos incompletos,
974
     *          'topicCompleted' => cantidad de tópicos completos,
975
     *          'percentCompleted' => % de diapositivas completados ,
976
     *          'percentIncompleted' => % de diapositivas incompletos ,
977
     *          'percentWithoutReturning' => % de cápsulas sin retorno después de completada,
978
     *          'percentWithReturning' => % de cápsulas con retorno después de completada,
558 stevensc 979
     *      ],
119 efrain 980
     * ]
981
     *
982
     *
983
     *  En caso contrario
984
     *  [
985
     *      'success' => false,
986
     *      'data' => mensaje de error
987
     *  ]
988
     *
989
     *
990
     * @return \Laminas\View\Model\JsonModel
991
     */
992
    public function progressAction()
993
    {
994
 
995
        $request = $this->getRequest();
996
        if($request->isGet()) {
997
            $currentUserPlugin = $this->plugin('currentUserPlugin');
998
            $currentUser = $currentUserPlugin->getUser();
999
 
1000
 
1001
            $accessGrantedIds = $this->getAccessGranted();
1002
            $id = $this->params()->fromRoute('id');
1003
 
1004
            $companyMapper = CompanyMapper::getInstance($this->adapter);
1005
            $company = $companyMapper->fetchOneByUuid($id);
1006
 
1007
            if(!$company) {
1008
                $response = [
1009
                    'success' => false,
1010
                    'data' => 'ERROR_COMPANY_NOT_FOUND',
1011
                ];
1012
 
1013
 
1014
                return new JsonModel($response);
1015
            }
1016
 
1017
            if(!in_array($company->id, $accessGrantedIds->companies)) {
1018
                $response = [
1019
                    'success' => false,
1020
                    'data' => 'ERROR_YOU_DO_NOT_HAVE_ACCESS_TO_THIS_COMPANY',
1021
                ];
1022
 
1023
 
1024
                return new JsonModel($response);
1025
            }
1026
 
1027
            $capsuleTotal              = 0;
1028
            $capsuleCompleted          = 0;
1029
            $capsuleWithReturning      = 0;
1030
            $capsuleWithoutReturning   = 0;
1031
            $capsuleStarted            = 0;
1032
            $capsuleToStart            = 0;
1033
            $percentCompleted          = 0;
1034
            $percentIncompleted        = 100;
1035
 
283 www 1036
            $topicMapper = MicrolearningTopicMapper::getInstance($this->adapter);
119 efrain 1037
            $topics = $topicMapper->fetchAllActiveByCompanyIdAndIds($company->id, $accessGrantedIds->topics);
1038
 
283 www 1039
            $progressMapper = MicrolearningUserProgressMapper::getInstance($this->adapter);
119 efrain 1040
 
302 www 1041
            $topicCapsuleMapper = MicrolearningTopicCapsuleMapper::getInstance($this->adapter);
119 efrain 1042
 
1043
            foreach($topics as $topic)
1044
            {
302 www 1045
                $resultCount = $topicCapsuleMapper->fetchCountByCompanyIdAndTopicId($company->id, $topic->id);
119 efrain 1046
                $capsuleTotal =  $capsuleTotal + $resultCount;
1047
 
1048
                $resultCount = $progressMapper->fetchCountCapsulesCompletedByIdAndTopicId($currentUser->id, $topic->id);
1049
                $capsuleCompleted = $capsuleCompleted + $resultCount;
1050
 
1051
                $resultCount = $progressMapper->fetchCountCapsulesCompletedWithReturningByIdAndTopicId($currentUser->id, $topic->id);
1052
                $capsuleWithReturning = $capsuleWithReturning + $resultCount;
1053
 
1054
                $resultCount = $progressMapper->fetchCountCapsulesCompletedWithoutReturningByIdAndTopicId($currentUser->id, $topic->id);
1055
                $capsuleWithoutReturning = $capsuleWithoutReturning + $resultCount;
1056
 
1057
                $resultCount = $progressMapper->fetchCountCapsulesCompletedByIdAndTopicId($currentUser->id, $topic->id);
1058
                $capsuleStarted = $capsuleStarted + $resultCount;
1059
            }
1060
 
1061
            $capsuleToStart = $capsuleTotal -  $capsuleStarted;
1062
 
1063
            if($capsuleTotal > 0) {
1064
                $percentCompleted = ($capsuleCompleted * 100) /  $capsuleTotal;
1065
                $percentIncompleted = 100 - $percentCompleted;
1066
            }
1067
 
1068
            return new JsonModel([
1069
                'success' => true,
1070
                'data' => [
1071
                    'capsuleTotal' => $capsuleTotal,
1072
                    'capsuleCompleted' => $capsuleCompleted,
1073
                    'capsuleStarted' => $capsuleStarted,
1074
                    'capsuleToStart' => $capsuleToStart,
1075
                    'percentCompleted' => number_format($percentCompleted, 2, '.', ','),
1076
                    'percentIncompleted' => number_format($percentIncompleted, 2, '.', ','),
1077
                    'capsuleWithReturning' => $capsuleWithReturning,
1078
                    'capsuleWithoutReturning' => $capsuleWithoutReturning,
1079
                ],
1080
            ]);
1081
 
1082
 
1083
        } else {
1084
            return new JsonModel([
1085
                'success' => false,
1086
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
1087
            ]);
1088
        }
1089
    }
1090
 
1091
 
1092
    public function topicsAction()
1093
    {
1094
        $request = $this->getRequest();
626 stevensc 1095
 
119 efrain 1096
        if($request->isGet()) {
1097
            $currentUserPlugin = $this->plugin('currentUserPlugin');
1098
            $currentUser = $currentUserPlugin->getUser();
1099
 
1100
            $data = [];
1101
            $accessGrantedIds = $this->getAccessGranted();
1102
 
283 www 1103
            $userProgressMapper = MicrolearningUserProgressMapper::getInstance($this->adapter);
1104
            $topicMapper = MicrolearningTopicMapper::getInstance($this->adapter);
119 efrain 1105
 
333 www 1106
            $storage = Storage::getInstance($this->config, $this->adapter);
283 www 1107
            $path = $storage->getPathMicrolearningTopic();
119 efrain 1108
 
1109
            foreach($accessGrantedIds->topics as $id)
1110
            {
1111
                $topic = $topicMapper->fetchOne($id);
1112
                if(!$topic) {
1113
                    continue;
1114
                }
1115
 
1116
                $userProgress = $userProgressMapper->fetchOneByUserIdAndTopicId($currentUser->id, $id);
1117
                if($userProgress) {
1118
                    $progress = $userProgress->progress;
1119
                    $completed = $userProgress->completed;
1120
                } else {
1121
                    $progress = 0;
1122
                    $completed = 0;
1123
                }
1124
 
1125
 
1126
 
1127
                array_push($data, [
164 efrain 1128
                    'uuid'          => $topic->uuid,
119 efrain 1129
                    'name'          => $topic->name ? $topic->name : '',
1130
                    'description'   => $topic->description ? $topic->description : '',
283 www 1131
                    'image'         => $topic->image ? $storage->getGenericImage($path, $topic->uuid, $topic->image) : '',
119 efrain 1132
                    'progress'      => $progress,
1133
                    'completed'     => $completed,
1134
                    'order'         => $topic->order,
1135
                    'added_on'      => $topic->added_on,
564 stevensc 1136
                    'updated_on'    => $topic->updated_on
119 efrain 1137
                ]);
1138
            }
1139
 
1140
            usort($data, function($a, $b) {
1141
 
1142
                $result =  $a['order'] <=> $b['order'];
1143
                if(0 == $result) {
1144
                    $result = strcasecmp($a['added_on'], $b['added_on']);
1145
                    if(0 == $result) {
1146
                        $result = strcasecmp($a['name'], $b['name']);
1147
                    }
1148
                }
1149
 
1150
                if($result < 0) {
1151
                    return 1;
1152
                } else if($result > 0) {
1153
                    return -1;
1154
                } else  {
1155
                    return  0;
1156
                }
1157
            });
1158
 
1159
 
1160
 
1161
                return new JsonModel([
1162
                    'success' => true,
1163
                    'data' => $data
1164
                ]);
1165
 
1166
        } else {
1167
            return new JsonModel([
1168
                'success' => false,
1169
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
1170
            ]);
1171
        }
1172
    }
1173
 
161 efrain 1174
    public function getTopicAction()
1175
    {
563 stevensc 1176
        // Handle GET request
161 efrain 1177
        $request = $this->getRequest();
1178
        if($request->isGet()) {
563 stevensc 1179
            // Get current user
161 efrain 1180
            $currentUserPlugin = $this->plugin('currentUserPlugin');
1181
            $currentUser = $currentUserPlugin->getUser();
563 stevensc 1182
 
1183
            // Get topic ID from route
161 efrain 1184
            $id = $this->params()->fromRoute('id');
283 www 1185
            $topicMapper = MicrolearningTopicMapper::getInstance($this->adapter);
161 efrain 1186
            $topic = $topicMapper->fetchOneByUuid($id);
563 stevensc 1187
 
1188
            // Return error if topic not found
161 efrain 1189
            if(!$topic) {
1190
                return new JsonModel([
1191
                    'success' => false,
1192
                    'data' => 'ERROR_TOPIC_NOT_FOUND'
1193
                ]);
1194
            }
563 stevensc 1195
 
1196
            // Check if current user has access to the topic
161 efrain 1197
            $accessGrantedIds = $this->getAccessGranted();
1198
            if(!in_array($topic->id, $accessGrantedIds->topics)) {
1199
                return new JsonModel([
1200
                    'success' => false,
1201
                    'data' => 'ERROR_YOU_DO_NOT_HAVE_ACCESS_TO_THIS_TOPIC'
1202
                ]);
1203
            }
563 stevensc 1204
 
1205
            // Get user progress for this topic
283 www 1206
            $userProgressMapper = MicrolearningUserProgressMapper::getInstance($this->adapter);
563 stevensc 1207
            $userProgress = $userProgressMapper->fetchOneByUserIdAndTopicId($currentUser->id, $topic->id);
161 efrain 1208
 
580 stevensc 1209
            $progress = $userProgress->progress ?? 0;
1210
            $completed = $userProgress->completed ?? 0;
563 stevensc 1211
 
1212
            // Initialize storage service to get image paths
333 www 1213
            $storage = Storage::getInstance($this->config, $this->adapter);
563 stevensc 1214
            $pathTopic = $storage->getPathMicrolearningTopic();
1215
 
1216
            // Fetch associated capsules using the private helper method
1217
            $capsulesData = $this->_getCapsulesByTopic($topic, $storage);
1218
 
1219
            // Prepare data for JSON response
161 efrain 1220
            $data = [
165 efrain 1221
                'uuid'          => $topic->uuid,
161 efrain 1222
                'name'          => $topic->name ? $topic->name : '',
1223
                'description'   => $topic->description ? $topic->description : '',
563 stevensc 1224
                'image'         => $topic->image ? $storage->getGenericImage($pathTopic, $topic->uuid, $topic->image) : '',
161 efrain 1225
                'progress'      => $progress,
1226
                'completed'     => $completed,
1227
                'order'         => $topic->order,
1228
                'added_on'      => $topic->added_on,
1229
                'updated_on'    => $topic->updated_on,
563 stevensc 1230
                'total_capsules' => count($capsulesData),
1231
                'capsules'      => $capsulesData,
161 efrain 1232
            ];
563 stevensc 1233
 
161 efrain 1234
            return new JsonModel([
1235
                'success' => true,
1236
                'data' => $data
1237
            ]);
563 stevensc 1238
 
161 efrain 1239
        } else {
563 stevensc 1240
            // Return error if not a GET request
161 efrain 1241
            return new JsonModel([
1242
                'success' => false,
1243
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
1244
            ]);
1245
        }
1246
    }
563 stevensc 1247
 
1248
    /**
580 stevensc 1249
     * @param MicrolearningTopic $topic The topic object.
1250
     * @param Storage $storage The storage object.
1251
     * @return array The capsules data.
563 stevensc 1252
     */
1253
    private function _getCapsulesByTopic($topic, $storage)
1254
    {
578 stevensc 1255
        $data = [];
584 stevensc 1256
        $accessGrantedIds = $this->getAccessGranted();
563 stevensc 1257
 
578 stevensc 1258
        if (!$topic) {
1259
            return $data;
1260
        }
1261
 
584 stevensc 1262
        if (!in_array($topic->id, $accessGrantedIds->topics)) {
578 stevensc 1263
            return $data;
584 stevensc 1264
        }
578 stevensc 1265
 
1266
        $currentUserPlugin = $this->plugin('currentUserPlugin');
1267
        $currentUser = $currentUserPlugin->getUser();
1268
 
1269
        $topicCapsuleMapper = MicrolearningTopicCapsuleMapper::getInstance($this->adapter);
574 stevensc 1270
        $topicCapsuleRelations = $topicCapsuleMapper->fetchAllActiveByTopicId($topic->id);
1271
 
581 stevensc 1272
        $userProgressMapper = MicrolearningUserProgressMapper::getInstance($this->adapter);
1273
        $capsuleCommentMapper = MicrolearningCapsuleCommentMapper::getInstance($this->adapter);
578 stevensc 1274
 
581 stevensc 1275
        $path = $storage->getPathMicrolearningCapsule();
1276
 
578 stevensc 1277
        foreach ($topicCapsuleRelations as $relation) {
640 stevensc 1278
            if(!in_array($relation->topic_id, $accessGrantedIds->topics)) {
584 stevensc 1279
                continue;
1280
            }
578 stevensc 1281
 
581 stevensc 1282
            $capsuleMapper = MicrolearningCapsuleMapper::getInstance($this->adapter);
1283
            $capsule = $capsuleMapper->fetchOne($relation->capsule_id);
563 stevensc 1284
 
581 stevensc 1285
            if(!$capsule) {
1286
                continue;
1287
            }
1288
 
578 stevensc 1289
            $userProgress = $userProgressMapper->fetchOneByUseridAndCapsuleId($currentUser->id, $capsule->id);
1290
            $progress = $userProgress->progress ?? 0;
1291
            $completed = $userProgress->completed ?? 0;
1292
            $dataCountAndRatingAverage = $capsuleCommentMapper->fetchCountAndRatingAverage($capsule->company_id, $capsule->id);
1293
            $image = $capsule->image ? $storage->getGenericImage($path, $capsule->uuid, $capsule->image) : '';
1294
            $total_comments = strval($dataCountAndRatingAverage['total_comments']);
1295
            $total_rating = strval($dataCountAndRatingAverage['total_rating']);
1296
 
581 stevensc 1297
            array_push($data, [
578 stevensc 1298
                'uuid'              => $capsule->uuid,
1299
                'name'              => $capsule->name ? $capsule->name : '',
1300
                'description'       => $capsule->description ? $capsule->description : '',
1301
                'image'             => $image,
1302
                'total_comments'    => $total_comments,
1303
                'total_rating'      => $total_rating,
1304
                'progress'          => $progress,
1305
                'completed'         => $completed,
1306
                'added_on'          => $capsule->added_on,
1307
                'updated_on'        => $capsule->updated_on,
581 stevensc 1308
            ]);
563 stevensc 1309
        }
578 stevensc 1310
 
581 stevensc 1311
        return $data;
563 stevensc 1312
    }
586 stevensc 1313
 
1314
    /**
1315
     * @param MicrolearningCapsule $capsule The capsule object.
1316
     * @param Storage $storage The storage object.
1317
     * @return array The slides data.
1318
     */
1319
    private function _getSlidesByCapsule($capsule, $storage)
1320
    {
1321
        $data = [];
1322
        $accessGrantedIds = $this->getAccessGranted();
1323
 
1324
        if (!$capsule) {
1325
            return $data;
1326
        }
1327
 
1328
        if (!in_array($capsule->id, $accessGrantedIds->capsules)) {
1329
            return $data;
1330
        }
1331
 
1332
        $currentUserPlugin = $this->plugin('currentUserPlugin');
1333
        $currentUser = $currentUserPlugin->getUser();
1334
 
1335
        $slideMapper = MicrolearningSlideMapper::getInstance($this->adapter);
1336
        $userProgressMapper = MicrolearningUserProgressMapper::getInstance($this->adapter);
1337
        $quizMapper = MicrolearningQuizMapper::getInstance($this->adapter);
1338
 
1339
        $path = $storage->getPathMicrolearningSlide();
587 stevensc 1340
        $slides = $slideMapper->fetchAllByCompanyIdAndCapsuleId($capsule->company_id, $capsule->id);
586 stevensc 1341
 
1342
        foreach ($slides as $slide) {
1343
            $userProgress = $userProgressMapper->fetchOneByUserIdAndSlideId($currentUser->id, $slide->id);
1344
            $completed = $userProgress ? $userProgress->completed : 0;
1345
 
1346
            $quiz_uuid = '';
1347
            $quiz_data = [];
1348
            $link_take_a_test = '';
1349
 
1350
            if ($slide->quiz_id) {
1351
                $quiz = $quizMapper->fetchOne($slide->quiz_id);
1352
                if ($quiz) {
1353
                    $quiz_uuid = $quiz->uuid;
1354
                    $quiz_data = $this->getQuiz($slide->quiz_id);
1355
                    $link_take_a_test = $this->url()->fromRoute('microlearning/take-a-test', ['slide_id' => $slide->uuid], ['force_canonical' => true]);
1356
                }
1357
            }
1358
 
1359
            array_push($data, [
1360
                'quiz'                  => $quiz_uuid,
1361
                'quiz_data'             => $quiz_data,
1362
                'uuid'                  => $slide->uuid,
1363
                'name'                  => $slide->name ? $slide->name : '',
1364
                'description'           => $slide->description ? $slide->description : '',
1365
                'type'                  => $slide->type,
1366
                'background'            => $slide->background ? $storage->getGenericImage($path, $slide->uuid, $slide->background) : '',
1367
                'file'                  => $slide->file ? $storage->getGenericFile($path, $slide->uuid, $slide->file) : '',
1368
                'order'                 => $slide->order,
1369
                'completed'             => $completed,
1370
                'link_take_a_test'      => $link_take_a_test,
1371
                'added_on'              => $slide->added_on,
1372
                'updated_on'            => $slide->updated_on,
1373
            ]);
1374
        }
1375
 
1376
        // Sort slides by order, then by added_on, then by name
1377
        usort($data, function($a, $b) {
1378
            $result = $a['order'] <=> $b['order'];
1379
            if (0 == $result) {
1380
                $result = strcasecmp($a['added_on'], $b['added_on']);
1381
                if (0 == $result) {
1382
                    $result = strcasecmp($a['name'], $b['name']);
1383
                }
1384
            }
1385
 
1386
            if ($result < 0) {
1387
                return 1;
1388
            } else if ($result > 0) {
1389
                return -1;
1390
            } else {
1391
                return 0;
1392
            }
1393
        });
1394
 
1395
        return $data;
1396
    }
1397
 
119 efrain 1398
    public function capsulesAction()
1399
    {
1400
        $request = $this->getRequest();
1401
        if($request->isGet()) {
580 stevensc 1402
            $currentUserPlugin = $this->plugin('currentUserPlugin');
1403
            $currentUser = $currentUserPlugin->getUser();
584 stevensc 1404
 
1405
            $topic_id_param = $this->params()->fromRoute('topic_id');
283 www 1406
            $topicMapper = MicrolearningTopicMapper::getInstance($this->adapter);
580 stevensc 1407
            $topic = $topicMapper->fetchOneByUuid($topic_id_param);
584 stevensc 1408
 
119 efrain 1409
            if(!$topic) {
1410
                return new JsonModel([
1411
                    'success' => false,
1412
                    'data' => 'ERROR_TOPIC_NOT_FOUND'
1413
                ]);
1414
            }
584 stevensc 1415
 
580 stevensc 1416
            $accessGrantedIds = $this->getAccessGranted();
584 stevensc 1417
 
119 efrain 1418
            if(!in_array($topic->id, $accessGrantedIds->topics)) {
1419
                return new JsonModel([
1420
                    'success' => false,
1421
                    'data' => 'ERROR_YOU_DO_NOT_HAVE_ACCESS_TO_THIS_TOPIC'
1422
                ]);
1423
            }
584 stevensc 1424
 
333 www 1425
            $storage = Storage::getInstance($this->config, $this->adapter);
584 stevensc 1426
            // Use the _getCapsulesByTopic method to fetch capsules
1427
            $data = $this->_getCapsulesByTopic($topic, $storage);
580 stevensc 1428
 
584 stevensc 1429
            // The _getCapsulesByTopic method already returns capsules with the required data structure.
1430
            // We just need to sort them.
1431
 
580 stevensc 1432
            usort($data, function($a, $b) {
584 stevensc 1433
 
580 stevensc 1434
                $result =  $a['order'] <=> $b['order'];
1435
                if(0 == $result) {
1436
                    $result = strcasecmp($a['added_on'], $b['added_on']);
1437
                    if(0 == $result) {
1438
                        $result = strcasecmp($a['name'], $b['name']);
1439
                    }
1440
                }
584 stevensc 1441
 
580 stevensc 1442
                if($result < 0) {
1443
                    return 1;
1444
                } else if($result > 0) {
1445
                    return -1;
1446
                } else  {
1447
                    return  0;
1448
                }
1449
            });
584 stevensc 1450
 
1451
            return new JsonModel([
1452
                'success' => true,
1453
                'data' => $data
1454
            ]);
1455
 
119 efrain 1456
        } else {
1457
            return new JsonModel([
1458
                'success' => false,
1459
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
1460
            ]);
1461
        }
1462
    }
1463
 
235 efrain 1464
    public function takeTestAction()
1465
    {
1466
        $request = $this->getRequest();
1467
        if($request->isPost()) {
1468
            $currentUserPlugin = $this->plugin('currentUserPlugin');
1469
            $currentUser = $currentUserPlugin->getUser();
1470
 
1471
            $slide_id = $this->params()->fromRoute('slide_id');
283 www 1472
            $slideMapper = MicrolearningSlideMapper::getInstance($this->adapter);
235 efrain 1473
            $slide = $slideMapper->fetchOneByUuid($slide_id);
1474
 
1475
            if(!$slide) {
1476
                return new JsonModel([
1477
                    'success' => false,
1478
                    'data' => 'ERROR_SLIDE_NOT_FOUND'
1479
                ]);
1480
            }
1481
 
283 www 1482
            if($slide->type != MicrolearningSlide::TYPE_QUIZ) {
235 efrain 1483
                return new JsonModel([
1484
                    'success' => false,
1485
                    'data' => 'ERROR_SLIDE_IS_NOT_QUIZ'
1486
                ]);
1487
            }
1488
 
1489
 
1490
 
283 www 1491
            $capsuleMapper = MicrolearningCapsuleMapper::getInstance($this->adapter);
235 efrain 1492
            $capsule = $capsuleMapper->fetchOne($slide->capsule_id);
1493
 
1494
            if(!$capsule) {
1495
                return new JsonModel([
1496
                    'success' => false,
1497
                    'data' => 'ERROR_CAPSULE_NOT_FOUND'
1498
                ]);
1499
            }
1500
 
1501
            $accessGrantedIds = $this->getAccessGranted();
1502
 
1503
            if(!in_array($capsule->id, $accessGrantedIds->capsules)) {
1504
                return new JsonModel([
1505
                    'success' => false,
1506
                    'data' => 'ERROR_YOU_DO_NOT_HAVE_ACCESS_TO_THIS_CAPSULE'
1507
                ]);
1508
            }
1509
 
283 www 1510
            $userLogMapper = MicrolearningUserLogMapper::getInstance($this->adapter);
235 efrain 1511
            $userLog = $userLogMapper->fetchOneTakeATestByUserIdAndSlideId($currentUser->id, $slide->id);
1512
 
1513
            if($userLog) {
283 www 1514
                $activity = MicrolearningUserLog::ACTIVITY_RETAKE_A_TEST;
235 efrain 1515
            } else {
283 www 1516
                $activity = MicrolearningUserLog::ACTIVITY_TAKE_A_TEST;
235 efrain 1517
            }
1518
 
1519
            $added_on = $userLogMapper->getDatebaseNow();
1520
 
283 www 1521
            $userLog = new MicrolearningUserLog();
235 efrain 1522
            $userLog->activity      = $activity;
1523
            $userLog->user_id       = $currentUser->id;
1524
            $userLog->company_id    = $slide->company_id;
1525
            $userLog->topic_id      = $slide->topic_id;
1526
            $userLog->capsule_id    = $slide->capsule_id;
1527
            $userLog->slide_id      = $slide->id;
1528
            $userLog->added_on      = $added_on;
1529
 
1530
            if($userLogMapper->insert($userLog)) {
1531
                return new JsonModel([
1532
                    'success' => true,
1533
                ]);
1534
            } else {
1535
                return new JsonModel([
1536
                    'success' => false,
1537
                    'data' => $userLogMapper->getError()
1538
                ]);
1539
            }
1540
 
1541
 
1542
 
1543
 
1544
 
1545
 
1546
 
1547
        } else {
1548
            return new JsonModel([
1549
                'success' => false,
1550
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
1551
            ]);
1552
        }
1553
    }
1554
 
161 efrain 1555
    public function getCapsuleAction()
1556
    {
1557
        $request = $this->getRequest();
587 stevensc 1558
 
161 efrain 1559
        if($request->isGet()) {
1560
            $currentUserPlugin = $this->plugin('currentUserPlugin');
1561
            $currentUser = $currentUserPlugin->getUser();
1562
 
558 stevensc 1563
            $capsule_uuid = $this->params()->fromRoute('id');
283 www 1564
            $capsuleMapper = MicrolearningCapsuleMapper::getInstance($this->adapter);
642 stevensc 1565
 
558 stevensc 1566
            $capsule = $capsuleMapper->fetchOneByUuid($capsule_uuid);
161 efrain 1567
            if(!$capsule) {
1568
                return new JsonModel([
1569
                    'success' => false,
1570
                    'data' => 'ERROR_CAPSULE_NOT_FOUND'
1571
                ]);
1572
            }
1573
 
1574
            $accessGrantedIds = $this->getAccessGranted();
1575
 
642 stevensc 1576
            if(!in_array($capsule->id, $accessGrantedIds->capsules)) {
161 efrain 1577
                return new JsonModel([
1578
                    'success' => false,
1579
                    'data' => 'ERROR_YOU_DO_NOT_HAVE_ACCESS_TO_THIS_CAPSULE'
1580
                ]);
1581
            }
1582
 
283 www 1583
            $userProgressMapper = MicrolearningUserProgressMapper::getInstance($this->adapter);
1584
            $capsuleCommentMapper = MicrolearningCapsuleCommentMapper::getInstance($this->adapter);
161 efrain 1585
 
1586
            $userProgress = $userProgressMapper->fetchOneByUseridAndCapsuleId($currentUser->id, $capsule->id);
587 stevensc 1587
            $progress = $userProgress->progress ?? 0;
1588
            $completed = $userProgress->completed ?? 0;
244 efrain 1589
 
586 stevensc 1590
            $dataCountAndRatingAverage = $capsuleCommentMapper->fetchCountAndRatingAverage($capsule->company_id, $capsule->id);
244 efrain 1591
 
587 stevensc 1592
            // Get comments data
1593
            $userMapper = UserMapper::getInstance($this->adapter);
333 www 1594
            $storage = Storage::getInstance($this->config, $this->adapter);
587 stevensc 1595
            $serviceDatetimeFormat = $this->config['leaderslinked.services.datetime'];
1596
 
1597
            $comments = [];
1598
            $records = $capsuleCommentMapper->fetchAllByCapsuleId($capsule->id);
1599
            foreach($records as $record) {
1600
                $user = $userMapper->fetchOne($record->user_id);
1601
                if(!$user) {
1602
                    continue;
1603
                }
1604
 
1605
                $dt = \DateTime::createFromFormat('Y-m-d H:i:s', $record->added_on);
1606
 
1607
                array_push($comments, [
597 stevensc 1608
                    'uuid' => $record->uuid,
587 stevensc 1609
                    'date' => $dt->format($serviceDatetimeFormat),
1610
                    'image' => $storage->getUserImage($user),
1611
                    'fullname' => trim(trim($user->first_name) . ' ' . trim($user->last_name)),
1612
                    'rating' => strval($record->rating),
1613
                    'comment' => $record->comment,
597 stevensc 1614
                    '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]) : ''
587 stevensc 1615
                ]);
1616
            }
1617
 
283 www 1618
            $path = $storage->getPathMicrolearningCapsule();
244 efrain 1619
 
586 stevensc 1620
            $slides = $this->_getSlidesByCapsule($capsule, $storage);
645 stevensc 1621
            $image = $storage->getGenericImage($path, $capsule->uuid, $capsule->image);
586 stevensc 1622
 
161 efrain 1623
            $data = [
586 stevensc 1624
                'uuid'              => $capsule->uuid,
641 stevensc 1625
                'name'              => $capsule->name ?? '',
1626
                'description'       => $capsule->description ?? '',
645 stevensc 1627
                'image'             => $image,
586 stevensc 1628
                'link_comment_add'  => $this->url()->fromRoute('microlearning/capsules-comments/add', ['capsule_id' => $capsule->uuid], ['force_canonical' => true]),
1629
                'total_comments'    => strval($dataCountAndRatingAverage['total_comments']),
1630
                'total_rating'      => strval($dataCountAndRatingAverage['total_rating']),
587 stevensc 1631
                'comments'          => $comments,
586 stevensc 1632
                'progress'          => $progress,
1633
                'completed'         => $completed,
1634
                'total_slides'      => count($slides),
1635
                'slides'            => $slides,
1636
                'added_on'          => $capsule->added_on,
1637
                'updated_on'        => $capsule->updated_on,
161 efrain 1638
            ];
586 stevensc 1639
 
161 efrain 1640
            return new JsonModel([
1641
                'success' => true,
1642
                'data' => $data
1643
            ]);
1644
        }
586 stevensc 1645
 
1646
        return new JsonModel([
1647
            'success' => false,
1648
            'data' => 'ERROR_METHOD_NOT_ALLOWED'
1649
        ]);
161 efrain 1650
    }
1651
 
119 efrain 1652
    public function slidesAction()
1653
    {
1654
        $request = $this->getRequest();
1655
        if($request->isGet()) {
1656
            $currentUserPlugin = $this->plugin('currentUserPlugin');
1657
            $currentUser = $currentUserPlugin->getUser();
1658
 
1659
 
1660
 
1661
            $topic_id = $this->params()->fromRoute('topic_id');
283 www 1662
            $topicMapper = MicrolearningTopicMapper::getInstance($this->adapter);
119 efrain 1663
            $topic = $topicMapper->fetchOneByUuid($topic_id);
1664
 
1665
            if(!$topic) {
1666
                return new JsonModel([
1667
                    'success' => false,
1668
                    'data' => 'ERROR_TOPIC_NOT_FOUND'
1669
                ]);
1670
            }
1671
 
1672
            $accessGrantedIds = $this->getAccessGranted();
1673
 
1674
            if(!in_array($topic->id, $accessGrantedIds->topics)) {
1675
                return new JsonModel([
1676
                    'success' => false,
1677
                    'data' => 'ERROR_YOU_DO_NOT_HAVE_ACCESS_TO_THIS_TOPIC'
1678
                ]);
1679
            }
1680
 
1681
            $capsule_id = $this->params()->fromRoute('capsule_id');
283 www 1682
            $capsuleMapper = MicrolearningCapsuleMapper::getInstance($this->adapter);
119 efrain 1683
            $capsule = $capsuleMapper->fetchOneByUuid($capsule_id);
1684
 
1685
            if(!$capsule) {
1686
                return new JsonModel([
1687
                    'success' => false,
1688
                    'data' => 'ERROR_CAPSULE_NOT_FOUND'
1689
                ]);
1690
            }
1691
 
1692
 
1693
 
1694
            if(!in_array($capsule->id, $accessGrantedIds->capsules)) {
1695
                return new JsonModel([
1696
                    'success' => false,
1697
                    'data' => 'ERROR_YOU_DO_NOT_HAVE_ACCESS_TO_THIS_CAPSULE'
1698
                ]);
1699
            }
1700
 
1701
 
1702
 
1703
            $data = [];
1704
 
283 www 1705
            $quizMapper = MicrolearningQuizMapper::getInstance($this->adapter);
119 efrain 1706
 
283 www 1707
            $slideMapper = MicrolearningSlideMapper::getInstance($this->adapter);
1708
            $userProgressMapper = MicrolearningUserProgressMapper::getInstance($this->adapter);
119 efrain 1709
 
333 www 1710
            $storage = Storage::getInstance($this->config, $this->adapter);
283 www 1711
            $path = $storage->getPathMicrolearningSlide();
119 efrain 1712
 
1713
            $slides = $slideMapper->fetchAllByCompanyIdAndTopicIdAndCapsuleId($capsule->company_id, $capsule->topic_id, $capsule->id);
1714
            foreach($slides as $slide)
1715
            {
1716
 
1717
 
1718
                $userProgress = $userProgressMapper->fetchOneByUserIdAndSlideId($currentUser->id, $slide->id);
1719
                if($userProgress) {
224 efrain 1720
                    $completed =  $userProgress->completed ;
119 efrain 1721
                } else {
1722
                    $completed = 0;
1723
                }
1724
 
235 efrain 1725
 
230 efrain 1726
 
235 efrain 1727
                $link_take_a_test = '';
230 efrain 1728
                if($slide->quiz_id) {
235 efrain 1729
 
283 www 1730
                    $quizMapper = MicrolearningQuizMapper::getInstance($this->adapter);
230 efrain 1731
                    $quiz = $quizMapper->fetchOne($slide->quiz_id);
1732
                    if($quiz) {
1733
                        $quiz_uuid = $quiz->uuid;
235 efrain 1734
                        $quiz_data = $this->getQuiz($slide->quiz_id);
1735
                        $link_take_a_test = $this->url()->fromRoute('microlearning/take-a-test', ['slide_id' => $slide->uuid], ['force_canonical' => true]);
230 efrain 1736
                    }
235 efrain 1737
 
1738
                }
119 efrain 1739
 
1740
 
1741
                array_push($data, [
235 efrain 1742
                    'quiz'                  => $quiz_uuid,
1743
                    'quiz_data'             => $quiz_data,
1744
                    'uuid'                  => $slide->uuid,
1745
                    'name'                  => $slide->name ? $slide->name : '',
1746
                    'description'           => $slide->description ? $slide->description : '',
1747
                    'type'                  => $slide->type,
283 www 1748
                    'background'            => $slide->background ? $storage->getGenericImage($path, $slide->uuid, $slide->background) : '',
1749
                    'file'                  => $slide->file ? $storage->getGenericFile($path, $slide->uuid, $slide->file) : '',
235 efrain 1750
                    'order'                 => $slide->order,
1751
                    'completed'             => $completed,
236 efrain 1752
                    'link_take_a_test'      => $link_take_a_test,
235 efrain 1753
                    'added_on'              => $slide->added_on,
1754
                    'updated_on'            => $slide->updated_on,
119 efrain 1755
                ]);
1756
 
1757
 
1758
 
1759
            }
1760
 
1761
            usort($data, function($a, $b) {
1762
 
1763
                $result =  $a['order'] <=> $b['order'];
1764
                if(0 == $result) {
1765
                    $result = strcasecmp($a['added_on'], $b['added_on']);
1766
                    if(0 == $result) {
1767
                        $result = strcasecmp($a['name'], $b['name']);
1768
                    }
1769
                }
1770
 
1771
                if($result < 0) {
1772
                    return 1;
1773
                } else if($result > 0) {
1774
                    return -1;
1775
                } else  {
1776
                    return  0;
1777
                }
1778
            });
1779
 
1780
 
1781
 
1782
                return new JsonModel([
1783
                    'success' => true,
1784
                    'data' => $data
1785
                ]);
1786
 
1787
        } else {
1788
            return new JsonModel([
1789
                'success' => false,
1790
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
1791
            ]);
1792
        }
1793
    }
1794
 
229 efrain 1795
    private function getQuiz($id)
1796
    {
1797
        $serviceDatetimeFormat = $this->config['leaderslinked.services.datetime'];
1798
 
1799
        $data = [];
1800
 
283 www 1801
        $quizMapper = MicrolearningQuizMapper::getInstance($this->adapter);
229 efrain 1802
        $quiz = $quizMapper->fetchOne($id);
1803
 
1804
        if(!$quiz) {
1805
            return [];
1806
        }
1807
 
1808
        $companyMapper = CompanyMapper::getInstance($this->adapter);
1809
        $company = $companyMapper->fetchOne($quiz->company_id);
1810
 
283 www 1811
        $questionMapper = MicrolearningQuestionMapper::getInstance($this->adapter);
1812
        $answerMapper = MicrolearningAnswerMapper::getInstance($this->adapter);
229 efrain 1813
 
1814
        $record_questions = [];
1815
        $questions = $questionMapper->fetchAllByQuizId($quiz->id);
1816
        foreach($questions as $question)
1817
        {
1818
            $record_answers = [];
1819
 
1820
            $answers = $answerMapper->fetchAllByQuizIdAndQuestionId($question->quiz_id, $question->id);
1821
            foreach($answers as $answer)
1822
            {
1823
                $dtAddedOn = \DateTime::createFromFormat('Y-m-d H:i:s', $answer->added_on);
1824
                $dtUpdatedOn = \DateTime::createFromFormat('Y-m-d H:i:s', $answer->updated_on);
1825
 
1826
                array_push($record_answers, [
1827
                    'uuid' => $answer->uuid,
1828
                    'text' => trim($answer->text),
1829
                    'correct' => $answer->correct ? $answer->correct  : 0 ,
1830
                    'points' => strval(intval($answer->points, 10)),
1831
                    'added_on'  => $dtAddedOn->format($serviceDatetimeFormat),
1832
                    'updated_on'    => $dtUpdatedOn->format($serviceDatetimeFormat),
1833
                ]);
1834
            }
1835
 
1836
            $dtAddedOn = \DateTime::createFromFormat('Y-m-d H:i:s', $question->added_on);
1837
            $dtUpdatedOn = \DateTime::createFromFormat('Y-m-d H:i:s', $question->updated_on);
1838
 
1839
            array_push($record_questions, [
1840
                'uuid'          => $question->uuid,
1841
                'text'          => trim($question->text),
1842
                'type'          => $question->type,
1843
                'maxlength'     => strval($question->maxlength),
1844
                'points'        => strval($question->points),
1845
                'answers'       => $record_answers,
1846
                'added_on'      => $dtAddedOn->format($serviceDatetimeFormat),
1847
                'updated_on'    => $dtUpdatedOn->format($serviceDatetimeFormat),
1848
            ]);
1849
        }
1850
 
645 stevensc 1851
        $storage = Storage::getInstance($this->config, $this->adapter);
229 efrain 1852
        $dtAddedOn = \DateTime::createFromFormat('Y-m-d H:i:s', $quiz->added_on);
1853
        $dtUpdatedOn = \DateTime::createFromFormat('Y-m-d H:i:s', $quiz->updated_on);
1854
 
1855
        array_push($data, [
1856
            'uuid' => $quiz->uuid,
1857
            'name' => $quiz->name,
1858
            'text' => trim($quiz->text ? $quiz->text : ''),
1859
            'failed' => trim($quiz->failed ? $quiz->failed : ''),
1860
            'points' => strval($quiz->points),
1861
            'minimum_points_required' => strval($quiz->minimum_points_required),
1862
            'max_time' => $quiz->max_time ? $quiz->max_time : 5,
1863
            'company_uuid' => $company->uuid,
1864
            'company_name' => $company->name,
645 stevensc 1865
            'company_image' => $storage->getCompanyImage($company),
229 efrain 1866
            'questions'     => $record_questions,
1867
            'added_on'      => $dtAddedOn->format($serviceDatetimeFormat),
1868
            'updated_on'    => $dtUpdatedOn->format($serviceDatetimeFormat),
1869
        ]);
1870
 
1871
        return $data;
1872
 
1873
    }
161 efrain 1874
 
229 efrain 1875
 
161 efrain 1876
    public function getSlideAction()
1877
    {
1878
        $request = $this->getRequest();
1879
        if($request->isGet()) {
1880
            $currentUserPlugin = $this->plugin('currentUserPlugin');
1881
            $currentUser = $currentUserPlugin->getUser();
1882
 
1883
            $id = $this->params()->fromRoute('id');
283 www 1884
            $slideMapper = MicrolearningSlideMapper::getInstance($this->adapter);
161 efrain 1885
            $slide = $slideMapper->fetchOneByUuid($id);
1886
 
1887
            if(!$slide) {
1888
                return new JsonModel([
1889
                    'success' => false,
1890
                    'data' => 'ERROR_SLIDE_NOT_FOUND'
1891
                ]);
1892
            }
1893
 
1894
            $accessGrantedIds = $this->getAccessGranted();
1895
 
1896
 
1897
 
1898
            if(!in_array($slide->capsule_id, $accessGrantedIds->capsules)) {
1899
                return new JsonModel([
1900
                    'success' => false,
1901
                    'data' => 'ERROR_YOU_DO_NOT_HAVE_ACCESS_TO_THIS_CAPSULE'
1902
                ]);
1903
            }
1904
 
283 www 1905
            $slideMapper = MicrolearningSlideMapper::getInstance($this->adapter);
1906
            $userProgressMapper = MicrolearningUserProgressMapper::getInstance($this->adapter);
161 efrain 1907
 
1908
            $userProgress = $userProgressMapper->fetchOneByUserIdAndSlideId($currentUser->id, $slide->id);
1909
            if($userProgress) {
1910
                $completed = $userProgress->completed;
1911
            } else {
1912
                $completed = 0;
1913
            }
235 efrain 1914
 
1915
            $quiz_uuid = '';
1916
            $quiz_data = [];
1917
            $link_take_a_test = '';
1918
            if($slide->quiz_id) {
1919
 
283 www 1920
                $quizMapper = MicrolearningQuizMapper::getInstance($this->adapter);
235 efrain 1921
                $quiz = $quizMapper->fetchOne($slide->quiz_id);
1922
                if($quiz) {
1923
                    $quiz_uuid = $quiz->uuid;
1924
                    $quiz_data = $this->getQuiz($slide->quiz_id);
1925
                    $link_take_a_test = $this->url()->fromRoute('microlearning/take-a-test', ['slide_id' => $slide->uuid], ['force_canonical' => true]);
1926
                }
161 efrain 1927
 
235 efrain 1928
            }
161 efrain 1929
 
333 www 1930
            $storage = Storage::getInstance($this->config, $this->adapter);
283 www 1931
            $path = $storage->getPathMicrolearningSlide();
618 stevensc 1932
 
1933
            $image = $storage->getGenericImage($path, $slide->uuid, $slide->background);
1934
            $file = $storage->getGenericFile($path, $slide->uuid, $slide->file);
161 efrain 1935
 
1936
            $data =[
235 efrain 1937
                'quiz'              => $quiz_uuid,
1938
                'quiz_data'         => $quiz_data,
1939
                'uuid'              => $slide->uuid,
1940
                'name'              => $slide->name ? $slide->name : '',
1941
                'description'       => $slide->description ? $slide->description : '',
1942
                'type'              => $slide->type,
618 stevensc 1943
                'background'        => $image,
1944
                'file'              => $file,
235 efrain 1945
                'order'             => $slide->order,
1946
                'completed'         => $completed,
1947
                'link_take_a_test'  => $link_take_a_test,
1948
                'added_on'          => $slide->added_on,
1949
                'updated_on'        => $slide->updated_on,
161 efrain 1950
            ];
1951
 
1952
            return new JsonModel([
1953
                'success' => true,
1954
                'data' => $data
1955
            ]);
1956
 
1957
        } else {
1958
            return new JsonModel([
1959
                'success' => false,
1960
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
1961
            ]);
1962
        }
1963
    }
1964
 
119 efrain 1965
    public function profileAction()
1966
    {
1967
        $request = $this->getRequest();
1968
        if($request->isGet()) {
1969
            $currentUserPlugin = $this->plugin('currentUserPlugin');
1970
            $currentUser = $currentUserPlugin->getUser();
1971
 
1972
 
1973
            $accessGrantedIds = $this->getAccessGranted();
1974
 
1975
            $companyMapper = CompanyMapper::getInstance($this->adapter);
283 www 1976
            $companyExtendUserMapper = MicrolearningExtendUserMapper::getInstance($this->adapter);
1977
            $companyExtendUserCompanyMapper = MicrolearningExtendUserCompanyMapper::getInstance($this->adapter);
1978
            $companyExtendUserFunctionMapper = MicrolearningExtendUserFunctionMapper::getInstance($this->adapter);
1979
            $companyExtendUserGroupMapper = MicrolearningExtendUserGroupMapper::getInstance($this->adapter);
1980
            $companyExtendUserInstitutionMapper = MicrolearningExtendUserInstitutionMapper::getInstance($this->adapter);
1981
            $companyExtendUserPartnerMapper = MicrolearningExtendUserPartnerMapper::getInstance($this->adapter);
1982
            $companyExtendUserProgramMapper = MicrolearningExtendUserProgramMapper::getInstance($this->adapter);
1983
            $companyExtendUserStudentTypeMapper = MicrolearningExtendUserStudentTypeMapper::getInstance($this->adapter);
1984
            $companyExtendUserSectorMapper = MicrolearningExtendUserSectorMapper::getInstance($this->adapter);
119 efrain 1985
 
333 www 1986
            $storage = Storage::getInstance($this->config, $this->adapter);
283 www 1987
 
119 efrain 1988
 
1989
            $data = [];
1990
            foreach($accessGrantedIds->companies as $company_id)
1991
            {
1992
                $company = $companyMapper->fetchOne($company_id);
1993
                if(!$company) {
1994
                    continue;
1995
                }
1996
 
1997
                $record = [
1998
                    'name' => $company->name,
283 www 1999
                    'image' => $storage->getCompanyImage($company),
119 efrain 2000
                    'details' => [],
2001
                ];
2002
 
2003
                $companyExtendUser = $companyExtendUserMapper->fetchOneByCompanyIdAndUserId($company->id, $currentUser->id);
2004
                if(!$companyExtendUser) {
2005
                    continue;
2006
                }
2007
 
2008
                if($companyExtendUser->extend_company_id) {
2009
 
2010
                    $extendedCompany = $companyExtendUserCompanyMapper->fetchOne($companyExtendUser->company_id);
2011
                    if($extendedCompany) {
2012
                        array_push($record['details'],[
2013
                            'uuid' => $extendedCompany->uuid,
2014
                            'label' => 'LABEL_COMPANY',
2015
                            'value' => $extendedCompany->name
2016
                        ]);
2017
                    }
2018
                }
2019
 
2020
                if($companyExtendUser->extend_function_id) {
2021
                    $extendedFunction = $companyExtendUserFunctionMapper->fetchOne($companyExtendUser->extend_function_id);
2022
                    if($extendedFunction) {
2023
                        array_push($record['details'],[
2024
                            'uuid' => $extendedFunction->uuid,
2025
                            'label' => 'LABEL_FUNCTION',
2026
                            'value' => $extendedFunction->name
2027
                        ]);
2028
                    }
2029
                }
2030
 
2031
                if($companyExtendUser->extend_group_id) {
2032
                    $extendedGroup = $companyExtendUserGroupMapper->fetchOne($companyExtendUser->extend_group_id);
2033
                    if($extendedGroup) {
2034
                        array_push($record['details'],[
2035
                            'uuid' => $extendedGroup->uuid,
2036
                            'label' => 'LABEL_GROUP',
2037
                            'value' => $extendedGroup->name
2038
                        ]);
2039
                    }
2040
                }
2041
 
2042
                if($companyExtendUser->extend_institution_id) {
2043
                    $extendedInstitution= $companyExtendUserInstitutionMapper->fetchOne($companyExtendUser->extend_institution_id);
2044
                    if($extendedInstitution) {
2045
                        array_push($record['details'],[
2046
                            'uuid' => $extendedInstitution->uuid,
2047
                            'label' => 'LABEL_INSTITUTION',
2048
                            'value' => $extendedInstitution->name
2049
                        ]);
2050
                    }
2051
                }
2052
 
2053
                if($companyExtendUser->extend_program_id) {
2054
                    $extendedProgram = $companyExtendUserProgramMapper->fetchOne($companyExtendUser->extend_program_id);
2055
                    if($extendedProgram) {
2056
                        array_push($record['details'],[
2057
                            'uuid' => $extendedProgram->uuid,
2058
                            'label' => 'LABEL_PROGRAM',
2059
                            'value' => $extendedProgram->name
2060
                        ]);
2061
 
2062
                    }
2063
                }
2064
 
2065
                if($companyExtendUser->extend_sector_id) {
2066
                    $extendedSector = $companyExtendUserSectorMapper->fetchOne($companyExtendUser->extend_sector_id);
2067
                    if($extendedSector) {
2068
                        array_push($record['details'],[
2069
                            'uuid' => $extendedSector->uuid,
2070
                            'label' => 'LABEL_SECTOR',
2071
                            'value' => $extendedSector->name
2072
                        ]);
2073
                    }
2074
                }
2075
 
2076
                if($companyExtendUser->extend_partner_id) {
2077
                    $extendedPartner = $companyExtendUserPartnerMapper->fetchOne($companyExtendUser->extend_partner_id);
2078
                    if($extendedPartner) {
2079
                        array_push($record['details'],[
2080
                            'uuid' => $extendedPartner->uuid,
2081
                            'label' => 'LABEL_PARTNER',
2082
                            'value' => $extendedPartner->name
2083
                        ]);
2084
                    }
2085
                }
2086
 
2087
                if($companyExtendUser->extend_student_type_id) {
2088
                    $extendedStudentType = $companyExtendUserStudentTypeMapper->fetchOne($companyExtendUser->extend_student_type_id);
2089
                    if($extendedStudentType) {
2090
                        array_push($record['details'],[
2091
                            'uuid' => $extendedStudentType->uuid,
2092
                            'label' => 'LABEL_TYPE',
2093
                            'value' => $extendedStudentType->name
2094
                        ]);
2095
                    }
2096
                }
2097
 
2098
                array_push($data, $record);
2099
            }
2100
 
2101
            return new JsonModel([
2102
                'success' => true,
2103
                'data' => $data
2104
            ]);
2105
 
2106
        } else {
2107
            return new JsonModel([
2108
                'success' => false,
2109
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
2110
            ]);
2111
        }
2112
    }
649 stevensc 2113
 
119 efrain 2114
    /**
2115
     *
2116
     * @return \LeadersLinked\Controller\MicrolearningUserAccessGrantedIds
2117
     */
2118
    private function getAccessGranted()
2119
    {
2120
        $currentUserPlugin = $this->plugin('currentUserPlugin');
2121
        $currentUser = $currentUserPlugin->getUser();
2122
 
626 stevensc 2123
        $topicUserMapper = MicrolearningTopicUserMapper::getInstance($this->adapter);
640 stevensc 2124
        $topicCapsuleMapper = MicrolearningTopicCapsuleMapper::getInstance($this->adapter);
626 stevensc 2125
        $now = $topicUserMapper->getDatebaseNow();
119 efrain 2126
 
626 stevensc 2127
        $records = $topicUserMapper->fetchAllActiveByUserId($currentUser->id);
119 efrain 2128
 
2129
        $accessGrantedIds = new MicrolearningUserAccessGrantedIds();
2130
 
2131
        foreach($records as $record)
2132
        {
626 stevensc 2133
            if($record->access != MicrolearningTopicUser::ACCESS_UNLIMITED && $record->access != MicrolearningTopicUser::ACCESS_PAY_PERIOD) {
119 efrain 2134
                continue;
2135
            }
626 stevensc 2136
            if($record->access == MicrolearningTopicUser::ACCESS_PAY_PERIOD) {
119 efrain 2137
                if($now < $record->paid_from || $now > $record->paid_to) {
2138
                    continue;
2139
                }
2140
            }
626 stevensc 2141
 
2142
            // Verificar si la empresa está en la lista de empresas permitidas
119 efrain 2143
            if(!in_array($record->company_id, $accessGrantedIds->companies )) {
2144
                array_push($accessGrantedIds->companies, $record->company_id);
2145
            }
2146
 
626 stevensc 2147
            // Verificar si el tópico está en la lista de tópicos permitidos
119 efrain 2148
            if(!in_array($record->topic_id, $accessGrantedIds->topics )) {
2149
                array_push( $accessGrantedIds->topics, $record->topic_id);
2150
            }
640 stevensc 2151
 
2152
            // Verificar si la cápsula está en la lista de cápsulas permitidas
2153
            $topicCapsules = $topicCapsuleMapper->fetchAllActiveByTopicId($record->topic_id);
2154
            foreach($topicCapsules as $topicCapsule) {
2155
                if(!in_array($topicCapsule->capsule_id, $accessGrantedIds->capsules)) {
2156
                    array_push($accessGrantedIds->capsules, $topicCapsule->capsule_id);
2157
                }
2158
            }
119 efrain 2159
        }
2160
 
2161
        return $accessGrantedIds;
2162
    }
2163
 
590 stevensc 2164
    /**
657 stevensc 2165
     * Marks a slide as completed and updates progress for capsule and topic
2166
     *
2167
     * @return \Laminas\View\Model\JsonModel
2168
     */
2169
    public function markSlideCompletedAction()
2170
    {
2171
        $request = $this->getRequest();
2172
        if (!$request->isPost()) {
2173
            return new JsonModel(['success' => false, 'data' => 'ERROR_INVALID_REQUEST']);
2174
        }
2175
 
2176
        // Get parameters
2177
        $slide_uuid = $this->params()->fromRoute('slide_uuid');
2178
        if (empty($slide_uuid)) {
2179
            return new JsonModel(['success' => false, 'data' => 'ERROR_MISSING_PARAMETERS']);
2180
        }
2181
 
2182
        // Get current user
2183
        $currentUser = $this->plugin('currentUserPlugin')->getUser();
2184
        $user_id = $currentUser->id ?? null;
2185
        if (!$user_id) {
2186
            return new JsonModel(['success' => false, 'data' => 'ERROR_USER_NOT_FOUND']);
2187
        }
2188
 
2189
        // Get access permissions
2190
        $accessGrantedIds = $this->getAccessGranted();
2191
 
2192
        // Get slide
2193
        $slideMapper = MicrolearningSlideMapper::getInstance($this->adapter);
2194
        $slide = $slideMapper->fetchOneByUuid($slide_uuid);
2195
        if (!$slide) {
2196
            return new JsonModel(['success' => false, 'data' => 'ERROR_SLIDE_NOT_FOUND']);
2197
        }
2198
 
2199
        // Get capsule and verify access
2200
        $capsuleMapper = MicrolearningCapsuleMapper::getInstance($this->adapter);
2201
        $capsule = $capsuleMapper->fetchOne($slide->capsule_id);
2202
        if (!$capsule || !in_array($capsule->id, $accessGrantedIds->capsules)) {
2203
            return new JsonModel(['success' => false, 'data' => 'ERROR_CAPSULE_ACCESS_DENIED']);
2204
        }
2205
 
2206
        // Get topic-capsule relations
2207
        $topicCapsuleMapper = MicrolearningTopicCapsuleMapper::getInstance($this->adapter);
2208
        $relations = $topicCapsuleMapper->fetchAllByCapsuleId($capsule->id);
2209
        if (!$relations) {
2210
            return new JsonModel(['success' => false, 'data' => 'ERROR_CAPSULE_DOES_NOT_BELONG_TO_TOPIC']);
2211
        }
2212
 
2213
        $progressMapper = MicrolearningUserProgressMapper::getInstance($this->adapter);
658 stevensc 2214
 
661 stevensc 2215
        // Actualizar progreso
2216
        foreach ($relations as $relation) {
2217
            // Actualizar progreso de la diapositiva
662 stevensc 2218
            if(!$progressMapper->updateSlideProgress($user_id, $relation->company_id, $slide->id, $relation->capsule_id, $relation->topic_id)){
661 stevensc 2219
                $this->logger->err('Error updating slide progress: ' . $progressMapper->getError());
2220
                return new JsonModel(['success' => false, 'data' => 'ERROR_COULD_NOT_UPDATE_SLIDE_PROGRESS']);
2221
            }
657 stevensc 2222
 
661 stevensc 2223
            // Actualizar progreso de la cápsula
662 stevensc 2224
            if(!$progressMapper->updateCapsuleProgress($user_id, $relation->company_id, $slide->id, $relation->capsule_id, $relation->topic_id)){
659 stevensc 2225
                $this->logger->err('Error updating capsule progress: ' . $progressMapper->getError());
658 stevensc 2226
                return new JsonModel(['success' => false, 'data' => 'ERROR_COULD_NOT_UPDATE_CAPSULE_PROGRESS']);
657 stevensc 2227
            }
661 stevensc 2228
 
2229
            // Actualizar progreso del tópico
662 stevensc 2230
            if(!$progressMapper->updateTopicProgress($user_id, $relation->company_id, $slide->id, $relation->capsule_id, $relation->topic_id)){
659 stevensc 2231
                $this->logger->err('Error updating topic progress: ' . $progressMapper->getError());
658 stevensc 2232
                return new JsonModel(['success' => false, 'data' => 'ERROR_COULD_NOT_UPDATE_TOPIC_PROGRESS']);
657 stevensc 2233
            }
2234
        }
2235
 
658 stevensc 2236
        return new JsonModel(['success' => true, 'data' => "LABEL_THE_USER_PROGRESS_FOR_THIS_SLIDE_HAS_BEEN_COMPLETED"]);
657 stevensc 2237
    }
119 efrain 2238
}