Proyectos de Subversion LeadersLinked - Backend

Rev

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