<?php
namespace App\Controller;
use App\Form\ContactFormType;
use App\Service\PrintJobBackend;
use App\Utils\SessionUtils;
use Symfony\Bridge\Twig\Mime\TemplatedEmail;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Contracts\Translation\TranslatorInterface;
use Symfony\Component\Mime\Email;
use Symfony\Component\Mailer\MailerInterface;
use Symfony\Component\Mime\Address;
use Symfony\Component\Mailer\Transport\Smtp\EsmtpTransport;
use Symfony\Component\Mailer\Exception\TransportExceptionInterface;
/**
* BaseController
*/
class BaseController extends AbstractController
{
use SessionUtils;
const DASHBOARD_RENDER = 'base/dashboard.html.twig';
/**
* This function reoresente the landing page (after Login)
* If the User (not SA) has many bubble, we only give his the first Bubble
* And after, when user change his bubble, we come here to change it
*
* Any bubble we display, we get all the information of profiles (complete Object with relation mapping) and store it in Session
* Asswel, the role of user is check > Store in DB > as the refresh process can refresh the firewall/token/rights
*
* Redirect to dashboard at the dashboard
*
* @param $b_key
* @param Request $request
* @return RedirectResponse
*
* @Route("/load/{b_key}", name="load_bubble")
*/
public function loadBubble(
$b_key,
Request $request
): RedirectResponse {
$session = $this->sessionByRequestStack();
/** Set user profile key */
$session->set('b_key', $b_key);
$referer = $request->headers->get('referer');
return new RedirectResponse($referer);
}
/**
* dashboard
*
* @return Response
*
* @Route("/", name="dashboard")
*/
public function dashboard(): Response
{
$session = $this->sessionByRequestStack();
$user = $this->getuser();
$profiles = $user->getProfiles();
$b_key = $session->get('b_key', 0);
$profile = $profiles[$b_key];
// User is SA
if ($user->getIsSA() == 1 || $profile['dashboard']['read'] == 1) {
$bubbles_infos = $user->getBubblesInfo();
if (!empty($bubbles_infos)) {
return $this->render(self::DASHBOARD_RENDER, [
'bubbles_infos' => $bubbles_infos
]);
}
}
return $this->render(self::DASHBOARD_RENDER);
}
/**
* documentation
*
* @Route("/documentation", name="documentation")
*/
public function documentation(TranslatorInterface $translator)
{
$this->addFlash('warning', sprintf($translator->trans("La documentation sera prochainement disponible")));
return $this->redirectToRoute('dashboard');
}
/**
* pageIntrouvable
*
* @param TranslatorInterface $translator
* @return Response
*
* @Route("/page_introuvale/404", name="404")
*/
public function pageIntrouvable(TranslatorInterface $translator)
{
$this->addFlash('empty', $translator->trans('Voici le texte de l\'erreur rencontrée. <br/>Vous pouvez faire <a href="">une action</a>'));
return $this->render('base/404.html.twig');
}
/**
*
* @Route("contact", name="contact")
*
*/
public function contact(
Request $request,
MailerInterface $mailer,
TranslatorInterface $translator
) {
$user = $this->getuser();
$form = $this->createForm(ContactFormType::class, NULL, [
'user' => $user,
]);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$data = $form->getData();
// $data contient le prenom, le nom, l'objet, l'entreprise, l'email de l'expediteur, le message... (le $_POST finalement)
try {
$this->sendEmail($mailer, $data);
$this->addFlash('success', $translator->trans('Votre email a été envoyé avec succès.'));
} catch (TransportExceptionInterface $e) {
$this->addFlash('errors', $translator->trans('Erreur dans l\'envoie de l\'email'));
}
}
return $this->render('base/contact.html.twig', [
'form' => $form->createView()
]);
}
/**
* Send mail
*
* @param $mailer
* @param $data
* @return mixed
*/
public function sendEmail($mailer, $data)
{
// $transport = new EsmtpTransport('localhost');
$mail = (new TemplatedEmail())
->subject('Support Client MainChain : ' . $data['request'] . ' - ' . $data['objet'])
->htmlTemplate('mail/contact_mail.html.twig')
->from('support@main-chain.org')
->to(new Address($data['email']))
->context(['data' => $data])
;
return $mailer->send($mail);
}
/**
* dashboard Export
*
* @param PrintJobBackend $jobBackend
* @param TranslatorInterface $translator
* @return RedirectResponse|Response|void
*
* @Route("/dashboard/export", name="dashboard_export")
*/
public function dashboardExport (
PrintJobBackend $jobBackend,
TranslatorInterface $translator
) {
$session = $this->sessionByRequestStack();
$user = $this->getuser();
$profiles = $user->getProfiles();
$b_key = $session->get('b_key', 0);
$profile = $profiles[$b_key];
$bubbleId = $profile['b_id'];
if ($profile['dashboard']['read'] == 1) {
$user = $this->getUser();
$date = ['from' => 0, 'to' => 0];
$resp = $jobBackend->getDashboardLog($bubbleId, $user, $date);
if ($resp->getSTatusCode() == '200') {
$response = json_decode($resp->getContent(), true)['contents'];
// Stats data set creation
$datas = [];
$i = 1;
foreach($response as $r) {
foreach($r as $indice => $value) {
$row['row'] = $i;
$row['full_date'] = date('d-m-Y', strtotime($r['job_start_time']));
$row['day'] = date('d', strtotime($r['job_start_time']));
$row['month'] = date('m', strtotime($r['job_start_time']));
$row['year'] = date('Y', strtotime($r['job_start_time']));
if (
$indice == 'job_start_time' ||
$indice == 'job_end_time' ||
$indice == 'job_deleted_at' ||
$indice == 'job_created_at'
) {
if ($value) {
$row[$indice . '_date'] = date('d-m-Y', strtotime($value));
$row[$indice] = date('H:i:s', strtotime($value));
}
else{
$row[$indice] = '-NC-';
}
}
if ($indice == 'job_status') {
if (
$value == 'finished' ||
$value == 'Success' ||
$value == 'success' ||
$value == 'Finished'
) {
$row[$indice] = 'finished';
}
else{
$row[$indice] = $value;
}
}
if ($indice == 's_name') {
$row['site'] = $value;
}
if ($indice == 'all_piece_controlled') {
if ($value == true) {
$row['all_piece_controlled'] = 'yes';
}
else{
$row['all_piece_controlled'] = 'no';
}
}
if ($indice == 'job_time_total') {
$row[$indice . (' (sec)')] = ($value / 1000);
}
if (
$indice != 'us_pro_id' &&
$indice != 's_id' &&
$indice != 's_name' &&
$indice != 'job_id' &&
$indice != 'job_build_plate' &&
$indice != 'job_start_time' &&
$indice != 'job_end_time' &&
$indice != 'job_estimated_time_total' &&
$indice != 'job_deleted_at' &&
$indice != 'job_created_at' &&
$indice != 'job_forced' &&
$indice != 'job_time_total' &&
$indice != 'job_owner' &&
$indice != 'job_status' &&
$indice != 'job_index' &&
$indice != 'job_req_id' &&
$indice != 'job_print_core_1' &&
$indice != 'job_print_core_2' &&
$indice != 'job_log_filename' &&
$indice != 'job_req_id' &&
$indice != 'b_id' &&
$indice != 's_id' &&
$indice != 'p_job_history_creation_date' &&
$indice != 'p_job_history_update_date' &&
$indice != 'job_programmed_count' &&
$indice != 'job_printed_count' &&
$indice != 'job_conf_count' &&
$indice != 'printer_job_id' &&
$indice != 'printer_model' &&
$indice != 'printer_brand' &&
$indice != 'all_piece_controlled'
) {
$row[$indice] = $value;
}
}
$i++;
$datas[] = $row;
}
// CSV GENERATION
$csvContent = '';
foreach($datas[0] as $indice => $title) {
$csvContent .= $indice . ";";
}
$csvContent .= "\n";
foreach($datas as $row) {
foreach($row as $data) {
$csvContent .= $data . ";";
}
$csvContent .= "\n";
}
$csvName = 'dashboard_' . strtolower(str_replace(' ', '_', $profile['b_name'])) . '_' . date('d_m_Y') .'.csv';
return new Response($csvContent,200, [
'Content-Type' => 'application/vnd.ms-excel',
"Content-disposition" => "attachment; filename=$csvName"
]
);
} else {
if ($resp->getStatusCode() == '204') {
$this->addFlash("errors", sprintf($translator->trans("Cette bubble ne dispose pas de sufisamment de données pour effectuer un export")));
} else {
$this->addFlash("errors", sprintf($translator->trans("Une erreur s'est produite; Veuillez ré-essayer plus tard")));
}
return $this->redirectToRoute('dashboard');
}
}
}
}