<?php
/*
* Copyright Bekanntmacher
*
* @author Simon Wohler <s.wohler@bekanntmacher.ch>
* @license commercial
*/
namespace Bekanntmacher\BoxmakerBundle\Module;
use Bekanntmacher\BoxmakerBundle\Calculation\OptionCalculator;
use Bekanntmacher\BoxmakerBundle\Classes\Config;
use Bekanntmacher\BoxmakerBundle\Classes\UserInput;
use Bekanntmacher\BoxmakerBundle\Model\FarbeModel;
use Bekanntmacher\BoxmakerBundle\Model\TypeModel;
use Bekanntmacher\BoxmakerBundle\Model\ConfigModel;
use Bekanntmacher\BoxmakerBundle\Model\WelleModel;
use Bekanntmacher\BoxmakerBundle\Calculation\PriceCalculator;
use Bekanntmacher\BoxmakerBundle\Calculation\Margin;
use Bekanntmacher\BoxmakerBundle\Classes\FormHelper;
use Bekanntmacher\BoxmakerBundle\Model\Order;
use Bekanntmacher\BoxmakerBundle\Model\Offer;
use Contao\File;
use Contao\FilesModel;
use Contao\Frontend;
use Haste\Form\Form;
use Haste\Util\Format;
use Bekanntmacher\BoxmakerBundle\Classes\PdfGenerator;
use Contao\Email;
/**
* Boxmaker Typelist
*/
class Checkout extends TypeUtil
{
/**
* @var string Template
*/
protected $strTemplate = 'mod_boxmaker_checkout';
protected $objType = null;
protected $objConfig = null;
protected $objUserInput = null;
/**
* Display a wildcard in the back end
* @return string
*/
public function generate()
{
// Display a wildcard in the back end
if (TL_MODE === 'BE')
{
$template = new \BackendTemplate('be_wildcard');
$template->wildcard = '### BOXMAKER TYPE DETAIL ###';
$template->title = $this->name;
$template->id = $this->id;
$template->link = $this->name;
$template->href = 'contao/main.php?do=themes&table=tl_module&act=edit&id=' . $this->id;
}
return parent::generate();
}
/**
* Generate the module
*/
protected function compile()
{
// Config
$this->objConfig = new Config(ConfigModel::findByPk($this->boxmaker_config)->row());
// Instantiate session
$objSession = \System::getContainer()->get('session');
$arrCart = array();
if($objSession->has('mybox_cart') && $objSession->get('mybox_cart') !== null)
{
$arrCart = $objSession->get('mybox_cart');
}
// Form offer
$objFormOffer = new Form('boxmaker_offer', 'POST', function($objHaste) {
return \Input::post('FORM_SUBMIT') === $objHaste->getFormId();
});
$arrFieldsOffer = FormHelper::getOfferFormFields();
$objFormOffer->addFormFields($arrFieldsOffer);
$objFormOffer->addSubmitFormField('submit', $GLOBALS['TL_LANG']['MSC']['boxmaker_typelist_labelOffer']);
if ($objFormOffer->validate() && count($arrCart) > 0) {
// Store Offer
$offer = new Offer();
$offer->cart = $arrCart;
$offer->save();
$intOfferid = str_pad($offer->id, 4, "0", STR_PAD_LEFT);
// New PDF
$objPdf = new PdfGenerator($this->objConfig);
// Add stylesheet
$strStylesheet = file_get_contents(\FilesModel::findByUuid($this->objConfig->pdf_css)->path);
$objPdf->setCss($strStylesheet);
// Write HTML
$strHTML = $this->getPdfHtml($objFormOffer->fetchAll(), $arrCart, $intOfferid);
$objPdf->writeHTML($strHTML);
// Send offer via swift mailer (because nc doesn't support attach file as string)
$objEmail = new Email();
$objEmail->subject = \StringUtil::parseSimpleTokens($this->objConfig->offer_subject, array('nr' => $intOfferid));
// Connvert to plain text
$strText = strip_tags($this->objConfig->offer_text);
$strText = \StringUtil::decodeEntities($strText);
$strText = str_replace(array('[&]', '[lt]', '[gt]'), array('&', '<', '>'), $strText);
$objEmail->text = $strText;
$objEmail->html = $this->objConfig->offer_text;
$objEmail->attachFileFromString($objPdf->getPDFasString(), $GLOBALS['TL_LANG']['MSC']['boxmaker_offer_filename'],'application/pdf');
$objEmail->from = $this->objConfig->offer_from;
$objEmail->sendTo($this->objConfig->offer_bcc);
$objEmail->sendTo($objFormOffer->fetch('offer_email'));
$objSession->remove('mybox_cart');
Frontend::jumpToOrReload($this->boxmaker_jumpToOfferConfirmation);
}
$objFormOfferContainer = new \stdClass();
$objFormOffer->addToObject($objFormOfferContainer);
$this->Template->form_offer = $objFormOfferContainer;
// Form Order
$objFormOrder = new Form('boxmaker_order', 'POST', function($objHaste) {
return \Input::post('FORM_SUBMIT') === $objHaste->getFormId();
});
$arrFieldsOrder = FormHelper::getOrderFormFields();
$objFormOrder->addFormFields($arrFieldsOrder);
$objFormOrder->addSubmitFormField('submit', $GLOBALS['TL_LANG']['MSC']['boxmaker_typelist_labelOrder']);
// Check if there are validators
foreach ($arrFieldsOrder as $name => $dca) {
if ($dca['eval']['boxmakerValidator']) {
$objFormOrder->addValidator($name, $dca['eval']['boxmakerValidator']);
}
}
if ($objFormOrder->validate() && count($arrCart) > 0) {
// Send admin notification (pro cart position one message)
foreach ($arrCart as $pos => $arrSessionType)
{
if($arrSessionType['muster'] != 1)
{
$notification = \NotificationCenter\Model\Notification::findByPk($this->objConfig->boxmaker_admin_notification);
}
else {
$notification = \NotificationCenter\Model\Notification::findByPk($this->objConfig->boxmaker_admin_muster_notification);
}
$tokens = $this->prepareTokens($objFormOrder->fetchAll(), $arrSessionType);
// Store Order
$order = new Order();
$order->setDataFromOrderForm($tokens, $this->typeModel);
$order->save();
$tokens['order_id'] = $order->id;
if (null !== $notification) {
$notification->send($tokens);
echo 'send';
}
}
$objSession->remove('mybox_cart');
Frontend::jumpToOrReload($this->boxmaker_jumpToConfirmation);
}
$objFormOrderContainer = new \stdClass();
$objFormOrder->addToObject($objFormOrderContainer);
$this->Template->form = $objFormOrderContainer;
// Weiterleitungsseite
$objJumpToStart = \PageModel::findByPk($this->boxmaker_jumpToStart);
if($objJumpToStart !== null) {
$this->Template->boxmaker_jumpToStart = $objJumpToStart->getFrontendUrl();
}
}
private function prepareTokens($formData, $arrCartPos)
{
$tokens = array();
// Format form data
$tokens = array_merge($tokens, $this->addAdressTokens($formData, $tokens));
// User Input
$this->objUserInput = new UserInput($arrCartPos);
$this->objUserInput->set('farbe_title', FarbeModel::findByPk($this->objUserInput->farbe)->selecttitle);
$objType = TypeModel::findByPk((int) $arrCartPos['type'], array('eager' => true));
$objT = new Type($this->compileTypeData($objType));
$objT->addTypeConfig($objType->getRelated('type_config_set')->row());
// Title
if($arrCartPos['muster'] != 1)
{
$tokens['type_title'] = $objT->title;
} else {
$tokens['type_title'] = ($arrCartPos['druckverfahren'] == 'blank') ? $objT->title . ' Muster unbedruckt' : $objT->title . ' Muster bedruckt';
}
// Auftrag
$tokens['stk'] = $this->objUserInput->stk;
$tokens['laenge'] = $this->objUserInput->laenge;
$tokens['breite'] = $this->objUserInput->breite;
$tokens['hoehe'] = $this->objUserInput->hoehe;
$tokens['welle'] = WelleModel::findByPk($this->objUserInput->welle)->title;
$tokens['farbe'] = FarbeModel::findByPk($this->objUserInput->farbe)->title;
$tokens['order_print'] = $this->getDruckLabel();
// Preis berechnen
$objCalc = new PriceCalculator($objT, $this->objConfig, $this->objUserInput);
$objMargin = new Margin($objT, $this->objUserInput);
$objOcalc = new OptionCalculator($objT, $this->objUserInput);
// EP's
// ep aterial
$objCalc->getCheapestProductionMethod();
$this->objUserInput->welle;
$this->objUserInput->farbe;
$material = $objCalc->getMaterialPrice($arrCartPos['methode_selected'], $this->objUserInput->welle, $this->objUserInput->farbe);
// ep produktion ( = stanzen und kleben )
$produktion = $objCalc->getProduktionPrice($arrCartPos['methode_selected']);
$tokens['methode_selected'] = $GLOBALS['BOXMAKER']['productionMethodsLabel'][$arrCartPos['methode_selected']];
$key = $arrCartPos['methode_selected'] . '_delivery_time';
$tokens['delivery_time'] = $objT->$key;
// drucken
$drucken = $objCalc->getDruckPrice($this->objUserInput->druckfarben, $this->objUserInput->druckverfahren);
// eco 2s ersetzen
$arrDP = $objCalc->getAllDruckPrices();
if($this->objUserInput->seite == '2s')
{
if($this->objUserInput->druckverfahren != 'digitaldruckeco_4f')
{
$drucken = $drucken * 2;
} else {
$lowest = 0;
foreach ($objCalc->getAllDruckPrices()['4f'] as $key => $value)
{
if(strpos($key,'_4f') !== false) {
if($key != 'digitaldruckeco_4f' && ($lowest == 0 || $value < $lowest)) {
$lowest = $value;
}
}
}
$drucken = $lowest * 2;
}
}
// Druckbild weiss hinterlegt
$tokens['druck_hg'] = '-';
$tokens['druck_hg_price'] = '0';
if($arrCartPos['druck_hg'] == 1)
{
$objO = new \stdClass();
$objO->surcharge_stk = $this->objConfig->hg_print_surcharge_stk;
$objO->surcharge_m2 = $this->objConfig->hg_print_surcharge_m2;
$objO->surcharge_total = $this->objConfig->hg_print_surcharge_total;
$weiss_hinterlegt = $objOcalc->calculateOptionPriceStk($objO);
$tokens['druck_hg'] = 'ja';
$tokens['druck_hg_price'] = $this->getAmount($weiss_hinterlegt, true, true, false);
}
// EP's
if($arrCartPos['muster'] != 1)
{
$tokens['ep_material'] = $this->getAmount($material);
$tokens['ep_produktion'] = $this->getAmount($produktion);
$tokens['ep_stanzen'] = $this->getAmount($objCalc->getStanzenPrice());
$tokens['ep_stanzmesser'] = $this->getAmount($objCalc->getStanzmesserPrice());
$tokens['ep_kleben'] = $this->getAmount($objCalc->getKlebenPrice());
$tokens['ep_drucken'] = $this->getAmount($drucken);
$tokens['ep_total_stk'] = $this->getAmount($material + $produktion + $drucken + $tokens['druck_hg_price']);
$tokens['ep_gesamt'] = $this->getAmount(($material + $produktion + $drucken + $weiss_hinterlegt ) * $this->objUserInput->stk);
}
// VP's Normal
$tokens['vp_total_stk'] = $this->getAmount
(
$material
+ $produktion
+ $drucken
+ $objMargin->getBaseMarginStk()
+ $objMargin->getDynamicMarginStk($material + $produktion + $drucken)
+ $weiss_hinterlegt
);
$tokens['vp_gesamt'] = $this->getAmount
(
$this->getAmount(
$material
+ $produktion
+ $drucken
+ $objMargin->getBaseMarginStk()
+ $objMargin->getDynamicMarginStk($material + $produktion + $drucken)
+ $weiss_hinterlegt
, false
)
* $this->objUserInput->stk
);
// VP Muster
if($arrCartPos['muster'] == 1)
{
if($arrCartPos['druckverfahren'] == 'blank')
{
$tokens['vp_total'] = $tokens['vp_total_stk'] = $this->getAmount($this->objConfig->boxmaker_price_sample_blank, false);
} else {
$tokens['vp_total'] = $tokens['vp_total_stk'] = $this->getAmount($this->objConfig->boxmaker_price_sample_printed, false);
}
$tokens['vp_options'] = 0;
$tokens['vp_gesamt'] = $tokens['vp_total'];
}
// günstigste Prod Methode
$tokens['method'] = $GLOBALS['BOXMAKER']['productionMethodsLabel'][$objCalc->getCheapestProductionMethod()];
// ep verfahren
$arrPrices = $objCalc->getAll();
if($arrCartPos['muster'] != 1)
{
foreach ($GLOBALS['BOXMAKER']['productionMethods'] as $method)
{
$m = $objCalc->getMaterialPrice($method, $this->objUserInput->welle, $this->objUserInput->farbe);
$p = $arrPrices['allProduktionPrices'][$method];
$s = $arrPrices['stanzen'][$method]['stanzen_per_stk'];
$sm = $arrPrices['stanzen'][$method]['stanzmesser'];
$k = $arrPrices['kleben'][$method]['kleben_per_stk'];
$tot = $m + $s + $k;
$tokens['produktion_' . $method . '_material'] = ($m == '') ? 'nicht lieferbar' : $this->getAmount($m);
$tokens['produktion_' . $method . '_produktion'] = $this->getAmount($p);
$tokens['produktion_' . $method . '_stanzen'] = $this->getAmount($s);
$tokens['produktion_' . $method . '_stanzmesser'] = $this->getAmount($sm);
$tokens['produktion_' . $method . '_kleben'] = $this->getAmount($k);
$tokens['produktion_' . $method . '_total'] = $this->getAmount($tot);
}
// Druck
$tokens['druck_Digitaldruck_1f'] = $this->getAmount($arrPrices['druck']['1f']['digitaldruck_1f']);
$tokens['druck_Digitaldruck_4f'] = $this->getAmount($arrPrices['druck']['1f']['digitaldruck_4f']);
$tokens['druck_Digitaldruckeco_4f'] = $this->getAmount($arrPrices['druck']['1f']['digitaldruckeco_4f']);
$tokens['druck_Siebdruck_1f'] = $this->getAmount($arrPrices['druck']['1f']['siebdruck_1f']);
$tokens['druck_Flexodruck_1f'] = $this->getAmount($arrPrices['druck']['1f']['flexodruck_1f']);
$tokens['druck_Offsetdruck_1f'] = $this->getAmount($arrPrices['druck']['1f']['offsetdruck_1f']);
$tokens['druck_Offsetdruck_4f'] = $this->getAmount($arrPrices['druck']['1f']['offsetdruck_4f']);
// Marge
$tokens['marge_prozent'] = $objMargin->getMarginPercent();
}
// infos
$tokens['mwst_satz'] = $this->objConfig->boxmaker_mwst;
$tokens['boxmaker_currency'] = $this->objConfig->boxmaker_currency;
// debug...
/*
$tokens['userInput'] = $this->objUserInput->getAll();
$tokens['type'] = $objT->getAll();
$tokens['arrPrices'] = $objCalc->getAll();
*/
return $tokens;
}
protected function addAdressTokens($formData)
{
$buffer = array();
$fields = FormHelper::getOrderFormFields();
foreach ($fields as $name => $dca) {
$buffer[$name] = Format::dcaValueFromArray($dca, $formData[$name]);
}
return $buffer;
}
public static function getOrderFormFields()
{
$arrFields = static::createAddressFields('billing');
$arrFields['enable_shipping_address'] = array(
'label' => array('', 'Abweichende Lieferadresse'),
'inputType' => 'checkbox'
);
$validator = new MandatoryOn();
$validator->addMatch('enable_shipping_address', true);
$arrFields = array_merge($arrFields, static::createAddressFields('shipping', $validator));
return $arrFields;
}
// PDF offer
private function getPdfHtml($arrFormData, $arrCart, $idOffer) {
$objTemplate = new \FrontendTemplate('boxmaker_pdf_offer');
// General
$objTemplate->boxmaker_currency = $this->objConfig->boxmaker_currency;
$objTemplate->offerid = $idOffer;
$objTemplate->datum = date('d.m.Y', time());
$objTemplate->address = $this->generateAddress($arrFormData);
// Generate cart items
$objCartUtil = new CartUtil($this->objConfig);
$cart_items = array();
foreach ($arrCart as $pos => $arrType)
{
$cart_items[] = $objCartUtil->renderType($pos, $arrType, 'cart_item_pdf_offer' , true);
}
$objTemplate->cart_items = $cart_items;
$objTemplate->show_total = (count($arrCart) == 1) ? true : false;
$objTemplate->boxmaker_currency = $this->objConfig->boxmaker_currency;
$objTemplate->zwischensumme = $objCartUtil->getAmount($objCartUtil->zwischensumme, false);
// VEK
$vek = $objCartUtil->zwischensumme * ($this->objConfig->boxmaker_vek/100);
$objTemplate->vek = $objCartUtil->getAmount($vek);
$objTemplate->vek_prozent = $this->objConfig->boxmaker_vek . ' % ' . $GLOBALS['TL_LANG']['MSC']['boxmaker_vek_label'];
$mwst = ($objCartUtil->zwischensumme + $vek) * ($this->objConfig->boxmaker_mwst/100);
$objTemplate->mwst = $objCartUtil->getAmount($mwst, false);
$objTemplate->mwst_satz = $this->objConfig->boxmaker_mwst . '%';
$objTemplate->total = $objCartUtil->getAmount($objCartUtil->zwischensumme + $vek + $mwst, false);
$this->objConfig->boxmaker_currency;
$objTemplate->shipping = ($this->objConfig->boxmaker_currency == 'EUR') ? $GLOBALS['TL_LANG']['MSC']['boxmaker_shipping_costs_de'] : $GLOBALS['TL_LANG']['MSC']['boxmaker_shipping_costs_ch'] ;
$objTemplate->conditions = $GLOBALS['TL_LANG']['MSC']['boxmaker_offer_conditions'];
$objTemplate->message_plus = $objCartUtil->getMessagePlus();
return $objTemplate->parse();
}
public function generateAddress($arrFormData)
{
$a = array();
$a[] = $arrFormData['offer_company'];
$a[] = $arrFormData['offer_name'];
$a[] = $arrFormData['offer_strasse'];
$a[] = $arrFormData['offer_ort'];
return array_filter($a);
}
}