<?php
namespace App\Controller\Frontend;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\JsonResponse;
use App\Entity\Orders;
use App\Entity\OrderDetail;
use App\Entity\OrderField;
use App\Entity\ProductInventoryLog;
use App\Entity\AlertPurchase;
use App\Entity\Setting;
use App\Entity\WebSlide;
use App\Entity\WebSetting;
use App\Entity\Brand;
use App\Entity\Payment;
use App\Entity\Category;
use App\Entity\Subcategory;
use App\Entity\Blog;
use App\Entity\Customer;
use App\Entity\Client;
use App\Entity\CustomerLocation;
use App\Service\PaymentQPayProHelper;
//use AppBundle\Helper\MailHelper;
use App\Service\DistanceHelper;
//use App\Helper\PaymentQPayProHelper;
use Nzo\UrlEncryptorBundle\Annotations\ParamDecryptor;
use Nzo\UrlEncryptorBundle\Annotations\ParamEncryptor;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Security\Core\Security;
use App\Service\HelperService;
use App\Service\MailHelper;
use Symfony\Component\String\Slugger\SluggerInterface;
use Nzo\UrlEncryptorBundle\Encryptor\Encryptor;
class WebsiteController extends AbstractController {
private $encryptor;
public function __construct( Encryptor $encryptor)
{
$this->encryptor = $encryptor;
}
/**
*
* @Route("{slug}/store-product", name="frontend_store_product")
*/
public function storeAction(Request $request, $slug)
{
$em = $this->getDoctrine()->getManager();
$userData = $this->get("session")->get("userData");
$currentCart = json_decode($this->get("session")->get("cart"));
/*
$newCart = array();
$this->get("session")->set("cart", json_encode($newCart));
$currentCart = json_decode($this->get("session")->get("cart"));
exit;
*/
if($currentCart)
{
if(count($currentCart) == 0)
{
$currentCart = array();
}
} else {
$currentCart = array();
}
//print_r($currentCart);exit;
if($request->get('remove'))
{
$key = $request->get('key');
$newCart = array();
foreach($currentCart as $thisKey => $cart)
{
if($thisKey == $key)
{
} else {
$newCart[] = $cart;
}
}
$this->get("session")->set("cart", json_encode($newCart));
$currentCart = json_decode($this->get("session")->get("cart"));
}
if($request->get('clean'))
{
$newCart = array();
$this->get("session")->set("cart", json_encode($newCart));
$currentCart = json_decode($this->get("session")->get("cart"));
}
if($request->get('cart'))
{
$pid = $request->get('pid');
$quantity = $request->get('quantity');
$clientId = 1;
$offerId = $request->get('oid','n');
$checkOffer = $em->getRepository(\App\Entity\Product::class)->findOffer($offerId);
$product = $em->getRepository(\App\Entity\Product::class)->findOneBy(array(
'productId' => $pid
));
$newCart = array();
$currentCart = json_decode($this->get("session")->get("cart"));
//print_r($currentCart);exit;
if (!$this->get("session")->get("cart") || $this->get("session")->get("cart") == "[]")
{
//print_r($currentCart);exit;
$price = $product->getMainPrice();
$o_name = "";
if($offerId)
{
if($checkOffer)
{
if($checkOffer['product_id'] != "" )
{
$o_name = $checkOffer['offer_name'];
$price = $checkOffer['new_price'];
} else {
$discount = ($checkOffer['percent_discount']/100);
$pricePercentage = $product->getMainPrice()*$discount;
$o_name = $checkOffer['offer_name'];
$price = number_format($product->getMainPrice()-$pricePercentage, 2, '.', '');
}
}
}
$newItem = array(
'name' => $product->getName(),
'quantity' => $quantity,
'price' => $price,
'pid' => $pid,
'oid' => $offerId,
'o_name'=> $o_name,
'img' => $product->getMainPicture()
);
array_push($newCart, $newItem);
} else {
$foundPid = -1;
foreach ($currentCart as $key => $cart)
{
if ($cart->pid == $pid) {
//En que KEY esta el PID en cuestion?
$foundPid = $key;
}
$productObj = $em->getRepository(\App\Entity\Product::class)->findOneBy(array(
'productId' => $cart->pid
));
$price = $cart->price;
$o_name = $cart->o_name;
if($cart->oid)
{
$checkOffer = $em->getRepository(\App\Entity\Product::class)->findOffer($cart->oid);
if($checkOffer)
{
if($checkOffer['brand_id'] != "" || $checkOffer['category_id'] != "" || $checkOffer['subcategory_id'] != "" )
{
$discount = ($checkOffer['percent_discount']/100);
$pricePercentage = $productObj->getMainPrice()*$discount;
$o_name = $checkOffer['offer_name'];
$price = number_format($productObj->getMainPrice()-$pricePercentage, 2, '.', '');
} else {
$o_name = $checkOffer['offer_name'];
$price = $checkOffer['new_price'];
}
}
}
$newItem = array(
'name' => $cart->name,
'quantity' => $cart->quantity,
'price' => $price,
'pid' => $cart->pid,
'oid' => $cart->oid,
'o_name'=> $o_name,
'img' => $cart->img
);
array_push($newCart, $newItem);
}
if ($foundPid == -1)
{
$price = $product->getMainPrice();
$o_name = "";
$checkOffer = $em->getRepository(\App\Entity\Product::class)->findOffer($offerId);
if($checkOffer)
{
if($checkOffer['product_id'] != "")
{
$o_name = $checkOffer['offer_name'];
$price = $checkOffer['new_price'];
} else {
$discount = ($checkOffer['percent_discount']/100);
$pricePercentage = $product->getMainPrice()*$discount;
$o_name = $checkOffer['offer_name'];
$price = number_format($product->getMainPrice()-$pricePercentage, 2, '.', '');
}
}
$newItem = array(
'name' => $product->getName(),
'quantity' => $quantity,
'price' => $price,
'pid' => $pid,
'oid' => $offerId,
'o_name'=> $o_name,
'img' => $product->getMainPicture()
);
array_push($newCart, $newItem);
} else {
if ($quantity > 0)
{
$newCart[$foundPid]['quantity'] = $quantity;
} else {
unset($newCart[$foundPid]);
}
}
}
$this->get("session")->set("cart", json_encode($newCart));
$currentCart = $this->get("session")->get("cart");
}
$val = 0;
$priceVal = 0;
if (is_array($currentCart)) {
$currentCarts = $currentCart;
} else {
$currentCarts = json_decode($currentCart);
}
/*echo "<pre>";
print_r($currentCarts);
echo "</pre>";*/
$quitCoupon =false;
foreach ($currentCarts as $cartTemp)
{
$val += $cartTemp->quantity;
$priceVal += $cartTemp->price * $cartTemp->quantity;
//$val++;
if($cartTemp->oid != ''){
$quitCoupon = true;
}
}
//Verificamos configuración de cupones si hay productos con ofertas
/*$client_id = $this->getParameter('client_id');
$client = $this->getDoctrine()->getRepository(\App\Entity\Client::class)->findOneBy(array(
"clientId" => $client_id
));*/
$client = $this->getDoctrine()->getRepository(\App\Entity\Client::class)->findOneBy(array(
"slug" => $slug
));
$client_id = $client->getClientId();
$setting = $this->getDoctrine()->getRepository(\App\Entity\Setting::class)->findOneBy(array(
"Client" => $client
));
if($quitCoupon && $setting->getCartAllowCouponWhithOffers() == '0'){
$this->get("session")->set("coupon",'');
}
$html = "";
if (is_array($currentCart)) {
$checkCart = $currentCart;
} else {
$checkCart = json_decode($currentCart);
}
if(count($checkCart) > 0)
{
if ($priceVal > 0) {
$total = 0;
$grandTotal = $priceVal;
if($this->get("session")->get("coupon") && $this->get("session")->get("coupon") != ''){
$coupon_id = $this->get("session")->get("coupon");
$couponObj = $this->getDoctrine()->getRepository('AppBundle:Coupon')->findOneBy(array(
"couponId" => $coupon_id
));
$discount = ($priceVal * $couponObj->getDiscountPercent())/100;
$total = $priceVal - $discount;
$grandTotal = $total;
}
$finalPrice = number_format($grandTotal, 2, '.', ',');
} else {
$finalPrice = '';
}
//Aplicamos cupón
//$client_id = $this->getParameter('client_id');
$url = $this->generateUrl('frontend_checkout', ['slug' => $slug]);
$information = $client;
//Obtenemos simbolo de moneda a utilizar
$symbol = $information->getCurrency()->getCurrencySymbol();
$html = "<div id='cart_main' rel='popover' class='icon-header-item cl2 hov-cl1 trans-04 p-l-22 p-r-11 icon-header-noti js-show-cart' onclick='window.location.href=\"$url\"' data-notify='$val'>
<i class='zmdi zmdi-shopping-cart'></i> $symbol$finalPrice
<small class='cart_bottom_legend'>Clic aquí para terminar</small>
</div>";
};
return new JsonResponse(array(
'slug' => $slug,
'quantity' => $val,
'price' => $priceVal,
'cart' => $currentCarts,
'html' => $html
));
}
/**
* @Route("{slug}/products", name="frontend_product")
*/
public function productAction(Request $request, $slug)
{
$em = $this->getDoctrine()->getManager();
$client = $this->getDoctrine()->getRepository(\App\Entity\Client::class)->findOneBy(array(
"slug" => $slug
));
$client_id = $client->getClientId();
$productCategory = "";
$pager_limit = 12;
$globalSearch = "";
$token = '';
$token2 = '';
$brand = '';
$category = '';
$type = $request->get('type');
if($request->get("token"))
{
$token = $request->get('token');
}
if($request->get("token2"))
{
$token2 = $request->get('token2');
}
if($request->get('search'))
{
$globalSearch = $request->get('search');
}
if ($request->get('brand'))
{
$brand = $request->get('brand');
$type = 3;
}
if($request->get('category'))
{
$category = $request->get('category');
$type = 3;
}
$filters = [
'token' => $token,
'token2' => $token2,
'type' => $type,
'search' => $globalSearch,
'brand' => $brand,
'category' => $category
];
//Obtenemos configuraciones para mostrar o ocultar productos sin stock
$client = $this->getDoctrine()->getRepository(\App\Entity\Client::class)->findOneBy(array(
"clientId" => $client_id
));
$settings = $this->getDoctrine()->getRepository(\App\Entity\Setting::class)->findOneBy(array(
"Client" => $client
));
$query = $em->getRepository(\App\Entity\Product::class)->getProducts($filters, $client_id, $settings->getCartHideEmptyStock());
$subcategories = $em->getRepository(\App\Entity\Subcategory::class)->findBy(array('is_active' => 1));
$categories = $em->getRepository(\App\Entity\Category::class)->getCategories($client_id);
$total = $em->getRepository(\App\Entity\Product::class)->getTotalCount();
$webSetting = $this->getDoctrine()->getRepository(\App\Entity\WebSetting::class)->findOneBy(array("Client" => $client_id));
// replace this example code with whatever you need
return $this->render('Frontend/Product/index.html.twig', array(
'list' => $query,
'pager_limit' => $pager_limit,
'subcategories' => $subcategories,
'categories' => $categories,
'productCategory' => $productCategory,
'globalSearch' => $globalSearch,
'webSetting' => $webSetting,
'brand' => $brand,
'category' => $category,
'slug' => $slug
));
}
/* @Route("/product/direct/{id}", name="frontend_product_direct")*/
/**
* @Route("{slug}/product/direct/{productId}", name="frontend_product_index")
* @ParamDecryptor({"productId"})
*/
public function productDirectAction(Request $request, Product $product) {
$em = $this->getDoctrine()->getManager();
$client_id = $this->getParameter('client_id');
//$productObj = $em->getRepository(Product)->findProductByMd5Id($id);
//if($productObj)
//{
//$product = $em->getRepository('AppBundle:Product')->findOneBy(array('productId' => $productObj['product_id']));
$serverName = $_SERVER['SERVER_NAME'];
$product_id = $product->getProductId();
return $this->render('Frontend/Product/product_direct.html.twig', array(
'product_id' => $product_id,
'product' => $product,
'brand' => '',
'category' => '',
'productCategory' => '',
'pager_limit' => 12,
'globalSearch' => '',
'serverName' => $serverName
));
//} else {
//return $this->redirectToRoute("frontend_index");
//}
}
/**
*
* @Route("{slug}/product-modal-load", name="frontend_product_modal_load")
*/
public function productModalLoadAction(Request $request, $slug)
{
$em = $this->getDoctrine()->getManager();
$information = $this->getDoctrine()->getRepository(\App\Entity\Client::class)->findOneBy([
"slug" => $slug
]);
$client_id = $information->getClientId();
//Obtenemos configuraciones para mostrar o ocultar productos sin stock
$setting = $this->getDoctrine()->getRepository(\App\Entity\Setting::class)->findOneBy([
"Client" => $information
]);
$query = $em->getRepository(\App\Entity\Product::class)->getOneProduct($request->get('id'),$setting->getCartHideEmptyStock());
//VERIFICAMOS HORARIOS
$store_status = 'open';
$day_number = date('N');
$hoursToday = $this->getDoctrine()->getRepository(\App\Entity\Setting::class)->verifyHoursForToday($day_number, $client_id);
if($hoursToday['is_open'] == '0')
{
$store_status = 'closed';
}
$customerData = '';
if($this->get("session")->get("userData"))
{
$customerData = $this->get("session")->get("userData");
}
// replace this example code with whatever you need
return $this->render('Frontend/_modal_content_product.html.twig', array(
'item' => $query,
'setting' => $setting,
'information' => $information,
'store_status' => $store_status,
'customerData' => $customerData,
'slug' => $slug
));
}
/**
*
* @Route("{slug}/get-product", name="frontend_get_product")
*/
public function getProductAction(Request $request, $slug)
{
$em = $this->getDoctrine()->getManager();
//$client_id = $this->getParameter('client_id');
$client = $this->getDoctrine()->getRepository(Client::class)->findOneBy(["slug" => $slug]);
$client_id = $client->getClientId();
$pager_limit = 12;
$globalSearch = "";
$token = '';
if($request->get("token"))
{
$token = $request->get('token');
}
$token2 = '';
if($request->get("token2"))
{
$token2 = $request->get('token2');
}
if($request->get('search'))
{
$globalSearch = $request->get('search');
}
$filters = [
'token' => $token,
'token2' => $token2,
'type' => $request->get('type'),
'search' => $globalSearch,
'limit' => $request->get('limit')
];
//Obtenemos configuraciones para mostrar o ocultar productos sin stock
$setting = $this->getDoctrine()->getRepository(\App\Entity\Setting::class)->findOneBy(["Client" => $client]);
$query = $em->getRepository(\App\Entity\Product::class)->getProducts($filters,$client_id,$setting->getCartHideEmptyStock());
$subcategories = $em->getRepository(\App\Entity\Subcategory::class)->findBy(['is_active' => 1]);
$categories = $em->getRepository(\App\Entity\Category::class)->getCategories($client_id);
$total = $em->getRepository(\App\Entity\Product::class)->getProducts($filters,$client_id,$setting->getCartHideEmptyStock(),true);
// replace this example code with whatever you need
return $this->render('Frontend/product_items.html.twig', array(
'list' => $query,
'pager_limit' => $pager_limit,
'subcategories' => $subcategories,
'categories' => $categories,
'product_count' => count($total),
'globalSearch' => $globalSearch,
'isMore' => $request->get('isMore'),
'setting' => $setting,
'slug' => $slug,
'information' => $client
));
}
/**
*
* @Route("/start/token={id}", name="frontend_start")
*/
public function startAction(Request $request) {
if($request->get('id') == 'c4ca4238a0b923820dcc509a6f75849b')
{
$valor = "25";
} elseif ($request->get('id') == 'c81e728d9d4c2f636f067f89cc14862c')
{
$valor = "58";
} elseif ($request->get('id') == 'eccbc87e4b5ce2fe28308fd9f2a7baf3')
{
$valor = "39";
}
return $this->render('Frontend/Index/start.html.twig', array(
"valor" => $valor
));
}
/**
* @Route("{slug}/blogs", name="frontend_blog")
*/
public function blogAction(Request $request, $slug)
{
// replace this example code with whatever you need
$categories = $this->getDoctrine()->getRepository(\App\Entity\Blog::class)->getCategoriesBlog($slug);
return $this->render('Frontend/Blog/blog.html.twig', array(
'categories' => $categories,
'slug' => $slug,
'productCategory' => '',
'pager_limit' => 12,
'globalSearch' => '',
'brand' => '',
'category' => ''
));
}
/**
* @Route("{slug}/blog/load-items", name="frontend_blog_items")
*/
public function blogLoadAction(Request $request, $slug)
{
$em = $this->getDoctrine()->getManager();
$desde = $request->get('desde');
$hasta = $request->get('hasta');
$categoria = $request->get('categoria');
//$client_id = $this->getParameter('client_id');
$client = $this->getDoctrine()->getRepository(Client::class)->findOneBy(array("slug" => $slug));
$client_id = $client->getClientId();
$blogs = $em->getRepository(\App\Entity\Blog::class)->listBlog($desde, $hasta, $categoria, false, $client_id);
$blogs_total = $em->getRepository(\App\Entity\Blog::class)->listBlog($desde, $hasta, $categoria, true, $client_id);
$blogs_count = $em->getRepository(\App\Entity\Blog::class)->listBlog(0,($desde+$hasta), $categoria, false, $client_id);
return $this->render('Frontend/Blog/load_items_blog.html.twig',array(
"list" => $blogs,
"slug" => $slug,
"count" => count($blogs_count),
"total" => count($blogs_total)
));
}
/**
* @Route("{slug}/blog/detail/{blogId}", name="frontend_blog_detail")
* @ParamDecryptor({"blogId"})
*/
public function blogDetailAction(Request $request, Blog $blog, $slug)
{
//$category = $this->getDoctrine()->getRepository('AppBundle:BlogCategory')->findBy(array("isActive" => '1'));
return $this->render('Frontend/Blog/blog_detail.html.twig',array(
"blog" => $blog,
"slug" => $slug,
'productCategory' => '',
'pager_limit' => 12,
'globalSearch' => '',
'brand' => '',
'category' => ''
));
}
/**
* @Route("/check", name="frontend_check" )
*/
public function checkAction(Request $request) {
return new JsonResponse(array(
'status' => 'success'
));
}
/**
* @Route("/process", name="frontend_process" )
*/
public function processAction(Request $request) {
var_dump($request);
die;
return new JsonResponse(array(
'status' => 'success'
));
}
/**
*
* @Route("{slug}/checkout", name="frontend_checkout")
*/
public function checkoutAction(Request $request, $slug)
{
$lastUsername = $request->getSession()->get(Security::LAST_USERNAME);
$information = $this->getDoctrine()->getRepository(\App\Entity\Client::class)->findOneBy([
"slug" => $slug
]);
$client_id = $information->getClientId();
if(!$information)
{
return $this->redirectToRoute("homepage_website", ['slug' => $slug]);
}
$currentCart = $this->get("session")->get("cart");
if($currentCart)
{
} else {
return $this->redirectToRoute("frontend_index", ['slug' => $slug]);
}
$settings = $this->getDoctrine()->getRepository(\App\Entity\Setting::class)->findOneBy([
"Client" => $information
]);
$customerData = '';
if($lastUsername)
{
$customerData = $request->getSession()->get($lastUsername);
}
$coupon = '';
if($this->get("session")->get("coupon"))
{
$coupon = $this->get("session")->get("coupon");
}
$day_number = date('N');
$store_status = "open";
$client = $this->getDoctrine()->getRepository(\App\Entity\Client::class)->findOneBy(["clientId" => $client_id]);
$hoursToday = $this->getDoctrine()->getRepository(\App\Entity\Setting::class)->verifyHoursForToday($day_number, $client_id);
$paymentMethods = $this->getDoctrine()->getRepository(\App\Entity\PaymentMethod::class)->findBy([
'Client' => $client,
'is_display' => 1,
'is_active' => 1
]);
$paymentCardObj = $this->getDoctrine()->getRepository(\App\Entity\PaymentMethod::class)->findOneBy([
'Client' => $client,
'is_active' => 1,
'is_cash' => 0
]);
if($hoursToday['is_open'] == '0')
{
$store_status = "closed";
}
$session_uniq_id = uniqid();
$org_id = "";
$random_value = "";
if($paymentCardObj->getPaymentMethodGateway())
{
//QPAYPRO es gateway 1
if($paymentCardObj->getPaymentMethodGateway()->getPaymentMethodGatewayId() == 1)
{
$org_id = "1snn5n9w";
$random_value = "visanet_qpay"."1618";
//Esta bandera es para definir si es PROD o no
//Get Field Token Tertiary es igual al public Key
if($paymentCardObj->getIsProd())
{
$org_id = "k8vif92e";
$random_value = $paymentCardObj->getFieldTokenTertiary()."1618";
}
}
}
$storedCards = [];
if($customerData)
{
$storedCards = $this->getDoctrine()->getRepository(\App\Entity\CustomerToken::class)->findBy([
'Customer' => $customerData['customer_id'],
'is_active' => 1
]);
}
return $this->render('Frontend/Checkout/checkout.html.twig', [
'productCategory' => '',
'pager_limit' => 12,
'globalSearch' => '',
'slug' => $slug,
'settings' => $settings,
'information' => $information,
'coupon' => $coupon,
'customerData' => $customerData,
'brand' => '',
'category' => '',
'store_stataus' => $store_status,
'client_id' => $client_id,
'payment_methods' => $paymentMethods,
'session_uniq_id' => $session_uniq_id,
'random_value' => $random_value,
'org_id' => $org_id,
'storedCards' => $storedCards
]);
}
/**
* @Route("{slug}/email_test", name="frontend_checkout_emailtest")
*/
public function emailTest(Request $request, MailHelper $MailHelper)
{
exit;
$textMessage = str_replace('_TABLA_PEDIDOS_', '<br>PEDIDOS PEDIDOS PEDIDOS',"Hola hola hola");
$myMessage = $this->render ( 'MailTemplate/template_email_orders.html.twig', array (
'emailTitle' => "Prueba Email",
'logoPath' => "https://dev.aguilalibreweb.com/2308/ecommerce_aguila/public/uploads/12/web/30724402820250820002840.png",
'message' => $textMessage,
'footer1' => "footer",
'user' => '',
'rootWebUrl' => "rootURL"
) )->getContent();
$debug = $MailHelper->sendEmail("Nombre de Tienda","servicio@aguilalibreweb.com", "Prueba Email", $myMessage, "");
return new JsonResponse(array(
'status' => 'success',
'orderId' => $debug
));
}
/**
*
* @Route("/checkout/execute", name="frontend_checkout_execute")
*/
public function checkoutExecuteAction(Request $request, MailHelper $MailHelper)
{
$lastUsername = $request->getSession()->get(Security::LAST_USERNAME);
$userData = false;
if($lastUsername)
{
$userData = $request->getSession()->get($lastUsername);
}
$em = $this->getDoctrine ()->getManager ();
$client_id = $this->getParameter('client_id');
$data = $request->get('query');
$payment_method = $request->get('payment_method');
$dummy_order_id = $request->get('auth');
/*echo "<pre>";
print_r($data);
echo "</pre>";
exit;*/
$userData = $this->get("session")->get("userData");
$information = $this->getDoctrine()->getRepository(\App\Entity\Client::class)->findOneBy(array(
"clientId" => $client_id
));
$webSetting = $this->getDoctrine()->getRepository(\App\Entity\WebSetting::class)->findOneBy(array(
"Client" => $information
));
//Obtenemos simbolo de moneda a utilizar
$symbol = $information->getCurrency()->getCurrencySymbol();
$payment = $this->getDoctrine()->getRepository(\App\Entity\PaymentMethod::class)->findOneBy(array(
"paymentMethodId" => $payment_method
));
$orderStatus = $this->getDoctrine()->getRepository(\App\Entity\OrderStatus::class)->findOneBy(array(
"orderStatusId" => 1
));
$deliveryCharge = "";
if($request->get("delivery_price"))
{
$deliveryCharge = $request->get("delivery_price");
}
$orders = new Orders();
$orders->setOrderType('cart');
$orders->setDeliveryCharge($deliveryCharge);
$orders->setPaymentMethod($payment);
$orders->setServiceFee($information->getServiceFee());
if($userData)
{
$customerObj = $this->getDoctrine()->getRepository(\App\Entity\Customer::class)->findOneBy(array(
"customerId" => $userData['customer_id']
));
$orders->setCustomer($customerObj);
}
$orders->setIsActive(1);
$orders->setClient($information);
$orders->setOrderStatus($orderStatus);
$orders->setCreatedAt(new \DateTime());
$em->persist($orders);
$em->flush();
if($orders)
{
$currentCart = $this->get("session")->get("cart");
$cartList = json_decode($currentCart);
$orderDetailMail ="<table style='width:100%;text-align: left!important;'>
<tr style='border-bottom:1px solid #ccc'>
<th>Productos</th><th></th>
</tr>";
$totalOrder = 0;
if(count($cartList) > 0)
{
foreach($cartList as $cart)
{
$productObj = $this->getDoctrine()->getRepository(\App\Entity\Product::class)->findOneBy(array(
"productId" => $cart->pid
));
$offerObj = $this->getDoctrine()->getRepository(\App\Entity\Offer::class)->findOneBy(array(
"offerId" => $cart->oid
));
$orderDetail = new OrderDetail();
$orderDetail->setOrder($orders);
$orderDetail->setProduct($productObj);
$orderDetail->setQuantity($cart->quantity);
$orderDetail->setPriceGiven($cart->price);
$orderDetail->setOriginalPrice($productObj->getMainPrice());
$orderDetail->setCreatedAt(new \DateTime());
$totalPrice = $cart->quantity*$cart->price;
$totalOrder = $totalOrder + $totalPrice;
$orderDetailMail .= "<tr style='border-bottom:1px solid #ccc;text-align: left!important;'>
<td style='padding:10px;text-align: left!important;'>
<img style='height:80px' src='".$productObj->getMainPicture()."' >
</td>
<td style='padding:10px;text-align: left!important;'>
".$productObj->getName()."<br>
$symbol.$cart->price x $cart->quantity = <b>$symbol.".number_format($totalPrice, 2, '.', '')."</b><br>
";
if($cart->oid)
{
$offerObj = $this->getDoctrine()->getRepository(\App\Entity\Offer::class)->findOneBy(array(
"offerId" => $cart->oid
));
$orderDetailMail.="<p style='color:tomato;'>".$offerObj->getOfferName()."</p>";
$orderDetail->setOffer($offerObj);
}
$orderDetailMail.="</td></tr>";
$em->persist($orderDetail);
$em->flush();
//RESTAMOS DE INVENTARIO
$is_not_stock = $productObj->getIsNotStock();
if($is_not_stock != '1')
{
$productInventory = $this->getDoctrine()->getRepository(\App\Entity\ProductInventory::class)->findOneBy(array(
"Product" => $productObj
));
if($productInventory)
{
$oldStock = $productInventory->getAvailable();
$stock = $oldStock - $cart->quantity;
$productInventory->setAvailable($stock);
$em->persist($productInventory);
$em->flush();
$productInventoryLog = new ProductInventoryLog();
$productInventoryLog->setProduct($productObj);
$productInventoryLog->setCreatedAt(new \DateTime());
$productInventoryLog->setOrderDetail($orderDetail);
$productInventoryLog->setSelledQuantity($cart->quantity);
$em->persist($productInventoryLog);
$em->flush();
}
}
}
}
$orderDetailMail.="</table>";
$grandTotal = $totalOrder;
$orders->setTotalOriginal($grandTotal);
if($this->get("session")->get("coupon") && $this->get("session")->get("coupon") != '')
{
$coupon_id = $this->get("session")->get("coupon");
$couponObj = $this->getDoctrine()->getRepository('AppBundle:Coupon')->findOneBy(array(
"couponId" => $coupon_id
));
$discount = ($totalOrder * $couponObj->getDiscountPercent())/100;
$total = $totalOrder - $discount;
$grandTotal = $total;
$orders->setTotal(number_format($total, 2, '.', ','));
$orders->setCoupon($couponObj);
$this->get("session")->set("coupon", '');
$orderDetailMail.="<center><table>
<tr><td style='width:150px;text-align: left!important;'><b style='color:#ccc'>Cupón aplicado: </b></td><td style='text-align: left!important;' >".$couponObj->getCouponCode()."</td></tr>
<tr><td style='text-align: left!important;'><b style='color:#ccc'>Subtotal: </b></td><td style='text-align: left!important;'> $symbol.".$total."</td></tr>
<tr><td style='text-align: left!important;'><b style='color:#ccc'>Descuento: </b></td><td style='text-align: left!important;'> $symbol.".number_format($discount, 2, '.', ',')." <b>-".$couponObj->getDiscountPercent()."%</b></td></tr></table></center>";
} else {
$orders->setTotal(number_format($totalOrder, 2, '.', ','));
}
$em->persist($orders);
$em->flush();
if($deliveryCharge == 'N')
{
$orderDetailMail.="<p style='color:tomato'>No se pudo calcular el cargo por la entrega automáticamente.Cargos de entrega podrían aplicar posterior a la confirmación de su pedido.</p>";
} else if($deliveryCharge == 'FREE')
{
$orderDetailMail.="<p style='color:tomato'>¡Envío Gratis!</p>";
} else if($deliveryCharge != "")
{
$orderDetailMail.="<p style='color:tomato'>+Cargo de envío: <b>$symbol.".number_format($deliveryCharge, 2, '.', ',')."</b></p>";
}
//Se agrega el service fee
if($information->getServiceFee() > 0)
{
$grandTotal = $grandTotal + $information->getServiceFee();
}
$orderDetailMail.="<h3><b>Total: $symbol.</b>".number_format($grandTotal, 2, '.', ',')." </h3>";
$purchaserValue = "";
$emailAnonymous="";
foreach($data['purchaser'] as $purchaser)
{
if($purchaser['is_email'] == true){
$emailAnonymous = $purchaser['value'];
}
$fieldClientObj = $this->getDoctrine()->getRepository(\App\Entity\FieldClient::class)->findOneBy(array(
"fieldClientId" => $purchaser['field_client_id']
));
$fieldTypeObj = $this->getDoctrine()->getRepository(\App\Entity\FieldType::class)->findOneBy(array(
"fieldTypeId" => $purchaser['field_type_id']
));
$orderField = new OrderField();
$orderField->setOrder($orders);
$orderField->setFieldClient($fieldClientObj);
$orderField->setFieldType($fieldTypeObj);
$orderField->setName($purchaser['name']);
if($purchaser['field_type_id'] == 3)
{
$fieldValueObj = $this->getDoctrine()->getRepository(\App\Entity\FieldValue::class)->findOneBy(array(
"fieldValueId" => $purchaser['value']
));
if($fieldValueObj)
{
$orderField->setFieldValue($fieldValueObj);
}
} else if($purchaser['field_type_id'] == 4)
{
$lat = $purchaser['value']['lat'];
$lng = $purchaser['value']['lng'];
$orderField->setValueText("$lat,$lng");
} else {
$orderField->setValueText($purchaser['value']);
}
$orderField->setCreatedAt(new \DateTime());
$em->persist($orderField);
$em->flush();
}
//ENVÍO DE EMAIL
$client = $this->getDoctrine()->getRepository(\App\Entity\Client::class)->findOneBy(array(
"clientId" => $client_id
));
$setting = $this->getDoctrine()->getRepository(\App\Entity\Setting::class)->findOneBy(array(
"Client" => $client
));
$MailHelper = new MailHelper();
$rootWebUrl = $MailHelper->getRootWebAppURL("0");
$subject = 'Nuevo pedido registrado #'.$orders->getOrderId();
$textMessage = $setting->getTemplateConfirmationOrders();
$array_cc = array();
$mails_sent = "";
if($userData)
{
$mailTo = $customerObj->getEmail();
$mailCopy = $setting->getEmailNotificationOrder();
$mails_sent=$mailTo.",".$mailCopy;
} else {
if($emailAnonymous != '')
{
$mailTo = $emailAnonymous;
$mailCopy = $setting->getEmailNotificationOrder();
$mails_sent=$mailTo.",".$mailCopy;
} else {
$mailTo = $setting->getEmailNotificationOrder();
$mails_sent=$mailTo;
$mailCopy = null;
}
}
$footer1 = null;
$textMessage = str_replace('_TABLA_PEDIDOS_', '<br>'.$orderDetailMail, $textMessage);
$myMessage = $this->render ( 'MailTemplate/template_email_orders.html.twig', array (
'emailTitle' => $subject,
'logoPath' => $webSetting->getLogoPath(),
'message' => $textMessage,
'footer1' => $footer1,
'user' => '',
'rootWebUrl' => $rootWebUrl
) )->getContent();
$MailHelper->sendEmail($client->getName(),$mailTo, $subject, $myMessage, $mailCopy );
//Guardamos log de envío de alerta
$alertPurchase = new AlertPurchase();
$alertPurchase->setClient($client);
$alertPurchase->setCreatedAt(new \DateTime());
$alertPurchase->setEmailSent($mails_sent);
$alertPurchase->setIsActive(1);
$alertPurchase->setOrder($orders);
$em->persist($alertPurchase);
$em->flush();
//Si la compra se proceso correctamente entonces guardamos el id de la orden en la tabla payment
if($payment->getIsCash() != '1' && $dummy_order_id != '0')
{
$paymentRegister = $this->getDoctrine()->getRepository(\App\Entity\Payment::class)->findOneBy(array(
"custom_auth_code" => $dummy_order_id
));
$paymentRegister->setOrder($orders);
$em->persist($paymentRegister);
$em->flush();
}
$orderIdEncoded = $this->encryptor->encrypt($orders->getOrderId());
return new JsonResponse(array(
'status' => 'success',
'orderId' => $orderIdEncoded
));
} else {
return new JsonResponse(array(
'status' => 'error',
'orderId' => ''
));
}
}
/**
*
* @Route("/checkout/direct-execute", name="frontend_checkout_direct_execute")
*/
public function checkoutDirectExecuteAction(Request $request)
{
$em = $this->getDoctrine ()->getManager ();
$client_id = $this->getParameter('client_id');
$product_id = $request->get('product_id');
$offer_id = $request->get('offer_id');
$price = $request->get('price');
$data = $request->get('query');
$userData = $this->get("session")->get("userData");
$information = $this->getDoctrine()->getRepository(\App\Entity\Client::class)->findOneBy(array(
"clientId" => $client_id
));
//Obtenemos simbolo de moneda a utilizar
$symbol = $information->getCurrency()->getCurrencySymbol();
$payment = $this->getDoctrine()->getRepository(\App\Entity\PaymentMethod::class)->findOneBy(array(
"paymentMethodId" => 1
));
$orderStatus = $this->getDoctrine()->getRepository(\App\Entity\OrderStatus::class)->findOneBy(array(
"orderStatusId" => 1
));
$orders = new Orders();
$orders->setOrderType('direct');
$orders->setPaymentMethod($payment);
if($userData)
{
$customerObj = $this->getDoctrine()->getRepository(\App\Entity\Customer::class)->findOneBy(array(
"customerId" => $userData['customer_id']
));
$orders->setCustomer($customerObj);
}
$orders->setIsActive(1);
$orders->setOrderStatus($orderStatus);
$orders->setCreatedAt(new \DateTime());
$em->persist($orders);
$em->flush();
if($orders)
{
$orderDetailMail ="<table style='width:100%;text-align: left!important;'>
<tr style='border-bottom:1px solid #ccc'>
<th>Producto</th><th></th>
</tr>";
$productObj = $this->getDoctrine()->getRepository(\App\Entity\Product::class)->findOneBy(array(
"productId" => $product_id
));
$offerObj = $this->getDoctrine()->getRepository(\App\Entity\Offer::class)->findOneBy(array(
"offerId" => $offer_id
));
$orderDetail = new OrderDetail();
$orderDetail->setOrder($orders);
$orderDetail->setProduct($productObj);
$orderDetail->setQuantity(1);
$orderDetail->setPriceGiven($price);
$orderDetail->setOriginalPrice($productObj->getMainPrice());
$orderDetail->setCreatedAt(new \DateTime());
$orderDetailMail .= "<tr style='border-bottom:1px solid #ccc;text-align: left!important;'>
<td style='padding:10px;text-align: left!important;'>
<img style='height:80px' src='".$productObj->getMainPicture()."' >
</td>
<td style='padding:10px;text-align: left!important;'>
".$productObj->getName()."<br>
$symbol.$price x 1 = <b>$symbol.".number_format($price, 2, '.', '')."</b><br>
";
if($offer_id && $offer_id != '')
{
$offerObj = $this->getDoctrine()->getRepository(\App\Entity\Offer::class)->findOneBy(array(
"offerId" => $offer_id
));
$orderDetailMail.="<p style='color:tomato;'>".$offerObj->getOfferName()."</p>";
$orderDetail->setOffer($offerObj);
}
$orderDetailMail.="</td></tr>";
$em->persist($orderDetail);
$em->flush();
//RESTAMOS DE INVENTARIO
$is_not_stock = $productObj->getIsNotStock();
if($is_not_stock != '1'){
$productInventory = $this->getDoctrine()->getRepository(\App\Entity\ProductInventory::class)->findOneBy(array(
"product" => $productObj
));
if($productInventory){
$oldStock = $productInventory->getAvailable();
$stock = $oldStock - 1;
$productInventory->setAvailable($stock);
$em->persist($productInventory);
$em->flush();
$productInventoryLog = new ProductInventoryLog();
$productInventoryLog->setProduct($productObj);
$productInventoryLog->setCreatedAt(new \DateTime());
$productInventoryLog->setOrderDetail($orderDetail);
$productInventoryLog->setSelledQuantityy(1);
$em->persist($productInventoryLog);
$em->flush();
}
}
$orderDetailMail.="</table>";
$grandTotal = $price;
$orders->setTotalOriginal($grandTotal);
$orders->setTotal(number_format($grandTotal, 2, '.', ','));
$orderDetailMail.="<h3><b>Total: $symbol.</b>".number_format($grandTotal, 2, '.', ',')." </h3>";
$em->persist($orders);
$em->flush();
$purchaserValue = "";
$emailAnonymous="";
foreach($data as $purchaser)
{
if($purchaser['is_email'] == true){
$emailAnonymous = $purchaser['value'];
}
$fieldClientObj = $this->getDoctrine()->getRepository(\App\Entity\FieldClient::class)->findOneBy(array(
"fieldClientId" => $purchaser['field_client_id']
));
$fieldTypeObj = $this->getDoctrine()->getRepository(\App\Entity\FieldType::class)->findOneBy(array(
"fieldTypeId" => $purchaser['field_type_id']
));
$orderField = new OrderField();
$orderField->setOrder($orders);
$orderField->setFieldClient($fieldClientObj);
$orderField->setFieldType($fieldTypeObj);
$orderField->setName($purchaser['name']);
if($purchaser['field_type_id'] == 3)
{
$fieldValueObj = $this->getDoctrine()->getRepository(\App\Entity\FieldValue::class)->findOneBy(array(
"fieldValueId" => $purchaser['value']
));
if($fieldValueObj)
{
$orderField->setFieldValue($fieldValueObj);
}
} else if($purchaser['field_type_id'] == 4)
{
$lat = $purchaser['value']['lat'];
$lng = $purchaser['value']['lng'];
$orderField->setValueText("$lat,$lng");
} else {
$orderField->setValueText($purchaser['value']);
}
$orderField->setCreatedAt(new \DateTime());
$em->persist($orderField);
$em->flush();
}
//ENVÍO DE EMAIL
$client = $this->getDoctrine()->getRepository(\App\Entity\Client::class)->findOneBy(array(
"clientId" => $client_id
));
$setting = $this->getDoctrine()->getRepository(\App\Entity\Setting::class)->findOneBy(array(
"client" => $client
));
$MailHelper = new MailHelper();
$rootWebUrl = $MailHelper->getRootWebAppURL("0");
$subject = 'Nuevo pedido registrado #'.$orders->getOrderId();
$textMessage = $setting->getDirectTemplateConfirmationOrders();
$array_cc = array();
$mails_sent = "";
if($userData){
$mailTo = $customerObj->getEmail();
$mailCopy = $setting->getDirectEmailNotificationOrder();
$mails_sent=$mailTo.",".$mailCopy;
}else{
if($emailAnonymous != ''){
$mailTo = $emailAnonymous;
$mailCopy = $setting->getDirectEmailNotificationOrder();
$mails_sent=$mailTo.",".$mailCopy;
}else{
$mailTo = $setting->getDirectEmailNotificationOrder();
$mails_sent=$mailTo;
$mailCopy = null;
}
}
$footer1 = null;
$textMessage = str_replace('_TABLA_PEDIDOS_', '<br>'.$orderDetailMail, $textMessage);
$myMessage = $this->render ( 'MailTemplate/template_email_orders.html.twig', array (
'emailTitle' => $subject,
'message' => $textMessage,
'footer1' => $footer1,
'user' => '',
'rootWebUrl' => $rootWebUrl
) )->getContent();
$MailHelper->sendEmail($client->getName(),$mailTo, $subject, $myMessage, $mailCopy );
//Guardamos log de envío de alerta
$alertPurchase = new AlertPurchase();
$alertPurchase->setClient($client);
$alertPurchase->setCreatedAt(new \DateTime());
$alertPurchase->setEmailSent($mails_sent);
$alertPurchase->setIsActive(1);
$alertPurchase->setOrder($orders);
$em->persist($alertPurchase);
$em->flush();
return new JsonResponse(array(
'status' => 'success',
'orderId' => $orders->getOrderId()
));
} else {
return new JsonResponse(array(
'status' => 'error',
'orderId' => ''
));
}
}
/**
* @Route("{slug}/checkout/validate-cart", name="frontend_checkout_validate_cart")
*/
public function checkoutValidateCartAction(Request $request, $slug)
{
$currentCart = $this->get("session")->get("cart");
$cartList = json_decode($currentCart);
if(count($cartList) > 0)
{
$validate = true;
foreach($cartList as $cart)
{
$product_stock = $this->getDoctrine()->getRepository(\App\Entity\Product::class)->getInventoryProduct($cart->pid);
$stock = 0;
if($product_stock){
if($product_stock['available'] != ''){
$stock = $product_stock['available'];
}
if($product_stock['is_not_stock'] == '1'){
$stock = 'not_stock';
}
}
if($stock != 'not_stock'){
if($cart->quantity > $stock){
$validate = false;
break;
}
}
}
}
return new JsonResponse(array(
'validate' => $validate
));
}
/**
* @Route("{slug}/checkout/validate-stock", name="frontend_checkout_validate_stock")
*/
public function checkoutValidateStockAction(Request $request, $slug)
{
$id = $request->get('id');
if($id != '')
{
$validate = true;
$product_stock = $this->getDoctrine()->getRepository(\App\Entity\Product::class)->getInventoryProduct($id);
$stock = 0;
if($product_stock){
if($product_stock['available'] != ''){
$stock = $product_stock['available'];
}
if($product_stock['is_not_stock'] == '1'){
$stock = 'not_stock';
}
}
if($stock != 'not_stock'){
if($stock < 1){
$validate = false;
}
}
}
return new JsonResponse(array(
'validate' => $validate
));
}
/**
*
* @Route("{slug}/checkout/thanks", name="frontend_checkout_thanks")
*/
public function checkOutThanksAction(Request $request, $slug)
{
// replace this example code with whatever you need
//$client_id = $this->getParameter('client_id');
$client = $this->getDoctrine()->getRepository(\App\Entity\Client::class)->findOneBy(array(
"slug" => $slug
));
if(!$client)
{
//Si no se encuentra debe indicar algún error
}
$orderNumberRaw = $request->get('orderNumber','');
$orderNumber = $this->encryptor->decrypt($orderNumberRaw);
$order = $this->getDoctrine()->getRepository(\App\Entity\Orders::class)->findOneBy(array("orderId"=> $orderNumber));
if(!$order)
{
return $this->redirectToRoute("frontend_index", ['slug' => $slug]);
}
//$categories = $this->getDoctrine()->getRepository(\App\Entity\Blog::class)->getCategoriesBlog($slug);
$settings = $this->getDoctrine()->getRepository(\App\Entity\Setting::class)->findOneBy(array(
"Client" => $client
));
return $this->render('Frontend/Checkout/thanks.html.twig', array(
'productCategory' => '',
'pager_limit' => 12,
'globalSearch' => '',
'settings' => $settings,
'orderNumber' => $orderNumber,
'brand' => '',
'category' => '',
'slug' => $slug,
'type' => $order->getOrderType()
));
}
/**
* @Route("{slug}/checkout/payment", name="frontend_checkout_payment")
*/
public function checkoutPaymentAction(Request $request, $slug)
{
$purchaser = $request->get('query');
$purchaserObj = $purchaser;
$currentCart = $this->get("session")->get("cart");
$response = $currentCart;
return new JsonResponse(array('status' => 'success', 'data' => $purchaserObj));
}
/**
* @Route("/checkout/test_payment", name="frontend_checkout_test")
*/
public function checkoutTestPayment(Request $request, PaymentQPayProHelper $paymentQPayProHelper)
{
$em = $this->getDoctrine()->getManager();
$parameters = array(
"x_amount" => 1.00,
"x_currency_code" => "GTQ",
"x_product_id" => "1618",
"x_freight" => 0,
"x_audit_number" => "123",
"x_line_item" => "T-shirt Live Dreams<|>w01<|><|>1<|>1000.00<|>N",
"x_email" => "servicio@aguilalibreweb.com",
"x_fp_sequence" => "123",
"x_fp_timestamp" => time(),
"x_invoice_num" => "123",
"x_first_name" => "Customer",
"x_last_name" => "Name",
"x_company" => "C/F",
"x_address" => "Guatemala",
"x_city" => "Guatemala",
"x_state" => "Guatemala",
"x_country" => "Guatemala",
"x_zip" => "01056",
"cc_number" => "4111111111111111",
"cc_exp" => "01/26",
"cc_cvv2" => "4567",
"cc_name" => "Josue Prueba Dos",
'finger' => "",
"device_fingerprint_id" => ""
);
$QPayPro = new PaymentQPayProHelper();
$response = $QPayPro->executePaymentOld($em, $parameters);
return new JsonResponse(array('status' => 'success','msg' => $response));
}
/**
* @Route("{slug}/checkout/payment_no_cash", name="frontend_checkout_no_cash")
*/
public function checkoutPaymentNoCashAction(Request $request, PaymentQPayProHelper $paymentQPayProHelper, $slug)
{
$lastUsername = $request->getSession()->get(Security::LAST_USERNAME);
$userData = false;
if($lastUsername)
{
$userData = $request->getSession()->get($lastUsername);
}
$ccData = $request->get('ccData');
$purchasers = $request->get('query');
$paymentId = $request->get('pmid');
$deliveryPrice = $request->get('deliveryPrice');
$finger = $request->get('finger');
$device_fingerprint_id = $request->get('device_fingerprint_id');
$em = $this->getDoctrine()->getManager();
//$client_id = $this->getParameter('client_id');
$session_uniq_id = uniqid();
//Información de la tarjeta
$dummyOrderId = date("Ymdhis").rand(1,999);
$expDate = $ccData['ccmonth']."/".$ccData['ccyear'];
$cleanNumber = str_replace(" ", "", $ccData['ccn']);
//Si viene desde la selección de un Token, entonces usaremos el nombre de sesión
//Que seguramente debería tener su sesión iniciada para usar la función de tokens
if($request->get('paymentMode') == 'token')
{
$customer_name = explode(' ',$userData['name']);
} else {
$customer_name = explode(' ',$ccData['name']);
}
if(count($customer_name) == 1 || !is_array($customer_name))
{
return new JsonResponse(array(
'status' => 'error',
'msg' => 'Por favor, escriba su nombre como aparece en la tarjeta de crédito'
));
}
if($paymentId > 0)
{
$clientObj = $this->getDoctrine()->getRepository(\App\Entity\Client::class)->findOneBy(array('slug' => $slug));
if(!$clientObj)
{
//Si no encuentra el cliente, entonces da error
return new JsonResponse(array(
'status' => 'error',
'msg' => 'No se puede realizar la transacción en este momento. Por favor, informar de este error a soporte técnico (A34)'
));
}
//Si el customer no esta registrado y no hay un campo configurado para email entonces envia el email al cliente
$emailCustomer = $clientObj->getEmail();
if($userData)
{
$customerObj = $this->getDoctrine()->getRepository(\App\Entity\Customer::class)->findOneBy(array('customerId' => $userData['customer_id']));
$emailCustomer = $customerObj->getEmail();
} else {
foreach($purchasers['purchaser'] as $purchaser)
{
if($purchaser['is_email'] == true)
{
$emailCustomer = $purchaser['value'];
}
}
}
$paymentMethod = $this->getDoctrine()->getRepository(\App\Entity\PaymentMethod::class)->findOneBy(array(
'paymentMethodId' => $paymentId,
'Client' => $clientObj
));
if($paymentMethod)
{
//QPAY PRO
if($paymentMethod->getPaymentMethodGateway() && $paymentMethod->getPaymentMethodGateway()->getPaymentMethodGatewayId() == '1')
{
//Calculo de Total incluyendo cargos dPre envio
$cartInfo = $this->refreshCart($slug);
$grandTotal = 0;
if($deliveryPrice == 'N')
{
$grandTotal = $cartInfo['price'];
} else if($deliveryPrice == "FREE")
{
$grandTotal = $cartInfo['price'];
} else {
if($deliveryPrice > 0)
{
$grandTotal = ($cartInfo['price']+$deliveryPrice);
} else {
$grandTotal = $cartInfo['price'];
}
}
//Agregando el servife fee
if($clientObj->getServiceFee() > 0)
{
$withServiceFee = $grandTotal + $clientObj->getServiceFee();
$grandTotal = number_format($withServiceFee, 2, '.', '');
}
$order = false;
$QPayPro = new PaymentQPayProHelper();
//Si se usa el metodo para llenar los datos de tarjeta de crédito
if($request->get('paymentMode') == 'card')
{
$parameters = array(
"x_amount" => $grandTotal,
"x_currency_code" => $clientObj->getCurrency()->getCurrencyIso(),
"x_product_id" => "1618",
"x_freight" => 0,
"x_audit_number" => $dummyOrderId,
"x_line_item" => $cartInfo['qpay_pro'],
"x_email" => $emailCustomer,
"x_fp_sequence" => $dummyOrderId,
"x_fp_timestamp" => time(),
"x_invoice_num" => $dummyOrderId,
"x_first_name" => $customer_name[0],
"x_last_name" => $customer_name[1],
"x_company" => "C/F", // Company o C/F
"x_address" => "Guatemala",
"x_city" => "Guatemala",
"x_state" => "Guatemala",
"x_country" => "Guatemala",
"x_zip" => "01056",
"cc_number" => $cleanNumber,
"cc_exp" => $expDate,
"cc_cvv2" => $ccData['ccv'],
"cc_name" => $ccData['name'],
'finger' => $finger,
"device_fingerprint_id" => $device_fingerprint_id
);
$response = $QPayPro->executePayment($em, $parameters, $clientObj, $paymentId);
//Si se usa el metodo de pago TOKEN (Solo para usuarios que esten registrados)
} else if($request->get('paymentMode') == 'token')
{
$parameters = array(
"x_amount" => $grandTotal,
"x_currency" => $clientObj->getCurrency()->getCurrencyIso()
);
$customerTokenDecrypted = $this->encryptor->decrypt($request->get('customerToken'));
$tokenObj = $this->getDoctrine()->getRepository(\App\Entity\CustomerToken::class)->findOneBy(array(
'customerTokenId' => $customerTokenDecrypted,
'is_active' => 1
));
if($tokenObj)
{
$response = $QPayPro->useToken($em, $parameters, $clientObj, $paymentId, $tokenObj->getToken());
} else {
return new JsonResponse(array(
'status' => 'error',
'msg' => 'No es posible utilizar esta tarjeta guardada en este momento. Por favor intente de nuevo y si el problema persiste Comuníquese con servicio al cliente.'
));
}
} else {
return new JsonResponse(array(
'status' => 'error',
'msg' => 'No es posible realizar la transacción en este momento. Por favor intente de nuevo y si el problema persiste Comuníquese con servicio al cliente.'
));
}
if(isset($response->responseCode))
{
if(strlen($response->responseText[0]) == 1)
{
$text = $response->responseText;
} else {
$text = $response->responseText[0];
}
$paymentObj = new Payment();
$paymentObj->setLast4Tdc(substr($cleanNumber,13,16));
$paymentObj->setResult($response->result);
$paymentObj->setTitle($response->title);
$paymentObj->setCustomAuthCode($dummyOrderId);
$paymentObj->setResponseCode($response->responseCode);
$paymentObj->setResponseText($response->responseText);
$paymentObj->setResponseObject(json_encode($response));
if($request->get('paymentMode') == 'token')
{
$paymentObj->setResponseAuthorization($response->responseAutorization);
$paymentObj->setIdTransaction($response->transactionId);
} else {
$paymentObj->setResponseAuthorization($response->responseAuthorization);
$paymentObj->setIdTransaction($response->idTransaction);
}
$paymentObj->setAmount($grandTotal);
$paymentObj->setRequest(json_encode($parameters));
$paymentObj->setCreatedAt(new \DateTime());
$paymentObj->setClient($clientObj);
$em->persist($paymentObj);
$em->flush();
if($response->responseCode == '100')
{
return new JsonResponse(array(
'status' => 'success',
'data' => $response,
'dummyOrderId' => $dummyOrderId,
'msg' => 'Pago recibido correctamente, estamos procesando en este momento la orden'
));
} else {
return new JsonResponse(array(
'status' => 'error',
'data' => $response,
'dummyOrderId' => $dummyOrderId,
'msg' => $text
));
}
}
//Termina qpay_pro
}
}
}
return new JsonResponse(array(
'status' => 'error',
'msg' => 'No fue posible comunicarse con la pasarela de Pago. Por favor utilice otro método de pago para continuar'
));
}
/**
*
* @Route("{slug}/checkout_fields", name="frontend_checkout_fields")
*/
public function checkoutFieldsAction(Request $request, $slug)
{
$clientIdNum = $this->getParameter('client_id');
$lastUsername = $request->getSession()->get(Security::LAST_USERNAME);
$userData = false;
if($lastUsername)
{
$userData = $request->getSession()->get($lastUsername);
}
$client = $this->getDoctrine()->getRepository(\App\Entity\Client::class)->findOneBy(array(
"clientId" => $clientIdNum
));
$settings = $this->getDoctrine()->getRepository(\App\Entity\Setting::class)->findOneBy(array(
"Client" => $client
));
//VERIFICAMOS HORARIOS
$store_status = 'open';
$message_closed = "";
$day_number = date('N');
$hoursToday = $this->getDoctrine()->getRepository(\App\Entity\Setting::class)->verifyHoursForToday($day_number, $clientIdNum);
if($hoursToday['is_open'] == '0')
{
$store_status = 'closed';
$information = $this->getDoctrine()->getRepository(\App\Entity\Client::class)->findOneBy(array(
"clientId" => $clientIdNum
));
$message_closed = $information->getClosedNotice();
}
$type = "";
if($request->get('direct_field_id'))
{
# REEMPLAZO DE TIENDA CERRADA
//Si tiene un horario configurado para este dia, entonces se reemplaza
if($store_status == 'open')
{
$cartField = $request->get('direct_field_id');
}else{
$cartField = $settings->getClosedDirectFieldList()->getFieldListId();
}
$type= "direct";
} else {
# REEMPLAZO DE TIENDA CERRADA
//Si tiene un horario configurado para este dia, entonces se reemplaza
//obtenemos el día actual
if($store_status == 'open')
{
$cartField = $settings->getCartFieldList()->getFieldListId();
} else {
$cartField = $settings->getClosedCartFieldList()->getFieldListId();
}
$type="cart";
}
if(true)
{
$array = $this->getDoctrine()->getRepository(\App\Entity\FieldList::class)->getFieldsById($cartField,$clientIdNum);
} else {
//Si no tiene campos el formulario que deberia de ser, mandamos el formulario por defecto.
$array = $this->getDoctrine()->getRepository(\App\Entity\FieldList::class)->getFieldsById(0,$clientIdNum);
}
$finalArray = array();
foreach($array as $item)
{
$merged = $item;
if($item['field_type_id'] == 4)
{
$polygons = $this->getDoctrine()->getRepository(\App\Entity\FieldList::class)->getPolygonsForFieldClient($item['field_client_id']);
if($polygons)
{
$polArray = array();
foreach($polygons as $pols)
{
$polArray[] = $pols;
}
$merged = array_merge($item, array('polygons'=>$polArray));
}
}
$finalArray[] = $merged;
}
/*echo "<pre>";
print_r($merged);
echo "</pre>"; */
/*return new JsonResponse(array(
'status' => 'success',
'result' => $array,
'store_status' => $store_status
));*/
$customerLocation = '';
if($userData)
{
if($userData['customer_id'])
{
$customerLocation = $this->getDoctrine()->getRepository(\App\Entity\CustomerLocation::class)->findOneBy([
"Customer" => $userData['customer_id']
]);
}
}
return $this->render('Frontend/Checkout/checkout_fields.html.twig', array(
'status' => 'success',
'result' => $finalArray,
'slug' => $slug,
'userData' => $userData,
'store_status' => $store_status,
'message_closed' => $message_closed,
'customerLocation' => $customerLocation,
'type' => $type
));
}
/**
*
* @Route("{slug}/checkout_table", name="frontend_checkout_table")
*/
public function checkoutTableAction(Request $request, $slug)
{
$cart = json_decode($this->get("session")->get("cart"));
$cartArray = array();
$grandTotal = 0;
$information = $this->getDoctrine()->getRepository(\App\Entity\Client::class)->findOneBy([
"slug" => $slug
]);
$client_id = $information->getClientId();
//Obtenemos simbolo de moneda a utilizar
$symbol = $information->getCurrency()->getCurrencySymbol();
if(count($cart) > 0)
{
foreach($cart as $item)
{
$productObj = $this->getDoctrine()->getRepository(\App\Entity\Product::class)->findOneBy(array(
'productId' => $item->pid
));
$productInventory = $this->getDoctrine()->getRepository(\App\Entity\Product::class)->getInventoryProduct($item->pid);
$stock = 0;
if($productInventory){
if($productInventory['available'] != ''){
$stock = $productInventory['available'];
}
if($productInventory['is_not_stock'] == '1'){
$stock = 'not_stock';
}
}
$cleanPrice = preg_replace("/[^0-9.]/","",$item->price);
$cleanPrice = ltrim($cleanPrice,".");
$cleanPrice = sprintf('%0.2f',$cleanPrice);
$subtotal = ($item->quantity * $cleanPrice);
$itemArray = [
'product' => [
"name" => $item->name,
"product_id" => $item->pid,
"offer_name" => $item->o_name,
"offer_id" => $item->oid,
"clean_price" => $cleanPrice,
"stock" => $stock,
'subtotal' => number_format($subtotal, 2, '.', ','),
'image' => $productObj->getMainPicture(),
],
"quantity" => $item->quantity,
"symbol" => $symbol,
'service_fee' => $information->getServiceFee()
];
$grandTotal += $subtotal;
$cartArray[] = $itemArray;
}
}
$coupon = '';
$grandTotalFinal = $grandTotal;
$discount = 0;
if($this->get("session")->get("coupon") && $this->get("session")->get("coupon") != '')
{
$coupon_id = $this->get("session")->get("coupon");
$coupon = $this->getDoctrine()->getRepository(\App\Entity\Coupon::class)->findOneBy(array(
'couponId' => $coupon_id
));
$discount_percent = $coupon->getDiscountPercent();
$discount = ($grandTotal*$discount_percent)/100;
$grandTotalFinal = $grandTotal - $discount;
}
//SE APLICA EL SERVICE FEE
if($information->getServiceFee() && $information->getServiceFee() > 0)
{
$grandTotalFinal = $grandTotalFinal + $information->getServiceFee();
}
return $this->render('Frontend/Checkout/checkout_table.html.twig', array(
'productCategory' => '',
'pager_limit' => 12,
'globalSearch' => '',
'slug' => $slug,
'cart' => $cartArray,
'coupon' => $coupon,
'subTotal' => number_format($grandTotal, 2, '.', ','),
'discount' => number_format($discount, 2, '.', ','),
'grandTotal' => number_format($grandTotalFinal, 2, '.', ','),
'symbol' => $symbol,
'service_fee' => $information->getServiceFee()
));
}
/**
* @Route("{slug}/checkout_refresh_cart", name="frontend_checkout_refresh_cart")
*/
public function checkoutRefreshCartAction(Request $request, $slug) {
$response = $this->refreshCart($slug);
return new JsonResponse($response);
}
public function refreshCart($slug)
{
$information = $this->getDoctrine()->getRepository(\App\Entity\Client::class)->findOneBy(array(
"slug" => $slug
));
if(!$information)
{
//@TODO hacer algo si no se detecta
}
$client_id = $information->getClientId();
//Obtenemos simbolo de moneda a utilizar
$symbol = $information->getCurrency()->getCurrencySymbol();
$currentCart = json_decode($this->get("session")->get("cart"));
if(is_array($currentCart))
{
if (count($currentCart) == 0) {
$currentCart = array();
}
}
$val = 0;
$priceVal = 0;
if (is_array($currentCart)) {
$currentCarts = $currentCart;
} else {
$currentCarts = json_decode($currentCart);
}
//Cadena para gateway de pago
$QPayPro = "";
//-------------------------
if(is_array($currentCarts))
{
foreach($currentCarts as $cartTemp)
{
$val += $cartTemp->quantity;
$priceVal += $cartTemp->price * $cartTemp->quantity;
//Cadenas para gateway de pago
$QPayPro .= $cartTemp->name."<|>".$cartTemp->pid."<|>".$cartTemp->quantity."<|>".$cartTemp->price."<|>N";
}
}
$coupon = '';
$grandTotalFinal = $priceVal;
$discount = 0;
if($grandTotalFinal > 0 ){
if($this->get("session")->get("coupon") && $this->get("session")->get("coupon") != ''){
$coupon_id = $this->get("session")->get("coupon");
$coupon = $this->getDoctrine()->getRepository(\App\Entity\Coupon::class)->findOneBy(array(
'couponId' => $coupon_id
));
$discount_percent = $coupon->getDiscountPercent();
$discount = ($priceVal*$discount_percent)/100;
$grandTotalFinal = $priceVal - $discount;
$grandTotalFinal= number_format($grandTotalFinal, 2, '.', ',');
}
}else{
$grandTotalFinal = '';
}
$url = $this->generateUrl('frontend_checkout', ['slug' => $slug]);
$html = "<div id='cart_main' rel='popover' class='icon-header-item cl2 hov-cl1 trans-04 p-l-22 p-r-11 icon-header-noti js-show-cart' onclick='window.location.href=\"$url\"' data-notify='$val'>
<i class='zmdi zmdi-shopping-cart'></i>$symbol$grandTotalFinal
<small class='cart_bottom_legend'>Clic aquí para terminar</small>
</div>";
$response = array(
'quantity' => $val,
'price' => $grandTotalFinal,
'cart' => $currentCarts,
'html' => $html,
'qpay_pro' => $QPayPro
);
return $response;
}
/**
* @Route("{slug}/checkout/verify-coupon", name="frontend_checkout_verify_coupon")
*/
public function checkoutVerifyCouponAction(Request $request, $slug)
{
$userData = $this->get("session")->get("userData");
$client = $this->getDoctrine()->getRepository(\App\Entity\Client::class)->findOneBy(array(
"slug" => $slug
));
$client_id = $client->getClientId();
if(!$client)
{
return new JsonResponse(array(
'status' => 'error',
'isValid' => 0,
'msg' => "No se puede validar el cupón en este momento",
'coupon' => ""
));
}
$setting = $this->getDoctrine()->getRepository(\App\Entity\Setting::class)->findOneBy(array(
"Client" => $client
));
$customerId = '';
if($userData)
{
$customerId = $userData['customer_id'];
}
$coupon = $request->get('coupon');
//VERIFICAMOS EXISTENCIA DEL CUPÓN
$couponExist = $this->getDoctrine()->getRepository(\App\Entity\Coupon::class)->verifyCoupon($coupon,$customerId, $client_id);
$isValid = false;
$msg = "El cupón no es valido";
$this->get("session")->set("coupon", '');
if($couponExist)
{
if($userData)
{
if($couponExist['customer_id'] != '' && $couponExist['customer_id'] != $userData['customer_id'])
{
$isValid = false;
$msg = "El cupón ingresado no es válido";
}else{
$isValid = true;
}
}else{
if($couponExist['customer_id'] == '')
{
$isValid = true;
}
}
//Verificamos productos ofertados
if($isValid && $setting->getCartAllowCouponWhithOffers() == '0')
{
$currentCart = $this->get("session")->get("cart");
$cartList = json_decode($currentCart);
if(count($cartList) > 0)
{
foreach($cartList as $cart)
{
if($cart->oid != ''){
$isValid = false;
$msg = "No es posible utilizar el cúpon con productos ofertados";
break;
}
}
}
}
if($isValid){
$this->get("session")->set("coupon", $couponExist['coupon_id']);
}
}
return new JsonResponse(array(
'status' => 'success',
'isValid' => $isValid,
'msg' => $msg,
'coupon' => $this->get("session")->get("coupon")
));
}
/**
* @Route("{slug}/checkout/distance-info", name="frontend_checkout_distance_info")
*/
public function distanceInfoAction(Request $request, DistanceHelper $distanceHelper, $slug)
{
$client = $this->getDoctrine()->getRepository(\App\Entity\Client::class)->findOneBy(array(
"slug" => $slug
));
$client_id = $client->getClientId();
$variable = $this->getDoctrine()->getRepository(\App\Entity\DeliveryVariable::class)->findOneBy(array(
"Client" => $client_id
));
$response = "";
if($variable)
{
$latTo = $request->get('latTo');
$lngTo = $request->get('lngTo');
if($latTo != "" && $lngTo != "")
{
$dummyLat = $variable->getOriginLat();
$dummyLng = $variable->getOriginLng();
$distanceHelper = new DistanceHelper();
$response = $distanceHelper->getDistanceInfo($dummyLat, $dummyLng, $latTo, $lngTo, $variable->getUseGoogle(), $variable->getApiKey());
if($response)
{
if(strlen($response['distance']) > 0)
{
$rangeFound = $this->getDoctrine()->getRepository(\App\Entity\DeliveryRange::class)->findRangePrice($response['distance'], $client_id);
if($rangeFound)
{
if($rangeFound['is_free'] == 1)
{
$finalPrice = 'FREE';
} else {
$finalPrice = $rangeFound['price'];
}
return new JsonResponse(array(
'status' => 'success',
'delivery_price' => $finalPrice,
'data' => $response
));
}
}
}
return new JsonResponse(array(
'status' => 'error',
'delivery_price' => '',
'data' => $response
));
}
}
return new JsonResponse(array(
'status' => 'success',
'delivery_price' => '',
'data' => ''
));
}
/**
* @Route("/checkout/quit-coupon", name="frontend_checkout_quit_coupon")
*/
public function checkoutQuitCouponAction(Request $request)
{
$this->get("session")->set("coupon",'');
return new JsonResponse(array(
'status' => 'success'
));
}
/**
* @Route("/{slug}", name="frontend_index", requirements={"slug"="^(?!(login|backend|logout)(/|$)).*"}))
*/
public function indexAction(Request $request, $slug)
{
$em = $this->getDoctrine()->getManager();
//$client_id = $this->getParameter('client_id');
$productCategory = "";
$pager_limit = 12;
$globalSearch = "";
//$client = $this->getDoctrine()->getRepository(Client::class)->findBy(array("clientId" => $client_id));
$client = $this->getDoctrine()->getRepository(Client::class)->findOneBy(array("slug" => $slug));
if(!$client)
{
return $this->redirectToRoute("homepage_website");
}
$client_id = $client->getClientId();
$slides = $this->getDoctrine()->getRepository(WebSlide::class)->findBy(array("Client" => $client, "is_active" => 1));
$webSetting = $this->getDoctrine()->getRepository(WebSetting::class)->findOneBy(array("Client" => $client));
$brands = $em->getRepository(Brand::class)->getBrands($client_id);
$categories = $em->getRepository(Category::class)->getCategories($client_id);
$subcategories = $em->getRepository(Subcategory::class)->findBy(array('is_active' => 1, 'Client'=> $client));
$blogs = $em->getRepository(Blog::class)->findBy(array('is_active' => 1, 'is_published' => 1, 'featured'=> 1, 'Client' => $client));
// replace this example code with whatever you need
return $this->render('Frontend/Index/index.html.twig', array(
'productCategory' => $productCategory,
'pager_limit' => $pager_limit,
'globalSearch' => $globalSearch,
'slides' => $slides,
'categories' => $categories,
'brands' => $brands,
'blogs' => $blogs,
'slug' => $slug,
'subcategories' => $subcategories,
'webSetting' => $webSetting,
'brand' => '',
'category' => ''
));
}
}