Proyectos de Subversion LeadersLinked - Backend

Rev

Rev 4 | Ir a la última revisión | | Ultima modificación | Ver Log |

Rev Autor Línea Nro. Línea
1 www 1
<?php
2
declare(strict_types=1);
3
 
4
namespace LeadersLinked\Controller;
5
 
6
use Laminas\Db\Adapter\AdapterInterface;
7
use Laminas\Cache\Storage\Adapter\AbstractAdapter;
8
 
9
 
10
use Laminas\Mvc\Controller\AbstractActionController;
11
use Laminas\Log\LoggerInterface;
12
 
13
use Laminas\View\Model\ViewModel;
14
use Laminas\View\Model\JsonModel;
15
use LeadersLinked\Library\Functions;
16
use LeadersLinked\Mapper\UserMapper;
17
use LeadersLinked\Mapper\UserPasswordMapper;
18
 
19
use LeadersLinked\Model\User;
20
use LeadersLinked\Form\ChangePasswordForm;
21
use LeadersLinked\Model\CompanyUser;
22
use LeadersLinked\Mapper\CompanyUserMapper;
23
use LeadersLinked\Mapper\CompanyUserRoleMapper;
24
use LeadersLinked\Mapper\RoleMapper;
25
use LeadersLinked\Model\UserType;
26
use LeadersLinked\Model\UserPassword;
27
use PhpOffice\PhpSpreadsheet\IOFactory;
28
use LeadersLinked\Form\UserUploadForm;
29
use LeadersLinked\Mapper\CompanyServiceMapper;
30
use LeadersLinked\Model\CompanyService;
31
use LeadersLinked\Model\Role;
32
use LeadersLinked\Mapper\CompanyRoleMapper;
33
use LeadersLinked\Model\CompanyUserRole;
34
use LeadersLinked\Model\Notification;
35
use LeadersLinked\Model\EmailTemplate;
36
use LeadersLinked\Mapper\NotificationMapper;
37
use LeadersLinked\Mapper\UserNotificationSettingMapper;
38
use LeadersLinked\Mapper\EmailTemplateMapper;
39
use LeadersLinked\Library\QueueEmail;
40
 
