Proyectos de Subversion LeadersLinked - Backend

Rev

Rev 17008 | | Comparar con el anterior | Ultima modificación | Ver Log |

Rev Autor Línea Nro. Línea
17007 efrain 1
<?php
2
 
3
declare(strict_types=1);
4
 
5
namespace LeadersLinked\Controller;
6
 
7
use Laminas\Db\Adapter\AdapterInterface;
8
 
9
use Laminas\Mvc\Controller\AbstractActionController;
10
use Laminas\Log\LoggerInterface;
11
use Laminas\View\Model\ViewModel;
12
use Laminas\View\Model\JsonModel;
13
use LeadersLinked\Library\Functions;
14
use LeadersLinked\Mapper\HabitUserMapper;
15
use LeadersLinked\Model\HabitUser;
16
use LeadersLinked\Mapper\UserMapper;
17008 efrain 17
 
17007 efrain 18
use LeadersLinked\Mapper\QueryMapper;
19
use Laminas\Paginator\Adapter\DbSelect;
20
use Laminas\Paginator\Paginator;
17008 efrain 21
use LeadersLinked\Form\Habit\HabitUserForm;
22
use LeadersLinked\Form\Habit\HabitUserUploadForm;
17019 efrain 23
use PhpOffice\PhpSpreadsheet\IOFactory;
24
use LeadersLinked\Mapper\LocationMapper;
25
use LeadersLinked\Mapper\CountryMapper;
26
use LeadersLinked\Mapper\NetworkMapper;
27
use LeadersLinked\Mapper\UserPasswordMapper;
28
use LeadersLinked\Model\User;
29
use LeadersLinked\Model\UserType;
30
use LeadersLinked\Model\Location;
31
use LeadersLinked\Model\UserPassword;
32
use LeadersLinked\Model\Network;
33
use LeadersLinked\Mapper\CompanyMapper;
34
use LeadersLinked\Mapper\CompanyFollowerMapper;
35
use LeadersLinked\Mapper\ConnectionMapper;
36
use LeadersLinked\Model\Connection;
37
use LeadersLinked\Model\CompanyFollower;
17007 efrain 38
 
