Proyectos de Subversion LeadersLinked - Services

Rev

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