Proyectos de Subversion LeadersLinked - Backend

Rev

Rev 16769 | Rev 16945 | 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 {
16943 efrain 402
                            list($target_width, $target_height) = explode('x', $this->config['leaderslinked.image_sizes.microlearning_image_size']);
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
                    }
667
 
668
                    if(isset($files['marketplace']) && empty($files['marketplace']['error'])) {
669
                        $tmp_filename  = $files['marketplace']['tmp_name'];
16943 efrain 670
                        // $filename      = $this->normalizeString($files['file']['name']);
1 www 671
 
672
                        try {
16943 efrain 673
                            if($capsule->image) {
1 www 674
 
675
                                if(!image ::delete($target_path, $capsule->marketplace)) {
676
                                    return new JsonModel([
677
                                        'success'   => false,
678
                                        'data'   =>  'ERROR_THERE_WAS_AN_ERROR'
679
                                    ]);
680
                                }
681
                            }
682
 
16943 efrain 683
                            list($target_width, $target_height) = explode('x', $this->config['leaderslinked.image_sizes.microlearning_image_size']);
1 www 684
 
16943 efrain 685
                            $filename = 'marketplace-' .uniqid() . '.jpg';
686
                            $crop_to_dimensions = false;
1 www 687
                            if(Image::uploadImage($tmp_filename, $target_path, $filename, $target_width, $target_height, $crop_to_dimensions)) {
688
                                $capsule->marketplace = $filename;
689
                                $capsuleMapper->update($capsule);
690
                            }
691
                        } catch(\Throwable $e) {
692
                            error_log($e->getTraceAsString());
693
                        }
694
                    }
16943 efrain 695
 
696
 
1 www 697
                    $this->logger->info('Se edito la cápsula ' . $capsule->name, ['user_id' => $currentUser->id, 'ip' => Functions::getUserIP()]);
698
 
699
                    $data = [
700
                        'success'   => true,
701
                        'data'   => 'LABEL_RECORD_UPDATED'
702
                    ];
703
                } else {
704
                    $data = [
705
                        'success'   => false,
706
                        'data'      => $capsuleMapper->getError()
707
                    ];
708
 
709
                }
710
 
711
                return new JsonModel($data);
712
 
713
            } else {
714
                $messages = [];
715
                $form_messages = (array) $form->getMessages();
716
                foreach($form_messages  as $fieldname => $field_messages)
717
                {
718
 
719
                    $messages[$fieldname] = array_values($field_messages);
720
                }
721
 
722
                return new JsonModel([
723
                    'success'   => false,
724
                    'data'   => $messages
725
                ]);
726
            }
727
        } else {
728
            $data = [
729
                'success' => false,
730
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
731
            ];
732
 
733
            return new JsonModel($data);
734
        }
735
 
736
        return new JsonModel($data);
737
    }
738
 
739
 
740
    public function usersAction()
