Proyectos de Subversion LeadersLinked - Backend

Rev

Rev 16943 | Rev 17002 | 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;
16768 efrain 7
 
1 www 8
use Laminas\Mvc\Controller\AbstractActionController;
9
use Laminas\Log\LoggerInterface;
10
use Laminas\View\Model\ViewModel;
11
use Laminas\View\Model\JsonModel;
12
 
13
use LeadersLinked\Library\Functions;
14
use LeadersLinked\Hydrator\ObjectPropertyHydrator;
15
use LeadersLinked\Library\Image;
16
use LeadersLinked\Mapper\CompanyMicrolearningTopicMapper;
17
use LeadersLinked\Mapper\CompanyMicrolearningCapsuleMapper;
18
use LeadersLinked\Model\CompanyMicrolearningCapsule;
19
use LeadersLinked\Form\CapsuleAddForm;
20
use LeadersLinked\Form\CapsuleEditForm;
21
use LeadersLinked\Mapper\CompanyMicrolearningCapsuleUserMapper;
22
use LeadersLinked\Form\CapsuleForm;
23
use LeadersLinked\Mapper\QueryMapper;
24
use LeadersLinked\Mapper\UserMapper;
25
use LeadersLinked\Model\CompanyMicrolearningCapsuleUser;
26
 
