Proyectos de Subversion LeadersLinked - Backend

Rev

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

Rev Autor Línea Nro. Línea
1 www 1
<?php
2
declare(strict_types=1);
3
 
4
namespace LeadersLinked\Controller;
5
 
6
use Laminas\Db\Adapter\AdapterInterface;
7
use Laminas\Cache\Storage\Adapter\AbstractAdapter;
8
 
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
 
129 efrain 692
    public function emailVerifyAction()
693
    {
694
        $currentUserPlugin = $this->plugin('currentUserPlugin');
695
        $currentUser = $currentUserPlugin->getUser();
696
        $request = $this->getRequest();
697
 
698
 
699
        if($request->isPost()) {
700
 
701
            $uuid = $this->params()->fromRoute('id');
702
            if(!$uuid) {
703
                return new JsonModel([
704
                    'success'   => false,
705
                    'data'      => 'ERROR_INVALID_PARAMETER'
706
                ]);
707
            }
708
 
709
            $userMapper = UserMapper::getInstance($this->adapter);
710
            $user = $userMapper->fetchOneByUuid($uuid);
711
 
712
            if(!$user) {
713
                return new JsonModel([
714
                    'success'   => false,
715
                    'data'      => 'ERROR_USER_NOT_FOUND'
716
                ]);
717
            }
718
 
719
            if($user->blocked == User::BLOCKED_NO) {
720
                return new JsonModel([
721
                    'success'   => false,
722
                    'data'      => 'ERROR_USER_IS_NOT_PENDING_FOR_EMAIL_VERIFY'
723
                ]);
724
            }
725
 
726
 
727
 
728
            $result = $userMapper->emailVerifyAndActive($user);
729
            if($result) {
730
                $this->logger->info('El usuario : ' . $user->email . ' ha sido desbloqueado ', ['user_id' => $currentUser->id, 'ip' => Functions::getUserIP()]);
731
 
732
                return new JsonModel([
733
                    'success'   => true,
734
                    'data'      => 'LABEL_USER_HAS_BEEN_UNBLOCKED',
735
                ]);
736
            }  else {
737
 
738
                return new JsonModel([
739
                    'success'   => false,
740
                    'data'      => $userMapper->getError()
741
                ]);
742
            }
743
 
744
 
745
        }
746
 
747
 
748
 
749
        return new JsonModel([
750
            'success' => false,
751
            'data' => 'ERROR_METHOD_NOT_ALLOWED'
752
        ]);
753
    }
754
 
1 www 755
    public function changePasswordAction()
756
    {
757
        $currentUserPlugin = $this->plugin('currentUserPlugin');
758
        $currentUser = $currentUserPlugin->getUser();
759
 
760
        $request = $this->getRequest();
761
 
762
        if($request->isGet()) {
763
            $uuid = $this->params()->fromRoute('id');
764
            if(!$uuid) {
765
                return new JsonModel([
766
                    'success'   => false,
767
                    'data'      => 'ERROR_INVALID_PARAMETER'
768
                ]);
769
            }
770
 
771
            $userMapper = UserMapper::getInstance($this->adapter);
772
            $user = $userMapper->fetchOneByUuid($uuid);
773
 
774
 
775
 
776
            if($user) {
777
                return new JsonModel([
778
                    'success'   => true,
779
                    'data'      => [
780
                        'first_name' => $user->first_name,
781
                        'last_name' => $user->last_name,
782
                        'email' => $user->email,
783
                    ]
784
                ]);
785
            } else {
786
                return new JsonModel([
787
                    'success'   => false,
788
                    'data'      => 'ERROR_USER_NOT_FOUND'
789
                ]);
790
            }
791
 
792
        }
793
 
794
        if($request->isPost()) {
795
 
796
            $uuid = $this->params()->fromRoute('id');
797
            if(!$uuid) {
798
                return new JsonModel([
799
                    'success'   => false,
800
                    'data'      => 'ERROR_INVALID_PARAMETER'
801
                ]);
802
            }
803
 
804
            $userMapper = UserMapper::getInstance($this->adapter);
805
            $user = $userMapper->fetchOneByUuid($uuid);
806
 
807
            if(!$user) {
808
                return new JsonModel([
809
                    'success'   => false,
810
                    'data'      => 'ERROR_USER_NOT_FOUND'
811
                ]);
812
            }
813
 
814
 
815
            $dataPost = $request->getPost()->toArray();
816
            $form = new ChangePasswordForm();
817
            $form->setData($dataPost);
818
 
819
            if($form->isValid()) {
820
 
821
 
822
 
823
                $data = (array) $form->getData();
824
                $password = $data['password'];
825
 
826
 
827
 
828
                $userPasswordMapper = UserPasswordMapper::getInstance($this->adapter);
829
                $userPasswords = $userPasswordMapper->fetchAllByUserId($user->id);
830
 
831
                $oldPassword = false;
832
                foreach($userPasswords as $userPassword)
833
                {
834
                    if(password_verify($password, $userPassword->password) || (md5($password) == $userPassword->password))
835
                    {
836
                        $oldPassword = true;
837
                        break;
838
                    }
839
                }
840
 
841
                if($oldPassword) {
842
                    $this->logger->err('Cambio de contraseña del usuario - error contraseña ya utilizada anteriormente', ['user_id' =>  $currentUser->id, 'ip' => Functions::getUserIP()]);
843
 
844
                    return new JsonModel([
845
                        'success'   => false,
846
                        'data'      => 'ERROR_PASSWORD_HAS_ALREADY_BEEN_USED'
847
 
848
                    ]);
849
                } else {
850
                    $password_hash = password_hash($password, PASSWORD_DEFAULT);
851
 
852
 
853
                    $result = $userMapper->updatePassword($user, $password_hash);
854
                    if($result) {
855
                        $this->logger->info('Cambio de contraseña del usuario realizado', ['user_id' => $currentUser->id, 'ip' => Functions::getUserIP()]);
856
 
857
 
858
                        return new JsonModel([
859
                            'success'   => true,
860
                            'data'      => 'LABEL_YOUR_PASSWORD_HAS_BEEN_UPDATED'
861
 
862
                        ]);
863
                    } else {
864
                        $this->logger->err('Cambio de contraseña del usuario - error desconocido', ['user_id' => $currentUser->id, 'ip' => Functions::getUserIP()]);
865
 
866
                        return new JsonModel([
867
                            'success'   => true,
868
                            'data'      => 'ERROR_THERE_WAS_AN_ERROR'
869
 
870
                        ]);
871
                    }
872
                }
873
 
874
            } else {
875
                $messages = [];
876
 
877
                $form_messages = (array) $form->getMessages();
878
                foreach($form_messages  as $fieldname => $field_messages)
879
                {
880
                    $messages[$fieldname] = array_values($field_messages);
881
                }
882
 
883
                return new JsonModel([
884
                    'success'   => false,
885
                    'data'   => $messages
886
                ]);
887
            }
888
 
889
        }
890
 
891
 
892
 
893
        return new JsonModel([
894
            'success' => false,
895
            'data' => 'ERROR_METHOD_NOT_ALLOWED'
896
        ]);
897
    }
