Proyectos de Subversion LeadersLinked - Backend

Rev

Rev 1458 | Rev 5576 | 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();
221
 
222
        if($request->isPost()) {
223
            $form = new  TopicAddForm();
224
            $dataPost = array_merge($request->getPost()->toArray(), $request->getFiles()->toArray());
225
 
226
            $form->setData($dataPost);
227
 
228
            if($form->isValid()) {
229
                $dataPost = (array) $form->getData();
230
 
231
                $hydrator = new ObjectPropertyHydrator();
232
                $topic = new CompanyMicrolearningTopic();
233
                $hydrator->hydrate($dataPost, $topic);
234
 
235
                $topic->company_id = $currentCompany->id;
236
                $topic->image = null;
237
 
238
 
239
 
240
                $topicMapper = CompanyMicrolearningTopicMapper::getInstance($this->adapter);
241
                if($topicMapper->insert($topic)) {
242
                    $topic = $topicMapper->fetchOne($topic->id);
243
 
1458 efrain 244
                    //leaderslinked.fullpath.recruitment_selection/uuid vacante/uuid candidato
5574 nelberth 245
                    try {
246
                        $target_path = $this->config['leaderslinked.fullpath.microlearning_topic'] . $topic->uuid;
247
                        if(!file_exists($target_path)) {
248
                            mkdir($target_path, 0755, true);
249
                        }
250
 
251
                        list($target_width, $target_height) = explode('x', $this->config['leaderslinked.image_sizes.microlearning_image_size']);
252
 
253
                        $topic_filename = substr($topic_filename, 0, strrpos($topic_filename, '.'))  . '.png';
254
                        $crop_to_dimensions = false;
255
                        if(Image::uploadImage($topic_tmp_filename, $target_path, $topic_filename, $target_width, $target_height, $crop_to_dimensions )) {
256
                            $topic->image = basename($topic_filename);
257
                            $topicMapper->update($topic);
258
                        }
259
                    } catch(\Throwable $e) {
260
                        error_log($e->getTraceAsString());
261
                    }
1 www 262
 
5574 nelberth 263
                  /*  $target_path = $this->config['leaderslinked.fullpath.microlearning_topic'] .  $topic->uuid;
1 www 264
                    if(!file_exists($target_path)) {
265
                        mkdir($target_path, 0755, true);
266
                    }
267
 
268
 
269
                    $files = $this->getRequest()->getFiles()->toArray();
270
                    if(isset($files['file']) && empty($files['file']['error'])) {
271
                        $tmp_filename  = $files['file']['tmp_name'];
272
 
273
                        try {
274
                            list($target_width, $target_height) = explode('x', $this->config['leaderslinked.image_sizes.microlearning_image_size']);
275
 
276
                            $filename = 'topic-' .uniqid() . '.png';
277
                            $crop_to_dimensions = true;
278
                            if(Image::uploadImage($tmp_filename, $target_path, $filename, $target_width, $target_height, $crop_to_dimensions)) {
279
                                $topic->image = $filename;
280
                                $topicMapper->update($topic);
281
                            }
282
                        } catch(\Throwable $e) {
283
                            error_log($e->getTraceAsString());
284
                        }
285
                    }
5574 nelberth 286
                    */
1 www 287
 
288
 
289
 
290
                    $this->logger->info('Se agrego el tópico ' . $topic->name, ['user_id' => $currentUser->id, 'ip' => Functions::getUserIP()]);
291
 
292
                    $data = [
293
                        'success'   => true,
294
                        'data'   => 'LABEL_RECORD_ADDED'
295
                    ];
296
                } else {
297
                    $data = [
298
                        'success'   => false,
299
                        'data'      => $topicMapper->getError()
300
                    ];
301
 
302
                }
303
 
304
                return new JsonModel($data);
305
 
306
            } else {
307
                $messages = [];
308
                $form_messages = (array) $form->getMessages();
309
                foreach($form_messages  as $fieldname => $field_messages)
310
                {
311
 
312
                    $messages[$fieldname] = array_values($field_messages);
313
                }
314
 
315
                return new JsonModel([
316
                    'success'   => false,
317
                    'data'   => $messages
318
                ]);
319
            }
320
 
321
        } else {
322
            $data = [
323
                'success' => false,
324
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
325
            ];
326
 
327
            return new JsonModel($data);
328
        }
