Proyectos de Subversion LeadersLinked - Backend

Rev

| Ultima modificación | Ver Log |

Rev Autor Línea Nro. Línea
5287 eleazar 1
<?php
2
 
3
declare(strict_types=1);
4
 
5
namespace LeadersLinked\Controller;
6
 
16768 efrain 7
 
5287 eleazar 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;
5572 eleazar 13
use LeadersLinked\Hydrator\ObjectPropertyHydrator;
14
use LeadersLinked\Mapper\UserMapper;
15
use LeadersLinked\Mapper\CompanyMapper;
16
use LeadersLinked\Model\Company;
17
use Laminas\Hydrator\ArraySerializableHydrator;
18
use Laminas\Db\ResultSet\HydratingResultSet;
19
use LeadersLinked\Mapper\QueryMapper;
20
use Laminas\Paginator\Adapter\DbSelect;
21
use Laminas\Paginator\Paginator;
22
use Laminas\Db\Adapter\AdapterInterface;
5287 eleazar 23
use LeadersLinked\Mapper\SurveyTestMapper;
5557 eleazar 24
use LeadersLinked\Mapper\SurveyMapper;
25
use LeadersLinked\Mapper\SurveyFormMapper;
5287 eleazar 26
use LeadersLinked\Form\SurveyTestForm;
27
use LeadersLinked\Model\SurveyTest;
7039 eleazar 28
use LeadersLinked\Library\UniqueSurveyReport;
15150 efrain 29
use LeadersLinked\Model\Survey;
5287 eleazar 30
class SurveyTestController extends AbstractActionController {
31
 
32
    /**
33
     *
16769 efrain 34
     * @var \Laminas\Db\Adapter\AdapterInterface
5287 eleazar 35
     */
36
    private $adapter;
16769 efrain 37
 
5287 eleazar 38
    /**
39
     *
16769 efrain 40
     * @var \LeadersLinked\Cache\CacheInterface
5287 eleazar 41
     */
16769 efrain 42
    private $cache;
43
 
44
 
45
    /**
46
     *
47
     * @var \Laminas\Log\LoggerInterface
48
     */
5287 eleazar 49
    private $logger;
16769 efrain 50
 
5287 eleazar 51
    /**
52
     *
53
     * @var array
54
     */
55
    private $config;
16769 efrain 56
 
57
 
5287 eleazar 58
    /**
59
     *
16769 efrain 60
     * @var \Laminas\Mvc\I18n\Translator
61
     */
62
    private $translator;
63
 
64
 
65
    /**
66
     *
67
     * @param \Laminas\Db\Adapter\AdapterInterface $adapter
68
     * @param \LeadersLinked\Cache\CacheInterface $cache
69
     * @param \Laminas\Log\LoggerInterface LoggerInterface $logger
5287 eleazar 70
     * @param array $config
16769 efrain 71
     * @param \Laminas\Mvc\I18n\Translator $translator
5287 eleazar 72
     */
16769 efrain 73
    public function __construct($adapter, $cache, $logger, $config, $translator)
16768 efrain 74
    {
16769 efrain 75
        $this->adapter      = $adapter;
76
        $this->cache        = $cache;
77
        $this->logger       = $logger;
78
        $this->config       = $config;
79
        $this->translator   = $translator;
5287 eleazar 80
    }
81
 
82
    public function indexAction() {
5889 eleazar 83
 
5287 eleazar 84
        $request = $this->getRequest();
85
        $currentUserPlugin = $this->plugin('currentUserPlugin');
86
        $currentCompany = $currentUserPlugin->getCompany();
87
        $currentUser = $currentUserPlugin->getUser();
88
 
5887 eleazar 89
        try{
5287 eleazar 90
        $request = $this->getRequest();
91
        if ($request->isGet()) {
92
 
93
            $headers = $request->getHeaders();
94
 
95
            $isJson = false;
96
            if ($headers->has('Accept')) {
97
                $accept = $headers->get('Accept');
98
 
99
                $prioritized = $accept->getPrioritized();
100
 
101
                foreach ($prioritized as $key => $value) {
102
                    $raw = trim($value->getRaw());
103
 
104
                    if (!$isJson) {
105
                        $isJson = strpos($raw, 'json');
106
                    }
107
                }
108
            }
109
 
110
            if ($isJson) {
5885 eleazar 111
                $survey_uuid = $this->params()->fromRoute('survey_id');
6879 eleazar 112
 
113
                if(!$survey_uuid){
114
                    return new JsonModel([
115
                        'success' => true,
116
                        'data' => [
117
                            'items' => [],
118
                            'total' => 0
119
                        ]
120
                    ]);
121
                }
5885 eleazar 122
 
123
                $surveyMapper = SurveyMapper::getInstance($this->adapter);
124
                $survey = $surveyMapper->fetchOneByUuid($survey_uuid);
6878 eleazar 125
 
5607 eleazar 126
                $search = $this->params()->fromQuery('search', []);
16766 efrain 127
                $search = empty($search['value']) ? '' :  Functions::sanitizeFilterString($search['value']);
5287 eleazar 128
 
15371 efrain 129
                $start = intval($this->params()->fromQuery('start', 0), 10);
5287 eleazar 130
                $records_x_page = intval($this->params()->fromQuery('length', 10), 10);
15371 efrain 131
                $page =  intval($start / $records_x_page);
132
                $page++;
133
 
5287 eleazar 134
                $order = $this->params()->fromQuery('order', []);
135
                $order_field = empty($order[0]['column']) ? 99 : intval($order[0]['column'], 10);
16766 efrain 136
                $order_direction = empty($order[0]['dir']) ? 'ASC' : Functions::sanitizeFilterString(filter_var($order[0]['dir']));
5287 eleazar 137
 
6801 eleazar 138
                $fields = ['first_name'];
139
                $order_field = isset($fields[$order_field]) ? $fields[$order_field] : 'first_name';
5613 eleazar 140
 
5614 eleazar 141
                if (!in_array($order_direction, ['ASC', 'DESC'])) {
142
                    $order_direction = 'ASC';
143
                }
144
 
6837 eleazar 145
                $surveyTestMapper = SurveyTestMapper::getInstance($this->adapter);
146
                $paginator = $surveyTestMapper->fetchAllDataTableBySurveyId($survey->id, $search, $page, $records_x_page, $order_field, $order_direction);
147
 
5287 eleazar 148
                $items = [];
149
                $records = $paginator->getCurrentItems();
6822 eleazar 150
 
15150 efrain 151
                $acl = $this->getEvent()->getViewModel()->getVariable('acl');
152
                $allowAdd = $acl->isAllowed($currentUser->usertype_id, 'survey/test/add');
153
                $allowDelete = $acl->isAllowed($currentUser->usertype_id, 'survey/test/delete');
154
                $allowReport = $acl->isAllowed($currentUser->usertype_id, 'survey/test/report');
155
 
156
 
157
 
158
 
5287 eleazar 159
                foreach ($records as $record) {
6668 eleazar 160
 
5287 eleazar 161
                    $item = [
15150 efrain 162
                        'first_name' => $survey->identity == Survey::IDENTITY_YES ? $record->first_name : 'LABEL_SURVEY_ANONYMOUS',
163
                        'last_name' => $survey->identity == Survey::IDENTITY_YES ? $record->last_name : '',
6873 eleazar 164
                        'date' => $record->added_on,
5288 eleazar 165
 
5287 eleazar 166
                        'actions' => [
15150 efrain 167
                            'link_delete' => $allowDelete ? $this->url()->fromRoute('survey/test/delete', ['id' => $record->id, 'survey_id' => $survey->uuid]) : '',
168
                            'link_report' => $allowReport ? $this->url()->fromRoute('survey/test/report', ['uuid' => $record->uuid, 'survey_id' => $survey->uuid]) : '',
5287 eleazar 169
                        ]
170
                    ];
171
 
172
                    array_push($items, $item);
173
                }
174
 
175
                return new JsonModel([
176
                    'success' => true,
177
                    'data' => [
178
                        'items' => $items,
15150 efrain 179
                        'link_add' => $allowAdd  ? $this->url()->fromRoute('survey/test/add', ['survey_id' => $survey->uuid]) : '',
5287 eleazar 180
                        'total' => $paginator->getTotalItemCount(),
181
                    ]
182
                ]);
183
            } else {
5564 eleazar 184
                $surveyMapper = SurveyMapper::getInstance($this->adapter);
185
                $survies = $surveyMapper->fetchAllByCompanyId($currentCompany->id);
186
 
5287 eleazar 187
                $form = new SurveyTestForm($this->adapter, $currentCompany->id);
188
 
189
                $this->layout()->setTemplate('layout/layout-backend');
190
                $viewModel = new ViewModel();
191
                $viewModel->setTemplate('leaders-linked/survey-test/index.phtml');
5564 eleazar 192
                $viewModel->setVariables([
6839 eleazar 193
                    'form'      => $form,
194
                    'survies' => $survies
5564 eleazar 195
                ]);
5287 eleazar 196
                return $viewModel;
197
            }
198
        } else {
199
            return new JsonModel([
200
                'success' => false,
201
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
202
            ]);
5663 eleazar 203
 
5287 eleazar 204
        }
5894 eleazar 205
        } catch (\Throwable $e) {
5887 eleazar 206
            $e->getMessage();
5888 eleazar 207
            return new JsonModel([
208
                'success' => false,
209
                'data' => $e
210
            ]);
5887 eleazar 211
        }
5287 eleazar 212
    }
213
 
214
    public function addAction() {
215
        $request = $this->getRequest();
216
        $currentUserPlugin = $this->plugin('currentUserPlugin');
217
        $currentCompany = $currentUserPlugin->getCompany();
218
        $currentUser = $currentUserPlugin->getUser();
219
 
220
        $request = $this->getRequest();
221
 
5732 eleazar 222
        $survey_id = $this->params()->fromRoute('survey_id');
5823 eleazar 223
 
5452 eleazar 224
        if ($request->isGet()) {
5649 eleazar 225
            $surveyMapper = SurveyMapper::getInstance($this->adapter);
5732 eleazar 226
            $survey = $surveyMapper->fetchOneByUuid($survey_id);
5570 eleazar 227
 
5452 eleazar 228
            $surveyFormMapper = SurveyFormMapper::getInstance($this->adapter);
229
            $surveyForm = $surveyFormMapper->fetchOne($survey->form_id);
5570 eleazar 230
 
5452 eleazar 231
            $data = [
15150 efrain 232
                'success' => true,
233
                'data' => [
5452 eleazar 234
                    'id' => $survey->uuid,
235
                    'content' => $surveyForm->content ? json_decode($surveyForm->content) : [],
236
                    'description' => $surveyForm->description,
237
                    'text' => $surveyForm->text,
15150 efrain 238
                    'identity' => $survey->identity,
5452 eleazar 239
                ],
6865 eleazar 240
            ];
5452 eleazar 241
 
242
        } else if ($request->isPost()) {
5287 eleazar 243
 
244
            $form = new SurveyTestForm($this->adapter, $currentCompany->id);
245
 
246
            $dataPost = $request->getPost()->toArray();
247
 
248
            $form->setData($dataPost);
249
 
250
            if ($form->isValid()) {
251
                $dataPost = (array) $form->getData();
252
 
253
                $hydrator = new ObjectPropertyHydrator();
254
                $survey = new SurveyTest();
255
                $hydrator->hydrate($dataPost, $survey);
256
 
5831 eleazar 257
                $surveyDoneMapper = SurveyMapper::getInstance($this->adapter);
258
                $surveyDone = $surveyDoneMapper->fetchOneByUuid($survey_id);
259
 
5287 eleazar 260
                $survey->company_id = $currentCompany->id;
5831 eleazar 261
                $survey->survey_id = $surveyDone->id;
5287 eleazar 262
 
263
                $surveyMapper = SurveyTestMapper::getInstance($this->adapter);
264
                $result = $surveyMapper->insert($survey);
265
 
266
                if ($result) {
5832 eleazar 267
                    $this->logger->info('Se agrego el formulario' . $survey->first_name, ['user_id' => $currentUser->id, 'ip' => Functions::getUserIP()]);
5287 eleazar 268
 
269
                    // Get record by id
270
                    $record = $surveyMapper->fetchOne($survey->id);
271
 
272
                    if ($record) {
273
 
274
                        $data = [
275
                            'success' => true,
276
                            'id' => $record->id,
277
                            'data' => 'LABEL_RECORD_ADDED'
278
                        ];
279
                    } else {
280
 
281
                        $data = [
282
                            'success' => false,
283
                            'data' => 'ERROR_RECORD_NOT_FOUND'
284
                        ];
285
                    }
286
                } else {
287
                    $data = [
288
                        'success' => false,
289
                        'data' => $surveyMapper->getError()
290
                    ];
291
                }
292
 
293
                return new JsonModel($data);
294
            } else {
295
                $messages = [];
296
                $form_messages = (array) $form->getMessages();
297
                foreach ($form_messages as $fieldname => $field_messages) {
298
 
299
                    $messages[$fieldname] = array_values($field_messages);
300
                }
301
 
302
                return new JsonModel([
303
                    'success' => false,
304
                    'data' => $messages
305
                ]);
306
            }
307
        } else {
308
            $data = [
309
                'success' => false,
310
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
311
            ];
312
 
313
            return new JsonModel($data);
314
        }
315
 
316
        return new JsonModel($data);
317
    }
318
 
6908 eleazar 319
    public function deleteAction() {
6668 eleazar 320
        $request = $this->getRequest();
321
        $currentUserPlugin = $this->plugin('currentUserPlugin');
322
        $currentCompany = $currentUserPlugin->getCompany();
323
        $currentUser = $currentUserPlugin->getUser();
6908 eleazar 324
        try{
6668 eleazar 325
        $request = $this->getRequest();
6908 eleazar 326
        $id = $this->params()->fromRoute('id');
6668 eleazar 327
 
6908 eleazar 328
        if (!$id) {
6668 eleazar 329
            $data = [
330
                'success' => false,
331
                'data' => 'ERROR_INVALID_PARAMETER'
332
            ];
333
 
334
            return new JsonModel($data);
335
        }
6908 eleazar 336
 
6668 eleazar 337
        $surveyTestMapper = SurveyTestMapper::getInstance($this->adapter);
6908 eleazar 338
        $survey = $surveyTestMapper->fetchOne($id);
339
        if (!$survey) {
6668 eleazar 340
            $data = [
341
                'success' => false,
342
                'data' => 'ERROR_RECORD_NOT_FOUND'
343
            ];
344
 
345
            return new JsonModel($data);
346
        }
347
 
6908 eleazar 348
        if ($survey->company_id != $currentCompany->id) {
349
            return new JsonModel([
350
                'success' => false,
351
                'data' => 'ERROR_UNAUTHORIZED'
352
            ]);
353
        }
6668 eleazar 354
 
6908 eleazar 355
        if ($request->isPost()) {
6668 eleazar 356
 
6908 eleazar 357
            $result = $surveyTestMapper->delete($survey->id);
358
            if ($result) {
359
               // $this->logger->info('Se borro el formulario ' . $survey->name, ['user_id' => $currentUser->id, 'ip' => Functions::getUserIP()]);
6668 eleazar 360
 
6908 eleazar 361
                $data = [
362
                    'success' => true,
363
                    'data' => 'LABEL_RECORD_DELETED'
364
                ];
6668 eleazar 365
            } else {
366
 
367
                $data = [
368
                    'success' => false,
6908 eleazar 369
                    'data' => $surveyTestMapper->getError()
6668 eleazar 370
                ];
371
 
372
                return new JsonModel($data);
373
            }
374
        } else {
375
            $data = [
376
                'success' => false,
377
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
378
            ];
379
 
380
            return new JsonModel($data);
381
        }
382
 
383
        return new JsonModel($data);
6908 eleazar 384
        } catch (\Throwable $e) {
385
            $e->getMessage();
386
            return new JsonModel([
387
                'success' => false,
388
                'data' => $e
389
            ]);
390
        }
391
 
6668 eleazar 392
    }
393
 
6908 eleazar 394
    public function reportAction() {
5287 eleazar 395
        $request = $this->getRequest();
396
        $currentUserPlugin = $this->plugin('currentUserPlugin');
397
        $currentCompany = $currentUserPlugin->getCompany();
398
        $currentUser = $currentUserPlugin->getUser();
6908 eleazar 399
 
5287 eleazar 400
        $request = $this->getRequest();
6908 eleazar 401
        $uuid = $this->params()->fromRoute('uuid');
6819 eleazar 402
 
6908 eleazar 403
 
404
 
405
        if (!$uuid) {
5287 eleazar 406
            $data = [
407
                'success' => false,
408
                'data' => 'ERROR_INVALID_PARAMETER'
409
            ];
410
 
411
            return new JsonModel($data);
412
        }
6908 eleazar 413
 
414
        $surveyTestMapper = SurveyTestMapper::getInstance($this->adapter);
7033 eleazar 415
        $surveyTest = $surveyTestMapper->fetchOneByuuid($uuid);
5287 eleazar 416
 
6908 eleazar 417
 
418
        $surveyMapper = SurveyMapper::getInstance($this->adapter);
7037 eleazar 419
        $survey = $surveyMapper->fetchOne($surveyTest->survey_id);
6908 eleazar 420
 
7033 eleazar 421
        if (!$surveyTest) {
5287 eleazar 422
            $data = [
423
                'success' => false,
424
                'data' => 'ERROR_RECORD_NOT_FOUND'
425
            ];
426
 
427
            return new JsonModel($data);
428
        }
429
 
430
 
6908 eleazar 431
        if ($request->isGet()) {
432
            $hydrator = new ObjectPropertyHydrator();
5287 eleazar 433
 
6908 eleazar 434
            //get form data
435
            $surveyFormMapper = SurveyFormMapper::getInstance($this->adapter);
436
            $surveyForm = $surveyFormMapper->fetchOne($survey->form_id);
5287 eleazar 437
 
6908 eleazar 438
            if ($surveyForm) {
439
 
15150 efrain 440
                return $this->renderPDF( $currentCompany, $surveyForm, $surveyTest, $survey);
5287 eleazar 441
            } else {
442
 
443
                $data = [
444
                    'success' => false,
6908 eleazar 445
                    'data' => 'ERROR_METHOD_NOT_ALLOWED'
5287 eleazar 446
                ];
447
 
448
                return new JsonModel($data);
449
            }
450
        } else {
451
            $data = [
452
                'success' => false,
453
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
454
            ];
455
 
456
            return new JsonModel($data);
457
        }
458
 
459
        return new JsonModel($data);
6908 eleazar 460
    }
461
 
15150 efrain 462
    public function renderPDF($company, $surveyForm, $surveyTest, $survey) {
6908 eleazar 463
 
15150 efrain 464
 
465
        //Generate New PDF
466
        $pdf = new UniqueSurveyReport();
467
 
468
        $target_path = $this->config['leaderslinked.fullpath.company'] . DIRECTORY_SEPARATOR . $company->uuid;
469
 
470
        $header = $company->header ? $target_path . DIRECTORY_SEPARATOR . $company->header : '';
471
        if(empty($header) || !file_exists($header)) {
472
            $header = $this->config['leaderslinked.images_default.company_pdf_header'];
473
        }
474
 
475
        $footer = $company->footer ? $target_path . DIRECTORY_SEPARATOR . $company->footer : '';
476
        if(empty($footer) || !file_exists($footer)) {
477
            $footer = $this->config['leaderslinked.images_default.company_pdf_footer'];
478
        }
479
 
480
        $pdf->header = $header;
481
        $pdf->footer = $footer;
482
 
6908 eleazar 483
        $target_path = $this->config['leaderslinked.fullpath.company'] . DIRECTORY_SEPARATOR . $survey->uuid;
484
 
485
 
486
        if(file_exists($target_path)) {
487
            Functions::deleteFiles($target_path);
488
        } else {
489
            @mkdir($target_path, 0755, true);
6817 eleazar 490
        }
491
 
6908 eleazar 492
        // Set Data
15150 efrain 493
        $headerFormName = $this->cleanStringToPdf($surveyForm->name);
15154 efrain 494
 
495
 
496
 
497
 
498
        if($survey->identity == Survey::IDENTITY_YES) {
499
            $headerUserName = $this->cleanStringToPdf(
500
                trim($surveyTest->first_name . ' ' . $surveyTest->last_name)
501
                . ' (' . $surveyTest->email . ')'
502
 
503
            );
504
        } else {
505
            $headerUserName = '';
506
        }
6908 eleazar 507
        $sections = json_decode($surveyForm->content, true);
15150 efrain 508
 
7033 eleazar 509
        $test = json_decode($surveyTest->content, true);
15150 efrain 510
 
6908 eleazar 511
 
512
        $pdf->AliasNbPages();
513
        $pdf->AddPage();
514
 
515
        // Set header secundary
15154 efrain 516
        $pdf->customHeader($headerFormName, $headerUserName);
6908 eleazar 517
 
518
        $countSection = 0;
519
 
520
        for ($i = 0; $i < count($sections); $i++) {
521
            if ($countSection > 1) {
522
                $countSection = 0;
523
                $pdf->AddPage();
15154 efrain 524
                $pdf->customHeader($headerFormName, $headerUserName);
6908 eleazar 525
            }
526
            $section = $sections[$i];
527
 
528
            foreach ($section['questions'] as $question) {
529
 
530
                    switch ($question['type']) {
531
                        case 'simple':
7061 eleazar 532
                            $options = [];
533
 
6908 eleazar 534
                            foreach($question['options'] as $option) {
7061 eleazar 535
                                $options []= [
15150 efrain 536
                                    'text' => $this->cleanStringToPdf($option['text']),
7061 eleazar 537
                                    'selected' => $option['slug_option'] == $test[$question['slug_question']],
538
                                ];
6908 eleazar 539
                            }
540
 
15150 efrain 541
                            $pdf->optionTable($this->cleanStringToPdf($question['text']), $options);
7033 eleazar 542
 
6908 eleazar 543
                            break;
544
 
545
                        case 'multiple':
7064 eleazar 546
                            $options = [];
6908 eleazar 547
 
548
                            foreach($question['options'] as $option) {
7064 eleazar 549
                                $options []= [
15150 efrain 550
                                    'text' => $this->cleanStringToPdf($option['text']),
7064 eleazar 551
                                    'selected' => in_array($option['slug_option'], $test[$question['slug_question']]),
552
                                ];
6908 eleazar 553
                            }
554
 
15150 efrain 555
                            $pdf->optionTable($this->cleanStringToPdf($question['text']), $options);
7064 eleazar 556
 
6908 eleazar 557
                            break;
7055 eleazar 558
                        case 'open':
15150 efrain 559
                            $pdf->borderTable($this->cleanStringToPdf($question['text']), [['content' => $test[$question['slug_question']]]]);
7055 eleazar 560
 
561
 
562
                            break;
6908 eleazar 563
                    }
564
                $countSection++;
565
            }
566
 
567
 
568
        }
569
 
570
        return $pdf->Output();
5287 eleazar 571
    }
15150 efrain 572
 
573
    private function cleanStringToPdf($s)
574
    {
575
 
576
        $s = html_entity_decode($s);
577
        $detect = mb_detect_encoding($s);
578
 
579
        if(strtoupper($detect) != 'UTF8') {
580
 
581
            $s = mb_convert_encoding($s, 'UTF8', $detect);
582
 
583
        }
5287 eleazar 584
 
15150 efrain 585
 
586
        return strip_tags($s);
587
    }
6908 eleazar 588
 
15150 efrain 589
 
5287 eleazar 590
}