898
 
899
    public function cancelAction()
900
    {
901
        $currentUserPlugin = $this->plugin('currentUserPlugin');
902
        $currentUser = $currentUserPlugin->getUser();
903
 
904
        $currentCompany = $currentUserPlugin->getCompany();
905
 
906
        $request = $this->getRequest();
907
 
908
 
909
        if($request->isPost()) {
910
 
911
            $uuid = $this->params()->fromRoute('id');
912
            if(!$uuid) {
913
                return new JsonModel([
914
                    'success'   => false,
915
                    'data'      => 'ERROR_INVALID_PARAMETER'
916
                ]);
917
            }
918
 
919
            $userMapper = UserMapper::getInstance($this->adapter);
920
            $user = $userMapper->fetchOneByUuid($uuid);
921
 
922
            if(!$user) {
923
                return new JsonModel([
924
                    'success'   => false,
925
                    'data'      => 'ERROR_USER_COMPANY_NOT_FOUND'
926
                ]);
927
            }
928
 
929
            $companyUserMapper = CompanyUserMapper::getInstance($this->adapter);
930
            $companyUser = $companyUserMapper->fetchOneByCompanyIdAndUserId($currentCompany->id, $user->id);
931
 
932
            if(!$companyUser) {
933
                return new JsonModel([
934
                    'success'   => false,
935
                    'data'      => 'ERROR_USER_NOT_FOUND'
936
                ]);
937
            }
938
 
939
 
940
            if(!in_array($companyUser->status, [  CompanyUser::STATUS_ADMIN_WILL_ADD, CompanyUser::STATUS_ACCEPTED])) {
941
                return new JsonModel([
942
                    'success'   => false,
943
                    'data'      => 'ERROR_USER_COMPANY_WRONG_STATUS'
944
                ]);
945
            }
946
 
947
            $companyUser->status = CompanyUser::STATUS_CANCELLED;
948
            $result = $companyUserMapper->update($companyUser);
949
            if($result) {
950
                $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()]);
951
 
952
                return new JsonModel([
953
                    'success'   => true,
954
                    'data'      => 'LABEL_USER_COMPANY_HAS_BEEN_CANCELLED',
955
                ]);
956
            }  else {
957
 
958
                return new JsonModel([
959
                    'success'   => false,
960
                    'data'      => $userMapper->getError()
961
                ]);
962
            }
963
 
964
 
965
        }
966
 
967
 
968
 
969
        return new JsonModel([
970
            'success' => false,
971
            'data' => 'ERROR_METHOD_NOT_ALLOWED'
972
        ]);
973
    }
974
 
975
    public function acceptAction()
