<?php
namespace App\Controller;
use App\Entity\Cart;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Routing\Annotation\Route;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\HttpFoundation\Request;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Entity;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Security;
use App\Entity\Company;
use App\Entity\CompanyAssociation;
use App\Entity\CompanyDeposit;
use App\Entity\Product;
use App\Entity\ProductAdjustment;
use App\Entity\Variable;
use App\Service\UserService;
use App\Service\ProductService;
use App\Service\ImageService;
use App\Service\CompanyService;
use App\Service\DistributorService;
use App\Service\PaymentService;
use App\Service\VariableService;
use Sonata\AdminBundle\Form\Type\Filter\NumberType;
use Symfony\Component\Form\Extension\Core\Type\MoneyType;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\HttpFoundation\Response;
class CompanyAssociationController extends AbstractController
{
/**
* @Route("/brome-missisquoi")
*
* @Template("frontend/associations.html.twig")
*
*/
public function tmpBromeRedirect(EntityManagerInterface $entityManager, UserService $userServ){
// get Brome Missiquoi Association
$association = $entityManager->getRepository(CompanyAssociation::class)->find(3);
return $this->redirectToRoute('companyAssociationList', [
'urlName' => $association->getUrlName(),
'city' => null,
]);
}
/**
* @Route(
* "/groupe/{urlName}/{city}",
* defaults={
* "urlName" = null,
* "city" = null,
* },
* name="companyAssociationList",
* )
* @Template("frontend/associations.html.twig")
*/
public function companyAssociationList(CompanyAssociation $association= null, $city=null, EntityManagerInterface $em, UserService $userServ)
{
$twigData = array();
$twigData['title']= 'Les associations';
$twigData['association'] = $association->getUrlName();
if($association){
//We set a var for 2h to stay in this branch
$userServ->setAssociationUserIsBrowsing($association->getId());
$twigData['title']= $association->getName();
if($association->getBanner())
$twigData['logoPage']= $association->getBanner();
if($association->getDescription())
$twigData['pageText'] = $association->getDescription();
$twigData['companies']= $em->getRepository(Company::class)->findByAssociationOrderedByCity($association, urldecode($city));
$twigData['inCity'] = $city;
foreach ($twigData['companies'] as $company) {
$city = $company->getMainLocation()->getCity();
//echo $city;
if (!isset($twigData['cities'][$city])) {
$twigData['cities'][$city] = $city;
}
}
# if not cities, probably because, no company found , use empty city array
if(!isset($twigData['cities'])){
$twigData['cities'] = [];
}
}else{
$twigData['companies']=
$em
->getRepository(Company::class)
->findWithAssociation();
}
return $twigData;
}
/**
* @Route("/user/removeAssociation", name="removeAssociationFromBrowsing");
*/
public function removeAssociation(USerService $userServ, Request $request)
{
// remove user's association variable
$userServ->delVariable('showThisAssociationIdOnly', 'customBrowsing');
// redirect to home if user is browsing an association page
$referer = $request->headers->get('referer');
if (strpos($request->headers->get('referer'), 'groupe') !== false){
//$companyAssociation = explode('/', explode('/groupe/', $referer)[1])[0];
//$referer = str_replace('/groupe/'.$companyAssociation, '', $referer);
return $this->redirectToRoute('home');
}
// else redirect to current page (like cart or profile)
return $this->redirect($referer);
}
/**
* @Route({
* "fr": "/vendeur/association/ajax_remove_company",
* "en": "/seller/association/ajax_remove_company"
* },
* name="associationProfileConfigAJAXRemoveCompany"
* )
* @Security("has_role('ROLE_ADMIN')")
*/
public function associationProfileConfigAJAXRemoveCompany(UserService $userServ, Request $request, EntityManagerInterface $em) {
$association_id = $request->get("association_id");
$company_id = $request->get("company_id");
$company = $em->getRepository(Company::class)->findOneBy(["id"=>$company_id]);
$association = $em->getRepository(CompanyAssociation::class)->findOneBy(["id"=>$association_id]);
$association->removeCompany($company);
$em->persist($association);
$em->flush();
die(json_encode(["results"=>"OK"]));
}
/**
* @Route({
* "fr": "/vendeur/association/ajax_add_company",
* "en": "/seller/association/ajax_add_company"
* },
* name="associationProfileConfigAJAXAddCompany"
* )
* @Security("has_role('ROLE_ADMIN')")
*/
public function associationProfileConfigAJAXAddCompany(UserService $userServ, Request $request, EntityManagerInterface $em) {
$association_id = $request->get("association_id");
$company_id = $request->get("company_id");
$company = $em->getRepository(Company::class)->findOneBy(["id"=>$company_id]);
$association = $em->getRepository(CompanyAssociation::class)->findOneBy(["id"=>$association_id]);
$association->addCompany($company);
$em->persist($association);
$em->flush();
die(json_encode(["results"=>"OK"]));
}
/**
* @Route({
* "fr": "/vendeur/association/ajax_search",
* "en": "/seller/association/ajax_search"
* },
* name="associationProfileConfigAJAXSearch"
* )
* @Security("has_role('ROLE_ADMIN')")
*/
public function associationProfileConfigAJAXSearch(UserService $userServ, Request $request, EntityManagerInterface $em) {
$search_query = $request->get("term");
$search_query = "%".str_replace(" ", "%", trim($search_query))."%";
$user = $userServ->getUser();
$search_results = $em->getRepository(Company::class)->searchByName($search_query, $user);
$results = [];
foreach($search_results as $result) {
$results[] = ["id"=>$result->getId(), "text"=>$result->getName()];
}
die(json_encode(["results"=>$results]));
}
/**
* @Route({
* "fr": "/vendeur/association/editer",
* "en": "/seller/association/edit"
* },
* name="associationProfileConfiguration"
* )
* @Security("has_role('ROLE_ADMIN')")
* @Template("admin/company/association.profile.html.twig")
*/
public function associationProfileConfiguration(UserService $userServ, Request $request, EntityManagerInterface $em, CompanyService $companyServ, ImageService $imageServ){
$twigData = array();
$twigData['company'] = $userServ->getUser()->getMakeCompanyForAssociation();
$action = $request->get('action');
if ($action == "update_profile") {
$company = $request->get('company');
$banner = $request->files->get('company')['banner'];
$image = $request->files->get('company')['logo'];
$CA = $em->getRepository(CompanyAssociation::class)->findOneBy(["id"=>$twigData['company']->getId()]);
$CA->setName($company["name"]);
$CA->setDescription($company["description"]);
if(!empty($image)) {
$imgImage = $imageServ->saveUploadedFile($image, 'company_association', false);
if($imgImage) {
$CA->setLogo($imgImage);
} else {
$CA->setLogo('reset');
}
}
if(!empty($banner)) {
$imgBanner = $imageServ->saveUploadedFile($banner, 'company_association_banner', false);
if($imgBanner) {
$CA->setBanner($imgBanner);
} else {
$CA->setBanner('reset');
}
}
$em->persist($CA);
$em->flush();
$twigData['company'] = $CA;
}
return $twigData;
}
/**
* @Route({
* "fr": "/vendeur/variableAssociation/liste",
* "en": "/seller/variableAssociation/list"
* },
* name="associationVariableList"
* )
* @Security("has_role('ROLE_ADMIN')")
* @Template("admin/company/listVariables.html.twig")
*/
public function associationVariableList(UserService $userServ, Request $request, EntityManagerInterface $em, CompanyService $companyServ, VariableService $variableServ){
if(empty($userServ->getUser()->getMakeCompanyForAssociation())){
$this->addFlash('error', "Vous n'avez pas d'association");
return $this->redirectToRoute('dashboard');
}
$twigData = array();
$twigData['company'] = $userServ->getUser()->getMakeCompanyForAssociation();
$twigData['title'] = "Vos paramètres d'association";
$twigData['schedule_available_hours'] = [
'00h00',
'00h30',
'01h00',
'01h30',
'02h00',
'02h30',
'03h00',
'03h30',
'04h00',
'04h30',
'05h00',
'05h30',
'06h00',
'06h30',
'07h00',
'07h30',
'08h00',
'08h30',
'09h00',
'09h30',
'10h00',
'10h30',
'11h00',
'11h30',
'12h00',
'12h30',
'13h00',
'13h30',
'14h00',
'14h30',
'15h00',
'15h30',
'16h00',
'16h30',
'17h00',
'17h30',
'18h00',
'18h30',
'19h00',
'19h30',
'20h00',
'20h30',
'21h00',
'21h30',
'22h00',
'22h30',
'23h00',
'23h30',
];
$twigData['schedule_available_days'] = [
1 => 'Lundi',
2 => 'Mardi',
3 => 'Mercredi',
4 => 'Jeudi',
5 => 'Vendredi',
6 => 'Samedi',
7 => 'Dimanche',
];
$variables = [
'orders.canPackUp' => '0',
'orders.canPickUp' => '0',
'orders.pickUpSchedule' => [],
'orders.pickUpScheduleTimes' => [],
'orders.pickUpScheduleDurations' => [],
'orders.pickUpScheduleSlotLimits' => [],
'orders.pickUpScheduleDaysChecked' => [],
'orders.pickUpAdress' => '',
'orders.prepareDelay' => '0',
'orders.packingFixedFee' => '0',
];
$action = $request->get('action');
if ($action == "save_variables") {
$orders_packingFixedFee = $request->get('orders_packingFixedFee');
$em->getRepository(Variable::class)->saveVariableForAsso(
$twigData['company'],
'Frais fixe de montage d\'une commande (cueillette)',
'orders.packingFixedFee',
$orders_packingFixedFee
);
$orders_prepareDelay = $request->get('orders_prepareDelay');
$em->getRepository(Variable::class)->saveVariableForAsso(
$twigData['company'],
'Delais de preparation d\'une commande en jours',
'orders.prepareDelay',
$orders_prepareDelay
);
$orders_canPickUp = $request->get('orders_canPickUp');
$em->getRepository(Variable::class)->saveVariableForAsso(
$twigData['company'],
'Ramassage possible',
'orders.canPickUp',
$orders_canPickUp
);
$orders_canPackUp = $request->get('orders_canPackUp');
$em->getRepository(Variable::class)->saveVariableForAsso(
$twigData['company'],
'Option de montage des commandes',
'orders.canPackUp',
$orders_canPackUp
);
$orders_pickUpAdress = $request->get('orders_pickUpAdress');
$em->getRepository(Variable::class)->saveVariableForAsso(
$twigData['company'],
'Adresse de ramassage',
'orders.pickUpAdress',
$orders_pickUpAdress
);
$orders_pickUpSchedule = $request->get('orders_pickUpSchedule');
$orders_pickUpScheduleDaysChecked = $request->get('orders_pickUpScheduleDaysChecked');
$orders_pickUpScheduleDuration = $request->get('orders_pickUpScheduleDuration');
$orders_pickUpScheduleSlotLimits = $request->get('orders_pickUpScheduleSlotLimits');
$pickUpSchedule = [];
$pickUpScheduleDurations = [];
$pickUpScheduleSlotLimits = [];
foreach($twigData['schedule_available_days'] as $day_idx => $day_name) {
if (isset($orders_pickUpScheduleDaysChecked[$day_idx])) {
if ($orders_pickUpScheduleDaysChecked[$day_idx] == "on") {
$pickUpSchedule[$day_idx] = [];
$time_start = strtotime(date("Y-m-d ").str_replace("h", ":", $orders_pickUpSchedule[$day_idx][0]));
$time_stop = strtotime(date("Y-m-d ").str_replace("h", ":", $orders_pickUpSchedule[$day_idx][1]));
$minutes = 30;
if ($orders_pickUpScheduleDuration[$day_idx] == "30") {
$minutes = 30;
}
if ($orders_pickUpScheduleDuration[$day_idx] == "60") {
$minutes = 60;
}
$pickUpScheduleDurations[$day_idx] = $minutes;
$pickUpScheduleSlotLimits[$day_idx] = $orders_pickUpScheduleSlotLimits[$day_idx];
$current_time_start = $time_start;
while ( true ) {
$current_time_stop = $current_time_start + ( $minutes * 60 );
$pickUpSchedule[$day_idx][] = [date("H\hi", $current_time_start), date("H\hi", $current_time_stop)];
if ( $current_time_stop >= $time_stop ) {
break;
}
$current_time_start = $current_time_start + ( $minutes * 60 );
}
}
}
}
$pickUpSchedule = json_encode($pickUpSchedule);
$em->getRepository(Variable::class)->saveVariableForAsso(
$twigData['company'],
'Horaire de ramassage',
'orders.pickUpSchedule',
$pickUpSchedule
);
$pickUpScheduleDurations = json_encode($pickUpScheduleDurations);
$em->getRepository(Variable::class)->saveVariableForAsso(
$twigData['company'],
'Durée des plages horaires',
'orders.pickUpScheduleDurations',
$pickUpScheduleDurations
);
$pickUpScheduleSlotLimits = json_encode($pickUpScheduleSlotLimits);
$em->getRepository(Variable::class)->saveVariableForAsso(
$twigData['company'],
'Limite de personnes des plages horaires',
'orders.pickUpScheduleSlotLimits',
$pickUpScheduleSlotLimits
);
$this->addFlash('success', "Vos paramètres on été mise à jour");
}
$company_variables = $twigData["company"]->getVariables();
foreach($company_variables as $company_variable) {
$codeName = $company_variable->getCodeName();
if (isset($variables[$codeName])) {
$variables[$codeName] = $company_variable->getValue();
if (
$codeName == "orders.pickUpSchedule" ||
$codeName == "orders.pickUpScheduleDurations" ||
$codeName == "orders.pickUpScheduleSlotLimits"
) {
$variables[$codeName] = json_decode($variables[$codeName], true);
}
}
}
/* set default values */
foreach($twigData['schedule_available_days'] as $x => $day) {
if (!isset($variables["orders.pickUpSchedule"][$x])) {
$variables["orders.pickUpScheduleTimes"][$x]["time_start"] = "00h00";
$variables["orders.pickUpScheduleTimes"][$x]["time_stop"] = "00h00";
$variables["orders.pickUpScheduleDaysChecked"][$x] = false;
} else {
$variables["orders.pickUpScheduleDaysChecked"][$x] = true;
$time_start = "23h59";
$time_stop = "00h00";
foreach($variables["orders.pickUpSchedule"][$x] as $times) {
if ($times[0] < $time_start) {
$time_start = $times[0];
}
if ($times[1] > $time_stop) {
$time_stop = $times[1];
}
}
$variables["orders.pickUpScheduleTimes"][$x]["time_start"] = $time_start;
$variables["orders.pickUpScheduleTimes"][$x]["time_stop"] = $time_stop;
}
}
$twigData["variables"] = $variables;
return $twigData;
}
/**
* @route({
* "fr": "/association/produits/liste/{id}",
* "en": "/groupe/product/list/{id}"
* },
* defaults = {
* "id" = false
* },
* options = { "expose" = true },
* name="adminCompanyGroupProductList")
* @Template("admin/product/companyGroupProductList.html.twig")
*/
public function listAssociationProducts(ProductService $ProductService, EntityManagerInterface $em, CompanyAssociation $association=null, DistributorService $distributorServ, UserService $userServ){
$twigData = array();
if(empty($association)){
$user = $userServ->getUser();
$association = $user->getMakeCompanyForAssociation();
/*
if(count($companyAssociation) > 1){
$this->addFlash('error', "Vous avez plusieur boutiques, pour accéder a l'inventaire via le menu");
return $this->redirectToRoute('dashboard');
}else{
$company = $companies->get(0);
}
*/
}
//@SECuritY
if($this->getUser()->getMakeCompanyForAssociation()->getId() != $association->getId()
&& !($this->getUser()->isGranted('ROLE_ADMIN_MATURIN') && !$this->getUser()->isGranted('ROLE_SUPER_ADMIN'))
){
$this->addFlash('error', "Vous n'avez pas d'accès à cette boutique, veuillez utiliser le menu");
return $this->redirectToRoute('dashboard');
}
/*
* Conflict with the cart, when a sale occur the quantity change
* If the producer check the list of product when a order was done but not shipped yet
* The quantity will reset to the one in Inventory which can make a "sale" happen
* as quantity is available again
*/
$twigData['products'] = $em->getRepository(Product::class)
->findAllAssociationProducts($association->getId());
$twigData['association']=$association;
return $twigData;
}
/**
* @Route({
* "fr": "/association/commandes/liste/{id}",
* "en": "/sellerGroup/orders/list/{id}",
* },
* defaults={
* "id" = false
* },
* name="companyGroupOrders")
*
* @Security("has_role('ROLE_ADMIN')")
* @Template("admin/companyGroup/ordersList.html.twig")
*/
public function companyGroupOrders(CompanyAssociation $association=null, EntityManagerInterface $em, UserService $userServ, Request $request){
$twigData = array();
if(empty($association)){
$user = $userServ->getUser();
$association = $user->getMakeCompanyForAssociation();
}
//@SECuritY
if($this->getUser()->getMakeCompanyForAssociation()->getId() != $association->getId()
&& !($this->getUser()->isGranted('ROLE_ADMIN_MATURIN') && !$this->getUser()->isGranted('ROLE_SUPER_ADMIN'))
){
$this->addFlash('error', "Vous n'avez pas d'accès à cette association, veuillez utiliser le menu");
return $this->redirectToRoute('dashboard');
}
if ($request->getMethod() == 'POST'){
$orderId = (int)$request->request->get('orderId');
$cart = $em->getRepository(Cart::class)->find($orderId);
$adjustments = [];
$orderHasBeenModified=false;
foreach ($cart->getProducts() as $cp){
// check if cart product quantity is in request
$cpId = $cp->getId();
if ($request->request->has($cpId)){
$qtConfirmed = (int)$request->request->get($cpId);
// check if confirmed quantity is different from original quntity
if ($qtConfirmed != $cp->getFinalQuantity()) {
// remove BOs if quantity confirmed is order initial quantity
// if ($qtConfirmed == $cp->getQuantity()){
// foreach ($cp->getProductAdjustments() as $pa){
// $em->remove($pa);
// $orderHasBeenModified = true;
// }
// continue;
// }
// create new adjustment
$pa = new ProductAdjustment();
$pa->setQuantity($qtConfirmed-$cp->getFinalQuantity());
$em->persist($pa);
// link adjustment
$cp->addProductAdjustment($pa);
$adjustments []= $cp;
}
if ($qtConfirmed > 0){
$cp->setIsShipped(true);
}
$em->persist($cp);
};
}
foreach ($cart->getCustomOrders() as $co){
$shipped = true;
foreach ($co->getItems() as $cp){
if (!$cp->getIsShipped()){
$shipped = false;
break;
}
}
$co->setIsShipped($shipped);
$em->persist($co);
}
// apply changes
$em->flush();
if(count($adjustments) > 0){
$emailSubject = 'Produits en rupture de stock sur votre commande '.$cart->getOrderNo();
$emailBody = $this->get('twig')->render('emails/back-order.html.twig', [
'cart' => $cart,
'user' => $cart->getUser(),
'cartProducts' => $adjustments
]);
$destAddress = $cart->getUser()->getEmail();
$userServ->sendEmail($emailSubject, $emailBody, false, $destAddress, null, true);
$this->addFlash('success', 'Commande '.$cart->getOrderNo().' validée !');
return $this->redirectToRoute('companyGroupOrders', [
'id' => $association->getId()
]);
}
}
$twigData['orders'] = $em->getRepository(Cart::class)
->getCompanyAssociationOrdersQuery($association)
->getResult();
return $twigData;
}
/**
* @Route({
* "fr": "/associat/{id}",
* "en": "/seller/{id}",
* },
* defaults={
* "id" = false
* },
* name="associat")
*
* @Security ("has_role('ROLE_ADMIN')")
*
*/
public function associatAjax(UserService $userServ, Request $request, EntityManagerInterface $em,CompanyAssociation $association=null)
{
die();
}
}