Proyectos de Subversion LeadersLinked - Backend

Rev

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

Rev Autor Línea Nro. Línea
1 www 1
<?php
2
declare(strict_types=1);
3
 
4
namespace LeadersLinked\Controller;
5
 
6
use Laminas\Db\Adapter\AdapterInterface;
7
use Laminas\Cache\Storage\Adapter\AbstractAdapter;
8
use Laminas\Mvc\Controller\AbstractActionController;
9
use Laminas\Log\LoggerInterface;
10
use Laminas\View\Model\ViewModel;
11
use Laminas\View\Model\JsonModel;
12
use LeadersLinked\Mapper\CompanyMicrolearningTopicMapper;
13
use LeadersLinked\Mapper\CompanyMicrolearningCapsuleMapper;
14
use LeadersLinked\Form\TopicCapsuleForm;
15
use LeadersLinked\Form\PushMicrolearningNotificationForm;
16
use LeadersLinked\Mapper\QueryMapper;
17
use LeadersLinked\Mapper\CompanyMicrolearningCapsuleUserMapper;
18
use LeadersLinked\Mapper\UserMapper;
19
use Laminas\Hydrator\ArraySerializableHydrator;
20
use Laminas\Db\ResultSet\HydratingResultSet;
21
use Laminas\Paginator\Adapter\DbSelect;
22
use Laminas\Paginator\Paginator;
23
use LeadersLinked\Model\CompanyMicrolearningCapsuleUser;
24
use LeadersLinked\Mapper\ApplicationMapper;
25
use LeadersLinked\Mapper\PushMapper;
26
use LeadersLinked\Mapper\PushTemplateMapper;
27
use LeadersLinked\Mapper\DeviceHistoryMapper;
28
use LeadersLinked\Model\Push;
29
use LeadersLinked\Model\Application;
30
use LeadersLinked\Form\CapsuleCustomerUploadForm;
31
use PhpOffice\PhpSpreadsheet\IOFactory;
32
use LeadersLinked\Model\User;
33
use LeadersLinked\Model\UserType;
34
use LeadersLinked\Model\UserPassword;
35
use LeadersLinked\Mapper\CompanyMicrolearningUserMapper;
36
use LeadersLinked\Mapper\UserPasswordMapper;
37
use LeadersLinked\Mapper\CompanyMicrolearningExtendUserMapper;
38
use LeadersLinked\Mapper\CompanyMicrolearningExtendUserCompanyMapper;
39
use LeadersLinked\Mapper\CompanyMicrolearningExtendUserFunctionMapper;
40
use LeadersLinked\Mapper\CompanyMicrolearningExtendUserGroupMapper;
41
use LeadersLinked\Mapper\CompanyMicrolearningExtendUserInstitutionMapper;
42
use LeadersLinked\Mapper\CompanyMicrolearningExtendUserProgramMapper;
43
use LeadersLinked\Mapper\CompanyMicrolearningExtendUserPartnerMapper;
44
use LeadersLinked\Mapper\CompanyMicrolearningExtendUserSectorMapper;
45
use LeadersLinked\Mapper\CompanyMicrolearningExtendUserStudentTypeMapper;
46
use LeadersLinked\Model\CompanyMicrolearningExtendUser;
47
use LeadersLinked\Model\CompanyMicrolearningExtendUserCompany;
48
use LeadersLinked\Model\CompanyMicrolearningExtendUserFunction;
49
use LeadersLinked\Model\CompanyMicrolearningExtendUserGroup;
50
use LeadersLinked\Model\CompanyMicrolearningExtendUserInstitution;
51
use LeadersLinked\Model\CompanyMicrolearningExtendUserProgram;
52
use LeadersLinked\Model\CompanyMicrolearningExtendUserPartner;
53
use LeadersLinked\Model\CompanyMicrolearningExtendUserSector;
54
use LeadersLinked\Model\CompanyMicrolearningExtendUserStudentType;
55
use LeadersLinked\Model\CompanyMicrolearningUser;
13755 efrain 56
use LeadersLinked\Mapper\ApplicationVariantMapper;
15394 efrain 57
use LeadersLinked\Mapper\CompanyMicrolearningExtendUserCountryMapper;
15452 efrain 58
use LeadersLinked\Model\CompanyMicrolearningExtendUserCountry;
15453 efrain 59
use LeadersLinked\Model\Network;
60
use LeadersLinked\Mapper\CompanyMapper;
61
use LeadersLinked\Mapper\NetworkMapper;
62
use LeadersLinked\Mapper\CompanyFollowerMapper;
63
use LeadersLinked\Mapper\ConnectionMapper;
64
use LeadersLinked\Model\Connection;
65
use LeadersLinked\Model\CompanyFollower;
1 www 66
 
67
 