976
    {
977
        $currentUserPlugin = $this->plugin('currentUserPlugin');
978
        $currentUser = $currentUserPlugin->getUser();
979
 
980
        $currentCompany = $currentUserPlugin->getCompany();
981
 
982
        $request = $this->getRequest();
983
 
984
 
985
        if($request->isPost()) {
986
 
987
            $uuid = $this->params()->fromRoute('id');
988
            if(!$uuid) {
989
                return new JsonModel([
990
                    'success'   => false,
991
                    'data'      => 'ERROR_INVALID_PARAMETER'
992
                ]);
993
            }
994
 
995
            $userMapper = UserMapper::getInstance($this->adapter);
996
            $user = $userMapper->fetchOneByUuid($uuid);
997
 
998
            if(!$user) {
999
                return new JsonModel([
1000
                    'success'   => false,
1001
                    'data'      => 'ERROR_USER_NOT_FOUND'
1002
                ]);
1003
            }
1004
 
1005
            $companyUserMapper = CompanyUserMapper::getInstance($this->adapter);
1006
            $companyUser = $companyUserMapper->fetchOneByCompanyIdAndUserId($currentCompany->id, $user->id);
1007
 
1008
            if(!$companyUser) {
1009
                return new JsonModel([
1010
                    'success'   => false,
1011
                    'data'      => 'ERROR_USER_NOT_FOUND'
1012
                ]);
1013
            }
1014
 
1015
            if($companyUser->status != CompanyUser::STATUS_PENDING
1016
                && $companyUser->status != CompanyUser::STATUS_SENT
1017
                && $companyUser->status != CompanyUser::STATUS_CANCELLED
1018
                && $companyUser->status != CompanyUser::STATUS_REJECTED) {
1019
                return new JsonModel([
1020
                    'success'   => false,
1021
                    'data'      => 'ERROR_USER_COMPANY_WRONG_STATUS'
1022
                ]);
1023
            }
1024
 
1025
            $companyUser->status = CompanyUser::STATUS_ACCEPTED;
1026
            $result = $companyUserMapper->update($companyUser);
1027
            if($result) {
1028
                $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()]);
1029
 
1030
                return new JsonModel([
1031
                    'success'   => true,
1032
                    'data'      => 'LABEL_USER_COMPANY_HAS_BEEN_ACCEPTED'
1033
                ]);
1034
            }  else {
1035
 
1036
                return new JsonModel([
1037
                    'success'   => false,
1038
                    'data'      => $userMapper->getError()
1039
                ]);
1040
            }
1041
 
1042
 
1043
        }
1044
 
1045
 
1046
 
1047
        return new JsonModel([
1048
            'success' => false,
1049
            'data' => 'ERROR_METHOD_NOT_ALLOWED'
1050
        ]);
1051
    }
1052
 
1053
    public function rejectAction()
1054
    {
1055
        $currentUserPlugin = $this->plugin('currentUserPlugin');
1056
        $currentUser = $currentUserPlugin->getUser();
1057
 
1058
        $currentCompany = $currentUserPlugin->getCompany();
1059
 
1060
        $request = $this->getRequest();
1061
 
1062
 
1063
        if($request->isPost()) {
1064
 
1065
            $uuid = $this->params()->fromRoute('id');
1066
            if(!$uuid) {
1067
                return new JsonModel([
1068
                    'success'   => false,
1069
                    'data'      => 'ERROR_INVALID_PARAMETER'
1070
                ]);
1071
            }
1072
 
1073
            $userMapper = UserMapper::getInstance($this->adapter);
1074
            $user = $userMapper->fetchOneByUuid($uuid);
1075
 
1076
            if(!$user) {
1077
                return new JsonModel([
1078
                    'success'   => false,
1079
                    'data'      => 'ERROR_USER_NOT_FOUND'
1080
                ]);
1081
            }
1082
 
1083
            $companyUserMapper = CompanyUserMapper::getInstance($this->adapter);
1084
            $companyUser = $companyUserMapper->fetchOneByCompanyIdAndUserId($currentCompany->id, $user->id);
1085
 
1086
            if(!$companyUser) {
1087
                return new JsonModel([
1088
                    'success'   => false,
1089
                    'data'      => 'ERROR_USER_COMPANY_NOT_FOUND'
1090
                ]);
1091
            }
1092
 
1093
            if($companyUser->status != CompanyUser::STATUS_PENDING
1094
                && $companyUser->status != CompanyUser::STATUS_SENT) {
1095
                return new JsonModel([
1096
                    'success'   => false,
1097
                    'data'      => 'ERROR_USER_COMPANY_WRONG_STATUS'
1098
                ]);
1099
            }
1100
 
1101
            $companyUser->status = CompanyUser::STATUS_REJECTED;
1102
            $result = $companyUserMapper->update($companyUser);
1103
            if($result) {
1104
                $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()]);
1105
 
1106
                return new JsonModel([
1107
                    'success'   => true,
1108
                    'data'      => 'LABEL_USER_COMPANY_HAS_BEEN_REJECTED',
1109
                ]);
1110
            }  else {
1111
 
1112
                return new JsonModel([
1113
                    'success'   => false,
1114
                    'data'      => $userMapper->getError()
1115
                ]);
1116
            }
1117
 
1118
 
1119
        }
1120
 
1121
 
1122
 
1123
        return new JsonModel([
1124
            'success' => false,
1125
            'data' => 'ERROR_METHOD_NOT_ALLOWED'
1126
        ]);
1127
    }
1128
 
1129
    public function inviteAction()
