Proyectos de Subversion LeadersLinked - Services

Rev

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

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