<?php
namespace App\V4Bundle\Controller;
use App\Enums\AdditionnalFeeAmountType;
use App\Enums\AdditionnalFeeType;
use App\Enums\AdditionalFeeRuleType;
use App\Entity\AdditionalFeeRule;
use App\Entity\AdditionalFees;
use App\Entity\Billing;
use App\Entity\PaymentBill;
use App\Entity\RestaurantConfig;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Annotation\Route;
use Doctrine\ORM\EntityManagerInterface;
use App\Entity\Food;
use App\Entity\Adresses;
use App\V4Bundle\Entity\Billing2;
use App\Entity\Client;
use App\V4Bundle\Entity\ClientBalance;
use App\Entity\Command;
use App\Entity\DeliveryRating;
use App\Entity\Livreur;
use App\V4Bundle\Entity\Loyalty;
use App\Entity\PackagingAdditionnalFeeBilling;
use App\V4Bundle\Entity\PayBonus;
use App\V4Bundle\Entity\PreOrderConfig;
use App\Entity\PromotionSchedule;
use App\Entity\RestoFraisSupp;
use App\V4Bundle\Entity\Schedule;
use App\Entity\Transaction;
use App\Entity\Voucher;
use App\V4Bundle\Entity\VoucherSubscription;
use App\Entity\WeatherRule;
use App\Entity\Zone;
use App\Entity\ZoneResto;
use DateTime;
use Doctrine\Common\Cache\Cache;
use Symfony\Component\Serializer\SerializerInterface;
use App\V4Bundle\Controller\BaseController;
use App\V4Bundle\Entity\DeliveryRating as EntityDeliveryRating;
use App\V4Bundle\Entity\Devices;
use App\V4Bundle\Entity\Employee;
use App\V4Bundle\Entity\NewUserPromotion;
use App\V4Bundle\Entity\Pack;
use App\V4Bundle\Entity\PreorderCommandDetails;
use App\V4Bundle\Entity\VoucherOwner;
use App\V4Bundle\Entity\VoucherTransaction;
use App\V4Bundle\Entity\VoucherUsage;
use Symfony\Component\Mime\Address;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
use App\V4Bundle\Words\Words;
use Doctrine\DBAL\Connection;
use Exception;
use Google\Service\SQLAdmin\Resource\Connect;
use Symfony\Contracts\HttpClient\HttpClientInterface;
use App\V4Bundle\Entity\Subscription;
use App\V4Bundle\Entity\SharedUser;
use App\V4Bundle\Entity\UserSusOrd;
use PhpParser\Node\Expr\Throw_;
use ProxyManager\Factory\RemoteObject\Adapter\JsonRpc;
use Symfony\Component\Validator\Constraints\Json;
use Throwable;
class CommandApiV4Controller extends BaseController
{
protected $tokenStorage;
protected $serializer;
protected $entityManager;
protected $passwordHasher;
protected $connection;
protected $http_client;
public function __construct(
SerializerInterface $serializer,
EntityManagerInterface $entityManager,
UserPasswordHasherInterface $passwordHasher,
TokenStorageInterface $tokenStorage,
Connection $connection,
HttpClientInterface $http_client
) {
$this->serializer = $serializer;
$this->entityManager = $entityManager;
$this->passwordHasher = $passwordHasher;
$this->tokenStorage = $tokenStorage;
$this->connection = $connection;
$this->http_client = $http_client;
}
/**
* @Route("mobile/api/command/billing/v5/get", name="user_mobile_v5_get_command_billing:", methods={"POST"})
*/
public function getCommandBillingWithVoucherV5Action(Request $request)
{
$currentToken = $this->get('security.token_storage')->getToken();
$user = $currentToken->getUser();
$id = $user->getId();
$data = json_decode($request->getContent(), true);
if (
isset($data["restaurant_id"]) &&
isset($data["shipping_address"]) &&
$data["restaurant_id"] != null &&
$data["shipping_address"] != null &&
count($data["food_command"]) != 0
) {
//check user's number of order so far
$nb_order = $this->checkNumberOfOrderFoUser($id);
if($nb_order >= 0 && $nb_order <= 5){
$data['voucher_id']=null;
$data['use_kaba_point']=false;
}
$restaurant = $this->entityManager->getRepository(RestaurantConfig::class)->find(intval($data["restaurant_id"]));
$address = $this->entityManager->getRepository(Adresses::class)->find(intval($data["shipping_address"]));
$configs_with_voucher = $this->configsWithVoucher($data, $currentToken, $user, $restaurant, $address);
/*
try {
$api_call = $this->http_client->request(
'POST',
'https://low-cod-36.deno.dev/relay',
[
'json' => ['userId' => $id],
'headers' => [
'Content-Type' => 'application/json',
'User-Agent' => 'PostmanRuntime/7.32.3'
],
'timeout' => 10,
'max_duration' => 10,
'http_version' => '1.1',
]
);
$res_api = $api_call->getContent(false);
$apiData = json_decode($res_api, true);
if ($apiData) {
$data['user_abonnement'] = $apiData;
}
} catch (\Throwable $e) {
error_log("API proxy failed: ".$e->getMessage());
$data['user_abonnement'] = null;
}
*/
$res = [];
$res["promotion_pricing"] = $this->getPromotionPricing($data, $configs_with_voucher);
$res["command_pricing"] = $this->calculate_command_pricing($data["food_command"]);
$res["account_balance"] = $this->getBalance($id);
$res["distance"] = $this->getDistance($restaurant->getLocation(), $address->getLocation());
$res["shipping_pricing"] = $this->calculate_shipping_price($res["distance"], $currentToken);
$res["kaba_point"] = $this->get_kaba_point($id, $res['shipping_pricing']);
$res['is_new_user']=false;
$res["promotion_shipping_pricing"] = $this->getPromotionOnShipping($restaurant, $data, $address, $currentToken, $user, $configs_with_voucher, $res['shipping_pricing'], $res['kaba_point']);
//Subscription
try{
if(isset($data['user_abonnement']) &&$data['user_abonnement']!=null){
$res["promotion_shipping_pricing"] = $this->applySubscriptionOnOrder($res['distance'], $data['user_abonnement'], $res['promotion_shipping_pricing']);
$res['has_subscription'] = $res["promotion_shipping_pricing"]==0?true:false;
}
}catch(Throwable $e){}
if(!isset($data['user_abonnement'])){
try{
if($nb_order >= 0 && $nb_order <= 5){
$promotion = $this->entityManager->getRepository(NewUserPromotion::class)->findAll();
if($promotion){
if($promotion[0]->getIsActive()==true){
$promotion_for_new_user = $promotion[0] ->getValue();
$res["promotion_shipping_pricing"] = $res['shipping_pricing']-$promotion_for_new_user;
$res['is_new_user']=true;
}else{
}
}
}
}catch(Throwable $e){}
}
$res['additional_fees'] = $this->getAdditionalFeesPrice($data['food_command'], $res['command_pricing'], $res['shipping_pricing'], $address, $restaurant);
$res['additional_fees_total_price'] = $this->getAdditionalFeesTotalPricing($res["additional_fees"]);
$res["total_pricing"] = $this->get_total_pricing($res, $configs_with_voucher, $data, $id, $res["kaba_point"]);
$res['total_normal_pricing'] = intval($res["command_pricing"]) + intval($res["shipping_pricing"]) + intval($res['additional_fees_total_price']);
$res["remise"] = $this->get_remise($id, $res, $data, $res["kaba_point"]);
$res["pay_at_delivery"] = $restaurant->getPayAtDelivery();
$res["prepayed"] = $restaurant->getPrepayed();
$res["trustful"] = $user->getTrustful();
$res["max_pay"] = intval($restaurant->getMaxPay());
$res["cooking_time"] = (int)$restaurant->getCookingTime();
$res['eligible_vouchers'] = $this->getUserEligibleVoucher($id);
$res["out_of_range"] = $this->isOutOfRange($res['distance']);
if(isset($data['user_abonnement'])){
$res['subscription']= $data['user_abonnement'];
}
$additional_fee = $this->entityManager->getRepository(AdditionalFees::class)->findOneBy(["fee_type" => AdditionnalFeeType::COMMISSION_FEE]);
try{
$commission_additional_fee = $this->entityManager->getRepository(RestoFraisSupp::class)->findOneBy(["resto_id" => $data['restaurant_id'], "additional_fee_id" => $additional_fee->getId()]);
if($commission_additional_fee){
$isEnabled = $commission_additional_fee->isFeeEnabled();
}
}catch(Throwable $e){
$isEnabled = false;
}
if ($isEnabled == true) {
$sql = 'SELECT * FROM devices WHERE id = :id';
$device = $this->connection->fetchAssociative($sql, ['id' => $user->getDeviceId()]);
$push_token = $device['push_token'];
try{
$notif = [];
$notif["error"] = 0;
$notif["message"] = "nothing";
$notif["data"] = [];
$notif["data"]["notification"] = [];
$notif["data"]["notification"]["title"] = "ℹ️ Frais supplémentaires";
$notif["data"]["notification"]["body"] = "Des frais supplémentaires sont appliqués chez ce marchand";
$notif["data"]["notification"]["image_link"] = '';
$notif["data"]["notification"]["destination"] = [];
$notif["data"]["notification"]["destination"]["type"] = 200;
$notif["data"]["notification"]["destination"]["priority"] = 2;
$notif["data"]["notification"]["destination"]["amount"] = intval(0);
$notif["data"]["notification"]["destination"]["is_out_of_app"] = intval(0);
$notif["data"]["notification"]["destination"]["product_id"] = intval(0);
// $this->sendNotificationToDeviceV2([$push_token],"Des frais supplémentaires sont appliqués chez ce marchand",$notif,1);
}catch(Throwable $e){
}
}
return new Response($this->serializer->serialize($this->okResponseBlob($res), 'json'));
} else {
return new Response($this->serializer->serialize($this->errorResponseBlob('Invalid parameter'), 'json'));
}
}
/**
* @Route("mobile/api/command/v5-old/create", name="mobile_api_command_v5_old_create", methods={"POST"})
*/
public function createCommandWithVoucherV5OldAction(Request $request)
{
$currentToken = $this->get('security.token_storage')->getToken();
$user = $currentToken->getUser();
$id = $user->getId();
$data = json_decode($request->getContent(), true);
$saved_data = json_decode($request->getContent(), true);
$is_preorder = 0;
$is_voucher = 0;
/*try {
$api_call = $this->http_client->request(
'POST',
'https://huge-bear-80.deno.dev/relay',
[
'json' => ['userId' => $id],
'headers' => [
'Content-Type' => 'application/json',
'User-Agent' => 'PostmanRuntime/7.32.3'
],
'timeout' => 10,
'max_duration' => 10,
'http_version' => '1.1',
]
);
$res_api = $api_call->getContent(false);
$apiData = json_decode($res_api, true);
if ($apiData) {
$saved_data['user_abonnement'] = $apiData;
}
} catch (\Throwable $e) {
error_log("API proxy failed: ".$e->getMessage());
$saved_data['user_abonnement'] = null;
}
*/
//check user's number of order so far
$nb_order = $this->checkNumberOfOrderFoUser($id);
if($nb_order >= 0 && $nb_order <= 5){
$data['voucher_id']=null;
$data['use_kaba_point']=false;
}
$deliveryRange = [];
if (isset($data["pre_order"]) && $data["pre_order"] == 1 && isset($data["pre_order_hour"]) && $data["pre_order_hour"] != null) {
$deliveryRange = array('start' => $data["pre_order_hour"]["start"], 'end' => $data["pre_order_hour"]["end"]);
$is_preorder = 1;
}
$restaurantId = $this->getRestaurantId($data["food_command"]);
$adress = $this->getAdress($data["shipping_address"]);
if ($restaurantId == -1)
return new Response($this->serializer->serialize($this->errorResponseBlob(null, 301), 'json'));
if ($adress == -1)
return new Response($this->serializer->serialize($this->errorResponseBlob(null, 304), 'json'));
$voucher_id = null;
if (isset($data["voucher_id"]) && $data["voucher_id"] != null) {
$voucher_id = intval($data["voucher_id"]);
$is_voucher = 1;
}
$use_kaba_point = false;
if (isset($data["use_kaba_point"]) && $data["use_kaba_point"] != null)
$use_kaba_point = $data["use_kaba_point"];
$command_details = $this->getCommandDetails2($data["food_command"], $restaurantId, $adress, $is_preorder, $voucher_id, $id, $use_kaba_point);
$data["food_command"] = $command_details["foods"];
$restaurant = $this->entityManager->getRepository(RestaurantConfig::class)->find($restaurantId);
$details = "Achat de " . " " . $command_details["food_litteral"] . " " . "à" . " " . $restaurant->getName();
if (!($this->checkValidUser($id)))
return new Response($this->serializer->serialize($this->errorResponseBlob(null, 306), 'json'));
$master_key = md5('kabapeur');
if (!(isset($data['master_key']) && $data['master_key'] == $master_key)) {
if (!($this->checkTransactionPassword($id, $data["transaction_password"])))
return new Response($this->serializer->serialize($this->errorResponseBlob(null, 300), 'json'));
}
$isFirstCommandBonusApply = $this->isFirstCommandBonusApply($id);
if ($isFirstCommandBonusApply['response'] && $isFirstCommandBonusApply['type'] == '1') {
$haveBillingDiscount = true;
} else {
$haveBillingDiscount = $command_details["haveBillingDiscount"];
}
$client = $this->entityManager->getRepository(Client::class)->find($id);
$command = new Command();
$em = $this->entityManager;
$word = false;
while ($word == false) {
$word = $this->generateWord();
}
$command->setPassPhrase($word);
if ($command_details["is_kaba_point_used"]) {
$kabaPointTransaction = $this->debitKabaPointAccount($id, intval($command_details["kaba_point_used_amount"]));
if ($kabaPointTransaction['state']) {
$command->setKabaPoint(intval($kabaPointTransaction["transaction"]["id"]));
$command->setKabaPointAmount(intval($command_details["kaba_point_used_amount"]));
} else {
$command_details["food_billing"] += intval($command_details["kaba_point_used_amount"]);
$command_details["email_shipping_pricing"] += intval($command_details["kaba_point_used_amount"]);
$command_details["phoneNumber_shipping_pricing"] += intval($command_details["kaba_point_used_amount"]);
}
}
$is_subscription_discount_allowed =false;
$realyShippingPrice = $isFirstCommandBonusApply['response'] && $isFirstCommandBonusApply['type'] == '1' ? 0 : $command_details["food_billing"];
$command->setFoodCommand($data["food_command"]);
$command->setPreOrder($is_preorder);
$command->setPayAtDelivery($data["pay_at_delivery"]);
$command->setClientId($id);
$command->setClient($user);
$command->setState(-1);
$command->setRestaurantId($restaurantId);
$command->setRestaurant($restaurant);
$command->setShippingAddress($adress);
$command->setHaveBillingDiscount($haveBillingDiscount);
$command->setExtraShippingPricing($command_details["extra_shipping_pricing"] > $realyShippingPrice ? 0 : $command_details["extra_shipping_pricing"]);
$command->setBaseShippingPricing($command_details["base_shipping_pricing"]);
$command->setEmailAccountShippingPricing($command_details["email_shipping_pricing"]);
$command->setPhoneNumberAccountShippingPricing($command_details["phoneNumber_shipping_pricing"]);
$command->setShippingPricing($realyShippingPrice);
//Subscription
try{
if(isset($saved_data['user_abonnement'])){
$promotion_shipping_pricing = $this->applySubscriptionOnOrder($this->getDistance($restaurant->getLocation(), $adress['location']),$saved_data['user_abonnement'],$command->getShippingPricing());
if($promotion_shipping_pricing==0){
$command->setHaveBillingDiscount(true);
$is_subscription_discount_allowed = true;
$command->setShippingPricing(0);
}else{
$command->setHaveBillingDiscount(false);
}
}
}catch(Throwable $e){
}
if(!isset($saved_data['user_abonnement'])){
try{
if($nb_order >= 0 && $nb_order <= 5){
$promotion = $this->entityManager->getRepository(NewUserPromotion::class)->findAll();
if($promotion){
if($promotion[0] ->getIsActive()==true){
$promotion_for_new_user = $promotion[0] ->getValue();
$command->setHaveBillingDiscount(true);
$command->setShippingPricing($realyShippingPrice-$promotion_for_new_user);
}
}
}
}catch(Throwable $e){
}
}
$command->setStartTime(date('Y-m-d H:i:s'));
$command->setStartDate(date('Y-m-d'));
$command->setLastUpdate(date('Y-m-d H:i:s'));
$client_commands = $this->entityManager->getRepository(Command::class)->findBy([
'clientId' => $id,
]);
if (count($client_commands) > 0)
$command->setIsFirstOrder(false);
else
$command->setIsFirstOrder(true);
if ($command_details['is_voucher_used'])
$command->setHasVoucher(true);
else
$command->setHasVoucher(false);
if (isset($data["infos"]) && $data["infos"] != null)
$command->setInfos($data["infos"]);
$now = new \DateTime();
$twoMinutesAgo = (clone $now)->modify('-2 minute');
$qb = $this->entityManager->getRepository(Command::class)->createQueryBuilder('c')
->where('c.clientId = :clientId')
->andWhere('c.restaurantId = :restaurantId')
->andWhere(is_array($data['food_command'])
? 'c.foodCommand IN (:foodCommand)'
: 'c.foodCommand = :foodCommand'
)
->andWhere('c.startTime BETWEEN :start AND :now')
->setParameter('clientId', $id)
->setParameter('restaurantId', $restaurantId)
->setParameter('foodCommand', $data['food_command'])
->setParameter('start', $twoMinutesAgo->format('Y-m-d H:i:s'))
->setParameter('now', $now->format('Y-m-d H:i:s'));
$existingCommand = $qb->getQuery()->getOneOrNullResult();
if ($existingCommand) {
$jsonData = json_encode([
"food_command" => $command->getFoodCommand(),
"restaurant_id" => $restaurant->getId(),
"shipping_address" => $adress['id'],
"voucher_id" => $voucher_id,
"use_kaba_point" => $use_kaba_point,
]);
$Billingrequest = new Request(
[],
[],
[],
[],
[],
['CONTENT_TYPE' => 'application/json'],
$jsonData
);
$getBilling = $this->getCommandBillingWithVoucherAction($Billingrequest);
$getBillingContent = $getBilling->getContent();
$getBillingData = json_decode($getBillingContent, true);
$this->createPaymentBill($getBillingData['data'], $command->getId());
return new JsonResponse($getBillingData, 200);
}
$em->persist($command);
$em->flush();
if($is_subscription_discount_allowed==true){
$command_details["with_promo"]["total"] = $command_details["with_promo"]["total"]-$realyShippingPrice;
$command_details["with_promo"]["billing"] = 0;
$command_details["without_promo"]["pre_order"]["total"] =$command_details["without_promo"]["pre_order"]["total"] -$realyShippingPrice;
$command_details["without_promo"]["pre_order"]["billing"] = 0;
}
if ($data["device"]["push_token"] != null) {
$device = $this->entityManager->getRepository(Devices::class)->findOneBy([
'pushToken' => $data["device"]["push_token"]
]);
if ($device != null) {
$client->setDeviceId($device->getId());
} else {
$device_id = $this->createDevice($data["device"], 1);
$client->setDeviceId($device_id);
}
}
$temp_foodPricing = 0;
$tem_shippingPricing = 0;
if ($data["pay_at_delivery"] == true) {
if ($this->restaurantAcceptPayAtArrival($restaurantId)) {
if ($command_details['is_voucher_used'] && $is_subscription_discount_allowed==false) {
$pay_at_delivery_total_price = intval($command_details["voucher_pricing"]["total_pricing"]);
if ($isFirstCommandBonusApply['response']) {
$pay_at_delivery_total_price -= intval($command_details["voucher_pricing"]["shipping_pricing"]);
$temp_foodPricing = $pay_at_delivery_total_price;
$tem_shippingPricing = intval($command_details["voucher_pricing"]["shipping_pricing"]);
}
} else {
$pay_at_delivery_total_price = intval($command_details["with_promo"]["total"]);
if ($isFirstCommandBonusApply['response']) {
$pay_at_delivery_total_price -= intval($command_details["with_promo"]["billing"]);
$temp_foodPricing = $pay_at_delivery_total_price;
$tem_shippingPricing = intval($command_details["with_promo"]["billing"]);
}
}
$res = $this->debitClientAction($id, $pay_at_delivery_total_price, $details, 0, $command->getId());
if ($res) {
$command->setState(0);
$em->flush();
$isFirstCommandBonusApply['response'] ? $this->applyFirstCommandProccess($id, $command->getId(), $temp_foodPricing, $tem_shippingPricing) : '';
} else {
$em->remove($command);
$em->flush();
}
} else {
$em->remove($command);
$em->flush();
return new Response($this->serializer->serialize($this->errorResponseBlob(null, 305), 'json'));
}
} else if ($data["pay_at_delivery"] == false) { // PREPAY
if (!$this->restaurantAcceptPrepay($restaurantId)) {
$em->remove($command);
$em->flush();
return new Response($this->serializer->serialize(
$this->errorResponseBlob(null, 308),
'json'
));
}
// =========================
// ===== PRE ORDER =========
// =========================
if ($is_preorder == 1) {
if (!$this->restaurantAcceptPreOrder($restaurantId, $deliveryRange)) {
$em->remove($command);
$em->flush();
return new Response($this->serializer->serialize(
$this->errorResponseBlob(null, 307),
'json'
));
}
// 🔥 TOTAL DÉJÀ FINAL
$preorderTotalPrice = $command_details['is_voucher_used']
? intval($command_details["voucher_pricing"]["total_pricing"])
: intval($command_details["without_promo"]["pre_order"]["total"]);
// 🎁 FIRST COMMAND BONUS (shipping déjà à 0 si subscription)
if ($isFirstCommandBonusApply['response']) {
if ($command_details['is_voucher_used']) {
$tem_shippingPricing = intval($command_details["voucher_pricing"]["shipping_pricing"]);
} else {
$tem_shippingPricing = intval($command_details["without_promo"]["pre_order"]["billing"]);
}
$preorderTotalPrice -= $tem_shippingPricing;
$temp_foodPricing = $preorderTotalPrice;
}
// 💳 DEBIT
if ($this->debitClientAction($id, $preorderTotalPrice, $details, 1, $command->getId())) {
$command->setState(0);
$em->flush();
if ($isFirstCommandBonusApply['response']) {
$this->applyFirstCommandProccess(
$id,
$command->getId(),
$temp_foodPricing,
$tem_shippingPricing
);
}
} else {
$em->remove($command);
$em->flush();
return new Response($this->serializer->serialize(
$this->errorResponseBlob(null, 305),
'json'
));
}
// =========================
// ===== NORMAL ORDER ======
// =========================
} else {
// 🔥 TOTAL DÉJÀ FINAL
$orderTotalPrice = $command_details['is_voucher_used']
? intval($command_details["voucher_pricing"]["total_pricing"])
: intval($command_details["with_promo"]["total"]);
// 🎁 FIRST COMMAND BONUS (shipping déjà à 0 si subscription)
if ($isFirstCommandBonusApply['response']) {
if ($command_details['is_voucher_used']) {
$tem_shippingPricing = intval($command_details["voucher_pricing"]["shipping_pricing"]);
} else {
$tem_shippingPricing = intval($command_details["with_promo"]["billing"]);
}
$orderTotalPrice -= $tem_shippingPricing;
$temp_foodPricing = $orderTotalPrice;
}
// 💳 DEBIT
if ($this->debitClientAction($id, $orderTotalPrice, $details, 1, $command->getId())) {
$command->setState(0);
$em->flush();
if ($isFirstCommandBonusApply['response']) {
$this->applyFirstCommandProccess(
$id,
$command->getId(),
$temp_foodPricing,
$tem_shippingPricing
);
}
} else {
// ===== MASTER KEY FALLBACK =====
if (isset($data['master_key']) && $data['master_key'] == $master_key) {
if ($client->getTrustful() == 0 || $this->isEmailAccount($client)) {
$em->remove($command);
$em->flush();
return new Response($this->serializer->serialize(
$this->errorResponseBlob(null, 309),
'json'
));
}
$_res = $this->debitClientAction(
$id,
$orderTotalPrice,
$details,
0,
$command->getId()
);
if ($_res) {
$command->setState(0);
$command->setPayAtDelivery(true);
$em->flush();
if ($isFirstCommandBonusApply['response']) {
$this->applyFirstCommandProccess(
$id,
$command->getId(),
$temp_foodPricing,
$tem_shippingPricing
);
}
} else {
$em->remove($command);
$em->flush();
return new Response($this->serializer->serialize(
$this->errorResponseBlob(null, 308),
'json'
));
}
} else {
$em->remove($command);
$em->flush();
return new Response($this->serializer->serialize(
$this->errorResponseBlob(null, 308),
'json'
));
}
}
}
}
if ($is_preorder == 1) {
$preorder_detail = new PreorderCommandDetails();
$preorder_detail->setCommandId($command->getId());
$preorder_detail->setStart($deliveryRange["start"]);
$preorder_detail->setEnd($deliveryRange["end"]);
$preorder_detail->setDiscount($command_details["discount"]);
$preorder_detail->setPrepayed(1);
$preorder_detail->setCreatedAt(strtotime(date("Y-m-d H:i:s")));
$em->persist($preorder_detail);
$em->flush();
}
if ($is_voucher == 1 && ($command_details["voucher_pricing"]["valid"] == true || $command_details["is_voucher_used"])) {
$voucher_id = intval($data["voucher_id"]);
$voucher = $this->entityManager->getRepository(Voucher::class)->find($voucher_id);
$voucher_subs = $this->entityManager->getRepository(VoucherSubscription::class)->findOneBy([
'userId' => $id,
'voucherId' => $voucher_id,
]);
if ($voucher_subs != null) {
$usage_count = count($this->entityManager->getRepository(VoucherUsage::class)->findBy([
'userId' => $id,
'voucherId' => $voucher_id,
'isReallyUsed' => 1
]));
if ($voucher != null) {
if (($usage_count + 1) >= intval($voucher->getUseCount())) {
$voucher_subs->setState(1);
}
$voucher_subs->setUseCount($usage_count + 1);
$new_usage = new VoucherUsage();
$new_usage->setUserId($id);
$new_usage->setVoucherId($voucher_id);
$new_usage->setCommandId($command->getId());
$new_usage->setIsReallyUsed(1);
$new_usage->setCreatedAt(strtotime(date('Y-m-d H:i:s')));
$em->persist($new_usage);
$reward = 0;
$check_voucher_owners = $this->entityManager->getRepository(VoucherOwner::class)->findBy([
'voucherId' => $voucher_id
]);
if ($check_voucher_owners != null) {
if ($command_details["voucher_pricing"]["owner"]["is_rewarded"] == 1) {
if ($command_details["voucher_pricing"]["owner"]["reward_on_food"] == 0) {
$reward = $command_details["voucher_pricing"]["owner"]["reward_cash_value"];
} else {
$reward = $command_details["voucher_pricing"]["owner"]["reward_on_food"] + $command_details["voucher_pricing"]["owner"]["reward_on_billing"];
}
}
if ($reward > 0) {
foreach ($check_voucher_owners as $owner) {
$voucher_transaction = new VoucherTransaction();
$voucher_transaction->setUserId($owner->getUserId());
$voucher_transaction->setVoucherId($voucher_id);
$voucher_transaction->setValue($reward);
$voucher_transaction->setType(1);
$voucher_transaction->setCommandId($command->getId());
$voucher_transaction->setState(0);
$voucher_transaction->setCreatedAt(strtotime(date('Y-m-d H:i:s')));
$voucher_transaction->setUpdatedAt(strtotime(date('Y-m-d H:i:s')));
$em->persist($voucher_transaction);
}
}
}
}
}
$em->flush();
}
if ($restaurant->getDeviceId() != null) {
$device = $this->entityManager->getRepository(Devices::class)->find($restaurant->getDeviceId());
if ($device != null && $device->getPushToken() != '') {
$devices_array = [];
array_push($devices_array, $device->getPushToken());
$devices_resto =[];
$devices_resto = [];
$device_resto = $this->entityManager->getRepository(Devices::class)->find($restaurant->getDeviceId());
if ($device_resto != null && $device_resto->getPushToken() != null)
array_push($devices_resto, $device_resto->getPushToken());
$notif = [];
$notif["error"] = 0;
$notif["message"] = "nothing";
$notif["data"] = [];
$notif["data"]["notification"] = [];
$notif["data"]["notification"]["title"] = "Kaba";
$notif["data"]["notification"]["body"] = "Vous avez une nouvelle commande !";
$notif["data"]["notification"]["image_link"] = '';
$notif["data"]["notification"]["destination"] = [];
$notif["data"]["notification"]["destination"]["type"] = 154;
$notif["data"]["notification"]["destination"]["priority"] = 300;
$notif["data"]["notification"]["destination"]["product_id"] = intval($command->getId());
$notif["data"]["notification"]["destination"]["is_out_of_app"] = intval(0);
try {
$this->sendNotificationToDeviceV2($devices_resto, "Vous avez une nouvelle commande !", $notif, 2);
} catch (\Throwable $e) {
}
}
}
$jsonData = json_encode([
"food_command" => $command->getFoodCommand(),
"restaurant_id" => $restaurant->getId(),
"shipping_address" => $adress['id'],
"voucher_id" => $voucher_id,
"use_kaba_point" => $use_kaba_point,
]);
$Billingrequest = new Request(
[],
[],
[],
[],
[],
['CONTENT_TYPE' => 'application/json'],
$jsonData
);
$getBilling = $this->getCommandBillingWithVoucherAction($Billingrequest);
$getBillingContent = $getBilling->getContent();
$getBillingData = json_decode($getBillingContent, true);
$this->createPaymentBill($getBillingData['data'], $command->getId());
$client_balance = $this->getBalance($id);
$data = [];
$data["balance"] = $client_balance;
$data["pre_order"] = $is_preorder;
$data["pre_order_hour"] = $deliveryRange;
$data["voucher_data"] = $command_details["voucher_pricing"];
$response["error"] = 0;
$response["code"] = 200;
$response["message"] = "200 OK";
$response["data"] = $data;
$pusher = $this->getPusher();
$message = [];
$message['id'] = $command->getId();
$message['state'] = $command->getState();
$pusher->trigger($this->getParameter('PUSHER_APP_CHANNEL'), BaseController::NEW_COMMAND, $message);
$sql = 'SELECT * FROM devices WHERE id = :id';
$device = $this->connection->fetchAssociative($sql, ['id' => $user->getDeviceId()]);
return new Response($this->serializer->serialize($this->okResponseBlob(['command_id'=>$command->getId(),'total_price'=>$command_details["with_promo"]["total"]]), 'json'));
}
/**
* @Route("mobile/api/command/v5/create", name="mobile_api_command_v5_create", methods={"POST"})
*/
public function createCommandWithVoucherV5Action(Request $request)
{
$currentToken = $this->get('security.token_storage')->getToken();
$user = $currentToken->getUser();
$id = $user->getId();
$data = json_decode($request->getContent(), true);
$saved_data = json_decode($request->getContent(), true);
$is_preorder = 0;
$is_voucher = 0;
/*
if (
!empty($data['user_abonnement']) &&
!empty($data['user_abonnement']['pack']) &&
!empty($data['user_abonnement']['pack']['id'])
) {
try {
$api_call = $this->http_client->request(
'POST',
'https://low-cod-36.deno.dev/relay',
[
'json' => ['userId' => $id],
'headers' => [
'Content-Type' => 'application/json',
'User-Agent' => 'PostmanRuntime/7.32.3'
],
'timeout' => 10,
'max_duration' => 10,
'http_version' => '1.1',
]
);
$res_api = $api_call->getContent(false);
$apiData = json_decode($res_api, true);
if ($apiData) {
$saved_data['user_abonnement'] = $apiData;
}
} catch (\Throwable $e) {
error_log("API proxy failed: ".$e->getMessage());
$saved_data['user_abonnement'] = null;
}
}
*/
//check user's number of order so far
$nb_order = $this->checkNumberOfOrderFoUser($id);
if($nb_order >= 0 && $nb_order <= 5){
$data['voucher_id']=null;
$data['use_kaba_point']=false;
}
$deliveryRange = [];
if (isset($data["pre_order"]) && $data["pre_order"] == 1 && isset($data["pre_order_hour"]) && $data["pre_order_hour"] != null) {
$deliveryRange = array('start' => $data["pre_order_hour"]["start"], 'end' => $data["pre_order_hour"]["end"]);
$is_preorder = 1;
}
$restaurantId = $this->getRestaurantId($data["food_command"]);
$adress = $this->getAdress($data["shipping_address"]);
if ($restaurantId == -1)
return new Response($this->serializer->serialize($this->errorResponseBlob(null, 301), 'json'));
if ($adress == -1)
return new Response($this->serializer->serialize($this->errorResponseBlob(null, 304), 'json'));
$voucher_id = null;
if (isset($data["voucher_id"]) && $data["voucher_id"] != null) {
$voucher_id = intval($data["voucher_id"]);
$is_voucher = 1;
}
$use_kaba_point = false;
if (isset($data["use_kaba_point"]) && $data["use_kaba_point"] != null)
$use_kaba_point = $data["use_kaba_point"];
$command_details = $this->getCommandDetails2($data["food_command"], $restaurantId, $adress, $is_preorder, $voucher_id, $id, $use_kaba_point);
$data["food_command"] = $command_details["foods"];
$restaurant = $this->entityManager->getRepository(RestaurantConfig::class)->find($restaurantId);
$details = "Achat de " . " " . $command_details["food_litteral"] . " " . "à" . " " . $restaurant->getName();
if (!($this->checkValidUser($id)))
return new Response($this->serializer->serialize($this->errorResponseBlob(null, 306), 'json'));
$master_key = md5('kabapeur');
if (!(isset($data['master_key']) && $data['master_key'] == $master_key)) {
if (!($this->checkTransactionPassword($id, $data["transaction_password"])))
return new Response($this->serializer->serialize($this->errorResponseBlob(null, 300), 'json'));
}
$isFirstCommandBonusApply = $this->isFirstCommandBonusApply($id);
if ($isFirstCommandBonusApply['response'] && $isFirstCommandBonusApply['type'] == '1') {
$haveBillingDiscount = true;
} else {
$haveBillingDiscount = $command_details["haveBillingDiscount"];
}
$client = $this->entityManager->getRepository(Client::class)->find($id);
$command = new Command();
$em = $this->entityManager;
$word = false;
while ($word == false) {
$word = $this->generateWord();
}
$command->setPassPhrase($word);
if ($command_details["is_kaba_point_used"]) {
$kabaPointTransaction = $this->debitKabaPointAccount($id, intval($command_details["kaba_point_used_amount"]));
if ($kabaPointTransaction['state']) {
$command->setKabaPoint(intval($kabaPointTransaction["transaction"]["id"]));
$command->setKabaPointAmount(intval($command_details["kaba_point_used_amount"]));
} else {
$command_details["food_billing"] += intval($command_details["kaba_point_used_amount"]);
$command_details["email_shipping_pricing"] += intval($command_details["kaba_point_used_amount"]);
$command_details["phoneNumber_shipping_pricing"] += intval($command_details["kaba_point_used_amount"]);
}
}
$is_subscription_discount_allowed =false;
$realyShippingPrice = $isFirstCommandBonusApply['response'] && $isFirstCommandBonusApply['type'] == '1' ? 0 : $command_details["food_billing"];
$command->setFoodCommand($data["food_command"]);
$command->setPreOrder($is_preorder);
$command->setPayAtDelivery($data["pay_at_delivery"]);
$command->setClientId($id);
$command->setClient($user);
$command->setState(-1);
$command->setRestaurantId($restaurantId);
$command->setRestaurant($restaurant);
$command->setShippingAddress($adress);
$command->setHaveBillingDiscount($haveBillingDiscount);
$command->setExtraShippingPricing($command_details["extra_shipping_pricing"] > $realyShippingPrice ? 0 : $command_details["extra_shipping_pricing"]);
$command->setBaseShippingPricing($command_details["base_shipping_pricing"]);
$command->setEmailAccountShippingPricing($command_details["email_shipping_pricing"]);
$command->setPhoneNumberAccountShippingPricing($command_details["phoneNumber_shipping_pricing"]);
$command->setShippingPricing($realyShippingPrice);
if (isset($data["infos"]) && $data["infos"] != null)
$command->setInfos($data["infos"]);
//Subscription
try{
if(isset($saved_data['user_abonnement']) && $saved_data['user_abonnement']!=null){
$promotion_shipping_pricing = $this->applySubscriptionOnOrder($this->getDistance($restaurant->getLocation(), $adress['location']),$saved_data['user_abonnement'],$command->getShippingPricing());
if($promotion_shipping_pricing==0){
$command->setHaveBillingDiscount(true);
$is_subscription_discount_allowed = true;
$command->setShippingPricing(0);
}else{
$command->setHaveBillingDiscount(false);
}
}
}catch(Throwable $e){
error_log($e->getMessage());
error_log($e->getTraceAsString());
}
if(!isset($saved_data['user_abonnement'])){
try{
if($nb_order >= 0 && $nb_order <= 5){
$promotion = $this->entityManager->getRepository(NewUserPromotion::class)->findAll();
if($promotion){
if($promotion[0] ->getIsActive()==true){
$promotion_for_new_user = $promotion[0] ->getValue();
$command->setHaveBillingDiscount(true);
$command->setShippingPricing($realyShippingPrice-$promotion_for_new_user);
}
}
}
}catch(Throwable $e){
error_log($e->getMessage());
error_log($e->getTraceAsString());
}
}
$command->setStartTime(date('Y-m-d H:i:s'));
$command->setStartDate(date('Y-m-d'));
$command->setLastUpdate(date('Y-m-d H:i:s'));
$client_commands = $this->entityManager->getRepository(Command::class)->findBy([
'clientId' => $id,
]);
if (count($client_commands) > 0)
$command->setIsFirstOrder(false);
else
$command->setIsFirstOrder(true);
if ($command_details['is_voucher_used'])
$command->setHasVoucher(true);
else
$command->setHasVoucher(false);
if($restaurant){
if($restaurant->getAutoAccept()==true){
$command->setIsAutoOrder(true);
}
}
$em->persist($command);
$em->flush();
try{
if ($data["device"]["push_token"] != null) {
$device = $this->entityManager->getRepository(Devices::class)->findOneBy([
'pushToken' => $data["device"]["push_token"]
]);
if ($device != null) {
$client->setDeviceId($device->getId());
} else {
$device_id = $this->createDevice($data["device"], 1);
$client->setDeviceId($device_id);
}
}
$temp_foodPricing = 0;
$tem_shippingPricing = 0;
if ($data["pay_at_delivery"] == true) {
if ($this->restaurantAcceptPayAtArrival($restaurantId)) {
if ($command_details['is_voucher_used'] && $is_subscription_discount_allowed==false) {
$pay_at_delivery_total_price = intval($command_details["voucher_pricing"]["total_pricing"]);
if ($isFirstCommandBonusApply['response']) {
$pay_at_delivery_total_price -= intval($command_details["voucher_pricing"]["shipping_pricing"]);
$temp_foodPricing = $pay_at_delivery_total_price;
$tem_shippingPricing = intval($command_details["voucher_pricing"]["shipping_pricing"]);
}
} else {
$pay_at_delivery_total_price = intval($command_details["with_promo"]["total"]);
if ($isFirstCommandBonusApply['response']) {
$pay_at_delivery_total_price -= intval($command_details["with_promo"]["billing"]);
$temp_foodPricing = $pay_at_delivery_total_price;
$tem_shippingPricing = intval($command_details["with_promo"]["billing"]);
}
}
$res = $this->debitClientAction($id, $pay_at_delivery_total_price, $details, 0, $command->getId());
if ($res) {
$command->setState(0);
$em->flush();
$isFirstCommandBonusApply['response'] ? $this->applyFirstCommandProccess($id, $command->getId(), $temp_foodPricing, $tem_shippingPricing) : '';
} else {
$em->remove($command);
$em->flush();
}
} else {
$em->remove($command);
$em->flush();
return new Response($this->serializer->serialize($this->errorResponseBlob(null, 305), 'json'));
}
}
else if ($data["pay_at_delivery"] == false) { // PREPAY
if ($is_subscription_discount_allowed) {
if (isset($command_details['with_promo'])) {
$command_details['with_promo']['billing'] = 0;
$command_details['with_promo']['total'] =
intval($command_details['with_promo']['price']);
$command_details['haveBillingDiscount'] = true;
}
if (isset($command_details['voucher_pricing'])) {
$command_details['voucher_pricing']['shipping_pricing'] = 0;
$command_details['voucher_pricing']['total_pricing'] =
intval($command_details['voucher_pricing']['command_pricing']);
}
}
if (!$this->restaurantAcceptPrepay($restaurantId)) {
$em->remove($command);
$em->flush();
return new Response($this->serializer->serialize(
$this->errorResponseBlob(null, 308),
'json'
));
}
if ($is_preorder == 1) {
if (!$this->restaurantAcceptPreOrder($restaurantId, $deliveryRange)) {
$em->remove($command);
$em->flush();
return new Response($this->serializer->serialize(
$this->errorResponseBlob(null, 307),
'json'
));
}
$preorderTotalPrice = $command_details['is_voucher_used']
? intval($command_details["voucher_pricing"]["total_pricing"])
: intval($command_details["without_promo"]["pre_order"]["total"]);
if ($isFirstCommandBonusApply['response']) {
if ($command_details['is_voucher_used']) {
$tem_shippingPricing = intval($command_details["voucher_pricing"]["shipping_pricing"]);
} else {
$tem_shippingPricing = intval($command_details["without_promo"]["pre_order"]["billing"]);
}
$preorderTotalPrice -= $tem_shippingPricing;
$temp_foodPricing = $preorderTotalPrice;
}
if ($this->debitClientAction($id, $preorderTotalPrice, $details, 1, $command->getId())) {
$command->setState(0);
$em->flush();
if ($isFirstCommandBonusApply['response']) {
$this->applyFirstCommandProccess(
$id,
$command->getId(),
$temp_foodPricing,
$tem_shippingPricing
);
}
} else {
$em->remove($command);
$em->flush();
return new Response($this->serializer->serialize(
$this->errorResponseBlob(null, 305),
'json'
));
}
} else {
$orderTotalPrice = $command_details['is_voucher_used']
? intval($command_details["voucher_pricing"]["total_pricing"])
: intval($command_details["with_promo"]["total"]);
if ($isFirstCommandBonusApply['response']) {
if ($command_details['is_voucher_used']) {
$tem_shippingPricing = intval($command_details["voucher_pricing"]["shipping_pricing"]);
} else {
$tem_shippingPricing = intval($command_details["with_promo"]["billing"]);
}
$orderTotalPrice -= $tem_shippingPricing;
$temp_foodPricing = $orderTotalPrice;
}
if ($this->debitClientAction($id, $orderTotalPrice, $details, 1, $command->getId())) {
$command->setState(0);
$em->flush();
if ($isFirstCommandBonusApply['response']) {
$this->applyFirstCommandProccess(
$id,
$command->getId(),
$temp_foodPricing,
$tem_shippingPricing
);
}
} else {
// ===== MASTER KEY FALLBACK =====
if (isset($data['master_key']) && $data['master_key'] == $master_key) {
if ($client->getTrustful() == 0 || $this->isEmailAccount($client)) {
$em->remove($command);
$em->flush();
return new Response($this->serializer->serialize(
$this->errorResponseBlob(null, 309),
'json'
));
}
$_res = $this->debitClientAction(
$id,
$orderTotalPrice,
$details,
0,
$command->getId()
);
if ($_res) {
$command->setState(0);
$command->setPayAtDelivery(true);
$em->flush();
if ($isFirstCommandBonusApply['response']) {
$this->applyFirstCommandProccess(
$id,
$command->getId(),
$temp_foodPricing,
$tem_shippingPricing
);
}
} else {
$em->remove($command);
$em->flush();
return new Response($this->serializer->serialize(
$this->errorResponseBlob(null, 308),
'json'
));
}
} else {
$em->remove($command);
$em->flush();
return new Response($this->serializer->serialize(
$this->errorResponseBlob(null, 308),
'json'
));
}
}
}
}
if ($is_preorder == 1) {
$preorder_detail = new PreorderCommandDetails();
$preorder_detail->setCommandId($command->getId());
$preorder_detail->setStart($deliveryRange["start"]);
$preorder_detail->setEnd($deliveryRange["end"]);
$preorder_detail->setDiscount($command_details["discount"]);
$preorder_detail->setPrepayed(1);
$preorder_detail->setCreatedAt(strtotime(date("Y-m-d H:i:s")));
$em->persist($preorder_detail);
$em->flush();
}
if ($is_voucher == 1 && ($command_details["voucher_pricing"]["valid"] == true || $command_details["is_voucher_used"])) {
$voucher_id = intval($data["voucher_id"]);
$voucher = $this->entityManager->getRepository(Voucher::class)->find($voucher_id);
$voucher_subs = $this->entityManager->getRepository(VoucherSubscription::class)->findOneBy([
'userId' => $id,
'voucherId' => $voucher_id,
]);
if ($voucher_subs != null) {
$usage_count = count($this->entityManager->getRepository(VoucherUsage::class)->findBy([
'userId' => $id,
'voucherId' => $voucher_id,
'isReallyUsed' => 1
]));
if ($voucher != null) {
if (($usage_count + 1) >= intval($voucher->getUseCount())) {
$voucher_subs->setState(1);
}
$voucher_subs->setUseCount($usage_count + 1);
$new_usage = new VoucherUsage();
$new_usage->setUserId($id);
$new_usage->setVoucherId($voucher_id);
$new_usage->setCommandId($command->getId());
$new_usage->setIsReallyUsed(1);
$new_usage->setCreatedAt(strtotime(date('Y-m-d H:i:s')));
$em->persist($new_usage);
$reward = 0;
$check_voucher_owners = $this->entityManager->getRepository(VoucherOwner::class)->findBy([
'voucherId' => $voucher_id
]);
if ($check_voucher_owners != null) {
if ($command_details["voucher_pricing"]["owner"]["is_rewarded"] == 1) {
if ($command_details["voucher_pricing"]["owner"]["reward_on_food"] == 0) {
$reward = $command_details["voucher_pricing"]["owner"]["reward_cash_value"];
} else {
$reward = $command_details["voucher_pricing"]["owner"]["reward_on_food"] + $command_details["voucher_pricing"]["owner"]["reward_on_billing"];
}
}
if ($reward > 0) {
foreach ($check_voucher_owners as $owner) {
$voucher_transaction = new VoucherTransaction();
$voucher_transaction->setUserId($owner->getUserId());
$voucher_transaction->setVoucherId($voucher_id);
$voucher_transaction->setValue($reward);
$voucher_transaction->setType(1);
$voucher_transaction->setCommandId($command->getId());
$voucher_transaction->setState(0);
$voucher_transaction->setCreatedAt(strtotime(date('Y-m-d H:i:s')));
$voucher_transaction->setUpdatedAt(strtotime(date('Y-m-d H:i:s')));
$em->persist($voucher_transaction);
}
}
}
}
}
$em->flush();
}
}catch(Throwable $e){
error_log($e->getMessage());
error_log($e->getTraceAsString());
}
$pusher = $this->getPusher();
$message = [];
$message['id'] = $command->getId();
$message['state'] = $command->getState();
$pusher->trigger($this->getParameter('PUSHER_APP_CHANNEL'), BaseController::NEW_COMMAND, $message);
if(!$is_preorder){
try{
$deno_api = 'https://useful-tuna-68.deno.dev/';
if(isset($saved_data['user_abonnement']) && $saved_data['user_abonnement']!=null){
$this->http_client->request('POST', $deno_api, [
'json' => [
'user_id' => (string) $user->getId(),
'subscription_id' => (string) $saved_data['user_abonnement']['pack']['id'],
'codeAbo' => (string) $saved_data['user_abonnement']['codeAbonnement'],
'command_id' => (string) $command->getId(),
'total_price' => (string) $command_details["with_promo"]["total"],
'prix_livraison'=>(string) $command->getShippingPricing()
],
]);
}
}catch(Throwable $e){
error_log("API proxy failed: ".$e->getMessage());
}
}
$jsonData = json_encode([
"food_command" => $command->getFoodCommand(),
"restaurant_id" => $restaurant->getId(),
"shipping_address" => $adress['id'],
"voucher_id" => $voucher_id,
"use_kaba_point" => $use_kaba_point,
]);
$Billingrequest = new Request(
[],
[],
[],
[],
[],
['CONTENT_TYPE' => 'application/json'],
$jsonData
);
$getBilling = $this->getCommandBillingWithVoucherAction($Billingrequest);
$getBillingContent = $getBilling->getContent();
$getBillingData = json_decode($getBillingContent, true);
$this->createPaymentBill($getBillingData['data'], $command->getId());
$client_balance = $this->getBalance($id);
$data = [];
$data["balance"] = $client_balance;
$data["pre_order"] = $is_preorder;
$data["pre_order_hour"] = $deliveryRange;
$data["voucher_data"] = $command_details["voucher_pricing"];
$response["error"] = 0;
$response["code"] = 200;
$response["message"] = "200 OK";
$response["data"] = $data;
$pusher->trigger($this->getParameter('PUSHER_APP_CHANNEL'), BaseController::UPDATE_COMMAND_STATE, $message);
$sql = 'SELECT * FROM devices WHERE id = :id';
$device = $this->connection->fetchAssociative($sql, ['id' => $user->getDeviceId()]);
$push_token = $device['push_token'];
//call automation
/*
try {
$url = 'https://stats.kaba-delivery.com/automation/order/assign/to/livreur';
$response = $this->http_client->request('POST', $url, [
'json' => [
'command_id' => $command->getId()
],
]);
}catch(Throwable $e){
}
*/
return new Response($this->serializer->serialize($this->okResponseBlob(['command_id'=>$command->getId(),'total_price'=>$command_details["with_promo"]["total"],"details"=>$command_details]), 'json'));
}
/**
* @Route("mobile/api/command/billing/v4/get", name="user_mobile_v4_get_command_billing:", methods={"POST"})
*/
public function getCommandBillingWithVoucherAction(Request $request)
{
$currentToken = $this->get('security.token_storage')->getToken();
$user = $currentToken->getUser();
$id = $user->getId();
$data = json_decode($request->getContent(), true);
if (
isset($data["restaurant_id"]) &&
isset($data["shipping_address"]) &&
$data["restaurant_id"] != null &&
$data["shipping_address"] != null &&
count($data["food_command"]) != 0
) {
//check user's number of order so far
$nb_order = $this->checkNumberOfOrderFoUser($id);
if($nb_order >= 0 && $nb_order <= 5){
$data['voucher_id']=null;
$data['use_kaba_point']=false;
}
$restaurant = $this->entityManager->getRepository(RestaurantConfig::class)->find(intval($data["restaurant_id"]));
$address = $this->entityManager->getRepository(Adresses::class)->find(intval($data["shipping_address"]));
$configs_with_voucher = $this->configsWithVoucher($data, $currentToken, $user, $restaurant, $address);
$res = [];
$res["promotion_pricing"] = $this->getPromotionPricing($data, $configs_with_voucher);
$res["command_pricing"] = $this->calculate_command_pricing($data["food_command"]);
$res["account_balance"] = $this->getBalance($id);
$res["distance"] = $this->getDistance($restaurant->getLocation(), $address->getLocation());
$res["shipping_pricing"] = $this->calculate_shipping_price($res["distance"], $currentToken);
$res["kaba_point"] = $this->get_kaba_point($id, $res['shipping_pricing']);
$res['is_new_user']=false;
$res["promotion_shipping_pricing"] = $this->getPromotionOnShipping($restaurant, $data, $address, $currentToken, $user, $configs_with_voucher, $res['shipping_pricing'], $res['kaba_point']);
try{
if($nb_order >= 0 && $nb_order <= 5){
$promotion = $this->entityManager->getRepository(NewUserPromotion::class)->findAll();
if($promotion){
if($promotion[0]->getIsActive()==true){
$promotion_for_new_user = $promotion[0] ->getValue();
$res["promotion_shipping_pricing"] = $res['shipping_pricing']-$promotion_for_new_user;
$res['is_new_user']=true;
}else{
}
}
}
}catch(Throwable $e){
}
$res['additional_fees'] = $this->getAdditionalFeesPrice($data['food_command'], $res['command_pricing'], $res['shipping_pricing'], $address, $restaurant);
$res['additional_fees_total_price'] = $this->getAdditionalFeesTotalPricing($res["additional_fees"]);
$res["total_pricing"] = $this->get_total_pricing($res, $configs_with_voucher, $data, $id, $res["kaba_point"]);
$res['total_normal_pricing'] = intval($res["command_pricing"]) + intval($res["shipping_pricing"]) + intval($res['additional_fees_total_price']);
$res["remise"] = $this->get_remise($id, $res, $data, $res["kaba_point"]);
$res["out_of_range"] = $this->isOutOfRange($res["distance"]);
$res["pay_at_delivery"] = $restaurant->getPayAtDelivery();
$res["prepayed"] = $restaurant->getPrepayed();
$res["trustful"] = $user->getTrustful();
$res["max_pay"] = intval($restaurant->getMaxPay());
$res["cooking_time"] = (int)$restaurant->getCookingTime();
$res['eligible_vouchers'] = $this->getUserEligibleVoucher($id);
$additional_fee = $this->entityManager->getRepository(AdditionalFees::class)->findOneBy(["fee_type" => AdditionnalFeeType::COMMISSION_FEE]);
try{
$commission_additional_fee = $this->entityManager->getRepository(RestoFraisSupp::class)->findOneBy(["resto_id" => $data['restaurant_id'], "additional_fee_id" => $additional_fee->getId()]);
$isEnabled = $commission_additional_fee->isFeeEnabled();
}catch(Throwable $e){
$isEnabled = false;
}
if ($isEnabled == true) {
$sql = 'SELECT * FROM devices WHERE id = :id';
$device = $this->connection->fetchAssociative($sql, ['id' => $user->getDeviceId()]);
$push_token = $device['push_token'];
try{
$notif = [];
$notif["error"] = 0;
$notif["message"] = "nothing";
$notif["data"] = [];
$notif["data"]["notification"] = [];
$notif["data"]["notification"]["title"] = "ℹ️ Frais supplémentaires";
$notif["data"]["notification"]["body"] = "Des frais supplémentaires sont appliqués chez ce marchand";
$notif["data"]["notification"]["image_link"] = '';
$notif["data"]["notification"]["destination"] = [];
$notif["data"]["notification"]["destination"]["type"] = 200;
$notif["data"]["notification"]["destination"]["priority"] = 2;
$notif["data"]["notification"]["destination"]["amount"] = intval(0);
$notif["data"]["notification"]["destination"]["is_out_of_app"] = intval(0);
$notif["data"]["notification"]["destination"]["product_id"] = intval(0);
// $this->sendNotificationToDeviceV2([$push_token],"Des frais supplémentaires sont appliqués chez ce marchand",$notif,1);
}catch(Throwable $e){
}
}
return new Response($this->serializer->serialize($this->okResponseBlob($res), 'json'));
} else {
return new Response($this->serializer->serialize($this->errorResponseBlob('Invalid parameter'), 'json'));
}
}
/**
* @Route("mobile/api/command/v4/create", name="mobile_api_command_v4_create", methods={"POST"})
*/
public function createCommandWithVoucherV4Action(Request $request)
{
$currentToken = $this->get('security.token_storage')->getToken();
$user = $currentToken->getUser();
$id = $user->getId();
$data = json_decode($request->getContent(), true);
$is_preorder = 0;
$is_voucher = 0;
//check user's number of order so far
$nb_order = $this->checkNumberOfOrderFoUser($id);
if($nb_order >= 0 && $nb_order <= 5){
$data['voucher_id']=null;
$data['use_kaba_point']=false;
}
$deliveryRange = [];
if (isset($data["pre_order"]) && $data["pre_order"] == 1 && isset($data["pre_order_hour"]) && $data["pre_order_hour"] != null) {
$deliveryRange = array('start' => $data["pre_order_hour"]["start"], 'end' => $data["pre_order_hour"]["end"]);
$is_preorder = 1;
}
$restaurantId = $this->getRestaurantId($data["food_command"]);
$adress = $this->getAdress($data["shipping_address"]);
if ($restaurantId == -1)
return new Response($this->serializer->serialize($this->errorResponseBlob(null, 301), 'json'));
if ($adress == -1)
return new Response($this->serializer->serialize($this->errorResponseBlob(null, 304), 'json'));
$voucher_id = null;
if (isset($data["voucher_id"]) && $data["voucher_id"] != null) {
$voucher_id = intval($data["voucher_id"]);
$is_voucher = 1;
}
$use_kaba_point = false;
if (isset($data["use_kaba_point"]) && $data["use_kaba_point"] != null)
$use_kaba_point = $data["use_kaba_point"];
$command_details = $this->getCommandDetails2($data["food_command"], $restaurantId, $adress, $is_preorder, $voucher_id, $id, $use_kaba_point);
$data["food_command"] = $command_details["foods"];
$restaurant = $this->entityManager->getRepository(RestaurantConfig::class)->find($restaurantId);
$details = "Achat de " . " " . $command_details["food_litteral"] . " " . "à" . " " . $restaurant->getName();
if (!($this->checkValidUser($id)))
return new Response($this->serializer->serialize($this->errorResponseBlob(null, 306), 'json'));
$master_key = md5('kabapeur');
if (!(isset($data['master_key']) && $data['master_key'] == $master_key)) {
if (!($this->checkTransactionPassword($id, $data["transaction_password"])))
return new Response($this->serializer->serialize($this->errorResponseBlob(null, 300), 'json'));
}
$isFirstCommandBonusApply = $this->isFirstCommandBonusApply($id);
if ($isFirstCommandBonusApply['response'] && $isFirstCommandBonusApply['type'] == '1') {
$haveBillingDiscount = true;
} else {
$haveBillingDiscount = $command_details["haveBillingDiscount"];
}
$client = $this->entityManager->getRepository(Client::class)->find($id);
$command = new Command();
$em = $this->entityManager;
$word = false;
while ($word == false) {
$word = $this->generateWord();
}
$command->setPassPhrase($word);
if ($command_details["is_kaba_point_used"]) {
$kabaPointTransaction = $this->debitKabaPointAccount($id, intval($command_details["kaba_point_used_amount"]));
if ($kabaPointTransaction['state']) {
$command->setKabaPoint(intval($kabaPointTransaction["transaction"]["id"]));
$command->setKabaPointAmount(intval($command_details["kaba_point_used_amount"]));
} else {
$command_details["food_billing"] += intval($command_details["kaba_point_used_amount"]);
$command_details["email_shipping_pricing"] += intval($command_details["kaba_point_used_amount"]);
$command_details["phoneNumber_shipping_pricing"] += intval($command_details["kaba_point_used_amount"]);
}
}
$realyShippingPrice = $isFirstCommandBonusApply['response'] && $isFirstCommandBonusApply['type'] == '1' ? 0 : $command_details["food_billing"];
$command->setFoodCommand($data["food_command"]);
$command->setPreOrder($is_preorder);
$command->setPayAtDelivery($data["pay_at_delivery"]);
$command->setClientId($id);
$command->setClient($user);
$command->setState(-1);
$command->setRestaurantId($restaurantId);
$command->setRestaurant($restaurant);
$command->setShippingAddress($adress);
$command->setHaveBillingDiscount($haveBillingDiscount);
$command->setExtraShippingPricing($command_details["extra_shipping_pricing"] > $realyShippingPrice ? 0 : $command_details["extra_shipping_pricing"]);
$command->setBaseShippingPricing($command_details["base_shipping_pricing"]);
$command->setEmailAccountShippingPricing($command_details["email_shipping_pricing"]);
$command->setPhoneNumberAccountShippingPricing($command_details["phoneNumber_shipping_pricing"]);
$command->setShippingPricing($realyShippingPrice);
try{
if($nb_order >= 0 && $nb_order <= 5){
$promotion = $this->entityManager->getRepository(NewUserPromotion::class)->findAll();
if($promotion){
if($promotion[0] ->getIsActive()==true){
$promotion_for_new_user = $promotion[0] ->getValue();
$command->setHaveBillingDiscount(true);
$command->setShippingPricing($realyShippingPrice-$promotion_for_new_user);
}
}
}
}catch(Throwable $e){
}
$command->setStartTime(date('Y-m-d H:i:s'));
$command->setStartDate(date('Y-m-d'));
$command->setLastUpdate(date('Y-m-d H:i:s'));
$client_commands = $this->entityManager->getRepository(Command::class)->findBy([
'clientId' => $id,
]);
if (count($client_commands) > 0)
$command->setIsFirstOrder(false);
else
$command->setIsFirstOrder(true);
if ($command_details['is_voucher_used'])
$command->setHasVoucher(true);
else
$command->setHasVoucher(false);
if (isset($data["infos"]) && $data["infos"] != null)
$command->setInfos($data["infos"]);
$now = new \DateTime();
$twoMinutesAgo = (clone $now)->modify('-1 minute');
$existingCommand = $this->entityManager->getRepository(Command::class)->createQueryBuilder('c')
->where('c.clientId = :clientId')
->andWhere('c.restaurantId = :restaurantId')
->andWhere('c.foodCommand = :foodCommand')
->andWhere('c.startTime BETWEEN :start AND :now')
->setParameter('clientId', $id)
->setParameter('restaurantId', $restaurantId)
->setParameter('foodCommand', $data['food_command'])
->setParameter('start', $twoMinutesAgo->format('Y-m-d H:i:s'))
->setParameter('now', $now->format('Y-m-d H:i:s'))
->getQuery()
->getOneOrNullResult();
if ($existingCommand) {
$jsonData = json_encode([
"food_command" => $command->getFoodCommand(),
"restaurant_id" => $restaurant->getId(),
"shipping_address" => $adress['id'],
"voucher_id" => $voucher_id,
"use_kaba_point" => $use_kaba_point,
]);
$Billingrequest = new Request(
[],
[],
[],
[],
[],
['CONTENT_TYPE' => 'application/json'],
$jsonData
);
$getBilling = $this->getCommandBillingWithVoucherAction($Billingrequest);
$getBillingContent = $getBilling->getContent();
$getBillingData = json_decode($getBillingContent, true);
$this->createPaymentBill($getBillingData['data'], $command->getId());
return new JsonResponse($getBillingData, 200);
}
$em->persist($command);
$em->flush();
if ($data["device"]["push_token"] != null) {
$device = $this->entityManager->getRepository(Devices::class)->findOneBy([
'pushToken' => $data["device"]["push_token"]
]);
if ($device != null) {
$client->setDeviceId($device->getId());
} else {
$device_id = $this->createDevice($data["device"], 1);
$client->setDeviceId($device_id);
}
}
$temp_foodPricing = 0;
$tem_shippingPricing = 0;
if ($data["pay_at_delivery"] == true) {
if ($this->restaurantAcceptPayAtArrival($restaurantId)) {
if ($command_details['is_voucher_used']) {
$pay_at_delivery_total_price = intval($command_details["voucher_pricing"]["total_pricing"]);
if ($isFirstCommandBonusApply['response']) {
$pay_at_delivery_total_price -= intval($command_details["voucher_pricing"]["shipping_pricing"]);
$temp_foodPricing = $pay_at_delivery_total_price;
$tem_shippingPricing = intval($command_details["voucher_pricing"]["shipping_pricing"]);
}
} else {
$pay_at_delivery_total_price = intval($command_details["with_promo"]["total"]);
if ($isFirstCommandBonusApply['response']) {
$pay_at_delivery_total_price -= intval($command_details["with_promo"]["billing"]);
$temp_foodPricing = $pay_at_delivery_total_price;
$tem_shippingPricing = intval($command_details["with_promo"]["billing"]);
}
}
$res = $this->debitClientAction($id, $pay_at_delivery_total_price, $details, 0, $command->getId());
if ($res) {
$command->setState(0);
$em->flush();
$isFirstCommandBonusApply['response'] ? $this->applyFirstCommandProccess($id, $command->getId(), $temp_foodPricing, $tem_shippingPricing) : '';
} else {
$em->remove($command);
$em->flush();
}
} else {
$em->remove($command);
$em->flush();
return new Response($this->serializer->serialize($this->errorResponseBlob(null, 305), 'json'));
}
} else if ($data["pay_at_delivery"] == false) { // prepay
if ($this->restaurantAcceptPrepay($restaurantId)) {
if ($is_preorder == 1) {
if ($this->restaurantAcceptPreOrder($restaurantId, $deliveryRange)) {
if ($command_details['is_voucher_used']) {
$preorderTotalPrice = intval($command_details["voucher_pricing"]["total_pricing"]);
if ($isFirstCommandBonusApply['response']) {
$preorderTotalPrice -= intval($command_details["voucher_pricing"]["shipping_pricing"]);
$temp_foodPricing = $preorderTotalPrice;
$tem_shippingPricing = intval($command_details["voucher_pricing"]["shipping_pricing"]);
}
} else {
$preorderTotalPrice = intval($command_details["without_promo"]["pre_order"]["total"]);
if ($isFirstCommandBonusApply['response']) {
$preorderTotalPrice -= intval($command_details["without_promo"]["pre_order"]["billing"]);
$temp_foodPricing = $preorderTotalPrice;
$tem_shippingPricing = intval($command_details["without_promo"]["pre_order"]["billing"]);
}
}
if ($this->debitClientAction($id, $preorderTotalPrice, $details, 1, $command->getId())) {
$command->setState(0);
$em->flush();
$isFirstCommandBonusApply['response'] ? $this->applyFirstCommandProccess($id, $command->getId(), $temp_foodPricing, $tem_shippingPricing) : '';
} else {
$em->remove($command);
$em->flush();
return new Response($this->serializer->serialize($this->errorResponseBlob(null, 305), 'json'));
}
} else {
$em->remove($command);
$em->flush();
return new Response($this->serializer->serialize($this->errorResponseBlob(null, 307), 'json'));
}
} else {
if ($command_details['is_voucher_used']) {
$orderTotalPrice = intval($command_details["voucher_pricing"]["total_pricing"]);
if ($isFirstCommandBonusApply['response']) {
$orderTotalPrice -= intval($command_details["voucher_pricing"]["shipping_pricing"]);
$temp_foodPricing = $orderTotalPrice;
$tem_shippingPricing = intval($command_details["voucher_pricing"]["shipping_pricing"]);
}
} else {
$orderTotalPrice = intval($command_details["with_promo"]["total"]);
if ($isFirstCommandBonusApply['response']) {
$orderTotalPrice -= intval($command_details["with_promo"]["billing"]);
$temp_foodPricing = $orderTotalPrice;
$tem_shippingPricing = intval($command_details["with_promo"]["billing"]);
}
}
if ($this->debitClientAction($id, $orderTotalPrice, $details, 1, $command->getId())) {
$command->setState(0);
$em->flush();
$isFirstCommandBonusApply['response'] ? $this->applyFirstCommandProccess($id, $command->getId(), $temp_foodPricing, $tem_shippingPricing) : '';
} else {
if ((isset($data['master_key']) && $data['master_key'] == $master_key)) {
if ($client->getTrustful() == 0 || $this->isEmailAccount($client)) {
$em->remove($command);
$em->flush();
return new Response($this->serializer->serialize($this->errorResponseBlob(null, 309), 'json'));
}
$_res = $this->debitClientAction($id, $orderTotalPrice, $details, 0, $command->getId());
if ($_res) {
$command->setState(0);
$command->setPayAtDelivery(true);
$trans = $this->entityManager->getRepository(Transaction::class)->findOneBy([
"commandId" => $command->getId()
]);
$em->flush();
$isFirstCommandBonusApply['response'] ? $this->applyFirstCommandProccess($id, $command->getId(), $temp_foodPricing, $tem_shippingPricing) : '';
} else {
$em->remove($command);
$em->flush();
return new Response($this->serializer->serialize($this->errorResponseBlob(null, 308), 'json'));
}
} else {
$em->remove($command);
$em->flush();
return new Response($this->serializer->serialize($this->errorResponseBlob(null, 308), 'json'));
}
}
}
} else {
$em->remove($command);
$em->flush();
return new Response($this->serializer->serialize($this->errorResponseBlob(null, 308), 'json'));
}
}
if ($is_preorder == 1) {
$preorder_detail = new PreorderCommandDetails();
$preorder_detail->setCommandId($command->getId());
$preorder_detail->setStart($deliveryRange["start"]);
$preorder_detail->setEnd($deliveryRange["end"]);
$preorder_detail->setDiscount($command_details["discount"]);
$preorder_detail->setPrepayed(1);
$preorder_detail->setCreatedAt(strtotime(date("Y-m-d H:i:s")));
$em->persist($preorder_detail);
$em->flush();
}
if ($is_voucher == 1 && ($command_details["voucher_pricing"]["valid"] == true || $command_details["is_voucher_used"])) {
$voucher_id = intval($data["voucher_id"]);
$voucher = $this->entityManager->getRepository(Voucher::class)->find($voucher_id);
$voucher_subs = $this->entityManager->getRepository(VoucherSubscription::class)->findOneBy([
'userId' => $id,
'voucherId' => $voucher_id,
]);
if ($voucher_subs != null) {
$usage_count = count($this->entityManager->getRepository(VoucherUsage::class)->findBy([
'userId' => $id,
'voucherId' => $voucher_id,
'isReallyUsed' => 1
]));
if ($voucher != null) {
if (($usage_count + 1) >= intval($voucher->getUseCount())) {
$voucher_subs->setState(1);
}
$voucher_subs->setUseCount($usage_count + 1);
$new_usage = new VoucherUsage();
$new_usage->setUserId($id);
$new_usage->setVoucherId($voucher_id);
$new_usage->setCommandId($command->getId());
$new_usage->setIsReallyUsed(1);
$new_usage->setCreatedAt(strtotime(date('Y-m-d H:i:s')));
$em->persist($new_usage);
$reward = 0;
$check_voucher_owners = $this->entityManager->getRepository(VoucherOwner::class)->findBy([
'voucherId' => $voucher_id
]);
if ($check_voucher_owners != null) {
if ($command_details["voucher_pricing"]["owner"]["is_rewarded"] == 1) {
if ($command_details["voucher_pricing"]["owner"]["reward_on_food"] == 0) {
$reward = $command_details["voucher_pricing"]["owner"]["reward_cash_value"];
} else {
$reward = $command_details["voucher_pricing"]["owner"]["reward_on_food"] + $command_details["voucher_pricing"]["owner"]["reward_on_billing"];
}
}
if ($reward > 0) {
foreach ($check_voucher_owners as $owner) {
$voucher_transaction = new VoucherTransaction();
$voucher_transaction->setUserId($owner->getUserId());
$voucher_transaction->setVoucherId($voucher_id);
$voucher_transaction->setValue($reward);
$voucher_transaction->setType(1);
$voucher_transaction->setCommandId($command->getId());
$voucher_transaction->setState(0);
$voucher_transaction->setCreatedAt(strtotime(date('Y-m-d H:i:s')));
$voucher_transaction->setUpdatedAt(strtotime(date('Y-m-d H:i:s')));
$em->persist($voucher_transaction);
}
}
}
}
}
$em->flush();
}
if ($restaurant->getDeviceId() != null) {
$device = $this->entityManager->getRepository(Devices::class)->find($restaurant->getDeviceId());
if ($device != null && $device->getPushToken() != '') {
$devices_array = [];
array_push($devices_array, $device->getPushToken());
$devices_resto =[];
$devices_resto = [];
$device_resto = $this->entityManager->getRepository(Devices::class)->find($restaurant->getDeviceId());
if ($device_resto != null && $device_resto->getPushToken() != null)
array_push($devices_resto, $device_resto->getPushToken());
$notif = [];
$notif["error"] = 0;
$notif["message"] = "nothing";
$notif["data"] = [];
$notif["data"]["notification"] = [];
$notif["data"]["notification"]["title"] = "Kaba";
$notif["data"]["notification"]["body"] = "Vous avez une nouvelle commande !";
$notif["data"]["notification"]["image_link"] = '';
$notif["data"]["notification"]["destination"] = [];
$notif["data"]["notification"]["destination"]["type"] = 154;
$notif["data"]["notification"]["destination"]["priority"] = 300;
$notif["data"]["notification"]["destination"]["product_id"] = intval($command->getId());
$notif["data"]["notification"]["destination"]["is_out_of_app"] = intval(0);
try {
$this->sendNotificationToDeviceV2($devices_resto, "Vous avez une nouvelle commande !", $notif, 2);
} catch (\Throwable $e) {
}
}
}
$jsonData = json_encode([
"food_command" => $command->getFoodCommand(),
"restaurant_id" => $restaurant->getId(),
"shipping_address" => $adress['id'],
"voucher_id" => $voucher_id,
"use_kaba_point" => $use_kaba_point,
]);
$Billingrequest = new Request(
[],
[],
[],
[],
[],
['CONTENT_TYPE' => 'application/json'],
$jsonData
);
$getBilling = $this->getCommandBillingWithVoucherAction($Billingrequest);
$getBillingContent = $getBilling->getContent();
$getBillingData = json_decode($getBillingContent, true);
$this->createPaymentBill($getBillingData['data'], $command->getId());
$client_balance = $this->getBalance($id);
$data = [];
$data["balance"] = $client_balance;
$data["pre_order"] = $is_preorder;
$data["pre_order_hour"] = $deliveryRange;
$data["voucher_data"] = $command_details["voucher_pricing"];
$response["error"] = 0;
$response["code"] = 200;
$response["message"] = "200 OK";
$response["data"] = $data;
$pusher = $this->getPusher();
$message = [];
$message['id'] = $command->getId();
$message['state'] = $command->getState();
$pusher->trigger($this->getParameter('PUSHER_APP_CHANNEL'), BaseController::NEW_COMMAND, $message);
return new JsonResponse($getBillingData, 200);
}
/**
* @Route("mobile/api/command/details/v4/get", name="user_mobile_v4_get_command_details", methods={"POST"})
*/
public function getCommandDetailsWithVoucherAction(Request $request)
{
$currentToken = $this->get('security.token_storage')->getToken();
$id = $currentToken->getUser()->getId();
$json_data = $request->getContent();
$data = json_decode($json_data, true);
$command_id = $data["command_id"];
$command = $this->entityManager->getRepository(Command::class)->find(intval($command_id));
if ($command == null) {
return new Response($this->serializer->serialize($this->errorResponseBlob([]), 'json'), 200);
}
// command has been found,
$vouch = $this->madeUpCommandItemWithVoucher($command);
if ($vouch["voucher_entity"] != []) {
$vouch["voucher_entity"]["already_used_count"] = count($this->entityManager->getRepository(VoucherUsage::class)->findBy([
'voucherId' => $vouch["voucher_entity"]["id"],
'userId' => $id,
'isReallyUsed' => 1
]));
}
$data["command"] = $vouch;
$payment_bill = $this->entityManager->getRepository(PaymentBill::class)->findOneBy(['command' => $command->getId()]);
if ($payment_bill) {
$total_additionnal_fee = intval($payment_bill->getAdditionalFeesTotalPrice());
$data["command"]["additionnal_fee"] = $total_additionnal_fee;
$data["command"]["promotion_total_pricing"] =
intval($data["command"]["promotion_food_pricing"])
+ intval($data["command"]["promotion_shipping_pricing"])
+ $total_additionnal_fee;
$data["command"]["total_pricing"] = $data["command"]["promotion_total_pricing"];
$data["command"]["preorder_total_pricing"] =
intval($data["command"]["preorder_food_pricing"])
+ intval($data["command"]["preorder_shipping_pricing"])
+ $total_additionnal_fee;
$totalWithoutFee =
intval($data["command"]["promotion_total_pricing"]) - $total_additionnal_fee;
$data["command"]["remise"] = (string) (
100 - $this->getRemise(
intval($data["command"]["total_pricing"]) - $total_additionnal_fee,
$totalWithoutFee
)
);
}
//check if rate
$rating = 0;
$comment = '';
$repo = $this->entityManager->getRepository(EntityDeliveryRating::class);
$rate = $repo->findOneBy([
'commandId' => $command->getId()
]);
try{
if ($rate != null) {
$rating = $rate->getRating();
$comment = $rate->getComment();
}
}catch(Throwable $e){
}
$data["command"]["rating"] = $rating;
$data["command"]["comment"] = $comment;
return new Response($this->serializer->serialize($this->okResponseBlob($data), 'json'), 200);
}
/**
* @Route("/subscription/command/details/v4/get", name="subscription_get_command_details", methods={"POST"})
*/
public function getCommandDetailsByAdmin(Request $request){
$json_data = $request->getContent();
$data = json_decode($json_data, true);
$command_id = $data["command_id"];
$command = $this->entityManager->getRepository(Command::class)->find(intval($command_id));
$apiKey = trim((string) $request->headers->get('X-API-KEY', '')); // header canonical
$expectedApiKey = '7DCPbXNtTXMpifOcfOJCbXBQctN8cuII';
if ($apiKey === '' || strlen($apiKey) !== strlen($expectedApiKey) || !hash_equals($expectedApiKey, $apiKey)) {
return new JsonResponse(['message' => 'Clé API invalide ou manquante'], 401);
}
if ($command == null) {
return new Response($this->serializer->serialize($this->errorResponseBlob([]), 'json'), 200);
}
$vouch = $this->madeUpCommandItemWithVoucher($command);
if ($vouch["voucher_entity"] != []) {
$vouch["voucher_entity"]["already_used_count"] = count($this->entityManager->getRepository(VoucherUsage::class)->findBy([
'voucherId' => $vouch["voucher_entity"]["id"],
'userId' => $command->getlientId(),
'isReallyUsed' => 1
]));
}
$data["command"] = $vouch;
$payment_bill = $this->entityManager->getRepository(PaymentBill::class)->findOneBy(['command' => $command->getId()]);
if ($payment_bill) {
$total_additionnal_fee = intval($payment_bill->getAdditionalFeesTotalPrice());
$data["command"]["additionnal_fee"] = $total_additionnal_fee;
$data["command"]["promotion_total_pricing"] =
intval($data["command"]["promotion_food_pricing"])
+ intval($data["command"]["promotion_shipping_pricing"])
+ $total_additionnal_fee;
$data["command"]["total_pricing"] = $data["command"]["promotion_total_pricing"];
$data["command"]["preorder_total_pricing"] =
intval($data["command"]["preorder_food_pricing"])
+ intval($data["command"]["preorder_shipping_pricing"])
+ $total_additionnal_fee;
$totalWithoutFee =
intval($data["command"]["promotion_total_pricing"]) - $total_additionnal_fee;
$data["command"]["remise"] = (string) (
100 - $this->getRemise(
intval($data["command"]["total_pricing"]) - $total_additionnal_fee,
$totalWithoutFee
)
);
}
//check if rate
$rating = 0;
$comment = '';
$repo = $this->entityManager->getRepository(EntityDeliveryRating::class);
$rate = $repo->findOneBy([
'commandId' => $command->getId()
]);
if ($rate != null) {
$rating = $rate->getRating();
$comment = $rate->getComment();
}
$data["command"]["rating"] = $rating;
$data["command"]["comment"] = $comment;
return new Response($this->serializer->serialize($this->okResponseBlob($data), 'json'), 200);
}
/**
* @Route("mobile/api/command/all/v4/get", name="user_mobile_v4_get_all_command", methods={"GET"})
*/
public function getApiAllCommandWithVoucherAction()
{
$currentToken = $this->get('security.token_storage')->getToken();
$id = $currentToken->getUser()->getId();
$start = date('Y-m-d', strtotime('-90 days'));
$end = date('Y-m-d', strtotime('+1 day'));
$conn = $this->entityManager->getConnection();
$sql = "
SELECT *
FROM command
WHERE client_id = :id
AND start_date BETWEEN :start AND :end
AND restaurant_id IS NOT NULL
ORDER BY last_update DESC
";
$stmt = $conn->prepare($sql);
$stmt->execute([
'id' => $id,
'start' => $start,
'end' => $end,
]);
$rows = $stmt->fetchAll();
$result = ['commands' => []];
foreach ($rows as $row) {
$result['commands'][] =
$this->forMobileWithVoucherCommandToArrayFromRow($row);
}
return new Response(
$this->serializer->serialize(
$this->okResponseBlob($result),
'json'
)
);
}
/**
* @Route("mobile/api/command/v4/get", name="user_mobile_v4_get_command", methods={"POST"})
*/
public function getApiCommandWithVoucherAction()
{
$em = $this->entityManager;
$currentToken = $this->get('security.token_storage')->getToken();
$id = (int) $currentToken->getUser()->getId();
$command_array = [
'commands' => []
];
$batchSize = 100;
$offset = 0;
$today = date('Y-m-d');
do {
/** -------------------------
* Fetch IDs only
* -------------------------
*/
$commandIds = $em->createQuery(
'SELECT c.id
FROM App:Command c
WHERE c.clientId = :id
AND (
c.startDate = :startDate
OR (c.startDate < :startDate AND c.state < :deliveredState)
)
AND c.order_type IS NULL
ORDER BY c.lastUpdate DESC'
)
->setParameter('id', $id)
->setParameter('startDate', $today)
->setParameter('deliveredState', 3)
->setFirstResult($offset)
->setMaxResults($batchSize)
->getScalarResult();
foreach ($commandIds as $row) {
try {
/** -------------------------
* Load command
* -------------------------
*/
$command = $em->getRepository(Command::class)->find($row['id']);
if (!$command) {
continue;
}
$tmp = $this->forMobileWithVoucherCommandToArray($command);
/** -------------------------
* Payment bill
* -------------------------
*/
$paymentBill = $em->getRepository(PaymentBill::class)
->findOneBy(['command' => $command->getId()]);
if ($paymentBill) {
$additionalFee = intval($paymentBill->getAdditionalFeesTotalPrice());
$tmp['additionnal_fees'] = $additionalFee;
$tmp['promotion_total_pricing'] =
intval($tmp['promotion_total_pricing']) + $additionalFee;
$tmp['total_pricing'] =
intval($tmp['total_pricing']) + $additionalFee;
$tmp['preorder_total_pricing'] =
intval($tmp['preorder_total_pricing']) + $additionalFee;
}
$command_array['commands'][] = $tmp;
} catch (\Throwable $e) {
$this->get('logger')->info(
'Command ID ' . $row['id'] . ' skipped: ' . $e->getMessage()
);
continue;
}
}
$em->clear();
$offset += $batchSize;
} while (count($commandIds) === $batchSize);
return new Response(
$this->serializer->serialize(
$this->okResponseBlob($command_array),
'json'
)
);
}
/**
* @Route("mobile/api/command/delivery_rating_pending/v4/get", name="user_mobile_v4_get_delivery_rating_pending", methods={"POST"})
*/
public function getDeliveryRatingPending(Request $request){
$currentToken = $this->get('security.token_storage')->getToken();
$json_data = $request->getContent();
$data = json_decode($json_data,true);
$delivery_rating_pending = [
"command_id" => null,
"delivery_man_image" => null,
"delivery_man_name" => null,
"articles" => null,
"seller_name" => null,
"seller_image" => null,
"delivery_rating" => 3,
"article_rating" => 3,
"article_comment" => "",
"delivery_comment" => "",
"speedRating" => 3,
"respectOfGeolocation" => 3,
"attidudeOfDeliveryMan" => 3,
"groomingOfDeliveryMan" => 3
];
$foods =[];
if(isset($data['command_id'])){
$delivery_rating_pending['command_id']=$data['command_id'];
$command = $this->entityManager->getRepository(Command::class)->find($data['command_id']);
if($command ){
if($command->getState()==3){
$livreur = $this->entityManager->getRepository(Livreur::class)->find($command->getLivreurId());
if($livreur){
$delivery_rating_pending['delivery_man_image'] = "https://kaba-delivery-pictures-store.s3.eu-west-3.amazonaws.com/employee_picture/".$livreur->getProfile()??"";
$delivery_rating_pending['delivery_man_name'] = $livreur->getName();
}else{
return new Response($this->serializer->serialize($this->errorResponseBlob([]), 'json'));
}
foreach ($command->getFoodCommand() as $i => $food_command) {
$food = $food_command["food_entity"];
array_push($foods,['name'=>$food['name'],'id'=>$food['id'],'rating'=>3]);
}
$delivery_rating_pending['articles'] =$foods;
$restaurant = $this->entityManager->getRepository(RestaurantConfig::class)->find($command->getRestaurantId());
$delivery_rating_pending['seller_name'] =$restaurant->getName();
$delivery_rating_pending['seller_image'] =$restaurant->getPic();
return new Response($this->serializer->serialize($this->okResponseBlob($delivery_rating_pending), 'json'));
}else{
return new Response($this->serializer->serialize($this->errorResponseBlob("Order is not delivered"), 'json'));
}
}else{
return new Response($this->serializer->serialize($this->errorResponseBlob("Command null"), 'json'));
}
}else{
return new Response($this->serializer->serialize($this->errorResponseBlob([]), 'json'));
}
}
/**
* @Route("mobile/api/command/rating/v4/get", name="user_mobile_v4_get_rating", methods={"GET"})
*/
public function getApiRatingAction()
{
$repo = $this->entityManager->getRepository(EntityDeliveryRating::class);
$ratings = $this->entityManager->createQuery(
' SELECT
r.speedRating AS speedRating,
r.respectOfGeolocation AS respectOfGeolocation,
r.attidudeOfDeliveryMan AS attidudeOfDeliveryMan,
r.groomingOfDeliveryMan AS groomingOfDeliveryMan
FROM App\V4Bundle\Entity\DeliveryRating r'
)->getArrayResult();
$speedSum = 0;
$geoSum = 0;
$attitudeSum = 0;
$appearanceSum = 0;
$speedCount = 0;
$geoCount = 0;
$attitudeCount = 0;
$appearanceCount = 0;
foreach ($ratings as $rating) {
if ($rating['speedRating'] != 0) {
$speedSum += $rating['speedRating'];
$speedCount++;
}
if ($rating['respectOfGeolocation'] != 0) {
$geoSum += $rating['respectOfGeolocation'];
$geoCount++;
}
if ($rating['attidudeOfDeliveryMan'] != 0) {
$attitudeSum += $rating['attidudeOfDeliveryMan'];
$attitudeCount++;
}
if ($rating['groomingOfDeliveryMan'] != 0) {
$appearanceSum += $rating['groomingOfDeliveryMan'];
$appearanceCount++;
}
}
$speedAvg = $speedCount > 0 ? $speedSum / $speedCount : 0;
$geoAvg = $geoCount > 0 ? $geoSum / $geoCount : 0;
$attitudeAvg = $attitudeCount > 0 ? $attitudeSum / $attitudeCount : 0;
$appearanceAvg = $appearanceCount > 0 ? $appearanceSum / $appearanceCount : 0;
$speedAvg = max($speedAvg, 3);
$geoAvg = max($geoAvg, 3);
$attitudeAvg = max($attitudeAvg, 3);
$appearanceAvg = max($appearanceAvg, 3);
$averages = [];
if ($speedCount > 0) $averages[] = $speedAvg;
if ($geoCount > 0) $averages[] = $geoAvg;
if ($attitudeCount > 0) $averages[] = $attitudeAvg;
if ($appearanceCount > 0) $averages[] = $appearanceAvg;
$finalRating = count($averages) > 0 ? array_sum($averages) / count($averages) : 0;
$data = [
"speed" => round($speedAvg, 1),
"geolocation" => round($geoAvg, 1),
"attitude" => round($attitudeAvg, 1),
"appearance" => round($appearanceAvg, 1),
"final" => round($finalRating, 1),
"count" => $speedCount
];
return new JsonResponse($data);
}
/**
* @Route("mobile/api/command/v4/rate", name="user_mobile_v4_rate_command", methods={"POST"})
*/
public function commandDeliveryManRateAction(Request $request)
{
$json_data = $request->getContent();
$data = json_decode($json_data, true);
$currentToken = $this->get('security.token_storage')->getToken();
$id = $currentToken->getUser()->getId();
if ($id != null) {
if (
isset($data["command_id"]) && $data["command_id"] != null
) {
/**
* @var Command $command
*/
$command = $this->entityManager->getRepository(Command::class)->find(intval($data["command_id"]));
if ($command != null) {
/*check if already rated*/
$em =$this->entityManager;
$repo = $this->entityManager->getRepository(EntityDeliveryRating::class);
$rate = $repo->findOneBy(['commandId' => $command->getId()]);
if ($rate != null) {
$rate->setDeliveryRating(intval($data["delivery_rating"]));
if (isset($data["delivery_comment"]) && $data["delivery_comment"] != null) {
$rate->setDeliveryComment($data["delivery_comment"]);
}
$rate->setCreatedAt(strtotime(date('Y-m-d H:i:s')));
} else {
$rating = new EntityDeliveryRating();
$rating->setUserId($id);
$rating->setCommandId(intval($data["command_id"]));
$rating->setLivreurId($command->getLivreurId());
$rating->setDeliveredAt($command->getEndOfDelivery());
$rating->setDeliveryRating(intval($data["delivery_rating"]));
if (isset($data["command_id"]) && $data["command_id"] != null) {
$rating->setCommandId($data["command_id"]);
}
if (isset($data["delivery_rating"]) && $data["delivery_rating"] != null) {
$rating->setDeliveryRating($data["delivery_rating"]);
}
if(isset($data['articles'])&& $data['articles']!=null){
$rating->setArticlesRating($data['articles']);
}
if (isset($data["article_comment"]) && $data["article_comment"] != null) {
$rating->setArticleComment($data["article_comment"]);
}
if (isset($data["delivery_comment"]) && $data["delivery_comment"] != null) {
$rating->setDeliveryComment($data["delivery_comment"]);
}
if (isset($data["speedRating"]) && $data["speedRating"] != null) {
$rating->setSpeedRating($data["speedRating"]);
}
if (isset($data["respectOfGeolocation"]) && $data["respectOfGeolocation"] != null) {
$rating->setRespectOfGeolocation($data["respectOfGeolocation"]);
}
if (isset($data["attidudeOfDeliveryMan"]) && $data["attidudeOfDeliveryMan"] != null) {
$rating->setAttidudeOfDeliveryMan($data["attidudeOfDeliveryMan"]);
}
if (isset($data["groomingOfDeliveryMan"]) && $data["groomingOfDeliveryMan"] != null) {
$rating->setGroomingOfDeliveryMan($data["groomingOfDeliveryMan"]);
}
$rating->setRestaurantId($command->getRestaurantId());
$rating->setCreatedAt(strtotime(date('Y-m-d H:i:s')));
$em->persist($rating);
// update command
$command->setHaveRating(true);
$em->flush();
$livreur = $this->entityManager
->getRepository(Livreur::class)
->find($rating->getLivreurId());
$new_rating = (intval($data["attidudeOfDeliveryMan"]) + intval($data["groomingOfDeliveryMan"])) / 2;
$deliveries_rating = $this->entityManager
->getRepository(EntityDeliveryRating::class)
->findBy(['livreurId' => $livreur->getId()]);
$total_rating = 0;
$valid_count = 0;
if ($deliveries_rating && count($deliveries_rating) > 0) {
foreach ($deliveries_rating as $r) {
if ($r->getDeliveryRating() !== null) {
$total_rating += $r->getDeliveryRating();
$valid_count++;
}
}
$total_livreur_rating = ($total_rating + $new_rating) / ($valid_count + 1);
$livreur->setRating($total_livreur_rating);
} else {
$livreur->setRating($new_rating);
}
$em->persist($livreur);
$em->flush();
//food rating
$query = $this->entityManager->createQuery('
SELECT r FROM App\V4Bundle\Entity\DeliveryRating r
WHERE r.restaurantId = :id
')
->setParameter('id', (int) $command->getRestaurantId());
$rates = $query->getResult();
$ratings = json_decode($this->serializer->serialize($rates,'json'), true);
$articles = $data['articles'];
if(count($articles)==1){
if($ratings !=null && count($ratings)>0){
$articles = $data['articles'];
$total_rating=0;
$total_count_rating=0;
foreach($ratings as $rating){
if($rating["articlesRating"]!=null && count($rating["articlesRating"])>0){
foreach ($rating["articlesRating"] as $art) {
if($data['articles'][0]['id']==$art['id']){
if($art['rating']!=0){
$total_rating+=$art['rating'];
$total_count_rating++;
break;
}
}
}
}else{
continue;
}
}
$total_article_rating = ($total_rating+$data['articles'][0]['rating'])/($total_count_rating+1);
$article_entity =$this->entityManager->getRepository(Food::class)->find($data['articles'][0]['id']);
$article_entity->setRating(round($total_article_rating, 1));
$em->persist($article_entity);
$em->flush();
}else{
$article_entity =$this->entityManager->getRepository(Food::class)->find($data['articles'][0]['id']);
$article_entity->setRating($data['articles'][0]['rating']);
$em->persist($article_entity);
$em->flush();
}
}
}
return new JsonResponse($this->serializer->serialize($this->okResponseBlob(null), 'json'));
} else {
return new JsonResponse($this->serializer->serialize($this->errorResponseBlob("No command"), 'json'));
}
} else {
return new JsonResponse($this->$this->serializer->serialize($this->errorResponseBlob("Invalid Parameters", 'json')));
}
} else {
return new JsonResponse($this->serializer->serialize($this->errorResponseBlob("Invalid token"), 'json'));
}
}
/**
* @Route("mobile/api/command/v4/rate/test", name="user_mobile_v4_rate_command_test", methods={"POST"})
*/
public function testRate(){
$currentToken = $this->get('security.token_storage')->getToken();
$id = $currentToken->getUser()->getId();
$articleId = 561;
$em = $this->entityManager;
$conn = $em->getConnection();
$sql = "
SELECT *
FROM delivery_rating r
WHERE r.restaurant_id = :restaurantId
AND r.articles_rating IS NOT NULL
AND r.articles_rating != ''
AND JSON_CONTAINS(r.articles_rating, :articleJson, '$') = 1
";
$stmt = $conn->prepare($sql);
$stmt->execute([
'restaurantId' => 15,
'articleJson' => json_encode(["id" => $articleId]),
]);
$ratings = $stmt->fetchAllAssociative();
$res['rate_count'] = count($ratings);
$article_comments = [];
foreach ($ratings as $rating) {
$comment = [
'rating' => 0,
'comment' => $rating['article_comment'],
'client_name'=>"",
'client_pic' =>'',
];
if($rating['articles_rating']!=null){
$articles =json_decode($rating['articles_rating'],true);
for($i=0;$i<count($articles); $i++){
if($articles[$i]['id']==$articleId){
$comment['rating'] = $articles[$i]['rating'];
break;
}
}
}
$command = $em->getRepository(Command::class)->find($rating['command_id']);
$client = $em->getRepository(Client::class)->find($command->getClientId());
if ($client != null) {
$comment['client_name'] = $client->getNickname();
$comment['client_pic'] = $client->getProfilePicture();
if($comment['comment']!=null){
array_push($article_comments, $comment);
}
}
}
return new JsonResponse($article_comments);
}
/**
* @Route("/subscription/user-transaction/get", name="subscription_user_transaction", methods={"GET"})
*/
public function SubscriptionGetUserTransaction(Request $request): JsonResponse
{
$apiKey = trim((string) $request->headers->get('X-API-KEY', '')); // header canonical
$expectedApiKey = '7DCPbXNtTXMpifOcfOJCbXBQctN8cuII';
if ($apiKey === '' || strlen($apiKey) !== strlen($expectedApiKey) || !hash_equals($expectedApiKey, $apiKey)) {
return new JsonResponse(['message' => 'Clé API invalide ou manquante'], 401);
}
$data = json_decode($request->getContent(), true) ?? [];
$transaction = $this->entityManager->getRepository(Transaction::class)->findOneBy(
['userId' => $data['user_id'],'transactionMotifId'=>2],
['createdDate' => 'DESC']
);
if (!$transaction) {
return new JsonResponse(['transaction' => null], 200);
}
$json = $this->serializer->serialize($transaction, 'json');
return new JsonResponse(['transaction' => json_decode($json, true)], 200);
}
public function createPaymentBill($data, $command_id)
{
$command = $this->entityManager->getRepository(Command::class)->find($command_id);
$payment_bill = new PaymentBill();
$payment_bill
->setShippingPricing(isset($data["shipping_pricing"]) ? $data["shipping_pricing"] : -1)
->setPromotionShippingPricing(isset($data["promotion_shipping_pricing"]) ? $data["promotion_shipping_pricing"] : -1)
->setPromotionPricing(isset($data["promotion_pricing"]) ? $data["promotion_pricing"] : -1)
->setCommandPricing(isset($data["command_pricing"]) ? $data["command_pricing"] : -1)
->setRemise(isset($data["remise"]) ? $data["remise"] : -1)
->setTotalPricing(isset($data["total_pricing"]) ? $data["total_pricing"] : -1)
->setTotalNormalPricing(isset($data["total_normal_pricing"]) ? $data["total_normal_pricing"] : -1)
->setAccountBalance(isset($data["account_balance"]) ? $data["account_balance"] : -1)
->setOutOfRange(isset($data["out_of_range"]) ? $data["out_of_range"] : false)
->setPayAtDelivery(isset($data["pay_at_delivery"]) ? $data["pay_at_delivery"] : false)
->setPrepaid(isset($data["prepayed"]) ? $data["prepayed"] : false)
->setTrustful(isset($data["trustful"]) ? $data["trustful"] : -1)
->setMaxPay(isset($data["max_pay"]) ? $data["max_pay"] : -1)
->setCookingTime(isset($data["cooking_time"]) ? $data["cooking_time"] : -1)
->setCanPreorder(isset($data["can_preorder"]) ? $data["can_preorder"] : -1)
->setDiscount(isset($data["discount"]) ? $data["discount"] : "")
->setOpenType(isset($data["open_type"]) ? $data["open_type"] : -1)
->setWorkingHour(isset($data["working_hour"]) ? $data["working_hour"] : "")
->setReason(isset($data["reason"]) ? $data["reason"] : "")
->setDeliveryFrames(isset($data["delivery_frames"]) && is_array($data["delivery_frames"]) ? $data["delivery_frames"] : null)
->setBillBuilt(isset($data["is_bill_built"]) ? $data["is_bill_built"] : false)
->setCheckedOpen(isset($data["checked_open"]) ? $data["checked_open"] : false)
->setTotalPreorderPricing(isset($data["total_preorder_pricing"]) ? $data["total_preorder_pricing"] : -1)
->setKabaPoint(isset($data["kaba_point"]) ? $data["kaba_point"] : ["value" => null])
->setEligibleVouchers(isset($data["eligible_vouchers"]) ? $data["eligible_vouchers"] : ["value" => null])
->setAdditionalFees(isset($data["additional_fees"]) ? $data["additional_fees"] : ["value" => null])
->setAdditionalFeesTotalPrice(isset($data["additional_fees_total_price"]) ? $data["additional_fees_total_price"] : -1)
->setCommandId($command);
$this->entityManager->persist($payment_bill);
$this->entityManager->flush();
return new Response("Success", 200);
}
private function madeUpCommandItemWithVoucher(Command $command)
{
$tmp = [];
$type = 1;
$user = $this->entityManager->getRepository(Client::class)->find($command->getClientId());
if ($user != null) {
$type = filter_var($user->getUsername(), FILTER_VALIDATE_EMAIL) ? 2 : 1;
}
$shipping_address = $command->getShippingAddress();
$restaurant = $this->entityManager->getRepository(RestaurantConfig::class)->find($command->getRestaurantId());
$addresss = $this->entityManager->getRepository(Adresses::class)->find(intval($shipping_address["id"]));
$address = $this->addressForMobileToArray($addresss);
$standard_price = $this->shippingPricing($restaurant->getId(), $address, $type);
$billing = intval($standard_price["billing"]);
$promotion_billing = intval($command->getShippingPricing());
$voucher_billing = 0;
$voucher_food_price = 0;
$is_voucher_used = 0;
$is_food_voucher_used = 0;
$is_billing_voucher_used = 0;
$tmp["food_list"] = [];
$state = intval($command->getState());
if ($state == 2 || $state == 3) {
$livreur = $this->entityManager->getRepository(Livreur::class)->find($command->getLivreurId());
if ($livreur != null) {
$tmp["livreur"] = [];
$tmp["livreur"]["id"] = $livreur->getId();
$tmp["livreur"]["name"] = $livreur->getName();
$tmp["livreur"]["workcontact"] = $livreur->getWorkContact();
$pic = '';
$employee = $this->entityManager->getRepository(Employee::class)->find(intval($livreur->getEmployeeId()));
if ($employee != null) {
$pic = 'employee_picture/' . $employee->getFileName();
}
$tmp["livreur"]["pic"] = $pic;
}
}
$price_remise = 0;
$price_command = 0;
$is_promo = 0;
$is_preorder = 0;
foreach ($command->getFoodCommand() as $i => $food_command) {
$food = $food_command["food_entity"];
if ($i == 0) {
$shipping = $food_command["food_shipping"];
if ($shipping["is_shipping_promo"] == 1) {
$is_promo = 1;
$billing = $shipping["shipping_pricing"];
}
}
$price_command += intval($food["price"]) * intval($food_command["quantity"]);
if ($food["promotion"] == 1) { /*if food is in promotion*/
$price_remise += intval($food["promotion_price"]) * intval($food_command["quantity"]);
$is_promo = 1;
} else {
$price_remise += intval($food["price"]) * intval($food_command["quantity"]);
}
$food["quantity"] = $food_command["quantity"];
$food["promotion_price"] = '' . $food["promotion_price"];
array_push($tmp["food_list"], $food);
}
if ($command->getPreOrder() == 1) {
$price_remise = $price_command;
$is_preorder = 1;
}
$total_without_remise = $price_command + $billing;
$total_with_remise = $price_remise + $promotion_billing;
$tmp["kaba_point_used_amount"] = 0;
if ($command->getKabaPoint() != null) {
$is_promo = 1;
$tmp["kaba_point_used_amount"] = $command->getKabaPointAmount();
}
$tmp["id"] = $command->getId();
$tmp["foods_count"] = count($command->getFoodCommand());
$tmp["is_payed_at_arrival"] = $command->getPayAtDelivery();
$tmp["state"] = $state;
$tmp["infos"] = $command->getInfos();
$tmp["restaurant_entity"] = [];
$tmp["restaurant_entity"]["id"] = $restaurant->getId();
$tmp["restaurant_entity"]["name"] = $restaurant->getName();
$tmp["restaurant_entity"]["pic"] = '/' . $this->getParameter('rp') . '/' . $restaurant->getPic();
$tmp["remise"] = '' . (100 - $this->getRemise($total_without_remise, $total_with_remise));
$tmp["out_of_range"] = $standard_price["out_of_range"];
$tmp["shipping_address"] = $shipping_address;
if (isset($tmp["shipping_address"]["user"])) {
$tmp["shipping_address"]["user"] = [];
}
$tmp["is_promotion"] = $is_promo;
$tmp["is_preorder"] = $is_preorder;
$tmp["shipping_pricing"] = intval($billing);
$tmp["food_pricing"] = intval($price_command);
$tmp["total_pricing"] = intval($billing + $price_command);
$tmp["promotion_shipping_pricing"] = intval($promotion_billing);
$tmp["promotion_food_pricing"] = intval($price_remise);
$tmp["promotion_total_pricing"] = intval($promotion_billing + $price_remise);
$tmp["preorder_shipping_pricing"] = intval($promotion_billing);
$tmp["preorder_food_pricing"] = intval($price_command);
$tmp["preorder_total_pricing"] = intval($promotion_billing + $price_command);
$tmp["voucher_entity"] = [];
$voucher_datas = $this->processVoucherDatas($command, $promotion_billing, $billing, $price_remise);
if ($voucher_datas["is_voucher_used"]) {
$tmp["is_promotion"] = 1;
$tmp["promotion_food_pricing"] = $voucher_datas["price_remise"];
$tmp["promotion_shipping_pricing"] = $voucher_datas["shipping_pricing"];
$tmp["promotion_total_pricing"] = intval($voucher_datas["price_remise"]) + intval($voucher_datas["shipping_pricing"]);
$tmp["remise"] = '' . (100 - $this->getRemise($total_without_remise, $tmp["promotion_total_pricing"]));
$tmp["is_voucher_used"] = 1;
if ($voucher_datas["voucher_id"] != null) {
$voucher = $this->entityManager->getRepository(Voucher::class)->find($voucher_datas["voucher_id"]);
if ($voucher != null) {
$tmp["voucher_entity"] = $this->voucherToArrayLite($voucher);
$tmp["voucher_entity"]["id"] = $voucher->getId();
}
}
}
$tmp["preorder"] = $command->getPreOrder();
$tmp["preorder_hour"] = null;
if ($command->getPreOrder() == 1) {
$preorder_hour = $this->entityManager->getRepository(PreorderCommandDetails::class)->findOneBy([
'commandId' => $command->getId()
]);
if ($preorder_hour != null) {
$tmp["preorder_hour"]["start"] = $preorder_hour->getStart();
$tmp["preorder_hour"]["end"] = $preorder_hour->getEnd();
$tmp["preorder_discount"] = $preorder_hour->getDiscount();
}
}
$tmp["passphrase"] = $command->getPassPhrase();
$tmp["last_update"] = strtotime($command->getLastUpdate());
$tmp["reason"] = $command->getReason();
$haveBonus = $this->entityManager->getRepository(PayBonus::class)->findOneBy(["clientId" => $command->getClientId(), "commandId" => $command->getId()]);
if ($haveBonus != null && $haveBonus->getOfferType() == '1') {
$tmp["is_promotion"] = 1;
$tmp["promotion_total_pricing"] -= $tmp["promotion_shipping_pricing"];
$tmp["promotion_shipping_pricing"] = 0;
$tmp["preorder_total_pricing"] -= $tmp["preorder_shipping_pricing"];
$tmp["preorder_shipping_pricing"] = 0;
$tmp["without_voucher_promotion_shipping_pricing"] = 0;
}
return $tmp;
}
private function getRestaurantId($food_command)
{
if (!($food_command != null && count($food_command) > 0))
return -1;
$food_id = $food_command[0]["food_id"];
$bdd_food = $this->entityManager->getRepository(Food::class)->find(intval($food_id));
return $bdd_food->getRestaurantId();
}
private function getAdress($shipping_address_id)
{
if ($shipping_address_id == null)
return -1;
$address = $this->entityManager->getRepository(Adresses::class)->find($shipping_address_id);
if ($address == null)
return -1;
$address_in_array = $this->addressForMobileToArray($address);
return $address_in_array;
}
private function getCommandDetails2($food_command, $restaurant_id, $address, $preorder, $voucher_id = null, $user_id = null, $use_kaba_point = false)
{
$price = 0;
$without_promotion_price = 0;
$without_promotion_billing = 0;
$food_litteral = "";
$haveBillingDiscount = false;
$is_voucher_used = false;
$is_food_voucher_used = false;
$is_billing_voucher_used = false;
$voucher_billing = 0;
$voucher_food_price = 0;
$voucher_owner_food_price_gain = 0;
$voucher_owner_billing_gain = 0;
$check_voucher_valid = $this->checkIfVoucherValid($user_id, $voucher_id);
$check_voucher_owners = $this->entityManager->getRepository(VoucherOwner::class)->findOneBy([
'voucherId' => $voucher_id
]);
$kabaPoint = null;
$type = 1;
$user = $this->entityManager->getRepository(Client::class)->find($user_id);
if ($user != null)
$type = filter_var($user->getUsername(), FILTER_VALIDATE_EMAIL) ? 2 : 1;
$standard_price = $this->shippingPricing($restaurant_id, $address, $type);
$restaurant = $this->entityManager->getRepository(RestaurantConfig::class)->find($restaurant_id);
$billing = $standard_price["billing"];
$voucher_billing = intval($billing);
$is_voucher_on_billing_already_applyed = false;
$without_promotion_billing = $standard_price["billing"];
$without_promotion_billing_for_email = $standard_price["email_account_billing"];
$without_promotion_billing_for_PhoneNumber = $standard_price["phoneNumber_account_billing"];
$extra_shipping_pricing = intval($standard_price["email_account_billing"]) - intval($standard_price["phoneNumber_account_billing"]);
$with_discount_billing_for_email = $standard_price["email_account_billing"];
$with_discount_billing_for_PhoneNumber = $standard_price["phoneNumber_account_billing"];
$voucherBillingForPhoneNumber = intval($standard_price["phoneNumber_account_billing"]);
$voucherBillingForEmail = intval($standard_price["email_account_billing"]);
$preorderBillingForPhoneNumber = intval($standard_price["email_account_billing"]);
$preorderBillingForEmail = intval($standard_price["phoneNumber_account_billing"]);
$is_shipping_promo = 0;
if ($restaurant != null && $address != null) {
$distance = $this->getDistance(
$address["location"],
$restaurant->getLocation()
);
$the_distance = $distance;
$promotion = $this->checkEligiblePromotionV2($the_distance, $restaurant_id, $food_command, $user);
if ($promotion["found"] == true) {
$billing = $promotion["billing"];
$with_discount_billing_for_email = $promotion["billing"];
$with_discount_billing_for_PhoneNumber = $promotion["billing"];
$is_shipping_promo = 1;
$haveBillingDiscount = true;
}
}
foreach ($food_command as $i => $food) {
if ($i != 0) $food_litteral .= "+";
$food_command[$i]["food_entity"] = [];
$foods = $this->entityManager->getRepository(Food::class)->find($food["food_id"]);
$food_litteral .= $foods->getName();
if ($foods->getPromotion() == 0) {
$price += intval($foods->getPrice()) * intval($food["quantity"]);
} else {
$promotion_price = 1;
if ($foods->getPromotionPrice() != null) {
$promotion_price = intval($foods->getPromotionPrice());
} else {
$promotion_price = intval($foods->getPrice());
}
$price += ($promotion_price * intval($food["quantity"]));
}
$without_promotion_price += (intval($foods->getPrice()) * intval($food["quantity"]));
$vouch_price = intval($foods->getPrice()) * intval($food["quantity"]);
$vouch_price_for_individual_food = intval($foods->getPrice());
$reduction = 0;
$owner_gain = 0;
if (
$check_voucher_valid["valid"] == true ||
sizeof($check_voucher_valid["products"]) == 0
) {
if (
in_array(intval($food["food_id"]), $check_voucher_valid["products"])
|| sizeof($check_voucher_valid["products"]) == 0
) {
if ($check_voucher_valid["type"] == 1 || $check_voucher_valid["type"] == 3) {
if ($check_voucher_valid["category"] == 1) {
$reduction = (intval($foods->getPrice()) * $check_voucher_valid["value"]) / 100;
$is_voucher_used = true;
$is_food_voucher_used = true;
} else {
$reduction = $check_voucher_valid["value"];
$is_voucher_used = true;
$is_food_voucher_used = true;
}
}
if (($check_voucher_valid["type"] == 2 || $check_voucher_valid["type"] == 3) &&
in_array($restaurant_id, $check_voucher_valid["restaurants"])
) {
if (!$is_voucher_on_billing_already_applyed) {
if ($check_voucher_valid["category"] == 1) {
$reductions = ($voucher_billing * $check_voucher_valid["value"]) / 100;
$voucher_billing -= $reductions;
$voucherBillingForPhoneNumber -= $reductions;
$voucherBillingForEmail -= $reductions;
$is_voucher_used = true;
$is_billing_voucher_used = true;
$is_voucher_on_billing_already_applyed = true;
} else {
$voucher_billing -= $check_voucher_valid["value"];
$voucherBillingForPhoneNumber -= $check_voucher_valid["value"];
$voucherBillingForEmail -= $check_voucher_valid["value"];
$is_voucher_used = true;
$is_billing_voucher_used = true;
$is_voucher_on_billing_already_applyed = true;
$haveBillingDiscount = true;
}
}
}
if ($check_voucher_owners != null) {
if ($check_voucher_valid["voucher"] != null) {
$voucher = $check_voucher_valid["voucher"];
if ($voucher["is_rewarded"] == 1 && $voucher["reward_on_food"] == 1) {
if ($is_billing_voucher_used && ($voucher["reward_type"] == 2 || $voucher["reward_type"] == 3)) {
$voucher_owner_billing_gain = (intval($billing) * $voucher["reward_percentage_value"]) / 100;
break;
}
if ($is_food_voucher_used && ($voucher["reward_type"] == 1 || $voucher["reward_type"] == 3)) {
$owner_gain = (intval($vouch_price) * $voucher["reward_percentage_value"]) / 100;
}
}
}
}
}
}
if ($reduction >= $vouch_price) {
$final_food_price = 0;
} else {
$final_food_price = $vouch_price - ($reduction * intval($food["quantity"]));
}
if ($reduction >= $vouch_price_for_individual_food) {
$final_food_price_for_individual_food = 0;
} else {
$final_food_price_for_individual_food = $vouch_price_for_individual_food - $reduction;
}
$voucher_food_price += $final_food_price;
$voucher_owner_food_price_gain += $owner_gain;
$food_command[$i]["food_entity"] = $this->foodApiForMobileToArray($foods);
$food_command[$i]["food_entity"]["promotion_voucher"] = 0;
if ($is_voucher_used && $is_food_voucher_used) {
$food_command[$i]["food_entity"]["promotion_voucher"] = 1;
$food_command[$i]["food_entity"]["promotion"] = 1;
$food_command[$i]["food_entity"]["promotion_price"] = '' . $final_food_price_for_individual_food;
}
$food_command[$i]["food_shipping"] = [];
$food_command[$i]["food_shipping"]["is_shipping_promo"] = $is_shipping_promo;
$food_command[$i]["food_shipping"]["shipping_pricing"] = intval($without_promotion_billing);
$food_command[$i]["food_shipping"]["phoneNumber_shipping_pricing"] = intval($without_promotion_billing_for_PhoneNumber);
$food_command[$i]["food_shipping"]["email_shipping_pricing"] = intval($without_promotion_billing_for_email);
}
$adress_entity = $this->entityManager->getRepository(Adresses::class)->findOneBy(['location' => $address["location"]]);
$additional_fees = $this->getAdditionalFeesPrice($food_command, $price, $billing, $adress_entity, $restaurant);
$additional_fee_total_price = $this->getAdditionalFeesTotalPricing($additional_fees);
$food_price = $price;
$food_billing = $billing;
$data = [];
$preorder_config = $this->entityManager->getRepository(PreOrderConfig::class)->findBy(
array(),
array('id' => 'DESC'),
1,
0
);
$discount = 0;
if ($preorder_config != null) {
$config = $preorder_config[0];
$discount = $config->getReduction();
}
$with_discount = ((100 - $discount) * $without_promotion_billing / 100);
$preorderBillingForPhoneNumber = ((100 - $discount) * $without_promotion_billing_for_PhoneNumber / 100);
$preorderBillingForEmail = ((100 - $discount) * $without_promotion_billing_for_email / 100);
$data["without_promo"]["pre_order"]["total"] = $with_discount + $without_promotion_price + $additional_fee_total_price;
$data["without_promo"]["pre_order"]["billing"] = $with_discount;
if ($preorder == 1) {
$food_price = $without_promotion_price;
$food_billing = $with_discount;
$with_discount_billing_for_email = $preorderBillingForEmail;
$with_discount_billing_for_PhoneNumber = $preorderBillingForPhoneNumber;
$haveBillingDiscount = true;
}
$voucher_food_price = intval($voucher_food_price) < 0 ? 0 : $voucher_food_price;
$voucher_billing = intval($voucher_billing) < 0 ? 0 : $voucher_billing;
if ($is_billing_voucher_used) {
$food_billing = $voucher_billing;
$with_discount_billing_for_email = $voucherBillingForEmail;
$with_discount_billing_for_PhoneNumber = $voucherBillingForPhoneNumber;
$haveBillingDiscount = true;
}
if ($is_food_voucher_used) {
$food_price = $voucher_food_price;
}
$is_kaba_point_used = false;
$kaba_point_used_amount = 0;
if ($use_kaba_point) {
$kabaPoint = $this->getMiniKabaPointBalance($user_id, $without_promotion_billing);
$data["kaba_point"] = $kabaPoint;
$amount = intval($kabaPoint["amount_to_reduce"]);
if ($kabaPoint['can_be_used']) {
$haveBillingDiscount = true;
$is_kaba_point_used = true;
if ($amount >= $without_promotion_billing) {
$billing = 0;
$food_billing = $billing;
$kaba_point_used_amount = $without_promotion_billing;
$with_discount_billing_for_email = $amount >= $without_promotion_billing_for_email ? 0 : $without_promotion_billing_for_email - $amount;
$with_discount_billing_for_PhoneNumber = $amount >= $without_promotion_billing_for_PhoneNumber ? 0 : $without_promotion_billing_for_PhoneNumber - $amount;
} else {
$kaba_point_used_amount = $amount;
$billing = $without_promotion_billing - $amount;
$food_billing = $billing;
$with_discount_billing_for_email = $without_promotion_billing_for_email - $amount;
$with_discount_billing_for_PhoneNumber = $without_promotion_billing_for_PhoneNumber - $amount;
}
} else {
$data["kaba_point"] = $kabaPoint;
}
} else {
$data["kaba_point"] = $kabaPoint;
}
$data["voucher_pricing"] = [];
$data["voucher_pricing"]["valid"] = $check_voucher_valid["valid"];
$data["voucher_pricing"]["command_pricing"] = intval($voucher_food_price);
$data["voucher_pricing"]["shipping_pricing"] = intval($voucher_billing);
$data["voucher_pricing"]["total_pricing"] = intval($voucher_food_price + $voucher_billing + $additional_fee_total_price);
$data["voucher_pricing"]["owner"] = [];
if ($voucher_id == null) {
$data["voucher_pricing"]["owner"]["is_rewarded"] = null;
$data["voucher_pricing"]["owner"]["reward_on_food"] = null;
$data["voucher_pricing"]["owner"]["reward_cash_value"] = null;
$data["voucher_pricing"]["owner"]["reward_type"] = null;
} else {
$data["voucher_pricing"]["owner"]["is_rewarded"] = $check_voucher_valid["voucher"]["is_rewarded"];
$data["voucher_pricing"]["owner"]["reward_on_food"] = $check_voucher_valid["voucher"]["reward_on_food"];
$data["voucher_pricing"]["owner"]["reward_cash_value"] = $check_voucher_valid["voucher"]["reward_cash_value"];
$data["voucher_pricing"]["owner"]["reward_type"] = $check_voucher_valid["voucher"]["reward_type"];
}
$data["voucher_pricing"]["owner"]["reward_on_billing"] = intval($voucher_owner_billing_gain);
$data["voucher_pricing"]["owner"]["reward_on_food"] = intval($voucher_owner_food_price_gain);
$data["is_voucher_used"] = $is_voucher_used;
$data["is_food_voucher_used"] = $is_food_voucher_used;
$data["is_billing_voucher_used"] = $is_billing_voucher_used;
$data["discount"] = $discount;
$data["is_kaba_point_used"] = $is_kaba_point_used;
$data["kaba_point_used_amount"] = $kaba_point_used_amount;
$data["foods"] = $food_command;
$data["food_litteral"] = $food_litteral;
$data["food_price"] = $food_price;
$data["food_billing"] = $food_billing;
$data["food_total"] = $food_price + $food_billing;
$data["with_promo"]["price"] = $price + $additional_fee_total_price;
$data["with_promo"]["billing"] = $billing;
$data["with_promo"]["total"] = $billing + $price + $additional_fee_total_price;
$data["without_promo"]["price"] = intval($without_promotion_price + $additional_fee_total_price);
$data["without_promo"]["billing"] = intval($without_promotion_billing);
$data["without_promo"]["total"] = intval($without_promotion_billing + $without_promotion_price + $additional_fee_total_price);
$data["phoneNumber_shipping_pricing"] = intval($with_discount_billing_for_PhoneNumber);
$data["email_shipping_pricing"] = intval($with_discount_billing_for_email);
$data["base_shipping_pricing"] = intval($standard_price["billing"]);
$data["extra_shipping_pricing"] = $extra_shipping_pricing > 0 ? $extra_shipping_pricing : 0;
$data["haveBillingDiscount"] = $haveBillingDiscount;
return $data;
}
public function foodApiForMobileToArray($food)
{
$res = [];
$res["id"] = $food->getId();
$res["name"] = $food->getName();
$res["description"] = $food->getDescription();
$res["promotion"] = $this->checkFoodPromoState($food)["promo"];
$res["promotion_price"] = $food->getPromotionPrice() == null ? "0" : $food->getPromotionPrice();
$res["pic"] = $this->getParameter('fp') . '/' . $food->getPic();
if ($food->getFoodDetailsPictures() != null && sizeof($food->getFoodDetailsPictures()) > 0) {
$i = 0;
foreach ($food->getFoodDetailsPictures() as $food_pic) {
$res["food_details_pictures"][$i] = $this->getParameter('fp') . '/' . $food_pic;
$i++;
}
}
$res["price"] = $food->getPrice();
$res["menu_id"] = $food->getMenuId();
$lastUpdate = $food->getLastUpdate();
if ($lastUpdate instanceof \DateTimeInterface) {
$res["lastupdate"] = $lastUpdate->format(DATE_ATOM);
} elseif (is_string($lastUpdate) && strtotime($lastUpdate) !== false) {
$res["lastupdate"] = date(DATE_ATOM, strtotime($lastUpdate));
} else {
$res["lastupdate"] = null;
}
return $res;
}
private function isFirstCommandBonusApply($id)
{
$loyalty = $this->entityManager->getRepository(Loyalty::class)->findOneBy([
"status" => "1"
]);
$today = new \DateTime();
$countUserCommand = count($this->entityManager->getRepository(Command::class)->findBy([
'clientId' => $id,
'state' => '3'
]));
$haveAlredyBonus = $this->entityManager->getRepository(PayBonus::class)->findOneBy([
'clientId' => $id
]);
if (
$haveAlredyBonus == null &&
$loyalty != null &&
$today >= $loyalty->getStartDate() &&
$today <= $loyalty->getEndDate() &&
$countUserCommand < intval($loyalty->getRequired())
) {
return ['response' => true, 'type' => $loyalty->getType()];
}
return ['response' => false, 'type' => '-1'];
}
private function restaurantAcceptPayAtArrival($restaurantId)
{
$restaurant = $this->entityManager->getRepository(RestaurantConfig::class)->find($restaurantId);
return $restaurant->getPayAtDelivery();
}
private function applyFirstCommandProccess($id, $commandId, $foodPring, $shippingPrincing)
{
$loyalty = $this->entityManager->getRepository(Loyalty::class)->findOneBy([
"status" => "1"
]);
$user = $this->entityManager->getRepository(Client::class)->find($id);
$today = new \DateTime();
$userCreatedAt = $user->getCreatedAt();
$bonus = new PayBonus();
$bonus->setCreatedAt($today)
->setClientId($id)
->setCommandDate($today)
->setPayDate($today)
->setPhone($user->getUsername())
->setAccountDate($user->getCreatedAt() ? new \DateTime("@$userCreatedAt") : $today)
->setCommandId($commandId)
->setOfferType($loyalty->getType())
->setStatus('-1')
->setFoodPrice($foodPring)
->setShippingPrice($shippingPrincing)
->setAmount($loyalty->getType() == '1' ? $shippingPrincing : $loyalty->getAmount());
$em = $this->entityManager;
$em->persist($bonus);
$em->flush();
}
private function restaurantAcceptPrepay($restaurantId)
{
$restaurant = $this->entityManager->getRepository(RestaurantConfig::class)->find($restaurantId);
return $restaurant->getPrepayed();
}
private function restaurantAcceptPreOrder($restaurantId, $timeRange/*plage*/)
{
$preorder_config = $this->entityManager->getRepository(PreOrderConfig::class)->findBy(
array(),
array('id' => 'DESC'),
1,
0
);
if ($preorder_config != null) {
$config = $preorder_config[0];
$delay = 3600 * (intval($config->getDelay()));
$max_hour_range = intval($config->getMaxHour());
$restaurant = $this->entityManager->getRepository(RestaurantConfig::class)->find($restaurantId);
$data = $this->getPreorderDatas($restaurant->getPreorderScheduleId(), $delay, $max_hour_range);
if ($data["can_preorder"] == 1 && in_array($timeRange, $data["hours"])) {
return true;
}
return false;
} else {
return false;
}
}
private function get_kaba_point($client_id, $shipping_price)
{
$kabaPoint = $this->getMiniKabaPointBalance($client_id, $shipping_price);
return $kabaPoint;
}
private function getAdditionalFeesPrice($food_command, $command_pricing, $shipping_price, $address, $restaurant)
{
$commission_fee = 0;
$packaging_fee = 0;
$weather_fee = 0;
$night_fee = 0;
$week_end_fee = 0;
$holy_day_fee = 0;
//ADD COMMISSION FEE
$additional_fee = $this->entityManager->getRepository(AdditionalFees::class)->findOneBy(["fee_type" => AdditionnalFeeType::COMMISSION_FEE]);
$commission_additional_fee = $this->entityManager->getRepository(RestoFraisSupp::class)->findOneBy(["resto_id" => $restaurant->getId(), "additional_fee_id" => $additional_fee->getId()]);
if($commission_additional_fee == null){
$isEnabled = false;
}else{
$isEnabled = $commission_additional_fee->isFeeEnabled();
}
if ($isEnabled == true) {
if ($commission_additional_fee->getAmountType() == AdditionnalFeeAmountType::PRIX_FIX) {
$commission_fee = $commission_additional_fee->getValue();
} else {
$commission_fee = ($command_pricing * ($commission_additional_fee->getValue() / 100));
}
}
//ADD PACKAGING_FEE
$additional_fee = $this->entityManager->getRepository(AdditionalFees::class)->findOneBy(["fee_type" => AdditionnalFeeType::PACKAGING_FEE]);
$packaging_additional_fee = $this->entityManager
->getRepository(RestoFraisSupp::class)
->findOneBy([
"resto_id" => $restaurant->getId(),
"additional_fee_id" => $additional_fee->getId()
]);
if($packaging_additional_fee == null){
$isEnabled = false;
}else{
$isEnabled = $packaging_additional_fee->isFeeEnabled();
}
if ($isEnabled == true) {
$billing = 0;
$db_billing = $this->entityManager->getRepository(PackagingAdditionnalFeeBilling::class)->findAll();
$number_of_products = 0;
foreach ($food_command as $food) {
$number_of_products += $food['quantity'];
}
if ($db_billing != null) {
foreach ($db_billing as $db_billing_item) {
if ($number_of_products >= intval($db_billing_item->getRangeStart()) && $number_of_products <= intval($db_billing_item->getRangeEnd())) {
$billing = $db_billing_item->getValue();
}
}
}
$packaging_fee = intval($billing);
}
try{
//ADD WEATHER_FEE
$raining_in_resto_zone = false;
$raining_in_customer_zone = false;
//check if order's zone
$order_zone = $this->entityManager->getRepository(ZoneResto::class)->findOneBy(['resto_id' => $restaurant->getId()]);
if ($order_zone) {
$weather_rule = $this->entityManager->getRepository(WeatherRule::class)->findOneBy(['zone_id' => $order_zone->getZoneId()]);
if ($weather_rule) {
$current_time = new DateTime();
$time_end = $weather_rule->getTimeEnd();
$time_start = $weather_rule->getTimeStart();
if ($current_time->format('H:i') >= $time_start->format('H:i') && $current_time->format('H:i') <= $time_end->format('H:i'))
$raining_in_resto_zone = $weather_rule->isEnabled();
if ($current_time->format('H:i') > $time_end->format('H:i')) {
$raining_in_resto_zone = false;
$weather_rule->setEnabled(false);
$this->entityManager->persist($weather_rule);
$this->entityManager->flush();
}
}
}
//check shipping zone
$zones = $this->entityManager->getRepository(Zone::class)->findAll();
$customer_zone = null;
foreach ($zones as $zone) {
list($clientLat, $clientLng) = explode(':', $address->getLocation());
$location = json_decode($zone->getLocation(), true);
$latitude = $location['lat'];
$longitude = $location['lng'];
$distance = $this->haversineDistance(
(float)$clientLat,
(float)$clientLng,
$latitude,
$longitude
);
if ($distance <= $zone->getRadius()) {
$customer_zone = $zone;
break;
}
}
if ($customer_zone) {
$weatherRuleForClientZone = $this->entityManager->getRepository(WeatherRule::class)->findOneBy(['zone_id' => $customer_zone->getId()]);
$raining_in_customer_zone = $weatherRuleForClientZone->isEnabled();
if ($raining_in_customer_zone == true || $raining_in_resto_zone == true) {
$weather_additional_fee = $this->entityManager->getRepository(AdditionalFees::class)->findByFeeType(AdditionnalFeeType::WEATHER_FEE);
if ($weather_additional_fee->getAmountType() == AdditionnalFeeAmountType::PRIX_FIX) {
$weather_fee = $weather_additional_fee->getAmountValue();
} else {
$weather_fee = ($shipping_price * ($weather_additional_fee->getAmountValue() / 100));
}
}
} else
$weather_fee = 0;
}catch(Throwable $e){
$weather_fee=0;
}
//ADD NIGHT_FEE
$current_time = new DateTime();
$night_additional_fee = $this->entityManager->getRepository(AdditionalFees::class)->findByFeeType(AdditionnalFeeType::NIGHT_FEE);
$night_rule = $this->entityManager->getRepository(AdditionalFeeRule::class)->findOneby(['rule_type' => AdditionalFeeRuleType::TIME_FRAME]);
$night_time_start = $night_rule->getTimeStart();
$night_time_end = $night_rule->getTimeEnd();
if ($current_time->format('H:i') >= $night_time_start->format('H:i') && $current_time->format('H:i') < $night_time_end->format('H:i')) {
if ($night_additional_fee->isEnabled()) {
if ($night_additional_fee->getAmountType() == AdditionnalFeeAmountType::PRIX_FIX) {
$night_fee = $night_additional_fee->getAmountValue();
} else {
$night_fee = ($shipping_price * ($night_additional_fee->getAmountValue() / 100));
}
}
}
//ADD WEEK_END FEE and HOLYDAY FEE
$week_end_additional_fee = $this->entityManager->getRepository(AdditionalFees::class)->findByFeeType(AdditionnalFeeType::NIGHT_FEE);
$public_holyday_additional_fee = $this->entityManager->getRepository(AdditionalFees::class)->findByFeeType(AdditionnalFeeType::PUBLIC_HOLYDAY_FEE);
$free_day_rule = $this->entityManager->getRepository(AdditionalFeeRule::class)->findOneby(['rule_type' => AdditionalFeeRuleType::FREE_DAY_FRAME]);
$free_day_time_start = $free_day_rule->getTimeStart();
$free_day_time_end = $free_day_rule->getTimeEnd();
if ($current_time->format('H:i') >= $free_day_time_start->format('H:i') && $current_time->format('H:i') < $free_day_time_end->format('H:i')) {
if ($week_end_additional_fee->isEnabled() && ($current_time->format('N') == 6 || $current_time->format('N') == 7)) {
if ($week_end_additional_fee->getAmountType() == AdditionnalFeeAmountType::PRIX_FIX) {
$week_end_fee = $week_end_additional_fee->getAmountValue();
} else {
$week_end_fee = ($shipping_price * ($week_end_additional_fee->getAmountValue() / 100));
}
}
if ($public_holyday_additional_fee->isEnabled()) {
if ($public_holyday_additional_fee->getAmountType() == AdditionnalFeeAmountType::PRIX_FIX) {
$holy_day_fee = $public_holyday_additional_fee->getAmountValue();
} else {
$holy_day_fee = ($shipping_price * ($public_holyday_additional_fee->getAmountValue() / 100));
}
}
}
$fees = [$weather_fee, $night_fee, $week_end_fee, $holy_day_fee];
$count = 0;
foreach ($fees as $fee) {
if ($fee > 0) {
$count++;
}
}
if ($count > 2) {
$weather_additional_fee = $this->entityManager->getRepository(AdditionalFees::class)->findOneBy(["fee_type" => AdditionnalFeeType::WEATHER_FEE]);
$night_additional_fee = $this->entityManager->getRepository(AdditionalFees::class)->findOneBy(["fee_type" => AdditionnalFeeType::NIGHT_FEE]);
$week_end_additional_fee = $this->entityManager->getRepository(AdditionalFees::class)->findOneBy(["fee_type" => AdditionnalFeeType::WEEKEND_FEE]);
$public_holiday_additional_fee = $this->entityManager->getRepository(AdditionalFees::class)->findOneBy(["fee_type" => AdditionnalFeeType::PUBLIC_HOLYDAY_FEE]);
$fees_entities = [$weather_additional_fee, $night_additional_fee, $week_end_additional_fee, $public_holiday_additional_fee];
usort($fees_entities, function ($a, $b) {
return $a->getPriority() - $b->getPriority();
});
$top_two_entities = array_slice($fees_entities, 0, 2);
$selected_fee_types = [];
foreach ($top_two_entities as $entity) {
$selected_fee_types[] = $entity->getFeeType();
}
if (!in_array(AdditionnalFeeType::WEATHER_FEE, $selected_fee_types)) {
$weather_fee = 0;
}
if (!in_array(AdditionnalFeeType::NIGHT_FEE, $selected_fee_types)) {
$night_fee = 0;
}
if (!in_array(AdditionnalFeeType::WEEKEND_FEE, $selected_fee_types)) {
$week_end_fee = 0;
}
if (!in_array(AdditionnalFeeType::PUBLIC_HOLYDAY_FEE, $selected_fee_types)) {
$holy_day_fee = 0;
}
}
$res = [];
$res["COMMISSION_FEE"] = $commission_fee;
$res["PACKAGING_FEE"] = $packaging_fee;
$res["WEATHER_FEE"] = $weather_fee;
$res["NIGHT_FEE"] = $night_fee;
$res["PUBLIC_HOLYDAY_FEE"] = $holy_day_fee;
$res["WEEKEND_FEE"] = $week_end_fee;
return $res;
}
private function getPromotionPricing($data, $configs_with_voucher)
{
$promotionPricing = 0;
foreach ($data["food_command"] as $json_food_command) {
$food = $this->entityManager->getRepository(Food::class)->find(intval($json_food_command["food_id"]));
$check_food_promo = $this->checkFoodPromoState($food);
if ($check_food_promo["promo"] == 1)
$promotionPricing += intval($food->getPromotionPrice()) * intval($json_food_command["quantity"]);
else
$promotionPricing += intval($food->getPrice()) * intval($json_food_command["quantity"]);
}
if (isset($data["voucher_id"]) && $data["voucher_id"] != null) {
$voucher_food_price = intval($configs_with_voucher["voucher_food_price"]) < 0 ? 0 : $configs_with_voucher["voucher_food_price"];
$promotionPricing = intval($voucher_food_price);
}
return $promotionPricing;
}
public function checkFoodPromoState($food)
{
$data = [];
$foods["schedule"] = [];
if ($food->getId() != null) {
$sched = $this->entityManager->getRepository(PromotionSchedule::class)->findOneBy([
'foodId' => $food->getId()
]);
if ($sched != null) {
$foods["schedule"] = $this->promotionScheduleToArray($sched);
}
}
if (isset($foods["schedule"]) && $foods["schedule"] != null && isset($foods["schedule"]["content_details"]) && $foods["schedule"]["content_details"] != null) {
$schedule = $foods["schedule"];
/*get day in format ==>exp: 'Monday' and the day_index in the week==>exp: 1 (first day of week)*/
$day_of_week = $this->getDayOfWeek(date("Y-m-d"));
foreach ($schedule["content_details"] as $detail) {
/*we find today date schedule program*/
if ($detail["day_index"] == $day_of_week["day_index"]) {
if ($detail["promo"] == 0) {
$data["promo"] = 0;
return $data;
} else {
$promo = 0;
$now = strtotime(date('H:i'));
/*if start <now< end*/
if (($detail["start"] != '' && $detail["end"] != '') || ($detail["start"] != null && $detail["end"] != null)) {
if ($now >= strtotime($detail["start"]) && $now < strtotime($detail["end"])) {
$promo = 1;
}
if (
strtotime('00:00') <= strtotime($detail["end"]) &&
strtotime($detail["end"]) < strtotime($detail["start"])
) {
/*if*/
if ($now < strtotime($detail["end"]) || $now >= strtotime($detail["start"])) {
$promo = 1;
}
}
}
$data["promo"] = $promo;
return $data;
}
}
}
} else {
$data["promo"] = $food->getPromotion();
return $data;
}
}
private function get_total_pricing($res, $configs_with_voucher, $data, $client_id, $kabaPoint)
{
$total_normal_pricing = 0;
if ($res["command_pricing"] > $res["promotion_pricing"]) {
if ($res["shipping_pricing"] > $res["promotion_shipping_pricing"])
$total_normal_pricing = $res["promotion_pricing"] + $res["promotion_shipping_pricing"];
else
$total_normal_pricing = $res["promotion_pricing"] + $res["shipping_pricing"];
} else {
if ($res["shipping_pricing"] > $res["promotion_shipping_pricing"])
$total_normal_pricing = $res["command_pricing"] + $res["promotion_shipping_pricing"];
else
$total_normal_pricing = $res["command_pricing"] + $res["shipping_pricing"];
}
if (isset($data["voucher_id"]) && $data["voucher_id"] != null) {
$voucher_food_price = intval($configs_with_voucher['voucher_food_price']) < 0 ? 0 : $configs_with_voucher["voucher_food_price"];
$voucher_billing = intval($configs_with_voucher["voucher_billing"]) < 0 ? 0 : $configs_with_voucher["voucher_billing"];
$total_normal_pricing = intval($voucher_food_price + $voucher_billing);
}
if (isset($data['use_kaba_point']) && $data['use_kaba_point']) {
$amount = intval($kabaPoint["amount_to_reduce"]);
if ($amount >= $res["shipping_pricing"])
$total_normal_pricing = $res["promotion_pricing"] + $res["promotion_shipping_pricing"];
else
$total_normal_pricing = $res["promotion_pricing"] + $res["promotion_shipping_pricing"];
}
$type = [];
$type["total_pricing"] = $total_normal_pricing;
$total_normal_pricing = $this->price_based_on_loyalty($client_id, $type, $res["promotion_pricing"], null, null);
$total_normal_pricing += $res['additional_fees_total_price'];
return $total_normal_pricing;
}
private function get_remise($client_id, $res, $data, $kabaPoint)
{
$remise = 0;
$total_pricing = $res['total_pricing'];
$total_without_remise = intval($res["command_pricing"]) + intval($res["shipping_pricing"]) + $res['additional_fees_total_price'];
$total_with_remise = intval($res["promotion_pricing"]) + intval($res["promotion_shipping_pricing"]) + $res['additional_fees_total_price'];
$remise = '' . (100 - $this->getRemise($total_without_remise, $total_with_remise));
if (isset($data["voucher_id"]) && $data["voucher_id"] != null) {
$total_with_voucher_remise = intval($res["total_pricing"]);
$remise = '' . (100 - $this->getRemise($total_without_remise, $total_with_voucher_remise));
}
if (isset($data['use_kaba_point']) && $data['use_kaba_point']) {
$amount = intval($kabaPoint["amount_to_reduce"]);
if ($amount >= $res["shipping_pricing"]) {
$total_pricing = $res["promotion_pricing"];
$remise = '' . (100 - $this->getRemise($total_without_remise, $total_pricing));
} else {
$promotion_shipping_pricing = $res["shipping_pricing"] - $amount;
$total_pricing = $res["promotion_pricing"] + $promotion_shipping_pricing;
$remise = '' . (100 - $this->getRemise($total_without_remise, $total_pricing));
}
}
$type = [];
$type['remise'] = $remise;
$remise = $this->price_based_on_loyalty($client_id, $type, null, $total_without_remise, $total_pricing);
return $remise . "";
}
private function isOutOfRange($distance)
{
if ($distance >= 15000)
return true;
else
return false;
}
private function calculate_command_pricing($foods)
{
$products_total_price = 0;
foreach ($foods as $json_food_command) {
$food = $this->entityManager->getRepository(Food::class)->find(intval($json_food_command["food_id"]));
$products_total_price += intval($food->getPrice()) * intval($json_food_command["quantity"]);
}
return $products_total_price;
}
private function calculate_shipping_price($distance, $currentToken)
{
$type = filter_var($currentToken->getUsername(), FILTER_VALIDATE_EMAIL) ? 2 : 1;
$shipping_price = 0;
$billing = 0;
$db_billing = $type == 2 ? $this->entityManager->getRepository(Billing2::class)->findAll() : $this->entityManager->getRepository(Billing::class)->findAll();
if ($db_billing != null) {
foreach ($db_billing as $db_billing_item) {
if ($distance >= intval($db_billing_item->getRangeStart()) * 1000 && $distance < intval($db_billing_item->getRangeEnd()) * 1000) {
$billing = $db_billing_item->getValue();
}
}
}
$shipping_price = intval($billing);
if ($shipping_price == 0) {
return $this->serializer->serialize($distance, "json");
}
return $shipping_price;
}
private function configsWithVoucher($data, $currentToken, $user, $restaurant, $address)
{
$distance = $this->getDistance($restaurant->getLocation(), $address->getLocation());
$promotion_billing = 0;
$voucher_billing = 0;
$voucher_food_price = 0;
$is_voucher_on_billing = false;
$is_voucher_on_billing_already_applyed = false;
$check_voucher_valid = $this->checkIfVoucherValid($user->getId(), $data["voucher_id"]);
$promotion = $this->checkEligiblePromotionV2($distance, "" . $restaurant->getId(), $data["food_command"], $user);
$type = filter_var($currentToken->getUsername(), FILTER_VALIDATE_EMAIL) ? 2 : 1;
$db_billing = $type == 2 ? $this->entityManager->getRepository(Billing2::class)->findAll() : $this->entityManager->getRepository(Billing::class)->findAll();
if ($db_billing != null) {
foreach ($db_billing as $db_billing_item) {
if (
$distance >= intval($db_billing_item->getRangeStart()) * 1000 &&
$distance < intval($db_billing_item->getRangeEnd()) * 1000
) {
$billing = $db_billing_item->getValue();
$voucher_billing = intval($billing);
if ($check_voucher_valid["valid"] == true) {
/*check if restaurant is in array of concern restaurants*/
if (in_array($data["restaurant_id"], $check_voucher_valid["restaurants"])) {
$is_voucher_on_billing = true;
break;
}
}
if ($promotion["found"] == true) {
$promotion_billing = $promotion["billing"];
} else
$promotion_billing = $billing;
}
}
}
foreach ($data["food_command"] as $json_food_command) {
$food = $this->entityManager->getRepository(Food::class)->find(intval($json_food_command["food_id"]));
$vouch_price = intval($food->getPrice()) * intval($json_food_command["quantity"]);
$reduction = 0;
if ($check_voucher_valid["valid"] == true) {
if ($check_voucher_valid["isAllRestaurant"] && $check_voucher_valid["isAllFood"]) {
/* check if reduction on food or both food and billing*/
if ($check_voucher_valid["type"] == 1 || $check_voucher_valid["type"] == 3) {
if ($check_voucher_valid["category"] == 1) {
/*in percent*/
$reduction = (intval($food->getPrice()) * $check_voucher_valid["value"]) / 100;
} else {
$reduction = $check_voucher_valid["value"];
}
}
/* check if reduction on billing or both billing and food*/
if ($check_voucher_valid["type"] == 2 || $check_voucher_valid["type"] == 3) {
/*check if restaurant is in array of concern restaurants means==>is_voucher_billing=true*/
if ($is_voucher_on_billing && !$is_voucher_on_billing_already_applyed) {
if ($check_voucher_valid["category"] == 1) {
/*in percent*/
$reductions = ($voucher_billing * $check_voucher_valid["value"]) / 100;
$voucher_billing -= $reductions;
$is_voucher_on_billing_already_applyed = true;
} else {
/*cash*/
$voucher_billing -= $check_voucher_valid["value"];
$is_voucher_on_billing_already_applyed = true;
}
}
}
} elseif (
in_array(intval($json_food_command["food_id"]), $check_voucher_valid["products"]) ||
sizeof($check_voucher_valid["products"]) == 0
) {
/*check if that food is in array of concerned foods*/
/*coz if products =[] it means all foods are selected*/
/* check if reduction on food or both food and billing*/
if ($check_voucher_valid["type"] == 1 || $check_voucher_valid["type"] == 3) {
if ($check_voucher_valid["category"] == 1) {
/*in percent*/
$reduction = (intval($food->getPrice()) * $check_voucher_valid["value"]) / 100;
} else {
$reduction = $check_voucher_valid["value"];
}
}
/* check if reduction on billing or both billing and food*/
if ($check_voucher_valid["type"] == 2 || $check_voucher_valid["type"] == 3) {
/*check if restaurant is in array of concern restaurants means==>is_voucher_billing=true*/
if ($is_voucher_on_billing && !$is_voucher_on_billing_already_applyed) {
if ($check_voucher_valid["category"] == 1) {
/*in percent*/
$reductions = ($voucher_billing * $check_voucher_valid["value"]) / 100;
$voucher_billing -= $reductions;
$is_voucher_on_billing_already_applyed = true;
} else {
/*cash*/
$voucher_billing -= $check_voucher_valid["value"];
$is_voucher_on_billing_already_applyed = true;
}
}
}
}
}
if ($reduction >= $vouch_price) {
$final_food_price = 0;
} else {
$final_food_price = $vouch_price - ($reduction * intval($json_food_command["quantity"]));
}
$voucher_food_price += $final_food_price;
}
$configs_with_voucher = [];
$configs_with_voucher["promotion_billing"] = $promotion_billing;
$configs_with_voucher["voucher_billing"] = $voucher_billing;
$configs_with_voucher["voucher_food_price"] = $voucher_food_price;
$configs_with_voucher["is_voucher_on_billing"] = $is_voucher_on_billing;
$configs_with_voucher["is_voucher_on_billing_already_applyed"] = $is_voucher_on_billing_already_applyed;
$configs_with_voucher["check_voucher_valid"] = $check_voucher_valid;
return $configs_with_voucher;
}
private function getPromotionOnShipping($restaurant, $data, $address, $currentToken, $user, $configs_with_voucher, $shipping_pricing, $kabaPoint)
{
$distance = $this->getDistance($restaurant->getLocation(), $address->getLocation());
$promotion_billing = 0;
$promotion = $this->checkEligiblePromotionV2($distance, "" . $restaurant->getId(), $data["food_command"], $user);
$type = filter_var($currentToken->getUsername(), FILTER_VALIDATE_EMAIL) ? 2 : 1;
$db_billing = $type == 2 ? $this->entityManager->getRepository(Billing2::class)->findAll() : $this->entityManager->getRepository(Billing::class)->findAll();
if ($db_billing != null) {
foreach ($db_billing as $db_billing_item) {
if (
$distance >= intval($db_billing_item->getRangeStart()) * 1000 &&
$distance < intval($db_billing_item->getRangeEnd()) * 1000
) {
$billing = $db_billing_item->getValue();
if ($promotion["found"] == true) {
$promotion_billing = $promotion["billing"];
} else
$promotion_billing = $billing;
}
}
}
if (isset($data["voucher_id"]) && $data["voucher_id"] != null) {
$voucher_billing = intval($configs_with_voucher["voucher_billing"]) < 0 ? 0 : $configs_with_voucher["voucher_billing"];
$promotion_billing = intval($voucher_billing);
}
if (isset($data['use_kaba_point']) && $data['use_kaba_point']) {
$amount = intval($kabaPoint["amount_to_reduce"]);
if ($amount >= $shipping_pricing)
$promotion_billing = 0;
else
$promotion_billing = $shipping_pricing - $amount;
}
$type = [];
$type["promotion_shipping_pricing"] = $promotion_billing;
$promotion_billing = $this->price_based_on_loyalty($user->getId(), $type, null, null, null);
return intval($promotion_billing);
}
private function price_based_on_loyalty($client_id, $data, $promotion_pricing = null, $total_without_remise = null, $total_pricing = null)
{
$price_on_loyalty = 0;
if (isset($data["promotion_shipping_pricing"]))
$price_on_loyalty = $data['promotion_shipping_pricing'];
if (isset($data["total_pricing"]))
$price_on_loyalty = $data["total_pricing"];
if (isset($data["remise"]))
$price_on_loyalty = $data['remise'];
/**
* @var Loyalty
*/
$loyalty = $this->entityManager->getRepository(Loyalty::class)->findOneBy([
"status" => "1"
]);
$today = new \DateTime();
$countUserCommand = count($this->entityManager->getRepository(Command::class)->findBy([
'clientId' => $client_id,
'state' => '3'
]));
$haveAlredyBonus = $this->entityManager->getRepository(PayBonus::class)->findOneBy([
'clientId' => $client_id
]);
if (
$haveAlredyBonus == null &&
$loyalty != null &&
$today >= $loyalty->getStartDate() &&
$today <= $loyalty->getEndDate() &&
$countUserCommand < intval($loyalty->getRequired())
) {
if ($loyalty->getType() == '1') {
if (isset($data["promotion_shipping_pricing"]))
$price_on_loyalty = 0;
if (isset($data["total_pricing"]))
$price_on_loyalty = $promotion_pricing;
if (isset($data["remise"]))
$price_on_loyalty = '' . (100 - $this->getRemise($total_without_remise, $total_pricing));
}
}
return $price_on_loyalty;
}
private function haversineDistance($lat1, $lng1, $lat2, $lng2): float
{
$earthRadius = 6371;
$lat1 = deg2rad($lat1);
$lng1 = deg2rad($lng1);
$lat2 = deg2rad($lat2);
$lng2 = deg2rad($lng2);
$dlat = $lat2 - $lat1;
$dlng = $lng2 - $lng1;
$a = sin($dlat / 2) ** 2 + cos($lat1) * cos($lat2) * sin($dlng / 2) ** 2;
$c = 2 * atan2(sqrt($a), sqrt(1 - $a));
return $earthRadius * $c * 1000;
}
private function checkNumberOfOrderFoUser($id){
$client = $this->entityManager->getRepository(Client::class)->find($id);
if($client){
$qb = $this->entityManager->createQueryBuilder();
$qb->select('COUNT(c.id)')
->from(Command::class,'c')
->where('c.clientId = :client_id')
->setParameter('client_id',$id);
return (int) $qb->getQuery()->getSingleScalarResult();
}else{
return -1;
}
}
private function applySubscriptionOnOrder($distance, $subscription, $prom_ship_price)
{
$promotion_shipping_pricing = $prom_ship_price;
try {
if (!$subscription || empty($subscription)) {
return $promotion_shipping_pricing;
}
$pack = $subscription['pack'] ?? null;
if (!$pack) {
return $promotion_shipping_pricing;
}
$endDate = isset($subscription['end_date']) ? new DateTime($subscription['end_date']) : null;
$now = new DateTime();
$isBefore = $endDate ? ($now < $endDate) : false;
$radius_limit = isset($pack['radius_km']) ? floatval($pack['radius_km']) : 0;
$delivery_limit = isset($pack['deliverylimit']) ? intval($pack['deliverylimit']) : 0;
$usage_count = isset($subscription['alreadyUsed']) ? intval($subscription['alreadyUsed']) : 0;
if (!$isBefore) {
return $promotion_shipping_pricing;
}
if ($distance < (($radius_limit * 1000)+100)) {
if ($usage_count < $delivery_limit) {
$promotion_shipping_pricing = 0;
}
return $promotion_shipping_pricing;
}
} catch (Exception $e) {
error_log("applySubscriptionOnOrder error: " . $e->getMessage());
}
return $promotion_shipping_pricing;
}
}