Proyectos de Subversion LeadersLinked - Services

Rev

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

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