src/Controller/IikoOrderController.php line 126

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