<?php
namespace App\Controller;
use App\Entity\Company;
use App\Entity\File\Contract;
use App\Entity\File\DigiSign;
use App\Entity\File\File;
use App\Entity\File\Signi;
use App\Entity\File\SimpleFile;
use App\Entity\Order;
use App\Entity\OrderEshop;
use App\Entity\Product;
use App\Entity\User;
use App\Exception\FulltextSearchNullResults;
use App\Form\Filter\OrderFilterType;
use App\Form\OrderType;
use App\Helper\EnumsHelper;
use App\Model\FileModel;
use App\Model\RewardLineModel;
use App\Model\RewardModel;
use App\Model\UserModel;
use App\Repository\FileRepository;
use App\Repository\OrderRepository;
use App\Repository\ProductRepository;
use App\Repository\UserRepository;
use App\Security\Voter\OrderVoter;
use App\Services\GalosoftAdamna;
use App\Services\GalosoftDigiSign;
use App\Services\GalosoftDigiSignGenerator;
use App\Services\GalosoftMailerInterface;
use App\Services\GalosoftNotifications;
use App\Services\GalosoftPdfGenerator;
use App\Services\GalosoftRaynet;
use App\Services\GalosoftSigni;
use App\Services\GalosoftSigniGenerator;
use App\Services\GalosoftValuablePaperGenerator;
use App\Services\OrderFilter;
use Doctrine\ORM\EntityManagerInterface;
use Knp\Component\Pager\PaginatorInterface;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\IsGranted;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Security;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\BinaryFileResponse;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\ResponseHeaderBag;
use Symfony\Component\HttpFoundation\Session\Session;
use Symfony\Component\HttpFoundation\StreamedResponse;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
use Symfony\Component\Routing\Annotation\Route;
/**
*
*/
class OrderController extends AbstractController
{
/**
* @isGranted("ROLE_MERCHANT")
* @Route("/order", name="app_order_index", methods={"GET", "POST"})
*/
public function index(FileRepository $repository,
OrderRepository $orderRepository,
Request $request,
PaginatorInterface $paginator,
GalosoftSigni $galosoftSigni,
Session $session,
EntityManagerInterface $entityManager,
OrderFilter $orderFilter,
UserModel $userModel,
\Symfony\Component\Security\Core\Security $security
): Response
{
// clear filter
if($orderFilter->clearFilter($session, $request) == true){
return $this->redirect($this->generateUrl('app_order_index'));
}
// ulozeni strankovace
$paginationSettings = $orderFilter->storePaginationSettings($session, $request);
// predvyplneni formulare filtrace
$data = $orderFilter->loadPrefilledData($session, $entityManager);
$formFilter = $this->createForm(OrderFilterType::class, $data, [
'action' => $this->generateUrl('app_order_index'),
'method' => 'post',
'request' => $request,
]);
// ulozim filtr do session
$orderFilter->storeFilter($formFilter, $request, $session);
// aplikace filtru na query builder
$queryBuilder = $orderRepository->createQueryBuilder('o');
try {
$orders = $orderFilter->applyFilter($session, $request, $queryBuilder, $paginator);
}catch (FulltextSearchNullResults $e){
$orders = [];
}
return $this->render('order/index.html.twig', [
'orders' => $orders,
'filter' => $formFilter->createView(),
'ordering' => $paginationSettings['ordering'],
'pageSize' => $paginationSettings['pageSize'],
'isOnlyMetalist' => $orderRepository->isOnlyMetalist()
]);
}
/**
* @Route("/order/export/{type}", name="app_order_export", methods={"GET"})
*/
public function export(
OrderRepository $orderRepository,
Session $session,
Request $request,
OrderFilter $orderFilter
){
$queryBuilder = $orderRepository->createQueryBuilder('o');
$orders = $orderFilter->applyFilter($session, $request, $queryBuilder);
$outputBuffer = fopen("php://temp", 'w');
$header = [
"ID",
"Datum podpisu",
"Datum úhrady",
"Datum odeslání",
"Datum doručeno",
"Produkt",
"Společnost",
"Jméno",
"Příjmení",
"T.P. - Ulice",
"T.P. - Město",
"T.P. - PSČ",
"K.A. - Ulice",
"K.A. - Město",
"K.A. - PSČ",
"Email",
"Telefon",
"Částka",
"Měna",
"Kód zástupce",
"Jméno zástupce",
"Email zástupce"
];
fputcsv($outputBuffer, $header);
$sum = 0;
/** @var Order $order */
foreach($orders->getQuery()->getResult() as $order) {
$row = [
$order->getId(),
($order->getSignedDate() instanceof \DateTime ? $order->getSignedDate()->format('Y-m-d') : ""),
($order->getPaidDate() instanceof \DateTime ? $order->getPaidDate()->format('Y-m-d') : ""),
($order->getSentDate() instanceof \DateTime ? $order->getSentDate()->format('Y-m-d') : ""),
($order->getVpDeliveryDate() instanceof \DateTime ? $order->getVpDeliveryDate()->format('Y-m-d') : ""),
($order->getProduct() instanceof Product) ? $order->getProduct()->getName() : '-',
($order->getCompany() instanceof Company) ? $order->getCompany()->getName() : '-',
($this->isGranted(OrderVoter::NOT_ANONYMIZE, $order) ? $order->getName() : ""),
($this->isGranted(OrderVoter::NOT_ANONYMIZE, $order) ? $order->getSurname() : ""),
($this->isGranted(OrderVoter::NOT_ANONYMIZE, $order) ? $order->getStreet() : ""),
($this->isGranted(OrderVoter::NOT_ANONYMIZE, $order) ? $order->getTown() : ""),
($this->isGranted(OrderVoter::NOT_ANONYMIZE, $order) ? $order->getPostal() : ""),
($this->isGranted(OrderVoter::NOT_ANONYMIZE, $order) ? $order->getStreet2() : ""),
($this->isGranted(OrderVoter::NOT_ANONYMIZE, $order) ? $order->getTown2() : ""),
($this->isGranted(OrderVoter::NOT_ANONYMIZE, $order) ? $order->getPostal2() : ""),
($this->isGranted(OrderVoter::NOT_ANONYMIZE, $order) ? $order->getEmail() : ""),
($this->isGranted(OrderVoter::NOT_ANONYMIZE, $order) ? $order->getPhone() : ""),
$order->getProductPriceTotal(),
($order->getProduct() instanceof Product) ? $order->getProduct()->getCurrency() : '-',
($this->isGranted(OrderVoter::NOT_ANONYMIZE, $order) ? $order->getMerchantCode() : ""),
($this->isGranted(OrderVoter::NOT_ANONYMIZE, $order) ? ($order->getMerchant() instanceof User ? $order->getMerchant()->getName() . " " . $order->getMerchant()->getSurname() : '') : ""),
($this->isGranted(OrderVoter::NOT_ANONYMIZE, $order) ? ($order->getMerchant() instanceof User ? $order->getMerchant()->getEmail() : '') : "")
];
$sum = $sum + (float)$order->getProductPriceTotal();
fputcsv($outputBuffer, $row);
}
$footer = ["CELKEM", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", "", $sum, "", "", "", ""];
fputcsv($outputBuffer, $footer);
rewind($outputBuffer);
$response = new Response(stream_get_contents($outputBuffer));
fclose($outputBuffer);
$response->headers->set('Content-Type', 'text/csv');
$response->headers->set('Content-Disposition', 'attachment; filename="EFS_'.date('Ymd').'.csv"');
return $response;
}
/**
* @IsGranted("ROLE_ADMIN")
*
* @Route("/order/report/{type}", name="app_order_report", methods={"GET"})
*/
public function report(
OrderRepository $orderRepository,
Session $session,
Request $request,
OrderFilter $orderFilter,
RewardModel $rewardModel
){
$queryBuilder = $orderRepository->createQueryBuilder('o');
$orders = $orderFilter->applyFilter($session, $request, $queryBuilder);
$rewards = $rewardModel->byOrderList($orders->getQuery()->getResult());
$outputBuffer = fopen("php://temp", 'w');
$header = [
"Jméno",
"Objednávka",
"Produkt",
"Celkem",
"Odměna %",
"Odměna Kč",
"Vztah"
];
fputcsv($outputBuffer, $header);
/** @var RewardLineModel $reward */
foreach($rewards as $reward) {
$row = $reward->toArray();
fputcsv($outputBuffer, $row);
}
rewind($outputBuffer);
$response = new Response(stream_get_contents($outputBuffer));
fclose($outputBuffer);
$response->headers->set('Content-Type', 'text/csv');
$response->headers->set('Content-Disposition', 'attachment; filename="EFS_report_'.date('Ymd').'.csv"');
return $response;
}
/**
* @Route("/order/new", name="app_order_new", methods={"GET", "POST"})
*/
public function new(Request $request, OrderRepository $orderRepository): Response
{
$order = new Order();
$currentPersonType = $order->getPersonType();
if(is_null($currentPersonType)){
$order->setPersonType('FO');
}
$options = [
'action' => $this->generateUrl('app_order_new_process'),
'method' => 'post',
'logged_user' => $this->getUser()
];
$form = $this->createForm(OrderType::class, $order, $options);
$form->handleRequest($request);
return $this->render('order/new.html.twig', [
'form' => $form->createView(),
'product' => $order->getProduct(),
'reloadUrl' => $this->generateUrl('app_order_new')
]);
}
/**
* @Route("/order/{hash}/preview", name="app_order_preview")
*/
public function previewPdf(
Request $request,
$hash,
OrderRepository $orderRepository,
EntityManagerInterface $entityManager,
GalosoftPdfGenerator $pdfGenerator
){
$order = $orderRepository->findOneBy(['hash' => $hash]);
if(!$order){
throw new NotFoundHttpException('Objednávka nenalezena');
}
$pdf = $pdfGenerator->generatePdf($order, false);
$response = new StreamedResponse(function() use ($pdf) {
$outputStream = fopen('php://output', 'wb');
$fileStream = fopen($pdf->getUrlDel(), 'r+');
stream_copy_to_stream($fileStream, $outputStream);
});
$response->headers->set('Content-Type', $pdf->getMime());
return $response;
}
/**
* @Route("/order/{order}", name="app_order_detail", requirements={"order"="\d+"})
*/
public function detail(Order $order, UserModel $userModel, \Symfony\Component\Security\Core\Security $security): Response
{
$this->denyAccessUnlessGranted(OrderVoter::NOT_ANONYMIZE, $order);
return $this->render('order/view.html.twig', [
'order' => $order,
'isOrderMetalist' => $order instanceof OrderEshop
]);
}
/**
* @Route("/order/{order}/sequence-number", name="app_order_save_sequence_number", requirements={"order"="\d+"})
*/
public function saveSequenceNumber(
Request $request,
Order $order,
EntityManagerInterface $entityManager
): Response
{
try {
//TODO: Add checking access for admin only
//$this->denyAccessUnlessGranted(OrderVoter::VIEW, $order);
$sequenceNumber = $request->get('sequenceNumber', null);
if (!is_null($sequenceNumber)) {
$order->setSequenceNumber($sequenceNumber);
$entityManager->flush();
}
return $this->json(['status' => 'success']);
} catch (\Exception $exception) {
return $this->json(['status' => 'error', 'message' => $exception->getMessage()]);
}
}
/**
* @Route("/order/{order}/valuable-paper/generate", name="app_order_valuable_paper_generate", requirements={"order"="\d+"})
*/
public function generateValuablePaper(
Request $request,
Order $order,
EntityManagerInterface $entityManager,
GalosoftValuablePaperGenerator $galosoftValuablePaperGenerator
): Response
{
try {
//TODO: Add checking access for admin only
//$this->denyAccessUnlessGranted(OrderVoter::VIEW, $order);
// generate and save valuable paper
$galosoftValuablePaperGenerator->generatePdf($order);
// generate and save valuable paper
$galosoftValuablePaperGenerator->generatePdf($order, true, GalosoftValuablePaperGenerator::TYPE_PDF_VALUABLE_PROTOCOL);
return $this->forward(OrderController::class . '::detail', [
'order' => $order->getId()
]);
} catch (\Exception $exception) {
return $this->json(['status' => 'error', 'message' => $exception->getMessage()]);
}
}
/**
* @Route("/order/{order}/edit", name="app_order_edit", requirements={"order"="\d+"})
*/
public function show(Order $order): Response
{
$this->denyAccessUnlessGranted(OrderVoter::EDIT, $order);
$form = $this->createForm(OrderType::class, $order, [
'action' => $this->generateUrl('app_order_edit_process', ['order' => $order->getId()]),
'method' => 'post',
'edit_entity' => true,
'logged_user' => $this->getUser()
]);
return $this->render('order/new.html.twig', [
'form' => $form->createView(),
'product' => $order->getProduct(),
'reloadUrl' => $this->generateUrl('app_order_new')
]);
}
/**
* To complete data from api
*
* @Route("/dokonceni-objednavky/{hash}", name="app_order_complete")
*/
public function complete(Request $request, $hash, OrderRepository $orderRepository, ProductRepository $productRepository): Response
{
$order = $orderRepository->findOneBy(['hash' => $hash]);
$now = new \DateTime('now');
if(!$order || $now > $order->getApiValidTill()){
return $this->render('errors/404.html.twig',
[
'title' => 'Ouha! Objednávku se nepodařilo najít!',
'description' => 'Požadovaná objednávka nebyla nalezena nebo expirovala její platnost. <br /> Pokud máte dotazy ozvěte se nám prosím na email <a href="objednavky@efsgroup.cz">objednavky@efsgroup.cz</a>.'
]);
}
$currentPersonType = $order->getPersonType();
if(is_null($currentPersonType)){
$order->setPersonType('FO');
}
if(isset($request->get('order')['product'])
&& (int)$request->get('order')['product'] != $order->getProduct()->getId()
){
// pri zmene produktu, aby se spravne renderoval formular tj. dependece atd. vlozim do objednavky novy
// produkt jiz ted a ne az skrze handlerequest
$formSentProduct = $productRepository->findOneBy(['id' => $request->get('order')['product']]);
if(false == is_null($formSentProduct)){
$order->setProduct($formSentProduct);
// array data from request
$requestOrder = $request->get('order');
$requestOrder['company'] = $formSentProduct->getCompany()->getId();
$request->request->set('order', $requestOrder);
}
//$order->setCompany($formSentProduct->getCompany());
}
$form = $this->createForm(OrderType::class, $order, [
'action' => $this->generateUrl('app_order_edit_process', ['order' => $order->getId()]),
'method' => 'post',
'edit_entity' => true,
'api_call' => true,
'api_complete' => true,
'logged_user' => $this->getUser()
]);
$form->handleRequest($request);
return $this->render('order/new.html.twig', [
'form' => $form->createView(),
'completeOrder' => true,
'product' => $order->getProduct(),
'reloadUrl' => $this->generateUrl('app_order_complete', ['hash' => $hash]),
]);
}
/**
* @Route("/order/new/process", name="app_order_new_process", methods={"POST"})
* @Route("/order/{order}/edit/process", name="app_order_edit_process", methods={"POST"})
*/
public function saveProcess(
Request $request,
OrderRepository $orderRepository,
Order $order = null,
GalosoftPdfGenerator $pdfGenerator,
GalosoftSigniGenerator $signiGenerator,
GalosoftSigni $signi,
EntityManagerInterface $entityManager,
UserPasswordHasherInterface $userPasswordHasher,
GalosoftMailerInterface $galosoftMailer,
UserRepository $userRepository,
GalosoftRaynet $galosoftRaynet,
GalosoftDigiSignGenerator $digiSignGenerator,
GalosoftDigiSign $digiSign,
GalosoftAdamna $galosoftAdamna
): Response
{
$orderEnt = is_null($order) ? new Order() : $order;
$orderData = $request->request->get('order');
if(isset($orderData['api_call']) && $orderData['api_call'] == "1") {
$orderOriginal = clone $order;
}
$form = $this->createForm(OrderType::class, $orderEnt, [
'edit_entity' => is_null($order) === false,
'allow_extra_fields' => true,
'logged_user' => $this->getUser()
]);
// vratim do puvodni podoby disabled data
if(isset($orderData['api_call']) && $orderData['api_call'] == "1") {
$orderEnt->setUser($orderOriginal->getUser())
->setMerchant($orderOriginal->getMerchant())
->setMerchantCode($orderOriginal->getMerchantCode())
->setCompany($orderOriginal->getCompany());
}
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$genSigni = @isset($request->request->get('order', [])['generateSigni']) ? @$request->request->get('order', [])['generateSigni'] : false;
$genPdf = @isset($request->request->get('order', [])['generatePdf']) ? @$request->request->get('order', [])['generatePdf'] : false;
$genDigiSign = @isset($request->request->get('order', [])['generateDigiSign']) ? @$request->request->get('order', [])['generateDigiSign'] : false;
$pdfPreview = true; // vzdycky generujeme pdf pro nahled
$genRaynet = $orderEnt->getProduct()->isGeneratorRaynet();
$genAdamna = $orderEnt->getProduct()->isUseAdamna();
$what = '';
if((boolean)$genPdf == true){
$what .= 'p';
}
if((boolean)$genSigni == true){
$what .= 's';
}
if((boolean)$genDigiSign == true){
$what .= 'd';
}
if((boolean)$genRaynet == true){
$what .= 'r';
}
if((boolean)$genAdamna == true){
$what .= 'a';
}
$targetUrl = $this->generateUrl('app_order_index');
if(isset($orderData['api_call']) && $orderData['api_call'] == "1") {
$orderEnt->setWhatGenerated($what);
$orderEnt->setReinvest((bool)$orderData['reinvest']);
$targetUrl = $this->generateUrl('app_order_thankyou', [
'hash' => $orderEnt->getHash()
]);
}
try {
if($orderEnt->getUser() == null){
$alreadyStored = $userRepository->findOneBy(['email' => $orderEnt->getEmail()]);
if(is_null($alreadyStored)) {
$user = new User();
$user->setEmail($orderEnt->getEmail())
->setActive(false)
->setIsVerified(false)
->setRoles(['ROLE_CUSTOMER'])
->setName($orderEnt->getName())
->setSurname($orderEnt->getSurname())
->setPassword($userPasswordHasher->hashPassword(
$user,
substr(md5(rand(10000, 999999999)), 0, 8)
));
$entityManager->persist($user);
}else{
$user = $alreadyStored;
}
$orderEnt->setUser($user);
}
$orderRepository->store($orderEnt, true);
if((boolean)$pdfPreview === true && $genPdf == false && $genSigni == false && $genDigiSign == false){
return $this->json([
'status' => 'success',
'previewUrl' => $this->generateUrl('app_order_preview', [
'hash' => $order->getHash()
])
]);
}
if ((boolean)$genPdf === true) {
$pdf = $pdfGenerator->generatePdf($orderEnt);
$pdfData = base64_encode(file_get_contents($pdf->getUrlDel()));
$filename = str_replace(['.docx', '.json'], '', $pdf->getName()). ".pdf";
if($request->get('preview', null) == "1"){
// jedna se o preview, vracim pdfko
return $this->json([
'status' => 'success',
'previewUrl' => $this->generateUrl('app_order_preview', [
'hash' => $order->getHash()
])
]);
}
if(isset($orderData['api_call']) && $orderData['api_call'] == "1") {
// posilame soubor na email - pouze v pripade ze se jedna o prichod z emailu - tj. api_call == 1
$galosoftMailer->send([
"template_id" => "d-a0b8f951e1af4fa4b73e5682fd2cc5b2",
"from" => array(
"name" => "EFS",
"email" => "info@efsgroup.cz"
),
"personalizations" => array(
array(
"dynamic_template_data" => [
"product" => $order->getProduct()->getName(),
"company" => $order->getProduct()->getCompany()->getName()
],
"to" => array(
array(
"email" => $orderEnt->getEmail()
),
)
)
),
"attachments" => [
[
"content" => $pdfData,
"type" => $pdf->getMime(),
"filename" => $filename
]
]
]);
}
}
if ((boolean)$genSigni === true && $orderEnt->getProduct()->isGeneratorSigni()) {
$signiContract = $signiGenerator->generateSigni($orderEnt, false);
$result = $signi->signContract($signiContract);
if($result !== false) {
$entityManager->flush();
}else{
throw new \Exception("Chyba při komunikaci se Signi.com");
}
}
if ((boolean)$genDigiSign === true) {
/** @var DigiSign $digiSignContract - Vygeneruje pdf, nasledne vytvorime obalku a posleme do digisignu */
$digiSignContract = $digiSignGenerator->generateDigiSign($orderEnt, false);
$result = $digiSign->send($digiSignContract->getEnvelopeId());
if($result !== false && $result['title'] != 'Validation Failed') {
$entityManager->flush();
}else{
throw new \Exception("Chyba při komunikaci se Digisign.org (".$result['detail'].")");
}
}
if ((boolean)$genRaynet === true) {
$result = $galosoftRaynet->sendContract($orderEnt);
if($result instanceof \stdClass && $result->success != 'true'){
throw new \Exception($result->message);
}
}
if ((boolean)$genAdamna === true) {
$result = $galosoftAdamna->sendContract($orderEnt);
if($result instanceof \stdClass && $result->status != 'true'){
throw new \Exception($result->message);
}
}
$entityManager->flush();
return $this->json([
'status' => 'success',
'target_url' => $targetUrl
]);
} catch (\Exception $exception) {
return $this->json([
'status' => 'error',
'msg' => $exception->getMessage()
]);
}
} else {
return $this->json([
'status' => 'error',
'msg' => (string)$form->getErrors(true, false)
]);
}
}
/**
* @Route("/dokonceni-objednavky/{hash}/dekujeme", name="app_order_thankyou", methods={"GET"})
*/
public function thankyou($hash, OrderRepository $orderRepository)
{
$order = $orderRepository->findOneBy(['hash' => $hash]);
if(!$order){
throw new NotFoundHttpException('Objednávka nenalezena');
}
$what = $order->getWhatGenerated();
return $this->render('order/thankyou.html.twig', [
'what' => $what
]);
}
/**
* @Route("/order/{order}/delete", name="app_order_delete", methods={"POST"}, requirements={"order"="\d+"})
*/
public function delete(Request $request,
Order $order,
OrderRepository $orderRepository,
FileRepository $fileRepository,
EntityManagerInterface $entityManager
): Response
{
try {
$this->denyAccessUnlessGranted(OrderVoter::DELETE, $order);
$files = $order->getFiles();
foreach ($files as $file){
$fileRepository->remove($file);
}
$orderRepository->remove($order, true);
$entityManager->flush();
return $this->json([
'status' => 'success'
]);
} catch (\Exception $e) {
return $this->json([
'status' => 'error',
'msg' => $e->getMessage()
]);
}
}
/**
* @Route("/order/{order}/state/{state}/date/{datechange}/{onoff}/", name="app_change_order_state", methods={"POST", "GET"}, requirements={"order"="\d+", "state"="inprogress|paid|sent|signed|paid2|vpDelivery"})
*/
public function changeState(Order $order, $state, $datechange, $onoff, EntityManagerInterface $entityManager): Response
{
try {
if($datechange == 'now'){
$date = new \DateTime('now');
}else {
$date = \DateTime::createFromFormat('d.m.Y', $datechange);
}
if(filter_var($onoff, FILTER_VALIDATE_BOOLEAN) == false){
$date = null;
}
switch ($state){
case "inprogress":
$order->setInProgress(filter_var($onoff, FILTER_VALIDATE_BOOLEAN))
->setInProgressDate($date);
break;
case "paid":
$order->setPaid(filter_var($onoff, FILTER_VALIDATE_BOOLEAN))
->setPaidDate($date);
break;
case "paid2":
$order->setPaid2(filter_var($onoff, FILTER_VALIDATE_BOOLEAN))
->setPaidDate2($date);
break;
case "signed":
$order->setSigned(filter_var($onoff, FILTER_VALIDATE_BOOLEAN));
$order->setSignedDate($date);
break;
case "vpDelivery":
$order->setVpDelivery(filter_var($onoff, FILTER_VALIDATE_BOOLEAN));
$order->setVpDeliveryDate($date);
break;
case "sent":
$order->setSent(filter_var($onoff, FILTER_VALIDATE_BOOLEAN))
->setSentDate($date);
break;
default:
throw new \Exception('Nepovoleny stav');
}
$entityManager->flush();
return $this->json([
'status' => 'success'
]);
} catch (\Exception $e) {
return $this->json([
'status' => 'error',
'msg' => $e->getMessage()
]);
}
}
/**
* @Route("/order/{order}/{file}/delete", name="app_order_file_delete", methods={"GET"}, requirements={"file"="\d+", "order"="\d+"})
*/
public function deleteFile(
Request $request,
Order $order,
File $file,
FileRepository $fileRepository
): Response
{
try {
$this->denyAccessUnlessGranted(OrderVoter::DELETE, $order);
$fileRepository->remove($file, true);
return $this->render('order/view.html.twig', [
'order' => $order,
'isOrderMetalist' => $order instanceof OrderEshop
]);
} catch (\Exception $e) {
return new JsonResponse(['statue' => 'error', 'msg' => $e->getMessage()]);
}
}
/**
* @Route("/order/download/digisign/{digiSign}/{output}", name="app_order_file_download_digisign", requirements={"digiSign"="\d+","output"="combined|only_log"})
* @param DigiSign $digiSign
*/
public function downloadDigiSign($digiSign, $output, GalosoftDigiSign $galosoftDigiSign, FileRepository $fileRepository)
{
$digiSignFile = $fileRepository->findOneBy(['id' => $digiSign]);
if(!$digiSignFile){
exit('Chyba aplikace');
}
$galosoftDigiSign->authenticate($digiSignFile->getProduct());
$data = $galosoftDigiSign->download($digiSignFile->getEnvelopeId(), $output);
// Vytvořte odpověď prohlížeče jako PDF soubor
$response = new Response($data);
$response->headers->set('Content-Type', 'application/pdf');
$response->headers->set('Content-Disposition', 'attachment; filename="'.$digiSignFile->getName().'.pdf"'); // Nastavte název souboru
// Odpověď odeslat
return $response;
}
/**
* @Route("/order/download/signi/{signi}", name="app_order_file_download_signi", requirements={"signi"="\d+"})
* @param Signi $signi
*/
public function downloadSigni(Signi $signi, GalosoftSigni $galosoftSigni)
{
// TODO: Check rights or is owner
$filePath = $galosoftSigni->downloadSigniContract($signi);
$pdfData = file_get_contents($filePath);
$response = new Response($pdfData, 200, [
'Content-Length' => strlen($pdfData),
'Content-type' => 'application/pdf',
'Content-Transfer-Encoding' => 'binary'
]);
$filename = str_replace(['.docx', '.json'], '', $signi->getName()). ".pdf";
$filenameFallback = preg_replace(
'#^.*\.#',
md5($filename) . '.', $filename
);
$disposition = $response->headers->makeDisposition(
ResponseHeaderBag::DISPOSITION_ATTACHMENT,
$filename,
$filenameFallback
);
$response->headers->set('Content-Disposition', $disposition);
return $response;
}
/**
* @Route("/order/download/signicl/{signi}", name="app_order_file_download_signi_cl", requirements={"signi"="\d+"})
* @param Signi $signi
*/
public function downloadSigniControlList(Signi $signi, GalosoftSigni $galosoftSigni)
{
// TODO: Check rights or is owner
$filePath = $galosoftSigni->downloadControlList($signi);
$pdfData = file_get_contents($filePath);
$response = new Response($pdfData, 200, [
'Content-Length' => strlen($pdfData),
'Content-type' => 'application/pdf',
'Content-Transfer-Encoding' => 'binary'
]);
$order = $signi->getOrderEnt();
preg_match("/v\.([0-9]+)\.docx/", $signi->getName(), $parsedVersion);
$version = isset($parsedVersion[1]) ? " v." .$parsedVersion[1] : "";
$filename = "Kontrolní list digitálního podpisu ke smlouvě č." . $order->getId() . $version. ".pdf";
$filenameFallback = preg_replace(
'#^.*\.#',
md5($filename) . '.', $filename
);
$disposition = $response->headers->makeDisposition(
ResponseHeaderBag::DISPOSITION_ATTACHMENT,
$filename,
$filenameFallback
);
$response->headers->set('Content-Disposition', $disposition);
return $response;
}
/**
* @Route("/order/{id}/uploadchunk/", name="app_order_uploadefilechunk")
* @param Request $request
* @return string
*/
public function uploadChunkFile(Request $request, Order $order, FileModel $fileModel){
try {
$fileModel->uploadChunkFile($request, $order);
return new JsonResponse(array(
"success" => true
));
} catch (Exception $e) {
return new JsonResponse(array(
"success" => false,
"error" => $e->getMessage()
));
}
}
/**
* @Route("/order/{id}/upload/", name="app_order_uploadefile")
* @param Request $request
* @return string
*/
public function uploadeFile(
Request $request,
EntityManagerInterface $em,
Order $order,
FileModel $fileModel,
GalosoftNotifications $galosoftNotifications
){
try {
$result = $fileModel->uploadOrderFile($request, $order);
$simpleFile = new SimpleFile();
$simpleFile->setName($result['fileName'])
->setMime($result['mimeType'])
->setUrl($result['url'])
->setUrlDel($result['urlDel'])
->setSize($result['size'])
->setOrderEnt($order)
->setProduct($order->getProduct())
->setVersion('1.0')
;
$em->persist($simpleFile);
$em->flush();
//$galosoftNotifications->manualUpload($order);
if(is_string($result['cmd'])){
$cmd = $result['cmd'];
}else{
$cmd = implode(" ", $result['cmd']);
}
return $this->json([
"success" => true,
"origName" => $result['origName'],
"slug" => $result['slug'],
"name" => $result['name'],
"type" => $result['type'],
"cmd" => $cmd,
"out" => $result['out']
]);
}catch (\Exception $exception){
return $this->json([
"success" => false,
"error" => $exception->getMessage(),
"preventRetry" => false
]);
}
}
/**
* @Route("/order/download/file/{file}", name="app_order_file_download", requirements={"file"="\d+"})
* @param File $file
*/
public function downloadFile(File $file)
{
$fileData = file_get_contents($file->getUrlDel());
$response = new Response($fileData, 200, [
'Content-Length' => strlen($fileData),
'Content-type' => $file->getMime(),
'Content-Transfer-Encoding' => 'binary'
]);
$filename = $file->getName();
$filenameFallback = preg_replace(
'#^.*\.#',
md5($filename) . '.', $filename
);
$disposition = $response->headers->makeDisposition(
ResponseHeaderBag::DISPOSITION_ATTACHMENT,
$filename,
$filenameFallback
);
$response->headers->set('Content-Disposition', $disposition);
return $response;
}
/**
* @Route("/order/download/pdf/{file}", name="app_order_file_download_file", requirements={"file"="\d+"})
* @param File $file
*/
public function downloadPdf(File $file, GalosoftSigni $galosoftSigni)
{
// TODO: Check rights or is owner
$pdfData = file_get_contents($file->getUrlDel());
$response = new Response($pdfData, 200, [
'Content-Length' => strlen($pdfData),
'Content-type' => 'application/pdf',
'Content-Transfer-Encoding' => 'binary'
]);
$filename = str_replace(['.docx', '.json'], '', $file->getName()) . ".pdf";
$filenameFallback = preg_replace(
'#^.*\.#',
md5($filename) . '.', $filename
);
$disposition = $response->headers->makeDisposition(
ResponseHeaderBag::DISPOSITION_ATTACHMENT,
$filename,
$filenameFallback
);
$response->headers->set('Content-Disposition', $disposition);
return $response;
}
}