Proyectos de Subversion LeadersLinked - Backend

Rev

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