Proyectos de Subversion LeadersLinked - Services

Rev

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