<?php
namespace Nordpeis\Bundle\CalculatorBundle\Controller;
use Knp\Bundle\SnappyBundle\Snappy\Response\PdfResponse;
use Nordpeis\Bundle\CalculatorBundle\Entity\Calculation;
use Nordpeis\Bundle\CalculatorBundle\Entity\CalculationHasColor;
use Nordpeis\Bundle\CalculatorBundle\Entity\CalculationHasModule;
use Nordpeis\Bundle\CalculatorBundle\Form\Type\CalculatorType;
use Nordpeis\Bundle\CalculatorBundle\Form\Type\DeliveryType;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\Debug\Exception\ContextErrorException;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
class DefaultController extends Controller
{
public function indexAction(Request $request)
{
$parameters = $request->query->all();
$calculator = null;
if (isset($parameters['fireplace'])) {
$entityManager = $this->get('doctrine')->getManager();
$fireplaceRepository = $entityManager->getRepository('NordpeisCalculatorBundle:Fireplace');
$fireplace = $fireplaceRepository->findOneByArtNr($parameters['fireplace']);
if (!empty($fireplace)) {
$calculator['fireplace'] = $fireplace->getId();
}
}
$form = $this->createForm(CalculatorType::class, $calculator);
return $this->render(
'NordpeisCalculatorBundle:Default:index.html.twig',
array(
'formCalculator' => $form->createView(),
)
);
}
public function fireplaceAction(Request $request)
{
$response = array();
$producerId = $request->get('producer_id');
if (empty($producerId)) {
return new JsonResponse($response);
}
$translator = $this->get('translator');
$entityManager = $this->get('doctrine')->getManager();
$query = $entityManager->createQuery(
'SELECT f from NordpeisCalculatorBundle:Fireplace f
JOIN NordpeisCalculatorBundle:Scheme s WITH s.fireplace = f
WHERE s.hidden = :hidden
and f.producer = :producer
ORDER BY f.name ASC'
)->setParameter('producer', $producerId)
->setParameter('hidden', false);
$fireplaces = $query->getResult();
if (empty($fireplaces)) {
return new JsonResponse($response);
}
foreach ($fireplaces as $fireplace) {
$response[] = [
'id' => $fireplace->getId(),
'type' => $translator->trans($fireplace->getName()),
];
}
return new JsonResponse($response);
}
public function schemeAction(Request $request)
{
$response = array();
$fireplaceId = $request->get('fireplace_id');
$pipeId = $request->get('pipe_id');
if (empty($fireplaceId)) {
return new JsonResponse($response);
}
$translator = $this->get('translator');
$entityManager = $this->get('doctrine')->getManager();
$fireplaceRepository = $entityManager->getRepository('NordpeisCalculatorBundle:Fireplace');
$fireplace = $fireplaceRepository->findOneById($fireplaceId);
$query = [
'fireplace' => $fireplace,
'hidden' => false,
];
if(!empty($pipeId)) $query['pipe'] = $pipeId;
$schemeRepository = $entityManager->getRepository('NordpeisCalculatorBundle:Scheme');
$schemes = $schemeRepository->findBy($query);
foreach ($schemes as $scheme) {
$response[] = [
'id' => $scheme->getId(),
'name' => $translator->trans($scheme->getMounting()->getMounting()) . ' - ' . $translator->trans($scheme->getType()->getType()),
'type' => $scheme->getType()->getId(),
'pipe' => $scheme->getPipe()->getId(),
'calculation_height' => $scheme->getCalculationHeight(),
'mounting_id' => $scheme->getMounting()->getId(),
'mount_option' => $scheme->getMountOption(),
'rear' => $scheme->getMounting()->getRear(),
'wall' => ($scheme->getMounting()->getInnerWall() || $scheme->getMounting()->getOuterWall()) ? true : false,
'ext' => $scheme->getMounting()->getOuterWall(),
'no_fireplace' => $scheme->getNoFireplace(),
'needs_x' => $scheme->getHangingFireplace() ||
(!empty($scheme->getMinBottomClearance()) || !empty($scheme->getMaxBottomClearance()) ||
!empty($scheme->getMinTopClearance()) || !empty($scheme->getMaxTopClearance())),
];
}
return new JsonResponse($response);
}
public function pipeAction(Request $request)
{
$response = array();
$fireplaceId = $request->get('fireplace_id');
if (empty($fireplaceId)) {
return new JsonResponse($response);
}
$translator = $this->get('translator');
$entityManager = $this->get('doctrine')->getManager();
$fireplaceRepository = $entityManager->getRepository('NordpeisCalculatorBundle:Fireplace');
$fireplace = $fireplaceRepository->findOneById($fireplaceId);
$schemeRepository = $entityManager->getRepository('NordpeisCalculatorBundle:Scheme');
$schemes = $schemeRepository->findBy([
'fireplace' => $fireplace,
'hidden' => false,
]);
$checkOption = array();
foreach ($schemes as $scheme) {
if(in_array($scheme->getPipe()->getId(), $checkOption) == false ){
$checkOption[] = $scheme->getPipe()->getId();
$response[] = [
'id' => $scheme->getPipe()->getId(),
'type' => $translator->trans($scheme->getPipe()->getDiameter()),
];
}
}
return new JsonResponse($response);
}
public function coverPlateAction(Request $request)
{
$response = array();
$shemeId = $request->get('scheme_id');
$translator = $this->get('translator');
if (empty($shemeId)) {
return new JsonResponse($response);
}
$entityManager = $this->get('doctrine')->getManager();
$schemeRepository = $entityManager->getRepository('NordpeisCalculatorBundle:Scheme');
$scheme = $schemeRepository->findOneById($shemeId);
if (empty($scheme)) {
return new JsonResponse($response);
}
if ($scheme->getMounting()->getId() == 4) {
$response = [[
'id' => 2,
'type' => 'Firkantet',
]];
return new JsonResponse($response);
}
$typeId = $scheme->getType()->getId();
if($scheme->getPipe()->getId() == 1){
switch ($scheme->getType()->getId()) {
case 1: // Fully isolated
case 3: // Unisolated
case 5: // Ventilated - Fully Isolated
$typeId = 1; // convert to Fully isolated
break;
case 2: // Half isolated
case 4: // Ventilated - Half Isolated
case 6: // Ventilated DV
$typeId = 2; // convert to Half isolated
break;
}
}else{
switch ($scheme->getType()->getId()) {
case 1: // Fully isolated
case 2: // Half isolated
case 3: // Unisolated
case 4: // Ventilated - Half Isolated
case 5: // Ventilated - Fully Isolated
case 6: // Ventilated DV
$typeId = 1; // convert to Fully isolated
break;
}
}
$query = $entityManager->createQuery(
'SELECT cp
FROM NordpeisCalculatorBundle:Module m
JOIN NordpeisCalculatorBundle:CoverPlate cp WITH m.coverPlate = cp
WHERE m.pipe in(:pipe)
AND m.type = :type
AND m.coverPlate IS NOT NULL
ORDER BY cp.name ASC'
)->setParameter('type', $typeId)
->setParameter('pipe', $scheme->getPipe());
$modules = $query->getResult();
foreach ($modules as $module) {
$response[] = [
'id' => $module->getId(),
'type' => $translator->trans($module->getName()),
];
}
return new JsonResponse($response);
}
public function pipehatAction(Request $request)
{
$response = array();
$mountingId = $request->get('mounting_id');
$translator = $this->get('translator');
if (empty($mountingId)) {
return new JsonResponse($response);
}
$entityManager = $this->get('doctrine')->getManager();
$mountingRepo = $entityManager->getRepository('NordpeisCalculatorBundle:Mounting');
$mounting = $mountingRepo->findOneById($mountingId);
if (empty($mounting)) {
return new JsonResponse($response);
}
$pipehats = $mounting->getPipehat();
foreach ($pipehats as $pipehat) {
$response[] = [
'id' => $pipehat->getId(),
'type' => $translator->trans($pipehat->getType()),
];
}
return new JsonResponse($response);
}
public function horizontalSelectAction(Request $request)
{
$response = array();
$mountingId = $request->get('mounting_id');
if (empty($mountingId)) {
return new JsonResponse($response);
}
$entityManager = $this->get('doctrine')->getManager();
$mountingRepo = $entityManager->getRepository('NordpeisCalculatorBundle:Mounting');
$mounting = $mountingRepo->findOneById($mountingId);
if (empty($mounting)) {
return new JsonResponse($response);
}
if ($mounting->getOuterWall()) {
$response = [[
'text' => '170 - 370',
'value' => '370',
], [
'text' => '371 - 470',
'value' => '470',
], [
'text' => '471 - 670',
'value' => '670',
], [
'text' => '671 - 1370',
'value' => '1370',
]];
} else {
$response = [[
'text' => '310 - 510',
'value' => '510',
], [
'text' => '511 - 610',
'value' => '610',
], [
'text' => '611 - 810',
'value' => '810',
]];
}
return new JsonResponse($response);
}
public function angleSelectAction(Request $request)
{
try {
$sizeList = $this->getParameter('calculation.angle.sizes');
} catch (\Exception $e) {
return new JsonResponse([]);
}
$pipeId = $request->get('pipe_id');
if ($pipeId && array_key_exists('pipe_' . $pipeId, $sizeList) == true ) {
$sizes = $sizeList['pipe_' . $pipeId];
}else{
$sizes = $sizeList['pipe_1'];
}
$fullyIsolated = array();
foreach ($sizes['fullyIsolated'] as $size) {
$fullyIsolated[] = [
'text' => (string) $size,
'value' => (string) $size,
];
}
$halfIsolated = array();
foreach ($sizes['halfIsolated'] as $size) {
$halfIsolated[] = [
'text' => (string) $size,
'value' => (string) $size,
];
}
$response[1] = $response[3] = $response[5] = [
1 => $fullyIsolated,
2 => $fullyIsolated,
];
$response[2] = $response[4] = $response[6] = [
1 => $halfIsolated,
2 => $fullyIsolated,
];
return new JsonResponse($response);
}
public function floorAction(Request $request)
{
$response = array();
if ($request->get('floor_id')) {
$entityManager = $this->get('doctrine')->getManager();
$floorRepository = $entityManager->getRepository('NordpeisCalculatorBundle:Floor');
$floor = $floorRepository->findOneById($request->get('floor_id'));
if (!empty($floor)) {
$response = [
'numFloors' => $floor->getNumFloors(),
'hasAttic' => $floor->getHasAttic(),
];
}
}
return new JsonResponse($response);
}
public function imageUrlAction(Request $request)
{
$parameters = $request->query->all();
return new JsonResponse(array('url' => $this->getImageUrl($parameters)));
}
private function getImageUrl($parameters)
{
$url = 'bundles/nordpeiscalculator/images/examples/Stal_calc';
switch (isset($parameters['has_angle']) ? ($parameters['has_angle'] === 'true' ? true : false) : null) {
case 0:
break;
case 1:
$url = $url . ' vinkel';
break;
default:
return null;
break;
}
switch (isset($parameters['mounting_id']) ? (int) $parameters['mounting_id'] : null) {
case 1: // Top
$url = $url . ' topp';
break;
case 2: // Rear
$url = $url . ' bak';
break;
case 3: // Rear Through Inner Wall
$url = 'bundles/nordpeiscalculator/images/examples/Stal_calc bak inne'; // No vinkel for these
// $url = $url . ' bak inne';
break;
case 4: // Rear Through Outer Wall
$pipeId = isset($parameters['pipe_id']) ? (int) $parameters['pipe_id'] : null;
$pipeUrl = $pipeId == 2 ? ' 130' : '';
return 'bundles/nordpeiscalculator/images/examples/Stal_calc utvendig 3'. $pipeUrl .'.png'; // There is only one image for backmounted through outer wall
break;
default:
// return new JsonResponse('Missing mounting_id', 400);
return null;
break;
}
switch (isset($parameters['type_id']) ? (int) $parameters['type_id'] : null) {
case 1: // Fully isolated
$url = $url . ' full';
break;
case 2: // Half isolated
$url = $url . ' halv';
break;
case 3: // Unisolated
$url = $url . ' oisolerat';
break;
case 5: // Ventilated - Fully Isolated
$url = $url . ' full TL';
break;
case 4: // Ventilated - Half Isolated
case 6: // Ventilated DV
$url = $url . ' halv TL';
break;
default:
// return new JsonResponse('Missing type_id', 400);
return null;
break;
}
switch (isset($parameters['floor_id']) ? (int) $parameters['floor_id'] : null) {
case 1:
$url = $url . ' 1-plan';
break;
case 2:
$url = $url . ' 2-plan';
break;
case 3:
$url = $url . ' 3-plan';
break;
default:
// return new JsonResponse('Missing floor_id', 400);
return null;
break;
}
switch (isset($parameters['pipe_id']) ? (int) $parameters['pipe_id'] : null) {
case 1:
$url = $url . '';
break;
case 2:
$url = $url . ' 130';
break;
default:
// return new JsonResponse('Missing floor_id', 400);
return null;
break;
}
$url = $url . '.png';
return $url;
}
public function addAction(Request $request)
{
$response = array();
$entityManager = $this->get('doctrine')->getManager();
$calculation = new Calculation();
$parameters = $request->request->all();
$serverVariables = array('HTTP_CLIENT_IP', 'HTTP_X_FORWARDED_FOR', 'REMOTE_ADDR');
foreach ($serverVariables as $svrVar) {
if (!empty($_SERVER[$svrVar])) {
$clientIP = $_SERVER[$svrVar];
break;
}
}
$date = new \DateTime();
$hash = hash('crc32', $date->getTimestamp() . $clientIP);
$calculation->setTimestamp($date->getTimestamp());
$calculation->setHash($hash);
if (isset($parameters['scheme'])) {
$schemeRepository = $entityManager->getRepository('NordpeisCalculatorBundle:Scheme');
$scheme = $schemeRepository->findOneById($parameters['scheme']);
$calculation->setScheme($scheme);
}
if (isset($parameters['floor'])) {
$floorRepository = $entityManager->getRepository('NordpeisCalculatorBundle:Floor');
$floor = $floorRepository->findOneById($parameters['floor']);
$calculation->setFloor($floor);
}
if (isset($parameters['roof'])) {
$roofTypeRepository = $entityManager->getRepository('NordpeisCalculatorBundle:RoofType');
$roofType = $roofTypeRepository->findOneById($parameters['roof']);
$calculation->setRoofType($roofType);
}
if (isset($parameters['upper_floor_living_room'])) {
$calculation->setUpperFloorLivingRoom($parameters['upper_floor_living_room'] === 'true' ? true : false);
} else {
$calculation->setUpperFloorLivingRoom(false);
}
if (isset($parameters['is_oppheng'])) {
$calculation->setIsMount($parameters['is_oppheng'] === 'true' ? true : false);
} else {
$calculation->setIsMount(false);
}
if (isset($parameters['a_size'])) {
$calculation->setA((int) $parameters['a_size']);
}
if (isset($parameters['g_size'])) {
$calculation->setG((float) $parameters['g_size']);
}
if (isset($parameters['h_size'])) {
$calculation->setH((int) $parameters['h_size']);
}
$needsX = $scheme->getNoFireplace() ||
$scheme->getHangingFireplace() ||
!empty($scheme->getMinBottomClearance()) ||
!empty($scheme->getMaxBottomClearance()) ||
!empty($scheme->getMinTopClearance()) ||
!empty($scheme->getMaxTopClearance());
if (isset($parameters['fireplace_height']) && $needsX) {
$calculation->setX((int) $parameters['fireplace_height']);
}
if (isset($parameters['l1_size'])) {
$calculation->setL1((int) $parameters['l1_size']);
}
if (isset($parameters['l2_size'])) {
$calculation->setL2((int) $parameters['l2_size']);
} else {
$calculation->setL2(0);
}
if (isset($parameters['l3_size']) && (isset($scheme) && $scheme->getMounting()->getInnerWall() || $scheme->getMounting()->getOuterWall())) {
$calculation->setL3((int) $parameters['l3_size']);
}
if (isset($parameters['has_angle'])) {
$has_angle = $parameters['has_angle'] === 'true' ? true : false;
$calculation->setHasAngle($has_angle);
if ($has_angle && isset($parameters['cc_size']) && isset($parameters['v1_size'])) {
// if ($parameters['v1_size'] > $parameters['l1_size'] + $parameters['l2_size']) {
// return new JsonResponse(array(
// 'calculator[v1_size]' => array('V1 needs to be less than L1 + L2')
// ), 409);
// }
$calculation->setCC((int) $parameters['cc_size']);
$calculation->setV1((int) $parameters['v1_size']);
}
}
$colors = array();
if (isset($parameters['color_1_floor'])) {
$colorRepository = $entityManager->getRepository('NordpeisCalculatorBundle:Color');
$color = $colorRepository->findOneById($parameters['color_1_floor']);
$colors[] = [
'color' => $color,
'floor' => 1,
];
}
if (isset($parameters['color_2_floor'])) {
$colorRepository = $entityManager->getRepository('NordpeisCalculatorBundle:Color');
$color = $colorRepository->findOneById($parameters['color_2_floor']);
$colors[] = [
'color' => $color,
'floor' => 2,
];
}
if (isset($parameters['pipehat'])) {
$pipehatRepository = $entityManager->getRepository('NordpeisCalculatorBundle:Pipehat');
$pipehat = $pipehatRepository->findOneById($parameters['pipehat']);
$calculation->setPipehat($pipehat);
}
if (isset($parameters['cover_plate'])) {
$coverPlateRepository = $entityManager->getRepository('NordpeisCalculatorBundle:CoverPlate');
$coverPlate = $coverPlateRepository->findOneById($parameters['cover_plate']);
$calculation->setCoverPlate($coverPlate);
}
$ventilationModule = null;
$ventilation2Type = null;
if (isset($parameters['ventilation_duct']) && ($scheme->getNoFireplace() && ( $scheme->getType()->getId() === 4 || $scheme->getType()->getId() === 5 ))) {
$moduleRepository = $entityManager->getRepository('NordpeisCalculatorBundle:Module');
$ventilationModule = $moduleRepository->findOneById($parameters['ventilation_duct']);
$productTypeRepository = $entityManager->getRepository('NordpeisCalculatorBundle:ProductType');
$ventilation2Type = $productTypeRepository->findOneById(7);
}
$validator = $this->get('validator');
$errors = $validator->validate($calculation);
$messages = $this->parseErrors($errors);
if (!empty($messages)) {
return new JsonResponse($messages, 409);
}
try {
$calculationHasColorArr = [];
foreach ($colors as $color) {
$calculationHasColor = new CalculationHasColor();
$calculationHasColor->setCalculation($calculation);
$calculationHasColor->setColor($color['color']);
$calculationHasColor->setFloor($color['floor']);
$calculationHasColorArr[] = $calculationHasColor;
}
$calculationHasModule = null;
if (!empty($ventilationModule) && !empty($ventilation2Type)) {
$calculationHasModule = new CalculationHasModule();
$calculationHasModule->setCalculation($calculation);
$calculationHasModule->setModule($ventilationModule);
$calculationHasModule->setProductType($ventilation2Type);
}
// Pre-calculate to check if its good.
$calculator = $this->get('nordpeis_calculator.calculator');
$result = $calculator->processCalculation($calculation, $calculationHasColorArr);
if (isset($result['errors']) && !empty($result['errors'])) {
return new JsonResponse($result['errors'], 409);
}
foreach ($result['modules'] as $module) {
$entityManager->refresh($module['module']);
}
$entityManager->persist($calculation);
$entityManager->flush();
foreach ($calculationHasColorArr as $floorColor) {
$entityManager->persist($floorColor);
$entityManager->flush();
}
if (!empty($calculationHasModule)) {
$entityManager->persist($calculationHasModule);
$entityManager->flush();
}
} catch (\Exception $e) {
$messages[] = $e->getMessage();
return new JsonResponse($messages, 409);
}
$response = [
'hash' => $hash,
'id' => $calculation->getId(),
];
return new JsonResponse($response);
}
private function parseErrors($errors)
{
$translator = $this->get('translator');
$messages = array();
if (count($errors) > 0) {
$messages = [];
foreach ($errors as $violation) {
$field = $violation->getPropertyPath();
if (strlen($field) < 3) {
$field = $field . '_size';
}
if ($field == 'scheme') {
$field = 'mounting';
}
$messages["calculator[$field]"][] = $translator->trans($violation->getMessage());
}
}
return $messages;
}
public function showAction(Request $request, $id)
{
$entityManager = $this->get('doctrine')->getManager();
if (empty($id)) {
throw new NotFoundHttpException("Invalid identifier");
}
$calculationRepository = $entityManager->getRepository('NordpeisCalculatorBundle:Calculation');
if (preg_match('/^[a-f0-9]{8}$/', $id)) {
$calculation = $calculationRepository->findOneByHash($id);
} else {
$calculation = $calculationRepository->findOneById($id);
}
if (empty($calculation)) {
throw new NotFoundHttpException("Sorry, calculation doesn't exist!");
}
$calculationHasColorRepository = $entityManager->getRepository('NordpeisCalculatorBundle:CalculationHasColor');
$calculationHasColor = $calculationHasColorRepository->findBy(
array('calculation' => $calculation),
array('floor' => 'ASC')
);
$calculator = $this->get('nordpeis_calculator.calculator');
$result = $calculator->processCalculation($calculation, $calculationHasColor);
$serializer = $this->get('nordpeis_calculator.serializer');
$summarizedCalculation = $serializer->summarizeModules($calculation, $result['modules']);
$serializedForm = $serializer->serializeForm($calculation, $calculationHasColor);
$tempText = $calculation->getScheme()->getTempText();
if(!empty($tempText)){
$tempTextArray = explode('|', $tempText);
if(count($tempTextArray) > 1){
foreach( $tempTextArray as $tempTextItem ){
$result['warnings'][] = trim($tempTextItem);
}
}else{
$result['warnings'][] = $tempText;
}
}
$imageUrl = $this->getImageUrl([
'has_angle' => $calculation->getHasAngle() ? 'true' : 'false',
'mounting_id' => $calculation->getScheme()->getMounting()->getId(),
'type_id' => $calculation->getScheme()->getType()->getId(),
'floor_id' => $calculation->getFloor()->getId(),
'pipe_id' => $calculation->getScheme()->getPipe()->getId(),
]);
$params = [
'calculation' => $calculation,
'calculationHasColor' => $calculationHasColor,
'imageUrl' => $imageUrl,
'leftover' => $result['leftover'],
'moduleList' => $summarizedCalculation,
'warnings' => $result['warnings'],
'errorsArray' => $result['errors'],
'serializedForm' => $serializedForm,
];
return $this->render('NordpeisCalculatorBundle:Default:show.html.twig', $params);
}
public function printAction($id)
{
$entityManager = $this->get('doctrine')->getManager();
if (empty($id)) {
throw new NotFoundHttpException("Invalid identifier");
}
$calculationRepository = $entityManager->getRepository('NordpeisCalculatorBundle:Calculation');
if (preg_match('/^[a-f0-9]{8}$/', $id)) {
$calculation = $calculationRepository->findOneByHash($id);
} else {
$calculation = $calculationRepository->findOneById($id);
}
if (empty($calculation)) {
throw new NotFoundHttpException("Sorry, calculation doesn't exist!");
}
$calculationHasColorRepository = $entityManager->getRepository('NordpeisCalculatorBundle:CalculationHasColor');
$calculationHasColor = $calculationHasColorRepository->findBy(
array('calculation' => $calculation),
array('floor' => 'ASC')
);
$calculator = $this->get('nordpeis_calculator.calculator');
$result = $calculator->processCalculation($calculation, $calculationHasColor);
$serializer = $this->get('nordpeis_calculator.serializer');
$imageUrl = $this->getImageUrl([
'has_angle' => $calculation->getHasAngle() ? 'true' : 'false',
'mounting_id' => $calculation->getScheme()->getMounting()->getId(),
'type_id' => $calculation->getScheme()->getType()->getId(),
'floor_id' => $calculation->getFloor()->getId(),
'pipe_id' => $calculation->getScheme()->getPipe()->getId(),
]);
$params = [
'calculation' => $calculation,
'calculationHasColor' => $calculationHasColor,
'imageUrl' => $imageUrl,
'descriptor' => $serializer->serializeModules($calculation, $result['modules']),
'moduleList' => $serializer->summarizeModules($calculation, $result['modules']),
'leftover' => $result['leftover'],
'warnings' => $result['warnings'],
'errors' => $result['errors'],
];
return $this->render('NordpeisCalculatorBundle:Default:print.html.twig', $params);
// $html = $this->renderView('NordpeisCalculatorBundle:Default:print.html.twig', $params);
}
public function pdfAction($id)
{
$pageUrl = $this->generateUrl('nordpeis_calculator_print', array('id' => $id), UrlGeneratorInterface::ABSOLUTE_URL);
return new PdfResponse(
$this->get('knp_snappy.pdf')->getOutput(
str_replace('https', 'http', $pageUrl),
array(
'lowquality' => false,
'encoding' => 'utf-8',
'images' => true,
'enable-javascript' => true,
'javascript-delay' => 5000,
'print-media-type' => true,
)
),
"calculation{$id}.pdf"
);
}
public function drawAction($id)
{
$entityManager = $this->get('doctrine')->getManager();
if (empty($id)) {
throw new NotFoundHttpException("Invalid identifier");
}
$calculationRepository = $entityManager->getRepository('NordpeisCalculatorBundle:Calculation');
if (preg_match('/^[a-f0-9]{8}$/', $id)) {
$calculation = $calculationRepository->findOneByHash($id);
} else {
$calculation = $calculationRepository->findOneById($id);
}
if (empty($calculation)) {
throw new NotFoundHttpException("Could not find an associated calculation");
}
$calculationHasColorRepository = $entityManager->getRepository('NordpeisCalculatorBundle:CalculationHasColor');
$calculationHasColor = $calculationHasColorRepository->findBy(
array('calculation' => $calculation),
array('floor' => 'ASC')
);
$calculator = $this->get('nordpeis_calculator.calculator');
$result = $calculator->processCalculation($calculation, $calculationHasColor);
$serializer = $this->get('nordpeis_calculator.serializer');
$params = [
'calculation' => $calculation,
'calculationHasColor' => $calculationHasColor,
'descriptor' => $serializer->serializeModules($calculation, $result['modules']),
];
return $this->render('NordpeisCalculatorBundle:Default:draw.html.twig', $params);
}
public function deliveryAction($id)
{
if (!isset($_COOKIE['username']) || empty($_COOKIE['username'])) {
return $this->redirectToRoute('nordpeis_calculator_form', array(), 301);
}
$entityManager = $this->get('doctrine')->getManager();
if (empty($id)) {
throw new NotFoundHttpException("Invalid identifier");
}
$calculationRepository = $entityManager->getRepository('NordpeisCalculatorBundle:Calculation');
if (preg_match('/^[a-f0-9]{8}$/', $id)) {
$calculation = $calculationRepository->findOneByHash($id);
} else {
$calculation = $calculationRepository->findOneById($id);
}
if (empty($calculation)) {
throw new NotFoundHttpException("Could not find an associated calculation");
}
// $calculationHasColorRepository = $entityManager->getRepository('NordpeisCalculatorBundle:CalculationHasColor');
// $calculationHasColor = $calculationHasColorRepository->findBy(
// array( 'calculation' => $calculation ),
// array( 'floor' => 'ASC' )
// );
// $calculator = $this->get('nordpeis_calculator.calculator');
$form = $this->createForm(DeliveryType::class);
$params = [
'calculation' => $calculation,
// 'calculationHasColor' => $calculationHasColor,
'deliveryForm' => $form->createView(),
// 'descriptor' => $serializer->serializeModules($calculation, $result['modules'])
];
return $this->render('NordpeisCalculatorBundle:Default:delivery.html.twig', $params);
}
//TODO:: need info on reseller stuff
public function resellerAction(Request $request)
{
//Just for now
$response = [
'reseller' => 'Example Company',
'address' => 'Test Street, 123',
'contact' => 'Sales McSales',
'references' => 'Reference',
];
return new JsonResponse($response);
}
public function orderAction(Request $request)
{
$logger = $this->get('logger');
$entityManager = $this->get('doctrine')->getManager();
$parameters = $request->request->all();
$response = array();
if (!isset($parameters['id'])) {
// $response[] = 'Invalid id';
// return new JsonResponse($response, 400);
return new JsonResponse(array(
'errorCode' => array(-1),
'message' => 'Missing calculation id',
));
}
$calculationRepository = $entityManager->getRepository('NordpeisCalculatorBundle:Calculation');
$calculation = $calculationRepository->findOneById($parameters['id']);
if (empty($calculation)) {
return new JsonResponse(array(
'errorCode' => array(-2),
'message' => 'Calculation id does not exist',
));
}
$calculationHasColorRepository = $entityManager->getRepository('NordpeisCalculatorBundle:CalculationHasColor');
$calculationHasColor = $calculationHasColorRepository->findBy(
array('calculation' => $calculation),
array('floor' => 'ASC')
);
$calculator = $this->get('nordpeis_calculator.calculator');
$result = $calculator->processCalculation($calculation, $calculationHasColor);
if ($calculation->getScheme()->getHidden() == true) {
return new JsonResponse(array(
'errorCode' => array(-3),
'message' => 'Ildstedet er deaktivert',
));
}
if (isset($result['errors']) && !empty($result['errors'])) {
$errorMessage = '';
foreach ($result['errors'] as $error) {
$errorMessage .= !empty($errorMessage) ? '; ' : '';
$errorMessage .= implode("; ", $error);
}
return new JsonResponse(array(
'errorCode' => array(-4),
'message' => $errorMessage,
));
}
$serializer = $this->get('nordpeis_calculator.serializer');
$summarized = $serializer->summarizeModules($calculation, $result['modules']);
$deliveryInfo = $parameters;
// $deliveryInfo['calculationId'] = $deliveryInfo['id'];
unset($deliveryInfo['id']);
// Set for test account, else get the username from somewhere
if ($this->get('kernel')->getEnvironment() === 'dev') {
$costumerId = '11532';
} else {
$fallback = isset($_COOKIE['username']) ? $_COOKIE['username'] : '';
$costumerId = isset($parameters['costumerId']) ? $parameters['costumerId'] : $fallback;
}
$backendInfo = array(
'clientId' => $this->getParameter('app.backend.clientId'),
'token' => $this->getParameter('app.backend.token'),
'costumerId' => $costumerId,
'orderStatus' => $this->getParameter('app.backend.orderStatus'),
);
if (isset($parameters['customerPurchaseNo']) && !empty($parameters['customerPurchaseNo'])) {
$backendInfo['webId'] = $parameters['customerPurchaseNo'];
}
if (isset($parameters['orderType']) && !empty($parameters['orderType']) && $parameters['orderType'] === 'on') {
$backendInfo['ordertype'] = $this->getParameter('app.backend.orderType');
}
$invoicer = $this->get('nordpeis_calculator.invoicer');
$invoice = $invoicer->makeInvoice($backendInfo, $summarized, $deliveryInfo);
$serializedInvoice = $serializer->serializeInvoice($invoice);
$stream_options = array(
'http' => array(
'method' => 'POST',
'header' => 'Content-type: text/xml' . '\r\n',
'content' => $serializedInvoice,
),
);
$url = $this->getParameter('app.backend.orderAddress');
$logger->alert('Posting an order to vitari backend', array_merge($backendInfo, $deliveryInfo));
$logger->info('Invoice', $invoice);
$context = stream_context_create($stream_options);
try {
$postResponse = file_get_contents($url, null, $context);
if ($postResponse === false) {
return new JsonResponse(array(
'errorCode' => '-2',
'message' => 'Failed to access order backend',
), 400);
}
$messages = $serializer->deserializeXML($postResponse);
if (isset($messages->ErrorMessage) && !empty($messages->ErrorMessage->errorCode)) {
$message = (string) $messages->ErrorMessage->message[0];
return new JsonResponse(array(
'errorCode' => count($messages->ErrorMessage->errorCode) > 0 ? (string) $messages->ErrorMessage->errorCode[0] : '-1',
'message' => $message,
), 400);
}
$response['orderNumber'] = (string) $messages->Customer->orderNo;
} catch (ContextErrorException | Exception $e) {
$logger->critical('Failed to access order backend', array(
'cause' => $e->getMessage()
));
return new JsonResponse(array(
'errorCode' => '-3',
'message' => 'Failed to access order backend',
), 400);
}
return new JsonResponse($response);
}
public function exportAction(Request $request, $id)
{
$logger = $this->get('logger');
$entityManager = $this->get('doctrine')->getManager();
$parameters = $request->request->all();
$response = array();
$calculationRepository = $entityManager->getRepository('NordpeisCalculatorBundle:Calculation');
$calculation = $calculationRepository->findOneById($id);
if (empty($calculation)) {
return new JsonResponse(array(
'errorCode' => array(-2),
'message' => 'Calculation id does not exist',
));
}
$calculationHasColorRepository = $entityManager->getRepository('NordpeisCalculatorBundle:CalculationHasColor');
$calculationHasColor = $calculationHasColorRepository->findBy(
array('calculation' => $calculation),
array('floor' => 'ASC')
);
$calculator = $this->get('nordpeis_calculator.calculator');
$result = $calculator->processCalculation($calculation, $calculationHasColor);
if ($calculation->getScheme()->getHidden() == true) {
return new JsonResponse(array(
'errorCode' => array(-3),
'message' => 'Ildstedet er deaktivert',
));
}
if (isset($result['errors']) && !empty($result['errors'])) {
$errorMessage = '';
foreach ($result['errors'] as $error) {
$errorMessage .= !empty($errorMessage) ? '; ' : '';
$errorMessage .= implode("; ", $error);
}
return new JsonResponse(array(
'errorCode' => array(-4),
'message' => $errorMessage,
));
}
$serializer = $this->get('nordpeis_calculator.serializer');
$summarized = $serializer->summarizeModules($calculation, $result['modules']);
$deliveryInfo = $parameters;
// $deliveryInfo['calculationId'] = $deliveryInfo['id'];
unset($deliveryInfo['id']);
// Set for test account, else get the username from somewhere
if ($this->get('kernel')->getEnvironment() === 'dev') {
$costumerId = '11532';
} else {
$fallback = isset($_COOKIE['username']) ? $_COOKIE['username'] : '';
$costumerId = isset($parameters['costumerId']) ? $parameters['costumerId'] : $fallback;
}
$backendInfo = array(
'clientId' => $this->getParameter('app.backend.clientId'),
'token' => $this->getParameter('app.backend.token'),
'costumerId' => $costumerId,
'orderStatus' => $this->getParameter('app.backend.orderStatus'),
);
if (isset($parameters['customerPurchaseNo']) && !empty($parameters['customerPurchaseNo'])) {
$backendInfo['webId'] = $parameters['customerPurchaseNo'];
}
if (isset($parameters['orderType']) && !empty($parameters['orderType']) && $parameters['orderType'] === 'on') {
$backendInfo['ordertype'] = $this->getParameter('app.backend.orderType');
}
$invoicer = $this->get('nordpeis_calculator.invoicer');
$invoice = $invoicer->makeInvoice($backendInfo, $summarized, $deliveryInfo);
$serializedInvoice = $serializer->serializeInvoice($invoice);
$params = [
'xml' => $serializedInvoice
];
return $this->render('NordpeisCalculatorBundle:Default:export.xml.twig', $params);
}
public function putOrderAction( Request $request ){
$logger = $this->get('logger');
$entityManager = $this->get('doctrine')->getManager();
$parameters = $request->request->all();
$response = array();
if( !isset($parameters['id']) ){
return new JsonResponse(
array(
'errorCode' => array(-1),
'message' => 'Missing calculation id.'
)
);
}
$calculationRepository = $entityManager->getRepository('NordpeisCalculatorBundle:Calculation');
$calculation = $calculationRepository->findOneById($parameters['id']);
if( empty( $calculation ) ){
return new JsonResponse(
array(
'errorCode' => array(-2),
'message' => 'Calculation id does not exist.'
)
);
}
$calculationHasColorRepository = $entityManager->getRepository('NordpeisCalculatorBundle:CalculationHasColor');
$calculationHasColor = $calculationHasColorRepository->findBy(
array('calculation' => $calculation),
array('floor' => 'ASC')
);
$calculator = $this->get('nordpeis_calculator.calculator');
$result = $calculator->processCalculation($calculation, $calculationHasColor);
if( $calculation->getScheme()->getHidden() == true ){
return new JsonResponse(
array(
'errorCode' => array(-3),
'message' => 'Ildstedet er deaktivert'
)
);
}
if( isset( $result['errors'] ) && !empty( $result['errors'] ) ){
$errorMessage = '';
foreach( $result['errors'] as $error ){
$errorMessage .= !empty($errorMessage) ? '; ' : '';
$errorMessage .= implode("; ", $error);
}
return new JsonResponse(
array(
'errorCode' => array(-4),
'message' => $errorMessage
)
);
}
$serializer = $this->get('nordpeis_calculator.serializer');
$summarized = $serializer->summarizeModules($calculation, $result['modules']);
$deliveryInfo = $parameters;
$deliveryInfo['calculationId'] = $deliveryInfo['id'];
unset($deliveryInfo['id']);
// test account
if( $this->get('kernel')->getEnvironment() === 'dev' )
$customerId = '11532';
else{
$fallback = isset( $_COOKIE['username'] ) ? $_COOKIE['username'] : '';
$customerId = isset( $parameters['customerId'] ) ? $parameters['customerId'] : $fallback;
}
$backendInfo = array(
'clientId' => $this->getParameter('app.backend.clientId'),
'token' => $this->getParameter('app.backend.token'),
'costumerId' => $customerId,
'orderStatus' => $this->getParameter('app.backend.orderStatus')
);
if( isset( $parameters['orderno'] ) && !empty( $parameters['orderno'] ) )
$backendInfo['orderno'] = $parameters['orderno'];
else{
return new JsonResponse(
array(
'errorCode' => array(-7),
'message' => 'Missing order number.'
)
);
}
$invoicer = $this->get('nordpeis_calculator.invoicer');
$invoice = $invoicer->makePutInvoice($backendInfo, $summarized, $deliveryInfo);
$serializedInvoice = $serializer->serializeInvoice($invoice);
$stream_options = array(
'http' => array(
'method' => 'POST',
'header' => 'Content-type: text/xml' . '\r\n',
'content' => $serializedInvoice
)
);
$url = $this->getParameter('app.backend.putOrderAddress');
$logger->alert('Updating an order to Vitari backend', array_merge($backendInfo, $deliveryInfo));
$logger->info('Invoice', $invoice);
$context = stream_context_create($stream_options);
try{
$putResponse = file_get_contents($url, null, $context);
if( !$putResponse ){
return new JsonResponse(
array(
'errorCode' => array(-6),
'message' => 'Failed to get access to order backend.'
)
);
}
$messages = $serializer->deserializeXML($putResponse);
if (isset($messages->ErrorMessage[0]) && !empty($messages->ErrorMessage[0]->ErrorCode)) {
$message = (string) $messages->ErrorMessage[0]->Message;
$code = (string) $messages->ErrorMessage[0]->ErrorCode;
return new JsonResponse(array(
'errorCode' => count( $messages->ErrorMessage[0]->ErrorCode ) > 0 ? $code : '-1',
'message' => $message,
), 400);
}
$response['orderNumber'] = (string) $messages->Customer->orderNo;
}catch( Exception $e ){
$logger->critical('Failed to get access to order backend.',
array(
'cause' => $e->getMessage()
)
);
return new JsonResponse(array(
'errorCode' => array(-5),
'message' => 'Failed to get access to order backend.'
),400);
}
return new JsonResponse($response);
}
}