1130
    {
1131
        $currentUserPlugin = $this->plugin('currentUserPlugin');
1132
        $currentUser = $currentUserPlugin->getUser();
1133
 
1134
        $currentCompany = $currentUserPlugin->getCompany();
1135
 
1136
        $request = $this->getRequest();
1137
 
1138
        if($request->isGet()) {
1139
 
1140
            $search = trim(filter_var( $this->params()->fromQuery('search'), FILTER_SANITIZE_STRING)) ;
1141
            if(strlen($search) >= 3) {
1142
 
1143
                $userMapper = UserMapper::getInstance($this->adapter);
1144
                $records  = $userMapper->fetchAllSuggestForInvitationByCompanyId($currentCompany->id, $search);
1145
 
1146
                $users = [];
1147
                foreach($records as $record)
1148
                {
1149
                    array_push($users, [
1150
                        'value' => $record->uuid,
1151
                        'text' => trim($record->first_name . ' ' . $record->last_name) . ' (' . $record->email . ')'
1152
 
1153
                    ]);
1154
                }
1155
 
1156
                return new JsonModel([
1157
                    'success' => true,
1158
                    'data' => $users
1159
                ]);
1160
 
1161
 
1162
 
1163
 
1164
            } else {
1165
                return new JsonModel([
1166
                    'success' => true,
1167
                    'data' => [
1168
 
1169
                    ]
1170
                ]);
1171
            }
1172
 
1173
 
1174
 
1175
 
1176
 
1177
 
1178
        } else if($request->isPost()) {
1179
 
1180
            $uuid = $this->params()->fromPost('id');
1181
            if(!$uuid) {
1182
                return new JsonModel([
1183
                    'success'   => false,
1184
                    'data'      => 'ERROR_INVALID_PARAMETER'
1185
                ]);
1186
            }
1187
 
1188
            $userMapper = UserMapper::getInstance($this->adapter);
1189
            $user = $userMapper->fetchOneByUuid($uuid);
1190
 
1191
            if(!$user) {
1192
                return new JsonModel([
1193
                    'success'   => false,
1194
                    'data'      => 'ERROR_USER_NOT_FOUND'
1195
                ]);
1196
            }
1197
 
1198
            if($user->status != User::STATUS_ACTIVE) {
1199
                return new JsonModel([
1200
                    'success'   => false,
1201
                    'data'      => 'ERROR_USER_IS_INACTIVE'
1202
                ]);
1203
            }
1204
 
1205
 
1206
 
1207
 
1208
 
1209
            $companyUserMapper = CompanyUserMapper::getInstance($this->adapter);
1210
            $companyUser = $companyUserMapper->fetchOneByCompanyIdAndUserId($currentCompany->id, $user->id);
1211
 
1212
            if($companyUser && $companyUser->status == CompanyUser::STATUS_ACCEPTED) {
1213
                return new JsonModel([
1214
                    'success'   => false,
1215
                    'data'      => 'ERROR_USER_COMPANY_FOUND'
1216
                ]);
1217
            }
1218
 
1219
 
1220
 
1221
            if($companyUser) {
1222
 
1223
                $companyUser->status = CompanyUser::STATUS_ADMIN_WILL_ADD;
1224
                $result = $companyUserMapper->update($companyUser);
1225
 
1226
            } else {
1227
                $companyUser = new CompanyUser();
1228
                $companyUser->company_id = $currentCompany->id;
1229
                $companyUser->backend = CompanyUser::BACKEND_NO;
1230
                $companyUser->creator = CompanyUser::CREATOR_NO;
1231
                $companyUser->owner = CompanyUser::OWNER_NO;
1232
                $companyUser->status = CompanyUser::STATUS_ADMIN_WILL_ADD;
1233
                $companyUser->user_id = $user->id;
1234
 
1235
 
1236
 
1237
                $result = $companyUserMapper->insert($companyUser);
1238
            }
1239
 
1240
 
1241
 
1242
            if($result) {
1243
 
1244
 
1245
                $notification = new Notification();
1246
                $notification->type     = Notification::TYPE_RECEIVE_INVITATION_COMPANY;
1247
                $notification->read     = Notification::NO;
1248
                $notification->user_id  = $user->id;
1249
                $notification->company_id = $currentCompany->id;
1250
                $notification->message  = 'LABEL_NOTIFICATION_RECEIVE_INVITATION_COMPANY';
1251
                $notification->url      = 'company/view/' . $currentCompany->uuid;
1252
 
1253
                $notificationMapper = NotificationMapper::getInstance($this->adapter);
1254
                $notificationMapper->insert($notification);
1255
 
1256
                $userNotificationMapper = UserNotificationSettingMapper::getInstance($this->adapter);
1257
                $userNotification = $userNotificationMapper->fetchOne($user->id);
1258
 
1259
                if($userNotification && $userNotification->receive_invitation_company)
1260
                {
1261
                    $emailTemplateMapper = EmailTemplateMapper::getInstance($this->adapter);
1262
                    $emailTemplate = $emailTemplateMapper->fetchOne(EmailTemplate::ID_RECEIVE_INVITATION_COMPANY);
1263
 
1264
                    if($emailTemplate) {
1265
 
1266
                        $sandbox = $this->config['leaderslinked.runmode.sandbox'];
1267
                        if($sandbox) {
1268
                            $company_profile_url = $this->config['leaderslinked.frontend.sandbox_company_profile'];
1269
                        } else {
1270
                            $company_profile_url = $this->config['leaderslinked.frontend.production_company_profile'];
1271
                        }
1272
 
1273
                        $company_profile_url = str_replace('[uuid]', $currentCompany->uuid, $company_profile_url);
1274
 
1275
                        $arrayCont = [
1276
                            'firstname'             => $currentUser->first_name,
1277
                            'lastname'              => $currentUser->last_name,
1278
                            'other_user_firstname'  => $user->first_name,
1279
                            'other_user_lastname'   => $user->last_name,
1280
                            'company_name'          => $currentCompany->name,
1281
                            'group_name'            => '',
1282
                            'content'               => '',
1283
                            'code'                  => '',
1284
                            'link'                  => $company_profile_url,
1285
                        ];
1286
 
1287
                        $email = new QueueEmail($this->adapter);
1288
                        $email->processEmailTemplate($emailTemplate, $arrayCont, $user->email, trim($user->first_name . ' ' . $user->last_name));
1289
                    }
1290
                }
1291
 
1292
 
1293
                $this->logger->info('La empresa : ' . $currentCompany->name . ' envio al usuario : ' . $user->email . ' una invitación ', ['user_id' => $currentUser->id, 'ip' => Functions::getUserIP()]);
1294
 
1295
                return new JsonModel([
1296
                    'success'   => true,
1297
                    'data'      => 'LABEL_USER_COMPANY_HAS_BEEN_SENT',
1298
                ]);
1299
            }  else {
1300
 
1301
                return new JsonModel([
1302
                    'success'   => false,
1303
                    'data'      => $userMapper->getError()
1304
                ]);
1305
            }
1306
 
1307
 
1308
        }
1309
 
1310
 
1311
 
1312
        return new JsonModel([
1313
            'success' => false,
1314
            'data' => 'ERROR_METHOD_NOT_ALLOWED'
1315
        ]);
1316
    }