41
class UserController extends AbstractActionController
42
{
43
    /**
44
     *
45
     * @var AdapterInterface
46
     */
47
    private $adapter;
48
 
49
 
50
    /**
51
     *
52
     * @var AbstractAdapter
53
     */
54
    private $cache;
55
 
56
    /**
57
     *
58
     * @var  LoggerInterface
59
     */
60
    private $logger;
61
 
62
 
63
    /**
64
     *
65
     * @var array
66
     */
67
    private $config;
68
 
69
 
70
    /**
71
     *
72
     * @param AdapterInterface $adapter
73
     * @param AbstractAdapter $cache
74
     * @param LoggerInterface $logger
75
     * @param array $config
76
     */
77
    public function __construct($adapter, $cache , $logger, $config)
78
    {
79
        $this->adapter      = $adapter;
80
        $this->cache        = $cache;
81
        $this->logger       = $logger;
82
        $this->config       = $config;
83
 
84
    }
85
 
86
    public function indexAction()
87
    {
88
        $currentUserPlugin = $this->plugin('currentUserPlugin');
89
        $currentUser = $currentUserPlugin->getUser();
90
        $currentCompany = $currentUserPlugin->getCompany();
91
 
92
        $request = $this->getRequest();
93
 
94
        if($request->isGet())
95
 
96
 
97
            $headers  = $request->getHeaders();
98
 
99
            $isJson = false;
100
            if($headers->has('Accept')) {
101
                $accept = $headers->get('Accept');
102
 
103
                $prioritized = $accept->getPrioritized();
104
 
105
                foreach($prioritized as $key => $value) {
106
                    $raw = trim($value->getRaw());
107
 
108
                    if(!$isJson) {
109
                        $isJson = strpos($raw, 'json');
110
                    }
111
 
112
                }
113
            }
114
 
115
            if($isJson) {
116
            {
117
                $sandbox = $this->config['leaderslinked.runmode.sandbox'];
118
                if($sandbox) {
119
                    $user_profile_url = $this->config['leaderslinked.frontend.sandbox_user_profile'];
120
                } else {
121
                    $user_profile_url = $this->config['leaderslinked.frontend.production_user_profile'];
122
                }
123
 
124
 
125
 
126
                $search = $this->params()->fromQuery('search', []);
127
                $search = empty($search['value']) ? '' : filter_var($search['value'], FILTER_SANITIZE_STRING);
128
 
129
                $page               = intval($this->params()->fromQuery('start', 1), 10);
130
                $records_x_page     = intval($this->params()->fromQuery('length', 10), 10);
131
                $order =  $this->params()->fromQuery('order', []);
132
                $order_field        = empty($order[0]['column']) ? 99 :  intval($order[0]['column'], 10);
133
                $order_direction    = empty($order[0]['dir']) ? 'ASC' : strtoupper(filter_var( $order[0]['dir'], FILTER_SANITIZE_STRING));
134
 
135
                $fields =  ['first_name', 'last_name', 'email'];
136
                $order_field = isset($fields[$order_field]) ? $fields[$order_field] : 'first_name';
137
 
138
                if(!in_array($order_direction, ['ASC', 'DESC'])) {
139
                    $order_direction = 'ASC';
140
                }
141
 
142
 
143
                if($currentCompany) {
144
                    $companyUserRoleMapper = CompanyUserRoleMapper::getInstance($this->adapter);
145
 
146
                    $roles = [];
147
                    $roleMapper = RoleMapper::getInstance($this->adapter);
148
                    $records = $roleMapper->fetchAll();
149
                    foreach ($records as $record)
150
                    {
151
                        $roles[ $record->id ] = $record->name;
152
                    }
153
 
154
 
155
                    //Usuarios cuando el nivel es empresa
156
 
157
                    $acl = $this->getEvent()->getViewModel()->getVariable('acl');
158
                    $allowUnblock = $acl->isAllowed($currentUser->usertype_id, 'users/unblock');
159
                    $allowChangePassword = $acl->isAllowed($currentUser->usertype_id, 'users/change-password');
160
 
161
                    $allowAccept    = $acl->isAllowed($currentUser->usertype_id, 'users/accept') ? 1 : 0;
162
                    $allowCancel    = $acl->isAllowed($currentUser->usertype_id, 'users/cancel') ? 1 : 0;
163
                    $allowReject    = $acl->isAllowed($currentUser->usertype_id, 'users/reject') ? 1 : 0;
164
                    $allowEdit     = $acl->isAllowed($currentUser->usertype_id, 'users/edit') ? 1 : 0;
165
 
166
 
167
                    $status = filter_var($this->params()->fromQuery('status'), FILTER_SANITIZE_STRING);
168
                    if(!in_array($status, [
169
                        CompanyUser::STATUS_ACCEPTED,
170
                        CompanyUser::STATUS_ADMIN_WILL_ADD,
171
                        CompanyUser::STATUS_CANCELLED,
172
                        CompanyUser::STATUS_PENDING,
173
                        CompanyUser::STATUS_REJECTED,
174
                        CompanyUser::STATUS_SENT,
175
                    ])) {
176
                        $status = '';
177
                    }
178
 
179
 
180
 
181
                    $userMapper = UserMapper::getInstance($this->adapter);
182
                    $companyUserMapper = CompanyUserMapper::getInstance($this->adapter);
183
 
184
                    $paginator = $userMapper->fetchAllDataTableByCompanyId($currentCompany->id, $status,  $search, $page, $records_x_page, $order_field, $order_direction);
185
 
186
                    $items = [];
187
                    $records = $paginator->getCurrentItems();
188
 
189
                    foreach($records as $record)
190
                    {
191
 
192
                        $actions = [];
193
                        $actions['link_profile'] = str_replace('[uuid]', $record['uuid'], $user_profile_url);
194
 
195
 
196
 
197
 
198
                        $details = [];
199
                        switch ($record['status'])
200
                        {
201
 
202
                            case CompanyUser::STATUS_PENDING :
203
                                $details['status']  = 'LABEL_PENDING';
204
                                $actions['link_accept'] = $allowAccept ? $this->url()->fromRoute('users/accept', ['id' => $record['uuid']]) : '';
205
                                $actions['link_reject'] = $allowReject ? $this->url()->fromRoute('users/reject', ['id' => $record['uuid']]) : '';
206
                                break;
207
 
208
                            case CompanyUser::STATUS_ACCEPTED :
209
                                $details['status']  = 'LABEL_ACCEPTED';
210
                                if($record['creator'] == CompanyUser::CREATOR_NO) {
211
                                    $actions['link_edit'] = $allowEdit ? $this->url()->fromRoute('users/edit', ['id' => $record['uuid']]) : '';
212
 
213
 
214
 
215
                                    $actions['link_cancel'] = $allowCancel ? $this->url()->fromRoute('users/cancel', ['id' => $record['uuid']]) : '';
216
                                }
217
 
218
                                break;
219
 
220
                            case CompanyUser::STATUS_ADMIN_WILL_ADD :
221
                                $details['status']  = 'LABEL_ADMIN_WILL_ADD';
222
                                $actions['link_cancel'] = $allowCancel ? $this->url()->fromRoute('users/cancel', ['id' => $record['uuid']]) : '';
223
                                $actions['link_edit'] = $allowEdit ? $this->url()->fromRoute('users/edit', ['id' => $record['uuid']]) : '';
224
 
225
                                break;
226
 
227
                            case CompanyUser::STATUS_SENT :
228
                                $details['status']  = 'LABEL_INVITED';
229
                                $actions['link_accept'] = $allowAccept ? $this->url()->fromRoute('users/accept', ['id' => $record['uuid']]) : '';
230
                                $actions['link_reject'] = $allowReject ? $this->url()->fromRoute('users/reject', ['id' => $record['uuid']]) : '';
231
                                break;
232
 
233
                            case CompanyUser::STATUS_REJECTED :
234
                                $actions['link_accept'] = $allowAccept ? $this->url()->fromRoute('users/accept', ['id' => $record['uuid']]) : '';
235
                                $details['status']  = 'LABEL_REJECTED';
236
                                break;
237
 
238
                            case CompanyUser::STATUS_CANCELLED :
239
                                $actions['link_accept'] = $allowAccept ? $this->url()->fromRoute('users/accept', ['id' => $record['uuid']]) : '';
240
                                $details['status']  = 'LABEL_CANCELLED';
241
                                break;
242
 
243
                            default :
244
                                $details['status']  = '';
245
                                break;
246
 
247
                        }
248
 
249
                        $totalOtherCompanies = $companyUserMapper->fetchCountOtherCompaniesByCompanyIdAndUserId($currentCompany->id, $record['id']);
250
                        if(!$totalOtherCompanies) {
251
 
252
                            $actions['link_change_password'] = $allowChangePassword ? $this->url()->fromRoute('users/change-password', ['id' => $record['uuid'] ]) : '';
253
                            if($record['blocked'] == User::BLOCKED_YES ) {
254
                                $actions['link_unblock'] = $allowUnblock ? $this->url()->fromRoute('users/unblock', ['id' => $record['uuid'] ]) : '';
255
                            }
256
                        }
257
 
258
                        if($record['blocked'] == User::BLOCKED_YES ) {
259
                            $details['blocked'] = 'LABEL_YES';
260
                        } else if($record['blocked'] == User::BLOCKED_NO ) {
261
                            $details['blocked'] = 'LABEL_NO';
262
                        }
263
                        if($record['email_verified'] == User::EMAIL_VERIFIED_YES ) {
264
                            $details['email_verified'] = 'LABEL_YES';
265
 
266
                        } else if($record['email_verified'] == User::EMAIL_VERIFIED_NO ) {
267
                            $details['email_verified'] = 'LABEL_NO';
268
                        }
269
                        $details['login_attempt'] = $record['login_attempt'];
270
 
271
 
272
                        $company_user_roles = $companyUserRoleMapper->fetchAllByCompanyIdAndUserId($currentCompany->id, $record['id']);
273
 
274
                        $details['roles'] = [];
275
 
276
                        if($record['creator'] == CompanyUser::CREATOR_YES) {
277
                            $details['roles'][] = 'LABEL_ALL_PERMITS';
278
                            $details['creator'] = 'LABEL_YES' ;
279
                        }  else {
280
                            $details['creator'] = 'LABEL_NO';
281
                            foreach($company_user_roles as $company_user_role)
282
                            {
283
                                $role = $roles[ $company_user_role->role_id ];
284
                                $details['roles'][] = $role;
285
 
286
                            }
287
                        }
288
 
289
 
290
                        $details['backend'] = $record['backend'] == CompanyUser::BACKEND_YES ? 'LABEL_YES' : 'LABEL_NO';
291
 
292
 
293
 
294
 
295
 
296
 
297
                        $item = [
298
                            'first_name' => $record['first_name'] ,
299
                            'last_name' => $record['last_name'],
300
                            'email' => $record['email'],
301
                            'details' => $details,
302
                            'actions' =>  $actions ,
303
                       ];
304
 
305
                        array_push($items, $item);
306
                    }
307
                } else {
308
                    //Usuario cuando el nivel es administrador
309
 
310
 
311
 
312
                    $acl = $this->getEvent()->getViewModel()->getVariable('acl');
313
                    $allowUnblock = $acl->isAllowed($currentUser->usertype_id, 'users/unblock');
314
                    $allowChangePassword = $acl->isAllowed($currentUser->usertype_id, 'users/change-password');
315
 
316
                    $userMapper = UserMapper::getInstance($this->adapter);
317
                    $paginator = $userMapper->fetchAllDataTable($search, $page, $records_x_page, $order_field, $order_direction);
318
 
319
                    $items = [];
320
                    $records = $paginator->getCurrentItems();
321
 
322
                    foreach($records as $record)
323
                    {
324
                        $actions = [];
325
                        $actions['link_profile'] = str_replace('[uuid]', $record->uuid, $user_profile_url);
326
 
327
 
328
                        $details = [] ;
329
                        if($record->status == User::STATUS_ACTIVE ) {
330
                            $details['status'] = 'LABEL_ACTIVE';
331
                        } else if($record->status == User::STATUS_INACTIVE ) {
332
                            $details['status'] = 'LABEL_INACTIVE';
333
                        }
334
                        if($record->blocked == User::BLOCKED_YES ) {
335
                            $details['blocked'] = 'LABEL_YES';
336
                        } else if($record->blocked == User::BLOCKED_NO ) {
337
                            $details['blocked'] = 'LABEL_NO';
338
                        }
339
                        if($record->email_verified == User::EMAIL_VERIFIED_YES ) {
340
                            $details['email_verified'] = 'LABEL_YES';
341
 
342
                        } else if($record->email_verified == User::EMAIL_VERIFIED_NO ) {
343
                            $details['email_verified'] = 'LABEL_NO';
344
                        }
345
                        $details['login_attempt'] = $record->login_attempt;
346
 
347
 
348
                        $actions['link_change_password'] = $allowChangePassword ? $this->url()->fromRoute('users/change-password', ['id' => $record->uuid ]) : '';
349
                        $actions['link_unblock'] = $allowUnblock && $record->blocked == User::BLOCKED_YES ? $this->url()->fromRoute('users/unblock', ['id' => $record->uuid ]) : '';
350
 
351
                        $item = [
352
 
353
 
354
                            'first_name' => $record->first_name,
355
                            'last_name' => $record->last_name,
356
                            'email' => $record->email,
357
                            'details' => $details,
358
                            'actions' => $actions
359
                         ];
360
 
361
                        array_push($items, $item);
362
                    }
363
                }
364
            }
365
 
366
            return new JsonModel([
367
                'success' => true,
368
                'data' => [
369
                    'items' => $items,
370
                    'total' => $paginator->getTotalItemCount(),
371
                ]
372
            ]);
373
 
374
 
375
 
376
        }
377
        else if($request->isGet()) {
378
            $this->layout()->setTemplate('layout/layout-backend');
379
            $viewModel = new ViewModel();
380
 
381
            $formChangePassword = new ChangePasswordForm();
382
            $company = $currentUserPlugin->getCompany();
383
            if($company) {
384
 
385
                $formUploadUsers = new UserUploadForm();
386
 
387
                $viewModel->setTemplate('leaders-linked/users/company.phtml');
388
                $viewModel->setVariables([
389
                    'formUploadUsers' => $formUploadUsers,
390
                    'formChangePassword' => $formChangePassword,
391
                ] );
392
            } else {
393
                $viewModel->setTemplate('leaders-linked/users/index.phtml');
394
                $viewModel->setVariables([
395
                    'formChangePassword' => $formChangePassword,
396
                ]);
397
            }
398
            return $viewModel ;
399
 
400
        } else {
401
            return new JsonModel([
402
                'success' => false,
403
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
404
            ]);;
405
        }
406
    }
407
    /*
408
    public function addAction()
409
    {
410
        $currentUserPlugin = $this->plugin('currentUserPlugin');
411
        $currentUser = $currentUserPlugin->getUser();
412
 
413
        $request = $this->getRequest();
414
 
415
 
416
        if($request->isPost()) {
417
            $form = new  AddForm($this->adapter);
418
            $dataPost = $request->getPost()->toArray();
419
 
420
            $form->setData($dataPost);
421
 
422
            if($form->isValid()) {
423
                $dataPost = (array) $form->getData();
424
 
425
                $hydrator = new ObjectPropertyHydrator();
426
                $user = new User();
427
                $hydrator->hydrate($dataPost, $user);
428
 
429
 
430
                $userMapper = UserMapper::getInstance($this->adapter);
431
                $result = $userMapper->insert($user);
432
 
433
                if($result) {
434
                    $this->logger->info('Se agrego el usuario ' . $user->name, ['user_id' => $currentUser->id, 'ip' => Functions::getUserIP()]);
435
 
436
                    $data = [
437
                        'success'   => true,
438
                        'data'   => 'LABEL_RECORD_ADDED'
439
                    ];
440
                } else {
441
                    $data = [
442
                        'success'   => false,
443
                        'data'      => $userMapper->getError()
444
                    ];
445
 
446
                }
447
 
448
                return new JsonModel($data);
449
 
450
            } else {
451
                $messages = [];
452
                $form_messages = (array) $form->getMessages();
453
                foreach($form_messages  as $fieldname => $field_messages)
454
                {
455
 
456
                    $messages[$fieldname] = array_values($field_messages);
457
                }
458
 
459
                return new JsonModel([
460
                    'success'   => false,
461
                    'data'   => $messages
462
                ]);
463
            }
464
 
465
        } else {
466
            $data = [
467
                'success' => false,
468
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
469
            ];
470
 
471
            return new JsonModel($data);
472
        }
473
 
474
        return new JsonModel($data);
475
    }
476
 
477
    public function editAction()
478
    {
479
        $currentUserPlugin = $this->plugin('currentUserPlugin');
480
        $currentUser = $currentUserPlugin->getUser();
481
 
482
        $request = $this->getRequest();
483
        $id = $this->params()->fromRoute('id');
484
 
485
 
486
        if(!$id) {
487
            $data = [
488
                'success'   => false,
489
                'data'   => 'ERROR_INVALID_PARAMETER'
490
            ];
491
 
492
            return new JsonModel($data);
493
        }
494
 
495
        $userMapper = UserMapper::getInstance($this->adapter);
496
        $user = $userMapper->fetchOne($id);
497
        if(!$user) {
498
            $data = [
499
                'success'   => false,
500
                'data'   => 'ERROR_RECORD_NOT_FOUND'
501
            ];
502
 
503
            return new JsonModel($data);
504
        }
505
 
506
        if($request->isPost()) {
507
            $form = new  EditForm($this->adapter);
508
            $dataPost = $request->getPost()->toArray();
509
 
510
            $form->setData($dataPost);
511
 
512
            if($form->isValid()) {
513
                $dataPost = (array) $form->getData();
514
 
515
                $hydrator = new ObjectPropertyHydrator();
516
                $hydrator->hydrate($dataPost, $user);
517
                $result = $userMapper->update($user);
518
 
519
                if($result) {
520
                    $this->logger->info('Se actualizo el usuario ' . $user->name, ['user_id' => $currentUser->id, 'ip' => Functions::getUserIP()]);
521
 
522
                    $data = [
523
                        'success' => true,
524
                        'data' => 'LABEL_RECORD_UPDATED'
525
                    ];
526
                } else {
527
                    $data = [
528
                        'success'   => false,
529
                        'data'      => $userMapper->getError()
530
                    ];
531
                }
532
 
533
                return new JsonModel($data);
534
 
535
            } else {
536
                $messages = [];
537
                $form_messages = (array) $form->getMessages();
538
                foreach($form_messages  as $fieldname => $field_messages)
539
                {
540
                    $messages[$fieldname] = array_values($field_messages);
541
                }
542
 
543
                return new JsonModel([
544
                    'success'   => false,
545
                    'data'   => $messages
546
                ]);
547
            }
548
        } else if ($request->isGet()) {
549
            $hydrator = new ObjectPropertyHydrator();
550
 
551
            $data = [
552
                'success' => true,
553
                'data' => $hydrator->extract($user)
554
            ];
555
 
556
            return new JsonModel($data);
557
        } else {
558
            $data = [
559
                'success' => false,
560
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
561
            ];
562
 
563
            return new JsonModel($data);
564
        }
565
 
566
        return new JsonModel($data);
567
    }
568
 
569
    public function deleteAction()
570
    {
571
        $currentUserPlugin = $this->plugin('currentUserPlugin');
572
        $currentUser = $currentUserPlugin->getUser();
573
 
574
        $request = $this->getRequest();
575
        $id = $this->params()->fromRoute('id');
576
 
577
        if(!$id) {
578
            $data = [
579
                'success'   => false,
580
                'data'   => 'ERROR_INVALID_PARAMETER'
581
            ];
582
 
583
            return new JsonModel($data);
584
        }
585
 
586
 
587
        $userMapper = UserMapper::getInstance($this->adapter);
588
        $user = $userMapper->fetchOne($id);
589
        if(!$user) {
590
            $data = [
591
                'success'   => false,
592
                'data'   => 'ERROR_RECORD_NOT_FOUND'
593
            ];
594
 
595
            return new JsonModel($data);
596
        }
597
 
598
        if($request->isPost()) {
599
            $result = $userMapper->delete($user);
600
            if($result) {
601
                $this->logger->info('Se borro el usuario ' . $user->name, ['user_id' => $currentUser->id, 'ip' => Functions::getUserIP()]);
602
 
603
                $data = [
604
                    'success' => true,
605
                    'data' => 'LABEL_RECORD_DELETED'
606
                ];
607
            } else {
608
 
609
                $data = [
610
                    'success'   => false,
611
                    'data'      => $userMapper->getError()
612
                ];
613
 
614
                return new JsonModel($data);
615
            }
616
 
617
        } else {
618
            $data = [
619
                'success' => false,
620
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
621
            ];
622
 
623
            return new JsonModel($data);
624
        }
625
 
626
        return new JsonModel($data);
627
    }*/
628
 
629
    public function unblockAction()
630
    {
631
        $currentUserPlugin = $this->plugin('currentUserPlugin');
632
        $currentUser = $currentUserPlugin->getUser();
633
        $request = $this->getRequest();
634
 
635
 
636
        if($request->isPost()) {
637
 
638
            $uuid = $this->params()->fromRoute('id');
639
            if(!$uuid) {
640
                return new JsonModel([
641
                    'success'   => false,
642
                    'data'      => 'ERROR_INVALID_PARAMETER'
643
                ]);
644
            }
645
 
646
            $userMapper = UserMapper::getInstance($this->adapter);
647
            $user = $userMapper->fetchOneByUuid($uuid);
648
 
649
            if(!$user) {
650
                return new JsonModel([
651
                    'success'   => false,
652
                    'data'      => 'ERROR_USER_NOT_FOUND'
653
                ]);
654
            }
655
 
656
            if($user->blocked == User::BLOCKED_NO) {
657
                return new JsonModel([
658
                    'success'   => false,
659
                    'data'      => 'ERROR_USER_IS_NOT_BLOCKED'
660
                ]);
661
            }
662
 
663
 
664
 
665
            $result = $userMapper->unblock($user);
666
            if($result) {
667
                $this->logger->info('El usuario : ' . $user->email . ' ha sido desbloqueado ', ['user_id' => $currentUser->id, 'ip' => Functions::getUserIP()]);
668
 
669
                return new JsonModel([
670
                    'success'   => true,
671
                    'data'      => 'LABEL_USER_HAS_BEEN_UNBLOCKED',
672
                ]);
673
            }  else {
674
 
675
                return new JsonModel([
676
                    'success'   => false,
677
                    'data'      => $userMapper->getError()
678
                ]);
679
            }
680
 
681
 
682
        }
683
 
684
 
685
 
686
        return new JsonModel([
687
            'success' => false,
688
            'data' => 'ERROR_METHOD_NOT_ALLOWED'
689
        ]);
690
    }
691
 
692
    public function changePasswordAction()
693
    {
694
        $currentUserPlugin = $this->plugin('currentUserPlugin');
695
        $currentUser = $currentUserPlugin->getUser();
696
 
697
        $request = $this->getRequest();
698
 
699
        if($request->isGet()) {
700
            $uuid = $this->params()->fromRoute('id');
701
            if(!$uuid) {
702
                return new JsonModel([
703
                    'success'   => false,
704
                    'data'      => 'ERROR_INVALID_PARAMETER'
705
                ]);
706
            }
707
 
708
            $userMapper = UserMapper::getInstance($this->adapter);
709
            $user = $userMapper->fetchOneByUuid($uuid);
710
 
711
 
712
 
713
            if($user) {
714
                return new JsonModel([
715
                    'success'   => true,
716
                    'data'      => [
717
                        'first_name' => $user->first_name,
718
                        'last_name' => $user->last_name,
719
                        'email' => $user->email,
720
                    ]
721
                ]);
722
            } else {
723
                return new JsonModel([
724
                    'success'   => false,
725
                    'data'      => 'ERROR_USER_NOT_FOUND'
726
                ]);
727
            }
728
 
729
        }
730
 
731
        if($request->isPost()) {
732
 
733
            $uuid = $this->params()->fromRoute('id');
734
            if(!$uuid) {
735
                return new JsonModel([
736
                    'success'   => false,
737
                    'data'      => 'ERROR_INVALID_PARAMETER'
738
                ]);
739
            }
740
 
741
            $userMapper = UserMapper::getInstance($this->adapter);
742
            $user = $userMapper->fetchOneByUuid($uuid);
743
 
744
            if(!$user) {
745
                return new JsonModel([
746
                    'success'   => false,
747
                    'data'      => 'ERROR_USER_NOT_FOUND'
748
                ]);
749
            }
750
 
751
 
752
            $dataPost = $request->getPost()->toArray();
753
            $form = new ChangePasswordForm();
754
            $form->setData($dataPost);
755
 
756
            if($form->isValid()) {
757
 
758
 
759
 
760
                $data = (array) $form->getData();
761
                $password = $data['password'];
762
 
763
 
764
 
765
                $userPasswordMapper = UserPasswordMapper::getInstance($this->adapter);
766
                $userPasswords = $userPasswordMapper->fetchAllByUserId($user->id);
767
 
768
                $oldPassword = false;
769
                foreach($userPasswords as $userPassword)
770
                {
771
                    if(password_verify($password, $userPassword->password) || (md5($password) == $userPassword->password))
772
                    {
773
                        $oldPassword = true;
774
                        break;
775
                    }
776
                }
777
 
778
                if($oldPassword) {
779
                    $this->logger->err('Cambio de contraseña del usuario - error contraseña ya utilizada anteriormente', ['user_id' =>  $currentUser->id, 'ip' => Functions::getUserIP()]);
780
 
781
                    return new JsonModel([
782
                        'success'   => false,
783
                        'data'      => 'ERROR_PASSWORD_HAS_ALREADY_BEEN_USED'
784
 
785
                    ]);
786
                } else {
787
                    $password_hash = password_hash($password, PASSWORD_DEFAULT);
788
 
789
 
790
                    $result = $userMapper->updatePassword($user, $password_hash);
791
                    if($result) {
792
                        $this->logger->info('Cambio de contraseña del usuario realizado', ['user_id' => $currentUser->id, 'ip' => Functions::getUserIP()]);
793
 
794
 
795
                        return new JsonModel([
796
                            'success'   => true,
797
                            'data'      => 'LABEL_YOUR_PASSWORD_HAS_BEEN_UPDATED'
798
 
799
                        ]);
800
                    } else {
801
                        $this->logger->err('Cambio de contraseña del usuario - error desconocido', ['user_id' => $currentUser->id, 'ip' => Functions::getUserIP()]);
802
 
803
                        return new JsonModel([
804
                            'success'   => true,
805
                            'data'      => 'ERROR_THERE_WAS_AN_ERROR'
806
 
807
                        ]);
808
                    }
809
                }
810
 
811
            } else {
812
                $messages = [];
813
 
814
                $form_messages = (array) $form->getMessages();
815
                foreach($form_messages  as $fieldname => $field_messages)
816
                {
817
                    $messages[$fieldname] = array_values($field_messages);
818
                }
819
 
820
                return new JsonModel([
821
                    'success'   => false,
822
                    'data'   => $messages
823
                ]);
824
            }
825
 
826
        }
827
 
828
 
829
 
830
        return new JsonModel([
831
            'success' => false,
832
            'data' => 'ERROR_METHOD_NOT_ALLOWED'
833
        ]);
834
    }
835
 
836
    public function cancelAction()
837
    {
838
        $currentUserPlugin = $this->plugin('currentUserPlugin');
839
        $currentUser = $currentUserPlugin->getUser();
840
 
841
        $currentCompany = $currentUserPlugin->getCompany();
842
 
843
        $request = $this->getRequest();
844
 
845
 
846
        if($request->isPost()) {
847
 
848
            $uuid = $this->params()->fromRoute('id');
849
            if(!$uuid) {
850
                return new JsonModel([
851
                    'success'   => false,
852
                    'data'      => 'ERROR_INVALID_PARAMETER'
853
                ]);
854
            }
855
 
856
            $userMapper = UserMapper::getInstance($this->adapter);
857
            $user = $userMapper->fetchOneByUuid($uuid);
858
 
859
            if(!$user) {
860
                return new JsonModel([
861
                    'success'   => false,
862
                    'data'      => 'ERROR_USER_COMPANY_NOT_FOUND'
863
                ]);
864
            }
865
 
866
            $companyUserMapper = CompanyUserMapper::getInstance($this->adapter);
867
            $companyUser = $companyUserMapper->fetchOneByCompanyIdAndUserId($currentCompany->id, $user->id);
868
 
869
            if(!$companyUser) {
870
                return new JsonModel([
871
                    'success'   => false,
872
                    'data'      => 'ERROR_USER_NOT_FOUND'
873
                ]);
874
            }
875
 
876
 
877
            if(!in_array($companyUser->status, [  CompanyUser::STATUS_ADMIN_WILL_ADD, CompanyUser::STATUS_ACCEPTED])) {
878
                return new JsonModel([
879
                    'success'   => false,
880
                    'data'      => 'ERROR_USER_COMPANY_WRONG_STATUS'
881
                ]);
882
            }
883
 
884
            $companyUser->status = CompanyUser::STATUS_CANCELLED;
885
            $result = $companyUserMapper->update($companyUser);
886
            if($result) {
887
                $this->logger->info('La relación del usuario : ' . $user->email . ' con la empresa : ' . $currentCompany->name  . ' ha sido cancelada ', ['user_id' => $currentUser->id, 'ip' => Functions::getUserIP()]);
888
 
889
                return new JsonModel([
890
                    'success'   => true,
891
                    'data'      => 'LABEL_USER_COMPANY_HAS_BEEN_CANCELLED',
892
                ]);
893
            }  else {
894
 
895
                return new JsonModel([
896
                    'success'   => false,
897
                    'data'      => $userMapper->getError()
898
                ]);
899
            }
900
 
901
 
902
        }
903
 
904
 
905
 
906
        return new JsonModel([
907
            'success' => false,
908
            'data' => 'ERROR_METHOD_NOT_ALLOWED'
909
        ]);
910
    }
911
 
912
    public function acceptAction()
913
    {
914
        $currentUserPlugin = $this->plugin('currentUserPlugin');
915
        $currentUser = $currentUserPlugin->getUser();
916
 
917
        $currentCompany = $currentUserPlugin->getCompany();
918
 
919
        $request = $this->getRequest();
920
 
921
 
922
        if($request->isPost()) {
923
 
924
            $uuid = $this->params()->fromRoute('id');
925
            if(!$uuid) {
926
                return new JsonModel([
927
                    'success'   => false,
928
                    'data'      => 'ERROR_INVALID_PARAMETER'
929
                ]);
930
            }
931
 
932
            $userMapper = UserMapper::getInstance($this->adapter);
933
            $user = $userMapper->fetchOneByUuid($uuid);
934
 
935
            if(!$user) {
936
                return new JsonModel([
937
                    'success'   => false,
938
                    'data'      => 'ERROR_USER_NOT_FOUND'
939
                ]);
940
            }
941
 
942
            $companyUserMapper = CompanyUserMapper::getInstance($this->adapter);
943
            $companyUser = $companyUserMapper->fetchOneByCompanyIdAndUserId($currentCompany->id, $user->id);
944
 
945
            if(!$companyUser) {
946
                return new JsonModel([
947
                    'success'   => false,
948
                    'data'      => 'ERROR_USER_NOT_FOUND'
949
                ]);
950
            }
951
 
952
            if($companyUser->status != CompanyUser::STATUS_PENDING
953
                && $companyUser->status != CompanyUser::STATUS_SENT
954
                && $companyUser->status != CompanyUser::STATUS_CANCELLED
955
                && $companyUser->status != CompanyUser::STATUS_REJECTED) {
956
                return new JsonModel([
957
                    'success'   => false,
958
                    'data'      => 'ERROR_USER_COMPANY_WRONG_STATUS'
959
                ]);
960
            }
961
 
962
            $companyUser->status = CompanyUser::STATUS_ACCEPTED;
963
            $result = $companyUserMapper->update($companyUser);
964
            if($result) {
965
                $this->logger->info('La relación del usuario : ' . $user->email . ' con la empresa : ' . $currentCompany->name  . ' ha sido aceptada ', ['user_id' => $currentUser->id, 'ip' => Functions::getUserIP()]);
966
 
967
                return new JsonModel([
968
                    'success'   => true,
969
                    'data'      => 'LABEL_USER_COMPANY_HAS_BEEN_ACCEPTED'
970
                ]);
971
            }  else {
972
 
973
                return new JsonModel([
974
                    'success'   => false,
975
                    'data'      => $userMapper->getError()
976
                ]);
977
            }
978
 
979
 
980
        }
981
 
982
 
983
 
984
        return new JsonModel([
985
            'success' => false,
986
            'data' => 'ERROR_METHOD_NOT_ALLOWED'
987
        ]);
988
    }
989
 
990
    public function rejectAction()
991
    {
992
        $currentUserPlugin = $this->plugin('currentUserPlugin');
993
        $currentUser = $currentUserPlugin->getUser();
994
 
995
        $currentCompany = $currentUserPlugin->getCompany();
996
 
997
        $request = $this->getRequest();
998
 
999
 
1000
        if($request->isPost()) {
1001
 
1002
            $uuid = $this->params()->fromRoute('id');
1003
            if(!$uuid) {
1004
                return new JsonModel([
1005
                    'success'   => false,
1006
                    'data'      => 'ERROR_INVALID_PARAMETER'
1007
                ]);
1008
            }
1009
 
1010
            $userMapper = UserMapper::getInstance($this->adapter);
1011
            $user = $userMapper->fetchOneByUuid($uuid);
1012
 
1013
            if(!$user) {
1014
                return new JsonModel([
1015
                    'success'   => false,
1016
                    'data'      => 'ERROR_USER_NOT_FOUND'
1017
                ]);
1018
            }
1019
 
1020
            $companyUserMapper = CompanyUserMapper::getInstance($this->adapter);
1021
            $companyUser = $companyUserMapper->fetchOneByCompanyIdAndUserId($currentCompany->id, $user->id);
1022
 
1023
            if(!$companyUser) {
1024
                return new JsonModel([
1025
                    'success'   => false,
1026
                    'data'      => 'ERROR_USER_COMPANY_NOT_FOUND'
1027
                ]);
1028
            }
1029
 
1030
            if($companyUser->status != CompanyUser::STATUS_PENDING
1031
                && $companyUser->status != CompanyUser::STATUS_SENT) {
1032
                return new JsonModel([
1033
                    'success'   => false,
1034
                    'data'      => 'ERROR_USER_COMPANY_WRONG_STATUS'
1035
                ]);
1036
            }
1037
 
1038
            $companyUser->status = CompanyUser::STATUS_REJECTED;
1039
            $result = $companyUserMapper->update($companyUser);
1040
            if($result) {
1041
                $this->logger->info('La relación del usuario : ' . $user->email . ' con la empresa : ' . $currentCompany->name  . ' ha sido rechazada ', ['user_id' => $currentUser->id, 'ip' => Functions::getUserIP()]);
1042
 
1043
                return new JsonModel([
1044
                    'success'   => true,
1045
                    'data'      => 'LABEL_USER_COMPANY_HAS_BEEN_REJECTED',
1046
                ]);
1047
            }  else {
1048
 
1049
                return new JsonModel([
1050
                    'success'   => false,
1051
                    'data'      => $userMapper->getError()
1052
                ]);
1053
            }
1054
 
1055
 
1056
        }
1057
 
1058
 
1059
 
1060
        return new JsonModel([
1061
            'success' => false,
1062
            'data' => 'ERROR_METHOD_NOT_ALLOWED'
1063
        ]);
1064
    }
1065
 
1066
    public function inviteAction()
1067
    {
1068
        $currentUserPlugin = $this->plugin('currentUserPlugin');
1069
        $currentUser = $currentUserPlugin->getUser();
1070
 
1071
        $currentCompany = $currentUserPlugin->getCompany();
1072
 
1073
        $request = $this->getRequest();
1074
 
1075
        if($request->isGet()) {
1076
 
1077
            $search = trim(filter_var( $this->params()->fromQuery('search'), FILTER_SANITIZE_STRING)) ;
1078
            if(strlen($search) >= 3) {
1079
 
1080
                $userMapper = UserMapper::getInstance($this->adapter);
1081
                $records  = $userMapper->fetchAllSuggestForInvitationByCompanyId($currentCompany->id, $search);
1082
 
1083
                $users = [];
1084
                foreach($records as $record)
1085
                {
1086
                    array_push($users, [
1087
                        'value' => $record->uuid,
1088
                        'text' => trim($record->first_name . ' ' . $record->last_name) . ' (' . $record->email . ')'
1089
 
1090
                    ]);
1091
                }
1092
 
1093
                return new JsonModel([
1094
                    'success' => true,
1095
                    'data' => $users
1096
                ]);
1097
 
1098
 
1099
 
1100
 
1101
            } else {
1102
                return new JsonModel([
1103
                    'success' => true,
1104
                    'data' => [
1105
 
1106
                    ]
1107
                ]);
1108
            }
1109
 
1110
 
1111
 
1112
 
1113
 
1114
 
1115
        } else if($request->isPost()) {
1116
 
1117
            $uuid = $this->params()->fromPost('id');
1118
            if(!$uuid) {
1119
                return new JsonModel([
1120
                    'success'   => false,
1121
                    'data'      => 'ERROR_INVALID_PARAMETER'
1122
                ]);
1123
            }
1124
 
1125
            $userMapper = UserMapper::getInstance($this->adapter);
1126
            $user = $userMapper->fetchOneByUuid($uuid);
1127
 
1128
            if(!$user) {
1129
                return new JsonModel([
1130
                    'success'   => false,
1131
                    'data'      => 'ERROR_USER_NOT_FOUND'
1132
                ]);
1133
            }
1134
 
1135
            if($user->status != User::STATUS_ACTIVE) {
1136
                return new JsonModel([
1137
                    'success'   => false,
1138
                    'data'      => 'ERROR_USER_IS_INACTIVE'
1139
                ]);
1140
            }
1141
 
1142
 
1143
 
1144
 
1145
 
1146
            $companyUserMapper = CompanyUserMapper::getInstance($this->adapter);
1147
            $companyUser = $companyUserMapper->fetchOneByCompanyIdAndUserId($currentCompany->id, $user->id);
1148
 
1149
            if($companyUser && $companyUser->status == CompanyUser::STATUS_ACCEPTED) {
1150
                return new JsonModel([
1151
                    'success'   => false,
1152
                    'data'      => 'ERROR_USER_COMPANY_FOUND'
1153
                ]);
1154
            }
1155
 
1156
 
1157
 
1158
            if($companyUser) {
1159
 
1160
                $companyUser->status = CompanyUser::STATUS_ADMIN_WILL_ADD;
1161
                $result = $companyUserMapper->update($companyUser);
1162
 
1163
            } else {
1164
                $companyUser = new CompanyUser();
1165
                $companyUser->company_id = $currentCompany->id;
1166
                $companyUser->backend = CompanyUser::BACKEND_NO;
1167
                $companyUser->creator = CompanyUser::CREATOR_NO;
1168
                $companyUser->owner = CompanyUser::OWNER_NO;
1169
                $companyUser->status = CompanyUser::STATUS_ADMIN_WILL_ADD;
1170
                $companyUser->user_id = $user->id;
1171
 
1172
 
1173
 
1174
                $result = $companyUserMapper->insert($companyUser);
1175
            }
1176
 
1177
 
1178
 
1179
            if($result) {
1180
 
1181
 
1182
                $notification = new Notification();
1183
                $notification->type     = Notification::TYPE_RECEIVE_INVITATION_COMPANY;
1184
                $notification->read     = Notification::NO;
1185
                $notification->user_id  = $user->id;
1186
                $notification->company_id = $currentCompany->id;
1187
                $notification->message  = 'LABEL_NOTIFICATION_RECEIVE_INVITATION_COMPANY';
1188
                $notification->url      = 'company/view/' . $currentCompany->uuid;
1189
 
1190
                $notificationMapper = NotificationMapper::getInstance($this->adapter);
1191
                $notificationMapper->insert($notification);
1192
 
1193
                $userNotificationMapper = UserNotificationSettingMapper::getInstance($this->adapter);
1194
                $userNotification = $userNotificationMapper->fetchOne($user->id);
1195
 
1196
                if($userNotification && $userNotification->receive_invitation_company)
1197
                {
1198
                    $emailTemplateMapper = EmailTemplateMapper::getInstance($this->adapter);
1199
                    $emailTemplate = $emailTemplateMapper->fetchOne(EmailTemplate::ID_RECEIVE_INVITATION_COMPANY);
1200
 
1201
                    if($emailTemplate) {
1202
 
1203
                        $sandbox = $this->config['leaderslinked.runmode.sandbox'];
1204
                        if($sandbox) {
1205
                            $company_profile_url = $this->config['leaderslinked.frontend.sandbox_company_profile'];
1206
                        } else {
1207
                            $company_profile_url = $this->config['leaderslinked.frontend.production_company_profile'];
1208
                        }
1209
 
1210
                        $company_profile_url = str_replace('[uuid]', $currentCompany->uuid, $company_profile_url);
1211
 
1212
                        $arrayCont = [
1213
                            'firstname'             => $currentUser->first_name,
1214
                            'lastname'              => $currentUser->last_name,
1215
                            'other_user_firstname'  => $user->first_name,
1216
                            'other_user_lastname'   => $user->last_name,
1217
                            'company_name'          => $currentCompany->name,
1218
                            'group_name'            => '',
1219
                            'content'               => '',
1220
                            'code'                  => '',
1221
                            'link'                  => $company_profile_url,
1222
                        ];
1223
 
1224
                        $email = new QueueEmail($this->adapter);
1225
                        $email->processEmailTemplate($emailTemplate, $arrayCont, $user->email, trim($user->first_name . ' ' . $user->last_name));
1226
                    }
1227
                }
1228
 
1229
 
1230
                $this->logger->info('La empresa : ' . $currentCompany->name . ' envio al usuario : ' . $user->email . ' una invitación ', ['user_id' => $currentUser->id, 'ip' => Functions::getUserIP()]);
1231
 
1232
                return new JsonModel([
1233
                    'success'   => true,
1234
                    'data'      => 'LABEL_USER_COMPANY_HAS_BEEN_SENT',
1235
                ]);
1236
            }  else {
1237
 
1238
                return new JsonModel([
1239
                    'success'   => false,
1240
                    'data'      => $userMapper->getError()
1241
                ]);
1242
            }
1243
 
1244
 
1245
        }
1246
 
1247
 
1248
 
1249
        return new JsonModel([
1250
            'success' => false,
1251
            'data' => 'ERROR_METHOD_NOT_ALLOWED'
1252
        ]);
1253
    }
1254
 
1255
 
1256
    public function deleteAction()
1257
    {
1258
        $currentUserPlugin = $this->plugin('currentUserPlugin');
1259
        $currentUser = $currentUserPlugin->getUser();
1260
 
1261
        $currentCompany = $currentUserPlugin->getCompany();
1262
 
1263
        $request = $this->getRequest();
1264
 
1265
 
1266
        if($request->isPost()) {
1267
 
1268
            $uuid = $this->params()->fromRoute('id');
1269
            if(!$uuid) {
1270
                return new JsonModel([
1271
                    'success'   => false,
1272
                    'data'      => 'ERROR_INVALID_PARAMETER'
1273
                ]);
1274
            }
1275
 
1276
            $userMapper = UserMapper::getInstance($this->adapter);
1277
            $user = $userMapper->fetchOneByUuid($uuid);
1278
 
1279
            if(!$user) {
1280
                return new JsonModel([
1281
                    'success'   => false,
1282
                    'data'      => 'ERROR_USER_NOT_FOUND'
1283
 
1284
                ]);
1285
            }
1286
 
1287
            $companyUserMapper = CompanyUserMapper::getInstance($this->adapter);
1288
            $companyUser = $companyUserMapper->fetchOneByCompanyIdAndUserId($currentCompany->id, $user->id);
1289
 
1290
            if($companyUser) {
1291
                return new JsonModel([
1292
                    'success'   => false,
1293
                    'data'      => 'ERROR_USER_COMPANY_NOT_FOUND'
1294
                ]);
1295
            }
1296
 
1297
 
1298
            if(!$currentCompany->internal) {
1299
                return new JsonModel([
1300
                    'success'   => false,
1301
                    'data'      => 'ERROR_INTERNAL_COMPANY_ONLY'
1302
                ]);
1303
            }
1304
 
1305
 
1306
 
1307
            $result = $companyUserMapper->delete($companyUser->id);
1308
            if($result) {
1309
                $this->logger->info('La relación del usuario : ' . $user->email . ' con la empresa : ' . $currentCompany->name  . ' ha sido eliminada ', ['user_id' => $currentUser->id, 'ip' => Functions::getUserIP()]);
1310
 
1311
                return new JsonModel([
1312
                    'success'   => true,
1313
                    'data'      => 'LABEL_USER_COMPANY_HAS_BEEN_DELETED',
1314
                ]);
1315
            }  else {
1316
 
1317
                return new JsonModel([
1318
                    'success'   => false,
1319
                    'data'      => $userMapper->getError()
1320
                ]);
1321
            }
1322
 
1323
 
1324
        }
1325
 
1326
 
1327
 
1328
        return new JsonModel([
1329
            'success' => false,
1330
            'data' => 'ERROR_METHOD_NOT_ALLOWED'
1331
        ]);
1332
    }
1333
 
1334
 
1335
    public function uploadAction()
1336
    {
1337
        $request = $this->getRequest();
1338
 
1339
        $currentUserPlugin = $this->plugin('currentUserPlugin');
1340
        $currentUser    = $currentUserPlugin->getUser();
1341
        $currentCompany = $currentUserPlugin->getCompany();
1342
 
1343
        $request    = $this->getRequest();
1344
 
1345
        if($request->isPost()) {
1346
 
1347
            $step = filter_var( $this->params()->fromPost('step'), FILTER_SANITIZE_STRING);
1348
            if($step == 'validation') {
1349
                $userMapper = UserMapper::getInstance($this->adapter);
1350
                $companyUserMapper = CompanyUserMapper::getInstance($this->adapter);
1351
 
1352
                $form = new  UserUploadForm();
1353
                $dataPost = array_merge($request->getPost()->toArray(), $request->getFiles()->toArray());
1354
 
1355
                $form->setData($dataPost);
1356
 
1357
                if($form->isValid()) {
1358
 
1359
                    $file = $_FILES['file'];
1360
                    $tmp_filename = $file['tmp_name'];
1361
                    $final_filename =  'data/' . $file['name'];
1362
 
1363
                    if(!move_uploaded_file($tmp_filename, $final_filename)) {
1364
                        return new JsonModel([
1365
                            'success' => false,
1366
                            'data' => 'ERROR_UPLOAD_FILE'
1367
                        ]);
1368
                    }
1369
 
1370
 
1371
                    $users = [];
1372
 
1373
 
1374
                    $spreadsheet = IOFactory::load($final_filename);
1375
                    $records = $spreadsheet->getActiveSheet()->toArray(null, true, true, true);
1376
 
1377
                    $emails = [];
1378
 
1379
                    foreach($records as $record)
1380
                    {
1381
                        //A = Nombre 	B = Apellidos	C = Email 	D = contraseña
1382
 
1383
 
1384
                        $email = trim(filter_var($record['C'], FILTER_SANITIZE_EMAIL));
1385
                        $first_name = trim(filter_var($record['A'], FILTER_SANITIZE_STRING));
1386
                        $last_name = trim(filter_var($record['B'], FILTER_SANITIZE_STRING));
1387
                        $password = trim(filter_var($record['D'], FILTER_SANITIZE_STRING));
1388
 
1389
                        if(empty($first_name) || empty($last_name) || !filter_var($email, FILTER_VALIDATE_EMAIL) ||  empty($password)) {
1390
                            continue;
1391
                        }
1392
 
1393
                        if(!in_array($email, $emails)) {
1394
 
1395
                            $user = $userMapper->fetchOneByEmail($email);
1396
 
1397
                            array_push($emails, $email);
1398
                            array_push($users, [
1399
                                'first_name' => $first_name,
1400
                                'last_name' => $last_name,
1401
                                'password'  => $password,
1402
                                'email' => $email,
1403
                            ]);
1404
                        }
1405
 
1406
 
1407
 
1408
 
1409
 
1410
                    }
1411
 
1412
                    $key = md5($currentUser->id . '-' . microtime(true));
1413
                    $this->cache->setItem($key, serialize($users));
1414
 
1415
                    return new JsonModel([
1416
                        'success' => true,
1417
                        'data' => [
1418
                            'key' => $key,
1419
                            'items' => $users,
1420
                        ]
1421
                    ]);
1422
 
1423
 
1424
 
1425
                } else {
1426
                    $messages = [];
1427
                    $form_messages = (array) $form->getMessages();
1428
                    foreach($form_messages  as $fieldname => $field_messages)
1429
                    {
1430
 
1431
                        $messages[$fieldname] = array_values($field_messages);
1432
                    }
1433
 
1434
                    return new JsonModel([
1435
                        'success'   => false,
1436
                        'data'   => $messages
1437
                    ]);
1438
                }
1439
            } else if($step == 'process') {
1440
 
1441
                $key = filter_var( $this->params()->fromPost('key'), FILTER_SANITIZE_STRING);
1442
                if(!$key) {
1443
                    return new JsonModel([
1444
                        'success' => false,
1445
                        'data' => 'ERROR_CACHE_KEY_EMPTY'
1446
                    ]);
1447
                }
1448
 
1449
                $value = $this->cache->getItem($key);
1450
                if(!$value) {
1451
 
1452
                    return new JsonModel([
1453
                        'success' => false,
1454
                        'data' => 'ERROR_CACHE_NOT_FOUND'
1455
                    ]);
1456
                }
1457
 
1458
                $records = unserialize($value);
1459
                if(!$records) {
1460
                    return new JsonModel([
1461
                        'success' => false,
1462
                        'data' => 'ERROR_CACHE_INVALID'
1463
                    ]);
1464
                }
1465
 
1466
                $userMapper = UserMapper::getInstance($this->adapter);
1467
                $userPasswordMapper = UserPasswordMapper::getInstance($this->adapter);
1468
                $companyUserMapper = CompanyUserMapper::getInstance($this->adapter);
1469
 
1470
                $users_created = 0;
1471
                $user_ids = [];
1472
                foreach($records as $record)
1473
                {
1474
                    $first_name = $record['first_name'];
1475
                    $last_name = $record['last_name'];
1476
                    $password = $record['password'];
1477
                    $email = $record['email'];
1478
 
1479
 
1480
                    $user = $userMapper->fetchOneByEmail($email);
1481
                    if(!$user) {
1482
                        $password_hash = password_hash($password, PASSWORD_DEFAULT);
1483
 
1484
                        $user = new User();
1485
 
1486
                        $user->blocked = User::BLOCKED_NO;
1487
                        $user->email_verified = User::EMAIL_VERIFIED_YES;
1488
                        $user->email = $email;
1489
                        $user->first_name = $first_name;
1490
                        $user->last_name = $last_name;
1491
                        $user->password = $password_hash;
1492
                        $user->login_attempt = 0;
1493
                        $user->usertype_id = UserType::USER;
1494
                        $user->status = User::STATUS_ACTIVE;
1495
 
1496
                        $result = $userMapper->insert($user);
1497
                        if($result) {
1498
                            $userPassword = new UserPassword();
1499
                            $userPassword->user_id = $user->id;
1500
                            $userPassword->password = $password_hash;
1501
                            $userPasswordMapper->insert($userPassword);
1502
                        } else {
1503
                            continue;
1504
                        }
1505
                    }
1506
 
1507
                    if(!in_array($user->id, $user_ids)) {
1508
                        array_push($user_ids, $user->id);
1509
                    }
1510
                }
1511
 
1512
                foreach($user_ids as $user_id)
1513
                {
1514
                    $companyUser = $companyUserMapper->fetchOneByCompanyIdAndUserId($currentCompany->id, $user_id);
1515
                    if(!$companyUser) {
1516
 
1517
                        $companyUser = new CompanyUser();
1518
                        $companyUser->company_id = $currentCompany->id;
1519
                        $companyUser->user_id = $user_id;
1520
                        $companyUser->backend = CompanyUser::BACKEND_NO;
1521
                        $companyUser->creator = CompanyUser::CREATOR_NO;
1522
                        $companyUser->owner = CompanyUser::OWNER_NO;
1523
                        $companyUser->status = CompanyUser::STATUS_ADMIN_WILL_ADD;
1524
 
1525
                        if($companyUserMapper->insert($companyUser)) {
1526
                            $users_created++;
1527
                        }
1528
 
1529
                    }
1530
 
1531
                }
1532
 
1533
                $this->logger->info('Se agregaron ' . $users_created . ' usuarios  la empresa ' . $currentCompany->name, ['user_id' => $currentUser->id, 'ip' => Functions::getUserIP()]);
1534
 
1535
                return new JsonModel([
1536
                    'success' => true,
1537
                    'data' => [
1538
                        'users_created' => $users_created
1539
                    ]
1540
                ]);
1541
 
1542
 
1543
 
1544
 
1545
            } else {
1546
                return new JsonModel([
1547
                    'success' => false,
1548
                    'data' => 'ERROR_PARAMETERS_ARE_INVALID'
1549
                ]);
1550
            }
1551
 
1552
 
1553
 
1554
 
1555
        }
1556
 
1557
        return new JsonModel([
1558
            'success' => false,
1559
            'data' => 'ERROR_METHOD_NOT_ALLOWED'
1560
        ]);
1561
    }
1562
 
1563
 
1564
    public function editAction()
1565
    {
1566
        $currentUserPlugin = $this->plugin('currentUserPlugin');
1567
        $currentUser = $currentUserPlugin->getUser();
1568
        $currentCompany = $currentUserPlugin->getCompany();
1569
 
1570
        $request = $this->getRequest();
1571
        $uuid = $this->params()->fromRoute('id');
1572
 
1573
 
1574
        if(!$uuid) {
1575
            $data = [
1576
                'success'   => false,
1577
                'data'   => 'ERROR_INVALID_PARAMETER'
1578
            ];
1579
 
1580
            return new JsonModel($data);
1581
        }
1582
 
1583
        $userMapper = UserMapper::getInstance($this->adapter);
1584
        $user = $userMapper->fetchOneByUuid($uuid);
1585
        if(!$user) {
1586
            $data = [
1587
                'success'   => false,
1588
                'data'   => 'ERROR_COMPANY_NOT_FOUND'
1589
            ];
1590
 
1591
            return new JsonModel($data);
1592
        }
1593
 
1594
        $companyUserMapper = CompanyUserMapper::getInstance($this->adapter);
1595
        $companyUser = $companyUserMapper->fetchOneByCompanyIdAndUserId($currentCompany->id, $user->id);
1596
        if(!$companyUser) {
1597
            return new JsonModel([
1598
                'success'   => false,
1599
                'data'   => 'ERROR_COMPANY_USER_NOT_FOUND'
1600
            ]);
1601
 
1602
        }
1603
 
1604
        if($companyUser->status != CompanyUser::STATUS_ACCEPTED && $companyUser->status != CompanyUser::STATUS_ADMIN_WILL_ADD) {
1605
            return new JsonModel([
1606
                'success'   => false,
1607
                'data'   => 'ERROR_COMPANY_USER_IS_NOT_ACTIVE'
1608
            ]);
1609
        }
1610
 
1611
 
1612
 
1613
 
1614
        if($request->isPost()) {
1615
 
1616
            $companyRoleMapper = CompanyRoleMapper::getInstance($this->adapter);
1617
            $companyUserMapper = CompanyUserMapper::getInstance($this->adapter);
1618
            $companyUserRoleMapper = CompanyUserRoleMapper::getInstance($this->adapter);
1619
 
1620
            $backend = filter_var( $this->params()->fromPost('backend'), FILTER_SANITIZE_STRING );
1621
            $companyUser->backend = $backend == CompanyUser::BACKEND_YES ? CompanyUser::BACKEND_YES : CompanyUser::BACKEND_NO;
1622
            $companyUserMapper->update($companyUser);
1623
 
1624
 
1625
            $roleMapper = RoleMapper::getInstance($this->adapter);
1626
            $roles = $roleMapper->fetchAll();
1627
 
1628
 
1629
            foreach($roles as $role)
1630
            {
1631
                $companyRole = $companyRoleMapper->fetchOneByCompanyIdAndRoleId($currentCompany->id, $role->id);
1632
                if(!$companyRole) {
1633
                    $companyUserRoleMapper->deleteByCompanyIdAndRoleId($currentCompany->id, $role->id);
1634
                    continue;
1635
                }
1636
 
1637
                $checked     = filter_var( $this->params()->fromPost('checked' . $role->id), FILTER_SANITIZE_NUMBER_INT);
1638
 
1639
                if($checked) {
1640
 
1641
                    $companyUserRole = $companyUserRoleMapper->fetchOneByCompanyIdAndUserIdAndRoleId($currentCompany->id, $user->id, $role->id);
1642
                    if(!$companyUserRole) {
1643
 
1644
                        $companyUserRole = new CompanyUserRole();
1645
                        $companyUserRole->company_id = $currentCompany->id;
1646
                        $companyUserRole->role_id = $role->id;
1647
                        $companyUserRole->user_id = $user->id;
1648
 
1649
                        $companyUserRoleMapper->insert($companyUserRole);
1650
 
1651
                    }
1652
 
1653
 
1654
 
1655
 
1656
                } else {
1657
 
1658
                    $companyUserRoleMapper->deleteByCompanyIdAndUserIdAndRoleId($currentCompany->id, $user->id, $role->id);
1659
                }
1660
            }
1661
 
1662
            $this->logger->info('Se actualizo los roles del usuario : ' . $user->email . ' en la empresa ' . $currentCompany->name, ['user_id' => $currentUser->id, 'ip' => Functions::getUserIP()]);
1663
 
1664
            return new JsonModel([
1665
                'success' => true,
1666
                'data' => 'LABEL_RECORD_UPDATED'
1667
            ]);
1668
 
1669
 
1670
        } else if ($request->isGet()) {
1671
            $companyServiceMapper = CompanyServiceMapper::getInstance($this->adapter);
1672
 
1673
            $roleMapper = RoleMapper::getInstance($this->adapter);
1674
            $records = $roleMapper->fetchAll();
1675
 
1676
            $companyRoleMapper = CompanyRoleMapper::getInstance($this->adapter);
1677
            $companyUserRoleMapper = CompanyUserRoleMapper::getInstance($this->adapter);
1678
 
1679
            $roles = [];
1680
            foreach($records as $record)
1681
            {
1682
                if($record->creator == Role::CREATOR_YES) {
1683
                    continue;
1684
                }
1685
 
1686
                if($record->service_id) {
1687
                    $companyService = $companyServiceMapper->fetchOneByCompanyIdAndServiceId($currentCompany->id, $record->service_id);
1688
                    if(!$companyService || $companyService->status == CompanyService::INACTIVE) {
1689
                        continue;
1690
                    }
1691
 
1692
                }
1693
 
1694
 
1695
 
1696
                $companyRole = $companyRoleMapper->fetchOneByCompanyIdAndRoleId($currentCompany->id, $record->id);
1697
                if(!$companyRole) {
1698
                    continue;
1699
                }
1700
 
1701
                $companyUserRole  = $companyUserRoleMapper->fetchOneByCompanyIdAndUserIdAndRoleId($currentCompany->id, $user->id, $record->id);
1702
 
1703
 
1704
                $roles[ $record->id ] = [
1705
                    'id' => $record->id,
1706
                    'name' => $record->name,
1707
                    'fixed' => $record->creator == Role::CREATOR_YES ? true : false,
1708
                    'checked' => $companyUserRole ? true : false,
1709
                ];
1710
            }
1711
 
1712
 
1713
 
1714
            $data = [
1715
                'success' => true,
1716
                'data' => [
1717
                   'backend' => $companyUser->backend == CompanyUser::BACKEND_YES ? 1 : 0,
1718
                   'roles' => $roles,
1719
                ] ,
1720
            ];
1721
 
1722
 
1723
 
1724
            return new JsonModel($data);
1725
        } else {
1726
            $data = [
1727
                'success' => false,
1728
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
1729
            ];
1730
 
1731
            return new JsonModel($data);
1732
        }
1733
 
1734
        return new JsonModel($data);
1735
    }
1736
 
1737
 
1738
}