Proyectos de Subversion LeadersLinked - Backend

Rev

Rev 6830 | Rev 6871 | Ir a la última revisión | | Comparar con el anterior | Ultima modificación | Ver Log |

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