1317
 
1318
 
1319
    public function deleteAction()
1320
    {
1321
        $currentUserPlugin = $this->plugin('currentUserPlugin');
1322
        $currentUser = $currentUserPlugin->getUser();
1323
 
1324
        $currentCompany = $currentUserPlugin->getCompany();
1325
 
1326
        $request = $this->getRequest();
1327
 
1328
 
1329
        if($request->isPost()) {
1330
 
1331
            $uuid = $this->params()->fromRoute('id');
1332
            if(!$uuid) {
1333
                return new JsonModel([
1334
                    'success'   => false,
1335
                    'data'      => 'ERROR_INVALID_PARAMETER'
1336
                ]);
1337
            }
1338
 
1339
            $userMapper = UserMapper::getInstance($this->adapter);
1340
            $user = $userMapper->fetchOneByUuid($uuid);
1341
 
1342
            if(!$user) {
1343
                return new JsonModel([
1344
                    'success'   => false,
1345
                    'data'      => 'ERROR_USER_NOT_FOUND'
1346
 
1347
                ]);
1348
            }
1349
 
1350
            $companyUserMapper = CompanyUserMapper::getInstance($this->adapter);
1351
            $companyUser = $companyUserMapper->fetchOneByCompanyIdAndUserId($currentCompany->id, $user->id);
1352
 
1353
            if($companyUser) {
1354
                return new JsonModel([
1355
                    'success'   => false,
1356
                    'data'      => 'ERROR_USER_COMPANY_NOT_FOUND'
1357
                ]);
1358
            }
1359
 
1360
 
1361
            if(!$currentCompany->internal) {
1362
                return new JsonModel([
1363
                    'success'   => false,
1364
                    'data'      => 'ERROR_INTERNAL_COMPANY_ONLY'
1365
                ]);
1366
            }
1367
 
1368
 
1369
 
1370
            $result = $companyUserMapper->delete($companyUser->id);
1371
            if($result) {
1372
                $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()]);
1373
 
1374
                return new JsonModel([
1375
                    'success'   => true,
1376
                    'data'      => 'LABEL_USER_COMPANY_HAS_BEEN_DELETED',
1377
                ]);
1378
            }  else {
1379
 
1380
                return new JsonModel([
1381
                    'success'   => false,
1382
                    'data'      => $userMapper->getError()
1383
                ]);
1384
            }
1385
 
1386
 
1387
        }
1388
 
1389
 
1390
 
1391
        return new JsonModel([
1392
            'success' => false,
1393
            'data' => 'ERROR_METHOD_NOT_ALLOWED'
1394
        ]);
1395
    }
1396
 
1397
 
1398
    public function uploadAction()
