Proyectos de Subversion LeadersLinked - Backend

Rev

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