Proyectos de Subversion LeadersLinked - Services

Rev

Rev 564 | Rev 575 | 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);
574 stevensc 1372
        $topicCapsuleMapper = MicrolearningTopicCapsuleMapper::getInstance($this->adapter); // Added mapper
563 stevensc 1373
 
574 stevensc 1374
        // Fetch access granted capsule IDs for the current user
1375
        $accessGrantedIds = $this->getAccessGranted();
563 stevensc 1376
 
574 stevensc 1377
        // Fetch active topic-capsule relations for the given topic
1378
        // Assuming the 'true' in the original call implied active relations/capsules.
1379
        // We fetch active relations first.
1380
        $topicCapsuleRelations = $topicCapsuleMapper->fetchAllActiveByTopicId($topic->id);
1381
 
1382
        $capsuleIdsToFetch = [];
1383
        if (!empty($topicCapsuleRelations)) {
1384
            foreach ($topicCapsuleRelations as $relation) {
1385
                // Ensure the user has access to this specific capsule ID from the relation
1386
                if (in_array($relation->capsule_id, $accessGrantedIds->capsules)) {
1387
                    $capsuleIdsToFetch[] = $relation->capsule_id;
1388
                }
1389
            }
1390
        }
1391
 
1392
        $capsules = []; // Initialize $capsules as an empty array
1393
        if (!empty($capsuleIdsToFetch)) {
1394
            // Fetch capsule details for the accessible and related capsule IDs
1395
            // Remove duplicates just in case, though relations should be unique per topic-capsule pair
1396
            $capsules = $capsuleMapper->fetchAllByIds(array_unique($capsuleIdsToFetch));
1397
        }
1398
 
563 stevensc 1399
        if(count($capsules) > 0) {
1400
            // Get current user
1401
            $currentUserPlugin = $this->plugin('currentUserPlugin');
1402
            $currentUser = $currentUserPlugin->getUser();
1403
 
1404
            // Iterate through each capsule to prepare its data
1405
            foreach($capsules as $capsule) {
1406
                // Get user progress for this capsule
1407
                $userCapsuleProgress = $userProgressMapper->fetchOneByUseridAndCapsuleId($currentUser->id, $capsule->id);
1408
                $capsuleProgress = 0;
1409
                $capsuleCompleted = false;
1410
                if($userCapsuleProgress) {
1411
                    $capsuleProgress = $userCapsuleProgress->progress;
1412
                    $capsuleCompleted = $userCapsuleProgress->completed;
1413
                }
1414
 
1415
                // Get comment count and average rating for the capsule
1416
                $dataCountAndRatingAverage = $capsuleCommentMapper->fetchCountAndRatingAverage($capsule->company_id, $capsule->id);
1417
 
1418
                // Add formatted capsule data to the array
1419
                array_push($capsulesData, [
1420
                    'uuid'              => $capsule->uuid,
1421
                    'name'              => $capsule->name ? $capsule->name : '',
1422
                    'description'       => $capsule->description ? $capsule->description : '',
1423
                    'image'             => $capsule->image ? $storage->getGenericImage($pathCapsule, $capsule->uuid, $capsule->image)  : '',
1424
                    'total_comments'    => strval($dataCountAndRatingAverage['total_comments']),
1425
                    'total_rating'      => strval($dataCountAndRatingAverage['total_rating']),
1426
                    'progress'          => $capsuleProgress,
1427
                    'completed'         => $capsuleCompleted,
1428
                    'order'             => $capsule->order,
1429
                    'added_on'          => $capsule->added_on,
1430
                    'updated_on'        => $capsule->updated_on,
1431
                ]);
1432
            }
1433
 
1434
            // Sort capsules by order, then by added_on date, then by name
1435
            usort($capsulesData, function($a, $b) {
1436
                $result =  $a['order'] <=> $b['order'];
1437
                if(0 == $result) {
1438
                    $result = strcasecmp($a['added_on'], $b['added_on']);
1439
                    if(0 == $result) {
1440
                        $result = strcasecmp($a['name'], $b['name']);
1441
                    }
1442
                }
1443
                // usort expects -1, 0, or 1. Adjusting the logic to fit this.
1444
                if($result < 0) { return -1; } else if($result > 0) { return 1; } else { return 0; }
1445
            });
1446
        }
1447
        return $capsulesData;
1448
    }
119 efrain 1449
 
161 efrain 1450
 
119 efrain 1451
    public function capsulesAction()
1452
    {
1453
        $request = $this->getRequest();
1454
        if($request->isGet()) {
1455
            $currentUserPlugin = $this->plugin('currentUserPlugin');
1456
            $currentUser = $currentUserPlugin->getUser();
1457
 
1458
 
1459
 
558 stevensc 1460
            $topic_id_param = $this->params()->fromRoute('topic_id'); // Renombrado para claridad
283 www 1461
            $topicMapper = MicrolearningTopicMapper::getInstance($this->adapter);
558 stevensc 1462
            $topic = $topicMapper->fetchOneByUuid($topic_id_param);
119 efrain 1463
 
1464
            if(!$topic) {
1465
                return new JsonModel([
1466
                    'success' => false,
1467
                    'data' => 'ERROR_TOPIC_NOT_FOUND'
1468
                ]);
1469
            }
1470
 
1471
            $accessGrantedIds = $this->getAccessGranted();
1472
 
1473
            if(!in_array($topic->id, $accessGrantedIds->topics)) {
1474
                return new JsonModel([
1475
                    'success' => false,
1476
                    'data' => 'ERROR_YOU_DO_NOT_HAVE_ACCESS_TO_THIS_TOPIC'
1477
                ]);
1478
            }
1479
 
1480
 
1481
 
1482
            $data = [];
1483
 
558 stevensc 1484
            // Obtener la relación Tópico-Cápsula
1485
            $topicCapsuleMapper = MicrolearningTopicCapsuleMapper::getInstance($this->adapter);
1486
            $topicCapsuleRelations = $topicCapsuleMapper->fetchAllActiveByTopicId($topic->id);
119 efrain 1487
 
558 stevensc 1488
            $capsuleIdsToFetch = [];
1489
            $capsuleRelationData = []; // Para guardar datos específicos de la relación si es necesario
1490
            foreach ($topicCapsuleRelations as $relation) {
1491
                if (in_array($relation->capsule_id, $accessGrantedIds->capsules)) {
1492
                    $capsuleIdsToFetch[] = $relation->capsule_id;
1493
                    $capsuleRelationData[$relation->capsule_id] = [
1494
                        // Aquí puedes guardar datos de $relation si los necesitas más tarde
1495
                        // por ejemplo: 'publish_on' => $relation->publish_on
1496
                    ];
1497
                }
1498
            }
1499
 
1500
            if (empty($capsuleIdsToFetch)) {
1501
                return new JsonModel([
1502
                    'success' => true,
1503
                    'data' => [] // No hay cápsulas accesibles para este tópico
1504
                ]);
1505
            }
1506
 
1507
            // Obtener los detalles de las cápsulas
283 www 1508
            $capsuleMapper = MicrolearningCapsuleMapper::getInstance($this->adapter);
558 stevensc 1509
            $capsules = $capsuleMapper->fetchAllByIds($capsuleIdsToFetch);
1510
 
283 www 1511
            $userProgressMapper = MicrolearningUserProgressMapper::getInstance($this->adapter);
1512
            $capsuleCommentMapper = MicrolearningCapsuleCommentMapper::getInstance($this->adapter);
119 efrain 1513
 
333 www 1514
            $storage = Storage::getInstance($this->config, $this->adapter);
283 www 1515
            $path = $storage->getPathMicrolearningCapsule();
119 efrain 1516
 
558 stevensc 1517
            // Construir la respuesta combinando datos de Cápsula y Progreso
1518
            foreach($capsules as $capsule) // Iterar sobre los objetos Capsule obtenidos
119 efrain 1519
            {
558 stevensc 1520
                // $capsule ya no tiene topic_id directamente.
1521
                // El contexto del tópico viene de $topic (obtenido al inicio).
119 efrain 1522
 
558 stevensc 1523
                // Verificar acceso de nuevo (doble chequeo, podría optimizarse si getAccessGranted es fiable)
119 efrain 1524
                if(!in_array($capsule->id, $accessGrantedIds->capsules)) {
558 stevensc 1525
                     continue;
119 efrain 1526
                }
1527
 
1528
                $userProgress = $userProgressMapper->fetchOneByUseridAndCapsuleId($currentUser->id, $capsule->id);
1529
                if($userProgress) {
1530
                    $progress = $userProgress->progress;
1531
                    $completed = $userProgress->completed;
1532
                } else {
1533
                    $progress = 0;
1534
                    $completed = 0;
1535
                }
1536
 
558 stevensc 1537
                // Pasar company_id y capsule_id de la cápsula
302 www 1538
                $dataCountAndRatingAverage = $capsuleCommentMapper->fetchCountAndRatingAverage($capsule->company_id,  $capsule->id);
119 efrain 1539
 
1540
 
1541
 
1542
                array_push($data, [
166 efrain 1543
                    'uuid'              => $capsule->uuid,
119 efrain 1544
                    'name'              => $capsule->name ? $capsule->name : '',
1545
                    'description'       => $capsule->description ? $capsule->description : '',
283 www 1546
                    'image'             => $capsule->image ? $storage->getGenericImage($path, $capsule->uuid, $capsule->image)  : '',
558 stevensc 1547
                    // Usar $topic->uuid y $capsule->uuid para los enlaces
119 efrain 1548
                    'link_comments'     => $this->url()->fromRoute('microlearning/capsules-comments', ['capsule_id' => $capsule->uuid], ['force_canonical' => true]),
1549
                    'link_comment_add'  => $this->url()->fromRoute('microlearning/capsules-comments/add', ['capsule_id' => $capsule->uuid],['force_canonical' => true]),
1550
                    'link_slides'       => $this->url()->fromRoute('microlearning/slides', ['topic_id' => $topic->uuid,  'capsule_id' => $capsule->uuid], ['force_canonical' => true]),
558 stevensc 1551
                    'link_get'          => $this->url()->fromRoute('microlearning/get-capsule', ['id' => $capsule->uuid], ['force_canonical' => true]),
119 efrain 1552
                    'total_comments'    => strval($dataCountAndRatingAverage['total_comments']),
1553
                    'total_rating'      => strval($dataCountAndRatingAverage['total_rating']),
1554
                    'progress'          => $progress,
1555
                    'completed'         => $completed,
558 stevensc 1556
                    'order'             => $capsule->order, // Asumiendo que el orden viene de la cápsula
1557
                    'added_on'          => $capsule->added_on, // Fecha de la cápsula
1558
                    'updated_on'        => $capsule->updated_on, // Fecha de la cápsula
1559
                    // Puedes agregar datos de $capsuleRelationData[$capsule->id] si es necesario
119 efrain 1560
                ]);
1561
 
1562
 
1563
 
1564
            }
1565
 
1566
            usort($data, function($a, $b) {
1567
 
1568
                $result =  $a['order'] <=> $b['order'];
1569
                if(0 == $result) {
1570
                    $result = strcasecmp($a['added_on'], $b['added_on']);
1571
                    if(0 == $result) {
1572
                        $result = strcasecmp($a['name'], $b['name']);
1573
                    }
1574
                }
1575
 
1576
                if($result < 0) {
1577
                    return 1;
1578
                } else if($result > 0) {
1579
                    return -1;
1580
                } else  {
1581
                    return  0;
1582
                }
1583
            });
1584
 
1585
 
1586
 
1587
                return new JsonModel([
1588
                    'success' => true,
1589
                    'data' => $data
1590
                ]);
1591
 
1592
        } else {
1593
            return new JsonModel([
1594
                'success' => false,
1595
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
1596
            ]);
1597
        }
1598
    }
