Proyectos de Subversion LeadersLinked - Services

Rev

Rev 578 | Rev 580 | 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\MicrolearningCapsuleUserMapper;
14
use LeadersLinked\Mapper\MicrolearningCapsuleCommentMapper;
119 efrain 15
use LeadersLinked\Form\Service\CapsuleCommentForm;
283 www 16
use LeadersLinked\Model\MicrolearningCapsuleComment;
17
use LeadersLinked\Model\MicrolearningCapsuleUser;
18
use LeadersLinked\Model\MicrolearningAnswer;
19
use LeadersLinked\Mapper\MicrolearningUserProgressMapper;
20
use LeadersLinked\Mapper\MicrolearningSlideMapper;
21
use LeadersLinked\Mapper\MicrolearningUserLogMapper;
22
use LeadersLinked\Model\MicrolearningUserLog;
23
use LeadersLinked\Mapper\MicrolearningTopicMapper;
119 efrain 24
use LeadersLinked\Mapper\CompanyMapper;
283 www 25
use LeadersLinked\Model\MicrolearningUserProgress;
26
use LeadersLinked\Mapper\MicrolearningExtendUserMapper;
27
use LeadersLinked\Mapper\MicrolearningExtendUserCompanyMapper;
28
use LeadersLinked\Mapper\MicrolearningExtendUserFunctionMapper;
29
use LeadersLinked\Mapper\MicrolearningExtendUserGroupMapper;
30
use LeadersLinked\Mapper\MicrolearningExtendUserInstitutionMapper;
31
use LeadersLinked\Mapper\MicrolearningExtendUserPartnerMapper;
32
use LeadersLinked\Mapper\MicrolearningExtendUserProgramMapper;
33
use LeadersLinked\Mapper\MicrolearningExtendUserStudentTypeMapper;
34
use LeadersLinked\Mapper\MicrolearningExtendUserSectorMapper;
35
use LeadersLinked\Mapper\MicrolearningQuizMapper;
36
use LeadersLinked\Mapper\MicrolearningQuestionMapper;
37
use LeadersLinked\Mapper\MicrolearningAnswerMapper;
38
use LeadersLinked\Model\MicrolearningSlide;
39
use LeadersLinked\Library\Storage;
302 www 40
use LeadersLinked\Mapper\MicrolearningTopicCapsuleMapper;
119 efrain 41
 
42
 
43
class MicrolearningUserAccessGrantedIds
44
{
45
    public $companies;
46
    public $topics;
47
    public $capsules;
48
 
49
 
50
    public function __construct()
51
    {
52
        $this->companies    = [];
53
        $this->topics       = [];
54
        $this->capsules     = [];
55
    }
56
}
57
 
