Proyectos de Subversion LeadersLinked - Services

Rev

Rev 574 | Rev 576 | 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);
119 efrain 515
 
516
 
302 www 517
                $dataCountAndRatingAverage = $capsuleCommentMapper->fetchCountAndRatingAverage($capsule->company_id,  $capsule->id);
119 efrain 518
 
301 www 519
 
119 efrain 520
                $response = [
521
                    'success' => true,
522
                    'data' => [
164 efrain 523
                        'uuid'              => $capsule->uuid,
119 efrain 524
                        'name'              => $capsule->name ? $capsule->name : '',
525
                        'description'       => $capsule->description ? $capsule->description : '',
575 stevensc 526
                        'image'             => ($capsule->image && $topic) ? $storage->getGenericImage($path,  $topic->uuid, $capsule->image )  : '',
119 efrain 527
                        'total_comments'    => strval($dataCountAndRatingAverage['total_comments']),
528
                        'total_rating'      => strval($dataCountAndRatingAverage['total_rating']),
529
                        'completed'         => $userProgress->completed,
145 efrain 530
                        'progress'          => $userProgress->progress,
119 efrain 531
                        'added_on'          => $userProgress->added_on,
532
                        'updated_on'        => $userProgress->updated_on
533
                    ]
534
                ];
535
 
536
 
537
            } else {
538
                $response = [
539
                    'success' => true,
575 stevensc 540
                    'data' => []
119 efrain 541
                ];
542
            }
543
 
544
 
545
        } else {
546
 
547
            $response = [
548
                'success' => false,
549
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
550
            ];
551
 
552
 
553
        }
554
 
555
        return new JsonModel($response);
556
    }
557
 
558
    public function capsulesPendingAction()
559
    {
560
        $request = $this->getRequest();
561
        if($request->isGet()) {
562
            $currentUserPlugin = $this->plugin('currentUserPlugin');
563
            $currentUser = $currentUserPlugin->getUser();
564
 
565
            $name = Functions::sanitizeFilterString($this->params()->fromQuery('name'));
245 efrain 566
            $order_field = Functions::sanitizeFilterString($this->params()->fromQuery('order_field'));
567
            $order_direction = Functions::sanitizeFilterString($this->params()->fromQuery('order_direction'));
119 efrain 568
 
245 efrain 569
            if(!in_array($order_field,['name', 'added_on'] )) {
570
                $order_field = 'name';
571
            }
119 efrain 572
 
245 efrain 573
            if(!in_array( $order_direction,['asc', 'desc'])) {
558 stevensc 574
                $order_direction = 'asc'; // Corregido: asignar a $order_direction
245 efrain 575
            }
576
 
283 www 577
            $userProgressMapper = MicrolearningUserProgressMapper::getInstance($this->adapter);
578
            $capsuleMapper = MicrolearningCapsuleMapper::getInstance($this->adapter);
558 stevensc 579
            $topicCapsuleMapper = MicrolearningTopicCapsuleMapper::getInstance($this->adapter); // Añadido
283 www 580
            $topicMapper = MicrolearningTopicMapper::getInstance($this->adapter);
558 stevensc 581
            $capsuleCommentMapper = MicrolearningCapsuleCommentMapper::getInstance($this->adapter); // Reordenado
119 efrain 582
 
583
            $accessGranted = $this->getAccessGranted();
558 stevensc 584
 
585
            // $topics = []; // Ya no es necesario cachear tópicos aquí
586
            $capsulesData = []; // Renombrado
119 efrain 587
 
333 www 588
            $storage = Storage::getInstance($this->config, $this->adapter);
283 www 589
            $path = $storage->getPathMicrolearningCapsule();
590
 
119 efrain 591
            foreach($accessGranted->capsules as $capsule_id)
592
            {
558 stevensc 593
                // 1. Verificar progreso (debe ser nulo para pendiente)
119 efrain 594
                $userProgress = $userProgressMapper->fetchOneByUseridAndCapsuleId($currentUser->id, $capsule_id);
595
                if($userProgress) {
596
                    continue;
597
                }
558 stevensc 598
 
599
                // 2. Obtener detalles de la cápsula
119 efrain 600
                $capsule = $capsuleMapper->fetchOne($capsule_id);
558 stevensc 601
                if(!$capsule) { // Añadir verificación por si la cápsula no existe
602
                    continue;
603
                }
119 efrain 604
 
558 stevensc 605
                // 3. Filtrar por nombre
119 efrain 606
                if($name) {
607
                    if(empty($name) || stripos($capsule->name, $name) === false) {
608
                        continue;
609
                    }
610
                }
611
 
558 stevensc 612
                // 4. Obtener Tópico asociado válido
613
                $topic = null;
614
                $topic_uuid_for_links = null;
615
                $relation = $topicCapsuleMapper->fetchOneByCapsuleId($capsule->id);
616
                if ($relation && in_array($relation->topic_id, $accessGranted->topics)) {
617
                    $topic = $topicMapper->fetchOne($relation->topic_id);
618
                    if ($topic) {
619
                        $topic_uuid_for_links = $topic->uuid;
620
                    }
621
                }
622
 
623
                // 5. Obtener datos de comentarios
302 www 624
                $dataCountAndRatingAverage = $capsuleCommentMapper->fetchCountAndRatingAverage($capsule->company_id,  $capsule->id);
119 efrain 625
 
558 stevensc 626
                // 6. Construir enlace slides
627
                $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 628
 
558 stevensc 629
                // 7. Añadir al array de resultados
630
                array_push($capsulesData, [
119 efrain 631
                    'uuid'              => $capsule->uuid,
632
                    'name'              => $capsule->name ? $capsule->name : '',
633
                    'description'       => $capsule->description ? $capsule->description : '',
283 www 634
                    'image'             => $capsule->image ? $storage->getGenericImage($path, $capsule->uuid, $capsule->image)  : '',
119 efrain 635
                    'position'          => $capsule->order,
636
                    'link_comments'     => $this->url()->fromRoute('microlearning/capsules-comments', ['capsule_id' => $capsule->uuid], ['force_canonical' => true]),
637
                    'link_comment_add'  => $this->url()->fromRoute('microlearning/capsules-comments/add', ['capsule_id' => $capsule->uuid],['force_canonical' => true]),
558 stevensc 638
                    'link_slides'       => $link_slides, // Usar enlace construido
119 efrain 639
                    'total_comments'    => strval($dataCountAndRatingAverage['total_comments']),
640
                    'total_rating'      => strval($dataCountAndRatingAverage['total_rating']),
191 efrain 641
                    'progress'          => 0,
162 efrain 642
                    'link_get'          => $this->url()->fromRoute('microlearning/get-capsule', ['id' => $capsule->uuid], ['force_canonical' => true]),
119 efrain 643
                    'added_on'          => $capsule->added_on,
644
                    'updated_on'        => $capsule->updated_on,
645
                ]);
646
            }
647
 
558 stevensc 648
            // 8. Ordenar
245 efrain 649
 
650
            if($order_field == 'name') {
651
                if($order_direction == 'asc') {
558 stevensc 652
                    usort($capsulesData, function($a, $b) {
245 efrain 653
                        return strcasecmp($a['name'], $b['name']);
654
                    });
655
                } else {
558 stevensc 656
                    usort($capsulesData, function($a, $b) {
245 efrain 657
                        $result = strcasecmp($a['name'], $b['name']);
558 stevensc 658
                        if($result < 0) { return 1; } else if($result > 0) { return -1; } else { return 0; } // Simplificado
245 efrain 659
                    });
119 efrain 660
                }
661
 
245 efrain 662
            }
663
 
664
            if($order_field == 'added_on') {
665
                if($order_direction == 'asc') {
558 stevensc 666
                    usort($capsulesData, function($a, $b) {
245 efrain 667
                        return strcasecmp($a['added_on'], $b['added_on']);
668
                    });
669
                } else {
558 stevensc 670
                    usort($capsulesData, function($a, $b) {
245 efrain 671
                        $result = strcasecmp($a['added_on'], $b['added_on']);
558 stevensc 672
                        if($result < 0) { return 1; } else if($result > 0) { return -1; } else { return 0; } // Simplificado
245 efrain 673
                    });
674
                }
119 efrain 675
 
558 stevensc 676
            }
119 efrain 677
 
558 stevensc 678
            // 9. Retornar
119 efrain 679
            return new JsonModel([
680
                'success' => true,
558 stevensc 681
                'data' => $capsulesData
119 efrain 682
            ]);
683
 
684
 
685
 
686
        }
687
 
688
        return new JsonModel([
689
            'success' => false,
690
            'data' => 'ERROR_METHOD_NOT_ALLOWED'
691
        ]);
692
 
693
    }
694
 
695
    public function capsulesCompletedAction()
696
    {
697
        $request = $this->getRequest();
698
        if($request->isGet()) {
699
            $currentUserPlugin = $this->plugin('currentUserPlugin');
700
            $currentUser = $currentUserPlugin->getUser();
701
 
702
            $name = Functions::sanitizeFilterString($this->params()->fromQuery('name'));
245 efrain 703
            $order_field = Functions::sanitizeFilterString($this->params()->fromQuery('order_field'));
704
            $order_direction = Functions::sanitizeFilterString($this->params()->fromQuery('order_direction'));
119 efrain 705
 
246 efrain 706
            if(!in_array($order_field,['name', 'added_on','last_access_on'] )) {
245 efrain 707
                $order_field = 'name';
708
            }
119 efrain 709
 
245 efrain 710
            if(!in_array( $order_direction,['asc', 'desc'])) {
711
                $order_field = 'asc';
712
            }
713
 
283 www 714
            $userProgressMapper = MicrolearningUserProgressMapper::getInstance($this->adapter);
715
            $capsuleMapper = MicrolearningCapsuleMapper::getInstance($this->adapter);
558 stevensc 716
            $topicCapsuleMapper = MicrolearningTopicCapsuleMapper::getInstance($this->adapter);
717
            $topicMapper = MicrolearningTopicMapper::getInstance($this->adapter);
283 www 718
            $capsuleCommentMapper = MicrolearningCapsuleCommentMapper::getInstance($this->adapter);
119 efrain 719
 
720
            $accessGranted = $this->getAccessGranted();
721
 
558 stevensc 722
            $capsulesData = [];
119 efrain 723
 
333 www 724
            $storage = Storage::getInstance($this->config, $this->adapter);
283 www 725
            $path = $storage->getPathMicrolearningCapsule();
726
 
119 efrain 727
            foreach($accessGranted->capsules as $capsule_id)
728
            {
558 stevensc 729
                // 1. Verificar progreso
119 efrain 730
                $userProgress = $userProgressMapper->fetchOneByUseridAndCapsuleId($currentUser->id, $capsule_id);
731
                if(!$userProgress) {
732
                    continue;
733
                }
734
 
735
                if(!$userProgress->completed) {
736
                    continue;
737
                }
738
 
558 stevensc 739
                // 2. Obtener detalles de la cápsula
119 efrain 740
                $capsule = $capsuleMapper->fetchOne($capsule_id);
558 stevensc 741
                if(!$capsule) {
742
                    continue;
743
                }
119 efrain 744
 
558 stevensc 745
                // 3. Filtrar por nombre
119 efrain 746
                if($name) {
747
                    if(empty($name) || stripos($capsule->name, $name) === false) {
748
                        continue;
749
                    }
750
                }
751
 
558 stevensc 752
                // 4. Obtener Tópico asociado válido
753
                $topic = null;
754
                $topic_uuid_for_links = null;
755
                $relation = $topicCapsuleMapper->fetchOneByCapsuleId($capsule->id);
756
                if ($relation && in_array($relation->topic_id, $accessGranted->topics)) {
757
                    $topic = $topicMapper->fetchOne($relation->topic_id);
758
                    if ($topic) {
759
                        $topic_uuid_for_links = $topic->uuid;
760
                    }
761
                }
762
 
763
                // 5. Obtener datos de comentarios
302 www 764
                $dataCountAndRatingAverage = $capsuleCommentMapper->fetchCountAndRatingAverage($capsule->company_id, $capsule->id);
119 efrain 765
 
558 stevensc 766
                // 6. Construir enlace slides
767
                $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 768
 
558 stevensc 769
                // 7. Añadir al array de resultados
770
                array_push($capsulesData, [
119 efrain 771
                    'uuid'              => $capsule->uuid,
772
                    'name'              => $capsule->name ? $capsule->name : '',
773
                    'description'       => $capsule->description ? $capsule->description : '',
283 www 774
                    'image'             => $capsule->image ? $storage->getGenericImage($path, $capsule->uuid, $capsule->image)  : '',
119 efrain 775
                    'position'          => $capsule->order,
776
                    'link_comments'     => $this->url()->fromRoute('microlearning/capsules-comments', ['capsule_id' => $capsule->uuid], ['force_canonical' => true]),
777
                    'link_comment_add'  => $this->url()->fromRoute('microlearning/capsules-comments/add', ['capsule_id' => $capsule->uuid],['force_canonical' => true]),
558 stevensc 778
                    'link_slides'       => $link_slides,
119 efrain 779
                    'total_comments'    => strval($dataCountAndRatingAverage['total_comments']),
780
                    'total_rating'      => strval($dataCountAndRatingAverage['total_rating']),
145 efrain 781
                    'progress'          => $userProgress->progress,
162 efrain 782
                    'link_get'          => $this->url()->fromRoute('microlearning/get-capsule', ['id' => $capsule->uuid], ['force_canonical' => true]),
119 efrain 783
                    'added_on'          => $capsule->added_on,
246 efrain 784
                    'last_access_on'    => $userProgress->updated_on,
119 efrain 785
                    'updated_on'        => $capsule->updated_on,
786
                ]);
787
            }
788
 
558 stevensc 789
            // 8. Ordenar (lógica de ordenación permanece igual, usando $capsulesData)
245 efrain 790
            if($order_field == 'name') {
791
                if($order_direction == 'asc') {
558 stevensc 792
                    usort($capsulesData, function($a, $b) {
245 efrain 793
                        return strcasecmp($a['name'], $b['name']);
794
                    });
795
                } else {
558 stevensc 796
                    usort($capsulesData, function($a, $b) {
245 efrain 797
                        $result = strcasecmp($a['name'], $b['name']);
558 stevensc 798
                        if($result < 0) { return 1; } else if($result > 0) { return -1; } else { return 0; }
245 efrain 799
                    });
119 efrain 800
                }
245 efrain 801
            }
802
 
803
            if($order_field == 'added_on') {
804
                if($order_direction == 'asc') {
558 stevensc 805
                    usort($capsulesData, function($a, $b) {
245 efrain 806
                        return strcasecmp($a['added_on'], $b['added_on']);
807
                    });
808
                } else {
558 stevensc 809
                    usort($capsulesData, function($a, $b) {
245 efrain 810
                        $result = strcasecmp($a['added_on'], $b['added_on']);
558 stevensc 811
                        if($result < 0) { return 1; } else if($result > 0) { return -1; } else { return 0; }
245 efrain 812
                    });
813
                }
814
            }
246 efrain 815
 
816
            if($order_field == 'last_access_on') {
817
                if($order_direction == 'asc') {
558 stevensc 818
                    usort($capsulesData, function($a, $b) {
246 efrain 819
                        return strcasecmp($a['last_access_on'], $b['last_access_on']);
820
                    });
821
                } else {
558 stevensc 822
                    usort($capsulesData, function($a, $b) {
246 efrain 823
                        $result = strcasecmp($a['last_access_on'], $b['last_access_on']);
558 stevensc 824
                        if($result < 0) { return 1; } else if($result > 0) { return -1; } else { return 0; }
246 efrain 825
                    });
826
                }
827
            }
828
 
829
 
830
 
831
 
119 efrain 832
 
833
            return new JsonModel([
834
                'success' => true,
558 stevensc 835
                'data' => $capsulesData
119 efrain 836
            ]);
837
 
838
        }
839
 
840
        return new JsonModel([
841
            'success' => false,
842
            'data' => 'ERROR_METHOD_NOT_ALLOWED'
843
        ]);
844
    }
