src/Controller/IikoOrderController.php line 107

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