Proyectos de Subversion LeadersLinked - Backend

Rev

Rev 15460 | Rev 16286 | 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
 
1606
                    $user = $userMapper->fetchOneByEmail($email);
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
 
1627
                            $country = $countryMapper->fetchOneByCodeOrCountry($record['country']);
1628
                            if($country) {
1629
 
1630
                                $location = new Location();
1631
                                $location->formatted_address = $country->country;
1632
                                $location->country = $country->country;
1633
                                if($locationMapper->insert($location)) {
1634
 
1635
                                    $user->location_id = $location->id;
1636
                                    $userMapper->updateLocation($user);
1637
                                }
1638
 
1639
                            }
1640
 
1 www 1641
                            $userPassword = new UserPassword();
1642
                            $userPassword->user_id = $user->id;
1643
                            $userPassword->password = $password_hash;
1644
                            $userPasswordMapper->insert($userPassword);
15460 efrain 1645
 
1646
 
1647
                            if($currentNetwork->default == Network::DEFAULT_YES) {
1648
                                array_push($user_ids_in_default_network, $user->id);
1649
                            } else {
1650
 
1651
 
1652
 
1653
                                if($user->is_adult == User::IS_ADULT_YES) {
1654
 
1655
                                    $userInDefaultNetwork = $userMapper->fetchOneByEmailAndNetworkId($user->email, $networkDefault->id);
1656
                                    if($userInDefaultNetwork) {
1657
 
1658
                                        array_push($user_ids_in_default_network, $userInDefaultNetwork->id);
1659
 
1660
                                        if($userInDefaultNetwork->email_verified == User::EMAIL_VERIFIED_NO || $userInDefaultNetwork->status != User::STATUS_ACTIVE) {
1661
                                            $userInDefaultNetwork->email_verified = User::EMAIL_VERIFIED_YES;
1662
                                            $userInDefaultNetwork->status != User::STATUS_ACTIVE;
1663
 
1664
                                            if(!$userMapper->update($userInDefaultNetwork)) {
1665
                                                continue;
1666
                                            }
1667
                                        }
1668
 
1669
 
1670
                                    } else {
1671
                                        $userInDefaultNetwork = new User();
1672
                                        $userInDefaultNetwork->network_id = $networkDefault->id;
1673
                                        $userInDefaultNetwork->blocked = User::BLOCKED_NO;
1674
                                        $userInDefaultNetwork->email_verified = User::EMAIL_VERIFIED_YES;
1675
                                        $userInDefaultNetwork->email = $email;
1676
                                        $userInDefaultNetwork->first_name = $first_name;
1677
                                        $userInDefaultNetwork->last_name = $last_name;
1678
                                        $userInDefaultNetwork->password = $password_hash;
1679
                                        $userInDefaultNetwork->login_attempt = 0;
1680
                                        $userInDefaultNetwork->usertype_id = UserType::USER;
1681
                                        $userInDefaultNetwork->status = User::STATUS_ACTIVE;
1682
                                        $userInDefaultNetwork->is_adult = User::IS_ADULT_YES;
1683
                                        $result = $userMapper->insert($userInDefaultNetwork);
1684
                                        if($result) {
1685
                                            array_push($user_ids_in_default_network, $userInDefaultNetwork->id);
1686
 
1687
                                            if($country) {
1688
 
1689
                                                $location = new Location();
1690
                                                $location->formatted_address = $country->country;
1691
                                                $location->country = $country->country;
1692
                                                if($locationMapper->insert($location)) {
1693
 
1694
                                                    $userInDefaultNetwork->location_id = $location->id;
1695
                                                    $userMapper->updateLocation($userInDefaultNetwork);
1696
                                                }
1697
 
1698
                                            }
1699
 
1700
 
1701
                                            $userPassword = new UserPassword();
1702
                                            $userPassword->user_id = $userInDefaultNetwork->id;
1703
                                            $userPassword->password = $password_hash;
1704
                                            $userPasswordMapper->insert($userPassword);
1705
                                        }
1706
 
1707
                                    }
1708
 
1709
 
1710
                                }
1711
 
1712
 
1713
                            }
1714
 