845
 
846
    public function capsulesInProgressAction()
847
    {
848
        $request = $this->getRequest();
849
        if($request->isGet()) {
850
            $currentUserPlugin = $this->plugin('currentUserPlugin');
851
            $currentUser = $currentUserPlugin->getUser();
852
 
853
            $name = Functions::sanitizeFilterString($this->params()->fromQuery('name'));
245 efrain 854
            $order_field = Functions::sanitizeFilterString($this->params()->fromQuery('order_field'));
855
            $order_direction = Functions::sanitizeFilterString($this->params()->fromQuery('order_direction'));
119 efrain 856
 
246 efrain 857
            if(!in_array($order_field,['name', 'added_on', 'last_access_on'] )) {
245 efrain 858
                $order_field = 'name';
859
            }
119 efrain 860
 
245 efrain 861
            if(!in_array( $order_direction,['asc', 'desc'])) {
558 stevensc 862
                $order_direction = 'asc';
245 efrain 863
            }
864
 
283 www 865
            $userProgressMapper = MicrolearningUserProgressMapper::getInstance($this->adapter);
866
            $capsuleMapper = MicrolearningCapsuleMapper::getInstance($this->adapter);
558 stevensc 867
            $topicCapsuleMapper = MicrolearningTopicCapsuleMapper::getInstance($this->adapter);
868
            $topicMapper = MicrolearningTopicMapper::getInstance($this->adapter);
283 www 869
            $capsuleCommentMapper = MicrolearningCapsuleCommentMapper::getInstance($this->adapter);
119 efrain 870
 
871
            $accessGranted = $this->getAccessGranted();
872
 
558 stevensc 873
            $capsulesData = [];
119 efrain 874
 
333 www 875
            $storage = Storage::getInstance($this->config, $this->adapter);
283 www 876
            $path = $storage->getPathMicrolearningCapsule();
877
 
119 efrain 878
            foreach($accessGranted->capsules as $capsule_id)
879
            {
558 stevensc 880
                // 1. Verificar progreso
119 efrain 881
                $userProgress = $userProgressMapper->fetchOneByUseridAndCapsuleId($currentUser->id, $capsule_id);
558 stevensc 882
                if(!$userProgress || $userProgress->completed) { // Si no hay progreso o ya está completada
119 efrain 883
                    continue;
884
                }
558 stevensc 885
 
886
                // 2. Obtener detalles de la cápsula
887
                $capsule = $capsuleMapper->fetchOne($capsule_id);
888
                if(!$capsule) {
119 efrain 889
                    continue;
890
                }
891
 
558 stevensc 892
                // 3. Filtrar por nombre
119 efrain 893
                if($name) {
894
                    if(empty($name) || stripos($capsule->name, $name) === false) {
895
                        continue;
896
                    }
897
                }
898
 
558 stevensc 899
                // 4. Obtener Tópico asociado válido
900
                $topic = null;
901
                $topic_uuid_for_links = null;
902
                $relation = $topicCapsuleMapper->fetchOneByCapsuleId($capsule->id);
903
                if ($relation && in_array($relation->topic_id, $accessGranted->topics)) {
904
                    $topic = $topicMapper->fetchOne($relation->topic_id);
905
                    if ($topic) {
906
                        $topic_uuid_for_links = $topic->uuid;
907
                    }
908
                }
119 efrain 909
 
558 stevensc 910
                // 5. Obtener datos de comentarios
302 www 911
                $dataCountAndRatingAverage = $capsuleCommentMapper->fetchCountAndRatingAverage($capsule->company_id,  $capsule->id);
119 efrain 912
 
558 stevensc 913
                // 6. Construir enlace slides
914
                $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 915
 
558 stevensc 916
                // 7. Añadir al array de resultados
917
                array_push($capsulesData, [
119 efrain 918
                    'uuid'              => $capsule->uuid,
919
                    'name'              => $capsule->name ? $capsule->name : '',
920
                    'description'       => $capsule->description ? $capsule->description : '',
283 www 921
                    'image'             => $capsule->image ? $storage->getGenericImage($path, $capsule->uuid, $capsule->image)  : '',
119 efrain 922
                    'position'          => $capsule->order,
923
                    'link_comments'     => $this->url()->fromRoute('microlearning/capsules-comments', ['capsule_id' => $capsule->uuid], ['force_canonical' => true]),
924
                    'link_comment_add'  => $this->url()->fromRoute('microlearning/capsules-comments/add', ['capsule_id' => $capsule->uuid],['force_canonical' => true]),
558 stevensc 925
                    'link_slides'       => $link_slides,
119 efrain 926
                    'total_comments'    => strval($dataCountAndRatingAverage['total_comments']),
927
                    'total_rating'      => strval($dataCountAndRatingAverage['total_rating']),
558 stevensc 928
                    'progress'          => $userProgress->progress, // Progreso real
162 efrain 929
                    'link_get'          => $this->url()->fromRoute('microlearning/get-capsule', ['id' => $capsule->uuid], ['force_canonical' => true]),
558 stevensc 930
                    'last_access_on'    => $userProgress->updated_on, // Fecha del progreso
931
                    'added_on'          => $capsule->added_on, // Fecha de la cápsula
932
                    'updated_on'        => $capsule->updated_on, // Fecha de la cápsula
119 efrain 933
                ]);
934
            }
935
 
558 stevensc 936
            // 8. Ordenar (lógica de ordenación permanece igual, usando $capsulesData)
245 efrain 937
            if($order_field == 'name') {
938
                if($order_direction == 'asc') {
558 stevensc 939
                    usort($capsulesData, function($a, $b) {
245 efrain 940
                        return strcasecmp($a['name'], $b['name']);
941
                    });
942
                } else {
558 stevensc 943
                    usort($capsulesData, function($a, $b) {
245 efrain 944
                        $result = strcasecmp($a['name'], $b['name']);
558 stevensc 945
                        if($result < 0) { return 1; } else if($result > 0) { return -1; } else { return 0; }
245 efrain 946
                    });
119 efrain 947
                }
245 efrain 948
            }
949
 
950
            if($order_field == 'added_on') {
951
                if($order_direction == 'asc') {
558 stevensc 952
                    usort($capsulesData, function($a, $b) {
245 efrain 953
                        return strcasecmp($a['added_on'], $b['added_on']);
954
                    });
955
                } else {
558 stevensc 956
                    usort($capsulesData, function($a, $b) {
245 efrain 957
                        $result = strcasecmp($a['added_on'], $b['added_on']);
558 stevensc 958
                        if($result < 0) { return 1; } else if($result > 0) { return -1; } else { return 0; }
245 efrain 959
                    });
960
                }
961
            }
246 efrain 962
 
963
            if($order_field == 'last_access_on') {
964
                if($order_direction == 'asc') {
558 stevensc 965
                    usort($capsulesData, function($a, $b) {
246 efrain 966
                        return strcasecmp($a['last_access_on'], $b['last_access_on']);
967
                    });
968
                } else {
558 stevensc 969
                    usort($capsulesData, function($a, $b) {
246 efrain 970
                        $result = strcasecmp($a['last_access_on'], $b['last_access_on']);
558 stevensc 971
                        if($result < 0) { return 1; } else if($result > 0) { return -1; } else { return 0; }
246 efrain 972
                    });
973
                }
974
            }
245 efrain 975
 
246 efrain 976
 
119 efrain 977
            return new JsonModel([
978
                'success' => true,
558 stevensc 979
                'data' => $capsulesData
119 efrain 980
            ]);
981
        }
982
 
983
        return new JsonModel([
984
            'success' => false,
985
            'data' => 'ERROR_METHOD_NOT_ALLOWED'
986
        ]);
987
    }
988
 
989
 
990
    public function timelineAction()
991
    {
992
 
993
        $request = $this->getRequest();
994
        if($request->isGet()) {
995
            $currentUserPlugin = $this->plugin('currentUserPlugin');
996
            $currentUser = $currentUserPlugin->getUser();
997
 
998
 
999
            $page = intval($this->params()->fromQuery('page'), 10);
1000
 
1001
            $activities = [
283 www 1002
                MicrolearningUserLog::ACTIVITY_SIGNIN            => 'LABEL_MICROLEARNING_ACTIVITY_SIGNIN',
1003
                MicrolearningUserLog::ACTIVITY_SIGNOUT           => 'LABEL_MICROLEARNING_ACTIVITY_SIGNOUT',
1004
                MicrolearningUserLog::ACTIVITY_START_TOPIC       => 'LABEL_MICROLEARNING_ACTIVITY_START_TOPIC',
1005
                MicrolearningUserLog::ACTIVITY_START_CAPSULE     => 'LABEL_MICROLEARNING_ACTIVITY_START_CAPSULE',
1006
                MicrolearningUserLog::ACTIVITY_VIEW_SLIDE        => 'LABEL_MICROLEARNING_ACTIVITY_VIEW_SLIDE',
1007
                MicrolearningUserLog::ACTIVITY_TAKE_A_TEST       => 'LABEL_MICROLEARNING_ACTIVITY_TAKE_A_TEST',
1008
                MicrolearningUserLog::ACTIVITY_RETAKE_A_TEST     => 'LABEL_MICROLEARNING_ACTIVITY_RETAKE_A_TEST',
1009
                MicrolearningUserLog::ACTIVITY_APPROVED_TEST     => 'LABEL_MICROLEARNING_ACTIVITY_APPROVED_TEST',
1010
                MicrolearningUserLog::ACTIVITY_COMPLETED_CAPSULE => 'LABEL_MICROLEARNING_ACTIVITY_COMPLETED_CAPSULE',
1011
                MicrolearningUserLog::ACTIVITY_COMPLETED_TOPIC   => 'LABEL_MICROLEARNING_ACTIVITY_COMPLETED_TOPIC',
119 efrain 1012
            ];
1013
 
1014
 
1015
 
283 www 1016
            $microlearningUserLogMapper = MicrolearningUserLogMapper::getInstance($this->adapter);
1017
            $paginator = $microlearningUserLogMapper->getAllMessagesPaginatorByUserId($currentUser->id, $page);
119 efrain 1018
 
1019
            $items = [];
1020
            foreach($paginator as $record)
1021
            {
1022
                $dt = \DateTime::createFromFormat('Y-m-d H:i:s', $record->added_on);
1023
 
1024
                array_push($items, [
1025
                    'activity' => $activities[$record->activity],
1026
                    'added_on' => $dt->format('d/m/Y H:i a')
1027
                ]);
1028
            }
1029
 
1030
 
1031
            return new JsonModel([
1032
                'success' => true,
1033
                'data' => [
1034
                    'total' => [
1035
                        'count' => $paginator->getTotalItemCount(),
1036
                        'pages' => $paginator->getPages()->pageCount,
1037
                    ],
1038
                    'current' => [
1039
                        'items'    => $items,
1040
                        'page'     => $paginator->getCurrentPageNumber(),
1041
                        'count'    => $paginator->getCurrentItemCount(),
1042
                    ]
1043
                ]
1044
            ]);
1045
 
1046
 
1047
        } else {
1048
            return new JsonModel([
1049
                'success' => false,
1050
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
1051
            ]);
1052
        }
1053
    }
1054
 
1055
    /**
1056
     * Valores para la generación de los gráficos de progreso
1057
     * Para las repuesta afirmativa
1058
     * [
1059
     *  'success' => true,
1060
     *      'data' => [
1061
     *          'topicTotal' => cantidad total de tópicos,
1062
     *          'topicStarted' => cantidad de tópicos iniciados,
1063
     *          'topicIncompleted' => cantidad de tópicos incompletos,
1064
     *          'topicCompleted' => cantidad de tópicos completos,
1065
     *          'percentCompleted' => % de diapositivas completados ,
1066
     *          'percentIncompleted' => % de diapositivas incompletos ,
1067
     *          'percentWithoutReturning' => % de cápsulas sin retorno después de completada,
1068
     *          'percentWithReturning' => % de cápsulas con retorno después de completada,
558 stevensc 1069
     *      ],
119 efrain 1070
     * ]
1071
     *
1072
     *
1073
     *  En caso contrario
1074
     *  [
1075
     *      'success' => false,
1076
     *      'data' => mensaje de error
1077
     *  ]
1078
     *
1079
     *
1080
     * @return \Laminas\View\Model\JsonModel
1081
     */