27
class MicrolearningCapsuleController extends AbstractActionController
28
{
29
    /**
30
     *
16769 efrain 31
     * @var \Laminas\Db\Adapter\AdapterInterface
1 www 32
     */
33
    private $adapter;
34
 
35
    /**
36
     *
16769 efrain 37
     * @var \LeadersLinked\Cache\CacheInterface
1 www 38
     */
16769 efrain 39
    private $cache;
40
 
41
 
42
    /**
43
     *
44
     * @var \Laminas\Log\LoggerInterface
45
     */
1 www 46
    private $logger;
47
 
48
    /**
49
     *
50
     * @var array
51
     */
52
    private $config;
53
 
16769 efrain 54
 
1 www 55
    /**
56
     *
16769 efrain 57
     * @var \Laminas\Mvc\I18n\Translator
58
     */
59
    private $translator;
60
 
61
 
62
    /**
63
     *
64
     * @param \Laminas\Db\Adapter\AdapterInterface $adapter
65
     * @param \LeadersLinked\Cache\CacheInterface $cache
66
     * @param \Laminas\Log\LoggerInterface LoggerInterface $logger
1 www 67
     * @param array $config
16769 efrain 68
     * @param \Laminas\Mvc\I18n\Translator $translator
1 www 69
     */
16769 efrain 70
    public function __construct($adapter, $cache, $logger, $config, $translator)
1 www 71
    {
16769 efrain 72
        $this->adapter      = $adapter;
73
        $this->cache        = $cache;
74
        $this->logger       = $logger;
75
        $this->config       = $config;
76
        $this->translator   = $translator;
1 www 77
    }
78
 
79
    /**
80
     *
81
     * Generación del listado de perfiles
82
     * {@inheritDoc}
83
     * @see \Laminas\Mvc\Controller\AbstractActionController::indexAction()
84
     */
85
    public function indexAction()
86
    {
87
        $request = $this->getRequest();
88
 
89
        $currentUserPlugin = $this->plugin('currentUserPlugin');
90
        $currentUser = $currentUserPlugin->getUser();
91
        $currentCompany = $currentUserPlugin->getCompany();
92
 
93
 
94
 
95
 
96
        $request = $this->getRequest();
97
        if($request->isGet()) {
98
 
99
 
100
            $headers  = $request->getHeaders();
101
 
102
            $isJson = false;
103
            if($headers->has('Accept')) {
104
                $accept = $headers->get('Accept');
105
 
106
                $prioritized = $accept->getPrioritized();
107
 
108
                foreach($prioritized as $key => $value) {
109
                    $raw = trim($value->getRaw());
110
 
111
                    if(!$isJson) {
112
                        $isJson = strpos($raw, 'json');
113
                    }
114
 
115
                }
116
            }
117
 
118
            if($isJson) {
119
 
120
 
16766 efrain 121
                $topic_uuid = Functions::sanitizeFilterString($this->params()->fromQuery('topic_uuid'));
1 www 122
 
6829 nelberth 123
                $topicMapper = CompanyMicrolearningTopicMapper::getInstance($this->adapter);
124
                $topic = $topicMapper->fetchOneByUuid($topic_uuid);
1 www 125
 
6829 nelberth 126
                if(!$topic) {
1 www 127
                    return new JsonModel([
128
                       'success' => false,
129
                       'data' => 'ERROR_TOPIC_NOT_FOUND'
130
                    ]);
131
 
132
                }
133
 
6829 nelberth 134
                if($topic->company_id != $currentCompany->id) {
1 www 135
                    return new JsonModel([
136
                        'success'   => false,
137
                        'data'   => 'ERROR_UNAUTHORIZED'
138
                    ]);
139
                }
140
 
141
                $search = $this->params()->fromQuery('search', []);
16766 efrain 142
                $search = empty($search['value']) ? '' :  Functions::sanitizeFilterString($search['value']);
1 www 143
 
144
                $records_x_page     = intval($this->params()->fromQuery('length', 10), 10);
6973 nelberth 145
                $page               = (intval($this->params()->fromQuery('start', 1), 10)/$records_x_page)+1;
1 www 146
                $order =  $this->params()->fromQuery('order', []);
147
                $order_field        = empty($order[0]['column']) ? 99 :  intval($order[0]['column'], 10);
16766 efrain 148
                $order_direction    = empty($order[0]['dir']) ? 'ASC' : strtoupper(Functions::sanitizeFilterString($order[0]['dir']));
1 www 149
 
150
                $fields =  ['name'];
151
                $order_field = isset($fields[$order_field]) ? $fields[$order_field] : 'name';
152
 
153
                if(!in_array($order_direction, ['ASC', 'DESC'])) {
154
                    $order_direction = 'ASC';
155
                }
156
 
157
 
158
 
159
                $acl = $this->getEvent()->getViewModel()->getVariable('acl');
160
                $allowAdd = $acl->isAllowed($currentUser->usertype_id, 'microlearning/content/capsules/add');
161
                $allowEdit = $acl->isAllowed($currentUser->usertype_id, 'microlearning/content/capsules/edit');
162
                $allowDelete = $acl->isAllowed($currentUser->usertype_id, 'microlearning/content/capsules/delete');
163
                $allowUsers = $acl->isAllowed($currentUser->usertype_id, 'microlearning/content/capsules/users');
164
 
165
                $capsuleMapper = CompanyMicrolearningCapsuleMapper::getInstance($this->adapter);
6829 nelberth 166
                $paginator = $capsuleMapper->fetchAllDataTableByCompanyIdAndTopicId($topic->company_id, $topic->id, $search, $page, $records_x_page, $order_field, $order_direction);
1 www 167
 
168
 
169
                $companyMicrolearningCapsuleUserMapper = CompanyMicrolearningCapsuleUserMapper::getInstance($this->adapter);
170
                 $records = $paginator->getCurrentItems();
171
 
172
 
173
                $items = [];
174
                foreach($records as $record)
175
                {
176
 
177
                    //print_r($record);
178
 
6829 nelberth 179
                    $total_users        = $companyMicrolearningCapsuleUserMapper->fetchCountUsersByCompanyIdAndTopicIdAndCapsuleId($topic->company_id, $topic->id, $record->id);
180
                    $total_users_active = $companyMicrolearningCapsuleUserMapper->fetchCountUsersActiveByCompanyIdAndTopicIdAndCapsuleId($topic->company_id, $topic->id, $record->id);
1 www 181
 
182
 
183
 
184
                    switch($record->status) {
185
                        case  CompanyMicrolearningCapsule::STATUS_ACTIVE :
186
                            $status = 'LABEL_ACTIVE';
187
                            break;
188
 
189
                        case  CompanyMicrolearningCapsule::STATUS_INACTIVE :
190
                            $status = 'LABEL_INACTIVE';
191
                            break;
192
 
193
                        default :
194
                            $status = '';
195
                            break;
196
                    }
197
 
198
 
199
                    switch($record->privacy) {
200
                        case  CompanyMicrolearningCapsule::PRIVACY_PUBLIC :
201
                            $privacy = 'LABEL_PUBLIC';
202
                            break;
203
 
204
                        case  CompanyMicrolearningCapsule::PRIVACY_PRIVATE :
205
                            $privacy = 'LABEL_PRIVATE';
206
                            break;
207
 
208
                        default :
209
                            $privacy = '';
210
                            break;
211
                    }
212
 
213
                    switch($record->type) {
214
                        case  CompanyMicrolearningCapsule::TYPE_FREE :
215
                            $type = 'LABEL_FREE';
216
                            break;
217
 
218
                        case  CompanyMicrolearningCapsule::TYPE_PRIVATE :
219
                            $type = 'LABEL_PRIVATE';
220
                            break;
221
 
222
                        case  CompanyMicrolearningCapsule::TYPE_SELLING :
223
                            $type = 'LABEL_SELLING';
224
                            break;
225
 
226
 
227
                        default :
228
                            $privacy = '';
229
                            break;
230
                    }
231
 
232
                    $params = [
6829 nelberth 233
                        'topic_uuid'    => $topic->uuid,
1 www 234
                        'capsule_uuid'  => $record->uuid
235
                    ];
236
 
237
 
238
                    $item = [
239
 
240
                        'name' => $record->name,
241
                        'details' => [
242
                            'status' => $status,
243
                            'privacy' => $privacy,
244
                            'type' => $type,
245
                            'cost' => $record->cost,
246
                            'total_users' => $total_users,
247
                            'total_users_active' => $total_users_active,
248
                         ],
249
 
250
                        'images' => [
251
                            'image' => $this->url()->fromRoute('storage', ['type' => 'microlearning-capsule', 'code' => $record->uuid, 'filename' => $record->image]),
252
                            'marketplace' => $record->marketplace ?  $this->url()->fromRoute('storage', ['type' => 'microlearning-capsule', 'code' => $record->uuid, 'filename' => $record->marketplace]) : '',
253
                        ] ,
254
                        'actions' => [
255
                            'link_edit' => $allowEdit ? $this->url()->fromRoute('microlearning/content/capsules/edit', $params)  : '',
256
                            'link_delete' => $allowDelete ? $this->url()->fromRoute('microlearning/content/capsules/delete', $params)  : '',
257
                            'link_total_users' => $allowUsers && $total_users ? $this->url()->fromRoute('microlearning/content/capsules/users', [
6829 nelberth 258
                                'topic_uuid'    => $topic->uuid,
1 www 259
                                'capsule_uuid'  => $record->uuid,
260
                                'type' => 'all'
261
                             ])  : '',
262
                            'link_total_users_actives' => $allowUsers && $total_users_active ? $this->url()->fromRoute('microlearning/content/capsules/users', [
6829 nelberth 263
                                'topic_uuid'    => $topic->uuid,
1 www 264
                                'capsule_uuid'  => $record->uuid,
265
                                'type' => 'active'
266
                            ])  : '',
267
                        ] ,
268
 
269
 
270
                     ];
271
 
272
 
273
                    array_push($items, $item);
274
                }
275
 
276
 
277
 
278
                return new JsonModel([
279
                    'success' => true,
280
                    'data' => [
6829 nelberth 281
                        'link_add' => $allowAdd ? $this->url()->fromRoute('microlearning/content/capsules/add', ['topic_uuid' => $topic->uuid] )  : '',
1 www 282
                        'items' => $items,
283
                        'total' => $paginator->getTotalItemCount(),
284
                    ]
285
                ]);
286
 
287
 
288
 
289
 
290
 
291
 
292
            } else {
293
 
294
                $image_size = $this->config['leaderslinked.image_sizes.microlearning_image_upload'];
295
                $marketplace_size = $this->config['leaderslinked.image_sizes.marketplace'];
296
 
297
                $form = new CapsuleForm($this->adapter, $currentCompany->id);
298
                $formAdd = new CapsuleAddForm($currentCompany->internal);
299
                $formEdit = new CapsuleEditForm($currentCompany->internal);
300
 
301
                $this->layout()->setTemplate('layout/layout-backend.phtml');
302
                $viewModel = new ViewModel();
303
                $viewModel->setTemplate('leaders-linked/microlearning-capsules/index.phtml');
304
                $viewModel->setVariables([
305
                   'form' => $form,
306
                   'formAdd' => $formAdd,
307
                   'formEdit' => $formEdit,
308
                   'company_uuid' => $currentCompany->uuid,
309
                   'image_size' => $image_size,
310
                   'marketplace_size' => $marketplace_size,
311
 
312
                ]);
313
                return $viewModel ;
314
            }
315
 
316
        } else {
317
            return new JsonModel([
318
                'success' => false,
319
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
320
            ]);
321
        }
322
    }
323
 
324
    public function addAction()
325
    {
326
        $currentUserPlugin  = $this->plugin('currentUserPlugin');
327
        $currentUser        = $currentUserPlugin->getUser();
328
        $currentCompany     = $currentUserPlugin->getCompany();
329
 
330
        $request    = $this->getRequest();
6829 nelberth 331
        $topic_uuid = $this->params()->fromRoute('topic_uuid');
1 www 332
 
6829 nelberth 333
        $topicMapper = CompanyMicrolearningTopicMapper::getInstance($this->adapter);
334
        $topic = $topicMapper->fetchOneByUuid($topic_uuid);
335
        if(!$topic) {
1 www 336
            return new JsonModel([
337
                'success'   => false,
338
                'data'   => 'ERROR_TOPIC_NOT_FOUND'
339
            ]);
340
        }
341
 
6829 nelberth 342
        if($topic->company_id != $currentCompany->id) {
1 www 343
            return new JsonModel([
344
                'success'   => false,
345
                'data'   => 'ERROR_UNAUTHORIZED'
346
            ]);
347
        }
348
 
349
 
350
        if($request->isPost()) {
351
            $form = new  CapsuleAddForm($currentCompany->internal);
352
            $dataPost = array_merge($request->getPost()->toArray(), $request->getFiles()->toArray());
353
 
354
            $form->setData($dataPost);
355
 
356
            if($form->isValid()) {
357
                $dataPost = (array) $form->getData();
358
 
359
                $hydrator = new ObjectPropertyHydrator();
360
                $capsule = new CompanyMicrolearningCapsule();
361
                $hydrator->hydrate($dataPost, $capsule);
362
 
6829 nelberth 363
                $capsule->company_id = $topic->company_id;
364
                $capsule->topic_id = $topic->id;
1458 efrain 365
                $capsule->image = '';
366
                $capsule->marketplace = '';
1 www 367
 
368
                $capsuleMapper = CompanyMicrolearningCapsuleMapper::getInstance($this->adapter);
369
                if($capsuleMapper->insert($capsule)) {
370
 
371
                    $capsule = $capsuleMapper->fetchOne($capsule->id);
372
 
373
                    $target_path = $this->config['leaderslinked.fullpath.microlearning_capsule'] .  $capsule->uuid;
374
                    if(!file_exists($target_path)) {
375
                        mkdir($target_path, 0755, true);
376
                    }
16943 efrain 377
 
1 www 378
                    $files = $this->getRequest()->getFiles()->toArray();
379
                    if(isset($files['file']) && empty($files['file']['error'])) {
380
                        $tmp_filename  = $files['file']['tmp_name'];
16943 efrain 381
                        // $filename      = $this->normalizeString($files['file']['name']);
1 www 382
 
383
                        try {
384
                            list($target_width, $target_height) = explode('x', $this->config['leaderslinked.image_sizes.microlearning_image_size']);
385
 
16943 efrain 386
                            $filename = 'capsule-' .uniqid() . '.jpg';
387
                            $crop_to_dimensions = false;
1 www 388
                            if(Image::uploadImage($tmp_filename, $target_path, $filename, $target_width, $target_height, $crop_to_dimensions)) {
389
                                $capsule->image = $filename;
390
                                $capsuleMapper->update($capsule);
391
                            }
392
                        } catch(\Throwable $e) {
393
                            error_log($e->getTraceAsString());
394
                        }
395
                    }
396
 
16943 efrain 397
                    if(isset($files['marketplace']) && empty($files['marketplace']['error'])) {
1 www 398
                        $tmp_filename  = $files['marketplace']['tmp_name'];
16943 efrain 399
                        // $filename      = $this->normalizeString($files['file']['name']);
1 www 400
 
401
                        try {
16945 efrain 402
                        list($target_width, $target_height) = explode('x', $this->config['leaderslinked.image_sizes.marketplace']);
1 www 403
 
16943 efrain 404
                            $filename = 'marketplace-' .uniqid() . '.jpg';
405
                            $crop_to_dimensions = false;
1 www 406
                            if(Image::uploadImage($tmp_filename, $target_path, $filename, $target_width, $target_height, $crop_to_dimensions)) {
407
                                $capsule->marketplace = $filename;
408
                                $capsuleMapper->update($capsule);
409
                            }
410
                        } catch(\Throwable $e) {
411
                            error_log($e->getTraceAsString());
412
                        }
413
                    }
16943 efrain 414
 
415
 
6829 nelberth 416
                    $this->logger->info('Se agrego la cápsula ' . $topic->name, ['user_id' => $currentUser->id, 'ip' => Functions::getUserIP()]);
1 www 417
 
418
                    $data = [
6945 nelberth 419
                        'success'   => true,
420
                        'data'   => 'LABEL_RECORD_ADDED'
1 www 421
                    ];
422
                } else {
423
                    $data = [
424
                        'success'   => false,
6829 nelberth 425
                        'data'      => $topicMapper->getError()
1 www 426
                    ];
427
 
428
                }
429
 
430
                return new JsonModel($data);
431
 
432
            } else {
433
                $messages = [];
434
                $form_messages = (array) $form->getMessages();
435
                foreach($form_messages  as $fieldname => $field_messages)
436
                {
437
 
438
                    $messages[$fieldname] = array_values($field_messages);
439
                }
440
 
441
                return new JsonModel([
442
                    'success'   => false,
443
                    'data'   => $messages
444
                ]);
445
            }
446
 
447
        } else {
448
            $data = [
449
                'success' => false,
450
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
451
            ];
452
 
453
            return new JsonModel($data);
454
        }
455
 
456
        return new JsonModel($data);
457
    }
458
 
459
    /**
460
     *
461
     * Borrar un perfil excepto el público
462
     * @return \Laminas\View\Model\JsonModel
463
     */
464
    public function deleteAction()
465
    {
466
        $currentUserPlugin = $this->plugin('currentUserPlugin');
467
        $currentUser    = $currentUserPlugin->getUser();
468
        $currentCompany = $currentUserPlugin->getCompany();
469
 
470
        $request        = $this->getRequest();
6829 nelberth 471
        $topic_uuid     = $this->params()->fromRoute('topic_uuid');
1 www 472
        $capsule_uuid   = $this->params()->fromRoute('capsule_uuid');
473
 
474
 
6829 nelberth 475
        $topicMapper = CompanyMicrolearningTopicMapper::getInstance($this->adapter);
476
        $topic = $topicMapper->fetchOneByUuid($topic_uuid);
477
        if(!$topic) {
1 www 478
            return new JsonModel([
479
                'success'   => false,
480
                'data'   => 'ERROR_TOPIC_NOT_FOUND'
481
            ]);
482
        }
483
 
6829 nelberth 484
        if($topic->company_id != $currentCompany->id) {
1 www 485
            return new JsonModel([
486
                'success'   => false,
487
                'data'   => 'ERROR_UNAUTHORIZED'
488
            ]);
489
        }
490
 
491
        $capsuleMapper = CompanyMicrolearningCapsuleMapper::getInstance($this->adapter);
492
        $capsule = $capsuleMapper->fetchOneByUuid($capsule_uuid);
493
        if(!$capsule) {
494
            return new JsonModel([
495
                'success'   => false,
496
                'data'   => 'ERROR_CAPSULE_NOT_FOUND'
497
            ]);
498
        }
499
 
6829 nelberth 500
        if($capsule->topic_id != $topic->id) {
1 www 501
            return new JsonModel([
502
                'success'   => false,
503
                'data'   => 'ERROR_UNAUTHORIZED'
504
            ]);
505
        }
506
 
507
        if($request->isPost()) {
508
 
509
            $result =  $capsuleMapper->delete($capsule);
510
            if($result) {
511
                $this->logger->info('Se borro la cápsula : ' .  $capsule->name, ['user_id' => $currentUser->id, 'ip' => Functions::getUserIP()]);
512
                try {
513
                    $target_path = $this->config['leaderslinked.fullpath.microlearning_capsule'] . $capsule->uuid;
514
                    if(file_exists($target_path)) {
515
                        Functions::rmDirRecursive($target_path);
516
                    }
517
                } catch(\Throwable $e) {
518
                    error_log($e->getTraceAsString());
519
                }
520
 
521
 
522
                $data = [
523
                    'success' => true,
524
                    'data' => 'LABEL_RECORD_DELETED'
525
                ];
526
            } else {
527
 
528
                $data = [
529
                    'success'   => false,
530
                    'data'      => $capsuleMapper->getError()
531
                ];
532
 
533
                return new JsonModel($data);
534
            }
535
 
536
        } else {
537
            $data = [
538
                'success' => false,
539
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
540
            ];
541
 
542
            return new JsonModel($data);
543
        }
544
 
545
        return new JsonModel($data);
546
    }
547
 
548
 
549
    public function editAction()
550
    {
551
        $currentUserPlugin = $this->plugin('currentUserPlugin');
552
        $currentUser    = $currentUserPlugin->getUser();
553
        $currentCompany = $currentUserPlugin->getCompany();
554
 
555
        $request    = $this->getRequest();
6829 nelberth 556
        $topic_uuid     = $this->params()->fromRoute('topic_uuid');
1 www 557
        $capsule_uuid   = $this->params()->fromRoute('capsule_uuid');
558
 
559
 
6829 nelberth 560
        $topicMapper = CompanyMicrolearningTopicMapper::getInstance($this->adapter);
561
        $topic = $topicMapper->fetchOneByUuid($topic_uuid);
562
        if(!$topic) {
1 www 563
            return new JsonModel([
564
                'success'   => false,
565
                'data'   => 'ERROR_TOPIC_NOT_FOUND'
566
            ]);
567
        }
568
 
569
 
570
 
6829 nelberth 571
        if($topic->company_id != $currentCompany->id) {
1 www 572
            return new JsonModel([
573
                'success'   => false,
574
                'data'   => 'ERROR_UNAUTHORIZED'
575
            ]);
576
        }
577
 
578
        $capsuleMapper = CompanyMicrolearningCapsuleMapper::getInstance($this->adapter);
579
        $capsule = $capsuleMapper->fetchOneByUuid($capsule_uuid);
580
        if(!$capsule) {
581
            return new JsonModel([
582
                'success'   => false,
583
                'data'   => 'ERROR_CAPSULE_NOT_FOUND'
584
            ]);
585
        }
586
 
587
 
6829 nelberth 588
        if($capsule->topic_id != $topic->id) {
1 www 589
            return new JsonModel([
590
                'success'   => false,
591
                'data'   => 'ERROR_UNAUTHORIZED'
592
            ]);
593
        }
594
 
595
        if($request->isGet()) {
596
            $data = [
597
                'success' => true,
598
                'data' => [
599
                    'name' => $capsule->name,
600
                    'description' => $capsule->description,
601
                    'order' => $capsule->order,
602
                    'status' => $capsule->status,
603
                    'privacy' => $capsule->privacy,
604
                    'type' => $capsule->type,
6974 nelberth 605
                    'cost' => $capsule->cost,
6983 nelberth 606
                    'image' => $this->url()->fromRoute('storage', ['type' => 'microlearning-capsule', 'code' => $capsule->uuid, 'filename' => $capsule->image]),
607
                    'marketplace' =>  $this->url()->fromRoute('storage', ['type' => 'microlearning-capsule', 'code' => $capsule->uuid, 'filename' => $capsule->marketplace]),
6982 nelberth 608
 
1 www 609
                ]
610
            ];
611
 
612
            return new JsonModel($data);
613
        }
614
        else if($request->isPost()) {
615
            $form = new  CapsuleEditForm($currentCompany->internal);
616
            $dataPost = array_merge($request->getPost()->toArray(), $request->getFiles()->toArray());
617
 
618
            $form->setData($dataPost);
619
 
620
            if($form->isValid()) {
621
                $dataPost = (array) $form->getData();
622
 
623
                $hydrator = new ObjectPropertyHydrator();
624
                $hydrator->hydrate($dataPost, $capsule);
625
 
626
                $capsule->image = null;
627
                $capsule->marketplace = null;
628
 
629
                if($capsuleMapper->update($capsule)) {
630
 
631
                    $capsule = $capsuleMapper->fetchOne($capsule->id);
16943 efrain 632
 
1 www 633
                    $files = $this->getRequest()->getFiles()->toArray();
16943 efrain 634
                    $target_path = $this->config['leaderslinked.fullpath.microlearning_capsule'] .  $capsule->uuid;
635
                    if(!file_exists($target_path)) {
636
                        mkdir($target_path, 0755, true);
637
                    }
638
 
1 www 639
                    if(isset($files['file']) && empty($files['file']['error'])) {
640
                        $tmp_filename  = $files['file']['tmp_name'];
16943 efrain 641
                        // $filename      = $this->normalizeString($files['file']['name']);
1 www 642
 
643
                        try {
16943 efrain 644
                            if($capsule->image) {
1 www 645
 
646
                                if(!image ::delete($target_path, $capsule->image)) {
647
                                    return new JsonModel([
648
                                        'success'   => false,
649
                                        'data'   =>  'ERROR_THERE_WAS_AN_ERROR'
650
                                    ]);
651
                                }
652
                            }
653
 
16943 efrain 654
 
1 www 655
                            list($target_width, $target_height) = explode('x', $this->config['leaderslinked.image_sizes.microlearning_image_size']);
656
 
16943 efrain 657
                            $filename = 'capsule-' .uniqid() . '.jpg';
658
                            $crop_to_dimensions = false;
1 www 659
                            if(Image::uploadImage($tmp_filename, $target_path, $filename, $target_width, $target_height, $crop_to_dimensions)) {
660
                                $capsule->image = $filename;
661
                                $capsuleMapper->update($capsule);
662
                            }
663
                        } catch(\Throwable $e) {
664
                            error_log($e->getTraceAsString());
665
                        }
666
                    }
16945 efrain 667
 
1 www 668
                    if(isset($files['marketplace']) && empty($files['marketplace']['error'])) {
16945 efrain 669
 
670
 
671
 
1 www 672
                        $tmp_filename  = $files['marketplace']['tmp_name'];
16943 efrain 673
                        // $filename      = $this->normalizeString($files['file']['name']);
1 www 674
 
675
                        try {
16943 efrain 676
                            if($capsule->image) {
1 www 677
 
678
                                if(!image ::delete($target_path, $capsule->marketplace)) {
679
                                    return new JsonModel([
680
                                        'success'   => false,
681
                                        'data'   =>  'ERROR_THERE_WAS_AN_ERROR'
682
                                    ]);
683
                                }
684
                            }
685
 
16945 efrain 686
                            list($target_width, $target_height) = explode('x', $this->config['leaderslinked.image_sizes.marketplace']);
1 www 687
 
16943 efrain 688
                            $filename = 'marketplace-' .uniqid() . '.jpg';
689
                            $crop_to_dimensions = false;
1 www 690
                            if(Image::uploadImage($tmp_filename, $target_path, $filename, $target_width, $target_height, $crop_to_dimensions)) {
691
                                $capsule->marketplace = $filename;
692
                                $capsuleMapper->update($capsule);
693
                            }
694
                        } catch(\Throwable $e) {
695
                            error_log($e->getTraceAsString());
696
                        }
697
                    }
16943 efrain 698
 
16945 efrain 699
 
700
 
16943 efrain 701
 
1 www 702
                    $this->logger->info('Se edito la cápsula ' . $capsule->name, ['user_id' => $currentUser->id, 'ip' => Functions::getUserIP()]);
703
 
704
                    $data = [
705
                        'success'   => true,
706
                        'data'   => 'LABEL_RECORD_UPDATED'
707
                    ];
708
                } else {
709
                    $data = [
710
                        'success'   => false,
711
                        'data'      => $capsuleMapper->getError()
712
                    ];
713
 
714
                }
715
 
716
                return new JsonModel($data);
717
 
718
            } else {
719
                $messages = [];
720
                $form_messages = (array) $form->getMessages();
721
                foreach($form_messages  as $fieldname => $field_messages)
722
                {
723
 
724
                    $messages[$fieldname] = array_values($field_messages);
725
                }
726
 
727
                return new JsonModel([
728
                    'success'   => false,
729
                    'data'   => $messages
730
                ]);
731
            }
732
        } else {
733
            $data = [
734
                'success' => false,
735
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
736
            ];
737
 
738
            return new JsonModel($data);
739
        }
740
 
741
        return new JsonModel($data);
742
    }
743
 
744
 
745
    public function usersAction()
746
    {
747
        $currentUserPlugin = $this->plugin('currentUserPlugin');
748
        $currentUser    = $currentUserPlugin->getUser();
749
        $currentCompany = $currentUserPlugin->getCompany();
750
 
751
        $request        = $this->getRequest();
6829 nelberth 752
        $topic_uuid     = $this->params()->fromRoute('topic_uuid');
1 www 753
        $capsule_uuid   = $this->params()->fromRoute('capsule_uuid');
754
        $type           = $this->params()->fromRoute('type');
755
 
756
 
6829 nelberth 757
        $topicMapper = CompanyMicrolearningTopicMapper::getInstance($this->adapter);
758
        $topic = $topicMapper->fetchOneByUuid($topic_uuid);
759
        if(!$topic) {
1 www 760
            return new JsonModel([
761
                'success'   => false,
762
                'data'   => 'ERROR_TOPIC_NOT_FOUND'
763
            ]);
764
        }
765
 
6829 nelberth 766
        if($topic->company_id != $currentCompany->id) {
1 www 767
            return new JsonModel([
768
                'success'   => false,
769
                'data'   => 'ERROR_UNAUTHORIZED'
770
            ]);
771
        }
772
 
773
        $capsuleMapper = CompanyMicrolearningCapsuleMapper::getInstance($this->adapter);
774
        $capsule = $capsuleMapper->fetchOneByUuid($capsule_uuid);
775
        if(!$capsule) {
776
            return new JsonModel([
777
                'success'   => false,
778
                'data'   => 'ERROR_CAPSULE_NOT_FOUND'
779
            ]);
780
        }
781
 
6829 nelberth 782
        if($capsule->topic_id != $topic->id) {
1 www 783
            return new JsonModel([
784
                'success'   => false,
785
                'data'   => 'ERROR_UNAUTHORIZED'
786
            ]);
787
        }
788
 
789
        if($request->isGet()) {
790
 
791
 
792
            $queryMapper = QueryMapper::getInstance($this->adapter);
793
            $sql = $queryMapper->getSql();
794
            $select = $sql->select();
795
            $select->columns(['access', 'paid_from', 'paid_to', 'added_on']);
796
            $select->from(['tb1' => CompanyMicrolearningCapsuleUserMapper::_TABLE] );
797
            $select->join(['tb2' => UserMapper::_TABLE], 'tb1.user_id = tb2.id', ['uuid', 'first_name', 'last_name', 'email']);
798
            $select->where->equalTo('tb1.company_id', $capsule->company_id);
6829 nelberth 799
            $select->where->equalTo('tb1.topic_id', $capsule->topic_id);
1 www 800
            $select->where->equalTo('tb1.capsule_id', $capsule->id);
801
 
802
            if($type == 'active') {
803
                $now = date('Y-m-d H:i:s');
804
                $select->where->nest->equalTo('access', CompanyMicrolearningCapsuleUser::ACCESS_UNLIMITED)->or->nest()
805
                ->equalTo('access', CompanyMicrolearningCapsuleUser::ACCESS_PAY_PERIOD)
806
                ->and->lessThanOrEqualTo('paid_from', $now)->and->greaterThanOrEqualTo('paid_to', $now )->unnest()->unnest();
807
 
808
            }
809
 
810
 
811
            $select->order(['first_name', 'last_name', 'email']);
812
            $records  = $queryMapper->fetchAll($select);
813
 
814
 
815
            $items = [ ];
816
            foreach($records as $record)
817
            {
818
 
819
 
820
 
821
 
822
                switch($record['access'])
823
                {
824
                    case CompanyMicrolearningCapsuleUser::ACCESS_UNLIMITED :
825
                        $details['access'] = 'LABEL_UNLIMIT';
826
                        break;
827
 
828
                    case CompanyMicrolearningCapsuleUser::ACCESS_REVOKE :
829
                        $details['access'] = 'LABEL_REVOKED';
830
                        break;
831
 
832
                    case CompanyMicrolearningCapsuleUser::ACCESS_PAY_PERIOD :
833
                        $dt_paid_from = \DateTime::createFromFormat('Y-m-d', $record['paid_from']);
834
                        $dt_paid_to = \DateTime::createFromFormat('Y-m-d', $record['paid_to']);
835
 
836
                        $details['access'] = 'LABEL_PAY_PERIOD';
837
                        $details['paid_from'] = $dt_paid_from->format('d/m/Y');
838
                        $details['paid_to'] = $dt_paid_to->format('d/m/Y');
839
                        break;
840
 
841
                    case CompanyMicrolearningCapsuleUser::ACCESS_SUPENDED :
842
                        $dt_paid_from = \DateTime::createFromFormat('Y-m-d', $record['paid_from']);
843
                        $dt_paid_to = \DateTime::createFromFormat('Y-m-d', $record['paid_to']);
844
 
845
                        $details['access'] = 'LABEL_SUSPENDED';
846
                        $details['paid_from'] = $dt_paid_from->format('d/m/Y');
847
                        $details['paid_to'] = $dt_paid_to->format('d/m/Y');
848
                        break;
849
 
850
                    case CompanyMicrolearningCapsuleUser::ACCESS_CANCELLED :
851
                        $dt_paid_from = \DateTime::createFromFormat('Y-m-d', $record['paid_from']);
852
                        $dt_paid_to = \DateTime::createFromFormat('Y-m-d', $record['paid_to']);
853
 
854
                        $details['access'] = 'LABEL_CANCELLED';
855
                        $details['paid_from'] = $dt_paid_from->format('d/m/Y');
856
                        $details['paid_to'] = $dt_paid_to->format('d/m/Y');
857
                        break;
858
 
859
                }
860
 
861
 
862
                $item = [
863
                    'first_name' => $record['first_name'],
864
                    'last_name' => $record['last_name'],
865
                    'email' => $record['email'],
866
                    'details' => $details,
867
                ];
868
 
869
 
870
 
871
                array_push($items, $item);
872
 
873
 
874
            }
875
 
876
            return new JsonModel([
877
                'success' => true,
878
                'data' => [
6829 nelberth 879
                    'topic' => $topic->name,
1 www 880
                    'capsule' => $capsule->name,
881
                    'items' => $items,
882
                ]
883
            ]);
884
 
885
 
886
 
887
        } else {
888
            $data = [
889
                'success' => false,
890
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
891
            ];
892
 
893
            return new JsonModel($data);
894
        }
895
 
896
        return new JsonModel($data);
897
    }
898
 
899
}