Proyectos de Subversion LeadersLinked - Backend

Rev

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