Proyectos de Subversion LeadersLinked - Services

Rev

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