1715
 
1716
 
1717
 
1718
 
1719
 
1 www 1720
                        } else {
1721
                            continue;
1722
                        }
129 efrain 1723
                    } else {
1724
                        if($user->email_verified == User::EMAIL_VERIFIED_NO || $user->status != User::STATUS_ACTIVE) {
1725
                            $user->email_verified = User::EMAIL_VERIFIED_YES;
1726
                            $user->status != User::STATUS_ACTIVE;
1727
 
1728
                            if(!$userMapper->update($user)) {
1729
                                continue;
1730
                            }
1731
                        }
1 www 1732
                    }
1733
 
15460 efrain 1734
                    array_push($user_ids, $user->id);
1735
 
1736
                }
1737
 
1738
                if($currentCompany) {
1739
 
1740
                    $companyUserMapper = CompanyUserMapper::getInstance($this->adapter);
1741
 
1742
                    $company_users_created = 0;
1743
 
1744
                    foreach($user_ids as $user_id)
1745
                    {
1746
                        $companyUser = $companyUserMapper->fetchOneByCompanyIdAndUserId($currentCompany->id, $user_id);
1747
                        if(!$companyUser) {
1748
 
1749
                            $companyUser = new CompanyUser();
1750
                            $companyUser->company_id = $currentCompany->id;
1751
                            $companyUser->user_id = $user_id;
1752
                            $companyUser->backend = CompanyUser::BACKEND_NO;
1753
                            $companyUser->creator = CompanyUser::CREATOR_NO;
1754
                            $companyUser->owner = CompanyUser::OWNER_NO;
1755
 
1756
                            if($currentNetwork->default == Network::DEFAULT_YES) {
1757
                                $companyUser->status = CompanyUser::STATUS_ADMIN_WILL_ADD;
1758
                            } else {
1759
                                $companyUser->status = CompanyUser::STATUS_ACCEPTED;
1760
                            }
1761
 
1762
                            if($companyUserMapper->insert($companyUser)) {
1763
                                $company_users_created++;
1764
                            }
1765
 
1766
                        }
1767
 
1 www 1768
                    }
15460 efrain 1769
 
1770
                    $this->logger->info('Se agregaron ' . $users_created . '  usuarios  la empresa ' . $currentCompany->name, ['user_id' => $currentUser->id, 'ip' => Functions::getUserIP()]);
1771
 
1772
 
1773
 
1774
                } else {
1775
 
1776
                    $this->logger->info('Se agregaron ' . $users_created . ' usuarios a la red', ['user_id' => $currentUser->id, 'ip' => Functions::getUserIP()]);
1777
 
1 www 1778
                }
1779
 
15460 efrain 1780
                if($user_ids_in_default_network) {
1781
                    $companyMapper = CompanyMapper::getInstance($this->adapter);
1782
                    $companyToFollower = $companyMapper->fetchOneDefaultForFollowers();
1783
 
1784
                    $companyFollowerMapper = CompanyFollowerMapper::getInstance($this->adapter);
1785
 
1786
                    $userToConnection = $userMapper->fetchOneDefaultForConnection();
1787
 
1788
 
1789
                    $connectionMapper = ConnectionMapper::getInstance($this->adapter);
1790
 
1791
                    foreach($user_ids_in_default_network as $user_id)
1792
                    {
1793
                        if($userToConnection) {
1794
                            $connection = $connectionMapper->fetchOneByUserId1AndUserId2($user_id, $userToConnection->id);
1795
                            if(!$connection) {
1796
                                $connection = new Connection();
1797
                                $connection->request_from = $user_id;
1798
                                $connection->request_to = $userToConnection->id;
1799
                                $connection->status = Connection::STATUS_ACCEPTED;
1800
 
1801
                                $connectionMapper->insert($connection);
1802
                            } else {
1803
                                if($connection->status == Connection::STATUS_SENT) {
1804
                                    $connectionMapper->approve($connection);
1805
                                }
1806
                            }
1807
                        }
1 www 1808
 
15460 efrain 1809
                        if($companyToFollower) {
1810
                            $companyFollower = $companyFollowerMapper->fetchOneByCompanyIdAndUserId($companyToFollower->id, $user_id);
1811
                            if(!$companyFollower) {
1812
                                $companyFollower = new CompanyFollower();
1813
                                $companyFollower->company_id = $companyToFollower->id;
1814
                                $companyFollower->follower_id = $user_id;
1815
 
1816
                                $companyFollowerMapper->insert($companyFollower);
1817
 
1818
                            }
1 www 1819
                        }
1820
 
1821
                    }
1822
 
15460 efrain 1823
 
1824
 
1825
 
1 www 1826
                }
