Proyectos de Subversion LeadersLinked - Backend

Rev

Rev 17128 | Rev 17132 | 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
 
17129 stevensc 245
                return new JsonModel([
246
                    'success'   => true,
247
                    'data'      => $dataPost
248
                ]);
249
 
17002 efrain 250
                $topic = new MicrolearningTopic();
17127 stevensc 251
                $topic->name = $dataPost['name'];
252
                $topic->description = $dataPost['description'];
253
                $topic->order = $dataPost['order'];
254
                $topic->status = $dataPost['status'];
255
                $topic->company_id = $currentCompany->id;
256
                $topic->image = '';
1 www 257
 
17127 stevensc 258
                $topicMapper = MicrolearningTopicMapper::getInstance($this->adapter);
1 www 259
 
17127 stevensc 260
                if(!$topicMapper->insert($topic)) {
261
                    $data = [
262
                        'success'   => false,
263
                        'data'      => $topicMapper->getError()
264
                    ];
265
                    return new JsonModel($data);
266
                }
267
 
268
                $topic = $topicMapper->fetchOne($topic->id);
1 www 269
 
17128 stevensc 270
                $capsuleUuids = $dataPost['capsule_id'];
271
                $capsuleMapper = MicrolearningCapsuleMapper::getInstance($this->adapter);
272
                $topicCapsuleMapper = MicrolearningTopicCapsuleMapper::getInstance($this->adapter);
273
 
274
                foreach ($capsuleUuids as $capsuleUuid) {
275
                    $capsule = $capsuleMapper->fetchOneByUuid($capsuleUuid);
16943 efrain 276
 
17128 stevensc 277
                    if ($capsule) {
278
                        $topicCapsule = new MicrolearningTopicCapsule();
279
                        $topicCapsule->topic_id = $topic->id;
280
                        $topicCapsule->capsule_id = $capsule->id;
281
                        $topicCapsule->company_id = $currentCompany->id;
282
                        $topicCapsuleMapper->insert($topicCapsule);
17107 stevensc 283
                    }
17127 stevensc 284
                }
285
 
286
                $storage = Storage::getInstance($this->config, $this->adapter);
287
                $storage->setFiles($request->getFiles()->toArray());
288
 
289
                if (!$storage->setCurrentFilename('file')) {
290
                    return new JsonModel([
1 www 291
                        'success'   => false,
17127 stevensc 292
                        'data'      => 'ERROR_UPLOAD_IMAGE'
293
                    ]);
294
                }
295
 
296
                $target_size = $this->config['leaderslinked.image_sizes.microlearning_image_size'];
297
                list($target_width, $target_height) = explode('x', $target_size);
298
 
299
                $source_filename = $storage->getTmpFilename();
300
                $filename = 'topic-' . uniqid() . '.png';
301
                $target_filename = $storage->composePathToFilename(
302
                    Storage::TYPE_MICROLEARNING_TOPIC,
303
                    $topic->uuid,
304
                    $filename
305
                );
306
 
307
                if (!$storage->uploadImageCrop($source_filename, $target_filename, $target_width, $target_height)) {
308
                    return new JsonModel([
309
                        'success'   => false,
310
                        'data'      => 'ERROR_UPLOAD_IMAGE'
311
                    ]);
312
                }
313
 
314
                $topic->image = $filename;
315
 
316
                if(!$topicMapper->update($topic)) {
317
                    return new JsonModel([
318
                        'success'   => false,
1 www 319
                        'data'      => $topicMapper->getError()
17127 stevensc 320
                    ]);
1 www 321
                }
322
 
17127 stevensc 323
                $this->logger->info('Se agrego el tópico ' . $topic->name, ['user_id' => $currentUser->id, 'ip' => Functions::getUserIP()]);
324
 
325
                $data = [
326
                    'success'   => true,
327
                    'data'   => 'LABEL_RECORD_ADDED'
328
                ];
329
 
1 www 330
                return new JsonModel($data);
331
            } else {
332
                $messages = [];
333
                $form_messages = (array) $form->getMessages();
334
                foreach($form_messages  as $fieldname => $field_messages)
335
                {
336
 
337
                    $messages[$fieldname] = array_values($field_messages);
338
                }
339
 
340
                return new JsonModel([
341
                    'success'   => false,
342
                    'data'   => $messages
343
                ]);
344
            }
345
 
17093 stevensc 346
        }