1599
 
235 efrain 1600
    public function takeTestAction()
1601
    {
1602
        $request = $this->getRequest();
1603
        if($request->isPost()) {
1604
            $currentUserPlugin = $this->plugin('currentUserPlugin');
1605
            $currentUser = $currentUserPlugin->getUser();
1606
 
1607
            $slide_id = $this->params()->fromRoute('slide_id');
283 www 1608
            $slideMapper = MicrolearningSlideMapper::getInstance($this->adapter);
235 efrain 1609
            $slide = $slideMapper->fetchOneByUuid($slide_id);
1610
 
1611
            if(!$slide) {
1612
                return new JsonModel([
1613
                    'success' => false,
1614
                    'data' => 'ERROR_SLIDE_NOT_FOUND'
1615
                ]);
1616
            }
1617
 
283 www 1618
            if($slide->type != MicrolearningSlide::TYPE_QUIZ) {
235 efrain 1619
                return new JsonModel([
1620
                    'success' => false,
1621
                    'data' => 'ERROR_SLIDE_IS_NOT_QUIZ'
1622
                ]);
1623
            }
1624
 
1625
 
1626
 
283 www 1627
            $capsuleMapper = MicrolearningCapsuleMapper::getInstance($this->adapter);
235 efrain 1628
            $capsule = $capsuleMapper->fetchOne($slide->capsule_id);
1629
 
1630
            if(!$capsule) {
1631
                return new JsonModel([
1632
                    'success' => false,
1633
                    'data' => 'ERROR_CAPSULE_NOT_FOUND'
1634
                ]);
1635
            }
1636
 
1637
            $accessGrantedIds = $this->getAccessGranted();
1638
 
1639
            if(!in_array($capsule->id, $accessGrantedIds->capsules)) {
1640
                return new JsonModel([
1641
                    'success' => false,
1642
                    'data' => 'ERROR_YOU_DO_NOT_HAVE_ACCESS_TO_THIS_CAPSULE'
1643
                ]);
1644
            }
1645
 
283 www 1646
            $userLogMapper = MicrolearningUserLogMapper::getInstance($this->adapter);
235 efrain 1647
            $userLog = $userLogMapper->fetchOneTakeATestByUserIdAndSlideId($currentUser->id, $slide->id);
1648
 
1649
            if($userLog) {
283 www 1650
                $activity = MicrolearningUserLog::ACTIVITY_RETAKE_A_TEST;
235 efrain 1651
            } else {
283 www 1652
                $activity = MicrolearningUserLog::ACTIVITY_TAKE_A_TEST;
235 efrain 1653
            }
1654
 
1655
            $added_on = $userLogMapper->getDatebaseNow();
1656
 
283 www 1657
            $userLog = new MicrolearningUserLog();
235 efrain 1658
            $userLog->activity      = $activity;
1659
            $userLog->user_id       = $currentUser->id;
1660
            $userLog->company_id    = $slide->company_id;
1661
            $userLog->topic_id      = $slide->topic_id;
1662
            $userLog->capsule_id    = $slide->capsule_id;
1663
            $userLog->slide_id      = $slide->id;
1664
            $userLog->added_on      = $added_on;
1665
 
1666
            if($userLogMapper->insert($userLog)) {
1667
                return new JsonModel([
1668
                    'success' => true,
1669
                ]);
1670
            } else {
1671
                return new JsonModel([
1672
                    'success' => false,
1673
                    'data' => $userLogMapper->getError()
1674
                ]);
1675
            }
1676
 
1677
 
1678
 
1679
 
1680
 
1681
 
1682
 
1683
        } else {
1684
            return new JsonModel([
1685
                'success' => false,
1686
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
1687
            ]);
1688
        }
1689
    }
1690
 
161 efrain 1691
    public function getCapsuleAction()
