Proyectos de Subversion LeadersLinked - Backend

Rev

Rev 6940 | Rev 6942 | 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());
6871 nelberth 395
                    }
6827 nelberth 396
 
6872 nelberth 397
                    $fileBase64Content2 = $this->params()->fromPost('marketplace');
6871 nelberth 398
                    try {
399
 
6872 nelberth 400
                        $fileBase64Content2 = base64_decode($fileBase64Content2);
6871 nelberth 401
                        $target_path = $this->config['leaderslinked.fullpath.microlearning_capsule'] . $capsule->uuid;
6931 nelberth 402
                        $capsule_filename2  = 'marketplace-' .uniqid() . '.jpg';
403
                        $capsule_tmp_filename2 = 'data' . DIRECTORY_SEPARATOR . 'tmp';
404
                        if(!file_exists($capsule_tmp_filename2)) {
405
                            mkdir($capsule_tmp_filename2, 0755, true);
6871 nelberth 406
                        }
6931 nelberth 407
                        $capsule_tmp_filename2 = 'data' . DIRECTORY_SEPARATOR . 'tmp' . DIRECTORY_SEPARATOR . $capsule_filename2;
408
                            file_put_contents($capsule_tmp_filename2, $fileBase64Content2);
6940 nelberth 409
 
6871 nelberth 410
                            list($target_width, $target_height) = explode('x', $this->config['leaderslinked.image_sizes.marketplace']);
6827 nelberth 411
 
6871 nelberth 412
                        $crop_to_dimensions = false;
6931 nelberth 413
                        if(Image::uploadImage($capsule_tmp_filename2, $target_path2, $capsule_filename2, $target_width, $target_height, $crop_to_dimensions )) {
414
                            $capsule->marketplace = basename($capsule_filename2);
6871 nelberth 415
                            $capsuleMapper->update($capsule);
416
                        }
417
                    } catch(\Throwable $e) {
418
                        error_log($e->getTraceAsString());
419
                    }
6829 nelberth 420
                    /*
1 www 421
                    if(isset($files['file']) && empty($files['file']['error'])) {
422
                        $tmp_filename  = $files['file']['tmp_name'];
423
                        //$filename      = $this->normalizeString($files['file']['name']);
424
 
425
                        try {
426
                            list($target_width, $target_height) = explode('x', $this->config['leaderslinked.image_sizes.microlearning_image_size']);
427
 
428
                            $filename = 'capsule-' .uniqid() . '.png';
429
                            $crop_to_dimensions = true;
430
                            if(Image::uploadImage($tmp_filename, $target_path, $filename, $target_width, $target_height, $crop_to_dimensions)) {
431
                                $capsule->image = $filename;
432
                                $capsuleMapper->update($capsule);
433
                            }
434
                        } catch(\Throwable $e) {
435
                            error_log($e->getTraceAsString());
436
                        }
437
                    }
6829 nelberth 438
                    */
1 www 439
 
440
 
6871 nelberth 441
                   /* if(isset($files['marketplace']) && empty($files['marketplace']['error'])) {
1 www 442
                        $tmp_filename  = $files['marketplace']['tmp_name'];
443
                        //$filename      = $this->normalizeString($files['marketplace']['name']);
444
 
445
                        try {
446
 
447
                            list($target_width, $target_height) = explode('x', $this->config['leaderslinked.image_sizes.marketplace']);
448
 
449
                            $filename = 'marketplace-' .uniqid() . '.png';
450
                            $crop_to_dimensions = true;
451
                            if(Image::uploadImage($tmp_filename, $target_path, $filename, $target_width, $target_height, $crop_to_dimensions)) {
452
                                $capsule->marketplace = $filename;
453
                                $capsuleMapper->update($capsule);
454
                            }
455
                        } catch(\Throwable $e) {
456
                            error_log($e->getTraceAsString());
457
                        }
458
                    }
6871 nelberth 459
                    */
6829 nelberth 460
                    $this->logger->info('Se agrego la cápsula ' . $topic->name, ['user_id' => $currentUser->id, 'ip' => Functions::getUserIP()]);
1 www 461
 
462
                    $data = [
463
                        'success'   => true,
464
                        'data'   => 'LABEL_RECORD_ADDED'
465
                    ];
466
                } else {
467
                    $data = [
468
                        'success'   => false,
6829 nelberth 469
                        'data'      => $topicMapper->getError()
1 www 470
                    ];
471
 
472
                }