329
 
330
        return new JsonModel($data);
331
    }
332
 
333
    /**
334
     *
335
     * Borrar un perfil excepto el público
336
     * @return \Laminas\View\Model\JsonModel
337
     */
338
    public function deleteAction()
339
    {
340
        $currentUserPlugin  = $this->plugin('currentUserPlugin');
341
        $currentCompany     = $currentUserPlugin->getCompany();
342
        $currentUser        = $currentUserPlugin->getUser();
343
 
344
        $request    = $this->getRequest();
345
        $id   = $this->params()->fromRoute('id');
346
 
347
 
348
        $topicMapper = CompanyMicrolearningTopicMapper::getInstance($this->adapter);
349
        $topic = $topicMapper->fetchOneByUuid($id);
350
        if(!$topic) {
351
            return new JsonModel([
352
                'success'   => false,
353
                'data'   => 'ERROR_TOPIC_NOT_FOUND'
354
            ]);
355
        }
356
 
357
        if($topic->company_id != $currentCompany->id) {
358
            return new JsonModel([
359
                'success'   => false,
360
                'data'   => 'ERROR_UNAUTHORIZED'
361
            ]);
362
        }
363
 
364
 
365
 
366
        if($request->isPost()) {
367
            $capsuleMapper = CompanyMicrolearningCapsuleMapper::getInstance($this->adapter);
368
            $count = $capsuleMapper->fetchTotalCountByCompanyIdAndTopicId($topic->company_id, $topic->id);
369
            if($count > 0 ) {
370
                return new JsonModel([
371
                    'success'   => false,
372
                    'data'   => 'ERROR_SQL_CANNOT_DELETE_OR_UPDATE_A_PARENT_ROW'
373
                ]);
374
            }
375
 
376
 
377
 
378
            $result = $topicMapper->delete($topic);
379
            if($result) {
380
                $this->logger->info('Se borro el tópico : ' .  $topic->name, ['user_id' => $currentUser->id, 'ip' => Functions::getUserIP()]);
381
                try {
382
                    $target_path = $this->config['leaderslinked.fullpath.microlearning_topic'] . DIRECTORY_SEPARATOR . $topic->uuid;
383
                    if(file_exists($target_path)) {
384
                        Functions::rmDirRecursive($target_path);
385
                    }
386
                } catch(\Throwable $e) {
387
                    error_log($e->getTraceAsString());
388
                }
389
 
390
 
391
                $data = [
392
                    'success' => true,
393
                    'data' => 'LABEL_RECORD_DELETED'
394
                ];
395
            } else {
396
 
397
                $data = [
398
                    'success'   => false,
399
                    'data'      => $topicMapper->getError()
400
                ];
401
 
402
                return new JsonModel($data);
403
            }
404
 
405
        } else {
406
            $data = [
407
                'success' => false,
408
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
409
            ];
410
 
411
            return new JsonModel($data);
412
        }
413
 
414
        return new JsonModel($data);
415
    }
416
 
417
 
418
    public function editAction()
