Proyectos de Subversion LeadersLinked - Backend

Rev

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