<?php
namespace App\Controller;
use App\Controller\Admin\AdminOrdersController;
use App\Entity\CalculationShape;
use App\Entity\Customer;
use App\Entity\DiameterHole;
use App\Entity\FeedData;
use App\Entity\FreightPricesCargo;
use App\Entity\FreightPricesPackage;
use App\Entity\FreightPricesTruck;
use App\Entity\Holiday;
use App\Entity\MaterialGrades;
use App\Entity\MaterialPrices;
use App\Entity\PostalCodes;
use App\Entity\PriceSurcharge;
use App\Entity\Representative;
use App\Entity\Setting;
use App\Entity\SurchargeDimensions;
use App\Entity\SurchargeHandling;
use App\Entity\Surcharges;
use App\Entity\SurchargesCategory;
use App\Entity\SurchargesHandlingCategory;
use App\Entity\SurchargesThickness;
use App\Entity\Thickness;
use App\Entity\User;
use App\Entity\UserAddress;
use App\Entity\UserRepresentative;
use App\Entity\WiCamFiles;
use App\Entity\WiCamFilesCircles;
use App\Entity\WiCamFilesPriceSurcharge;
use App\Entity\WiCamFilesSurcharges;
use App\Entity\WiCamFilesVariables;
use App\Entity\WiCamHeader;
use App\Entity\WiCamHeaderTemp;
use App\Entity\WiCamHeaderNotes;
use App\HttpClient\WiCamApiToken;
use App\HttpClient\WiCamApiClient;
use App\Repository\OrderStatusRepository;
use App\Repository\SettingRepository;
use App\Repository\SurchargesHandlingCategoryRepository;
use App\Repository\WiCamHeaderRepository;
use App\Service\DeliveryTypeService;
use App\Repository\WiCamHeaderTempRepository;
use App\Tools\NumberFormatter;
use App\Tools\WicamApiLogHelper;
use App\Tools\WicamOrderHelper;
use Doctrine\ORM\EntityManagerInterface;
use Doctrine\ORM\EntityRepository;
use Elastica\Processor\Set;
use Knp\Component\Pager\PaginatorInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Mailer\Exception\TransportExceptionInterface;
use Symfony\Component\Mailer\MailerInterface;
use Symfony\Component\Mime\Email;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\HttpFoundation\JsonResponse;
use App\Service\PrintOffer;
use Nzo\UrlEncryptorBundle\Encryptor\Encryptor;
use PhpOffice\PhpSpreadsheet;
use Symfony\Contracts\Translation\TranslatorInterface;
class WiCamController extends AbstractController
{
const EUR_PER_TON = 1;
const EUR_PER_PIECE = 2;
const EUR_EFFECTIVE_PER_FILE = 3;
const EUR_EFFECTIVE_FOR_ORDER = 4;
const MAX_DRILLING_DIAMETER_ID = 18;
const SETTING_OFFER_TEXT = 19;
const ATTEMPTS_CONNECTION = 22;
const SECONDS_WAITING = 23;
const DEFAULT_REPRESENTATIVE = 33;
const MAX_WEIGHT_PALLET = 34;
const MAX_LENGTH_PALLET = 35;
const MAX_WIDTH_PALLET = 37;
const MAX_HEIGHT_SHAPE = 36;
const MAX_WICAM_UPLOAD_FILES = 38;
const VAT_PERCENT = 40;
const IN_PRICE = 1;
const SEPARATED_PRICE = 2;
/**
* @var WiCamApiToken
*/
private $tokenClient;
/**
* @var WiCamApiClient
*/
private $api_client;
/**
* @var TranslatorInterface
*/
private $translator;
private $encryptor;
private $currencySymbol;
private $entityManager;
public function __construct(
WiCamApiToken $client,
WiCamApiClient $api_client,
WicamApiLogHelper $apiLogHelper,
Encryptor $encryptor,
NumberFormatter $numberFormatter,
TranslatorInterface $translator,
EntityManagerInterface $entityManager)
{
$this->tokenClient = $client;
$this->api_client = $api_client;
$this->api_client->setApiLogHelper($apiLogHelper);
$this->encryptor = $encryptor;
$this->entityManager = $entityManager;
if ($numberFormatter->locale == 'en') {
$this->currencySymbol = '€';
} else {
$this->currencySymbol = '€';
}
$this->translator = $translator;
}
/**
* @Route("/upload/load-customers", name="wi_cam_load_customer")
*/
public function loadCustomers(Request $request)
{
$id = $request->get('id');
$customers = $this->getDoctrine()->getRepository(Customer::class)->findBy(['representative' => $id]);
return $this->render('includes/select-customer.html.twig', ['customers' => $customers]);
}
/**
* @Route("/upload", name="wi_cam_home")
* @Route("/admin/upload", name="wi_cam_admin_home")
* @param Request $request
*
* @return Response
*/
public function index(Request $request)
{
$idEdit = $request->get('id');
$thickness = $this->getDoctrine()->getRepository(Thickness::class)->findBy(['active' => 1], ['value' => 'ASC']);
$materialgrades = $this->getDoctrine()->getRepository(MaterialGrades::class)->findBy(['active' => true]);
$pricessurcharges = $this->getDoctrine()->getRepository(PriceSurcharge::class)->findAll();
$surcharges = $this->getDoctrine()->getRepository(Surcharges::class)->findBy(['active' => 1, 'allow_to_apply_all' => 1]);
$shapes = $this->getDoctrine()->getRepository(CalculationShape::class)->findBy(['active' => 1], ['orden' => 'ASC']);
/** @var Setting $maxUploadFiles */
$maxUploadFiles = $this->getDoctrine()->getRepository(Setting::class)->find(self::MAX_WICAM_UPLOAD_FILES);
/** @var EntityRepository $repository */
$repository = $this->getDoctrine()->getRepository(CalculationShape::class);
$qb = $repository->createQueryBuilder('cs');
$customers = null;
$user = $this->getUser();
$isLoggedIn = $user ? true : false;
$qbT = $qb
->select('DISTINCT cs')
->from('App\Entity\WiCamFiles', 'wf')
->from('App\Entity\WiCamHeader', 'wh')
->AndWhere('cs.id = wf.CalculationShape ')
->AndWhere('wf.wicam_header = wh.id ')
->AndWhere('wf.deleted = 0')
->AndWhere('cs.active IN(1,15)')
->orderBy('cs.orden', 'ASC');
if ($user) {
if ($this->isGranted('ROLE_REPRESENTATIVE')) {
/** @var Representative $representative */
$representative = $user->getUserRepresentatives()->get(0)->getRepresentative();
$qbT->andWhere('wh.representative = :representative ')
->setParameter('representative', $representative->getId());
$customers = $representative->getCustomers();
}
}
$shapesFrequently = $qbT->getQuery()
->getResult();
/** @var WiCamHeader $wicamHeader */
$wicamHeader = null;
$countWicamFiles = false;
/** @var WiCamHeaderTemp $wicamHTemp */
$wicamHTemp = null;
$plz = null;
$filesHtml = '';
$isRepresentativeOrAdmin = $this->isGranted('ROLE_REPRESENTATIVE') || $this->isGranted('ROLE_ADMIN');
$toEdit = false;
$notes = [];
$representatives = null;
if (!empty($idEdit)) {
$wsCode = $idEdit;
$wicamHeader = $this->getDoctrine()->getRepository(WiCamHeader::class)->find($wsCode);
//Create temporal wicamHeader in the same table oc_wicam_header (temporal = 1)
$em = $this->getDoctrine()->getManager();
$wicamHeaderTemporal = new WiCamHeaderTemp();
$wicamHeaderTemporal->setDateSurcharge($wicamHeader->getDateSurcharge());
$wicamHeaderTemporal->setGuid($wicamHeader->getGuid());
if(is_int((int)$wicamHeader->getPlz())){
$wicamHeaderTemporal->setPlz($wicamHeader->getPlz());
} else {
$wicamHeaderTemporal->setPlz(0);
}
$wicamHeaderTemporal->setPriceSurchargeId($wicamHeader->getPriceSurcharge()->getId());
$wicamHeaderTemporal->setDeliveryType($wicamHeader->getDeliveryType());
$wicamHeaderTemporal->setDeliveryCost($wicamHeader->getDeliveryCost());
$wicamHeaderTemporal->setGeneralTotalPrice($wicamHeader->getGeneralTotalPrice());
$wicamHeaderTemporal->setSurchargesTotal($wicamHeader->getSurchargesTotal());
$wicamHeaderTemporal->setVatPercent($wicamHeader->getVatPercent());
if(!empty($wicamHeader->getVatPercentTotal())){
$wicamHeaderTemporal->setVatPercentTotal($wicamHeader->getVatPercentTotal());
} else {
$wicamHeaderTemporal->setVatPercentTotal("0");
}
$wicamHeaderTemporal->setGeneralTotal($wicamHeader->getGeneralTotal());
$wicamHeaderTemporal->setIsOrder($wicamHeader->getIsOrder());
$wicamHeaderTemporal->setOrderNumber($wicamHeader->getOrderNumber());
$wicamHeaderTemporal->setDateOrder($wicamHeader->getDateOrder());
$wicamHeaderTemporal->setRepresentativeId($wicamHeader->getRepresentative()->getId());
if(!empty($wicamHeader->getCustomer())){
$wicamHeaderTemporal->setCustomerId($wicamHeader->getCustomer()->getId());
} else {
$wicamHeaderTemporal->setCustomerId(null);
}
$wicamHeaderTemporal->setOrderStatusId($wicamHeader->getOrderStatus()->getId());
$wicamHeaderTemporal->setOrderStatusDateChanged($wicamHeader->getOrderStatusDateChanged());
$wicamHeaderTemporal->setDeleted($wicamHeader->getDeleted());
$wicamHeaderTemporal->setDateSys($wicamHeader->getDateSys());
$wicamHeaderTemporal->setWicamHeaderId($wicamHeader->getId());
$em->persist($wicamHeaderTemporal);
$em->flush();
$idTemporal = $wicamHeaderTemporal->getId();
$wicamHTemp = $this->getDoctrine()->getRepository(WiCamHeaderTemp::class)->find($idTemporal);
$countWicamFiles = $wicamHeader->getCountActiveWicamFiles() > 0;
$filesHtml = $this->GetFileResponse($wicamHeader, $thickness, $materialgrades, $pricessurcharges);
$plz = $this->getDoctrine()->getRepository(PostalCodes::class)->findOneBy(['plz' => $wicamHeader->getPlz()]);
$toEdit = true;
$notes = $this->getDoctrine()->getRepository(WiCamHeaderNotes::class)->findBy(['flag' => 1, 'wicam_header' => $wicamHeader->getId()]);
if ($this->isGranted('ROLE_ADMIN')) {
$representatives = $this->getDoctrine()->getRepository(Representative::class)->findAll();
if (!empty($wicamHTemp->getRepresentativeId())) {
$representative = $wicamHTemp->getRepresentativeId();
$customers = $this->getDoctrine()->getRepository(Representative::class)->find($representative)->getCustomers();
}
}
} else {
if (isset($_COOKIE['wsCode'])) {
$wsCode = $_COOKIE['wsCode'];
if (!empty($wsCode)) {
if (is_numeric($wsCode)) {
$wsCodeEn = $this->encryptor->encrypt($wsCode);
setcookie('wsCode', $wsCodeEn, time() + 604800, '/');
} else {
$wsCode = $this->encryptor->decrypt($wsCode);
}
$wicamHeader = $this->getDoctrine()->getRepository(WiCamHeader::class)->find($wsCode);
// if the offer in the cookie doesnt have representative assigned then it can show but it has representative assigned then should check if the representative
// is the same that the user logged.
$countWicamFiles = $wicamHeader->getCountActiveWicamFiles() > 0;
if ($wicamHeader->getIsOrder()) {
$wicamHeader = null;
setcookie("wsCode", "", time() - 3600, '/');
} elseif (empty($wicamHeader->getRepresentative())) {
if ($this->getUser()) {
/** @var User $user */
$user = $this->getUser();
if ($this->isGranted('ROLE_REPRESENTATIVE')) {
/** @var UserRepresentative $userRepresentative */
$userRepresentative = $user->getUserRepresentatives()->get(0);
$wicamHeader->setRepresentative($userRepresentative->getRepresentative());
$this->getDoctrine()->getManager()->flush();
} elseif ($this->isGranted('ROLE_USER')) { // if it is customer login
$activeCustomer = $user->getActiveCustomerForUserCustomer();
$arrayAddress = $this->getArrayAddress($user);
$wicamHeader->setCustomer($activeCustomer);
$wicamHeader->setPlz($arrayAddress['plz']);
$wicamHeader->setCity($arrayAddress['city']);
$wicamHeader->setCountry($arrayAddress['country']);
$wicamHeader->setStreet($arrayAddress['street']);
$wicamHeader->setRepresentative($activeCustomer->getRepresentative());
$this->getDoctrine()->getManager()->flush();
}
}
$filesHtml = $this->GetFileResponse($wicamHeader, $thickness, $materialgrades, $pricessurcharges);
$plz = $this->getDoctrine()->getRepository(PostalCodes::class)->findOneBy(array('plz' => $wicamHeader->getPlz()));
} else {
if ($this->getUser()) {
/** @var User $user */
$user = $this->getUser();
if ($this->isGranted('ROLE_REPRESENTATIVE')) {
/** @var UserRepresentative $userRepresentative */
$userRepresentative = $user->getUserRepresentatives()->get(0);
if ($wicamHeader->getRepresentative()->getId() == $userRepresentative->getRepresentative()->getId()) {
$filesHtml = $this->GetFileResponse($wicamHeader, $thickness, $materialgrades, $pricessurcharges);
$plz = $this->getDoctrine()->getRepository(PostalCodes::class)->findOneBy(array('plz' => $wicamHeader->getPlz()));
}
} elseif ($this->isGranted('ROLE_USER')) { // if it is customer login
$activeCustomer = $user->getActiveCustomerForUserCustomer();
$arrayAddress = $this->getArrayAddress($user);
$wicamHeader->setCustomer($activeCustomer);
$wicamHeader->setRepresentative($activeCustomer->getRepresentative());
$wicamHeader->setPlz($arrayAddress['plz']);
$wicamHeader->setCity($arrayAddress['city']);
$wicamHeader->setCountry($arrayAddress['country']);
$wicamHeader->setStreet($arrayAddress['street']);
$this->getDoctrine()->getManager()->flush();
$filesHtml = $this->GetFileResponse($wicamHeader, $thickness, $materialgrades, $pricessurcharges);
$plz = $this->getDoctrine()->getRepository(PostalCodes::class)->findOneBy(array('plz' => $wicamHeader->getPlz()));
} else {
$wicamHeader = null;
setcookie("wsCode", "", time() - 3600, '/');
}
} else {
$wicamHeader = null;
setcookie("wsCode", "", time() - 3600, '/');
}
}
}
}
}
return $this->render('wicam/index.html.twig', [
'isLoggedIn' => $isLoggedIn,
'isRepresentativeOrAdmin' => $isRepresentativeOrAdmin,
'thickness' => $thickness,
'materialgrades' => $materialgrades,
'pricessurcharges' => $pricessurcharges,
'surcharges_items' => $surcharges,
'shapes' => $shapes,
'shapesFrequently' => $shapesFrequently,
'guid' => uniqid(),
'WH' => $wicamHTemp,
'plz' => $plz,
'files' => $filesHtml,
'toEdit' => $toEdit,
'notes' => $notes,
'customers' => $customers,
'representatives' => $representatives,
'maxUploadFiles' => $maxUploadFiles->getValue(),
'general_setting_box' => $countWicamFiles
]);
}
private function GetFileResponse(WiCamHeader $WH, $thickness, $materialgrades, $prices_surcharge)
{
$entityManager = $this->getDoctrine()->getManager();
$surcharges = $entityManager->getRepository(Surcharges::class)->findBy(['active' => 1]);
$wicamFiles = $entityManager->getRepository(WiCamFiles::class)->findBy(['deleted' => 0, 'validation' => 1, 'wicam_header' => $WH->getId()], ['orden' => 'ASC']);
$response = [];
/** @var WiCamFiles $wf */
foreach ($wicamFiles as $wf) {
$key = $wf->getId();
$circles = [];
/** @var WiCamFilesCircles $wfc */
if (!empty($wf->getWiCamFilesCircles())) {
foreach ($wf->getWiCamFilesCircles() as $wfc) {
$circle['diameter'] = $wfc->getDiameter();
$circle['amount'] = $wfc->getAmount();
$thickness_value = 0;
if ($wf->getThickness() != null) {
$thickness_value = $wf->getThickness()->getValue();
}
$diameters = $this->getDoctrine()->getRepository(DiameterHole::class)->findByThicknessAmount($thickness_value, $wfc->getAmount());
//$html_diameters = $this->renderView('includes/wicam-diameter-hole.html.twig',['diameters'=>$diameters]);
$circle['diameters'] = $diameters;
$circle['wfc'] = $wfc;
$circles[] = $circle;
}
}
$basicInformation = ['width' => $wf->getWidth(), 'length' => $wf->getLength()];
$extendedInformation = [
'contour' => ['total' => $wf->getContours()],
'length' => ['total' => $wf->getTotalLenght()],
'area' => ['geometry' => $wf->getPartNetArea()],
'circles' => $circles
];
$isShape = $wf->getIsShape();
if ($isShape) {
$CalculationShape = $wf->getCalculationShape();
$response[$key]['name'] = $CalculationShape->getDescription();
$response[$key]['CalculationShape'] = $CalculationShape;
$WiCamFilesVariables = $this->getDoctrine()->getRepository(WiCamFilesVariables::class)->findBy(['wicam_files' => $wf->getId()]);
$response[$key]['WiCamFilesVariables'] = $WiCamFilesVariables;
} else {
$response[$key]['name'] = $wf->getName();
}
$response[$key]['isShape'] = $isShape;
$response[$key]['identify'] = $wf->getId();
$response[$key]['is_valid'] = true;
$response[$key]['invalid_reason'] = '';
$response[$key]['validation'] = "";
$response[$key]['information'] = [];
$response[$key]['image'] = base64_decode($wf->getSvgFile());
$response[$key]['wicam'] = $wf;
$response[$key]['information'] = [
'basicInformation' => $basicInformation,
'extendedInformation' => $extendedInformation
];
$response[$key]['res'] = ['fileId' => $wf->getWicamId()];
}
$responseFiles['thickness'] = $thickness;
$responseFiles['materialgrades'] = $materialgrades;
$responseFiles['prices_surcharges'] = $prices_surcharge;
$responseFiles['countFiles'] = count($response);
$responseFiles['files'] = $response;
$responseFiles['surcharges'] = $surcharges;
$validation_errors = [];
/** @var Setting $setting */
$setting = $this->getDoctrine()->getManager()->getRepository(Setting::class)->find(self::MAX_DRILLING_DIAMETER_ID);
/** @var Setting $maxHeightShape */
$maxHeightShape = $this->getDoctrine()->getManager()->getRepository(Setting::class)->find(self::MAX_HEIGHT_SHAPE);
$isRepresentativeOrAdmin = $this->isGranted('ROLE_REPRESENTATIVE') || $this->isGranted('ROLE_ADMIN');
$html = $this->renderView('wicam/files.html.twig', [
'responseFiles' => $responseFiles,
'errors' => $validation_errors,
'MAX_DRILLING_DIAMETER' => $setting->getValue(),
'maxHeightShape' => $maxHeightShape,
'isRepresentativeOrAdmin' => $isRepresentativeOrAdmin
]);
return $html;
}
/**
* @Route("/upload/file", methods={"POST"}, name="wi_cam_upload")
* @param Request $request
*
* @return JsonResponse
*/
public function upload_file(Request $request)
{
/*return new Response(
var_export($request,true)
);*/
$file = $request->files->get('file');
$filenames = [];
foreach ($file as $fl) {
if (strtolower($fl->getClientOriginalExtension()) == 'dxf' || strtolower($fl->getClientOriginalExtension()) == 'dwg') {
$fileName = uniqid() . '.' . $fl->getClientOriginalExtension();
$realName = $fl->getClientOriginalName();
$uploadFile = $fl->move(
$this->getParameter('uploaded_image_directory'),
$fileName
);
$filenames[] = ['name' => $fileName, 'realname' => $realName];
}
}
$html = $this->renderView('includes/wicam-list-files.html.twig', [
'responseFiles' => $filenames
]);
$response = ['filenames' => $filenames, 'html' => $html];
return new JsonResponse($response);
}
/**
* @Route("/upload/generate", methods={"POST"}, name="wi_cam_generate")
* @param Request $request
*
* @return JsonResponse
*/
public function GenerateHeader(Request $request, OrderStatusRepository $orderStatusRepository)
{
$guid = $request->get("guid");
$manager = $this->getDoctrine()->getManager();
/** @var WiCamHeader $wicamheader */
$wicamheader = new WiCamHeader();
$wicamheader->setGuid($guid);
$wicamheader->setPlz("");
$wicamheader->setOrderStatus($orderStatusRepository->find(1));
/** @var User $user */
$user = $this->getUser();
if ($user) {
if ($this->isGranted('ROLE_REPRESENTATIVE')) {
/** @var UserRepresentative $userRepresentative */
$userRepresentative = $user->getUserRepresentatives()->get(0);
$wicamheader->setRepresentative($userRepresentative->getRepresentative());
} elseif ($this->isGranted('ROLE_USER')) {
$activeCustomer = $user->getActiveCustomerForUserCustomer();
$wicamheader->setCustomer($activeCustomer);
$wicamheader->setRepresentative($activeCustomer->getRepresentative());
} else {
$wicamHeader = null;
setcookie("wsCode", "", time() - 3600, '/');
}
}
$manager->persist($wicamheader);
$manager->flush();
setcookie('wsCode', $this->encryptor->encrypt($wicamheader->getId()), time() + 604800, '/');
return new JsonResponse(array('id' => $wicamheader->getId()));
}
/**
* @Route("/upload/set_header", methods={"POST"}, name="wi_cam_set_header")
* @param Request $request
*
* @return JsonResponse
* @throws \Exception
*/
public function SetHeader(Request $request): JsonResponse
{
$header_id = $request->get("header_id");
$date_surcharge = $request->get("date_surcharge");
$ps = $request->get("ps");
$manager = $this->getDoctrine()->getManager();
/** @var WiCamHeader $wicamheader */
$wicamheader = $manager->getRepository(WiCamHeader::class)->find($header_id);
/** @var PriceSurcharge $price_surcharge */
$price_surcharge = $manager->getRepository(PriceSurcharge::class)->find($ps);
if (empty($date_surcharge)) {
$wicamheader->setDateSurcharge(null);
$wicamheader->setPriceSurcharge(null);
} else {
$wicamheader->setDateSurcharge(new \DateTime($date_surcharge));
$wicamheader->setPriceSurcharge($price_surcharge);
}
$manager->flush();
return new JsonResponse(array('id' => $wicamheader->getId()));
}
/**
* @Route("/upload/send", methods={"POST"}, name="wi_cam_send")
* @param Request $request
*
* @return JsonResponse
*/
public function send_file(Request $request, SettingRepository $settingRepository)
{
$token = $this->GetToken($request);
$files = $request->get("files");
$guid = $request->get("guid");
$header_id = $request->get("header_id");
$manager = $this->getDoctrine()->getManager();
/** @var Setting $setting */
$setting = $manager->getRepository(Setting::class)->find(14);
$minimal_length = $setting->getValue() * 1.0;
$setting = $manager->getRepository(Setting::class)->find(15);
$maximal_length = $setting->getValue() * 1.0;
$setting = $manager->getRepository(Setting::class)->find(16);
$minimal_width = $setting->getValue() * 1.0;
$setting = $manager->getRepository(Setting::class)->find(17);
$maximal_width = $setting->getValue() * 1.0;
$thickness = $this->getDoctrine()->getRepository(Thickness::class)->findBy(['active' => 1], ['value' => 'ASC']);
$materialgrades = $this->getDoctrine()->getRepository(MaterialGrades::class)->findBy(['active' => true]);
/** @var MaterialGrades $mg */
$mg = null;
if (count($materialgrades) == 1) {
$mg = $materialgrades[0];
}
$surcharges = $this->getDoctrine()->getRepository(Surcharges::class)->findBy(['active' => 1]);
$prices_surcharge = $this->getDoctrine()->getRepository(PriceSurcharge::class)->findAll();
/** @var Setting $setting */
$setting = $settingRepository->find(self::MAX_DRILLING_DIAMETER_ID);
$canProduceDrillings = $this->getParameter('can_produce_drillings');
$finalFiles = [];
foreach ($files as $fl) {
$finalFiles[] = [
'filename' => $this->getParameter('uploaded_image_directory') . '/' . $fl['realName'],
'name' => $fl['fileName']
];
}
/** @var WiCamHeader $wicamheader */
$wicamheader = $this->getDoctrine()->getRepository(WiCamHeader::class)->find($header_id);
$response = $this->api_client->sendFiles($token, $finalFiles);
$validation_errors = [];
if ($response) {
foreach ($response as $key => $rp) {
$invalid_reason = '';
$file_id = $rp['res']['fileId'];
$collectionID = $rp['res']['collectionId'];
$fileInformation = '';
$fileInformation = $this->GetInformationFile($token, $file_id, $collectionID);
$validation = '';
sleep(1);
$image = $this->getImage($token, $file_id, $collectionID);
$ct = 1;
while ($image['status'] <> 200 && $ct <= 5) {
sleep(1);
$image = $this->getImage($token, $file_id, $collectionID);
$ct++;
}
$pngImage = $this->getImagePng($token, $file_id, $collectionID);
$pngImage = base64_encode($pngImage['image']);
$validation = $this->InternalValidation($fileInformation);
$validation_errors = $validation[1];
$validation = $validation[0];
$response[$key]['validation'] = $validation;
$response[$key]['information'] = $fileInformation;
$response[$key]['image'] = ($image['image']);
/** @var WiCamFiles $WiCamFile */
$WiCamFile = new WiCamFiles();
$is_valid = $validation == 'Valid' ? '1' : '0';
$w = $fileInformation['basicInformation']['width'];
$l = $fileInformation['basicInformation']['length'];
$is_valid_l = true;
$is_valid_w = true;
$is_valid_lmin = true;
$is_valid_lmax = true;
$is_valid_wmin = true;
$is_valid_wmax = true;
if ($minimal_length >= 0 || $maximal_length > 0 || $minimal_width >= 0 || $maximal_width > 0) {
$is_valid_l = $is_valid_lmin = ($l >= $minimal_length);
if ($maximal_length > 0) {
$is_valid_lmax = $l <= $maximal_length;
$is_valid_l = $is_valid_lmin && $is_valid_lmax;
}
$is_valid_w = $is_valid_wmin = ($w >= $minimal_width);
if ($maximal_width > 0) {
$is_valid_wmax = $w <= $maximal_width;
$is_valid_w = $is_valid_wmin && $is_valid_wmax;
}
}
if (!$is_valid_l || !$is_valid_w) {
if (!$is_valid_lmin || !$is_valid_wmin) {
$msgInvalid = "Ein min. Wert wird unterschritten: <br>
Das von Ihnen eingelesene Bauteil unterschreitet das Mindestmaß (min. Bauteilgröße: %minimalLength% x %minimalWidth% mm).
<br><br> Bitte fragen Sie größere Abmessungen unter <a href='mailto:info@cad2cut.de'>info@cad2cut.de</a> an.";
$invalid_reason .= "\n" . $this->translator->trans($msgInvalid, ['%minimalWidth%' => $minimal_width, '%minimalLength%' => $minimal_length]);
}
if (!$is_valid_lmax || !$is_valid_wmax) {
$msgInvalid = "Ein max. Wert wird überschritten: <br>
Das von Ihnen eingelesene Bauteil überschreitet die maximal mögliche Abmessung (max. Bauteilgröße: %maximalLength% x %maximalWidth% mm).
<br><br> Bitte fragen Sie größere Abmessungen unter <a href='mailto:info@cad2cut.de'>info@cad2cut.de</a> an.";
$invalid_reason .= "\n" . $this->translator->trans($msgInvalid, ['%maximalWidth%' => $maximal_width, '%maximalLength%' => $maximal_length]);
}
$is_valid = '0';
}
/** @var WiCamFilesCircles $WiCamCircle */
if ($fileInformation['extendedInformation']['circles']) {
$circles = 0;
foreach ($fileInformation['extendedInformation']['circles'] as $circle) {
if ($circle['diameter'] <= $setting->getValue()) {
$circles++;
} else {
$is_valid = '0';
$validation = 'Invalid File<br>Has circles with diameter not allowed.<br>';
$invalid_reason = 'Has circles with diameter not allowed.';
}
$WiCamCircle = new WiCamFilesCircles();
$WiCamCircle->setWicamFiles($WiCamFile)
->setDiameter($circle['diameter'])
->setAmount($circle['amount']);
$manager->persist($WiCamCircle);
}
if (!$canProduceDrillings && $circles > 0) {
$is_valid = '0';
$validation = 'Invalid File<br>Has circles<br>';
$invalid_reason = 'Has circles';
}
if ($circles > 0) {
$WiCamFile->setHasCircles(true);
} else {
$WiCamFile->setHasCircles(false);
}
} else {
$WiCamFile->setHasCircles(false);
}
$WiCamFile->setWicamId($file_id)
->setName($fileInformation['file']['name'])
->setCollectionID($collectionID)
->setOriginalName($fileInformation['file']['name'])
->setGeometryName("")
->setExtension($fileInformation['file']['extension'])
->setLength($fileInformation['basicInformation']['length'])
->setWidth($fileInformation['basicInformation']['width'])
->setPartNetArea($fileInformation['extendedInformation']['area']['geometry'])
->setContours($fileInformation['extendedInformation']['contour']['total'])
->setTotalLenght($fileInformation['extendedInformation']['length']['total'])
->setValidationInfo($validation)
->setValidation($is_valid)
->setPngFile($pngImage)
->setSvgFile(base64_encode($image['image']))
->setDeleted(false)
->setGuid($guid)
->setIsShape(false)
->setWiCamHeader($wicamheader);
if (!empty($mg)) {
$WiCamFile->setMaterialGrades($mg);
}
$WiCamFile->setJson(json_encode($fileInformation));
$manager->persist($WiCamFile);
$manager->flush();
$response[$key]['identify'] = $WiCamFile->getId();
$response[$key]['wicam'] = $WiCamFile;
$response[$key]['isShape'] = false;
$response[$key]['is_valid'] = $is_valid;
$response[$key]['invalid_reason'] = $invalid_reason;
}
}
$responseFiles['thickness'] = $thickness;
$responseFiles['materialgrades'] = $materialgrades;
$responseFiles['prices_surcharges'] = $prices_surcharge;
$responseFiles['countFiles'] = count($response);
$responseFiles['files'] = $response;
$responseFiles['surcharges'] = $surcharges;
//echo '<pre>'; var_dump($response); die;
/*return $this->render('wicam/files.html.twig', [
'responseFiles' => $responseFiles
]);*/
/** @var Setting $maxHeightShape */
$maxHeightShape = $settingRepository->find(self::MAX_HEIGHT_SHAPE);
$isRepresentativeOrAdmin = $this->isGranted('ROLE_REPRESENTATIVE') || $this->isGranted('ROLE_ADMIN');
$html = $this->renderView('wicam/files.html.twig', [
'responseFiles' => $responseFiles,
'errors' => $validation_errors,
'MAX_DRILLING_DIAMETER' => $setting->getValue(),
'maxHeightShape' => $maxHeightShape,
'isRepresentativeOrAdmin' => $isRepresentativeOrAdmin
]);
$html_invalid_files = $this->renderView('includes/wicam-invalid-files.html.twig', [
'responseFiles' => $responseFiles,
'errors' => $validation_errors
]);
$response_ar = array('html' => $html, 'errors' => $validation_errors, 'header_id' => $wicamheader->getId(), 'html_invalid_files' => $html_invalid_files);
return new JsonResponse($response_ar);
}
/**
* @Route("/upload/validate", methods={"POST"}, name="wi_cam_validate")
* @param Request $request
*
* @return Response
*/
public function Validate(Request $request)
{
$token = $this->GetToken($request);
$id = $request->get("id");
$htmlResponse = $this->InternalValidation($token, $id);
return new Response($htmlResponse);
}
function InternalValidation($fileInformation)
{
$errors[50001] = 'Open contour';
$errors[50002] = 'Double contour';
$errors[50003] = 'Part in part';
$errors[50004] = 'No geometry found';
$errors[50005] = 'Overlapping lines';
$errors[50006] = 'Open outer contour';
$errors[50007] = 'Inner contour collides with outer contour';
$validation = $fileInformation['validation'];
if (empty($validation['geometryErrors'])) {
$htmlResponse = 'Valid';
} else {
$htmlResponse = 'Invalid File<br>';
if ($validation['geometryErrors']) {
foreach ($validation['geometryErrors'] as $er) {
$code = $er['code'];
$code = (int)$code;
$htmlResponse .= '' . $errors[$code] . '<br>';
$htmlResponse .= '<b>X:</b>' . $er['x'] . ' ';
$htmlResponse .= '<b>Y:</b>' . $er['y'] . '<br>';
//$htmlResponse .= ''.$errors[$er].'<br>';
}
}
}
return [$htmlResponse, $validation['geometryErrors']];
}
function GetInformationFile($token, $id, $collectionId)
{
$entityManager = $this->getDoctrine()->getManager();
$attemps = $entityManager->getRepository(Setting::class)->find(self::ATTEMPTS_CONNECTION);
$attemps = $attemps->getValue();
$seconds = $entityManager->getRepository(Setting::class)->find(self::SECONDS_WAITING);
$seconds = $seconds->getValue();
return $this->api_client->FileInformation($token, $id, $collectionId, $attemps, $seconds);
/* $htmlResponse = '';
$htmlResponse .= '<b>length:</b> <span class="length">'.$response['length'].'</span><br>';
$htmlResponse .= '<b>width:</b> <span class="width">'.$response['width'].'</span><br>';
$htmlResponse .= '<b>partNetArea:</b> <span class="partNetArea">'.$response['partNetArea'].'</span><br>';
$htmlResponse .= '<b>partArea:</b> '.$response['partArea'].'<br>';
$htmlResponse .= '<b>closedInnerContours:</b> '.$response['closedInnerContours'];
return $htmlResponse;*/
}
/**
* @Route("/upload/download", methods={"POST"}, name="wi_cam_download")
* @param Request $request
*
* @return JsonResponse
*/
public function Download(Request $request)
{
$token = $this->GetToken($request);
$id = $request->get("id");
$response = $this->api_client->DownloadFile($token, $id);
//sleep(1);
$fileInformation = $this->GetInformationFile($token, $id);
$finalResponse = [
'image' => $response,
'information' => $fileInformation
];
return new JsonResponse($finalResponse);
}
/**
* @Route("/upload/calculate", methods={"POST"}, name="wi_cam_calculate")
* @param Request $request
*
* @return JsonResponse
*/
public function Calculate(Request $request): JsonResponse
{
$plz = $request->get('plz');
$customer = $request->get('customer');
/** @var Customer $customer_ent */
$customer_ent = null;
$representative = $request->get('representative');
$guid = $request->get('guid');
$header_id = $request->get('header_id');
$getbox = $request->get('getbox');
$getbox = $getbox == 'true' ? true : false;
$data_response = [];
$entityManager = $this->getDoctrine()->getManager();
/** @var WiCamHeader $wicam_header */
$wicam_header = $entityManager->getRepository(WiCamHeader::class)->find($header_id);
$no_plz = true;
if ($plz) {
/** @var PostalCodes $Plz */
$Plz = $entityManager->getRepository(PostalCodes::class)->findBY(['plz' => $plz]);
if ($Plz) {
$no_plz = false;
$wicam_header->setPlz($plz);
}
}
if (!empty($customer)) {
/** @var Customer $customer_ent */
$customer_ent = $entityManager->getRepository(Customer::class)->find($customer);
$wicam_header->setCustomer($customer_ent);
}
if (!empty($representative)) {
/** @var Representative $representative_ent */
$representative_ent = $entityManager->getRepository(Representative::class)->find($representative);
$wicam_header->setRepresentative($representative_ent);
}
$data_files = $request->get('data_files');
if ($data_files) {
/** @var Setting $setting */
$setting_specific_weight = $entityManager->getRepository(Setting::class)->find(9);
/** @var Setting $setting_verputzen */
$setting_verputzen = $entityManager->getRepository(Setting::class)->find(13);
/** @var Setting $setting_general_surcharge */
$setting_general_surcharge = $entityManager->getRepository(Setting::class)->find(11);
$setting_value = json_decode($setting_general_surcharge->getValue(), true);
$customer = $wicam_header->getCustomer();
$surcharge_value = 0;
if(!is_null($customer)){
$customer_category = $customer->getCategory()->getDescription();
} else {
$customer_category = 'no_category';
}
foreach($setting_value as $k=>$s){
$categoryDescription = str_replace('category_','',$k);
if($categoryDescription == $customer_category){
$surcharge_value = $s * 1.0;
}
}
if($surcharge_value == 0){
$customer_category = 'no_category';
foreach($setting_value as $k=>$s){
$categoryDescription = str_replace('category_','',$k);
if($categoryDescription == $customer_category){
$surcharge_value = $s * 1.0;
}
}
}
/** @var Setting $setting_max_drilling */
$setting_max_drilling = $entityManager->getRepository(Setting::class)->find(self::MAX_DRILLING_DIAMETER_ID);
$surcharges_handlings = $entityManager->getRepository(SurchargeHandling::class)->findAll();
$prices_surcharges_ext = $entityManager->getRepository(PriceSurcharge::class)->findAll();
//create wicamheader temporal object
$wiCamHeaderTemporal = $entityManager->getRepository(WiCamHeaderTemp::class)->findBy(['wicamHeaderId'=>$header_id]);
foreach ($data_files as $df) {
$identify = $df['identify'];
/** @var WiCamFiles $wicam_file */
$wicam_file = $entityManager->getRepository(WiCamFiles::class)->find($identify);
//fill the JSON object for the wicam_files
$wicamFileObject = array(
'id'=>$wicam_file->getId(),
'wicam_header_id'=>$wicam_file->getWicamHeader()->getId(),
'wicam_id'=>$wicam_file->getWicamId(),
'collectionID'=>$wicam_file->getCollectionID(),
'name'=>$wicam_file->getName(),
'originalName'=>$wicam_file->getOriginalName(),
'geometryName'=>$wicam_file->getGeometryName(),
'extension'=>$wicam_file->getExtension(),
'length'=>$wicam_file->getLength(),
'width'=>$wicam_file->getWidth(),
'partNetArea'=>$wicam_file->getPartNetArea(),
'contours'=>$wicam_file->getContours(),
'totalLength'=>$wicam_file->getTotalLenght(),
'validation'=>$wicam_file->getValidation(),
'validation_info'=>$wicam_file->getValidationInfo(),
'json'=>$wicam_file->getJson(),
'material_grades_id'=>$wicam_file->getMaterialGrades()->getId(),
'thickness_id'=>$wicam_file->getThickness()->getId(),
'amount'=>$wicam_file->getAmount(),
'plz'=>$wicam_file->getPlz(),
'total_weight'=>$wicam_file->getTotalWeight(),
'total_price'=>$wicam_file->getTotalPrice(),
'piece_price'=>$wicam_file->getPiecePrice(),
'total_piece_price'=>$wicam_file->getTotalPiecePrice(),
'total'=>$wicam_file->getTotal(),
'real_weight'=>$wicam_file->getRealWeight(),
'delivery_cost'=>$wicam_file->getDeliveryCost(),
'png_file'=>$wicam_file->getPngFile(),
'svg_file'=>$wicam_file->getSvgFile(),
'cutting_time'=>$wicam_file->getCuttingTime(),
//'calculation_shape_id'=>$wicam_file->getCalculationShape()->getId(),
'is_shape'=>$wicam_file->getIsShape(),
'hasCircles'=>$wicam_file->getHasCircles(),
'deleted'=>$wicam_file->getDeleted(),
'guid'=>$wicam_file->getGuid(),
'orden'=>$wicam_file->getOrden(),
'creation_date'=>$wicam_file->getCreationDate(),
);
$wicamFileObj = json_encode($wicamFileObject);
// var_dump($wicamFileObj);
// $wiCamHeaderTemporal->setFileInfo($wicamFileObject);
// $old_amount = $wicam_file->getAmount();
$thickness_id = $df["thickness"];
$thickness = $entityManager->getRepository(Thickness::class)->findOneBy(["id" => $thickness_id]);
$material_grade_id = $df["materialgrade"];
/** @var MaterialGrades $material_grades */
$material_grades = $entityManager->getRepository(MaterialGrades::class)->find($material_grade_id);
$delivery_cost = null;
$TotalPrice = null;
$price_surcharge = null;
$total_weight = null;
$piece_price = null;
$total_piece_price = null;
$total = null;
$response = [];
$price_surcharge_id = $df['price_surcharge'];
$amount = $df['amount'];
/** @var SurchargeDimensions $surcharge_dimension */
$surcharge_dimension = $entityManager->getRepository(SurchargeDimensions::class)->findOneByThickness($thickness_id);
$wicam_file->setMaterialGrades($material_grades);
$real_plz = substr($plz, 0, 2);
// $orderLimitReached = $this->isValidPricesLimit($header_id);
// $newAmountGreaterThanOld = $amount > $old_amount ? true : false;
// if ($orderLimitReached) {
// if ($newAmountGreaterThanOld) {
// $amount = $old_amount;
// }
// }
$amount = empty($amount) ? 0 : $amount;
if ($amount < 0) {
$amount = 0;
}
$wicam_file->setThickness($thickness)
->setAmount($amount)
->setPlz($plz);
if ($thickness != null && $surcharge_dimension != null && !empty($price_surcharge_id)
&& !empty($material_grade_id) && $wicam_file->getValidation() == '1') {
$total_weight = $this->getTotalWeight($wicam_file, $thickness, $surcharge_dimension, $setting_specific_weight);
$response['total_weight'] = $total_weight;
$ad_handling_percent = $this->getAddtionalHandling($surcharges_handlings, $total_weight, $amount,
$wicam_header->getCustomer());
$totalMaterialPrices = $this->getPriceMaterialAndSurcharges($wicam_file, $thickness_id, $material_grade_id);
$TotalPrice = ($totalMaterialPrices * $total_weight) / 1000; // get prices by KG
$TotalPrice = round($TotalPrice, 2);
$response['total_price'] = $TotalPrice;
$cutting_time = $this->getCuttingTime($wicam_file, $setting_max_drilling, $thickness_id);
$wicam_file->setCuttingTime($cutting_time);
/** @var PriceSurcharge $price_surcharge */
$price_surcharge = $entityManager->getRepository(PriceSurcharge::class)->find($price_surcharge_id);
$price_minute = $price_surcharge->getPriceMinute() * 1.0;
$piece_price = $cutting_time * $price_minute;
$piece_price = round($piece_price, 2);
$piece_price += $setting_verputzen->getValue() * 1.0;
$piece_price = $response['piece_price'] = round($piece_price, 2);
$additional_general_surcharge = $surcharge_value * 1.0;
$additional_general_surcharge = ($additional_general_surcharge / 100.0) + 1.0;
// Get surcharges EUR PER PIECE
if($wicam_header->getCustomer() != null && $wicam_header->getCustomer()->getCategory() != null){
$addtional_per_piece = $this->GetSurchargesTotals(self::EUR_PER_PIECE, self::IN_PRICE, $wicam_file->getId(),
$wicam_header->getCustomer()->getCategory()->getId());
} else {
$addtional_per_piece = $this->GetSurchargesTotals(self::EUR_PER_PIECE, self::IN_PRICE, $wicam_file->getId(),
null);
}
$additional_value_circle = $this->getAdditionalValueCircle($header_id);
$response['total_piece_price'] = round((($piece_price + $TotalPrice + $addtional_per_piece + $additional_value_circle) * $additional_general_surcharge) * $ad_handling_percent, 2);
if ($amount <= 0) { // if not amount the total piece price must be 0
$response['total_piece_price'] = 0.0;
}
$total_piece_price = $response['total_piece_price'];
$response['total'] = round(((($piece_price + $TotalPrice + $addtional_per_piece + $additional_value_circle) * $additional_general_surcharge) * $ad_handling_percent) * ($amount * 1.0), 2);
$response['total_piece_price_str'] = number_format($response['total_piece_price'], 2, ',', '.');
if ($request->getLocale() == 'en') {
$response['total_piece_price_str'] = $this->currencySymbol . ' ' . $response['total_piece_price_str'];
} else {
$response['total_piece_price_str'] = $response['total_piece_price_str'] . ' ' . $this->currencySymbol;
}
// Get surcharges EUR PER FILE
if($wicam_header->getCustomer() != null && $wicam_header->getCustomer()->getCategory() != null) {
$addtional_per_file = $this->GetSurchargesTotals(self::EUR_EFFECTIVE_PER_FILE, self::IN_PRICE, $wicam_file->getId(),
$wicam_header->getCustomer()->getCategory()->getId());
} else {
$addtional_per_file = $this->GetSurchargesTotals(self::EUR_EFFECTIVE_PER_FILE, self::IN_PRICE, $wicam_file->getId(),
null);
}
$total = $response['total'] = $response['total'] + $addtional_per_file;
$response['total_str'] = number_format($response['total'], 2, ',', '.');
if ($request->getLocale() == 'en') {
$response['total_str'] = $this->currencySymbol . ' ' . $response['total_str'];
} else {
$response['total_str'] = $response['total_str'] . ' ' . $this->currencySymbol;
}
$this->deleteWiCamFilesPriceSurcharge($wicam_file);
/** @var PriceSurcharge $ps */
foreach ($prices_surcharges_ext as $ps) {
$price_minute_ext = $ps->getPriceMinute();
$piece_price_ext = $cutting_time * $price_minute_ext;
$piece_price_ext = round($piece_price_ext, 2);
$piece_price_ext += $setting_verputzen->getValue() * 1.0;
$total_piece_price_ext = round((($piece_price_ext + $TotalPrice + $addtional_per_piece + $additional_value_circle) * $additional_general_surcharge) * $ad_handling_percent, 2);
$total_ext = round(((($piece_price_ext + $TotalPrice + $addtional_per_piece + $additional_value_circle) * $additional_general_surcharge) * $ad_handling_percent) * ($amount * 1.0), 2);
$total_ext = $total_ext + $addtional_per_file;
/** @var WiCamFilesPriceSurcharge $WiCamFilesPriceSurcharge */
$WiCamFilesPriceSurcharge = new WiCamFilesPriceSurcharge();
$WiCamFilesPriceSurcharge->setWicamFiles($wicam_file)
->setPriceSurcharge($ps)
->setPiecePrice($piece_price_ext)
->setTotalPiecePrice($total_piece_price_ext)
->setTotal($total_ext);
$entityManager->persist($WiCamFilesPriceSurcharge);
}
$real_weight = round($wicam_file->getRealWeight(), 2);
$response['real_weight'] = $real_weight;
$tooltip = $this->renderView('includes/tooltip-content.html.twig', [
'total_weight' => round($response['total_weight'], 2),
'piece_price' => $response['piece_price'],
'real_weight' => round($response['real_weight'], 2),
'total_piece_price' => $response['total_piece_price'],
'total_price' => $response['total_price']
]);
} else {
$response['total_weight'] = 0.0;
$response['total'] = 0.0;
$response['total_str'] = number_format(0.0, 2, ',', '.');
if ($request->getLocale() == 'en') {
$response['total_str'] = $this->currencySymbol . ' ' . $response['total_str'];
} else {
$response['total_str'] = $response['total_str'] . ' ' . $this->currencySymbol;
}
$real_weight = round($wicam_file->getRealWeight(), 2);
$tooltip = $this->renderView('includes/tooltip-content.html.twig',
[
'real_weight' => $real_weight
]
);
}
$wicam_file->setTotalWeight($total_weight)
->setTotalPrice($TotalPrice)
->setPiecePrice($piece_price)
->setTotalPiecePrice($total_piece_price)
->setTotal($total)
->setDeliveryCost($delivery_cost)
->setMaterialGrades($material_grades)
->setPriceSurcharge($price_surcharge);
$wicam_file->setFreightPricesCargo(null);
$wicam_file->setFreightPricesTruck(null);
// Get surcharges EUR PER PIECE SEPARATE VALUE
if(!is_null($customer)){
$this->GetSurchargesTotals(self::EUR_PER_PIECE, self::SEPARATED_PRICE, $wicam_file->getId(),
$customer->getCategory()->getId());
$this->GetSurchargesTotals(self::EUR_EFFECTIVE_PER_FILE, self::SEPARATED_PRICE, $wicam_file->getId(),
$customer->getCategory()->getId());
} else {
$this->GetSurchargesTotals(self::EUR_PER_PIECE, self::SEPARATED_PRICE, $wicam_file->getId(),
null);
$this->GetSurchargesTotals(self::EUR_EFFECTIVE_PER_FILE, self::SEPARATED_PRICE, $wicam_file->getId(),
null);
}
$response['tooltip'] = $tooltip;
$data_response[$identify] = $response;
$entityManager->flush();
}
}
// $new response
$response = [];
$response['data_files'] = $data_response;
if ($getbox) {
$response_delivery = $this->GetDeliveryType($guid, $header_id, $real_plz);
if ($response_delivery['transport'] == 3) {
$wicam_header->setDeliveryCost($response_delivery['delivery_cost']);
$wicam_header->setDeliveryType($response_delivery['transport']);
$no_plz = false;
} else if (isset($real_plz)) {
$no_plz = true;
$response_delivery = $this->GetDeliveryType($guid, $header_id, $real_plz);
$wicam_header->setDeliveryCost($response_delivery['delivery_cost']);
$wicam_header->setDeliveryType($response_delivery['transport']);
} else {
$wicam_header->setDeliveryCost(null);
$wicam_header->setDeliveryType("");
}
$entityManager->flush();
if(!is_null($customer)){
$buybox = $this->GetBuyBox($guid, $header_id, false, $customer->getCategory()->getId());
} else {
$buybox = $this->GetBuyBox($guid, $header_id, false, null);
}
$response['buybox'] = $buybox;
$response['no_plz'] = $no_plz;
$response['transport'] = $response_delivery['transport'];
}
return new JsonResponse($response);
}
private function GetSurchargesTotals(int $price_form, int $type_addition, int $wicam_file_id, $category_id)
{
/** @var EntityRepository $repository */
$repository = $this->getDoctrine()->getRepository(WiCamFilesSurcharges::class);
$qb = $repository->createQueryBuilder('ws');
if ($type_addition == self::IN_PRICE) {
$qb = $qb
->select('SUM(sc.price) AS TotalPrice')
->leftJoin('ws.surcharges', 's')
->leftJoin('ws.surcharges_category', 'sc')
->where('ws.wicam_files = :wicam_files')
->andWhere('s.price_form = :price_form')
->andWhere('s.type_addition = :type_addition')
->andWhere('s.active = :active')
->andwhere('sc.category = :category')
->setParameter('wicam_files', $wicam_file_id)
->setParameter('price_form', $price_form)
->setParameter('type_addition', $type_addition)
->setParameter('active', 1)
->setParameter('category', $category_id)
->getQuery();
$total = $qb->getOneOrNullResult();
} else {
$qb = $qb
->select('ws.id,sc.price')
->leftJoin('ws.surcharges', 's')
->leftJoin('ws.surcharges_category', 'sc')
->where('ws.wicam_files = :wicam_files')
->andWhere('s.price_form = :price_form')
->andWhere('s.type_addition = :type_addition')
->andWhere('s.active = :active')
->andWhere('sc.category = :category')
->setParameter('wicam_files', $wicam_file_id)
->setParameter('price_form', $price_form)
->setParameter('type_addition', $type_addition)
->setParameter('active', 1)
->setParameter('category', $category_id)
->getQuery()
->getResult();
$entityManager = $this->getDoctrine()->getManager();
/** @var WiCamFilesSurcharges $ws */
/** @var WiCamFiles $wicam_file $sh */
$wicam_file = $entityManager->getRepository(WiCamFiles::class)->find($wicam_file_id);
if (!empty($qb)) {
foreach ($qb as $sh) {
$ws = $entityManager->getRepository(WiCamFilesSurcharges::class)->find($sh['id']);
if ($price_form == self::EUR_PER_PIECE) {
$ws->setSeparateValue($sh['price'] * $wicam_file->getAmount());
} elseif ($price_form == self::EUR_EFFECTIVE_PER_FILE || $price_form == self::EUR_EFFECTIVE_FOR_ORDER) {
$ws->setSeparateValue($sh['price']);
}
$entityManager->flush();
}
}
$total['TotalPrice'] = 0;
}
return (empty($total['TotalPrice']) ? 0.0 : $total['TotalPrice']);
}
/**
* @Route("/upload/calculate-weight", methods={"POST"}, name="wi_cam_calculate_weight")
* @param Request $request
*
* @return JsonResponse
*/
public function CalculateRealWeight(Request $request): JsonResponse
{
/**
* @var Thickness $thickness
* @var Setting $setting
* @var WiCamFiles $wicam_file
* @var WiCamHeader $wicam_header
*/
$guid = $request->get('guid');
$header_id = $request->get('header_id');
$data_files = $request->get('data_files');
$entityManager = $this->getDoctrine()->getManager();
if ($data_files) {
foreach ($data_files as $df) {
$thickness_id = $df["thickness"];
$identify = $df['identify'];
$wicam_file = $entityManager->getRepository(WiCamFiles::class)->find($identify);
if (!empty($thickness_id)) {
$thickness = $entityManager->getRepository(Thickness::class)->findOneBy(["id" => $thickness_id]);
$setting = $entityManager->getRepository(Setting::class)->find(9);
$partNetArea = $wicam_file->getPartNetArea();
$thickness_vl = $thickness->getValue() * 1.0;
$specific_weight = $setting->getValue() * 1.0;
$real_weight = (($partNetArea * 1.0) * $thickness_vl * $specific_weight) / 1000000;
$wicam_file->setRealWeight($real_weight);
$wicam_file->setThickness($thickness);
} else {
$wicam_file->setRealWeight(null);
$wicam_file->setThickness(null);
}
//var_dump($real_weight); die;
$entityManager->flush();
}
}
return $this->Calculate($request);
}
private function getFpp($length,$width,$real_weight,$thickness){
$freightPricesPackage = $this->entityManager->getRepository(FreightPricesPackage::class)->isLike(
['length' => $length, 'width' => $width, 'weight' => $real_weight, 'height' => $thickness]);
if (!empty($freightPricesPackage)) {
$result_length = [];
$result_width = [];
$result_height = [];
$result_weight = [];
foreach ($freightPricesPackage as $fpp) {
$result_length[] = $fpp->getLength();
$result_width[] = $fpp->getWidth();
$result_height[] = $fpp->getHeight();
$result_weight[] = $fpp->getWeight();
}
$min_length = min($result_length);
$min_width = min($result_width);
$min_height = min($result_height);
$min_weight = min($result_weight);
return $fppMin = $this->entityManager->getRepository(FreightPricesPackage::class)->findBY(
['length' => $min_length, 'width' => $min_width, 'height' => $min_height, 'weight' => $min_weight],
['price' => 'ASC']
);
}
}
private function getParcelAmount($amount_left,$pieces_per_parcel,$parcel_amount){
$amount_left = $amount_left - $pieces_per_parcel;
if ($amount_left == 0) {
$parcel_amount++;
} else {
while ($amount_left != 0) {
$parcel_amount++;
if ($amount_left < 0) {
$amount_left = 0;
} else {
$amount_left = $amount_left - $pieces_per_parcel;
if($amount_left == 0){
$parcel_amount++;
}
}
}
}
return $parcel_amount;
}
function isParcelFull($total_pieces, $pieces_per_parcel) {
$parcels = ceil($total_pieces / $pieces_per_parcel);
$result = [];
for ($i = 1; $i <= $parcels; $i++) {
$remaining_pieces = $total_pieces - ($i - 1) * $pieces_per_parcel;
$is_full = ($remaining_pieces >= $pieces_per_parcel) ? true : false;
$result[] = $is_full;
}
return $result;
}
/**
* @param $guid
* @param $header_id
* @param $real_plz
*
* @return array
*/
private function GetDeliveryType($guid, $header_id, $real_plz): array
{
$entityManager = $this->getDoctrine()->getManager();
/** @var Setting $max_weight_pal */
$max_weight_pal = $entityManager->getRepository(Setting::class)->find(self::MAX_WEIGHT_PALLET);
/** @var Setting $max_length_pal */
$max_length_pal = $entityManager->getRepository(Setting::class)->find(self::MAX_LENGTH_PALLET);
/** @var Setting $max_width_pal */
$max_width_pal = $entityManager->getRepository(Setting::class)->find(self::MAX_WIDTH_PALLET);
$files = $entityManager->getRepository(WiCamFiles::class)->findBy(['wicam_header' => $header_id, 'deleted' => 0, 'validation' => '1']);
$c_cargo = 0;
$c_truck = 0;
$c_package = 0;
$sum_real_weight = 0.0;
$delivery_costPackage = 0.0;
$transport = 0;
$delivery_cost = 0.0;
$dts = new DeliveryTypeService($this->entityManager);
$parcelInfo = $dts->run($files);
// var_dump($parcelInfo);
// die;
if(!$parcelInfo['isParcel']){
/** @var WiCamFiles $item */
foreach ($files as $item) {
$width = $item->getWidth();
$length = $item->getLength();
$real_weight = $item->getRealWeight() * $item->getAmount();
$thickness = $item->getThickness()->getValue();
if (
$width <= (float)$max_width_pal->getValue()
&& $length <= (float)$max_length_pal->getValue()
&& $real_weight <= (float)$max_weight_pal->getValue()
) {
$c_cargo++;
} else {
$c_truck++;
}
$sum_real_weight += $real_weight;
}
$delivery_costCargo = 0.0;
$delivery_costTruck = 0.0;
if (!empty($real_plz)) {
/********** Calculation for Cargo **********/
$freightpricescargo = $entityManager->getRepository(FreightPricesCargo::class)->findOneBy(['postal_code' => $real_plz]);
if (!is_null($freightpricescargo)) {
if ($sum_real_weight < 150) {
$delivery_costCargo = $freightpricescargo->getRange1();
} else if (150 <= $sum_real_weight && $sum_real_weight < 300) {
$delivery_costCargo = $freightpricescargo->getRange2();
} else if (300 <= $sum_real_weight && $sum_real_weight < 500) {
$delivery_costCargo = $freightpricescargo->getRange3();
} else if (500 <= $sum_real_weight && $sum_real_weight < 800) {
$delivery_costCargo = $freightpricescargo->getRange4();
} else if (800 <= $sum_real_weight && $sum_real_weight < 1000) {
$delivery_costCargo = $freightpricescargo->getRange5();
}
}
/********** Calculation for Truck **********/
/** @var FreightPricesTruck $freightpricestruck */
$freightpricestruck = $entityManager->getRepository(FreightPricesTruck::class)->findOneBy(['postal_code' => $real_plz]);
if (!is_null($freightpricestruck)) {
$tonnes = $sum_real_weight / 1000;
while ($tonnes > 0.0) {
if ($tonnes >= 24.0) {
$delivery_costTruck += $freightpricestruck->getUpTwentyFour() * 1.0;
$tonnes = $tonnes - 24.0;
} elseif ($tonnes >= 12.0) {
$delivery_costTruck += $freightpricestruck->getUpTwelve() * 1.0;
$tonnes = $tonnes - 12.0;
} else {
$delivery_costTruck += $freightpricestruck->getUpFive() * 1.0;
$tonnes = 0.0;
}
}
}
}
// 1 = truck
// 2 == pallet
// 3 == package
if ($c_truck > 0) {
$transport = 1;
$delivery_cost = $delivery_costTruck;
} else if ($c_cargo > 0) {
if ($delivery_costCargo == 0) { // if cargo is empty then we need to send to truck
$delivery_cost = $delivery_costTruck;
$transport = 1;
} else {
if ($delivery_costCargo <= $delivery_costTruck) {
$delivery_cost = $delivery_costCargo;
$transport = 2;
} else {
$delivery_cost = $delivery_costTruck;
$transport = 1;
}
}
}
} else {
$transport = 3;
$delivery_cost = $parcelInfo['totalDeliveryCost'];
}
$response['transport'] = $transport;
$response['sum_real_weight'] = $sum_real_weight;
$response['delivery_cost'] = $delivery_cost;
return $response;
}
public function GetBuyBox($guid, $header_id, $return_data = false, $category_id)
{
$entityManager = $this->getDoctrine()->getManager();
/** @var WiCamHeader $wiCamHeader */
$wiCamHeader = $entityManager->getRepository(WiCamHeader::class)->find($header_id);
/** @var Setting $setting_min_price */
$setting_min_price = $entityManager->getRepository(Setting::class)->find(12);
$setting_value = json_decode($setting_min_price->getValue(), true);
$customer = $wiCamHeader->getCustomer();
$minimum_value = 0;
if(!is_null($customer)){
$customer_category = $customer->getCategory()->getDescription();
} else {
$customer_category = 'no_category';
}
foreach($setting_value as $k=>$s){
$categoryDescription = str_replace('category_','',$k);
if($categoryDescription == $customer_category){
$minimum_value = $s * 1.0;
}
}
if($minimum_value == 0){
$customer_category = 'no_category';
foreach($setting_value as $k=>$s){
$categoryDescription = str_replace('category_','',$k);
if($categoryDescription == $customer_category){
$minimum_value = $s * 1.0;
}
}
}
/** @var Setting $setting_mvat_percent */
$setting_mvat_percent = $entityManager->getRepository(Setting::class)->find(static::VAT_PERCENT);
/** @var EntityRepository $repository */
$repository = $entityManager->getRepository(WiCamFiles::class);
$qb = $repository->createQueryBuilder('w');
$result = $qb->select(" SUM(w.total) as total ")
->where(' w.guid = :guid ')
->andWhere(' w.deleted = 0 ')
->andWhere(' w.validation = :val_validation ')
->andWhere(' w.wicam_header = :wicam_header ')
->setParameter('guid', $guid)
->setParameter('wicam_header', $header_id)
->setParameter('val_validation', '1')
->getQuery()
->getOneOrNullResult();
/** @var WiCamHeader $wiCamHeader */
$wiCamHeader = $entityManager->getRepository(WiCamHeader::class)->find($header_id);
$old_totales = $wiCamHeader->getGeneralTotal();
// SURCHARGES
/** @var EntityRepository $repository */
$repository = $this->getDoctrine()->getRepository(WiCamFilesSurcharges::class);
$qb = $repository->createQueryBuilder('ws');
$qb = $qb
->select('s.id,s.description,SUM(sc.price) AS total')
->innerJoin('ws.surcharges', 's')
->innerJoin('ws.wicam_files', 'wf')
->innerJoin('ws.surcharges_category', 'sc')
->where('wf.wicam_header = :wicam_header')
->andWhere('s.type_addition = :type_addition')
->andWhere('s.active = :active')
->andWhere('wf.deleted = :deleted')
->andWhere('sc.category = :category')
->groupBy('s.id')
->addGroupBy('s.description')
->setParameter('wicam_header', $header_id)
->setParameter('type_addition', self::SEPARATED_PRICE)
->setParameter('active', 1)
->setParameter('deleted', 0)
->setParameter('category', $category_id)
->getQuery()
->getResult();
$surcharges_total = 0.0;
if (!empty($qb)) {
foreach ($qb as $key => $sr) {
$surcharge = $entityManager->getRepository(Surcharges::class)->find($sr['id']);
$qb[$key]['surcharge'] = $surcharge;
$surcharges_total += empty($sr['total']) ? 0.0 : $sr['total'];
}
}
$deliveryCost = !empty($wiCamHeader->getDeliveryCost()) ? $wiCamHeader->getDeliveryCost() : 0.0;
$vatPercent = $setting_mvat_percent->getValue();
$subTotal = $result['total'] + $surcharges_total + $deliveryCost;
if ($subTotal <= $minimum_value) {
$minimun_vl = $minimum_value - $subTotal;
$subTotal = $minimum_value;
}
$vatPercentTotal = $subTotal * ($vatPercent / 100);
$totales = $subTotal + $vatPercentTotal;
$wiCamHeader->setGeneralTotalPrice($result['total']);
$wiCamHeader->setSurchargesTotal($surcharges_total);
$wiCamHeader->setVatPercent($vatPercent);
$wiCamHeader->setVatPercentTotal($vatPercentTotal);
$wiCamHeader->setGeneralTotal($totales);
$entityManager->flush();
$orderReachedLimit = $this->isValidPricesLimit($header_id);
$newTotalGreaterThanOld = $totales > $old_totales ? true : false;
// var_dump($newTotalGreaterThanOld, 'totales: '.$totales.' old totales: '.$old_totales);
$show_validation_message = "";
if ($newTotalGreaterThanOld && $orderReachedLimit) {
$totales = $old_totales;
$wicamHeaderTemporal = $this->getDoctrine()->getRepository(WiCamHeaderTemp::class)->findOneBy(['wicamHeaderId' => $header_id]);
if(!empty($wicamHeaderTemporal)){
$wiCamHeader->setGeneralTotalPrice($wicamHeaderTemporal->getGeneralTotalPrice());
$wiCamHeader->setSurchargesTotal($wicamHeaderTemporal->getSurchargesTotal());
$wiCamHeader->setVatPercent($wicamHeaderTemporal->getVatPercent());
$wiCamHeader->setVatPercentTotal($wicamHeaderTemporal->getVatPercentTotal());
$wiCamHeader->setGeneralTotal($wicamHeaderTemporal->getGeneralTotal());
$entityManager->flush();
$entityManager->remove($wicamHeaderTemporal);
$entityManager->persist($wicamHeaderTemporal);
}
$show_validation_message = "YOU have reached your total purchase limit";
}
$dataCalculator = [
'total' => $result['total'],
'vatPercent' => $vatPercent,
'wicamheader' => $wiCamHeader,
'surcharges' => $qb,
'minimun' => $minimum_value,
'vatPercentTotal' => $vatPercentTotal,
'generalTotal' => $totales,
'surchargesTotal' => $surcharges_total,
'newTotal' => $newTotalGreaterThanOld,
'purchaseLimit' => $orderReachedLimit,
'val_message' => $show_validation_message,
];
if ($return_data) {
return $dataCalculator;
}
$buybox = $this->renderView('includes/buybox-wicam.html.twig', $dataCalculator);
$buybox_m = $this->renderView('includes/buybox-wicam-mobile-overview.html.twig', $dataCalculator);
$response['buyboxdp'] = $buybox;
$response['buyboxmb'] = $buybox_m;
return $response;
}
/**
* @Route("/upload/total", methods={"GET"}, name="wi_cam_total")
* @param Request $request
*
* @return JsonResponse
*/
public function Total(Request $request)
{
$entityManager = $this->getDoctrine()->getManager();
$guid = $request->get('guid');
$header_id = $request->get('header_id');
$wicam_header = $entityManager->getRepository(WiCamHeader::class)->find($header_id);
if($wicam_header->getCustomer() != null && $wicam_header->getCustomer()->getCategory() != null){
$category_id = $wicam_header->getCustomer()->getCategory()->getId();
} else {
$category_id = null;
}
$buybox = $this->GetBuyBox($guid, $header_id, false, $category_id);
$response['buybox'] = $buybox;
return new JsonResponse($response);
}
/**
* @Route("/upload/delete", methods={"POST"}, name="wi_cam_delete")
* @param Request $request
*
* @return JsonResponse
*/
public function deleteItem(Request $request)
{
$identify = $request->get('identify');
/**
* @var WiCamFiles $file
*/
$entityManager = $this->getDoctrine()->getManager();
$file = $entityManager->getRepository(WiCamFiles::class)->find($identify);
$file->setDeleted(true);
$entityManager->flush();
$response['status'] = true;
return new JsonResponse($response);
}
/**
* @Route("/upload/zipcodes", methods={"GET"}, name="wi_cam_postcodes")
* @param Request $request
*
* @return JsonResponse
*/
public function GetPostCodes(Request $request)
{
/**
* @var PostalCodes $postalcodes
*/
$term = $request->get("term");
$entityManager = $this->getDoctrine()->getManager();
$postalcodes = $entityManager->getRepository(PostalCodes::class)->findByPlzField($term);
$response = [];
$i = 0;
foreach ($postalcodes as $pt) {
$response[$i]['value'] = $pt->getPlz();
$response[$i]['label'] = $pt->getPlz() . " - " . $pt->getOrt() . " - " . $pt->getBundesland();
$response[$i]['city'] = $pt->getOrt() . " - " . $pt->getBundesland();
$i++;
}
return new JsonResponse($response);
}
public function getImage($token, $id, $collectionId)
{
$response = $this->api_client->DownloadFile($token, $id, $collectionId);
//sleep(1);
//$fileInformation = $this->GetInformationFile($token,$id);
$finalResponse = [
'image' => $response['content'],
'status' => $response['status']
];
return $finalResponse;
}
public function getImagePng($token, $id, $collectionId)
{
$response = $this->api_client->DownloadFilePng($token, $id, $collectionId);
//sleep(1);
//$fileInformation = $this->GetInformationFile($token,$id);
$finalResponse = [
'image' => $response['content'],
'status' => $response['status']
];
return $finalResponse;
}
private function GetToken(Request $request)
{
/*$token_response = $this->tokenClient->getToken();
$request->getSession()->set("wicam_token",$token_response['access_token']);
$token_send = $token_response['access_token'];*/
$session = $request->getSession();
$token_send = $session->get('wicam_token');
$token_time = $session->get('wicam_token_time');
$now = date('Y-m-d H:i:s');
if (!empty($token_time)) {
$start_ts = strtotime($token_time);
$end_ts = strtotime($now);
$diff = $end_ts - $start_ts;
$diffFinal = round($diff / 60);
if ($diffFinal > 55) {
$token_send = '';
}
} else {
$token_send = '';
}
if (empty($token_send)) {
$token_response = $this->tokenClient->getToken();
$request->getSession()->set("wicam_token", $token_response['access_token']);
$request->getSession()->set("wicam_token_time", $now);
$token_send = $token_response['access_token'];
}
return $token_send;
}
/**
* @param $wicam_header_id
*
* @return mixed
* @throws \Doctrine\ORM\NonUniqueResultException
*/
public function getCuttingTimeByWicamHeader($wicam_header_id)
{
$repository_cutting = $this->getDoctrine()->getRepository(WiCamFiles::class);
$qb_cutting = $repository_cutting->createQueryBuilder('qc');
$qb_cutting = $qb_cutting
->select('COALESCE(SUM(qc.cutting_time*qc.amount),0.0) AS cutting_time')
->where('qc.wicam_header = :wicam_header')
->andWhere('qc.deleted = :deleted')
->setParameter('wicam_header', $wicam_header_id)
->setParameter('deleted', 0)
->getQuery()
->setMaxResults(1)
->getOneOrNullResult();
return $qb_cutting['cutting_time'];
}
/**
* @Route("/upload/calendar_settings/{id}", methods={"GET"}, name="wi_cam_calendar_days")
* @param Request $request
*
* @return JsonResponse
*/
public function getDeliveryDays(Request $request): JsonResponse
{
$date_initial = new \DateTime("NOW");
/** @var PriceSurcharge $priceSurcharge
* @var PriceSurcharge $priceSurchargeNext
* @var Setting $setting
*/
$wicam_header_id = $request->get("id");
/** @var WiCamHeader $wicam_header */
$wicam_header = $this->getDoctrine()->getRepository(WiCamHeader::class)->find($wicam_header_id);
if($wicam_header->getCustomer() != null && $wicam_header->getCustomer()->getCategory() != null) {
$category_id = $wicam_header->getCustomer()->getCategory()->getId();
} else {
$category_id = null;
}
// Get Max Additional days
/** @var EntityRepository $repository */
$repository = $this->getDoctrine()->getRepository(WiCamFilesSurcharges::class);
$qb = $repository->createQueryBuilder('ws');
$qb = $qb
->select('MAX(s.addition_days) as addition_days')
->leftJoin('ws.surcharges', 's')
->leftJoin('ws.wicam_files', 'wf')
->where('wf.wicam_header = :wicam_header')
->andWhere('s.active = :active')
->andWhere('wf.deleted = :deleted')
->setParameter('wicam_header', $wicam_header_id)
->setParameter('active', 1)
->setParameter('deleted', 0)
->getQuery()
->getResult();
$repository = $this->getDoctrine()->getRepository(WiCamFilesSurcharges::class);
$qbTotals = $repository->createQueryBuilder('ws');
$qbTotals = $qbTotals
->select('COALESCE(SUM(sc.price),0.0) AS total')
->leftJoin('ws.surcharges', 's')
->leftJoin('ws.wicam_files', 'wf')
->leftJoin('ws.surcharges_category', 'sc')
->where('wf.wicam_header = :wicam_header')
->andWhere('s.type_addition = :type_addition')
->andWhere('s.active = :active')
->andWhere('wf.deleted = :deleted')
->andWhere('sc.category = :category')
->setParameter('wicam_header', $wicam_header_id)
->setParameter('type_addition', self::SEPARATED_PRICE)
->setParameter('active', 1)
->setParameter('deleted', 0)
->setParameter('category', $category_id)
->getQuery()
->setMaxResults(1)
->getOneOrNullResult();
$addition_days = $qb[0]['addition_days'];
$labels = [];
$colors = [];
$legends_colors = [];
$sum_cutting_time = $this->getCuttingTimeByWicamHeader($wicam_header_id);
$priceSurcharge = $this->getDoctrine()->getRepository(PriceSurcharge::class)->findOneByDaysNextException(0, $sum_cutting_time);
$setting = $this->getDoctrine()->getRepository(Setting::class)->find(10);
$max_available_days = $setting->getValue();
$is_first_date = true;
$min = '';
while (!empty($priceSurcharge)) {
$date_initial = new \DateTime("NOW");
$priceSurchargeNext = $this->getDoctrine()->getRepository(PriceSurcharge::class)->findOneByDaysNextException($priceSurcharge->getId(), $sum_cutting_time);
//$date_initial->add(new \DateInterval('P'.$priceSurcharge->getDays().'D'));
$days_increment = 0;
if (!$is_first_date) {
$days_increment = 1;
}
for ($i = 1; $i <= ($priceSurcharge->getDays() + $days_increment); $i++) {
$date_initial = $this->AddDateExcludeWeekends($date_initial, 1);
}
if ($is_first_date) {
$min = $date_initial->format('Y-m-d');
}
$is_first_date = false;
//echo "\n".($priceSurcharge->getDays()+1)."\n\n";
$date_f = $date_initial->format('Y-m-d');
$date_fi = str_replace("-", "", $date_f);
//echo $date_f."\n";
$labels["$date_f"] = ['start' => $date_f, 'price_surcharge' => $priceSurcharge->getId()];
//$labels[$date_f] = array('start'=>$date_f,'title'=>'$ '.$priceSurcharge->getPriceMinute(),'price_surcharge'=>$priceSurcharge->getId());
$colors["$date_f"] = ['date' => $date_f, 'background' => $priceSurcharge->getColor(), 'textcolor' => $priceSurcharge->getTextColor(), 'name' => $priceSurcharge->getName(), 'price_surcharge' => $priceSurcharge->getId(), 'price' => '€ ' . $priceSurcharge->getPriceMinute()];
$labels_index["$date_f"] = $priceSurcharge->getId();
if (empty($priceSurchargeNext)) {
$max_days = $max_available_days;
} else {
$max_days = $priceSurchargeNext->getDays();
}
$max_days = (int)$max_days;
for ($i = 1; $i <= $max_days; $i++) {
//$date_initial->add(new \DateInterval('P1D'));
$date_initial = $this->AddDateExcludeWeekends($date_initial, 1);
$date_f = $date_initial->format('Y-m-d');
$date_fi = str_replace("-", "", $date_f);
//echo $date_f."\n";
$labels["$date_f"] = ['start' => $date_f, 'price_surcharge' => $priceSurcharge->getId()];
//$labels[$date_f] = array('start'=>$date_f,'title'=>'$ '.$priceSurcharge->getPriceMinute(),'price_surcharge'=>$priceSurcharge->getId());
$colors["$date_f"] = ['date' => $date_f, 'background' => $priceSurcharge->getColor(), 'textcolor' => $priceSurcharge->getTextColor(), 'name' => $priceSurcharge->getName(), 'price_surcharge' => $priceSurcharge->getId(), 'price' => '€ ' . $priceSurcharge->getPriceMinute()];
$labels_index["$date_f"] = $priceSurcharge->getId();
}
$priceSurcharge = $priceSurchargeNext;
}
for ($i = 0; $i < $addition_days; $i++) {
array_shift($labels);
array_shift($colors);
array_shift($labels_index);
}
$labels_copy = $labels;
reset($labels_copy);
$min = key($labels_copy);
/** @var Setting $setting */
$setting = $this->getDoctrine()->getRepository(Setting::class)->find(12);
$setting_value = json_decode($setting->getValue(), true);
$customer = $wicam_header->getCustomer();
$minimum_value = 0;
if(!is_null($customer)){
$customer_category = $customer->getCategory()->getDescription();
} else {
$customer_category = 'no_category';
}
foreach($setting_value as $k=>$s){
$categoryDescription = str_replace('category_','',$k);
if($categoryDescription == $customer_category){
$minimum_value = $s * 1.0;
}
}
if($minimum_value == 0){
$customer_category = 'no_category';
foreach($setting_value as $k=>$s){
$categoryDescription = str_replace('category_','',$k);
if($categoryDescription == $customer_category){
$minimum_value = $s * 1.0;
}
}
}
$new_labels = [];
foreach ($labels as $lb) {
$new_labels[] = $lb;
}
$new_colors = [];
$is_first_price_surcharge = true;
$first_price_surcharge = 0;
foreach ($colors as $lb) {
$new_colors[] = $lb;
$totals = $this->getDoctrine()->getManager()->getRepository(WiCamFilesPriceSurcharge::class)->findTotalByWiCamHeader($wicam_header_id, $lb['price_surcharge']);
$totals += $qbTotals['total'];
$totals += $wicam_header->getDeliveryCost();
$totals = $totals <= $minimum_value ? $minimum_value : $totals;
//$legends_colors[$lb['price_surcharge']] = array($lb['background'],$lb['price']);
$value_m = number_format($totals, 2, ',', '.');
if ($request->getLocale() == 'en') {
$value_m = $this->currencySymbol . ' ' . $value_m;
} else {
$value_m = $value_m . ' ' . $this->currencySymbol;
}
$legends_colors[$lb['price_surcharge']] = [$lb['background'], $value_m, (empty($lb['name']) ? ' ' : $lb['name']), $lb['textcolor']];
if ($is_first_price_surcharge) {
$is_first_price_surcharge = false;
$first_price_surcharge = $lb['price_surcharge'];
}
}
// Set invalid parameters
$invalid = [];
$invalid[] = ['recurring' => ['repeat' => 'weekly', 'weekDays' => 'SA,SU']];
// add holidays
$holidays = $this->getDoctrine()->getRepository(Holiday::class)->findAllHolidaysFromNow();
if ($holidays) {
foreach ($holidays as $h) {
$hd = $h->getDate();
$invalid[] = $hd->format('Y-m-d');
}
}
$max = $date_initial->format('Y-m-d');
return new JsonResponse(['labels' => $new_labels, 'colors' => $new_colors, 'labels_index' => $labels_index, 'legends_colors' => $legends_colors, 'invalid' => $invalid, 'min' => $min, 'max' => $max, 'first_price_surcharge' => $first_price_surcharge, 'cutting_time' => $sum_cutting_time]);
}
private function AddDateExcludeWeekends($date_initial, $number)
{
$date_initial->add(new \DateInterval('P' . $number . 'D'));
$dayOfWeek = date('w', strtotime($date_initial->format('Y-m-d')));
$holiday = $this->getDoctrine()->getRepository(Holiday::class)->findOneByDateFromNow($date_initial->format('Y-m-d'));
while ($dayOfWeek == 6 || $dayOfWeek == 0 || !empty($holiday)) {
$date_initial->add(new \DateInterval('P1D'));
$dayOfWeek = date('w', strtotime($date_initial->format('Y-m-d')));
$holiday = $this->getDoctrine()->getRepository(Holiday::class)->findOneByDateFromNow($date_initial->format('Y-m-d'));
//echo 'Add new date-> '.$date_initial->format('Y-m-d')." - ".$dayOfWeek."\n";
}
return $date_initial;
}
/**
* @Route("/upload/wicam_files_surcharges", methods={"POST"}, name="wi_cam_files_surcharges")
* @param Request $request
*
* @return JsonResponse
*/
public function WiCamFilesSurcharges(Request $request): JsonResponse
{
$wicam_file_id = $request->get("wicam_file");
$identify = $request->get("identify");
$type = $request->get("type");
$entityManager = $this->getDoctrine()->getManager();
$w_surcharges = $entityManager->getRepository(WiCamFilesSurcharges::class)->findBy(['wicam_files' => $wicam_file_id, 'surcharges' => $identify]);
if (!empty($w_surcharges)) {
foreach ($w_surcharges as $sch) {
$entityManager->remove($sch);
}
}
if ($type == 'add') {
$surcharges = $entityManager->getRepository(Surcharges::class)->find($identify);
$wicam_file = $entityManager->getRepository(WiCamFiles::class)->find($wicam_file_id);
if($wicam_file->getWicamHeader()->getCustomer() != null && $wicam_file->getWicamHeader()->getCustomer()->getCategory() != null){
$category_id = $wicam_file->getWicamHeader()->getCustomer()->getCategory();
} else {
$category_id = null;
}
if($surcharges != null){
$surcharges_id = $surcharges;
} else {
$surcharges_id = null;
}
$surcharges_category = $entityManager->getRepository(SurchargesCategory::class)->findOneBy(['category_id' => $category_id, 'surcharges_id' => $surcharges_id]);
/** @var WiCamFilesSurcharges $wicam_files_surcharges */
$wicam_files_surcharges = new WiCamFilesSurcharges();
$wicam_files_surcharges->setWicamFiles($wicam_file)
->setSurcharges($surcharges)
->setSurchargesCategory($surcharges_category);
$entityManager->persist($wicam_files_surcharges);
}
$entityManager->flush();
return new JsonResponse(['status' => true]);
}
/**
* @Route("/upload/multiple_surcharges", methods={"POST"}, name="multiple_surcharges")
* @param Request $request
*
* @return JsonResponse
*/
public function MultipleSurcharges(Request $request): JsonResponse
{
$entityManager = $this->getDoctrine()->getManager();
$header_id = $request->get("header_id");
$surcharges = $request->get("data");
/** @var WiCamHeader $wicam_header */
/** @var WiCamFiles $wicamFile */
$wicam_header = $entityManager->getRepository(WiCamHeader::class)->find($header_id);
foreach ($wicam_header->getWicamFiles() as $wicamFile) {
/** @var WiCamFilesSurcharges $ws */
foreach ($wicamFile->getWiCamFilesSurcharges() as $ws) {
if ($ws->getSurcharges()->getAllowToApplyAll()) {
$entityManager->remove($ws);
}
}
/** @var WiCamFilesSurcharges $wicamsurcharge */
if (count($surcharges) > 0) {
/** @var Surcharges $surcharge */
foreach ($surcharges as $surch) {
$surcharge = $entityManager->getRepository(Surcharges::class)->find($surch);
if($surcharge != null){
$surcharge_id = $surcharge;
} else {
$surcharge_id = null;
}
if($wicam_header->getCustomer() != null && $wicam_header->getCustomer()->getCategory() != null) {
$category_id = $wicam_header->getCustomer()->getCategory();
} else {
$category_id = null;
}
$surcharge_category = $entityManager->getRepository(SurchargesCategory::class)->findOneBy(['category_id' => $category_id, 'surcharges_id' => $surcharge_id]);
$wicamsurcharge = new WiCamFilesSurcharges();
$wicamsurcharge->setWicamFiles($wicamFile);
$wicamsurcharge->setSurcharges($surcharge);
$wicamsurcharge->setSurchargesCategory($surcharge_category);
$entityManager->persist($wicamsurcharge);
}
}
}
$entityManager->flush();
return new JsonResponse(['msg' => 'done']);
}
/**
* @Route("/upload/get_diameter_hole", methods={"POST"}, name="wi_cam_get_diameters")
* @param Request $request
*
* @return JsonResponse
*/
public function getDiameterHoles(Request $request): JsonResponse
{
$thickness = $request->get('thickness');
$amount = $request->get('amount');
$identify = $request->get('identify');
/** @var Thickness $thick */
$thick = $this->getDoctrine()->getRepository(Thickness::class)->find($thickness);
$thickness_value = $thick->getValue();
$wicam_file_circles = $this->getDoctrine()->getRepository(WiCamFilesCircles::class)->findBy(['wicam_files' => $identify]);
$html_response = [];
if ($wicam_file_circles) {
/** @var WiCamFilesCircles $wicam_circle */
foreach ($wicam_file_circles as $wicam_circle) {
$diameters = $this->getDoctrine()->getRepository(DiameterHole::class)->findByThicknessAmount($thickness_value, $wicam_circle->getAmount());
$html = $this->renderView('includes/wicam-diameter-hole.html.twig', ['diameters' => $diameters]);
$html_response[$wicam_circle->getDiameter()]['html'] = $html;
$html_response[$wicam_circle->getDiameter()]['count'] = count($diameters);
}
}
return new JsonResponse([
'html_response' => $html_response,
'thickness_value' => $thickness_value
]);
}
/**
* @Route("/upload/set_circle_data", methods={"POST"}, name="wi_cam_get_circle_data")
* @param Request $request
*
* @return JsonResponse
*/
public function setWiCamFilesCircles(Request $request): JsonResponse
{
$identify = $request->get('identify');
$diameter = $request->get('diameter');
$technology = $request->get('technology');
$diameter_hole_id = $request->get('diameter_hole');
$wicam_file = $this->getDoctrine()->getRepository(WiCamFiles::class)->find($identify);
/** @var WiCamFilesCircles $WiCamCircle */
$manager = $this->getDoctrine()->getManager();
$WiCamCircle = $manager->getRepository(WiCamFilesCircles::class)->findOneByWiCamFileDiameter($identify, $diameter);
$response = ['not done'];
if (!empty($diameter_hole_id)) {
$diameter_hole = $this->getDoctrine()->getRepository(DiameterHole::class)->find($diameter_hole_id);
$WiCamCircle->setDiameterHole($diameter_hole);
$response = ['done'];
} else {
$WiCamCircle->setDiameterHole(null);
$response = ['done'];
}
if (!empty($technology)) {
$WiCamCircle->setTechnology($technology);
if ($technology == 1) {
$WiCamCircle->setDiameterHole(null);
}
$response = ['done'];
}
$manager->flush();
return new JsonResponse($response);
}
/**
* @Route("/upload/print_offer", methods={"POST","GET"}, name="wi_cam_print_offer")
* @param Request $request
*
* @return Response
*/
public function print_offer(Request $request)
{
$header_id = $request->get('code-of');
//dump($header_id);
$response = $this->printOffer($header_id, $request->getLocale());
//dump($response);
$filename = $response['filename'];
$pdf = $response['pdf'];
$pdf->Output($filename, 'I');
/*return new JsonResponse(array("path"=>'/offerFiles/'.$filename,
"realname"=>$filename));*/
return new Response();
}
public function printOffer($header_id, $locale, $return = false)
{
if (empty($header_id)) {
return $this->redirectToRoute('wi_cam_home');
}
// $header_id = 502;
$entityManager = $this->getDoctrine()->getManager();
/** @var WiCamHeader $wicam_heafder */
/** @var WiCamFiles $wicam_files */
$wicam_header = $entityManager->getRepository(WiCamHeader::class)->find($header_id);
if($wicam_header->getCustomer() != null && $wicam_header->getCustomer()->getCategory() != null) {
$total_data = $this->GetBuyBox($wicam_header->getGuid(), $header_id, true, $wicam_header->getCustomer()->getCategory()->getId());
} else {
$total_data = $this->GetBuyBox($wicam_header->getGuid(), $header_id, true, null);
}
/*return array('total' => $result['total'],
'wicamheader' => $wiCamHeader,
'surcharges' => $qb,
'minimun'=>$setting);*/
$wicam_files = $entityManager->getRepository(WiCamFiles::class)->findBy(['wicam_header' => $header_id, 'validation' => 1, 'deleted' => 0], ['orden' => 'ASC']);
$total = $entityManager->getRepository(WiCamFilesPriceSurcharge::class)->findTotalByWiCamHeader($header_id, $wicam_header->getPriceSurcharge()->getId());
$offer_text = $entityManager->getRepository(Setting::class)->find(self::SETTING_OFFER_TEXT);
$vatPercent = $entityManager->getRepository(Setting::class)->find(static::VAT_PERCENT)->getValue();
$offer_text = unserialize($offer_text->getValue());
$offer_text = $offer_text[$locale];
$defaultId = $entityManager->getRepository(Setting::class)->find(self::DEFAULT_REPRESENTATIVE);
$defaultRepresentative = $entityManager->getRepository(Representative::class)->find($defaultId->getValue());
/** @var Setting $setting */
$setting = $entityManager->getRepository(Setting::class)->find(self::MAX_DRILLING_DIAMETER_ID);
// dump($defaultRepresentative);
// Retrieve the HTML generated in our twig file
$html = $this->renderView('wicam/print-offer.html.twig', [
'wicam_header' => $wicam_header,
'wicam_files' => $wicam_files,
'totalsum' => $total,
'total' => $total_data['total'],
'vatPercent' => $vatPercent,
'wicamheader' => $total_data['wicamheader'],
'surcharges' => $total_data['surcharges'],
'minimun' => $total_data['minimun'],
'offer_text' => $offer_text,
'defaultRepresentative' => $defaultRepresentative,
'MAX_DRILLING_DIAMETER' => $setting->getValue()
]);
$pdf = new PrintOffer();
$html_header = $this->renderView('wicam/print-header-offer.html.twig', [
'header' => ''
]);
$html_footer = $this->renderView('wicam/print-footer-offer.html.twig', [
'footer' => ''
]);
$pdf->htmlHeader = $html_header;
$pdf->htmlFooter = $html_footer;
//$pdf->SetMargins(0.3,0.3,0.2,20);// left, top, right
$pdf->startPageGroup();
$pdf->SetMargins(20, 36); //left, top, right
$pdf->setHeaderMargin(12);
$pdf->SetAutoPageBreak(true, 40);
$pdf->AddPage('P', 'A4');
//$pdf->AddPage('L', 'A4');
// Retrieve the HTML generated in our twig file
//echo $html;
//die;
$pdf->writeHTML($html, true, false, false, false, '');
$pdf->lastPage();
$orderNumber = $wicam_header->getOrderNumber();
if ($orderNumber > 0) {
$filename = "Order" . "_" . $wicam_header->getOrderNumber() . ".pdf";
} else {
$filename = "Offer" . "_" . $wicam_header->getId() . ".pdf";
}
ob_clean();
$publicDirectory = $this->getParameter('kernel.project_dir') . '/public/offerFiles';
if ($return) {
$realDirectory = $publicDirectory . '/' . $filename;
$pdf->Output($realDirectory, 'F');
return ['path' => $realDirectory];
} else {
return ['filename' => $filename, 'pdf' => $pdf];
}
}
/**
* @Route("/upload/update_positions", methods={"POST"}, name="wi_cam_update_positions")
* @param Request $request
*
* @return JsonResponse
*/
public function update_positions(Request $request): JsonResponse
{
$positions = $request->get('positions');
$entityManager = $this->getDoctrine()->getManager();
if (!empty($positions)) {
foreach ($positions as $item) {
$id = $item['identify'];
$orden = $item['order'];
/** @var WiCamFiles $wf */
$wf = $entityManager->getRepository(WiCamFiles::class)->find($id);
$wf->setOrden($orden);
$entityManager->flush();
}
}
return new JsonResponse(['msg' => 'update_positions']);
}
/**
* @Route("/upload/orderNow", name="wi_cam_create_order")
* @param Request $request
* @param WicamOrderHelper $wicamOrderHelper
*
* @return JsonResponse
*/
public function create_order(Request $request, WicamOrderHelper $wicamOrderHelper): Response
{
if ($this->getUser()) {
$wicamOrderHelper->setLocale($request->getLocale());
$parameters = [];
if (isset($_COOKIE['wsCode'])) {
$wsCode = $_COOKIE['wsCode'];
if (!empty($wsCode)) {
if (is_numeric($wsCode)) {
$wsCodeEn = $this->encryptor->encrypt($wsCode);
setcookie('wsCode', $wsCodeEn, time() + 604800, '/');
} else {
$wsCode = $this->encryptor->decrypt($wsCode);
}
$parameters = $wicamOrderHelper->OfferToOrder($wsCode);
//$parameters = array('status'=>true,'orderNumber'=>1,'type_error'=>'');
if ($parameters['status']) {
$vatPercent = $this->getDoctrine()->getRepository(Setting::class)->find(static::VAT_PERCENT)->getValue();
$wicamHeader = $this->getDoctrine()->getRepository(WiCamHeader::class)->find($wsCode);
$WiCamFiles = $this->getDoctrine()->getRepository(WiCamFiles::class)->findByHeader($wsCode);
$parameters['wicamHeader'] = $wicamHeader;
$parameters['WiCamFiles'] = $WiCamFiles;
if($wicamHeader->getCustomer() != null && $wicamHeader->getCustomer()->getCategory() != null) {
$total_data = $this->GetBuyBox($wicamHeader->getGuid(), $wicamHeader->getId(), true, $wicamHeader->getCustomer()->getCategory()->getId());
} else {
$total_data = $this->GetBuyBox($wicamHeader->getGuid(), $wicamHeader->getId(), true, null);
}
//$total_data = $this->GetBuyBox($wicamHeader->getGuid(), $wicamHeader->getId(), true,$wicamHeader->getCustomer()->getCategory()->getId());
$parameters['wicamheader'] = $total_data['wicamheader'];
$parameters['surcharges'] = $total_data['surcharges'];
$parameters['minimun'] = $total_data['minimun'];
$parameters['total'] = $total_data['total'];
$parameters['vatPercent'] = $vatPercent;
// destroy cookie if the offer it correctly converted
setcookie("wsCode", "", time() - 3600, '/');
}
}
} else {
$parameters = ['status' => false, 'type_error' => 'NOTHING_TO_ORDER'];
}
return $this->render('checkout/checkout-wicam.html.twig', $parameters);
} else {
return $this->redirectToRoute('app_login', ['referer' => $this->generateUrl('wi_cam_home')]);
}
}
public function orders(Request $request, AdminOrdersController $adminOrdersController, PaginatorInterface $paginator): Response
{
if (!$this->getUser()) {
return $this->redirectToRoute('app_login');
}
$are_orders = empty($request->get('are_orders')) ? false : $request->get('are_orders');
$data = [];
$itemsPerPage = 10;
/** @var User $user */
$user = $this->getUser();
if (count($user->getUserRepresentatives()) > 0) {
/** @var UserRepresentative $userRepresentative */
$userRepresentative = $user->getUserRepresentatives()[0];
$data['representative'] = $userRepresentative->getRepresentative()->getId();
$sort = !empty($request->get('sort')) ? $request->get('sort') : "wh.orderNumber";
$direction = !empty($request->get('direction')) ? $request->get('direction') : "desc";
$orders = $adminOrdersController->GetOrders($data, $sort, $direction, false, $are_orders);
} else if ($user->getActiveCustomerForUserCustomer()) {
$data['customer'] = $user->getActiveCustomerForUserCustomer();
$sort = !empty($request->get('sort')) ? $request->get('sort') : "wh.orderNumber";
$direction = !empty($request->get('direction')) ? $request->get('direction') : "desc";
$orders = $adminOrdersController->GetOrders($data, $sort, $direction, false, $are_orders);
} else {
$orders = [];
}
$pagination = $paginator->paginate(
$orders, /* query NOT result */
$request->get("page", 1),
$itemsPerPage, /*limit per page*/
['wrap-queries' => true]
);
return $this->render(
'account/orders.html.twig', [
'popup_message' => getenv("ENVIRONMENT"),
'are_orders' => $are_orders,
'orders' => $orders,
'pagination' => $pagination
]
);
}
/**
* @Route("/upload/reload-entry", name="wi_cam_reload_entry")
* @param Request $request
*
* @return JsonResponse
*/
public function reloadOrder(Request $request, WicamOrderHelper $wicamOrderHelper): JsonResponse
{
if (!$this->getUser()) {
die();
}
/** @var WiCamHeaderTemp $wh */
// $wh = $this->getDoctrine()->getRepository(WiCamHeaderTemp::class)->find($request->get('id'));
// var_dump($request->get('id'));
// var_dump($wh);
/** @var WiCamHeader $wicamHeader */
$wicamHeader = $this->getDoctrine()->getRepository(WiCamHeader::class)->find($request->get('id'));
// var_dump($wicamHeader);
$sendEmail = $request->get('sendEmail');
$sendEmail = $sendEmail == 'true' ? true : false;
// $representativeId = $wh->getRepresentativeId();
// $representative = $this->getDoctrine()->getRepository(Representative::class)->find($representativeId);
if ($wicamHeader->getIsOrder()) {
if ($sendEmail) {
$wicamOrderHelper->SendEmailOrder($wicamHeader->getRepresentative(), $wicamHeader);
}
}
$html = $this->renderView('account/order-entry.html.twig', ['wh' => $wicamHeader, 'are_orders' => $wicamHeader->getIsOrder()]);
// var_dump($html);
return new JsonResponse(['html' => $html]);
}
/**
* @Route("/upload/convert-order", name="wi_cam_convertorder")
* @param Request $request
* @param WicamOrderHelper $orderWicamHelper
*
* @return JsonResponse
*/
function ConvertToOrder(Request $request, WicamOrderHelper $orderWicamHelper): JsonResponse
{
$id = $request->get("id");
$orderWicamHelper->setLocale($request->getLocale());
return new JsonResponse($orderWicamHelper->OfferToOrder($id, false));
}
/**
* @param WiCamFiles $wicam_file
* @param Thickness $thickness
* @param SurchargeDimensions $surcharge_dimension
* @param Setting $setting_specific_weight
*
* @return float
*/
private function getTotalWeight(
WiCamFiles $wicam_file,
Thickness $thickness,
SurchargeDimensions $surcharge_dimension,
Setting $setting_specific_weight): float
{
$width = $wicam_file->getWidth();
$length = $wicam_file->getLength();
$thickness_vl = $thickness->getValue() * 1.0;
$width_s = $surcharge_dimension->getWidth() * 1.0;
$specific_weight = $setting_specific_weight->getValue() * 1.0;
$pre_weight = $thickness_vl * ($width + $width_s) * ($length + $width_s) * $specific_weight;
$pre_weight = $pre_weight / 1000000;
return $pre_weight * ($thickness->getScrapFactor() * 1.0);
}
/**
* @param array $surcharges_handlings
* @param $total_weight
* @param $amount
* @param $customer
*
* @return float|null
*/
private function getAddtionalHandling(array $surcharges_handlings, $total_weight, $amount,
$customer): ?float
{
$entityManager = $this->getDoctrine()->getManager();
$additional_handling = 0.0;
if ($surcharges_handlings) {
/** @var SurchargeHandling $sh */
foreach ($surcharges_handlings as $sh) {
$filter_operator_to = '';
$filter_operator_to_pi = '';
if (!empty($sh->getWeightTo()) && !empty($sh->getOperatorTo())) {
$filter_operator_to = ' && ' . $total_weight . $sh->getOperatorTo() . $sh->getWeightTo();
}
if ($sh->getPiecesValidation()) {
if (!empty($sh->getNumberPiecesTo()) && !empty($sh->getOperatorPiecesTo())) {
$filter_operator_to_pi = ' && ' . $amount . $sh->getOperatorPiecesTo() . $sh->getNumberPiecesTo();
}
eval('$res = ' . $total_weight . $sh->getOperator() . $sh->getWeight() . $filter_operator_to . ' && ' . $amount . $sh->getOperatorPieces() . $sh->getNumberPieces() . $filter_operator_to_pi . ';');
} else {
eval(' $res = ' . $total_weight . $sh->getOperator() . $sh->getWeight() . $filter_operator_to . ';');
}
if ($res) {
$surcharges_handlings_category_repository = $entityManager->getRepository(SurchargesHandlingCategory::class);
if(!is_null($customer)){
if(!is_null($customer->getCategory())){
$surcharges_handlings_category = $surcharges_handlings_category_repository->findOneBy(['surcharges_handling_id' => $sh->getId(), 'category_id' => $customer->getCategory()->getId()]);
$customer_category = $customer->getCategory()->getDescription();
$surchargeHandlingCategory = $surcharges_handlings_category->getCategory()->getDescription();
if($customer_category == $surchargeHandlingCategory){
$additional_handling += $surcharges_handlings_category->getPercent();
}
} else {
$surcharges_handlings_category = $surcharges_handlings_category_repository->findOneBy(['surcharges_handling_id' => $sh->getId()]);
$customer_category = 'no_category';
$additional_handling += $surcharges_handlings_category->getPercent();
}
} else {
$surcharges_handlings_category = $surcharges_handlings_category_repository->findOneBy(['surcharges_handling_id' => $sh->getId()]);
$customer_category = 'no_category';
$additional_handling += $surcharges_handlings_category->getPercent();
}
}
}
}
return ($additional_handling / 100) + 1;
}
/**
* @param WiCamFiles $wicam_file
* @param $thickness_id
* @param $material_grade_id
*
* @return float|null
*/
private function getPriceMaterialAndSurcharges(WiCamFiles $wicam_file, $thickness_id, $material_grade_id): ?float
{
$entityManager = $this->getDoctrine()->getManager();
/** @var MaterialPrices $material_prices */
$MaterialPrices = $entityManager->getRepository(MaterialPrices::class)->findOneByThicknessMaterial($thickness_id, $material_grade_id);
$totalMaterialPrices = $MaterialPrices->getValue() * 1.0;
$surcharges = $wicam_file->getWiCamFilesSurcharges();
if (!empty($surcharges)) {
/** @var WiCamFilesPriceSurcharge $sh */
foreach ($surcharges as $sh) {
if ($sh->getSurcharges()->getPriceForm() == self::EUR_PER_TON) {
$surchargesThickness = $entityManager->getRepository(SurchargesThickness::class)->findBy(['thickness' => $thickness_id, 'surcharges' => $sh->getSurcharges()->getId()]);
if (!empty($surchargesThickness)) {
/** @var SurchargesThickness $st */
foreach ($surchargesThickness as $st) {
$totalMaterialPrices += $st->getValue();
}
}
}
}
}
return $totalMaterialPrices;
}
/**
* @param WiCamFiles $wicam_file
* @param Setting $setting_max_drilling
* @param $thickness_id
*
* @return float
*/
private function getCuttingTime(WiCamFiles $wicam_file, Setting $setting_max_drilling, $thickness_id): float
{
$entityManager = $this->getDoctrine()->getManager();
$REDUCTION_CUTTING_TIME = 0.0;
$REDUCING_CONTURS = 0.0;
$contours = $wicam_file->getContours();
$cutLenght = $wicam_file->getTotalLenght();
/** @var FeedData $feed_data */
$feed_data = $entityManager->getRepository(FeedData::class)->findOneByThickness($thickness_id);
$mm_min = $feed_data->getMmMin() * 1.0;
$punching_time = $feed_data->getPunchingTime() * 1.0;
$circles = $wicam_file->getWiCamFilesCircles();
if (!empty($circles)) {
/** @var WiCamFilesCircles $cl */
foreach ($circles as $cl) {
if ($cl->getTechnology() == 2 || $cl->getTechnology() == 3 || $cl->getDiameter() >= $setting_max_drilling->getValue()) {
$REDUCTION_CUTTING_TIME += $cl->getDiameter() * M_PI * $cl->getAmount();
$REDUCING_CONTURS += $cl->getAmount();
}
}
}
$REDUCTION_CUTTING_TIME = round($REDUCTION_CUTTING_TIME, 2);
return ((($cutLenght - $REDUCTION_CUTTING_TIME) / $mm_min) + ((($contours - $REDUCING_CONTURS) * $punching_time) / 60));
}
/**
* @param $header_id
*
* @return float
*/
private function getAdditionalValueCircle($header_id): float
{
/** @var EntityRepository $repository */
$repository = $this->getDoctrine()->getRepository(WiCamFilesCircles::class);
$qb = $repository->createQueryBuilder('ws');
$qb = $qb
->select('COALESCE(SUM(dh.value * ws.amount),0.0) as total')
->innerJoin('ws.wicam_files', 'wf')
->innerJoin('ws.diameter_hole', 'dh')
->where('wf.wicam_header = :wicam_header')
->andWhere('ws.technology = :technology')
->setParameter('wicam_header', $header_id)
->setParameter('technology', 2)
->getQuery()
->getResult();
return $qb[0]['total'];
}
/**
* @param WiCamFiles $wicam_file
*
* @return void
*/
private function deleteWiCamFilesPriceSurcharge(WiCamFiles $wicam_file)
{
$entityManager = $this->getDoctrine()->getManager();
$query = $entityManager->createQuery(
'DELETE
FROM App\Entity\WiCamFilesPriceSurcharge p
WHERE p.wicam_files = :wicam_file'
)->setParameter('wicam_file', $wicam_file->getId());
$query->getResult();
}
/**
* @Route("/upload/test-email", name="wi_cam_test-email")
* @param Request $request
* @param MailerInterface $mailer
*
* @return JsonResponse
*/
function TestEmail(Request $request,MailerInterface $mailer):JsonResponse{
$email = (new Email())
->from('info@cad2cut.de')
->to('ibarragan2004@hotmail.com');
$email->subject("Test")
->html("test");
$status = false;
$msg = '';
try {
$mailer->send($email);
$status = true;
$msg = $this->translator->trans("The email has been sended");
} catch (TransportExceptionInterface $e) {
$msg = $e->getMessage();
}
echo $msg;
die;
return new JsonResponse(['msg' => $msg]);
}
public function getArrayAddress(User $user): array
{
$userAddresses = $user->getAddresses();
if (!$user->getUseBillingAddressAsShippingAddress() and count($userAddresses) > 0) {
/** @var UserAddress $address */
foreach ($userAddresses as $address) {
if ($address->getIsPrimary()) {
return [
'plz' => $address->getZip(),
'street' => $address->getStreet(),
'city' => $address->getCity(),
'country' => $address->getCountry(),
];
}
}
$address = $userAddresses->first();
return [
'plz' => $address->getZip(),
'street' => $address->getStreet(),
'city' => $address->getCity(),
'country' => $address->getCountry(),
];
}
return [
'plz' => $user->getZip(),
'street' => $user->getStreet(),
'city' => $user->getCity(),
'country' => $user->getCountry(),
];
}
/**
* isValidPricesLimit
*
* @param mixed $header_id
* @return bool
*/
public function isValidPricesLimit($header_id): bool
{
$generalLimitCustomer = '-1';
$entityManager = $this->getDoctrine()->getManager();
/** @var Setting $general_limit */
$general_limit = $entityManager->getRepository(Setting::class)->find(20);
/** @var WiCamHeader $WiCamHeader */
$WiCamHeader = $entityManager->getRepository(WiCamHeader::class)->find($header_id);
$Customer = $WiCamHeader->getCustomer();
if(!empty($Customer)){
if ($Customer->getLimitPurchase() > 0) {
$generalLimitCustomer = $WiCamHeader->getCustomer()->getLimitPurchase();
}
$totalOrders = $entityManager->getRepository(WiCamHeader::class)->getCustomerTotal($Customer);
$totalGeneral = $WiCamHeader->getGeneralTotal();
$finalTotal = (float) $totalOrders + $totalGeneral;
$limitReached = false;
if ('-1' != $generalLimitCustomer) {
if ((float)$totalOrders > (float) $generalLimitCustomer) {
$limitReached = true;
}
} elseif ('0' != $general_limit->getValue()) {
if ((float)$totalOrders > (float) $general_limit->getValue()) {
$limitReached = true;
}
}
return $limitReached;
} else {
return false;
}
}
}