1082
    public function progressAction()
1083
    {
1084
 
1085
        $request = $this->getRequest();
1086
        if($request->isGet()) {
1087
            $currentUserPlugin = $this->plugin('currentUserPlugin');
1088
            $currentUser = $currentUserPlugin->getUser();
1089
 
1090
 
1091
            $accessGrantedIds = $this->getAccessGranted();
1092
            $id = $this->params()->fromRoute('id');
1093
 
1094
            $companyMapper = CompanyMapper::getInstance($this->adapter);
1095
            $company = $companyMapper->fetchOneByUuid($id);
1096
 
1097
            if(!$company) {
1098
                $response = [
1099
                    'success' => false,
1100
                    'data' => 'ERROR_COMPANY_NOT_FOUND',
1101
                ];
1102
 
1103
 
1104
                return new JsonModel($response);
1105
            }
1106
 
1107
            if(!in_array($company->id, $accessGrantedIds->companies)) {
1108
                $response = [
1109
                    'success' => false,
1110
                    'data' => 'ERROR_YOU_DO_NOT_HAVE_ACCESS_TO_THIS_COMPANY',
1111
                ];
1112
 
1113
 
1114
                return new JsonModel($response);
1115
            }
1116
 
1117
            $capsuleTotal              = 0;
1118
            $capsuleCompleted          = 0;
1119
            $capsuleWithReturning      = 0;
1120
            $capsuleWithoutReturning   = 0;
1121
            $capsuleStarted            = 0;
1122
            $capsuleToStart            = 0;
1123
            $percentCompleted          = 0;
1124
            $percentIncompleted        = 100;
1125
 
283 www 1126
            $topicMapper = MicrolearningTopicMapper::getInstance($this->adapter);
119 efrain 1127
            $topics = $topicMapper->fetchAllActiveByCompanyIdAndIds($company->id, $accessGrantedIds->topics);
1128
 
302 www 1129
            //$capsuleMapper = MicrolearningCapsuleMapper::getInstance($this->adapter);
283 www 1130
            $progressMapper = MicrolearningUserProgressMapper::getInstance($this->adapter);
119 efrain 1131
 
302 www 1132
            $topicCapsuleMapper = MicrolearningTopicCapsuleMapper::getInstance($this->adapter);
119 efrain 1133
 
302 www 1134
            //$capsuleUserMapper = MicrolearningCapsuleUserMapper::getInstance($this->adapter);
1135
 
1136
 
119 efrain 1137
            foreach($topics as $topic)
1138
            {
302 www 1139
                $resultCount = $topicCapsuleMapper->fetchCountByCompanyIdAndTopicId($company->id, $topic->id);
119 efrain 1140
                $capsuleTotal =  $capsuleTotal + $resultCount;
1141
 
1142
                $resultCount = $progressMapper->fetchCountCapsulesCompletedByIdAndTopicId($currentUser->id, $topic->id);
1143
                $capsuleCompleted = $capsuleCompleted + $resultCount;
1144
 
1145
                $resultCount = $progressMapper->fetchCountCapsulesCompletedWithReturningByIdAndTopicId($currentUser->id, $topic->id);
1146
                $capsuleWithReturning = $capsuleWithReturning + $resultCount;
1147
 
1148
                $resultCount = $progressMapper->fetchCountCapsulesCompletedWithoutReturningByIdAndTopicId($currentUser->id, $topic->id);
1149
                $capsuleWithoutReturning = $capsuleWithoutReturning + $resultCount;
1150
 
1151
                $resultCount = $progressMapper->fetchCountCapsulesCompletedByIdAndTopicId($currentUser->id, $topic->id);
1152
                $capsuleStarted = $capsuleStarted + $resultCount;
1153
            }
1154
 
1155
            $capsuleToStart = $capsuleTotal -  $capsuleStarted;
1156
 
1157
 
1158
            if($capsuleTotal > 0) {
1159
                $percentCompleted = ($capsuleCompleted * 100) /  $capsuleTotal;
1160
                $percentIncompleted = 100 - $percentCompleted;
1161
            }
1162
 
1163
 
1164
 
1165
            return new JsonModel([
1166
                'success' => true,
1167
                'data' => [
1168
                    'capsuleTotal' => $capsuleTotal,
1169
                    'capsuleCompleted' => $capsuleCompleted,
1170
                    'capsuleStarted' => $capsuleStarted,
1171
                    'capsuleToStart' => $capsuleToStart,
1172
                    'percentCompleted' => number_format($percentCompleted, 2, '.', ','),
1173
                    'percentIncompleted' => number_format($percentIncompleted, 2, '.', ','),
1174
                    'capsuleWithReturning' => $capsuleWithReturning,
1175
                    'capsuleWithoutReturning' => $capsuleWithoutReturning,
1176
                ],
1177
            ]);
1178
 
1179
 
1180
        } else {
1181
            return new JsonModel([
1182
                'success' => false,
1183
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
1184
            ]);
1185
        }
1186
    }
1187
 
1188
 
1189
    public function topicsAction()
1190
    {
1191
        $request = $this->getRequest();
1192
        if($request->isGet()) {
1193
            $currentUserPlugin = $this->plugin('currentUserPlugin');
1194
            $currentUser = $currentUserPlugin->getUser();
1195
 
1196
 
1197
            $data = [];
1198
            $accessGrantedIds = $this->getAccessGranted();
1199
 
283 www 1200
            $userProgressMapper = MicrolearningUserProgressMapper::getInstance($this->adapter);
1201
            $topicMapper = MicrolearningTopicMapper::getInstance($this->adapter);
119 efrain 1202
 
333 www 1203
            $storage = Storage::getInstance($this->config, $this->adapter);
283 www 1204
            $path = $storage->getPathMicrolearningTopic();
119 efrain 1205
 
1206
            foreach($accessGrantedIds->topics as $id)
1207
            {
1208
                $topic = $topicMapper->fetchOne($id);
1209
                if(!$topic) {
1210
                    continue;
1211
                }
1212
 
1213
                $userProgress = $userProgressMapper->fetchOneByUserIdAndTopicId($currentUser->id, $id);
1214
                if($userProgress) {
1215
                    $progress = $userProgress->progress;
1216
                    $completed = $userProgress->completed;
1217
                } else {
1218
                    $progress = 0;
1219
                    $completed = 0;
1220
                }
1221
 
1222
 
1223
 
1224
                array_push($data, [
164 efrain 1225
                    'uuid'          => $topic->uuid,
119 efrain 1226
                    'name'          => $topic->name ? $topic->name : '',
1227
                    'description'   => $topic->description ? $topic->description : '',
283 www 1228
                    'image'         => $topic->image ? $storage->getGenericImage($path, $topic->uuid, $topic->image) : '',
119 efrain 1229
                    'progress'      => $progress,
1230
                    'completed'     => $completed,
1231
                    'order'         => $topic->order,
1232
                    'added_on'      => $topic->added_on,
564 stevensc 1233
                    'updated_on'    => $topic->updated_on
119 efrain 1234
                ]);
1235
            }
1236
 
1237
            usort($data, function($a, $b) {
1238
 
1239
                $result =  $a['order'] <=> $b['order'];
1240
                if(0 == $result) {
1241
                    $result = strcasecmp($a['added_on'], $b['added_on']);
1242
                    if(0 == $result) {
1243
                        $result = strcasecmp($a['name'], $b['name']);
1244
                    }
1245
                }
1246
 
1247
                if($result < 0) {
1248
                    return 1;
1249
                } else if($result > 0) {
1250
                    return -1;
1251
                } else  {
1252
                    return  0;
1253
                }
1254
            });
1255
 
1256
 
1257
 
1258
                return new JsonModel([
1259
                    'success' => true,
1260
                    'data' => $data
1261
                ]);
1262
 
1263
        } else {
1264
            return new JsonModel([
1265
                'success' => false,
1266
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
1267
            ]);
1268
        }
1269
    }
1270
 
161 efrain 1271
    public function getTopicAction()
1272
    {
563 stevensc 1273
        // Handle GET request
161 efrain 1274
        $request = $this->getRequest();
1275
        if($request->isGet()) {
563 stevensc 1276
            // Get current user
161 efrain 1277
            $currentUserPlugin = $this->plugin('currentUserPlugin');
1278
            $currentUser = $currentUserPlugin->getUser();
563 stevensc 1279
 
1280
            // Get topic ID from route
161 efrain 1281
            $id = $this->params()->fromRoute('id');
283 www 1282
            $topicMapper = MicrolearningTopicMapper::getInstance($this->adapter);
161 efrain 1283
            $topic = $topicMapper->fetchOneByUuid($id);
563 stevensc 1284
 
1285
            // Return error if topic not found
161 efrain 1286
            if(!$topic) {
1287
                return new JsonModel([
1288
                    'success' => false,
1289
                    'data' => 'ERROR_TOPIC_NOT_FOUND'
1290
                ]);
1291
            }
563 stevensc 1292
 
1293
            // Check if current user has access to the topic
161 efrain 1294
            $accessGrantedIds = $this->getAccessGranted();
1295
            if(!in_array($topic->id, $accessGrantedIds->topics)) {
1296
                return new JsonModel([
1297
                    'success' => false,
1298
                    'data' => 'ERROR_YOU_DO_NOT_HAVE_ACCESS_TO_THIS_TOPIC'
1299
                ]);
1300
            }
563 stevensc 1301
 
1302
            // Get user progress for this topic
283 www 1303
            $userProgressMapper = MicrolearningUserProgressMapper::getInstance($this->adapter);
563 stevensc 1304
            $userProgress = $userProgressMapper->fetchOneByUserIdAndTopicId($currentUser->id, $topic->id);
161 efrain 1305
 
563 stevensc 1306
            $progress = 0;
1307
            $completed = false;
161 efrain 1308
            if($userProgress) {
1309
                $progress = $userProgress->progress;
1310
                $completed = $userProgress->completed;
1311
            }
563 stevensc 1312
 
1313
            // Initialize storage service to get image paths
333 www 1314
            $storage = Storage::getInstance($this->config, $this->adapter);
563 stevensc 1315
            $pathTopic = $storage->getPathMicrolearningTopic();
1316
 
1317
            // Fetch associated capsules using the private helper method
1318
            $capsulesData = $this->_getCapsulesByTopic($topic, $storage);
1319
 
1320
            // Prepare data for JSON response
161 efrain 1321
            $data = [
165 efrain 1322
                'uuid'          => $topic->uuid,
161 efrain 1323
                'name'          => $topic->name ? $topic->name : '',
1324
                'description'   => $topic->description ? $topic->description : '',
563 stevensc 1325
                'image'         => $topic->image ? $storage->getGenericImage($pathTopic, $topic->uuid, $topic->image) : '',
161 efrain 1326
                'progress'      => $progress,
1327
                'completed'     => $completed,
1328
                'order'         => $topic->order,
1329
                'added_on'      => $topic->added_on,
1330
                'updated_on'    => $topic->updated_on,
563 stevensc 1331
                'total_capsules' => count($capsulesData),
1332
                'capsules'      => $capsulesData,
161 efrain 1333
            ];
563 stevensc 1334
 
161 efrain 1335
            return new JsonModel([
1336
                'success' => true,
1337
                'data' => $data
1338
            ]);
563 stevensc 1339
 
161 efrain 1340
        } else {
563 stevensc 1341
            // Return error if not a GET request
161 efrain 1342
            return new JsonModel([
1343
                'success' => false,
1344
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
1345
            ]);
1346
        }
1347
    }
563 stevensc 1348
 
1349
    /**
1350
     * Fetches and formats capsules associated with a given topic.
1351
     *
1352
     * @param mixed $topic The topic object.
1353
     * @param Storage $storage The storage service instance.
1354
     * @return array An array of formatted capsule data.
1355
     */
1356
    private function _getCapsulesByTopic($topic, $storage)
