Proyectos de Subversion LeadersLinked - Backend

Rev

| Ultima modificación | Ver Log |

Rev Autor Línea Nro. Línea
9334 eleazar 1
<?php
2
 
3
declare(strict_types=1);
4
 
5
namespace LeadersLinked\Controller;
6
 
7
use Laminas\Db\Adapter\AdapterInterface;
8
use Laminas\Cache\Storage\Adapter\AbstractAdapter;
9
use Laminas\Mvc\Controller\AbstractActionController;
10
use Laminas\Log\LoggerInterface;
11
use Laminas\View\Model\ViewModel;
12
use Laminas\View\Model\JsonModel;
13
use LeadersLinked\Library\Functions;
14
use LeadersLinked\Mapper\MyTrainerCategoriesMapper;
9735 eleazar 15
use LeadersLinked\Mapper\TopicMapper;
16
use LeadersLinked\Mapper\QueryMapper;
9739 eleazar 17
use Laminas\Paginator\Adapter\DbSelect;
18
use Laminas\Paginator\Paginator;
9334 eleazar 19
use LeadersLinked\Form\MyTrainerCategoriesForm;
9736 eleazar 20
use LeadersLinked\Form\TopicForm;
9334 eleazar 21
use LeadersLinked\Model\MyTrainerCategories;
9738 eleazar 22
use Laminas\Hydrator\ArraySerializableHydrator;
23
use Laminas\Db\ResultSet\HydratingResultSet;
9735 eleazar 24
use LeadersLinked\Model\Topic;
9334 eleazar 25
use LeadersLinked\Mapper\CompanyMapper;
26
use LeadersLinked\Model\Company;
27
use LeadersLinked\Hydrator\ObjectPropertyHydrator;
28
 
