src/Controller/IikoOrderController.php line 92

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