src/Controller/IikoOrderController.php line 133

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