src/Controller/IikoOrderController.php line 99

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