Proyectos de Subversion LeadersLinked - Backend

Rev

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