Proyectos de Subversion LeadersLinked - Services

Rev

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