Proyectos de Subversion LeadersLinked - Services

Rev

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