17101 stevensc 347
        else if($request->isGet()) {
17093 stevensc 348
            $capsuleMapper = MicrolearningCapsuleMapper::getInstance($this->adapter);
17101 stevensc 349
 
350
            if(!$currentCompany) {
17098 stevensc 351
                return new JsonModel([
352
                    'success' => false,
17101 stevensc 353
                    'data' => 'ERROR_COMPANY_NOT_FOUND'
17098 stevensc 354
                ]);
355
            }
17101 stevensc 356
 
17106 stevensc 357
            $records = $currentCompany ? $capsuleMapper->fetchAllActiveByCompanyId($currentCompany->id) : $capsuleMapper->fetchAllActive();
17100 stevensc 358
            $capsules = [];
17098 stevensc 359
 
360
            foreach($records as $record) {
17093 stevensc 361
                array_push($capsules, [
362
                    'id' => $record->uuid,
363
                    'name' => $record->name,
364
                ]);
365
            }
17097 stevensc 366
 
1 www 367
            $data = [
17093 stevensc 368
                'success' => true,
369
                'data' => [
17106 stevensc 370
                    'capsules' => $capsules
17093 stevensc 371
                ]
372
            ];
373
        }
374
        else {
375
            $data = [
1 www 376
                'success' => false,
377
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
378
            ];
379
        }
380
 
381
        return new JsonModel($data);
382
    }
383
 
384
    /**
385
     *
386
     * Borrar un perfil excepto el público
387
     * @return \Laminas\View\Model\JsonModel
388
     */
389
    public function deleteAction()
390
    {
391
        $currentUserPlugin  = $this->plugin('currentUserPlugin');
392
        $currentCompany     = $currentUserPlugin->getCompany();
393
        $currentUser        = $currentUserPlugin->getUser();
394
 
395
        $request    = $this->getRequest();
396
        $id   = $this->params()->fromRoute('id');
397
 
398
 
17002 efrain 399
        $topicMapper = MicrolearningTopicMapper::getInstance($this->adapter);
1 www 400
        $topic = $topicMapper->fetchOneByUuid($id);
401
        if(!$topic) {
402
            return new JsonModel([
403
                'success'   => false,
404
                'data'   => 'ERROR_TOPIC_NOT_FOUND'
405
            ]);
406
        }
407
 
408
        if($topic->company_id != $currentCompany->id) {
409
            return new JsonModel([
410
                'success'   => false,
411
                'data'   => 'ERROR_UNAUTHORIZED'
412
            ]);
413
        }
414
 
415
 
416
 
417
        if($request->isPost()) {
17002 efrain 418
            $capsuleMapper = MicrolearningCapsuleMapper::getInstance($this->adapter);
1 www 419
            $count = $capsuleMapper->fetchTotalCountByCompanyIdAndTopicId($topic->company_id, $topic->id);
420
            if($count > 0 ) {
421
                return new JsonModel([
422
                    'success'   => false,
423
                    'data'   => 'ERROR_SQL_CANNOT_DELETE_OR_UPDATE_A_PARENT_ROW'
424
                ]);
425
            }
426
 
427
 
428
 
429
            $result = $topicMapper->delete($topic);
430
            if($result) {
431
                $this->logger->info('Se borro el tópico : ' .  $topic->name, ['user_id' => $currentUser->id, 'ip' => Functions::getUserIP()]);
432
 
17018 efrain 433
                $storage = Storage::getInstance($this->config, $this->adapter);
17002 efrain 434
                $target_path = $storage->getPathMicrolearningTopic();
1 www 435
 
17002 efrain 436
                $storage->deleteFile($target_path, $topic->uuid, $topic->image);
437
 
438
 
439
 
1 www 440
                $data = [
441
                    'success' => true,
442
                    'data' => 'LABEL_RECORD_DELETED'
443
                ];
444
            } else {
445
 
446
                $data = [
447
                    'success'   => false,
448
                    'data'      => $topicMapper->getError()
449
                ];
450
 
451
                return new JsonModel($data);
452
            }
453
 
454
        } else {
455
            $data = [
456
                'success' => false,
457
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
458
            ];
459
 
460
            return new JsonModel($data);
461
        }
462
 
463
        return new JsonModel($data);
464
    }
465
 
466
 
467
    public function editAction()
