Proyectos de Subversion LeadersLinked - Services

Rev

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