Proyectos de Subversion LeadersLinked - Backend

Rev

Rev 17013 | | Comparar con el anterior | 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
 
17018 efrain 124
                $storage = Storage::getInstance($this->config, $this->adapter);
17013 efrain 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
 
17018 efrain 238
                    $image = \LeadersLinked\Library\Image::getInstance($this->config);
239
                    $storage = \LeadersLinked\Library\Storage::getInstance($this->config, $this->adapter);
240
                    $target_path = $storage->getPathHabitEmoji();
17013 efrain 241
 
242
                    $files = $this->getRequest()->getFiles()->toArray();
243
 
244
 
245
                    if(isset($files['image']) && empty($files['image']['error'])) {
246
                        $tmp_filename  = $files['image']['tmp_name'];
247
                        $filename      = explode('.',  $files['image']['name']);
248
                        $filename       = Functions::normalizeStringFilename(uniqid() . '-' . $filename[0].'.png');
249
 
250
                        $crop_to_dimensions = true;
17018 efrain 251
                        $full_tmp_filename = $image->uploadProcessChangeSize($tmp_filename, $filename, $target_width, $target_height, $crop_to_dimensions);
17013 efrain 252
 
17018 efrain 253
                        if($full_tmp_filename) {
254
                            if($storage->putFile($target_path, $habitEmoji->uuid,  $full_tmp_filename)) {
255
                                $habitEmoji->image = $filename;
256
                                $habitEmojiMapper->update($habitEmoji);
257
                            }
17013 efrain 258
                        }
17018 efrain 259
 
17013 efrain 260
                    }
261
 
262
 
263
                    $this->logger->info('Se agrego el emoji ' . $habitEmoji->name, ['user_id' => $currentUser->id, 'ip' => Functions::getUserIP()]);
264
 
265
                    $data = [
266
                        'success'   => true,
267
                        'data'   => 'LABEL_RECORD_ADDED'
268
                    ];
269
                } else {
270
                    $data = [
271
                        'success'   => false,
272
                        'data'      => $habitEmojiMapper->getError()
273
                    ];
274
 
275
                }
276
 
277
                return new JsonModel($data);
278
 
279
            } else {
280
                $messages = [];
281
                $form_messages = (array) $form->getMessages();
282
                foreach($form_messages  as $fieldname => $field_messages)
283
                {
284
 
285
                    $messages[$fieldname] = array_values($field_messages);
286
                }
287
 
288
                return new JsonModel([
289
                    'success'   => false,
290
                    'data'   => $messages
291
                ]);
292
            }
293
 
294
        } else {
295
            $data = [
296
                'success' => false,
297
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
298
            ];
299
 
300
            return new JsonModel($data);
301
        }
302
 
303
        return new JsonModel($data);
304
    }
305
 
306
    /**
307
     *
308
     * Borrar un perfil excepto el público
309
     * @return \Laminas\View\Model\JsonModel
310
     */
311
    public function deleteAction()
312
    {
313
        $currentUserPlugin = $this->plugin('currentUserPlugin');
314
        $currentUser    = $currentUserPlugin->getUser();
315
        $currentCompany = $currentUserPlugin->getCompany();
316
 
317
        $request        = $this->getRequest();
318
        $id         = $this->params()->fromRoute('id');
319
 
320
 
321
 
322
        $habitEmojiMapper = HabitEmojiMapper::getInstance($this->adapter);
323
        $habitEmoji = $habitEmojiMapper->fetchOneByUuid($id);
324
        if(!$habitEmoji) {
325
            return new JsonModel([
326
                'success'   => false,
327
                'data'   => 'ERROR_RECORD_NOT_FOUND'
328
            ]);
329
        }
330
 
331
        if($habitEmoji->company_id != $currentCompany->id) {
332
            return new JsonModel([
333
                'success'   => false,
334
                'data'   => 'ERROR_UNAUTHORIZED'
335
            ]);
336
        }
337
 
338
        if($request->isPost()) {
339
 
340
            $result =  $habitEmojiMapper->delete($habitEmoji);
341
            if($result) {
342
                $this->logger->info('Se borro el emoji : ' .  $habitEmoji->name, ['user_id' => $currentUser->id, 'ip' => Functions::getUserIP()]);
343
 
344
                if($habitEmoji->image) {
345
 
17018 efrain 346
 
347
                    $storage = \LeadersLinked\Library\Storage::getInstance($this->config, $this->adapter);
348
 
349
                    $target_path = $storage->getPathHabitEmoji();
350
                    $storage->delete($target_path, $habitEmoji->uuid, $habitEmoji->image);
17013 efrain 351
                }
352
 
353
                $data = [
354
                    'success' => true,
355
                    'data' => 'LABEL_RECORD_DELETED'
356
                ];
357
            } else {
358
 
359
                $data = [
360
                    'success'   => false,
361
                    'data'      => $habitEmojiMapper->getError()
362
                ];
363
 
364
                return new JsonModel($data);
365
            }
366
 
367
        } else {
368
            $data = [
369
                'success' => false,
370
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
371
            ];
372
 
373
            return new JsonModel($data);
374
        }
375
 
376
        return new JsonModel($data);
377
    }
378
 
379
 
380
    public function editAction()