1399
    {
1400
        $request = $this->getRequest();
1401
 
1402
        $currentUserPlugin = $this->plugin('currentUserPlugin');
1403
        $currentUser    = $currentUserPlugin->getUser();
1404
        $currentCompany = $currentUserPlugin->getCompany();
1405
 
1406
        $request    = $this->getRequest();
1407
 
1408
        if($request->isPost()) {
1409
 
1410
            $step = filter_var( $this->params()->fromPost('step'), FILTER_SANITIZE_STRING);
1411
            if($step == 'validation') {
1412
                $userMapper = UserMapper::getInstance($this->adapter);
1413
                $companyUserMapper = CompanyUserMapper::getInstance($this->adapter);
1414
 
1415
                $form = new  UserUploadForm();
1416
                $dataPost = array_merge($request->getPost()->toArray(), $request->getFiles()->toArray());
1417
 
1418
                $form->setData($dataPost);
1419
 
1420
                if($form->isValid()) {
1421
 
1422
                    $file = $_FILES['file'];
1423
                    $tmp_filename = $file['tmp_name'];
1424
                    $final_filename =  'data/' . $file['name'];
1425
 
1426
                    if(!move_uploaded_file($tmp_filename, $final_filename)) {
1427
                        return new JsonModel([
1428
                            'success' => false,
1429
                            'data' => 'ERROR_UPLOAD_FILE'
1430
                        ]);
1431
                    }
1432
 
1433
 
1434
                    $users = [];
1435
 
1436
 
1437
                    $spreadsheet = IOFactory::load($final_filename);
1438
                    $records = $spreadsheet->getActiveSheet()->toArray(null, true, true, true);
1439
 
1440
                    $emails = [];
1441
 
1442
                    foreach($records as $record)
1443
                    {
1444
                        //A = Nombre 	B = Apellidos	C = Email 	D = contraseña
1445
 
1446
 
1447
                        $email = trim(filter_var($record['C'], FILTER_SANITIZE_EMAIL));
1448
                        $first_name = trim(filter_var($record['A'], FILTER_SANITIZE_STRING));
1449
                        $last_name = trim(filter_var($record['B'], FILTER_SANITIZE_STRING));
1450
                        $password = trim(filter_var($record['D'], FILTER_SANITIZE_STRING));
1451
 
1452
                        if(empty($first_name) || empty($last_name) || !filter_var($email, FILTER_VALIDATE_EMAIL) ||  empty($password)) {
1453
                            continue;
1454
                        }
1455
 
1456
                        if(!in_array($email, $emails)) {
1457
 
1458
                            $user = $userMapper->fetchOneByEmail($email);
1459
 
1460
                            array_push($emails, $email);
1461
                            array_push($users, [
1462
                                'first_name' => $first_name,
1463
                                'last_name' => $last_name,
1464
                                'password'  => $password,
1465
                                'email' => $email,
1466
                            ]);
1467
                        }
1468
 
1469
 
1470
 
1471
 
1472
 
1473
                    }
1474
 
1475
                    $key = md5($currentUser->id . '-' . microtime(true));
1476
                    $this->cache->setItem($key, serialize($users));
1477
 
1478
                    return new JsonModel([
1479
                        'success' => true,
1480
                        'data' => [
1481
                            'key' => $key,
1482
                            'items' => $users,
1483
                        ]
1484
                    ]);
1485
 
1486
 
1487
 
1488
                } else {
1489
                    $messages = [];
1490
                    $form_messages = (array) $form->getMessages();
1491
                    foreach($form_messages  as $fieldname => $field_messages)
1492
                    {
1493
 
1494
                        $messages[$fieldname] = array_values($field_messages);
1495
                    }
1496
 
1497
                    return new JsonModel([
1498
                        'success'   => false,
1499
                        'data'   => $messages
1500
                    ]);
1501
                }
1502
            } else if($step == 'process') {
1503
 
1504
                $key = filter_var( $this->params()->fromPost('key'), FILTER_SANITIZE_STRING);
1505
                if(!$key) {
1506
                    return new JsonModel([
1507
                        'success' => false,
1508
                        'data' => 'ERROR_CACHE_KEY_EMPTY'
1509
                    ]);
1510
                }
1511
 
1512
                $value = $this->cache->getItem($key);
1513
                if(!$value) {
1514
 
1515
                    return new JsonModel([
1516
                        'success' => false,
1517
                        'data' => 'ERROR_CACHE_NOT_FOUND'
1518
                    ]);
1519
                }
1520
 
1521
                $records = unserialize($value);
1522
                if(!$records) {
1523
                    return new JsonModel([
1524
                        'success' => false,
1525
                        'data' => 'ERROR_CACHE_INVALID'
1526
                    ]);
1527
                }
1528
 
1529
                $userMapper = UserMapper::getInstance($this->adapter);
1530
                $userPasswordMapper = UserPasswordMapper::getInstance($this->adapter);
1531
                $companyUserMapper = CompanyUserMapper::getInstance($this->adapter);
1532
 
1533
                $users_created = 0;
1534
                $user_ids = [];
1535
                foreach($records as $record)
1536
                {
1537
                    $first_name = $record['first_name'];
1538
                    $last_name = $record['last_name'];
1539
                    $password = $record['password'];
1540
                    $email = $record['email'];
1541
 
1542
 
1543
                    $user = $userMapper->fetchOneByEmail($email);
1544
                    if(!$user) {
1545
                        $password_hash = password_hash($password, PASSWORD_DEFAULT);
1546
 
1547
                        $user = new User();
1548
 
1549
                        $user->blocked = User::BLOCKED_NO;
1550
                        $user->email_verified = User::EMAIL_VERIFIED_YES;
1551
                        $user->email = $email;
1552
                        $user->first_name = $first_name;
1553
                        $user->last_name = $last_name;
1554
                        $user->password = $password_hash;
1555
                        $user->login_attempt = 0;
1556
                        $user->usertype_id = UserType::USER;
1557
                        $user->status = User::STATUS_ACTIVE;
1558
 
1559
                        $result = $userMapper->insert($user);
1560
                        if($result) {
1561
                            $userPassword = new UserPassword();
1562
                            $userPassword->user_id = $user->id;
1563
                            $userPassword->password = $password_hash;
1564
                            $userPasswordMapper->insert($userPassword);
1565
                        } else {
1566
                            continue;
1567
                        }
129 efrain 1568
                    } else {
1569
                        if($user->email_verified == User::EMAIL_VERIFIED_NO || $user->status != User::STATUS_ACTIVE) {
1570
                            $user->email_verified = User::EMAIL_VERIFIED_YES;
1571
                            $user->status != User::STATUS_ACTIVE;
1572
 
1573
                            if(!$userMapper->update($user)) {
1574
                                continue;
1575
                            }
1576
                        }
1 www 1577
                    }
1578
 
1579
                    if(!in_array($user->id, $user_ids)) {
1580
                        array_push($user_ids, $user->id);
1581
                    }
1582
                }
1583
 
1584
                foreach($user_ids as $user_id)
1585
                {
1586
                    $companyUser = $companyUserMapper->fetchOneByCompanyIdAndUserId($currentCompany->id, $user_id);
1587
                    if(!$companyUser) {
1588
 
1589
                        $companyUser = new CompanyUser();
1590
                        $companyUser->company_id = $currentCompany->id;
1591
                        $companyUser->user_id = $user_id;
1592
                        $companyUser->backend = CompanyUser::BACKEND_NO;
1593
                        $companyUser->creator = CompanyUser::CREATOR_NO;
1594
                        $companyUser->owner = CompanyUser::OWNER_NO;
1595
                        $companyUser->status = CompanyUser::STATUS_ADMIN_WILL_ADD;
1596
 
1597
                        if($companyUserMapper->insert($companyUser)) {
1598
                            $users_created++;
1599
                        }
1600
 
1601
                    }
1602
 
1603
                }
1604
 
1605
                $this->logger->info('Se agregaron ' . $users_created . ' usuarios  la empresa ' . $currentCompany->name, ['user_id' => $currentUser->id, 'ip' => Functions::getUserIP()]);
1606
 
1607
                return new JsonModel([
1608
                    'success' => true,
1609
                    'data' => [
1610
                        'users_created' => $users_created
1611
                    ]
1612
                ]);
1613
 
1614
 
1615
 
1616
 
1617
            } else {
1618
                return new JsonModel([
1619
                    'success' => false,
1620
                    'data' => 'ERROR_PARAMETERS_ARE_INVALID'
1621
                ]);
1622
            }
1623
 
1624
 
1625
 
1626
 
1627
        }
1628
 
1629
        return new JsonModel([
1630
            'success' => false,
1631
            'data' => 'ERROR_METHOD_NOT_ALLOWED'
1632
        ]);
1633
    }
