Proyectos de Subversion LeadersLinked - Backend

Rev

Ir a la última revisión | | Ultima modificación | Ver Log |

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