Proyectos de Subversion LeadersLinked - Backend

Rev

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