473
 
474
                return new JsonModel($data);
475
 
476
            } else {
477
                $messages = [];
478
                $form_messages = (array) $form->getMessages();
479
                foreach($form_messages  as $fieldname => $field_messages)
480
                {
481
 
482
                    $messages[$fieldname] = array_values($field_messages);
483
                }
484
 
485
                return new JsonModel([
486
                    'success'   => false,
487
                    'data'   => $messages
488
                ]);
489
            }
490
 
491
        } else {
492
            $data = [
493
                'success' => false,
494
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
495
            ];
496
 
497
            return new JsonModel($data);
498
        }
499
 
500
        return new JsonModel($data);
501
    }
502
 
503
    /**
504
     *
505
     * Borrar un perfil excepto el público
506
     * @return \Laminas\View\Model\JsonModel
507
     */
508
    public function deleteAction()
509
    {
510
        $currentUserPlugin = $this->plugin('currentUserPlugin');
511
        $currentUser    = $currentUserPlugin->getUser();
512
        $currentCompany = $currentUserPlugin->getCompany();
513
 
514
        $request        = $this->getRequest();
6829 nelberth 515
        $topic_uuid     = $this->params()->fromRoute('topic_uuid');
1 www 516
        $capsule_uuid   = $this->params()->fromRoute('capsule_uuid');
517
 
518
 
6829 nelberth 519
        $topicMapper = CompanyMicrolearningTopicMapper::getInstance($this->adapter);
520
        $topic = $topicMapper->fetchOneByUuid($topic_uuid);
521
        if(!$topic) {
1 www 522
            return new JsonModel([
523
                'success'   => false,
524
                'data'   => 'ERROR_TOPIC_NOT_FOUND'
525
            ]);
526
        }
527
 
6829 nelberth 528
        if($topic->company_id != $currentCompany->id) {
1 www 529
            return new JsonModel([
530
                'success'   => false,
531
                'data'   => 'ERROR_UNAUTHORIZED'
532
            ]);
533
        }
534
 
535
        $capsuleMapper = CompanyMicrolearningCapsuleMapper::getInstance($this->adapter);
536
        $capsule = $capsuleMapper->fetchOneByUuid($capsule_uuid);
537
        if(!$capsule) {
538
            return new JsonModel([
539
                'success'   => false,
540
                'data'   => 'ERROR_CAPSULE_NOT_FOUND'
541
            ]);
542
        }
543
 
6829 nelberth 544
        if($capsule->topic_id != $topic->id) {
1 www 545
            return new JsonModel([
546
                'success'   => false,
547
                'data'   => 'ERROR_UNAUTHORIZED'
548
            ]);
549
        }
550
 
551
        if($request->isPost()) {
552
 
553
            $result =  $capsuleMapper->delete($capsule);
554
            if($result) {
555
                $this->logger->info('Se borro la cápsula : ' .  $capsule->name, ['user_id' => $currentUser->id, 'ip' => Functions::getUserIP()]);
556
                try {
557
                    $target_path = $this->config['leaderslinked.fullpath.microlearning_capsule'] . $capsule->uuid;
558
                    if(file_exists($target_path)) {
559
                        Functions::rmDirRecursive($target_path);
560
                    }
561
                } catch(\Throwable $e) {
562
                    error_log($e->getTraceAsString());
563
                }
564
 
565
 
566
                $data = [
567
                    'success' => true,
568
                    'data' => 'LABEL_RECORD_DELETED'
569
                ];
570
            } else {
571
 
572
                $data = [
573
                    'success'   => false,
574
                    'data'      => $capsuleMapper->getError()
575
                ];
576
 
577
                return new JsonModel($data);
578
            }
579
 
580
        } else {
581
            $data = [
582
                'success' => false,
583
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
584
            ];
585
 
586
            return new JsonModel($data);
587
        }
588
 
589
        return new JsonModel($data);
590
    }
591
 
592
 
593
    public function editAction()
