<?php
namespace App\Controller;
use App\Entity\CompanyAssociation;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\HttpFoundation\Request;
use Doctrine\ORM\EntityManagerInterface;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Entity;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Security;
use Symfony\Component\HttpFoundation\File\UploadedFile;
use Symfony\Component\HttpFoundation\File\File;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\Routing\Exception\ResourceNotFoundException;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use FOS\UserBundle\Model\UserManagerInterface;
use FOS\UserBundle\Util\TokenGeneratorInterface;
use FOS\UserBundle\Mailer\MailerInterface;
//Form element
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\Extension\Core\Type\TextareaType;
use Symfony\Component\Form\Extension\Core\Type\DateType;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\Form\Extension\Core\Type\CheckboxType;
use Symfony\Component\Form\Extension\Core\Type\NumberType;
use Symfony\Component\Form\Extension\Core\Type\MoneyType;
use Symfony\Component\Form\Extension\Core\Type\EmailType;
use Symfony\Component\Form\Extension\Core\Type\PasswordType;
use Symfony\Component\Form\Extension\Core\Type\RepeatedType;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use App\Form\CompanyType;
use App\Form\CompanyDepositType;
use App\Form\CompanyPaymentType;
use App\Form\CompanyDefaultShippingType;
use App\Form\CompanySubscriptionType;
use App\Form\CompanyLocationType;
use App\Form\UserType;
use App\Service\UserService;
use App\Service\ProductService;
use App\Service\ImageService;
use App\Service\CompanyService;
use App\Service\PaymentService;
use App\Service\VariableService;
use App\Entity\User;
use App\Entity\Product;
use App\Entity\CartProduct;
use App\Entity\Company;
use App\Entity\Category;
use App\Entity\CompanyPayment;
use App\Entity\CompanyDefaultShipping;
use App\Entity\CompanyLocation;
use App\Entity\CompanySubscription;
use App\Entity\CompanyDeposit;
use App\Entity\CustomOrder;
use App\Entity\FinancialLog;
use App\Entity\UserViewedProduct;
use App\Entity\Variable;
use App\Service\StripeService;
class CompanyController extends AbstractController
{
private $imageServ;
function __construct(ImageService $imageServ){
$this->imageServ = $imageServ;
}
function createFastCompanyForm($data = false){
if(!$data)
$data = ['message' => 'Type your message here'];
$form = $this->createFormBuilder($data)
->add('user', UserType::class, [
'label' => false
])
->add('company', CompanyType::class, [
'label' => false
])
->add('payment', CompanyPaymentType::class, [
'label' => false
])
->add('subscription', CompanySubscriptionType::class, [
'label' => false
])
->add('storeMadeByMaturin', ChoiceType::class, array(
'required' => true,
'placeholder' => 'Choisir...',
'choices' => array(
'Oui, faites le montage pour nous' => true,
'Non, nous ferons le montage nous-même' => false
)
))
->add('submit', SubmitType::Class,
array(
'label' => 'Enregistrer',
'attr' => [
'class' => 'pull-right'
]
)
)
;
$form->get('user')
->remove('displayName')
->remove('phone')
->remove('locale')
->remove('profileImage')
->remove('settingsReceiveMessageNotification')
->remove('shippingAddresses')
->remove('save');
$form->get('payment')->remove('save');
$form->get('subscription')->remove('save');
$form->get('company')->get('mainLocation')
->remove('country')
->remove('province')
->remove('mobilePhone')
->remove('email')
->remove('pickUp')
->remove('notesForBuyer')
->remove('name')
->remove('defaultShipping')
->remove('showPublic')
;
$form->get('company')
->remove('submit')
->remove('conditionsCancel')
->remove('conditionsReturn')
->remove('conditionsShipping')
->remove('customSaleConditions')
->remove('speciality')
->remove('banner')
->remove('image')
->remove('otherLocations')
->remove('description')
->remove('website')
//->remove('termsAcceptance')
->remove('defaultShipping')
->remove('customUrl')
;
return $form->getForm();
}
/**
* @Route({
* "fr": "/go",
* "en": "/go",
* },
* name="fastCompanyInscription")
*
* @Template("frontend/fastCompanyInscription.html.twig")
*/
public function fastCompanyInscription(EntityManagerInterface $em, Request $request, UserManagerInterface $userManager, PaymentService $paymentServ, UserService $userServ){
$twigData = array();
$twigData['hideSideMenu'] = true;
$twigData['forceFooter']=true;
$company = new Company();
$form = $this->createFastCompanyForm();
$twigData['form']=$form->createView();
$form->handleRequest($request);
if($form->isSubmitted() && $form->isValid()){
//Ok we got the entire form, let's proceed step by step
/*
* Creation of the user
*/
$user = $form->get('user')->getData();
$user->setUsername($user->getEmail());
$user->setEmailCanonical($user->getEmail());
$user->setPhone($form->get('company')->get('mainLocation')->get('phone')->getData());
$user->setDisplayName($user->getFirstName());
$user->setEnabled(true);
$em->persist($user);
/*
* User done, let's do the Company
*/
$company = $form->get('company')->getData();
$testName = $em->getRepository(Company::class)->findOneBy(
[
'name' => $company->getName()
]
);
if(!empty($testName)){
//Check if this company name exist
$this->addFlash('error', 'Ce nom de boutique est déja existant.');
$form = $this->createFastCompanyForm($form->getData());
$twigData['form']=$form->createView();
return $twigData;
}else{
$company->addUsersAdmin($user);
$company->setExportColabor(false);
$em->persist($company);
}
/*
* Ok Company done let's do the payment
*/
$payment = $form->get('payment')->getData();
$company->addPayment($payment);
$paymentServ->testOnly = true;
$stripe = $paymentServ->getPaymentAccount($company);
if($stripe){
$em->persist($payment);
}else{
$this->addFlash('error', "Votre carte de crédit n'est pas valide");
$form = $this->createFastCompanyForm($form->getData());
$twigData['form']=$form->createView();
return $twigData;
}
/*
* Subscribtion
*/
$subscription = $form->get('subscription')->getData();
$company->addSubscription($subscription);
$em->persist($subscription);
$paymentServ->testOnly = false;
$paymentServ->subscribeToPlan($company, $subscription);
/*
* Ok time to check for the store at 125$
* @NOTE mettre a jour aussi le template d'email!
*/
$store = $form->get('storeMadeByMaturin')->getData();
if($store){
if($paymentServ->collectFromCompany(275, $company)){
$company->setStoreMadeByMaturin(true);
$userServ->sendEmail('Paiement recu pour creation boutique de la compagnie: '.$company->getName(), false, 'Recu un paiement de 275$ pour la compagnie Id:'.$company->getName().' via le formulaire /go', 'support@maturin.ca');
}
}
$this->addFlash('success', 'Merci, votre compte a été créé avec succès!');
$email = $this->get('twig')->render('emails/newCompany.html.twig', array('company' => $company, 'user' => $user));
$userServ->sendEmail('Bienvenue chez Maturin', $email, false, $user->getEmail());
$userServ->sendEmail('Maturin: Nouvelle compagnie via le formulare go '.$company->getName(), false, 'La compagnie '.$company->getName().' vient de remplir le formulaire /go', 'support@maturin.ca');
$em->persist($company);
$em->flush();
return $this->redirectToRoute('companyStore', array('id' => $company->getId(), 'urlname' => $company->getUrlName()));
}else if($form->isSubmitted() && !$form->isValid()){
foreach($form->getErrors(true) as $error){
$this->addFlash('error', $error->getMessage());
}
$form = $this->createFastCompanyForm($form->getData());
$twigData['form']=$form->createView();
}
return $twigData;
}
/**
* @Route({
* "fr": "/epicerie/liste",
* "en": "/compagnie/liste",
* },
* name="CompanyList")
*
* @Template("frontend/companies.html.twig")
*/
public function companyList(EntityManagerInterface $em){
$twigData = array();
$twigData['companies'] =
$em
->getRepository(Company::class)
->findAllValid();
return $twigData;
}
/**
* @Route({
* "fr": "/vendeur/controle/{id}",
* "en": "/seller/dashboard/{id}",
* },
* defaults={
* "id" = false
* },
* name="dashboardCompany")
*
* @Security("has_role('ROLE_ADMIN')")
* @Template("admin/dashboardCompany.html.twig")
*/
public function dashboard(Company $company=null, CompanyService $companyServ, EntityManagerInterface $em, UserService $userServ){
$twigData = array();
$user = $userServ->getUser();
if(empty($company)){
$companies = $user->getCompanies();
if(count($companies) > 1){
$this->addFlash('error', "Vous avez plusieur boutiques, pour accéder au paiement utiliser le lien Info & Dépot dans le menu sous l'onglet 'Paramètre'");
return $this->redirectToRoute('dashboard');
}else{
$company = $companies->get(0);
}
}
if(empty($company)){
$this->addFlash('error', "Nous n'arrivons pas a trouver votre boutique, utiliser le lien Info & Dépot dans le menu sous l'onglet 'Paramètre'");
return $this->redirectToRoute('dashboard');
}
if(!$companyServ->allowedToModify($company)){
$this->addFlash('error', "Vous n'avez pas accès a cette commpagnie");
return $this->redirectToRoute('dashboard');
}
$twigData['company'] = $company;
$twigData['maturinOrders'] = $em->getRepository(CartProduct::class)->findMaturinOrdersOf($company, 5);
$twigData['customOrders'] = $em->getRepository(CustomOrder::class)->findCustomOrdersOf($company, 5);
$twigData['visitors'] = $em->getRepository(UserViewedProduct::class)->findVisitorsOnProducer($company);
$twigData['totalSales'] = $em->getRepository(CartProduct::class)->findTotalSalesForCompany($company);
$twigData['totalSalesLast7days'] = $em->getRepository(CartProduct::class)->findTotalSalesLastXDaysForCompany($company, 7);
return $twigData;
}
/**
* @Route({
* "fr": "/vendeur/nouveau",
* "en": "/seller/new"
* },
* name="adminCompanyNew"
* )
* @Security("has_role('ROLE_ADMIN')")
* @Template("admin/company/new.html.twig")
*/
public function adminCompanyNew(Request $request, UserService $userServ, UrlGeneratorInterface $router)
{
$twigData = array();
$imageServ = $this->imageServ;
$em = $this->getDoctrine()->getManager();
$company = new Company();
$mainLocation = new CompanyLocation();
$mainLocation->setPickUp(false);
$company->setMainLocation($mainLocation);
$form = $this->createForm(CompanyType::class, $company);
/*
* Default shipping
if(empty($company->getDefaultShipping())){
$defaultShipping = new CompanyDefaultShipping();
}else
$defaultShipping = $company->getDefaultShipping();
$formDefaultShipping = $this->createForm(CompanyDefaultShippingType::class, $defaultShipping);
$twigData['entity']['defaultShipping'] = $defaultShipping;
$twigData['forms']['defaultShipping'] = $formDefaultShipping->createView();
*/
$form->handleRequest($request);
if($form->isSubmitted() && $form->isValid()){
$company = $form->getData();
$user = $userServ->getUser();
//Bind the association right away if it's that kind of users
if($user->getIsAllowedToMakeCompanyForAssociation() && $user->getMakeCompanyForAssociation()){
$company->addAssociation($user->getMakeCompanyForAssociation());
}
//Let's check if the custom Url exist
$routeIsAvailable = false;
try {
if($company->getCustomUrl()){
$route = $router->match( '/' . $company->getCustomUrl());
//To avoid taking url of another company
if($route['_route']== 'companyStore' && $route['id']== $company->getId())
$routeIsAvailable = true;
}
} catch ( ResourceNotFoundException $e ) {
// If the url didn't match any route at all
$testUrl = $em->getRepository(Company::class)->findOneByCustomUrl($company->getCustomUrl());
if(empty($testUrl))
$routeIsAvailable = true;
}
//Bad route
if(!$routeIsAvailable){
$this->addFlash('error', "Ce lien maturin n'est pas disponible");
$company->setCustomUrl(null);
}
$newShippings = $request->request->get('newShipping');
if($newShippings){
foreach($newShippings as $ship){
if($ship == 'main'){
$company->getDefaultshipping()->addLocation($company->getMainLocation());
}else{
//Ok we receive this one as urlencode(name)||zipCode
$rawValues = explode('||', $ship);
if(count($rawValues) == 2){
//We can't use the entity repository has it's not been recorded yet
//So we go through the otherLocations
foreach($company->getOtherLocations() as $location){
if($location->getName() == urldecode($rawValues[0]) && $location->getZipCode() == $rawValues[1])
$company->getDefaultshipping()->addLocation($location);
}
}
}
}
}
//As this user created the company, it's a Admin per default
$company->addAdminUser($userServ->getUser());
//@TODO change to FormType Image and remove this
if(!empty($company->getImage())){
$file = new File($company->getImage());
$image = $imageServ->saveUploadedFile($file, 'company_image', false);
if($image)
$company->setImage($image);
else
$company->setImage('reset');
}
if(!empty($company->getBanner())){
$file = new File($company->getBanner());
$banner = $imageServ->saveUploadedFile($file, 'company_banner', false);
if($banner)
$company->setBanner($banner);
else
$company->setBanner('reset');
}
$company->setExportColabor(false);
try {
$em->persist($company);
$em->flush();
$this->addFlash('success', 'Votre boutique a été créé avec succès.');
//Let's send it to the support team
$link = $router->generate('companyStore', array('urlname' => $company->getUrlName(), 'id' => $company->getId()));
$userServ->sendEmail('Maturin: Nouvelle boutique '.$company->getName(), "Cette boutique vien d'être créé sur Maturin, vous pouvez la voir a : ".$link , false, 'support@maturin.ca');
return $this->redirectToRoute('adminNewProduct', array('id' => $company->getId()));
} catch (\Exception $e ){
if(stristr($e->getMessage(), 'duplicate'))
$this->addFlash('error', 'Ce nom de boutique est pris.');
else{
$this->addFlash('error', 'Une erreur est survenu, veuillez contacter notre support.');
$this->addFlash('error', $e->getMessage());
}
}
}else{
foreach($form->getErrors(true) as $error){
$this->addFlash('error', $error->getMessage());
}
}
$twigData['company'] = $company;
$twigData['addNewForm'] = $form->createView();
$twigData['companyForm']= true;
return $twigData;
}
/**
* @Route({
* "fr": "/vendeur/paiement/{id}",
* "en": "/seller/payment/{id}"
* },
* defaults={
* "id" = false
* },
* name="companyPayment"
* )
* @Security("has_role('ROLE_ADMIN')")
* @Template("admin/company/payment.html.twig")
*/
public function companyPayment(Request $request, PaymentService $paymentServ, UserService $userServ, Company $company=null, CompanyService $companyServ){
$twigData = array();
$user = $userServ->getUser();
if(empty($company)){
$companies = $user->getCompanies();
if(count($companies) > 1){
$this->addFlash('error', "Vous avez plusieur boutiques, pour accéder au paiement utiliser le lien Info & Dépot dans le menu sous l'onglet 'Paramètre'");
return $this->redirectToRoute('dashboard');
}else{
$company = $companies->get(0);
}
}
if(empty($company)){
$this->addFlash('error', "Nous n'arrivons pas a trouver votre boutique, utiliser le lien Info & Dépot dans le menu sous l'onglet 'Paramètre'");
return $this->redirectToRoute('dashboard');
}
if(!$companyServ->allowedToModify($company)){
$this->addFlash('error', "Vous n'avez pas accès a cette commpagnie");
return $this->redirectToRoute('dashboard');
}
$twigData['company'] = $company;
/*
* Buy a already made store
*/
$formCreateStore = $this->createFormBuilder($company)
->add('storeMadeByMaturin', CheckboxType::class, array(
'label' => 'Oui je voudrais que Maturin configure ma boutique et produits',
'required' => true,
))
->add('extra', TextareaType::class, array(
'label' => 'Information supplémentaire',
'mapped' => false,
'required' => false
))
->add('save', SubmitType::class, array('label' => 'Commander'))
->getForm();
$twigData['forms']['createStore'] = $formCreateStore->createView();
$formCreateStore->handleRequest($request);
if($formCreateStore->isSubmitted() && $formCreateStore->isValid()){
if($paymentServ->collectFromCompany(275, $company)){
$em = $this->getDoctrine()->getManager();
$extra = $formCreateStore->get('extra')->getData();
$userServ->sendEmail('Paiement recu pour creation boutique de la compagnie: '.$company->getName(), false, 'Recu un paiement de 275$ pour la compagnie Id:'.$company->getId().' la compagnie a entré comme texte extra:'.$extra, 'support@maturin.ca');
$this->addFlash('success', 'Merci, votre demande a été envoyé a notre équipe!');
$userServ->addNotification('success', 'Achat création boutique', 'Merci, votre demande a été envoyé a notre équipe!');
return $this->redirectToRoute('companyPayment', array('id' => $company->getId()));
}else{
$company->setStoreMadeByMaturin(false);
$this->addFlash('error', 'Une erreur est survenue lors de votre paiement');
}
$em->persist($company);
$em->flush();
}
/*
* Payment Form
*/
if($company->hasPayment())
$payment = $company->getCurrentPayment();
else
$payment = new CompanyPayment();
$formPayment = $this->createForm(CompanyPaymentType::class, $payment);
$formPayment->handleRequest($request);
if($formPayment->isSubmitted() && $formPayment->isValid()){
$em = $this->getDoctrine()->getManager();
//Let's test with Stripe see if it's a valid card
$company->addPayment($payment);
$stripe = $paymentServ->getPaymentAccount($company);
if($stripe){
$em->persist($payment);
$em->persist($company);
$em->flush();
$this->addFlash('success', 'Informations enregistré avec succès');
$this->addFlash('focus', 'form[name="company_payment"]');
return $this->redirectToRoute('companyPayment', array('id' => $company->getId()));
}else{
$company->removePayment($payment);
$em->persist($company);
$em->flush();
//Repopulate the form with the previous information
$p = $formPayment->getData();
$p->forceDisplayNumbers = true;
$formPayment = $this->createForm(CompanyPaymentType::class, $p);
}
}
$twigData['forms']['payments'] = $formPayment->createView();
/*
* Subscriptions
*/
$subscription = new CompanySubscription();
$twigData['subscriptions']=$company->getSubscriptions();
$formSubscription = $this->createForm(CompanySubscriptionType::class, $subscription);
$twigData['forms']['subscription'] = $formSubscription->createView();
$formSubscription->handleRequest($request);
if($formSubscription->isSubmitted() && $formSubscription->isValid()){
$subscription = $formSubscription->getData();
$subscription->setCompany($company);
$em = $this->getDoctrine()->getManager();
$em->persist($subscription);
$company->addSubscription($subscription);
$em->persist($company);
$em->flush();
if(count($company->getPayments()) == 0){
$this->addFlash('error', "Votre n'avez pas de carte de crédit à votre compte");
$userServ->addNotification('error', 'Votre abonnement', "Votre compte n'a pas de carte de crédit configuré, donc la facturation a échoué.");
$this->addFlash('focus', 'form[name="company_subscription"]');
}else{
$paymentServ->subscribeToPlan($company, $subscription);
$this->addFlash('success', 'Informations enregistré avec succès');
$this->addFlash('focus', 'form[name="company_subscription"]');
}
return $this->redirectToRoute('companyPayment', array('id' => $company->getId()));
}
return $twigData;
}
/**
* @Route({
* "fr": "/vendeur/depot/{id}",
* "en": "/seller/deposit/{id}"
* },
* defaults={
* "id" = false
* },
* name="adminCompanySettings"
* )
* @Security("has_role('ROLE_ADMIN')")
* @Template("admin/company/settings.html.twig")
*/
public function adminCompanySettings(Company $company=null, Request $request, ProductService $prodServ, PaymentService $paymentServ, UserService $userServ, CompanyService $companyServ,StripeService $stripeService){
$user = $userServ->getUser();
if(empty($company)){
$companies = $user->getCompanies();
if(count($companies) > 1){
$this->addFlash('error', "Vous avez plusieur boutiques, pour accéder au paiement utiliser le lien Info & Dépot dans le menu sous l'onglet 'Paramètre'");
return $this->redirectToRoute('dashboard');
}else{
$company = $companies->get(0);
}
}
if(!$companyServ->allowedToModify($company)){
$this->addFlash('error', "Vous n'avez pas accès a cette boutique");
return $this->redirectToRoute('dashboard');
}
$twigData = array(
'company' => $company,
'amountOfProducts' => $prodServ->countProducts($company->getId())
);
$formSettings = $this->createFormBuilder($company)
->add('taxeTPS', TextType::class, array(
'label' => 'Numéro de TPS',
'required' => false
))
->add('taxeTVX', TextType::class, array(
'label'=>'Numéro de TVP ou TVH',
'required' => false
))
->add('companyNumber', TextType::class, array('label' => "Numéro d'entreprise : ARC ou NEQ"))
->add('saleId', TextType::class, array(
'label' => 'Numéro de vendeur',
'disabled' =>true,
'empty_data' => uniqid(),
'required' => false
))
->add('numberOfSales', NumberType::class, array(
'label' => 'Nombre de vente',
'disabled' => true,
'empty_data' => '0',
'required' => false
))
->add('totalSalesInDollars', MoneyType::class, array(
'label' => 'Total en vente',
'disabled' => true,
'empty_data' => '0',
'required' => false
))
->add('save', SubmitType::class, array('label' => 'Enregistrer'))
->getForm();
$twigData['forms']['settings'] = $formSettings->createView();
$formSettings->handleRequest($request);
if($formSettings->isSubmitted() && $formSettings->isValid()){
$newCompany = $formSettings->getData();
$em = $this->getDoctrine()->getManager();
$em->persist($newCompany);
$em->flush();
$this->addFlash('success', 'Informations enregistré avec succès');
$this->addFlash('focus', 'form[name="form"]');
return $this->redirectToRoute('adminCompanySettings', array('id' => $newCompany->getId()));
}
/*
* Deposit
*/
if (empty($company->getDeposit()))
$deposit = new CompanyDeposit();
else
$deposit = $company->getDeposit();
$acct = false;
if ($deposit)
$acct = $this->retriveCompanyStripeAccount($deposit,$company,$userServ,$stripeService);
//We leave standard and express account as they are They dont have property verification
if ( $acct && !($acct->type == "standard") && !($acct->type == "express") ) {
$accountStatus=$acct->legal_entity->verification->status;
$twigData['accountStatus'] = $accountStatus;
$accountLink = $this->getAccountLink($deposit,$company,$userServ);
if ($accountLink)
$twigData['accountLink'] = $accountLink->url;
else
$twigData['accountLink'] = false;
$verificationList= $this->getErrorsVerificationArray($acct,$stripeService);
$twigData['verificationList'] = $verificationList;
$twigData['forms']['deposit'] = false;
} else {
//Prefill the address with the one we have in the database.
if (!empty($company->getMainLocation()) && empty($deposit->getLegalStreetName())) {
$deposit->setLegalCivicNumber($company->getMainLocation()->getCivicNumber());
$deposit->setLegalStreetName($company->getMainLocation()->getStreetName());
$deposit->setLegalCity($company->getMainLocation()->getCity());
$deposit->setLegalProvince($company->getMainLocation()->getProvince());
$deposit->setLegalZipCode($company->getMainLocation()->getZipCode());
}
$formDeposit = $this->createForm(CompanyDepositType::class, $deposit);
$twigData['forms']['deposit'] = $formDeposit->createView();
$formDeposit->handleRequest($request);
if ($formDeposit->isSubmitted() && $formDeposit->isValid()) {
$deposit = $formDeposit->getData();
$otherOwnersFirst = $request->get('otherOwnersFirst');
$otherOwnersLast = $request->get('otherOwnersLast');
$otherOwners = array();
foreach ($otherOwnersFirst as $k => $o) {
if (!empty($o)) {
$otherOwners[] = array(
'first_name' => $o,
'last_name' => $otherOwnersLast[$k]
);
}
}
if (!empty($otherOwners))
$deposit->setCompanyOwners($otherOwners);
$em = $this->getDoctrine()->getManager();
$em->persist($deposit);
$company->setDeposit($deposit);
$em->persist($company);
$em->flush();
//Ok let's update the Stripe Account for deposit while at it
$paymentServ->updateAccount($company);
$this->addFlash('success', 'Informations enregistré avec succès');
$this->addFlash('focus', 'form[name="company_deposit"]');
return $this->redirectToRoute('adminCompanySettings', array('id' => $company->getId()));
} else {
foreach ($formDeposit->getErrors(true) as $error) {
$this->addFlash('error', $error->getMessage());
}
}
}
return $twigData;
}
public function getErrorsVerificationArray($acct,StripeService $stripeService){
$verificationList=[];
//Get the document verification needed for the company
$errorsCode = $acct->verification->errors;
if($errorsCode){
foreach ($errorsCode as $code) {
$verificationCode= $stripeService->getErrorsCodeType($code->code);
array_push($verificationList, $verificationCode);
}
}
return $verificationList;
}
public function getAccountLink(CompanyDeposit $companyDeposit,Company $company,UserService $userServ){
$log = new FinancialLog();
$log->setCompanyReceiving($company);
$log->setMethod('Get Company Account Link');
try {
$account_links = \Stripe\AccountLink::create([
'account' => $companyDeposit->getStripeAccountId(),
'refresh_url' => 'https://www.maturin.ca/vendeur/depot/'.$company->getId(),
'return_url' => 'https://www.maturin.ca/vendeur/depot/'.$company->getId(),
'type' => 'account_update',
]);
return $account_links;
} catch (\Exception $e) {
$log->setStripeRawResponse($e->getMessage());
$log->setStatus(false);
//$this->saveLog($log);
$userServ->addFlash('error', $e->getMessage());
return false;
}
return false;
}
public function retriveCompanyStripeAccount(CompanyDeposit $companyDeposit,Company $company,UserService $userServ,StripeService $stripeService){
$log = new FinancialLog();
$log->setCompanyReceiving($company);
$log->setMethod('Company stripe account ');
try{
$acct = \Stripe\Account::retrieve($companyDeposit->getStripeAccountId());
return $acct;
} catch (\Exception $e){
$log->setStripeRawResponse($e->getMessage());
$log->setStatus(false);
//$this->saveLog($log);
$userServ->addFlash('error', $e->getMessage());
}
return false;
}
/**
* @Route({
* "fr": "/vendeur/profile/{id}",
* "en": "/seller/profil/{id}"
* },
* defaults={
* "id" = false
* },
* name="adminCompanyProfile"
* )
* @Security("has_role('ROLE_ADMIN')")
* @Template("admin/company/new.html.twig")
*/
public function adminCompanyProfile(Request $request, UserService $userServ, ImageService $imageServ, Company $company = null, UrlGeneratorInterface $router)
{
if(empty($company)){
$user = $userServ->getUser();
$companies = $user->getCompanies();
if(count($companies) > 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);
}
}
$twigData = array();
$em = $this->getDoctrine()->getManager();
$pass = false;
foreach($userServ->getUser()->getCompanies() as $userAllowed){
if($userAllowed->getId() == $company->getId()){
$pass = true;
break;
}
}
if(!$pass){
$this->redirectToRoute('dashboardCompany', array('id' => $company->getId()));
}
$tmpImage = $company->getImage();
$tmpBanner = $company->getBanner();
$form = $this->createForm(CompanyType::class, $company);
$twigData['entity']['defaultShipping'] = $company->getDefaultShipping();
$form->handleRequest($request);
if($form->isSubmitted() && $form->isValid()){
//Let's check if the custom Url exist
$routeIsAvailable = false;
try {
if($company->getCustomUrl()){
$route = $router->match( '/' . $company->getCustomUrl());
//To avoid taking url of another company
if($route['_route']== 'companyStore' && $route['id']== $company->getId())
$routeIsAvailable = true;
}
} catch ( ResourceNotFoundException $e ) {
// If the url didn't match any route at all
$testUrl = $em->getRepository(Company::class)->findOneByCustomUrl($company->getCustomUrl());
if(empty($testUrl) || $testUrl->getId() == $company->getId())
$routeIsAvailable = true;
}
//Bad route
if(!$routeIsAvailable){
$this->addFlash('error', "Ce lien maturin n'est pas disponible");
$company->setCustomUrl(null);
}
$banner = $request->files->get('company')['banner'];
$image = $request->files->get('company')['image'];
if(!empty($image)){
//$file = new File($company->getImage());
$imgImage = $imageServ->saveUploadedFile($image, 'company_image', false);
if($imgImage)
$company->setImage($imgImage);
else
$company->setImage('reset');
}elseif($tmpImage){
//The Image wasn'T updated, fall back on the old one
if($tmpImage)
$company->setImage($tmpImage);
}
if(!empty($banner)){
//$file = new File($company->getBanner());
$imgBanner = $imageServ->saveUploadedFile($banner, 'company_banner', false);
if($imgBanner){
$company->setBanner($imgBanner);
}else{
$company->setBanner('reset');
}
}elseif($tmpBanner){
//Banner wasn'T updated, let's use the old one
if($tmpBanner)
$company->setBanner($tmpBanner);
}
$em->persist($company);
$em->flush();
$this->addFlash('success', 'Informations enregistré avec succès');
return $this->redirectToRoute('adminCompanyProfile', array('id' => $company->getId()));
}else{
foreach($form->getErrors(true) as $error){
$this->addFlash('error', $error->getMessage());
}
}
$twigData['company'] = $company;
$twigData['addNewForm'] = $form->createView();
$twigData['companyForm']= true;
/*
* Default shipping
*/
/*
if(empty($company->getDefaultShipping())){
$defaultShipping = new CompanyDefaultShipping();
$defaultShipping->setCompany($company);
}else
$defaultShipping = $company->getDefaultShipping();
$formDefaultShipping = $this->createForm(CompanyDefaultShippingType::class, $defaultShipping);
$twigData['forms']['defaultShipping'] = $formDefaultShipping->createView();
$formDefaultShipping->handleRequest($request);
if($formDefaultShipping->isSubmitted() && $formDefaultShipping->isValid()){
die('GOOD');
$em = $this->getDoctrine()->getManager();
$em->persist($defaultShipping);
$em->flush();
$this->addFlash('success', 'Informations enregistré avec succès');
$this->addFlash('focus', 'form[name="company_default_shipping"]');
return $this->redirectToRoute('adminCompanyProfile', array('id' => $company->getId()));
}else{
foreach($formDefaultShipping->getErrors(true) as $error){
$this->addFlash('error', $error->getMessage());
echo $error->getMessage();
}
if($formDefaultShipping->isSubmitted())
die('Valid');
die('bad');
}
*/
return $twigData;
}
/**
* @route({
* "fr": "/groupe/{groupurlname}/producteur/{urlname}/{id}",
* "en": "/group/{groupurlname}/producer/{urlname}/{id}"
* },
* options = {
* "expose" = true
* },
* name="viewCompanyInGroup")
* @Template("frontend/company.html.twig")
*/
public function companyIn($groupurlname, $urlname , $id, ProductService $prodServ, EntityManagerInterface $em, UserService $userServ){
$company = $em->getRepository(Company::class)->find((int)$id);
$assocation=$em->getRepository(CompanyAssociation::class)
->findOneBy([
'urlName' => $groupurlname
]);
if ($assocation && $assocation != $userServ->getAssociationUserIsBrowsing()){
$userServ->setAssociationUserIsBrowsing($assocation->getId());
//$this->addFlash('success');
}
return $this->company($urlname, $company, $prodServ, $em);
}
/**
* @route({
* "fr": "/producteur/{urlname}/{id}",
* "en": "/producer/{urlname}/{id}"
* },
* options = {
* "expose" = true
* },
* name="companyStore")
* @Template("frontend/company.html.twig")
*/
public function company($urlname, Company $company, ProductService $prodServ, EntityManagerInterface $em, Request $request ){
$twigData = array();
$twigData['link'] = $request->getPathInfo();
if (!$company->getShowPublicly() /*&& !$CompanyServ->allowedToModify($company)*/){
$this->addFlash('error', 'Cette compagnie n\'est pas disponible ');
$referer = null;//$request->headers->get('referer');
return $this->redirect($referer != null ? $referer : '/', 307);
}
$order = "DESC";
if ($request->get("order")) {
$order = $request->get("order");
}
$twigData['order']= $order;
$sorting = "date";
// $sorting = null;
if ($request->get("sorting")) {
$sorting = $request->get("sorting");
}
$twigData['sorting']= $sorting;
$twigData['company'] = $company;
$twigData['noPagination'] = true;
$twigData['companyTotalProducts'] = $em->getRepository(Product::class)->getTotalProducts($company);
if($request->get('filter')){
$filter = $request->get('filter');
$category = $em->getRepository(Category::class)->findBy(['id' => $filter]);
$twigData['availableProducts'] = $em->getRepository(Product::class)->getProductsByCompanyId($company->getId(), $sorting, $order, $category[0]);
$twigData['amountProductsPerCategories'] = count($twigData['availableProducts']);
}else{
$twigData['availableProducts'] = $em->getRepository(Product::class)->getProductsByCompanyId($company->getId(), $sorting, $order);
$twigData['amountProductsPerCategories'] = count($twigData['availableProducts']);
}
$twigData['amountProductsTotal'] = array(
'total' => $prodServ->countProducts($company->getId())
);
$categories = $prodServ->getAllUsedCategories($company->getId());
$twigData['productCategories'] = array();
foreach($categories as $key => $cat){
$twigData['productCategories'][] =
array(
'id' => $key,
'name' => $cat,
'amount' => $prodServ->countProducts($company->getId(), $key)
);
}
$twigData['totalSales'] = $em->getRepository(CartProduct::class)->findAmountSalesForCompany($company);
//$twigData['totalproduit'] = $em->getRepository(Product::class)->getProductsByCompanyId($company->getId());
$twigData['orderDates ']= $em->getRepository(Product::class)->findBy(
[
'company' => $company,
'available' => true
],[
'creationDate' => 'DESC'
]
);
$twigData['imagesGallery'] = $prodServ->getGalleryImages($company, 20);
return $twigData;
}
/**
* @Route({
* "fr": "/vendeur/usagers/{id}",
* "en": "/seller/users/{id}"
* },
* options = {
* "expose" = true
* },
* name="adminCompanyListUsers"
* )
* @Security("has_role('ROLE_ADMIN')")
* @Template("admin/company/userList.html.twig")
*/
public function adminCompanyListUsers(Company $company, CompanyService $companyServ)
{
if(!$companyServ->allowedToModify($company)){
$this->addFlash('error', "Vous n'avez pas accès a cette boutique");
return $this->redirectToRoute('dashboard');
}
$twigData = array();
$twigData['company']=$company;
$twigData['companyUsers'] = $company->getAdminUsers();
return $twigData;
}
/**
* @Route({
* "fr": "/vendeur/usagers/nouveau/{id}",
* "en": "/seller/users/new/{id}"
* },
* name="adminCompanyUsers"
* )
* @Security("has_role('ROLE_ADMIN')")
* @Template("admin/company/user.html.twig")
*/
public function adminCompanyUsers(Company $company)
{
$twigData = array();
return $twigData;
}
/**
* @Route({
* "fr": "/vendeur/usagers/effacer/{companyId}/{userId}",
* "en": "/seller/users/delete/{companyId}/{userId}"
* },
* options = {
* "expose" = true
* },
* name="adminCompanyDeleteUser"
* )
* @Security("has_role('ROLE_ADMIN')")
* @Entity("company", expr="repository.find(companyId)")
* @Entity("user", expr="repository.find(userId)")
*/
public function adminCompanyDeleteUsers(Company $company, User $user, UserService $UserServ, CompanyService $CompanyServ, EntityManagerInterface $em)
{
$return = array(
'status' => false
);
//Little bit of security here
$currentUser = $UserServ->getUser();
if(!$CompanyServ->allowedToModify($company))
die('Not allowed');
else{
$company->removeAdminUser($user);
$em->persist($company);
$em->flush();
$return['status'] = true;
}
$jsonResponse = new JsonResponse();
$jsonResponse->setData($return);
return $jsonResponse;
}
/**
* @Route({
* "fr": "/admin/compagnie/{companyId}/usagers/{userEmail}/ajouter",
* "en": "/admin/company/{companyId}/users/{userEmail}/add"
* },
* options = {
* "expose" = true
* },
* name="adminCompanyAddUser"
* )
* @Security("has_role('ROLE_ADMIN')")
* @Entity("company", expr="repository.find(companyId)")
* @Entity("user", options={"mapping": {"userEmail": "email"}})
*/
public function adminCompanyAddUser(Company $company, User $user=NULL, UserService $UserServ, CompanyService $CompanyServ, EntityManagerInterface $em)
{
$return = array(
'status' => false,
'message' => ''
);
if(empty($user)){
$return['message']='User not found';
}else{
//Little bit of security here
$currentUser = $UserServ->getUser();
if(!$CompanyServ->allowedToModify($company))
$return['message'] = 'You are not allowed';
else{
$company->addAdminUser($user);
$em->persist($company);
$em->flush();
$return['status'] = true;
}
}
$jsonResponse = new JsonResponse();
$jsonResponse->setData($return);
return $jsonResponse;
}
/**
* @Route(
* "/vendeur/conditions/{id}",
* options = {
* "expose" = true
* },
* name="acceptCompanyTerms"
* )
* @Security("has_role('ROLE_ADMIN')")
*/
public function acceptTerms(Company $company, EntityManagerInterface $em, CompanyService $CompanyServ)
{
$return = array(
'status' => false,
'message' => ''
);
if(!$CompanyServ->allowedToModify($company))
$return['message'] = 'You are not allowed';
else{
$company->setTermsAcceptance(true);
$em->persist($company);
$em->flush();
$return['message'] = 'Terms Accepted';
$return['status'] = true;
}
$jsonResponse = new JsonResponse();
$jsonResponse->setData($return);
return $jsonResponse;
}
/**
* @Route({
* "fr": "/vendeur/variableCompagnie/liste/{id}",
* "en": "/seller/variableCompany/list/{id}"
* },
* defaults={
* "id" = false
* },
* name="companyVariableList"
* )
* @Security("has_role('ROLE_ADMIN')")
* @Template("admin/company/listVariables.html.twig")
*/
public function companyVariableList(Company $company=null, UserService $userServ, Request $request, EntityManagerInterface $em, CompanyService $companyServ, VariableService $variableServ){
if(empty($company)){
$user = $userServ->getUser();
$companies = $user->getCompanies();
if(count($companies) > 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);
}
}
if(!$companyServ->allowedToModify($company)){
$this->addFlash('error', "Vous n'avez pas accès a cette boutique");
return $this->redirectToRoute('dashboard');
}
$twigData = array();
$twigData['company']= $company;
$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)->saveVariableForCompany(
$twigData['company'],
'Frais fixe de montage d\'une commande (cueillette)',
'orders.packingFixedFee',
$orders_packingFixedFee
);
$orders_prepareDelay = $request->get('orders_prepareDelay');
$em->getRepository(Variable::class)->saveVariableForCompany(
$twigData['company'],
'Delais de preparation d\'une commande en jours',
'orders.prepareDelay',
$orders_prepareDelay
);
$orders_canPickUp = $request->get('orders_canPickUp');
$em->getRepository(Variable::class)->saveVariableForCompany(
$twigData['company'],
'Ramassage possible',
'orders.canPickUp',
$orders_canPickUp
);
$orders_canPackUp = $request->get('orders_canPackUp');
$em->getRepository(Variable::class)->saveVariableForCompany(
$twigData['company'],
'Option de montage des commandes',
'orders.canPackUp',
$orders_canPackUp
);
$orders_pickUpAdress = $request->get('orders_pickUpAdress');
$em->getRepository(Variable::class)->saveVariableForCompany(
$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)->saveVariableForCompany(
$twigData['company'],
'Horaire de ramassage',
'orders.pickUpSchedule',
$pickUpSchedule
);
$pickUpScheduleDurations = json_encode($pickUpScheduleDurations);
$em->getRepository(Variable::class)->saveVariableForCompany(
$twigData['company'],
'Durée des plages horaires',
'orders.pickUpScheduleDurations',
$pickUpScheduleDurations
);
$pickUpScheduleSlotLimits = json_encode($pickUpScheduleSlotLimits);
$em->getRepository(Variable::class)->saveVariableForCompany(
$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;
// //If that simple form was submitted
// $testVar = $request->get('var');
// if($testVar){
// foreach($testVar as $id => $value){
// //Validation and security
// $cv = $em->getRepository(Variable::class)->findOneBy(
// [
// 'id' => $id
// ]
// );
// if($cv && $cv->getIsEditableByTarget()){
// $variableServ->setVariableById($id, $value);
// }
// }
// $this->addFlash('success', "Vos paramètres on été mise à jour");
// }
return $twigData;
}
/**
* @Route({
* "fr": "/SupprimeAdresse/{id}",
* "en": "/removeProduct/{id}",
* },
* name="removeProduct")
*
*/
public function removeProduct(Request $request, $id){
$em = $this->getDoctrine()->getManager();
$productCompany = $em->getRepository(Product::class)->findOneBy(["id"=>$id]);
if ($productCompany->getQtyReadyToShip() == 0 ){
$productCompany->setProductDelete(1);
$productCompany->setAvailable(0);
}else{
$this->addFlash('error', "Vous ne pouvez pas supprimer ce produit car ça quantité est supérieure a 0.");
return $this->redirectToRoute('adminListProducts', [
'id' => $productCompany->getCompany()->getId()
]);
}
$em->persist($productCompany);
$em->flush();
$this->addFlash('success', "Le produit " . $productCompany ." a bien été mis à jour.");
return $this->redirectToRoute('adminListProducts', [
'id' => $productCompany->getCompany()->getId()
]);
}
}