1357
    {
1358
        $capsulesData = [];
575 stevensc 1359
 
563 stevensc 1360
        // Get path for capsule images
1361
        $pathCapsule = $storage->getPathMicrolearningCapsule();
1362
 
1363
        // Initialize mappers
1364
        $capsuleMapper = MicrolearningCapsuleMapper::getInstance($this->adapter);
1365
        $userProgressMapper = MicrolearningUserProgressMapper::getInstance($this->adapter);
1366
        $capsuleCommentMapper = MicrolearningCapsuleCommentMapper::getInstance($this->adapter);
574 stevensc 1367
        $topicCapsuleMapper = MicrolearningTopicCapsuleMapper::getInstance($this->adapter); // Added mapper
563 stevensc 1368
 
574 stevensc 1369
        // Fetch access granted capsule IDs for the current user
1370
        $accessGrantedIds = $this->getAccessGranted();
563 stevensc 1371
 
574 stevensc 1372
        // Fetch active topic-capsule relations for the given topic
1373
        // Assuming the 'true' in the original call implied active relations/capsules.
1374
        // We fetch active relations first.
1375
        $topicCapsuleRelations = $topicCapsuleMapper->fetchAllActiveByTopicId($topic->id);
1376
 
1377
        $capsuleIdsToFetch = [];
1378
        if (!empty($topicCapsuleRelations)) {
1379
            foreach ($topicCapsuleRelations as $relation) {
1380
                // Ensure the user has access to this specific capsule ID from the relation
1381
                if (in_array($relation->capsule_id, $accessGrantedIds->capsules)) {
1382
                    $capsuleIdsToFetch[] = $relation->capsule_id;
1383
                }
1384
            }
1385
        }
1386
 
575 stevensc 1387
        $capsules = [];
574 stevensc 1388
        if (!empty($capsuleIdsToFetch)) {
1389
            // Fetch capsule details for the accessible and related capsule IDs
575 stevensc 1390
            // Removed array_unique to match capsulesAction more closely
1391
            $capsules = $capsuleMapper->fetchAllByIds($capsuleIdsToFetch);
574 stevensc 1392
        }
1393
 
563 stevensc 1394
        if(count($capsules) > 0) {
1395
            // Get current user
1396
            $currentUserPlugin = $this->plugin('currentUserPlugin');
1397
            $currentUser = $currentUserPlugin->getUser();
1398
 
1399
            // Iterate through each capsule to prepare its data
1400
            foreach($capsules as $capsule) {
1401
                // Get user progress for this capsule
1402
                $userCapsuleProgress = $userProgressMapper->fetchOneByUseridAndCapsuleId($currentUser->id, $capsule->id);
1403
                $capsuleProgress = 0;
1404
                $capsuleCompleted = false;
1405
                if($userCapsuleProgress) {
1406
                    $capsuleProgress = $userCapsuleProgress->progress;
1407
                    $capsuleCompleted = $userCapsuleProgress->completed;
1408
                }
1409
 
1410
                // Get comment count and average rating for the capsule
1411
                $dataCountAndRatingAverage = $capsuleCommentMapper->fetchCountAndRatingAverage($capsule->company_id, $capsule->id);
1412
 
575 stevensc 1413
                // Add formatted capsule data to the array, ensuring links are present as in capsulesAction
563 stevensc 1414
                array_push($capsulesData, [
1415
                    'uuid'              => $capsule->uuid,
1416
                    'name'              => $capsule->name ? $capsule->name : '',
1417
                    'description'       => $capsule->description ? $capsule->description : '',
1418
                    'image'             => $capsule->image ? $storage->getGenericImage($pathCapsule, $capsule->uuid, $capsule->image)  : '',
575 stevensc 1419
                    'link_comments'     => $this->url()->fromRoute('microlearning/capsules-comments', ['capsule_id' => $capsule->uuid], ['force_canonical' => true]),
1420
                    'link_comment_add'  => $this->url()->fromRoute('microlearning/capsules-comments/add', ['capsule_id' => $capsule->uuid],['force_canonical' => true]),
1421
                    'link_slides'       => $this->url()->fromRoute('microlearning/slides', ['topic_id' => $topic->uuid,  'capsule_id' => $capsule->uuid], ['force_canonical' => true]),
1422
                    'link_get'          => $this->url()->fromRoute('microlearning/get-capsule', ['id' => $capsule->uuid], ['force_canonical' => true]),
563 stevensc 1423
                    'total_comments'    => strval($dataCountAndRatingAverage['total_comments']),
1424
                    'total_rating'      => strval($dataCountAndRatingAverage['total_rating']),
1425
                    'progress'          => $capsuleProgress,
1426
                    'completed'         => $capsuleCompleted,
1427
                    'order'             => $capsule->order,
1428
                    'added_on'          => $capsule->added_on,
1429
                    'updated_on'        => $capsule->updated_on,
1430
                ]);
1431
            }
1432
 
1433
            // Sort capsules by order, then by added_on date, then by name
1434
            usort($capsulesData, function($a, $b) {
1435
                $result =  $a['order'] <=> $b['order'];
1436
                if(0 == $result) {
1437
                    $result = strcasecmp($a['added_on'], $b['added_on']);
1438
                    if(0 == $result) {
1439
                        $result = strcasecmp($a['name'], $b['name']);
1440
                    }
1441
                }
1442
                // usort expects -1, 0, or 1. Adjusting the logic to fit this.
1443
                if($result < 0) { return -1; } else if($result > 0) { return 1; } else { return 0; }
1444
            });
1445
        }
1446
        return $capsulesData;
1447
    }
119 efrain 1448
 
161 efrain 1449
 
119 efrain 1450
    public function capsulesAction()
1451
    {
1452
        $request = $this->getRequest();
1453
        if($request->isGet()) {
1454
            $currentUserPlugin = $this->plugin('currentUserPlugin');
1455
            $currentUser = $currentUserPlugin->getUser();
1456
 
1457
 
1458
 
558 stevensc 1459
            $topic_id_param = $this->params()->fromRoute('topic_id'); // Renombrado para claridad
283 www 1460
            $topicMapper = MicrolearningTopicMapper::getInstance($this->adapter);
558 stevensc 1461
            $topic = $topicMapper->fetchOneByUuid($topic_id_param);
119 efrain 1462
 
1463
            if(!$topic) {
1464
                return new JsonModel([
1465
                    'success' => false,
1466
                    'data' => 'ERROR_TOPIC_NOT_FOUND'
1467
                ]);
1468
            }
1469
 
1470
            $accessGrantedIds = $this->getAccessGranted();
1471
 
1472
            if(!in_array($topic->id, $accessGrantedIds->topics)) {
1473
                return new JsonModel([
1474
                    'success' => false,
1475
                    'data' => 'ERROR_YOU_DO_NOT_HAVE_ACCESS_TO_THIS_TOPIC'
1476
                ]);
1477
            }
1478
 
1479
 
1480
 
1481
            $data = [];
1482
 
558 stevensc 1483
            // Obtener la relación Tópico-Cápsula
1484
            $topicCapsuleMapper = MicrolearningTopicCapsuleMapper::getInstance($this->adapter);
1485
            $topicCapsuleRelations = $topicCapsuleMapper->fetchAllActiveByTopicId($topic->id);
119 efrain 1486
 
558 stevensc 1487
            $capsuleIdsToFetch = [];
1488
            $capsuleRelationData = []; // Para guardar datos específicos de la relación si es necesario
1489
            foreach ($topicCapsuleRelations as $relation) {
1490
                if (in_array($relation->capsule_id, $accessGrantedIds->capsules)) {
1491
                    $capsuleIdsToFetch[] = $relation->capsule_id;
1492
                    $capsuleRelationData[$relation->capsule_id] = [
1493
                        // Aquí puedes guardar datos de $relation si los necesitas más tarde
1494
                        // por ejemplo: 'publish_on' => $relation->publish_on
1495
                    ];
1496
                }
1497
            }
1498
 
1499
            if (empty($capsuleIdsToFetch)) {
1500
                return new JsonModel([
1501
                    'success' => true,
1502
                    'data' => [] // No hay cápsulas accesibles para este tópico
1503
                ]);
1504
            }
1505
 
1506
            // Obtener los detalles de las cápsulas
283 www 1507
            $capsuleMapper = MicrolearningCapsuleMapper::getInstance($this->adapter);
558 stevensc 1508
            $capsules = $capsuleMapper->fetchAllByIds($capsuleIdsToFetch);
1509
 
283 www 1510
            $userProgressMapper = MicrolearningUserProgressMapper::getInstance($this->adapter);
1511
            $capsuleCommentMapper = MicrolearningCapsuleCommentMapper::getInstance($this->adapter);
119 efrain 1512
 
333 www 1513
            $storage = Storage::getInstance($this->config, $this->adapter);
283 www 1514
            $path = $storage->getPathMicrolearningCapsule();
119 efrain 1515
 
558 stevensc 1516
            // Construir la respuesta combinando datos de Cápsula y Progreso
1517
            foreach($capsules as $capsule) // Iterar sobre los objetos Capsule obtenidos
119 efrain 1518
            {
558 stevensc 1519
                // $capsule ya no tiene topic_id directamente.
1520
                // El contexto del tópico viene de $topic (obtenido al inicio).
119 efrain 1521
 
558 stevensc 1522
                // Verificar acceso de nuevo (doble chequeo, podría optimizarse si getAccessGranted es fiable)
119 efrain 1523
                if(!in_array($capsule->id, $accessGrantedIds->capsules)) {
558 stevensc 1524
                     continue;
119 efrain 1525
                }
1526
 
1527
                $userProgress = $userProgressMapper->fetchOneByUseridAndCapsuleId($currentUser->id, $capsule->id);
1528
                if($userProgress) {
1529
                    $progress = $userProgress->progress;
1530
                    $completed = $userProgress->completed;
1531
                } else {
1532
                    $progress = 0;
1533
                    $completed = 0;
1534
                }
1535
 
558 stevensc 1536
                // Pasar company_id y capsule_id de la cápsula
302 www 1537
                $dataCountAndRatingAverage = $capsuleCommentMapper->fetchCountAndRatingAverage($capsule->company_id,  $capsule->id);
119 efrain 1538
 
1539
 
1540
 
1541
                array_push($data, [
166 efrain 1542
                    'uuid'              => $capsule->uuid,
119 efrain 1543
                    'name'              => $capsule->name ? $capsule->name : '',
1544
                    'description'       => $capsule->description ? $capsule->description : '',
283 www 1545
                    'image'             => $capsule->image ? $storage->getGenericImage($path, $capsule->uuid, $capsule->image)  : '',
558 stevensc 1546
                    // Usar $topic->uuid y $capsule->uuid para los enlaces
119 efrain 1547
                    'link_comments'     => $this->url()->fromRoute('microlearning/capsules-comments', ['capsule_id' => $capsule->uuid], ['force_canonical' => true]),
1548
                    'link_comment_add'  => $this->url()->fromRoute('microlearning/capsules-comments/add', ['capsule_id' => $capsule->uuid],['force_canonical' => true]),
1549
                    'link_slides'       => $this->url()->fromRoute('microlearning/slides', ['topic_id' => $topic->uuid,  'capsule_id' => $capsule->uuid], ['force_canonical' => true]),
558 stevensc 1550
                    'link_get'          => $this->url()->fromRoute('microlearning/get-capsule', ['id' => $capsule->uuid], ['force_canonical' => true]),
119 efrain 1551
                    'total_comments'    => strval($dataCountAndRatingAverage['total_comments']),
1552
                    'total_rating'      => strval($dataCountAndRatingAverage['total_rating']),
1553
                    'progress'          => $progress,
1554
                    'completed'         => $completed,
558 stevensc 1555
                    'order'             => $capsule->order, // Asumiendo que el orden viene de la cápsula
1556
                    'added_on'          => $capsule->added_on, // Fecha de la cápsula
1557
                    'updated_on'        => $capsule->updated_on, // Fecha de la cápsula
1558
                    // Puedes agregar datos de $capsuleRelationData[$capsule->id] si es necesario
119 efrain 1559
                ]);
1560
 
1561
 
1562
 
1563
            }
1564
 
1565
            usort($data, function($a, $b) {
1566
 
1567
                $result =  $a['order'] <=> $b['order'];
1568
                if(0 == $result) {
1569
                    $result = strcasecmp($a['added_on'], $b['added_on']);
1570
                    if(0 == $result) {
1571
                        $result = strcasecmp($a['name'], $b['name']);
1572
                    }
1573
                }
1574
 
1575
                if($result < 0) {
1576
                    return 1;
1577
                } else if($result > 0) {
1578
                    return -1;
1579
                } else  {
1580
                    return  0;
1581
                }
1582
            });
1583
 
1584
 
1585
 
1586
                return new JsonModel([
1587
                    'success' => true,
1588
                    'data' => $data
1589
                ]);
1590
 
1591
        } else {
1592
            return new JsonModel([
1593
                'success' => false,
1594
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
1595
            ]);
1596
        }
1597
    }
1598
 
235 efrain 1599
    public function takeTestAction()
1600
    {
1601
        $request = $this->getRequest();
1602
        if($request->isPost()) {
1603
            $currentUserPlugin = $this->plugin('currentUserPlugin');
1604
            $currentUser = $currentUserPlugin->getUser();
1605
 
1606
            $slide_id = $this->params()->fromRoute('slide_id');
283 www 1607
            $slideMapper = MicrolearningSlideMapper::getInstance($this->adapter);
235 efrain 1608
            $slide = $slideMapper->fetchOneByUuid($slide_id);
1609
 
1610
            if(!$slide) {
1611
                return new JsonModel([
1612
                    'success' => false,
1613
                    'data' => 'ERROR_SLIDE_NOT_FOUND'
1614
                ]);
1615
            }
1616
 
283 www 1617
            if($slide->type != MicrolearningSlide::TYPE_QUIZ) {
235 efrain 1618
                return new JsonModel([
1619
                    'success' => false,
1620
                    'data' => 'ERROR_SLIDE_IS_NOT_QUIZ'
1621
                ]);
1622
            }
1623
 
1624
 
1625
 
283 www 1626
            $capsuleMapper = MicrolearningCapsuleMapper::getInstance($this->adapter);
235 efrain 1627
            $capsule = $capsuleMapper->fetchOne($slide->capsule_id);
1628
 
1629
            if(!$capsule) {
1630
                return new JsonModel([
1631
                    'success' => false,
1632
                    'data' => 'ERROR_CAPSULE_NOT_FOUND'
1633
                ]);
1634
            }
1635
 
1636
            $accessGrantedIds = $this->getAccessGranted();
1637
 
1638
            if(!in_array($capsule->id, $accessGrantedIds->capsules)) {
1639
                return new JsonModel([
1640
                    'success' => false,
1641
                    'data' => 'ERROR_YOU_DO_NOT_HAVE_ACCESS_TO_THIS_CAPSULE'
1642
                ]);
1643
            }
1644
 
283 www 1645
            $userLogMapper = MicrolearningUserLogMapper::getInstance($this->adapter);
235 efrain 1646
            $userLog = $userLogMapper->fetchOneTakeATestByUserIdAndSlideId($currentUser->id, $slide->id);
1647
 
1648
            if($userLog) {
283 www 1649
                $activity = MicrolearningUserLog::ACTIVITY_RETAKE_A_TEST;
235 efrain 1650
            } else {
283 www 1651
                $activity = MicrolearningUserLog::ACTIVITY_TAKE_A_TEST;
235 efrain 1652
            }
1653
 
1654
            $added_on = $userLogMapper->getDatebaseNow();
1655
 
283 www 1656
            $userLog = new MicrolearningUserLog();
235 efrain 1657
            $userLog->activity      = $activity;
1658
            $userLog->user_id       = $currentUser->id;
1659
            $userLog->company_id    = $slide->company_id;
1660
            $userLog->topic_id      = $slide->topic_id;
1661
            $userLog->capsule_id    = $slide->capsule_id;
1662
            $userLog->slide_id      = $slide->id;
1663
            $userLog->added_on      = $added_on;
1664
 
1665
            if($userLogMapper->insert($userLog)) {
1666
                return new JsonModel([
1667
                    'success' => true,
1668
                ]);
1669
            } else {
1670
                return new JsonModel([
1671
                    'success' => false,
1672
                    'data' => $userLogMapper->getError()
1673
                ]);
1674
            }
1675
 
1676
 
1677
 
1678
 
1679
 
1680
 
1681
 
1682
        } else {
1683
            return new JsonModel([
1684
                'success' => false,
1685
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
1686
            ]);
1687
        }
1688
    }
