Proyectos de Subversion LeadersLinked - Backend

Rev

Rev 17126 | Rev 17128 | 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
use LeadersLinked\Library\Functions;
13
use LeadersLinked\Hydrator\ObjectPropertyHydrator;
14
use LeadersLinked\Library\Image;
17002 efrain 15
use LeadersLinked\Mapper\MicrolearningTopicMapper;
17101 stevensc 16
use LeadersLinked\Mapper\MicrolearningCapsuleMapper;
17002 efrain 17
use LeadersLinked\Model\MicrolearningTopic;
18
use LeadersLinked\Form\Microlearning\TopicAddForm;
19
use LeadersLinked\Form\Microlearning\TopicEditForm;
17081 stevensc 20
use LeadersLinked\Form\Microlearning\TopicForm;
17002 efrain 21
use LeadersLinked\Library\Storage;
17107 stevensc 22
use LeadersLinked\Model\MicrolearningTopicCapsule;
23
use LeadersLinked\Mapper\MicrolearningTopicCapsuleMapper;
1 www 24
 
25
 
26
class MicrolearningTopicController extends AbstractActionController
27
{
28
    /**
29
     *
16769 efrain 30
     * @var \Laminas\Db\Adapter\AdapterInterface
1 www 31
     */
32
    private $adapter;
33
 
34
    /**
35
     *
16769 efrain 36
     * @var \LeadersLinked\Cache\CacheInterface
1 www 37
     */
16769 efrain 38
    private $cache;
39
 
40
 
41
    /**
42
     *
43
     * @var \Laminas\Log\LoggerInterface
44
     */
1 www 45
    private $logger;
46
 
47
    /**
48
     *
49
     * @var array
50
     */
51
    private $config;
52
 
16769 efrain 53
 
1 www 54
    /**
55
     *
16769 efrain 56
     * @var \Laminas\Mvc\I18n\Translator
57
     */
58
    private $translator;
59
 
60
 
61
    /**
62
     *
63
     * @param \Laminas\Db\Adapter\AdapterInterface $adapter
64
     * @param \LeadersLinked\Cache\CacheInterface $cache
65
     * @param \Laminas\Log\LoggerInterface LoggerInterface $logger
1 www 66
     * @param array $config
16769 efrain 67
     * @param \Laminas\Mvc\I18n\Translator $translator
1 www 68
     */
16769 efrain 69
    public function __construct($adapter, $cache, $logger, $config, $translator)
1 www 70
    {
16769 efrain 71
        $this->adapter      = $adapter;
72
        $this->cache        = $cache;
73
        $this->logger       = $logger;
74
        $this->config       = $config;
75
        $this->translator   = $translator;
1 www 76
    }
77
 
78
    /**
79
     *
80
     * Generación del listado de perfiles
81
     * {@inheritDoc}
82
     * @see \Laminas\Mvc\Controller\AbstractActionController::indexAction()
83
     */
84
    public function indexAction()
85
    {
86
        $request = $this->getRequest();
87
        $currentUserPlugin = $this->plugin('currentUserPlugin');
88
        $currentCompany = $currentUserPlugin->getCompany();
89
        $currentUser    = $currentUserPlugin->getUser();
90
 
91
 
92
        $request = $this->getRequest();
93
        if($request->isGet()) {
94
 
95
 
96
            $headers  = $request->getHeaders();
97
 
98
            $isJson = false;
99
            if($headers->has('Accept')) {
100
                $accept = $headers->get('Accept');
101
 
102
                $prioritized = $accept->getPrioritized();
103
 
104
                foreach($prioritized as $key => $value) {
105
                    $raw = trim($value->getRaw());
106
 
107
                    if(!$isJson) {
108
                        $isJson = strpos($raw, 'json');
109
                    }
110
 
111
                }
112
            }
113
 
114
            if($isJson) {
115
                $search = $this->params()->fromQuery('search', []);
16766 efrain 116
                $search = empty($search['value']) ? '' :  Functions::sanitizeFilterString($search['value']);
1 www 117
 
118
                $records_x_page     = intval($this->params()->fromQuery('length', 10), 10);
5655 nelberth 119
                $page               = (intval($this->params()->fromQuery('start', 1), 10)/$records_x_page)+1;
1 www 120
                $order =  $this->params()->fromQuery('order', []);
121
                $order_field        = empty($order[0]['column']) ? 99 :  intval($order[0]['column'], 10);
16766 efrain 122
                $order_direction    = empty($order[0]['dir']) ? 'ASC' : strtoupper(Functions::sanitizeFilterString($order[0]['dir']));
1 www 123
 
124
                $fields =  ['name'];
125
                $order_field = isset($fields[$order_field]) ? $fields[$order_field] : 'name';
126
 
127
                if(!in_array($order_direction, ['ASC', 'DESC'])) {
128
                    $order_direction = 'ASC';
129
                }
130
 
131
 
132
 
133
                $acl = $this->getEvent()->getViewModel()->getVariable('acl');
134
                $allowEdit = $acl->isAllowed($currentUser->usertype_id, 'microlearning/content/topics/edit');
135
                $allowDelete = $acl->isAllowed($currentUser->usertype_id, 'microlearning/content/topics/delete');
136
 
137
 
17002 efrain 138
                $microlearningTopicMapper = MicrolearningTopicMapper::getInstance($this->adapter);
1 www 139
 
17002 efrain 140
                $paginator = $microlearningTopicMapper->fetchAllDataTableByCompanyId($currentCompany->id, $search, $page, $records_x_page, $order_field, $order_direction);
1 www 141
 
17002 efrain 142
 
17018 efrain 143
                $storage = Storage::getInstance($this->config, $this->adapter);
17002 efrain 144
                $path = $storage->getPathMicrolearningTopic();
145
 
1 www 146
                $records = $paginator->getCurrentItems();
147
 
148
                $items = [];
149
                foreach($records as $record)
150
                {
17002 efrain 151
 
1 www 152
                    switch($record->status) {
17002 efrain 153
                        case  MicrolearningTopic::STATUS_ACTIVE :
1 www 154
                            $status = 'LABEL_ACTIVE';
155
                            break;
156
 
17002 efrain 157
                        case  MicrolearningTopic::STATUS_INACTIVE :
1 www 158
                            $status = 'LABEL_INACTIVE';
159
                            break;
160
 
161
                        default :
162
                            $status = '';
163
                            break;
164
                    }
165
 
166
 
167
 
168
 
169
                    $item = [
170
 
171
                        'name' => $record->name,
172
                        'status' => $status,
17002 efrain 173
                        'image' => $storage->getGenericImage($path, $record->uuid, $record->image),
1 www 174
                        'actions' => [
175
                            'link_edit' => $allowEdit ? $this->url()->fromRoute('microlearning/content/topics/edit', ['id' => $record->uuid ])  : '',
176
                            'link_delete' => $allowDelete ? $this->url()->fromRoute('microlearning/content/topics/delete', ['id' => $record->uuid ]) : '',
177
                        ]
178
 
179
 
180
                    ];
181
 
182
 
183
                    array_push($items, $item);
184
                }
185
 
186
 
187
 
188
                return new JsonModel([
189
                    'success' => true,
190
                    'data' => [
191
                        'items' => $items,
192
                        'total' => $paginator->getTotalItemCount(),
193
                    ]
194
                ]);
195
 
196
 
197
 
198
            } else {
199
 
200
                $image_size = $this->config['leaderslinked.image_sizes.microlearning_image_upload'];
16945 efrain 201
 
17081 stevensc 202
 
17111 stevensc 203
                $form = new TopicForm($this->adapter);
204
                $formAdd = new TopicAddForm($this->adapter, $currentCompany->id);
205
                $formEdit = new TopicEditForm($this->adapter);
1 www 206
                $this->layout()->setTemplate('layout/layout-backend.phtml');
207
                $viewModel = new ViewModel();
208
                $viewModel->setTemplate('leaders-linked/microlearning-topics/index.phtml');
209
                $viewModel->setVariables([
17081 stevensc 210
                    'form' => $form,
1 www 211
                   'formAdd' => $formAdd,
212
                   'formEdit' => $formEdit,
213
                   'company_uuid' => $currentCompany->uuid,
214
                   'image_size' => $image_size,
16945 efrain 215
 
1 www 216
                ]);
217
                return $viewModel ;
218
            }
219
 
220
        } else {
221
            return new JsonModel([
222
                'success' => false,
223
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
224
            ]);
225
        }
226
    }
227
 
228
    public function addAction()
229
    {
230
        $currentUserPlugin  = $this->plugin('currentUserPlugin');
231
        $currentCompany     = $currentUserPlugin->getCompany();
232
        $currentUser        = $currentUserPlugin->getUser();
233
 
234
        $request    = $this->getRequest();
16943 efrain 235
 
1 www 236
        if($request->isPost()) {
17126 stevensc 237
            $form = new TopicAddForm($this->adapter, $currentCompany->id);
1 www 238
            $dataPost = array_merge($request->getPost()->toArray(), $request->getFiles()->toArray());
239
 
240
            $form->setData($dataPost);
241
 
242
            if($form->isValid()) {
243
                $dataPost = (array) $form->getData();
17127 stevensc 244
 
17002 efrain 245
                $topic = new MicrolearningTopic();
17127 stevensc 246
                $topic->name = $dataPost['name'];
247
                $topic->description = $dataPost['description'];
248
                $topic->order = $dataPost['order'];
249
                $topic->status = $dataPost['status'];
250
                $topic->company_id = $currentCompany->id;
251
                $topic->image = '';
1 www 252
 
17127 stevensc 253
                $topicMapper = MicrolearningTopicMapper::getInstance($this->adapter);
1 www 254
 
17127 stevensc 255
                if(!$topicMapper->insert($topic)) {
256
                    $data = [
257
                        'success'   => false,
258
                        'data'      => $topicMapper->getError()
259
                    ];
260
                    return new JsonModel($data);
261
                }
262
 
263
                $topic = $topicMapper->fetchOne($topic->id);
1 www 264
 
17127 stevensc 265
                if (!empty($dataPost['capsule_id'])) {
266
                    $capsuleUuids = is_array($dataPost['capsule_id']) ? $dataPost['capsule_id'] : [$dataPost['capsule_id']];
267
                    $capsuleMapper = MicrolearningCapsuleMapper::getInstance($this->adapter);
268
                    $topicCapsuleMapper = MicrolearningTopicCapsuleMapper::getInstance($this->adapter);
16943 efrain 269
 
17127 stevensc 270
                    foreach ($capsuleUuids as $capsuleUuid) {
271
                        $capsule = $capsuleMapper->fetchOneByUuid($capsuleUuid);
17107 stevensc 272
 
17127 stevensc 273
                        if ($capsule) {
274
                            $topicCapsule = new MicrolearningTopicCapsule();
275
                            $topicCapsule->topic_id = $topic->id;
276
                            $topicCapsule->capsule_id = $capsule->id;
277
                            $topicCapsule->company_id = $currentCompany->id;
278
                            $topicCapsuleMapper->insert($topicCapsule);
17107 stevensc 279
                        }
280
                    }
17127 stevensc 281
                }
282
 
283
                $storage = Storage::getInstance($this->config, $this->adapter);
284
                $storage->setFiles($request->getFiles()->toArray());
285
 
286
                if (!$storage->setCurrentFilename('file')) {
287
                    return new JsonModel([
1 www 288
                        'success'   => false,
17127 stevensc 289
                        'data'      => 'ERROR_UPLOAD_IMAGE'
290
                    ]);
291
                }
292
 
293
                $target_size = $this->config['leaderslinked.image_sizes.microlearning_image_size'];
294
                list($target_width, $target_height) = explode('x', $target_size);
295
 
296
                $source_filename = $storage->getTmpFilename();
297
                $filename = 'topic-' . uniqid() . '.png';
298
                $target_filename = $storage->composePathToFilename(
299
                    Storage::TYPE_MICROLEARNING_TOPIC,
300
                    $topic->uuid,
301
                    $filename
302
                );
303
 
304
                if (!$storage->uploadImageCrop($source_filename, $target_filename, $target_width, $target_height)) {
305
                    return new JsonModel([
306
                        'success'   => false,
307
                        'data'      => 'ERROR_UPLOAD_IMAGE'
308
                    ]);
309
                }
310
 
311
                $topic->image = $filename;
312
 
313
                if(!$topicMapper->update($topic)) {
314
                    return new JsonModel([
315
                        'success'   => false,
1 www 316
                        'data'      => $topicMapper->getError()
17127 stevensc 317
                    ]);
1 www 318
                }
319
 
17127 stevensc 320
                $this->logger->info('Se agrego el tópico ' . $topic->name, ['user_id' => $currentUser->id, 'ip' => Functions::getUserIP()]);
321
 
322
                $data = [
323
                    'success'   => true,
324
                    'data'   => 'LABEL_RECORD_ADDED'
325
                ];
326
 
1 www 327
                return new JsonModel($data);
328
            } else {
329
                $messages = [];
330
                $form_messages = (array) $form->getMessages();
331
                foreach($form_messages  as $fieldname => $field_messages)
332
                {
333
 
334
                    $messages[$fieldname] = array_values($field_messages);
335
                }
336
 
337
                return new JsonModel([
338
                    'success'   => false,
339
                    'data'   => $messages
340
                ]);
341
            }
342
 
17093 stevensc 343
        }
17101 stevensc 344
        else if($request->isGet()) {
17093 stevensc 345
            $capsuleMapper = MicrolearningCapsuleMapper::getInstance($this->adapter);
17101 stevensc 346
 
347
            if(!$currentCompany) {
17098 stevensc 348
                return new JsonModel([
349
                    'success' => false,
17101 stevensc 350
                    'data' => 'ERROR_COMPANY_NOT_FOUND'
17098 stevensc 351
                ]);
352
            }
17101 stevensc 353
 
17106 stevensc 354
            $records = $currentCompany ? $capsuleMapper->fetchAllActiveByCompanyId($currentCompany->id) : $capsuleMapper->fetchAllActive();
17100 stevensc 355
            $capsules = [];
17098 stevensc 356
 
357
            foreach($records as $record) {
17093 stevensc 358
                array_push($capsules, [
359
                    'id' => $record->uuid,
360
                    'name' => $record->name,
361
                ]);
362
            }
17097 stevensc 363
 
1 www 364
            $data = [
17093 stevensc 365
                'success' => true,
366
                'data' => [
17106 stevensc 367
                    'capsules' => $capsules
17093 stevensc 368
                ]
369
            ];
370
        }
371
        else {
372
            $data = [
1 www 373
                'success' => false,
374
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
375
            ];
376
        }
377
 
378
        return new JsonModel($data);
379
    }
380
 
381
    /**
382
     *
383
     * Borrar un perfil excepto el público
384
     * @return \Laminas\View\Model\JsonModel
385
     */
386
    public function deleteAction()
387
    {
388
        $currentUserPlugin  = $this->plugin('currentUserPlugin');
389
        $currentCompany     = $currentUserPlugin->getCompany();
390
        $currentUser        = $currentUserPlugin->getUser();
391
 
392
        $request    = $this->getRequest();
393
        $id   = $this->params()->fromRoute('id');
394
 
395
 
17002 efrain 396
        $topicMapper = MicrolearningTopicMapper::getInstance($this->adapter);
1 www 397
        $topic = $topicMapper->fetchOneByUuid($id);
398
        if(!$topic) {
399
            return new JsonModel([
400
                'success'   => false,
401
                'data'   => 'ERROR_TOPIC_NOT_FOUND'
402
            ]);
403
        }
404
 
405
        if($topic->company_id != $currentCompany->id) {
406
            return new JsonModel([
407
                'success'   => false,
408
                'data'   => 'ERROR_UNAUTHORIZED'
409
            ]);
410
        }
411
 
412
 
413
 
414
        if($request->isPost()) {
17002 efrain 415
            $capsuleMapper = MicrolearningCapsuleMapper::getInstance($this->adapter);
1 www 416
            $count = $capsuleMapper->fetchTotalCountByCompanyIdAndTopicId($topic->company_id, $topic->id);
417
            if($count > 0 ) {
418
                return new JsonModel([
419
                    'success'   => false,
420
                    'data'   => 'ERROR_SQL_CANNOT_DELETE_OR_UPDATE_A_PARENT_ROW'
421
                ]);
422
            }
423
 
424
 
425
 
426
            $result = $topicMapper->delete($topic);
427
            if($result) {
428
                $this->logger->info('Se borro el tópico : ' .  $topic->name, ['user_id' => $currentUser->id, 'ip' => Functions::getUserIP()]);
429
 
17018 efrain 430
                $storage = Storage::getInstance($this->config, $this->adapter);
17002 efrain 431
                $target_path = $storage->getPathMicrolearningTopic();
1 www 432
 
17002 efrain 433
                $storage->deleteFile($target_path, $topic->uuid, $topic->image);
434
 
435
 
436
 
1 www 437
                $data = [
438
                    'success' => true,
439
                    'data' => 'LABEL_RECORD_DELETED'
440
                ];
441
            } else {
442
 
443
                $data = [
444
                    'success'   => false,
445
                    'data'      => $topicMapper->getError()
446
                ];
447
 
448
                return new JsonModel($data);
449
            }
450
 
451
        } else {
452
            $data = [
453
                'success' => false,
454
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
455
            ];
456
 
457
            return new JsonModel($data);
458
        }
459
 
460
        return new JsonModel($data);
461
    }
462
 
463
 
464
    public function editAction()
465
    {
466
        $currentUserPlugin  = $this->plugin('currentUserPlugin');
467
        $currentCompany     = $currentUserPlugin->getCompany();
468
        $currentUser        = $currentUserPlugin->getUser();
469
 
470
        $request    = $this->getRequest();
471
        $id   = $this->params()->fromRoute('id');
472
 
17109 stevensc 473
 
474
 
17002 efrain 475
        $topicMapper = MicrolearningTopicMapper::getInstance($this->adapter);
1 www 476
        $topic = $topicMapper->fetchOneByUuid($id);
477
        if(!$topic) {
478
            return new JsonModel([
479
                'success'   => false,
480
                'data'   => 'ERROR_TOPIC_NOT_FOUND'
481
            ]);
482
        }
483
 
484
        if($topic->company_id != $currentCompany->id) {
485
            return new JsonModel([
486
                'success'   => false,
487
                'data'   => 'ERROR_UNAUTHORIZED'
488
            ]);
489
        }
490
 
491
        if($request->isGet()) {
17109 stevensc 492
 
17018 efrain 493
            $storage = Storage::getInstance($this->config, $this->adapter);
17002 efrain 494
            $path = $storage->getPathMicrolearningTopic();
495
 
1 www 496
            $data = [
497
                'success' => true,
498
                'data' => [
499
                    'name' => $topic->name,
500
                    'description' => $topic->description,
501
                    'order' => $topic->order,
502
                    'status' => $topic->status,
17109 stevensc 503
                    'image'=> $storage->getGenericImage($path, $topic->uuid, $topic->image)
1 www 504
                ]
505
            ];
506
 
507
            return new JsonModel($data);
508
        }
509
        else if($request->isPost()) {
510
            $form = new  TopicEditForm();
511
            $dataPost = array_merge($request->getPost()->toArray(), $request->getFiles()->toArray());
512
 
513
            $form->setData($dataPost);
514
 
515
            if($form->isValid()) {
516
                $dataPost = (array) $form->getData();
517
 
518
                $hydrator = new ObjectPropertyHydrator();
519
                $hydrator->hydrate($dataPost, $topic);
520
                $topic->image = null;
16945 efrain 521
 
1 www 522
                if($topicMapper->update($topic)) {
523
                    $topic = $topicMapper->fetchOne($topic->id);
524
 
17002 efrain 525
                    $image = Image::getInstance($this->config);
526
                    $target_path = $image->getStorage()->getPathMicrolearningTopic();
1 www 527
 
17109 stevensc 528
 
1 www 529
                    $files = $this->getRequest()->getFiles()->toArray();
530
                    if(isset($files['file']) && empty($files['file']['error'])) {
531
                        $tmp_filename  = $files['file']['tmp_name'];
17109 stevensc 532
                        //$filename      = \LeadersLinked\Library\Functions::normalizeStringFilename($files['file']['name']);
1 www 533
 
534
                        try {
535
                            if($topic->image) {
17109 stevensc 536
 
17002 efrain 537
                                if(!$image->getStorage()->deleteFile($target_path, $topic->uuid, $topic->image)) {
1 www 538
                                    return new JsonModel([
539
                                        'success'   => false,
540
                                        'data'   =>  'ERROR_THERE_WAS_AN_ERROR'
541
                                    ]);
542
                                }
543
                            }
544
 
545
                            list($target_width, $target_height) = explode('x', $this->config['leaderslinked.image_sizes.microlearning_image_size']);
546
 
547
                            $filename = 'topic-' .uniqid() . '.png';
16943 efrain 548
                            $crop_to_dimensions = false;
17002 efrain 549
                            $unlink_source = true;
550
 
17018 efrain 551
                            if($image->uploadProcessChangeSize($tmp_filename, $target_path, $topic->uuid, $filename, $target_width, $target_height, $crop_to_dimensions, $unlink_source)) {
1 www 552
                                $topic->image = $filename;
553
                                $topicMapper->update($topic);
554
                            }
555
                        } catch(\Throwable $e) {
556
                            error_log($e->getTraceAsString());
557
                        }
558
                    }
559
 
17109 stevensc 560
 
561
 
562
 
1 www 563
                    $this->logger->info('Se edito el tópico ' . $topic->name, ['user_id' => $currentUser->id, 'ip' => Functions::getUserIP()]);
564
 
565
                    $data = [
566
                        'success'   => true,
567
                        'data'   => 'LABEL_RECORD_UPDATED'
16943 efrain 568
                    ];
1 www 569
                } else {
570
                    $data = [
571
                        'success'   => false,
572
                        'data'      => $topicMapper->getError()
573
                    ];
574
 
575
                }
576
 
577
                return new JsonModel($data);
578
 
579
            } else {
580
                $messages = [];
581
                $form_messages = (array) $form->getMessages();
582
                foreach($form_messages  as $fieldname => $field_messages)
583
                {
17109 stevensc 584
 
1 www 585
                    $messages[$fieldname] = array_values($field_messages);
586
                }
587
 
588
                return new JsonModel([
589
                    'success'   => false,
590
                    'data'   => $messages
591
                ]);
592
            }
593
        } else {
594
            $data = [
595
                'success' => false,
596
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
597
            ];
598
 
599
            return new JsonModel($data);
600
        }
17109 stevensc 601
 
602
        return new JsonModel($data);
1 www 603
    }
604
}