Proyectos de Subversion LeadersLinked - Services

Rev

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

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