1692
    {
1693
        $request = $this->getRequest();
1694
        if($request->isGet()) {
1695
            $currentUserPlugin = $this->plugin('currentUserPlugin');
1696
            $currentUser = $currentUserPlugin->getUser();
1697
 
1698
 
1699
 
558 stevensc 1700
            $capsule_uuid = $this->params()->fromRoute('id');
283 www 1701
            $capsuleMapper = MicrolearningCapsuleMapper::getInstance($this->adapter);
558 stevensc 1702
            $capsule = $capsuleMapper->fetchOneByUuid($capsule_uuid);
161 efrain 1703
 
1704
            if(!$capsule) {
1705
                return new JsonModel([
1706
                    'success' => false,
1707
                    'data' => 'ERROR_CAPSULE_NOT_FOUND'
1708
                ]);
1709
            }
1710
 
1711
            $accessGrantedIds = $this->getAccessGranted();
1712
 
558 stevensc 1713
            // Verificar si el usuario tiene acceso a esta cápsula específica
161 efrain 1714
            if(!in_array($capsule->id, $accessGrantedIds->capsules)) {
1715
                return new JsonModel([
1716
                    'success' => false,
1717
                    'data' => 'ERROR_YOU_DO_NOT_HAVE_ACCESS_TO_THIS_CAPSULE'
1718
                ]);
1719
            }
1720
 
558 stevensc 1721
            // --- Obtener el Tópico asociado (si existe y es necesario) ---
1722
            $topic = null;
1723
            $topic_uuid_for_links = null; // UUID del tópico para construir enlaces
1724
            $topicCapsuleMapper = MicrolearningTopicCapsuleMapper::getInstance($this->adapter);
1725
            // Asumiendo que una cápsula puede estar asociada a múltiples tópicos (muchos-a-muchos),
1726
            // necesitamos decidir cuál tópico usar como contexto aquí. Usaremos el primero que encontremos.
1727
            // 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).
1728
            $relation = $topicCapsuleMapper->fetchOneByCapsuleId($capsule->id); // Necesitamos un método como este
1729
 
1730
            if ($relation && in_array($relation->topic_id, $accessGrantedIds->topics)) {
1731
                $topicMapper = MicrolearningTopicMapper::getInstance($this->adapter);
1732
                $topic = $topicMapper->fetchOne($relation->topic_id);
1733
                if ($topic) {
1734
                    $topic_uuid_for_links = $topic->uuid;
1735
                }
1736
            }
1737
            // Si no se encontró un tópico asociado o el usuario no tiene acceso a él,
1738
            // algunos enlaces podrían no generarse o la lógica necesitaría ajustarse.
1739
            // Por ahora, si no hay $topic_uuid_for_links, el link_slides será inválido.
1740
            // --------------------------------------------------------------
161 efrain 1741
 
1742
 
283 www 1743
            $userProgressMapper = MicrolearningUserProgressMapper::getInstance($this->adapter);
1744
            $capsuleCommentMapper = MicrolearningCapsuleCommentMapper::getInstance($this->adapter);
161 efrain 1745
 
1746
 
1747
 
1748
            $userProgress = $userProgressMapper->fetchOneByUseridAndCapsuleId($currentUser->id, $capsule->id);
1749
            if($userProgress) {
1750
                $progress = $userProgress->progress;
1751
                $completed = $userProgress->completed;
1752
            } else {
1753
                $progress = 0;
1754
                $completed = 0;
1755
            }
1756
 
302 www 1757
            $dataCountAndRatingAverage = $capsuleCommentMapper->fetchCountAndRatingAverage($capsule->company_id,  $capsule->id);
161 efrain 1758
 
244 efrain 1759
 
283 www 1760
            $slideMapper = MicrolearningSlideMapper::getInstance($this->adapter);
558 stevensc 1761
            // Para contar slides, necesitamos el contexto del tópico.
1762
            $totalSlides = 0;
1763
            if ($topic) { // Solo contar si tenemos un tópico asociado válido
1764
                $totalSlides = $slideMapper->fetchTotalCountByCompanyIdAndTopicIdAndCapsuleId($capsule->company_id, $topic->id, $capsule->id);
1765
            }
244 efrain 1766
 
1767
 
558 stevensc 1768
            $link_first_slide = '';
1769
            $type_first_slide = '';
1770
            if ($topic) { // Solo buscar primer slide si tenemos tópico
1771
                $slide = $slideMapper->fetchFirstByCompanyIdAndTopicIdAndCapsuleId($capsule->company_id, $topic->id, $capsule->id);
1772
                if($slide) {
1773
                    $link_first_slide = $this->url()->fromRoute('microlearning/get-slide', ['id' => $slide->uuid], ['force_canonical' => true]);
1774
                    $type_first_slide = $slide->type;
1775
                }
244 efrain 1776
            }
1777
 
333 www 1778
            $storage = Storage::getInstance($this->config, $this->adapter);
283 www 1779
            $path = $storage->getPathMicrolearningCapsule();
244 efrain 1780
 
1781
 
558 stevensc 1782
            // Construir enlaces usando $topic_uuid_for_links si está disponible
1783
            $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 1784
 
161 efrain 1785
            $data = [
164 efrain 1786
                    'uuid'              => $capsule->uuid,
161 efrain 1787
                    'name'              => $capsule->name ? $capsule->name : '',
1788
                    'description'       => $capsule->description ? $capsule->description : '',
283 www 1789
                    'image'             => $capsule->image ? $storage->getGenericImage($path, $capsule->uuid, $capsule->image)  : '',
161 efrain 1790
                    'link_comments'     => $this->url()->fromRoute('microlearning/capsules-comments', ['capsule_id' => $capsule->uuid], ['force_canonical' => true]),
1791
                    'link_comment_add'  => $this->url()->fromRoute('microlearning/capsules-comments/add', ['capsule_id' => $capsule->uuid],['force_canonical' => true]),
558 stevensc 1792
                    'link_slides'       => $link_slides, // Usar el enlace construido
161 efrain 1793
                    'total_comments'    => strval($dataCountAndRatingAverage['total_comments']),
1794
                    'total_rating'      => strval($dataCountAndRatingAverage['total_rating']),
1795
                    'progress'          => $progress,
1796
                    'completed'         => $completed,
245 efrain 1797
                    'total_slides'      => $totalSlides,
244 efrain 1798
                    'link_first_slide'  => $link_first_slide,
1799
                    'type_first_slide'  => $type_first_slide,
161 efrain 1800
                    'order'             => $capsule->order,
1801
                    'added_on'          => $capsule->added_on,
1802
                    'updated_on'        => $capsule->updated_on,
1803
            ];
1804
 
1805
 
1806
 
1807
            return new JsonModel([
1808
                'success' => true,
1809
                'data' => $data
1810
            ]);
1811
 
1812
        } else {
1813
            return new JsonModel([
1814
                'success' => false,
1815
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
1816
            ]);
1817
        }
1818
    }
1819
 
119 efrain 1820
    public function slidesAction()
1821
    {
1822
        $request = $this->getRequest();
1823
        if($request->isGet()) {
1824
            $currentUserPlugin = $this->plugin('currentUserPlugin');
1825
            $currentUser = $currentUserPlugin->getUser();
1826
 
1827
 
1828
 
1829
            $topic_id = $this->params()->fromRoute('topic_id');
283 www 1830
            $topicMapper = MicrolearningTopicMapper::getInstance($this->adapter);
119 efrain 1831
            $topic = $topicMapper->fetchOneByUuid($topic_id);
1832
 
1833
            if(!$topic) {
1834
                return new JsonModel([
1835
                    'success' => false,
1836
                    'data' => 'ERROR_TOPIC_NOT_FOUND'
1837
                ]);
1838
            }
1839
 
1840
            $accessGrantedIds = $this->getAccessGranted();
1841
 
1842
            if(!in_array($topic->id, $accessGrantedIds->topics)) {
1843
                return new JsonModel([
1844
                    'success' => false,
1845
                    'data' => 'ERROR_YOU_DO_NOT_HAVE_ACCESS_TO_THIS_TOPIC'
1846
                ]);
1847
            }
1848
 
1849
            $capsule_id = $this->params()->fromRoute('capsule_id');
283 www 1850
            $capsuleMapper = MicrolearningCapsuleMapper::getInstance($this->adapter);
119 efrain 1851
            $capsule = $capsuleMapper->fetchOneByUuid($capsule_id);
1852
 
1853
            if(!$capsule) {
1854
                return new JsonModel([
1855
                    'success' => false,
1856
                    'data' => 'ERROR_CAPSULE_NOT_FOUND'
1857
                ]);
1858
            }
1859
 
1860
 
1861
 
1862
            if(!in_array($capsule->id, $accessGrantedIds->capsules)) {
1863
                return new JsonModel([
1864
                    'success' => false,
1865
                    'data' => 'ERROR_YOU_DO_NOT_HAVE_ACCESS_TO_THIS_CAPSULE'
1866
                ]);
1867
            }
1868
 
1869
 
1870
 
1871
            $data = [];
1872
 
283 www 1873
            $quizMapper = MicrolearningQuizMapper::getInstance($this->adapter);
119 efrain 1874
 
283 www 1875
            $slideMapper = MicrolearningSlideMapper::getInstance($this->adapter);
1876
            $userProgressMapper = MicrolearningUserProgressMapper::getInstance($this->adapter);
119 efrain 1877
 
333 www 1878
            $storage = Storage::getInstance($this->config, $this->adapter);
283 www 1879
            $path = $storage->getPathMicrolearningSlide();
119 efrain 1880
 
1881
            $slides = $slideMapper->fetchAllByCompanyIdAndTopicIdAndCapsuleId($capsule->company_id, $capsule->topic_id, $capsule->id);
1882
            foreach($slides as $slide)
1883
            {
1884
 
1885
 
1886
                $userProgress = $userProgressMapper->fetchOneByUserIdAndSlideId($currentUser->id, $slide->id);
1887
                if($userProgress) {
224 efrain 1888
                    $completed =  $userProgress->completed ;
119 efrain 1889
                } else {
1890
                    $completed = 0;
1891
                }
1892
 
235 efrain 1893
 
230 efrain 1894
 
235 efrain 1895
                $link_take_a_test = '';
230 efrain 1896
                if($slide->quiz_id) {
235 efrain 1897
 
283 www 1898
                    $quizMapper = MicrolearningQuizMapper::getInstance($this->adapter);
230 efrain 1899
                    $quiz = $quizMapper->fetchOne($slide->quiz_id);
1900
                    if($quiz) {
1901
                        $quiz_uuid = $quiz->uuid;
235 efrain 1902
                        $quiz_data = $this->getQuiz($slide->quiz_id);
1903
                        $link_take_a_test = $this->url()->fromRoute('microlearning/take-a-test', ['slide_id' => $slide->uuid], ['force_canonical' => true]);
230 efrain 1904
                    }
235 efrain 1905
 
1906
                }
119 efrain 1907
 
1908
 
1909
                array_push($data, [
235 efrain 1910
                    'quiz'                  => $quiz_uuid,
1911
                    'quiz_data'             => $quiz_data,
1912
                    'uuid'                  => $slide->uuid,
1913
                    'name'                  => $slide->name ? $slide->name : '',
1914
                    'description'           => $slide->description ? $slide->description : '',
1915
                    'type'                  => $slide->type,
283 www 1916
                    'background'            => $slide->background ? $storage->getGenericImage($path, $slide->uuid, $slide->background) : '',
1917
                    'file'                  => $slide->file ? $storage->getGenericFile($path, $slide->uuid, $slide->file) : '',
235 efrain 1918
                    'order'                 => $slide->order,
1919
                    'completed'             => $completed,
1920
                    'link_get'              => $this->url()->fromRoute('microlearning/get-slide', ['id' => $slide->uuid], ['force_canonical' => true]),
1921
                    '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 1922
                    'link_take_a_test'      => $link_take_a_test,
235 efrain 1923
                    'added_on'              => $slide->added_on,
1924
                    'updated_on'            => $slide->updated_on,
119 efrain 1925
                ]);
1926
 
1927
 
1928
 
1929
            }
1930
 
1931
            usort($data, function($a, $b) {
1932
 
1933
                $result =  $a['order'] <=> $b['order'];
1934
                if(0 == $result) {
1935
                    $result = strcasecmp($a['added_on'], $b['added_on']);
1936
                    if(0 == $result) {
1937
                        $result = strcasecmp($a['name'], $b['name']);
1938
                    }
1939
                }
1940
 
1941
                if($result < 0) {
1942
                    return 1;
1943
                } else if($result > 0) {
1944
                    return -1;
1945
                } else  {
1946
                    return  0;
1947
                }
1948
            });
1949
 
1950
 
1951
 
1952
                return new JsonModel([
1953
                    'success' => true,
1954
                    'data' => $data
1955
                ]);
1956
 
1957
        } else {
1958
            return new JsonModel([
1959
                'success' => false,
1960
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
1961
            ]);
1962
        }
1963
    }