594
    {
595
        $currentUserPlugin = $this->plugin('currentUserPlugin');
596
        $currentUser    = $currentUserPlugin->getUser();
597
        $currentCompany = $currentUserPlugin->getCompany();
598
 
599
        $request    = $this->getRequest();
6829 nelberth 600
        $topic_uuid     = $this->params()->fromRoute('topic_uuid');
1 www 601
        $capsule_uuid   = $this->params()->fromRoute('capsule_uuid');
602
 
603
 
6829 nelberth 604
        $topicMapper = CompanyMicrolearningTopicMapper::getInstance($this->adapter);
605
        $topic = $topicMapper->fetchOneByUuid($topic_uuid);
606
        if(!$topic) {
1 www 607
            return new JsonModel([
608
                'success'   => false,
609
                'data'   => 'ERROR_TOPIC_NOT_FOUND'
610
            ]);
611
        }
612
 
613
 
614
 
6829 nelberth 615
        if($topic->company_id != $currentCompany->id) {
1 www 616
            return new JsonModel([
617
                'success'   => false,
618
                'data'   => 'ERROR_UNAUTHORIZED'
619
            ]);
620
        }
621
 
622
        $capsuleMapper = CompanyMicrolearningCapsuleMapper::getInstance($this->adapter);
623
        $capsule = $capsuleMapper->fetchOneByUuid($capsule_uuid);
624
        if(!$capsule) {
625
            return new JsonModel([
626
                'success'   => false,
627
                'data'   => 'ERROR_CAPSULE_NOT_FOUND'
628
            ]);
629
        }
630
 
631
 
6829 nelberth 632
        if($capsule->topic_id != $topic->id) {
1 www 633
            return new JsonModel([
634
                'success'   => false,
635
                'data'   => 'ERROR_UNAUTHORIZED'
636
            ]);
637
        }
638
 
639
        if($request->isGet()) {
640
            $data = [
641
                'success' => true,
642
                'data' => [
643
                    'name' => $capsule->name,
644
                    'description' => $capsule->description,
645
                    'order' => $capsule->order,
646
                    'status' => $capsule->status,
647
                    'privacy' => $capsule->privacy,
648
                    'type' => $capsule->type,
649
                    'cost' => $capsule->cost
650
                ]
651
            ];
652
 
653
            return new JsonModel($data);
654
        }
655
        else if($request->isPost()) {
656
            $form = new  CapsuleEditForm($currentCompany->internal);
657
            $dataPost = array_merge($request->getPost()->toArray(), $request->getFiles()->toArray());
658
 
659
            $form->setData($dataPost);
660
 
661
            if($form->isValid()) {
662
                $dataPost = (array) $form->getData();
663
 
664
                $hydrator = new ObjectPropertyHydrator();
665
                $hydrator->hydrate($dataPost, $capsule);
666
 
667
                $capsule->image = null;
668
                $capsule->marketplace = null;
669
 
670
                if($capsuleMapper->update($capsule)) {
671
 
672
                    $capsule = $capsuleMapper->fetchOne($capsule->id);
673
                    $target_path = $this->config['leaderslinked.fullpath.microlearning_capsule'] .  $capsule->uuid;
674
                    if(!file_exists($target_path)) {
675
                        mkdir($target_path, 0755, true);
676
                    }
677
 
678
 
679
                    $files = $this->getRequest()->getFiles()->toArray();
680
                    if(isset($files['file']) && empty($files['file']['error'])) {
681
                        $tmp_filename  = $files['file']['tmp_name'];
682
                        //$filename      = $this->normalizeString($files['file']['name']);
683
 
684
                        try {
6829 nelberth 685
                            if($topic->image) {
1 www 686
 
687
                                if(!image ::delete($target_path, $capsule->image)) {
688
                                    return new JsonModel([
689
                                        'success'   => false,
690
                                        'data'   =>  'ERROR_THERE_WAS_AN_ERROR'
691
                                    ]);
692
                                }
693
                            }
694
 
695
                            list($target_width, $target_height) = explode('x', $this->config['leaderslinked.image_sizes.microlearning_image_size']);
696
 
697
                            $filename = 'capsule-' .uniqid() . '.png';
698
                            $crop_to_dimensions = true;
699
                            if(Image::uploadImage($tmp_filename, $target_path, $filename, $target_width, $target_height, $crop_to_dimensions)) {
700
                                $capsule->image = $filename;
701
                                $capsuleMapper->update($capsule);
702
                            }
703
                        } catch(\Throwable $e) {
704
                            error_log($e->getTraceAsString());
705
                        }
706
                    }
707
 
708
 
709
 
710
                    if(isset($files['marketplace']) && empty($files['marketplace']['error'])) {
711
                        $tmp_filename  = $files['marketplace']['tmp_name'];
712
                        //$filename      = $this->normalizeString($files['marketplace']['name']);
713
 
714
                        try {
6829 nelberth 715
                            if($topic->marketplace) {
1 www 716
 
717
                                if(!image ::delete($target_path, $capsule->marketplace)) {
718
                                    return new JsonModel([
719
                                        'success'   => false,
720
                                        'data'   =>  'ERROR_THERE_WAS_AN_ERROR'
721
                                    ]);
722
                                }
723
                            }
724
 
725
                            list($target_width, $target_height) = explode('x', $this->config['leaderslinked.image_sizes.marketplace']);
726
 
727
                            $filename = 'marketplace-' .uniqid() . '.png';
728
                            $crop_to_dimensions = true;
729
                            if(Image::uploadImage($tmp_filename, $target_path, $filename, $target_width, $target_height, $crop_to_dimensions)) {
730
                                $capsule->marketplace = $filename;
731
                                $capsuleMapper->update($capsule);
732
                            }
733
                        } catch(\Throwable $e) {
734
                            error_log($e->getTraceAsString());
735
                        }
736
                    }
737
 
738
                    $this->logger->info('Se edito la cápsula ' . $capsule->name, ['user_id' => $currentUser->id, 'ip' => Functions::getUserIP()]);
739
 
740
                    $data = [
741
                        'success'   => true,
742
                        'data'   => 'LABEL_RECORD_UPDATED'
743
                    ];
744
                } else {
745
                    $data = [
746
                        'success'   => false,
747
                        'data'      => $capsuleMapper->getError()
748
                    ];
749
 
750
                }
751
 
752
                return new JsonModel($data);
753
 
754
            } else {
755
                $messages = [];
756
                $form_messages = (array) $form->getMessages();
757
                foreach($form_messages  as $fieldname => $field_messages)
758
                {
759
 
760
                    $messages[$fieldname] = array_values($field_messages);
761
                }
762
 
763
                return new JsonModel([
764
                    'success'   => false,
765
                    'data'   => $messages
766
                ]);
767
            }
768
        } else {
769
            $data = [
770
                'success' => false,
771
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
772
            ];
773
 
774
            return new JsonModel($data);
775
        }
776
 
777
        return new JsonModel($data);
778
    }
