Proyectos de Subversion LeadersLinked - Backend

Rev

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