Proyectos de Subversion LeadersLinked - Backend

Rev

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

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