1827
 
1828
 
15460 efrain 1829
 
1 www 1830
                return new JsonModel([
1831
                    'success' => true,
1832
                    'data' => [
1833
                        'users_created' => $users_created
1834
                    ]
1835
                ]);
1836
 
1837
 
1838
 
1839
 
1840
            } else {
1841
                return new JsonModel([
1842
                    'success' => false,
1843
                    'data' => 'ERROR_PARAMETERS_ARE_INVALID'
1844
                ]);
1845
            }
1846
 
1847
 
1848
 
1849
 
1850
        }
1851
 
1852
        return new JsonModel([
1853
            'success' => false,
1854
            'data' => 'ERROR_METHOD_NOT_ALLOWED'
1855
        ]);
1856
    }
1857
 
1858
 
1859
    public function editAction()
1860
    {
1861
        $currentUserPlugin = $this->plugin('currentUserPlugin');
1862
        $currentUser = $currentUserPlugin->getUser();
1863
        $currentCompany = $currentUserPlugin->getCompany();
1864
 
1865
        $request = $this->getRequest();
1866
        $uuid = $this->params()->fromRoute('id');
1867
 
1868
 
1869
        if(!$uuid) {
1870
            $data = [
1871
                'success'   => false,
1872
                'data'   => 'ERROR_INVALID_PARAMETER'
1873
            ];
1874
 
1875
            return new JsonModel($data);
1876
        }
1877
 
1878
        $userMapper = UserMapper::getInstance($this->adapter);
1879
        $user = $userMapper->fetchOneByUuid($uuid);
1880
        if(!$user) {
1881
            $data = [
1882
                'success'   => false,
1883
                'data'   => 'ERROR_COMPANY_NOT_FOUND'
1884
            ];
1885
 
1886
            return new JsonModel($data);
1887
        }
1888
 
1889
        $companyUserMapper = CompanyUserMapper::getInstance($this->adapter);
1890
        $companyUser = $companyUserMapper->fetchOneByCompanyIdAndUserId($currentCompany->id, $user->id);
1891
        if(!$companyUser) {
1892
            return new JsonModel([
1893
                'success'   => false,
1894
                'data'   => 'ERROR_COMPANY_USER_NOT_FOUND'
1895
            ]);
1896
 
1897
        }
1898
 
1899
        if($companyUser->status != CompanyUser::STATUS_ACCEPTED && $companyUser->status != CompanyUser::STATUS_ADMIN_WILL_ADD) {
1900
            return new JsonModel([
1901
                'success'   => false,
1902
                'data'   => 'ERROR_COMPANY_USER_IS_NOT_ACTIVE'
1903
            ]);
1904
        }
1905
 
1906
 
1907
 
1908
 
1909
        if($request->isPost()) {
1910
 
1911
            $companyRoleMapper = CompanyRoleMapper::getInstance($this->adapter);
1912
            $companyUserMapper = CompanyUserMapper::getInstance($this->adapter);
1913
            $companyUserRoleMapper = CompanyUserRoleMapper::getInstance($this->adapter);
1914
 
1915
            $backend = filter_var( $this->params()->fromPost('backend'), FILTER_SANITIZE_STRING );
1916
            $companyUser->backend = $backend == CompanyUser::BACKEND_YES ? CompanyUser::BACKEND_YES : CompanyUser::BACKEND_NO;
1917
            $companyUserMapper->update($companyUser);
1918
 
1919
 
1920
            $roleMapper = RoleMapper::getInstance($this->adapter);
1921
            $roles = $roleMapper->fetchAll();
1922
 
1923
 
1924
            foreach($roles as $role)
1925
            {
1926
                $companyRole = $companyRoleMapper->fetchOneByCompanyIdAndRoleId($currentCompany->id, $role->id);
1927
                if(!$companyRole) {
1928
                    $companyUserRoleMapper->deleteByCompanyIdAndRoleId($currentCompany->id, $role->id);
1929
                    continue;
1930
                }
1931
 
1932
                $checked     = filter_var( $this->params()->fromPost('checked' . $role->id), FILTER_SANITIZE_NUMBER_INT);
1933
 
1934
                if($checked) {
1935
 
1936
                    $companyUserRole = $companyUserRoleMapper->fetchOneByCompanyIdAndUserIdAndRoleId($currentCompany->id, $user->id, $role->id);
1937
                    if(!$companyUserRole) {
1938
 
1939
                        $companyUserRole = new CompanyUserRole();
1940
                        $companyUserRole->company_id = $currentCompany->id;
1941
                        $companyUserRole->role_id = $role->id;
1942
                        $companyUserRole->user_id = $user->id;
1943
 
1944
                        $companyUserRoleMapper->insert($companyUserRole);
1945
 
1946
                    }
1947
 
1948
 
1949
 
1950
 
1951
                } else {
1952
 
1953
                    $companyUserRoleMapper->deleteByCompanyIdAndUserIdAndRoleId($currentCompany->id, $user->id, $role->id);
1954
                }
1955
            }
1956
 
1957
            $this->logger->info('Se actualizo los roles del usuario : ' . $user->email . ' en la empresa ' . $currentCompany->name, ['user_id' => $currentUser->id, 'ip' => Functions::getUserIP()]);
1958
 
1959
            return new JsonModel([
1960
                'success' => true,
1961
                'data' => 'LABEL_RECORD_UPDATED'
1962
            ]);
1963
 
1964
 
1965
        } else if ($request->isGet()) {
1966
            $companyServiceMapper = CompanyServiceMapper::getInstance($this->adapter);
1967
 
1968
            $roleMapper = RoleMapper::getInstance($this->adapter);
1969
            $records = $roleMapper->fetchAll();
1970
 
4 efrain 1971
 
1972
 
1 www 1973
            $companyRoleMapper = CompanyRoleMapper::getInstance($this->adapter);
1974
            $companyUserRoleMapper = CompanyUserRoleMapper::getInstance($this->adapter);
1975
 
1976
            $roles = [];
1977
            foreach($records as $record)
1978
            {
1979
                if($record->creator == Role::CREATOR_YES) {
1980
                    continue;
1981
                }
1982
 
1983
                if($record->service_id) {
1984
                    $companyService = $companyServiceMapper->fetchOneByCompanyIdAndServiceId($currentCompany->id, $record->service_id);
1985
                    if(!$companyService || $companyService->status == CompanyService::INACTIVE) {
1986
                        continue;
1987
                    }
1988
 
1989
                }
1990
 
1991
 
1992
 
1993
                $companyRole = $companyRoleMapper->fetchOneByCompanyIdAndRoleId($currentCompany->id, $record->id);
1994
                if(!$companyRole) {
1995
                    continue;
1996
                }
1997
 
1998
                $companyUserRole  = $companyUserRoleMapper->fetchOneByCompanyIdAndUserIdAndRoleId($currentCompany->id, $user->id, $record->id);
1999
 
2000
 
2001
                $roles[ $record->id ] = [
2002
                    'id' => $record->id,
2003
                    'name' => $record->name,
2004
                    'fixed' => $record->creator == Role::CREATOR_YES ? true : false,
2005
                    'checked' => $companyUserRole ? true : false,
2006
                ];
4 efrain 2007
 
2008
 
1 www 2009
            }
2010
 
2011
 
2012
 
2013
            $data = [
2014
                'success' => true,
2015
                'data' => [
2016
                   'backend' => $companyUser->backend == CompanyUser::BACKEND_YES ? 1 : 0,
2017
                   'roles' => $roles,
2018
                ] ,
2019
            ];
2020
 
2021
 
2022
 
2023
            return new JsonModel($data);
2024
        } else {
2025
            $data = [
2026
                'success' => false,
2027
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
2028
            ];
2029
 
2030
            return new JsonModel($data);
2031
        }
2032
 
2033
        return new JsonModel($data);
2034
    }
