Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- namespace iLinkQuotation\V2\Rest\Quotation;
- use Application\Controller\BaseException;
- require_once APPL_PATH . 'oracle.showroom.loc/class/Offer.class.php';
- require_once APPL_PATH . 'oracle.showroom.loc/class/Dealer.class.php';
- require_once APPL_PATH . 'oracle.showroom.loc/clases/class_sesion_showroom.php';
- require_once APPL_PATH . 'oracle.showroom.loc/clases/class_extrabase.php';
- require_once APPL_PATH . 'oracle.showroom.loc/clases/class_promociones.php';
- require_once APPL_PATH . 'oracle.showroom.loc/clases/class_parametric_tax_category.php';
- require_once APPL_PATH . 'oracle.showroom.loc/clases/class_parametric_tax.php';
- require_once APPL_PATH . 'oracle.showroom.loc/clases/class_extrabase.php';
- require_once APPL_PATH . 'oracle.showroom.loc/clases/class_extrabase_excluyente.php';
- require_once APPL_PATH . 'oracle.showroom.loc/clases/class_extra_operacion.php';
- require_once APPL_PATH . 'oracle.showroom.loc/clases/class_tipo_promocion.php';
- require_once APPL_PATH . 'oracle.showroom.loc/clases/class_promocion_opcional.php';
- require_once APPL_PATH . 'oracle.showroom.loc/clases/class_descuento_concesionario.php';
- require_once APPL_PATH . 'oracle.showroom.loc/offer/model/Accessors.class.php';
- require_once APPL_PATH . 'oracle.showroom.loc/offer/model/Eproduct.class.php';
- require_once APPL_PATH . 'oracle.showroom.loc/offer/model/ValidateOffer.class.php';
- require_once APPL_PATH . 'oracle.showroom.loc/offer/used_vehicle/model/UsedVehicle1000.class.php';
- require_once APPL_PATH . 'oracle.showroom.loc/offer/controller/OfferController.class.php';
- require_once APPL_PATH . 'oracle.showroom.loc/libs/base.lib.php';
- require_once APPL_PATH . 'oracle.showroom.loc/crm_wii/model/crm_wii.class.php';
- require_once APPL_PATH . 'COMMON/classes/OfferBase.class.php';
- require_once APPL_PATH . 'COMMON/classes/Nazioni.class.php';
- require_once APPL_PATH . 'COMMON/classes/Util.class.php';
- require_once APPL_PATH . 'oracle.showroom.loc/class/Offer.class.php';
- require_once APPL_PATH . 'COMMON/classes/MappingParameters.class.php';
- require_once APPL_PATH . 'COMMON/classes/class_opcional.php';
- require_once APPL_PATH . 'COMMON/classes/class_impuesto_version.php';
- require_once APPL_PATH . 'COMMON/classes/IPTBase.class.php';
- require_once APPL_PATH . 'COMMON/classes/MarketOfferBreakPoints.class.php';
- require_once APPL_PATH . 'COMMON/classes/CommercialVehicle.class.php';
- require_once APPL_PATH . 'COMMON/pricing/PriceItemCollection.class.php';
- require_once APPL_PATH . 'COMMON/pricing/PriceItemCollectionTaxOverrider.class.php';
- require_once APPL_PATH . 'COMMON/pricing/PriceEngine.class.php';
- require_once APPL_PATH . 'COMMON/classes/TRK_SpecialSales.class.php';
- require_once APPL_PATH . 'COMMON/classes/TRK_Stock.class.php';
- require_once APPL_PATH . 'COMMON/classes/OcfModel.class.php';
- require_once APPL_PATH . 'COMMON/classes/ILinkOffer/IlinkPromotion.class.php'; //B42226 - Applicazone IVA (corretta) alle promozioni
- require_once APPL_PATH . 'COMMON/classes/CarConfB2C_Loader.class.php';
- // CONTROLLER
- require_once APPL_PATH . 'oracle.showroom.loc/offer/controller/OfferSummaryController.class.php';
- require_once APPL_PATH . 'oracle.showroom.loc/offer/controller/OfferPrintedControllerUE.class.php';
- // PRINT
- require_once APPL_PATH . 'oracle.showroom.loc/clases/class_color_language.php';
- require_once APPL_PATH . 'oracle.showroom.loc/clases/class_color_tapiceria.php';
- require_once APPL_PATH . 'oracle.showroom.loc/clases/class_tipo_combustible_language.php';
- use COMMON\classes\TRK_SpecialSales;
- /**
- *
- * @see http://linkentry.fiat.com/mobile/ilcc/sampleJson/
- */
- class QuotationMapper
- {
- /**
- * oggetto Offer
- *
- * @var \Offer
- */
- private $offer;
- /**
- * variabile che contiene gli attributi di sessione
- *
- * @var array
- */
- private $tokenProperties;
- private $timezone;
- private $codCurrency;
- private $localeid;
- /**
- * costruttore not so lazy...
- * inizializza il token che contiene le variabili di sessione
- *
- * @param unknown $tokenProperties
- */
- public function __construct($tokenProperties)
- {
- $this->tokenProperties = $tokenProperties;
- // recupero gli attributi del mercato da utilizzare a livello locale
- $marketObj = \Market::findByPrimaryKey($this->tokenProperties['CODMARKET']);
- $this->timezone = $marketObj[0]['TIMEZONE_REGION'];
- $this->codCurrency = $marketObj[0]['CODCURRENCY'];
- $this->localeid = $marketObj[0]['LOCALE_ID'];
- }
- public function getOffer()
- {
- return $this->offer;
- }
- public function setOffer($offer)
- {
- $this->offer = $offer;
- }
- /**
- * Metodo usato per retrocompatibilità con le vecchie classi di esales.
- *
- * @param string $codoffer
- */
- public function initSession($codoffer)
- {
- $_SESSION['SS_USER_PRIVILEGES'][] = 'VN'; // / da vedere
- $_SESSION['SS_CODMARKET'] = $this->tokenProperties['CODMARKET'];
- $_SERVER['CODMARKET'] = $this->tokenProperties['CODMARKET'];
- $GLOBALS['SS_CODMARKET'] = $this->tokenProperties['CODMARKET'];
- $_SESSION['SS_CODLANGUAGE'] = $this->tokenProperties['CODLANGUAGE'];
- $_SESSION['SS_FLAGSHIP_DEALER'] = ''; // dipende dal coddelaer!!
- $_SESSION['SS_VIP_FLAGSHIP'] = ''; // da ricavare
- $_SESSION['OFFERPATH'] = '';
- $_SESSION['SS_USERNAME'] = $this->tokenProperties['LOGINNAME']; // @TODO
- $_SESSION['SS_WORKING_VEHTYPE'] = '01'; // @TODO
- $_SESSION['STOCKOFFER'] = '0'; // @TODO
- $_SESSION['DOC_ALLESTIMENTO'] = '';
- $_SESSION['ALL_DISC'] = '';
- $_SESSION['SS_OFFER_VIEW_TYPE'] = 1; // tax + detax
- $_SESSION['SS_APPLTYPE'] = 'ESALES';
- $_SESSION['SS_LOGINNAME'] = $this->tokenProperties['LOGINNAME'];
- $_SESSION['SS_CODMAINDEALER'] = self::getCodMainDealer($this->tokenProperties['CODMARKET'],
- $this->tokenProperties['CODDEALER']);
- $_SESSION['SS_CODDEALER'] = $this->tokenProperties['CODDEALER'];
- //$_SESSION['SS_CUSTOMER_TYPE'] = 'P'; // P or C
- $_SESSION['SS_ISAPI'] = 1; // necessario per le traduzioni.
- // il barbatrucco che fa funzionare le classi esales è qui,
- // dove si mette il codice offerta in sessione :P
- $_SESSION['CK_SESION'] = $codoffer;
- $_SESSION['CK_MONEY_SYMBOL'] = '€'; // @TODO
- $codNation = \Nazioni::getNationForUser($this->tokenProperties['CODMARKET'],
- $this->tokenProperties['CODDEALER']);
- if($_SERVER['CODMARKET'] == "3239") {
- $offerBase = new \OfferBase();
- $offerBaseData = $offerBase->findOfferByPrimaryKey($codoffer);
- $_SESSION['SS_CODBILLCATEGORY'] = $offerBaseData[0]['CODBILLCATEGORY'];
- } else {
- $_SESSION['SS_CODBILLCATEGORY'] = \Util::getCodBillCategory(
- $this->tokenProperties['CODMARKET'], $this->tokenProperties['CODDEALER'], $codNation,
- $this->tokenProperties['CODLANGUAGE']);
- }
- // $params['ROLECODE']
- // $params['UPSAPPLICATIONNAME']
- // INSTANTIATE OFFER DATA OBJECTS
- $offer = new \Offer();
- // prendo le info sul modello data l'offerta.
- if ($offer->findByPrimaryKey($codoffer)) {
- $this->setOffer($offer);
- $commercialVehicle = \CommercialVehicle::findByPrimaryKey($offer->getCodMarket(),
- $offer->getCodBrand(), $offer->getCodModel(), $offer->getCodVersion(),
- $offer->getCodSerie(), $offer->getCodSpecialSerie(),
- $this->tokenProperties['CODLANGUAGE']);
- $_SESSION['SS_VEHICLE_TYPE'] = !empty($commercialVehicle) ? $commercialVehicle[0]['CODVEHICLETYPE'] : '01';
- $_SESSION ['SS_WORKING_VEHTYPE'] = $_SESSION['SS_VEHICLE_TYPE'];
- // il metodo OfferPathController::getCodoffer antepone il valore
- // presente nella $_REQUEST al valore di sessione
- $_REQUEST['codoffer'] = $codoffer;
- $_SESSION['CK_CLIENTE_SHOWROOM'] = $offer->getCodContact();
- $_SESSION['SS_CODBRAND'] = $offer->getCodBrand();
- $_SESSION['SS_CODMODEL'] = $offer->getCodModel();
- $_SESSION['SS_CODLOCATION'] = $offer->getCodDealerLocation();
- $_SESSION["SS_CODNATION"] = $offer->getCodNation();
- $_SESSION['CK_COUNTRY'] = $offer->getCodNation();
- $_SESSION['SS_CODDEALER'] = $offer->getCodDealer();
- $_SESSION['CK_CONCESIONARIO'] = $offer->getCodMarket() . '_' . $offer->getCodDealer() .
- '_' . $offer->getCodDealerLocation();
- $_SESSION['SS_WORKING_CODMAINDEALER'] = $this->tokenProperties['CODDEALER'];
- $_SESSION['SS_WORKING_CODBRAND'] = $offer->getCodBrand();
- $_SESSION['SS_WORKING_CODDEALER'] = $offer->getCodDealer();
- // check codnation
- if (empty($_SESSION["SS_CODNATION"])) {
- $dealer = \Dealer::findDealerByPk($offer->getCodMarket(), $offer->getCodDealer());
- if (empty($dealer) || empty($dealer[0]['CODNATION'])) {
- return new BaseException(BaseException::BAD_PARAMETERS,
- 'codNation could not be empty!');
- }
- $_SESSION["SS_CODNATION"] = $dealer[0]['CODNATION'];
- $_SESSION['CK_COUNTRY'] = $dealer[0]['CODNATION'];
- }
- // Variabili necessarie per la stampa dell'offerta.
- // NetworkBrand sarebbe da spostare in >COMMON/classes
- require_once (APPL_PATH . 'welcome/classes/networkBrand.class.php');
- $networkBrand = \NetworkBrand::findNetworkByCodDealer($_SESSION['SS_CODMARKET'],
- $_SESSION['SS_CODDEALER'], '');
- // UserProfile
- // require_once(APPL_PATH . 'oracle.showroom.loc/class/UserProfile.class.php');
- // $userProfile = new \UserProfile();
- // $roles = array();
- $roles = array(
- 'RGIT.LINK'
- );
- $userPrivileges = self::getPrivileges($_SESSION['SS_CODMARKET'], $roles);
- // [DM] TASK 622 - Pricing rounding rules
- $roundingRules = \Market::getRoundingRules($_SESSION['SS_CODMARKET']);
- $codnation = \Nazioni::getNationForUser($_SESSION['SS_CODMARKET'],
- $_SESSION['SS_CODMAINDEALER']);
- $roleType = 'ALL';
- $userRole = 'RGIT.LINK';
- $_SESSION['SS_CODNETWORKAREA'] = $networkBrand['CODNETWORKAREA'];
- $_SESSION['SS_CODNETWORKZONE'] = $networkBrand['CODNETWORKZONE'];
- $_SESSION['SS_CODNETWORKBRAND'] = '';
- $_SESSION['SS_DEALER_NETWORK_LEVEL'] = '1';
- // $_SESSION['SS_CODLINK'] = 20;
- // $_SESSION['SS_USER_PRIVILEGES'] = $userPrivileges;
- $_SESSION['SS_ROLETYPE'] = $roleType;
- $_SESSION['SS_CODROLE'] = $userRole;
- $_SESSION['SS_ROUNDINGRULES'] = $roundingRules;
- $_SESSION['CK_MONEY_SYMBOL'] = $this->codCurrency;
- $_SESSION['SS_MONEY_SYMBOL'] = $this->codCurrency;
- // Gestione date offer.
- $_SESSION['SS_LOCALE_MONTHS'] = array(
- txt("Enero"),
- txt("Febrero"),
- txt("Marzo"),
- txt("Abril"),
- txt("Mayo"),
- txt("Junio"),
- txt("Julio"),
- txt("Agosto"),
- txt("Septiembre"),
- txt("Octubre"),
- txt("Noviembre"),
- txt("Diciembre")
- );
- $_SESSION['SS_LOCALE_DAYS'] = array(
- txt('Lunes'),
- txt('Martes'),
- txt('Miercoles'),
- txt('Jueves'),
- txt('Viernes'),
- txt('Sabado'),
- txt('Domingo')
- );
- $_SESSION['SS_LOCALE_ID'] = $this->localeid;
- $_SESSION['SS_LOCALE_FRAC_DIGITS'] = "2";
- $_SESSION['SS_LOCALE_THOUSANDS_SEP'] = ".";
- $_SESSION['SS_LOCALE_DECIMAL_POINT'] = ",";
- $_SESSION['SS_LOCALE_MON_THOUSANDS_SEP'] = ".";
- $_SESSION['SS_LOCALE_MON_DECIMAL_POINT'] = ",";
- $_SESSION['SS_LOCALE_DATEFORMAT']['short'] = str_replace('-', '/', explode(' ', \DateUtils::getDateFormat())[0]);
- // info dealer.
- /*
- * $dealerData = \DealerBase::findByPrimaryKeyDealer($_SESSION['SS_CODMARKET'], $_SESSION['SS_CODDEALER']); if (!$dealerData) throw new \Exception("DealerData not found!");
- */
- $userData = \ElinkUser::findUserbyPk($_SESSION['SS_CODMARKET'],
- $this->tokenProperties['LOGINNAME']);
- if (!$userData)
- throw new \Exception("UserData not found!");
- $_SESSION['SS_USERNAME'] = $userData[0]['FIRSTNAME'] . ' ' . $userData[0]['LASTNAME'];
- // da verificare.
- if ($_SESSION['SS_VEHICLE_TYPE'] == '01') {
- $_SERVER['CODLINK'] = self::getCodLink($this->tokenProperties['UPSAPPLICATIONNAME'],
- $_SESSION['SS_CODBRAND']);
- } else {
- $_SERVER['CODLINK'] = '9';
- }
- $_SESSION['SS_CODLINK'] = $_SERVER['CODLINK'];
- } else {
- throw new BaseException(BaseException::PROCESS_ERROR,
- "Quotation::init: Offer {$codoffer} not found!");
- }
- }
- /**
- * ritorna un oggetto Quotation per chiave
- *
- * @param int $codoffer
- */
- public function getQuotation($codoffer)
- {
- // inizializzazione delle variabili d'ambiente
- $this->initSession($codoffer);
- // carichiamo l'OfferController che usiamo come DAO...
- $offerController = new \OfferController();
- $offerController->viewType = 0;
- $offerController->changeViewType = 1;
- $offerController->codoffer = $codoffer;
- // attualizziamo l'offerta
- $offerController->process(true);
- // istanza della classe che rappresenta la quotazione
- // il costruttore invoca il metodo QuotationEntity::update()
- // che fa l'override del BaseEntity::update()
- $quotationEntity = new QuotationEntity($offerController, $this->timezone);
- $quotationEntity->offervalidity = $this->getOfferValidity($codoffer);
- //echo '<pre>'; var_dump($offerController); exit();
- /**
- * Dati del veicolo da percorso offerta
- */
- $configuration = array(
- 'brandConf' => '57',
- 'metadataModel' => '6094',
- 'modelDescription' => 'Renegade MY19',
- 'configDescription' => 'Renegade MY19 SPORT 1.0 GSE T3 120cv FWD',
- 'modelName' => 'Renegade MY19',
- 'footerPrivacy' => '',
- 'useExtdFilters' => 'True',
- 'showMvsList' => 'False',
- 'useLMFIPlus' => 'True',
- 'predictiveGrids' => 'True',
- 'groups' => 'ENGN|DRVE|GEAR|FUEL|EQPM|BODY|SEAT|WHEL|PACK',
- 'LMFIModel' => '',
- 'mvs' => '57609L204000',
- 'device' => 'D',
- 'co2' => '134',
- 'body' => '176$5CJ',
- 'whel' => 'WDJ',
- 'seat' => '009#-',
- 'eqpm' => '010',
- 'drve' => '1',
- 'engn' => '10',
- 'fuel' => '2',
- 'gear' => '43',
- 'pack' => '',
- 'opts' => '|009#-|011|023|025|026|112|132|198|264|392|416|4DK|4JA|505|511|5A0|5BH|176$5CJ|5DE|5J9|631|BGG|BNS|CGW|CJ2|JAY|JTM|MXU|RCG|RS9|RSW|UGA|WDJ',
- 'price' => '22400',
- 'priceNoVat' => '17581.97'
- );
- $this->getQrCodeFromConf($configuration);
- return $quotationEntity;
- }
- /**
- * ritorna una collezione di oggetti Quotation
- *
- * @param string $date in formato Y-m-d
- */
- public function listQuotation($p_offerdateFrom, $p_offerdateTo)
- {
- // $debug = $pippo;
- $p_codlanguage = $this->tokenProperties['CODLANGUAGE'];
- $p_loginname = $this->tokenProperties['LOGINNAME'];
- $offs = \OfferBase::findAllByLoginname($p_loginname, $p_codlanguage, $p_offerdateFrom, $p_offerdateTo);
- if (empty($offs)) {
- return new QuotationCollection();
- }
- $collection = new QuotationCollection();
- foreach ($offs as $item) {
- //var_dump($item); die;
- $quotation = new QuotationEntity($item, $this->timezone);
- $quotation->contactname = $item['FULLNAME'];
- $quotation->versionname = $item['VEHICLEDESCR'];
- $quotation->quantity = intval($item['QUANTITY']);
- $quotation->ocfnumber = $item['OCFNUMBER'];
- $quotation->is_multiple = $item['IS_BASKET'] == 'Y' ? 'Y' : 'N';
- // @TODO: $quotation->offervalidity = nel cursore manca OFFER.DAYVALIDITYPERIOD
- $collection->add($quotation);
- }
- return $collection;
- }
- /**
- * Verifica la possibilità di utilizzare un'offerta.
- *
- * @see /offer/validate.php
- *
- * @param string $codoffer
- * @return QuotationCollection
- */
- public function validateQuotation($codoffer)
- {
- // MANDATORY
- $summary = \ValidateOffer::validateSummary($codoffer);
- if ($_SESSION['SS_FLAGSHIP_DEALER']) {
- $hasStock = true;
- $stock = true;
- } else {
- $hasStock = \ValidateOffer::hasStock($codoffer);
- $stock = \ValidateOffer::validateStock($codoffer);
- }
- $color_upholstery[] = 'V';
- $mvs[] = 'V';
- if (!$hasStock) {
- $mvs = \ValidateOffer::validateMVS($codoffer);
- $color_upholstery = \ValidateOffer::validateColorAndUpholstery($codoffer);
- }
- // OPTIONALS
- $hasOptionals = \ValidateOffer::hasOptionals($codoffer);
- $hasAccessories = \ValidateOffer::hasAccessories($codoffer);
- $hasUsed = \ValidateOffer::hasUsed($codoffer);
- $hasFinancing = \ValidateOffer::hasFinancing($codoffer);
- // CONDITIONAL CHECKS
- $globally_valid_accessories = true;
- if ($hasAccessories) {
- $accessories = \ValidateOffer::validateAccessories($codoffer);
- $globally_valid_accessories = ($accessories[0] != 'B');
- }
- $globally_valid_optionals = true;
- if ($hasOptionals) {
- if (!$_SESSION['SS_FLAGSHIP_DEALER'] && !$hasStock) {
- $optionals = \ValidateOffer::validateOptionals($codoffer);
- $globally_valid_optionals = ($optionals[0] != 'B');
- } else {
- $optionals = \ValidateOffer::answerProcessor('');
- }
- }
- // TOTAL VALIDATION SUMMARY
- $globally_valid = false;
- // for Sudafrica the check are limitated
- if ($_SESSION['SS_CODMARKET'] == MARKET_ZA) {
- if ($mvs[0] != 'B' and $color_upholstery[0] != 'B' and $summary[0] != 'B' and
- $globally_valid_optionals) {
- $globally_valid = true;
- }
- } else {
- if ($mvs[0] != 'B' and $color_upholstery[0] != 'B' and $summary[0] != 'B' and $stock and
- $globally_valid_accessories and $globally_valid_optionals) {
- $globally_valid = true;
- }
- }
- // 1. MVS
- $notes = '';
- if (isset($mvs[1])) {
- foreach ($mvs[1] as $msg) {
- $notes .= \Util::txtAPI("offer validate - $msg", $this->tokenProperties) . '\n';
- }
- }
- $sections[] = array(
- 'name' => \Util::txtAPI('offer validate - mvs', $this->tokenProperties),
- 'check' => self::returnValidation($mvs[0]),
- 'notes' => $notes
- );
- // 2. Color upholstery
- $notes = '';
- if (isset($color_upholstery[1])) {
- foreach ($color_upholstery[1] as $msg) {
- $notes .= \Util::txtAPI("offer validate - $msg", $this->tokenProperties) . '\n';
- }
- }
- $sections[] = array(
- 'name' => \Util::txtAPI('offer validate - color upholstery', $this->tokenProperties),
- 'check' => self::returnValidation($color_upholstery[0]),
- 'notes' => $notes
- );
- // 3. Optionals
- $notes = '';
- if (isset($optionals[1])) {
- foreach ($optionals[1] as $msg) {
- $notes .= \Util::txtAPI("offer validate - $msg", $this->tokenProperties) . '\n';
- }
- }
- $sections[] = array(
- 'name' => \Util::txtAPI('offer validate - optionals', $this->tokenProperties),
- 'check' => self::returnValidation($optionals[0]),
- 'notes' => $notes
- );
- // 4. Accessories
- $notes = '';
- if ($hasAccessories) {
- foreach ($accessories[1] as $msg) {
- $notes .= \Util::txtAPI("offer validate - $msg", $this->tokenProperties) . '\n';
- }
- }
- $sections[] = array(
- 'name' => \Util::txtAPI('offer validate - accessories', $this->tokenProperties),
- 'check' => $hasAccessories ? self::returnValidation($accessories[0]) : 0,
- 'notes' => $notes
- );
- // 5. Availability
- $sections[] = array(
- 'name' => \Util::txtAPI('offer validate - availability', $this->tokenProperties),
- 'check' => $_SESSION['SS_FLAGSHIP_DEALER'] ? 1 : 0,
- 'notes' => $_SESSION['SS_FLAGSHIP_DEALER'] ? \Util::txtAPI(
- "NOT_LOCAL_STOCK_CHECK_STATUS_IN_SAP", $this->tokenProperties) : \Util::txtAPI(
- "VEHICLE_NOT_IN_STOCK", $this->tokenProperties)
- );
- // 6. Used
- $sections[] = array(
- 'name' => \Util::txtAPI('offer validate - used', $this->tokenProperties),
- 'check' => $hasUsed ? 1 : 0,
- 'notes' => $hasUsed ? \Util::txtAPI("offer validate - controllare usato",
- $this->tokenProperties) : \Util::txtAPI("offer validate - usato non presente",
- $this->tokenProperties)
- );
- // 7. Financing
- $sections[] = array(
- 'name' => \Util::txtAPI('offer validate - financing', $this->tokenProperties),
- 'check' => $hasFinancing ? 1 : 0,
- 'notes' => $hasFinancing ? \Util::txtAPI("offer validate - controllare finanziamento",
- $this->tokenProperties) : \Util::txtAPI(
- "offer validate - finanziamento non presente", $this->tokenProperties)
- );
- // 8. Offer
- $notes = '';
- if (isset($summary[1])) {
- foreach ($summary[1] as $msg) {
- $notes .= \Util::txtAPI("offer validate - $msg", $this->tokenProperties) . '\n';
- }
- }
- $sections[] = array(
- 'name' => \Util::txtAPI('offer validate - offer', $this->tokenProperties),
- 'check' => self::returnValidation($summary[0]),
- 'notes' => $notes
- );
- $models[] = array(
- 'codoffer' => $codoffer,
- 'sections' => $sections
- );
- $c = new QuotationCollection();
- foreach ($models as $item) {
- // $q = new QuotationEntity($item);
- $c->add($item);
- }
- return $c;
- }
- /**
- * Richiede la duplicazione di un'offerta.
- * Se ha successo ritorna una nuova QuotationEntity.
- *
- * @see OfferPathController
- *
- * @param string $codoffer
- */
- public function duplicateQuotation($codoffer)
- {
- $debug = $pippo;
- $_GET['id_sesion_sr'] = $codoffer;
- // carichiamo l'OfferController che usiamo come DAO...
- $offerPathController = new \OfferPathController();
- $offerPathController->viewType = 0;
- $offerPathController->changeViewType = 1;
- $offerPathController->action = 'modality';
- $offerPathController->mode = 'duplicate';
- $offerPathController->isAPI = 1;
- // $offerController->setProperties(); // ritorna un 404
- // attualizziamo l'offerta, da verificare se serve
- $new_codoffer = $offerPathController->process(true);
- self::addOMobileOffer($codoffer, $new_codoffer);
- return self::getQuotation($new_codoffer);
- }
- private function addOMobileOffer($codoffer, $new_codoffer) {
- require_once APPL_PATH . 'COMMON/classes/MobileOffer.class.php';
- $res = \MobileOffer::findByPrimaryKey($codoffer);
- $offermobile = 'IP';
- $url_photo = '';
- $appsource = '';
- if (empty($res)) {
- \MobileOffer::insertoffer($codoffer, $offermobile, 0, $url_photo, $appsource);
- \MobileOffer::insertoffer($new_codoffer, $offermobile, 0, $url_photo, $appsource);
- } else {
- if (empty($url_photo) && !empty($res[0]['URL_PHOTO'])) {
- $url_photo = $res[0]['URL_PHOTO'];
- }
- if (empty($appsource) && !empty($res[0]['APPSOURCE'])) {
- $appsource = $res[0]['APPSOURCE'];
- }
- //\MobileOffer::updateoffer($codoffer, $res[0]['PRICE'], $url_photo, $appsource);
- \MobileOffer::insertoffer($new_codoffer, $offermobile, $res[0]['PRICE'], $url_photo, $appsource);
- }
- }
- /**
- * Ritorna il numero massimo di giorni di validità dell'offerta.
- *
- * ripreso da oracle.showroom.loc/offer_validity_layer.php
- *
- * @param int $codoffer
- * @return int numero di giorni di validità dell'offerta
- */
- public function getOfferValidity($codoffer)
- {
- if (empty($this->offer)) {
- // inizializzazione delle variabili d'ambiente
- $this->initSession($codoffer);
- }
- require_once (APPL_PATH . 'oracle.showroom.loc/class/Dealer.class.php');
- $concesionario = new \Dealer();
- // DEALER MAX VALIDITY
- $concesionario->findDealerByPrimaryKey($_SESSION['SS_CODMARKET'], $_SESSION['SS_CODDEALER']);
- $maxOfferValidity = $concesionario->getDaysOfferValid();
- if (empty($maxOfferValidity)) {
- $maxOfferValidity = 30;
- }
- // B3378 (this check block)
- if ($_SESSION['SS_CODMARKET'] == MARKET_NL) {
- if ($maxOfferValidity > 14) {
- $maxOfferValidity = 14;
- }
- }
- // normalmente la validità dell'offerta è sono i giorni mancanti al fine mese
- $offerValidity = date('t') - date('j');
- // se siamo nell'ultimo giorno del mese impostiamo a 1
- if ($offerValidity == 0) {
- $offerValidity = 1;
- }
- // se abbiamo un limite più stringente lo applichiamo
- if ($offerValidity > $maxOfferValidity) {
- $offerValidity = $maxOfferValidity;
- }
- /**
- * array (schiantato in offer_validity_layer.php) dei mercati
- * che vogliono offervalidity=maoffervalidity
- */
- $arr[] = MARKET_AT;
- $arr[] = MARKET_CH;
- $arr[] = MARKET_PL;
- $arr[] = MARKET_FR;
- $arr[] = MARKET_DE;
- if (in_array($_SESSION['SS_CODMARKET'], $arr)) {
- $offerValidity = $maxOfferValidity;
- }
- return $offerValidity;
- }
- /**
- * setOfferValidity
- *
- * @see /post_conf_pago.php?next=&validez=13&dms=&codoffer=73738856&validez_maxima=30
- *
- * @param string $codOffer
- * @param integer $validez
- */
- public function setOfferValidity($codoffer, $validez, $status = 0)
- {
- // verifichiamo che l'offerta non sia completa
- if ($status == 0 && $this->offer->offerstate) {
- return new BaseException(BaseException::PROCESS_ERROR, "Offer {$codoffer} is complete!");
- }
- $sesionShowroom = new \SesionShowroom();
- $sesionShowroom->findByPrimaryKey($codoffer);
- /**
- * BUG 9696.
- * Modifiche perse che riguardano il T1493
- */
- if ($_SESSION['SS_CODMARKET'] == MARKET_NL) {
- if ($_SESSION['SS_CUSTOMER_TYPE'] == 'C') // [FG TASK 1802] sostituzione codici R1 con R2 e variabile di sessione
- $viewType = 1;
- else
- $viewType = 0;
- $_SESSION['SS_OFFER_VIEW_TYPE'] = $viewType;
- $sesionShowroom->setVisualizationType($viewType);
- }
- /**
- * END BUG 9696 *
- */
- $sesionShowroom->setValidez($validez);
- // Per tutti mercati la offerta viene chiusa qui (OFFERSTATUS = 1), invece per prima lo faceva r2.propuesta con la funzione tryClose.
- //$sesionShowroom->setCerrado("NU");
- $res = $sesionShowroom->store();
- return $res;
- }
- /**
- * stampa:
- * /offer/offer_printed.php
- *
- * invio mail:
- * /offer/ajax/sendmail_ajax_call.php
- *
- * mopar:
- * /offer/view/offer_print_mopar_section.tpl.php
- *
- * @sample
- * /offer/offer_printed.php?printable=yes&reanudar=&detalle=&idioma=¬ax=no&smart=3&pageBreaks=[]
- *
- * @param string $codoffer
- */
- public function submitOffer($data)
- {
- $codoffer = $data->codoffer;
- $sendmail = !empty($data->sendmail) ? $data->sendmail : 0;
- $validity_days = !empty($data->validity_days) ? intval($data->validity_days) : 0;
- $createocf = !empty($data->createOcf) ? $data->createOcf : 0;
- $priceprotection = !empty($data->priceprotection) ? $data->priceprotection : null;
- $lastDayThisMonth = date("t");
- $todayDayThisMonth = date("j");
- $dayDifference = $lastDayThisMonth - $todayDayThisMonth;
- if($validity_days == 0 || $validity_days > $dayDifference) {
- $validity_days = $dayDifference;
- }
- $ocfnumber = null;
- $p_codlanguage = $this->tokenProperties['CODLANGUAGE'];
- $codnegotiation = !empty($data->codnegotiation) ? $data->codnegotiation : null;
- $namenegotiation = !empty($data->namenegotiation) ? $data->namenegotiation : '';
- $status = !empty($data->status) ? $data->status : 0;
- $note = !empty($data->note) ? $data->note : '';
- $tax = strlen($data->tax) ? filter_var($data->tax, FILTER_VALIDATE_BOOLEAN) : false;
- $technical_info = strlen($data->technical_info) ? intval($data->technical_info) : 0;
- $breakpoint = !empty($data->breakpoint) ? explode(',', $data->breakpoint) : array();
- self::initSession($codoffer);
- ### /offer/offer_printed.php
- $offerLayoutUeEnable = true; //\MarketParams::findValueByPrimaryKey('OFFERLAYOUT_UE_ENABLE', $_SESSION['SS_CODMARKET'], '', '0');
- //$use_iText = \MarketParams::findValueByPrimaryKey("PDF_GENERATOR_ITEXT", $_SESSION['SS_CODMARKET']);
- if ($offerLayoutUeEnable) {
- switch($_SESSION['SS_CODMARKET']) {
- case MARKET_DE:
- require_once(APPL_PATH . 'oracle.showroom.loc/offer/controller/OfferPrintedControllerUE_3110.class.php' );
- $offerPrintController = new \OfferPrintedControllerUE_3110();
- break;
- case MARKET_TR:
- require_once(APPL_PATH . 'oracle.showroom.loc/offer/controller/OfferPrintedControllerUE_3239.class.php' );
- $offerPrintController = new \OfferPrintedControllerUE_3239();
- break;
- /*
- case MARKET_HU:
- require_once(APPL_PATH . 'oracle.showroom.loc/offer/controller/OfferPrintedControllerUE_3129.class.php' );
- $offerPrintController = new \OfferPrintedControllerUE_3129();
- break;
- */
- default:
- //require_once(APPL_PATH . 'oracle.showroom.loc/offer/controller/OfferPrintedControllerUE.class.php' );
- $offerPrintController = new \OfferPrintedControllerUE();
- }
- } else {
- //require_once(APPL_PATH . 'oracle.showroom.loc/offer/controller/OfferPrintedController.class.php' );
- //$offerPrintController = new \OfferPrintedController();
- $offerPrintController = new \OfferPrintedControllerUE();
- }
- // OFFER PRINT CONTROLLER
- $offerPrintController->printable = 'yes';
- $offerPrintController->isAjax = 1;
- $offerPrintController->isAPI = 1;
- $offerPrintController->sendpdf = ($sendmail && $status) ? 1 : 0;
- $offerPrintController->status = $status;
- $offerPrintController->pageBreaks = $breakpoint;
- $offerPrintController->setProperties();
- // attualizziamo l'offerta, da verificare se serve
- $offerPrintController->process(true);
- $offerPrintController->load();
- //$url_pdf = $offerPrintController->display(); // ritorna l'url del pdf (pdfoutput_footer.inc.php).
- if($status == 1 && $sendmail == 1 && is_null($offerPrintController->userObj->getEmail())) {
- return new BaseException(BaseException::PROCESS_ERROR, "mailfrom could not be empty!");
- }
- // inizializzazione delle variabili d'ambiente
- $this->initSession($codoffer);
- $offerController = new \OfferController();
- $offerController->viewType = 0;
- $offerController->changeViewType = 1;
- $offerController->codoffer = $codoffer;
- // attualizziamo l'offerta
- $offerController->process(true);
- if ($status == 1) {
- require_once APPL_PATH . 'COMMON/classes/iLinkApp.class.php';
- \iLinkApp::insertOfferOnQuotation($codoffer, $sendmail, $technical_info);
- }
- $offer = self::getOffer();
- if($_SESSION['SS_CODMARKET'] == MARKET_TR) {
- $offerPrintController->notes = $note;
- $this->profitability_free = null;
- $this->profitability_stock = null;
- $offerAddonTrk = \OfferBase::findOfferAddonTrkByPrimaryKey($this->codoffer);
- $profitabilityfree_ratio = $offerController->tplOffer['profitabilityfree_ratio'];
- $profitabilityfree_value = $offerController->tplOffer['profitabilityfree_value'];
- $profitabilitystock_ratio = $offerController->tplOffer['profitabilitystock_ratio'];
- $profitabilitystock_value = $offerController->tplOffer['profitabilitystock_value'];
- $deliverydate = !empty($offerAddonTrk[0]['DELIVERYDATE']) ? $offerAddonTrk[0]['DELIVERYDATE'] : null;
- $insuranceamount = !empty($offerAddonTrk[0]['INSURANCEAMOUNT']) ? $offerAddonTrk[0]['INSURANCEAMOUNT'] : 0;
- $trafficinsurance = !empty($offerAddonTrk[0]['TRAFFICINSURANCE']) ? $offerAddonTrk[0]['TRAFFICINSURANCE'] : 0;
- $statusvehicle = "Conf tool";
- if (!empty($this->codorder)) {
- $trkStock = \TRK_Stock::find_stockByCodfactoryorder($this->codorder, $this->tokenProperties['CODLANGUAGE']);
- if (count($trkStock) > 0) {
- if (!empty($trkStock[0]['INVOICEDATE']) && ($trkStock[0]['SECONDARY_STATUS']!='SW10' && $trkStock[0]['SECONDARY_STATUS']!='SW20') && $trkStock[0]['PRICETODEALER']) {
- $profitstockloss = ($profitabilitystock_value > 0) ? "OP" : "OL";
- $profitabilitystockPercentage = (($profitabilitystock_ratio) * 100);
- if($profitabilitystockPercentage < 0) {
- $profitabilitystockPercentage *= -1;
- }
- $profitabilityStringStock = "LINK-NOM-" . str_replace(".", ",", sprintf("%.2f", abs($profitabilitystock_value))) . "-" . str_replace(".", ",", sprintf("%.2f", $profitabilitystockPercentage)) . "-" . $profitstockloss;
- $this->profitability_stock = $profitabilityStringStock;
- $dealerBase = \DealerBase::findByPrimaryKeyDealer($trkStock[0]['CODMARKET'], $trkStock[0]['CODDEALER']);
- if ($dealerBase[0]['CODMAINDEALER'] == $this->tokenProperties['CODDEALER']) {
- $statusvehicle = "Invoiced";
- } else {
- $statusvehicle = "Invoiced other dealer";
- }
- } else {
- $statusvehicle = "Uninvoiced";
- }
- }
- }
- $profitfreeloss = ($profitabilityfree_value > 0) ? "OP" : "OL";
- $profitabilityfreePercentage = (($profitabilityfree_ratio) * 100);
- if($profitabilityfreePercentage < 0) {
- $profitabilityfreePercentage *= -1;
- }
- $profitabilityStringFree = "LINK-CUR-" . str_replace(".", ",", sprintf("%.2f", abs($profitabilityfree_value))) . "-" . str_replace(".", ",", sprintf("%.2f",$profitabilityfreePercentage)) . "-" . $profitfreeloss;
- $this->profitability_free = $profitabilityStringFree;
- $result = \OfferBase::storeOfferAddonTrk($codoffer, $statusvehicle, $deliverydate, $insuranceamount, $trafficinsurance, $profitabilityfree_ratio, $profitabilityfree_value, $profitabilitystock_ratio, $profitabilitystock_value, null, null, null);
- if ($result < 0) {
- return new BaseException(BaseException::PROCESS_ERROR, "Offer " . $codoffer . " error!");
- }
- if ($status == 1 && $createocf == 1) {
- $ocfmodel = new \OcfModel();
- $ocfmodel->codmarket = $_SESSION['SS_CODMARKET'];
- $ocfmodel->loginname = $_SESSION['SS_LOGINNAME'];
- $ocfmodel->codlanguage = $_SESSION['SS_CODLANGUAGE'];
- $ocfmodel->codfactoryorder = $offer->codorder;
- $ocfmodel->ocfpriceprotected = $priceprotection;
- $ocfmodel->codoffer = $codoffer;
- $ocfmodel->codsalesman = $_SESSION['SS_LOGINNAME'];
- $userData = \ElinkUser::findUserbyPk($_SESSION['SS_CODMARKET'],
- $this->tokenProperties['LOGINNAME']);
- if (!$userData)
- throw new \Exception("UserData not found!");
- $ocfmodel->lastname = $userData[0]['LASTNAME'];
- $result = $ocfmodel->confirmOcf();
- if(!$result['success']) {
- return new BaseException(BaseException::PROCESS_ERROR, "OCF create error!");
- }
- $ocfnumber = explode("-", $result["data"])[0];
- }
- }
- // ## Scheda Tecnica ###
- if ($technical_info == 1) {
- $_REQUEST['schedaTecnica'] = 'S';
- $_REQUEST['fileNameFicha'] = '';
- }
- // verifichiamo che l'offerta non sia completa
- if ($offer->getOfferState()) {
- return new BaseException(BaseException::PROCESS_ERROR, "Offer {$codoffer} is complete!");
- }
- if (!empty($codnegotiation) || !empty($namenegotiation)) {
- self::createNegotiation($codoffer, $codnegotiation, $namenegotiation);
- }
- // STAMPA PDF
- $_SESSION['SS_OFFER_VIEW_TYPE'] = $tax;
- ### CALCOLATRICE FINANZIARIA: Sviluppata nella CR4067 testata per mercati GR 3113, NL 3122, SE 3127...
- if (in_array($_SESSION["SS_CODMARKET"], array(MARKET_GR, MARKET_NL, MARKET_SE))) {
- // carichiamo l'OfferSummaryController che usiamo come DAO...
- $offerSummaryController = new \OfferSummaryController();
- $offerSummaryController->changeViewType = $tax ? 1 : 0;
- $offerSummaryController->viewType = $tax ? 1 : 0; // 0 = normal (TAX); 1 = detailed (DETAX)
- $offerSummaryController->isAPI = 1;
- $offerSummaryController->setProperties();
- // attualizziamo l'offerta
- $offerSummaryController->process();
- $offerSummaryController->display();
- //var_dump($_SESSION["CAR_PRICE"] .' - '. $_SESSION["CAR_PRICEDETAX"]); die;
- }
- if ($validity_days > 0) {
- self::setOfferValidity($codoffer, $validity_days, $status);
- }
- if($status) {
- $offer->setOfferState($status);
- }
- $offer->setNotes($note);
- $offer->setDayValidityPeriod($validity_days);
- $offer->store();
- $url_pdf = $offerPrintController->display(); // ritorna l'url del pdf (pdfoutput_footer.inc.php).
- $pdf = \Util::getProtocol() . '://' . $_SERVER['HTTP_HOST'] . $url_pdf;
- $quotation = new QuotationEntity(null);
- $quotation->codoffer = $codoffer;
- $quotation->pdf = $pdf;
- if(!empty($ocfnumber)) {
- $quotation->ocfnumber = $ocfnumber;
- }
- if ($offerPrintController->sendpdf || !empty($email)) {
- // ## Scheda Tecnica ###
- if ($technical_info == 1) {
- $_REQUEST['schedaTecnica'] = 'S';
- $_REQUEST['fileNameFicha'] = '';
- $_GET['printable'] = 'yes';
- $_GET['send_ficha_crm'] = 1;
- unset($_GET['isAjax']);
- ob_start();
- require_once APPL_PATH . 'oracle.showroom.loc/ficha_tecnica.php';
- $data = ob_get_clean();
- }
- // ## Invio Mail ###
- $_REQUEST['mailfrom'] = $offerPrintController->userObj->getEmail();
- $_REQUEST['mailto'] = !empty($email) ? $email : $offerPrintController->contactObj->getEmail();
- $_REQUEST['contactname'] = $offerPrintController->contactname;
- $_REQUEST['filename'] = urlencode($offerPrintController->modeloObj->getNombre());
- if (file_exists(APPL_PATH . 'oracle.showroom.loc/offer/ajax/sendmail_ajax_call.php')) {
- require_once APPL_PATH . 'oracle.showroom.loc/offer/ajax/sendmail_ajax_call.php';
- }
- }
- return $quotation;
- }
- /**
- * Verifica se il veicolo usato selezionato è cambiato, ne imposta
- * il valore e lo associa alla quotazione.
- *
- * I parametri sono validati dal chiamante
- *
- * @param string $codoffer
- * @param string $codUsed
- * @param float $value
- * @param float $taxAmount imporo complessivo kanten per NL
- * @param float $taxAmountStanding residuo Kanten per NL
- * @param string $modality non utilizzato, mantenuto per usi futuri
- * @return QuotationEntity
- */
- public function setSaleChannel($codoffer, $codchannel)
- {
- // verifichiamo che l'offerta non sia completa
- if ($this->offer->offerstate) {
- return new BaseException(BaseException::PROCESS_ERROR, "Offer {$codoffer} is complete!");
- }
- $offer = new \Offer();
- $result = $offer->setSaleChannel($codoffer, $codchannel);
- if(!$result) {
- return new BaseException(BaseException::PROCESS_ERROR,
- "Error storing codchannel {$codchannel} of Offer {$codoffer}.");
- }
- return $this->getQuotation($codoffer);
- }
- public function setSpecialSalesRequest($codoffer, $idrequest)
- {
- // verifichiamo che l'offerta non sia completa
- if ($this->offer->offerstate) {
- return new BaseException(BaseException::PROCESS_ERROR, "Offer {$codoffer} is complete!");
- }
- $offer = new \Offer();
- if($offer->findByPrimaryKey($codoffer)) {
- $this->setOffer($offer);
- $promotion = TRK_SpecialSales::findPromobySSrequestDetail($idrequest, $this->tokenProperties['CODLANGUAGE']);
- if(count($promotion) > 0) {
- foreach ($promotion as $item) {
- if($item['MVSSPE'] == $offer->getCodModel() . "." . $offer->getCodVersion() . "." . $offer->getCodSerie() . "." . $offer->getCodSpecialSerie()) {
- $this->setPromotion($codoffer, $item['CODPROMOTION']);
- }
- }
- }
- $addDiscount = TRK_SpecialSales::getAddDiscByMVSS($idrequest, $offer->getCodBrand(), $offer->getCodModel() . "." . $offer->getCodVersion() . "." . $offer->getCodSerie() . "." . $offer->getCodSpecialSerie(), null);
- if($addDiscount != 0) {
- $this->setDealerFreeService($codoffer, "TRKPROMO", $addDiscount . "%", 'tax', 0, 1);
- }
- $result = $offer->setSpecialSalesRequest($codoffer, $idrequest);
- if(!$result) {
- return new BaseException(BaseException::PROCESS_ERROR,
- "Error storing requestid {$idrequest} of Offer {$codoffer}.");
- }
- }
- return $this->getQuotation($codoffer);
- }
- /**
- * Verifica se il veicolo usato selezionato è cambiato, ne imposta
- * il valore e lo associa alla quotazione.
- *
- * I parametri sono validati dal chiamante
- *
- * @param string $codoffer
- * @param string $codUsed
- * @param float $value
- * @param float $taxAmount imporo complessivo kanten per NL
- * @param float $taxAmountStanding residuo Kanten per NL
- * @param string $modality non utilizzato, mantenuto per usi futuri
- * @return QuotationEntity
- */
- public function setTradeInValue($codoffer, $codUsedVehicle, $value, $taxAmount = null,
- $taxAmountStanding = null, $modality = null)
- {
- // verifichiamo che l'offerta non sia completa
- if ($this->offer->offerstate) {
- return new BaseException(BaseException::PROCESS_ERROR, "Offer {$codoffer} is complete!");
- }
- $changedVehicle = (bool) ($this->offer->codusedvehicle != $codUsedVehicle);
- $usedVehicle = new \UsedVehicle();
- $usedVehicle->loadOfferUsedVehicle();
- if ($changedVehicle) {
- // notare che la findByPrimaryKey ritorna una collezione di oggetti...
- $res = $usedVehicle->findByPrimaryKey($codUsedVehicle,
- $this->tokenProperties['CODLANGUAGE']);
- if (count($res) == 0) {
- return new BaseException(BaseException::PROCESS_ERROR,
- "Trade-in vehicle {$codUsedVehicle} not found!");
- }
- // popolo l'attributo offer (che sarebbe un OfferUsedVehicle utilizzando
- // il primo UsedVehicle trovato castandolo ad array
- $usedVehicle->offer->loadDBRecord((array) $res[0]);
- // valorizza l'attributo codoffer dell'OfferUsedVehicle
- $usedVehicle->offer->codoffer = $codoffer;
- } else {
- $usedVehicle->offer->findByCodOffer($codoffer);
- }
- $usedVehicle->offer->setmodifiedprice(abs($value));
- if(!$usedVehicle->offer->storeOfferUsedVehicle()) {
- return new BaseException(BaseException::PROCESS_ERROR,
- "Error storing Trade-in vehicle {$codUsedVehicle} of Offer {$codoffer}.");
- }
- return self::getQuotation($codoffer);
- }
- /**
- * Imposta il prezzo finale dell'offerta calcolando lo sconto da applicare
- * per ottenere il valore desiderato.
- * Nasce per il mercato Austria.
- * Potrebbe applicarsi anche ad altri mercati?
- * vedi offer_summary_detail_3103.tpl.php, offer_summary.js, discountedPrice.js
- *
- * @param string $codoffer
- * @param float $finalPrice prezzo lordo finale desiderato (compreso tasse)
- * @return \iLinkQuotation\V2\Rest\Quotation\QuotationEntity
- */
- public function setFinalPrice($codoffer, $finalPrice)
- {
- // inizializzazione delle variabili d'ambiente
- $this->initSession($codoffer);
- // carichiamo l'OfferController che usiamo come DAO...
- $offerController = new \OfferController();
- $offerController->viewType = 0;
- $offerController->changeViewType = 1;
- $offerController->codoffer = $codoffer;
- // attualizziamo l'offerta
- $offerController->process(true);
- // il calcolo dello sconto implica una formula che andrebbe gestita tramite
- // PriceEngine...
- // è accettabile solo una riduzione del prezzo
- if ($finalPrice < $offerController->tplOffer['total_pagare_ivato']) {
- $offertafinaleSoloIvato = $offerController->tplVehicle['taxedPrice_PC'] +
- $offerController->tplOffer['optsoloivato'];
- $differBase = -$offerController->tplOffer['differbase'];
- $novaPerc = $offerController->tplOffer['nova'];
- $iva = $offerController->tplOffer['iva'];
- $prezzop1 = $differBase / ($novaPerc / 100);
- $d44 = $offertafinaleSoloIvato / (1 + $iva);
- $prezzop2 = ($d44 - $prezzop1) * (1 + $iva);
- $totExtraProduct = $offerController->tplOffer['extrasNoNovaTotal']['taxedPrice'] +
- $offerController->tplOffer['extrasNovaTotal']['taxedPrice'];
- if ($prezzop2 > $finalPrice) {
- // p2>PF
- $sconto = ($finalPrice - $offertafinaleSoloIvato - $totExtraProduct) / (1 + $iva);
- } else {
- $sconto = -((($offertafinaleSoloIvato + $totExtraProduct + ($differBase)) -
- $finalPrice) / ((1 + $iva) + ($novaPerc / 100)));
- }
- // lo sconto in Austria viene comunque applicato senza tasse
- return self::setDealerFreeService($codoffer, 'Rabatt auf den Endpreis berechnet',
- $sconto, 'detax');
- }
- return self::getQuotation($codoffer);
- }
- /**
- * Remove the vehicle from the current offer.
- *
- * @see removeUsedVehicleHandler (OfferSummaryController.class.php)
- *
- * @param string $codoffer
- */
- public function deleteTradeInValue($codoffer)
- {
- $usedVehicle = new \UsedVehicle();
- $usedVehicle->loadOfferUsedVehicle();
- $usedVehicle->removeUsedVehicleFromOffer($codoffer);
- return self::getQuotation($codoffer);
- }
- /**
- * Associa una clientela speciale all'offerta e ritorna un oggetto QuotationEntity aggiornato.
- *
- * @param string $codoffer
- * @param string $codcustomertype
- * @return \iLinkQuotation\V2\Rest\Quotation\QuotationEntity
- * @throws \Exception
- */
- public function setSpecialCustomer($codoffer, $codcustomertype)
- {
- // verifichiamo che l'offerta non sia completa
- if ($this->offer->offerstate) {
- return new BaseException(BaseException::PROCESS_ERROR, "Offer {$codoffer} is complete!");
- }
- try {
- // carichiamo l'OfferSummaryController che usiamo come DAO...
- $offerSummaryController = new \OfferSummaryController();
- // forziamo gli attributi necessari all'azione
- $offerSummaryController->doAction = 'add_extra'; // -> addExtraHandler
- $offerSummaryController->extraType = 3; // -> addVipDiscounts
- $offerSummaryController->changeViewType = 1;
- $offerSummaryController->viewType = 1; // 0 = normal (TAX); 1 = detailed (DETAX)
- $offerSummaryController->extraCode = $codcustomertype;
- $offerSummaryController->isAPI = 1;
- $offerSummaryController->setProperties();
- // attualizziamo l'offerta
- $offerSummaryController->process();
- if ($offerSummaryController->showJavascriptAlerts)
- return new BaseException(BaseException::PROCESS_ERROR,
- $offerSummaryController->javascriptAlertMessages[0]);
- return self::getQuotation($codoffer);
- } catch (\Exception $e) {
- return new BaseException(BaseException::PROCESS_ERROR, $e->getMessage());
- }
- }
- /**
- * Metodo specifico per mercato Olanda
- * Associa una clientela speciale all'offerta e ritorna un oggetto QuotationEntity aggiornato.
- *
- * @param string $codoffer
- * @param string $customercategory
- * @return \iLinkQuotation\V2\Rest\Quotation\QuotationEntity
- * @throws \Exception
- */
- public function setCustomerCategory($codoffer, $customercategory)
- {
- // verifichiamo che l'offerta non sia completa
- if ($this->offer->offerstate) {
- return new BaseException(BaseException::PROCESS_ERROR, "Offer {$codoffer} is complete!");
- }
- try {
- // carichiamo l'OfferSummaryController che usiamo come DAO...
- $offerSummaryController = new \OfferSummaryController();
- // forziamo gli attributi necessari all'azione
- $offerSummaryController->doAction = 'switch_customer_category'; // -> addExtraHandler
- $offerSummaryController->extraType = 3; // -> addVipDiscounts
- $offerSummaryController->changeViewType = 0;
- $offerSummaryController->viewType = 1; // 0 = normal (TAX); 1 = detailed (DETAX)
- $offerSummaryController->extraCode = $codcustomertype;
- $offerSummaryController->isAPI = 1;
- $offerSummaryController->setProperties();
- // attualizziamo l'offerta
- $offerSummaryController->process();
- if ($offerSummaryController->showJavascriptAlerts)
- return new BaseException(BaseException::PROCESS_ERROR,
- $offerSummaryController->javascriptAlertMessages[0]);
- return self::getQuotation($codoffer);
- } catch (\Exception $e) {
- return new BaseException(BaseException::PROCESS_ERROR, $e->getMessage());
- }
- }
- /**
- * Remove the given VIPDISCOUNT from the OFFER
- *
- * @param string $codoffer
- * @param string $codcustomertype
- * @return \iLinkQuotation\V2\Rest\Quotation\QuotationEntity
- * @throws \Exception
- */
- public function deleteSpecialCustomer($codoffer, $codcustomertype)
- {
- // carichiamo l'OfferSummaryController che usiamo come DAO...
- $offerSummaryController = new \OfferSummaryController();
- // forziamo gli attributi necessari all'azione
- $offerSummaryController->doAction = 'remove_extra'; // -> removeExtraHandler
- $offerSummaryController->extraType = 3; // -> removeVipDiscounts
- $offerSummaryController->changeViewType = 1;
- $offerSummaryController->viewType = 1; // 0 = normal (TAX); 1 = detailed (DETAX)
- $offerSummaryController->extraCode = $codcustomertype;
- $offerSummaryController->isAPI = 1;
- $offerSummaryController->setProperties();
- // attualizziamo l'offerta
- $offerSummaryController->process();
- if ($offerSummaryController->showJavascriptAlerts)
- return new BaseException(BaseException::PROCESS_ERROR,
- $offerSummaryController->javascriptAlertMessages[0]);
- return self::getQuotation($codoffer);
- }
- /**
- * Associa una promozione all'offerta e ritorna un oggetto QuotationEntity aggiornato.
- *
- * @param string $codoffer
- * @param string $codpromotion
- * @return \iLinkQuotation\V2\Rest\Quotation\QuotationEntity
- * @throws \Exception
- */
- public function setPromotion($codoffer, $codPromotion)
- {
- // verifichiamo che l'offerta non sia completa
- if ($this->offer->offerstate) {
- return new BaseException(BaseException::PROCESS_ERROR, "Offer {$codoffer} is complete!");
- }
- try {
- //B42226 - applicazone %iva alle promozioni
- $calc_iva = \IlinkPromotion::findByPrimaryKey($codPromotion, $this->tokenProperties['CODLANGUAGE']);
- if($_SESSION['SS_CODMARKET'] == "3239" && count($calc_iva) == 0) {
- $calc_iva = \IlinkPromotion::findByPrimaryKeyNoPv($codPromotion, $this->tokenProperties['CODLANGUAGE']);
- if($calc_iva['MAIN'] == "2") {
- return new BaseException(BaseException::PROCESS_ERROR,
- "Codpromotion " . $codPromotion . " is not compatible to " . $codoffer);
- }
- }
- $iva = $calc_iva[0]['IVAEXCLUDED'];
- // carichiamo l'OfferSummaryController che usiamo come DAO...
- $offerSummaryController = new \OfferSummaryController();
- // forziamo gli attributi necessari all'azione
- $offerSummaryController->doAction = 'add_extra'; // -> addExtraHandler
- $offerSummaryController->extraType = 1; // -> addPromotions
- $offerSummaryController->changeViewType = 1;
- $offerSummaryController->viewType = 1; // 0 = normal (TAX); 1 = detailed (DETAX)
- $offerSummaryController->extraCode = $codPromotion;
- $offerSummaryController->isAPI = 1;
- if($iva == 1){//B42226 - Applicazone IVA (corretta) alle promozioni
- $offerSummaryController->extraValue = $calc_iva[0]['VALUE']*(1+$offerSummaryController->extraIva);
- } else {
- $offerSummaryController->extraValue = $calc_iva[0]['VALUE'];
- }
- $offerSummaryController->setProperties();
- // attualizziamo l'offerta
- $offerSummaryController->process();
- if ($offerSummaryController->showJavascriptAlerts)
- return new BaseException(BaseException::PROCESS_ERROR,
- $offerSummaryController->javascriptAlertMessages[0]);
- return self::getQuotation($codoffer);
- } catch (\Exception $e) {
- return new BaseException(BaseException::PROCESS_ERROR, $e->getMessage());
- }
- }
- /**
- * Remove the given PROMOTION from the OFFER.
- *
- * @param string $codoffer
- * @param string $codPromotion
- * @return \iLinkQuotation\V2\Rest\Quotation\QuotationEntity
- * @throws \Exception
- */
- public function deletePromotion($codoffer, $codPromotion)
- {
- // carichiamo l'OfferSummaryController che usiamo come DAO...
- $offerSummaryController = new \OfferSummaryController();
- // forziamo gli attributi necessari all'azione
- $offerSummaryController->doAction = 'remove_extra'; // -> removeExtraHandler
- $offerSummaryController->extraType = 1; // -> removePromotions
- $offerSummaryController->changeViewType = 1;
- $offerSummaryController->viewType = 1; // 0 = normal (TAX); 1 = detailed (DETAX)
- $offerSummaryController->extraCode = $codPromotion;
- $offerSummaryController->isAPI = 1;
- $offerSummaryController->setProperties();
- // attualizziamo l'offerta
- $offerSummaryController->process();
- if ($offerSummaryController->showJavascriptAlerts)
- return new BaseException(BaseException::PROCESS_ERROR,
- $offerSummaryController->javascriptAlertMessages[0]);
- return self::getQuotation($codoffer);
- }
- /**
- * Associa una categoria IVA speciale all'offerta e
- * ritorna un oggetto QuotationEntity aggiornato.
- *
- * @see addParametricVatHandler (OfferSummaryController.class.php)
- *
- * @param string $codoffer
- * @param string $value
- * @return \iLinkQuotation\V2\Rest\Quotation\QuotationEntity
- * @throws \Exception
- */
- public function setVAT($codoffer, $value)
- {
- // verifichiamo che l'offerta non sia completa
- if ($this->offer->offerstate) {
- return new BaseException(BaseException::PROCESS_ERROR, "Offer {$codoffer} is complete!");
- }
- // carichiamo l'OfferSummaryController che usiamo come DAO...
- $offerSummaryController = new \OfferSummaryController();
- $offerSummaryController->doAction = 'add_parametric_vat';
- $offerSummaryController->removeIvaInOperation = 0;
- $offerSummaryController->extraIva = 0.22; // @TODO: da dove si deve ricavare?
- $offerSummaryController->codCategory = $value;
- $offerSummaryController->extra_id = 0;
- $offerSummaryController->changeViewType = 1;
- $offerSummaryController->viewType = 1;
- $offerSummaryController->setProperties();
- // attualizziamo l'offerta
- $offerSummaryController->process();
- return self::getQuotation($codoffer);
- }
- /**
- * Aggiorna la Kosten legata all'offert Olanda e
- * ritorna un oggetto QuotationEntity aggiornato.
- *
- * @see
- *
- *
- *
- *
- * @param string $codoffer
- * @param string $value
- * @return \iLinkQuotation\V2\Rest\Quotation\QuotationEntity
- * @throws \Exception
- */
- public function setKosten($codoffer, $value)
- {
- // verifichiamo che l'offerta non sia completa
- if ($this->offer->offerstate) {
- return new BaseException(BaseException::PROCESS_ERROR, "Offer {$codoffer} is complete!");
- }
- // carichiamo l'OfferSummaryController che usiamo come DAO...
- $offerSummaryController = new \OfferSummaryController();
- $offerSummaryController->doAction = 'update_dealer_tax';
- $offerSummaryController->dealerTaxValue = $value;
- $offerSummaryController->dealerTaxName = 'KOSTEN';
- $offerSummaryController->changeViewType = 1;
- $offerSummaryController->viewType = 1;
- $offerSummaryController->setProperties();
- // attualizziamo l'offerta
- $offerSummaryController->process();
- return self::getQuotation($codoffer);
- }
- /**
- * Associa un IPT all'offerta e ritorna un oggetto QuotationEntity aggiornato.
- *
- * @see changeIptHandler (OfferSummaryController.class.php)
- *
- * @param string $codoffer
- * @param string $value
- * @return \iLinkQuotation\V2\Rest\Quotation\QuotationEntity
- * @throws \Exception
- */
- public function setIpt($codoffer, $value)
- {
- // verifichiamo che l'offerta non sia completa
- if ($this->offer->offerstate) {
- return new BaseException(BaseException::PROCESS_ERROR, "Offer {$codoffer} is complete!");
- }
- // carichiamo l'OfferSummaryController che usiamo come DAO...
- $offerSummaryController = new \OfferSummaryController();
- // forziamo gli attributi necessari alla action prima
- // della setProperties perche alcuni sono utilizzati in tale contesto... :P
- $offerSummaryController->doAction = 'change_ipt';
- $params = explode('|', $value);
- $offerSummaryController->codProvince = $params[0];
- if (isset($params[1])) {
- $offerSummaryController->codDestination = $params[1];
- }
- $offerSummaryController->changeViewType = 1;
- $offerSummaryController->viewType = 1;
- $offerSummaryController->setProperties();
- // attualizziamo l'offerta
- $offerSummaryController->process();
- return self::getQuotation($codoffer);
- }
- /**
- * Associa una Register Tax all'offerta e ritorna un oggetto QuotationEntity aggiornato.
- *
- * @see changeIptHandler (OfferSummaryController.class.php)
- *
- * @param string $codoffer
- * @param string $value
- * @return \iLinkQuotation\V2\Rest\Quotation\QuotationEntity
- * @throws \Exception
- */
- public function setRegisterTax($codoffer, $value)
- {
- // verifichiamo che l'offerta non sia completa
- if ($this->offer->offerstate) {
- return new BaseException(BaseException::PROCESS_ERROR, "Offer {$codoffer} is complete!");
- }
- if($_SESSION['SS_CODMARKET'] == "3239") {
- if(preg_match('/^\d{4},\d{2},[A-Z]{3}\d{1}?$/', $value)) {
- $value = null;
- }
- $result = \OfferBase::setRegTaxValue($codoffer, $value); // REGTAXVGALUE
- }
- if($result < 0) {
- return new BaseException(BaseException::PROCESS_ERROR, "Register Tax edit error!");
- }
- return self::getQuotation($codoffer);
- }
- /**
- * Associa una Register Tax all'offerta e ritorna un oggetto QuotationEntity aggiornato.
- *
- * @see changeIptHandler (OfferSummaryController.class.php)
- *
- * @param string $codoffer
- * @param string $value
- * @return \iLinkQuotation\V2\Rest\Quotation\QuotationEntity
- * @throws \Exception
- */
- public function setMvt($codoffer, $value)
- {
- // verifichiamo che l'offerta non sia completa
- if ($this->offer->offerstate) {
- return new BaseException(BaseException::PROCESS_ERROR, "Offer {$codoffer} is complete!");
- }
- if($_SESSION['SS_CODMARKET'] == "3239") {
- $result = \OfferBase::setMvtValue($codoffer, null);
- } else {
- $result = \OfferBase::setMvtValue($codoffer, $value);
- }
- // $result = \OfferBase::getMvtValue($codoffer); // MVT
- //
- // if(count($result) > 0) {
- //
- // if(is_null($result[0]['MVTVALUE'])) {
- // $result = \OfferBase::setMvtValue($codoffer, 0); // MVT
- // } else {
- // $result = \OfferBase::setMvtValue($codoffer, null); // MVT
- // }
- //
- // } else {
- // $result = \OfferBase::setMvtValue($codoffer, 0); // MVT
- // }
- if($result < 0) {
- return new BaseException(BaseException::PROCESS_ERROR, "Mvt Tax edit error!");
- }
- return self::getQuotation($codoffer);
- }
- /**
- * Associa una Register Tax all'offerta e ritorna un oggetto QuotationEntity aggiornato.
- *
- * @see changeIptHandler (OfferSummaryController.class.php)
- *
- * @param string $codoffer
- * @param string $value
- * @return \iLinkQuotation\V2\Rest\Quotation\QuotationEntity
- * @throws \Exception
- */
- public function setSct($codoffer, $value)
- {
- // verifichiamo che l'offerta non sia completa
- if ($this->offer->offerstate) {
- return new BaseException(BaseException::PROCESS_ERROR, "Offer {$codoffer} is complete!");
- }
- $result = \OfferBase::setSctValue($codoffer, $value); // SCT VALUE
- if($result < 0) {
- return new BaseException(BaseException::PROCESS_ERROR, "Sct Tax edit error!");
- }
- return self::getQuotation($codoffer);
- }
- /**
- * ripristina un agenerica tassa preceedentemente azzerata
- *
- * @param string $codoffer
- * @param string $codtax
- */
- public function restoreTax($codoffer, $codtax)
- {
- // verifichiamo che l'offerta non sia completa
- if ($this->offer->offerstate) {
- return new BaseException(BaseException::PROCESS_ERROR, "Offer {$codoffer} is complete!");
- }
- $quotationEntity = self::getQuotation($codoffer);
- $canbereset = false;
- /**
- * verifichiamo se la tassa da ripristinare esiste nella quotation
- * serve anche a recuperare il codvalue che viene utilizzato
- * dal controller
- */
- foreach ($quotationEntity->taxes as $tax) {
- if ($tax->codtax == $codtax) {
- $canbereset = $tax->canbereset;
- // trick per superare indenni la setProperties del controller
- // che utilizza nomi diversi delle variabili
- $_POST['codtax'] = $tax->codvalue;
- break; // trovata quella che ci serve è inutile continuare
- }
- }
- if (!$canbereset) {
- return new BaseException(BaseException::PROCESS_ERROR,
- "action restoreTax: tax {$codtax} could not be restored!");
- }
- // carichiamo l'OfferSummaryController che usiamo come DAO...
- $offerSummaryController = new \OfferSummaryController();
- // forziamo gli attributi necessari alla action prima
- // della setProperties perche alcuni sono utilizzati in tale contesto... :P
- $offerSummaryController->changeViewType = 1;
- $offerSummaryController->viewType = 1;
- $offerSummaryController->isAPI = 1;
- /**
- * non ci siamo bevuti il cervello...
- * in OfferSummaryController::taxHandler
- * viene gestita una logica inversa per adattarsi al front-end html
- */
- $offerSummaryController->doAction = 'remove_tax'; // taxHandler
- $offerSummaryController->setProperties();
- // attualizziamo l'offerta
- $offerSummaryController->process();
- return self::getQuotation($codoffer);
- }
- /**
- * Associa un accessorio del concessionario all'offerta e ritorna un oggetto QuotationEntity aggiornato.
- *
- * @see viewAccessors (AccessorsController.class.php)
- *
- * @param string $codoffer
- * @param array $addaccessors
- * @param string $addinstaccessors
- * @return \iLinkQuotation\V2\Rest\Quotation\QuotationEntity
- * @throws \Exception
- */
- public function setDealerAccessory($codoffer, $codaccessory, $onlywork)
- {
- // verifichiamo che l'offerta non sia completa
- if ($this->offer->offerstate) {
- return new BaseException(BaseException::PROCESS_ERROR, "Offer {$codoffer} is complete!");
- }
- // 1000_-11830 -> -11830
- $needle = $_SESSION['SS_CODMARKET'] . '_';
- if (preg_match('/' . $needle . '/', $codaccessory)) {
- $codaccessory = str_replace($needle, "", $codaccessory);
- }
- /*
- // TODO: agganciare il costruttore accessori.
- require_once APPL_PATH . 'oracle.showroom.loc/offer/controller/AccessorsController.class.php';
- $accessorController = new \AccessorsController();
- $accessorController->init();
- $accessorController->process();
- */
- $accessors = new \Accessors();
- $accessor = explode(',', $codaccessory);
- $instaccessor = $onlywork == 0 ? $accessor : array();
- //$accessors->removeByCodOffer($codoffer);
- $novaselected = array(); // $this->getNovaSelectedArray();
- for ($a = 0; $a < count($accessor); $a++) {
- if (trim($accessor[$a]) == '')
- continue;
- // Per austria ci sarebbe la variabile novaselected con gli accessori novati
- if (in_array($accessor[$a], $novaselected)) {
- $taxcalc = 1;
- } else {
- $taxcalc = 0;
- }
- if (in_array($accessor[$a], $instaccessor)) {
- $accessors->remove($codoffer, $accessor[$a]);
- $accessors->insertOfferAccessory($accessor[$a], true, $taxcalc,
- $_SESSION['SS_CODBILLCATEGORY']);
- } else {
- $accessors->insertOfferAccessory($accessor[$a], false, $taxcalc,
- $_SESSION['SS_CODBILLCATEGORY']);
- }
- }
- return self::getQuotation($codoffer);
- }
- /**
- * Elimina un accessorio/mano d'opera e ritorna un oggetto QuotationEntity aggiornato.
- *
- * @see viewAccessors (AccessorsController.class.php)
- *
- * @param string $codoffer
- * @param string $codaccessory
- * @return \iLinkQuotation\V2\Rest\Quotation\QuotationEntity
- * @throws \Exception
- */
- public function deleteAccessory($codoffer, $codaccessory, $onlywork)
- {
- // verifichiamo che l'offerta non sia completa
- if ($this->offer->offerstate) {
- return new BaseException(BaseException::PROCESS_ERROR, "Offer {$codoffer} is complete!");
- }
- // -11830 -> 1000_-11830
- $needle = $_SESSION['SS_CODMARKET'] . '_';
- if (!preg_match('/' . $needle . '/', $codaccessory)) {
- $codaccessory = $needle . $codaccessory;
- }
- // if ($onlywork == 1)
- {
- require_once APPL_PATH . 'COMMON/classes/class_accesorio_sesion_showroom.php';
- $accessors = new \AccesorioSesionShowroom();
- // $selaccessors = (array) $accessors->findAllByCodOffer($codoffer);
- // var_dump($selaccessors); die;
- $res = $accessors->remove_mo($codoffer, $codaccessory); // carrito_mo
- if ($onlywork == 0) {
- $accessors->remove($codoffer, $codaccessory);
- }
- if ($res) {
- return self::getQuotation($codoffer);
- } else {
- return new BaseException(BaseException::PROCESS_ERROR,
- "deleteAccessory {$codaccessory} failed!");
- }
- }
- /*
- * // Questa soluzione presenta problemi nella rimozione dell'accessorio.
- // $onlywork == 0 cancello tutto.
- // carichiamo l'OfferSummaryController che usiamo come DAO...
- $offerSummaryController = new \OfferSummaryController();
- // forziamo gli attributi necessari all'azione
- $offerSummaryController->doAction = 'remove_accessory'; // -> removeAccessoryHandler
- $offerSummaryController->changeViewType = 1;
- $offerSummaryController->viewType = 1;
- $offerSummaryController->isAPI = 1;
- $offerSummaryController->setProperties();
- // attualizziamo l'offerta
- $offerSummaryController->process();
- if ($offerSummaryController->showJavascriptAlerts)
- return new BaseException(BaseException::PROCESS_ERROR, $offerSummaryController->javascriptAlertMessages[0]);
- return self::getQuotation($codoffer);
- */
- }
- /**
- * Associa un servizio/sconto del concessionario all'offerta e ritorna un oggetto
- * QuotationEntity aggiornato.
- *
- * doAction:add_extra -> addDealerDiscounts();
- * /offer/offer_summary.php
- *
- * @param string $codoffer
- * @param string $coddealerservice
- */
- public function setDealerService($codoffer, $coddealerservice, $value = 0, $modality = '')
- {
- // verifichiamo che l'offerta non sia completa
- if ($this->offer->offerstate) {
- return new BaseException(BaseException::PROCESS_ERROR, "Offer {$codoffer} is complete!");
- }
- $p_codLanguage = $this->tokenProperties['CODLANGUAGE'];
- $idConcesionario = $_SESSION['CK_CONCESIONARIO']; // $p_codMarket.'_'.$p_codDealer.'_'.$p_dealerLocation; // -> $_SESSION['CK_CONCESIONARIO']
- $descuentoConcesionario = new \DescuentoConcesionario();
- $disc = $descuentoConcesionario->findByPrimaryKey($coddealerservice, $p_codLanguage);
- $extraValue = !empty($disc) ? $disc->getCantidad() : '';
- if (!empty($value) && !empty($disc) && $disc->getEditable() == 'Y')
- $extraValue = $value;
- // carichiamo l'OfferSummaryController che usiamo come DAO...
- $offerSummaryController = new \OfferSummaryController();
- // forziamo gli attributi necessari all'azione
- $offerSummaryController->doAction = 'add_extra'; // -> addExtraHandler
- $offerSummaryController->extraType = 2; // -> addDealerDiscounts
- $offerSummaryController->changeViewType = 1;
- $offerSummaryController->viewType = $modality == 'detax' ? 1 : 0;
- $offerSummaryController->isAPI = 1;
- $offerSummaryController->extraCode = $coddealerservice;
- $offerSummaryController->extraValue = str_replace("%", "", $extraValue);
- $offerSummaryController->extraIsPercentage = strpos($extraValue, "%") === false ? 0 : 1;
- $offerSummaryController->setProperties();
- // attualizziamo l'offerta
- $offerSummaryController->process();
- if ($offerSummaryController->showJavascriptAlerts) {
- return new BaseException(BaseException::PROCESS_ERROR,
- $offerSummaryController->javascriptAlertMessages[0]);
- }
- return self::getQuotation($codoffer);
- }
- /**
- * Elimina un servizio/sconto del concessionario all'offerta e ritorna un oggetto QuotationEntity aggiornato.
- *
- * doAction:add_extra -> removeExtraHandler();
- * /offer/offer_summary.php
- *
- * @param string $codoffer
- * @param string $coddealerservice
- */
- public function deleteDealerService($codoffer, $coddealerservice)
- {
- // verifichiamo che l'offerta non sia completa
- if ($this->offer->offerstate) {
- return new BaseException(BaseException::PROCESS_ERROR, "Offer {$codoffer} is complete!");
- }
- // carichiamo l'OfferSummaryController che usiamo come DAO...
- $offerSummaryController = new \OfferSummaryController();
- // forziamo gli attributi necessari all'azione
- $offerSummaryController->doAction = 'remove_extra'; // -> removeExtraHandler
- $offerSummaryController->extraType = 2; // -> removeDealerDiscounts
- $offerSummaryController->changeViewType = 1;
- $offerSummaryController->viewType = 1;
- $offerSummaryController->isAPI = 1;
- $offerSummaryController->extraCode = $coddealerservice;
- $offerSummaryController->setProperties();
- // attualizziamo l'offerta
- $offerSummaryController->process();
- if ($offerSummaryController->showJavascriptAlerts)
- return new BaseException(BaseException::PROCESS_ERROR,
- $offerSummaryController->javascriptAlertMessages[0]);
- return self::getQuotation($codoffer);
- }
- /**
- * Associa un servizio/sconto del concessionario con importo e descrizione libera
- * all'offerta e ritorna un oggetto QuotationEntity aggiornato.
- *
- * E' necessario specificare la modalità di lavoro in cui avviene la richiesta
- * (tax/detax) per determinare se il valore va
- * considerato IVA compresa (tax) o IVA esclusa (detax).
- * $value puo essere un float e rappresenta un valore assoluto, negativo se è uno sconto,
- * positivo se è un servizio (costo) oppure una stringa che finisce con "%" per uno sconto
- * percentuale, ad es. -10% oppure –6,5%, positivo se è un costo ad es. 10% oppure 5,5%
- *
- * @param string $codoffer
- * @param string $coddealerservice
- * @param string $value
- * @param string $modality
- * @param string $novaexcluded
- */
- public function setDealerFreeService($codoffer, $description, $value, $modality, $novaexcluded = 0, $discountfordealer = NULL)
- {
- // verifichiamo che l'offerta non sia completa
- if ($this->offer->offerstate) {
- return new BaseException(BaseException::PROCESS_ERROR, "Offer {$codoffer} is complete!");
- }
- $value = str_replace(",", ".", $value);
- // inizializzazione delle variabili d'ambiente
- $this->initSession($codoffer);
- // carichiamo l'OfferController che usiamo come DAO...
- $offerController = new \OfferController();
- $offerController->viewType = 0;
- $offerController->changeViewType = 1;
- $offerController->codoffer = $codoffer;
- // attualizziamo l'offerta
- $offerController->process(true);
- // carichiamo l'OfferSummaryController che usiamo come DAO...
- $offerSummaryController = new \OfferSummaryController();
- // forziamo gli attributi necessari all'azione
- $offerSummaryController->doAction = 'add_extra'; // -> addExtraHandler
- $offerSummaryController->extraType = $novaexcluded != 1 ? 4 : 8; // -> addRealExtras
- $offerSummaryController->changeViewType = 1;
- $offerSummaryController->viewType = 0;
- $offerSummaryController->discountfordealer = $discountfordealer;
- if ($modality == 'detax') {
- $offerSummaryController->viewType = 1;
- if ($offerSummaryController->isAustria()) {
- $offerSummaryController->novaextra = 1;
- }
- }
- if ($offerSummaryController->isAustria()) {
- $offerSummaryController->novaPercentage = $offerController->tplOffer['nova']; // valore della nova (es. 12% )
- }
- // novaextra
- $offerSummaryController->isAPI = 1;
- $offerSummaryController->extraCode = $description;
- $offerSummaryController->extraValue = str_replace("%", "", $value);
- $offerSummaryController->extraIsPercentage = strpos($value, "%") === false ? 0 : 1;
- $offerSummaryController->setProperties();
- // attualizziamo l'offerta
- $offerSummaryController->process();
- if ($offerSummaryController->showJavascriptAlerts) {
- return new BaseException(BaseException::PROCESS_ERROR,
- $offerSummaryController->javascriptAlertMessages[0]);
- }
- return self::getQuotation($codoffer);
- }
- /** deleteDealerFreeService
- *
- * @param string $codoffer
- * @param string $coddealerservice
- * @param string $novaexcluded
- *
- * @return QuotationEntity
- */
- public function deleteDealerFreeService($codoffer, $coddealerservice, $novaexcluded = 0)
- {
- // verifichiamo che l'offerta non sia completa
- if ($this->offer->offerstate) {
- return new BaseException(BaseException::PROCESS_ERROR, "Offer {$codoffer} is complete!");
- }
- // carichiamo l'OfferSummaryController che usiamo come DAO...
- $offerSummaryController = new \OfferSummaryController();
- // forziamo gli attributi necessari all'azione
- $offerSummaryController->doAction = 'remove_extra'; // -> removeExtraHandler
- $offerSummaryController->extraType = $novaexcluded != 1 ? 4 : 8; // -> removeRealExtras
- $offerSummaryController->changeViewType = 1;
- $offerSummaryController->viewType = 1;
- $offerSummaryController->isAPI = 1;
- $offerSummaryController->extraCode = $coddealerservice;
- $offerSummaryController->extraName = $coddealerservice;
- $offerSummaryController->setProperties();
- // attualizziamo l'offerta
- $offerSummaryController->process();
- if ($offerSummaryController->showJavascriptAlerts)
- return new BaseException(BaseException::PROCESS_ERROR,
- $offerSummaryController->javascriptAlertMessages[0]);
- return self::getQuotation($codoffer);
- }
- /** setVehiclePrice
- *
- * @see
- * /offer/view/offer_summary_detail_3103.tpl.php
- *
- * @param string $codoffer
- * @param string $value
- *
- * @return \Application\Controller\BaseException|\iLinkQuotation\V2\Rest\Quotation\QuotationEntity
- */
- public function setVehiclePrice($codoffer, $value)
- {
- // verifichiamo che l'offerta non sia completa
- if ($this->offer->offerstate) {
- return new BaseException(BaseException::PROCESS_ERROR, "Offer {$codoffer} is complete!");
- }
- $description = txt('Rabatt auf den Endpreis berechnet');
- self::deleteDealerFreeService($codoffer, $description);
- $sconto = self::calcDiscount($this->offer, $value);
- $value = $sconto;
- // inizializzazione delle variabili d'ambiente
- $this->initSession($codoffer);
- // carichiamo l'OfferController che usiamo come DAO...
- $offerController = new \OfferController();
- $offerController->viewType = 0;
- $offerController->changeViewType = 1;
- $offerController->codoffer = $codoffer;
- // attualizziamo l'offerta
- $offerController->process(true);
- // $codoffer, $description, $value, $modality, $novaexcluded = 0
- // lo sconto in Austria viene comunque applicato senza tasse
- //return self::setDealerFreeService($codoffer, $description, $sconto, 'detax');
- // diseguito troviamo l'implementazione ad-hoc della setDealerFreeService.
- // carichiamo l'OfferSummaryController che usiamo come DAO...
- $offerSummaryController = new \OfferSummaryController();
- // forziamo gli attributi necessari all'azione
- $offerSummaryController->doAction = 'add_extra'; // -> addExtraHandler
- $offerSummaryController->extraType = $novaexcluded != 1 ? 4 : 8; // -> addRealExtras
- $offerSummaryController->changeViewType = 1;
- $offerSummaryController->viewType = 1;
- if ($offerSummaryController->isAustria()) {
- $offerSummaryController->novaextra = 1;
- $offerSummaryController->novaPercentage = $offerController->tplOffer['nova']; // valore della nova (es. 12% )
- }
- // novaextra
- $offerSummaryController->isAPI = 1;
- $offerSummaryController->extraCode = $description;
- $offerSummaryController->extraValue = str_replace("%", "", $value);
- $offerSummaryController->extraIsPercentage = strpos($value, "%") === false ? 0 : 1;
- //var_dump($offerSummaryController); die;
- $offerSummaryController->setProperties();
- // attualizziamo l'offerta
- $offerSummaryController->process();
- if ($offerSummaryController->showJavascriptAlerts) {
- return new BaseException(BaseException::PROCESS_ERROR,
- $offerSummaryController->javascriptAlertMessages[0]);
- }
- return self::getQuotation($codoffer);
- }
- /**
- * Ritorna il valore dello sconto calcolato.
- *
- * FORMULA APPLICATA
- * se p2 > PF (PF - (veh+opt) * (1+iva%))/(1+iva%)
- * se p2 < PF -(((offertafinaleSoloIvato + (differ_base)) - PF) / ((1+iva%) + (nova%/100)))
- *
- * @see
- * /offer/view/offer_summary_detail_3103.tpl.php
- * /offer/js/discountedPrice.js
- */
- private function calcDiscount($offer, $value)
- {
- $quotation = self::getQuotation($offer->codoffer);
- $tot_quotation_price = $quotation->tot_quotation_price->taxed_float;
- $veh_price = $quotation->veh_price->detaxed_float;
- $sconto = 0;
- // inizializzazione delle variabili d'ambiente
- $this->initSession($offer->codoffer);
- // carichiamo l'OfferController che usiamo come DAO...
- $offerController = new \OfferController();
- $offerController->viewType = 0;
- $offerController->changeViewType = 1;
- $offerController->codoffer = $codoffer;
- // attualizziamo l'offerta
- $offerController->process(true);
- $novaPerc = $offerController->tplOffer['nova']; // valore della nova (es. 12% )
- $iva = $offerController->tplOffer['iva']; // iva di mercato
- $d44 = $veh_price;
- //var_dump($offerController->tplOffer); die;
- //F66 prezzo finale (veh+opt)*iva
- //tplOffer['total_pagare_ivato']
- $prezzoOffertafinale = $tot_quotation_price; //tplOffer['total_pagare_ivato']
- //D81 (PF)
- //prezzo desiderato
- $prezzofinale = $value;
- //H83
- //tplVehicle['taxedPrice_PC']+$this->tplOffer['optsoloivato']
- $offertafinaleSoloIvato = $d44*(1+$iva); //this.offertafinaleSoloIvato;
- //tplOffer['differbase']
- $differ_base = -$offerController->tplOffer['differbase'];
- //differbase diviso percentuale di nova
- $prezzop1 = $differ_base/($novaPerc/100);
- //Prezzo IVA incl. Attrezzatura speciale (senza NoVA Bonus & Discount)
- //riferimento alla cella D44 del foglio excel allegato alla cr4871
- //$d44 = $offertafinaleSoloIvato/(1+$iva);
- //
- $prezzop2 = ($d44-$prezzop1)*(1+$iva);
- //se il prezzo inserito da campo è maggiore del prezzo dell'offerta
- if ($prezzofinale > $prezzoOffertafinale) {
- return new BaseException(BaseException::PROCESS_ERROR, txt('Not possible, desired price has to be lower then Listprice'));
- } else {
- $g_flagFormula = 0; //$this->isAustria() ? '0' : '1';
- $viewType = 1; // 1 pagina di dettaglio, 0 pagina di summary.
- $totExtraProduct=0;
- /*
- if ($offerController->viewType) {
- $totExtraProduct = $offerController->tplOffer['extrasNovaTotal']['taxedPrice']+$offerController->tplOffer['extrasNoNovaTotal']['taxedPrice'];
- } else {
- $totExtraProduct = $offerController->tplOffer['extrasNoNovaTotal']['taxedPrice']+$offerController->tplOffer['extrasNovaTotal']['taxedPrice'];
- }
- */
- // Oppure ciclo su tutti gli tmpSummaryExtra.
- foreach ($offerController->tmpSummaryExtra as $extra) {
- if ($extra['category'] == 4 && empty($extra['isextraopt'])) {
- $totExtraProduct += $extra['taxedPrice'];
- }
- }
- $totproduct = $totExtraProduct;
- ///////////////////////////////attuazione della formula /////////////////////
- if ($prezzop2 > $prezzofinale) {
- //p2>PF
- $sconto = ($prezzofinale - $offertafinaleSoloIvato-$totproduct)/(1+$iva);
- } else {
- if($g_flagFormula == 1) {
- $sconto = -((($prezzoOffertafinale+$totproduct+($differ_base)) - $prezzofinale) / ((1+$iva)+($novaPerc/100)));
- } else {
- $sconto = -((($offertafinaleSoloIvato+$totproduct+($differ_base)) - $prezzofinale) / ((1+$iva)+($novaPerc/100)));
- }
- }
- /////////////////////////fine attuazione ///////////////////////////////////
- /*
- * Quando si effettua l'inserimento del prezzo da videata summary (viewtype=0)
- * si devono effetuare ulteriori considerazioni sullo sconto calcolato
- * Se il differbase è maggiore di 0, allo sconto devo sorporare l'iva + la nova
- * altrimenti solo l'iva
- */
- if ($viewType==0) {
- if ($differ_base > 0) {
- $sconto = $sconto*((1+$iva)+($novaPerc/100));
- } else {
- $sconto = $sconto*(1+$iva);
- }
- }
- }
- /*
- $html = "prezzoOffertafinale: " . $prezzoOffertafinale . "\n";
- $html .= "prezzo desiderato: " . $prezzofinale . "\n";
- $html .= "offertafinaleSoloIvato: " . $offertafinaleSoloIvato . "\n";
- $html .= "differ_base: -" . $differ_base . "\n";
- $html .= "d44: " . $d44 . "\n";
- $html .= "prezzop1: " . $prezzop1 . "\n";
- $html .= "prezzop2: " . $prezzop2 . "\n";
- $html .= "totproduct: " . $totproduct . "\n";
- $html .= "sconto: " . $sconto . "\n";
- var_dump($html); die;
- */
- return $sconto;
- }
- /**
- * Rimuove una tassa dall'offerta (sul F/E viene disabilitata ma rimane visibile)
- * e ritorna un oggetto QuotationEntity aggiornato.
- *
- * @param string $codoffer
- * @param string $codtax
- *
- * @return QuotationEntity
- */
- public function deleteTax($codoffer, $codtax)
- {
- // verifichiamo che l'offerta non sia completa
- if ($this->offer->offerstate) {
- return new BaseException(BaseException::PROCESS_ERROR, "Offer {$codoffer} is complete!");
- }
- $quotationEntity = self::getQuotation($codoffer);
- $canbereset = false;
- /**
- * in reltà sembra che tutte le tasse possano essere azzerate
- * questo ciclo serve a recuperare il codvalue che viene utilizzato
- * dal controller
- */
- foreach ($quotationEntity->taxes as $tax) {
- if ($tax->codtax == $codtax) {
- $canbereset = $tax->canbereset;
- // trick per superare indenni la setProperties del controller
- // che utilizza nomi diversi delle variabili
- $_POST['codtax'] = $tax->codvalue;
- break; // trovata quella che ci serve è inutile continuare
- }
- }
- if($_SESSION['SS_CODMARKET'] != "3239" && $codtax == "SCT") {
- if (!$canbereset) {
- return new BaseException(BaseException::PROCESS_ERROR,
- "action deletetax: tax {$codtax} could not be removed!");
- }
- }
- if($_SESSION['SS_CODMARKET'] == "3239") {
- $result = -1;
- if($codtax == "REGISTER_TAX") {
- $result = \OfferBase::setRegTaxValue($codoffer, null); // REGTAXVGALUE
- } else if($codtax == "MVT") {
- $result = \OfferBase::setMvtValue($codoffer, 0);
- // $result = \OfferBase::getMvtValue($codoffer); // MVT
- /* if(count($result) > 0) {
- if(is_null($result[0]['MVTVALUE'])) {
- $result = \OfferBase::setMvtValue($codoffer, 0); // MVT
- } else {
- $result = \OfferBase::setMvtValue($codoffer, null); // MVT
- }
- } else {
- $result = \OfferBase::setMvtValue($codoffer, 0); // MVT
- }
- */
- } else if($codtax == "SCT") {
- $result = \OfferBase::setSctValue($codoffer, null); // SCT
- }
- if ($result < 0) {
- return new BaseException(BaseException::PROCESS_ERROR, "Edit error!");
- }
- return self::getQuotation($codoffer);
- }
- // carichiamo l'OfferSummaryController che usiamo come DAO...
- $offerSummaryController = new \OfferSummaryController();
- // forziamo gli attributi necessari alla action prima
- // della setProperties perche alcuni sono utilizzati in tale contesto... :P
- $offerSummaryController->changeViewType = 1;
- $offerSummaryController->viewType = 1;
- $offerSummaryController->isAPI = 1;
- /**
- * non ci siamo bevuti il cervello...
- * in OfferSummaryController::taxHandler
- * viene gestita una logica inversa per adattarsi al front-end html
- */
- $offerSummaryController->doAction = 'add_tax';
- // $offerSummaryController->codTax = $codtax;
- $offerSummaryController->setProperties();
- // attualizziamo l'offerta
- $offerSummaryController->process();
- return self::getQuotation($codoffer);
- }
- public function getSincomByBrandMainDealer($p_codMarket, $p_codDealer, $codbrand)
- {
- $codmaindealer = \DealerBase::findByPrimaryKeyDealer($p_codMarket, $p_codDealer);
- if ($codmaindealer) {
- $codmaindealer = $codmaindealer[0]['CODMAINDEALER'];
- } else {
- $codmaindealer = $p_codDealer;
- }
- return \DealerBase::findByCodBrandCodMainDealer($codbrand, $codmaindealer, $p_codMarket);
- }
- /**
- * Restituisce le regole di compatibilita dei prodotti.
- *
- * @param string $codoffer
- * @param array $basket
- * @param array $families
- * @return \Application\Controller\BaseException
- */
- public function findCompatibleProducts($codoffer, $basket, $families)
- {
- $basketValues = explode(',', $basket);
- $families = explode(',', $families);
- if (empty($basketValues)) {
- return new BaseException(BaseException::BAD_PARAMETERS, 'basket could not be empty!');
- }
- if (empty($families)) {
- return new BaseException(BaseException::BAD_PARAMETERS, 'families could not be empty!');
- }
- require_once (APPL_PATH . 'COMMON/VinDriven/controllers/VinDrivenController.class.php');
- $vinDrivenObj = new \VinDrivenController();
- $vinDrivenObj->init();
- $vinDrivenObj->isAPI = 1;
- // Restituisce le regole di compatibilita dei prodotti.
- $vinDrivenObj->setbasketRowsValues(json_encode($basketValues));
- $vinDrivenObj->setfamilies(json_encode($families));
- $vinDrivenObj->setplanSaleDate(\DateUtils::mysqlToUTC(date("Y-m-d H:i:s")));
- $vinDrivenObj->setAction('findCompatibleProducts');
- $productData = $vinDrivenObj->process();
- var_dump($productData);
- die();
- }
- /**
- * Aggiunge uno o piu' elementi nel carrello e ritorna un oggetto QuotationEntity aggiornato.
- *
- * @param string $codoffer
- * @param array $basket
- * @param array $families
- *
- * @return QuotationEntity
- */
- public function storeBasketMVP($codoffer, $basket)
- {
- $offer = self::getOffer();
- $basketValues = json_decode($basket);
- // var_dump($offer); die;
- $_SESSION['SS_APPLTYPE'] = 'PORTAL'; // necessario per il tool (newcontractproposal).
- $mvs = $offer->getCodModel() . '' . $offer->getCodVersion() . '' . $offer->getCodSerie();
- require_once (APPL_PATH . 'COMMON/VinDriven/controllers/VinDrivenController.class.php');
- $vinDrivenObj = new \VinDrivenController();
- $vinDrivenObj->init();
- $vinDrivenObj->isAPI = 1;
- $vinDrivenObj->setcodoffer($codoffer);
- // vehicle
- $vinDrivenObj->setmvs($mvs);
- $vinDrivenObj->setAction('findByMVS');
- $vehicleData = $vinDrivenObj->process();
- // var_dump($vehicleData); die;
- // listCustomerType
- $vinDrivenObj->setAction('listCustomerType');
- $listCustomerTypeData = $vinDrivenObj->process();
- // listNations
- $vinDrivenObj->setAction('listNations');
- $listNationsData = $vinDrivenObj->process();
- // contact
- $vinDrivenObj->setcodcontact($offer->getCodContact());
- $vinDrivenObj->setAction('findContactDetails');
- $contactData = $vinDrivenObj->process();
- $eligibilityData = array(
- 'PLANSALEDATE' => \DateUtils::mysqlToUTC(date("Y-m-d H:i:s")), // '2016-11-11T00:00:00',
- 'SALESTYPE' => 'DLR',
- 'PLANTYPE' => 'A',
- 'SOURCEOFSALE' => 'FGA',
- 'hiddenCodOrigin' => ''
- );
- $vehicleData['WARRANTYCOVERAGECODE'] = 'W24';
- $vehicleData['MVS'] = $vehicleData['CODMVS'];
- $vehicleData['MVSdisplay'] = $vehicleData['CODMVS'];
- $vehicleData['MODELYEARDISPLAY'] = $vehicleData['MODELYEAR'];
- $vehicleData['MILEAGE'] = 0;
- // var_dump($vehicleData); die;
- // eliproduct
- $sentdata = json_encode(
- array(
- 'vehicleData' => $vehicleData,
- 'customerData' => $contactData,
- 'eligibilityData' => $eligibilityData,
- "OfferFlag" => ""
- ));
- $vinDrivenObj->setsentdata($sentdata);
- $vinDrivenObj->setAction('eliproduct');
- $eliproductData = $vinDrivenObj->process();
- if (!empty($eliproductData['errorMessage'])) {
- throw new BaseException(BaseException::PROCESS_ERROR,
- "Mvp::listMvp: {$eliproductData['errorMessage']}");
- }
- $opts = array();
- foreach ($eliproductData['opts'] as $opt) {
- foreach ($basketValues as $basket) {
- if (\Util::array_search_key_recursive($basket->familycode, $opt) &&
- \Util::array_search_key_recursive($basket->plancode, $opt)) {
- array_push($opts, $opt);
- }
- }
- }
- if (empty($opts)) {
- return new BaseException(BaseException::BAD_PARAMETERS, 'basket could not be empty!');
- }
- // storeBasket
- $sentdata = json_encode(
- array(
- 'basketRows' => $opts,
- 'commonData' => array(
- 'vehicleData' => $vehicleData,
- 'customerData' => $contactData,
- 'eligibilityData' => $eligibilityData,
- 'OfferFlag' => '',
- 'idBasket' => null,
- 'codrepairorder' => ''
- ),
- 'basketInitData' => array(
- "codoffer" => $codoffer,
- "codorigin" => 3
- )
- ));
- // storeBasket
- $vinDrivenObj->setsentdata($sentdata);
- $vinDrivenObj->setAction('storeBasket');
- $basketData = $vinDrivenObj->process();
- if (isset($basketData->results) && !empty($basketData->results->error)) {
- throw new BaseException(BaseException::PROCESS_ERROR,
- "Mvp::storeBasketMVP: {$basketData->results->error}");
- }
- // var_dump($basketData->results->idbasket); die;
- return self::getQuotation($codoffer);
- }
- /**
- * Funzione che cancella logicamente i dati del basket e ritorna un oggetto QuotationEntity aggiornato.
- *
- * @param string $codoffer
- *
- * @return QuotationEntity
- */
- public function deleteMvp($codoffer)
- {
- // verifichiamo che l'offerta non sia completa
- if ($this->offer->offerstate) {
- return new BaseException(BaseException::PROCESS_ERROR, "Offer {$codoffer} is complete!");
- }
- require_once (APPL_PATH . 'COMMON/VinDriven/models/VinDrivenModel.class.php');
- $basketEsalesData = \VinDrivenModel::findProductsByOffer($codoffer);
- if (!empty($basketEsalesData) && intval($basketEsalesData[0]['IDBASKET'])) {
- if (\VinDrivenModel::deleteAllBasket($basketEsalesData[0]['IDBASKET']) <= 0) {
- return new BaseException(BaseException::PROCESS_ERROR,
- "action deleteMvp: basketID {$basketEsalesData[0]['IDBASKET']} could not be removed!");
- }
- }
- return self::getQuotation($codoffer);
- }
- /**
- * API ResetAll
- * dato in input un'offerta singola/multipla va a rimuovere tutti gli eventuali sconti, promozioni, accessori, tradeIn...
- * Cancellazione di una singola offerta e di tutte le sue relazioni.
- *
- * Tecnicamente bisogna rimuovere i seguenti record:
- * -offerta singola
- * -offerproductdealerdiscount
- * -offerproductextra
- * -offerproductpromotion - OK
- * -offeraccessory - OK
- * -offerusedvehicle_new
- * -scm_basket
- *
- * offerta multipla:
- * -offerbasketextra
- * -offerbasketoffers
- *
- * @param string $codoffer
- *
- * @return QuotationEntity
- */
- public function resetAll($codoffer)
- {
- self::initSession($codoffer);
- $offer = self::getOffer();
- // verifichiamo che l'offerta non sia completa
- if ($offer->getOfferState()) {
- return new BaseException(BaseException::PROCESS_ERROR, "Offer {$codoffer} is complete!");
- }
- $quot = self::getQuotation($codoffer);
- if (!empty($quot->promotions)) { // 1. promotions
- foreach ($quot->promotions as $promo) {
- self::deletePromotion($codoffer, $promo->codpromotion);
- }
- }
- if (!empty($quot->accessories)) { // 2. accessories
- foreach ($quot->accessories as $acc) {
- $onlywork=0;
- self::deleteAccessory($codoffer, $acc->codaccessory, $onlywork);
- }
- }
- /*
- if (!empty($quot->taxes)) { // 3. taxes
- foreach ($quot->taxes as $tax) {
- if ($tax->codtax == 'IPT')
- continue;
- self::deleteTax($codoffer, $tax->codtax);
- }
- }
- */
- if (!empty($quot->services)) { // 3. sconti
- foreach ($quot->services as $service) {
- self::deleteDealerService($codoffer, $service->codservice);
- }
- }
- //self::deleteDealerFreeService($codoffer, $coddealerservice, $novaexcluded = 0);
- self::deleteTradeInValue($codoffer);
- \OfferBase::cleanOffer($codoffer);
- /*
- if (intval(\OfferBase::removeOfferCascade($codoffer)) >= 0) {
- return $quot;
- }
- */
- return self::getQuotation($codoffer);
- }
- private function setOfferState($codoffer, $status = 0)
- {
- self::initSession($codoffer);
- $offer = self::getOffer();
- $offer->setOfferState(intval($status));
- $offer->store();
- }
- /**
- * createNegotiation
- *
- * @param string $codOffer
- * @param string $codNegotiation
- * @param string $nameNegotiation
- */
- private function createNegotiation($codOffer, $codNegotiation, $nameNegotiation)
- {
- $offer = self::getOffer();
- $plannedDate = date('Y-m-d H:i:s', strtotime("+2 day"));
- $codlead = ''; // !empty($this->getCodLead()) ? $this->getCodLead() : $_SESSION['CRM_CODLEAD'];
- // Aggiorno il CRM WII CORE venendo dall'offerta
- $wiiclass = new \crm_wii();
- $result = $wiiclass->crmwiiCore(null, null, $_SESSION['SS_LOGINNAME'], 'OF',
- $offer->getCodContact(), null, null, $plannedDate, $codNegotiation, $nameNegotiation,
- null, null, null, null, null, null, $_SESSION["CK_SESION"], null,
- $_SESSION['SS_CODBRAND'], $codlead);
- // T9158
- if ($result && $result == 1) {
- // $result = $this->insertFollowUp($offer->getCodContact());
- }
- return $result;
- }
- /**
- * getBreakPoints
- *
- * @see BreakPointsController /offerBreakPoints/index.php?action=load_break_point&
- *
- * @param string $codMarket
- * @param string $codBrand
- * @param string $codLanguage
- * @return array
- */
- public function getBreakPoints($codMarket, $codBrand, $codLanguage)
- {
- $breakPointList = \MarketOfferBreakPoints::findbymarketbrand($codMarket, $codBrand,
- $codLanguage);
- foreach ($breakPointList as $k => $val) {
- $breakPointList[$k]['SECTION_DESC'] = addslashes(
- \Util::txtAPI($breakPointList[$k]['SECTION_TAG'], $this->tokenProperties));
- }
- return $breakPointList;
- }
- /**
- * wrapper di DealerBase::findMainDealer che (inspiegabilmente)
- * ritorna un array (anche vuoto!)
- *
- * @param string $codMarket
- * @param string $coddealer
- * @throws Exception
- * @return string
- */
- private static function getCodMainDealer($codMarket, $coddealer)
- {
- $maindealer = \DealerBase::findMainDealer($coddealer, $codMarket);
- if (isset($maindealer[0])) {
- return $maindealer[0];
- } else {
- throw new \Exception("Invalid coddealer $codMarket/$coddealer");
- }
- }
- static function isFlagshipVipOffer()
- {
- if (isset($_SESSION['SS_VIP_FLAGSHIP'])) {
- return $_SESSION['SS_VIP_FLAGSHIP'];
- }
- return false;
- }
- static function checkDestinationIpt($codNation, $codRegion, $codDepartment)
- {
- $departments = \IPTBase::findByTechchar($codNation, $codRegion, 'DEST');
- foreach ($departments as $idx => $val) {
- if ($val['CODDEPARTMENT'] == $codDepartment) {
- return true;
- }
- }
- return false;
- }
- private static function isFlagshipDealer()
- {
- if (isset($_SESSION['SS_FLAGSHIP_DEALER'])) {
- return $_SESSION['SS_FLAGSHIP_DEALER'];
- }
- return false;
- }
- private static function returnValidation($data)
- {
- switch ($data) {
- case ('V'):
- return 1;
- case ('B'):
- return 0;
- case ('W'):
- return 2;
- }
- }
- private static function canDuplicateOffer()
- {
- return \MarketParams::findValueByPrimaryKey('OFFERMODIFY_ENABLED',
- $_SESSION['SS_CODMARKET'], '', 0);
- }
- /**
- * getPrivileges
- * Ritorna una matrice con i privilegi dell'utente sull'applicazione.
- * Al package viene sempre passato un array di ruoli, il ruolo
- * primario per Link ed eventuali ruoli secondari per altre applicazioni
- *
- * @return array
- */
- private static function getPrivileges($codMarket, $roles)
- {
- $result = array();
- $sql = 'pkLinkProfile.findPrivilegecodesByRole (:p_codMarket , :p_roles )';
- $stmt = $GLOBALS['dbObj']->prepareCall($sql, true);
- $stmt->setArrayParamDataTypes(array(
- ':p_roles' => SQLT_CHR
- ));
- $stmt->execute(
- array(
- ':p_codMarket' => $codMarket,
- ':p_roles' => $roles
- ));
- $data = $stmt->fetch();
- unset($stmt);
- foreach ($data as $loop)
- $result[] = $loop['PRIVCODE'];
- return $result;
- }
- private static function getCodLink($upsApplicationName, $codBrand)
- {
- $linkappls = \Profile::getLinkMarket($upsApplicationName);
- if (!empty($linkappls)) {
- foreach ($linkappls as $linkapp) {
- if ($linkapp['CODBRAND'] == $codBrand)
- return $linkapp['CODLINK'];
- }
- }
- return 0;
- }
- private function getQrCodeFromConf ($configuration) {
- /**
- * Parametri mercato e lingua
- */
- $localeID = explode('_', $_SESSION['SS_LOCALE_ID']);
- $languageConfigurator = $localeID[0];
- $marketConfigurator = strtolower($localeID[1]);
- $marketConf = $_SESSION['SS_CODMARKET'];
- $languageConf = $_SESSION['SS_CODLANGUAGE'];
- /**
- * Parametro che permette di stabilire se
- * allegare alla mail il codice QR (se restituito)
- */
- $attachQRinMail = false;
- /**
- * Si recupera il ccurl direttamente dal file
- * di innesco per essere allineati a produzione.
- *
- * Se l'url non esiste il servizio non è previsto
- * per quel mercato o quel brand.
- */
- $configuratorLoader = \CarConfB2C_Loader::getConfiguratorLoaderUrl($marketConf, $configuration['brandConf'], $languageConf);
- if (!!$configuratorLoader) {
- $confLoaderUrl = $configuratorLoader[0]['LOADERURL'];
- $apiPostUrl = $configuratorLoader[0]['APIENDPOINTPOST'];
- $apiQRUrl = $configuratorLoader[0]['APIENDPOINTQR'];
- $brandDescription = strtolower($configuratorLoader[0]['BRANDNAME']);
- $ch = curl_init();
- curl_setopt($ch, CURLOPT_URL, $confLoaderUrl);
- curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
- curl_setopt($ch, CURLOPT_HTTPHEADER, array());
- curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
- curl_setopt($ch, CURLOPT_PROXY, PROXY_HOST . ':' . PROXY_PORT);
- curl_setopt($ch, CURLOPT_PROXYUSERPWD, PROXY_USER . ':' . PROXY_PASS);
- $response = curl_exec($ch);
- curl_close($ch);
- $responseDecoded = json_decode($response, true)['models'][$configuration['metadataModel']];
- if(!!$responseDecoded) {
- $ccurl = $responseDecoded['url'].'/#/confID/';
- /**
- * Si apre il file con la configurazione XML vuota
- */
- $filename = APPL_PATH . 'apigility/data/file_config_empty.xml';
- $xmlMod = simplexml_load_file($filename);
- if ($xmlMod) {
- //**************************************************************************
- $metadataNode = $xmlMod->metadata;
- /**
- * Si modifica l'oggetto con l'xml con i dati provenienti
- * dal percorso dell'offerta.
- *
- * ***************** METADATA NODE *****************
- *
- * 1) MARKET:
- */
- $metadataNode->Item[0] = (isset($marketConf)) ? $marketConf : '';
- /**
- * 2) BRAND:
- */
- $metadataNode->Item[1] = (isset($configuration['brandConf'])) ? $configuration['brandConf'] : '';
- /**
- * 3) LANGUAGE:
- */
- $metadataNode->Item[2] = (isset($languageConf)) ? $languageConf : '';
- /**
- * 4) MODEL DESCRIPTION:
- */
- $metadataNode->Item[3] = (isset($configuration['modelDescription'])) ? $configuration['modelDescription'] : '';
- /**
- * 5) CONFIGURATION DESCRIPTION:
- */
- $metadataNode->Item[4] = (isset($configuration['configDescription'])) ? $configuration['configDescription'] : '';
- /**
- * 6) MODEL NAME:
- */
- $metadataNode->Item[5] = (isset($configuration['modelName'])) ? $configuration['modelName'] : '';
- /**
- * 7) MODEL:
- */
- $metadataNode->Item[6] = (isset($configuration['metadataModel'])) ? $configuration['metadataModel'] : '';
- /**
- * 8) CCURL:
- */
- $metadataNode->Item[7] = (isset($ccurl)) ? $ccurl : '';
- /**
- * 9) FOOTER PRIVACY:
- */
- $metadataNode->Item[8] = (isset($configuration['footerPrivacy'])) ? $configuration['footerPrivacy'] : '';
- $LMFINode = $xmlMod->LMFI;
- /**
- * ***************** LMFI NODE *****************
- *
- * 10) USE EXTENDED FILTERS:
- */
- $LMFINode->Item[0] = (isset($configuration['useExtdFilters'])) ? $configuration['useExtdFilters'] : '';
- /**
- * 11) SHOW MVS LIST:
- */
- $LMFINode->Item[1] = (isset($configuration['showMvsList'])) ? $configuration['showMvsList'] : '';
- /**
- * 12) USE LMFI PLUS:
- */
- $LMFINode->Item[2] = (isset($configuration['useLMFIPlus'])) ? $configuration['useLMFIPlus'] : '';
- /**
- * 13) PREDICTIVE GRIDS:
- */
- $LMFINode->Item[3] = (isset($configuration['predictiveGrids'])) ? $configuration['predictiveGrids'] : '';
- /**
- * 14) GROUPS:
- * (e.g.: GROUP1|GROUP2|GROUP3)
- */
- $LMFINode->Item[4] = (isset($configuration['groups'])) ? $configuration['groups'] : '';
- /**
- * 15) MODEL:
- */
- $LMFINode->Item[5] = (isset($configuration['LMFIModel'])) ? $configuration['LMFIModel'] : '';
- /**
- * 16) MVS:
- * (e.g.: 57609L204000)
- */
- $LMFINode->Item[6] = (isset($configuration['mvs'])) ? $configuration['mvs'] : '';
- /**
- * 17) DEVICE:
- */
- $LMFINode->Item[7] = (isset($configuration['device'])) ? $configuration['device'] : '';
- /**
- * 18) CO2:
- */
- $LMFINode->Item[8] = (isset($configuration['co2'])) ? $configuration['co2'] : '';
- /**
- * 19) BODY:
- */
- $LMFINode->Item[9] = (isset($configuration['body'])) ? $configuration['body'] : '';
- /**
- * 20) WHEL:
- */
- $LMFINode->Item[10] = (isset($configuration['whel'])) ? $configuration['whel'] : '';
- /**
- * 21) SEAT:
- */
- $LMFINode->Item[11] = (isset($configuration['seat'])) ? $configuration['seat'] : '';
- /**
- * 22) EQPM:
- */
- $LMFINode->Item[12] = (isset($configuration['eqpm'])) ? $configuration['eqpm'] : '';
- /**
- * 23) DRVE:
- */
- $LMFINode->Item[13] = (isset($configuration['drve'])) ? $configuration['drve'] : '';
- /**
- * 24) ENGN:
- */
- $LMFINode->Item[14] = (isset($configuration['engn'])) ? $configuration['engn'] : '';
- /**
- * 25) FUEL:
- */
- $LMFINode->Item[15] = (isset($configuration['fuel'])) ? $configuration['fuel'] : '';
- /**
- * 26) GEAR:
- */
- $LMFINode->Item[16] = (isset($configuration['gear'])) ? $configuration['gear'] : '';
- /**
- * 27) PACK:
- */
- $LMFINode->Item[17] = (isset($configuration['pack'])) ? $configuration['pack'] : '';
- /**
- * 28) OPTS:
- * (e.g.: |009#-|011|023|025|026|112|132)
- */
- $LMFINode->Item[18] = (isset($configuration['opts'])) ? $configuration['opts'] : '';
- /**
- * 29) PRICE:
- * (Il separatore è il punto)
- */
- $LMFINode->Item[19] = (isset($configuration['price'])) ? $configuration['price'] : '';
- /**
- * 30) PRICE NO VAT:
- * (Il separatore è il punto)
- */
- $LMFINode->Item[20] = (isset($configuration['priceNoVat'])) ? $configuration['priceNoVat'] : '';
- /**
- * Nodo tools da considerare? Lasciare pre-compilato?
- */
- //$ToolsNode = $xmlMod->Tools;
- //$firstImageUrl = $ToolsNode->groups[0]->group->images->image->layer['path'];
- //$secondImageUrl = $ToolsNode->groups[1]->group->images->image->layer['path'];
- //$thirdImageUrl = $ToolsNode->groups[2]->group->images->image->layer['path'];
- //$baseUrl = $ToolsNode->groups[0]->group->settings->baseUrl;
- /**
- * Si memorizza il file xml opportunamente
- * modificato nella variabile $xml e passato
- * al payload
- */
- $xml = $xmlMod->asXML();
- //**************************************************************************
- $payloadArray = array(
- "market" => $marketConfigurator,
- "language" => $languageConfigurator,
- "brand" => $brandDescription,
- "configurationType" => "ANONYMOUS",
- "configurationId" =>null,
- "configurationData" => $xml
- );
- $payload = json_encode($payloadArray);
- $headers = array(
- 'Content-type: application/json',
- 'Connection: close',
- 'accept-encoding: gzip, deflate, br'
- );
- /**
- * Inizializzo curl e le sue proprietÃ
- */
- $ch = curl_init();
- /**
- * Recupero il configuration ID da:
- * bp_vl/bm/vehicles/configuration/post/set/json
- */
- curl_setopt($ch, CURLOPT_URL, $apiPostUrl);
- curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
- curl_setopt($ch, CURLOPT_VERBOSE, 1);
- curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
- curl_setopt($ch, CURLOPT_POST, true);
- curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
- curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
- curl_setopt($ch, CURLOPT_PROXY, PROXY_HOST . ':' . PROXY_PORT);
- curl_setopt($ch, CURLOPT_PROXYUSERPWD, PROXY_USER . ':' . PROXY_PASS);
- /**
- * Eseguo la chiamata
- */
- $response = curl_exec($ch);
- curl_close($ch);
- $result = json_decode($response, true);
- $configurationIdAlias = $result['configurationIdAlias'];
- /**
- * Check configuration ID:
- *
- * http://carconfigurator.fiat.com/ProductCatalog.asmx?op=getConfiguration
- */
- if (!!$configurationIdAlias || !curl_error($ch)) {
- $configurationId = $result['configurationId'];
- /**
- * Si recupera il baseUrl direttamente dal file
- * di innesco per essere allineati a produzione.
- */
- $ch = curl_init();
- $baseUrl = urlencode($ccurl);
- $url = $apiQRUrl;
- $url .= '?market='.$languageConfigurator;
- $url .= '&brand='.$brandDescription;
- $url .= '&baseURL='.$baseUrl.$configurationIdAlias;
- $url .= '&configurationId=?';
- $url .= '&filters=';
- curl_setopt($ch, CURLOPT_URL, $url);
- curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
- curl_setopt($ch, CURLOPT_HTTPHEADER, array());
- curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
- curl_setopt($ch, CURLOPT_PROXY, PROXY_HOST . ':' . PROXY_PORT);
- curl_setopt($ch, CURLOPT_PROXYUSERPWD, PROXY_USER . ':' . PROXY_PASS);
- $response = curl_exec($ch);
- curl_close($ch);
- $result = json_decode($response, true);
- $qrcode = $result['Items'][0]['value'];
- if (!!$qrcode) {
- $attachQRinMail = true;
- echo ('CONFIGURATION CODE: '.$configurationIdAlias).'<br>';
- echo "<img src=data:image/png;base64,$qrcode>";
- } else {
- var_dump('QRcode is NULL'); exit();
- }
- } else {
- var_dump('Configuration id Alias is NULL'); exit();
- }
- } else {
- var_dump('Impossible to open the XML File'); exit();
- }
- } else {
- var_dump('No configuration loader found'); exit();
- }
- } else {
- var_dump('Service not allowed for current Market'); exit();
- }
- exit();
- }
- }
Add Comment
Please, Sign In to add comment