29
class MyTrainerCategoriesController extends AbstractActionController {
30
 
31
    /**
32
     *
33
     * @var AdapterInterface
34
     */
35
    private $adapter;
36
 
37
    /**
38
     *
39
     * @var AbstractAdapter
40
     */
41
    private $cache;
42
 
43
    /**
44
     *
45
     * @var  LoggerInterface
46
     */
47
    private $logger;
48
 
49
    /**
50
     *
51
     * @var array
52
     */
53
    private $config;
54
 
55
    /**
56
     *
57
     * @param AdapterInterface $adapter
58
     * @param AbstractAdapter $cache
59
     * @param LoggerInterface $logger
60
     * @param array $config
61
     */
62
    public function __construct($adapter, $cache, $logger, $config) {
63
        $this->adapter = $adapter;
64
        $this->cache = $cache;
65
        $this->logger = $logger;
66
        $this->config = $config;
67
    }
68
 
69
    public function indexAction() {
70
        $request = $this->getRequest();
71
        $currentUserPlugin = $this->plugin('currentUserPlugin');
72
        $currentCompany = $currentUserPlugin->getCompany();
73
        $currentUser = $currentUserPlugin->getUser();
74
 
9339 eleazar 75
        try{
9334 eleazar 76
        $request = $this->getRequest();
77
        if ($request->isGet()) {
78
 
79
            $headers = $request->getHeaders();
80
 
81
            $isJson = false;
82
            if ($headers->has('Accept')) {
83
                $accept = $headers->get('Accept');
84
 
85
                $prioritized = $accept->getPrioritized();
86
 
87
                foreach ($prioritized as $key => $value) {
88
                    $raw = trim($value->getRaw());
89
 
90
                    if (!$isJson) {
91
                        $isJson = strpos($raw, 'json');
92
                    }
93
                }
94
            }
95
 
96
            if ($isJson) {
97
                $search = $this->params()->fromQuery('search', []);
98
                $search = empty($search['value']) ? '' : filter_var($search['value'], FILTER_SANITIZE_STRING);
99
 
100
                $page = intval($this->params()->fromQuery('start', 1), 10);
101
                $records_x_page = intval($this->params()->fromQuery('length', 10), 10);
102
                $order = $this->params()->fromQuery('order', []);
103
                $order_field = empty($order[0]['column']) ? 99 : intval($order[0]['column'], 10);
104
                $order_direction = empty($order[0]['dir']) ? 'ASC' : strtoupper(filter_var($order[0]['dir'], FILTER_SANITIZE_STRING));
105
 
106
                $fields = ['title'];
107
                $order_field = isset($fields[$order_field]) ? $fields[$order_field] : 'title';
108
 
109
                if (!in_array($order_direction, ['ASC', 'DESC'])) {
110
                    $order_direction = 'ASC';
111
                }
112
 
113
                $acl = $this->getEvent()->getViewModel()->getVariable('acl');
114
                $allowAdd = $acl->isAllowed($currentUser->usertype_id, 'my-trainer/category/add');
115
                $allowEdit = $acl->isAllowed($currentUser->usertype_id, 'my-trainer/category/edit');
116
                $allowDelete = $acl->isAllowed($currentUser->usertype_id, 'my-trainer/category/delete');
117
 
9735 eleazar 118
                $queryMapper = QueryMapper::getInstance($this->adapter);
119
                $sql = $queryMapper->getSql();
120
                $select = $sql->select();
121
                $select->columns(['id', 'uuid', 'title', 'description']);
122
                $select->from(['tb1' => TopicMapper::_TABLE]);
123
                $select->where->equalTo('tb1.type', Topic::TYPE_MYT);
9334 eleazar 124
 
9735 eleazar 125
                if($search) {
126
                    $select->where->nest()
127
                    ->like('title', '%' . $search . '%')
128
                    ->unnest();
129
                }
130
 
131
                $select->order($order_field . ' ' . $order_direction);
132
 
133
                $hydrator = new ArraySerializableHydrator();
134
                $resultset = new HydratingResultSet($hydrator);
135
 
136
                $adapter = new DbSelect($select, $sql, $resultset);
137
                $paginator = new Paginator($adapter);
138
                $paginator->setItemCountPerPage($records_x_page);
139
                $paginator->setCurrentPageNumber($page);
140
 
9334 eleazar 141
                $items = [];
142
                $records = $paginator->getCurrentItems();
143
 
144
                foreach ($records as $record) {
145
 
146
                    $item = [
9735 eleazar 147
                        'id' => $record['id'],
148
                        'title' => $record['title'],
9745 eleazar 149
                        'text' => $record['description'],
9334 eleazar 150
                        'actions' => [
9735 eleazar 151
                            'link_edit' => $this->url()->fromRoute('my-trainer/category/edit', ['id' => $record['uuid']]),
152
                            'link_delete' => $this->url()->fromRoute('my-trainer/category/delete', ['id' => $record['uuid']])
9334 eleazar 153
                        ]
154
                    ];
155
 
156
                    array_push($items, $item);
157
                }
158
 
159
                return new JsonModel([
160
                    'success' => true,
161
                    'data' => [
162
                        'items' => $items,
163
                        'total' => $paginator->getTotalItemCount(),
164
                    ]
165
                ]);
166
            } else {
167
 
9735 eleazar 168
                $form = new TopicForm($this->adapter, $currentCompany->id);
9334 eleazar 169
 
170
                $this->layout()->setTemplate('layout/layout-backend');
171
                $viewModel = new ViewModel();
172
                $viewModel->setTemplate('leaders-linked/my-trainer-categories/index.phtml');
173
                $viewModel->setVariable('form', $form);
174
                return $viewModel;
175
            }
176
        } else {
177
            return new JsonModel([
178
                'success' => false,
179
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
180
            ]);
181
        }
9339 eleazar 182
    } catch (\Throwable $e) {
183
            $e->getMessage();
184
            return new JsonModel([
185
                'success' => false,
186
                'data' => $e
187
            ]);
188
        }
9334 eleazar 189
    }
190
 
191
    public function addAction() {
192
        $currentUserPlugin  = $this->plugin('currentUserPlugin');
193
        $currentCompany     = $currentUserPlugin->getCompany();
194
        $currentUser        = $currentUserPlugin->getUser();
195
 
196
        $request    = $this->getRequest();
197
 
9341 eleazar 198
        try{
9334 eleazar 199
        if($request->isPost()) {
9735 eleazar 200
            $form = new  TopicForm($this->adapter, $currentCompany->id);
9349 eleazar 201
 
9334 eleazar 202
            $dataPost = $request->getPost()->toArray();
203
 
204
            $form->setData($dataPost);
10208 eleazar 205
 
9334 eleazar 206
            if($form->isValid()) {
10209 eleazar 207
 
9334 eleazar 208
                $dataPost = (array) $form->getData();
209
 
210
                $hydrator = new ObjectPropertyHydrator();
9735 eleazar 211
                $categories = new Topic();
9334 eleazar 212
                $hydrator->hydrate($dataPost, $categories);
9735 eleazar 213
 
9744 eleazar 214
                $categories->type='myt';
9745 eleazar 215
               // echo $select->getSqlString($this->adapter->platform);
9735 eleazar 216
                $categoriesMapper = TopicMapper::getInstance($this->adapter);
9334 eleazar 217
 
218
                if($categoriesMapper->insert($categories)) {
219
                     $categories = $categoriesMapper->fetchOne($categories->id);
220
 
9343 eleazar 221
                    $this->logger->info('Se agrego la categoria ' . $categories->title, ['user_id' => $currentUser->id, 'ip' => Functions::getUserIP()]);
9334 eleazar 222
 
223
                    $data = [
224
                        'success'   => true,
225
                        'data'   => 'LABEL_RECORD_ADDED'
226
                    ];
227
                } else {
228
                    $data = [
229
                        'success'   => false,
230
                        'data'      => $categoriesMapper->getError()
231
                    ];
232
 
233
                }
234
 
235
                return new JsonModel($data);
236
 
237
            } else {
238
                $messages = [];
239
                $form_messages = (array) $form->getMessages();
240
                foreach($form_messages  as $fieldname => $field_messages)
241
                {
242
 
243
                    $messages[$fieldname] = array_values($field_messages);
244
                }
245
 
246
            }
247
 
248
        } else {
249
            $data = [
250
                'success' => false,
251
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
252
            ];
253
 
254
            return new JsonModel($data);
255
        }
256
 
257
        return new JsonModel($data);
9341 eleazar 258
    } catch (\Throwable $e) {
259
        $e->getMessage();
260
        return new JsonModel([
261
            'success' => false,
262
            'data' => $e
263
        ]);
264
    }
9334 eleazar 265
 
266
    }
267
 
268
    public function editAction() {
269
        $request = $this->getRequest();
270
        $currentUserPlugin = $this->plugin('currentUserPlugin');
271
        $currentCompany = $currentUserPlugin->getCompany();
272
        $currentUser = $currentUserPlugin->getUser();
273
 
274
        $request = $this->getRequest();
275
        $uuid = $this->params()->fromRoute('id');
9345 eleazar 276
        try{
9344 eleazar 277
        if (!$uuid) {
9334 eleazar 278
            $data = [
279
                'success' => false,
280
                'data' => 'ERROR_INVALID_PARAMETER'
281
            ];
282
 
283
            return new JsonModel($data);
284
        }
285
 
9746 eleazar 286
        $categoriesMapper = TopicMapper::getInstance($this->adapter);
9334 eleazar 287
        $categories = $categoriesMapper->fetchOneByUuid($uuid);
288
 
289
        if (!$categories) {
290
            $data = [
291
                'success' => false,
292
                'data' => 'ERROR_RECORD_NOT_FOUND'
293
            ];
294
 
295
            return new JsonModel($data);
296
        }
297
 
298
 
299
        if ($request->isPost()) {
9747 eleazar 300
            $form = new TopicForm();
9334 eleazar 301
            $dataPost = $request->getPost()->toArray();
302
 
303
            $form->setData($dataPost);
304
 
305
            if ($form->isValid()) {
306
                $dataPost = (array) $form->getData();
307
 
308
                $hydrator = new ObjectPropertyHydrator();
309
                $hydrator->hydrate($dataPost, $categories);
310
 
311
                if($categoriesMapper->update($categories)) {
312
                    $categories = $categoriesMapper->fetchOne($categories->id);
313
 
314
                   $this->logger->info('Se modifico la categoria ' . $categories->title, ['user_id' => $currentUser->id, 'ip' => Functions::getUserIP()]);
315
 
316
                   $data = [
317
                       'success'   => true,
318
                       'data'   => 'LABEL_RECORD_UPDATED'
319
                   ];
320
               } else {
321
                   $data = [
322
                       'success'   => false,
323
                       'data'      => $categoriesMapper->getError()
324
                   ];
325
 
326
               }
327
 
328
                return new JsonModel($data);
329
            } else {
330
                $messages = [];
331
                $form_messages = (array) $form->getMessages();
332
                foreach ($form_messages as $fieldname => $field_messages) {
333
                    $messages[$fieldname] = array_values($field_messages);
334
                }
335
 
336
                return new JsonModel([
337
                    'success' => false,
338
                    'data' => $messages
339
                ]);
340
            }
341
        } else if ($request->isGet()) {
342
 
343
            $hydrator = new ObjectPropertyHydrator();
344
 
345
            $data = [
346
                'success' => true,
347
                'data' => [
348
                    'id' => $categories->uuid,
349
                    'title' => $categories->title,
9748 eleazar 350
                    'description' => $categories->description,
9334 eleazar 351
                ]
352
            ];
353
 
354
            return new JsonModel($data);
355
        } else {
356
            $data = [
357
                'success' => false,
358
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
359
            ];
360
 
361
            return new JsonModel($data);
362
        }
363
 
364
        return new JsonModel($data);
9345 eleazar 365
    } catch (\Throwable $e) {
366
        $e->getMessage();
367
        return new JsonModel([
368
            'success' => false,
369
            'data' => $e
370
        ]);
9334 eleazar 371
    }
9345 eleazar 372
    }
9334 eleazar 373
 
374
    public function deleteAction() {
375
        $request = $this->getRequest();
376
        $currentUserPlugin = $this->plugin('currentUserPlugin');
377
        $currentCompany = $currentUserPlugin->getCompany();
378
        $currentUser = $currentUserPlugin->getUser();
379
 
380
        $request = $this->getRequest();
381
        $uuid = $this->params()->fromRoute('id');
382
 
383
        if (!$uuid) {
384
            $data = [
385
                'success' => false,
386
                'data' => 'ERROR_INVALID_PARAMETER'
387
            ];
388
 
389
            return new JsonModel($data);
390
        }
391
 
9746 eleazar 392
        $categoriesMapper = TopicMapper::getInstance($this->adapter);
9334 eleazar 393
        $categories = $categoriesMapper->fetchOneByUuid($uuid);
394
        if (!$categories) {
395
            $data = [
396
                'success' => false,
397
                'data' => 'ERROR_RECORD_NOT_FOUND'
398
            ];
399
 
400
            return new JsonModel($data);
401
        }
402
 
403
        if ($request->isPost()) {
404
 
405
 
406
            $result = $categoriesMapper->delete($categories->id);
407
            if ($result) {
408
                $this->logger->info('Se borro la categoria ' . $categories->title, ['user_id' => $currentUser->id, 'ip' => Functions::getUserIP()]);
409
 
410
                $data = [
411
                    'success' => true,
412
                    'data' => 'LABEL_RECORD_DELETED'
413
                ];
414
            } else {
415
 
416
                $data = [
417
                    'success' => false,
418
                    'data' => $categoriesMapper->getError()
419
                ];
420
 
421
                return new JsonModel($data);
422
            }
423
        } else {
424
            $data = [
425
                'success' => false,
426
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
427
            ];
428
 
429
            return new JsonModel($data);
430
        }
431
 
432
        return new JsonModel($data);
433
    }
434
}