58
class MicrolearningController extends AbstractActionController
59
{
60
 
61
    /**
62
     *
63
     * @var \Laminas\Db\Adapter\AdapterInterface
64
     */
65
    private $adapter;
66
 
67
    /**
68
     *
69
     * @var \LeadersLinked\Cache\CacheInterface
70
     */
71
    private $cache;
72
 
73
 
74
    /**
75
     *
76
     * @var \Laminas\Log\LoggerInterface
77
     */
78
    private $logger;
79
 
80
    /**
81
     *
82
     * @var array
83
     */
84
    private $config;
85
 
86
 
87
    /**
88
     *
89
     * @var \Laminas\Mvc\I18n\Translator
90
     */
91
    private $translator;
92
 
93
 
94
    /**
95
     *
96
     * @param \Laminas\Db\Adapter\AdapterInterface $adapter
97
     * @param \LeadersLinked\Cache\CacheInterface $cache
98
     * @param \Laminas\Log\LoggerInterface LoggerInterface $logger
99
     * @param array $config
100
     * @param \Laminas\Mvc\I18n\Translator $translator
101
     */
102
    public function __construct($adapter, $cache, $logger, $config, $translator)
103
    {
104
        $this->adapter      = $adapter;
105
        $this->cache        = $cache;
106
        $this->logger       = $logger;
107
        $this->config       = $config;
108
        $this->translator   = $translator;
109
    }
110
 
111
    public function indexAction()
112
    {
113
        $request = $this->getRequest();
114
 
115
        if($request->isGet()) {
116
            return new JsonModel([
117
                'success' => true,
118
                'data' =>  [
119
                    'link_companies' => $this->url()->fromRoute('microlearning/companies',[], ['force_canonical' => true]),
120
                    'link_timeline' => $this->url()->fromRoute('microlearning/timeline',[], ['force_canonical' => true]),
121
                    'link_last_capsule_in_progress' => $this->url()->fromRoute('microlearning/last-capsule-in-progress',[], ['force_canonical' => true]),
122
                    'link_profile' => $this->url()->fromRoute('microlearning/profile',[], ['force_canonical' => true]),
123
                    'link_topics' => $this->url()->fromRoute('microlearning/topics',[], ['force_canonical' => true]),
124
                    'link_capsules_pending' => $this->url()->fromRoute('microlearning/capsules-pending',[], ['force_canonical' => true]),
125
                    'link_capsules_completed' => $this->url()->fromRoute('microlearning/capsules-completed',[], ['force_canonical' => true]),
126
                    'link_capsules_in_progress' => $this->url()->fromRoute('microlearning/capsules-in-progress',[], ['force_canonical' => true]),
127
 
128
 
129
                ]
130
            ]);
131
        }
132
 
133
        return new JsonModel([
134
            'success' => false,
135
            'data' => 'ERROR_METHOD_NOT_ALLOWED'
136
        ]);
137
    }
138
 
139
    public function companiesAction()
140
    {
141
 
142
        $request = $this->getRequest();
143
 
144
        if($request->isGet()) {
145
            $currentNetworkPlugin = $this->plugin('currentNetworkPlugin');
146
            $currentNetwork = $currentNetworkPlugin->getNetwork();
147
 
148
 
149
            $accessGrantedIds = $this->getAccessGranted();
150
            $companyMapper = CompanyMapper::getInstance($this->adapter);
151
            $records = $companyMapper->fetchAllByIdsAndNetworkId($accessGrantedIds->companies, $currentNetwork->id);
152
 
333 www 153
            $storage = Storage::getInstance($this->config, $this->adapter);
119 efrain 154
 
155
            $companies = [];
156
            foreach($records as $record)
157
            {
158
                array_push($companies, [
164 efrain 159
                    'uuid' => $record->uuid,
119 efrain 160
                    'name' => $record->name,
283 www 161
                    'image' => $storage->getCompanyImage($record),
119 efrain 162
                    'link_progress' => $this->url()->fromRoute('microlearning/progress',['id' => $record->uuid], ['force_canonical' => true]),
163
                ]);
164
            }
165
 
166
            return new JsonModel([
167
                'success' => true,
168
                'data' =>  $companies
169
            ]);
170
 
171
 
172
        }
173
        return new JsonModel([
174
            'success' => false,
175
            'data' => 'ERROR_METHOD_NOT_ALLOWED'
176
        ]);
177
    }
178
 
179
 
180
 
181
    public function capsuleCommentsAction()
182
    {
183
 
184
        $request = $this->getRequest();
185
 
186
        if($request->isGet()) {
187
            $serviceDatetimeFormat = $this->config['leaderslinked.services.datetime'];
188
 
189
            $currentUserPlugin = $this->plugin('currentUserPlugin');
190
            $currentUser = $currentUserPlugin->getUser();
191
 
192
            $capsule_id = $this->params()->fromRoute('capsule_id');
193
 
283 www 194
            $capsuleMapper = MicrolearningCapsuleMapper::getInstance($this->adapter);
119 efrain 195
            $capsule = $capsuleMapper->fetchOneByUuid($capsule_id);
196
 
197
            if(!$capsule) {
198
                return new JsonModel([
199
                    'success' => false,
200
                    'data' => 'ERROR_CAPSULE_NOT_FOUND'
201
 
202
                ]);
203
 
204
            }
205
 
283 www 206
            $capsuleUserMapper = MicrolearningCapsuleUserMapper::getInstance($this->adapter);
119 efrain 207
            $capsuleUser = $capsuleUserMapper->fetchOneByUserIdAndCapsuleId($currentUser->id, $capsule->id);
208
            if(! $capsuleUser) {
209
                return new JsonModel([
210
                    'success' => false,
211
                    'data' => 'ERROR_YOU_DO_NOT_HAVE_ACCESS_TO_THIS_CAPSULE',
212
                ]);
213
            }
214
 
215
            $userMapper = UserMapper::getInstance($this->adapter);
216
            $users = [];
217
 
283 www 218
 
333 www 219
            $storage = Storage::getInstance($this->config, $this->adapter);
283 www 220
 
221
            $capsuleCommentMapper = MicrolearningCapsuleCommentMapper::getInstance($this->adapter);
119 efrain 222
            $records = $capsuleCommentMapper->fetchAllByCapsuleId($capsule->id);
223
 
224
            $comments = [];
225
            foreach($records as $record)
226
            {
227
 
228
                if(isset($users[$record->user_id])) {
229
 
230
                    $user = $users[$record->user_id];
231
 
232
                } else {
233
 
234
                    $user = $userMapper->fetchOne($record->user_id);
235
                    if(!$user) {
236
                        continue;
237
                    }
238
 
239
                    $users[$record->user_id] = $user;
240
 
241
 
242
                }
243
 
244
 
245
                $dt = \DateTime::createFromFormat('Y-m-d H:i:s', $record->added_on);
246
 
247
                array_push($comments, [
248
                    'date' => $dt->format($serviceDatetimeFormat),
283 www 249
                    'image' => $storage->getUserImage($user),
119 efrain 250
                    'fullname' => trim(trim($user->first_name) . ' ' . trim($user->last_name)),
251
                    'rating' => strval($record->rating),
252
                    'comment' => $record->comment,
253
                    '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]) : '',
254
                ]);
255
            }
256
 
302 www 257
            $dataCountAndRatingAverage = $capsuleCommentMapper->fetchCountAndRatingAverage($capsule->company_id, $capsule->id);
119 efrain 258
 
259
            return new JsonModel([
260
                'success' => true,
261
                'data' => [
262
                    'comments' => $comments,
263
                    'capsule' => [
264
                        'total_comments' => strval($dataCountAndRatingAverage['total_comments']),
265
                        'total_rating' => strval($dataCountAndRatingAverage['total_rating'])
266
                    ]
267
                ]
268
 
269
            ]);
270
 
271
        }
272
 
273
        return new JsonModel([
274
            'success' => false,
275
            'data' => 'ERROR_METHOD_NOT_ALLOWED'
276
        ]);
277
    }
278
 
279
 
280
 
281
    public function capsuleDeleteMyCommentAction()
282
    {
283
 
284
        $request = $this->getRequest();
285
 
286
        if($request->isPost()) {
287
 
288
            $currentUserPlugin = $this->plugin('currentUserPlugin');
289
            $currentUser = $currentUserPlugin->getUser();
290
 
291
            $capsule_id = $this->params()->fromRoute('capsule_id');
292
            $comment_id = $this->params()->fromRoute('comment_id');
293
 
283 www 294
            $capsuleMapper = MicrolearningCapsuleMapper::getInstance($this->adapter);
119 efrain 295
            $capsule = $capsuleMapper->fetchOneByUuid($capsule_id);
296
 
297
            if(!$capsule) {
298
                return new JsonModel([
299
                    'success' => false,
300
                    'data' => 'ERROR_CAPSULE_NOT_FOUND'
301
 
302
                ]);
303
 
304
            }
305
 
283 www 306
            $capsuleUserMapper = MicrolearningCapsuleUserMapper::getInstance($this->adapter);
119 efrain 307
            $capsuleUser = $capsuleUserMapper->fetchOneByUserIdAndCapsuleId($currentUser->id, $capsule->id);
308
            if(! $capsuleUser) {
309
                return new JsonModel([
310
                    'success' => false,
311
                    'data' => 'ERROR_YOU_DO_NOT_HAVE_ACCESS_TO_THIS_CAPSULE',
312
                ]);
313
            }
314
 
283 www 315
            $capsuleCommentMapper = MicrolearningCapsuleCommentMapper::getInstance($this->adapter);
119 efrain 316
            $capsuleComment = $capsuleCommentMapper->fetchOneByUuid($comment_id);
317
 
318
            if(!$capsuleComment) {
319
                return new JsonModel([
320
                    'success' => false,
321
                    'data' => 'ERROR_CAPSULE_COMMENT_NOT_FOUND',
322
                ]);
323
            }
324
 
325
            if($capsuleComment->capsule_id != $capsule->id || $capsuleComment->user_id != $currentUser->id) {
326
                return new JsonModel([
327
                    'success' => false,
328
                    'data' => 'ERROR_YOU_DO_NOT_HAVE_ACCESS_TO_THIS_CAPSULE_COMMENT',
329
                ]);
330
            }
331
 
332
 
333
            $result = $capsuleCommentMapper->delete($capsuleComment->id);
334
            if($result) {
302 www 335
                $dataCountAndRatingAverage = $capsuleCommentMapper->fetchCountAndRatingAverage($capsule->company_id, $capsule->id);
119 efrain 336
 
337
 
338
 
339
 
340
                return new JsonModel([
341
                    'success' => true,
342
                    'data' => [
343
                        'message' => 'LABEL_CAPSULE_COMMENT_HAVE_BEEN_SUCCESSFULLY_DELETE',
344
                        'capsule' => [
345
                            'total_comments' => strval($dataCountAndRatingAverage['total_comments']),
346
                            'total_rating' => strval($dataCountAndRatingAverage['total_rating'])
347
                        ]
348
                    ],
349
 
350
                ]);
351
            } else {
352
                return new JsonModel([
353
                    'success' => false,
354
                    'data' => $capsuleCommentMapper->getError()
355
 
356
                ]);
357
            }
358
 
359
 
360
 
361
        }
362
 
363
        return new JsonModel([
364
            'success' => false,
365
            'data' => 'ERROR_METHOD_NOT_ALLOWED'
366
        ]);
367
    }
368
 
369
    public function capsuleAddMyCommentAction()
370
    {
371
 
372
        $request = $this->getRequest();
373
 
374
        if($request->isPost()) {
375
 
376
            $currentUserPlugin = $this->plugin('currentUserPlugin');
377
            $currentUser = $currentUserPlugin->getUser();
378
 
379
            $capsule_id = $this->params()->fromRoute('capsule_id');
380
 
381
 
283 www 382
            $capsuleMapper = MicrolearningCapsuleMapper::getInstance($this->adapter);
119 efrain 383
            $capsule = $capsuleMapper->fetchOneByUuid($capsule_id);
384
 
385
            if(!$capsule) {
386
                return new JsonModel([
387
                    'success' => false,
388
                    'data' => 'ERROR_CAPSULE_NOT_FOUND'
389
 
390
                ]);
391
 
392
            }
393
 
283 www 394
            $capsuleUserMapper = MicrolearningCapsuleUserMapper::getInstance($this->adapter);
119 efrain 395
            $capsuleUser = $capsuleUserMapper->fetchOneByUserIdAndCapsuleId($currentUser->id, $capsule->id);
396
            if(! $capsuleUser) {
397
                return new JsonModel([
398
                    'success' => false,
399
                    'data' => 'ERROR_YOU_DO_NOT_HAVE_ACCESS_TO_THIS_CAPSULE',
400
                ]);
401
            }
402
 
403
            //$rawdata = file_get_contents("php://input");
404
            //  error_log('$rawdata = ' . $rawdata );
405
 
406
 
407
            $form = new  CapsuleCommentForm();
408
            $dataPost = $request->getPost()->toArray();
409
            $dataPost['added_on'] = $capsuleMapper->getDatebaseNow();
410
 
411
 
412
            $form->setData($dataPost);
413
 
414
            if($form->isValid()) {
415
                $dataPost = (array) $form->getData();
416
 
417
 
283 www 418
                $capsuleComment = new MicrolearningCapsuleComment();
119 efrain 419
                $capsuleComment->company_id = $capsule->company_id;
420
                $capsuleComment->capsule_id = $capsule->id;
421
                $capsuleComment->user_id = $currentUser->id;
422
                $capsuleComment->comment = $dataPost['comment'];
423
                $capsuleComment->rating = strval($dataPost['rating']);
424
                $capsuleComment->added_on =  $dataPost['added_on'];
425
 
426
 
283 www 427
                $capsuleCommentMapper = MicrolearningCapsuleCommentMapper::getInstance($this->adapter);
119 efrain 428
                $result = $capsuleCommentMapper->insert($capsuleComment);
429
                if($result) {
430
 
431
                    $capsuleComment = $capsuleCommentMapper->fetchOne($capsuleComment->id);
432
 
302 www 433
                    $dataCountAndRatingAverage = $capsuleCommentMapper->fetchCountAndRatingAverage($capsule->company_id,  $capsule->id);
119 efrain 434
 
435
 
436
 
437
                    return new JsonModel([
438
                        'success' => true,
439
                        'data' => [
440
                            'message' =>'LABEL_CAPSULE_COMMENT_HAVE_BEEN_SUCCESSFULLY_ADDED',
441
 
442
                            'comment' => [
443
                                'comment' => $capsuleComment->comment,
444
                                'rating' => $capsuleComment->rating,
445
                                'link_delete' => $this->url()->fromRoute('microlearning/capsules-comments/delete', ['capsule_id' => $capsule->uuid, 'comment_id' => $capsuleComment->uuid], ['force_canonical' => true])
446
                            ],
447
                            'capsule' => [
448
                                'total_comments' => strval($dataCountAndRatingAverage['total_comments']),
449
                                'total_rating' => strval($dataCountAndRatingAverage['total_rating'])
450
                            ]
451
                        ]
452
 
453
                    ]);
454
                } else {
455
                    return new JsonModel([
456
                        'success' => false,
457
                        'data' => $capsuleCommentMapper->getError()
458
 
459
                    ]);
460
                }
461
 
462
 
463
            } else {
464
                $messages = [];
465
                $form_messages = (array) $form->getMessages();
466
                foreach($form_messages  as $fieldname => $field_messages)
467
                {
468
 
469
                    $messages[$fieldname] = array_values($field_messages);
470
                }
471
 
472
                return new JsonModel([
473
                    'success'   => false,
474
                    'data'   => $messages
475
                ]);
476
            }
477
 
478
 
479
 
480
 
481
        }
482
 
483
        return new JsonModel([
484
            'success' => false,
485
            'data' => 'ERROR_METHOD_NOT_ALLOWED'
486
        ]);
487
    }
488
 
489
    public function lastCapsuleInProgressAction()
490
    {
491
        $request = $this->getRequest();
492
 
493
        if($request->isGet())
494
        {
495
            $currentUserPlugin = $this->plugin('currentUserPlugin');
496
            $currentUser = $currentUserPlugin->getUser();
497
 
498
            $accessGrantedIds = $this->getAccessGranted();
499
 
500
 
283 www 501
            $userProgressMapper = MicrolearningUserProgressMapper::getInstance($this->adapter);
119 efrain 502
            $userProgress = $userProgressMapper->fetchOneLastCapsuleInProgressByUserIdAndCapsuleIds($currentUser->id, $accessGrantedIds->capsules);
283 www 503
            $topicMapper = MicrolearningTopicMapper::getInstance($this->adapter);
119 efrain 504
 
505
            if($userProgress) {
333 www 506
                $storage = Storage::getInstance($this->config, $this->adapter);
283 www 507
                $path = $storage->getPathMicrolearningCapsule();
508
 
509
                $capsuleMapper = MicrolearningCapsuleMapper::getInstance($this->adapter);
119 efrain 510
                $capsule = $capsuleMapper->fetchOne($userProgress->capsule_id);
511
 
301 www 512
                $topic = $topicMapper->fetchOne($userProgress->topic_id);
513
 
283 www 514
                $capsuleCommentMapper = MicrolearningCapsuleCommentMapper::getInstance($this->adapter);
302 www 515
                $dataCountAndRatingAverage = $capsuleCommentMapper->fetchCountAndRatingAverage($capsule->company_id,  $capsule->id);
576 stevensc 516
                $image = $storage->getGenericImage($path, $topic->uuid, $capsule->image);
517
 
119 efrain 518
                $response = [
519
                    'success' => true,
520
                    'data' => [
164 efrain 521
                        'uuid'              => $capsule->uuid,
119 efrain 522
                        'name'              => $capsule->name ? $capsule->name : '',
523
                        'description'       => $capsule->description ? $capsule->description : '',
575 stevensc 524
                        'image'             => ($capsule->image && $topic) ? $storage->getGenericImage($path,  $topic->uuid, $capsule->image )  : '',
119 efrain 525
                        'total_comments'    => strval($dataCountAndRatingAverage['total_comments']),
526
                        'total_rating'      => strval($dataCountAndRatingAverage['total_rating']),
527
                        'completed'         => $userProgress->completed,
145 efrain 528
                        'progress'          => $userProgress->progress,
119 efrain 529
                        'added_on'          => $userProgress->added_on,
530
                        'updated_on'        => $userProgress->updated_on
531
                    ]
532
                ];
533
 
534
 
535
            } else {
536
                $response = [
537
                    'success' => true,
575 stevensc 538
                    'data' => []
119 efrain 539
                ];
540
            }
541
 
542
 
543
        } else {
544
 
545
            $response = [
546
                'success' => false,
547
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
548
            ];
549
 
550
 
551
        }
552
 
553
        return new JsonModel($response);
554
    }
555
 
556
    public function capsulesPendingAction()
557
    {
558
        $request = $this->getRequest();
559
        if($request->isGet()) {
560
            $currentUserPlugin = $this->plugin('currentUserPlugin');
561
            $currentUser = $currentUserPlugin->getUser();
562
 
563
            $name = Functions::sanitizeFilterString($this->params()->fromQuery('name'));
245 efrain 564
            $order_field = Functions::sanitizeFilterString($this->params()->fromQuery('order_field'));
565
            $order_direction = Functions::sanitizeFilterString($this->params()->fromQuery('order_direction'));
119 efrain 566
 
245 efrain 567
            if(!in_array($order_field,['name', 'added_on'] )) {
568
                $order_field = 'name';
569
            }
119 efrain 570
 
245 efrain 571
            if(!in_array( $order_direction,['asc', 'desc'])) {
558 stevensc 572
                $order_direction = 'asc'; // Corregido: asignar a $order_direction
245 efrain 573
            }
574
 
283 www 575
            $userProgressMapper = MicrolearningUserProgressMapper::getInstance($this->adapter);
576
            $capsuleMapper = MicrolearningCapsuleMapper::getInstance($this->adapter);
558 stevensc 577
            $topicCapsuleMapper = MicrolearningTopicCapsuleMapper::getInstance($this->adapter); // Añadido
283 www 578
            $topicMapper = MicrolearningTopicMapper::getInstance($this->adapter);
558 stevensc 579
            $capsuleCommentMapper = MicrolearningCapsuleCommentMapper::getInstance($this->adapter); // Reordenado
119 efrain 580
 
581
            $accessGranted = $this->getAccessGranted();
558 stevensc 582
 
583
            // $topics = []; // Ya no es necesario cachear tópicos aquí
584
            $capsulesData = []; // Renombrado
119 efrain 585
 
333 www 586
            $storage = Storage::getInstance($this->config, $this->adapter);
283 www 587
            $path = $storage->getPathMicrolearningCapsule();
588
 
119 efrain 589
            foreach($accessGranted->capsules as $capsule_id)
590
            {
558 stevensc 591
                // 1. Verificar progreso (debe ser nulo para pendiente)
119 efrain 592
                $userProgress = $userProgressMapper->fetchOneByUseridAndCapsuleId($currentUser->id, $capsule_id);
593
                if($userProgress) {
594
                    continue;
595
                }
558 stevensc 596
 
597
                // 2. Obtener detalles de la cápsula
119 efrain 598
                $capsule = $capsuleMapper->fetchOne($capsule_id);
558 stevensc 599
                if(!$capsule) { // Añadir verificación por si la cápsula no existe
600
                    continue;
601
                }
119 efrain 602
 
558 stevensc 603
                // 3. Filtrar por nombre
119 efrain 604
                if($name) {
605
                    if(empty($name) || stripos($capsule->name, $name) === false) {
606
                        continue;
607
                    }
608
                }
609
 
558 stevensc 610
                // 4. Obtener Tópico asociado válido
611
                $topic = null;
612
                $topic_uuid_for_links = null;
613
                $relation = $topicCapsuleMapper->fetchOneByCapsuleId($capsule->id);
614
                if ($relation && in_array($relation->topic_id, $accessGranted->topics)) {
615
                    $topic = $topicMapper->fetchOne($relation->topic_id);
616
                    if ($topic) {
617
                        $topic_uuid_for_links = $topic->uuid;
618
                    }
619
                }
620
 
621
                // 5. Obtener datos de comentarios
302 www 622
                $dataCountAndRatingAverage = $capsuleCommentMapper->fetchCountAndRatingAverage($capsule->company_id,  $capsule->id);
119 efrain 623
 
558 stevensc 624
                // 6. Construir enlace slides
625
                $link_slides = $topic_uuid_for_links ? $this->url()->fromRoute('microlearning/slides', ['topic_id' => $topic_uuid_for_links,  'capsule_id' => $capsule->uuid], ['force_canonical' => true]) : '';
119 efrain 626
 
558 stevensc 627
                // 7. Añadir al array de resultados
628
                array_push($capsulesData, [
119 efrain 629
                    'uuid'              => $capsule->uuid,
630
                    'name'              => $capsule->name ? $capsule->name : '',
631
                    'description'       => $capsule->description ? $capsule->description : '',
283 www 632
                    'image'             => $capsule->image ? $storage->getGenericImage($path, $capsule->uuid, $capsule->image)  : '',
119 efrain 633
                    'position'          => $capsule->order,
634
                    'link_comments'     => $this->url()->fromRoute('microlearning/capsules-comments', ['capsule_id' => $capsule->uuid], ['force_canonical' => true]),
635
                    'link_comment_add'  => $this->url()->fromRoute('microlearning/capsules-comments/add', ['capsule_id' => $capsule->uuid],['force_canonical' => true]),
558 stevensc 636
                    'link_slides'       => $link_slides, // Usar enlace construido
119 efrain 637
                    'total_comments'    => strval($dataCountAndRatingAverage['total_comments']),
638
                    'total_rating'      => strval($dataCountAndRatingAverage['total_rating']),
191 efrain 639
                    'progress'          => 0,
162 efrain 640
                    'link_get'          => $this->url()->fromRoute('microlearning/get-capsule', ['id' => $capsule->uuid], ['force_canonical' => true]),
119 efrain 641
                    'added_on'          => $capsule->added_on,
642
                    'updated_on'        => $capsule->updated_on,
643
                ]);
644
            }
645
 
558 stevensc 646
            // 8. Ordenar
245 efrain 647
 
648
            if($order_field == 'name') {
649
                if($order_direction == 'asc') {
558 stevensc 650
                    usort($capsulesData, function($a, $b) {
245 efrain 651
                        return strcasecmp($a['name'], $b['name']);
652
                    });
653
                } else {
558 stevensc 654
                    usort($capsulesData, function($a, $b) {
245 efrain 655
                        $result = strcasecmp($a['name'], $b['name']);
558 stevensc 656
                        if($result < 0) { return 1; } else if($result > 0) { return -1; } else { return 0; } // Simplificado
245 efrain 657
                    });
119 efrain 658
                }
659
 
245 efrain 660
            }
661
 
662
            if($order_field == 'added_on') {
663
                if($order_direction == 'asc') {
558 stevensc 664
                    usort($capsulesData, function($a, $b) {
245 efrain 665
                        return strcasecmp($a['added_on'], $b['added_on']);
666
                    });
667
                } else {
558 stevensc 668
                    usort($capsulesData, function($a, $b) {
245 efrain 669
                        $result = strcasecmp($a['added_on'], $b['added_on']);
558 stevensc 670
                        if($result < 0) { return 1; } else if($result > 0) { return -1; } else { return 0; } // Simplificado
245 efrain 671
                    });
672
                }
119 efrain 673
 
558 stevensc 674
            }
119 efrain 675
 
558 stevensc 676
            // 9. Retornar
119 efrain 677
            return new JsonModel([
678
                'success' => true,
558 stevensc 679
                'data' => $capsulesData
119 efrain 680
            ]);
681
 
682
 
683
 
684
        }
685
 
686
        return new JsonModel([
687
            'success' => false,
688
            'data' => 'ERROR_METHOD_NOT_ALLOWED'
689
        ]);
690
 
691
    }
692
 
693
    public function capsulesCompletedAction()
694
    {
695
        $request = $this->getRequest();
696
        if($request->isGet()) {
697
            $currentUserPlugin = $this->plugin('currentUserPlugin');
698
            $currentUser = $currentUserPlugin->getUser();
699
 
700
            $name = Functions::sanitizeFilterString($this->params()->fromQuery('name'));
245 efrain 701
            $order_field = Functions::sanitizeFilterString($this->params()->fromQuery('order_field'));
702
            $order_direction = Functions::sanitizeFilterString($this->params()->fromQuery('order_direction'));
119 efrain 703
 
246 efrain 704
            if(!in_array($order_field,['name', 'added_on','last_access_on'] )) {
245 efrain 705
                $order_field = 'name';
706
            }
119 efrain 707
 
245 efrain 708
            if(!in_array( $order_direction,['asc', 'desc'])) {
709
                $order_field = 'asc';
710
            }
711
 
283 www 712
            $userProgressMapper = MicrolearningUserProgressMapper::getInstance($this->adapter);
713
            $capsuleMapper = MicrolearningCapsuleMapper::getInstance($this->adapter);
558 stevensc 714
            $topicCapsuleMapper = MicrolearningTopicCapsuleMapper::getInstance($this->adapter);
715
            $topicMapper = MicrolearningTopicMapper::getInstance($this->adapter);
283 www 716
            $capsuleCommentMapper = MicrolearningCapsuleCommentMapper::getInstance($this->adapter);
119 efrain 717
 
718
            $accessGranted = $this->getAccessGranted();
719
 
558 stevensc 720
            $capsulesData = [];
119 efrain 721
 
333 www 722
            $storage = Storage::getInstance($this->config, $this->adapter);
283 www 723
            $path = $storage->getPathMicrolearningCapsule();
724
 
119 efrain 725
            foreach($accessGranted->capsules as $capsule_id)
726
            {
558 stevensc 727
                // 1. Verificar progreso
119 efrain 728
                $userProgress = $userProgressMapper->fetchOneByUseridAndCapsuleId($currentUser->id, $capsule_id);
729
                if(!$userProgress) {
730
                    continue;
731
                }
732
 
733
                if(!$userProgress->completed) {
734
                    continue;
735
                }
736
 
558 stevensc 737
                // 2. Obtener detalles de la cápsula
119 efrain 738
                $capsule = $capsuleMapper->fetchOne($capsule_id);
558 stevensc 739
                if(!$capsule) {
740
                    continue;
741
                }
119 efrain 742
 
558 stevensc 743
                // 3. Filtrar por nombre
119 efrain 744
                if($name) {
745
                    if(empty($name) || stripos($capsule->name, $name) === false) {
746
                        continue;
747
                    }
748
                }
749
 
558 stevensc 750
                // 4. Obtener Tópico asociado válido
751
                $topic = null;
752
                $topic_uuid_for_links = null;
753
                $relation = $topicCapsuleMapper->fetchOneByCapsuleId($capsule->id);
754
                if ($relation && in_array($relation->topic_id, $accessGranted->topics)) {
755
                    $topic = $topicMapper->fetchOne($relation->topic_id);
756
                    if ($topic) {
757
                        $topic_uuid_for_links = $topic->uuid;
758
                    }
759
                }
760
 
761
                // 5. Obtener datos de comentarios
302 www 762
                $dataCountAndRatingAverage = $capsuleCommentMapper->fetchCountAndRatingAverage($capsule->company_id, $capsule->id);
119 efrain 763
 
558 stevensc 764
                // 6. Construir enlace slides
765
                $link_slides = $topic_uuid_for_links ? $this->url()->fromRoute('microlearning/slides', ['topic_id' => $topic_uuid_for_links,  'capsule_id' => $capsule->uuid], ['force_canonical' => true]) : '';
119 efrain 766
 
558 stevensc 767
                // 7. Añadir al array de resultados
768
                array_push($capsulesData, [
119 efrain 769
                    'uuid'              => $capsule->uuid,
770
                    'name'              => $capsule->name ? $capsule->name : '',
771
                    'description'       => $capsule->description ? $capsule->description : '',
283 www 772
                    'image'             => $capsule->image ? $storage->getGenericImage($path, $capsule->uuid, $capsule->image)  : '',
119 efrain 773
                    'position'          => $capsule->order,
774
                    'link_comments'     => $this->url()->fromRoute('microlearning/capsules-comments', ['capsule_id' => $capsule->uuid], ['force_canonical' => true]),
775
                    'link_comment_add'  => $this->url()->fromRoute('microlearning/capsules-comments/add', ['capsule_id' => $capsule->uuid],['force_canonical' => true]),
558 stevensc 776
                    'link_slides'       => $link_slides,
119 efrain 777
                    'total_comments'    => strval($dataCountAndRatingAverage['total_comments']),
778
                    'total_rating'      => strval($dataCountAndRatingAverage['total_rating']),
145 efrain 779
                    'progress'          => $userProgress->progress,
162 efrain 780
                    'link_get'          => $this->url()->fromRoute('microlearning/get-capsule', ['id' => $capsule->uuid], ['force_canonical' => true]),
119 efrain 781
                    'added_on'          => $capsule->added_on,
246 efrain 782
                    'last_access_on'    => $userProgress->updated_on,
119 efrain 783
                    'updated_on'        => $capsule->updated_on,
784
                ]);
785
            }
786
 
558 stevensc 787
            // 8. Ordenar (lógica de ordenación permanece igual, usando $capsulesData)
245 efrain 788
            if($order_field == 'name') {
789
                if($order_direction == 'asc') {
558 stevensc 790
                    usort($capsulesData, function($a, $b) {
245 efrain 791
                        return strcasecmp($a['name'], $b['name']);
792
                    });
793
                } else {
558 stevensc 794
                    usort($capsulesData, function($a, $b) {
245 efrain 795
                        $result = strcasecmp($a['name'], $b['name']);
558 stevensc 796
                        if($result < 0) { return 1; } else if($result > 0) { return -1; } else { return 0; }
245 efrain 797
                    });
119 efrain 798
                }
245 efrain 799
            }
800
 
801
            if($order_field == 'added_on') {
802
                if($order_direction == 'asc') {
558 stevensc 803
                    usort($capsulesData, function($a, $b) {
245 efrain 804
                        return strcasecmp($a['added_on'], $b['added_on']);
805
                    });
806
                } else {
558 stevensc 807
                    usort($capsulesData, function($a, $b) {
245 efrain 808
                        $result = strcasecmp($a['added_on'], $b['added_on']);
558 stevensc 809
                        if($result < 0) { return 1; } else if($result > 0) { return -1; } else { return 0; }
245 efrain 810
                    });
811
                }
812
            }
246 efrain 813
 
814
            if($order_field == 'last_access_on') {
815
                if($order_direction == 'asc') {
558 stevensc 816
                    usort($capsulesData, function($a, $b) {
246 efrain 817
                        return strcasecmp($a['last_access_on'], $b['last_access_on']);
818
                    });
819
                } else {
558 stevensc 820
                    usort($capsulesData, function($a, $b) {
246 efrain 821
                        $result = strcasecmp($a['last_access_on'], $b['last_access_on']);
558 stevensc 822
                        if($result < 0) { return 1; } else if($result > 0) { return -1; } else { return 0; }
246 efrain 823
                    });
824
                }
825
            }
826
 
827
 
828
 
829
 
119 efrain 830
 
831
            return new JsonModel([
832
                'success' => true,
558 stevensc 833
                'data' => $capsulesData
119 efrain 834
            ]);
835
 
836
        }
837
 
838
        return new JsonModel([
839
            'success' => false,
840
            'data' => 'ERROR_METHOD_NOT_ALLOWED'
841
        ]);
842
    }
843
 
844
    public function capsulesInProgressAction()
845
    {
846
        $request = $this->getRequest();
847
        if($request->isGet()) {
848
            $currentUserPlugin = $this->plugin('currentUserPlugin');
849
            $currentUser = $currentUserPlugin->getUser();
850
 
851
            $name = Functions::sanitizeFilterString($this->params()->fromQuery('name'));
245 efrain 852
            $order_field = Functions::sanitizeFilterString($this->params()->fromQuery('order_field'));
853
            $order_direction = Functions::sanitizeFilterString($this->params()->fromQuery('order_direction'));
119 efrain 854
 
246 efrain 855
            if(!in_array($order_field,['name', 'added_on', 'last_access_on'] )) {
245 efrain 856
                $order_field = 'name';
857
            }
119 efrain 858
 
245 efrain 859
            if(!in_array( $order_direction,['asc', 'desc'])) {
558 stevensc 860
                $order_direction = 'asc';
245 efrain 861
            }
862
 
283 www 863
            $userProgressMapper = MicrolearningUserProgressMapper::getInstance($this->adapter);
864
            $capsuleMapper = MicrolearningCapsuleMapper::getInstance($this->adapter);
558 stevensc 865
            $topicCapsuleMapper = MicrolearningTopicCapsuleMapper::getInstance($this->adapter);
866
            $topicMapper = MicrolearningTopicMapper::getInstance($this->adapter);
283 www 867
            $capsuleCommentMapper = MicrolearningCapsuleCommentMapper::getInstance($this->adapter);
119 efrain 868
 
869
            $accessGranted = $this->getAccessGranted();
870
 
558 stevensc 871
            $capsulesData = [];
119 efrain 872
 
333 www 873
            $storage = Storage::getInstance($this->config, $this->adapter);
283 www 874
            $path = $storage->getPathMicrolearningCapsule();
875
 
119 efrain 876
            foreach($accessGranted->capsules as $capsule_id)
877
            {
558 stevensc 878
                // 1. Verificar progreso
119 efrain 879
                $userProgress = $userProgressMapper->fetchOneByUseridAndCapsuleId($currentUser->id, $capsule_id);
558 stevensc 880
                if(!$userProgress || $userProgress->completed) { // Si no hay progreso o ya está completada
119 efrain 881
                    continue;
882
                }
558 stevensc 883
 
884
                // 2. Obtener detalles de la cápsula
885
                $capsule = $capsuleMapper->fetchOne($capsule_id);
886
                if(!$capsule) {
119 efrain 887
                    continue;
888
                }
889
 
558 stevensc 890
                // 3. Filtrar por nombre
119 efrain 891
                if($name) {
892
                    if(empty($name) || stripos($capsule->name, $name) === false) {
893
                        continue;
894
                    }
895
                }
896
 
558 stevensc 897
                // 4. Obtener Tópico asociado válido
898
                $topic = null;
899
                $topic_uuid_for_links = null;
900
                $relation = $topicCapsuleMapper->fetchOneByCapsuleId($capsule->id);
901
                if ($relation && in_array($relation->topic_id, $accessGranted->topics)) {
902
                    $topic = $topicMapper->fetchOne($relation->topic_id);
903
                    if ($topic) {
904
                        $topic_uuid_for_links = $topic->uuid;
905
                    }
906
                }
119 efrain 907
 
558 stevensc 908
                // 5. Obtener datos de comentarios
302 www 909
                $dataCountAndRatingAverage = $capsuleCommentMapper->fetchCountAndRatingAverage($capsule->company_id,  $capsule->id);
119 efrain 910
 
558 stevensc 911
                // 6. Construir enlace slides
912
                $link_slides = $topic_uuid_for_links ? $this->url()->fromRoute('microlearning/slides', ['topic_id' => $topic_uuid_for_links,  'capsule_id' => $capsule->uuid], ['force_canonical' => true]) : '';
119 efrain 913
 
558 stevensc 914
                // 7. Añadir al array de resultados
915
                array_push($capsulesData, [
119 efrain 916
                    'uuid'              => $capsule->uuid,
917
                    'name'              => $capsule->name ? $capsule->name : '',
918
                    'description'       => $capsule->description ? $capsule->description : '',
283 www 919
                    'image'             => $capsule->image ? $storage->getGenericImage($path, $capsule->uuid, $capsule->image)  : '',
119 efrain 920
                    'position'          => $capsule->order,
921
                    'link_comments'     => $this->url()->fromRoute('microlearning/capsules-comments', ['capsule_id' => $capsule->uuid], ['force_canonical' => true]),
922
                    'link_comment_add'  => $this->url()->fromRoute('microlearning/capsules-comments/add', ['capsule_id' => $capsule->uuid],['force_canonical' => true]),
558 stevensc 923
                    'link_slides'       => $link_slides,
119 efrain 924
                    'total_comments'    => strval($dataCountAndRatingAverage['total_comments']),
925
                    'total_rating'      => strval($dataCountAndRatingAverage['total_rating']),
558 stevensc 926
                    'progress'          => $userProgress->progress, // Progreso real
162 efrain 927
                    'link_get'          => $this->url()->fromRoute('microlearning/get-capsule', ['id' => $capsule->uuid], ['force_canonical' => true]),
558 stevensc 928
                    'last_access_on'    => $userProgress->updated_on, // Fecha del progreso
929
                    'added_on'          => $capsule->added_on, // Fecha de la cápsula
930
                    'updated_on'        => $capsule->updated_on, // Fecha de la cápsula
119 efrain 931
                ]);
932
            }
933
 
558 stevensc 934
            // 8. Ordenar (lógica de ordenación permanece igual, usando $capsulesData)
245 efrain 935
            if($order_field == 'name') {
936
                if($order_direction == 'asc') {
558 stevensc 937
                    usort($capsulesData, function($a, $b) {
245 efrain 938
                        return strcasecmp($a['name'], $b['name']);
939
                    });
940
                } else {
558 stevensc 941
                    usort($capsulesData, function($a, $b) {
245 efrain 942
                        $result = strcasecmp($a['name'], $b['name']);
558 stevensc 943
                        if($result < 0) { return 1; } else if($result > 0) { return -1; } else { return 0; }
245 efrain 944
                    });
119 efrain 945
                }
245 efrain 946
            }
947
 
948
            if($order_field == 'added_on') {
949
                if($order_direction == 'asc') {
558 stevensc 950
                    usort($capsulesData, function($a, $b) {
245 efrain 951
                        return strcasecmp($a['added_on'], $b['added_on']);
952
                    });
953
                } else {
558 stevensc 954
                    usort($capsulesData, function($a, $b) {
245 efrain 955
                        $result = strcasecmp($a['added_on'], $b['added_on']);
558 stevensc 956
                        if($result < 0) { return 1; } else if($result > 0) { return -1; } else { return 0; }
245 efrain 957
                    });
958
                }
959
            }
246 efrain 960
 
961
            if($order_field == 'last_access_on') {
962
                if($order_direction == 'asc') {
558 stevensc 963
                    usort($capsulesData, function($a, $b) {
246 efrain 964
                        return strcasecmp($a['last_access_on'], $b['last_access_on']);
965
                    });
966
                } else {
558 stevensc 967
                    usort($capsulesData, function($a, $b) {
246 efrain 968
                        $result = strcasecmp($a['last_access_on'], $b['last_access_on']);
558 stevensc 969
                        if($result < 0) { return 1; } else if($result > 0) { return -1; } else { return 0; }
246 efrain 970
                    });
971
                }
972
            }
245 efrain 973
 
246 efrain 974
 
119 efrain 975
            return new JsonModel([
976
                'success' => true,
558 stevensc 977
                'data' => $capsulesData
119 efrain 978
            ]);
979
        }
980
 
981
        return new JsonModel([
982
            'success' => false,
983
            'data' => 'ERROR_METHOD_NOT_ALLOWED'
984
        ]);
985
    }
986
 
987
 
988
    public function timelineAction()
989
    {
990
 
991
        $request = $this->getRequest();
992
        if($request->isGet()) {
993
            $currentUserPlugin = $this->plugin('currentUserPlugin');
994
            $currentUser = $currentUserPlugin->getUser();
995
 
996
 
997
            $page = intval($this->params()->fromQuery('page'), 10);
998
 
999
            $activities = [
283 www 1000
                MicrolearningUserLog::ACTIVITY_SIGNIN            => 'LABEL_MICROLEARNING_ACTIVITY_SIGNIN',
1001
                MicrolearningUserLog::ACTIVITY_SIGNOUT           => 'LABEL_MICROLEARNING_ACTIVITY_SIGNOUT',
1002
                MicrolearningUserLog::ACTIVITY_START_TOPIC       => 'LABEL_MICROLEARNING_ACTIVITY_START_TOPIC',
1003
                MicrolearningUserLog::ACTIVITY_START_CAPSULE     => 'LABEL_MICROLEARNING_ACTIVITY_START_CAPSULE',
1004
                MicrolearningUserLog::ACTIVITY_VIEW_SLIDE        => 'LABEL_MICROLEARNING_ACTIVITY_VIEW_SLIDE',
1005
                MicrolearningUserLog::ACTIVITY_TAKE_A_TEST       => 'LABEL_MICROLEARNING_ACTIVITY_TAKE_A_TEST',
1006
                MicrolearningUserLog::ACTIVITY_RETAKE_A_TEST     => 'LABEL_MICROLEARNING_ACTIVITY_RETAKE_A_TEST',
1007
                MicrolearningUserLog::ACTIVITY_APPROVED_TEST     => 'LABEL_MICROLEARNING_ACTIVITY_APPROVED_TEST',
1008
                MicrolearningUserLog::ACTIVITY_COMPLETED_CAPSULE => 'LABEL_MICROLEARNING_ACTIVITY_COMPLETED_CAPSULE',
1009
                MicrolearningUserLog::ACTIVITY_COMPLETED_TOPIC   => 'LABEL_MICROLEARNING_ACTIVITY_COMPLETED_TOPIC',
119 efrain 1010
            ];
1011
 
1012
 
1013
 
283 www 1014
            $microlearningUserLogMapper = MicrolearningUserLogMapper::getInstance($this->adapter);
1015
            $paginator = $microlearningUserLogMapper->getAllMessagesPaginatorByUserId($currentUser->id, $page);
119 efrain 1016
 
1017
            $items = [];
1018
            foreach($paginator as $record)
1019
            {
1020
                $dt = \DateTime::createFromFormat('Y-m-d H:i:s', $record->added_on);
1021
 
1022
                array_push($items, [
1023
                    'activity' => $activities[$record->activity],
1024
                    'added_on' => $dt->format('d/m/Y H:i a')
1025
                ]);
1026
            }
1027
 
1028
 
1029
            return new JsonModel([
1030
                'success' => true,
1031
                'data' => [
1032
                    'total' => [
1033
                        'count' => $paginator->getTotalItemCount(),
1034
                        'pages' => $paginator->getPages()->pageCount,
1035
                    ],
1036
                    'current' => [
1037
                        'items'    => $items,
1038
                        'page'     => $paginator->getCurrentPageNumber(),
1039
                        'count'    => $paginator->getCurrentItemCount(),
1040
                    ]
1041
                ]
1042
            ]);
1043
 
1044
 
1045
        } else {
1046
            return new JsonModel([
1047
                'success' => false,
1048
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
1049
            ]);
1050
        }
1051
    }
1052
 
1053
    /**
1054
     * Valores para la generación de los gráficos de progreso
1055
     * Para las repuesta afirmativa
1056
     * [
1057
     *  'success' => true,
1058
     *      'data' => [
1059
     *          'topicTotal' => cantidad total de tópicos,
1060
     *          'topicStarted' => cantidad de tópicos iniciados,
1061
     *          'topicIncompleted' => cantidad de tópicos incompletos,
1062
     *          'topicCompleted' => cantidad de tópicos completos,
1063
     *          'percentCompleted' => % de diapositivas completados ,
1064
     *          'percentIncompleted' => % de diapositivas incompletos ,
1065
     *          'percentWithoutReturning' => % de cápsulas sin retorno después de completada,
1066
     *          'percentWithReturning' => % de cápsulas con retorno después de completada,
558 stevensc 1067
     *      ],
119 efrain 1068
     * ]
1069
     *
1070
     *
1071
     *  En caso contrario
1072
     *  [
1073
     *      'success' => false,
1074
     *      'data' => mensaje de error
1075
     *  ]
1076
     *
1077
     *
1078
     * @return \Laminas\View\Model\JsonModel
1079
     */
1080
    public function progressAction()
1081
    {
1082
 
1083
        $request = $this->getRequest();
1084
        if($request->isGet()) {
1085
            $currentUserPlugin = $this->plugin('currentUserPlugin');
1086
            $currentUser = $currentUserPlugin->getUser();
1087
 
1088
 
1089
            $accessGrantedIds = $this->getAccessGranted();
1090
            $id = $this->params()->fromRoute('id');
1091
 
1092
            $companyMapper = CompanyMapper::getInstance($this->adapter);
1093
            $company = $companyMapper->fetchOneByUuid($id);
1094
 
1095
            if(!$company) {
1096
                $response = [
1097
                    'success' => false,
1098
                    'data' => 'ERROR_COMPANY_NOT_FOUND',
1099
                ];
1100
 
1101
 
1102
                return new JsonModel($response);
1103
            }
1104
 
1105
            if(!in_array($company->id, $accessGrantedIds->companies)) {
1106
                $response = [
1107
                    'success' => false,
1108
                    'data' => 'ERROR_YOU_DO_NOT_HAVE_ACCESS_TO_THIS_COMPANY',
1109
                ];
1110
 
1111
 
1112
                return new JsonModel($response);
1113
            }
1114
 
1115
            $capsuleTotal              = 0;
1116
            $capsuleCompleted          = 0;
1117
            $capsuleWithReturning      = 0;
1118
            $capsuleWithoutReturning   = 0;
1119
            $capsuleStarted            = 0;
1120
            $capsuleToStart            = 0;
1121
            $percentCompleted          = 0;
1122
            $percentIncompleted        = 100;
1123
 
283 www 1124
            $topicMapper = MicrolearningTopicMapper::getInstance($this->adapter);
119 efrain 1125
            $topics = $topicMapper->fetchAllActiveByCompanyIdAndIds($company->id, $accessGrantedIds->topics);
1126
 
302 www 1127
            //$capsuleMapper = MicrolearningCapsuleMapper::getInstance($this->adapter);
283 www 1128
            $progressMapper = MicrolearningUserProgressMapper::getInstance($this->adapter);
119 efrain 1129
 
302 www 1130
            $topicCapsuleMapper = MicrolearningTopicCapsuleMapper::getInstance($this->adapter);
119 efrain 1131
 
302 www 1132
            //$capsuleUserMapper = MicrolearningCapsuleUserMapper::getInstance($this->adapter);
1133
 
1134
 
119 efrain 1135
            foreach($topics as $topic)
1136
            {
302 www 1137
                $resultCount = $topicCapsuleMapper->fetchCountByCompanyIdAndTopicId($company->id, $topic->id);
119 efrain 1138
                $capsuleTotal =  $capsuleTotal + $resultCount;
1139
 
1140
                $resultCount = $progressMapper->fetchCountCapsulesCompletedByIdAndTopicId($currentUser->id, $topic->id);
1141
                $capsuleCompleted = $capsuleCompleted + $resultCount;
1142
 
1143
                $resultCount = $progressMapper->fetchCountCapsulesCompletedWithReturningByIdAndTopicId($currentUser->id, $topic->id);
1144
                $capsuleWithReturning = $capsuleWithReturning + $resultCount;
1145
 
1146
                $resultCount = $progressMapper->fetchCountCapsulesCompletedWithoutReturningByIdAndTopicId($currentUser->id, $topic->id);
1147
                $capsuleWithoutReturning = $capsuleWithoutReturning + $resultCount;
1148
 
1149
                $resultCount = $progressMapper->fetchCountCapsulesCompletedByIdAndTopicId($currentUser->id, $topic->id);
1150
                $capsuleStarted = $capsuleStarted + $resultCount;
1151
            }
1152
 
1153
            $capsuleToStart = $capsuleTotal -  $capsuleStarted;
1154
 
1155
 
1156
            if($capsuleTotal > 0) {
1157
                $percentCompleted = ($capsuleCompleted * 100) /  $capsuleTotal;
1158
                $percentIncompleted = 100 - $percentCompleted;
1159
            }
1160
 
1161
 
1162
 
1163
            return new JsonModel([
1164
                'success' => true,
1165
                'data' => [
1166
                    'capsuleTotal' => $capsuleTotal,
1167
                    'capsuleCompleted' => $capsuleCompleted,
1168
                    'capsuleStarted' => $capsuleStarted,
1169
                    'capsuleToStart' => $capsuleToStart,
1170
                    'percentCompleted' => number_format($percentCompleted, 2, '.', ','),
1171
                    'percentIncompleted' => number_format($percentIncompleted, 2, '.', ','),
1172
                    'capsuleWithReturning' => $capsuleWithReturning,
1173
                    'capsuleWithoutReturning' => $capsuleWithoutReturning,
1174
                ],
1175
            ]);
1176
 
1177
 
1178
        } else {
1179
            return new JsonModel([
1180
                'success' => false,
1181
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
1182
            ]);
1183
        }
1184
    }
1185
 
1186
 
1187
    public function topicsAction()
1188
    {
1189
        $request = $this->getRequest();
1190
        if($request->isGet()) {
1191
            $currentUserPlugin = $this->plugin('currentUserPlugin');
1192
            $currentUser = $currentUserPlugin->getUser();
1193
 
1194
 
1195
            $data = [];
1196
            $accessGrantedIds = $this->getAccessGranted();
1197
 
283 www 1198
            $userProgressMapper = MicrolearningUserProgressMapper::getInstance($this->adapter);
1199
            $topicMapper = MicrolearningTopicMapper::getInstance($this->adapter);
119 efrain 1200
 
333 www 1201
            $storage = Storage::getInstance($this->config, $this->adapter);
283 www 1202
            $path = $storage->getPathMicrolearningTopic();
119 efrain 1203
 
1204
            foreach($accessGrantedIds->topics as $id)
1205
            {
1206
                $topic = $topicMapper->fetchOne($id);
1207
                if(!$topic) {
1208
                    continue;
1209
                }
1210
 
1211
                $userProgress = $userProgressMapper->fetchOneByUserIdAndTopicId($currentUser->id, $id);
1212
                if($userProgress) {
1213
                    $progress = $userProgress->progress;
1214
                    $completed = $userProgress->completed;
1215
                } else {
1216
                    $progress = 0;
1217
                    $completed = 0;
1218
                }
1219
 
1220
 
1221
 
1222
                array_push($data, [
164 efrain 1223
                    'uuid'          => $topic->uuid,
119 efrain 1224
                    'name'          => $topic->name ? $topic->name : '',
1225
                    'description'   => $topic->description ? $topic->description : '',
283 www 1226
                    'image'         => $topic->image ? $storage->getGenericImage($path, $topic->uuid, $topic->image) : '',
119 efrain 1227
                    'progress'      => $progress,
1228
                    'completed'     => $completed,
1229
                    'order'         => $topic->order,
1230
                    'added_on'      => $topic->added_on,
564 stevensc 1231
                    'updated_on'    => $topic->updated_on
119 efrain 1232
                ]);
1233
            }
1234
 
1235
            usort($data, function($a, $b) {
1236
 
1237
                $result =  $a['order'] <=> $b['order'];
1238
                if(0 == $result) {
1239
                    $result = strcasecmp($a['added_on'], $b['added_on']);
1240
                    if(0 == $result) {
1241
                        $result = strcasecmp($a['name'], $b['name']);
1242
                    }
1243
                }
1244
 
1245
                if($result < 0) {
1246
                    return 1;
1247
                } else if($result > 0) {
1248
                    return -1;
1249
                } else  {
1250
                    return  0;
1251
                }
1252
            });
1253
 
1254
 
1255
 
1256
                return new JsonModel([
1257
                    'success' => true,
1258
                    'data' => $data
1259
                ]);
1260
 
1261
        } else {
1262
            return new JsonModel([
1263
                'success' => false,
1264
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
1265
            ]);
1266
        }
1267
    }
1268
 
161 efrain 1269
    public function getTopicAction()
1270
    {
563 stevensc 1271
        // Handle GET request
161 efrain 1272
        $request = $this->getRequest();
1273
        if($request->isGet()) {
563 stevensc 1274
            // Get current user
161 efrain 1275
            $currentUserPlugin = $this->plugin('currentUserPlugin');
1276
            $currentUser = $currentUserPlugin->getUser();
563 stevensc 1277
 
1278
            // Get topic ID from route
161 efrain 1279
            $id = $this->params()->fromRoute('id');
283 www 1280
            $topicMapper = MicrolearningTopicMapper::getInstance($this->adapter);
161 efrain 1281
            $topic = $topicMapper->fetchOneByUuid($id);
563 stevensc 1282
 
1283
            // Return error if topic not found
161 efrain 1284
            if(!$topic) {
1285
                return new JsonModel([
1286
                    'success' => false,
1287
                    'data' => 'ERROR_TOPIC_NOT_FOUND'
1288
                ]);
1289
            }
563 stevensc 1290
 
1291
            // Check if current user has access to the topic
161 efrain 1292
            $accessGrantedIds = $this->getAccessGranted();
1293
            if(!in_array($topic->id, $accessGrantedIds->topics)) {
1294
                return new JsonModel([
1295
                    'success' => false,
1296
                    'data' => 'ERROR_YOU_DO_NOT_HAVE_ACCESS_TO_THIS_TOPIC'
1297
                ]);
1298
            }
563 stevensc 1299
 
1300
            // Get user progress for this topic
283 www 1301
            $userProgressMapper = MicrolearningUserProgressMapper::getInstance($this->adapter);
563 stevensc 1302
            $userProgress = $userProgressMapper->fetchOneByUserIdAndTopicId($currentUser->id, $topic->id);
161 efrain 1303
 
563 stevensc 1304
            $progress = 0;
1305
            $completed = false;
161 efrain 1306
            if($userProgress) {
1307
                $progress = $userProgress->progress;
1308
                $completed = $userProgress->completed;
1309
            }
563 stevensc 1310
 
1311
            // Initialize storage service to get image paths
333 www 1312
            $storage = Storage::getInstance($this->config, $this->adapter);
563 stevensc 1313
            $pathTopic = $storage->getPathMicrolearningTopic();
1314
 
1315
            // Fetch associated capsules using the private helper method
1316
            $capsulesData = $this->_getCapsulesByTopic($topic, $storage);
1317
 
1318
            // Prepare data for JSON response
161 efrain 1319
            $data = [
165 efrain 1320
                'uuid'          => $topic->uuid,
161 efrain 1321
                'name'          => $topic->name ? $topic->name : '',
1322
                'description'   => $topic->description ? $topic->description : '',
563 stevensc 1323
                'image'         => $topic->image ? $storage->getGenericImage($pathTopic, $topic->uuid, $topic->image) : '',
161 efrain 1324
                'progress'      => $progress,
1325
                'completed'     => $completed,
1326
                'order'         => $topic->order,
1327
                'added_on'      => $topic->added_on,
1328
                'updated_on'    => $topic->updated_on,
563 stevensc 1329
                'total_capsules' => count($capsulesData),
1330
                'capsules'      => $capsulesData,
161 efrain 1331
            ];
563 stevensc 1332
 
161 efrain 1333
            return new JsonModel([
1334
                'success' => true,
1335
                'data' => $data
1336
            ]);
563 stevensc 1337
 
161 efrain 1338
        } else {
563 stevensc 1339
            // Return error if not a GET request
161 efrain 1340
            return new JsonModel([
1341
                'success' => false,
1342
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
1343
            ]);
1344
        }
1345
    }
563 stevensc 1346
 
1347
    /**
1348
     * Fetches and formats capsules associated with a given topic.
1349
     *
1350
     * @param mixed $topic The topic object.
1351
     * @param Storage $storage The storage service instance.
1352
     * @return array An array of formatted capsule data.
1353
     */
1354
    private function _getCapsulesByTopic($topic, $storage)
1355
    {
578 stevensc 1356
        $data = [];
579 stevensc 1357
        // $accessGrantedIds = $this->getAccessGranted();
563 stevensc 1358
 
578 stevensc 1359
        if (!$topic) {
1360
            return $data;
1361
        }
1362
 
579 stevensc 1363
        /* if (!in_array($topic->id, $accessGrantedIds->topics)) {
578 stevensc 1364
            return $data;
579 stevensc 1365
        } */
578 stevensc 1366
 
1367
        $currentUserPlugin = $this->plugin('currentUserPlugin');
1368
        $currentUser = $currentUserPlugin->getUser();
1369
 
1370
        $topicCapsuleMapper = MicrolearningTopicCapsuleMapper::getInstance($this->adapter);
574 stevensc 1371
        $topicCapsuleRelations = $topicCapsuleMapper->fetchAllActiveByTopicId($topic->id);
1372
 
1373
        $capsuleIdsToFetch = [];
578 stevensc 1374
 
1375
        foreach ($topicCapsuleRelations as $relation) {
579 stevensc 1376
            $capsuleIdsToFetch[] = $relation->capsule_id;
1377
            /* if (in_array($relation->capsule_id, $accessGrantedIds->capsules)) {
578 stevensc 1378
                $capsuleIdsToFetch[] = $relation->capsule_id;
579 stevensc 1379
            } */
574 stevensc 1380
        }
578 stevensc 1381
 
1382
        if (empty($capsuleIdsToFetch)) {
1383
            return $data;
574 stevensc 1384
        }
1385
 
578 stevensc 1386
        $capsuleMapper = MicrolearningCapsuleMapper::getInstance($this->adapter);
1387
        $capsules = $capsuleMapper->fetchAllByIds($capsuleIdsToFetch);
563 stevensc 1388
 
578 stevensc 1389
        $userProgressMapper = MicrolearningUserProgressMapper::getInstance($this->adapter);
1390
        $capsuleCommentMapper = MicrolearningCapsuleCommentMapper::getInstance($this->adapter);
1391
 
1392
        $path = $storage->getPathMicrolearningCapsule();
563 stevensc 1393
 
578 stevensc 1394
        foreach ($capsules as $capsule) {
579 stevensc 1395
            /* if (!in_array($capsule->id, $accessGrantedIds->capsules)) {
578 stevensc 1396
                continue;
579 stevensc 1397
            } */
563 stevensc 1398
 
578 stevensc 1399
            $userProgress = $userProgressMapper->fetchOneByUseridAndCapsuleId($currentUser->id, $capsule->id);
1400
            $progress = $userProgress->progress ?? 0;
1401
            $completed = $userProgress->completed ?? 0;
1402
            $dataCountAndRatingAverage = $capsuleCommentMapper->fetchCountAndRatingAverage($capsule->company_id, $capsule->id);
1403
            $image = $capsule->image ? $storage->getGenericImage($path, $capsule->uuid, $capsule->image) : '';
1404
            $total_comments = strval($dataCountAndRatingAverage['total_comments']);
1405
            $total_rating = strval($dataCountAndRatingAverage['total_rating']);
1406
 
1407
            array_push($data, [
1408
                'uuid'              => $capsule->uuid,
1409
                'name'              => $capsule->name ? $capsule->name : '',
1410
                'description'       => $capsule->description ? $capsule->description : '',
1411
                'image'             => $image,
1412
                'total_comments'    => $total_comments,
1413
                'total_rating'      => $total_rating,
1414
                'progress'          => $progress,
1415
                'completed'         => $completed,
1416
                'order'             => $capsule->order,
1417
                'added_on'          => $capsule->added_on,
1418
                'updated_on'        => $capsule->updated_on,
1419
            ]);
563 stevensc 1420
        }
578 stevensc 1421
 
1422
        return $data;
563 stevensc 1423
    }
119 efrain 1424
 
161 efrain 1425
 
119 efrain 1426
    public function capsulesAction()
1427
    {
1428
        $request = $this->getRequest();
1429
        if($request->isGet()) {
578 stevensc 1430
            // currentUserPlugin and currentUser are fetched within _getCapsulesByTopic if needed directly by it
1431
            // $currentUserPlugin = $this->plugin('currentUserPlugin');
1432
            // $currentUser = $currentUserPlugin->getUser();
119 efrain 1433
 
578 stevensc 1434
            $topic_id_param = $this->params()->fromRoute('topic_id');
283 www 1435
            $topicMapper = MicrolearningTopicMapper::getInstance($this->adapter);
578 stevensc 1436
            $topic = $topicMapper->fetchOneByUuid($topic_id_param); // $topic is the topic object
119 efrain 1437
 
1438
            if(!$topic) {
1439
                return new JsonModel([
1440
                    'success' => false,
1441
                    'data' => 'ERROR_TOPIC_NOT_FOUND'
1442
                ]);
1443
            }
1444
 
578 stevensc 1445
            $accessGrantedIds = $this->getAccessGranted(); // Needed for the access check here
119 efrain 1446
 
1447
            if(!in_array($topic->id, $accessGrantedIds->topics)) {
1448
                return new JsonModel([
1449
                    'success' => false,
1450
                    'data' => 'ERROR_YOU_DO_NOT_HAVE_ACCESS_TO_THIS_TOPIC'
1451
                ]);
1452
            }
1453
 
578 stevensc 1454
            // Initialize storage and call the refactored private method
333 www 1455
            $storage = Storage::getInstance($this->config, $this->adapter);
578 stevensc 1456
            $data = $this->_getCapsulesByTopic($topic, $storage); // $topic is the object
119 efrain 1457
 
578 stevensc 1458
            // The extensive logic for fetching, processing, and sorting capsules
1459
            // has been removed from here and is now in _getCapsulesByTopic.
119 efrain 1460
 
578 stevensc 1461
            return new JsonModel([
1462
                'success' => true,
1463
                'data' => $data
1464
            ]);
119 efrain 1465
 
1466
        } else {
1467
            return new JsonModel([
1468
                'success' => false,
1469
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
1470
            ]);
1471
        }
1472
    }
1473
 
235 efrain 1474
    public function takeTestAction()
1475
    {
1476
        $request = $this->getRequest();
1477
        if($request->isPost()) {
1478
            $currentUserPlugin = $this->plugin('currentUserPlugin');
1479
            $currentUser = $currentUserPlugin->getUser();
1480
 
1481
            $slide_id = $this->params()->fromRoute('slide_id');
283 www 1482
            $slideMapper = MicrolearningSlideMapper::getInstance($this->adapter);
235 efrain 1483
            $slide = $slideMapper->fetchOneByUuid($slide_id);
1484
 
1485
            if(!$slide) {
1486
                return new JsonModel([
1487
                    'success' => false,
1488
                    'data' => 'ERROR_SLIDE_NOT_FOUND'
1489
                ]);
1490
            }
1491
 
283 www 1492
            if($slide->type != MicrolearningSlide::TYPE_QUIZ) {
235 efrain 1493
                return new JsonModel([
1494
                    'success' => false,
1495
                    'data' => 'ERROR_SLIDE_IS_NOT_QUIZ'
1496
                ]);
1497
            }
1498
 
1499
 
1500
 
283 www 1501
            $capsuleMapper = MicrolearningCapsuleMapper::getInstance($this->adapter);
235 efrain 1502
            $capsule = $capsuleMapper->fetchOne($slide->capsule_id);
1503
 
1504
            if(!$capsule) {
1505
                return new JsonModel([
1506
                    'success' => false,
1507
                    'data' => 'ERROR_CAPSULE_NOT_FOUND'
1508
                ]);
1509
            }
1510
 
1511
            $accessGrantedIds = $this->getAccessGranted();
1512
 
1513
            if(!in_array($capsule->id, $accessGrantedIds->capsules)) {
1514
                return new JsonModel([
1515
                    'success' => false,
1516
                    'data' => 'ERROR_YOU_DO_NOT_HAVE_ACCESS_TO_THIS_CAPSULE'
1517
                ]);
1518
            }
1519
 
283 www 1520
            $userLogMapper = MicrolearningUserLogMapper::getInstance($this->adapter);
235 efrain 1521
            $userLog = $userLogMapper->fetchOneTakeATestByUserIdAndSlideId($currentUser->id, $slide->id);
1522
 
1523
            if($userLog) {
283 www 1524
                $activity = MicrolearningUserLog::ACTIVITY_RETAKE_A_TEST;
235 efrain 1525
            } else {
283 www 1526
                $activity = MicrolearningUserLog::ACTIVITY_TAKE_A_TEST;
235 efrain 1527
            }
1528
 
1529
            $added_on = $userLogMapper->getDatebaseNow();
1530
 
283 www 1531
            $userLog = new MicrolearningUserLog();
235 efrain 1532
            $userLog->activity      = $activity;
1533
            $userLog->user_id       = $currentUser->id;
1534
            $userLog->company_id    = $slide->company_id;
1535
            $userLog->topic_id      = $slide->topic_id;
1536
            $userLog->capsule_id    = $slide->capsule_id;
1537
            $userLog->slide_id      = $slide->id;
1538
            $userLog->added_on      = $added_on;
1539
 
1540
            if($userLogMapper->insert($userLog)) {
1541
                return new JsonModel([
1542
                    'success' => true,
1543
                ]);
1544
            } else {
1545
                return new JsonModel([
1546
                    'success' => false,
1547
                    'data' => $userLogMapper->getError()
1548
                ]);
1549
            }
1550
 
1551
 
1552
 
1553
 
1554
 
1555
 
1556
 
1557
        } else {
1558
            return new JsonModel([
1559
                'success' => false,
1560
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
1561
            ]);
1562
        }
1563
    }
1564
 
161 efrain 1565
    public function getCapsuleAction()
1566
    {
1567
        $request = $this->getRequest();
1568
        if($request->isGet()) {
1569
            $currentUserPlugin = $this->plugin('currentUserPlugin');
1570
            $currentUser = $currentUserPlugin->getUser();
1571
 
1572
 
1573
 
558 stevensc 1574
            $capsule_uuid = $this->params()->fromRoute('id');
283 www 1575
            $capsuleMapper = MicrolearningCapsuleMapper::getInstance($this->adapter);
558 stevensc 1576
            $capsule = $capsuleMapper->fetchOneByUuid($capsule_uuid);
161 efrain 1577
 
1578
            if(!$capsule) {
1579
                return new JsonModel([
1580
                    'success' => false,
1581
                    'data' => 'ERROR_CAPSULE_NOT_FOUND'
1582
                ]);
1583
            }
1584
 
1585
            $accessGrantedIds = $this->getAccessGranted();
1586
 
558 stevensc 1587
            // Verificar si el usuario tiene acceso a esta cápsula específica
161 efrain 1588
            if(!in_array($capsule->id, $accessGrantedIds->capsules)) {
1589
                return new JsonModel([
1590
                    'success' => false,
1591
                    'data' => 'ERROR_YOU_DO_NOT_HAVE_ACCESS_TO_THIS_CAPSULE'
1592
                ]);
1593
            }
1594
 
558 stevensc 1595
            // --- Obtener el Tópico asociado (si existe y es necesario) ---
1596
            $topic = null;
1597
            $topic_uuid_for_links = null; // UUID del tópico para construir enlaces
1598
            $topicCapsuleMapper = MicrolearningTopicCapsuleMapper::getInstance($this->adapter);
1599
            // Asumiendo que una cápsula puede estar asociada a múltiples tópicos (muchos-a-muchos),
1600
            // necesitamos decidir cuál tópico usar como contexto aquí. Usaremos el primero que encontremos.
1601
            // Si una cápsula SIEMPRE pertenece a UN SOLO tópico, la tabla de unión podría tener una restricción UNIQUE(capsule_id).
1602
            $relation = $topicCapsuleMapper->fetchOneByCapsuleId($capsule->id); // Necesitamos un método como este
1603
 
1604
            if ($relation && in_array($relation->topic_id, $accessGrantedIds->topics)) {
1605
                $topicMapper = MicrolearningTopicMapper::getInstance($this->adapter);
1606
                $topic = $topicMapper->fetchOne($relation->topic_id);
1607
                if ($topic) {
1608
                    $topic_uuid_for_links = $topic->uuid;
1609
                }
1610
            }
1611
            // Si no se encontró un tópico asociado o el usuario no tiene acceso a él,
1612
            // algunos enlaces podrían no generarse o la lógica necesitaría ajustarse.
1613
            // Por ahora, si no hay $topic_uuid_for_links, el link_slides será inválido.
1614
            // --------------------------------------------------------------
161 efrain 1615
 
1616
 
283 www 1617
            $userProgressMapper = MicrolearningUserProgressMapper::getInstance($this->adapter);
1618
            $capsuleCommentMapper = MicrolearningCapsuleCommentMapper::getInstance($this->adapter);
161 efrain 1619
 
1620
 
1621
 
1622
            $userProgress = $userProgressMapper->fetchOneByUseridAndCapsuleId($currentUser->id, $capsule->id);
1623
            if($userProgress) {
1624
                $progress = $userProgress->progress;
1625
                $completed = $userProgress->completed;
1626
            } else {
1627
                $progress = 0;
1628
                $completed = 0;
1629
            }
1630
 
302 www 1631
            $dataCountAndRatingAverage = $capsuleCommentMapper->fetchCountAndRatingAverage($capsule->company_id,  $capsule->id);
161 efrain 1632
 
244 efrain 1633
 
283 www 1634
            $slideMapper = MicrolearningSlideMapper::getInstance($this->adapter);
558 stevensc 1635
            // Para contar slides, necesitamos el contexto del tópico.
1636
            $totalSlides = 0;
1637
            if ($topic) { // Solo contar si tenemos un tópico asociado válido
1638
                $totalSlides = $slideMapper->fetchTotalCountByCompanyIdAndTopicIdAndCapsuleId($capsule->company_id, $topic->id, $capsule->id);
1639
            }
244 efrain 1640
 
1641
 
558 stevensc 1642
            $link_first_slide = '';
1643
            $type_first_slide = '';
1644
            if ($topic) { // Solo buscar primer slide si tenemos tópico
1645
                $slide = $slideMapper->fetchFirstByCompanyIdAndTopicIdAndCapsuleId($capsule->company_id, $topic->id, $capsule->id);
1646
                if($slide) {
1647
                    $link_first_slide = $this->url()->fromRoute('microlearning/get-slide', ['id' => $slide->uuid], ['force_canonical' => true]);
1648
                    $type_first_slide = $slide->type;
1649
                }
244 efrain 1650
            }
1651
 
333 www 1652
            $storage = Storage::getInstance($this->config, $this->adapter);
283 www 1653
            $path = $storage->getPathMicrolearningCapsule();
244 efrain 1654
 
1655
 
558 stevensc 1656
            // Construir enlaces usando $topic_uuid_for_links si está disponible
1657
            $link_slides = $topic_uuid_for_links ? $this->url()->fromRoute('microlearning/slides', ['topic_id' => $topic_uuid_for_links,  'capsule_id' => $capsule->uuid], ['force_canonical' => true]) : '';
244 efrain 1658
 
161 efrain 1659
            $data = [
164 efrain 1660
                    'uuid'              => $capsule->uuid,
161 efrain 1661
                    'name'              => $capsule->name ? $capsule->name : '',
1662
                    'description'       => $capsule->description ? $capsule->description : '',
283 www 1663
                    'image'             => $capsule->image ? $storage->getGenericImage($path, $capsule->uuid, $capsule->image)  : '',
161 efrain 1664
                    'link_comments'     => $this->url()->fromRoute('microlearning/capsules-comments', ['capsule_id' => $capsule->uuid], ['force_canonical' => true]),
1665
                    'link_comment_add'  => $this->url()->fromRoute('microlearning/capsules-comments/add', ['capsule_id' => $capsule->uuid],['force_canonical' => true]),
558 stevensc 1666
                    'link_slides'       => $link_slides, // Usar el enlace construido
161 efrain 1667
                    'total_comments'    => strval($dataCountAndRatingAverage['total_comments']),
1668
                    'total_rating'      => strval($dataCountAndRatingAverage['total_rating']),
1669
                    'progress'          => $progress,
1670
                    'completed'         => $completed,
245 efrain 1671
                    'total_slides'      => $totalSlides,
244 efrain 1672
                    'link_first_slide'  => $link_first_slide,
1673
                    'type_first_slide'  => $type_first_slide,
161 efrain 1674
                    'order'             => $capsule->order,
1675
                    'added_on'          => $capsule->added_on,
1676
                    'updated_on'        => $capsule->updated_on,
1677
            ];
1678
 
1679
 
1680
 
1681
            return new JsonModel([
1682
                'success' => true,
1683
                'data' => $data
1684
            ]);
1685
 
1686
        } else {
1687
            return new JsonModel([
1688
                'success' => false,
1689
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
1690
            ]);
1691
        }
1692
    }
1693
 
119 efrain 1694
    public function slidesAction()
1695
    {
1696
        $request = $this->getRequest();
1697
        if($request->isGet()) {
1698
            $currentUserPlugin = $this->plugin('currentUserPlugin');
1699
            $currentUser = $currentUserPlugin->getUser();
1700
 
1701
 
1702
 
1703
            $topic_id = $this->params()->fromRoute('topic_id');
283 www 1704
            $topicMapper = MicrolearningTopicMapper::getInstance($this->adapter);
119 efrain 1705
            $topic = $topicMapper->fetchOneByUuid($topic_id);
1706
 
1707
            if(!$topic) {
1708
                return new JsonModel([
1709
                    'success' => false,
1710
                    'data' => 'ERROR_TOPIC_NOT_FOUND'
1711
                ]);
1712
            }
1713
 
1714
            $accessGrantedIds = $this->getAccessGranted();
1715
 
1716
            if(!in_array($topic->id, $accessGrantedIds->topics)) {
1717
                return new JsonModel([
1718
                    'success' => false,
1719
                    'data' => 'ERROR_YOU_DO_NOT_HAVE_ACCESS_TO_THIS_TOPIC'
1720
                ]);
1721
            }
1722
 
1723
            $capsule_id = $this->params()->fromRoute('capsule_id');
283 www 1724
            $capsuleMapper = MicrolearningCapsuleMapper::getInstance($this->adapter);
119 efrain 1725
            $capsule = $capsuleMapper->fetchOneByUuid($capsule_id);
1726
 
1727
            if(!$capsule) {
1728
                return new JsonModel([
1729
                    'success' => false,
1730
                    'data' => 'ERROR_CAPSULE_NOT_FOUND'
1731
                ]);
1732
            }
1733
 
1734
 
1735
 
1736
            if(!in_array($capsule->id, $accessGrantedIds->capsules)) {
1737
                return new JsonModel([
1738
                    'success' => false,
1739
                    'data' => 'ERROR_YOU_DO_NOT_HAVE_ACCESS_TO_THIS_CAPSULE'
1740
                ]);
1741
            }
1742
 
1743
 
1744
 
1745
            $data = [];
1746
 
283 www 1747
            $quizMapper = MicrolearningQuizMapper::getInstance($this->adapter);
119 efrain 1748
 
283 www 1749
            $slideMapper = MicrolearningSlideMapper::getInstance($this->adapter);
1750
            $userProgressMapper = MicrolearningUserProgressMapper::getInstance($this->adapter);
119 efrain 1751
 
333 www 1752
            $storage = Storage::getInstance($this->config, $this->adapter);
283 www 1753
            $path = $storage->getPathMicrolearningSlide();
119 efrain 1754
 
1755
            $slides = $slideMapper->fetchAllByCompanyIdAndTopicIdAndCapsuleId($capsule->company_id, $capsule->topic_id, $capsule->id);
1756
            foreach($slides as $slide)
1757
            {
1758
 
1759
 
1760
                $userProgress = $userProgressMapper->fetchOneByUserIdAndSlideId($currentUser->id, $slide->id);
1761
                if($userProgress) {
224 efrain 1762
                    $completed =  $userProgress->completed ;
119 efrain 1763
                } else {
1764
                    $completed = 0;
1765
                }
1766
 
235 efrain 1767
 
230 efrain 1768
 
235 efrain 1769
                $link_take_a_test = '';
230 efrain 1770
                if($slide->quiz_id) {
235 efrain 1771
 
283 www 1772
                    $quizMapper = MicrolearningQuizMapper::getInstance($this->adapter);
230 efrain 1773
                    $quiz = $quizMapper->fetchOne($slide->quiz_id);
1774
                    if($quiz) {
1775
                        $quiz_uuid = $quiz->uuid;
235 efrain 1776
                        $quiz_data = $this->getQuiz($slide->quiz_id);
1777
                        $link_take_a_test = $this->url()->fromRoute('microlearning/take-a-test', ['slide_id' => $slide->uuid], ['force_canonical' => true]);
230 efrain 1778
                    }
235 efrain 1779
 
1780
                }
119 efrain 1781
 
1782
 
1783
                array_push($data, [
235 efrain 1784
                    'quiz'                  => $quiz_uuid,
1785
                    'quiz_data'             => $quiz_data,
1786
                    'uuid'                  => $slide->uuid,
1787
                    'name'                  => $slide->name ? $slide->name : '',
1788
                    'description'           => $slide->description ? $slide->description : '',
1789
                    'type'                  => $slide->type,
283 www 1790
                    'background'            => $slide->background ? $storage->getGenericImage($path, $slide->uuid, $slide->background) : '',
1791
                    'file'                  => $slide->file ? $storage->getGenericFile($path, $slide->uuid, $slide->file) : '',
235 efrain 1792
                    'order'                 => $slide->order,
1793
                    'completed'             => $completed,
1794
                    'link_get'              => $this->url()->fromRoute('microlearning/get-slide', ['id' => $slide->uuid], ['force_canonical' => true]),
1795
                    'link_sync'             => $this->url()->fromRoute('microlearning/sync', ['operation' => 'slide-view', 'topic_uuid' => $topic->uuid, 'capsule_uuid' => $capsule->uuid, 'slide_uuid' => $slide->uuid], ['force_canonical' => true]),
236 efrain 1796
                    'link_take_a_test'      => $link_take_a_test,
235 efrain 1797
                    'added_on'              => $slide->added_on,
1798
                    'updated_on'            => $slide->updated_on,
119 efrain 1799
                ]);
1800
 
1801
 
1802
 
1803
            }
1804
 
1805
            usort($data, function($a, $b) {
1806
 
1807
                $result =  $a['order'] <=> $b['order'];
1808
                if(0 == $result) {
1809
                    $result = strcasecmp($a['added_on'], $b['added_on']);
1810
                    if(0 == $result) {
1811
                        $result = strcasecmp($a['name'], $b['name']);
1812
                    }
1813
                }
1814
 
1815
                if($result < 0) {
1816
                    return 1;
1817
                } else if($result > 0) {
1818
                    return -1;
1819
                } else  {
1820
                    return  0;
1821
                }
1822
            });
1823
 
1824
 
1825
 
1826
                return new JsonModel([
1827
                    'success' => true,
1828
                    'data' => $data
1829
                ]);
1830
 
1831
        } else {
1832
            return new JsonModel([
1833
                'success' => false,
1834
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
1835
            ]);
1836
        }
1837
    }
1838
 
229 efrain 1839
    private function getQuiz($id)
1840
    {
1841
        $serviceDatetimeFormat = $this->config['leaderslinked.services.datetime'];
1842
 
1843
        $data = [];
1844
 
283 www 1845
        $quizMapper = MicrolearningQuizMapper::getInstance($this->adapter);
229 efrain 1846
        $quiz = $quizMapper->fetchOne($id);
1847
 
1848
        if(!$quiz) {
1849
            return [];
1850
        }
1851
 
1852
        $companyMapper = CompanyMapper::getInstance($this->adapter);
1853
        $company = $companyMapper->fetchOne($quiz->company_id);
1854
 
283 www 1855
        $questionMapper = MicrolearningQuestionMapper::getInstance($this->adapter);
1856
        $answerMapper = MicrolearningAnswerMapper::getInstance($this->adapter);
229 efrain 1857
 
1858
        $record_questions = [];
1859
        $questions = $questionMapper->fetchAllByQuizId($quiz->id);
1860
        foreach($questions as $question)
1861
        {
1862
            $record_answers = [];
1863
 
1864
            $answers = $answerMapper->fetchAllByQuizIdAndQuestionId($question->quiz_id, $question->id);
1865
            foreach($answers as $answer)
1866
            {
1867
                $dtAddedOn = \DateTime::createFromFormat('Y-m-d H:i:s', $answer->added_on);
1868
                $dtUpdatedOn = \DateTime::createFromFormat('Y-m-d H:i:s', $answer->updated_on);
1869
 
1870
                array_push($record_answers, [
1871
                    'uuid' => $answer->uuid,
1872
                    'text' => trim($answer->text),
1873
                    'correct' => $answer->correct ? $answer->correct  : 0 ,
1874
                    'points' => strval(intval($answer->points, 10)),
1875
                    'added_on'  => $dtAddedOn->format($serviceDatetimeFormat),
1876
                    'updated_on'    => $dtUpdatedOn->format($serviceDatetimeFormat),
1877
                ]);
1878
            }
1879
 
1880
            $dtAddedOn = \DateTime::createFromFormat('Y-m-d H:i:s', $question->added_on);
1881
            $dtUpdatedOn = \DateTime::createFromFormat('Y-m-d H:i:s', $question->updated_on);
1882
 
1883
            array_push($record_questions, [
1884
                'uuid'          => $question->uuid,
1885
                'text'          => trim($question->text),
1886
                'type'          => $question->type,
1887
                'maxlength'     => strval($question->maxlength),
1888
                'points'        => strval($question->points),
1889
                'answers'       => $record_answers,
1890
                'added_on'      => $dtAddedOn->format($serviceDatetimeFormat),
1891
                'updated_on'    => $dtUpdatedOn->format($serviceDatetimeFormat),
1892
            ]);
1893
        }
1894
 
1895
        $dtAddedOn = \DateTime::createFromFormat('Y-m-d H:i:s', $quiz->added_on);
1896
        $dtUpdatedOn = \DateTime::createFromFormat('Y-m-d H:i:s', $quiz->updated_on);
1897
 
1898
        array_push($data, [
1899
            'uuid' => $quiz->uuid,
1900
            'name' => $quiz->name,
1901
            'text' => trim($quiz->text ? $quiz->text : ''),
1902
            'failed' => trim($quiz->failed ? $quiz->failed : ''),
1903
            'points' => strval($quiz->points),
1904
            'minimum_points_required' => strval($quiz->minimum_points_required),
1905
            'max_time' => $quiz->max_time ? $quiz->max_time : 5,
1906
            'company_uuid' => $company->uuid,
1907
            'company_name' => $company->name,
1908
            'company_image' => $this->url()->fromRoute('services/storage',['type' => 'company', 'code' => $company->uuid, 'filename' => $company->image], ['force_canonical' => true]),
1909
            'questions'     => $record_questions,
1910
            'added_on'      => $dtAddedOn->format($serviceDatetimeFormat),
1911
            'updated_on'    => $dtUpdatedOn->format($serviceDatetimeFormat),
1912
        ]);
1913
 
1914
        return $data;
1915
 
1916
    }
161 efrain 1917
 
229 efrain 1918
 
161 efrain 1919
    public function getSlideAction()
1920
    {
1921
        $request = $this->getRequest();
1922
        if($request->isGet()) {
1923
            $currentUserPlugin = $this->plugin('currentUserPlugin');
1924
            $currentUser = $currentUserPlugin->getUser();
1925
 
1926
 
1927
 
1928
            $id = $this->params()->fromRoute('id');
283 www 1929
            $slideMapper = MicrolearningSlideMapper::getInstance($this->adapter);
161 efrain 1930
            $slide = $slideMapper->fetchOneByUuid($id);
1931
 
1932
            if(!$slide) {
1933
                return new JsonModel([
1934
                    'success' => false,
1935
                    'data' => 'ERROR_SLIDE_NOT_FOUND'
1936
                ]);
1937
            }
1938
 
1939
            $accessGrantedIds = $this->getAccessGranted();
1940
 
1941
 
1942
 
1943
            if(!in_array($slide->capsule_id, $accessGrantedIds->capsules)) {
1944
                return new JsonModel([
1945
                    'success' => false,
1946
                    'data' => 'ERROR_YOU_DO_NOT_HAVE_ACCESS_TO_THIS_CAPSULE'
1947
                ]);
1948
            }
1949
 
1950
 
283 www 1951
            $topicMapper = MicrolearningTopicMapper::getInstance($this->adapter);
161 efrain 1952
            $topic = $topicMapper->fetchOne($slide->topic_id);
1953
 
283 www 1954
            $capsuleMapper =  MicrolearningCapsuleMapper::getInstance($this->adapter);
161 efrain 1955
            $capsule = $capsuleMapper->fetchOne($slide->capsule_id);
1956
 
1957
 
1958
 
1959
 
1960
 
283 www 1961
            $slideMapper = MicrolearningSlideMapper::getInstance($this->adapter);
1962
            $userProgressMapper = MicrolearningUserProgressMapper::getInstance($this->adapter);
161 efrain 1963
 
1964
 
1965
            $userProgress = $userProgressMapper->fetchOneByUserIdAndSlideId($currentUser->id, $slide->id);
1966
            if($userProgress) {
1967
                $completed = $userProgress->completed;
1968
            } else {
1969
                $completed = 0;
1970
            }
235 efrain 1971
 
1972
            $quiz_uuid = '';
1973
            $quiz_data = [];
1974
            $link_take_a_test = '';
1975
            if($slide->quiz_id) {
1976
 
283 www 1977
                $quizMapper = MicrolearningQuizMapper::getInstance($this->adapter);
235 efrain 1978
                $quiz = $quizMapper->fetchOne($slide->quiz_id);
1979
                if($quiz) {
1980
                    $quiz_uuid = $quiz->uuid;
1981
                    $quiz_data = $this->getQuiz($slide->quiz_id);
1982
                    $link_take_a_test = $this->url()->fromRoute('microlearning/take-a-test', ['slide_id' => $slide->uuid], ['force_canonical' => true]);
1983
                }
161 efrain 1984
 
235 efrain 1985
            }
161 efrain 1986
 
333 www 1987
            $storage = Storage::getInstance($this->config, $this->adapter);
283 www 1988
            $path = $storage->getPathMicrolearningSlide();
161 efrain 1989
 
1990
            $data =[
235 efrain 1991
                'quiz'              => $quiz_uuid,
1992
                'quiz_data'         => $quiz_data,
1993
                'uuid'              => $slide->uuid,
1994
                'name'              => $slide->name ? $slide->name : '',
1995
                'description'       => $slide->description ? $slide->description : '',
1996
                'type'              => $slide->type,
283 www 1997
                'background'        => $slide->background ? $storage->getGenericImage($path, $slide->uuid, $slide->background) : '',
1998
                'file'              => $slide->file ? $storage->getGenericFile($path, $slide->uuid, $slide->file) : '',
235 efrain 1999
                'order'             => $slide->order,
2000
                'completed'         => $completed,
2001
                'link_sync'         => $this->url()->fromRoute('microlearning/sync', ['operation' => 'slide-view', 'topic_uuid' => $topic->uuid, 'capsule_uuid' => $capsule->uuid, 'slide_uuid' => $slide->uuid], ['force_canonical' => true]),
2002
                'link_take_a_test'  => $link_take_a_test,
2003
                'added_on'          => $slide->added_on,
2004
                'updated_on'        => $slide->updated_on,
161 efrain 2005
            ];
2006
 
2007
 
2008
 
2009
 
2010
            return new JsonModel([
2011
                'success' => true,
2012
                'data' => $data
2013
            ]);
2014
 
2015
        } else {
2016
            return new JsonModel([
2017
                'success' => false,
2018
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
2019
            ]);
2020
        }
2021
    }
2022
 
119 efrain 2023
    public function profileAction()
2024
    {
2025
        $request = $this->getRequest();
2026
        if($request->isGet()) {
2027
            $currentUserPlugin = $this->plugin('currentUserPlugin');
2028
            $currentUser = $currentUserPlugin->getUser();
2029
 
2030
 
2031
            $accessGrantedIds = $this->getAccessGranted();
2032
 
2033
            $companyMapper = CompanyMapper::getInstance($this->adapter);
283 www 2034
            $companyExtendUserMapper = MicrolearningExtendUserMapper::getInstance($this->adapter);
2035
            $companyExtendUserCompanyMapper = MicrolearningExtendUserCompanyMapper::getInstance($this->adapter);
2036
            $companyExtendUserFunctionMapper = MicrolearningExtendUserFunctionMapper::getInstance($this->adapter);
2037
            $companyExtendUserGroupMapper = MicrolearningExtendUserGroupMapper::getInstance($this->adapter);
2038
            $companyExtendUserInstitutionMapper = MicrolearningExtendUserInstitutionMapper::getInstance($this->adapter);
2039
            $companyExtendUserPartnerMapper = MicrolearningExtendUserPartnerMapper::getInstance($this->adapter);
2040
            $companyExtendUserProgramMapper = MicrolearningExtendUserProgramMapper::getInstance($this->adapter);
2041
            $companyExtendUserStudentTypeMapper = MicrolearningExtendUserStudentTypeMapper::getInstance($this->adapter);
2042
            $companyExtendUserSectorMapper = MicrolearningExtendUserSectorMapper::getInstance($this->adapter);
119 efrain 2043
 
333 www 2044
            $storage = Storage::getInstance($this->config, $this->adapter);
283 www 2045
 
119 efrain 2046
 
2047
            $data = [];
2048
            foreach($accessGrantedIds->companies as $company_id)
2049
            {
2050
                $company = $companyMapper->fetchOne($company_id);
2051
                if(!$company) {
2052
                    continue;
2053
                }
2054
 
2055
                $record = [
2056
                    'name' => $company->name,
283 www 2057
                    'image' => $storage->getCompanyImage($company),
119 efrain 2058
                    'details' => [],
2059
                ];
2060
 
2061
                $companyExtendUser = $companyExtendUserMapper->fetchOneByCompanyIdAndUserId($company->id, $currentUser->id);
2062
                if(!$companyExtendUser) {
2063
                    continue;
2064
                }
2065
 
2066
                if($companyExtendUser->extend_company_id) {
2067
 
2068
                    $extendedCompany = $companyExtendUserCompanyMapper->fetchOne($companyExtendUser->company_id);
2069
                    if($extendedCompany) {
2070
                        array_push($record['details'],[
2071
                            'uuid' => $extendedCompany->uuid,
2072
                            'label' => 'LABEL_COMPANY',
2073
                            'value' => $extendedCompany->name
2074
                        ]);
2075
                    }
2076
                }
2077
 
2078
                if($companyExtendUser->extend_function_id) {
2079
                    $extendedFunction = $companyExtendUserFunctionMapper->fetchOne($companyExtendUser->extend_function_id);
2080
                    if($extendedFunction) {
2081
                        array_push($record['details'],[
2082
                            'uuid' => $extendedFunction->uuid,
2083
                            'label' => 'LABEL_FUNCTION',
2084
                            'value' => $extendedFunction->name
2085
                        ]);
2086
                    }
2087
                }
2088
 
2089
                if($companyExtendUser->extend_group_id) {
2090
                    $extendedGroup = $companyExtendUserGroupMapper->fetchOne($companyExtendUser->extend_group_id);
2091
                    if($extendedGroup) {
2092
                        array_push($record['details'],[
2093
                            'uuid' => $extendedGroup->uuid,
2094
                            'label' => 'LABEL_GROUP',
2095
                            'value' => $extendedGroup->name
2096
                        ]);
2097
                    }
2098
                }
2099
 
2100
                if($companyExtendUser->extend_institution_id) {
2101
                    $extendedInstitution= $companyExtendUserInstitutionMapper->fetchOne($companyExtendUser->extend_institution_id);
2102
                    if($extendedInstitution) {
2103
                        array_push($record['details'],[
2104
                            'uuid' => $extendedInstitution->uuid,
2105
                            'label' => 'LABEL_INSTITUTION',
2106
                            'value' => $extendedInstitution->name
2107
                        ]);
2108
                    }
2109
                }
2110
 
2111
                if($companyExtendUser->extend_program_id) {
2112
                    $extendedProgram = $companyExtendUserProgramMapper->fetchOne($companyExtendUser->extend_program_id);
2113
                    if($extendedProgram) {
2114
                        array_push($record['details'],[
2115
                            'uuid' => $extendedProgram->uuid,
2116
                            'label' => 'LABEL_PROGRAM',
2117
                            'value' => $extendedProgram->name
2118
                        ]);
2119
 
2120
                    }
2121
                }
2122
 
2123
                if($companyExtendUser->extend_sector_id) {
2124
                    $extendedSector = $companyExtendUserSectorMapper->fetchOne($companyExtendUser->extend_sector_id);
2125
                    if($extendedSector) {
2126
                        array_push($record['details'],[
2127
                            'uuid' => $extendedSector->uuid,
2128
                            'label' => 'LABEL_SECTOR',
2129
                            'value' => $extendedSector->name
2130
                        ]);
2131
                    }
2132
                }
2133
 
2134
                if($companyExtendUser->extend_partner_id) {
2135
                    $extendedPartner = $companyExtendUserPartnerMapper->fetchOne($companyExtendUser->extend_partner_id);
2136
                    if($extendedPartner) {
2137
                        array_push($record['details'],[
2138
                            'uuid' => $extendedPartner->uuid,
2139
                            'label' => 'LABEL_PARTNER',
2140
                            'value' => $extendedPartner->name
2141
                        ]);
2142
                    }
2143
                }
2144
 
2145
                if($companyExtendUser->extend_student_type_id) {
2146
                    $extendedStudentType = $companyExtendUserStudentTypeMapper->fetchOne($companyExtendUser->extend_student_type_id);
2147
                    if($extendedStudentType) {
2148
                        array_push($record['details'],[
2149
                            'uuid' => $extendedStudentType->uuid,
2150
                            'label' => 'LABEL_TYPE',
2151
                            'value' => $extendedStudentType->name
2152
                        ]);
2153
                    }
2154
                }
2155
 
2156
                array_push($data, $record);
2157
            }
2158
 
2159
            return new JsonModel([
2160
                'success' => true,
2161
                'data' => $data
2162
            ]);
2163
 
2164
        } else {
2165
            return new JsonModel([
2166
                'success' => false,
2167
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
2168
            ]);
2169
        }
2170
    }
2171
 
167 efrain 2172
    public function syncAction()
2173
    {
2174
        $request = $this->getRequest();
168 efrain 2175
        if($request->isPost()) {
167 efrain 2176
            $currentUserPlugin = $this->plugin('currentUserPlugin');
2177
            $currentUser = $currentUserPlugin->getUser();
2178
 
2179
 
2180
            $operation = $this->params()->fromRoute('operation');
2181
            if($operation == 'slide-view' || $operation == 'capsule-close' || $operation == 'topic-close') {
2182
                $accessGrantedIds = $this->getAccessGranted();
2183
 
2184
                $topic_uuid     = $this->params()->fromRoute('topic_uuid');
2185
                $capsule_uuid   = $this->params()->fromRoute('capsule_uuid');
2186
                $slide_uuid     = $this->params()->fromRoute('slide_uuid');
2187
 
2188
                $accessGrantedIds = $this->getAccessGranted();
2189
                if($operation == 'slide-view') {
2190
 
2191
                    if(empty($slide_uuid) || empty($capsule_uuid ) || empty($topic_uuid)) {
2192
                        return new JsonModel([
2193
                            'success' => false,
2194
                            'data' => 'ERROR_INVALID_PARAMETERS'
2195
                        ]);
2196
                    }
2197
 
2198
 
283 www 2199
                    $topicMapper = MicrolearningTopicMapper::getInstance($this->adapter);
167 efrain 2200
                    $topic = $topicMapper->fetchOneByUuid($topic_uuid);
2201
 
2202
                    if(!$topic) {
2203
                        return new JsonModel([
2204
                            'success' => false,
2205
                            'data' => 'ERROR_TOPIC_NOT_FOUND'
2206
                        ]);
2207
                    }
2208
 
2209
 
2210
 
2211
                    if(!in_array($topic->id, $accessGrantedIds->topics)) {
2212
                        return new JsonModel([
2213
                            'success' => false,
2214
                            'data' => 'ERROR_YOU_DO_NOT_HAVE_ACCESS_TO_THIS_TOPIC'
2215
                        ]);
2216
                    }
2217
 
283 www 2218
                    $capsuleMapper = MicrolearningCapsuleMapper::getInstance($this->adapter);
167 efrain 2219
                    $capsule = $capsuleMapper->fetchOneByUuid($capsule_uuid);
2220
 
2221
                    if(!$capsule) {
2222
                        return new JsonModel([
2223
                            'success' => false,
2224
                            'data' => 'ERROR_CAPSULE_NOT_FOUND'
2225
                        ]);
2226
                    }
119 efrain 2227
 
167 efrain 2228
                    if(!in_array($capsule->id, $accessGrantedIds->capsules) || $capsule->topic_id != $topic->id) {
2229
                        return new JsonModel([
2230
                            'success' => false,
2231
                            'data' => 'ERROR_YOU_DO_NOT_HAVE_ACCESS_TO_THIS_CAPSULE'
2232
                        ]);
2233
                    }
2234
 
283 www 2235
                    $slideMapper = MicrolearningSlideMapper::getInstance($this->adapter);
167 efrain 2236
                    $slide = $slideMapper->fetchOneByUuid($slide_uuid);
2237
                    if(!$slide) {
2238
                        return new JsonModel([
2239
                            'success' => false,
2240
                            'data' => 'ERROR_SLIDE_NOT_FOUND'
2241
                        ]);
2242
                    }
2243
 
2244
                    if($slide->capsule_id != $capsule->id && $slide->topic_id != $topic->id) {
2245
                        return new JsonModel([
2246
                            'success' => false,
2247
                            'data' => 'ERROR_SLIDE_NOT_FOUND'
2248
                        ]);
2249
 
2250
                    }
2251
 
2252
 
283 www 2253
                    $userLogMapper = MicrolearningUserLogMapper::getInstance($this->adapter);
167 efrain 2254
 
283 www 2255
                    $userProgressMapper = MicrolearningUserProgressMapper::getInstance($this->adapter);
167 efrain 2256
                    $added_on = $userProgressMapper->getDatebaseNow();
2257
 
2258
 
2259
                    $userProgressTopic = $userProgressMapper->fetchOneByUserIdAndTopicId($currentUser->id, $topic->id);
2260
                    if(!$userProgressTopic) {
2261
 
283 www 2262
                        $userProgressTopic = new MicrolearningUserProgress();
558 stevensc 2263
                        $userProgressTopic->company_id                  = $topic->company_id; // Usar company_id del tópico
2264
                        $userProgressTopic->topic_id                    = $topic->id;        // Usar id del tópico
176 efrain 2265
                        $userProgressTopic->user_id                     = $currentUser->id;
167 efrain 2266
                        $userProgressTopic->progress                    = 0;
2267
                        $userProgressTopic->returning                   = 0;
2268
                        $userProgressTopic->returning_after_completed   = 0;
2269
                        $userProgressTopic->completed                   = 0;
558 stevensc 2270
                        $userProgressTopic->total_slides                = $slideMapper->fetchTotalCountByCompanyIdAndTopicId($topic->company_id, $topic->id);
167 efrain 2271
                        $userProgressTopic->view_slides                 = 0;
283 www 2272
                        $userProgressTopic->type                        = MicrolearningUserProgress::TYPE_TOPIC;
167 efrain 2273
                        $userProgressTopic->added_on                    = $added_on;
2274
                        $userProgressTopic->updated_on                  = $added_on;
2275
 
2276
                        if($userProgressMapper->insert($userProgressTopic)) {
2277
 
283 www 2278
                            $userLog = new MicrolearningUserLog();
2279
                            $userLog->activity      = MicrolearningUserLog::ACTIVITY_START_TOPIC;
167 efrain 2280
                            $userLog->user_id       = $currentUser->id;
558 stevensc 2281
                            $userLog->company_id    = $topic->company_id;
2282
                            $userLog->topic_id      = $topic->id;
167 efrain 2283
                            $userLog->added_on      = $added_on;
2284
 
2285
                            if(!$userLogMapper->insert($userLog)) {
2286
                                return new JsonModel([
2287
                                    'success' => false,
2288
                                    'data' => $userProgressMapper->getError()
2289
                                ]);
2290
                            }
2291
                        } else {
2292
                            return new JsonModel([
2293
                                'success' => false,
2294
                                'data' => $userProgressMapper->getError()
2295
                            ]);
2296
                        }
2297
                    }
2298
 
2299
 
2300
                    $userProgressCapsule = $userProgressMapper->fetchOneByUseridAndCapsuleId($currentUser->id, $capsule->id);
2301
                    if(!$userProgressCapsule) {
2302
 
283 www 2303
                        $userProgressCapsule = new MicrolearningUserProgress();
558 stevensc 2304
                        $userProgressCapsule->company_id                  = $capsule->company_id; // Usar company_id de la cápsula
2305
                        $userProgressCapsule->topic_id                    = $topic->id;         // Usar el id del tópico obtenido previamente
2306
                        $userProgressCapsule->capsule_id                  = $capsule->id;       // Usar id de la cápsula
176 efrain 2307
                        $userProgressCapsule->user_id                     = $currentUser->id;
167 efrain 2308
                        $userProgressCapsule->progress                    = 0;
2309
                        $userProgressCapsule->returning                   = 0;
2310
                        $userProgressCapsule->returning_after_completed   = 0;
2311
                        $userProgressCapsule->completed                   = 0;
558 stevensc 2312
                        $userProgressCapsule->total_slides                = $slideMapper->fetchTotalCountByCompanyIdAndTopicIdAndCapsuleId($capsule->company_id, $topic->id, $capsule->id);
167 efrain 2313
                        $userProgressCapsule->view_slides                 = 0;
2314
                        $userProgressTopic->updated_on                    = $added_on;
2315
 
2316
                        if($userProgressMapper->insert($userProgressCapsule)) {
2317
 
283 www 2318
                            $userLog = new MicrolearningUserLog();
2319
                            $userLog->activity      = MicrolearningUserLog::ACTIVITY_START_CAPSULE;
167 efrain 2320
                            $userLog->user_id       = $currentUser->id;
558 stevensc 2321
                            $userLog->company_id    = $capsule->company_id;
2322
                            $userLog->topic_id      = $topic->id;
2323
                            $userLog->capsule_id    = $capsule->id;
167 efrain 2324
                            $userLog->added_on      = $added_on;
2325
 
2326
                            if(!$userLogMapper->insert($userLog)) {
2327
                                return new JsonModel([
2328
                                    'success' => false,
2329
                                    'data' => $userLogMapper->getError()
2330
                                ]);
2331
                            }
2332
                        } else {
2333
                            return new JsonModel([
2334
                                'success' => false,
2335
                                'data' => $userProgressMapper->getError()
2336
                            ]);
2337
                        }
2338
                    }
2339
 
2340
 
2341
                    $userProgressSlide = $userProgressMapper->fetchOneByUserIdAndSlideId($currentUser->id, $slide->id);
2342
                    if(!$userProgressSlide) {
283 www 2343
                        $userProgressSlide = new MicrolearningUserProgress();
167 efrain 2344
                        $userProgressSlide->company_id                  = $slide->company_id;
2345
                        $userProgressSlide->topic_id                    = $slide->topic_id;
2346
                        $userProgressSlide->capsule_id                  = $slide->capsule_id;
2347
                        $userProgressSlide->slide_id                    = $slide->id;
176 efrain 2348
                        $userProgressSlide->user_id                     = $currentUser->id;
167 efrain 2349
                        $userProgressSlide->progress                    = 0;
2350
                        $userProgressSlide->returning                   = 0;
2351
                        $userProgressSlide->returning_after_completed   = 0;
2352
                        $userProgressSlide->completed                   = 1;
2353
                        $userProgressSlide->total_slides                = 0;
2354
                        $userProgressSlide->view_slides                 = 0;
283 www 2355
                        $userProgressSlide->type                        = MicrolearningUserProgress::TYPE_SLIDE;
167 efrain 2356
                        $userProgressSlide->added_on                    = $added_on;
2357
                        $userProgressSlide->updated_on                  = $added_on;
2358
 
2359
                        if(!$userProgressMapper->insert($userProgressSlide)) {
2360
                            return new JsonModel([
2361
                                'success' => false,
2362
                                'data' => $userProgressMapper->getError()
2363
                            ]);
2364
                        }
2365
                    }
2366
 
283 www 2367
                    $userLog = new MicrolearningUserLog();
2368
                    $userLog->activity      = MicrolearningUserLog::ACTIVITY_VIEW_SLIDE;
167 efrain 2369
                    $userLog->user_id       = $currentUser->id;
2370
                    $userLog->company_id    = $slide->company_id;
2371
                    $userLog->topic_id      = $slide->topic_id;
2372
                    $userLog->capsule_id    = $slide->capsule_id;
2373
                    $userLog->slide_id      = $slide->id;
2374
                    $userLog->added_on      = $added_on;
2375
 
2376
                    if(!$userLogMapper->insert($userLog)) {
2377
                        return new JsonModel([
2378
                            'success' => false,
2379
                            'data' => $userLogMapper->getError()
2380
                        ]);
2381
                    }
2382
 
2383
                    $closeCapsule = false;
2384
 
2385
                    if($userProgressCapsule->completed) {
2386
 
2387
                        $dt = \DateTime::createFromFormat('Y-m-d H:i:s', $added_on);
2388
                        $returning_on = $dt->format('Y-m-d');
2389
 
558 stevensc 2390
                        // Asegurarse que returning_on existe en el objeto antes de comparar
2391
                        $current_returning_on = isset($userProgressCapsule->returning_on) ? $userProgressCapsule->returning_on : null;
2392
 
2393
                        if(!$current_returning_on || $current_returning_on != $returning_on) {
167 efrain 2394
 
2395
                            $userProgressCapsule->returning_on = $returning_on;
558 stevensc 2396
                            // Asegurarse que returning_after_completed existe y es numérico antes de incrementar
2397
                            $userProgressCapsule->returning_after_completed = (isset($userProgressCapsule->returning_after_completed) ? intval($userProgressCapsule->returning_after_completed) : 0) + 1;
167 efrain 2398
 
2399
                            if(!$userProgressMapper->update($userProgressCapsule)) {
2400
                                return new JsonModel([
2401
                                    'success' => false,
2402
                                    'data' => $userProgressMapper->getError()
2403
                                ]);
2404
                            }
2405
                        }
2406
 
2407
                    }  else {
2408
 
558 stevensc 2409
                        // Usar $topic->id para obtener el total de slides de la cápsula en el contexto de este tópico
2410
                        $userProgressCapsule->total_slides = $slideMapper->fetchTotalCountByCompanyIdAndTopicIdAndCapsuleId($capsule->company_id, $topic->id, $capsule->id);
2411
                        $userProgressCapsule->view_slides = $userProgressMapper->fetchCountAllSlideCompletedByUserIdAndCapsuleId($currentUser->id, $capsule->id);
167 efrain 2412
 
2413
                        if($userProgressCapsule->total_slides) {
2414
 
2415
                            $userProgressCapsule->progress = ($userProgressCapsule->view_slides * 100) / $userProgressCapsule->total_slides;
2416
                            $userProgressCapsule->progress = $userProgressCapsule->progress > 100 ? 100 : $userProgressCapsule->progress;
2417
                        }
2418
 
2419
                        if(!$userProgressMapper->update($userProgressCapsule)) {
2420
                            return new JsonModel([
2421
                                'success' => false,
2422
                                'data' => $userProgressMapper->getError()
2423
                            ]);
2424
                        }
2425
 
2426
                        if($userProgressCapsule->progress >= 100) {
2427
                            $closeCapsule = true;
2428
                        }
171 efrain 2429
 
283 www 2430
 
167 efrain 2431
                    }
2432
 
2433
                    $closeTopic = false;
2434
                    if(!$userProgressTopic->completed) {
2435
 
558 stevensc 2436
                        // Usar $topic->id para obtener el total de slides del tópico
2437
                        $userProgressTopic->total_slides = $slideMapper->fetchTotalCountByCompanyIdAndTopicId($topic->company_id, $topic->id);
2438
                        $userProgressTopic->view_slides = $userProgressMapper->fetchCountAllSlideCompletedByUserIdAndTopicId($currentUser->id, $topic->id);
167 efrain 2439
 
2440
                        if($userProgressTopic->total_slides) {
2441
 
2442
                            $userProgressTopic->progress = ($userProgressTopic->view_slides * 100) / $userProgressTopic->total_slides;
2443
                            $userProgressTopic->progress = $userProgressTopic->progress > 100 ? 100 : $userProgressTopic->progress;
2444
                        }
2445
                        if(!$userProgressMapper->update($userProgressTopic)) {
2446
                            return new JsonModel([
2447
                                'success' => false,
2448
                                'data' => $userProgressMapper->getError()
2449
                            ]);
2450
                        }
2451
 
2452
                        if($userProgressTopic->progress >= 100) {
2453
                            $closeTopic = true;
2454
                        }
2455
                    }
2456
 
2457
 
2458
                    $data = [
2459
                        'message' => 'LABEL_THE_USER_PROGRESS_FOR_THIS_SLIDE_HAS_BEEN_COMPLETED',
2460
 
2461
                    ];
2462
 
2463
                    if($closeCapsule) {
173 efrain 2464
                        $data['link_close_capsule'] = $this->url()->fromRoute('microlearning/sync', ['operation' => 'capsule-close', 'topic_uuid' => $topic->uuid, 'capsule_uuid' => $capsule->uuid], ['force_canonical' => true]);
167 efrain 2465
                    }
2466
 
2467
 
2468
                    if($closeTopic) {
173 efrain 2469
                        $data['link_close_topic'] = $this->url()->fromRoute('microlearning/sync', ['operation' => 'topic-close', 'topic_uuid' => $topic->uuid], ['force_canonical' => true]);
167 efrain 2470
                    }
2471
 
2472
 
2473
                    return new JsonModel([
2474
                        'success' => true,
2475
                        'data' => $data
2476
                    ]);
2477
 
2478
 
2479
 
2480
 
2481
                } else if($operation == 'capsule-close') {
2482
 
2483
                    if(empty($capsule_uuid ) || empty($topic_uuid)) {
2484
                        return new JsonModel([
2485
                            'success' => false,
2486
                            'data' => 'ERROR_INVALID_PARAMETERS'
2487
                        ]);
2488
                    }
2489
 
2490
 
283 www 2491
                    $topicMapper = MicrolearningTopicMapper::getInstance($this->adapter);
167 efrain 2492
                    $topic = $topicMapper->fetchOneByUuid($topic_uuid);
2493
 
2494
                    if(!$topic) {
2495
                        return new JsonModel([
2496
                            'success' => false,
2497
                            'data' => 'ERROR_TOPIC_NOT_FOUND'
2498
                        ]);
2499
                    }
2500
 
2501
 
2502
 
2503
                    if(!in_array($topic->id, $accessGrantedIds->topics)) {
2504
                        return new JsonModel([
2505
                            'success' => false,
2506
                            'data' => 'ERROR_YOU_DO_NOT_HAVE_ACCESS_TO_THIS_TOPIC'
2507
                        ]);
2508
                    }
2509
 
283 www 2510
                    $capsuleMapper = MicrolearningCapsuleMapper::getInstance($this->adapter);
167 efrain 2511
                    $capsule = $capsuleMapper->fetchOneByUuid($capsule_uuid);
2512
 
2513
                    if(!$capsule) {
2514
                        return new JsonModel([
2515
                            'success' => false,
2516
                            'data' => 'ERROR_CAPSULE_NOT_FOUND'
2517
                        ]);
2518
                    }
2519
 
2520
                    if(!in_array($capsule->id, $accessGrantedIds->capsules) || $capsule->topic_id != $topic->id) {
2521
                        return new JsonModel([
2522
                            'success' => false,
2523
                            'data' => 'ERROR_YOU_DO_NOT_HAVE_ACCESS_TO_THIS_CAPSULE'
2524
                        ]);
2525
                    }
2526
 
2527
 
283 www 2528
                    $userLogMapper = MicrolearningUserLogMapper::getInstance($this->adapter);
167 efrain 2529
 
283 www 2530
                    $userProgressMapper = MicrolearningUserProgressMapper::getInstance($this->adapter);
167 efrain 2531
                    $updated_on = $userProgressMapper->getDatebaseNow();
2532
 
2533
                    $userProgressCapsule = $userProgressMapper->fetchOneByUseridAndCapsuleId($currentUser->id, $capsule->id);
2534
                    if(!$userProgressCapsule) {
2535
                        return new JsonModel([
2536
                            'success' => false,
2537
                            'data' => 'ERROR_THE_USER_PROGRESS_FOR_THIS_CAPSULE_NOT_FOUND'
2538
                        ]);
2539
                    }
2540
 
2541
                    if($userProgressCapsule->completed) {
2542
                        return new JsonModel([
2543
                            'success' => false,
2544
                            'data' => 'ERROR_THE_USER_PROGRESS_FOR_THIS_CAPSULE_ALREADY_CLOSED'
2545
                        ]);
2546
                    }
2547
 
2548
 
2549
                    $userProgressCapsule->completed = 1;
2550
                    $userProgressCapsule->updated_on = $updated_on;
2551
 
2552
                    if($userProgressMapper->update($userProgressCapsule)) {
225 efrain 2553
 
2554
 
283 www 2555
                        $userLog = new MicrolearningUserLog();
2556
                        $userLog->activity      = MicrolearningUserLog::ACTIVITY_COMPLETED_CAPSULE;
227 efrain 2557
                        $userLog->user_id       = $currentUser->id;
2558
                        $userLog->company_id    = $capsule->company_id;
2559
                        $userLog->topic_id      = $capsule->topic_id;
2560
                        $userLog->capsule_id    = $capsule->id;
2561
                        $userLog->added_on      = $updated_on;
225 efrain 2562
 
2563
                        if(!$userLogMapper->insert($userLog)) {
2564
                            return new JsonModel([
2565
                                'success' => false,
2566
                                'data' => $userProgressMapper->getError()
2567
                            ]);
2568
                        }
2569
 
2570
 
167 efrain 2571
                        return new JsonModel([
2572
                            'success' => true,
2573
                            'data' => 'LABEL_THE_USER_PROGRESS_FOR_THIS_CAPSULE_HAS_BEEN_COMPLETED'
2574
                        ]);
2575
                    } else {
2576
                        return new JsonModel([
2577
                            'success' => false,
2578
                            'data' => 'ERROR_THE_USER_PROGRESS_FOR_THIS_CAPSULE_COULD_NOT_BE_COMPLETED'
2579
                        ]);
2580
                    }
2581
 
2582
 
2583
 
2584
 
2585
 
2586
 
2587
 
2588
                } else if($operation == 'topic-close') {
174 efrain 2589
                    if(empty($topic_uuid)) {
167 efrain 2590
                        return new JsonModel([
2591
                            'success' => false,
2592
                            'data' => 'ERROR_INVALID_PARAMETERS'
2593
                        ]);
2594
                    }
2595
 
2596
 
283 www 2597
                    $topicMapper = MicrolearningTopicMapper::getInstance($this->adapter);
167 efrain 2598
                    $topic = $topicMapper->fetchOneByUuid($topic_uuid);
2599
 
2600
                    if(!$topic) {
2601
                        return new JsonModel([
2602
                            'success' => false,
2603
                            'data' => 'ERROR_TOPIC_NOT_FOUND'
2604
                        ]);
2605
                    }
2606
 
2607
 
2608
 
2609
                    if(!in_array($topic->id, $accessGrantedIds->topics)) {
2610
                        return new JsonModel([
2611
                            'success' => false,
2612
                            'data' => 'ERROR_YOU_DO_NOT_HAVE_ACCESS_TO_THIS_TOPIC'
2613
                        ]);
2614
                    }
2615
 
2616
 
2617
 
2618
 
283 www 2619
                    $userLogMapper = MicrolearningUserLogMapper::getInstance($this->adapter);
167 efrain 2620
 
283 www 2621
                    $userProgressMapper = MicrolearningUserProgressMapper::getInstance($this->adapter);
167 efrain 2622
                    $updated_on = $userProgressMapper->getDatebaseNow();
2623
 
2624
                    $userProgressTopic = $userProgressMapper->fetchOneByUserIdAndTopicId($currentUser->id, $topic->id);
2625
                    if(!$userProgressTopic) {
2626
                        return new JsonModel([
2627
                            'success' => false,
2628
                            'data' => 'ERROR_THE_USER_PROGRESS_FOR_THIS_TOPIC_NOT_FOUND'
2629
                        ]);
2630
                    }
2631
 
2632
                    if($userProgressTopic->completed) {
2633
                        return new JsonModel([
2634
                            'success' => false,
2635
                            'data' => 'ERROR_THE_USER_PROGRESS_FOR_THIS_TOPIC_ALREADY_CLOSED'
2636
                        ]);
2637
                    }
2638
 
2639
 
2640
                    $userProgressTopic->completed = 1;
2641
                    $userProgressTopic->updated_on = $updated_on;
2642
 
2643
                    if($userProgressMapper->update($userProgressTopic)) {
226 efrain 2644
 
283 www 2645
                        $userLog = new MicrolearningUserLog();
2646
                        $userLog->activity      = MicrolearningUserLog::ACTIVITY_COMPLETED_TOPIC;
227 efrain 2647
                        $userLog->user_id       = $currentUser->id;
2648
                        $userLog->company_id    = $topic->company_id;
2649
                        $userLog->topic_id      = $topic->id;
2650
                        $userLog->added_on      = $updated_on;
226 efrain 2651
 
2652
                        if(!$userLogMapper->insert($userLog)) {
2653
                            return new JsonModel([
2654
                                'success' => false,
2655
                                'data' => $userProgressMapper->getError()
2656
                            ]);
2657
                        }
2658
 
167 efrain 2659
                        return new JsonModel([
2660
                            'success' => true,
2661
                            'data' => 'LABEL_THE_USER_PROGRESS_FOR_THIS_TOPIC_HAS_BEEN_COMPLETED'
2662
                        ]);
2663
                    } else {
2664
                        return new JsonModel([
2665
                            'success' => false,
2666
                            'data' => 'ERROR_THE_USER_PROGRESS_FOR_THIS_TOPIC_COULD_NOT_BE_COMPLETED'
2667
                        ]);
2668
                    }
2669
                }
2670
 
2671
 
2672
 
2673
 
2674
            } else {
2675
 
2676
                return new JsonModel([
2677
                    'success' => false,
2678
                    'data' => 'ERROR_OPERATION_UNKNOWN'
2679
                ]);
2680
 
2681
 
2682
            }
2683
 
2684
        } else {
2685
            return new JsonModel([
2686
                'success' => false,
2687
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
2688
            ]);
2689
        }
2690
    }
2691
 
2692
 
302 www 2693
 
2694
 
2695
 
119 efrain 2696
    /**
2697
     *
2698
     * @return \LeadersLinked\Controller\MicrolearningUserAccessGrantedIds
2699
     */
2700
    private function getAccessGranted()
2701
    {
2702
        $currentUserPlugin = $this->plugin('currentUserPlugin');
2703
        $currentUser = $currentUserPlugin->getUser();
2704
 
283 www 2705
        $capsuleUserMapper = MicrolearningCapsuleUserMapper::getInstance($this->adapter);
119 efrain 2706
        $now = $capsuleUserMapper->getDatebaseNow();
2707
 
2708
        $records = $capsuleUserMapper->fetchAllActiveByUserId($currentUser->id);
2709
 
2710
        $accessGrantedIds = new MicrolearningUserAccessGrantedIds();
2711
 
2712
 
2713
        foreach($records as $record)
2714
        {
283 www 2715
            if($record->access != MicrolearningCapsuleUser::ACCESS_UNLIMITED && $record->access != MicrolearningCapsuleUser::ACCESS_PAY_PERIOD) {
119 efrain 2716
                continue;
2717
            }
283 www 2718
            if($record->access == MicrolearningCapsuleUser::ACCESS_PAY_PERIOD) {
119 efrain 2719
                if($now < $record->paid_from || $now > $record->paid_to) {
2720
                    continue;
2721
                }
2722
            }
2723
 
2724
 
2725
            if(!in_array($record->company_id, $accessGrantedIds->companies )) {
2726
                array_push($accessGrantedIds->companies, $record->company_id);
2727
            }
2728
 
2729
            if(!in_array($record->topic_id, $accessGrantedIds->topics )) {
2730
                array_push( $accessGrantedIds->topics, $record->topic_id);
2731
            }
2732
 
2733
            if(!in_array($record->capsule_id, $accessGrantedIds->capsules)) {
2734
                array_push( $accessGrantedIds->capsules, $record->capsule_id);
2735
            }
2736
        }
2737
 
2738
        return $accessGrantedIds;
2739
    }
2740
 
2741
 
2742
}