Files
kupshop/bundles/External/PompoBundle/Controller/PompoController.php
2025-08-02 16:30:27 +02:00

254 lines
8.7 KiB
PHP

<?php
declare(strict_types=1);
namespace External\PompoBundle\Controller;
use External\PompoBundle\Attachment\ReceiptPDFAttachment;
use External\PompoBundle\DataGo\Util\DataGoApi;
use External\PompoBundle\Util\AutomaticImport\KnizniWeb\KnizniWebTypeEnum;
use External\PompoBundle\Util\AutomaticImport\KnizniWeb\KnizniWebUtil;
use External\PompoBundle\Util\Export\OSSExport;
use External\PompoBundle\Util\User\UserCardUtil;
use External\PompoBundle\View\UserCardsView;
use KupShop\ContentBundle\View\OrderView;
use KupShop\KupShopBundle\Config;
use KupShop\KupShopBundle\Context\UserContext;
use KupShop\KupShopBundle\Routing\TranslatedRoute;
use KupShop\KupShopBundle\Util\Contexts;
use KupShop\KupShopBundle\Views\Traits\MessagesTrait;
use KupShop\KupShopBundle\Views\View;
use KupShop\OrderingBundle\Exception\InvoiceException;
use Query\Operator;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\StreamedResponse;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\Routing\Annotation\Route;
class PompoController extends AbstractController
{
use MessagesTrait;
/**
* @TranslatedRoute("/#orderView#/{orderId}/receipt/")
*/
public function orderReceiptPDF(Request $request, ReceiptPDFAttachment $attachment, int $orderId): Response
{
OrderView::checkOrderOwnership($orderId, $request->get('cf'));
$order = new \Order();
if (!$order->createFromDB($orderId)) {
throw new NotFoundHttpException('Neexistujici objednavka');
}
$attachment->setOrder($order);
$response = new Response();
$response->headers->set('Content-Type', $attachment->getMimeType());
$response->headers->set('Content-Disposition', 'inline; filename="'.$attachment->getFilename().'"');
try {
$content = $attachment->getContent();
} catch (InvoiceException $e) {
throw new NotFoundHttpException($e->getMessage());
}
if (!$content) {
throw new \UnexpectedValueException('PDF error: server returned false');
}
$response->setContent($content);
return $response;
}
/**
* @TranslatedRoute(path="/#orderView#/{id_order}/pdf/", requirements={"id_order": "\d+"}, name="kupshop_orderingbundle_pdfinvoice")
*/
public function orderPDF(Request $request, DataGoApi $dataGoApi, int $id_order): Response
{
OrderView::checkOrderOwnership($id_order, $request->get('cf'));
try {
$order = \Order::get($id_order);
} catch (\InvalidArgumentException $e) {
throw new NotFoundHttpException('Order not found');
}
// Pokud ma objednavka uctenku, tak udelam redirect na uctenku
if ($order->getData('transactionPrintout')) {
return new RedirectResponse(
path('external_pompo_pompo_orderreceiptpdf', ['orderId' => $id_order, 'cf' => $request->get('cf')])
);
}
$dataGoId = sqlQueryBuilder()
->select('id_datago')
->from('datago_orders')
->where(Operator::equals(['id_order' => $id_order]))
->execute()->fetchOne();
if (!$dataGoId) {
return $this->invoicePDFNotFound($request, $id_order);
}
$filename = 'Faktura_'.$order->order_no.'.pdf';
if (!($invoice = $dataGoApi->getOrderInvoice($dataGoId))) {
return $this->invoicePDFNotFound($request, $id_order);
}
$response = new Response($invoice);
$response->headers->set('Content-Type', 'application/pdf');
$response->headers->set('Content-Disposition', 'inline; filename="'.$filename.'"');
return $response;
}
private function invoicePDFNotFound(Request $request, int $orderId): RedirectResponse
{
$dbcfg = \Settings::getDefault();
// soubor neexistuje na FTP - pravdepodobne ho uz smazali, takze zobrazime hlasku
addUserMessage(
sprintf('Fakturu se nepodařilo stáhnout. Pokud fakturu potřebujete, tak nás prosím kontaktujte na e-mailu <strong>%s</strong>',
$dbcfg->shop_email)
);
return new RedirectResponse(
path('kupshop_content_orders_order', ['id' => $orderId, 'cf' => $request->query->get('cf')])
);
}
/**
* @TranslatedRoute(path="/#account#/#user_cards#/")
*/
public function userCards(Request $request, UserCardUtil $userCardUtil, UserCardsView $view): Response
{
if (!Contexts::get(UserContext::class)->isActive()) {
return new RedirectResponse(
path('kupshop_user_login_login')
);
}
if ($request->get('generateCard')) {
$userId = (int) Contexts::get(UserContext::class)->getActiveId();
if (count($userCardUtil->getUserCards($userId)) < 4) {
$userCardUtil->generateUserCard(
(int) Contexts::get(UserContext::class)->getActiveId()
);
$this->addSuccessMessage(translate('generatedNewCard', 'pompo'));
}
return new RedirectResponse(
path('external_pompo_pompo_usercards')
);
}
return $view->getResponse();
}
#[Route('/kod/{codes}/')]
public function productListByCodes(string $codes): Response
{
return $this->forward('\KupShop\CatalogBundle\Controller\CatalogController::productListByCodes', [
'codes' => $codes,
]);
}
/**
* @Route("/_pompo/sellers/")
*/
public function sellers(Request $request): Response
{
$view = new class extends View {
protected $template = 'sellers.ajax.tpl';
public ?string $type = null;
public ?int $productId = null;
public $assortParam;
public function getBodyVariables()
{
$vars = parent::getBodyVariables();
$vars['assortParam'] = $this->assortParam;
$vars['type'] = $this->type;
$vars['productId'] = $this->productId;
return $vars;
}
};
$view->assortParam = $request->get('assortParam');
$view->type = $request->get('type');
$view->productId = $request->get('productId') ? (int) $request->get('productId') : null;
return $view->getResponse();
}
/**
* @Route("/_pompo/export/oss/")
*/
public function ossExport(Request $request, OSSExport $export): Response
{
if (!getAdminUser()) {
return new RedirectResponse(
'/'.trim(Config::get()['Path']['admin'], '/').'/index.php?error=4&url='.urlencode($request->getRequestUri())
);
}
return new StreamedResponse(function () use ($export) {
$export->export();
});
}
#[Route('/_pompo/knizniweb/feed/{type}/')]
public function knizniWebXML(KnizniWebUtil $util, string $type): Response
{
$dbcfg = \Settings::getDefault();
$config = $dbcfg->loadValue('knizniweb') ?: [];
// vycistim drive stazene soubory, ktere uz nejsou fresh a vratim ty, ktere jsou jeste aktualni
$cache = $util->cleanup();
$typeEnum = KnizniWebTypeEnum::from($type);
$response = new StreamedResponse(function () use ($util, $cache, $type, $typeEnum, $config) {
$token = $config['tokens'][$type] ?? null;
if (!empty($token)) {
// zkusim vzit file z cache
if (!($file = $cache[$config['tokens'][$type]] ?? false)) {
// pokud neni, tak ho zkusim stahnout
if (!($file = $util->getFeedFile($typeEnum, $config['tokens'][$type], false))) {
// pokud se nepodari stahnout, tak zkusim vygenerovat a stahnout
$file = $util->getFeedFile($typeEnum, $config['tokens'][$type]);
} else {
// poradilo se mi stahnout feed, tak rovnou poslu zadost na novej, at mam v dalsim runu novej
$util->requestNewFeed($typeEnum);
}
}
} else {
// pokud nemam token, tak zazadam o novy feed
$file = $util->getFeedFile($typeEnum, '');
}
if ($file) {
increaseMemoryLimit(2048);
readfile($file);
return;
}
echo 'Feed is being generated... try again in a minute';
});
$response->headers->set('Content-type', 'text/xml; charset=utf-8');
return $response;
}
}