Current presenter located at app/presenters/HomepagePresenter.php
<?php
namespace App\Presenters;
use Latte\Engine;
use Mpdf\Mpdf;
use Mpdf\MpdfException;
use Mpdf\Output\Destination;
use Nette;
use Nette\Application\Responses\JsonResponse;
use Nette\Application\UI;
use Nette\Application\UI\Form;
use Nette\Utils\DateTime;
use Tracy\Debugger;
class HomepagePresenter extends BasePresenter
{
private $code;
private $purposeOfTheStay = [
null => '',
0 => 'messages.typePurposeOfTheStay.0',
1 => 'messages.typePurposeOfTheStay.1',
2 => 'messages.typePurposeOfTheStay.2',
3 => 'messages.typePurposeOfTheStay.3',
4 => 'messages.typePurposeOfTheStay.4',
5 => 'messages.typePurposeOfTheStay.5',
6 => 'messages.typePurposeOfTheStay.6',
7 => 'messages.typePurposeOfTheStay.7',
10 => 'messages.typePurposeOfTheStay.10',
11 => 'messages.typePurposeOfTheStay.11',
12 => 'messages.typePurposeOfTheStay.12',
13 => 'messages.typePurposeOfTheStay.13',
27 => 'messages.typePurposeOfTheStay.27',
93 => 'messages.typePurposeOfTheStay.93',
99 => 'messages.typePurposeOfTheStay.99',
];
private function checkCode($apCode)
{
$apCode = $this->refactorCode($apCode);
if (array_key_exists($apCode, $this->apartmentsTranslator)) {
return true;
}
$text = "The apartment code: '$apCode' was not found! used name: '$apCode'";
//$this->flashMessage($text);
return false;
}
private function refactorCode($apCode)
{
$apCode = str_replace(' ', '_', str_replace(['/', '-', '_'], '', trim(strtolower($apCode))));
return $apCode;
}
private function getApartmentName($apCode)
{
return $this->checkCode($apCode) ? $this->apartmentsTranslator[$apCode]['name'] : $apCode;
}
public function renderDefault()
{
$this->getHttpResponse()->setHeader('Access-Control-Allow-Origin', $this->context->parameters['rapartmentUrl']);
$this->getHttpResponse()->setHeader('Access-Control-Allow-Credentials', 'true');
$this->template->titleTranslation = $this->translator->translate('messages.registration');
}
public function actionGetGuestsInformation()
{
$users = [];
$result = $this->guestListManager->getInfo($this->request->getPost('code') ?: '');
foreach ($result as $user) {
$us = [];
foreach ($user as $key => $item) {
$us[$key] = $item;
}
$users[] = $us;
}
$this->getHttpResponse()->setHeader('Access-Control-Allow-Origin', $this->context->parameters['rapartmentUrl']);
$this->getHttpResponse()->setHeader('Access-Control-Allow-Credentials', 'true');
$this->sendResponse(new JsonResponse(json_encode($users)));
exit();
}
public function actionSetGuestInfo()
{
try {
$this->registrationFormSucceeded(null, $this->request->getPost());
} catch (\Exception $e) {
Debugger::log($e);
}
}
public function renderRegistration($code, $lang = null)
{
$this->translator->setLocale($lang);
$this->code = $code;
$this->template->setTranslator($this->translator);
$this->template->code = $code;
$this->template->titleTranslation = $this->translator->translate('messages.registration');
$this->template->apartmentTranslation = $this->translator->translate('messages.apartment');
if (!$result = $this->guestListManager->getInfo($this->code ?: $this->request->getParameter('code'))) {
$this->flashMessage($this->translator->translate('messages.error.codeDontExist'));
$this->redirect('Homepage:');
}
$this->template->usersName = [];
foreach ($result as $user) {
if ($user['passport']) {
$this->template->usersName[] = $user['surname'] . ' ' . $user['name'];
}
$this->template->apartment = $this->getApartmentName($user['apartment']);
}
}
protected function createComponentRegistrationForm()
{
$code = $this->code ?: $this->request->getParameter('code');
if (!$result = $this->guestListManager->getInfo($code)) {
$this->error($this->translator->translate('messages.error.codeDontExist'), 404);
}
$name = $sName = null;
$ifFirst = 1 === count($result);
$result = array_shift($result);
if ($ifFirst) {
$name = $result->name;
$sName = $result->surname;
}
$countryArray = [];
foreach ($this->database->table('country')->select('*')->order('code')->fetchAssoc('code') as $item) {
$countryArray[$item['code']] = 'messages.countries.' . $item['code'];
}
$form = new UI\Form;
$required = 'messages.error.required.';
$form->setTranslator($this->translator);
$form->addText('checkInDate', 'checkInDate')
->setType('date')
->setAttribute('description', $this->translator->translate('messages.description.checkInDate'))
->setDefaultValue((new DateTime($result->checkInDate))->format('Y-m-d'))
->setRequired($required . 'checkInDate')
->addRule($form::PATTERN, '%label example: ' . (new DateTime())->format('Y-m-d'), '[0-9]{4}-(0[1-9]|1[012])-(0[1-9]|1[0-9]|2[0-9]|3[01])')
->setAttribute('readonly');
$form->addText('checkOutDate', 'checkOutDate')
->setType('date')
->setAttribute('description', $this->translator->translate('messages.description.checkOutDate'))
->setDefaultValue((new Nette\Utils\DateTime($result->checkOutDate))->format('Y-m-d'))
->addRule($form::PATTERN, '%label example: ' . (new DateTime())->format('Y-m-d'), '[0-9]{4}-(0[1-9]|1[012])-(0[1-9]|1[0-9]|2[0-9]|3[01])')
->setRequired($required . 'checkOutDate')
->setAttribute('readonly');
$form->addText('name', 'name')
->setAttribute('description', $this->translator->translate('messages.description.name'))
->setDefaultValue($name)
->setRequired($required . 'name');
$form->addText('surname', 'surname')
->setDefaultValue($sName)
->setAttribute('description', $this->translator->translate('messages.description.surname'))
->setRequired($required . 'surname');
$form->addText('dateOfBirth', 'dateOfBirth')
->setType('date')
->setAttribute('max', (new Nette\Utils\DateTime())->modify('-15 years')->format('Y-m-d'))
->setAttribute('description', $this->translator->translate('messages.description.dateOfBirth'))
->addRule($form::PATTERN, '%label example: ' . (new DateTime())->format('Y-m-d'), '[0-9]{4}-(0[1-9]|1[012])-(0[1-9]|1[0-9]|2[0-9]|3[01])')
->setRequired($required . 'checkInDate');
$form->addSelect('country', 'country', $countryArray)
->setAttribute('description', $this->translator->translate('messages.description.country'))
->setRequired($required . 'country');
$form->addText('homeAddress', 'homeAddress')
->setAttribute('description', $this->translator->translate('messages.description.homeAddress'))
->setRequired($required . 'homeAddress')
->addRule(Form::MIN_LENGTH, 'messages.error.validate.homeAddressMinLength', 10);
$form->addText('passport', 'passport')
->setAttribute('description', $this->translator->translate('messages.description.passport'))
->setRequired($required . 'passport');
$form->addInteger('visa', 'visa')
->setAttribute('description', $this->translator->translate('messages.description.visa'));
$form->addText('checkInTime', 'checkInTime')
->setType('time')
->setAttribute('description', $this->translator->translate('messages.description.checkInTime'))
->setDefaultValue($result->checkInTime)
->setRequired($required . 'checkInTime');
$form->addRadioList('typeIn', 'messages.typeIn.title',
[
'car' => 'messages.typeIn.car',
'train' => 'messages.typeIn.train',
'plane' => 'messages.typeIn.plane',
'bus' => 'messages.typeIn.bus',
]
)
->setAttribute('description', $this->translator->translate('messages.description.typeIn'))
->setRequired($required . 'radio');
$form->addSelect('purposeOfTheStay', 'messages.typePurposeOfTheStay.name', $this->purposeOfTheStay)
->setAttribute('description', $this->translator->translate('messages.description.purposeOfTheStay'))
->setRequired($required . 'purposeOfTheStay');
$form->addCheckbox('check', 'check')->setRequired($required . 'check');
$form->addCheckbox('check2', 'I agree to provide my personal information for the Czech Police foreign')
->setRequired($required . 'check');
$form->addHidden('checkOutTime', $result->checkOutTime);
$form->addHidden('apartment', $result->apartment);
$form->addHidden('sumPeoples')->setDefaultValue($result->sumPeoples);
$form->addHidden('code')->setDefaultValue($code);
$form->addSubmit('submit', 'submit');
$form->onSuccess[] = [$this, 'registrationFormSucceeded'];
$form->onValidate[] = [$this, 'registrationFormValidator'];
return $form;
}
public function registrationFormValidator($form, $values)
{
if ((new \DateTime($this->reformatDate($values['dateOfBirth']))) >= (new \DateTime())->modify('-15 years')) {
$form->addError($this->translator->translate('messages.error.validate.youAreYoung'));
}
}
public function registrationFormSucceeded($form, $values)
{
unset($values['check'], $values['check2']);
foreach (['dateOfBirth', 'checkOutDate', 'checkInDate'] as $item) {
$values[$item] = $this->reformatDate($values[$item]);
}
$values['passport'] = str_replace(' ', '', $values['passport']);
$values['visa'] = str_replace(' ', '', $values['visa']);
$this->guestListManager->deleteFirstCode($values['code']);
if ($this->guestListManager->getInfo($values['code'], $values['name'], $values['surname'], $values['dateOfBirth'])) {
$this->guestListManager->updateInfo($values, $values['code']);
} else {
$this->guestListManager->setInfo($values);
}
if ($this->guestListManager->isAllSet($values['code'])) {
try {
$this->finishing($values['code']);
} catch (\Exception $e) {
//$this->emailManager->sendMailError($e);
}
}
if ($this->action === 'setGuestInfo') {
return;
}
$this->flashMessage($this->translator->translate('messages.succeeded.guest', ['guest' => $values['surname'] . ' ' . $values['name']]));
$this->redirect('Homepage:registration', $values['code']);
}
private function getIdubFileName($code)
{
return $this->apartmentsTranslator[$code]['code'] . '_' . (new \dateTime())->format('ymdhm');
}
/**
* @param $code
* @throws Nette\Application\AbortException
*/
public function actionForce($code)
{
$this->getHttpResponse()->setHeader('Access-Control-Allow-Origin', $this->context->parameters['rapartmentUrl']);
$this->getHttpResponse()->setHeader('Access-Control-Allow-Credentials', 'true');
$this->finishing($code);
$this->sendResponse(new Nette\Application\Responses\TextResponse('Ok'));
}
private function getHeadForIdub($code)
{
return $this->apartmentsTranslator[$this->refactorCode($code)]['header'] . '|' . (new \dateTime())->format('Y.m.d H:i:s') . '||';
}
private function setFile($user)
{
$linkToDir = ROOT_DIR . '/temp/files/police/' . $this->reformatDate($user['checkInDate']);
$linkToFile = $linkToDir . '/' . $this->getIdubFileName($user->apartment) . '.unl';
if (!file_exists($linkToDir)) {
mkdir($linkToDir, 0777);
}
if (!file_exists($linkToFile)) {
$this->setLineToFile($linkToFile, $this->getHeadForIdub($user->apartment));
}
$this->setLineToFile($linkToFile,
'U|' .
$this->reformatDate($user['checkInDate']) . '|' .
$this->reformatDate($user['checkOutDate']) . '|' .
$user['surname'] . '|' .
$user['name'] . '||' .
$this->reformatDate($user['dateOfBirth']) . '|||' .
$user['country'] . '|' .
$user['homeAddress'] . '|' .
$user['passport'] . '|' .
$user['visa'] . '|' .
$user['purposeOfTheStay'] . '||'
);
}
/**
* @param $date
* @return string
*/
private function reformatDate($date)
{
$_d = $date;
if (is_array($date) && key_exists('date', $date)) {
$date = $date['date'];
}
if (!($date = strtotime($date))) {
Debugger::log($_d, 'dateError');
return (new \DateTime())->format('d.m.Y');
}
try {
return (new \DateTime())->setTimestamp($date)->format('d.m.Y');
} catch (\Exception $e) {
return (new \DateTime())->format('d.m.Y');
}
}
private function setFileForManager($user)
{
$linkToDir = ROOT_DIR . '/temp/files/export/' . (new \DateTime())->format('Y');
if (!file_exists($linkToDir)) {
mkdir($linkToDir, 0777);
}
$linkToFile = $linkToDir . '/' . $this->refactorCode($this->getApartmentName($user['apartment'])) . '.csv';
if (!file_exists($linkToFile)) {
$this->setLineToFile($linkToFile,
'name|code|surname|visa|sumPeoples|dateOfBirth|homeAddress|checkInDate|checkInTime|checkOutDate|checkOutTime|apartment|country|typeIn|passport|purposeOfTheStay|sum days|sum pay');
}
$sumDays = (new \DateTime($user['checkInDate']))->diff(new \DateTime($user['checkOutDate']))->days;
$this->setLineToFile($linkToFile,
$user['name'] . '|' .
$user['code'] . '|' .
$user['surname'] . '|' .
$user['visa'] . '|' .
$user['sumPeoples'] . '|' .
$user['dateOfBirth'] . '|' .
$user['homeAddress'] . '|' .
$user['checkInDate'] . '|' .
$user['checkInTime'] . '|' .
$user['checkOutDate'] . '|' .
$user['checkOutTime'] . '|' .
$user['apartment'] . '|' .
$user['country'] . '|' .
$user['typeIn'] . '|' .
$user['passport'] . '|' .
$user['purposeOfTheStay'] . '|' .
$sumDays . '|' .
$sumDays * 0.6
);
}
private function createPdf($user)
{
}
public function renderSendEmails($date = null)
{
$this->template->titleTranslation = 'emails';
$date = $this->reformatDate($date);
$linkToDir = ROOT_DIR . '/temp/files/police/' . $date;
if (!file_exists($linkToDir)) {
$this->flashMessage("reservation on $date don't find");
return;
}
$files = scandir($linkToDir);
unset($files[0], $files[1]);
if (count($files) === 0) {
$this->flashMessage('dir is empty');
}
foreach ($files as $file) {
$this->emailManager->sendMailPolice($linkToDir . '/' . $file);
}
}
/**
* @param $code
* @throws Nette\Application\AbortException
*/
private function finishing($code)
{
$users = $this->guestListManager->getInfo($code);
if (empty($users)) {
$this->redirect('Homepage:');
}
$needSend = true;
$linkToDir = ROOT_DIR . '/temp/files/pdf/';
$uName = '';
foreach ($users as $user) {
if ($needSend) {
try {
$ch = curl_init($this->context->parameters['rapartmentUrl'] . '/Api/setGuestInformation');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query([
'code' => $user['code'],
'name' => $user['surname'] . ' ' . $user['name'],
'address' => $user['homeAddress'],
'arrivalType' => $user['typeIn'],
'arrivalDate' => $user['checkInDate'],
'arrivalTime' => $user['checkInTime'],
'transferInformation' => $user['typeIn'],
'nationality' => $user['country'],
'age' => (new \DateTime())->diff(new \DateTime($user['dateOfBirth']))->y,
], '', '&'));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_exec($ch);
curl_close($ch);
$needSend = false;
} catch (Nette\Neon\Exception $e) {
$this->flashMessage($e->getMessage());
}
}
$this->setFile($user);
$this->setFileForManager($user);
$userData = [];
foreach ($user as $key => $value) {
$userData[$key] = $value;
}
$userData['apartment'] = $this->apartmentsTranslator[$userData['apartment']]['name'];
$userData['_control'] = $userData['_presenter'] = $this->presenter;
$userData['ifOnOpenTime'] = $this->ifAtOpenTime($user['checkInTime'], $user['checkInDate']);
$uName = $uName ?: $user['surname'] . ' ' . $user['name'];
$linkToDir = ROOT_DIR . "/temp/files/pdf/" . $userData['apartment'];
//$this->emailManager->sendMailToUser($user['email'], $user['typeIn'], $userData);
}
try {
if (!is_dir($linkToDir)) {
mkdir($linkToDir, 0777);
}
$linkToDir = $linkToDir . "/$uName.pdf";
$this->cretePdf($code)->Output($linkToDir, Destination::FILE);
$this->emailManager->sendMailToManager($this->context->parameters['emailAddress'], ['users' => $users], $linkToDir);
} catch (\Exception $e) {
$this->emailManager->sendMailError($e->getMessage());
$this->emailManager->sendMailToManager($this->context->parameters['emailAddress'], ['users' => $users]);
}
$this->guestListManager->deleteCode($code);
$this->flashMessage('messages.succeeded.AllPeopleAreRegistered');
$this->redirect('Homepage:');
}
private function setLineToFile($file, $line)
{
file_put_contents($file, $line . "\r\n", FILE_APPEND);
}
public function renderUpLoad()
{
$this->template->titleTranslation = $this->translator->translate('messages.upLoad');
$this->template->setTranslator($this->translator);
}
protected function createComponentUploadForm()
{
$form = new UI\Form;
$form->addMultiUpload("file", "file");
$form->addSubmit('submit', 'submit');
$form->setTranslator($this->translator);
$form->onValidate[] = [$this, 'validateUploadFile'];
$form->onSuccess[] = [$this, 'saveUploadFile'];
return $form;
}
public function validateUploadFile(Form $form)
{
$values = $form->values;
$uploadDir = ROOT_DIR . '/temp/files';
foreach ($values['file'] as $file) {
$fileName = $file->name;
if (explode(".", $fileName)[1] !== 'csv') {
$form->addError($this->translator->translate('messages.error.validate.fileFormat'));
return;
}
if (!file_exists($uploadDir)) {
mkdir($uploadDir, 0777);
}
$file->move($uploadDir . '/../' . $fileName);
}
}
public function saveUploadFile(Form $form)
{
$values = $form->values;
$uploadDir = ROOT_DIR . '/temp/files';
/** @var Nette\Http\FileUpload $file */
foreach ($values['file'] as $file) {
$fileName = $file->name;
$handle = fopen($uploadDir . '/../' . $fileName, "r");
if ($handle) {
try {
$header = explode(';', iconv('windows-1251', 'utf-8', fgets($handle)));
$indexCode = array_search('Код', $header);
$indexCostumer = array_search('Заказчик', $header);
$indexApartment = array_search('Категория', $header);
$indexCheckIn = array_search('Заезд', $header);
$indexCheckOut = array_search('Выезд', $header);
$indexSumPeoples = array_search('Взр/Дети', $header);
if (false === $indexCode) {
$this->flashMessage('"Код" not found!');
var_dump($header);
break;
}
if (false === $indexCostumer) {
$this->flashMessage('"Заказчик" not found!');
var_dump($header);
break;
}
if (false === $indexApartment) {
$this->flashMessage('"Категория" not found!');
var_dump($header);
break;
}
if (false === $indexCheckIn) {
$this->flashMessage('"Заезд" not found!');
var_dump($header);
break;
}
if (false === $indexCheckOut) {
$this->flashMessage('"Выезд" not found!');
var_dump($header);
break;
}
if (false === $indexSumPeoples) {
$this->flashMessage('"Взр/Дети" not found!');
var_dump($header);
break;
}
} catch (Nette\Neon\Exception $e) {
$this->flashMessage($e);
break;
}
while (1 < count($buffer = explode(';', iconv('windows-1251', 'utf-8', fgets($handle))))) {
if ($this->guestListManager->getInfo($buffer[$indexCode])) {
$this->flashMessage('Code ' . $buffer[$indexCode] . ' already exists!');
continue;
}
if (!$this->checkCode($buffer[$indexApartment])) {
$this->flashMessage('Apartment with name ' . $buffer[$indexApartment] . ' don\'t exists!');
continue;
}
$array = [
'code' => $buffer[$indexCode],
'surname' => explode(' ', $buffer[$indexCostumer])[0],
'name' => key_exists(1, $surName = explode(' ', $buffer[$indexCostumer])) ? $surName[1] : '',
'apartment' => $this->refactorCode($buffer[$indexApartment]),
'checkInDate' => $this->reformatDate(explode(' ', $buffer[$indexCheckIn])[0]),
'checkInTime' => key_exists(1, $arrivalTime = explode(' ', $buffer[$indexCheckIn])) ? $arrivalTime[1] : '',
'checkOutDate' => $this->reformatDate(explode(' ', $buffer[$indexCheckOut])[0]),
'checkOutTime' => key_exists(1, $checkOutTime = explode(' ', $buffer[$indexCheckOut])) ? $checkOutTime[1] : '',
'sumPeoples' => array_sum(explode('/', $buffer[$indexSumPeoples])),
];
if (!$this->guestListManager->getInfo($array['code'])) {
$this->guestListManager->setInfo($array);
}
}
fclose($handle);
}
$file->move($uploadDir . '/' . $fileName);
$this->flashMessage($this->translator->translate('messages.importWasFinished'));
}
}
private function ifAtOpenTime($time, $date)
{
$time = (int)str_replace([':', '/', ' ', '-'], '', $time);
switch (strftime('%u', strtotime($date))) {
case 1:
case 2:
case 3:
case 4:
case 5:
$timeStart = 900;
$timeEnd = 2200;
break;
case 6:
case 7:
$timeStart = 1100;
$timeEnd = 1800;
break;
}
return $time > $timeStart && $time < $timeEnd;
}
/**
* @param $code
* @throws Nette\Application\AbortException
* @throws \Mpdf\MpdfException
*/
public function renderPdf($code)
{
$this->cretePdf($code)->Output();
die;
}
/**
* @param $code
* @return Mpdf
* @throws Nette\Application\AbortException
* @throws \Mpdf\MpdfException
*/
private function cretePdf($code)
{
$users = $this->guestListManager->getInfo($code);
if (empty($users)) {
$this->flashMessage("code: '$code' was not found!");
$this->redirect('Homepage:');
}
/*vytvoření objektu*/
$mpdf = new mPDF();
//exit;
$template = (new Engine)->renderToString(APP_DIR . "/presenters/templates/pdf/guests.latte", ['users' => $users, 'translate' => $this->translator, 'getApartmentAddress' => function ($name) {
$header = $this->database->table('idubs')->select('header')->where(['id' => $name])->fetch();
if (!$header) {
return $name;
}
//Balbinova 223/5, 12000, Praha, Vinohrady
//A|2|100103628264|USMAO|Ruterra Apartment Cimburkova 332/33|734284209|Praha|Praha|Zizkov|Cimburkova|332|33|13000
$header = explode('|', $header->header);
$address = $header[9] . ' ' . $header[10] . '/' . $header[11] . ' ' . $header[12] . ', ' . $header[6] . ', ' . $header[8];
return $address;
}]);
/*Přidání HTML*/
$mpdf->WriteHTML($template);
return $mpdf;
}
}