Proyectos de Subversion LeadersLinked - Services

Rev

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

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