Proyectos de Subversion LeadersLinked - Backend

Rev

Rev 15540 | Rev 15545 | Ir a la última revisión | Autoría | Comparar con el anterior | Ultima modificación | Ver Log |

<?php
declare(strict_types=1);

namespace LeadersLinked\Controller;

use Laminas\Db\Adapter\AdapterInterface;
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\CompanyMapper;
use LeadersLinked\Mapper\DailyPulseEmojiMapper;
use LeadersLinked\Form\DailyPulse\DailyPulseAddEmojiForm;
use LeadersLinked\Form\DailyPulse\DailyPulseEditEmojiForm;
use LeadersLinked\Model\DailyPulseEmoji;
use LeadersLinked\Library\Image;
use LeadersLinked\Mapper\DailyPulseRecordMapper;
use LeadersLinked\Model\DailyPulseRecord;
use PhpOffice\PhpSpreadsheet\IOFactory;
use PhpOffice\PhpSpreadsheet\Spreadsheet;

class DailyPulseReportsController 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()
    {
        return new JsonModel([
            'success' => false,
            'data' => 'ERROR_METHOD_NOT_ALLOWED'
        ]);
    }
    
    public function overviewAction()
    {
        $currentUserPlugin = $this->plugin('currentUserPlugin');
        $currentUser = $currentUserPlugin->getUser();
        
        $currentNetworkPlugin = $this->plugin('currentNetworkPlugin');
        $currentNetwork = $currentNetworkPlugin->getNetwork();
        
        $companyMapper = CompanyMapper::getInstance($this->adapter);
        $company = $companyMapper->fetchDefaultForNetworkByNetworkId($currentNetwork->id);
        
        $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) {
                
                $startDate = $this->params()->fromQuery('startDate');
                if(empty($startDate)) {
                    $startDate = date('Y-m-d');
                }
                
                
                $endDate = $this->params()->fromQuery('endDate');
                if(empty($startDate)) {
                    $endDate = date('Y-m-d');
                }
                
                //$startDate = '2023-03-01';
                //$endDate = '2023-03-19';
                
                $dtStartDate = \DateTime::createFromFormat('Y-n-d', $startDate);
                $dtEndDate = \DateTime::createFromFormat('Y-n-d', $endDate);
                
                if(!$dtStartDate || !$dtEndDate) {
                    $startDate = date('Y-m-d');
                    $endDate = date('Y-m-d');
                } else {
                    
                    if($dtStartDate->getTimestamp() > $dtEndDate->getTimestamp()) {
                        $startDate = date('Y-m-d');
                        $endDate = date('Y-m-d');
                    }
                }
                
                $dailyPulseRecordMapper = DailyPulseRecordMapper::getInstance($this->adapter);
                $how_are_you_feel = $dailyPulseRecordMapper->fetchAllDataChartOrExcelByCompanyIdAndTypeAndDateRange($company->id, DailyPulseRecord::TYPE_HOW_ARE_YOU_FEEL, $startDate, $endDate);
                
                $climate_on_your_organization = $dailyPulseRecordMapper->fetchAllDataChartOrExcelByCompanyIdAndTypeAndDateRange($company->id, DailyPulseRecord::TYPE_CLIMATE_ON_YOUR_ORGANIZATION, $startDate, $endDate);
                
                

                $data = [
                   'how_are_you_feel' => [
                       'average_points'     => 0,
                       'average_users'      => 0,
                       'labels'             => [],
                       'dataset1'           => [],
                       'dataset2'           => [],
                    ],    
                    'climate_on_your_organization' => [
                        'average_points'    => 0,
                        'average_users'     => 0,
                        'labels'            => [],
                        'dataset1'          => [],
                        'dataset2'          => [],
                    ]
                ];
                
                
                $how_are_you_feel_points = 0;
                $how_are_you_feel_users = 0;
                
                $climate_on_your_organization_points = 0;
                $climate_on_your_organization_users = 0;
                
                $count = 0;


                $dt = \DateTime::createFromFormat('Y-m-d', $startDate);
                do {
                    $count++;
                    $date = $dt->format('Y-m-d');
                    $label = $dt->format('d/m/Y');
                    
                    
                    $dataset1 = 0;
                    $dataset2 = 0;
                    foreach($how_are_you_feel as $record)
                    {
                        if($date == $record['date']) {
                            $dataset1 = $record['points'];
                            $dataset2 = $record['users'];
                        }
                    }
                    
                    $how_are_you_feel_points += $dataset1;
                    $how_are_you_feel_users += $dataset2;
                    
                    array_push($data['how_are_you_feel']['labels'], $label); 
                    array_push($data['how_are_you_feel']['dataset1'], $dataset1);
                    array_push($data['how_are_you_feel']['dataset2'], $dataset2);

                    
                    $dataset1 = 0;
                    $dataset2 = 0;
                    foreach($climate_on_your_organization as $record)
                    {
                        if($date == $record['date']) {
                            $dataset1 = $record['points'];
                            $dataset2 = $record['users'];
                        }
                    }
                    
                    $climate_on_your_organization_points += $dataset1;
                    $climate_on_your_organization_users += $dataset2;
                    
                    
                    array_push($data['climate_on_your_organization']['labels'], $label);
                    array_push($data['climate_on_your_organization']['dataset1'], $dataset1);
                    array_push($data['climate_on_your_organization']['dataset2'], $dataset2);
                    

                    
                    
                    $dt->add(new \DateInterval('P1D'));
                   
                    
                } while($date < $endDate);
                    
                $data['how_are_you_feel']['average_points'] =  number_format($how_are_you_feel_points / $count, 2);
                $data['how_are_you_feel']['average_users'] = number_format($how_are_you_feel_users / $count, 2);
                
                $data['climate_on_your_organization']['average_points'] = number_format($climate_on_your_organization_points / $count, 2);
                $data['climate_on_your_organization']['average_users'] = number_format($climate_on_your_organization_users / $count, 2);
                

                
                return new JsonModel([
                   'success' => true,
                   'data' => $data,
                ]);
                
                
                
                
                
            } else {
            
                //$form = new BehaviorForm();
                
                $this->layout()->setTemplate('layout/layout-backend');
                $viewModel = new ViewModel();
                $viewModel->setTemplate('leaders-linked/daily-pulse-reports/overview.phtml');
               // $viewModel->setVariable('form', $form);
                return $viewModel ;
            }
            
        } else {
            
            
            return new JsonModel([
                'success' => false,
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
            ]);
        }
    }
    
    public function overviewDownloadAction()
    {
        $currentUserPlugin = $this->plugin('currentUserPlugin');
        $currentUser = $currentUserPlugin->getUser();
        
        $currentNetworkPlugin = $this->plugin('currentNetworkPlugin');
        $currentNetwork = $currentNetworkPlugin->getNetwork();
        
        $companyMapper = CompanyMapper::getInstance($this->adapter);
        $company = $companyMapper->fetchDefaultForNetworkByNetworkId($currentNetwork->id);
        
        $request = $this->getRequest();
        
        if($request->isGet())
        {
            
            $startDate = $this->params()->fromQuery('startDate');
            if(empty($startDate)) {
                $startDate = date('Y-m-d');
            }
            
            
            $endDate = $this->params()->fromQuery('endDate');
            if(empty($startDate)) {
                $endDate = date('Y-m-d');
            }
            
            //$startDate = '2023-03-01';
            //$endDate = '2023-03-19';
            
            $dtStartDate = \DateTime::createFromFormat('Y-n-d', $startDate);
            $dtEndDate = \DateTime::createFromFormat('Y-n-d', $endDate);
            
            if(!$dtStartDate || !$dtEndDate) {
                $startDate = date('Y-m-d');
                $endDate = date('Y-m-d');
            } else {
                
                if($dtStartDate->getTimestamp() > $dtEndDate->getTimestamp()) {
                    $startDate = date('Y-m-d');
                    $endDate = date('Y-m-d');
                }
            }
            
            $dailyPulseRecordMapper = DailyPulseRecordMapper::getInstance($this->adapter);
            $how_are_you_feel = $dailyPulseRecordMapper->fetchAllDataChartOrExcelByCompanyIdAndTypeAndDateRange($company->id, DailyPulseRecord::TYPE_HOW_ARE_YOU_FEEL, $startDate, $endDate);
            
            $climate_on_your_organization = $dailyPulseRecordMapper->fetchAllDataChartOrExcelByCompanyIdAndTypeAndDateRange($company->id, DailyPulseRecord::TYPE_CLIMATE_ON_YOUR_ORGANIZATION, $startDate, $endDate);
            
            
            
            $data = [
                'how_are_you_feel' => [
                    'average_points'    => 0,
                    'average_users'     => 0,
                    'items'             => [],
                ],
                'climate_on_your_organization' => [
                    'average_points'    => 0,
                    'average_users'     => 0,
                    'items'             => [],
                ]
            ];
            
            
            $how_are_you_feel_points = 0;
            $how_are_you_feel_users = 0;
            
            $climate_on_your_organization_points = 0;
            $climate_on_your_organization_users = 0;
            
            $count = 0;
            
            
            $dt = \DateTime::createFromFormat('Y-m-d', $startDate);
            do {
                $count++;
                $date = $dt->format('Y-m-d');
                $label = $dt->format('d/m/Y');
                
                
                $dataset1 = 0;
                $dataset2 = 0;
                foreach($how_are_you_feel as $record)
                {
                    if($date == $record['date']) {
                        $dataset1 = $record['points'];
                        $dataset2 = $record['users'];
                    }
                }
                
                $how_are_you_feel_points += $dataset1;
                $how_are_you_feel_users += $dataset2;
                
                array_push($data['how_are_you_feel']['items'], [
                    'label' => $label, 
                    'dataset1' =>  $dataset1,
                    'dataset2' => $dataset2
                ]);
                
                
                $dataset1 = 0;
                $dataset2 = 0;
                foreach($climate_on_your_organization as $record)
                {
                    if($date == $record['date']) {
                        $dataset1 = $record['points'];
                        $dataset2 = $record['users'];
                    }
                }
                
                $climate_on_your_organization_points += $dataset1;
                $climate_on_your_organization_users += $dataset2;
                
                array_push($data['climate_on_your_organization']['items'], [
                    'label' => $label,
                    'dataset1' =>  $dataset1,
                    'dataset2' => $dataset2
                ]);
                
                
                $dt->add(new \DateInterval('P1D'));
                
                
            } while($date < $endDate);
            
            $data['how_are_you_feel']['average_points'] =  number_format($how_are_you_feel_points / $count, 2);
            $data['how_are_you_feel']['average_users'] = number_format($how_are_you_feel_users / $count, 2);
            
            $data['climate_on_your_organization']['average_points'] = number_format($climate_on_your_organization_points / $count, 2);
            $data['climate_on_your_organization']['average_users'] = number_format($climate_on_your_organization_users / $count, 2);
            
            
            
            
            
            $spreadsheet = new Spreadsheet();
            $spreadsheet->getProperties()->setTitle('Pulso Diario');
            
            
            
            $spreadsheet->setActiveSheetIndex(0);
            $dt = \DateTime::createFromFormat('Y-m-d', $startDate);
            
            $spreadsheet->getActiveSheet()->SetCellValue('A1', 'Desde:');
            $spreadsheet->getActiveSheet()->SetCellValue('B1', $dt->format('d/m/Y'));
            
            
            $dt = \DateTime::createFromFormat('Y-m-d', $startDate);
            $spreadsheet->getActiveSheet()->SetCellValue('C1', 'Hasta:');
            $spreadsheet->getActiveSheet()->SetCellValue('D1', $dt->format('d/m/Y'));
            
            
            $spreadsheet->getActiveSheet()->SetCellValue('A3', 'Como te sientes hoy');
            $spreadsheet->getActiveSheet()->SetCellValue('A4', 'Puntos promedios');
            $spreadsheet->getActiveSheet()->SetCellValue('B4',  $data['how_are_you_feel']['average_points']);
            $spreadsheet->getActiveSheet()->SetCellValue('C4', 'Usuarios promedios');
            $spreadsheet->getActiveSheet()->SetCellValue('D4',  $data['how_are_you_feel']['average_users']);
            
            
            $spreadsheet->getActiveSheet()->SetCellValue('F3', 'Clima en su organización');
            $spreadsheet->getActiveSheet()->SetCellValue('F4', 'Puntos promedios');
            $spreadsheet->getActiveSheet()->SetCellValue('G4',  $data['climate_on_your_organization']['average_points']);
            $spreadsheet->getActiveSheet()->SetCellValue('H4', 'Usuarios promedios');
            $spreadsheet->getActiveSheet()->SetCellValue('I4',  $data['climate_on_your_organization']['average_users']);
            
            $spreadsheet->getActiveSheet()->SetCellValue('A6', 'Fecha');
            $spreadsheet->getActiveSheet()->SetCellValue('B6', 'Puntos promedios');
            $spreadsheet->getActiveSheet()->SetCellValue('C6', 'Cantidad de usuarios');
            
            $i = 7;
            foreach($data['how_are_you_feel']['items'] as $record)
            {
                $spreadsheet->getActiveSheet()->SetCellValue('A' . $i, $record['label']);
                $spreadsheet->getActiveSheet()->SetCellValue('B' . $i, $record['dataset1']);
                $spreadsheet->getActiveSheet()->SetCellValue('C' . $i, $record['dataset2']);
                
                $i++;
            }
            
            
            $spreadsheet->getActiveSheet()->SetCellValue('F6', 'Fecha');
            $spreadsheet->getActiveSheet()->SetCellValue('G6', 'Puntos promedios');
            $spreadsheet->getActiveSheet()->SetCellValue('H6', 'Cantidad de usuarios');
            
            $i = 7;
            foreach($data['climate_on_your_organization']['items'] as $record)
            {
                $spreadsheet->getActiveSheet()->SetCellValue('F' . $i, $record['label']);
                $spreadsheet->getActiveSheet()->SetCellValue('G' . $i, $record['dataset1']);
                $spreadsheet->getActiveSheet()->SetCellValue('H' . $i, $record['dataset2']);
                
                $i++;
            }
            
                     
            $fileName = 'reporte_pulso_diario_'  . date('d-m-Y-h-i-a', time()) . '.xls';
            $tempFilename = tempnam(sys_get_temp_dir(), 'reporte_pulso_diario_' . time());
            
            $writer = IOFactory::createWriter($spreadsheet, 'Xlsx');
            $writer->save($tempFilename);
            
            $content = file_get_contents($tempFilename);
            @unlink($tempFilename);
            
            return new JsonModel([
                'success' => true,
                'data' => [
                    'content' => base64_encode($content),
                    'basename' => $fileName
                    
                ]
            ]);
            
            
            
            
        } else {
            return new JsonModel([
                'success' => false,
                'data' => 'ERROR_METHOD_NOT_ALLOWED'
            ]);
        }
    }
    
    
}