Rev 7062 | AutorÃa | Ultima modificación | Ver Log |
<?php
declare(strict_types=1);
namespace LeadersLinked\Controller;
use Laminas\Cache\Storage\Adapter\AbstractAdapter;
use Laminas\Mvc\Controller\AbstractActionController;
use Laminas\Log\LoggerInterface;
use Laminas\View\Model\ViewModel;
use Laminas\View\Model\JsonModel;
use LeadersLinked\Library\Functions;
use LeadersLinked\Hydrator\ObjectPropertyHydrator;
use LeadersLinked\Mapper\UserMapper;
use LeadersLinked\Mapper\CompanyMapper;
use LeadersLinked\Model\Company;
use Laminas\Hydrator\ArraySerializableHydrator;
use Laminas\Db\ResultSet\HydratingResultSet;
use LeadersLinked\Mapper\QueryMapper;
use Laminas\Paginator\Adapter\DbSelect;
use Laminas\Paginator\Paginator;
use Laminas\Db\Adapter\AdapterInterface;
use LeadersLinked\Mapper\SurveyTestMapper;
use LeadersLinked\Mapper\SurveyMapper;
use LeadersLinked\Mapper\SurveyFormMapper;
use LeadersLinked\Form\SurveyTestForm;
use LeadersLinked\Model\SurveyTest;
use LeadersLinked\Library\UniqueSurveyReport;
class SurveyTestController extends AbstractActionController {
/**
*
* @var AdapterInterface
*/
private $adapter;
/**
*
* @var AbstractAdapter
*/
private $cache;
/**
*
* @var LoggerInterface
*/
private $logger;
/**
*
* @var array
*/
private $config;
/**
*
* @param AdapterInterface $adapter
* @param AbstractAdapter $cache
* @param LoggerInterface $logger
* @param array $config
*/
public function __construct($adapter, $cache, $logger, $config) {
$this->adapter = $adapter;
$this->cache = $cache;
$this->logger = $logger;
$this->config = $config;
}
public function indexAction() {
$request = $this->getRequest();
$currentUserPlugin = $this->plugin('currentUserPlugin');
$currentCompany = $currentUserPlugin->getCompany();
$currentUser = $currentUserPlugin->getUser();
try{
$request = $this->getRequest();
if ($request->isGet()) {
$headers = $request->getHeaders();
$isJson = false;
if ($headers->has('Accept')) {
$accept = $headers->get('Accept');
$prioritized = $accept->getPrioritized();
foreach ($prioritized as $key => $value) {
$raw = trim($value->getRaw());
if (!$isJson) {
$isJson = strpos($raw, 'json');
}
}
}
if ($isJson) {
$survey_uuid = $this->params()->fromRoute('survey_id');
if(!$survey_uuid){
return new JsonModel([
'success' => true,
'data' => [
'items' => [],
'total' => 0
]
]);
}
$surveyMapper = SurveyMapper::getInstance($this->adapter);
$survey = $surveyMapper->fetchOneByUuid($survey_uuid);
$search = $this->params()->fromQuery('search', []);
$search = empty($search['value']) ? '' : filter_var($search['value'], FILTER_SANITIZE_STRING);
$page = intval($this->params()->fromQuery('start', 1), 10);
$records_x_page = intval($this->params()->fromQuery('length', 10), 10);
$order = $this->params()->fromQuery('order', []);
$order_field = empty($order[0]['column']) ? 99 : intval($order[0]['column'], 10);
$order_direction = empty($order[0]['dir']) ? 'ASC' : strtoupper(filter_var($order[0]['dir'], FILTER_SANITIZE_STRING));
$fields = ['first_name'];
$order_field = isset($fields[$order_field]) ? $fields[$order_field] : 'first_name';
if (!in_array($order_direction, ['ASC', 'DESC'])) {
$order_direction = 'ASC';
}
$surveyTestMapper = SurveyTestMapper::getInstance($this->adapter);
$paginator = $surveyTestMapper->fetchAllDataTableBySurveyId($survey->id, $search, $page, $records_x_page, $order_field, $order_direction);
$items = [];
$records = $paginator->getCurrentItems();
foreach ($records as $record) {
$item = [
'id' => $record->id,
'first_name' => $record->first_name,
'date' => $record->added_on,
'actions' => [
'link_delete' => $this->url()->fromRoute('survey/test/delete', ['id' => $record->id, 'survey_id' => $survey->uuid]),
'link_report' => $this->url()->fromRoute('survey/test/report', ['uuid' => $record->uuid, 'survey_id' => $survey->uuid])
]
];
array_push($items, $item);
}
return new JsonModel([
'success' => true,
'data' => [
'items' => $items,
'total' => $paginator->getTotalItemCount(),
]
]);
} else {
$surveyMapper = SurveyMapper::getInstance($this->adapter);
$survies = $surveyMapper->fetchAllByCompanyId($currentCompany->id);
$form = new SurveyTestForm($this->adapter, $currentCompany->id);
$this->layout()->setTemplate('layout/layout-backend');
$viewModel = new ViewModel();
$viewModel->setTemplate('leaders-linked/survey-test/index.phtml');
$viewModel->setVariables([
'form' => $form,
'survies' => $survies
]);
return $viewModel;
}
} else {
return new JsonModel([
'success' => false,
'data' => 'ERROR_METHOD_NOT_ALLOWED'
]);
}
} catch (\Throwable $e) {
$e->getMessage();
return new JsonModel([
'success' => false,
'data' => $e
]);
}
}
public function addAction() {
$request = $this->getRequest();
$currentUserPlugin = $this->plugin('currentUserPlugin');
$currentCompany = $currentUserPlugin->getCompany();
$currentUser = $currentUserPlugin->getUser();
$request = $this->getRequest();
$survey_id = $this->params()->fromRoute('survey_id');
if ($request->isGet()) {
$surveyMapper = SurveyMapper::getInstance($this->adapter);
$survey = $surveyMapper->fetchOneByUuid($survey_id);
$surveyFormMapper = SurveyFormMapper::getInstance($this->adapter);
$surveyForm = $surveyFormMapper->fetchOne($survey->form_id);
$data = [
'survey' => [
'id' => $survey->uuid,
'content' => $surveyForm->content ? json_decode($surveyForm->content) : [],
'description' => $surveyForm->description,
'text' => $surveyForm->text,
],
];
} else if ($request->isPost()) {
$form = new SurveyTestForm($this->adapter, $currentCompany->id);
$dataPost = $request->getPost()->toArray();
$form->setData($dataPost);
if ($form->isValid()) {
$dataPost = (array) $form->getData();
$hydrator = new ObjectPropertyHydrator();
$survey = new SurveyTest();
$hydrator->hydrate($dataPost, $survey);
$surveyDoneMapper = SurveyMapper::getInstance($this->adapter);
$surveyDone = $surveyDoneMapper->fetchOneByUuid($survey_id);
$survey->company_id = $currentCompany->id;
$survey->survey_id = $surveyDone->id;
$surveyMapper = SurveyTestMapper::getInstance($this->adapter);
$result = $surveyMapper->insert($survey);
if ($result) {
$this->logger->info('Se agrego el formulario' . $survey->first_name, ['user_id' => $currentUser->id, 'ip' => Functions::getUserIP()]);
// Get record by id
$record = $surveyMapper->fetchOne($survey->id);
if ($record) {
$data = [
'success' => true,
'id' => $record->id,
'data' => 'LABEL_RECORD_ADDED'
];
} else {
$data = [
'success' => false,
'data' => 'ERROR_RECORD_NOT_FOUND'
];
}
} else {
$data = [
'success' => false,
'data' => $surveyMapper->getError()
];
}
return new JsonModel($data);
} else {
$messages = [];
$form_messages = (array) $form->getMessages();
foreach ($form_messages as $fieldname => $field_messages) {
$messages[$fieldname] = array_values($field_messages);
}
return new JsonModel([
'success' => false,
'data' => $messages
]);
}
} else {
$data = [
'success' => false,
'data' => 'ERROR_METHOD_NOT_ALLOWED'
];
return new JsonModel($data);
}
return new JsonModel($data);
}
public function deleteAction() {
$request = $this->getRequest();
$currentUserPlugin = $this->plugin('currentUserPlugin');
$currentCompany = $currentUserPlugin->getCompany();
$currentUser = $currentUserPlugin->getUser();
try{
$request = $this->getRequest();
$id = $this->params()->fromRoute('id');
if (!$id) {
$data = [
'success' => false,
'data' => 'ERROR_INVALID_PARAMETER'
];
return new JsonModel($data);
}
$surveyTestMapper = SurveyTestMapper::getInstance($this->adapter);
$survey = $surveyTestMapper->fetchOne($id);
if (!$survey) {
$data = [
'success' => false,
'data' => 'ERROR_RECORD_NOT_FOUND'
];
return new JsonModel($data);
}
if ($survey->company_id != $currentCompany->id) {
return new JsonModel([
'success' => false,
'data' => 'ERROR_UNAUTHORIZED'
]);
}
if ($request->isPost()) {
$result = $surveyTestMapper->delete($survey->id);
if ($result) {
// $this->logger->info('Se borro el formulario ' . $survey->name, ['user_id' => $currentUser->id, 'ip' => Functions::getUserIP()]);
$data = [
'success' => true,
'data' => 'LABEL_RECORD_DELETED'
];
} else {
$data = [
'success' => false,
'data' => $surveyTestMapper->getError()
];
return new JsonModel($data);
}
} else {
$data = [
'success' => false,
'data' => 'ERROR_METHOD_NOT_ALLOWED'
];
return new JsonModel($data);
}
return new JsonModel($data);
} catch (\Throwable $e) {
$e->getMessage();
return new JsonModel([
'success' => false,
'data' => $e
]);
}
}
public function reportAction() {
$request = $this->getRequest();
$currentUserPlugin = $this->plugin('currentUserPlugin');
$currentCompany = $currentUserPlugin->getCompany();
$currentUser = $currentUserPlugin->getUser();
$request = $this->getRequest();
$uuid = $this->params()->fromRoute('uuid');
if (!$uuid) {
$data = [
'success' => false,
'data' => 'ERROR_INVALID_PARAMETER'
];
return new JsonModel($data);
}
$surveyTestMapper = SurveyTestMapper::getInstance($this->adapter);
$surveyTest = $surveyTestMapper->fetchOneByuuid($uuid);
$surveyMapper = SurveyMapper::getInstance($this->adapter);
$survey = $surveyMapper->fetchOne($surveyTest->survey_id);
if (!$surveyTest) {
$data = [
'success' => false,
'data' => 'ERROR_RECORD_NOT_FOUND'
];
return new JsonModel($data);
}
if ($request->isGet()) {
$hydrator = new ObjectPropertyHydrator();
//get form data
$surveyFormMapper = SurveyFormMapper::getInstance($this->adapter);
$surveyForm = $surveyFormMapper->fetchOne($survey->form_id);
if ($surveyForm) {
return $this->renderPDF($surveyForm, $surveyTest, $survey);
} else {
$data = [
'success' => false,
'data' => 'ERROR_METHOD_NOT_ALLOWED'
];
return new JsonModel($data);
}
} else {
$data = [
'success' => false,
'data' => 'ERROR_METHOD_NOT_ALLOWED'
];
return new JsonModel($data);
}
return new JsonModel($data);
}
public function renderPDF($surveyForm, $surveyTest, $survey) {
$target_path = $this->config['leaderslinked.fullpath.company'] . DIRECTORY_SEPARATOR . $survey->uuid;
if(file_exists($target_path)) {
Functions::deleteFiles($target_path);
} else {
@mkdir($target_path, 0755, true);
}
// Set Data
$headerFormName = utf8_decode($surveyForm->name);
$headerSurveyName = utf8_decode('Informe de Encuesta: ' . trim($survey->name) . ' al ' . date("m-d-Y H:i:s", strtotime($survey->added_on)));
$sections = json_decode($surveyForm->content, true);
$test = json_decode($surveyTest->content, true);
//Generate New PDF
$pdf = new UniqueSurveyReport();
$pdf->AliasNbPages();
$pdf->AddPage();
// Set header secundary
$pdf->customHeader($headerFormName, $headerSurveyName);
$countSection = 0;
for ($i = 0; $i < count($sections); $i++) {
if ($countSection > 1) {
$countSection = 0;
$pdf->AddPage();
$pdf->customHeader($headerFormName);
}
$section = $sections[$i];
foreach ($section['questions'] as $question) {
switch ($question['type']) {
case 'simple':
$options = [];
foreach($question['options'] as $option) {
$options []= [
'text' => strip_tags($option['text']),
'selected' => $option['slug_option'] == $test[$question['slug_question']],
];
}
$pdf->optionTable(strip_tags($question['text']), $options);
break;
case 'multiple':
$options = [];
foreach($question['options'] as $option) {
$options []= [
'text' => strip_tags($option['text']),
'selected' => in_array($option['slug_option'], $test[$question['slug_question']]),
];
}
$pdf->optionTable(strip_tags($question['text']), $options);
break;
case 'open':
$pdf->borderTable(strip_tags($question['text']), [['content' => $test[$question['slug_question']]]]);
break;
}
$countSection++;
}
}
return $pdf->Output();
}
}