1689
 
161 efrain 1690
    public function getCapsuleAction()
1691
    {
1692
        $request = $this->getRequest();
1693
        if($request->isGet()) {
1694
            $currentUserPlugin = $this->plugin('currentUserPlugin');
1695
            $currentUser = $currentUserPlugin->getUser();
1696
 
1697
 
1698
 
558 stevensc 1699
            $capsule_uuid = $this->params()->fromRoute('id');
283 www 1700
            $capsuleMapper = MicrolearningCapsuleMapper::getInstance($this->adapter);
558 stevensc 1701
            $capsule = $capsuleMapper->fetchOneByUuid($capsule_uuid);
161 efrain 1702
 
1703
            if(!$capsule) {
1704
                return new JsonModel([
1705
                    'success' => false,
1706
                    'data' => 'ERROR_CAPSULE_NOT_FOUND'
1707
                ]);
1708
            }
1709
 
1710
            $accessGrantedIds = $this->getAccessGranted();
1711
 
558 stevensc 1712
            // Verificar si el usuario tiene acceso a esta cápsula específica
161 efrain 1713
            if(!in_array($capsule->id, $accessGrantedIds->capsules)) {
1714
                return new JsonModel([
1715
                    'success' => false,
1716
                    'data' => 'ERROR_YOU_DO_NOT_HAVE_ACCESS_TO_THIS_CAPSULE'
1717
                ]);
1718
            }
1719
 
558 stevensc 1720
            // --- Obtener el Tópico asociado (si existe y es necesario) ---
1721
            $topic = null;
1722
            $topic_uuid_for_links = null; // UUID del tópico para construir enlaces
1723
            $topicCapsuleMapper = MicrolearningTopicCapsuleMapper::getInstance($this->adapter);
1724
            // Asumiendo que una cápsula puede estar asociada a múltiples tópicos (muchos-a-muchos),
1725
            // necesitamos decidir cuál tópico usar como contexto aquí. Usaremos el primero que encontremos.
1726
            // 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).
1727
            $relation = $topicCapsuleMapper->fetchOneByCapsuleId($capsule->id); // Necesitamos un método como este
1728
 
1729
            if ($relation && in_array($relation->topic_id, $accessGrantedIds->topics)) {
1730
                $topicMapper = MicrolearningTopicMapper::getInstance($this->adapter);
1731
                $topic = $topicMapper->fetchOne($relation->topic_id);
1732
                if ($topic) {
1733
                    $topic_uuid_for_links = $topic->uuid;
1734
                }
1735
            }
1736
            // Si no se encontró un tópico asociado o el usuario no tiene acceso a él,
1737
            // algunos enlaces podrían no generarse o la lógica necesitaría ajustarse.
1738
            // Por ahora, si no hay $topic_uuid_for_links, el link_slides será inválido.
1739
            // --------------------------------------------------------------
161 efrain 1740
 
1741
 
283 www 1742
            $userProgressMapper = MicrolearningUserProgressMapper::getInstance($this->adapter);
1743
            $capsuleCommentMapper = MicrolearningCapsuleCommentMapper::getInstance($this->adapter);
161 efrain 1744
 
1745
 
1746
 
1747
            $userProgress = $userProgressMapper->fetchOneByUseridAndCapsuleId($currentUser->id, $capsule->id);
1748
            if($userProgress) {
1749
                $progress = $userProgress->progress;
1750
                $completed = $userProgress->completed;
1751
            } else {
1752
                $progress = 0;
1753
                $completed = 0;
1754
            }
1755
 
302 www 1756
            $dataCountAndRatingAverage = $capsuleCommentMapper->fetchCountAndRatingAverage($capsule->company_id,  $capsule->id);
161 efrain 1757
 
244 efrain 1758
 
283 www 1759
            $slideMapper = MicrolearningSlideMapper::getInstance($this->adapter);
558 stevensc 1760
            // Para contar slides, necesitamos el contexto del tópico.
1761
            $totalSlides = 0;
1762
            if ($topic) { // Solo contar si tenemos un tópico asociado válido
1763
                $totalSlides = $slideMapper->fetchTotalCountByCompanyIdAndTopicIdAndCapsuleId($capsule->company_id, $topic->id, $capsule->id);
1764
            }
244 efrain 1765
 
1766
 
558 stevensc 1767
            $link_first_slide = '';
1768
            $type_first_slide = '';
1769
            if ($topic) { // Solo buscar primer slide si tenemos tópico
1770
                $slide = $slideMapper->fetchFirstByCompanyIdAndTopicIdAndCapsuleId($capsule->company_id, $topic->id, $capsule->id);
1771
                if($slide) {
1772
                    $link_first_slide = $this->url()->fromRoute('microlearning/get-slide', ['id' => $slide->uuid], ['force_canonical' => true]);
1773
                    $type_first_slide = $slide->type;
1774
                }
244 efrain 1775
            }
1776
 
333 www 1777
            $storage = Storage::getInstance($this->config, $this->adapter);
283 www 1778
            $path = $storage->getPathMicrolearningCapsule();
244 efrain 1779
 
1780
 
558 stevensc 1781
            // Construir enlaces usando $topic_uuid_for_links si está disponible
1782
            $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 1783
 
161 efrain 1784
            $data = [
164 efrain 1785
                    'uuid'              => $capsule->uuid,
161 efrain 1786
                    'name'              => $capsule->name ? $capsule->name : '',
1787
                    'description'       => $capsule->description ? $capsule->description : '',
283 www 1788
                    'image'             => $capsule->image ? $storage->getGenericImage($path, $capsule->uuid, $capsule->image)  : '',
161 efrain 1789
                    'link_comments'     => $this->url()->fromRoute('microlearning/capsules-comments', ['capsule_id' => $capsule->uuid], ['force_canonical' => true]),
1790
                    'link_comment_add'  => $this->url()->fromRoute('microlearning/capsules-comments/add', ['capsule_id' => $capsule->uuid],['force_canonical' => true]),
558 stevensc 1791
                    'link_slides'       => $link_slides, // Usar el enlace construido
161 efrain 1792
                    'total_comments'    => strval($dataCountAndRatingAverage['total_comments']),
1793
                    'total_rating'      => strval($dataCountAndRatingAverage['total_rating']),
1794
                    'progress'          => $progress,
1795
                    'completed'         => $completed,
245 efrain 1796
                    'total_slides'      => $totalSlides,
244 efrain 1797
                    'link_first_slide'  => $link_first_slide,
1798
                    'type_first_slide'  => $type_first_slide,
161 efrain 1799
                    'order'             => $capsule->order,
1800
                    'added_on'          => $capsule->added_on,
1801
                    'updated_on'        => $capsule->updated_on,
1802
            ];
1803
 
1804
 
1805
 
1806
            return new JsonModel([
1807
                'success' => true,
1808
                'data' => $data
1809
            ]);
1810
 
1811
        } else {
1812
            return new JsonModel([
1813
                'success' => false,
1814
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
1815
            ]);
1816
        }
1817
    }
1818
 
119 efrain 1819
    public function slidesAction()
1820
    {
1821
        $request = $this->getRequest();
1822
        if($request->isGet()) {
1823
            $currentUserPlugin = $this->plugin('currentUserPlugin');
1824
            $currentUser = $currentUserPlugin->getUser();
1825
 
1826
 
1827
 
1828
            $topic_id = $this->params()->fromRoute('topic_id');
283 www 1829
            $topicMapper = MicrolearningTopicMapper::getInstance($this->adapter);
119 efrain 1830
            $topic = $topicMapper->fetchOneByUuid($topic_id);
1831
 
1832
            if(!$topic) {
1833
                return new JsonModel([
1834
                    'success' => false,
1835
                    'data' => 'ERROR_TOPIC_NOT_FOUND'
1836
                ]);
1837
            }
1838
 
1839
            $accessGrantedIds = $this->getAccessGranted();
1840
 
1841
            if(!in_array($topic->id, $accessGrantedIds->topics)) {
1842
                return new JsonModel([
1843
                    'success' => false,
1844
                    'data' => 'ERROR_YOU_DO_NOT_HAVE_ACCESS_TO_THIS_TOPIC'
1845
                ]);
1846
            }
1847
 
1848
            $capsule_id = $this->params()->fromRoute('capsule_id');
283 www 1849
            $capsuleMapper = MicrolearningCapsuleMapper::getInstance($this->adapter);
119 efrain 1850
            $capsule = $capsuleMapper->fetchOneByUuid($capsule_id);
1851
 
1852
            if(!$capsule) {
1853
                return new JsonModel([
1854
                    'success' => false,
1855
                    'data' => 'ERROR_CAPSULE_NOT_FOUND'
1856
                ]);
1857
            }
1858
 
1859
 
1860
 
1861
            if(!in_array($capsule->id, $accessGrantedIds->capsules)) {
1862
                return new JsonModel([
1863
                    'success' => false,
1864
                    'data' => 'ERROR_YOU_DO_NOT_HAVE_ACCESS_TO_THIS_CAPSULE'
1865
                ]);
1866
            }
1867
 
1868
 
1869
 
1870
            $data = [];
1871
 
283 www 1872
            $quizMapper = MicrolearningQuizMapper::getInstance($this->adapter);
119 efrain 1873
 
283 www 1874
            $slideMapper = MicrolearningSlideMapper::getInstance($this->adapter);
1875
            $userProgressMapper = MicrolearningUserProgressMapper::getInstance($this->adapter);
119 efrain 1876
 
333 www 1877
            $storage = Storage::getInstance($this->config, $this->adapter);
283 www 1878
            $path = $storage->getPathMicrolearningSlide();
119 efrain 1879
 
1880
            $slides = $slideMapper->fetchAllByCompanyIdAndTopicIdAndCapsuleId($capsule->company_id, $capsule->topic_id, $capsule->id);
1881
            foreach($slides as $slide)
1882
            {
1883
 
1884
 
1885
                $userProgress = $userProgressMapper->fetchOneByUserIdAndSlideId($currentUser->id, $slide->id);
1886
                if($userProgress) {
224 efrain 1887
                    $completed =  $userProgress->completed ;
119 efrain 1888
                } else {
1889
                    $completed = 0;
1890
                }
1891
 
235 efrain 1892
 
230 efrain 1893
 
235 efrain 1894
                $link_take_a_test = '';
230 efrain 1895
                if($slide->quiz_id) {
235 efrain 1896
 
283 www 1897
                    $quizMapper = MicrolearningQuizMapper::getInstance($this->adapter);
230 efrain 1898
                    $quiz = $quizMapper->fetchOne($slide->quiz_id);
1899
                    if($quiz) {
1900
                        $quiz_uuid = $quiz->uuid;
235 efrain 1901
                        $quiz_data = $this->getQuiz($slide->quiz_id);
1902
                        $link_take_a_test = $this->url()->fromRoute('microlearning/take-a-test', ['slide_id' => $slide->uuid], ['force_canonical' => true]);
230 efrain 1903
                    }
235 efrain 1904
 
1905
                }
119 efrain 1906
 
1907
 
1908
                array_push($data, [
235 efrain 1909
                    'quiz'                  => $quiz_uuid,
1910
                    'quiz_data'             => $quiz_data,
1911
                    'uuid'                  => $slide->uuid,
1912
                    'name'                  => $slide->name ? $slide->name : '',
1913
                    'description'           => $slide->description ? $slide->description : '',
1914
                    'type'                  => $slide->type,
283 www 1915
                    'background'            => $slide->background ? $storage->getGenericImage($path, $slide->uuid, $slide->background) : '',
1916
                    'file'                  => $slide->file ? $storage->getGenericFile($path, $slide->uuid, $slide->file) : '',
235 efrain 1917
                    'order'                 => $slide->order,
1918
                    'completed'             => $completed,
1919
                    'link_get'              => $this->url()->fromRoute('microlearning/get-slide', ['id' => $slide->uuid], ['force_canonical' => true]),
1920
                    '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 1921
                    'link_take_a_test'      => $link_take_a_test,
235 efrain 1922
                    'added_on'              => $slide->added_on,
1923
                    'updated_on'            => $slide->updated_on,
119 efrain 1924
                ]);
1925
 
1926
 
1927
 
1928
            }
1929
 
1930
            usort($data, function($a, $b) {
1931
 
1932
                $result =  $a['order'] <=> $b['order'];
1933
                if(0 == $result) {
1934
                    $result = strcasecmp($a['added_on'], $b['added_on']);
1935
                    if(0 == $result) {
1936
                        $result = strcasecmp($a['name'], $b['name']);
1937
                    }
1938
                }
1939
 
1940
                if($result < 0) {
1941
                    return 1;
1942
                } else if($result > 0) {
1943
                    return -1;
1944
                } else  {
1945
                    return  0;
1946
                }
1947
            });
1948
 
1949
 
1950
 
1951
                return new JsonModel([
1952
                    'success' => true,
1953
                    'data' => $data
1954
                ]);
1955
 
1956
        } else {
1957
            return new JsonModel([
1958
                'success' => false,
1959
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
1960
            ]);
1961
        }
1962
    }
1963
 
229 efrain 1964
    private function getQuiz($id)
