<?php
namespace App\Controller;
use App\Entity\Eventos;
use App\Entity\Estilistas;
use App\Entity\Clientes;
use App\Entity\Productos;
use App\Entity\SoldProducts;
use App\Entity\Notifications;
use App\Form\UserType;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Asset\Package;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
use Symfony\Component\Validator\Constraints\DateTime;
use Symfony\Component\Asset\VersionStrategy\EmptyVersionStrategy;
use Symfony\Component\HttpFoundation\RedirectResponse;
class RegistroController extends AbstractController
{
private function getLanguage()
{
$language = "es";
if (isset($_COOKIE['lang']))
{
$language = $_COOKIE['lang'];
}
$package = new Package(new EmptyVersionStrategy());
$urlLang = $package->getUrl('language/'.$language.'.json');
$lang = json_decode(file_get_contents($urlLang));
return $lang;
}
function activeWorkers($em)
{
$wokerName = [];
$user = $this->getUser();
if (method_exists($user, 'getCompany')) { $company= $user->getCompany()->getId(); }
else{ $company = $user->getId(); }
// $em = $this->getDoctrine()->getManager();
$workers = $em->getRepository(Estilistas::class)->findBy(['enabled'=> true, 'company'=>$company]);
foreach ($workers as $worker)
{
$wokerName[] = [
'id' => $worker->getId(),
'nombre' => $worker->getNombre(),
'apellidos' => $worker->getApellidos()
];
}
return $wokerName;
}
/**
* @Route("/registro", name="registro")
*/
public function registro(Request $request, UserPasswordEncoderInterface $encoder): Response
{ //crear usuario
$user = new User();
$form = $this->createForm(UserType::class, $user);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid())
{
$em = $this->getDoctrine()->getManager();
$user->setRoles(['ROLE_ADMIN']);
$user->setPassword($encoder->encodePassword($user, $form['password']->getData()));
$em->persist($user);
$em->flush();
$this->addFlash('exito', 'Data uploaded');
return $this->redirectToRoute('registro');
}
return $this->render('registro/index.html.twig', [
'formulario' => $form->createView(),
]);
}
/**
* @Route("/access_registros", name="accessRegistros", options={"expose"=true})
*/
public function accessRegistros(Request $request, EntityManagerInterface $em): Response
{
$user = $this->getUser();
if (method_exists($user, 'getCompany')) { $company= $user->getCompany(); }
else{ $company = $user; }
$lang = self::getLanguage();
$workers = self::activeWorkers($em);
if ($content = $request->request->all())
{
if (!array_key_exists('workerName', $content))
{
$this->addFlash(
'error',
$lang->login->tellMeHowAreYou
);
return $this->render('registro/index.html.twig', [
'lang' => $lang,
'workers'=> $workers
]);
}
$pass = hash('sha256', $content['password']);
$fullName = explode(",", $content['workerName']);
$name = $fullName[0];
$surname = $fullName[1];
$id = $fullName[2];
$codeConfirmed = false;
$isAdmin = false;
$worker = $em->getRepository(Estilistas::class)->findOneBy(['id'=>$id]);
if ($worker)
{
if ($worker->getCode() === $pass) {
$codeConfirmed = true;
if ( in_array("ROLE_ADMIN", $worker->getRoles()) ) //$realPass->getAdminPass() == true
{
$isAdmin = true;
}
}
if ($codeConfirmed) {
if ($isAdmin) {
return $this->redirectToRoute('registros', ['id'=>$worker->getId()]);
}else{
return $this->redirectToRoute('registrosWorker', ['id'=>$worker->getId()] );
}
}else{
$this->addFlash(
'error',
$lang->login->userNotActive
);
return $this->render('registro/index.html.twig', [
'lang' => $lang,
'workers'=> $workers
]);
}
// if ($realPass->getNombre() == $name)
// {
// if ($realPass->getEnabled() == true)
// {
// if ( in_array("ROLE_ADMIN", $realPass->getRoles()) ) //$realPass->getAdminPass() == true
// {
// return $this->redirectToRoute('registros', ['id'=>$realPass->getId()]);
// }
// else
// {
// return $this->redirectToRoute('registrosWorker', ['id'=>$realPass->getId()] );
// }
// }
// else
// {
// $this->addFlash(
// 'error',
// $lang->login->userNotActive
// );
// return $this->render('registro/index.html.twig', [
// 'lang' => $lang,
// 'workers'=> $workers
// ]);
// }
// }
// else
// {
// $this->addFlash(
// 'error',
// $lang->login->passIncorrect
// );
// return $this->render('registro/index.html.twig', [
// 'lang' => $lang,
// 'workers'=> $workers
// ]);
// }
}
else
{
$this->addFlash(
'error',
$lang->login->passIncorrect
);
return $this->render('registro/index.html.twig', [
'lang' => $lang,
'workers'=> $workers
]);
// $response = new JsonResponse('error');
}
}
else
{
return $this->render('registro/index.html.twig', [
'data'=> new \DateTime(),
'lang' => $lang,
'workers'=> $workers
]);
}
return $response;
}
/**
* @Route("/registros/{id}", name="registros")
*/
public function resgitros($id, Request $request, EntityManagerInterface $em): Response
{
$user = $this->getUser();
if ($user) {
if (method_exists($user, 'getCompany')) { $company= $user->getCompany()->getId(); }
else{ $company = $user->getId(); }
$lang = self::getLanguage();
$month = $lang->setting->months;
foreach ($month as $mes)
{
$meses[] = $mes;
}
$workers = [];
$stylist = $em->getRepository(Estilistas::class)->findBy(['company'=>$company, 'showed'=>1]);
if($stylist){
foreach ($stylist as $employee)
{
$workers[] = [
'id' => $employee->getId(),
'name' => $employee->getNombre(),
'surName' => $employee->getApellidos(),
];
}
}
$now = new \DateTime('Europe/london');
$fisrtDay = new \DateTime('first day of this month');
$mesesHastaAhora = $now->format('m');
return $this->render('registro/registros.html.twig', [
'dateStart' => $fisrtDay,
'dateEnd' => $now,
'months' => $meses,
'lang' => $lang,
'workers' => $workers,
'userAccess' => $id,
'notifications' => $notifications=[]
]);
}else{
return $this->redirectToRoute('app_login');
}
}
/**
* @Route("/balance_serv", name="balanceServ", options={"expose"=true})
*/
public function balanceServ(Request $request, EntityManagerInterface $em): Response
{
if ($request->isXmlHttpRequest())
{
$lang= self::getLanguage();
$user = $this->getUser();
if (method_exists($user, 'getCompany')) { $company= $user->getCompany()->getId(); }
else{ $company = $user->getId(); }
$dateFrom = new \DateTime($request->request->get('desde'));
$dateTo = new \DateTime($request->request->get('hasta'));
$desde = $dateFrom->format('Y-m-d').' 00:00:00';
$hasta = $dateTo->format('Y-m-d').' 23:59:59';
$response = [];
$workers = $em->getRepository(Estilistas::class)->findBy(['company'=>$company]);
foreach ($workers as $worker)
{
$detailsId = [];
$totalCash =0;
$totalCard =0;
$totalGiftCard =0;
$total =0;
$totalForward = 0;
$elTotal = 0;
$result = $em->getRepository(Eventos::class)->getRegistro($desde, $hasta, $worker->getId(), '#1c7430');
if (!empty($result))
{
$isResult= true;
$paidBy='';
foreach ($result as $balanceWorker)
{
$servicios = explode("-", $balanceWorker['servicios']);
$tamanio = $servicios[0];
$services = $servicios[1];
$total = $balanceWorker['total'];
$detailsId[] = [
'id' => $balanceWorker['id'],
'customer' =>$balanceWorker['kunde'],
'description' =>$balanceWorker['descripcion'],
'date' =>$balanceWorker['start']->format('d/m/y'),
'name' =>$balanceWorker['nombre'],
'payment' =>$balanceWorker['payment'],
'total' =>$balanceWorker['total'],
'cash' => $balanceWorker['cash'],
'card' => $balanceWorker['card'],
'giftCard' => $balanceWorker['giftCard']
];
if ($balanceWorker['payment'] == 1)
{
$totalCash += $total;
}
elseif ($balanceWorker['payment'] == 2)
{
$totalCard += $total;
}
elseif ($balanceWorker['payment'] == 3)
{
if (!is_null($balanceWorker['cash'])) { $totalCash += $balanceWorker['cash']; $paidBy.='1';}
if (!is_null($balanceWorker['card'])) { $totalCard += $balanceWorker['card']; $paidBy.='2';}
if (!is_null($balanceWorker['giftCard'])) { $totalGiftCard += $balanceWorker['giftCard']; $paidBy.='3';}
}
}
}
else
{
$isResult= false;
}
$elTotal += $totalCash + $totalCard + $totalGiftCard;
$analiticTotal = $elTotal + $totalForward;
if ($isResult) {
$response[]= [
'totalCash' => $totalCash,
'totalCard' => $totalCard,
'totalGiftCard' => $totalGiftCard,
'totalDone' => $elTotal,
'paidBy' => $paidBy,
'estilista' => $worker->getNombre(),
'detailsId' => $detailsId,
'enabled' => $worker->getEnabled()
];
}else{
$response[]= [
'totalCash' => 0,
'totalCard' => 0,
'totalGiftCard' => 0,
'totalDone' => 0,
'paidBy' => '',
'estilista' => $worker->getNombre(),
'detailsId' => $detailsId,
'enabled' => $worker->getEnabled()
];
}
}
}
else
{
$response = ['error'=>'no results found'];
}
return new JsonResponse(['response'=>$response, 'lang'=>$lang]);
}
/**
* @Route("/balance_booking", name="balanceBooking", options={"expose"=true})
*/
public function balanceBooking(Request $request, EntityManagerInterface $em): Response
{
if ($request->isXmlHttpRequest())
{
$lang= self::getLanguage();
$user = $this->getUser();
if (method_exists($user, 'getCompany')) { $company= $user->getCompany()->getId(); }
else{ $company = $user->getId(); }
$lang= self::getLanguage();
$user = $this->getUser();
if (method_exists($user, 'getCompany')) { $company= $user->getCompany()->getId(); }
else{ $company = $user->getId(); }
$dateFrom = new \DateTime($request->request->get('desde'));
$dateTo = new \DateTime($request->request->get('hasta'));
$desde = $dateFrom->format('Y-m-d').' 00:00:00';
$hasta = $dateTo->format('Y-m-d').' 23:59:59';
// $state = $request->request->get('status');
// $estado = explode(',', $state);
$response = [];
$workers = $em->getRepository(Estilistas::class)->findBy(['company'=>$company]);
foreach ($workers as $worker)
{
$detailsId = [];
$totalCash =0;
$totalCard =0;
$totalGiftCard =0;
$total =0;
$totalForward = 0;
$elTotal = 0;
$result = $em->getRepository(Eventos::class)->getRegistro($desde, $hasta, $worker->getId(), '#000000');
if (!empty($result))
{
$isResult= true;
$paidBy='';
foreach ($result as $balanceWorker)
{
$servicios = explode("-", $balanceWorker['servicios']);
$tamanio = $servicios[0];
$services = $servicios[1];
$total = $balanceWorker['total'];
$detailsId[] = [
'id' => $balanceWorker['id'],
'customer' => $balanceWorker['kunde'],
'description' => $balanceWorker['descripcion'],
'date' => $balanceWorker['start']->format('d-M-Y'),
'name' => $balanceWorker['nombre'],
'payment' => $balanceWorker['payment'],
'total' => $balanceWorker['total'],
'cash' => $balanceWorker['cash'],
'card' => $balanceWorker['card'],
'giftCard' => $balanceWorker['giftCard']
];
$totalForward += $total;
}
}
else
{
$isResult= false;
}
$elTotal += $totalCash + $totalCard + $totalGiftCard;
$analiticTotal = $elTotal + $totalForward;
if ($isResult) {
$response[]= [
'totalForward' => $totalForward,
'estilista' => $worker->getNombre(),
'detailsId' => $detailsId,
'enabled' => $worker->getEnabled()
];
}else{
$response[]= [
'totalForward' => 0,
'estilista' => $worker->getNombre(),
'detailsId' => $detailsId,
'enabled' => $worker->getEnabled()
];
}
}
}
else
{
$response = ['error'=>'no results found'];
}
return new JsonResponse(['response'=>$response, 'lang'=>$lang]);
}
/**
* @Route("/balance_prod", name="balanceProd", options={"expose"=true})
*/
public function balanceProd(Request $request, EntityManagerInterface $em): Response
{
if ($request->isXmlHttpRequest())
{
$lang= self::getLanguage();
$user = $this->getUser();
if (method_exists($user, 'getCompany')) { $company= $user->getCompany()->getId(); }
else{ $company = $user->getId(); }
$dateFrom = new \DateTime($request->request->get('desde'));
$dateTo = new \DateTime($request->request->get('hasta'));
$desde = $dateFrom->format('Y-m-d').' 00:00:00';
$hasta = $dateTo->format('Y-m-d').' 23:59:59';
// $state = $request->request->get('status');
// $stado = explode(',', $state);
$response = [];
$workers = $em->getRepository(Estilistas::class)->findBy(['company'=>$company]);
foreach ($workers as $worker)
{
$totalProducts = 0;
$detailsProd = [];
$products = $em->getRepository(SoldProducts::class)->getProducts($desde, $hasta, $worker->getId());
if ($products)
{
$isResult= true;
foreach ($products as $prod)
{
for ($i=0; $i < count($prod['productosId']); $i++)
{
$prueba = $prod['productosId'][$i];
$prodSplit = explode('-', $prod['productosId'][$i]);
$product = $em->getRepository(Productos::class)->findOneBy(['id'=>$prodSplit[0]]);
if ($product)
{
$total = $product->getPrecioVp() * $prodSplit[1];
$detailsProd[] = [
$product->getId(),
$product->getCodigoProducto(),
$product->getNombre(),
$product->getMarca(),
number_format($product->getPrecioVp(), 2),
$prodSplit[1],
number_format($total, 2),
$prod['paymentMethod'],
$prod['date']->format('d/m/y H:i'),
number_format($prod['total'], 2)
];
}
// else
// {
// $detailsProd[] = 'no data';
// }
}
$totalProducts = $totalProducts + $prod['total'];
}
}
else{
$isResult= false;
}
if ($isResult) {
$response[]= [
'totalProducts' => number_format($totalProducts, 2),
'estilista' => $worker->getNombre(),
'detailsProd' => $detailsProd,
'enabled' => $worker->getEnabled()
];
}else{
$response[]= [
'totalProducts' => 0,
'estilista' => $worker->getNombre(),
'detailsProd' => $detailsProd,
'enabled' => $worker->getEnabled()
];
}
}
}
else
{
$response = ['error'=>'no results found'];
}
return new JsonResponse(['response'=>$response, 'lang'=>$lang]);
}
/**
* @Route("/balance_analitic", name="balanceAnalitic", options={"expose"=true})
*/
public function balanceAnalitic(Request $request, EntityManagerInterface $em): Response
{
if ($request->isXmlHttpRequest())
{
$lang= self::getLanguage();
$user = $this->getUser();
if (method_exists($user, 'getCompany')) { $company= $user->getCompany()->getId(); }
else{ $company = $user->getId(); }
$dateFrom = new \DateTime($request->request->get('desde'));
$dateTo = new \DateTime($request->request->get('hasta'));
$desde = $dateFrom->format('Y-m-d').' 00:00:00';
$hasta = $dateTo->format('Y-m-d').' 23:59:59';
// $state = $request->request->get('status');
// $stado = explode(',', $state);
$response = [];
$workers = $em->getRepository(Estilistas::class)->findBy(['company'=>$company]);
foreach ($workers as $worker)
{
$totalProducts = 0;
$detailsProd = [];
$products = $em->getRepository(SoldProducts::class)->getProducts($desde, $hasta, $worker->getId());
if ($products)
{
foreach ($products as $prod)
{
for ($i=0; $i < count($prod['productosId']); $i++)
{
$prodSplit = explode('-', $prod['productosId'][$i]);
$product = $em->getRepository(Productos::class)->findOneBy(['id'=>$prodSplit[0]]);
if ($product)
{
$detailsProd[] = [
$product->getId(),
$product->getCodigoProducto(),
$product->getNombre(),
$product->getMarca(),
$product->getPrecioVp(),
];
}
else
{
$detailsProd[] = 'no data';
}
}
$totalProducts = $totalProducts + $prod['total'];
}
}
$detailsId = [];
$totalCash =0;
$totalCard =0;
$totalGiftCard =0;
$total =0;
$totalForward = 0;
$elTotal = 0;
$result = $em->getRepository(Eventos::class)->getAllRegistro($desde, $hasta, $worker->getId());
if (!empty($result))
{
$isResult= true;
$paidBy='';
foreach ($result as $balanceWorker)
{
$servicios = explode("-", $balanceWorker['servicios']);
$tamanio = $servicios[0];
$services = $servicios[1];
$total = $balanceWorker['total'];
$detailsId[] = [
'id' => $balanceWorker['id'],
'customer' =>$balanceWorker['kunde'],
'description' =>$balanceWorker['descripcion'],
'date' =>$balanceWorker['start']->format('d-M-Y'),
'name' =>$balanceWorker['nombre'],
'payment' =>$balanceWorker['payment'],
'total' =>$balanceWorker['total']
];
if (!is_null($balanceWorker['payment']))
{
if ($balanceWorker['payment'] == 1)
{
$totalCash += $total;
}
elseif ($balanceWorker['payment'] == 2)
{
$totalCard += $total;
}
elseif ($balanceWorker['payment'] == 3)
{
if (!is_null($balanceWorker['cash'])) { $totalCash += $balanceWorker['cash']; $paidBy.='1';}
if (!is_null($balanceWorker['card'])) { $totalCard += $balanceWorker['card']; $paidBy.='2';}
if (!is_null($balanceWorker['giftCard'])) { $totalGiftCard += $balanceWorker['giftCard']; $paidBy.='3';}
}
}
else
{
$totalForward += $total;
}
}
}
else
{
$isResult= false;
}
$elTotal += $totalCash + $totalCard + $totalGiftCard;
$analiticTotal = $elTotal + $totalForward ;//+ $totalProducts;
if ($isResult) {
$response[]= [
'totalCash' => number_format($totalCash, 2),
'totalCard' => number_format($totalCard, 2),
'totalGiftCard' => number_format($totalGiftCard, 2),
'totalProducts' => number_format($totalProducts, 2),
'totalDone' => number_format($elTotal, 2),
'analiticTotal' => $analiticTotal,
'totalForward' => number_format($totalForward, 2),
'paidBy' => $paidBy,
'estilista' => $worker->getNombre(),
'detailsId' => $detailsId,
'detailsProd' => $detailsProd,
'enabled' => $worker->getEnabled()
];
}else{
$response[]= [
'totalCash' => 0,
'totalCard' => 0,
'totalGiftCard' => 0,
'totalProducts' => number_format($totalProducts, 2),
'totalDone' => 0,
'analiticTotal' => 0,
'totalForward' => 0,
'paidBy' => '',
'estilista' => $worker->getNombre(),
'detailsId' => $detailsId,
'detailsProd' => $detailsProd,
'enabled' => $worker->getEnabled()
];
}
}
}
else
{
$response = ['error'=>'no results found'];
}
return new JsonResponse(['response'=>$response, 'lang'=>$lang]);
}
// /**
// * @Route("/balance", name="balance", options={"expose"=true})
// */
// public function balance(Request $request, EntityManagerInterface $em): Response
// {
// if ($request->isXmlHttpRequest())
// {
// $lang= self::getLanguage();
// $user = $this->getUser();
// if (method_exists($user, 'getCompany')) { $company= $user->getCompany()->getId(); }
// else{ $company = $user->getId(); }
// $dateFrom = new \DateTime($request->request->get('desde'));
// $dateTo = new \DateTime($request->request->get('hasta'));
// $desde = $dateFrom->format('Y-m-d').' 00:00:00';
// $hasta = $dateTo->format('Y-m-d').' 23:59:59';
// $state = $request->request->get('status');
// $stado = explode(',', $state);
// $response = [];
// $workers = $em->getRepository(Estilistas::class)->findBy(['company'=>$company]);
// foreach ($workers as $worker)
// {
// $totalProducts = 0;
// $detailsProd = [];
// $products = $em->getRepository(SoldProducts::class)->getProducts($desde, $hasta, $worker->getId());
// if ($products)
// {
// foreach ($products as $prod)
// {
// $idProd = explode('-', $prod['idProductos']);
// for ($i=0; $i < count($idProd); $i++)
// {
// $product = $em->getRepository(Productos::class)->findOneBy(['id'=>$idProd[$i]]);
// if ($product)
// {
// $detailsProd[] = [
// $product->getId(),
// $product->getCodigoProducto(),
// $product->getNombre(),
// $product->getMarca(),
// $product->getPrecioVp(),
// ];
// }
// else
// {
// $detailsProd[] = 'no data';
// }
// }
// $totalProducts = $totalProducts + $prod['total'];
// }
// }
// $detailsId = [];
// $totalCash =0;
// $totalCard =0;
// $totalGiftCard =0;
// $total =0;
// $totalForward = 0;
// $elTotal = 0;
// foreach ($stado as $status)
// {
// $result = $em->getRepository(Eventos::class)->getRegistro($desde, $hasta, $worker->getId(), $status);
// if (!empty($result))
// {
// $isResult= true;
// $paidBy='';
// foreach ($result as $balanceWorker)
// {
// $servicios = explode("-", $balanceWorker['servicios']);
// $tamanio = $servicios[0];
// $services = $servicios[1];
// $total = $balanceWorker['total'];
// $detailsId[] = [
// 'id' => $balanceWorker['id'],
// 'customer' =>$balanceWorker['kunde'],
// 'description' =>$balanceWorker['descripcion'],
// 'date' =>$balanceWorker['start']->format('d-M-Y'),
// 'name' =>$balanceWorker['nombre'],
// 'payment' =>$balanceWorker['payment'],
// 'total' =>$balanceWorker['total']
// ];
// if (array_key_exists(2, $servicios)) //si existe forma de pago
// {
// $formaPago = $servicios[2];
// }
// else{ $formaPago = 0; }
// if ($status == '#1c7430')
// {
// if ($balanceWorker['payment'] == 1)
// {
// $totalCash += $total;
// }
// elseif ($balanceWorker['payment'] == 2)
// {
// $totalCard += $total;
// }
// elseif ($balanceWorker['payment'] == 3)
// {
// if (!is_null($balanceWorker['cash'])) { $totalCash += $balanceWorker['cash']; $paidBy.='1';}
// if (!is_null($balanceWorker['card'])) { $totalCard += $balanceWorker['card']; $paidBy.='2';}
// if (!is_null($balanceWorker['giftCard'])) { $totalGiftCard += $balanceWorker['giftCard']; $paidBy.='3';}
// // $totalNoRegistrado += $total;
// }
// }
// else
// {
// $totalForward += $total;
// }
// }
// // si checka los pagados o no
// // if ($totalCash == 0 && $totalCard == 0 && $totalGiftCard == 0)
// // {
// // $elTotal += $totalForward;
// // }
// // else
// // {
// // $elTotal += $totalCash + $totalCard + $totalGiftCard;
// // }
// // $elTotal += $totalCash + $totalCard + $totalGiftCard + $totalForward;
// }
// else
// {
// $isResult= false;
// }
// }
// $elTotal += $totalCash + $totalCard + $totalGiftCard;
// $analiticTotal = $elTotal + $totalForward;
// if ($isResult) {
// $response[]= [
// 'totalCash' => $totalCash,
// 'totalCard' => $totalCard,
// 'totalGiftCard' => $totalGiftCard,
// 'totalProducts' => $totalProducts,
// 'totalDone' => $elTotal,
// 'analiticTotal' => $analiticTotal,
// 'totalForward' => $totalForward,
// 'paidBy' => $paidBy,
// 'estilista' => $worker->getNombre(),
// 'status' => $status,
// 'detailsId' => $detailsId,
// 'detailsProd' => $detailsProd,
// 'enabled' => $worker->getEnabled()
// ];
// }else{
// $response[]= [
// 'totalCash' => 0,
// 'totalCard' => 0,
// 'totalGiftCard' => 0,
// 'totalProducts' => 0,
// 'totalDone' => 0,
// 'analiticTotal' => 0,
// 'totalForward' => 0,
// 'paidBy' => '',
// 'estilista' => $worker->getNombre(),
// 'status' => $status,
// 'detailsId' => $detailsId,
// 'detailsProd' => $detailsProd,
// 'enabled' => $worker->getEnabled()
// ];
// }
// }
// }
// else
// {
// $response = ['error'=>'no results found'];
// }
// return new JsonResponse(['response'=>$response, 'lang'=>$lang]);
// }
/**
* @Route("/acceso_balance", name="accesoBalance")
*/
public function accesoBalance(Request $request, UserPasswordEncoderInterface $encoder): Response
{
$lang = self::getLanguage();
return $this->render('registro/accesoBalance.html.twig', [
'formulario' => $form->createView(),
'lang' => $lang
]);
}
// /**
// * @Route("/get_profits/{id}", name="getProfits")
// */
// public function getProfits($id, Request $request): Response
// {
// $lang = self::getLanguage();
// return $this->render('registro/profits.html.twig', [
// // 'formulario' => $form->createView(),
// 'lang' => $lang,
// 'userAccess' => $id,
// ]);
// }
/**
* @Route("/vista_anual", name="vistaAnual", options={"expose"=true})
*/
public function vistaAnual(Request $request, EntityManagerInterface $em): Response
{
if ($request->isXmlHttpRequest()) {
$lang = self::getLanguage();
$user = $this->getUser();
if (method_exists($user, 'getCompany')) { $company= $user->getCompany(); }
else{ $company = $user; }
$year = $request->request->get('year');
$max = 1000;
if($company->getMax()){
if ($company->getMax() > $max) {
$max = $company->getMax();
}
}else{
$company->setMax($max);
$em->flush();
}
$now = new \DateTime('Europe/London');
$anio = $now->format('Y');
$anual=[];
$quantityYear=[];
if ($year != '' || $year != null)
{
$anio = $year;
}
for ($i=1; $i <= 12; $i++)
{
$desde = $anio.'-'.$i.'-01 00:00:00';
$hasta = $anio.'-'.$i.'-31 23:59:59';
$mensual = $em->getRepository(Eventos::class)->getMothly($desde, $hasta, $company->getId());
//Codigo de test
// if (!$mensual) {
// for ($x=1; $x <=12 ; $x++) {
// $mensual = [];
// $aleatorio = mt_rand(3500, 20000);
// $mensual[] = ['total'=> $aleatorio];
// }
// }
//
$total=0;
$amount=0;
foreach ($mensual as $mes)
{
$porcent = ($mes['total']*100) / $max;
$result = $porcent;
$total += $result;
$amount +=$mes['total'];
}
if ($total > $max) {
$company->setMax($total);
$em->flush();
}
$anual[] = $total;
$quantityYear[]= $amount;
}
$actual = $now->format('Y-m');
$from = $actual.'-01 00:00:00';
$to = $actual.'-31 23:59:59';
$nuevosClientes = 0;
$newKunder = $em->getRepository(Clientes::class)->getNewCostumers($from, $to, $company->getId());
foreach ($newKunder as $value)
{
$nuevosClientes++;
}
$response = new JsonResponse(['anual'=>$anual, 'max'=>$max, 'anio'=>$anio, 'newKunder'=>$nuevosClientes, 'amount'=>$quantityYear, 'new'=>$lang->setting->balance->newCustomers]);
return $response;
}
else{
throw new Exception("Error Processing Request", 1);
}
}
// /**
// * @Route("/db_import", name="dbImport")
// */
// public function dbImport(Request $request, UserPasswordEncoderInterface $encoder, EntityManagerInterface $em): Response
// {
// $server = "localhost";
// $user = "sirox";
// $pass = "Vidaeterna22";
// $database = "tpv";
// $conexion = mysqli_connect($server, $user, $pass, $database);
//
// $query = mysqli_query($conexion, "SELECT * FROM eventos");
// if (mysqli_num_rows($query))
// {
// while($listaEventos = mysqli_fetch_array($query))
// {
// // LETRAS NORUEGAS
// $cambio1 = mb_convert_encoding($listaEventos['comentario'], "HTML-ENTITIES", "UTF-8");
// $cambio2 = str_replace('�', 'å', $cambio1);
// $cambio3 = str_replace('�', 'ø', $cambio2);
// $cambio4 = str_replace('�', 'æ', $cambio3);
// // $cambio4 = str_replace('�', 'Å', $cambio3);
// $cambio5 = str_replace('�', 'Ø', $cambio4);
// // $cambio6 = str_replace('�', 'Æ', $cambio3);
// $cambio6 = str_replace('�', 'ø', $cambio5);
//
//
// // NOMBRE DE CLIENTES
// $query3 = mysqli_query($conexion, "SELECT * FROM clientes WHERE id = ".$listaEventos['id_cliente']);
// if (mysqli_num_rows($query3))
// {
// while ($cliente = mysqli_fetch_array($query3))
// {
// $nombeCliente = $cliente['nombre'];
// }
// }
//
//
//
//
// // DESCIPCION DE LOS SERVICIOS
// $service = "";
// $servicios1 = explode("-", $listaEventos['id_servicio']);
// if (array_key_exists(1, $servicios1))
// {
// $servicios2 = explode(" / ", $servicios1[1]);
// }
// else{ $servicios2 = ['7','']; }
// //
// // // $service = var_dump($servicios2);
// //
// for ($i=0; $i <count($servicios2)-1 ; $i++) //Sacamos los nombres de los servicios asociados al evento
// {
// $query2 = mysqli_query($conexion, "SELECT * FROM servicios WHERE id = ".$servicios2[$i]);
// if (mysqli_num_rows($query2))
// {
// while($serv = mysqli_fetch_array($query2))
// {
// $service .= $serv['servicio']." / ";
// }
// }
// }
// // // $serviceName = $em->getRepository(Servicios::class)->findOneBy(['id'=>$servicios2[$i]]); // MODIFICAR !!
// // // if (!is_null($serviceName) )
// // // {
// // // }
//
//
//
// $response[] = [
// 'id'=>$listaEventos['id'],
// 'start'=>$listaEventos['start'],
// 'end'=>$listaEventos['end'],
// 'color'=>$listaEventos['color'],
// 'textColor'=>$listaEventos['textColor'],
// 'total'=>$listaEventos['total'],
// 'comentario'=>$cambio6,
// 'id_cliente'=>$listaEventos['id_cliente'],
// 'id_servicio'=>$listaEventos['id_servicio'],
// 'id_producto'=>$listaEventos['id_producto'],
// 'id_estilista'=>$listaEventos['id_estilista'],
// 'nombreCliente'=>$nombeCliente,
// 'descripcion'=>$service
// ];
// }
// }
//
// foreach ($response as $value)
// {
// if ($value['id_cliente'] == 0)
// {
// $value['id_cliente'] = 1;
// }
// $estilista = $em->getRepository(Estilistas::class)->findOneBy(['id'=>$value['id_estilista']]);
// $cliente = $em->getRepository(Clientes::class)->findOneBy(['id'=>$value['id_cliente']]);
//
// $eventos = new Eventos();
// $eventos->setStart(new \DateTime($value['start']));
// $eventos->setEnd(new \DateTime($value['end']));
// $eventos->setColor($value['color']);
// $eventos->setTextColor($value['textColor']);
// $eventos->setTotal($value['total']);
// $eventos->setComentario($value['comentario']);
// $eventos->setServicios($value['id_servicio']);
// $eventos->setProductos($value['id_producto']);
// $eventos->setEstilistas($estilista);
// $eventos->setClientes($cliente);
// $eventos->setDescripcion($value['descripcion']);
// $eventos->setKunde($value['nombreCliente']);
//
// $em->persist($eventos);
// }
//
// $em->flush();
// return new JsonResponse(['msg'=>'Data uploaded']);
//
// }
//############-----REGISTROS WORKER-----##############
/**
* @Route("/registros_worker/{id}", name="registrosWorker")
*/
public function resgitrosWorker($id, Request $request, EntityManagerInterface $em): Response
{
$lang = self::getLanguage();
// $fisrtDay = new \DateTime('first day of this month');
// $lastDay = new \DateTime('last day of this month');
// $now = new \DateTime('Europe/London');
// $date = $now->format('Y-m');
// $fecha = $now->format('M - Y');
// $desde = $date.'-01 00:00:00';
// $hasta = $date.'-31 23:59:59';
// $status = '#1c7430';
// $resultado=[];
// $response =[];
// $total=0;
// $sueldo = 0;
// $comision = 0;
$worker = $em->getRepository(Estilistas::class)->findOneBy(['id'=>$id]);
// $eventos = $em->getRepository(Eventos::class)->getRegistro($desde, $hasta, $worker->getId(), $status);
// foreach ($eventos as $totally)
// {
// $total += $totally['total'];
// }
// $resultado = [
// 'total' => $total,
// 'porcent' => $worker->getPorcent(),
// 'salary' => $worker->getSalary(),
// 'salaryHour' => $worker->getSalaryHour()
// ];
// if ($resultado['porcent'] != 0) {
// $comision = $resultado['total'] * $resultado['porcent'] / 100;
// }
// if ($resultado['salary'] != 0) {
// $sueldo = $resultado['salary'];
// }
// POR COMISION
// if ($resultado['salary'] == 0 && $resultado['salaryHour'] == 0)
// {
// $comision = $resultado['total'] * $resultado['porcent'] / 100;
// }
// POR HORAS
// elseif ($resultado['salary'] == 0 && $resultado['porcent'] == 0)
// {
// }
// SUELDO FIJO
// elseif ($resultado['porcent'] == 0 && $resultado['salaryHour'] == 0)
// {
// $sueldo = $resultado['salary'];
// }
// // SUELDO FIJO + COMISIÓN
// elseif ($resultado['salaryHour'] == 0)
// {
// $sueldo = $resultado['salary'];
// $comision = $resultado['total'] * $resultado['porcent'] / 100;
// // $sueldo = $salary + $comision;
// }
// $response = [
// 'total' => $resultado['total'],
// 'porcent' => $resultado['porcent'],
// 'fijo' => $sueldo,
// 'comision' => $comision
// ];
return $this->render('registro/registrosWorker.html.twig', [
'lang' => $lang,
'id' => $worker->getId(),
// 'fecha' => $fecha,
// 'firstDay' => $fisrtDay,
// 'lastDay' => $lastDay,
'nombre' => $worker->getNombre(),
'apellidos' => $worker->getApellidos(),
// 'response' => $response,
'workers' => self::activeWorkers($em)
]);
}
/**
* @Route("/registros_worker_by_date", name="registrosWorkerByDate", options={"expose"=true})
*/
public function registrosWorkerByDate(Request $request, EntityManagerInterface $em): Response
{
$response = new JsonResponse('nope');
if ($request->isXMLHttpRequest())
{
$lang = self::getLanguage();
$status = '#1c7430';
$date = $request->request->get('date');
$from = new \DateTime($date.'-01');
$lastDay = date('t', strtotime("$date-01"));
$to = new \DateTime($date.'-'.$lastDay);
$desde = $from->format('Y-m-d').' 00:00:00';
$hasta = $to->format('Y-m-d').' 23:59:59';
$now = new \DateTime("now");
$result=[];
$response =[];
$total=0;
$sueldo = 0;
$comision = 0;
$comisionProd = 0;
$totalProd = 0;
$worker = $em->getRepository(Estilistas::class)->findOneBy(['id'=>$request->request->get('id')]);
$products = $em->getRepository(SoldProducts::class)->getProducts($desde, $hasta, $worker->getId());
$eventos = $em->getRepository(Eventos::class)->getRegistro($desde, $hasta, $worker->getId(), $status);
foreach ($eventos as $totally)
{
$total += $totally['total'];
}
$resultado = [
'total' => $total,
'porcent' => $worker->getPorcent(),
'salary' => $worker->getSalary(),
'salaryHour' => $worker->getSalaryHour()
];
// POR COMISION
if ($resultado['salary'] == 0 && $resultado['salaryHour'] == 0)
{
$sueldo = $resultado['total'] * $resultado['porcent'] / 100;
$comision = $sueldo;
}
// POR HORAS
elseif ($resultado['salary'] == 0 && $resultado['porcent'] == 0)
{
}
// SUELDO FIJO
elseif ($resultado['porcent'] == 0 && $resultado['salaryHour'] == 0)
{
$sueldo = $resultado['salary'];
}
// SUELDO FIJO + COMISIÓN
elseif ($resultado['salaryHour'] == 0)
{
$salary = $resultado['salary'];
$comision = $resultado['total'] * $resultado['porcent'] / 100;
$sueldo = $salary + $comision;
}
// if ($resultado['porcent'] != 0) {
// $comision = $resultado['total'] * $resultado['porcent'] / 100;
// }
// if ($resultado['salary'] != 0) {
// $sueldo = $resultado['salary'];
// }
// POR COMISION
// if ($resultado['salary'] == 0 && $resultado['salaryHour'] == 0)
// {
// $comision = $resultado['total'] * $resultado['porcent'] / 100;
// }
// POR HORAS
// elseif ($resultado['salary'] == 0 && $resultado['porcent'] == 0)
// {
// }
// SUELDO FIJO
// elseif ($resultado['porcent'] == 0 && $resultado['salaryHour'] == 0)
// {
// $sueldo = $resultado['salary'];
// }
// // SUELDO FIJO + COMISIÓN
// elseif ($resultado['salaryHour'] == 0)
// {
// $sueldo = $resultado['salary'];
// $comision = $resultado['total'] * $resultado['porcent'] / 100;
// // $sueldo = $salary + $comision;
// }
if ($products){
$comisionProd = 0;
foreach ($products as $product) {
$comisionProd = $comisionProd + $product['total'];
$totalProd = $totalProd + $product['total'];
}
$comisionProd = $comisionProd * $worker->getProductPercent() / 100;
// $resultado['products'] = [
// 'percent' => $worker->getProductPercent(),
// 'total' => $comisionProd,
// 'comision' => $comisionProd * $worker->getProductPercent() / 100
// ];
}
$response = [
'total' => $resultado['total'],
'porcent' => $resultado['porcent'],
'fijo' => $resultado['salary'],
'comision' => $comision,
'comisionProd' => $comisionProd,
'totalProd' => $totalProd,
'percentProd' => $worker->getProductPercent()
];
}
return new JsonResponse(['data'=>$response, 'lang'=>$lang]);
}
}
// namespace App\Controller;
// use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
// use Symfony\Component\HttpFoundation\Response;
// use Symfony\Component\Routing\Annotation\Route;
// class RegistroController extends AbstractController
// {
// #[Route('/registro', name: 'app_registro')]
// public function index(): Response
// {
// return $this->render('registro/index.html.twig', [
// 'controller_name' => 'RegistroController',
// ]);
// }
// }