Proyectos de Subversion LeadersLinked - Services

Rev

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

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