2035
 
2036
 
16248 efrain 2037
    public function changeTypeAction()
2038
    {
2039
        $currentUserPlugin = $this->plugin('currentUserPlugin');
2040
        $currentUser = $currentUserPlugin->getUser();
2041
 
2042
        $request = $this->getRequest();
2043
 
2044
        if($request->isGet()) {
2045
            $uuid = $this->params()->fromRoute('id');
2046
            if(!$uuid) {
2047
                return new JsonModel([
2048
                    'success'   => false,
2049
                    'data'      => 'ERROR_INVALID_PARAMETER'
2050
                ]);
2051
            }
2052
 
2053
            $userMapper = UserMapper::getInstance($this->adapter);
2054
            $user = $userMapper->fetchOneByUuid($uuid);
2055
 
2056
 
2057
 
2058
            if($user) {
2059
                return new JsonModel([
2060
                    'success'   => true,
2061
                    'data'      => [
2062
                        'usertype_id' => $user->usertype_id,
2063
                    ]
2064
                ]);
2065
            } else {
2066
                return new JsonModel([
2067
                    'success'   => false,
2068
                    'data'      => 'ERROR_USER_NOT_FOUND'
2069
                ]);
2070
            }
2071
 
2072
        }
2073
 
2074
        if($request->isPost()) {
2075
 
2076
            $uuid = $this->params()->fromRoute('id');
2077
            if(!$uuid) {
2078
                return new JsonModel([
2079
                    'success'   => false,
2080
                    'data'      => 'ERROR_INVALID_PARAMETER'
2081
                ]);
2082
            }
2083
 
2084
            $userMapper = UserMapper::getInstance($this->adapter);
2085
            $user = $userMapper->fetchOneByUuid($uuid);
2086
 
2087
            if(!$user) {
2088
                return new JsonModel([
2089
                    'success'   => false,
2090
                    'data'      => 'ERROR_USER_NOT_FOUND'
2091
                ]);
2092
            }
2093
 
2094
 
2095
            $dataPost = $request->getPost()->toArray();
2096
            $form = new ChangeTypeForm();
2097
            $form->setData($dataPost);
2098
 
2099
            if($form->isValid()) {
2100
                $dataPost = (array) $form->getData();
2101
 
2102
                $result = $userMapper->updateUserTypeId($user, $dataPost['usertype_id']);
2103
                if($result) {
2104
                    $this->logger->info('Cambio del tipo de usuario realizado por realizado', ['user_id' => $currentUser->id, 'ip' => Functions::getUserIP()]);
2105
 
2106
 
2107
                    return new JsonModel([
2108
                        'success'   => true,
2109
                        'data'      => 'LABEL_USER_CHANGE_TYPE_HAS_BEEN_UPDATED'
2110
 
2111
                    ]);
2112
                } else {
2113
                    $this->logger->err('Cambio del tipo de usuario - error desconocido', ['user_id' => $currentUser->id, 'ip' => Functions::getUserIP()]);
2114
 
2115
                    return new JsonModel([
2116
                        'success'   => true,
2117
                        'data'      => 'ERROR_THERE_WAS_AN_ERROR'
2118
 
2119
                    ]);
2120
 
2121
                }
2122
 
2123
            } else {
2124
                $messages = [];
2125
 
2126
                $form_messages = (array) $form->getMessages();
2127
                foreach($form_messages  as $fieldname => $field_messages)
2128
                {
2129
                    $messages[$fieldname] = array_values($field_messages);
2130
                }
2131
 
2132
                return new JsonModel([
2133
                    'success'   => false,
2134
                    'data'   => $messages
2135
                ]);
2136
            }
2137
 
2138
        }
2139
 
2140
 
2141
 
2142
        return new JsonModel([
2143
            'success' => false,
2144
            'data' => 'ERROR_METHOD_NOT_ALLOWED'
2145
        ]);
2146
    }
2147
 
2148
 
1 www 2149
}