1965
    {
1966
        $serviceDatetimeFormat = $this->config['leaderslinked.services.datetime'];
1967
 
1968
        $data = [];
1969
 
283 www 1970
        $quizMapper = MicrolearningQuizMapper::getInstance($this->adapter);
229 efrain 1971
        $quiz = $quizMapper->fetchOne($id);
1972
 
1973
        if(!$quiz) {
1974
            return [];
1975
        }
1976
 
1977
        $companyMapper = CompanyMapper::getInstance($this->adapter);
1978
        $company = $companyMapper->fetchOne($quiz->company_id);
1979
 
283 www 1980
        $questionMapper = MicrolearningQuestionMapper::getInstance($this->adapter);
1981
        $answerMapper = MicrolearningAnswerMapper::getInstance($this->adapter);
229 efrain 1982
 
1983
        $record_questions = [];
1984
        $questions = $questionMapper->fetchAllByQuizId($quiz->id);
1985
        foreach($questions as $question)
1986
        {
1987
            $record_answers = [];
1988
 
1989
            $answers = $answerMapper->fetchAllByQuizIdAndQuestionId($question->quiz_id, $question->id);
1990
            foreach($answers as $answer)
1991
            {
1992
                $dtAddedOn = \DateTime::createFromFormat('Y-m-d H:i:s', $answer->added_on);
1993
                $dtUpdatedOn = \DateTime::createFromFormat('Y-m-d H:i:s', $answer->updated_on);
1994
 
1995
                array_push($record_answers, [
1996
                    'uuid' => $answer->uuid,
1997
                    'text' => trim($answer->text),
1998
                    'correct' => $answer->correct ? $answer->correct  : 0 ,
1999
                    'points' => strval(intval($answer->points, 10)),
2000
                    'added_on'  => $dtAddedOn->format($serviceDatetimeFormat),
2001
                    'updated_on'    => $dtUpdatedOn->format($serviceDatetimeFormat),
2002
                ]);
2003
            }
2004
 
2005
            $dtAddedOn = \DateTime::createFromFormat('Y-m-d H:i:s', $question->added_on);
2006
            $dtUpdatedOn = \DateTime::createFromFormat('Y-m-d H:i:s', $question->updated_on);
2007
 
2008
            array_push($record_questions, [
2009
                'uuid'          => $question->uuid,
2010
                'text'          => trim($question->text),
2011
                'type'          => $question->type,
2012
                'maxlength'     => strval($question->maxlength),
2013
                'points'        => strval($question->points),
2014
                'answers'       => $record_answers,
2015
                'added_on'      => $dtAddedOn->format($serviceDatetimeFormat),
2016
                'updated_on'    => $dtUpdatedOn->format($serviceDatetimeFormat),
2017
            ]);
2018
        }
2019
 
2020
        $dtAddedOn = \DateTime::createFromFormat('Y-m-d H:i:s', $quiz->added_on);
2021
        $dtUpdatedOn = \DateTime::createFromFormat('Y-m-d H:i:s', $quiz->updated_on);
2022
 
2023
        array_push($data, [
2024
            'uuid' => $quiz->uuid,
2025
            'name' => $quiz->name,
2026
            'text' => trim($quiz->text ? $quiz->text : ''),
2027
            'failed' => trim($quiz->failed ? $quiz->failed : ''),
2028
            'points' => strval($quiz->points),
2029
            'minimum_points_required' => strval($quiz->minimum_points_required),
2030
            'max_time' => $quiz->max_time ? $quiz->max_time : 5,
2031
            'company_uuid' => $company->uuid,
2032
            'company_name' => $company->name,
2033
            'company_image' => $this->url()->fromRoute('services/storage',['type' => 'company', 'code' => $company->uuid, 'filename' => $company->image], ['force_canonical' => true]),
2034
            'questions'     => $record_questions,
2035
            'added_on'      => $dtAddedOn->format($serviceDatetimeFormat),
2036
            'updated_on'    => $dtUpdatedOn->format($serviceDatetimeFormat),
2037
        ]);
2038
 
2039
        return $data;
2040
 
2041
    }
161 efrain 2042
 
229 efrain 2043
 
161 efrain 2044
    public function getSlideAction()
2045
    {
2046
        $request = $this->getRequest();
2047
        if($request->isGet()) {
2048
            $currentUserPlugin = $this->plugin('currentUserPlugin');
2049
            $currentUser = $currentUserPlugin->getUser();
2050
 
2051
 
2052
 
2053
            $id = $this->params()->fromRoute('id');
283 www 2054
            $slideMapper = MicrolearningSlideMapper::getInstance($this->adapter);
161 efrain 2055
            $slide = $slideMapper->fetchOneByUuid($id);
2056
 
2057
            if(!$slide) {
2058
                return new JsonModel([
2059
                    'success' => false,
2060
                    'data' => 'ERROR_SLIDE_NOT_FOUND'
2061
                ]);
2062
            }
2063
 
2064
            $accessGrantedIds = $this->getAccessGranted();
2065
 
2066
 
2067
 
2068
            if(!in_array($slide->capsule_id, $accessGrantedIds->capsules)) {
2069
                return new JsonModel([
2070
                    'success' => false,
2071
                    'data' => 'ERROR_YOU_DO_NOT_HAVE_ACCESS_TO_THIS_CAPSULE'
2072
                ]);
2073
            }
2074
 
2075
 
283 www 2076
            $topicMapper = MicrolearningTopicMapper::getInstance($this->adapter);
161 efrain 2077
            $topic = $topicMapper->fetchOne($slide->topic_id);
2078
 
283 www 2079
            $capsuleMapper =  MicrolearningCapsuleMapper::getInstance($this->adapter);
161 efrain 2080
            $capsule = $capsuleMapper->fetchOne($slide->capsule_id);
2081
 
2082
 
2083
 
2084
 
2085
 
283 www 2086
            $slideMapper = MicrolearningSlideMapper::getInstance($this->adapter);
2087
            $userProgressMapper = MicrolearningUserProgressMapper::getInstance($this->adapter);
161 efrain 2088
 
2089
 
2090
            $userProgress = $userProgressMapper->fetchOneByUserIdAndSlideId($currentUser->id, $slide->id);
2091
            if($userProgress) {
2092
                $completed = $userProgress->completed;
2093
            } else {
2094
                $completed = 0;
2095
            }
235 efrain 2096
 
2097
            $quiz_uuid = '';
2098
            $quiz_data = [];
2099
            $link_take_a_test = '';
2100
            if($slide->quiz_id) {
2101
 
283 www 2102
                $quizMapper = MicrolearningQuizMapper::getInstance($this->adapter);
235 efrain 2103
                $quiz = $quizMapper->fetchOne($slide->quiz_id);
2104
                if($quiz) {
2105
                    $quiz_uuid = $quiz->uuid;
2106
                    $quiz_data = $this->getQuiz($slide->quiz_id);
2107
                    $link_take_a_test = $this->url()->fromRoute('microlearning/take-a-test', ['slide_id' => $slide->uuid], ['force_canonical' => true]);
2108
                }
161 efrain 2109
 
235 efrain 2110
            }
161 efrain 2111
 
333 www 2112
            $storage = Storage::getInstance($this->config, $this->adapter);
283 www 2113
            $path = $storage->getPathMicrolearningSlide();
161 efrain 2114
 
2115
            $data =[
235 efrain 2116
                'quiz'              => $quiz_uuid,
2117
                'quiz_data'         => $quiz_data,
2118
                'uuid'              => $slide->uuid,
2119
                'name'              => $slide->name ? $slide->name : '',
2120
                'description'       => $slide->description ? $slide->description : '',
2121
                'type'              => $slide->type,
283 www 2122
                'background'        => $slide->background ? $storage->getGenericImage($path, $slide->uuid, $slide->background) : '',
2123
                'file'              => $slide->file ? $storage->getGenericFile($path, $slide->uuid, $slide->file) : '',
235 efrain 2124
                'order'             => $slide->order,
2125
                'completed'         => $completed,
2126
                '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]),
2127
                'link_take_a_test'  => $link_take_a_test,
2128
                'added_on'          => $slide->added_on,
2129
                'updated_on'        => $slide->updated_on,
161 efrain 2130
            ];
2131
 
2132
 
2133
 
2134
 
2135
            return new JsonModel([
2136
                'success' => true,
2137
                'data' => $data
2138
            ]);
2139
 
2140
        } else {
2141
            return new JsonModel([
2142
                'success' => false,
2143
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
2144
            ]);
2145
        }
2146
    }
2147
 
119 efrain 2148
    public function profileAction()
2149
    {
2150
        $request = $this->getRequest();
2151
        if($request->isGet()) {
2152
            $currentUserPlugin = $this->plugin('currentUserPlugin');
2153
            $currentUser = $currentUserPlugin->getUser();
2154
 
2155
 
2156
            $accessGrantedIds = $this->getAccessGranted();
2157
 
2158
            $companyMapper = CompanyMapper::getInstance($this->adapter);
283 www 2159
            $companyExtendUserMapper = MicrolearningExtendUserMapper::getInstance($this->adapter);
2160
            $companyExtendUserCompanyMapper = MicrolearningExtendUserCompanyMapper::getInstance($this->adapter);
2161
            $companyExtendUserFunctionMapper = MicrolearningExtendUserFunctionMapper::getInstance($this->adapter);
2162
            $companyExtendUserGroupMapper = MicrolearningExtendUserGroupMapper::getInstance($this->adapter);
2163
            $companyExtendUserInstitutionMapper = MicrolearningExtendUserInstitutionMapper::getInstance($this->adapter);
2164
            $companyExtendUserPartnerMapper = MicrolearningExtendUserPartnerMapper::getInstance($this->adapter);
2165
            $companyExtendUserProgramMapper = MicrolearningExtendUserProgramMapper::getInstance($this->adapter);
2166
            $companyExtendUserStudentTypeMapper = MicrolearningExtendUserStudentTypeMapper::getInstance($this->adapter);
2167
            $companyExtendUserSectorMapper = MicrolearningExtendUserSectorMapper::getInstance($this->adapter);
119 efrain 2168
 
333 www 2169
            $storage = Storage::getInstance($this->config, $this->adapter);
283 www 2170
 
119 efrain 2171
 
2172
            $data = [];
2173
            foreach($accessGrantedIds->companies as $company_id)
2174
            {
2175
                $company = $companyMapper->fetchOne($company_id);
2176
                if(!$company) {
2177
                    continue;
2178
                }
2179
 
2180
                $record = [
2181
                    'name' => $company->name,
283 www 2182
                    'image' => $storage->getCompanyImage($company),
119 efrain 2183
                    'details' => [],
2184
                ];
2185
 
2186
                $companyExtendUser = $companyExtendUserMapper->fetchOneByCompanyIdAndUserId($company->id, $currentUser->id);
2187
                if(!$companyExtendUser) {
2188
                    continue;
2189
                }
2190
 
2191
                if($companyExtendUser->extend_company_id) {
2192
 
2193
                    $extendedCompany = $companyExtendUserCompanyMapper->fetchOne($companyExtendUser->company_id);
2194
                    if($extendedCompany) {
2195
                        array_push($record['details'],[
2196
                            'uuid' => $extendedCompany->uuid,
2197
                            'label' => 'LABEL_COMPANY',
2198
                            'value' => $extendedCompany->name
2199
                        ]);
2200
                    }
2201
                }
2202
 
2203
                if($companyExtendUser->extend_function_id) {
2204
                    $extendedFunction = $companyExtendUserFunctionMapper->fetchOne($companyExtendUser->extend_function_id);
2205
                    if($extendedFunction) {
2206
                        array_push($record['details'],[
2207
                            'uuid' => $extendedFunction->uuid,
2208
                            'label' => 'LABEL_FUNCTION',
2209
                            'value' => $extendedFunction->name
2210
                        ]);
2211
                    }
2212
                }
2213
 
2214
                if($companyExtendUser->extend_group_id) {
2215
                    $extendedGroup = $companyExtendUserGroupMapper->fetchOne($companyExtendUser->extend_group_id);
2216
                    if($extendedGroup) {
2217
                        array_push($record['details'],[
2218
                            'uuid' => $extendedGroup->uuid,
2219
                            'label' => 'LABEL_GROUP',
2220
                            'value' => $extendedGroup->name
2221
                        ]);
2222
                    }
2223
                }
2224
 
2225
                if($companyExtendUser->extend_institution_id) {
2226
                    $extendedInstitution= $companyExtendUserInstitutionMapper->fetchOne($companyExtendUser->extend_institution_id);
2227
                    if($extendedInstitution) {
2228
                        array_push($record['details'],[
2229
                            'uuid' => $extendedInstitution->uuid,
2230
                            'label' => 'LABEL_INSTITUTION',
2231
                            'value' => $extendedInstitution->name
2232
                        ]);
2233
                    }
2234
                }
2235
 
2236
                if($companyExtendUser->extend_program_id) {
2237
                    $extendedProgram = $companyExtendUserProgramMapper->fetchOne($companyExtendUser->extend_program_id);
2238
                    if($extendedProgram) {
2239
                        array_push($record['details'],[
2240
                            'uuid' => $extendedProgram->uuid,
2241
                            'label' => 'LABEL_PROGRAM',
2242
                            'value' => $extendedProgram->name
2243
                        ]);
2244
 
2245
                    }
2246
                }
2247
 
2248
                if($companyExtendUser->extend_sector_id) {
2249
                    $extendedSector = $companyExtendUserSectorMapper->fetchOne($companyExtendUser->extend_sector_id);
2250
                    if($extendedSector) {
2251
                        array_push($record['details'],[
2252
                            'uuid' => $extendedSector->uuid,
2253
                            'label' => 'LABEL_SECTOR',
2254
                            'value' => $extendedSector->name
2255
                        ]);
2256
                    }
2257
                }
2258
 
2259
                if($companyExtendUser->extend_partner_id) {
2260
                    $extendedPartner = $companyExtendUserPartnerMapper->fetchOne($companyExtendUser->extend_partner_id);
2261
                    if($extendedPartner) {
2262
                        array_push($record['details'],[
2263
                            'uuid' => $extendedPartner->uuid,
2264
                            'label' => 'LABEL_PARTNER',
2265
                            'value' => $extendedPartner->name
2266
                        ]);
2267
                    }
2268
                }
2269
 
2270
                if($companyExtendUser->extend_student_type_id) {
2271
                    $extendedStudentType = $companyExtendUserStudentTypeMapper->fetchOne($companyExtendUser->extend_student_type_id);
2272
                    if($extendedStudentType) {
2273
                        array_push($record['details'],[
2274
                            'uuid' => $extendedStudentType->uuid,
2275
                            'label' => 'LABEL_TYPE',
2276
                            'value' => $extendedStudentType->name
2277
                        ]);
2278
                    }
2279
                }
2280
 
2281
                array_push($data, $record);
2282
            }
2283
 
2284
            return new JsonModel([
2285
                'success' => true,
2286
                'data' => $data
2287
            ]);
2288
 
2289
        } else {
2290
            return new JsonModel([
2291
                'success' => false,
2292
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
2293
            ]);
2294
        }
2295
    }
