<?php
namespace App\Controller;
use App\Entity\Cart;
use App\Entity\Company;
use App\Entity\Grade;
use App\Entity\Imei;
use App\Entity\Order;
use App\Entity\Product;
use App\Entity\Shop;
use App\Entity\Status;
use App\Entity\User;
use App\Form\CompanyType;
use App\Form\OrderCommentType;
use App\Form\OrderCouponType;
use App\Form\OrderDeliveryType;
use App\Form\OrderSummaryType;
use App\Form\OrderType;
use App\Repository\AddressRepository;
use App\Repository\CartRepository;
use App\Repository\CompanyRepository;
use App\Repository\CouponRepository;
use App\Repository\DeliveryRepository;
use App\Repository\GradeRepository;
use App\Repository\ImeiRepository;
use App\Repository\OptionRepository;
use App\Repository\OrderRepository;
use App\Repository\ProductRepository;
use App\Repository\ShopRepository;
use App\Repository\StatusRepository;
use App\Repository\UserRepository;
use App\Service\DeliveryService;
use App\Service\OptionService;
use App\Service\PriceService;
use App\Service\ShopService;
use Doctrine\Persistence\ManagerRegistry;
use Knp\Bundle\SnappyBundle\KnpSnappyBundle;
use Knp\Component\Pager\PaginatorInterface;
use Knp\Snappy\GeneratorInterface;
use Knp\Snappy\Pdf;
use Psr\Log\LoggerInterface;
use Symfony\Bridge\Twig\Mime\TemplatedEmail;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
use Symfony\Component\HttpFoundation\File\Exception\FileException;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\ParameterBag;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Mailer\Exception\TransportExceptionInterface;
use Symfony\Component\Mailer\Mailer;
use Symfony\Component\Mailer\MailerInterface;
use Symfony\Component\Messenger\MessageBusInterface;
use Symfony\Component\Mime\Address;
use Symfony\Component\Mime\Mail;
use Symfony\Component\Mime\Part\DataPart;
use Symfony\Component\Mime\Part\File;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\String\Slugger\SluggerInterface;
use Symfony\Contracts\HttpClient\HttpClientInterface;
/**
* @Route("/{_locale<%app.supported_locales%>}/order")
*/
class OrderController extends AbstractController
{
private $doctrine;
private $bak2life_api_url;
private $bak2life_api_key;
private $mailer_sender;
private $bak2_api_url;
private $bak2_mp_buyer_id;
public function __construct(ParameterBagInterface $params)
{
$this->bak2life_api_url = $params->get('app.bak2life_api_url');
$this->bak2_api_url = $params->get('app.bak2_api_url');
$this->bak2_mp_buyer_id = $params->get('app.bak2_mp_buyer_id');
$this->mailer_sender = $params->get('app.mailer_sender');
}
/**
* @Route("/", name="app_order_index", methods={"GET"})
*/
public function index(OrderRepository $orderRepository, ShopRepository $shopRepository, PaginatorInterface $paginator, Request $request): Response
{
$user = $this->getUser();
$shop = $user->getShop();
$tOrders=$orderRepository->findBy(['shop'=>$shop->getId()]);
foreach($tOrders as $o) {
$o->setActive(1);
$orderRepository->add($o);
}
if ($this->isGranted('ROLE_SUPER_ADMIN')) {
//$orders = $orderRepository->findAll();
$query=$orderRepository->findAllDql();
$orders = $paginator->paginate(
$query, /* query NOT result */
$request->query->getInt('page', 1), /*page number*/
30 /*limit per page*/
);
} else if ($this->isGranted('ROLE_ADMIN')) {
$query=$orderRepository->findByDql(['shop'=>$shop->getId()]);
$orders = $paginator->paginate(
$query, /* query NOT result */
$request->query->getInt('page', 1), /*page number*/
30 /*limit per page*/
);
} else {
$query=$orderRepository->findByDql(['user'=>$this->getUser()->getId()]);
$orders = $paginator->paginate(
$query, /* query NOT result */
$request->query->getInt('page', 1), /*page number*/
30 /*limit per page*/
);
}
return $this->render('order/index.html.twig', [
'orders' => $orders,
]);
}
/**
* @Route("/new", name="app_order_new", methods={"GET", "POST"})
*/
public function new(Request $request, OrderRepository $orderRepository): Response
{
$order = new Order();
$order->setActive(1);
$form = $this->createForm(OrderType::class, $order);
$form->handleRequest($request);
$user = $this->getUser();
$shop=$user->getShop();
if ($form->isSubmitted() && $form->isValid()) {
$order->setActive(1);
$orderRepository->add($order);
return $this->redirectToRoute('app_order_index', [], Response::HTTP_SEE_OTHER);
}
return $this->renderForm('order/new.html.twig', [
'order' => $order,
'form' => $form,
'shop'=>$shop,
'user'=>$user
]);
}
/**
* @Route("/{id}", name="app_order_show", methods={"GET"})
*/
public function show(Order $order, OptionService $optionService): Response
{
$user=$order->getUser();
$shop=$user->getShop();
if ($user == $this->getUser() || $this->isGranted('ROLE_ADMIN')) {
return $this->render('order/show.html.twig', [
'order' => $order,
'shop'=>$shop,
'user'=>$user,
'cartOptions'=>$optionService->getCartOptions($order)
]);
}
return $this->redirectToRoute('app_order_index', [], Response::HTTP_SEE_OTHER);
}
/**
* @Route("/{id}/edit", name="app_order_edit", methods={"GET", "POST"})
*/
public function edit(Request $request, Order $order, OrderRepository $orderRepository, OptionService $optionService, SluggerInterface $slugger): Response
{
$user = $order->getUser();
$shop = $user->getShop();
$form = $this->createForm(OrderType::class, $order, array('shop'=>$shop, 'user'=>$user));
$form->handleRequest($request);
$invoiceDirectory=$this->getParameter('kernel.project_dir').'/private/users/'.$order->getUser()->getId().'/invoices/'.$order->getShop()->getId()."/".$order->getDate()->format('Ymd');
//$invoiceDirectory=$this->getParameter('kernel.project_dir').'/private/users/'.$order->getUser()->getId().'/invoices/'.$order->getShop()->getId()."/".$order->getDate()->format('Ymd')."/".$filename;
if ($form->isSubmitted() && $form->isValid()) {
$invoiceFile = $form->get('invoice')->getData();
if($invoiceFile) {
$originalFilename = pathinfo($invoiceFile->getClientOriginalName(), PATHINFO_FILENAME);
// this is needed to safely include the file name as part of the URL
$safeFilename = $slugger->slug($originalFilename);
$newFilename = $safeFilename.'-'.uniqid().'.'.$invoiceFile->guessExtension();
// Move the file to the directory where brochures are stored
try {
//$invoiceFile->move($invoiceDirectory."/".$shop->getId()."/".$order->getDate()->format('Ymd'), $newFilename);
$invoiceFile->move($invoiceDirectory, $newFilename);
} catch (FileException $e) {
// ... handle exception if something happens during file upload
}
// updates the 'brochureFilename' property to store the PDF file name
// instead of its contents
$order->setInvoiceFilename($newFilename);
}
$orderRepository->add($order);
return $this->redirectToRoute('app_order_edit', ['id'=>$order->getId()], Response::HTTP_SEE_OTHER);
}
return $this->renderForm('order/edit.html.twig', [
'order' => $order,
'form' => $form,
'shop'=>$shop,
'user'=>$user,
'cartOptions'=>$optionService->getCartOptions($order)
]);
}
/**
* @Route("/{id}/summary", name="app_order_summary", methods={"GET","POST"})
*/
public function summary(Request $request, Order $order, OrderRepository $orderRepository, OptionService $optionService): Response
{
$shop=$order->getShop();
$user=$order->getUser();
if(!$order->getDeliveryAddress() || !$order->getInvoiceAddress()) {
$this->addFlash('error', 'Missing address');
return $this->redirectToRoute('app_order_delivery', ['id'=>$order->getId()], Response::HTTP_SEE_OTHER);
}
$form = $this->createForm(OrderSummaryType::class, $order, array('shop'=>$shop, 'user'=>$user));
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$orderRepository->add($order);
return $this->redirectToRoute('app_order_confirm', ['id'=>$order->getId()], Response::HTTP_SEE_OTHER);
}
return $this->renderForm('order/summary.html.twig', [
'order' => $order,
'form' => $form,
'shop'=>$shop,
'user'=>$user,
'cartOptions'=>$optionService->getCartOptions($order)
]);
/*
if ($order->getUser() == $this->getUser() || $this->isGranted('ROLE_ADMIN')) {
$shop=$order->getShop();
if($order->getCoupon()) {
$couponName = trim(strtoupper(preg_replace('/\s+/', '', $order->getCoupon())));
if($coupon=$couponRepository->findOneByName($couponName, $order->getShop())) {
$order->setDiscount($coupon);
//echo $order->getDiscount();
}
}
return $this->render('order/summary.html.twig', [
'order' => $order,
'shop'=>$shop
]);
}
return $this->redirectToRoute('app_order_index', [], Response::HTTP_SEE_OTHER);
*/
}
/**
* @Route("/{id}/comments", name="app_order_comments", methods={"GET", "POST"})
*/
public function comments(Request $request, Order $order, OrderRepository $orderRepository): Response
{
$user=$this->getUser();
$shop = $order->getShop();
$form = $this->createForm(OrderCommentType::class, $order,['shop'=>$order->getShop()]);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$orderRepository->add($order);
return $this->redirectToRoute('app_order_delivery', ['id'=>$order->getId()], Response::HTTP_SEE_OTHER);
}
return $this->renderForm('order/comments.html.twig', [
'order'=>$order,
'form'=>$form
]);
}
/**
* @Route("/{id}/delivery", name="app_order_delivery", methods={"GET", "POST"})
*/
public function delivery(Request $request, Order $order, OrderRepository $orderRepository, UserRepository $userRepository, ShopService $shopService): Response
{
$user=$this->getUser();
$shop = $order->getShop();
if($user->getCompany()) {
if($companyAddress=$user->getCompany()->getAddress()) {
$user->addAddress($companyAddress);
$userRepository->add($user);
}
if($childrenCompanies = $user->getCompany()->getChildrenCompanies()) {
foreach($childrenCompanies as $co) {
if($co->getAddress()) {
$user->addAddress($co->getAddress());
}
}
$userRepository->add($user);
}
}
if($shopService->hasSetting($shop, 'invoice-parent')) {
if($parentCompany = $user->getCompany()->getParent()) {
$order->setInvoiceAddress($parentCompany->getAddress());
$orderRepository->add($order);
}
}
$form = $this->createForm(OrderDeliveryType::class, $order,['user'=>$user,'shop'=>$shop]);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$orderRepository->add($order);
return $this->redirectToRoute('app_order_delivery', ['id'=>$order->getId()], Response::HTTP_SEE_OTHER);
}
return $this->renderForm('order/delivery.html.twig', [
'order'=>$order,
'form'=>$form
]);
}
/**
* @Route("/{id}/checkout", name="app_order_checkout", methods={"GET", "POST"})
*/
public function checkout(Request $request, Order $order, OrderRepository $orderRepository, AddressRepository $addressRepository, DeliveryRepository $deliveryRepository, DeliveryService $deliveryService, ImeiRepository $imeiRepository, UserRepository $userRepository, CouponRepository $couponRepository, MessageBusInterface $bus): Response
{
$em = $this->getDoctrine()->getManager();
$user = $this->getUser();
$shop = $user->getShop();
$isPos = $shop->getSetting('is-point-of-sale');
if(count($order->getCarts())<=0) {
return $this->redirectToRoute('app_cart_index', [], Response::HTTP_SEE_OTHER);
}
$availableImeis=array();
$allImeis=$imeiRepository->findInStock($shop);
foreach($allImeis as $imei) {
$availableImeis[]=array(
'imei'=>$imei,
'model'=>$imei->getProduct()->getModel()->getId(),
'color'=>$imei->getProduct()->getColor()->getId(),
'grade'=>$imei->getProduct()->getGrade()->getId()
);
}
//$form = $this->createForm(OrderType::class, $order, array('IsPos'=>$isPos,'user'=>$user,'shop'=>$shop,'imeis'=>$availableImeis));
$form = $this->createForm(OrderDeliveryType::class, $order,['user'=>$user,'shop'=>$shop]);
$form->handleRequest($request);
if($isPos) {
$imeis=array();
$totalQty=0;
foreach($order->getCarts() as $cart) {
$totalQty+=$cart->getQty();
foreach($cart->getImei() as $imei) {
$imeis[]= $imei->getImei();
}
}
}
//$order->setDeliveryHt($this->getDeliveryPrice($order, $deliveryRepository));
$order->setDeliveryHt($deliveryService->getDeliveryPriceHT($order,$deliveryRepository));
if ($form->isSubmitted() && $form->isValid()) {
$order->setDeliveryHt(0);
if($order->getDeliveryAddress()) {
$country=$order->getDeliveryAddress()->getCountry();
if(in_array($country,array('Martinique','Guadeloupe','Guyane','Reunion'))) {
$order->setDeliveryHt(3000);
}
else {
if($deliveries=$deliveryRepository->findBy(array('shop'=>$order->getShop()->getId()))) {
$deliveryHt=$this->getDeliveryPrice($order, $deliveryRepository);
$order->setDeliveryHt($deliveryHt);
}
}
}
$em->persist($order);
if($isPos) {
if($newInvoiceAddress = $form->get('newInvoiceAddress')->getData()['__name__']) {
$invoiceAddress=$this->setAddress($newInvoiceAddress, $order->getInvoiceAddress());
$order->setInvoiceAddress($invoiceAddress);
$order->setDeliveryAddress($invoiceAddress);
}
/*
if($newDeliveryAddress = $form->get('newDeliveryAddress')->getData()['__name__']) {
$deliveryAddress=$this->setAddress($newDeliveryAddress, $order->getDeliveryAddress());
$order->setDeliveryAddress($deliveryAddress);
}
*/
}
if($order->getUser()->getShop()->getName()=='AFPA') {
if(!$existingUser=$userRepository->findOneByEmail($order->getInvoiceAddress()->getEmail())) {
//$order->setUser($existingUser);
$tmpUser=$order->getUser();
$tmpUser->setEmail($order->getInvoiceAddress()->getEmail());
$tmpUser->setFirstname($order->getInvoiceAddress()->getFirstname());
$tmpUser->setLastname($order->getInvoiceAddress()->getLastname());
$userRepository->add($tmpUser);
}
}
if($order->getCoupon()) {
$couponName = trim(strtoupper(preg_replace('/\s+/', '', $order->getCoupon())));
if($coupon=$couponRepository->findOneByName($couponName, $order->getShop())) {
$order->setDiscount($coupon);
//echo $order->getDiscount();
}
}
$order->setReference($order->generateReference());
$orderRepository->add($order);
//echo $order->getDeliveryHt();
if($isPos && (count($imeis)<$totalQty || count($imeis)>$totalQty)) {
$this->addFlash('error', 'Error in IMEIS selection');
return $this->redirectToRoute('app_order_checkout', ['id'=>$order->getId()], Response::HTTP_SEE_OTHER);
}
if(!$order->getDeliveryAddress() || !$order->getInvoiceAddress()) {
return $this->redirectToRoute('app_order_delivery', ['id'=>$order->getId()], Response::HTTP_SEE_OTHER);
}
$totalQty=0;
$totalAmount=0;
foreach($order->getCarts() as $cart) {
$totalQty+=$cart->getQty();
$totalAmount+=$cart->getQty()*$cart->getPrice();
foreach($cart->getImei() as $imei) {
$imei->setCart($cart);
$imeiRepository->add($imei);
}
}
//$order->setAmountTotal($totalAmount);
$orderRepository->add($order);
return $this->redirectToRoute('app_order_summary', ['id'=>$order->getId()], Response::HTTP_SEE_OTHER);
}
else {
die('no');
}
if($order->getReference()=='') {
$order->setReference($order->generateReference());
$orderRepository->add($order);
}
return $this->renderForm('order/edit.html.twig', [
'order' => $order,
'form' => $form,
'user'=>$user,
'shop'=>$shop
]);
}
/**
* @Route("/addoption", name="app_order_add_option", methods={"POST","GET"})
*/
public function addoption(Request $request, OptionRepository $optionRepository, PriceService $priceService): Response {
$em = $this->getDoctrine()->getManager();
$optionId=$request->request->get('option');
$user = $this->getUser();
if($order=$em->getRepository(Order::class)->findOneBy(array('user'=>$user,'status'=>10))) {
$carts=$order->getCarts();
$totalAmount=0;
foreach($carts as $cart) {
$totalAmount+=$cart->getPrice()*$cart->getQty();
foreach($cart->getOptions() as $o) {
$totalAmount+=$cart->getQty()*$o->getPrice();
}
}
if($option = $optionRepository->find($optionId)) {
foreach($order->getOptions() as $o) {
$order->removeOption($o);
}
$order->addOption($option);
$em->persist($order);
$em->flush();
$priceService->getPrices($order, true);
return new JsonResponse(array(
'reload'=>true
));
}
else {
if($optionId==0) {
foreach($order->getOptions() as $o) {
$order->removeOption($o);
}
//$order->setOptionPrice(0);
$em->persist($order);
$em->flush();
$priceService->getPrices($order, true);
return new JsonResponse(array(
'reload'=>true
));
}
}
}
$priceService->getPrices($order, true);
return new JsonResponse(array(
'result'=>'no'
));
}
/**
* @Route("/{id}/resend", name="app_order_resend_email", methods={"GET"})
*/
public function resendEmail(Order $order, OptionService $optionService, MailerInterface $mailer, ParameterBagInterface $params): Response
{
$this->sendConfirmationEmail($order, $mailer, $params);
return $this->render('order/show.html.twig', [
'order' => $order,
'cartOptions'=>$optionService->getCartOptions($order)
]);
return $this->redirectToRoute('app_order_show', ['id' => $order->getId()], Response::HTTP_SEE_OTHER);
}
/**
* @Route("/{id}/confirm", name="app_order_confirm", methods={"GET","POST"})
*/
public function confirm(Request $request, Order $order, OrderRepository $orderRepository, ProductRepository $productRepository, GradeRepository $gradeRepository, CartRepository $cartRepository, ImeiRepository $imeiRepository, StatusRepository $statusRepository, ManagerRegistry $doctrine, HttpClientInterface $client, MailerInterface $mailer, LoggerInterface $logger, ShopService $shopService, PriceService $priceService, ParameterBagInterface $params): Response
{
if($order->getUser()!=$this->getUser() || $order->getStatus()->getId()!=10 || $order->getConfirm()) {
return $this->redirectToRoute('app_order_index', [], Response::HTTP_SEE_OTHER);
}
if ($pendingOrder = $orderRepository->findOneBy(array('user' => $this->getUser(), 'status' => 10, 'confirm' => 0, 'id' => $order->getId()))) {
$shop=$order->getShop();
$vat = $shopService->getSetting($shop, 'vat');
//$vat = 20;
/*
if($shop->getCountry()=='es') {
$vat=21;
}*/
$carts = $order->getCarts();
$totalProduct = 0;
$amountHt = 0;
$totalDeliveryHt = 0;
$amountTotal = 0;
$totalDelivery = 0;
$discount=0;
foreach ($carts as $cart) {
$stock = $cart->getStock();
$sourceGrades = $stock->getSourceGrade();
foreach (explode(',', $sourceGrades) as $sourceGrade) {
if ($grade = $gradeRepository->findOneByName($sourceGrade)) {
if ($product = $productRepository->findOneBy(array('channel'=>$this->getUser()->getShop()->getChannel(),'grade' => $grade, 'model' => $stock->getModel(), 'color' => $stock->getColor()))) {
$cart->setSku($product->getSku());
$cartRepository->add($cart);
break;
}
}
}
$amountHt += (int)$cart->getQty() * $cart->getPrice();
//echo $amountHt."<br/>";
$totalProduct += (int)$cart->getQty();
}
if($order->getOptions()) {
foreach($order->getOptions() as $option) {
$amountHt+=($amountHt*((int)$option->getPrice())/100);
//echo $amountHt."<br/>";
}
}
if($order->getDiscount()) {
$amountHt=$amountHt-$order->getDiscount();
}
$tAmountTotal = $amountHt ;
if($order->getDeliveryHt()) {
$tAmountTotal=$amountHt+ $order->getDeliveryHt();
}
$amountTotal = ($vat * $tAmountTotal) / 100 + $tAmountTotal ;
//$amountTotal = ($vat * $amountHt) / 100 + $amountHt ;
$priceService->getPrices($order, true);
/*
$order->setTotalProduct($totalProduct);
$order->setAmountHt($amountHt);
$order->setAmountTotal($amountTotal);
*/
$order->setReference($order->generateReference());
$orderRepository->add($order);
$hasError = true;
$response = null;
$message = "";
$datas = $this->getPostOrderData($order, $imeiRepository);
$logger->info(json_encode($datas));
if($shop->getSetting('stripe')) {
//die('stripe');
return $this->renderForm('checkout/stripe.html.twig', [
'order' => $order,
'shop'=>$shop
]);
}
else if(!$order->getShop()->getSetting('post-to-b2l')) {
$status = $statusRepository->find(11); //posted
$hasError = false;
$order->setStatus($status);
$orderRepository->add($order);
$this->sendConfirmationEmail($order, $mailer, $params);
}
else {
if ($response = $this->postOrder($datas)) {
if (isset($response->orderId)) {
$status = $statusRepository->find(11);//posted
$hasError = false;
$order->setB2lId($response->orderId);
$order->setStatus($status);
$orderRepository->add($order);
$this->sendConfirmationEmail($order, $mailer, $params);
//$this->moveColis($order);
} else {
//echo "eee";
//var_dump($response);
$logger->info($response);
if (is_string($response)) {
//var_dump($response);
$message = $response;
}
}
} else {
$hasError = true;
echo json_encode($datas);
$message = "no curl response";
}
}
} else {
$hasError = true;
$message = "already processed";
}
return $this->render('order/confirm.html.twig', [
'order' => $order,
'error' => $hasError,
'message' => $message
]);
}
/**
* @Route("/{id}/paid", name="app_order_paid", methods={"GET","POST"})
*/
public function paid(Request $request, Order $order, OrderRepository $orderRepository, StatusRepository $statusRepository, MailerInterface $mailer, ParameterBagInterface $params ): Response
{
$user = $this->getUser();
if($order = $orderRepository->findOneBy(array('user' => $user, 'status' => 10, 'confirm' => 0, 'id' => $order->getId()))) {
$shop = $order->getShop();
$status = $statusRepository->find(2); //Paiement accepté
$hasError = false;
$order->setStatus($status);
if($shop->getCountry()=='es') {
$stripeSecretKey = $params->get("app.stripe_secret_key_es");
}
else {
$stripeSecretKey = $params->get("app.stripe_secret_key");
}
$stripe = new \Stripe\StripeClient($stripeSecretKey);
if($stripe_session = $stripe->checkout->sessions->retrieve(
$request->get('session_id'),
[]
)) {
$order->setPayment("stripe");
$order->setPaymentReference($stripe_session->payment_intent);
}
$orderRepository->add($order);
$this->sendConfirmationEmail($order, $mailer, $params);
return $this->renderForm('order/paid.html.twig', [
'order' => $order,
'shop' => $shop
]);
}
else {
die('payment error');
}
}
/**
* @Route("/{id}", name="app_order_delete", methods={"POST"})
*/
public function delete(Request $request, Order $order, OrderRepository $orderRepository): Response
{
if ($this->isCsrfTokenValid('delete' . $order->getId(), $request->request->get('_token'))) {
$order->setActive(0);
$orderRepository->add($order);
//$orderRepository->remove($order);
}
return $this->redirectToRoute('app_order_index', [], Response::HTTP_SEE_OTHER);
}
private function getPostOrderData($order, $imeiRepository)
{
$isPos=$this->getUser()->getShop()->getSetting('is-point-of-sale');
$datetime = new \DateTime('now');
$date = $datetime->format('Y-m-d\TH:i:s');
$reference = $order->getReference();
$privateKey = "eee";
$carts = $order->getCarts();
$products = array();
foreach ($carts as $cart) {
$imeis=array();
$imeisCollection=$imeiRepository->findByCart($cart);
foreach($imeisCollection as $imei) {
$imeis[]=$imei->getImei();
}
$products[] = array(
'reference' => $cart->getSku(),
'main_ref' => $cart->getStock()->getModel()->getMainReference(),
"price" => $cart->getPrice() / 100 + ($cart->getPrice()*02) / 100,
'qty' => $cart->getQty(),
"imeis"=>implode(",",$imeis),
'availability' => $cart->getStock()->getQty(),
//'color'=>$cart->getStock()->getColor(),
'name' => $cart->getStock()->getModel()->getName(),
'manufacturer' => $cart->getStock()->getModel()->getManufacturer()->getName(),
'attributes' => array(
'color' => $cart->getStock()->getColor()->getName(),
)
);
/*
$products[] = array(
"reference" =>$cart->getSku(),
"name"=>$cart->getModel()->getName(),
"main_ref"=>$cart->getSku(),
"price" => $cart->getPrice(),
"qty" => $cart->getQty()
);
*/
}
$invoiceAddress = $order->getInvoiceAddress();
$deliveryAddress = $order->getDeliveryAddress();
$invoiceEmail = $deliveryAddress->getEmail();
$parentUser=null;
if(!$this->getUser()->getShop()->getSetting('is-point-of-sale')) {
if ($this->getUser()->getParent() && !$isPos) {
$parentUser = $this->getUser()->getParent();
$invoiceEmail = $parentUser->getEmail();
$company = $parentUser->getCompany();
$invoiceAddress = $parentUser->getCompany()->getAddress();
}
}
$privateKey = "2y10DBkKsebmrm6fh5uDHR7eQeJtHQitSUeSpLnQmkyXLyR3og4nSy";
$str = $privateKey . "+" . $reference . "+" . $date . "+" . $invoiceEmail;
foreach ($products as $product) {
$str .= "+" . $product['reference'] . "+" . $product['qty'];
}
$hash = md5($str);
$datas = [
"hash" => $hash,
"reference" => $reference,
"date" => $date,
"carrier" => "DHL".(!$this->getUser()->getShop()->getSetting('is-point-of-sale')?' B2B':' Gratuit'),
"id_shop" => $this->getUser()->getShop()->getSetting('is-point-of-sale')?1:2,
"payment_method"=>$order->getPayment(),
"billing_address" => [
//"alias"=>$parentUser->getCompany()->getName(),
"company" => $parentUser?$parentUser->getCompany()->getName():$invoiceAddress->getName(),
"firstname" => $parentUser?$parentUser->getFirstname():$invoiceAddress->getFirstname(),
"lastname" => $parentUser?$parentUser->getLastname():$invoiceAddress->getLastname(),
"email" => $invoiceEmail,
"address1" => $invoiceAddress->getAddress(),
"address2" => "",
"postcode" => $invoiceAddress->getZip(),
"city" => $invoiceAddress->getCity(),
"phone" => $invoiceAddress->getPhone(),
"country" => substr(strtoupper($deliveryAddress->getCountry()), 0, 2),
"vat_number" => $parentUser?$parentUser->getCompany()->getVat():''
],
"shipping_address" => [
"alias" => $deliveryAddress->getName(),
"company" => $deliveryAddress->getName(),
"firstname" => $isPos?$deliveryAddress->getFirstname():$order->getUser()->getFirstname(),
"lastname" => $isPos?$deliveryAddress->getLastname():$order->getUser()->getLastname(),
"address1" => $deliveryAddress->getAddress(),
"address2" => "",
"postcode" => $deliveryAddress->getZip(),
"city" => $deliveryAddress->getCity(),
"phone" => $deliveryAddress->getPhone(),
"country" => substr(strtoupper($deliveryAddress->getCountry()), 0, 2)
],
"cart" => [
"products" => $products
]
];
return $datas;
}
private function postOrder($datas)
{
$this->bak2life_api_key = $this->getUser()->getShop()->getApikey();
$url = $this->bak2life_api_url . "?order=1";
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_USERPWD => $this->bak2life_api_key . ":",
CURLOPT_HTTPHEADER => array(
"cache-control: no-cache",
'Content-Type:application/json'
),
CURLOPT_POSTFIELDS => json_encode($datas),
));
//$mailMessage['response']=$response;
$err = curl_error($curl);
if ($err) {
return array('error' => $err);
// mail($dest,'sync order kustee curcl error', json_encode($mailMessage));
} else {
$response = curl_exec($curl);
curl_close($curl);
$return = json_decode($response);
if (isset($return->success)) {
$responseArray = json_decode($return->success);
return $responseArray;
}
mail($this->mailer_sender, 'error', json_encode($datas));
return $return;
}
}
/**
* @Route("/{id}/invoice", name="app_order_download_invoice", methods={"GET"})
*/
public function downloadInvoice(Order $order): Response {
$this->bak2life_api_key = $this->getUser()->getShop()->getApikey();
$url = $this->bak2life_api_url . "?invoice=1&reference=".$order->getBak2Reference();
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_USERPWD => $this->bak2life_api_key . ":",
CURLOPT_HTTPHEADER => array(
"cache-control: no-cache",
'Content-Type:application/json'
)
));
$err = curl_error($curl);
if ($err) {
return array('error' => $err);
// mail($dest,'sync order kustee curcl error', json_encode($mailMessage));
} else {
$response = curl_exec($curl);
curl_close($curl);
header('Content-type: application/pdf');
echo $response;
die();
}
return $this->redirectToRoute('app_order_index', [], Response::HTTP_SEE_OTHER);
}
public function syncOrders($em)
{
$shops = $em->getRepository(Shop::class)->findAll();
foreach($shops as $shop) {
if($this->bak2life_api_key=$shop->getApiKey()) {
echo $shop->getName()."\n";
$orders = $em->getRepository(Order::class)->findAllNotIn('status', array(5, 6, 7, 8, 10), null);
foreach ($orders as $order) {
$url = $this->bak2life_api_url . "?sync=1&reference=" . $order->getReference();
//echo $url;
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "GET",
CURLOPT_USERPWD => $this->bak2life_api_key . ":",
CURLOPT_HTTPHEADER => array(
"cache-control: no-cache",
'Content-Type:application/json'
),
//CURLOPT_POSTFIELDS => json_encode($orderToPost),
));
$response = curl_exec($curl);
//var_dump($response);
$mailMessage['response'] = $response;
$err = curl_error($curl);
if ($err) {
//echo $response;
echo "cURL Error---- #:" . $err;
mail($this->dest, 'sync order kustee curcl error', json_encode($mailMessage));
} else {
$b2lOrder = json_decode($response);
if (isset($b2lOrder->reference)) {
$order->setBak2Reference($b2lOrder->reference);
$order->setShippingNumber($b2lOrder->shipping_number);
if ($status = $em->getRepository(Status::class)->findOneByB2lId($b2lOrder->current_state)) {
$order->setStatus($status);
}
$em->persist($order);
}
}
$this->moveColis($order, $em);
}
$em->flush();
}
}
//$this->bak2life_api_key = $this->getUser()->getShop()->getApikey();
return 'ok';
}
private function sendConfirmationEmail(Order $order, MailerInterface $mailer, ParameterBagInterface $params)
{
$isPos=$this->getUser()->getShop()->getSetting('is-point-of-sale');
$b2Order=$this->getUser()->getShop()->getSetting('post-to-b2l');
$bcc = array($this->mailer_sender);
//$subject = '[' . $order->getUser()->getCompany() . '] '.$b2Order==1?"Confirmation de commande":"Demande d'offre";
$subject = '[' . $order->getUser()->getCompany() . '] Confirmation de commande';
if($order->getStatus()->getId()==2) {
$subject = '[' . $order->getUser()->getCompany() . '] Confirmation de commande';
}
if ($parentUser = $order->getUser()->getParent()) {
$subject = '[' . $order->getUser()->getParent()->getCompany() . '][' . $order->getUser()->getCompany() . '] Confirmation de commande';
}
$destinationEmail=$order->getUser()->getEmail();
if($order->getInvoiceAddress()->getEmail()!='') {
$destinationEmail=$order->getInvoiceAddress()->getEmail();
}
if($mailCopy=$this->getUser()->getShop()->getMailCopy()) {
$bcc=array_merge($bcc,explode(',',$mailCopy));
}
if($isPos) {
$destinationEmail=$this->getUser()->getEmail();//$order->getInvoiceAddress()->getEmail();
$subject = '[' . $order->getUser()->getCompany() . '] Confirmation de commande';
}
//attachment
$filename=$order->getReference().".pdf";
$filePath=$params->get('kernel.project_dir').'/private/users/'.$order->getUser()->getId().'/orders/'.$order->getShop()->getId()."/".$order->getDate()->format('Ymd')."/".$filename;
if(!file_exists($filePath)) {
$this->createPdf($order, $filePath, $params);
}
$email = (new TemplatedEmail())
->from($this->mailer_sender)
->to($destinationEmail)
->bcc(...$bcc)
->subject($subject)
// path of the Twig template to render
->htmlTemplate('emails/order/confirm.html.twig')
->attachFromPath($filePath)
// pass variables (name => value) to the template
->context([
'order' => $order,
'shop'=>$order->getShop()
]);
if ($parentUser = $order->getUser()->getParent()) {
$email->addBcc($parentUser->getEmail());
}
try {
$mailer->send($email);
} catch (TransportExceptionInterface $e) {
// some error prevented the email sending; display an
// error message or try to resend the message
echo "<pre>";
var_dump($e);
echo "</pre>";
}
//$bcc = $this->mailer_sender;
$email = (new TemplatedEmail())
->from($this->mailer_sender)
->to($this->mailer_sender)
->bcc(...$bcc)
->subject($subject)
// path of the Twig template to render
->htmlTemplate('emails/order/inform.html.twig')
->attachFromPath($filePath)
// pass variables (name => value) to the template
->context([
'order' => $order,
//'cartOptions'=>$optionService->getCartOptions($order),
'shop'=>$order->getShop()
]);
if ($parentUser = $order->getUser()->getParent()) {
$email->addCc($parentUser->getEmail());
}
if($order->getUser()->getCompany()) {
if ($parentCompany = $order->getUser()->getCompany()->getParent()) {
foreach($parentCompany->getUsers() as $parentUser) {
$email->addCc($parentUser->getEmail());
}
}
}
try {
$mailer->send($email);
} catch (TransportExceptionInterface $e) {
// some error prevented the email sending; display an
// error message or try to resend the message
echo "<pre>cc-";
var_dump($e);
echo "</pre>";
}
}
private function setAddress($newAddress, $address = null) {
if(!$address) {
$address = new \App\Entity\Address();
}
if(!$name=$newAddress->getName()) {
$name=$newAddress->getFirstname()." ".$newAddress->getLastname();
}
$address->setName($name);
$address->setFirstname($newAddress->getFirstname());
$address->setLastname($newAddress->getLastname());
$address->setAddress($newAddress->getAddress());
$address->setZip($newAddress->getZip());
$address->setCity($newAddress->getCity());
$address->setCountry($newAddress->getCountry());
$address->setPhone($newAddress->getPhone());
$address->setEmail($newAddress->getEmail());
return $address;
}
private function moveColis($order,$em) {
$imeiRepository = $em->getRepository(Imei::class);
$buyerId=$this->bak2_mp_buyer_id;
$currentColis=array();
// echo $this->bak2_api_url . "/tempStock.php?action=getColisByBuyerId&buyerId=" . $buyerId;
if($allColis=file_get_contents($this->bak2_api_url . "/tempStock.php?action=getColisByBuyerId&buyerId=" . $buyerId)) {
//echo $this->bak2_api_url . "/tempStock.php?action=getColisByBuyerId&buyerId=" . $buyerId;
$allColis=json_decode($allColis);
foreach($allColis as $colis) {
if(!isset($currentColis[$colis->outGrade])) {
$currentColis[$colis->outGrade]=$colis->colisId;
}
}
}
foreach($order->getCarts() as $cart) {
if($imeis=$cart->getImei()) {
foreach($imeis as $imei) {
if(!$imei->getSync()) {
$outGrade = $cart->getStock()->getSourceGrade();
//echo $outGrade;
if($imeiMoved=file_get_contents($this->bak2_api_url . "/tempStock.php?action=moveImeiToColis&imei=" . $imei->getImei()."&colisId=".$currentColis[$outGrade])) {
$imeiMoved=json_decode($imeiMoved);
//echo intval((string)$imeiMoved->colisId);
if($currentColis[$outGrade]==$imeiMoved->colisId) {
$imei->setSync(true);
$imeiRepository->add($imei);
}
}
}
}
}
}
$em->flush();
//$productContent = file_get_contents($this->bak2_api_url . "/tempStock.php?action=getProductByColis&imei=" . $imei);
}
private function getDeliveryPrice($order,DeliveryRepository $deliveryRepository) {
$cats=array();
$deliveryHt=0;
foreach($order->getCarts() as $cart) {
$categoryId=$cart->getStock()->getModel()->getCategory()->getId();
if(!isset($cats[$categoryId])) {
$cats[$categoryId]=0;
}
$cats[$categoryId]+=(int)$cart->getQty();
//echo $cart->getStock()->getModel()->getCategory();
}
foreach($cats as $cat=>$qty) {
if($deliveries=$deliveryRepository->findBy(array('category'=>$cat,'fromUnit'=>$qty,'shop'=>$order->getShop()->getId()))) {
$deliveryHt+=(int)$deliveries[0]->getPrice()*$qty;
}
}
return $deliveryHt;
}
public function priceSummary(Request $request, Order $order, string $nextStep, bool $coupon, PriceService $priceService, OrderRepository $orderRepository, CouponRepository $couponRepository) {
$prices=$priceService->getPrices($order);
if(!$couponRepository->findBy(['shop'=>$order->getShop()])) {
$coupon=false;
}
$couponForm = $this->createForm(OrderCouponType::class, $order,[
'action'=>$this->generateUrl('app_order_coupon',['id'=>$order->getId()])
]);
return $this->renderForm('order/price.html.twig', [
'order'=>$order,
'prices'=>$prices,
'nextStep'=>$nextStep,
'coupon'=>$coupon,
'couponForm'=>$couponForm
]);
}
/**
* @Route("/{id}/pdf/invoice", name="app_order_pdf_invoice", methods={"GET"})
*/
public function pdfInvoice(Order $order, ParameterBagInterface $parameterBag) {
$user=$this->getUser();
if($order->getUser()->getId()!=$user->getId() || !$this->isGranted('ROLE_ADMIN')) {
if($order->getInvoiceFilename()!='') {
$filename=$order->getInvoiceFilename();
$filePath=$parameterBag->get('kernel.project_dir').'/private/users/'.$order->getUser()->getId().'/invoices/'.$order->getShop()->getId()."/".$order->getDate()->format('Ymd')."/".$filename;
$headers = array('Content-Type' => 'application/pdf',
'Content-Disposition' => 'inline; filename="file1.pdf"');
return new Response(file_get_contents($filePath), 200, $headers);
//return $this->redirect('/uploads/invoices/'.$order->getShop()->getId()."/".$order->getDate()->format('Ymd')."/".$order->getInvoiceFilename());
}
return $this->redirectToRoute('app_order_edit',['id'=>$order->getId()]);
}
return $this->redirectToRoute('app_order_show',['id'=>$order->getId()]);
}
/**
* @Route("/{id}/pdf/order", name="app_order_pdf_order", methods={"GET"})
*/
public function pdfOrder(Order $order, ParameterBagInterface $parameterBag) {
$user=$this->getUser();
if($order->getUser()->getId()!=$user->getId() || !$this->isGranted('ROLE_ADMIN')) {
$filename=$order->getReference().".pdf";
//$filePath=$parameterBag->get('kernel.project_dir').'/public/uploads/orders/'.$order->getShop()->getId()."/".$order->getDate()->format('Ymd')."/".$filename;
$filePath=$parameterBag->get('kernel.project_dir').'/private/users/'.$order->getUser()->getId().'/orders/'.$order->getShop()->getId()."/".$order->getDate()->format('Ymd')."/".$filename;
if(!file_exists($filePath)) {
$this->createPdf($order, $filePath, $parameterBag);
}
$headers = array('Content-Type' => 'application/pdf',
'Content-Disposition' => 'inline; filename="file1.pdf"');
return new Response(file_get_contents($filePath), 200, $headers);
}
return $this->redirectToRoute('app_order_show',['id'=>$order->getId()]);
// return $this->redirect('/uploads/orders/'.$order->getShop()->getId()."/".$order->getDate()->format('Ymd')."/".$filename);
}
/**
* @Route("/{id}/coupon", name="app_order_coupon", methods={"GET", "POST"})
*/
public function coupon(Request $request, Order $order, OrderRepository $orderRepository) {
$couponForm = $this->createForm(OrderCouponType::class, $order,[
'action'=>$this->generateUrl('app_order_coupon',['id'=>$order->getId()])
]);
$couponForm->handleRequest($request);
if($couponForm->isSubmitted() && $couponForm->isValid()) {
$orderRepository->add($order);
}
return $this->redirectToRoute('app_cart_index', [], Response::HTTP_SEE_OTHER);
}
private function createPdf($order, $filepath, $parameterBag) {
$company=null;
$parentCompany=null;
if($order->getUser()->getCompany()) {
if($company=$order->getUser()->getCompany()) {
if($company->getParent()) {
$parentCompany=$company->getParent();
}
}
}
$template='order/pdf.html.twig';
if(file_exists($parameterBag->get('kernel.project_dir')."/private/shops/".$order->getShop()->getId()."/templates/order.html.twig")) {
$template="shops/".$order->getShop()->getId()."/templates/order.html.twig";
}
$knpSnappyPdf=new Pdf($parameterBag->get('app.wkhtmltopdf'));
$knpSnappyPdf->setTemporaryFolder($parameterBag->get('kernel.project_dir')."/tmp");
$knpSnappyPdf->setOptions([
'enable-local-file-access' => true,
'keep-relative-links' => true,
'disable-smart-shrinking' => true,
'margin-top'=>"20mm",
'margin-right'=>"20mm",
'margin-bottom'=>"20mm",
'margin-left'=>"20mm",
]);
$html=$this->renderView(
$template,
array(
'order' => $order,
'company'=>$company,
'parentCompany'=>$parentCompany
)
);
$knpSnappyPdf->generateFromHtml(
$html,
$filepath
);
}
}