Proyectos de Subversion LeadersLinked - Backend

Rev

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