468
    {
469
        $currentUserPlugin  = $this->plugin('currentUserPlugin');
470
        $currentCompany     = $currentUserPlugin->getCompany();
471
        $currentUser        = $currentUserPlugin->getUser();
472
 
473
        $request    = $this->getRequest();
474
        $id   = $this->params()->fromRoute('id');
475
 
17109 stevensc 476
 
477
 
17002 efrain 478
        $topicMapper = MicrolearningTopicMapper::getInstance($this->adapter);
1 www 479
        $topic = $topicMapper->fetchOneByUuid($id);
480
        if(!$topic) {
481
            return new JsonModel([
482
                'success'   => false,
483
                'data'   => 'ERROR_TOPIC_NOT_FOUND'
484
            ]);
485
        }
486
 
487
        if($topic->company_id != $currentCompany->id) {
488
            return new JsonModel([
489
                'success'   => false,
490
                'data'   => 'ERROR_UNAUTHORIZED'
491
            ]);
492
        }
493
 
494
        if($request->isGet()) {
17109 stevensc 495
 
17018 efrain 496
            $storage = Storage::getInstance($this->config, $this->adapter);
17002 efrain 497
            $path = $storage->getPathMicrolearningTopic();
498
 
1 www 499
            $data = [
500
                'success' => true,
501
                'data' => [
502
                    'name' => $topic->name,
503
                    'description' => $topic->description,
504
                    'order' => $topic->order,
505
                    'status' => $topic->status,
17109 stevensc 506
                    'image'=> $storage->getGenericImage($path, $topic->uuid, $topic->image)
1 www 507
                ]
508
            ];
509
 
510
            return new JsonModel($data);
511
        }
512
        else if($request->isPost()) {
513
            $form = new  TopicEditForm();
514
            $dataPost = array_merge($request->getPost()->toArray(), $request->getFiles()->toArray());
515
 
516
            $form->setData($dataPost);
517
 
518
            if($form->isValid()) {
519
                $dataPost = (array) $form->getData();
520
 
521
                $hydrator = new ObjectPropertyHydrator();
522
                $hydrator->hydrate($dataPost, $topic);
523
                $topic->image = null;
16945 efrain 524
 
1 www 525
                if($topicMapper->update($topic)) {
526
                    $topic = $topicMapper->fetchOne($topic->id);
527
 
17002 efrain 528
                    $image = Image::getInstance($this->config);
529
                    $target_path = $image->getStorage()->getPathMicrolearningTopic();
1 www 530
 
17109 stevensc 531
 
1 www 532
                    $files = $this->getRequest()->getFiles()->toArray();
533
                    if(isset($files['file']) && empty($files['file']['error'])) {
534
                        $tmp_filename  = $files['file']['tmp_name'];
17109 stevensc 535
                        //$filename      = \LeadersLinked\Library\Functions::normalizeStringFilename($files['file']['name']);
1 www 536
 
537
                        try {
538
                            if($topic->image) {
17109 stevensc 539
 
17002 efrain 540
                                if(!$image->getStorage()->deleteFile($target_path, $topic->uuid, $topic->image)) {
1 www 541
                                    return new JsonModel([
542
                                        'success'   => false,
543
                                        'data'   =>  'ERROR_THERE_WAS_AN_ERROR'
544
                                    ]);
545
                                }
546
                            }
547
 
548
                            list($target_width, $target_height) = explode('x', $this->config['leaderslinked.image_sizes.microlearning_image_size']);
549
 
550
                            $filename = 'topic-' .uniqid() . '.png';
16943 efrain 551
                            $crop_to_dimensions = false;
17002 efrain 552
                            $unlink_source = true;
553
 
17018 efrain 554
                            if($image->uploadProcessChangeSize($tmp_filename, $target_path, $topic->uuid, $filename, $target_width, $target_height, $crop_to_dimensions, $unlink_source)) {
1 www 555
                                $topic->image = $filename;
556
                                $topicMapper->update($topic);
557
                            }
558
                        } catch(\Throwable $e) {
559
                            error_log($e->getTraceAsString());
560
                        }
561
                    }
562
 
17109 stevensc 563
 
564
 
565
 
1 www 566
                    $this->logger->info('Se edito el tópico ' . $topic->name, ['user_id' => $currentUser->id, 'ip' => Functions::getUserIP()]);
567
 
568
                    $data = [
569
                        'success'   => true,
570
                        'data'   => 'LABEL_RECORD_UPDATED'
16943 efrain 571
                    ];
1 www 572
                } else {
573
                    $data = [
574
                        'success'   => false,
575
                        'data'      => $topicMapper->getError()
576
                    ];
577
 
578
                }
579
 
580
                return new JsonModel($data);
581
 
582
            } else {
583
                $messages = [];
584
                $form_messages = (array) $form->getMessages();
585
                foreach($form_messages  as $fieldname => $field_messages)
586
                {
17109 stevensc 587
 
1 www 588
                    $messages[$fieldname] = array_values($field_messages);
589
                }
590
 
591
                return new JsonModel([
592
                    'success'   => false,
593
                    'data'   => $messages
594
                ]);
595
            }
596
        } else {
597
            $data = [
598
                'success' => false,
599
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
600
            ];
601
 
602
            return new JsonModel($data);
603
        }
17109 stevensc 604
 
605
        return new JsonModel($data);
1 www 606
    }
607
}