1964
 
229 efrain 1965
    private function getQuiz($id)
1966
    {
1967
        $serviceDatetimeFormat = $this->config['leaderslinked.services.datetime'];
1968
 
1969
        $data = [];
1970
 
283 www 1971
        $quizMapper = MicrolearningQuizMapper::getInstance($this->adapter);
229 efrain 1972
        $quiz = $quizMapper->fetchOne($id);
1973
 
1974
        if(!$quiz) {
1975
            return [];
1976
        }
1977
 
1978
        $companyMapper = CompanyMapper::getInstance($this->adapter);
1979
        $company = $companyMapper->fetchOne($quiz->company_id);
1980
 
283 www 1981
        $questionMapper = MicrolearningQuestionMapper::getInstance($this->adapter);
1982
        $answerMapper = MicrolearningAnswerMapper::getInstance($this->adapter);
229 efrain 1983
 
1984
        $record_questions = [];
1985
        $questions = $questionMapper->fetchAllByQuizId($quiz->id);
1986
        foreach($questions as $question)
1987
        {
1988
            $record_answers = [];
1989
 
1990
            $answers = $answerMapper->fetchAllByQuizIdAndQuestionId($question->quiz_id, $question->id);
1991
            foreach($answers as $answer)
1992
            {
1993
                $dtAddedOn = \DateTime::createFromFormat('Y-m-d H:i:s', $answer->added_on);
1994
                $dtUpdatedOn = \DateTime::createFromFormat('Y-m-d H:i:s', $answer->updated_on);
1995
 
1996
                array_push($record_answers, [
1997
                    'uuid' => $answer->uuid,
1998
                    'text' => trim($answer->text),
1999
                    'correct' => $answer->correct ? $answer->correct  : 0 ,
2000
                    'points' => strval(intval($answer->points, 10)),
2001
                    'added_on'  => $dtAddedOn->format($serviceDatetimeFormat),
2002
                    'updated_on'    => $dtUpdatedOn->format($serviceDatetimeFormat),
2003
                ]);
2004
            }
2005
 
2006
            $dtAddedOn = \DateTime::createFromFormat('Y-m-d H:i:s', $question->added_on);
2007
            $dtUpdatedOn = \DateTime::createFromFormat('Y-m-d H:i:s', $question->updated_on);
2008
 
2009
            array_push($record_questions, [
2010
                'uuid'          => $question->uuid,
2011
                'text'          => trim($question->text),
2012
                'type'          => $question->type,
2013
                'maxlength'     => strval($question->maxlength),
2014
                'points'        => strval($question->points),
2015
                'answers'       => $record_answers,
2016
                'added_on'      => $dtAddedOn->format($serviceDatetimeFormat),
2017
                'updated_on'    => $dtUpdatedOn->format($serviceDatetimeFormat),
2018
            ]);
2019
        }
2020
 
2021
        $dtAddedOn = \DateTime::createFromFormat('Y-m-d H:i:s', $quiz->added_on);
2022
        $dtUpdatedOn = \DateTime::createFromFormat('Y-m-d H:i:s', $quiz->updated_on);
2023
 
2024
        array_push($data, [
2025
            'uuid' => $quiz->uuid,
2026
            'name' => $quiz->name,
2027
            'text' => trim($quiz->text ? $quiz->text : ''),
2028
            'failed' => trim($quiz->failed ? $quiz->failed : ''),
2029
            'points' => strval($quiz->points),
2030
            'minimum_points_required' => strval($quiz->minimum_points_required),
2031
            'max_time' => $quiz->max_time ? $quiz->max_time : 5,
2032
            'company_uuid' => $company->uuid,
2033
            'company_name' => $company->name,
2034
            'company_image' => $this->url()->fromRoute('services/storage',['type' => 'company', 'code' => $company->uuid, 'filename' => $company->image], ['force_canonical' => true]),
2035
            'questions'     => $record_questions,
2036
            'added_on'      => $dtAddedOn->format($serviceDatetimeFormat),
2037
            'updated_on'    => $dtUpdatedOn->format($serviceDatetimeFormat),
2038
        ]);
2039
 
2040
        return $data;
2041
 
2042
    }
161 efrain 2043
 
229 efrain 2044
 
161 efrain 2045
    public function getSlideAction()
2046
    {
2047
        $request = $this->getRequest();
2048
        if($request->isGet()) {
2049
            $currentUserPlugin = $this->plugin('currentUserPlugin');
2050
            $currentUser = $currentUserPlugin->getUser();
2051
 
2052
 
2053
 
2054
            $id = $this->params()->fromRoute('id');
283 www 2055
            $slideMapper = MicrolearningSlideMapper::getInstance($this->adapter);
161 efrain 2056
            $slide = $slideMapper->fetchOneByUuid($id);
2057
 
2058
            if(!$slide) {
2059
                return new JsonModel([
2060
                    'success' => false,
2061
                    'data' => 'ERROR_SLIDE_NOT_FOUND'
2062
                ]);
2063
            }
2064
 
2065
            $accessGrantedIds = $this->getAccessGranted();
2066
 
2067
 
2068
 
2069
            if(!in_array($slide->capsule_id, $accessGrantedIds->capsules)) {
2070
                return new JsonModel([
2071
                    'success' => false,
2072
                    'data' => 'ERROR_YOU_DO_NOT_HAVE_ACCESS_TO_THIS_CAPSULE'
2073
                ]);
2074
            }
2075
 
2076
 
283 www 2077
            $topicMapper = MicrolearningTopicMapper::getInstance($this->adapter);
161 efrain 2078
            $topic = $topicMapper->fetchOne($slide->topic_id);
2079
 
283 www 2080
            $capsuleMapper =  MicrolearningCapsuleMapper::getInstance($this->adapter);
161 efrain 2081
            $capsule = $capsuleMapper->fetchOne($slide->capsule_id);
2082
 
2083
 
2084
 
2085
 
2086
 
283 www 2087
            $slideMapper = MicrolearningSlideMapper::getInstance($this->adapter);
2088
            $userProgressMapper = MicrolearningUserProgressMapper::getInstance($this->adapter);
161 efrain 2089
 
2090
 
2091
            $userProgress = $userProgressMapper->fetchOneByUserIdAndSlideId($currentUser->id, $slide->id);
2092
            if($userProgress) {
2093
                $completed = $userProgress->completed;
2094
            } else {
2095
                $completed = 0;
2096
            }
235 efrain 2097
 
2098
            $quiz_uuid = '';
2099
            $quiz_data = [];
2100
            $link_take_a_test = '';
2101
            if($slide->quiz_id) {
2102
 
283 www 2103
                $quizMapper = MicrolearningQuizMapper::getInstance($this->adapter);
235 efrain 2104
                $quiz = $quizMapper->fetchOne($slide->quiz_id);
2105
                if($quiz) {
2106
                    $quiz_uuid = $quiz->uuid;
2107
                    $quiz_data = $this->getQuiz($slide->quiz_id);
2108
                    $link_take_a_test = $this->url()->fromRoute('microlearning/take-a-test', ['slide_id' => $slide->uuid], ['force_canonical' => true]);
2109
                }
161 efrain 2110
 
235 efrain 2111
            }
161 efrain 2112
 
333 www 2113
            $storage = Storage::getInstance($this->config, $this->adapter);
283 www 2114
            $path = $storage->getPathMicrolearningSlide();
161 efrain 2115
 
2116
            $data =[
235 efrain 2117
                'quiz'              => $quiz_uuid,
2118
                'quiz_data'         => $quiz_data,
2119
                'uuid'              => $slide->uuid,
2120
                'name'              => $slide->name ? $slide->name : '',
2121
                'description'       => $slide->description ? $slide->description : '',
2122
                'type'              => $slide->type,
283 www 2123
                'background'        => $slide->background ? $storage->getGenericImage($path, $slide->uuid, $slide->background) : '',
2124
                'file'              => $slide->file ? $storage->getGenericFile($path, $slide->uuid, $slide->file) : '',
235 efrain 2125
                'order'             => $slide->order,
2126
                'completed'         => $completed,
2127
                '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]),
2128
                'link_take_a_test'  => $link_take_a_test,
2129
                'added_on'          => $slide->added_on,
2130
                'updated_on'        => $slide->updated_on,
161 efrain 2131
            ];
2132
 
2133
 
2134
 
2135
 
2136
            return new JsonModel([
2137
                'success' => true,
2138
                'data' => $data
2139
            ]);
2140
 
2141
        } else {
2142
            return new JsonModel([
2143
                'success' => false,
2144
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
2145
            ]);
2146
        }
2147
    }
