src/Controller/IikoOrderController.php line 94

Open in your IDE?
  1. <?php
  2. namespace Slivki\Controller;
  3. use Doctrine\DBAL\Connection;
  4. use Doctrine\Persistence\ManagerRegistry;
  5. use libphonenumber\PhoneNumberUtil;
  6. use Slivki\BusinessFeature\VirtualWallet\Service\VirtualWalletChecker;
  7. use Slivki\Dao\FastDelivery\OfferFastDeliveryDaoInterface;
  8. use Slivki\Dao\Offer\DeliveryZoneDaoInterface;
  9. use Slivki\Dao\Order\OfferOrderPurchaseCountDaoInterface;
  10. use Slivki\Entity\City;
  11. use Slivki\Entity\Director;
  12. use Slivki\Entity\EntityOption;
  13. use Slivki\Entity\FoodOfferExtension;
  14. use Slivki\Entity\FoodOfferOptionExtension;
  15. use Slivki\Entity\FoodOrder;
  16. use Slivki\Entity\GeoLocation;
  17. use Slivki\Entity\Media\OfferExtensionMedia;
  18. use Slivki\Entity\Offer;
  19. use Slivki\Entity\OfferExtension;
  20. use Slivki\Entity\OfferExtensionOnlineCategory;
  21. use Slivki\Entity\OfferExtensionVariant;
  22. use Slivki\Entity\OfferOrder;
  23. use Slivki\Entity\OfferOrderDetails;
  24. use Slivki\Entity\OnlineOrderHistory;
  25. use Slivki\Entity\PriceDeliveryType;
  26. use Slivki\Entity\Seo;
  27. use Slivki\Entity\Street;
  28. use Slivki\Entity\UserAddress;
  29. use Slivki\Entity\UserBalanceActivity;
  30. use Slivki\Entity\Visit;
  31. use Slivki\Enum\OfferCode\PurchaseCountPeriod;
  32. use Slivki\Enum\Order\PaymentType;
  33. use Slivki\Exception\Offer\OfferExtension\Visibility\OfferExtensionNotVisibleException;
  34. use Slivki\Exception\Order\InsufficientBalanceFundsException;
  35. use Slivki\Handler\Order\OnlineOrderHistoryHandler;
  36. use Slivki\Helpers\PhoneNumberHelper;
  37. use Slivki\Helpers\WeightParserHelper;
  38. use Slivki\Repository\Delivery\FoodFilterCounterRepositoryInterface;
  39. use Slivki\Repository\Director\DirectorRepositoryInterface;
  40. use Slivki\Repository\Offer\DeliveryZoneRepositoryInterface;
  41. use Slivki\Repository\Offer\FoodOfferExtensionRepositoryInterface;
  42. use Slivki\Repository\PurchaseCount\PurchaseCountRepositoryInterface;
  43. use Slivki\Repository\SeoRepository;
  44. use Slivki\Repository\StreetRepository;
  45. use Slivki\Repository\User\CreditCardRepositoryInterface;
  46. use Slivki\Services\ImageService;
  47. use Slivki\Services\Mailer;
  48. use Slivki\Services\MapProviders\CoordinatesYandex;
  49. use Slivki\Services\Offer\CustomProductOfferSorter;
  50. use Slivki\Services\Offer\DeliveryZoneSorter;
  51. use Slivki\Services\Offer\OfferCacheService;
  52. use Slivki\Services\Offer\ProductFastDeliveryService;
  53. use Slivki\Services\OfferExtension\FoodByOnlineCategoriesBuilder;
  54. use Slivki\Services\OfferExtension\VisibilityFilterService;
  55. use Slivki\Services\Order\PricePromocodeForOnlineOrder;
  56. use Slivki\Services\PartnerBePaidService;
  57. use Slivki\Services\Payment\PaymentService;
  58. use Slivki\Services\Seo\SeoResourceService;
  59. use Slivki\Services\ShippingSchedulerService;
  60. use Slivki\Services\Subscription\SubscriptionService;
  61. use Slivki\Util\CommonUtil;
  62. use Slivki\Util\Iiko\AbstractDelivery;
  63. use Slivki\Util\Iiko\Dominos;
  64. use Slivki\Util\Iiko\IikoUtil;
  65. use Slivki\Util\Iiko\SushiChefArts;
  66. use Slivki\Util\Iiko\SushiHouse;
  67. use Slivki\Util\Iiko\SushiVesla;
  68. use Slivki\Util\Logger;
  69. use Symfony\Component\DependencyInjection\ContainerInterface;
  70. use Symfony\Component\HttpFoundation\JsonResponse;
  71. use Symfony\Component\HttpFoundation\Request;
  72. use Symfony\Component\HttpFoundation\Response;
  73. use Symfony\Component\Routing\Annotation\Route;
  74. use function array_search;
  75. use function array_unshift;
  76. use function array_column;
  77. use function array_map;
  78. use function array_filter;
  79. use function in_array;
  80. use function is_subclass_of;
  81. use function count;
  82. use function array_key_exists;
  83. use function array_merge;
  84. class IikoOrderController extends SiteController
  85. {
  86.     private const KILOGRAM 1000;
  87.     public const NEARLY 'Ближайшее';
  88.     /** @Route("/delivery/select/{offerID}", name = "deliveryOrder") */
  89.     public function indexAction(
  90.         Request $request,
  91.         ContainerInterface $container,
  92.         FoodFilterCounterRepositoryInterface $foodFilterCounterRepository,
  93.         SeoResourceService $seoResourceService,
  94.         SubscriptionService $subscriptionService,
  95.         PurchaseCountRepositoryInterface $purchaseCountRepository,
  96.         OfferCacheService $offerCacheService,
  97.         DirectorRepositoryInterface $directorRepository,
  98.         OfferFastDeliveryDaoInterface $offerFastDeliveryDao,
  99.         $offerID
  100.     ) {
  101.         $response = new Response();
  102.         $entityManager $this->getDoctrine()->getManager();
  103.         /** @var Offer|false $offerCached */
  104.         $offerCached $offerCacheService->getOffer($offerIDtruetrue);
  105.         if (false === $offerCached
  106.             || !$offerCached->hasFreeCodes()
  107.             || !($offerCached->isFoodOnlineOrderAllowedOnSite() || $offerCached->isAvailableOnFood())) {
  108.             return $this->redirect($seoResourceService->getOfferSeo($offerID)->getMainAlias());
  109.         }
  110.         $orderUtil AbstractDelivery::instance($offerCached);
  111.         $orderUtil->setContainer($container);
  112.         $isDominos $orderUtil instanceof Dominos;
  113.         $isSushiHouse $orderUtil instanceof SushiHouse;
  114.         $data['isDominos'] = $isDominos;
  115.         $data['showSortingIndexOrder'] = !($isSushiHouse || $isDominos);
  116.         $cityID $entityManager->getRepository(Offer::class)->getCityID($offerID);
  117.         $city $entityManager->find(City::class, $cityID);
  118.         $request->getSession()->set(City::CITY_ID_SESSION_KEY$city->getID());
  119.         $request->getSession()->set(City::CITY_DOMAIN_SESSION_KEY$city->getDomain());
  120.         $data['offer'] = $offerCached;
  121.         Logger::instance('IIKO-DEBUG')->info($offerID);
  122.         $director $directorRepository->getById((int) $offerCached->getDirectorID());
  123.         $data['company'] = $director;
  124.         $data['domain'] = $orderUtil->getDomain();
  125.         if (null !== $offerCached->getOnlineOrderSettings() && $offerCached->getOnlineOrderSettings()->getDomain()) {
  126.             $data['domain'] = $offerCached->getOnlineOrderSettings()->getDomain();
  127.         }
  128.         $data['dishes'] = [];
  129.         $user $this->getUser();
  130.         if (null !== $user) {
  131.             if ($subscriptionService->isSubscriber($user)) {
  132.                 $data['allowedCodesToBuy'] = $subscriptionService->getSubscription($user)->getNumberOfCodes();
  133.             } elseif ($user->isBatchCodesAllowed()) {
  134.                 $data['allowedCodesToBuyBatchCodes'] = $user->getBatchCodesCount();
  135.             }
  136.         }
  137.         $codeCost $this->getOfferRepository()->getCodeCost($offerCached);
  138.         $data['options'] = [];
  139.         $data['robotsMeta'] = 'noindex, follow';
  140.         $data['offerID'] = $offerID;
  141.         $data['director'] = $director;
  142.         $data['minSumForFreeDelivery'] = $orderUtil->getMinSumForFreeDelivery();
  143.         $data['minOrderSum'] = $orderUtil->getMinOrderSum();
  144.         $data['foodOffer'] = true;
  145.         $data['formAction'] = '/delivery/order/checkout';
  146.         $data['showDelivery'] = true;
  147.         $data['categoryName'] = $orderUtil::CATEGORY_NAME;
  148.         $data['footerOfferConditionID'] = $offerID;
  149.         $data['categoryURL'] = $entityManager->getRepository(Seo::class)->getSeoForEntity(SeoRepository::RESOURCE_URL_OFFER_CATEGORY$orderUtil::CATEGORY_ID)->getMainAlias();
  150.         $data['deliveryPrice'] = $orderUtil->getDeliveryPriceSettings();
  151.         $data['pickupEnabled'] = $orderUtil->isPickupEnabled();
  152.         $data['deliveryEnabled'] = $orderUtil->isDeliveryEnabled();
  153.         $data['isBuyCodeDisable'] = $offerCached->isBuyCodeDisable();
  154.         $data['isOnlineOrderAllowed'] = $offerCached->isFoodOnlineOrderAllowedOnSite();
  155.         $data['isAvailableOnFood'] = $offerCached->isAvailableOnFood();
  156.         $data['visitCount'] = $entityManager->getRepository(Visit::class)->getVisitCount($orderUtil::OFFER_IDVisit::TYPE_OFFER30true);
  157.         $data['filterAction'] = $foodFilterCounterRepository->findByOfferId((int) $offerID);
  158.         $purchaseCount $purchaseCountRepository->findByOfferId((int) $offerID);
  159.         $data['purchaseCountMonth'] = null === $purchaseCount $purchaseCount->getPurchaseCountLastMonthWithCorrection();
  160.         $data['sortList'] = CustomProductOfferSorter::SORT_LIST;
  161.         $data['codeCost'] = $codeCost;
  162.         if (!$offerFastDeliveryDao->isOfferHasActiveFastDelivery($offerID)) {
  163.             unset($data['sortList'][CustomProductOfferSorter::FAST_CUSTOM_PRODUCT_SORT]);
  164.         }
  165.         $view CommonUtil::isMobileDevice($request) ? 'Slivki/mobile/delivery/order.html.twig' 'Slivki/delivery/order.html.twig';
  166.         $response->setContent($this->renderView($view$data));
  167.         return $response;
  168.     }
  169.     /** @Route("/delivery/order/checkout", name = "deliveryOrderCheckout") */
  170.     public function checkoutAction(
  171.         Request $request,
  172.         ShippingSchedulerService $shippingSchedulerService,
  173.         ContainerInterface $container,
  174.         ManagerRegistry $registry,
  175.         SeoResourceService $seoResourceService,
  176.         SubscriptionService $subscriptionService,
  177.         DeliveryZoneDaoInterface $deliveryZoneDao,
  178.         DeliveryZoneSorter $deliveryZoneSorter,
  179.         PricePromocodeForOnlineOrder $pricePromocodeForOnlineOrder
  180.     ) {
  181.         ini_set('memory_limit''1g');
  182.         $additionalDominos null;
  183.         $response = new Response();
  184.         $offerID $request->request->getInt('offerID');
  185.         $entityManager $this->getDoctrine()->getManager();
  186.         $requestBasket $request->request->get('basket');
  187.         $pickupDeliveryType = empty($request->request->get('pickupDeliveryType')) ? FoodOfferExtension::DELIVERY_METHOD $request->request->getInt('pickupDeliveryType');
  188.         if (!$requestBasket) {
  189.             return $this->redirectToRoute('deliveryOrder', ['offerID' => $offerID]);
  190.         }
  191.         $request->getSession()->set(OnlineOrderHistory::SORT_SESSION_NAME$request->request->get('dishSortBy'));
  192.         /** @var Offer $offer */
  193.         $offer $entityManager->find(Offer::class, $offerID);
  194.         $slivkiDeliveryOption $entityManager->getRepository(EntityOption::class)->findBy([
  195.             'entityID' => $offerID,
  196.             'name' => EntityOption::OPTION_SLIVKI_DELIVERY
  197.         ]);
  198.         if (!$offer->hasFreeCodes()) {
  199.             return $this->redirect($seoResourceService->getOfferSeo($offerID)->getMainAlias());
  200.         }
  201.         $iikoUtil AbstractDelivery::instance($offer);
  202.         $iikoUtil->setContainer($container);
  203.         $isSushiVesla $iikoUtil instanceof SushiVesla;
  204.         $isDominos $iikoUtil instanceof Dominos;
  205.         if ($isDominos) {
  206.             $dominosSpesialData = [
  207.                 'amountPizza' => 0,
  208.             ];
  209.         }
  210.         $requestBasket json_decode($requestBaskettrue);
  211.         $basket = [];
  212.         foreach ($requestBasket as $basketItem) {
  213.             $key array_key_first($basketItem);
  214.             $variants = [];
  215.             if (is_array($basketItem[$key])) {
  216.                 foreach ($basketItem[$key] as $variantItem) {
  217.                     $variantKey array_key_first($variantItem);
  218.                     $variants[$variantKey] = $variantItem[$variantKey];
  219.                 }
  220.             } else {
  221.                 $variants $basketItem[$key];
  222.             }
  223.             $basket[$key] = $variants;
  224.         }
  225.         $totalDishCount 0;
  226.         foreach ($basket as $dishID => $variants) {
  227.             $extension $entityManager->find(OfferExtension::class, $dishID);
  228.             if (!$extension || $extension instanceof FoodOfferOptionExtension) {
  229.                 continue;
  230.             }
  231.             $dishCount 0;
  232.             if (!is_array($variants)) {
  233.                 $dishCount $variants;
  234.             } else {
  235.                 foreach ($variants as $variantID => $variantCount) {
  236.                     $extensionVariant $entityManager->find(OfferExtensionVariant::class, $variantID);
  237.                     if (!$extensionVariant) {
  238.                         continue;
  239.                     }
  240.                     $dishCount += $variantCount;
  241.                     
  242.                     if ($isDominos) {
  243.                         $dominosSpesialData['amountPizza'] += $variantCount;
  244.                     }
  245.                 }
  246.             }
  247.             $totalDishCount += $dishCount;
  248.         }
  249.         
  250.         if ($isDominos && $dominosSpesialData['amountPizza'] === 0) {
  251.             return new JsonResponse(['status' => 'error''error' => true'message' => 'Скидка на доп. меню действует только при заказе пиццы']);
  252.         }
  253.         if ($totalDishCount == 0) {
  254.             return $this->redirectToRoute('deliveryOrder', ['offerID' => $offerID]);
  255.         }
  256.         $user $this->getUser();
  257.         /** @var OfferOrder $order */
  258.         $order = new FoodOrder();
  259.         $order->setUser($user);
  260.         $order->setStatus(FoodOrder::STATUS_INIT);
  261.         $order->setOffer($offer);
  262.         $totalAmount 0;
  263.         $totalOfferAmount 0;
  264.         $codesCount 0;
  265.         $city $entityManager->find(City::class, $iikoUtil::CITY_ID);
  266.         $request->getSession()->set(City::CITY_ID_SESSION_KEY$city->getID());
  267.         $request->getSession()->set(City::CITY_DOMAIN_SESSION_KEY$city->getDomain());
  268.         $offersDetails = [];
  269.         foreach ($basket as $dishID => $variants) {
  270.             /** @var OfferExtension $extension */
  271.             $extension $entityManager->find(OfferExtension::class, $dishID);
  272.             if (!$extension) {
  273.                 continue;
  274.             }
  275.             if (is_array($variants)) {
  276.                 foreach ($variants as $variantID => $variantCount) {
  277.                     /** @var OfferExtensionVariant $extensionVariant */
  278.                     $extensionVariant $entityManager->find(OfferExtensionVariant::class, $variantID);
  279.                     if (!$extensionVariant) {
  280.                         continue;
  281.                     }
  282.                     $productsPerCode $extension->getProductsPerCode();
  283.                     if ($productsPerCode 0) {
  284.                         $codesCount += $productsPerCode == $variantCount $variantCount/$productsPerCode;
  285.                     }
  286.                     $variantOfferPrice PriceDeliveryType::calcDeliveryPickupPrice(
  287.                         $extension,
  288.                         $pickupDeliveryType,
  289.                         $extensionVariant->getRegularPrice(),
  290.                         $extensionVariant->getOfferPrice(),
  291.                         $additionalDominos
  292.                     );
  293.                     $totalOfferAmount += $variantCount $variantOfferPrice;
  294.                     $totalAmount += $variantCount $extensionVariant->getRegularPrice();
  295.                     $details = new OfferOrderDetails();
  296.                     $details->setOfferExtension($extension);
  297.                     $details->setOfferExtensionVariant($extensionVariant);
  298.                     $details->setItemsCount($variantCount);
  299.                     $order->addOfferOrderDetails($details);
  300.                 }
  301.             } else {
  302.                 $count = (int) $variants;
  303.                 if (=== $count) {
  304.                     continue;
  305.                 }
  306.                 $product $isSushiVesla
  307.                     $iikoUtil->getProductByDB($extension->getPartnerItemID(), $registry)
  308.                     : $iikoUtil->getProduct($extension->getPartnerItemID());
  309.                 if ($product->regularPrice == 0) {
  310.                     $product->regularPrice $extension->getPrice();
  311.                 }
  312.                 $totalAmount += $count $product->regularPrice;
  313.                 $recalculatedOfferPriceValue PriceDeliveryType::calcDeliveryPickupPrice(
  314.                     $extension,
  315.                     $pickupDeliveryType,
  316.                     $product->regularPrice,
  317.                     $extension->getCurrentPrice(null$pickupDeliveryType),
  318.                 );
  319.                 $product->offerPrice $recalculatedOfferPriceValue;
  320.                 $totalOfferAmount += $count $product->offerPrice;
  321.                 if (!$extension instanceof FoodOfferOptionExtension) {
  322.                     $productsPerCode $extension->getProductsPerCode();
  323.                     if ($productsPerCode 0) {
  324.                         $codesCount += $productsPerCode == $count $count/$productsPerCode;
  325.                     }
  326.                 }
  327.                 $details = new OfferOrderDetails();
  328.                 $details->setOfferExtension($extension);
  329.                 $details->setItemsCount($count);
  330.                 $order->addOfferOrderDetails($details);
  331.             }
  332.         }
  333.         $codesCount = \ceil($codesCount);
  334.         $totalAmountWithoutCode $totalOfferAmount;
  335.         $codeCost $pricePromocodeForOnlineOrder->getPrice($order$offer$codesCount$totalAmountWithoutCode);
  336.         $codeCostRegular $codeCost;
  337.         $user $order->getUser();
  338.         $allowedCodesToBuyBalance false;
  339.         if ($subscriptionService->isSubscriber($user) || $user->isBatchCodesAllowed()) {
  340.             $codeCost 0;
  341.         } elseif ($user->isBalanceAllowed($codesCount $codeCost)) {
  342.             $codeCost 0;
  343.             $allowedCodesToBuyBalance true;
  344.         }
  345.         $totalOfferAmount += $codesCount $codeCost;
  346.         $order->setCodesCount($codesCount);
  347.         $order->setCodeCost($codeCostRegular);
  348.         $deliveryPrice $iikoUtil->getMinSumForFreeDelivery() > && $totalAmountWithoutCode $iikoUtil->getMinSumForFreeDelivery() ? $iikoUtil->getDeliveryPriceSettings() : 0;
  349.         // Delivery price will be calculated after choosing the address
  350.         if (null !== $offer->getOfferDeliveryZone() && $offer->getOfferDeliveryZone()->count() > 0) {
  351.             $deliveryPrice 0;
  352.         }
  353.         if ($pickupDeliveryType === FoodOfferExtension::DELIVERY_METHOD_PICKUP) {
  354.             $deliveryPrice 0;
  355.         }
  356.         $order->setAmount($totalOfferAmount $deliveryPrice);
  357.         $order->setDeliveryCost($deliveryPrice);
  358.         if (CommonUtil::isMobileDevice($request)) {
  359.             $order->setDeviceType(SiteController::DEVICE_TYPE_MOBILE);
  360.         } else {
  361.             $order->setDeviceType(SiteController::DEVICE_TYPE_DESKTOP);
  362.         }
  363.         $entityManager->persist($order);
  364.         $entityManager->flush();
  365.         $entityManager->detach($order);
  366.         $deliveryAddresses $user->getAvailableUserAddresses($offerID);
  367.         $defaultDeliveryAddress = empty($deliveryAddresses) ? false $deliveryAddresses[0];
  368.         $deliveryAddressesGift $user->getAvailableUserAddressesGift($offerID);
  369.         if ($order->isOnlineGift()) {
  370.             $defaultDeliveryAddress $deliveryAddressesGift[0] ?? false;
  371.             $deliveryAddresses $deliveryAddressesGift;
  372.         }
  373.         $brandboxEnabled $offer->getBrandboxEnabled();
  374.         $deliveryEnabled $iikoUtil->isDeliveryEnabled();
  375.         $pickupEnabled $iikoUtil->isPickupEnabled();
  376.         $isAjaxScheduleForDelivery false;
  377.         $schedule $shippingSchedulerService->getEmptySchedule($iikoUtil$pickupDeliveryType);
  378.         if (
  379.             ($brandboxEnabled && $pickupDeliveryType === FoodOfferExtension::DELIVERY_METHOD && $deliveryAddresses) ||
  380.             (!$brandboxEnabled && $deliveryEnabled && $deliveryAddresses)
  381.         ) {
  382.             $schedule $shippingSchedulerService->getDeliverySchedule($iikoUtil$pickupDeliveryType);
  383.         }
  384.         $citySelect '';
  385.         $citySelectData $iikoUtil->getCitySelectData($entityManager);
  386.         if ($citySelectData) {
  387.             $citySelect $this->renderView(CommonUtil::isMobileDevice($request) ? 'Slivki/mobile/delivery/city_select.html.twig'
  388.                 'Slivki/delivery/city_select.html.twig', ['deliveryLocations' => $citySelectData]);
  389.         }
  390.         $workHourFrom 0;
  391.         $workHourTo 0;
  392.         $pickupLocations '';
  393.         $defaultLocationID null;
  394.         /** @var GeoLocation $geoLocation */
  395.         foreach ($offer->getGeoLocations() as $geoLocation) {
  396.             if (!$geoLocation->isActive()) {
  397.                 continue;
  398.             }
  399.             if (!$defaultLocationID) {
  400.                 $defaultLocationID $geoLocation->getID();
  401.             }
  402.             $pickupPointScheduleParsed $geoLocation->getPickupPointScheduleParsed();
  403.             if (!$pickupPointScheduleParsed) {
  404.                 continue;
  405.             }
  406.             $pickupLocations .= $this->renderView('Slivki/delivery/pickup_location_item.html.twig', [
  407.                 'location' => $geoLocation,
  408.             ]);
  409.         }
  410.         $nearestTime 'Ближайшее';
  411.         $deliveryTimeFrom $iikoUtil->getDeliveryTimeFrom();
  412.         $deliveryTimeTill $iikoUtil->getDeliveryTimeTill();
  413.         $additionalDominos = !(null === $additionalDominos);
  414.         $this->reCalcOrder(
  415.             $order,
  416.             0,
  417.             $pickupDeliveryType,
  418.             $subscriptionService->isSubscriber($this->getUser()),
  419.             $pricePromocodeForOnlineOrder
  420.         );
  421.         $data = [
  422.             'order' => $order,
  423.             'offer' => $offer,
  424.             'codeCost' => $codeCost,
  425.             'codeCostRegular' => $codeCostRegular,
  426.             'deliveryPrice' => $deliveryPrice,
  427.             'offerURL' => $entityManager->getRepository(Seo::class)->getOfferURL($offer->getID())->getMainAlias(),
  428.             'totalAmount' => $totalAmount $deliveryPrice,
  429.             'director' => $offer->getDirectors()->first(),
  430.             'robotsMeta' => 'noindex, follow',
  431.             'offerID' => $offerID,
  432.             'showCheckAddressButton' => $iikoUtil::SHOW_CHECK_ADDRESS_BUTTON,
  433.             'streetSuggest' => $iikoUtil::STREET_SUGGEST,
  434.             'workHourFrom' => $workHourFrom,
  435.             'workHourTo' => $workHourTo,
  436.             'citySelect' => $citySelect,
  437.             'multipleLocationDelivery' => $iikoUtil::MULTIPLE_LOCATIONS_DELIVERY,
  438.             'formAction' => '/delivery/order/check-payment',
  439.             'categoryName' => $iikoUtil::CATEGORY_NAME,
  440.             'categoryURL' => $entityManager->getRepository(Seo::class)->getSeoForEntity(SeoRepository::RESOURCE_URL_OFFER_CATEGORY$iikoUtil::CATEGORY_ID)->getMainAlias(),
  441.             'pickupLocations' => $pickupLocations,
  442.             'nearestTimeLabel' => $nearestTime,
  443.             'showDelivery' => true,
  444.             'defaultLocationID' => $defaultLocationID,
  445.             'pickupEnabled' => $pickupEnabled,
  446.             'deliveryEnabled' => $deliveryEnabled,
  447.             'allowedPaymentMethods' => $iikoUtil->getAllowedPaymentMethods(),
  448.             'footerOfferConditionID' => $offerID,
  449.             'pickupDiscount' => $iikoUtil->getPickupDiscount(),
  450.             'pickupDeliveryType' => $pickupDeliveryType,
  451.             'deliveryTimeFrom' => $deliveryTimeFrom,
  452.             'deliveryTimeTill' => $deliveryTimeTill,
  453.             'orderPeriodInDays' => $iikoUtil->getOrderPeriodInDays(),
  454.             'offersDetails' => $offersDetails,
  455.             'schedule' => $schedule,
  456.             'deliveryAddresses' => $deliveryAddresses,
  457.             'deliveryAddressesGift' => $deliveryAddressesGift,
  458.             'defaultDeliveryAddress' => $defaultDeliveryAddress,
  459.             'brandboxEnabled' => $brandboxEnabled,
  460.             'additionalDominos' => $additionalDominos,
  461.             'isSushiVesla' => $isSushiVesla,
  462.             'isDominos' => $isDominos,
  463.             'isAjaxScheduleForDelivery' => $isAjaxScheduleForDelivery,
  464.             'isOnlineGift' => $offer->isOnlineOrderGiftEnabled(),
  465.             'allowedCodesToBuyBalance' => $allowedCodesToBuyBalance,
  466.             'deliveryZones' => $deliveryZoneSorter->sortByDefault($deliveryZoneDao->findByOfferId($offerID)),
  467.             'offerForSlivkiDelivery' => $slivkiDeliveryOption,
  468.         ];
  469.         $data['iikoOrder'] = true;
  470.         $view CommonUtil::isMobileDevice($request) ? 'Slivki/mobile/delivery/delivery_checkout.html.twig' 'Slivki/delivery/delivery_checkout.html.twig';
  471.         $content $this->renderView($view$data);
  472.         $response->setContent($content);
  473.         $response->headers->addCacheControlDirective('no-cache'true);
  474.         $response->headers->addCacheControlDirective('max-age'0);
  475.         $response->headers->addCacheControlDirective('must-revalidate'true);
  476.         $response->headers->addCacheControlDirective('no-store'true);
  477.         return $response;
  478.     }
  479.     /**
  480.      * @Route("/delivery/order/payment/{orderID}", name="delivery_order_payment")
  481.      */
  482.     public function deliveryOrderPaymentAction(
  483.         Request $request,
  484.         PartnerBePaidService $partnerBePaidService,
  485.         OnlineOrderHistoryHandler $onlineOrderHistoryHandler,
  486.         SubscriptionService $subscriptionService,
  487.         CreditCardRepositoryInterface $creditCardRepository,
  488.         DirectorRepositoryInterface $directorRepository,
  489.         VirtualWalletChecker $virtualWalletChecker,
  490.         PricePromocodeForOnlineOrder $pricePromocodeForOnlineOrder,
  491.         $orderID
  492.     ) {
  493.         $entityManager $this->getDoctrine()->getManager();
  494.         $response = new Response();
  495.         /** @var FoodOrder $order */
  496.         $order $entityManager->find(FoodOrder::class, $orderID);
  497.         if (!$order) {
  498.             throw $this->createNotFoundException();
  499.         }
  500.         $user $order->getUser();
  501.         $offer $order->getOffer();
  502.         $offerID $offer->getID();
  503.         $iikoUtil IikoUtil::instance($offer);
  504.         $iikoUtil->setContainer($this->kernel->getContainer());
  505.         $isPickup $order->getDeliveryAddress()->isPickup();
  506.         $detailIdCount = [];
  507.         $totalAmount 0;
  508.         /** @var OfferOrderDetails $details */
  509.         $extensionIds = [];
  510.         foreach ($order->getOfferOrderDetails() as $details) {
  511.             $extension $details->getOfferExtension();
  512.             $extensionIds[] = $extension->getId();
  513.             if ($iikoUtil instanceof SushiHouse) {
  514.                 if (isset($detailIdCount[$extension->getID()])) {
  515.                     $detailIdCount[$extension->getID()] += $details->getItemsCount();
  516.                 } else {
  517.                     $detailIdCount[$extension->getID()] = $details->getItemsCount();
  518.                 }
  519.             }
  520.             $variant $details->getOfferExtensionVariant();
  521.             $regularPrice $variant $variant->getRegularPrice() : $details->getOfferExtension()->getPrice();
  522.             $totalAmount += $details->getItemsCount() * $regularPrice;
  523.             $sortByFromDelivery $request->getSession()->get(OnlineOrderHistory::SORT_SESSION_NAME);
  524.             if (null !== $sortByFromDelivery) {
  525.                 $onlineOrderHistoryHandler->handle(
  526.                     $order,
  527.                     $extension->getID(),
  528.                     $sortByFromDelivery
  529.                 );
  530.             }
  531.         }
  532.         $request->getSession()->set(OnlineOrderHistory::SORT_SESSION_NAMEnull);
  533.         $pickupDeliveryType $isPickup FoodOfferExtension::DELIVERY_METHOD_PICKUP FoodOfferExtension::DELIVERY_METHOD;
  534.         $deliveryCost 0;
  535.         if ($pickupDeliveryType === FoodOfferExtension::DELIVERY_METHOD || !$isPickup) {
  536.             $totalAmount += $order->getDeliveryCost();
  537.             $deliveryCost $order->getDeliveryCost();
  538.         }
  539.         $codeCost $order->getCodeCost();
  540.         $regularCodeCost $codeCost;
  541.         $allowedCodesToBuyBalance false;
  542.         if ($subscriptionService->isSubscriber($user) || $user->isBatchCodesAllowed()) {
  543.             $codeCost 0;
  544.         } elseif ($user->isBalanceAllowed($codeCost $order->getCodesCount())) {
  545.             $codeCost 0;
  546.             $allowedCodesToBuyBalance true;
  547.         }
  548.         $partnerBePaidService->setOrder($order);
  549.         $paymentToken $partnerBePaidService->getPaymentToken($ordernull$codeCost);
  550.         $view CommonUtil::isMobileDevice($request)
  551.             ? 'Slivki/mobile/delivery/delivery_payment.html.twig'
  552.             'Slivki/delivery/delivery_payment.html.twig';
  553.         $offersDetails = [];
  554.         $director $directorRepository->findById($offer->getDirectorID());
  555.         $fullOrderAmount $order->getAmount();
  556.         if ($allowedCodesToBuyBalance) {
  557.             $fullOrderAmount += $regularCodeCost $order->getCodesCount();
  558.         }
  559.         $this->reCalcOrder(
  560.             $order,
  561.             0,
  562.             $pickupDeliveryType,
  563.             $subscriptionService->isSubscriber($this->getUser()),
  564.             $pricePromocodeForOnlineOrder
  565.         );
  566.         $content =  $this->renderView($view, [
  567.             'order' => $order,
  568.             'offer' => $offer,
  569.             'offerURL' => $entityManager->getRepository(Seo::class)->getOfferURL($offerID)->getMainAlias(),
  570.             'offerID' => $offerID,
  571.             'categoryName' => $iikoUtil::CATEGORY_NAME,
  572.             'deliveryPrice' => $deliveryCost,
  573.             'codeCost' => $codeCost,
  574.             'totalAmount' => $totalAmount,
  575.             'showCheckAddressButton' => false,
  576.             'categoryURL' => $entityManager->getRepository(Seo::class)->getSeoForEntity(SeoRepository::RESOURCE_URL_OFFER_CATEGORY$iikoUtil::CATEGORY_ID)->getMainAlias(),
  577.             'isPickup' => $isPickup,
  578.             'allowedPaymentMethods' => $iikoUtil->getAllowedPaymentMethods()[$isPickup 'pickup' 'delivery'],
  579.             'pickupDiscount' => $isPickup $iikoUtil->getPickupDiscount() : 0,
  580.             'pickupDeliveryType' => $pickupDeliveryType,
  581.             'paymentToken' => $paymentToken['checkout']['token'],
  582.             'offersDetails' => $offersDetails,
  583.             'additionalDominos' => false,
  584.             'isDominos' => $iikoUtil instanceof Dominos,
  585.             'activeCreditCards' => !$offer->isRecurrentDisabled() ? $creditCardRepository->findActiveByUser($user) : [],
  586.             'directorName' => $director instanceof Director $director->getName() : '',
  587.             'allowedCodesToBuyBalance' => $allowedCodesToBuyBalance,
  588.             'isSlivkiPayAllowed' => $virtualWalletChecker->availableSlivkiPay($fullOrderAmount$user),
  589.             'allowedCashbackSumToPay' => $iikoUtil->getAllowedCashbackSumToPay($order$entityManager),
  590.             'allowedFastDeliveryForSushiHouse' => $iikoUtil->enabledFastDelivery($order),
  591.         ]);
  592.         $response->setContent($content);
  593.         return $response;
  594.     }
  595.     /** @Route("/delivery/order/check-payment", name = "deliveryOrderCheckPayment") */
  596.     public function checkPaymentAction(
  597.         Request $request,
  598.         CoordinatesYandex $coordinatesYandex,
  599.         DeliveryZoneRepositoryInterface $deliveryZoneRepository,
  600.         ShippingSchedulerService $shippingSchedulerService,
  601.         SubscriptionService $subscriptionService,
  602.         PhoneNumberUtil $phoneNumberUtil,
  603.         PhoneNumberHelper $phoneNumberHelper,
  604.         PricePromocodeForOnlineOrder $pricePromocodeForOnlineOrder,
  605.         VisibilityFilterService $visibilityFilterService
  606.     ) {
  607.         if (!$request->isMethod(Request::METHOD_POST)) {
  608.             throw $this->createNotFoundException();
  609.         }
  610.         $entityManager $this->getDoctrine()->getManager();
  611.         $orderID $request->request->getInt('orderID');
  612.         $pickupDeliveryType $request->request->get('pickupDeliveryType');
  613.         $pickupDeliveryType $pickupDeliveryType ? (int) $pickupDeliveryType null;
  614.         $isOnlineOrderGift $request->request->getBoolean('isOnlineGift');
  615.         $discount 0;
  616.         /** @var FoodOrder $order */
  617.         $order $entityManager->find(FoodOrder::class, $orderID);
  618.         if (!$order || $order->getUser()->getID() != $this->getUser()->getID() || $order->getStatus() != FoodOrder::STATUS_INIT) {
  619.             throw $this->createNotFoundException();
  620.         }
  621.         $order->setComment($request->request->get('comment'));
  622.         $order->setDeliveryTime($request->request->get('deliveryTime'));
  623.         $order->setIsOnlineGift($isOnlineOrderGift);
  624.         $iikoUtil IikoUtil::instance($order->getOffer());
  625.         $iikoUtil->setContainer($this->kernel->getContainer());
  626.         $possibilityOrder $iikoUtil->getPossibilityOrderStatus($order);
  627.         if ($possibilityOrder['status'] === 'error') {
  628.             return new JsonResponse(['status' => 'error''error' => true'message' => $possibilityOrder['message']]);
  629.         }
  630.         $isSushiHouse $iikoUtil instanceof SushiHouse;
  631.         $isSushiVesla $iikoUtil instanceof SushiVesla;
  632.         if (!$isSushiHouse && !$isSushiVesla) {
  633.             $this->reCalcOrder(
  634.                 $order,
  635.                 0,
  636.                 $pickupDeliveryType,
  637.                 $subscriptionService->isSubscriber($this->getUser()),
  638.                 $pricePromocodeForOnlineOrder
  639.             );
  640.         }
  641.         $request->getSession()->set("pickupDiscount"null);
  642.         if ($request->request->has('pickup')) {
  643.             $addressID $request->request->getInt('pickupAddressID');
  644.             $discount $request->request->getInt('pickupDiscount');
  645.             $request->getSession()->set("pickupDiscount"$discount);
  646.             $geoLocation $entityManager->find(GeoLocation::class, $addressID);
  647.             $userAddresses $entityManager->getRepository(UserAddress::class)->findBy(['user' => $this->getUser(), 'geoLocation' => $geoLocation]);
  648.             $address null;
  649.             foreach ($userAddresses as $location) {
  650.                 if ($location->getGeoLocation()->getID() == $addressID) {
  651.                     $address $location;
  652.                     break;
  653.                 }
  654.             }
  655.             if (!$address) {
  656.                 $address = new UserAddress();
  657.                 $address->setUser($this->getUser());
  658.                 $address->setGeoLocation($geoLocation);
  659.                 $address->setOfferID($order->getOffer()->getID());
  660.                 $entityManager->persist($address);
  661.             }
  662.             $address->setPickup(true);
  663.         } else {
  664.             $address $entityManager->find(UserAddress::class, $request->request->getInt('addressID'));
  665.             $geoLocation null;
  666.         }
  667.         if ($address) {
  668.             $name $request->request->get('name''');
  669.             $phone $request->request->get('phone''');
  670.             if (trim($name) == '' || trim($phone) == '') {
  671.                 return new JsonResponse(['error' => true]);
  672.             }
  673.             if (\mb_strlen($phone) > 0) {
  674.                 $phoneNumberObject $phoneNumberUtil->parse($phone);
  675.                 if (!$phoneNumberUtil->isValidNumber($phoneNumberObject)) {
  676.                     return new JsonResponse(['error' => true'message' => 'Введен некорректный номер телефона']);
  677.                 }
  678.             }
  679.             $address->setPhone($phone);
  680.             $address->setName($name);
  681.             $address->setIsOnlineGift($isOnlineOrderGift);
  682.             if ($isOnlineOrderGift) {
  683.                 $address->setNameGift($request->request->get('nameGift'));
  684.                 $address->setPhoneNumberGift(
  685.                     $phoneNumberHelper->convert($request->request->get('phoneNumberGift'), ''),
  686.                 );
  687.             }
  688.             $order->setDeliveryAddress($address);
  689.         } else {
  690.             return new JsonResponse(['error' => true'message' => 'Не выбран адрес']);
  691.         }
  692.         $result $iikoUtil->checkOrder($entityManager$order$subscriptionService);
  693.         if (!$result || $result->resultState 0) {
  694.             $message null;
  695.             if ($result) {
  696.                 switch ($result->resultState) {
  697.                     case 1:
  698.                         if (isset($result->problem)) {
  699.                             $message $result->problem;
  700.                         }
  701.                         if (isset($result->minSumForFreeDelivery)) {
  702.                             $message = \sprintf('Минимальная сумма заказа %s руб.', (string) $result->minSumForFreeDelivery);
  703.                         }
  704.                         break;
  705.                     case 2:
  706.                         $message 'Извините, в данное время заказ невозможен. Пожалуйста, выберите другое время';
  707.                         break;
  708.                     case 3:
  709.                         $message 'Извините, на данный адрес доставка не осуществляется';
  710.                         break;
  711.                     case 4:
  712.                     case 5:
  713.                         $message 'На данный момент заказ одного из товаров невозможен';
  714.                         break;
  715.                     case 9999:
  716.                         $message 'Заказы принимаются с 11:00 по 22:20';
  717.                         break;
  718.                 }
  719.             }
  720.             return new JsonResponse(['error' => true'message' => $message]);
  721.         }
  722.         try {
  723.             $visibilityFilterService->assertAllVisibleOrFail(array_map(
  724.                 static fn (OfferOrderDetails $orderDetail) => $orderDetail->getOfferExtension(),
  725.                 $order->getOfferOrderDetails()->toArray(),
  726.             ));
  727.         } catch (OfferExtensionNotVisibleException $e) {
  728.             return new JsonResponse(['error' => true'message' => $e->getMessage()]);
  729.         }
  730.         if ($request->request->get('deliveryTime') !== self::NEARLY) {
  731.             if ($request->request->get('deliveryTime') === null) {
  732.                 $checkSchedule = [
  733.                     'status' => 'error',
  734.                     'message' => 'Выберите время',
  735.                 ];
  736.             } else {
  737.                 $checkSchedule $iikoUtil->checkSchedule($shippingSchedulerService$geoLocation$entityManager$pickupDeliveryType$request->request->get('deliveryTime'));
  738.             }
  739.             if ($checkSchedule['status'] === 'error') {
  740.                 return new JsonResponse(['status' => $checkSchedule['status'], 'message' => $checkSchedule['message'], 'error' => true], Response::HTTP_OK);
  741.             }
  742.         }
  743.         if (null !== $order->getOffer()->getOfferDeliveryZone() && $order->getOffer()->getOfferDeliveryZone()->count() > 0) {
  744.             if (null === $address->isPickup()) {
  745.                 $points $address->getCoordinatesForDeliveryZone() ?? $coordinatesYandex->getGeoCoordinates(
  746.                     $address->buildFullAddress(),
  747.                     ['offerId' => (int)$order->getOffer()->getID()]
  748.                 );
  749.                 $deliveryZone $deliveryZoneRepository->getPolygonByPoint($order->getOffer(), $points);
  750.                 if (null !== $deliveryZone) {
  751.                     $user $order->getUser();
  752.                     $codeCost $order->getCodeCost();
  753.                     if ($subscriptionService->isSubscriber($user) || $user->isBatchCodesAllowed() || $user->isBalanceAllowed($codeCost $order->getCodesCount())) {
  754.                         $codeCost 0;
  755.                     }
  756.                     $total $order->getAmount() - ($order->getCodesCount() * $codeCost);
  757.                     if ($total $deliveryZone->getMinOrderAmount()) {
  758.                         return new JsonResponse([
  759.                             'error' => true,
  760.                             'message' => \sprintf('До минимальной суммы заказа в этой зоне %s р.', (string) ($deliveryZone->getMinOrderAmount() - $total)),
  761.                         ]);
  762.                     }
  763.                     $order->setDeliveryZoneLocationId($deliveryZone->getGeoLocationId());
  764.                     $order->setDeliveryCost($deliveryZone->getPaidDeliveryAmount());
  765.                     if ($total >= $deliveryZone->getFreeDeliveryAmount()) {
  766.                         $order->setDeliveryCost(0);
  767.                     }
  768.                     if (null === $address->getCoordinatesForDeliveryZone()) {
  769.                         $coordinates explode(' '$points);
  770.                         $address->setLatitude($coordinates[1]);
  771.                         $address->setLongitude($coordinates[0]);
  772.                     }
  773.                 } else {
  774.                     return new JsonResponse([
  775.                         'error' => true,
  776.                         'message' => 'Данный адрес не входит в зону доставки. Выберите другой адрес.',
  777.                     ]);
  778.                 }
  779.             } else {
  780.                 $order->setDeliveryZoneLocationId($address->getGeoLocation()->getID());
  781.             }
  782.         }
  783.         $this->reCalcOrder(
  784.             $order,
  785.             $discount,
  786.             $pickupDeliveryType,
  787.             $subscriptionService->isSubscriber($this->getUser()),
  788.             $pricePromocodeForOnlineOrder
  789.         );
  790.         $entityManager->flush();
  791.         return new JsonResponse(['error' => false'redirectURL' => '/delivery/order/payment/' $order->getID() ]);
  792.     }
  793.     /**
  794.      * @Route("/delivery/order/pay/{orderID}", name="deliveryOrderPay")
  795.      */
  796.     public function payAction(
  797.         Request $request,
  798.         PartnerBePaidService $partnerBePaidService,
  799.         PaymentService $paymentService,
  800.         CreditCardRepositoryInterface $creditCardRepository,
  801.         SubscriptionService $subscriptionService,
  802.         ContainerInterface $container,
  803.         PricePromocodeForOnlineOrder $pricePromocodeForOnlineOrder,
  804.         VirtualWalletChecker $virtualWalletChecker,
  805.         $orderID
  806.     ) {
  807.         $paymentMethod $request->request->getInt('paymentMethod');
  808.         $entityManager $this->getDoctrine()->getManager();
  809.         $order $entityManager->find(FoodOrder::class, $orderID);
  810.         if (null === $order) {
  811.             return new JsonResponse(['error' => true]);
  812.         }
  813.         $iikoUtil IikoUtil::instance($order->getOffer());
  814.         $iikoUtil->setContainer($container);
  815.         $order->setPaymentType($paymentMethod);
  816.         $order->setPaymentMethodID(OfferOrder::METHOD_BEPAID);
  817.         $isUsePartnerCashbackBalance $request->request->getBoolean('usePartnerCashbackBalance');
  818.         $order->setUsePartnerCashbackBalance($isUsePartnerCashbackBalance);
  819.         if ($isUsePartnerCashbackBalance) {
  820.             $allowedCashbackSumToPay $iikoUtil->getAllowedCashbackSumToPay($order$entityManager);
  821.             $order->setUsedPartnerCashbackSum($allowedCashbackSumToPay);
  822.         }
  823.         $order->setUseFastDelivery(
  824.             $request->request->getBoolean('useFastDelivery')
  825.         );
  826.         $order->setChangeAmount(
  827.             $request->request->get('changeAmount')
  828.                 ? (float) $request->request->get('changeAmount')
  829.                 : null
  830.         );
  831.         $codeCost $order->getCodeCost();
  832.         $codeCostRegular $codeCost;
  833.         $user $order->getUser();
  834.         $subscriber false;
  835.         if ($subscriptionService->isSubscriber($user)) {
  836.             $subscriber true;
  837.             $codeCost 0;
  838.         }
  839.         $isBatchCodes false;
  840.         if ($user->isBatchCodesAllowed()) {
  841.             $isBatchCodes true;
  842.             $codeCost 0;
  843.         }
  844.         if (in_array($paymentMethod, [PaymentType::CASHPaymentType::TERMINAL], true)) {
  845.             if ($subscriber || $isBatchCodes) {
  846.                 $order->setAmount($codeCost);
  847.                 $paymentService->createCode(
  848.                     $order,
  849.                     $order->getCodesCount(),
  850.                     false,
  851.                     null,
  852.                     false,
  853.                     $isBatchCodes UserBalanceActivity::TYPE_REDUCTION_BATCH_CODES null
  854.                 );
  855.                 return new JsonResponse(['error' => false]);
  856.             }
  857.             $order->setAmount($order->getCodesCount() * $codeCost);
  858.             $entityManager->flush();
  859.             return new JsonResponse([
  860.                 'redirectURL' => $this->redirectToRoute('buyCode', [
  861.                         'offerID' => $order->getOffer()->getID(),
  862.                         'codesCount' =>  $order->getCodesCount(),
  863.                         'orderID' => $order->getID()
  864.                     ]
  865.                 )->getTargetUrl()
  866.             ]);
  867.         }
  868.         $deliveryType $order->getDeliveryAddress()->isPickup() ? FoodOfferExtension::DELIVERY_METHOD_PICKUP FoodOfferExtension::DELIVERY_METHOD;
  869.         $discount $request->getSession()->get("pickupDiscount") ? $request->getSession()->get("pickupDiscount") : 0;
  870.         $this->reCalcOrder(
  871.             $order,
  872.             $discount,
  873.             $deliveryType,
  874.             $subscriptionService->isSubscriber($user),
  875.             $pricePromocodeForOnlineOrder
  876.         );
  877.         if ($paymentMethod === PaymentType::SLIVKI_PAY) {
  878.             $codeCostForSlivkiPay $order->getCodesCount() * (float) $order->getCodeCost();
  879.             try {
  880.                 $orderAmount $order->getAmount();
  881.                 if ($order->getUsedPartnerCashbackSum() > 0) {
  882.                     $orderAmount -= $order->getUsedPartnerCashbackSum();
  883.                 }
  884.                 if ($codeCost === || $user->isBalanceAllowed($codeCost $order->getCodesCount())) {
  885.                     $orderAmount += $codeCostForSlivkiPay;
  886.                 }
  887.                 if (!$virtualWalletChecker->availableSlivkiPay($orderAmount$user)) {
  888.                     return new JsonResponse(
  889.                         [
  890.                             'error' => true,
  891.                             'message' => 'Недостаточно средств на балансе SlivkiPay',
  892.                             'slivkiPay' => true,
  893.                         ]
  894.                     );
  895.                 }
  896.                 $paymentService->payOrder($user$orderAmount);
  897.                 $paymentService->createCode($order$order->getCodesCount(), false);
  898.             } catch (InsufficientBalanceFundsException $exception) {
  899.                 return new JsonResponse(['error' => true]);
  900.             }
  901.             return new JsonResponse(['error' => false]);
  902.         }
  903.         $order->setPaymentType(PaymentType::ONLINE);
  904.         if ($user->isBalanceAllowed($codeCost $order->getCodesCount())) {
  905.             $codeCost 0;
  906.         }
  907.         $iikoUtil->modifyOrder($order$entityManager);
  908.         $entityManager->flush();
  909.         $partnerBePaidService->setOrder($order);
  910.         $card $creditCardRepository->findById($request->request->getInt('creditCardID'));
  911.         if (null === $card || !$card->isOwner($this->getUser()->getID())) {
  912.             $paymentToken $partnerBePaidService->getPaymentToken($ordernull$codeCost);
  913.             if (!$paymentToken) {
  914.                 return new JsonResponse(['error' => true]);
  915.             }
  916.             $partnerBePaidService->createBePaidPaiment($order$paymentToken['checkout']['token']);
  917.             return new JsonResponse([
  918.                 'token' => $paymentToken['checkout']['token'],
  919.             ]);
  920.         }
  921.         $offerSettings $order->getOffer()->getOnlineOrderSettings();
  922.         if (($iikoUtil::SPLIT_PAYMENT || ($offerSettings && $offerSettings->isSplitPayment()))
  923.             && (!$subscriber && !$user->isBatchCodesAllowed() && !$user->isBalanceAllowed($codeCostRegular $order->getCodesCount()))
  924.         ) {
  925.             $amount $order->getAmount() - $order->getCodesCount() * $codeCost;
  926.         } else {
  927.             $amount $order->getAmount();
  928.         }
  929.         $result $partnerBePaidService->checkoutByToken($order$card->getID(), $amount);
  930.         if (!$result) {
  931.             return new JsonResponse(['error' => true]);
  932.         }
  933.         if (is_array($result) && isset($result['token'])) {
  934.             return new JsonResponse(['token' => $result['token']]);
  935.         }
  936.         $partnerBePaidService->createBePaidPaiment($order$result);
  937.         
  938.         return new JsonResponse(['error' => false]);
  939.     }
  940.     /** @Route("/delivery/street/suggest/{offerID}") */
  941.     public function deliveryStreetSuggest(Request $request$offerID): JsonResponse
  942.     {
  943.         /** @var StreetRepository $street */
  944.         $street $this->getDoctrine()->getManager()->getRepository(Street::class);
  945.         $streets $street->getStreets($offerID$request->query->get('q'));
  946.         return new JsonResponse($streets);
  947.     }
  948.     /** @Route("/delivery/feedback/{offerID}") */
  949.     public function feedbackAction(Request $requestMailer $mailer$offerID) {
  950.         $text $request->request->get('name') . ', ' $request->request->get('email') . "\n" $request->request->get('message') . "\n";
  951.         $subj ='';
  952.         if (is_numeric($offerID)) {
  953.             $offerID = (int)$offerID;
  954.             $offer $this->getDoctrine()->getManager()->find(Offer::class, $offerID);
  955.             if ($offer) {
  956.                 $subj 'Жалоба на акцию: ' $offer->getTitle();
  957.             } else {
  958.                 $subj 'Фидбек с доставки суши';
  959.             }
  960.         }
  961.         else if ($offerID == 'subscription-landing') {
  962.             $subj 'Фидбек с лендинга подписки';
  963.         }
  964.         else if ($offerID == 'auth') {
  965.             $subj 'Фидбек с попапа авторизации';
  966.         }
  967.         $message $mailer->createMessage($subj$text);
  968.         $message->setFrom('info@slivki.by''Slivki.by');
  969.         $message->setTo('1@slivki.by')
  970.             ->addTo('info@slivki.by')
  971.             ->addTo('yuri@slivki.com')
  972.             ->addCc('dmitry.kazak@slivki.com');
  973.         $mailer->send($message);
  974.         return new Response();
  975.     }
  976.     private function reCalcOrder(
  977.         FoodOrder $order,
  978.         $discount 0,
  979.         $typePrice null,
  980.         bool $isSubscriber false,
  981.         PricePromocodeForOnlineOrder $pricePromocodeForOnlineOrder
  982.     ) {
  983.         /** @var OfferOrderDetails $details */
  984.         $orderSum 0;
  985.         $additionalInfo $order->getAdditionalInfo();
  986.         $additionalDominos false;
  987.         if (isset($additionalInfo['dominosCoupon'])) {
  988.             $additionalDominos true;
  989.         }
  990.         $iikoUtil AbstractDelivery::instance($order->getOffer());
  991.         $iikoUtil->setContainer($this->kernel->getContainer());
  992.         foreach ($order->getOfferOrderDetails() as $details) {
  993.             $variant $details->getOfferExtensionVariant();
  994.             if ($variant) {
  995.                 $extension $variant->getOfferExtension();
  996.                 if ($additionalDominos) {
  997.                     $variantAdditionalDominos $variant;
  998.                 } else {
  999.                     $variantAdditionalDominos null;
  1000.                 }
  1001.                 $purchasePrice PriceDeliveryType::calcDeliveryPickupPrice(
  1002.                     $extension,
  1003.                     $typePrice,
  1004.                     $variant->getRegularPrice(),
  1005.                     $variant->getOfferPrice(),
  1006.                     $variantAdditionalDominos
  1007.                 );
  1008.             } else {
  1009.                 $extension $details->getOfferExtension();
  1010.                 $product $iikoUtil->getProduct($extension->getPartnerItemID());
  1011.                 $purchasePrice PriceDeliveryType::calcDeliveryPickupPrice(
  1012.                     $extension,
  1013.                     $typePrice,
  1014.                     $product->regularPrice,
  1015.                     $extension->getCurrentPrice(null$typePrice),
  1016.                 );
  1017.             }
  1018.             $orderSum += $details->getItemsCount() * $purchasePrice;
  1019.             $details->setPurchasePrice($purchasePrice);
  1020.         }
  1021.         $deliveryCost $order->getDeliveryCost();
  1022.         if (
  1023.             ($typePrice !== null && (int) $typePrice === FoodOfferExtension::DELIVERY_METHOD_PICKUP)
  1024.             || (null !== $order->getDeliveryAddress() && $order->getDeliveryAddress()->isPickup())
  1025.         ) {
  1026.             $deliveryCost 0;
  1027.         }
  1028.         $order->setDeliveryCost($deliveryCost);
  1029.         $regularCodeCost $pricePromocodeForOnlineOrder->getPrice(
  1030.             $order,
  1031.             $order->getOffer(),
  1032.             $order->getCodesCount(),
  1033.             $orderSum $deliveryCost
  1034.         );
  1035.         $codeCost 0;
  1036.         if (!$isSubscriber
  1037.             && !$order->getUser()->isBatchCodesAllowed()
  1038.             && !$order->getUser()->isBalanceAllowed($regularCodeCost $order->getCodesCount())
  1039.         ) {
  1040.             $codeCost $regularCodeCost;
  1041.         }
  1042.         $orderSum += $codeCost $order->getCodesCount() + $deliveryCost;
  1043.         if ($discount 0) {
  1044.             $orderSum -= ($orderSum * ($discount 100));
  1045.         }
  1046.         if ($order->getUsedPartnerCashbackSum() > 0) {
  1047.             $orderSum -= $order->getUsedPartnerCashbackSum();
  1048.         }
  1049.         $order->setAmount($orderSum);
  1050.     }
  1051.     /**
  1052.      * @Route("/delivery/check-address", name="delivery_check_address")
  1053.      */
  1054.     public function checkAddressAction(
  1055.         Request $request,
  1056.         SubscriptionService $subscriptionService,
  1057.         VisibilityFilterService $visibilityFilterService
  1058.     ): JsonResponse {
  1059.         $entityManager $this->getDoctrine()->getManager();
  1060.         $orderID $request->request->getInt('orderID');
  1061.         $addressID $request->request->getInt('addressID');
  1062.         $deliveryTime $request->request->get('deliveryTime');
  1063.         $order $entityManager->find(FoodOrder::class, $orderID);
  1064.         $order->setDeliveryTime($deliveryTime);
  1065.         $order->setPaymentType($request->request->getInt('paymentType'1));
  1066.         $address $entityManager->find(UserAddress::class, $addressID);
  1067.         $order->setDeliveryAddress($address);
  1068.         $orderInfo IikoUtil::instance($order->getOffer())->checkOrder($entityManager$order$subscriptionService);
  1069.         if (!$orderInfo) {
  1070.             return new JsonResponse(['error' => true]);
  1071.         }
  1072.         $entityManager->flush();
  1073.         $response $this->getCheckAddressResponse($orderInfo);
  1074.         try {
  1075.             $visibilityFilterService->assertAllVisibleOrFail(array_map(
  1076.                 static fn (OfferOrderDetails $orderDetail) => $orderDetail->getOfferExtension(),
  1077.                 $order->getOfferOrderDetails()->toArray(),
  1078.             ));
  1079.         } catch (OfferExtensionNotVisibleException $e) {
  1080.             return new JsonResponse([
  1081.                 'status' => 'error',
  1082.                 'error' => true,
  1083.                 'deliveryPrice' => $response['deliveryPrice'],
  1084.                 'message' => $e->getMessage(),
  1085.             ]);
  1086.         }
  1087.         return new JsonResponse($response);
  1088.     }
  1089.     /** @Route("/delivery/reload/offer/{offerId}/type/{typePrice}", name="deliveryReloadDish") */
  1090.     public function reloadDish(
  1091.         Request $request,
  1092.         ImageService $imageService,
  1093.         ProductFastDeliveryService $productFastDeliveryService,
  1094.         CustomProductOfferSorter $productSorter,
  1095.         ContainerInterface $container,
  1096.         FoodFilterCounterRepositoryInterface $foodFilterCounterRepository,
  1097.         CustomProductOfferSorter $customProductOfferSorter,
  1098.         OfferOrderPurchaseCountDaoInterface $offerOrderPurchaseCountDao,
  1099.         OfferCacheService $offerCacheService,
  1100.         FoodOfferExtensionRepositoryInterface $foodOfferExtensionRepository,
  1101.         WeightParserHelper $weightParserHelper,
  1102.         ShippingSchedulerService $shippingSchedulerService,
  1103.         FoodByOnlineCategoriesBuilder $foodByOnlineCategoriesBuilder,
  1104.         VisibilityFilterService $visibilityFilterService,
  1105.         $offerId,
  1106.         $typePrice
  1107.     ) {
  1108.         $offerCached $offerCacheService->getOffer($offerIdtruetrue);
  1109.         $data['offer'] = $offerCached;
  1110.         $orderUtil AbstractDelivery::instance($offerCached);
  1111.         $orderUtil->setContainer($container);
  1112.         $data['filterAction'] = $foodFilterCounterRepository->findByOfferId((int) $offerCached->getID());
  1113.         $isSushiVesla $orderUtil instanceof SushiVesla;
  1114.         $isDominos $orderUtil instanceof Dominos;
  1115.         $isSushiHouse $orderUtil instanceof SushiHouse;
  1116.         $isSushiChefArts $orderUtil instanceof SushiChefArts;
  1117.         $data['isDominos'] = $isDominos;
  1118.         $data['showSortingIndexOrder'] = $isSushiVesla || $isDominos false true;
  1119.         $allDishes = [];
  1120.         if ($isSushiVesla) {
  1121.             $allDishes $foodOfferExtensionRepository->findActiveByOfferIdAndShippingType($offerId$typePrice);
  1122.         }
  1123.         $shippingType FoodOfferExtension::LABEL_SHIPPING_TYPE[$typePrice];
  1124.         if ($isSushiVesla) {
  1125.             $dishes $orderUtil->getProductsDBByShippingType(
  1126.                 array_filter($allDishes, static fn (OfferExtension $offerExtension): bool => !is_subclass_of($offerExtensionFoodOfferExtension::class)),
  1127.             );
  1128.         } else {
  1129.             $dishes $orderUtil->getDishes();
  1130.         }
  1131.         $extensions $foodOfferExtensionRepository->findActiveByOfferIdAndShippingType($offerId$typePrice);
  1132.         $extensions array_combine(
  1133.             array_map(static fn (FoodOfferExtension $e) => $e->getPartnerItemID(), $extensions),
  1134.             $extensions,
  1135.         );
  1136.         $dishPurchaseCount $offerOrderPurchaseCountDao->getPurchaseCountsForPeriodByOffer((int) $offerIdPurchaseCountPeriod::LAST_MONTH);
  1137.         $dishPurchaseDayCount $offerOrderPurchaseCountDao->getPurchaseCountsForPeriodByOffer((int) $offerIdPurchaseCountPeriod::LAST_DAY);
  1138.         $data['dishes'] = [];
  1139.         $data['showPricePerKilogram'] = false;
  1140.         foreach ($dishes as $dish) {
  1141.             if (!array_key_exists($dish->id$extensions)) {
  1142.                 continue;
  1143.             }
  1144.             $offerExtension $extensions[$dish->id];
  1145.             $dish->productsPerCode $offerExtension->getProductsPerCode();
  1146.             $dish->offerPrice $offerExtension->getCurrentPrice(null$typePrice);
  1147.             $dish->sauceNeed $offerExtension->isSauceNeed();
  1148.             $dish->rating = (float) $offerCached->getRating();
  1149.             $dish->onlineCategories array_map(
  1150.                 static fn (OfferExtensionOnlineCategory $category): string => $category->getName(),
  1151.                 $offerExtension->getActiveOnlineCategories()->getValues(),
  1152.             );
  1153.             if (isset($dish->regularPrice) && $dish->regularPrice == 0) {
  1154.                 $dish->regularPrice $offerExtension->getPrice();
  1155.             }
  1156.             $dishSizeFull $dish->sizeFull;
  1157.             $dish->sizeFull '';
  1158.             $dish->pricePerKilogram null;
  1159.             $dish->itemCount = (int) $offerExtension->getComponentsCount();
  1160.             $dish->offerPrice = (float) PriceDeliveryType::calcDeliveryPickupPrice(
  1161.                 $offerExtension,
  1162.                 $typePrice,
  1163.                 $dish->regularPrice,
  1164.                 $dish->offerPrice,
  1165.             );
  1166.             if ($extensions[$dish->id]->getWeight()) {
  1167.                 $dish->sizeFull $offerExtension->getWeight() . ' г';
  1168.                 $dish->pricePerKilogram $this->calcPricePerKilogram(
  1169.                     $dish->offerPrice,
  1170.                     (float) $offerExtension->getWeight(),
  1171.                 );
  1172.                 $data['showPricePerKilogram'] = true;
  1173.             }
  1174.             if ($offerExtension->getComponentsCount()) {
  1175.                 if ($dish->sizeFull != '') {
  1176.                     $dish->sizeFull .= ', ';
  1177.                 }
  1178.                 $dish->sizeFull .= $offerExtension->getComponentsCount() . ' шт';
  1179.             }
  1180.             if ($dish->sizeFull === '') {
  1181.                 $dish->sizeFull $dishSizeFull;
  1182.             }
  1183.             if (null === $dish->pricePerKilogram && !empty($dish->sizeFull)) {
  1184.                 $dish->pricePerKilogram $this->calcPricePerKilogram(
  1185.                     $dish->offerPrice,
  1186.                     (float) $weightParserHelper->parse($dish->sizeFull),
  1187.                 );
  1188.                 $data['showPricePerKilogram'] = true;
  1189.             }
  1190.             $dish->originId $dish->id;
  1191.             $dish->position $offerExtension->getPosition() ?: CustomProductOfferSorter::DEFAULT_POSITION;
  1192.             $dish->id $offerExtension->getID();
  1193.             $dish->description str_replace("\n"'<br/>'$dish->description);
  1194.             $dish->imageURL null;
  1195.             if (isset($dish->images[count($dish->images) - 1])) {
  1196.                 if ($dish->images[count($dish->images) - 1] instanceof OfferExtensionMedia) {
  1197.                     $dish->imageURL $imageService->getImageURLCached($dish->images[count($dish->images) - 1], 5400);
  1198.                 } else if ($dish->images[count($dish->images) - 1]) {
  1199.                     $dish->imageURL $dish->images[count($dish->images) - 1]->imageUrl;
  1200.                 }
  1201.             }
  1202.             $key array_search($dish->idarray_column($dishPurchaseCount'id'), true);
  1203.             $dish->purchaseCount = isset($dishPurchaseCount[$key]['cnt']) && $key !== false $dishPurchaseCount[$key]['cnt'] : 0;
  1204.             $keyDay array_search($dish->idarray_column($dishPurchaseDayCount'id'), true);
  1205.             $dish->purchaseDayCount = isset($dishPurchaseDayCount[$keyDay]['cnt']) && $keyDay !== false
  1206.                 $dishPurchaseDayCount[$keyDay]['cnt']
  1207.                 : 0;
  1208.             $deliveryTime $productFastDeliveryService->findProductFastDelivery($offerCached$dish->originId);
  1209.             $dish->fastDeliveryTime CustomProductOfferSorter::DEFAULT_POSITION;
  1210.             if ($deliveryTime) {
  1211.                 $dish->fastDelivery $deliveryTime;
  1212.                 $dish->fastDeliveryTime = (int) $deliveryTime['time'];
  1213.             }
  1214.             if (isset($dish->variants) && count($dish->variants) > 0) {
  1215.                 $offerExtensionVariants array_reduce(
  1216.                     $extensions[$dish->originId]->getVariants()->getValues(),
  1217.                     static function (array $variantsOfferExtensionVariant $variant)
  1218.                     {
  1219.                         $variants[$variant->getPartnerID()] = $variant;
  1220.                         return $variants;
  1221.                     },
  1222.                     [],
  1223.                 );
  1224.                 foreach ($dish->variants as $key => $variant) {
  1225.                     if (!array_key_exists($variant->id$offerExtensionVariants)) {
  1226.                         unset($dish->variants[$key]);
  1227.                         continue;
  1228.                     }
  1229.                     /**
  1230.                      * @var $offerExtensionVariant OfferExtensionVariant
  1231.                      */
  1232.                     $offerExtensionVariant $offerExtensionVariants[$dish->variants[$key]->partnerId];
  1233.                     $dish->variants[$key]->id $offerExtensionVariant->getID();
  1234.                     if (PriceDeliveryType::PERCENT_PRICE === $offerExtension->getPriceDeliveryType()) {
  1235.                         $dish->variants[$key]->offerPrice = (float) PriceDeliveryType::calcDeliveryPickupPrice(
  1236.                             $offerExtension,
  1237.                             $typePrice,
  1238.                             $dish->variants[$key]->regularPrice,
  1239.                             $offerExtension->getCurrentPrice(null$typePrice),
  1240.                         );
  1241.                     }
  1242.                 }
  1243.             }
  1244.             $data['dishes'][] = $dish;
  1245.         }
  1246.         $data['dishes'] = $visibilityFilterService->filterInvisibleExtensions($data['dishes']);
  1247.         $sortType $request->query->get('sort'CustomProductOfferSorter::DEFAULT_CUSTOM_PRODUCT_SORT);
  1248.         $data['dishes'] = $productSorter->sort($data['dishes'], $sortType);
  1249.         $dishGroup $orderUtil->getDishGroups();
  1250.         $foodDishExtensionId $request->query->get('extension');
  1251.         if (null !== $foodDishExtensionId) {
  1252.             $dishKey array_search($foodDishExtensionId, \array_column($data['dishes'], 'id'));
  1253.             $foodCourtExtensionDish $data['dishes'][$dishKey];
  1254.             unset($data['dishes'][$dishKey]);
  1255.             array_unshift($data['dishes'], $foodCourtExtensionDish);
  1256.             if (count($dishGroup)) {
  1257.                 $category $isSushiHouse $foodCourtExtensionDish->parentGroup $foodCourtExtensionDish->groupName;
  1258.                 $keyDishGroup array_search($category$dishGroup);
  1259.                 $group $dishGroup[$keyDishGroup];
  1260.                 unset($dishGroup[$keyDishGroup]);
  1261.                 array_unshift($dishGroup$group);
  1262.             }
  1263.         }
  1264.         $data['topDishIDList'] = [];
  1265.         for ($i 0$i 3$i++) {
  1266.             if (isset($dishPurchaseCount[$i]['id'])) {
  1267.                 $data['topDishIDList'][] = $dishPurchaseCount[$i]['id'];
  1268.             }
  1269.         }
  1270.         if ($orderUtil::DISH_BY_GROUP) {
  1271.             $dishByGroupLabel = [];
  1272.             $dishByGroupContent = [];
  1273.             if ($isSushiHouse || $isSushiChefArts) {
  1274.                 foreach ($data['dishes'] as $dish) {
  1275.                     $dishByGroupContent[$dish->groupName][] = $dish;
  1276.                     if (!in_array($dish->parentGroup$dishByGroupLabel)) {
  1277.                         $dishByGroupLabel[$dish->groupName] = $dish->parentGroup;
  1278.                     }
  1279.                 }
  1280.                 if ($isSushiHouse) {
  1281.                     $dishByGroupContent $this->customSortDishByGroup($dishByGroupContent$dishGroup);
  1282.                 }
  1283.             }
  1284.             if ($isDominos) {
  1285.                 foreach ($data['dishes'] as $dish) {
  1286.                     $dish->parentGroup $dish->groupName;
  1287.                     $dishByGroupContent[$dish->groupName][] = $dish;
  1288.                     if (!in_array($dish->groupName$dishByGroupLabeltrue)) {
  1289.                         $dishByGroupLabel[$dish->groupName] = $dish->groupName;
  1290.                     }
  1291.                 }
  1292.             }
  1293.             $data['dishByGroup'] = [
  1294.                 'content' => $dishByGroupContent,
  1295.                 'label' => $dishByGroupLabel,
  1296.             ];
  1297.         }
  1298.         $dishGroup $foodByOnlineCategoriesBuilder->create($offerId,$data['dishes']);
  1299.         if (!empty($dishGroup)) {
  1300.             $data['dishByGroup'] = array_key_exists('dishByGroup'$data)
  1301.                 ? [
  1302.                     'content' => array_merge($dishGroup['content'], $data['dishByGroup']['content']),
  1303.                     'label' => array_merge($dishGroup['label'], $data['dishByGroup']['label']),
  1304.                 ]
  1305.                 : $dishGroup;
  1306.         }
  1307.         $options $isSushiVesla
  1308.             $orderUtil->getOptionsDBByShippingType(
  1309.                 $imageService,
  1310.                 \array_filter($allDishes, static fn (OfferExtension $offerExtension): bool => $offerExtension instanceof FoodOfferOptionExtension)
  1311.             )
  1312.             : $this->getOptions($imageService$offerCached$orderUtil0$isDominos $shippingType null);
  1313.         $data['options'] = $customProductOfferSorter->sort(
  1314.             $visibilityFilterService->filterInvisibleExtensions($options),
  1315.             CustomProductOfferSorter::DEFAULT_CUSTOM_PRODUCT_SORT,
  1316.         );
  1317.         $data['sortList'] = CustomProductOfferSorter::SORT_LIST;
  1318.         $data['isAvailableOnFood'] = $offerCached->isAvailableOnFood();
  1319.         $data['isAvailableOrderForToday'] = $shippingSchedulerService->availableOrderForToday($orderUtil$offerCached$typePrice);
  1320.         if ($isDominos) {
  1321.             $view CommonUtil::isMobileDevice($request) ? 'Slivki/mobile/delivery/delivery_teaser_reload_pickup.html.twig' 'Slivki/delivery/delivery_teaser_reload_pickup.html.twig';
  1322.         } else {
  1323.             $view CommonUtil::isMobileDevice($request) ? 'Slivki/mobile/delivery/delivery_teaser_reload.html.twig' 'Slivki/delivery/delivery_teaser_reload.html.twig';
  1324.         }
  1325.         return $this->render($view$data);
  1326.     }
  1327.     private function calcPricePerKilogram(float $offerPriceint $weight): ?float
  1328.     {
  1329.         if (!$weight) {
  1330.             return null;
  1331.         }
  1332.         return \round(self::KILOGRAM $offerPrice $weight2);
  1333.     }
  1334.     /** @Route("/expresspizza-orders") */
  1335.     public function expressPizzaOrdersAction(Request $request) {
  1336.         $offerID 282278;
  1337.         $pass '67380b434f';
  1338.         $objectCode '0017-4-009';
  1339.         if ($pass != $request->query->get('pass')) {
  1340.             return new Response('ERROR: Wrong password!');
  1341.         }
  1342.         $date = \DateTime::createFromFormat('U'$request->query->get('date'));
  1343.         if (!$date) {
  1344.             return new Response('ERROR: Wrong date format!');
  1345.         }
  1346.         $entityManager $this->getDoctrine()->getManager();
  1347.         /** @var Connection $connection */
  1348.         $connection $entityManager->getConnection();
  1349.         $sql "select"
  1350.                 " offer_order.id as order_id,"
  1351.                 " offer_order.paid_at as order_datetime,"
  1352.                 " offer_order.delivery_time as delivery_datetime,"
  1353.                 " user_address.name as client_name,"
  1354.                 " user_address.phone as client_phone,"
  1355.                 " user_address.pickup as pickup,"
  1356.                 " street.name as street_name,"
  1357.                 " user_address.house as house,"
  1358.                 " user_address.block as block,"
  1359.                 " user_address.entrance as entrance,"
  1360.                 " user_address.floor as floor,"
  1361.                 " user_address.doorphone as doorphone,"
  1362.                 " user_address.appartment as appartment,"
  1363.                 " offer_extension.partner_item_id as product_code,"
  1364.                 " offer_extension.name as product_name,"
  1365.                 " offer_order_details.items_count as items_count,"
  1366.                 " offer_extension.dish_delivery_price as delivery_price,"
  1367.                 " offer_extension.pickup_price as pickup_price,"
  1368.                 " offer_order.parameter_int_0 as payment_type,"
  1369.                 " offer_order.comment as comment,"
  1370.                 " coalesce(geo_location.pickup_point_partner_id, '$objectCode') as object_code"
  1371.             " from offer_order_details"
  1372.             " inner join offer_order on offer_order.id = offer_order_details.offer_order_id"
  1373.             " inner join user_address on offer_order.delivery_address_id = user_address.id"
  1374.             " left join street on user_address.street_id = street.id"
  1375.             " left join geo_location on user_address.geo_location_id = geo_location.id"
  1376.             " inner join offer_extension on offer_extension.id = offer_order_details.offer_extension_id"
  1377.             " where offer_order.offer_id = $offerID and offer_order.status > 0 and"
  1378.                 " offer_order.paid_at >= '" $date->format('Y-m-d H:i') . "'"
  1379.             " order by offer_order.id";
  1380.         $orderDetails $connection->executeQuery($sql)->fetchAll(\PDO::FETCH_ASSOC);
  1381.         $result = [];
  1382.         foreach ($orderDetails as $orderDetail) {
  1383.             $orderDateTime = new \DateTime($orderDetail['order_datetime']);
  1384.             $deliveryDateTime = new \DateTime();
  1385.             if ($orderDetail['delivery_datetime'] != 'Ближайшее') {
  1386.                 $deliveryDateTime = new \DateTime($orderDetail['delivery_datetime']);
  1387.             }
  1388.             $comment '';
  1389.             if (trim($orderDetail['entrance'])) {
  1390.                 $comment .= 'П' trim($orderDetail['entrance']) . ' ';
  1391.             }
  1392.             if (trim($orderDetail['floor'])) {
  1393.                 $comment .= 'Э' trim($orderDetail['floor']) . ' ';
  1394.             }
  1395.             if (trim($orderDetail['doorphone'])) {
  1396.                 $comment .= 'Д' trim($orderDetail['doorphone']) . ' ';
  1397.             }
  1398.             $paymentType '';
  1399.             switch ($orderDetail['payment_type']) {
  1400.                 case 1:
  1401.                     $paymentType 'Оплата: онлайн, ';
  1402.                     break;
  1403.                 case 2:
  1404.                     $paymentType 'Оплата: наличные, ';
  1405.                     break;
  1406.                 case 3:
  1407.                     $paymentType 'Оплата: терминал, ';
  1408.                     break;
  1409.                 case PaymentType::SLIVKI_PAY:
  1410.                     $paymentType 'Оплата: SlivkiPay, ';
  1411.                     break;
  1412.             }
  1413.             $comment .= $paymentType;
  1414.             $comment .= trim($orderDetail['comment']);
  1415.             $result[] = join(chr(9), [
  1416.                 $orderDetail['object_code'], // Код объекта
  1417.                 $orderDetail['order_id'], // Номер заказа
  1418.                 $orderDateTime->format('d.m.Y'), // Дата заказа
  1419.                 $orderDateTime->format('H:i'), // Время заказа
  1420.                 $deliveryDateTime->format('H:i'), // Изготовить к какому времени
  1421.                 $orderDetail['client_name'], // Имя клиента – Контакт
  1422.                 str_replace('+375''+375 '$orderDetail['client_phone']), // Контактный телефон.
  1423.                 $orderDetail['pickup'] ? 1// Тип получения: на месте (0) или доставка (1).
  1424.                 trim($orderDetail['street_name']) ?: ' '// Улица доставки
  1425.                 trim($orderDetail['house']) ?: ' '// Номер дома
  1426.                 trim($orderDetail['block']) ?: ' '// Корпус
  1427.                 trim($orderDetail['appartment']) ?: ' '// Квартира
  1428.                 ' '// Код группы
  1429.                 $orderDetail['product_code'], // Код товара
  1430.                 ' '// IDNT Номер выгрузки (оставляйте пустым)
  1431.                 $orderDetail['product_name'], // Название товара
  1432.                 $orderDetail['items_count'], // Количество
  1433.                 $orderDetail['pickup'] ? $orderDetail['pickup_price'] : $orderDetail['delivery_price'], // Цена
  1434.                 str_replace(["\r\n""\n"],' '$comment), // Примечание
  1435.             ]);
  1436.         }
  1437.         $result[] = chr(9) . 'OK';
  1438.         return new Response(join("\r\n"$result));
  1439.     }
  1440.     private function customSortDishByGroup(array $dishByGroupContent, array $sort): array
  1441.     {
  1442.         uasort($dishByGroupContent, function ($dishGroup1$dishGroup2) use ($sort) {
  1443.             if (!count($dishGroup1)) {
  1444.                 return 1;
  1445.             }
  1446.             if (!count($dishGroup2)) {
  1447.                 return -1;
  1448.             }
  1449.             $dishGroup1Key array_search($dishGroup1[0]->parentGroup$sort);
  1450.             $dishGroup2Key array_search($dishGroup2[0]->parentGroup$sort);
  1451.             return $dishGroup1Key $dishGroup2Key ? -1;
  1452.         });
  1453.         return $dishByGroupContent;
  1454.     }
  1455. }