779
 
780
 
781
    public function usersAction()
782
    {
783
        $currentUserPlugin = $this->plugin('currentUserPlugin');
784
        $currentUser    = $currentUserPlugin->getUser();
785
        $currentCompany = $currentUserPlugin->getCompany();
786
 
787
        $request        = $this->getRequest();
6829 nelberth 788
        $topic_uuid     = $this->params()->fromRoute('topic_uuid');
1 www 789
        $capsule_uuid   = $this->params()->fromRoute('capsule_uuid');
790
        $type           = $this->params()->fromRoute('type');
791
 
792
 
6829 nelberth 793
        $topicMapper = CompanyMicrolearningTopicMapper::getInstance($this->adapter);
794
        $topic = $topicMapper->fetchOneByUuid($topic_uuid);
795
        if(!$topic) {
1 www 796
            return new JsonModel([
797
                'success'   => false,
798
                'data'   => 'ERROR_TOPIC_NOT_FOUND'
799
            ]);
800
        }
801
 
6829 nelberth 802
        if($topic->company_id != $currentCompany->id) {
1 www 803
            return new JsonModel([
804
                'success'   => false,
805
                'data'   => 'ERROR_UNAUTHORIZED'
806
            ]);
807
        }
808
 
809
        $capsuleMapper = CompanyMicrolearningCapsuleMapper::getInstance($this->adapter);
810
        $capsule = $capsuleMapper->fetchOneByUuid($capsule_uuid);
811
        if(!$capsule) {
812
            return new JsonModel([
813
                'success'   => false,
814
                'data'   => 'ERROR_CAPSULE_NOT_FOUND'
815
            ]);
816
        }
817
 
6829 nelberth 818
        if($capsule->topic_id != $topic->id) {
1 www 819
            return new JsonModel([
820
                'success'   => false,
821
                'data'   => 'ERROR_UNAUTHORIZED'
822
            ]);
823
        }
824
 
825
        if($request->isGet()) {
826
 
827
 
828
            $queryMapper = QueryMapper::getInstance($this->adapter);
829
            $sql = $queryMapper->getSql();
830
            $select = $sql->select();
831
            $select->columns(['access', 'paid_from', 'paid_to', 'added_on']);
832
            $select->from(['tb1' => CompanyMicrolearningCapsuleUserMapper::_TABLE] );
833
            $select->join(['tb2' => UserMapper::_TABLE], 'tb1.user_id = tb2.id', ['uuid', 'first_name', 'last_name', 'email']);
834
            $select->where->equalTo('tb1.company_id', $capsule->company_id);
6829 nelberth 835
            $select->where->equalTo('tb1.topic_id', $capsule->topic_id);
1 www 836
            $select->where->equalTo('tb1.capsule_id', $capsule->id);
837
 
838
            if($type == 'active') {
839
                $now = date('Y-m-d H:i:s');
840
                $select->where->nest->equalTo('access', CompanyMicrolearningCapsuleUser::ACCESS_UNLIMITED)->or->nest()
841
                ->equalTo('access', CompanyMicrolearningCapsuleUser::ACCESS_PAY_PERIOD)
842
                ->and->lessThanOrEqualTo('paid_from', $now)->and->greaterThanOrEqualTo('paid_to', $now )->unnest()->unnest();
843
 
844
            }
845
 
846
 
847
            $select->order(['first_name', 'last_name', 'email']);
848
            $records  = $queryMapper->fetchAll($select);
849
 
850
 
851
            $items = [ ];
852
            foreach($records as $record)
853
            {
854
 
855
 
856
 
857
 
858
                switch($record['access'])
859
                {
860
                    case CompanyMicrolearningCapsuleUser::ACCESS_UNLIMITED :
861
                        $details['access'] = 'LABEL_UNLIMIT';
862
                        break;
863
 
864
                    case CompanyMicrolearningCapsuleUser::ACCESS_REVOKE :
865
                        $details['access'] = 'LABEL_REVOKED';
866
                        break;
867
 
868
                    case CompanyMicrolearningCapsuleUser::ACCESS_PAY_PERIOD :
869
                        $dt_paid_from = \DateTime::createFromFormat('Y-m-d', $record['paid_from']);
870
                        $dt_paid_to = \DateTime::createFromFormat('Y-m-d', $record['paid_to']);
871
 
872
                        $details['access'] = 'LABEL_PAY_PERIOD';
873
                        $details['paid_from'] = $dt_paid_from->format('d/m/Y');
874
                        $details['paid_to'] = $dt_paid_to->format('d/m/Y');
875
                        break;
876
 
877
                    case CompanyMicrolearningCapsuleUser::ACCESS_SUPENDED :
878
                        $dt_paid_from = \DateTime::createFromFormat('Y-m-d', $record['paid_from']);
879
                        $dt_paid_to = \DateTime::createFromFormat('Y-m-d', $record['paid_to']);
880
 
881
                        $details['access'] = 'LABEL_SUSPENDED';
882
                        $details['paid_from'] = $dt_paid_from->format('d/m/Y');
883
                        $details['paid_to'] = $dt_paid_to->format('d/m/Y');
884
                        break;
885
 
886
                    case CompanyMicrolearningCapsuleUser::ACCESS_CANCELLED :
887
                        $dt_paid_from = \DateTime::createFromFormat('Y-m-d', $record['paid_from']);
888
                        $dt_paid_to = \DateTime::createFromFormat('Y-m-d', $record['paid_to']);
889
 
890
                        $details['access'] = 'LABEL_CANCELLED';
891
                        $details['paid_from'] = $dt_paid_from->format('d/m/Y');
892
                        $details['paid_to'] = $dt_paid_to->format('d/m/Y');
893
                        break;
894
 
895
                }
896
 
897
 
898
                $item = [
899
                    'first_name' => $record['first_name'],
900
                    'last_name' => $record['last_name'],
901
                    'email' => $record['email'],
902
                    'details' => $details,
903
                ];
904
 
905
 
906
 
907
                array_push($items, $item);
908
 
909
 
910
            }
911
 
912
            return new JsonModel([
913
                'success' => true,
914
                'data' => [
6829 nelberth 915
                    'topic' => $topic->name,
1 www 916
                    'capsule' => $capsule->name,
917
                    'items' => $items,
918
                ]
919
            ]);
920
 
921
 
922
 
923
        } else {
924
            $data = [
925
                'success' => false,
926
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
927
            ];
928
 
929
            return new JsonModel($data);
930
        }
931
 
932
        return new JsonModel($data);
933
    }
934
 
935
}