Proyectos de Subversion LeadersLinked - Backend

Rev

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