1634
 
1635
 
1636
    public function editAction()
1637
    {
1638
        $currentUserPlugin = $this->plugin('currentUserPlugin');
1639
        $currentUser = $currentUserPlugin->getUser();
1640
        $currentCompany = $currentUserPlugin->getCompany();
1641
 
1642
        $request = $this->getRequest();
1643
        $uuid = $this->params()->fromRoute('id');
1644
 
1645
 
1646
        if(!$uuid) {
1647
            $data = [
1648
                'success'   => false,
1649
                'data'   => 'ERROR_INVALID_PARAMETER'
1650
            ];
1651
 
1652
            return new JsonModel($data);
1653
        }
1654
 
1655
        $userMapper = UserMapper::getInstance($this->adapter);
1656
        $user = $userMapper->fetchOneByUuid($uuid);
1657
        if(!$user) {
1658
            $data = [
1659
                'success'   => false,
1660
                'data'   => 'ERROR_COMPANY_NOT_FOUND'
1661
            ];
1662
 
1663
            return new JsonModel($data);
1664
        }
1665
 
1666
        $companyUserMapper = CompanyUserMapper::getInstance($this->adapter);
1667
        $companyUser = $companyUserMapper->fetchOneByCompanyIdAndUserId($currentCompany->id, $user->id);
1668
        if(!$companyUser) {
1669
            return new JsonModel([
1670
                'success'   => false,
1671
                'data'   => 'ERROR_COMPANY_USER_NOT_FOUND'
1672
            ]);
1673
 
1674
        }
1675
 
1676
        if($companyUser->status != CompanyUser::STATUS_ACCEPTED && $companyUser->status != CompanyUser::STATUS_ADMIN_WILL_ADD) {
1677
            return new JsonModel([
1678
                'success'   => false,
1679
                'data'   => 'ERROR_COMPANY_USER_IS_NOT_ACTIVE'
1680
            ]);
1681
        }
1682
 
1683
 
1684
 
1685
 
1686
        if($request->isPost()) {
1687
 
1688
            $companyRoleMapper = CompanyRoleMapper::getInstance($this->adapter);
1689
            $companyUserMapper = CompanyUserMapper::getInstance($this->adapter);
1690
            $companyUserRoleMapper = CompanyUserRoleMapper::getInstance($this->adapter);
1691
 
1692
            $backend = filter_var( $this->params()->fromPost('backend'), FILTER_SANITIZE_STRING );
1693
            $companyUser->backend = $backend == CompanyUser::BACKEND_YES ? CompanyUser::BACKEND_YES : CompanyUser::BACKEND_NO;
1694
            $companyUserMapper->update($companyUser);
1695
 
1696
 
1697
            $roleMapper = RoleMapper::getInstance($this->adapter);
1698
            $roles = $roleMapper->fetchAll();
1699
 
1700
 
1701
            foreach($roles as $role)
1702
            {
1703
                $companyRole = $companyRoleMapper->fetchOneByCompanyIdAndRoleId($currentCompany->id, $role->id);
1704
                if(!$companyRole) {
1705
                    $companyUserRoleMapper->deleteByCompanyIdAndRoleId($currentCompany->id, $role->id);
1706
                    continue;
1707
                }
1708
 
1709
                $checked     = filter_var( $this->params()->fromPost('checked' . $role->id), FILTER_SANITIZE_NUMBER_INT);
1710
 
1711
                if($checked) {
1712
 
1713
                    $companyUserRole = $companyUserRoleMapper->fetchOneByCompanyIdAndUserIdAndRoleId($currentCompany->id, $user->id, $role->id);
1714
                    if(!$companyUserRole) {
1715
 
1716
                        $companyUserRole = new CompanyUserRole();
1717
                        $companyUserRole->company_id = $currentCompany->id;
1718
                        $companyUserRole->role_id = $role->id;
1719
                        $companyUserRole->user_id = $user->id;
1720
 
1721
                        $companyUserRoleMapper->insert($companyUserRole);
1722
 
1723
                    }
1724
 
1725
 
1726
 
1727
 
1728
                } else {
1729
 
1730
                    $companyUserRoleMapper->deleteByCompanyIdAndUserIdAndRoleId($currentCompany->id, $user->id, $role->id);
1731
                }
1732
            }
1733
 
1734
            $this->logger->info('Se actualizo los roles del usuario : ' . $user->email . ' en la empresa ' . $currentCompany->name, ['user_id' => $currentUser->id, 'ip' => Functions::getUserIP()]);
1735
 
1736
            return new JsonModel([
1737
                'success' => true,
1738
                'data' => 'LABEL_RECORD_UPDATED'
1739
            ]);
1740
 
1741
 
1742
        } else if ($request->isGet()) {
1743
            $companyServiceMapper = CompanyServiceMapper::getInstance($this->adapter);
1744
 
1745
            $roleMapper = RoleMapper::getInstance($this->adapter);
1746
            $records = $roleMapper->fetchAll();
1747
 
4 efrain 1748
 
1749
 
1 www 1750
            $companyRoleMapper = CompanyRoleMapper::getInstance($this->adapter);
1751
            $companyUserRoleMapper = CompanyUserRoleMapper::getInstance($this->adapter);
1752
 
1753
            $roles = [];
1754
            foreach($records as $record)
1755
            {
1756
                if($record->creator == Role::CREATOR_YES) {
1757
                    continue;
1758
                }
1759
 
1760
                if($record->service_id) {
1761
                    $companyService = $companyServiceMapper->fetchOneByCompanyIdAndServiceId($currentCompany->id, $record->service_id);
1762
                    if(!$companyService || $companyService->status == CompanyService::INACTIVE) {
1763
                        continue;
1764
                    }
1765
 
1766
                }
1767
 
1768
 
1769
 
1770
                $companyRole = $companyRoleMapper->fetchOneByCompanyIdAndRoleId($currentCompany->id, $record->id);
1771
                if(!$companyRole) {
1772
                    continue;
1773
                }
1774
 
1775
                $companyUserRole  = $companyUserRoleMapper->fetchOneByCompanyIdAndUserIdAndRoleId($currentCompany->id, $user->id, $record->id);
1776
 
1777
 
1778
                $roles[ $record->id ] = [
1779
                    'id' => $record->id,
1780
                    'name' => $record->name,
1781
                    'fixed' => $record->creator == Role::CREATOR_YES ? true : false,
1782
                    'checked' => $companyUserRole ? true : false,
1783
                ];
4 efrain 1784
 
1785
 
1 www 1786
            }
1787
 
1788
 
1789
 
1790
            $data = [
1791
                'success' => true,
1792
                'data' => [
1793
                   'backend' => $companyUser->backend == CompanyUser::BACKEND_YES ? 1 : 0,
1794
                   'roles' => $roles,
1795
                ] ,
1796
            ];
1797
 
1798
 
1799
 
1800
            return new JsonModel($data);
1801
        } else {
1802
            $data = [
1803
                'success' => false,
1804
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
1805
            ];
1806
 
1807
            return new JsonModel($data);
1808
        }
1809
 
1810
        return new JsonModel($data);
1811
    }
1812
 
1813
 
1814
}