Proyectos de Subversion LeadersLinked - Backend

Rev

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