741
    {
742
        $currentUserPlugin = $this->plugin('currentUserPlugin');
743
        $currentUser    = $currentUserPlugin->getUser();
744
        $currentCompany = $currentUserPlugin->getCompany();
745
 
746
        $request        = $this->getRequest();
6829 nelberth 747
        $topic_uuid     = $this->params()->fromRoute('topic_uuid');
1 www 748
        $capsule_uuid   = $this->params()->fromRoute('capsule_uuid');
749
        $type           = $this->params()->fromRoute('type');
750
 
751
 
6829 nelberth 752
        $topicMapper = CompanyMicrolearningTopicMapper::getInstance($this->adapter);
753
        $topic = $topicMapper->fetchOneByUuid($topic_uuid);
754
        if(!$topic) {
1 www 755
            return new JsonModel([
756
                'success'   => false,
757
                'data'   => 'ERROR_TOPIC_NOT_FOUND'
758
            ]);
759
        }
760
 
6829 nelberth 761
        if($topic->company_id != $currentCompany->id) {
1 www 762
            return new JsonModel([
763
                'success'   => false,
764
                'data'   => 'ERROR_UNAUTHORIZED'
765
            ]);
766
        }
767
 
768
        $capsuleMapper = CompanyMicrolearningCapsuleMapper::getInstance($this->adapter);
769
        $capsule = $capsuleMapper->fetchOneByUuid($capsule_uuid);
770
        if(!$capsule) {
771
            return new JsonModel([
772
                'success'   => false,
773
                'data'   => 'ERROR_CAPSULE_NOT_FOUND'
774
            ]);
775
        }
776
 
6829 nelberth 777
        if($capsule->topic_id != $topic->id) {
1 www 778
            return new JsonModel([
779
                'success'   => false,
780
                'data'   => 'ERROR_UNAUTHORIZED'
781
            ]);
782
        }
783
 
784
        if($request->isGet()) {
785
 
786
 
787
            $queryMapper = QueryMapper::getInstance($this->adapter);
788
            $sql = $queryMapper->getSql();
789
            $select = $sql->select();
790
            $select->columns(['access', 'paid_from', 'paid_to', 'added_on']);
791
            $select->from(['tb1' => CompanyMicrolearningCapsuleUserMapper::_TABLE] );
792
            $select->join(['tb2' => UserMapper::_TABLE], 'tb1.user_id = tb2.id', ['uuid', 'first_name', 'last_name', 'email']);
793
            $select->where->equalTo('tb1.company_id', $capsule->company_id);
6829 nelberth 794
            $select->where->equalTo('tb1.topic_id', $capsule->topic_id);
1 www 795
            $select->where->equalTo('tb1.capsule_id', $capsule->id);
796
 
797
            if($type == 'active') {
798
                $now = date('Y-m-d H:i:s');
799
                $select->where->nest->equalTo('access', CompanyMicrolearningCapsuleUser::ACCESS_UNLIMITED)->or->nest()
800
                ->equalTo('access', CompanyMicrolearningCapsuleUser::ACCESS_PAY_PERIOD)
801
                ->and->lessThanOrEqualTo('paid_from', $now)->and->greaterThanOrEqualTo('paid_to', $now )->unnest()->unnest();
802
 
803
            }
804
 
805
 
806
            $select->order(['first_name', 'last_name', 'email']);
807
            $records  = $queryMapper->fetchAll($select);
808
 
809
 
810
            $items = [ ];
811
            foreach($records as $record)
812
            {
813
 
814
 
815
 
816
 
817
                switch($record['access'])
818
                {
819
                    case CompanyMicrolearningCapsuleUser::ACCESS_UNLIMITED :
820
                        $details['access'] = 'LABEL_UNLIMIT';
821
                        break;
822
 
823
                    case CompanyMicrolearningCapsuleUser::ACCESS_REVOKE :
824
                        $details['access'] = 'LABEL_REVOKED';
825
                        break;
826
 
827
                    case CompanyMicrolearningCapsuleUser::ACCESS_PAY_PERIOD :
828
                        $dt_paid_from = \DateTime::createFromFormat('Y-m-d', $record['paid_from']);
829
                        $dt_paid_to = \DateTime::createFromFormat('Y-m-d', $record['paid_to']);
830
 
831
                        $details['access'] = 'LABEL_PAY_PERIOD';
832
                        $details['paid_from'] = $dt_paid_from->format('d/m/Y');
833
                        $details['paid_to'] = $dt_paid_to->format('d/m/Y');
834
                        break;
835
 
836
                    case CompanyMicrolearningCapsuleUser::ACCESS_SUPENDED :
837
                        $dt_paid_from = \DateTime::createFromFormat('Y-m-d', $record['paid_from']);
838
                        $dt_paid_to = \DateTime::createFromFormat('Y-m-d', $record['paid_to']);
839
 
840
                        $details['access'] = 'LABEL_SUSPENDED';
841
                        $details['paid_from'] = $dt_paid_from->format('d/m/Y');
842
                        $details['paid_to'] = $dt_paid_to->format('d/m/Y');
843
                        break;
844
 
845
                    case CompanyMicrolearningCapsuleUser::ACCESS_CANCELLED :
846
                        $dt_paid_from = \DateTime::createFromFormat('Y-m-d', $record['paid_from']);
847
                        $dt_paid_to = \DateTime::createFromFormat('Y-m-d', $record['paid_to']);
848
 
849
                        $details['access'] = 'LABEL_CANCELLED';
850
                        $details['paid_from'] = $dt_paid_from->format('d/m/Y');
851
                        $details['paid_to'] = $dt_paid_to->format('d/m/Y');
852
                        break;
853
 
854
                }
855
 
856
 
857
                $item = [
858
                    'first_name' => $record['first_name'],
859
                    'last_name' => $record['last_name'],
860
                    'email' => $record['email'],
861
                    'details' => $details,
862
                ];
863
 
864
 
865
 
866
                array_push($items, $item);
867
 
868
 
869
            }
870
 
871
            return new JsonModel([
872
                'success' => true,
873
                'data' => [
6829 nelberth 874
                    'topic' => $topic->name,
1 www 875
                    'capsule' => $capsule->name,
876
                    'items' => $items,
877
                ]
878
            ]);
879
 
880
 
881
 
882
        } else {
883
            $data = [
884
                'success' => false,
885
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
886
            ];
887
 
888
            return new JsonModel($data);
889
        }
890
 
891
        return new JsonModel($data);
892
    }
893
 
894
}