Proyectos de Subversion LeadersLinked - Backend

Rev

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