Rev 16766 | Autoría | Ultima modificación | Ver Log |
<?php
declare(strict_types=1);
namespace LeadersLinked\Controller;
use Laminas\Db\Adapter\AdapterInterface;
use Laminas\Mvc\Controller\AbstractActionController;
use Laminas\Log\LoggerInterface;
use Laminas\View\Model\ViewModel;
use Laminas\View\Model\JsonModel;
use LeadersLinked\Mapper\QueryMapper;
use Laminas\Db\Sql\Select;
use LeadersLinked\Library\Functions;
use LeadersLinked\Mapper\OrganizationalClimateTestMapper;
use LeadersLinked\Mapper\OrganizationalClimateMapper;
use LeadersLinked\Mapper\OrganizationalClimateFormMapper;
use LeadersLinked\Form\OrganizationalClimateTestForm;
use LeadersLinked\Model\OrganizationalClimateTest;
use LeadersLinked\Mapper\UserMapper;
use LeadersLinked\Hydrator\ObjectPropertyHydrator;
use LeadersLinked\Library\SurveyReport;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use PhpOffice\PhpSpreadsheet\IOFactory;
class OrganizationalClimateReportController extends AbstractActionController {
/**
*
* @var AdapterInterface
*/
private $adapter;
/**
*
* @var LoggerInterface
*/
private $logger;
/**
*
* @var array
*/
private $config;
/**
*
* @param AdapterInterface $adapter
* @param LoggerInterface $logger
* @param array $config
*/
public function __construct($adapter, $logger, $config)
{
$this->adapter = $adapter;
$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) {
$search = $this->params()->fromQuery('search', []);
$search = empty($search['value']) ? '' : Functions::sanitizeFilterString($search['value']);
$start = intval($this->params()->fromQuery('start', 0), 10);
$records_x_page = intval($this->params()->fromQuery('length', 10), 10);
$page = intval($start / $records_x_page);
$page++;
$order = $this->params()->fromQuery('order', []);
$order_field = empty($order[0]['column']) ? 99 : intval($order[0]['column'], 10);
$order_direction = empty($order[0]['dir']) ? 'ASC' : Functions::sanitizeFilterString(filter_var($order[0]['dir']));
$fields = ['name'];
$order_field = isset($fields[$order_field]) ? $fields[$order_field] : 'name';
if (!in_array($order_direction, ['ASC', 'DESC'])) {
$order_direction = 'ASC';
}
$organizationalClimateMapper = OrganizationalClimateMapper::getInstance($this->adapter);
$paginator = $organizationalClimateMapper->fetchAllDataTableByCompanyId($currentCompany->id, $search, $page, $records_x_page, $order_field, $order_direction);
$organizationalClimateFormMapper = OrganizationalClimateFormMapper::getInstance($this->adapter);
$items = [];
$records = $paginator->getCurrentItems();
foreach ($records as $record) {
$organizationalClimateForm = $organizationalClimateFormMapper->fetchOne($record->form_id);
$params = [
'id' => $record->uuid,
];
$item = [
'id' => $record->id,
'name' => $record->name,
'form' => $organizationalClimateForm->name,
'status' => $record->status,
'actions' => [
'link_report_all' => $this->url()->fromRoute('organizational-climate/report/all', ['organizational_climate_id' => $record->uuid]),
'link_report_csv' => $this->url()->fromRoute('organizational-climate/report/csv', ['organizational_climate_id' => $record->uuid]),
'link_overview' => $this->url()->fromRoute('organizational-climate/report/overview', ['organizational_climate_id' => $record->uuid])
]
];
array_push($items, $item);
}
return new JsonModel([
'success' => true,
'data' => [
'items' => $items,
'total' => $paginator->getTotalItemCount(),
]
]);
} else {
$organizationalClimateMapper = OrganizationalClimateMapper::getInstance($this->adapter);
$survies = $organizationalClimateMapper->fetchAllByCompanyId($currentCompany->id);
$form = new OrganizationalClimateTestForm($this->adapter, $currentCompany->id);
$this->layout()->setTemplate('layout/layout-backend');
$viewModel = new ViewModel();
$viewModel->setTemplate('leaders-linked/organizational-climate-report/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 overviewAction(){
$request = $this->getRequest();
$currentUserPlugin = $this->plugin('currentUserPlugin');
$currentCompany = $currentUserPlugin->getCompany();
$currentUser = $currentUserPlugin->getUser();
$request = $this->getRequest();
$uuid = $this->params()->fromRoute('organizational_climate_id');
if (!$uuid) {
$data = [
'success' => false,
'data' => 'ERROR_INVALID_PARAMETER'
];
return new JsonModel($data);
}
$organizationalClimateMapper = OrganizationalClimateMapper::getInstance($this->adapter);
$organizationalClimate = $organizationalClimateMapper->fetchOneByUuid($uuid);
$organizationalClimateMapper = OrganizationalClimateMapper::getInstance($this->adapter);
$organizationalClimate = $organizationalClimateMapper->fetchOneByUuid($uuid);
$organizationalClimateTestMapper = OrganizationalClimateTestMapper::getInstance($this->adapter);
$organizationalClimateTests = $organizationalClimateTestMapper->fetchAllBySurveyId($organizationalClimate->id);
$organizationalClimateFormMapper = OrganizationalClimateFormMapper::getInstance($this->adapter);
$organizationalClimateForm = $organizationalClimateFormMapper->fetchOne($organizationalClimate->form_id);
$sections = json_decode($organizationalClimateForm->content, true);
$allTests = array_map(
function($response) {
return json_decode($response->content, true);
},
$organizationalClimateTests,
);
$averages = [];
foreach($sections as $section) {
foreach($section['questions'] as $question) {
switch ($question['type']) {
case 'multiple':
$totals = [];
foreach($question['options'] as $option) {
$totals[$option['slug_option']] = 0;
}
foreach($question['options'] as $option) {
$totals[$option['slug_option']] = count(array_filter(
$allTests,
function ($test) use($option, $question) {
return in_array($option['slug_option'], $test[$question['slug_question']]);
}
));
}
$averages[$question['slug_question']] = $totals;
break;
case 'simple':
$totals = [];
foreach($question['options'] as $option) {
$totals[$option['slug_option']] = 0;
}
foreach ($allTests as $test) {
$totals[$test[$question['slug_question']]]++;
}
foreach($totals as $slug => $amount) {
$totals[$slug] = ($amount / count($allTests)) * 100;
}
$averages[$question['slug_question']] = $totals;
break;
}
}
}
$this->layout()->setTemplate('layout/layout-backend.phtml');
$viewModel = new ViewModel();
$viewModel->setTemplate('leaders-linked/organizational-climate-report/overview.phtml');
$viewModel->setVariables([
'sections' => $sections,
'averages' => $averages,
]);
return $viewModel ;
}
public function allAction() {
$request = $this->getRequest();
$currentUserPlugin = $this->plugin('currentUserPlugin');
$currentCompany = $currentUserPlugin->getCompany();
$currentUser = $currentUserPlugin->getUser();
$request = $this->getRequest();
$uuid = $this->params()->fromRoute('organizational_climate_id');
if (!$uuid) {
$data = [
'success' => false,
'data' => 'ERROR_INVALID_PARAMETER'
];
return new JsonModel($data);
}
$organizationalClimateMapper = OrganizationalClimateMapper::getInstance($this->adapter);
$organizationalClimate = $organizationalClimateMapper->fetchOneByUuid($uuid);
$organizationalClimateTestMapper = OrganizationalClimateTestMapper::getInstance($this->adapter);
$organizationalClimateTests = $organizationalClimateTestMapper->fetchAllBySurveyId($organizationalClimate->id);
if (!$organizationalClimateTests) {
$data = [
'success' => false,
'data' => 'ERROR_RECORD_NOT_FOUND'
];
return new JsonModel($data);
}
if ($request->isGet()) {
$hydrator = new ObjectPropertyHydrator();
//get form data
$organizationalClimateFormMapper = OrganizationalClimateFormMapper::getInstance($this->adapter);
$organizationalClimateForm = $organizationalClimateFormMapper->fetchOne($organizationalClimate->form_id);
if ($organizationalClimateForm) {
return $this->renderPDF($organizationalClimateForm, $organizationalClimateTests, $organizationalClimate);
} 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($organizationalClimateForm, $organizationalClimateTests, $organizationalClimate) {
$target_path = $this->config['leaderslinked.fullpath.company'] . DIRECTORY_SEPARATOR . $organizationalClimate->uuid;
if(file_exists($target_path)) {
Functions::deleteFiles($target_path);
} else {
@mkdir($target_path, 0755, true);
}
// Set Data
$headerFormName = Functions::utf8_decode($organizationalClimateForm->name);
$headerSurveyName = Functions::utf8_decode('Informe de Encuesta: ' . trim($organizationalClimate->name) . ' al ' . date("m-d-Y H:i:s", strtotime($organizationalClimate->added_on)));
$sections = json_decode($organizationalClimateForm->content, true);
$allTests = array_map(
function($response) {
return json_decode($response->content, true);
},
$organizationalClimateTests,
);
$averages = [];
foreach($sections as $section) {
foreach($section['questions'] as $question) {
switch ($question['type']) {
case 'multiple':
$totals = [];
foreach($question['options'] as $option) {
$totals[$option['slug_option']] = 0;
}
foreach($question['options'] as $option) {
$totals[$option['slug_option']] = count(array_filter(
$allTests,
function ($test) use($option, $question) {
return in_array($option['slug_option'], $test[$question['slug_question']]);
}
));
}
$averages[$question['slug_question']] = $totals;
break;
case 'simple':
$totals = [];
foreach($question['options'] as $option) {
$totals[$option['slug_option']] = 0;
}
foreach ($allTests as $test) {
$totals[$test[$question['slug_question']]]++;
}
foreach($totals as $slug => $amount) {
$totals[$slug] = ($amount / count($allTests)) * 100;
}
$averages[$question['slug_question']] = $totals;
break;
}
}
}
//Generate New PDF
$pdf = new SurveyReport();
$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, $headerUserName);
}
$section = $sections[$i];
foreach ($section['questions'] as $question) {
switch ($question['type']) {
case 'simple':
$labels = [];
$values = [];
foreach($question['options'] as $option) {
$labels []= strip_tags($option['text']) . "\n(%.1f%%)";
$values []= $averages[$question['slug_question']][$option['slug_option']];
}
$filename = $target_path . DIRECTORY_SEPARATOR . $question['slug_question'] . '.png';
$pdf->Cell(0,10,strip_tags(trim(str_replace(' ', ' ', html_entity_decode($question['text'])))),0,1);
$pdf->pieChart($labels, $values, '', $filename);
$pdf->SetFont('Arial', '', 12);
$pdf->Image($filename, 45, $pdf->getY(), 120);
$pdf->setY($pdf->getY() + 90);
break;
case 'multiple':
$labels = [];
$values = [];
foreach($question['options'] as $option) {
$labels []= strip_tags($option['text']);
$values []= $averages[$question['slug_question']][$option['slug_option']];
}
$filename = $target_path . DIRECTORY_SEPARATOR . $question['slug_question'] . '.png';
$pdf->Cell(0,10,strip_tags($question['text']),0,1);
$pdf->barChart($labels, $values, '', $filename);
$pdf->SetFont('Arial', '', 12);
$pdf->Image($filename, 12, $pdf->getY());
$pdf->setY($pdf->getY() + (count($values) * 13) + 10);
break;
}
$countSection++;
}
}
return $pdf->Output();
}
public function csvAction() {
$request = $this->getRequest();
$currentUserPlugin = $this->plugin('currentUserPlugin');
$currentCompany = $currentUserPlugin->getCompany();
$currentUser = $currentUserPlugin->getUser();
$request = $this->getRequest();
$uuid = $this->params()->fromRoute('organizational_climate_id');
if (!$uuid) {
$data = [
'success' => false,
'data' => 'ERROR_INVALID_PARAMETER'
];
return new JsonModel($data);
}
$organizationalClimateMapper = OrganizationalClimateMapper::getInstance($this->adapter);
$organizationalClimate = $organizationalClimateMapper->fetchOneByUuid($uuid);
$organizationalClimateTestMapper = OrganizationalClimateTestMapper::getInstance($this->adapter);
$organizationalClimateTests = $organizationalClimateTestMapper->fetchAllBySurveyId($organizationalClimate->id);
if (!$organizationalClimateTests) {
$data = [
'success' => false,
'data' => 'ERROR_RECORD_NOT_FOUND'
];
return new JsonModel($data);
}
if ($request->isGet()) {
$hydrator = new ObjectPropertyHydrator();
//get form data
$organizationalClimateFormMapper = OrganizationalClimateFormMapper::getInstance($this->adapter);
$organizationalClimateForm = $organizationalClimateFormMapper->fetchOne($organizationalClimate->form_id);
if ($organizationalClimateForm) {
return $this->csvRender($organizationalClimateForm, $organizationalClimateTests, $organizationalClimate);
} 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 csvRender($organizationalClimateForm, $organizationalClimateTests, $organizationalClimate)
{
$sections = json_decode($organizationalClimateForm->content, true);
$spreadsheet = new Spreadsheet();
$sheet = $spreadsheet->getActiveSheet();
$allTests = array_map(
function($response) {
return json_decode($response->content, true);
},
$organizationalClimateTests,
);
$averages = [];
foreach($sections as $section) {
foreach($section['questions'] as $question) {
switch ($question['type']) {
case 'multiple':
$totals = [];
foreach($question['options'] as $option) {
$totals[$option['slug_option']] = 0;
}
foreach($question['options'] as $option) {
$totals[$option['slug_option']] = count(array_filter(
$allTests,
function ($test) use($option, $question) {
return in_array($option['slug_option'], $test[$question['slug_question']]);
}
));
}
$averages[$question['slug_question']] = $totals;
break;
case 'simple':
$totals = [];
foreach($question['options'] as $option) {
$totals[$option['slug_option']] = 0;
}
foreach ($allTests as $test) {
$totals[$test[$question['slug_question']]]++;
}
foreach($totals as $slug => $amount) {
$totals[$slug] = ($amount / count($allTests)) * 100;
}
$averages[$question['slug_question']] = $totals;
break;
}
}
}
$row = 1;
for ($i = 0; $i < count($sections); $i++) {
$section = $sections[$i];
for($j = 0; $j < count($section['questions']); $j++) {
$question = $section['questions'][$j];
if (!in_array($question['type'], ['simple', 'multiple'])){
continue;
}
$sheet->setCellValueByColumnAndRow(1, $row++, strip_tags($question['text']));
switch ($question['type']) {
case 'simple':
for($k = 0; $k < count($question['options']); $k++) {
$option = $question['options'][$k];
$sheet->setCellValueByColumnAndRow(1, $row, strip_tags($option['text']));
$sheet->setCellValueByColumnAndRow(2, $row, round($averages[$question['slug_question']][$option['slug_option']], 2) . '%');
$row++;
}
break;
case 'multiple':
for($k = 0; $k < count($question['options']); $k++) {
$option = $question['options'][$k];
$sheet->setCellValueByColumnAndRow(1, $row, strip_tags($option['text']));
$sheet->setCellValueByColumnAndRow(2, $row,$averages[$question['slug_question']][$option['slug_option']]);
$row++;
}
break;
}
}
}
header('Content-Description: File Transfer');
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment; filename=report.xls');
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
$writer = new Xlsx($spreadsheet);
ob_clean();
flush();
$writer->save('php://output');
return;
}
}