419
    {
420
        $currentUserPlugin  = $this->plugin('currentUserPlugin');
421
        $currentCompany     = $currentUserPlugin->getCompany();
422
        $currentUser        = $currentUserPlugin->getUser();
423
 
424
        $request    = $this->getRequest();
425
        $id   = $this->params()->fromRoute('id');
426
 
427
 
428
 
429
        $topicMapper = CompanyMicrolearningTopicMapper::getInstance($this->adapter);
430
        $topic = $topicMapper->fetchOneByUuid($id);
431
        if(!$topic) {
432
            return new JsonModel([
433
                'success'   => false,
434
                'data'   => 'ERROR_TOPIC_NOT_FOUND'
435
            ]);
436
        }
437
 
438
        if($topic->company_id != $currentCompany->id) {
439
            return new JsonModel([
440
                'success'   => false,
441
                'data'   => 'ERROR_UNAUTHORIZED'
442
            ]);
443
        }
444
 
445
        if($request->isGet()) {
446
            $data = [
447
                'success' => true,
448
                'data' => [
449
                    'name' => $topic->name,
450
                    'description' => $topic->description,
451
                    'order' => $topic->order,
452
                    'status' => $topic->status,
453
                ]
454
            ];
455
 
456
            return new JsonModel($data);
457
        }
458
        else if($request->isPost()) {
459
            $form = new  TopicEditForm();
460
            $dataPost = array_merge($request->getPost()->toArray(), $request->getFiles()->toArray());
461
 
462
            $form->setData($dataPost);
463
 
464
            if($form->isValid()) {
465
                $dataPost = (array) $form->getData();
466
 
467
                $hydrator = new ObjectPropertyHydrator();
468
                $hydrator->hydrate($dataPost, $topic);
469
                $topic->image = null;
470
                $topic->marketplace = null;
471
 
472
                if($topicMapper->update($topic)) {
473
                    $topic = $topicMapper->fetchOne($topic->id);
474
 
475
 
476
                    $target_path = $this->config['leaderslinked.fullpath.microlearning_topic'] .  $topic->uuid;
477
                    if(!file_exists($target_path)) {
478
                        mkdir($target_path, 0755, true);
479
                    }
480
 
481
 
482
                    $files = $this->getRequest()->getFiles()->toArray();
483
                    if(isset($files['file']) && empty($files['file']['error'])) {
484
                        $tmp_filename  = $files['file']['tmp_name'];
485
                        //$filename      = $this->normalizeString($files['file']['name']);
486
 
487
                        try {
488
                            if($topic->image) {
489
 
490
                                if(!image ::delete($target_path, $topic->image)) {
491
                                    return new JsonModel([
492
                                        'success'   => false,
493
                                        'data'   =>  'ERROR_THERE_WAS_AN_ERROR'
494
                                    ]);
495
                                }
496
                            }
497
 
498
                            list($target_width, $target_height) = explode('x', $this->config['leaderslinked.image_sizes.microlearning_image_size']);
499
 
500
                            $filename = 'topic-' .uniqid() . '.png';
501
                            $crop_to_dimensions = true;
502
                            if(Image::uploadImage($tmp_filename, $target_path, $filename, $target_width, $target_height, $crop_to_dimensions)) {
503
                                $topic->image = $filename;
504
                                $topicMapper->update($topic);
505
                            }
506
                        } catch(\Throwable $e) {
507
                            error_log($e->getTraceAsString());
508
                        }
509
                    }
510
 
511
 
512
 
513
 
514
                    $this->logger->info('Se edito el tópico ' . $topic->name, ['user_id' => $currentUser->id, 'ip' => Functions::getUserIP()]);
515
 
516
                    $data = [
517
                        'success'   => true,
518
                        'data'   => 'LABEL_RECORD_UPDATED'
519
                    ];
520
                } else {
521
                    $data = [
522
                        'success'   => false,
523
                        'data'      => $topicMapper->getError()
524
                    ];
525
 
526
                }
527
 
528
                return new JsonModel($data);
529
 
530
            } else {
531
                $messages = [];
532
                $form_messages = (array) $form->getMessages();
533
                foreach($form_messages  as $fieldname => $field_messages)
534
                {
535
 
536
                    $messages[$fieldname] = array_values($field_messages);
537
                }
538
 
539
                return new JsonModel([
540
                    'success'   => false,
541
                    'data'   => $messages
542
                ]);
543
            }
544
        } else {
545
            $data = [
546
                'success' => false,
547
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
548
            ];
549
 
550
            return new JsonModel($data);
551
        }
552
 
553
        return new JsonModel($data);
554
    }
555
}