<?php
namespace App\V4Bundle\Controller;
use App\Entity\AdditionalFeeRule;
use App\Entity\AdditionalFees;
use App\Entity\Adresses;
use App\Entity\Billing;
use App\Entity\Client;
use App\Entity\Command;
use App\Entity\Food;
use App\Entity\Livreur;
use App\Entity\LivreurAdditionnalFeeConfig;
use App\Entity\PaymentBill;
use App\Entity\RestaurantConfig;
use App\Entity\Voucher;
use App\Entity\WeatherRule;
use App\Entity\Zone;
use App\V4Bundle\Entity\DeliveryRating as EntityDeliveryRating;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\Serializer\SerializerInterface;
use App\V4Bundle\Controller\BaseController;
use App\V4Bundle\Entity\Billing2;
use App\V4Bundle\Entity\Devices;
use App\V4Bundle\Entity\Employee;
use App\V4Bundle\Entity\Loyalty;
use App\V4Bundle\Entity\PayBonus;
use App\V4Bundle\Entity\PreorderCommandDetails;
use App\V4Bundle\Entity\VoucherOwner;
use App\V4Bundle\Entity\VoucherSubscription;
use App\V4Bundle\Entity\VoucherTransaction;
use App\V4Bundle\Entity\VoucherUsage;
use DateTime;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
use Symfony\Component\Routing\Annotation\Route;
use App\V4Bundle\Entity\DeliveryRating;
use App\V4Bundle\Service\AwsS3Service;
use App\V4Bundle\Entity\OutOfAppOrder;
use Symfony\Component\Security\Core\Security;
use Firebase\JWT\JWT;
use Symfony\Component\HttpClient\HttpClient;
use App\Entity\Menu;
use App\Entity\RestoFraisSupp;
use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;
use Symfony\Component\Serializer\Normalizer\NormalizerInterface;
use Symfony\Component\Serializer\Serializer;
use App\Enums\AdditionnalFeeType;
use App\Enums\AdditionnalFeeAmountType;
use App\Enums\AdditionalFeeRuleType;
use App\V4Bundle\Entity\DistrictBaricentre;
use Exception;
use Symfony\Component\Mime\Address;
use Symfony\Contracts\HttpClient\HttpClientInterface;
use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
use Doctrine\DBAL\Connection;
use App\V4Bundle\Entity\Subscription;
use App\V4Bundle\Entity\SharedUser;
use App\V4Bundle\Entity\Pack;
use App\V4Bundle\Entity\UserSusOrd;
use App\V4Bundle\Entity\NewUserPromotion;
class OutOfAppOrderController extends BaseController
{
protected $tokenStorage;
protected $serializer;
protected $entityManager;
protected $passwordHasher;
protected $awsS3Service;
protected $http_client;
protected $security;
protected $passwordEncoder;
protected $connection;
public function __construct(
SerializerInterface $serializer,
EntityManagerInterface $entityManager,
UserPasswordHasherInterface $passwordHasher,
TokenStorageInterface $tokenStorage,
AwsS3Service $awsS3Service,
Security $security,
HttpClientInterface $http_client,
UserPasswordEncoderInterface $passwordEncoder,
Connection $connection
) {
$this->serializer = $serializer;
$this->entityManager = $entityManager;
$this->passwordHasher = $passwordHasher;
$this->tokenStorage = $tokenStorage;
$this->awsS3Service = $awsS3Service;
$this->security = $security;
$this->http_client = $http_client;
$this->passwordEncoder = $passwordEncoder;
$this->connection = $connection;
}
// order type of order with order address is 3
// order type of order without order address is 4
// order type for colis is 5
const RESTAURANT_ORDER = 1;
const KABA_COLIS_ORDER = 2;
const OUT_OF_APP_ORDER = 3;
const OUT_OF_APP_WITHOUT_ORDER_ADDRESS = 4;
const KABA_COLIS_SHIPPING = 5;
const KABA_COLIS_FETCHING = 6;
/**
* @Route("mobile/api/out_of_app_order/billing/get", name="out_of_app_order_billing_get", methods={"POST"})
*/
public function getOutOfAppOrderBilling(Request $request)
{
$currentToken = $this->get('security.token_storage')->getToken();
$data = json_decode($request->getContent(), true);
if (isset($data['user_id'])) {
$id = $data['user_id'];
$user = $this->entityManager->getRepository(Client::class)->find($id);
if ($user) {
$tokenRequest = new Request(
[],
[],
[],
[],
[],
['CONTENT_TYPE' => 'application/json'],
json_encode(['username' => $user->getUsername()])
);
$jwtResponse = $this->generateJwt($tokenRequest);
$jwtData = json_decode($jwtResponse->getContent(), true);
if (isset($jwtData['token'])) {
$currentToken = $jwtData['token'];
}
}
} else {
$user = $currentToken->getUser();
$id = $user->getId();
}
if (
isset($data["order_address"]) &&
isset($data["shipping_address"]) &&
$data["order_address"] != null &&
$data["shipping_address"] != null &&
isset($data["order_details"])
) {
$nb_order = $this->checkNumberOfOrderFoUser($id);
$companie_service_fee = 0;
if (isset($data['companie_service_fee']))
$companie_service_fee = $data['companie_service_fee'];
$shipping_address = $this->entityManager->getRepository(Adresses::class)->find(intval($data["shipping_address"]));
if ($data['order_address'][0] != 0) {
$order_address = $this->entityManager->getRepository(Adresses::class)->find(intval($data["order_address"][0]));
} else {
$order_address = $this->entityManager->getRepository(Adresses::class)->find($data['shipping_address']);
}
$configs_with_voucher = $this->configsWithVoucher($data, $currentToken, $user, $order_address, $shipping_address);
$res = [];
$res["account_balance"] = $this->getBalance($id);
$res["distance"] = $this->getDistance($order_address->getLocation(), $shipping_address->getLocation());
$res["shipping_pricing"] = $this->calculate_shipping_price($res["distance"], $currentToken) ;
$res["kaba_point"] = $this->get_kaba_point($id, $res['shipping_pricing']);
$res['reduced_shipping_price'] = $this->getReducedShippingPrice($data, $configs_with_voucher, $res['kaba_point'], $res);
$res['promotion_shipping_pricing'] = $res['reduced_shipping_price'];
//Subscription
try{
if($data['user_abonnement']){
$res["promotion_shipping_pricing"] = $this->applySubscriptionOnOrder($res['distance'], $data['user_abonnement'], $res['promotion_shipping_pricing']);
$res["reduced_shipping_price"] = $res["promotion_shipping_pricing"];
$res['has_subscription'] = $res["reduced_shipping_price"]==0?true:false;
}
}catch(Exception $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["reduced_shipping_price"] = $res["promotion_shipping_pricing"];
$res['is_new_user']=true;
}else{
}
}
}
}catch(Exception $e){}
}
$res["command_pricing"] = $this->getCommandPricing($data['order_details']);
$res['additional_fees'] = $this->getOutOfAppAdditionnalFees($res['shipping_pricing'], $shipping_address, $order_address);
$res['additional_fees_total_price'] = $this->getAdditionalFeesTotalPricing($res["additional_fees"]);
$res["total_pricing"] = $this->get_total_pricing($res, $configs_with_voucher, $data, $res["kaba_point"], $res["command_pricing"]) + $companie_service_fee;
$res['total_normal_pricing'] = intval($res["command_pricing"]) + intval($res["shipping_pricing"]) + intval($res['additional_fees_total_price']) + $companie_service_fee;
$res['total_reduced_pricing'] = intval($res["command_pricing"]) + intval($res["reduced_shipping_price"]) + intval($res['additional_fees_total_price']) + $companie_service_fee;
$res['promotion_pricing'] = $res['total_reduced_pricing'];
$res["out_of_range"] = $this->isOutOfRange($res["distance"]);
$res["pay_at_delivery"] = $data['pay_at_delivery'];
$res["remise"] = $this->get_remise($id, $res, $data, $res["kaba_point"]);
$res["trustful"] = $user->getTrustful();
$res['eligible_vouchers'] = $this->getUserEligibleVoucher($id);
$res['promotion_pricing'] = $res['total_reduced_pricing'];
$res['promotion_shipping_pricing'] = $res['reduced_shipping_price'];
$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"] = "Ce service est sujet de frais supplémentaires";
$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],"Ce service est sujet de frais supplémentaires",$notif,1);
}catch(Exception $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/out_of_app_order/create", name="out_of_app_order_command_create", methods={"POST"})
*/
public function createOutOfAppOrderWithVoucherAction(Request $request)
{
$currentToken = $this->get('security.token_storage')->getToken();
$user = $currentToken->getUser();
$id = $user->getId();
$data = json_decode($request->getContent(), true);
$nb_order = $this->checkNumberOfOrderFoUser($id);
if($nb_order >= 0 && $nb_order <= 5){
$data['voucher_id']=null;
$data['use_kaba_point']=false;
}
$is_voucher = 0;
$deliveryRange = [];
$companie_service_fee = 0;
if (isset($data['companie_service_fee']))
$companie_service_fee = $data['companie_service_fee'];
$shipping_address = $this->entityManager->getRepository(Adresses::class)->find(intval($data["shipping_address"]));
if ($data['order_address'][0] != 0) {
$order_address = $this->entityManager->getRepository(Adresses::class)->find(intval($data["order_address"][0]));
} else {
$order_address = $this->entityManager->getRepository(Adresses::class)->find($data['shipping_address']);
}
$shipping_addres_array = $this->getAdress($data["shipping_address"]);
$order_address_array = $this->getAdress($order_address->getId());
if ($order_address_array == -1)
return new Response($this->serializer->serialize($this->errorResponseBlob(null, 301), 'json'));
if ($shipping_addres_array == -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->getCommandDetails($data['order_details'], $order_address, $shipping_address, $data['voucher_id'], $id, $data['use_kaba_point']);
$data["food_command"] = $command_details["foods"];
$details = "Livraison de " . " " . $command_details["food_litteral"];
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'));
}
$files = $request->files->all();
$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 = $command_details["voucher_pricing"]["shipping_pricing"] ;
if (intval($data['order_type']) == 5 || intval($data['order_type']) == 6) {
$resto = $this->entityManager->getRepository(RestaurantConfig::class)->findOneBy(['username' => "kaba_colis"]);
$food_command = $this->createColisFoods($command_details['foods']);
} else if (intval($data['order_type']) == 3 || intval($data['order_type']) == 4) {
$resto = $this->entityManager->getRepository(RestaurantConfig::class)->findOneBy(['username' => "hors_appli"]);
$food_command = $this->createHorsAppliFoods($command_details['foods']);
}
$command->setFoodCommand($food_command);
$command->setOrderDetails($data["order_details"]);
$command->setPayAtDelivery($data["pay_at_delivery"]);
$command->setClientId($id);
$command->setClient($user);
$command->setState(-1);
$command->setOrderShippingAddress($order_address_array);
$command->setShippingAddress($shipping_addres_array);
$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($data['user_abonnement']){
$promotion_shipping_pricing = $this->applySubscriptionOnOrder($this->getDistance($shipping_addres_array['location'], $order_address_array['location']),$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(Exception $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();
$command->setHaveBillingDiscount(true);
$command->setShippingPricing($realyShippingPrice-$promotion_for_new_user);
}
}
}
}catch(Exception $e){
}
}
$command->setOrderType($data['order_type']);
$command->setStartTime(date('Y-m-d H:i:s'));
$command->setStartDate(date('Y-m-d'));
$command->setLastUpdate(date('Y-m-d H:i:s'));
$command->setRestaurant($resto);
$command->setRestaurantId($resto->getId());
$command->setPhoneNumber($data['phone_number']);
$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"]);
if (isset($data['infos_image'])) {
$command->setAdditionnalInfoImage($data['infos_image']);
}
$em->persist($command);
$em->flush();
if (isset($data['device'])) {
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 ($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["without_promo"]["total"]);
if ($isFirstCommandBonusApply['response']) {
$pay_at_delivery_total_price -= intval($command_details["without_promo"]["billing"]);
$temp_foodPricing = $pay_at_delivery_total_price;
$tem_shippingPricing = intval($command_details["without_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 if ($data["pay_at_delivery"] == false) {
return new JsonResponse(['error' => "Action not allowed"]);
}
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) {
$reward = $command_details["voucher_pricing"]["owner"]["reward_cash_value"];
}
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();
}
$jsonData = json_encode([
"order_details" => $command->getOrderDetails(),
"order_address" => $data['order_address'],
"shipping_address" => $data['shipping_address'],
"voucher_id" => $voucher_id,
"use_kaba_point" => $use_kaba_point,
"pay_at_delivery" => $data['pay_at_delivery'],
"companie_service_fee" => $companie_service_fee
]);
$Billingrequest = new Request(
[],
[],
[],
[],
[],
['CONTENT_TYPE' => 'application/json'],
$jsonData
);
$getBilling = $this->getOutOfAppOrderBilling($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"] = false;
$data["pre_order_hour"] = $deliveryRange;
$data["voucher_data"] = $command_details["voucher_pricing"];
$data["command_details"] = $getBillingData;
$response["error"] = 0;
$response["code"] = 200;
$response["message"] = "200 OK";
$response["data"] = [];
$response["data"]['distance'] = $getBillingData['data']['distance'];
$response["data"]['shipping_pricing'] = $getBillingData['data']['shipping_pricing'];
$response["data"]['command_pricing'] = $getBillingData['data']['command_pricing'];
$response["data"]['additional_fees'] = $getBillingData['data']['additional_fees_total_price'];
$response["data"]['out_of_range'] = $getBillingData['data']['out_of_range'];
$response["data"]['total_pricing'] = $getBillingData['data']['total_pricing'];
$response["data"]["command_id"] = $command->getId();
$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(json_decode($this->serializer->serialize($getBillingData, 'json')), 200);
}
/**
* @Route("mobile/api/out_of_app_order/get/details", name="out_of_app_order_get_details", methods={"POST"})
*/
public function getOutOfAppOrderDetailsWithVoucher(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)->findOneBy([
'id' => intval($command_id),
]);
$companie_service_fee = 0;
if (isset($data['companie_service_fee']))
$companie_service_fee = $data['companie_service_fee'];
if ($command == null || ($command->getClient() != null && $command->getClientId() != $id)) {
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' => $id,
'isReallyUsed' => 1
]));
}
$data["command"] = $vouch;
$payment_bill = $this->entityManager->getRepository(PaymentBill::class)->findOneBy(['command' => $command->getId()]);
if ($payment_bill) {
$total_additionnal_fee = $payment_bill->getAdditionalFeesTotalPrice();
$data["command"]["total_pricing"] = $data["command"]["total_pricing"] + $total_additionnal_fee + $companie_service_fee;
$data["command"]["preorder_total_pricing"] = $data["command"]["preorder_total_pricing"] + $total_additionnal_fee + $companie_service_fee;
$data["command"]["promotion_total_pricing"] = $total_additionnal_fee + $data["command"]["promotion_total_pricing"] + $companie_service_fee;
$data["command"]["additionnal_fee"] = $total_additionnal_fee;
$data["command"]["remise"] = '' . (100 - $this->getRemise($data["command"]["total_pricing"], $data["command"]["promotion_total_pricing"]));
}
$rating = 0;
$comment = '';
$repo = $this->entityManager->getRepository(EntityDeliveryRating::class);
$rate = $repo->findOneBy([
'commandId' => $command->getId()
]);
if ($rate != null) {
$rating = $rate->getRating()??0;
$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/out_of_app_order/all/get", name="out_of_app_order_get_all_orders", methods={"POST"})
*/
public function getApiAllCommandWithVoucherAction()
{
$currentToken = $this->get('security.token_storage')->getToken();
$id = $currentToken->getUser()->getId();
$repository = $this->entityManager->getRepository(Command::class);
$start_date = date('Y-m-d', strtotime('-90 days'));
$end = date('Y-m-d', strtotime('+1 day'));
$period = new \DatePeriod(
new \DateTime($start_date),
new \DateInterval('P1D'),
new \DateTime($end)
);
$date_array = [];
foreach ($period as $key => $value) {
array_push($date_array, $value->format('Y-m-d'));
}
$commands = $repository->createQueryBuilder('c')
->where('c.clientId = :clientId')
->andWhere('c.startDate IN (:dateArray)')
->andWhere('c.order_type = 3 OR c.order_type = 4 OR c.order_type = 5 OR c.order_type = 6')
->setParameter('clientId', $id)
->setParameter('dateArray', $date_array)
->orderBy('c.lastUpdate', 'DESC')
->getQuery()
->getResult();
if ($commands != null) {
$command_array = [];
$command_array["commands"] = [];
foreach ($commands as $command) {
$tmp = $this->forMobileWithVoucherCommandToArray($command);
$payment_bill = $this->entityManager->getRepository(PaymentBill::class)->findOneBy(['command' => $command->getId()]);
if ($payment_bill) {
$total_additionnal_fee = $payment_bill->getAdditionalFeesTotalPrice();
$tmp["total_pricing"] = $tmp["total_pricing"] + $total_additionnal_fee;
$tmp["preorder_total_pricing"] = $tmp["preorder_total_pricing"] + $total_additionnal_fee;
$tmp["promotion_total_pricing"] = $total_additionnal_fee + $tmp["promotion_total_pricing"];
$tmp["additionnal_fee"] = $total_additionnal_fee;
}
array_push($command_array["commands"], $tmp);
}
return new Response($this->serializer->serialize($this->okResponseBlob($command_array), 'json'));
} else {
return new Response($this->serializer->serialize($this->okResponseBlob([]), 'json'));
}
}
/**
* @Route("mobile/api/out_of_app_order/get", name="user_mobile_out_of_app_order_get", methods={"POST"})
*/
public function getApiOutOfAppWithVoucherAction()
{
$currentToken = $this->get('security.token_storage')->getToken();
$id = $currentToken->getUser()->getId();
$query = $this->entityManager->createQuery('
SELECT c FROM App:Command c
WHERE c.clientId = :id
AND ((c.startDate = :startDate)
OR (c.startDate < :startDate AND c.state < :deliveredState))
AND (c.order_type = 3 OR c.order_type = 4 OR c.order_type = 5 OR c.order_type = 6)
AND c.order_type IS NOT NULL
ORDER BY c.lastUpdate DESC
')
->setParameter('startDate', date("Y-m-d"))
->setParameter('deliveredState', 3)
->setParameter('id', intval($id));
$commands = $query->execute();
$command_array = [];
$command_array["commands"] = [];
if ($commands != null) {
foreach ($commands as $command) {
$tmp = $this->forMobileWithVoucherCommandToArray($command);
$payment_bill = $this->entityManager->getRepository(PaymentBill::class)->findOneBy(['command' => $tmp["id"]]);
if ($payment_bill) {
$total_additionnal_fee = $payment_bill->getAdditionalFeesTotalPrice();
$tmp["total_pricing"] = $tmp["total_pricing"] + $total_additionnal_fee;
$tmp["preorder_total_pricing"] = $tmp["preorder_total_pricing"] + $total_additionnal_fee;
$tmp["promotion_total_pricing"] = $total_additionnal_fee + $tmp["promotion_total_pricing"];
}
array_push($command_array["commands"], $tmp);
}
return new Response($this->serializer->serialize($this->okResponseBlob($command_array), 'json'));
} else {
return new Response($this->serializer->serialize($this->okResponseBlob($command_array), 'json'));
}
}
/**
* @Route("mobile/api/out_of_app_order/image/upload", name="user_mobile_out_of_app_order_image_upload", methods={"POST"})
*/
public function uploadMultipleImages(Request $request)
{
return $this->processImageUpload($request);
}
/**
* @Route("mobile/api/v4/livreur/out_of_app_order/receipt/upload", name="livreur_mobile_out_of_app_order_receipt_upload", methods={"POST"})
*/
public function uploadReceiptImages(Request $request)
{
return $this->processImageUpload($request);
}
/**
* @Route("mobile/api/out_of_app_order/districts/get", name="out_of_app_order_get_all_districts", methods={"POST"})
*/
public function getDistrict()
{
$currentToken = $this->get('security.token_storage')->getToken();
$districts = $this->entityManager->getRepository(DistrictBaricentre::class)->findAll();
$districts_array = [];
foreach ($districts as $district) {
$district_content = [
"name" => $district->getName(),
"geopoint" => $district->getGeopoint(),
"state" => $district->getState(),
];
$address = $this->entityManager->getRepository(Adresses::class)->findOneBy(["name" => $district_content['name']]);
if (!$address) {
$address = new Adresses();
$address->setDescription("Le quartier de " . $district_content['name']);
$address->setName($district_content['name']);
$address->setPhoneNumber("91215301");
$address->setLocation($district->getGeopoint());
$address->setNear("Se situe à lomé");
$address->setQuartier($district->getName());
$address->setDescriptionDetails("Le quartier de " . $district_content['name']);
$user = $this->entityManager->getRepository(Client::class)->findOneBy(["username" => "91215301"]);
if (!$user) {
$user = new Client();
$hash = $this->passwordEncoder->encodePassword(new \App\Entity\Client(), "1234");
$user->setPassword($hash);
$user->setUsername("91215301");
$user->setNickName('Kaba 91215301');
$user->setSalt('');
$user->setIsSet(0);
$user->setRoles(array('ROLE_USER'));
$user->setGender(0);
$user->setProfilePicture('defult.jpeg');
$user->setThemePicture('default.jpeg');
$user->setCreatedAt(strtotime(date("Y-m-d H:i:s")));
$user->setCreatedDate(date("Y-m-d"));
$user->setLastUpdate(date("Y-m-d H:i:s"));
$user->setBirthday('');
$user->setEnabled(1);
$user->setTrustful(1);
$user->setIsSponsored(0);
$this->entityManager->persist($user);
$this->entityManager->flush($user);
}
$address->setUserId($user->getId());
$address->setUpdatedAt(date("Y-m-d H:i:s"));
$address->setState(1);
$this->entityManager->persist($address);
$this->entityManager->flush($address);
}
$district_content['address_id'] = $address->getId();
$district_content['description'] = $address->getDescription();
array_push($districts_array, $district_content);
}
return new JsonResponse(['districts' => $districts_array]);
}
/**
* @Route("mobile/api/out_of_app_order/shipping_price_range/get", name="out_of_app_order_get_shipping_price_range", methods={"POST"})
*/
public function getShippingRange(){
$db_billing = $this->entityManager->getRepository(Billing::class)->findAll();
$minimum = 0;
$maximum = 0;
if ($db_billing != null) {
foreach ($db_billing as $db_billing_item) {
if (intval($db_billing_item->getRangeStart())==0) {
$minimum = $db_billing_item->getValue();
}
if (intval($db_billing_item->getRangeStart())==5) {
$maximum = $db_billing_item->getValue();
}
}
}
return new JsonResponse(['range'=>['minimum'=>$minimum,'maximum'=>$maximum]]);
}
private function get_remise($client_id, $res, $data, $kabaPoint)
{
$remise = 0;
$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'];
$total_pricing = $res["total_normal_pricing"];
$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 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 processImageUpload(Request $request)
{
$data = json_decode($request->getContent(), true);
if (!isset($data['orderDetails'])) {
return new JsonResponse(['error' => 'Invalid order details'], Response::HTTP_BAD_REQUEST);
}
if (!is_array($data['orderDetails'])) {
$data['orderDetails'] = [$data['orderDetails']];
}
$folder = 'out_of_app_orders';
foreach ($data['orderDetails'] as &$order) {
if (!isset($order['image']) || empty($order['image'])) {
continue;
}
try {
$order['image'] = $this->uploadImageToS3($order['image'], $folder);
} catch (\Exception $e) {
return new JsonResponse(['error' => 'Error uploading file: ' . $e->getMessage()], Response::HTTP_INTERNAL_SERVER_ERROR);
}
}
return new JsonResponse([
'message' => 'Upload successful',
'orders' => $data['orderDetails']
], Response::HTTP_OK);
}
private function uploadImageToS3($base64Image, $folder)
{
$imageData = base64_decode($base64Image);
$tempFile = tempnam(sys_get_temp_dir(), 'aws_upload_');
file_put_contents($tempFile, $imageData);
$finfo = finfo_open(FILEINFO_MIME_TYPE);
$mimeType = finfo_file($finfo, $tempFile);
finfo_close($finfo);
switch ($mimeType) {
case 'image/jpg':
case 'image/jpeg':
$extension = 'jpg';
break;
case 'image/png':
$extension = 'png';
break;
case 'image/gif':
$extension = 'gif';
break;
default:
$extension = 'jpg';
}
$fileName = time() . '_' . uniqid() . '.' . $extension;
$s3Path = $folder . '/' . $fileName;
$url = $this->awsS3Service->uploadFile($tempFile, $folder, $fileName);
unlink($tempFile);
return $url;
}
//API FOR COMPANIES OUT OF APP ORDERS
/**
* @Route("out_of_app/api/order/billing/get", name="out_of_app_api_order_billing_get", methods={"POST"})
*/
public function OutOfOrderGetBilling(Request $request)
{
$currentToken = $this->get('security.token_storage')->getToken();
$userId = $currentToken->getUser()->getId();
$data = json_decode($request->getContent(), 'true');
if (isset($data['order_details']) && isset($data['order_address']) && isset($data['shipping_address'])) {
$user = $this->entityManager->getRepository(Client::class)->findOneBy(['id' => $userId]);
$OrderAddress = new Adresses();
$OrderAddress->setDescription("this my description and its an order address");
$OrderAddress->setName("no name yet");
$OrderAddress->setPhoneNumber($user->getPhoneNumber());
$OrderAddress->setLocation($data['order_address']);
$OrderAddress->setNear("near location");
$OrderAddress->setQuartier("Nothing here");
$OrderAddress->setDescriptionDetails("decription details of mine");
$OrderAddress->setUserId($userId);
$OrderAddress->setUpdatedAt(date("Y-m-d H:i:s"));
$OrderAddress->setState(1);
$this->entityManager->persist($OrderAddress);
$this->entityManager->flush($OrderAddress);
$shippingAddress = new Adresses();
$shippingAddress->setDescription("this my description and its a shipping address");
$shippingAddress->setName("no name yet");
$shippingAddress->setPhoneNumber($user->getPhoneNumber());
$shippingAddress->setLocation($data['shipping_address']);
$shippingAddress->setNear("near location");
$shippingAddress->setQuartier("Nothing here");
$shippingAddress->setDescriptionDetails("decription details of mine");
$shippingAddress->setUserId($userId);
$shippingAddress->setUpdatedAt(date("Y-m-d H:i:s"));
$shippingAddress->setState(1);
$this->entityManager->persist($shippingAddress);
$this->entityManager->flush($shippingAddress);
try {
$jsonData = json_encode([
"order_details" => $data['order_details'],
"order_address" => [$OrderAddress->getId()],
"shipping_address" => $shippingAddress->getId(),
"voucher_id" => null,
"use_kaba_point" => false,
"pay_at_delivery" => true,
"companie_service_fee" => $data['service_fee']
]);
$Billingrequest = new Request(
[],
[],
[],
[],
[],
[
'CONTENT_TYPE' => 'application/json'
],
$jsonData
);
$getBilling = $this->getOutOfAppOrderBilling($Billingrequest);
$getBillingContent = $getBilling->getContent();
$getBillingData = json_decode($getBillingContent, true);
$this->entityManager->remove($OrderAddress);
$this->entityManager->remove($shippingAddress);
$res = [];
$res['distance'] = $getBillingData['data']['distance'];
$res['shipping_pricing'] = $getBillingData['data']['shipping_pricing'];
$res['command_pricing'] = $getBillingData['data']['command_pricing'];
$res['additional_fees'] = $getBillingData['data']['additional_fees_total_price'];
$res['out_of_range'] = $getBillingData['data']['out_of_range'];
$res['total_pricing'] = $getBillingData['data']['total_pricing'];
$res['company_commission_fee'] = $data['service_fee'];
return new Response($this->serializer->serialize($this->okResponseBlob($res), 'json'));
} catch (\Exception $e) {
$this->entityManager->remove($OrderAddress);
$this->entityManager->remove($shippingAddress);
return new Response($this->serializer->serialize($this->errorResponseBlob('There was a problem getting the billing in INTERNAL SERVER' . $e), 'json'));
}
} else {
return new Response($this->serializer->serialize($this->errorResponseBlob('Invalid parameter'), 'json'));
}
}
/**
* @Route("out_of_app/api/order/create", name="create_out_of_app_order", methods={"POST"})
*/
public function CreateOutOfAppOrder(Request $request)
{
$currentToken = $this->get('security.token_storage')->getToken();
$userId = $currentToken->getUser()->getId();
$data = json_decode($request->getContent(), 'true');
if (isset($data['order_details']) && isset($data['order_address']) && isset($data['shipping_address'])) {
$order_address_id = null;
$shipping_address_id = null;
$existingAddress = $this->entityManager->getRepository(Adresses::class)->findOneBy([
'user_id' => $userId,
'location' => $data['order_address']
]);
if (!$existingAddress) {
$OrderAddress = new Adresses();
$OrderAddress->setDescription("this my description and its an order address");
$OrderAddress->setName("no name yet");
$OrderAddress->setPhoneNumber("92702550");
$OrderAddress->setLocation($data['order_address']);
$OrderAddress->setNear("near location");
$OrderAddress->setQuartier("Nothing here");
$OrderAddress->setDescriptionDetails("decription details of mine");
$OrderAddress->setUserId($userId);
$OrderAddress->setUpdatedAt(date("Y-m-d H:i:s"));
$OrderAddress->setState(1);
$this->entityManager->persist($OrderAddress);
$this->entityManager->flush();
$order_address_id = $OrderAddress->getId();
} else {
$order_address_id = $existingAddress->getId();
}
$existingShippingAddress = $this->entityManager->getRepository(Adresses::class)->findOneBy([
'user_id' => $userId,
'location' => $data['shipping_address']
]);
if (!$existingShippingAddress) {
$shippingAddress = new Adresses();
$shippingAddress->setDescription("this my description and its a shipping address");
$shippingAddress->setName("no name yet");
$shippingAddress->setPhoneNumber("92702550");
$shippingAddress->setLocation($data['shipping_address']);
$shippingAddress->setNear("near location");
$shippingAddress->setQuartier("Nothing here");
$shippingAddress->setDescriptionDetails("decription details of mine");
$shippingAddress->setUserId($userId);
$shippingAddress->setUpdatedAt(date("Y-m-d H:i:s"));
$shippingAddress->setState(1);
$this->entityManager->persist($shippingAddress);
$this->entityManager->flush();
$shipping_address_id = $shippingAddress->getId();
} else {
$shipping_address_id = $existingShippingAddress->getId();
}
try {
$jsonData = json_encode([
"order_details" => $data['order_details'],
"order_address" => [$order_address_id],
"shipping_address" => $shipping_address_id,
"voucher_id" => null,
"order_type" => 3,
"transaction_password" => "1204",
"infos" => "",
"use_kaba_point" => false,
"pay_at_delivery" => true,
"companie_service_fee" => $data['service_fee'],
"phone_number" => $data['phone_number']
]);
$createCommandRequest = new Request(
[],
[],
[],
[],
[],
[
'CONTENT_TYPE' => 'application/json'
],
$jsonData
);
$createCommand = $this->createOutOfAppOrderWithVoucherAction($createCommandRequest);
$Command = $createCommand->getContent();
$CommandData = json_decode($Command, true);
$order = new OutOfAppOrder();
$order->setCommandId($CommandData['data']['command_id']);
$order->setServiceFee($data['service_fee']);
$order->setAdditionnalImageLinks($data['additionnal_images_links'] ?? []);
$order->setShippingAddress($data['shipping_address']);
$order->setOrderAddress($data['order_address']);
$order->setAdditionnalInfo("Info : \n" . $data['additionnal_info'] . "\n" . "Info pharmacie : \n" . $data['pharmacie_info']);
$order->setPhoneNumber($data['phone_number'] ?? null);
$order->setReceipt(null);
$this->entityManager->persist($order);
$this->entityManager->flush();
$res = [];
$res['distance'] = $CommandData['data']['distance'];
$res['shipping_pricing'] = $CommandData['data']['shipping_pricing'];
$res['command_pricing'] = $CommandData['data']['command_pricing'];
$res['additional_fees'] = $CommandData['data']['additional_fees'];
$res['out_of_range'] = $CommandData['data']['out_of_range'];
$res['total_pricing'] = $CommandData['data']['total_pricing'];
$res['command_id'] = $CommandData['data']['command_id'];
$res['company_commission_fee'] = $data['service_fee'];
return new Response($this->serializer->serialize($this->okResponseBlob($res), 'json'));
} catch (\Exception $e) {
return new Response($this->serializer->serialize($this->errorResponseBlob('There was a problem getting the billing in INTERNAL SERVER' . $e), 'json'));
}
} else {
return new Response($this->serializer->serialize($this->errorResponseBlob('Invalid parameter'), 'json'));
}
}
/**
* @Route("out_of_app/api/order/details/get", name="out_of_app_order_details_get", methods={"POST"})
*/
public function getOutOfAppOrderDetails(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"];
$serviceFee = 0;
$out_of_app_order = $this->entityManager->getRepository(OutOfAppOrder::class)->findOneBy(['commandId' => $command_id]);
$serviceFee = 0;
if ($out_of_app_order) {
$serviceFee = $out_of_app_order->getServiceFee();
}
$command_detail_request = new Request(
[],
[],
[],
[],
[],
[
'CONTENT_TYPE' => 'application/json'
],
json_encode([
'command_id' => $command_id,
"companie_service_fee" => $serviceFee
])
);
$command_detail = $this->getOutOfAppOrderDetailsWithVoucher($command_detail_request);
$command = $command_detail->getContent();
$commandData = json_decode($command, true);
$res = [];
$out_of_app_order = $this->entityManager->getRepository(OutOfAppOrder::class)->findOneBy(['commandId' => $commandData['data']['command']['id']]);
$res['id'] = $commandData['data']['command']['id'];
$res['food_list'] = $commandData['data']['command']['food_list'];
$res['food_pricing'] = $commandData['data']['command']['food_pricing'];
$res['shipping_pricing'] = $commandData['data']['command']['shipping_pricing'];
$res['out_of_range'] = $commandData['data']['command']['out_of_range'];
$res['additional_fees'] = $commandData['data']['command']['additionnal_fee'];
$res['company_commission_fee'] = $commandData['data']['command']['serviceFee'];;
$res['total_pricing'] = $commandData['data']['command']['total_pricing'];
$res['shipping_address'] = $commandData['data']['command']['shipping_address']['location'];
$res['delivery_time_estimation_in_mins'] = "30";
$res['last_update'] = $commandData['data']['command']['last_update'];
$res['start_time'] = $commandData['data']['command']['start_time'];
$res['start_date'] = $commandData['data']['command']['start_date'];
$res['state'] = $commandData['data']['command']['state'];
$res['delivery_time_estimation_in_mins'] = "30";
$res['receipt_image'] = $out_of_app_order->getReceipt();
$res['additionnal_info'] = $out_of_app_order->getAdditionnalInfo();
$res['phone_numnber'] = $out_of_app_order->getPhoneNumber();
return new Response($this->serializer->serialize($this->okResponseBlob($res), 'json'), 200);
}
/**
* @Route("api/token/generate", name="api_token_generate", methods={"POST"})
*/
public function generateJwt(Request $request): JsonResponse
{
$data = json_decode($request->getContent(), true);
$client = $this->entityManager->getRepository(Client::class)->findOneBy(['username' => $data['username']]);
if ($client) {
$privateKeyPath = $this->getParameter('kernel.project_dir') . '/config/jwt/private.pem';
$privateKey = file_get_contents($privateKeyPath);
$payload = [
'roles' => ['ROLE_USER'],
'username' => $data['username'],
'iat' => time(),
'exp' => time() + (10 * 365 * 24 * 60 * 60)
];
$jwt = JWT::encode($payload, $privateKey, 'RS256');
return new JsonResponse(['token' => $jwt]);
} else {
return new JsonResponse(['Error' => "User doesnt exists"]);
}
}
/**
* @Route("mobile/api/v4/livreur/out_of_app_order/update", name="update_out_of_app_order", methods={"POST"})
*/
public function UpdateOutOfAppOrder(Request $request)
{
$currentToken = $this->get('security.token_storage')->getToken();
$data = json_decode($request->getContent(), 'true');
$command_id = $data['command_id'];
$res = [];
$command = $this->entityManager->getRepository(Command::class)->find($command_id);
//change me depending on env.
$endPoint = "http://app.kaba-delivery.com/livreur/api/command/modify";
$content = [
'headers' => [
'Authorization' => 'Bearer ' . $currentToken->getCredentials(),
'Accept' => 'application/json',
'Cache-Control' => 'no-cache',
],
'json' => [
'command_id' => $command_id,
],
];
if (isset($data['order_address'])) {
$names = array_map(function ($product) {
return $product['name'];
}, $data['temp_product']);
$result = implode(",", $names);
//check if its an update on order address
if ($data['order_address'] != null) {
$client = $this->entityManager->getRepository(Client::class)->find($command->getClientId());
$order_address_entity = new Adresses();
$order_address_entity->setDescription("Achat pour le produit " . $result);
$order_address_entity->setName("Achat pour le produit" . $data['temp_product'][0]['name']);
$order_address_entity->setPhoneNumber($client->getUsername());
$order_address_entity->setLocation($data['order_address']);
$order_address_entity->setNear("azertyuiop");
$order_address_entity->setQuartier("Aucun");
$order_address_entity->setDescriptionDetails("Achat pour le produit " . $result);
$order_address_entity->setUserId($command->getClientId());
$order_address_entity->setUpdatedAt(date("Y-m-d H:i:s"));
$order_address_entity->setState(1);
$order_address_entity->setLocation($data['order_address']);
$address_to_delete = $this->entityManager->getRepository(Adresses::class)->findOneBy(['name' => "Achat pour le produit " . $data['temp_product'][0]['name']]);
if ($address_to_delete) {
$this->entityManager->remove($address_to_delete);
}
$this->entityManager->persist($order_address_entity);
$this->entityManager->flush();
$client_id = $command->getClientId();
$voucher_usage = $this->entityManager->getRepository(VoucherUsage::class)->findOneBy([
'commandId' => $command_id,
'userId' => $client_id
]);
$jsonData = json_encode([
"order_details" => $data['temp_product'],
"order_address" => [$order_address_entity->getId()],
"shipping_address" => $command->getShippingAddress()["id"],
"voucher_id" => $voucher_usage ? $voucher_usage->getVoucherId() : null,
"use_kaba_point" => false,
"pay_at_delivery" => true,
"user_id" => $client_id
]);
$billingRequest = new Request(
[],
[],
[],
[],
[],
[
'CONTENT_TYPE' => 'application/json',
],
$jsonData
);
$user = $this->entityManager->getRepository(Client::class)->find($client_id);
$type = filter_var($user->getUsername(), FILTER_VALIDATE_EMAIL) ? 2 : 1;
$getBilling = $this->getOutOfAppOrderBilling($billingRequest);
$getBillingContent = $getBilling->getContent();
$getBillingData = json_decode($getBillingContent, true);
$order_address_array = $this->getAdress($order_address_entity->getId());
$res['distance'] = $getBillingData['data']['distance'];
$res['shipping_pricing'] = $getBillingData['data']['shipping_pricing'];
$res['command_pricing'] = $getBillingData['data']['command_pricing'];
$res['additional_fees'] = $getBillingData['data']['additional_fees_total_price'];
$res['out_of_range'] = $getBillingData['data']['out_of_range'];
$res['total_pricing'] = $getBillingData['data']['total_pricing'];
$standard_price = $this->shippingPricing($order_address_entity->getId(), $command->getShippingAddress()["id"], $type);
$without_promotion_billing_for_email = $standard_price["email_account_billing"];
$extra_shipping_pricing = intval($standard_price["email_account_billing"]) - intval($getBillingData['data']['reduced_shipping_price']);
$command->setLastUpdate(date("Y-m-d H:i:s"));
$command->setShippingPricing(strval($getBillingData['data']['reduced_shipping_price']));
$command->setEmailAccountShippingPricing(strval($without_promotion_billing_for_email));
$command->setPhoneNumberAccountShippingPricing(strval($getBillingData['data']['reduced_shipping_price']));
$command->setExtraShippingPricing(strval($extra_shipping_pricing));
$command->setBaseShippingPricing(strval($standard_price["billing"]));
$command->setOrderShippingAddress($order_address_array);
$this->entityManager->persist($command);
$this->entityManager->flush();
}
}
if (isset($data['foods'])) {
//check if its an update on food price
if ($data['foods'] != null) {
$food_list = [];
$order_details = [];
$normalizer = new Serializer([new ObjectNormalizer()]);
foreach ($data['foods'] as $food) {
$food_item = $this->entityManager->getRepository(Food::class)->find($food['id']);
$food_item->setPrice($food['price']);
$this->entityManager->persist($food_item);
$food_command = $command->getFoodCommand();
$food_shipping = null;
foreach ($food_command as $fc) {
if ($fc['food_id'] == $food_item->getId()) {
$food_shipping = $fc['food_shipping'];
break;
}
}
array_push($food_list, [
'food_id' => $food_item->getId(),
'quantity' => $food['quantity'],
'food_entity' => $normalizer->normalize($food_item),
'food_shipping' => $food_shipping
]);
array_push($order_details, [
"name" => $food_item->getName(),
"image" => $food_item->getPic(),
"price" => $food_item->getPrice(),
"quantity" => $food['quantity']
]);
}
$command->setFoodCommand($food_list);
$command->setOrderDetails($order_details);
$this->entityManager->persist($command);
$this->entityManager->flush();
}
}
$response = $this->http_client->request('POST', $endPoint, $content);
return new JsonResponse($res);
}
/**
* @Route("mobile/api/v4/livreur/order_receipt/update", name="update_order_receipt", methods={"POST"})
*/
public function updateOrderReceipt(Request $request)
{
$data = json_decode($request->getContent(), true);
$command_id = $data['command_id'];
$receipt = $data['image_link'];
$out_of_app_order = $this->entityManager->getRepository(OutOfAppOrder::class)->findOneBy(['commandId' => $command_id]);
$out_of_app_order->setReceipt($receipt);
$this->entityManager->persist($out_of_app_order);
$this->entityManager->flush();
return new JsonResponse(['message' => 'Receipt updated successfully']);
}
/**
* @Route("mobile/api/v4/livreur/command/additionnal_images/get", name="get_command_additionnal_images", methods={"POST"})
*/
public function getCommandAdditionnalImages(Request $request)
{
$data = json_decode($request->getContent(), true);
$command_id = $data['command_id'];
$images = [];
$out_of_app_order = $this->entityManager->getRepository(OutOfAppOrder::class)->findOneBy(['commandId' => $command_id]);
if ($out_of_app_order) {
$images = $out_of_app_order->getAdditionnalImageLinks();
foreach ($images as $image) {
array_push($images, $image);
}
return new JsonResponse(['images' => $images]);
} else {
return new JsonResponse(['images' => []]);
}
}
public function setDefaultOrderAddress($shipping_address, $currentToken)
{
$order_address_id = null;
$batchSize = 100;
$offset = 0;
do {
$addresses = $this->entityManager->createQueryBuilder()
->select('a.location, a.id')
->from(Adresses::class, 'a')
->setFirstResult($offset)
->setMaxResults($batchSize)
->getQuery()
->getArrayResult();
foreach ($addresses as $address) {
$distance = $this->getDistance($shipping_address->getLocation(), $address['location']);
if ($distance <= 1000) {
return $address['id'];
}
}
$offset += $batchSize;
} while (count($addresses) === $batchSize);
return null;
}
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 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();
}
public function shippingPricing($order_address, $shipping_address, $type = 1)
{
$orderAdress = $this->entityManager->getRepository(Adresses::class)->find($order_address);
$shippingAddress = $this->entityManager->getRepository(Adresses::class)->find($shipping_address);
$response = $this->getDistance($orderAdress->getLocation(), $shippingAddress->getLocation());
$distance = $response;
$billing = 0;
$emailAccountBilling = 0;
$phoneNumberAccountBilling = 0;
$out_of_range = false;
$db_billing = $type == 2 ? $this->entityManager->getRepository(Billing2::class)->findAll() : $this->entityManager->getRepository(Billing::class)->findAll();
$db_phoneNumber_billing = $this->entityManager->getRepository(Billing::class)->findAll();
$db_email_account_billing = $this->entityManager->getRepository(Billing2::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 ($db_phoneNumber_billing != null) {
foreach ($db_phoneNumber_billing as $item) {
if ($distance >= intval($item->getRangeStart()) * 1000 && $distance < intval($item->getRangeEnd()) * 1000) {
$phoneNumberAccountBilling = $item->getValue();
}
}
}
if ($db_email_account_billing != null) {
foreach ($db_email_account_billing as $item) {
if ($distance >= intval($item->getRangeStart()) * 1000 && $distance < intval($item->getRangeEnd()) * 1000) {
$emailAccountBilling = $item->getValue();
}
}
}
if ($billing == 0) {
$out_of_range = true;
}
return [
'billing' => $billing,
'email_account_billing' => $emailAccountBilling,
'phoneNumber_account_billing' => $phoneNumberAccountBilling,
'out_of_range' => $out_of_range,
'distance' => $distance
];
}
private function calculate_shipping_price($distance, $currentToken)
{
if (is_string($currentToken)) {
$jwtData = json_decode(base64_decode(explode('.', $currentToken)[1]), true);
$username = $jwtData['username'];
$type = filter_var($username, FILTER_VALIDATE_EMAIL) ? 2 : 1;
} else {
$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);
return $shipping_price;
}
private function configsWithVoucher($data, $currentToken, $user, $order_address, $shipping_address)
{
$distance = $this->getDistance($order_address->getLocation(), $shipping_address->getLocation());
$voucher_billing = 0;
$is_voucher_on_billing = false;
$is_voucher_on_billing_already_applyed = false;
$check_voucher_valid = $this->checkIfVoucherValid($user->getId(), $data["voucher_id"]);
$type = 1;
if (is_string($currentToken)) {
$jwtData = json_decode(base64_decode(explode('.', $currentToken)[1]), true);
$username = $jwtData['username'];
$type = filter_var($username, FILTER_VALIDATE_EMAIL) ? 2 : 1;
} else {
$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) {
$is_voucher_on_billing = true;
break;
}
}
}
}
if ($check_voucher_valid["valid"] == true) {
// check if reduction on billing
if ($check_voucher_valid["type"] == 2) {
if ($is_voucher_on_billing) {
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;
}
}
}
}
$configs_with_voucher = [];
$configs_with_voucher["voucher_billing"] = $voucher_billing;
$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 get_kaba_point($client_id, $shipping_price)
{
$kabaPoint = $this->getMiniKabaPointBalance($client_id, $shipping_price);
return $kabaPoint;
}
private function getOutOfAppAdditionnalFees($shipping_price, $shipping_address, $order_address)
{
$weather_fee = 0;
$night_fee = 0;
$week_end_fee = 0;
$holy_day_fee = 0;
$kaba_fee = 0;
//ADD WEATHER_FEE
$raining_in_order_zone = false;
$raining_in_customer_zone = false;
$zones = $this->entityManager->getRepository(Zone::class)->findAll();
//check if order's zone
$order_zone = null;
foreach ($zones as $zone) {
list($orderLat, $OrderLng) = explode(':', $order_address->getLocation());
$location = json_decode($zone->getLocation(), true);
$latitude = $location['lat'];
$longitude = $location['lng'];
$distance = $this->haversineDistance(
(float)$orderLat,
(float)$OrderLng,
$latitude,
$longitude
);
if ($distance <= $zone->getRadius()) {
$order_zone = $zone;
break;
}
}
if ($order_zone) {
$weather_rule = $this->entityManager->getRepository(WeatherRule::class)->findOneBy(['zone_id' => $order_zone->getId()]);
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_order_zone = $weather_rule->isEnabled();
if ($current_time->format('H:i') > $time_end->format('H:i')) {
$raining_in_order_zone = false;
$weather_rule->setEnabled(false);
$this->entityManager->persist($weather_rule);
$this->entityManager->flush();
}
}
}
//check shipping zone
$customer_zone = null;
foreach ($zones as $zone) {
list($clientLat, $clientLng) = explode(':', $shipping_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_order_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));
}
}
}
//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));
}
}
}
//ADD KABA FEE
$kaba_commission_fee = $this->entityManager->getRepository(AdditionalFees::class)->findOneBy(['fee_type' => AdditionnalFeeType::OUT_OF_APP_FEE]);
if ($kaba_commission_fee->isEnabled()) {
if ($kaba_commission_fee->getAmountType() == AdditionnalFeeAmountType::PRIX_FIX) {
$kaba_fee = $kaba_commission_fee->getAmountValue();
} else {
$kaba_fee = ($shipping_price * ($kaba_commission_fee->getAmountValue() / 100));
}
}
$fees = [$weather_fee, $night_fee, $week_end_fee, $holy_day_fee,$kaba_fee];
$count = 0;
foreach ($fees as $fee) {
if ($fee > 0) {
$count++;
}
}
if ($count > 3) {
$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]);
$kaba_commission_fee = $this->entityManager->getRepository(AdditionalFees::class)->findOneBy(['fee_type' => AdditionnalFeeType::OUT_OF_APP_FEE]);
$fees_entities = [$weather_additional_fee, $night_additional_fee, $week_end_additional_fee, $public_holiday_additional_fee,$kaba_commission_fee];
usort($fees_entities, function ($a, $b) {
return $a->getPriority() - $b->getPriority();
});
$top_two_entities = array_slice($fees_entities, 0, 3);
$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;
}
if (!in_array(AdditionnalFeeType::OUT_OF_APP_FEE, $selected_fee_types)) {
$kaba_fee = 0;
}
}
$res = [];
$res["WEATHER_FEE"] = $weather_fee;
$res["NIGHT_FEE"] = $night_fee;
$res["PUBLIC_HOLYDAY_FEE"] = $holy_day_fee;
$res["WEEKEND_FEE"] = $week_end_fee;
$res["OUT_OF_APP_FEE"] = $kaba_fee;
return $res;
}
public function getAdditionalFeesTotalPricing($additional_fees)
{
$total_additional_fees_pricing = 0;
foreach ($additional_fees as $additional_fee) {
$total_additional_fees_pricing += $additional_fee;
}
return $total_additional_fees_pricing;
}
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 get_total_pricing($res, $configs_with_voucher, $data, $kabaPoint, $command_pricing)
{
$total_pricing = 0;
$total_pricing = $res['shipping_pricing'];
if (isset($data["voucher_id"]) && $data["voucher_id"] != null) {
$voucher_billing = intval($configs_with_voucher["voucher_billing"]) < 0 ? 0 : $configs_with_voucher["voucher_billing"];
$total_pricing = intval($voucher_billing);
}
if (isset($data['use_kaba_point']) && $data['use_kaba_point']) {
$amount = intval($kabaPoint["amount_to_reduce"]);
$total_pricing = $res["shipping_pricing"] - $amount;
}
$type = [];
$type["total_pricing"] = $total_pricing;
$total_pricing += $res['additional_fees_total_price'] + $command_pricing;
return $total_pricing;
}
private function getReducedShippingPrice($data, $configs_with_voucher, $kabaPoint, $res)
{
$reducedShippingPrice = $res['shipping_pricing'];
if (isset($data["voucher_id"]) && $data["voucher_id"] != null) {
$voucher_billing = intval($configs_with_voucher["voucher_billing"]) < 0 ? 0 : $configs_with_voucher["voucher_billing"];
$reducedShippingPrice = intval($voucher_billing);
}
if (isset($data['use_kaba_point']) && $data['use_kaba_point']) {
$amount = intval($kabaPoint["amount_to_reduce"]);
$reducedShippingPrice = $res["shipping_pricing"] - $amount;
}
return $reducedShippingPrice;
}
public function getRemise($big, $small)
{
$remise = (intval($small) * 100) / intval($big);
return intval($remise);
}
private function getCommandPricing($food_command)
{
$pricing = 0;
foreach ($food_command as $i => $food) {
$pricing += (intval($food['price']) * intval($food["quantity"]));
}
return $pricing;
}
private function isOutOfRange($distance)
{
if ($distance >= 15000)
return true;
else
return false;
}
private function getCommandDetails($food_command, $order_address, $shipping_address, $voucher_id = null, $user_id = null, $use_kaba_point = false)
{
$price = 0;
$food_litteral = "";
$is_voucher_used = false;
$is_billing_voucher_used = false;
$haveBillingDiscount = false;
$voucher_billing = 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($order_address, $shipping_address, $type);
$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"]);
foreach ($food_command as $i => $food) {
if ($i != 0) $food_litteral .= "+";
$food_command[$i]["food_entity"] = [];
$food_litteral .= $food['name'];
$price += (intval($food['price']) * intval($food["quantity"]));
$food_command[$i]["food_shipping"] = [];
$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);
if ($check_voucher_valid["valid"] == true) {
if (($check_voucher_valid["type"] == 2 || $check_voucher_valid["type"] == 3)) {
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) {
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;
}
}
}
}
}
$food_command[$i]["food_shipping"] = [];
$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);
}
$additional_fees = $this->getOutOfAppAdditionnalFees($billing, $shipping_address, $order_address);
$additional_fee_total_price = $this->getAdditionalFeesTotalPricing($additional_fees);
$food_price = $price;
$food_billing = $billing;
$data = [];
$discount = 0;
$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;
}
$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"]["shipping_pricing"] = intval($voucher_billing);
$data["voucher_pricing"]["total_pricing"] = intval($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_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_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["is_voucher_used"] = $is_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["without_promo"]["price"] = intval($additional_fee_total_price);
$data["without_promo"]["billing"] = intval($without_promotion_billing);
$data["without_promo"]["total"] = intval($without_promotion_billing + $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['additional_fees'] = $additional_fees;
$data['additional_fee_total_price'] = $additional_fee_total_price;
$data["haveBillingDiscount"] = $haveBillingDiscount;
return $data;
}
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 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 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;
}
$restaurant = $this->entityManager->getRepository(RestaurantConfig::class)->find($command->getRestaurantId());
$shipping_address = $command->getShippingAddress();
$order_shipping_address = $command->getOrderShippingAddress();
$standard_price = $this->shippingPricing($order_shipping_address['id'], $shipping_address['id'], $type);
$billing = intval($standard_price["billing"]);
$promotion_billing = intval($command->getShippingPricing());
/*check if voucher has been used*/
$voucher_billing = 0;
$voucher_food_price = 0;
$is_voucher_used = 0;
$is_food_voucher_used = 0;
$is_billing_voucher_used = 0;
$tmp["food_list"] = [];
$tmp["order_type"] = $command->getOrderType();
$tmp['start_date'] = strval($command->getStartDate());
$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->getOrderDetails() as $food) {
$price_command += intval($food["price"]) * intval($food["quantity"]);
$food["quantity"] = strval($food["quantity"]);
$food["price"] = strval($food["price"]);
array_push($tmp["food_list"], $food);
}
$price_remise = $price_command;
$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->getOrderDetails());
$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"] = $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["start_delivery"] = $command->getStartOfDelivery();
$tmp["end_delivery"] = $command->getEndOfDelivery();
$tmp["start_time"] = $command->getStartTime();
$tmp["start_date"] = $command->getStartDate();
$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"] = '' . ($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;
}
public function forMobileWithVoucherCommandToArray(Command $command)
{
$com = [];
$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();
$order_address = $command->getOrderShippingAddress();
$standard_price = $this->shippingPricing($order_address['id'], $shipping_address['id'], $type);
$billing = intval($standard_price["billing"]);
$promotion_billing = intval($command->getShippingPricing());
$price_remise = 0;
$price_command = 0;
$is_promo = 0;
$is_preorder = 0;
$com["food_list"] = [];
if (!empty($command->getOrderDetails()) && is_iterable($command->getOrderDetails())) {
foreach ($command->getOrderDetails() as $i => $food_command) {
$food = $food_command;
$price_command += intval($food["price"]) * intval($food_command["quantity"]);
$fd = [];
$fd["name"] = $food["name"];
$fd["price"] = strlen($food["price"]) > 0 ? strval($food["price"]) : "0";
$fd["quantity"] = strlen($food_command["quantity"]) > 0 ? strval($food_command["quantity"]) : "0";
$fd["pic"] = $food["pic"] ?? "";
array_push($com["food_list"], $fd);
}
}
$state = intval($command->getState());
if ($state == 2 || $state == 3) {
$livreur = $this->entityManager->getRepository(Livreur::class)->find(intval($command->getLivreurId()));
if ($livreur != null) {
$com["livreur"] = $this->livreurToArrayDashboard($livreur);
}
}
$com["kaba_point_used_amount"] = 0;
if ($command->getKabaPoint() != null) {
$is_promo = 1;
$com["kaba_point_used_amount"] = $command->getKabaPointAmount();
}
$client = $this->entityManager->getRepository(Client::class)->find(intval($command->getClientId()));
$com["id"] = $command->getId();
$com["customer_username"] = '';
if ($client != null) {
$com["customer_username"] = $client->getUsername();
}
$com["restaurant_entity"] = [];
$restaurant = $this->entityManager->getRepository(RestaurantConfig::class)->find($command->getRestaurantId());
$com["restaurant_entity"]["id"] = $restaurant->getId();
$com["restaurant_entity"]["name"] = $restaurant->getName();
$com["restaurant_entity"]["pic"] = '/' . $this->getParameter('rp') . '/' . $restaurant->getPic();
$com["shipping_address"] = $shipping_address;
if (isset($com["shipping_address"]["user"])) {
$com["shipping_address"]["user"] = [];
}
$com["is_promotion"] = $is_promo;
$com["is_preorder"] = $is_preorder;
$com["shipping_pricing"] = intval($billing);
$com["food_pricing"] = $price_command;
$com["total_pricing"] = $billing + $price_command;
$com["promotion_shipping_pricing"] = $promotion_billing;
$com["promotion_food_pricing"] = $price_command;
$com["without_voucher_promotion_shipping_pricing"] = $billing;
$com["without_voucher_promotion_food_pricing"] = $price_command;
$com["promotion_total_pricing"] = $promotion_billing + $price_command;
$com["preorder_shipping_pricing"] = $promotion_billing;
$com["preorder_food_pricing"] = $price_command;
$com["preorder_total_pricing"] = $promotion_billing + $price_command;
$com["is_voucher_used"] = 0;
$com["preorder"] = $command->getPreOrder();
$com["preorder_hour"] = null;
if ($command->getPreOrder() == 1) {
$preorder_hour = $this->entityManager->getRepository(PreorderCommandDetails::class)->findOneBy([
'commandId' => $command->getId()
]);
if ($preorder_hour != null) {
$com["preorder_hour"]["start"] = $preorder_hour->getStart();
$com["preorder_hour"]["end"] = $preorder_hour->getEnd();
$com["preorder_discount"] = "" . $preorder_hour->getDiscount();
}
}
$com["foods_count"] = count($command->getFoodCommand());
$com["last_update"] = strtotime($command->getLastUpdate());
$com["last_update_sample"] = $command->getLastUpdate();
$com["start_time"] = $command->getStartTime();
$com["start_date"] = $command->getStartDate();
$com["state"] = $state;
$com["infos"] = $command->getInfos() ?? "";
$com["reason"] = $command->getReason();
$com["passphrase"] = $command->getPassPhrase();
$com["is_payed_at_arrival"] = $command->getPayAtDelivery();
$com["order_type"] = $command->getOrderType();
$rating = 0;
$comment = '';
$repo = $this->entityManager->getRepository(DeliveryRating::class);
$rate = $repo->findOneBy([
'commandId' => $command->getId()
]);
if ($rate != null) {
$rating = $rate->getRating()??0;
$comment = $rate->getComment();
}
$com["rating"] = $rating;
$com["comment"] = $comment;
$com["voucher_entity"] = [];
$voucher_datas = $this->processVoucherDatas($command, $promotion_billing, $billing, $price_remise);
if ($voucher_datas["is_voucher_used"]) {
$com["is_promotion"] = 1;
$com["promotion_shipping_pricing"] = $voucher_datas["shipping_pricing"];
$com["promotion_total_pricing"] = intval($price_command) + intval($voucher_datas["shipping_pricing"]);
$com["is_voucher_used"] = 1;
if ($voucher_datas["voucher_id"] != null) {
$voucher = $this->entityManager->getRepository(Voucher::class)->find($voucher_datas["voucher_id"]);
if ($voucher != null) {
$com["voucher_entity"] = $this->voucherToArrayLite($voucher);
}
}
}
$haveBonus = $this->entityManager->getRepository(PayBonus::class)->findOneBy(["clientId" => $user->getId(), "commandId" => $command->getId()]);
if ($haveBonus != null && $haveBonus->getOfferType() == '1') {
$com["is_promotion"] = 1;
$com["promotion_total_pricing"] -= $com["promotion_shipping_pricing"];
$com["promotion_shipping_pricing"] = 0;
$com["preorder_total_pricing"] -= $com["preorder_shipping_pricing"];
$com["preorder_shipping_pricing"] = 0;
$com["without_voucher_promotion_shipping_pricing"] = 0;
}
return $com;
}
public function processVoucherDatas($command, $shipping_pricing, $billing, $price_remise)
{
/*check if voucher has been used*/
$check_voucher_usage = $this->entityManager->getRepository(VoucherUsage::class)->findOneBy([
'commandId' => $command->getId(),
'userId' => $command->getClientId(),
]);
$voucher_id = null;
if ($check_voucher_usage != null) {
$voucher_id = $check_voucher_usage->getVoucherId();
}
$get_voucher_datas = $this->getVoucherApplyDatas($command->getClientId(), $voucher_id);
$voucher_billing = 0;
$voucher_food_price = 0;
$is_voucher_used = false;
$is_food_voucher_used = false;
$is_billing_voucher_used = false;
$is_voucher_on_billing_already_applyed = false;
$com = [];
$com["price_remise"] = intval($price_remise);
$com["shipping_pricing"] = intval($shipping_pricing);
$com["is_voucher_used"] = false;
$com["is_billing_promotion"] = false;
$com["voucher_id"] = $voucher_id;
$voucher_billing = intval($billing);
foreach ($command->getFoodCommand() as $food_command) {
$food = $food_command["food_entity"];
/*voucher */
$vouch_price = intval($food["price"]) * intval($food_command["quantity"]);
$reduction = 0;
if ($get_voucher_datas["valid"] == true) {
/*check if that food is in array of concerned foods*/
if (
in_array(intval($food["id"]), $get_voucher_datas["products"])
|| sizeof($get_voucher_datas["products"]) == 0 /*coz if products =[] it means all foods are selected*/
) {
if ($get_voucher_datas["type"] == 1 || $get_voucher_datas["type"] == 3) { /* reduction on food or all*/
if ($get_voucher_datas["category"] == 1) {
/*in percent*/
$reduction = (intval($food["price"]) * $get_voucher_datas["value"]) / 100;
$is_voucher_used = true;
$is_food_voucher_used = true;
} else {
$reduction = $get_voucher_datas["value"];
$is_voucher_used = true;
$is_food_voucher_used = true;
}
}
}
if ($get_voucher_datas["type"] == 2 || $get_voucher_datas["type"] == 3) {
if (
in_array("" . $command->getRestaurantId(), $get_voucher_datas["restaurant_allowed"])
|| sizeof($get_voucher_datas["restaurant_allowed"]) == 0 /*coz if restaurant_allowed =[] it means all restos are selected*/
) {
if (!$is_voucher_on_billing_already_applyed) {
if ($get_voucher_datas["category"] == 1) {
/*in percent*/
$reductions = ($voucher_billing * $get_voucher_datas["value"]) / 100;
$voucher_billing -= $reductions;
$is_voucher_used = true;
$is_billing_voucher_used = true;
$is_voucher_on_billing_already_applyed = true;
} else {
$voucher_billing -= intval($get_voucher_datas["value"]);
$is_voucher_used = true;
$is_billing_voucher_used = true;
$is_voucher_on_billing_already_applyed = true;
}
}
}
}
}
$final_food_price = $vouch_price - ($reduction * intval($food_command["quantity"]));
$voucher_food_price += $final_food_price;
}
if ($check_voucher_usage != null && $is_voucher_used) {
$voucher_food_price = intval($voucher_food_price) < 0 ? 0 : $voucher_food_price;
$voucher_billing = intval($voucher_billing) < 0 ? 0 : $voucher_billing;
if ($is_food_voucher_used) {
$com["price_remise"] = $voucher_food_price;
}
if ($is_billing_voucher_used) {
$com["shipping_pricing"] = $voucher_billing;
$com["is_billing_promotion"] = true;
}
$com["is_voucher_used"] = true;
}
return $com;
}
private function createColisFoods($products)
{
$menu = $this->entityManager->getRepository(Menu::class)->findOneBy(['name' => "KABA_COLIS"]);
$resto = $this->entityManager->getRepository(RestaurantConfig::class)->findOneBy([
'username' => "kaba_colis"
]);
$foods = [];
if (!$menu) {
$menu = new Menu();
$menu->setName("KABA_COLIS");
$menu->setDescription("Le menu des commandes colis");
$menu->setPic("");
$menu->setState(1);
$menu->setPromotion(0);
$menu->setRestaurantId($resto->getId());
$menu->setDeleted(0);
$menu->setPriority(1);
$menu->setLastUpdate(date("d-m-Y H:i:sa"));
$em = $this->entityManager;
$em->persist($menu);
$em->flush();
}
$res = $this->createOutOfAppFoods($products, $menu, $resto);
return $res;
}
private function createHorsAppliFoods($products)
{
$menu = $this->entityManager->getRepository(Menu::class)->findOneBy(['name' => "HORS_APPLI"]);
$resto = $this->entityManager->getRepository(RestaurantConfig::class)->findOneBy([
'username' => "hors_appli"
]);
$foods = [];
if (!$menu) {
$menu = new Menu();
$menu->setName("HORS_APPLI");
$menu->setDescription("Le menu des commandes hors appli");
$menu->setPic("");
$menu->setState(1);
$menu->setPromotion(0);
$menu->setRestaurantId($resto->getId());
$menu->setDeleted(0);
$menu->setPriority(1);
$menu->setLastUpdate(date("d-m-Y H:i:sa"));
$em = $this->entityManager;
$em->persist($menu);
$em->flush();
}
$res = $this->createOutOfAppFoods($products, $menu, $resto);
return $res;
}
private function createOutOfAppFoods($products, $menu, $resto)
{
$normalizer = new Serializer([new ObjectNormalizer()]);
$foods = [];
foreach ($products as $food) {
$new_food = new Food();
$new_food->setMenuId($menu->getId());
$new_food->setName($food['name']);
$new_food->setDescription("");
$new_food->setPriority(1);
$new_food->setDeleted(0);
$new_food->setRestaurantId($resto->getId());
$new_food->setRestaurant($resto);
$new_food->setCategory(1);
$new_food->setPromotion(0);
$new_food->setState(1);
$new_food->setPic($food['image']);
$new_food->setPrice($food['price']);
$new_food->setPromotionPrice($food['price']);
$new_food->setFoodDetailsPictures([$food['image']]);
$new_food->setLastUpdate(date("d-m-Y H:i:sa"));
$em = $this->entityManager;
$em->persist($new_food);
$em->flush();
array_push($foods, [
'food_id' => $new_food->getId(),
'quantity' => $food['quantity'],
'food_entity' => $normalizer->normalize($new_food),
'food_shipping' => $food['food_shipping']
]);
}
return $foods;
}
private function applySubscriptionOnOrder($distance, $subscriptionData, $promotion_shipping_pricing)
{
$promotion_shipping_pricing = $promotion_shipping_pricing;
try {
if (!$subscriptionData || empty($subscriptionData)) {
return $promotion_shipping_pricing;
}
$packData = $subscriptionData['pack'] ?? null;
if (!$packData) {
return $promotion_shipping_pricing;
}
$endDate = isset($subscriptionData['end_date']) ? new DateTime($subscriptionData['end_date']) : null;
$now = new DateTime();
$isBefore = $endDate ? ($now < $endDate) : false;
$radius_limit = isset($packData['radius_km']) ? floatval($packData['radius_km']) : 0;
$delivery_limit = isset($packData['deliverylimit']) ? intval($packData['deliverylimit']) : 0;
$usage_count = isset($subscription['alreadyUsed']) ? intval($subscription['alreadyUsed']) : 0;
if (!$isBefore) {
return $promotion_shipping_pricing;
}
if ($distance < ($radius_limit * 1000)) {
$promotion_shipping_pricing = 0;
return $promotion_shipping_pricing;
}
if ($usage_count < $delivery_limit) {
$promotion_shipping_pricing = 0;
return $promotion_shipping_pricing;
}
} catch (Exception $e) {
error_log("Error in applySubscriptionOnOrder: " . $e->getMessage());
}
return $promotion_shipping_pricing;
}
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;
}
}
}