2148
 
119 efrain 2149
    public function profileAction()
2150
    {
2151
        $request = $this->getRequest();
2152
        if($request->isGet()) {
2153
            $currentUserPlugin = $this->plugin('currentUserPlugin');
2154
            $currentUser = $currentUserPlugin->getUser();
2155
 
2156
 
2157
            $accessGrantedIds = $this->getAccessGranted();
2158
 
2159
            $companyMapper = CompanyMapper::getInstance($this->adapter);
283 www 2160
            $companyExtendUserMapper = MicrolearningExtendUserMapper::getInstance($this->adapter);
2161
            $companyExtendUserCompanyMapper = MicrolearningExtendUserCompanyMapper::getInstance($this->adapter);
2162
            $companyExtendUserFunctionMapper = MicrolearningExtendUserFunctionMapper::getInstance($this->adapter);
2163
            $companyExtendUserGroupMapper = MicrolearningExtendUserGroupMapper::getInstance($this->adapter);
2164
            $companyExtendUserInstitutionMapper = MicrolearningExtendUserInstitutionMapper::getInstance($this->adapter);
2165
            $companyExtendUserPartnerMapper = MicrolearningExtendUserPartnerMapper::getInstance($this->adapter);
2166
            $companyExtendUserProgramMapper = MicrolearningExtendUserProgramMapper::getInstance($this->adapter);
2167
            $companyExtendUserStudentTypeMapper = MicrolearningExtendUserStudentTypeMapper::getInstance($this->adapter);
2168
            $companyExtendUserSectorMapper = MicrolearningExtendUserSectorMapper::getInstance($this->adapter);
119 efrain 2169
 
333 www 2170
            $storage = Storage::getInstance($this->config, $this->adapter);
283 www 2171
 
119 efrain 2172
 
2173
            $data = [];
2174
            foreach($accessGrantedIds->companies as $company_id)
2175
            {
2176
                $company = $companyMapper->fetchOne($company_id);
2177
                if(!$company) {
2178
                    continue;
2179
                }
2180
 
2181
                $record = [
2182
                    'name' => $company->name,
283 www 2183
                    'image' => $storage->getCompanyImage($company),
119 efrain 2184
                    'details' => [],
2185
                ];
2186
 
2187
                $companyExtendUser = $companyExtendUserMapper->fetchOneByCompanyIdAndUserId($company->id, $currentUser->id);
2188
                if(!$companyExtendUser) {
2189
                    continue;
2190
                }
2191
 
2192
                if($companyExtendUser->extend_company_id) {
2193
 
2194
                    $extendedCompany = $companyExtendUserCompanyMapper->fetchOne($companyExtendUser->company_id);
2195
                    if($extendedCompany) {
2196
                        array_push($record['details'],[
2197
                            'uuid' => $extendedCompany->uuid,
2198
                            'label' => 'LABEL_COMPANY',
2199
                            'value' => $extendedCompany->name
2200
                        ]);
2201
                    }
2202
                }
2203
 
2204
                if($companyExtendUser->extend_function_id) {
2205
                    $extendedFunction = $companyExtendUserFunctionMapper->fetchOne($companyExtendUser->extend_function_id);
2206
                    if($extendedFunction) {
2207
                        array_push($record['details'],[
2208
                            'uuid' => $extendedFunction->uuid,
2209
                            'label' => 'LABEL_FUNCTION',
2210
                            'value' => $extendedFunction->name
2211
                        ]);
2212
                    }
2213
                }
2214
 
2215
                if($companyExtendUser->extend_group_id) {
2216
                    $extendedGroup = $companyExtendUserGroupMapper->fetchOne($companyExtendUser->extend_group_id);
2217
                    if($extendedGroup) {
2218
                        array_push($record['details'],[
2219
                            'uuid' => $extendedGroup->uuid,
2220
                            'label' => 'LABEL_GROUP',
2221
                            'value' => $extendedGroup->name
2222
                        ]);
2223
                    }
2224
                }
2225
 
2226
                if($companyExtendUser->extend_institution_id) {
2227
                    $extendedInstitution= $companyExtendUserInstitutionMapper->fetchOne($companyExtendUser->extend_institution_id);
2228
                    if($extendedInstitution) {
2229
                        array_push($record['details'],[
2230
                            'uuid' => $extendedInstitution->uuid,
2231
                            'label' => 'LABEL_INSTITUTION',
2232
                            'value' => $extendedInstitution->name
2233
                        ]);
2234
                    }
2235
                }
2236
 
2237
                if($companyExtendUser->extend_program_id) {
2238
                    $extendedProgram = $companyExtendUserProgramMapper->fetchOne($companyExtendUser->extend_program_id);
2239
                    if($extendedProgram) {
2240
                        array_push($record['details'],[
2241
                            'uuid' => $extendedProgram->uuid,
2242
                            'label' => 'LABEL_PROGRAM',
2243
                            'value' => $extendedProgram->name
2244
                        ]);
2245
 
2246
                    }
2247
                }
2248
 
2249
                if($companyExtendUser->extend_sector_id) {
2250
                    $extendedSector = $companyExtendUserSectorMapper->fetchOne($companyExtendUser->extend_sector_id);
2251
                    if($extendedSector) {
2252
                        array_push($record['details'],[
2253
                            'uuid' => $extendedSector->uuid,
2254
                            'label' => 'LABEL_SECTOR',
2255
                            'value' => $extendedSector->name
2256
                        ]);
2257
                    }
2258
                }
2259
 
2260
                if($companyExtendUser->extend_partner_id) {
2261
                    $extendedPartner = $companyExtendUserPartnerMapper->fetchOne($companyExtendUser->extend_partner_id);
2262
                    if($extendedPartner) {
2263
                        array_push($record['details'],[
2264
                            'uuid' => $extendedPartner->uuid,
2265
                            'label' => 'LABEL_PARTNER',
2266
                            'value' => $extendedPartner->name
2267
                        ]);
2268
                    }
2269
                }
2270
 
2271
                if($companyExtendUser->extend_student_type_id) {
2272
                    $extendedStudentType = $companyExtendUserStudentTypeMapper->fetchOne($companyExtendUser->extend_student_type_id);
2273
                    if($extendedStudentType) {
2274
                        array_push($record['details'],[
2275
                            'uuid' => $extendedStudentType->uuid,
2276
                            'label' => 'LABEL_TYPE',
2277
                            'value' => $extendedStudentType->name
2278
                        ]);
2279
                    }
2280
                }
2281
 
2282
                array_push($data, $record);
2283
            }
2284
 
2285
            return new JsonModel([
2286
                'success' => true,
2287
                'data' => $data
2288
            ]);
2289
 
2290
        } else {
2291
            return new JsonModel([
2292
                'success' => false,
2293
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
2294
            ]);
2295
        }
2296
    }
2297
 
167 efrain 2298
    public function syncAction()