2296
 
167 efrain 2297
    public function syncAction()
2298
    {
2299
        $request = $this->getRequest();
168 efrain 2300
        if($request->isPost()) {
167 efrain 2301
            $currentUserPlugin = $this->plugin('currentUserPlugin');
2302
            $currentUser = $currentUserPlugin->getUser();
2303
 
2304
 
2305
            $operation = $this->params()->fromRoute('operation');
2306
            if($operation == 'slide-view' || $operation == 'capsule-close' || $operation == 'topic-close') {
2307
                $accessGrantedIds = $this->getAccessGranted();
2308
 
2309
                $topic_uuid     = $this->params()->fromRoute('topic_uuid');
2310
                $capsule_uuid   = $this->params()->fromRoute('capsule_uuid');
2311
                $slide_uuid     = $this->params()->fromRoute('slide_uuid');
2312
 
2313
                $accessGrantedIds = $this->getAccessGranted();
2314
                if($operation == 'slide-view') {
2315
 
2316
                    if(empty($slide_uuid) || empty($capsule_uuid ) || empty($topic_uuid)) {
2317
                        return new JsonModel([
2318
                            'success' => false,
2319
                            'data' => 'ERROR_INVALID_PARAMETERS'
2320
                        ]);
2321
                    }
2322
 
2323
 
283 www 2324
                    $topicMapper = MicrolearningTopicMapper::getInstance($this->adapter);
167 efrain 2325
                    $topic = $topicMapper->fetchOneByUuid($topic_uuid);
2326
 
2327
                    if(!$topic) {
2328
                        return new JsonModel([
2329
                            'success' => false,
2330
                            'data' => 'ERROR_TOPIC_NOT_FOUND'
2331
                        ]);
2332
                    }
2333
 
2334
 
2335
 
2336
                    if(!in_array($topic->id, $accessGrantedIds->topics)) {
2337
                        return new JsonModel([
2338
                            'success' => false,
2339
                            'data' => 'ERROR_YOU_DO_NOT_HAVE_ACCESS_TO_THIS_TOPIC'
2340
                        ]);
2341
                    }
2342
 
283 www 2343
                    $capsuleMapper = MicrolearningCapsuleMapper::getInstance($this->adapter);
167 efrain 2344
                    $capsule = $capsuleMapper->fetchOneByUuid($capsule_uuid);
2345
 
2346
                    if(!$capsule) {
2347
                        return new JsonModel([
2348
                            'success' => false,
2349
                            'data' => 'ERROR_CAPSULE_NOT_FOUND'
2350
                        ]);
2351
                    }
119 efrain 2352
 
167 efrain 2353
                    if(!in_array($capsule->id, $accessGrantedIds->capsules) || $capsule->topic_id != $topic->id) {
2354
                        return new JsonModel([
2355
                            'success' => false,
2356
                            'data' => 'ERROR_YOU_DO_NOT_HAVE_ACCESS_TO_THIS_CAPSULE'
2357
                        ]);
2358
                    }
2359
 
283 www 2360
                    $slideMapper = MicrolearningSlideMapper::getInstance($this->adapter);
167 efrain 2361
                    $slide = $slideMapper->fetchOneByUuid($slide_uuid);
2362
                    if(!$slide) {
2363
                        return new JsonModel([
2364
                            'success' => false,
2365
                            'data' => 'ERROR_SLIDE_NOT_FOUND'
2366
                        ]);
2367
                    }
2368
 
2369
                    if($slide->capsule_id != $capsule->id && $slide->topic_id != $topic->id) {
2370
                        return new JsonModel([
2371
                            'success' => false,
2372
                            'data' => 'ERROR_SLIDE_NOT_FOUND'
2373
                        ]);
2374
 
2375
                    }
2376
 
2377
 
283 www 2378
                    $userLogMapper = MicrolearningUserLogMapper::getInstance($this->adapter);
167 efrain 2379
 
283 www 2380
                    $userProgressMapper = MicrolearningUserProgressMapper::getInstance($this->adapter);
167 efrain 2381
                    $added_on = $userProgressMapper->getDatebaseNow();
2382
 
2383
 
2384
                    $userProgressTopic = $userProgressMapper->fetchOneByUserIdAndTopicId($currentUser->id, $topic->id);
2385
                    if(!$userProgressTopic) {
2386
 
283 www 2387
                        $userProgressTopic = new MicrolearningUserProgress();
558 stevensc 2388
                        $userProgressTopic->company_id                  = $topic->company_id; // Usar company_id del tópico
2389
                        $userProgressTopic->topic_id                    = $topic->id;        // Usar id del tópico
176 efrain 2390
                        $userProgressTopic->user_id                     = $currentUser->id;
167 efrain 2391
                        $userProgressTopic->progress                    = 0;
2392
                        $userProgressTopic->returning                   = 0;
2393
                        $userProgressTopic->returning_after_completed   = 0;
2394
                        $userProgressTopic->completed                   = 0;
558 stevensc 2395
                        $userProgressTopic->total_slides                = $slideMapper->fetchTotalCountByCompanyIdAndTopicId($topic->company_id, $topic->id);
167 efrain 2396
                        $userProgressTopic->view_slides                 = 0;
283 www 2397
                        $userProgressTopic->type                        = MicrolearningUserProgress::TYPE_TOPIC;
167 efrain 2398
                        $userProgressTopic->added_on                    = $added_on;
2399
                        $userProgressTopic->updated_on                  = $added_on;
2400
 
2401
                        if($userProgressMapper->insert($userProgressTopic)) {
2402
 
283 www 2403
                            $userLog = new MicrolearningUserLog();
2404
                            $userLog->activity      = MicrolearningUserLog::ACTIVITY_START_TOPIC;
167 efrain 2405
                            $userLog->user_id       = $currentUser->id;
558 stevensc 2406
                            $userLog->company_id    = $topic->company_id;
2407
                            $userLog->topic_id      = $topic->id;
167 efrain 2408
                            $userLog->added_on      = $added_on;
2409
 
2410
                            if(!$userLogMapper->insert($userLog)) {
2411
                                return new JsonModel([
2412
                                    'success' => false,
2413
                                    'data' => $userProgressMapper->getError()
2414
                                ]);
2415
                            }
2416
                        } else {
2417
                            return new JsonModel([
2418
                                'success' => false,
2419
                                'data' => $userProgressMapper->getError()
2420
                            ]);
2421
                        }
2422
                    }
2423
 
2424
 
2425
                    $userProgressCapsule = $userProgressMapper->fetchOneByUseridAndCapsuleId($currentUser->id, $capsule->id);
2426
                    if(!$userProgressCapsule) {
2427
 
283 www 2428
                        $userProgressCapsule = new MicrolearningUserProgress();
558 stevensc 2429
                        $userProgressCapsule->company_id                  = $capsule->company_id; // Usar company_id de la cápsula
2430
                        $userProgressCapsule->topic_id                    = $topic->id;         // Usar el id del tópico obtenido previamente
2431
                        $userProgressCapsule->capsule_id                  = $capsule->id;       // Usar id de la cápsula
176 efrain 2432
                        $userProgressCapsule->user_id                     = $currentUser->id;
167 efrain 2433
                        $userProgressCapsule->progress                    = 0;
2434
                        $userProgressCapsule->returning                   = 0;
2435
                        $userProgressCapsule->returning_after_completed   = 0;
2436
                        $userProgressCapsule->completed                   = 0;
558 stevensc 2437
                        $userProgressCapsule->total_slides                = $slideMapper->fetchTotalCountByCompanyIdAndTopicIdAndCapsuleId($capsule->company_id, $topic->id, $capsule->id);
167 efrain 2438
                        $userProgressCapsule->view_slides                 = 0;
2439
                        $userProgressTopic->updated_on                    = $added_on;
2440
 
2441
                        if($userProgressMapper->insert($userProgressCapsule)) {
2442
 
283 www 2443
                            $userLog = new MicrolearningUserLog();
2444
                            $userLog->activity      = MicrolearningUserLog::ACTIVITY_START_CAPSULE;
167 efrain 2445
                            $userLog->user_id       = $currentUser->id;
558 stevensc 2446
                            $userLog->company_id    = $capsule->company_id;
2447
                            $userLog->topic_id      = $topic->id;
2448
                            $userLog->capsule_id    = $capsule->id;
167 efrain 2449
                            $userLog->added_on      = $added_on;
2450
 
2451
                            if(!$userLogMapper->insert($userLog)) {
2452
                                return new JsonModel([
2453
                                    'success' => false,
2454
                                    'data' => $userLogMapper->getError()
2455
                                ]);
2456
                            }
2457
                        } else {
2458
                            return new JsonModel([
2459
                                'success' => false,
2460
                                'data' => $userProgressMapper->getError()
2461
                            ]);
2462
                        }
2463
                    }
2464
 
2465
 
2466
                    $userProgressSlide = $userProgressMapper->fetchOneByUserIdAndSlideId($currentUser->id, $slide->id);
2467
                    if(!$userProgressSlide) {
283 www 2468
                        $userProgressSlide = new MicrolearningUserProgress();
167 efrain 2469
                        $userProgressSlide->company_id                  = $slide->company_id;
2470
                        $userProgressSlide->topic_id                    = $slide->topic_id;
2471
                        $userProgressSlide->capsule_id                  = $slide->capsule_id;
2472
                        $userProgressSlide->slide_id                    = $slide->id;
176 efrain 2473
                        $userProgressSlide->user_id                     = $currentUser->id;
167 efrain 2474
                        $userProgressSlide->progress                    = 0;
2475
                        $userProgressSlide->returning                   = 0;
2476
                        $userProgressSlide->returning_after_completed   = 0;
2477
                        $userProgressSlide->completed                   = 1;
2478
                        $userProgressSlide->total_slides                = 0;
2479
                        $userProgressSlide->view_slides                 = 0;
283 www 2480
                        $userProgressSlide->type                        = MicrolearningUserProgress::TYPE_SLIDE;
167 efrain 2481
                        $userProgressSlide->added_on                    = $added_on;
2482
                        $userProgressSlide->updated_on                  = $added_on;
2483
 
2484
                        if(!$userProgressMapper->insert($userProgressSlide)) {
2485
                            return new JsonModel([
2486
                                'success' => false,
2487
                                'data' => $userProgressMapper->getError()
2488
                            ]);
2489
                        }
2490
                    }
2491
 
283 www 2492
                    $userLog = new MicrolearningUserLog();
2493
                    $userLog->activity      = MicrolearningUserLog::ACTIVITY_VIEW_SLIDE;
167 efrain 2494
                    $userLog->user_id       = $currentUser->id;
2495
                    $userLog->company_id    = $slide->company_id;
2496
                    $userLog->topic_id      = $slide->topic_id;
2497
                    $userLog->capsule_id    = $slide->capsule_id;
2498
                    $userLog->slide_id      = $slide->id;
2499
                    $userLog->added_on      = $added_on;
2500
 
2501
                    if(!$userLogMapper->insert($userLog)) {
2502
                        return new JsonModel([
2503
                            'success' => false,
2504
                            'data' => $userLogMapper->getError()
2505
                        ]);
2506
                    }
2507
 
2508
                    $closeCapsule = false;
2509
 
2510
                    if($userProgressCapsule->completed) {
2511
 
2512
                        $dt = \DateTime::createFromFormat('Y-m-d H:i:s', $added_on);
2513
                        $returning_on = $dt->format('Y-m-d');
2514
 
558 stevensc 2515
                        // Asegurarse que returning_on existe en el objeto antes de comparar
2516
                        $current_returning_on = isset($userProgressCapsule->returning_on) ? $userProgressCapsule->returning_on : null;
2517
 
2518
                        if(!$current_returning_on || $current_returning_on != $returning_on) {
167 efrain 2519
 
2520
                            $userProgressCapsule->returning_on = $returning_on;
558 stevensc 2521
                            // Asegurarse que returning_after_completed existe y es numérico antes de incrementar
2522
                            $userProgressCapsule->returning_after_completed = (isset($userProgressCapsule->returning_after_completed) ? intval($userProgressCapsule->returning_after_completed) : 0) + 1;
167 efrain 2523
 
2524
                            if(!$userProgressMapper->update($userProgressCapsule)) {
2525
                                return new JsonModel([
2526
                                    'success' => false,
2527
                                    'data' => $userProgressMapper->getError()
2528
                                ]);
2529
                            }
2530
                        }
2531
 
2532
                    }  else {
2533
 
558 stevensc 2534
                        // Usar $topic->id para obtener el total de slides de la cápsula en el contexto de este tópico
2535
                        $userProgressCapsule->total_slides = $slideMapper->fetchTotalCountByCompanyIdAndTopicIdAndCapsuleId($capsule->company_id, $topic->id, $capsule->id);
2536
                        $userProgressCapsule->view_slides = $userProgressMapper->fetchCountAllSlideCompletedByUserIdAndCapsuleId($currentUser->id, $capsule->id);
167 efrain 2537
 
2538
                        if($userProgressCapsule->total_slides) {
2539
 
2540
                            $userProgressCapsule->progress = ($userProgressCapsule->view_slides * 100) / $userProgressCapsule->total_slides;
2541
                            $userProgressCapsule->progress = $userProgressCapsule->progress > 100 ? 100 : $userProgressCapsule->progress;
2542
                        }
2543
 
2544
                        if(!$userProgressMapper->update($userProgressCapsule)) {
2545
                            return new JsonModel([
2546
                                'success' => false,
2547
                                'data' => $userProgressMapper->getError()
2548
                            ]);
2549
                        }
2550
 
2551
                        if($userProgressCapsule->progress >= 100) {
2552
                            $closeCapsule = true;
2553
                        }
171 efrain 2554
 
283 www 2555
 
167 efrain 2556
                    }
2557
 
2558
                    $closeTopic = false;
2559
                    if(!$userProgressTopic->completed) {
2560
 
558 stevensc 2561
                        // Usar $topic->id para obtener el total de slides del tópico
2562
                        $userProgressTopic->total_slides = $slideMapper->fetchTotalCountByCompanyIdAndTopicId($topic->company_id, $topic->id);
2563
                        $userProgressTopic->view_slides = $userProgressMapper->fetchCountAllSlideCompletedByUserIdAndTopicId($currentUser->id, $topic->id);
167 efrain 2564
 
2565
                        if($userProgressTopic->total_slides) {
2566
 
2567
                            $userProgressTopic->progress = ($userProgressTopic->view_slides * 100) / $userProgressTopic->total_slides;
2568
                            $userProgressTopic->progress = $userProgressTopic->progress > 100 ? 100 : $userProgressTopic->progress;
2569
                        }
2570
                        if(!$userProgressMapper->update($userProgressTopic)) {
2571
                            return new JsonModel([
2572
                                'success' => false,
2573
                                'data' => $userProgressMapper->getError()
2574
                            ]);
2575
                        }
2576
 
2577
                        if($userProgressTopic->progress >= 100) {
2578
                            $closeTopic = true;
2579
                        }
2580
                    }
2581
 
2582
 
2583
                    $data = [
2584
                        'message' => 'LABEL_THE_USER_PROGRESS_FOR_THIS_SLIDE_HAS_BEEN_COMPLETED',
2585
 
2586
                    ];
2587
 
2588
                    if($closeCapsule) {
173 efrain 2589
                        $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 2590
                    }
2591
 
2592
 
2593
                    if($closeTopic) {
173 efrain 2594
                        $data['link_close_topic'] = $this->url()->fromRoute('microlearning/sync', ['operation' => 'topic-close', 'topic_uuid' => $topic->uuid], ['force_canonical' => true]);
167 efrain 2595
                    }
2596
 
2597
 
2598
                    return new JsonModel([
2599
                        'success' => true,
2600
                        'data' => $data
2601
                    ]);
2602
 
2603
 
2604
 
2605
 
2606
                } else if($operation == 'capsule-close') {
2607
 
2608
                    if(empty($capsule_uuid ) || empty($topic_uuid)) {
2609
                        return new JsonModel([
2610
                            'success' => false,
2611
                            'data' => 'ERROR_INVALID_PARAMETERS'
2612
                        ]);
2613
                    }
2614
 
2615
 
283 www 2616
                    $topicMapper = MicrolearningTopicMapper::getInstance($this->adapter);
167 efrain 2617
                    $topic = $topicMapper->fetchOneByUuid($topic_uuid);
2618
 
2619
                    if(!$topic) {
2620
                        return new JsonModel([
2621
                            'success' => false,
2622
                            'data' => 'ERROR_TOPIC_NOT_FOUND'
2623
                        ]);
2624
                    }
2625
 
2626
 
2627
 
2628
                    if(!in_array($topic->id, $accessGrantedIds->topics)) {
2629
                        return new JsonModel([
2630
                            'success' => false,
2631
                            'data' => 'ERROR_YOU_DO_NOT_HAVE_ACCESS_TO_THIS_TOPIC'
2632
                        ]);
2633
                    }
2634
 
283 www 2635
                    $capsuleMapper = MicrolearningCapsuleMapper::getInstance($this->adapter);
167 efrain 2636
                    $capsule = $capsuleMapper->fetchOneByUuid($capsule_uuid);
2637
 
2638
                    if(!$capsule) {
2639
                        return new JsonModel([
2640
                            'success' => false,
2641
                            'data' => 'ERROR_CAPSULE_NOT_FOUND'
2642
                        ]);
2643
                    }
2644
 
2645
                    if(!in_array($capsule->id, $accessGrantedIds->capsules) || $capsule->topic_id != $topic->id) {
2646
                        return new JsonModel([
2647
                            'success' => false,
2648
                            'data' => 'ERROR_YOU_DO_NOT_HAVE_ACCESS_TO_THIS_CAPSULE'
2649
                        ]);
2650
                    }
2651
 
2652
 
283 www 2653
                    $userLogMapper = MicrolearningUserLogMapper::getInstance($this->adapter);
167 efrain 2654
 
283 www 2655
                    $userProgressMapper = MicrolearningUserProgressMapper::getInstance($this->adapter);
167 efrain 2656
                    $updated_on = $userProgressMapper->getDatebaseNow();
2657
 
2658
                    $userProgressCapsule = $userProgressMapper->fetchOneByUseridAndCapsuleId($currentUser->id, $capsule->id);
2659
                    if(!$userProgressCapsule) {
2660
                        return new JsonModel([
2661
                            'success' => false,
2662
                            'data' => 'ERROR_THE_USER_PROGRESS_FOR_THIS_CAPSULE_NOT_FOUND'
2663
                        ]);
2664
                    }
2665
 
2666
                    if($userProgressCapsule->completed) {
2667
                        return new JsonModel([
2668
                            'success' => false,
2669
                            'data' => 'ERROR_THE_USER_PROGRESS_FOR_THIS_CAPSULE_ALREADY_CLOSED'
2670
                        ]);
2671
                    }
2672
 
2673
 
2674
                    $userProgressCapsule->completed = 1;
2675
                    $userProgressCapsule->updated_on = $updated_on;
2676
 
2677
                    if($userProgressMapper->update($userProgressCapsule)) {
225 efrain 2678
 
2679
 
283 www 2680
                        $userLog = new MicrolearningUserLog();
2681
                        $userLog->activity      = MicrolearningUserLog::ACTIVITY_COMPLETED_CAPSULE;
227 efrain 2682
                        $userLog->user_id       = $currentUser->id;
2683
                        $userLog->company_id    = $capsule->company_id;
2684
                        $userLog->topic_id      = $capsule->topic_id;
2685
                        $userLog->capsule_id    = $capsule->id;
2686
                        $userLog->added_on      = $updated_on;
225 efrain 2687
 
2688
                        if(!$userLogMapper->insert($userLog)) {
2689
                            return new JsonModel([
2690
                                'success' => false,
2691
                                'data' => $userProgressMapper->getError()
2692
                            ]);
2693
                        }
2694
 
2695
 
167 efrain 2696
                        return new JsonModel([
2697
                            'success' => true,
2698
                            'data' => 'LABEL_THE_USER_PROGRESS_FOR_THIS_CAPSULE_HAS_BEEN_COMPLETED'
2699
                        ]);
2700
                    } else {
2701
                        return new JsonModel([
2702
                            'success' => false,
2703
                            'data' => 'ERROR_THE_USER_PROGRESS_FOR_THIS_CAPSULE_COULD_NOT_BE_COMPLETED'
2704
                        ]);
2705
                    }
2706
 
2707
 
2708
 
2709
 
2710
 
2711
 
2712
 
2713
                } else if($operation == 'topic-close') {
174 efrain 2714
                    if(empty($topic_uuid)) {
167 efrain 2715
                        return new JsonModel([
2716
                            'success' => false,
2717
                            'data' => 'ERROR_INVALID_PARAMETERS'
2718
                        ]);
2719
                    }
2720
 
2721
 
283 www 2722
                    $topicMapper = MicrolearningTopicMapper::getInstance($this->adapter);
167 efrain 2723
                    $topic = $topicMapper->fetchOneByUuid($topic_uuid);
2724
 
2725
                    if(!$topic) {
2726
                        return new JsonModel([
2727
                            'success' => false,
2728
                            'data' => 'ERROR_TOPIC_NOT_FOUND'
2729
                        ]);
2730
                    }
2731
 
2732
 
2733
 
2734
                    if(!in_array($topic->id, $accessGrantedIds->topics)) {
2735
                        return new JsonModel([
2736
                            'success' => false,
2737
                            'data' => 'ERROR_YOU_DO_NOT_HAVE_ACCESS_TO_THIS_TOPIC'
2738
                        ]);
2739
                    }
2740
 
2741
 
2742
 
2743
 
283 www 2744
                    $userLogMapper = MicrolearningUserLogMapper::getInstance($this->adapter);
167 efrain 2745
 
283 www 2746
                    $userProgressMapper = MicrolearningUserProgressMapper::getInstance($this->adapter);
167 efrain 2747
                    $updated_on = $userProgressMapper->getDatebaseNow();
2748
 
2749
                    $userProgressTopic = $userProgressMapper->fetchOneByUserIdAndTopicId($currentUser->id, $topic->id);
2750
                    if(!$userProgressTopic) {
2751
                        return new JsonModel([
2752
                            'success' => false,
2753
                            'data' => 'ERROR_THE_USER_PROGRESS_FOR_THIS_TOPIC_NOT_FOUND'
2754
                        ]);
2755
                    }
2756
 
2757
                    if($userProgressTopic->completed) {
2758
                        return new JsonModel([
2759
                            'success' => false,
2760
                            'data' => 'ERROR_THE_USER_PROGRESS_FOR_THIS_TOPIC_ALREADY_CLOSED'
2761
                        ]);
2762
                    }
2763
 
2764
 
2765
                    $userProgressTopic->completed = 1;
2766
                    $userProgressTopic->updated_on = $updated_on;
2767
 
2768
                    if($userProgressMapper->update($userProgressTopic)) {
226 efrain 2769
 
283 www 2770
                        $userLog = new MicrolearningUserLog();
2771
                        $userLog->activity      = MicrolearningUserLog::ACTIVITY_COMPLETED_TOPIC;
227 efrain 2772
                        $userLog->user_id       = $currentUser->id;
2773
                        $userLog->company_id    = $topic->company_id;
2774
                        $userLog->topic_id      = $topic->id;
2775
                        $userLog->added_on      = $updated_on;
226 efrain 2776
 
2777
                        if(!$userLogMapper->insert($userLog)) {
2778
                            return new JsonModel([
2779
                                'success' => false,
2780
                                'data' => $userProgressMapper->getError()
2781
                            ]);
2782
                        }
2783
 
167 efrain 2784
                        return new JsonModel([
2785
                            'success' => true,
2786
                            'data' => 'LABEL_THE_USER_PROGRESS_FOR_THIS_TOPIC_HAS_BEEN_COMPLETED'
2787
                        ]);
2788
                    } else {
2789
                        return new JsonModel([
2790
                            'success' => false,
2791
                            'data' => 'ERROR_THE_USER_PROGRESS_FOR_THIS_TOPIC_COULD_NOT_BE_COMPLETED'
2792
                        ]);
2793
                    }
2794
                }
2795
 
2796
 
2797
 
2798
 
2799
            } else {
2800
 
2801
                return new JsonModel([
2802
                    'success' => false,
2803
                    'data' => 'ERROR_OPERATION_UNKNOWN'
2804
                ]);
2805
 
2806
 
2807
            }
2808
 
2809
        } else {
2810
            return new JsonModel([
2811
                'success' => false,
2812
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
2813
            ]);
2814
        }
2815
    }