68
class MicrolearningAccessForStudentsController extends AbstractActionController
69
{
70
    /**
71
     *
72
     * @var AdapterInterface
73
     */
74
    private $adapter;
75
 
76
 
77
    /**
78
     *
79
     * @var AbstractAdapter
80
     */
81
    private $cache;
82
 
83
    /**
84
     *
85
     * @var  LoggerInterface
86
     */
87
    private $logger;
88
 
89
 
90
    /**
91
     *
92
     * @var array
93
     */
94
    private $config;
95
 
96
    /**
97
     *
98
     * @param AdapterInterface $adapter
99
     * @param AbstractAdapter $cache
100
     * @param LoggerInterface $logger
101
     * @param array $config
102
     */
103
    public function __construct($adapter, $cache , $logger,  $config)
104
    {
105
        $this->adapter      = $adapter;
106
        $this->cache        = $cache;
107
        $this->logger       = $logger;
108
        $this->config       = $config;
109
 
110
    }
111
 
112
    public function indexAction()
113
    {
114
        $currentUserPlugin = $this->plugin('currentUserPlugin');
115
        $currentUser = $currentUserPlugin->getUser();
116
        $currentCompany = $currentUserPlugin->getCompany();
117
 
118
        $request = $this->getRequest();
119
 
120
        if($request->isGet())
121
        {
122
 
123
            $headers  = $request->getHeaders();
124
 
125
            $isJson = false;
126
            if($headers->has('Accept')) {
127
                $accept = $headers->get('Accept');
128
 
129
                $prioritized = $accept->getPrioritized();
130
 
131
                foreach($prioritized as $key => $value) {
132
                    $raw = trim($value->getRaw());
133
 
134
                    if(!$isJson) {
135
                        $isJson = strpos($raw, 'json');
136
                    }
137
 
138
                }
139
            }
140
 
141
            if($isJson) {
142
                $topic_uuid     = filter_var($this->params()->fromQuery('topic_uuid'), FILTER_SANITIZE_STRING);
143
                $capsule_uuid   = filter_var($this->params()->fromQuery('capsule_uuid'), FILTER_SANITIZE_STRING);
144
 
145
                $data = [
146
                    'link_upload' => '',
147
                    'items' => [] ,
148
                    'total' => 0,
149
 
150
                ];
151
 
152
 
153
                if(!$topic_uuid) {
154
                    return new JsonModel([
155
                        'success' => true,
156
                        'data' => $data
157
                    ]);
158
 
159
                }
160
 
161
 
162
                $topicMapper = CompanyMicrolearningTopicMapper::getInstance($this->adapter);
163
                $topic = $topicMapper->fetchOneByUuid($topic_uuid);
164
                if(!$topic) {
165
                    return new JsonModel([
166
                        'success' => true,
167
                        'data' => 'ERROR_TOPIC_NOT_FOUND'
168
                    ]);
169
                }
170
 
171
                if($topic->company_id != $currentCompany->id) {
172
                    return new JsonModel([
173
                        'success' => true,
174
                        'data' => 'ERROR_UNAUTHORIZED'
175
                    ]);
176
                }
177
 
178
 
179
 
180
                if(!$capsule_uuid) {
181
                    $capsuleMapper = CompanyMicrolearningCapsuleMapper::getInstance($this->adapter);
182
                    $records = $capsuleMapper->fetchAllByCompanyIdAndTopicId($topic->company_id, $topic->id);
183
 
184
                    $capsules = [];
185
                    foreach($records as $record)
186
                    {
187
                        if(!$capsule_uuid) {
188
                            $capsule_uuid = $record->uuid;
189
                        }
190
 
191
                        $capsules[ $record->uuid ] = $record->name;
192
                    }
193
 
194
                    $data['capsules']  = $capsules;
195
                }
196
 
197
                if(!$capsule_uuid) {
198
                    return new JsonModel([
199
                        'success' => true,
200
                        'data' => $data
201
                    ]);
202
 
203
                }
204
 
205
                $capsuleMapper = CompanyMicrolearningCapsuleMapper::getInstance($this->adapter);
206
                $capsule = $capsuleMapper->fetchOneByUuid($capsule_uuid);
207
 
208
 
209
 
210
                if(!$capsule) {
211
                    return new JsonModel([
212
                        'success' => true,
213
                        'data' => 'ERROR_CAPSULE_NOT_FOUND'
214
                    ]);
215
                }
216
 
217
                if($capsule->topic_id != $topic->id) {
218
                    return new JsonModel([
219
                        'success' => true,
220
                        'data' => 'ERROR_UNAUTHORIZED'
221
                    ]);
222
                }
223
 
224
 
225
                $data['link_upload'] = $this->url()->fromRoute('microlearning/access-for-students/upload',['topic_uuid' => $topic->uuid, 'capsule_uuid' => $capsule->uuid]);
226
                $data['link_notification'] = $this->url()->fromRoute('microlearning/access-for-students/notification',['topic_uuid' => $topic->uuid, 'capsule_uuid' => $capsule->uuid]);
227
 
228
                $search = $this->params()->fromQuery('search', []);
229
                $search = empty($search['value']) ? '' : filter_var($search['value'], FILTER_SANITIZE_STRING);
230
 
231
                $page               = intval($this->params()->fromQuery('start', 1), 10);
232
                $records_x_page     = intval($this->params()->fromQuery('length', 10), 10);
233
                $order =  $this->params()->fromQuery('order', []);
234
                $order_field        = empty($order[0]['column']) ? 99 :  intval($order[0]['column'], 10);
235
                $order_direction    = empty($order[0]['dir']) ? 'ASC' : strtoupper(filter_var( $order[0]['dir'], FILTER_SANITIZE_STRING));
236
 
237
                $fields =  ['uuid', 'first_name', 'last_name', 'email'];
238
                $order_field = isset($fields[$order_field]) ? $fields[$order_field] : 'first_name';
239
 
240
                if(!in_array($order_direction, ['ASC', 'DESC'])) {
241
                    $order_direction = 'ASC';
242
                }
243
 
244
                $acl = $this->getEvent()->getViewModel()->getVariable('acl');
245
                $allowRevoke = $acl->isAllowed($currentUser->usertype_id, 'microlearning/access-for-students/revoke');
246
                $allowUnlimit = $acl->isAllowed($currentUser->usertype_id, 'microlearning/access-for-students/unlimit');
247
                $allowCancel = $acl->isAllowed($currentUser->usertype_id, 'microlearning/access-for-students/cancel');
248
                $allowReactive = $acl->isAllowed($currentUser->usertype_id, 'microlearning/access-for-students/reactive');
249
 
250
                $queryMapper = QueryMapper::getInstance($this->adapter);
251
                $sql = $queryMapper->getSql();
252
                $select = $sql->select();
253
                $select->columns(['access', 'paid_from', 'paid_to', 'added_on', 'updated_on']);
254
                $select->from(['tb1' => CompanyMicrolearningCapsuleUserMapper::_TABLE] );
255
                $select->join(['tb2' => UserMapper::_TABLE], 'tb1.user_id = tb2.id', ['uuid', 'first_name', 'last_name', 'email']);
256
                $select->where->equalTo('tb1.company_id', $capsule->company_id);
257
                $select->where->equalTo('tb1.topic_id', $capsule->topic_id);
258
                $select->where->equalTo('tb1.capsule_id', $capsule->id);
259
 
260
                if($search) {
261
                    $select->where->nest()
262
                    ->like('first_name', '%' . $search . '%')
263
                    ->or->like('last_name', '%' . $search . '%')
264
                    ->or->like('email', '%' . $search . '%')
265
                    ->unnest();
266
 
267
                }
268
 
269
 
270
                $select->order($order_field . ' ' . $order_direction);
271
 
272
                $hydrator   = new ArraySerializableHydrator();
273
                $resultset  = new HydratingResultSet($hydrator);
274
 
275
                $adapter = new DbSelect($select, $sql, $resultset);
276
                $paginator = new Paginator($adapter);
277
                $paginator->setItemCountPerPage($records_x_page);
278
                $paginator->setCurrentPageNumber($page);
279
 
280
 
281
                $items = [ ];
282
                $records = $paginator->getCurrentItems();
283
                foreach($records as $record)
284
                {
285
                    $params = [
286
                        'topic_uuid' => $topic->uuid,
287
                        'capsule_uuid' => $capsule->uuid,
288
                        'user_uuid' => $record['uuid']
289
                    ];
290
 
291
                    $actions = [];
292
 
293
 
294
 
295
                    switch($record['access'])
296
                    {
297
                        case CompanyMicrolearningCapsuleUser::ACCESS_UNLIMITED :
298
                            $actions['link_revoke'] = $allowRevoke ? $this->url()->fromRoute('microlearning/access-for-students/revoke', $params) : '';
299
                            $details['access'] = 'LABEL_UNLIMIT';
300
                            break;
301
 
302
                        case CompanyMicrolearningCapsuleUser::ACCESS_REVOKE :
303
                            $actions['link_unlimit'] = $allowUnlimit ? $this->url()->fromRoute('microlearning/access-for-students/unlimit', $params) : '';
304
                            $details['access'] = 'LABEL_REVOKED';
305
                            break;
306
 
307
                        case CompanyMicrolearningCapsuleUser::ACCESS_PAY_PERIOD :
308
                            $actions['link_cancel'] = $allowCancel ? $this->url()->fromRoute('microlearning/access-for-students/cancel', $params) : '';
309
 
310
                            $dt_paid_from = \DateTime::createFromFormat('Y-m-d', $record['paid_from']);
311
                            $dt_paid_to = \DateTime::createFromFormat('Y-m-d', $record['paid_to']);
312
 
313
                            $details['access'] = 'LABEL_PAY_PERIOD';
314
                            $details['paid_from'] = $dt_paid_from->format('d/m/Y');
315
                            $details['paid_to'] = $dt_paid_to->format('d/m/Y');
316
                            break;
317
 
318
                        case CompanyMicrolearningCapsuleUser::ACCESS_SUPENDED :
319
                            $dt_paid_from = \DateTime::createFromFormat('Y-m-d', $record['paid_from']);
320
                            $dt_paid_to = \DateTime::createFromFormat('Y-m-d', $record['paid_to']);
321
 
322
                            $details['access'] = 'LABEL_SUSPENDED';
323
                            $details['paid_from'] = $dt_paid_from->format('d/m/Y');
324
                            $details['paid_to'] = $dt_paid_to->format('d/m/Y');
325
                            break;
326
 
327
                        case CompanyMicrolearningCapsuleUser::ACCESS_CANCELLED :
328
 
329
                            $date = date('Y-m-d');
330
                            if($allowCancel && $record['paid_from'] <= $date && $record['paid_to'] >= $date) {
331
                                $actions['link_reactive'] = $allowReactive ? $this->url()->fromRoute('microlearning/access-for-students/reactive', $params) : '';
332
                            }
333
 
334
                            $dt_paid_from = \DateTime::createFromFormat('Y-m-d', $record['paid_from']);
335
                            $dt_paid_to = \DateTime::createFromFormat('Y-m-d', $record['paid_to']);
336
 
337
                            $details['access'] = 'LABEL_CANCELLED';
338
                            $details['paid_from'] = $dt_paid_from->format('d/m/Y');
339
                            $details['paid_to'] = $dt_paid_to->format('d/m/Y');
340
                            break;
341
 
342
                    }
343
 
344
                    $dt_added_on = \DateTime::createFromFormat('Y-m-d H:i:s', $record['added_on']);
345
                    $details['added_on'] = $dt_added_on->format('d/m/Y h:i a');
346
 
347
                    $dt_updated_on = \DateTime::createFromFormat('Y-m-d H:i:s', $record['updated_on']);
348
                    $details['updated_on'] = $dt_updated_on->format('d/m/Y h:i a');
349
 
350
                    $item = [
351
                        'uuid' => $record['uuid'],
352
                        'first_name' => $record['first_name'],
353
                        'last_name' => $record['last_name'],
354
                        'email' => $record['email'],
355
                        'details' => $details,
356
                        'actions' => $actions
357
                    ];
358
 
359
 
360
                    array_push($items, $item);
361
 
362
 
363
                }
364
 
365
                $data['items'] = $items;
366
                $data['total'] = $paginator->getTotalItemCount();
367
 
368
 
369
                return new JsonModel([
370
                    'success' => true,
371
                    'data' => $data
372
                ]);
373
            } else {
374
                $topicMapper = CompanyMicrolearningTopicMapper::getInstance($this->adapter);
375
                $topics = $topicMapper->fetchAllByCompanyId($currentCompany->id);
376
 
377
                if($topics) {
378
                    $topic_id = $topics[0]->id;
379
                }  else {
380
                    $topic_id = 0;
381
                }
382
 
383
 
384
                $form = new TopicCapsuleForm($this->adapter, $currentCompany->id, $topic_id);
15355 efrain 385
                $formPushNotification = new PushMicrolearningNotificationForm($this->adapter, $currentCompany->id);
1 www 386
                $formCapsuleCustomer = new CapsuleCustomerUploadForm();
387
 
388
 
389
 
390
                $this->layout()->setTemplate('layout/layout-backend');
391
                $viewModel = new ViewModel();
392
                $viewModel->setTemplate('leaders-linked/microlearning-access-for-students/index.phtml');
393
                $viewModel->setVariables([
394
                    'form' => $form,
395
                    'formPushNotification' => $formPushNotification,
396
                    'formCapsuleCustomer' => $formCapsuleCustomer
397
                ]);
398
 
399
                return $viewModel ;
400
            }
401
 
402
        } else {
403
            return new JsonModel([
404
                'success' => false,
405
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
187 efrain 406
            ]);
1 www 407
        }
408
    }
409
 
410
 
411
 
412
 
413
    public function revokeAction()
414
    {
415
        $request = $this->getRequest();
416
 
417
        $currentUserPlugin = $this->plugin('currentUserPlugin');
418
        $currentUser    = $currentUserPlugin->getUser();
419
        $currentCompany = $currentUserPlugin->getCompany();
420
 
421
        $request    = $this->getRequest();
422
        $topic_uuid     = $this->params()->fromRoute('topic_uuid');
423
        $capsule_uuid   = $this->params()->fromRoute('capsule_uuid');
424
        $user_uuid   = $this->params()->fromRoute('user_uuid');
425
 
426
 
427
        $topicMapper = CompanyMicrolearningTopicMapper::getInstance($this->adapter);
428
        $topic = $topicMapper->fetchOneByUuid($topic_uuid);
429
        if(!$topic) {
430
            return new JsonModel([
431
                'success'   => false,
432
                'data'   => 'ERROR_TOPIC_NOT_FOUND'
433
            ]);
434
        }
435
 
436
 
437
 
438
        if($topic->company_id != $currentCompany->id) {
439
            return new JsonModel([
440
                'success'   => false,
441
                'data'   => 'ERROR_UNAUTHORIZED'
442
            ]);
443
        }
444
 
445
        $capsuleMapper = CompanyMicrolearningCapsuleMapper::getInstance($this->adapter);
446
        $capsule = $capsuleMapper->fetchOneByUuid($capsule_uuid);
447
        if(!$capsule) {
448
            return new JsonModel([
449
                'success'   => false,
450
                'data'   => 'ERROR_CAPSULE_NOT_FOUND'
451
            ]);
452
        }
453
 
454
 
455
        if($capsule->topic_id != $topic->id) {
456
            return new JsonModel([
457
                'success'   => false,
458
                'data'   => 'ERROR_UNAUTHORIZED'
459
            ]);
460
        }
461
 
462
        $userMapper = UserMapper::getInstance($this->adapter);
463
        $user = $userMapper->fetchOneByUuid($user_uuid);
464
 
465
        if(!$user) {
466
            return new JsonModel([
467
                'success'   => false,
468
                'data'   => 'ERROR_USER_NOT_FOUND'
469
            ]);
470
        }
471
 
472
        $capsuleUserMapper = CompanyMicrolearningCapsuleUserMapper::getInstance($this->adapter);
473
        $capsuleUser = $capsuleUserMapper->fetchOneByUserIdAndCapsuleId($user->id, $capsule->id);
474
        if(!$capsuleUser) {
475
            return new JsonModel([
476
                'success'   => false,
477
                'data'   => 'ERROR_UNAUTHORIZED'
478
            ]);
479
        }
480
 
481
        if($request->isPost()) {
482
 
483
 
484
            if($capsuleUser->access != CompanyMicrolearningCapsuleUser::ACCESS_UNLIMITED) {
485
                return new JsonModel([
486
                    'success'   => false,
487
                    'data'   => 'ERROR_USER_ACCESS_CANNT_BE_REVOKE'
488
                ]);
489
            }
490
            $capsuleUser->access = CompanyMicrolearningCapsuleUser::ACCESS_REVOKE;
491
            if($capsuleUserMapper->update($capsuleUser)) {
492
 
493
                $capsuleUser = $capsuleUserMapper->fetchOne($capsuleUser->id);
494
                if($capsuleUser) {
495
                    $companyMicrolearningUserMapper = CompanyMicrolearningUserMapper::getInstance($this->adapter);
496
                    $companyMicrolearningUser = $companyMicrolearningUserMapper->fetchOneByUserIdAndCompanyId($capsuleUser->user_id, $capsuleUser->company_id);
497
                    if($companyMicrolearningUser) {
498
                        $companyMicrolearningUser->updated_on = $capsuleUser->updated_on;
499
 
500
                        $companyMicrolearningUserMapper->update($companyMicrolearningUser);
501
 
502
                    } else {
503
                        $companyMicrolearningUser = new CompanyMicrolearningUser();
504
                        $companyMicrolearningUser->company_id = $capsuleUser->company_id;
505
                        $companyMicrolearningUser->user_id = $capsuleUser->user_id;
506
                        $companyMicrolearningUser->added_on = $capsuleUser->added_on;
507
                        $companyMicrolearningUser->updated_on = $capsuleUser->updated_on;
508
 
509
                        $companyMicrolearningUserMapper->insert($companyMicrolearningUser);
510
                    }
511
                }
512
 
513
                return new JsonModel([
514
                    'success' => true,
515
                    'data' => 'LABEL_USER_ACCESS_HAS_BEEN_REVOKE'
516
                ]);
517
 
518
            } else {
519
 
520
                return new JsonModel([
521
                    'success'   => false,
522
                    'data'      => $capsuleUserMapper->getError()
523
                ]);
524
            }
525
        }
526
 
527
        return new JsonModel([
528
            'success' => false,
529
            'data' => 'ERROR_METHOD_NOT_ALLOWED'
530
        ]);
531
    }
532
 
533
    public function unlimitAction()
534
    {
535
        $request = $this->getRequest();
536
 
537
        $currentUserPlugin = $this->plugin('currentUserPlugin');
538
        $currentUser    = $currentUserPlugin->getUser();
539
        $currentCompany = $currentUserPlugin->getCompany();
540
 
541
        $request    = $this->getRequest();
542
        $topic_uuid     = $this->params()->fromRoute('topic_uuid');
543
        $capsule_uuid   = $this->params()->fromRoute('capsule_uuid');
544
        $user_uuid   = $this->params()->fromRoute('user_uuid');
545
 
546
 
547
        $topicMapper = CompanyMicrolearningTopicMapper::getInstance($this->adapter);
548
        $topic = $topicMapper->fetchOneByUuid($topic_uuid);
549
        if(!$topic) {
550
            return new JsonModel([
551
                'success'   => false,
552
                'data'   => 'ERROR_TOPIC_NOT_FOUND'
553
            ]);
554
        }
555
 
556
 
557
 
558
        if($topic->company_id != $currentCompany->id) {
559
            return new JsonModel([
560
                'success'   => false,
561
                'data'   => 'ERROR_UNAUTHORIZED'
562
            ]);
563
        }
564
 
565
        $capsuleMapper = CompanyMicrolearningCapsuleMapper::getInstance($this->adapter);
566
        $capsule = $capsuleMapper->fetchOneByUuid($capsule_uuid);
567
        if(!$capsule) {
568
            return new JsonModel([
569
                'success'   => false,
570
                'data'   => 'ERROR_CAPSULE_NOT_FOUND'
571
            ]);
572
        }
573
 
574
 
575
        if($capsule->topic_id != $topic->id) {
576
            return new JsonModel([
577
                'success'   => false,
578
                'data'   => 'ERROR_UNAUTHORIZED'
579
            ]);
580
        }
581
 
582
        $userMapper = UserMapper::getInstance($this->adapter);
583
        $user = $userMapper->fetchOneByUuid($user_uuid);
584
 
585
        if(!$user) {
586
            return new JsonModel([
587
                'success'   => false,
588
                'data'   => 'ERROR_USER_NOT_FOUND'
589
            ]);
590
        }
591
 
592
        $capsuleUserMapper = CompanyMicrolearningCapsuleUserMapper::getInstance($this->adapter);
593
        $capsuleUser = $capsuleUserMapper->fetchOneByUserIdAndCapsuleId($user->id, $capsule->id);
594
        if(!$capsuleUser) {
595
            return new JsonModel([
596
                'success'   => false,
597
                'data'   => 'ERROR_UNAUTHORIZED'
598
            ]);
599
        }
600
 
601
        if($request->isPost()) {
602
 
603
 
604
            if($capsuleUser->access != CompanyMicrolearningCapsuleUser::ACCESS_REVOKE) {
605
                return new JsonModel([
606
                    'success'   => false,
607
                    'data'   => 'ERROR_USER_ACCESS_CANNT_BE_UNLIMIT'
608
                ]);
609
            }
610
            $capsuleUser->access = CompanyMicrolearningCapsuleUser::ACCESS_UNLIMITED;
611
            if($capsuleUserMapper->update($capsuleUser)) {
612
 
613
                $capsuleUser = $capsuleUserMapper->fetchOne($capsuleUser->id);
614
                if($capsuleUser) {
615
                    $companyMicrolearningUserMapper = CompanyMicrolearningUserMapper::getInstance($this->adapter);
616
                    $companyMicrolearningUser = $companyMicrolearningUserMapper->fetchOneByUserIdAndCompanyId($capsuleUser->user_id, $capsuleUser->company_id);
617
                    if($companyMicrolearningUser) {
618
                        $companyMicrolearningUser->updated_on = $capsuleUser->updated_on;
619
 
620
                        $companyMicrolearningUserMapper->update($companyMicrolearningUser);
621
 
622
                    } else {
623
                        $companyMicrolearningUser = new CompanyMicrolearningUser();
624
                        $companyMicrolearningUser->company_id = $capsuleUser->company_id;
625
                        $companyMicrolearningUser->user_id = $capsuleUser->user_id;
626
                        $companyMicrolearningUser->added_on = $capsuleUser->added_on;
627
                        $companyMicrolearningUser->updated_on = $capsuleUser->updated_on;
628
 
629
                        $companyMicrolearningUserMapper->insert($companyMicrolearningUser);
630
                    }
631
                }
632
 
633
                return new JsonModel([
634
                    'success' => true,
635
                    'data' => 'LABEL_USER_ACCESS_HAS_BEEN_UNLIMITED'
636
                ]);
637
 
638
            } else {
639
 
640
                return new JsonModel([
641
                    'success'   => false,
642
                    'data'      => $capsuleUserMapper->getError()
643
                ]);
644
            }
645
        }
646
 
647
        return new JsonModel([
648
            'success' => false,
649
            'data' => 'ERROR_METHOD_NOT_ALLOWED'
650
        ]);
651
    }
652
 
653
    public function uploadAction()
654
    {
655
        $request = $this->getRequest();
656
 
657
        $currentUserPlugin = $this->plugin('currentUserPlugin');
658
        $currentUser    = $currentUserPlugin->getUser();
659
        $currentCompany = $currentUserPlugin->getCompany();
660
 
15394 efrain 661
        $currentNetworkPlugin = $this->plugin('currentNetworkPlugin');
662
        $currentNetwork = $currentNetworkPlugin->getNetwork();
663
 
1 www 664
        $request    = $this->getRequest();
665
        $topic_uuid     = $this->params()->fromRoute('topic_uuid');
666
        $capsule_uuid   = $this->params()->fromRoute('capsule_uuid');
667
 
668
 
669
        $topicMapper = CompanyMicrolearningTopicMapper::getInstance($this->adapter);
670
        $topic = $topicMapper->fetchOneByUuid($topic_uuid);
671
        if(!$topic) {
672
            return new JsonModel([
673
                'success'   => false,
674
                'data'   => 'ERROR_TOPIC_NOT_FOUND'
675
            ]);
676
        }
677
 
678
 
679
 
680
        if($topic->company_id != $currentCompany->id) {
681
            return new JsonModel([
682
                'success'   => false,
683
                'data'   => 'ERROR_UNAUTHORIZED'
684
            ]);
685
        }
686
 
687
        $capsuleMapper = CompanyMicrolearningCapsuleMapper::getInstance($this->adapter);
688
        $capsule = $capsuleMapper->fetchOneByUuid($capsule_uuid);
689
        if(!$capsule) {
690
            return new JsonModel([
691
                'success'   => false,
692
                'data'   => 'ERROR_CAPSULE_NOT_FOUND'
693
            ]);
694
        }
695
 
696
 
697
        if($capsule->topic_id != $topic->id) {
698
            return new JsonModel([
699
                'success'   => false,
700
                'data'   => 'ERROR_UNAUTHORIZED'
701
            ]);
702
        }
703
 
704
 
705
 
706
        if($request->isPost()) {
707
 
708
            $step = filter_var( $this->params()->fromPost('step'), FILTER_SANITIZE_STRING);
709
            if($step == 'validation') {
15455 efrain 710
 
711
 
1 www 712
                $userMapper = UserMapper::getInstance($this->adapter);
713
                $capsuleUserMapper = CompanyMicrolearningCapsuleUserMapper::getInstance($this->adapter);
714
 
715
                $form = new  CapsuleCustomerUploadForm();
716
                $dataPost = array_merge($request->getPost()->toArray(), $request->getFiles()->toArray());
717
 
718
                $form->setData($dataPost);
719
 
720
                if($form->isValid()) {
721
 
722
                    $file = $_FILES['file'];
723
                    $tmp_filename = $file['tmp_name'];
724
                    $final_filename =  'data/' . $file['name'];
725
 
726
                    if(!move_uploaded_file($tmp_filename, $final_filename)) {
727
                        return new JsonModel([
728
                            'success' => false,
729
                            'data' => 'ERROR_UPLOAD_FILE'
730
                        ]);
731
                    }
732
 
15455 efrain 733
 
1 www 734
 
735
                    $users = [];
736
 
737
 
738
                    $spreadsheet = IOFactory::load($final_filename);
739
                    $records = $spreadsheet->getActiveSheet()->toArray(null, true, true, true);
740
 
741
                    $emails = [];
742
 
743
                    foreach($records as $record)
744
                    {
15452 efrain 745
                        /*
746
                        A = Nombre
747
                        B = Apellido
748
                        C = Email
749
                        D = Contraseña
750
                        E = Empresa
751
                        F = Función
752
                        G = Grupo
753
                        H = Institución
754
                        I = Programa
755
                        J = Socio
756
                        K = Sector
757
                        L = Tipo de Estudiante
758
                        M = País
759
                        N = Es adulto
760
                        */
1 www 761
 
762
 
763
                        $first_name = trim(filter_var($record['A'], FILTER_SANITIZE_STRING));
764
                        $last_name = trim(filter_var($record['B'], FILTER_SANITIZE_STRING));
15394 efrain 765
                        $email = trim(filter_var($record['C'], FILTER_SANITIZE_EMAIL));
1 www 766
                        $password = trim(filter_var($record['D'], FILTER_SANITIZE_STRING));
767
 
15452 efrain 768
                        $company =  isset($record['E']) ? trim(filter_var($record['E'], FILTER_SANITIZE_STRING)) : '';
769
                        $function = isset($record['F']) ? trim(filter_var($record['F'], FILTER_SANITIZE_STRING)) : '';
770
                        $group = isset($record['G']) ? trim(filter_var($record['G'], FILTER_SANITIZE_STRING)) : '';
771
                        $institution = isset($record['H']) ? trim(filter_var($record['H'], FILTER_SANITIZE_STRING)) : '';
772
                        $program = isset($record['I']) ? trim(filter_var($record['I'], FILTER_SANITIZE_STRING)) : '';
773
                        $partner = isset($record['J']) ? trim(filter_var($record['J'], FILTER_SANITIZE_STRING)) : '';
774
                        $sector = isset($record['K']) ? trim(filter_var($record['K'], FILTER_SANITIZE_STRING)) : '';
775
                        $studentType = isset($record['L']) ? trim(filter_var($record['L'], FILTER_SANITIZE_STRING)) : '';
776
                        $country =  isset($record['M']) ? trim(filter_var($record['M'], FILTER_SANITIZE_STRING)) : '';
777
                        $isAdult = isset($record['N']) ? trim(filter_var($record['N'], FILTER_SANITIZE_STRING)) : '';
778
 
15394 efrain 779
 
780
 
129 efrain 781
                        //||  empty($password)
782
                        if(empty($first_name) || empty($last_name) || !filter_var($email, FILTER_VALIDATE_EMAIL) ) {
1 www 783
                            continue;
784
                        }
785
 
786
                        if(!in_array($email, $emails)) {
787
 
788
                            $user = $userMapper->fetchOneByEmail($email);
789
                            if($user) {
790
                                $assigned_capsules =  $capsuleUserMapper->fetchCountByCompanyIdAndTopicIdAndUserId($topic->company_id, $topic->id, $user->id);
791
                            } else {
792
                                $assigned_capsules = 0;
793
                            }
794
 
795
                            array_push($emails, $email);
796
                            array_push($users, [
797
                                'first_name' => $first_name,
798
                                'last_name' => $last_name,
799
                                'password'  => $password,
800
                                'email' => $email,
801
                                'assigned_capsules' => $assigned_capsules,
15452 efrain 802
                                'company' => $company,
803
                                'function' => $function,
804
                                'group' => $group,
805
                                'institution' => $institution,
806
                                'program' => $program,
807
                                'partner' => $partner,
808
                                'sector' => $sector,
809
                                'studentType' => $studentType,
810
                                'country' => $country,
811
                                'isAdult' => $isAdult,
1 www 812
                            ]);
813
                        }
814
 
815
 
816
 
817
 
818
 
819
                    }
15457 efrain 820
 
1 www 821
 
822
                    $key = md5($currentUser->id . '-' . $topic->uuid . '-' . $capsule->uuid);
823
                    $this->cache->setItem($key, serialize($users));
824
 
825
                    return new JsonModel([
826
                        'success' => true,
827
                        'data' => [
828
                            'key' => $key,
829
                            'topic' => $topic->name,
830
                            'capsule' => $capsule->name,
831
                            'items' => $users,
832
                        ]
833
                    ]);
834
 
835
 
836
 
837
                } else {
838
                    $messages = [];
839
                    $form_messages = (array) $form->getMessages();
840
                    foreach($form_messages  as $fieldname => $field_messages)
841
                    {
842
 
843
                        $messages[$fieldname] = array_values($field_messages);
844
                    }
845
 
846
                    return new JsonModel([
847
                        'success'   => false,
848
                        'data'   => $messages
849
                    ]);
850
                }
851
            } else if($step == 'process') {
852
 
853
                $key = filter_var( $this->params()->fromPost('key'), FILTER_SANITIZE_STRING);
854
                if(!$key) {
855
                    return new JsonModel([
856
                        'success' => false,
857
                        'data' => 'ERROR_CACHE_KEY_EMPTY'
858
                    ]);
859
                }
860
 
861
                $value = $this->cache->getItem($key);
862
                if(!$value) {
863
 
864
                    return new JsonModel([
865
                        'success' => false,
866
                        'data' => 'ERROR_CACHE_NOT_FOUND'
867
                    ]);
868
                }
869
 
870
                $records = unserialize($value);
871
                if(!$records) {
872
                    return new JsonModel([
873
                        'success' => false,
874
                        'data' => 'ERROR_CACHE_INVALID'
875
                    ]);
876
                }
877
 
15455 efrain 878
 
15453 efrain 879
                $networkMapper = NetworkMapper::getInstance($this->adapter);
880
                $companyMapper = CompanyMapper::getInstance($this->adapter);
881
                $companyFollowerMapper = CompanyFollowerMapper::getInstance($this->adapter);
882
 
883
                $connectionMapper = ConnectionMapper::getInstance($this->adapter);
1 www 884
                $userMapper = UserMapper::getInstance($this->adapter);
885
                $userPasswordMapper = UserPasswordMapper::getInstance($this->adapter);
886
                $capsuleUserMapper = CompanyMicrolearningCapsuleUserMapper::getInstance($this->adapter);
887
 
888
                $companyMicrolearningExtendUserMapper = CompanyMicrolearningExtendUserMapper::getInstance($this->adapter);
889
                $companyMicrolearningExtendUserCompanyMapper = CompanyMicrolearningExtendUserCompanyMapper::getInstance($this->adapter);
890
                $companyMicrolearningExtendUserFunctionMapper = CompanyMicrolearningExtendUserFunctionMapper::getInstance($this->adapter);
891
                $companyMicrolearningExtendUserGroupMapper = CompanyMicrolearningExtendUserGroupMapper::getInstance($this->adapter);
892
                $companyMicrolearningExtendUserInstitutionMapper = CompanyMicrolearningExtendUserInstitutionMapper::getInstance($this->adapter);
893
                $companyMicrolearningExtendUserProgramMapper = CompanyMicrolearningExtendUserProgramMapper::getInstance($this->adapter);
894
                $companyMicrolearningExtendUserPartnerMapper = CompanyMicrolearningExtendUserPartnerMapper::getInstance($this->adapter);
895
                $companyMicrolearningExtendUserSectorMapper = CompanyMicrolearningExtendUserSectorMapper::getInstance($this->adapter);
896
                $companyMicrolearningExtendUserStudentTypeMapper = CompanyMicrolearningExtendUserStudentTypeMapper::getInstance($this->adapter);
15394 efrain 897
                $companyMicrolearningExtendUserCountryMapper = CompanyMicrolearningExtendUserCountryMapper::getInstance($this->adapter);
4 efrain 898
 
1 www 899
 
15453 efrain 900
                $networkDefault = $networkMapper->fetchOneByDefault();
901
 
902
                //print_r($networkDefault);
903
 
904
                $userDefaultForConnection = $userMapper->fetchOneDefaultForConnection();
905
 
906
                //print_r($userDefaultForConnection);
907
 
908
 
909
                $companyForFollower = $companyMapper->fetchOneDefaultForFollowers();
910
                //print_r($companyForFollower);
15457 efrain 911
 
4 efrain 912
 
15457 efrain 913
                $users_processed = 0;
1 www 914
                $users_assigned = 0;
915
                $user_ids = [];
916
                foreach($records as $record)
917
                {
918
                    $first_name = $record['first_name'];
919
                    $last_name = $record['last_name'];
920
                    $password = $record['password'];
921
                    $email = $record['email'];
922
 
923
 
15452 efrain 924
                    $company = $record['company'];
925
                    $function = $record['function'];
926
                    $group = $record['group'];
927
                    $institution = $record['institution'];
928
                    $program = $record['program'];
929
                    $partner = $record['partner'];
930
                    $sector = $record['sector'];
931
                    $studentType = $record['studentType'];
932
                    $country = $record['country'];
15453 efrain 933
                    $isAdult = strtolower(trim( $record['isAdult'])) == User::IS_ADULT_YES;
934
 
935
 
1 www 936
                    $user = $userMapper->fetchOneByEmail($email);
937
                    if(!$user) {
938
 
939
 
129 efrain 940
                        if($password) {
941
                            $password_hash = password_hash($password, PASSWORD_DEFAULT);
942
 
943
                            $user = new User();
944
 
15452 efrain 945
                            $user->network_id = $currentNetwork->id;
129 efrain 946
                            $user->blocked = User::BLOCKED_NO;
947
                            $user->email_verified = User::EMAIL_VERIFIED_YES;
948
                            $user->email = $email;
949
                            $user->first_name = $first_name;
950
                            $user->last_name = $last_name;
951
                            $user->password = $password_hash;
952
                            $user->login_attempt = 0;
953
                            $user->usertype_id = UserType::USER;
954
                            $user->status = User::STATUS_ACTIVE;
15453 efrain 955
                            $user->is_adult = $isAdult ? User::IS_ADULT_YES : User::IS_ADULT_NO;
129 efrain 956
 
957
                            $result = $userMapper->insert($user);
958
                            if($result) {
959
                                $userPassword = new UserPassword();
960
                                $userPassword->user_id = $user->id;
961
                                $userPassword->password = $password_hash;
962
                                $userPasswordMapper->insert($userPassword);
963
                            } else {
964
                                continue;
965
                            }
15453 efrain 966
 
129 efrain 967
                        }
968
                    } else {
15453 efrain 969
                        $user->is_adult = $isAdult ? User::IS_ADULT_YES : User::IS_ADULT_NO;
129 efrain 970
                        if($user->email_verified == User::EMAIL_VERIFIED_NO || $user->status != User::STATUS_ACTIVE) {
971
                            $user->email_verified = User::EMAIL_VERIFIED_YES;
972
                            $user->status != User::STATUS_ACTIVE;
973
 
15453 efrain 974
 
129 efrain 975
                        }
15453 efrain 976
                        if(!$userMapper->update($user)) {
977
                            continue;
978
                        }
129 efrain 979
 
980
 
1 www 981
                    }
982
 
15453 efrain 983
 
984
                    $user_id_in_default_network = 0;
985
                    if($user->is_adult == User::IS_ADULT_YES) {
986
 
987
                        if($currentNetwork->default == Network::DEFAULT_YES) {
988
 
989
                            $user_id_in_default_network = $user->id;
990
 
991
 
992
 
993
                        } else {
994
 
995
                            $userInDefaultNetwork = $userMapper->fetchOneByEmailAndNetworkId($user->email, $networkDefault->id);
996
                            if($userInDefaultNetwork) {
997
                                $user_id_in_default_network = $userInDefaultNetwork->id;
998
 
999
                                if($userInDefaultNetwork->email_verified == User::EMAIL_VERIFIED_NO || $userInDefaultNetwork->status != User::STATUS_ACTIVE) {
1000
                                    $userInDefaultNetwork->email_verified = User::EMAIL_VERIFIED_YES;
1001
                                    $userInDefaultNetwork->status != User::STATUS_ACTIVE;
1002
 
1003
                                    if(!$userMapper->update($userInDefaultNetwork)) {
1004
                                        continue;
1005
                                    }
1006
                                }
1007
 
1008
 
1009
                            } else {
1010
                                $userInDefaultNetwork = new User();
1011
                                $userInDefaultNetwork->network_id = $networkDefault->id;
1012
                                $userInDefaultNetwork->blocked = User::BLOCKED_NO;
1013
                                $userInDefaultNetwork->email_verified = User::EMAIL_VERIFIED_YES;
1014
                                $userInDefaultNetwork->email = $email;
1015
                                $userInDefaultNetwork->first_name = $first_name;
1016
                                $userInDefaultNetwork->last_name = $last_name;
1017
                                $userInDefaultNetwork->password = $password_hash;
1018
                                $userInDefaultNetwork->login_attempt = 0;
1019
                                $userInDefaultNetwork->usertype_id = UserType::USER;
1020
                                $userInDefaultNetwork->status = User::STATUS_ACTIVE;
1021
                                $userInDefaultNetwork->is_adult = $isAdult == User::IS_ADULT_YES;
1022
                                $result = $userMapper->insert($userInDefaultNetwork);
1023
                                if($result) {
1024
                                    $user_id_in_default_network = $userInDefaultNetwork->id;
1025
 
1026
 
1027
                                    $userPassword = new UserPassword();
1028
                                    $userPassword->user_id = $userInDefaultNetwork->id;
1029
                                    $userPassword->password = $password_hash;
1030
                                    $userPasswordMapper->insert($userPassword);
1031
                                }
1032
 
1033
                            }
1034
 
1035
 
1036
                        }
1037
                    }
1038
 
1039
                    if($user_id_in_default_network) {
1040
 
1041
                        if($userDefaultForConnection) {
1042
 
1043
                            $connection = $connectionMapper->fetchOneByUserId1AndUserId2($userDefaultForConnection->id, $user_id_in_default_network);
1044
                            if($connection) {
1045
                                if($connection->status != Connection::STATUS_ACCEPTED) {
1046
                                    $connection->status = Connection::STATUS_ACCEPTED;
1047
                                    $connectionMapper->update($connection);
1048
 
1049
                                }
1050
 
1051
 
1052
                            } else {
1053
                                $connection = new Connection();
1054
                                $connection->request_to = $user_id_in_default_network;
1055
                                $connection->request_from = $userDefaultForConnection->id;
1056
                                $connection->status = Connection::STATUS_ACCEPTED;
1057
                                $connectionMapper->insert($connection);
1058
                            }
1059
                        }
1060
 
1061
                        if($companyForFollower) {
1062
                            $companyFollower = $companyFollowerMapper->fetchOneByCompanyIdAndUserId($companyForFollower->id, $user_id_in_default_network);
1063
                            if(!$companyFollower) {
1064
                                $companyFollower = new CompanyFollower();
1065
                                $companyFollower->company_id = $companyForFollower->id;
1066
                                $companyFollower->follower_id = $user_id_in_default_network;
1067
 
1068
                                $companyFollowerMapper->insert($companyFollower);
1069
 
1070
 
1071
                            }
1072
                        }
1073
 
1074
 
1075
                    }
1076
 
1077
 
1 www 1078
                    if(!in_array($user->id, $user_ids)) {
1079
                        array_push($user_ids, $user->id);
1080
                    }
1081
 
4 efrain 1082
                    /*
1083
                    echo '$filterCompany = ' . $filterCompany . PHP_EOL;
1084
                    echo '$filterFunctio = ' . $filterFunction . PHP_EOL;
1085
                    echo '$filterGroup = ' . $filterGroup . PHP_EOL;
1086
                    echo '$filterInstitution = ' . $filterInstitution . PHP_EOL;
1087
                    echo '$filterPartner = ' . $filterPartner . PHP_EOL;
1088
                    echo '$filterProgram = ' . $filterProgram . PHP_EOL;
1089
                    echo '$filterSector = ' . $filterSector . PHP_EOL;
1090
                    echo '$filterStudentType = ' . $filterStudentType . PHP_EOL;
1091
                  */
1092
 
1093
 
1094
                    $extendUser = $companyMicrolearningExtendUserMapper->fetchOneByCompanyIdAndUserId($currentCompany->id, $user->id);
1095
                    if(!$extendUser) {
1096
                        $extendUser = new CompanyMicrolearningExtendUser();
1097
                        $extendUser->company_id = $currentCompany->id;
1098
                        $extendUser->user_id = $user->id;
1099
                    }
1100
 
1101
 
15452 efrain 1102
                    if($company) {
1103
                        $record = $companyMicrolearningExtendUserCompanyMapper->fetchOneByCompanyIdAndName($currentCompany->id, $company);
4 efrain 1104
 
1105
                        if(!$record) {
1106
                            $record = new CompanyMicrolearningExtendUserCompany();
1107
                            $record->company_id = $currentCompany->id;
15452 efrain 1108
                            $record->name = $company;
1 www 1109
 
4 efrain 1110
                            $companyMicrolearningExtendUserCompanyMapper->insert($record);
1111
                        }
1112
 
1113
 
1114
 
1 www 1115
 
4 efrain 1116
                        if($record->id) {
1117
                            $extendUser->extend_company_id = $record->id;
1118
                        }
1119
                    }
1 www 1120
 
15452 efrain 1121
                    if($function) {
1122
                        $record = $companyMicrolearningExtendUserFunctionMapper->fetchOneByCompanyIdAndName($currentCompany->id, $function);
4 efrain 1123
                        if(!$record) {
1124
                            $record = new CompanyMicrolearningExtendUserFunction();
1125
                            $record->company_id = $currentCompany->id;
15452 efrain 1126
                            $record->name = $function;
1 www 1127
 
4 efrain 1128
                            $companyMicrolearningExtendUserFunctionMapper->insert($record);
1129
                        }
1 www 1130
 
4 efrain 1131
                        if($record->id) {
1132
                            $extendUser->extend_function_id = $record->id;
1133
                        }
1134
                    }
1 www 1135
 
15452 efrain 1136
                    if($group) {
1137
                        $record = $companyMicrolearningExtendUserGroupMapper->fetchOneByCompanyIdAndName($currentCompany->id, $group);
4 efrain 1138
                        if(!$record) {
1139
                            $record = new CompanyMicrolearningExtendUserGroup();
1140
                            $record->company_id = $currentCompany->id;
15452 efrain 1141
                            $record->name = $group;
1 www 1142
 
4 efrain 1143
                            $companyMicrolearningExtendUserGroupMapper->insert($record);
1144
                        }
1 www 1145
 
4 efrain 1146
                        if($record->id) {
1147
                            $extendUser->extend_group_id = $record->id;
1148
                        }
1149
                    }
1 www 1150
 
15452 efrain 1151
                    if($institution) {
1152
                        $record = $companyMicrolearningExtendUserInstitutionMapper->fetchOneByCompanyIdAndName($currentCompany->id, $institution);
4 efrain 1153
                        if(!$record) {
1154
                            $record = new CompanyMicrolearningExtendUserInstitution();
1155
                            $record->company_id = $currentCompany->id;
15452 efrain 1156
                            $record->name = $institution;
1 www 1157
 
4 efrain 1158
                            $companyMicrolearningExtendUserInstitutionMapper->insert($record);
1159
                        }
1 www 1160
 
4 efrain 1161
                        if($record->id) {
1162
                            $extendUser->extend_institution_id = $record->id;
1163
                        }
1164
                    }
1 www 1165
 
15452 efrain 1166
                    if($program) {
1167
                        $record = $companyMicrolearningExtendUserProgramMapper->fetchOneByCompanyIdAndName($currentCompany->id, $program);
4 efrain 1168
                        if(!$record) {
1169
                            $record = new CompanyMicrolearningExtendUserProgram();
1170
                            $record->company_id = $currentCompany->id;
15452 efrain 1171
                            $record->name = $program;
1 www 1172
 
4 efrain 1173
                            $companyMicrolearningExtendUserProgramMapper->insert($record);
1174
                        }
1 www 1175
 
4 efrain 1176
                        if($record->id) {
1177
                            $extendUser->extend_program_id = $record->id;
1178
                        }
1179
                    }
1 www 1180
 
15452 efrain 1181
                    if($partner) {
4 efrain 1182
 
1183
 
15452 efrain 1184
                        $record = $companyMicrolearningExtendUserPartnerMapper->fetchOneByCompanyIdAndName($currentCompany->id, $partner);
4 efrain 1185
                        if(!$record) {
1186
                            $record = new CompanyMicrolearningExtendUserPartner();
1187
                            $record->company_id = $currentCompany->id;
15452 efrain 1188
                            $record->name = $partner;
1 www 1189
 
4 efrain 1190
                            $companyMicrolearningExtendUserPartnerMapper->insert($record);
1191
                        }
1 www 1192
 
4 efrain 1193
                        if($record->id) {
1194
                            $extendUser->extend_partner_id = $record->id;
1195
                        }
1196
                    }
1 www 1197
 
15452 efrain 1198
                    if($sector) {
1199
                        $record = $companyMicrolearningExtendUserSectorMapper->fetchOneByCompanyIdAndName($currentCompany->id, $sector);
4 efrain 1200
                        if(!$record) {
1201
                            $record = new CompanyMicrolearningExtendUserSector();
1202
                            $record->company_id = $currentCompany->id;
15452 efrain 1203
                            $record->name = $sector;
1 www 1204
 
4 efrain 1205
                            $companyMicrolearningExtendUserSectorMapper->insert($record);
1206
                        }
1 www 1207
 
4 efrain 1208
                        if($record->id) {
1209
                            $extendUser->extend_sector_id = $record->id;
1210
                        }
1211
                    }
1 www 1212
 
15452 efrain 1213
                    if($studentType) {
1214
                        $record = $companyMicrolearningExtendUserStudentTypeMapper->fetchOneByCompanyIdAndName($currentCompany->id, $studentType);
4 efrain 1215
                        if(!$record) {
1216
                            $record = new CompanyMicrolearningExtendUserStudentType();
1217
                            $record->company_id = $currentCompany->id;
15452 efrain 1218
                            $record->name = $studentType;
1 www 1219
 
4 efrain 1220
                            $companyMicrolearningExtendUserStudentTypeMapper->insert($record);
1221
                        }
1222
                        if($record->id) {
1223
                            $extendUser->extend_student_type_id = $record->id;
1224
                        }
1225
                    }
1226
 
15452 efrain 1227
                    if($country) {
1228
                        $record = $companyMicrolearningExtendUserCountryMapper->fetchOneByCompanyIdAndName($currentCompany->id, $country);
1229
                        if(!$record) {
1230
                            $record = new CompanyMicrolearningExtendUserCountry();
1231
                            $record->company_id = $currentCompany->id;
1232
                            $record->name = $country;
1233
 
1234
                            $companyMicrolearningExtendUserCountryMapper->insert($record);
1235
                        }
1236
                        if($record->id) {
1237
                            $extendUser->extend_country_id = $record->id;
1238
                        }
1239
                    }
4 efrain 1240
 
1241
 
15452 efrain 1242
 
1243
 
1 www 1244
 
4 efrain 1245
                    if($extendUser->id) {
1246
                       $result =   $companyMicrolearningExtendUserMapper->update($extendUser);
1247
                    } else {
1248
                       $result = $companyMicrolearningExtendUserMapper->insert($extendUser);
1249
                    }
1250
 
1251
 
1252
 
1 www 1253
                }
1254
 
4 efrain 1255
 
15457 efrain 1256
                $users_processed = 0;
1257
                $users_previous = 0;
1 www 1258
                foreach($user_ids as $user_id)
1259
                {
15457 efrain 1260
 
1261
                    $users_processed++;
1 www 1262
                    $capsuleUser = $capsuleUserMapper->fetchOneByUserIdAndCapsuleId($user_id, $capsule->id);
15457 efrain 1263
                    if($capsuleUser) {
1264
                        $users_previous++;
1265
                    } else {
1 www 1266
                        $capsuleUser = new CompanyMicrolearningCapsuleUser();
1267
                        $capsuleUser->company_id = $capsule->company_id;
1268
                        $capsuleUser->topic_id = $capsule->topic_id;
1269
                        $capsuleUser->capsule_id = $capsule->id;
1270
                        $capsuleUser->user_id = $user_id;
1271
                        $capsuleUser->access = CompanyMicrolearningCapsuleUser::ACCESS_UNLIMITED;
1272
 
1273
                        if($capsuleUserMapper->insert($capsuleUser)) {
1274
                            $users_assigned++;
1275
 
1276
 
1277
                            $capsuleUser = $capsuleUserMapper->fetchOne($capsuleUser->id);
1278
                            if($capsuleUser) {
1279
                                $companyMicrolearningUserMapper = CompanyMicrolearningUserMapper::getInstance($this->adapter);
1280
                                $companyMicrolearningUser = $companyMicrolearningUserMapper->fetchOneByUserIdAndCompanyId($capsuleUser->user_id, $capsuleUser->company_id);
1281
                                if($companyMicrolearningUser) {
1282
                                    $companyMicrolearningUser->updated_on = $capsuleUser->updated_on;
1283
 
1284
                                    $companyMicrolearningUserMapper->update($companyMicrolearningUser);
1285
 
1286
                                } else {
1287
                                    $companyMicrolearningUser = new CompanyMicrolearningUser();
1288
                                    $companyMicrolearningUser->company_id = $capsuleUser->company_id;
1289
                                    $companyMicrolearningUser->user_id = $capsuleUser->user_id;
1290
                                    $companyMicrolearningUser->added_on = $capsuleUser->added_on;
1291
                                    $companyMicrolearningUser->updated_on = $capsuleUser->updated_on;
1292
 
1293
                                    $companyMicrolearningUserMapper->insert($companyMicrolearningUser);
1294
                                }
1295
                            }
1296
                        }
1297
 
1298
                    }
1299
 
1300
 
1301
 
1302
                }
1303
 
15457 efrain 1304
                $users_in_the_capsule = $capsuleUserMapper->fetchCountByCompanyIdAndTopicIdAndCapsuleId($capsule->company_id, $capsule->topic_id, $capsule->id);
1305
 
1 www 1306
                return new JsonModel([
1307
                    'success' => true,
1308
                    'data' => [
15457 efrain 1309
                        'users_assigned' => $users_assigned,
1310
                        'users_processed' => $users_processed,
1311
                        'users_in_the_capsule' => $users_in_the_capsule,
1312
                        'users_previous' => $users_previous
1 www 1313
                    ]
1314
                ]);
1315
 
1316
 
1317
 
1318
 
1319
            } else {
1320
                return new JsonModel([
1321
                    'success' => false,
1322
                    'data' => 'ERROR_PARAMETERS_ARE_INVALID'
1323
                ]);
1324
            }
1325
 
1326
 
1327
 
1328
 
1329
        }
1330
 
1331
        return new JsonModel([
1332
            'success' => false,
1333
            'data' => 'ERROR_METHOD_NOT_ALLOWED'
1334
        ]);
1335
    }
1336
 
1337
    public function notificationAction()
1338
    {
1339
        $request = $this->getRequest();
1340
 
1341
        $currentUserPlugin = $this->plugin('currentUserPlugin');
1342
        $currentUser    = $currentUserPlugin->getUser();
1343
        $currentCompany = $currentUserPlugin->getCompany();
1344
 
1345
        $request    = $this->getRequest();
1346
        $topic_uuid     = $this->params()->fromRoute('topic_uuid');
1347
        $capsule_uuid   = $this->params()->fromRoute('capsule_uuid');
1348
 
1349
 
1350
        $topicMapper = CompanyMicrolearningTopicMapper::getInstance($this->adapter);
1351
        $topic = $topicMapper->fetchOneByUuid($topic_uuid);
1352
        if(!$topic) {
1353
            return new JsonModel([
1354
                'success'   => false,
1355
                'data'   => 'ERROR_TOPIC_NOT_FOUND'
1356
            ]);
1357
        }
1358
 
1359
 
1360
 
1361
        if($topic->company_id != $currentCompany->id) {
1362
            return new JsonModel([
1363
                'success'   => false,
1364
                'data'   => 'ERROR_UNAUTHORIZED'
1365
            ]);
1366
        }
1367
 
1368
        $capsuleMapper = CompanyMicrolearningCapsuleMapper::getInstance($this->adapter);
1369
        $capsule = $capsuleMapper->fetchOneByUuid($capsule_uuid);
1370
        if(!$capsule) {
1371
            return new JsonModel([
1372
                'success'   => false,
1373
                'data'   => 'ERROR_CAPSULE_NOT_FOUND'
1374
            ]);
1375
        }
1376
 
1377
 
1378
        if($capsule->topic_id != $topic->id) {
1379
            return new JsonModel([
1380
                'success'   => false,
1381
                'data'   => 'ERROR_UNAUTHORIZED'
1382
            ]);
1383
        }
1384
 
1385
 
1386
        if($request->isPost()) {
1387
            $dataPost = $request->getPost()->toArray();
15390 efrain 1388
            $form = new PushMicrolearningNotificationForm($this->adapter, $currentCompany->id);
1 www 1389
 
1390
            $form->setData($dataPost);
1391
 
1392
            if($form->isValid()) {
1393
                $customer_uuids = $this->params()->fromPost('customer_uuids');
1394
                if(!$customer_uuids) {
1395
                    return new JsonModel([
1396
                        'success' => false,
1397
                        'data' => 'ERROR_NOT_SELECTED_CUSTOMERS'
1398
                    ]);
1399
 
1400
                }
1401
 
1402
                $push_template_uuid = filter_var($form->get('push_template_id')->getValue(), FILTER_SANITIZE_STRING);
1403
                $pushMapper = PushMapper::getInstance($this->adapter);
1404
                $pushTemplateMapper = PushTemplateMapper::getInstance($this->adapter);
1405
                $pushTemplate = $pushTemplateMapper->fetchOneByUuid($push_template_uuid);
1406
 
1407
                if(!$pushTemplate) {
1408
                    return new JsonModel([
1409
                        'success' => false,
1410
                        'data' => 'ERROR_PUSH_TEMPLATE_NOT_FOUND'
1411
                    ]);
1412
                }
1413
 
1414
 
1415
 
1416
                $applicationMapper = ApplicationMapper::getInstance($this->adapter);
1417
                $application = $applicationMapper->fetchOne(Application::TWOGETSKILLS);
1418
 
1419
                $capsuleUserMapper = CompanyMicrolearningCapsuleUserMapper::getInstance($this->adapter);
1420
 
1421
                $push_to_send = 0;
1422
 
1423
 
1424
 
1425
                $userMapper = UserMapper::getInstance($this->adapter);
1426
                $deviceHistoryMapper = DeviceHistoryMapper::getInstance($this->adapter);
1427
                foreach($customer_uuids as $customer_uuid)
1428
                {
1429
 
1430
 
1431
                    $user = $userMapper->fetchOneByUuid($customer_uuid);
1432
                    if(!$user) {
1433
                        continue;
1434
                    }
1435
 
1436
                    $capsuleUser = $capsuleUserMapper->fetchOneByUserIdAndCapsuleId($user->id, $capsule->id);
1437
                    if(!$capsuleUser) {
1438
                        continue;
1439
                    }
1440
 
1441
 
13755 efrain 1442
                    //$token = $deviceHistoryMapper->fetchLastDeviceTokenByApplicationIdAndUserId(Application::TWOGETSKILLS, $user->id);
1443
                    $device = $deviceHistoryMapper->fetchLastDeviceByApplicationIdAndUserId(Application::TWOGETSKILLS, $user->id);
1 www 1444
 
13755 efrain 1445
 
1446
 
1447
                    if($device && $device->token) {
1448
 
1449
                        $key = $application->key;
1450
                        if($device->variant_id) {
1451
 
1452
                            $applicationVariantMapper = ApplicationVariantMapper::getInstance($this->adapter);
1453
                            $applicationVariant = $applicationVariantMapper->fetchOneByApplicationIdAndVariantId($device->application_id, $device->variant_id);
1454
                            if($applicationVariant) {
1455
                                $key = $applicationVariant->key;
1456
                            } else {
1457
                                $applicationVariant = $applicationVariantMapper->fetchOneByApplicationIdAndDefault($device->application_id);
1458
                                if($applicationVariant) {
1459
                                    $key = $applicationVariant->key;
1460
                                }
1461
                            }
1462
 
1463
                        }
1464
 
1 www 1465
                        $push = new Push();
1466
                        $push->status = Push::STATUS_PENDING;
1467
                        $push->data = json_encode([
1468
                            'server' => [
13755 efrain 1469
                                'key' => $key,
1 www 1470
                            ],
1471
                            'push' => [
1472
                                'registration_ids'   => [
13755 efrain 1473
                                    $device->token,
1 www 1474
                                ],
1475
                                'notification' => [
1476
                                    'body' =>  $pushTemplate->body,
1477
                                    'title' => $pushTemplate->title,
1478
                                    'vibrate' => 1,
1479
                                    'sound' =>  1
1480
                                ],
1671 efrain 1481
                                'data' => [
10435 efrain 1482
                                    'command' => 'content-refresh',
1483
                                    'new_capsules' => '0',
1671 efrain 1484
                                ]
1 www 1485
                            ]
1486
                        ]);
1487
 
1488
                        if($pushMapper->insert($push)) {
1489
                            $push_to_send = $push_to_send + 1;
1490
                        }
1491
 
1492
                    }
1493
                }
1494
 
1495
                if(0 == $push_to_send) {
1496
                    return new JsonModel([
1497
                        'success' => false,
1498
                        'data' => 'ERROR_NO_USER_DEVICES_WERE_FOUND_TO_SEND_PUSH'
1499
                    ]);
1500
                }
1501
 
1502
 
1503
 
1504
 
1505
 
1506
                return new JsonModel([
1507
                    'success' => true,
1508
                    'data' => [
1509
                        'push_to_send' => $push_to_send,
1510
                    ]
1511
                ]);
1512
 
1513
 
1514
 
1515
 
1516
 
1517
            } else {
1518
 
1519
                $messages = [];
1520
                $form_messages = (array) $form->getMessages();
1521
                foreach($form_messages  as $fieldname => $field_messages)
1522
                {
1523
                    $messages[$fieldname] = array_values($field_messages);
1524
                }
1525
 
1526
                return new JsonModel([
1527
                    'success'   => false,
1528
                    'data'      => $messages
1529
                ]);
1530
            }
1531
        }
1532
 
1533
        return new JsonModel([
1534
            'success' => false,
1535
            'data' => 'ERROR_METHOD_NOT_ALLOWED'
1536
        ]);
1537
    }
1538
 
1539
 
1540
}