2299
    {
2300
        $request = $this->getRequest();
168 efrain 2301
        if($request->isPost()) {
167 efrain 2302
            $currentUserPlugin = $this->plugin('currentUserPlugin');
2303
            $currentUser = $currentUserPlugin->getUser();
2304
 
2305
 
2306
            $operation = $this->params()->fromRoute('operation');
2307
            if($operation == 'slide-view' || $operation == 'capsule-close' || $operation == 'topic-close') {
2308
                $accessGrantedIds = $this->getAccessGranted();
2309
 
2310
                $topic_uuid     = $this->params()->fromRoute('topic_uuid');
2311
                $capsule_uuid   = $this->params()->fromRoute('capsule_uuid');
2312
                $slide_uuid     = $this->params()->fromRoute('slide_uuid');
2313
 
2314
                $accessGrantedIds = $this->getAccessGranted();
2315
                if($operation == 'slide-view') {
2316
 
2317
                    if(empty($slide_uuid) || empty($capsule_uuid ) || empty($topic_uuid)) {
2318
                        return new JsonModel([
2319
                            'success' => false,
2320
                            'data' => 'ERROR_INVALID_PARAMETERS'
2321
                        ]);
2322
                    }
2323
 
2324
 
283 www 2325
                    $topicMapper = MicrolearningTopicMapper::getInstance($this->adapter);
167 efrain 2326
                    $topic = $topicMapper->fetchOneByUuid($topic_uuid);
2327
 
2328
                    if(!$topic) {
2329
                        return new JsonModel([
2330
                            'success' => false,
2331
                            'data' => 'ERROR_TOPIC_NOT_FOUND'
2332
                        ]);
2333
                    }
2334
 
2335
 
2336
 
2337
                    if(!in_array($topic->id, $accessGrantedIds->topics)) {
2338
                        return new JsonModel([
2339
                            'success' => false,
2340
                            'data' => 'ERROR_YOU_DO_NOT_HAVE_ACCESS_TO_THIS_TOPIC'
2341
                        ]);
2342
                    }
2343
 
283 www 2344
                    $capsuleMapper = MicrolearningCapsuleMapper::getInstance($this->adapter);
167 efrain 2345
                    $capsule = $capsuleMapper->fetchOneByUuid($capsule_uuid);
2346
 
2347
                    if(!$capsule) {
2348
                        return new JsonModel([
2349
                            'success' => false,
2350
                            'data' => 'ERROR_CAPSULE_NOT_FOUND'
2351
                        ]);
2352
                    }
119 efrain 2353
 
167 efrain 2354
                    if(!in_array($capsule->id, $accessGrantedIds->capsules) || $capsule->topic_id != $topic->id) {
2355
                        return new JsonModel([
2356
                            'success' => false,
2357
                            'data' => 'ERROR_YOU_DO_NOT_HAVE_ACCESS_TO_THIS_CAPSULE'
2358
                        ]);
2359
                    }
2360
 
283 www 2361
                    $slideMapper = MicrolearningSlideMapper::getInstance($this->adapter);
167 efrain 2362
                    $slide = $slideMapper->fetchOneByUuid($slide_uuid);
2363
                    if(!$slide) {
2364
                        return new JsonModel([
2365
                            'success' => false,
2366
                            'data' => 'ERROR_SLIDE_NOT_FOUND'
2367
                        ]);
2368
                    }
2369
 
2370
                    if($slide->capsule_id != $capsule->id && $slide->topic_id != $topic->id) {
2371
                        return new JsonModel([
2372
                            'success' => false,
2373
                            'data' => 'ERROR_SLIDE_NOT_FOUND'
2374
                        ]);
2375
 
2376
                    }
2377
 
2378
 
283 www 2379
                    $userLogMapper = MicrolearningUserLogMapper::getInstance($this->adapter);
167 efrain 2380
 
283 www 2381
                    $userProgressMapper = MicrolearningUserProgressMapper::getInstance($this->adapter);
167 efrain 2382
                    $added_on = $userProgressMapper->getDatebaseNow();
2383
 
2384
 
2385
                    $userProgressTopic = $userProgressMapper->fetchOneByUserIdAndTopicId($currentUser->id, $topic->id);
2386
                    if(!$userProgressTopic) {
2387
 
283 www 2388
                        $userProgressTopic = new MicrolearningUserProgress();
558 stevensc 2389
                        $userProgressTopic->company_id                  = $topic->company_id; // Usar company_id del tópico
2390
                        $userProgressTopic->topic_id                    = $topic->id;        // Usar id del tópico
176 efrain 2391
                        $userProgressTopic->user_id                     = $currentUser->id;
167 efrain 2392
                        $userProgressTopic->progress                    = 0;
2393
                        $userProgressTopic->returning                   = 0;
2394
                        $userProgressTopic->returning_after_completed   = 0;
2395
                        $userProgressTopic->completed                   = 0;
558 stevensc 2396
                        $userProgressTopic->total_slides                = $slideMapper->fetchTotalCountByCompanyIdAndTopicId($topic->company_id, $topic->id);
167 efrain 2397
                        $userProgressTopic->view_slides                 = 0;
283 www 2398
                        $userProgressTopic->type                        = MicrolearningUserProgress::TYPE_TOPIC;
167 efrain 2399
                        $userProgressTopic->added_on                    = $added_on;
2400
                        $userProgressTopic->updated_on                  = $added_on;
2401
 
2402
                        if($userProgressMapper->insert($userProgressTopic)) {
2403
 
283 www 2404
                            $userLog = new MicrolearningUserLog();
2405
                            $userLog->activity      = MicrolearningUserLog::ACTIVITY_START_TOPIC;
167 efrain 2406
                            $userLog->user_id       = $currentUser->id;
558 stevensc 2407
                            $userLog->company_id    = $topic->company_id;
2408
                            $userLog->topic_id      = $topic->id;
167 efrain 2409
                            $userLog->added_on      = $added_on;
2410
 
2411
                            if(!$userLogMapper->insert($userLog)) {
2412
                                return new JsonModel([
2413
                                    'success' => false,
2414
                                    'data' => $userProgressMapper->getError()
2415
                                ]);
2416
                            }
2417
                        } else {
2418
                            return new JsonModel([
2419
                                'success' => false,
2420
                                'data' => $userProgressMapper->getError()
2421
                            ]);
2422
                        }
2423
                    }
2424
 
2425
 
2426
                    $userProgressCapsule = $userProgressMapper->fetchOneByUseridAndCapsuleId($currentUser->id, $capsule->id);
2427
                    if(!$userProgressCapsule) {
2428
 
283 www 2429
                        $userProgressCapsule = new MicrolearningUserProgress();
558 stevensc 2430
                        $userProgressCapsule->company_id                  = $capsule->company_id; // Usar company_id de la cápsula
2431
                        $userProgressCapsule->topic_id                    = $topic->id;         // Usar el id del tópico obtenido previamente
2432
                        $userProgressCapsule->capsule_id                  = $capsule->id;       // Usar id de la cápsula
176 efrain 2433
                        $userProgressCapsule->user_id                     = $currentUser->id;
167 efrain 2434
                        $userProgressCapsule->progress                    = 0;
2435
                        $userProgressCapsule->returning                   = 0;
2436
                        $userProgressCapsule->returning_after_completed   = 0;
2437
                        $userProgressCapsule->completed                   = 0;
558 stevensc 2438
                        $userProgressCapsule->total_slides                = $slideMapper->fetchTotalCountByCompanyIdAndTopicIdAndCapsuleId($capsule->company_id, $topic->id, $capsule->id);
167 efrain 2439
                        $userProgressCapsule->view_slides                 = 0;
2440
                        $userProgressTopic->updated_on                    = $added_on;
2441
 
2442
                        if($userProgressMapper->insert($userProgressCapsule)) {
2443
 
283 www 2444
                            $userLog = new MicrolearningUserLog();
2445
                            $userLog->activity      = MicrolearningUserLog::ACTIVITY_START_CAPSULE;
167 efrain 2446
                            $userLog->user_id       = $currentUser->id;
558 stevensc 2447
                            $userLog->company_id    = $capsule->company_id;
2448
                            $userLog->topic_id      = $topic->id;
2449
                            $userLog->capsule_id    = $capsule->id;
167 efrain 2450
                            $userLog->added_on      = $added_on;
2451
 
2452
                            if(!$userLogMapper->insert($userLog)) {
2453
                                return new JsonModel([
2454
                                    'success' => false,
2455
                                    'data' => $userLogMapper->getError()
2456
                                ]);
2457
                            }
2458
                        } else {
2459
                            return new JsonModel([
2460
                                'success' => false,
2461
                                'data' => $userProgressMapper->getError()
2462
                            ]);
2463
                        }
2464
                    }
2465
 
2466
 
2467
                    $userProgressSlide = $userProgressMapper->fetchOneByUserIdAndSlideId($currentUser->id, $slide->id);
2468
                    if(!$userProgressSlide) {
283 www 2469
                        $userProgressSlide = new MicrolearningUserProgress();
167 efrain 2470
                        $userProgressSlide->company_id                  = $slide->company_id;
2471
                        $userProgressSlide->topic_id                    = $slide->topic_id;
2472
                        $userProgressSlide->capsule_id                  = $slide->capsule_id;
2473
                        $userProgressSlide->slide_id                    = $slide->id;
176 efrain 2474
                        $userProgressSlide->user_id                     = $currentUser->id;
167 efrain 2475
                        $userProgressSlide->progress                    = 0;
2476
                        $userProgressSlide->returning                   = 0;
2477
                        $userProgressSlide->returning_after_completed   = 0;
2478
                        $userProgressSlide->completed                   = 1;
2479
                        $userProgressSlide->total_slides                = 0;
2480
                        $userProgressSlide->view_slides                 = 0;
283 www 2481
                        $userProgressSlide->type                        = MicrolearningUserProgress::TYPE_SLIDE;
167 efrain 2482
                        $userProgressSlide->added_on                    = $added_on;
2483
                        $userProgressSlide->updated_on                  = $added_on;
2484
 
2485
                        if(!$userProgressMapper->insert($userProgressSlide)) {
2486
                            return new JsonModel([
2487
                                'success' => false,
2488
                                'data' => $userProgressMapper->getError()
2489
                            ]);
2490
                        }
2491
                    }
2492
 
283 www 2493
                    $userLog = new MicrolearningUserLog();
2494
                    $userLog->activity      = MicrolearningUserLog::ACTIVITY_VIEW_SLIDE;
167 efrain 2495
                    $userLog->user_id       = $currentUser->id;
2496
                    $userLog->company_id    = $slide->company_id;
2497
                    $userLog->topic_id      = $slide->topic_id;
2498
                    $userLog->capsule_id    = $slide->capsule_id;
2499
                    $userLog->slide_id      = $slide->id;
2500
                    $userLog->added_on      = $added_on;
2501
 
2502
                    if(!$userLogMapper->insert($userLog)) {
2503
                        return new JsonModel([
2504
                            'success' => false,
2505
                            'data' => $userLogMapper->getError()
2506
                        ]);
2507
                    }
2508
 
2509
                    $closeCapsule = false;
2510
 
2511
                    if($userProgressCapsule->completed) {
2512
 
2513
                        $dt = \DateTime::createFromFormat('Y-m-d H:i:s', $added_on);
2514
                        $returning_on = $dt->format('Y-m-d');
2515
 
558 stevensc 2516
                        // Asegurarse que returning_on existe en el objeto antes de comparar
2517
                        $current_returning_on = isset($userProgressCapsule->returning_on) ? $userProgressCapsule->returning_on : null;
2518
 
2519
                        if(!$current_returning_on || $current_returning_on != $returning_on) {
167 efrain 2520
 
2521
                            $userProgressCapsule->returning_on = $returning_on;
558 stevensc 2522
                            // Asegurarse que returning_after_completed existe y es numérico antes de incrementar
2523
                            $userProgressCapsule->returning_after_completed = (isset($userProgressCapsule->returning_after_completed) ? intval($userProgressCapsule->returning_after_completed) : 0) + 1;
167 efrain 2524
 
2525
                            if(!$userProgressMapper->update($userProgressCapsule)) {
2526
                                return new JsonModel([
2527
                                    'success' => false,
2528
                                    'data' => $userProgressMapper->getError()
2529
                                ]);
2530
                            }
2531
                        }
2532
 
2533
                    }  else {
2534
 
558 stevensc 2535
                        // Usar $topic->id para obtener el total de slides de la cápsula en el contexto de este tópico
2536
                        $userProgressCapsule->total_slides = $slideMapper->fetchTotalCountByCompanyIdAndTopicIdAndCapsuleId($capsule->company_id, $topic->id, $capsule->id);
2537
                        $userProgressCapsule->view_slides = $userProgressMapper->fetchCountAllSlideCompletedByUserIdAndCapsuleId($currentUser->id, $capsule->id);
167 efrain 2538
 
2539
                        if($userProgressCapsule->total_slides) {
2540
 
2541
                            $userProgressCapsule->progress = ($userProgressCapsule->view_slides * 100) / $userProgressCapsule->total_slides;
2542
                            $userProgressCapsule->progress = $userProgressCapsule->progress > 100 ? 100 : $userProgressCapsule->progress;
2543
                        }
2544
 
2545
                        if(!$userProgressMapper->update($userProgressCapsule)) {
2546
                            return new JsonModel([
2547
                                'success' => false,
2548
                                'data' => $userProgressMapper->getError()
2549
                            ]);
2550
                        }
2551
 
2552
                        if($userProgressCapsule->progress >= 100) {
2553
                            $closeCapsule = true;
2554
                        }
171 efrain 2555
 
283 www 2556
 
167 efrain 2557
                    }
2558
 
2559
                    $closeTopic = false;
2560
                    if(!$userProgressTopic->completed) {
2561
 
558 stevensc 2562
                        // Usar $topic->id para obtener el total de slides del tópico
2563
                        $userProgressTopic->total_slides = $slideMapper->fetchTotalCountByCompanyIdAndTopicId($topic->company_id, $topic->id);
2564
                        $userProgressTopic->view_slides = $userProgressMapper->fetchCountAllSlideCompletedByUserIdAndTopicId($currentUser->id, $topic->id);
167 efrain 2565
 
2566
                        if($userProgressTopic->total_slides) {
2567
 
2568
                            $userProgressTopic->progress = ($userProgressTopic->view_slides * 100) / $userProgressTopic->total_slides;
2569
                            $userProgressTopic->progress = $userProgressTopic->progress > 100 ? 100 : $userProgressTopic->progress;
2570
                        }
2571
                        if(!$userProgressMapper->update($userProgressTopic)) {
2572
                            return new JsonModel([
2573
                                'success' => false,
2574
                                'data' => $userProgressMapper->getError()
2575
                            ]);
2576
                        }
2577
 
2578
                        if($userProgressTopic->progress >= 100) {
2579
                            $closeTopic = true;
2580
                        }
2581
                    }
2582
 
2583
 
2584
                    $data = [
2585
                        'message' => 'LABEL_THE_USER_PROGRESS_FOR_THIS_SLIDE_HAS_BEEN_COMPLETED',
2586
 
2587
                    ];
2588
 
2589
                    if($closeCapsule) {
173 efrain 2590
                        $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 2591
                    }
2592
 
2593
 
2594
                    if($closeTopic) {
173 efrain 2595
                        $data['link_close_topic'] = $this->url()->fromRoute('microlearning/sync', ['operation' => 'topic-close', 'topic_uuid' => $topic->uuid], ['force_canonical' => true]);
167 efrain 2596
                    }
2597
 
2598
 
2599
                    return new JsonModel([
2600
                        'success' => true,
2601
                        'data' => $data
2602
                    ]);
2603
 
2604
 
2605
 
2606
 
2607
                } else if($operation == 'capsule-close') {
2608
 
2609
                    if(empty($capsule_uuid ) || empty($topic_uuid)) {
2610
                        return new JsonModel([
2611
                            'success' => false,
2612
                            'data' => 'ERROR_INVALID_PARAMETERS'
2613
                        ]);
2614
                    }
2615
 
2616
 
283 www 2617
                    $topicMapper = MicrolearningTopicMapper::getInstance($this->adapter);
167 efrain 2618
                    $topic = $topicMapper->fetchOneByUuid($topic_uuid);
2619
 
2620
                    if(!$topic) {
2621
                        return new JsonModel([
2622
                            'success' => false,
2623
                            'data' => 'ERROR_TOPIC_NOT_FOUND'
2624
                        ]);
2625
                    }
2626
 
2627
 
2628
 
2629
                    if(!in_array($topic->id, $accessGrantedIds->topics)) {
2630
                        return new JsonModel([
2631
                            'success' => false,
2632
                            'data' => 'ERROR_YOU_DO_NOT_HAVE_ACCESS_TO_THIS_TOPIC'
2633
                        ]);
2634
                    }
2635
 
283 www 2636
                    $capsuleMapper = MicrolearningCapsuleMapper::getInstance($this->adapter);
167 efrain 2637
                    $capsule = $capsuleMapper->fetchOneByUuid($capsule_uuid);
2638
 
2639
                    if(!$capsule) {
2640
                        return new JsonModel([
2641
                            'success' => false,
2642
                            'data' => 'ERROR_CAPSULE_NOT_FOUND'
2643
                        ]);
2644
                    }
2645
 
2646
                    if(!in_array($capsule->id, $accessGrantedIds->capsules) || $capsule->topic_id != $topic->id) {
2647
                        return new JsonModel([
2648
                            'success' => false,
2649
                            'data' => 'ERROR_YOU_DO_NOT_HAVE_ACCESS_TO_THIS_CAPSULE'
2650
                        ]);
2651
                    }
2652
 
2653
 
283 www 2654
                    $userLogMapper = MicrolearningUserLogMapper::getInstance($this->adapter);
167 efrain 2655
 
283 www 2656
                    $userProgressMapper = MicrolearningUserProgressMapper::getInstance($this->adapter);
167 efrain 2657
                    $updated_on = $userProgressMapper->getDatebaseNow();
2658
 
2659
                    $userProgressCapsule = $userProgressMapper->fetchOneByUseridAndCapsuleId($currentUser->id, $capsule->id);
2660
                    if(!$userProgressCapsule) {
2661
                        return new JsonModel([
2662
                            'success' => false,
2663
                            'data' => 'ERROR_THE_USER_PROGRESS_FOR_THIS_CAPSULE_NOT_FOUND'
2664
                        ]);
2665
                    }
2666
 
2667
                    if($userProgressCapsule->completed) {
2668
                        return new JsonModel([
2669
                            'success' => false,
2670
                            'data' => 'ERROR_THE_USER_PROGRESS_FOR_THIS_CAPSULE_ALREADY_CLOSED'
2671
                        ]);
2672
                    }
2673
 
2674
 
2675
                    $userProgressCapsule->completed = 1;
2676
                    $userProgressCapsule->updated_on = $updated_on;
2677
 
2678
                    if($userProgressMapper->update($userProgressCapsule)) {
225 efrain 2679
 
2680
 
283 www 2681
                        $userLog = new MicrolearningUserLog();
2682
                        $userLog->activity      = MicrolearningUserLog::ACTIVITY_COMPLETED_CAPSULE;
227 efrain 2683
                        $userLog->user_id       = $currentUser->id;
2684
                        $userLog->company_id    = $capsule->company_id;
2685
                        $userLog->topic_id      = $capsule->topic_id;
2686
                        $userLog->capsule_id    = $capsule->id;
2687
                        $userLog->added_on      = $updated_on;
225 efrain 2688
 
2689
                        if(!$userLogMapper->insert($userLog)) {
2690
                            return new JsonModel([
2691
                                'success' => false,
2692
                                'data' => $userProgressMapper->getError()
2693
                            ]);
2694
                        }
2695
 
2696
 
167 efrain 2697
                        return new JsonModel([
2698
                            'success' => true,
2699
                            'data' => 'LABEL_THE_USER_PROGRESS_FOR_THIS_CAPSULE_HAS_BEEN_COMPLETED'
2700
                        ]);
2701
                    } else {
2702
                        return new JsonModel([
2703
                            'success' => false,
2704
                            'data' => 'ERROR_THE_USER_PROGRESS_FOR_THIS_CAPSULE_COULD_NOT_BE_COMPLETED'
2705
                        ]);
2706
                    }
2707
 
2708
 
2709
 
2710
 
2711
 
2712
 
2713
 
2714
                } else if($operation == 'topic-close') {
174 efrain 2715
                    if(empty($topic_uuid)) {
167 efrain 2716
                        return new JsonModel([
2717
                            'success' => false,
2718
                            'data' => 'ERROR_INVALID_PARAMETERS'
2719
                        ]);
2720
                    }
2721
 
2722
 
283 www 2723
                    $topicMapper = MicrolearningTopicMapper::getInstance($this->adapter);
167 efrain 2724
                    $topic = $topicMapper->fetchOneByUuid($topic_uuid);
2725
 
2726
                    if(!$topic) {
2727
                        return new JsonModel([
2728
                            'success' => false,
2729
                            'data' => 'ERROR_TOPIC_NOT_FOUND'
2730
                        ]);
2731
                    }
2732
 
2733
 
2734
 
2735
                    if(!in_array($topic->id, $accessGrantedIds->topics)) {
2736
                        return new JsonModel([
2737
                            'success' => false,
2738
                            'data' => 'ERROR_YOU_DO_NOT_HAVE_ACCESS_TO_THIS_TOPIC'
2739
                        ]);
2740
                    }
2741
 
2742
 
2743
 
2744
 
283 www 2745
                    $userLogMapper = MicrolearningUserLogMapper::getInstance($this->adapter);
167 efrain 2746
 
283 www 2747
                    $userProgressMapper = MicrolearningUserProgressMapper::getInstance($this->adapter);
167 efrain 2748
                    $updated_on = $userProgressMapper->getDatebaseNow();
2749
 
2750
                    $userProgressTopic = $userProgressMapper->fetchOneByUserIdAndTopicId($currentUser->id, $topic->id);
2751
                    if(!$userProgressTopic) {
2752
                        return new JsonModel([
2753
                            'success' => false,
2754
                            'data' => 'ERROR_THE_USER_PROGRESS_FOR_THIS_TOPIC_NOT_FOUND'
2755
                        ]);
2756
                    }
2757
 
2758
                    if($userProgressTopic->completed) {
2759
                        return new JsonModel([
2760
                            'success' => false,
2761
                            'data' => 'ERROR_THE_USER_PROGRESS_FOR_THIS_TOPIC_ALREADY_CLOSED'
2762
                        ]);
2763
                    }
2764
 
2765
 
2766
                    $userProgressTopic->completed = 1;
2767
                    $userProgressTopic->updated_on = $updated_on;
2768
 
2769
                    if($userProgressMapper->update($userProgressTopic)) {
226 efrain 2770
 
283 www 2771
                        $userLog = new MicrolearningUserLog();
2772
                        $userLog->activity      = MicrolearningUserLog::ACTIVITY_COMPLETED_TOPIC;
227 efrain 2773
                        $userLog->user_id       = $currentUser->id;
2774
                        $userLog->company_id    = $topic->company_id;
2775
                        $userLog->topic_id      = $topic->id;
2776
                        $userLog->added_on      = $updated_on;
226 efrain 2777
 
2778
                        if(!$userLogMapper->insert($userLog)) {
2779
                            return new JsonModel([
2780
                                'success' => false,
2781
                                'data' => $userProgressMapper->getError()
2782
                            ]);
2783
                        }
2784
 
167 efrain 2785
                        return new JsonModel([
2786
                            'success' => true,
2787
                            'data' => 'LABEL_THE_USER_PROGRESS_FOR_THIS_TOPIC_HAS_BEEN_COMPLETED'
2788
                        ]);
2789
                    } else {
2790
                        return new JsonModel([
2791
                            'success' => false,
2792
                            'data' => 'ERROR_THE_USER_PROGRESS_FOR_THIS_TOPIC_COULD_NOT_BE_COMPLETED'
2793
                        ]);
2794
                    }
2795
                }
2796
 
2797
 
2798
 
2799
 
2800
            } else {
2801
 
2802
                return new JsonModel([
2803
                    'success' => false,
2804
                    'data' => 'ERROR_OPERATION_UNKNOWN'
2805
                ]);
2806
 
2807
 
2808
            }
2809
 
2810
        } else {
2811
            return new JsonModel([
2812
                'success' => false,
2813
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
2814
            ]);
2815
        }
2816
    }
