<?php
namespace App\Controller\Api\Factory;
use App\Entity\Adherent\Annuaire\MagasinContact;
use App\Entity\Adherent\Magasin;
use App\Entity\Adherent\MagasinCollaborateurs;
use App\Entity\Adherent\MagasinCoordonnees;
use App\Entity\Adherent\MagasinEquipe;
use App\Entity\Adherent\MagasinMarques;
use App\Entity\Adherent\MagasinUrl;
use App\Entity\Image\Image;
use App\Entity\ImagePartner;
use App\Entity\OffresConso\OffreInscription;
use App\Entity\OffresConso\OffreWeb;
use App\Entity\Webfactory\Actualites\WebfactoryActualite;
use App\Entity\Webfactory\Actualites\WebfactoryActualiteCategory;
use App\Entity\Webfactory\AnnouncementBar;
use App\Entity\Webfactory\CustomCssJs;
use App\Entity\Webfactory\SeoVilles;
use App\Entity\Webfactory\SeoVillesContenus;
use App\Entity\Webfactory\WebfactoryFittingBoxImg;
use App\Entity\Webfactory\WebfactoryPage;
use App\Entity\Webfactory\WebfactoryWidget;
use App\Entity\Webfactory\Widget\SiteWebService;
use App\Entity\Webfactory\Widget\SiteWebSpecialite;
use App\Entity\Webfactory\Widget\WidgetAbstract;
use App\Enum\FactoryEnum;
use App\Helper\Factory\FactoryHelper;
use App\Helper\FiltersReviewsHelper;
use App\Manager\Crm\CrmAccessManager;
use App\Manager\Crm\RcuManager;
use App\Manager\DatasProgress;
use App\Manager\OpcManager;
use App\Manager\QueryProgress;
use App\Manager\Webfactory\MarquesManager;
use App\Manager\Webfactory\WebfactoryManager;
use App\Manager\WsProgressManager;
use Cocur\Slugify\Slugify;
use Doctrine\Common\Collections\Criteria;
use Doctrine\ORM\EntityManagerInterface;
use Doctrine\ORM\NonUniqueResultException;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;
use Symfony\Contracts\HttpClient\HttpClientInterface;
use Symfony\Contracts\Translation\TranslatorInterface;
/**
* @Route("/api/v1")
*/
class ApiWidgetsController extends AbstractController
{
private $entityManager;
private $wsProgressManager;
private $datasProgress;
private $webfactoryManager;
private $session;
private $translator;
private $factoryHelper;
private $rcuManager;
private $crmAccessManager;
private $cdnOpc;
private $opcManager;
private $marquesManager;
private $langs;
private $urlPhotosAdh;
/**
* @param EntityManagerInterface $entityManager
* @param WsProgressManager $wsProgressManager
* @param DatasProgress $datasProgress
* @param WebfactoryManager $webfactoryManager
* @param SessionInterface $session
*/
public function __construct(
FactoryHelper $factoryHelper,
EntityManagerInterface $entityManager,
WsProgressManager $wsProgressManager,
DatasProgress $datasProgress,
WebfactoryManager $webfactoryManager,
SessionInterface $session,
TranslatorInterface $translator,
RcuManager $rcuManager,
CrmAccessManager $crmAccessManager,
ParameterBagInterface $parameterBag,
OpcManager $opcManager,
MarquesManager $marquesManager,
private HttpClientInterface $client,
private FiltersReviewsHelper $filtersReviewsHelper
)
{
$this->entityManager = $entityManager;
$this->wsProgressManager = $wsProgressManager;
$this->datasProgress = $datasProgress;
$this->webfactoryManager = $webfactoryManager;
$this->session = $session;
$this->translator = $translator;
$this->factoryHelper = $factoryHelper;
$this->rcuManager = $rcuManager;
$this->crmAccessManager = $crmAccessManager;
$this->cdnOpc = $parameterBag->get('twicpics_domain_images_OPC');
$this->opcManager = $opcManager;
$this->marquesManager = $marquesManager;
$this->langs = ['fr', 'nl'];
$request = Request::createFromGlobals();
if ($request->getHttpHost() == "espace-adherent.groupeall.com" || $request->getHttpHost() == "api.groupeall.com") {
$this->urlPhotosAdh = $parameterBag->get('twicpics_domain_images_OPC') . 'adherent/';
$this->urlPhotosDefault = $parameterBag->get('twicpics_domain_images_OPC') . 'webfactory/fitting_box/';
$this->urlPhotosPrivateUpload = $parameterBag->get('twicpics_domain_images'). 'adherent/';
} elseif ($request->getHttpHost() == "espace-adherentpp.groupeall.com" || $request->getHttpHost() == "apipp.groupeall.com") {
$this->urlPhotosAdh = $request->getSchemeAndHttpHost() . "/privateUploads/photos_adh_web/";
$this->urlPhotosDefault = $request->getSchemeAndHttpHost() . "/build/images/webfactory/fitting_box/";
$this->urlPhotosPrivateUpload = $request->getSchemeAndHttpHost() . "/privateUploads/photos_adh_web/";
} else {
$this->urlPhotosAdh = $request->getSchemeAndHttpHost() . "/espace_adherent/public/privateUploads/photos_adh_web/";
$this->urlPhotosDefault = $request->getSchemeAndHttpHost() . "/espace_adherent/public/build/images/webfactory/fitting_box/";
$this->urlPhotosPrivateUpload = $request->getSchemeAndHttpHost() . "/espace_adherent/public/privateUploads/photos_adh_web/";
}
}
/**
* @Route("/magasin/{magasin}/widget/virtual_fitting", name="factory_api_widget_virtual_fitting")
* @param Request $request
* @param Magasin $magasin
* @return void
*/
public function widgetCabineEssayage(Request $request, Magasin $magasin)
{
$listBrands = $this->entityManager->getRepository(MagasinMarques::class)->findBy(['magasin' => $magasin]);
$tabListBrands = $this->marquesManager->formatTabListBrandsApi($listBrands, $magasin);
// ----------------------------------------- Gestion images fitting box -----------------------------------------------
$selectedFittingBoxImg = $this->entityManager->getRepository(WebfactoryFittingBoxImg::class)->findOneBy(['adherent' => $magasin->getKAdherent()]);
$finalTab = [];
foreach ($this->langs as $lang) {
$finalTab[strtolower($lang)] = [
"alt" => $this->translator->trans("Cabine d'essayage virtuelle", [], "messages", $lang),
"title" => $this->translator->trans("Essayez votre monture en ligne", [], "messages", $lang),
"button_text" => $this->translator->trans("Essayer maintenant", [], "messages", $lang),
"brands_slides" => [
'list' => $tabListBrands[strtolower($lang)]['list'],
'total' => $tabListBrands[strtolower($lang)]['total']
]
];
if ($selectedFittingBoxImg) {
if ($selectedFittingBoxImg->getImageDefault()){
$finalTab[strtolower($lang)]['image'] = $this->urlPhotosDefault . $selectedFittingBoxImg->getImageWidget();
} else {
$finalTab[strtolower($lang)]['image'] = $this->urlPhotosPrivateUpload . $magasin->getKAdherent() . "/". $selectedFittingBoxImg->getImageWidget();
}
} else {
$finalTab[strtolower($lang)]['image'] = $this->urlPhotosDefault . "widget_fitting_box_2.png";
}
}
return new JsonResponse($finalTab);
}
/**
* @param Magasin $magasin
* @return JsonResponse
* @Route("/magasin/{magasin}/widget/hours", name="factory_api_widget_hours")
*/
public function horaires(Magasin $magasin)
{
$datas = [
'fr' => $this->webfactoryManager->formatHoursForApi($magasin),
'nl' => $this->webfactoryManager->formatHoursForApi($magasin, "nl")
];
return new JsonResponse($datas);
}
/**
* @Route("/magasin/{magasin}/widget/store_presentation", name="factory_api_widget_store_presentation")
* @param Request $request
* @param Magasin $magasin
* @return JsonResponse
*/
public function widgetPresentationMagasin(Request $request, Magasin $magasin)
{
if (!$request->query->has('page')) {
return new JsonResponse(['status' => 400, 'error' => 'Paramètre page manquant'], 400);
}
$page = $request->query->get('page');
$page = $this->entityManager->getRepository(WebfactoryPage::class)->findOneBy(['id' => $page]);
$pageCustomId = $request->query->get('customPage');
$config = $this->webfactoryManager->getFactoryConfig($magasin->getKAdherent());
$opc = $this->webfactoryManager->getAffichageOpc($magasin->getKAdherent());
($magasin->getKNIVEAUADH() == "LOL4G") ? $esv = true : $esv = false;
$theme = $config['offer']['theme']['name'];
$widget = $this->entityManager->getRepository(WebfactoryWidget::class)->findOneBy(['identifier' => 'store_presentation']);
try {
$widgets = $this->entityManager->getRepository(WidgetAbstract::class)->findBy([
'magasin' => $magasin->getKAdherent(),
'page' => $page->getIdentifier(),
'theme' => $theme,
'widget' => $widget,
'pageCustom' => $pageCustomId
]);
} catch (\Exception $e) {
return new JsonResponse(['status' => 500, 'error' => $e->getMessage()], 500);
}
$datas = [];
if (!empty($widgets)) {
foreach ($widgets as $widgetDetail) {
$datas[strtolower($widgetDetail->getLang())] =
[
"title" => $widgetDetail->getTitle(),
"baseline" => $widgetDetail->getText(),
"button_text" => $widgetDetail->getButtonText(),
"button_url" => $widgetDetail->getButtonUrl(),
"perso_button_url" => $widgetDetail->getButtonUrlOther(),
"hours" => $widgetDetail->getHours(),
"images" => [
]
];
if ($esv) {
$datas[strtolower($widgetDetail->getLang())]['images'][] =
[
"src" => [
"mobile" => $this->cdnOpc . "images/logo/Expert_Sante_Visuelle-ESV-noir-petit-FR.svg",
"tablette" => $this->cdnOpc . "images/logo/Expert_Sante_Visuelle-ESV-noir-moyen-FR.svg",
"desktop" => $this->cdnOpc . "images/logo/Expert_Sante_Visuelle-ESV-noir-grand-FR.svg"
],
"alt" => "Logo du label Expert en santé visuelle",
"title" => "Expert en santé visuelle"
];
}
if ($opc) {
$datas[strtolower($widgetDetail->getLang())]['images'][] = [
"src" => [
"mobile" => $this->cdnOpc . "images/logo/OPC-vert-petit.svg",
"tablette" => $this->cdnOpc . "images/logo/OPC-vert-moyen.svg",
"desktop" => $this->cdnOpc . "images/logo/OPC-vert-grand.svg",
],
"alt" => "Logo Opticiens par conviction",
"title" => "Opticiens par conviction"
];
}
}
return new JsonResponse($datas);
} else {
return new JsonResponse(['status' => 400, 'error' => 'Aucun widget pour cette page'], 400);
}
}
/**
* @Route("/magasin/{magasin}/widget/contact", name="factory_api_widget_contact")
* @param Request $request
* @param Magasin $magasin
* @return void
*/
public function widgetCoordonnees(Request $request, Magasin $magasin)
{
$social_medias = $this->entityManager->getRepository(MagasinUrl::class)->findBy(['magasin' => $magasin]);
$socials = [];
$socialsNl = [];
if (!empty($social_medias)) {
foreach ($social_medias as $social_media) {
if ($social_media->getType() == "facebook" && !is_null($social_media->getUrl())) {
$currentSocial = [
"url" => $this->forceHttps($social_media->getUrl()),
"svg_name" => "facebook",
"icon" => file_get_contents($this->getParameter("images_directory") . '/webfactory/svg/facebook.svg'),
"type" => "facebook",
"title" => "Voir notre compte Facebook"
];
$socials[] = $currentSocial;
$currentSocial['title'] = "Zie onze Facebook-account";
$socialsNl = $currentSocial;
}
if ($social_media->getType() == "twitter" && !is_null($social_media->getUrl())) {
$currentSocial = [
"url" => $this->forceHttps($social_media->getUrl()),
"svg_name" => "twitter",
"icon" => file_get_contents($this->getParameter("images_directory") . '/webfactory/svg/twitter.svg'),
"type" => "twitter",
"title" => "Voir notre compte Twitter"
];
$socials[] = $currentSocial;
$currentSocial['title'] = "Zie onze Twitter-account";
$socialsNl = $currentSocial;
}
if ($social_media->getType() == "instagram" && !is_null($social_media->getUrl())) {
$currentSocial = [
"url" => $this->forceHttps($social_media->getUrl()),
"svg_name" => "instagram",
"icon" => file_get_contents($this->getParameter("images_directory") . '/webfactory/svg/instagram.svg'),
"type" => "instagram",
"title" => "Voir notre profil Instagram"
];
$socials[] = $currentSocial;
$currentSocial['title'] = "Zie onze Instagram-account";
$socialsNl = $currentSocial;
}
if ($social_media->getType() == "tiktok" && !is_null($social_media->getUrl())) {
$currentSocial = [
"url" => $this->forceHttps($social_media->getUrl()),
"svg_name" => "tiktok",
"icon" => file_get_contents($this->getParameter("images_directory") . '/webfactory/svg/tiktok.svg'),
"type" => "tiktok",
"title" => "Voir notre profil TikTok"
];
$socials[] = $currentSocial;
$currentSocial['title'] = "Zie onze TikTok-account";
$socialsNl = $currentSocial;
}
}
}
$ficheCoordonnees = $this->entityManager->getRepository(MagasinCoordonnees::class)->findOneBy(
['K_ADHERENT' => $magasin->getKAdherent(), 'TYPE' => 'MARKETING']);
if (empty($ficheCoordonnees)) {
$ficheCoordonnees = $this->entityManager->getRepository(MagasinCoordonnees::class)->findOneBy(
['K_ADHERENT' => $magasin->getKAdherent(), 'TYPE' => 'MAGASIN']);
if (empty($ficheCoordonnees)) {
$ficheCoordonnees = $this->entityManager->getRepository(MagasinCoordonnees::class)->findOneBy(
['K_ADHERENT' => $magasin->getKAdherent(), 'TYPE' => 'SIEGE']);
}
}
// Mails pour "Envoyer un message"
$magasinContactsEmails = $this->entityManager->getRepository(MagasinContact::class)->getSpecificContact($magasin, 'site_web_emails_contacts', true, false, true);
// Numéro de téléphone pour la prise de contact
$telDeContact = $this->entityManager->getRepository(MagasinContact::class)->getSpecificContact($magasin, 'site_web_tel_contact');
$urlMagasin = $this->entityManager->getRepository(MagasinUrl::class)->findOneBy(['magasin' => $magasin, 'type' => 'OPC/OZC']);
$urlRdv = $this->entityManager->getRepository(MagasinUrl::class)->findOneBy(['magasin' => $magasin, 'type' => 'rdv']);
$contactsFr = [];
$contactsNl = [];
if (!is_null($ficheCoordonnees)) {
// Prise de rdv
preg_match("/(opticiens-oc.be\/nl\/*)|(:8082)/", $urlMagasin->getUrl(), $matches);
if (!empty($matches)) {
$urlRdvOPC = $urlMagasin->getUrl() . '/maak-een-afspraak';
} else {
$urlRdvOPC = $urlMagasin->getUrl() . '/prise-de-rdv';
}
$priseRdv = [
"title" => "Prendre RDV",
"svg_name" => "calendar-time",
"icon" => file_get_contents($this->getParameter("images_directory") . '/webfactory/svg/calendar-week.svg'),
"content" => null,
"button_text" => "Prendre RDV",
"link" => (!is_null($urlRdv)) ? $urlRdv->getUrl() : $urlRdvOPC,
"target" => "_blank",
"type" => "rdv",
'rel' => 'nofollow'
];
$contactsFr[] = $priseRdv;
$priseRdv['title'] = "Afspraak";
$priseRdv['button_text'] = "Lees meer";
$contactsNl[] = $priseRdv;
//Y aller
$destination = urlencode(strtolower($ficheCoordonnees->getLib() . " " . trim($ficheCoordonnees->getVOIENUM() . ' ' . $ficheCoordonnees->getVOIETYPE() . ' ' . $ficheCoordonnees->getVOIELIB()) . "," . $ficheCoordonnees->getKCP() . "," . $ficheCoordonnees->getKVILLE()));
$urlYAller = "https://www.google.com/maps/dir/?api=1&destination=" . $destination . "&travelmode=driving";
$voieCplt = (!is_null($ficheCoordonnees->getVOIECPLT())) ? $ficheCoordonnees->getVOIECPLT() : "";
$content = $ficheCoordonnees->getVOIENUM() . " " . $voieCplt . " " . $ficheCoordonnees->getVOIETYPE() . " " . $ficheCoordonnees->getVOIELIB() . "<br>" . $ficheCoordonnees->getKCP() . " " . $ficheCoordonnees->getKVILLE();
$yAller = [
"title" => "S'y rendre",
"svg_name" => "location",
"icon" => file_get_contents($this->getParameter("images_directory") . '/webfactory/svg/geo-alt.svg'),
"content" => $content,
"button_text" => "S'y rendre",
"link" => $urlYAller,
"target" => "_blank",
"type" => "location",
"street" => $ficheCoordonnees->getVOIENUM() . " " . $ficheCoordonnees->getVOIETYPE() . " " . $ficheCoordonnees->getVOIELIB(),
"zipcode" => $ficheCoordonnees->getKCP(),
"city" => $ficheCoordonnees->getKVILLE(),
"country" => $ficheCoordonnees->getKPAYS(),
"lib" => $ficheCoordonnees->getLib()
];
$contactsFr[] = $yAller;
$yAller['title'] = "Route";
$yAller['button_text'] = "Lees meer";
$contactsNl[] = $yAller;
// Appeler
if (!is_null($telDeContact)) {
$indicatifs = ['+33', '+32', '+590', '+596', '+262', '+377'];
foreach ($indicatifs as $indicatif) {
if (str_starts_with($telDeContact->getValue(), $indicatif)) {
$telDeContactVisible = substr($telDeContact->getValue(), strlen($indicatif));
// clear
$telDeContactVisible = preg_replace('/\D/', '', $telDeContactVisible);
if ($telDeContactVisible[0] !== '0') {
$telDeContactVisible = '0' . $telDeContactVisible;
}
break;
}
}
// formatage espace entre 2
$telDeContactVisible = trim(chunk_split($telDeContactVisible, 2, ' '));
$appeler = [
"title" => "Appeler",
"svg_name" => "phone",
"icon" => file_get_contents($this->getParameter("images_directory") . '/webfactory/svg/telephone-fill.svg'),
"content" => $telDeContactVisible,
"button_text" => $telDeContactVisible,
"link" => "tel:" . str_replace(" ", "", $telDeContact->getValue()),
"target" => null,
"type" => "phone"
];
$contactsFr[] = $appeler;
$appeler['title'] = "Bel";
$appeler['button_text'] = $telDeContactVisible;
$contactsNl[] = $appeler;
}
// Mail
if (!empty($magasinContactsEmails)) {
$mails = $magasinContactsEmails;
$envoieMail = [
"title" => "Envoyer un e-mail",
"svg_name" => "mail",
"icon" => file_get_contents($this->getParameter("images_directory") . '/webfactory/svg/send.svg'),
"content" => $mails,
"button_text" => "Nous contacter",
// "link" => "mailto:" . rtrim($mails, ";"),
"link" => "/contact",
"target" => null,
"type" => "mail"
];
$contactsFr[] = $envoieMail;
$envoieMail['title'] = "Stuur een e-mail";
$envoieMail['button_text'] = "Neem contact op";
$contactsNl[] = $envoieMail;
}
}
$contact_fr = [
"title" => "Contactez-nous",
"svg_name" => "clock",
"icon" => file_get_contents($this->getParameter("images_directory") . '/webfactory/svg/clock.svg'),
"contacts" => $contactsFr,
'socials' => $socials
];
$contact_nl = [
"title" => "Neem contact op",
"svg_name" => "clock",
"icon" => "<svg width='18' height='20' viewBox='0 0 18 20'><path d='M15,2h0V0H13V2H5V0H3V2H3A3,3,0,0,0,0,5V17a3,3,0,0,0,3,3H15a3,3,0,0,0,3-3V5A3,3,0,0,0,15,2Zm1,14.83a1,1,0,0,1-1,1H3a1,1,0,0,1-1-1v-10a1,1,0,0,1,1-1H15a1,1,0,0,1,1,1Z'/></svg>",
"contacts" => $contactsNl,
'socials' => $socialsNl
];
$datas = [
'fr' => $contact_fr,
'nl' => $contact_nl
];
return new JsonResponse($datas);
}
/**
* @Route("/magasin/{magasin}/widget/social_networks", name="factory_api_widget_social_networks")
* @param Request $request
* @param Magasin $magasin
* @return void
*/
public function widgetSocialNetwork(Request $request, Magasin $magasin)
{
$social_medias = $this->entityManager->getRepository(MagasinUrl::class)->findBy(['magasin' => $magasin]);
$socials = [];
$socialsNl = [];
$allowTypes = ['facebook', 'twitter', 'instagram', 'youtube', 'linkedin', 'whatsapp', 'tiktok'];
if (!empty($social_medias)) {
foreach ($social_medias as $social_media) {
if (in_array($social_media->getType(), $allowTypes) && !is_null($social_media->getUrl())) {
$currentSocial = [
"url" => $this->forceHttps($social_media->getUrl()),
"svg_name" => strtolower($social_media->getType()),
"icon" => file_get_contents($this->getParameter("images_directory") . '/webfactory/svg/' . strtolower($social_media->getType()) . '.svg'),
"type" => strtolower($social_media->getType()),
"title" => "Voir notre compte " . ucfirst($social_media->getType()),
];
$socials[] = $currentSocial;
$currentSocial['title'] = "Zie onze " . ucfirst($social_media->getType()) . "-account";
$socialsNl[] = $currentSocial;
}
}
}
$contact_fr = [
'socials' => $socials
];
$contact_nl = [
'socials' => $socialsNl
];
$datas = [
'fr' => $contact_fr,
'nl' => $contact_nl
];
return new JsonResponse($datas);
}
/**
* @Route("/magasin/{magasin}/widget/brands", name="factory_api_widget_brands")
* @param Request $request
* @param Magasin $magasin
* @return void
*/
public function widgetMarques(Request $request, Magasin $magasin)
{
$config = $this->webfactoryManager->getFactoryConfig($magasin->getKAdherent());
$theme = $config['offer']['theme']['name'];
$entityName = "App\Entity\Webfactory\\Widget\\" . $theme . "\\Brands";
$widgets = $this->entityManager->getRepository($entityName)->findBy(['magasin' => $magasin]);
$brands = [
'fr' => ['widget' => [], 'categories' => [], 'total' => 0],
'nl' => ['widget' => [], 'categories' => [], 'total' => 0]
];
if (!empty($widgets)) {
foreach ($widgets as $widget) {
$brands[strtolower($widget->getLang())] = [
"widget" => [
"title" => $widget->getTitle(),
"description" => $widget->getDescription(),
"image" => $this->urlPhotosAdh . $magasin->getKAdherent() . '/' . $widget->getImage(),
"button" => $widget->getButton()
],
"categories" => [],
"total" => 0
];
}
}
return new JsonResponse($brands);
}
/**
* @Route("/magasin/{magasin}/widget/list-brands", name="factory_api_widget_list_marques")
* @param Request $request
* @param Magasin $magasin
* @return JsonResponse
*/
public function widgetListMarques(Request $request, Magasin $magasin): JsonResponse
{
// ?limit=9&page=0
$limit = ($request->query->has('limit')) ? intval($request->query->get('limit')) : 100;
$page = ($request->query->has('page')) ? intval($request->query->get('page')) : 1;
if ($page <= 1) {
$offset = 0;
} else {
$offset = $page * $limit - $limit;
}
$config = $this->webfactoryManager->getFactoryConfig($magasin->getKAdherent());
$theme = $config['offer']['theme']['name'];
$entityName = "App\Entity\Webfactory\\Widget\\" . $theme . "\\Brands";
$widgets = $this->entityManager->getRepository($entityName)->findBy(['magasin' => $magasin]);
$finalTab = [];
if (!empty($widgets)) {
foreach ($widgets as $widget) {
$finalTab[strtolower($widget->getLang())] = [
"title" => $widget->getTitle(),
"description" => $widget->getDescription(),
"bouton_text" => $widget->getButton(),
"url" => (strtolower($widget->getLang()) == "nl") ? '/merken' : '/marques',
'list' => []
];
$listBrands = $widget->getListBrands();
$criteria = Criteria::create()->where(Criteria::expr()->in("id", array_slice($listBrands, $offset, $limit)));
$magMarques = $this->entityManager->getRepository(MagasinMarques::class)->matching($criteria)->getValues();
$tabListBrands = $this->marquesManager->formatTabListBrandsApi($magMarques);
$finalTab[strtolower($widget->getLang())]['list'] = $tabListBrands[strtolower($widget->getLang())]['list'];
}
}
return new JsonResponse($finalTab);
}
/**
* @Route("/magasin/{magasin}/widget/deals", name="factory_api_widget_deals")
* @param Request $request
* @param Magasin $magasin
* @return JsonResponse
*/
public function widgetDeals(Request $request, Magasin $magasin)
{
$date = new \DateTime('now');
$year = $date->format('Y');
$previousYear = $date->sub(new \DateInterval("P1Y"));
$prev_year = $previousYear->format("Y");
$anneeLimitTraitement = $year - 2;
$offres_inscription = $this->entityManager->getRepository(OffreInscription::class)->findBy(['adherent' => $magasin->getKAdherent(), 'tag' => [$year, $prev_year]]);
$address = $this->entityManager->getRepository(MagasinCoordonnees::class)->findOneBy([
'K_ADHERENT' => $magasin->getKAdherent(),
'TYPE' => 'MAGASIN'
]);
if (empty($address)) {
$address = $this->entityManager->getRepository(MagasinCoordonnees::class)->findOneBy(['K_ADHERENT' => $magasin->getKAdherent(), 'TYPE' => 'SIEGE']);
}
$details['deals'] = [];
if (!empty($offres_inscription)) {
foreach ($offres_inscription as $inscription) {
if (substr($inscription->getTag(), 0, 4) > $anneeLimitTraitement) {
$list_insc = json_decode($inscription->getOffres());
foreach ($list_insc as $insc) {
$offre = $this->entityManager->getRepository(OffreWeb::class)->findOneBy(['code' => $insc]);
$debut = $offre->getDateDebut();
$fin = $offre->getDateFin();
$tag = substr($offre->getTag(), 0, 4);
if (date("Y-m-d h:m:s") >= $debut->format('Y-m-d h:m:s') && date("Y-m-d h:m:s") <= $fin->format('Y-m-d h:m:s')) {
$infosOffre = [
"src" => $this->getParameter("twicpics_domain_images_OPC") . "offres-web/" . $tag . "/640x338/" . $offre->getPays() . "/" . $offre->getFileEmail(),
"alt" => $offre->getTexte(),
"title" => $offre->getTexte(),
"slug_title" => $offre->getName(),
"url" => $this->opcManager->getAdhOpcUrl($address),
"legals" => $offre->getMentions(),
"type" => $offre->getType() == 'P' ? 'headline' : 'season',
"uid" => $offre->getTag() . $insc,
"year" => $offre->getTag(),
"seo" => [
"title" => ucfirst(strtolower($magasin->getLib())) . " - " . $offre->getName(),
"description" => $offre->getTexte(),
"keywords" => ""
],
'rel' => 'nofollow'
];
if ($offre->getType() === "S") {
$details['current'][] = $infosOffre;
} else {
$details['deals'][] = $infosOffre;
}
}
}
}
}
}
$dealsYear = [
"title" => "Découvrez nos offres",
"subtitle" => "valables toute l'année",
"button_text" => "Voir nos bons plans",
"button_url" => $this->opcManager->getAdhOpcUrl($address),
"deals" => $details['deals']
];
$dealCurrent = [
"title" => "Découvrez notre offre",
"subtitle" => "du moment",
"button_text" => "Voir nos bons plans",
"button_url" => $this->opcManager->getAdhOpcUrl($address),
"deal" => (array_key_exists('current', $details)) ? $details['current'] : []
];
$datas = [
'fr' => [
'current' => (array_key_exists('current', $details)) ? $dealCurrent : [],
'year' => (!empty($details['deals'])) ? $dealsYear : [],
'slug' => "offres",
'slug_translated' => 'deals',
],
'nl' => [
'current' => (array_key_exists('current', $details)) ? $dealCurrent : [],
'year' => (!empty($details['deals'])) ? $dealsYear : [],
'slug' => "deals",
'slug_translated' => 'offres',
]
];
return new JsonResponse($datas);
}
/**
* @Route("/magasin/{magasin}/widget/teams", name="factory_api_widget_teams")
* @param Request $request
* @param Magasin $magasin
* @return void
*/
public function widgetTeams(Request $request, Magasin $magasin)
{
$datas = [
'fr' => [],
'nl' => []
];
$config = $this->webfactoryManager->getFactoryConfig($magasin->getKAdherent());
$theme = $config['offer']['theme']['name'];
$entityName = "App\Entity\Webfactory\\Widget\\" . $theme . "\\Teams";
$widgetTeams = $this->entityManager->getRepository($entityName)->findBy(['magasin' => $magasin->getKAdherent()]);
$magasinEquipe = $this->entityManager->getRepository(MagasinEquipe::class)->findOneBy(['magasin' => $magasin->getKAdherent()]);
if (!empty($widgetTeams)) {
foreach ($widgetTeams as $widgetTeam) {
$verbatim = [
"quote" => "",
"from" => ""
];
if (!is_null($magasinEquipe)) {
if (strtolower($widgetTeam->getLang()) === "fr") {
$verbatim["quote"] = $magasinEquipe->getVerbatim();
$verbatim["from"] = "L'équipe " . ucfirst(strtolower($magasin->getLib()));
} else {
$verbatim["quote"] = $magasinEquipe->getVerbatimNl();
$verbatim["from"] = "Het " . ucfirst(strtolower($magasin->getLib())) . " team";
}
}
$widget = [
"title" => $widgetTeam->getEquipeTitre(),
"description" => $widgetTeam->getEquipeDescription(),
"button_text" => $widgetTeam->getButtonText(),
"verbatim" => $verbatim
];
$detail = [
"image" => [
[
"media" => [
"mobile" => (!is_null($magasinEquipe)) ? $this->urlPhotosAdh . $magasin->getKAdherent() . "/" . $magasinEquipe->getPhotoEquipe() : "",
"desktop" => (!is_null($magasinEquipe)) ? $this->urlPhotosAdh . $magasin->getKAdherent() . "/" . $magasinEquipe->getPhotoEquipe() : "",
],
"alt" => "",
"title" => ""
]
],
"title" => "",
"description" => "",
"seo" => [
"title" => "",
"description" => "",
"keywords" => ""
]
];
$teams = [];
$arrayIdCollabo = $widgetTeam->getEquipeList();
$collaborateurs = $this->entityManager->getRepository(MagasinCollaborateurs::class)->findByArrayId($arrayIdCollabo);
foreach ($collaborateurs as $collaborateur) {
$teams[] = [
"image" => [
"small" => (!is_null($collaborateur->getImage())) ? $this->urlPhotosAdh . $magasin->getKAdherent() . "/" . $collaborateur->getImage() : $this->cdnOpc . 'webfactory/default/' . FactoryEnum::ProfileImage,
"big" => (!is_null($collaborateur->getImage())) ? $this->urlPhotosAdh . $magasin->getKAdherent() . "/" . $collaborateur->getImage() : $this->cdnOpc . 'webfactory/default/' . FactoryEnum::ProfileImage
],
"alt" => $collaborateur->getImage(),
"title" => $collaborateur->getImage(),
"name" => $collaborateur->getLastName(),
"firstname" => $collaborateur->getFirstName(),
"job" => (strtolower($widgetTeam->getLang()) === "fr") ? $collaborateur->getJobs() : $collaborateur->getJobsNl(),
"skills" => (strtolower($widgetTeam->getLang()) === "fr") ? $collaborateur->getSpecialties() : $collaborateur->getSpecialtiesNl(),
"presentation" => (strtolower($widgetTeam->getLang()) === "fr") ? $collaborateur->getPresentation() : $collaborateur->getPresentationNl(),
"verbatim" => (strtolower($widgetTeam->getLang()) === "fr") ? $collaborateur->getVerbatim() : $collaborateur->getVerbatimNl()
];
}
$team = [
'widget' => $widget,
"details" => $detail,
"teams" => $teams
];
(strtolower($widgetTeam->getLang()) === "fr") ? $datas['fr'][] = $team : $datas['nl'][] = $team;
}
}
return new JsonResponse($datas);
}
/**
* @Route("/magasin/{magasin}/widget/crm_reviews", name="factory_api_widget_crm_reviews")
* @Route("/magasin/{magasin}/page/reviews_detail", name="factory_api_page_reviews_detail")
* @param Request $request
* @param Magasin $magasin
* @return void
* @throws \Exception
*/
public function widgetCrmReviews(Request $request, Magasin $magasin)
{
$queryParams = $request->query->all();
$limit = (!empty($queryParams && array_key_exists('limit', $queryParams))) ? intval($queryParams['limit']) : 3;
$offset = (!empty($queryParams && array_key_exists('offset', $queryParams))) ? intval($queryParams['offset']) : 0;
// Vérification si adhérent a le CRM ou des avis GMB
$CRM_infos = $this->crmAccessManager->checkAccessCrm($magasin->getKAdherent(), null);
$avisGmb = $magasin->isAvisGmbActive();
$data['statutAvisGMB'] = false;
$listAvis = [];
$noteAvis = [];
if ($avisGmb) {
$data['statutAvisGMB'] = true;
}
if ($magasin->getKAdherent() == "C9920") {
$CRM_infos["access"] = true;
$CRM_infos["avis_crm"] = true;
}
// Contrat CRM valide, a des avis et souhaite les afficher
if ($CRM_infos['access'] && $CRM_infos['avis_crm']) {
$query = (new QueryProgress("quest_ach_indiv"))
->where('K_QUEST', '=', 'SAT')
->andWhere("K_ADHERENT", '=', ($magasin->getKAdherent() == "C9920") ? "C3571" : $magasin->getKAdherent())
->orderBy('D_CREE', 'DESC')
->limit(0, 5000);
$allAvis = $this->rcuManager->findAvis($query);
foreach ($allAvis as &$data) {
// Traitement du tableau QUEST_L
$quest = [];
if ($data['QUEST_L']) {
foreach ($data['QUEST_L'] as $quest_l) {
$quest[$quest_l["K_QUEST_L"]] = ['val' => $quest_l['VAL'], 'date' => $quest_l['D_CREE']];
}
$data['QUEST_L'] = $quest;
// Gestion des variables réutilisables
$commentaire = (isset($data['QUEST_L']['experience_opticien_commentaire']['val'])) ? addslashes($data['QUEST_L']['experience_opticien_commentaire']['val']) : "";
$reponse = (isset($data['QUEST_L']['experience_opticien_commentaire_rep']['val'])) ? addslashes($data['QUEST_L']['experience_opticien_commentaire_rep']['val']) : "";
$d_cree = new \DateTime($data['D_CREE']);
$now = new \DateTime('2021-04-27');
$autoPublicationDate = new \DateTime('2024-02-20');
// Application des CGU le 27/04/2021
// Avant le 27/04
if ($d_cree->getTimestamp() < $now->getTimestamp()) {
//On crée le tableau que si l'avis peut être publié
if (isset($data['QUEST_L']['publication_avis']['val']) && $data['QUEST_L']['publication_avis']['val'] == 1 && !isset($data['QUEST_L']['publication_OPC']['val'])) {
$listAvis[] = [
"name" => $data['PRENOM'] . " " . $data['NOM'][0],
"fr" => $commentaire,
"nl" => $commentaire,
"lang" => "fr",
"rating" => $data['QUEST_L']['experience_opticien']['val'],
"answer" => $reponse,
"date" => $data['D_CREE'],
"origin" => "Groupe All"
];
}
} else {
// A partir du 20/02/2024 les avis sont publiés automatiquement
//On crée le tableau que si l'avis peut être publié en acceptant les CGU
if (
(isset($data['QUEST_L']['cgu']['val']) &&
(isset($data['QUEST_L']['publication_avis']['val']) &&
$data['QUEST_L']['publication_avis']['val'] == "1") &&
($data['QUEST_L']['cgu']['val'] == 'yes' || $data['QUEST_L']['cgu']['val'] == '1') &&
!isset($data['QUEST_L']['publication_OPC']['val']))
|| $d_cree->getTimestamp() >= $autoPublicationDate->getTimestamp()
) {
$listAvis[] = [
"name" => $data['PRENOM'] . " " . $data['NOM'][0],
"fr" => $commentaire,
"nl" => $commentaire,
"lang" => "fr",
"rating" => (int)$data['QUEST_L']['experience_opticien']['val'],
"answer" => $reponse,
"date" => $data['D_CREE'],
"origin" => "Groupe All"
];
}
}
}
}
}
if (!empty($listAvis)) {
//Somme des notes de l'adhérent
$notes = 0;
foreach ($listAvis as $k => $v) {
$notes += $v['rating'];
}
$noteAvis['total'] = count($listAvis);
$noteAvis['note'] = floor($notes / count($listAvis) * 10) / 10;
$noteAvis['detail']['five'] = $this->filtersReviewsHelper->countStarsReview($listAvis, 5);
$noteAvis['detail']['four'] = $this->filtersReviewsHelper->countStarsReview($listAvis, 4);
$noteAvis['detail']['three'] = $this->filtersReviewsHelper->countStarsReview($listAvis, 3);
$noteAvis['detail']['two'] = $this->filtersReviewsHelper->countStarsReview($listAvis, 2);
$noteAvis['detail']['one'] = $this->filtersReviewsHelper->countStarsReview($listAvis, 1);
}
$rating = [
"total_rating" => $noteAvis ? $noteAvis['total'] : null,
"average_rating" => $noteAvis ? $noteAvis['note'] : null,
'detailed_rating' => $noteAvis ? $noteAvis['detail'] : null,
"ratings" => $listAvis,
"limited_ratings" => $limit ? array_slice($listAvis, $offset, $limit) : null,
"image" => $this->cdnOpc . "webfactory/pages/Details-avis.png",
"lang" => [
"fr" => [
"title" => "Découvrez",
"subtitle" => "nos avis clients"
],
"nl" => [
"title" => "Ontdek",
"subtitle" => "onze klantenbeoordelingen"
]
]
];
return new JsonResponse($rating);
}
/**
* @Route("/magasin/{magasin}/widget/crm_reviews_by_note", name="factory_api_widget_crm_reviews_by_note")
* @param Request $request
* @param Magasin $magasin
* @return void
* @throws \Exception
*/
public function widgetCrmReviewsByNote(Request $request, Magasin $magasin)
{
$queryParams = $request->query->all();
$note = intval($queryParams['note']);
$limit = (!empty($queryParams && array_key_exists('limit', $queryParams))) ? intval($queryParams['limit']) : null;
$offset = (!empty($queryParams && array_key_exists('offset', $queryParams))) ? intval($queryParams['offset']) : 0;
// Vérification si adhérent a le CRM ou des avis GMB
$CRM_infos = $this->crmAccessManager->checkAccessCrm($magasin->getKAdherent(), null);
$avisGmb = $magasin->isAvisGmbActive();
$data['statutAvisGMB'] = false;
$listAvis = [];
$noteAvis = [];
if ($avisGmb) {
$data['statutAvisGMB'] = true;
}
if ($magasin->getKAdherent() == "C9920") {
$CRM_infos["access"] = true;
$CRM_infos["avis_crm"] = true;
}
// Contrat CRM valide, a des avis et souhaite les afficher
if ($CRM_infos['access'] && $CRM_infos['avis_crm']) {
$query = (new QueryProgress("quest_ach_indiv"))
->where('K_QUEST', '=', 'SAT')
->andWhere("K_ADHERENT", '=', ($magasin->getKAdherent() == "C9920") ? "C3571" : $magasin->getKAdherent())
->orderBy('D_CREE', 'DESC')
->limit(0, 5000);
$allAvis = $this->rcuManager->findAvis($query);
foreach ($allAvis as &$data) {
// Traitement du tableau QUEST_L
$quest = [];
if ($data['QUEST_L']) {
foreach ($data['QUEST_L'] as $quest_l) {
$quest[$quest_l["K_QUEST_L"]] = ['val' => $quest_l['VAL'], 'date' => $quest_l['D_CREE']];
}
$data['QUEST_L'] = $quest;
// Gestion des variables réutilisables
$commentaire = (isset($data['QUEST_L']['experience_opticien_commentaire']['val'])) ? addslashes($data['QUEST_L']['experience_opticien_commentaire']['val']) : "";
$d_cree = new \DateTime($data['D_CREE']);
$now = new \DateTime('2021-04-27');
$autoPublicationDate = new \DateTime('2024-02-20');
// Application des CGU le 27/04/2021
// Avant le 27/04
if ($d_cree->getTimestamp() < $now->getTimestamp()) {
//On crée le tableau que si l'avis peut être publié
if (isset($data['QUEST_L']['publication_avis']['val']) && $data['QUEST_L']['publication_avis']['val'] == 1 && !isset($data['QUEST_L']['publication_OPC']['val'])) {
if ($note == $data['QUEST_L']['experience_opticien']['val']) {
$listAvis[] = [
"name" => $data['PRENOM'] . " " . $data['NOM'][0],
"fr" => $commentaire,
"nl" => $commentaire,
"lang" => "fr",
"rating" => $data['QUEST_L']['experience_opticien']['val'],
"date" => $data['D_CREE'],
"origin" => "Groupe All"
];
}
}
} else {
// A partir du 20/02/2024 les avis sont publiés automatiquement
//On crée le tableau que si l'avis peut être publié en acceptant les CGU
if (
(isset($data['QUEST_L']['cgu']['val']) &&
(isset($data['QUEST_L']['publication_avis']['val']) &&
$data['QUEST_L']['publication_avis']['val'] == "1") &&
($data['QUEST_L']['cgu']['val'] == 'yes' || $data['QUEST_L']['cgu']['val'] == '1') &&
!isset($data['QUEST_L']['publication_OPC']['val']))
|| $d_cree->getTimestamp() >= $autoPublicationDate->getTimestamp()
) {
if ($note == $data['QUEST_L']['experience_opticien']['val']) {
$listAvis[] = [
"name" => $data['PRENOM'] . " " . $data['NOM'][0],
"fr" => $commentaire,
"nl" => $commentaire,
"lang" => "fr",
"rating" => (int)$data['QUEST_L']['experience_opticien']['val'],
"date" => $data['D_CREE'],
"origin" => "Groupe All"
];
}
}
}
}
}
}
$rating = [
"ratings" => $listAvis,
"limited_ratings" => $limit ? array_slice($listAvis, $offset, $limit) : null,
"nb_notes" => count($listAvis),
"lang" => [
"fr" => [
"title" => "Découvrez",
"subtitle" => "Nos avis clients"
],
"nl" => [
"title" => "Ontdek",
"subtitle" => "Onze klantenbeoordelingen"
]
]
];
return new JsonResponse($rating);
}
/**
* @Route("/magasin/{magasin}/widget/news", name="factory_api_widget_news")
* @param Request $request
* @param Magasin $magasin
* @return void
*/
public function widgetNews(Request $request, Magasin $magasin)
{
$queryParams = $request->query->all();
$limit = (!empty($queryParams && array_key_exists('limit', $queryParams))) ? intval($queryParams['limit']) : 4;
$page = (!empty($queryParams && array_key_exists('page', $queryParams))) ? intval($queryParams['page']) : 0;
$categoryiD = (!empty($queryParams && array_key_exists('category', $queryParams))) ? intval($queryParams['category']) : null;
$lang = (!empty($queryParams && array_key_exists('lang', $queryParams))) ? strtolower($queryParams['lang']) : 'fr';
$offset = ($page > 1) ? ($page * $limit - $limit) : 0;
$articles = [];
if (!is_null($categoryiD) && $categoryiD != 0) {
$category = $this->entityManager->getRepository(WebfactoryActualiteCategory::class)->findOneBy(['id' => $categoryiD]);
if (!is_null($category)) {
$dataArticles = $this->entityManager->getRepository(WebfactoryActualite::class)->paginateArticlesByCategory($magasin, $offset, $limit, $category->getId(), $lang);
} else {
return new JsonResponse('Catégorie inconnue');
}
} else {
$datas = $this->entityManager->getRepository(WebfactoryActualite::class)->findBy(['adherent' => $magasin->getKAdherent(), 'active' => true], ['updated_at' => 'DESC'], $limit, $offset);
$dataArticles['articles'] = $datas;
}
foreach ($dataArticles['articles'] as $article) {
foreach ($article->getWebfactoryActualiteContenus() as $contenu) {
if ($contenu->getStatut() != "brouillon"
&& (
(is_null($contenu->getDateDebutpublication()) && is_null($contenu->getDateFinPublication()))
|| ($contenu->getDateDebutpublication() <= new \DateTime('today'))
|| ($contenu->getDateDebutpublication() <= new \DateTime('today') && $contenu->getDateFinPublication() >= new \DateTime('today'))
)
) {
$categoryContenu = $article->getActualiteCategory()?->getContenuByLang($lang);
$articles[strtolower($contenu->getLang())][] = [
"id" => $article->getId(),
"slug" => $contenu->getSlug(),
"title" => $contenu->getTitle(),
"short_description" => html_entity_decode($contenu->getShortDescription()),
"description" => $contenu->getContent(),
"date" => $contenu->getDateDebutPublication() ? strtotime($contenu->getDateDebutPublication()->format('Y-m-d H:i:s')) : strtotime($contenu->getCreatedAt()->format('Y-m-d H:i:s')),
"author" => $article->getAuthor(),
"lang" => strtolower($contenu->getLang()),
"categories" => [
[
"title" => ($categoryContenu) ? $categoryContenu->getName() : "",
"id" => ($article->getActualiteCategory()) ? $article->getActualiteCategory()->getId() : "",
'lang' => strtolower($contenu->getLang())
]
],
"src" => ($article->isLockCopie()) ? $this->cdnOpc . "articlesPrerediges/" . $contenu->getImage() : $this->cdnOpc . 'adherent/' . $article->getAdherent() . "/" . $contenu->getImage()
];
}
}
}
$datas = [
'fr' => [
"news" => (array_key_exists('fr', $articles)) ? $articles['fr'] : [],
"seo" => [
"title" => "",
"description" => "",
"keywords" => ""
],
"total" => (array_key_exists('fr', $articles)) ? count($articles['fr']) : 0
],
'nl' => [
"news" => (array_key_exists('nl', $articles)) ? $articles['nl'] : [],
"seo" => [
"title" => "",
"description" => "",
"keywords" => ""
],
"total" => (array_key_exists('nl', $articles)) ? count($articles['nl']) : 0
]
];
return new JsonResponse($datas);
}
/**
* @Route("/magasin/{magasin}/widget/lastnews", name="factory_api_widget_lastnews")
* @param Request $request
* @param Magasin $magasin
* @return void
*/
public function widgetLastNews(Request $request, Magasin $magasin)
{
$limit = 4;
$articlesFr = [];
$articlesNl = [];
$articles = $this->entityManager->getRepository(WebfactoryActualite::class)->findLastActu($magasin, $limit);
foreach ($articles as $article) {
foreach ($article->getWebfactoryActualiteContenus() as $contenu) {
if ($contenu->getStatut() != "brouillon"
&& (
(is_null($contenu->getDateDebutpublication()) && is_null($contenu->getDateFinPublication()))
|| ($contenu->getDateDebutpublication() <= new \DateTime('today'))
|| ($contenu->getDateDebutpublication() <= new \DateTime('today') && $contenu->getDateFinPublication() >= new \DateTime('today'))
)
) {
$categoryContenu = $article->getActualiteCategory()?->getContenuByLang($contenu->getLang());
$art = [
"id" => $article->getId(),
"slug" => $contenu->getSlug(),
"title" => $contenu->getTitle(),
"lang" => strtolower($contenu->getLang()),
"short_description" => html_entity_decode($contenu->getShortDescription()),
"date" => strtotime($contenu->getCreatedAt()->format('Y-m-d H:i:s')),
"author" => $article->getAuthor(),
"categories" => [
[
"title" => ($categoryContenu) ? $categoryContenu->getName() : "",
"id" => ($article->getActualiteCategory()) ? $article->getActualiteCategory()->getId() : "",
'lang' => strtolower($contenu->getLang())
]
],
"src" => ($article->isLockCopie()) ? $this->cdnOpc . "articlesPrerediges/" . $contenu->getImage() : $this->urlPhotosAdh . $article->getAdherent() . "/" . $contenu->getImage()
];
(strtolower($contenu->getLang()) === "fr") ? $articlesFr[] = $art : $articlesNl[] = $art;
}
}
}
$datas = [
'fr' => [
"last_news" => $articlesFr
],
'nl' => [
"last_news" => $articlesNl
],
];
return new JsonResponse($datas);
}
/**
* @Route("/magasin/{magasin}/widget/news/categories", name="factory_api_widget_categories")
* @param Request $request
* @param Magasin $magasin
* @return JsonResponse
*/
public function widgetCategories(Request $request, Magasin $magasin)
{
$categoriesFr = [];
$categoriesNl = [];
$nbTotalNews = ['fr' => 0, 'nl' => 0];
$categoriesFrNl = $this->entityManager->getRepository(WebfactoryActualiteCategory::class)->findBy(['adherent' => $magasin]);
foreach ($categoriesFrNl as $categorie) {
foreach ($categorie->getWebfactoryActualiteCategoryContenus() as $contenu) {
$categ = [
"name" => $contenu->getName(),
"id" => $categorie->getId(),
"slug" => $contenu->getSlug(),
"total" => count($categorie->getWebfactoryActualites()->toArray())
/* "lang" => $categorie->getLang(),
'correspondance' => (!is_null($categorie->getCorrespondance())) ? $categorie->getCorrespondance()->getId() : null*/
];
$nbTotalNews[strtolower($contenu->getLang())] += count($categorie->getWebfactoryActualites()->toArray());
(strtolower($contenu->getLang()) === "fr") ? $categoriesFr[] = $categ : $categoriesNl[] = $categ;
}
}
array_unshift($categoriesFr, ['name' => 'Toutes', 'id' => 0, 'slug' => 'toutes', 'total' => $nbTotalNews['fr']]);
array_unshift($categoriesNl, ['name' => 'alle', 'id' => 0, 'slug' => 'alle', 'total' => $nbTotalNews['nl']]);
$datas = [
'fr' => [
"categories" => $categoriesFr
],
'nl' => [
"categories" => $categoriesNl
],
];
return new JsonResponse($datas);
}
/**
* @Route("/magasin/{magasin}/widget/news/{slug}", name="factory_api_widget_news_detail")
* @param Magasin $magasin
* @param null $slug
* @return void
* @throws NonUniqueResultException
*/
public function widgetNewsDetail(Magasin $magasin, $slug = null)
{
$article = $this->entityManager->getRepository(WebfactoryActualite::class)->createQueryBuilder('a')
->join('a.webfactoryActualiteContenus', 'ac', 'ac.article')
->where('ac.slug = :slug')
->andWhere('a.adherent = :adherent')
->andWhere('ac.statut != :statut OR ac.statut IS NULL')
->setParameter('slug', $slug)
->setParameter('adherent', $magasin)
->setParameter('statut', 'brouillon')
->getQuery()->getOneOrNullResult();
if (!is_null($article)) {
foreach ($article->getWebfactoryActualiteContenus() as $contenu) {
$categoryContent = $article->getActualiteCategory()?->getContenuByLang($contenu->getLang());
$news[strtolower($contenu->getLang())] = [
"id" => $article->getId(),
"slug" => $contenu->getSlug(),
"title" => $contenu->getTitle(),
"image" => [
"mobile" => ($article->isLockCopie()) ? $this->cdnOpc . "articlesPrerediges/" . $contenu->getImage() : $this->urlPhotosAdh . $magasin->getKAdherent() . "/" . $contenu->getImage(),
"desktop" => ($article->isLockCopie()) ? $this->cdnOpc . "articlesPrerediges/" . $contenu->getImage() : $this->urlPhotosAdh . $magasin->getKAdherent() . "/" . $contenu->getImage(),
"alt" => $contenu->getTitle(),
"title" => $contenu->getTitle()
],
"description1" => $contenu->getContent(),
"description2" => "",
"date" => $contenu->getDateDebutPublication() ? $contenu->getDateDebutPublication()->format('Y-m-d H:i:s') : $contenu->getUpdatedAt()->format('Y-m-d H:i:s'),
"author" => $article->getAuthor(),
"author_job" => (strtolower(strtolower($contenu->getLang())) === "nl") ? "Het team van " . $magasin->getLib() : "L'équipe de " . $magasin->getLib(),
"lang" => strtolower($contenu->getLang()),
"categories" => [
[
"title" => (isset($categoryContent)) ? $categoryContent->getName() : "",
"id" => (isset($categoryContent)) ? $article->getActualiteCategory()->getId() : "",
'lang' => (isset($categoryContent)) ? strtolower($categoryContent->getLang()) : "",
]
],
"seo" => [
"title" => $contenu->getMetatitle(),
"description" => $contenu->getMetaDesc(),
"keywords" => $contenu->getMetaKeywords()
]
];
}
$datas = [
'fr' => (array_key_exists('fr', $news)) ? $news['fr'] : [],
'nl' => (array_key_exists('nl', $news)) ? $news['nl'] : []
];
return new JsonResponse($datas);
}
return new JsonResponse('Article introuvable');
}
/**
* @Route("/magasin/{magasin}/widget/banner", name="factory_api_widget_banner")
* @param Request $request
* @param Magasin $magasin
* @return void
*/
public function widgetAnnouncementBar(Request $request, Magasin $magasin)
{
$datas = [
'fr' => [
'banner' => []
],
'nl' => [
'banner' => []
],
];
if (!is_null($magasin)) {
$announcementBars = $this->entityManager->getRepository(AnnouncementBar::class)->findBy(['magasin' => $magasin]);
foreach ($announcementBars as $announcementBar) {
$options = $announcementBar->getOptions()->toArray();
foreach ($options as $option) {
$banner = [];
switch ($option->getChoice()) {
case 'texte_libre':
$banner = [
"type" => $option->getChoice(),
"content" => $option->getContent(),
"url" => $option->getUrl(),
"target" => $option->getTarget(),
"rating" => null,
"author" => null
];
break;
case 'rdv':
$urlRdv = $this->entityManager->getRepository(MagasinUrl::class)->findOneBy(['magasin' => $magasin, 'type' => 'rdv']);
// Prise de rdv
$urlMagasin = $this->entityManager->getRepository(MagasinUrl::class)->findOneBy(['magasin' => $magasin, 'type' => 'OPC/OZC']);
preg_match("/(opticiens-oc.be\/nl\/*)/", $urlMagasin->getUrl(), $matches);
if (!empty($matches)) {
$slugrdv = $urlMagasin->getUrl() . '/maak-een-afspraak';
} else {
$slugrdv = $urlMagasin->getUrl() . '/prise-de-rdv';
}
$urlRDV = (!is_null($urlRdv)) ? $urlRdv->getUrl() : $slugrdv;
$banner = [
"type" => $option->getChoice(),
"content" => $option->getContent(),
"url" => $urlRDV,
"target" => $option->getTarget(),
"rating" => null,
"author" => null,
'rel' => 'nofollow'
];
break;
case 'avis_CRM':
if (!is_null($option->getAvisCrm())) {
$avis = json_decode($option->getAvisCrm(), true);
$content = [
"date" => $avis['D_CREE'],
"comment" => $avis['COMMENT']
];
$banner = [
"type" => $option->getChoice(),
"content" => $content,
"url" => null,
"target" => $option->getTarget(),
"rating" => $avis['NOTE'],
"author" => $avis['AUTEUR']
];
}
break;
case 'offers':
$banner = [
"type" => $option->getChoice(),
"content" => json_decode($option->getOffreWeb()),
"url" => null,
"target" => $option->getTarget(),
"rating" => null,
"author" => null
];
break;
}
if (strtolower($announcementBar->getLang()) === "fr") {
$datas['fr']['banner'][] = $banner;
} else {
$datas['nl']['banner'][] = $banner;
}
}
}
}
return new JsonResponse($datas);
}
/**
* @Route("/magasin/{magasin}/widget/stores", name="factory_api_widget_stores")
* @param Request $request
* @param Magasin $magasin
* @return void
*/
public function widgetStores(Request $request, Magasin $magasin)
{
$stores = [];
$seoFr = [
"title" => "",
"description" => "",
"keywords" => ""
];
$seoNl = $seoFr;
$magasins = $this->entityManager->getRepository(Magasin::class)->findBy(['adhMmStat' => $magasin->getAdhMmStat()]);
foreach ($magasins as $magasin) {
foreach ($magasin->getMagasinCoordonnees() as $adresse) {
if (strtoupper($adresse->getTYPE()) === "MAGASIN") {
$entityName = "App\Entity\Webfactory\\Page\\Classique\\Store";
$pageMagasins = $this->entityManager->getRepository($entityName)->findBy(['magasin' => $magasin->getKADHERENT()]);
foreach ($pageMagasins as $pageMagasin) {
if (strtolower($pageMagasin->getLang()) === "fr") {
$seoFr = [
"title" => (empty($seo['title'])) ? $pageMagasin->getMetatitle() : $seo['title'],
"description" => (empty($seo['description'])) ? $pageMagasin->getMetadescription() : $seo['description'],
"keywords" => (empty($seo['keywords'])) ? $pageMagasin->getMetakeywords() : $seo['keywords']
];
} else {
$seoNl = [
"title" => (empty($seo['title'])) ? $pageMagasin->getMetatitle() : $seo['title'],
"description" => (empty($seo['description'])) ? $pageMagasin->getMetadescription() : $seo['description'],
"keywords" => (empty($seo['keywords'])) ? $pageMagasin->getMetakeywords() : $seo['keywords']
];
}
}
$rue = ((!empty($adresse->getVOIENUM())) ? $adresse->getVOIENUM() . ' ' : '') .
((!empty($adresse->getVOIECPLT())) ? $adresse->getVOIECPLT() . ' ' : '') .
((!empty($adresse->getVOIETYPE())) ? $adresse->getVOIETYPE() . ' ' : '') .
((!empty($adresse->getVOIELIB())) ? $adresse->getVOIELIB() : '');
// Image
$imageMags = $this->entityManager->getRepository(Image::class)->findOneBy([
'adherent' => $magasin->getKADHERENT(),
'profileDefault' => true
]);
$stores[] = [
"name" => $adresse->getLIB(),
"address" => $rue,
"address_2" => null,
"postal_code" => $adresse->getKCP(),
"city" => $adresse->getKVILLE(),
"src" => $imageMags != null ? $this->urlPhotosAdh . $adresse->getKAdherent() . "/" . $imageMags->getName() : null,
"code" => $adresse->getKADHERENT(),
"hours" => $this->webfactoryManager->formatHoursForApi($magasin),
];
}
}
}
$datas = [
'fr' => [
"stores" => $stores,
"seo" => $seoFr
],
'nl' => [
"stores" => $stores,
"seo" => $seoNl
]
];
return new JsonResponse($datas);
}
/**
* @Route("/magasin/{magasin}/widget/more_about", name="factory_api_widget_more_about")
* @param Request $request
* @param Magasin $magasin
* @return void
* MULTIPAGE !
*/
public function widgetMoreAbout(Request $request, Magasin $magasin)
{
if (!$request->query->has('page')) {
return new JsonResponse(['status' => 400, 'error' => 'Paramètre page manquant'], 400);
}
$page = $request->query->get('page');
$page = $this->entityManager->getRepository(WebfactoryPage::class)->findOneBy(['id' => $page]);
$pageCustomId = $request->query->get('customPage');
$config = $this->webfactoryManager->getFactoryConfig($magasin->getKAdherent());
$theme = $config['offer']['theme']['name'];
$widget = $this->entityManager->getRepository(WebfactoryWidget::class)->findOneBy(['identifier' => 'more_about']);
$widgets = $this->entityManager->getRepository(WidgetAbstract::class)->findBy([
'magasin' => $magasin->getKAdherent(),
'page' => $page->getIdentifier(),
'theme' => $theme,
'widget' => $widget,
'pageCustom' => $pageCustomId
]);
$datas = ['fr' => [], 'nl' => []];
if (!empty($widgets)) {
foreach ($widgets as $widgetDetails) {
$datas[strtolower($widgetDetails->getLang())] = [
'title' => $widgetDetails->getText(),
'link' => $widgetDetails->getLink(),
"perso_link" => $widgetDetails->getLinkOther(),
'image' => $this->urlPhotosAdh . $magasin->getKAdherent() . "/" . $widgetDetails->getImage(),
'target' => '_blank',
"button" => $this->translator->trans("En savoir plus", [], 'messages', $widgetDetails->getLang())
];
}
return new JsonResponse($datas);
} else {
return new JsonResponse(['status' => 400, 'error' => 'Aucun widget pour cette page'], 400);
}
}
/**
* @Route("/magasin/{magasin}/widget/custom_text", name="factory_api_widget_custom_text")
* @param Request $request
* @param Magasin $magasin
* @return void
* MULTIPAGE !
*/
public function widgetCustomText(Request $request, Magasin $magasin)
{
if (!$request->query->has('page')) {
return new JsonResponse(['status' => 400, 'error' => 'Paramètre page manquant'], 400);
}
$page = $request->query->get('page');
$page = $this->entityManager->getRepository(WebfactoryPage::class)->findOneBy(['id' => $page]);
$pageCustomId = $request->query->get('customPage');
$config = $this->webfactoryManager->getFactoryConfig($magasin->getKAdherent());
$theme = $config['offer']['theme']['name'];
$widget = $this->entityManager->getRepository(WebfactoryWidget::class)->findOneBy(['identifier' => 'custom_text']);
$widgetDetails = $this->entityManager->getRepository(WidgetAbstract::class)->findBy([
'magasin' => $magasin->getKAdherent(),
'page' => $page->getIdentifier(),
'theme' => $theme,
'widget' => $widget,
'pageCustom' => $pageCustomId
]);
$datas['fr']['content'] = [];
$datas['nl']['content'] = [];
if (!empty($widgetDetails)) {
foreach ($widgetDetails as $widgetDetail) {
$datas[strtolower($widgetDetail->getLang())]['content'] = $widgetDetail->getContent();
}
}
return new JsonResponse($datas);
}
/**
* @Route("/magasin/{magasin}/widget/gallery", name="factory_api_widget_gallery")
* @param Request $request
* @param Magasin $magasin
* @return void
* MULTIPAGE
*/
public function widgetGallery(Request $request, Magasin $magasin)
{
if (!$request->query->has('page')) {
return new JsonResponse(['status' => 400, 'error' => 'Paramètre page manquant'], 400);
}
$page = $request->query->get('page');
$page = $this->entityManager->getRepository(WebfactoryPage::class)->findOneBy(['id' => $page]);
$pageCustomId = $request->query->get('customPage');
$config = $this->webfactoryManager->getFactoryConfig($magasin->getKAdherent());
$theme = $config['offer']['theme']['name'];
$widget = $this->entityManager->getRepository(WebfactoryWidget::class)->findOneBy(['identifier' => 'gallery']);
$widgetDetails = $this->entityManager->getRepository(WidgetAbstract::class)->findBy([
'magasin' => $magasin->getKAdherent(),
'page' => $page->getIdentifier(),
'theme' => $theme,
'widget' => $widget,
'pageCustom' => $pageCustomId
]);
$datas['fr']['images'] = [];
$datas['nl']['images'] = [];
if (!empty($widgetDetails)) {
foreach ($widgetDetails as $widgetDetail) {
if (!empty($widgetDetail->getImages()->toArray())) {
$images = $widgetDetail->getImages()->toArray();
foreach ($images as $image) {
if (intval($image->getWidth()) > intval($image->getHeight())) {
$orientation = "landscape";
} else {
$orientation = "portrait";
}
$datas[strtolower($widgetDetail->getLang())]['images'][] = [
"media" => [
"mobile" => $this->urlPhotosAdh . $magasin->getKAdherent() . "/" . $image->getName(),
"desktop" => $this->urlPhotosAdh . $magasin->getKAdherent() . "/" . $image->getName(),
],
"alt" => $image->getAlt(),
"title" => str_replace("." . $image->getExtension(), "", $image->getName()),
'orientation' => $orientation,
];
}
$datas[strtolower($widgetDetail->getLang())]['affichage'] = $widgetDetail->getTypeAffichagePhotos();
$datas[strtolower($widgetDetail->getLang())]['slider_slide_to_show'] = $widgetDetail->getSliderSlideToShow();
}
}
}
return new JsonResponse($datas);
}
/**
* @Route("/magasin/{magasin}/widget/esv", name="factory_api_widget_esv")
* @param Request $request
* @param Magasin $magasin
* @return void
*/
public function widgetESV(Request $request, Magasin $magasin)
{
if ($magasin->getKNIVEAUADH() === "LOL4G") {
$esv = [
'fr' => [
"title" => "Expert santé visuelle",
"blocks" => [
[
"title" => "Experts santé visuelle qui sont-ils ?",
"svg_name" => "bullseye",
"icon" => file_get_contents($this->getParameter("images_directory") . "/icons/bxs-bullseye.svg.svg"),
"button_text" => "En savoir plus",
"link" => "https://www.opticiensparconviction.fr/les-experts-en-sante-visuelle",
"target" => "_blank",
'rel' => 'nofollow'
],
[
"title" => "Ce qu’il faut savoir<br />Prix, qualité...",
"svg_name" => "purchase-tag",
"icon" => file_get_contents($this->getParameter("images_directory") . "/icons/bxs-purchase-tag.svg.svg"),
"button_text" => "En savoir plus",
"link" => "https://www.expertsantevisuelle.com/prix-qualite-remboursement/payer-le-bon-prix",
"target" => "_blank",
'rel' => 'nofollow'
],
[
"title" => "Clins d’oeil, infos, astuces, conseils...",
"svg_name" => "info-circle",
"icon" => file_get_contents($this->getParameter("images_directory") . "/icons/bxs-info-circle.svg.svg"),
"button_text" => "En savoir plus",
"link" => "https://www.expertsantevisuelle.com/clin-oeil",
"target" => "_blank",
'rel' => 'nofollow'
]
]
],
'nl' => []
];
return new JsonResponse($esv);
} else {
return new JsonResponse(['status' => 400, 'error' => 'Adhérent non ESV'], 400);
}
}
/**
* @Route("/magasin/{magasin}/widget/services_specialties", name="factory_api_widget_services_specialties")
* @param Request $request
* @param Magasin $magasin
* @return void
*/
public function widgetServicesEtSpecialities(Request $request, Magasin $magasin)
{
$services = $this->entityManager->getRepository(SiteWebService::class)->findBy(['kAdh' => $magasin], ['sort' => 'ASC']);
$specialites = $this->entityManager->getRepository(SiteWebSpecialite::class)->findBy(['kAdh' => $magasin], ['sort' => 'ASC']);
$datas = [];
$datas['fr']['widgets']['services_specialties'][] = [
'subtitle' => "Notre expertise à votre service",
'subdescription' => "Dans notre magasin, nous mettons à votre disposition une palette de services et de spécialités afin de vous garantir une expérience unique."
];
$datas['nl']['widgets']['services_specialties'][] = [
'subtitle' => "Onze expertise tot uw dienst",
'subdescription' => "In onze winkel bieden wij een waaier van diensten en specialiteiten aan om een unieke ervaring te garanderen."
];
foreach ($services as $serv) {
$datas['fr']['widgets']['services_specialties']['services'][] = [
"name" => $serv->getIdService()->getName(),
"svg_name" => $serv->getIdService()->getSvg(),
'icon' => (!is_null($serv->getIdService()->getSvg())) ? file_get_contents($this->getParameter("images_directory") . '/webfactory/svg/' . $serv->getIdService()->getSvg()) : ""
];
$datas['nl']['widgets']['services_specialties']['services'][] = [
"name" => $this->translator->trans($serv->getIdService()->getName(), [], 'messages', 'nl'),
"svg_name" => $serv->getIdService()->getSvg(),
'icon' => (!is_null($serv->getIdService()->getSvg())) ? file_get_contents($this->getParameter("images_directory") . '/webfactory/svg/' . $serv->getIdService()->getSvg()) : ""
];
}
foreach ($specialites as $spec) {
$datas['fr']['widgets']['services_specialties']['specialites'][] = [
"name" => $spec->getIdSpecialite()->getName(),
"svg_name" => $spec->getIdSpecialite()->getSvg(),
'icon' => (!is_null($spec->getIdSpecialite()->getSvg())) ? file_get_contents($this->getParameter("images_directory") . '/webfactory/svg/' . $spec->getIdSpecialite()->getSvg() . ".svg") : ""
];
$datas['nl']['widgets']['services_specialties']['specialites'][] = [
"name" => $this->translator->trans($spec->getIdSpecialite()->getName(), [], 'messages', 'nl'),
"svg_name" => $spec->getIdSpecialite()->getSvg(),
'icon' => (!is_null($spec->getIdSpecialite()->getSvg())) ? file_get_contents($this->getParameter("images_directory") . '/webfactory/svg/' . $spec->getIdSpecialite()->getSvg() . ".svg") : ""
];
}
return new JsonResponse($datas);
}
/**
* @Route("/magasin/{magasin}/widget/verbatim", name="factory_api_widget_verbatim")
* @param Request $request
* @param Magasin $magasin
* @return void
* MULTIPAGE !
*/
public function widgetVerbatim(Request $request, Magasin $magasin)
{
if (!$request->query->has('page')) {
return new JsonResponse(['status' => 400, 'error' => 'Paramètre page manquant'], 400);
}
$page = $request->query->get('page');
$page = $this->entityManager->getRepository(WebfactoryPage::class)->findOneBy(['id' => $page]);
$pageCustomId = $request->query->get('customPage');
$config = $this->webfactoryManager->getFactoryConfig($magasin->getKAdherent());
$theme = $config['offer']['theme']['name'];
$widget = $this->entityManager->getRepository(WebfactoryWidget::class)->findOneBy(['identifier' => 'verbatim']);
$widgets = $this->entityManager->getRepository(WidgetAbstract::class)->findBy([
'magasin' => $magasin->getKAdherent(),
'page' => $page->getIdentifier(),
'theme' => $theme,
'widget' => $widget,
'pageCustom' => $pageCustomId
]);
$datas = [];
foreach ($widgets as $widget) {
$datas[strtolower($widget->getLang())][] = [
'quote' => $widget->getConviction(),
'from' => $widget->getAuthor()
];
}
return new JsonResponse($datas);
}
/**
* @Route("/magasin/{magasin}/widget/promote", name="factory_api_widget_promote")
* @param Request $request
* @param Magasin $magasin
* @return JsonResponse
* MULTIPAGE !
*/
public function widgetPromote(Request $request, Magasin $magasin)
{
if (!$request->query->has('page')) {
return new JsonResponse(['status' => 400, 'error' => 'Paramètre page manquant'], 400);
}
$page = $request->query->get('page');
$page = $this->entityManager->getRepository(WebfactoryPage::class)->findOneBy(['id' => $page]);
$pageCustomId = $request->query->get('customPage');
$config = $this->webfactoryManager->getFactoryConfig($magasin->getKAdherent());
$theme = $config['offer']['theme']['name'];
$widget = $this->entityManager->getRepository(WebfactoryWidget::class)->findOneBy(['identifier' => 'promote']);
$widgets = $this->entityManager->getRepository(WidgetAbstract::class)->findBy([
'magasin' => $magasin->getKAdherent(),
'page' => $page->getIdentifier(),
'theme' => $theme,
'widget' => $widget,
'pageCustom' => $pageCustomId
]);
$datas = [];
if (!empty($widgets)) {
foreach ($widgets as $widgetDetail) {
$datas[strtolower($widgetDetail->getLang())] = [
"first" => [
"title" => $widgetDetail->getDiscoveryTitle1(),
"button_text" => $widgetDetail->getDiscoveryBtnText1(),
"link" => $widgetDetail->getDiscoveryBtnUrl1(),
"perso_link" => $widgetDetail->getDiscoveryBtnUrlOther1(),
"images" => [
"image" => (!is_null($widgetDetail->getDiscoveryImg1())) ? $this->urlPhotosAdh . $magasin->getKAdherent() . "/" . $widgetDetail->getDiscoveryImg1() : null,
"alt" => (!is_null($widgetDetail->getDiscoveryImg1())) ? "Image de présentation" : null,
"title" => (!is_null($widgetDetail->getDiscoveryImg1())) ? "Image de présentation" : null
]
],
"second" => [
"title" => $widgetDetail->getDiscoveryTitle2(),
"button_text" => $widgetDetail->getDiscoveryBtnText2(),
"link" => $widgetDetail->getDiscoveryBtnUrl2(),
"perso_link" => $widgetDetail->getDiscoveryBtnUrlOther2(),
"images" => [
"image" => (!is_null($widgetDetail->getDiscoveryImg2())) ? $this->urlPhotosAdh . $magasin->getKAdherent() . "/" . $widgetDetail->getDiscoveryImg2() : null,
"alt" => (!is_null($widgetDetail->getDiscoveryImg2())) ? "Image de présentation" : null,
"title" => (!is_null($widgetDetail->getDiscoveryImg2())) ? "Image de présentation" : null
]
]
];
}
return new JsonResponse($datas);
} else {
return new JsonResponse(['status' => 400, 'error' => 'Aucun widget pour cette page'], 400);
}
}
/**
* @Route("/magasin/{magasin}/widget/notification", name="factory_api_widget_notification")
* @param Request $request
* @param Magasin $magasin
* @return void
* MULTIPAGE
*/
public function widgetNotification(Request $request, Magasin $magasin)
{
if (!$request->query->has('page')) {
return new JsonResponse(['status' => 400, 'error' => 'Paramètre page manquant'], 400);
}
$page = $request->query->get('page');
$page = $this->entityManager->getRepository(WebfactoryPage::class)->findOneBy(['id' => $page]);
$pageCustomId = $request->query->get('customPage');
$config = $this->webfactoryManager->getFactoryConfig($magasin->getKAdherent());
$theme = $config['offer']['theme']['name'];
$widget = $this->entityManager->getRepository(WebfactoryWidget::class)->findOneBy(['identifier' => 'notification']);
$widgetDetails = $this->entityManager->getRepository(WidgetAbstract::class)->findBy([
'magasin' => $magasin->getKAdherent(),
'page' => $page->getIdentifier(),
'theme' => $theme,
'widget' => $widget,
'pageCustom' => $pageCustomId
]);
$datas['fr'] = [];
$datas['nl'] = [];
if (!empty($widgetDetails)) {
foreach ($widgetDetails as $widgetDetail) {
$datas[strtolower($widgetDetail->getLang())]['content'] = $widgetDetail->getContent();
$datas[strtolower($widgetDetail->getLang())]['start_date'] = $widgetDetail->getStartDate();
$datas[strtolower($widgetDetail->getLang())]['end_date'] = $widgetDetail->getEndDate();
$datas[strtolower($widgetDetail->getLang())]['uuid'] = base64_encode(uniqid($widgetDetail->getMagasin() . $widgetDetail->getId() . $widgetDetail->getUpdatedAt()?->format('Y-m-d')));
}
}
return new JsonResponse($datas);
}
/**
* @Route("/magasin/{magasin}/custom_css_js", name="factory_api_custom_css_js")
* @param Request $request
* @param Magasin $magasin
* @return JsonResponse
*/
public function customCssJs(Request $request, Magasin $magasin): JsonResponse
{
$custom = $this->entityManager->getRepository(CustomCssJs::class)->findOneBy(['magasin' => $magasin->getKAdherent(), 'active' => 1]);
$datas = [];
if ($custom) {
$datas = [
'css' => $custom->getContentCss(),
'js' => $custom->getContentJs()
];
} else {
return new JsonResponse(['status' => 400, 'error' => 'Aucun code css/js actif'], 400);
}
return new JsonResponse($datas, 200);
}
/**
* @Route("/magasin/{magasin}/seo_ville/{ville}", name="factory_api_seo_villes")
* @Route("/magasin/{magasin}/seo_ville/{ville}", name="factory_api_page_seo_ville_detail")
* @param Request $request
* @param Magasin $magasin
* @return JsonResponse
*/
public function apiSeoVilleDetail(Request $request, Magasin $magasin, $ville = null): JsonResponse
{
$arrayLangues = ['fr', 'nl'];
$datas = [];
if (is_null($ville)) {
foreach ($arrayLangues as $langue) {
$findCities = $this->entityManager->getRepository(SeoVilles::class)->createQueryBuilder('ville', 'ville.name')
->select('ville.name, contenu.langue')
->join(SeoVillesContenus::class, "contenu", "WITH", 'contenu.ville = ville.id')
->where('ville.magasin = :magasin')
->andWhere('contenu.langue = :langue')
->setParameters(['magasin' => $magasin->getKAdherent(), 'langue' => $langue])
->getQuery()->getResult();
foreach ($findCities as $city) {
$datas[$city['name']][$langue] = [
'name' => $city['name']
];
}
}
} else {
foreach ($arrayLangues as $langue) {
$findCity = $this->entityManager->getRepository(SeoVilles::class)->createQueryBuilder('ville', 'ville.name')
->select('ville.name,contenu.intro, contenu.text, contenu.metatitle, contenu.metadesc,contenu.image, contenu.langue')
->join(SeoVillesContenus::class, "contenu", "WITH", 'contenu.ville = ville.id')
->where('ville.magasin = :magasin')
->andWhere('contenu.langue = :langue')
->andWhere('ville.name = :ville')
->setParameters(['magasin' => $magasin->getKAdherent(), 'langue' => $langue, 'ville' => strtoupper($ville)])
->getQuery()->getOneOrNullResult();
if ($findCity) {
$datas[$langue]['name'] = $findCity['name'];
$datas[$langue]['intro'] = $findCity['intro'];
$datas[$langue]['text'] = $findCity['text'];
$datas[$langue]['metatitle'] = $findCity['metatitle'];
$datas[$langue]['metadesc'] = $findCity['metadesc'];
$datas[$langue]['image'] = ($findCity['image']) ? $this->urlPhotosAdh . $magasin->getKAdherent() . "/" . $findCity['image'] : null;
$datas[$langue]['enseigne'] = $magasin->getLib();
}
}
}
if ($datas) {
return new JsonResponse($datas, 200);
} else {
return new JsonResponse(['status' => 400, 'error' => 'Aucune ville'], 400);
}
}
/**
* @Route("/magasin/{magasin}/widget/faq", name="factory_api_widget_faq")
* @param Request $request
* @param Magasin $magasin
* @return void
* MULTIPAGE
*/
public
function widgetFaq(Request $request, Magasin $magasin)
{
if (!$request->query->has('page')) {
return new JsonResponse(['status' => 400, 'error' => 'Paramètre page manquant'], 400);
}
$page = $request->query->get('page');
$page = $this->entityManager->getRepository(WebfactoryPage::class)->findOneBy(['id' => $page]);
$pageCustomId = $request->query->get('customPage');
$config = $this->webfactoryManager->getFactoryConfig($magasin->getKAdherent());
$theme = $config['offer']['theme']['name'];
$widget = $this->entityManager->getRepository(WebfactoryWidget::class)->findOneBy(['identifier' => 'faq']);
$widgetDetails = $this->entityManager->getRepository(WidgetAbstract::class)->findBy([
'magasin' => $magasin->getKAdherent(),
'page' => $page->getIdentifier(),
'theme' => $theme,
'widget' => $widget,
'pageCustom' => $pageCustomId
]);
$datas['fr'] = [];
$datas['nl'] = [];
if (!empty($widgetDetails)) {
foreach ($widgetDetails as $widgetDetail) {
foreach ($widgetDetail->getFaqContenus() as $key => $question) {
$datas[strtolower($widgetDetail->getLang())][$widgetDetail->getTitre()][$key]['question'] = $question->getQuestion();
$datas[strtolower($widgetDetail->getLang())][$widgetDetail->getTitre()][$key]['reponse'] = $question->getReponse();
$datas[strtolower($widgetDetail->getLang())][$widgetDetail->getTitre()][$key]['created_at'] = $question->getCreatedAt();
$datas[strtolower($widgetDetail->getLang())][$widgetDetail->getTitre()][$key]['updated_at'] = $question->getUpdatedAt();
}
}
}
return new JsonResponse($datas);
}
/**
* @Route("/magasin/{magasin}/image_partner", name="factory_api_image_partner")
* @param Request $request
* @param Magasin $magasin
* @return JsonResponse
*/
public function apiImagesPartners(Magasin $magasin): JsonResponse
{
$datas['fr'] = [];
$datas['nl'] = [];
$listImages = $this->entityManager->getRepository(ImagePartner::class)->findBy(['magasin' => $magasin]);
foreach ($listImages as $image) {
$datas[strtolower($image->getLang())][] = [
'image' => $this->urlPhotosAdh . $magasin->getKAdherent() . '/' . $image->getImage(),
'slot' => $image->getSlot(),
];
}
return new JsonResponse($datas ?? null, $datas ? 200 : 400);
}
private
function translateHoursNL($day)
{
if (isset($day['morning']['hours']) && is_string($day['morning']['hours'])) {
$day['morning']['hours'] = str_replace("h", "u", $day['morning']['hours']);
}
if (isset($day['afternoon']['hours']) && is_string($day['afternoon']['hours'])) {
$day['afternoon']['hours'] = str_replace("h", "u", $day['afternoon']['hours']);
}
return $day;
}
private
function forceHttps($url)
{
// Search the pattern
if (!preg_match("~^(?:f|ht)tps?://~i", $url)) {
// If not exist then add http
$url = "https://" . $url;
}
// Return the URL
return $url;
}
}