Proyectos de Subversion LeadersLinked - Backend

Rev

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