Proyectos de Subversion LeadersLinked - Backend

Rev

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