39
class HabitUserController extends AbstractActionController {
40
 
41
    /**
42
     *
43
     * @var \Laminas\Db\Adapter\AdapterInterface
44
     */
45
    private $adapter;
46
 
47
    /**
48
     *
49
     * @var \LeadersLinked\Cache\CacheInterface
50
     */
51
    private $cache;
52
 
53
 
54
    /**
55
     *
56
     * @var \Laminas\Log\LoggerInterface
57
     */
58
    private $logger;
59
 
60
    /**
61
     *
62
     * @var array
63
     */
64
    private $config;
65
 
66
 
67
    /**
68
     *
69
     * @var \Laminas\Mvc\I18n\Translator
70
     */
71
    private $translator;
72
 
73
 
74
    /**
75
     *
76
     * @param \Laminas\Db\Adapter\AdapterInterface $adapter
77
     * @param \LeadersLinked\Cache\CacheInterface $cache
78
     * @param \Laminas\Log\LoggerInterface LoggerInterface $logger
79
     * @param array $config
80
     * @param \Laminas\Mvc\I18n\Translator $translator
81
     */
82
    public function __construct($adapter, $cache, $logger, $config, $translator)
83
    {
84
        $this->adapter      = $adapter;
85
        $this->cache        = $cache;
86
        $this->logger       = $logger;
87
        $this->config       = $config;
88
        $this->translator   = $translator;
89
    }
90
 
91
    public function indexAction() {
92
        $request = $this->getRequest();
93
        $currentUserPlugin = $this->plugin('currentUserPlugin');
94
        $currentCompany = $currentUserPlugin->getCompany();
95
        $currentUser = $currentUserPlugin->getUser();
96
 
97
 
98
        $request = $this->getRequest();
99
        if ($request->isGet()) {
100
 
101
            $headers = $request->getHeaders();
102
 
103
            $isJson = false;
104
            if ($headers->has('Accept')) {
105
                $accept = $headers->get('Accept');
106
 
107
                $prioritized = $accept->getPrioritized();
108
 
109
                foreach ($prioritized as $key => $value) {
110
                    $raw = trim($value->getRaw());
111
 
112
                    if (!$isJson) {
113
                        $isJson = strpos($raw, 'json');
114
                    }
115
                }
116
            }
117
 
17019 efrain 118
           // $isJson = true;
17007 efrain 119
            if ($isJson) {
120
 
121
 
122
                $search = $this->params()->fromQuery('search', []);
123
                $search = empty($search['value']) ? '' :  Functions::sanitizeFilterString($search['value']);
124
 
125
                $start = intval($this->params()->fromQuery('start', 0), 10);
126
                $records_x_page = intval($this->params()->fromQuery('length', 10), 10);
127
                $page =  intval($start / $records_x_page);
128
                $page++;
129
 
130
                $order = $this->params()->fromQuery('order', []);
131
                $order_field = empty($order[0]['column']) ? 99 : intval($order[0]['column'], 10);
132
                $order_direction = empty($order[0]['dir']) ? 'ASC' : Functions::sanitizeFilterString(filter_var($order[0]['dir']));
133
 
134
                $fields = ['first_name', 'last_name', 'email'];
135
                $order_field = isset($fields[$order_field]) ? $fields[$order_field] : 'first_name';
136
 
137
                if (!in_array($order_direction, ['ASC', 'DESC'])) {
138
                    $order_direction = 'ASC';
139
                }
140
 
141
 
142
 
143
                $acl = $this->getEvent()->getViewModel()->getVariable('acl');
144
                $allowAdd = $acl->isAllowed($currentUser->usertype_id, 'habits/users/add');
17008 efrain 145
               // $allowEdit = $acl->isAllowed($currentUser->usertype_id, 'habits/users/edit');
17007 efrain 146
                $allowDelete = $acl->isAllowed($currentUser->usertype_id, 'habits/users/delete');
17008 efrain 147
                //$allowUpload = $acl->isAllowed($currentUser->usertype_id, 'habits/users/upload');
17007 efrain 148
 
149
 
150
                $items = [];
151
 
152
                $queryMapper = QueryMapper::getInstance($this->adapter);
153
                $select = $queryMapper->getSql()->select();
17019 efrain 154
                $select->columns([]);
17007 efrain 155
                $select->from(['cu' => HabitUserMapper::_TABLE]);
156
                $select->join(['u' => UserMapper::_TABLE], 'cu.user_id = u.id',  ['uuid', 'first_name', 'last_name', 'email']);
17008 efrain 157
 
158
 
17019 efrain 159
                $select->where->equalTo('cu.company_id', $currentCompany->id);
160
 
17007 efrain 161
                if($search) {
162
                    $select->where->nest()->like('first_name', '%' . $search . '%')
163
                    ->or->like('last_name', '%' . $search . '%')
164
                    ->or->like('email', '%' . $search . '%')->unnest();
165
                }
166
 
167
                $select->order($order_field . ' ' . $order_direction);
168
 
169
                //echo $select->getSqlString($this->adapter->platform); exit;
170
 
171
 
172
                $paginatorAdapter = new DbSelect($select, $this->adapter);
173
                $paginator = new Paginator($paginatorAdapter);
174
                $paginator->setItemCountPerPage($records_x_page);
175
                $paginator->setCurrentPageNumber($page);
176
 
177
                $records = $paginator->getCurrentItems();
178
 
179
                foreach ($records as $record)
180
                {
181
                    $item = [
182
                        'first_name' => $record['first_name'],
183
                        'last_name' => $record['last_name'],
184
                        'email' => $record['email'],
185
                        'actions' => [
17008 efrain 186
                            //'link_edit' => $allowEdit ? $this->url()->fromRoute('habits/users/edit', ['id' => $record['uuid'] ]) : '',
17007 efrain 187
                            'link_delete' => $allowDelete ? $this->url()->fromRoute('habits/users/delete', ['id' => $record['uuid'] ]) : '',
188
                        ]
189
                    ];
190
 
191
                    array_push($items, $item);
192
                }
193
 
194
 
195
 
196
 
197
                return new JsonModel([
198
                    'success' => true,
199
                    'data' => [
200
                        'total' => $paginator->getTotalItemCount(),
201
                        'items' => $items,
202
                    ]
203
                ]);
204
            } else {
205
 
206
 
17019 efrain 207
                $form = new HabitUserForm($this->adapter, $currentCompany->id);
208
                $formUploadUsers = new HabitUserUploadForm();
17007 efrain 209
 
210
                $this->layout()->setTemplate('layout/layout-backend');
211
                $viewModel = new ViewModel();
17008 efrain 212
                $viewModel->setTemplate('leaders-linked/habits/users.phtml');
17007 efrain 213
                $viewModel->setVariables([
17019 efrain 214
                    'form' =>  $form,
215
                    'formUploadUsers' => $formUploadUsers,
17008 efrain 216
 
17007 efrain 217
                ]);
218
                return $viewModel;
219
            }
220
        } else {
221
            return new JsonModel([
222
                'success' => false,
223
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
224
            ]);
225
        }
226
 
227
    }
228
 
229
 
230
 
231
    public function addAction()
232
    {
233
        $currentUserPlugin  = $this->plugin('currentUserPlugin');
234
        $currentCompany     = $currentUserPlugin->getCompany();
235
        $currentUser        = $currentUserPlugin->getUser();
236
        $request            = $this->getRequest();
237
 
238
        if($request->isPost()) {
239
 
240
 
241
            $dataPost = $request->getPost()->toArray();
242
 
243
            $form = new  HabitUserForm($this->adapter, $currentCompany->id);
244
            $form->setData($dataPost);
245
 
246
            if($form->isValid()) {
247
 
248
                $dataPost = (array) $form->getData();
249
 
250
 
251
                $userMapper = UserMapper::getInstance($this->adapter);
252
                $user = $userMapper->fetchOneByUuid($dataPost['user_id']);
253
 
254
                $habitUserMapper = HabitUserMapper::getInstance($this->adapter);
17008 efrain 255
                $habitUser = $habitUserMapper->fetchOneByCompanyIdAndUserId($currentCompany->id, $user->id);
17007 efrain 256
 
257
                if($habitUser) {
258
                    return new JsonModel([
259
                        'success' => false,
17008 efrain 260
                        'data' => 'ERROR_HABITS_USER_NOT_FOUND'
17007 efrain 261
                    ]);
262
                }
263
 
17008 efrain 264
 
17007 efrain 265
 
17008 efrain 266
 
17007 efrain 267
                $habitUser =  new HabitUser();
17008 efrain 268
                $habitUser->network_id  = $currentCompany->network_id;
269
                $habitUser->company_id  = $currentCompany->id;
270
                $habitUser->user_id     = $user->id;
271
                $habitUser->access      = HabitUser::ACCESS_UNLIMITED;
272
                $habitUserMapper        = HabitUserMapper::getInstance($this->adapter);
17007 efrain 273
 
274
 
275
                if($habitUserMapper->insert($habitUser)) {
276
 
277
 
17008 efrain 278
                    $this->logger->info('Se agrego el usuario ' . $user->first_name . ' ' . $user->last_name . ' (' . $user->email . ') ' , ['user_id' => $currentUser->id, 'ip' => Functions::getUserIP()]);
17007 efrain 279
 
280
                    $data = [
281
                        'success'   => true,
282
                        'data'   => 'LABEL_RECORD_ADDED'
283
                    ];
284
                } else {
285
                    $data = [
286
                        'success'   => false,
287
                        'data'      => $habitUserMapper->getError()
288
                    ];
289
 
290
                }
291
 
292
                return new JsonModel($data);
293
 
294
            } else {
295
                $messages = [];
296
                $form_messages = (array) $form->getMessages();
297
                foreach ($form_messages as $fieldname => $field_messages) {
298
 
299
                    $messages[$fieldname] = array_values($field_messages);
300
                }
301
 
302
                return new JsonModel([
303
                    'success' => false,
304
                    'data' => $messages
305
                ]);
306
 
307
            }
308
 
309
        } else {
310
            $data = [
311
                'success' => false,
312
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
313
            ];
314
 
315
            return new JsonModel($data);
316
        }
317
 
318
        return new JsonModel($data);
319
 
320
 
321
    }
322
 
323
 
324
 
325
    public function deleteAction()
326
    {
327
        $request = $this->getRequest();
328
        $currentUserPlugin = $this->plugin('currentUserPlugin');
329
        $currentCompany = $currentUserPlugin->getCompany();
330
        $currentUser = $currentUserPlugin->getUser();
331
 
332
        $request = $this->getRequest();
333
        $uuid = $this->params()->fromRoute('id');
334
        $user_id = $this->params()->fromRoute('user_id');
335
 
336
 
337
        $userMapper = UserMapper::getInstance($this->adapter);
17008 efrain 338
        $user = $userMapper->fetchOneByUuid($uuid);
17007 efrain 339
 
340
        if(!$user) {
341
            return new JsonModel([
342
                'success' => false,
343
                'data' => 'ERROR_USER_NOT_FOUND'
344
            ]);
345
 
346
        }
347
 
348
        $habitUserMapper = HabitUserMapper::getInstance($this->adapter);
17008 efrain 349
        $habitUser = $habitUserMapper->fetchOneByCompanyIdAndUserId($currentCompany->id, $user->id);
17007 efrain 350
 
351
        if(!$habitUser) {
352
            return new JsonModel([
353
                'success' => false,
17008 efrain 354
                'data' => 'ERROR_HABITS_USER_NOT_FOUND'
17007 efrain 355
            ]);
356
        }
357
 
17008 efrain 358
 
17007 efrain 359
 
17008 efrain 360
 
17007 efrain 361
 
362
        if ($request->isPost()) {
363
 
17008 efrain 364
            if ($habitUserMapper->delete($habitUser)) {
365
            $this->logger->info('Se borro el usuario ' . $user->first_name . ' ' . $user->last_name . ' (' . $user->email . ') ', ['user_id' => $currentUser->id, 'ip' => Functions::getUserIP()]);
17007 efrain 366
 
367
                $data = [
368
                    'success' => true,
369
                    'data' => 'LABEL_RECORD_DELETED'
370
                ];
371
            } else {
372
 
373
                $data = [
374
                    'success' => false,
375
                    'data' => $habitUserMapper->getError()
376
                ];
377
 
378
 
379
            }
380
        } else {
381
            $data = [
382
                'success' => false,
383
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
384
            ];
385
 
386
 
387
        }
388
 
389
 
390
        return new JsonModel($data);
391
 
392
    }
393
 
17019 efrain 394
 
395
    public function uploadAction()
396
    {
397
        $request = $this->getRequest();
398
 
399
        $currentNetworkPlugin = $this->plugin('currentNetworkPlugin');
400
        $currentNetwork    = $currentNetworkPlugin->getNetwork();
401
 
402
        $currentUserPlugin = $this->plugin('currentUserPlugin');
403
        $currentUser    = $currentUserPlugin->getUser();
404
        $currentCompany = $currentUserPlugin->getCompany();
405
 
406
        $request    = $this->getRequest();
407
 
408
        if($request->isPost()) {
409
 
410
            $step = Functions::sanitizeFilterString($this->params()->fromPost('step'));
411
            if($step == 'validation') {
412
                $userMapper = UserMapper::getInstance($this->adapter);
413
                $habitUserMapper = HabitUserMapper::getInstance($this->adapter);
414
 
415
                $form = new  HabitUserUploadForm();
416
                $dataPost = array_merge($request->getPost()->toArray(), $request->getFiles()->toArray());
417
 
418
                $form->setData($dataPost);
419
 
420
                if($form->isValid()) {
421
 
422
                    $file = $_FILES['file'];
423
                    $tmp_filename = $file['tmp_name'];
424
                    $final_filename =  'data/' . $file['name'];
425
 
426
                    if(!move_uploaded_file($tmp_filename, $final_filename)) {
427
                        return new JsonModel([
428
                            'success' => false,
429
                            'data' => 'ERROR_UPLOAD_FILE'
430
                        ]);
431
                    }
432
 
433
 
434
                    $users = [];
435
 
436
 
437
                    $spreadsheet = IOFactory::load($final_filename);
438
                    $records = $spreadsheet->getActiveSheet()->toArray(null, true, true, true);
439
 
440
                    $emails = [];
441
 
442
                    foreach($records as $record)
443
                    {
444
                        //A = Nombre 	B = Apellidos	C = Email 	D = contraseña
445
 
446
 
447
                        $first_name = Functions::sanitizeFilterString($record['A']);
448
                        $last_name = Functions::sanitizeFilterString($record['B']);
449
                        $email = trim(filter_var($record['C'], FILTER_SANITIZE_EMAIL));
450
                        $password = Functions::sanitizeFilterString($record['D']);
451
                        $isAdult = strtolower(Functions::sanitizeFilterString($record['E']));
452
                        $country = strtolower(Functions::sanitizeFilterString($record['F']));
453
 
454
 
455
                        if(empty($first_name) || empty($last_name) || !filter_var($email, FILTER_VALIDATE_EMAIL) ||  empty($password)) {
456
                            continue;
457
                        }
458
 
459
                        if(!in_array($email, $emails)) {
460
 
461
                            $user = $userMapper->fetchOneByEmail($email);
462
 
463
                            array_push($emails, $email);
464
                            array_push($users, [
465
                                'first_name' => $first_name,
466
                                'last_name' => $last_name,
467
                                'password'  => $password,
468
                                'email' => $email,
469
                                'is_adult' => $isAdult,
470
                                'country' => $country,
471
 
472
                            ]);
473
                        }
474
 
475
 
476
 
477
 
478
 
479
                    }
480
 
481
                    $key = md5($currentUser->id . '-' . microtime(true));
482
                    $this->cache->setItem($key, serialize($users));
483
 
484
                    return new JsonModel([
485
                        'success' => true,
486
                        'data' => [
487
                            'key' => $key,
488
                            'items' => $users,
489
                        ]
490
                    ]);
491
 
492
                    @unlink($final_filename);
493
 
494
 
495
                } else {
496
                    $messages = [];
497
                    $form_messages = (array) $form->getMessages();
498
                    foreach($form_messages  as $fieldname => $field_messages)
499
                    {
500
 
501
                        $messages[$fieldname] = array_values($field_messages);
502
                    }
503
 
504
                    return new JsonModel([
505
                        'success'   => false,
506
                        'data'   => $messages
507
                    ]);
508
                }
509
            } else if($step == 'process') {
510
 
511
                $key = Functions::sanitizeFilterString($this->params()->fromPost('key'));
512
                if(!$key) {
513
                    return new JsonModel([
514
                        'success' => false,
515
                        'data' => 'ERROR_CACHE_KEY_EMPTY'
516
                    ]);
517
                }
518
 
519
                $value = $this->cache->getItem($key);
520
                if(!$value) {
521
 
522
                    return new JsonModel([
523
                        'success' => false,
524
                        'data' => 'ERROR_CACHE_NOT_FOUND'
525
                    ]);
526
                }
527
 
528
                $records = unserialize($value);
529
                if(!$records) {
530
                    return new JsonModel([
531
                        'success' => false,
532
                        'data' => 'ERROR_CACHE_INVALID'
533
                    ]);
534
                }
535
 
536
                $locationMapper = LocationMapper::getInstance($this->adapter);
537
                $countryMapper = CountryMapper::getInstance($this->adapter);
538
 
539
 
540
                $networkMapper = NetworkMapper::getInstance($this->adapter);
541
                $networkDefault = $networkMapper->fetchOneByDefault();
542
 
543
                $userMapper = UserMapper::getInstance($this->adapter);
544
                $userPasswordMapper = UserPasswordMapper::getInstance($this->adapter);
545
 
546
 
547
                $user_ids_in_default_network = [];
548
 
549
 
550
                $users_created = 0;
551
                $user_ids = [];
552
                foreach($records as $record)
553
                {
554
                    $first_name = $record['first_name'];
555
                    $last_name = $record['last_name'];
556
                    $password = $record['password'];
557
                    $email = $record['email'];
558
 
559
 
560
                    $user = $userMapper->fetchOneByEmailAndNetworkId($email, $currentNetwork->id);
561
                    if(!$user) {
562
                        $password_hash = password_hash($password, PASSWORD_DEFAULT);
563
 
564
                        $user = new User();
565
                        $user->network_id = $currentNetwork->id;
566
                        $user->blocked = User::BLOCKED_NO;
567
                        $user->email_verified = User::EMAIL_VERIFIED_YES;
568
                        $user->email = $email;
569
                        $user->first_name = $first_name;
570
                        $user->last_name = $last_name;
571
                        $user->password = $password_hash;
572
                        $user->login_attempt = 0;
573
                        $user->usertype_id = UserType::USER;
574
                        $user->status = User::STATUS_ACTIVE;
575
                        $user->is_adult = $record['is_adult'] == 'y' ? User::IS_ADULT_YES : User::IS_ADULT_NO;
576
 
577
                        $result = $userMapper->insert($user);
578
                        if($result) {
579
                            $users_created++;
580
 
581
                            $country_code = trim($record['country']);
582
 
583
                            if($country_code) {
584
                                $country = $countryMapper->fetchOneByCodeOrCountry($record['country']);
585
                                if($country) {
586
 
587
                                    $location = new Location();
588
                                    $location->formatted_address = $country->country;
589
                                    $location->country = $country->country;
590
                                    if($locationMapper->insert($location)) {
591
 
592
                                        $user->location_id = $location->id;
593
                                        $userMapper->updateLocation($user);
594
                                    }
595
 
596
                                }
597
                            } else {
598
                                $country_code = '';
599
                            }
600
 
601
                            $userPassword = new UserPassword();
602
                            $userPassword->user_id = $user->id;
603
                            $userPassword->password = $password_hash;
604
                            $userPasswordMapper->insert($userPassword);
605
 
606
 
607
                            if($currentNetwork->default == Network::DEFAULT_YES) {
608
                                array_push($user_ids_in_default_network, $user->id);
609
                            } else {
610
 
611
 
612
 
613
                                if($user->is_adult == User::IS_ADULT_YES) {
614
 
615
                                    $userInDefaultNetwork = $userMapper->fetchOneByEmailAndNetworkId($user->email, $networkDefault->id);
616
                                    if($userInDefaultNetwork) {
617
 
618
                                        array_push($user_ids_in_default_network, $userInDefaultNetwork->id);
619
 
620
                                        if($userInDefaultNetwork->email_verified == User::EMAIL_VERIFIED_NO || $userInDefaultNetwork->status != User::STATUS_ACTIVE) {
621
                                            $userInDefaultNetwork->email_verified = User::EMAIL_VERIFIED_YES;
622
                                            $userInDefaultNetwork->status != User::STATUS_ACTIVE;
623
 
624
                                            if(!$userMapper->update($userInDefaultNetwork)) {
625
                                                continue;
626
                                            }
627
                                        }
628
 
629
 
630
                                    } else {
631
                                        $userInDefaultNetwork = new User();
632
                                        $userInDefaultNetwork->network_id = $networkDefault->id;
633
                                        $userInDefaultNetwork->blocked = User::BLOCKED_NO;
634
                                        $userInDefaultNetwork->email_verified = User::EMAIL_VERIFIED_YES;
635
                                        $userInDefaultNetwork->email = $email;
636
                                        $userInDefaultNetwork->first_name = $first_name;
637
                                        $userInDefaultNetwork->last_name = $last_name;
638
                                        $userInDefaultNetwork->password = $password_hash;
639
                                        $userInDefaultNetwork->login_attempt = 0;
640
                                        $userInDefaultNetwork->usertype_id = UserType::USER;
641
                                        $userInDefaultNetwork->status = User::STATUS_ACTIVE;
642
                                        $userInDefaultNetwork->is_adult = User::IS_ADULT_YES;
643
                                        $result = $userMapper->insert($userInDefaultNetwork);
644
                                        if($result) {
645
                                            array_push($user_ids_in_default_network, $userInDefaultNetwork->id);
646
 
647
                                            if($country) {
648
 
649
                                                $location = new Location();
650
                                                $location->formatted_address = $country->country;
651
                                                $location->country = $country->country;
652
                                                if($locationMapper->insert($location)) {
653
 
654
                                                    $userInDefaultNetwork->location_id = $location->id;
655
                                                    $userMapper->updateLocation($userInDefaultNetwork);
656
                                                }
657
 
658
                                            }
659
 
660
 
661
                                            $userPassword = new UserPassword();
662
                                            $userPassword->user_id = $userInDefaultNetwork->id;
663
                                            $userPassword->password = $password_hash;
664
                                            $userPasswordMapper->insert($userPassword);
665
                                        }
666
 
667
                                    }
668
 
669
 
670
                                }
671
 
672
 
673
                            }
674
 
675
 
676
 
677
 
678
 
679
 
680
                        } else {
681
                            continue;
682
                        }
683
                    } else {
684
                        if($user->email_verified == User::EMAIL_VERIFIED_NO || $user->status != User::STATUS_ACTIVE) {
685
                            $user->email_verified = User::EMAIL_VERIFIED_YES;
686
                            $user->status != User::STATUS_ACTIVE;
687
 
688
                            if(!$userMapper->update($user)) {
689
                                continue;
690
                            }
691
                        }
692
                    }
693
 
694
                    array_push($user_ids, $user->id);
695
 
696
                }
697
 
698
                if($currentCompany) {
699
 
700
                    $habitUserMapper = HabitUserMapper::getInstance($this->adapter);
701
 
702
                    $company_users_created = 0;
703
 
704
                    foreach($user_ids as $user_id)
705
                    {
706
                        $habitUser = $habitUserMapper->fetchOneByCompanyIdAndUserId($currentCompany->id, $user_id);
707
                        if(!$habitUser) {
708
 
709
                            $habitUser = new HabitUser();
710
                            $habitUser->network_id  = $currentCompany->network_id;
711
                            $habitUser->company_id  = $currentCompany->id;
712
                            $habitUser->user_id     = $user_id;
713
                            $habitUser->access      = HabitUser::ACCESS_UNLIMITED;
714
 
715
 
716
                            if($habitUserMapper->insert($habitUser)) {
717
                                $company_users_created++;
718
                            }
719
 
720
                        }
721
 
722
                    }
723
 
724
                    $this->logger->info('Se agregaron ' . $users_created . '  usuarios  la empresa ' . $currentCompany->name, ['user_id' => $currentUser->id, 'ip' => Functions::getUserIP()]);
725
 
726
 
727
 
728
                } else {
729
 
730
                    $this->logger->info('Se agregaron ' . $users_created . ' usuarios a la red', ['user_id' => $currentUser->id, 'ip' => Functions::getUserIP()]);
731
 
732
                }
733
 
734
                if($user_ids_in_default_network) {
735
                    $companyMapper = CompanyMapper::getInstance($this->adapter);
736
                    $companyToFollower = $companyMapper->fetchOneDefaultForFollowers();
737
 
738
                    $companyFollowerMapper = CompanyFollowerMapper::getInstance($this->adapter);
739
 
740
                    $userToConnection = $userMapper->fetchOneDefaultForConnection();
741
 
742
 
743
                    $connectionMapper = ConnectionMapper::getInstance($this->adapter);
744
 
745
                    foreach($user_ids_in_default_network as $user_id)
746
                    {
747
                        if($userToConnection) {
748
                            $connection = $connectionMapper->fetchOneByUserId1AndUserId2($user_id, $userToConnection->id);
749
                            if(!$connection) {
750
                                $connection = new Connection();
751
                                $connection->request_from = $user_id;
752
                                $connection->request_to = $userToConnection->id;
753
                                $connection->status = Connection::STATUS_ACCEPTED;
754
 
755
                                $connectionMapper->insert($connection);
756
                            } else {
757
                                if($connection->status == Connection::STATUS_SENT) {
758
                                    $connectionMapper->approve($connection);
759
                                }
760
                            }
761
                        }
762
 
763
                        if($companyToFollower) {
764
                            $companyFollower = $companyFollowerMapper->fetchOneByCompanyIdAndUserId($companyToFollower->id, $user_id);
765
                            if(!$companyFollower) {
766
                                $companyFollower = new CompanyFollower();
767
                                $companyFollower->company_id = $companyToFollower->id;
768
                                $companyFollower->follower_id = $user_id;
769
 
770
                                $companyFollowerMapper->insert($companyFollower);
771
 
772
                            }
773
                        }
774
 
775
                    }
776
 
777
 
778
 
779
 
780
                }
781
 
782
 
783
 
784
                return new JsonModel([
785
                    'success' => true,
786
                    'data' => [
787
                        'users_created' => $users_created
788
                    ]
789
                ]);
790
 
791
 
792
 
793
 
794
            } else {
795
                return new JsonModel([
796
                    'success' => false,
797
                    'data' => 'ERROR_PARAMETERS_ARE_INVALID'
798
                ]);
799
            }
800
 
801
 
802
 
803
 
804
        }
805
 
806
        return new JsonModel([
807
            'success' => false,
808
            'data' => 'ERROR_METHOD_NOT_ALLOWED'
809
        ]);
810
    }
811
 
17007 efrain 812
 
813
}