Proyectos de Subversion LeadersLinked - Backend

Rev

Rev 16768 | Rev 17002 | Ir a la última revisión | | Comparar con el anterior | Ultima modificación | Ver Log |

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