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