2816
 
2817
 
302 www 2818
 
2819
 
2820
 
119 efrain 2821
    /**
2822
     *
2823
     * @return \LeadersLinked\Controller\MicrolearningUserAccessGrantedIds
2824
     */
2825
    private function getAccessGranted()
2826
    {
2827
        $currentUserPlugin = $this->plugin('currentUserPlugin');
2828
        $currentUser = $currentUserPlugin->getUser();
2829
 
283 www 2830
        $capsuleUserMapper = MicrolearningCapsuleUserMapper::getInstance($this->adapter);
119 efrain 2831
        $now = $capsuleUserMapper->getDatebaseNow();
2832
 
2833
        $records = $capsuleUserMapper->fetchAllActiveByUserId($currentUser->id);
2834
 
2835
        $accessGrantedIds = new MicrolearningUserAccessGrantedIds();
2836
 
2837
 
2838
        foreach($records as $record)
2839
        {
283 www 2840
            if($record->access != MicrolearningCapsuleUser::ACCESS_UNLIMITED && $record->access != MicrolearningCapsuleUser::ACCESS_PAY_PERIOD) {
119 efrain 2841
                continue;
2842
            }
283 www 2843
            if($record->access == MicrolearningCapsuleUser::ACCESS_PAY_PERIOD) {
119 efrain 2844
                if($now < $record->paid_from || $now > $record->paid_to) {
2845
                    continue;
2846
                }
2847
            }
2848
 
2849
 
2850
            if(!in_array($record->company_id, $accessGrantedIds->companies )) {
2851
                array_push($accessGrantedIds->companies, $record->company_id);
2852
            }
2853
 
2854
            if(!in_array($record->topic_id, $accessGrantedIds->topics )) {
2855
                array_push( $accessGrantedIds->topics, $record->topic_id);
2856
            }
2857
 
2858
            if(!in_array($record->capsule_id, $accessGrantedIds->capsules)) {
2859
                array_push( $accessGrantedIds->capsules, $record->capsule_id);
2860
            }
2861
        }
2862
 
2863
        return $accessGrantedIds;
2864
    }
2865
 
2866
 
2867
}