381
    {
382
        $currentUserPlugin = $this->plugin('currentUserPlugin');
383
        $currentUser    = $currentUserPlugin->getUser();
384
        $currentCompany = $currentUserPlugin->getCompany();
385
 
386
        $request    = $this->getRequest();
387
        $id    = $this->params()->fromRoute('id');
388
 
389
 
390
        $habitEmojiMapper = HabitEmojiMapper::getInstance($this->adapter);
391
        $habitEmoji = $habitEmojiMapper->fetchOneByUuid($id);
392
        if(!$habitEmoji) {
393
            return new JsonModel([
394
                'success'   => false,
395
                'data'   => 'ERROR_RECORD_NOT_FOUND'
396
            ]);
397
        }
398
 
399
 
400
        if($habitEmoji->company_id != $currentCompany->id) {
401
            return new JsonModel([
402
                'success'   => false,
403
                'data'   => 'ERROR_UNAUTHORIZED'
404
            ]);
405
        }
406
 
407
        if($request->isGet()) {
17018 efrain 408
            $storage = Storage::getInstance($this->config, $this->adapter);
17013 efrain 409
            $path = $storage->getPathHabitEmoji();
410
 
411
 
412
            $data = [
413
                'success' => true,
414
                'data' => [
415
                    'name' => $habitEmoji->name,
416
                    'order' => $habitEmoji->order,
417
                    'status' => $habitEmoji->status,
418
                    'code' => $habitEmoji->code,
419
                    'image' => $habitEmoji->image ? $storage->getGenericImage($path,  $habitEmoji->uuid, $habitEmoji->image) : '',
420
                ]
421
            ];
422
 
423
            return new JsonModel($data);
424
        }
425
        else if($request->isPost()) {
426
            $form = new  HabitEmojiEditForm();
427
            $dataPost = array_merge($request->getPost()->toArray(), $request->getFiles()->toArray());
428
            $dataPost['status'] = empty($dataPost['status'])  ? HabitEmoji::STATUS_INACTIVE : $dataPost['status'];
429
 
430
 
431
            $form->setData($dataPost);
432
 
433
            if($form->isValid()) {
434
                $dataPost = (array) $form->getData();
435
 
436
                $habitEmoji->name = $dataPost['name'];
437
                $habitEmoji->order = $dataPost['order'];
438
                $habitEmoji->code = $dataPost['code'];
439
                $habitEmoji->status = $dataPost['status'];
440
 
441
                if($habitEmojiMapper->update($habitEmoji)) {
442
 
443
 
444
 
445
                    $target_size = $this->config['leaderslinked.image_sizes.emoji'];
446
                    list($target_width, $target_height) = explode('x', $target_size);
447
 
448
 
449
 
450
 
451
                    $files = $this->getRequest()->getFiles()->toArray();
452
                    if(isset($files['image']) && empty($files['image']['error'])) {
453
 
17018 efrain 454
                        $image      = \LeadersLinked\Library\Image::getInstance($this->config);
455
                        $storage    = \LeadersLinked\Library\Storage::getInstance($this->config, $this->adapter);
17013 efrain 456
 
17018 efrain 457
                        $target_path =  $storage->getPathHabitEmoji();
458
 
17013 efrain 459
                        $tmp_filename  = $files['image']['tmp_name'];
460
                        $filename      = explode('.',  $files['image']['name']);
461
                        $filename       = Functions::normalizeStringFilename(uniqid() . '-' . $filename[0].'.png');
462
 
463
                        $crop_to_dimensions = true;
17018 efrain 464
                        $full_tmp_filename = $image->uploadProcessChangeSize($tmp_filename, $filename, $target_width, $target_height,  $crop_to_dimensions);
465
 
466
                        if($full_tmp_filename) {
467
 
17013 efrain 468
                            if($habitEmoji->image) {
469
                                $image->getStorage()->deleteFile($target_path, $habitEmoji->uuid, $habitEmoji->image);
470
                            }
471
 
17018 efrain 472
 
473
                            if($storage->putFile($target_path, $habitEmoji->uuid,  $full_tmp_filename)) {
474
                                $habitEmoji->image = $filename;
475
                                $habitEmojiMapper->update($habitEmoji);
476
                            }
17013 efrain 477
                        }
17018 efrain 478
 
479
 
17013 efrain 480
                    }
481
 
482
 
483
 
484
                    $this->logger->info('Se edito el emoji' . $habitEmoji->name, ['user_id' => $currentUser->id, 'ip' => Functions::getUserIP()]);
485
 
486
                    $data = [
487
                        'success'   => true,
488
                        'data'   => 'LABEL_RECORD_UPDATED'
489
                    ];
490
                } else {
491
                    $data = [
492
                        'success'   => false,
493
                        'data'      => $habitEmojiMapper->getError()
494
                    ];
495
 
496
                }
497
 
498
                return new JsonModel($data);
499
 
500
            } else {
501
                $messages = [];
502
                $form_messages = (array) $form->getMessages();
503
                foreach($form_messages  as $fieldname => $field_messages)
504
                {
505
 
506
                    $messages[$fieldname] = array_values($field_messages);
507
                }
508
 
509
                return new JsonModel([
510
                    'success'   => false,
511
                    'data'   => $messages
512
                ]);
513
            }
514
        } else {
515
            $data = [
516
                'success' => false,
517
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
518
            ];
519
 
520
            return new JsonModel($data);
521
        }
522
 
523
        return new JsonModel($data);
524
    }
525
 
526
 
527
}