2817
 
2818
 
302 www 2819
 
2820
 
2821
 
119 efrain 2822
    /**
2823
     *
2824
     * @return \LeadersLinked\Controller\MicrolearningUserAccessGrantedIds
2825
     */
2826
    private function getAccessGranted()
2827
    {
2828
        $currentUserPlugin = $this->plugin('currentUserPlugin');
2829
        $currentUser = $currentUserPlugin->getUser();
2830
 
283 www 2831
        $capsuleUserMapper = MicrolearningCapsuleUserMapper::getInstance($this->adapter);
119 efrain 2832
        $now = $capsuleUserMapper->getDatebaseNow();
2833
 
2834
        $records = $capsuleUserMapper->fetchAllActiveByUserId($currentUser->id);
2835
 
2836
        $accessGrantedIds = new MicrolearningUserAccessGrantedIds();
2837
 
2838
 
2839
        foreach($records as $record)
2840
        {
283 www 2841
            if($record->access != MicrolearningCapsuleUser::ACCESS_UNLIMITED && $record->access != MicrolearningCapsuleUser::ACCESS_PAY_PERIOD) {
119 efrain 2842
                continue;
2843
            }
283 www 2844
            if($record->access == MicrolearningCapsuleUser::ACCESS_PAY_PERIOD) {
119 efrain 2845
                if($now < $record->paid_from || $now > $record->paid_to) {
2846
                    continue;
2847
                }
2848
            }
2849
 
2850
 
2851
            if(!in_array($record->company_id, $accessGrantedIds->companies )) {
2852
                array_push($accessGrantedIds->companies, $record->company_id);
2853
            }
2854
 
2855
            if(!in_array($record->topic_id, $accessGrantedIds->topics )) {
2856
                array_push( $accessGrantedIds->topics, $record->topic_id);
2857
            }
2858
 
2859
            if(!in_array($record->capsule_id, $accessGrantedIds->capsules)) {
2860
                array_push( $accessGrantedIds->capsules, $record->capsule_id);
2861
            }
2862
        }
2863
 
2864
        return $accessGrantedIds;
2865
    }
2866
 
2867
 
2868
}