Proyectos de Subversion LeadersLinked - Services

Rev

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

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