<?php
namespace App\Controller;
use App\Entity\Billing;
use App\Entity\Client;
use App\Entity\Company;
use App\Entity\Contract;
use App\Entity\ContractProduct;
use App\Entity\IntervenantSalon;
use App\Entity\Product;
use App\Entity\RDV;
use App\Entity\RDVProduct;
use App\Entity\Recurrence;
use App\Entity\RecurrenceProduct;
use App\Entity\Salon;
use App\Entity\SessionSalon;
use App\Entity\Site;
use App\Form\Billing\FilterType;
use App\Form\ClientType;
use App\Form\Reglement\FilterType as ReglementFilterType;
use App\Form\RelanceFactureType;
use App\Manager\ClientManager;
use App\Repository\BillingInfosRepository;
use App\Repository\BillingRepository;
use App\Repository\ClientRepository;
use App\Repository\CompanyRepository;
use App\Repository\FamilleRepository;
use App\Repository\ProductRepository;
use App\Repository\ProductTypeRepository;
use App\Repository\PromoCodeRepository;
use App\Repository\RDVRepository;
use App\Repository\RecurrenceProductRepository;
use App\Repository\RecurrenceRepository;
use App\Repository\ReglementRepository;
use App\Repository\SessionSalonRepository;
use App\Repository\SiteRepository;
use App\Repository\SousFamilleRepository;
use App\Service\FileUploader;
use App\Service\MailService;
use App\Service\PaytweakService;
use App\Traits\Autowired\Vendor\EntityManagerTrait;
use App\Traits\BillingManagerTrait;
use App\Traits\MailServiceTrait;
use App\Traits\PdfServiceTrait;
use App\Traits\RDVManagerTrait;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Criteria;
use Doctrine\ORM\EntityManagerInterface;
use Knp\Bundle\SnappyBundle\Snappy\Response\PdfResponse;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\StreamedResponse;
use Symfony\Component\Routing\Annotation\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Symfony\Component\Serializer\SerializerInterface;
use Yectep\PhpSpreadsheetBundle\Factory;
/**
* @Route("/client")
*/
class ClientController extends AbstractController
{
use PdfServiceTrait;
use MailServiceTrait;
use EntityManagerTrait;
use BillingManagerTrait;
use RDVManagerTrait;
/** @var ProductRepository */
private $productRepository;
/**
* @Route("/", name="client_index", methods={"GET"})
*/
public function index(Request $request,
ClientRepository $clientRepository,
SiteRepository $siteRepository
): Response
{
$q = $request->query->get('q');
$site = $request->query->get('site');
$tel = $request->query->get('tel');
$email = $request->query->get('email');
$emailNotaire = $request->query->get('email-notaire');
$emailContact = $request->query->get('email-contact');
$nom = $request->query->get('nom');
$sites = $siteRepository->findBy(['status' => 'actif']);
$status = $request->query->get('status');
return $this->render('client/index.html.twig', [
'nom' => $nom,
'emailNotaire' => $emailNotaire,
'status' => $status,
'emailContact' => $emailContact,
'email' => $email,
'q' => $q,
'tel' => $tel,
'sites' => $sites,
'clients' => $clientRepository->search($q, $site, $email, $emailContact, $emailNotaire, $nom, $tel, $status),
]);
}
/**
* @Route("/sendBilling/{client}", name="client_send_billing")
*/
public function sendBilling(
Request $request,
Client $client,
BillingRepository $billingRepository,
PaytweakService $paytweakService
) {
$status = $request->request->get('status');
$billings = $billingRepository->searchForLot(null, null, null, null, $status, null, $client);
foreach ($billings as $billing) {
/** @var Client $client */
$client = $billing->getClient();
$company = $client->getBillingInfos() ? $client->getBillingInfos()->getCompany() : null;
$email = $billing->getClient()->getBillingInfos() ? $billing->getClient()->getBillingInfos()->getEmail() : null;
if ($email && $company) {
$senderAdress = new \Symfony\Component\Mime\Address('comptabilite@silverbeaute.com', 'Comptabilité Silver Beauté');
$html = $this->renderView('billing/pdf.html.twig', [
'billings' => [$billing],
'company' => $billing->getCompany()
]);
$this->pdfService->setTimeout(120);
$this->pdfService->setOption('enable-local-file-access', true);
$pdf = $this->pdfService->getOutputFromHtml($html);
//$call = $paytweakService->reSend($company, $billing->getCode(), $email);
$res = $paytweakService->getLink($client->getBillingInfos()->getCompany(), $billing->getCode());
if ($res['code'] === PaytweakService::CODE_OK) {
$link = reset($res);
if ($link["paid"] == "1") {
continue;
}
$this->mailService->sentRelance($senderAdress, $email, $company, $pdf, $billing, $link["link_url"]);
} elseif ($res['code'] === PaytweakService::CODE_NOT_FOUND) {
$invoice = $paytweakService->createInvoiceFromClient($client, $billing);
$call = $paytweakService->createBilling($invoice, $company);
if ($call['code'] == 'OK') {
$billing->setStatus(Billing::STATUS_SENT);
$billing->setSendingDate(new \DateTime());
$this->em->persist($billing);
} else {
$this->mailService->sentErrorPaytweak($billing, $call['code'], $call['message']);
}
} else {
//$mailService->sentErrorPaytweak($billing, $call['code'], $call['message']);
}
}
}
$this->em->flush();
$this->addFlash('success', 'Renvoi par payweak effectué');
return $this->redirectToRoute('client_edit', ['id' => $client->getId()]);
}
/**
* @Route("/new", name="client_new", methods={"GET","POST"})
*/
public function new(Request $request, BillingInfosRepository $billingRepository, ClientManager $clientManager): Response
{
$entityManager = $this->getDoctrine()->getManager();
$client = new Client();
$form = $this->createForm(ClientType::class, $client, ['defaultCompany' => $entityManager->getRepository(Company::class)->find(2)]);
$form->handleRequest($request);
//dump($form->getErrors());die;
if ($form->isSubmitted() && $form->isValid()) {
$lastname = $client->getLastname();
$mail = $client->getEmailTuteur();
if ($mail) {
$client->getBillingInfos()->setEmail($mail);
}
//$client->getBillingInfos()->setDiscount(0);
$client->setCreator($this->getUser());
$client->setMaj($this->getUser());
if (!$client->getBillingInfos()->getPhone()) {
$client->getBillingInfos()->setPhone($client->getNumeroTuteur());
}
$client->setIdentifier(strtoupper(substr($client->getLastname(), 0, 3) . $clientManager->getLastId()));
$entityManager->persist($client);
//$this->generateRecurrence($form);
$entityManager->flush();
if ($client->getBillingInfos() && !$client->getBillingInfos()->getAccount()) {
if ($billingRepository->findOneBy(['account' => '411' . substr($lastname, 0)])) {
$client->getBillingInfos()->setAccount('411' . substr($lastname, 0) . $client->getId());
} else {
$client->getBillingInfos()->setAccount('411' . substr($lastname, 0));
}
}
$entityManager->persist($client);
$entityManager->flush();
return $this->redirectToRoute('client_edit', ['id' => $client->getId()]);
}
return $this->render('client/new.html.twig', [
'client' => $client,
'form' => $form->createView(),
]);
}
/**
* @Route("/import", name="client_import")
* @Template()
*/
public function import(
Request $request,
SiteRepository $siteRepository,
CompanyRepository $companyRepository,
BillingInfosRepository $billingInfosRepository
) {
$sites = $siteRepository->findBy(['status' => Site::STATUS_ACTIF]);
$companies = $companyRepository->findBy([]);
$path = $this->getParameter('client_import_directory');
$order = [
'A' => 'setIdentifier',
'B' => 'setFirstname',
'C' => 'setLastname',
'D' => 'setBirthday',
'E' => 'setDeathday',
'F' => 'setCivilite', // setGender is for contact infos
'G' => 'setEmail',
'H' => 'setPhone',
'I' => 'setComments',
'J' => 'setRoomNumber',
'K' => 'setBuildingRoom',
'L' => 'setStairs',
'M' => 'setGender',
'N' => 'setNomTuteur',
'O' => 'setPrenomTuteur',
'P' => 'setEmailTuteur',
'Q' => 'setEmailNotaire',
'R' => 'setNumeroTuteur',
'S' => 'setTypeTuteur',
'T' => 'setCommentTuteur',
'U' => 'setNumClient',
'V' => 'setAddressTuteur',
'W' => 'setAddressTuteur2',
'X' => 'setCity',
'Y' => 'setZipcode',
'AJ' => 'setProfilClient',
'AK' => 'setStatusProspect',
'AL' => 'setSuiviClient',
];
if ($request->isMethod(Request::METHOD_POST)) {
$files = $request->request->get('files');
$siteId = $request->request->get('site');
$companyId = $request->request->get('company');
$site = $siteRepository->find($siteId);
$company = $companyRepository->find($companyId);
$em = $this->getDoctrine()->getManager();
if ($files) {
foreach ($files as $file) {
$path_file = $path . '/' . $file;
if (file_exists($path_file)) {
try {
/** Identify the type of $inputFileName **/
$inputFileType = \PhpOffice\PhpSpreadsheet\IOFactory::identify($path_file);
/** Create a new Reader of the type defined in $inputFileType **/
$reader = \PhpOffice\PhpSpreadsheet\IOFactory::createReader($inputFileType);
/** Advise the Reader that we only want to load cell data **/
$reader->setReadDataOnly(true);
$spreadsheet = $reader->load($path_file);
$worksheet = $spreadsheet->getActiveSheet();
//$lines = $spreadsheet->getActiveSheet()->toArray();
foreach ($worksheet->getRowIterator() as $key => $row) {
if ($key === 1) {
continue;
}
$cellIterator = $row->getCellIterator();
$cellIterator->setIterateOnlyExistingCells(false); // This loops through all cells,
// even if a cell value is not set.
// By default, only cells that have a value
// set will be iterated.
$client = new Client();
$billingInfos = new Client\BillingInfos();
if ($company) {
$billingInfos->setCompany($company);
}
$em->persist($billingInfos);
$client->setBillingInfos($billingInfos);
if ($site) {
$client->setSite($site);
}
$clientExists = false;
$lastname = '';
foreach ($cellIterator as $key2 => $cell) {
if (array_key_exists($key2, $order)) {
$setter = $order[$key2];
if ($setter) {
$value = $cell->getValue();
if (!isset($value)) {
continue;
}
// if($setter === 'email'){
//
// $existingClient = $em->getRepository(Client::class)->findOneBy(['email' => $value]);
// if ($existingClient) {
// $clientExists = true;
// }
// }
call_user_func_array([$client, $setter], [$value]);
// if(!$clientExists){
// $em->persist($client);
// }
}
}
else {
$cellValue = $cell->getValue();
if (!isset($cellValue)) {
continue;
}
switch ($key2) {
case 'Z': {
$billingInfos->setEmail($cellValue);
break;
}
case 'AA': {
$billingInfos->setPhone($cellValue);
break;
}
case 'AB': {
$billingInfos->setDiscount($cellValue);
break;
}
case 'AC': {
$sendMode = Client\BillingInfos::SEND_MODE_EMAIL;
if ($cellValue == 'Courrier') {
$sendMode = Client\BillingInfos::SEND_MODE_COURRIER;
}
$billingInfos->setSendMode($sendMode);
break;
}
case 'AD': {
$payMode = Client\BillingInfos::PAY_MODE_CB;
if ($cellValue == 'CB') {
$payMode = Client\BillingInfos::PAY_MODE_CB;
} elseif ($cellValue == 'SEPA') {
$payMode = Client\BillingInfos::PAY_MODE_SEPA;
} elseif ($cellValue == 'CHEQUES') {
$payMode = Client\BillingInfos::PAY_MODE_CHEQUES;
} elseif ($cellValue == 'VIREMENT') {
$payMode = Client\BillingInfos::PAY_MODE_VIREMENT;
}
$billingInfos->setPayMode($payMode);
break;
}
case 'AE': {
$billingInfos->setAccount($cellValue);
break;
}
case 'AF': {
$billingInfos->setBankName($cellValue);
break;
}
case 'AG': {
$billingInfos->setIban($cellValue);
break;
}
case 'AH': {
$billingInfos->setBic($cellValue);
break;
}
case 'AI': {
$billingInfos->setRum($cellValue);
break;
}
// case 'AJ': {
// $billingInfos->setDateSignatureMandat($cellValue);
// break;
// }
default:
break;
}
}
}
// Check if the client with the same name and gender already exists for the same site
if ($client->getLastname() && $client->getCivilite() && $site) {
$existingClient = $em->getRepository(Client::class)->findOneBy([
'lastname' => $client->getLastname(),
'civilite' => $client->getCivilite(),
'site' => $site
]);
if ($existingClient) {
$clientExists = true;
}
}
if (!$clientExists) {
if ($billingInfosRepository->findOneBy(['account' => '411' . substr($client->getLastname(), 0)])) {
$client->getBillingInfos()->setAccount('411' . substr($client->getLastname(), 0) . $client->getId());
} else {
$client->getBillingInfos()->setAccount('411' . substr($client->getLastname(), 0));
}
if(!$client->getLastname()){
continue;
}
$em->persist($client);
$em->flush();
$client->setIdentifier($client->getId() . ' ' . $client->getLastname());
$em->persist($client);
}
}
$em->flush();
} catch (\Exception $exception) {
dump($exception);
die;
}
}
}
//
$this->addFlash('success', 'Fichier importé');
}
}
return [
'compagnies' => $companies,
'sites' => $sites
];
}
/**
* @Route("/import-ajax", name="client_importajax")
*/
public function importajax(Request $request, FileUploader $fileUploader)
{
$path = $this->getParameter('client_import_directory');
$file = $request->files->get('file');
if ($file) {
try {
$resp = $fileUploader->upload($request->files->get('file'), $path);
return new JsonResponse(['filename' => $resp]);
} catch (\Exception $e) {
}
}
return new JsonResponse(['error' => '']);
}
/**
* @Route("/import-ajax-contract", name="client_importajaxcontract")
*/
public function importajaxcontract(Request $request, FileUploader $fileUploader)
{
$path = $this->getParameter('client_contract_import_directory');
$file = $request->files->get('file');
if ($file) {
try {
$resp = $fileUploader->upload($request->files->get('file'), $path);
return new JsonResponse(['filename' => $resp]);
} catch (\Exception $e) {
dd($e);
}
}
return new JsonResponse(['error' => '']);
}
/**
* @Route("/import-contract", name="client_importContract")
*/
public function importContract(
Request $request,
ClientRepository $repository,
ProductTypeRepository $productTypeRepository,
ProductRepository $productRepository,
SousFamilleRepository $sousFamilleRepository,
FamilleRepository $familleRepository
) {
$path = $this->getParameter('client_contract_import_directory');
$em = $this->getDoctrine()->getManager();
if ($request->isMethod(Request::METHOD_POST)) {
$files = $request->request->get('files');
foreach ($files as $file) {
$path_file = $path . '/' . $file;
if (file_exists($path_file)) {
try {
/** Identify the type of $inputFileName **/
$inputFileType = \PhpOffice\PhpSpreadsheet\IOFactory::identify($path_file);
/** Create a new Reader of the type defined in $inputFileType **/
$reader = \PhpOffice\PhpSpreadsheet\IOFactory::createReader($inputFileType);
/** Advise the Reader that we only want to load cell data **/
$reader->setReadDataOnly(true);
$spreadsheet = $reader->load($path_file);
$worksheet = $spreadsheet->getActiveSheet();
//$lines = $spreadsheet->getActiveSheet()->toArray();
foreach ($worksheet->getRowIterator() as $key => $row) {
if ($key === 1) {
continue;
}
$cellIterator = $row->getCellIterator();
$cellIterator->setIterateOnlyExistingCells(FALSE); // This loops through all cells,
// even if a cell value is not set.
// By default, only cells that have a value
// set will be iterated.
/** @var Client|null $client */
$client = null;
/** @var Contract|null $contract */
$contract = null;
$skip = true;
$productsArrayEntities = [];
foreach ($cellIterator as $key2 => $cell) {
$cellValue = $cell->getValue();
if (!isset($cellValue)) {
continue;
}
//dump($key2);die;
switch ($key2) {
case 'A': {
$client = $repository->findOneBy(['identifier' => $cellValue]);
dd($cellValue);
if ($client) {
$contract = new Contract();
$contract->setClient($client);
$skip = false;
}
break;
}
case 'B': {
if ($client) {
$date = \PhpOffice\PhpSpreadsheet\Shared\Date::excelToDateTimeObject($cellValue);
$contract->setDateDebutRelation($date->format('d/m/Y'));
}
break;
}
case 'C': {
if ($client) {
$date = \PhpOffice\PhpSpreadsheet\Shared\Date::excelToDateTimeObject($cellValue);
$contract->setDateDebutRelation($date->format('d/m/Y'));
$contract->setDateFinRelation($cellValue);
}
break;
}
case 'D': {
if ($client) {
$contract->setDateDebut($cellValue);
}
break;
}
case 'E': {
if ($client) {
$contract->setDateFin($cellValue);
}
break;
}
case 'F': {
if ($client) {
$contract->setTypePrestation($cellValue);
}
break;
}
case 'G': {
if ($client) {
if ($cellValue === 'Périodiques') {
$cellValue = Contract::TYPE_RDV_PERIODIQUE;
}
if ($cellValue === 'Sur demande famille') {
$cellValue = Contract::TYPE_RDV_FAMILLE;
}
$contract->setTypeRDV($cellValue);
}
break;
}
case 'H': {
if ($client) {
$contract->setLibellePrestation($cellValue);
if ($client) {
$product = $productRepository->findOneBy(['name' => $cellValue]);
if ($product) {
$contractProduct = new ContractProduct();
$contractProduct->setProduct($product);
$contractProduct->setContract($contract);
$em->persist($contractProduct);
$productsArrayEntities[] = $product;
}
}
}
break;
}
case 'I': {
if ($client) {
$contract->setRecurrence($cellValue);
}
break;
}
default:
break;
}
}
if (!$skip) {
$em->persist($contract);
$client->addContract($contract);
$em->persist($client);
$em->flush(); // flush contrqcct
if (!$contract->getRecurrenceGenerated() && $contract->getTypeRDV() === Contract::TYPE_RDV_PERIODIQUE) {
$intervenant = null;
$salon = null;
$start = $contract->getDateDebutRelation();
$end = $contract->getDateFinRelation();
if (!$start) {
continue;
}
//OK
$dateAdd = strtotime($start); // date début contrat
$endTime = strtotime($end); //date fin contrat
// si ehpad RDV généré sur 4 ans
if ($contract->getClient()->getSite()->getType() === Site::TYPE_EHPAD) {
$ending = strtotime('+4 year', strtotime($start));
} else {
$ending = strtotime('+6 month', strtotime($start));
}
// si pas défini par défault 4 ans aprés la date de début
if (!$endTime) {
$endTime = strtotime('+4 year', strtotime($start));
}
$client = $contract->getClient();
// get tag of the first product
$tag = null;
if (isset($productsArrayEntities[0])) {
/** @var Product $product */
$product = $productsArrayEntities[0];
$tag = $product->getType();
}
$salons = $client->getSite()->getFirstSalonsByTag($tag);
if (!$salons->isEmpty() && $salons->first()) {
/** @var Salon $first */
$salon = $salons->first();
/** @var IntervenantSalon $intervenantSalon */
$intervenantSalon = $salon->getIntervenantSalons()->first();
if ($intervenantSalon) {
$intervenant = $intervenantSalon->getIntervenant();
}
}
// generate first one Le début et la fin sont le meme jour soit la date de début
$rdv = new RDV();
$rdv->setClient($client);
$datetime = new \DateTime();
//dump($dateAdd);
$rdv->setStart($datetime->setTimestamp($dateAdd));
$rdv->setEnd($datetime->setTimestamp($dateAdd));
if ($salon) {
$rdv->setSalon($salon);
}
if ($intervenant) {
$rdv->setIntervenant($intervenant);
}
$rdv->setContract($contract);
$em->persist($rdv);
foreach ($productsArrayEntities as $product) {
$rdvProduct = $this->createRDVProduct($product, $rdv);
$em->persist($rdvProduct);
}
$i = 0;
$max = 1000;
// TODO : refactor
switch ($contract->getRecurrence()) {
case Contract::RECURRENCE_1_SUR_SEMAINE: {
while ($i < $max && $dateAdd < $ending && $dateAdd < $endTime) {
$dateAdd = strtotime('+1 week', $dateAdd);
//dump(date('d/m/y',$dateAdd));
$rdv = new RDV();
$rdv->setClient($client);
$datetime = new \DateTime();
$rdv->setStart($datetime->setTimestamp($dateAdd));
$rdv->setEnd($datetime->setTimestamp($dateAdd));
$rdv->setContract($contract);
$rdv->setPriorite(1);
if ($intervenant) {
$rdv->setIntervenant($intervenant);
}
if ($salon) {
$rdv->setSalon($salon);
}
$em->persist($rdv);
foreach ($productsArrayEntities as $product) {
$rdvProduct = $this->createRDVProduct($product, $rdv);
$em->persist($rdvProduct);
}
$i++;
}
break;
}
case Contract::RECURRENCE_1_SUR_2: {
// compare timestamp
while ($i < $max && $dateAdd < $ending && $dateAdd < $endTime) {
$dateAdd = strtotime('+2 week', $dateAdd);
//dump(date('d/m/y',$dateAdd));
$rdv = new RDV();
$rdv->setClient($client);
$datetime = new \DateTime();
$rdv->setStart($datetime->setTimestamp($dateAdd));
$rdv->setEnd($datetime->setTimestamp($dateAdd));
$rdv->setContract($contract);
$rdv->setPriorite(1);
if ($intervenant) {
$rdv->setIntervenant($intervenant);
}
if ($salon) {
$rdv->setSalon($salon);
}
$em->persist($rdv);
foreach ($productsArrayEntities as $product) {
$rdvProduct = $this->createRDVProduct($product, $rdv);
$em->persist($rdvProduct);
}
$i++;
}
//dump($i); // max 13 6 month
break;
}
case Contract::RECURRENCE_1_SUR_3: {
while ($i < $max && $dateAdd < $ending && $dateAdd < $endTime) {
$dateAdd = strtotime('+3 week', $dateAdd);
//dump(date('d/m/y',$dateAdd));
$rdv = new RDV();
$rdv->setClient($client);
$datetime = new \DateTime();
$rdv->setStart($datetime->setTimestamp($dateAdd));
$rdv->setEnd($datetime->setTimestamp($dateAdd));
$rdv->setContract($contract);
$rdv->setPriorite(2);
if ($intervenant) {
$rdv->setIntervenant($intervenant);
}
if ($salon) {
$rdv->setSalon($salon);
}
$em->persist($rdv);
foreach ($productsArrayEntities as $product) {
$rdvProduct = $this->createRDVProduct($product, $rdv);
$em->persist($rdvProduct);
}
$i++;
}
break;
}
case Contract::RECURRENCE_1_SUR_4: {
while ($i < $max && $dateAdd < $ending && $dateAdd < $endTime) {
$dateAdd = strtotime('+4 week', $dateAdd);
//dump(date('d/m/y',$dateAdd));
$rdv = new RDV();
$rdv->setClient($client);
$datetime = new \DateTime();
$rdv->setStart($datetime->setTimestamp($dateAdd));
$rdv->setEnd($datetime->setTimestamp($dateAdd));
$rdv->setContract($contract);
$rdv->setPriorite(2);
if ($intervenant) {
$rdv->setIntervenant($intervenant);
}
if ($salon) {
$rdv->setSalon($salon);
}
$em->persist($rdv);
foreach ($productsArrayEntities as $product) {
$rdvProduct = $this->createRDVProduct($product, $rdv);
$em->persist($rdvProduct);
}
$i++;
}
break;
}
case Contract::RECURRENCE_1_SUR_8: {
while ($i < $max && $dateAdd < $ending && $dateAdd < $endTime) {
$dateAdd = strtotime('+5 week', $dateAdd);
//dump(date('d/m/y',$dateAdd));
$rdv = new RDV();
$rdv->setClient($client);
$datetime = new \DateTime();
$rdv->setStart($datetime->setTimestamp($dateAdd));
$rdv->setEnd($datetime->setTimestamp($dateAdd));
$rdv->setContract($contract);
$rdv->setPriorite(2);
if ($intervenant) {
$rdv->setIntervenant($intervenant);
}
if ($salon) {
$rdv->setSalon($salon);
}
$em->persist($rdv);
foreach ($productsArrayEntities as $product) {
$rdvProduct = $this->createRDVProduct($product, $rdv);
$em->persist($rdvProduct);
}
$i++;
}
break;
}
case Contract::RECURRENCE_1_SUR_12: {
while ($i < $max && $dateAdd < $ending && $dateAdd < $endTime) {
$dateAdd = strtotime('+6 week', $dateAdd);
//dump(date('d/m/y',$dateAdd));
$rdv = new RDV();
$rdv->setClient($client);
$datetime = new \DateTime();
$rdv->setStart($datetime->setTimestamp($dateAdd));
$rdv->setEnd($datetime->setTimestamp($dateAdd));
$rdv->setContract($contract);
$rdv->setPriorite(2);
if ($intervenant) {
$rdv->setIntervenant($intervenant);
}
if ($salon) {
$rdv->setSalon($salon);
}
$em->persist($rdv);
foreach ($productsArrayEntities as $product) {
$rdvProduct = $this->createRDVProduct($product, $rdv);
$em->persist($rdvProduct);
}
$i++;
}
break;
}
case Contract::RECURRENCE_1_SUR_5: {
while ($i < $max && $dateAdd < $ending && $dateAdd < $endTime) {
$dateAdd = strtotime('+5 week', $dateAdd);
//dump(date('d/m/y',$dateAdd));
$rdv = new RDV();
$rdv->setClient($client);
$datetime = new \DateTime();
$rdv->setStart($datetime->setTimestamp($dateAdd));
$rdv->setEnd($datetime->setTimestamp($dateAdd));
$rdv->setContract($contract);
$rdv->setPriorite(2);
if ($intervenant) {
$rdv->setIntervenant($intervenant);
}
if ($salon) {
$rdv->setSalon($salon);
}
$em->persist($rdv);
foreach ($productsArrayEntities as $product) {
$rdvProduct = $this->createRDVProduct($product, $rdv);
$em->persist($rdvProduct);
}
$i++;
}
break;
}
case Contract::RECURRENCE_1_SUR_6: {
while ($i < $max && $dateAdd < $ending && $dateAdd < $endTime) {
$dateAdd = strtotime('+6 week', $dateAdd);
//dump(date('d/m/y',$dateAdd));
$rdv = new RDV();
$rdv->setClient($client);
$datetime = new \DateTime();
$rdv->setStart($datetime->setTimestamp($dateAdd));
$rdv->setEnd($datetime->setTimestamp($dateAdd));
$rdv->setContract($contract);
$rdv->setPriorite(2);
if ($intervenant) {
$rdv->setIntervenant($intervenant);
}
if ($salon) {
$rdv->setSalon($salon);
}
$em->persist($rdv);
foreach ($productsArrayEntities as $product) {
$rdvProduct = $this->createRDVProduct($product, $rdv);
$em->persist($rdvProduct);
}
$i++;
}
break;
}
case Contract::RECURRENCE_1_SUR_2_MONTH: {
while ($i < $max && $dateAdd < $ending && $dateAdd < $endTime) {
$dateAdd = strtotime('+9 week', $dateAdd);
//dump(date('d/m/y',$dateAdd));
$rdv = new RDV();
$rdv->setClient($client);
$datetime = new \DateTime();
$rdv->setStart($datetime->setTimestamp($dateAdd));
$rdv->setEnd($datetime->setTimestamp($dateAdd));
$rdv->setContract($contract);
$rdv->setPriorite(2);
if ($intervenant) {
$rdv->setIntervenant($intervenant);
}
if ($salon) {
$rdv->setSalon($salon);
}
$em->persist($rdv);
foreach ($productsArrayEntities as $product) {
$rdvProduct = $this->createRDVProduct($product, $rdv);
$em->persist($rdvProduct);
}
$i++;
}
break;
}
case Contract::RECURRENCE_1_SUR_TRIM: {
while ($i < $max && $dateAdd < $ending && $dateAdd < $endTime) {
$dateAdd = strtotime('+13 week', $dateAdd);
//dump(date('d/m/y',$dateAdd));
$rdv = new RDV();
$rdv->setClient($client);
$datetime = new \DateTime();
$rdv->setStart($datetime->setTimestamp($dateAdd));
$rdv->setEnd($datetime->setTimestamp($dateAdd));
$rdv->setContract($contract);
$rdv->setPriorite(2);
if ($intervenant) {
$rdv->setIntervenant($intervenant);
}
if ($salon) {
$rdv->setSalon($salon);
}
$em->persist($rdv);
foreach ($productsArrayEntities as $product) {
$rdvProduct = $this->createRDVProduct($product, $rdv);
$em->persist($rdvProduct);
}
$i++;
}
break;
}
case Contract::RECURRENCE_1_SUR_6_MONTH: {
while ($i < $max && $dateAdd < $ending && $dateAdd < $endTime) {
$dateAdd = strtotime('+26 week', $dateAdd);
//dump(date('d/m/y',$dateAdd));
$rdv = new RDV();
$rdv->setClient($client);
$datetime = new \DateTime();
$rdv->setStart($datetime->setTimestamp($dateAdd));
$rdv->setEnd($datetime->setTimestamp($dateAdd));
$rdv->setContract($contract);
$rdv->setPriorite(2);
if ($intervenant) {
$rdv->setIntervenant($intervenant);
}
if ($salon) {
$rdv->setSalon($salon);
}
$em->persist($rdv);
foreach ($productsArrayEntities as $product) {
$rdvProduct = $this->createRDVProduct($product, $rdv);
$em->persist($rdvProduct);
}
$i++;
}
break;
}
}
$contract->setRecurrenceGenerated(true);
}
$em->flush();
}
}
} catch (\Exception $exception) {
$this->addFlash('error', 'Erreur lors de limport', $exception->getMessage());
}
}
}
}
return $this->render('client/importContract.html.twig', []);
}
/**
* @Route("/downloadExcel")
*/
public function downloadExcel(ClientRepository $repository, RDVRepository $RDVRepository)
{
$entities = new ArrayCollection($repository->findAll());
$response = new StreamedResponse();
$columns = $this->getColumnsForEntity(Client::class, $RDVRepository);
$response->setCallback(function () use ($entities, $columns) {
$handle = fopen('php://output', 'w+');
// Add header
fputcsv($handle, array_keys($columns));
while ($entity = $entities->current()) {
$values = [];
foreach ($columns as $column => $callback) {
$value = $callback;
if (is_callable($callback)) {
$value = $callback($entity);
}
$values[] = $value;
}
fputcsv($handle, $values);
$entities->next();
}
fclose($handle);
});
$filename = 'client_export.csv';
$response->headers->set('Content-Type', 'text/csv; charset=utf-8');
$response->headers->set('Content-Disposition', 'attachment; filename="' . $filename . '"');
return $response;
}
/**
* @Route("/downloadClient")
*/
public function downloadClient(Request $request, ClientRepository $repository)
{
$statuses = $request->request->get('statusProspect', []);
$site = $request->request->get('site');
$filters = ['statusProspect' => $statuses];
if (!empty($site)) {
$filters['site'] = $site;
}
$entities = new ArrayCollection($repository->downloadClient($statuses, $site));
$response = new StreamedResponse();
$columns = $this->getColumnsForEntity(Client::class);
$response->setCallback(function () use ($entities, $columns) {
$handle = fopen('php://output', 'w+');
// Add header
fputcsv($handle, array_keys($columns));
while ($entity = $entities->current()) {
$values = [];
foreach ($columns as $column => $callback) {
$value = $callback;
if (is_callable($callback)) {
$value = $callback($entity);
}
$values[] = $value;
}
fputcsv($handle, $values);
$entities->next();
}
fclose($handle);
});
$filename = 'client_export.csv';
$response->headers->set('Content-Type', 'text/csv; charset=utf-8');
$response->headers->set('Content-Disposition', 'attachment; filename="' . $filename . '"');
return $response;
}
/**
* @Route("/{id}", name="client_show", methods={"GET"})
*/
public function show(Client $client): Response
{
return $this->render('client/show.html.twig', [
'client' => $client,
]);
}
/**
* @Route("/{id}/edit", name="client_edit", methods={"GET","POST","PUT"})
*/
public function edit(
Request $request,
Client $client,
PaytweakService $paytweakService,
BillingRepository $billingRepository,
ReglementRepository $reglementRepository
): Response
{
$entityManager = $this->getDoctrine()->getManager();
$reglements = $reglementRepository->findBy(['client' => $client], ['id' => 'DESC'], 12);
$filterFormReglement = $this->createForm(ReglementFilterType::class, [], ['client_form' => false]);
$filterFormReglement->handleRequest($request);
$isReg = false;
if ($filterFormReglement->isSubmitted() && $filterFormReglement->isValid()) {
$status = $filterFormReglement['statut']->getData();
$mode = $filterFormReglement['mode']->getData();
$date = $filterFormReglement['date']->getData();
$dateEnd = $filterFormReglement['dateEnd']->getData();
//global list
$reglements = $reglementRepository->filter($mode, $client, $date, $dateEnd, [], [], $status, true);
$isReg = true;
}
$isBillingFilter = false;
$allBillings = $billingRepository->filter(null, $client,null, null,null,null, null, true, 12);
$filterForm = $this->createForm(FilterType::class, null, ['client_form' => false]);
$filterForm->handleRequest($request);
if ($filterForm->isSubmitted() && $filterForm->isValid()) {
$status = $filterForm['status']->getData();
$date = $filterForm['dateDebut']->getData();
$dateEnd = $filterForm['dateFin']->getData();
$allBillings = $billingRepository->filter(null, $client, $date, $dateEnd, $status, null,null,true);
$isBillingFilter = true;
}
$originalFamilyMembers = new ArrayCollection();
$originalContracts = new ArrayCollection();
// Create an ArrayCollection of the current Tag objects in the database
foreach ($client->getFamilyMembers() as $familyMember) {
$originalFamilyMembers->add($familyMember);
}
foreach ($client->getContract() as $contract) {
$originalContracts->add($contract);
}
$form = $this->createForm(ClientType::class, $client, [
'show_sepa' => $client->getBillingInfos()->getPayMode() === Client\BillingInfos::PAY_MODE_SEPA,
]);
$formRelance = $this->createForm(RelanceFactureType::class);
$form->handleRequest($request);
$formRelance->handleRequest($request);
if ($formRelance->isSubmitted() && $formRelance->isValid()) {
$status = $formRelance->get('status')->getData();
$start = $formRelance->get('start')->getData();
$end = $formRelance->get('end')->getData();
/** @var BillingRepository $billingRepo */
$billingRepo = $this->billingManager->getRepository();
$startPass = \DateTime::createFromFormat('d-m-Y', $start );
$endPass = \DateTime::createFromFormat('d-m-Y', $end );
$billings = $billingRepo->searchForRelanceByClient($client, $status, $startPass, $endPass);
/** @var Billing $billing */
foreach($billings as $billing) {
/** @var Client $client */
$client = $billing->getClient();
$payMode = $client->getBillingInfos()->getPayMode();
$sendMode = $client->getBillingInfos()->getSendMode();
if (
(
(
$sendMode === Client\BillingInfos::SEND_MODE_EMAIL &&
($payMode == Client\BillingInfos::PAY_MODE_CB
|| $payMode == Client\BillingInfos::PAY_MODE_CHEQUES
|| $payMode == Client\BillingInfos::PAY_MODE_VIREMENT)
)
||
($sendMode === Client\BillingInfos::SEND_MODE_COURRIER && $payMode == Client\BillingInfos::PAY_MODE_CB )
|| ( $sendMode === Client\BillingInfos::SEND_MODE_EMAIL && $payMode === null)
)
)
{
$email = $billing->getClient()->getBillingInfos() ? $billing->getClient()->getBillingInfos()->getEmail(): null;
if($email){
$senderAdress = new \Symfony\Component\Mime\Address( 'comptabilite@silverbeaute.com', 'Comptabilité Silver Beauté');
$html = $this->renderView('billing/pdf.html.twig',[
'billings' => [$billing],
'company' => $billing->getCompany()
]);
$this->pdfService->setTimeout(120);
$this->pdfService->setOption('enable-local-file-access', true);
$pdf = $this->pdfService->getOutputFromHtml($html);
//$call = $paytweakService->reSend($company, $billing->getCode(), $email);
$res = $paytweakService->getLink($billing->getCompany(), $billing->getCode());
if($res['code'] === PaytweakService::CODE_OK) {
$link = reset($res);
if($link["paid"] == "1"){
continue;
}
$this->mailService->sentRelance($senderAdress,$email, $billing->getCompany(), $pdf, $billing, $link["link_url"]);
}
elseif($res['code'] === PaytweakService::CODE_NOT_FOUND){
$invoice = $paytweakService->createInvoiceFromClient($client, $billing);
$call = $paytweakService->createBilling($invoice, $billing->getCompany());
if($call['code'] == 'OK') {
$billing->setStatus(Billing::STATUS_SENT);
$billing->setSendingDate(new \DateTime());
if(isset($call['link_id'] )){
$billing->setLinkPaytweak($call['link_id']);
}
$entityManager->persist($billing);
}
else {
$this->mailService->sentErrorPaytweak($billing, $call['code'], $call['message']);
}
}
else {
//$mailService->sentErrorPaytweak($billing, $call['code'], $call['message']);
}
}
}
}
$entityManager->flush();
return $this->redirectToRoute('client_edit', [
'id' => $client->getId(),
]);
}
$isContact = false;
if ($form->isSubmitted() && $form->isValid()) {
/** @var Client\FamilyMember $familyMember */
foreach ($originalFamilyMembers as $familyMember) {
if (false === $client->getFamilyMembers()->contains($familyMember)) {
// remove the Task from the Tag
$client->getFamilyMembers()->removeElement($client);
$entityManager->remove($familyMember);
}
}
/** @var Contract $contract */
foreach ($originalContracts as $contract) {
if (false === $client->getContract()->contains($contract)) {
/** @var RDV $rdv */
foreach ($contract->getRdvs() as $rdv) {
if ($rdv->getStatus() === RDV::STATUS_PLANIFIER) {
$contract->getRdvs()->removeElement($rdv);
$entityManager->remove($rdv);
}
}
$client->getContract()->removeElement($client);
$entityManager->remove($contract);
}
}
/** @var Contract $contract */
foreach ($client->getContract() as $contract) {
$contract->setClient($client);
$entityManager->persist($contract);
}
if (!$client->getBillingInfos()->getPhone()) {
$client->getBillingInfos()->setPhone($client->getNumeroTuteur());
}
$uow = $entityManager->getUnitOfWork();
$oldStatus = $uow->getOriginalEntityData($client)['statusProspect'];
if(
($client->getStatusProspect() === Client::STATUS_INACTIF ||
$client->getStatusProspect() === Client::STATUS_PARTI) &&
($oldStatus != Client::STATUS_INACTIF || $oldStatus != Client::STATUS_PARTI)
){
$rdvsTodelete = $this->RDVManager->findFromTodayByStatusPlan($client);
foreach ($rdvsTodelete as $rdv) {
$entityManager->remove($rdv);
}
$entityManager->flush();
// Retrieve the recurrence record to delete
}
$client->setMaj($this->getUser());
$entityManager->persist($client);
//$this->generateRecurrence($form, true);
$entityManager->flush();
$isContact = true;
// return $this->redirectToRoute('client_edit', [
// 'id' => $client->getId(),
// ]);
}
$products = $this->productRepository->findAll();
return $this->render('client/edit.html.twig', [
'products' => $products,
'client' => $client,
'formRelance' => $formRelance->createView(),
'form' => $form->createView(),
'formFilter' => $filterForm->createView(),
'factures' => $allBillings,
'isBilling' => $isBillingFilter,
'reglements' => $reglements,
'formFilterReglement' => $filterFormReglement->createView(),
'isReg' => $isReg,
'isContact' => $isContact,
]);
}
/**
* @Route("/sendBillingMultiple", name="client_send_billing_multiple", methods={"GET","POST","PUT"})
*/
public function sendBillingMultiple(Request $request, BillingRepository $billingRepository, PaytweakService $paytweakService) {
$data = json_decode($request->getContent(), true);
$billings = $data['factures'];
foreach ($billings as $billingItem){
$billing = $billingRepository->find($billingItem);
$client = $billing->getClient();
$payMode = $client->getBillingInfos()->getPayMode();
$sendMode = $client->getBillingInfos()->getSendMode();
if (
(
(
$sendMode === Client\BillingInfos::SEND_MODE_EMAIL &&
($payMode == Client\BillingInfos::PAY_MODE_CB
|| $payMode == Client\BillingInfos::PAY_MODE_CHEQUES
|| $payMode == Client\BillingInfos::PAY_MODE_VIREMENT)
)
||
($sendMode === Client\BillingInfos::SEND_MODE_COURRIER && $payMode == Client\BillingInfos::PAY_MODE_CB )
|| ( $sendMode === Client\BillingInfos::SEND_MODE_EMAIL && $payMode === null)
)
)
{
$email = $billing->getClient()->getBillingInfos() ? $billing->getClient()->getBillingInfos()->getEmail(): null;
if($email){
$senderAdress = new \Symfony\Component\Mime\Address( 'comptabilite@silverbeaute.com', 'Comptabilité Silver Beauté');
$html = $this->renderView('billing/pdf.html.twig',[
'billings' => [$billing],
'company' => $billing->getCompany()
]);
$this->pdfService->setTimeout(120);
$this->pdfService->setOption('enable-local-file-access', true);
$pdf = $this->pdfService->getOutputFromHtml($html);
//$call = $paytweakService->reSend($company, $billing->getCode(), $email);
$res = $paytweakService->getLink($billing->getCompany(), $billing->getCode());
if($res['code'] === PaytweakService::CODE_OK) {
$link = reset($res);
if($link["paid"] == "1"){
continue;
}
$this->mailService->sentRelance($senderAdress,$email, $billing->getCompany(), $pdf, $billing, $link["link_url"]);
}
elseif($res['code'] === PaytweakService::CODE_NOT_FOUND){
$invoice = $paytweakService->createInvoiceFromClient($client, $billing);
$call = $paytweakService->createBilling($invoice, $billing->getCompany());
if($call['code'] == 'OK') {
$billing->setStatus(Billing::STATUS_SENT);
$billing->setSendingDate(new \DateTime());
if(isset($call['link_id'] )){
$billing->setLinkPaytweak($call['link_id']);
}
$this->em->persist($billing);
}
else {
$this->mailService->sentErrorPaytweak($billing, $call['code'], $call['message']);
}
}
else {
//$mailService->sentErrorPaytweak($billing, $call['code'], $call['message']);
}
}
}
}
$this->em->flush();
return new JsonResponse('ok');
}
/**
* @Route("/{id}/recurrence", methods={"GET","POST"})
*/
public function recurrence(
Client $client, Request $request,
ProductRepository $productRepository,
RecurrenceRepository $recurrenceRepository,
RecurrenceProductRepository $recurrenceProductRepository,
SessionSalonRepository $sessionSalonRepository,
PromoCodeRepository $promoCodeRepository
) {
$productsAll = $this->productRepository->findBy([
"indisponibleVente" =>false,
"type" => Product::TYPE_COIFFURE
]);
$type = $request->request->get('type');
$recurrence = $recurrenceRepository->findOneBy(['client' => $client, 'type' => $type ?? Product::TYPE_COIFFURE]);
$salonCoiffure = $client->getSite()->getFirstSalonsByTag(Product::TYPE_COIFFURE)->first();
$sessionSalonDates = $sessionSalonRepository->findSessionsBySalon($salonCoiffure);
//dd($sessionSalonDates);
$codePromos = $promoCodeRepository->findAll();
$post = $request->isMethod(Request::METHOD_POST);
if($post){
$selectedPromoCode = $request->request->get('codePromo');
$promoCode = $promoCodeRepository->findOneBy(['code' => $selectedPromoCode]);
if(!$recurrence){
$recurrence = new Recurrence();
$recurrence->setClient($client);
}
else {
$currentTime = new \DateTime();
foreach ($recurrence->getRdvs() as $rdv) {
if ($rdv->getStart() > $currentTime && ($rdv->getStatus() === RDV::STATUS_PLANIFIER ||$rdv->getStatus() === RDV::STATUS_REPLANIFIER )) {
$this->em->remove($rdv);
}
}
}
$nbSemaine = $request->request->get('nbSemaine');
$JOS = $request->request->get('date_debut');
$products = $request->request->get('products');
$startDate = \DateTime::createFromFormat('Y-m-d H:i', $JOS);
$endDate = \DateTime::createFromFormat('Y-m-d H:i', $JOS);
$recurrence->setNbSemaine($nbSemaine);
$recurrence->setType($type);
$date = new \DateTime($JOS);
$recurrence->setJos($date);
$this->em->persist($recurrence);
$endDate->add(new \DateInterval('P1Y'));
if($products){
foreach ($products as $key => $product){
$productFind = $productRepository->find($product['product']);
$recurrenceProduct = $recurrenceProductRepository->findOneBy(['product' => $productFind, 'recurrence' => $recurrence]);
if(!$recurrenceProduct){
$recurrenceProduct = new RecurrenceProduct();
}
$recurrenceProduct->setFrequency($product['frequency']);
$this->em->persist($recurrenceProduct);
$productFind->addRecurrenceProduct($recurrenceProduct);
$this->em->persist($productFind);
$this->em->persist($recurrenceProduct);
$recurrence->addRecurrenceProduct($recurrenceProduct);
$this->em->persist($recurrence);
}
}
$i = 0;
while ($startDate <= $endDate) {
// Create an RDV object with the current date
$rdv = new RDV();
if ($i === 0 && $promoCode) {
$rdv->setCodePromo($promoCode);
}
$rdv->setClient($client);
$newStartDate = clone $startDate;
$newEndDate = clone $startDate;
//$startDate->setTime(10, 0, 0);
$rdv->setStart($newStartDate);
$rdv->setEnd($newEndDate);
$salons = $client->getSite()->getSalons();
/** @var Salon $salon */
$salonFind = null;
foreach ($salons as $salon){
if($type === $salon->getService()) {
$salonFind = $salon;
break;
}
}
if($salonFind){
$rdv->setSalon($salonFind);
/** @var IntervenantSalon $intervenant */
$intervenant = $salonFind->getIntervenantSalons()->last();
if($intervenant){
$rdv->setIntervenant($intervenant->getIntervenant());
}
}
$rdv->setStatus(RDV::STATUS_PLANIFIER);
$rdv->setNewRecurrence(true);
if($products){
foreach ($products as $key => $product){
/** @var Product $productFind */
$productFind = $productRepository->find($product['product']);
if($i === 0){
$rdvProduct = new RDVProduct();
$rdvProduct->setRdv($rdv);
$rdvProduct->setProduct($productFind);
$this->em->persist($rdvProduct);
$rdv->addRdvProduct($rdvProduct);
}
else {
$selectedFrequency = $product['frequency'];
if ($selectedFrequency == "every") {
// Handle the case where you want every RDV
$rdvProduct = new RDVProduct();
$rdvProduct->setRdv($rdv);
$rdvProduct->setProduct($productFind);
$this->em->persist($rdvProduct);
$rdv->addRdvProduct($rdvProduct);
}
elseif ($selectedFrequency == "every_other") {
// Handle the case where you want every 1 of 2 RDV
if ($i % 2 == 0) { // Check if $i is even
$rdvProduct = new RDVProduct();
$rdvProduct->setRdv($rdv);
$rdvProduct->setProduct($productFind);
$this->em->persist($rdvProduct);
$rdv->addRdvProduct($rdvProduct);
}
}
elseif ($selectedFrequency == "every_third") {
// Handle the case where you want every 1 of 3 RDV
if ($i % 3 == 0) { // Check if $i is divisible by 3
$rdvProduct = new RDVProduct();
$rdvProduct->setRdv($rdv);
$rdvProduct->setProduct($productFind);
$this->em->persist($rdvProduct);
$rdv->addRdvProduct($rdvProduct);
}
}
elseif ($selectedFrequency == "every_fourth") {
// Handle the case where you want every 1 of 4 RDV
if ($i % 4 == 0) { // Check if $i is divisible by 4
$rdvProduct = new RDVProduct();
$rdvProduct->setRdv($rdv);
$rdvProduct->setProduct($productFind);
$this->em->persist($rdvProduct);
$rdv->addRdvProduct($rdvProduct);
}
}
elseif ($selectedFrequency == "every_fifth") {
// Handle the case where you want every 1 of 5 RDV
if ($i % 5 == 0) { // Check if $i is divisible by 5
$rdvProduct = new RDVProduct();
$rdvProduct->setRdv($rdv);
$rdvProduct->setProduct($productFind);
$this->em->persist($rdvProduct);
$rdv->addRdvProduct($rdvProduct);
}
}
elseif ($selectedFrequency == "every_sixth") {
// Handle the case where you want every 1 of 6 RDV
if ($i % 6 == 0) { // Check if $i is divisible by 6
$rdvProduct = new RDVProduct();
$rdvProduct->setRdv($rdv);
$rdvProduct->setProduct($productFind);
$this->em->persist($rdvProduct);
$rdv->addRdvProduct($rdvProduct);
}
}
elseif ($selectedFrequency == "every_seventh") {
// Handle the case where you want every 1 of 7 RDV
if ($i % 7 == 0) { // Check if $i is divisible by 7
$rdvProduct = new RDVProduct();
$rdvProduct->setRdv($rdv);
$rdvProduct->setProduct($productFind);
$this->em->persist($rdvProduct);
$rdv->addRdvProduct($rdvProduct);
}
}
elseif ($selectedFrequency == "every_eighth") {
// Handle the case where you want every 1 of 8 RDV
if ($i % 8 == 0) { // Check if $i is divisible by 8
$rdvProduct = new RDVProduct();
$rdvProduct->setRdv($rdv);
$rdvProduct->setProduct($productFind);
$this->em->persist($rdvProduct);
$rdv->addRdvProduct($rdvProduct);
}
}
elseif ($selectedFrequency == "every_ninth") {
// Handle the case where you want every 1 of 9 RDV
if ($i % 9 == 0) { // Check if $i is divisible by 9
$rdvProduct = new RDVProduct();
$rdvProduct->setRdv($rdv);
$rdvProduct->setProduct($productFind);
$this->em->persist($rdvProduct);
$rdv->addRdvProduct($rdvProduct);
}
} elseif ($selectedFrequency == "every_tenth") {
// Handle the case where you want every 1 of 10 RDV
if ($i % 10 == 0) { // Check if $i is divisible by 10
$rdvProduct = new RDVProduct();
$rdvProduct->setRdv($rdv);
$rdvProduct->setProduct($productFind);
$this->em->persist($rdvProduct);
$rdv->addRdvProduct($rdvProduct);
}
}
elseif ($selectedFrequency == "every_eleventh") {
// Handle the case where you want every 1 of 11 RDV
if ($i % 11 == 0) { // Check if $i is divisible by 11
$rdvProduct = new RDVProduct();
$rdvProduct->setRdv($rdv);
$rdvProduct->setProduct($productFind);
$this->em->persist($rdvProduct);
$rdv->addRdvProduct($rdvProduct);
}
}
elseif ($selectedFrequency == "every_twelfth") {
// Handle the case where you want every 1 of 12 RDV
if ($i % 12 == 0) { // Check if $i is divisible by 12
$rdvProduct = new RDVProduct();
$rdvProduct->setRdv($rdv);
$rdvProduct->setProduct($productFind);
$this->em->persist($rdvProduct);
$rdv->addRdvProduct($rdvProduct);
}
}
}
}
}
$recurrence->addRdv($rdv);
$this->em->persist($recurrence);
$this->em->persist($rdv);
$i++;
// Increment the date by the number of weeks specified
$startDate->add(new \DateInterval('P' . $nbSemaine . 'W'));
}
$this->em->flush();
}
return $this->render('client/recurrence.html.twig', [
'client' => $client,
'products' => $productsAll,
'recurrence' => $recurrence,
'sessionSalonDates' => $sessionSalonDates,
'promoCodes' =>$codePromos
]);
}
/**
* @Route("/{id}/recurrence/{type}/delete", methods={"POST"})
*/
public function deleteRecurrence(Client $client, $type)
{
$entityManager = $this->getDoctrine()->getManager();
$recurrenceRepository = $this->getDoctrine()->getRepository(Recurrence::class);
// Retrieve the recurrence record to delete
/** @var Recurrence $recurrence */
$recurrence = $recurrenceRepository->findOneBy(['client' => $client, 'type' => $type]);
$currentTime = new \DateTime();
if ($recurrence) {
foreach ($recurrence->getRdvs() as $rdv) {
if ($rdv->getStart() > $currentTime && ($rdv->getStatus() === RDV::STATUS_PLANIFIER ||$rdv->getStatus() === RDV::STATUS_REPLANIFIER )) {
$entityManager->remove($rdv);
}
else {
$rdv->setRecurrenceRdvs(null);
$entityManager->persist($rdv);
}
}
// Delete the recurrence record
$entityManager->remove($recurrence);
$entityManager->flush();
// You can also delete associated RDV records here if needed
}
// Return a response indicating success or failure
return new JsonResponse(['message' => 'Recurrence deleted successfully']);
}
/**
* @Route("/{id}/recurrence-esthetique", methods={"GET","POST"})
*/
public function recurrenceEsthetique(
Client $client, Request $request,
ProductRepository $productRepository,
RecurrenceRepository $recurrenceRepository,
RecurrenceProductRepository $recurrenceProductRepository,
EntityManagerInterface $entityManager,
SessionSalonRepository $sessionSalonRepository,
PromoCodeRepository $promoCodeRepository
) {
$codePromos = $promoCodeRepository->findAll();
$productsAll = $this->productRepository->findBy([
"indisponibleVente" =>false,
"type" => Product::TYPE_ESTHETHIQUE
]);
$recurrence = $recurrenceRepository->findOneBy(['client' => $client, 'type' => Product::TYPE_ESTHETHIQUE]);
$salonCoiffure = $client->getSite()->getFirstSalonsByTag(Product::TYPE_ESTHETHIQUE)->first();
$sessionSalonDates = $sessionSalonRepository->findSessionsBySalon($salonCoiffure);
$post = $request->isMethod(Request::METHOD_POST);
if($post){
if(!$recurrence){
$recurrence = new Recurrence();
$recurrence->setClient($client);
}
else {
$currentTime = new \DateTime();
foreach ($recurrence->getRdvs() as $rdv) {
if ($rdv->getStart() > $currentTime && ($rdv->getStatus() === RDV::STATUS_PLANIFIER ||$rdv->getStatus() === RDV::STATUS_REPLANIFIER )) {
$entityManager->remove($rdv);
}
}
}
$nbSemaine = $request->request->get('nbSemaine');
$JOS = $request->request->get('date_debut');
$products = $request->request->get('products');
$type = $request->request->get('type');
$startDate = \DateTime::createFromFormat('Y-m-d H:i', $JOS);
$endDate = \DateTime::createFromFormat('Y-m-d H:i', $JOS);
$recurrence->setNbSemaine($nbSemaine);
$recurrence->setType($type);
$date = new \DateTime($JOS);
$recurrence->setJos($date);
$this->em->persist($recurrence);
$endDate->add(new \DateInterval('P1Y'));
foreach ($products as $key => $product){
$productFind = $productRepository->find($product['product']);
$recurrenceProduct = $recurrenceProductRepository->findOneBy(['product' => $productFind, 'recurrence' => $recurrence]);
if(!$recurrenceProduct){
$recurrenceProduct = new RecurrenceProduct();
}
$recurrenceProduct->setFrequency($product['frequency']);
$this->em->persist($recurrenceProduct);
$productFind->addRecurrenceProduct($recurrenceProduct);
$this->em->persist($productFind);
$this->em->persist($recurrenceProduct);
$recurrence->addRecurrenceProduct($recurrenceProduct);
$this->em->persist($recurrence);
}
$i = 0;
while ($startDate <= $endDate) {
// Create an RDV object with the current date
$rdv = new RDV();
$rdv->setClient($client);
//$startDate->setTime(10, 0, 0);
$rdv->setStart(clone $startDate);
$rdv->setEnd(clone $startDate);
$salons = $client->getSite()->getSalons();
/** @var Salon $salon */
$salonFind = null;
foreach ($salons as $salon){
if($type === $salon->getService()) {
$salonFind = $salon;
break;
}
}
if($salonFind){
$rdv->setSalon($salonFind);
/** @var IntervenantSalon $intervenant */
$intervenant = $salonFind->getIntervenantSalons()->last();
if($intervenant){
$rdv->setIntervenant($intervenant->getIntervenant());
}
}
$rdv->setStatus(RDV::STATUS_PLANIFIER);
$rdv->setNewRecurrence(true);
foreach ($products as $key => $product){
$productFind = $productRepository->find($product['product']);
if($i === 0){
$rdvProduct = new RDVProduct();
$rdvProduct->setRdv($rdv);
$rdvProduct->setProduct($productFind);
$this->em->persist($rdvProduct);
$rdv->addRdvProduct($rdvProduct);
}
else {
$selectedFrequency = $product['frequency'];
if ($selectedFrequency == "every") {
// Handle the case where you want every RDV
$rdvProduct = new RDVProduct();
$rdvProduct->setRdv($rdv);
$rdvProduct->setProduct($productFind);
$this->em->persist($rdvProduct);
$rdv->addRdvProduct($rdvProduct);
}
elseif ($selectedFrequency == "every_other") {
// Handle the case where you want every 1 of 2 RDV
if ($i % 2 == 0) { // Check if $i is even
$rdvProduct = new RDVProduct();
$rdvProduct->setRdv($rdv);
$rdvProduct->setProduct($productFind);
$this->em->persist($rdvProduct);
$rdv->addRdvProduct($rdvProduct);
}
}
elseif ($selectedFrequency == "every_third") {
// Handle the case where you want every 1 of 3 RDV
if ($i % 3 == 0) { // Check if $i is divisible by 3
$rdvProduct = new RDVProduct();
$rdvProduct->setRdv($rdv);
$rdvProduct->setProduct($productFind);
$this->em->persist($rdvProduct);
$rdv->addRdvProduct($rdvProduct);
}
}
elseif ($selectedFrequency == "every_fourth") {
// Handle the case where you want every 1 of 4 RDV
if ($i % 4 == 0) { // Check if $i is divisible by 4
$rdvProduct = new RDVProduct();
$rdvProduct->setRdv($rdv);
$rdvProduct->setProduct($productFind);
$this->em->persist($rdvProduct);
$rdv->addRdvProduct($rdvProduct);
}
}
elseif ($selectedFrequency == "every_fifth") {
// Handle the case where you want every 1 of 5 RDV
if ($i % 5 == 0) { // Check if $i is divisible by 5
$rdvProduct = new RDVProduct();
$rdvProduct->setRdv($rdv);
$rdvProduct->setProduct($productFind);
$this->em->persist($rdvProduct);
$rdv->addRdvProduct($rdvProduct);
}
}
elseif ($selectedFrequency == "every_sixth") {
// Handle the case where you want every 1 of 6 RDV
if ($i % 6 == 0) { // Check if $i is divisible by 6
$rdvProduct = new RDVProduct();
$rdvProduct->setRdv($rdv);
$rdvProduct->setProduct($productFind);
$this->em->persist($rdvProduct);
$rdv->addRdvProduct($rdvProduct);
}
}
elseif ($selectedFrequency == "every_seventh") {
// Handle the case where you want every 1 of 7 RDV
if ($i % 7 == 0) { // Check if $i is divisible by 7
$rdvProduct = new RDVProduct();
$rdvProduct->setRdv($rdv);
$rdvProduct->setProduct($productFind);
$this->em->persist($rdvProduct);
$rdv->addRdvProduct($rdvProduct);
}
}
elseif ($selectedFrequency == "every_eighth") {
// Handle the case where you want every 1 of 8 RDV
if ($i % 8 == 0) { // Check if $i is divisible by 8
$rdvProduct = new RDVProduct();
$rdvProduct->setRdv($rdv);
$rdvProduct->setProduct($productFind);
$this->em->persist($rdvProduct);
$rdv->addRdvProduct($rdvProduct);
}
}
elseif ($selectedFrequency == "every_ninth") {
// Handle the case where you want every 1 of 9 RDV
if ($i % 9 == 0) { // Check if $i is divisible by 9
$rdvProduct = new RDVProduct();
$rdvProduct->setRdv($rdv);
$rdvProduct->setProduct($productFind);
$this->em->persist($rdvProduct);
$rdv->addRdvProduct($rdvProduct);
}
} elseif ($selectedFrequency == "every_tenth") {
// Handle the case where you want every 1 of 10 RDV
if ($i % 10 == 0) { // Check if $i is divisible by 10
$rdvProduct = new RDVProduct();
$rdvProduct->setRdv($rdv);
$rdvProduct->setProduct($productFind);
$this->em->persist($rdvProduct);
$rdv->addRdvProduct($rdvProduct);
}
}
elseif ($selectedFrequency == "every_eleventh") {
// Handle the case where you want every 1 of 11 RDV
if ($i % 11 == 0) { // Check if $i is divisible by 11
$rdvProduct = new RDVProduct();
$rdvProduct->setRdv($rdv);
$rdvProduct->setProduct($productFind);
$this->em->persist($rdvProduct);
$rdv->addRdvProduct($rdvProduct);
}
}
elseif ($selectedFrequency == "every_twelfth") {
// Handle the case where you want every 1 of 12 RDV
if ($i % 12 == 0) { // Check if $i is divisible by 12
$rdvProduct = new RDVProduct();
$rdvProduct->setRdv($rdv);
$rdvProduct->setProduct($productFind);
$this->em->persist($rdvProduct);
$rdv->addRdvProduct($rdvProduct);
}
}
}
}
$recurrence->addRdv($rdv);
$this->em->persist($recurrence);
$this->em->persist($rdv);
$i++;
// Increment the date by the number of weeks specified
$startDate->add(new \DateInterval('P' . $nbSemaine . 'W'));
}
$this->em->flush();
}
return $this->render('client/recurrence.html.twig', [
'client' => $client,
'products' => $productsAll,
'recurrence' => $recurrence,
'promoCodes' => $codePromos,
'sessionSalonDates' => $sessionSalonDates
]);
}
/**
* @Route("/{id}/generateRecurrence", name="client_generaterecurrence", methods={"GET","POST"})
*/
public function generateRecurrenceNew(Request $request, Client $client): Response
{
return $this->redirectToRoute('client_edit', ['id' => $client->getId()]);
}
/**
* @Route("/{id}", name="client_delete", methods={"DELETE"})
*/
public function delete(Request $request, Client $client): Response
{
if ($this->isCsrfTokenValid('delete' . $client->getId(), $request->request->get('_token'))) {
$entityManager = $this->getDoctrine()->getManager();
$entityManager->remove($client);
$entityManager->flush();
}
return $this->redirectToRoute('client_index');
}
/**
* @param FormInterface $form
* @throws \Exception
*/
private function generateRecurrence(FormInterface $form, $edit = false)
{
$contracts = $form->get('contract');
$entityManager = $this->getDoctrine()->getManager();
foreach ($contracts as $contract) {
$products = $contract->get('products')->getViewData();
/** @var Contract $contract */
$contract = $contract->getData();
$dateDeFinNew = date_create_from_format('d-m-Y', $contract->getDateFinRelation());
$uow = $entityManager->getUnitOfWork();
$oldContract = $uow->getOriginalEntityData($contract);
$oldDate = isset($oldContract['dateFinRelation']) ? $oldContract['dateFinRelation'] : null;
$dateDeFinOld = date_create_from_format('d-m-Y', $oldDate);
// createt all contract prroduct for this contract
$productsArrayEntities = [];
foreach ($products as $key => $product) {
$productE = $this->productRepository->find($product);
$contractProduct = new ContractProduct();
$contractProduct->setProduct($productE);
$contractProduct->setContract($contract);
$entityManager->persist($contractProduct);
$productsArrayEntities[] = $productE;
}
//$condition = $oldDate && $dateDeFinNew ? ($oldDate->format('d/m/Y') != $dateDeFinNew->format('d/m/Y') ): false;
// suppresion des recurrences en cas de date de fin
if ($edit && $contract->getRecurrenceGenerated() && $dateDeFinOld != $dateDeFinNew) {
foreach ($contract->getRdvs() as $rdv) {
if ($rdv->getStart() > $dateDeFinNew) {
$contract->removeRDV($rdv);
$entityManager->persist($contract);
$entityManager->remove($rdv);
}
}
$entityManager->flush();
}
if (!$contract->getRecurrenceGenerated() && $contract->getTypeRDV() === Contract::TYPE_RDV_PERIODIQUE) {
$intervenant = null;
$salon = null;
$start = $contract->getDateDebutRelation();
$end = $contract->getDateFinRelation();
$heure = $contract->getHeure();
$remarque = $contract->getRemarque();
if (!$start) {
continue;
}
//OK
$dateAdd = strtotime($start . ' ' . $heure); // date début contrat
if ($end) {
$endTime = strtotime($end . ' ' . $heure); //date fin contrat
} else {
// si ehpad RDV généré sur 4 ans
if ($contract->getClient()->getSite()->getType() === Site::TYPE_EHPAD) {
$endTime = strtotime('+4 year', strtotime($start));
} else {
$endTime = strtotime('+6 month', strtotime($start));
}
}
$client = $contract->getClient();
// ON RECUPERER LETAG DU PREMIER PRODUIT
$tag = null;
if (isset($productsArrayEntities[0])) {
/** @var Product $product */
$product = $productsArrayEntities[0];
$tag = $product->getType();
}
// get intervenant
$salons = $client->getSite()->getFirstSalonsByTag($tag);
if (!$salons->isEmpty() && $salons->first()) {
/** @var Salon $first */
$salon = $salons->first();
/** @var IntervenantSalon $intervenantSalon */
$intervenantSalon = $salon->getIntervenantSalons()->last();
if ($intervenantSalon) {
$intervenant = $intervenantSalon->getIntervenant();
}
}
// generate first one Le début et la fin sont le meme jour soit la date de début
$rdv = new RDV();
// recuperation du champ remarque
$rdv->setComment($remarque);
$rdv->setClient($client);
$datetime = new \DateTime();
//dump($dateAdd);
$rdv->setStart($datetime->setTimestamp($dateAdd));
$end = (new \DateTime())->setTimestamp($dateAdd);
$end->add(new \DateInterval('PT1H'));
$rdv->setEnd($end);
if ($salon) {
$rdv->setSalon($salon);
}
if ($intervenant) {
$rdv->setIntervenant($intervenant);
}
$rdv->setContract($contract);
$entityManager->persist($rdv);
foreach ($productsArrayEntities as $product) {
$rdvProduct = $this->createRDVProduct($product, $rdv);
$entityManager->persist($rdvProduct);
}
$i = 0;
$max = 1000;
// TODO : refactor
switch ($contract->getRecurrence()) {
case Contract::RECURRENCE_1_SUR_SEMAINE: {
while ($i < $max && $dateAdd < $endTime) {
$dateAdd = strtotime('+1 week', $dateAdd);
//dump(date('d/m/y',$dateAdd));
$rdv = new RDV();
$rdv->setClient($client);
$rdv->setComment($remarque);
$datetime = new \DateTime();
$rdv->setStart($datetime->setTimestamp($dateAdd));
$end = (new \DateTime())->setTimestamp($dateAdd);
$end->add(new \DateInterval('PT1H'));
$rdv->setEnd($end);
$rdv->setContract($contract);
$rdv->setPriorite(1);
if ($intervenant) {
$rdv->setIntervenant($intervenant);
}
if ($salon) {
$rdv->setSalon($salon);
}
$entityManager->persist($rdv);
foreach ($productsArrayEntities as $product) {
$rdvProduct = $this->createRDVProduct($product, $rdv);
$entityManager->persist($rdvProduct);
}
$i++;
}
break;
}
case Contract::RECURRENCE_1_SUR_2: {
// compare timestamp
while ($i < $max && $dateAdd < $endTime) {
$dateAdd = strtotime('+2 week', $dateAdd);
//dump(date('d/m/y',$dateAdd));
$rdv = new RDV();
$rdv->setClient($client);
$datetime = new \DateTime();
$rdv->setStart($datetime->setTimestamp($dateAdd));
$rdv->setComment($remarque);
$end = (new \DateTime())->setTimestamp($dateAdd);
$end->add(new \DateInterval('PT1H'));
$rdv->setEnd($end);
$rdv->setContract($contract);
$rdv->setPriorite(1);
if ($intervenant) {
$rdv->setIntervenant($intervenant);
}
if ($salon) {
$rdv->setSalon($salon);
}
$entityManager->persist($rdv);
foreach ($productsArrayEntities as $product) {
$rdvProduct = $this->createRDVProduct($product, $rdv);
$entityManager->persist($rdvProduct);
}
$i++;
}
//dump($i); // max 13 6 month
break;
}
case Contract::RECURRENCE_1_SUR_3: {
while ($i < $max && $dateAdd < $endTime) {
$dateAdd = strtotime('+3 week', $dateAdd);
//dump(date('d/m/y',$dateAdd));
$rdv = new RDV();
$rdv->setClient($client);
$datetime = new \DateTime();
$rdv->setStart($datetime->setTimestamp($dateAdd));
$rdv->setComment($remarque);
$end = (new \DateTime())->setTimestamp($dateAdd);
$end->add(new \DateInterval('PT1H'));
$rdv->setEnd($end);
$rdv->setContract($contract);
$rdv->setPriorite(2);
if ($intervenant) {
$rdv->setIntervenant($intervenant);
}
if ($salon) {
$rdv->setSalon($salon);
}
$entityManager->persist($rdv);
foreach ($productsArrayEntities as $product) {
$rdvProduct = $this->createRDVProduct($product, $rdv);
$entityManager->persist($rdvProduct);
}
$i++;
}
break;
}
case Contract::RECURRENCE_1_SUR_4: {
while ($i < $max && $dateAdd < $endTime) {
$dateAdd = strtotime('+4 week', $dateAdd);
//dump(date('d/m/y',$dateAdd));
$rdv = new RDV();
$rdv->setClient($client);
$datetime = new \DateTime();
$rdv->setStart($datetime->setTimestamp($dateAdd));
$rdv->setComment($remarque);
$end = (new \DateTime())->setTimestamp($dateAdd);
$end->add(new \DateInterval('PT1H'));
$rdv->setEnd($end);
$rdv->setContract($contract);
$rdv->setPriorite(2);
if ($intervenant) {
$rdv->setIntervenant($intervenant);
}
if ($salon) {
$rdv->setSalon($salon);
}
$entityManager->persist($rdv);
foreach ($productsArrayEntities as $product) {
$rdvProduct = $this->createRDVProduct($product, $rdv);
$entityManager->persist($rdvProduct);
}
$i++;
}
break;
}
case Contract::RECURRENCE_1_SUR_8: {
while ($i < $max && $dateAdd < $endTime) {
$dateAdd = strtotime('+8 week', $dateAdd);
//dump(date('d/m/y',$dateAdd));
$rdv = new RDV();
$rdv->setClient($client);
$datetime = new \DateTime();
$rdv->setStart($datetime->setTimestamp($dateAdd));
$rdv->setComment($remarque);
$end = (new \DateTime())->setTimestamp($dateAdd);
$end->add(new \DateInterval('PT1H'));
$rdv->setEnd($end);
$rdv->setContract($contract);
$rdv->setPriorite(2);
if ($intervenant) {
$rdv->setIntervenant($intervenant);
}
if ($salon) {
$rdv->setSalon($salon);
}
$entityManager->persist($rdv);
foreach ($productsArrayEntities as $product) {
$rdvProduct = $this->createRDVProduct($product, $rdv);
$entityManager->persist($rdvProduct);
}
$i++;
}
break;
}
case Contract::RECURRENCE_1_SUR_12: {
while ($i < $max && $dateAdd < $endTime) {
$dateAdd = strtotime('+12 week', $dateAdd);
//dump(date('d/m/y',$dateAdd));
$rdv = new RDV();
$rdv->setClient($client);
$datetime = new \DateTime();
$rdv->setStart($datetime->setTimestamp($dateAdd));
$end = (new \DateTime())->setTimestamp($dateAdd);
$end->add(new \DateInterval('PT1H'));
$rdv->setEnd($end);
$rdv->setComment($remarque);
$rdv->setContract($contract);
$rdv->setPriorite(2);
if ($intervenant) {
$rdv->setIntervenant($intervenant);
}
if ($salon) {
$rdv->setSalon($salon);
}
$entityManager->persist($rdv);
foreach ($productsArrayEntities as $product) {
$rdvProduct = $this->createRDVProduct($product, $rdv);
$entityManager->persist($rdvProduct);
}
$i++;
}
break;
}
case Contract::RECURRENCE_1_SUR_5: {
while ($i < $max && $dateAdd < $endTime) {
$dateAdd = strtotime('+5 week', $dateAdd);
//dump(date('d/m/y',$dateAdd));
$rdv = new RDV();
$rdv->setClient($client);
$datetime = new \DateTime();
$rdv->setStart($datetime->setTimestamp($dateAdd));
$end = (new \DateTime())->setTimestamp($dateAdd);
$end->add(new \DateInterval('PT1H'));
$rdv->setEnd($end);
$rdv->setComment($remarque);
$rdv->setContract($contract);
$rdv->setPriorite(2);
if ($intervenant) {
$rdv->setIntervenant($intervenant);
}
if ($salon) {
$rdv->setSalon($salon);
}
$entityManager->persist($rdv);
foreach ($productsArrayEntities as $product) {
$rdvProduct = $this->createRDVProduct($product, $rdv);
$entityManager->persist($rdvProduct);
}
$i++;
}
break;
}
case Contract::RECURRENCE_1_SUR_6: {
while ($i < $max && $dateAdd < $endTime) {
$dateAdd = strtotime('+6 week', $dateAdd);
//dump(date('d/m/y',$dateAdd));
$rdv = new RDV();
$rdv->setClient($client);
$datetime = new \DateTime();
$rdv->setStart($datetime->setTimestamp($dateAdd));
$end = (new \DateTime())->setTimestamp($dateAdd);
$end->add(new \DateInterval('PT1H'));
$rdv->setEnd($end);
$rdv->setComment($remarque);
$rdv->setContract($contract);
$rdv->setPriorite(2);
if ($intervenant) {
$rdv->setIntervenant($intervenant);
}
if ($salon) {
$rdv->setSalon($salon);
}
$entityManager->persist($rdv);
foreach ($productsArrayEntities as $product) {
$rdvProduct = $this->createRDVProduct($product, $rdv);
$entityManager->persist($rdvProduct);
}
$i++;
}
break;
}
case Contract::RECURRENCE_1_SUR_2_MONTH: {
while ($i < $max && $dateAdd < $endTime) {
$dateAdd = strtotime('+9 week', $dateAdd);
//dump(date('d/m/y',$dateAdd));
$rdv = new RDV();
$rdv->setClient($client);
$datetime = new \DateTime();
$rdv->setStart($datetime->setTimestamp($dateAdd));
$end = (new \DateTime())->setTimestamp($dateAdd);
$end->add(new \DateInterval('PT1H'));
$rdv->setEnd($end);
$rdv->setComment($remarque);
$rdv->setContract($contract);
$rdv->setPriorite(2);
if ($intervenant) {
$rdv->setIntervenant($intervenant);
}
if ($salon) {
$rdv->setSalon($salon);
}
$entityManager->persist($rdv);
foreach ($productsArrayEntities as $product) {
$rdvProduct = $this->createRDVProduct($product, $rdv);
$entityManager->persist($rdvProduct);
}
$i++;
}
break;
}
case Contract::RECURRENCE_1_SUR_TRIM: {
while ($i < $max && $dateAdd < $endTime) {
$dateAdd = strtotime('+13 week', $dateAdd);
//dump(date('d/m/y',$dateAdd));
$rdv = new RDV();
$rdv->setClient($client);
$datetime = new \DateTime();
$rdv->setStart($datetime->setTimestamp($dateAdd));
$end = (new \DateTime())->setTimestamp($dateAdd);
$end->add(new \DateInterval('PT1H'));
$rdv->setEnd($end);
$rdv->setComment($remarque);
$rdv->setContract($contract);
$rdv->setPriorite(2);
if ($intervenant) {
$rdv->setIntervenant($intervenant);
}
if ($salon) {
$rdv->setSalon($salon);
}
$entityManager->persist($rdv);
foreach ($productsArrayEntities as $product) {
$rdvProduct = $this->createRDVProduct($product, $rdv);
$entityManager->persist($rdvProduct);
}
$i++;
}
break;
}
case Contract::RECURRENCE_1_SUR_6_MONTH: {
while ($i < $max && $dateAdd < $endTime) {
$dateAdd = strtotime('+26 week', $dateAdd);
//dump(date('d/m/y',$dateAdd));
$rdv = new RDV();
$rdv->setClient($client);
$datetime = new \DateTime();
$rdv->setStart($datetime->setTimestamp($dateAdd));
$end = (new \DateTime())->setTimestamp($dateAdd);
$end->add(new \DateInterval('PT1H'));
$rdv->setEnd($end);
$rdv->setComment($remarque);
$rdv->setContract($contract);
$rdv->setPriorite(2);
if ($intervenant) {
$rdv->setIntervenant($intervenant);
}
if ($salon) {
$rdv->setSalon($salon);
}
$entityManager->persist($rdv);
foreach ($productsArrayEntities as $product) {
$rdvProduct = $this->createRDVProduct($product, $rdv);
$entityManager->persist($rdvProduct);
}
$i++;
}
break;
}
}
$contract->setRecurrenceGenerated(true);
}
}
$entityManager->flush();
}
/**
* @Route("/getProducts/{id}", methods={"GET"}, condition="request.isXmlHttpRequest()")
*/
public function ajaxGetProducts($id, SerializerInterface $serializer, ProductRepository $productRepository)
{
// dump('d'. $client->getSite()->getId());die;
$products = $productRepository->findBy([
'type' => strtolower($id)
]);
$result = $serializer->serialize($products, 'json', [
'circular_reference_handler' => function ($object) {
return $object->getId();
}
]);
return new JsonResponse($result, Response::HTTP_OK, [], true);
}
/**
* @required
* @param ProductRepository $productRepository
*/
public function setProductRepository(ProductRepository $productRepository)
{
$this->productRepository = $productRepository;
}
private function createRDVProduct(Product $product, RDV $RDV)
{
$rdvProduct = new RDVProduct();
$rdvProduct->setProduct($product);
$rdvProduct->setRdv($RDV);
return $rdvProduct;
}
private function getColumnsForEntity($class)
{
$columns[Client::class] = [
'Id' => function (Client $client) {
return $client->getId();
},
'Prénom' => function (Client $client) {
return $client->getFirstname();
},
'Nom' => function (Client $client) {
return $client->getLastname();
},
'Date de naissance' => function (Client $client) {
return $client->getBirthday();
},
'Date de Décès' => function (Client $client) {
return $client->getDeathday();
},
'Email' => function (Client $client) {
return $client->getEmail();
},
'Phone' => function (Client $client) {
return $client->getPhone();
},
'Commentaires' => function (Client $client) {
return $client->getComments();
},
'Numéro de chambre' => function (Client $client) {
return $client->getRoomNumber();
},
'Numéro de batiment' => function (Client $client) {
return $client->getBuildingRoom();
},
'Etages' => function (Client $client) {
return $client->getStairs();
},
'Civilite' => function (Client $client) {
return $client->getCivilite();
},
'Tuteur' => function (Client $client) {
return $client->getPrenomTuteur() . ' ' . $client->getNomTuteur();
},
'Adresse Tuteur' => function (Client $client) {
return $client->getAddressTuteur() . ' ' . $client->getAddressTuteur2() . ' ' . $client->getZipcode() . ' ' . $client->getCity();
},
// 'Mail notaire' => function (Client $client) {
// return $client->getEmailNotaire();
// },
'Email Tuteur' => function (Client $client) {
return $client->getEmailTuteur();
},
'Type Tuteur' => function (Client $client) {
return $client->getTypeTuteur();
},
'Numero tuteur' => function (Client $client) {
return $client->getNumeroTuteur();
},
'Compte bancaire' => function (Client $client) {
$bill = $client->getBillingInfos();
return $bill ? $bill->getAccount() : '';
},
'Banque' => function (Client $client) {
$bill = $client->getBillingInfos();
return $bill ? $bill->getBankName() : '';
},
'IBAN' => function (Client $client) {
$bill = $client->getBillingInfos();
return $bill ? $bill->getIban() : '';
},
'Bic' => function (Client $client) {
$bill = $client->getBillingInfos();
return $bill ? $bill->getBic() : '';
},
'RUM' => function (Client $client) {
$bill = $client->getBillingInfos();
return $bill ? $bill->getRum() : '';
},
'Mode de paiement' => function (Client $client) {
$bill = $client->getBillingInfos();
return $bill ? $bill->getBillingMode() : '';
},
'Mode de réglement' => function (Client $client) {
$bill = $client->getBillingInfos();
return $bill ? $bill->getPayMode() : '';
},
'Société' => function (Client $client) {
$company = null;
$bill = $client->getBillingInfos();
if ($bill) {
$company = $bill->getCompany();
}
return $company ? $client->getBillingInfos()->getCompany()->getName() : '';
},
'Status Prospect' => function (Client $client) {
return $client->getStatusProspect();
},
'Mail facturation' => function (Client $client) {
$bill = $client->getBillingInfos();
return $bill ? $client->getBillingInfos()->getEmail() : '';
},
'Tel facturation' => function (Client $client) {
$bill = $client->getBillingInfos();
return $bill ? $client->getBillingInfos()->getPhone() : '';
},
'Mode envoi' => function (Client $client) {
$bill = $client->getBillingInfos();
return $bill ? $bill->getSendMode() : '';
},
'Site' => function (Client $client) {
$siteName = $client->getSite() ? $client->getSite()->getName() : "";
return $siteName;
},
'Creation' => function (Client $client) {
return $client->getCreated()->format('d/m/Y');
},
// 'Contract' => function (Client $client) {
//
// $contractString = '';
// /** @var Contract $contrat */
// foreach ($client->getContract() as $contrat) {
// $contractString .= (string) $contrat->getId() . ' ';
// }
//
// return $contractString;
// },
'Type de RDV' => function (Client $client) {
/** @var RDV $rdv */
$rdv = $this->RDVManager->getRepository()->getLastRDVsByClient($client);
return $rdv && $rdv->getSalon() ? $rdv->getSalon()->getService(): "";
},
'Dernier RDV Date' => function (Client $client) {
$rdv = $this->RDVManager->getRepository()->getLastRDVsByClient($client);
return $rdv ? $rdv->getStart()->format('d/m/y') : "";
},
'Dernier RDV Heure' => function (Client $client) {
$rdv = $this->RDVManager->getRepository()->getLastRDVsByClient($client);
return $rdv ? $rdv->getStart()->format('H i') : "";
},
'Recurrence' => function (Client $client) {
$ids = [];
foreach ( $client->getRecurrences() as $recurrence){
$ids[]= $recurrence->getId();
}
/** @var RDV $rdv */
return implode(' ---- ',$ids);
},
'Recurrence type' => function (Client $client) {
$ids = [];
foreach ( $client->getRecurrences() as $recurrence){
$ids[]= $recurrence->getType();
}
/** @var RDV $rdv */
return implode(' ---- ',$ids);
},
];
if (array_key_exists($class, $columns)) {
return $columns[$class];
}
throw new \InvalidArgumentException(sprintf(
'No columns set for "%s" entity',
$class
));
}
}