diff --git a/local/modules/ColissimoHomeDelivery/ColissimoHomeDelivery.php b/local/modules/ColissimoHomeDelivery/ColissimoHomeDelivery.php new file mode 100644 index 00000000..5b2860d3 --- /dev/null +++ b/local/modules/ColissimoHomeDelivery/ColissimoHomeDelivery.php @@ -0,0 +1,362 @@ +findOne(); + ColissimoHomeDeliveryFreeshippingQuery::create()->findOne(); + ColissimoHomeDeliveryAreaFreeshippingQuery::create()->findOne(); + } catch (\Exception $ex) { + $database = new Database($con->getWrappedConnection()); + $database->insertSql(null, [__DIR__ . "/Config/thelia.sql"]); + } + + if (!ColissimoHomeDeliveryFreeshippingQuery::create()->filterById(1)->findOne()) { + ColissimoHomeDeliveryFreeshippingQuery::create()->filterById(1)->findOneOrCreate()->setActive(0)->save(); + } + + if (!self::getConfigValue(self::AFFRANCHISSEMENT_ENDPOINT_URL)) { + self::setConfigValue(self::AFFRANCHISSEMENT_ENDPOINT_URL, 'https://ws.colissimo.fr/sls-ws/SlsServiceWS?wsdl'); + } + + if (!self::getConfigValue(self::COLISSIMO_USERNAME)) { + self::setConfigValue(self::COLISSIMO_USERNAME, ' '); + } + + if (!self::getConfigValue(self::COLISSIMO_PASSWORD)) { + self::setConfigValue(self::COLISSIMO_PASSWORD, ' '); + } + + if (!self::getConfigValue(self::ACTIVATE_DETAILED_DEBUG)) { + self::setConfigValue(self::ACTIVATE_DETAILED_DEBUG, '0'); + } + + if (null === MessageQuery::create()->findOneByName(self::CONFIRMATION_MESSAGE_NAME)) { + $message = new Message(); + + $message + ->setName(self::CONFIRMATION_MESSAGE_NAME) + ->setHtmlLayoutFileName('order_shipped.html') + ->setTextLayoutFileName('order_shipped.txt') + ->setLocale('en_US') + ->setTitle('Order send confirmation') + ->setSubject('Order send confirmation') + + ->setLocale('fr_FR') + ->setTitle('Confirmation d\'envoi de commande') + ->setSubject('Confirmation d\'envoi de commande') + + ->save() + ; + } + } + + /** + * @inheritDoc + */ + public function update($currentVersion, $newVersion, ConnectionInterface $con = null) + { + $finder = (new Finder) + ->files() + ->name('#.*?\.sql#') + ->sortByName() + ->in(__DIR__ . DS . 'Config' . DS . 'update'); + + $database = new Database($con); + + /** @var \Symfony\Component\Finder\SplFileInfo $updateSQLFile */ + foreach ($finder as $updateSQLFile) { + if (version_compare($currentVersion, str_replace('.sql', '', $updateSQLFile->getFilename()), '<')) { + $database->insertSql( + null, + [ + $updateSQLFile->getPathname() + ] + ); + } + } + } + + /** + * Returns ids of area containing this country and covered by this module + * @param Country $country + * @return array Area ids + */ + public function getAllAreasForCountry(Country $country) + { + $areaArray = []; + + $sql = 'SELECT ca.area_id as area_id FROM country_area ca + INNER JOIN area_delivery_module adm ON (ca.area_id = adm.area_id AND adm.delivery_module_id = :p0) + WHERE ca.country_id = :p1'; + + $con = Propel::getConnection(); + + $stmt = $con->prepare($sql); + $stmt->bindValue(':p0', $this->getModuleModel()->getId(), PDO::PARAM_INT); + $stmt->bindValue(':p1', $country->getId(), PDO::PARAM_INT); + $stmt->execute(); + + while ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) { + $areaArray[] = $row['area_id']; + } + + return $areaArray; + } + + /** + * @param $areaId + * @param $weight + * @param $cartAmount + * @param $deliverModeCode + * + * @return mixed + * @throws DeliveryException + */ + public static function getPostageAmount($areaId, $weight, $cartAmount = 0) + { + /** Check if freeshipping is activated */ + try { + $freeshipping = ColissimoHomeDeliveryFreeshippingQuery::create() + ->findPk(1) + ->getActive() + ; + } catch (\Exception $exception) { + $freeshipping = false; + } + + /** Get the total cart price needed to have a free shipping for all areas, if it exists */ + try { + $freeshippingFrom = ColissimoHomeDeliveryFreeshippingQuery::create() + ->findPk(1) + ->getFreeshippingFrom() + ; + } catch (\Exception $exception) { + $freeshippingFrom = false; + } + + /** Set the initial postage price as 0 */ + $postage = 0; + + /** If free shipping is enabled, skip and return 0 */ + if (!$freeshipping) { + + /** If a min price for general freeshipping is defined and the cart reach this amount, return a postage of 0 */ + if (null !== $freeshippingFrom && $freeshippingFrom <= $cartAmount) { + return 0; + } + + $areaFreeshipping = ColissimoHomeDeliveryAreaFreeshippingQuery::create() + ->filterByAreaId($areaId) + ->findOne() + ; + + if ($areaFreeshipping) { + $areaFreeshipping = $areaFreeshipping->getCartAmount(); + } + + /** If the cart price is superior to the minimum price for free shipping in the area of the order, + * return the postage as free. + */ + if (null !== $areaFreeshipping && $areaFreeshipping <= $cartAmount) { + return 0; + } + + /** Search the list of prices and order it in ascending order */ + $areaPrices = ColissimoHomeDeliveryPriceSlicesQuery::create() + ->filterByAreaId($areaId) + ->filterByMaxWeight($weight, Criteria::GREATER_EQUAL) + ->_or() + ->filterByMaxWeight(null) + ->filterByMaxPrice($cartAmount, Criteria::GREATER_EQUAL) + ->_or() + ->filterByMaxPrice(null) + ->orderByMaxWeight() + ->orderByMaxPrice() + ; + + /** Find the correct postage price for the cart weight and price according to the area and delivery mode in $areaPrices*/ + $firstPrice = $areaPrices->find() + ->getFirst(); + + if (null === $firstPrice) { + return null; + //throw new DeliveryException("Colissimo delivery unavailable for your cart weight or delivery country"); + } + + $postage = $firstPrice->getShipping(); + } + + return $postage; + } + + public function getMinPostage($areaIdArray, $cartWeight, $cartAmount) + { + $minPostage = null; + + foreach ($areaIdArray as $areaId) { + try { + $postage = self::getPostageAmount($areaId, $cartWeight, $cartAmount); + if (null === $postage) { + continue ; + } + if ($minPostage === null || $postage < $minPostage) { + $minPostage = $postage; + if ($minPostage == 0) { + break; + } + } + } catch (\Exception $ex) { + throw new DeliveryException($ex->getMessage()); //todo make a better catch + } + } + + if (null === $minPostage) { + throw new DeliveryException("Colissimo delivery unavailable for your cart weight or delivery country"); + } + + return $minPostage; + } + + /** + * Calculate and return delivery price + * + * @param Country $country + * @return mixed + * @throws DeliveryException + */ + public function getPostage(Country $country) + { + $request = $this->getRequest(); + + $postage = 0; + + $freeshippingIsActive = ColissimoHomeDeliveryFreeshippingQuery::create()->findOneById(1)->getActive(); + + if (false === $freeshippingIsActive){ + $cartWeight = $request->getSession()->getSessionCart($this->getDispatcher())->getWeight(); + $cartAmount = $request->getSession()->getSessionCart($this->getDispatcher())->getTaxedAmount($country); + + $areaIdArray = $this->getAllAreasForCountry($country); + if (empty($areaIdArray)) { + throw new DeliveryException("Your delivery country is not covered by Colissimo."); + } + + if (null === $postage = $this->getMinPostage($areaIdArray, $cartWeight, $cartAmount)) { + throw new DeliveryException("Colissimo delivery unavailable for your cart weight or delivery country"); + } + } + /* + * Laurent le 27/07/2025 : un seul module ColissimoHomeDelivery mais une case à cocher permet au client + * de choisir s'il souhaite bénéficier d'une remise avec signature et payer un montant forfaitaire paramétrable via une variable. + */ + $signature = $request->get('remise-avec-signature'); + if ($signature && $signature == 'on') { + $postage = ConfigQuery::read("surcout_remise_avec_signature"); + } + + return $postage; + } + + /** + * This method is called by the Delivery loop, to check if the current module has to be displayed to the customer. + * Override it to implements your delivery rules/ + * + * If you return true, the delivery method will de displayed to the customer + * If you return false, the delivery method will not be displayed + * + * @param Country $country the country to deliver to. + * + * @return boolean + */ + public function isValidDelivery(Country $country) + { + if (empty($this->getAllAreasForCountry($country))) { + return false; + } + + $countryAreas = $country->getCountryAreas(); + $areasArray = []; + + /** @var CountryArea $countryArea */ + foreach ($countryAreas as $countryArea) { + $areasArray[] = $countryArea->getAreaId(); + } + + $prices = ColissimoHomeDeliveryPriceSlicesQuery::create() + ->filterByAreaId($areasArray) + ->findOne(); + + $freeShipping = ColissimoHomeDeliveryFreeshippingQuery::create() + ->filterByActive(1) + ->findOne() + ; + + /** Check if Colissimo delivers the asked area*/ + if (null !== $prices || null !== $freeShipping) { + return true; + } + + return false; + } + + public static function getModCode() + { + return ModuleQuery::create()->findOneByCode('ColissimoHomeDelivery')->getId(); + } + + public function getDeliveryMode() + { + return "delivery"; + } +} diff --git a/local/modules/ColissimoHomeDelivery/Config/config.xml b/local/modules/ColissimoHomeDelivery/Config/config.xml new file mode 100644 index 00000000..f82c3d24 --- /dev/null +++ b/local/modules/ColissimoHomeDelivery/Config/config.xml @@ -0,0 +1,38 @@ + + + + + + + + + + + +
+ + + + + + + + + + + + + + + + + + + + + + + + diff --git a/local/modules/ColissimoHomeDelivery/Config/module.xml b/local/modules/ColissimoHomeDelivery/Config/module.xml new file mode 100644 index 00000000..41268995 --- /dev/null +++ b/local/modules/ColissimoHomeDelivery/Config/module.xml @@ -0,0 +1,24 @@ + + + ColissimoHomeDelivery\ColissimoHomeDelivery + + Home delivery with Colissimo + + + Livraison à domicile avec Colissimo + + + en_US + fr_FR + + 1.0.2 + + Thelia + info@thelia.net + + delivery + 2.3.3 + other + diff --git a/local/modules/ColissimoHomeDelivery/Config/routing.xml b/local/modules/ColissimoHomeDelivery/Config/routing.xml new file mode 100644 index 00000000..bb9b6037 --- /dev/null +++ b/local/modules/ColissimoHomeDelivery/Config/routing.xml @@ -0,0 +1,29 @@ + + + + + + ColissimoHomeDelivery\Controller\ConfigurationController::configure + + + + + + ColissimoHomeDelivery\Controller\FreeShippingController::toggleFreeShippingActivation + + + + ColissimoHomeDelivery\Controller\FreeShippingController::setAreaFreeShipping + + + + ColissimoHomeDelivery\Controller\PriceSliceController::savePriceSliceAction + + + + ColissimoHomeDelivery\Controller\PriceSliceController::deletePriceSliceAction + + + diff --git a/local/modules/ColissimoHomeDelivery/Config/schema.xml b/local/modules/ColissimoHomeDelivery/Config/schema.xml new file mode 100644 index 00000000..6b00508b --- /dev/null +++ b/local/modules/ColissimoHomeDelivery/Config/schema.xml @@ -0,0 +1,34 @@ + + + + + + + + + + + + + +
+ + + + + +
+ + + + + + + + +
+ + +
diff --git a/local/modules/ColissimoHomeDelivery/Config/sqldb.map b/local/modules/ColissimoHomeDelivery/Config/sqldb.map new file mode 100644 index 00000000..63a93baa --- /dev/null +++ b/local/modules/ColissimoHomeDelivery/Config/sqldb.map @@ -0,0 +1,2 @@ +# Sqlfile -> Database map +thelia.sql=thelia diff --git a/local/modules/ColissimoHomeDelivery/Config/thelia.sql b/local/modules/ColissimoHomeDelivery/Config/thelia.sql new file mode 100644 index 00000000..dbe22a3c --- /dev/null +++ b/local/modules/ColissimoHomeDelivery/Config/thelia.sql @@ -0,0 +1,63 @@ + +# This is a fix for InnoDB in MySQL >= 4.1.x +# It "suspends judgement" for fkey relationships until are tables are set. +SET FOREIGN_KEY_CHECKS = 0; + +-- --------------------------------------------------------------------- +-- colissimo_home_delivery_price_slices +-- --------------------------------------------------------------------- + +DROP TABLE IF EXISTS `colissimo_home_delivery_price_slices`; + +CREATE TABLE `colissimo_home_delivery_price_slices` +( + `id` INTEGER NOT NULL AUTO_INCREMENT, + `area_id` INTEGER NOT NULL, + `max_weight` FLOAT, + `max_price` FLOAT, + `shipping` FLOAT NOT NULL, + PRIMARY KEY (`id`), + INDEX `FI_colissimo_home_delivery_price_slices_area_id` (`area_id`), + CONSTRAINT `fk_colissimo_home_delivery_price_slices_area_id` + FOREIGN KEY (`area_id`) + REFERENCES `area` (`id`) + ON UPDATE RESTRICT + ON DELETE RESTRICT +) ENGINE=InnoDB; + +-- --------------------------------------------------------------------- +-- colissimo_home_delivery_freeshipping +-- --------------------------------------------------------------------- + +DROP TABLE IF EXISTS `colissimo_home_delivery_freeshipping`; + +CREATE TABLE `colissimo_home_delivery_freeshipping` +( + `id` INTEGER NOT NULL, + `active` TINYINT(1) DEFAULT 0, + `freeshipping_from` DECIMAL(18,2), + PRIMARY KEY (`id`) +) ENGINE=InnoDB; + +-- --------------------------------------------------------------------- +-- colissimo_home_delivery_area_freeshipping +-- --------------------------------------------------------------------- + +DROP TABLE IF EXISTS `colissimo_home_delivery_area_freeshipping`; + +CREATE TABLE `colissimo_home_delivery_area_freeshipping` +( + `id` INTEGER NOT NULL, + `area_id` INTEGER NOT NULL, + `cart_amount` DECIMAL(18,2) DEFAULT 0.00, + PRIMARY KEY (`id`), + INDEX `FI_colissimo_home_delivery_area_freeshipping_area_id` (`area_id`), + CONSTRAINT `fk_colissimo_home_delivery_area_freeshipping_area_id` + FOREIGN KEY (`area_id`) + REFERENCES `area` (`id`) + ON UPDATE RESTRICT + ON DELETE RESTRICT +) ENGINE=InnoDB; + +# This restores the fkey checks, after having unset them earlier +SET FOREIGN_KEY_CHECKS = 1; diff --git a/local/modules/ColissimoHomeDelivery/Config/update/1.0.0.sql b/local/modules/ColissimoHomeDelivery/Config/update/1.0.0.sql new file mode 100644 index 00000000..e69de29b diff --git a/local/modules/ColissimoHomeDelivery/Controller/ConfigurationController.php b/local/modules/ColissimoHomeDelivery/Controller/ConfigurationController.php new file mode 100644 index 00000000..369ff35b --- /dev/null +++ b/local/modules/ColissimoHomeDelivery/Controller/ConfigurationController.php @@ -0,0 +1,80 @@ + + * Date: 17/08/2019 12:26 + */ +namespace ColissimoHomeDelivery\Controller; + +use ColissimoHomeDelivery\ColissimoHomeDelivery; +use Thelia\Controller\Admin\BaseAdminController; +use Thelia\Core\Security\AccessManager; +use Thelia\Core\Security\Resource\AdminResources; +use Thelia\Form\Exception\FormValidationException; +use Thelia\Tools\URL; + +class ConfigurationController extends BaseAdminController +{ + public function configure() + { + if (null !== $response = $this->checkAuth(AdminResources::MODULE, ColissimoHomeDelivery::DOMAIN_NAME, AccessManager::UPDATE)) { + return $response; + } + + $configurationForm = $this->createForm('colissimo.homedelivery.configuration.form'); + + $message = false; + + $url = '/admin/module/ColissimoHomeDelivery'; + + try { + $form = $this->validateForm($configurationForm); + + // Get the form field values + $data = $form->getData(); + + foreach ($data as $name => $value) { + if (is_array($value)) { + $value = implode(';', $value); + } + + ColissimoHomeDelivery::setConfigValue($name, $value); + } + + // Log configuration modification + $this->adminLogAppend( + 'colissimo.home.delivery.configuration.message', + AccessManager::UPDATE, + 'ColissimoHomeDelivery configuration updated' + ); + + // Redirect to the success URL, + if (! $this->getRequest()->get('save_mode') === 'stay') { + $url = '/admin/modules'; + } + } catch (FormValidationException $ex) { + $message = $this->createStandardFormValidationErrorMessage($ex); + } catch (\Exception $ex) { + $message = $ex->getMessage(); + } + + if ($message !== false) { + $this->setupFormErrorContext( + $this->getTranslator()->trans('ColissimoHomeDelivery configuration', [], ColissimoHomeDelivery::DOMAIN_NAME), + $message, + $configurationForm, + $ex + ); + } + + return $this->generateRedirect(URL::getInstance()->absoluteUrl($url, [ 'tab' => 'config', 'success' => $message === false ])); + } +} diff --git a/local/modules/ColissimoHomeDelivery/Controller/FreeShippingController.php b/local/modules/ColissimoHomeDelivery/Controller/FreeShippingController.php new file mode 100644 index 00000000..bc4ddcd1 --- /dev/null +++ b/local/modules/ColissimoHomeDelivery/Controller/FreeShippingController.php @@ -0,0 +1,123 @@ +. */ +/* */ +/*************************************************************************************/ + +namespace ColissimoHomeDelivery\Controller; + +use ColissimoHomeDelivery\Form\FreeShippingForm; +use ColissimoHomeDelivery\Model\ColissimoHomeDeliveryAreaFreeshippingQuery; +use ColissimoHomeDelivery\Model\ColissimoHomeDeliveryFreeshipping; +use ColissimoHomeDelivery\Model\ColissimoHomeDeliveryFreeshippingQuery; +use Symfony\Component\HttpFoundation\JsonResponse; +use Symfony\Component\HttpFoundation\Response; +use Thelia\Controller\Admin\BaseAdminController; + +use Thelia\Core\Security\Resource\AdminResources; +use Thelia\Core\Security\AccessManager; +use Thelia\Model\AreaQuery; +use Thelia\Tools\URL; + +class FreeShippingController extends BaseAdminController +{ + public function toggleFreeShippingActivation() + { + if (null !== $response = $this + ->checkAuth(array(AdminResources::MODULE), array('ColissimoHomeDelivery'), AccessManager::UPDATE)) { + return $response; + } + + $form = new FreeShippingForm($this->getRequest()); + $response = null; + + try { + $vform = $this->validateForm($form); + $freeshipping = $vform->get('freeshipping')->getData(); + $freeshippingFrom = $vform->get('freeshipping_from')->getData(); + + if (null === $isFreeShippingActive = ColissimoHomeDeliveryFreeshippingQuery::create()->findOneById(1)){ + $isFreeShippingActive = new ColissimoHomeDeliveryFreeshipping(); + } + + $isFreeShippingActive + ->setActive($freeshipping) + ->setFreeshippingFrom($freeshippingFrom) + ; + $isFreeShippingActive->save(); + + $response = $this->generateRedirectFromRoute( + 'admin.module.configure', + array(), + array ( + 'current_tab'=> 'prices_slices_tab', + 'module_code'=> 'ColissimoHomeDelivery', + '_controller' => 'Thelia\\Controller\\Admin\\ModuleController::configureAction', + 'price_error_id' => null, + 'price_error' => null + ) + ); + } catch (\Exception $e) { + $response = JsonResponse::create(array('error' => $e->getMessage()), 500); + } + return $response; + } + + /** + * @return mixed|Response|null + */ + public function setAreaFreeShipping() + { + if (null !== $response = $this + ->checkAuth(array(AdminResources::MODULE), array('ColissimoHomeDelivery'), AccessManager::UPDATE)) { + return $response; + } + + try { + $data = $this->getRequest()->request; + + $colissimo_homedelivery_area_id = $data->get('area-id'); + $cartAmount = $data->get('cart-amount'); + + if ($cartAmount < 0 || $cartAmount === '') { + $cartAmount = null; + } + + $areaQuery = AreaQuery::create()->findOneById($colissimo_homedelivery_area_id); + if (null === $areaQuery) { + return null; + } + + $colissimoHomeDeliveryAreaFreeshippingQuery = ColissimoHomeDeliveryAreaFreeshippingQuery::create() + ->filterByAreaId($colissimo_homedelivery_area_id) + ->findOneOrCreate(); + + $colissimoHomeDeliveryAreaFreeshippingQuery + ->setAreaId($colissimo_homedelivery_area_id) + ->setCartAmount($cartAmount) + ->save(); + + } catch (\Exception $e) { + } + + return $this->generateRedirect(URL::getInstance()->absoluteUrl('/admin/module/ColissimoHomeDelivery')); + } + +} diff --git a/local/modules/ColissimoHomeDelivery/Controller/LabelController.php b/local/modules/ColissimoHomeDelivery/Controller/LabelController.php new file mode 100644 index 00000000..0a705b88 --- /dev/null +++ b/local/modules/ColissimoHomeDelivery/Controller/LabelController.php @@ -0,0 +1,68 @@ + + * Date: 04/09/2019 21:51 + */ +namespace ColissimoHomeDelivery\Controller; + +use Thelia\Controller\Admin\BaseAdminController; +use Thelia\Core\Event\PdfEvent; +use Thelia\Core\Event\TheliaEvents; +use Thelia\Log\Tlog; + +class LabelController extends BaseAdminController +{ + const LABEL_DIRECTORY = THELIA_LOCAL_DIR . 'colissimo-label'; + + /** + * [DEPRECATED] Generates the customs invoice. + * /!\ COMPATIBILITY /!\ DO NOT REMOVE + * + * + * @param $orderId + * @param $orderRef + * @return string + * @throws \Exception + */ + public function createCustomsInvoice($orderId, $orderRef) + { + $html = $this->renderRaw( + 'customs-invoice', + array( + 'order_id' => $orderId + ), + $this->getTemplateHelper()->getActivePdfTemplate() + ); + + try { + $pdfEvent = new PdfEvent($html); + + $this->dispatch(TheliaEvents::GENERATE_PDF, $pdfEvent); + + $pdfFileName = self::LABEL_DIRECTORY . DS . $orderRef . '-customs-invoice.pdf'; + + file_put_contents($pdfFileName, $pdfEvent->getPdf()); + + return $pdfFileName; + } catch (\Exception $e) { + Tlog::getInstance()->error( + sprintf( + 'error during generating invoice pdf for order id : %d with message "%s"', + $orderId, + $e->getMessage() + ) + ); + + throw $e; + } + } +} diff --git a/local/modules/ColissimoHomeDelivery/Controller/PriceSliceController.php b/local/modules/ColissimoHomeDelivery/Controller/PriceSliceController.php new file mode 100644 index 00000000..ec8704cf --- /dev/null +++ b/local/modules/ColissimoHomeDelivery/Controller/PriceSliceController.php @@ -0,0 +1,184 @@ +checkAuth([], ['colissimohomedelivery'], AccessManager::UPDATE); + + if (null !== $response) { + return $response; + } + + $this->checkXmlHttpRequest(); + + $responseData = [ + 'success' => false, + 'message' => '', + 'slice' => null + ]; + + $messages = []; + $response = null; + + try { + $requestData = $this->getRequest()->request; + + if (0 !== $id = (int)$requestData->get('id', 0)) { + $slice = ColissimoHomeDeliveryPriceSlicesQuery::create()->findPk($id); + } else { + $slice = new ColissimoHomeDeliveryPriceSlices(); + } + + + if (0 !== $areaId = (int)$requestData->get('area', 0)) { + $slice->setAreaId($areaId); + } else { + $messages[] = $this->getTranslator()->trans( + 'The area is not valid', + [], + ColissimoHomeDelivery::DOMAIN_NAME + ); + } + + $requestPriceMax = $requestData->get('maxPrice', null); + $requestmaxWeight = $requestData->get('maxWeight', null); + + if (empty($requestPriceMax) && empty($requestmaxWeight)) { + $messages[] = $this->getTranslator()->trans( + 'You must specify at least a price max or a weight max value.', + [], + ColissimoHomeDelivery::DOMAIN_NAME + ); + } else { + if (!empty($requestPriceMax)) { + $maxPrice = $this->getFloatVal($requestPriceMax); + if (0 < $maxPrice) { + $slice->setMaxPrice($maxPrice); + } else { + $messages[] = $this->getTranslator()->trans( + 'The price max value is not valid', + [], + ColissimoHomeDelivery::DOMAIN_NAME + ); + } + } else { + $slice->setMaxPrice(null); + } + + if (!empty($requestmaxWeight)) { + $maxWeight = $this->getFloatVal($requestmaxWeight); + if (0 < $maxWeight) { + $slice->setMaxWeight($maxWeight); + } else { + $messages[] = $this->getTranslator()->trans( + 'The weight max value is not valid', + [], + ColissimoHomeDelivery::DOMAIN_NAME + ); + } + } else { + $slice->setMaxWeight(null); + } + } + + + + $price = $this->getFloatVal($requestData->get('shipping', 0)); + if (0 <= $price) { + $slice->setShipping($price); + } else { + $messages[] = $this->getTranslator()->trans( + 'The price value is not valid', + [], + ColissimoHomeDelivery::DOMAIN_NAME + ); + } + + if (0 === count($messages)) { + $slice->save(); + $messages[] = $this->getTranslator()->trans( + 'Your slice has been saved', + [], + ColissimoHomeDelivery::DOMAIN_NAME + ); + + $responseData['success'] = true; + $responseData['slice'] = $slice->toArray(TableMap::TYPE_STUDLYPHPNAME); + } + } catch (\Exception $e) { + $message[] = $e->getMessage(); + } + + $responseData['message'] = $messages; + + return $this->jsonResponse(json_encode($responseData)); + } + + public function deletePriceSliceAction() + { + $response = $this->checkAuth([], ['colissimohomedelivery'], AccessManager::DELETE); + + if (null !== $response) { + return $response; + } + + $this->checkXmlHttpRequest(); + + $responseData = [ + 'success' => false, + 'message' => '', + 'slice' => null + ]; + + $response = null; + + try { + $requestData = $this->getRequest()->request; + + if (0 !== $id = (int)$requestData->get('id', 0)) { + $priceSlice = ColissimoHomeDeliveryPriceSlicesQuery::create()->findPk($id); + $priceSlice->delete(); + $responseData['success'] = true; + } else { + $responseData['message'] = $this->getTranslator()->trans( + 'The slice has not been deleted', + [], + ColissimoHomeDelivery::DOMAIN_NAME + ); + } + } catch (\Exception $e) { + $responseData['message'] = $e->getMessage(); + } + + return $this->jsonResponse(json_encode($responseData)); + } +} \ No newline at end of file diff --git a/local/modules/ColissimoHomeDelivery/EventListeners/APIListener.php b/local/modules/ColissimoHomeDelivery/EventListeners/APIListener.php new file mode 100644 index 00000000..295ceb55 --- /dev/null +++ b/local/modules/ColissimoHomeDelivery/EventListeners/APIListener.php @@ -0,0 +1,99 @@ +container = $container; + } + + public function getDeliveryModuleOptions(DeliveryModuleOptionEvent $deliveryModuleOptionEvent) + { + if ($deliveryModuleOptionEvent->getModule()->getId() !== ColissimoHomeDelivery::getModuleId()) { + return ; + } + + $isValid = true; + $postage = null; + $postageTax = null; + + try { + $module = new ColissimoHomeDelivery(); + $country = $deliveryModuleOptionEvent->getCountry(); + + if (empty($module->getAllAreasForCountry($country))) { + throw new DeliveryException(Translator::getInstance()->trans("Your delivery country is not covered by Colissimo")); + } + + $countryAreas = $country->getCountryAreas(); + $areasArray = []; + + /** @var CountryArea $countryArea */ + foreach ($countryAreas as $countryArea) { + $areasArray[] = $countryArea->getAreaId(); + } + + $postage = $module->getMinPostage( + $areasArray, + $deliveryModuleOptionEvent->getCart()->getWeight(), + $deliveryModuleOptionEvent->getCart()->getTaxedAmount($country) + ); + + $postageTax = 0; //TODO + } catch (\Exception $exception) { + $isValid = false; + } + + $minimumDeliveryDate = ''; // TODO (calculate delivery date from day of order) + $maximumDeliveryDate = ''; // TODO (calculate delivery date from day of order + + /** @var DeliveryModuleOption $deliveryModuleOption */ + $deliveryModuleOption = ($this->container->get('open_api.model.factory'))->buildModel('DeliveryModuleOption'); + $deliveryModuleOption + ->setCode('ColissimoHomeDelivery') + ->setValid($isValid) + ->setTitle('Colissimo Home Delivery') + ->setImage('') + ->setMinimumDeliveryDate($minimumDeliveryDate) + ->setMaximumDeliveryDate($maximumDeliveryDate) + ->setPostage($postage) + ->setPostageTax($postageTax) + ->setPostageUntaxed($postage - $postageTax) + ; + + $deliveryModuleOptionEvent->appendDeliveryModuleOptions($deliveryModuleOption); + } + + public static function getSubscribedEvents() + { + $listenedEvents = []; + + /** Check for old versions of Thelia where the events used by the API didn't exists */ + if (class_exists(DeliveryModuleOptionEvent::class)) { + $listenedEvents[OpenApiEvents::MODULE_DELIVERY_GET_OPTIONS] = array("getDeliveryModuleOptions", 129); + } + + return $listenedEvents; + } +} \ No newline at end of file diff --git a/local/modules/ColissimoHomeDelivery/EventListeners/ShippingNotificationSender.php b/local/modules/ColissimoHomeDelivery/EventListeners/ShippingNotificationSender.php new file mode 100644 index 00000000..a7c3e5cb --- /dev/null +++ b/local/modules/ColissimoHomeDelivery/EventListeners/ShippingNotificationSender.php @@ -0,0 +1,78 @@ + + * Date: 04/09/2019 14:34 + */ +namespace ColissimoHomeDelivery\EventListeners; + +use ColissimoHomeDelivery\ColissimoHomeDelivery; +use Symfony\Component\EventDispatcher\EventSubscriberInterface; +use Thelia\Action\BaseAction; +use Thelia\Core\Event\Order\OrderEvent; +use Thelia\Core\Event\TheliaEvents; +use Thelia\Core\Template\ParserInterface; +use Thelia\Mailer\MailerFactory; +use Thelia\Model\ConfigQuery; + +class ShippingNotificationSender extends BaseAction implements EventSubscriberInterface +{ + /** @var MailerFactory */ + protected $mailer; + /** @var ParserInterface */ + protected $parser; + + public function __construct(ParserInterface $parser, MailerFactory $mailer) + { + $this->parser = $parser; + $this->mailer = $mailer; + } + + /** + * + * @inheritdoc + */ + public static function getSubscribedEvents() + { + return [ + TheliaEvents::ORDER_UPDATE_STATUS => ['sendShippingNotification', 128] + ]; + } + + /** + * @param OrderEvent $event + * @throws \Propel\Runtime\Exception\PropelException + */ + public function sendShippingNotification(OrderEvent $event) + { + if ($event->getOrder()->isSent()) { + $contact_email = ConfigQuery::getStoreEmail(); + + if ($contact_email) { + $order = $event->getOrder(); + $customer = $order->getCustomer(); + + $this->mailer->sendEmailToCustomer( + ColissimoHomeDelivery::CONFIRMATION_MESSAGE_NAME, + $order->getCustomer(), + [ + 'order_id' => $order->getId(), + 'order_ref' => $order->getRef(), + 'customer_id' => $customer->getId(), + 'order_date' => $order->getCreatedAt(), + 'update_date' => $order->getUpdatedAt(), + 'package' => $order->getDeliveryRef() + ] + ); + } + } + } +} diff --git a/local/modules/ColissimoHomeDelivery/Form/ConfigurationForm.php b/local/modules/ColissimoHomeDelivery/Form/ConfigurationForm.php new file mode 100644 index 00000000..d16b4039 --- /dev/null +++ b/local/modules/ColissimoHomeDelivery/Form/ConfigurationForm.php @@ -0,0 +1,95 @@ + + * Date: 17/08/2019 12:26 + */ +namespace ColissimoHomeDelivery\Form; + +use ColissimoHomeDelivery\ColissimoHomeDelivery; +use SimpleDhl\SimpleDhl; +use Symfony\Component\Validator\Constraints\NotBlank; +use Thelia\Form\BaseForm; + +class ConfigurationForm extends BaseForm +{ + protected function buildForm() + { + $this->formBuilder + ->add( + ColissimoHomeDelivery::COLISSIMO_USERNAME, + 'text', + [ + 'constraints' => [ + new NotBlank(), + ], + 'label' => $this->translator->trans('Colissimo username', [], ColissimoHomeDelivery::DOMAIN_NAME), + 'label_attr' => [ + 'help' => $this->translator->trans( + 'Nom d\'utilisateur Colissimo. C\'est l\'identifiants qui vous permet d’accéder à votre espace client à l\'adresse https://www.colissimo.fr/entreprise', + [], + ColissimoHomeDelivery::DOMAIN_NAME + ) + ] + ] + ) + ->add( + ColissimoHomeDelivery::COLISSIMO_PASSWORD, + 'text', + [ + 'constraints' => [ + new NotBlank(), + ], + 'label' => $this->translator->trans('Colissimo password', [], ColissimoHomeDelivery::DOMAIN_NAME), + 'label_attr' => [ + 'help' => $this->translator->trans( + 'Le mot de passe qui vous permet d’accéder à votre espace client à l\'adresse https://www.colissimo.fr/entreprise', + [], + ColissimoHomeDelivery::DOMAIN_NAME + ) + ] + ] + ) + ->add( + ColissimoHomeDelivery::AFFRANCHISSEMENT_ENDPOINT_URL, + 'url', + [ + 'constraints' => [ + new NotBlank(), + ], + 'label' => $this->translator->trans('Endpoint du web service d\'affranchissement', [], ColissimoHomeDelivery::DOMAIN_NAME), + 'label_attr' => [ + 'help' => $this->translator->trans( + 'Indiquez le endpoint de base à utiliser, par exemple https://domain.tld/transactionaldata/api/v1', + [], + ColissimoHomeDelivery::DOMAIN_NAME + ) + ] + ] + ) + ->add( + ColissimoHomeDelivery::ACTIVATE_DETAILED_DEBUG, + 'checkbox', + [ + 'required' => false, + 'label' => $this->translator->trans('Activer les logs détaillés', [], ColissimoHomeDelivery::DOMAIN_NAME), + 'label_attr' => [ + 'help' => $this->translator->trans( + 'Si cette case est cochée, le texte complet des requêtes et des réponses figurera dans le log Thelia', + [], + ColissimoHomeDelivery::DOMAIN_NAME + ) + ] + ] + ) + ; + } +} diff --git a/local/modules/ColissimoHomeDelivery/Form/FreeShippingForm.php b/local/modules/ColissimoHomeDelivery/Form/FreeShippingForm.php new file mode 100644 index 00000000..47f35532 --- /dev/null +++ b/local/modules/ColissimoHomeDelivery/Form/FreeShippingForm.php @@ -0,0 +1,88 @@ +. */ +/* */ +/*************************************************************************************/ + +namespace ColissimoHomeDelivery\Form; + +use ColissimoHomeDelivery\ColissimoHomeDelivery; +use ColissimoHomeDelivery\Model\Base\ColissimoHomeDeliveryFreeshippingQuery; +use Symfony\Component\Form\Extension\Core\Type\CheckboxType; +use Symfony\Component\Form\Extension\Core\Type\IntegerType; +use Symfony\Component\Form\Extension\Core\Type\NumberType; +use Thelia\Core\Translation\Translator; +use Thelia\Form\BaseForm; + +class FreeShippingForm extends BaseForm +{ + /** + * + * in this function you add all the fields you need for your Form. + * Form this you have to call add method on $this->formBuilder attribute : + * + * $this->formBuilder->add("name", "text") + * ->add("email", "email", array( + * "attr" => array( + * "class" => "field" + * ), + * "label" => "email", + * "constraints" => array( + * new \Symfony\Component\Validator\Constraints\NotBlank() + * ) + * ) + * ) + * ->add('age', 'integer'); + * + * @return null + */ + protected function buildForm() + { + $this->formBuilder + ->add( + 'freeshipping', + CheckboxType::class, + [ + 'label' => Translator::getInstance()->trans("Activate free shipping: ", [], ColissimoHomeDelivery::DOMAIN_NAME) + ] + ) + ->add( + 'freeshipping_from', + NumberType::class, + [ + 'required' => false, + 'label' => Translator::getInstance()->trans("Free shipping from: ", [], ColissimoHomeDelivery::DOMAIN_NAME), + 'data' => ColissimoHomeDeliveryFreeshippingQuery::create()->findOneById(1)->getFreeshippingFrom(), + 'scale' => 2, + ] + ) + + ; + } + + /** + * @return string the name of you form. This name must be unique + */ + public function getName() + { + return "colissimohomedeliveryfreeshipping"; + } + +} \ No newline at end of file diff --git a/local/modules/ColissimoHomeDelivery/Hook/HookManager.php b/local/modules/ColissimoHomeDelivery/Hook/HookManager.php new file mode 100644 index 00000000..1dcc886a --- /dev/null +++ b/local/modules/ColissimoHomeDelivery/Hook/HookManager.php @@ -0,0 +1,65 @@ + + * Date: 17/08/2019 14:34 + */ +namespace ColissimoHomeDelivery\Hook; + +use ColissimoHomeDelivery\ColissimoHomeDelivery; +use ColissimoHomeDelivery\Model\ColissimowsLabelQuery; +use Thelia\Core\Event\Hook\HookRenderBlockEvent; +use Thelia\Core\Event\Hook\HookRenderEvent; +use Thelia\Core\Hook\BaseHook; +use Thelia\Model\ModuleConfig; +use Thelia\Model\ModuleConfigQuery; +use Thelia\Tools\URL; + +class HookManager extends BaseHook +{ + public function onMainHeadBottom(HookRenderEvent $event) + { + $content = $this->addCSS('assets/css/styles.css'); + $event->add($content); + } + + public function onOrderDeliveryExtra(HookRenderEvent $event) + { + $content = $this->render('avec-signature.html', $event->getArguments()); + $event->add($content); + } + + public function onModuleConfigure(HookRenderEvent $event) + { + $vars = [ ]; + + if (null !== $params = ModuleConfigQuery::create()->findByModuleId(ColissimoHomeDelivery::getModuleId())) { + + /** @var ModuleConfig $param */ + foreach ($params as $param) { + $vars[ $param->getName() ] = $param->getValue(); + } + } + + $event->add( + $this->render( + 'module_configuration.html', + $vars + ) + ); + } + + public function onModuleConfigJs(HookRenderEvent $event) + { + $event->add($this->render('module-config-js.html')); + } + +} diff --git a/local/modules/ColissimoHomeDelivery/I18n/backOffice/default/en_US.php b/local/modules/ColissimoHomeDelivery/I18n/backOffice/default/en_US.php new file mode 100644 index 00000000..f27a4005 --- /dev/null +++ b/local/modules/ColissimoHomeDelivery/I18n/backOffice/default/en_US.php @@ -0,0 +1,29 @@ + 'Actions', + 'Activate free shipping from (€) :' => 'Activate free shipping from (€) :', + 'Activate total free shipping ' => 'Activate total free shipping ', + 'Add this price slice' => 'Add this price slice', + 'Area : ' => 'Area : ', + 'Colissimo Web service configuration' => 'Colissimo Web service configuration', + 'Configuration' => 'Configuration', + 'Configuration du service' => 'Configuration du service', + 'If a cart matches multiple slices, it will take the last slice following that order.' => 'If a cart matches multiple slices, it will take the last slice following that order.', + 'If you don\'t specify a cart price in a slice, it will have priority over the other slices with the same weight.' => 'If you don\'t specify a cart price in a slice, it will have priority over the other slices with the same weight.', + 'If you don\'t specify a cart weight in a slice, it will have priority over the slices with weight.' => 'If you don\'t specify a cart weight in a slice, it will have priority over the slices with weight.', + 'If you specify both, the cart will require to have a lower weight AND a lower price in order to match the slice.' => 'If you specify both, the cart will require to have a lower weight AND a lower price in order to match the slice.', + 'Message' => 'Message', + 'Or activate free shipping from (€) :' => 'Or activate free shipping from (€) :', + 'Price slices (Dom)' => 'Price slices (Dom)', + 'Price slices for domicile delivery' => 'Price slices for domicile delivery', + 'Save' => 'Save', + 'Save this price slice' => 'Save this price slice', + 'Shipping Price ($)' => 'Shipping Price ($)', + 'The slices are ordered by maximum cart weight then by maximum cart price.' => 'The slices are ordered by maximum cart weight then by maximum cart price.', + 'Untaxed Price up to ... ($)' => 'Untaxed Price up to ... ($)', + 'Weight up to ... kg' => 'Weight up to ... kg', + 'You can create price slices by specifying a maximum cart weight and/or a maximum cart price.' => 'You can create price slices by specifying a maximum cart weight and/or a maximum cart price.', + 'You should first attribute shipping zones to the modules: ' => 'You should first attribute shipping zones to the modules: ', + 'manage shipping zones' => 'manage shipping zones', +); diff --git a/local/modules/ColissimoHomeDelivery/I18n/backOffice/default/fr_FR.php b/local/modules/ColissimoHomeDelivery/I18n/backOffice/default/fr_FR.php new file mode 100644 index 00000000..9e2edd72 --- /dev/null +++ b/local/modules/ColissimoHomeDelivery/I18n/backOffice/default/fr_FR.php @@ -0,0 +1,30 @@ + 'Actions', + 'Activate free shipping from (€) :' => 'Activer la livraison gratuite à partir de (€) :', + 'Activate total free shipping ' => 'Activer la livraison gratuite totale', + 'Add this price slice' => 'Ajouter cette tranche de prix', + 'Area : ' => 'Zone :', + 'Colissimo Web service configuration' => 'Configuration Colissimo Affranchissement', + 'Configuration' => 'Configuration', + 'Configuration du service' => 'Configuration du service', + 'Delete this price slice' => 'Supprimer cette tranche de prix', + 'If a cart matches multiple slices, it will take the last slice following that order.' => 'Si un panier correspond à plusieurs tranches, la dernière tranche sera prise en compte selon cet ordre.', + 'If you don\'t specify a cart price in a slice, it will have priority over the other slices with the same weight.' => 'Si vous ne renseignez pas de prix de panier max dans une tranche, elle aura la priorité sur les autres tranches ayant le même poids.', + 'If you don\'t specify a cart weight in a slice, it will have priority over the slices with weight.' => 'Si vous ne renseignez pas de poids max dans une tranche, elle aura la priorité sur les tranches ayant un poids.', + 'If you specify both, the cart will require to have a lower weight AND a lower price in order to match the slice.' => 'Si vous renseignez les deux, le panier devra avoir à la fois un poids inférieur ET un prix inférieur pour correspondre à cette tranche.', + 'Message' => 'Message', + 'Or activate free shipping from (€) :' => 'Ou activer la livraison gratuite à partir de (€) :', + 'Price slices (Dom)' => 'Tranches de prix (Domicile)', + 'Price slices for domicile delivery' => 'Tranches de prix pour la livraison à domicile', + 'Save' => 'Enregistrer', + 'Save this price slice' => 'Sauvegarder cette tranche de prix', + 'Shipping Price ($)' => 'Frais de livraison', + 'The slices are ordered by maximum cart weight then by maximum cart price.' => 'Les tranches sont triés pour poids de panier max puis par prix de panier max.', + 'Untaxed Price up to ... ($)' => 'Prix (HT) jusqu\'à :', + 'Weight up to ... kg' => 'Poids (kg) jusqu\'à :', + 'You can create price slices by specifying a maximum cart weight and/or a maximum cart price.' => 'Vous pouvez créer des tranches de prix pour les frais de port en spécifiant un poids de panier maximum et/ou un prix de panier maximum.', + 'You should first attribute shipping zones to the modules: ' => 'Vous devez tout d\'abord ajouter des zones de livraisons au module', + 'manage shipping zones' => 'Gérer les zones de livraison', +); diff --git a/local/modules/ColissimoHomeDelivery/I18n/email/default/en_US.php b/local/modules/ColissimoHomeDelivery/I18n/email/default/en_US.php new file mode 100644 index 00000000..6ae5d8e4 --- /dev/null +++ b/local/modules/ColissimoHomeDelivery/I18n/email/default/en_US.php @@ -0,0 +1,15 @@ +Click here to track your shipment. You can also enter the tracking number on https://www.laposte.fr/outils/suivre-vos-envois' => 'Click here to track your shipment. You can also enter the tracking number on https://www.laposte.fr/outils/suivre-vos-envois', + 'Dear Mr. ' => 'Dear Mr. ', + 'Dear Ms. ' => 'Dear Ms. ', + 'Please display this message in HTML' => 'Please display this message in HTML', + 'Thank you for your shopping with us and hope to see you soon on www.yourshop.com' => 'Thank you for your shopping with us and hope to see you soon on www.yourshop.com', + 'We are pleased to inform you that your order number' => 'We are pleased to inform you that your order number', + 'Your on-line store Manager' => 'Your on-line store Manager', + 'Your order confirmation Nº %ref' => 'Your order confirmation Nº %ref', + 'Your shop' => 'Your shop', + 'has been shipped on' => 'has been shipped on', + 'with the tracking number' => 'with the tracking number', +); diff --git a/local/modules/ColissimoHomeDelivery/I18n/email/default/fr_FR.php b/local/modules/ColissimoHomeDelivery/I18n/email/default/fr_FR.php new file mode 100644 index 00000000..51739960 --- /dev/null +++ b/local/modules/ColissimoHomeDelivery/I18n/email/default/fr_FR.php @@ -0,0 +1,15 @@ +Click here to track your shipment. You can also enter the tracking number on https://www.laposte.fr/outils/suivre-vos-envois' => 'Cliquez ici pour suivre l\'acheminement. Vous pouvez aussi entrer le numéro de suivi sur https://www.laposte.fr/outils/suivre-vos-envois', + 'Dear Mr. ' => 'Cher Mr', + 'Dear Ms. ' => 'Cher Mme', + 'Please display this message in HTML' => 'Afficher ce message en HTML', + 'Thank you for your shopping with us and hope to see you soon on www.yourshop.com' => 'Nous vous remercions pour votre achat et espérons vous revoir très vite sur www.votreboutique.com', + 'We are pleased to inform you that your order number' => 'Nous sommes heureux de vous informer que votre commande N°', + 'Your on-line store Manager' => 'Nom de personne chargé de la communication', + 'Your order confirmation Nº %ref' => 'Votre commande N° %ref', + 'Your shop' => 'Votre boutique', + 'has been shipped on' => 'a été envoyé le', + 'with the tracking number' => 'avec le numéro de suivi', +); diff --git a/local/modules/ColissimoHomeDelivery/I18n/en_US.php b/local/modules/ColissimoHomeDelivery/I18n/en_US.php new file mode 100644 index 00000000..9905201c --- /dev/null +++ b/local/modules/ColissimoHomeDelivery/I18n/en_US.php @@ -0,0 +1,22 @@ + 'Activate free shipping: ', + 'Activer les logs détaillés' => 'Activate detailed logs', + 'Colissimo password' => 'Colissimo password', + 'Colissimo username' => 'Colissimo username', + 'ColissimoHomeDelivery configuration' => 'ColissimoHomeDelivery configuration', + 'Endpoint du web service d\'affranchissement' => 'Endpoint', + 'Free shipping from: ' => 'Free shipping from: ', + 'Indiquez le endpoint de base à utiliser, par exemple https://domain.tld/transactionaldata/api/v1' => 'Write the base endpoint to use, e.g. : https://domain.tld/transactionaldata/api/v1', + 'Le mot de passe qui vous permet d’accéder à votre espace client à l\'adresse https://www.colissimo.fr/entreprise' => 'The password that allows you to connect to your customer page at https://www.colissimo.fr/entreprise', + 'Nom d\'utilisateur Colissimo. C\'est l\'identifiants qui vous permet d’accéder à votre espace client à l\'adresse https://www.colissimo.fr/entreprise' => 'Colissimo username. These are the IDs that allows you to connect to your customer page at https://www.colissimo.fr/entreprise', + 'Si cette case est cochée, le texte complet des requêtes et des réponses figurera dans le log Thelia' => 'If this is checked, all request and response texts will be written in the Thelia log', + 'The area is not valid' => 'The area is not valid', + 'The price max value is not valid' => 'The price max value is not valid', + 'The price value is not valid' => 'The price value is not valid', + 'The slice has not been deleted' => 'The slice has not been deleted', + 'The weight max value is not valid' => 'The weight max value is not valid', + 'You must specify at least a price max or a weight max value.' => 'You must specify at least a price max or a weight max value.', + 'Your slice has been saved' => 'Your slice has been saved', +); diff --git a/local/modules/ColissimoHomeDelivery/I18n/fr_FR.php b/local/modules/ColissimoHomeDelivery/I18n/fr_FR.php new file mode 100644 index 00000000..5be7d689 --- /dev/null +++ b/local/modules/ColissimoHomeDelivery/I18n/fr_FR.php @@ -0,0 +1,22 @@ + 'Activer les frais de ports gratuits', + 'Activer les logs détaillés' => 'Activer les logs détaillés', + 'Colissimo password' => 'Mot de passe Colissimo', + 'Colissimo username' => 'Nom d\'utilisateur Colissimo', + 'ColissimoHomeDelivery configuration' => 'Configuration Colissimo Affranchissement', + 'Endpoint du web service d\'affranchissement' => 'Endpoint du web service d\'affranchissement', + 'Free shipping from: ' => 'Livraison gratuite à partir de :', + 'Indiquez le endpoint de base à utiliser, par exemple https://domain.tld/transactionaldata/api/v1' => 'Indiquez le endpoint de base à utiliser, par exemple https://domain.tld/transactionaldata/api/v1', + 'Le mot de passe qui vous permet d’accéder à votre espace client à l\'adresse https://www.colissimo.fr/entreprise' => 'Le mot de passe qui vous permet d’accéder à votre espace client à l\'adresse https://www.colissimo.fr/entreprise', + 'Nom d\'utilisateur Colissimo. C\'est l\'identifiants qui vous permet d’accéder à votre espace client à l\'adresse https://www.colissimo.fr/entreprise' => 'Nom d\'utilisateur Colissimo. C\'est l\'identifiants qui vous permet d’accéder à votre espace client à l\'adresse https://www.colissimo.fr/entreprise', + 'Si cette case est cochée, le texte complet des requêtes et des réponses figurera dans le log Thelia' => 'Si cette case est cochée, le texte complet des requêtes et des réponses figurera dans le log Thelia', + 'The area is not valid' => 'La zone n\'est pas valide', + 'The price max value is not valid' => 'La valeur du prix max. n\'est pas valide', + 'The price value is not valid' => 'La valeur du prix n\'est pas valide', + 'The slice has not been deleted' => 'La tranche de prix n\'a pas été supprimée', + 'The weight max value is not valid' => 'La valeur du poids max. n\'est pas valide', + 'You must specify at least a price max or a weight max value.' => 'Vous devez spécifier au moins un prix max. ou un poids max.', + 'Your slice has been saved' => 'La tranche de prix a été sauvegardée', +); diff --git a/local/modules/ColissimoHomeDelivery/I18n/frontOffice/default/fr_FR.php b/local/modules/ColissimoHomeDelivery/I18n/frontOffice/default/fr_FR.php new file mode 100644 index 00000000..64465a43 --- /dev/null +++ b/local/modules/ColissimoHomeDelivery/I18n/frontOffice/default/fr_FR.php @@ -0,0 +1,6 @@ + 'Je souhaite bénéficier d\'une remise avec signature (coût forfaitaire de %surcout %unite)', + 'Titre Avec signature' => 'Supplément', +); diff --git a/local/modules/ColissimoHomeDelivery/I18n/pdf/default/en_US.php b/local/modules/ColissimoHomeDelivery/I18n/pdf/default/en_US.php new file mode 100644 index 00000000..03e2992d --- /dev/null +++ b/local/modules/ColissimoHomeDelivery/I18n/pdf/default/en_US.php @@ -0,0 +1,23 @@ + 'Comm. code', + 'Country' => 'Country', + 'Engraving ' => 'Engraving ', + 'Font ' => 'Font ', + 'Free samples ' => 'Free samples ', + 'Full Description of Goods' => 'Full Description of Goods', + 'Position ' => 'Position ', + 'Quantity' => 'Quantity', + 'Sender\'s name' => 'Sender\'s name', + 'Shop - Email : {$store_email} - Phone : {$store_phone}' => 'Shop - Email : {$store_email} - Phone : {$store_phone}', + 'Style ' => 'Style ', + 'Subtotal value' => 'Subtotal value', + 'Thelia V2' => 'Thelia V2', + 'Unit net weight' => 'Unit net weight', + 'Unit value' => 'Unit value', + 'Your gift ' => 'Your gift ', + 'Your text ' => 'Your text ', + '{$store_description} - Legal numbers (ex: SIRET)' => '{$store_description} - Legal numbers (ex: SIRET)', + '{$store_name} - {$store_address1} - Phone : {$store_phone}' => '{$store_name} - {$store_address1} - Phone : {$store_phone}', +); diff --git a/local/modules/ColissimoHomeDelivery/I18n/pdf/default/fr_FR.php b/local/modules/ColissimoHomeDelivery/I18n/pdf/default/fr_FR.php new file mode 100644 index 00000000..bf4973e5 --- /dev/null +++ b/local/modules/ColissimoHomeDelivery/I18n/pdf/default/fr_FR.php @@ -0,0 +1,23 @@ + 'Code comm.', + 'Country' => 'Pays', + 'Engraving ' => 'Gravure', + 'Font ' => 'Police de caractère', + 'Free samples ' => 'Échantillons gratuits ', + 'Full Description of Goods' => 'Description complète des biens', + 'Position ' => 'Position', + 'Quantity' => 'Quantité', + 'Sender\'s name' => 'Nom de l\'envoyeur', + 'Shop - Email : {$store_email} - Phone : {$store_phone}' => 'Magasin - Email : {$store_email} - Téléphone : {$store_phone}', + 'Style ' => 'Style', + 'Subtotal value' => 'Sous-total', + 'Thelia V2' => 'Thelia V2', + 'Unit net weight' => 'Poids net unitaire', + 'Unit value' => 'Valeur unitaire', + 'Your gift ' => 'Votre cadeau', + 'Your text ' => 'Votre texte', + '{$store_description} - Legal numbers (ex: SIRET)' => '{$store_description} - Numéros légaux (ex: SIRET)', + '{$store_name} - {$store_address1} - Phone : {$store_phone}' => '{$store_name} - {$store_address1} - Téléphone : {$store_phone}', +); diff --git a/local/modules/ColissimoHomeDelivery/Loop/ColissimoHomeDeliveryAreaFreeShippingLoop.php b/local/modules/ColissimoHomeDelivery/Loop/ColissimoHomeDeliveryAreaFreeShippingLoop.php new file mode 100644 index 00000000..a476e3fc --- /dev/null +++ b/local/modules/ColissimoHomeDelivery/Loop/ColissimoHomeDeliveryAreaFreeShippingLoop.php @@ -0,0 +1,54 @@ +getAreaId(); + + $search = ColissimoHomeDeliveryAreaFreeshippingQuery::create(); + + if (null !== $areaId) { + $search->filterByAreaId($areaId); + } + + return $search; + } + + public function parseResults(LoopResult $loopResult) + { + /** @var ColissimoHomeDeliveryAreaFreeshipping $mode */ + foreach ($loopResult->getResultDataCollection() as $mode) { + $loopResultRow = new LoopResultRow($mode); + $loopResultRow + ->set("ID", $mode->getId()) + ->set("AREA_ID", $mode->getAreaId()) + ->set("CART_AMOUNT", $mode->getCartAmount()); + $loopResult->addRow($loopResultRow); + } + return $loopResult; + } +} \ No newline at end of file diff --git a/local/modules/ColissimoHomeDelivery/Loop/ColissimoHomeDeliveryFreeShippingLoop.php b/local/modules/ColissimoHomeDelivery/Loop/ColissimoHomeDeliveryFreeShippingLoop.php new file mode 100644 index 00000000..5792597f --- /dev/null +++ b/local/modules/ColissimoHomeDelivery/Loop/ColissimoHomeDeliveryFreeShippingLoop.php @@ -0,0 +1,51 @@ +findOneById(1)){ + $isFreeShippingActive = new ColissimoHomeDeliveryFreeshipping(); + $isFreeShippingActive->setId(1); + $isFreeShippingActive->setActive(0); + $isFreeShippingActive->save(); + } + + return ColissimoHomeDeliveryFreeshippingQuery::create()->filterById(1); + } + + public function parseResults(LoopResult $loopResult) + { + /** @var ColissimoHomeDeliveryFreeshipping $freeshipping */ + foreach ($loopResult->getResultDataCollection() as $freeshipping) { + $loopResultRow = new LoopResultRow($freeshipping); + $loopResultRow + ->set('FREESHIPPING_ACTIVE', $freeshipping->getActive()) + ->set('FREESHIPPING_FROM', $freeshipping->getFreeshippingFrom()); + $loopResult->addRow($loopResultRow); + } + return $loopResult; + } + +} \ No newline at end of file diff --git a/local/modules/ColissimoHomeDelivery/Loop/PriceSlicesLoop.php b/local/modules/ColissimoHomeDelivery/Loop/PriceSlicesLoop.php new file mode 100644 index 00000000..6f2677cb --- /dev/null +++ b/local/modules/ColissimoHomeDelivery/Loop/PriceSlicesLoop.php @@ -0,0 +1,56 @@ +getAreaId(); + + $areaPrices = ColissimoHomeDeliveryPriceSlicesQuery::create() + ->filterByAreaId($areaId) + ->orderByMaxWeight() + ->orderByMaxPrice() + ; + + return $areaPrices; + } + + public function parseResults(LoopResult $loopResult) + { + /** @var \ColissimoHomeDelivery\Model\ColissimoHomeDeliveryPriceSlices $priceSlice */ + foreach ($loopResult->getResultDataCollection() as $priceSlice) { + $loopResultRow = new LoopResultRow($priceSlice); + $loopResultRow + ->set('SLICE_ID', $priceSlice->getId()) + ->set('MAX_WEIGHT', $priceSlice->getMaxWeight()) + ->set('MAX_PRICE', $priceSlice->getMaxPrice()) + ->set('SHIPPING', $priceSlice->getShipping()) + ; + $loopResult->addRow($loopResultRow); + } + return $loopResult; + } +} \ No newline at end of file diff --git a/local/modules/ColissimoHomeDelivery/Model/Base/ColissimoHomeDeliveryAreaFreeshipping.php b/local/modules/ColissimoHomeDelivery/Model/Base/ColissimoHomeDeliveryAreaFreeshipping.php new file mode 100644 index 00000000..b3c06046 --- /dev/null +++ b/local/modules/ColissimoHomeDelivery/Model/Base/ColissimoHomeDeliveryAreaFreeshipping.php @@ -0,0 +1,1261 @@ +cart_amount = '0.00'; + } + + /** + * Initializes internal state of ColissimoHomeDelivery\Model\Base\ColissimoHomeDeliveryAreaFreeshipping object. + * @see applyDefaults() + */ + public function __construct() + { + $this->applyDefaultValues(); + } + + /** + * Returns whether the object has been modified. + * + * @return boolean True if the object has been modified. + */ + public function isModified() + { + return !!$this->modifiedColumns; + } + + /** + * Has specified column been modified? + * + * @param string $col column fully qualified name (TableMap::TYPE_COLNAME), e.g. Book::AUTHOR_ID + * @return boolean True if $col has been modified. + */ + public function isColumnModified($col) + { + return $this->modifiedColumns && isset($this->modifiedColumns[$col]); + } + + /** + * Get the columns that have been modified in this object. + * @return array A unique list of the modified column names for this object. + */ + public function getModifiedColumns() + { + return $this->modifiedColumns ? array_keys($this->modifiedColumns) : []; + } + + /** + * Returns whether the object has ever been saved. This will + * be false, if the object was retrieved from storage or was created + * and then saved. + * + * @return boolean true, if the object has never been persisted. + */ + public function isNew() + { + return $this->new; + } + + /** + * Setter for the isNew attribute. This method will be called + * by Propel-generated children and objects. + * + * @param boolean $b the state of the object. + */ + public function setNew($b) + { + $this->new = (Boolean) $b; + } + + /** + * Whether this object has been deleted. + * @return boolean The deleted state of this object. + */ + public function isDeleted() + { + return $this->deleted; + } + + /** + * Specify whether this object has been deleted. + * @param boolean $b The deleted state of this object. + * @return void + */ + public function setDeleted($b) + { + $this->deleted = (Boolean) $b; + } + + /** + * Sets the modified state for the object to be false. + * @param string $col If supplied, only the specified column is reset. + * @return void + */ + public function resetModified($col = null) + { + if (null !== $col) { + if (isset($this->modifiedColumns[$col])) { + unset($this->modifiedColumns[$col]); + } + } else { + $this->modifiedColumns = array(); + } + } + + /** + * Compares this with another ColissimoHomeDeliveryAreaFreeshipping instance. If + * obj is an instance of ColissimoHomeDeliveryAreaFreeshipping, delegates to + * equals(ColissimoHomeDeliveryAreaFreeshipping). Otherwise, returns false. + * + * @param mixed $obj The object to compare to. + * @return boolean Whether equal to the object specified. + */ + public function equals($obj) + { + $thisclazz = get_class($this); + if (!is_object($obj) || !($obj instanceof $thisclazz)) { + return false; + } + + if ($this === $obj) { + return true; + } + + if (null === $this->getPrimaryKey() + || null === $obj->getPrimaryKey()) { + return false; + } + + return $this->getPrimaryKey() === $obj->getPrimaryKey(); + } + + /** + * If the primary key is not null, return the hashcode of the + * primary key. Otherwise, return the hash code of the object. + * + * @return int Hashcode + */ + public function hashCode() + { + if (null !== $this->getPrimaryKey()) { + return crc32(serialize($this->getPrimaryKey())); + } + + return crc32(serialize(clone $this)); + } + + /** + * Get the associative array of the virtual columns in this object + * + * @return array + */ + public function getVirtualColumns() + { + return $this->virtualColumns; + } + + /** + * Checks the existence of a virtual column in this object + * + * @param string $name The virtual column name + * @return boolean + */ + public function hasVirtualColumn($name) + { + return array_key_exists($name, $this->virtualColumns); + } + + /** + * Get the value of a virtual column in this object + * + * @param string $name The virtual column name + * @return mixed + * + * @throws PropelException + */ + public function getVirtualColumn($name) + { + if (!$this->hasVirtualColumn($name)) { + throw new PropelException(sprintf('Cannot get value of inexistent virtual column %s.', $name)); + } + + return $this->virtualColumns[$name]; + } + + /** + * Set the value of a virtual column in this object + * + * @param string $name The virtual column name + * @param mixed $value The value to give to the virtual column + * + * @return ColissimoHomeDeliveryAreaFreeshipping The current object, for fluid interface + */ + public function setVirtualColumn($name, $value) + { + $this->virtualColumns[$name] = $value; + + return $this; + } + + /** + * Logs a message using Propel::log(). + * + * @param string $msg + * @param int $priority One of the Propel::LOG_* logging levels + * @return boolean + */ + protected function log($msg, $priority = Propel::LOG_INFO) + { + return Propel::log(get_class($this) . ': ' . $msg, $priority); + } + + /** + * Populate the current object from a string, using a given parser format + * + * $book = new Book(); + * $book->importFrom('JSON', '{"Id":9012,"Title":"Don Juan","ISBN":"0140422161","Price":12.99,"PublisherId":1234,"AuthorId":5678}'); + * + * + * @param mixed $parser A AbstractParser instance, + * or a format name ('XML', 'YAML', 'JSON', 'CSV') + * @param string $data The source data to import from + * + * @return ColissimoHomeDeliveryAreaFreeshipping The current object, for fluid interface + */ + public function importFrom($parser, $data) + { + if (!$parser instanceof AbstractParser) { + $parser = AbstractParser::getParser($parser); + } + + $this->fromArray($parser->toArray($data), TableMap::TYPE_PHPNAME); + + return $this; + } + + /** + * Export the current object properties to a string, using a given parser format + * + * $book = BookQuery::create()->findPk(9012); + * echo $book->exportTo('JSON'); + * => {"Id":9012,"Title":"Don Juan","ISBN":"0140422161","Price":12.99,"PublisherId":1234,"AuthorId":5678}'); + * + * + * @param mixed $parser A AbstractParser instance, or a format name ('XML', 'YAML', 'JSON', 'CSV') + * @param boolean $includeLazyLoadColumns (optional) Whether to include lazy load(ed) columns. Defaults to TRUE. + * @return string The exported data + */ + public function exportTo($parser, $includeLazyLoadColumns = true) + { + if (!$parser instanceof AbstractParser) { + $parser = AbstractParser::getParser($parser); + } + + return $parser->fromArray($this->toArray(TableMap::TYPE_PHPNAME, $includeLazyLoadColumns, array(), true)); + } + + /** + * Clean up internal collections prior to serializing + * Avoids recursive loops that turn into segmentation faults when serializing + */ + public function __sleep() + { + $this->clearAllReferences(); + + return array_keys(get_object_vars($this)); + } + + /** + * Get the [id] column value. + * + * @return int + */ + public function getId() + { + + return $this->id; + } + + /** + * Get the [area_id] column value. + * + * @return int + */ + public function getAreaId() + { + + return $this->area_id; + } + + /** + * Get the [cart_amount] column value. + * + * @return string + */ + public function getCartAmount() + { + + return $this->cart_amount; + } + + /** + * Set the value of [id] column. + * + * @param int $v new value + * @return \ColissimoHomeDelivery\Model\ColissimoHomeDeliveryAreaFreeshipping The current object (for fluent API support) + */ + public function setId($v) + { + if ($v !== null) { + $v = (int) $v; + } + + if ($this->id !== $v) { + $this->id = $v; + $this->modifiedColumns[ColissimoHomeDeliveryAreaFreeshippingTableMap::ID] = true; + } + + + return $this; + } // setId() + + /** + * Set the value of [area_id] column. + * + * @param int $v new value + * @return \ColissimoHomeDelivery\Model\ColissimoHomeDeliveryAreaFreeshipping The current object (for fluent API support) + */ + public function setAreaId($v) + { + if ($v !== null) { + $v = (int) $v; + } + + if ($this->area_id !== $v) { + $this->area_id = $v; + $this->modifiedColumns[ColissimoHomeDeliveryAreaFreeshippingTableMap::AREA_ID] = true; + } + + if ($this->aArea !== null && $this->aArea->getId() !== $v) { + $this->aArea = null; + } + + + return $this; + } // setAreaId() + + /** + * Set the value of [cart_amount] column. + * + * @param string $v new value + * @return \ColissimoHomeDelivery\Model\ColissimoHomeDeliveryAreaFreeshipping The current object (for fluent API support) + */ + public function setCartAmount($v) + { + if ($v !== null) { + $v = (string) $v; + } + + if ($this->cart_amount !== $v) { + $this->cart_amount = $v; + $this->modifiedColumns[ColissimoHomeDeliveryAreaFreeshippingTableMap::CART_AMOUNT] = true; + } + + + return $this; + } // setCartAmount() + + /** + * Indicates whether the columns in this object are only set to default values. + * + * This method can be used in conjunction with isModified() to indicate whether an object is both + * modified _and_ has some values set which are non-default. + * + * @return boolean Whether the columns in this object are only been set with default values. + */ + public function hasOnlyDefaultValues() + { + if ($this->cart_amount !== '0.00') { + return false; + } + + // otherwise, everything was equal, so return TRUE + return true; + } // hasOnlyDefaultValues() + + /** + * Hydrates (populates) the object variables with values from the database resultset. + * + * An offset (0-based "start column") is specified so that objects can be hydrated + * with a subset of the columns in the resultset rows. This is needed, for example, + * for results of JOIN queries where the resultset row includes columns from two or + * more tables. + * + * @param array $row The row returned by DataFetcher->fetch(). + * @param int $startcol 0-based offset column which indicates which restultset column to start with. + * @param boolean $rehydrate Whether this object is being re-hydrated from the database. + * @param string $indexType The index type of $row. Mostly DataFetcher->getIndexType(). + One of the class type constants TableMap::TYPE_PHPNAME, TableMap::TYPE_STUDLYPHPNAME + * TableMap::TYPE_COLNAME, TableMap::TYPE_FIELDNAME, TableMap::TYPE_NUM. + * + * @return int next starting column + * @throws PropelException - Any caught Exception will be rewrapped as a PropelException. + */ + public function hydrate($row, $startcol = 0, $rehydrate = false, $indexType = TableMap::TYPE_NUM) + { + try { + + + $col = $row[TableMap::TYPE_NUM == $indexType ? 0 + $startcol : ColissimoHomeDeliveryAreaFreeshippingTableMap::translateFieldName('Id', TableMap::TYPE_PHPNAME, $indexType)]; + $this->id = (null !== $col) ? (int) $col : null; + + $col = $row[TableMap::TYPE_NUM == $indexType ? 1 + $startcol : ColissimoHomeDeliveryAreaFreeshippingTableMap::translateFieldName('AreaId', TableMap::TYPE_PHPNAME, $indexType)]; + $this->area_id = (null !== $col) ? (int) $col : null; + + $col = $row[TableMap::TYPE_NUM == $indexType ? 2 + $startcol : ColissimoHomeDeliveryAreaFreeshippingTableMap::translateFieldName('CartAmount', TableMap::TYPE_PHPNAME, $indexType)]; + $this->cart_amount = (null !== $col) ? (string) $col : null; + $this->resetModified(); + + $this->setNew(false); + + if ($rehydrate) { + $this->ensureConsistency(); + } + + return $startcol + 3; // 3 = ColissimoHomeDeliveryAreaFreeshippingTableMap::NUM_HYDRATE_COLUMNS. + + } catch (Exception $e) { + throw new PropelException("Error populating \ColissimoHomeDelivery\Model\ColissimoHomeDeliveryAreaFreeshipping object", 0, $e); + } + } + + /** + * Checks and repairs the internal consistency of the object. + * + * This method is executed after an already-instantiated object is re-hydrated + * from the database. It exists to check any foreign keys to make sure that + * the objects related to the current object are correct based on foreign key. + * + * You can override this method in the stub class, but you should always invoke + * the base method from the overridden method (i.e. parent::ensureConsistency()), + * in case your model changes. + * + * @throws PropelException + */ + public function ensureConsistency() + { + if ($this->aArea !== null && $this->area_id !== $this->aArea->getId()) { + $this->aArea = null; + } + } // ensureConsistency + + /** + * Reloads this object from datastore based on primary key and (optionally) resets all associated objects. + * + * This will only work if the object has been saved and has a valid primary key set. + * + * @param boolean $deep (optional) Whether to also de-associated any related objects. + * @param ConnectionInterface $con (optional) The ConnectionInterface connection to use. + * @return void + * @throws PropelException - if this object is deleted, unsaved or doesn't have pk match in db + */ + public function reload($deep = false, ConnectionInterface $con = null) + { + if ($this->isDeleted()) { + throw new PropelException("Cannot reload a deleted object."); + } + + if ($this->isNew()) { + throw new PropelException("Cannot reload an unsaved object."); + } + + if ($con === null) { + $con = Propel::getServiceContainer()->getReadConnection(ColissimoHomeDeliveryAreaFreeshippingTableMap::DATABASE_NAME); + } + + // We don't need to alter the object instance pool; we're just modifying this instance + // already in the pool. + + $dataFetcher = ChildColissimoHomeDeliveryAreaFreeshippingQuery::create(null, $this->buildPkeyCriteria())->setFormatter(ModelCriteria::FORMAT_STATEMENT)->find($con); + $row = $dataFetcher->fetch(); + $dataFetcher->close(); + if (!$row) { + throw new PropelException('Cannot find matching row in the database to reload object values.'); + } + $this->hydrate($row, 0, true, $dataFetcher->getIndexType()); // rehydrate + + if ($deep) { // also de-associate any related objects? + + $this->aArea = null; + } // if (deep) + } + + /** + * Removes this object from datastore and sets delete attribute. + * + * @param ConnectionInterface $con + * @return void + * @throws PropelException + * @see ColissimoHomeDeliveryAreaFreeshipping::setDeleted() + * @see ColissimoHomeDeliveryAreaFreeshipping::isDeleted() + */ + public function delete(ConnectionInterface $con = null) + { + if ($this->isDeleted()) { + throw new PropelException("This object has already been deleted."); + } + + if ($con === null) { + $con = Propel::getServiceContainer()->getWriteConnection(ColissimoHomeDeliveryAreaFreeshippingTableMap::DATABASE_NAME); + } + + $con->beginTransaction(); + try { + $deleteQuery = ChildColissimoHomeDeliveryAreaFreeshippingQuery::create() + ->filterByPrimaryKey($this->getPrimaryKey()); + $ret = $this->preDelete($con); + if ($ret) { + $deleteQuery->delete($con); + $this->postDelete($con); + $con->commit(); + $this->setDeleted(true); + } else { + $con->commit(); + } + } catch (Exception $e) { + $con->rollBack(); + throw $e; + } + } + + /** + * Persists this object to the database. + * + * If the object is new, it inserts it; otherwise an update is performed. + * All modified related objects will also be persisted in the doSave() + * method. This method wraps all precipitate database operations in a + * single transaction. + * + * @param ConnectionInterface $con + * @return int The number of rows affected by this insert/update and any referring fk objects' save() operations. + * @throws PropelException + * @see doSave() + */ + public function save(ConnectionInterface $con = null) + { + if ($this->isDeleted()) { + throw new PropelException("You cannot save an object that has been deleted."); + } + + if ($con === null) { + $con = Propel::getServiceContainer()->getWriteConnection(ColissimoHomeDeliveryAreaFreeshippingTableMap::DATABASE_NAME); + } + + $con->beginTransaction(); + $isInsert = $this->isNew(); + try { + $ret = $this->preSave($con); + if ($isInsert) { + $ret = $ret && $this->preInsert($con); + } else { + $ret = $ret && $this->preUpdate($con); + } + if ($ret) { + $affectedRows = $this->doSave($con); + if ($isInsert) { + $this->postInsert($con); + } else { + $this->postUpdate($con); + } + $this->postSave($con); + ColissimoHomeDeliveryAreaFreeshippingTableMap::addInstanceToPool($this); + } else { + $affectedRows = 0; + } + $con->commit(); + + return $affectedRows; + } catch (Exception $e) { + $con->rollBack(); + throw $e; + } + } + + /** + * Performs the work of inserting or updating the row in the database. + * + * If the object is new, it inserts it; otherwise an update is performed. + * All related objects are also updated in this method. + * + * @param ConnectionInterface $con + * @return int The number of rows affected by this insert/update and any referring fk objects' save() operations. + * @throws PropelException + * @see save() + */ + protected function doSave(ConnectionInterface $con) + { + $affectedRows = 0; // initialize var to track total num of affected rows + if (!$this->alreadyInSave) { + $this->alreadyInSave = true; + + // We call the save method on the following object(s) if they + // were passed to this object by their corresponding set + // method. This object relates to these object(s) by a + // foreign key reference. + + if ($this->aArea !== null) { + if ($this->aArea->isModified() || $this->aArea->isNew()) { + $affectedRows += $this->aArea->save($con); + } + $this->setArea($this->aArea); + } + + if ($this->isNew() || $this->isModified()) { + // persist changes + if ($this->isNew()) { + $this->doInsert($con); + } else { + $this->doUpdate($con); + } + $affectedRows += 1; + $this->resetModified(); + } + + $this->alreadyInSave = false; + + } + + return $affectedRows; + } // doSave() + + /** + * Insert the row in the database. + * + * @param ConnectionInterface $con + * + * @throws PropelException + * @see doSave() + */ + protected function doInsert(ConnectionInterface $con) + { + $modifiedColumns = array(); + $index = 0; + + + // check the columns in natural order for more readable SQL queries + if ($this->isColumnModified(ColissimoHomeDeliveryAreaFreeshippingTableMap::ID)) { + $modifiedColumns[':p' . $index++] = 'ID'; + } + if ($this->isColumnModified(ColissimoHomeDeliveryAreaFreeshippingTableMap::AREA_ID)) { + $modifiedColumns[':p' . $index++] = 'AREA_ID'; + } + if ($this->isColumnModified(ColissimoHomeDeliveryAreaFreeshippingTableMap::CART_AMOUNT)) { + $modifiedColumns[':p' . $index++] = 'CART_AMOUNT'; + } + + $sql = sprintf( + 'INSERT INTO colissimo_home_delivery_area_freeshipping (%s) VALUES (%s)', + implode(', ', $modifiedColumns), + implode(', ', array_keys($modifiedColumns)) + ); + + try { + $stmt = $con->prepare($sql); + foreach ($modifiedColumns as $identifier => $columnName) { + switch ($columnName) { + case 'ID': + $stmt->bindValue($identifier, $this->id, PDO::PARAM_INT); + break; + case 'AREA_ID': + $stmt->bindValue($identifier, $this->area_id, PDO::PARAM_INT); + break; + case 'CART_AMOUNT': + $stmt->bindValue($identifier, $this->cart_amount, PDO::PARAM_STR); + break; + } + } + $stmt->execute(); + } catch (Exception $e) { + Propel::log($e->getMessage(), Propel::LOG_ERR); + throw new PropelException(sprintf('Unable to execute INSERT statement [%s]', $sql), 0, $e); + } + + $this->setNew(false); + } + + /** + * Update the row in the database. + * + * @param ConnectionInterface $con + * + * @return Integer Number of updated rows + * @see doSave() + */ + protected function doUpdate(ConnectionInterface $con) + { + $selectCriteria = $this->buildPkeyCriteria(); + $valuesCriteria = $this->buildCriteria(); + + return $selectCriteria->doUpdate($valuesCriteria, $con); + } + + /** + * Retrieves a field from the object by name passed in as a string. + * + * @param string $name name + * @param string $type The type of fieldname the $name is of: + * one of the class type constants TableMap::TYPE_PHPNAME, TableMap::TYPE_STUDLYPHPNAME + * TableMap::TYPE_COLNAME, TableMap::TYPE_FIELDNAME, TableMap::TYPE_NUM. + * Defaults to TableMap::TYPE_PHPNAME. + * @return mixed Value of field. + */ + public function getByName($name, $type = TableMap::TYPE_PHPNAME) + { + $pos = ColissimoHomeDeliveryAreaFreeshippingTableMap::translateFieldName($name, $type, TableMap::TYPE_NUM); + $field = $this->getByPosition($pos); + + return $field; + } + + /** + * Retrieves a field from the object by Position as specified in the xml schema. + * Zero-based. + * + * @param int $pos position in xml schema + * @return mixed Value of field at $pos + */ + public function getByPosition($pos) + { + switch ($pos) { + case 0: + return $this->getId(); + break; + case 1: + return $this->getAreaId(); + break; + case 2: + return $this->getCartAmount(); + break; + default: + return null; + break; + } // switch() + } + + /** + * Exports the object as an array. + * + * You can specify the key type of the array by passing one of the class + * type constants. + * + * @param string $keyType (optional) One of the class type constants TableMap::TYPE_PHPNAME, TableMap::TYPE_STUDLYPHPNAME, + * TableMap::TYPE_COLNAME, TableMap::TYPE_FIELDNAME, TableMap::TYPE_NUM. + * Defaults to TableMap::TYPE_PHPNAME. + * @param boolean $includeLazyLoadColumns (optional) Whether to include lazy loaded columns. Defaults to TRUE. + * @param array $alreadyDumpedObjects List of objects to skip to avoid recursion + * @param boolean $includeForeignObjects (optional) Whether to include hydrated related objects. Default to FALSE. + * + * @return array an associative array containing the field names (as keys) and field values + */ + public function toArray($keyType = TableMap::TYPE_PHPNAME, $includeLazyLoadColumns = true, $alreadyDumpedObjects = array(), $includeForeignObjects = false) + { + if (isset($alreadyDumpedObjects['ColissimoHomeDeliveryAreaFreeshipping'][$this->getPrimaryKey()])) { + return '*RECURSION*'; + } + $alreadyDumpedObjects['ColissimoHomeDeliveryAreaFreeshipping'][$this->getPrimaryKey()] = true; + $keys = ColissimoHomeDeliveryAreaFreeshippingTableMap::getFieldNames($keyType); + $result = array( + $keys[0] => $this->getId(), + $keys[1] => $this->getAreaId(), + $keys[2] => $this->getCartAmount(), + ); + $virtualColumns = $this->virtualColumns; + foreach ($virtualColumns as $key => $virtualColumn) { + $result[$key] = $virtualColumn; + } + + if ($includeForeignObjects) { + if (null !== $this->aArea) { + $result['Area'] = $this->aArea->toArray($keyType, $includeLazyLoadColumns, $alreadyDumpedObjects, true); + } + } + + return $result; + } + + /** + * Sets a field from the object by name passed in as a string. + * + * @param string $name + * @param mixed $value field value + * @param string $type The type of fieldname the $name is of: + * one of the class type constants TableMap::TYPE_PHPNAME, TableMap::TYPE_STUDLYPHPNAME + * TableMap::TYPE_COLNAME, TableMap::TYPE_FIELDNAME, TableMap::TYPE_NUM. + * Defaults to TableMap::TYPE_PHPNAME. + * @return void + */ + public function setByName($name, $value, $type = TableMap::TYPE_PHPNAME) + { + $pos = ColissimoHomeDeliveryAreaFreeshippingTableMap::translateFieldName($name, $type, TableMap::TYPE_NUM); + + return $this->setByPosition($pos, $value); + } + + /** + * Sets a field from the object by Position as specified in the xml schema. + * Zero-based. + * + * @param int $pos position in xml schema + * @param mixed $value field value + * @return void + */ + public function setByPosition($pos, $value) + { + switch ($pos) { + case 0: + $this->setId($value); + break; + case 1: + $this->setAreaId($value); + break; + case 2: + $this->setCartAmount($value); + break; + } // switch() + } + + /** + * Populates the object using an array. + * + * This is particularly useful when populating an object from one of the + * request arrays (e.g. $_POST). This method goes through the column + * names, checking to see whether a matching key exists in populated + * array. If so the setByName() method is called for that column. + * + * You can specify the key type of the array by additionally passing one + * of the class type constants TableMap::TYPE_PHPNAME, TableMap::TYPE_STUDLYPHPNAME, + * TableMap::TYPE_COLNAME, TableMap::TYPE_FIELDNAME, TableMap::TYPE_NUM. + * The default key type is the column's TableMap::TYPE_PHPNAME. + * + * @param array $arr An array to populate the object from. + * @param string $keyType The type of keys the array uses. + * @return void + */ + public function fromArray($arr, $keyType = TableMap::TYPE_PHPNAME) + { + $keys = ColissimoHomeDeliveryAreaFreeshippingTableMap::getFieldNames($keyType); + + if (array_key_exists($keys[0], $arr)) $this->setId($arr[$keys[0]]); + if (array_key_exists($keys[1], $arr)) $this->setAreaId($arr[$keys[1]]); + if (array_key_exists($keys[2], $arr)) $this->setCartAmount($arr[$keys[2]]); + } + + /** + * Build a Criteria object containing the values of all modified columns in this object. + * + * @return Criteria The Criteria object containing all modified values. + */ + public function buildCriteria() + { + $criteria = new Criteria(ColissimoHomeDeliveryAreaFreeshippingTableMap::DATABASE_NAME); + + if ($this->isColumnModified(ColissimoHomeDeliveryAreaFreeshippingTableMap::ID)) $criteria->add(ColissimoHomeDeliveryAreaFreeshippingTableMap::ID, $this->id); + if ($this->isColumnModified(ColissimoHomeDeliveryAreaFreeshippingTableMap::AREA_ID)) $criteria->add(ColissimoHomeDeliveryAreaFreeshippingTableMap::AREA_ID, $this->area_id); + if ($this->isColumnModified(ColissimoHomeDeliveryAreaFreeshippingTableMap::CART_AMOUNT)) $criteria->add(ColissimoHomeDeliveryAreaFreeshippingTableMap::CART_AMOUNT, $this->cart_amount); + + return $criteria; + } + + /** + * Builds a Criteria object containing the primary key for this object. + * + * Unlike buildCriteria() this method includes the primary key values regardless + * of whether or not they have been modified. + * + * @return Criteria The Criteria object containing value(s) for primary key(s). + */ + public function buildPkeyCriteria() + { + $criteria = new Criteria(ColissimoHomeDeliveryAreaFreeshippingTableMap::DATABASE_NAME); + $criteria->add(ColissimoHomeDeliveryAreaFreeshippingTableMap::ID, $this->id); + + return $criteria; + } + + /** + * Returns the primary key for this object (row). + * @return int + */ + public function getPrimaryKey() + { + return $this->getId(); + } + + /** + * Generic method to set the primary key (id column). + * + * @param int $key Primary key. + * @return void + */ + public function setPrimaryKey($key) + { + $this->setId($key); + } + + /** + * Returns true if the primary key for this object is null. + * @return boolean + */ + public function isPrimaryKeyNull() + { + + return null === $this->getId(); + } + + /** + * Sets contents of passed object to values from current object. + * + * If desired, this method can also make copies of all associated (fkey referrers) + * objects. + * + * @param object $copyObj An object of \ColissimoHomeDelivery\Model\ColissimoHomeDeliveryAreaFreeshipping (or compatible) type. + * @param boolean $deepCopy Whether to also copy all rows that refer (by fkey) to the current row. + * @param boolean $makeNew Whether to reset autoincrement PKs and make the object new. + * @throws PropelException + */ + public function copyInto($copyObj, $deepCopy = false, $makeNew = true) + { + $copyObj->setId($this->getId()); + $copyObj->setAreaId($this->getAreaId()); + $copyObj->setCartAmount($this->getCartAmount()); + if ($makeNew) { + $copyObj->setNew(true); + } + } + + /** + * Makes a copy of this object that will be inserted as a new row in table when saved. + * It creates a new object filling in the simple attributes, but skipping any primary + * keys that are defined for the table. + * + * If desired, this method can also make copies of all associated (fkey referrers) + * objects. + * + * @param boolean $deepCopy Whether to also copy all rows that refer (by fkey) to the current row. + * @return \ColissimoHomeDelivery\Model\ColissimoHomeDeliveryAreaFreeshipping Clone of current object. + * @throws PropelException + */ + public function copy($deepCopy = false) + { + // we use get_class(), because this might be a subclass + $clazz = get_class($this); + $copyObj = new $clazz(); + $this->copyInto($copyObj, $deepCopy); + + return $copyObj; + } + + /** + * Declares an association between this object and a ChildArea object. + * + * @param ChildArea $v + * @return \ColissimoHomeDelivery\Model\ColissimoHomeDeliveryAreaFreeshipping The current object (for fluent API support) + * @throws PropelException + */ + public function setArea(ChildArea $v = null) + { + if ($v === null) { + $this->setAreaId(NULL); + } else { + $this->setAreaId($v->getId()); + } + + $this->aArea = $v; + + // Add binding for other direction of this n:n relationship. + // If this object has already been added to the ChildArea object, it will not be re-added. + if ($v !== null) { + $v->addColissimoHomeDeliveryAreaFreeshipping($this); + } + + + return $this; + } + + + /** + * Get the associated ChildArea object + * + * @param ConnectionInterface $con Optional Connection object. + * @return ChildArea The associated ChildArea object. + * @throws PropelException + */ + public function getArea(ConnectionInterface $con = null) + { + if ($this->aArea === null && ($this->area_id !== null)) { + $this->aArea = AreaQuery::create()->findPk($this->area_id, $con); + /* The following can be used additionally to + guarantee the related object contains a reference + to this object. This level of coupling may, however, be + undesirable since it could result in an only partially populated collection + in the referenced object. + $this->aArea->addColissimoHomeDeliveryAreaFreeshippings($this); + */ + } + + return $this->aArea; + } + + /** + * Clears the current object and sets all attributes to their default values + */ + public function clear() + { + $this->id = null; + $this->area_id = null; + $this->cart_amount = null; + $this->alreadyInSave = false; + $this->clearAllReferences(); + $this->applyDefaultValues(); + $this->resetModified(); + $this->setNew(true); + $this->setDeleted(false); + } + + /** + * Resets all references to other model objects or collections of model objects. + * + * This method is a user-space workaround for PHP's inability to garbage collect + * objects with circular references (even in PHP 5.3). This is currently necessary + * when using Propel in certain daemon or large-volume/high-memory operations. + * + * @param boolean $deep Whether to also clear the references on all referrer objects. + */ + public function clearAllReferences($deep = false) + { + if ($deep) { + } // if ($deep) + + $this->aArea = null; + } + + /** + * Return the string representation of this object + * + * @return string + */ + public function __toString() + { + return (string) $this->exportTo(ColissimoHomeDeliveryAreaFreeshippingTableMap::DEFAULT_STRING_FORMAT); + } + + /** + * Code to be run before persisting the object + * @param ConnectionInterface $con + * @return boolean + */ + public function preSave(ConnectionInterface $con = null) + { + return true; + } + + /** + * Code to be run after persisting the object + * @param ConnectionInterface $con + */ + public function postSave(ConnectionInterface $con = null) + { + + } + + /** + * Code to be run before inserting to database + * @param ConnectionInterface $con + * @return boolean + */ + public function preInsert(ConnectionInterface $con = null) + { + return true; + } + + /** + * Code to be run after inserting to database + * @param ConnectionInterface $con + */ + public function postInsert(ConnectionInterface $con = null) + { + + } + + /** + * Code to be run before updating the object in database + * @param ConnectionInterface $con + * @return boolean + */ + public function preUpdate(ConnectionInterface $con = null) + { + return true; + } + + /** + * Code to be run after updating the object in database + * @param ConnectionInterface $con + */ + public function postUpdate(ConnectionInterface $con = null) + { + + } + + /** + * Code to be run before deleting the object in database + * @param ConnectionInterface $con + * @return boolean + */ + public function preDelete(ConnectionInterface $con = null) + { + return true; + } + + /** + * Code to be run after deleting the object in database + * @param ConnectionInterface $con + */ + public function postDelete(ConnectionInterface $con = null) + { + + } + + + /** + * Derived method to catches calls to undefined methods. + * + * Provides magic import/export method support (fromXML()/toXML(), fromYAML()/toYAML(), etc.). + * Allows to define default __call() behavior if you overwrite __call() + * + * @param string $name + * @param mixed $params + * + * @return array|string + */ + public function __call($name, $params) + { + if (0 === strpos($name, 'get')) { + $virtualColumn = substr($name, 3); + if ($this->hasVirtualColumn($virtualColumn)) { + return $this->getVirtualColumn($virtualColumn); + } + + $virtualColumn = lcfirst($virtualColumn); + if ($this->hasVirtualColumn($virtualColumn)) { + return $this->getVirtualColumn($virtualColumn); + } + } + + if (0 === strpos($name, 'from')) { + $format = substr($name, 4); + + return $this->importFrom($format, reset($params)); + } + + if (0 === strpos($name, 'to')) { + $format = substr($name, 2); + $includeLazyLoadColumns = isset($params[0]) ? $params[0] : true; + + return $this->exportTo($format, $includeLazyLoadColumns); + } + + throw new BadMethodCallException(sprintf('Call to undefined method: %s.', $name)); + } + +} diff --git a/local/modules/ColissimoHomeDelivery/Model/Base/ColissimoHomeDeliveryAreaFreeshippingQuery.php b/local/modules/ColissimoHomeDelivery/Model/Base/ColissimoHomeDeliveryAreaFreeshippingQuery.php new file mode 100644 index 00000000..19680ad7 --- /dev/null +++ b/local/modules/ColissimoHomeDelivery/Model/Base/ColissimoHomeDeliveryAreaFreeshippingQuery.php @@ -0,0 +1,519 @@ +setModelAlias($modelAlias); + } + if ($criteria instanceof Criteria) { + $query->mergeWith($criteria); + } + + return $query; + } + + /** + * Find object by primary key. + * Propel uses the instance pool to skip the database if the object exists. + * Go fast if the query is untouched. + * + * + * $obj = $c->findPk(12, $con); + * + * + * @param mixed $key Primary key to use for the query + * @param ConnectionInterface $con an optional connection object + * + * @return ChildColissimoHomeDeliveryAreaFreeshipping|array|mixed the result, formatted by the current formatter + */ + public function findPk($key, $con = null) + { + if ($key === null) { + return null; + } + if ((null !== ($obj = ColissimoHomeDeliveryAreaFreeshippingTableMap::getInstanceFromPool((string) $key))) && !$this->formatter) { + // the object is already in the instance pool + return $obj; + } + if ($con === null) { + $con = Propel::getServiceContainer()->getReadConnection(ColissimoHomeDeliveryAreaFreeshippingTableMap::DATABASE_NAME); + } + $this->basePreSelect($con); + if ($this->formatter || $this->modelAlias || $this->with || $this->select + || $this->selectColumns || $this->asColumns || $this->selectModifiers + || $this->map || $this->having || $this->joins) { + return $this->findPkComplex($key, $con); + } else { + return $this->findPkSimple($key, $con); + } + } + + /** + * Find object by primary key using raw SQL to go fast. + * Bypass doSelect() and the object formatter by using generated code. + * + * @param mixed $key Primary key to use for the query + * @param ConnectionInterface $con A connection object + * + * @return ChildColissimoHomeDeliveryAreaFreeshipping A model object, or null if the key is not found + */ + protected function findPkSimple($key, $con) + { + $sql = 'SELECT ID, AREA_ID, CART_AMOUNT FROM colissimo_home_delivery_area_freeshipping WHERE ID = :p0'; + try { + $stmt = $con->prepare($sql); + $stmt->bindValue(':p0', $key, PDO::PARAM_INT); + $stmt->execute(); + } catch (Exception $e) { + Propel::log($e->getMessage(), Propel::LOG_ERR); + throw new PropelException(sprintf('Unable to execute SELECT statement [%s]', $sql), 0, $e); + } + $obj = null; + if ($row = $stmt->fetch(\PDO::FETCH_NUM)) { + $obj = new ChildColissimoHomeDeliveryAreaFreeshipping(); + $obj->hydrate($row); + ColissimoHomeDeliveryAreaFreeshippingTableMap::addInstanceToPool($obj, (string) $key); + } + $stmt->closeCursor(); + + return $obj; + } + + /** + * Find object by primary key. + * + * @param mixed $key Primary key to use for the query + * @param ConnectionInterface $con A connection object + * + * @return ChildColissimoHomeDeliveryAreaFreeshipping|array|mixed the result, formatted by the current formatter + */ + protected function findPkComplex($key, $con) + { + // As the query uses a PK condition, no limit(1) is necessary. + $criteria = $this->isKeepQuery() ? clone $this : $this; + $dataFetcher = $criteria + ->filterByPrimaryKey($key) + ->doSelect($con); + + return $criteria->getFormatter()->init($criteria)->formatOne($dataFetcher); + } + + /** + * Find objects by primary key + * + * $objs = $c->findPks(array(12, 56, 832), $con); + * + * @param array $keys Primary keys to use for the query + * @param ConnectionInterface $con an optional connection object + * + * @return ObjectCollection|array|mixed the list of results, formatted by the current formatter + */ + public function findPks($keys, $con = null) + { + if (null === $con) { + $con = Propel::getServiceContainer()->getReadConnection($this->getDbName()); + } + $this->basePreSelect($con); + $criteria = $this->isKeepQuery() ? clone $this : $this; + $dataFetcher = $criteria + ->filterByPrimaryKeys($keys) + ->doSelect($con); + + return $criteria->getFormatter()->init($criteria)->format($dataFetcher); + } + + /** + * Filter the query by primary key + * + * @param mixed $key Primary key to use for the query + * + * @return ChildColissimoHomeDeliveryAreaFreeshippingQuery The current query, for fluid interface + */ + public function filterByPrimaryKey($key) + { + + return $this->addUsingAlias(ColissimoHomeDeliveryAreaFreeshippingTableMap::ID, $key, Criteria::EQUAL); + } + + /** + * Filter the query by a list of primary keys + * + * @param array $keys The list of primary key to use for the query + * + * @return ChildColissimoHomeDeliveryAreaFreeshippingQuery The current query, for fluid interface + */ + public function filterByPrimaryKeys($keys) + { + + return $this->addUsingAlias(ColissimoHomeDeliveryAreaFreeshippingTableMap::ID, $keys, Criteria::IN); + } + + /** + * Filter the query on the id column + * + * Example usage: + * + * $query->filterById(1234); // WHERE id = 1234 + * $query->filterById(array(12, 34)); // WHERE id IN (12, 34) + * $query->filterById(array('min' => 12)); // WHERE id > 12 + * + * + * @param mixed $id The value to use as filter. + * Use scalar values for equality. + * Use array values for in_array() equivalent. + * Use associative array('min' => $minValue, 'max' => $maxValue) for intervals. + * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL + * + * @return ChildColissimoHomeDeliveryAreaFreeshippingQuery The current query, for fluid interface + */ + public function filterById($id = null, $comparison = null) + { + if (is_array($id)) { + $useMinMax = false; + if (isset($id['min'])) { + $this->addUsingAlias(ColissimoHomeDeliveryAreaFreeshippingTableMap::ID, $id['min'], Criteria::GREATER_EQUAL); + $useMinMax = true; + } + if (isset($id['max'])) { + $this->addUsingAlias(ColissimoHomeDeliveryAreaFreeshippingTableMap::ID, $id['max'], Criteria::LESS_EQUAL); + $useMinMax = true; + } + if ($useMinMax) { + return $this; + } + if (null === $comparison) { + $comparison = Criteria::IN; + } + } + + return $this->addUsingAlias(ColissimoHomeDeliveryAreaFreeshippingTableMap::ID, $id, $comparison); + } + + /** + * Filter the query on the area_id column + * + * Example usage: + * + * $query->filterByAreaId(1234); // WHERE area_id = 1234 + * $query->filterByAreaId(array(12, 34)); // WHERE area_id IN (12, 34) + * $query->filterByAreaId(array('min' => 12)); // WHERE area_id > 12 + * + * + * @see filterByArea() + * + * @param mixed $areaId The value to use as filter. + * Use scalar values for equality. + * Use array values for in_array() equivalent. + * Use associative array('min' => $minValue, 'max' => $maxValue) for intervals. + * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL + * + * @return ChildColissimoHomeDeliveryAreaFreeshippingQuery The current query, for fluid interface + */ + public function filterByAreaId($areaId = null, $comparison = null) + { + if (is_array($areaId)) { + $useMinMax = false; + if (isset($areaId['min'])) { + $this->addUsingAlias(ColissimoHomeDeliveryAreaFreeshippingTableMap::AREA_ID, $areaId['min'], Criteria::GREATER_EQUAL); + $useMinMax = true; + } + if (isset($areaId['max'])) { + $this->addUsingAlias(ColissimoHomeDeliveryAreaFreeshippingTableMap::AREA_ID, $areaId['max'], Criteria::LESS_EQUAL); + $useMinMax = true; + } + if ($useMinMax) { + return $this; + } + if (null === $comparison) { + $comparison = Criteria::IN; + } + } + + return $this->addUsingAlias(ColissimoHomeDeliveryAreaFreeshippingTableMap::AREA_ID, $areaId, $comparison); + } + + /** + * Filter the query on the cart_amount column + * + * Example usage: + * + * $query->filterByCartAmount(1234); // WHERE cart_amount = 1234 + * $query->filterByCartAmount(array(12, 34)); // WHERE cart_amount IN (12, 34) + * $query->filterByCartAmount(array('min' => 12)); // WHERE cart_amount > 12 + * + * + * @param mixed $cartAmount The value to use as filter. + * Use scalar values for equality. + * Use array values for in_array() equivalent. + * Use associative array('min' => $minValue, 'max' => $maxValue) for intervals. + * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL + * + * @return ChildColissimoHomeDeliveryAreaFreeshippingQuery The current query, for fluid interface + */ + public function filterByCartAmount($cartAmount = null, $comparison = null) + { + if (is_array($cartAmount)) { + $useMinMax = false; + if (isset($cartAmount['min'])) { + $this->addUsingAlias(ColissimoHomeDeliveryAreaFreeshippingTableMap::CART_AMOUNT, $cartAmount['min'], Criteria::GREATER_EQUAL); + $useMinMax = true; + } + if (isset($cartAmount['max'])) { + $this->addUsingAlias(ColissimoHomeDeliveryAreaFreeshippingTableMap::CART_AMOUNT, $cartAmount['max'], Criteria::LESS_EQUAL); + $useMinMax = true; + } + if ($useMinMax) { + return $this; + } + if (null === $comparison) { + $comparison = Criteria::IN; + } + } + + return $this->addUsingAlias(ColissimoHomeDeliveryAreaFreeshippingTableMap::CART_AMOUNT, $cartAmount, $comparison); + } + + /** + * Filter the query by a related \Thelia\Model\Area object + * + * @param \Thelia\Model\Area|ObjectCollection $area The related object(s) to use as filter + * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL + * + * @return ChildColissimoHomeDeliveryAreaFreeshippingQuery The current query, for fluid interface + */ + public function filterByArea($area, $comparison = null) + { + if ($area instanceof \Thelia\Model\Area) { + return $this + ->addUsingAlias(ColissimoHomeDeliveryAreaFreeshippingTableMap::AREA_ID, $area->getId(), $comparison); + } elseif ($area instanceof ObjectCollection) { + if (null === $comparison) { + $comparison = Criteria::IN; + } + + return $this + ->addUsingAlias(ColissimoHomeDeliveryAreaFreeshippingTableMap::AREA_ID, $area->toKeyValue('PrimaryKey', 'Id'), $comparison); + } else { + throw new PropelException('filterByArea() only accepts arguments of type \Thelia\Model\Area or Collection'); + } + } + + /** + * Adds a JOIN clause to the query using the Area relation + * + * @param string $relationAlias optional alias for the relation + * @param string $joinType Accepted values are null, 'left join', 'right join', 'inner join' + * + * @return ChildColissimoHomeDeliveryAreaFreeshippingQuery The current query, for fluid interface + */ + public function joinArea($relationAlias = null, $joinType = Criteria::INNER_JOIN) + { + $tableMap = $this->getTableMap(); + $relationMap = $tableMap->getRelation('Area'); + + // create a ModelJoin object for this join + $join = new ModelJoin(); + $join->setJoinType($joinType); + $join->setRelationMap($relationMap, $this->useAliasInSQL ? $this->getModelAlias() : null, $relationAlias); + if ($previousJoin = $this->getPreviousJoin()) { + $join->setPreviousJoin($previousJoin); + } + + // add the ModelJoin to the current object + if ($relationAlias) { + $this->addAlias($relationAlias, $relationMap->getRightTable()->getName()); + $this->addJoinObject($join, $relationAlias); + } else { + $this->addJoinObject($join, 'Area'); + } + + return $this; + } + + /** + * Use the Area relation Area object + * + * @see useQuery() + * + * @param string $relationAlias optional alias for the relation, + * to be used as main alias in the secondary query + * @param string $joinType Accepted values are null, 'left join', 'right join', 'inner join' + * + * @return \Thelia\Model\AreaQuery A secondary query class using the current class as primary query + */ + public function useAreaQuery($relationAlias = null, $joinType = Criteria::INNER_JOIN) + { + return $this + ->joinArea($relationAlias, $joinType) + ->useQuery($relationAlias ? $relationAlias : 'Area', '\Thelia\Model\AreaQuery'); + } + + /** + * Exclude object from result + * + * @param ChildColissimoHomeDeliveryAreaFreeshipping $colissimoHomeDeliveryAreaFreeshipping Object to remove from the list of results + * + * @return ChildColissimoHomeDeliveryAreaFreeshippingQuery The current query, for fluid interface + */ + public function prune($colissimoHomeDeliveryAreaFreeshipping = null) + { + if ($colissimoHomeDeliveryAreaFreeshipping) { + $this->addUsingAlias(ColissimoHomeDeliveryAreaFreeshippingTableMap::ID, $colissimoHomeDeliveryAreaFreeshipping->getId(), Criteria::NOT_EQUAL); + } + + return $this; + } + + /** + * Deletes all rows from the colissimo_home_delivery_area_freeshipping table. + * + * @param ConnectionInterface $con the connection to use + * @return int The number of affected rows (if supported by underlying database driver). + */ + public function doDeleteAll(ConnectionInterface $con = null) + { + if (null === $con) { + $con = Propel::getServiceContainer()->getWriteConnection(ColissimoHomeDeliveryAreaFreeshippingTableMap::DATABASE_NAME); + } + $affectedRows = 0; // initialize var to track total num of affected rows + try { + // use transaction because $criteria could contain info + // for more than one table or we could emulating ON DELETE CASCADE, etc. + $con->beginTransaction(); + $affectedRows += parent::doDeleteAll($con); + // Because this db requires some delete cascade/set null emulation, we have to + // clear the cached instance *after* the emulation has happened (since + // instances get re-added by the select statement contained therein). + ColissimoHomeDeliveryAreaFreeshippingTableMap::clearInstancePool(); + ColissimoHomeDeliveryAreaFreeshippingTableMap::clearRelatedInstancePool(); + + $con->commit(); + } catch (PropelException $e) { + $con->rollBack(); + throw $e; + } + + return $affectedRows; + } + + /** + * Performs a DELETE on the database, given a ChildColissimoHomeDeliveryAreaFreeshipping or Criteria object OR a primary key value. + * + * @param mixed $values Criteria or ChildColissimoHomeDeliveryAreaFreeshipping object or primary key or array of primary keys + * which is used to create the DELETE statement + * @param ConnectionInterface $con the connection to use + * @return int The number of affected rows (if supported by underlying database driver). This includes CASCADE-related rows + * if supported by native driver or if emulated using Propel. + * @throws PropelException Any exceptions caught during processing will be + * rethrown wrapped into a PropelException. + */ + public function delete(ConnectionInterface $con = null) + { + if (null === $con) { + $con = Propel::getServiceContainer()->getWriteConnection(ColissimoHomeDeliveryAreaFreeshippingTableMap::DATABASE_NAME); + } + + $criteria = $this; + + // Set the correct dbName + $criteria->setDbName(ColissimoHomeDeliveryAreaFreeshippingTableMap::DATABASE_NAME); + + $affectedRows = 0; // initialize var to track total num of affected rows + + try { + // use transaction because $criteria could contain info + // for more than one table or we could emulating ON DELETE CASCADE, etc. + $con->beginTransaction(); + + + ColissimoHomeDeliveryAreaFreeshippingTableMap::removeInstanceFromPool($criteria); + + $affectedRows += ModelCriteria::delete($con); + ColissimoHomeDeliveryAreaFreeshippingTableMap::clearRelatedInstancePool(); + $con->commit(); + + return $affectedRows; + } catch (PropelException $e) { + $con->rollBack(); + throw $e; + } + } + +} // ColissimoHomeDeliveryAreaFreeshippingQuery diff --git a/local/modules/ColissimoHomeDelivery/Model/Base/ColissimoHomeDeliveryFreeshipping.php b/local/modules/ColissimoHomeDelivery/Model/Base/ColissimoHomeDeliveryFreeshipping.php new file mode 100644 index 00000000..02f90709 --- /dev/null +++ b/local/modules/ColissimoHomeDelivery/Model/Base/ColissimoHomeDeliveryFreeshipping.php @@ -0,0 +1,1184 @@ +active = false; + } + + /** + * Initializes internal state of ColissimoHomeDelivery\Model\Base\ColissimoHomeDeliveryFreeshipping object. + * @see applyDefaults() + */ + public function __construct() + { + $this->applyDefaultValues(); + } + + /** + * Returns whether the object has been modified. + * + * @return boolean True if the object has been modified. + */ + public function isModified() + { + return !!$this->modifiedColumns; + } + + /** + * Has specified column been modified? + * + * @param string $col column fully qualified name (TableMap::TYPE_COLNAME), e.g. Book::AUTHOR_ID + * @return boolean True if $col has been modified. + */ + public function isColumnModified($col) + { + return $this->modifiedColumns && isset($this->modifiedColumns[$col]); + } + + /** + * Get the columns that have been modified in this object. + * @return array A unique list of the modified column names for this object. + */ + public function getModifiedColumns() + { + return $this->modifiedColumns ? array_keys($this->modifiedColumns) : []; + } + + /** + * Returns whether the object has ever been saved. This will + * be false, if the object was retrieved from storage or was created + * and then saved. + * + * @return boolean true, if the object has never been persisted. + */ + public function isNew() + { + return $this->new; + } + + /** + * Setter for the isNew attribute. This method will be called + * by Propel-generated children and objects. + * + * @param boolean $b the state of the object. + */ + public function setNew($b) + { + $this->new = (Boolean) $b; + } + + /** + * Whether this object has been deleted. + * @return boolean The deleted state of this object. + */ + public function isDeleted() + { + return $this->deleted; + } + + /** + * Specify whether this object has been deleted. + * @param boolean $b The deleted state of this object. + * @return void + */ + public function setDeleted($b) + { + $this->deleted = (Boolean) $b; + } + + /** + * Sets the modified state for the object to be false. + * @param string $col If supplied, only the specified column is reset. + * @return void + */ + public function resetModified($col = null) + { + if (null !== $col) { + if (isset($this->modifiedColumns[$col])) { + unset($this->modifiedColumns[$col]); + } + } else { + $this->modifiedColumns = array(); + } + } + + /** + * Compares this with another ColissimoHomeDeliveryFreeshipping instance. If + * obj is an instance of ColissimoHomeDeliveryFreeshipping, delegates to + * equals(ColissimoHomeDeliveryFreeshipping). Otherwise, returns false. + * + * @param mixed $obj The object to compare to. + * @return boolean Whether equal to the object specified. + */ + public function equals($obj) + { + $thisclazz = get_class($this); + if (!is_object($obj) || !($obj instanceof $thisclazz)) { + return false; + } + + if ($this === $obj) { + return true; + } + + if (null === $this->getPrimaryKey() + || null === $obj->getPrimaryKey()) { + return false; + } + + return $this->getPrimaryKey() === $obj->getPrimaryKey(); + } + + /** + * If the primary key is not null, return the hashcode of the + * primary key. Otherwise, return the hash code of the object. + * + * @return int Hashcode + */ + public function hashCode() + { + if (null !== $this->getPrimaryKey()) { + return crc32(serialize($this->getPrimaryKey())); + } + + return crc32(serialize(clone $this)); + } + + /** + * Get the associative array of the virtual columns in this object + * + * @return array + */ + public function getVirtualColumns() + { + return $this->virtualColumns; + } + + /** + * Checks the existence of a virtual column in this object + * + * @param string $name The virtual column name + * @return boolean + */ + public function hasVirtualColumn($name) + { + return array_key_exists($name, $this->virtualColumns); + } + + /** + * Get the value of a virtual column in this object + * + * @param string $name The virtual column name + * @return mixed + * + * @throws PropelException + */ + public function getVirtualColumn($name) + { + if (!$this->hasVirtualColumn($name)) { + throw new PropelException(sprintf('Cannot get value of inexistent virtual column %s.', $name)); + } + + return $this->virtualColumns[$name]; + } + + /** + * Set the value of a virtual column in this object + * + * @param string $name The virtual column name + * @param mixed $value The value to give to the virtual column + * + * @return ColissimoHomeDeliveryFreeshipping The current object, for fluid interface + */ + public function setVirtualColumn($name, $value) + { + $this->virtualColumns[$name] = $value; + + return $this; + } + + /** + * Logs a message using Propel::log(). + * + * @param string $msg + * @param int $priority One of the Propel::LOG_* logging levels + * @return boolean + */ + protected function log($msg, $priority = Propel::LOG_INFO) + { + return Propel::log(get_class($this) . ': ' . $msg, $priority); + } + + /** + * Populate the current object from a string, using a given parser format + * + * $book = new Book(); + * $book->importFrom('JSON', '{"Id":9012,"Title":"Don Juan","ISBN":"0140422161","Price":12.99,"PublisherId":1234,"AuthorId":5678}'); + * + * + * @param mixed $parser A AbstractParser instance, + * or a format name ('XML', 'YAML', 'JSON', 'CSV') + * @param string $data The source data to import from + * + * @return ColissimoHomeDeliveryFreeshipping The current object, for fluid interface + */ + public function importFrom($parser, $data) + { + if (!$parser instanceof AbstractParser) { + $parser = AbstractParser::getParser($parser); + } + + $this->fromArray($parser->toArray($data), TableMap::TYPE_PHPNAME); + + return $this; + } + + /** + * Export the current object properties to a string, using a given parser format + * + * $book = BookQuery::create()->findPk(9012); + * echo $book->exportTo('JSON'); + * => {"Id":9012,"Title":"Don Juan","ISBN":"0140422161","Price":12.99,"PublisherId":1234,"AuthorId":5678}'); + * + * + * @param mixed $parser A AbstractParser instance, or a format name ('XML', 'YAML', 'JSON', 'CSV') + * @param boolean $includeLazyLoadColumns (optional) Whether to include lazy load(ed) columns. Defaults to TRUE. + * @return string The exported data + */ + public function exportTo($parser, $includeLazyLoadColumns = true) + { + if (!$parser instanceof AbstractParser) { + $parser = AbstractParser::getParser($parser); + } + + return $parser->fromArray($this->toArray(TableMap::TYPE_PHPNAME, $includeLazyLoadColumns, array(), true)); + } + + /** + * Clean up internal collections prior to serializing + * Avoids recursive loops that turn into segmentation faults when serializing + */ + public function __sleep() + { + $this->clearAllReferences(); + + return array_keys(get_object_vars($this)); + } + + /** + * Get the [id] column value. + * + * @return int + */ + public function getId() + { + + return $this->id; + } + + /** + * Get the [active] column value. + * + * @return boolean + */ + public function getActive() + { + + return $this->active; + } + + /** + * Get the [freeshipping_from] column value. + * + * @return string + */ + public function getFreeshippingFrom() + { + + return $this->freeshipping_from; + } + + /** + * Set the value of [id] column. + * + * @param int $v new value + * @return \ColissimoHomeDelivery\Model\ColissimoHomeDeliveryFreeshipping The current object (for fluent API support) + */ + public function setId($v) + { + if ($v !== null) { + $v = (int) $v; + } + + if ($this->id !== $v) { + $this->id = $v; + $this->modifiedColumns[ColissimoHomeDeliveryFreeshippingTableMap::ID] = true; + } + + + return $this; + } // setId() + + /** + * Sets the value of the [active] column. + * Non-boolean arguments are converted using the following rules: + * * 1, '1', 'true', 'on', and 'yes' are converted to boolean true + * * 0, '0', 'false', 'off', and 'no' are converted to boolean false + * Check on string values is case insensitive (so 'FaLsE' is seen as 'false'). + * + * @param boolean|integer|string $v The new value + * @return \ColissimoHomeDelivery\Model\ColissimoHomeDeliveryFreeshipping The current object (for fluent API support) + */ + public function setActive($v) + { + if ($v !== null) { + if (is_string($v)) { + $v = in_array(strtolower($v), array('false', 'off', '-', 'no', 'n', '0', '')) ? false : true; + } else { + $v = (boolean) $v; + } + } + + if ($this->active !== $v) { + $this->active = $v; + $this->modifiedColumns[ColissimoHomeDeliveryFreeshippingTableMap::ACTIVE] = true; + } + + + return $this; + } // setActive() + + /** + * Set the value of [freeshipping_from] column. + * + * @param string $v new value + * @return \ColissimoHomeDelivery\Model\ColissimoHomeDeliveryFreeshipping The current object (for fluent API support) + */ + public function setFreeshippingFrom($v) + { + if ($v !== null) { + $v = (string) $v; + } + + if ($this->freeshipping_from !== $v) { + $this->freeshipping_from = $v; + $this->modifiedColumns[ColissimoHomeDeliveryFreeshippingTableMap::FREESHIPPING_FROM] = true; + } + + + return $this; + } // setFreeshippingFrom() + + /** + * Indicates whether the columns in this object are only set to default values. + * + * This method can be used in conjunction with isModified() to indicate whether an object is both + * modified _and_ has some values set which are non-default. + * + * @return boolean Whether the columns in this object are only been set with default values. + */ + public function hasOnlyDefaultValues() + { + if ($this->active !== false) { + return false; + } + + // otherwise, everything was equal, so return TRUE + return true; + } // hasOnlyDefaultValues() + + /** + * Hydrates (populates) the object variables with values from the database resultset. + * + * An offset (0-based "start column") is specified so that objects can be hydrated + * with a subset of the columns in the resultset rows. This is needed, for example, + * for results of JOIN queries where the resultset row includes columns from two or + * more tables. + * + * @param array $row The row returned by DataFetcher->fetch(). + * @param int $startcol 0-based offset column which indicates which restultset column to start with. + * @param boolean $rehydrate Whether this object is being re-hydrated from the database. + * @param string $indexType The index type of $row. Mostly DataFetcher->getIndexType(). + One of the class type constants TableMap::TYPE_PHPNAME, TableMap::TYPE_STUDLYPHPNAME + * TableMap::TYPE_COLNAME, TableMap::TYPE_FIELDNAME, TableMap::TYPE_NUM. + * + * @return int next starting column + * @throws PropelException - Any caught Exception will be rewrapped as a PropelException. + */ + public function hydrate($row, $startcol = 0, $rehydrate = false, $indexType = TableMap::TYPE_NUM) + { + try { + + + $col = $row[TableMap::TYPE_NUM == $indexType ? 0 + $startcol : ColissimoHomeDeliveryFreeshippingTableMap::translateFieldName('Id', TableMap::TYPE_PHPNAME, $indexType)]; + $this->id = (null !== $col) ? (int) $col : null; + + $col = $row[TableMap::TYPE_NUM == $indexType ? 1 + $startcol : ColissimoHomeDeliveryFreeshippingTableMap::translateFieldName('Active', TableMap::TYPE_PHPNAME, $indexType)]; + $this->active = (null !== $col) ? (boolean) $col : null; + + $col = $row[TableMap::TYPE_NUM == $indexType ? 2 + $startcol : ColissimoHomeDeliveryFreeshippingTableMap::translateFieldName('FreeshippingFrom', TableMap::TYPE_PHPNAME, $indexType)]; + $this->freeshipping_from = (null !== $col) ? (string) $col : null; + $this->resetModified(); + + $this->setNew(false); + + if ($rehydrate) { + $this->ensureConsistency(); + } + + return $startcol + 3; // 3 = ColissimoHomeDeliveryFreeshippingTableMap::NUM_HYDRATE_COLUMNS. + + } catch (Exception $e) { + throw new PropelException("Error populating \ColissimoHomeDelivery\Model\ColissimoHomeDeliveryFreeshipping object", 0, $e); + } + } + + /** + * Checks and repairs the internal consistency of the object. + * + * This method is executed after an already-instantiated object is re-hydrated + * from the database. It exists to check any foreign keys to make sure that + * the objects related to the current object are correct based on foreign key. + * + * You can override this method in the stub class, but you should always invoke + * the base method from the overridden method (i.e. parent::ensureConsistency()), + * in case your model changes. + * + * @throws PropelException + */ + public function ensureConsistency() + { + } // ensureConsistency + + /** + * Reloads this object from datastore based on primary key and (optionally) resets all associated objects. + * + * This will only work if the object has been saved and has a valid primary key set. + * + * @param boolean $deep (optional) Whether to also de-associated any related objects. + * @param ConnectionInterface $con (optional) The ConnectionInterface connection to use. + * @return void + * @throws PropelException - if this object is deleted, unsaved or doesn't have pk match in db + */ + public function reload($deep = false, ConnectionInterface $con = null) + { + if ($this->isDeleted()) { + throw new PropelException("Cannot reload a deleted object."); + } + + if ($this->isNew()) { + throw new PropelException("Cannot reload an unsaved object."); + } + + if ($con === null) { + $con = Propel::getServiceContainer()->getReadConnection(ColissimoHomeDeliveryFreeshippingTableMap::DATABASE_NAME); + } + + // We don't need to alter the object instance pool; we're just modifying this instance + // already in the pool. + + $dataFetcher = ChildColissimoHomeDeliveryFreeshippingQuery::create(null, $this->buildPkeyCriteria())->setFormatter(ModelCriteria::FORMAT_STATEMENT)->find($con); + $row = $dataFetcher->fetch(); + $dataFetcher->close(); + if (!$row) { + throw new PropelException('Cannot find matching row in the database to reload object values.'); + } + $this->hydrate($row, 0, true, $dataFetcher->getIndexType()); // rehydrate + + if ($deep) { // also de-associate any related objects? + + } // if (deep) + } + + /** + * Removes this object from datastore and sets delete attribute. + * + * @param ConnectionInterface $con + * @return void + * @throws PropelException + * @see ColissimoHomeDeliveryFreeshipping::setDeleted() + * @see ColissimoHomeDeliveryFreeshipping::isDeleted() + */ + public function delete(ConnectionInterface $con = null) + { + if ($this->isDeleted()) { + throw new PropelException("This object has already been deleted."); + } + + if ($con === null) { + $con = Propel::getServiceContainer()->getWriteConnection(ColissimoHomeDeliveryFreeshippingTableMap::DATABASE_NAME); + } + + $con->beginTransaction(); + try { + $deleteQuery = ChildColissimoHomeDeliveryFreeshippingQuery::create() + ->filterByPrimaryKey($this->getPrimaryKey()); + $ret = $this->preDelete($con); + if ($ret) { + $deleteQuery->delete($con); + $this->postDelete($con); + $con->commit(); + $this->setDeleted(true); + } else { + $con->commit(); + } + } catch (Exception $e) { + $con->rollBack(); + throw $e; + } + } + + /** + * Persists this object to the database. + * + * If the object is new, it inserts it; otherwise an update is performed. + * All modified related objects will also be persisted in the doSave() + * method. This method wraps all precipitate database operations in a + * single transaction. + * + * @param ConnectionInterface $con + * @return int The number of rows affected by this insert/update and any referring fk objects' save() operations. + * @throws PropelException + * @see doSave() + */ + public function save(ConnectionInterface $con = null) + { + if ($this->isDeleted()) { + throw new PropelException("You cannot save an object that has been deleted."); + } + + if ($con === null) { + $con = Propel::getServiceContainer()->getWriteConnection(ColissimoHomeDeliveryFreeshippingTableMap::DATABASE_NAME); + } + + $con->beginTransaction(); + $isInsert = $this->isNew(); + try { + $ret = $this->preSave($con); + if ($isInsert) { + $ret = $ret && $this->preInsert($con); + } else { + $ret = $ret && $this->preUpdate($con); + } + if ($ret) { + $affectedRows = $this->doSave($con); + if ($isInsert) { + $this->postInsert($con); + } else { + $this->postUpdate($con); + } + $this->postSave($con); + ColissimoHomeDeliveryFreeshippingTableMap::addInstanceToPool($this); + } else { + $affectedRows = 0; + } + $con->commit(); + + return $affectedRows; + } catch (Exception $e) { + $con->rollBack(); + throw $e; + } + } + + /** + * Performs the work of inserting or updating the row in the database. + * + * If the object is new, it inserts it; otherwise an update is performed. + * All related objects are also updated in this method. + * + * @param ConnectionInterface $con + * @return int The number of rows affected by this insert/update and any referring fk objects' save() operations. + * @throws PropelException + * @see save() + */ + protected function doSave(ConnectionInterface $con) + { + $affectedRows = 0; // initialize var to track total num of affected rows + if (!$this->alreadyInSave) { + $this->alreadyInSave = true; + + if ($this->isNew() || $this->isModified()) { + // persist changes + if ($this->isNew()) { + $this->doInsert($con); + } else { + $this->doUpdate($con); + } + $affectedRows += 1; + $this->resetModified(); + } + + $this->alreadyInSave = false; + + } + + return $affectedRows; + } // doSave() + + /** + * Insert the row in the database. + * + * @param ConnectionInterface $con + * + * @throws PropelException + * @see doSave() + */ + protected function doInsert(ConnectionInterface $con) + { + $modifiedColumns = array(); + $index = 0; + + + // check the columns in natural order for more readable SQL queries + if ($this->isColumnModified(ColissimoHomeDeliveryFreeshippingTableMap::ID)) { + $modifiedColumns[':p' . $index++] = 'ID'; + } + if ($this->isColumnModified(ColissimoHomeDeliveryFreeshippingTableMap::ACTIVE)) { + $modifiedColumns[':p' . $index++] = 'ACTIVE'; + } + if ($this->isColumnModified(ColissimoHomeDeliveryFreeshippingTableMap::FREESHIPPING_FROM)) { + $modifiedColumns[':p' . $index++] = 'FREESHIPPING_FROM'; + } + + $sql = sprintf( + 'INSERT INTO colissimo_home_delivery_freeshipping (%s) VALUES (%s)', + implode(', ', $modifiedColumns), + implode(', ', array_keys($modifiedColumns)) + ); + + try { + $stmt = $con->prepare($sql); + foreach ($modifiedColumns as $identifier => $columnName) { + switch ($columnName) { + case 'ID': + $stmt->bindValue($identifier, $this->id, PDO::PARAM_INT); + break; + case 'ACTIVE': + $stmt->bindValue($identifier, (int) $this->active, PDO::PARAM_INT); + break; + case 'FREESHIPPING_FROM': + $stmt->bindValue($identifier, $this->freeshipping_from, PDO::PARAM_STR); + break; + } + } + $stmt->execute(); + } catch (Exception $e) { + Propel::log($e->getMessage(), Propel::LOG_ERR); + throw new PropelException(sprintf('Unable to execute INSERT statement [%s]', $sql), 0, $e); + } + + $this->setNew(false); + } + + /** + * Update the row in the database. + * + * @param ConnectionInterface $con + * + * @return Integer Number of updated rows + * @see doSave() + */ + protected function doUpdate(ConnectionInterface $con) + { + $selectCriteria = $this->buildPkeyCriteria(); + $valuesCriteria = $this->buildCriteria(); + + return $selectCriteria->doUpdate($valuesCriteria, $con); + } + + /** + * Retrieves a field from the object by name passed in as a string. + * + * @param string $name name + * @param string $type The type of fieldname the $name is of: + * one of the class type constants TableMap::TYPE_PHPNAME, TableMap::TYPE_STUDLYPHPNAME + * TableMap::TYPE_COLNAME, TableMap::TYPE_FIELDNAME, TableMap::TYPE_NUM. + * Defaults to TableMap::TYPE_PHPNAME. + * @return mixed Value of field. + */ + public function getByName($name, $type = TableMap::TYPE_PHPNAME) + { + $pos = ColissimoHomeDeliveryFreeshippingTableMap::translateFieldName($name, $type, TableMap::TYPE_NUM); + $field = $this->getByPosition($pos); + + return $field; + } + + /** + * Retrieves a field from the object by Position as specified in the xml schema. + * Zero-based. + * + * @param int $pos position in xml schema + * @return mixed Value of field at $pos + */ + public function getByPosition($pos) + { + switch ($pos) { + case 0: + return $this->getId(); + break; + case 1: + return $this->getActive(); + break; + case 2: + return $this->getFreeshippingFrom(); + break; + default: + return null; + break; + } // switch() + } + + /** + * Exports the object as an array. + * + * You can specify the key type of the array by passing one of the class + * type constants. + * + * @param string $keyType (optional) One of the class type constants TableMap::TYPE_PHPNAME, TableMap::TYPE_STUDLYPHPNAME, + * TableMap::TYPE_COLNAME, TableMap::TYPE_FIELDNAME, TableMap::TYPE_NUM. + * Defaults to TableMap::TYPE_PHPNAME. + * @param boolean $includeLazyLoadColumns (optional) Whether to include lazy loaded columns. Defaults to TRUE. + * @param array $alreadyDumpedObjects List of objects to skip to avoid recursion + * + * @return array an associative array containing the field names (as keys) and field values + */ + public function toArray($keyType = TableMap::TYPE_PHPNAME, $includeLazyLoadColumns = true, $alreadyDumpedObjects = array()) + { + if (isset($alreadyDumpedObjects['ColissimoHomeDeliveryFreeshipping'][$this->getPrimaryKey()])) { + return '*RECURSION*'; + } + $alreadyDumpedObjects['ColissimoHomeDeliveryFreeshipping'][$this->getPrimaryKey()] = true; + $keys = ColissimoHomeDeliveryFreeshippingTableMap::getFieldNames($keyType); + $result = array( + $keys[0] => $this->getId(), + $keys[1] => $this->getActive(), + $keys[2] => $this->getFreeshippingFrom(), + ); + $virtualColumns = $this->virtualColumns; + foreach ($virtualColumns as $key => $virtualColumn) { + $result[$key] = $virtualColumn; + } + + + return $result; + } + + /** + * Sets a field from the object by name passed in as a string. + * + * @param string $name + * @param mixed $value field value + * @param string $type The type of fieldname the $name is of: + * one of the class type constants TableMap::TYPE_PHPNAME, TableMap::TYPE_STUDLYPHPNAME + * TableMap::TYPE_COLNAME, TableMap::TYPE_FIELDNAME, TableMap::TYPE_NUM. + * Defaults to TableMap::TYPE_PHPNAME. + * @return void + */ + public function setByName($name, $value, $type = TableMap::TYPE_PHPNAME) + { + $pos = ColissimoHomeDeliveryFreeshippingTableMap::translateFieldName($name, $type, TableMap::TYPE_NUM); + + return $this->setByPosition($pos, $value); + } + + /** + * Sets a field from the object by Position as specified in the xml schema. + * Zero-based. + * + * @param int $pos position in xml schema + * @param mixed $value field value + * @return void + */ + public function setByPosition($pos, $value) + { + switch ($pos) { + case 0: + $this->setId($value); + break; + case 1: + $this->setActive($value); + break; + case 2: + $this->setFreeshippingFrom($value); + break; + } // switch() + } + + /** + * Populates the object using an array. + * + * This is particularly useful when populating an object from one of the + * request arrays (e.g. $_POST). This method goes through the column + * names, checking to see whether a matching key exists in populated + * array. If so the setByName() method is called for that column. + * + * You can specify the key type of the array by additionally passing one + * of the class type constants TableMap::TYPE_PHPNAME, TableMap::TYPE_STUDLYPHPNAME, + * TableMap::TYPE_COLNAME, TableMap::TYPE_FIELDNAME, TableMap::TYPE_NUM. + * The default key type is the column's TableMap::TYPE_PHPNAME. + * + * @param array $arr An array to populate the object from. + * @param string $keyType The type of keys the array uses. + * @return void + */ + public function fromArray($arr, $keyType = TableMap::TYPE_PHPNAME) + { + $keys = ColissimoHomeDeliveryFreeshippingTableMap::getFieldNames($keyType); + + if (array_key_exists($keys[0], $arr)) $this->setId($arr[$keys[0]]); + if (array_key_exists($keys[1], $arr)) $this->setActive($arr[$keys[1]]); + if (array_key_exists($keys[2], $arr)) $this->setFreeshippingFrom($arr[$keys[2]]); + } + + /** + * Build a Criteria object containing the values of all modified columns in this object. + * + * @return Criteria The Criteria object containing all modified values. + */ + public function buildCriteria() + { + $criteria = new Criteria(ColissimoHomeDeliveryFreeshippingTableMap::DATABASE_NAME); + + if ($this->isColumnModified(ColissimoHomeDeliveryFreeshippingTableMap::ID)) $criteria->add(ColissimoHomeDeliveryFreeshippingTableMap::ID, $this->id); + if ($this->isColumnModified(ColissimoHomeDeliveryFreeshippingTableMap::ACTIVE)) $criteria->add(ColissimoHomeDeliveryFreeshippingTableMap::ACTIVE, $this->active); + if ($this->isColumnModified(ColissimoHomeDeliveryFreeshippingTableMap::FREESHIPPING_FROM)) $criteria->add(ColissimoHomeDeliveryFreeshippingTableMap::FREESHIPPING_FROM, $this->freeshipping_from); + + return $criteria; + } + + /** + * Builds a Criteria object containing the primary key for this object. + * + * Unlike buildCriteria() this method includes the primary key values regardless + * of whether or not they have been modified. + * + * @return Criteria The Criteria object containing value(s) for primary key(s). + */ + public function buildPkeyCriteria() + { + $criteria = new Criteria(ColissimoHomeDeliveryFreeshippingTableMap::DATABASE_NAME); + $criteria->add(ColissimoHomeDeliveryFreeshippingTableMap::ID, $this->id); + + return $criteria; + } + + /** + * Returns the primary key for this object (row). + * @return int + */ + public function getPrimaryKey() + { + return $this->getId(); + } + + /** + * Generic method to set the primary key (id column). + * + * @param int $key Primary key. + * @return void + */ + public function setPrimaryKey($key) + { + $this->setId($key); + } + + /** + * Returns true if the primary key for this object is null. + * @return boolean + */ + public function isPrimaryKeyNull() + { + + return null === $this->getId(); + } + + /** + * Sets contents of passed object to values from current object. + * + * If desired, this method can also make copies of all associated (fkey referrers) + * objects. + * + * @param object $copyObj An object of \ColissimoHomeDelivery\Model\ColissimoHomeDeliveryFreeshipping (or compatible) type. + * @param boolean $deepCopy Whether to also copy all rows that refer (by fkey) to the current row. + * @param boolean $makeNew Whether to reset autoincrement PKs and make the object new. + * @throws PropelException + */ + public function copyInto($copyObj, $deepCopy = false, $makeNew = true) + { + $copyObj->setId($this->getId()); + $copyObj->setActive($this->getActive()); + $copyObj->setFreeshippingFrom($this->getFreeshippingFrom()); + if ($makeNew) { + $copyObj->setNew(true); + } + } + + /** + * Makes a copy of this object that will be inserted as a new row in table when saved. + * It creates a new object filling in the simple attributes, but skipping any primary + * keys that are defined for the table. + * + * If desired, this method can also make copies of all associated (fkey referrers) + * objects. + * + * @param boolean $deepCopy Whether to also copy all rows that refer (by fkey) to the current row. + * @return \ColissimoHomeDelivery\Model\ColissimoHomeDeliveryFreeshipping Clone of current object. + * @throws PropelException + */ + public function copy($deepCopy = false) + { + // we use get_class(), because this might be a subclass + $clazz = get_class($this); + $copyObj = new $clazz(); + $this->copyInto($copyObj, $deepCopy); + + return $copyObj; + } + + /** + * Clears the current object and sets all attributes to their default values + */ + public function clear() + { + $this->id = null; + $this->active = null; + $this->freeshipping_from = null; + $this->alreadyInSave = false; + $this->clearAllReferences(); + $this->applyDefaultValues(); + $this->resetModified(); + $this->setNew(true); + $this->setDeleted(false); + } + + /** + * Resets all references to other model objects or collections of model objects. + * + * This method is a user-space workaround for PHP's inability to garbage collect + * objects with circular references (even in PHP 5.3). This is currently necessary + * when using Propel in certain daemon or large-volume/high-memory operations. + * + * @param boolean $deep Whether to also clear the references on all referrer objects. + */ + public function clearAllReferences($deep = false) + { + if ($deep) { + } // if ($deep) + + } + + /** + * Return the string representation of this object + * + * @return string + */ + public function __toString() + { + return (string) $this->exportTo(ColissimoHomeDeliveryFreeshippingTableMap::DEFAULT_STRING_FORMAT); + } + + /** + * Code to be run before persisting the object + * @param ConnectionInterface $con + * @return boolean + */ + public function preSave(ConnectionInterface $con = null) + { + return true; + } + + /** + * Code to be run after persisting the object + * @param ConnectionInterface $con + */ + public function postSave(ConnectionInterface $con = null) + { + + } + + /** + * Code to be run before inserting to database + * @param ConnectionInterface $con + * @return boolean + */ + public function preInsert(ConnectionInterface $con = null) + { + return true; + } + + /** + * Code to be run after inserting to database + * @param ConnectionInterface $con + */ + public function postInsert(ConnectionInterface $con = null) + { + + } + + /** + * Code to be run before updating the object in database + * @param ConnectionInterface $con + * @return boolean + */ + public function preUpdate(ConnectionInterface $con = null) + { + return true; + } + + /** + * Code to be run after updating the object in database + * @param ConnectionInterface $con + */ + public function postUpdate(ConnectionInterface $con = null) + { + + } + + /** + * Code to be run before deleting the object in database + * @param ConnectionInterface $con + * @return boolean + */ + public function preDelete(ConnectionInterface $con = null) + { + return true; + } + + /** + * Code to be run after deleting the object in database + * @param ConnectionInterface $con + */ + public function postDelete(ConnectionInterface $con = null) + { + + } + + + /** + * Derived method to catches calls to undefined methods. + * + * Provides magic import/export method support (fromXML()/toXML(), fromYAML()/toYAML(), etc.). + * Allows to define default __call() behavior if you overwrite __call() + * + * @param string $name + * @param mixed $params + * + * @return array|string + */ + public function __call($name, $params) + { + if (0 === strpos($name, 'get')) { + $virtualColumn = substr($name, 3); + if ($this->hasVirtualColumn($virtualColumn)) { + return $this->getVirtualColumn($virtualColumn); + } + + $virtualColumn = lcfirst($virtualColumn); + if ($this->hasVirtualColumn($virtualColumn)) { + return $this->getVirtualColumn($virtualColumn); + } + } + + if (0 === strpos($name, 'from')) { + $format = substr($name, 4); + + return $this->importFrom($format, reset($params)); + } + + if (0 === strpos($name, 'to')) { + $format = substr($name, 2); + $includeLazyLoadColumns = isset($params[0]) ? $params[0] : true; + + return $this->exportTo($format, $includeLazyLoadColumns); + } + + throw new BadMethodCallException(sprintf('Call to undefined method: %s.', $name)); + } + +} diff --git a/local/modules/ColissimoHomeDelivery/Model/Base/ColissimoHomeDeliveryFreeshippingQuery.php b/local/modules/ColissimoHomeDelivery/Model/Base/ColissimoHomeDeliveryFreeshippingQuery.php new file mode 100644 index 00000000..24f6f393 --- /dev/null +++ b/local/modules/ColissimoHomeDelivery/Model/Base/ColissimoHomeDeliveryFreeshippingQuery.php @@ -0,0 +1,420 @@ +setModelAlias($modelAlias); + } + if ($criteria instanceof Criteria) { + $query->mergeWith($criteria); + } + + return $query; + } + + /** + * Find object by primary key. + * Propel uses the instance pool to skip the database if the object exists. + * Go fast if the query is untouched. + * + * + * $obj = $c->findPk(12, $con); + * + * + * @param mixed $key Primary key to use for the query + * @param ConnectionInterface $con an optional connection object + * + * @return ChildColissimoHomeDeliveryFreeshipping|array|mixed the result, formatted by the current formatter + */ + public function findPk($key, $con = null) + { + if ($key === null) { + return null; + } + if ((null !== ($obj = ColissimoHomeDeliveryFreeshippingTableMap::getInstanceFromPool((string) $key))) && !$this->formatter) { + // the object is already in the instance pool + return $obj; + } + if ($con === null) { + $con = Propel::getServiceContainer()->getReadConnection(ColissimoHomeDeliveryFreeshippingTableMap::DATABASE_NAME); + } + $this->basePreSelect($con); + if ($this->formatter || $this->modelAlias || $this->with || $this->select + || $this->selectColumns || $this->asColumns || $this->selectModifiers + || $this->map || $this->having || $this->joins) { + return $this->findPkComplex($key, $con); + } else { + return $this->findPkSimple($key, $con); + } + } + + /** + * Find object by primary key using raw SQL to go fast. + * Bypass doSelect() and the object formatter by using generated code. + * + * @param mixed $key Primary key to use for the query + * @param ConnectionInterface $con A connection object + * + * @return ChildColissimoHomeDeliveryFreeshipping A model object, or null if the key is not found + */ + protected function findPkSimple($key, $con) + { + $sql = 'SELECT ID, ACTIVE, FREESHIPPING_FROM FROM colissimo_home_delivery_freeshipping WHERE ID = :p0'; + try { + $stmt = $con->prepare($sql); + $stmt->bindValue(':p0', $key, PDO::PARAM_INT); + $stmt->execute(); + } catch (Exception $e) { + Propel::log($e->getMessage(), Propel::LOG_ERR); + throw new PropelException(sprintf('Unable to execute SELECT statement [%s]', $sql), 0, $e); + } + $obj = null; + if ($row = $stmt->fetch(\PDO::FETCH_NUM)) { + $obj = new ChildColissimoHomeDeliveryFreeshipping(); + $obj->hydrate($row); + ColissimoHomeDeliveryFreeshippingTableMap::addInstanceToPool($obj, (string) $key); + } + $stmt->closeCursor(); + + return $obj; + } + + /** + * Find object by primary key. + * + * @param mixed $key Primary key to use for the query + * @param ConnectionInterface $con A connection object + * + * @return ChildColissimoHomeDeliveryFreeshipping|array|mixed the result, formatted by the current formatter + */ + protected function findPkComplex($key, $con) + { + // As the query uses a PK condition, no limit(1) is necessary. + $criteria = $this->isKeepQuery() ? clone $this : $this; + $dataFetcher = $criteria + ->filterByPrimaryKey($key) + ->doSelect($con); + + return $criteria->getFormatter()->init($criteria)->formatOne($dataFetcher); + } + + /** + * Find objects by primary key + * + * $objs = $c->findPks(array(12, 56, 832), $con); + * + * @param array $keys Primary keys to use for the query + * @param ConnectionInterface $con an optional connection object + * + * @return ObjectCollection|array|mixed the list of results, formatted by the current formatter + */ + public function findPks($keys, $con = null) + { + if (null === $con) { + $con = Propel::getServiceContainer()->getReadConnection($this->getDbName()); + } + $this->basePreSelect($con); + $criteria = $this->isKeepQuery() ? clone $this : $this; + $dataFetcher = $criteria + ->filterByPrimaryKeys($keys) + ->doSelect($con); + + return $criteria->getFormatter()->init($criteria)->format($dataFetcher); + } + + /** + * Filter the query by primary key + * + * @param mixed $key Primary key to use for the query + * + * @return ChildColissimoHomeDeliveryFreeshippingQuery The current query, for fluid interface + */ + public function filterByPrimaryKey($key) + { + + return $this->addUsingAlias(ColissimoHomeDeliveryFreeshippingTableMap::ID, $key, Criteria::EQUAL); + } + + /** + * Filter the query by a list of primary keys + * + * @param array $keys The list of primary key to use for the query + * + * @return ChildColissimoHomeDeliveryFreeshippingQuery The current query, for fluid interface + */ + public function filterByPrimaryKeys($keys) + { + + return $this->addUsingAlias(ColissimoHomeDeliveryFreeshippingTableMap::ID, $keys, Criteria::IN); + } + + /** + * Filter the query on the id column + * + * Example usage: + * + * $query->filterById(1234); // WHERE id = 1234 + * $query->filterById(array(12, 34)); // WHERE id IN (12, 34) + * $query->filterById(array('min' => 12)); // WHERE id > 12 + * + * + * @param mixed $id The value to use as filter. + * Use scalar values for equality. + * Use array values for in_array() equivalent. + * Use associative array('min' => $minValue, 'max' => $maxValue) for intervals. + * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL + * + * @return ChildColissimoHomeDeliveryFreeshippingQuery The current query, for fluid interface + */ + public function filterById($id = null, $comparison = null) + { + if (is_array($id)) { + $useMinMax = false; + if (isset($id['min'])) { + $this->addUsingAlias(ColissimoHomeDeliveryFreeshippingTableMap::ID, $id['min'], Criteria::GREATER_EQUAL); + $useMinMax = true; + } + if (isset($id['max'])) { + $this->addUsingAlias(ColissimoHomeDeliveryFreeshippingTableMap::ID, $id['max'], Criteria::LESS_EQUAL); + $useMinMax = true; + } + if ($useMinMax) { + return $this; + } + if (null === $comparison) { + $comparison = Criteria::IN; + } + } + + return $this->addUsingAlias(ColissimoHomeDeliveryFreeshippingTableMap::ID, $id, $comparison); + } + + /** + * Filter the query on the active column + * + * Example usage: + * + * $query->filterByActive(true); // WHERE active = true + * $query->filterByActive('yes'); // WHERE active = true + * + * + * @param boolean|string $active The value to use as filter. + * Non-boolean arguments are converted using the following rules: + * * 1, '1', 'true', 'on', and 'yes' are converted to boolean true + * * 0, '0', 'false', 'off', and 'no' are converted to boolean false + * Check on string values is case insensitive (so 'FaLsE' is seen as 'false'). + * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL + * + * @return ChildColissimoHomeDeliveryFreeshippingQuery The current query, for fluid interface + */ + public function filterByActive($active = null, $comparison = null) + { + if (is_string($active)) { + $active = in_array(strtolower($active), array('false', 'off', '-', 'no', 'n', '0', '')) ? false : true; + } + + return $this->addUsingAlias(ColissimoHomeDeliveryFreeshippingTableMap::ACTIVE, $active, $comparison); + } + + /** + * Filter the query on the freeshipping_from column + * + * Example usage: + * + * $query->filterByFreeshippingFrom(1234); // WHERE freeshipping_from = 1234 + * $query->filterByFreeshippingFrom(array(12, 34)); // WHERE freeshipping_from IN (12, 34) + * $query->filterByFreeshippingFrom(array('min' => 12)); // WHERE freeshipping_from > 12 + * + * + * @param mixed $freeshippingFrom The value to use as filter. + * Use scalar values for equality. + * Use array values for in_array() equivalent. + * Use associative array('min' => $minValue, 'max' => $maxValue) for intervals. + * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL + * + * @return ChildColissimoHomeDeliveryFreeshippingQuery The current query, for fluid interface + */ + public function filterByFreeshippingFrom($freeshippingFrom = null, $comparison = null) + { + if (is_array($freeshippingFrom)) { + $useMinMax = false; + if (isset($freeshippingFrom['min'])) { + $this->addUsingAlias(ColissimoHomeDeliveryFreeshippingTableMap::FREESHIPPING_FROM, $freeshippingFrom['min'], Criteria::GREATER_EQUAL); + $useMinMax = true; + } + if (isset($freeshippingFrom['max'])) { + $this->addUsingAlias(ColissimoHomeDeliveryFreeshippingTableMap::FREESHIPPING_FROM, $freeshippingFrom['max'], Criteria::LESS_EQUAL); + $useMinMax = true; + } + if ($useMinMax) { + return $this; + } + if (null === $comparison) { + $comparison = Criteria::IN; + } + } + + return $this->addUsingAlias(ColissimoHomeDeliveryFreeshippingTableMap::FREESHIPPING_FROM, $freeshippingFrom, $comparison); + } + + /** + * Exclude object from result + * + * @param ChildColissimoHomeDeliveryFreeshipping $colissimoHomeDeliveryFreeshipping Object to remove from the list of results + * + * @return ChildColissimoHomeDeliveryFreeshippingQuery The current query, for fluid interface + */ + public function prune($colissimoHomeDeliveryFreeshipping = null) + { + if ($colissimoHomeDeliveryFreeshipping) { + $this->addUsingAlias(ColissimoHomeDeliveryFreeshippingTableMap::ID, $colissimoHomeDeliveryFreeshipping->getId(), Criteria::NOT_EQUAL); + } + + return $this; + } + + /** + * Deletes all rows from the colissimo_home_delivery_freeshipping table. + * + * @param ConnectionInterface $con the connection to use + * @return int The number of affected rows (if supported by underlying database driver). + */ + public function doDeleteAll(ConnectionInterface $con = null) + { + if (null === $con) { + $con = Propel::getServiceContainer()->getWriteConnection(ColissimoHomeDeliveryFreeshippingTableMap::DATABASE_NAME); + } + $affectedRows = 0; // initialize var to track total num of affected rows + try { + // use transaction because $criteria could contain info + // for more than one table or we could emulating ON DELETE CASCADE, etc. + $con->beginTransaction(); + $affectedRows += parent::doDeleteAll($con); + // Because this db requires some delete cascade/set null emulation, we have to + // clear the cached instance *after* the emulation has happened (since + // instances get re-added by the select statement contained therein). + ColissimoHomeDeliveryFreeshippingTableMap::clearInstancePool(); + ColissimoHomeDeliveryFreeshippingTableMap::clearRelatedInstancePool(); + + $con->commit(); + } catch (PropelException $e) { + $con->rollBack(); + throw $e; + } + + return $affectedRows; + } + + /** + * Performs a DELETE on the database, given a ChildColissimoHomeDeliveryFreeshipping or Criteria object OR a primary key value. + * + * @param mixed $values Criteria or ChildColissimoHomeDeliveryFreeshipping object or primary key or array of primary keys + * which is used to create the DELETE statement + * @param ConnectionInterface $con the connection to use + * @return int The number of affected rows (if supported by underlying database driver). This includes CASCADE-related rows + * if supported by native driver or if emulated using Propel. + * @throws PropelException Any exceptions caught during processing will be + * rethrown wrapped into a PropelException. + */ + public function delete(ConnectionInterface $con = null) + { + if (null === $con) { + $con = Propel::getServiceContainer()->getWriteConnection(ColissimoHomeDeliveryFreeshippingTableMap::DATABASE_NAME); + } + + $criteria = $this; + + // Set the correct dbName + $criteria->setDbName(ColissimoHomeDeliveryFreeshippingTableMap::DATABASE_NAME); + + $affectedRows = 0; // initialize var to track total num of affected rows + + try { + // use transaction because $criteria could contain info + // for more than one table or we could emulating ON DELETE CASCADE, etc. + $con->beginTransaction(); + + + ColissimoHomeDeliveryFreeshippingTableMap::removeInstanceFromPool($criteria); + + $affectedRows += ModelCriteria::delete($con); + ColissimoHomeDeliveryFreeshippingTableMap::clearRelatedInstancePool(); + $con->commit(); + + return $affectedRows; + } catch (PropelException $e) { + $con->rollBack(); + throw $e; + } + } + +} // ColissimoHomeDeliveryFreeshippingQuery diff --git a/local/modules/ColissimoHomeDelivery/Model/Base/ColissimoHomeDeliveryPriceSlices.php b/local/modules/ColissimoHomeDelivery/Model/Base/ColissimoHomeDeliveryPriceSlices.php new file mode 100644 index 00000000..e5b363ad --- /dev/null +++ b/local/modules/ColissimoHomeDelivery/Model/Base/ColissimoHomeDeliveryPriceSlices.php @@ -0,0 +1,1369 @@ +modifiedColumns; + } + + /** + * Has specified column been modified? + * + * @param string $col column fully qualified name (TableMap::TYPE_COLNAME), e.g. Book::AUTHOR_ID + * @return boolean True if $col has been modified. + */ + public function isColumnModified($col) + { + return $this->modifiedColumns && isset($this->modifiedColumns[$col]); + } + + /** + * Get the columns that have been modified in this object. + * @return array A unique list of the modified column names for this object. + */ + public function getModifiedColumns() + { + return $this->modifiedColumns ? array_keys($this->modifiedColumns) : []; + } + + /** + * Returns whether the object has ever been saved. This will + * be false, if the object was retrieved from storage or was created + * and then saved. + * + * @return boolean true, if the object has never been persisted. + */ + public function isNew() + { + return $this->new; + } + + /** + * Setter for the isNew attribute. This method will be called + * by Propel-generated children and objects. + * + * @param boolean $b the state of the object. + */ + public function setNew($b) + { + $this->new = (Boolean) $b; + } + + /** + * Whether this object has been deleted. + * @return boolean The deleted state of this object. + */ + public function isDeleted() + { + return $this->deleted; + } + + /** + * Specify whether this object has been deleted. + * @param boolean $b The deleted state of this object. + * @return void + */ + public function setDeleted($b) + { + $this->deleted = (Boolean) $b; + } + + /** + * Sets the modified state for the object to be false. + * @param string $col If supplied, only the specified column is reset. + * @return void + */ + public function resetModified($col = null) + { + if (null !== $col) { + if (isset($this->modifiedColumns[$col])) { + unset($this->modifiedColumns[$col]); + } + } else { + $this->modifiedColumns = array(); + } + } + + /** + * Compares this with another ColissimoHomeDeliveryPriceSlices instance. If + * obj is an instance of ColissimoHomeDeliveryPriceSlices, delegates to + * equals(ColissimoHomeDeliveryPriceSlices). Otherwise, returns false. + * + * @param mixed $obj The object to compare to. + * @return boolean Whether equal to the object specified. + */ + public function equals($obj) + { + $thisclazz = get_class($this); + if (!is_object($obj) || !($obj instanceof $thisclazz)) { + return false; + } + + if ($this === $obj) { + return true; + } + + if (null === $this->getPrimaryKey() + || null === $obj->getPrimaryKey()) { + return false; + } + + return $this->getPrimaryKey() === $obj->getPrimaryKey(); + } + + /** + * If the primary key is not null, return the hashcode of the + * primary key. Otherwise, return the hash code of the object. + * + * @return int Hashcode + */ + public function hashCode() + { + if (null !== $this->getPrimaryKey()) { + return crc32(serialize($this->getPrimaryKey())); + } + + return crc32(serialize(clone $this)); + } + + /** + * Get the associative array of the virtual columns in this object + * + * @return array + */ + public function getVirtualColumns() + { + return $this->virtualColumns; + } + + /** + * Checks the existence of a virtual column in this object + * + * @param string $name The virtual column name + * @return boolean + */ + public function hasVirtualColumn($name) + { + return array_key_exists($name, $this->virtualColumns); + } + + /** + * Get the value of a virtual column in this object + * + * @param string $name The virtual column name + * @return mixed + * + * @throws PropelException + */ + public function getVirtualColumn($name) + { + if (!$this->hasVirtualColumn($name)) { + throw new PropelException(sprintf('Cannot get value of inexistent virtual column %s.', $name)); + } + + return $this->virtualColumns[$name]; + } + + /** + * Set the value of a virtual column in this object + * + * @param string $name The virtual column name + * @param mixed $value The value to give to the virtual column + * + * @return ColissimoHomeDeliveryPriceSlices The current object, for fluid interface + */ + public function setVirtualColumn($name, $value) + { + $this->virtualColumns[$name] = $value; + + return $this; + } + + /** + * Logs a message using Propel::log(). + * + * @param string $msg + * @param int $priority One of the Propel::LOG_* logging levels + * @return boolean + */ + protected function log($msg, $priority = Propel::LOG_INFO) + { + return Propel::log(get_class($this) . ': ' . $msg, $priority); + } + + /** + * Populate the current object from a string, using a given parser format + * + * $book = new Book(); + * $book->importFrom('JSON', '{"Id":9012,"Title":"Don Juan","ISBN":"0140422161","Price":12.99,"PublisherId":1234,"AuthorId":5678}'); + * + * + * @param mixed $parser A AbstractParser instance, + * or a format name ('XML', 'YAML', 'JSON', 'CSV') + * @param string $data The source data to import from + * + * @return ColissimoHomeDeliveryPriceSlices The current object, for fluid interface + */ + public function importFrom($parser, $data) + { + if (!$parser instanceof AbstractParser) { + $parser = AbstractParser::getParser($parser); + } + + $this->fromArray($parser->toArray($data), TableMap::TYPE_PHPNAME); + + return $this; + } + + /** + * Export the current object properties to a string, using a given parser format + * + * $book = BookQuery::create()->findPk(9012); + * echo $book->exportTo('JSON'); + * => {"Id":9012,"Title":"Don Juan","ISBN":"0140422161","Price":12.99,"PublisherId":1234,"AuthorId":5678}'); + * + * + * @param mixed $parser A AbstractParser instance, or a format name ('XML', 'YAML', 'JSON', 'CSV') + * @param boolean $includeLazyLoadColumns (optional) Whether to include lazy load(ed) columns. Defaults to TRUE. + * @return string The exported data + */ + public function exportTo($parser, $includeLazyLoadColumns = true) + { + if (!$parser instanceof AbstractParser) { + $parser = AbstractParser::getParser($parser); + } + + return $parser->fromArray($this->toArray(TableMap::TYPE_PHPNAME, $includeLazyLoadColumns, array(), true)); + } + + /** + * Clean up internal collections prior to serializing + * Avoids recursive loops that turn into segmentation faults when serializing + */ + public function __sleep() + { + $this->clearAllReferences(); + + return array_keys(get_object_vars($this)); + } + + /** + * Get the [id] column value. + * + * @return int + */ + public function getId() + { + + return $this->id; + } + + /** + * Get the [area_id] column value. + * + * @return int + */ + public function getAreaId() + { + + return $this->area_id; + } + + /** + * Get the [max_weight] column value. + * + * @return double + */ + public function getMaxWeight() + { + + return $this->max_weight; + } + + /** + * Get the [max_price] column value. + * + * @return double + */ + public function getMaxPrice() + { + + return $this->max_price; + } + + /** + * Get the [shipping] column value. + * + * @return double + */ + public function getShipping() + { + + return $this->shipping; + } + + /** + * Set the value of [id] column. + * + * @param int $v new value + * @return \ColissimoHomeDelivery\Model\ColissimoHomeDeliveryPriceSlices The current object (for fluent API support) + */ + public function setId($v) + { + if ($v !== null) { + $v = (int) $v; + } + + if ($this->id !== $v) { + $this->id = $v; + $this->modifiedColumns[ColissimoHomeDeliveryPriceSlicesTableMap::ID] = true; + } + + + return $this; + } // setId() + + /** + * Set the value of [area_id] column. + * + * @param int $v new value + * @return \ColissimoHomeDelivery\Model\ColissimoHomeDeliveryPriceSlices The current object (for fluent API support) + */ + public function setAreaId($v) + { + if ($v !== null) { + $v = (int) $v; + } + + if ($this->area_id !== $v) { + $this->area_id = $v; + $this->modifiedColumns[ColissimoHomeDeliveryPriceSlicesTableMap::AREA_ID] = true; + } + + if ($this->aArea !== null && $this->aArea->getId() !== $v) { + $this->aArea = null; + } + + + return $this; + } // setAreaId() + + /** + * Set the value of [max_weight] column. + * + * @param double $v new value + * @return \ColissimoHomeDelivery\Model\ColissimoHomeDeliveryPriceSlices The current object (for fluent API support) + */ + public function setMaxWeight($v) + { + if ($v !== null) { + $v = (double) $v; + } + + if ($this->max_weight !== $v) { + $this->max_weight = $v; + $this->modifiedColumns[ColissimoHomeDeliveryPriceSlicesTableMap::MAX_WEIGHT] = true; + } + + + return $this; + } // setMaxWeight() + + /** + * Set the value of [max_price] column. + * + * @param double $v new value + * @return \ColissimoHomeDelivery\Model\ColissimoHomeDeliveryPriceSlices The current object (for fluent API support) + */ + public function setMaxPrice($v) + { + if ($v !== null) { + $v = (double) $v; + } + + if ($this->max_price !== $v) { + $this->max_price = $v; + $this->modifiedColumns[ColissimoHomeDeliveryPriceSlicesTableMap::MAX_PRICE] = true; + } + + + return $this; + } // setMaxPrice() + + /** + * Set the value of [shipping] column. + * + * @param double $v new value + * @return \ColissimoHomeDelivery\Model\ColissimoHomeDeliveryPriceSlices The current object (for fluent API support) + */ + public function setShipping($v) + { + if ($v !== null) { + $v = (double) $v; + } + + if ($this->shipping !== $v) { + $this->shipping = $v; + $this->modifiedColumns[ColissimoHomeDeliveryPriceSlicesTableMap::SHIPPING] = true; + } + + + return $this; + } // setShipping() + + /** + * Indicates whether the columns in this object are only set to default values. + * + * This method can be used in conjunction with isModified() to indicate whether an object is both + * modified _and_ has some values set which are non-default. + * + * @return boolean Whether the columns in this object are only been set with default values. + */ + public function hasOnlyDefaultValues() + { + // otherwise, everything was equal, so return TRUE + return true; + } // hasOnlyDefaultValues() + + /** + * Hydrates (populates) the object variables with values from the database resultset. + * + * An offset (0-based "start column") is specified so that objects can be hydrated + * with a subset of the columns in the resultset rows. This is needed, for example, + * for results of JOIN queries where the resultset row includes columns from two or + * more tables. + * + * @param array $row The row returned by DataFetcher->fetch(). + * @param int $startcol 0-based offset column which indicates which restultset column to start with. + * @param boolean $rehydrate Whether this object is being re-hydrated from the database. + * @param string $indexType The index type of $row. Mostly DataFetcher->getIndexType(). + One of the class type constants TableMap::TYPE_PHPNAME, TableMap::TYPE_STUDLYPHPNAME + * TableMap::TYPE_COLNAME, TableMap::TYPE_FIELDNAME, TableMap::TYPE_NUM. + * + * @return int next starting column + * @throws PropelException - Any caught Exception will be rewrapped as a PropelException. + */ + public function hydrate($row, $startcol = 0, $rehydrate = false, $indexType = TableMap::TYPE_NUM) + { + try { + + + $col = $row[TableMap::TYPE_NUM == $indexType ? 0 + $startcol : ColissimoHomeDeliveryPriceSlicesTableMap::translateFieldName('Id', TableMap::TYPE_PHPNAME, $indexType)]; + $this->id = (null !== $col) ? (int) $col : null; + + $col = $row[TableMap::TYPE_NUM == $indexType ? 1 + $startcol : ColissimoHomeDeliveryPriceSlicesTableMap::translateFieldName('AreaId', TableMap::TYPE_PHPNAME, $indexType)]; + $this->area_id = (null !== $col) ? (int) $col : null; + + $col = $row[TableMap::TYPE_NUM == $indexType ? 2 + $startcol : ColissimoHomeDeliveryPriceSlicesTableMap::translateFieldName('MaxWeight', TableMap::TYPE_PHPNAME, $indexType)]; + $this->max_weight = (null !== $col) ? (double) $col : null; + + $col = $row[TableMap::TYPE_NUM == $indexType ? 3 + $startcol : ColissimoHomeDeliveryPriceSlicesTableMap::translateFieldName('MaxPrice', TableMap::TYPE_PHPNAME, $indexType)]; + $this->max_price = (null !== $col) ? (double) $col : null; + + $col = $row[TableMap::TYPE_NUM == $indexType ? 4 + $startcol : ColissimoHomeDeliveryPriceSlicesTableMap::translateFieldName('Shipping', TableMap::TYPE_PHPNAME, $indexType)]; + $this->shipping = (null !== $col) ? (double) $col : null; + $this->resetModified(); + + $this->setNew(false); + + if ($rehydrate) { + $this->ensureConsistency(); + } + + return $startcol + 5; // 5 = ColissimoHomeDeliveryPriceSlicesTableMap::NUM_HYDRATE_COLUMNS. + + } catch (Exception $e) { + throw new PropelException("Error populating \ColissimoHomeDelivery\Model\ColissimoHomeDeliveryPriceSlices object", 0, $e); + } + } + + /** + * Checks and repairs the internal consistency of the object. + * + * This method is executed after an already-instantiated object is re-hydrated + * from the database. It exists to check any foreign keys to make sure that + * the objects related to the current object are correct based on foreign key. + * + * You can override this method in the stub class, but you should always invoke + * the base method from the overridden method (i.e. parent::ensureConsistency()), + * in case your model changes. + * + * @throws PropelException + */ + public function ensureConsistency() + { + if ($this->aArea !== null && $this->area_id !== $this->aArea->getId()) { + $this->aArea = null; + } + } // ensureConsistency + + /** + * Reloads this object from datastore based on primary key and (optionally) resets all associated objects. + * + * This will only work if the object has been saved and has a valid primary key set. + * + * @param boolean $deep (optional) Whether to also de-associated any related objects. + * @param ConnectionInterface $con (optional) The ConnectionInterface connection to use. + * @return void + * @throws PropelException - if this object is deleted, unsaved or doesn't have pk match in db + */ + public function reload($deep = false, ConnectionInterface $con = null) + { + if ($this->isDeleted()) { + throw new PropelException("Cannot reload a deleted object."); + } + + if ($this->isNew()) { + throw new PropelException("Cannot reload an unsaved object."); + } + + if ($con === null) { + $con = Propel::getServiceContainer()->getReadConnection(ColissimoHomeDeliveryPriceSlicesTableMap::DATABASE_NAME); + } + + // We don't need to alter the object instance pool; we're just modifying this instance + // already in the pool. + + $dataFetcher = ChildColissimoHomeDeliveryPriceSlicesQuery::create(null, $this->buildPkeyCriteria())->setFormatter(ModelCriteria::FORMAT_STATEMENT)->find($con); + $row = $dataFetcher->fetch(); + $dataFetcher->close(); + if (!$row) { + throw new PropelException('Cannot find matching row in the database to reload object values.'); + } + $this->hydrate($row, 0, true, $dataFetcher->getIndexType()); // rehydrate + + if ($deep) { // also de-associate any related objects? + + $this->aArea = null; + } // if (deep) + } + + /** + * Removes this object from datastore and sets delete attribute. + * + * @param ConnectionInterface $con + * @return void + * @throws PropelException + * @see ColissimoHomeDeliveryPriceSlices::setDeleted() + * @see ColissimoHomeDeliveryPriceSlices::isDeleted() + */ + public function delete(ConnectionInterface $con = null) + { + if ($this->isDeleted()) { + throw new PropelException("This object has already been deleted."); + } + + if ($con === null) { + $con = Propel::getServiceContainer()->getWriteConnection(ColissimoHomeDeliveryPriceSlicesTableMap::DATABASE_NAME); + } + + $con->beginTransaction(); + try { + $deleteQuery = ChildColissimoHomeDeliveryPriceSlicesQuery::create() + ->filterByPrimaryKey($this->getPrimaryKey()); + $ret = $this->preDelete($con); + if ($ret) { + $deleteQuery->delete($con); + $this->postDelete($con); + $con->commit(); + $this->setDeleted(true); + } else { + $con->commit(); + } + } catch (Exception $e) { + $con->rollBack(); + throw $e; + } + } + + /** + * Persists this object to the database. + * + * If the object is new, it inserts it; otherwise an update is performed. + * All modified related objects will also be persisted in the doSave() + * method. This method wraps all precipitate database operations in a + * single transaction. + * + * @param ConnectionInterface $con + * @return int The number of rows affected by this insert/update and any referring fk objects' save() operations. + * @throws PropelException + * @see doSave() + */ + public function save(ConnectionInterface $con = null) + { + if ($this->isDeleted()) { + throw new PropelException("You cannot save an object that has been deleted."); + } + + if ($con === null) { + $con = Propel::getServiceContainer()->getWriteConnection(ColissimoHomeDeliveryPriceSlicesTableMap::DATABASE_NAME); + } + + $con->beginTransaction(); + $isInsert = $this->isNew(); + try { + $ret = $this->preSave($con); + if ($isInsert) { + $ret = $ret && $this->preInsert($con); + } else { + $ret = $ret && $this->preUpdate($con); + } + if ($ret) { + $affectedRows = $this->doSave($con); + if ($isInsert) { + $this->postInsert($con); + } else { + $this->postUpdate($con); + } + $this->postSave($con); + ColissimoHomeDeliveryPriceSlicesTableMap::addInstanceToPool($this); + } else { + $affectedRows = 0; + } + $con->commit(); + + return $affectedRows; + } catch (Exception $e) { + $con->rollBack(); + throw $e; + } + } + + /** + * Performs the work of inserting or updating the row in the database. + * + * If the object is new, it inserts it; otherwise an update is performed. + * All related objects are also updated in this method. + * + * @param ConnectionInterface $con + * @return int The number of rows affected by this insert/update and any referring fk objects' save() operations. + * @throws PropelException + * @see save() + */ + protected function doSave(ConnectionInterface $con) + { + $affectedRows = 0; // initialize var to track total num of affected rows + if (!$this->alreadyInSave) { + $this->alreadyInSave = true; + + // We call the save method on the following object(s) if they + // were passed to this object by their corresponding set + // method. This object relates to these object(s) by a + // foreign key reference. + + if ($this->aArea !== null) { + if ($this->aArea->isModified() || $this->aArea->isNew()) { + $affectedRows += $this->aArea->save($con); + } + $this->setArea($this->aArea); + } + + if ($this->isNew() || $this->isModified()) { + // persist changes + if ($this->isNew()) { + $this->doInsert($con); + } else { + $this->doUpdate($con); + } + $affectedRows += 1; + $this->resetModified(); + } + + $this->alreadyInSave = false; + + } + + return $affectedRows; + } // doSave() + + /** + * Insert the row in the database. + * + * @param ConnectionInterface $con + * + * @throws PropelException + * @see doSave() + */ + protected function doInsert(ConnectionInterface $con) + { + $modifiedColumns = array(); + $index = 0; + + $this->modifiedColumns[ColissimoHomeDeliveryPriceSlicesTableMap::ID] = true; + if (null !== $this->id) { + throw new PropelException('Cannot insert a value for auto-increment primary key (' . ColissimoHomeDeliveryPriceSlicesTableMap::ID . ')'); + } + + // check the columns in natural order for more readable SQL queries + if ($this->isColumnModified(ColissimoHomeDeliveryPriceSlicesTableMap::ID)) { + $modifiedColumns[':p' . $index++] = 'ID'; + } + if ($this->isColumnModified(ColissimoHomeDeliveryPriceSlicesTableMap::AREA_ID)) { + $modifiedColumns[':p' . $index++] = 'AREA_ID'; + } + if ($this->isColumnModified(ColissimoHomeDeliveryPriceSlicesTableMap::MAX_WEIGHT)) { + $modifiedColumns[':p' . $index++] = 'MAX_WEIGHT'; + } + if ($this->isColumnModified(ColissimoHomeDeliveryPriceSlicesTableMap::MAX_PRICE)) { + $modifiedColumns[':p' . $index++] = 'MAX_PRICE'; + } + if ($this->isColumnModified(ColissimoHomeDeliveryPriceSlicesTableMap::SHIPPING)) { + $modifiedColumns[':p' . $index++] = 'SHIPPING'; + } + + $sql = sprintf( + 'INSERT INTO colissimo_home_delivery_price_slices (%s) VALUES (%s)', + implode(', ', $modifiedColumns), + implode(', ', array_keys($modifiedColumns)) + ); + + try { + $stmt = $con->prepare($sql); + foreach ($modifiedColumns as $identifier => $columnName) { + switch ($columnName) { + case 'ID': + $stmt->bindValue($identifier, $this->id, PDO::PARAM_INT); + break; + case 'AREA_ID': + $stmt->bindValue($identifier, $this->area_id, PDO::PARAM_INT); + break; + case 'MAX_WEIGHT': + $stmt->bindValue($identifier, $this->max_weight, PDO::PARAM_STR); + break; + case 'MAX_PRICE': + $stmt->bindValue($identifier, $this->max_price, PDO::PARAM_STR); + break; + case 'SHIPPING': + $stmt->bindValue($identifier, $this->shipping, PDO::PARAM_STR); + break; + } + } + $stmt->execute(); + } catch (Exception $e) { + Propel::log($e->getMessage(), Propel::LOG_ERR); + throw new PropelException(sprintf('Unable to execute INSERT statement [%s]', $sql), 0, $e); + } + + try { + $pk = $con->lastInsertId(); + } catch (Exception $e) { + throw new PropelException('Unable to get autoincrement id.', 0, $e); + } + $this->setId($pk); + + $this->setNew(false); + } + + /** + * Update the row in the database. + * + * @param ConnectionInterface $con + * + * @return Integer Number of updated rows + * @see doSave() + */ + protected function doUpdate(ConnectionInterface $con) + { + $selectCriteria = $this->buildPkeyCriteria(); + $valuesCriteria = $this->buildCriteria(); + + return $selectCriteria->doUpdate($valuesCriteria, $con); + } + + /** + * Retrieves a field from the object by name passed in as a string. + * + * @param string $name name + * @param string $type The type of fieldname the $name is of: + * one of the class type constants TableMap::TYPE_PHPNAME, TableMap::TYPE_STUDLYPHPNAME + * TableMap::TYPE_COLNAME, TableMap::TYPE_FIELDNAME, TableMap::TYPE_NUM. + * Defaults to TableMap::TYPE_PHPNAME. + * @return mixed Value of field. + */ + public function getByName($name, $type = TableMap::TYPE_PHPNAME) + { + $pos = ColissimoHomeDeliveryPriceSlicesTableMap::translateFieldName($name, $type, TableMap::TYPE_NUM); + $field = $this->getByPosition($pos); + + return $field; + } + + /** + * Retrieves a field from the object by Position as specified in the xml schema. + * Zero-based. + * + * @param int $pos position in xml schema + * @return mixed Value of field at $pos + */ + public function getByPosition($pos) + { + switch ($pos) { + case 0: + return $this->getId(); + break; + case 1: + return $this->getAreaId(); + break; + case 2: + return $this->getMaxWeight(); + break; + case 3: + return $this->getMaxPrice(); + break; + case 4: + return $this->getShipping(); + break; + default: + return null; + break; + } // switch() + } + + /** + * Exports the object as an array. + * + * You can specify the key type of the array by passing one of the class + * type constants. + * + * @param string $keyType (optional) One of the class type constants TableMap::TYPE_PHPNAME, TableMap::TYPE_STUDLYPHPNAME, + * TableMap::TYPE_COLNAME, TableMap::TYPE_FIELDNAME, TableMap::TYPE_NUM. + * Defaults to TableMap::TYPE_PHPNAME. + * @param boolean $includeLazyLoadColumns (optional) Whether to include lazy loaded columns. Defaults to TRUE. + * @param array $alreadyDumpedObjects List of objects to skip to avoid recursion + * @param boolean $includeForeignObjects (optional) Whether to include hydrated related objects. Default to FALSE. + * + * @return array an associative array containing the field names (as keys) and field values + */ + public function toArray($keyType = TableMap::TYPE_PHPNAME, $includeLazyLoadColumns = true, $alreadyDumpedObjects = array(), $includeForeignObjects = false) + { + if (isset($alreadyDumpedObjects['ColissimoHomeDeliveryPriceSlices'][$this->getPrimaryKey()])) { + return '*RECURSION*'; + } + $alreadyDumpedObjects['ColissimoHomeDeliveryPriceSlices'][$this->getPrimaryKey()] = true; + $keys = ColissimoHomeDeliveryPriceSlicesTableMap::getFieldNames($keyType); + $result = array( + $keys[0] => $this->getId(), + $keys[1] => $this->getAreaId(), + $keys[2] => $this->getMaxWeight(), + $keys[3] => $this->getMaxPrice(), + $keys[4] => $this->getShipping(), + ); + $virtualColumns = $this->virtualColumns; + foreach ($virtualColumns as $key => $virtualColumn) { + $result[$key] = $virtualColumn; + } + + if ($includeForeignObjects) { + if (null !== $this->aArea) { + $result['Area'] = $this->aArea->toArray($keyType, $includeLazyLoadColumns, $alreadyDumpedObjects, true); + } + } + + return $result; + } + + /** + * Sets a field from the object by name passed in as a string. + * + * @param string $name + * @param mixed $value field value + * @param string $type The type of fieldname the $name is of: + * one of the class type constants TableMap::TYPE_PHPNAME, TableMap::TYPE_STUDLYPHPNAME + * TableMap::TYPE_COLNAME, TableMap::TYPE_FIELDNAME, TableMap::TYPE_NUM. + * Defaults to TableMap::TYPE_PHPNAME. + * @return void + */ + public function setByName($name, $value, $type = TableMap::TYPE_PHPNAME) + { + $pos = ColissimoHomeDeliveryPriceSlicesTableMap::translateFieldName($name, $type, TableMap::TYPE_NUM); + + return $this->setByPosition($pos, $value); + } + + /** + * Sets a field from the object by Position as specified in the xml schema. + * Zero-based. + * + * @param int $pos position in xml schema + * @param mixed $value field value + * @return void + */ + public function setByPosition($pos, $value) + { + switch ($pos) { + case 0: + $this->setId($value); + break; + case 1: + $this->setAreaId($value); + break; + case 2: + $this->setMaxWeight($value); + break; + case 3: + $this->setMaxPrice($value); + break; + case 4: + $this->setShipping($value); + break; + } // switch() + } + + /** + * Populates the object using an array. + * + * This is particularly useful when populating an object from one of the + * request arrays (e.g. $_POST). This method goes through the column + * names, checking to see whether a matching key exists in populated + * array. If so the setByName() method is called for that column. + * + * You can specify the key type of the array by additionally passing one + * of the class type constants TableMap::TYPE_PHPNAME, TableMap::TYPE_STUDLYPHPNAME, + * TableMap::TYPE_COLNAME, TableMap::TYPE_FIELDNAME, TableMap::TYPE_NUM. + * The default key type is the column's TableMap::TYPE_PHPNAME. + * + * @param array $arr An array to populate the object from. + * @param string $keyType The type of keys the array uses. + * @return void + */ + public function fromArray($arr, $keyType = TableMap::TYPE_PHPNAME) + { + $keys = ColissimoHomeDeliveryPriceSlicesTableMap::getFieldNames($keyType); + + if (array_key_exists($keys[0], $arr)) $this->setId($arr[$keys[0]]); + if (array_key_exists($keys[1], $arr)) $this->setAreaId($arr[$keys[1]]); + if (array_key_exists($keys[2], $arr)) $this->setMaxWeight($arr[$keys[2]]); + if (array_key_exists($keys[3], $arr)) $this->setMaxPrice($arr[$keys[3]]); + if (array_key_exists($keys[4], $arr)) $this->setShipping($arr[$keys[4]]); + } + + /** + * Build a Criteria object containing the values of all modified columns in this object. + * + * @return Criteria The Criteria object containing all modified values. + */ + public function buildCriteria() + { + $criteria = new Criteria(ColissimoHomeDeliveryPriceSlicesTableMap::DATABASE_NAME); + + if ($this->isColumnModified(ColissimoHomeDeliveryPriceSlicesTableMap::ID)) $criteria->add(ColissimoHomeDeliveryPriceSlicesTableMap::ID, $this->id); + if ($this->isColumnModified(ColissimoHomeDeliveryPriceSlicesTableMap::AREA_ID)) $criteria->add(ColissimoHomeDeliveryPriceSlicesTableMap::AREA_ID, $this->area_id); + if ($this->isColumnModified(ColissimoHomeDeliveryPriceSlicesTableMap::MAX_WEIGHT)) $criteria->add(ColissimoHomeDeliveryPriceSlicesTableMap::MAX_WEIGHT, $this->max_weight); + if ($this->isColumnModified(ColissimoHomeDeliveryPriceSlicesTableMap::MAX_PRICE)) $criteria->add(ColissimoHomeDeliveryPriceSlicesTableMap::MAX_PRICE, $this->max_price); + if ($this->isColumnModified(ColissimoHomeDeliveryPriceSlicesTableMap::SHIPPING)) $criteria->add(ColissimoHomeDeliveryPriceSlicesTableMap::SHIPPING, $this->shipping); + + return $criteria; + } + + /** + * Builds a Criteria object containing the primary key for this object. + * + * Unlike buildCriteria() this method includes the primary key values regardless + * of whether or not they have been modified. + * + * @return Criteria The Criteria object containing value(s) for primary key(s). + */ + public function buildPkeyCriteria() + { + $criteria = new Criteria(ColissimoHomeDeliveryPriceSlicesTableMap::DATABASE_NAME); + $criteria->add(ColissimoHomeDeliveryPriceSlicesTableMap::ID, $this->id); + + return $criteria; + } + + /** + * Returns the primary key for this object (row). + * @return int + */ + public function getPrimaryKey() + { + return $this->getId(); + } + + /** + * Generic method to set the primary key (id column). + * + * @param int $key Primary key. + * @return void + */ + public function setPrimaryKey($key) + { + $this->setId($key); + } + + /** + * Returns true if the primary key for this object is null. + * @return boolean + */ + public function isPrimaryKeyNull() + { + + return null === $this->getId(); + } + + /** + * Sets contents of passed object to values from current object. + * + * If desired, this method can also make copies of all associated (fkey referrers) + * objects. + * + * @param object $copyObj An object of \ColissimoHomeDelivery\Model\ColissimoHomeDeliveryPriceSlices (or compatible) type. + * @param boolean $deepCopy Whether to also copy all rows that refer (by fkey) to the current row. + * @param boolean $makeNew Whether to reset autoincrement PKs and make the object new. + * @throws PropelException + */ + public function copyInto($copyObj, $deepCopy = false, $makeNew = true) + { + $copyObj->setAreaId($this->getAreaId()); + $copyObj->setMaxWeight($this->getMaxWeight()); + $copyObj->setMaxPrice($this->getMaxPrice()); + $copyObj->setShipping($this->getShipping()); + if ($makeNew) { + $copyObj->setNew(true); + $copyObj->setId(NULL); // this is a auto-increment column, so set to default value + } + } + + /** + * Makes a copy of this object that will be inserted as a new row in table when saved. + * It creates a new object filling in the simple attributes, but skipping any primary + * keys that are defined for the table. + * + * If desired, this method can also make copies of all associated (fkey referrers) + * objects. + * + * @param boolean $deepCopy Whether to also copy all rows that refer (by fkey) to the current row. + * @return \ColissimoHomeDelivery\Model\ColissimoHomeDeliveryPriceSlices Clone of current object. + * @throws PropelException + */ + public function copy($deepCopy = false) + { + // we use get_class(), because this might be a subclass + $clazz = get_class($this); + $copyObj = new $clazz(); + $this->copyInto($copyObj, $deepCopy); + + return $copyObj; + } + + /** + * Declares an association between this object and a ChildArea object. + * + * @param ChildArea $v + * @return \ColissimoHomeDelivery\Model\ColissimoHomeDeliveryPriceSlices The current object (for fluent API support) + * @throws PropelException + */ + public function setArea(ChildArea $v = null) + { + if ($v === null) { + $this->setAreaId(NULL); + } else { + $this->setAreaId($v->getId()); + } + + $this->aArea = $v; + + // Add binding for other direction of this n:n relationship. + // If this object has already been added to the ChildArea object, it will not be re-added. + if ($v !== null) { + $v->addColissimoHomeDeliveryPriceSlices($this); + } + + + return $this; + } + + + /** + * Get the associated ChildArea object + * + * @param ConnectionInterface $con Optional Connection object. + * @return ChildArea The associated ChildArea object. + * @throws PropelException + */ + public function getArea(ConnectionInterface $con = null) + { + if ($this->aArea === null && ($this->area_id !== null)) { + $this->aArea = AreaQuery::create()->findPk($this->area_id, $con); + /* The following can be used additionally to + guarantee the related object contains a reference + to this object. This level of coupling may, however, be + undesirable since it could result in an only partially populated collection + in the referenced object. + $this->aArea->addColissimoHomeDeliveryPriceSlicess($this); + */ + } + + return $this->aArea; + } + + /** + * Clears the current object and sets all attributes to their default values + */ + public function clear() + { + $this->id = null; + $this->area_id = null; + $this->max_weight = null; + $this->max_price = null; + $this->shipping = null; + $this->alreadyInSave = false; + $this->clearAllReferences(); + $this->resetModified(); + $this->setNew(true); + $this->setDeleted(false); + } + + /** + * Resets all references to other model objects or collections of model objects. + * + * This method is a user-space workaround for PHP's inability to garbage collect + * objects with circular references (even in PHP 5.3). This is currently necessary + * when using Propel in certain daemon or large-volume/high-memory operations. + * + * @param boolean $deep Whether to also clear the references on all referrer objects. + */ + public function clearAllReferences($deep = false) + { + if ($deep) { + } // if ($deep) + + $this->aArea = null; + } + + /** + * Return the string representation of this object + * + * @return string + */ + public function __toString() + { + return (string) $this->exportTo(ColissimoHomeDeliveryPriceSlicesTableMap::DEFAULT_STRING_FORMAT); + } + + /** + * Code to be run before persisting the object + * @param ConnectionInterface $con + * @return boolean + */ + public function preSave(ConnectionInterface $con = null) + { + return true; + } + + /** + * Code to be run after persisting the object + * @param ConnectionInterface $con + */ + public function postSave(ConnectionInterface $con = null) + { + + } + + /** + * Code to be run before inserting to database + * @param ConnectionInterface $con + * @return boolean + */ + public function preInsert(ConnectionInterface $con = null) + { + return true; + } + + /** + * Code to be run after inserting to database + * @param ConnectionInterface $con + */ + public function postInsert(ConnectionInterface $con = null) + { + + } + + /** + * Code to be run before updating the object in database + * @param ConnectionInterface $con + * @return boolean + */ + public function preUpdate(ConnectionInterface $con = null) + { + return true; + } + + /** + * Code to be run after updating the object in database + * @param ConnectionInterface $con + */ + public function postUpdate(ConnectionInterface $con = null) + { + + } + + /** + * Code to be run before deleting the object in database + * @param ConnectionInterface $con + * @return boolean + */ + public function preDelete(ConnectionInterface $con = null) + { + return true; + } + + /** + * Code to be run after deleting the object in database + * @param ConnectionInterface $con + */ + public function postDelete(ConnectionInterface $con = null) + { + + } + + + /** + * Derived method to catches calls to undefined methods. + * + * Provides magic import/export method support (fromXML()/toXML(), fromYAML()/toYAML(), etc.). + * Allows to define default __call() behavior if you overwrite __call() + * + * @param string $name + * @param mixed $params + * + * @return array|string + */ + public function __call($name, $params) + { + if (0 === strpos($name, 'get')) { + $virtualColumn = substr($name, 3); + if ($this->hasVirtualColumn($virtualColumn)) { + return $this->getVirtualColumn($virtualColumn); + } + + $virtualColumn = lcfirst($virtualColumn); + if ($this->hasVirtualColumn($virtualColumn)) { + return $this->getVirtualColumn($virtualColumn); + } + } + + if (0 === strpos($name, 'from')) { + $format = substr($name, 4); + + return $this->importFrom($format, reset($params)); + } + + if (0 === strpos($name, 'to')) { + $format = substr($name, 2); + $includeLazyLoadColumns = isset($params[0]) ? $params[0] : true; + + return $this->exportTo($format, $includeLazyLoadColumns); + } + + throw new BadMethodCallException(sprintf('Call to undefined method: %s.', $name)); + } + +} diff --git a/local/modules/ColissimoHomeDelivery/Model/Base/ColissimoHomeDeliveryPriceSlicesQuery.php b/local/modules/ColissimoHomeDelivery/Model/Base/ColissimoHomeDeliveryPriceSlicesQuery.php new file mode 100644 index 00000000..745b1ba3 --- /dev/null +++ b/local/modules/ColissimoHomeDelivery/Model/Base/ColissimoHomeDeliveryPriceSlicesQuery.php @@ -0,0 +1,609 @@ +setModelAlias($modelAlias); + } + if ($criteria instanceof Criteria) { + $query->mergeWith($criteria); + } + + return $query; + } + + /** + * Find object by primary key. + * Propel uses the instance pool to skip the database if the object exists. + * Go fast if the query is untouched. + * + * + * $obj = $c->findPk(12, $con); + * + * + * @param mixed $key Primary key to use for the query + * @param ConnectionInterface $con an optional connection object + * + * @return ChildColissimoHomeDeliveryPriceSlices|array|mixed the result, formatted by the current formatter + */ + public function findPk($key, $con = null) + { + if ($key === null) { + return null; + } + if ((null !== ($obj = ColissimoHomeDeliveryPriceSlicesTableMap::getInstanceFromPool((string) $key))) && !$this->formatter) { + // the object is already in the instance pool + return $obj; + } + if ($con === null) { + $con = Propel::getServiceContainer()->getReadConnection(ColissimoHomeDeliveryPriceSlicesTableMap::DATABASE_NAME); + } + $this->basePreSelect($con); + if ($this->formatter || $this->modelAlias || $this->with || $this->select + || $this->selectColumns || $this->asColumns || $this->selectModifiers + || $this->map || $this->having || $this->joins) { + return $this->findPkComplex($key, $con); + } else { + return $this->findPkSimple($key, $con); + } + } + + /** + * Find object by primary key using raw SQL to go fast. + * Bypass doSelect() and the object formatter by using generated code. + * + * @param mixed $key Primary key to use for the query + * @param ConnectionInterface $con A connection object + * + * @return ChildColissimoHomeDeliveryPriceSlices A model object, or null if the key is not found + */ + protected function findPkSimple($key, $con) + { + $sql = 'SELECT ID, AREA_ID, MAX_WEIGHT, MAX_PRICE, SHIPPING FROM colissimo_home_delivery_price_slices WHERE ID = :p0'; + try { + $stmt = $con->prepare($sql); + $stmt->bindValue(':p0', $key, PDO::PARAM_INT); + $stmt->execute(); + } catch (Exception $e) { + Propel::log($e->getMessage(), Propel::LOG_ERR); + throw new PropelException(sprintf('Unable to execute SELECT statement [%s]', $sql), 0, $e); + } + $obj = null; + if ($row = $stmt->fetch(\PDO::FETCH_NUM)) { + $obj = new ChildColissimoHomeDeliveryPriceSlices(); + $obj->hydrate($row); + ColissimoHomeDeliveryPriceSlicesTableMap::addInstanceToPool($obj, (string) $key); + } + $stmt->closeCursor(); + + return $obj; + } + + /** + * Find object by primary key. + * + * @param mixed $key Primary key to use for the query + * @param ConnectionInterface $con A connection object + * + * @return ChildColissimoHomeDeliveryPriceSlices|array|mixed the result, formatted by the current formatter + */ + protected function findPkComplex($key, $con) + { + // As the query uses a PK condition, no limit(1) is necessary. + $criteria = $this->isKeepQuery() ? clone $this : $this; + $dataFetcher = $criteria + ->filterByPrimaryKey($key) + ->doSelect($con); + + return $criteria->getFormatter()->init($criteria)->formatOne($dataFetcher); + } + + /** + * Find objects by primary key + * + * $objs = $c->findPks(array(12, 56, 832), $con); + * + * @param array $keys Primary keys to use for the query + * @param ConnectionInterface $con an optional connection object + * + * @return ObjectCollection|array|mixed the list of results, formatted by the current formatter + */ + public function findPks($keys, $con = null) + { + if (null === $con) { + $con = Propel::getServiceContainer()->getReadConnection($this->getDbName()); + } + $this->basePreSelect($con); + $criteria = $this->isKeepQuery() ? clone $this : $this; + $dataFetcher = $criteria + ->filterByPrimaryKeys($keys) + ->doSelect($con); + + return $criteria->getFormatter()->init($criteria)->format($dataFetcher); + } + + /** + * Filter the query by primary key + * + * @param mixed $key Primary key to use for the query + * + * @return ChildColissimoHomeDeliveryPriceSlicesQuery The current query, for fluid interface + */ + public function filterByPrimaryKey($key) + { + + return $this->addUsingAlias(ColissimoHomeDeliveryPriceSlicesTableMap::ID, $key, Criteria::EQUAL); + } + + /** + * Filter the query by a list of primary keys + * + * @param array $keys The list of primary key to use for the query + * + * @return ChildColissimoHomeDeliveryPriceSlicesQuery The current query, for fluid interface + */ + public function filterByPrimaryKeys($keys) + { + + return $this->addUsingAlias(ColissimoHomeDeliveryPriceSlicesTableMap::ID, $keys, Criteria::IN); + } + + /** + * Filter the query on the id column + * + * Example usage: + * + * $query->filterById(1234); // WHERE id = 1234 + * $query->filterById(array(12, 34)); // WHERE id IN (12, 34) + * $query->filterById(array('min' => 12)); // WHERE id > 12 + * + * + * @param mixed $id The value to use as filter. + * Use scalar values for equality. + * Use array values for in_array() equivalent. + * Use associative array('min' => $minValue, 'max' => $maxValue) for intervals. + * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL + * + * @return ChildColissimoHomeDeliveryPriceSlicesQuery The current query, for fluid interface + */ + public function filterById($id = null, $comparison = null) + { + if (is_array($id)) { + $useMinMax = false; + if (isset($id['min'])) { + $this->addUsingAlias(ColissimoHomeDeliveryPriceSlicesTableMap::ID, $id['min'], Criteria::GREATER_EQUAL); + $useMinMax = true; + } + if (isset($id['max'])) { + $this->addUsingAlias(ColissimoHomeDeliveryPriceSlicesTableMap::ID, $id['max'], Criteria::LESS_EQUAL); + $useMinMax = true; + } + if ($useMinMax) { + return $this; + } + if (null === $comparison) { + $comparison = Criteria::IN; + } + } + + return $this->addUsingAlias(ColissimoHomeDeliveryPriceSlicesTableMap::ID, $id, $comparison); + } + + /** + * Filter the query on the area_id column + * + * Example usage: + * + * $query->filterByAreaId(1234); // WHERE area_id = 1234 + * $query->filterByAreaId(array(12, 34)); // WHERE area_id IN (12, 34) + * $query->filterByAreaId(array('min' => 12)); // WHERE area_id > 12 + * + * + * @see filterByArea() + * + * @param mixed $areaId The value to use as filter. + * Use scalar values for equality. + * Use array values for in_array() equivalent. + * Use associative array('min' => $minValue, 'max' => $maxValue) for intervals. + * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL + * + * @return ChildColissimoHomeDeliveryPriceSlicesQuery The current query, for fluid interface + */ + public function filterByAreaId($areaId = null, $comparison = null) + { + if (is_array($areaId)) { + $useMinMax = false; + if (isset($areaId['min'])) { + $this->addUsingAlias(ColissimoHomeDeliveryPriceSlicesTableMap::AREA_ID, $areaId['min'], Criteria::GREATER_EQUAL); + $useMinMax = true; + } + if (isset($areaId['max'])) { + $this->addUsingAlias(ColissimoHomeDeliveryPriceSlicesTableMap::AREA_ID, $areaId['max'], Criteria::LESS_EQUAL); + $useMinMax = true; + } + if ($useMinMax) { + return $this; + } + if (null === $comparison) { + $comparison = Criteria::IN; + } + } + + return $this->addUsingAlias(ColissimoHomeDeliveryPriceSlicesTableMap::AREA_ID, $areaId, $comparison); + } + + /** + * Filter the query on the max_weight column + * + * Example usage: + * + * $query->filterByMaxWeight(1234); // WHERE max_weight = 1234 + * $query->filterByMaxWeight(array(12, 34)); // WHERE max_weight IN (12, 34) + * $query->filterByMaxWeight(array('min' => 12)); // WHERE max_weight > 12 + * + * + * @param mixed $maxWeight The value to use as filter. + * Use scalar values for equality. + * Use array values for in_array() equivalent. + * Use associative array('min' => $minValue, 'max' => $maxValue) for intervals. + * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL + * + * @return ChildColissimoHomeDeliveryPriceSlicesQuery The current query, for fluid interface + */ + public function filterByMaxWeight($maxWeight = null, $comparison = null) + { + if (is_array($maxWeight)) { + $useMinMax = false; + if (isset($maxWeight['min'])) { + $this->addUsingAlias(ColissimoHomeDeliveryPriceSlicesTableMap::MAX_WEIGHT, $maxWeight['min'], Criteria::GREATER_EQUAL); + $useMinMax = true; + } + if (isset($maxWeight['max'])) { + $this->addUsingAlias(ColissimoHomeDeliveryPriceSlicesTableMap::MAX_WEIGHT, $maxWeight['max'], Criteria::LESS_EQUAL); + $useMinMax = true; + } + if ($useMinMax) { + return $this; + } + if (null === $comparison) { + $comparison = Criteria::IN; + } + } + + return $this->addUsingAlias(ColissimoHomeDeliveryPriceSlicesTableMap::MAX_WEIGHT, $maxWeight, $comparison); + } + + /** + * Filter the query on the max_price column + * + * Example usage: + * + * $query->filterByMaxPrice(1234); // WHERE max_price = 1234 + * $query->filterByMaxPrice(array(12, 34)); // WHERE max_price IN (12, 34) + * $query->filterByMaxPrice(array('min' => 12)); // WHERE max_price > 12 + * + * + * @param mixed $maxPrice The value to use as filter. + * Use scalar values for equality. + * Use array values for in_array() equivalent. + * Use associative array('min' => $minValue, 'max' => $maxValue) for intervals. + * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL + * + * @return ChildColissimoHomeDeliveryPriceSlicesQuery The current query, for fluid interface + */ + public function filterByMaxPrice($maxPrice = null, $comparison = null) + { + if (is_array($maxPrice)) { + $useMinMax = false; + if (isset($maxPrice['min'])) { + $this->addUsingAlias(ColissimoHomeDeliveryPriceSlicesTableMap::MAX_PRICE, $maxPrice['min'], Criteria::GREATER_EQUAL); + $useMinMax = true; + } + if (isset($maxPrice['max'])) { + $this->addUsingAlias(ColissimoHomeDeliveryPriceSlicesTableMap::MAX_PRICE, $maxPrice['max'], Criteria::LESS_EQUAL); + $useMinMax = true; + } + if ($useMinMax) { + return $this; + } + if (null === $comparison) { + $comparison = Criteria::IN; + } + } + + return $this->addUsingAlias(ColissimoHomeDeliveryPriceSlicesTableMap::MAX_PRICE, $maxPrice, $comparison); + } + + /** + * Filter the query on the shipping column + * + * Example usage: + * + * $query->filterByShipping(1234); // WHERE shipping = 1234 + * $query->filterByShipping(array(12, 34)); // WHERE shipping IN (12, 34) + * $query->filterByShipping(array('min' => 12)); // WHERE shipping > 12 + * + * + * @param mixed $shipping The value to use as filter. + * Use scalar values for equality. + * Use array values for in_array() equivalent. + * Use associative array('min' => $minValue, 'max' => $maxValue) for intervals. + * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL + * + * @return ChildColissimoHomeDeliveryPriceSlicesQuery The current query, for fluid interface + */ + public function filterByShipping($shipping = null, $comparison = null) + { + if (is_array($shipping)) { + $useMinMax = false; + if (isset($shipping['min'])) { + $this->addUsingAlias(ColissimoHomeDeliveryPriceSlicesTableMap::SHIPPING, $shipping['min'], Criteria::GREATER_EQUAL); + $useMinMax = true; + } + if (isset($shipping['max'])) { + $this->addUsingAlias(ColissimoHomeDeliveryPriceSlicesTableMap::SHIPPING, $shipping['max'], Criteria::LESS_EQUAL); + $useMinMax = true; + } + if ($useMinMax) { + return $this; + } + if (null === $comparison) { + $comparison = Criteria::IN; + } + } + + return $this->addUsingAlias(ColissimoHomeDeliveryPriceSlicesTableMap::SHIPPING, $shipping, $comparison); + } + + /** + * Filter the query by a related \Thelia\Model\Area object + * + * @param \Thelia\Model\Area|ObjectCollection $area The related object(s) to use as filter + * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL + * + * @return ChildColissimoHomeDeliveryPriceSlicesQuery The current query, for fluid interface + */ + public function filterByArea($area, $comparison = null) + { + if ($area instanceof \Thelia\Model\Area) { + return $this + ->addUsingAlias(ColissimoHomeDeliveryPriceSlicesTableMap::AREA_ID, $area->getId(), $comparison); + } elseif ($area instanceof ObjectCollection) { + if (null === $comparison) { + $comparison = Criteria::IN; + } + + return $this + ->addUsingAlias(ColissimoHomeDeliveryPriceSlicesTableMap::AREA_ID, $area->toKeyValue('PrimaryKey', 'Id'), $comparison); + } else { + throw new PropelException('filterByArea() only accepts arguments of type \Thelia\Model\Area or Collection'); + } + } + + /** + * Adds a JOIN clause to the query using the Area relation + * + * @param string $relationAlias optional alias for the relation + * @param string $joinType Accepted values are null, 'left join', 'right join', 'inner join' + * + * @return ChildColissimoHomeDeliveryPriceSlicesQuery The current query, for fluid interface + */ + public function joinArea($relationAlias = null, $joinType = Criteria::INNER_JOIN) + { + $tableMap = $this->getTableMap(); + $relationMap = $tableMap->getRelation('Area'); + + // create a ModelJoin object for this join + $join = new ModelJoin(); + $join->setJoinType($joinType); + $join->setRelationMap($relationMap, $this->useAliasInSQL ? $this->getModelAlias() : null, $relationAlias); + if ($previousJoin = $this->getPreviousJoin()) { + $join->setPreviousJoin($previousJoin); + } + + // add the ModelJoin to the current object + if ($relationAlias) { + $this->addAlias($relationAlias, $relationMap->getRightTable()->getName()); + $this->addJoinObject($join, $relationAlias); + } else { + $this->addJoinObject($join, 'Area'); + } + + return $this; + } + + /** + * Use the Area relation Area object + * + * @see useQuery() + * + * @param string $relationAlias optional alias for the relation, + * to be used as main alias in the secondary query + * @param string $joinType Accepted values are null, 'left join', 'right join', 'inner join' + * + * @return \Thelia\Model\AreaQuery A secondary query class using the current class as primary query + */ + public function useAreaQuery($relationAlias = null, $joinType = Criteria::INNER_JOIN) + { + return $this + ->joinArea($relationAlias, $joinType) + ->useQuery($relationAlias ? $relationAlias : 'Area', '\Thelia\Model\AreaQuery'); + } + + /** + * Exclude object from result + * + * @param ChildColissimoHomeDeliveryPriceSlices $colissimoHomeDeliveryPriceSlices Object to remove from the list of results + * + * @return ChildColissimoHomeDeliveryPriceSlicesQuery The current query, for fluid interface + */ + public function prune($colissimoHomeDeliveryPriceSlices = null) + { + if ($colissimoHomeDeliveryPriceSlices) { + $this->addUsingAlias(ColissimoHomeDeliveryPriceSlicesTableMap::ID, $colissimoHomeDeliveryPriceSlices->getId(), Criteria::NOT_EQUAL); + } + + return $this; + } + + /** + * Deletes all rows from the colissimo_home_delivery_price_slices table. + * + * @param ConnectionInterface $con the connection to use + * @return int The number of affected rows (if supported by underlying database driver). + */ + public function doDeleteAll(ConnectionInterface $con = null) + { + if (null === $con) { + $con = Propel::getServiceContainer()->getWriteConnection(ColissimoHomeDeliveryPriceSlicesTableMap::DATABASE_NAME); + } + $affectedRows = 0; // initialize var to track total num of affected rows + try { + // use transaction because $criteria could contain info + // for more than one table or we could emulating ON DELETE CASCADE, etc. + $con->beginTransaction(); + $affectedRows += parent::doDeleteAll($con); + // Because this db requires some delete cascade/set null emulation, we have to + // clear the cached instance *after* the emulation has happened (since + // instances get re-added by the select statement contained therein). + ColissimoHomeDeliveryPriceSlicesTableMap::clearInstancePool(); + ColissimoHomeDeliveryPriceSlicesTableMap::clearRelatedInstancePool(); + + $con->commit(); + } catch (PropelException $e) { + $con->rollBack(); + throw $e; + } + + return $affectedRows; + } + + /** + * Performs a DELETE on the database, given a ChildColissimoHomeDeliveryPriceSlices or Criteria object OR a primary key value. + * + * @param mixed $values Criteria or ChildColissimoHomeDeliveryPriceSlices object or primary key or array of primary keys + * which is used to create the DELETE statement + * @param ConnectionInterface $con the connection to use + * @return int The number of affected rows (if supported by underlying database driver). This includes CASCADE-related rows + * if supported by native driver or if emulated using Propel. + * @throws PropelException Any exceptions caught during processing will be + * rethrown wrapped into a PropelException. + */ + public function delete(ConnectionInterface $con = null) + { + if (null === $con) { + $con = Propel::getServiceContainer()->getWriteConnection(ColissimoHomeDeliveryPriceSlicesTableMap::DATABASE_NAME); + } + + $criteria = $this; + + // Set the correct dbName + $criteria->setDbName(ColissimoHomeDeliveryPriceSlicesTableMap::DATABASE_NAME); + + $affectedRows = 0; // initialize var to track total num of affected rows + + try { + // use transaction because $criteria could contain info + // for more than one table or we could emulating ON DELETE CASCADE, etc. + $con->beginTransaction(); + + + ColissimoHomeDeliveryPriceSlicesTableMap::removeInstanceFromPool($criteria); + + $affectedRows += ModelCriteria::delete($con); + ColissimoHomeDeliveryPriceSlicesTableMap::clearRelatedInstancePool(); + $con->commit(); + + return $affectedRows; + } catch (PropelException $e) { + $con->rollBack(); + throw $e; + } + } + +} // ColissimoHomeDeliveryPriceSlicesQuery diff --git a/local/modules/ColissimoHomeDelivery/Model/ColissimoHomeDeliveryAreaFreeshipping.php b/local/modules/ColissimoHomeDelivery/Model/ColissimoHomeDeliveryAreaFreeshipping.php new file mode 100644 index 00000000..78b181fb --- /dev/null +++ b/local/modules/ColissimoHomeDelivery/Model/ColissimoHomeDeliveryAreaFreeshipping.php @@ -0,0 +1,10 @@ + array('Id', 'AreaId', 'CartAmount', ), + self::TYPE_STUDLYPHPNAME => array('id', 'areaId', 'cartAmount', ), + self::TYPE_COLNAME => array(ColissimoHomeDeliveryAreaFreeshippingTableMap::ID, ColissimoHomeDeliveryAreaFreeshippingTableMap::AREA_ID, ColissimoHomeDeliveryAreaFreeshippingTableMap::CART_AMOUNT, ), + self::TYPE_RAW_COLNAME => array('ID', 'AREA_ID', 'CART_AMOUNT', ), + self::TYPE_FIELDNAME => array('id', 'area_id', 'cart_amount', ), + self::TYPE_NUM => array(0, 1, 2, ) + ); + + /** + * holds an array of keys for quick access to the fieldnames array + * + * first dimension keys are the type constants + * e.g. self::$fieldKeys[self::TYPE_PHPNAME]['Id'] = 0 + */ + protected static $fieldKeys = array ( + self::TYPE_PHPNAME => array('Id' => 0, 'AreaId' => 1, 'CartAmount' => 2, ), + self::TYPE_STUDLYPHPNAME => array('id' => 0, 'areaId' => 1, 'cartAmount' => 2, ), + self::TYPE_COLNAME => array(ColissimoHomeDeliveryAreaFreeshippingTableMap::ID => 0, ColissimoHomeDeliveryAreaFreeshippingTableMap::AREA_ID => 1, ColissimoHomeDeliveryAreaFreeshippingTableMap::CART_AMOUNT => 2, ), + self::TYPE_RAW_COLNAME => array('ID' => 0, 'AREA_ID' => 1, 'CART_AMOUNT' => 2, ), + self::TYPE_FIELDNAME => array('id' => 0, 'area_id' => 1, 'cart_amount' => 2, ), + self::TYPE_NUM => array(0, 1, 2, ) + ); + + /** + * Initialize the table attributes and columns + * Relations are not initialized by this method since they are lazy loaded + * + * @return void + * @throws PropelException + */ + public function initialize() + { + // attributes + $this->setName('colissimo_home_delivery_area_freeshipping'); + $this->setPhpName('ColissimoHomeDeliveryAreaFreeshipping'); + $this->setClassName('\\ColissimoHomeDelivery\\Model\\ColissimoHomeDeliveryAreaFreeshipping'); + $this->setPackage('ColissimoHomeDelivery.Model'); + $this->setUseIdGenerator(false); + // columns + $this->addPrimaryKey('ID', 'Id', 'INTEGER', true, null, null); + $this->addForeignKey('AREA_ID', 'AreaId', 'INTEGER', 'area', 'ID', true, null, null); + $this->addColumn('CART_AMOUNT', 'CartAmount', 'DECIMAL', false, 18, 0); + } // initialize() + + /** + * Build the RelationMap objects for this table relationships + */ + public function buildRelations() + { + $this->addRelation('Area', '\\Thelia\\Model\\Area', RelationMap::MANY_TO_ONE, array('area_id' => 'id', ), 'RESTRICT', 'RESTRICT'); + } // buildRelations() + + /** + * Retrieves a string version of the primary key from the DB resultset row that can be used to uniquely identify a row in this table. + * + * For tables with a single-column primary key, that simple pkey value will be returned. For tables with + * a multi-column primary key, a serialize()d version of the primary key will be returned. + * + * @param array $row resultset row. + * @param int $offset The 0-based offset for reading from the resultset row. + * @param string $indexType One of the class type constants TableMap::TYPE_PHPNAME, TableMap::TYPE_STUDLYPHPNAME + * TableMap::TYPE_COLNAME, TableMap::TYPE_FIELDNAME, TableMap::TYPE_NUM + */ + public static function getPrimaryKeyHashFromRow($row, $offset = 0, $indexType = TableMap::TYPE_NUM) + { + // If the PK cannot be derived from the row, return NULL. + if ($row[TableMap::TYPE_NUM == $indexType ? 0 + $offset : static::translateFieldName('Id', TableMap::TYPE_PHPNAME, $indexType)] === null) { + return null; + } + + return (string) $row[TableMap::TYPE_NUM == $indexType ? 0 + $offset : static::translateFieldName('Id', TableMap::TYPE_PHPNAME, $indexType)]; + } + + /** + * Retrieves the primary key from the DB resultset row + * For tables with a single-column primary key, that simple pkey value will be returned. For tables with + * a multi-column primary key, an array of the primary key columns will be returned. + * + * @param array $row resultset row. + * @param int $offset The 0-based offset for reading from the resultset row. + * @param string $indexType One of the class type constants TableMap::TYPE_PHPNAME, TableMap::TYPE_STUDLYPHPNAME + * TableMap::TYPE_COLNAME, TableMap::TYPE_FIELDNAME, TableMap::TYPE_NUM + * + * @return mixed The primary key of the row + */ + public static function getPrimaryKeyFromRow($row, $offset = 0, $indexType = TableMap::TYPE_NUM) + { + + return (int) $row[ + $indexType == TableMap::TYPE_NUM + ? 0 + $offset + : self::translateFieldName('Id', TableMap::TYPE_PHPNAME, $indexType) + ]; + } + + /** + * The class that the tableMap will make instances of. + * + * If $withPrefix is true, the returned path + * uses a dot-path notation which is translated into a path + * relative to a location on the PHP include_path. + * (e.g. path.to.MyClass -> 'path/to/MyClass.php') + * + * @param boolean $withPrefix Whether or not to return the path with the class name + * @return string path.to.ClassName + */ + public static function getOMClass($withPrefix = true) + { + return $withPrefix ? ColissimoHomeDeliveryAreaFreeshippingTableMap::CLASS_DEFAULT : ColissimoHomeDeliveryAreaFreeshippingTableMap::OM_CLASS; + } + + /** + * Populates an object of the default type or an object that inherit from the default. + * + * @param array $row row returned by DataFetcher->fetch(). + * @param int $offset The 0-based offset for reading from the resultset row. + * @param string $indexType The index type of $row. Mostly DataFetcher->getIndexType(). + One of the class type constants TableMap::TYPE_PHPNAME, TableMap::TYPE_STUDLYPHPNAME + * TableMap::TYPE_COLNAME, TableMap::TYPE_FIELDNAME, TableMap::TYPE_NUM. + * + * @throws PropelException Any exceptions caught during processing will be + * rethrown wrapped into a PropelException. + * @return array (ColissimoHomeDeliveryAreaFreeshipping object, last column rank) + */ + public static function populateObject($row, $offset = 0, $indexType = TableMap::TYPE_NUM) + { + $key = ColissimoHomeDeliveryAreaFreeshippingTableMap::getPrimaryKeyHashFromRow($row, $offset, $indexType); + if (null !== ($obj = ColissimoHomeDeliveryAreaFreeshippingTableMap::getInstanceFromPool($key))) { + // We no longer rehydrate the object, since this can cause data loss. + // See http://www.propelorm.org/ticket/509 + // $obj->hydrate($row, $offset, true); // rehydrate + $col = $offset + ColissimoHomeDeliveryAreaFreeshippingTableMap::NUM_HYDRATE_COLUMNS; + } else { + $cls = ColissimoHomeDeliveryAreaFreeshippingTableMap::OM_CLASS; + $obj = new $cls(); + $col = $obj->hydrate($row, $offset, false, $indexType); + ColissimoHomeDeliveryAreaFreeshippingTableMap::addInstanceToPool($obj, $key); + } + + return array($obj, $col); + } + + /** + * The returned array will contain objects of the default type or + * objects that inherit from the default. + * + * @param DataFetcherInterface $dataFetcher + * @return array + * @throws PropelException Any exceptions caught during processing will be + * rethrown wrapped into a PropelException. + */ + public static function populateObjects(DataFetcherInterface $dataFetcher) + { + $results = array(); + + // set the class once to avoid overhead in the loop + $cls = static::getOMClass(false); + // populate the object(s) + while ($row = $dataFetcher->fetch()) { + $key = ColissimoHomeDeliveryAreaFreeshippingTableMap::getPrimaryKeyHashFromRow($row, 0, $dataFetcher->getIndexType()); + if (null !== ($obj = ColissimoHomeDeliveryAreaFreeshippingTableMap::getInstanceFromPool($key))) { + // We no longer rehydrate the object, since this can cause data loss. + // See http://www.propelorm.org/ticket/509 + // $obj->hydrate($row, 0, true); // rehydrate + $results[] = $obj; + } else { + $obj = new $cls(); + $obj->hydrate($row); + $results[] = $obj; + ColissimoHomeDeliveryAreaFreeshippingTableMap::addInstanceToPool($obj, $key); + } // if key exists + } + + return $results; + } + /** + * Add all the columns needed to create a new object. + * + * Note: any columns that were marked with lazyLoad="true" in the + * XML schema will not be added to the select list and only loaded + * on demand. + * + * @param Criteria $criteria object containing the columns to add. + * @param string $alias optional table alias + * @throws PropelException Any exceptions caught during processing will be + * rethrown wrapped into a PropelException. + */ + public static function addSelectColumns(Criteria $criteria, $alias = null) + { + if (null === $alias) { + $criteria->addSelectColumn(ColissimoHomeDeliveryAreaFreeshippingTableMap::ID); + $criteria->addSelectColumn(ColissimoHomeDeliveryAreaFreeshippingTableMap::AREA_ID); + $criteria->addSelectColumn(ColissimoHomeDeliveryAreaFreeshippingTableMap::CART_AMOUNT); + } else { + $criteria->addSelectColumn($alias . '.ID'); + $criteria->addSelectColumn($alias . '.AREA_ID'); + $criteria->addSelectColumn($alias . '.CART_AMOUNT'); + } + } + + /** + * Returns the TableMap related to this object. + * This method is not needed for general use but a specific application could have a need. + * @return TableMap + * @throws PropelException Any exceptions caught during processing will be + * rethrown wrapped into a PropelException. + */ + public static function getTableMap() + { + return Propel::getServiceContainer()->getDatabaseMap(ColissimoHomeDeliveryAreaFreeshippingTableMap::DATABASE_NAME)->getTable(ColissimoHomeDeliveryAreaFreeshippingTableMap::TABLE_NAME); + } + + /** + * Add a TableMap instance to the database for this tableMap class. + */ + public static function buildTableMap() + { + $dbMap = Propel::getServiceContainer()->getDatabaseMap(ColissimoHomeDeliveryAreaFreeshippingTableMap::DATABASE_NAME); + if (!$dbMap->hasTable(ColissimoHomeDeliveryAreaFreeshippingTableMap::TABLE_NAME)) { + $dbMap->addTableObject(new ColissimoHomeDeliveryAreaFreeshippingTableMap()); + } + } + + /** + * Performs a DELETE on the database, given a ColissimoHomeDeliveryAreaFreeshipping or Criteria object OR a primary key value. + * + * @param mixed $values Criteria or ColissimoHomeDeliveryAreaFreeshipping object or primary key or array of primary keys + * which is used to create the DELETE statement + * @param ConnectionInterface $con the connection to use + * @return int The number of affected rows (if supported by underlying database driver). This includes CASCADE-related rows + * if supported by native driver or if emulated using Propel. + * @throws PropelException Any exceptions caught during processing will be + * rethrown wrapped into a PropelException. + */ + public static function doDelete($values, ConnectionInterface $con = null) + { + if (null === $con) { + $con = Propel::getServiceContainer()->getWriteConnection(ColissimoHomeDeliveryAreaFreeshippingTableMap::DATABASE_NAME); + } + + if ($values instanceof Criteria) { + // rename for clarity + $criteria = $values; + } elseif ($values instanceof \ColissimoHomeDelivery\Model\ColissimoHomeDeliveryAreaFreeshipping) { // it's a model object + // create criteria based on pk values + $criteria = $values->buildPkeyCriteria(); + } else { // it's a primary key, or an array of pks + $criteria = new Criteria(ColissimoHomeDeliveryAreaFreeshippingTableMap::DATABASE_NAME); + $criteria->add(ColissimoHomeDeliveryAreaFreeshippingTableMap::ID, (array) $values, Criteria::IN); + } + + $query = ColissimoHomeDeliveryAreaFreeshippingQuery::create()->mergeWith($criteria); + + if ($values instanceof Criteria) { ColissimoHomeDeliveryAreaFreeshippingTableMap::clearInstancePool(); + } elseif (!is_object($values)) { // it's a primary key, or an array of pks + foreach ((array) $values as $singleval) { ColissimoHomeDeliveryAreaFreeshippingTableMap::removeInstanceFromPool($singleval); + } + } + + return $query->delete($con); + } + + /** + * Deletes all rows from the colissimo_home_delivery_area_freeshipping table. + * + * @param ConnectionInterface $con the connection to use + * @return int The number of affected rows (if supported by underlying database driver). + */ + public static function doDeleteAll(ConnectionInterface $con = null) + { + return ColissimoHomeDeliveryAreaFreeshippingQuery::create()->doDeleteAll($con); + } + + /** + * Performs an INSERT on the database, given a ColissimoHomeDeliveryAreaFreeshipping or Criteria object. + * + * @param mixed $criteria Criteria or ColissimoHomeDeliveryAreaFreeshipping object containing data that is used to create the INSERT statement. + * @param ConnectionInterface $con the ConnectionInterface connection to use + * @return mixed The new primary key. + * @throws PropelException Any exceptions caught during processing will be + * rethrown wrapped into a PropelException. + */ + public static function doInsert($criteria, ConnectionInterface $con = null) + { + if (null === $con) { + $con = Propel::getServiceContainer()->getWriteConnection(ColissimoHomeDeliveryAreaFreeshippingTableMap::DATABASE_NAME); + } + + if ($criteria instanceof Criteria) { + $criteria = clone $criteria; // rename for clarity + } else { + $criteria = $criteria->buildCriteria(); // build Criteria from ColissimoHomeDeliveryAreaFreeshipping object + } + + + // Set the correct dbName + $query = ColissimoHomeDeliveryAreaFreeshippingQuery::create()->mergeWith($criteria); + + try { + // use transaction because $criteria could contain info + // for more than one table (I guess, conceivably) + $con->beginTransaction(); + $pk = $query->doInsert($con); + $con->commit(); + } catch (PropelException $e) { + $con->rollBack(); + throw $e; + } + + return $pk; + } + +} // ColissimoHomeDeliveryAreaFreeshippingTableMap +// This is the static code needed to register the TableMap for this table with the main Propel class. +// +ColissimoHomeDeliveryAreaFreeshippingTableMap::buildTableMap(); diff --git a/local/modules/ColissimoHomeDelivery/Model/Map/ColissimoHomeDeliveryFreeshippingTableMap.php b/local/modules/ColissimoHomeDelivery/Model/Map/ColissimoHomeDeliveryFreeshippingTableMap.php new file mode 100644 index 00000000..f4a7821e --- /dev/null +++ b/local/modules/ColissimoHomeDelivery/Model/Map/ColissimoHomeDeliveryFreeshippingTableMap.php @@ -0,0 +1,414 @@ + array('Id', 'Active', 'FreeshippingFrom', ), + self::TYPE_STUDLYPHPNAME => array('id', 'active', 'freeshippingFrom', ), + self::TYPE_COLNAME => array(ColissimoHomeDeliveryFreeshippingTableMap::ID, ColissimoHomeDeliveryFreeshippingTableMap::ACTIVE, ColissimoHomeDeliveryFreeshippingTableMap::FREESHIPPING_FROM, ), + self::TYPE_RAW_COLNAME => array('ID', 'ACTIVE', 'FREESHIPPING_FROM', ), + self::TYPE_FIELDNAME => array('id', 'active', 'freeshipping_from', ), + self::TYPE_NUM => array(0, 1, 2, ) + ); + + /** + * holds an array of keys for quick access to the fieldnames array + * + * first dimension keys are the type constants + * e.g. self::$fieldKeys[self::TYPE_PHPNAME]['Id'] = 0 + */ + protected static $fieldKeys = array ( + self::TYPE_PHPNAME => array('Id' => 0, 'Active' => 1, 'FreeshippingFrom' => 2, ), + self::TYPE_STUDLYPHPNAME => array('id' => 0, 'active' => 1, 'freeshippingFrom' => 2, ), + self::TYPE_COLNAME => array(ColissimoHomeDeliveryFreeshippingTableMap::ID => 0, ColissimoHomeDeliveryFreeshippingTableMap::ACTIVE => 1, ColissimoHomeDeliveryFreeshippingTableMap::FREESHIPPING_FROM => 2, ), + self::TYPE_RAW_COLNAME => array('ID' => 0, 'ACTIVE' => 1, 'FREESHIPPING_FROM' => 2, ), + self::TYPE_FIELDNAME => array('id' => 0, 'active' => 1, 'freeshipping_from' => 2, ), + self::TYPE_NUM => array(0, 1, 2, ) + ); + + /** + * Initialize the table attributes and columns + * Relations are not initialized by this method since they are lazy loaded + * + * @return void + * @throws PropelException + */ + public function initialize() + { + // attributes + $this->setName('colissimo_home_delivery_freeshipping'); + $this->setPhpName('ColissimoHomeDeliveryFreeshipping'); + $this->setClassName('\\ColissimoHomeDelivery\\Model\\ColissimoHomeDeliveryFreeshipping'); + $this->setPackage('ColissimoHomeDelivery.Model'); + $this->setUseIdGenerator(false); + // columns + $this->addPrimaryKey('ID', 'Id', 'INTEGER', true, null, null); + $this->addColumn('ACTIVE', 'Active', 'BOOLEAN', false, 1, false); + $this->addColumn('FREESHIPPING_FROM', 'FreeshippingFrom', 'DECIMAL', false, 18, null); + } // initialize() + + /** + * Build the RelationMap objects for this table relationships + */ + public function buildRelations() + { + } // buildRelations() + + /** + * Retrieves a string version of the primary key from the DB resultset row that can be used to uniquely identify a row in this table. + * + * For tables with a single-column primary key, that simple pkey value will be returned. For tables with + * a multi-column primary key, a serialize()d version of the primary key will be returned. + * + * @param array $row resultset row. + * @param int $offset The 0-based offset for reading from the resultset row. + * @param string $indexType One of the class type constants TableMap::TYPE_PHPNAME, TableMap::TYPE_STUDLYPHPNAME + * TableMap::TYPE_COLNAME, TableMap::TYPE_FIELDNAME, TableMap::TYPE_NUM + */ + public static function getPrimaryKeyHashFromRow($row, $offset = 0, $indexType = TableMap::TYPE_NUM) + { + // If the PK cannot be derived from the row, return NULL. + if ($row[TableMap::TYPE_NUM == $indexType ? 0 + $offset : static::translateFieldName('Id', TableMap::TYPE_PHPNAME, $indexType)] === null) { + return null; + } + + return (string) $row[TableMap::TYPE_NUM == $indexType ? 0 + $offset : static::translateFieldName('Id', TableMap::TYPE_PHPNAME, $indexType)]; + } + + /** + * Retrieves the primary key from the DB resultset row + * For tables with a single-column primary key, that simple pkey value will be returned. For tables with + * a multi-column primary key, an array of the primary key columns will be returned. + * + * @param array $row resultset row. + * @param int $offset The 0-based offset for reading from the resultset row. + * @param string $indexType One of the class type constants TableMap::TYPE_PHPNAME, TableMap::TYPE_STUDLYPHPNAME + * TableMap::TYPE_COLNAME, TableMap::TYPE_FIELDNAME, TableMap::TYPE_NUM + * + * @return mixed The primary key of the row + */ + public static function getPrimaryKeyFromRow($row, $offset = 0, $indexType = TableMap::TYPE_NUM) + { + + return (int) $row[ + $indexType == TableMap::TYPE_NUM + ? 0 + $offset + : self::translateFieldName('Id', TableMap::TYPE_PHPNAME, $indexType) + ]; + } + + /** + * The class that the tableMap will make instances of. + * + * If $withPrefix is true, the returned path + * uses a dot-path notation which is translated into a path + * relative to a location on the PHP include_path. + * (e.g. path.to.MyClass -> 'path/to/MyClass.php') + * + * @param boolean $withPrefix Whether or not to return the path with the class name + * @return string path.to.ClassName + */ + public static function getOMClass($withPrefix = true) + { + return $withPrefix ? ColissimoHomeDeliveryFreeshippingTableMap::CLASS_DEFAULT : ColissimoHomeDeliveryFreeshippingTableMap::OM_CLASS; + } + + /** + * Populates an object of the default type or an object that inherit from the default. + * + * @param array $row row returned by DataFetcher->fetch(). + * @param int $offset The 0-based offset for reading from the resultset row. + * @param string $indexType The index type of $row. Mostly DataFetcher->getIndexType(). + One of the class type constants TableMap::TYPE_PHPNAME, TableMap::TYPE_STUDLYPHPNAME + * TableMap::TYPE_COLNAME, TableMap::TYPE_FIELDNAME, TableMap::TYPE_NUM. + * + * @throws PropelException Any exceptions caught during processing will be + * rethrown wrapped into a PropelException. + * @return array (ColissimoHomeDeliveryFreeshipping object, last column rank) + */ + public static function populateObject($row, $offset = 0, $indexType = TableMap::TYPE_NUM) + { + $key = ColissimoHomeDeliveryFreeshippingTableMap::getPrimaryKeyHashFromRow($row, $offset, $indexType); + if (null !== ($obj = ColissimoHomeDeliveryFreeshippingTableMap::getInstanceFromPool($key))) { + // We no longer rehydrate the object, since this can cause data loss. + // See http://www.propelorm.org/ticket/509 + // $obj->hydrate($row, $offset, true); // rehydrate + $col = $offset + ColissimoHomeDeliveryFreeshippingTableMap::NUM_HYDRATE_COLUMNS; + } else { + $cls = ColissimoHomeDeliveryFreeshippingTableMap::OM_CLASS; + $obj = new $cls(); + $col = $obj->hydrate($row, $offset, false, $indexType); + ColissimoHomeDeliveryFreeshippingTableMap::addInstanceToPool($obj, $key); + } + + return array($obj, $col); + } + + /** + * The returned array will contain objects of the default type or + * objects that inherit from the default. + * + * @param DataFetcherInterface $dataFetcher + * @return array + * @throws PropelException Any exceptions caught during processing will be + * rethrown wrapped into a PropelException. + */ + public static function populateObjects(DataFetcherInterface $dataFetcher) + { + $results = array(); + + // set the class once to avoid overhead in the loop + $cls = static::getOMClass(false); + // populate the object(s) + while ($row = $dataFetcher->fetch()) { + $key = ColissimoHomeDeliveryFreeshippingTableMap::getPrimaryKeyHashFromRow($row, 0, $dataFetcher->getIndexType()); + if (null !== ($obj = ColissimoHomeDeliveryFreeshippingTableMap::getInstanceFromPool($key))) { + // We no longer rehydrate the object, since this can cause data loss. + // See http://www.propelorm.org/ticket/509 + // $obj->hydrate($row, 0, true); // rehydrate + $results[] = $obj; + } else { + $obj = new $cls(); + $obj->hydrate($row); + $results[] = $obj; + ColissimoHomeDeliveryFreeshippingTableMap::addInstanceToPool($obj, $key); + } // if key exists + } + + return $results; + } + /** + * Add all the columns needed to create a new object. + * + * Note: any columns that were marked with lazyLoad="true" in the + * XML schema will not be added to the select list and only loaded + * on demand. + * + * @param Criteria $criteria object containing the columns to add. + * @param string $alias optional table alias + * @throws PropelException Any exceptions caught during processing will be + * rethrown wrapped into a PropelException. + */ + public static function addSelectColumns(Criteria $criteria, $alias = null) + { + if (null === $alias) { + $criteria->addSelectColumn(ColissimoHomeDeliveryFreeshippingTableMap::ID); + $criteria->addSelectColumn(ColissimoHomeDeliveryFreeshippingTableMap::ACTIVE); + $criteria->addSelectColumn(ColissimoHomeDeliveryFreeshippingTableMap::FREESHIPPING_FROM); + } else { + $criteria->addSelectColumn($alias . '.ID'); + $criteria->addSelectColumn($alias . '.ACTIVE'); + $criteria->addSelectColumn($alias . '.FREESHIPPING_FROM'); + } + } + + /** + * Returns the TableMap related to this object. + * This method is not needed for general use but a specific application could have a need. + * @return TableMap + * @throws PropelException Any exceptions caught during processing will be + * rethrown wrapped into a PropelException. + */ + public static function getTableMap() + { + return Propel::getServiceContainer()->getDatabaseMap(ColissimoHomeDeliveryFreeshippingTableMap::DATABASE_NAME)->getTable(ColissimoHomeDeliveryFreeshippingTableMap::TABLE_NAME); + } + + /** + * Add a TableMap instance to the database for this tableMap class. + */ + public static function buildTableMap() + { + $dbMap = Propel::getServiceContainer()->getDatabaseMap(ColissimoHomeDeliveryFreeshippingTableMap::DATABASE_NAME); + if (!$dbMap->hasTable(ColissimoHomeDeliveryFreeshippingTableMap::TABLE_NAME)) { + $dbMap->addTableObject(new ColissimoHomeDeliveryFreeshippingTableMap()); + } + } + + /** + * Performs a DELETE on the database, given a ColissimoHomeDeliveryFreeshipping or Criteria object OR a primary key value. + * + * @param mixed $values Criteria or ColissimoHomeDeliveryFreeshipping object or primary key or array of primary keys + * which is used to create the DELETE statement + * @param ConnectionInterface $con the connection to use + * @return int The number of affected rows (if supported by underlying database driver). This includes CASCADE-related rows + * if supported by native driver or if emulated using Propel. + * @throws PropelException Any exceptions caught during processing will be + * rethrown wrapped into a PropelException. + */ + public static function doDelete($values, ConnectionInterface $con = null) + { + if (null === $con) { + $con = Propel::getServiceContainer()->getWriteConnection(ColissimoHomeDeliveryFreeshippingTableMap::DATABASE_NAME); + } + + if ($values instanceof Criteria) { + // rename for clarity + $criteria = $values; + } elseif ($values instanceof \ColissimoHomeDelivery\Model\ColissimoHomeDeliveryFreeshipping) { // it's a model object + // create criteria based on pk values + $criteria = $values->buildPkeyCriteria(); + } else { // it's a primary key, or an array of pks + $criteria = new Criteria(ColissimoHomeDeliveryFreeshippingTableMap::DATABASE_NAME); + $criteria->add(ColissimoHomeDeliveryFreeshippingTableMap::ID, (array) $values, Criteria::IN); + } + + $query = ColissimoHomeDeliveryFreeshippingQuery::create()->mergeWith($criteria); + + if ($values instanceof Criteria) { ColissimoHomeDeliveryFreeshippingTableMap::clearInstancePool(); + } elseif (!is_object($values)) { // it's a primary key, or an array of pks + foreach ((array) $values as $singleval) { ColissimoHomeDeliveryFreeshippingTableMap::removeInstanceFromPool($singleval); + } + } + + return $query->delete($con); + } + + /** + * Deletes all rows from the colissimo_home_delivery_freeshipping table. + * + * @param ConnectionInterface $con the connection to use + * @return int The number of affected rows (if supported by underlying database driver). + */ + public static function doDeleteAll(ConnectionInterface $con = null) + { + return ColissimoHomeDeliveryFreeshippingQuery::create()->doDeleteAll($con); + } + + /** + * Performs an INSERT on the database, given a ColissimoHomeDeliveryFreeshipping or Criteria object. + * + * @param mixed $criteria Criteria or ColissimoHomeDeliveryFreeshipping object containing data that is used to create the INSERT statement. + * @param ConnectionInterface $con the ConnectionInterface connection to use + * @return mixed The new primary key. + * @throws PropelException Any exceptions caught during processing will be + * rethrown wrapped into a PropelException. + */ + public static function doInsert($criteria, ConnectionInterface $con = null) + { + if (null === $con) { + $con = Propel::getServiceContainer()->getWriteConnection(ColissimoHomeDeliveryFreeshippingTableMap::DATABASE_NAME); + } + + if ($criteria instanceof Criteria) { + $criteria = clone $criteria; // rename for clarity + } else { + $criteria = $criteria->buildCriteria(); // build Criteria from ColissimoHomeDeliveryFreeshipping object + } + + + // Set the correct dbName + $query = ColissimoHomeDeliveryFreeshippingQuery::create()->mergeWith($criteria); + + try { + // use transaction because $criteria could contain info + // for more than one table (I guess, conceivably) + $con->beginTransaction(); + $pk = $query->doInsert($con); + $con->commit(); + } catch (PropelException $e) { + $con->rollBack(); + throw $e; + } + + return $pk; + } + +} // ColissimoHomeDeliveryFreeshippingTableMap +// This is the static code needed to register the TableMap for this table with the main Propel class. +// +ColissimoHomeDeliveryFreeshippingTableMap::buildTableMap(); diff --git a/local/modules/ColissimoHomeDelivery/Model/Map/ColissimoHomeDeliveryPriceSlicesTableMap.php b/local/modules/ColissimoHomeDelivery/Model/Map/ColissimoHomeDeliveryPriceSlicesTableMap.php new file mode 100644 index 00000000..5e868875 --- /dev/null +++ b/local/modules/ColissimoHomeDelivery/Model/Map/ColissimoHomeDeliveryPriceSlicesTableMap.php @@ -0,0 +1,435 @@ + array('Id', 'AreaId', 'MaxWeight', 'MaxPrice', 'Shipping', ), + self::TYPE_STUDLYPHPNAME => array('id', 'areaId', 'maxWeight', 'maxPrice', 'shipping', ), + self::TYPE_COLNAME => array(ColissimoHomeDeliveryPriceSlicesTableMap::ID, ColissimoHomeDeliveryPriceSlicesTableMap::AREA_ID, ColissimoHomeDeliveryPriceSlicesTableMap::MAX_WEIGHT, ColissimoHomeDeliveryPriceSlicesTableMap::MAX_PRICE, ColissimoHomeDeliveryPriceSlicesTableMap::SHIPPING, ), + self::TYPE_RAW_COLNAME => array('ID', 'AREA_ID', 'MAX_WEIGHT', 'MAX_PRICE', 'SHIPPING', ), + self::TYPE_FIELDNAME => array('id', 'area_id', 'max_weight', 'max_price', 'shipping', ), + self::TYPE_NUM => array(0, 1, 2, 3, 4, ) + ); + + /** + * holds an array of keys for quick access to the fieldnames array + * + * first dimension keys are the type constants + * e.g. self::$fieldKeys[self::TYPE_PHPNAME]['Id'] = 0 + */ + protected static $fieldKeys = array ( + self::TYPE_PHPNAME => array('Id' => 0, 'AreaId' => 1, 'MaxWeight' => 2, 'MaxPrice' => 3, 'Shipping' => 4, ), + self::TYPE_STUDLYPHPNAME => array('id' => 0, 'areaId' => 1, 'maxWeight' => 2, 'maxPrice' => 3, 'shipping' => 4, ), + self::TYPE_COLNAME => array(ColissimoHomeDeliveryPriceSlicesTableMap::ID => 0, ColissimoHomeDeliveryPriceSlicesTableMap::AREA_ID => 1, ColissimoHomeDeliveryPriceSlicesTableMap::MAX_WEIGHT => 2, ColissimoHomeDeliveryPriceSlicesTableMap::MAX_PRICE => 3, ColissimoHomeDeliveryPriceSlicesTableMap::SHIPPING => 4, ), + self::TYPE_RAW_COLNAME => array('ID' => 0, 'AREA_ID' => 1, 'MAX_WEIGHT' => 2, 'MAX_PRICE' => 3, 'SHIPPING' => 4, ), + self::TYPE_FIELDNAME => array('id' => 0, 'area_id' => 1, 'max_weight' => 2, 'max_price' => 3, 'shipping' => 4, ), + self::TYPE_NUM => array(0, 1, 2, 3, 4, ) + ); + + /** + * Initialize the table attributes and columns + * Relations are not initialized by this method since they are lazy loaded + * + * @return void + * @throws PropelException + */ + public function initialize() + { + // attributes + $this->setName('colissimo_home_delivery_price_slices'); + $this->setPhpName('ColissimoHomeDeliveryPriceSlices'); + $this->setClassName('\\ColissimoHomeDelivery\\Model\\ColissimoHomeDeliveryPriceSlices'); + $this->setPackage('ColissimoHomeDelivery.Model'); + $this->setUseIdGenerator(true); + // columns + $this->addPrimaryKey('ID', 'Id', 'INTEGER', true, null, null); + $this->addForeignKey('AREA_ID', 'AreaId', 'INTEGER', 'area', 'ID', true, null, null); + $this->addColumn('MAX_WEIGHT', 'MaxWeight', 'FLOAT', false, null, null); + $this->addColumn('MAX_PRICE', 'MaxPrice', 'FLOAT', false, null, null); + $this->addColumn('SHIPPING', 'Shipping', 'FLOAT', true, null, null); + } // initialize() + + /** + * Build the RelationMap objects for this table relationships + */ + public function buildRelations() + { + $this->addRelation('Area', '\\Thelia\\Model\\Area', RelationMap::MANY_TO_ONE, array('area_id' => 'id', ), 'RESTRICT', 'RESTRICT'); + } // buildRelations() + + /** + * Retrieves a string version of the primary key from the DB resultset row that can be used to uniquely identify a row in this table. + * + * For tables with a single-column primary key, that simple pkey value will be returned. For tables with + * a multi-column primary key, a serialize()d version of the primary key will be returned. + * + * @param array $row resultset row. + * @param int $offset The 0-based offset for reading from the resultset row. + * @param string $indexType One of the class type constants TableMap::TYPE_PHPNAME, TableMap::TYPE_STUDLYPHPNAME + * TableMap::TYPE_COLNAME, TableMap::TYPE_FIELDNAME, TableMap::TYPE_NUM + */ + public static function getPrimaryKeyHashFromRow($row, $offset = 0, $indexType = TableMap::TYPE_NUM) + { + // If the PK cannot be derived from the row, return NULL. + if ($row[TableMap::TYPE_NUM == $indexType ? 0 + $offset : static::translateFieldName('Id', TableMap::TYPE_PHPNAME, $indexType)] === null) { + return null; + } + + return (string) $row[TableMap::TYPE_NUM == $indexType ? 0 + $offset : static::translateFieldName('Id', TableMap::TYPE_PHPNAME, $indexType)]; + } + + /** + * Retrieves the primary key from the DB resultset row + * For tables with a single-column primary key, that simple pkey value will be returned. For tables with + * a multi-column primary key, an array of the primary key columns will be returned. + * + * @param array $row resultset row. + * @param int $offset The 0-based offset for reading from the resultset row. + * @param string $indexType One of the class type constants TableMap::TYPE_PHPNAME, TableMap::TYPE_STUDLYPHPNAME + * TableMap::TYPE_COLNAME, TableMap::TYPE_FIELDNAME, TableMap::TYPE_NUM + * + * @return mixed The primary key of the row + */ + public static function getPrimaryKeyFromRow($row, $offset = 0, $indexType = TableMap::TYPE_NUM) + { + + return (int) $row[ + $indexType == TableMap::TYPE_NUM + ? 0 + $offset + : self::translateFieldName('Id', TableMap::TYPE_PHPNAME, $indexType) + ]; + } + + /** + * The class that the tableMap will make instances of. + * + * If $withPrefix is true, the returned path + * uses a dot-path notation which is translated into a path + * relative to a location on the PHP include_path. + * (e.g. path.to.MyClass -> 'path/to/MyClass.php') + * + * @param boolean $withPrefix Whether or not to return the path with the class name + * @return string path.to.ClassName + */ + public static function getOMClass($withPrefix = true) + { + return $withPrefix ? ColissimoHomeDeliveryPriceSlicesTableMap::CLASS_DEFAULT : ColissimoHomeDeliveryPriceSlicesTableMap::OM_CLASS; + } + + /** + * Populates an object of the default type or an object that inherit from the default. + * + * @param array $row row returned by DataFetcher->fetch(). + * @param int $offset The 0-based offset for reading from the resultset row. + * @param string $indexType The index type of $row. Mostly DataFetcher->getIndexType(). + One of the class type constants TableMap::TYPE_PHPNAME, TableMap::TYPE_STUDLYPHPNAME + * TableMap::TYPE_COLNAME, TableMap::TYPE_FIELDNAME, TableMap::TYPE_NUM. + * + * @throws PropelException Any exceptions caught during processing will be + * rethrown wrapped into a PropelException. + * @return array (ColissimoHomeDeliveryPriceSlices object, last column rank) + */ + public static function populateObject($row, $offset = 0, $indexType = TableMap::TYPE_NUM) + { + $key = ColissimoHomeDeliveryPriceSlicesTableMap::getPrimaryKeyHashFromRow($row, $offset, $indexType); + if (null !== ($obj = ColissimoHomeDeliveryPriceSlicesTableMap::getInstanceFromPool($key))) { + // We no longer rehydrate the object, since this can cause data loss. + // See http://www.propelorm.org/ticket/509 + // $obj->hydrate($row, $offset, true); // rehydrate + $col = $offset + ColissimoHomeDeliveryPriceSlicesTableMap::NUM_HYDRATE_COLUMNS; + } else { + $cls = ColissimoHomeDeliveryPriceSlicesTableMap::OM_CLASS; + $obj = new $cls(); + $col = $obj->hydrate($row, $offset, false, $indexType); + ColissimoHomeDeliveryPriceSlicesTableMap::addInstanceToPool($obj, $key); + } + + return array($obj, $col); + } + + /** + * The returned array will contain objects of the default type or + * objects that inherit from the default. + * + * @param DataFetcherInterface $dataFetcher + * @return array + * @throws PropelException Any exceptions caught during processing will be + * rethrown wrapped into a PropelException. + */ + public static function populateObjects(DataFetcherInterface $dataFetcher) + { + $results = array(); + + // set the class once to avoid overhead in the loop + $cls = static::getOMClass(false); + // populate the object(s) + while ($row = $dataFetcher->fetch()) { + $key = ColissimoHomeDeliveryPriceSlicesTableMap::getPrimaryKeyHashFromRow($row, 0, $dataFetcher->getIndexType()); + if (null !== ($obj = ColissimoHomeDeliveryPriceSlicesTableMap::getInstanceFromPool($key))) { + // We no longer rehydrate the object, since this can cause data loss. + // See http://www.propelorm.org/ticket/509 + // $obj->hydrate($row, 0, true); // rehydrate + $results[] = $obj; + } else { + $obj = new $cls(); + $obj->hydrate($row); + $results[] = $obj; + ColissimoHomeDeliveryPriceSlicesTableMap::addInstanceToPool($obj, $key); + } // if key exists + } + + return $results; + } + /** + * Add all the columns needed to create a new object. + * + * Note: any columns that were marked with lazyLoad="true" in the + * XML schema will not be added to the select list and only loaded + * on demand. + * + * @param Criteria $criteria object containing the columns to add. + * @param string $alias optional table alias + * @throws PropelException Any exceptions caught during processing will be + * rethrown wrapped into a PropelException. + */ + public static function addSelectColumns(Criteria $criteria, $alias = null) + { + if (null === $alias) { + $criteria->addSelectColumn(ColissimoHomeDeliveryPriceSlicesTableMap::ID); + $criteria->addSelectColumn(ColissimoHomeDeliveryPriceSlicesTableMap::AREA_ID); + $criteria->addSelectColumn(ColissimoHomeDeliveryPriceSlicesTableMap::MAX_WEIGHT); + $criteria->addSelectColumn(ColissimoHomeDeliveryPriceSlicesTableMap::MAX_PRICE); + $criteria->addSelectColumn(ColissimoHomeDeliveryPriceSlicesTableMap::SHIPPING); + } else { + $criteria->addSelectColumn($alias . '.ID'); + $criteria->addSelectColumn($alias . '.AREA_ID'); + $criteria->addSelectColumn($alias . '.MAX_WEIGHT'); + $criteria->addSelectColumn($alias . '.MAX_PRICE'); + $criteria->addSelectColumn($alias . '.SHIPPING'); + } + } + + /** + * Returns the TableMap related to this object. + * This method is not needed for general use but a specific application could have a need. + * @return TableMap + * @throws PropelException Any exceptions caught during processing will be + * rethrown wrapped into a PropelException. + */ + public static function getTableMap() + { + return Propel::getServiceContainer()->getDatabaseMap(ColissimoHomeDeliveryPriceSlicesTableMap::DATABASE_NAME)->getTable(ColissimoHomeDeliveryPriceSlicesTableMap::TABLE_NAME); + } + + /** + * Add a TableMap instance to the database for this tableMap class. + */ + public static function buildTableMap() + { + $dbMap = Propel::getServiceContainer()->getDatabaseMap(ColissimoHomeDeliveryPriceSlicesTableMap::DATABASE_NAME); + if (!$dbMap->hasTable(ColissimoHomeDeliveryPriceSlicesTableMap::TABLE_NAME)) { + $dbMap->addTableObject(new ColissimoHomeDeliveryPriceSlicesTableMap()); + } + } + + /** + * Performs a DELETE on the database, given a ColissimoHomeDeliveryPriceSlices or Criteria object OR a primary key value. + * + * @param mixed $values Criteria or ColissimoHomeDeliveryPriceSlices object or primary key or array of primary keys + * which is used to create the DELETE statement + * @param ConnectionInterface $con the connection to use + * @return int The number of affected rows (if supported by underlying database driver). This includes CASCADE-related rows + * if supported by native driver or if emulated using Propel. + * @throws PropelException Any exceptions caught during processing will be + * rethrown wrapped into a PropelException. + */ + public static function doDelete($values, ConnectionInterface $con = null) + { + if (null === $con) { + $con = Propel::getServiceContainer()->getWriteConnection(ColissimoHomeDeliveryPriceSlicesTableMap::DATABASE_NAME); + } + + if ($values instanceof Criteria) { + // rename for clarity + $criteria = $values; + } elseif ($values instanceof \ColissimoHomeDelivery\Model\ColissimoHomeDeliveryPriceSlices) { // it's a model object + // create criteria based on pk values + $criteria = $values->buildPkeyCriteria(); + } else { // it's a primary key, or an array of pks + $criteria = new Criteria(ColissimoHomeDeliveryPriceSlicesTableMap::DATABASE_NAME); + $criteria->add(ColissimoHomeDeliveryPriceSlicesTableMap::ID, (array) $values, Criteria::IN); + } + + $query = ColissimoHomeDeliveryPriceSlicesQuery::create()->mergeWith($criteria); + + if ($values instanceof Criteria) { ColissimoHomeDeliveryPriceSlicesTableMap::clearInstancePool(); + } elseif (!is_object($values)) { // it's a primary key, or an array of pks + foreach ((array) $values as $singleval) { ColissimoHomeDeliveryPriceSlicesTableMap::removeInstanceFromPool($singleval); + } + } + + return $query->delete($con); + } + + /** + * Deletes all rows from the colissimo_home_delivery_price_slices table. + * + * @param ConnectionInterface $con the connection to use + * @return int The number of affected rows (if supported by underlying database driver). + */ + public static function doDeleteAll(ConnectionInterface $con = null) + { + return ColissimoHomeDeliveryPriceSlicesQuery::create()->doDeleteAll($con); + } + + /** + * Performs an INSERT on the database, given a ColissimoHomeDeliveryPriceSlices or Criteria object. + * + * @param mixed $criteria Criteria or ColissimoHomeDeliveryPriceSlices object containing data that is used to create the INSERT statement. + * @param ConnectionInterface $con the ConnectionInterface connection to use + * @return mixed The new primary key. + * @throws PropelException Any exceptions caught during processing will be + * rethrown wrapped into a PropelException. + */ + public static function doInsert($criteria, ConnectionInterface $con = null) + { + if (null === $con) { + $con = Propel::getServiceContainer()->getWriteConnection(ColissimoHomeDeliveryPriceSlicesTableMap::DATABASE_NAME); + } + + if ($criteria instanceof Criteria) { + $criteria = clone $criteria; // rename for clarity + } else { + $criteria = $criteria->buildCriteria(); // build Criteria from ColissimoHomeDeliveryPriceSlices object + } + + if ($criteria->containsKey(ColissimoHomeDeliveryPriceSlicesTableMap::ID) && $criteria->keyContainsValue(ColissimoHomeDeliveryPriceSlicesTableMap::ID) ) { + throw new PropelException('Cannot insert a value for auto-increment primary key ('.ColissimoHomeDeliveryPriceSlicesTableMap::ID.')'); + } + + + // Set the correct dbName + $query = ColissimoHomeDeliveryPriceSlicesQuery::create()->mergeWith($criteria); + + try { + // use transaction because $criteria could contain info + // for more than one table (I guess, conceivably) + $con->beginTransaction(); + $pk = $query->doInsert($con); + $con->commit(); + } catch (PropelException $e) { + $con->rollBack(); + throw $e; + } + + return $pk; + } + +} // ColissimoHomeDeliveryPriceSlicesTableMap +// This is the static code needed to register the TableMap for this table with the main Propel class. +// +ColissimoHomeDeliveryPriceSlicesTableMap::buildTableMap(); diff --git a/local/modules/ColissimoHomeDelivery/Readme.md b/local/modules/ColissimoHomeDelivery/Readme.md new file mode 100644 index 00000000..b37ec490 --- /dev/null +++ b/local/modules/ColissimoHomeDelivery/Readme.md @@ -0,0 +1,81 @@ +# ColissimoHomeDelivery + +Adds a delivery system for Colissimo Domicile delivery, with or without signature. +For pickup delivery look at this module https://github.com/thelia-modules/ColissimoPickupPoint + +## Installation + +### Manually + +* Copy the module into ```/local/modules/``` directory and be sure that the name of the module is ReadmeTest. +* Activate it in your thelia administration panel + +### Composer + +Add it in your main thelia composer.json file + +``` +composer require thelia/colissimo-home-delivery-module:~1.0.0 +``` + +## Usage + +From the module configuration tab : + +- Price slice tab : Allow you to define price slices for every area served by your module, as well as to toggle free shipping, +for a minimum price, minimum price by area, or for everyone. +- Configuration tab : Lets you configure your module + +## Loop + +If your module declare one or more loop, describe them here like this : + +[colissimo.homedelivery.price-slices] + +### Input arguments + +|Argument |Description | +|--- |--- | +|**area_id** | Mandatory. The ID of an area served by your module | + +### Output arguments + +|Variable |Description | +|--- |--- | +|$SLICE_ID | The price slice ID | +|$MAX_WEIGHT | The max weight for this price slice | +|$MAX_PRICE | The max cart price for this price slice | +|$SHIPPING | The shipping cost for this price slice | + +[colissimo.homedelivery.freeshipping] + +### Input arguments + +|Argument |Description | +|--- |--- | +|**id** | The entry ID in the table. It should always be 1 | + +### Output arguments + +|Variable |Description | +|--- |--- | +|$FREESHIPPING_ACTIVE | (bool) Whether the global freeshipping without restrictions is activated or not | +|$FREESHIPPING_FROM | The minimum cart amount to have a global freeshipping | + +[colissimo.homedelivery.area.freeshipping] + +### Input arguments + +|Argument |Description | +|--- |--- | +|**area_id** | The ID of an area served by your module | + +### Output arguments + +|Variable |Description | +|--- |--- | +|$ID | The entry ID in the table | +|$AREA_ID | The area ID | +|$CART_AMOUNT | The cart amount necessary to benefit from free delivery for this area | + + diff --git a/local/modules/ColissimoHomeDelivery/composer.json b/local/modules/ColissimoHomeDelivery/composer.json new file mode 100644 index 00000000..15e5c877 --- /dev/null +++ b/local/modules/ColissimoHomeDelivery/composer.json @@ -0,0 +1,11 @@ +{ + "name": "thelia/colissimo-home-delivery-module", + "license": "LGPL-3.0+", + "type": "thelia-module", + "require": { + "thelia/installer": "~1.1" + }, + "extra": { + "installer-name": "ColissimoHomeDelivery" + } +} \ No newline at end of file diff --git a/local/modules/ColissimoHomeDelivery/templates/backOffice/default/module-config-js.html b/local/modules/ColissimoHomeDelivery/templates/backOffice/default/module-config-js.html new file mode 100644 index 00000000..330d209e --- /dev/null +++ b/local/modules/ColissimoHomeDelivery/templates/backOffice/default/module-config-js.html @@ -0,0 +1,166 @@ +{javascripts file='assets/js/bootstrap-switch/bootstrap-switch.js'} + +{/javascripts} + +{javascripts file='assets/js/libs/underscore-min.js'} + +{/javascripts} + + + \ No newline at end of file diff --git a/local/modules/ColissimoHomeDelivery/templates/backOffice/default/module_configuration.html b/local/modules/ColissimoHomeDelivery/templates/backOffice/default/module_configuration.html new file mode 100644 index 00000000..c080b97e --- /dev/null +++ b/local/modules/ColissimoHomeDelivery/templates/backOffice/default/module_configuration.html @@ -0,0 +1,286 @@ +{if isset($smarty.get.tab)} +{$tab=$smarty.get.tab} +{else} +{$tab='prices-dom'} +{/if} + +
+
+
+
+
+ + +
+ +
+
+ +
+
+
+ {intl l="Colissimo Web service configuration" d='colissimo.home.delivery.bo.default'} +
+ + {form name="colissimo.homedelivery.configuration.form"} + {if $form_error}
{$form_error_message}
{/if} + + + {form_hidden_fields form=$form} + + {include file = "includes/inner-form-toolbar.html" + hide_flags = true + page_url = "{url path='/admin/module/ColissimoHomeDelivery'}" + close_url = "{url path='/admin/modules'}" + } + + {if $form_error} +
{$form_error_message}
+ {/if} + + {if $smarty.get.success} +
Les données de configuration ont été mises à jour.
+ {/if} + +
+
+
{intl d='colissimo.home.delivery.bo.default' l="Configuration du service"}
+
+
+
+
+ {render_form_field field="colissimo_home_delivery_username" value=$colissimo_home_delivery_username} + {render_form_field field="colissimo_home_delivery_password" value=$colissimo_home_delivery_password} +
+ +
+ {render_form_field field="affranchissement_endpoint_url" value=$affranchissement_endpoint_url} + {render_form_field field="activate_detailed_debug" value=$activate_detailed_debug} +
+
+
+
+ + {/form} + +
+ +
+
+
+ {intl l="Price slices for domicile delivery" d='colissimo.home.delivery.bo.default'} +
+ + + +
+ + {assign var="isColissimoHomeDeliveryFreeshipping" value=0} + {form name="colissimo.homedelivery.freeshipping.form"} +
+
+ {form_hidden_fields form=$form} + {form_field form=$form field="freeshipping"} + +
+ {loop type="colissimo.homedelivery.freeshipping" name="freeshipping_colissimo_home_delivery"} + + {/loop} +
+ {/form_field} +
+
+
+ {form_field form=$form field="freeshipping_from"} + {loop type="colissimo.homedelivery.freeshipping" name="freeshipping_colissimo_home_delivery"} + {intl l="Or activate free shipping from (€) :" d="colissimo.home.delivery.bo.default"} + + {/loop} + {/form_field} + + + +
+
+
+ {/form} +
+ +
+ + + +
+ {intl l="You can create price slices by specifying a maximum cart weight and/or a maximum cart price." d='colissimo.home.delivery.bo.default'} + {intl l="The slices are ordered by maximum cart weight then by maximum cart price." d='colissimo.home.delivery.bo.default'} + {intl l="If a cart matches multiple slices, it will take the last slice following that order." d='colissimo.home.delivery.bo.default'} + {intl l="If you don't specify a cart weight in a slice, it will have priority over the slices with weight." d='colissimo.home.delivery.bo.default'} + {intl l="If you don't specify a cart price in a slice, it will have priority over the other slices with the same weight." d='colissimo.home.delivery.bo.default'} + {intl l="If you specify both, the cart will require to have a lower weight AND a lower price in order to match the slice." d='colissimo.home.delivery.bo.default'} +
+ +
+ {loop type="module" name="colissimo_home_delivery_id" code="ColissimoHomeDelivery"} + {loop type="area" name="area_loop" module_id=$ID backend_context=true} + {$area_id=$ID} +
+
+ + + + + + + + + + + + + + + + + + {loop type="colissimo.homedelivery.price-slices" name="colissimo_home_delivery_area_$ID" area_id={$area_id} } + + + + + + + {/loop} + + {* New slice *} + {loop type="auth" name="can_change" role="ADMIN" module="colissimohomedelivery" access="CREATE"} + + + + + + + {/loop} + +
+ + + +
{intl l="Weight up to ... kg" d='colissimo.home.delivery.bo.default'}{intl l="Untaxed Price up to ... ($)" d='colissimo.home.delivery.bo.default'}{intl l="Shipping Price ($)" d='colissimo.home.delivery.bo.default'}{intl l="Actions" d='colissimo.home.delivery.bo.default'}
+ + + + + + +
+ {loop type="auth" name="can_change" role="ADMIN" module="customdelivery" access="UPDATE"} + + + + {/loop} + {loop type="auth" name="can_change" role="ADMIN" module="customdelivery" access="DELETE"} + + + + {/loop} +
+
+ + + + + + + + + +
+
+
+ {/loop} + {elseloop rel="area_loop"} +
+
+ {intl d='colissimo.home.delivery.bo.default' l="You should first attribute shipping zones to the modules: "} + + {intl d='colissimo.home.delivery.bo.default' l="manage shipping zones"} + +
+
+ {/elseloop} + {/loop} +
+
+ + {include + file = "includes/generic-warning-dialog.html" + + dialog_id = "colissimo_home_delivery_dialog" + dialog_title = {intl d='colissimo.home.delivery.bo.default' l="Message"} + dialog_body = "" + } + + {* JS Templates *} + +
+
+
\ No newline at end of file diff --git a/local/modules/ColissimoHomeDelivery/templates/email/default/order_shipped.html b/local/modules/ColissimoHomeDelivery/templates/email/default/order_shipped.html new file mode 100644 index 00000000..d56f4620 --- /dev/null +++ b/local/modules/ColissimoHomeDelivery/templates/email/default/order_shipped.html @@ -0,0 +1,34 @@ +{extends file="email-layout.tpl"} + +{* Do not provide a "Open in browser" link *} +{block name="browser"}{/block} +{* No pre-header *} +{block name="pre-header"}{/block} + +{* Subject *} +{block name="email-subject"}{intl l="Your order confirmation Nº %ref" ref={$order_ref}}{/block} + +{* Title *} +{block name="email-title"}{/block} + +{* Content *} +{block name="email-content"} + + {loop type="customer" name="customer.politesse" id={$customer_id} current="0"} + {assign var="customerRef" value=$REF} + +

{if {$TITLE} == 9}{intl l="Dear Mr. "} + {else}{intl l="Dear Ms. "} + {/if} + {$FIRSTNAME} {$LASTNAME}, +

+ + {/loop} + +

{intl l="We are pleased to inform you that your order number"} {$order_ref} {intl l="has been shipped on"} {format_date date=$update_date output="date"} {intl l="with the tracking number"} {$package}.

+ +

{intl l='Click here to track your shipment. You can also enter the tracking number on https://www.laposte.fr/outils/suivre-vos-envois' package=$package}

+

{intl l='Thank you for your shopping with us and hope to see you soon on www.yourshop.com'}

+

{intl l="Your on-line store Manager"}
+ {intl l="Your shop"}

+{/block} diff --git a/local/modules/ColissimoHomeDelivery/templates/email/default/order_shipped.txt b/local/modules/ColissimoHomeDelivery/templates/email/default/order_shipped.txt new file mode 100644 index 00000000..7222a484 --- /dev/null +++ b/local/modules/ColissimoHomeDelivery/templates/email/default/order_shipped.txt @@ -0,0 +1 @@ +{intl l="Please display this message in HTML"} diff --git a/local/modules/ColissimoHomeDelivery/templates/frontOffice/default/assets/css/styles.css b/local/modules/ColissimoHomeDelivery/templates/frontOffice/default/assets/css/styles.css new file mode 100644 index 00000000..8a20b86c --- /dev/null +++ b/local/modules/ColissimoHomeDelivery/templates/frontOffice/default/assets/css/styles.css @@ -0,0 +1,8 @@ +#point-colissimo-homedelivery .panel-body { + padding: 10px !important; +} + +#point-colissimo-homedelivery .panel-body span { + color: red; + padding-left: 10px !important; +} diff --git a/local/modules/ColissimoHomeDelivery/templates/frontOffice/default/avec-signature.html b/local/modules/ColissimoHomeDelivery/templates/frontOffice/default/avec-signature.html new file mode 100644 index 00000000..5dd4d2da --- /dev/null +++ b/local/modules/ColissimoHomeDelivery/templates/frontOffice/default/avec-signature.html @@ -0,0 +1,27 @@ + + +
+
+
+ {intl l="Titre Avec signature" d="colissimohomedelivery.fo.default"} +
+
+  {intl l="Message Avec signature" d="colissimohomedelivery.fo.default" surcout={config key="surcout_remise_avec_signature"} unite={currency attr="symbol"}} +
+
+ + + + \ No newline at end of file diff --git a/local/modules/ColissimoHomeDelivery/templates/pdf/default/customs-invoice.html b/local/modules/ColissimoHomeDelivery/templates/pdf/default/customs-invoice.html new file mode 100644 index 00000000..2295bb5a --- /dev/null +++ b/local/modules/ColissimoHomeDelivery/templates/pdf/default/customs-invoice.html @@ -0,0 +1,417 @@ +{*************************************************************************************/ +/* This file is part of the Thelia package. */ +/* */ +/* Copyright (c) OpenStudio */ +/* email : dev@thelia.net */ +/* web : http://www.thelia.net */ +/* */ +/* For the full copyright and license information, please view the LICENSE.txt */ +/* file that was distributed with this source code. */ +/*************************************************************************************} + +{* -- Define some stuff for Smarty ------------------------------------------ *} +{assign var="store_name" value={config key="store_name"}} +{assign var="store_description" value={config key="store_description"}} +{assign var="store_phone" value={config key="store_phone"}} +{assign var="store_email" value={config key="store_email"}} +{assign var="store_description" value={config key="store_description"}} + +{assign var="store_address1" value={config key="store_address1"}} +{assign var="store_address2" value={config key="store_address2"}} +{assign var="store_address3" value={config key="store_address3"}} +{assign var="store_zipcode" value={config key="store_zipcode"}} +{assign var="store_city" value={config key="store_city"}} +{assign var="store_country_code" value={config key="store_country_code"}} + +{loop type="country" name="store_country_name_loop" id="$store_country_code"} +{assign var="store_country_name" value=$TITLE} +{/loop} + +{assign var="lang_code" value={lang attr="code"}} +{assign var="lang_locale" value={lang attr="locale"}} +{if not $store_name}{assign var="store_name" value={intl l='Thelia V2'}}{/if} +{if not $store_description}{assign var="store_description" value={$store_name}}{/if} + +{* Set the default translation domain, that will be used by {intl} when the 'd' parameter is not set *} +{default_translation_domain domain='pdf.mfk'} + +{* Declare assets directory, relative to template base directory *} +{declare_assets directory='assets'} +{literal} + + +{/literal} + + + + + + + + + + {$taxes = []} + + {loop name="order.invoice" type="order" id=$order_id customer="*"} + + {loop name="currency.order" type="currency" id=$CURRENCY} + {assign "orderCurrency" $ISOCODE} + {assign "orderCurrencySymbol" $SYMBOL} + {/loop} + + + + + + + + + + +
+ + + + + + + + + +
Sender
+

+ {$store_name} + {$store_address1}
+ {if $store_address2!=null} {$store_address2}
{/if} + {if $store_address3!=null} {$store_address3}
{/if} + {$store_zipcode} {$store_city}
+ {$store_country}
+

+
+
+ +
+
Commercial Invoice
+ Date: {format_date date=$INVOICE_DATE output="date"}
+ Invoice number: {$REF} +
+
+ + + + + + + + +
+ + + + + + + + +
Delivery address
+

+ {loop type="order_address" name="delivery_address" id=$DELIVERY_ADDRESS} + {loop type="title" name="order-invoice-address-title" id=$TITLE}{$LONG} {/loop} {$FIRSTNAME} {$LASTNAME} +
+ {if ! empty($COMPANY)} + {$COMPANY} +
+ {/if} + {$ADDRESS1} {$ADDRESS2} {$ADDRESS3} +
+ {$ZIPCODE} {$CITY} +
+ {loop type="country" name="country_delivery" id=$COUNTRY}{$TITLE}{/loop} +
+ {$PHONE} + {/loop} +

+
+
+ + + + + + + + +
Invoice address
+

+ {loop type="order_address" name="delivery_address" id=$INVOICE_ADDRESS} + {loop type="title" name="order-invoice-address-title" id=$TITLE}{$LONG} {/loop}{$FIRSTNAME} {$LASTNAME} +
+ {if ! empty($COMPANY)} + {$COMPANY} +
+ {/if} + {$ADDRESS1} {$ADDRESS2} {$ADDRESS3} +
+ {$ZIPCODE} {$CITY} +
+ {loop type="country" name="country_delivery" id=$COUNTRY}{$TITLE}{/loop} +
+ {$PHONE} {$MOBILE} + {/loop} +
+ {loop type="customer" name="customer_email" id=$CUSTOMER current="0"} + {$EMAIL} + {/loop} +

+
+
+
+ + {$totalValue = $TOTAL_TAXED_AMOUNT - $POSTAGE_UNTAXED} + {$itemCount = 0} + + + + + + + + + + + + + + + + + + + + + + {loop type="order_product" name="order-products" order=$ID} + {if $WAS_IN_PROMO == 1} + {assign "realPrice" $PROMO_PRICE} + {assign "realTax" $PROMO_PRICE_TAX} + {assign "realTaxedPrice" $TAXED_PROMO_PRICE} + {else} + {assign "realPrice" $PRICE} + {assign "realTax" $PRICE_TAX} + {assign "realTaxedPrice" $TAXED_PRICE} + {/if} + + {if $realTax==null} + {assign "realTax" 0} + {/if} + + {$taxes[{$TAX_RULE_TITLE}][] = $realTax * $QUANTITY} + + + + + + + + + + + {/loop} + + {loop type="mfk.selection.order" name="cadeaux_et_message_cadeau" order_id=$order_id} + {if ! empty($ECHANTILLON_1) || ! empty($ECHANTILLON_2)} + {$prixEchantillons = floatval({config key="tarif_echantillons_export"})} + + + + + + + + + + {$totalValue = $totalValue + $prixEchantillons} + {$itemCount = $itemCount + 1} + + {/if} + + {if ! empty($CADEAU)} + {$prixCadeau = floatval({config key="tarif_cadeau_export"})} + + + + + + + + + + {* A changer si besoin *} + {$totalValue = $totalValue + $prixCadeau} + {$itemCount = $itemCount + 1} + + {/if} + + {/loop} +
{intl l="Full Description of Goods"}{intl l="Quantity"}{intl l="Unit value"}{intl l="Subtotal value"}{intl l="Unit net weight"}{intl l="Country"}{intl l="Comm. code"}
+ + {$itemCount = $itemCount + $QUANTITY} + + {$TITLE} + {ifloop rel="combinations"} +
+ {loop type="order_product_attribute_combination" name="combinations" order_product=$ID} + - {$ATTRIBUTE_TITLE} - {$ATTRIBUTE_AVAILABILITY_TITLE} +
+ {/loop} + {/ifloop} + + {loop type="marquage.orderproduct" name="gravures" order_product_id=$ID} + {loop type="marquage.police" name="police" id=$POLICE} + {$nomPolice = $NOM} + {/loop} +
+ {intl l='Engraving '}: +
+ - {intl l='Font '}: {$nomPolice} +
+ - {intl l='Position '}: {$POSITION} +
+ - {intl l='Style '}: {$TYPE} +
+ - {intl l='Your text '}: {$TEXTE} + {/loop} + +
{$QUANTITY}{format_money number=$realTaxedPrice symbol=$orderCurrencySymbol}{format_money number={$realTaxedPrice * $QUANTITY} symbol=$orderCurrencySymbol}{$WEIGHT}France 
{intl l="Free samples "}: {$ECHANTILLON_1} + , {$ECHANTILLON_2}1{format_money number=$prixEchantillons}{format_money number=$prixEchantillons}France 
{intl l="Your gift "}: {$CADEAU}1{format_money number=$prixCadeau}{format_money number=$prixCadeau}France 
+ + {if $POSTAGE_TAX_RULE_TITLE} + {$taxes[$POSTAGE_TAX_RULE_TITLE][] = $POSTAGE_TAX} + {/if} + + + + + + + + + + +
  +

Total declared value : {format_money number={$totalValue} symbol=$orderCurrency}

+

Total units: {$itemCount}

+
+

Total Net Weight: {$WEIGHT} kg(s)

+ {* Mettre une estimation du poids brut *} +

Total Gross Weight: {$WEIGHT + 0} kg(s)

+
+ + + + + + + + +
+

Type of Export: permanent

+

Reason for Export

+
+

Currency Code :{$orderCurrency}

+

Terms of Trade : DAP

+

City Name of liability

+
+ + + + + + + + + +
+

Signature: {intl l="Sender's name"}

+

Airwaybill Number:

+
+

Company Stamp: {$store_name}

+

{$store_zipcode} {$store_city}

+
+ + {/loop} +
\ No newline at end of file diff --git a/local/modules/ColissimoLabel/ColissimoLabel.php b/local/modules/ColissimoLabel/ColissimoLabel.php new file mode 100644 index 00000000..8927b85a --- /dev/null +++ b/local/modules/ColissimoLabel/ColissimoLabel.php @@ -0,0 +1,410 @@ +gilles.bourgeat@gmail.com> + */ +class ColissimoLabel extends BaseModule +{ + /** Constants */ + const DOMAIN_NAME = 'colissimolabel'; + + const LABEL_FOLDER = THELIA_LOCAL_DIR . 'colissimo-label'; + + const BORDEREAU_FOLDER = self::LABEL_FOLDER . DIRECTORY_SEPARATOR . 'bordereau'; + + const AUTHORIZED_MODULES = ['ColissimoWs', 'SoColissimo', 'ColissimoHomeDelivery', 'ColissimoPickupPoint']; + + const CONFIG_KEY_DEFAULT_LABEL_FORMAT = 'default-label-format'; + + const CONFIG_KEY_CONTRACT_NUMBER = 'contract-number'; + + const CONFIG_KEY_PASSWORD = 'password'; + + const CONFIG_KEY_LAST_BORDEREAU_DATE = 'last-bordereau-date'; + + const CONFIG_DEFAULT_KEY_LAST_BORDEREAU_DATE = 1970; + + const CONFIG_KEY_DEFAULT_SIGNED = 'default-signed'; + + const CONFIG_DEFAULT_KEY_DEFAULT_SIGNED = true; + + const CONFIG_KEY_GENERATE_BORDEREAU = 'generate-bordereau'; + + const CONFIG_DEFAULT_KEY_GENERATE_BORDEREAU = false; + + const CONFIG_KEY_GET_INVOICES = 'get-invoices'; + + const CONFIG_DEFAULT_KEY_GET_INVOICES = true; + + const CONFIG_KEY_GET_CUSTOMS_INVOICES = 'get-customs-invoices'; + + const CONFIG_DEFAULT_KEY_GET_CUSTOMS_INVOICES = false; + + const CONFIG_KEY_CUSTOMS_PRODUCT_HSCODE = 'customs-product-hscode'; + + const CONFIG_DEFAULT_KEY_CUSTOMS_PRODUCT_HSCODE = ''; + + const CONFIG_KEY_STATUS_CHANGE = 'new_status'; + + const CONFIG_DEFAULT_KEY_STATUS_CHANGE = 'nochange'; + + const CONFIG_KEY_ENDPOINT = 'colissimolabel-endpoint'; + + const CONFIG_DEFAULT_KEY_ENDPOINT = 'https://ws.colissimo.fr/sls-ws/SlsServiceWS/2.0?wsdl'; + + const CONFIG_KEY_FROM_NAME = 'colissimolabel-company-name'; + + const CONFIG_KEY_FROM_ADDRESS_1 = 'colissimolabel-from-address-1'; + + const CONFIG_KEY_FROM_ADDRESS_2 = 'colissimolabel-from-address-2'; + + const CONFIG_KEY_FROM_CITY = 'colissimolabel-from-city'; + + const CONFIG_KEY_FROM_ZIPCODE = 'colissimolabel-from-zipcode'; + + const CONFIG_KEY_FROM_COUNTRY = 'colissimolabel-from-country'; + + const CONFIG_KEY_FROM_CONTACT_EMAIL = 'colissimolabel-from-contact-email'; + + const CONFIG_KEY_FROM_PHONE = 'colissimolabel-from-phone'; + + /** + * @param ConnectionInterface $con + */ + public function postActivation(ConnectionInterface $con = null) + { + static::checkLabelFolder(); + + if (!self::getConfigValue('is_initialized', false)) { + $database = new Database($con); + $database->insertSql(null, [__DIR__ . '/Config/thelia.sql']); + self::setConfigValue('is_initialized', true); + } + + $this->checkConfigurationsValues(); + } + + public function update($currentVersion, $newVersion, ConnectionInterface $con = null) + { + $finder = Finder::create() + ->name('*.sql') + ->depth(0) + ->sortByName() + ->in(__DIR__ . DS . 'Config' . DS . 'update'); + + $database = new Database($con); + + /** @var \SplFileInfo $file */ + foreach ($finder as $file) { + if (version_compare($currentVersion, $file->getBasename('.sql'), '<')) { + $database->insertSql(null, [$file->getPathname()]); + } + } + } + + /** + * Check if config values exist in the module config table exists. Creates them with a default value otherwise + */ + public function checkConfigurationsValues() + { + /** Check if the default label format config value exists, and sets it to PDF_10x15_300dpi is it doesn't exists */ + if (null === self::getConfigValue(self::CONFIG_KEY_DEFAULT_LABEL_FORMAT)) { + self::setConfigValue( + self::CONFIG_KEY_DEFAULT_LABEL_FORMAT, + OutputFormat::OUTPUT_PRINTING_TYPE_DEFAULT + ); + } + + /** + * Check if the contract number config value exists, and sets it to either of the following : + * The contract number of the ColissimoHomeDelivery config, if the module is installed + * Otherwise : the contract number of the ColissimoPickupPoint config, if the module is installed + * Otherwise : the contract number of the ColissimoWs config, if the module is installed + * Otherwise : the contract number of the SoColissimo config, if the module is installed + * Otherwise : a blanck string : "" + */ + if (null === self::getConfigValue(self::CONFIG_KEY_CONTRACT_NUMBER)) { + + $contractNumber = ''; + if (ModuleQuery::create()->findOneByCode(self::AUTHORIZED_MODULES[1])) { + $contractNumber = SoColissimo::getConfigValue('socolissimo_username'); + } + if (ModuleQuery::create()->findOneByCode(self::AUTHORIZED_MODULES[0])) { + $contractNumber = ColissimoWs::getConfigValue('colissimo_username'); + } + if (ModuleQuery::create()->findOneByCode(self::AUTHORIZED_MODULES[3])) { + $contractNumber = ColissimoPickupPoint::getConfigValue('colissimo_pickup_point_username'); + } + if (ModuleQuery::create()->findOneByCode(self::AUTHORIZED_MODULES[2])) { + $contractNumber = ColissimoHomeDelivery::getConfigValue('colissimo_home_delivery_username'); + } + + self::setConfigValue( + self::CONFIG_KEY_CONTRACT_NUMBER, + $contractNumber + ); + } + + /** + * Check if the contract password config value exists, and sets it to either of the following : + * The contract password of the ColissimoHomeDelivery config, if the module is activated + * Otherwise : the contract password of the ColissimoPickupPoint config, if the module is activated + * Otherwise : the contract password of the ColissimoWS config, if the module is activated + * Otherwise : the contract password of the SoColissimo config, if the module is activated + * Otherwise : a blank string : "" + */ + if (null === self::getConfigValue(self::CONFIG_KEY_PASSWORD)) { + + $contractPassword = ''; + if (ModuleQuery::create()->findOneByCode(self::AUTHORIZED_MODULES[1])) { + $contractPassword = SoColissimo::getConfigValue('socolissimo_password'); + } + if (ModuleQuery::create()->findOneByCode(self::AUTHORIZED_MODULES[0])) { + $contractPassword = ColissimoWs::getConfigValue('colissimo_password'); + } + if (ModuleQuery::create()->findOneByCode(self::AUTHORIZED_MODULES[3])) { + $contractPassword = ColissimoPickupPoint::getConfigValue('colissimo_pickup_point_password'); + } + if (ModuleQuery::create()->findOneByCode(self::AUTHORIZED_MODULES[2])) { + $contractPassword = ColissimoHomeDelivery::getConfigValue('colissimo_home_delivery_password'); + } + + self::setConfigValue( + self::CONFIG_KEY_PASSWORD, + $contractPassword + ); + } + + /** Check if the config value for the status change exists, creates it with a default value of 'nochange' otherwise */ + if (null === self::getConfigValue(self::CONFIG_KEY_STATUS_CHANGE)) { + self::setConfigValue( + self::CONFIG_KEY_STATUS_CHANGE, + self::CONFIG_DEFAULT_KEY_STATUS_CHANGE + ); + } + + /** Check if the config value for the endpoint exists, creates it with a default value otherwise */ + if (null === self::getConfigValue(self::CONFIG_KEY_ENDPOINT)) { + self::setConfigValue( + self::CONFIG_KEY_ENDPOINT, + self::CONFIG_DEFAULT_KEY_ENDPOINT + ); + } + + /** Check if the config value for the last bordereau date exists, creates it with a default value of 1970 otherwise */ + if (null === self::getConfigValue(self::CONFIG_KEY_LAST_BORDEREAU_DATE)) { + self::setConfigValue( + self::CONFIG_KEY_LAST_BORDEREAU_DATE, + self::CONFIG_DEFAULT_KEY_LAST_BORDEREAU_DATE + ); + } + + /** Check if the config value for the default signed state for labels exists, creates it with a value of true otherwise */ + if (null === self::getConfigValue(self::CONFIG_KEY_DEFAULT_SIGNED)) { + self::setConfigValue( + self::CONFIG_KEY_DEFAULT_SIGNED, + self::CONFIG_DEFAULT_KEY_DEFAULT_SIGNED + ); + } + + /** Check if the config value for whether bordereau should be generated with labels exists, creates it with a value of false otherwise */ + if (null === self::getConfigValue(self::CONFIG_KEY_GENERATE_BORDEREAU)) { + self::setConfigValue( + self::CONFIG_KEY_GENERATE_BORDEREAU, + (int)self::CONFIG_DEFAULT_KEY_GENERATE_BORDEREAU + ); + } + + /** Check if the config value for whether invoices should be automatically generated exists, creates it with a value of true otherwise */ + if (null === self::getConfigValue(self::CONFIG_KEY_GET_INVOICES)) { + self::setConfigValue( + self::CONFIG_KEY_GET_INVOICES, + self::CONFIG_DEFAULT_KEY_GET_INVOICES + ); + } + + /** Check if the config value for whether customs invoices should be automatically generated exists, creates it with a value of false otherwise */ + if (null === self::getConfigValue(self::CONFIG_KEY_GET_CUSTOMS_INVOICES)) { + self::setConfigValue( + self::CONFIG_KEY_GET_CUSTOMS_INVOICES, + self::CONFIG_DEFAULT_KEY_GET_CUSTOMS_INVOICES + ); + } + + /** Check if the config value for the customs product HsCode exists, creates it without value otherwise */ + if (null === self::getConfigValue(self::CONFIG_KEY_CUSTOMS_PRODUCT_HSCODE)) { + self::setConfigValue( + self::CONFIG_KEY_CUSTOMS_PRODUCT_HSCODE, + self::CONFIG_DEFAULT_KEY_CUSTOMS_PRODUCT_HSCODE + ); + } + + /** Check if the config values for the sender address exist, create them otherwise with the store address values otherwise */ + if (null === self::getConfigValue(self::CONFIG_KEY_FROM_NAME)) { + self::setConfigValue( + self::CONFIG_KEY_FROM_NAME, + ConfigQuery::read('store_name') + ); + } + + if (null === self::getConfigValue(self::CONFIG_KEY_FROM_ADDRESS_1)) { + self::setConfigValue( + self::CONFIG_KEY_FROM_ADDRESS_1, + ConfigQuery::read('store_address1') + ); + } + + if (null === self::getConfigValue(self::CONFIG_KEY_FROM_ADDRESS_2)) { + self::setConfigValue( + self::CONFIG_KEY_FROM_ADDRESS_2, + ConfigQuery::read('store_address2') + ); + } + + if (null === self::getConfigValue(self::CONFIG_KEY_FROM_CITY)) { + self::setConfigValue( + self::CONFIG_KEY_FROM_CITY, + ConfigQuery::read('store_city') + ); + } + + if (null === self::getConfigValue(self::CONFIG_KEY_FROM_ZIPCODE)) { + self::setConfigValue( + self::CONFIG_KEY_FROM_ZIPCODE, + ConfigQuery::read('store_zipcode') + ); + } + + if (null === self::getConfigValue(self::CONFIG_KEY_FROM_COUNTRY)) { + self::setConfigValue( + self::CONFIG_KEY_FROM_COUNTRY, + ConfigQuery::read('store_country') + ); + } + + if (null === self::getConfigValue(self::CONFIG_KEY_FROM_CONTACT_EMAIL)) { + self::setConfigValue( + self::CONFIG_KEY_FROM_CONTACT_EMAIL, + ConfigQuery::read('store_email') + ); + } + + if (null === self::getConfigValue(self::CONFIG_KEY_FROM_PHONE)) { + self::setConfigValue( + self::CONFIG_KEY_FROM_PHONE, + ConfigQuery::read('store_phone') + ); + } + /** Sender address values check end here */ + } + + /** + * Check if the label and bordereau folders exists. Creates them otherwise. + */ + public static function checkLabelFolder() + { + $fileSystem = new Filesystem(); + + if (!$fileSystem->exists(self::LABEL_FOLDER)) { + $fileSystem->mkdir(self::LABEL_FOLDER); + } + if (!$fileSystem->exists(self::BORDEREAU_FOLDER)) { + $fileSystem->mkdir(self::BORDEREAU_FOLDER); + } + } + + /** Get the path of a given label file, according to its number + * @param $fileName + * @param $extension + * @return string + */ + public static function getLabelPath($fileName, $extension) + { + return self::LABEL_FOLDER . DS . $fileName . '.' . $extension; + } + + /** Get the path of a given CN23 customs file, according to the order ref + * @param $fileName + * @param $extension + * @return string + */ + public static function getLabelCN23Path($fileName, $extension) + { + return self::LABEL_FOLDER . DS . $fileName . '.' . $extension; + } + + /** Get the path of a bordereau file, according to a date + * @param $date + * @return string + */ + public static function getBordereauPath($date) + { + return self::BORDEREAU_FOLDER . DS . $date . '.pdf'; + } + + /** Get the label files extension according to the file type indicated in the module config */ + public static function getFileExtension() + { + return strtolower(substr(OutputFormat::OUTPUT_PRINTING_TYPE[self::getConfigValue(self::CONFIG_KEY_DEFAULT_LABEL_FORMAT)], 0, 3)); + } + + /** + * Check if order has to be signed or if it is optional (aka if its in Europe or not) + * + * @param Order $order + * @return bool + * @throws PropelException + */ + public static function canOrderBeNotSigned(Order $order) + { + $countryIsoCode = $order->getOrderAddressRelatedByDeliveryOrderAddressId()->getCountry()->getIsocode(); + + /** Checking if the delivery country is in Europe or a DOMTOM. If not, it HAS to be signed */ + if (!in_array($countryIsoCode, Service::DOMTOM_ISOCODES, false) + && !in_array($countryIsoCode, Service::EUROPE_ISOCODES, false)) + { + return false; + } + + return true; + } + + /** + * Remove the accentuated and special characters from a string an replace them with + * latin ASCII characters. Does the same to cyrillic. + * + * @param $str + * @return false|string + */ + public static function removeAccents($str) { + return iconv("UTF-8", "ASCII//TRANSLIT//IGNORE", transliterator_transliterate('Any-Latin; Latin-ASCII; Upper()', $str)); + } +} diff --git a/local/modules/ColissimoLabel/Config/config.xml b/local/modules/ColissimoLabel/Config/config.xml new file mode 100644 index 00000000..6f290b0c --- /dev/null +++ b/local/modules/ColissimoLabel/Config/config.xml @@ -0,0 +1,60 @@ + + + + + + + + + + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/local/modules/ColissimoLabel/Config/module.xml b/local/modules/ColissimoLabel/Config/module.xml new file mode 100644 index 00000000..7821f402 --- /dev/null +++ b/local/modules/ColissimoLabel/Config/module.xml @@ -0,0 +1,24 @@ + + + ColissimoLabel\ColissimoLabel + + Generate the delivery labels for Colissimo + + + Genérer les étiquettes de livraison pour Colissimo + + + en_US + fr_FR + + 1.0.4 + + Gilles Bourgeat + gbourgeat@openstudio.fr + + classic + 2.2.0 + beta + diff --git a/local/modules/ColissimoLabel/Config/routing.xml b/local/modules/ColissimoLabel/Config/routing.xml new file mode 100644 index 00000000..fb06f9d8 --- /dev/null +++ b/local/modules/ColissimoLabel/Config/routing.xml @@ -0,0 +1,63 @@ + + + + + + ColissimoLabel\Controller\Admin\OrderController::generateLabelAction + + + + ColissimoLabel\Controller\Admin\OrderController::getLabelZip + [A-Za-z0-9]+ + + + + ColissimoLabel\Controller\Admin\OrderController::getLabelAction + [0-9A-Z]+ + + + + ColissimoLabel\Controller\Admin\OrderController::getCustomsInvoiceAction + [0-9A-Z]+ + + + + ColissimoLabel\Controller\Admin\OrderController::deleteLabelAction + [0-9A-Z]+ + + + + ColissimoLabel\Controller\Admin\OrderController::getOrderLabelsAction + [0-9]+ + + + + ColissimoLabel\Controller\Admin\BordereauController::listBordereauAction + + + + ColissimoLabel\Controller\Admin\ConfigurationController::renderConfigPageAction + + + + ColissimoLabel\Controller\Admin\ConfigurationController::saveConfig + + + + ColissimoLabel\Controller\Admin\BordereauController::listLabelsAction + + + + ColissimoLabel\Controller\Admin\BordereauController::generateBordereauAction + + + + ColissimoLabel\Controller\Admin\BordereauController::downloadBordereauAction + + + + ColissimoLabel\Controller\Admin\BordereauController::deleteBordereauAction + + diff --git a/local/modules/ColissimoLabel/Config/schema.xml b/local/modules/ColissimoLabel/Config/schema.xml new file mode 100644 index 00000000..becf4c9c --- /dev/null +++ b/local/modules/ColissimoLabel/Config/schema.xml @@ -0,0 +1,26 @@ + + + + + + + + + + + + + + + + + + + + +
+ + +
diff --git a/local/modules/ColissimoLabel/Config/sqldb.map b/local/modules/ColissimoLabel/Config/sqldb.map new file mode 100644 index 00000000..63a93baa --- /dev/null +++ b/local/modules/ColissimoLabel/Config/sqldb.map @@ -0,0 +1,2 @@ +# Sqlfile -> Database map +thelia.sql=thelia diff --git a/local/modules/ColissimoLabel/Config/thelia.sql b/local/modules/ColissimoLabel/Config/thelia.sql new file mode 100644 index 00000000..e96f30e0 --- /dev/null +++ b/local/modules/ColissimoLabel/Config/thelia.sql @@ -0,0 +1,36 @@ + +# This is a fix for InnoDB in MySQL >= 4.1.x +# It "suspends judgement" for fkey relationships until are tables are set. +SET FOREIGN_KEY_CHECKS = 0; + +-- --------------------------------------------------------------------- +-- colissimo_label +-- --------------------------------------------------------------------- + +DROP TABLE IF EXISTS `colissimo_label`; + +CREATE TABLE `colissimo_label` +( + `id` INTEGER NOT NULL AUTO_INCREMENT, + `order_id` INTEGER NOT NULL, + `order_ref` VARCHAR(255) NOT NULL, + `error` TINYINT(1) DEFAULT 0 NOT NULL, + `error_message` VARCHAR(255) DEFAULT '', + `tracking_number` VARCHAR(255), + `label_type` VARCHAR(4), + `weight` DECIMAL(6,2) DEFAULT 0.00, + `signed` TINYINT(1) DEFAULT 0 NOT NULL, + `with_customs_invoice` TINYINT(1) DEFAULT 0 NOT NULL, + `created_at` DATETIME, + `updated_at` DATETIME, + PRIMARY KEY (`id`), + INDEX `colissimo_label_FI_1` (`order_id`), + CONSTRAINT `colissimo_label_FK_1` + FOREIGN KEY (`order_id`) + REFERENCES `order` (`id`) + ON UPDATE RESTRICT + ON DELETE CASCADE +) ENGINE=InnoDB; + +# This restores the fkey checks, after having unset them earlier +SET FOREIGN_KEY_CHECKS = 1; diff --git a/local/modules/ColissimoLabel/Config/update/0.4.0.sql b/local/modules/ColissimoLabel/Config/update/0.4.0.sql new file mode 100644 index 00000000..d44638a9 --- /dev/null +++ b/local/modules/ColissimoLabel/Config/update/0.4.0.sql @@ -0,0 +1,12 @@ +# This is a fix for InnoDB in MySQL >= 4.1.x +# It "suspends judgement" for fkey relationships until are tables are set. +SET FOREIGN_KEY_CHECKS = 0; + +-- --------------------------------------------------------------------- +-- colissimo_label +-- --------------------------------------------------------------------- + +ALTER TABLE `colissimo_label` ADD COLUMN `signed` TINYINT NOT NULL AFTER `weight`; + +# This restores the fkey checks, after having unset them earlier +SET FOREIGN_KEY_CHECKS = 1; \ No newline at end of file diff --git a/local/modules/ColissimoLabel/Config/update/1.0.0.sql b/local/modules/ColissimoLabel/Config/update/1.0.0.sql new file mode 100644 index 00000000..e3e39e10 --- /dev/null +++ b/local/modules/ColissimoLabel/Config/update/1.0.0.sql @@ -0,0 +1,18 @@ +# This is a fix for InnoDB in MySQL >= 4.1.x +# It "suspends judgement" for fkey relationships until are tables are set. +SET FOREIGN_KEY_CHECKS = 0; + +-- --------------------------------------------------------------------- +-- colissimo_label +-- --------------------------------------------------------------------- + +ALTER TABLE `colissimo_label` ADD COLUMN `order_ref` VARCHAR(255) NOT NULL AFTER `order_id`; +ALTER TABLE `colissimo_label` ADD COLUMN `error` TINYINT NOT NULL AFTER `order_id`; +ALTER TABLE `colissimo_label` ADD COLUMN `error_message` VARCHAR(255) AFTER `order_ref`; +ALTER TABLE `colissimo_label` CHANGE COLUMN `number` `tracking_number` VARCHAR(255) NOT NULL; +ALTER TABLE `colissimo_label` ADD COLUMN `label_type` VARCHAR(4) NOT NULL AFTER `error_message`; +ALTER TABLE `colissimo_label` ADD COLUMN `with_customs_invoice` TINYINT NOT NULL AFTER `signed`; +ALTER TABLE `colissimo_label` MODIFY `tracking_number` VARCHAR(255) AFTER `error_message`; + +# This restores the fkey checks, after having unset them earlier +SET FOREIGN_KEY_CHECKS = 1; \ No newline at end of file diff --git a/local/modules/ColissimoLabel/Controller/Admin/BordereauController.php b/local/modules/ColissimoLabel/Controller/Admin/BordereauController.php new file mode 100644 index 00000000..d41db849 --- /dev/null +++ b/local/modules/ColissimoLabel/Controller/Admin/BordereauController.php @@ -0,0 +1,194 @@ +files()->in(ColissimoLabel::BORDEREAU_FOLDER); + + /** We set a variable for the name and path of every found bordereau file, to be used in the template */ + $bordereaux = []; + foreach ($finder as $file) { + $bordereaux[] = [ + 'name' => $file->getRelativePathname(), + 'path' => $file->getRealPath(), + ]; + } + + /** We sort the bordereau by last created date */ + sort($bordereaux); + $bordereaux = array_reverse($bordereaux); + + /** We render the page */ + return $this->render('colissimo-label/bordereau-list', compact('lastBordereauDate', 'bordereaux', 'error')); + } + + /** + * Render the label list page + * + * @return \Thelia\Core\HttpFoundation\Response + */ + public function listLabelsAction() + { + ColissimoLabel::checkLabelFolder(); + + return $this->render('colissimo-label/labels'); + } + + /** + * Generate the bordereau, using the tracking/parcel numbers from the labels and the date since the + * last time it was done + * + * @return \Thelia\Core\HttpFoundation\Response + * @throws \Exception + */ + public function generateBordereauAction() + { + /** Checking that the folder exists, and creates it otherwise */ + ColissimoLabel::checkLabelFolder(); + + $lastBordereauDate = ColissimoLabel::getConfigValue(ColissimoLabel::CONFIG_KEY_LAST_BORDEREAU_DATE); + + /** We get the informations of all labels since the last time we created a bordereau with this method */ + $labels = ColissimoLabelQuery::create() + ->filterByCreatedAt($lastBordereauDate, Criteria::GREATER_THAN) + ->find(); + + $parcelNumbers = []; + + /** @var ColissimoLabelModel $label */ + foreach ($labels as $label) { + $parcelNumbers[] = $label->getTrackingNumber(); + } + + /** Compatibility with ColissimoWS < 2.0.0 */ + if (ModuleQuery::create()->findOneByCode('ColissimoWs')) { + $labelsWs = ColissimowsLabelQuery::create() + ->filterByCreatedAt($lastBordereauDate, Criteria::GREATER_THAN) + ->find(); + + /** @var ColissimowsLabel $label */ + foreach ($labelsWs as $labelWs) { + $parcelNumbers[] = $labelWs->getTrackingNumber(); + } + } + + $service = new SOAPService(); + $APIConfiguration = new BordereauRequestAPIConfiguration(); + $APIConfiguration->setContractNumber(ColissimoLabel::getConfigValue(ColissimoLabel::CONFIG_KEY_CONTRACT_NUMBER)); + $APIConfiguration->setPassword(ColissimoLabel::getConfigValue(ColissimoLabel::CONFIG_KEY_PASSWORD)); + + $parseResponse = $service->callGenerateBordereauByParcelsNumbersAPI($APIConfiguration, $parcelNumbers); + $resultAttachment = $parseResponse->attachments; + if (!isset($resultAttachment[0])) { + if (!isset($parseResponse->soapResponse['data'])) { + return $this->listBordereauAction('No label found'); + } + return $this->listBordereauAction('Error : ' . $this->getError($parseResponse->soapResponse['data'])); + } + $bordereauContent = $resultAttachment[0]; + $fileContent = $bordereauContent['data']; + + if ('' == $fileContent) { + throw new \Exception('File is empty'); + } + + /** We save the file on the server */ + $filePath = ColissimoLabel::getBordereauPath('bordereau_' .(new \DateTime())->format('Y-m-d_H-i-s')); + $fileSystem = new Filesystem(); + $fileSystem->dumpFile( + $filePath, + $fileContent + ); + + /** We set the new date for the next time we want to use this method */ + ColissimoLabel::setConfigValue(ColissimoLabel::CONFIG_KEY_LAST_BORDEREAU_DATE, (new \DateTime())->format('Y-m-d H:i:s')); + + /** We reload the list of bordereau */ + return $this->listBordereauAction(); + } + + /** + * Return the error message contained in the SOAP response from Colissimo + * + * @param $data + * @return array + */ + protected function getError($data) { + $errorMessage = explode("", $data); + $errorMessage = explode("", $errorMessage[1]); + + return $errorMessage[0]; + } + + /** + * Retrieve a bordereau on the server given its filename passed in the request, and return it as a binary response + * + * @return BinaryFileResponse + */ + public function downloadBordereauAction() + { + $filePath = $this->getRequest()->get('filePath'); + $filePathArray = explode('/', $filePath); + $fileName = array_pop($filePathArray); + $download = $this->getRequest()->get('stay'); + + $response = new BinaryFileResponse($filePath); + + /** Download instead of opening the label in a window, if requested */ + if ($download) { + $response->setContentDisposition( + ResponseHeaderBag::DISPOSITION_ATTACHMENT, + $fileName + ); + } + + + return $response; + } + + /** + * Deletes a bordereau file, then reload the page + * + * @return \Thelia\Core\HttpFoundation\Response + */ + public function deleteBordereauAction() { + $fs = new Filesystem(); + $filePath = $this->getRequest()->get('filePath'); + + $fs->remove($filePath); + + return $this->listBordereauAction(); + } +} \ No newline at end of file diff --git a/local/modules/ColissimoLabel/Controller/Admin/ConfigurationController.php b/local/modules/ColissimoLabel/Controller/Admin/ConfigurationController.php new file mode 100644 index 00000000..8961982a --- /dev/null +++ b/local/modules/ColissimoLabel/Controller/Admin/ConfigurationController.php @@ -0,0 +1,72 @@ +checkConfigurationsValues(); + + return $this->render('colissimo-label/module-configuration'); + } + + public function saveConfig() + { + if (null !== $response = $this->checkAuth(array(AdminResources::MODULE), array('ColissimoLabel'), AccessManager::UPDATE)) { + return $response; + } + + $form = new ConfigureColissimoLabel($this->getRequest()); + try { + $vform = $this->validateForm($form); + + /** General config values */ + ColissimoLabel::setConfigValue(ColissimoLabel::CONFIG_KEY_CONTRACT_NUMBER, $vform->get(ColissimoLabel::CONFIG_KEY_CONTRACT_NUMBER)->getData()); + ColissimoLabel::setConfigValue(ColissimoLabel::CONFIG_KEY_PASSWORD, $vform->get(ColissimoLabel::CONFIG_KEY_PASSWORD)->getData()); + ColissimoLabel::setConfigValue(ColissimoLabel::CONFIG_KEY_DEFAULT_SIGNED, (int)$vform->get(ColissimoLabel::CONFIG_KEY_DEFAULT_SIGNED)->getData()); + ColissimoLabel::setConfigValue(ColissimoLabel::CONFIG_KEY_GENERATE_BORDEREAU, (int)$vform->get(ColissimoLabel::CONFIG_KEY_GENERATE_BORDEREAU)->getData()); + ColissimoLabel::setConfigValue(ColissimoLabel::CONFIG_KEY_DEFAULT_LABEL_FORMAT, $vform->get(ColissimoLabel::CONFIG_KEY_DEFAULT_LABEL_FORMAT)->getData()); + ColissimoLabel::setConfigValue(ColissimoLabel::CONFIG_KEY_LAST_BORDEREAU_DATE, $vform->get(ColissimoLabel::CONFIG_KEY_LAST_BORDEREAU_DATE)->getData()); + ColissimoLabel::setConfigValue(ColissimoLabel::CONFIG_KEY_GET_INVOICES, (int)$vform->get(ColissimoLabel::CONFIG_KEY_GET_INVOICES)->getData()); + ColissimoLabel::setConfigValue(ColissimoLabel::CONFIG_KEY_GET_CUSTOMS_INVOICES, (int)$vform->get(ColissimoLabel::CONFIG_KEY_GET_CUSTOMS_INVOICES)->getData()); + ColissimoLabel::setConfigValue(ColissimoLabel::CONFIG_KEY_CUSTOMS_PRODUCT_HSCODE, $vform->get(ColissimoLabel::CONFIG_KEY_CUSTOMS_PRODUCT_HSCODE)->getData()); + ColissimoLabel::setConfigValue(ColissimoLabel::CONFIG_KEY_ENDPOINT, $vform->get(ColissimoLabel::CONFIG_KEY_ENDPOINT)->getData()); + + /** Sender's address values */ + ColissimoLabel::setConfigValue(ColissimoLabel::CONFIG_KEY_FROM_NAME, $vform->get(ColissimoLabel::CONFIG_KEY_FROM_NAME)->getData()); + ColissimoLabel::setConfigValue(ColissimoLabel::CONFIG_KEY_FROM_ADDRESS_1, $vform->get(ColissimoLabel::CONFIG_KEY_FROM_ADDRESS_1)->getData()); + ColissimoLabel::setConfigValue(ColissimoLabel::CONFIG_KEY_FROM_ADDRESS_2, $vform->get(ColissimoLabel::CONFIG_KEY_FROM_ADDRESS_2)->getData()); + ColissimoLabel::setConfigValue(ColissimoLabel::CONFIG_KEY_FROM_CITY, $vform->get(ColissimoLabel::CONFIG_KEY_FROM_CITY)->getData()); + ColissimoLabel::setConfigValue(ColissimoLabel::CONFIG_KEY_FROM_ZIPCODE, $vform->get(ColissimoLabel::CONFIG_KEY_FROM_ZIPCODE)->getData()); + ColissimoLabel::setConfigValue(ColissimoLabel::CONFIG_KEY_FROM_COUNTRY, $vform->get(ColissimoLabel::CONFIG_KEY_FROM_COUNTRY)->getData()); + ColissimoLabel::setConfigValue(ColissimoLabel::CONFIG_KEY_FROM_CONTACT_EMAIL, $vform->get(ColissimoLabel::CONFIG_KEY_FROM_CONTACT_EMAIL)->getData()); + ColissimoLabel::setConfigValue(ColissimoLabel::CONFIG_KEY_FROM_PHONE, $vform->get(ColissimoLabel::CONFIG_KEY_FROM_PHONE)->getData()); + if ($vform->get(ColissimoLabel::CONFIG_KEY_FROM_ADDRESS_2)->getData() === ' ') { + ColissimoLabel::setConfigValue(ColissimoLabel::CONFIG_KEY_FROM_ADDRESS_2, null); + } + + return $this->generateRedirect( + URL::getInstance()->absoluteUrl('/admin/module/colissimolabel/configuration') + ); + } catch (\Exception $e) { + $this->setupFormErrorContext( + Translator::getInstance()->trans('ColissimoLabel update config'), + $e->getMessage(), + $form, + $e + ); + + return $this->renderConfigPageAction(); + } + } +} \ No newline at end of file diff --git a/local/modules/ColissimoLabel/Controller/Admin/OrderController.php b/local/modules/ColissimoLabel/Controller/Admin/OrderController.php new file mode 100644 index 00000000..433b9d1c --- /dev/null +++ b/local/modules/ColissimoLabel/Controller/Admin/OrderController.php @@ -0,0 +1,368 @@ +checkAuth(array(AdminResources::MODULE), array('ColissimoLabel'), AccessManager::UPDATE)) { + return new JsonResponse([ + 'error' => $this->getTranslator()->trans("Sorry, you're not allowed to perform this action") + ], 403); + } + + /** Make sure label and bordereau directories exist, creates them otherwise */ + ColissimoLabel::checkLabelFolder(); + + $exportForm = $this->createForm('colissimolabel_export_form'); + + $files = $params = $parcelNumbers = []; + + try { + $form = $this->validateForm($exportForm); + + $data = $form->getData(); + + $isEditPage = $request->query->get('edit-order'); + + ColissimoLabel::setConfigValue('new_status', $data['new_status']); + + $service = $this->getContainer()->get('colissimolabel.generate.label.service'); + $response = $service->generateLabel($data, $isEditPage); + + if ($isEditPage) { + return $response; + } + } catch (\Exception $ex) { + $this->setupFormErrorContext("Generation étiquettes Colissimo", $ex->getMessage(), $exportForm, $ex); + } + + foreach ($data['order_id'] as $orderId) { + if (null !== $order = OrderQuery::create()->findOneById($orderId)) { + $fileSystem = new Filesystem(); + /** Generates and dump the invoice file if it is requested */ + if (ColissimoLabel::getConfigValue(ColissimoLabel::CONFIG_KEY_GET_INVOICES)) { + $invoiceResponse = $this->generateOrderPdf($orderId, ConfigQuery::read('pdf_invoice_file', 'invoice')); + $fileSystem->dumpFile( + $invoiceName = ColissimoLabel::getLabelPath($order->getRef() . '-invoice', 'pdf'), + $invoiceResponse->getContent() + ); + $files[] = $invoiceName; + } + } + } + + /** If we get here, that means the form was called from the module label page so we put every file requested in a .zip */ + if (count($files) > 0) { + $bordereau = null; + if (ColissimoLabel::getConfigValue(ColissimoLabel::CONFIG_KEY_GENERATE_BORDEREAU)) { + $bordereau = $this->addBordereau($parcelNumbers); + $files[] = $bordereau; + } + + $zip = new \ZipArchive(); + $zipFilename = sys_get_temp_dir() . DS . uniqid('colissimo-label-', false); + + if (true !== $zip->open($zipFilename, \ZipArchive::CREATE)) { + throw new TheliaProcessException("Cannot open zip file $zipFilename\n"); + } + + foreach ($files as $file) { + $zip->addFile($file, basename($file)); + } + + $zip->close(); + + $params = [ 'zip' => base64_encode($zipFilename) ]; + + if ($bordereau) { + $fs = new Filesystem(); + $fs->remove($bordereau); + } + } + + /** We redirect to the module label page with parameters to download the zip file as well */ + return $this->generateRedirect(URL::getInstance()->absoluteUrl('/admin/module/colissimolabel/labels', $params)); + } + + /** + * Add a bordereau to the labels generated, if requested + * + * @param $parcelNumbers + * @return string + * @throws \Exception + */ + protected function addBordereau($parcelNumbers) { + $service = new SOAPService(); + $APIConfiguration = new BordereauRequestAPIConfiguration(); + $APIConfiguration->setContractNumber(ColissimoLabel::getConfigValue(ColissimoLabel::CONFIG_KEY_CONTRACT_NUMBER)); + $APIConfiguration->setPassword(ColissimoLabel::getConfigValue(ColissimoLabel::CONFIG_KEY_PASSWORD)); + + $parseResponse = $service->callGenerateBordereauByParcelsNumbersAPI($APIConfiguration, $parcelNumbers); + $resultAttachment = $parseResponse->attachments; + $bordereauContent = $resultAttachment[0]; + $fileContent = $bordereauContent['data']; + + if ('' == $fileContent) { + throw new \Exception('File is empty'); + } + + $filePath = ColissimoLabel::getLabelPath('bordereau', 'pdf'); + + $fileSystem = new Filesystem(); + $fileSystem->dumpFile( + $filePath, + $fileContent + ); + + return $filePath; + } + + /** + * Return a template with a list of all labels for a given order + * + * @param $orderId + * @return Response + */ + public function getOrderLabelsAction($orderId) + { + if (null !== $response = $this->checkAuth(AdminResources::ORDER, [], AccessManager::UPDATE)) { + return new Response($this->getTranslator()->trans("Sorry, you're not allowed to perform this action"), 403); + } + + return $this->render('colissimo-label/label-list', ['order_id' => $orderId]); + } + + /** + * Delete the label and invoice files on the server, given to the label name + * + * @param $fileName + */ + protected function deleteLabelFile($fileName) { + $finder = new Finder(); + $fileSystem = new Filesystem(); + + $finder->files()->name($fileName . '*')->in(ColissimoLabel::LABEL_FOLDER); + foreach ($finder as $file) { + $fileSystem->remove(ColissimoLabel::LABEL_FOLDER . DS . $file->getFilename()); + } + } + + /** + * Delete a label file from server and delete its related table entry + * + * Compatibility with ColissimoLabel < 1.0.0 + * Compatibility with ColissimoWs < 2.0.0 + * + * @param Request $request + * @param $number + * @return \Symfony\Component\HttpFoundation\Response + * @throws PropelException + */ + public function deleteLabelAction(Request $request, $number) { + $label = ColissimoLabelQuery::create()->findOneByTrackingNumber($number); + /** We check if the label is from this module -- Compatibility with ColissimoWs */ + if ($label) { + /** We check if the label is from this version of the module -- Compatibility with ColissimoLabel < 1.0.0 */ + if ('' !== $orderRef = $label->getOrderRef()) { + $this->deleteLabelFile($orderRef); + $label->delete(); + + /** Handle the return when called from order edit */ + if ($editOrder = $request->get('edit-order')) { + return $this->generateRedirect(URL::getInstance()->absoluteUrl('/admin/order/update/' . $label->getOrderId() . '?tab=bill')); + } + + return $this->generateRedirect(URL::getInstance()->absoluteUrl('admin/module/colissimolabel/labels#order-' . $label->getOrderId())); + } + } + + /** + * If we're here, it means the label was not from this module or module version, so we get it by other means + * for compatibility reasons. + */ + + /** Trying to get it from ColissimoWs */ + if ($orderId = $request->get('order')) { + /** Checking if ColissimoWs is installed */ + if (ModuleQuery::create()->findOneByCode(ColissimoLabel::AUTHORIZED_MODULES[0])) { + /** Checking if the label entry exists in the deprecated ColissimoWsLabel table */ + if ($colissimoWslabel = ColissimowsLabelQuery::create()->findOneByOrderId($orderId)) { + $orderRef = $colissimoWslabel->getOrderRef(); + $this->deleteLabelFile($orderRef); + + $colissimoWslabel->delete(); + + /** Handle the return when called from order edit */ + if ($editOrder = $request->get('edit-order')) { + return $this->generateRedirect(URL::getInstance()->absoluteUrl('/admin/order/update/' . $orderId . '?tab=bill')); + } + + return $this->generateRedirect(URL::getInstance()->absoluteUrl('admin/module/colissimolabel/labels#order-' . $orderId)); + } + } + } + + /** + * If we're here, it means the label is coming from a version of ColissimoLabel < 1.0.0 + * So we need to delete it with its tracking number instead of order ref, since it was named like that back then + */ + $this->deleteLabelFile($number); + $label->delete(); + + /** Handle the return when called from order edit */ + if ($editOrder = $request->get('edit-order')) { + return $this->generateRedirect(URL::getInstance()->absoluteUrl('/admin/order/update/' . $label->getOrderId() . '?tab=bill')); + } + + return $this->generateRedirect(URL::getInstance()->absoluteUrl('admin/module/colissimolabel/labels#order-' . $label->getOrderId())); + } + + /** + * Download the CN23 customs invoice, given an order Id + * + * @param $orderId + * @return \Symfony\Component\HttpFoundation\Response|Response + * @throws \Exception + */ + public function getCustomsInvoiceAction($orderId) { + if (null !== $order = OrderQuery::create()->findOneById($orderId)) { + + if ($label = ColissimoLabelQuery::create()->findOneByOrderId($orderId)) { + $fileName = ColissimoLabel::getLabelCN23Path($label->getOrderRef() . 'CN23', 'pdf'); + } else { + /** Compatibility with ColissimoWs < 2.0.0 */ + $label = new LabelController(); + $fileName = $label->createCustomsInvoice($orderId, $order->getRef()); + } + + return Response::create( + file_get_contents($fileName), + 200, + [ + 'Content-Type' => 'application/pdf', + 'Content-disposition' => 'Attachement;filename=' . basename($fileName) + ] + ); + } + + return $this->generateRedirect(URL::getInstance()->absoluteUrl('/admin/module/colissimolabel/labels')); + } + + /** + * Find the order label on the server and return it as a download response + * + * @param Request $request + * @param $number + * @return mixed|BinaryFileResponse + */ + public function getLabelAction(Request $request, $number) + { + if (null !== $response = $this->checkAuth(AdminResources::ORDER, [], AccessManager::UPDATE)) { + return $response; + } + + $label = ColissimoLabelQuery::create()->findOneByTrackingNumber($number); + + /** Compatibility for ColissimoLabel < 1.0.0 */ + if ($label) { + $file = ColissimoLabel::getLabelPath($number, ColissimoLabel::getFileExtension()); + $fileName = $number; + + $orderRef = $label->getOrderRef(); + } + + /** Compatibility for ColissimoWs < 2.0.0 */ + if (ModuleQuery::create()->findOneByCode(ColissimoLabel::AUTHORIZED_MODULES[0])) { + if ($labelWs = ColissimowsLabelQuery::create()->findOneByTrackingNumber($number)) { + $file = ColissimoLabel::getLabelPath($labelWs->getOrderRef(), $labelWs->getLabelType()); + $fileName = $labelWs->getOrderRef(); + } + } + + /** The correct way to find the file for ColissimoLabel >= 1.0.0 */ + if ($orderRef && $orderRef !== '') { + $file = ColissimoLabel::getLabelPath($label->getOrderRef(), ColissimoLabel::getFileExtension()); + $fileName = $label->getOrderRef(); + } + + $response = new BinaryFileResponse($file); + + + if ($request->get('download')) { + $response->setContentDisposition( + ResponseHeaderBag::DISPOSITION_ATTACHMENT, + $fileName . '.' . ColissimoLabel::getFileExtension() + ); + } + + return $response; + } + + /** + * Handles the download of the zip file given as hashed base 64 in the URL + * + * @param $orderId + * + * @return \Symfony\Component\HttpFoundation\Response + * @throws \Propel\Runtime\Exception\PropelException + */ + public function getLabelZip($base64EncodedZipFilename) + { + $zipFilename = base64_decode($base64EncodedZipFilename); + + if (file_exists($zipFilename)) { + return new StreamedResponse( + function () use ($zipFilename) { + readfile($zipFilename); + @unlink($zipFilename); + }, + 200, + [ + 'Content-Type' => 'application/zip', + 'Content-disposition' => 'attachement; filename=colissimo-labels.zip', + 'Content-Length' => filesize($zipFilename) + ] + ); + } + + return new \Symfony\Component\HttpFoundation\Response('File no longer exists'); + } + +} diff --git a/local/modules/ColissimoLabel/Event/ColissimoLabelEvents.php b/local/modules/ColissimoLabel/Event/ColissimoLabelEvents.php new file mode 100644 index 00000000..dac6da5a --- /dev/null +++ b/local/modules/ColissimoLabel/Event/ColissimoLabelEvents.php @@ -0,0 +1,11 @@ +gilles.bourgeat@gmail.com> + */ +class ColissimoLabelEvents +{ + const LABEL_REQUEST = 'ColissimoLabel.labelRequest'; +} diff --git a/local/modules/ColissimoLabel/Event/LabelEvent.php b/local/modules/ColissimoLabel/Event/LabelEvent.php new file mode 100644 index 00000000..8691131f --- /dev/null +++ b/local/modules/ColissimoLabel/Event/LabelEvent.php @@ -0,0 +1,98 @@ +orderId = $orderId; + } + + /** + * @return int + */ + public function getOrderId() + { + return $this->orderId; + } + + /** + * @return ColissimoLabel + */ + public function getColissimoLabel() + { + return $this->colissimoLabel; + } + + /** + * @param ColissimoLabel $colissimoLabel + * @return $this + */ + public function setColissimoLabel($colissimoLabel) + { + $this->colissimoLabel = $colissimoLabel; + return $this; + } + + public function hasLabel() + { + return null !== $this->colissimoWsLabel; + } + + /** + * @return float|null + */ + public function getWeight() + { + return $this->weight; + } + + /** + * @param float|null $weight + * @return $this + */ + public function setWeight($weight) + { + $this->weight = $weight; + return $this; + } + + /** + * @return bool|null + */ + public function getSigned() + { + return $this->signed; + } + + /** + * @param bool|null $signed + * @return $this + */ + public function setSigned($signed) + { + $this->signed = $signed; + return $this; + } +} \ No newline at end of file diff --git a/local/modules/ColissimoLabel/Event/LabelRequestEvent.php b/local/modules/ColissimoLabel/Event/LabelRequestEvent.php new file mode 100644 index 00000000..11a08f98 --- /dev/null +++ b/local/modules/ColissimoLabel/Event/LabelRequestEvent.php @@ -0,0 +1,24 @@ +gilles.bourgeat@gmail.com> + */ +class LabelRequestEvent extends Event +{ + protected $labelRequest; + + public function __construct(LabelRequest $labelRequest) + { + $this->labelRequest = $labelRequest; + } + + public function getLabelRequest() + { + return $this->labelRequest; + } +} diff --git a/local/modules/ColissimoLabel/EventListeners/GenerateLabelListener.php b/local/modules/ColissimoLabel/EventListeners/GenerateLabelListener.php new file mode 100644 index 00000000..80deeceb --- /dev/null +++ b/local/modules/ColissimoLabel/EventListeners/GenerateLabelListener.php @@ -0,0 +1,57 @@ +labelService = $labelService; + } + + /** + * @param GenerateLabelEvent $event + */ + public function generateLabel(GenerateLabelEvent $event) + { + $deliveryModuleCode = $event->getOrder()->getModuleRelatedByDeliveryModuleId()->getCode(); + if ($deliveryModuleCode === "ColissimoHomeDelivery" || $deliveryModuleCode === "ColissimoPickupPoint"|| $deliveryModuleCode === "SoColissimo") { + $data = []; + $orderId = $event->getOrder()->getId(); + $data['new_status'] = ''; + $data['order_id'][$orderId] = $orderId; + $data['weight'][$orderId] = $event->getWeight(); + $data['signed'][$orderId] = $event->isSignedDelivery(); + $event->setResponse($this->labelService->generateLabel($data, true)); + } + } + + public static function getSubscribedEvents() + { + $events = []; + if (class_exists('Picking\Event\GenerateLabelEvent')){ + $events[GenerateLabelEvent::PICKING_GENERATE_LABEL] = ['generateLabel', 65]; + } + return $events; + } +} \ No newline at end of file diff --git a/local/modules/ColissimoLabel/EventListeners/UpdateDeliveryAddressListener.php b/local/modules/ColissimoLabel/EventListeners/UpdateDeliveryAddressListener.php new file mode 100644 index 00000000..7bdd73ef --- /dev/null +++ b/local/modules/ColissimoLabel/EventListeners/UpdateDeliveryAddressListener.php @@ -0,0 +1,274 @@ +dispatcher = $dispatcher; + $this->container = $container; + } + + /** + * @param OrderAddressEvent $event + * @throws \Propel\Runtime\Exception\PropelException + */ + public function updateLabel(OrderAddressEvent $event) + { + $order = $event->getOrder(); + + if ($labels = ColissimoLabelQuery::create()->filterByOrderId($order->getId())->find()) { + foreach ($labels as $label) { + $weight = $label->getWeight(); + $signedDelivery = $label->getSigned(); + $this->deleteLabel($label, $order); + $this->generateLabel($order, $weight, $signedDelivery); + } + } + } + + /** + * @param ColissimoLabel $label + * @param Order $order + * @throws \Propel\Runtime\Exception\PropelException + */ + protected function deleteLabel(ColissimoLabel $label, Order $order) + { + + /** We check if the label is from this module -- Compatibility with ColissimoWs */ + if ($label) { + /** We check if the label is from this version of the module -- Compatibility with ColissimoLabel < 1.0.0 */ + if ('' !== $orderRef = $label->getOrderRef()) { + $this->deleteLabelFile($orderRef); + $label->delete(); + } + } + + /** + * If we're here, it means the label was not from this module or module version, so we get it by other means + * for compatibility reasons. + */ + + /** Trying to get it from ColissimoWs */ + if ($orderId = $order->getId()) { + /** Checking if ColissimoWs is installed */ + if (ModuleQuery::create()->findOneByCode(ColissimoLabelModule::AUTHORIZED_MODULES[0])) { + /** Checking if the label entry exists in the deprecated ColissimoWsLabel table */ + if ($colissimoWslabel = ColissimowsLabelQuery::create()->findOneByOrderId($orderId)) { + $orderRef = $colissimoWslabel->getOrderRef(); + $this->deleteLabelFile($orderRef); + + $colissimoWslabel->delete(); + + } + } + } + } + + protected function deleteLabelFile($fileName) + { + $finder = new Finder(); + $fileSystem = new Filesystem(); + + $finder->files()->name($fileName . '*')->in(ColissimoLabelModule::LABEL_FOLDER); + foreach ($finder as $file) { + $fileSystem->remove(ColissimoLabelModule::LABEL_FOLDER . DS . $file->getFilename()); + } + } + + /** + * @param Order $order + * @param $weight + * @param $signedDelivery + * @throws \Propel\Runtime\Exception\PropelException + */ + protected function generateLabel(Order $order, $weight, $signedDelivery) + { + $APIConfiguration = new LabelRequestAPIConfiguration(); + $APIConfiguration->setContractNumber(ColissimoLabelModule::getConfigValue(ColissimoLabelModule::CONFIG_KEY_CONTRACT_NUMBER)); + $APIConfiguration->setPassword(ColissimoLabelModule::getConfigValue(ColissimoLabelModule::CONFIG_KEY_PASSWORD)); + + /** Check if delivery is a relay point through SoColissimo. Use relay point address if it is */ + if (ColissimoLabelModule::AUTHORIZED_MODULES[1] === $order->getModuleRelatedByDeliveryModuleId()->getCode() && + null !== ($AddressColissimoPickupPoint = OrderAddressSoColissimoPickupPointQuery::create() + ->findOneById($order->getDeliveryOrderAddressId())) && + $AddressColissimoPickupPoint) { + + $colissimoRequest = new LabelRequest( + $order, + $AddressColissimoPickupPoint->getCode() === '0' ? null : $AddressColissimoPickupPoint->getCode(), + $AddressColissimoPickupPoint->getType() + ); + + $colissimoRequest->getLetter()->getService()->setCommercialName( + $colissimoRequest->getLetter()->getSender()->getAddress()->getCompanyName() + ); + } + + + /** Same thing with ColissimoPickupPoint */ + if (ColissimoLabelModule::AUTHORIZED_MODULES[3] === $order->getModuleRelatedByDeliveryModuleId()->getCode() && + null !== ($AddressColissimoPickupPoint = OrderAddressColissimoPickupPointQuery::create() + ->findOneById($order->getDeliveryOrderAddressId())) + && $AddressColissimoPickupPoint) { + + /** If the delivery is through a relay point, we create a new LabelRequest with the relay point and order infos */ + $colissimoRequest = new LabelRequest( + $order, + $AddressColissimoPickupPoint->getCode() === '0' ? null : $AddressColissimoPickupPoint->getCode(), + $AddressColissimoPickupPoint->getType() + ); + + $colissimoRequest->getLetter()->getService()->setCommercialName( + $colissimoRequest->getLetter()->getSender()->getAddress()->getCompanyName() + ); + } + + /** If this is a domicile delivery, we only use the order information to create a Labelrequest, not the relay point */ + if (!isset($colissimoRequest)) { + $colissimoRequest = new LabelRequest($order, null, null, $signedDelivery); + } + + /** We set the weight as the one indicated from the form */ + if (null !== $weight) { + $colissimoRequest->getLetter()->getParcel()->setWeight($weight); + } + + /** We set whether the delivery is a signed one or not thanks to the 'signed' checkbox in the form */ + if (null !== $signedDelivery) { + $colissimoRequest->getLetter()->getParcel()->setSignedDelivery($signedDelivery); + } + + $service = new SOAPService(); + $this->dispatcher->dispatch( + ColissimoLabelEvents::LABEL_REQUEST, + new LabelRequestEvent($colissimoRequest) + ); + + $response = $service->callAPI($APIConfiguration, $colissimoRequest); + + /** Handling what happens if the response from Colissimo is valid */ + if ($response->isValid()) { + $fileSystem = new Filesystem(); + + /** We dump / save the label on the server */ + $fileSystem->dumpFile( + $labelName = ColissimoLabelModule::getLabelPath($order->getRef(), ColissimoLabelModule::getFileExtension()), + $response->getFile() + ); + + $files[] = $labelName; + $hasCustomsFile = 0; + + /** Dump the CN23 customs file if there is one */ + if ($response->hasFileCN23()) { + $fileSystem->dumpFile( + $customsFileName = ColissimoLabelModule::getLabelCN23Path($order->getRef() . 'CN23', 'pdf'), + $response->getFileCN23() + ); + $files[] = $customsFileName; + $hasCustomsFile = 1; + } + + /** Generates and dump the invoice file if it is requested */ + if (ColissimoLabelModule::getConfigValue(ColissimoLabelModule::CONFIG_KEY_GET_INVOICES)) { + $invoiceResponse = $this->generateOrderPdf($order->getId(), ConfigQuery::read('pdf_invoice_file', 'invoice')); + $fileSystem->dumpFile( + $invoiceName = ColissimoLabelModule::getLabelPath($order->getRef() . '-invoice', 'pdf'), + $invoiceResponse->getContent() + ); + $files[] = $invoiceName; + } + + /** + * Checking if an entry with an error already exists in the table for this order label, creates one otherwise + * This allows to modify only entry with errors, while creating new ones if none with error were found + */ + $colissimoLabelModel = ColissimoLabelQuery::create() + ->filterByOrder($order) + ->filterByError(1) + ->findOneOrCreate(); + /** Saving the label info in the table */ + $colissimoLabelModel + ->setOrderId($order->getId()) + ->setOrderRef($order->getRef()) + ->setError(0) + ->setErrorMessage('') + ->setWeight($colissimoRequest->getLetter()->getParcel()->getWeight()) + ->setTrackingNumber($response->getParcelNumber()) + ->setSigned($signedDelivery) + ->setLabelType(ColissimoLabelModule::getFileExtension()) + ->setWithCustomsInvoice($hasCustomsFile); + $colissimoLabelModel->save(); + + $parcelNumbers[] = $response->getParcelNumber(); + + $order->setDeliveryRef($response->getParcelNumber()); + $order->save(); + + } else { + /** Handling errors when the response is invalid */ + + $colissimoLabelError = ColissimoLabelQuery::create() + ->filterByOrder($order) + ->filterByError(1) + ->findOneOrCreate(); + + $colissimoLabelError + ->setError(1) + ->setErrorMessage($response->getError(true)[0]) + ->setSigned($signedDelivery) + ->setWeight($colissimoRequest->getLetter()->getParcel()->getWeight()) + ->save(); + } + } + + public static function getSubscribedEvents() + { + return [ + TheliaEvents::ORDER_UPDATE_ADDRESS => ['updateLabel', 128] + ]; + } +} \ No newline at end of file diff --git a/local/modules/ColissimoLabel/Exception/Exception.php b/local/modules/ColissimoLabel/Exception/Exception.php new file mode 100644 index 00000000..6231390a --- /dev/null +++ b/local/modules/ColissimoLabel/Exception/Exception.php @@ -0,0 +1,9 @@ +gilles.bourgeat@gmail.com> + */ +class Exception extends \Exception +{ +} diff --git a/local/modules/ColissimoLabel/Exception/InvalidArgumentException.php b/local/modules/ColissimoLabel/Exception/InvalidArgumentException.php new file mode 100644 index 00000000..dcb4a81e --- /dev/null +++ b/local/modules/ColissimoLabel/Exception/InvalidArgumentException.php @@ -0,0 +1,9 @@ +gilles.bourgeat@gmail.com> + */ +class InvalidArgumentException extends \InvalidArgumentException +{ +} diff --git a/local/modules/ColissimoLabel/Form/ConfigureColissimoLabel.php b/local/modules/ColissimoLabel/Form/ConfigureColissimoLabel.php new file mode 100644 index 00000000..514804ea --- /dev/null +++ b/local/modules/ColissimoLabel/Form/ConfigureColissimoLabel.php @@ -0,0 +1,217 @@ +formBuilder + ->add( + ColissimoLabel::CONFIG_KEY_CONTRACT_NUMBER, + TextType::class, + [ + 'constraints' => [new NotBlank()], + 'data' => ColissimoLabel::getConfigValue(ColissimoLabel::CONFIG_KEY_CONTRACT_NUMBER), + 'label' => $translator->trans('Account number', [], ColissimoLabel::DOMAIN_NAME), + 'label_attr' => ['for' => ColissimoLabel::CONFIG_KEY_CONTRACT_NUMBER] + ] + ) + ->add( + ColissimoLabel::CONFIG_KEY_PASSWORD, + TextType::class, + [ + 'constraints' => [new NotBlank()], + 'data' => ColissimoLabel::getConfigValue(ColissimoLabel::CONFIG_KEY_PASSWORD), + 'label' => $translator->trans('Password', [], ColissimoLabel::DOMAIN_NAME), + 'label_attr' => ['for' => ColissimoLabel::CONFIG_KEY_PASSWORD] + ] + ) + ->add( + ColissimoLabel::CONFIG_KEY_DEFAULT_SIGNED, + CheckboxType::class, + [ + 'required' => false, + 'data' => (bool)ColissimoLabel::getConfigValue(ColissimoLabel::CONFIG_KEY_DEFAULT_SIGNED), + 'value' => (bool)ColissimoLabel::getConfigValue(ColissimoLabel::CONFIG_KEY_DEFAULT_SIGNED), + 'label' => $translator->trans('Default signed', [], ColissimoLabel::DOMAIN_NAME), + 'label_attr' => ['for' => ColissimoLabel::CONFIG_KEY_DEFAULT_SIGNED] + ] + ) + ->add( + ColissimoLabel::CONFIG_KEY_GENERATE_BORDEREAU, + CheckboxType::class, + [ + 'required' => false, + 'data' => (bool)ColissimoLabel::getConfigValue(ColissimoLabel::CONFIG_KEY_GENERATE_BORDEREAU), + 'value' => (bool)ColissimoLabel::getConfigValue(ColissimoLabel::CONFIG_KEY_GENERATE_BORDEREAU), + 'label' => $translator->trans('Generate bordereau with labels', [], ColissimoLabel::DOMAIN_NAME), + 'label_attr' => ['for' => ColissimoLabel::CONFIG_KEY_GENERATE_BORDEREAU] + ] + ) + ->add( + ColissimoLabel::CONFIG_KEY_DEFAULT_LABEL_FORMAT, + ChoiceType::class, + [ + 'constraints' => [new NotBlank()], + 'data' => ColissimoLabel::getConfigValue(ColissimoLabel::CONFIG_KEY_DEFAULT_LABEL_FORMAT), + 'choices' => OutputFormat::OUTPUT_PRINTING_TYPE, + 'label' => $translator->trans('Label format', [], ColissimoLabel::DOMAIN_NAME), + 'label_attr' => ['for' => ColissimoLabel::CONFIG_KEY_DEFAULT_LABEL_FORMAT] + ] + ) + ->add( + ColissimoLabel::CONFIG_KEY_LAST_BORDEREAU_DATE, + TextType::class, + [ + 'constraints' => [new NotBlank()], + 'data' => ColissimoLabel::getConfigValue(ColissimoLabel::CONFIG_KEY_LAST_BORDEREAU_DATE), + 'label' => $translator->trans('Last bordereau date', [], ColissimoLabel::DOMAIN_NAME), + 'label_attr' => ['for' => ColissimoLabel::CONFIG_KEY_LAST_BORDEREAU_DATE] + ] + ) + ->add( + ColissimoLabel::CONFIG_KEY_GET_INVOICES, + CheckboxType::class, + [ + 'required' => false, + 'data' => (bool)ColissimoLabel::getConfigValue(ColissimoLabel::CONFIG_KEY_GET_INVOICES), + 'value' => (bool)ColissimoLabel::getConfigValue(ColissimoLabel::CONFIG_KEY_GET_INVOICES), + 'label' => $translator->trans('Get the invoices', [], ColissimoLabel::DOMAIN_NAME), + 'label_attr' => ['for' => ColissimoLabel::CONFIG_KEY_GET_INVOICES] + ] + ) + ->add( + ColissimoLabel::CONFIG_KEY_GET_CUSTOMS_INVOICES, + CheckboxType::class, + [ + 'required' => false, + 'data' => (bool)ColissimoLabel::getConfigValue(ColissimoLabel::CONFIG_KEY_GET_CUSTOMS_INVOICES), + 'value' => (bool)ColissimoLabel::getConfigValue(ColissimoLabel::CONFIG_KEY_GET_CUSTOMS_INVOICES), + 'label' => $translator->trans('Get the customs invoices (Need a product HS code to work)', [], ColissimoLabel::DOMAIN_NAME), + 'label_attr' => ['for' => ColissimoLabel::CONFIG_KEY_GET_CUSTOMS_INVOICES] + ] + ) + ->add( + ColissimoLabel::CONFIG_KEY_CUSTOMS_PRODUCT_HSCODE, + TextType::class, + [ + 'required' => false, + 'data' => ColissimoLabel::getConfigValue(ColissimoLabel::CONFIG_KEY_CUSTOMS_PRODUCT_HSCODE), + 'label' => $translator->trans('Product HS Code for Customs invoices', [], ColissimoLabel::DOMAIN_NAME), + 'label_attr' => ['for' => ColissimoLabel::CONFIG_KEY_CUSTOMS_PRODUCT_HSCODE] + ] + ) + ->add( + ColissimoLabel::CONFIG_KEY_ENDPOINT, + TextType::class, + [ + 'required' => true, + 'data' => ColissimoLabel::getConfigValue(ColissimoLabel::CONFIG_KEY_ENDPOINT), + 'label' => $translator->trans('Endpoint', [], ColissimoLabel::DOMAIN_NAME), + 'label_attr' => ['for' => ColissimoLabel::CONFIG_KEY_ENDPOINT] + ] + ) + ->add( + ColissimoLabel::CONFIG_KEY_FROM_NAME, + 'text', + [ + 'constraints' => [ + new NotBlank(), + ], + 'data' => ColissimoLabel::getConfigValue(ColissimoLabel::CONFIG_KEY_FROM_NAME), + 'label' => $this->translator->trans('Nom de société', [], ColissimoLabel::DOMAIN_NAME), + ] + ) + ->add( + ColissimoLabel::CONFIG_KEY_FROM_ADDRESS_1, + 'text', + [ + 'constraints' => [ new NotBlank() ], + 'data' => ColissimoLabel::getConfigValue(ColissimoLabel::CONFIG_KEY_FROM_ADDRESS_1), + 'label' => $this->translator->trans('Adresse', [], ColissimoLabel::DOMAIN_NAME) + ] + ) + ->add( + ColissimoLabel::CONFIG_KEY_FROM_ADDRESS_2, + 'text', + [ + 'constraints' => [ ], + 'required' => false, + 'data' => $this->emptyAddress(ColissimoLabel::getConfigValue(ColissimoLabel::CONFIG_KEY_FROM_ADDRESS_1)), + 'label' => $this->translator->trans('Adresse (suite)', [], ColissimoLabel::DOMAIN_NAME) + ] + ) + ->add( + ColissimoLabel::CONFIG_KEY_FROM_CITY, + 'text', + [ + 'constraints' => [ new NotBlank() ], + 'data' => ColissimoLabel::getConfigValue(ColissimoLabel::CONFIG_KEY_FROM_CITY), + 'label' => $this->translator->trans('Ville', [], ColissimoLabel::DOMAIN_NAME) + ] + ) + ->add( + ColissimoLabel::CONFIG_KEY_FROM_ZIPCODE, + 'text', + [ + 'constraints' => [ new NotBlank() ], + 'data' => ColissimoLabel::getConfigValue(ColissimoLabel::CONFIG_KEY_FROM_ZIPCODE), + 'label' => $this->translator->trans('Code postal', [], ColissimoLabel::DOMAIN_NAME) + ] + ) + ->add( + ColissimoLabel::CONFIG_KEY_FROM_COUNTRY, + 'text', + [ + 'constraints' => [ new NotBlank() ], + 'data' => ColissimoLabel::getConfigValue(ColissimoLabel::CONFIG_KEY_FROM_COUNTRY), + 'label' => $this->translator->trans('Pays', [], ColissimoLabel::DOMAIN_NAME) + ] + )->add( + ColissimoLabel::CONFIG_KEY_FROM_CONTACT_EMAIL, + 'email', + [ + 'constraints' => [ new NotBlank() ], + 'data' => ColissimoLabel::getConfigValue(ColissimoLabel::CONFIG_KEY_FROM_CONTACT_EMAIL), + 'label' => $this->translator->trans('Adresse e-mail de contact pour les expéditions', [], ColissimoLabel::DOMAIN_NAME) + ] + )->add( + ColissimoLabel::CONFIG_KEY_FROM_PHONE, + 'text', + [ + 'constraints' => [ new NotBlank() ], + 'data' => ColissimoLabel::getConfigValue(ColissimoLabel::CONFIG_KEY_FROM_PHONE), + 'label' => $this->translator->trans('Téléphone', [], ColissimoLabel::DOMAIN_NAME) + ] + ) + ; + } + + protected function emptyAddress($value = null) { + if (!$value) { + return ' '; + } + return $value; + } + + /** + * @return string the name of you form. This name must be unique + */ + public function getName() + { + return 'configure_colissimolabel'; + } +} \ No newline at end of file diff --git a/local/modules/ColissimoLabel/Form/LabelGenerationForm.php b/local/modules/ColissimoLabel/Form/LabelGenerationForm.php new file mode 100644 index 00000000..e90c1681 --- /dev/null +++ b/local/modules/ColissimoLabel/Form/LabelGenerationForm.php @@ -0,0 +1,75 @@ +formBuilder + ->add( + 'new_status', + ChoiceType::class, [ + 'label' => Translator::getInstance()->trans('Order status after export'), + 'choices' => [ + 'nochange' => Translator::getInstance()->trans("Do not change", [], ColissimoLabel::DOMAIN_NAME), + 'processing' => Translator::getInstance()->trans("Set orders status as processing", [], ColissimoLabel::DOMAIN_NAME), + 'sent' => Translator::getInstance()->trans("Set orders status as sent", [], ColissimoLabel::DOMAIN_NAME) + ], + 'required' => 'false', + 'expanded' => true, + 'multiple' => false, + 'data' => ColissimoLabel::getConfigValue("new_status", 'nochange') + ] + ) + ->add( + 'order_id', + CollectionType::class, + [ + 'required' => 'false', + 'type' => 'integer', + 'allow_add' => true, + 'allow_delete' => true, + ] + ) + ->add( + 'weight', + CollectionType::class, + [ + 'required' => 'false', + 'type' => 'number', + 'allow_add' => true, + 'allow_delete' => true, + ] + ) + ->add( + 'signed', + CollectionType::class, + [ + 'required' => 'false', + 'type' => 'checkbox', + 'label' => 'Signature', + 'allow_add' => true, + 'allow_delete' => true, + ] + ) + ; + } + + /** + * @return string the name of you form. This name must be unique + */ + public function getName() + { + return "colissimolabel_export_form"; + } + +} \ No newline at end of file diff --git a/local/modules/ColissimoLabel/Hook/Back/MenuHook.php b/local/modules/ColissimoLabel/Hook/Back/MenuHook.php new file mode 100644 index 00000000..d34e7fc4 --- /dev/null +++ b/local/modules/ColissimoLabel/Hook/Back/MenuHook.php @@ -0,0 +1,17 @@ +add( + $this->render('colissimo-label/hook/main.in.top.menu.items.html', []) + ); + } +} diff --git a/local/modules/ColissimoLabel/Hook/Back/OrderEditHook.php b/local/modules/ColissimoLabel/Hook/Back/OrderEditHook.php new file mode 100644 index 00000000..6ac9cfc1 --- /dev/null +++ b/local/modules/ColissimoLabel/Hook/Back/OrderEditHook.php @@ -0,0 +1,18 @@ +gilles.bourgeat@gmail.com> + */ +class OrderEditHook extends BaseHook +{ + public function onOrderEditJs(HookRenderEvent $event) + { + $event->add($this->render('colissimo-label/hook/order-edit-js.html')); + } +} diff --git a/local/modules/ColissimoLabel/I18n/backOffice/default/en_US.php b/local/modules/ColissimoLabel/I18n/backOffice/default/en_US.php new file mode 100644 index 00000000..bf814983 --- /dev/null +++ b/local/modules/ColissimoLabel/I18n/backOffice/default/en_US.php @@ -0,0 +1,59 @@ + '/kg', + 'Action' => 'Action', + 'Advanced configuration' => 'Advanced configuration', + 'Bordereau' => 'Bordereau', + 'Bordereaux' => 'Bordereaux', + 'Cancel' => 'Cancel', + 'Change to "Processing"' => 'Change to "Processing"', + 'Change to "Sent". If you choose this option, the delivery notification email is sent to the customer, and the processed order are removed from this page.' => 'Change to "Sent". If you choose this option, the delivery notification email is sent to the customer, and the processed order are removed from this page.', + 'Clear label' => 'Clear label', + 'Colissimo Labels' => 'Colissimo Labels', + 'ColissimoLabel' => 'Colissimo Labels', + 'Configuration' => 'Configuration', + 'Customs invoice' => 'Customs invoice', + 'Date' => 'Date', + 'Delete' => 'Delete', + 'Delete bordereau' => 'Delete bordereau', + 'Destination' => 'Destination', + 'Do not change' => 'Do not change', + 'Do you want to clear label and tracking number for this order ?' => 'Do you want to clear label and tracking number for this order ?', + 'Do you want to clear this label and tracking number ?' => 'Do you want to clear this label and tracking number ?', + 'Download' => 'Download', + 'Download and print Colissimo labels for orders not yet sent' => 'Download and print Colissimo labels for orders not yet sent', + 'Download bordereau' => 'Download bordereau', + 'Download customs invoice (PDF)' => 'Download customs invoice (PDF)', + 'Download label (%fmt)' => 'Download label (%fmt)', + 'General informations' => 'General informations', + 'Generate bordereau for label since : %date' => 'Generate bordereau for label since : %date', + 'Generate new label' => 'Generate new label', + 'Label' => 'Label', + 'Label cannot be created. Error is: ' => 'Label cannot be created. Error is: ', + 'Labels' => 'Labels', + 'Labels Colissimo' => 'Labels Colissimo', + 'Livraison avec signature :' => 'Delivery w/ signature', + 'Module' => 'Module', + 'No existing label for this order' => 'No existing label for this order', + 'Non disponible' => 'Non disponible', + 'Number' => 'Tracking Number', + 'Order date' => 'Order date', + 'Order status change after processing' => 'Order status change after processing', + 'Please wait ...' => 'Please wait ...', + 'Price (with taxes)' => 'Price (with taxes)', + 'Print' => 'Print', + 'Process selected orders' => 'Process selected orders', + 'REF' => 'REF', + 'Save changes' => 'Save changes', + 'Sel.' => 'Sel.', + 'Sender\'s address' => 'Sender\'s address', + 'Shipping weight :' => 'Shipping weight :', + 'Signature' => 'Signature', + 'There are currently no orders to ship with Colissimo' => 'There are currently no orders to ship with Colissimo', + 'Tracking' => 'Tracking', + 'Tracking URL' => 'Tracking URL', + 'View' => 'View', + 'Weight' => 'Weight', + 'kg' => 'kg', +); diff --git a/local/modules/ColissimoLabel/I18n/backOffice/default/fr_FR.php b/local/modules/ColissimoLabel/I18n/backOffice/default/fr_FR.php new file mode 100644 index 00000000..65cfc026 --- /dev/null +++ b/local/modules/ColissimoLabel/I18n/backOffice/default/fr_FR.php @@ -0,0 +1,59 @@ + '/kg', + 'Action' => 'Action', + 'Advanced configuration' => 'Configuration avancée', + 'Bordereau' => 'Bordereau', + 'Bordereaux' => 'Bordereaux', + 'Cancel' => 'Annuler', + 'Change to "Processing"' => 'Changer en "Traitement"', + 'Change to "Sent". If you choose this option, the delivery notification email is sent to the customer, and the processed order are removed from this page.' => 'Changer en "Envoyé". Choisir cette option retirera la commande de cette liste, et enverra un mail de notification au client.', + 'Clear label' => 'Supprimer l\'étiquette', + 'Colissimo Labels' => 'Etiquettes Colissimo', + 'ColissimoLabel' => 'Etiquettes Colissimo', + 'Configuration' => 'Configuration', + 'Customs invoice' => 'Facture douane', + 'Date' => 'Date', + 'Delete' => 'Supprimer', + 'Delete bordereau' => 'Supprimer le bordereau', + 'Destination' => 'Destination', + 'Do not change' => 'Ne pas modifier', + 'Do you want to clear label and tracking number for this order ?' => 'Voulez-vous supprimer cette étiquette et le n° de suivi ?', + 'Do you want to clear this label and tracking number ?' => 'Voulez-vous supprimer cette étiquette ainsi que son numéro de suivi ?', + 'Download' => 'Télécharger', + 'Download and print Colissimo labels for orders not yet sent' => 'Télécharger et imprimer les étiquettes Colissimo pour les commandes non envoyées', + 'Download bordereau' => 'Télécharger le bordereau', + 'Download customs invoice (PDF)' => 'Télécharger la facture de douanes', + 'Download label (%fmt)' => 'Télécharger l\'étiquette (%fmt)', + 'General informations' => 'Informations générales', + 'Generate bordereau for label since : %date' => 'Générer un bordereau pour les étiquettes créée depuis : %date', + 'Generate new label' => 'Générer une étiquette', + 'Label' => 'Etiquette', + 'Label cannot be created. Error is: ' => 'L\'étiquette n\'a pas pu être créée. Erreur: ', + 'Labels' => 'Etiquettes', + 'Labels Colissimo' => 'Étiquette Colissimo', + 'Livraison avec signature :' => 'Livraison avec signature :', + 'Module' => 'Module', + 'No existing label for this order' => 'Aucune étiquette pour cette commande', + 'Non disponible' => 'Non disponible', + 'Number' => 'Numéro', + 'Order date' => 'Date de commande', + 'Order status change after processing' => 'Status de commande après l\'export', + 'Please wait ...' => 'Veuillez patienter ...', + 'Price (with taxes)' => 'Prix (TTC)', + 'Print' => 'Imprimer', + 'Process selected orders' => 'Traiter les commandes sélectionnées', + 'REF' => 'REF', + 'Save changes' => 'Enregistrer les modifications', + 'Sel.' => 'Sel.', + 'Sender\'s address' => 'Adresse de l\'envoyeur', + 'Shipping weight :' => 'Poids d\'expédition :', + 'Signature' => 'Signature', + 'There are currently no orders to ship with Colissimo' => 'Il n\'y a aucune commande à envoyer avec Colissimo pour le moment', + 'Tracking' => 'N° de suivi', + 'Tracking URL' => 'URL de tracking', + 'View' => 'Voir', + 'Weight' => 'Poids', + 'kg' => 'kg', +); diff --git a/local/modules/ColissimoLabel/I18n/en_US.php b/local/modules/ColissimoLabel/I18n/en_US.php new file mode 100644 index 00000000..1615be9d --- /dev/null +++ b/local/modules/ColissimoLabel/I18n/en_US.php @@ -0,0 +1,29 @@ + 'Account number', + 'Adresse' => 'Address', + 'Adresse (suite)' => 'Address (continued)', + 'Adresse e-mail de contact pour les expéditions' => 'Contact email for expeditions', + 'Code postal' => 'Postal code', + 'ColissimoLabel update config' => 'ColissimoLabel update config', + 'Default signed' => 'Default signed', + 'Do not change' => 'Do not change', + 'Endpoint' => 'Endpoint', + 'Generate bordereau with labels' => 'Generate bordereau with labels', + 'Get the customs invoices (Need a product HS code to work)' => 'Get the customs invoices (Need a product HS code to work)', + 'Get the invoices' => 'Get the invoices', + 'Label format' => 'Label format', + 'Last bordereau date' => 'Last bordereau date', + 'Nom de société' => 'Company\'s name', + 'Order status after export' => 'Order status after export', + 'Password' => 'Password', + 'Pays' => 'Country', + 'Please enter a weight for every selected order' => 'Please enter a weight for every selected order', + 'Product HS Code for Customs invoices' => 'Product HS Code for Customs invoices', + 'Set orders status as processing' => 'Set orders status as processing', + 'Set orders status as sent' => 'Set orders status as sent', + 'Sorry, you\'re not allowed to perform this action' => 'Sorry, you\'re not allowed to perform this action', + 'Téléphone' => 'Phone', + 'Ville' => 'City', +); diff --git a/local/modules/ColissimoLabel/I18n/fr_FR.php b/local/modules/ColissimoLabel/I18n/fr_FR.php new file mode 100644 index 00000000..136da49f --- /dev/null +++ b/local/modules/ColissimoLabel/I18n/fr_FR.php @@ -0,0 +1,29 @@ + 'N° de compte', + 'Adresse' => 'Adresse', + 'Adresse (suite)' => 'Adresse (suite)', + 'Adresse e-mail de contact pour les expéditions' => 'Adresse e-mail de contact pour les expéditions', + 'Code postal' => 'Code postal', + 'ColissimoLabel update config' => 'Mise à jour de la configuration de ColissimoLabel', + 'Default signed' => 'Signé par défaut', + 'Do not change' => 'Ne pas changer', + 'Endpoint' => 'Endpoint', + 'Generate bordereau with labels' => 'Générer un bordereau avec les étiquettes', + 'Get the customs invoices (Need a product HS code to work)' => 'Générer les factures de douane (Nécessite d\'indiquer un code HS pour fonctionner)', + 'Get the invoices' => 'Générer les factures avec les étiquettes', + 'Label format' => 'Format d\'étiquette', + 'Last bordereau date' => 'Date du dernier bordereau', + 'Nom de société' => 'Nom de société', + 'Order status after export' => 'Status de commande après l\'export', + 'Password' => 'Mot de passe', + 'Pays' => 'Pays', + 'Please enter a weight for every selected order' => 'Veuillez entrer un poids pour toutes les commandes sélectionnées', + 'Product HS Code for Customs invoices' => 'Code HS pour les factures de douane', + 'Set orders status as processing' => 'Changer le status à "Traitement"', + 'Set orders status as sent' => 'Changer le status à "Envoyé" (retirera les commandes de la liste)', + 'Sorry, you\'re not allowed to perform this action' => 'Désolé, vous n\'êtes pas autorisé à performer cette action', + 'Téléphone' => 'Téléphone', + 'Ville' => 'Ville', +); diff --git a/local/modules/ColissimoLabel/LICENSE b/local/modules/ColissimoLabel/LICENSE new file mode 100644 index 00000000..8b23445f --- /dev/null +++ b/local/modules/ColissimoLabel/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2019 + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/local/modules/ColissimoLabel/Loop/ColissimoLabelInfo.php b/local/modules/ColissimoLabel/Loop/ColissimoLabelInfo.php new file mode 100644 index 00000000..4f570cbd --- /dev/null +++ b/local/modules/ColissimoLabel/Loop/ColissimoLabelInfo.php @@ -0,0 +1,129 @@ +filterByOrderId($this->getOrderId()); + + /** Compatibility for old versions of ColissimoWS where the label info was on a ColissimoWs table */ + if (null === $search->findOne()) { + /** We check that ColissimoWS is installed */ + if (ModuleQuery::create()->findOneByCode(ColissimoLabel::AUTHORIZED_MODULES[0])) { + /** Security check to make sure the ColissimoWSLabel table exists */ + try { + $searchColissimoWS = ColissimowsLabelQuery::create()->filterByOrderId($this->getOrderId()); + /** If there is an old entry for a label in the ColissimoWSLabel table, we return that instead of the ColissimoLabel one */ + if (null !== $searchColissimoWS->findOne()) { + return $searchColissimoWS; + } + } catch (\Exception $ex) { + /** If the table doesn't exist, we just return the original search */ + return $search; + } + } + } + + return $search; + } + + /** + * @param LoopResult $loopResult + * @return LoopResult + * @throws \Propel\Runtime\Exception\PropelException + */ + public function parseResults(LoopResult $loopResult) + { + if ($loopResult->getResultDataCollectionCount() === 0) { + if (null !== $order = OrderQuery::create()->findPk($this->getOrderId())) { + $loopResultRow = new LoopResultRow(); + + $defaultSigned = ColissimoLabel::getConfigValue(ColissimoLabel::CONFIG_KEY_DEFAULT_SIGNED); + + $loopResultRow + ->set('ORDER_ID', $this->getOrderId()) + ->set('HAS_ERROR', false) + ->set('ERROR_MESSAGE', null) + ->set('WEIGHT', $order->getWeight()) + ->set('SIGNED', $defaultSigned) + ->set('TRACKING_NUMBER', null) + ->set('HAS_LABEL', false) + ->set('LABEL_URL', null) + ->set('CLEAR_LABEL_URL', null) + ->set('CAN_BE_NOT_SIGNED', ColissimoLabel::canOrderBeNotSigned($order)); + + $loopResult->addRow($loopResultRow); + } + } else { + /** @var ColissimowsLabel|ColissimoLabelModel $result */ + foreach ($loopResult->getResultDataCollection() as $result) { + + /** Compatibility for ColissimoLabel < 1.0.0 */ + if ('' === $result->getOrderRef()) { + $finder = new Finder(); + $finder->files()->name($result->getTrackingNumber() . '.*')->in(ColissimoLabel::LABEL_FOLDER); + foreach ($finder as $file) { + $result->setLabelType($file->getExtension()); + } + } + + $loopResultRow = new LoopResultRow(); + $loopResultRow + ->set('ORDER_ID', $result->getOrderId()) + ->set('HAS_ERROR', $result->getError()) + ->set('ERROR_MESSAGE', $result->getErrorMessage()) + ->set('WEIGHT', empty($result->getWeight()) ? $result->getOrder()->getWeight() : $result->getWeight()) + ->set('SIGNED', $result->getSigned()) + ->set('TRACKING_NUMBER', $result->getTrackingNumber()) + ->set('HAS_LABEL', !empty($result->getLabelType())) + ->set('LABEL_TYPE', $result->getLabelType()) + ->set('HAS_CUSTOMS_INVOICE', $result->getWithCustomsInvoice()) + ->set('LABEL_URL', URL::getInstance()->absoluteUrl('/admin/module/colissimolabel/label/' . $result->getTrackingNumber() . '?download=1')) + ->set('CUSTOMS_INVOICE_URL', URL::getInstance()->absoluteUrl('/admin/module/colissimolabel/customs-invoice/' . $result->getOrderId())) + ->set('CLEAR_LABEL_URL', URL::getInstance()->absoluteUrl('/admin/module/colissimolabel/label/delete/' . $result->getTrackingNumber() . '?order=' . $result->getOrderId())) + ->set('CAN_BE_NOT_SIGNED', ColissimoLabel::canOrderBeNotSigned($result->getOrder())) + ->set('ORDER_DATE', $result->getOrder()->getCreatedAt()) + ; + + $loopResult->addRow($loopResultRow); + } + } + + return $loopResult; + } +} \ No newline at end of file diff --git a/local/modules/ColissimoLabel/Loop/OrdersNotSentLoop.php b/local/modules/ColissimoLabel/Loop/OrdersNotSentLoop.php new file mode 100644 index 00000000..347c1b9b --- /dev/null +++ b/local/modules/ColissimoLabel/Loop/OrdersNotSentLoop.php @@ -0,0 +1,73 @@ +filterByCode( + array( + OrderStatus::CODE_PAID, + OrderStatus::CODE_PROCESSING, + ), + Criteria::IN + ) + ->find() + ->toArray("code"); + + /** Verify what modules are installed */ + $moduleIds = []; + if ($colissimoWS = ModuleQuery::create()->findOneByCode(ColissimoLabel::AUTHORIZED_MODULES[0])) { + $moduleIds[] = $colissimoWS->getId(); + } + if ($soColissimo = ModuleQuery::create()->findOneByCode(ColissimoLabel::AUTHORIZED_MODULES[1])) { + $moduleIds[] = $soColissimo->getId(); + } + if ($colissimoHomeDelivery = ModuleQuery::create()->findOneByCode(ColissimoLabel::AUTHORIZED_MODULES[2])) { + $moduleIds[] = $colissimoHomeDelivery->getId(); + } + if ($colissimoPickupPoint = ModuleQuery::create()->findOneByCode(ColissimoLabel::AUTHORIZED_MODULES[3])) { + $moduleIds[] = $colissimoPickupPoint->getId(); + } + + $query = OrderQuery::create() + ->filterByDeliveryModuleId( + $moduleIds, + Criteria::IN + ) + ->filterByStatusId( + array( + $status[OrderStatus::CODE_PAID]['Id'], + $status[OrderStatus::CODE_PROCESSING]['Id'] + ), + Criteria::IN + ); + + return $query; + } +} \ No newline at end of file diff --git a/local/modules/ColissimoLabel/Model/Base/ColissimoLabel.php b/local/modules/ColissimoLabel/Model/Base/ColissimoLabel.php new file mode 100644 index 00000000..ecc969fc --- /dev/null +++ b/local/modules/ColissimoLabel/Model/Base/ColissimoLabel.php @@ -0,0 +1,1894 @@ +error = false; + $this->error_message = ''; + $this->weight = '0.00'; + $this->signed = false; + $this->with_customs_invoice = false; + } + + /** + * Initializes internal state of ColissimoLabel\Model\Base\ColissimoLabel object. + * @see applyDefaults() + */ + public function __construct() + { + $this->applyDefaultValues(); + } + + /** + * Returns whether the object has been modified. + * + * @return boolean True if the object has been modified. + */ + public function isModified() + { + return !!$this->modifiedColumns; + } + + /** + * Has specified column been modified? + * + * @param string $col column fully qualified name (TableMap::TYPE_COLNAME), e.g. Book::AUTHOR_ID + * @return boolean True if $col has been modified. + */ + public function isColumnModified($col) + { + return $this->modifiedColumns && isset($this->modifiedColumns[$col]); + } + + /** + * Get the columns that have been modified in this object. + * @return array A unique list of the modified column names for this object. + */ + public function getModifiedColumns() + { + return $this->modifiedColumns ? array_keys($this->modifiedColumns) : []; + } + + /** + * Returns whether the object has ever been saved. This will + * be false, if the object was retrieved from storage or was created + * and then saved. + * + * @return boolean true, if the object has never been persisted. + */ + public function isNew() + { + return $this->new; + } + + /** + * Setter for the isNew attribute. This method will be called + * by Propel-generated children and objects. + * + * @param boolean $b the state of the object. + */ + public function setNew($b) + { + $this->new = (Boolean) $b; + } + + /** + * Whether this object has been deleted. + * @return boolean The deleted state of this object. + */ + public function isDeleted() + { + return $this->deleted; + } + + /** + * Specify whether this object has been deleted. + * @param boolean $b The deleted state of this object. + * @return void + */ + public function setDeleted($b) + { + $this->deleted = (Boolean) $b; + } + + /** + * Sets the modified state for the object to be false. + * @param string $col If supplied, only the specified column is reset. + * @return void + */ + public function resetModified($col = null) + { + if (null !== $col) { + if (isset($this->modifiedColumns[$col])) { + unset($this->modifiedColumns[$col]); + } + } else { + $this->modifiedColumns = array(); + } + } + + /** + * Compares this with another ColissimoLabel instance. If + * obj is an instance of ColissimoLabel, delegates to + * equals(ColissimoLabel). Otherwise, returns false. + * + * @param mixed $obj The object to compare to. + * @return boolean Whether equal to the object specified. + */ + public function equals($obj) + { + $thisclazz = get_class($this); + if (!is_object($obj) || !($obj instanceof $thisclazz)) { + return false; + } + + if ($this === $obj) { + return true; + } + + if (null === $this->getPrimaryKey() + || null === $obj->getPrimaryKey()) { + return false; + } + + return $this->getPrimaryKey() === $obj->getPrimaryKey(); + } + + /** + * If the primary key is not null, return the hashcode of the + * primary key. Otherwise, return the hash code of the object. + * + * @return int Hashcode + */ + public function hashCode() + { + if (null !== $this->getPrimaryKey()) { + return crc32(serialize($this->getPrimaryKey())); + } + + return crc32(serialize(clone $this)); + } + + /** + * Get the associative array of the virtual columns in this object + * + * @return array + */ + public function getVirtualColumns() + { + return $this->virtualColumns; + } + + /** + * Checks the existence of a virtual column in this object + * + * @param string $name The virtual column name + * @return boolean + */ + public function hasVirtualColumn($name) + { + return array_key_exists($name, $this->virtualColumns); + } + + /** + * Get the value of a virtual column in this object + * + * @param string $name The virtual column name + * @return mixed + * + * @throws PropelException + */ + public function getVirtualColumn($name) + { + if (!$this->hasVirtualColumn($name)) { + throw new PropelException(sprintf('Cannot get value of inexistent virtual column %s.', $name)); + } + + return $this->virtualColumns[$name]; + } + + /** + * Set the value of a virtual column in this object + * + * @param string $name The virtual column name + * @param mixed $value The value to give to the virtual column + * + * @return ColissimoLabel The current object, for fluid interface + */ + public function setVirtualColumn($name, $value) + { + $this->virtualColumns[$name] = $value; + + return $this; + } + + /** + * Logs a message using Propel::log(). + * + * @param string $msg + * @param int $priority One of the Propel::LOG_* logging levels + * @return boolean + */ + protected function log($msg, $priority = Propel::LOG_INFO) + { + return Propel::log(get_class($this) . ': ' . $msg, $priority); + } + + /** + * Populate the current object from a string, using a given parser format + * + * $book = new Book(); + * $book->importFrom('JSON', '{"Id":9012,"Title":"Don Juan","ISBN":"0140422161","Price":12.99,"PublisherId":1234,"AuthorId":5678}'); + * + * + * @param mixed $parser A AbstractParser instance, + * or a format name ('XML', 'YAML', 'JSON', 'CSV') + * @param string $data The source data to import from + * + * @return ColissimoLabel The current object, for fluid interface + */ + public function importFrom($parser, $data) + { + if (!$parser instanceof AbstractParser) { + $parser = AbstractParser::getParser($parser); + } + + $this->fromArray($parser->toArray($data), TableMap::TYPE_PHPNAME); + + return $this; + } + + /** + * Export the current object properties to a string, using a given parser format + * + * $book = BookQuery::create()->findPk(9012); + * echo $book->exportTo('JSON'); + * => {"Id":9012,"Title":"Don Juan","ISBN":"0140422161","Price":12.99,"PublisherId":1234,"AuthorId":5678}'); + * + * + * @param mixed $parser A AbstractParser instance, or a format name ('XML', 'YAML', 'JSON', 'CSV') + * @param boolean $includeLazyLoadColumns (optional) Whether to include lazy load(ed) columns. Defaults to TRUE. + * @return string The exported data + */ + public function exportTo($parser, $includeLazyLoadColumns = true) + { + if (!$parser instanceof AbstractParser) { + $parser = AbstractParser::getParser($parser); + } + + return $parser->fromArray($this->toArray(TableMap::TYPE_PHPNAME, $includeLazyLoadColumns, array(), true)); + } + + /** + * Clean up internal collections prior to serializing + * Avoids recursive loops that turn into segmentation faults when serializing + */ + public function __sleep() + { + $this->clearAllReferences(); + + return array_keys(get_object_vars($this)); + } + + /** + * Get the [id] column value. + * + * @return int + */ + public function getId() + { + + return $this->id; + } + + /** + * Get the [order_id] column value. + * + * @return int + */ + public function getOrderId() + { + + return $this->order_id; + } + + /** + * Get the [order_ref] column value. + * + * @return string + */ + public function getOrderRef() + { + + return $this->order_ref; + } + + /** + * Get the [error] column value. + * + * @return boolean + */ + public function getError() + { + + return $this->error; + } + + /** + * Get the [error_message] column value. + * + * @return string + */ + public function getErrorMessage() + { + + return $this->error_message; + } + + /** + * Get the [tracking_number] column value. + * + * @return string + */ + public function getTrackingNumber() + { + + return $this->tracking_number; + } + + /** + * Get the [label_type] column value. + * + * @return string + */ + public function getLabelType() + { + + return $this->label_type; + } + + /** + * Get the [weight] column value. + * + * @return string + */ + public function getWeight() + { + + return $this->weight; + } + + /** + * Get the [signed] column value. + * + * @return boolean + */ + public function getSigned() + { + + return $this->signed; + } + + /** + * Get the [with_customs_invoice] column value. + * + * @return boolean + */ + public function getWithCustomsInvoice() + { + + return $this->with_customs_invoice; + } + + /** + * Get the [optionally formatted] temporal [created_at] column value. + * + * + * @param string $format The date/time format string (either date()-style or strftime()-style). + * If format is NULL, then the raw \DateTime object will be returned. + * + * @return mixed Formatted date/time value as string or \DateTime object (if format is NULL), NULL if column is NULL, and 0 if column value is 0000-00-00 00:00:00 + * + * @throws PropelException - if unable to parse/validate the date/time value. + */ + public function getCreatedAt($format = NULL) + { + if ($format === null) { + return $this->created_at; + } else { + return $this->created_at instanceof \DateTime ? $this->created_at->format($format) : null; + } + } + + /** + * Get the [optionally formatted] temporal [updated_at] column value. + * + * + * @param string $format The date/time format string (either date()-style or strftime()-style). + * If format is NULL, then the raw \DateTime object will be returned. + * + * @return mixed Formatted date/time value as string or \DateTime object (if format is NULL), NULL if column is NULL, and 0 if column value is 0000-00-00 00:00:00 + * + * @throws PropelException - if unable to parse/validate the date/time value. + */ + public function getUpdatedAt($format = NULL) + { + if ($format === null) { + return $this->updated_at; + } else { + return $this->updated_at instanceof \DateTime ? $this->updated_at->format($format) : null; + } + } + + /** + * Set the value of [id] column. + * + * @param int $v new value + * @return \ColissimoLabel\Model\ColissimoLabel The current object (for fluent API support) + */ + public function setId($v) + { + if ($v !== null) { + $v = (int) $v; + } + + if ($this->id !== $v) { + $this->id = $v; + $this->modifiedColumns[ColissimoLabelTableMap::ID] = true; + } + + + return $this; + } // setId() + + /** + * Set the value of [order_id] column. + * + * @param int $v new value + * @return \ColissimoLabel\Model\ColissimoLabel The current object (for fluent API support) + */ + public function setOrderId($v) + { + if ($v !== null) { + $v = (int) $v; + } + + if ($this->order_id !== $v) { + $this->order_id = $v; + $this->modifiedColumns[ColissimoLabelTableMap::ORDER_ID] = true; + } + + if ($this->aOrder !== null && $this->aOrder->getId() !== $v) { + $this->aOrder = null; + } + + + return $this; + } // setOrderId() + + /** + * Set the value of [order_ref] column. + * + * @param string $v new value + * @return \ColissimoLabel\Model\ColissimoLabel The current object (for fluent API support) + */ + public function setOrderRef($v) + { + if ($v !== null) { + $v = (string) $v; + } + + if ($this->order_ref !== $v) { + $this->order_ref = $v; + $this->modifiedColumns[ColissimoLabelTableMap::ORDER_REF] = true; + } + + + return $this; + } // setOrderRef() + + /** + * Sets the value of the [error] column. + * Non-boolean arguments are converted using the following rules: + * * 1, '1', 'true', 'on', and 'yes' are converted to boolean true + * * 0, '0', 'false', 'off', and 'no' are converted to boolean false + * Check on string values is case insensitive (so 'FaLsE' is seen as 'false'). + * + * @param boolean|integer|string $v The new value + * @return \ColissimoLabel\Model\ColissimoLabel The current object (for fluent API support) + */ + public function setError($v) + { + if ($v !== null) { + if (is_string($v)) { + $v = in_array(strtolower($v), array('false', 'off', '-', 'no', 'n', '0', '')) ? false : true; + } else { + $v = (boolean) $v; + } + } + + if ($this->error !== $v) { + $this->error = $v; + $this->modifiedColumns[ColissimoLabelTableMap::ERROR] = true; + } + + + return $this; + } // setError() + + /** + * Set the value of [error_message] column. + * + * @param string $v new value + * @return \ColissimoLabel\Model\ColissimoLabel The current object (for fluent API support) + */ + public function setErrorMessage($v) + { + if ($v !== null) { + $v = (string) $v; + } + + if ($this->error_message !== $v) { + $this->error_message = $v; + $this->modifiedColumns[ColissimoLabelTableMap::ERROR_MESSAGE] = true; + } + + + return $this; + } // setErrorMessage() + + /** + * Set the value of [tracking_number] column. + * + * @param string $v new value + * @return \ColissimoLabel\Model\ColissimoLabel The current object (for fluent API support) + */ + public function setTrackingNumber($v) + { + if ($v !== null) { + $v = (string) $v; + } + + if ($this->tracking_number !== $v) { + $this->tracking_number = $v; + $this->modifiedColumns[ColissimoLabelTableMap::TRACKING_NUMBER] = true; + } + + + return $this; + } // setTrackingNumber() + + /** + * Set the value of [label_type] column. + * + * @param string $v new value + * @return \ColissimoLabel\Model\ColissimoLabel The current object (for fluent API support) + */ + public function setLabelType($v) + { + if ($v !== null) { + $v = (string) $v; + } + + if ($this->label_type !== $v) { + $this->label_type = $v; + $this->modifiedColumns[ColissimoLabelTableMap::LABEL_TYPE] = true; + } + + + return $this; + } // setLabelType() + + /** + * Set the value of [weight] column. + * + * @param string $v new value + * @return \ColissimoLabel\Model\ColissimoLabel The current object (for fluent API support) + */ + public function setWeight($v) + { + if ($v !== null) { + $v = (string) $v; + } + + if ($this->weight !== $v) { + $this->weight = $v; + $this->modifiedColumns[ColissimoLabelTableMap::WEIGHT] = true; + } + + + return $this; + } // setWeight() + + /** + * Sets the value of the [signed] column. + * Non-boolean arguments are converted using the following rules: + * * 1, '1', 'true', 'on', and 'yes' are converted to boolean true + * * 0, '0', 'false', 'off', and 'no' are converted to boolean false + * Check on string values is case insensitive (so 'FaLsE' is seen as 'false'). + * + * @param boolean|integer|string $v The new value + * @return \ColissimoLabel\Model\ColissimoLabel The current object (for fluent API support) + */ + public function setSigned($v) + { + if ($v !== null) { + if (is_string($v)) { + $v = in_array(strtolower($v), array('false', 'off', '-', 'no', 'n', '0', '')) ? false : true; + } else { + $v = (boolean) $v; + } + } + + if ($this->signed !== $v) { + $this->signed = $v; + $this->modifiedColumns[ColissimoLabelTableMap::SIGNED] = true; + } + + + return $this; + } // setSigned() + + /** + * Sets the value of the [with_customs_invoice] column. + * Non-boolean arguments are converted using the following rules: + * * 1, '1', 'true', 'on', and 'yes' are converted to boolean true + * * 0, '0', 'false', 'off', and 'no' are converted to boolean false + * Check on string values is case insensitive (so 'FaLsE' is seen as 'false'). + * + * @param boolean|integer|string $v The new value + * @return \ColissimoLabel\Model\ColissimoLabel The current object (for fluent API support) + */ + public function setWithCustomsInvoice($v) + { + if ($v !== null) { + if (is_string($v)) { + $v = in_array(strtolower($v), array('false', 'off', '-', 'no', 'n', '0', '')) ? false : true; + } else { + $v = (boolean) $v; + } + } + + if ($this->with_customs_invoice !== $v) { + $this->with_customs_invoice = $v; + $this->modifiedColumns[ColissimoLabelTableMap::WITH_CUSTOMS_INVOICE] = true; + } + + + return $this; + } // setWithCustomsInvoice() + + /** + * Sets the value of [created_at] column to a normalized version of the date/time value specified. + * + * @param mixed $v string, integer (timestamp), or \DateTime value. + * Empty strings are treated as NULL. + * @return \ColissimoLabel\Model\ColissimoLabel The current object (for fluent API support) + */ + public function setCreatedAt($v) + { + $dt = PropelDateTime::newInstance($v, null, '\DateTime'); + if ($this->created_at !== null || $dt !== null) { + if ($dt !== $this->created_at) { + $this->created_at = $dt; + $this->modifiedColumns[ColissimoLabelTableMap::CREATED_AT] = true; + } + } // if either are not null + + + return $this; + } // setCreatedAt() + + /** + * Sets the value of [updated_at] column to a normalized version of the date/time value specified. + * + * @param mixed $v string, integer (timestamp), or \DateTime value. + * Empty strings are treated as NULL. + * @return \ColissimoLabel\Model\ColissimoLabel The current object (for fluent API support) + */ + public function setUpdatedAt($v) + { + $dt = PropelDateTime::newInstance($v, null, '\DateTime'); + if ($this->updated_at !== null || $dt !== null) { + if ($dt !== $this->updated_at) { + $this->updated_at = $dt; + $this->modifiedColumns[ColissimoLabelTableMap::UPDATED_AT] = true; + } + } // if either are not null + + + return $this; + } // setUpdatedAt() + + /** + * Indicates whether the columns in this object are only set to default values. + * + * This method can be used in conjunction with isModified() to indicate whether an object is both + * modified _and_ has some values set which are non-default. + * + * @return boolean Whether the columns in this object are only been set with default values. + */ + public function hasOnlyDefaultValues() + { + if ($this->error !== false) { + return false; + } + + if ($this->error_message !== '') { + return false; + } + + if ($this->weight !== '0.00') { + return false; + } + + if ($this->signed !== false) { + return false; + } + + if ($this->with_customs_invoice !== false) { + return false; + } + + // otherwise, everything was equal, so return TRUE + return true; + } // hasOnlyDefaultValues() + + /** + * Hydrates (populates) the object variables with values from the database resultset. + * + * An offset (0-based "start column") is specified so that objects can be hydrated + * with a subset of the columns in the resultset rows. This is needed, for example, + * for results of JOIN queries where the resultset row includes columns from two or + * more tables. + * + * @param array $row The row returned by DataFetcher->fetch(). + * @param int $startcol 0-based offset column which indicates which restultset column to start with. + * @param boolean $rehydrate Whether this object is being re-hydrated from the database. + * @param string $indexType The index type of $row. Mostly DataFetcher->getIndexType(). + One of the class type constants TableMap::TYPE_PHPNAME, TableMap::TYPE_STUDLYPHPNAME + * TableMap::TYPE_COLNAME, TableMap::TYPE_FIELDNAME, TableMap::TYPE_NUM. + * + * @return int next starting column + * @throws PropelException - Any caught Exception will be rewrapped as a PropelException. + */ + public function hydrate($row, $startcol = 0, $rehydrate = false, $indexType = TableMap::TYPE_NUM) + { + try { + + + $col = $row[TableMap::TYPE_NUM == $indexType ? 0 + $startcol : ColissimoLabelTableMap::translateFieldName('Id', TableMap::TYPE_PHPNAME, $indexType)]; + $this->id = (null !== $col) ? (int) $col : null; + + $col = $row[TableMap::TYPE_NUM == $indexType ? 1 + $startcol : ColissimoLabelTableMap::translateFieldName('OrderId', TableMap::TYPE_PHPNAME, $indexType)]; + $this->order_id = (null !== $col) ? (int) $col : null; + + $col = $row[TableMap::TYPE_NUM == $indexType ? 2 + $startcol : ColissimoLabelTableMap::translateFieldName('OrderRef', TableMap::TYPE_PHPNAME, $indexType)]; + $this->order_ref = (null !== $col) ? (string) $col : null; + + $col = $row[TableMap::TYPE_NUM == $indexType ? 3 + $startcol : ColissimoLabelTableMap::translateFieldName('Error', TableMap::TYPE_PHPNAME, $indexType)]; + $this->error = (null !== $col) ? (boolean) $col : null; + + $col = $row[TableMap::TYPE_NUM == $indexType ? 4 + $startcol : ColissimoLabelTableMap::translateFieldName('ErrorMessage', TableMap::TYPE_PHPNAME, $indexType)]; + $this->error_message = (null !== $col) ? (string) $col : null; + + $col = $row[TableMap::TYPE_NUM == $indexType ? 5 + $startcol : ColissimoLabelTableMap::translateFieldName('TrackingNumber', TableMap::TYPE_PHPNAME, $indexType)]; + $this->tracking_number = (null !== $col) ? (string) $col : null; + + $col = $row[TableMap::TYPE_NUM == $indexType ? 6 + $startcol : ColissimoLabelTableMap::translateFieldName('LabelType', TableMap::TYPE_PHPNAME, $indexType)]; + $this->label_type = (null !== $col) ? (string) $col : null; + + $col = $row[TableMap::TYPE_NUM == $indexType ? 7 + $startcol : ColissimoLabelTableMap::translateFieldName('Weight', TableMap::TYPE_PHPNAME, $indexType)]; + $this->weight = (null !== $col) ? (string) $col : null; + + $col = $row[TableMap::TYPE_NUM == $indexType ? 8 + $startcol : ColissimoLabelTableMap::translateFieldName('Signed', TableMap::TYPE_PHPNAME, $indexType)]; + $this->signed = (null !== $col) ? (boolean) $col : null; + + $col = $row[TableMap::TYPE_NUM == $indexType ? 9 + $startcol : ColissimoLabelTableMap::translateFieldName('WithCustomsInvoice', TableMap::TYPE_PHPNAME, $indexType)]; + $this->with_customs_invoice = (null !== $col) ? (boolean) $col : null; + + $col = $row[TableMap::TYPE_NUM == $indexType ? 10 + $startcol : ColissimoLabelTableMap::translateFieldName('CreatedAt', TableMap::TYPE_PHPNAME, $indexType)]; + if ($col === '0000-00-00 00:00:00') { + $col = null; + } + $this->created_at = (null !== $col) ? PropelDateTime::newInstance($col, null, '\DateTime') : null; + + $col = $row[TableMap::TYPE_NUM == $indexType ? 11 + $startcol : ColissimoLabelTableMap::translateFieldName('UpdatedAt', TableMap::TYPE_PHPNAME, $indexType)]; + if ($col === '0000-00-00 00:00:00') { + $col = null; + } + $this->updated_at = (null !== $col) ? PropelDateTime::newInstance($col, null, '\DateTime') : null; + $this->resetModified(); + + $this->setNew(false); + + if ($rehydrate) { + $this->ensureConsistency(); + } + + return $startcol + 12; // 12 = ColissimoLabelTableMap::NUM_HYDRATE_COLUMNS. + + } catch (Exception $e) { + throw new PropelException("Error populating \ColissimoLabel\Model\ColissimoLabel object", 0, $e); + } + } + + /** + * Checks and repairs the internal consistency of the object. + * + * This method is executed after an already-instantiated object is re-hydrated + * from the database. It exists to check any foreign keys to make sure that + * the objects related to the current object are correct based on foreign key. + * + * You can override this method in the stub class, but you should always invoke + * the base method from the overridden method (i.e. parent::ensureConsistency()), + * in case your model changes. + * + * @throws PropelException + */ + public function ensureConsistency() + { + if ($this->aOrder !== null && $this->order_id !== $this->aOrder->getId()) { + $this->aOrder = null; + } + } // ensureConsistency + + /** + * Reloads this object from datastore based on primary key and (optionally) resets all associated objects. + * + * This will only work if the object has been saved and has a valid primary key set. + * + * @param boolean $deep (optional) Whether to also de-associated any related objects. + * @param ConnectionInterface $con (optional) The ConnectionInterface connection to use. + * @return void + * @throws PropelException - if this object is deleted, unsaved or doesn't have pk match in db + */ + public function reload($deep = false, ConnectionInterface $con = null) + { + if ($this->isDeleted()) { + throw new PropelException("Cannot reload a deleted object."); + } + + if ($this->isNew()) { + throw new PropelException("Cannot reload an unsaved object."); + } + + if ($con === null) { + $con = Propel::getServiceContainer()->getReadConnection(ColissimoLabelTableMap::DATABASE_NAME); + } + + // We don't need to alter the object instance pool; we're just modifying this instance + // already in the pool. + + $dataFetcher = ChildColissimoLabelQuery::create(null, $this->buildPkeyCriteria())->setFormatter(ModelCriteria::FORMAT_STATEMENT)->find($con); + $row = $dataFetcher->fetch(); + $dataFetcher->close(); + if (!$row) { + throw new PropelException('Cannot find matching row in the database to reload object values.'); + } + $this->hydrate($row, 0, true, $dataFetcher->getIndexType()); // rehydrate + + if ($deep) { // also de-associate any related objects? + + $this->aOrder = null; + } // if (deep) + } + + /** + * Removes this object from datastore and sets delete attribute. + * + * @param ConnectionInterface $con + * @return void + * @throws PropelException + * @see ColissimoLabel::setDeleted() + * @see ColissimoLabel::isDeleted() + */ + public function delete(ConnectionInterface $con = null) + { + if ($this->isDeleted()) { + throw new PropelException("This object has already been deleted."); + } + + if ($con === null) { + $con = Propel::getServiceContainer()->getWriteConnection(ColissimoLabelTableMap::DATABASE_NAME); + } + + $con->beginTransaction(); + try { + $deleteQuery = ChildColissimoLabelQuery::create() + ->filterByPrimaryKey($this->getPrimaryKey()); + $ret = $this->preDelete($con); + if ($ret) { + $deleteQuery->delete($con); + $this->postDelete($con); + $con->commit(); + $this->setDeleted(true); + } else { + $con->commit(); + } + } catch (Exception $e) { + $con->rollBack(); + throw $e; + } + } + + /** + * Persists this object to the database. + * + * If the object is new, it inserts it; otherwise an update is performed. + * All modified related objects will also be persisted in the doSave() + * method. This method wraps all precipitate database operations in a + * single transaction. + * + * @param ConnectionInterface $con + * @return int The number of rows affected by this insert/update and any referring fk objects' save() operations. + * @throws PropelException + * @see doSave() + */ + public function save(ConnectionInterface $con = null) + { + if ($this->isDeleted()) { + throw new PropelException("You cannot save an object that has been deleted."); + } + + if ($con === null) { + $con = Propel::getServiceContainer()->getWriteConnection(ColissimoLabelTableMap::DATABASE_NAME); + } + + $con->beginTransaction(); + $isInsert = $this->isNew(); + try { + $ret = $this->preSave($con); + if ($isInsert) { + $ret = $ret && $this->preInsert($con); + // timestampable behavior + if (!$this->isColumnModified(ColissimoLabelTableMap::CREATED_AT)) { + $this->setCreatedAt(time()); + } + if (!$this->isColumnModified(ColissimoLabelTableMap::UPDATED_AT)) { + $this->setUpdatedAt(time()); + } + } else { + $ret = $ret && $this->preUpdate($con); + // timestampable behavior + if ($this->isModified() && !$this->isColumnModified(ColissimoLabelTableMap::UPDATED_AT)) { + $this->setUpdatedAt(time()); + } + } + if ($ret) { + $affectedRows = $this->doSave($con); + if ($isInsert) { + $this->postInsert($con); + } else { + $this->postUpdate($con); + } + $this->postSave($con); + ColissimoLabelTableMap::addInstanceToPool($this); + } else { + $affectedRows = 0; + } + $con->commit(); + + return $affectedRows; + } catch (Exception $e) { + $con->rollBack(); + throw $e; + } + } + + /** + * Performs the work of inserting or updating the row in the database. + * + * If the object is new, it inserts it; otherwise an update is performed. + * All related objects are also updated in this method. + * + * @param ConnectionInterface $con + * @return int The number of rows affected by this insert/update and any referring fk objects' save() operations. + * @throws PropelException + * @see save() + */ + protected function doSave(ConnectionInterface $con) + { + $affectedRows = 0; // initialize var to track total num of affected rows + if (!$this->alreadyInSave) { + $this->alreadyInSave = true; + + // We call the save method on the following object(s) if they + // were passed to this object by their corresponding set + // method. This object relates to these object(s) by a + // foreign key reference. + + if ($this->aOrder !== null) { + if ($this->aOrder->isModified() || $this->aOrder->isNew()) { + $affectedRows += $this->aOrder->save($con); + } + $this->setOrder($this->aOrder); + } + + if ($this->isNew() || $this->isModified()) { + // persist changes + if ($this->isNew()) { + $this->doInsert($con); + } else { + $this->doUpdate($con); + } + $affectedRows += 1; + $this->resetModified(); + } + + $this->alreadyInSave = false; + + } + + return $affectedRows; + } // doSave() + + /** + * Insert the row in the database. + * + * @param ConnectionInterface $con + * + * @throws PropelException + * @see doSave() + */ + protected function doInsert(ConnectionInterface $con) + { + $modifiedColumns = array(); + $index = 0; + + $this->modifiedColumns[ColissimoLabelTableMap::ID] = true; + if (null !== $this->id) { + throw new PropelException('Cannot insert a value for auto-increment primary key (' . ColissimoLabelTableMap::ID . ')'); + } + + // check the columns in natural order for more readable SQL queries + if ($this->isColumnModified(ColissimoLabelTableMap::ID)) { + $modifiedColumns[':p' . $index++] = 'ID'; + } + if ($this->isColumnModified(ColissimoLabelTableMap::ORDER_ID)) { + $modifiedColumns[':p' . $index++] = 'ORDER_ID'; + } + if ($this->isColumnModified(ColissimoLabelTableMap::ORDER_REF)) { + $modifiedColumns[':p' . $index++] = 'ORDER_REF'; + } + if ($this->isColumnModified(ColissimoLabelTableMap::ERROR)) { + $modifiedColumns[':p' . $index++] = 'ERROR'; + } + if ($this->isColumnModified(ColissimoLabelTableMap::ERROR_MESSAGE)) { + $modifiedColumns[':p' . $index++] = 'ERROR_MESSAGE'; + } + if ($this->isColumnModified(ColissimoLabelTableMap::TRACKING_NUMBER)) { + $modifiedColumns[':p' . $index++] = 'TRACKING_NUMBER'; + } + if ($this->isColumnModified(ColissimoLabelTableMap::LABEL_TYPE)) { + $modifiedColumns[':p' . $index++] = 'LABEL_TYPE'; + } + if ($this->isColumnModified(ColissimoLabelTableMap::WEIGHT)) { + $modifiedColumns[':p' . $index++] = 'WEIGHT'; + } + if ($this->isColumnModified(ColissimoLabelTableMap::SIGNED)) { + $modifiedColumns[':p' . $index++] = 'SIGNED'; + } + if ($this->isColumnModified(ColissimoLabelTableMap::WITH_CUSTOMS_INVOICE)) { + $modifiedColumns[':p' . $index++] = 'WITH_CUSTOMS_INVOICE'; + } + if ($this->isColumnModified(ColissimoLabelTableMap::CREATED_AT)) { + $modifiedColumns[':p' . $index++] = 'CREATED_AT'; + } + if ($this->isColumnModified(ColissimoLabelTableMap::UPDATED_AT)) { + $modifiedColumns[':p' . $index++] = 'UPDATED_AT'; + } + + $sql = sprintf( + 'INSERT INTO colissimo_label (%s) VALUES (%s)', + implode(', ', $modifiedColumns), + implode(', ', array_keys($modifiedColumns)) + ); + + try { + $stmt = $con->prepare($sql); + foreach ($modifiedColumns as $identifier => $columnName) { + switch ($columnName) { + case 'ID': + $stmt->bindValue($identifier, $this->id, PDO::PARAM_INT); + break; + case 'ORDER_ID': + $stmt->bindValue($identifier, $this->order_id, PDO::PARAM_INT); + break; + case 'ORDER_REF': + $stmt->bindValue($identifier, $this->order_ref, PDO::PARAM_STR); + break; + case 'ERROR': + $stmt->bindValue($identifier, (int) $this->error, PDO::PARAM_INT); + break; + case 'ERROR_MESSAGE': + $stmt->bindValue($identifier, $this->error_message, PDO::PARAM_STR); + break; + case 'TRACKING_NUMBER': + $stmt->bindValue($identifier, $this->tracking_number, PDO::PARAM_STR); + break; + case 'LABEL_TYPE': + $stmt->bindValue($identifier, $this->label_type, PDO::PARAM_STR); + break; + case 'WEIGHT': + $stmt->bindValue($identifier, $this->weight, PDO::PARAM_STR); + break; + case 'SIGNED': + $stmt->bindValue($identifier, (int) $this->signed, PDO::PARAM_INT); + break; + case 'WITH_CUSTOMS_INVOICE': + $stmt->bindValue($identifier, (int) $this->with_customs_invoice, PDO::PARAM_INT); + break; + case 'CREATED_AT': + $stmt->bindValue($identifier, $this->created_at ? $this->created_at->format("Y-m-d H:i:s") : null, PDO::PARAM_STR); + break; + case 'UPDATED_AT': + $stmt->bindValue($identifier, $this->updated_at ? $this->updated_at->format("Y-m-d H:i:s") : null, PDO::PARAM_STR); + break; + } + } + $stmt->execute(); + } catch (Exception $e) { + Propel::log($e->getMessage(), Propel::LOG_ERR); + throw new PropelException(sprintf('Unable to execute INSERT statement [%s]', $sql), 0, $e); + } + + try { + $pk = $con->lastInsertId(); + } catch (Exception $e) { + throw new PropelException('Unable to get autoincrement id.', 0, $e); + } + $this->setId($pk); + + $this->setNew(false); + } + + /** + * Update the row in the database. + * + * @param ConnectionInterface $con + * + * @return Integer Number of updated rows + * @see doSave() + */ + protected function doUpdate(ConnectionInterface $con) + { + $selectCriteria = $this->buildPkeyCriteria(); + $valuesCriteria = $this->buildCriteria(); + + return $selectCriteria->doUpdate($valuesCriteria, $con); + } + + /** + * Retrieves a field from the object by name passed in as a string. + * + * @param string $name name + * @param string $type The type of fieldname the $name is of: + * one of the class type constants TableMap::TYPE_PHPNAME, TableMap::TYPE_STUDLYPHPNAME + * TableMap::TYPE_COLNAME, TableMap::TYPE_FIELDNAME, TableMap::TYPE_NUM. + * Defaults to TableMap::TYPE_PHPNAME. + * @return mixed Value of field. + */ + public function getByName($name, $type = TableMap::TYPE_PHPNAME) + { + $pos = ColissimoLabelTableMap::translateFieldName($name, $type, TableMap::TYPE_NUM); + $field = $this->getByPosition($pos); + + return $field; + } + + /** + * Retrieves a field from the object by Position as specified in the xml schema. + * Zero-based. + * + * @param int $pos position in xml schema + * @return mixed Value of field at $pos + */ + public function getByPosition($pos) + { + switch ($pos) { + case 0: + return $this->getId(); + break; + case 1: + return $this->getOrderId(); + break; + case 2: + return $this->getOrderRef(); + break; + case 3: + return $this->getError(); + break; + case 4: + return $this->getErrorMessage(); + break; + case 5: + return $this->getTrackingNumber(); + break; + case 6: + return $this->getLabelType(); + break; + case 7: + return $this->getWeight(); + break; + case 8: + return $this->getSigned(); + break; + case 9: + return $this->getWithCustomsInvoice(); + break; + case 10: + return $this->getCreatedAt(); + break; + case 11: + return $this->getUpdatedAt(); + break; + default: + return null; + break; + } // switch() + } + + /** + * Exports the object as an array. + * + * You can specify the key type of the array by passing one of the class + * type constants. + * + * @param string $keyType (optional) One of the class type constants TableMap::TYPE_PHPNAME, TableMap::TYPE_STUDLYPHPNAME, + * TableMap::TYPE_COLNAME, TableMap::TYPE_FIELDNAME, TableMap::TYPE_NUM. + * Defaults to TableMap::TYPE_PHPNAME. + * @param boolean $includeLazyLoadColumns (optional) Whether to include lazy loaded columns. Defaults to TRUE. + * @param array $alreadyDumpedObjects List of objects to skip to avoid recursion + * @param boolean $includeForeignObjects (optional) Whether to include hydrated related objects. Default to FALSE. + * + * @return array an associative array containing the field names (as keys) and field values + */ + public function toArray($keyType = TableMap::TYPE_PHPNAME, $includeLazyLoadColumns = true, $alreadyDumpedObjects = array(), $includeForeignObjects = false) + { + if (isset($alreadyDumpedObjects['ColissimoLabel'][$this->getPrimaryKey()])) { + return '*RECURSION*'; + } + $alreadyDumpedObjects['ColissimoLabel'][$this->getPrimaryKey()] = true; + $keys = ColissimoLabelTableMap::getFieldNames($keyType); + $result = array( + $keys[0] => $this->getId(), + $keys[1] => $this->getOrderId(), + $keys[2] => $this->getOrderRef(), + $keys[3] => $this->getError(), + $keys[4] => $this->getErrorMessage(), + $keys[5] => $this->getTrackingNumber(), + $keys[6] => $this->getLabelType(), + $keys[7] => $this->getWeight(), + $keys[8] => $this->getSigned(), + $keys[9] => $this->getWithCustomsInvoice(), + $keys[10] => $this->getCreatedAt(), + $keys[11] => $this->getUpdatedAt(), + ); + $virtualColumns = $this->virtualColumns; + foreach ($virtualColumns as $key => $virtualColumn) { + $result[$key] = $virtualColumn; + } + + if ($includeForeignObjects) { + if (null !== $this->aOrder) { + $result['Order'] = $this->aOrder->toArray($keyType, $includeLazyLoadColumns, $alreadyDumpedObjects, true); + } + } + + return $result; + } + + /** + * Sets a field from the object by name passed in as a string. + * + * @param string $name + * @param mixed $value field value + * @param string $type The type of fieldname the $name is of: + * one of the class type constants TableMap::TYPE_PHPNAME, TableMap::TYPE_STUDLYPHPNAME + * TableMap::TYPE_COLNAME, TableMap::TYPE_FIELDNAME, TableMap::TYPE_NUM. + * Defaults to TableMap::TYPE_PHPNAME. + * @return void + */ + public function setByName($name, $value, $type = TableMap::TYPE_PHPNAME) + { + $pos = ColissimoLabelTableMap::translateFieldName($name, $type, TableMap::TYPE_NUM); + + return $this->setByPosition($pos, $value); + } + + /** + * Sets a field from the object by Position as specified in the xml schema. + * Zero-based. + * + * @param int $pos position in xml schema + * @param mixed $value field value + * @return void + */ + public function setByPosition($pos, $value) + { + switch ($pos) { + case 0: + $this->setId($value); + break; + case 1: + $this->setOrderId($value); + break; + case 2: + $this->setOrderRef($value); + break; + case 3: + $this->setError($value); + break; + case 4: + $this->setErrorMessage($value); + break; + case 5: + $this->setTrackingNumber($value); + break; + case 6: + $this->setLabelType($value); + break; + case 7: + $this->setWeight($value); + break; + case 8: + $this->setSigned($value); + break; + case 9: + $this->setWithCustomsInvoice($value); + break; + case 10: + $this->setCreatedAt($value); + break; + case 11: + $this->setUpdatedAt($value); + break; + } // switch() + } + + /** + * Populates the object using an array. + * + * This is particularly useful when populating an object from one of the + * request arrays (e.g. $_POST). This method goes through the column + * names, checking to see whether a matching key exists in populated + * array. If so the setByName() method is called for that column. + * + * You can specify the key type of the array by additionally passing one + * of the class type constants TableMap::TYPE_PHPNAME, TableMap::TYPE_STUDLYPHPNAME, + * TableMap::TYPE_COLNAME, TableMap::TYPE_FIELDNAME, TableMap::TYPE_NUM. + * The default key type is the column's TableMap::TYPE_PHPNAME. + * + * @param array $arr An array to populate the object from. + * @param string $keyType The type of keys the array uses. + * @return void + */ + public function fromArray($arr, $keyType = TableMap::TYPE_PHPNAME) + { + $keys = ColissimoLabelTableMap::getFieldNames($keyType); + + if (array_key_exists($keys[0], $arr)) $this->setId($arr[$keys[0]]); + if (array_key_exists($keys[1], $arr)) $this->setOrderId($arr[$keys[1]]); + if (array_key_exists($keys[2], $arr)) $this->setOrderRef($arr[$keys[2]]); + if (array_key_exists($keys[3], $arr)) $this->setError($arr[$keys[3]]); + if (array_key_exists($keys[4], $arr)) $this->setErrorMessage($arr[$keys[4]]); + if (array_key_exists($keys[5], $arr)) $this->setTrackingNumber($arr[$keys[5]]); + if (array_key_exists($keys[6], $arr)) $this->setLabelType($arr[$keys[6]]); + if (array_key_exists($keys[7], $arr)) $this->setWeight($arr[$keys[7]]); + if (array_key_exists($keys[8], $arr)) $this->setSigned($arr[$keys[8]]); + if (array_key_exists($keys[9], $arr)) $this->setWithCustomsInvoice($arr[$keys[9]]); + if (array_key_exists($keys[10], $arr)) $this->setCreatedAt($arr[$keys[10]]); + if (array_key_exists($keys[11], $arr)) $this->setUpdatedAt($arr[$keys[11]]); + } + + /** + * Build a Criteria object containing the values of all modified columns in this object. + * + * @return Criteria The Criteria object containing all modified values. + */ + public function buildCriteria() + { + $criteria = new Criteria(ColissimoLabelTableMap::DATABASE_NAME); + + if ($this->isColumnModified(ColissimoLabelTableMap::ID)) $criteria->add(ColissimoLabelTableMap::ID, $this->id); + if ($this->isColumnModified(ColissimoLabelTableMap::ORDER_ID)) $criteria->add(ColissimoLabelTableMap::ORDER_ID, $this->order_id); + if ($this->isColumnModified(ColissimoLabelTableMap::ORDER_REF)) $criteria->add(ColissimoLabelTableMap::ORDER_REF, $this->order_ref); + if ($this->isColumnModified(ColissimoLabelTableMap::ERROR)) $criteria->add(ColissimoLabelTableMap::ERROR, $this->error); + if ($this->isColumnModified(ColissimoLabelTableMap::ERROR_MESSAGE)) $criteria->add(ColissimoLabelTableMap::ERROR_MESSAGE, $this->error_message); + if ($this->isColumnModified(ColissimoLabelTableMap::TRACKING_NUMBER)) $criteria->add(ColissimoLabelTableMap::TRACKING_NUMBER, $this->tracking_number); + if ($this->isColumnModified(ColissimoLabelTableMap::LABEL_TYPE)) $criteria->add(ColissimoLabelTableMap::LABEL_TYPE, $this->label_type); + if ($this->isColumnModified(ColissimoLabelTableMap::WEIGHT)) $criteria->add(ColissimoLabelTableMap::WEIGHT, $this->weight); + if ($this->isColumnModified(ColissimoLabelTableMap::SIGNED)) $criteria->add(ColissimoLabelTableMap::SIGNED, $this->signed); + if ($this->isColumnModified(ColissimoLabelTableMap::WITH_CUSTOMS_INVOICE)) $criteria->add(ColissimoLabelTableMap::WITH_CUSTOMS_INVOICE, $this->with_customs_invoice); + if ($this->isColumnModified(ColissimoLabelTableMap::CREATED_AT)) $criteria->add(ColissimoLabelTableMap::CREATED_AT, $this->created_at); + if ($this->isColumnModified(ColissimoLabelTableMap::UPDATED_AT)) $criteria->add(ColissimoLabelTableMap::UPDATED_AT, $this->updated_at); + + return $criteria; + } + + /** + * Builds a Criteria object containing the primary key for this object. + * + * Unlike buildCriteria() this method includes the primary key values regardless + * of whether or not they have been modified. + * + * @return Criteria The Criteria object containing value(s) for primary key(s). + */ + public function buildPkeyCriteria() + { + $criteria = new Criteria(ColissimoLabelTableMap::DATABASE_NAME); + $criteria->add(ColissimoLabelTableMap::ID, $this->id); + + return $criteria; + } + + /** + * Returns the primary key for this object (row). + * @return int + */ + public function getPrimaryKey() + { + return $this->getId(); + } + + /** + * Generic method to set the primary key (id column). + * + * @param int $key Primary key. + * @return void + */ + public function setPrimaryKey($key) + { + $this->setId($key); + } + + /** + * Returns true if the primary key for this object is null. + * @return boolean + */ + public function isPrimaryKeyNull() + { + + return null === $this->getId(); + } + + /** + * Sets contents of passed object to values from current object. + * + * If desired, this method can also make copies of all associated (fkey referrers) + * objects. + * + * @param object $copyObj An object of \ColissimoLabel\Model\ColissimoLabel (or compatible) type. + * @param boolean $deepCopy Whether to also copy all rows that refer (by fkey) to the current row. + * @param boolean $makeNew Whether to reset autoincrement PKs and make the object new. + * @throws PropelException + */ + public function copyInto($copyObj, $deepCopy = false, $makeNew = true) + { + $copyObj->setOrderId($this->getOrderId()); + $copyObj->setOrderRef($this->getOrderRef()); + $copyObj->setError($this->getError()); + $copyObj->setErrorMessage($this->getErrorMessage()); + $copyObj->setTrackingNumber($this->getTrackingNumber()); + $copyObj->setLabelType($this->getLabelType()); + $copyObj->setWeight($this->getWeight()); + $copyObj->setSigned($this->getSigned()); + $copyObj->setWithCustomsInvoice($this->getWithCustomsInvoice()); + $copyObj->setCreatedAt($this->getCreatedAt()); + $copyObj->setUpdatedAt($this->getUpdatedAt()); + if ($makeNew) { + $copyObj->setNew(true); + $copyObj->setId(NULL); // this is a auto-increment column, so set to default value + } + } + + /** + * Makes a copy of this object that will be inserted as a new row in table when saved. + * It creates a new object filling in the simple attributes, but skipping any primary + * keys that are defined for the table. + * + * If desired, this method can also make copies of all associated (fkey referrers) + * objects. + * + * @param boolean $deepCopy Whether to also copy all rows that refer (by fkey) to the current row. + * @return \ColissimoLabel\Model\ColissimoLabel Clone of current object. + * @throws PropelException + */ + public function copy($deepCopy = false) + { + // we use get_class(), because this might be a subclass + $clazz = get_class($this); + $copyObj = new $clazz(); + $this->copyInto($copyObj, $deepCopy); + + return $copyObj; + } + + /** + * Declares an association between this object and a ChildOrder object. + * + * @param ChildOrder $v + * @return \ColissimoLabel\Model\ColissimoLabel The current object (for fluent API support) + * @throws PropelException + */ + public function setOrder(ChildOrder $v = null) + { + if ($v === null) { + $this->setOrderId(NULL); + } else { + $this->setOrderId($v->getId()); + } + + $this->aOrder = $v; + + // Add binding for other direction of this n:n relationship. + // If this object has already been added to the ChildOrder object, it will not be re-added. + if ($v !== null) { + $v->addColissimoLabel($this); + } + + + return $this; + } + + + /** + * Get the associated ChildOrder object + * + * @param ConnectionInterface $con Optional Connection object. + * @return ChildOrder The associated ChildOrder object. + * @throws PropelException + */ + public function getOrder(ConnectionInterface $con = null) + { + if ($this->aOrder === null && ($this->order_id !== null)) { + $this->aOrder = OrderQuery::create()->findPk($this->order_id, $con); + /* The following can be used additionally to + guarantee the related object contains a reference + to this object. This level of coupling may, however, be + undesirable since it could result in an only partially populated collection + in the referenced object. + $this->aOrder->addColissimoLabels($this); + */ + } + + return $this->aOrder; + } + + /** + * Clears the current object and sets all attributes to their default values + */ + public function clear() + { + $this->id = null; + $this->order_id = null; + $this->order_ref = null; + $this->error = null; + $this->error_message = null; + $this->tracking_number = null; + $this->label_type = null; + $this->weight = null; + $this->signed = null; + $this->with_customs_invoice = null; + $this->created_at = null; + $this->updated_at = null; + $this->alreadyInSave = false; + $this->clearAllReferences(); + $this->applyDefaultValues(); + $this->resetModified(); + $this->setNew(true); + $this->setDeleted(false); + } + + /** + * Resets all references to other model objects or collections of model objects. + * + * This method is a user-space workaround for PHP's inability to garbage collect + * objects with circular references (even in PHP 5.3). This is currently necessary + * when using Propel in certain daemon or large-volume/high-memory operations. + * + * @param boolean $deep Whether to also clear the references on all referrer objects. + */ + public function clearAllReferences($deep = false) + { + if ($deep) { + } // if ($deep) + + $this->aOrder = null; + } + + /** + * Return the string representation of this object + * + * @return string + */ + public function __toString() + { + return (string) $this->exportTo(ColissimoLabelTableMap::DEFAULT_STRING_FORMAT); + } + + // timestampable behavior + + /** + * Mark the current object so that the update date doesn't get updated during next save + * + * @return ChildColissimoLabel The current object (for fluent API support) + */ + public function keepUpdateDateUnchanged() + { + $this->modifiedColumns[ColissimoLabelTableMap::UPDATED_AT] = true; + + return $this; + } + + /** + * Code to be run before persisting the object + * @param ConnectionInterface $con + * @return boolean + */ + public function preSave(ConnectionInterface $con = null) + { + return true; + } + + /** + * Code to be run after persisting the object + * @param ConnectionInterface $con + */ + public function postSave(ConnectionInterface $con = null) + { + + } + + /** + * Code to be run before inserting to database + * @param ConnectionInterface $con + * @return boolean + */ + public function preInsert(ConnectionInterface $con = null) + { + return true; + } + + /** + * Code to be run after inserting to database + * @param ConnectionInterface $con + */ + public function postInsert(ConnectionInterface $con = null) + { + + } + + /** + * Code to be run before updating the object in database + * @param ConnectionInterface $con + * @return boolean + */ + public function preUpdate(ConnectionInterface $con = null) + { + return true; + } + + /** + * Code to be run after updating the object in database + * @param ConnectionInterface $con + */ + public function postUpdate(ConnectionInterface $con = null) + { + + } + + /** + * Code to be run before deleting the object in database + * @param ConnectionInterface $con + * @return boolean + */ + public function preDelete(ConnectionInterface $con = null) + { + return true; + } + + /** + * Code to be run after deleting the object in database + * @param ConnectionInterface $con + */ + public function postDelete(ConnectionInterface $con = null) + { + + } + + + /** + * Derived method to catches calls to undefined methods. + * + * Provides magic import/export method support (fromXML()/toXML(), fromYAML()/toYAML(), etc.). + * Allows to define default __call() behavior if you overwrite __call() + * + * @param string $name + * @param mixed $params + * + * @return array|string + */ + public function __call($name, $params) + { + if (0 === strpos($name, 'get')) { + $virtualColumn = substr($name, 3); + if ($this->hasVirtualColumn($virtualColumn)) { + return $this->getVirtualColumn($virtualColumn); + } + + $virtualColumn = lcfirst($virtualColumn); + if ($this->hasVirtualColumn($virtualColumn)) { + return $this->getVirtualColumn($virtualColumn); + } + } + + if (0 === strpos($name, 'from')) { + $format = substr($name, 4); + + return $this->importFrom($format, reset($params)); + } + + if (0 === strpos($name, 'to')) { + $format = substr($name, 2); + $includeLazyLoadColumns = isset($params[0]) ? $params[0] : true; + + return $this->exportTo($format, $includeLazyLoadColumns); + } + + throw new BadMethodCallException(sprintf('Call to undefined method: %s.', $name)); + } + +} diff --git a/local/modules/ColissimoLabel/Model/Base/ColissimoLabelQuery.php b/local/modules/ColissimoLabel/Model/Base/ColissimoLabelQuery.php new file mode 100644 index 00000000..4644248b --- /dev/null +++ b/local/modules/ColissimoLabel/Model/Base/ColissimoLabelQuery.php @@ -0,0 +1,904 @@ +setModelAlias($modelAlias); + } + if ($criteria instanceof Criteria) { + $query->mergeWith($criteria); + } + + return $query; + } + + /** + * Find object by primary key. + * Propel uses the instance pool to skip the database if the object exists. + * Go fast if the query is untouched. + * + * + * $obj = $c->findPk(12, $con); + * + * + * @param mixed $key Primary key to use for the query + * @param ConnectionInterface $con an optional connection object + * + * @return ChildColissimoLabel|array|mixed the result, formatted by the current formatter + */ + public function findPk($key, $con = null) + { + if ($key === null) { + return null; + } + if ((null !== ($obj = ColissimoLabelTableMap::getInstanceFromPool((string) $key))) && !$this->formatter) { + // the object is already in the instance pool + return $obj; + } + if ($con === null) { + $con = Propel::getServiceContainer()->getReadConnection(ColissimoLabelTableMap::DATABASE_NAME); + } + $this->basePreSelect($con); + if ($this->formatter || $this->modelAlias || $this->with || $this->select + || $this->selectColumns || $this->asColumns || $this->selectModifiers + || $this->map || $this->having || $this->joins) { + return $this->findPkComplex($key, $con); + } else { + return $this->findPkSimple($key, $con); + } + } + + /** + * Find object by primary key using raw SQL to go fast. + * Bypass doSelect() and the object formatter by using generated code. + * + * @param mixed $key Primary key to use for the query + * @param ConnectionInterface $con A connection object + * + * @return ChildColissimoLabel A model object, or null if the key is not found + */ + protected function findPkSimple($key, $con) + { + $sql = 'SELECT ID, ORDER_ID, ORDER_REF, ERROR, ERROR_MESSAGE, TRACKING_NUMBER, LABEL_TYPE, WEIGHT, SIGNED, WITH_CUSTOMS_INVOICE, CREATED_AT, UPDATED_AT FROM colissimo_label WHERE ID = :p0'; + try { + $stmt = $con->prepare($sql); + $stmt->bindValue(':p0', $key, PDO::PARAM_INT); + $stmt->execute(); + } catch (Exception $e) { + Propel::log($e->getMessage(), Propel::LOG_ERR); + throw new PropelException(sprintf('Unable to execute SELECT statement [%s]', $sql), 0, $e); + } + $obj = null; + if ($row = $stmt->fetch(\PDO::FETCH_NUM)) { + $obj = new ChildColissimoLabel(); + $obj->hydrate($row); + ColissimoLabelTableMap::addInstanceToPool($obj, (string) $key); + } + $stmt->closeCursor(); + + return $obj; + } + + /** + * Find object by primary key. + * + * @param mixed $key Primary key to use for the query + * @param ConnectionInterface $con A connection object + * + * @return ChildColissimoLabel|array|mixed the result, formatted by the current formatter + */ + protected function findPkComplex($key, $con) + { + // As the query uses a PK condition, no limit(1) is necessary. + $criteria = $this->isKeepQuery() ? clone $this : $this; + $dataFetcher = $criteria + ->filterByPrimaryKey($key) + ->doSelect($con); + + return $criteria->getFormatter()->init($criteria)->formatOne($dataFetcher); + } + + /** + * Find objects by primary key + * + * $objs = $c->findPks(array(12, 56, 832), $con); + * + * @param array $keys Primary keys to use for the query + * @param ConnectionInterface $con an optional connection object + * + * @return ObjectCollection|array|mixed the list of results, formatted by the current formatter + */ + public function findPks($keys, $con = null) + { + if (null === $con) { + $con = Propel::getServiceContainer()->getReadConnection($this->getDbName()); + } + $this->basePreSelect($con); + $criteria = $this->isKeepQuery() ? clone $this : $this; + $dataFetcher = $criteria + ->filterByPrimaryKeys($keys) + ->doSelect($con); + + return $criteria->getFormatter()->init($criteria)->format($dataFetcher); + } + + /** + * Filter the query by primary key + * + * @param mixed $key Primary key to use for the query + * + * @return ChildColissimoLabelQuery The current query, for fluid interface + */ + public function filterByPrimaryKey($key) + { + + return $this->addUsingAlias(ColissimoLabelTableMap::ID, $key, Criteria::EQUAL); + } + + /** + * Filter the query by a list of primary keys + * + * @param array $keys The list of primary key to use for the query + * + * @return ChildColissimoLabelQuery The current query, for fluid interface + */ + public function filterByPrimaryKeys($keys) + { + + return $this->addUsingAlias(ColissimoLabelTableMap::ID, $keys, Criteria::IN); + } + + /** + * Filter the query on the id column + * + * Example usage: + * + * $query->filterById(1234); // WHERE id = 1234 + * $query->filterById(array(12, 34)); // WHERE id IN (12, 34) + * $query->filterById(array('min' => 12)); // WHERE id > 12 + * + * + * @param mixed $id The value to use as filter. + * Use scalar values for equality. + * Use array values for in_array() equivalent. + * Use associative array('min' => $minValue, 'max' => $maxValue) for intervals. + * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL + * + * @return ChildColissimoLabelQuery The current query, for fluid interface + */ + public function filterById($id = null, $comparison = null) + { + if (is_array($id)) { + $useMinMax = false; + if (isset($id['min'])) { + $this->addUsingAlias(ColissimoLabelTableMap::ID, $id['min'], Criteria::GREATER_EQUAL); + $useMinMax = true; + } + if (isset($id['max'])) { + $this->addUsingAlias(ColissimoLabelTableMap::ID, $id['max'], Criteria::LESS_EQUAL); + $useMinMax = true; + } + if ($useMinMax) { + return $this; + } + if (null === $comparison) { + $comparison = Criteria::IN; + } + } + + return $this->addUsingAlias(ColissimoLabelTableMap::ID, $id, $comparison); + } + + /** + * Filter the query on the order_id column + * + * Example usage: + * + * $query->filterByOrderId(1234); // WHERE order_id = 1234 + * $query->filterByOrderId(array(12, 34)); // WHERE order_id IN (12, 34) + * $query->filterByOrderId(array('min' => 12)); // WHERE order_id > 12 + * + * + * @see filterByOrder() + * + * @param mixed $orderId The value to use as filter. + * Use scalar values for equality. + * Use array values for in_array() equivalent. + * Use associative array('min' => $minValue, 'max' => $maxValue) for intervals. + * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL + * + * @return ChildColissimoLabelQuery The current query, for fluid interface + */ + public function filterByOrderId($orderId = null, $comparison = null) + { + if (is_array($orderId)) { + $useMinMax = false; + if (isset($orderId['min'])) { + $this->addUsingAlias(ColissimoLabelTableMap::ORDER_ID, $orderId['min'], Criteria::GREATER_EQUAL); + $useMinMax = true; + } + if (isset($orderId['max'])) { + $this->addUsingAlias(ColissimoLabelTableMap::ORDER_ID, $orderId['max'], Criteria::LESS_EQUAL); + $useMinMax = true; + } + if ($useMinMax) { + return $this; + } + if (null === $comparison) { + $comparison = Criteria::IN; + } + } + + return $this->addUsingAlias(ColissimoLabelTableMap::ORDER_ID, $orderId, $comparison); + } + + /** + * Filter the query on the order_ref column + * + * Example usage: + * + * $query->filterByOrderRef('fooValue'); // WHERE order_ref = 'fooValue' + * $query->filterByOrderRef('%fooValue%'); // WHERE order_ref LIKE '%fooValue%' + * + * + * @param string $orderRef The value to use as filter. + * Accepts wildcards (* and % trigger a LIKE) + * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL + * + * @return ChildColissimoLabelQuery The current query, for fluid interface + */ + public function filterByOrderRef($orderRef = null, $comparison = null) + { + if (null === $comparison) { + if (is_array($orderRef)) { + $comparison = Criteria::IN; + } elseif (preg_match('/[\%\*]/', $orderRef)) { + $orderRef = str_replace('*', '%', $orderRef); + $comparison = Criteria::LIKE; + } + } + + return $this->addUsingAlias(ColissimoLabelTableMap::ORDER_REF, $orderRef, $comparison); + } + + /** + * Filter the query on the error column + * + * Example usage: + * + * $query->filterByError(true); // WHERE error = true + * $query->filterByError('yes'); // WHERE error = true + * + * + * @param boolean|string $error The value to use as filter. + * Non-boolean arguments are converted using the following rules: + * * 1, '1', 'true', 'on', and 'yes' are converted to boolean true + * * 0, '0', 'false', 'off', and 'no' are converted to boolean false + * Check on string values is case insensitive (so 'FaLsE' is seen as 'false'). + * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL + * + * @return ChildColissimoLabelQuery The current query, for fluid interface + */ + public function filterByError($error = null, $comparison = null) + { + if (is_string($error)) { + $error = in_array(strtolower($error), array('false', 'off', '-', 'no', 'n', '0', '')) ? false : true; + } + + return $this->addUsingAlias(ColissimoLabelTableMap::ERROR, $error, $comparison); + } + + /** + * Filter the query on the error_message column + * + * Example usage: + * + * $query->filterByErrorMessage('fooValue'); // WHERE error_message = 'fooValue' + * $query->filterByErrorMessage('%fooValue%'); // WHERE error_message LIKE '%fooValue%' + * + * + * @param string $errorMessage The value to use as filter. + * Accepts wildcards (* and % trigger a LIKE) + * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL + * + * @return ChildColissimoLabelQuery The current query, for fluid interface + */ + public function filterByErrorMessage($errorMessage = null, $comparison = null) + { + if (null === $comparison) { + if (is_array($errorMessage)) { + $comparison = Criteria::IN; + } elseif (preg_match('/[\%\*]/', $errorMessage)) { + $errorMessage = str_replace('*', '%', $errorMessage); + $comparison = Criteria::LIKE; + } + } + + return $this->addUsingAlias(ColissimoLabelTableMap::ERROR_MESSAGE, $errorMessage, $comparison); + } + + /** + * Filter the query on the tracking_number column + * + * Example usage: + * + * $query->filterByTrackingNumber('fooValue'); // WHERE tracking_number = 'fooValue' + * $query->filterByTrackingNumber('%fooValue%'); // WHERE tracking_number LIKE '%fooValue%' + * + * + * @param string $trackingNumber The value to use as filter. + * Accepts wildcards (* and % trigger a LIKE) + * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL + * + * @return ChildColissimoLabelQuery The current query, for fluid interface + */ + public function filterByTrackingNumber($trackingNumber = null, $comparison = null) + { + if (null === $comparison) { + if (is_array($trackingNumber)) { + $comparison = Criteria::IN; + } elseif (preg_match('/[\%\*]/', $trackingNumber)) { + $trackingNumber = str_replace('*', '%', $trackingNumber); + $comparison = Criteria::LIKE; + } + } + + return $this->addUsingAlias(ColissimoLabelTableMap::TRACKING_NUMBER, $trackingNumber, $comparison); + } + + /** + * Filter the query on the label_type column + * + * Example usage: + * + * $query->filterByLabelType('fooValue'); // WHERE label_type = 'fooValue' + * $query->filterByLabelType('%fooValue%'); // WHERE label_type LIKE '%fooValue%' + * + * + * @param string $labelType The value to use as filter. + * Accepts wildcards (* and % trigger a LIKE) + * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL + * + * @return ChildColissimoLabelQuery The current query, for fluid interface + */ + public function filterByLabelType($labelType = null, $comparison = null) + { + if (null === $comparison) { + if (is_array($labelType)) { + $comparison = Criteria::IN; + } elseif (preg_match('/[\%\*]/', $labelType)) { + $labelType = str_replace('*', '%', $labelType); + $comparison = Criteria::LIKE; + } + } + + return $this->addUsingAlias(ColissimoLabelTableMap::LABEL_TYPE, $labelType, $comparison); + } + + /** + * Filter the query on the weight column + * + * Example usage: + * + * $query->filterByWeight(1234); // WHERE weight = 1234 + * $query->filterByWeight(array(12, 34)); // WHERE weight IN (12, 34) + * $query->filterByWeight(array('min' => 12)); // WHERE weight > 12 + * + * + * @param mixed $weight The value to use as filter. + * Use scalar values for equality. + * Use array values for in_array() equivalent. + * Use associative array('min' => $minValue, 'max' => $maxValue) for intervals. + * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL + * + * @return ChildColissimoLabelQuery The current query, for fluid interface + */ + public function filterByWeight($weight = null, $comparison = null) + { + if (is_array($weight)) { + $useMinMax = false; + if (isset($weight['min'])) { + $this->addUsingAlias(ColissimoLabelTableMap::WEIGHT, $weight['min'], Criteria::GREATER_EQUAL); + $useMinMax = true; + } + if (isset($weight['max'])) { + $this->addUsingAlias(ColissimoLabelTableMap::WEIGHT, $weight['max'], Criteria::LESS_EQUAL); + $useMinMax = true; + } + if ($useMinMax) { + return $this; + } + if (null === $comparison) { + $comparison = Criteria::IN; + } + } + + return $this->addUsingAlias(ColissimoLabelTableMap::WEIGHT, $weight, $comparison); + } + + /** + * Filter the query on the signed column + * + * Example usage: + * + * $query->filterBySigned(true); // WHERE signed = true + * $query->filterBySigned('yes'); // WHERE signed = true + * + * + * @param boolean|string $signed The value to use as filter. + * Non-boolean arguments are converted using the following rules: + * * 1, '1', 'true', 'on', and 'yes' are converted to boolean true + * * 0, '0', 'false', 'off', and 'no' are converted to boolean false + * Check on string values is case insensitive (so 'FaLsE' is seen as 'false'). + * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL + * + * @return ChildColissimoLabelQuery The current query, for fluid interface + */ + public function filterBySigned($signed = null, $comparison = null) + { + if (is_string($signed)) { + $signed = in_array(strtolower($signed), array('false', 'off', '-', 'no', 'n', '0', '')) ? false : true; + } + + return $this->addUsingAlias(ColissimoLabelTableMap::SIGNED, $signed, $comparison); + } + + /** + * Filter the query on the with_customs_invoice column + * + * Example usage: + * + * $query->filterByWithCustomsInvoice(true); // WHERE with_customs_invoice = true + * $query->filterByWithCustomsInvoice('yes'); // WHERE with_customs_invoice = true + * + * + * @param boolean|string $withCustomsInvoice The value to use as filter. + * Non-boolean arguments are converted using the following rules: + * * 1, '1', 'true', 'on', and 'yes' are converted to boolean true + * * 0, '0', 'false', 'off', and 'no' are converted to boolean false + * Check on string values is case insensitive (so 'FaLsE' is seen as 'false'). + * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL + * + * @return ChildColissimoLabelQuery The current query, for fluid interface + */ + public function filterByWithCustomsInvoice($withCustomsInvoice = null, $comparison = null) + { + if (is_string($withCustomsInvoice)) { + $with_customs_invoice = in_array(strtolower($withCustomsInvoice), array('false', 'off', '-', 'no', 'n', '0', '')) ? false : true; + } + + return $this->addUsingAlias(ColissimoLabelTableMap::WITH_CUSTOMS_INVOICE, $withCustomsInvoice, $comparison); + } + + /** + * Filter the query on the created_at column + * + * Example usage: + * + * $query->filterByCreatedAt('2011-03-14'); // WHERE created_at = '2011-03-14' + * $query->filterByCreatedAt('now'); // WHERE created_at = '2011-03-14' + * $query->filterByCreatedAt(array('max' => 'yesterday')); // WHERE created_at > '2011-03-13' + * + * + * @param mixed $createdAt The value to use as filter. + * Values can be integers (unix timestamps), DateTime objects, or strings. + * Empty strings are treated as NULL. + * Use scalar values for equality. + * Use array values for in_array() equivalent. + * Use associative array('min' => $minValue, 'max' => $maxValue) for intervals. + * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL + * + * @return ChildColissimoLabelQuery The current query, for fluid interface + */ + public function filterByCreatedAt($createdAt = null, $comparison = null) + { + if (is_array($createdAt)) { + $useMinMax = false; + if (isset($createdAt['min'])) { + $this->addUsingAlias(ColissimoLabelTableMap::CREATED_AT, $createdAt['min'], Criteria::GREATER_EQUAL); + $useMinMax = true; + } + if (isset($createdAt['max'])) { + $this->addUsingAlias(ColissimoLabelTableMap::CREATED_AT, $createdAt['max'], Criteria::LESS_EQUAL); + $useMinMax = true; + } + if ($useMinMax) { + return $this; + } + if (null === $comparison) { + $comparison = Criteria::IN; + } + } + + return $this->addUsingAlias(ColissimoLabelTableMap::CREATED_AT, $createdAt, $comparison); + } + + /** + * Filter the query on the updated_at column + * + * Example usage: + * + * $query->filterByUpdatedAt('2011-03-14'); // WHERE updated_at = '2011-03-14' + * $query->filterByUpdatedAt('now'); // WHERE updated_at = '2011-03-14' + * $query->filterByUpdatedAt(array('max' => 'yesterday')); // WHERE updated_at > '2011-03-13' + * + * + * @param mixed $updatedAt The value to use as filter. + * Values can be integers (unix timestamps), DateTime objects, or strings. + * Empty strings are treated as NULL. + * Use scalar values for equality. + * Use array values for in_array() equivalent. + * Use associative array('min' => $minValue, 'max' => $maxValue) for intervals. + * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL + * + * @return ChildColissimoLabelQuery The current query, for fluid interface + */ + public function filterByUpdatedAt($updatedAt = null, $comparison = null) + { + if (is_array($updatedAt)) { + $useMinMax = false; + if (isset($updatedAt['min'])) { + $this->addUsingAlias(ColissimoLabelTableMap::UPDATED_AT, $updatedAt['min'], Criteria::GREATER_EQUAL); + $useMinMax = true; + } + if (isset($updatedAt['max'])) { + $this->addUsingAlias(ColissimoLabelTableMap::UPDATED_AT, $updatedAt['max'], Criteria::LESS_EQUAL); + $useMinMax = true; + } + if ($useMinMax) { + return $this; + } + if (null === $comparison) { + $comparison = Criteria::IN; + } + } + + return $this->addUsingAlias(ColissimoLabelTableMap::UPDATED_AT, $updatedAt, $comparison); + } + + /** + * Filter the query by a related \Thelia\Model\Order object + * + * @param \Thelia\Model\Order|ObjectCollection $order The related object(s) to use as filter + * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL + * + * @return ChildColissimoLabelQuery The current query, for fluid interface + */ + public function filterByOrder($order, $comparison = null) + { + if ($order instanceof \Thelia\Model\Order) { + return $this + ->addUsingAlias(ColissimoLabelTableMap::ORDER_ID, $order->getId(), $comparison); + } elseif ($order instanceof ObjectCollection) { + if (null === $comparison) { + $comparison = Criteria::IN; + } + + return $this + ->addUsingAlias(ColissimoLabelTableMap::ORDER_ID, $order->toKeyValue('PrimaryKey', 'Id'), $comparison); + } else { + throw new PropelException('filterByOrder() only accepts arguments of type \Thelia\Model\Order or Collection'); + } + } + + /** + * Adds a JOIN clause to the query using the Order relation + * + * @param string $relationAlias optional alias for the relation + * @param string $joinType Accepted values are null, 'left join', 'right join', 'inner join' + * + * @return ChildColissimoLabelQuery The current query, for fluid interface + */ + public function joinOrder($relationAlias = null, $joinType = Criteria::INNER_JOIN) + { + $tableMap = $this->getTableMap(); + $relationMap = $tableMap->getRelation('Order'); + + // create a ModelJoin object for this join + $join = new ModelJoin(); + $join->setJoinType($joinType); + $join->setRelationMap($relationMap, $this->useAliasInSQL ? $this->getModelAlias() : null, $relationAlias); + if ($previousJoin = $this->getPreviousJoin()) { + $join->setPreviousJoin($previousJoin); + } + + // add the ModelJoin to the current object + if ($relationAlias) { + $this->addAlias($relationAlias, $relationMap->getRightTable()->getName()); + $this->addJoinObject($join, $relationAlias); + } else { + $this->addJoinObject($join, 'Order'); + } + + return $this; + } + + /** + * Use the Order relation Order object + * + * @see useQuery() + * + * @param string $relationAlias optional alias for the relation, + * to be used as main alias in the secondary query + * @param string $joinType Accepted values are null, 'left join', 'right join', 'inner join' + * + * @return \Thelia\Model\OrderQuery A secondary query class using the current class as primary query + */ + public function useOrderQuery($relationAlias = null, $joinType = Criteria::INNER_JOIN) + { + return $this + ->joinOrder($relationAlias, $joinType) + ->useQuery($relationAlias ? $relationAlias : 'Order', '\Thelia\Model\OrderQuery'); + } + + /** + * Exclude object from result + * + * @param ChildColissimoLabel $colissimoLabel Object to remove from the list of results + * + * @return ChildColissimoLabelQuery The current query, for fluid interface + */ + public function prune($colissimoLabel = null) + { + if ($colissimoLabel) { + $this->addUsingAlias(ColissimoLabelTableMap::ID, $colissimoLabel->getId(), Criteria::NOT_EQUAL); + } + + return $this; + } + + /** + * Deletes all rows from the colissimo_label table. + * + * @param ConnectionInterface $con the connection to use + * @return int The number of affected rows (if supported by underlying database driver). + */ + public function doDeleteAll(ConnectionInterface $con = null) + { + if (null === $con) { + $con = Propel::getServiceContainer()->getWriteConnection(ColissimoLabelTableMap::DATABASE_NAME); + } + $affectedRows = 0; // initialize var to track total num of affected rows + try { + // use transaction because $criteria could contain info + // for more than one table or we could emulating ON DELETE CASCADE, etc. + $con->beginTransaction(); + $affectedRows += parent::doDeleteAll($con); + // Because this db requires some delete cascade/set null emulation, we have to + // clear the cached instance *after* the emulation has happened (since + // instances get re-added by the select statement contained therein). + ColissimoLabelTableMap::clearInstancePool(); + ColissimoLabelTableMap::clearRelatedInstancePool(); + + $con->commit(); + } catch (PropelException $e) { + $con->rollBack(); + throw $e; + } + + return $affectedRows; + } + + /** + * Performs a DELETE on the database, given a ChildColissimoLabel or Criteria object OR a primary key value. + * + * @param mixed $values Criteria or ChildColissimoLabel object or primary key or array of primary keys + * which is used to create the DELETE statement + * @param ConnectionInterface $con the connection to use + * @return int The number of affected rows (if supported by underlying database driver). This includes CASCADE-related rows + * if supported by native driver or if emulated using Propel. + * @throws PropelException Any exceptions caught during processing will be + * rethrown wrapped into a PropelException. + */ + public function delete(ConnectionInterface $con = null) + { + if (null === $con) { + $con = Propel::getServiceContainer()->getWriteConnection(ColissimoLabelTableMap::DATABASE_NAME); + } + + $criteria = $this; + + // Set the correct dbName + $criteria->setDbName(ColissimoLabelTableMap::DATABASE_NAME); + + $affectedRows = 0; // initialize var to track total num of affected rows + + try { + // use transaction because $criteria could contain info + // for more than one table or we could emulating ON DELETE CASCADE, etc. + $con->beginTransaction(); + + + ColissimoLabelTableMap::removeInstanceFromPool($criteria); + + $affectedRows += ModelCriteria::delete($con); + ColissimoLabelTableMap::clearRelatedInstancePool(); + $con->commit(); + + return $affectedRows; + } catch (PropelException $e) { + $con->rollBack(); + throw $e; + } + } + + // timestampable behavior + + /** + * Filter by the latest updated + * + * @param int $nbDays Maximum age of the latest update in days + * + * @return ChildColissimoLabelQuery The current query, for fluid interface + */ + public function recentlyUpdated($nbDays = 7) + { + return $this->addUsingAlias(ColissimoLabelTableMap::UPDATED_AT, time() - $nbDays * 24 * 60 * 60, Criteria::GREATER_EQUAL); + } + + /** + * Filter by the latest created + * + * @param int $nbDays Maximum age of in days + * + * @return ChildColissimoLabelQuery The current query, for fluid interface + */ + public function recentlyCreated($nbDays = 7) + { + return $this->addUsingAlias(ColissimoLabelTableMap::CREATED_AT, time() - $nbDays * 24 * 60 * 60, Criteria::GREATER_EQUAL); + } + + /** + * Order by update date desc + * + * @return ChildColissimoLabelQuery The current query, for fluid interface + */ + public function lastUpdatedFirst() + { + return $this->addDescendingOrderByColumn(ColissimoLabelTableMap::UPDATED_AT); + } + + /** + * Order by update date asc + * + * @return ChildColissimoLabelQuery The current query, for fluid interface + */ + public function firstUpdatedFirst() + { + return $this->addAscendingOrderByColumn(ColissimoLabelTableMap::UPDATED_AT); + } + + /** + * Order by create date desc + * + * @return ChildColissimoLabelQuery The current query, for fluid interface + */ + public function lastCreatedFirst() + { + return $this->addDescendingOrderByColumn(ColissimoLabelTableMap::CREATED_AT); + } + + /** + * Order by create date asc + * + * @return ChildColissimoLabelQuery The current query, for fluid interface + */ + public function firstCreatedFirst() + { + return $this->addAscendingOrderByColumn(ColissimoLabelTableMap::CREATED_AT); + } + +} // ColissimoLabelQuery diff --git a/local/modules/ColissimoLabel/Model/ColissimoLabel.php b/local/modules/ColissimoLabel/Model/ColissimoLabel.php new file mode 100644 index 00000000..704de5d2 --- /dev/null +++ b/local/modules/ColissimoLabel/Model/ColissimoLabel.php @@ -0,0 +1,10 @@ + array('Id', 'OrderId', 'OrderRef', 'Error', 'ErrorMessage', 'TrackingNumber', 'LabelType', 'Weight', 'Signed', 'WithCustomsInvoice', 'CreatedAt', 'UpdatedAt', ), + self::TYPE_STUDLYPHPNAME => array('id', 'orderId', 'orderRef', 'error', 'errorMessage', 'trackingNumber', 'labelType', 'weight', 'signed', 'withCustomsInvoice', 'createdAt', 'updatedAt', ), + self::TYPE_COLNAME => array(ColissimoLabelTableMap::ID, ColissimoLabelTableMap::ORDER_ID, ColissimoLabelTableMap::ORDER_REF, ColissimoLabelTableMap::ERROR, ColissimoLabelTableMap::ERROR_MESSAGE, ColissimoLabelTableMap::TRACKING_NUMBER, ColissimoLabelTableMap::LABEL_TYPE, ColissimoLabelTableMap::WEIGHT, ColissimoLabelTableMap::SIGNED, ColissimoLabelTableMap::WITH_CUSTOMS_INVOICE, ColissimoLabelTableMap::CREATED_AT, ColissimoLabelTableMap::UPDATED_AT, ), + self::TYPE_RAW_COLNAME => array('ID', 'ORDER_ID', 'ORDER_REF', 'ERROR', 'ERROR_MESSAGE', 'TRACKING_NUMBER', 'LABEL_TYPE', 'WEIGHT', 'SIGNED', 'WITH_CUSTOMS_INVOICE', 'CREATED_AT', 'UPDATED_AT', ), + self::TYPE_FIELDNAME => array('id', 'order_id', 'order_ref', 'error', 'error_message', 'tracking_number', 'label_type', 'weight', 'signed', 'with_customs_invoice', 'created_at', 'updated_at', ), + self::TYPE_NUM => array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ) + ); + + /** + * holds an array of keys for quick access to the fieldnames array + * + * first dimension keys are the type constants + * e.g. self::$fieldKeys[self::TYPE_PHPNAME]['Id'] = 0 + */ + protected static $fieldKeys = array ( + self::TYPE_PHPNAME => array('Id' => 0, 'OrderId' => 1, 'OrderRef' => 2, 'Error' => 3, 'ErrorMessage' => 4, 'TrackingNumber' => 5, 'LabelType' => 6, 'Weight' => 7, 'Signed' => 8, 'WithCustomsInvoice' => 9, 'CreatedAt' => 10, 'UpdatedAt' => 11, ), + self::TYPE_STUDLYPHPNAME => array('id' => 0, 'orderId' => 1, 'orderRef' => 2, 'error' => 3, 'errorMessage' => 4, 'trackingNumber' => 5, 'labelType' => 6, 'weight' => 7, 'signed' => 8, 'withCustomsInvoice' => 9, 'createdAt' => 10, 'updatedAt' => 11, ), + self::TYPE_COLNAME => array(ColissimoLabelTableMap::ID => 0, ColissimoLabelTableMap::ORDER_ID => 1, ColissimoLabelTableMap::ORDER_REF => 2, ColissimoLabelTableMap::ERROR => 3, ColissimoLabelTableMap::ERROR_MESSAGE => 4, ColissimoLabelTableMap::TRACKING_NUMBER => 5, ColissimoLabelTableMap::LABEL_TYPE => 6, ColissimoLabelTableMap::WEIGHT => 7, ColissimoLabelTableMap::SIGNED => 8, ColissimoLabelTableMap::WITH_CUSTOMS_INVOICE => 9, ColissimoLabelTableMap::CREATED_AT => 10, ColissimoLabelTableMap::UPDATED_AT => 11, ), + self::TYPE_RAW_COLNAME => array('ID' => 0, 'ORDER_ID' => 1, 'ORDER_REF' => 2, 'ERROR' => 3, 'ERROR_MESSAGE' => 4, 'TRACKING_NUMBER' => 5, 'LABEL_TYPE' => 6, 'WEIGHT' => 7, 'SIGNED' => 8, 'WITH_CUSTOMS_INVOICE' => 9, 'CREATED_AT' => 10, 'UPDATED_AT' => 11, ), + self::TYPE_FIELDNAME => array('id' => 0, 'order_id' => 1, 'order_ref' => 2, 'error' => 3, 'error_message' => 4, 'tracking_number' => 5, 'label_type' => 6, 'weight' => 7, 'signed' => 8, 'with_customs_invoice' => 9, 'created_at' => 10, 'updated_at' => 11, ), + self::TYPE_NUM => array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, ) + ); + + /** + * Initialize the table attributes and columns + * Relations are not initialized by this method since they are lazy loaded + * + * @return void + * @throws PropelException + */ + public function initialize() + { + // attributes + $this->setName('colissimo_label'); + $this->setPhpName('ColissimoLabel'); + $this->setClassName('\\ColissimoLabel\\Model\\ColissimoLabel'); + $this->setPackage('ColissimoLabel.Model'); + $this->setUseIdGenerator(true); + // columns + $this->addPrimaryKey('ID', 'Id', 'INTEGER', true, null, null); + $this->addForeignKey('ORDER_ID', 'OrderId', 'INTEGER', 'order', 'ID', true, null, null); + $this->addColumn('ORDER_REF', 'OrderRef', 'VARCHAR', true, 255, null); + $this->addColumn('ERROR', 'Error', 'BOOLEAN', true, 1, false); + $this->addColumn('ERROR_MESSAGE', 'ErrorMessage', 'VARCHAR', false, 255, ''); + $this->addColumn('TRACKING_NUMBER', 'TrackingNumber', 'VARCHAR', false, 255, null); + $this->addColumn('LABEL_TYPE', 'LabelType', 'VARCHAR', false, 4, null); + $this->addColumn('WEIGHT', 'Weight', 'DECIMAL', false, 6, 0); + $this->addColumn('SIGNED', 'Signed', 'BOOLEAN', true, 1, false); + $this->addColumn('WITH_CUSTOMS_INVOICE', 'WithCustomsInvoice', 'BOOLEAN', true, 1, false); + $this->addColumn('CREATED_AT', 'CreatedAt', 'TIMESTAMP', false, null, null); + $this->addColumn('UPDATED_AT', 'UpdatedAt', 'TIMESTAMP', false, null, null); + } // initialize() + + /** + * Build the RelationMap objects for this table relationships + */ + public function buildRelations() + { + $this->addRelation('Order', '\\Thelia\\Model\\Order', RelationMap::MANY_TO_ONE, array('order_id' => 'id', ), 'CASCADE', 'RESTRICT'); + } // buildRelations() + + /** + * + * Gets the list of behaviors registered for this table + * + * @return array Associative array (name => parameters) of behaviors + */ + public function getBehaviors() + { + return array( + 'timestampable' => array('create_column' => 'created_at', 'update_column' => 'updated_at', ), + ); + } // getBehaviors() + + /** + * Retrieves a string version of the primary key from the DB resultset row that can be used to uniquely identify a row in this table. + * + * For tables with a single-column primary key, that simple pkey value will be returned. For tables with + * a multi-column primary key, a serialize()d version of the primary key will be returned. + * + * @param array $row resultset row. + * @param int $offset The 0-based offset for reading from the resultset row. + * @param string $indexType One of the class type constants TableMap::TYPE_PHPNAME, TableMap::TYPE_STUDLYPHPNAME + * TableMap::TYPE_COLNAME, TableMap::TYPE_FIELDNAME, TableMap::TYPE_NUM + */ + public static function getPrimaryKeyHashFromRow($row, $offset = 0, $indexType = TableMap::TYPE_NUM) + { + // If the PK cannot be derived from the row, return NULL. + if ($row[TableMap::TYPE_NUM == $indexType ? 0 + $offset : static::translateFieldName('Id', TableMap::TYPE_PHPNAME, $indexType)] === null) { + return null; + } + + return (string) $row[TableMap::TYPE_NUM == $indexType ? 0 + $offset : static::translateFieldName('Id', TableMap::TYPE_PHPNAME, $indexType)]; + } + + /** + * Retrieves the primary key from the DB resultset row + * For tables with a single-column primary key, that simple pkey value will be returned. For tables with + * a multi-column primary key, an array of the primary key columns will be returned. + * + * @param array $row resultset row. + * @param int $offset The 0-based offset for reading from the resultset row. + * @param string $indexType One of the class type constants TableMap::TYPE_PHPNAME, TableMap::TYPE_STUDLYPHPNAME + * TableMap::TYPE_COLNAME, TableMap::TYPE_FIELDNAME, TableMap::TYPE_NUM + * + * @return mixed The primary key of the row + */ + public static function getPrimaryKeyFromRow($row, $offset = 0, $indexType = TableMap::TYPE_NUM) + { + + return (int) $row[ + $indexType == TableMap::TYPE_NUM + ? 0 + $offset + : self::translateFieldName('Id', TableMap::TYPE_PHPNAME, $indexType) + ]; + } + + /** + * The class that the tableMap will make instances of. + * + * If $withPrefix is true, the returned path + * uses a dot-path notation which is translated into a path + * relative to a location on the PHP include_path. + * (e.g. path.to.MyClass -> 'path/to/MyClass.php') + * + * @param boolean $withPrefix Whether or not to return the path with the class name + * @return string path.to.ClassName + */ + public static function getOMClass($withPrefix = true) + { + return $withPrefix ? ColissimoLabelTableMap::CLASS_DEFAULT : ColissimoLabelTableMap::OM_CLASS; + } + + /** + * Populates an object of the default type or an object that inherit from the default. + * + * @param array $row row returned by DataFetcher->fetch(). + * @param int $offset The 0-based offset for reading from the resultset row. + * @param string $indexType The index type of $row. Mostly DataFetcher->getIndexType(). + One of the class type constants TableMap::TYPE_PHPNAME, TableMap::TYPE_STUDLYPHPNAME + * TableMap::TYPE_COLNAME, TableMap::TYPE_FIELDNAME, TableMap::TYPE_NUM. + * + * @throws PropelException Any exceptions caught during processing will be + * rethrown wrapped into a PropelException. + * @return array (ColissimoLabel object, last column rank) + */ + public static function populateObject($row, $offset = 0, $indexType = TableMap::TYPE_NUM) + { + $key = ColissimoLabelTableMap::getPrimaryKeyHashFromRow($row, $offset, $indexType); + if (null !== ($obj = ColissimoLabelTableMap::getInstanceFromPool($key))) { + // We no longer rehydrate the object, since this can cause data loss. + // See http://www.propelorm.org/ticket/509 + // $obj->hydrate($row, $offset, true); // rehydrate + $col = $offset + ColissimoLabelTableMap::NUM_HYDRATE_COLUMNS; + } else { + $cls = ColissimoLabelTableMap::OM_CLASS; + $obj = new $cls(); + $col = $obj->hydrate($row, $offset, false, $indexType); + ColissimoLabelTableMap::addInstanceToPool($obj, $key); + } + + return array($obj, $col); + } + + /** + * The returned array will contain objects of the default type or + * objects that inherit from the default. + * + * @param DataFetcherInterface $dataFetcher + * @return array + * @throws PropelException Any exceptions caught during processing will be + * rethrown wrapped into a PropelException. + */ + public static function populateObjects(DataFetcherInterface $dataFetcher) + { + $results = array(); + + // set the class once to avoid overhead in the loop + $cls = static::getOMClass(false); + // populate the object(s) + while ($row = $dataFetcher->fetch()) { + $key = ColissimoLabelTableMap::getPrimaryKeyHashFromRow($row, 0, $dataFetcher->getIndexType()); + if (null !== ($obj = ColissimoLabelTableMap::getInstanceFromPool($key))) { + // We no longer rehydrate the object, since this can cause data loss. + // See http://www.propelorm.org/ticket/509 + // $obj->hydrate($row, 0, true); // rehydrate + $results[] = $obj; + } else { + $obj = new $cls(); + $obj->hydrate($row); + $results[] = $obj; + ColissimoLabelTableMap::addInstanceToPool($obj, $key); + } // if key exists + } + + return $results; + } + /** + * Add all the columns needed to create a new object. + * + * Note: any columns that were marked with lazyLoad="true" in the + * XML schema will not be added to the select list and only loaded + * on demand. + * + * @param Criteria $criteria object containing the columns to add. + * @param string $alias optional table alias + * @throws PropelException Any exceptions caught during processing will be + * rethrown wrapped into a PropelException. + */ + public static function addSelectColumns(Criteria $criteria, $alias = null) + { + if (null === $alias) { + $criteria->addSelectColumn(ColissimoLabelTableMap::ID); + $criteria->addSelectColumn(ColissimoLabelTableMap::ORDER_ID); + $criteria->addSelectColumn(ColissimoLabelTableMap::ORDER_REF); + $criteria->addSelectColumn(ColissimoLabelTableMap::ERROR); + $criteria->addSelectColumn(ColissimoLabelTableMap::ERROR_MESSAGE); + $criteria->addSelectColumn(ColissimoLabelTableMap::TRACKING_NUMBER); + $criteria->addSelectColumn(ColissimoLabelTableMap::LABEL_TYPE); + $criteria->addSelectColumn(ColissimoLabelTableMap::WEIGHT); + $criteria->addSelectColumn(ColissimoLabelTableMap::SIGNED); + $criteria->addSelectColumn(ColissimoLabelTableMap::WITH_CUSTOMS_INVOICE); + $criteria->addSelectColumn(ColissimoLabelTableMap::CREATED_AT); + $criteria->addSelectColumn(ColissimoLabelTableMap::UPDATED_AT); + } else { + $criteria->addSelectColumn($alias . '.ID'); + $criteria->addSelectColumn($alias . '.ORDER_ID'); + $criteria->addSelectColumn($alias . '.ORDER_REF'); + $criteria->addSelectColumn($alias . '.ERROR'); + $criteria->addSelectColumn($alias . '.ERROR_MESSAGE'); + $criteria->addSelectColumn($alias . '.TRACKING_NUMBER'); + $criteria->addSelectColumn($alias . '.LABEL_TYPE'); + $criteria->addSelectColumn($alias . '.WEIGHT'); + $criteria->addSelectColumn($alias . '.SIGNED'); + $criteria->addSelectColumn($alias . '.WITH_CUSTOMS_INVOICE'); + $criteria->addSelectColumn($alias . '.CREATED_AT'); + $criteria->addSelectColumn($alias . '.UPDATED_AT'); + } + } + + /** + * Returns the TableMap related to this object. + * This method is not needed for general use but a specific application could have a need. + * @return TableMap + * @throws PropelException Any exceptions caught during processing will be + * rethrown wrapped into a PropelException. + */ + public static function getTableMap() + { + return Propel::getServiceContainer()->getDatabaseMap(ColissimoLabelTableMap::DATABASE_NAME)->getTable(ColissimoLabelTableMap::TABLE_NAME); + } + + /** + * Add a TableMap instance to the database for this tableMap class. + */ + public static function buildTableMap() + { + $dbMap = Propel::getServiceContainer()->getDatabaseMap(ColissimoLabelTableMap::DATABASE_NAME); + if (!$dbMap->hasTable(ColissimoLabelTableMap::TABLE_NAME)) { + $dbMap->addTableObject(new ColissimoLabelTableMap()); + } + } + + /** + * Performs a DELETE on the database, given a ColissimoLabel or Criteria object OR a primary key value. + * + * @param mixed $values Criteria or ColissimoLabel object or primary key or array of primary keys + * which is used to create the DELETE statement + * @param ConnectionInterface $con the connection to use + * @return int The number of affected rows (if supported by underlying database driver). This includes CASCADE-related rows + * if supported by native driver or if emulated using Propel. + * @throws PropelException Any exceptions caught during processing will be + * rethrown wrapped into a PropelException. + */ + public static function doDelete($values, ConnectionInterface $con = null) + { + if (null === $con) { + $con = Propel::getServiceContainer()->getWriteConnection(ColissimoLabelTableMap::DATABASE_NAME); + } + + if ($values instanceof Criteria) { + // rename for clarity + $criteria = $values; + } elseif ($values instanceof \ColissimoLabel\Model\ColissimoLabel) { // it's a model object + // create criteria based on pk values + $criteria = $values->buildPkeyCriteria(); + } else { // it's a primary key, or an array of pks + $criteria = new Criteria(ColissimoLabelTableMap::DATABASE_NAME); + $criteria->add(ColissimoLabelTableMap::ID, (array) $values, Criteria::IN); + } + + $query = ColissimoLabelQuery::create()->mergeWith($criteria); + + if ($values instanceof Criteria) { ColissimoLabelTableMap::clearInstancePool(); + } elseif (!is_object($values)) { // it's a primary key, or an array of pks + foreach ((array) $values as $singleval) { ColissimoLabelTableMap::removeInstanceFromPool($singleval); + } + } + + return $query->delete($con); + } + + /** + * Deletes all rows from the colissimo_label table. + * + * @param ConnectionInterface $con the connection to use + * @return int The number of affected rows (if supported by underlying database driver). + */ + public static function doDeleteAll(ConnectionInterface $con = null) + { + return ColissimoLabelQuery::create()->doDeleteAll($con); + } + + /** + * Performs an INSERT on the database, given a ColissimoLabel or Criteria object. + * + * @param mixed $criteria Criteria or ColissimoLabel object containing data that is used to create the INSERT statement. + * @param ConnectionInterface $con the ConnectionInterface connection to use + * @return mixed The new primary key. + * @throws PropelException Any exceptions caught during processing will be + * rethrown wrapped into a PropelException. + */ + public static function doInsert($criteria, ConnectionInterface $con = null) + { + if (null === $con) { + $con = Propel::getServiceContainer()->getWriteConnection(ColissimoLabelTableMap::DATABASE_NAME); + } + + if ($criteria instanceof Criteria) { + $criteria = clone $criteria; // rename for clarity + } else { + $criteria = $criteria->buildCriteria(); // build Criteria from ColissimoLabel object + } + + if ($criteria->containsKey(ColissimoLabelTableMap::ID) && $criteria->keyContainsValue(ColissimoLabelTableMap::ID) ) { + throw new PropelException('Cannot insert a value for auto-increment primary key ('.ColissimoLabelTableMap::ID.')'); + } + + + // Set the correct dbName + $query = ColissimoLabelQuery::create()->mergeWith($criteria); + + try { + // use transaction because $criteria could contain info + // for more than one table (I guess, conceivably) + $con->beginTransaction(); + $pk = $query->doInsert($con); + $con->commit(); + } catch (PropelException $e) { + $con->rollBack(); + throw $e; + } + + return $pk; + } + +} // ColissimoLabelTableMap +// This is the static code needed to register the TableMap for this table with the main Propel class. +// +ColissimoLabelTableMap::buildTableMap(); diff --git a/local/modules/ColissimoLabel/Readme.md b/local/modules/ColissimoLabel/Readme.md new file mode 100644 index 00000000..c8746d69 --- /dev/null +++ b/local/modules/ColissimoLabel/Readme.md @@ -0,0 +1,84 @@ +# ColissimoLabel + +Allows you to generate labels for orders passed through SoColissimo and ColissimoWs. + +## Installation + +### Manually + +* Copy the module into ```/local/modules/``` directory and be sure that the name of the module is ReadmeTest. +* Activate it in your thelia administration panel + +### Composer + +Add it in your main thelia composer.json file + +``` +composer require thelia/colissimo-label-module:~1.0.0 +``` + +## Usage + +Activating the module will add a button "ColissimoLabel" tor your left toolbar. Clicking it will +redirect you to the module page, which has 3 tabs. + +- Bordereau tab : Allows you to generate a bordereau for every label generated since the last time you made a bordereau +- Label tab : Shows you the list of not sent orders, allowing you to generate labels for them, or to view ones that already exists +- Configuration tab : Lets you configure your module + +The module also includes a new part to the delivery tab of the order edit page, allowing you to see every label +created for this order, as well as create new ones. + +## Hook + + - order.edit-js : This hook is used to add a label list and label generation interface + to the order edit page. + + - main.in-top-menu-items : Adds a button that redirects to the module page, in the left toolbar + +## Loop + +If your module declare one or more loop, describe them here like this : + +[colissimolabel.label-info] + +### Input arguments + +|Argument |Description | +|--- |--- | +|**order_id** | An order ID | + +### Output arguments + +|Variable |Description | +|--- |--- | +|$ORDER_ID | The order ID | +|$HAS_ERROR | (bool) Whether an error occured during the label generation or not | +|$ERROR_MESSAGE | The error message | +|$WEIGHT | The weight indicated on the label | +|$SIGNED | (bool) Whether the label is a signed one or not | +|$TRACKING_NUMBER | The order tracking number | +|$HAS_LABEL | (bool) Whether the order has a label or not | +|$LABEL_TYPE | The file extension of the label | +|$HAS_CUSTOMS_INVOICE | (bool) Whether a customs invoice was created or not | +|$LABEL_URL | The URL from which to download the URL | +|$CUSTOMS_INVOICE_URL | The URL from which to download the customs invoice | +|$CLEAR_LABEL_URL | The URL from which to delete the label | +|$CAN_BE_NOT_SIGNED | (bool) Whether the order HAS to be signed or not | +|$ORDER_DATE | The order date | + +[colissimolabel.orders-not-sent] + +### Input arguments + +|Argument |Description | +|--- |--- | +|**with_prev_next_info** | See Thelia documentation | + +### Output arguments + +Same as an order loop, but only order that weren't sent or cancelled and that are paid for will be searched for. + +## Other ? + +If you have other think to put, feel free to complete your readme as you want. diff --git a/local/modules/ColissimoLabel/Request/AbstractLabelRequest.php b/local/modules/ColissimoLabel/Request/AbstractLabelRequest.php new file mode 100644 index 00000000..afe35aaf --- /dev/null +++ b/local/modules/ColissimoLabel/Request/AbstractLabelRequest.php @@ -0,0 +1,132 @@ +gilles.bourgeat@gmail.com> + */ +abstract class AbstractLabelRequest extends AbstractRequest +{ + /** @var OutputFormat|null */ + private $outputFormat; + + /** @var Letter */ + private $letter; + + /** + * @return OutputFormat|null + */ + public function getOutputFormat() + { + return $this->outputFormat; + } + + /** + * @param OutputFormat $outputFormat + * @return self + */ + protected function setOutputFormat(OutputFormat $outputFormat) + { + $this->outputFormat = $outputFormat; + return $this; + } + + /** + * @return Letter + */ + public function getLetter() + { + return $this->letter; + } + + /** + * @param Letter $letter + * @return self + */ + protected function setLetter(Letter $letter) + { + $this->letter = $letter; + return $this; + } + + /** + * @inheritdoc + */ + public function generateArrayRequest() + { + return array_merge_recursive(parent::generateArrayRequest(), [ + 'outputFormat' => [ + 'x' => $this->getOutputFormat()->getX(), + 'y' => $this->getOutputFormat()->getY(), + 'outputPrintingType' => $this->getOutputFormat()->getOutputPrintingType() + ], + 'letter' => [ + 'service' => [ + 'productCode' => $this->getLetter()->getService()->getProductCode(), + 'depositDate' => $this->getLetter()->getService()->getDepositDate()->format('Y-m-d'), + 'transportationAmount' => $this->getLetter()->getService()->getTransportationAmount(), + 'totalAmount' => $this->getLetter()->getService()->getTransportationAmount(), + 'orderNumber' => $this->getLetter()->getService()->getOrderNumber(), + 'commercialName' => $this->getLetter()->getService()->getCommercialName(), + 'returnTypeChoice' => $this->getLetter()->getService()->getReturnTypeChoice(), + ], + 'parcel' => [ + 'weight' => $this->getLetter()->getParcel()->getWeight(), + 'pickupLocationId' => $this->getLetter()->getParcel()->getPickupLocationId() + ], + 'customsDeclarations' => [ + 'includeCustomsDeclarations' => $this->getLetter()->getCustomsDeclarations()->getIncludeCustomsDeclarations(), + 'contents' => [ + 'article' => 'falseArticle', + 'category' => [ + 'value' => $this->getLetter()->getCustomsDeclarations()->getCategory(), + ] + ] + + ], + 'sender' => [ + 'senderParcelRef' => $this->getLetter()->getSender()->getSenderParcelRef(), + 'address' => [ + 'companyName' => $this->getLetter()->getSender()->getAddress()->getCompanyName(), + 'lastName' => $this->getLetter()->getSender()->getAddress()->getLastName(), + 'firstName' => $this->getLetter()->getSender()->getAddress()->getFirstName(), + 'line0' => $this->getLetter()->getSender()->getAddress()->getLine0(), + 'line1' => $this->getLetter()->getSender()->getAddress()->getLine1(), + 'line2' => $this->getLetter()->getSender()->getAddress()->getLine2(), + 'line3' => $this->getLetter()->getSender()->getAddress()->getLine3(), + 'countryCode' => $this->getLetter()->getSender()->getAddress()->getCountryCode(), + 'city' => $this->getLetter()->getSender()->getAddress()->getCity(), + 'zipCode' => $this->getLetter()->getSender()->getAddress()->getZipCode(), + 'phoneNumber' => $this->getLetter()->getSender()->getAddress()->getPhoneNumber(), + 'mobileNumber' => $this->getLetter()->getSender()->getAddress()->getMobileNumber(), + 'email'=> $this->getLetter()->getSender()->getAddress()->getEmail(), + 'language' => $this->getLetter()->getSender()->getAddress()->getLanguage() + ] + ], + 'addressee' => [ + 'addresseeParcelRef' => $this->getLetter()->getAddressee()->getAddresseeParcelRef(), + 'address' => [ + 'companyName' => ColissimoLabel::removeAccents($this->getLetter()->getAddressee()->getAddress()->getCompanyName()), + 'lastName' => ColissimoLabel::removeAccents($this->getLetter()->getAddressee()->getAddress()->getLastName()), + 'firstName' => ColissimoLabel::removeAccents($this->getLetter()->getAddressee()->getAddress()->getFirstName()), + 'line0' => ColissimoLabel::removeAccents($this->getLetter()->getAddressee()->getAddress()->getLine0()), + 'line1' => ColissimoLabel::removeAccents($this->getLetter()->getAddressee()->getAddress()->getLine1()), + 'line2' => ColissimoLabel::removeAccents($this->getLetter()->getAddressee()->getAddress()->getLine2()), + 'line3' => ColissimoLabel::removeAccents($this->getLetter()->getAddressee()->getAddress()->getLine3()), + 'countryCode' => $this->getLetter()->getAddressee()->getAddress()->getCountryCode(), + 'city' => ColissimoLabel::removeAccents($this->getLetter()->getAddressee()->getAddress()->getCity()), + 'zipCode' => $this->getLetter()->getAddressee()->getAddress()->getZipCode(), + 'phoneNumber' => $this->getLetter()->getAddressee()->getAddress()->getPhoneNumber(), + 'mobileNumber' => $this->getLetter()->getAddressee()->getAddress()->getMobileNumber(), + 'email'=> $this->getLetter()->getAddressee()->getAddress()->getEmail(), + 'language' => $this->getLetter()->getAddressee()->getAddress()->getLanguage() + ] + ], + ] + ]); + } +} diff --git a/local/modules/ColissimoLabel/Request/AbstractRequest.php b/local/modules/ColissimoLabel/Request/AbstractRequest.php new file mode 100644 index 00000000..e03ccb0a --- /dev/null +++ b/local/modules/ColissimoLabel/Request/AbstractRequest.php @@ -0,0 +1,57 @@ +gilles.bourgeat@gmail.com> + */ +abstract class AbstractRequest +{ + protected $contractNumber = ''; + + protected $password = ''; + + /** + * @return string + */ + public function getContractNumber() + { + return $this->contractNumber; + } + + /** + * @param string $contractNumber + * @return self + */ + public function setContractNumber($contractNumber) + { + $this->contractNumber = $contractNumber; + return $this; + } + + /** + * @return string + */ + public function getPassword() + { + return $this->password; + } + + /** + * @param string $password + * @return self + */ + public function setPassword($password) + { + $this->password = $password; + return $this; + } + + public function generateArrayRequest() + { + return [ + 'contractNumber' => $this->getContractNumber(), + 'password' => $this->getPassword() + ]; + } +} diff --git a/local/modules/ColissimoLabel/Request/Helper/APIConfiguration.php b/local/modules/ColissimoLabel/Request/Helper/APIConfiguration.php new file mode 100644 index 00000000..91fd484d --- /dev/null +++ b/local/modules/ColissimoLabel/Request/Helper/APIConfiguration.php @@ -0,0 +1,119 @@ +gilles.bourgeat@gmail.com> + */ +abstract class APIConfiguration +{ + protected $contractNumber = ''; + + protected $password = ''; + + protected $version = '2.0'; + + protected $wsdl = ''; + + protected $method = ''; + + public function __construct() + { + $this->setContractNumber(ColissimoLabel::getConfigValue(ColissimoLabel::CONFIG_KEY_CONTRACT_NUMBER)); + $this->setPassword(ColissimoLabel::getConfigValue(ColissimoLabel::CONFIG_KEY_PASSWORD)); + $this->setWsdl(ColissimoLabel::getConfigValue(ColissimoLabel::CONFIG_KEY_ENDPOINT)); + } + + /** + * @return string + */ + public function getContractNumber() + { + return $this->contractNumber; + } + + /** + * @param string $contractNumber + * @return self + */ + public function setContractNumber($contractNumber) + { + $this->contractNumber = $contractNumber; + return $this; + } + + /** + * @return string + */ + public function getPassword() + { + return $this->password; + } + + /** + * @param string $password + * @return self + */ + public function setPassword($password) + { + $this->password = $password; + return $this; + } + + /** + * @return string + */ + public function getVersion() + { + return $this->version; + } + + /** + * @param string $version + * @return self + */ + public function setVersion($version) + { + $this->version = $version; + return $this; + } + + /** + * @return string + */ + public function getWsdl() + { + return $this->wsdl; + } + + /** + * @param string $wsdl + * @return self + */ + public function setWsdl($wsdl) + { + $this->wsdl = $wsdl; + return $this; + } + + /** + * @return string + */ + public function getMethod() + { + return $this->method; + } + + /** + * @param string $method + * @return self + */ + public function setMethod($method) + { + $this->method = $method; + return $this; + } +} diff --git a/local/modules/ColissimoLabel/Request/Helper/Address.php b/local/modules/ColissimoLabel/Request/Helper/Address.php new file mode 100644 index 00000000..acc16ae6 --- /dev/null +++ b/local/modules/ColissimoLabel/Request/Helper/Address.php @@ -0,0 +1,289 @@ +gilles.bourgeat@gmail.com> + */ +class Address +{ + protected $companyName =''; + + protected $lastName = ''; + + protected $firstName = ''; + + protected $line0 = ''; + + protected $line1 = ''; + + protected $line2 = ''; + + protected $line3 = ''; + + protected $countryCode = ''; + + protected $city = ''; + + protected $zipCode = ''; + + protected $phoneNumber = ''; + + protected $mobileNumber = ''; + + protected $email = ''; + + protected $language = ''; + + /** + * @return string + */ + public function getLanguage() + { + return $this->language; + } + + /** + * @param string $language + * @return Address + */ + public function setLanguage($language) + { + $this->language = $language; + return $this; + } + + /** + * @return string + */ + public function getPhoneNumber() + { + return $this->phoneNumber; + } + + /** + * @param string $phoneNumber + * @return Address + */ + public function setPhoneNumber($phoneNumber) + { + $this->phoneNumber = $phoneNumber; + return $this; + } + + /** + * @return string + */ + public function getMobileNumber() + { + return $this->mobileNumber; + } + + /** + * @param string $mobileNumber + * @return Address + */ + public function setMobileNumber($mobileNumber) + { + $this->mobileNumber = $mobileNumber; + return $this; + } + + /** + * @return string + */ + public function getEmail() + { + return $this->email; + } + + /** + * @param string $email + * @return Address + */ + public function setEmail($email) + { + $this->email = $email; + return $this; + } + + /** + * @return string + */ + public function getCompanyName() + { + return $this->companyName; + } + + /** + * @param string $companyName + * @return self + */ + public function setCompanyName($companyName) + { + $this->companyName = $companyName; + return $this; + } + + /** + * @return string + */ + public function getLastName() + { + return $this->lastName; + } + + /** + * @param string $lastName + * @return self + */ + public function setLastName($lastName) + { + $this->lastName = $lastName; + return $this; + } + + /** + * @return string + */ + public function getFirstName() + { + return $this->firstName; + } + + /** + * @param string $firstName + * @return self + */ + public function setFirstName($firstName) + { + $this->firstName = $firstName; + return $this; + } + + /** + * @return string + */ + public function getLine0() + { + return $this->line0; + } + + /** + * @param string $line0 + * @return self + */ + public function setLine0($line0) + { + $this->line0 = $line0; + return $this; + } + + /** + * @return string + */ + public function getLine1() + { + return $this->line1; + } + + /** + * @param string $line1 + * @return self + */ + public function setLine1($line1) + { + $this->line1 = $line1; + return $this; + } + + /** + * @return string + */ + public function getLine2() + { + return $this->line2; + } + + /** + * @param string $line2 + * @return self + */ + public function setLine2($line2) + { + $this->line2 = $line2; + return $this; + } + + /** + * @return string + */ + public function getLine3() + { + return $this->line3; + } + + /** + * @param string $line3 + * @return self + */ + public function setLine3($line3) + { + $this->line3 = $line3; + return $this; + } + + /** + * @return string + */ + public function getCountryCode() + { + return $this->countryCode; + } + + /** + * @param string $countryCode + * @return self + */ + public function setCountryCode($countryCode) + { + $this->countryCode = $countryCode; + return $this; + } + + /** + * @return string + */ + public function getCity() + { + return $this->city; + } + + /** + * @param string $city + * @return self + */ + public function setCity($city) + { + $this->city = $city; + return $this; + } + + /** + * @return string + */ + public function getZipCode() + { + return $this->zipCode; + } + + /** + * @param string $zipCode + * @return self + */ + public function setZipCode($zipCode) + { + $this->zipCode = $zipCode; + return $this; + } +} diff --git a/local/modules/ColissimoLabel/Request/Helper/Addressee.php b/local/modules/ColissimoLabel/Request/Helper/Addressee.php new file mode 100644 index 00000000..d249ba0f --- /dev/null +++ b/local/modules/ColissimoLabel/Request/Helper/Addressee.php @@ -0,0 +1,44 @@ +gilles.bourgeat@gmail.com> + */ +class Addressee +{ + /** @var string */ + protected $addresseeParcelRef; + + /** @var Address */ + protected $address; + + public function __construct(Address $address) + { + $this->address = $address; + } + + /** + * @return string + */ + public function getAddresseeParcelRef() + { + return $this->addresseeParcelRef; + } + + /** + * @param string $addresseeParcelRef + */ + public function setAddresseeParcelRef($addresseeParcelRef) + { + $this->addresseeParcelRef = $addresseeParcelRef; + } + + /** + * @return Address + */ + public function getAddress() + { + return $this->address; + } +} diff --git a/local/modules/ColissimoLabel/Request/Helper/Article.php b/local/modules/ColissimoLabel/Request/Helper/Article.php new file mode 100644 index 00000000..ec2bd741 --- /dev/null +++ b/local/modules/ColissimoLabel/Request/Helper/Article.php @@ -0,0 +1,161 @@ +description = $description; + $this->quantity = $quantity; + $this->weight = (float) $weight; + $this->value = (float) $value; + $this->hsCode = $hsCode; + $this->currency = $currency; + } + + /** + * @return string + */ + public function getDescription() + { + return \Transliterator::create('NFD; [:Nonspacing Mark:] Remove; NFC')->transliterate($this->description); + } + + /** + * @param $description + * @return $this + */ + public function setDescription($description) + { + $this->description = $description; + return $this; + } + + /** + * @return int + */ + public function getQuantity() + { + return $this->quantity; + } + + /** + * @param $quantity + * @return $this + */ + public function setQuantity($quantity) + { + $this->quantity = $quantity; + return $this; + } + + /** + * @return float|int + */ + public function getWeight() + { + return $this->weight; + } + + /** + * @param float|int $weight + * @return self + */ + public function setWeight($weight) + { + $this->weight = $weight; + return $this; + } + + /** + * @return float|int + */ + public function getValue() + { + return $this->value; + } + + /** + * @param float|int $value + * @return $this + */ + public function setValue($value) + { + $this->value = $value; + return $this; + } + + /** + * @return string + */ + public function getHsCode() + { + return $this->hsCode; + } + + /** + * @param $hsCode + * @return $this + */ + public function setHsCode($hsCode) + { + $this->hsCode = $hsCode; + return $this; + } + + /** + * @return string + */ + public function getOriginCountry() { + return CountryQuery::create()->findOneById(ColissimoLabel::getConfigValue(ColissimoLabel::CONFIG_KEY_FROM_COUNTRY))->getIsoalpha2(); + } + + /** + * @param $currency + * @return $this + */ + public function setCurrency($currency) + { + $this->currency = $currency; + return $this; + } + + /** + * @return string + */ + public function getCurrency() { + return $this->currency; + } +} \ No newline at end of file diff --git a/local/modules/ColissimoLabel/Request/Helper/BordereauRequestAPIConfiguration.php b/local/modules/ColissimoLabel/Request/Helper/BordereauRequestAPIConfiguration.php new file mode 100644 index 00000000..393e53d8 --- /dev/null +++ b/local/modules/ColissimoLabel/Request/Helper/BordereauRequestAPIConfiguration.php @@ -0,0 +1,16 @@ +gilles.bourgeat@gmail.com> + */ +class BordereauRequestAPIConfiguration extends APIConfiguration +{ + public function __construct() + { + parent::__construct(); + + $this->setMethod('generateBordereauByParcelsNumbers'); + } +} diff --git a/local/modules/ColissimoLabel/Request/Helper/CustomsDeclarations.php b/local/modules/ColissimoLabel/Request/Helper/CustomsDeclarations.php new file mode 100644 index 00000000..cc4839b5 --- /dev/null +++ b/local/modules/ColissimoLabel/Request/Helper/CustomsDeclarations.php @@ -0,0 +1,78 @@ +includeCustomsDeclarations = $includeCustomsDeclarations; + $this->category = $category; + $this->articles = $articles; + } + + /** + * @return bool|string + */ + public function getIncludeCustomsDeclarations() + { + if (!$this->includeCustomsDeclarations) { + return 'false'; + } + return $this->includeCustomsDeclarations; + } + + /** + * @param $includeCustomsDeclarations + * @return $this + */ + public function setIncludeCustomsDeclarations($includeCustomsDeclarations) + { + $this->includeCustomsDeclarations = $includeCustomsDeclarations; + return $this; + } + + /** + * @return int + */ + public function getCategory() + { + return $this->category; + } + + /** + * @param $category + * @return $this + */ + public function setCategory($category) + { + $this->category = $category; + return $this; + } + + /** + * @return array + */ + public function getArticles() + { + return $this->articles; + } + + /** + * @param $articles + * @return $this + */ + public function setArticles($articles) + { + $this->articles[] = $articles; + return $this; + } +} \ No newline at end of file diff --git a/local/modules/ColissimoLabel/Request/Helper/LabelRequestAPIConfiguration.php b/local/modules/ColissimoLabel/Request/Helper/LabelRequestAPIConfiguration.php new file mode 100644 index 00000000..d5001289 --- /dev/null +++ b/local/modules/ColissimoLabel/Request/Helper/LabelRequestAPIConfiguration.php @@ -0,0 +1,16 @@ +gilles.bourgeat@gmail.com> + */ +class LabelRequestAPIConfiguration extends APIConfiguration +{ + public function __construct() + { + parent::__construct(); + + $this->setMethod('generateLabel'); + } +} diff --git a/local/modules/ColissimoLabel/Request/Helper/Letter.php b/local/modules/ColissimoLabel/Request/Helper/Letter.php new file mode 100644 index 00000000..3224f540 --- /dev/null +++ b/local/modules/ColissimoLabel/Request/Helper/Letter.php @@ -0,0 +1,78 @@ +gilles.bourgeat@gmail.com> + */ +class Letter +{ + /** @var Sender */ + protected $sender; + + /** @var Addressee */ + protected $addressee; + + /** @var Parcel */ + protected $parcel; + + /** @var Service */ + protected $service; + + /** @var CustomsDeclarations */ + protected $customsDeclarations; + + public function __construct( + Service $service, + Sender $sender, + Addressee $addressee, + Parcel $parcel, + CustomsDeclarations $customsDeclarations + ) { + $this->sender = $sender; + $this->addressee = $addressee; + $this->parcel = $parcel; + $this->service = $service; + $this->customsDeclarations = $customsDeclarations; + } + + /** + * @return Service + */ + public function getService() + { + return $this->service; + } + + /** + * @return Sender + */ + public function getSender() + { + return $this->sender; + } + + /** + * @return Addressee + */ + public function getAddressee() + { + return $this->addressee; + } + + /** + * @return Parcel + */ + public function getParcel() + { + return $this->parcel; + } + + /** + * @return CustomsDeclarations + */ + public function getCustomsDeclarations() + { + return $this->customsDeclarations; + } +} diff --git a/local/modules/ColissimoLabel/Request/Helper/OutputFormat.php b/local/modules/ColissimoLabel/Request/Helper/OutputFormat.php new file mode 100644 index 00000000..fd4c2cb4 --- /dev/null +++ b/local/modules/ColissimoLabel/Request/Helper/OutputFormat.php @@ -0,0 +1,87 @@ +gilles.bourgeat@gmail.com> + */ +class OutputFormat +{ + const OUTPUT_PRINTING_TYPE = [ + 0 => 'ZPL_10x15_203dpi', + 1 => 'ZPL_10x15_300dpi', + 2 => 'DPL_10x15_203dpi', + 3 => 'DPL_10x15_300dpi', + 4 => 'PDF_10x15_300dpi', + 5 => 'PDF_A4_300dpi' + ]; + + /** Default label format is : PDF_10x15_300dpi */ + const OUTPUT_PRINTING_TYPE_DEFAULT = 4; + + protected $x = 0; + + protected $y = 0; + + protected $outputPrintingType = self::OUTPUT_PRINTING_TYPE_DEFAULT; + + /** + * @return int + */ + public function getX() + { + return $this->x; + } + + /** + * @param int $x + * @return self + */ + public function setX($x) + { + $this->x = (int) $x; + return $this; + } + + /** + * @return int + */ + public function getY() + { + return $this->y; + } + + /** + * @param int $y + * @return self + */ + public function setY($y) + { + $this->y = (int) $y; + return $this; + } + + /** + * @return string value of the list ColissimoAPI\Request\Helper\LabelOutputFormat::OUTPUT_PRINTING_TYPE + */ + public function getOutputPrintingType() + { + return $this->outputPrintingType; + } + + /** + * @param string $outputPrintingType value of the list ColissimoAPI\Request\Helper\LabelOutputFormat::OUTPUT_PRINTING_TYPE + * @return self + */ + public function setOutputPrintingType($outputPrintingType) + { + if (\in_array($outputPrintingType, self::OUTPUT_PRINTING_TYPE)) { + new InvalidArgumentException('Invalid value "' . $outputPrintingType . '" for argument $outputPrintingType'); + } + + $this->outputPrintingType = $outputPrintingType; + return $this; + } +} diff --git a/local/modules/ColissimoLabel/Request/Helper/Parcel.php b/local/modules/ColissimoLabel/Request/Helper/Parcel.php new file mode 100644 index 00000000..2f72b3c2 --- /dev/null +++ b/local/modules/ColissimoLabel/Request/Helper/Parcel.php @@ -0,0 +1,94 @@ +gilles.bourgeat@gmail.com> + */ +class Parcel +{ + protected $weight = 0; + + protected $signedDelivery = false; + + protected $instructions = ''; + + protected $pickupLocationId; + + public function __construct($weight) + { + $this->weight = (float) $weight; + } + + /** + * @return int + */ + public function getWeight() + { + return $this->weight; + } + + /** + * @param int $weight + * @return self + */ + public function setWeight($weight) + { + $this->weight = $weight; + return $this; + } + + /** + * @return bool + */ + public function getSignedDelivery() + { + return $this->signedDelivery; + } + + /** + * @param bool $signedDelivery + * @return self + */ + public function setSignedDelivery($signedDelivery) + { + $this->signedDelivery = $signedDelivery; + return $this; + } + + /** + * @return string + */ + public function getInstructions() + { + return $this->instructions; + } + + /** + * @param string $instructions + * @return self + */ + public function setInstructions($instructions) + { + $this->instructions = $instructions; + return $this; + } + + /** + * @return string + */ + public function getPickupLocationId() + { + return $this->pickupLocationId; + } + + /** + * @param string $pickupLocationId + * @return self + */ + public function setPickupLocationId($pickupLocationId) + { + $this->pickupLocationId = $pickupLocationId; + return $this; + } +} diff --git a/local/modules/ColissimoLabel/Request/Helper/Sender.php b/local/modules/ColissimoLabel/Request/Helper/Sender.php new file mode 100644 index 00000000..8fcbb2dd --- /dev/null +++ b/local/modules/ColissimoLabel/Request/Helper/Sender.php @@ -0,0 +1,46 @@ +gilles.bourgeat@gmail.com> + */ +class Sender +{ + /** @var string */ + protected $senderParcelRef; + + /** @var Address */ + protected $address; + + public function __construct(Address $address) + { + $this->address = $address; + } + + /** + * @return string + */ + public function getSenderParcelRef() + { + return $this->senderParcelRef; + } + + /** + * @param string $senderParcelRef + * @return self + */ + public function setSenderParcelRef($senderParcelRef) + { + $this->senderParcelRef = $senderParcelRef; + return $this; + } + + /** + * @return Address + */ + public function getAddress() + { + return $this->address; + } +} diff --git a/local/modules/ColissimoLabel/Request/Helper/Service.php b/local/modules/ColissimoLabel/Request/Helper/Service.php new file mode 100644 index 00000000..4c94d3f5 --- /dev/null +++ b/local/modules/ColissimoLabel/Request/Helper/Service.php @@ -0,0 +1,234 @@ +gilles.bourgeat@gmail.com> + */ +class Service +{ + const PRODUCT_CODE_LIST = [ + 0 => 'DOM', + 1 => 'COLD', + 2 => 'DOS', + 3 => 'COL', + 4 => 'BPR', + 5 => 'A2P', + 6 => 'CORE', + 7 => 'COLR', + 8 => 'J+1 ', + 9 => 'CORI', + 10 => 'COM', + 11 => 'CDS', + 12 => 'ECO', + 13 => 'CORI', + 14 => 'COLI', + 15 => 'ACCI', + 16 => 'CMT', + 17 => 'PCS', + 18 => 'DOM', + 19 => 'DOS', + 20 => 'BDP' + ]; + + const PRODUCT_CODE_LIST_COMMERCIAL_NAME = [ + 0 => 'France Colissimo Domicile - sans signature', + 1 => 'France Colissimo Domicile - sans signature', + 2 => 'France Colissimo Domicile - avec signature', + 3 => 'France Colissimo Domicile - avec signature', + 4 => 'France Colissimo - Point Retrait – en Bureau de Poste ** ', + 5 => 'France Colissimo - Point Retrait – en relais Pickup ou en consigne Pickup Station', + 6 => 'France Colissimo Retour France', + 7 => 'France Colissimo Flash - sans signature', + 8 => 'Colissimo Flash – avec signature', + 9 => 'Colissimo Retour International ', + 10 => 'Outre-Mer Colissimo Domicile - sans signature ', + 11 => 'Outre-Mer Colissimo Domicile - avec signature', + 12 => 'Outre-Mer Colissimo Eco OM', + 13 => 'Outre-Mer Colissimo Retour OM', + 14 => 'International Colissimo Expert International', + 15 => 'International Offre Economique Grand Export (offre en test pour la Chine pour un client Pilote)', + 16 => 'International (Europe) Colissimo - Point Retrait – en relais ****', + 17 => 'International (Europe) Colissimo - Point Retrait – Consigne Pickup Station – Sauf France et Belgique', + 18 => 'International (Europe) Colissimo Domicile - sans signature ****', + 19 => 'International (Europe) Colissimo Domicile - avec signature ****', + 20 => 'International (Europe) Colissimo Point Retrait – en bureau de poste ****' + ]; + + const EUROPE_ISOCODES = [ + '040', /** Austria */ + '056', /** Belgium */ + '100', /** Bulgaria */ + '191', /** Croatia */ + '196', /** Cyprus */ + '203', /** Czech Republic */ + '208', /** Denmark */ + '233', /** Estonia */ + '246', /** Finland */ + '250', /** France */ + '276', /** Germany */ + '300', /** Greece */ + '348', /** Hungary */ + '352', /** Iceland */ + '372', /** Ireland */ + '380', /** Italy */ + '428', /** Latvia */ + '440', /** Lithuania */ + '442', /** Luxembourg */ + '470', /** Malta */ + '528', /** Netherlands */ + '578', /** Norway */ + '616', /** Poland */ + '620', /** Portugal */ + '642', /** Romania */ + '703', /** Slovakia */ + '705', /** Slovenia */ + '724', /** Spain */ + '752', /** Sweden */ + '756', /** Switzerland */ + '826', /** United Kingdom */ + ]; + + const DOMTOM_ISOCODES = [ + '175', /** Mayotte */ + '254', /** Guyane Française */ + '258', /** Polynésie Française */ + '312', /** Guadeloupe */ + '474', /** Martinique */ + '540', /** Nouvelle-Calédonie */ + '638', /** Réunion(La) */ + '666', /** St Pierre et Miquelon */ + '876', /** Wallis et Futuna */ + ]; + + protected $productCode = ''; + + /** @var \DateTime */ + protected $depositDate; + + protected $orderNumber = ''; + + protected $commercialName = ''; + + protected $transportationAmount = ''; + + protected $returnTypeChoice = 3; + + public function __construct($productCode, \DateTime $depositDate, $orderNumber, $transportationAmount, $returnTypeChoice) + { + if (empty($orderNumber)) { + throw new InvalidArgumentException('Invalid argument orderNumber'); + } + + if (empty($productCode)) { + throw new InvalidArgumentException('Invalid argument productCode'); + } + + $this->orderNumber = $orderNumber; + $this->depositDate = $depositDate; + $this->productCode = $productCode; + $this->transportationAmount = $transportationAmount; + $this->returnTypeChoice = $returnTypeChoice; + } + + /** + * @return string + */ + public function getProductCode() + { + return $this->productCode; + } + + /** + * @param string $productCode + * @return $this + */ + public function setProductCode($productCode) + { + $this->productCode = $productCode; + return $this; + } + + /** + * @return \DateTime + */ + public function getDepositDate() + { + return $this->depositDate; + } + + /** + * @return string + */ + public function getOrderNumber() + { + return $this->orderNumber; + } + + /** + * @return string + */ + public function getCommercialName() + { + return $this->commercialName; + } + + /** + * @param string $commercialName + * @return Service + */ + public function setCommercialName($commercialName) + { + $this->commercialName = $commercialName; + return $this; + } + + /** + * @return string + */ + public function getTransportationAmount() + { + /** DO NOT use strict comparison here */ + if ($this->transportationAmount == 0) { + return '0'; + } + + /** Formatting the postage price in a XXXX format (price in cents without separator), as requested by the Colissimo API */ + $nbr = number_format($this->transportationAmount, 2, '.', ''); + if ((float)$nbr < 10) { + $nbr = '0' . $nbr; + } + return str_pad(str_replace('.', '', $nbr), 4, '0', STR_PAD_RIGHT); + } + + /** + * @param $transportationAmount + * @return $this + */ + public function setTransportationAmount($transportationAmount) + { + $this->transportationAmount = $transportationAmount; + return $this; + } + + + /** + * @return int + */ + public function getReturnTypeChoice() + { + return $this->returnTypeChoice; + } + + /** + * @param $returnTypeChoice + * @return $this + */ + public function setReturnTypeChoice($returnTypeChoice) + { + $this->returnTypeChoice = $returnTypeChoice; + return $this; + } +} diff --git a/local/modules/ColissimoLabel/Request/LabelRequest.php b/local/modules/ColissimoLabel/Request/LabelRequest.php new file mode 100644 index 00000000..8efc312b --- /dev/null +++ b/local/modules/ColissimoLabel/Request/LabelRequest.php @@ -0,0 +1,145 @@ +gilles.bourgeat@gmail.com> + */ +class LabelRequest extends AbstractLabelRequest +{ + use MethodCreateAddressFromStore; + use MethodCreateAddressFromOrderAddress; + + public function __construct(Order $order, $pickupCode = null, $pickupType = null, $signedDelivery = false) + { + $orderAddress = OrderAddressQuery::create()->findOneById($order->getDeliveryOrderAddressId()); + + /** + * If a pickup type was given (relay point delivery), we set the delivery code $productCode as this. + * Otherwise, we check in getProductCode which delivery type is necessary given the delivery country and whether this + * is a signed delivery or not, and set $productCode as what ie returns + */ + if (null === $productCode = $pickupType) { + $productCode = $this->getProductCode($order, $signedDelivery); + } + + $articles = []; + foreach ($order->getOrderProducts() as $orderProduct) { + $productPrice = $orderProduct->getWasInPromo() ? $orderProduct->getPromoPrice() : $orderProduct->getPrice(); + $articles[] = new Article( + $orderProduct->getTitle(), + $orderProduct->getQuantity(), + $orderProduct->getWeight(), + $productPrice, + ColissimoLabel::getConfigValue(ColissimoLabel::CONFIG_KEY_CUSTOMS_PRODUCT_HSCODE), + CurrencyQuery::create()->findOneById($order->getCurrencyId())->getCode() + ); + } + + $this->setLetter(new Letter( + /** We set the general delivery informations */ + new Service( + $productCode, + new DateTime(), + $order->getRef(), + $order->getPostage(), + 3 + ), + /** We set the sender address */ + new Sender( + $this->createAddressFromStore() + ), + /** We set the receiver address */ + new Addressee( + $this->createAddressFromOrderAddress( + $orderAddress, + $order->getCustomer() + ) + ), + new Parcel( + $order->getWeight() + ), + new CustomsDeclarations( + (bool)ColissimoLabel::getConfigValue(ColissimoLabel::CONFIG_KEY_GET_CUSTOMS_INVOICES), + 3, + $articles + ) + )); + + /** If this is a pickup/relay point delivery, we set the pickup location ID */ + if (null !== $pickupCode) { + $this->getLetter()->getParcel()->setPickupLocationId($pickupCode); + } + + $this->getLetter()->getAddressee()->setAddresseeParcelRef($order->getRef()); + $this->getLetter()->getSender()->setSenderParcelRef($order->getRef()); + + /** We initialize the label format */ + $this->setOutputFormat(new OutputFormat()); + + /** We set the label format from the one indicated in the module config table */ + $this->getOutputFormat()->setOutputPrintingType( + OutputFormat::OUTPUT_PRINTING_TYPE[ColissimoLabel::getConfigValue(ColissimoLabel::CONFIG_KEY_DEFAULT_LABEL_FORMAT)] + ); + } + + /** + * Return a domicile delivery code given the order country and whether this is a signed delivery or not + * + * @param Order $order + * @param bool $signedDelivery + * @return mixed + * @throws \Propel\Runtime\Exception\PropelException + */ + protected function getProductCode(Order $order, $signedDelivery = false) + { + /** @var OrderAddress $deliveryAddress */ + $deliveryAddress = $order->getOrderAddressRelatedByDeliveryOrderAddressId(); + + $code = $deliveryAddress->getCountry()->getIsocode(); + + /** France Case */ + if ($code == '250') { + if ($signedDelivery) { + return Service::PRODUCT_CODE_LIST[2]; + } + return Service::PRODUCT_CODE_LIST[0]; + } + + /** Europe Case */ + if (in_array($code, Service::EUROPE_ISOCODES, false)) { + if ($signedDelivery) { + return Service::PRODUCT_CODE_LIST[2]; + } + return Service::PRODUCT_CODE_LIST[0]; + } + + /** DOM TOM case */ + if (in_array($code, Service::DOMTOM_ISOCODES, false)) { + if ($signedDelivery) { + return Service::PRODUCT_CODE_LIST[11]; + } + return Service::PRODUCT_CODE_LIST[10]; + } + + /** Other cases */ + return Service::PRODUCT_CODE_LIST[14]; + } +} diff --git a/local/modules/ColissimoLabel/Request/Traits/MethodCreateAddressFromOrderAddress.php b/local/modules/ColissimoLabel/Request/Traits/MethodCreateAddressFromOrderAddress.php new file mode 100644 index 00000000..c7b35776 --- /dev/null +++ b/local/modules/ColissimoLabel/Request/Traits/MethodCreateAddressFromOrderAddress.php @@ -0,0 +1,32 @@ +gilles.bourgeat@gmail.com> + */ +trait MethodCreateAddressFromOrderAddress +{ + public function createAddressFromOrderAddress(OrderAddress $orderAddress, Customer $customer) + { + return (new Address()) + ->setCompanyName($orderAddress->getCompany()) + ->setFirstName($orderAddress->getFirstname()) + ->setLastName($orderAddress->getLastname()) + ->setCity($orderAddress->getCity()) + ->setZipCode($orderAddress->getZipcode()) + ->setCountryCode($orderAddress->getCountry()->getIsoalpha2()) + ->setLine2($orderAddress->getAddress1()) + ->setLine3($orderAddress->getAddress2()) + ->setPhoneNumber(trim(str_replace(' ', '', $orderAddress->getPhone()))) + ->setMobileNumber(trim(str_replace(' ', '', $orderAddress->getCellphone()))) + ->setEmail($customer->getEmail()) + ->setLanguage(strtoupper(LangQuery::create()->filterByByDefault(true)->findOne()->getCode())) + ; + } +} diff --git a/local/modules/ColissimoLabel/Request/Traits/MethodCreateAddressFromStore.php b/local/modules/ColissimoLabel/Request/Traits/MethodCreateAddressFromStore.php new file mode 100644 index 00000000..72fb41d2 --- /dev/null +++ b/local/modules/ColissimoLabel/Request/Traits/MethodCreateAddressFromStore.php @@ -0,0 +1,30 @@ +gilles.bourgeat@gmail.com> + */ +trait MethodCreateAddressFromStore +{ + public function createAddressFromStore() + { + return (new Address()) + ->setCompanyName(ColissimoLabel::getConfigValue(ColissimoLabel::CONFIG_KEY_FROM_NAME)) + ->setCity(ColissimoLabel::getConfigValue(ColissimoLabel::CONFIG_KEY_FROM_CITY)) + ->setZipCode(ColissimoLabel::getConfigValue(ColissimoLabel::CONFIG_KEY_FROM_ZIPCODE)) + ->setCountryCode(CountryQuery::create()->findOneById(ColissimoLabel::getConfigValue(ColissimoLabel::CONFIG_KEY_FROM_COUNTRY))->getIsoalpha2()) + ->setLine2(ColissimoLabel::getConfigValue(ColissimoLabel::CONFIG_KEY_FROM_ADDRESS_1)) + ->setLine3(ColissimoLabel::getConfigValue(ColissimoLabel::CONFIG_KEY_FROM_ADDRESS_2)) + ->setEmail(trim(ColissimoLabel::getConfigValue(ColissimoLabel::CONFIG_KEY_FROM_CONTACT_EMAIL))) + ->setPhoneNumber(trim(str_replace(' ', '', ColissimoLabel::getConfigValue(ColissimoLabel::CONFIG_KEY_FROM_PHONE)))) + ->setLanguage(strtoupper(LangQuery::create()->filterByByDefault(true)->findOne()->getCode())) + ; + } +} diff --git a/local/modules/ColissimoLabel/Response/BordereauResponse.php b/local/modules/ColissimoLabel/Response/BordereauResponse.php new file mode 100644 index 00000000..ad95cf7c --- /dev/null +++ b/local/modules/ColissimoLabel/Response/BordereauResponse.php @@ -0,0 +1,78 @@ +gilles.bourgeat@gmail.com> + */ +class BordereauResponse +{ + const UUID = '/--uuid:/'; //This is the separator of each part of the response + const CONTENT = 'Content-'; + + public $soapResponse = []; + public $attachments = []; + public $uuid; + + public function __construct($soapResponse) + { + $this->soapResponse[] = $soapResponse; + + $this->parseResponse($soapResponse); + } + + protected function parseResponse($response) + { + $content = array (); + $matches = array (); + preg_match_all(self::UUID, $response, $matches, PREG_OFFSET_CAPTURE); + + for($i = 0; $i < count ( $matches [0] ) -1; $i ++) { + if ($i + 1 < count ( $matches [0] )) { + $content [$i] = substr ( $response, $matches [0] [$i] [1], $matches [0] [$i + 1] [1] - $matches [0][$i] [1] ); + } else { + $content [$i] = substr ( $response, $matches [0] [$i] [1], strlen ( $response ) ); + } + } + + foreach ( $content as $part ) { + if ($this->uuid == null) { + $uuidStart = 0; + $uuidEnd = 0; + $uuidStart = strpos($part, self::UUID, 0) + strlen(self::UUID); + $uuidEnd = strpos($part, "\r\n", $uuidStart); + $this->uuid = substr($part, $uuidStart, $uuidEnd - $uuidStart); + } + $header = $this->extractHeader($part); + if(count($header) > 0) { + if (strpos($header['Content-Type'], 'type="text/xml"') !== FALSE) { + $this->soapResponse['header'] = $header; + $this->soapResponse['data'] = trim(substr($part, $header['offsetEnd'])); + } else { + $attachment['header'] = $header; + $attachment['data'] = trim(substr($part, $header['offsetEnd'])); + array_push($this->attachments, $attachment); + } + } + } + } + + /** + * Exclude the header from the Web Service response * @param string $part + * @return array $header + */ + private function extractHeader($part) + { + $header = array(); + $headerLineStart = strpos($part, self::CONTENT, 0); + $endLine = 0; + while($headerLineStart !== FALSE) { + $header['offsetStart'] = $headerLineStart; + $endLine = strpos($part, "\r\n", $headerLineStart); + $headerLine = explode(': ', substr($part, $headerLineStart, $endLine-$headerLineStart)); $header[$headerLine[0]] = $headerLine[1]; + $headerLineStart = strpos($part, self::CONTENT, $endLine); + } + $header['offsetEnd'] = $endLine; + return $header; + } +} diff --git a/local/modules/ColissimoLabel/Response/LabelResponse.php b/local/modules/ColissimoLabel/Response/LabelResponse.php new file mode 100644 index 00000000..b0326096 --- /dev/null +++ b/local/modules/ColissimoLabel/Response/LabelResponse.php @@ -0,0 +1,159 @@ +gilles.bourgeat@gmail.com> + */ +class LabelResponse +{ + const UUID = '/--uuid:/'; //This is the separator of each part of the response + const CONTENT = 'Content-'; + + protected $soapResponse; + protected $cacheAttachments = []; + protected $cacheSoapResponse = []; + protected $uuid; + + public function __construct($soapResponse) + { + $this->soapResponse = $soapResponse; + + $this->parseResponse($soapResponse); + } + + public function getFile() + { + if ($this->isValid()) { + return $this->cacheAttachments[0]["data"]; + } + + return null; + } + + public function getParcelNumber() + { + if ($this->isValid()) { + $pieces = explode("", $this->cacheSoapResponse["data"]); + $pieces = explode("", $pieces[1]); + + return $pieces[0]; + } + + return null; + } + + public function hasFileCN23() + { + if ($this->isValid()) { + return isset($this->cacheAttachments[1]["data"]); + } + + return false; + } + + public function getFileCN23() + { + if ($this->isValid()) { + if (\count($this->cacheAttachments) > 1) { + return $this->cacheAttachments[1]["data"]; + } + } + + return null; + } + + public function isValid() + { + if (!isset($this->cacheSoapResponse["data"])) { + return false; + } + + $soapResult = $this->cacheSoapResponse["data"]; + $errorCode = explode("", $soapResult); + $errorCode = explode("", $errorCode[1]); + //- Parse Web Service Response + //+ Error handling and label saving + if ($errorCode[0] == 0) { + return true; + } + + return false; + } + + public function getError($messageOnly = false) + { + if (!isset($this->cacheSoapResponse['data'])) { + return [$this->soapResponse]; + } + + if ($this->isValid()) { + return []; + } + + $soapResult = $this->cacheSoapResponse["data"]; + $errorCode = explode("", $soapResult); + $errorCode = explode("", $errorCode[1]); + + $errorMessage = explode("", $this->cacheSoapResponse["data"]); + $errorMessage = explode("", $errorMessage[1]); + + if ($messageOnly) { + return $errorMessage; + } + + return [$errorCode[0] => $errorMessage]; + } + + protected function parseResponse($response) + { + $content = array (); + $matches = array (); + preg_match_all(self::UUID, $response, $matches, PREG_OFFSET_CAPTURE); + + for ($i = 0; $i < count($matches[0]) -1; $i++) { + if ($i + 1 < count($matches[0])) { + $content[$i] = substr($response, $matches[0][$i][1], $matches[0][$i + 1][1] - $matches[0][$i][1]); + } else { + $content[$i] = substr($response, $matches[0][$i][1], strlen($response)); + } + } + + foreach ($content as $part) { + if ($this->uuid == null) { + $uuidStart = strpos($part, self::UUID, 0)+strlen(self::UUID); + $uuidEnd = strpos($part, "\r\n", $uuidStart); + $this->uuid = substr($part, $uuidStart, $uuidEnd-$uuidStart); + } + $header = $this->extractHeader($part); + if (count($header) > 0) { + if (false !== strpos($header['Content-Type'], 'type="text/xml"')) { + $this->cacheSoapResponse['header'] = $header; + $this->cacheSoapResponse['data'] = trim(substr($part, $header['offsetEnd'])); + } else { + $attachment['header'] = $header; + $attachment['data'] = trim(substr($part, $header['offsetEnd'])); + array_push($this->cacheAttachments, $attachment); + } + } + } + + return $this; + } + + protected function extractHeader($part) + { + $header = array(); + $headerLineStart = strpos($part, self::CONTENT, 0); + $endLine = 0; + while (false !== $headerLineStart) { + $header['offsetStart'] = $headerLineStart; + $endLine = strpos($part, "\r\n", $headerLineStart); + $headerLine = explode(': ', substr($part, $headerLineStart, $endLine-$headerLineStart)); + $header[$headerLine[0]] = $headerLine[1]; + $headerLineStart = strpos($part, self::CONTENT, $endLine); + } + $header['offsetEnd'] = $endLine; + return $header; + } +} diff --git a/local/modules/ColissimoLabel/Service/LabelService.php b/local/modules/ColissimoLabel/Service/LabelService.php new file mode 100644 index 00000000..79d2dded --- /dev/null +++ b/local/modules/ColissimoLabel/Service/LabelService.php @@ -0,0 +1,239 @@ +dispatcher = $dispatcher; + } + + public function generateLabel($data, $isEditPage) + { + /** Check if status needs to be changed after processing */ + $newStatus = OrderStatusQuery::create()->findOneByCode($data['new_status']); + + $weightArray = $data['weight']; + $signedArray = $data['signed']; + + foreach ($data['order_id'] as $orderId) { + if (null !== $order = OrderQuery::create()->findOneById($orderId)) { + /** DO NOT use strict comparison here */ + if (!isset($weightArray[$orderId]) || 0 == (float)$weightArray[$orderId]) { + $weight = $order->getWeight(); + } else { + $weight = (float)$weightArray[$orderId]; + } + + if ($weight === null) { + throw new \Exception('Please enter a weight for every selected order'); + } + + /** Check if the 'signed' checkbox was checked for this particular order */ + $signedDelivery = false; + if (array_key_exists($orderId, $signedArray)) { + $signedDelivery = $signedArray[$orderId]; + } + + $APIConfiguration = new LabelRequestAPIConfiguration(); + $APIConfiguration->setContractNumber(ColissimoLabel::getConfigValue(ColissimoLabel::CONFIG_KEY_CONTRACT_NUMBER)); + $APIConfiguration->setPassword(ColissimoLabel::getConfigValue(ColissimoLabel::CONFIG_KEY_PASSWORD)); + + /** Check if delivery is a relay point through SoColissimo. Use relay point address if it is */ + if (ColissimoLabel::AUTHORIZED_MODULES[1] === $order->getModuleRelatedByDeliveryModuleId()->getCode()) { + if (null !== $AddressColissimoPickupPoint = OrderAddressSoColissimoPickupPointQuery::create() + ->findOneById($order->getDeliveryOrderAddressId())) { + /** If the delivery is through a relay point, we create a new LabelRequest with the relay point and order infos */ + if ($AddressColissimoPickupPoint) { + $colissimoRequest = new LabelRequest( + $order, + $AddressColissimoPickupPoint->getCode() == '0' ? null : $AddressColissimoPickupPoint->getCode(), + $AddressColissimoPickupPoint->getType() + ); + + $colissimoRequest->getLetter()->getService()->setCommercialName( + $colissimoRequest->getLetter()->getSender()->getAddress()->getCompanyName() + ); + } + } + } + + /** Same thing with ColissimoPickupPoint */ + if (ColissimoLabel::AUTHORIZED_MODULES[3] === $order->getModuleRelatedByDeliveryModuleId()->getCode()) { + if (null !== $AddressColissimoPickupPoint = OrderAddressColissimoPickupPointQuery::create() + ->findOneById($order->getDeliveryOrderAddressId())) { + /** If the delivery is through a relay point, we create a new LabelRequest with the relay point and order infos */ + if ($AddressColissimoPickupPoint) { + $colissimoRequest = new LabelRequest( + $order, + $AddressColissimoPickupPoint->getCode() == '0' ? null : $AddressColissimoPickupPoint->getCode(), + $AddressColissimoPickupPoint->getType() + ); + + $colissimoRequest->getLetter()->getService()->setCommercialName( + $colissimoRequest->getLetter()->getSender()->getAddress()->getCompanyName() + ); + } + } + } + + /** If this is a domicile delivery, we only use the order information to create a Labelrequest, not the relay point */ + if (!isset($colissimoRequest)) { + $colissimoRequest = new LabelRequest($order, null, null, $signedDelivery); + } + + /** We set the weight as the one indicated from the form */ + if (null !== $weight) { + $colissimoRequest->getLetter()->getParcel()->setWeight($weight); + } + + /** We set whether the delivery is a signed one or not thanks to the 'signed' checkbox in the form */ + if (null !== $signedDelivery) { + $colissimoRequest->getLetter()->getParcel()->setSignedDelivery($signedDelivery); + } + + $service = new SOAPService(); + + $this->dispatcher->dispatch( + ColissimoLabelEvents::LABEL_REQUEST, + new LabelRequestEvent($colissimoRequest) + ); + + $response = $service->callAPI($APIConfiguration, $colissimoRequest); + + /** Handling what happens if the response from Colissimo is valid */ + if ($response->isValid()) { + $fileSystem = new Filesystem(); + + /** We dump / save the label on the server */ + $fileSystem->dumpFile( + $labelName = ColissimoLabel::getLabelPath($order->getRef(), ColissimoLabel::getFileExtension()), + $response->getFile() + ); + + $files[] = $labelName; + $hasCustomsFile = 0; + + /** Dump the CN23 customs file if there is one */ + if ($response->hasFileCN23()) { + $fileSystem->dumpFile( + $customsFileName = ColissimoLabel::getLabelCN23Path($order->getRef() . 'CN23', 'pdf'), + $response->getFileCN23() + ); + $files[] = $customsFileName; + $hasCustomsFile = 1; + } + + /** + * Checking if an entry with an error already exists in the table for this order label, creates one otherwise + * This allows to modify only entry with errors, while creating new ones if none with error were found + */ + $colissimoLabelModel = ColissimoLabelQuery::create() + ->filterByOrder($order) + ->filterByError(1) + ->findOneOrCreate() + ; + + /** Saving the label info in the table */ + $colissimoLabelModel + ->setOrderId($order->getId()) + ->setOrderRef($order->getRef()) + ->setError(0) + ->setErrorMessage('') + ->setWeight($colissimoRequest->getLetter()->getParcel()->getWeight()) + ->setTrackingNumber($response->getParcelNumber()) + ->setSigned($signedDelivery) + ->setLabelType(ColissimoLabel::getFileExtension()) + ->setWithCustomsInvoice($hasCustomsFile) + ; + $colissimoLabelModel->save(); + + $parcelNumbers[] = $response->getParcelNumber(); + + $order->setDeliveryRef($response->getParcelNumber()); + $order->save(); + + /** Change the order status if it was requested by the user */ + if ($newStatus) { + $newStatusId = $newStatus->getId(); + + if ((int)$order->getOrderStatus()->getId() !== $newStatusId) { + $order->setOrderStatus($newStatus); + $this->dispatcher->dispatch( + TheliaEvents::ORDER_UPDATE_STATUS, + (new OrderEvent($order))->setStatus($newStatusId) + ); + } + } + + /** Return JSON response when the form is called from order edit page */ + if ($isEditPage) { + return new JsonResponse([ + 'id' => $colissimoLabelModel->getId(), + 'url' => URL::getInstance()->absoluteUrl('/admin/module/colissimolabel/label/' . $response->getParcelNumber()), + 'number' => $response->getParcelNumber(), + 'order' => [ + 'id' => $order->getId(), + 'status' => [ + 'id' => $order->getOrderStatus()->getId() + ] + ] + ]); + } + + } else { + /** Handling errors when the response is invalid */ + + $colissimoLabelError = ColissimoLabelQuery::create() + ->filterByOrder($order) + ->filterByError(1) + ->findOneOrCreate() + ; + + $colissimoLabelError + ->setError(1) + ->setErrorMessage($response->getError(true)[0]) + ->setSigned($signedDelivery) + ->setWeight($colissimoRequest->getLetter()->getParcel()->getWeight()) + ->save() + ; + + /** Return JSON response when the form is called from the order edit page */ + if ($isEditPage) { + return new JsonResponse([ + 'error' => $response->getError() + ]); + } + } + } + } + } +} diff --git a/local/modules/ColissimoLabel/Service/SOAPService.php b/local/modules/ColissimoLabel/Service/SOAPService.php new file mode 100644 index 00000000..200f48a9 --- /dev/null +++ b/local/modules/ColissimoLabel/Service/SOAPService.php @@ -0,0 +1,104 @@ +gilles.bourgeat@gmail.com> + */ +class SOAPService +{ + public function callGenerateBordereauByParcelsNumbersAPI(APIConfiguration $APIConfiguration, $parcelNumbers = []) + { + //+ Generate SOAPRequest + $xml = new \SimpleXMLElement(''); + $xml->addChild("soapenv:Header"); + $children = $xml->addChild("soapenv:Body"); + $children = $children->addChild("sls:generateBordereauByParcelsNumbers", null, 'http://sls.ws.coliposte.fr'); + $children->addChild("contractNumber", $APIConfiguration->getContractNumber(), ""); + $children->addChild("password", $APIConfiguration->getPassword(), ""); + $children = $children->addChild("generateBordereauParcelNumberList", null, ""); + + foreach ($parcelNumbers as $parcelNumber) + { + $children->addChild("parcelsNumbers", $parcelNumber, ""); + } + + $soap = new \SoapClient($APIConfiguration->getWsdl()); + + return new BordereauResponse($soap->__doRequest( + $xml->asXML(), + $APIConfiguration->getWsdl(), + $APIConfiguration->getMethod(), + $APIConfiguration->getVersion(), + 0 + )); + } + + public function callAPI(APIConfiguration $APIConfiguration, LabelRequest $request) + { + $request->setContractNumber($APIConfiguration->getContractNumber()); + $request->setPassword($APIConfiguration->getPassword()); + + //+ Generate SOAPRequest + $xml = new \SimpleXMLElement(''); + $xml->addChild("soapenv:Header"); + $children = $xml->addChild("soapenv:Body"); + $children = $children->addChild("sls:generateLabel", null, 'http://sls.ws.coliposte.fr'); + $children = $children->addChild("generateLabelRequest", null, ""); + + $this->arrayToXml($request->generateArrayRequest(), $children, $request->getLetter()->getCustomsDeclarations()->getArticles()); + + $soap = new \SoapClient($APIConfiguration->getWsdl()); + + $test = $xml->asXML(); + + return new LabelResponse($soap->__doRequest( + $xml->asXML(), + $APIConfiguration->getWsdl(), + $APIConfiguration->getMethod(), + $APIConfiguration->getVersion(), + 0 + )); + } + + protected function arrayToXml(array $soapRequest, \SimpleXMLElement $soapRequestXml, $articles) + { + foreach ($soapRequest as $key => $value) { + if ($value === null || empty($value)) { + continue; + } + if (is_array($value)) { + if (!is_numeric($key)) { + $subnode = $soapRequestXml->addChild($key); + $this->arrayToXml($value, $subnode, $articles); + } else { + $subnode = $soapRequestXml->addChild("item" . $key); + $this->arrayToXml($value, $subnode, $articles); + } + } else { + if ($key === 'article') { + /** @var Article $article */ + foreach ($articles as $article) { + $xmlArticle = $soapRequestXml->addChild($key); + $xmlArticle->addChild('description', $article->getDescription()); + $xmlArticle->addChild('quantity', $article->getQuantity()); + $xmlArticle->addChild('weight', $article->getWeight()); + $xmlArticle->addChild('value', $article->getValue()); + $xmlArticle->addChild('hsCode', $article->getHsCode()); + $xmlArticle->addChild('originCountry', $article->getOriginCountry()); + $xmlArticle->addChild('currency', $article->getCurrency()); + } + } else { + $soapRequestXml->addChild($key, htmlspecialchars($value)); + } + } + } + } +} diff --git a/local/modules/ColissimoLabel/composer.json b/local/modules/ColissimoLabel/composer.json new file mode 100644 index 00000000..274ed544 --- /dev/null +++ b/local/modules/ColissimoLabel/composer.json @@ -0,0 +1,11 @@ +{ + "name": "thelia/colissimo-label-module", + "license": "LGPL-3.0+", + "type": "thelia-module", + "require": { + "thelia/installer": "~1.1" + }, + "extra": { + "installer-name": "ColissimoLabel" + } +} \ No newline at end of file diff --git a/local/modules/ColissimoLabel/spec_ws_affranchissement.pdf b/local/modules/ColissimoLabel/spec_ws_affranchissement.pdf new file mode 100644 index 00000000..7e9099b8 Binary files /dev/null and b/local/modules/ColissimoLabel/spec_ws_affranchissement.pdf differ diff --git a/local/modules/ColissimoLabel/templates/backOffice/default/colissimo-label/bordereau-list.html b/local/modules/ColissimoLabel/templates/backOffice/default/colissimo-label/bordereau-list.html new file mode 100644 index 00000000..3cfc118d --- /dev/null +++ b/local/modules/ColissimoLabel/templates/backOffice/default/colissimo-label/bordereau-list.html @@ -0,0 +1,89 @@ +{extends file="admin-layout.tpl"} + +{block name="check-resource"}admin.order{/block} +{block name="check-access"}view{/block} +{block name="page-title"}Bordereaux Colissimo{/block} + +{block name="after-admin-css"} +{/block} + +{if isset($smarty.get.tab)} + {$tab=$smarty.get.tab} +{else} + {$tab='bordereaux'} +{/if} + +{block name="main-content"} +
+
+
+
+
+ + +
+ + + {if $bordereaux} + + + + + + + + + + + + + {foreach from=$bordereaux item=bordereau} + + + + + {/foreach} + +
{intl d='colissimolabel.bo.default' l="Bordereau"}{intl d='colissimolabel.bo.default' l="Action"}
+ + {$bordereau['name']} + + + + + + + + +
+
+ {/if} +
+
+
+
+
+
+{/block} + +{block name="javascript-last-call"} +{/block} \ No newline at end of file diff --git a/local/modules/ColissimoLabel/templates/backOffice/default/colissimo-label/hook/main.in.top.menu.items.html b/local/modules/ColissimoLabel/templates/backOffice/default/colissimo-label/hook/main.in.top.menu.items.html new file mode 100644 index 00000000..f16b4410 --- /dev/null +++ b/local/modules/ColissimoLabel/templates/backOffice/default/colissimo-label/hook/main.in.top.menu.items.html @@ -0,0 +1,6 @@ +
  • + + + {intl l="ColissimoLabel" d="colissimolabel.bo.default"} + +
  • \ No newline at end of file diff --git a/local/modules/ColissimoLabel/templates/backOffice/default/colissimo-label/hook/order-edit-js.html b/local/modules/ColissimoLabel/templates/backOffice/default/colissimo-label/hook/order-edit-js.html new file mode 100644 index 00000000..98c0e693 --- /dev/null +++ b/local/modules/ColissimoLabel/templates/backOffice/default/colissimo-label/hook/order-edit-js.html @@ -0,0 +1,251 @@ +{loop type="order" name="the-order" id=$order_id customer="*" backend_context=true} + {$enable = false} + {loop type="module" name="module-order" active="yes" backend_context=true id=$DELIVERY_MODULE} + + {if $CODE === "ColissimoWs" || $CODE === "SoColissimo" || $CODE === "ColissimoHomeDelivery" || $CODE === "ColissimoPickupPoint"} + {$enable = true} + {/if} + {/loop} + + {if $enable} + + + + + {/if} +{/loop} \ No newline at end of file diff --git a/local/modules/ColissimoLabel/templates/backOffice/default/colissimo-label/label-list.html b/local/modules/ColissimoLabel/templates/backOffice/default/colissimo-label/label-list.html new file mode 100644 index 00000000..6bf8fcbd --- /dev/null +++ b/local/modules/ColissimoLabel/templates/backOffice/default/colissimo-label/label-list.html @@ -0,0 +1,30 @@ +{loop type="colissimolabel.label-info" name="colissimolabel.label-info" order_id=$order_id} +{if $TRACKING_NUMBER} + + + {$TRACKING_NUMBER} + + + {$WEIGHT} / Kg + + + {format_date date=$ORDER_DATE} + + + https://www.laposte.fr/particulier/outils/suivre-vos-envois?code={$TRACKING_NUMBER} + + + {intl l="Download" d="colissimolabel.bo.default"} + {intl l="View" d="colissimolabel.bo.default"} + {intl l="Print" d="colissimolabel.bo.default"} + {intl l="Delete" d="colissimolabel.bo.default"} + + +{else} + + + {intl l="No existing label for this order" d="colissimolabel.bo.default"} + + +{/if} +{/loop} diff --git a/local/modules/ColissimoLabel/templates/backOffice/default/colissimo-label/labels.html b/local/modules/ColissimoLabel/templates/backOffice/default/colissimo-label/labels.html new file mode 100644 index 00000000..ce85b8cd --- /dev/null +++ b/local/modules/ColissimoLabel/templates/backOffice/default/colissimo-label/labels.html @@ -0,0 +1,227 @@ +{extends file="admin-layout.tpl"} + +{block name="check-resource"}admin.order{/block} +{block name="check-access"}view{/block} +{block name="page-title"}Labels Colissimo{/block} + +{block name="after-admin-css"} +{/block} + +{if isset($smarty.get.tab)} + {$tab=$smarty.get.tab} +{else} + {$tab='labels'} +{/if} + +{block name="main-content"} +
    +
    +
    +
    +
    + + +
    +
    +
    +
    + {intl l="Download and print Colissimo labels for orders not yet sent" d='colissimolabel.bo.default'} +
    + + {form name="colissimolabel_export_form"} + {if $form_error}
    {$form_error_message}
    {/if} + +
    + {form_hidden_fields} +
    +
    + {intl d='colissimolabel.bo.default' l="Order status change after processing"} +
    + +
    + {form_field field="new_status"} +
    + +
    +
    + +
    +
    + +
    + {/form_field} +
    +
    + + + + + + + + + + + + + + + + + + + + {loop type="colissimolabel.orders-not-sent" name="orders.not.sent"} + {loop type="colissimolabel.label-info" name="label-info" order_id=$ID} + + + + + + + + + + + + + + + + + + + {if $HAS_ERROR} + + + + {/if} + + {/loop} + {/loop} + +
    + {intl d='colissimolabel.bo.default' l="REF"} + + {intl d='colissimolabel.bo.default' l="Order date"} + + {intl d='colissimolabel.bo.default' l="Destination"} + + {intl d='colissimolabel.bo.default' l="Weight"} + + {intl d='colissimolabel.bo.default' l="Price (with taxes)"} + + {intl d='colissimolabel.bo.default' l="Signature"} + + {intl d='colissimolabel.bo.default' l="Module"} + + {intl d='colissimolabel.bo.default' l="Tracking"} + + {intl d='colissimolabel.bo.default' l="Label"} + + {intl d='colissimolabel.bo.default' l="Customs invoice"} + + {intl l="Sel." d='colissimolabel.bo.default'} +
    + {$REF} + + {format_date date=$CREATE_DATE} + + {loop type='order_address' name='colissimolabel.address' backend_context=1 id=$DELIVERY_ADDRESS} + {$CITY|strtoupper} {$ZIPCODE|strtoupper}, {loop backend_context=1 type="country" name="adrctry" id=$COUNTRY}{$TITLE|strtoupper}{/loop} + {/loop} + + {form_field field="weight" value_key=$ORDER_ID} +
    + + {intl l="kg" d='colissimolabel.bo.default'} +
    + {/form_field} +
    + {$TOTAL_TAXED_AMOUNT|string_format:"%.2f"} + + {form_field field="signed" value_key=$ORDER_ID} + + {/form_field} + + {loop type="order" name="order-loop-labels" id="{$ORDER_ID}" customer='*' backend_context=1} + {loop type="module" name="delivery-module-loop" id=$DELIVERY_MODULE backend_context=1} + {$CODE} + {/loop} + {/loop} + + {if $TRACKING_NUMBER} + {$TRACKING_NUMBER} + {else} + + {/if} + + {if $HAS_LABEL} + + + + {else} + + {/if} + + {if $HAS_CUSTOMS_INVOICE} + + + + {else} + - + {/if} + + {if !$HAS_LABEL} + {form_field field="order_id" value_key=$ORDER_ID} + + {/form_field} + {else} + + + + {/if} +
    + {intl l="Label cannot be created. Error is: " d='colissimolabel.bo.default'} + {$ERROR_MESSAGE nofilter} +
    + + {elseloop rel="orders.not.sent"} +
    {intl d='colissimolabel.bo.default' l="There are currently no orders to ship with Colissimo"}
    + {/elseloop} + + {ifloop rel="orders.not.sent"} +
    + +
    + {/ifloop} +
    + {/form} +
    +
    +
    +
    +
    +
    +{* Download zip file if we have the name in the URL parameters *} +{if $smarty.get.zip} + +{/if} +{/block} + +{block name="javascript-last-call"} +{/block} + diff --git a/local/modules/ColissimoLabel/templates/backOffice/default/colissimo-label/module-configuration.html b/local/modules/ColissimoLabel/templates/backOffice/default/colissimo-label/module-configuration.html new file mode 100644 index 00000000..3fd9da47 --- /dev/null +++ b/local/modules/ColissimoLabel/templates/backOffice/default/colissimo-label/module-configuration.html @@ -0,0 +1,169 @@ +{extends file="admin-layout.tpl"} + +{block name="check-resource"}admin.order{/block} +{block name="check-access"}view{/block} +{block name="page-title"}Bordereaux Colissimo{/block} + +{block name="after-admin-css"} +{/block} + +{if isset($smarty.get.tab)} + {$tab=$smarty.get.tab} +{else} + {$tab='config'} +{/if} + +{block name="main-content"} +{$conf} +
    +
    +
    +
    +
    + + +
    +
    +
    +
    + {intl l="Advanced configuration" d='colissimolabel.bo.default'} +
    + +
    + {form name="colissimolabel.configure"} + {if $form_error && $form_error_message} +
    {$form_error_message}
    + {/if} +
    + + +
    +
    +
    {intl d='colissimolabel.bo.default' l="General informations"}
    +
    +
    + {form_hidden_fields form=$form} + + {render_form_field form=$form field='colissimolabel-endpoint' value={$value}} + {form_field form=$form field='contract-number'} +
    + + +
    + {/form_field} + {form_field form=$form field='password'} +
    + + +
    + {/form_field} + {form_field form=$form field='default-signed'} +
    + + {if $value == 1} + + {else} + + {/if} +
    + {/form_field} + {form_field form=$form field='generate-bordereau'} +
    + + {if $value == 1} + + {else} + + {/if} +
    + {/form_field} + {render_form_field form=$form field='default-label-format' value={$value}} + {render_form_field form=$form field='last-bordereau-date' value={$value}} + {form_field form=$form field='get-invoices'} +
    + + {if $value == 1} + + {else} + + {/if} +
    + {/form_field} + {form_field form=$form field='get-customs-invoices'} +
    + + {if $value == 1} + + {else} + + {/if} +
    + {/form_field} + {render_form_field form=$form field='customs-product-hscode' value={$value}} +
    +
    +
    + + +
    +
    +
    {intl d='colissimolabel.bo.default' l="Sender's address"}
    +
    +
    +
    +
    + {render_form_field field="colissimolabel-company-name" value={$value}} +
    +
    + {render_form_field field="colissimolabel-from-contact-email" value={$value}} +
    +
    + {render_form_field field="colissimolabel-from-phone" value={$value}} +
    +
    + {render_form_field field="colissimolabel-from-address-1" value={$value}} +
    +
    + {render_form_field field="colissimolabel-from-address-2" value={$value}} +
    +
    + {render_form_field field="colissimolabel-from-zipcode" value={$value}} +
    +
    + {render_form_field field="colissimolabel-from-city" value={$value}} +
    +
    + {custom_render_form_field form=$form field="colissimolabel-from-country"} + + {/custom_render_form_field} +
    +
    +
    +
    + + +
    + {/form} +
    +
    +
    +
    + +
    +
    +
    +
    +
    +{/block} + +{block name="javascript-last-call"} +{/block} \ No newline at end of file diff --git a/local/modules/ColissimoPickupPoint/AdminIncludes/order-edit.html b/local/modules/ColissimoPickupPoint/AdminIncludes/order-edit.html new file mode 100755 index 00000000..0f706ca2 --- /dev/null +++ b/local/modules/ColissimoPickupPoint/AdminIncludes/order-edit.html @@ -0,0 +1,31 @@ +{loop name="check.module.colissimo.pickup.point.order.edit" type="order" id=$ID status="2,3"} +{loop name="check.module.colissimo.pickup.point.id" type="colissimo.pickup.point.id"} + {if $MODULE_ID == $DELIVERY_MODULE} +
    +
    +
    + {intl l="Export Coliship file" d='colissimo.pickup.point.ai'} +
    +
    + + {form name="colissimo.pickup.point.export"} +
    + {form_hidden_fields form=$form} + {form_field form=$form field="new_status_id"} + + {/form_field} + + {form_field form=$form field="order_"|cat:$ID} + + {/form_field} + +
    + {/form} +
    + + Suivi du colis: ici +
    +
    + {/if} +{/loop} +{/loop} diff --git a/local/modules/ColissimoPickupPoint/ColissimoPickupPoint.php b/local/modules/ColissimoPickupPoint/ColissimoPickupPoint.php new file mode 100755 index 00000000..6cae6beb --- /dev/null +++ b/local/modules/ColissimoPickupPoint/ColissimoPickupPoint.php @@ -0,0 +1,342 @@ +. */ +/* */ +/*************************************************************************************/ + +namespace ColissimoPickupPoint; + +use ColissimoPickupPoint\Model\ColissimoPickupPointAreaFreeshippingQuery; +use ColissimoPickupPoint\Model\ColissimoPickupPointFreeshippingQuery; +use PDO; +use Propel\Runtime\ActiveQuery\Criteria; +use Propel\Runtime\Exception\PropelException; +use Propel\Runtime\Propel; +use ColissimoPickupPoint\Model\ColissimoPickupPointPriceSlicesQuery; +use Symfony\Component\Finder\Finder; +use Symfony\Component\Finder\SplFileInfo; +use Thelia\Model\Country; +use Thelia\Model\ModuleImageQuery; +use Thelia\Model\ModuleQuery; +use Propel\Runtime\Connection\ConnectionInterface; +use Thelia\Install\Database; +use Thelia\Module\AbstractDeliveryModule; +use Thelia\Module\Exception\DeliveryException; +use Thelia\Tools\Version\Version; + +class ColissimoPickupPoint extends AbstractDeliveryModule +{ + protected $request; + protected $dispatcher; + + private static $prices = null; + + const DOMAIN = 'colissimopickuppoint'; + + const COLISSIMO_USERNAME = 'colissimo_pickup_point_username'; + + const COLISSIMO_PASSWORD = 'colissimo_pickup_point_password'; + + const COLISSIMO_GOOGLE_KEY = 'colissimo_pickup_point_google_map_key'; + + const COLISSIMO_ENDPOINT = 'colissimo_pickup_point_endpoint_url'; + + /** + * These constants refer to the imported CSV file. + * IMPORT_NB_COLS: file's number of columns (begin at 1) + * IMPORT_DELIVERY_REF_COL: file's column where delivery reference is set (begin at 0) + * IMPORT_ORDER_REF_COL: file's column where order reference is set (begin at 0) + */ + const IMPORT_NB_COLS = 2; + const IMPORT_DELIVERY_REF_COL = 0; + const IMPORT_ORDER_REF_COL = 1; + + /** + * This method is called by the Delivery loop, to check if the current module has to be displayed to the customer. + * Override it to implements your delivery rules/ + * + * If you return true, the delivery method will de displayed to the customer + * If you return false, the delivery method will not be displayed + * + * @param Country $country the country to deliver to. + * + * @return boolean + * @throws PropelException + */ + public function isValidDelivery(Country $country) + { + $cartWeight = $this->getRequest()->getSession()->getSessionCart($this->getDispatcher())->getWeight(); + + $areaId = $country->getAreaId(); + + $prices = ColissimoPickupPointPriceSlicesQuery::create() + ->filterByAreaId($areaId) + ->findOne(); + + $freeShipping = ColissimoPickupPointFreeshippingQuery::create() + ->findOneByActive(1); + + /* check if Colissimo delivers the asked area*/ + if (null !== $prices || null !== $freeShipping) { + return true; + } + return false; + } + + /** + * @param $areaId + * @param $weight + * @param $cartAmount + * + * @return mixed + * @throws DeliveryException + */ + public static function getPostageAmount($areaId, $weight, $cartAmount = 0) + { + $freeshipping = ColissimoPickupPointFreeshippingQuery::create() + ->findOneById(1) + ->getActive() + ; + + $freeshippingFrom = ColissimoPickupPointFreeshippingQuery::create() + ->findOneById(1) + ->getFreeshippingFrom() + ; + + $postage = 0; + + if (!$freeshipping) { + $areaPrices = ColissimoPickupPointPriceSlicesQuery::create() + ->filterByAreaId($areaId) + ->filterByWeightMax($weight, Criteria::GREATER_EQUAL) + ->_or() + ->filterByWeightMax(null) + ->filterByPriceMax($cartAmount, Criteria::GREATER_EQUAL) + ->_or() + ->filterByPriceMax(null) + ->orderByWeightMax() + ->orderByPriceMax(); + + $firstPrice = $areaPrices->find() + ->getFirst(); + + if (null === $firstPrice) { + throw new DeliveryException('Colissimo delivery unavailable for your cart weight or delivery country'); + } + + /** If a min price for general freeshipping is defined and the cart reach this amount, return a postage of 0 */ + if (null !== $freeshippingFrom && $freeshippingFrom <= $cartAmount) { + $postage = 0; + return $postage; + } + + $areaFreeshipping = ColissimoPickupPointAreaFreeshippingQuery::create() + ->filterByAreaId($areaId) + ->findOne(); + + if ($areaFreeshipping) { + $areaFreeshipping = $areaFreeshipping->getCartAmount(); + } + + /** If a min price for area freeshipping is defined and the cart reach this amount, return a postage of 0 */ + if (null !== $areaFreeshipping && $areaFreeshipping <= $cartAmount) { + $postage = 0; + return $postage; + } + + $postage = $firstPrice->getPrice(); + } + return $postage; + } + + /** + * Calculate and return delivery price + * + * @param Country $country + * @return mixed + * @throws DeliveryException + * @throws PropelException + */ + public function getPostage(Country $country) + { + $request = $this->getRequest(); + + $cartWeight = $request->getSession()->getSessionCart($this->getDispatcher())->getWeight(); + $cartAmount = $request->getSession()->getSessionCart($this->getDispatcher())->getTaxedAmount($country); + + $areaIdArray = $this->getAllAreasForCountry($country); + if (empty($areaIdArray)) { + throw new DeliveryException('Your delivery country is not covered by Colissimo.'); + } + $postage = null; + + if (null === $postage = $this->getMinPostage($areaIdArray, $cartWeight, $cartAmount)) { + $postage = $this->getMinPostage($areaIdArray, $cartWeight, $cartAmount); + if (null === $postage) { + throw new DeliveryException('Colissimo delivery unavailable for your cart weight or delivery country'); + } + } + return $postage; + } + + + private function getMinPostage($areaIdArray, $cartWeight, $cartAmount) + { + $minPostage = null; + + foreach ($areaIdArray as $areaId) { + try { + $postage = self::getPostageAmount($areaId, $cartWeight, $cartAmount); + if ($minPostage === null || $postage < $minPostage) { + $minPostage = $postage; + if ($minPostage == 0) { + break; + } + } + } catch (\Exception $ex) { + } + } + + return $minPostage; + } + + /** + * Returns ids of area containing this country and covers by this module + * @param Country $country + * @return array Area ids + */ + private function getAllAreasForCountry(Country $country) + { + $areaArray = []; + + $sql = 'SELECT ca.area_id as area_id FROM country_area ca + INNER JOIN area_delivery_module adm ON (ca.area_id = adm.area_id AND adm.delivery_module_id = :p0) + WHERE ca.country_id = :p1'; + + $con = Propel::getConnection(); + + $stmt = $con->prepare($sql); + $stmt->bindValue(':p0', $this->getModuleModel()->getId(), PDO::PARAM_INT); + $stmt->bindValue(':p1', $country->getId(), PDO::PARAM_INT); + $stmt->execute(); + + while ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) { + $areaArray[] = $row['area_id']; + } + + return $areaArray; + } + + /** Return the module code */ + public function getCode() + { + return 'ColissimoPickupPoint'; + } + + /** + * Check if the config values exist, and creates them otherwise + */ + protected function checkModuleConfig() { + /** Colissimo Username / Account number */ + if (null === self::getConfigValue(self::COLISSIMO_USERNAME)) { + self::setConfigValue(self::COLISSIMO_USERNAME, ''); + } + + /** Colissimo password */ + if (null === self::getConfigValue(self::COLISSIMO_PASSWORD)) { + self::setConfigValue(self::COLISSIMO_PASSWORD, ''); + } + + /** Colissimo Google Map key */ + if (null === self::getConfigValue(self::COLISSIMO_GOOGLE_KEY)) { + self::setConfigValue(self::COLISSIMO_GOOGLE_KEY, ''); + } + + /** Colissimo Endpoint url for pickup point */ + if (null === self::getConfigValue(self::COLISSIMO_ENDPOINT)) { + self::setConfigValue(self::COLISSIMO_ENDPOINT, 'https://ws.colissimo.fr/pointretrait-ws-cxf/PointRetraitServiceWS/2.0?wsdl'); + } + } + + + public function postActivation(ConnectionInterface $con = null) + { + try { + // Security to not erase user config on reactivation + ColissimoPickupPointPriceSlicesQuery::create()->findOne(); + ColissimoPickupPointAreaFreeshippingQuery::create()->findOne(); + ColissimoPickupPointFreeshippingQuery::create()->findOne(); + } catch (\Exception $e) { + $database = new Database($con->getWrappedConnection()); + $database->insertSql(null, [__DIR__ . '/Config/thelia.sql', __DIR__ . '/Config/insert.sql']); + } + + if (!ColissimoPickupPointFreeshippingQuery::create()->filterById(1)->findOne()) { + ColissimoPickupPointFreeshippingQuery::create()->filterById(1)->findOneOrCreate()->setActive(0)->save(); + } + + $this->checkModuleConfig(); + + /** Insert the images from image folder if first module activation */ + $module = $this->getModuleModel(); + if (ModuleImageQuery::create()->filterByModule($module)->count() === 0) { + $this->deployImageFolder($module, sprintf('%s/images', __DIR__), $con); + } + } + + /** Return the module ID */ + public static function getModCode() + { + return ModuleQuery::create()->findOneByCode('ColissimoPickupPoint')->getId(); + } + + /** + * @inheritDoc + */ + public function update($currentVersion, $newVersion, ConnectionInterface $con = null) + { + $this->checkModuleConfig(); + + $finder = (new Finder) + ->files() + ->name('#.*?\.sql#') + ->sortByName() + ->in(__DIR__ . DS . 'Config' . DS . 'update'); + + $database = new Database($con); + + /** @var SplFileInfo $updateSQLFile */ + foreach ($finder as $updateSQLFile) { + if (version_compare($currentVersion, str_replace('.sql', '', $updateSQLFile->getFilename()), '<')) { + $database->insertSql( + null, + [ + $updateSQLFile->getPathname() + ] + ); + } + } + } + + public function getDeliveryMode() + { + return "pickup"; + } +} diff --git a/local/modules/ColissimoPickupPoint/Config/config.xml b/local/modules/ColissimoPickupPoint/Config/config.xml new file mode 100755 index 00000000..4b719487 --- /dev/null +++ b/local/modules/ColissimoPickupPoint/Config/config.xml @@ -0,0 +1,69 @@ + + + + + + + + + + + + + + + + + +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/local/modules/ColissimoPickupPoint/Config/insert.sql b/local/modules/ColissimoPickupPoint/Config/insert.sql new file mode 100644 index 00000000..da4a6891 --- /dev/null +++ b/local/modules/ColissimoPickupPoint/Config/insert.sql @@ -0,0 +1,30 @@ +# This is a fix for InnoDB in MySQL >= 4.1.x +# It "suspends judgement" for fkey relationships until are tables are set. +SET FOREIGN_KEY_CHECKS = 0; + +-- --------------------------------------------------------------------- +-- Mail templates for colissimo pickup point +-- --------------------------------------------------------------------- +-- First, delete existing entries +SET @var := 0; +SELECT @var := `id` FROM `message` WHERE name="mail_colissimo_pickup_point"; +DELETE FROM `message` WHERE `id`=@var; +-- Try if ON DELETE constraint isn't set +DELETE FROM `message_i18n` WHERE `id`=@var; + +-- Then add new entries +SELECT @max := MAX(`id`) FROM `message`; +SET @max := @max+1; +-- insert message +INSERT INTO `message` (`id`, `name`, `secured`) VALUES + (@max, + 'mail_colissimo_pickup_point', + '0' + ); + +-- and template fr_FR +INSERT INTO `message_i18n` (`id`, `locale`, `title`, `subject`, `text_message`, `html_message`) VALUES + (@max, 'fr_FR', 'Mail livraison Colissimo Point Relais', 'Suivi Colissimo Point Relais commande : {$order_ref}', '{loop type="customer" name="customer.order" current="false" id="$customer_id" backend_context="1"}\r\n{$LASTNAME} {$FIRSTNAME},\r\n{/loop}\r\nNous vous remercions de votre commande sur notre site {config key="store_name"}\r\nUn colis concernant votre commande {$order_ref} du {format_date date=$order_date} a quitté nos entrepôts pour être pris en charge par La Poste le {format_date date=$update_date}.\r\nSon numéro de suivi est le suivant : {$package}\r\nIl vous permet de suivre votre colis en ligne sur le site de La Poste : www.coliposte.net\r\nNous restons à votre disposition pour toute information complémentaire.\r\nCordialement', '{loop type="customer" name="customer.order" current="false" id="$customer_id" backend_context="1"}\r\n{$LASTNAME} {$FIRSTNAME},\r\n{/loop}\r\nNous vous remercions de votre commande sur notre site {config key="store_name"}\r\nUn colis concernant votre commande {$order_ref} du {format_date date=$order_date} a quitté nos entrepôts pour être pris en charge par La Poste le {format_date date=$update_date}.\r\nSon numéro de suivi est le suivant : {$package}\r\nIl vous permet de suivre votre colis en ligne sur le site de La Poste : www.coliposte.net\r\nIl vous sera, par ailleurs, très utile si vous étiez absent au moment de la livraison de votre colis : en fournissant ce numéro de Colissimo Suivi, vous pourrez retirer votre colis dans le bureau de Poste le plus proche.\r\nATTENTION ! Si vous ne trouvez pas l''avis de passage normalement déposé dans votre boîte aux lettres au bout de 48 Heures jours ouvrables, n''hésitez pas à aller le réclamer à votre bureau de Poste, muni de votre numéro de Colissimo Suivi.\r\nNous restons à votre disposition pour toute information complémentaire.\r\nCordialement'); + +# This restores the fkey checks, after having unset them earlier +SET FOREIGN_KEY_CHECKS = 1; diff --git a/local/modules/ColissimoPickupPoint/Config/module.xml b/local/modules/ColissimoPickupPoint/Config/module.xml new file mode 100755 index 00000000..80ab1e6f --- /dev/null +++ b/local/modules/ColissimoPickupPoint/Config/module.xml @@ -0,0 +1,18 @@ + + + ColissimoPickupPoint\ColissimoPickupPoint + + Colissimo Pickup Point Delivery + + + Livraison Colissimo en Point Retrait + + 1.0.2 + + Thelia + info@thelia.net + + delivery + 2.3.3 + other + diff --git a/local/modules/ColissimoPickupPoint/Config/routing.xml b/local/modules/ColissimoPickupPoint/Config/routing.xml new file mode 100755 index 00000000..fd379beb --- /dev/null +++ b/local/modules/ColissimoPickupPoint/Config/routing.xml @@ -0,0 +1,46 @@ + + + + + ColissimoPickupPoint\Controller\SliceController::saveSliceAction + + + ColissimoPickupPoint\Controller\SliceController::deleteSliceAction + + + + ColissimoPickupPoint\Controller\FreeShipping::toggleFreeShippingActivation + + + + ColissimoPickupPoint\Controller\FreeShipping::setAreaFreeShipping + + + + ColissimoPickupPoint\Controller\SaveConfig::save + + + + ColissimoPickupPoint\Controller\GetSpecificLocation::get + + [a-zA-Z\- ]+ + + + + ColissimoPickupPoint\Controller\GetSpecificLocation::getPointInfo + + + + ColissimoPickupPoint\Controller\GetSpecificLocation::search + + + + ColissimoPickupPoint\Controller\Export::export + + + + ColissimoPickupPoint:Import:import + + diff --git a/local/modules/ColissimoPickupPoint/Config/schema.xml b/local/modules/ColissimoPickupPoint/Config/schema.xml new file mode 100755 index 00000000..39eeed70 --- /dev/null +++ b/local/modules/ColissimoPickupPoint/Config/schema.xml @@ -0,0 +1,64 @@ + + + + + + + + + + + + + + + + + + + + + + + + +
    + + + + + + + + +
    + + + + + + + + + + + +
    + + + + + +
    + + + + + + + + +
    + + +
    diff --git a/local/modules/ColissimoPickupPoint/Config/sqldb.map b/local/modules/ColissimoPickupPoint/Config/sqldb.map new file mode 100644 index 00000000..63a93baa --- /dev/null +++ b/local/modules/ColissimoPickupPoint/Config/sqldb.map @@ -0,0 +1,2 @@ +# Sqlfile -> Database map +thelia.sql=thelia diff --git a/local/modules/ColissimoPickupPoint/Config/thelia.sql b/local/modules/ColissimoPickupPoint/Config/thelia.sql new file mode 100644 index 00000000..ad870c65 --- /dev/null +++ b/local/modules/ColissimoPickupPoint/Config/thelia.sql @@ -0,0 +1,120 @@ + +# This is a fix for InnoDB in MySQL >= 4.1.x +# It "suspends judgement" for fkey relationships until are tables are set. +SET FOREIGN_KEY_CHECKS = 0; + +-- --------------------------------------------------------------------- +-- address_colissimo_pickup_point +-- --------------------------------------------------------------------- + +DROP TABLE IF EXISTS `address_colissimo_pickup_point`; + +CREATE TABLE `address_colissimo_pickup_point` +( + `id` INTEGER NOT NULL, + `title_id` INTEGER NOT NULL, + `company` VARCHAR(255), + `firstname` VARCHAR(255) NOT NULL, + `lastname` VARCHAR(255) NOT NULL, + `address1` VARCHAR(255) NOT NULL, + `address2` VARCHAR(255) NOT NULL, + `address3` VARCHAR(255) NOT NULL, + `zipcode` VARCHAR(10) NOT NULL, + `city` VARCHAR(255) NOT NULL, + `country_id` INTEGER NOT NULL, + `code` VARCHAR(10) NOT NULL, + `type` VARCHAR(10) NOT NULL, + `cellphone` VARCHAR(20), + PRIMARY KEY (`id`), + INDEX `FI_address_colissimo_pickup_point_customer_title_id` (`title_id`), + INDEX `FI_address_colissimo_pickup_point_country_id` (`country_id`), + CONSTRAINT `fk_address_colissimo_pickup_point_customer_title_id` + FOREIGN KEY (`title_id`) + REFERENCES `customer_title` (`id`) + ON UPDATE RESTRICT + ON DELETE RESTRICT, + CONSTRAINT `fk_address_colissimo_pickup_point_country_id` + FOREIGN KEY (`country_id`) + REFERENCES `country` (`id`) + ON UPDATE RESTRICT + ON DELETE RESTRICT +) ENGINE=InnoDB; + +-- --------------------------------------------------------------------- +-- order_address_colissimo_pickup_point +-- --------------------------------------------------------------------- + +DROP TABLE IF EXISTS `order_address_colissimo_pickup_point`; + +CREATE TABLE `order_address_colissimo_pickup_point` +( + `id` INTEGER NOT NULL, + `code` VARCHAR(10) NOT NULL, + `type` VARCHAR(10) NOT NULL, + PRIMARY KEY (`id`), + CONSTRAINT `fk_order_address_colissimo_pickup_point_order_address_id` + FOREIGN KEY (`id`) + REFERENCES `order_address` (`id`) + ON UPDATE CASCADE + ON DELETE CASCADE +) ENGINE=InnoDB; + +-- --------------------------------------------------------------------- +-- colissimo_pickup_point_price_slices +-- --------------------------------------------------------------------- + +DROP TABLE IF EXISTS `colissimo_pickup_point_price_slices`; + +CREATE TABLE `colissimo_pickup_point_price_slices` +( + `id` INTEGER NOT NULL AUTO_INCREMENT, + `area_id` INTEGER NOT NULL, + `weight_max` FLOAT, + `price_max` FLOAT, + `franco_min_price` FLOAT, + `price` FLOAT NOT NULL, + PRIMARY KEY (`id`), + INDEX `FI_colissimo_pickup_point_price_slices_area_id` (`area_id`), + CONSTRAINT `fk_colissimo_pickup_point_price_slices_area_id` + FOREIGN KEY (`area_id`) + REFERENCES `area` (`id`) + ON UPDATE RESTRICT + ON DELETE RESTRICT +) ENGINE=InnoDB; + +-- --------------------------------------------------------------------- +-- colissimo_pickup_point_freeshipping +-- --------------------------------------------------------------------- + +DROP TABLE IF EXISTS `colissimo_pickup_point_freeshipping`; + +CREATE TABLE `colissimo_pickup_point_freeshipping` +( + `id` INTEGER NOT NULL, + `active` TINYINT(1) DEFAULT 0, + `freeshipping_from` DECIMAL(18,2), + PRIMARY KEY (`id`) +) ENGINE=InnoDB; + +-- --------------------------------------------------------------------- +-- colissimo_pickup_point_area_freeshipping +-- --------------------------------------------------------------------- + +DROP TABLE IF EXISTS `colissimo_pickup_point_area_freeshipping`; + +CREATE TABLE `colissimo_pickup_point_area_freeshipping` +( + `id` INTEGER NOT NULL AUTO_INCREMENT, + `area_id` INTEGER NOT NULL, + `cart_amount` DECIMAL(18,2) DEFAULT 0.00, + PRIMARY KEY (`id`), + INDEX `FI_colissimo_pickup_point_area_freeshipping_pr_area_id` (`area_id`), + CONSTRAINT `fk_colissimo_pickup_point_area_freeshipping_pr_area_id` + FOREIGN KEY (`area_id`) + REFERENCES `area` (`id`) + ON UPDATE RESTRICT + ON DELETE RESTRICT +) ENGINE=InnoDB; + +# This restores the fkey checks, after having unset them earlier +SET FOREIGN_KEY_CHECKS = 1; diff --git a/local/modules/ColissimoPickupPoint/Config/update/1.0.1.sql b/local/modules/ColissimoPickupPoint/Config/update/1.0.1.sql new file mode 100644 index 00000000..e69de29b diff --git a/local/modules/ColissimoPickupPoint/Controller/Export.php b/local/modules/ColissimoPickupPoint/Controller/Export.php new file mode 100755 index 00000000..6324562f --- /dev/null +++ b/local/modules/ColissimoPickupPoint/Controller/Export.php @@ -0,0 +1,249 @@ +. */ +/* */ +/*************************************************************************************/ + +namespace ColissimoPickupPoint\Controller; + +use Propel\Runtime\ActiveQuery\Criteria; +use ColissimoPickupPoint\Form\ExportOrder; +use ColissimoPickupPoint\Format\CSV; +use ColissimoPickupPoint\Format\CSVLine; +use ColissimoPickupPoint\Model\OrderAddressColissimoPickupPointQuery; +use ColissimoPickupPoint\ColissimoPickupPoint; +use Symfony\Component\Config\Definition\Exception\Exception; +use Thelia\Controller\Admin\BaseAdminController; +use Thelia\Core\Event\TheliaEvents; +use Thelia\Core\HttpFoundation\Response; +use Thelia\Model\Base\CountryQuery; +use Thelia\Model\ConfigQuery; +use Thelia\Model\CustomerTitleI18nQuery; +use Thelia\Model\OrderAddressQuery; +use Thelia\Model\OrderQuery; +use Thelia\Core\Event\Order\OrderEvent; +use Thelia\Model\OrderStatus; +use Thelia\Model\OrderStatusQuery; +use Thelia\Core\Security\Resource\AdminResources; +use Thelia\Core\Security\AccessManager; + +/** + * Class Export + * @package ColissimoPickupPoint\Controller + * @author Thelia + */ +class Export extends BaseAdminController +{ + const CSV_SEPARATOR = ';'; + + const DEFAULT_PHONE = '0100000000'; + const DEFAULT_CELLPHONE = '0600000000'; + + public function export() + { + if (null !== $response = $this->checkAuth(array(AdminResources::MODULE), array('ColissimoPickupPoint'), AccessManager::UPDATE)) { + return $response; + } + + $csv = new CSV(self::CSV_SEPARATOR); + + try { + $form = new ExportOrder($this->getRequest()); + $vform = $this->validateForm($form); + + // Check status_id + $status_id = $vform->get('new_status_id')->getData(); + if (!preg_match('#^nochange|processing|sent$#',$status_id)) { + throw new Exception('Bad value for new_status_id field'); + } + + $status = OrderStatusQuery::create() + ->filterByCode( + array( + OrderStatus::CODE_PAID, + OrderStatus::CODE_PROCESSING, + OrderStatus::CODE_SENT + ), + Criteria::IN + ) + ->find() + ->toArray('code') + ; + + $query = OrderQuery::create() + ->filterByDeliveryModuleId(ColissimoPickupPoint::getModCode()) + ->filterByStatusId( + array( + $status[OrderStatus::CODE_PAID]['Id'], + $status[OrderStatus::CODE_PROCESSING]['Id']), + Criteria::IN + ) + ->find(); + + // check form && exec csv + /** @var \Thelia\Model\Order $order */ + foreach ($query as $order) { + $value = $vform->get('order_'.$order->getId())->getData(); + + // If checkbox is checked + if ($value) { + /** + * Retrieve user with the order + */ + $customer = $order->getCustomer(); + + /** + * Retrieve address with the order + */ + $address = OrderAddressQuery::create() + ->findPk($order->getDeliveryOrderAddressId()); + + if ($address === null) { + throw new Exception("Could not find the order's invoice address"); + } + + /** + * Retrieve country with the address + */ + $country = CountryQuery::create() + ->findPk($address->getCountryId()); + + if ($country === null) { + throw new Exception("Could not find the order's country"); + } + + /** + * Retrieve Title + */ + $title = CustomerTitleI18nQuery::create() + ->filterById($customer->getTitleId()) + ->findOneByLocale( + $this->getSession() + ->getAdminEditionLang() + ->getLocale() + ); + + /** + * Get user's phone & cellphone + * First get invoice address phone, + * If empty, try to get default address' phone. + * If still empty, set default value + */ + $phone = $address->getPhone(); + if (empty($phone)) { + $phone = $customer->getDefaultAddress()->getPhone(); + + if (empty($phone)) { + $phone = self::DEFAULT_PHONE; + } + } + + /** + * Cellphone + */ + $cellphone = $customer->getDefaultAddress()->getCellphone(); + + if (empty($cellphone)) { + $cellphone = self::DEFAULT_CELLPHONE; + } + + /** + * Compute package weight + */ + $weight = 0; + if ($vform->get('order_weight_'.$order->getId())->getData() == 0) { + /** @var \Thelia\Model\OrderProduct $product */ + foreach ($order->getOrderProducts() as $product) { + $weight+=(double) $product->getWeight() * $product->getQuantity(); + } + } else { + $weight = $vform->get('order_weight_'.$order->getId())->getData(); + } + + /** + * Get relay ID + */ + $relay_id = OrderAddressColissimoPickupPointQuery::create() + ->findPk($order->getDeliveryOrderAddressId()); + + /** + * Get store's name + */ + $store_name = ConfigQuery::read('store_name'); + /** + * Write CSV line + */ + $csv->addLine( + CSVLine::create( + array( + $address->getFirstname(), + $address->getLastname(), + $address->getCompany(), + $address->getAddress1(), + $address->getAddress2(), + $address->getAddress3(), + $address->getZipcode(), + $address->getCity(), + $country->getIsoalpha2(), + $phone, + $cellphone, + $order->getRef(), + $title->getShort(), + // the Expeditor software used to accept a relay id of 0, but no longer does + ($relay_id !== null) ? ($relay_id->getCode() == 0) ? '' : $relay_id->getCode() : 0, + $customer->getEmail(), + $weight, + $store_name, + ($relay_id !== null) ? $relay_id->getType() : 0 + ) + ) + ); + + /** + * Then update order's status if necessary + */ + if ($status_id === 'processing') { + $event = new OrderEvent($order); + $event->setStatus($status[OrderStatus::CODE_PROCESSING]['Id']); + $this->dispatch(TheliaEvents::ORDER_UPDATE_STATUS, $event); + } elseif ($status_id === 'sent') { + $event = new OrderEvent($order); + $event->setStatus($status[OrderStatus::CODE_SENT]['Id']); + $this->dispatch(TheliaEvents::ORDER_UPDATE_STATUS, $event); + } + + } + } + + } catch (\Exception $e) { + return Response::create($e->getMessage(),500); + } + + return Response::create( + utf8_decode($csv->parse()), + 200, + array( + 'Content-Encoding' => 'ISO-8889-1', + 'Content-Type' => 'application/csv-tab-delimited-table', + 'Content-disposition' => 'filename=expeditor_thelia.csv' + ) + ); + } +} diff --git a/local/modules/ColissimoPickupPoint/Controller/FreeShipping.php b/local/modules/ColissimoPickupPoint/Controller/FreeShipping.php new file mode 100755 index 00000000..0a81da5b --- /dev/null +++ b/local/modules/ColissimoPickupPoint/Controller/FreeShipping.php @@ -0,0 +1,150 @@ +. */ +/* */ +/*************************************************************************************/ + +namespace ColissimoPickupPoint\Controller; + +use ColissimoPickupPoint\Form\FreeShippingForm; +use ColissimoPickupPoint\Model\ColissimoPickupPointAreaFreeshipping; +use ColissimoPickupPoint\Model\ColissimoPickupPointAreaFreeshippingQuery; +use ColissimoPickupPoint\Model\ColissimoPickupPointFreeshipping; +use ColissimoPickupPoint\Model\ColissimoPickupPointFreeshippingQuery; +use Symfony\Component\HttpFoundation\JsonResponse; +use Thelia\Controller\Admin\BaseAdminController; +use Thelia\Core\HttpFoundation\Response; + +use Thelia\Core\Security\Resource\AdminResources; +use Thelia\Core\Security\AccessManager; +use Thelia\Model\AreaQuery; + +class FreeShipping extends BaseAdminController +{ + /** + * Toggle on or off free shipping for all areas without minimum cart amount, or set the minimum cart amount to reach for all areas to get free shipping + * + * @return mixed|JsonResponse|Response|null + */ + public function toggleFreeShippingActivation() + { + if (null !== $response = $this + ->checkAuth(array(AdminResources::MODULE), array('ColissimoPickupPoint'), AccessManager::UPDATE)) { + return $response; + } + + $form = new FreeShippingForm($this->getRequest()); + $response=null; + + try { + $vform = $this->validateForm($form); + $freeshipping = $vform->get('freeshipping')->getData(); + $freeshippingFrom = $vform->get('freeshipping_from')->getData(); + + if (null === $deliveryFreeshipping = ColissimoPickupPointFreeshippingQuery::create()->findOneById(1)){ + $deliveryFreeshipping = new ColissimoPickupPointFreeshipping(); + } + + $deliveryFreeshipping + ->setActive($freeshipping) + ->setFreeshippingFrom($freeshippingFrom) + ->save() + ; + + $response = $this->generateRedirectFromRoute( + 'admin.module.configure', + array(), + array ( + 'current_tab'=> 'prices_slices_tab', + 'module_code'=> 'ColissimoPickupPoint', + '_controller' => 'Thelia\\Controller\\Admin\\ModuleController::configureAction', + 'price_error_id' => null, + 'price_error' => null + ) + ); + } catch (\Exception $e) { + $response = JsonResponse::create(array('error' => $e->getMessage()), 500); + } + + return $response; + } + + /** + * @return mixed|null|\Symfony\Component\HttpFoundation\Response + */ + public function setAreaFreeShipping() + { + if (null !== $response = $this + ->checkAuth(array(AdminResources::MODULE), array('ColissimoPickupPoint'), AccessManager::UPDATE)) { + return $response; + } + + $data = $this->getRequest()->request; + + try { + $data = $this->getRequest()->request; + + $colissimo_pickup_area_id = $data->get('area-id'); + $cartAmount = $data->get('cart-amount'); + + if ($cartAmount < 0 || $cartAmount === '') { + $cartAmount = null; + } + + $aeraQuery = AreaQuery::create()->findOneById($colissimo_pickup_area_id); + if (null === $aeraQuery) { + return null; + } + + $colissimoPickupPointAreaFreeshippingQuery = ColissimoPickupPointAreaFreeshippingQuery::create() + ->filterByAreaId($colissimo_pickup_area_id) + ->findOne(); + + if (null === $colissimoPickupPointAreaFreeshippingQuery) { + $colissimoPickupPointFreeShipping = new ColissimoPickupPointAreaFreeshipping(); + + $colissimoPickupPointFreeShipping + ->setAreaId($colissimo_pickup_area_id) + ->setCartAmount($cartAmount) + ->save(); + } + + $cartAmountQuery = ColissimoPickupPointAreaFreeshippingQuery::create() + ->filterByAreaId($colissimo_pickup_area_id) + ->findOneOrCreate() + ->setCartAmount($cartAmount) + ->save(); + + } catch (\Exception $e) { + } + + return $this->generateRedirectFromRoute( + 'admin.module.configure', + array(), + array( + 'current_tab' => 'prices_slices_tab', + 'module_code' => 'ColissimoPickupPoint', + '_controller' => 'Thelia\\Controller\\Admin\\ModuleController::configureAction', + 'price_error_id' => null, + 'price_error' => null + ) + ); + } +} diff --git a/local/modules/ColissimoPickupPoint/Controller/GetSpecificLocation.php b/local/modules/ColissimoPickupPoint/Controller/GetSpecificLocation.php new file mode 100755 index 00000000..2b38ac51 --- /dev/null +++ b/local/modules/ColissimoPickupPoint/Controller/GetSpecificLocation.php @@ -0,0 +1,106 @@ +. */ +/* */ +/*************************************************************************************/ + +namespace ColissimoPickupPoint\Controller; + +use ColissimoPickupPoint\ColissimoPickupPoint; +use ColissimoPickupPoint\WebService\FindById; +use Exception; +use Symfony\Component\HttpFoundation\JsonResponse; +use Thelia\Controller\Front\BaseFrontController; +use Thelia\Core\HttpFoundation\Response; +use Thelia\Core\Template\ParserInterface; +use Thelia\Core\Template\TemplateDefinition; +use Thelia\Model\ConfigQuery; + +/** + * Class SearchCityController + * @package IciRelais\Controller + * @author Thelia + */ +class GetSpecificLocation extends BaseFrontController +{ + public function get($countryid, $zipcode, $city, $address="") + { + $content = $this->renderRaw( + 'getSpecificLocationColissimoPickupPoint', + array( + '_countryid_' => $countryid, + '_zipcode_' => $zipcode, + '_city_' => $city, + '_address_' => $address + ) + ); + $response = new Response($content, 200, $headers = array('Content-Type' => 'application/json')); + + return $response; + } + + public function getPointInfo($point_id) + { + $req = new FindById(); + + $req->setId($point_id) + ->setLangue('FR') + ->setDate(date('d/m/Y')) + ->setAccountNumber(ColissimoPickupPoint::getConfigValue(ColissimoPickupPoint::COLISSIMO_USERNAME)) + ->setPassword(ColissimoPickupPoint::getConfigValue(ColissimoPickupPoint::COLISSIMO_PASSWORD)) + ; + + $response = $req->exec(); + + $response = new JsonResponse($response); + + return $response; + } + + public function search() + { + $countryid = $this->getRequest()->query->get('countryid'); + $zipcode = $this->getRequest()->query->get('zipcode'); + $city = $this->getRequest()->query->get('city'); + $addressId = $this->getRequest()->query->get('address'); + + return $this->get($countryid, $zipcode, $city, $addressId); + } + + /** + * @param null $template + * @return ParserInterface instance parser + * @throws Exception + */ + protected function getParser($template = null) + { + $parser = $this->container->get('thelia.parser'); + + // Define the template that should be used + $parser->setTemplateDefinition( + new TemplateDefinition( + 'default', + TemplateDefinition::FRONT_OFFICE + ) + ); + + return $parser; + } +} diff --git a/local/modules/ColissimoPickupPoint/Controller/ImportController.php b/local/modules/ColissimoPickupPoint/Controller/ImportController.php new file mode 100644 index 00000000..9781d8da --- /dev/null +++ b/local/modules/ColissimoPickupPoint/Controller/ImportController.php @@ -0,0 +1,129 @@ + + */ +class ImportController extends BaseAdminController +{ + public function importAction() + { + $i = 0; + + $con = Propel::getWriteConnection(OrderTableMap::DATABASE_NAME); + $con->beginTransaction(); + + $form = $this->createForm('colissimo.pickup.point.import'); + + try { + $vForm = $this->validateForm($form); + + // Get file + $importedFile = $vForm->getData()['import_file']; + + // Check extension + if (strtolower($importedFile->getClientOriginalExtension()) !='csv') { + throw new FormValidationException( + Translator::getInstance()->trans('Bad file format. CSV expected.', + [], + ColissimoPickupPoint::DOMAIN) + ); + } + + $csvData = file_get_contents($importedFile); + $lines = explode(PHP_EOL, $csvData); + + // For each line, parse columns + foreach ($lines as $line) { + $parsedLine = str_getcsv($line, ";"); + + // Get delivery and order ref + $deliveryRef = $parsedLine[ColissimoPickupPoint::IMPORT_DELIVERY_REF_COL]; + $orderRef = $parsedLine[ColissimoPickupPoint::IMPORT_ORDER_REF_COL]; + + // Save delivery ref if there is one + if (!empty($deliveryRef)) { + $this->importDeliveryRef($deliveryRef, $orderRef, $i); + } + } + + $con->commit(); + + // Get number of affected rows to display + $this->getSession()->getFlashBag()->add( + 'import-result', + Translator::getInstance()->trans( + 'Operation successful. %i orders affected.', + ['%i' => $i], + ColissimoPickupPoint::DOMAIN + ) + ); + + // Redirect + return $this->generateRedirect(URL::getInstance()->absoluteUrl($form->getSuccessUrl(), ['current_tab' => 'import'])); + } catch (FormValidationException $e) { + $con->rollback(); + + $this->setupFormErrorContext(null, $e->getMessage(), $form); + + return $this->render( + 'module-configure', + [ + 'module_code' => ColissimoPickupPoint::getModuleCode(), + 'current_tab' => 'import' + ] + ); + } + } + + /** + * Update order's delivery ref + * + * @param string $deliveryRef + * @param string $orderRef + * @param int $i + * @throws PropelException + */ + public function importDeliveryRef($deliveryRef, $orderRef, &$i) + { + // Check if the order exists + if (null !== $order = OrderQuery::create()->findOneByRef($orderRef)) { + $event = new OrderEvent($order); + + // Check if delivery refs are different + if ($order->getDeliveryRef() != $deliveryRef) { + $event->setDeliveryRef($deliveryRef); + $this->getDispatcher()->dispatch(TheliaEvents::ORDER_UPDATE_DELIVERY_REF, $event); + + $sentStatusId = OrderStatusQuery::create() + ->filterByCode('sent') + ->select('ID') + ->findOne(); + + // Set 'sent' order status if not already sent + if ($sentStatusId != null && $order->getStatusId() != $sentStatusId) { + $event->setStatus($sentStatusId); + $this->getDispatcher()->dispatch(TheliaEvents::ORDER_UPDATE_STATUS, $event); + } + + $i++; + } + } + } +} diff --git a/local/modules/ColissimoPickupPoint/Controller/SaveConfig.php b/local/modules/ColissimoPickupPoint/Controller/SaveConfig.php new file mode 100755 index 00000000..db5d1839 --- /dev/null +++ b/local/modules/ColissimoPickupPoint/Controller/SaveConfig.php @@ -0,0 +1,51 @@ +checkAuth(array(AdminResources::MODULE), array('ColissimoPickupPoint'), AccessManager::UPDATE)) { + return $response; + } + + $form = new ConfigureColissimoPickupPoint($this->getRequest()); + try { + $vform = $this->validateForm($form); + + ColissimoPickupPoint::setConfigValue(ColissimoPickupPoint::COLISSIMO_USERNAME, $vform->get(ColissimoPickupPoint::COLISSIMO_USERNAME)->getData()); + ColissimoPickupPoint::setConfigValue(ColissimoPickupPoint::COLISSIMO_PASSWORD, $vform->get(ColissimoPickupPoint::COLISSIMO_PASSWORD)->getData()); + ColissimoPickupPoint::setConfigValue(ColissimoPickupPoint::COLISSIMO_GOOGLE_KEY, $vform->get(ColissimoPickupPoint::COLISSIMO_GOOGLE_KEY)->getData()); + ColissimoPickupPoint::setConfigValue(ColissimoPickupPoint::COLISSIMO_ENDPOINT, $vform->get(ColissimoPickupPoint::COLISSIMO_ENDPOINT)->getData()); + + return $this->generateRedirect( + URL::getInstance()->absoluteUrl('/admin/module/ColissimoPickupPoint', ['current_tab' => 'configure']) + ); + } catch (\Exception $e) { + $this->setupFormErrorContext( + Translator::getInstance()->trans('Colissimo Pickup Point update config'), + $e->getMessage(), + $form, + $e + ); + + return $this->render( + 'module-configure', + [ + 'module_code' => 'ColissimoPickupPoint', + 'current_tab' => 'configure', + ] + ); + } + } +} diff --git a/local/modules/ColissimoPickupPoint/Controller/SliceController.php b/local/modules/ColissimoPickupPoint/Controller/SliceController.php new file mode 100644 index 00000000..dd7ca419 --- /dev/null +++ b/local/modules/ColissimoPickupPoint/Controller/SliceController.php @@ -0,0 +1,180 @@ +checkAuth(array(AdminResources::MODULE), ['ColissimoPickupPoint'], AccessManager::UPDATE)) { + return $response; + } + + $this->checkXmlHttpRequest(); + + $responseData = [ + 'success' => false, + 'message' => '', + 'slice' => null + ]; + + $messages = []; + $response = null; + + try { + $requestData = $this->getRequest()->request; + + if (0 !== $id = (int)$requestData->get('id', 0)) { + $slice = ColissimoPickupPointPriceSlicesQuery::create()->findPk($id); + } else { + $slice = new ColissimoPickupPointPriceSlices(); + } + + + if (0 !== $areaId = (int)$requestData->get('area', 0)) { + $slice->setAreaId($areaId); + } else { + $messages[] = $this->getTranslator()->trans( + 'The area is not valid', + [], + ColissimoPickupPoint::DOMAIN + ); + } + + $requestPriceMax = $requestData->get('priceMax', null); + $requestWeightMax = $requestData->get('weightMax', null); + + if (empty($requestPriceMax) && empty($requestWeightMax)) { + $messages[] = $this->getTranslator()->trans( + 'You must specify at least a price max or a weight max value.', + [], + ColissimoPickupPoint::DOMAIN + ); + } else { + if (!empty($requestPriceMax)) { + $priceMax = $this->getFloatVal($requestPriceMax); + if (0 < $priceMax) { + $slice->setPriceMax($priceMax); + } else { + $messages[] = $this->getTranslator()->trans( + 'The price max value is not valid', + [], + ColissimoPickupPoint::DOMAIN + ); + } + } else { + $slice->setPriceMax(null); + } + + if (!empty($requestWeightMax)) { + $weightMax = $this->getFloatVal($requestWeightMax); + if (0 < $weightMax) { + $slice->setWeightMax($weightMax); + } else { + $messages[] = $this->getTranslator()->trans( + 'The weight max value is not valid', + [], + ColissimoPickupPoint::DOMAIN + ); + } + } else { + $slice->setWeightMax(null); + } + } + + + + $price = $this->getFloatVal($requestData->get('price', 0)); + if (0 <= $price) { + $slice->setPrice($price); + } else { + $messages[] = $this->getTranslator()->trans( + 'The price value is not valid', + [], + ColissimoPickupPoint::DOMAIN + ); + } + + if (0 === count($messages)) { + $slice->save(); + $messages[] = $this->getTranslator()->trans( + 'Your slice has been saved', + [], + ColissimoPickupPoint::DOMAIN + ); + + $responseData['success'] = true; + $responseData['slice'] = $slice->toArray(TableMap::TYPE_STUDLYPHPNAME); + } + } catch (\Exception $e) { + $message[] = $e->getMessage(); + } + + $responseData['message'] = $messages; + + return $this->jsonResponse(json_encode($responseData)); + } + + protected function getFloatVal($val, $default = -1) + { + if (preg_match("#^([0-9\.,]+)$#", $val, $match)) { + $val = $match[0]; + if (strstr($val, ",")) { + $val = str_replace(".", "", $val); + $val = str_replace(",", ".", $val); + } + $val = (float)$val; + + return $val; + } + + return $default; + } + + public function deleteSliceAction() + { + $response = $this->checkAuth([], ['ColissimoPickupPoint'], AccessManager::DELETE); + + if (null !== $response) { + return $response; + } + + $this->checkXmlHttpRequest(); + + $responseData = [ + 'success' => false, + 'message' => '', + 'slice' => null + ]; + + $response = null; + + try { + $requestData = $this->getRequest()->request; + + if (0 !== $id = (int)$requestData->get('id', 0)) { + $slice = ColissimoPickupPointPriceSlicesQuery::create()->findPk($id); + $slice->delete(); + $responseData['success'] = true; + } else { + $responseData['message'] = $this->getTranslator()->trans( + 'The slice has not been deleted', + [], + ColissimoPickupPoint::DOMAIN + ); + } + } catch (\Exception $e) { + $responseData['message'] = $e->getMessage(); + } + + return $this->jsonResponse(json_encode($responseData)); + } +} diff --git a/local/modules/ColissimoPickupPoint/Form/AddPriceForm.php b/local/modules/ColissimoPickupPoint/Form/AddPriceForm.php new file mode 100644 index 00000000..0a7d3d51 --- /dev/null +++ b/local/modules/ColissimoPickupPoint/Form/AddPriceForm.php @@ -0,0 +1,85 @@ +formBuilder + ->add('area', 'integer', array( + 'constraints' => array( + new Constraints\NotBlank(), + new Constraints\Callback(array( + 'methods' => array( + array($this, + 'verifyAreaExist') + ) + )) + ) + )) + ->add('weight', 'number', array( + 'constraints' => array( + new Constraints\NotBlank(), + new Constraints\Callback(array( + 'methods' => array( + array($this, + 'verifyValidWeight') + ) + )) + ) + )) + ->add('price', 'number', array( + 'constraints' => array( + new Constraints\NotBlank(), + new Constraints\Callback(array( + 'methods' => array( + array($this, + 'verifyValidPrice') + ) + )) + ) + )) + ->add('franco', 'number', array()) + ; + } + + public function verifyAreaExist($value, ExecutionContextInterface $context) + { + $area = AreaQuery::create()->findPk($value); + if (null === $area) { + $context->addViolation(Translator::getInstance()->trans("This area doesn't exists.", [], ColissimoPickupPoint::DOMAIN)); + } + } + + public function verifyValidWeight($value, ExecutionContextInterface $context) + { + if (!preg_match("#^\d+\.?\d*$#", $value)) { + $context->addViolation(Translator::getInstance()->trans("The weight value is not valid.", [], ColissimoPickupPoint::DOMAIN)); + } + + if ($value < 0) { + $context->addViolation(Translator::getInstance()->trans("The weight value must be superior to 0.", [], ColissimoPickupPoint::DOMAIN)); + } + } + + public function verifyValidPrice($value, ExecutionContextInterface $context) + { + if (!preg_match("#^\d+\.?\d*$#", $value)) { + $context->addViolation(Translator::getInstance()->trans("The price value is not valid.", [], ColissimoPickupPoint::DOMAIN)); + } + } + + public function getName() + { + return 'colissimo_pickup_point_price_slices_create'; + } +} \ No newline at end of file diff --git a/local/modules/ColissimoPickupPoint/Form/ConfigureColissimoPickupPoint.php b/local/modules/ColissimoPickupPoint/Form/ConfigureColissimoPickupPoint.php new file mode 100755 index 00000000..b759f881 --- /dev/null +++ b/local/modules/ColissimoPickupPoint/Form/ConfigureColissimoPickupPoint.php @@ -0,0 +1,121 @@ +. */ +/* */ +/*************************************************************************************/ + +namespace ColissimoPickupPoint\Form; + +use ColissimoPickupPoint\ColissimoPickupPoint; +use Symfony\Component\Form\Extension\Core\Type\CheckboxType; +use Symfony\Component\Form\Extension\Core\Type\TextType; +use Symfony\Component\Validator\Constraints\NotBlank; +use Symfony\Component\Validator\Constraints\Url; +use Thelia\Core\Translation\Translator; +use Thelia\Form\BaseForm; +use Thelia\Model\ConfigQuery; + +/** + * Class ConfigureColissimoPickupPoint + * @package ColissimoPickupPoint\Form + * @author Thelia + */ +class ConfigureColissimoPickupPoint extends BaseForm +{ + /** + * + * in this function you add all the fields you need for your Form. + * Form this you have to call add method on $this->formBuilder attribute : + * + * $this->formBuilder->add("name", "text") + * ->add("email", "email", array( + * "attr" => array( + * "class" => "field" + * ), + * "label" => "email", + * "constraints" => array( + * new \Symfony\Component\Validator\Constraints\NotBlank() + * ) + * ) + * ) + * ->add('age', 'integer'); + * + * @return null + */ + protected function buildForm() + { + $translator = Translator::getInstance(); + $this->formBuilder + ->add( + ColissimoPickupPoint::COLISSIMO_USERNAME, + TextType::class, + [ + 'constraints' => [new NotBlank()], + 'data' => ColissimoPickupPoint::getConfigValue(ColissimoPickupPoint::COLISSIMO_USERNAME), + 'label' => $translator->trans('Account number', [], ColissimoPickupPoint::DOMAIN), + 'label_attr' => ['for' => ColissimoPickupPoint::COLISSIMO_USERNAME] + ] + ) + ->add( + ColissimoPickupPoint::COLISSIMO_PASSWORD, + TextType::class, + [ + 'constraints' => [new NotBlank()], + 'data' => ColissimoPickupPoint::getConfigValue(ColissimoPickupPoint::COLISSIMO_PASSWORD), + 'label' => $translator->trans('Password', [], ColissimoPickupPoint::DOMAIN), + 'label_attr' => ['for' => ColissimoPickupPoint::COLISSIMO_PASSWORD] + ] + ) + ->add( + ColissimoPickupPoint::COLISSIMO_ENDPOINT, + TextType::class, + [ + 'constraints' => [ + new NotBlank(), + new Url([ + 'protocols' => ['https', 'http'] + ]) + ], + 'data' => ColissimoPickupPoint::getConfigValue(ColissimoPickupPoint::COLISSIMO_ENDPOINT), + 'label' => $translator->trans('Colissimo URL prod', [], ColissimoPickupPoint::DOMAIN), + 'label_attr' => ['for' => ColissimoPickupPoint::COLISSIMO_ENDPOINT] + ] + ) + ->add( + ColissimoPickupPoint::COLISSIMO_GOOGLE_KEY, + TextType::class, + [ + 'constraints' => [], + 'data' => ColissimoPickupPoint::getConfigValue(ColissimoPickupPoint::COLISSIMO_GOOGLE_KEY), + 'label' => $translator->trans('Google map API key', [], ColissimoPickupPoint::DOMAIN), + 'label_attr' => ['for' => ColissimoPickupPoint::COLISSIMO_GOOGLE_KEY] + ] + ) + ; + } + + /** + * @return string the name of you form. This name must be unique + */ + public function getName() + { + return 'configurecolissimopickuppoint'; + } +} diff --git a/local/modules/ColissimoPickupPoint/Form/ExportOrder.php b/local/modules/ColissimoPickupPoint/Form/ExportOrder.php new file mode 100755 index 00000000..46ec31f9 --- /dev/null +++ b/local/modules/ColissimoPickupPoint/Form/ExportOrder.php @@ -0,0 +1,121 @@ +. */ +/* */ +/*************************************************************************************/ + +namespace ColissimoPickupPoint\Form; +use Propel\Runtime\ActiveQuery\Criteria; +use ColissimoPickupPoint\ColissimoPickupPoint; +use Thelia\Form\BaseForm; +use Thelia\Model\Base\OrderQuery; +use Thelia\Core\Translation\Translator; +use Thelia\Model\Order; +use Thelia\Model\OrderStatusQuery; +use Thelia\Model\OrderStatus; + +/** + * Class ExportOrder + * @package ColissimoPickupPoint\Form + * @author Thelia + */ +class ExportOrder extends BaseForm +{ + /** + * + * in this function you add all the fields you need for your Form. + * Form this you have to call add method on $this->formBuilder attribute : + * + * $this->formBuilder->add("name", "text") + * ->add("email", "email", array( + * "attr" => array( + * "class" => "field" + * ), + * "label" => "email", + * "constraints" => array( + * new \Symfony\Component\Validator\Constraints\NotBlank() + * ) + * ) + * ) + * ->add('age', 'integer'); + * + * @return null + */ + protected function buildForm() + { + $status = OrderStatusQuery::create() + ->filterByCode( + array( + OrderStatus::CODE_PAID, + OrderStatus::CODE_PROCESSING, + OrderStatus::CODE_SENT + ), + Criteria::IN + ) + ->find() + ->toArray('code') + ; + $query = OrderQuery::create() + ->filterByDeliveryModuleId(ColissimoPickupPoint::getModCode()) + ->filterByStatusId(array($status['paid']['Id'], $status['processing']['Id']), Criteria::IN) + ->find(); + + $this->formBuilder + ->add('new_status_id', 'choice',array( + 'label' => Translator::getInstance()->trans('server'), + 'choices' => array( + 'nochange' => Translator::getInstance()->trans('Do not change'), + 'processing' => Translator::getInstance()->trans('Set orders status as processing'), + 'sent' => Translator::getInstance()->trans('Set orders status as sent') + ), + 'required' => 'true', + 'expanded' => true, + 'multiple' => false, + 'data' => 'nochange' + ) + ); + /** @var Order $order */ + foreach ($query as $order) { + $this->formBuilder + ->add( + 'order_' . $order->getId(), + 'checkbox', + [ + 'label' => $order->getRef(), + 'label_attr' => ['for' => 'export_' . $order->getId()] + ] + ) + ->add( + 'order_weight_' . $order->getId(), + 'number' + ) + ; + } + } + + /** + * @return string the name of you form. This name must be unique + */ + public function getName() + { + return 'exportcolissimopickuppointorder'; + } + +} diff --git a/local/modules/ColissimoPickupPoint/Form/FreeShippingForm.php b/local/modules/ColissimoPickupPoint/Form/FreeShippingForm.php new file mode 100755 index 00000000..d7821b7d --- /dev/null +++ b/local/modules/ColissimoPickupPoint/Form/FreeShippingForm.php @@ -0,0 +1,88 @@ +. */ +/* */ +/*************************************************************************************/ + +namespace ColissimoPickupPoint\Form; + +use ColissimoPickupPoint\ColissimoPickupPoint; +use ColissimoPickupPoint\Model\ColissimoPickupPointFreeshippingQuery; +use Symfony\Component\Form\Extension\Core\Type\CheckboxType; +use Symfony\Component\Form\Extension\Core\Type\IntegerType; +use Symfony\Component\Form\Extension\Core\Type\NumberType; +use Thelia\Core\Translation\Translator; +use Thelia\Form\BaseForm; + +class FreeShippingForm extends BaseForm +{ + /** + * + * in this function you add all the fields you need for your Form. + * Form this you have to call add method on $this->formBuilder attribute : + * + * $this->formBuilder->add("name", "text") + * ->add("email", "email", array( + * "attr" => array( + * "class" => "field" + * ), + * "label" => "email", + * "constraints" => array( + * new \Symfony\Component\Validator\Constraints\NotBlank() + * ) + * ) + * ) + * ->add('age', 'integer'); + * + * @return null + */ + protected function buildForm() + { + $this->formBuilder + ->add( + 'freeshipping', + CheckboxType::class, + [ + 'label' => Translator::getInstance()->trans('Activate free shipping: ', [], ColissimoPickupPoint::DOMAIN) + ] + ) + ->add( + 'freeshipping_from', + NumberType::class, + [ + 'required' => false, + 'label' => Translator::getInstance()->trans("Free shipping from: ", [], ColissimoPickupPoint::DOMAIN), + 'data' => ColissimoPickupPointFreeshippingQuery::create()->findOneById(1)->getFreeshippingFrom(), + 'scale' => 2, + ] + ) + + ; + } + + /** + * @return string the name of you form. This name must be unique + */ + public function getName() + { + return 'colissimopickuppointfreeshipping'; + } + +} diff --git a/local/modules/ColissimoPickupPoint/Form/ImportForm.php b/local/modules/ColissimoPickupPoint/Form/ImportForm.php new file mode 100644 index 00000000..cf0c02d9 --- /dev/null +++ b/local/modules/ColissimoPickupPoint/Form/ImportForm.php @@ -0,0 +1,37 @@ + + */ +class ImportForm extends BaseForm +{ + public function getName() + { + return 'import_form'; + } + + protected function buildForm() + { + $this->formBuilder + ->add( + 'import_file', 'file', + [ + 'label' => Translator::getInstance()->trans('Select file to import', [], ColissimoPickupPoint::DOMAIN), + 'constraints' => [ + new Constraints\NotBlank(), + new Constraints\File(['mimeTypes' => ['text/csv', 'text/plain']]) + ], + 'label_attr' => ['for' => 'import_file'] + ] + ); + } +} diff --git a/local/modules/ColissimoPickupPoint/Form/UpdatePriceForm.php b/local/modules/ColissimoPickupPoint/Form/UpdatePriceForm.php new file mode 100644 index 00000000..b50398e5 --- /dev/null +++ b/local/modules/ColissimoPickupPoint/Form/UpdatePriceForm.php @@ -0,0 +1,68 @@ +formBuilder + ->add('area', 'integer', array( + 'constraints' => array( + new Constraints\NotBlank(), + new Constraints\Callback(array( + 'methods' => array( + array($this, + 'verifyAreaExist') + ) + )) + ) + )) + ->add('weight', 'number', array( + 'constraints' => array( + new Constraints\NotBlank(), + ) + )) + ->add('price', 'number', array( + 'constraints' => array( + new Constraints\NotBlank(), + new Constraints\Callback(array( + 'methods' => array( + array($this, + 'verifyValidPrice') + ) + )) + ) + )) + ->add('franco', 'number', array()) + ; + } + + public function verifyAreaExist($value, ExecutionContextInterface $context) + { + $area = AreaQuery::create()->findPk($value); + if (null === $area) { + $context->addViolation(Translator::getInstance()->trans("This area doesn't exists.", [], ColissimoPickupPoint::DOMAIN)); + } + } + + public function verifyValidPrice($value, ExecutionContextInterface $context) + { + if (!preg_match("#^\d+\.?\d*$#", $value)) { + $context->addViolation(Translator::getInstance()->trans('The price value is not valid.', [], ColissimoPickupPoint::DOMAIN)); + } + } + + public function getName() + { + return 'colissimo_pickup_point_price_slices_create'; + } +} \ No newline at end of file diff --git a/local/modules/ColissimoPickupPoint/Format/CSV.php b/local/modules/ColissimoPickupPoint/Format/CSV.php new file mode 100755 index 00000000..a54adf6f --- /dev/null +++ b/local/modules/ColissimoPickupPoint/Format/CSV.php @@ -0,0 +1,99 @@ +. */ +/* */ +/*************************************************************************************/ + +namespace ColissimoPickupPoint\Format; + +/** + * Class CSV + * @package ColissimoPickupPoint\Format + * @author Thelia + */ +class CSV +{ + protected $separator; + protected $lines=array(); + + const CRLF = "\r\n"; + /** + * @param $separator + * @param array $lines + */ + public function __construct($separator, array $lines=array()) + { + $this->separator = $separator; + + foreach ($lines as $line) { + if ($line instanceof CSVLine) { + $this->addLine($line); + } + } + } + + /** + * @param $separator + * @param array $lines + * @return CSV + */ + public static function create($separator, array $lines=array()) + { + return new static($separator, $lines); + } + + /** + * @param CSVLine $line + * @return $this + */ + public function addLine(CSVLine $line) + { + $this->lines[] = $line; + + return $this; + } + + /** + * @return string parsed CSV + */ + public function parse() + { + $buffer = ''; + + for ($j=0; $j < ($lineslen = count($this->lines)); ++$j) { + /** @var CSVLine $line */ + $line = $this->lines[$j]; + $aline = $line->getValues(); + + for ($i=0; $i < ($linelen = count($aline)); ++$i) { + $buffer .= '"' . $aline[$i] . '"'; + + if ($i !== $linelen-1) { + $buffer .= $this->separator; + } + } + if ($j !== $lineslen - 1) { + $buffer .= self::CRLF; + } + } + + return $buffer; + } +} diff --git a/local/modules/ColissimoPickupPoint/Format/CSVLine.php b/local/modules/ColissimoPickupPoint/Format/CSVLine.php new file mode 100755 index 00000000..90754347 --- /dev/null +++ b/local/modules/ColissimoPickupPoint/Format/CSVLine.php @@ -0,0 +1,67 @@ +. */ +/* */ +/*************************************************************************************/ + +namespace ColissimoPickupPoint\Format; + +/** + * Class CSVLine + * @package ColissimoPickupPoint\Format + * @author Thelia + */ +class CSVLine +{ + protected $values = array(); + + public function __construct(array $values) + { + $this->values = $values; + } + + /** + * @param array $values + * @return CSVLine + */ + public static function create(array $values) + { + return new static($values); + } + + /** + * @return array + */ + public function getValues() + { + return $this->values; + } + + /** + * @param $value + * @return $this + */ + public function addValue($value) + { + $this->values[] = $value; + + return $this; + } +} diff --git a/local/modules/ColissimoPickupPoint/Hook/BackHook.php b/local/modules/ColissimoPickupPoint/Hook/BackHook.php new file mode 100644 index 00000000..3533cb35 --- /dev/null +++ b/local/modules/ColissimoPickupPoint/Hook/BackHook.php @@ -0,0 +1,23 @@ +add($this->render('module_configuration.html')); + } + + public function onModuleConfigJs(HookRenderEvent $event) + { + $event->add($this->render('module-config-js.html')); + } +} diff --git a/local/modules/ColissimoPickupPoint/Hook/FrontHook.php b/local/modules/ColissimoPickupPoint/Hook/FrontHook.php new file mode 100644 index 00000000..0676db0d --- /dev/null +++ b/local/modules/ColissimoPickupPoint/Hook/FrontHook.php @@ -0,0 +1,41 @@ + + */ +class FrontHook extends BaseHook { + public function onOrderDeliveryExtra(HookRenderEvent $event) + { + $content = $this->render('colissimo-pickup-point.html', $event->getArguments()); + $event->add($content); + } + + public function onOrderInvoiceDeliveryAddress(HookRenderEvent $event) + { + $content = $this->render('delivery-address.html', $event->getArguments()); + $event->add($content); + } + + public function onMainHeadBottom(HookRenderEvent $event) + { + $content = $this->addCSS('assets/css/styles.css'); + $event->add($content); + } +} \ No newline at end of file diff --git a/local/modules/ColissimoPickupPoint/Hook/PdfHook.php b/local/modules/ColissimoPickupPoint/Hook/PdfHook.php new file mode 100644 index 00000000..3361707b --- /dev/null +++ b/local/modules/ColissimoPickupPoint/Hook/PdfHook.php @@ -0,0 +1,38 @@ +getArgument('module_id')) { + return; + } + + $order = OrderQuery::create()->findOneById($event->getArgument('order')); + + if (!is_null($order)) { + $event->add($this->render( + 'delivery_mode_infos.html', + ['delivery_address_id' => $order->getDeliveryOrderAddressId()] + )); + } + } +} diff --git a/local/modules/ColissimoPickupPoint/I18n/AdminIncludes/en_US.php b/local/modules/ColissimoPickupPoint/I18n/AdminIncludes/en_US.php new file mode 100644 index 00000000..9944984f --- /dev/null +++ b/local/modules/ColissimoPickupPoint/I18n/AdminIncludes/en_US.php @@ -0,0 +1,6 @@ + 'Export', + 'Export Coliship file' => 'Export Coliship file', +); diff --git a/local/modules/ColissimoPickupPoint/I18n/AdminIncludes/fr_FR.php b/local/modules/ColissimoPickupPoint/I18n/AdminIncludes/fr_FR.php new file mode 100755 index 00000000..fd8ed53b --- /dev/null +++ b/local/modules/ColissimoPickupPoint/I18n/AdminIncludes/fr_FR.php @@ -0,0 +1,6 @@ + 'Export', + 'Export Coliship file' => 'Export de fichier Coliship', +); diff --git a/local/modules/ColissimoPickupPoint/I18n/backOffice/default/en_US.php b/local/modules/ColissimoPickupPoint/I18n/backOffice/default/en_US.php new file mode 100644 index 00000000..44e8f8d7 --- /dev/null +++ b/local/modules/ColissimoPickupPoint/I18n/backOffice/default/en_US.php @@ -0,0 +1,51 @@ + '*If you choose this option, the exported orders would not be available on this page anymore', + 'Actions' => 'Actions', + 'Activate free shipping from (€) :' => 'Activate free shipping from (€) :', + 'Activate total free shipping ' => 'Activate total free shipping ', + 'Add this price slice' => 'Add this price slice', + 'Advanced configuration' => 'Advanced configuration', + 'An error occured' => 'An error occured', + 'Area : ' => 'Area : ', + 'Change orders status after export' => 'Change orders status after export', + 'Check all' => 'Check all', + 'Customer' => 'Customer', + 'Date' => 'Date', + 'Delete this price slice' => 'Delete this price slice', + 'Do not change' => 'Do not change', + 'Export' => 'Export', + 'Export Coliship file' => 'Export Coliship file', + 'If a cart matches multiple slices, it will take the last slice following that order.' => 'If a cart matches multiple slices, it will take the last slice following that order.', + 'If you don\'t specify a cart price in a slice, it will have priority over the other slices with the same weight.' => 'If you don\'t specify a cart price in a slice, it will have priority over the other slices with the same weight.', + 'If you don\'t specify a cart weight in a slice, it will have priority over the slices with weight.' => 'If you don\'t specify a cart weight in a slice, it will have priority over the slices with weight.', + 'If you specify both, the cart will require to have a lower weight AND a lower price in order to match the slice.' => 'If you specify both, the cart will require to have a lower weight AND a lower price in order to match the slice.', + 'Import Coliship file' => 'Import Coliship file', + 'Message' => 'Message', + 'Only use this for compatibility reason or if you have no other choice. For domicile delivery, you should use ColissimoWs instead.' => 'Only use this for compatibility reason or if you have no other choice. For domicile delivery, you should use ColissimoWs instead.', + 'Or activate free shipping from (€) :' => 'Or activate free shipping from (€) :', + 'Package weight' => 'Package weight', + 'Please change the access rights' => 'Please change the access rights', + 'Price (%symbol)' => 'Price (%symbol)', + 'Price slices for "%mode"' => 'Price slices for "%mode"', + 'Processing' => 'Processing', + 'REF' => 'REF', + 'Reverse selection' => 'Reverse selection', + 'Save' => 'Save', + 'Save changes' => 'Save changes', + 'Save this price slice' => 'Save this price slice', + 'Sent' => 'Sent', + 'The file has to be a CSV with 2 columns. The first contains the delivery reference, the second the order reference.' => 'The file has to be a CSV with 2 columns. The first contains the delivery reference, the second the order reference.', + 'The slices are ordered by maximum cart weight then by maximum cart price.' => 'The slices are ordered by maximum cart weight then by maximum cart price.', + 'Total taxed amount' => 'Total taxed amount', + 'Uncheck all' => 'Uncheck all', + 'Unknown customer' => 'Unknown customer', + 'Untaxed Price up to ... %symbol' => 'Untaxed Price up to ... %symbol', + 'Upload' => 'Upload', + 'Weight up to ... kg' => 'Weight up to ... kg', + 'You can create price slices by specifying a maximum cart weight and/or a maximum cart price.' => 'You can create price slices by specifying a maximum cart weight and/or a maximum cart price.', + 'You should first attribute shipping zones to the modules: ' => 'You should first attribute shipping zones to the modules: ', + 'manage shipping zones' => 'manage shipping zones', + 'operations' => 'operations', +); diff --git a/local/modules/ColissimoPickupPoint/I18n/backOffice/default/fr_FR.php b/local/modules/ColissimoPickupPoint/I18n/backOffice/default/fr_FR.php new file mode 100644 index 00000000..8b65f350 --- /dev/null +++ b/local/modules/ColissimoPickupPoint/I18n/backOffice/default/fr_FR.php @@ -0,0 +1,51 @@ + '* Si vous choisissez cette option, les commandes exportées n\'apparaitront plus dans cette page', + 'Actions' => 'Actions', + 'Activate free shipping from (€) :' => 'Activer les frais de port gratuits à partir de (€)', + 'Activate total free shipping ' => 'Activer les frais de port gratuits', + 'Add this price slice' => 'Ajouter cette tranche de prix', + 'Advanced configuration' => 'Configuration avancée', + 'An error occured' => 'Une erreur est survenue', + 'Area : ' => 'Zone :', + 'Change orders status after export' => 'Modifier le statut des commandes après l\'export', + 'Check all' => 'Tout cocher', + 'Customer' => 'Client', + 'Date' => 'Date', + 'Delete this price slice' => 'Supprimer cette tranche de prix', + 'Do not change' => 'Ne pas modifier', + 'Export' => 'Export', + 'Export Coliship file' => 'Export de fichier Coliship', + 'If a cart matches multiple slices, it will take the last slice following that order.' => 'Si un panier correspond à plusieurs tranches, la dernière tranche sera prise en compte selon cet ordre.', + 'If you don\'t specify a cart price in a slice, it will have priority over the other slices with the same weight.' => 'Si vous ne renseignez pas de prix de panier max dans une tranche, elle aura la priorité sur les autres tranches ayant le même poids.', + 'If you don\'t specify a cart weight in a slice, it will have priority over the slices with weight.' => 'Si vous ne renseignez pas de poids max dans une tranche, elle aura la priorité sur les tranches ayant un poids.', + 'If you specify both, the cart will require to have a lower weight AND a lower price in order to match the slice.' => 'Si vous renseignez les deux, le panier devra avoir à la fois un poids inférieur ET un prix inférieur pour correspondre à cette tranche.', + 'Import Coliship file' => 'Import de fichier Coliship', + 'Message' => 'Message', + 'Only use this for compatibility reason or if you have no other choice. For domicile delivery, you should use ColissimoWs instead.' => 'N\'utilisez ceci que pour des raisons de compatibilité ou si vous n\'avez pas d\'autres choix. Pour la livraison à domicile, utilisez plutôt désormais le module ColissimoWs', + 'Or activate free shipping from (€) :' => 'Ou activer les frais de port gratuits à partir de (€)', + 'Package weight' => 'Poids des colis (kg)', + 'Please change the access rights' => 'Merci de modifier les droits d\'accès', + 'Price (%symbol)' => 'Frais de livraison (%symbol)', + 'Price slices for "%mode"' => 'Tranche de prix pour "%mode"', + 'Processing' => 'En cours', + 'REF' => 'REF', + 'Reverse selection' => 'Inverser la sélection', + 'Save' => 'Sauvegarder', + 'Save changes' => 'Enregistrer les modifications', + 'Save this price slice' => 'Enregistrer cette tranche de prix', + 'Sent' => 'Envoyé', + 'The file has to be a CSV with 2 columns. The first contains the delivery reference, the second the order reference.' => 'Le fichier doit être au format CSV et contenir 2 colonnes. La première indique les références colis, la seconde les références des commandes.', + 'The slices are ordered by maximum cart weight then by maximum cart price.' => 'Les tranches sont triés pour poids de panier max puis par prix de panier max.', + 'Total taxed amount' => 'Montant total (avec taxes)', + 'Uncheck all' => 'Tout décocher', + 'Unknown customer' => 'Client inconnu', + 'Untaxed Price up to ... %symbol' => 'Prix HT max du panier (%symbol)', + 'Upload' => 'Charger le fichier', + 'Weight up to ... kg' => 'Poids maximum (kg)', + 'You can create price slices by specifying a maximum cart weight and/or a maximum cart price.' => 'Vous pouvez créer des tranches de prix pour les frais de port en spécifiant un poids de panier maximum et/ou un prix de panier maximum.', + 'You should first attribute shipping zones to the modules: ' => 'Vous devez d\'abord attribuer des zones de livraison à ce module :', + 'manage shipping zones' => 'Configurer les zones de livraison', + 'operations' => 'Opérations', +); diff --git a/local/modules/ColissimoPickupPoint/I18n/en_US.php b/local/modules/ColissimoPickupPoint/I18n/en_US.php new file mode 100644 index 00000000..2204e8c3 --- /dev/null +++ b/local/modules/ColissimoPickupPoint/I18n/en_US.php @@ -0,0 +1,34 @@ + 'Account number', + 'Activate free shipping: ' => 'Activate free shipping: ', + 'Bad file format. CSV expected.' => 'Bad file format. CSV expected.', + 'Can\'t read Config directory' => 'Can\'t read Config directory', + 'Can\'t read file' => 'Can\'t read file', + 'Colissimo URL prod' => 'Colissimo URL prod', + 'Do not change' => 'Do not change', + 'Google map API key' => 'Google map API key', + 'No relay points were selected' => 'No relay points were selected', + 'Operation successful. %i orders affected.' => 'Operation successful. %i orders affected.', + 'Password' => 'Password', + 'Select file to import' => 'Select file to import', + 'Set orders status as processing' => 'Set orders status as processing', + 'Set orders status as sent' => 'Set orders status as sent', + 'So Colissimo update config' => 'So Colissimo update config', + 'The area is not valid' => 'The area is not valid', + 'The delivery mode is not valid' => 'The delivery mode is not valid', + 'The price max value is not valid' => 'The price max value is not valid', + 'The price value is not valid' => 'The price value is not valid', + 'The price value is not valid.' => 'The price value is not valid.', + 'The slice has not been deleted' => 'The slice has not been deleted', + 'The weight max value is not valid' => 'The weight max value is not valid', + 'The weight value is not valid.' => 'The weight value is not valid.', + 'The weight value must be superior to 0.' => 'The weight value must be superior to 0.', + 'This area doesn\'t exists.' => 'This area doesn\'t exists.', + 'This delivery mode doesn\'t exists.' => 'This delivery mode doesn\'t exists.', + 'You must specify at least a price max or a weight max value.' => 'You must specify at least a price max or a weight max value.', + 'Your slice has been saved' => 'Your slice has been saved', + '[DEPRECATED] Activate Dom delivery' => '[DEPRECATED] Activate Dom delivery', + 'server' => 'server', +); diff --git a/local/modules/ColissimoPickupPoint/I18n/fr_FR.php b/local/modules/ColissimoPickupPoint/I18n/fr_FR.php new file mode 100755 index 00000000..db0c01fe --- /dev/null +++ b/local/modules/ColissimoPickupPoint/I18n/fr_FR.php @@ -0,0 +1,34 @@ + 'Numéro de compte', + 'Activate free shipping: ' => 'Livraison offerte: ', + 'Bad file format. CSV expected.' => 'Mauvais format de fichier. CSV attendu.', + 'Can\'t read Config directory' => 'Le dossier Config ne peut être lu', + 'Can\'t read file' => 'Le fichier suivant ne peut être lu', + 'Colissimo URL prod' => 'URL de Colissimo en production', + 'Do not change' => 'Ne pas changer', + 'Google map API key' => 'Clé API Google map', + 'No relay points were selected' => 'Aucun point relais n\'a été sélectionné', + 'Operation successful. %i orders affected.' => 'Opération effectuée avec succès. %i commandes affectées.', + 'Password' => 'Mot de passe', + 'Select file to import' => 'Sélectionner un fichier à importer', + 'Set orders status as processing' => 'En traitement', + 'Set orders status as sent' => 'Envoyée', + 'So Colissimo update config' => 'Mise à jour de la configuration de So Colissimo ', + 'The area is not valid' => 'La zone de livraison n\'est pas valide.', + 'The delivery mode is not valid' => 'Le mode de livraison n\'est pas valide.', + 'The price max value is not valid' => 'Le prix maximum n\'est pas valide.', + 'The price value is not valid' => 'Les frais de livraison ne sont pas valides.', + 'The price value is not valid.' => 'Le prix n\'est pas valide.', + 'The slice has not been deleted' => 'La tranche n\'a pas été supprimée.', + 'The weight max value is not valid' => 'Le poids maximum n\'est pas valide.', + 'The weight value is not valid.' => 'Le poids n\'est pas valide.', + 'The weight value must be superior to 0.' => 'Le poids doit être supérieur à 0.', + 'This area doesn\'t exists.' => 'Cette zone n\'existe pas.', + 'This delivery mode doesn\'t exists.' => 'Ce mode de livraison n\'existe pas.', + 'You must specify at least a price max or a weight max value.' => 'Vous devez spécifier au moins un prix maximum ou un poids maximum.', + 'Your slice has been saved' => 'Votre tranche a été enregistrée.', + '[DEPRECATED] Activate Dom delivery' => '[DEPRECIE] Activer la livraison à domicile', + 'server' => 'Serveur', +); diff --git a/local/modules/ColissimoPickupPoint/I18n/frontOffice/default/en_US.php b/local/modules/ColissimoPickupPoint/I18n/frontOffice/default/en_US.php new file mode 100644 index 00000000..1cef33ba --- /dev/null +++ b/local/modules/ColissimoPickupPoint/I18n/frontOffice/default/en_US.php @@ -0,0 +1,33 @@ + 'Actual address can\'t be geolocated', + 'Automatic pickup point' => 'Automatic pickup point', + 'Choose this delivery mode' => 'Choose this delivery mode', + 'Colissimo is unavailable. Please choose another delivery method' => 'Colissimo is unavailable. Please choose another delivery method', + 'Delivery address' => 'Delivery address', + 'Delivery in France in one of the 500 automatic instructions 7/7 and 24h/24.' => 'Delivery in France in one of the 500 automatic instructions 7/7 and 24h/24.', + 'Delivery in one of the 10,000 collection points La Poste in France or in a post office in Europe.' => 'Delivery in one of the 10,000 collection points La Poste in France or in a post office in Europe.', + 'Delivery in one of the 7,500 shops in the PICKUP network.' => 'Delivery in one of the 7,500 shops in the PICKUP network.', + 'Delivery to you or a personal address of your choice.' => 'Delivery to you or a personal address of your choice.', + 'Friday' => 'Friday', + 'Monday' => 'Monday', + 'My home' => 'My home', + 'Near you' => 'Near you', + 'No relay points were selected' => 'No relay points were selected', + 'Pickup shop' => 'Pickup shop', + 'Please enter a city and a zipcode' => 'Please enter a city and a zipcode', + 'Post office' => 'Post office', + 'Saturday' => 'Saturday', + 'Search' => 'Search', + 'Search Colissimo relay in a city' => 'Search Colissimo relay in a city', + 'Sunday' => 'Sunday', + 'Thursday' => 'Thursday', + 'Tuesday' => 'Tuesday', + 'Wednesday' => 'Wednesday', + 'address' => 'address', + 'city' => 'city', + 'home delivery' => 'home delivery', + 'include in results' => 'include in results', + 'zipcode' => 'zipcode', +); diff --git a/local/modules/ColissimoPickupPoint/I18n/frontOffice/default/fr_FR.php b/local/modules/ColissimoPickupPoint/I18n/frontOffice/default/fr_FR.php new file mode 100755 index 00000000..6b0699e0 --- /dev/null +++ b/local/modules/ColissimoPickupPoint/I18n/frontOffice/default/fr_FR.php @@ -0,0 +1,33 @@ + 'Actual address can\'t be geolocated ', + 'Automatic pickup point' => 'En consigne Pickup Station', + 'Choose this delivery mode' => 'Choisir ce mode de livraison', + 'Colissimo is unavailable. Please choose another delivery method' => 'Colissimo est indisponible. Merci de choisir un autre moyen de livraison.', + 'Delivery address' => 'Adresse de livraison', + 'Delivery in France in one of the 500 automatic instructions 7/7 and 24h/24.' => 'Livraison en France dans l’une des 500 consignes automatiques de retrait accessibles 7j/7 et 24h/24 (sauf consignes soumises aux horaires des galeries marchandes et zones de transports).', + 'Delivery in one of the 10,000 collection points La Poste in France or in a post office in Europe.' => 'Livraison dans l\'un des 10 000 points de retrait La Poste en France ou dans un bureau de poste à l\'étranger.', + 'Delivery in one of the 7,500 shops in the PICKUP network.' => 'Livraison dans l’un des 7500 commerçants de proximité du réseau Pickup.', + 'Delivery to you or a personal address of your choice.' => '

    Livraison chez vous ou à une adresse personnelle de votre choix avec tentative de remise en mains propres ou en boîte aux lettres.

    En cas d\'absence, remise en bureau de poste.

    ', + 'Friday' => 'Jeudi', + 'Monday' => 'Lundi', + 'My home' => 'Mon domicile', + 'Near you' => 'A proximité de chez vous', + 'No relay points were selected' => 'Aucun point relais n\'a été sélectionné', + 'Pickup shop' => 'En relais Pickup', + 'Please enter a city and a zipcode' => 'Merci de renseigner le code postal et la ville', + 'Post office' => 'En bureau de poste', + 'Saturday' => 'Samedi', + 'Search' => 'Rechercher', + 'Search Colissimo relay in a city' => 'Rechercher un point de retrait Colissimo dans une ville', + 'Sunday' => 'Dimanche', + 'Thursday' => 'Vendredi', + 'Tuesday' => 'Mardi', + 'Wednesday' => 'Mercredi', + 'address' => 'adresse', + 'city' => 'ville', + 'home delivery' => 'Livraison à domicile', + 'include in results' => 'inclure dans la recherche', + 'zipcode' => 'code postal', +); diff --git a/local/modules/ColissimoPickupPoint/I18n/pdf/default/en_US.php b/local/modules/ColissimoPickupPoint/I18n/pdf/default/en_US.php new file mode 100644 index 00000000..75d92322 --- /dev/null +++ b/local/modules/ColissimoPickupPoint/I18n/pdf/default/en_US.php @@ -0,0 +1,8 @@ + 'Delivered at a relay.', + 'Delivered at home.' => 'Delivered at home.', + 'Relay address:' => 'Relay address:', + 'no address' => 'no address', +); diff --git a/local/modules/ColissimoPickupPoint/I18n/pdf/default/fr_FR.php b/local/modules/ColissimoPickupPoint/I18n/pdf/default/fr_FR.php new file mode 100644 index 00000000..4e71ca3e --- /dev/null +++ b/local/modules/ColissimoPickupPoint/I18n/pdf/default/fr_FR.php @@ -0,0 +1,8 @@ + 'Livré en point relais.', + 'Delivered at home.' => 'Livré à domicile.', + 'Relay address:' => 'Adresse du point relais :', + 'no address' => 'Aucune adresse', +); diff --git a/local/modules/ColissimoPickupPoint/LICENSE.txt b/local/modules/ColissimoPickupPoint/LICENSE.txt new file mode 100644 index 00000000..65c5ca88 --- /dev/null +++ b/local/modules/ColissimoPickupPoint/LICENSE.txt @@ -0,0 +1,165 @@ + GNU LESSER GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + + This version of the GNU Lesser General Public License incorporates +the terms and conditions of version 3 of the GNU General Public +License, supplemented by the additional permissions listed below. + + 0. Additional Definitions. + + As used herein, "this License" refers to version 3 of the GNU Lesser +General Public License, and the "GNU GPL" refers to version 3 of the GNU +General Public License. + + "The Library" refers to a covered work governed by this License, +other than an Application or a Combined Work as defined below. + + An "Application" is any work that makes use of an interface provided +by the Library, but which is not otherwise based on the Library. +Defining a subclass of a class defined by the Library is deemed a mode +of using an interface provided by the Library. + + A "Combined Work" is a work produced by combining or linking an +Application with the Library. The particular version of the Library +with which the Combined Work was made is also called the "Linked +Version". + + The "Minimal Corresponding Source" for a Combined Work means the +Corresponding Source for the Combined Work, excluding any source code +for portions of the Combined Work that, considered in isolation, are +based on the Application, and not on the Linked Version. + + The "Corresponding Application Code" for a Combined Work means the +object code and/or source code for the Application, including any data +and utility programs needed for reproducing the Combined Work from the +Application, but excluding the System Libraries of the Combined Work. + + 1. Exception to Section 3 of the GNU GPL. + + You may convey a covered work under sections 3 and 4 of this License +without being bound by section 3 of the GNU GPL. + + 2. Conveying Modified Versions. + + If you modify a copy of the Library, and, in your modifications, a +facility refers to a function or data to be supplied by an Application +that uses the facility (other than as an argument passed when the +facility is invoked), then you may convey a copy of the modified +version: + + a) under this License, provided that you make a good faith effort to + ensure that, in the event an Application does not supply the + function or data, the facility still operates, and performs + whatever part of its purpose remains meaningful, or + + b) under the GNU GPL, with none of the additional permissions of + this License applicable to that copy. + + 3. Object Code Incorporating Material from Library Header Files. + + The object code form of an Application may incorporate material from +a header file that is part of the Library. You may convey such object +code under terms of your choice, provided that, if the incorporated +material is not limited to numerical parameters, data structure +layouts and accessors, or small macros, inline functions and templates +(ten or fewer lines in length), you do both of the following: + + a) Give prominent notice with each copy of the object code that the + Library is used in it and that the Library and its use are + covered by this License. + + b) Accompany the object code with a copy of the GNU GPL and this license + document. + + 4. Combined Works. + + You may convey a Combined Work under terms of your choice that, +taken together, effectively do not restrict modification of the +portions of the Library contained in the Combined Work and reverse +engineering for debugging such modifications, if you also do each of +the following: + + a) Give prominent notice with each copy of the Combined Work that + the Library is used in it and that the Library and its use are + covered by this License. + + b) Accompany the Combined Work with a copy of the GNU GPL and this license + document. + + c) For a Combined Work that displays copyright notices during + execution, include the copyright notice for the Library among + these notices, as well as a reference directing the user to the + copies of the GNU GPL and this license document. + + d) Do one of the following: + + 0) Convey the Minimal Corresponding Source under the terms of this + License, and the Corresponding Application Code in a form + suitable for, and under terms that permit, the user to + recombine or relink the Application with a modified version of + the Linked Version to produce a modified Combined Work, in the + manner specified by section 6 of the GNU GPL for conveying + Corresponding Source. + + 1) Use a suitable shared library mechanism for linking with the + Library. A suitable mechanism is one that (a) uses at run time + a copy of the Library already present on the user's computer + system, and (b) will operate properly with a modified version + of the Library that is interface-compatible with the Linked + Version. + + e) Provide Installation Information, but only if you would otherwise + be required to provide such information under section 6 of the + GNU GPL, and only to the extent that such information is + necessary to install and execute a modified version of the + Combined Work produced by recombining or relinking the + Application with a modified version of the Linked Version. (If + you use option 4d0, the Installation Information must accompany + the Minimal Corresponding Source and Corresponding Application + Code. If you use option 4d1, you must provide the Installation + Information in the manner specified by section 6 of the GNU GPL + for conveying Corresponding Source.) + + 5. Combined Libraries. + + You may place library facilities that are a work based on the +Library side by side in a single library together with other library +facilities that are not Applications and are not covered by this +License, and convey such a combined library under terms of your +choice, if you do both of the following: + + a) Accompany the combined library with a copy of the same work based + on the Library, uncombined with any other library facilities, + conveyed under the terms of this License. + + b) Give prominent notice with the combined library that part of it + is a work based on the Library, and explaining where to find the + accompanying uncombined form of the same work. + + 6. Revised Versions of the GNU Lesser General Public License. + + The Free Software Foundation may publish revised and/or new versions +of the GNU Lesser General Public License from time to time. Such new +versions will be similar in spirit to the present version, but may +differ in detail to address new problems or concerns. + + Each version is given a distinguishing version number. If the +Library as you received it specifies that a certain numbered version +of the GNU Lesser General Public License "or any later version" +applies to it, you have the option of following the terms and +conditions either of that published version or of any later version +published by the Free Software Foundation. If the Library as you +received it does not specify a version number of the GNU Lesser +General Public License, you may choose any version of the GNU Lesser +General Public License ever published by the Free Software Foundation. + + If the Library as you received it specifies that a proxy can decide +whether future versions of the GNU Lesser General Public License shall +apply, that proxy's public statement of acceptance of any version is +permanent authorization for you to choose that version for the +Library. diff --git a/local/modules/ColissimoPickupPoint/Listener/APIListener.php b/local/modules/ColissimoPickupPoint/Listener/APIListener.php new file mode 100644 index 00000000..5ee4865f --- /dev/null +++ b/local/modules/ColissimoPickupPoint/Listener/APIListener.php @@ -0,0 +1,162 @@ +getCountry()) { + $countryCode = $country->getIsoalpha2(); + } + + // Then ask the Web Service + $request = new FindByAddress(); + $request + ->setAddress($pickupLocationEvent->getAddress()) + ->setZipCode($pickupLocationEvent->getZipCode()) + ->setCity($pickupLocationEvent->getCity()) + ->setCountryCode($countryCode) + ->setFilterRelay('1') + ->setRequestId(md5(microtime())) + ->setLang('FR') + ->setOptionInter('1') + ->setShippingDate(date('d/m/Y')) + ->setAccountNumber(ColissimoPickupPoint::getConfigValue(ColissimoPickupPoint::COLISSIMO_USERNAME)) + ->setPassword(ColissimoPickupPoint::getConfigValue(ColissimoPickupPoint::COLISSIMO_PASSWORD)) + ; + + try { + $responses = $request->exec(); + } catch (InvalidArgumentException $e) { + $responses = array(); + } catch (\SoapFault $e) { + $responses = array(); + } + + if (!is_array($responses) && $responses !== null) { + $newResponse[] = $responses; + $responses = $newResponse; + } + + return $responses; + } + + /** + * Creates and returns a new location address + * + * @param $response + * @return PickupLocationAddress + */ + protected function createPickupLocationAddressFromResponse($response) + { + /** We create the new location address */ + $pickupLocationAddress = new PickupLocationAddress(); + + /** We set the differents properties of the location address */ + $pickupLocationAddress + ->setId($response->identifiant) + ->setTitle($response->nom) + ->setAddress1($response->adresse1) + ->setAddress2($response->adresse2) + ->setAddress3($response->adresse3) + ->setCity($response->localite) + ->setZipCode($response->codePostal) + ->setPhoneNumber('') + ->setCellphoneNumber('') + ->setCompany('') + ->setCountryCode($response->codePays) + ->setFirstName('') + ->setLastName('') + ->setIsDefault(0) + ->setLabel('') + ->setAdditionalData([]) + ; + + return $pickupLocationAddress; + } + + /** + * Creates then returns a location from a response of the WebService + * + * @param $response + * @return PickupLocation + * @throws \Exception + */ + protected function createPickupLocationFromResponse($response) + { + /** We create the new location */ + $pickupLocation = new PickupLocation(); + + /** We set the differents properties of the location */ + $pickupLocation + ->setId($response->identifiant) + ->setTitle($response->nom) + ->setAddress($this->createPickupLocationAddressFromResponse($response)) + ->setLatitude($response->coordGeolocalisationLatitude) + ->setLongitude($response->coordGeolocalisationLongitude) + ->setOpeningHours(PickupLocation::MONDAY_OPENING_HOURS_KEY, $response->horairesOuvertureLundi) + ->setOpeningHours(PickupLocation::TUESDAY_OPENING_HOURS_KEY, $response->horairesOuvertureMardi) + ->setOpeningHours(PickupLocation::WEDNESDAY_OPENING_HOURS_KEY, $response->horairesOuvertureMercredi) + ->setOpeningHours(PickupLocation::THURSDAY_OPENING_HOURS_KEY, $response->horairesOuvertureJeudi) + ->setOpeningHours(PickupLocation::FRIDAY_OPENING_HOURS_KEY, $response->horairesOuvertureVendredi) + ->setOpeningHours(PickupLocation::SATURDAY_OPENING_HOURS_KEY, $response->horairesOuvertureSamedi) + ->setOpeningHours(PickupLocation::SUNDAY_OPENING_HOURS_KEY, $response->horairesOuvertureDimanche) + ->setModuleId(ColissimoPickupPoint::getModuleId()) + ; + + return $pickupLocation; + } + + /** + * Get the list of locations (relay points) + * + * @param PickupLocationEvent $pickupLocationEvent + * @throws \Exception + */ + public function getPickupLocations(PickupLocationEvent $pickupLocationEvent) + { + if (null !== $moduleIds = $pickupLocationEvent->getModuleIds()) { + if (!in_array(ColissimoPickupPoint::getModuleId(), $moduleIds)) { + return ; + } + } + + $responses = $this->callWebService($pickupLocationEvent); + + foreach ($responses as $response) { + $pickupLocationEvent->appendLocation($this->createPickupLocationFromResponse($response)); + } + } + + public static function getSubscribedEvents() + { + $listenedEvents = []; + + /** Check for old versions of Thelia where the events used by the API didn't exists */ + if (class_exists(PickupLocation::class)) { + $listenedEvents[TheliaEvents::MODULE_DELIVERY_GET_PICKUP_LOCATIONS] = array("getPickupLocations", 128); + } + + return $listenedEvents; + } +} \ No newline at end of file diff --git a/local/modules/ColissimoPickupPoint/Listener/SendMail.php b/local/modules/ColissimoPickupPoint/Listener/SendMail.php new file mode 100755 index 00000000..b19d9483 --- /dev/null +++ b/local/modules/ColissimoPickupPoint/Listener/SendMail.php @@ -0,0 +1,123 @@ +. */ +/* */ +/*************************************************************************************/ + +namespace ColissimoPickupPoint\Listener; + +use ColissimoPickupPoint\ColissimoPickupPoint; +use Symfony\Component\EventDispatcher\EventSubscriberInterface; +use Thelia\Core\Event\Order\OrderEvent; +use Thelia\Core\Event\TheliaEvents; +use Thelia\Core\Template\ParserInterface; +use Thelia\Mailer\MailerFactory; +use Thelia\Model\ConfigQuery; +use Thelia\Model\MessageQuery; + +/** + * Class SendMail + * @package Colissimo\Listener + * @author Manuel Raynaud + */ +class SendMail implements EventSubscriberInterface +{ + + protected $parser; + + protected $mailer; + + public function __construct(ParserInterface $parser, MailerFactory $mailer) + { + $this->parser = $parser; + $this->mailer = $mailer; + } + + public function updateStatus(OrderEvent $event) + { + $order = $event->getOrder(); + $colissimoPickupPoint = new ColissimoPickupPoint(); + + if ($order->isSent() && $order->getDeliveryModuleId() == $colissimoPickupPoint->getModuleModel()->getId()) { + $contact_email = ConfigQuery::read('store_email'); + + if ($contact_email) { + + $message = MessageQuery::create() + ->filterByName('mail_colissimo_pickup_point') + ->findOne(); + + if (false === $message || null === $message) { + throw new \Exception("Failed to load message 'order_confirmation'."); + } + + $order = $event->getOrder(); + $customer = $order->getCustomer(); + + $this->parser->assign('customer_id', $customer->getId()); + $this->parser->assign('order_ref', $order->getRef()); + $this->parser->assign('order_date', $order->getCreatedAt()); + $this->parser->assign('update_date', $order->getUpdatedAt()); + $this->parser->assign('package', $order->getDeliveryRef()); + + $message + ->setLocale($order->getLang()->getLocale()); + + $instance = \Swift_Message::newInstance() + ->addTo($customer->getEmail(), $customer->getFirstname() . ' ' . $customer->getLastname()) + ->addFrom($contact_email, ConfigQuery::read('store_name')) + ; + + // Build subject and body + + $message->buildMessage($this->parser, $instance); + + $this->mailer->send($instance); + } + } + } + + /** + * Returns an array of event names this subscriber wants to listen to. + * + * The array keys are event names and the value can be: + * + * * The method name to call (priority defaults to 0) + * * An array composed of the method name to call and the priority + * * An array of arrays composed of the method names to call and respective + * priorities, or 0 if unset + * + * For instance: + * + * * array('eventName' => 'methodName') + * * array('eventName' => array('methodName', $priority)) + * * array('eventName' => array(array('methodName1', $priority), array('methodName2')) + * + * @return array The event names to listen to + * + * @api + */ + public static function getSubscribedEvents() + { + return array( + TheliaEvents::ORDER_UPDATE_STATUS => array('updateStatus', 128) + ); + } +} diff --git a/local/modules/ColissimoPickupPoint/Listener/SetDeliveryModule.php b/local/modules/ColissimoPickupPoint/Listener/SetDeliveryModule.php new file mode 100755 index 00000000..b5874c69 --- /dev/null +++ b/local/modules/ColissimoPickupPoint/Listener/SetDeliveryModule.php @@ -0,0 +1,249 @@ +. */ +/* */ +/*************************************************************************************/ + +namespace ColissimoPickupPoint\Listener; + +use ColissimoPickupPoint\Utils\ColissimoCodeReseau; +use ColissimoPickupPoint\WebService\FindById; +use Symfony\Component\EventDispatcher\EventSubscriberInterface; +use Thelia\Core\Event\Delivery\DeliveryPostageEvent; +use Thelia\Core\Event\TheliaEvents; + +use Thelia\Core\HttpFoundation\Request; +use Thelia\Core\Translation\Translator; +use Thelia\Model\Address; +use Thelia\Model\CountryQuery; +use Thelia\Model\OrderAddressQuery; +use ColissimoPickupPoint\ColissimoPickupPoint; +use Thelia\Core\Event\Order\OrderEvent; +use Thelia\Model\AddressQuery; +use ColissimoPickupPoint\Model\AddressColissimoPickupPointQuery; +use ColissimoPickupPoint\Model\AddressColissimoPickupPoint; +use ColissimoPickupPoint\Model\OrderAddressColissimoPickupPoint; + +/** + * Class SetDeliveryModule + * @package ColissimoPickupPoint\Listener + * @author Thelia + */ +class SetDeliveryModule implements EventSubscriberInterface +{ + protected $request; + + public function __construct(Request $request) + { + $this->request = $request; + } + + public function getRequest() + { + return $this->request; + } + + protected function check_module($id) + { + return $id == ColissimoPickupPoint::getModCode(); + } + + private function callWebServiceFindRelayPointByIdFromRequest(Request $request) + { + $relay_infos = explode(':', $request->get('colissimo_pickup_point_code')); + + $pr_code = $relay_infos[0]; + $relayType = count($relay_infos) > 1 ? $relay_infos[1] : null ; + $relayCountryCode = count($relay_infos) > 2 ? $relay_infos[2] : null ; + + if (!empty($pr_code)) { + $req = new FindById(); + + $req->setId($pr_code) + ->setLangue('FR') + ->setDate(date('d/m/Y')) + ->setAccountNumber(ColissimoPickupPoint::getConfigValue(ColissimoPickupPoint::COLISSIMO_USERNAME)) + ->setPassword(ColissimoPickupPoint::getConfigValue(ColissimoPickupPoint::COLISSIMO_PASSWORD)); + + // An argument "Code réseau" is now required in addition to the Relay Point Code to identify a relay point outside France. + // This argument is optional for relay points inside France. + if ($relayType != null && $relayCountryCode != null) { + $codeReseau = ColissimoCodeReseau::getCodeReseau($relayCountryCode, $relayType); + if ($codeReseau !== null) { + $req->setReseau($codeReseau); + } + } + + return $req->exec(); + } + + return null; + } + + public function isModuleColissimoPickupPoint(OrderEvent $event) + { + if ($this->check_module($event->getDeliveryModule())) { + $request = $this->getRequest(); + + $address = AddressColissimoPickupPointQuery::create() + ->findPk($event->getDeliveryAddress()); + + $request->getSession()->set('ColissimoPickupPointDeliveryId', $event->getDeliveryAddress()); + if ($address === null) { + $address = new AddressColissimoPickupPoint(); + $address->setId($event->getDeliveryAddress()); + } + + $response = $this->callWebServiceFindRelayPointByIdFromRequest($request); + + if ($response !== null) { + $customerName = AddressQuery::create() + ->findPk($event->getDeliveryAddress()); + + $address = AddressColissimoPickupPointQuery::create() + ->findPk($event->getDeliveryAddress()); + + $request->getSession()->set('ColissimoPickupPointDeliveryId', $event->getDeliveryAddress()); + + if ($address === null) { + $address = new AddressColissimoPickupPoint(); + $address->setId($event->getDeliveryAddress()); + } + + $relayCountry = CountryQuery::create()->findOneByIsoalpha2($response->codePays); + + if ($relayCountry == null) { + $relayCountry = $customerName->getCountry(); + } + + $address + ->setCode($response->identifiant) + ->setType($response->typeDePoint) + ->setCompany($response->nom) + ->setAddress1($response->adresse1) + ->setAddress2($response->adresse2) + ->setAddress3($response->adresse3) + ->setZipcode($response->codePostal) + ->setCity($response->localite) + ->setFirstname($customerName->getFirstname()) + ->setLastname($customerName->getLastname()) + ->setTitleId($customerName->getTitleId()) + ->setCountryId($relayCountry->getId()) + ->save() + ; + } else { + $message = Translator::getInstance()->trans('No pickup points were selected', [], ColissimoPickupPoint::DOMAIN); + throw new \Exception($message); + } + } + } + + public function updateDeliveryAddress(OrderEvent $event) + { + if ($this->check_module($event->getOrder()->getDeliveryModuleId())) { + $request = $this->getRequest(); + + $tmp_address = AddressColissimoPickupPointQuery::create() + ->findPk($request->getSession()->get('ColissimoPickupPointDeliveryId')); + + if ($tmp_address === null) { + throw new \ErrorException('Got an error with ColissimoPickupPoint module. Please try again to checkout.'); + } + + $savecode = new OrderAddressColissimoPickupPoint(); + + $savecode + ->setId($event->getOrder()->getDeliveryOrderAddressId()) + ->setCode($tmp_address->getCode()) + ->setType($tmp_address->getType()) + ->save() + ; + + $update = OrderAddressQuery::create() + ->findPK($event->getOrder()->getDeliveryOrderAddressId()) + ->setCompany($tmp_address->getCompany()) + ->setAddress1($tmp_address->getAddress1()) + ->setAddress2($tmp_address->getAddress2()) + ->setAddress3($tmp_address->getAddress3()) + ->setZipcode($tmp_address->getZipcode()) + ->setCity($tmp_address->getCity()) + ->save() + ; + } + } + + public function getPostageRelayPoint(DeliveryPostageEvent $event) + { + if ($this->check_module($event->getModule()->getModuleModel()->getId())) { + $request = $this->getRequest(); + + // If the relay point service was chosen, we store the address of the chosen relay point in + // the DeliveryPostageEvent in order for Thelia to recalculate the postage cost from this address. + + $response = $this->callWebServiceFindRelayPointByIdFromRequest($request); + + if ($response !== null) { + $address = new Address(); + $relayCountry = CountryQuery::create()->findOneByIsoalpha2($response->codePays); + + $address + ->setCompany($response->nom) + ->setAddress1($response->adresse1) + ->setAddress2($response->adresse2) + ->setAddress3($response->adresse3) + ->setZipcode($response->codePostal) + ->setCity($response->localite) + ->setCountryId($relayCountry->getId()) + ; + + $event->setAddress($address); + } + } + } + + /** + * Returns an array of event names this subscriber wants to listen to. + * + * The array keys are event names and the value can be: + * + * * The method name to call (priority defaults to 0) + * * An array composed of the method name to call and the priority + * * An array of arrays composed of the method names to call and respective + * priorities, or 0 if unset + * + * For instance: + * + * * array('eventName' => 'methodName') + * * array('eventName' => array('methodName', $priority)) + * * array('eventName' => array(array('methodName1', $priority), array('methodName2')) + * + * @return array The event names to listen to + * + * @api + */ + public static function getSubscribedEvents() + { + return array( + TheliaEvents::ORDER_SET_DELIVERY_MODULE => array('isModuleColissimoPickupPoint', 64), + TheliaEvents::ORDER_BEFORE_PAYMENT => array('updateDeliveryAddress', 256), + TheliaEvents::MODULE_DELIVERY_GET_POSTAGE => array('getPostageRelayPoint', 257) + ); + } +} diff --git a/local/modules/ColissimoPickupPoint/Loop/AreaFreeshipping.php b/local/modules/ColissimoPickupPoint/Loop/AreaFreeshipping.php new file mode 100644 index 00000000..d487e48a --- /dev/null +++ b/local/modules/ColissimoPickupPoint/Loop/AreaFreeshipping.php @@ -0,0 +1,54 @@ +getAreaId(); + + $modes = ColissimoPickupPointAreaFreeshippingQuery::create(); + + if (null !== $areaId) { + $modes->filterByAreaId($areaId); + } + + return $modes; + } + + public function parseResults(LoopResult $loopResult) + { + /** @var ColissimoPickupPointAreaFreeshipping $mode */ + foreach ($loopResult->getResultDataCollection() as $mode) { + $loopResultRow = new LoopResultRow($mode); + $loopResultRow + ->set('ID', $mode->getId()) + ->set('AREA_ID', $mode->getAreaId()) + ->set('CART_AMOUNT', $mode->getCartAmount()); + + $loopResult->addRow($loopResultRow); + } + return $loopResult; + } + +} \ No newline at end of file diff --git a/local/modules/ColissimoPickupPoint/Loop/CheckRightsLoop.php b/local/modules/ColissimoPickupPoint/Loop/CheckRightsLoop.php new file mode 100755 index 00000000..6d2e0b0f --- /dev/null +++ b/local/modules/ColissimoPickupPoint/Loop/CheckRightsLoop.php @@ -0,0 +1,78 @@ +. */ +/* */ +/*************************************************************************************/ + +namespace ColissimoPickupPoint\Loop; + +use Thelia\Core\Template\Loop\Argument\ArgumentCollection; +use Thelia\Core\Template\Element\BaseLoop; +use Thelia\Core\Template\Element\LoopResultRow; +use Thelia\Core\Template\Element\LoopResult; +use Thelia\Core\Template\Element\ArraySearchLoopInterface; +use Thelia\Core\Translation\Translator; + +/** + * Class CheckRightsLoop + * @package Colissimo\Looop + * @author Thelia + */ + +class CheckRightsLoop extends BaseLoop implements ArraySearchLoopInterface +{ + protected function getArgDefinitions() + { + return new ArgumentCollection(); + } + + public function buildArray() + { + $ret = array(); + $dir = __DIR__ . '/../Config/'; + if (!is_readable($dir)) { + $ret[] = array('ERRMES' => Translator::getInstance()->trans("Can't read Config directory"), 'ERRFILE' => ''); + } + if ($handle = opendir($dir)) { + while (false !== ($file = readdir($handle))) { + if (strlen($file) > 5 && substr($file, -5) === '.json') { + if (!is_readable($dir.$file)) { + $ret[] = array('ERRMES' => Translator::getInstance()->trans("Can't read file"), 'ERRFILE' => 'Colissimo/Config/' . $file); + } + } + } + } + + return $ret; + } + public function parseResults(LoopResult $loopResult) + { + foreach ($loopResult->getResultDataCollection() as $arr) { + $loopResultRow = new LoopResultRow(); + $loopResultRow + ->set('ERRMES', $arr['ERRMES']) + ->set('ERRFILE', $arr['ERRFILE']) + ; + $loopResult->addRow($loopResultRow); + } + + return $loopResult; + } +} diff --git a/local/modules/ColissimoPickupPoint/Loop/ColissimoPickupPointAddress.php b/local/modules/ColissimoPickupPoint/Loop/ColissimoPickupPointAddress.php new file mode 100755 index 00000000..e8afb380 --- /dev/null +++ b/local/modules/ColissimoPickupPoint/Loop/ColissimoPickupPointAddress.php @@ -0,0 +1,83 @@ +. */ +/* */ +/*************************************************************************************/ + +namespace ColissimoPickupPoint\Loop; + +use ColissimoPickupPoint\Model\AddressColissimoPickupPoint; +use ColissimoPickupPoint\Model\AddressColissimoPickupPointQuery; +use Thelia\Core\Template\Loop\Address; +use Thelia\Core\Template\Element\LoopResult; +use Thelia\Core\Template\Element\LoopResultRow; +/** + * class ColissimoPickupPointDelivery + * @package ColissimoPickupPoint\Loop + * @author Thelia + */ +class ColissimoPickupPointAddress extends Address +{ + protected $exists = false; + protected $timestampable = false; + + protected function setExists($id) + { + $this->exists = AddressColissimoPickupPointQuery::create()->findPK($id) !== null; + } + + public function buildModelCriteria() + { + $id = $this->getId(); + $this->setExists($id[0]); + + return $this->exists ? + AddressColissimoPickupPointQuery::create()->filterById($id[0]) : + parent::buildModelCriteria(); + } + + public function parseResults(LoopResult $loopResult) + { + if (!$this->exists) { + return parent::parseResults($loopResult); + } + + /** @var AddressColissimoPickupPoint $address */ + foreach ($loopResult->getResultDataCollection() as $address) { + $loopResultRow = new LoopResultRow(); + $loopResultRow + ->set('TITLE', $address->getTitleId()) + ->set('COMPANY', $address->getCompany()) + ->set('FIRSTNAME', $address->getFirstname()) + ->set('LASTNAME', $address->getLastname()) + ->set('ADDRESS1', $address->getAddress1()) + ->set('ADDRESS2', $address->getAddress2()) + ->set('ADDRESS3', $address->getAddress3()) + ->set('ZIPCODE', $address->getZipcode()) + ->set('CITY', $address->getCity()) + ->set('COUNTRY', $address->getCountryId()) + ->set('CELLPHONE', $address->getCellphone()) + ; + $loopResult->addRow($loopResultRow); + } + + return $loopResult; + } +} diff --git a/local/modules/ColissimoPickupPoint/Loop/ColissimoPickupPointFreeshippingLoop.php b/local/modules/ColissimoPickupPoint/Loop/ColissimoPickupPointFreeshippingLoop.php new file mode 100644 index 00000000..385689ee --- /dev/null +++ b/local/modules/ColissimoPickupPoint/Loop/ColissimoPickupPointFreeshippingLoop.php @@ -0,0 +1,52 @@ +findOneById(1)){ + $isFreeShippingActive = new ColissimoPickupPointFreeshipping(); + $isFreeShippingActive->setId(1); + $isFreeShippingActive->setActive(0); + $isFreeShippingActive->save(); + } + + return ColissimoPickupPointFreeshippingQuery::create()->filterById(1); + } + + public function parseResults(LoopResult $loopResult) + { + /** @var ColissimoPickupPointFreeshipping $freeshipping */ + foreach ($loopResult->getResultDataCollection() as $freeshipping) { + $loopResultRow = new LoopResultRow($freeshipping); + $loopResultRow + ->set('FREESHIPPING_ACTIVE', $freeshipping->getActive()) + ->set('FREESHIPPING_FROM', $freeshipping->getFreeshippingFrom()); + $loopResult->addRow($loopResultRow); + } + return $loopResult; + } +} \ No newline at end of file diff --git a/local/modules/ColissimoPickupPoint/Loop/ColissimoPickupPointId.php b/local/modules/ColissimoPickupPoint/Loop/ColissimoPickupPointId.php new file mode 100755 index 00000000..5b9bcd6f --- /dev/null +++ b/local/modules/ColissimoPickupPoint/Loop/ColissimoPickupPointId.php @@ -0,0 +1,71 @@ +. */ +/* */ +/*************************************************************************************/ + +namespace ColissimoPickupPoint\Loop; +use ColissimoPickupPoint\ColissimoPickupPoint; +use Thelia\Core\Template\Element\ArraySearchLoopInterface; +use Thelia\Core\Template\Element\BaseLoop; +use Thelia\Core\Template\Element\LoopResult; +use Thelia\Core\Template\Element\LoopResultRow; +use Thelia\Core\Template\Loop\Argument\ArgumentCollection; + +/** + * class ColissimoPickupPointId + * @package ColissimoPickupPoint\Loop + * @author Thelia + */ +class ColissimoPickupPointId extends BaseLoop implements ArraySearchLoopInterface +{ + /** + * this method returns an array + * + * @return array + */ + public function buildArray() + { + return array(ColissimoPickupPoint::getModCode()); + } + + /** + * @param LoopResult $loopResult + * + * @return LoopResult + */ + public function parseResults(LoopResult $loopResult) + { + foreach ($loopResult->getResultDataCollection() as $id) { + $loopResultRow = new LoopResultRow(); + $loopResult->addRow( + $loopResultRow->set('MODULE_ID', $id) + ); + } + + return $loopResult; + } + + protected function getArgDefinitions() + { + return new ArgumentCollection(); + } + +} diff --git a/local/modules/ColissimoPickupPoint/Loop/ColissimoPickupPointOrderAddressLoop.php b/local/modules/ColissimoPickupPoint/Loop/ColissimoPickupPointOrderAddressLoop.php new file mode 100644 index 00000000..812843f7 --- /dev/null +++ b/local/modules/ColissimoPickupPoint/Loop/ColissimoPickupPointOrderAddressLoop.php @@ -0,0 +1,92 @@ +getId()) !== null) { + $query->filterById((int)$id); + } + + return $query; + } + + /** + * @param LoopResult $loopResult + * + * @return LoopResult + */ + public function parseResults(LoopResult $loopResult) + { + /** @var OrderAddressColissimoPickupPoint $orderAddressColissimoPickupPoint */ + foreach ($loopResult->getResultDataCollection() as $orderAddressColissimoPickupPoint) { + $row = new LoopResultRow(); + $row->set('ID', $orderAddressColissimoPickupPoint->getId()); + $row->set('CODE', $orderAddressColissimoPickupPoint->getCode()); + $row->set('TYPE', $orderAddressColissimoPickupPoint->getType()); + $loopResult->addRow($row) + ; + } + + return $loopResult; + } +} diff --git a/local/modules/ColissimoPickupPoint/Loop/ColissimoPickupPointPriceSlices.php b/local/modules/ColissimoPickupPoint/Loop/ColissimoPickupPointPriceSlices.php new file mode 100644 index 00000000..6e351fe6 --- /dev/null +++ b/local/modules/ColissimoPickupPoint/Loop/ColissimoPickupPointPriceSlices.php @@ -0,0 +1,52 @@ +getAreaId(); + + $areaPrices = ColissimoPickupPointPriceSlicesQuery::create() + ->filterByAreaId($areaId) + ->orderByWeightMax(); + + return $areaPrices; + } + + public function parseResults(LoopResult $loopResult) + { + /** @var \ColissimoPickupPoint\Model\ColissimoPickupPointPriceSlices $price */ + foreach ($loopResult->getResultDataCollection() as $price) { + $loopResultRow = new LoopResultRow($price); + $loopResultRow + ->set('SLICE_ID', $price->getId()) + ->set('MAX_WEIGHT', $price->getWeightMax()) + ->set('MAX_PRICE', $price->getPriceMax()) + ->set('PRICE', $price->getPrice()) + ->set('FRANCO', $price->getFrancoMinPrice()) + ; + $loopResult->addRow($loopResultRow); + } + return $loopResult; + } +} diff --git a/local/modules/ColissimoPickupPoint/Loop/GetRelais.php b/local/modules/ColissimoPickupPoint/Loop/GetRelais.php new file mode 100755 index 00000000..9fc142a0 --- /dev/null +++ b/local/modules/ColissimoPickupPoint/Loop/GetRelais.php @@ -0,0 +1,179 @@ +. */ +/* */ +/*************************************************************************************/ + +namespace ColissimoPickupPoint\Loop; + +use ColissimoPickupPoint\ColissimoPickupPoint; +use ColissimoPickupPoint\WebService\FindByAddress; +use Symfony\Component\Serializer\Exception\InvalidArgumentException; +use Thelia\Core\Template\Element\ArraySearchLoopInterface; +use Thelia\Core\Template\Element\BaseLoop; +use Thelia\Core\Template\Element\LoopResult; +use Thelia\Core\Template\Element\LoopResultRow; +use Thelia\Core\Template\Loop\Argument\Argument; +use Thelia\Core\Template\Loop\Argument\ArgumentCollection; +use Thelia\Log\Tlog; +use Thelia\Model\AddressQuery; +use Thelia\Model\ConfigQuery; +use Thelia\Model\CountryQuery; + +/** + * Class GetRelais + * @package ColissimoPickupPoint\Loop + * @author Thelia + */ +class GetRelais extends BaseLoop implements ArraySearchLoopInterface +{ + /** + * @inheritdoc + */ + protected function getArgDefinitions() + { + return new ArgumentCollection( + Argument::createIntTypeArgument('countryid', ''), + Argument::createAnyTypeArgument('zipcode', ''), + Argument::createAnyTypeArgument('city', ''), + Argument::createIntTypeArgument('address') + ); + } + + /** + * @return array|mixed + * @throws \ErrorException + * @throws \Propel\Runtime\Exception\PropelException + */ + public function buildArray() + { + // Find the address ... To find ! \m/ + $zipcode = $this->getZipcode(); + $city = $this->getCity(); + $countryId = $this->getCountryid(); + + $addressId = $this->getAddress(); + + if (!empty($addressId) && (!empty($zipcode) || !empty($city))) { + throw new \InvalidArgumentException( + "Cannot have argument 'address' and 'zipcode' or 'city' at the same time." + ); + } + + if (null !== $addressModel = AddressQuery::create()->findPk($addressId)) { + $address = array( + 'zipcode' => $addressModel->getZipcode(), + 'city' => $addressModel->getCity(), + 'address' => $addressModel->getAddress1(), + 'countrycode' => $addressModel->getCountry()->getIsoalpha2() + ); + } elseif (empty($zipcode) || empty($city)) { + $search = AddressQuery::create(); + + $customer = $this->securityContext->getCustomerUser(); + if ($customer !== null) { + $search->filterByCustomerId($customer->getId()); + $search->filterByIsDefault('1'); + } else { + throw new \ErrorException('Customer not connected.'); + } + + $search = $search->findOne(); + $address['zipcode'] = $search->getZipcode(); + $address['city'] = $search->getCity(); + $address['address'] = $search->getAddress1(); + $address['countrycode'] = $search->getCountry()->getIsoalpha2(); + } else { + $address = array( + 'zipcode' => $zipcode, + 'city' => $city, + 'address' => '', + 'countrycode' => CountryQuery::create() + ->findOneById($countryId) + ->getIsoalpha2() + ); + } + + // Then ask the Web Service + $request = new FindByAddress(); + $request + ->setAddress($address['address']) + ->setZipCode($address['zipcode']) + ->setCity($address['city']) + ->setCountryCode($address['countrycode']) + ->setFilterRelay('1') + ->setRequestId(md5(microtime())) + ->setLang('FR') + ->setOptionInter('1') + ->setShippingDate(date('d/m/Y')) + ->setAccountNumber(ColissimoPickupPoint::getConfigValue(ColissimoPickupPoint::COLISSIMO_USERNAME)) + ->setPassword(ColissimoPickupPoint::getConfigValue(ColissimoPickupPoint::COLISSIMO_PASSWORD)) + ; + + try { + $response = $request->exec(); + } catch (InvalidArgumentException $e) { + $response = array(); + } catch (\SoapFault $e) { + $response = array(); + } + + if (!is_array($response) && $response !== null) { + $newResponse[] = $response; + $response = $newResponse; + } + + return $response; + } + + /** + * @param LoopResult $loopResult + * + * @return LoopResult + */ + public function parseResults(LoopResult $loopResult) + { + foreach ($loopResult->getResultDataCollection() as $item) { + $loopResultRow = new LoopResultRow(); + + //Tlog::getInstance()->addDebug(print_r($item, true)); + foreach ($item as $key => $value) { + $loopResultRow->set($key, $value); + } + + // format distance + $distance = (string) $loopResultRow->get('distanceEnMetre'); + if (strlen($distance) < 4) { + $distance .= ' m'; + } else { + $distance = (string)(float)$distance / 1000; + while (substr($distance, strlen($distance) - 1, 1) == "0") { + $distance = substr($distance, 0, strlen($distance) - 1); + } + $distance = str_replace('.', ',', $distance) . ' km'; + } + $loopResultRow->set('distance', $distance); + + $loopResult->addRow($loopResultRow); + } + + return $loopResult; + } +} diff --git a/local/modules/ColissimoPickupPoint/Loop/NotSentOrders.php b/local/modules/ColissimoPickupPoint/Loop/NotSentOrders.php new file mode 100755 index 00000000..871b68af --- /dev/null +++ b/local/modules/ColissimoPickupPoint/Loop/NotSentOrders.php @@ -0,0 +1,75 @@ +. */ +/* */ +/*************************************************************************************/ + +namespace ColissimoPickupPoint\Loop; + +use Propel\Runtime\ActiveQuery\Criteria; +use ColissimoPickupPoint\ColissimoPickupPoint; +use Thelia\Core\Template\Loop\Argument\Argument; +use Thelia\Core\Template\Loop\Argument\ArgumentCollection; +use Thelia\Model\OrderQuery; +use Thelia\Core\Template\Loop\Order; +use Thelia\Model\OrderStatus; +use Thelia\Model\OrderStatusQuery; + +/** + * Class NotSentOrders + * @package ColissimoPickupPoint\Loop + * @author Thelia + */ +class NotSentOrders extends Order +{ + public function getArgDefinitions() + { + return new ArgumentCollection(Argument::createBooleanTypeArgument('with_prev_next_info', false)); + } + + /** + * this method returns a Propel ModelCriteria + * + * @return \Propel\Runtime\ActiveQuery\ModelCriteria + */ + public function buildModelCriteria() + { + $status = OrderStatusQuery::create() + ->filterByCode( + array( + OrderStatus::CODE_PAID, + OrderStatus::CODE_PROCESSING, + ), + Criteria::IN + ) + ->find() + ->toArray('code'); + $query = OrderQuery::create() + ->filterByDeliveryModuleId(ColissimoPickupPoint::getModCode()) + ->filterByStatusId( + array( + $status[OrderStatus::CODE_PAID]['Id'], + $status[OrderStatus::CODE_PROCESSING]['Id']), + Criteria::IN + ); + + return $query; + } +} diff --git a/local/modules/ColissimoPickupPoint/Model/AddressColissimoPickupPoint.php b/local/modules/ColissimoPickupPoint/Model/AddressColissimoPickupPoint.php new file mode 100644 index 00000000..38044c2e --- /dev/null +++ b/local/modules/ColissimoPickupPoint/Model/AddressColissimoPickupPoint.php @@ -0,0 +1,10 @@ +modifiedColumns; + } + + /** + * Has specified column been modified? + * + * @param string $col column fully qualified name (TableMap::TYPE_COLNAME), e.g. Book::AUTHOR_ID + * @return boolean True if $col has been modified. + */ + public function isColumnModified($col) + { + return $this->modifiedColumns && isset($this->modifiedColumns[$col]); + } + + /** + * Get the columns that have been modified in this object. + * @return array A unique list of the modified column names for this object. + */ + public function getModifiedColumns() + { + return $this->modifiedColumns ? array_keys($this->modifiedColumns) : []; + } + + /** + * Returns whether the object has ever been saved. This will + * be false, if the object was retrieved from storage or was created + * and then saved. + * + * @return boolean true, if the object has never been persisted. + */ + public function isNew() + { + return $this->new; + } + + /** + * Setter for the isNew attribute. This method will be called + * by Propel-generated children and objects. + * + * @param boolean $b the state of the object. + */ + public function setNew($b) + { + $this->new = (Boolean) $b; + } + + /** + * Whether this object has been deleted. + * @return boolean The deleted state of this object. + */ + public function isDeleted() + { + return $this->deleted; + } + + /** + * Specify whether this object has been deleted. + * @param boolean $b The deleted state of this object. + * @return void + */ + public function setDeleted($b) + { + $this->deleted = (Boolean) $b; + } + + /** + * Sets the modified state for the object to be false. + * @param string $col If supplied, only the specified column is reset. + * @return void + */ + public function resetModified($col = null) + { + if (null !== $col) { + if (isset($this->modifiedColumns[$col])) { + unset($this->modifiedColumns[$col]); + } + } else { + $this->modifiedColumns = array(); + } + } + + /** + * Compares this with another AddressColissimoPickupPoint instance. If + * obj is an instance of AddressColissimoPickupPoint, delegates to + * equals(AddressColissimoPickupPoint). Otherwise, returns false. + * + * @param mixed $obj The object to compare to. + * @return boolean Whether equal to the object specified. + */ + public function equals($obj) + { + $thisclazz = get_class($this); + if (!is_object($obj) || !($obj instanceof $thisclazz)) { + return false; + } + + if ($this === $obj) { + return true; + } + + if (null === $this->getPrimaryKey() + || null === $obj->getPrimaryKey()) { + return false; + } + + return $this->getPrimaryKey() === $obj->getPrimaryKey(); + } + + /** + * If the primary key is not null, return the hashcode of the + * primary key. Otherwise, return the hash code of the object. + * + * @return int Hashcode + */ + public function hashCode() + { + if (null !== $this->getPrimaryKey()) { + return crc32(serialize($this->getPrimaryKey())); + } + + return crc32(serialize(clone $this)); + } + + /** + * Get the associative array of the virtual columns in this object + * + * @return array + */ + public function getVirtualColumns() + { + return $this->virtualColumns; + } + + /** + * Checks the existence of a virtual column in this object + * + * @param string $name The virtual column name + * @return boolean + */ + public function hasVirtualColumn($name) + { + return array_key_exists($name, $this->virtualColumns); + } + + /** + * Get the value of a virtual column in this object + * + * @param string $name The virtual column name + * @return mixed + * + * @throws PropelException + */ + public function getVirtualColumn($name) + { + if (!$this->hasVirtualColumn($name)) { + throw new PropelException(sprintf('Cannot get value of inexistent virtual column %s.', $name)); + } + + return $this->virtualColumns[$name]; + } + + /** + * Set the value of a virtual column in this object + * + * @param string $name The virtual column name + * @param mixed $value The value to give to the virtual column + * + * @return AddressColissimoPickupPoint The current object, for fluid interface + */ + public function setVirtualColumn($name, $value) + { + $this->virtualColumns[$name] = $value; + + return $this; + } + + /** + * Logs a message using Propel::log(). + * + * @param string $msg + * @param int $priority One of the Propel::LOG_* logging levels + * @return boolean + */ + protected function log($msg, $priority = Propel::LOG_INFO) + { + return Propel::log(get_class($this) . ': ' . $msg, $priority); + } + + /** + * Populate the current object from a string, using a given parser format + * + * $book = new Book(); + * $book->importFrom('JSON', '{"Id":9012,"Title":"Don Juan","ISBN":"0140422161","Price":12.99,"PublisherId":1234,"AuthorId":5678}'); + * + * + * @param mixed $parser A AbstractParser instance, + * or a format name ('XML', 'YAML', 'JSON', 'CSV') + * @param string $data The source data to import from + * + * @return AddressColissimoPickupPoint The current object, for fluid interface + */ + public function importFrom($parser, $data) + { + if (!$parser instanceof AbstractParser) { + $parser = AbstractParser::getParser($parser); + } + + $this->fromArray($parser->toArray($data), TableMap::TYPE_PHPNAME); + + return $this; + } + + /** + * Export the current object properties to a string, using a given parser format + * + * $book = BookQuery::create()->findPk(9012); + * echo $book->exportTo('JSON'); + * => {"Id":9012,"Title":"Don Juan","ISBN":"0140422161","Price":12.99,"PublisherId":1234,"AuthorId":5678}'); + * + * + * @param mixed $parser A AbstractParser instance, or a format name ('XML', 'YAML', 'JSON', 'CSV') + * @param boolean $includeLazyLoadColumns (optional) Whether to include lazy load(ed) columns. Defaults to TRUE. + * @return string The exported data + */ + public function exportTo($parser, $includeLazyLoadColumns = true) + { + if (!$parser instanceof AbstractParser) { + $parser = AbstractParser::getParser($parser); + } + + return $parser->fromArray($this->toArray(TableMap::TYPE_PHPNAME, $includeLazyLoadColumns, array(), true)); + } + + /** + * Clean up internal collections prior to serializing + * Avoids recursive loops that turn into segmentation faults when serializing + */ + public function __sleep() + { + $this->clearAllReferences(); + + return array_keys(get_object_vars($this)); + } + + /** + * Get the [id] column value. + * + * @return int + */ + public function getId() + { + + return $this->id; + } + + /** + * Get the [title_id] column value. + * + * @return int + */ + public function getTitleId() + { + + return $this->title_id; + } + + /** + * Get the [company] column value. + * + * @return string + */ + public function getCompany() + { + + return $this->company; + } + + /** + * Get the [firstname] column value. + * + * @return string + */ + public function getFirstname() + { + + return $this->firstname; + } + + /** + * Get the [lastname] column value. + * + * @return string + */ + public function getLastname() + { + + return $this->lastname; + } + + /** + * Get the [address1] column value. + * + * @return string + */ + public function getAddress1() + { + + return $this->address1; + } + + /** + * Get the [address2] column value. + * + * @return string + */ + public function getAddress2() + { + + return $this->address2; + } + + /** + * Get the [address3] column value. + * + * @return string + */ + public function getAddress3() + { + + return $this->address3; + } + + /** + * Get the [zipcode] column value. + * + * @return string + */ + public function getZipcode() + { + + return $this->zipcode; + } + + /** + * Get the [city] column value. + * + * @return string + */ + public function getCity() + { + + return $this->city; + } + + /** + * Get the [country_id] column value. + * + * @return int + */ + public function getCountryId() + { + + return $this->country_id; + } + + /** + * Get the [code] column value. + * + * @return string + */ + public function getCode() + { + + return $this->code; + } + + /** + * Get the [type] column value. + * + * @return string + */ + public function getType() + { + + return $this->type; + } + + /** + * Get the [cellphone] column value. + * + * @return string + */ + public function getCellphone() + { + + return $this->cellphone; + } + + /** + * Set the value of [id] column. + * + * @param int $v new value + * @return \ColissimoPickupPoint\Model\AddressColissimoPickupPoint The current object (for fluent API support) + */ + public function setId($v) + { + if ($v !== null) { + $v = (int) $v; + } + + if ($this->id !== $v) { + $this->id = $v; + $this->modifiedColumns[AddressColissimoPickupPointTableMap::ID] = true; + } + + + return $this; + } // setId() + + /** + * Set the value of [title_id] column. + * + * @param int $v new value + * @return \ColissimoPickupPoint\Model\AddressColissimoPickupPoint The current object (for fluent API support) + */ + public function setTitleId($v) + { + if ($v !== null) { + $v = (int) $v; + } + + if ($this->title_id !== $v) { + $this->title_id = $v; + $this->modifiedColumns[AddressColissimoPickupPointTableMap::TITLE_ID] = true; + } + + if ($this->aCustomerTitle !== null && $this->aCustomerTitle->getId() !== $v) { + $this->aCustomerTitle = null; + } + + + return $this; + } // setTitleId() + + /** + * Set the value of [company] column. + * + * @param string $v new value + * @return \ColissimoPickupPoint\Model\AddressColissimoPickupPoint The current object (for fluent API support) + */ + public function setCompany($v) + { + if ($v !== null) { + $v = (string) $v; + } + + if ($this->company !== $v) { + $this->company = $v; + $this->modifiedColumns[AddressColissimoPickupPointTableMap::COMPANY] = true; + } + + + return $this; + } // setCompany() + + /** + * Set the value of [firstname] column. + * + * @param string $v new value + * @return \ColissimoPickupPoint\Model\AddressColissimoPickupPoint The current object (for fluent API support) + */ + public function setFirstname($v) + { + if ($v !== null) { + $v = (string) $v; + } + + if ($this->firstname !== $v) { + $this->firstname = $v; + $this->modifiedColumns[AddressColissimoPickupPointTableMap::FIRSTNAME] = true; + } + + + return $this; + } // setFirstname() + + /** + * Set the value of [lastname] column. + * + * @param string $v new value + * @return \ColissimoPickupPoint\Model\AddressColissimoPickupPoint The current object (for fluent API support) + */ + public function setLastname($v) + { + if ($v !== null) { + $v = (string) $v; + } + + if ($this->lastname !== $v) { + $this->lastname = $v; + $this->modifiedColumns[AddressColissimoPickupPointTableMap::LASTNAME] = true; + } + + + return $this; + } // setLastname() + + /** + * Set the value of [address1] column. + * + * @param string $v new value + * @return \ColissimoPickupPoint\Model\AddressColissimoPickupPoint The current object (for fluent API support) + */ + public function setAddress1($v) + { + if ($v !== null) { + $v = (string) $v; + } + + if ($this->address1 !== $v) { + $this->address1 = $v; + $this->modifiedColumns[AddressColissimoPickupPointTableMap::ADDRESS1] = true; + } + + + return $this; + } // setAddress1() + + /** + * Set the value of [address2] column. + * + * @param string $v new value + * @return \ColissimoPickupPoint\Model\AddressColissimoPickupPoint The current object (for fluent API support) + */ + public function setAddress2($v) + { + if ($v !== null) { + $v = (string) $v; + } + + if ($this->address2 !== $v) { + $this->address2 = $v; + $this->modifiedColumns[AddressColissimoPickupPointTableMap::ADDRESS2] = true; + } + + + return $this; + } // setAddress2() + + /** + * Set the value of [address3] column. + * + * @param string $v new value + * @return \ColissimoPickupPoint\Model\AddressColissimoPickupPoint The current object (for fluent API support) + */ + public function setAddress3($v) + { + if ($v !== null) { + $v = (string) $v; + } + + if ($this->address3 !== $v) { + $this->address3 = $v; + $this->modifiedColumns[AddressColissimoPickupPointTableMap::ADDRESS3] = true; + } + + + return $this; + } // setAddress3() + + /** + * Set the value of [zipcode] column. + * + * @param string $v new value + * @return \ColissimoPickupPoint\Model\AddressColissimoPickupPoint The current object (for fluent API support) + */ + public function setZipcode($v) + { + if ($v !== null) { + $v = (string) $v; + } + + if ($this->zipcode !== $v) { + $this->zipcode = $v; + $this->modifiedColumns[AddressColissimoPickupPointTableMap::ZIPCODE] = true; + } + + + return $this; + } // setZipcode() + + /** + * Set the value of [city] column. + * + * @param string $v new value + * @return \ColissimoPickupPoint\Model\AddressColissimoPickupPoint The current object (for fluent API support) + */ + public function setCity($v) + { + if ($v !== null) { + $v = (string) $v; + } + + if ($this->city !== $v) { + $this->city = $v; + $this->modifiedColumns[AddressColissimoPickupPointTableMap::CITY] = true; + } + + + return $this; + } // setCity() + + /** + * Set the value of [country_id] column. + * + * @param int $v new value + * @return \ColissimoPickupPoint\Model\AddressColissimoPickupPoint The current object (for fluent API support) + */ + public function setCountryId($v) + { + if ($v !== null) { + $v = (int) $v; + } + + if ($this->country_id !== $v) { + $this->country_id = $v; + $this->modifiedColumns[AddressColissimoPickupPointTableMap::COUNTRY_ID] = true; + } + + if ($this->aCountry !== null && $this->aCountry->getId() !== $v) { + $this->aCountry = null; + } + + + return $this; + } // setCountryId() + + /** + * Set the value of [code] column. + * + * @param string $v new value + * @return \ColissimoPickupPoint\Model\AddressColissimoPickupPoint The current object (for fluent API support) + */ + public function setCode($v) + { + if ($v !== null) { + $v = (string) $v; + } + + if ($this->code !== $v) { + $this->code = $v; + $this->modifiedColumns[AddressColissimoPickupPointTableMap::CODE] = true; + } + + + return $this; + } // setCode() + + /** + * Set the value of [type] column. + * + * @param string $v new value + * @return \ColissimoPickupPoint\Model\AddressColissimoPickupPoint The current object (for fluent API support) + */ + public function setType($v) + { + if ($v !== null) { + $v = (string) $v; + } + + if ($this->type !== $v) { + $this->type = $v; + $this->modifiedColumns[AddressColissimoPickupPointTableMap::TYPE] = true; + } + + + return $this; + } // setType() + + /** + * Set the value of [cellphone] column. + * + * @param string $v new value + * @return \ColissimoPickupPoint\Model\AddressColissimoPickupPoint The current object (for fluent API support) + */ + public function setCellphone($v) + { + if ($v !== null) { + $v = (string) $v; + } + + if ($this->cellphone !== $v) { + $this->cellphone = $v; + $this->modifiedColumns[AddressColissimoPickupPointTableMap::CELLPHONE] = true; + } + + + return $this; + } // setCellphone() + + /** + * Indicates whether the columns in this object are only set to default values. + * + * This method can be used in conjunction with isModified() to indicate whether an object is both + * modified _and_ has some values set which are non-default. + * + * @return boolean Whether the columns in this object are only been set with default values. + */ + public function hasOnlyDefaultValues() + { + // otherwise, everything was equal, so return TRUE + return true; + } // hasOnlyDefaultValues() + + /** + * Hydrates (populates) the object variables with values from the database resultset. + * + * An offset (0-based "start column") is specified so that objects can be hydrated + * with a subset of the columns in the resultset rows. This is needed, for example, + * for results of JOIN queries where the resultset row includes columns from two or + * more tables. + * + * @param array $row The row returned by DataFetcher->fetch(). + * @param int $startcol 0-based offset column which indicates which restultset column to start with. + * @param boolean $rehydrate Whether this object is being re-hydrated from the database. + * @param string $indexType The index type of $row. Mostly DataFetcher->getIndexType(). + One of the class type constants TableMap::TYPE_PHPNAME, TableMap::TYPE_STUDLYPHPNAME + * TableMap::TYPE_COLNAME, TableMap::TYPE_FIELDNAME, TableMap::TYPE_NUM. + * + * @return int next starting column + * @throws PropelException - Any caught Exception will be rewrapped as a PropelException. + */ + public function hydrate($row, $startcol = 0, $rehydrate = false, $indexType = TableMap::TYPE_NUM) + { + try { + + + $col = $row[TableMap::TYPE_NUM == $indexType ? 0 + $startcol : AddressColissimoPickupPointTableMap::translateFieldName('Id', TableMap::TYPE_PHPNAME, $indexType)]; + $this->id = (null !== $col) ? (int) $col : null; + + $col = $row[TableMap::TYPE_NUM == $indexType ? 1 + $startcol : AddressColissimoPickupPointTableMap::translateFieldName('TitleId', TableMap::TYPE_PHPNAME, $indexType)]; + $this->title_id = (null !== $col) ? (int) $col : null; + + $col = $row[TableMap::TYPE_NUM == $indexType ? 2 + $startcol : AddressColissimoPickupPointTableMap::translateFieldName('Company', TableMap::TYPE_PHPNAME, $indexType)]; + $this->company = (null !== $col) ? (string) $col : null; + + $col = $row[TableMap::TYPE_NUM == $indexType ? 3 + $startcol : AddressColissimoPickupPointTableMap::translateFieldName('Firstname', TableMap::TYPE_PHPNAME, $indexType)]; + $this->firstname = (null !== $col) ? (string) $col : null; + + $col = $row[TableMap::TYPE_NUM == $indexType ? 4 + $startcol : AddressColissimoPickupPointTableMap::translateFieldName('Lastname', TableMap::TYPE_PHPNAME, $indexType)]; + $this->lastname = (null !== $col) ? (string) $col : null; + + $col = $row[TableMap::TYPE_NUM == $indexType ? 5 + $startcol : AddressColissimoPickupPointTableMap::translateFieldName('Address1', TableMap::TYPE_PHPNAME, $indexType)]; + $this->address1 = (null !== $col) ? (string) $col : null; + + $col = $row[TableMap::TYPE_NUM == $indexType ? 6 + $startcol : AddressColissimoPickupPointTableMap::translateFieldName('Address2', TableMap::TYPE_PHPNAME, $indexType)]; + $this->address2 = (null !== $col) ? (string) $col : null; + + $col = $row[TableMap::TYPE_NUM == $indexType ? 7 + $startcol : AddressColissimoPickupPointTableMap::translateFieldName('Address3', TableMap::TYPE_PHPNAME, $indexType)]; + $this->address3 = (null !== $col) ? (string) $col : null; + + $col = $row[TableMap::TYPE_NUM == $indexType ? 8 + $startcol : AddressColissimoPickupPointTableMap::translateFieldName('Zipcode', TableMap::TYPE_PHPNAME, $indexType)]; + $this->zipcode = (null !== $col) ? (string) $col : null; + + $col = $row[TableMap::TYPE_NUM == $indexType ? 9 + $startcol : AddressColissimoPickupPointTableMap::translateFieldName('City', TableMap::TYPE_PHPNAME, $indexType)]; + $this->city = (null !== $col) ? (string) $col : null; + + $col = $row[TableMap::TYPE_NUM == $indexType ? 10 + $startcol : AddressColissimoPickupPointTableMap::translateFieldName('CountryId', TableMap::TYPE_PHPNAME, $indexType)]; + $this->country_id = (null !== $col) ? (int) $col : null; + + $col = $row[TableMap::TYPE_NUM == $indexType ? 11 + $startcol : AddressColissimoPickupPointTableMap::translateFieldName('Code', TableMap::TYPE_PHPNAME, $indexType)]; + $this->code = (null !== $col) ? (string) $col : null; + + $col = $row[TableMap::TYPE_NUM == $indexType ? 12 + $startcol : AddressColissimoPickupPointTableMap::translateFieldName('Type', TableMap::TYPE_PHPNAME, $indexType)]; + $this->type = (null !== $col) ? (string) $col : null; + + $col = $row[TableMap::TYPE_NUM == $indexType ? 13 + $startcol : AddressColissimoPickupPointTableMap::translateFieldName('Cellphone', TableMap::TYPE_PHPNAME, $indexType)]; + $this->cellphone = (null !== $col) ? (string) $col : null; + $this->resetModified(); + + $this->setNew(false); + + if ($rehydrate) { + $this->ensureConsistency(); + } + + return $startcol + 14; // 14 = AddressColissimoPickupPointTableMap::NUM_HYDRATE_COLUMNS. + + } catch (Exception $e) { + throw new PropelException("Error populating \ColissimoPickupPoint\Model\AddressColissimoPickupPoint object", 0, $e); + } + } + + /** + * Checks and repairs the internal consistency of the object. + * + * This method is executed after an already-instantiated object is re-hydrated + * from the database. It exists to check any foreign keys to make sure that + * the objects related to the current object are correct based on foreign key. + * + * You can override this method in the stub class, but you should always invoke + * the base method from the overridden method (i.e. parent::ensureConsistency()), + * in case your model changes. + * + * @throws PropelException + */ + public function ensureConsistency() + { + if ($this->aCustomerTitle !== null && $this->title_id !== $this->aCustomerTitle->getId()) { + $this->aCustomerTitle = null; + } + if ($this->aCountry !== null && $this->country_id !== $this->aCountry->getId()) { + $this->aCountry = null; + } + } // ensureConsistency + + /** + * Reloads this object from datastore based on primary key and (optionally) resets all associated objects. + * + * This will only work if the object has been saved and has a valid primary key set. + * + * @param boolean $deep (optional) Whether to also de-associated any related objects. + * @param ConnectionInterface $con (optional) The ConnectionInterface connection to use. + * @return void + * @throws PropelException - if this object is deleted, unsaved or doesn't have pk match in db + */ + public function reload($deep = false, ConnectionInterface $con = null) + { + if ($this->isDeleted()) { + throw new PropelException("Cannot reload a deleted object."); + } + + if ($this->isNew()) { + throw new PropelException("Cannot reload an unsaved object."); + } + + if ($con === null) { + $con = Propel::getServiceContainer()->getReadConnection(AddressColissimoPickupPointTableMap::DATABASE_NAME); + } + + // We don't need to alter the object instance pool; we're just modifying this instance + // already in the pool. + + $dataFetcher = ChildAddressColissimoPickupPointQuery::create(null, $this->buildPkeyCriteria())->setFormatter(ModelCriteria::FORMAT_STATEMENT)->find($con); + $row = $dataFetcher->fetch(); + $dataFetcher->close(); + if (!$row) { + throw new PropelException('Cannot find matching row in the database to reload object values.'); + } + $this->hydrate($row, 0, true, $dataFetcher->getIndexType()); // rehydrate + + if ($deep) { // also de-associate any related objects? + + $this->aCustomerTitle = null; + $this->aCountry = null; + } // if (deep) + } + + /** + * Removes this object from datastore and sets delete attribute. + * + * @param ConnectionInterface $con + * @return void + * @throws PropelException + * @see AddressColissimoPickupPoint::setDeleted() + * @see AddressColissimoPickupPoint::isDeleted() + */ + public function delete(ConnectionInterface $con = null) + { + if ($this->isDeleted()) { + throw new PropelException("This object has already been deleted."); + } + + if ($con === null) { + $con = Propel::getServiceContainer()->getWriteConnection(AddressColissimoPickupPointTableMap::DATABASE_NAME); + } + + $con->beginTransaction(); + try { + $deleteQuery = ChildAddressColissimoPickupPointQuery::create() + ->filterByPrimaryKey($this->getPrimaryKey()); + $ret = $this->preDelete($con); + if ($ret) { + $deleteQuery->delete($con); + $this->postDelete($con); + $con->commit(); + $this->setDeleted(true); + } else { + $con->commit(); + } + } catch (Exception $e) { + $con->rollBack(); + throw $e; + } + } + + /** + * Persists this object to the database. + * + * If the object is new, it inserts it; otherwise an update is performed. + * All modified related objects will also be persisted in the doSave() + * method. This method wraps all precipitate database operations in a + * single transaction. + * + * @param ConnectionInterface $con + * @return int The number of rows affected by this insert/update and any referring fk objects' save() operations. + * @throws PropelException + * @see doSave() + */ + public function save(ConnectionInterface $con = null) + { + if ($this->isDeleted()) { + throw new PropelException("You cannot save an object that has been deleted."); + } + + if ($con === null) { + $con = Propel::getServiceContainer()->getWriteConnection(AddressColissimoPickupPointTableMap::DATABASE_NAME); + } + + $con->beginTransaction(); + $isInsert = $this->isNew(); + try { + $ret = $this->preSave($con); + if ($isInsert) { + $ret = $ret && $this->preInsert($con); + } else { + $ret = $ret && $this->preUpdate($con); + } + if ($ret) { + $affectedRows = $this->doSave($con); + if ($isInsert) { + $this->postInsert($con); + } else { + $this->postUpdate($con); + } + $this->postSave($con); + AddressColissimoPickupPointTableMap::addInstanceToPool($this); + } else { + $affectedRows = 0; + } + $con->commit(); + + return $affectedRows; + } catch (Exception $e) { + $con->rollBack(); + throw $e; + } + } + + /** + * Performs the work of inserting or updating the row in the database. + * + * If the object is new, it inserts it; otherwise an update is performed. + * All related objects are also updated in this method. + * + * @param ConnectionInterface $con + * @return int The number of rows affected by this insert/update and any referring fk objects' save() operations. + * @throws PropelException + * @see save() + */ + protected function doSave(ConnectionInterface $con) + { + $affectedRows = 0; // initialize var to track total num of affected rows + if (!$this->alreadyInSave) { + $this->alreadyInSave = true; + + // We call the save method on the following object(s) if they + // were passed to this object by their corresponding set + // method. This object relates to these object(s) by a + // foreign key reference. + + if ($this->aCustomerTitle !== null) { + if ($this->aCustomerTitle->isModified() || $this->aCustomerTitle->isNew()) { + $affectedRows += $this->aCustomerTitle->save($con); + } + $this->setCustomerTitle($this->aCustomerTitle); + } + + if ($this->aCountry !== null) { + if ($this->aCountry->isModified() || $this->aCountry->isNew()) { + $affectedRows += $this->aCountry->save($con); + } + $this->setCountry($this->aCountry); + } + + if ($this->isNew() || $this->isModified()) { + // persist changes + if ($this->isNew()) { + $this->doInsert($con); + } else { + $this->doUpdate($con); + } + $affectedRows += 1; + $this->resetModified(); + } + + $this->alreadyInSave = false; + + } + + return $affectedRows; + } // doSave() + + /** + * Insert the row in the database. + * + * @param ConnectionInterface $con + * + * @throws PropelException + * @see doSave() + */ + protected function doInsert(ConnectionInterface $con) + { + $modifiedColumns = array(); + $index = 0; + + + // check the columns in natural order for more readable SQL queries + if ($this->isColumnModified(AddressColissimoPickupPointTableMap::ID)) { + $modifiedColumns[':p' . $index++] = 'ID'; + } + if ($this->isColumnModified(AddressColissimoPickupPointTableMap::TITLE_ID)) { + $modifiedColumns[':p' . $index++] = 'TITLE_ID'; + } + if ($this->isColumnModified(AddressColissimoPickupPointTableMap::COMPANY)) { + $modifiedColumns[':p' . $index++] = 'COMPANY'; + } + if ($this->isColumnModified(AddressColissimoPickupPointTableMap::FIRSTNAME)) { + $modifiedColumns[':p' . $index++] = 'FIRSTNAME'; + } + if ($this->isColumnModified(AddressColissimoPickupPointTableMap::LASTNAME)) { + $modifiedColumns[':p' . $index++] = 'LASTNAME'; + } + if ($this->isColumnModified(AddressColissimoPickupPointTableMap::ADDRESS1)) { + $modifiedColumns[':p' . $index++] = 'ADDRESS1'; + } + if ($this->isColumnModified(AddressColissimoPickupPointTableMap::ADDRESS2)) { + $modifiedColumns[':p' . $index++] = 'ADDRESS2'; + } + if ($this->isColumnModified(AddressColissimoPickupPointTableMap::ADDRESS3)) { + $modifiedColumns[':p' . $index++] = 'ADDRESS3'; + } + if ($this->isColumnModified(AddressColissimoPickupPointTableMap::ZIPCODE)) { + $modifiedColumns[':p' . $index++] = 'ZIPCODE'; + } + if ($this->isColumnModified(AddressColissimoPickupPointTableMap::CITY)) { + $modifiedColumns[':p' . $index++] = 'CITY'; + } + if ($this->isColumnModified(AddressColissimoPickupPointTableMap::COUNTRY_ID)) { + $modifiedColumns[':p' . $index++] = 'COUNTRY_ID'; + } + if ($this->isColumnModified(AddressColissimoPickupPointTableMap::CODE)) { + $modifiedColumns[':p' . $index++] = 'CODE'; + } + if ($this->isColumnModified(AddressColissimoPickupPointTableMap::TYPE)) { + $modifiedColumns[':p' . $index++] = 'TYPE'; + } + if ($this->isColumnModified(AddressColissimoPickupPointTableMap::CELLPHONE)) { + $modifiedColumns[':p' . $index++] = 'CELLPHONE'; + } + + $sql = sprintf( + 'INSERT INTO address_colissimo_pickup_point (%s) VALUES (%s)', + implode(', ', $modifiedColumns), + implode(', ', array_keys($modifiedColumns)) + ); + + try { + $stmt = $con->prepare($sql); + foreach ($modifiedColumns as $identifier => $columnName) { + switch ($columnName) { + case 'ID': + $stmt->bindValue($identifier, $this->id, PDO::PARAM_INT); + break; + case 'TITLE_ID': + $stmt->bindValue($identifier, $this->title_id, PDO::PARAM_INT); + break; + case 'COMPANY': + $stmt->bindValue($identifier, $this->company, PDO::PARAM_STR); + break; + case 'FIRSTNAME': + $stmt->bindValue($identifier, $this->firstname, PDO::PARAM_STR); + break; + case 'LASTNAME': + $stmt->bindValue($identifier, $this->lastname, PDO::PARAM_STR); + break; + case 'ADDRESS1': + $stmt->bindValue($identifier, $this->address1, PDO::PARAM_STR); + break; + case 'ADDRESS2': + $stmt->bindValue($identifier, $this->address2, PDO::PARAM_STR); + break; + case 'ADDRESS3': + $stmt->bindValue($identifier, $this->address3, PDO::PARAM_STR); + break; + case 'ZIPCODE': + $stmt->bindValue($identifier, $this->zipcode, PDO::PARAM_STR); + break; + case 'CITY': + $stmt->bindValue($identifier, $this->city, PDO::PARAM_STR); + break; + case 'COUNTRY_ID': + $stmt->bindValue($identifier, $this->country_id, PDO::PARAM_INT); + break; + case 'CODE': + $stmt->bindValue($identifier, $this->code, PDO::PARAM_STR); + break; + case 'TYPE': + $stmt->bindValue($identifier, $this->type, PDO::PARAM_STR); + break; + case 'CELLPHONE': + $stmt->bindValue($identifier, $this->cellphone, PDO::PARAM_STR); + break; + } + } + $stmt->execute(); + } catch (Exception $e) { + Propel::log($e->getMessage(), Propel::LOG_ERR); + throw new PropelException(sprintf('Unable to execute INSERT statement [%s]', $sql), 0, $e); + } + + $this->setNew(false); + } + + /** + * Update the row in the database. + * + * @param ConnectionInterface $con + * + * @return Integer Number of updated rows + * @see doSave() + */ + protected function doUpdate(ConnectionInterface $con) + { + $selectCriteria = $this->buildPkeyCriteria(); + $valuesCriteria = $this->buildCriteria(); + + return $selectCriteria->doUpdate($valuesCriteria, $con); + } + + /** + * Retrieves a field from the object by name passed in as a string. + * + * @param string $name name + * @param string $type The type of fieldname the $name is of: + * one of the class type constants TableMap::TYPE_PHPNAME, TableMap::TYPE_STUDLYPHPNAME + * TableMap::TYPE_COLNAME, TableMap::TYPE_FIELDNAME, TableMap::TYPE_NUM. + * Defaults to TableMap::TYPE_PHPNAME. + * @return mixed Value of field. + */ + public function getByName($name, $type = TableMap::TYPE_PHPNAME) + { + $pos = AddressColissimoPickupPointTableMap::translateFieldName($name, $type, TableMap::TYPE_NUM); + $field = $this->getByPosition($pos); + + return $field; + } + + /** + * Retrieves a field from the object by Position as specified in the xml schema. + * Zero-based. + * + * @param int $pos position in xml schema + * @return mixed Value of field at $pos + */ + public function getByPosition($pos) + { + switch ($pos) { + case 0: + return $this->getId(); + break; + case 1: + return $this->getTitleId(); + break; + case 2: + return $this->getCompany(); + break; + case 3: + return $this->getFirstname(); + break; + case 4: + return $this->getLastname(); + break; + case 5: + return $this->getAddress1(); + break; + case 6: + return $this->getAddress2(); + break; + case 7: + return $this->getAddress3(); + break; + case 8: + return $this->getZipcode(); + break; + case 9: + return $this->getCity(); + break; + case 10: + return $this->getCountryId(); + break; + case 11: + return $this->getCode(); + break; + case 12: + return $this->getType(); + break; + case 13: + return $this->getCellphone(); + break; + default: + return null; + break; + } // switch() + } + + /** + * Exports the object as an array. + * + * You can specify the key type of the array by passing one of the class + * type constants. + * + * @param string $keyType (optional) One of the class type constants TableMap::TYPE_PHPNAME, TableMap::TYPE_STUDLYPHPNAME, + * TableMap::TYPE_COLNAME, TableMap::TYPE_FIELDNAME, TableMap::TYPE_NUM. + * Defaults to TableMap::TYPE_PHPNAME. + * @param boolean $includeLazyLoadColumns (optional) Whether to include lazy loaded columns. Defaults to TRUE. + * @param array $alreadyDumpedObjects List of objects to skip to avoid recursion + * @param boolean $includeForeignObjects (optional) Whether to include hydrated related objects. Default to FALSE. + * + * @return array an associative array containing the field names (as keys) and field values + */ + public function toArray($keyType = TableMap::TYPE_PHPNAME, $includeLazyLoadColumns = true, $alreadyDumpedObjects = array(), $includeForeignObjects = false) + { + if (isset($alreadyDumpedObjects['AddressColissimoPickupPoint'][$this->getPrimaryKey()])) { + return '*RECURSION*'; + } + $alreadyDumpedObjects['AddressColissimoPickupPoint'][$this->getPrimaryKey()] = true; + $keys = AddressColissimoPickupPointTableMap::getFieldNames($keyType); + $result = array( + $keys[0] => $this->getId(), + $keys[1] => $this->getTitleId(), + $keys[2] => $this->getCompany(), + $keys[3] => $this->getFirstname(), + $keys[4] => $this->getLastname(), + $keys[5] => $this->getAddress1(), + $keys[6] => $this->getAddress2(), + $keys[7] => $this->getAddress3(), + $keys[8] => $this->getZipcode(), + $keys[9] => $this->getCity(), + $keys[10] => $this->getCountryId(), + $keys[11] => $this->getCode(), + $keys[12] => $this->getType(), + $keys[13] => $this->getCellphone(), + ); + $virtualColumns = $this->virtualColumns; + foreach ($virtualColumns as $key => $virtualColumn) { + $result[$key] = $virtualColumn; + } + + if ($includeForeignObjects) { + if (null !== $this->aCustomerTitle) { + $result['CustomerTitle'] = $this->aCustomerTitle->toArray($keyType, $includeLazyLoadColumns, $alreadyDumpedObjects, true); + } + if (null !== $this->aCountry) { + $result['Country'] = $this->aCountry->toArray($keyType, $includeLazyLoadColumns, $alreadyDumpedObjects, true); + } + } + + return $result; + } + + /** + * Sets a field from the object by name passed in as a string. + * + * @param string $name + * @param mixed $value field value + * @param string $type The type of fieldname the $name is of: + * one of the class type constants TableMap::TYPE_PHPNAME, TableMap::TYPE_STUDLYPHPNAME + * TableMap::TYPE_COLNAME, TableMap::TYPE_FIELDNAME, TableMap::TYPE_NUM. + * Defaults to TableMap::TYPE_PHPNAME. + * @return void + */ + public function setByName($name, $value, $type = TableMap::TYPE_PHPNAME) + { + $pos = AddressColissimoPickupPointTableMap::translateFieldName($name, $type, TableMap::TYPE_NUM); + + return $this->setByPosition($pos, $value); + } + + /** + * Sets a field from the object by Position as specified in the xml schema. + * Zero-based. + * + * @param int $pos position in xml schema + * @param mixed $value field value + * @return void + */ + public function setByPosition($pos, $value) + { + switch ($pos) { + case 0: + $this->setId($value); + break; + case 1: + $this->setTitleId($value); + break; + case 2: + $this->setCompany($value); + break; + case 3: + $this->setFirstname($value); + break; + case 4: + $this->setLastname($value); + break; + case 5: + $this->setAddress1($value); + break; + case 6: + $this->setAddress2($value); + break; + case 7: + $this->setAddress3($value); + break; + case 8: + $this->setZipcode($value); + break; + case 9: + $this->setCity($value); + break; + case 10: + $this->setCountryId($value); + break; + case 11: + $this->setCode($value); + break; + case 12: + $this->setType($value); + break; + case 13: + $this->setCellphone($value); + break; + } // switch() + } + + /** + * Populates the object using an array. + * + * This is particularly useful when populating an object from one of the + * request arrays (e.g. $_POST). This method goes through the column + * names, checking to see whether a matching key exists in populated + * array. If so the setByName() method is called for that column. + * + * You can specify the key type of the array by additionally passing one + * of the class type constants TableMap::TYPE_PHPNAME, TableMap::TYPE_STUDLYPHPNAME, + * TableMap::TYPE_COLNAME, TableMap::TYPE_FIELDNAME, TableMap::TYPE_NUM. + * The default key type is the column's TableMap::TYPE_PHPNAME. + * + * @param array $arr An array to populate the object from. + * @param string $keyType The type of keys the array uses. + * @return void + */ + public function fromArray($arr, $keyType = TableMap::TYPE_PHPNAME) + { + $keys = AddressColissimoPickupPointTableMap::getFieldNames($keyType); + + if (array_key_exists($keys[0], $arr)) $this->setId($arr[$keys[0]]); + if (array_key_exists($keys[1], $arr)) $this->setTitleId($arr[$keys[1]]); + if (array_key_exists($keys[2], $arr)) $this->setCompany($arr[$keys[2]]); + if (array_key_exists($keys[3], $arr)) $this->setFirstname($arr[$keys[3]]); + if (array_key_exists($keys[4], $arr)) $this->setLastname($arr[$keys[4]]); + if (array_key_exists($keys[5], $arr)) $this->setAddress1($arr[$keys[5]]); + if (array_key_exists($keys[6], $arr)) $this->setAddress2($arr[$keys[6]]); + if (array_key_exists($keys[7], $arr)) $this->setAddress3($arr[$keys[7]]); + if (array_key_exists($keys[8], $arr)) $this->setZipcode($arr[$keys[8]]); + if (array_key_exists($keys[9], $arr)) $this->setCity($arr[$keys[9]]); + if (array_key_exists($keys[10], $arr)) $this->setCountryId($arr[$keys[10]]); + if (array_key_exists($keys[11], $arr)) $this->setCode($arr[$keys[11]]); + if (array_key_exists($keys[12], $arr)) $this->setType($arr[$keys[12]]); + if (array_key_exists($keys[13], $arr)) $this->setCellphone($arr[$keys[13]]); + } + + /** + * Build a Criteria object containing the values of all modified columns in this object. + * + * @return Criteria The Criteria object containing all modified values. + */ + public function buildCriteria() + { + $criteria = new Criteria(AddressColissimoPickupPointTableMap::DATABASE_NAME); + + if ($this->isColumnModified(AddressColissimoPickupPointTableMap::ID)) $criteria->add(AddressColissimoPickupPointTableMap::ID, $this->id); + if ($this->isColumnModified(AddressColissimoPickupPointTableMap::TITLE_ID)) $criteria->add(AddressColissimoPickupPointTableMap::TITLE_ID, $this->title_id); + if ($this->isColumnModified(AddressColissimoPickupPointTableMap::COMPANY)) $criteria->add(AddressColissimoPickupPointTableMap::COMPANY, $this->company); + if ($this->isColumnModified(AddressColissimoPickupPointTableMap::FIRSTNAME)) $criteria->add(AddressColissimoPickupPointTableMap::FIRSTNAME, $this->firstname); + if ($this->isColumnModified(AddressColissimoPickupPointTableMap::LASTNAME)) $criteria->add(AddressColissimoPickupPointTableMap::LASTNAME, $this->lastname); + if ($this->isColumnModified(AddressColissimoPickupPointTableMap::ADDRESS1)) $criteria->add(AddressColissimoPickupPointTableMap::ADDRESS1, $this->address1); + if ($this->isColumnModified(AddressColissimoPickupPointTableMap::ADDRESS2)) $criteria->add(AddressColissimoPickupPointTableMap::ADDRESS2, $this->address2); + if ($this->isColumnModified(AddressColissimoPickupPointTableMap::ADDRESS3)) $criteria->add(AddressColissimoPickupPointTableMap::ADDRESS3, $this->address3); + if ($this->isColumnModified(AddressColissimoPickupPointTableMap::ZIPCODE)) $criteria->add(AddressColissimoPickupPointTableMap::ZIPCODE, $this->zipcode); + if ($this->isColumnModified(AddressColissimoPickupPointTableMap::CITY)) $criteria->add(AddressColissimoPickupPointTableMap::CITY, $this->city); + if ($this->isColumnModified(AddressColissimoPickupPointTableMap::COUNTRY_ID)) $criteria->add(AddressColissimoPickupPointTableMap::COUNTRY_ID, $this->country_id); + if ($this->isColumnModified(AddressColissimoPickupPointTableMap::CODE)) $criteria->add(AddressColissimoPickupPointTableMap::CODE, $this->code); + if ($this->isColumnModified(AddressColissimoPickupPointTableMap::TYPE)) $criteria->add(AddressColissimoPickupPointTableMap::TYPE, $this->type); + if ($this->isColumnModified(AddressColissimoPickupPointTableMap::CELLPHONE)) $criteria->add(AddressColissimoPickupPointTableMap::CELLPHONE, $this->cellphone); + + return $criteria; + } + + /** + * Builds a Criteria object containing the primary key for this object. + * + * Unlike buildCriteria() this method includes the primary key values regardless + * of whether or not they have been modified. + * + * @return Criteria The Criteria object containing value(s) for primary key(s). + */ + public function buildPkeyCriteria() + { + $criteria = new Criteria(AddressColissimoPickupPointTableMap::DATABASE_NAME); + $criteria->add(AddressColissimoPickupPointTableMap::ID, $this->id); + + return $criteria; + } + + /** + * Returns the primary key for this object (row). + * @return int + */ + public function getPrimaryKey() + { + return $this->getId(); + } + + /** + * Generic method to set the primary key (id column). + * + * @param int $key Primary key. + * @return void + */ + public function setPrimaryKey($key) + { + $this->setId($key); + } + + /** + * Returns true if the primary key for this object is null. + * @return boolean + */ + public function isPrimaryKeyNull() + { + + return null === $this->getId(); + } + + /** + * Sets contents of passed object to values from current object. + * + * If desired, this method can also make copies of all associated (fkey referrers) + * objects. + * + * @param object $copyObj An object of \ColissimoPickupPoint\Model\AddressColissimoPickupPoint (or compatible) type. + * @param boolean $deepCopy Whether to also copy all rows that refer (by fkey) to the current row. + * @param boolean $makeNew Whether to reset autoincrement PKs and make the object new. + * @throws PropelException + */ + public function copyInto($copyObj, $deepCopy = false, $makeNew = true) + { + $copyObj->setId($this->getId()); + $copyObj->setTitleId($this->getTitleId()); + $copyObj->setCompany($this->getCompany()); + $copyObj->setFirstname($this->getFirstname()); + $copyObj->setLastname($this->getLastname()); + $copyObj->setAddress1($this->getAddress1()); + $copyObj->setAddress2($this->getAddress2()); + $copyObj->setAddress3($this->getAddress3()); + $copyObj->setZipcode($this->getZipcode()); + $copyObj->setCity($this->getCity()); + $copyObj->setCountryId($this->getCountryId()); + $copyObj->setCode($this->getCode()); + $copyObj->setType($this->getType()); + $copyObj->setCellphone($this->getCellphone()); + if ($makeNew) { + $copyObj->setNew(true); + } + } + + /** + * Makes a copy of this object that will be inserted as a new row in table when saved. + * It creates a new object filling in the simple attributes, but skipping any primary + * keys that are defined for the table. + * + * If desired, this method can also make copies of all associated (fkey referrers) + * objects. + * + * @param boolean $deepCopy Whether to also copy all rows that refer (by fkey) to the current row. + * @return \ColissimoPickupPoint\Model\AddressColissimoPickupPoint Clone of current object. + * @throws PropelException + */ + public function copy($deepCopy = false) + { + // we use get_class(), because this might be a subclass + $clazz = get_class($this); + $copyObj = new $clazz(); + $this->copyInto($copyObj, $deepCopy); + + return $copyObj; + } + + /** + * Declares an association between this object and a ChildCustomerTitle object. + * + * @param ChildCustomerTitle $v + * @return \ColissimoPickupPoint\Model\AddressColissimoPickupPoint The current object (for fluent API support) + * @throws PropelException + */ + public function setCustomerTitle(ChildCustomerTitle $v = null) + { + if ($v === null) { + $this->setTitleId(NULL); + } else { + $this->setTitleId($v->getId()); + } + + $this->aCustomerTitle = $v; + + // Add binding for other direction of this n:n relationship. + // If this object has already been added to the ChildCustomerTitle object, it will not be re-added. + if ($v !== null) { + $v->addAddressColissimoPickupPoint($this); + } + + + return $this; + } + + + /** + * Get the associated ChildCustomerTitle object + * + * @param ConnectionInterface $con Optional Connection object. + * @return ChildCustomerTitle The associated ChildCustomerTitle object. + * @throws PropelException + */ + public function getCustomerTitle(ConnectionInterface $con = null) + { + if ($this->aCustomerTitle === null && ($this->title_id !== null)) { + $this->aCustomerTitle = CustomerTitleQuery::create()->findPk($this->title_id, $con); + /* The following can be used additionally to + guarantee the related object contains a reference + to this object. This level of coupling may, however, be + undesirable since it could result in an only partially populated collection + in the referenced object. + $this->aCustomerTitle->addAddressColissimoPickupPoints($this); + */ + } + + return $this->aCustomerTitle; + } + + /** + * Declares an association between this object and a ChildCountry object. + * + * @param ChildCountry $v + * @return \ColissimoPickupPoint\Model\AddressColissimoPickupPoint The current object (for fluent API support) + * @throws PropelException + */ + public function setCountry(ChildCountry $v = null) + { + if ($v === null) { + $this->setCountryId(NULL); + } else { + $this->setCountryId($v->getId()); + } + + $this->aCountry = $v; + + // Add binding for other direction of this n:n relationship. + // If this object has already been added to the ChildCountry object, it will not be re-added. + if ($v !== null) { + $v->addAddressColissimoPickupPoint($this); + } + + + return $this; + } + + + /** + * Get the associated ChildCountry object + * + * @param ConnectionInterface $con Optional Connection object. + * @return ChildCountry The associated ChildCountry object. + * @throws PropelException + */ + public function getCountry(ConnectionInterface $con = null) + { + if ($this->aCountry === null && ($this->country_id !== null)) { + $this->aCountry = CountryQuery::create()->findPk($this->country_id, $con); + /* The following can be used additionally to + guarantee the related object contains a reference + to this object. This level of coupling may, however, be + undesirable since it could result in an only partially populated collection + in the referenced object. + $this->aCountry->addAddressColissimoPickupPoints($this); + */ + } + + return $this->aCountry; + } + + /** + * Clears the current object and sets all attributes to their default values + */ + public function clear() + { + $this->id = null; + $this->title_id = null; + $this->company = null; + $this->firstname = null; + $this->lastname = null; + $this->address1 = null; + $this->address2 = null; + $this->address3 = null; + $this->zipcode = null; + $this->city = null; + $this->country_id = null; + $this->code = null; + $this->type = null; + $this->cellphone = null; + $this->alreadyInSave = false; + $this->clearAllReferences(); + $this->resetModified(); + $this->setNew(true); + $this->setDeleted(false); + } + + /** + * Resets all references to other model objects or collections of model objects. + * + * This method is a user-space workaround for PHP's inability to garbage collect + * objects with circular references (even in PHP 5.3). This is currently necessary + * when using Propel in certain daemon or large-volume/high-memory operations. + * + * @param boolean $deep Whether to also clear the references on all referrer objects. + */ + public function clearAllReferences($deep = false) + { + if ($deep) { + } // if ($deep) + + $this->aCustomerTitle = null; + $this->aCountry = null; + } + + /** + * Return the string representation of this object + * + * @return string + */ + public function __toString() + { + return (string) $this->exportTo(AddressColissimoPickupPointTableMap::DEFAULT_STRING_FORMAT); + } + + /** + * Code to be run before persisting the object + * @param ConnectionInterface $con + * @return boolean + */ + public function preSave(ConnectionInterface $con = null) + { + return true; + } + + /** + * Code to be run after persisting the object + * @param ConnectionInterface $con + */ + public function postSave(ConnectionInterface $con = null) + { + + } + + /** + * Code to be run before inserting to database + * @param ConnectionInterface $con + * @return boolean + */ + public function preInsert(ConnectionInterface $con = null) + { + return true; + } + + /** + * Code to be run after inserting to database + * @param ConnectionInterface $con + */ + public function postInsert(ConnectionInterface $con = null) + { + + } + + /** + * Code to be run before updating the object in database + * @param ConnectionInterface $con + * @return boolean + */ + public function preUpdate(ConnectionInterface $con = null) + { + return true; + } + + /** + * Code to be run after updating the object in database + * @param ConnectionInterface $con + */ + public function postUpdate(ConnectionInterface $con = null) + { + + } + + /** + * Code to be run before deleting the object in database + * @param ConnectionInterface $con + * @return boolean + */ + public function preDelete(ConnectionInterface $con = null) + { + return true; + } + + /** + * Code to be run after deleting the object in database + * @param ConnectionInterface $con + */ + public function postDelete(ConnectionInterface $con = null) + { + + } + + + /** + * Derived method to catches calls to undefined methods. + * + * Provides magic import/export method support (fromXML()/toXML(), fromYAML()/toYAML(), etc.). + * Allows to define default __call() behavior if you overwrite __call() + * + * @param string $name + * @param mixed $params + * + * @return array|string + */ + public function __call($name, $params) + { + if (0 === strpos($name, 'get')) { + $virtualColumn = substr($name, 3); + if ($this->hasVirtualColumn($virtualColumn)) { + return $this->getVirtualColumn($virtualColumn); + } + + $virtualColumn = lcfirst($virtualColumn); + if ($this->hasVirtualColumn($virtualColumn)) { + return $this->getVirtualColumn($virtualColumn); + } + } + + if (0 === strpos($name, 'from')) { + $format = substr($name, 4); + + return $this->importFrom($format, reset($params)); + } + + if (0 === strpos($name, 'to')) { + $format = substr($name, 2); + $includeLazyLoadColumns = isset($params[0]) ? $params[0] : true; + + return $this->exportTo($format, $includeLazyLoadColumns); + } + + throw new BadMethodCallException(sprintf('Call to undefined method: %s.', $name)); + } + +} diff --git a/local/modules/ColissimoPickupPoint/Model/Base/AddressColissimoPickupPointQuery.php b/local/modules/ColissimoPickupPoint/Model/Base/AddressColissimoPickupPointQuery.php new file mode 100644 index 00000000..5fde914b --- /dev/null +++ b/local/modules/ColissimoPickupPoint/Model/Base/AddressColissimoPickupPointQuery.php @@ -0,0 +1,964 @@ +setModelAlias($modelAlias); + } + if ($criteria instanceof Criteria) { + $query->mergeWith($criteria); + } + + return $query; + } + + /** + * Find object by primary key. + * Propel uses the instance pool to skip the database if the object exists. + * Go fast if the query is untouched. + * + * + * $obj = $c->findPk(12, $con); + * + * + * @param mixed $key Primary key to use for the query + * @param ConnectionInterface $con an optional connection object + * + * @return ChildAddressColissimoPickupPoint|array|mixed the result, formatted by the current formatter + */ + public function findPk($key, $con = null) + { + if ($key === null) { + return null; + } + if ((null !== ($obj = AddressColissimoPickupPointTableMap::getInstanceFromPool((string) $key))) && !$this->formatter) { + // the object is already in the instance pool + return $obj; + } + if ($con === null) { + $con = Propel::getServiceContainer()->getReadConnection(AddressColissimoPickupPointTableMap::DATABASE_NAME); + } + $this->basePreSelect($con); + if ($this->formatter || $this->modelAlias || $this->with || $this->select + || $this->selectColumns || $this->asColumns || $this->selectModifiers + || $this->map || $this->having || $this->joins) { + return $this->findPkComplex($key, $con); + } else { + return $this->findPkSimple($key, $con); + } + } + + /** + * Find object by primary key using raw SQL to go fast. + * Bypass doSelect() and the object formatter by using generated code. + * + * @param mixed $key Primary key to use for the query + * @param ConnectionInterface $con A connection object + * + * @return ChildAddressColissimoPickupPoint A model object, or null if the key is not found + */ + protected function findPkSimple($key, $con) + { + $sql = 'SELECT ID, TITLE_ID, COMPANY, FIRSTNAME, LASTNAME, ADDRESS1, ADDRESS2, ADDRESS3, ZIPCODE, CITY, COUNTRY_ID, CODE, TYPE, CELLPHONE FROM address_colissimo_pickup_point WHERE ID = :p0'; + try { + $stmt = $con->prepare($sql); + $stmt->bindValue(':p0', $key, PDO::PARAM_INT); + $stmt->execute(); + } catch (Exception $e) { + Propel::log($e->getMessage(), Propel::LOG_ERR); + throw new PropelException(sprintf('Unable to execute SELECT statement [%s]', $sql), 0, $e); + } + $obj = null; + if ($row = $stmt->fetch(\PDO::FETCH_NUM)) { + $obj = new ChildAddressColissimoPickupPoint(); + $obj->hydrate($row); + AddressColissimoPickupPointTableMap::addInstanceToPool($obj, (string) $key); + } + $stmt->closeCursor(); + + return $obj; + } + + /** + * Find object by primary key. + * + * @param mixed $key Primary key to use for the query + * @param ConnectionInterface $con A connection object + * + * @return ChildAddressColissimoPickupPoint|array|mixed the result, formatted by the current formatter + */ + protected function findPkComplex($key, $con) + { + // As the query uses a PK condition, no limit(1) is necessary. + $criteria = $this->isKeepQuery() ? clone $this : $this; + $dataFetcher = $criteria + ->filterByPrimaryKey($key) + ->doSelect($con); + + return $criteria->getFormatter()->init($criteria)->formatOne($dataFetcher); + } + + /** + * Find objects by primary key + * + * $objs = $c->findPks(array(12, 56, 832), $con); + * + * @param array $keys Primary keys to use for the query + * @param ConnectionInterface $con an optional connection object + * + * @return ObjectCollection|array|mixed the list of results, formatted by the current formatter + */ + public function findPks($keys, $con = null) + { + if (null === $con) { + $con = Propel::getServiceContainer()->getReadConnection($this->getDbName()); + } + $this->basePreSelect($con); + $criteria = $this->isKeepQuery() ? clone $this : $this; + $dataFetcher = $criteria + ->filterByPrimaryKeys($keys) + ->doSelect($con); + + return $criteria->getFormatter()->init($criteria)->format($dataFetcher); + } + + /** + * Filter the query by primary key + * + * @param mixed $key Primary key to use for the query + * + * @return ChildAddressColissimoPickupPointQuery The current query, for fluid interface + */ + public function filterByPrimaryKey($key) + { + + return $this->addUsingAlias(AddressColissimoPickupPointTableMap::ID, $key, Criteria::EQUAL); + } + + /** + * Filter the query by a list of primary keys + * + * @param array $keys The list of primary key to use for the query + * + * @return ChildAddressColissimoPickupPointQuery The current query, for fluid interface + */ + public function filterByPrimaryKeys($keys) + { + + return $this->addUsingAlias(AddressColissimoPickupPointTableMap::ID, $keys, Criteria::IN); + } + + /** + * Filter the query on the id column + * + * Example usage: + * + * $query->filterById(1234); // WHERE id = 1234 + * $query->filterById(array(12, 34)); // WHERE id IN (12, 34) + * $query->filterById(array('min' => 12)); // WHERE id > 12 + * + * + * @param mixed $id The value to use as filter. + * Use scalar values for equality. + * Use array values for in_array() equivalent. + * Use associative array('min' => $minValue, 'max' => $maxValue) for intervals. + * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL + * + * @return ChildAddressColissimoPickupPointQuery The current query, for fluid interface + */ + public function filterById($id = null, $comparison = null) + { + if (is_array($id)) { + $useMinMax = false; + if (isset($id['min'])) { + $this->addUsingAlias(AddressColissimoPickupPointTableMap::ID, $id['min'], Criteria::GREATER_EQUAL); + $useMinMax = true; + } + if (isset($id['max'])) { + $this->addUsingAlias(AddressColissimoPickupPointTableMap::ID, $id['max'], Criteria::LESS_EQUAL); + $useMinMax = true; + } + if ($useMinMax) { + return $this; + } + if (null === $comparison) { + $comparison = Criteria::IN; + } + } + + return $this->addUsingAlias(AddressColissimoPickupPointTableMap::ID, $id, $comparison); + } + + /** + * Filter the query on the title_id column + * + * Example usage: + * + * $query->filterByTitleId(1234); // WHERE title_id = 1234 + * $query->filterByTitleId(array(12, 34)); // WHERE title_id IN (12, 34) + * $query->filterByTitleId(array('min' => 12)); // WHERE title_id > 12 + * + * + * @see filterByCustomerTitle() + * + * @param mixed $titleId The value to use as filter. + * Use scalar values for equality. + * Use array values for in_array() equivalent. + * Use associative array('min' => $minValue, 'max' => $maxValue) for intervals. + * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL + * + * @return ChildAddressColissimoPickupPointQuery The current query, for fluid interface + */ + public function filterByTitleId($titleId = null, $comparison = null) + { + if (is_array($titleId)) { + $useMinMax = false; + if (isset($titleId['min'])) { + $this->addUsingAlias(AddressColissimoPickupPointTableMap::TITLE_ID, $titleId['min'], Criteria::GREATER_EQUAL); + $useMinMax = true; + } + if (isset($titleId['max'])) { + $this->addUsingAlias(AddressColissimoPickupPointTableMap::TITLE_ID, $titleId['max'], Criteria::LESS_EQUAL); + $useMinMax = true; + } + if ($useMinMax) { + return $this; + } + if (null === $comparison) { + $comparison = Criteria::IN; + } + } + + return $this->addUsingAlias(AddressColissimoPickupPointTableMap::TITLE_ID, $titleId, $comparison); + } + + /** + * Filter the query on the company column + * + * Example usage: + * + * $query->filterByCompany('fooValue'); // WHERE company = 'fooValue' + * $query->filterByCompany('%fooValue%'); // WHERE company LIKE '%fooValue%' + * + * + * @param string $company The value to use as filter. + * Accepts wildcards (* and % trigger a LIKE) + * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL + * + * @return ChildAddressColissimoPickupPointQuery The current query, for fluid interface + */ + public function filterByCompany($company = null, $comparison = null) + { + if (null === $comparison) { + if (is_array($company)) { + $comparison = Criteria::IN; + } elseif (preg_match('/[\%\*]/', $company)) { + $company = str_replace('*', '%', $company); + $comparison = Criteria::LIKE; + } + } + + return $this->addUsingAlias(AddressColissimoPickupPointTableMap::COMPANY, $company, $comparison); + } + + /** + * Filter the query on the firstname column + * + * Example usage: + * + * $query->filterByFirstname('fooValue'); // WHERE firstname = 'fooValue' + * $query->filterByFirstname('%fooValue%'); // WHERE firstname LIKE '%fooValue%' + * + * + * @param string $firstname The value to use as filter. + * Accepts wildcards (* and % trigger a LIKE) + * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL + * + * @return ChildAddressColissimoPickupPointQuery The current query, for fluid interface + */ + public function filterByFirstname($firstname = null, $comparison = null) + { + if (null === $comparison) { + if (is_array($firstname)) { + $comparison = Criteria::IN; + } elseif (preg_match('/[\%\*]/', $firstname)) { + $firstname = str_replace('*', '%', $firstname); + $comparison = Criteria::LIKE; + } + } + + return $this->addUsingAlias(AddressColissimoPickupPointTableMap::FIRSTNAME, $firstname, $comparison); + } + + /** + * Filter the query on the lastname column + * + * Example usage: + * + * $query->filterByLastname('fooValue'); // WHERE lastname = 'fooValue' + * $query->filterByLastname('%fooValue%'); // WHERE lastname LIKE '%fooValue%' + * + * + * @param string $lastname The value to use as filter. + * Accepts wildcards (* and % trigger a LIKE) + * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL + * + * @return ChildAddressColissimoPickupPointQuery The current query, for fluid interface + */ + public function filterByLastname($lastname = null, $comparison = null) + { + if (null === $comparison) { + if (is_array($lastname)) { + $comparison = Criteria::IN; + } elseif (preg_match('/[\%\*]/', $lastname)) { + $lastname = str_replace('*', '%', $lastname); + $comparison = Criteria::LIKE; + } + } + + return $this->addUsingAlias(AddressColissimoPickupPointTableMap::LASTNAME, $lastname, $comparison); + } + + /** + * Filter the query on the address1 column + * + * Example usage: + * + * $query->filterByAddress1('fooValue'); // WHERE address1 = 'fooValue' + * $query->filterByAddress1('%fooValue%'); // WHERE address1 LIKE '%fooValue%' + * + * + * @param string $address1 The value to use as filter. + * Accepts wildcards (* and % trigger a LIKE) + * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL + * + * @return ChildAddressColissimoPickupPointQuery The current query, for fluid interface + */ + public function filterByAddress1($address1 = null, $comparison = null) + { + if (null === $comparison) { + if (is_array($address1)) { + $comparison = Criteria::IN; + } elseif (preg_match('/[\%\*]/', $address1)) { + $address1 = str_replace('*', '%', $address1); + $comparison = Criteria::LIKE; + } + } + + return $this->addUsingAlias(AddressColissimoPickupPointTableMap::ADDRESS1, $address1, $comparison); + } + + /** + * Filter the query on the address2 column + * + * Example usage: + * + * $query->filterByAddress2('fooValue'); // WHERE address2 = 'fooValue' + * $query->filterByAddress2('%fooValue%'); // WHERE address2 LIKE '%fooValue%' + * + * + * @param string $address2 The value to use as filter. + * Accepts wildcards (* and % trigger a LIKE) + * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL + * + * @return ChildAddressColissimoPickupPointQuery The current query, for fluid interface + */ + public function filterByAddress2($address2 = null, $comparison = null) + { + if (null === $comparison) { + if (is_array($address2)) { + $comparison = Criteria::IN; + } elseif (preg_match('/[\%\*]/', $address2)) { + $address2 = str_replace('*', '%', $address2); + $comparison = Criteria::LIKE; + } + } + + return $this->addUsingAlias(AddressColissimoPickupPointTableMap::ADDRESS2, $address2, $comparison); + } + + /** + * Filter the query on the address3 column + * + * Example usage: + * + * $query->filterByAddress3('fooValue'); // WHERE address3 = 'fooValue' + * $query->filterByAddress3('%fooValue%'); // WHERE address3 LIKE '%fooValue%' + * + * + * @param string $address3 The value to use as filter. + * Accepts wildcards (* and % trigger a LIKE) + * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL + * + * @return ChildAddressColissimoPickupPointQuery The current query, for fluid interface + */ + public function filterByAddress3($address3 = null, $comparison = null) + { + if (null === $comparison) { + if (is_array($address3)) { + $comparison = Criteria::IN; + } elseif (preg_match('/[\%\*]/', $address3)) { + $address3 = str_replace('*', '%', $address3); + $comparison = Criteria::LIKE; + } + } + + return $this->addUsingAlias(AddressColissimoPickupPointTableMap::ADDRESS3, $address3, $comparison); + } + + /** + * Filter the query on the zipcode column + * + * Example usage: + * + * $query->filterByZipcode('fooValue'); // WHERE zipcode = 'fooValue' + * $query->filterByZipcode('%fooValue%'); // WHERE zipcode LIKE '%fooValue%' + * + * + * @param string $zipcode The value to use as filter. + * Accepts wildcards (* and % trigger a LIKE) + * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL + * + * @return ChildAddressColissimoPickupPointQuery The current query, for fluid interface + */ + public function filterByZipcode($zipcode = null, $comparison = null) + { + if (null === $comparison) { + if (is_array($zipcode)) { + $comparison = Criteria::IN; + } elseif (preg_match('/[\%\*]/', $zipcode)) { + $zipcode = str_replace('*', '%', $zipcode); + $comparison = Criteria::LIKE; + } + } + + return $this->addUsingAlias(AddressColissimoPickupPointTableMap::ZIPCODE, $zipcode, $comparison); + } + + /** + * Filter the query on the city column + * + * Example usage: + * + * $query->filterByCity('fooValue'); // WHERE city = 'fooValue' + * $query->filterByCity('%fooValue%'); // WHERE city LIKE '%fooValue%' + * + * + * @param string $city The value to use as filter. + * Accepts wildcards (* and % trigger a LIKE) + * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL + * + * @return ChildAddressColissimoPickupPointQuery The current query, for fluid interface + */ + public function filterByCity($city = null, $comparison = null) + { + if (null === $comparison) { + if (is_array($city)) { + $comparison = Criteria::IN; + } elseif (preg_match('/[\%\*]/', $city)) { + $city = str_replace('*', '%', $city); + $comparison = Criteria::LIKE; + } + } + + return $this->addUsingAlias(AddressColissimoPickupPointTableMap::CITY, $city, $comparison); + } + + /** + * Filter the query on the country_id column + * + * Example usage: + * + * $query->filterByCountryId(1234); // WHERE country_id = 1234 + * $query->filterByCountryId(array(12, 34)); // WHERE country_id IN (12, 34) + * $query->filterByCountryId(array('min' => 12)); // WHERE country_id > 12 + * + * + * @see filterByCountry() + * + * @param mixed $countryId The value to use as filter. + * Use scalar values for equality. + * Use array values for in_array() equivalent. + * Use associative array('min' => $minValue, 'max' => $maxValue) for intervals. + * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL + * + * @return ChildAddressColissimoPickupPointQuery The current query, for fluid interface + */ + public function filterByCountryId($countryId = null, $comparison = null) + { + if (is_array($countryId)) { + $useMinMax = false; + if (isset($countryId['min'])) { + $this->addUsingAlias(AddressColissimoPickupPointTableMap::COUNTRY_ID, $countryId['min'], Criteria::GREATER_EQUAL); + $useMinMax = true; + } + if (isset($countryId['max'])) { + $this->addUsingAlias(AddressColissimoPickupPointTableMap::COUNTRY_ID, $countryId['max'], Criteria::LESS_EQUAL); + $useMinMax = true; + } + if ($useMinMax) { + return $this; + } + if (null === $comparison) { + $comparison = Criteria::IN; + } + } + + return $this->addUsingAlias(AddressColissimoPickupPointTableMap::COUNTRY_ID, $countryId, $comparison); + } + + /** + * Filter the query on the code column + * + * Example usage: + * + * $query->filterByCode('fooValue'); // WHERE code = 'fooValue' + * $query->filterByCode('%fooValue%'); // WHERE code LIKE '%fooValue%' + * + * + * @param string $code The value to use as filter. + * Accepts wildcards (* and % trigger a LIKE) + * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL + * + * @return ChildAddressColissimoPickupPointQuery The current query, for fluid interface + */ + public function filterByCode($code = null, $comparison = null) + { + if (null === $comparison) { + if (is_array($code)) { + $comparison = Criteria::IN; + } elseif (preg_match('/[\%\*]/', $code)) { + $code = str_replace('*', '%', $code); + $comparison = Criteria::LIKE; + } + } + + return $this->addUsingAlias(AddressColissimoPickupPointTableMap::CODE, $code, $comparison); + } + + /** + * Filter the query on the type column + * + * Example usage: + * + * $query->filterByType('fooValue'); // WHERE type = 'fooValue' + * $query->filterByType('%fooValue%'); // WHERE type LIKE '%fooValue%' + * + * + * @param string $type The value to use as filter. + * Accepts wildcards (* and % trigger a LIKE) + * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL + * + * @return ChildAddressColissimoPickupPointQuery The current query, for fluid interface + */ + public function filterByType($type = null, $comparison = null) + { + if (null === $comparison) { + if (is_array($type)) { + $comparison = Criteria::IN; + } elseif (preg_match('/[\%\*]/', $type)) { + $type = str_replace('*', '%', $type); + $comparison = Criteria::LIKE; + } + } + + return $this->addUsingAlias(AddressColissimoPickupPointTableMap::TYPE, $type, $comparison); + } + + /** + * Filter the query on the cellphone column + * + * Example usage: + * + * $query->filterByCellphone('fooValue'); // WHERE cellphone = 'fooValue' + * $query->filterByCellphone('%fooValue%'); // WHERE cellphone LIKE '%fooValue%' + * + * + * @param string $cellphone The value to use as filter. + * Accepts wildcards (* and % trigger a LIKE) + * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL + * + * @return ChildAddressColissimoPickupPointQuery The current query, for fluid interface + */ + public function filterByCellphone($cellphone = null, $comparison = null) + { + if (null === $comparison) { + if (is_array($cellphone)) { + $comparison = Criteria::IN; + } elseif (preg_match('/[\%\*]/', $cellphone)) { + $cellphone = str_replace('*', '%', $cellphone); + $comparison = Criteria::LIKE; + } + } + + return $this->addUsingAlias(AddressColissimoPickupPointTableMap::CELLPHONE, $cellphone, $comparison); + } + + /** + * Filter the query by a related \ColissimoPickupPoint\Model\Thelia\Model\CustomerTitle object + * + * @param \ColissimoPickupPoint\Model\Thelia\Model\CustomerTitle|ObjectCollection $customerTitle The related object(s) to use as filter + * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL + * + * @return ChildAddressColissimoPickupPointQuery The current query, for fluid interface + */ + public function filterByCustomerTitle($customerTitle, $comparison = null) + { + if ($customerTitle instanceof \ColissimoPickupPoint\Model\Thelia\Model\CustomerTitle) { + return $this + ->addUsingAlias(AddressColissimoPickupPointTableMap::TITLE_ID, $customerTitle->getId(), $comparison); + } elseif ($customerTitle instanceof ObjectCollection) { + if (null === $comparison) { + $comparison = Criteria::IN; + } + + return $this + ->addUsingAlias(AddressColissimoPickupPointTableMap::TITLE_ID, $customerTitle->toKeyValue('PrimaryKey', 'Id'), $comparison); + } else { + throw new PropelException('filterByCustomerTitle() only accepts arguments of type \ColissimoPickupPoint\Model\Thelia\Model\CustomerTitle or Collection'); + } + } + + /** + * Adds a JOIN clause to the query using the CustomerTitle relation + * + * @param string $relationAlias optional alias for the relation + * @param string $joinType Accepted values are null, 'left join', 'right join', 'inner join' + * + * @return ChildAddressColissimoPickupPointQuery The current query, for fluid interface + */ + public function joinCustomerTitle($relationAlias = null, $joinType = Criteria::INNER_JOIN) + { + $tableMap = $this->getTableMap(); + $relationMap = $tableMap->getRelation('CustomerTitle'); + + // create a ModelJoin object for this join + $join = new ModelJoin(); + $join->setJoinType($joinType); + $join->setRelationMap($relationMap, $this->useAliasInSQL ? $this->getModelAlias() : null, $relationAlias); + if ($previousJoin = $this->getPreviousJoin()) { + $join->setPreviousJoin($previousJoin); + } + + // add the ModelJoin to the current object + if ($relationAlias) { + $this->addAlias($relationAlias, $relationMap->getRightTable()->getName()); + $this->addJoinObject($join, $relationAlias); + } else { + $this->addJoinObject($join, 'CustomerTitle'); + } + + return $this; + } + + /** + * Use the CustomerTitle relation CustomerTitle object + * + * @see useQuery() + * + * @param string $relationAlias optional alias for the relation, + * to be used as main alias in the secondary query + * @param string $joinType Accepted values are null, 'left join', 'right join', 'inner join' + * + * @return \ColissimoPickupPoint\Model\Thelia\Model\CustomerTitleQuery A secondary query class using the current class as primary query + */ + public function useCustomerTitleQuery($relationAlias = null, $joinType = Criteria::INNER_JOIN) + { + return $this + ->joinCustomerTitle($relationAlias, $joinType) + ->useQuery($relationAlias ? $relationAlias : 'CustomerTitle', '\ColissimoPickupPoint\Model\Thelia\Model\CustomerTitleQuery'); + } + + /** + * Filter the query by a related \ColissimoPickupPoint\Model\Thelia\Model\Country object + * + * @param \ColissimoPickupPoint\Model\Thelia\Model\Country|ObjectCollection $country The related object(s) to use as filter + * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL + * + * @return ChildAddressColissimoPickupPointQuery The current query, for fluid interface + */ + public function filterByCountry($country, $comparison = null) + { + if ($country instanceof \ColissimoPickupPoint\Model\Thelia\Model\Country) { + return $this + ->addUsingAlias(AddressColissimoPickupPointTableMap::COUNTRY_ID, $country->getId(), $comparison); + } elseif ($country instanceof ObjectCollection) { + if (null === $comparison) { + $comparison = Criteria::IN; + } + + return $this + ->addUsingAlias(AddressColissimoPickupPointTableMap::COUNTRY_ID, $country->toKeyValue('PrimaryKey', 'Id'), $comparison); + } else { + throw new PropelException('filterByCountry() only accepts arguments of type \ColissimoPickupPoint\Model\Thelia\Model\Country or Collection'); + } + } + + /** + * Adds a JOIN clause to the query using the Country relation + * + * @param string $relationAlias optional alias for the relation + * @param string $joinType Accepted values are null, 'left join', 'right join', 'inner join' + * + * @return ChildAddressColissimoPickupPointQuery The current query, for fluid interface + */ + public function joinCountry($relationAlias = null, $joinType = Criteria::INNER_JOIN) + { + $tableMap = $this->getTableMap(); + $relationMap = $tableMap->getRelation('Country'); + + // create a ModelJoin object for this join + $join = new ModelJoin(); + $join->setJoinType($joinType); + $join->setRelationMap($relationMap, $this->useAliasInSQL ? $this->getModelAlias() : null, $relationAlias); + if ($previousJoin = $this->getPreviousJoin()) { + $join->setPreviousJoin($previousJoin); + } + + // add the ModelJoin to the current object + if ($relationAlias) { + $this->addAlias($relationAlias, $relationMap->getRightTable()->getName()); + $this->addJoinObject($join, $relationAlias); + } else { + $this->addJoinObject($join, 'Country'); + } + + return $this; + } + + /** + * Use the Country relation Country object + * + * @see useQuery() + * + * @param string $relationAlias optional alias for the relation, + * to be used as main alias in the secondary query + * @param string $joinType Accepted values are null, 'left join', 'right join', 'inner join' + * + * @return \ColissimoPickupPoint\Model\Thelia\Model\CountryQuery A secondary query class using the current class as primary query + */ + public function useCountryQuery($relationAlias = null, $joinType = Criteria::INNER_JOIN) + { + return $this + ->joinCountry($relationAlias, $joinType) + ->useQuery($relationAlias ? $relationAlias : 'Country', '\ColissimoPickupPoint\Model\Thelia\Model\CountryQuery'); + } + + /** + * Exclude object from result + * + * @param ChildAddressColissimoPickupPoint $addressColissimoPickupPoint Object to remove from the list of results + * + * @return ChildAddressColissimoPickupPointQuery The current query, for fluid interface + */ + public function prune($addressColissimoPickupPoint = null) + { + if ($addressColissimoPickupPoint) { + $this->addUsingAlias(AddressColissimoPickupPointTableMap::ID, $addressColissimoPickupPoint->getId(), Criteria::NOT_EQUAL); + } + + return $this; + } + + /** + * Deletes all rows from the address_colissimo_pickup_point table. + * + * @param ConnectionInterface $con the connection to use + * @return int The number of affected rows (if supported by underlying database driver). + */ + public function doDeleteAll(ConnectionInterface $con = null) + { + if (null === $con) { + $con = Propel::getServiceContainer()->getWriteConnection(AddressColissimoPickupPointTableMap::DATABASE_NAME); + } + $affectedRows = 0; // initialize var to track total num of affected rows + try { + // use transaction because $criteria could contain info + // for more than one table or we could emulating ON DELETE CASCADE, etc. + $con->beginTransaction(); + $affectedRows += parent::doDeleteAll($con); + // Because this db requires some delete cascade/set null emulation, we have to + // clear the cached instance *after* the emulation has happened (since + // instances get re-added by the select statement contained therein). + AddressColissimoPickupPointTableMap::clearInstancePool(); + AddressColissimoPickupPointTableMap::clearRelatedInstancePool(); + + $con->commit(); + } catch (PropelException $e) { + $con->rollBack(); + throw $e; + } + + return $affectedRows; + } + + /** + * Performs a DELETE on the database, given a ChildAddressColissimoPickupPoint or Criteria object OR a primary key value. + * + * @param mixed $values Criteria or ChildAddressColissimoPickupPoint object or primary key or array of primary keys + * which is used to create the DELETE statement + * @param ConnectionInterface $con the connection to use + * @return int The number of affected rows (if supported by underlying database driver). This includes CASCADE-related rows + * if supported by native driver or if emulated using Propel. + * @throws PropelException Any exceptions caught during processing will be + * rethrown wrapped into a PropelException. + */ + public function delete(ConnectionInterface $con = null) + { + if (null === $con) { + $con = Propel::getServiceContainer()->getWriteConnection(AddressColissimoPickupPointTableMap::DATABASE_NAME); + } + + $criteria = $this; + + // Set the correct dbName + $criteria->setDbName(AddressColissimoPickupPointTableMap::DATABASE_NAME); + + $affectedRows = 0; // initialize var to track total num of affected rows + + try { + // use transaction because $criteria could contain info + // for more than one table or we could emulating ON DELETE CASCADE, etc. + $con->beginTransaction(); + + + AddressColissimoPickupPointTableMap::removeInstanceFromPool($criteria); + + $affectedRows += ModelCriteria::delete($con); + AddressColissimoPickupPointTableMap::clearRelatedInstancePool(); + $con->commit(); + + return $affectedRows; + } catch (PropelException $e) { + $con->rollBack(); + throw $e; + } + } + +} // AddressColissimoPickupPointQuery diff --git a/local/modules/ColissimoPickupPoint/Model/Base/ColissimoPickupPointAreaFreeshipping.php b/local/modules/ColissimoPickupPoint/Model/Base/ColissimoPickupPointAreaFreeshipping.php new file mode 100644 index 00000000..d51ecd8a --- /dev/null +++ b/local/modules/ColissimoPickupPoint/Model/Base/ColissimoPickupPointAreaFreeshipping.php @@ -0,0 +1,1272 @@ +cart_amount = '0.00'; + } + + /** + * Initializes internal state of ColissimoPickupPoint\Model\Base\ColissimoPickupPointAreaFreeshipping object. + * @see applyDefaults() + */ + public function __construct() + { + $this->applyDefaultValues(); + } + + /** + * Returns whether the object has been modified. + * + * @return boolean True if the object has been modified. + */ + public function isModified() + { + return !!$this->modifiedColumns; + } + + /** + * Has specified column been modified? + * + * @param string $col column fully qualified name (TableMap::TYPE_COLNAME), e.g. Book::AUTHOR_ID + * @return boolean True if $col has been modified. + */ + public function isColumnModified($col) + { + return $this->modifiedColumns && isset($this->modifiedColumns[$col]); + } + + /** + * Get the columns that have been modified in this object. + * @return array A unique list of the modified column names for this object. + */ + public function getModifiedColumns() + { + return $this->modifiedColumns ? array_keys($this->modifiedColumns) : []; + } + + /** + * Returns whether the object has ever been saved. This will + * be false, if the object was retrieved from storage or was created + * and then saved. + * + * @return boolean true, if the object has never been persisted. + */ + public function isNew() + { + return $this->new; + } + + /** + * Setter for the isNew attribute. This method will be called + * by Propel-generated children and objects. + * + * @param boolean $b the state of the object. + */ + public function setNew($b) + { + $this->new = (Boolean) $b; + } + + /** + * Whether this object has been deleted. + * @return boolean The deleted state of this object. + */ + public function isDeleted() + { + return $this->deleted; + } + + /** + * Specify whether this object has been deleted. + * @param boolean $b The deleted state of this object. + * @return void + */ + public function setDeleted($b) + { + $this->deleted = (Boolean) $b; + } + + /** + * Sets the modified state for the object to be false. + * @param string $col If supplied, only the specified column is reset. + * @return void + */ + public function resetModified($col = null) + { + if (null !== $col) { + if (isset($this->modifiedColumns[$col])) { + unset($this->modifiedColumns[$col]); + } + } else { + $this->modifiedColumns = array(); + } + } + + /** + * Compares this with another ColissimoPickupPointAreaFreeshipping instance. If + * obj is an instance of ColissimoPickupPointAreaFreeshipping, delegates to + * equals(ColissimoPickupPointAreaFreeshipping). Otherwise, returns false. + * + * @param mixed $obj The object to compare to. + * @return boolean Whether equal to the object specified. + */ + public function equals($obj) + { + $thisclazz = get_class($this); + if (!is_object($obj) || !($obj instanceof $thisclazz)) { + return false; + } + + if ($this === $obj) { + return true; + } + + if (null === $this->getPrimaryKey() + || null === $obj->getPrimaryKey()) { + return false; + } + + return $this->getPrimaryKey() === $obj->getPrimaryKey(); + } + + /** + * If the primary key is not null, return the hashcode of the + * primary key. Otherwise, return the hash code of the object. + * + * @return int Hashcode + */ + public function hashCode() + { + if (null !== $this->getPrimaryKey()) { + return crc32(serialize($this->getPrimaryKey())); + } + + return crc32(serialize(clone $this)); + } + + /** + * Get the associative array of the virtual columns in this object + * + * @return array + */ + public function getVirtualColumns() + { + return $this->virtualColumns; + } + + /** + * Checks the existence of a virtual column in this object + * + * @param string $name The virtual column name + * @return boolean + */ + public function hasVirtualColumn($name) + { + return array_key_exists($name, $this->virtualColumns); + } + + /** + * Get the value of a virtual column in this object + * + * @param string $name The virtual column name + * @return mixed + * + * @throws PropelException + */ + public function getVirtualColumn($name) + { + if (!$this->hasVirtualColumn($name)) { + throw new PropelException(sprintf('Cannot get value of inexistent virtual column %s.', $name)); + } + + return $this->virtualColumns[$name]; + } + + /** + * Set the value of a virtual column in this object + * + * @param string $name The virtual column name + * @param mixed $value The value to give to the virtual column + * + * @return ColissimoPickupPointAreaFreeshipping The current object, for fluid interface + */ + public function setVirtualColumn($name, $value) + { + $this->virtualColumns[$name] = $value; + + return $this; + } + + /** + * Logs a message using Propel::log(). + * + * @param string $msg + * @param int $priority One of the Propel::LOG_* logging levels + * @return boolean + */ + protected function log($msg, $priority = Propel::LOG_INFO) + { + return Propel::log(get_class($this) . ': ' . $msg, $priority); + } + + /** + * Populate the current object from a string, using a given parser format + * + * $book = new Book(); + * $book->importFrom('JSON', '{"Id":9012,"Title":"Don Juan","ISBN":"0140422161","Price":12.99,"PublisherId":1234,"AuthorId":5678}'); + * + * + * @param mixed $parser A AbstractParser instance, + * or a format name ('XML', 'YAML', 'JSON', 'CSV') + * @param string $data The source data to import from + * + * @return ColissimoPickupPointAreaFreeshipping The current object, for fluid interface + */ + public function importFrom($parser, $data) + { + if (!$parser instanceof AbstractParser) { + $parser = AbstractParser::getParser($parser); + } + + $this->fromArray($parser->toArray($data), TableMap::TYPE_PHPNAME); + + return $this; + } + + /** + * Export the current object properties to a string, using a given parser format + * + * $book = BookQuery::create()->findPk(9012); + * echo $book->exportTo('JSON'); + * => {"Id":9012,"Title":"Don Juan","ISBN":"0140422161","Price":12.99,"PublisherId":1234,"AuthorId":5678}'); + * + * + * @param mixed $parser A AbstractParser instance, or a format name ('XML', 'YAML', 'JSON', 'CSV') + * @param boolean $includeLazyLoadColumns (optional) Whether to include lazy load(ed) columns. Defaults to TRUE. + * @return string The exported data + */ + public function exportTo($parser, $includeLazyLoadColumns = true) + { + if (!$parser instanceof AbstractParser) { + $parser = AbstractParser::getParser($parser); + } + + return $parser->fromArray($this->toArray(TableMap::TYPE_PHPNAME, $includeLazyLoadColumns, array(), true)); + } + + /** + * Clean up internal collections prior to serializing + * Avoids recursive loops that turn into segmentation faults when serializing + */ + public function __sleep() + { + $this->clearAllReferences(); + + return array_keys(get_object_vars($this)); + } + + /** + * Get the [id] column value. + * + * @return int + */ + public function getId() + { + + return $this->id; + } + + /** + * Get the [area_id] column value. + * + * @return int + */ + public function getAreaId() + { + + return $this->area_id; + } + + /** + * Get the [cart_amount] column value. + * + * @return string + */ + public function getCartAmount() + { + + return $this->cart_amount; + } + + /** + * Set the value of [id] column. + * + * @param int $v new value + * @return \ColissimoPickupPoint\Model\ColissimoPickupPointAreaFreeshipping The current object (for fluent API support) + */ + public function setId($v) + { + if ($v !== null) { + $v = (int) $v; + } + + if ($this->id !== $v) { + $this->id = $v; + $this->modifiedColumns[ColissimoPickupPointAreaFreeshippingTableMap::ID] = true; + } + + + return $this; + } // setId() + + /** + * Set the value of [area_id] column. + * + * @param int $v new value + * @return \ColissimoPickupPoint\Model\ColissimoPickupPointAreaFreeshipping The current object (for fluent API support) + */ + public function setAreaId($v) + { + if ($v !== null) { + $v = (int) $v; + } + + if ($this->area_id !== $v) { + $this->area_id = $v; + $this->modifiedColumns[ColissimoPickupPointAreaFreeshippingTableMap::AREA_ID] = true; + } + + if ($this->aArea !== null && $this->aArea->getId() !== $v) { + $this->aArea = null; + } + + + return $this; + } // setAreaId() + + /** + * Set the value of [cart_amount] column. + * + * @param string $v new value + * @return \ColissimoPickupPoint\Model\ColissimoPickupPointAreaFreeshipping The current object (for fluent API support) + */ + public function setCartAmount($v) + { + if ($v !== null) { + $v = (string) $v; + } + + if ($this->cart_amount !== $v) { + $this->cart_amount = $v; + $this->modifiedColumns[ColissimoPickupPointAreaFreeshippingTableMap::CART_AMOUNT] = true; + } + + + return $this; + } // setCartAmount() + + /** + * Indicates whether the columns in this object are only set to default values. + * + * This method can be used in conjunction with isModified() to indicate whether an object is both + * modified _and_ has some values set which are non-default. + * + * @return boolean Whether the columns in this object are only been set with default values. + */ + public function hasOnlyDefaultValues() + { + if ($this->cart_amount !== '0.00') { + return false; + } + + // otherwise, everything was equal, so return TRUE + return true; + } // hasOnlyDefaultValues() + + /** + * Hydrates (populates) the object variables with values from the database resultset. + * + * An offset (0-based "start column") is specified so that objects can be hydrated + * with a subset of the columns in the resultset rows. This is needed, for example, + * for results of JOIN queries where the resultset row includes columns from two or + * more tables. + * + * @param array $row The row returned by DataFetcher->fetch(). + * @param int $startcol 0-based offset column which indicates which restultset column to start with. + * @param boolean $rehydrate Whether this object is being re-hydrated from the database. + * @param string $indexType The index type of $row. Mostly DataFetcher->getIndexType(). + One of the class type constants TableMap::TYPE_PHPNAME, TableMap::TYPE_STUDLYPHPNAME + * TableMap::TYPE_COLNAME, TableMap::TYPE_FIELDNAME, TableMap::TYPE_NUM. + * + * @return int next starting column + * @throws PropelException - Any caught Exception will be rewrapped as a PropelException. + */ + public function hydrate($row, $startcol = 0, $rehydrate = false, $indexType = TableMap::TYPE_NUM) + { + try { + + + $col = $row[TableMap::TYPE_NUM == $indexType ? 0 + $startcol : ColissimoPickupPointAreaFreeshippingTableMap::translateFieldName('Id', TableMap::TYPE_PHPNAME, $indexType)]; + $this->id = (null !== $col) ? (int) $col : null; + + $col = $row[TableMap::TYPE_NUM == $indexType ? 1 + $startcol : ColissimoPickupPointAreaFreeshippingTableMap::translateFieldName('AreaId', TableMap::TYPE_PHPNAME, $indexType)]; + $this->area_id = (null !== $col) ? (int) $col : null; + + $col = $row[TableMap::TYPE_NUM == $indexType ? 2 + $startcol : ColissimoPickupPointAreaFreeshippingTableMap::translateFieldName('CartAmount', TableMap::TYPE_PHPNAME, $indexType)]; + $this->cart_amount = (null !== $col) ? (string) $col : null; + $this->resetModified(); + + $this->setNew(false); + + if ($rehydrate) { + $this->ensureConsistency(); + } + + return $startcol + 3; // 3 = ColissimoPickupPointAreaFreeshippingTableMap::NUM_HYDRATE_COLUMNS. + + } catch (Exception $e) { + throw new PropelException("Error populating \ColissimoPickupPoint\Model\ColissimoPickupPointAreaFreeshipping object", 0, $e); + } + } + + /** + * Checks and repairs the internal consistency of the object. + * + * This method is executed after an already-instantiated object is re-hydrated + * from the database. It exists to check any foreign keys to make sure that + * the objects related to the current object are correct based on foreign key. + * + * You can override this method in the stub class, but you should always invoke + * the base method from the overridden method (i.e. parent::ensureConsistency()), + * in case your model changes. + * + * @throws PropelException + */ + public function ensureConsistency() + { + if ($this->aArea !== null && $this->area_id !== $this->aArea->getId()) { + $this->aArea = null; + } + } // ensureConsistency + + /** + * Reloads this object from datastore based on primary key and (optionally) resets all associated objects. + * + * This will only work if the object has been saved and has a valid primary key set. + * + * @param boolean $deep (optional) Whether to also de-associated any related objects. + * @param ConnectionInterface $con (optional) The ConnectionInterface connection to use. + * @return void + * @throws PropelException - if this object is deleted, unsaved or doesn't have pk match in db + */ + public function reload($deep = false, ConnectionInterface $con = null) + { + if ($this->isDeleted()) { + throw new PropelException("Cannot reload a deleted object."); + } + + if ($this->isNew()) { + throw new PropelException("Cannot reload an unsaved object."); + } + + if ($con === null) { + $con = Propel::getServiceContainer()->getReadConnection(ColissimoPickupPointAreaFreeshippingTableMap::DATABASE_NAME); + } + + // We don't need to alter the object instance pool; we're just modifying this instance + // already in the pool. + + $dataFetcher = ChildColissimoPickupPointAreaFreeshippingQuery::create(null, $this->buildPkeyCriteria())->setFormatter(ModelCriteria::FORMAT_STATEMENT)->find($con); + $row = $dataFetcher->fetch(); + $dataFetcher->close(); + if (!$row) { + throw new PropelException('Cannot find matching row in the database to reload object values.'); + } + $this->hydrate($row, 0, true, $dataFetcher->getIndexType()); // rehydrate + + if ($deep) { // also de-associate any related objects? + + $this->aArea = null; + } // if (deep) + } + + /** + * Removes this object from datastore and sets delete attribute. + * + * @param ConnectionInterface $con + * @return void + * @throws PropelException + * @see ColissimoPickupPointAreaFreeshipping::setDeleted() + * @see ColissimoPickupPointAreaFreeshipping::isDeleted() + */ + public function delete(ConnectionInterface $con = null) + { + if ($this->isDeleted()) { + throw new PropelException("This object has already been deleted."); + } + + if ($con === null) { + $con = Propel::getServiceContainer()->getWriteConnection(ColissimoPickupPointAreaFreeshippingTableMap::DATABASE_NAME); + } + + $con->beginTransaction(); + try { + $deleteQuery = ChildColissimoPickupPointAreaFreeshippingQuery::create() + ->filterByPrimaryKey($this->getPrimaryKey()); + $ret = $this->preDelete($con); + if ($ret) { + $deleteQuery->delete($con); + $this->postDelete($con); + $con->commit(); + $this->setDeleted(true); + } else { + $con->commit(); + } + } catch (Exception $e) { + $con->rollBack(); + throw $e; + } + } + + /** + * Persists this object to the database. + * + * If the object is new, it inserts it; otherwise an update is performed. + * All modified related objects will also be persisted in the doSave() + * method. This method wraps all precipitate database operations in a + * single transaction. + * + * @param ConnectionInterface $con + * @return int The number of rows affected by this insert/update and any referring fk objects' save() operations. + * @throws PropelException + * @see doSave() + */ + public function save(ConnectionInterface $con = null) + { + if ($this->isDeleted()) { + throw new PropelException("You cannot save an object that has been deleted."); + } + + if ($con === null) { + $con = Propel::getServiceContainer()->getWriteConnection(ColissimoPickupPointAreaFreeshippingTableMap::DATABASE_NAME); + } + + $con->beginTransaction(); + $isInsert = $this->isNew(); + try { + $ret = $this->preSave($con); + if ($isInsert) { + $ret = $ret && $this->preInsert($con); + } else { + $ret = $ret && $this->preUpdate($con); + } + if ($ret) { + $affectedRows = $this->doSave($con); + if ($isInsert) { + $this->postInsert($con); + } else { + $this->postUpdate($con); + } + $this->postSave($con); + ColissimoPickupPointAreaFreeshippingTableMap::addInstanceToPool($this); + } else { + $affectedRows = 0; + } + $con->commit(); + + return $affectedRows; + } catch (Exception $e) { + $con->rollBack(); + throw $e; + } + } + + /** + * Performs the work of inserting or updating the row in the database. + * + * If the object is new, it inserts it; otherwise an update is performed. + * All related objects are also updated in this method. + * + * @param ConnectionInterface $con + * @return int The number of rows affected by this insert/update and any referring fk objects' save() operations. + * @throws PropelException + * @see save() + */ + protected function doSave(ConnectionInterface $con) + { + $affectedRows = 0; // initialize var to track total num of affected rows + if (!$this->alreadyInSave) { + $this->alreadyInSave = true; + + // We call the save method on the following object(s) if they + // were passed to this object by their corresponding set + // method. This object relates to these object(s) by a + // foreign key reference. + + if ($this->aArea !== null) { + if ($this->aArea->isModified() || $this->aArea->isNew()) { + $affectedRows += $this->aArea->save($con); + } + $this->setArea($this->aArea); + } + + if ($this->isNew() || $this->isModified()) { + // persist changes + if ($this->isNew()) { + $this->doInsert($con); + } else { + $this->doUpdate($con); + } + $affectedRows += 1; + $this->resetModified(); + } + + $this->alreadyInSave = false; + + } + + return $affectedRows; + } // doSave() + + /** + * Insert the row in the database. + * + * @param ConnectionInterface $con + * + * @throws PropelException + * @see doSave() + */ + protected function doInsert(ConnectionInterface $con) + { + $modifiedColumns = array(); + $index = 0; + + $this->modifiedColumns[ColissimoPickupPointAreaFreeshippingTableMap::ID] = true; + if (null !== $this->id) { + throw new PropelException('Cannot insert a value for auto-increment primary key (' . ColissimoPickupPointAreaFreeshippingTableMap::ID . ')'); + } + + // check the columns in natural order for more readable SQL queries + if ($this->isColumnModified(ColissimoPickupPointAreaFreeshippingTableMap::ID)) { + $modifiedColumns[':p' . $index++] = 'ID'; + } + if ($this->isColumnModified(ColissimoPickupPointAreaFreeshippingTableMap::AREA_ID)) { + $modifiedColumns[':p' . $index++] = 'AREA_ID'; + } + if ($this->isColumnModified(ColissimoPickupPointAreaFreeshippingTableMap::CART_AMOUNT)) { + $modifiedColumns[':p' . $index++] = 'CART_AMOUNT'; + } + + $sql = sprintf( + 'INSERT INTO colissimo_pickup_point_area_freeshipping (%s) VALUES (%s)', + implode(', ', $modifiedColumns), + implode(', ', array_keys($modifiedColumns)) + ); + + try { + $stmt = $con->prepare($sql); + foreach ($modifiedColumns as $identifier => $columnName) { + switch ($columnName) { + case 'ID': + $stmt->bindValue($identifier, $this->id, PDO::PARAM_INT); + break; + case 'AREA_ID': + $stmt->bindValue($identifier, $this->area_id, PDO::PARAM_INT); + break; + case 'CART_AMOUNT': + $stmt->bindValue($identifier, $this->cart_amount, PDO::PARAM_STR); + break; + } + } + $stmt->execute(); + } catch (Exception $e) { + Propel::log($e->getMessage(), Propel::LOG_ERR); + throw new PropelException(sprintf('Unable to execute INSERT statement [%s]', $sql), 0, $e); + } + + try { + $pk = $con->lastInsertId(); + } catch (Exception $e) { + throw new PropelException('Unable to get autoincrement id.', 0, $e); + } + $this->setId($pk); + + $this->setNew(false); + } + + /** + * Update the row in the database. + * + * @param ConnectionInterface $con + * + * @return Integer Number of updated rows + * @see doSave() + */ + protected function doUpdate(ConnectionInterface $con) + { + $selectCriteria = $this->buildPkeyCriteria(); + $valuesCriteria = $this->buildCriteria(); + + return $selectCriteria->doUpdate($valuesCriteria, $con); + } + + /** + * Retrieves a field from the object by name passed in as a string. + * + * @param string $name name + * @param string $type The type of fieldname the $name is of: + * one of the class type constants TableMap::TYPE_PHPNAME, TableMap::TYPE_STUDLYPHPNAME + * TableMap::TYPE_COLNAME, TableMap::TYPE_FIELDNAME, TableMap::TYPE_NUM. + * Defaults to TableMap::TYPE_PHPNAME. + * @return mixed Value of field. + */ + public function getByName($name, $type = TableMap::TYPE_PHPNAME) + { + $pos = ColissimoPickupPointAreaFreeshippingTableMap::translateFieldName($name, $type, TableMap::TYPE_NUM); + $field = $this->getByPosition($pos); + + return $field; + } + + /** + * Retrieves a field from the object by Position as specified in the xml schema. + * Zero-based. + * + * @param int $pos position in xml schema + * @return mixed Value of field at $pos + */ + public function getByPosition($pos) + { + switch ($pos) { + case 0: + return $this->getId(); + break; + case 1: + return $this->getAreaId(); + break; + case 2: + return $this->getCartAmount(); + break; + default: + return null; + break; + } // switch() + } + + /** + * Exports the object as an array. + * + * You can specify the key type of the array by passing one of the class + * type constants. + * + * @param string $keyType (optional) One of the class type constants TableMap::TYPE_PHPNAME, TableMap::TYPE_STUDLYPHPNAME, + * TableMap::TYPE_COLNAME, TableMap::TYPE_FIELDNAME, TableMap::TYPE_NUM. + * Defaults to TableMap::TYPE_PHPNAME. + * @param boolean $includeLazyLoadColumns (optional) Whether to include lazy loaded columns. Defaults to TRUE. + * @param array $alreadyDumpedObjects List of objects to skip to avoid recursion + * @param boolean $includeForeignObjects (optional) Whether to include hydrated related objects. Default to FALSE. + * + * @return array an associative array containing the field names (as keys) and field values + */ + public function toArray($keyType = TableMap::TYPE_PHPNAME, $includeLazyLoadColumns = true, $alreadyDumpedObjects = array(), $includeForeignObjects = false) + { + if (isset($alreadyDumpedObjects['ColissimoPickupPointAreaFreeshipping'][$this->getPrimaryKey()])) { + return '*RECURSION*'; + } + $alreadyDumpedObjects['ColissimoPickupPointAreaFreeshipping'][$this->getPrimaryKey()] = true; + $keys = ColissimoPickupPointAreaFreeshippingTableMap::getFieldNames($keyType); + $result = array( + $keys[0] => $this->getId(), + $keys[1] => $this->getAreaId(), + $keys[2] => $this->getCartAmount(), + ); + $virtualColumns = $this->virtualColumns; + foreach ($virtualColumns as $key => $virtualColumn) { + $result[$key] = $virtualColumn; + } + + if ($includeForeignObjects) { + if (null !== $this->aArea) { + $result['Area'] = $this->aArea->toArray($keyType, $includeLazyLoadColumns, $alreadyDumpedObjects, true); + } + } + + return $result; + } + + /** + * Sets a field from the object by name passed in as a string. + * + * @param string $name + * @param mixed $value field value + * @param string $type The type of fieldname the $name is of: + * one of the class type constants TableMap::TYPE_PHPNAME, TableMap::TYPE_STUDLYPHPNAME + * TableMap::TYPE_COLNAME, TableMap::TYPE_FIELDNAME, TableMap::TYPE_NUM. + * Defaults to TableMap::TYPE_PHPNAME. + * @return void + */ + public function setByName($name, $value, $type = TableMap::TYPE_PHPNAME) + { + $pos = ColissimoPickupPointAreaFreeshippingTableMap::translateFieldName($name, $type, TableMap::TYPE_NUM); + + return $this->setByPosition($pos, $value); + } + + /** + * Sets a field from the object by Position as specified in the xml schema. + * Zero-based. + * + * @param int $pos position in xml schema + * @param mixed $value field value + * @return void + */ + public function setByPosition($pos, $value) + { + switch ($pos) { + case 0: + $this->setId($value); + break; + case 1: + $this->setAreaId($value); + break; + case 2: + $this->setCartAmount($value); + break; + } // switch() + } + + /** + * Populates the object using an array. + * + * This is particularly useful when populating an object from one of the + * request arrays (e.g. $_POST). This method goes through the column + * names, checking to see whether a matching key exists in populated + * array. If so the setByName() method is called for that column. + * + * You can specify the key type of the array by additionally passing one + * of the class type constants TableMap::TYPE_PHPNAME, TableMap::TYPE_STUDLYPHPNAME, + * TableMap::TYPE_COLNAME, TableMap::TYPE_FIELDNAME, TableMap::TYPE_NUM. + * The default key type is the column's TableMap::TYPE_PHPNAME. + * + * @param array $arr An array to populate the object from. + * @param string $keyType The type of keys the array uses. + * @return void + */ + public function fromArray($arr, $keyType = TableMap::TYPE_PHPNAME) + { + $keys = ColissimoPickupPointAreaFreeshippingTableMap::getFieldNames($keyType); + + if (array_key_exists($keys[0], $arr)) $this->setId($arr[$keys[0]]); + if (array_key_exists($keys[1], $arr)) $this->setAreaId($arr[$keys[1]]); + if (array_key_exists($keys[2], $arr)) $this->setCartAmount($arr[$keys[2]]); + } + + /** + * Build a Criteria object containing the values of all modified columns in this object. + * + * @return Criteria The Criteria object containing all modified values. + */ + public function buildCriteria() + { + $criteria = new Criteria(ColissimoPickupPointAreaFreeshippingTableMap::DATABASE_NAME); + + if ($this->isColumnModified(ColissimoPickupPointAreaFreeshippingTableMap::ID)) $criteria->add(ColissimoPickupPointAreaFreeshippingTableMap::ID, $this->id); + if ($this->isColumnModified(ColissimoPickupPointAreaFreeshippingTableMap::AREA_ID)) $criteria->add(ColissimoPickupPointAreaFreeshippingTableMap::AREA_ID, $this->area_id); + if ($this->isColumnModified(ColissimoPickupPointAreaFreeshippingTableMap::CART_AMOUNT)) $criteria->add(ColissimoPickupPointAreaFreeshippingTableMap::CART_AMOUNT, $this->cart_amount); + + return $criteria; + } + + /** + * Builds a Criteria object containing the primary key for this object. + * + * Unlike buildCriteria() this method includes the primary key values regardless + * of whether or not they have been modified. + * + * @return Criteria The Criteria object containing value(s) for primary key(s). + */ + public function buildPkeyCriteria() + { + $criteria = new Criteria(ColissimoPickupPointAreaFreeshippingTableMap::DATABASE_NAME); + $criteria->add(ColissimoPickupPointAreaFreeshippingTableMap::ID, $this->id); + + return $criteria; + } + + /** + * Returns the primary key for this object (row). + * @return int + */ + public function getPrimaryKey() + { + return $this->getId(); + } + + /** + * Generic method to set the primary key (id column). + * + * @param int $key Primary key. + * @return void + */ + public function setPrimaryKey($key) + { + $this->setId($key); + } + + /** + * Returns true if the primary key for this object is null. + * @return boolean + */ + public function isPrimaryKeyNull() + { + + return null === $this->getId(); + } + + /** + * Sets contents of passed object to values from current object. + * + * If desired, this method can also make copies of all associated (fkey referrers) + * objects. + * + * @param object $copyObj An object of \ColissimoPickupPoint\Model\ColissimoPickupPointAreaFreeshipping (or compatible) type. + * @param boolean $deepCopy Whether to also copy all rows that refer (by fkey) to the current row. + * @param boolean $makeNew Whether to reset autoincrement PKs and make the object new. + * @throws PropelException + */ + public function copyInto($copyObj, $deepCopy = false, $makeNew = true) + { + $copyObj->setAreaId($this->getAreaId()); + $copyObj->setCartAmount($this->getCartAmount()); + if ($makeNew) { + $copyObj->setNew(true); + $copyObj->setId(NULL); // this is a auto-increment column, so set to default value + } + } + + /** + * Makes a copy of this object that will be inserted as a new row in table when saved. + * It creates a new object filling in the simple attributes, but skipping any primary + * keys that are defined for the table. + * + * If desired, this method can also make copies of all associated (fkey referrers) + * objects. + * + * @param boolean $deepCopy Whether to also copy all rows that refer (by fkey) to the current row. + * @return \ColissimoPickupPoint\Model\ColissimoPickupPointAreaFreeshipping Clone of current object. + * @throws PropelException + */ + public function copy($deepCopy = false) + { + // we use get_class(), because this might be a subclass + $clazz = get_class($this); + $copyObj = new $clazz(); + $this->copyInto($copyObj, $deepCopy); + + return $copyObj; + } + + /** + * Declares an association between this object and a ChildArea object. + * + * @param ChildArea $v + * @return \ColissimoPickupPoint\Model\ColissimoPickupPointAreaFreeshipping The current object (for fluent API support) + * @throws PropelException + */ + public function setArea(ChildArea $v = null) + { + if ($v === null) { + $this->setAreaId(NULL); + } else { + $this->setAreaId($v->getId()); + } + + $this->aArea = $v; + + // Add binding for other direction of this n:n relationship. + // If this object has already been added to the ChildArea object, it will not be re-added. + if ($v !== null) { + $v->addColissimoPickupPointAreaFreeshipping($this); + } + + + return $this; + } + + + /** + * Get the associated ChildArea object + * + * @param ConnectionInterface $con Optional Connection object. + * @return ChildArea The associated ChildArea object. + * @throws PropelException + */ + public function getArea(ConnectionInterface $con = null) + { + if ($this->aArea === null && ($this->area_id !== null)) { + $this->aArea = AreaQuery::create()->findPk($this->area_id, $con); + /* The following can be used additionally to + guarantee the related object contains a reference + to this object. This level of coupling may, however, be + undesirable since it could result in an only partially populated collection + in the referenced object. + $this->aArea->addColissimoPickupPointAreaFreeshippings($this); + */ + } + + return $this->aArea; + } + + /** + * Clears the current object and sets all attributes to their default values + */ + public function clear() + { + $this->id = null; + $this->area_id = null; + $this->cart_amount = null; + $this->alreadyInSave = false; + $this->clearAllReferences(); + $this->applyDefaultValues(); + $this->resetModified(); + $this->setNew(true); + $this->setDeleted(false); + } + + /** + * Resets all references to other model objects or collections of model objects. + * + * This method is a user-space workaround for PHP's inability to garbage collect + * objects with circular references (even in PHP 5.3). This is currently necessary + * when using Propel in certain daemon or large-volume/high-memory operations. + * + * @param boolean $deep Whether to also clear the references on all referrer objects. + */ + public function clearAllReferences($deep = false) + { + if ($deep) { + } // if ($deep) + + $this->aArea = null; + } + + /** + * Return the string representation of this object + * + * @return string + */ + public function __toString() + { + return (string) $this->exportTo(ColissimoPickupPointAreaFreeshippingTableMap::DEFAULT_STRING_FORMAT); + } + + /** + * Code to be run before persisting the object + * @param ConnectionInterface $con + * @return boolean + */ + public function preSave(ConnectionInterface $con = null) + { + return true; + } + + /** + * Code to be run after persisting the object + * @param ConnectionInterface $con + */ + public function postSave(ConnectionInterface $con = null) + { + + } + + /** + * Code to be run before inserting to database + * @param ConnectionInterface $con + * @return boolean + */ + public function preInsert(ConnectionInterface $con = null) + { + return true; + } + + /** + * Code to be run after inserting to database + * @param ConnectionInterface $con + */ + public function postInsert(ConnectionInterface $con = null) + { + + } + + /** + * Code to be run before updating the object in database + * @param ConnectionInterface $con + * @return boolean + */ + public function preUpdate(ConnectionInterface $con = null) + { + return true; + } + + /** + * Code to be run after updating the object in database + * @param ConnectionInterface $con + */ + public function postUpdate(ConnectionInterface $con = null) + { + + } + + /** + * Code to be run before deleting the object in database + * @param ConnectionInterface $con + * @return boolean + */ + public function preDelete(ConnectionInterface $con = null) + { + return true; + } + + /** + * Code to be run after deleting the object in database + * @param ConnectionInterface $con + */ + public function postDelete(ConnectionInterface $con = null) + { + + } + + + /** + * Derived method to catches calls to undefined methods. + * + * Provides magic import/export method support (fromXML()/toXML(), fromYAML()/toYAML(), etc.). + * Allows to define default __call() behavior if you overwrite __call() + * + * @param string $name + * @param mixed $params + * + * @return array|string + */ + public function __call($name, $params) + { + if (0 === strpos($name, 'get')) { + $virtualColumn = substr($name, 3); + if ($this->hasVirtualColumn($virtualColumn)) { + return $this->getVirtualColumn($virtualColumn); + } + + $virtualColumn = lcfirst($virtualColumn); + if ($this->hasVirtualColumn($virtualColumn)) { + return $this->getVirtualColumn($virtualColumn); + } + } + + if (0 === strpos($name, 'from')) { + $format = substr($name, 4); + + return $this->importFrom($format, reset($params)); + } + + if (0 === strpos($name, 'to')) { + $format = substr($name, 2); + $includeLazyLoadColumns = isset($params[0]) ? $params[0] : true; + + return $this->exportTo($format, $includeLazyLoadColumns); + } + + throw new BadMethodCallException(sprintf('Call to undefined method: %s.', $name)); + } + +} diff --git a/local/modules/ColissimoPickupPoint/Model/Base/ColissimoPickupPointAreaFreeshippingQuery.php b/local/modules/ColissimoPickupPoint/Model/Base/ColissimoPickupPointAreaFreeshippingQuery.php new file mode 100644 index 00000000..eafcfcaf --- /dev/null +++ b/local/modules/ColissimoPickupPoint/Model/Base/ColissimoPickupPointAreaFreeshippingQuery.php @@ -0,0 +1,519 @@ +setModelAlias($modelAlias); + } + if ($criteria instanceof Criteria) { + $query->mergeWith($criteria); + } + + return $query; + } + + /** + * Find object by primary key. + * Propel uses the instance pool to skip the database if the object exists. + * Go fast if the query is untouched. + * + * + * $obj = $c->findPk(12, $con); + * + * + * @param mixed $key Primary key to use for the query + * @param ConnectionInterface $con an optional connection object + * + * @return ChildColissimoPickupPointAreaFreeshipping|array|mixed the result, formatted by the current formatter + */ + public function findPk($key, $con = null) + { + if ($key === null) { + return null; + } + if ((null !== ($obj = ColissimoPickupPointAreaFreeshippingTableMap::getInstanceFromPool((string) $key))) && !$this->formatter) { + // the object is already in the instance pool + return $obj; + } + if ($con === null) { + $con = Propel::getServiceContainer()->getReadConnection(ColissimoPickupPointAreaFreeshippingTableMap::DATABASE_NAME); + } + $this->basePreSelect($con); + if ($this->formatter || $this->modelAlias || $this->with || $this->select + || $this->selectColumns || $this->asColumns || $this->selectModifiers + || $this->map || $this->having || $this->joins) { + return $this->findPkComplex($key, $con); + } else { + return $this->findPkSimple($key, $con); + } + } + + /** + * Find object by primary key using raw SQL to go fast. + * Bypass doSelect() and the object formatter by using generated code. + * + * @param mixed $key Primary key to use for the query + * @param ConnectionInterface $con A connection object + * + * @return ChildColissimoPickupPointAreaFreeshipping A model object, or null if the key is not found + */ + protected function findPkSimple($key, $con) + { + $sql = 'SELECT ID, AREA_ID, CART_AMOUNT FROM colissimo_pickup_point_area_freeshipping WHERE ID = :p0'; + try { + $stmt = $con->prepare($sql); + $stmt->bindValue(':p0', $key, PDO::PARAM_INT); + $stmt->execute(); + } catch (Exception $e) { + Propel::log($e->getMessage(), Propel::LOG_ERR); + throw new PropelException(sprintf('Unable to execute SELECT statement [%s]', $sql), 0, $e); + } + $obj = null; + if ($row = $stmt->fetch(\PDO::FETCH_NUM)) { + $obj = new ChildColissimoPickupPointAreaFreeshipping(); + $obj->hydrate($row); + ColissimoPickupPointAreaFreeshippingTableMap::addInstanceToPool($obj, (string) $key); + } + $stmt->closeCursor(); + + return $obj; + } + + /** + * Find object by primary key. + * + * @param mixed $key Primary key to use for the query + * @param ConnectionInterface $con A connection object + * + * @return ChildColissimoPickupPointAreaFreeshipping|array|mixed the result, formatted by the current formatter + */ + protected function findPkComplex($key, $con) + { + // As the query uses a PK condition, no limit(1) is necessary. + $criteria = $this->isKeepQuery() ? clone $this : $this; + $dataFetcher = $criteria + ->filterByPrimaryKey($key) + ->doSelect($con); + + return $criteria->getFormatter()->init($criteria)->formatOne($dataFetcher); + } + + /** + * Find objects by primary key + * + * $objs = $c->findPks(array(12, 56, 832), $con); + * + * @param array $keys Primary keys to use for the query + * @param ConnectionInterface $con an optional connection object + * + * @return ObjectCollection|array|mixed the list of results, formatted by the current formatter + */ + public function findPks($keys, $con = null) + { + if (null === $con) { + $con = Propel::getServiceContainer()->getReadConnection($this->getDbName()); + } + $this->basePreSelect($con); + $criteria = $this->isKeepQuery() ? clone $this : $this; + $dataFetcher = $criteria + ->filterByPrimaryKeys($keys) + ->doSelect($con); + + return $criteria->getFormatter()->init($criteria)->format($dataFetcher); + } + + /** + * Filter the query by primary key + * + * @param mixed $key Primary key to use for the query + * + * @return ChildColissimoPickupPointAreaFreeshippingQuery The current query, for fluid interface + */ + public function filterByPrimaryKey($key) + { + + return $this->addUsingAlias(ColissimoPickupPointAreaFreeshippingTableMap::ID, $key, Criteria::EQUAL); + } + + /** + * Filter the query by a list of primary keys + * + * @param array $keys The list of primary key to use for the query + * + * @return ChildColissimoPickupPointAreaFreeshippingQuery The current query, for fluid interface + */ + public function filterByPrimaryKeys($keys) + { + + return $this->addUsingAlias(ColissimoPickupPointAreaFreeshippingTableMap::ID, $keys, Criteria::IN); + } + + /** + * Filter the query on the id column + * + * Example usage: + * + * $query->filterById(1234); // WHERE id = 1234 + * $query->filterById(array(12, 34)); // WHERE id IN (12, 34) + * $query->filterById(array('min' => 12)); // WHERE id > 12 + * + * + * @param mixed $id The value to use as filter. + * Use scalar values for equality. + * Use array values for in_array() equivalent. + * Use associative array('min' => $minValue, 'max' => $maxValue) for intervals. + * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL + * + * @return ChildColissimoPickupPointAreaFreeshippingQuery The current query, for fluid interface + */ + public function filterById($id = null, $comparison = null) + { + if (is_array($id)) { + $useMinMax = false; + if (isset($id['min'])) { + $this->addUsingAlias(ColissimoPickupPointAreaFreeshippingTableMap::ID, $id['min'], Criteria::GREATER_EQUAL); + $useMinMax = true; + } + if (isset($id['max'])) { + $this->addUsingAlias(ColissimoPickupPointAreaFreeshippingTableMap::ID, $id['max'], Criteria::LESS_EQUAL); + $useMinMax = true; + } + if ($useMinMax) { + return $this; + } + if (null === $comparison) { + $comparison = Criteria::IN; + } + } + + return $this->addUsingAlias(ColissimoPickupPointAreaFreeshippingTableMap::ID, $id, $comparison); + } + + /** + * Filter the query on the area_id column + * + * Example usage: + * + * $query->filterByAreaId(1234); // WHERE area_id = 1234 + * $query->filterByAreaId(array(12, 34)); // WHERE area_id IN (12, 34) + * $query->filterByAreaId(array('min' => 12)); // WHERE area_id > 12 + * + * + * @see filterByArea() + * + * @param mixed $areaId The value to use as filter. + * Use scalar values for equality. + * Use array values for in_array() equivalent. + * Use associative array('min' => $minValue, 'max' => $maxValue) for intervals. + * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL + * + * @return ChildColissimoPickupPointAreaFreeshippingQuery The current query, for fluid interface + */ + public function filterByAreaId($areaId = null, $comparison = null) + { + if (is_array($areaId)) { + $useMinMax = false; + if (isset($areaId['min'])) { + $this->addUsingAlias(ColissimoPickupPointAreaFreeshippingTableMap::AREA_ID, $areaId['min'], Criteria::GREATER_EQUAL); + $useMinMax = true; + } + if (isset($areaId['max'])) { + $this->addUsingAlias(ColissimoPickupPointAreaFreeshippingTableMap::AREA_ID, $areaId['max'], Criteria::LESS_EQUAL); + $useMinMax = true; + } + if ($useMinMax) { + return $this; + } + if (null === $comparison) { + $comparison = Criteria::IN; + } + } + + return $this->addUsingAlias(ColissimoPickupPointAreaFreeshippingTableMap::AREA_ID, $areaId, $comparison); + } + + /** + * Filter the query on the cart_amount column + * + * Example usage: + * + * $query->filterByCartAmount(1234); // WHERE cart_amount = 1234 + * $query->filterByCartAmount(array(12, 34)); // WHERE cart_amount IN (12, 34) + * $query->filterByCartAmount(array('min' => 12)); // WHERE cart_amount > 12 + * + * + * @param mixed $cartAmount The value to use as filter. + * Use scalar values for equality. + * Use array values for in_array() equivalent. + * Use associative array('min' => $minValue, 'max' => $maxValue) for intervals. + * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL + * + * @return ChildColissimoPickupPointAreaFreeshippingQuery The current query, for fluid interface + */ + public function filterByCartAmount($cartAmount = null, $comparison = null) + { + if (is_array($cartAmount)) { + $useMinMax = false; + if (isset($cartAmount['min'])) { + $this->addUsingAlias(ColissimoPickupPointAreaFreeshippingTableMap::CART_AMOUNT, $cartAmount['min'], Criteria::GREATER_EQUAL); + $useMinMax = true; + } + if (isset($cartAmount['max'])) { + $this->addUsingAlias(ColissimoPickupPointAreaFreeshippingTableMap::CART_AMOUNT, $cartAmount['max'], Criteria::LESS_EQUAL); + $useMinMax = true; + } + if ($useMinMax) { + return $this; + } + if (null === $comparison) { + $comparison = Criteria::IN; + } + } + + return $this->addUsingAlias(ColissimoPickupPointAreaFreeshippingTableMap::CART_AMOUNT, $cartAmount, $comparison); + } + + /** + * Filter the query by a related \ColissimoPickupPoint\Model\Thelia\Model\Area object + * + * @param \ColissimoPickupPoint\Model\Thelia\Model\Area|ObjectCollection $area The related object(s) to use as filter + * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL + * + * @return ChildColissimoPickupPointAreaFreeshippingQuery The current query, for fluid interface + */ + public function filterByArea($area, $comparison = null) + { + if ($area instanceof \ColissimoPickupPoint\Model\Thelia\Model\Area) { + return $this + ->addUsingAlias(ColissimoPickupPointAreaFreeshippingTableMap::AREA_ID, $area->getId(), $comparison); + } elseif ($area instanceof ObjectCollection) { + if (null === $comparison) { + $comparison = Criteria::IN; + } + + return $this + ->addUsingAlias(ColissimoPickupPointAreaFreeshippingTableMap::AREA_ID, $area->toKeyValue('PrimaryKey', 'Id'), $comparison); + } else { + throw new PropelException('filterByArea() only accepts arguments of type \ColissimoPickupPoint\Model\Thelia\Model\Area or Collection'); + } + } + + /** + * Adds a JOIN clause to the query using the Area relation + * + * @param string $relationAlias optional alias for the relation + * @param string $joinType Accepted values are null, 'left join', 'right join', 'inner join' + * + * @return ChildColissimoPickupPointAreaFreeshippingQuery The current query, for fluid interface + */ + public function joinArea($relationAlias = null, $joinType = Criteria::INNER_JOIN) + { + $tableMap = $this->getTableMap(); + $relationMap = $tableMap->getRelation('Area'); + + // create a ModelJoin object for this join + $join = new ModelJoin(); + $join->setJoinType($joinType); + $join->setRelationMap($relationMap, $this->useAliasInSQL ? $this->getModelAlias() : null, $relationAlias); + if ($previousJoin = $this->getPreviousJoin()) { + $join->setPreviousJoin($previousJoin); + } + + // add the ModelJoin to the current object + if ($relationAlias) { + $this->addAlias($relationAlias, $relationMap->getRightTable()->getName()); + $this->addJoinObject($join, $relationAlias); + } else { + $this->addJoinObject($join, 'Area'); + } + + return $this; + } + + /** + * Use the Area relation Area object + * + * @see useQuery() + * + * @param string $relationAlias optional alias for the relation, + * to be used as main alias in the secondary query + * @param string $joinType Accepted values are null, 'left join', 'right join', 'inner join' + * + * @return \ColissimoPickupPoint\Model\Thelia\Model\AreaQuery A secondary query class using the current class as primary query + */ + public function useAreaQuery($relationAlias = null, $joinType = Criteria::INNER_JOIN) + { + return $this + ->joinArea($relationAlias, $joinType) + ->useQuery($relationAlias ? $relationAlias : 'Area', '\ColissimoPickupPoint\Model\Thelia\Model\AreaQuery'); + } + + /** + * Exclude object from result + * + * @param ChildColissimoPickupPointAreaFreeshipping $colissimoPickupPointAreaFreeshipping Object to remove from the list of results + * + * @return ChildColissimoPickupPointAreaFreeshippingQuery The current query, for fluid interface + */ + public function prune($colissimoPickupPointAreaFreeshipping = null) + { + if ($colissimoPickupPointAreaFreeshipping) { + $this->addUsingAlias(ColissimoPickupPointAreaFreeshippingTableMap::ID, $colissimoPickupPointAreaFreeshipping->getId(), Criteria::NOT_EQUAL); + } + + return $this; + } + + /** + * Deletes all rows from the colissimo_pickup_point_area_freeshipping table. + * + * @param ConnectionInterface $con the connection to use + * @return int The number of affected rows (if supported by underlying database driver). + */ + public function doDeleteAll(ConnectionInterface $con = null) + { + if (null === $con) { + $con = Propel::getServiceContainer()->getWriteConnection(ColissimoPickupPointAreaFreeshippingTableMap::DATABASE_NAME); + } + $affectedRows = 0; // initialize var to track total num of affected rows + try { + // use transaction because $criteria could contain info + // for more than one table or we could emulating ON DELETE CASCADE, etc. + $con->beginTransaction(); + $affectedRows += parent::doDeleteAll($con); + // Because this db requires some delete cascade/set null emulation, we have to + // clear the cached instance *after* the emulation has happened (since + // instances get re-added by the select statement contained therein). + ColissimoPickupPointAreaFreeshippingTableMap::clearInstancePool(); + ColissimoPickupPointAreaFreeshippingTableMap::clearRelatedInstancePool(); + + $con->commit(); + } catch (PropelException $e) { + $con->rollBack(); + throw $e; + } + + return $affectedRows; + } + + /** + * Performs a DELETE on the database, given a ChildColissimoPickupPointAreaFreeshipping or Criteria object OR a primary key value. + * + * @param mixed $values Criteria or ChildColissimoPickupPointAreaFreeshipping object or primary key or array of primary keys + * which is used to create the DELETE statement + * @param ConnectionInterface $con the connection to use + * @return int The number of affected rows (if supported by underlying database driver). This includes CASCADE-related rows + * if supported by native driver or if emulated using Propel. + * @throws PropelException Any exceptions caught during processing will be + * rethrown wrapped into a PropelException. + */ + public function delete(ConnectionInterface $con = null) + { + if (null === $con) { + $con = Propel::getServiceContainer()->getWriteConnection(ColissimoPickupPointAreaFreeshippingTableMap::DATABASE_NAME); + } + + $criteria = $this; + + // Set the correct dbName + $criteria->setDbName(ColissimoPickupPointAreaFreeshippingTableMap::DATABASE_NAME); + + $affectedRows = 0; // initialize var to track total num of affected rows + + try { + // use transaction because $criteria could contain info + // for more than one table or we could emulating ON DELETE CASCADE, etc. + $con->beginTransaction(); + + + ColissimoPickupPointAreaFreeshippingTableMap::removeInstanceFromPool($criteria); + + $affectedRows += ModelCriteria::delete($con); + ColissimoPickupPointAreaFreeshippingTableMap::clearRelatedInstancePool(); + $con->commit(); + + return $affectedRows; + } catch (PropelException $e) { + $con->rollBack(); + throw $e; + } + } + +} // ColissimoPickupPointAreaFreeshippingQuery diff --git a/local/modules/ColissimoPickupPoint/Model/Base/ColissimoPickupPointFreeshipping.php b/local/modules/ColissimoPickupPoint/Model/Base/ColissimoPickupPointFreeshipping.php new file mode 100644 index 00000000..22c1c039 --- /dev/null +++ b/local/modules/ColissimoPickupPoint/Model/Base/ColissimoPickupPointFreeshipping.php @@ -0,0 +1,1184 @@ +active = false; + } + + /** + * Initializes internal state of ColissimoPickupPoint\Model\Base\ColissimoPickupPointFreeshipping object. + * @see applyDefaults() + */ + public function __construct() + { + $this->applyDefaultValues(); + } + + /** + * Returns whether the object has been modified. + * + * @return boolean True if the object has been modified. + */ + public function isModified() + { + return !!$this->modifiedColumns; + } + + /** + * Has specified column been modified? + * + * @param string $col column fully qualified name (TableMap::TYPE_COLNAME), e.g. Book::AUTHOR_ID + * @return boolean True if $col has been modified. + */ + public function isColumnModified($col) + { + return $this->modifiedColumns && isset($this->modifiedColumns[$col]); + } + + /** + * Get the columns that have been modified in this object. + * @return array A unique list of the modified column names for this object. + */ + public function getModifiedColumns() + { + return $this->modifiedColumns ? array_keys($this->modifiedColumns) : []; + } + + /** + * Returns whether the object has ever been saved. This will + * be false, if the object was retrieved from storage or was created + * and then saved. + * + * @return boolean true, if the object has never been persisted. + */ + public function isNew() + { + return $this->new; + } + + /** + * Setter for the isNew attribute. This method will be called + * by Propel-generated children and objects. + * + * @param boolean $b the state of the object. + */ + public function setNew($b) + { + $this->new = (Boolean) $b; + } + + /** + * Whether this object has been deleted. + * @return boolean The deleted state of this object. + */ + public function isDeleted() + { + return $this->deleted; + } + + /** + * Specify whether this object has been deleted. + * @param boolean $b The deleted state of this object. + * @return void + */ + public function setDeleted($b) + { + $this->deleted = (Boolean) $b; + } + + /** + * Sets the modified state for the object to be false. + * @param string $col If supplied, only the specified column is reset. + * @return void + */ + public function resetModified($col = null) + { + if (null !== $col) { + if (isset($this->modifiedColumns[$col])) { + unset($this->modifiedColumns[$col]); + } + } else { + $this->modifiedColumns = array(); + } + } + + /** + * Compares this with another ColissimoPickupPointFreeshipping instance. If + * obj is an instance of ColissimoPickupPointFreeshipping, delegates to + * equals(ColissimoPickupPointFreeshipping). Otherwise, returns false. + * + * @param mixed $obj The object to compare to. + * @return boolean Whether equal to the object specified. + */ + public function equals($obj) + { + $thisclazz = get_class($this); + if (!is_object($obj) || !($obj instanceof $thisclazz)) { + return false; + } + + if ($this === $obj) { + return true; + } + + if (null === $this->getPrimaryKey() + || null === $obj->getPrimaryKey()) { + return false; + } + + return $this->getPrimaryKey() === $obj->getPrimaryKey(); + } + + /** + * If the primary key is not null, return the hashcode of the + * primary key. Otherwise, return the hash code of the object. + * + * @return int Hashcode + */ + public function hashCode() + { + if (null !== $this->getPrimaryKey()) { + return crc32(serialize($this->getPrimaryKey())); + } + + return crc32(serialize(clone $this)); + } + + /** + * Get the associative array of the virtual columns in this object + * + * @return array + */ + public function getVirtualColumns() + { + return $this->virtualColumns; + } + + /** + * Checks the existence of a virtual column in this object + * + * @param string $name The virtual column name + * @return boolean + */ + public function hasVirtualColumn($name) + { + return array_key_exists($name, $this->virtualColumns); + } + + /** + * Get the value of a virtual column in this object + * + * @param string $name The virtual column name + * @return mixed + * + * @throws PropelException + */ + public function getVirtualColumn($name) + { + if (!$this->hasVirtualColumn($name)) { + throw new PropelException(sprintf('Cannot get value of inexistent virtual column %s.', $name)); + } + + return $this->virtualColumns[$name]; + } + + /** + * Set the value of a virtual column in this object + * + * @param string $name The virtual column name + * @param mixed $value The value to give to the virtual column + * + * @return ColissimoPickupPointFreeshipping The current object, for fluid interface + */ + public function setVirtualColumn($name, $value) + { + $this->virtualColumns[$name] = $value; + + return $this; + } + + /** + * Logs a message using Propel::log(). + * + * @param string $msg + * @param int $priority One of the Propel::LOG_* logging levels + * @return boolean + */ + protected function log($msg, $priority = Propel::LOG_INFO) + { + return Propel::log(get_class($this) . ': ' . $msg, $priority); + } + + /** + * Populate the current object from a string, using a given parser format + * + * $book = new Book(); + * $book->importFrom('JSON', '{"Id":9012,"Title":"Don Juan","ISBN":"0140422161","Price":12.99,"PublisherId":1234,"AuthorId":5678}'); + * + * + * @param mixed $parser A AbstractParser instance, + * or a format name ('XML', 'YAML', 'JSON', 'CSV') + * @param string $data The source data to import from + * + * @return ColissimoPickupPointFreeshipping The current object, for fluid interface + */ + public function importFrom($parser, $data) + { + if (!$parser instanceof AbstractParser) { + $parser = AbstractParser::getParser($parser); + } + + $this->fromArray($parser->toArray($data), TableMap::TYPE_PHPNAME); + + return $this; + } + + /** + * Export the current object properties to a string, using a given parser format + * + * $book = BookQuery::create()->findPk(9012); + * echo $book->exportTo('JSON'); + * => {"Id":9012,"Title":"Don Juan","ISBN":"0140422161","Price":12.99,"PublisherId":1234,"AuthorId":5678}'); + * + * + * @param mixed $parser A AbstractParser instance, or a format name ('XML', 'YAML', 'JSON', 'CSV') + * @param boolean $includeLazyLoadColumns (optional) Whether to include lazy load(ed) columns. Defaults to TRUE. + * @return string The exported data + */ + public function exportTo($parser, $includeLazyLoadColumns = true) + { + if (!$parser instanceof AbstractParser) { + $parser = AbstractParser::getParser($parser); + } + + return $parser->fromArray($this->toArray(TableMap::TYPE_PHPNAME, $includeLazyLoadColumns, array(), true)); + } + + /** + * Clean up internal collections prior to serializing + * Avoids recursive loops that turn into segmentation faults when serializing + */ + public function __sleep() + { + $this->clearAllReferences(); + + return array_keys(get_object_vars($this)); + } + + /** + * Get the [id] column value. + * + * @return int + */ + public function getId() + { + + return $this->id; + } + + /** + * Get the [active] column value. + * + * @return boolean + */ + public function getActive() + { + + return $this->active; + } + + /** + * Get the [freeshipping_from] column value. + * + * @return string + */ + public function getFreeshippingFrom() + { + + return $this->freeshipping_from; + } + + /** + * Set the value of [id] column. + * + * @param int $v new value + * @return \ColissimoPickupPoint\Model\ColissimoPickupPointFreeshipping The current object (for fluent API support) + */ + public function setId($v) + { + if ($v !== null) { + $v = (int) $v; + } + + if ($this->id !== $v) { + $this->id = $v; + $this->modifiedColumns[ColissimoPickupPointFreeshippingTableMap::ID] = true; + } + + + return $this; + } // setId() + + /** + * Sets the value of the [active] column. + * Non-boolean arguments are converted using the following rules: + * * 1, '1', 'true', 'on', and 'yes' are converted to boolean true + * * 0, '0', 'false', 'off', and 'no' are converted to boolean false + * Check on string values is case insensitive (so 'FaLsE' is seen as 'false'). + * + * @param boolean|integer|string $v The new value + * @return \ColissimoPickupPoint\Model\ColissimoPickupPointFreeshipping The current object (for fluent API support) + */ + public function setActive($v) + { + if ($v !== null) { + if (is_string($v)) { + $v = in_array(strtolower($v), array('false', 'off', '-', 'no', 'n', '0', '')) ? false : true; + } else { + $v = (boolean) $v; + } + } + + if ($this->active !== $v) { + $this->active = $v; + $this->modifiedColumns[ColissimoPickupPointFreeshippingTableMap::ACTIVE] = true; + } + + + return $this; + } // setActive() + + /** + * Set the value of [freeshipping_from] column. + * + * @param string $v new value + * @return \ColissimoPickupPoint\Model\ColissimoPickupPointFreeshipping The current object (for fluent API support) + */ + public function setFreeshippingFrom($v) + { + if ($v !== null) { + $v = (string) $v; + } + + if ($this->freeshipping_from !== $v) { + $this->freeshipping_from = $v; + $this->modifiedColumns[ColissimoPickupPointFreeshippingTableMap::FREESHIPPING_FROM] = true; + } + + + return $this; + } // setFreeshippingFrom() + + /** + * Indicates whether the columns in this object are only set to default values. + * + * This method can be used in conjunction with isModified() to indicate whether an object is both + * modified _and_ has some values set which are non-default. + * + * @return boolean Whether the columns in this object are only been set with default values. + */ + public function hasOnlyDefaultValues() + { + if ($this->active !== false) { + return false; + } + + // otherwise, everything was equal, so return TRUE + return true; + } // hasOnlyDefaultValues() + + /** + * Hydrates (populates) the object variables with values from the database resultset. + * + * An offset (0-based "start column") is specified so that objects can be hydrated + * with a subset of the columns in the resultset rows. This is needed, for example, + * for results of JOIN queries where the resultset row includes columns from two or + * more tables. + * + * @param array $row The row returned by DataFetcher->fetch(). + * @param int $startcol 0-based offset column which indicates which restultset column to start with. + * @param boolean $rehydrate Whether this object is being re-hydrated from the database. + * @param string $indexType The index type of $row. Mostly DataFetcher->getIndexType(). + One of the class type constants TableMap::TYPE_PHPNAME, TableMap::TYPE_STUDLYPHPNAME + * TableMap::TYPE_COLNAME, TableMap::TYPE_FIELDNAME, TableMap::TYPE_NUM. + * + * @return int next starting column + * @throws PropelException - Any caught Exception will be rewrapped as a PropelException. + */ + public function hydrate($row, $startcol = 0, $rehydrate = false, $indexType = TableMap::TYPE_NUM) + { + try { + + + $col = $row[TableMap::TYPE_NUM == $indexType ? 0 + $startcol : ColissimoPickupPointFreeshippingTableMap::translateFieldName('Id', TableMap::TYPE_PHPNAME, $indexType)]; + $this->id = (null !== $col) ? (int) $col : null; + + $col = $row[TableMap::TYPE_NUM == $indexType ? 1 + $startcol : ColissimoPickupPointFreeshippingTableMap::translateFieldName('Active', TableMap::TYPE_PHPNAME, $indexType)]; + $this->active = (null !== $col) ? (boolean) $col : null; + + $col = $row[TableMap::TYPE_NUM == $indexType ? 2 + $startcol : ColissimoPickupPointFreeshippingTableMap::translateFieldName('FreeshippingFrom', TableMap::TYPE_PHPNAME, $indexType)]; + $this->freeshipping_from = (null !== $col) ? (string) $col : null; + $this->resetModified(); + + $this->setNew(false); + + if ($rehydrate) { + $this->ensureConsistency(); + } + + return $startcol + 3; // 3 = ColissimoPickupPointFreeshippingTableMap::NUM_HYDRATE_COLUMNS. + + } catch (Exception $e) { + throw new PropelException("Error populating \ColissimoPickupPoint\Model\ColissimoPickupPointFreeshipping object", 0, $e); + } + } + + /** + * Checks and repairs the internal consistency of the object. + * + * This method is executed after an already-instantiated object is re-hydrated + * from the database. It exists to check any foreign keys to make sure that + * the objects related to the current object are correct based on foreign key. + * + * You can override this method in the stub class, but you should always invoke + * the base method from the overridden method (i.e. parent::ensureConsistency()), + * in case your model changes. + * + * @throws PropelException + */ + public function ensureConsistency() + { + } // ensureConsistency + + /** + * Reloads this object from datastore based on primary key and (optionally) resets all associated objects. + * + * This will only work if the object has been saved and has a valid primary key set. + * + * @param boolean $deep (optional) Whether to also de-associated any related objects. + * @param ConnectionInterface $con (optional) The ConnectionInterface connection to use. + * @return void + * @throws PropelException - if this object is deleted, unsaved or doesn't have pk match in db + */ + public function reload($deep = false, ConnectionInterface $con = null) + { + if ($this->isDeleted()) { + throw new PropelException("Cannot reload a deleted object."); + } + + if ($this->isNew()) { + throw new PropelException("Cannot reload an unsaved object."); + } + + if ($con === null) { + $con = Propel::getServiceContainer()->getReadConnection(ColissimoPickupPointFreeshippingTableMap::DATABASE_NAME); + } + + // We don't need to alter the object instance pool; we're just modifying this instance + // already in the pool. + + $dataFetcher = ChildColissimoPickupPointFreeshippingQuery::create(null, $this->buildPkeyCriteria())->setFormatter(ModelCriteria::FORMAT_STATEMENT)->find($con); + $row = $dataFetcher->fetch(); + $dataFetcher->close(); + if (!$row) { + throw new PropelException('Cannot find matching row in the database to reload object values.'); + } + $this->hydrate($row, 0, true, $dataFetcher->getIndexType()); // rehydrate + + if ($deep) { // also de-associate any related objects? + + } // if (deep) + } + + /** + * Removes this object from datastore and sets delete attribute. + * + * @param ConnectionInterface $con + * @return void + * @throws PropelException + * @see ColissimoPickupPointFreeshipping::setDeleted() + * @see ColissimoPickupPointFreeshipping::isDeleted() + */ + public function delete(ConnectionInterface $con = null) + { + if ($this->isDeleted()) { + throw new PropelException("This object has already been deleted."); + } + + if ($con === null) { + $con = Propel::getServiceContainer()->getWriteConnection(ColissimoPickupPointFreeshippingTableMap::DATABASE_NAME); + } + + $con->beginTransaction(); + try { + $deleteQuery = ChildColissimoPickupPointFreeshippingQuery::create() + ->filterByPrimaryKey($this->getPrimaryKey()); + $ret = $this->preDelete($con); + if ($ret) { + $deleteQuery->delete($con); + $this->postDelete($con); + $con->commit(); + $this->setDeleted(true); + } else { + $con->commit(); + } + } catch (Exception $e) { + $con->rollBack(); + throw $e; + } + } + + /** + * Persists this object to the database. + * + * If the object is new, it inserts it; otherwise an update is performed. + * All modified related objects will also be persisted in the doSave() + * method. This method wraps all precipitate database operations in a + * single transaction. + * + * @param ConnectionInterface $con + * @return int The number of rows affected by this insert/update and any referring fk objects' save() operations. + * @throws PropelException + * @see doSave() + */ + public function save(ConnectionInterface $con = null) + { + if ($this->isDeleted()) { + throw new PropelException("You cannot save an object that has been deleted."); + } + + if ($con === null) { + $con = Propel::getServiceContainer()->getWriteConnection(ColissimoPickupPointFreeshippingTableMap::DATABASE_NAME); + } + + $con->beginTransaction(); + $isInsert = $this->isNew(); + try { + $ret = $this->preSave($con); + if ($isInsert) { + $ret = $ret && $this->preInsert($con); + } else { + $ret = $ret && $this->preUpdate($con); + } + if ($ret) { + $affectedRows = $this->doSave($con); + if ($isInsert) { + $this->postInsert($con); + } else { + $this->postUpdate($con); + } + $this->postSave($con); + ColissimoPickupPointFreeshippingTableMap::addInstanceToPool($this); + } else { + $affectedRows = 0; + } + $con->commit(); + + return $affectedRows; + } catch (Exception $e) { + $con->rollBack(); + throw $e; + } + } + + /** + * Performs the work of inserting or updating the row in the database. + * + * If the object is new, it inserts it; otherwise an update is performed. + * All related objects are also updated in this method. + * + * @param ConnectionInterface $con + * @return int The number of rows affected by this insert/update and any referring fk objects' save() operations. + * @throws PropelException + * @see save() + */ + protected function doSave(ConnectionInterface $con) + { + $affectedRows = 0; // initialize var to track total num of affected rows + if (!$this->alreadyInSave) { + $this->alreadyInSave = true; + + if ($this->isNew() || $this->isModified()) { + // persist changes + if ($this->isNew()) { + $this->doInsert($con); + } else { + $this->doUpdate($con); + } + $affectedRows += 1; + $this->resetModified(); + } + + $this->alreadyInSave = false; + + } + + return $affectedRows; + } // doSave() + + /** + * Insert the row in the database. + * + * @param ConnectionInterface $con + * + * @throws PropelException + * @see doSave() + */ + protected function doInsert(ConnectionInterface $con) + { + $modifiedColumns = array(); + $index = 0; + + + // check the columns in natural order for more readable SQL queries + if ($this->isColumnModified(ColissimoPickupPointFreeshippingTableMap::ID)) { + $modifiedColumns[':p' . $index++] = 'ID'; + } + if ($this->isColumnModified(ColissimoPickupPointFreeshippingTableMap::ACTIVE)) { + $modifiedColumns[':p' . $index++] = 'ACTIVE'; + } + if ($this->isColumnModified(ColissimoPickupPointFreeshippingTableMap::FREESHIPPING_FROM)) { + $modifiedColumns[':p' . $index++] = 'FREESHIPPING_FROM'; + } + + $sql = sprintf( + 'INSERT INTO colissimo_pickup_point_freeshipping (%s) VALUES (%s)', + implode(', ', $modifiedColumns), + implode(', ', array_keys($modifiedColumns)) + ); + + try { + $stmt = $con->prepare($sql); + foreach ($modifiedColumns as $identifier => $columnName) { + switch ($columnName) { + case 'ID': + $stmt->bindValue($identifier, $this->id, PDO::PARAM_INT); + break; + case 'ACTIVE': + $stmt->bindValue($identifier, (int) $this->active, PDO::PARAM_INT); + break; + case 'FREESHIPPING_FROM': + $stmt->bindValue($identifier, $this->freeshipping_from, PDO::PARAM_STR); + break; + } + } + $stmt->execute(); + } catch (Exception $e) { + Propel::log($e->getMessage(), Propel::LOG_ERR); + throw new PropelException(sprintf('Unable to execute INSERT statement [%s]', $sql), 0, $e); + } + + $this->setNew(false); + } + + /** + * Update the row in the database. + * + * @param ConnectionInterface $con + * + * @return Integer Number of updated rows + * @see doSave() + */ + protected function doUpdate(ConnectionInterface $con) + { + $selectCriteria = $this->buildPkeyCriteria(); + $valuesCriteria = $this->buildCriteria(); + + return $selectCriteria->doUpdate($valuesCriteria, $con); + } + + /** + * Retrieves a field from the object by name passed in as a string. + * + * @param string $name name + * @param string $type The type of fieldname the $name is of: + * one of the class type constants TableMap::TYPE_PHPNAME, TableMap::TYPE_STUDLYPHPNAME + * TableMap::TYPE_COLNAME, TableMap::TYPE_FIELDNAME, TableMap::TYPE_NUM. + * Defaults to TableMap::TYPE_PHPNAME. + * @return mixed Value of field. + */ + public function getByName($name, $type = TableMap::TYPE_PHPNAME) + { + $pos = ColissimoPickupPointFreeshippingTableMap::translateFieldName($name, $type, TableMap::TYPE_NUM); + $field = $this->getByPosition($pos); + + return $field; + } + + /** + * Retrieves a field from the object by Position as specified in the xml schema. + * Zero-based. + * + * @param int $pos position in xml schema + * @return mixed Value of field at $pos + */ + public function getByPosition($pos) + { + switch ($pos) { + case 0: + return $this->getId(); + break; + case 1: + return $this->getActive(); + break; + case 2: + return $this->getFreeshippingFrom(); + break; + default: + return null; + break; + } // switch() + } + + /** + * Exports the object as an array. + * + * You can specify the key type of the array by passing one of the class + * type constants. + * + * @param string $keyType (optional) One of the class type constants TableMap::TYPE_PHPNAME, TableMap::TYPE_STUDLYPHPNAME, + * TableMap::TYPE_COLNAME, TableMap::TYPE_FIELDNAME, TableMap::TYPE_NUM. + * Defaults to TableMap::TYPE_PHPNAME. + * @param boolean $includeLazyLoadColumns (optional) Whether to include lazy loaded columns. Defaults to TRUE. + * @param array $alreadyDumpedObjects List of objects to skip to avoid recursion + * + * @return array an associative array containing the field names (as keys) and field values + */ + public function toArray($keyType = TableMap::TYPE_PHPNAME, $includeLazyLoadColumns = true, $alreadyDumpedObjects = array()) + { + if (isset($alreadyDumpedObjects['ColissimoPickupPointFreeshipping'][$this->getPrimaryKey()])) { + return '*RECURSION*'; + } + $alreadyDumpedObjects['ColissimoPickupPointFreeshipping'][$this->getPrimaryKey()] = true; + $keys = ColissimoPickupPointFreeshippingTableMap::getFieldNames($keyType); + $result = array( + $keys[0] => $this->getId(), + $keys[1] => $this->getActive(), + $keys[2] => $this->getFreeshippingFrom(), + ); + $virtualColumns = $this->virtualColumns; + foreach ($virtualColumns as $key => $virtualColumn) { + $result[$key] = $virtualColumn; + } + + + return $result; + } + + /** + * Sets a field from the object by name passed in as a string. + * + * @param string $name + * @param mixed $value field value + * @param string $type The type of fieldname the $name is of: + * one of the class type constants TableMap::TYPE_PHPNAME, TableMap::TYPE_STUDLYPHPNAME + * TableMap::TYPE_COLNAME, TableMap::TYPE_FIELDNAME, TableMap::TYPE_NUM. + * Defaults to TableMap::TYPE_PHPNAME. + * @return void + */ + public function setByName($name, $value, $type = TableMap::TYPE_PHPNAME) + { + $pos = ColissimoPickupPointFreeshippingTableMap::translateFieldName($name, $type, TableMap::TYPE_NUM); + + return $this->setByPosition($pos, $value); + } + + /** + * Sets a field from the object by Position as specified in the xml schema. + * Zero-based. + * + * @param int $pos position in xml schema + * @param mixed $value field value + * @return void + */ + public function setByPosition($pos, $value) + { + switch ($pos) { + case 0: + $this->setId($value); + break; + case 1: + $this->setActive($value); + break; + case 2: + $this->setFreeshippingFrom($value); + break; + } // switch() + } + + /** + * Populates the object using an array. + * + * This is particularly useful when populating an object from one of the + * request arrays (e.g. $_POST). This method goes through the column + * names, checking to see whether a matching key exists in populated + * array. If so the setByName() method is called for that column. + * + * You can specify the key type of the array by additionally passing one + * of the class type constants TableMap::TYPE_PHPNAME, TableMap::TYPE_STUDLYPHPNAME, + * TableMap::TYPE_COLNAME, TableMap::TYPE_FIELDNAME, TableMap::TYPE_NUM. + * The default key type is the column's TableMap::TYPE_PHPNAME. + * + * @param array $arr An array to populate the object from. + * @param string $keyType The type of keys the array uses. + * @return void + */ + public function fromArray($arr, $keyType = TableMap::TYPE_PHPNAME) + { + $keys = ColissimoPickupPointFreeshippingTableMap::getFieldNames($keyType); + + if (array_key_exists($keys[0], $arr)) $this->setId($arr[$keys[0]]); + if (array_key_exists($keys[1], $arr)) $this->setActive($arr[$keys[1]]); + if (array_key_exists($keys[2], $arr)) $this->setFreeshippingFrom($arr[$keys[2]]); + } + + /** + * Build a Criteria object containing the values of all modified columns in this object. + * + * @return Criteria The Criteria object containing all modified values. + */ + public function buildCriteria() + { + $criteria = new Criteria(ColissimoPickupPointFreeshippingTableMap::DATABASE_NAME); + + if ($this->isColumnModified(ColissimoPickupPointFreeshippingTableMap::ID)) $criteria->add(ColissimoPickupPointFreeshippingTableMap::ID, $this->id); + if ($this->isColumnModified(ColissimoPickupPointFreeshippingTableMap::ACTIVE)) $criteria->add(ColissimoPickupPointFreeshippingTableMap::ACTIVE, $this->active); + if ($this->isColumnModified(ColissimoPickupPointFreeshippingTableMap::FREESHIPPING_FROM)) $criteria->add(ColissimoPickupPointFreeshippingTableMap::FREESHIPPING_FROM, $this->freeshipping_from); + + return $criteria; + } + + /** + * Builds a Criteria object containing the primary key for this object. + * + * Unlike buildCriteria() this method includes the primary key values regardless + * of whether or not they have been modified. + * + * @return Criteria The Criteria object containing value(s) for primary key(s). + */ + public function buildPkeyCriteria() + { + $criteria = new Criteria(ColissimoPickupPointFreeshippingTableMap::DATABASE_NAME); + $criteria->add(ColissimoPickupPointFreeshippingTableMap::ID, $this->id); + + return $criteria; + } + + /** + * Returns the primary key for this object (row). + * @return int + */ + public function getPrimaryKey() + { + return $this->getId(); + } + + /** + * Generic method to set the primary key (id column). + * + * @param int $key Primary key. + * @return void + */ + public function setPrimaryKey($key) + { + $this->setId($key); + } + + /** + * Returns true if the primary key for this object is null. + * @return boolean + */ + public function isPrimaryKeyNull() + { + + return null === $this->getId(); + } + + /** + * Sets contents of passed object to values from current object. + * + * If desired, this method can also make copies of all associated (fkey referrers) + * objects. + * + * @param object $copyObj An object of \ColissimoPickupPoint\Model\ColissimoPickupPointFreeshipping (or compatible) type. + * @param boolean $deepCopy Whether to also copy all rows that refer (by fkey) to the current row. + * @param boolean $makeNew Whether to reset autoincrement PKs and make the object new. + * @throws PropelException + */ + public function copyInto($copyObj, $deepCopy = false, $makeNew = true) + { + $copyObj->setId($this->getId()); + $copyObj->setActive($this->getActive()); + $copyObj->setFreeshippingFrom($this->getFreeshippingFrom()); + if ($makeNew) { + $copyObj->setNew(true); + } + } + + /** + * Makes a copy of this object that will be inserted as a new row in table when saved. + * It creates a new object filling in the simple attributes, but skipping any primary + * keys that are defined for the table. + * + * If desired, this method can also make copies of all associated (fkey referrers) + * objects. + * + * @param boolean $deepCopy Whether to also copy all rows that refer (by fkey) to the current row. + * @return \ColissimoPickupPoint\Model\ColissimoPickupPointFreeshipping Clone of current object. + * @throws PropelException + */ + public function copy($deepCopy = false) + { + // we use get_class(), because this might be a subclass + $clazz = get_class($this); + $copyObj = new $clazz(); + $this->copyInto($copyObj, $deepCopy); + + return $copyObj; + } + + /** + * Clears the current object and sets all attributes to their default values + */ + public function clear() + { + $this->id = null; + $this->active = null; + $this->freeshipping_from = null; + $this->alreadyInSave = false; + $this->clearAllReferences(); + $this->applyDefaultValues(); + $this->resetModified(); + $this->setNew(true); + $this->setDeleted(false); + } + + /** + * Resets all references to other model objects or collections of model objects. + * + * This method is a user-space workaround for PHP's inability to garbage collect + * objects with circular references (even in PHP 5.3). This is currently necessary + * when using Propel in certain daemon or large-volume/high-memory operations. + * + * @param boolean $deep Whether to also clear the references on all referrer objects. + */ + public function clearAllReferences($deep = false) + { + if ($deep) { + } // if ($deep) + + } + + /** + * Return the string representation of this object + * + * @return string + */ + public function __toString() + { + return (string) $this->exportTo(ColissimoPickupPointFreeshippingTableMap::DEFAULT_STRING_FORMAT); + } + + /** + * Code to be run before persisting the object + * @param ConnectionInterface $con + * @return boolean + */ + public function preSave(ConnectionInterface $con = null) + { + return true; + } + + /** + * Code to be run after persisting the object + * @param ConnectionInterface $con + */ + public function postSave(ConnectionInterface $con = null) + { + + } + + /** + * Code to be run before inserting to database + * @param ConnectionInterface $con + * @return boolean + */ + public function preInsert(ConnectionInterface $con = null) + { + return true; + } + + /** + * Code to be run after inserting to database + * @param ConnectionInterface $con + */ + public function postInsert(ConnectionInterface $con = null) + { + + } + + /** + * Code to be run before updating the object in database + * @param ConnectionInterface $con + * @return boolean + */ + public function preUpdate(ConnectionInterface $con = null) + { + return true; + } + + /** + * Code to be run after updating the object in database + * @param ConnectionInterface $con + */ + public function postUpdate(ConnectionInterface $con = null) + { + + } + + /** + * Code to be run before deleting the object in database + * @param ConnectionInterface $con + * @return boolean + */ + public function preDelete(ConnectionInterface $con = null) + { + return true; + } + + /** + * Code to be run after deleting the object in database + * @param ConnectionInterface $con + */ + public function postDelete(ConnectionInterface $con = null) + { + + } + + + /** + * Derived method to catches calls to undefined methods. + * + * Provides magic import/export method support (fromXML()/toXML(), fromYAML()/toYAML(), etc.). + * Allows to define default __call() behavior if you overwrite __call() + * + * @param string $name + * @param mixed $params + * + * @return array|string + */ + public function __call($name, $params) + { + if (0 === strpos($name, 'get')) { + $virtualColumn = substr($name, 3); + if ($this->hasVirtualColumn($virtualColumn)) { + return $this->getVirtualColumn($virtualColumn); + } + + $virtualColumn = lcfirst($virtualColumn); + if ($this->hasVirtualColumn($virtualColumn)) { + return $this->getVirtualColumn($virtualColumn); + } + } + + if (0 === strpos($name, 'from')) { + $format = substr($name, 4); + + return $this->importFrom($format, reset($params)); + } + + if (0 === strpos($name, 'to')) { + $format = substr($name, 2); + $includeLazyLoadColumns = isset($params[0]) ? $params[0] : true; + + return $this->exportTo($format, $includeLazyLoadColumns); + } + + throw new BadMethodCallException(sprintf('Call to undefined method: %s.', $name)); + } + +} diff --git a/local/modules/ColissimoPickupPoint/Model/Base/ColissimoPickupPointFreeshippingQuery.php b/local/modules/ColissimoPickupPoint/Model/Base/ColissimoPickupPointFreeshippingQuery.php new file mode 100644 index 00000000..f9121ba8 --- /dev/null +++ b/local/modules/ColissimoPickupPoint/Model/Base/ColissimoPickupPointFreeshippingQuery.php @@ -0,0 +1,420 @@ +setModelAlias($modelAlias); + } + if ($criteria instanceof Criteria) { + $query->mergeWith($criteria); + } + + return $query; + } + + /** + * Find object by primary key. + * Propel uses the instance pool to skip the database if the object exists. + * Go fast if the query is untouched. + * + * + * $obj = $c->findPk(12, $con); + * + * + * @param mixed $key Primary key to use for the query + * @param ConnectionInterface $con an optional connection object + * + * @return ChildColissimoPickupPointFreeshipping|array|mixed the result, formatted by the current formatter + */ + public function findPk($key, $con = null) + { + if ($key === null) { + return null; + } + if ((null !== ($obj = ColissimoPickupPointFreeshippingTableMap::getInstanceFromPool((string) $key))) && !$this->formatter) { + // the object is already in the instance pool + return $obj; + } + if ($con === null) { + $con = Propel::getServiceContainer()->getReadConnection(ColissimoPickupPointFreeshippingTableMap::DATABASE_NAME); + } + $this->basePreSelect($con); + if ($this->formatter || $this->modelAlias || $this->with || $this->select + || $this->selectColumns || $this->asColumns || $this->selectModifiers + || $this->map || $this->having || $this->joins) { + return $this->findPkComplex($key, $con); + } else { + return $this->findPkSimple($key, $con); + } + } + + /** + * Find object by primary key using raw SQL to go fast. + * Bypass doSelect() and the object formatter by using generated code. + * + * @param mixed $key Primary key to use for the query + * @param ConnectionInterface $con A connection object + * + * @return ChildColissimoPickupPointFreeshipping A model object, or null if the key is not found + */ + protected function findPkSimple($key, $con) + { + $sql = 'SELECT ID, ACTIVE, FREESHIPPING_FROM FROM colissimo_pickup_point_freeshipping WHERE ID = :p0'; + try { + $stmt = $con->prepare($sql); + $stmt->bindValue(':p0', $key, PDO::PARAM_INT); + $stmt->execute(); + } catch (Exception $e) { + Propel::log($e->getMessage(), Propel::LOG_ERR); + throw new PropelException(sprintf('Unable to execute SELECT statement [%s]', $sql), 0, $e); + } + $obj = null; + if ($row = $stmt->fetch(\PDO::FETCH_NUM)) { + $obj = new ChildColissimoPickupPointFreeshipping(); + $obj->hydrate($row); + ColissimoPickupPointFreeshippingTableMap::addInstanceToPool($obj, (string) $key); + } + $stmt->closeCursor(); + + return $obj; + } + + /** + * Find object by primary key. + * + * @param mixed $key Primary key to use for the query + * @param ConnectionInterface $con A connection object + * + * @return ChildColissimoPickupPointFreeshipping|array|mixed the result, formatted by the current formatter + */ + protected function findPkComplex($key, $con) + { + // As the query uses a PK condition, no limit(1) is necessary. + $criteria = $this->isKeepQuery() ? clone $this : $this; + $dataFetcher = $criteria + ->filterByPrimaryKey($key) + ->doSelect($con); + + return $criteria->getFormatter()->init($criteria)->formatOne($dataFetcher); + } + + /** + * Find objects by primary key + * + * $objs = $c->findPks(array(12, 56, 832), $con); + * + * @param array $keys Primary keys to use for the query + * @param ConnectionInterface $con an optional connection object + * + * @return ObjectCollection|array|mixed the list of results, formatted by the current formatter + */ + public function findPks($keys, $con = null) + { + if (null === $con) { + $con = Propel::getServiceContainer()->getReadConnection($this->getDbName()); + } + $this->basePreSelect($con); + $criteria = $this->isKeepQuery() ? clone $this : $this; + $dataFetcher = $criteria + ->filterByPrimaryKeys($keys) + ->doSelect($con); + + return $criteria->getFormatter()->init($criteria)->format($dataFetcher); + } + + /** + * Filter the query by primary key + * + * @param mixed $key Primary key to use for the query + * + * @return ChildColissimoPickupPointFreeshippingQuery The current query, for fluid interface + */ + public function filterByPrimaryKey($key) + { + + return $this->addUsingAlias(ColissimoPickupPointFreeshippingTableMap::ID, $key, Criteria::EQUAL); + } + + /** + * Filter the query by a list of primary keys + * + * @param array $keys The list of primary key to use for the query + * + * @return ChildColissimoPickupPointFreeshippingQuery The current query, for fluid interface + */ + public function filterByPrimaryKeys($keys) + { + + return $this->addUsingAlias(ColissimoPickupPointFreeshippingTableMap::ID, $keys, Criteria::IN); + } + + /** + * Filter the query on the id column + * + * Example usage: + * + * $query->filterById(1234); // WHERE id = 1234 + * $query->filterById(array(12, 34)); // WHERE id IN (12, 34) + * $query->filterById(array('min' => 12)); // WHERE id > 12 + * + * + * @param mixed $id The value to use as filter. + * Use scalar values for equality. + * Use array values for in_array() equivalent. + * Use associative array('min' => $minValue, 'max' => $maxValue) for intervals. + * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL + * + * @return ChildColissimoPickupPointFreeshippingQuery The current query, for fluid interface + */ + public function filterById($id = null, $comparison = null) + { + if (is_array($id)) { + $useMinMax = false; + if (isset($id['min'])) { + $this->addUsingAlias(ColissimoPickupPointFreeshippingTableMap::ID, $id['min'], Criteria::GREATER_EQUAL); + $useMinMax = true; + } + if (isset($id['max'])) { + $this->addUsingAlias(ColissimoPickupPointFreeshippingTableMap::ID, $id['max'], Criteria::LESS_EQUAL); + $useMinMax = true; + } + if ($useMinMax) { + return $this; + } + if (null === $comparison) { + $comparison = Criteria::IN; + } + } + + return $this->addUsingAlias(ColissimoPickupPointFreeshippingTableMap::ID, $id, $comparison); + } + + /** + * Filter the query on the active column + * + * Example usage: + * + * $query->filterByActive(true); // WHERE active = true + * $query->filterByActive('yes'); // WHERE active = true + * + * + * @param boolean|string $active The value to use as filter. + * Non-boolean arguments are converted using the following rules: + * * 1, '1', 'true', 'on', and 'yes' are converted to boolean true + * * 0, '0', 'false', 'off', and 'no' are converted to boolean false + * Check on string values is case insensitive (so 'FaLsE' is seen as 'false'). + * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL + * + * @return ChildColissimoPickupPointFreeshippingQuery The current query, for fluid interface + */ + public function filterByActive($active = null, $comparison = null) + { + if (is_string($active)) { + $active = in_array(strtolower($active), array('false', 'off', '-', 'no', 'n', '0', '')) ? false : true; + } + + return $this->addUsingAlias(ColissimoPickupPointFreeshippingTableMap::ACTIVE, $active, $comparison); + } + + /** + * Filter the query on the freeshipping_from column + * + * Example usage: + * + * $query->filterByFreeshippingFrom(1234); // WHERE freeshipping_from = 1234 + * $query->filterByFreeshippingFrom(array(12, 34)); // WHERE freeshipping_from IN (12, 34) + * $query->filterByFreeshippingFrom(array('min' => 12)); // WHERE freeshipping_from > 12 + * + * + * @param mixed $freeshippingFrom The value to use as filter. + * Use scalar values for equality. + * Use array values for in_array() equivalent. + * Use associative array('min' => $minValue, 'max' => $maxValue) for intervals. + * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL + * + * @return ChildColissimoPickupPointFreeshippingQuery The current query, for fluid interface + */ + public function filterByFreeshippingFrom($freeshippingFrom = null, $comparison = null) + { + if (is_array($freeshippingFrom)) { + $useMinMax = false; + if (isset($freeshippingFrom['min'])) { + $this->addUsingAlias(ColissimoPickupPointFreeshippingTableMap::FREESHIPPING_FROM, $freeshippingFrom['min'], Criteria::GREATER_EQUAL); + $useMinMax = true; + } + if (isset($freeshippingFrom['max'])) { + $this->addUsingAlias(ColissimoPickupPointFreeshippingTableMap::FREESHIPPING_FROM, $freeshippingFrom['max'], Criteria::LESS_EQUAL); + $useMinMax = true; + } + if ($useMinMax) { + return $this; + } + if (null === $comparison) { + $comparison = Criteria::IN; + } + } + + return $this->addUsingAlias(ColissimoPickupPointFreeshippingTableMap::FREESHIPPING_FROM, $freeshippingFrom, $comparison); + } + + /** + * Exclude object from result + * + * @param ChildColissimoPickupPointFreeshipping $colissimoPickupPointFreeshipping Object to remove from the list of results + * + * @return ChildColissimoPickupPointFreeshippingQuery The current query, for fluid interface + */ + public function prune($colissimoPickupPointFreeshipping = null) + { + if ($colissimoPickupPointFreeshipping) { + $this->addUsingAlias(ColissimoPickupPointFreeshippingTableMap::ID, $colissimoPickupPointFreeshipping->getId(), Criteria::NOT_EQUAL); + } + + return $this; + } + + /** + * Deletes all rows from the colissimo_pickup_point_freeshipping table. + * + * @param ConnectionInterface $con the connection to use + * @return int The number of affected rows (if supported by underlying database driver). + */ + public function doDeleteAll(ConnectionInterface $con = null) + { + if (null === $con) { + $con = Propel::getServiceContainer()->getWriteConnection(ColissimoPickupPointFreeshippingTableMap::DATABASE_NAME); + } + $affectedRows = 0; // initialize var to track total num of affected rows + try { + // use transaction because $criteria could contain info + // for more than one table or we could emulating ON DELETE CASCADE, etc. + $con->beginTransaction(); + $affectedRows += parent::doDeleteAll($con); + // Because this db requires some delete cascade/set null emulation, we have to + // clear the cached instance *after* the emulation has happened (since + // instances get re-added by the select statement contained therein). + ColissimoPickupPointFreeshippingTableMap::clearInstancePool(); + ColissimoPickupPointFreeshippingTableMap::clearRelatedInstancePool(); + + $con->commit(); + } catch (PropelException $e) { + $con->rollBack(); + throw $e; + } + + return $affectedRows; + } + + /** + * Performs a DELETE on the database, given a ChildColissimoPickupPointFreeshipping or Criteria object OR a primary key value. + * + * @param mixed $values Criteria or ChildColissimoPickupPointFreeshipping object or primary key or array of primary keys + * which is used to create the DELETE statement + * @param ConnectionInterface $con the connection to use + * @return int The number of affected rows (if supported by underlying database driver). This includes CASCADE-related rows + * if supported by native driver or if emulated using Propel. + * @throws PropelException Any exceptions caught during processing will be + * rethrown wrapped into a PropelException. + */ + public function delete(ConnectionInterface $con = null) + { + if (null === $con) { + $con = Propel::getServiceContainer()->getWriteConnection(ColissimoPickupPointFreeshippingTableMap::DATABASE_NAME); + } + + $criteria = $this; + + // Set the correct dbName + $criteria->setDbName(ColissimoPickupPointFreeshippingTableMap::DATABASE_NAME); + + $affectedRows = 0; // initialize var to track total num of affected rows + + try { + // use transaction because $criteria could contain info + // for more than one table or we could emulating ON DELETE CASCADE, etc. + $con->beginTransaction(); + + + ColissimoPickupPointFreeshippingTableMap::removeInstanceFromPool($criteria); + + $affectedRows += ModelCriteria::delete($con); + ColissimoPickupPointFreeshippingTableMap::clearRelatedInstancePool(); + $con->commit(); + + return $affectedRows; + } catch (PropelException $e) { + $con->rollBack(); + throw $e; + } + } + +} // ColissimoPickupPointFreeshippingQuery diff --git a/local/modules/ColissimoPickupPoint/Model/Base/ColissimoPickupPointPriceSlices.php b/local/modules/ColissimoPickupPoint/Model/Base/ColissimoPickupPointPriceSlices.php new file mode 100644 index 00000000..e308c628 --- /dev/null +++ b/local/modules/ColissimoPickupPoint/Model/Base/ColissimoPickupPointPriceSlices.php @@ -0,0 +1,1427 @@ +modifiedColumns; + } + + /** + * Has specified column been modified? + * + * @param string $col column fully qualified name (TableMap::TYPE_COLNAME), e.g. Book::AUTHOR_ID + * @return boolean True if $col has been modified. + */ + public function isColumnModified($col) + { + return $this->modifiedColumns && isset($this->modifiedColumns[$col]); + } + + /** + * Get the columns that have been modified in this object. + * @return array A unique list of the modified column names for this object. + */ + public function getModifiedColumns() + { + return $this->modifiedColumns ? array_keys($this->modifiedColumns) : []; + } + + /** + * Returns whether the object has ever been saved. This will + * be false, if the object was retrieved from storage or was created + * and then saved. + * + * @return boolean true, if the object has never been persisted. + */ + public function isNew() + { + return $this->new; + } + + /** + * Setter for the isNew attribute. This method will be called + * by Propel-generated children and objects. + * + * @param boolean $b the state of the object. + */ + public function setNew($b) + { + $this->new = (Boolean) $b; + } + + /** + * Whether this object has been deleted. + * @return boolean The deleted state of this object. + */ + public function isDeleted() + { + return $this->deleted; + } + + /** + * Specify whether this object has been deleted. + * @param boolean $b The deleted state of this object. + * @return void + */ + public function setDeleted($b) + { + $this->deleted = (Boolean) $b; + } + + /** + * Sets the modified state for the object to be false. + * @param string $col If supplied, only the specified column is reset. + * @return void + */ + public function resetModified($col = null) + { + if (null !== $col) { + if (isset($this->modifiedColumns[$col])) { + unset($this->modifiedColumns[$col]); + } + } else { + $this->modifiedColumns = array(); + } + } + + /** + * Compares this with another ColissimoPickupPointPriceSlices instance. If + * obj is an instance of ColissimoPickupPointPriceSlices, delegates to + * equals(ColissimoPickupPointPriceSlices). Otherwise, returns false. + * + * @param mixed $obj The object to compare to. + * @return boolean Whether equal to the object specified. + */ + public function equals($obj) + { + $thisclazz = get_class($this); + if (!is_object($obj) || !($obj instanceof $thisclazz)) { + return false; + } + + if ($this === $obj) { + return true; + } + + if (null === $this->getPrimaryKey() + || null === $obj->getPrimaryKey()) { + return false; + } + + return $this->getPrimaryKey() === $obj->getPrimaryKey(); + } + + /** + * If the primary key is not null, return the hashcode of the + * primary key. Otherwise, return the hash code of the object. + * + * @return int Hashcode + */ + public function hashCode() + { + if (null !== $this->getPrimaryKey()) { + return crc32(serialize($this->getPrimaryKey())); + } + + return crc32(serialize(clone $this)); + } + + /** + * Get the associative array of the virtual columns in this object + * + * @return array + */ + public function getVirtualColumns() + { + return $this->virtualColumns; + } + + /** + * Checks the existence of a virtual column in this object + * + * @param string $name The virtual column name + * @return boolean + */ + public function hasVirtualColumn($name) + { + return array_key_exists($name, $this->virtualColumns); + } + + /** + * Get the value of a virtual column in this object + * + * @param string $name The virtual column name + * @return mixed + * + * @throws PropelException + */ + public function getVirtualColumn($name) + { + if (!$this->hasVirtualColumn($name)) { + throw new PropelException(sprintf('Cannot get value of inexistent virtual column %s.', $name)); + } + + return $this->virtualColumns[$name]; + } + + /** + * Set the value of a virtual column in this object + * + * @param string $name The virtual column name + * @param mixed $value The value to give to the virtual column + * + * @return ColissimoPickupPointPriceSlices The current object, for fluid interface + */ + public function setVirtualColumn($name, $value) + { + $this->virtualColumns[$name] = $value; + + return $this; + } + + /** + * Logs a message using Propel::log(). + * + * @param string $msg + * @param int $priority One of the Propel::LOG_* logging levels + * @return boolean + */ + protected function log($msg, $priority = Propel::LOG_INFO) + { + return Propel::log(get_class($this) . ': ' . $msg, $priority); + } + + /** + * Populate the current object from a string, using a given parser format + * + * $book = new Book(); + * $book->importFrom('JSON', '{"Id":9012,"Title":"Don Juan","ISBN":"0140422161","Price":12.99,"PublisherId":1234,"AuthorId":5678}'); + * + * + * @param mixed $parser A AbstractParser instance, + * or a format name ('XML', 'YAML', 'JSON', 'CSV') + * @param string $data The source data to import from + * + * @return ColissimoPickupPointPriceSlices The current object, for fluid interface + */ + public function importFrom($parser, $data) + { + if (!$parser instanceof AbstractParser) { + $parser = AbstractParser::getParser($parser); + } + + $this->fromArray($parser->toArray($data), TableMap::TYPE_PHPNAME); + + return $this; + } + + /** + * Export the current object properties to a string, using a given parser format + * + * $book = BookQuery::create()->findPk(9012); + * echo $book->exportTo('JSON'); + * => {"Id":9012,"Title":"Don Juan","ISBN":"0140422161","Price":12.99,"PublisherId":1234,"AuthorId":5678}'); + * + * + * @param mixed $parser A AbstractParser instance, or a format name ('XML', 'YAML', 'JSON', 'CSV') + * @param boolean $includeLazyLoadColumns (optional) Whether to include lazy load(ed) columns. Defaults to TRUE. + * @return string The exported data + */ + public function exportTo($parser, $includeLazyLoadColumns = true) + { + if (!$parser instanceof AbstractParser) { + $parser = AbstractParser::getParser($parser); + } + + return $parser->fromArray($this->toArray(TableMap::TYPE_PHPNAME, $includeLazyLoadColumns, array(), true)); + } + + /** + * Clean up internal collections prior to serializing + * Avoids recursive loops that turn into segmentation faults when serializing + */ + public function __sleep() + { + $this->clearAllReferences(); + + return array_keys(get_object_vars($this)); + } + + /** + * Get the [id] column value. + * + * @return int + */ + public function getId() + { + + return $this->id; + } + + /** + * Get the [area_id] column value. + * + * @return int + */ + public function getAreaId() + { + + return $this->area_id; + } + + /** + * Get the [weight_max] column value. + * + * @return double + */ + public function getWeightMax() + { + + return $this->weight_max; + } + + /** + * Get the [price_max] column value. + * + * @return double + */ + public function getPriceMax() + { + + return $this->price_max; + } + + /** + * Get the [franco_min_price] column value. + * + * @return double + */ + public function getFrancoMinPrice() + { + + return $this->franco_min_price; + } + + /** + * Get the [price] column value. + * + * @return double + */ + public function getPrice() + { + + return $this->price; + } + + /** + * Set the value of [id] column. + * + * @param int $v new value + * @return \ColissimoPickupPoint\Model\ColissimoPickupPointPriceSlices The current object (for fluent API support) + */ + public function setId($v) + { + if ($v !== null) { + $v = (int) $v; + } + + if ($this->id !== $v) { + $this->id = $v; + $this->modifiedColumns[ColissimoPickupPointPriceSlicesTableMap::ID] = true; + } + + + return $this; + } // setId() + + /** + * Set the value of [area_id] column. + * + * @param int $v new value + * @return \ColissimoPickupPoint\Model\ColissimoPickupPointPriceSlices The current object (for fluent API support) + */ + public function setAreaId($v) + { + if ($v !== null) { + $v = (int) $v; + } + + if ($this->area_id !== $v) { + $this->area_id = $v; + $this->modifiedColumns[ColissimoPickupPointPriceSlicesTableMap::AREA_ID] = true; + } + + if ($this->aArea !== null && $this->aArea->getId() !== $v) { + $this->aArea = null; + } + + + return $this; + } // setAreaId() + + /** + * Set the value of [weight_max] column. + * + * @param double $v new value + * @return \ColissimoPickupPoint\Model\ColissimoPickupPointPriceSlices The current object (for fluent API support) + */ + public function setWeightMax($v) + { + if ($v !== null) { + $v = (double) $v; + } + + if ($this->weight_max !== $v) { + $this->weight_max = $v; + $this->modifiedColumns[ColissimoPickupPointPriceSlicesTableMap::WEIGHT_MAX] = true; + } + + + return $this; + } // setWeightMax() + + /** + * Set the value of [price_max] column. + * + * @param double $v new value + * @return \ColissimoPickupPoint\Model\ColissimoPickupPointPriceSlices The current object (for fluent API support) + */ + public function setPriceMax($v) + { + if ($v !== null) { + $v = (double) $v; + } + + if ($this->price_max !== $v) { + $this->price_max = $v; + $this->modifiedColumns[ColissimoPickupPointPriceSlicesTableMap::PRICE_MAX] = true; + } + + + return $this; + } // setPriceMax() + + /** + * Set the value of [franco_min_price] column. + * + * @param double $v new value + * @return \ColissimoPickupPoint\Model\ColissimoPickupPointPriceSlices The current object (for fluent API support) + */ + public function setFrancoMinPrice($v) + { + if ($v !== null) { + $v = (double) $v; + } + + if ($this->franco_min_price !== $v) { + $this->franco_min_price = $v; + $this->modifiedColumns[ColissimoPickupPointPriceSlicesTableMap::FRANCO_MIN_PRICE] = true; + } + + + return $this; + } // setFrancoMinPrice() + + /** + * Set the value of [price] column. + * + * @param double $v new value + * @return \ColissimoPickupPoint\Model\ColissimoPickupPointPriceSlices The current object (for fluent API support) + */ + public function setPrice($v) + { + if ($v !== null) { + $v = (double) $v; + } + + if ($this->price !== $v) { + $this->price = $v; + $this->modifiedColumns[ColissimoPickupPointPriceSlicesTableMap::PRICE] = true; + } + + + return $this; + } // setPrice() + + /** + * Indicates whether the columns in this object are only set to default values. + * + * This method can be used in conjunction with isModified() to indicate whether an object is both + * modified _and_ has some values set which are non-default. + * + * @return boolean Whether the columns in this object are only been set with default values. + */ + public function hasOnlyDefaultValues() + { + // otherwise, everything was equal, so return TRUE + return true; + } // hasOnlyDefaultValues() + + /** + * Hydrates (populates) the object variables with values from the database resultset. + * + * An offset (0-based "start column") is specified so that objects can be hydrated + * with a subset of the columns in the resultset rows. This is needed, for example, + * for results of JOIN queries where the resultset row includes columns from two or + * more tables. + * + * @param array $row The row returned by DataFetcher->fetch(). + * @param int $startcol 0-based offset column which indicates which restultset column to start with. + * @param boolean $rehydrate Whether this object is being re-hydrated from the database. + * @param string $indexType The index type of $row. Mostly DataFetcher->getIndexType(). + One of the class type constants TableMap::TYPE_PHPNAME, TableMap::TYPE_STUDLYPHPNAME + * TableMap::TYPE_COLNAME, TableMap::TYPE_FIELDNAME, TableMap::TYPE_NUM. + * + * @return int next starting column + * @throws PropelException - Any caught Exception will be rewrapped as a PropelException. + */ + public function hydrate($row, $startcol = 0, $rehydrate = false, $indexType = TableMap::TYPE_NUM) + { + try { + + + $col = $row[TableMap::TYPE_NUM == $indexType ? 0 + $startcol : ColissimoPickupPointPriceSlicesTableMap::translateFieldName('Id', TableMap::TYPE_PHPNAME, $indexType)]; + $this->id = (null !== $col) ? (int) $col : null; + + $col = $row[TableMap::TYPE_NUM == $indexType ? 1 + $startcol : ColissimoPickupPointPriceSlicesTableMap::translateFieldName('AreaId', TableMap::TYPE_PHPNAME, $indexType)]; + $this->area_id = (null !== $col) ? (int) $col : null; + + $col = $row[TableMap::TYPE_NUM == $indexType ? 2 + $startcol : ColissimoPickupPointPriceSlicesTableMap::translateFieldName('WeightMax', TableMap::TYPE_PHPNAME, $indexType)]; + $this->weight_max = (null !== $col) ? (double) $col : null; + + $col = $row[TableMap::TYPE_NUM == $indexType ? 3 + $startcol : ColissimoPickupPointPriceSlicesTableMap::translateFieldName('PriceMax', TableMap::TYPE_PHPNAME, $indexType)]; + $this->price_max = (null !== $col) ? (double) $col : null; + + $col = $row[TableMap::TYPE_NUM == $indexType ? 4 + $startcol : ColissimoPickupPointPriceSlicesTableMap::translateFieldName('FrancoMinPrice', TableMap::TYPE_PHPNAME, $indexType)]; + $this->franco_min_price = (null !== $col) ? (double) $col : null; + + $col = $row[TableMap::TYPE_NUM == $indexType ? 5 + $startcol : ColissimoPickupPointPriceSlicesTableMap::translateFieldName('Price', TableMap::TYPE_PHPNAME, $indexType)]; + $this->price = (null !== $col) ? (double) $col : null; + $this->resetModified(); + + $this->setNew(false); + + if ($rehydrate) { + $this->ensureConsistency(); + } + + return $startcol + 6; // 6 = ColissimoPickupPointPriceSlicesTableMap::NUM_HYDRATE_COLUMNS. + + } catch (Exception $e) { + throw new PropelException("Error populating \ColissimoPickupPoint\Model\ColissimoPickupPointPriceSlices object", 0, $e); + } + } + + /** + * Checks and repairs the internal consistency of the object. + * + * This method is executed after an already-instantiated object is re-hydrated + * from the database. It exists to check any foreign keys to make sure that + * the objects related to the current object are correct based on foreign key. + * + * You can override this method in the stub class, but you should always invoke + * the base method from the overridden method (i.e. parent::ensureConsistency()), + * in case your model changes. + * + * @throws PropelException + */ + public function ensureConsistency() + { + if ($this->aArea !== null && $this->area_id !== $this->aArea->getId()) { + $this->aArea = null; + } + } // ensureConsistency + + /** + * Reloads this object from datastore based on primary key and (optionally) resets all associated objects. + * + * This will only work if the object has been saved and has a valid primary key set. + * + * @param boolean $deep (optional) Whether to also de-associated any related objects. + * @param ConnectionInterface $con (optional) The ConnectionInterface connection to use. + * @return void + * @throws PropelException - if this object is deleted, unsaved or doesn't have pk match in db + */ + public function reload($deep = false, ConnectionInterface $con = null) + { + if ($this->isDeleted()) { + throw new PropelException("Cannot reload a deleted object."); + } + + if ($this->isNew()) { + throw new PropelException("Cannot reload an unsaved object."); + } + + if ($con === null) { + $con = Propel::getServiceContainer()->getReadConnection(ColissimoPickupPointPriceSlicesTableMap::DATABASE_NAME); + } + + // We don't need to alter the object instance pool; we're just modifying this instance + // already in the pool. + + $dataFetcher = ChildColissimoPickupPointPriceSlicesQuery::create(null, $this->buildPkeyCriteria())->setFormatter(ModelCriteria::FORMAT_STATEMENT)->find($con); + $row = $dataFetcher->fetch(); + $dataFetcher->close(); + if (!$row) { + throw new PropelException('Cannot find matching row in the database to reload object values.'); + } + $this->hydrate($row, 0, true, $dataFetcher->getIndexType()); // rehydrate + + if ($deep) { // also de-associate any related objects? + + $this->aArea = null; + } // if (deep) + } + + /** + * Removes this object from datastore and sets delete attribute. + * + * @param ConnectionInterface $con + * @return void + * @throws PropelException + * @see ColissimoPickupPointPriceSlices::setDeleted() + * @see ColissimoPickupPointPriceSlices::isDeleted() + */ + public function delete(ConnectionInterface $con = null) + { + if ($this->isDeleted()) { + throw new PropelException("This object has already been deleted."); + } + + if ($con === null) { + $con = Propel::getServiceContainer()->getWriteConnection(ColissimoPickupPointPriceSlicesTableMap::DATABASE_NAME); + } + + $con->beginTransaction(); + try { + $deleteQuery = ChildColissimoPickupPointPriceSlicesQuery::create() + ->filterByPrimaryKey($this->getPrimaryKey()); + $ret = $this->preDelete($con); + if ($ret) { + $deleteQuery->delete($con); + $this->postDelete($con); + $con->commit(); + $this->setDeleted(true); + } else { + $con->commit(); + } + } catch (Exception $e) { + $con->rollBack(); + throw $e; + } + } + + /** + * Persists this object to the database. + * + * If the object is new, it inserts it; otherwise an update is performed. + * All modified related objects will also be persisted in the doSave() + * method. This method wraps all precipitate database operations in a + * single transaction. + * + * @param ConnectionInterface $con + * @return int The number of rows affected by this insert/update and any referring fk objects' save() operations. + * @throws PropelException + * @see doSave() + */ + public function save(ConnectionInterface $con = null) + { + if ($this->isDeleted()) { + throw new PropelException("You cannot save an object that has been deleted."); + } + + if ($con === null) { + $con = Propel::getServiceContainer()->getWriteConnection(ColissimoPickupPointPriceSlicesTableMap::DATABASE_NAME); + } + + $con->beginTransaction(); + $isInsert = $this->isNew(); + try { + $ret = $this->preSave($con); + if ($isInsert) { + $ret = $ret && $this->preInsert($con); + } else { + $ret = $ret && $this->preUpdate($con); + } + if ($ret) { + $affectedRows = $this->doSave($con); + if ($isInsert) { + $this->postInsert($con); + } else { + $this->postUpdate($con); + } + $this->postSave($con); + ColissimoPickupPointPriceSlicesTableMap::addInstanceToPool($this); + } else { + $affectedRows = 0; + } + $con->commit(); + + return $affectedRows; + } catch (Exception $e) { + $con->rollBack(); + throw $e; + } + } + + /** + * Performs the work of inserting or updating the row in the database. + * + * If the object is new, it inserts it; otherwise an update is performed. + * All related objects are also updated in this method. + * + * @param ConnectionInterface $con + * @return int The number of rows affected by this insert/update and any referring fk objects' save() operations. + * @throws PropelException + * @see save() + */ + protected function doSave(ConnectionInterface $con) + { + $affectedRows = 0; // initialize var to track total num of affected rows + if (!$this->alreadyInSave) { + $this->alreadyInSave = true; + + // We call the save method on the following object(s) if they + // were passed to this object by their corresponding set + // method. This object relates to these object(s) by a + // foreign key reference. + + if ($this->aArea !== null) { + if ($this->aArea->isModified() || $this->aArea->isNew()) { + $affectedRows += $this->aArea->save($con); + } + $this->setArea($this->aArea); + } + + if ($this->isNew() || $this->isModified()) { + // persist changes + if ($this->isNew()) { + $this->doInsert($con); + } else { + $this->doUpdate($con); + } + $affectedRows += 1; + $this->resetModified(); + } + + $this->alreadyInSave = false; + + } + + return $affectedRows; + } // doSave() + + /** + * Insert the row in the database. + * + * @param ConnectionInterface $con + * + * @throws PropelException + * @see doSave() + */ + protected function doInsert(ConnectionInterface $con) + { + $modifiedColumns = array(); + $index = 0; + + $this->modifiedColumns[ColissimoPickupPointPriceSlicesTableMap::ID] = true; + if (null !== $this->id) { + throw new PropelException('Cannot insert a value for auto-increment primary key (' . ColissimoPickupPointPriceSlicesTableMap::ID . ')'); + } + + // check the columns in natural order for more readable SQL queries + if ($this->isColumnModified(ColissimoPickupPointPriceSlicesTableMap::ID)) { + $modifiedColumns[':p' . $index++] = 'ID'; + } + if ($this->isColumnModified(ColissimoPickupPointPriceSlicesTableMap::AREA_ID)) { + $modifiedColumns[':p' . $index++] = 'AREA_ID'; + } + if ($this->isColumnModified(ColissimoPickupPointPriceSlicesTableMap::WEIGHT_MAX)) { + $modifiedColumns[':p' . $index++] = 'WEIGHT_MAX'; + } + if ($this->isColumnModified(ColissimoPickupPointPriceSlicesTableMap::PRICE_MAX)) { + $modifiedColumns[':p' . $index++] = 'PRICE_MAX'; + } + if ($this->isColumnModified(ColissimoPickupPointPriceSlicesTableMap::FRANCO_MIN_PRICE)) { + $modifiedColumns[':p' . $index++] = 'FRANCO_MIN_PRICE'; + } + if ($this->isColumnModified(ColissimoPickupPointPriceSlicesTableMap::PRICE)) { + $modifiedColumns[':p' . $index++] = 'PRICE'; + } + + $sql = sprintf( + 'INSERT INTO colissimo_pickup_point_price_slices (%s) VALUES (%s)', + implode(', ', $modifiedColumns), + implode(', ', array_keys($modifiedColumns)) + ); + + try { + $stmt = $con->prepare($sql); + foreach ($modifiedColumns as $identifier => $columnName) { + switch ($columnName) { + case 'ID': + $stmt->bindValue($identifier, $this->id, PDO::PARAM_INT); + break; + case 'AREA_ID': + $stmt->bindValue($identifier, $this->area_id, PDO::PARAM_INT); + break; + case 'WEIGHT_MAX': + $stmt->bindValue($identifier, $this->weight_max, PDO::PARAM_STR); + break; + case 'PRICE_MAX': + $stmt->bindValue($identifier, $this->price_max, PDO::PARAM_STR); + break; + case 'FRANCO_MIN_PRICE': + $stmt->bindValue($identifier, $this->franco_min_price, PDO::PARAM_STR); + break; + case 'PRICE': + $stmt->bindValue($identifier, $this->price, PDO::PARAM_STR); + break; + } + } + $stmt->execute(); + } catch (Exception $e) { + Propel::log($e->getMessage(), Propel::LOG_ERR); + throw new PropelException(sprintf('Unable to execute INSERT statement [%s]', $sql), 0, $e); + } + + try { + $pk = $con->lastInsertId(); + } catch (Exception $e) { + throw new PropelException('Unable to get autoincrement id.', 0, $e); + } + $this->setId($pk); + + $this->setNew(false); + } + + /** + * Update the row in the database. + * + * @param ConnectionInterface $con + * + * @return Integer Number of updated rows + * @see doSave() + */ + protected function doUpdate(ConnectionInterface $con) + { + $selectCriteria = $this->buildPkeyCriteria(); + $valuesCriteria = $this->buildCriteria(); + + return $selectCriteria->doUpdate($valuesCriteria, $con); + } + + /** + * Retrieves a field from the object by name passed in as a string. + * + * @param string $name name + * @param string $type The type of fieldname the $name is of: + * one of the class type constants TableMap::TYPE_PHPNAME, TableMap::TYPE_STUDLYPHPNAME + * TableMap::TYPE_COLNAME, TableMap::TYPE_FIELDNAME, TableMap::TYPE_NUM. + * Defaults to TableMap::TYPE_PHPNAME. + * @return mixed Value of field. + */ + public function getByName($name, $type = TableMap::TYPE_PHPNAME) + { + $pos = ColissimoPickupPointPriceSlicesTableMap::translateFieldName($name, $type, TableMap::TYPE_NUM); + $field = $this->getByPosition($pos); + + return $field; + } + + /** + * Retrieves a field from the object by Position as specified in the xml schema. + * Zero-based. + * + * @param int $pos position in xml schema + * @return mixed Value of field at $pos + */ + public function getByPosition($pos) + { + switch ($pos) { + case 0: + return $this->getId(); + break; + case 1: + return $this->getAreaId(); + break; + case 2: + return $this->getWeightMax(); + break; + case 3: + return $this->getPriceMax(); + break; + case 4: + return $this->getFrancoMinPrice(); + break; + case 5: + return $this->getPrice(); + break; + default: + return null; + break; + } // switch() + } + + /** + * Exports the object as an array. + * + * You can specify the key type of the array by passing one of the class + * type constants. + * + * @param string $keyType (optional) One of the class type constants TableMap::TYPE_PHPNAME, TableMap::TYPE_STUDLYPHPNAME, + * TableMap::TYPE_COLNAME, TableMap::TYPE_FIELDNAME, TableMap::TYPE_NUM. + * Defaults to TableMap::TYPE_PHPNAME. + * @param boolean $includeLazyLoadColumns (optional) Whether to include lazy loaded columns. Defaults to TRUE. + * @param array $alreadyDumpedObjects List of objects to skip to avoid recursion + * @param boolean $includeForeignObjects (optional) Whether to include hydrated related objects. Default to FALSE. + * + * @return array an associative array containing the field names (as keys) and field values + */ + public function toArray($keyType = TableMap::TYPE_PHPNAME, $includeLazyLoadColumns = true, $alreadyDumpedObjects = array(), $includeForeignObjects = false) + { + if (isset($alreadyDumpedObjects['ColissimoPickupPointPriceSlices'][$this->getPrimaryKey()])) { + return '*RECURSION*'; + } + $alreadyDumpedObjects['ColissimoPickupPointPriceSlices'][$this->getPrimaryKey()] = true; + $keys = ColissimoPickupPointPriceSlicesTableMap::getFieldNames($keyType); + $result = array( + $keys[0] => $this->getId(), + $keys[1] => $this->getAreaId(), + $keys[2] => $this->getWeightMax(), + $keys[3] => $this->getPriceMax(), + $keys[4] => $this->getFrancoMinPrice(), + $keys[5] => $this->getPrice(), + ); + $virtualColumns = $this->virtualColumns; + foreach ($virtualColumns as $key => $virtualColumn) { + $result[$key] = $virtualColumn; + } + + if ($includeForeignObjects) { + if (null !== $this->aArea) { + $result['Area'] = $this->aArea->toArray($keyType, $includeLazyLoadColumns, $alreadyDumpedObjects, true); + } + } + + return $result; + } + + /** + * Sets a field from the object by name passed in as a string. + * + * @param string $name + * @param mixed $value field value + * @param string $type The type of fieldname the $name is of: + * one of the class type constants TableMap::TYPE_PHPNAME, TableMap::TYPE_STUDLYPHPNAME + * TableMap::TYPE_COLNAME, TableMap::TYPE_FIELDNAME, TableMap::TYPE_NUM. + * Defaults to TableMap::TYPE_PHPNAME. + * @return void + */ + public function setByName($name, $value, $type = TableMap::TYPE_PHPNAME) + { + $pos = ColissimoPickupPointPriceSlicesTableMap::translateFieldName($name, $type, TableMap::TYPE_NUM); + + return $this->setByPosition($pos, $value); + } + + /** + * Sets a field from the object by Position as specified in the xml schema. + * Zero-based. + * + * @param int $pos position in xml schema + * @param mixed $value field value + * @return void + */ + public function setByPosition($pos, $value) + { + switch ($pos) { + case 0: + $this->setId($value); + break; + case 1: + $this->setAreaId($value); + break; + case 2: + $this->setWeightMax($value); + break; + case 3: + $this->setPriceMax($value); + break; + case 4: + $this->setFrancoMinPrice($value); + break; + case 5: + $this->setPrice($value); + break; + } // switch() + } + + /** + * Populates the object using an array. + * + * This is particularly useful when populating an object from one of the + * request arrays (e.g. $_POST). This method goes through the column + * names, checking to see whether a matching key exists in populated + * array. If so the setByName() method is called for that column. + * + * You can specify the key type of the array by additionally passing one + * of the class type constants TableMap::TYPE_PHPNAME, TableMap::TYPE_STUDLYPHPNAME, + * TableMap::TYPE_COLNAME, TableMap::TYPE_FIELDNAME, TableMap::TYPE_NUM. + * The default key type is the column's TableMap::TYPE_PHPNAME. + * + * @param array $arr An array to populate the object from. + * @param string $keyType The type of keys the array uses. + * @return void + */ + public function fromArray($arr, $keyType = TableMap::TYPE_PHPNAME) + { + $keys = ColissimoPickupPointPriceSlicesTableMap::getFieldNames($keyType); + + if (array_key_exists($keys[0], $arr)) $this->setId($arr[$keys[0]]); + if (array_key_exists($keys[1], $arr)) $this->setAreaId($arr[$keys[1]]); + if (array_key_exists($keys[2], $arr)) $this->setWeightMax($arr[$keys[2]]); + if (array_key_exists($keys[3], $arr)) $this->setPriceMax($arr[$keys[3]]); + if (array_key_exists($keys[4], $arr)) $this->setFrancoMinPrice($arr[$keys[4]]); + if (array_key_exists($keys[5], $arr)) $this->setPrice($arr[$keys[5]]); + } + + /** + * Build a Criteria object containing the values of all modified columns in this object. + * + * @return Criteria The Criteria object containing all modified values. + */ + public function buildCriteria() + { + $criteria = new Criteria(ColissimoPickupPointPriceSlicesTableMap::DATABASE_NAME); + + if ($this->isColumnModified(ColissimoPickupPointPriceSlicesTableMap::ID)) $criteria->add(ColissimoPickupPointPriceSlicesTableMap::ID, $this->id); + if ($this->isColumnModified(ColissimoPickupPointPriceSlicesTableMap::AREA_ID)) $criteria->add(ColissimoPickupPointPriceSlicesTableMap::AREA_ID, $this->area_id); + if ($this->isColumnModified(ColissimoPickupPointPriceSlicesTableMap::WEIGHT_MAX)) $criteria->add(ColissimoPickupPointPriceSlicesTableMap::WEIGHT_MAX, $this->weight_max); + if ($this->isColumnModified(ColissimoPickupPointPriceSlicesTableMap::PRICE_MAX)) $criteria->add(ColissimoPickupPointPriceSlicesTableMap::PRICE_MAX, $this->price_max); + if ($this->isColumnModified(ColissimoPickupPointPriceSlicesTableMap::FRANCO_MIN_PRICE)) $criteria->add(ColissimoPickupPointPriceSlicesTableMap::FRANCO_MIN_PRICE, $this->franco_min_price); + if ($this->isColumnModified(ColissimoPickupPointPriceSlicesTableMap::PRICE)) $criteria->add(ColissimoPickupPointPriceSlicesTableMap::PRICE, $this->price); + + return $criteria; + } + + /** + * Builds a Criteria object containing the primary key for this object. + * + * Unlike buildCriteria() this method includes the primary key values regardless + * of whether or not they have been modified. + * + * @return Criteria The Criteria object containing value(s) for primary key(s). + */ + public function buildPkeyCriteria() + { + $criteria = new Criteria(ColissimoPickupPointPriceSlicesTableMap::DATABASE_NAME); + $criteria->add(ColissimoPickupPointPriceSlicesTableMap::ID, $this->id); + + return $criteria; + } + + /** + * Returns the primary key for this object (row). + * @return int + */ + public function getPrimaryKey() + { + return $this->getId(); + } + + /** + * Generic method to set the primary key (id column). + * + * @param int $key Primary key. + * @return void + */ + public function setPrimaryKey($key) + { + $this->setId($key); + } + + /** + * Returns true if the primary key for this object is null. + * @return boolean + */ + public function isPrimaryKeyNull() + { + + return null === $this->getId(); + } + + /** + * Sets contents of passed object to values from current object. + * + * If desired, this method can also make copies of all associated (fkey referrers) + * objects. + * + * @param object $copyObj An object of \ColissimoPickupPoint\Model\ColissimoPickupPointPriceSlices (or compatible) type. + * @param boolean $deepCopy Whether to also copy all rows that refer (by fkey) to the current row. + * @param boolean $makeNew Whether to reset autoincrement PKs and make the object new. + * @throws PropelException + */ + public function copyInto($copyObj, $deepCopy = false, $makeNew = true) + { + $copyObj->setAreaId($this->getAreaId()); + $copyObj->setWeightMax($this->getWeightMax()); + $copyObj->setPriceMax($this->getPriceMax()); + $copyObj->setFrancoMinPrice($this->getFrancoMinPrice()); + $copyObj->setPrice($this->getPrice()); + if ($makeNew) { + $copyObj->setNew(true); + $copyObj->setId(NULL); // this is a auto-increment column, so set to default value + } + } + + /** + * Makes a copy of this object that will be inserted as a new row in table when saved. + * It creates a new object filling in the simple attributes, but skipping any primary + * keys that are defined for the table. + * + * If desired, this method can also make copies of all associated (fkey referrers) + * objects. + * + * @param boolean $deepCopy Whether to also copy all rows that refer (by fkey) to the current row. + * @return \ColissimoPickupPoint\Model\ColissimoPickupPointPriceSlices Clone of current object. + * @throws PropelException + */ + public function copy($deepCopy = false) + { + // we use get_class(), because this might be a subclass + $clazz = get_class($this); + $copyObj = new $clazz(); + $this->copyInto($copyObj, $deepCopy); + + return $copyObj; + } + + /** + * Declares an association between this object and a ChildArea object. + * + * @param ChildArea $v + * @return \ColissimoPickupPoint\Model\ColissimoPickupPointPriceSlices The current object (for fluent API support) + * @throws PropelException + */ + public function setArea(ChildArea $v = null) + { + if ($v === null) { + $this->setAreaId(NULL); + } else { + $this->setAreaId($v->getId()); + } + + $this->aArea = $v; + + // Add binding for other direction of this n:n relationship. + // If this object has already been added to the ChildArea object, it will not be re-added. + if ($v !== null) { + $v->addColissimoPickupPointPriceSlices($this); + } + + + return $this; + } + + + /** + * Get the associated ChildArea object + * + * @param ConnectionInterface $con Optional Connection object. + * @return ChildArea The associated ChildArea object. + * @throws PropelException + */ + public function getArea(ConnectionInterface $con = null) + { + if ($this->aArea === null && ($this->area_id !== null)) { + $this->aArea = AreaQuery::create()->findPk($this->area_id, $con); + /* The following can be used additionally to + guarantee the related object contains a reference + to this object. This level of coupling may, however, be + undesirable since it could result in an only partially populated collection + in the referenced object. + $this->aArea->addColissimoPickupPointPriceSlicess($this); + */ + } + + return $this->aArea; + } + + /** + * Clears the current object and sets all attributes to their default values + */ + public function clear() + { + $this->id = null; + $this->area_id = null; + $this->weight_max = null; + $this->price_max = null; + $this->franco_min_price = null; + $this->price = null; + $this->alreadyInSave = false; + $this->clearAllReferences(); + $this->resetModified(); + $this->setNew(true); + $this->setDeleted(false); + } + + /** + * Resets all references to other model objects or collections of model objects. + * + * This method is a user-space workaround for PHP's inability to garbage collect + * objects with circular references (even in PHP 5.3). This is currently necessary + * when using Propel in certain daemon or large-volume/high-memory operations. + * + * @param boolean $deep Whether to also clear the references on all referrer objects. + */ + public function clearAllReferences($deep = false) + { + if ($deep) { + } // if ($deep) + + $this->aArea = null; + } + + /** + * Return the string representation of this object + * + * @return string + */ + public function __toString() + { + return (string) $this->exportTo(ColissimoPickupPointPriceSlicesTableMap::DEFAULT_STRING_FORMAT); + } + + /** + * Code to be run before persisting the object + * @param ConnectionInterface $con + * @return boolean + */ + public function preSave(ConnectionInterface $con = null) + { + return true; + } + + /** + * Code to be run after persisting the object + * @param ConnectionInterface $con + */ + public function postSave(ConnectionInterface $con = null) + { + + } + + /** + * Code to be run before inserting to database + * @param ConnectionInterface $con + * @return boolean + */ + public function preInsert(ConnectionInterface $con = null) + { + return true; + } + + /** + * Code to be run after inserting to database + * @param ConnectionInterface $con + */ + public function postInsert(ConnectionInterface $con = null) + { + + } + + /** + * Code to be run before updating the object in database + * @param ConnectionInterface $con + * @return boolean + */ + public function preUpdate(ConnectionInterface $con = null) + { + return true; + } + + /** + * Code to be run after updating the object in database + * @param ConnectionInterface $con + */ + public function postUpdate(ConnectionInterface $con = null) + { + + } + + /** + * Code to be run before deleting the object in database + * @param ConnectionInterface $con + * @return boolean + */ + public function preDelete(ConnectionInterface $con = null) + { + return true; + } + + /** + * Code to be run after deleting the object in database + * @param ConnectionInterface $con + */ + public function postDelete(ConnectionInterface $con = null) + { + + } + + + /** + * Derived method to catches calls to undefined methods. + * + * Provides magic import/export method support (fromXML()/toXML(), fromYAML()/toYAML(), etc.). + * Allows to define default __call() behavior if you overwrite __call() + * + * @param string $name + * @param mixed $params + * + * @return array|string + */ + public function __call($name, $params) + { + if (0 === strpos($name, 'get')) { + $virtualColumn = substr($name, 3); + if ($this->hasVirtualColumn($virtualColumn)) { + return $this->getVirtualColumn($virtualColumn); + } + + $virtualColumn = lcfirst($virtualColumn); + if ($this->hasVirtualColumn($virtualColumn)) { + return $this->getVirtualColumn($virtualColumn); + } + } + + if (0 === strpos($name, 'from')) { + $format = substr($name, 4); + + return $this->importFrom($format, reset($params)); + } + + if (0 === strpos($name, 'to')) { + $format = substr($name, 2); + $includeLazyLoadColumns = isset($params[0]) ? $params[0] : true; + + return $this->exportTo($format, $includeLazyLoadColumns); + } + + throw new BadMethodCallException(sprintf('Call to undefined method: %s.', $name)); + } + +} diff --git a/local/modules/ColissimoPickupPoint/Model/Base/ColissimoPickupPointPriceSlicesQuery.php b/local/modules/ColissimoPickupPoint/Model/Base/ColissimoPickupPointPriceSlicesQuery.php new file mode 100644 index 00000000..ded790ea --- /dev/null +++ b/local/modules/ColissimoPickupPoint/Model/Base/ColissimoPickupPointPriceSlicesQuery.php @@ -0,0 +1,654 @@ +setModelAlias($modelAlias); + } + if ($criteria instanceof Criteria) { + $query->mergeWith($criteria); + } + + return $query; + } + + /** + * Find object by primary key. + * Propel uses the instance pool to skip the database if the object exists. + * Go fast if the query is untouched. + * + * + * $obj = $c->findPk(12, $con); + * + * + * @param mixed $key Primary key to use for the query + * @param ConnectionInterface $con an optional connection object + * + * @return ChildColissimoPickupPointPriceSlices|array|mixed the result, formatted by the current formatter + */ + public function findPk($key, $con = null) + { + if ($key === null) { + return null; + } + if ((null !== ($obj = ColissimoPickupPointPriceSlicesTableMap::getInstanceFromPool((string) $key))) && !$this->formatter) { + // the object is already in the instance pool + return $obj; + } + if ($con === null) { + $con = Propel::getServiceContainer()->getReadConnection(ColissimoPickupPointPriceSlicesTableMap::DATABASE_NAME); + } + $this->basePreSelect($con); + if ($this->formatter || $this->modelAlias || $this->with || $this->select + || $this->selectColumns || $this->asColumns || $this->selectModifiers + || $this->map || $this->having || $this->joins) { + return $this->findPkComplex($key, $con); + } else { + return $this->findPkSimple($key, $con); + } + } + + /** + * Find object by primary key using raw SQL to go fast. + * Bypass doSelect() and the object formatter by using generated code. + * + * @param mixed $key Primary key to use for the query + * @param ConnectionInterface $con A connection object + * + * @return ChildColissimoPickupPointPriceSlices A model object, or null if the key is not found + */ + protected function findPkSimple($key, $con) + { + $sql = 'SELECT ID, AREA_ID, WEIGHT_MAX, PRICE_MAX, FRANCO_MIN_PRICE, PRICE FROM colissimo_pickup_point_price_slices WHERE ID = :p0'; + try { + $stmt = $con->prepare($sql); + $stmt->bindValue(':p0', $key, PDO::PARAM_INT); + $stmt->execute(); + } catch (Exception $e) { + Propel::log($e->getMessage(), Propel::LOG_ERR); + throw new PropelException(sprintf('Unable to execute SELECT statement [%s]', $sql), 0, $e); + } + $obj = null; + if ($row = $stmt->fetch(\PDO::FETCH_NUM)) { + $obj = new ChildColissimoPickupPointPriceSlices(); + $obj->hydrate($row); + ColissimoPickupPointPriceSlicesTableMap::addInstanceToPool($obj, (string) $key); + } + $stmt->closeCursor(); + + return $obj; + } + + /** + * Find object by primary key. + * + * @param mixed $key Primary key to use for the query + * @param ConnectionInterface $con A connection object + * + * @return ChildColissimoPickupPointPriceSlices|array|mixed the result, formatted by the current formatter + */ + protected function findPkComplex($key, $con) + { + // As the query uses a PK condition, no limit(1) is necessary. + $criteria = $this->isKeepQuery() ? clone $this : $this; + $dataFetcher = $criteria + ->filterByPrimaryKey($key) + ->doSelect($con); + + return $criteria->getFormatter()->init($criteria)->formatOne($dataFetcher); + } + + /** + * Find objects by primary key + * + * $objs = $c->findPks(array(12, 56, 832), $con); + * + * @param array $keys Primary keys to use for the query + * @param ConnectionInterface $con an optional connection object + * + * @return ObjectCollection|array|mixed the list of results, formatted by the current formatter + */ + public function findPks($keys, $con = null) + { + if (null === $con) { + $con = Propel::getServiceContainer()->getReadConnection($this->getDbName()); + } + $this->basePreSelect($con); + $criteria = $this->isKeepQuery() ? clone $this : $this; + $dataFetcher = $criteria + ->filterByPrimaryKeys($keys) + ->doSelect($con); + + return $criteria->getFormatter()->init($criteria)->format($dataFetcher); + } + + /** + * Filter the query by primary key + * + * @param mixed $key Primary key to use for the query + * + * @return ChildColissimoPickupPointPriceSlicesQuery The current query, for fluid interface + */ + public function filterByPrimaryKey($key) + { + + return $this->addUsingAlias(ColissimoPickupPointPriceSlicesTableMap::ID, $key, Criteria::EQUAL); + } + + /** + * Filter the query by a list of primary keys + * + * @param array $keys The list of primary key to use for the query + * + * @return ChildColissimoPickupPointPriceSlicesQuery The current query, for fluid interface + */ + public function filterByPrimaryKeys($keys) + { + + return $this->addUsingAlias(ColissimoPickupPointPriceSlicesTableMap::ID, $keys, Criteria::IN); + } + + /** + * Filter the query on the id column + * + * Example usage: + * + * $query->filterById(1234); // WHERE id = 1234 + * $query->filterById(array(12, 34)); // WHERE id IN (12, 34) + * $query->filterById(array('min' => 12)); // WHERE id > 12 + * + * + * @param mixed $id The value to use as filter. + * Use scalar values for equality. + * Use array values for in_array() equivalent. + * Use associative array('min' => $minValue, 'max' => $maxValue) for intervals. + * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL + * + * @return ChildColissimoPickupPointPriceSlicesQuery The current query, for fluid interface + */ + public function filterById($id = null, $comparison = null) + { + if (is_array($id)) { + $useMinMax = false; + if (isset($id['min'])) { + $this->addUsingAlias(ColissimoPickupPointPriceSlicesTableMap::ID, $id['min'], Criteria::GREATER_EQUAL); + $useMinMax = true; + } + if (isset($id['max'])) { + $this->addUsingAlias(ColissimoPickupPointPriceSlicesTableMap::ID, $id['max'], Criteria::LESS_EQUAL); + $useMinMax = true; + } + if ($useMinMax) { + return $this; + } + if (null === $comparison) { + $comparison = Criteria::IN; + } + } + + return $this->addUsingAlias(ColissimoPickupPointPriceSlicesTableMap::ID, $id, $comparison); + } + + /** + * Filter the query on the area_id column + * + * Example usage: + * + * $query->filterByAreaId(1234); // WHERE area_id = 1234 + * $query->filterByAreaId(array(12, 34)); // WHERE area_id IN (12, 34) + * $query->filterByAreaId(array('min' => 12)); // WHERE area_id > 12 + * + * + * @see filterByArea() + * + * @param mixed $areaId The value to use as filter. + * Use scalar values for equality. + * Use array values for in_array() equivalent. + * Use associative array('min' => $minValue, 'max' => $maxValue) for intervals. + * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL + * + * @return ChildColissimoPickupPointPriceSlicesQuery The current query, for fluid interface + */ + public function filterByAreaId($areaId = null, $comparison = null) + { + if (is_array($areaId)) { + $useMinMax = false; + if (isset($areaId['min'])) { + $this->addUsingAlias(ColissimoPickupPointPriceSlicesTableMap::AREA_ID, $areaId['min'], Criteria::GREATER_EQUAL); + $useMinMax = true; + } + if (isset($areaId['max'])) { + $this->addUsingAlias(ColissimoPickupPointPriceSlicesTableMap::AREA_ID, $areaId['max'], Criteria::LESS_EQUAL); + $useMinMax = true; + } + if ($useMinMax) { + return $this; + } + if (null === $comparison) { + $comparison = Criteria::IN; + } + } + + return $this->addUsingAlias(ColissimoPickupPointPriceSlicesTableMap::AREA_ID, $areaId, $comparison); + } + + /** + * Filter the query on the weight_max column + * + * Example usage: + * + * $query->filterByWeightMax(1234); // WHERE weight_max = 1234 + * $query->filterByWeightMax(array(12, 34)); // WHERE weight_max IN (12, 34) + * $query->filterByWeightMax(array('min' => 12)); // WHERE weight_max > 12 + * + * + * @param mixed $weightMax The value to use as filter. + * Use scalar values for equality. + * Use array values for in_array() equivalent. + * Use associative array('min' => $minValue, 'max' => $maxValue) for intervals. + * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL + * + * @return ChildColissimoPickupPointPriceSlicesQuery The current query, for fluid interface + */ + public function filterByWeightMax($weightMax = null, $comparison = null) + { + if (is_array($weightMax)) { + $useMinMax = false; + if (isset($weightMax['min'])) { + $this->addUsingAlias(ColissimoPickupPointPriceSlicesTableMap::WEIGHT_MAX, $weightMax['min'], Criteria::GREATER_EQUAL); + $useMinMax = true; + } + if (isset($weightMax['max'])) { + $this->addUsingAlias(ColissimoPickupPointPriceSlicesTableMap::WEIGHT_MAX, $weightMax['max'], Criteria::LESS_EQUAL); + $useMinMax = true; + } + if ($useMinMax) { + return $this; + } + if (null === $comparison) { + $comparison = Criteria::IN; + } + } + + return $this->addUsingAlias(ColissimoPickupPointPriceSlicesTableMap::WEIGHT_MAX, $weightMax, $comparison); + } + + /** + * Filter the query on the price_max column + * + * Example usage: + * + * $query->filterByPriceMax(1234); // WHERE price_max = 1234 + * $query->filterByPriceMax(array(12, 34)); // WHERE price_max IN (12, 34) + * $query->filterByPriceMax(array('min' => 12)); // WHERE price_max > 12 + * + * + * @param mixed $priceMax The value to use as filter. + * Use scalar values for equality. + * Use array values for in_array() equivalent. + * Use associative array('min' => $minValue, 'max' => $maxValue) for intervals. + * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL + * + * @return ChildColissimoPickupPointPriceSlicesQuery The current query, for fluid interface + */ + public function filterByPriceMax($priceMax = null, $comparison = null) + { + if (is_array($priceMax)) { + $useMinMax = false; + if (isset($priceMax['min'])) { + $this->addUsingAlias(ColissimoPickupPointPriceSlicesTableMap::PRICE_MAX, $priceMax['min'], Criteria::GREATER_EQUAL); + $useMinMax = true; + } + if (isset($priceMax['max'])) { + $this->addUsingAlias(ColissimoPickupPointPriceSlicesTableMap::PRICE_MAX, $priceMax['max'], Criteria::LESS_EQUAL); + $useMinMax = true; + } + if ($useMinMax) { + return $this; + } + if (null === $comparison) { + $comparison = Criteria::IN; + } + } + + return $this->addUsingAlias(ColissimoPickupPointPriceSlicesTableMap::PRICE_MAX, $priceMax, $comparison); + } + + /** + * Filter the query on the franco_min_price column + * + * Example usage: + * + * $query->filterByFrancoMinPrice(1234); // WHERE franco_min_price = 1234 + * $query->filterByFrancoMinPrice(array(12, 34)); // WHERE franco_min_price IN (12, 34) + * $query->filterByFrancoMinPrice(array('min' => 12)); // WHERE franco_min_price > 12 + * + * + * @param mixed $francoMinPrice The value to use as filter. + * Use scalar values for equality. + * Use array values for in_array() equivalent. + * Use associative array('min' => $minValue, 'max' => $maxValue) for intervals. + * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL + * + * @return ChildColissimoPickupPointPriceSlicesQuery The current query, for fluid interface + */ + public function filterByFrancoMinPrice($francoMinPrice = null, $comparison = null) + { + if (is_array($francoMinPrice)) { + $useMinMax = false; + if (isset($francoMinPrice['min'])) { + $this->addUsingAlias(ColissimoPickupPointPriceSlicesTableMap::FRANCO_MIN_PRICE, $francoMinPrice['min'], Criteria::GREATER_EQUAL); + $useMinMax = true; + } + if (isset($francoMinPrice['max'])) { + $this->addUsingAlias(ColissimoPickupPointPriceSlicesTableMap::FRANCO_MIN_PRICE, $francoMinPrice['max'], Criteria::LESS_EQUAL); + $useMinMax = true; + } + if ($useMinMax) { + return $this; + } + if (null === $comparison) { + $comparison = Criteria::IN; + } + } + + return $this->addUsingAlias(ColissimoPickupPointPriceSlicesTableMap::FRANCO_MIN_PRICE, $francoMinPrice, $comparison); + } + + /** + * Filter the query on the price column + * + * Example usage: + * + * $query->filterByPrice(1234); // WHERE price = 1234 + * $query->filterByPrice(array(12, 34)); // WHERE price IN (12, 34) + * $query->filterByPrice(array('min' => 12)); // WHERE price > 12 + * + * + * @param mixed $price The value to use as filter. + * Use scalar values for equality. + * Use array values for in_array() equivalent. + * Use associative array('min' => $minValue, 'max' => $maxValue) for intervals. + * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL + * + * @return ChildColissimoPickupPointPriceSlicesQuery The current query, for fluid interface + */ + public function filterByPrice($price = null, $comparison = null) + { + if (is_array($price)) { + $useMinMax = false; + if (isset($price['min'])) { + $this->addUsingAlias(ColissimoPickupPointPriceSlicesTableMap::PRICE, $price['min'], Criteria::GREATER_EQUAL); + $useMinMax = true; + } + if (isset($price['max'])) { + $this->addUsingAlias(ColissimoPickupPointPriceSlicesTableMap::PRICE, $price['max'], Criteria::LESS_EQUAL); + $useMinMax = true; + } + if ($useMinMax) { + return $this; + } + if (null === $comparison) { + $comparison = Criteria::IN; + } + } + + return $this->addUsingAlias(ColissimoPickupPointPriceSlicesTableMap::PRICE, $price, $comparison); + } + + /** + * Filter the query by a related \ColissimoPickupPoint\Model\Thelia\Model\Area object + * + * @param \ColissimoPickupPoint\Model\Thelia\Model\Area|ObjectCollection $area The related object(s) to use as filter + * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL + * + * @return ChildColissimoPickupPointPriceSlicesQuery The current query, for fluid interface + */ + public function filterByArea($area, $comparison = null) + { + if ($area instanceof \ColissimoPickupPoint\Model\Thelia\Model\Area) { + return $this + ->addUsingAlias(ColissimoPickupPointPriceSlicesTableMap::AREA_ID, $area->getId(), $comparison); + } elseif ($area instanceof ObjectCollection) { + if (null === $comparison) { + $comparison = Criteria::IN; + } + + return $this + ->addUsingAlias(ColissimoPickupPointPriceSlicesTableMap::AREA_ID, $area->toKeyValue('PrimaryKey', 'Id'), $comparison); + } else { + throw new PropelException('filterByArea() only accepts arguments of type \ColissimoPickupPoint\Model\Thelia\Model\Area or Collection'); + } + } + + /** + * Adds a JOIN clause to the query using the Area relation + * + * @param string $relationAlias optional alias for the relation + * @param string $joinType Accepted values are null, 'left join', 'right join', 'inner join' + * + * @return ChildColissimoPickupPointPriceSlicesQuery The current query, for fluid interface + */ + public function joinArea($relationAlias = null, $joinType = Criteria::INNER_JOIN) + { + $tableMap = $this->getTableMap(); + $relationMap = $tableMap->getRelation('Area'); + + // create a ModelJoin object for this join + $join = new ModelJoin(); + $join->setJoinType($joinType); + $join->setRelationMap($relationMap, $this->useAliasInSQL ? $this->getModelAlias() : null, $relationAlias); + if ($previousJoin = $this->getPreviousJoin()) { + $join->setPreviousJoin($previousJoin); + } + + // add the ModelJoin to the current object + if ($relationAlias) { + $this->addAlias($relationAlias, $relationMap->getRightTable()->getName()); + $this->addJoinObject($join, $relationAlias); + } else { + $this->addJoinObject($join, 'Area'); + } + + return $this; + } + + /** + * Use the Area relation Area object + * + * @see useQuery() + * + * @param string $relationAlias optional alias for the relation, + * to be used as main alias in the secondary query + * @param string $joinType Accepted values are null, 'left join', 'right join', 'inner join' + * + * @return \ColissimoPickupPoint\Model\Thelia\Model\AreaQuery A secondary query class using the current class as primary query + */ + public function useAreaQuery($relationAlias = null, $joinType = Criteria::INNER_JOIN) + { + return $this + ->joinArea($relationAlias, $joinType) + ->useQuery($relationAlias ? $relationAlias : 'Area', '\ColissimoPickupPoint\Model\Thelia\Model\AreaQuery'); + } + + /** + * Exclude object from result + * + * @param ChildColissimoPickupPointPriceSlices $colissimoPickupPointPriceSlices Object to remove from the list of results + * + * @return ChildColissimoPickupPointPriceSlicesQuery The current query, for fluid interface + */ + public function prune($colissimoPickupPointPriceSlices = null) + { + if ($colissimoPickupPointPriceSlices) { + $this->addUsingAlias(ColissimoPickupPointPriceSlicesTableMap::ID, $colissimoPickupPointPriceSlices->getId(), Criteria::NOT_EQUAL); + } + + return $this; + } + + /** + * Deletes all rows from the colissimo_pickup_point_price_slices table. + * + * @param ConnectionInterface $con the connection to use + * @return int The number of affected rows (if supported by underlying database driver). + */ + public function doDeleteAll(ConnectionInterface $con = null) + { + if (null === $con) { + $con = Propel::getServiceContainer()->getWriteConnection(ColissimoPickupPointPriceSlicesTableMap::DATABASE_NAME); + } + $affectedRows = 0; // initialize var to track total num of affected rows + try { + // use transaction because $criteria could contain info + // for more than one table or we could emulating ON DELETE CASCADE, etc. + $con->beginTransaction(); + $affectedRows += parent::doDeleteAll($con); + // Because this db requires some delete cascade/set null emulation, we have to + // clear the cached instance *after* the emulation has happened (since + // instances get re-added by the select statement contained therein). + ColissimoPickupPointPriceSlicesTableMap::clearInstancePool(); + ColissimoPickupPointPriceSlicesTableMap::clearRelatedInstancePool(); + + $con->commit(); + } catch (PropelException $e) { + $con->rollBack(); + throw $e; + } + + return $affectedRows; + } + + /** + * Performs a DELETE on the database, given a ChildColissimoPickupPointPriceSlices or Criteria object OR a primary key value. + * + * @param mixed $values Criteria or ChildColissimoPickupPointPriceSlices object or primary key or array of primary keys + * which is used to create the DELETE statement + * @param ConnectionInterface $con the connection to use + * @return int The number of affected rows (if supported by underlying database driver). This includes CASCADE-related rows + * if supported by native driver or if emulated using Propel. + * @throws PropelException Any exceptions caught during processing will be + * rethrown wrapped into a PropelException. + */ + public function delete(ConnectionInterface $con = null) + { + if (null === $con) { + $con = Propel::getServiceContainer()->getWriteConnection(ColissimoPickupPointPriceSlicesTableMap::DATABASE_NAME); + } + + $criteria = $this; + + // Set the correct dbName + $criteria->setDbName(ColissimoPickupPointPriceSlicesTableMap::DATABASE_NAME); + + $affectedRows = 0; // initialize var to track total num of affected rows + + try { + // use transaction because $criteria could contain info + // for more than one table or we could emulating ON DELETE CASCADE, etc. + $con->beginTransaction(); + + + ColissimoPickupPointPriceSlicesTableMap::removeInstanceFromPool($criteria); + + $affectedRows += ModelCriteria::delete($con); + ColissimoPickupPointPriceSlicesTableMap::clearRelatedInstancePool(); + $con->commit(); + + return $affectedRows; + } catch (PropelException $e) { + $con->rollBack(); + throw $e; + } + } + +} // ColissimoPickupPointPriceSlicesQuery diff --git a/local/modules/ColissimoPickupPoint/Model/Base/OrderAddressColissimoPickupPoint.php b/local/modules/ColissimoPickupPoint/Model/Base/OrderAddressColissimoPickupPoint.php new file mode 100644 index 00000000..fb4fa11a --- /dev/null +++ b/local/modules/ColissimoPickupPoint/Model/Base/OrderAddressColissimoPickupPoint.php @@ -0,0 +1,1236 @@ +modifiedColumns; + } + + /** + * Has specified column been modified? + * + * @param string $col column fully qualified name (TableMap::TYPE_COLNAME), e.g. Book::AUTHOR_ID + * @return boolean True if $col has been modified. + */ + public function isColumnModified($col) + { + return $this->modifiedColumns && isset($this->modifiedColumns[$col]); + } + + /** + * Get the columns that have been modified in this object. + * @return array A unique list of the modified column names for this object. + */ + public function getModifiedColumns() + { + return $this->modifiedColumns ? array_keys($this->modifiedColumns) : []; + } + + /** + * Returns whether the object has ever been saved. This will + * be false, if the object was retrieved from storage or was created + * and then saved. + * + * @return boolean true, if the object has never been persisted. + */ + public function isNew() + { + return $this->new; + } + + /** + * Setter for the isNew attribute. This method will be called + * by Propel-generated children and objects. + * + * @param boolean $b the state of the object. + */ + public function setNew($b) + { + $this->new = (Boolean) $b; + } + + /** + * Whether this object has been deleted. + * @return boolean The deleted state of this object. + */ + public function isDeleted() + { + return $this->deleted; + } + + /** + * Specify whether this object has been deleted. + * @param boolean $b The deleted state of this object. + * @return void + */ + public function setDeleted($b) + { + $this->deleted = (Boolean) $b; + } + + /** + * Sets the modified state for the object to be false. + * @param string $col If supplied, only the specified column is reset. + * @return void + */ + public function resetModified($col = null) + { + if (null !== $col) { + if (isset($this->modifiedColumns[$col])) { + unset($this->modifiedColumns[$col]); + } + } else { + $this->modifiedColumns = array(); + } + } + + /** + * Compares this with another OrderAddressColissimoPickupPoint instance. If + * obj is an instance of OrderAddressColissimoPickupPoint, delegates to + * equals(OrderAddressColissimoPickupPoint). Otherwise, returns false. + * + * @param mixed $obj The object to compare to. + * @return boolean Whether equal to the object specified. + */ + public function equals($obj) + { + $thisclazz = get_class($this); + if (!is_object($obj) || !($obj instanceof $thisclazz)) { + return false; + } + + if ($this === $obj) { + return true; + } + + if (null === $this->getPrimaryKey() + || null === $obj->getPrimaryKey()) { + return false; + } + + return $this->getPrimaryKey() === $obj->getPrimaryKey(); + } + + /** + * If the primary key is not null, return the hashcode of the + * primary key. Otherwise, return the hash code of the object. + * + * @return int Hashcode + */ + public function hashCode() + { + if (null !== $this->getPrimaryKey()) { + return crc32(serialize($this->getPrimaryKey())); + } + + return crc32(serialize(clone $this)); + } + + /** + * Get the associative array of the virtual columns in this object + * + * @return array + */ + public function getVirtualColumns() + { + return $this->virtualColumns; + } + + /** + * Checks the existence of a virtual column in this object + * + * @param string $name The virtual column name + * @return boolean + */ + public function hasVirtualColumn($name) + { + return array_key_exists($name, $this->virtualColumns); + } + + /** + * Get the value of a virtual column in this object + * + * @param string $name The virtual column name + * @return mixed + * + * @throws PropelException + */ + public function getVirtualColumn($name) + { + if (!$this->hasVirtualColumn($name)) { + throw new PropelException(sprintf('Cannot get value of inexistent virtual column %s.', $name)); + } + + return $this->virtualColumns[$name]; + } + + /** + * Set the value of a virtual column in this object + * + * @param string $name The virtual column name + * @param mixed $value The value to give to the virtual column + * + * @return OrderAddressColissimoPickupPoint The current object, for fluid interface + */ + public function setVirtualColumn($name, $value) + { + $this->virtualColumns[$name] = $value; + + return $this; + } + + /** + * Logs a message using Propel::log(). + * + * @param string $msg + * @param int $priority One of the Propel::LOG_* logging levels + * @return boolean + */ + protected function log($msg, $priority = Propel::LOG_INFO) + { + return Propel::log(get_class($this) . ': ' . $msg, $priority); + } + + /** + * Populate the current object from a string, using a given parser format + * + * $book = new Book(); + * $book->importFrom('JSON', '{"Id":9012,"Title":"Don Juan","ISBN":"0140422161","Price":12.99,"PublisherId":1234,"AuthorId":5678}'); + * + * + * @param mixed $parser A AbstractParser instance, + * or a format name ('XML', 'YAML', 'JSON', 'CSV') + * @param string $data The source data to import from + * + * @return OrderAddressColissimoPickupPoint The current object, for fluid interface + */ + public function importFrom($parser, $data) + { + if (!$parser instanceof AbstractParser) { + $parser = AbstractParser::getParser($parser); + } + + $this->fromArray($parser->toArray($data), TableMap::TYPE_PHPNAME); + + return $this; + } + + /** + * Export the current object properties to a string, using a given parser format + * + * $book = BookQuery::create()->findPk(9012); + * echo $book->exportTo('JSON'); + * => {"Id":9012,"Title":"Don Juan","ISBN":"0140422161","Price":12.99,"PublisherId":1234,"AuthorId":5678}'); + * + * + * @param mixed $parser A AbstractParser instance, or a format name ('XML', 'YAML', 'JSON', 'CSV') + * @param boolean $includeLazyLoadColumns (optional) Whether to include lazy load(ed) columns. Defaults to TRUE. + * @return string The exported data + */ + public function exportTo($parser, $includeLazyLoadColumns = true) + { + if (!$parser instanceof AbstractParser) { + $parser = AbstractParser::getParser($parser); + } + + return $parser->fromArray($this->toArray(TableMap::TYPE_PHPNAME, $includeLazyLoadColumns, array(), true)); + } + + /** + * Clean up internal collections prior to serializing + * Avoids recursive loops that turn into segmentation faults when serializing + */ + public function __sleep() + { + $this->clearAllReferences(); + + return array_keys(get_object_vars($this)); + } + + /** + * Get the [id] column value. + * + * @return int + */ + public function getId() + { + + return $this->id; + } + + /** + * Get the [code] column value. + * + * @return string + */ + public function getCode() + { + + return $this->code; + } + + /** + * Get the [type] column value. + * + * @return string + */ + public function getType() + { + + return $this->type; + } + + /** + * Set the value of [id] column. + * + * @param int $v new value + * @return \ColissimoPickupPoint\Model\OrderAddressColissimoPickupPoint The current object (for fluent API support) + */ + public function setId($v) + { + if ($v !== null) { + $v = (int) $v; + } + + if ($this->id !== $v) { + $this->id = $v; + $this->modifiedColumns[OrderAddressColissimoPickupPointTableMap::ID] = true; + } + + if ($this->aOrderAddress !== null && $this->aOrderAddress->getId() !== $v) { + $this->aOrderAddress = null; + } + + + return $this; + } // setId() + + /** + * Set the value of [code] column. + * + * @param string $v new value + * @return \ColissimoPickupPoint\Model\OrderAddressColissimoPickupPoint The current object (for fluent API support) + */ + public function setCode($v) + { + if ($v !== null) { + $v = (string) $v; + } + + if ($this->code !== $v) { + $this->code = $v; + $this->modifiedColumns[OrderAddressColissimoPickupPointTableMap::CODE] = true; + } + + + return $this; + } // setCode() + + /** + * Set the value of [type] column. + * + * @param string $v new value + * @return \ColissimoPickupPoint\Model\OrderAddressColissimoPickupPoint The current object (for fluent API support) + */ + public function setType($v) + { + if ($v !== null) { + $v = (string) $v; + } + + if ($this->type !== $v) { + $this->type = $v; + $this->modifiedColumns[OrderAddressColissimoPickupPointTableMap::TYPE] = true; + } + + + return $this; + } // setType() + + /** + * Indicates whether the columns in this object are only set to default values. + * + * This method can be used in conjunction with isModified() to indicate whether an object is both + * modified _and_ has some values set which are non-default. + * + * @return boolean Whether the columns in this object are only been set with default values. + */ + public function hasOnlyDefaultValues() + { + // otherwise, everything was equal, so return TRUE + return true; + } // hasOnlyDefaultValues() + + /** + * Hydrates (populates) the object variables with values from the database resultset. + * + * An offset (0-based "start column") is specified so that objects can be hydrated + * with a subset of the columns in the resultset rows. This is needed, for example, + * for results of JOIN queries where the resultset row includes columns from two or + * more tables. + * + * @param array $row The row returned by DataFetcher->fetch(). + * @param int $startcol 0-based offset column which indicates which restultset column to start with. + * @param boolean $rehydrate Whether this object is being re-hydrated from the database. + * @param string $indexType The index type of $row. Mostly DataFetcher->getIndexType(). + One of the class type constants TableMap::TYPE_PHPNAME, TableMap::TYPE_STUDLYPHPNAME + * TableMap::TYPE_COLNAME, TableMap::TYPE_FIELDNAME, TableMap::TYPE_NUM. + * + * @return int next starting column + * @throws PropelException - Any caught Exception will be rewrapped as a PropelException. + */ + public function hydrate($row, $startcol = 0, $rehydrate = false, $indexType = TableMap::TYPE_NUM) + { + try { + + + $col = $row[TableMap::TYPE_NUM == $indexType ? 0 + $startcol : OrderAddressColissimoPickupPointTableMap::translateFieldName('Id', TableMap::TYPE_PHPNAME, $indexType)]; + $this->id = (null !== $col) ? (int) $col : null; + + $col = $row[TableMap::TYPE_NUM == $indexType ? 1 + $startcol : OrderAddressColissimoPickupPointTableMap::translateFieldName('Code', TableMap::TYPE_PHPNAME, $indexType)]; + $this->code = (null !== $col) ? (string) $col : null; + + $col = $row[TableMap::TYPE_NUM == $indexType ? 2 + $startcol : OrderAddressColissimoPickupPointTableMap::translateFieldName('Type', TableMap::TYPE_PHPNAME, $indexType)]; + $this->type = (null !== $col) ? (string) $col : null; + $this->resetModified(); + + $this->setNew(false); + + if ($rehydrate) { + $this->ensureConsistency(); + } + + return $startcol + 3; // 3 = OrderAddressColissimoPickupPointTableMap::NUM_HYDRATE_COLUMNS. + + } catch (Exception $e) { + throw new PropelException("Error populating \ColissimoPickupPoint\Model\OrderAddressColissimoPickupPoint object", 0, $e); + } + } + + /** + * Checks and repairs the internal consistency of the object. + * + * This method is executed after an already-instantiated object is re-hydrated + * from the database. It exists to check any foreign keys to make sure that + * the objects related to the current object are correct based on foreign key. + * + * You can override this method in the stub class, but you should always invoke + * the base method from the overridden method (i.e. parent::ensureConsistency()), + * in case your model changes. + * + * @throws PropelException + */ + public function ensureConsistency() + { + if ($this->aOrderAddress !== null && $this->id !== $this->aOrderAddress->getId()) { + $this->aOrderAddress = null; + } + } // ensureConsistency + + /** + * Reloads this object from datastore based on primary key and (optionally) resets all associated objects. + * + * This will only work if the object has been saved and has a valid primary key set. + * + * @param boolean $deep (optional) Whether to also de-associated any related objects. + * @param ConnectionInterface $con (optional) The ConnectionInterface connection to use. + * @return void + * @throws PropelException - if this object is deleted, unsaved or doesn't have pk match in db + */ + public function reload($deep = false, ConnectionInterface $con = null) + { + if ($this->isDeleted()) { + throw new PropelException("Cannot reload a deleted object."); + } + + if ($this->isNew()) { + throw new PropelException("Cannot reload an unsaved object."); + } + + if ($con === null) { + $con = Propel::getServiceContainer()->getReadConnection(OrderAddressColissimoPickupPointTableMap::DATABASE_NAME); + } + + // We don't need to alter the object instance pool; we're just modifying this instance + // already in the pool. + + $dataFetcher = ChildOrderAddressColissimoPickupPointQuery::create(null, $this->buildPkeyCriteria())->setFormatter(ModelCriteria::FORMAT_STATEMENT)->find($con); + $row = $dataFetcher->fetch(); + $dataFetcher->close(); + if (!$row) { + throw new PropelException('Cannot find matching row in the database to reload object values.'); + } + $this->hydrate($row, 0, true, $dataFetcher->getIndexType()); // rehydrate + + if ($deep) { // also de-associate any related objects? + + $this->aOrderAddress = null; + } // if (deep) + } + + /** + * Removes this object from datastore and sets delete attribute. + * + * @param ConnectionInterface $con + * @return void + * @throws PropelException + * @see OrderAddressColissimoPickupPoint::setDeleted() + * @see OrderAddressColissimoPickupPoint::isDeleted() + */ + public function delete(ConnectionInterface $con = null) + { + if ($this->isDeleted()) { + throw new PropelException("This object has already been deleted."); + } + + if ($con === null) { + $con = Propel::getServiceContainer()->getWriteConnection(OrderAddressColissimoPickupPointTableMap::DATABASE_NAME); + } + + $con->beginTransaction(); + try { + $deleteQuery = ChildOrderAddressColissimoPickupPointQuery::create() + ->filterByPrimaryKey($this->getPrimaryKey()); + $ret = $this->preDelete($con); + if ($ret) { + $deleteQuery->delete($con); + $this->postDelete($con); + $con->commit(); + $this->setDeleted(true); + } else { + $con->commit(); + } + } catch (Exception $e) { + $con->rollBack(); + throw $e; + } + } + + /** + * Persists this object to the database. + * + * If the object is new, it inserts it; otherwise an update is performed. + * All modified related objects will also be persisted in the doSave() + * method. This method wraps all precipitate database operations in a + * single transaction. + * + * @param ConnectionInterface $con + * @return int The number of rows affected by this insert/update and any referring fk objects' save() operations. + * @throws PropelException + * @see doSave() + */ + public function save(ConnectionInterface $con = null) + { + if ($this->isDeleted()) { + throw new PropelException("You cannot save an object that has been deleted."); + } + + if ($con === null) { + $con = Propel::getServiceContainer()->getWriteConnection(OrderAddressColissimoPickupPointTableMap::DATABASE_NAME); + } + + $con->beginTransaction(); + $isInsert = $this->isNew(); + try { + $ret = $this->preSave($con); + if ($isInsert) { + $ret = $ret && $this->preInsert($con); + } else { + $ret = $ret && $this->preUpdate($con); + } + if ($ret) { + $affectedRows = $this->doSave($con); + if ($isInsert) { + $this->postInsert($con); + } else { + $this->postUpdate($con); + } + $this->postSave($con); + OrderAddressColissimoPickupPointTableMap::addInstanceToPool($this); + } else { + $affectedRows = 0; + } + $con->commit(); + + return $affectedRows; + } catch (Exception $e) { + $con->rollBack(); + throw $e; + } + } + + /** + * Performs the work of inserting or updating the row in the database. + * + * If the object is new, it inserts it; otherwise an update is performed. + * All related objects are also updated in this method. + * + * @param ConnectionInterface $con + * @return int The number of rows affected by this insert/update and any referring fk objects' save() operations. + * @throws PropelException + * @see save() + */ + protected function doSave(ConnectionInterface $con) + { + $affectedRows = 0; // initialize var to track total num of affected rows + if (!$this->alreadyInSave) { + $this->alreadyInSave = true; + + // We call the save method on the following object(s) if they + // were passed to this object by their corresponding set + // method. This object relates to these object(s) by a + // foreign key reference. + + if ($this->aOrderAddress !== null) { + if ($this->aOrderAddress->isModified() || $this->aOrderAddress->isNew()) { + $affectedRows += $this->aOrderAddress->save($con); + } + $this->setOrderAddress($this->aOrderAddress); + } + + if ($this->isNew() || $this->isModified()) { + // persist changes + if ($this->isNew()) { + $this->doInsert($con); + } else { + $this->doUpdate($con); + } + $affectedRows += 1; + $this->resetModified(); + } + + $this->alreadyInSave = false; + + } + + return $affectedRows; + } // doSave() + + /** + * Insert the row in the database. + * + * @param ConnectionInterface $con + * + * @throws PropelException + * @see doSave() + */ + protected function doInsert(ConnectionInterface $con) + { + $modifiedColumns = array(); + $index = 0; + + + // check the columns in natural order for more readable SQL queries + if ($this->isColumnModified(OrderAddressColissimoPickupPointTableMap::ID)) { + $modifiedColumns[':p' . $index++] = 'ID'; + } + if ($this->isColumnModified(OrderAddressColissimoPickupPointTableMap::CODE)) { + $modifiedColumns[':p' . $index++] = 'CODE'; + } + if ($this->isColumnModified(OrderAddressColissimoPickupPointTableMap::TYPE)) { + $modifiedColumns[':p' . $index++] = 'TYPE'; + } + + $sql = sprintf( + 'INSERT INTO order_address_colissimo_pickup_point (%s) VALUES (%s)', + implode(', ', $modifiedColumns), + implode(', ', array_keys($modifiedColumns)) + ); + + try { + $stmt = $con->prepare($sql); + foreach ($modifiedColumns as $identifier => $columnName) { + switch ($columnName) { + case 'ID': + $stmt->bindValue($identifier, $this->id, PDO::PARAM_INT); + break; + case 'CODE': + $stmt->bindValue($identifier, $this->code, PDO::PARAM_STR); + break; + case 'TYPE': + $stmt->bindValue($identifier, $this->type, PDO::PARAM_STR); + break; + } + } + $stmt->execute(); + } catch (Exception $e) { + Propel::log($e->getMessage(), Propel::LOG_ERR); + throw new PropelException(sprintf('Unable to execute INSERT statement [%s]', $sql), 0, $e); + } + + $this->setNew(false); + } + + /** + * Update the row in the database. + * + * @param ConnectionInterface $con + * + * @return Integer Number of updated rows + * @see doSave() + */ + protected function doUpdate(ConnectionInterface $con) + { + $selectCriteria = $this->buildPkeyCriteria(); + $valuesCriteria = $this->buildCriteria(); + + return $selectCriteria->doUpdate($valuesCriteria, $con); + } + + /** + * Retrieves a field from the object by name passed in as a string. + * + * @param string $name name + * @param string $type The type of fieldname the $name is of: + * one of the class type constants TableMap::TYPE_PHPNAME, TableMap::TYPE_STUDLYPHPNAME + * TableMap::TYPE_COLNAME, TableMap::TYPE_FIELDNAME, TableMap::TYPE_NUM. + * Defaults to TableMap::TYPE_PHPNAME. + * @return mixed Value of field. + */ + public function getByName($name, $type = TableMap::TYPE_PHPNAME) + { + $pos = OrderAddressColissimoPickupPointTableMap::translateFieldName($name, $type, TableMap::TYPE_NUM); + $field = $this->getByPosition($pos); + + return $field; + } + + /** + * Retrieves a field from the object by Position as specified in the xml schema. + * Zero-based. + * + * @param int $pos position in xml schema + * @return mixed Value of field at $pos + */ + public function getByPosition($pos) + { + switch ($pos) { + case 0: + return $this->getId(); + break; + case 1: + return $this->getCode(); + break; + case 2: + return $this->getType(); + break; + default: + return null; + break; + } // switch() + } + + /** + * Exports the object as an array. + * + * You can specify the key type of the array by passing one of the class + * type constants. + * + * @param string $keyType (optional) One of the class type constants TableMap::TYPE_PHPNAME, TableMap::TYPE_STUDLYPHPNAME, + * TableMap::TYPE_COLNAME, TableMap::TYPE_FIELDNAME, TableMap::TYPE_NUM. + * Defaults to TableMap::TYPE_PHPNAME. + * @param boolean $includeLazyLoadColumns (optional) Whether to include lazy loaded columns. Defaults to TRUE. + * @param array $alreadyDumpedObjects List of objects to skip to avoid recursion + * @param boolean $includeForeignObjects (optional) Whether to include hydrated related objects. Default to FALSE. + * + * @return array an associative array containing the field names (as keys) and field values + */ + public function toArray($keyType = TableMap::TYPE_PHPNAME, $includeLazyLoadColumns = true, $alreadyDumpedObjects = array(), $includeForeignObjects = false) + { + if (isset($alreadyDumpedObjects['OrderAddressColissimoPickupPoint'][$this->getPrimaryKey()])) { + return '*RECURSION*'; + } + $alreadyDumpedObjects['OrderAddressColissimoPickupPoint'][$this->getPrimaryKey()] = true; + $keys = OrderAddressColissimoPickupPointTableMap::getFieldNames($keyType); + $result = array( + $keys[0] => $this->getId(), + $keys[1] => $this->getCode(), + $keys[2] => $this->getType(), + ); + $virtualColumns = $this->virtualColumns; + foreach ($virtualColumns as $key => $virtualColumn) { + $result[$key] = $virtualColumn; + } + + if ($includeForeignObjects) { + if (null !== $this->aOrderAddress) { + $result['OrderAddress'] = $this->aOrderAddress->toArray($keyType, $includeLazyLoadColumns, $alreadyDumpedObjects, true); + } + } + + return $result; + } + + /** + * Sets a field from the object by name passed in as a string. + * + * @param string $name + * @param mixed $value field value + * @param string $type The type of fieldname the $name is of: + * one of the class type constants TableMap::TYPE_PHPNAME, TableMap::TYPE_STUDLYPHPNAME + * TableMap::TYPE_COLNAME, TableMap::TYPE_FIELDNAME, TableMap::TYPE_NUM. + * Defaults to TableMap::TYPE_PHPNAME. + * @return void + */ + public function setByName($name, $value, $type = TableMap::TYPE_PHPNAME) + { + $pos = OrderAddressColissimoPickupPointTableMap::translateFieldName($name, $type, TableMap::TYPE_NUM); + + return $this->setByPosition($pos, $value); + } + + /** + * Sets a field from the object by Position as specified in the xml schema. + * Zero-based. + * + * @param int $pos position in xml schema + * @param mixed $value field value + * @return void + */ + public function setByPosition($pos, $value) + { + switch ($pos) { + case 0: + $this->setId($value); + break; + case 1: + $this->setCode($value); + break; + case 2: + $this->setType($value); + break; + } // switch() + } + + /** + * Populates the object using an array. + * + * This is particularly useful when populating an object from one of the + * request arrays (e.g. $_POST). This method goes through the column + * names, checking to see whether a matching key exists in populated + * array. If so the setByName() method is called for that column. + * + * You can specify the key type of the array by additionally passing one + * of the class type constants TableMap::TYPE_PHPNAME, TableMap::TYPE_STUDLYPHPNAME, + * TableMap::TYPE_COLNAME, TableMap::TYPE_FIELDNAME, TableMap::TYPE_NUM. + * The default key type is the column's TableMap::TYPE_PHPNAME. + * + * @param array $arr An array to populate the object from. + * @param string $keyType The type of keys the array uses. + * @return void + */ + public function fromArray($arr, $keyType = TableMap::TYPE_PHPNAME) + { + $keys = OrderAddressColissimoPickupPointTableMap::getFieldNames($keyType); + + if (array_key_exists($keys[0], $arr)) $this->setId($arr[$keys[0]]); + if (array_key_exists($keys[1], $arr)) $this->setCode($arr[$keys[1]]); + if (array_key_exists($keys[2], $arr)) $this->setType($arr[$keys[2]]); + } + + /** + * Build a Criteria object containing the values of all modified columns in this object. + * + * @return Criteria The Criteria object containing all modified values. + */ + public function buildCriteria() + { + $criteria = new Criteria(OrderAddressColissimoPickupPointTableMap::DATABASE_NAME); + + if ($this->isColumnModified(OrderAddressColissimoPickupPointTableMap::ID)) $criteria->add(OrderAddressColissimoPickupPointTableMap::ID, $this->id); + if ($this->isColumnModified(OrderAddressColissimoPickupPointTableMap::CODE)) $criteria->add(OrderAddressColissimoPickupPointTableMap::CODE, $this->code); + if ($this->isColumnModified(OrderAddressColissimoPickupPointTableMap::TYPE)) $criteria->add(OrderAddressColissimoPickupPointTableMap::TYPE, $this->type); + + return $criteria; + } + + /** + * Builds a Criteria object containing the primary key for this object. + * + * Unlike buildCriteria() this method includes the primary key values regardless + * of whether or not they have been modified. + * + * @return Criteria The Criteria object containing value(s) for primary key(s). + */ + public function buildPkeyCriteria() + { + $criteria = new Criteria(OrderAddressColissimoPickupPointTableMap::DATABASE_NAME); + $criteria->add(OrderAddressColissimoPickupPointTableMap::ID, $this->id); + + return $criteria; + } + + /** + * Returns the primary key for this object (row). + * @return int + */ + public function getPrimaryKey() + { + return $this->getId(); + } + + /** + * Generic method to set the primary key (id column). + * + * @param int $key Primary key. + * @return void + */ + public function setPrimaryKey($key) + { + $this->setId($key); + } + + /** + * Returns true if the primary key for this object is null. + * @return boolean + */ + public function isPrimaryKeyNull() + { + + return null === $this->getId(); + } + + /** + * Sets contents of passed object to values from current object. + * + * If desired, this method can also make copies of all associated (fkey referrers) + * objects. + * + * @param object $copyObj An object of \ColissimoPickupPoint\Model\OrderAddressColissimoPickupPoint (or compatible) type. + * @param boolean $deepCopy Whether to also copy all rows that refer (by fkey) to the current row. + * @param boolean $makeNew Whether to reset autoincrement PKs and make the object new. + * @throws PropelException + */ + public function copyInto($copyObj, $deepCopy = false, $makeNew = true) + { + $copyObj->setId($this->getId()); + $copyObj->setCode($this->getCode()); + $copyObj->setType($this->getType()); + if ($makeNew) { + $copyObj->setNew(true); + } + } + + /** + * Makes a copy of this object that will be inserted as a new row in table when saved. + * It creates a new object filling in the simple attributes, but skipping any primary + * keys that are defined for the table. + * + * If desired, this method can also make copies of all associated (fkey referrers) + * objects. + * + * @param boolean $deepCopy Whether to also copy all rows that refer (by fkey) to the current row. + * @return \ColissimoPickupPoint\Model\OrderAddressColissimoPickupPoint Clone of current object. + * @throws PropelException + */ + public function copy($deepCopy = false) + { + // we use get_class(), because this might be a subclass + $clazz = get_class($this); + $copyObj = new $clazz(); + $this->copyInto($copyObj, $deepCopy); + + return $copyObj; + } + + /** + * Declares an association between this object and a ChildOrderAddress object. + * + * @param ChildOrderAddress $v + * @return \ColissimoPickupPoint\Model\OrderAddressColissimoPickupPoint The current object (for fluent API support) + * @throws PropelException + */ + public function setOrderAddress(ChildOrderAddress $v = null) + { + if ($v === null) { + $this->setId(NULL); + } else { + $this->setId($v->getId()); + } + + $this->aOrderAddress = $v; + + // Add binding for other direction of this 1:1 relationship. + if ($v !== null) { + $v->setOrderAddressColissimoPickupPoint($this); + } + + + return $this; + } + + + /** + * Get the associated ChildOrderAddress object + * + * @param ConnectionInterface $con Optional Connection object. + * @return ChildOrderAddress The associated ChildOrderAddress object. + * @throws PropelException + */ + public function getOrderAddress(ConnectionInterface $con = null) + { + if ($this->aOrderAddress === null && ($this->id !== null)) { + $this->aOrderAddress = OrderAddressQuery::create()->findPk($this->id, $con); + // Because this foreign key represents a one-to-one relationship, we will create a bi-directional association. + $this->aOrderAddress->setOrderAddressColissimoPickupPoint($this); + } + + return $this->aOrderAddress; + } + + /** + * Clears the current object and sets all attributes to their default values + */ + public function clear() + { + $this->id = null; + $this->code = null; + $this->type = null; + $this->alreadyInSave = false; + $this->clearAllReferences(); + $this->resetModified(); + $this->setNew(true); + $this->setDeleted(false); + } + + /** + * Resets all references to other model objects or collections of model objects. + * + * This method is a user-space workaround for PHP's inability to garbage collect + * objects with circular references (even in PHP 5.3). This is currently necessary + * when using Propel in certain daemon or large-volume/high-memory operations. + * + * @param boolean $deep Whether to also clear the references on all referrer objects. + */ + public function clearAllReferences($deep = false) + { + if ($deep) { + } // if ($deep) + + $this->aOrderAddress = null; + } + + /** + * Return the string representation of this object + * + * @return string + */ + public function __toString() + { + return (string) $this->exportTo(OrderAddressColissimoPickupPointTableMap::DEFAULT_STRING_FORMAT); + } + + /** + * Code to be run before persisting the object + * @param ConnectionInterface $con + * @return boolean + */ + public function preSave(ConnectionInterface $con = null) + { + return true; + } + + /** + * Code to be run after persisting the object + * @param ConnectionInterface $con + */ + public function postSave(ConnectionInterface $con = null) + { + + } + + /** + * Code to be run before inserting to database + * @param ConnectionInterface $con + * @return boolean + */ + public function preInsert(ConnectionInterface $con = null) + { + return true; + } + + /** + * Code to be run after inserting to database + * @param ConnectionInterface $con + */ + public function postInsert(ConnectionInterface $con = null) + { + + } + + /** + * Code to be run before updating the object in database + * @param ConnectionInterface $con + * @return boolean + */ + public function preUpdate(ConnectionInterface $con = null) + { + return true; + } + + /** + * Code to be run after updating the object in database + * @param ConnectionInterface $con + */ + public function postUpdate(ConnectionInterface $con = null) + { + + } + + /** + * Code to be run before deleting the object in database + * @param ConnectionInterface $con + * @return boolean + */ + public function preDelete(ConnectionInterface $con = null) + { + return true; + } + + /** + * Code to be run after deleting the object in database + * @param ConnectionInterface $con + */ + public function postDelete(ConnectionInterface $con = null) + { + + } + + + /** + * Derived method to catches calls to undefined methods. + * + * Provides magic import/export method support (fromXML()/toXML(), fromYAML()/toYAML(), etc.). + * Allows to define default __call() behavior if you overwrite __call() + * + * @param string $name + * @param mixed $params + * + * @return array|string + */ + public function __call($name, $params) + { + if (0 === strpos($name, 'get')) { + $virtualColumn = substr($name, 3); + if ($this->hasVirtualColumn($virtualColumn)) { + return $this->getVirtualColumn($virtualColumn); + } + + $virtualColumn = lcfirst($virtualColumn); + if ($this->hasVirtualColumn($virtualColumn)) { + return $this->getVirtualColumn($virtualColumn); + } + } + + if (0 === strpos($name, 'from')) { + $format = substr($name, 4); + + return $this->importFrom($format, reset($params)); + } + + if (0 === strpos($name, 'to')) { + $format = substr($name, 2); + $includeLazyLoadColumns = isset($params[0]) ? $params[0] : true; + + return $this->exportTo($format, $includeLazyLoadColumns); + } + + throw new BadMethodCallException(sprintf('Call to undefined method: %s.', $name)); + } + +} diff --git a/local/modules/ColissimoPickupPoint/Model/Base/OrderAddressColissimoPickupPointQuery.php b/local/modules/ColissimoPickupPoint/Model/Base/OrderAddressColissimoPickupPointQuery.php new file mode 100644 index 00000000..c517ea98 --- /dev/null +++ b/local/modules/ColissimoPickupPoint/Model/Base/OrderAddressColissimoPickupPointQuery.php @@ -0,0 +1,495 @@ +setModelAlias($modelAlias); + } + if ($criteria instanceof Criteria) { + $query->mergeWith($criteria); + } + + return $query; + } + + /** + * Find object by primary key. + * Propel uses the instance pool to skip the database if the object exists. + * Go fast if the query is untouched. + * + * + * $obj = $c->findPk(12, $con); + * + * + * @param mixed $key Primary key to use for the query + * @param ConnectionInterface $con an optional connection object + * + * @return ChildOrderAddressColissimoPickupPoint|array|mixed the result, formatted by the current formatter + */ + public function findPk($key, $con = null) + { + if ($key === null) { + return null; + } + if ((null !== ($obj = OrderAddressColissimoPickupPointTableMap::getInstanceFromPool((string) $key))) && !$this->formatter) { + // the object is already in the instance pool + return $obj; + } + if ($con === null) { + $con = Propel::getServiceContainer()->getReadConnection(OrderAddressColissimoPickupPointTableMap::DATABASE_NAME); + } + $this->basePreSelect($con); + if ($this->formatter || $this->modelAlias || $this->with || $this->select + || $this->selectColumns || $this->asColumns || $this->selectModifiers + || $this->map || $this->having || $this->joins) { + return $this->findPkComplex($key, $con); + } else { + return $this->findPkSimple($key, $con); + } + } + + /** + * Find object by primary key using raw SQL to go fast. + * Bypass doSelect() and the object formatter by using generated code. + * + * @param mixed $key Primary key to use for the query + * @param ConnectionInterface $con A connection object + * + * @return ChildOrderAddressColissimoPickupPoint A model object, or null if the key is not found + */ + protected function findPkSimple($key, $con) + { + $sql = 'SELECT ID, CODE, TYPE FROM order_address_colissimo_pickup_point WHERE ID = :p0'; + try { + $stmt = $con->prepare($sql); + $stmt->bindValue(':p0', $key, PDO::PARAM_INT); + $stmt->execute(); + } catch (Exception $e) { + Propel::log($e->getMessage(), Propel::LOG_ERR); + throw new PropelException(sprintf('Unable to execute SELECT statement [%s]', $sql), 0, $e); + } + $obj = null; + if ($row = $stmt->fetch(\PDO::FETCH_NUM)) { + $obj = new ChildOrderAddressColissimoPickupPoint(); + $obj->hydrate($row); + OrderAddressColissimoPickupPointTableMap::addInstanceToPool($obj, (string) $key); + } + $stmt->closeCursor(); + + return $obj; + } + + /** + * Find object by primary key. + * + * @param mixed $key Primary key to use for the query + * @param ConnectionInterface $con A connection object + * + * @return ChildOrderAddressColissimoPickupPoint|array|mixed the result, formatted by the current formatter + */ + protected function findPkComplex($key, $con) + { + // As the query uses a PK condition, no limit(1) is necessary. + $criteria = $this->isKeepQuery() ? clone $this : $this; + $dataFetcher = $criteria + ->filterByPrimaryKey($key) + ->doSelect($con); + + return $criteria->getFormatter()->init($criteria)->formatOne($dataFetcher); + } + + /** + * Find objects by primary key + * + * $objs = $c->findPks(array(12, 56, 832), $con); + * + * @param array $keys Primary keys to use for the query + * @param ConnectionInterface $con an optional connection object + * + * @return ObjectCollection|array|mixed the list of results, formatted by the current formatter + */ + public function findPks($keys, $con = null) + { + if (null === $con) { + $con = Propel::getServiceContainer()->getReadConnection($this->getDbName()); + } + $this->basePreSelect($con); + $criteria = $this->isKeepQuery() ? clone $this : $this; + $dataFetcher = $criteria + ->filterByPrimaryKeys($keys) + ->doSelect($con); + + return $criteria->getFormatter()->init($criteria)->format($dataFetcher); + } + + /** + * Filter the query by primary key + * + * @param mixed $key Primary key to use for the query + * + * @return ChildOrderAddressColissimoPickupPointQuery The current query, for fluid interface + */ + public function filterByPrimaryKey($key) + { + + return $this->addUsingAlias(OrderAddressColissimoPickupPointTableMap::ID, $key, Criteria::EQUAL); + } + + /** + * Filter the query by a list of primary keys + * + * @param array $keys The list of primary key to use for the query + * + * @return ChildOrderAddressColissimoPickupPointQuery The current query, for fluid interface + */ + public function filterByPrimaryKeys($keys) + { + + return $this->addUsingAlias(OrderAddressColissimoPickupPointTableMap::ID, $keys, Criteria::IN); + } + + /** + * Filter the query on the id column + * + * Example usage: + * + * $query->filterById(1234); // WHERE id = 1234 + * $query->filterById(array(12, 34)); // WHERE id IN (12, 34) + * $query->filterById(array('min' => 12)); // WHERE id > 12 + * + * + * @see filterByOrderAddress() + * + * @param mixed $id The value to use as filter. + * Use scalar values for equality. + * Use array values for in_array() equivalent. + * Use associative array('min' => $minValue, 'max' => $maxValue) for intervals. + * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL + * + * @return ChildOrderAddressColissimoPickupPointQuery The current query, for fluid interface + */ + public function filterById($id = null, $comparison = null) + { + if (is_array($id)) { + $useMinMax = false; + if (isset($id['min'])) { + $this->addUsingAlias(OrderAddressColissimoPickupPointTableMap::ID, $id['min'], Criteria::GREATER_EQUAL); + $useMinMax = true; + } + if (isset($id['max'])) { + $this->addUsingAlias(OrderAddressColissimoPickupPointTableMap::ID, $id['max'], Criteria::LESS_EQUAL); + $useMinMax = true; + } + if ($useMinMax) { + return $this; + } + if (null === $comparison) { + $comparison = Criteria::IN; + } + } + + return $this->addUsingAlias(OrderAddressColissimoPickupPointTableMap::ID, $id, $comparison); + } + + /** + * Filter the query on the code column + * + * Example usage: + * + * $query->filterByCode('fooValue'); // WHERE code = 'fooValue' + * $query->filterByCode('%fooValue%'); // WHERE code LIKE '%fooValue%' + * + * + * @param string $code The value to use as filter. + * Accepts wildcards (* and % trigger a LIKE) + * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL + * + * @return ChildOrderAddressColissimoPickupPointQuery The current query, for fluid interface + */ + public function filterByCode($code = null, $comparison = null) + { + if (null === $comparison) { + if (is_array($code)) { + $comparison = Criteria::IN; + } elseif (preg_match('/[\%\*]/', $code)) { + $code = str_replace('*', '%', $code); + $comparison = Criteria::LIKE; + } + } + + return $this->addUsingAlias(OrderAddressColissimoPickupPointTableMap::CODE, $code, $comparison); + } + + /** + * Filter the query on the type column + * + * Example usage: + * + * $query->filterByType('fooValue'); // WHERE type = 'fooValue' + * $query->filterByType('%fooValue%'); // WHERE type LIKE '%fooValue%' + * + * + * @param string $type The value to use as filter. + * Accepts wildcards (* and % trigger a LIKE) + * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL + * + * @return ChildOrderAddressColissimoPickupPointQuery The current query, for fluid interface + */ + public function filterByType($type = null, $comparison = null) + { + if (null === $comparison) { + if (is_array($type)) { + $comparison = Criteria::IN; + } elseif (preg_match('/[\%\*]/', $type)) { + $type = str_replace('*', '%', $type); + $comparison = Criteria::LIKE; + } + } + + return $this->addUsingAlias(OrderAddressColissimoPickupPointTableMap::TYPE, $type, $comparison); + } + + /** + * Filter the query by a related \ColissimoPickupPoint\Model\Thelia\Model\OrderAddress object + * + * @param \ColissimoPickupPoint\Model\Thelia\Model\OrderAddress|ObjectCollection $orderAddress The related object(s) to use as filter + * @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL + * + * @return ChildOrderAddressColissimoPickupPointQuery The current query, for fluid interface + */ + public function filterByOrderAddress($orderAddress, $comparison = null) + { + if ($orderAddress instanceof \ColissimoPickupPoint\Model\Thelia\Model\OrderAddress) { + return $this + ->addUsingAlias(OrderAddressColissimoPickupPointTableMap::ID, $orderAddress->getId(), $comparison); + } elseif ($orderAddress instanceof ObjectCollection) { + if (null === $comparison) { + $comparison = Criteria::IN; + } + + return $this + ->addUsingAlias(OrderAddressColissimoPickupPointTableMap::ID, $orderAddress->toKeyValue('PrimaryKey', 'Id'), $comparison); + } else { + throw new PropelException('filterByOrderAddress() only accepts arguments of type \ColissimoPickupPoint\Model\Thelia\Model\OrderAddress or Collection'); + } + } + + /** + * Adds a JOIN clause to the query using the OrderAddress relation + * + * @param string $relationAlias optional alias for the relation + * @param string $joinType Accepted values are null, 'left join', 'right join', 'inner join' + * + * @return ChildOrderAddressColissimoPickupPointQuery The current query, for fluid interface + */ + public function joinOrderAddress($relationAlias = null, $joinType = Criteria::INNER_JOIN) + { + $tableMap = $this->getTableMap(); + $relationMap = $tableMap->getRelation('OrderAddress'); + + // create a ModelJoin object for this join + $join = new ModelJoin(); + $join->setJoinType($joinType); + $join->setRelationMap($relationMap, $this->useAliasInSQL ? $this->getModelAlias() : null, $relationAlias); + if ($previousJoin = $this->getPreviousJoin()) { + $join->setPreviousJoin($previousJoin); + } + + // add the ModelJoin to the current object + if ($relationAlias) { + $this->addAlias($relationAlias, $relationMap->getRightTable()->getName()); + $this->addJoinObject($join, $relationAlias); + } else { + $this->addJoinObject($join, 'OrderAddress'); + } + + return $this; + } + + /** + * Use the OrderAddress relation OrderAddress object + * + * @see useQuery() + * + * @param string $relationAlias optional alias for the relation, + * to be used as main alias in the secondary query + * @param string $joinType Accepted values are null, 'left join', 'right join', 'inner join' + * + * @return \ColissimoPickupPoint\Model\Thelia\Model\OrderAddressQuery A secondary query class using the current class as primary query + */ + public function useOrderAddressQuery($relationAlias = null, $joinType = Criteria::INNER_JOIN) + { + return $this + ->joinOrderAddress($relationAlias, $joinType) + ->useQuery($relationAlias ? $relationAlias : 'OrderAddress', '\ColissimoPickupPoint\Model\Thelia\Model\OrderAddressQuery'); + } + + /** + * Exclude object from result + * + * @param ChildOrderAddressColissimoPickupPoint $orderAddressColissimoPickupPoint Object to remove from the list of results + * + * @return ChildOrderAddressColissimoPickupPointQuery The current query, for fluid interface + */ + public function prune($orderAddressColissimoPickupPoint = null) + { + if ($orderAddressColissimoPickupPoint) { + $this->addUsingAlias(OrderAddressColissimoPickupPointTableMap::ID, $orderAddressColissimoPickupPoint->getId(), Criteria::NOT_EQUAL); + } + + return $this; + } + + /** + * Deletes all rows from the order_address_colissimo_pickup_point table. + * + * @param ConnectionInterface $con the connection to use + * @return int The number of affected rows (if supported by underlying database driver). + */ + public function doDeleteAll(ConnectionInterface $con = null) + { + if (null === $con) { + $con = Propel::getServiceContainer()->getWriteConnection(OrderAddressColissimoPickupPointTableMap::DATABASE_NAME); + } + $affectedRows = 0; // initialize var to track total num of affected rows + try { + // use transaction because $criteria could contain info + // for more than one table or we could emulating ON DELETE CASCADE, etc. + $con->beginTransaction(); + $affectedRows += parent::doDeleteAll($con); + // Because this db requires some delete cascade/set null emulation, we have to + // clear the cached instance *after* the emulation has happened (since + // instances get re-added by the select statement contained therein). + OrderAddressColissimoPickupPointTableMap::clearInstancePool(); + OrderAddressColissimoPickupPointTableMap::clearRelatedInstancePool(); + + $con->commit(); + } catch (PropelException $e) { + $con->rollBack(); + throw $e; + } + + return $affectedRows; + } + + /** + * Performs a DELETE on the database, given a ChildOrderAddressColissimoPickupPoint or Criteria object OR a primary key value. + * + * @param mixed $values Criteria or ChildOrderAddressColissimoPickupPoint object or primary key or array of primary keys + * which is used to create the DELETE statement + * @param ConnectionInterface $con the connection to use + * @return int The number of affected rows (if supported by underlying database driver). This includes CASCADE-related rows + * if supported by native driver or if emulated using Propel. + * @throws PropelException Any exceptions caught during processing will be + * rethrown wrapped into a PropelException. + */ + public function delete(ConnectionInterface $con = null) + { + if (null === $con) { + $con = Propel::getServiceContainer()->getWriteConnection(OrderAddressColissimoPickupPointTableMap::DATABASE_NAME); + } + + $criteria = $this; + + // Set the correct dbName + $criteria->setDbName(OrderAddressColissimoPickupPointTableMap::DATABASE_NAME); + + $affectedRows = 0; // initialize var to track total num of affected rows + + try { + // use transaction because $criteria could contain info + // for more than one table or we could emulating ON DELETE CASCADE, etc. + $con->beginTransaction(); + + + OrderAddressColissimoPickupPointTableMap::removeInstanceFromPool($criteria); + + $affectedRows += ModelCriteria::delete($con); + OrderAddressColissimoPickupPointTableMap::clearRelatedInstancePool(); + $con->commit(); + + return $affectedRows; + } catch (PropelException $e) { + $con->rollBack(); + throw $e; + } + } + +} // OrderAddressColissimoPickupPointQuery diff --git a/local/modules/ColissimoPickupPoint/Model/ColissimoPickupPointAreaFreeshipping.php b/local/modules/ColissimoPickupPoint/Model/ColissimoPickupPointAreaFreeshipping.php new file mode 100644 index 00000000..7c2fd1fa --- /dev/null +++ b/local/modules/ColissimoPickupPoint/Model/ColissimoPickupPointAreaFreeshipping.php @@ -0,0 +1,10 @@ + array('Id', 'TitleId', 'Company', 'Firstname', 'Lastname', 'Address1', 'Address2', 'Address3', 'Zipcode', 'City', 'CountryId', 'Code', 'Type', 'Cellphone', ), + self::TYPE_STUDLYPHPNAME => array('id', 'titleId', 'company', 'firstname', 'lastname', 'address1', 'address2', 'address3', 'zipcode', 'city', 'countryId', 'code', 'type', 'cellphone', ), + self::TYPE_COLNAME => array(AddressColissimoPickupPointTableMap::ID, AddressColissimoPickupPointTableMap::TITLE_ID, AddressColissimoPickupPointTableMap::COMPANY, AddressColissimoPickupPointTableMap::FIRSTNAME, AddressColissimoPickupPointTableMap::LASTNAME, AddressColissimoPickupPointTableMap::ADDRESS1, AddressColissimoPickupPointTableMap::ADDRESS2, AddressColissimoPickupPointTableMap::ADDRESS3, AddressColissimoPickupPointTableMap::ZIPCODE, AddressColissimoPickupPointTableMap::CITY, AddressColissimoPickupPointTableMap::COUNTRY_ID, AddressColissimoPickupPointTableMap::CODE, AddressColissimoPickupPointTableMap::TYPE, AddressColissimoPickupPointTableMap::CELLPHONE, ), + self::TYPE_RAW_COLNAME => array('ID', 'TITLE_ID', 'COMPANY', 'FIRSTNAME', 'LASTNAME', 'ADDRESS1', 'ADDRESS2', 'ADDRESS3', 'ZIPCODE', 'CITY', 'COUNTRY_ID', 'CODE', 'TYPE', 'CELLPHONE', ), + self::TYPE_FIELDNAME => array('id', 'title_id', 'company', 'firstname', 'lastname', 'address1', 'address2', 'address3', 'zipcode', 'city', 'country_id', 'code', 'type', 'cellphone', ), + self::TYPE_NUM => array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, ) + ); + + /** + * holds an array of keys for quick access to the fieldnames array + * + * first dimension keys are the type constants + * e.g. self::$fieldKeys[self::TYPE_PHPNAME]['Id'] = 0 + */ + protected static $fieldKeys = array ( + self::TYPE_PHPNAME => array('Id' => 0, 'TitleId' => 1, 'Company' => 2, 'Firstname' => 3, 'Lastname' => 4, 'Address1' => 5, 'Address2' => 6, 'Address3' => 7, 'Zipcode' => 8, 'City' => 9, 'CountryId' => 10, 'Code' => 11, 'Type' => 12, 'Cellphone' => 13, ), + self::TYPE_STUDLYPHPNAME => array('id' => 0, 'titleId' => 1, 'company' => 2, 'firstname' => 3, 'lastname' => 4, 'address1' => 5, 'address2' => 6, 'address3' => 7, 'zipcode' => 8, 'city' => 9, 'countryId' => 10, 'code' => 11, 'type' => 12, 'cellphone' => 13, ), + self::TYPE_COLNAME => array(AddressColissimoPickupPointTableMap::ID => 0, AddressColissimoPickupPointTableMap::TITLE_ID => 1, AddressColissimoPickupPointTableMap::COMPANY => 2, AddressColissimoPickupPointTableMap::FIRSTNAME => 3, AddressColissimoPickupPointTableMap::LASTNAME => 4, AddressColissimoPickupPointTableMap::ADDRESS1 => 5, AddressColissimoPickupPointTableMap::ADDRESS2 => 6, AddressColissimoPickupPointTableMap::ADDRESS3 => 7, AddressColissimoPickupPointTableMap::ZIPCODE => 8, AddressColissimoPickupPointTableMap::CITY => 9, AddressColissimoPickupPointTableMap::COUNTRY_ID => 10, AddressColissimoPickupPointTableMap::CODE => 11, AddressColissimoPickupPointTableMap::TYPE => 12, AddressColissimoPickupPointTableMap::CELLPHONE => 13, ), + self::TYPE_RAW_COLNAME => array('ID' => 0, 'TITLE_ID' => 1, 'COMPANY' => 2, 'FIRSTNAME' => 3, 'LASTNAME' => 4, 'ADDRESS1' => 5, 'ADDRESS2' => 6, 'ADDRESS3' => 7, 'ZIPCODE' => 8, 'CITY' => 9, 'COUNTRY_ID' => 10, 'CODE' => 11, 'TYPE' => 12, 'CELLPHONE' => 13, ), + self::TYPE_FIELDNAME => array('id' => 0, 'title_id' => 1, 'company' => 2, 'firstname' => 3, 'lastname' => 4, 'address1' => 5, 'address2' => 6, 'address3' => 7, 'zipcode' => 8, 'city' => 9, 'country_id' => 10, 'code' => 11, 'type' => 12, 'cellphone' => 13, ), + self::TYPE_NUM => array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, ) + ); + + /** + * Initialize the table attributes and columns + * Relations are not initialized by this method since they are lazy loaded + * + * @return void + * @throws PropelException + */ + public function initialize() + { + // attributes + $this->setName('address_colissimo_pickup_point'); + $this->setPhpName('AddressColissimoPickupPoint'); + $this->setClassName('\\ColissimoPickupPoint\\Model\\AddressColissimoPickupPoint'); + $this->setPackage('ColissimoPickupPoint.Model'); + $this->setUseIdGenerator(false); + // columns + $this->addPrimaryKey('ID', 'Id', 'INTEGER', true, null, null); + $this->addForeignKey('TITLE_ID', 'TitleId', 'INTEGER', 'customer_title', 'ID', true, null, null); + $this->addColumn('COMPANY', 'Company', 'VARCHAR', false, 255, null); + $this->addColumn('FIRSTNAME', 'Firstname', 'VARCHAR', true, 255, null); + $this->addColumn('LASTNAME', 'Lastname', 'VARCHAR', true, 255, null); + $this->addColumn('ADDRESS1', 'Address1', 'VARCHAR', true, 255, null); + $this->addColumn('ADDRESS2', 'Address2', 'VARCHAR', true, 255, null); + $this->addColumn('ADDRESS3', 'Address3', 'VARCHAR', true, 255, null); + $this->addColumn('ZIPCODE', 'Zipcode', 'VARCHAR', true, 10, null); + $this->addColumn('CITY', 'City', 'VARCHAR', true, 255, null); + $this->addForeignKey('COUNTRY_ID', 'CountryId', 'INTEGER', 'country', 'ID', true, null, null); + $this->addColumn('CODE', 'Code', 'VARCHAR', true, 10, null); + $this->addColumn('TYPE', 'Type', 'VARCHAR', true, 10, null); + $this->addColumn('CELLPHONE', 'Cellphone', 'VARCHAR', false, 20, null); + } // initialize() + + /** + * Build the RelationMap objects for this table relationships + */ + public function buildRelations() + { + $this->addRelation('CustomerTitle', '\\ColissimoPickupPoint\\Model\\Thelia\\Model\\CustomerTitle', RelationMap::MANY_TO_ONE, array('title_id' => 'id', ), 'RESTRICT', 'RESTRICT'); + $this->addRelation('Country', '\\ColissimoPickupPoint\\Model\\Thelia\\Model\\Country', RelationMap::MANY_TO_ONE, array('country_id' => 'id', ), 'RESTRICT', 'RESTRICT'); + } // buildRelations() + + /** + * Retrieves a string version of the primary key from the DB resultset row that can be used to uniquely identify a row in this table. + * + * For tables with a single-column primary key, that simple pkey value will be returned. For tables with + * a multi-column primary key, a serialize()d version of the primary key will be returned. + * + * @param array $row resultset row. + * @param int $offset The 0-based offset for reading from the resultset row. + * @param string $indexType One of the class type constants TableMap::TYPE_PHPNAME, TableMap::TYPE_STUDLYPHPNAME + * TableMap::TYPE_COLNAME, TableMap::TYPE_FIELDNAME, TableMap::TYPE_NUM + */ + public static function getPrimaryKeyHashFromRow($row, $offset = 0, $indexType = TableMap::TYPE_NUM) + { + // If the PK cannot be derived from the row, return NULL. + if ($row[TableMap::TYPE_NUM == $indexType ? 0 + $offset : static::translateFieldName('Id', TableMap::TYPE_PHPNAME, $indexType)] === null) { + return null; + } + + return (string) $row[TableMap::TYPE_NUM == $indexType ? 0 + $offset : static::translateFieldName('Id', TableMap::TYPE_PHPNAME, $indexType)]; + } + + /** + * Retrieves the primary key from the DB resultset row + * For tables with a single-column primary key, that simple pkey value will be returned. For tables with + * a multi-column primary key, an array of the primary key columns will be returned. + * + * @param array $row resultset row. + * @param int $offset The 0-based offset for reading from the resultset row. + * @param string $indexType One of the class type constants TableMap::TYPE_PHPNAME, TableMap::TYPE_STUDLYPHPNAME + * TableMap::TYPE_COLNAME, TableMap::TYPE_FIELDNAME, TableMap::TYPE_NUM + * + * @return mixed The primary key of the row + */ + public static function getPrimaryKeyFromRow($row, $offset = 0, $indexType = TableMap::TYPE_NUM) + { + + return (int) $row[ + $indexType == TableMap::TYPE_NUM + ? 0 + $offset + : self::translateFieldName('Id', TableMap::TYPE_PHPNAME, $indexType) + ]; + } + + /** + * The class that the tableMap will make instances of. + * + * If $withPrefix is true, the returned path + * uses a dot-path notation which is translated into a path + * relative to a location on the PHP include_path. + * (e.g. path.to.MyClass -> 'path/to/MyClass.php') + * + * @param boolean $withPrefix Whether or not to return the path with the class name + * @return string path.to.ClassName + */ + public static function getOMClass($withPrefix = true) + { + return $withPrefix ? AddressColissimoPickupPointTableMap::CLASS_DEFAULT : AddressColissimoPickupPointTableMap::OM_CLASS; + } + + /** + * Populates an object of the default type or an object that inherit from the default. + * + * @param array $row row returned by DataFetcher->fetch(). + * @param int $offset The 0-based offset for reading from the resultset row. + * @param string $indexType The index type of $row. Mostly DataFetcher->getIndexType(). + One of the class type constants TableMap::TYPE_PHPNAME, TableMap::TYPE_STUDLYPHPNAME + * TableMap::TYPE_COLNAME, TableMap::TYPE_FIELDNAME, TableMap::TYPE_NUM. + * + * @throws PropelException Any exceptions caught during processing will be + * rethrown wrapped into a PropelException. + * @return array (AddressColissimoPickupPoint object, last column rank) + */ + public static function populateObject($row, $offset = 0, $indexType = TableMap::TYPE_NUM) + { + $key = AddressColissimoPickupPointTableMap::getPrimaryKeyHashFromRow($row, $offset, $indexType); + if (null !== ($obj = AddressColissimoPickupPointTableMap::getInstanceFromPool($key))) { + // We no longer rehydrate the object, since this can cause data loss. + // See http://www.propelorm.org/ticket/509 + // $obj->hydrate($row, $offset, true); // rehydrate + $col = $offset + AddressColissimoPickupPointTableMap::NUM_HYDRATE_COLUMNS; + } else { + $cls = AddressColissimoPickupPointTableMap::OM_CLASS; + $obj = new $cls(); + $col = $obj->hydrate($row, $offset, false, $indexType); + AddressColissimoPickupPointTableMap::addInstanceToPool($obj, $key); + } + + return array($obj, $col); + } + + /** + * The returned array will contain objects of the default type or + * objects that inherit from the default. + * + * @param DataFetcherInterface $dataFetcher + * @return array + * @throws PropelException Any exceptions caught during processing will be + * rethrown wrapped into a PropelException. + */ + public static function populateObjects(DataFetcherInterface $dataFetcher) + { + $results = array(); + + // set the class once to avoid overhead in the loop + $cls = static::getOMClass(false); + // populate the object(s) + while ($row = $dataFetcher->fetch()) { + $key = AddressColissimoPickupPointTableMap::getPrimaryKeyHashFromRow($row, 0, $dataFetcher->getIndexType()); + if (null !== ($obj = AddressColissimoPickupPointTableMap::getInstanceFromPool($key))) { + // We no longer rehydrate the object, since this can cause data loss. + // See http://www.propelorm.org/ticket/509 + // $obj->hydrate($row, 0, true); // rehydrate + $results[] = $obj; + } else { + $obj = new $cls(); + $obj->hydrate($row); + $results[] = $obj; + AddressColissimoPickupPointTableMap::addInstanceToPool($obj, $key); + } // if key exists + } + + return $results; + } + /** + * Add all the columns needed to create a new object. + * + * Note: any columns that were marked with lazyLoad="true" in the + * XML schema will not be added to the select list and only loaded + * on demand. + * + * @param Criteria $criteria object containing the columns to add. + * @param string $alias optional table alias + * @throws PropelException Any exceptions caught during processing will be + * rethrown wrapped into a PropelException. + */ + public static function addSelectColumns(Criteria $criteria, $alias = null) + { + if (null === $alias) { + $criteria->addSelectColumn(AddressColissimoPickupPointTableMap::ID); + $criteria->addSelectColumn(AddressColissimoPickupPointTableMap::TITLE_ID); + $criteria->addSelectColumn(AddressColissimoPickupPointTableMap::COMPANY); + $criteria->addSelectColumn(AddressColissimoPickupPointTableMap::FIRSTNAME); + $criteria->addSelectColumn(AddressColissimoPickupPointTableMap::LASTNAME); + $criteria->addSelectColumn(AddressColissimoPickupPointTableMap::ADDRESS1); + $criteria->addSelectColumn(AddressColissimoPickupPointTableMap::ADDRESS2); + $criteria->addSelectColumn(AddressColissimoPickupPointTableMap::ADDRESS3); + $criteria->addSelectColumn(AddressColissimoPickupPointTableMap::ZIPCODE); + $criteria->addSelectColumn(AddressColissimoPickupPointTableMap::CITY); + $criteria->addSelectColumn(AddressColissimoPickupPointTableMap::COUNTRY_ID); + $criteria->addSelectColumn(AddressColissimoPickupPointTableMap::CODE); + $criteria->addSelectColumn(AddressColissimoPickupPointTableMap::TYPE); + $criteria->addSelectColumn(AddressColissimoPickupPointTableMap::CELLPHONE); + } else { + $criteria->addSelectColumn($alias . '.ID'); + $criteria->addSelectColumn($alias . '.TITLE_ID'); + $criteria->addSelectColumn($alias . '.COMPANY'); + $criteria->addSelectColumn($alias . '.FIRSTNAME'); + $criteria->addSelectColumn($alias . '.LASTNAME'); + $criteria->addSelectColumn($alias . '.ADDRESS1'); + $criteria->addSelectColumn($alias . '.ADDRESS2'); + $criteria->addSelectColumn($alias . '.ADDRESS3'); + $criteria->addSelectColumn($alias . '.ZIPCODE'); + $criteria->addSelectColumn($alias . '.CITY'); + $criteria->addSelectColumn($alias . '.COUNTRY_ID'); + $criteria->addSelectColumn($alias . '.CODE'); + $criteria->addSelectColumn($alias . '.TYPE'); + $criteria->addSelectColumn($alias . '.CELLPHONE'); + } + } + + /** + * Returns the TableMap related to this object. + * This method is not needed for general use but a specific application could have a need. + * @return TableMap + * @throws PropelException Any exceptions caught during processing will be + * rethrown wrapped into a PropelException. + */ + public static function getTableMap() + { + return Propel::getServiceContainer()->getDatabaseMap(AddressColissimoPickupPointTableMap::DATABASE_NAME)->getTable(AddressColissimoPickupPointTableMap::TABLE_NAME); + } + + /** + * Add a TableMap instance to the database for this tableMap class. + */ + public static function buildTableMap() + { + $dbMap = Propel::getServiceContainer()->getDatabaseMap(AddressColissimoPickupPointTableMap::DATABASE_NAME); + if (!$dbMap->hasTable(AddressColissimoPickupPointTableMap::TABLE_NAME)) { + $dbMap->addTableObject(new AddressColissimoPickupPointTableMap()); + } + } + + /** + * Performs a DELETE on the database, given a AddressColissimoPickupPoint or Criteria object OR a primary key value. + * + * @param mixed $values Criteria or AddressColissimoPickupPoint object or primary key or array of primary keys + * which is used to create the DELETE statement + * @param ConnectionInterface $con the connection to use + * @return int The number of affected rows (if supported by underlying database driver). This includes CASCADE-related rows + * if supported by native driver or if emulated using Propel. + * @throws PropelException Any exceptions caught during processing will be + * rethrown wrapped into a PropelException. + */ + public static function doDelete($values, ConnectionInterface $con = null) + { + if (null === $con) { + $con = Propel::getServiceContainer()->getWriteConnection(AddressColissimoPickupPointTableMap::DATABASE_NAME); + } + + if ($values instanceof Criteria) { + // rename for clarity + $criteria = $values; + } elseif ($values instanceof \ColissimoPickupPoint\Model\AddressColissimoPickupPoint) { // it's a model object + // create criteria based on pk values + $criteria = $values->buildPkeyCriteria(); + } else { // it's a primary key, or an array of pks + $criteria = new Criteria(AddressColissimoPickupPointTableMap::DATABASE_NAME); + $criteria->add(AddressColissimoPickupPointTableMap::ID, (array) $values, Criteria::IN); + } + + $query = AddressColissimoPickupPointQuery::create()->mergeWith($criteria); + + if ($values instanceof Criteria) { AddressColissimoPickupPointTableMap::clearInstancePool(); + } elseif (!is_object($values)) { // it's a primary key, or an array of pks + foreach ((array) $values as $singleval) { AddressColissimoPickupPointTableMap::removeInstanceFromPool($singleval); + } + } + + return $query->delete($con); + } + + /** + * Deletes all rows from the address_colissimo_pickup_point table. + * + * @param ConnectionInterface $con the connection to use + * @return int The number of affected rows (if supported by underlying database driver). + */ + public static function doDeleteAll(ConnectionInterface $con = null) + { + return AddressColissimoPickupPointQuery::create()->doDeleteAll($con); + } + + /** + * Performs an INSERT on the database, given a AddressColissimoPickupPoint or Criteria object. + * + * @param mixed $criteria Criteria or AddressColissimoPickupPoint object containing data that is used to create the INSERT statement. + * @param ConnectionInterface $con the ConnectionInterface connection to use + * @return mixed The new primary key. + * @throws PropelException Any exceptions caught during processing will be + * rethrown wrapped into a PropelException. + */ + public static function doInsert($criteria, ConnectionInterface $con = null) + { + if (null === $con) { + $con = Propel::getServiceContainer()->getWriteConnection(AddressColissimoPickupPointTableMap::DATABASE_NAME); + } + + if ($criteria instanceof Criteria) { + $criteria = clone $criteria; // rename for clarity + } else { + $criteria = $criteria->buildCriteria(); // build Criteria from AddressColissimoPickupPoint object + } + + + // Set the correct dbName + $query = AddressColissimoPickupPointQuery::create()->mergeWith($criteria); + + try { + // use transaction because $criteria could contain info + // for more than one table (I guess, conceivably) + $con->beginTransaction(); + $pk = $query->doInsert($con); + $con->commit(); + } catch (PropelException $e) { + $con->rollBack(); + throw $e; + } + + return $pk; + } + +} // AddressColissimoPickupPointTableMap +// This is the static code needed to register the TableMap for this table with the main Propel class. +// +AddressColissimoPickupPointTableMap::buildTableMap(); diff --git a/local/modules/ColissimoPickupPoint/Model/Map/ColissimoPickupPointAreaFreeshippingTableMap.php b/local/modules/ColissimoPickupPoint/Model/Map/ColissimoPickupPointAreaFreeshippingTableMap.php new file mode 100644 index 00000000..8933c601 --- /dev/null +++ b/local/modules/ColissimoPickupPoint/Model/Map/ColissimoPickupPointAreaFreeshippingTableMap.php @@ -0,0 +1,419 @@ + array('Id', 'AreaId', 'CartAmount', ), + self::TYPE_STUDLYPHPNAME => array('id', 'areaId', 'cartAmount', ), + self::TYPE_COLNAME => array(ColissimoPickupPointAreaFreeshippingTableMap::ID, ColissimoPickupPointAreaFreeshippingTableMap::AREA_ID, ColissimoPickupPointAreaFreeshippingTableMap::CART_AMOUNT, ), + self::TYPE_RAW_COLNAME => array('ID', 'AREA_ID', 'CART_AMOUNT', ), + self::TYPE_FIELDNAME => array('id', 'area_id', 'cart_amount', ), + self::TYPE_NUM => array(0, 1, 2, ) + ); + + /** + * holds an array of keys for quick access to the fieldnames array + * + * first dimension keys are the type constants + * e.g. self::$fieldKeys[self::TYPE_PHPNAME]['Id'] = 0 + */ + protected static $fieldKeys = array ( + self::TYPE_PHPNAME => array('Id' => 0, 'AreaId' => 1, 'CartAmount' => 2, ), + self::TYPE_STUDLYPHPNAME => array('id' => 0, 'areaId' => 1, 'cartAmount' => 2, ), + self::TYPE_COLNAME => array(ColissimoPickupPointAreaFreeshippingTableMap::ID => 0, ColissimoPickupPointAreaFreeshippingTableMap::AREA_ID => 1, ColissimoPickupPointAreaFreeshippingTableMap::CART_AMOUNT => 2, ), + self::TYPE_RAW_COLNAME => array('ID' => 0, 'AREA_ID' => 1, 'CART_AMOUNT' => 2, ), + self::TYPE_FIELDNAME => array('id' => 0, 'area_id' => 1, 'cart_amount' => 2, ), + self::TYPE_NUM => array(0, 1, 2, ) + ); + + /** + * Initialize the table attributes and columns + * Relations are not initialized by this method since they are lazy loaded + * + * @return void + * @throws PropelException + */ + public function initialize() + { + // attributes + $this->setName('colissimo_pickup_point_area_freeshipping'); + $this->setPhpName('ColissimoPickupPointAreaFreeshipping'); + $this->setClassName('\\ColissimoPickupPoint\\Model\\ColissimoPickupPointAreaFreeshipping'); + $this->setPackage('ColissimoPickupPoint.Model'); + $this->setUseIdGenerator(true); + // columns + $this->addPrimaryKey('ID', 'Id', 'INTEGER', true, null, null); + $this->addForeignKey('AREA_ID', 'AreaId', 'INTEGER', 'area', 'ID', true, null, null); + $this->addColumn('CART_AMOUNT', 'CartAmount', 'DECIMAL', false, 18, 0); + } // initialize() + + /** + * Build the RelationMap objects for this table relationships + */ + public function buildRelations() + { + $this->addRelation('Area', '\\ColissimoPickupPoint\\Model\\Thelia\\Model\\Area', RelationMap::MANY_TO_ONE, array('area_id' => 'id', ), 'RESTRICT', 'RESTRICT'); + } // buildRelations() + + /** + * Retrieves a string version of the primary key from the DB resultset row that can be used to uniquely identify a row in this table. + * + * For tables with a single-column primary key, that simple pkey value will be returned. For tables with + * a multi-column primary key, a serialize()d version of the primary key will be returned. + * + * @param array $row resultset row. + * @param int $offset The 0-based offset for reading from the resultset row. + * @param string $indexType One of the class type constants TableMap::TYPE_PHPNAME, TableMap::TYPE_STUDLYPHPNAME + * TableMap::TYPE_COLNAME, TableMap::TYPE_FIELDNAME, TableMap::TYPE_NUM + */ + public static function getPrimaryKeyHashFromRow($row, $offset = 0, $indexType = TableMap::TYPE_NUM) + { + // If the PK cannot be derived from the row, return NULL. + if ($row[TableMap::TYPE_NUM == $indexType ? 0 + $offset : static::translateFieldName('Id', TableMap::TYPE_PHPNAME, $indexType)] === null) { + return null; + } + + return (string) $row[TableMap::TYPE_NUM == $indexType ? 0 + $offset : static::translateFieldName('Id', TableMap::TYPE_PHPNAME, $indexType)]; + } + + /** + * Retrieves the primary key from the DB resultset row + * For tables with a single-column primary key, that simple pkey value will be returned. For tables with + * a multi-column primary key, an array of the primary key columns will be returned. + * + * @param array $row resultset row. + * @param int $offset The 0-based offset for reading from the resultset row. + * @param string $indexType One of the class type constants TableMap::TYPE_PHPNAME, TableMap::TYPE_STUDLYPHPNAME + * TableMap::TYPE_COLNAME, TableMap::TYPE_FIELDNAME, TableMap::TYPE_NUM + * + * @return mixed The primary key of the row + */ + public static function getPrimaryKeyFromRow($row, $offset = 0, $indexType = TableMap::TYPE_NUM) + { + + return (int) $row[ + $indexType == TableMap::TYPE_NUM + ? 0 + $offset + : self::translateFieldName('Id', TableMap::TYPE_PHPNAME, $indexType) + ]; + } + + /** + * The class that the tableMap will make instances of. + * + * If $withPrefix is true, the returned path + * uses a dot-path notation which is translated into a path + * relative to a location on the PHP include_path. + * (e.g. path.to.MyClass -> 'path/to/MyClass.php') + * + * @param boolean $withPrefix Whether or not to return the path with the class name + * @return string path.to.ClassName + */ + public static function getOMClass($withPrefix = true) + { + return $withPrefix ? ColissimoPickupPointAreaFreeshippingTableMap::CLASS_DEFAULT : ColissimoPickupPointAreaFreeshippingTableMap::OM_CLASS; + } + + /** + * Populates an object of the default type or an object that inherit from the default. + * + * @param array $row row returned by DataFetcher->fetch(). + * @param int $offset The 0-based offset for reading from the resultset row. + * @param string $indexType The index type of $row. Mostly DataFetcher->getIndexType(). + One of the class type constants TableMap::TYPE_PHPNAME, TableMap::TYPE_STUDLYPHPNAME + * TableMap::TYPE_COLNAME, TableMap::TYPE_FIELDNAME, TableMap::TYPE_NUM. + * + * @throws PropelException Any exceptions caught during processing will be + * rethrown wrapped into a PropelException. + * @return array (ColissimoPickupPointAreaFreeshipping object, last column rank) + */ + public static function populateObject($row, $offset = 0, $indexType = TableMap::TYPE_NUM) + { + $key = ColissimoPickupPointAreaFreeshippingTableMap::getPrimaryKeyHashFromRow($row, $offset, $indexType); + if (null !== ($obj = ColissimoPickupPointAreaFreeshippingTableMap::getInstanceFromPool($key))) { + // We no longer rehydrate the object, since this can cause data loss. + // See http://www.propelorm.org/ticket/509 + // $obj->hydrate($row, $offset, true); // rehydrate + $col = $offset + ColissimoPickupPointAreaFreeshippingTableMap::NUM_HYDRATE_COLUMNS; + } else { + $cls = ColissimoPickupPointAreaFreeshippingTableMap::OM_CLASS; + $obj = new $cls(); + $col = $obj->hydrate($row, $offset, false, $indexType); + ColissimoPickupPointAreaFreeshippingTableMap::addInstanceToPool($obj, $key); + } + + return array($obj, $col); + } + + /** + * The returned array will contain objects of the default type or + * objects that inherit from the default. + * + * @param DataFetcherInterface $dataFetcher + * @return array + * @throws PropelException Any exceptions caught during processing will be + * rethrown wrapped into a PropelException. + */ + public static function populateObjects(DataFetcherInterface $dataFetcher) + { + $results = array(); + + // set the class once to avoid overhead in the loop + $cls = static::getOMClass(false); + // populate the object(s) + while ($row = $dataFetcher->fetch()) { + $key = ColissimoPickupPointAreaFreeshippingTableMap::getPrimaryKeyHashFromRow($row, 0, $dataFetcher->getIndexType()); + if (null !== ($obj = ColissimoPickupPointAreaFreeshippingTableMap::getInstanceFromPool($key))) { + // We no longer rehydrate the object, since this can cause data loss. + // See http://www.propelorm.org/ticket/509 + // $obj->hydrate($row, 0, true); // rehydrate + $results[] = $obj; + } else { + $obj = new $cls(); + $obj->hydrate($row); + $results[] = $obj; + ColissimoPickupPointAreaFreeshippingTableMap::addInstanceToPool($obj, $key); + } // if key exists + } + + return $results; + } + /** + * Add all the columns needed to create a new object. + * + * Note: any columns that were marked with lazyLoad="true" in the + * XML schema will not be added to the select list and only loaded + * on demand. + * + * @param Criteria $criteria object containing the columns to add. + * @param string $alias optional table alias + * @throws PropelException Any exceptions caught during processing will be + * rethrown wrapped into a PropelException. + */ + public static function addSelectColumns(Criteria $criteria, $alias = null) + { + if (null === $alias) { + $criteria->addSelectColumn(ColissimoPickupPointAreaFreeshippingTableMap::ID); + $criteria->addSelectColumn(ColissimoPickupPointAreaFreeshippingTableMap::AREA_ID); + $criteria->addSelectColumn(ColissimoPickupPointAreaFreeshippingTableMap::CART_AMOUNT); + } else { + $criteria->addSelectColumn($alias . '.ID'); + $criteria->addSelectColumn($alias . '.AREA_ID'); + $criteria->addSelectColumn($alias . '.CART_AMOUNT'); + } + } + + /** + * Returns the TableMap related to this object. + * This method is not needed for general use but a specific application could have a need. + * @return TableMap + * @throws PropelException Any exceptions caught during processing will be + * rethrown wrapped into a PropelException. + */ + public static function getTableMap() + { + return Propel::getServiceContainer()->getDatabaseMap(ColissimoPickupPointAreaFreeshippingTableMap::DATABASE_NAME)->getTable(ColissimoPickupPointAreaFreeshippingTableMap::TABLE_NAME); + } + + /** + * Add a TableMap instance to the database for this tableMap class. + */ + public static function buildTableMap() + { + $dbMap = Propel::getServiceContainer()->getDatabaseMap(ColissimoPickupPointAreaFreeshippingTableMap::DATABASE_NAME); + if (!$dbMap->hasTable(ColissimoPickupPointAreaFreeshippingTableMap::TABLE_NAME)) { + $dbMap->addTableObject(new ColissimoPickupPointAreaFreeshippingTableMap()); + } + } + + /** + * Performs a DELETE on the database, given a ColissimoPickupPointAreaFreeshipping or Criteria object OR a primary key value. + * + * @param mixed $values Criteria or ColissimoPickupPointAreaFreeshipping object or primary key or array of primary keys + * which is used to create the DELETE statement + * @param ConnectionInterface $con the connection to use + * @return int The number of affected rows (if supported by underlying database driver). This includes CASCADE-related rows + * if supported by native driver or if emulated using Propel. + * @throws PropelException Any exceptions caught during processing will be + * rethrown wrapped into a PropelException. + */ + public static function doDelete($values, ConnectionInterface $con = null) + { + if (null === $con) { + $con = Propel::getServiceContainer()->getWriteConnection(ColissimoPickupPointAreaFreeshippingTableMap::DATABASE_NAME); + } + + if ($values instanceof Criteria) { + // rename for clarity + $criteria = $values; + } elseif ($values instanceof \ColissimoPickupPoint\Model\ColissimoPickupPointAreaFreeshipping) { // it's a model object + // create criteria based on pk values + $criteria = $values->buildPkeyCriteria(); + } else { // it's a primary key, or an array of pks + $criteria = new Criteria(ColissimoPickupPointAreaFreeshippingTableMap::DATABASE_NAME); + $criteria->add(ColissimoPickupPointAreaFreeshippingTableMap::ID, (array) $values, Criteria::IN); + } + + $query = ColissimoPickupPointAreaFreeshippingQuery::create()->mergeWith($criteria); + + if ($values instanceof Criteria) { ColissimoPickupPointAreaFreeshippingTableMap::clearInstancePool(); + } elseif (!is_object($values)) { // it's a primary key, or an array of pks + foreach ((array) $values as $singleval) { ColissimoPickupPointAreaFreeshippingTableMap::removeInstanceFromPool($singleval); + } + } + + return $query->delete($con); + } + + /** + * Deletes all rows from the colissimo_pickup_point_area_freeshipping table. + * + * @param ConnectionInterface $con the connection to use + * @return int The number of affected rows (if supported by underlying database driver). + */ + public static function doDeleteAll(ConnectionInterface $con = null) + { + return ColissimoPickupPointAreaFreeshippingQuery::create()->doDeleteAll($con); + } + + /** + * Performs an INSERT on the database, given a ColissimoPickupPointAreaFreeshipping or Criteria object. + * + * @param mixed $criteria Criteria or ColissimoPickupPointAreaFreeshipping object containing data that is used to create the INSERT statement. + * @param ConnectionInterface $con the ConnectionInterface connection to use + * @return mixed The new primary key. + * @throws PropelException Any exceptions caught during processing will be + * rethrown wrapped into a PropelException. + */ + public static function doInsert($criteria, ConnectionInterface $con = null) + { + if (null === $con) { + $con = Propel::getServiceContainer()->getWriteConnection(ColissimoPickupPointAreaFreeshippingTableMap::DATABASE_NAME); + } + + if ($criteria instanceof Criteria) { + $criteria = clone $criteria; // rename for clarity + } else { + $criteria = $criteria->buildCriteria(); // build Criteria from ColissimoPickupPointAreaFreeshipping object + } + + if ($criteria->containsKey(ColissimoPickupPointAreaFreeshippingTableMap::ID) && $criteria->keyContainsValue(ColissimoPickupPointAreaFreeshippingTableMap::ID) ) { + throw new PropelException('Cannot insert a value for auto-increment primary key ('.ColissimoPickupPointAreaFreeshippingTableMap::ID.')'); + } + + + // Set the correct dbName + $query = ColissimoPickupPointAreaFreeshippingQuery::create()->mergeWith($criteria); + + try { + // use transaction because $criteria could contain info + // for more than one table (I guess, conceivably) + $con->beginTransaction(); + $pk = $query->doInsert($con); + $con->commit(); + } catch (PropelException $e) { + $con->rollBack(); + throw $e; + } + + return $pk; + } + +} // ColissimoPickupPointAreaFreeshippingTableMap +// This is the static code needed to register the TableMap for this table with the main Propel class. +// +ColissimoPickupPointAreaFreeshippingTableMap::buildTableMap(); diff --git a/local/modules/ColissimoPickupPoint/Model/Map/ColissimoPickupPointFreeshippingTableMap.php b/local/modules/ColissimoPickupPoint/Model/Map/ColissimoPickupPointFreeshippingTableMap.php new file mode 100644 index 00000000..968fa576 --- /dev/null +++ b/local/modules/ColissimoPickupPoint/Model/Map/ColissimoPickupPointFreeshippingTableMap.php @@ -0,0 +1,414 @@ + array('Id', 'Active', 'FreeshippingFrom', ), + self::TYPE_STUDLYPHPNAME => array('id', 'active', 'freeshippingFrom', ), + self::TYPE_COLNAME => array(ColissimoPickupPointFreeshippingTableMap::ID, ColissimoPickupPointFreeshippingTableMap::ACTIVE, ColissimoPickupPointFreeshippingTableMap::FREESHIPPING_FROM, ), + self::TYPE_RAW_COLNAME => array('ID', 'ACTIVE', 'FREESHIPPING_FROM', ), + self::TYPE_FIELDNAME => array('id', 'active', 'freeshipping_from', ), + self::TYPE_NUM => array(0, 1, 2, ) + ); + + /** + * holds an array of keys for quick access to the fieldnames array + * + * first dimension keys are the type constants + * e.g. self::$fieldKeys[self::TYPE_PHPNAME]['Id'] = 0 + */ + protected static $fieldKeys = array ( + self::TYPE_PHPNAME => array('Id' => 0, 'Active' => 1, 'FreeshippingFrom' => 2, ), + self::TYPE_STUDLYPHPNAME => array('id' => 0, 'active' => 1, 'freeshippingFrom' => 2, ), + self::TYPE_COLNAME => array(ColissimoPickupPointFreeshippingTableMap::ID => 0, ColissimoPickupPointFreeshippingTableMap::ACTIVE => 1, ColissimoPickupPointFreeshippingTableMap::FREESHIPPING_FROM => 2, ), + self::TYPE_RAW_COLNAME => array('ID' => 0, 'ACTIVE' => 1, 'FREESHIPPING_FROM' => 2, ), + self::TYPE_FIELDNAME => array('id' => 0, 'active' => 1, 'freeshipping_from' => 2, ), + self::TYPE_NUM => array(0, 1, 2, ) + ); + + /** + * Initialize the table attributes and columns + * Relations are not initialized by this method since they are lazy loaded + * + * @return void + * @throws PropelException + */ + public function initialize() + { + // attributes + $this->setName('colissimo_pickup_point_freeshipping'); + $this->setPhpName('ColissimoPickupPointFreeshipping'); + $this->setClassName('\\ColissimoPickupPoint\\Model\\ColissimoPickupPointFreeshipping'); + $this->setPackage('ColissimoPickupPoint.Model'); + $this->setUseIdGenerator(false); + // columns + $this->addPrimaryKey('ID', 'Id', 'INTEGER', true, null, null); + $this->addColumn('ACTIVE', 'Active', 'BOOLEAN', false, 1, false); + $this->addColumn('FREESHIPPING_FROM', 'FreeshippingFrom', 'DECIMAL', false, 18, null); + } // initialize() + + /** + * Build the RelationMap objects for this table relationships + */ + public function buildRelations() + { + } // buildRelations() + + /** + * Retrieves a string version of the primary key from the DB resultset row that can be used to uniquely identify a row in this table. + * + * For tables with a single-column primary key, that simple pkey value will be returned. For tables with + * a multi-column primary key, a serialize()d version of the primary key will be returned. + * + * @param array $row resultset row. + * @param int $offset The 0-based offset for reading from the resultset row. + * @param string $indexType One of the class type constants TableMap::TYPE_PHPNAME, TableMap::TYPE_STUDLYPHPNAME + * TableMap::TYPE_COLNAME, TableMap::TYPE_FIELDNAME, TableMap::TYPE_NUM + */ + public static function getPrimaryKeyHashFromRow($row, $offset = 0, $indexType = TableMap::TYPE_NUM) + { + // If the PK cannot be derived from the row, return NULL. + if ($row[TableMap::TYPE_NUM == $indexType ? 0 + $offset : static::translateFieldName('Id', TableMap::TYPE_PHPNAME, $indexType)] === null) { + return null; + } + + return (string) $row[TableMap::TYPE_NUM == $indexType ? 0 + $offset : static::translateFieldName('Id', TableMap::TYPE_PHPNAME, $indexType)]; + } + + /** + * Retrieves the primary key from the DB resultset row + * For tables with a single-column primary key, that simple pkey value will be returned. For tables with + * a multi-column primary key, an array of the primary key columns will be returned. + * + * @param array $row resultset row. + * @param int $offset The 0-based offset for reading from the resultset row. + * @param string $indexType One of the class type constants TableMap::TYPE_PHPNAME, TableMap::TYPE_STUDLYPHPNAME + * TableMap::TYPE_COLNAME, TableMap::TYPE_FIELDNAME, TableMap::TYPE_NUM + * + * @return mixed The primary key of the row + */ + public static function getPrimaryKeyFromRow($row, $offset = 0, $indexType = TableMap::TYPE_NUM) + { + + return (int) $row[ + $indexType == TableMap::TYPE_NUM + ? 0 + $offset + : self::translateFieldName('Id', TableMap::TYPE_PHPNAME, $indexType) + ]; + } + + /** + * The class that the tableMap will make instances of. + * + * If $withPrefix is true, the returned path + * uses a dot-path notation which is translated into a path + * relative to a location on the PHP include_path. + * (e.g. path.to.MyClass -> 'path/to/MyClass.php') + * + * @param boolean $withPrefix Whether or not to return the path with the class name + * @return string path.to.ClassName + */ + public static function getOMClass($withPrefix = true) + { + return $withPrefix ? ColissimoPickupPointFreeshippingTableMap::CLASS_DEFAULT : ColissimoPickupPointFreeshippingTableMap::OM_CLASS; + } + + /** + * Populates an object of the default type or an object that inherit from the default. + * + * @param array $row row returned by DataFetcher->fetch(). + * @param int $offset The 0-based offset for reading from the resultset row. + * @param string $indexType The index type of $row. Mostly DataFetcher->getIndexType(). + One of the class type constants TableMap::TYPE_PHPNAME, TableMap::TYPE_STUDLYPHPNAME + * TableMap::TYPE_COLNAME, TableMap::TYPE_FIELDNAME, TableMap::TYPE_NUM. + * + * @throws PropelException Any exceptions caught during processing will be + * rethrown wrapped into a PropelException. + * @return array (ColissimoPickupPointFreeshipping object, last column rank) + */ + public static function populateObject($row, $offset = 0, $indexType = TableMap::TYPE_NUM) + { + $key = ColissimoPickupPointFreeshippingTableMap::getPrimaryKeyHashFromRow($row, $offset, $indexType); + if (null !== ($obj = ColissimoPickupPointFreeshippingTableMap::getInstanceFromPool($key))) { + // We no longer rehydrate the object, since this can cause data loss. + // See http://www.propelorm.org/ticket/509 + // $obj->hydrate($row, $offset, true); // rehydrate + $col = $offset + ColissimoPickupPointFreeshippingTableMap::NUM_HYDRATE_COLUMNS; + } else { + $cls = ColissimoPickupPointFreeshippingTableMap::OM_CLASS; + $obj = new $cls(); + $col = $obj->hydrate($row, $offset, false, $indexType); + ColissimoPickupPointFreeshippingTableMap::addInstanceToPool($obj, $key); + } + + return array($obj, $col); + } + + /** + * The returned array will contain objects of the default type or + * objects that inherit from the default. + * + * @param DataFetcherInterface $dataFetcher + * @return array + * @throws PropelException Any exceptions caught during processing will be + * rethrown wrapped into a PropelException. + */ + public static function populateObjects(DataFetcherInterface $dataFetcher) + { + $results = array(); + + // set the class once to avoid overhead in the loop + $cls = static::getOMClass(false); + // populate the object(s) + while ($row = $dataFetcher->fetch()) { + $key = ColissimoPickupPointFreeshippingTableMap::getPrimaryKeyHashFromRow($row, 0, $dataFetcher->getIndexType()); + if (null !== ($obj = ColissimoPickupPointFreeshippingTableMap::getInstanceFromPool($key))) { + // We no longer rehydrate the object, since this can cause data loss. + // See http://www.propelorm.org/ticket/509 + // $obj->hydrate($row, 0, true); // rehydrate + $results[] = $obj; + } else { + $obj = new $cls(); + $obj->hydrate($row); + $results[] = $obj; + ColissimoPickupPointFreeshippingTableMap::addInstanceToPool($obj, $key); + } // if key exists + } + + return $results; + } + /** + * Add all the columns needed to create a new object. + * + * Note: any columns that were marked with lazyLoad="true" in the + * XML schema will not be added to the select list and only loaded + * on demand. + * + * @param Criteria $criteria object containing the columns to add. + * @param string $alias optional table alias + * @throws PropelException Any exceptions caught during processing will be + * rethrown wrapped into a PropelException. + */ + public static function addSelectColumns(Criteria $criteria, $alias = null) + { + if (null === $alias) { + $criteria->addSelectColumn(ColissimoPickupPointFreeshippingTableMap::ID); + $criteria->addSelectColumn(ColissimoPickupPointFreeshippingTableMap::ACTIVE); + $criteria->addSelectColumn(ColissimoPickupPointFreeshippingTableMap::FREESHIPPING_FROM); + } else { + $criteria->addSelectColumn($alias . '.ID'); + $criteria->addSelectColumn($alias . '.ACTIVE'); + $criteria->addSelectColumn($alias . '.FREESHIPPING_FROM'); + } + } + + /** + * Returns the TableMap related to this object. + * This method is not needed for general use but a specific application could have a need. + * @return TableMap + * @throws PropelException Any exceptions caught during processing will be + * rethrown wrapped into a PropelException. + */ + public static function getTableMap() + { + return Propel::getServiceContainer()->getDatabaseMap(ColissimoPickupPointFreeshippingTableMap::DATABASE_NAME)->getTable(ColissimoPickupPointFreeshippingTableMap::TABLE_NAME); + } + + /** + * Add a TableMap instance to the database for this tableMap class. + */ + public static function buildTableMap() + { + $dbMap = Propel::getServiceContainer()->getDatabaseMap(ColissimoPickupPointFreeshippingTableMap::DATABASE_NAME); + if (!$dbMap->hasTable(ColissimoPickupPointFreeshippingTableMap::TABLE_NAME)) { + $dbMap->addTableObject(new ColissimoPickupPointFreeshippingTableMap()); + } + } + + /** + * Performs a DELETE on the database, given a ColissimoPickupPointFreeshipping or Criteria object OR a primary key value. + * + * @param mixed $values Criteria or ColissimoPickupPointFreeshipping object or primary key or array of primary keys + * which is used to create the DELETE statement + * @param ConnectionInterface $con the connection to use + * @return int The number of affected rows (if supported by underlying database driver). This includes CASCADE-related rows + * if supported by native driver or if emulated using Propel. + * @throws PropelException Any exceptions caught during processing will be + * rethrown wrapped into a PropelException. + */ + public static function doDelete($values, ConnectionInterface $con = null) + { + if (null === $con) { + $con = Propel::getServiceContainer()->getWriteConnection(ColissimoPickupPointFreeshippingTableMap::DATABASE_NAME); + } + + if ($values instanceof Criteria) { + // rename for clarity + $criteria = $values; + } elseif ($values instanceof \ColissimoPickupPoint\Model\ColissimoPickupPointFreeshipping) { // it's a model object + // create criteria based on pk values + $criteria = $values->buildPkeyCriteria(); + } else { // it's a primary key, or an array of pks + $criteria = new Criteria(ColissimoPickupPointFreeshippingTableMap::DATABASE_NAME); + $criteria->add(ColissimoPickupPointFreeshippingTableMap::ID, (array) $values, Criteria::IN); + } + + $query = ColissimoPickupPointFreeshippingQuery::create()->mergeWith($criteria); + + if ($values instanceof Criteria) { ColissimoPickupPointFreeshippingTableMap::clearInstancePool(); + } elseif (!is_object($values)) { // it's a primary key, or an array of pks + foreach ((array) $values as $singleval) { ColissimoPickupPointFreeshippingTableMap::removeInstanceFromPool($singleval); + } + } + + return $query->delete($con); + } + + /** + * Deletes all rows from the colissimo_pickup_point_freeshipping table. + * + * @param ConnectionInterface $con the connection to use + * @return int The number of affected rows (if supported by underlying database driver). + */ + public static function doDeleteAll(ConnectionInterface $con = null) + { + return ColissimoPickupPointFreeshippingQuery::create()->doDeleteAll($con); + } + + /** + * Performs an INSERT on the database, given a ColissimoPickupPointFreeshipping or Criteria object. + * + * @param mixed $criteria Criteria or ColissimoPickupPointFreeshipping object containing data that is used to create the INSERT statement. + * @param ConnectionInterface $con the ConnectionInterface connection to use + * @return mixed The new primary key. + * @throws PropelException Any exceptions caught during processing will be + * rethrown wrapped into a PropelException. + */ + public static function doInsert($criteria, ConnectionInterface $con = null) + { + if (null === $con) { + $con = Propel::getServiceContainer()->getWriteConnection(ColissimoPickupPointFreeshippingTableMap::DATABASE_NAME); + } + + if ($criteria instanceof Criteria) { + $criteria = clone $criteria; // rename for clarity + } else { + $criteria = $criteria->buildCriteria(); // build Criteria from ColissimoPickupPointFreeshipping object + } + + + // Set the correct dbName + $query = ColissimoPickupPointFreeshippingQuery::create()->mergeWith($criteria); + + try { + // use transaction because $criteria could contain info + // for more than one table (I guess, conceivably) + $con->beginTransaction(); + $pk = $query->doInsert($con); + $con->commit(); + } catch (PropelException $e) { + $con->rollBack(); + throw $e; + } + + return $pk; + } + +} // ColissimoPickupPointFreeshippingTableMap +// This is the static code needed to register the TableMap for this table with the main Propel class. +// +ColissimoPickupPointFreeshippingTableMap::buildTableMap(); diff --git a/local/modules/ColissimoPickupPoint/Model/Map/ColissimoPickupPointPriceSlicesTableMap.php b/local/modules/ColissimoPickupPoint/Model/Map/ColissimoPickupPointPriceSlicesTableMap.php new file mode 100644 index 00000000..d7b40a4b --- /dev/null +++ b/local/modules/ColissimoPickupPoint/Model/Map/ColissimoPickupPointPriceSlicesTableMap.php @@ -0,0 +1,443 @@ + array('Id', 'AreaId', 'WeightMax', 'PriceMax', 'FrancoMinPrice', 'Price', ), + self::TYPE_STUDLYPHPNAME => array('id', 'areaId', 'weightMax', 'priceMax', 'francoMinPrice', 'price', ), + self::TYPE_COLNAME => array(ColissimoPickupPointPriceSlicesTableMap::ID, ColissimoPickupPointPriceSlicesTableMap::AREA_ID, ColissimoPickupPointPriceSlicesTableMap::WEIGHT_MAX, ColissimoPickupPointPriceSlicesTableMap::PRICE_MAX, ColissimoPickupPointPriceSlicesTableMap::FRANCO_MIN_PRICE, ColissimoPickupPointPriceSlicesTableMap::PRICE, ), + self::TYPE_RAW_COLNAME => array('ID', 'AREA_ID', 'WEIGHT_MAX', 'PRICE_MAX', 'FRANCO_MIN_PRICE', 'PRICE', ), + self::TYPE_FIELDNAME => array('id', 'area_id', 'weight_max', 'price_max', 'franco_min_price', 'price', ), + self::TYPE_NUM => array(0, 1, 2, 3, 4, 5, ) + ); + + /** + * holds an array of keys for quick access to the fieldnames array + * + * first dimension keys are the type constants + * e.g. self::$fieldKeys[self::TYPE_PHPNAME]['Id'] = 0 + */ + protected static $fieldKeys = array ( + self::TYPE_PHPNAME => array('Id' => 0, 'AreaId' => 1, 'WeightMax' => 2, 'PriceMax' => 3, 'FrancoMinPrice' => 4, 'Price' => 5, ), + self::TYPE_STUDLYPHPNAME => array('id' => 0, 'areaId' => 1, 'weightMax' => 2, 'priceMax' => 3, 'francoMinPrice' => 4, 'price' => 5, ), + self::TYPE_COLNAME => array(ColissimoPickupPointPriceSlicesTableMap::ID => 0, ColissimoPickupPointPriceSlicesTableMap::AREA_ID => 1, ColissimoPickupPointPriceSlicesTableMap::WEIGHT_MAX => 2, ColissimoPickupPointPriceSlicesTableMap::PRICE_MAX => 3, ColissimoPickupPointPriceSlicesTableMap::FRANCO_MIN_PRICE => 4, ColissimoPickupPointPriceSlicesTableMap::PRICE => 5, ), + self::TYPE_RAW_COLNAME => array('ID' => 0, 'AREA_ID' => 1, 'WEIGHT_MAX' => 2, 'PRICE_MAX' => 3, 'FRANCO_MIN_PRICE' => 4, 'PRICE' => 5, ), + self::TYPE_FIELDNAME => array('id' => 0, 'area_id' => 1, 'weight_max' => 2, 'price_max' => 3, 'franco_min_price' => 4, 'price' => 5, ), + self::TYPE_NUM => array(0, 1, 2, 3, 4, 5, ) + ); + + /** + * Initialize the table attributes and columns + * Relations are not initialized by this method since they are lazy loaded + * + * @return void + * @throws PropelException + */ + public function initialize() + { + // attributes + $this->setName('colissimo_pickup_point_price_slices'); + $this->setPhpName('ColissimoPickupPointPriceSlices'); + $this->setClassName('\\ColissimoPickupPoint\\Model\\ColissimoPickupPointPriceSlices'); + $this->setPackage('ColissimoPickupPoint.Model'); + $this->setUseIdGenerator(true); + // columns + $this->addPrimaryKey('ID', 'Id', 'INTEGER', true, null, null); + $this->addForeignKey('AREA_ID', 'AreaId', 'INTEGER', 'area', 'ID', true, null, null); + $this->addColumn('WEIGHT_MAX', 'WeightMax', 'FLOAT', false, null, null); + $this->addColumn('PRICE_MAX', 'PriceMax', 'FLOAT', false, null, null); + $this->addColumn('FRANCO_MIN_PRICE', 'FrancoMinPrice', 'FLOAT', false, null, null); + $this->addColumn('PRICE', 'Price', 'FLOAT', true, null, null); + } // initialize() + + /** + * Build the RelationMap objects for this table relationships + */ + public function buildRelations() + { + $this->addRelation('Area', '\\ColissimoPickupPoint\\Model\\Thelia\\Model\\Area', RelationMap::MANY_TO_ONE, array('area_id' => 'id', ), 'RESTRICT', 'RESTRICT'); + } // buildRelations() + + /** + * Retrieves a string version of the primary key from the DB resultset row that can be used to uniquely identify a row in this table. + * + * For tables with a single-column primary key, that simple pkey value will be returned. For tables with + * a multi-column primary key, a serialize()d version of the primary key will be returned. + * + * @param array $row resultset row. + * @param int $offset The 0-based offset for reading from the resultset row. + * @param string $indexType One of the class type constants TableMap::TYPE_PHPNAME, TableMap::TYPE_STUDLYPHPNAME + * TableMap::TYPE_COLNAME, TableMap::TYPE_FIELDNAME, TableMap::TYPE_NUM + */ + public static function getPrimaryKeyHashFromRow($row, $offset = 0, $indexType = TableMap::TYPE_NUM) + { + // If the PK cannot be derived from the row, return NULL. + if ($row[TableMap::TYPE_NUM == $indexType ? 0 + $offset : static::translateFieldName('Id', TableMap::TYPE_PHPNAME, $indexType)] === null) { + return null; + } + + return (string) $row[TableMap::TYPE_NUM == $indexType ? 0 + $offset : static::translateFieldName('Id', TableMap::TYPE_PHPNAME, $indexType)]; + } + + /** + * Retrieves the primary key from the DB resultset row + * For tables with a single-column primary key, that simple pkey value will be returned. For tables with + * a multi-column primary key, an array of the primary key columns will be returned. + * + * @param array $row resultset row. + * @param int $offset The 0-based offset for reading from the resultset row. + * @param string $indexType One of the class type constants TableMap::TYPE_PHPNAME, TableMap::TYPE_STUDLYPHPNAME + * TableMap::TYPE_COLNAME, TableMap::TYPE_FIELDNAME, TableMap::TYPE_NUM + * + * @return mixed The primary key of the row + */ + public static function getPrimaryKeyFromRow($row, $offset = 0, $indexType = TableMap::TYPE_NUM) + { + + return (int) $row[ + $indexType == TableMap::TYPE_NUM + ? 0 + $offset + : self::translateFieldName('Id', TableMap::TYPE_PHPNAME, $indexType) + ]; + } + + /** + * The class that the tableMap will make instances of. + * + * If $withPrefix is true, the returned path + * uses a dot-path notation which is translated into a path + * relative to a location on the PHP include_path. + * (e.g. path.to.MyClass -> 'path/to/MyClass.php') + * + * @param boolean $withPrefix Whether or not to return the path with the class name + * @return string path.to.ClassName + */ + public static function getOMClass($withPrefix = true) + { + return $withPrefix ? ColissimoPickupPointPriceSlicesTableMap::CLASS_DEFAULT : ColissimoPickupPointPriceSlicesTableMap::OM_CLASS; + } + + /** + * Populates an object of the default type or an object that inherit from the default. + * + * @param array $row row returned by DataFetcher->fetch(). + * @param int $offset The 0-based offset for reading from the resultset row. + * @param string $indexType The index type of $row. Mostly DataFetcher->getIndexType(). + One of the class type constants TableMap::TYPE_PHPNAME, TableMap::TYPE_STUDLYPHPNAME + * TableMap::TYPE_COLNAME, TableMap::TYPE_FIELDNAME, TableMap::TYPE_NUM. + * + * @throws PropelException Any exceptions caught during processing will be + * rethrown wrapped into a PropelException. + * @return array (ColissimoPickupPointPriceSlices object, last column rank) + */ + public static function populateObject($row, $offset = 0, $indexType = TableMap::TYPE_NUM) + { + $key = ColissimoPickupPointPriceSlicesTableMap::getPrimaryKeyHashFromRow($row, $offset, $indexType); + if (null !== ($obj = ColissimoPickupPointPriceSlicesTableMap::getInstanceFromPool($key))) { + // We no longer rehydrate the object, since this can cause data loss. + // See http://www.propelorm.org/ticket/509 + // $obj->hydrate($row, $offset, true); // rehydrate + $col = $offset + ColissimoPickupPointPriceSlicesTableMap::NUM_HYDRATE_COLUMNS; + } else { + $cls = ColissimoPickupPointPriceSlicesTableMap::OM_CLASS; + $obj = new $cls(); + $col = $obj->hydrate($row, $offset, false, $indexType); + ColissimoPickupPointPriceSlicesTableMap::addInstanceToPool($obj, $key); + } + + return array($obj, $col); + } + + /** + * The returned array will contain objects of the default type or + * objects that inherit from the default. + * + * @param DataFetcherInterface $dataFetcher + * @return array + * @throws PropelException Any exceptions caught during processing will be + * rethrown wrapped into a PropelException. + */ + public static function populateObjects(DataFetcherInterface $dataFetcher) + { + $results = array(); + + // set the class once to avoid overhead in the loop + $cls = static::getOMClass(false); + // populate the object(s) + while ($row = $dataFetcher->fetch()) { + $key = ColissimoPickupPointPriceSlicesTableMap::getPrimaryKeyHashFromRow($row, 0, $dataFetcher->getIndexType()); + if (null !== ($obj = ColissimoPickupPointPriceSlicesTableMap::getInstanceFromPool($key))) { + // We no longer rehydrate the object, since this can cause data loss. + // See http://www.propelorm.org/ticket/509 + // $obj->hydrate($row, 0, true); // rehydrate + $results[] = $obj; + } else { + $obj = new $cls(); + $obj->hydrate($row); + $results[] = $obj; + ColissimoPickupPointPriceSlicesTableMap::addInstanceToPool($obj, $key); + } // if key exists + } + + return $results; + } + /** + * Add all the columns needed to create a new object. + * + * Note: any columns that were marked with lazyLoad="true" in the + * XML schema will not be added to the select list and only loaded + * on demand. + * + * @param Criteria $criteria object containing the columns to add. + * @param string $alias optional table alias + * @throws PropelException Any exceptions caught during processing will be + * rethrown wrapped into a PropelException. + */ + public static function addSelectColumns(Criteria $criteria, $alias = null) + { + if (null === $alias) { + $criteria->addSelectColumn(ColissimoPickupPointPriceSlicesTableMap::ID); + $criteria->addSelectColumn(ColissimoPickupPointPriceSlicesTableMap::AREA_ID); + $criteria->addSelectColumn(ColissimoPickupPointPriceSlicesTableMap::WEIGHT_MAX); + $criteria->addSelectColumn(ColissimoPickupPointPriceSlicesTableMap::PRICE_MAX); + $criteria->addSelectColumn(ColissimoPickupPointPriceSlicesTableMap::FRANCO_MIN_PRICE); + $criteria->addSelectColumn(ColissimoPickupPointPriceSlicesTableMap::PRICE); + } else { + $criteria->addSelectColumn($alias . '.ID'); + $criteria->addSelectColumn($alias . '.AREA_ID'); + $criteria->addSelectColumn($alias . '.WEIGHT_MAX'); + $criteria->addSelectColumn($alias . '.PRICE_MAX'); + $criteria->addSelectColumn($alias . '.FRANCO_MIN_PRICE'); + $criteria->addSelectColumn($alias . '.PRICE'); + } + } + + /** + * Returns the TableMap related to this object. + * This method is not needed for general use but a specific application could have a need. + * @return TableMap + * @throws PropelException Any exceptions caught during processing will be + * rethrown wrapped into a PropelException. + */ + public static function getTableMap() + { + return Propel::getServiceContainer()->getDatabaseMap(ColissimoPickupPointPriceSlicesTableMap::DATABASE_NAME)->getTable(ColissimoPickupPointPriceSlicesTableMap::TABLE_NAME); + } + + /** + * Add a TableMap instance to the database for this tableMap class. + */ + public static function buildTableMap() + { + $dbMap = Propel::getServiceContainer()->getDatabaseMap(ColissimoPickupPointPriceSlicesTableMap::DATABASE_NAME); + if (!$dbMap->hasTable(ColissimoPickupPointPriceSlicesTableMap::TABLE_NAME)) { + $dbMap->addTableObject(new ColissimoPickupPointPriceSlicesTableMap()); + } + } + + /** + * Performs a DELETE on the database, given a ColissimoPickupPointPriceSlices or Criteria object OR a primary key value. + * + * @param mixed $values Criteria or ColissimoPickupPointPriceSlices object or primary key or array of primary keys + * which is used to create the DELETE statement + * @param ConnectionInterface $con the connection to use + * @return int The number of affected rows (if supported by underlying database driver). This includes CASCADE-related rows + * if supported by native driver or if emulated using Propel. + * @throws PropelException Any exceptions caught during processing will be + * rethrown wrapped into a PropelException. + */ + public static function doDelete($values, ConnectionInterface $con = null) + { + if (null === $con) { + $con = Propel::getServiceContainer()->getWriteConnection(ColissimoPickupPointPriceSlicesTableMap::DATABASE_NAME); + } + + if ($values instanceof Criteria) { + // rename for clarity + $criteria = $values; + } elseif ($values instanceof \ColissimoPickupPoint\Model\ColissimoPickupPointPriceSlices) { // it's a model object + // create criteria based on pk values + $criteria = $values->buildPkeyCriteria(); + } else { // it's a primary key, or an array of pks + $criteria = new Criteria(ColissimoPickupPointPriceSlicesTableMap::DATABASE_NAME); + $criteria->add(ColissimoPickupPointPriceSlicesTableMap::ID, (array) $values, Criteria::IN); + } + + $query = ColissimoPickupPointPriceSlicesQuery::create()->mergeWith($criteria); + + if ($values instanceof Criteria) { ColissimoPickupPointPriceSlicesTableMap::clearInstancePool(); + } elseif (!is_object($values)) { // it's a primary key, or an array of pks + foreach ((array) $values as $singleval) { ColissimoPickupPointPriceSlicesTableMap::removeInstanceFromPool($singleval); + } + } + + return $query->delete($con); + } + + /** + * Deletes all rows from the colissimo_pickup_point_price_slices table. + * + * @param ConnectionInterface $con the connection to use + * @return int The number of affected rows (if supported by underlying database driver). + */ + public static function doDeleteAll(ConnectionInterface $con = null) + { + return ColissimoPickupPointPriceSlicesQuery::create()->doDeleteAll($con); + } + + /** + * Performs an INSERT on the database, given a ColissimoPickupPointPriceSlices or Criteria object. + * + * @param mixed $criteria Criteria or ColissimoPickupPointPriceSlices object containing data that is used to create the INSERT statement. + * @param ConnectionInterface $con the ConnectionInterface connection to use + * @return mixed The new primary key. + * @throws PropelException Any exceptions caught during processing will be + * rethrown wrapped into a PropelException. + */ + public static function doInsert($criteria, ConnectionInterface $con = null) + { + if (null === $con) { + $con = Propel::getServiceContainer()->getWriteConnection(ColissimoPickupPointPriceSlicesTableMap::DATABASE_NAME); + } + + if ($criteria instanceof Criteria) { + $criteria = clone $criteria; // rename for clarity + } else { + $criteria = $criteria->buildCriteria(); // build Criteria from ColissimoPickupPointPriceSlices object + } + + if ($criteria->containsKey(ColissimoPickupPointPriceSlicesTableMap::ID) && $criteria->keyContainsValue(ColissimoPickupPointPriceSlicesTableMap::ID) ) { + throw new PropelException('Cannot insert a value for auto-increment primary key ('.ColissimoPickupPointPriceSlicesTableMap::ID.')'); + } + + + // Set the correct dbName + $query = ColissimoPickupPointPriceSlicesQuery::create()->mergeWith($criteria); + + try { + // use transaction because $criteria could contain info + // for more than one table (I guess, conceivably) + $con->beginTransaction(); + $pk = $query->doInsert($con); + $con->commit(); + } catch (PropelException $e) { + $con->rollBack(); + throw $e; + } + + return $pk; + } + +} // ColissimoPickupPointPriceSlicesTableMap +// This is the static code needed to register the TableMap for this table with the main Propel class. +// +ColissimoPickupPointPriceSlicesTableMap::buildTableMap(); diff --git a/local/modules/ColissimoPickupPoint/Model/Map/OrderAddressColissimoPickupPointTableMap.php b/local/modules/ColissimoPickupPoint/Model/Map/OrderAddressColissimoPickupPointTableMap.php new file mode 100644 index 00000000..6b58545e --- /dev/null +++ b/local/modules/ColissimoPickupPoint/Model/Map/OrderAddressColissimoPickupPointTableMap.php @@ -0,0 +1,415 @@ + array('Id', 'Code', 'Type', ), + self::TYPE_STUDLYPHPNAME => array('id', 'code', 'type', ), + self::TYPE_COLNAME => array(OrderAddressColissimoPickupPointTableMap::ID, OrderAddressColissimoPickupPointTableMap::CODE, OrderAddressColissimoPickupPointTableMap::TYPE, ), + self::TYPE_RAW_COLNAME => array('ID', 'CODE', 'TYPE', ), + self::TYPE_FIELDNAME => array('id', 'code', 'type', ), + self::TYPE_NUM => array(0, 1, 2, ) + ); + + /** + * holds an array of keys for quick access to the fieldnames array + * + * first dimension keys are the type constants + * e.g. self::$fieldKeys[self::TYPE_PHPNAME]['Id'] = 0 + */ + protected static $fieldKeys = array ( + self::TYPE_PHPNAME => array('Id' => 0, 'Code' => 1, 'Type' => 2, ), + self::TYPE_STUDLYPHPNAME => array('id' => 0, 'code' => 1, 'type' => 2, ), + self::TYPE_COLNAME => array(OrderAddressColissimoPickupPointTableMap::ID => 0, OrderAddressColissimoPickupPointTableMap::CODE => 1, OrderAddressColissimoPickupPointTableMap::TYPE => 2, ), + self::TYPE_RAW_COLNAME => array('ID' => 0, 'CODE' => 1, 'TYPE' => 2, ), + self::TYPE_FIELDNAME => array('id' => 0, 'code' => 1, 'type' => 2, ), + self::TYPE_NUM => array(0, 1, 2, ) + ); + + /** + * Initialize the table attributes and columns + * Relations are not initialized by this method since they are lazy loaded + * + * @return void + * @throws PropelException + */ + public function initialize() + { + // attributes + $this->setName('order_address_colissimo_pickup_point'); + $this->setPhpName('OrderAddressColissimoPickupPoint'); + $this->setClassName('\\ColissimoPickupPoint\\Model\\OrderAddressColissimoPickupPoint'); + $this->setPackage('ColissimoPickupPoint.Model'); + $this->setUseIdGenerator(false); + // columns + $this->addForeignPrimaryKey('ID', 'Id', 'INTEGER' , 'order_address', 'ID', true, null, null); + $this->addColumn('CODE', 'Code', 'VARCHAR', true, 10, null); + $this->addColumn('TYPE', 'Type', 'VARCHAR', true, 10, null); + } // initialize() + + /** + * Build the RelationMap objects for this table relationships + */ + public function buildRelations() + { + $this->addRelation('OrderAddress', '\\ColissimoPickupPoint\\Model\\Thelia\\Model\\OrderAddress', RelationMap::MANY_TO_ONE, array('id' => 'id', ), 'CASCADE', 'CASCADE'); + } // buildRelations() + + /** + * Retrieves a string version of the primary key from the DB resultset row that can be used to uniquely identify a row in this table. + * + * For tables with a single-column primary key, that simple pkey value will be returned. For tables with + * a multi-column primary key, a serialize()d version of the primary key will be returned. + * + * @param array $row resultset row. + * @param int $offset The 0-based offset for reading from the resultset row. + * @param string $indexType One of the class type constants TableMap::TYPE_PHPNAME, TableMap::TYPE_STUDLYPHPNAME + * TableMap::TYPE_COLNAME, TableMap::TYPE_FIELDNAME, TableMap::TYPE_NUM + */ + public static function getPrimaryKeyHashFromRow($row, $offset = 0, $indexType = TableMap::TYPE_NUM) + { + // If the PK cannot be derived from the row, return NULL. + if ($row[TableMap::TYPE_NUM == $indexType ? 0 + $offset : static::translateFieldName('Id', TableMap::TYPE_PHPNAME, $indexType)] === null) { + return null; + } + + return (string) $row[TableMap::TYPE_NUM == $indexType ? 0 + $offset : static::translateFieldName('Id', TableMap::TYPE_PHPNAME, $indexType)]; + } + + /** + * Retrieves the primary key from the DB resultset row + * For tables with a single-column primary key, that simple pkey value will be returned. For tables with + * a multi-column primary key, an array of the primary key columns will be returned. + * + * @param array $row resultset row. + * @param int $offset The 0-based offset for reading from the resultset row. + * @param string $indexType One of the class type constants TableMap::TYPE_PHPNAME, TableMap::TYPE_STUDLYPHPNAME + * TableMap::TYPE_COLNAME, TableMap::TYPE_FIELDNAME, TableMap::TYPE_NUM + * + * @return mixed The primary key of the row + */ + public static function getPrimaryKeyFromRow($row, $offset = 0, $indexType = TableMap::TYPE_NUM) + { + + return (int) $row[ + $indexType == TableMap::TYPE_NUM + ? 0 + $offset + : self::translateFieldName('Id', TableMap::TYPE_PHPNAME, $indexType) + ]; + } + + /** + * The class that the tableMap will make instances of. + * + * If $withPrefix is true, the returned path + * uses a dot-path notation which is translated into a path + * relative to a location on the PHP include_path. + * (e.g. path.to.MyClass -> 'path/to/MyClass.php') + * + * @param boolean $withPrefix Whether or not to return the path with the class name + * @return string path.to.ClassName + */ + public static function getOMClass($withPrefix = true) + { + return $withPrefix ? OrderAddressColissimoPickupPointTableMap::CLASS_DEFAULT : OrderAddressColissimoPickupPointTableMap::OM_CLASS; + } + + /** + * Populates an object of the default type or an object that inherit from the default. + * + * @param array $row row returned by DataFetcher->fetch(). + * @param int $offset The 0-based offset for reading from the resultset row. + * @param string $indexType The index type of $row. Mostly DataFetcher->getIndexType(). + One of the class type constants TableMap::TYPE_PHPNAME, TableMap::TYPE_STUDLYPHPNAME + * TableMap::TYPE_COLNAME, TableMap::TYPE_FIELDNAME, TableMap::TYPE_NUM. + * + * @throws PropelException Any exceptions caught during processing will be + * rethrown wrapped into a PropelException. + * @return array (OrderAddressColissimoPickupPoint object, last column rank) + */ + public static function populateObject($row, $offset = 0, $indexType = TableMap::TYPE_NUM) + { + $key = OrderAddressColissimoPickupPointTableMap::getPrimaryKeyHashFromRow($row, $offset, $indexType); + if (null !== ($obj = OrderAddressColissimoPickupPointTableMap::getInstanceFromPool($key))) { + // We no longer rehydrate the object, since this can cause data loss. + // See http://www.propelorm.org/ticket/509 + // $obj->hydrate($row, $offset, true); // rehydrate + $col = $offset + OrderAddressColissimoPickupPointTableMap::NUM_HYDRATE_COLUMNS; + } else { + $cls = OrderAddressColissimoPickupPointTableMap::OM_CLASS; + $obj = new $cls(); + $col = $obj->hydrate($row, $offset, false, $indexType); + OrderAddressColissimoPickupPointTableMap::addInstanceToPool($obj, $key); + } + + return array($obj, $col); + } + + /** + * The returned array will contain objects of the default type or + * objects that inherit from the default. + * + * @param DataFetcherInterface $dataFetcher + * @return array + * @throws PropelException Any exceptions caught during processing will be + * rethrown wrapped into a PropelException. + */ + public static function populateObjects(DataFetcherInterface $dataFetcher) + { + $results = array(); + + // set the class once to avoid overhead in the loop + $cls = static::getOMClass(false); + // populate the object(s) + while ($row = $dataFetcher->fetch()) { + $key = OrderAddressColissimoPickupPointTableMap::getPrimaryKeyHashFromRow($row, 0, $dataFetcher->getIndexType()); + if (null !== ($obj = OrderAddressColissimoPickupPointTableMap::getInstanceFromPool($key))) { + // We no longer rehydrate the object, since this can cause data loss. + // See http://www.propelorm.org/ticket/509 + // $obj->hydrate($row, 0, true); // rehydrate + $results[] = $obj; + } else { + $obj = new $cls(); + $obj->hydrate($row); + $results[] = $obj; + OrderAddressColissimoPickupPointTableMap::addInstanceToPool($obj, $key); + } // if key exists + } + + return $results; + } + /** + * Add all the columns needed to create a new object. + * + * Note: any columns that were marked with lazyLoad="true" in the + * XML schema will not be added to the select list and only loaded + * on demand. + * + * @param Criteria $criteria object containing the columns to add. + * @param string $alias optional table alias + * @throws PropelException Any exceptions caught during processing will be + * rethrown wrapped into a PropelException. + */ + public static function addSelectColumns(Criteria $criteria, $alias = null) + { + if (null === $alias) { + $criteria->addSelectColumn(OrderAddressColissimoPickupPointTableMap::ID); + $criteria->addSelectColumn(OrderAddressColissimoPickupPointTableMap::CODE); + $criteria->addSelectColumn(OrderAddressColissimoPickupPointTableMap::TYPE); + } else { + $criteria->addSelectColumn($alias . '.ID'); + $criteria->addSelectColumn($alias . '.CODE'); + $criteria->addSelectColumn($alias . '.TYPE'); + } + } + + /** + * Returns the TableMap related to this object. + * This method is not needed for general use but a specific application could have a need. + * @return TableMap + * @throws PropelException Any exceptions caught during processing will be + * rethrown wrapped into a PropelException. + */ + public static function getTableMap() + { + return Propel::getServiceContainer()->getDatabaseMap(OrderAddressColissimoPickupPointTableMap::DATABASE_NAME)->getTable(OrderAddressColissimoPickupPointTableMap::TABLE_NAME); + } + + /** + * Add a TableMap instance to the database for this tableMap class. + */ + public static function buildTableMap() + { + $dbMap = Propel::getServiceContainer()->getDatabaseMap(OrderAddressColissimoPickupPointTableMap::DATABASE_NAME); + if (!$dbMap->hasTable(OrderAddressColissimoPickupPointTableMap::TABLE_NAME)) { + $dbMap->addTableObject(new OrderAddressColissimoPickupPointTableMap()); + } + } + + /** + * Performs a DELETE on the database, given a OrderAddressColissimoPickupPoint or Criteria object OR a primary key value. + * + * @param mixed $values Criteria or OrderAddressColissimoPickupPoint object or primary key or array of primary keys + * which is used to create the DELETE statement + * @param ConnectionInterface $con the connection to use + * @return int The number of affected rows (if supported by underlying database driver). This includes CASCADE-related rows + * if supported by native driver or if emulated using Propel. + * @throws PropelException Any exceptions caught during processing will be + * rethrown wrapped into a PropelException. + */ + public static function doDelete($values, ConnectionInterface $con = null) + { + if (null === $con) { + $con = Propel::getServiceContainer()->getWriteConnection(OrderAddressColissimoPickupPointTableMap::DATABASE_NAME); + } + + if ($values instanceof Criteria) { + // rename for clarity + $criteria = $values; + } elseif ($values instanceof \ColissimoPickupPoint\Model\OrderAddressColissimoPickupPoint) { // it's a model object + // create criteria based on pk values + $criteria = $values->buildPkeyCriteria(); + } else { // it's a primary key, or an array of pks + $criteria = new Criteria(OrderAddressColissimoPickupPointTableMap::DATABASE_NAME); + $criteria->add(OrderAddressColissimoPickupPointTableMap::ID, (array) $values, Criteria::IN); + } + + $query = OrderAddressColissimoPickupPointQuery::create()->mergeWith($criteria); + + if ($values instanceof Criteria) { OrderAddressColissimoPickupPointTableMap::clearInstancePool(); + } elseif (!is_object($values)) { // it's a primary key, or an array of pks + foreach ((array) $values as $singleval) { OrderAddressColissimoPickupPointTableMap::removeInstanceFromPool($singleval); + } + } + + return $query->delete($con); + } + + /** + * Deletes all rows from the order_address_colissimo_pickup_point table. + * + * @param ConnectionInterface $con the connection to use + * @return int The number of affected rows (if supported by underlying database driver). + */ + public static function doDeleteAll(ConnectionInterface $con = null) + { + return OrderAddressColissimoPickupPointQuery::create()->doDeleteAll($con); + } + + /** + * Performs an INSERT on the database, given a OrderAddressColissimoPickupPoint or Criteria object. + * + * @param mixed $criteria Criteria or OrderAddressColissimoPickupPoint object containing data that is used to create the INSERT statement. + * @param ConnectionInterface $con the ConnectionInterface connection to use + * @return mixed The new primary key. + * @throws PropelException Any exceptions caught during processing will be + * rethrown wrapped into a PropelException. + */ + public static function doInsert($criteria, ConnectionInterface $con = null) + { + if (null === $con) { + $con = Propel::getServiceContainer()->getWriteConnection(OrderAddressColissimoPickupPointTableMap::DATABASE_NAME); + } + + if ($criteria instanceof Criteria) { + $criteria = clone $criteria; // rename for clarity + } else { + $criteria = $criteria->buildCriteria(); // build Criteria from OrderAddressColissimoPickupPoint object + } + + + // Set the correct dbName + $query = OrderAddressColissimoPickupPointQuery::create()->mergeWith($criteria); + + try { + // use transaction because $criteria could contain info + // for more than one table (I guess, conceivably) + $con->beginTransaction(); + $pk = $query->doInsert($con); + $con->commit(); + } catch (PropelException $e) { + $con->rollBack(); + throw $e; + } + + return $pk; + } + +} // OrderAddressColissimoPickupPointTableMap +// This is the static code needed to register the TableMap for this table with the main Propel class. +// +OrderAddressColissimoPickupPointTableMap::buildTableMap(); diff --git a/local/modules/ColissimoPickupPoint/Model/OrderAddressColissimoPickupPoint.php b/local/modules/ColissimoPickupPoint/Model/OrderAddressColissimoPickupPoint.php new file mode 100644 index 00000000..1d4ddc03 --- /dev/null +++ b/local/modules/ColissimoPickupPoint/Model/OrderAddressColissimoPickupPoint.php @@ -0,0 +1,10 @@ +/local/modules/``` directory and be sure that the name of the module is ColissimoPickupPoint. +* Activate it in your thelia administration panel + +### Composer + +Add it in your main thelia composer.json file + +``` +composer require thelia/colissimo-pickup-point-module:~1.0.0 +``` + +How to use +----------- +First, go to your back office, tab Modules, and activate the module ColissimoPickupPoint. +Then go to the ColissimoPickupPoint config page, tab "Advanced Configuration" and enter your Colissimo id and password. +To import exported files in Expeditor INET, you need the file THELIA_INET.FMT, that is in the archive. + +Loops +----- +1. colissimo.pickup.point.check.rights + - Arguments: + None + - Output: + 1. $ERRMES: Error message + 2. $ERRFILE: File where the error has been detected + - Usage: + ```{loop name="yourloopname" type="colissimo.pickup.point.check.rights"}{/loop}``` + +2. colissimo.pickup.point + - Arguments: + 1. area_id | mandatory | id of the area we want to know the price slices of + - Output: + 1. $SLICE_ID: The ID of this price slice + 2. $MAX_WEIGHT: Max cart weight for the price slice + 3. $MAX_PRICE: Max cart price for the price slice + 4. $PRICE: Delivery price for this price slice + 5. $FRANCO: UNUSED + - Usage: + ```{loop name="yourloopname" type="colissimo.pickup.point"}{/loop}``` + +3. colissimo.pickup.point.id + - Arguments: + None + - Output: + 1. $MODULE_ID: Id of the ColissimoPickupPoint module + - Usage: + ```{loop name="yourloopname" type="colissimo.pickup.point.id"}{/loop}``` + +4. colissimo.pickup.point.around + - Arguments: + 1. countryid | optionnal | Country ID of where the search location is + 2. zipcode | optionnal | Zipcode of the searched city + 3. city | optionnal | Name of the searched city + 4. address | optionnal | Id of the address to use for the search. + address cannot be used at the same time as zipcode + city + - Output: + 1. $LONGITUDE: longitude of the pickup & go store + 2. $LATITUDE : latitude of the pickup & go store + 3. $CODE : ID of the pickup & go store + 4. $ADDRESS : address of the pickup & go store + 5. $ZIPCODE : zipcode of the pickup & go store + 6. $CITY : city of the pickup & go store + 7. $DISTANCE : distance between the store and the customer's address/searched address + - Usage: + ```{loop name="yourloopname" type="colissimo.pickup.point.around"}{/loop}``` + +5. address.colissimo.pickup.point + - Arguments: + The same as the loop address + - Output: + The same as the loop address, but with pickup & go store's address + - Usage: + ```{loop name="yourloopname" type="address.colissimo.pickup.point"}{/loop}``` + +6. order.notsent.colissimo.pickup.point + - Arguments: + None + - Output: + The same as the loop order, but with not sent ColissimoPickupPoint orders. + - Usage: + ```{loop name="yourloopname" type="order.notsent.colissimo.pickup.point"}{/loop}``` + +7. colissimo.pickup.point.order_address + - Arguments: + 1. id | mandatory | ID of the OrderAddressColissimoPickupPoint that should be retrieved by the loop. + - Outputs: + 1. $ID : OrderAddressColissimoPickupPoint ID. + 2. $CODE : OrderAddressColissimoPickupPoint code. + 3. $TYPE : OrderAddressColissimoPickupPoint type. + - Usage: + ```{loop name="yourloopname" type="colissimo.pickup.point.order_address"}{/loop}``` + +8. colissimo.pickup.point.area.freeshipping + - Arguments: + 1. area_id | optionnal | Id of the area we want to know if freeshipping from is active + - Outputs: + 1. $ID : ColissimoPickupPointAreaFreeshipping ID. + 2. $AREA_ID : The area ID. + 3. $CART_AMOUNT : The minimum cart amount to have free shipping for this area. + - Usage: + ```{loop name="yourloopname" type="colissimo.pickup.point.area.freeshipping"}{/loop}``` + +9. colissimo.pickup.point.freeshipping + - Arguments: + 1. id | optionnal | Should always be 1. + - Outputs: + 1. $FREESHIPPING_ACTIVE : Whether free shipping is activated with no restrictions on all area. + 2. $FREESHIPPING_FROM : The minimum cart amount to have free shipping on all alreas. + - Usage: + ```{loop name="yourloopname" type="colissimo.pickup.point.freeshipping"}{/loop}``` + +Plugins Smarty +----- +1. colissimoPickupPointDeliveryPrice + - Arguments: + 1. country | optionnal | The country ID from which you want to get the delivery prices. Defaults to store country + - Outputs: + 1. $isValidMode : Whether the delivery is valid for the cart in session and the chosen country. + 2. $deliveryPrice : The delivery price for the cart in session in the chosen country. + - Usage: + ```{colissimoPickupPointDeliveryPrice country=64}``` + +Integration +----------- +A integration example is available for the default theme of Thelia. +To install it, copy the files of pathToColissimoPickupPoint/templates/frontOffice/default and +pathToColissimoPickupPoint/templates/frontOffice/default/ajax respectively in pathToThelia/templates/frontOffice/default +and pathToThelia/templates/frontOffice/default/ajax diff --git a/local/modules/ColissimoPickupPoint/Smarty/Plugins/ColissimoPickupPointDeliveryPrice.php b/local/modules/ColissimoPickupPoint/Smarty/Plugins/ColissimoPickupPointDeliveryPrice.php new file mode 100644 index 00000000..8bdc929b --- /dev/null +++ b/local/modules/ColissimoPickupPoint/Smarty/Plugins/ColissimoPickupPointDeliveryPrice.php @@ -0,0 +1,56 @@ +request = $request; + $this->dispatcher = $dispatcher; + } + + public function getPluginDescriptors() + { + return array( + new SmartyPluginDescriptor('function', 'colissimoPickupPointDeliveryPrice', $this, 'colissimoPickupPointDeliveryPrice') + ); + } + + public function colissimoPickupPointDeliveryPrice($params, $smarty) + { + $country = Country::getShopLocation(); + if (isset($params['country'])) { + $country = CountryQuery::create()->findOneById($params['country']); + } + + $cartWeight = $this->request->getSession()->getSessionCart($this->dispatcher)->getWeight(); + $cartAmount = $this->request->getSession()->getSessionCart($this->dispatcher)->getTaxedAmount($country); + + try { + $price = ColissimoPickupPoint::getPostageAmount( + $country->getAreaId(), + $cartWeight, + $cartAmount + ); + } catch (DeliveryException $ex) { + $smarty->assign('isValidMode', false); + } + + $smarty->assign('deliveryPrice', $price); + } +} \ No newline at end of file diff --git a/local/modules/ColissimoPickupPoint/Smarty/Plugins/ColissimoPickupPointGoogleApiKey.php b/local/modules/ColissimoPickupPoint/Smarty/Plugins/ColissimoPickupPointGoogleApiKey.php new file mode 100644 index 00000000..323d7f77 --- /dev/null +++ b/local/modules/ColissimoPickupPoint/Smarty/Plugins/ColissimoPickupPointGoogleApiKey.php @@ -0,0 +1,45 @@ +request = $request; + $this->dispatcher = $dispatcher; + } + + public function getPluginDescriptors() + { + return array( + new SmartyPluginDescriptor('function', 'colissimoPickupPointGoogleApiKey', $this, 'colissimoPickupPointGoogleApiKey') + ); + } + + public function colissimoPickupPointGoogleApiKey($params, $smarty) + { + $key = ModuleConfigQuery::create() + ->filterByName('colissimo_pickup_point_google_map_key') + ->findOne() + ->getValue() + ; + + $smarty->assign('colissimoPickupPointGoogleMapKey', $key); + + return $key; + } +} \ No newline at end of file diff --git a/local/modules/ColissimoPickupPoint/THELIA_INET.FMT b/local/modules/ColissimoPickupPoint/THELIA_INET.FMT new file mode 100644 index 00000000..9697ab83 --- /dev/null +++ b/local/modules/ColissimoPickupPoint/THELIA_INET.FMT @@ -0,0 +1,25 @@ +[GENERAL] +DELIMITE=O +SEPARATEUR=59 +DELIMITEUR=34 +FINDELIGNE=CRLF +Unité poids=KG +[CHAMPS] +Prenom=1 +NomDestinataire=2 +RaisonSociale=3 +Adresse1=4 +Adresse2=5 +Adresse3=6 +CodePostal=7 +Commune=8 +CodePays=9 +Telephone=10 +Portable=11 +CodeProduit=12 +Civilite=13 +CodePointRetrait=14 +Mail=15 +Poids=16 +NomCommercialChargeur=17 +typeDePoint=18 \ No newline at end of file diff --git a/local/modules/ColissimoPickupPoint/Utils/ColissimoCodeReseau.php b/local/modules/ColissimoPickupPoint/Utils/ColissimoCodeReseau.php new file mode 100644 index 00000000..68d48483 --- /dev/null +++ b/local/modules/ColissimoPickupPoint/Utils/ColissimoCodeReseau.php @@ -0,0 +1,56 @@ + + [ + 'CMT' => 'R03', + 'BDP' => 'X00', + 'PCS' => 'X00' + ], + 'ES' => + [ + 'CMT' => 'R03', + 'BDP' => 'X00', + ], + 'GB' => + [ + 'CMT' => 'R03' + ], + 'LU' => + [ + 'CMT' => 'R03' + ], + 'NL' => + [ + 'BDP' => 'X00', + 'CMT' => 'R03', + ], + 'BE' => + [ + 'BDP' => 'R12', + 'CMT' => 'R12', + ] + ]; + + public static function getCodeReseau($countryCode, $relayTypeCode) + { + if (array_key_exists($countryCode, self::CODE_RESEAU_ARRAY)) { + $innerArray = self::CODE_RESEAU_ARRAY[$countryCode]; + if (array_key_exists($relayTypeCode, $innerArray)) { + return $innerArray[$relayTypeCode]; + } + } + return null; + } +} diff --git a/local/modules/ColissimoPickupPoint/WebService/BaseColissimoPickupPointWebService.php b/local/modules/ColissimoPickupPoint/WebService/BaseColissimoPickupPointWebService.php new file mode 100755 index 00000000..d09fb5ff --- /dev/null +++ b/local/modules/ColissimoPickupPoint/WebService/BaseColissimoPickupPointWebService.php @@ -0,0 +1,55 @@ +. */ +/* */ +/*************************************************************************************/ + +namespace ColissimoPickupPoint\WebService; + +use ColissimoPickupPoint\ColissimoPickupPoint; + +/** + * Class BaseColissimoPickupPointWebService + * @package ColissimoPickupPoint\WebService + * @author Thelia + * + * @method BaseColissimoPickupPointWebService getAccountNumber() + * @method BaseColissimoPickupPointWebService setAccountNumber($value) + * @method BaseColissimoPickupPointWebService getPassword() + * @method BaseColissimoPickupPointWebService setPassword($value) + * @method BaseColissimoPickupPointWebService getWeight() + * @method BaseColissimoPickupPointWebService setWeight($value) + */ +abstract class BaseColissimoPickupPointWebService extends BaseWebService +{ + + protected $account_number=null; + protected $password=null; + protected $filter_relay=null; + /** @var string Weight in grammes !*/ + protected $weight=null; + + public function __construct($function) + { + $url = ColissimoPickupPoint::getConfigValue(ColissimoPickupPoint::COLISSIMO_ENDPOINT); + + parent::__construct($url, $function); + } +} diff --git a/local/modules/ColissimoPickupPoint/WebService/BaseWebService.php b/local/modules/ColissimoPickupPoint/WebService/BaseWebService.php new file mode 100755 index 00000000..1e780389 --- /dev/null +++ b/local/modules/ColissimoPickupPoint/WebService/BaseWebService.php @@ -0,0 +1,229 @@ +. */ +/* */ +/*************************************************************************************/ + +namespace ColissimoPickupPoint\WebService; +use Symfony\Component\Serializer\Exception\InvalidArgumentException; + +/** + * Class BaseWebService + * @package ColissimoPickupPoint\WebService + * @author Thelia + * + * @method BaseWebService getSoap() + * @method BaseWebService setSoap(\SoapClient $soap) + * @method BaseWebService getWebFunction() + * @method BaseWebService setWebFunction($value) + */ +abstract class BaseWebService +{ + protected $soap; + protected $web_function; + + public function __construct($wsdl, $web_function=null) + { + $this->soap = new \SoapClient($wsdl); + $this->web_function=$web_function; + } + + /** + * @param $name + * @return mixed|string + */ + private function getProprietyRealName($name) + { + $propriety_real_name = substr($name,3); + + if (preg_match("#^[A-Z]$#", substr($propriety_real_name, 0,1))) { + $propriety_real_name = strtolower(substr($propriety_real_name, 0, 1)).substr($propriety_real_name, 1); + $propriety_real_name = preg_replace_callback( + "#([A-Z])#", + function ($match) { + return strtolower("_".$match[0]); + }, + $propriety_real_name + ); + } + + return $propriety_real_name; + } + + /** + * @param $name + * @param $arguments + * @return mixed + * @throws \Symfony\Component\Serializer\Exception\InvalidArgumentException + * @throws \BadFunctionCallException + */ + public function __call($name, $arguments) + { + if (method_exists($this, $name)) { + return call_user_func($this->$name, $arguments); + } + + if (substr($name,0,3) === "get") { + if (!empty($arguments)) { + throw new InvalidArgumentException("The function ".$name." in ".get_class($this)." doesn't take any argument."); + } + + $real_name = $this->getProprietyRealName($name); + if (property_exists($this, $real_name)) { + return $this->$real_name; + } + + } elseif (substr($name,0,3) === "set") { + if (count($arguments) !== 1) { + throw new InvalidArgumentException("The function ".$name." in ".get_class($this)." take only one argument."); + } + + $real_name = $this->getProprietyRealName($name); + $this->$real_name = $arguments[array_keys($arguments)[0]]; + + return $this; + } + + throw new \BadFunctionCallException("The function ".$name." doesn't exist in ".get_class($this)); + } + + /** + * @return mixed + * @throws \Symfony\Component\Serializer\Exception\InvalidArgumentException + */ + public function exec() + { + $function = $this->web_function; + $response = $this->soap->$function($this->getArgs()); + + if ($this->isError($response)) { + throw new InvalidArgumentException($this->getError($response)); + } + + return $this->getFormattedResponse($response); + } + + /** + * @return array of web function args + */ + public function getArgs() + { + $args= $this->getSoapNames($this->getThisVars()); + + /* + * Clear array + */ + foreach ($args as $key => $value) { + if ($key == "address" || $key == "city") { + $args[$key] = $this->normalize($value); + } + + if (empty($value)) { + unset($args[$key]); + } + } + + return $args; + } + + /** + * @return array + */ + protected function getThisVars() + { + $this_class_vars = get_object_vars($this); + $base_class_vars = get_class_vars("\\ColissimoPickupPoint\\WebService\\BaseWebService"); + $pks = array_diff_key($this_class_vars, $base_class_vars); + + return $pks; + } + + /** + * @param array $names + * @return array + */ + protected function getSoapNames(array $names) + { + foreach ($names as $name=>$value) { + $real_name = $this->getSoapName($name); + $names[$real_name] = $value; + if ($name !== $real_name) { + unset($names[$name]); + } + } + + return $names; + } + + /** + * @param string $name + * @return string + */ + protected function getSoapName($name) + { + return preg_replace_callback( + "#_([a-z]{1})#", + function ($match) { + return strtoupper($match[1]); + }, + $name + ); + } + + protected function normalize($text) + { + $utf8 = array( + '/[áàâãªä]/u' => 'a', + '/[ÁÀÂÃÄ]/u' => 'A', + '/[ÍÌÎÏ]/u' => 'I', + '/[íìîï]/u' => 'i', + '/[éèêë]/u' => 'e', + '/[ÉÈÊË]/u' => 'E', + '/[óòôõºö]/u' => 'o', + '/[ÓÒÔÕÖ]/u' => 'O', + '/[úùûü]/u' => 'u', + '/[ÚÙÛÜ]/u' => 'U', + '/ç/' => 'c', + '/Ç/' => 'C', + '/ñ/' => 'n', + '/Ñ/' => 'N', + '/–/' => '-', // UTF-8 hyphen to "normal" hyphen + '/[’‘‹›‚]/u' => ' ', // Literally a single quote + '/[“”«»„]/u' => ' ', // Double quote + '/ /' => ' ', // nonbreaking space (equiv. to 0x160) + ); + return preg_replace(array_keys($utf8), array_values($utf8), $text); + } + + /** + * @return bool + */ + abstract public function isError(\stdClass $response); + + /** + * @return string + */ + abstract public function getError(\stdClass $response); + + /** + * @return something + */ + abstract public function getFormattedResponse(\stdClass $response); +} diff --git a/local/modules/ColissimoPickupPoint/WebService/FindByAddress.php b/local/modules/ColissimoPickupPoint/WebService/FindByAddress.php new file mode 100755 index 00000000..d4c56726 --- /dev/null +++ b/local/modules/ColissimoPickupPoint/WebService/FindByAddress.php @@ -0,0 +1,92 @@ +. */ +/* */ +/*************************************************************************************/ + +namespace ColissimoPickupPoint\WebService; + +use stdClass; +use Symfony\Component\Config\Definition\Exception\Exception; + +/** + * Class FindByAddress + * @package ColissimoPickupPoint\WebService + * @author Thelia + * + * @method FindByAddress getAddress() + * @method FindByAddress setAddress($value) + * @method FindByAddress getZipCode() + * @method FindByAddress setZipCode($value) + * @method FindByAddress getCity() + * @method FindByAddress setCity($value) + * @method FindByAddress getCountryCode() + * @method FindByAddress setCountryCode($value) + * @method FindByAddress getFilterRelay() + * @method FindByAddress setFilterRelay($value) + * @method FindByAddress getRequestId() + * @method FindByAddress setRequestId($value) + * @method FindByAddress getLang() + * @method FindByAddress setLang($value) + * @method FindByAddress getOptionInter() + * @method FindByAddress setOptionInter($value) + * @method FindByAddress getShippingDate() + * @method FindByAddress setShippingDate($value) + */ +class FindByAddress extends BaseColissimoPickupPointWebService +{ + protected $address=null; + protected $zip_code=null; + protected $city=null; + protected $country_code=null; + protected $request_id=null; + protected $lang=null; + protected $option_inter=null; + protected $shipping_date=null; + + public function __construct() + { + parent::__construct('findRDVPointRetraitAcheminement'); + } + + public function isError(stdClass $response) + { + return isset($response->return->errorCode) && $response->return->errorCode != 0; + } + + public function getError(stdClass $response) + { + return isset($response->return->errorMessage) ? $response->return->errorMessage : 'Unknown error'; + } + + /** + * @param stdClass $response + * @return array + * @throws Exception + */ + public function getFormattedResponse(stdClass $response) + { + if (!isset($response->return->listePointRetraitAcheminement)) { + throw new Exception('An unknown error happened'); + } + + return $response->return->listePointRetraitAcheminement; + } +} diff --git a/local/modules/ColissimoPickupPoint/WebService/FindById.php b/local/modules/ColissimoPickupPoint/WebService/FindById.php new file mode 100755 index 00000000..793e442c --- /dev/null +++ b/local/modules/ColissimoPickupPoint/WebService/FindById.php @@ -0,0 +1,79 @@ +. */ +/* */ +/*************************************************************************************/ + +namespace ColissimoPickupPoint\WebService; +use stdClass; +use Symfony\Component\Config\Definition\Exception\Exception; + +/** + * Class FindById + * @package ColissimoPickupPoint\WebService + * @author Thelia + * + * @method FindById getId() + * @method FindById setId($value) + * @method FindById getReseau() + * @method FindById setReseau($value) + * @method FindById getLangue() + * @method FindById setLangue($value) + * @method FindById getDate() + * @method FindById setDate($value) + */ +class FindById extends BaseColissimoPickupPointWebService +{ + protected $id; + /** @var string if belgique: R12, else empty */ + protected $reseau; + protected $langue; + protected $date; + + public function __construct() + { + parent::__construct('findPointRetraitAcheminementByID'); + } + + public function isError(stdClass $response) + { + return isset($response->return->errorCode) && $response->return->errorCode != 0; + } + + public function getError(stdClass $response) + { + return isset($response->return->errorMessage) ? $response->return->errorMessage : 'Unknown error'; + } + + /** + * @param stdClass $response + * @return stdClass + * @throws Exception + */ + public function getFormattedResponse(stdClass $response) + { + if (!isset($response->return->pointRetraitAcheminement)) { + throw new Exception('An unknown error happened'); + } + + return $response->return->pointRetraitAcheminement; + } + +} diff --git a/local/modules/ColissimoPickupPoint/composer.json b/local/modules/ColissimoPickupPoint/composer.json new file mode 100644 index 00000000..320dbcb6 --- /dev/null +++ b/local/modules/ColissimoPickupPoint/composer.json @@ -0,0 +1,11 @@ +{ + "name": "thelia/colissimo-pickup-point-module", + "license": "LGPL-3.0+", + "type": "thelia-module", + "require": { + "thelia/installer": "~1.1" + }, + "extra": { + "installer-name": "ColissimoPickupPoint" + } +} \ No newline at end of file diff --git a/local/modules/ColissimoPickupPoint/images/socolissimo.png b/local/modules/ColissimoPickupPoint/images/socolissimo.png new file mode 100644 index 00000000..6317f927 Binary files /dev/null and b/local/modules/ColissimoPickupPoint/images/socolissimo.png differ diff --git a/local/modules/ColissimoPickupPoint/templates/backOffice/default/module-config-js.html b/local/modules/ColissimoPickupPoint/templates/backOffice/default/module-config-js.html new file mode 100755 index 00000000..c6811084 --- /dev/null +++ b/local/modules/ColissimoPickupPoint/templates/backOffice/default/module-config-js.html @@ -0,0 +1,201 @@ +{javascripts file='assets/js/bootstrap-switch/bootstrap-switch.js'} + +{/javascripts} + +{javascripts file='assets/js/libs/underscore-min.js'} + +{/javascripts} + + + \ No newline at end of file diff --git a/local/modules/ColissimoPickupPoint/templates/backOffice/default/module_configuration.html b/local/modules/ColissimoPickupPoint/templates/backOffice/default/module_configuration.html new file mode 100755 index 00000000..1b8a8c3e --- /dev/null +++ b/local/modules/ColissimoPickupPoint/templates/backOffice/default/module_configuration.html @@ -0,0 +1,474 @@ + +
    + + {loop name="checkrights.colissimo.pickup.point" type="colissimo.pickup.point.check.rights"} +
    +

    {$ERRMES} {$ERRFILE} | {intl l="Please change the access rights" d='colissimo.pickup.point.bo.default'}.

    +
    + {/loop} +
    + +{elseloop rel="checkrights.colissimo.pickup.point"} + + + +{assign var="tab" value="export"} +{if isset($smarty.get.current_tab)} + {assign var="tab" value=$smarty.get.current_tab} +{/if} + +{* default currency *} +{loop type="currency" name="default_currency" default_only="1"} +{$currencySymbol=$SYMBOL} +{/loop} + +
    +
    +
    + + + +
    +
    +
    +
    + {intl l="operations" d='colissimo.pickup.point.bo.default'} +
    +
    + + + +
    +
    + {form name="colissimo.pickup.point.export"} + + {form_hidden_fields form=$form} +
    +
    + {intl l="Change orders status after export" d='colissimo.pickup.point.bo.default'} +
    +
    + {form_field form=$form field="new_status_id"} + + + + + + + + + + + + + + +
    +   + + +
    +   + + +
    +   + + +
    + {/form_field} + {intl l="*If you choose this option, the exported orders would not be available on this page anymore" d='colissimo.pickup.point.bo.default'} +
    +
    + + + + + + + + + + + + {loop name="order.notsent.colissimo.pickup.point" type="order.notsent.colissimo.pickup.point"} + + + + + + + + + {/loop} + +
    + {intl l="REF" d='colissimo.pickup.point.bo.default'} + + {intl l="Customer"} + + {intl l="Date" d='colissimo.pickup.point.bo.default'} + + {intl l="Total taxed amount" d='colissimo.pickup.point.bo.default'} + + {intl l="Package weight" d='colissimo.pickup.point.bo.default'} + + {intl l="Export" d='colissimo.pickup.point.bo.default'} +
    + + + {loop name='order-customer' type='customer' id={$CUSTOMER} current=false} + {$FIRSTNAME} {$LASTNAME} + {/loop} + {elseloop rel='order-customer'} + {intl l='Unknown customer' d='colissimo.pickup.point.bo.default'} + {/elseloop} + + {format_date date=$CREATE_DATE output="datetime"} + + {$TOTAL_TAXED_AMOUNT} {loop name="list.colissimo.pickup.point.getcurrency" type="currency" id=$CURRENCY}{$SYMBOL}{/loop} + + {form_field form=$form field="order_weight_"|cat:$ID} + + {/form_field} + + {form_field form=$form field="order_"|cat:$ID} + + {/form_field} +
    + + + {/form} +
    + + +
    + +
    +
    + {intl l="The file has to be a CSV with 2 columns. The first contains the delivery reference, the second the order reference." d='colissimo.pickup.point.bo.default'} +
    + +
    + + {flash type='import-result'} +
    + {$MESSAGE} +
    + {/flash} + + {form name='colissimo.pickup.point.import'} +
    + {form_hidden_fields form=$form} + {render_form_field form=$form field="success_url" value={url path="/admin/module/ColissimoPickupPoint"} current_tab="import"} + + {if $form_error} +
    {$form_error_message}
    + {/if} + + {form_field form=$form field="import_file"} +
    + + + +
    + {/form_field} + + +
    + {/form} +
    +
    +
    + +
    +
    +
    + {intl l="Advanced configuration" d='colissimo.pickup.bo.default'} +
    + +
    + {form name="colissimo.pickup.point.configure"} + {if $form_error && $form_error_message} +
    {$form_error_message}
    + {/if} +
    + {form_hidden_fields form=$form} + {form_field form=$form field='colissimo_pickup_point_endpoint_url'} +
    + + +
    + {/form_field} + {form_field form=$form field='colissimo_pickup_point_username'} +
    + + +
    + {/form_field} + {form_field form=$form field='colissimo_pickup_point_password'} +
    + + +
    + {/form_field} + {form_field form=$form field='colissimo_pickup_point_google_map_key'} +
    + + +
    + {/form_field} +
    + +
    + {/form} +
    +
    +
    + +
    + {if null !== $smarty.get.price_error} + + {/if} +
    + +
    + + {assign var="isColissimoPickupPointFreeShipping" value=0} + {form name="colissimo.pickup.point.freeshipping.form"} +
    +
    + {form_hidden_fields form=$form} + + {form_field form=$form field="freeshipping"} + +
    + {loop type="colissimo.pickup.point.freeshipping" name="freeshipping_colissimo_pickup_point"} + + {/loop} +
    + {/form_field} +
    + +
    +
    + {form_field form=$form field="freeshipping_from"} + {loop type="colissimo.pickup.point.freeshipping" name="freeshipping_colissimo_pickup_point"} + {intl l="Or activate free shipping from (€) :" d="colissimo.pickup.point.bo.default"} + + {/loop} + {/form_field} + + + +
    +
    +
    + {/form} +
    + + +
    + +
    + {intl l="You can create price slices by specifying a maximum cart weight and/or a maximum cart price." d='colissimo.pickup.point.bo.default'} + {intl l="The slices are ordered by maximum cart weight then by maximum cart price." d='colissimo.pickup.point.bo.default'} + {intl l="If a cart matches multiple slices, it will take the last slice following that order." d='colissimo.pickup.point.bo.default'} + {intl l="If you don't specify a cart weight in a slice, it will have priority over the slices with weight." d='colissimo.pickup.point.bo.default'} + {intl l="If you don't specify a cart price in a slice, it will have priority over the other slices with the same weight." d='colissimo.pickup.point.bo.default'} + {intl l="If you specify both, the cart will require to have a lower weight AND a lower price in order to match the slice." d='colissimo.pickup.point.bo.default'} +
    + +
    + + {loop type="module" name="module-id-loop" code="ColissimoPickupPoint"} + {assign var="module_id" value=$ID} + {/loop} + {loop type="area" name="area_loop" module_id=$module_id backend_context=true} + {$area_id=$ID} +
    +
    + + + + + + + + + + + + + + + + + {loop type="colissimo.pickup.point" name="colissimo_pickup_point_area_$ID" area_id={$area_id} } + + + + + + + {/loop} + + {* New slice *} + {loop type="auth" name="can_change" role="ADMIN" module="colissimopickuppoint" access="CREATE"} + + + + + + + {/loop} + +
    + + + +
    {intl l="Weight up to ... kg" d='colissimo.pickup.point.bo.default'}{intl l="Untaxed Price up to ... %symbol" symbol=$currencySymbol d='colissimo.pickup.point.bo.default'}{intl l="Price (%symbol)" symbol=$currencySymbol d='colissimo.pickup.point.bo.default'}{intl l="Actions" d='colissimo.pickup.point.bo.default'}
    + + + + + + +
    + {loop type="auth" name="can_change" role="ADMIN" module="colissimopickuppoint" access="UPDATE"} + + + + {/loop} + {loop type="auth" name="can_change" role="ADMIN" module="colissimopickuppoint" access="DELETE"} + + + + {/loop} +
    +
    + + + + + + + + + +
    +
    +
    + + {/loop} + {elseloop rel="area_loop"} +
    +
    + {intl d='colissimo.pickup.point.bo.default' l="You should first attribute shipping zones to the modules: "} + + {intl d='colissimo.pickup.point.bo.default' l="manage shipping zones"} + +
    +
    + {/elseloop} +
    + +
    + +
    +
    +
    +
    + + + {include + file = "includes/generic-warning-dialog.html" + + dialog_id = "colissimo_pickup_point_dialog" + dialog_title = {intl d='colissimo.pickup.bo.default' l="Message"} + dialog_body = "" +} + + {* JS Templates *} + + +{/elseloop} diff --git a/local/modules/ColissimoPickupPoint/templates/frontOffice/default/assets/css/styles.css b/local/modules/ColissimoPickupPoint/templates/frontOffice/default/assets/css/styles.css new file mode 100644 index 00000000..0661c09c --- /dev/null +++ b/local/modules/ColissimoPickupPoint/templates/frontOffice/default/assets/css/styles.css @@ -0,0 +1,7 @@ +#colissimo-pickup-pointmap .table tbody > tr > th, #colissimo-pickup-pointmap .table tbody > tr > td { + padding: 10px 10px 0; +} + +.title-colissimo-pickup-point-pickup-type{ + color: #E47A10; +} \ No newline at end of file diff --git a/local/modules/ColissimoPickupPoint/templates/frontOffice/default/assets/img/A2P.png b/local/modules/ColissimoPickupPoint/templates/frontOffice/default/assets/img/A2P.png new file mode 100644 index 00000000..6930dc52 Binary files /dev/null and b/local/modules/ColissimoPickupPoint/templates/frontOffice/default/assets/img/A2P.png differ diff --git a/local/modules/ColissimoPickupPoint/templates/frontOffice/default/assets/img/BPR.png b/local/modules/ColissimoPickupPoint/templates/frontOffice/default/assets/img/BPR.png new file mode 100644 index 00000000..5afe2472 Binary files /dev/null and b/local/modules/ColissimoPickupPoint/templates/frontOffice/default/assets/img/BPR.png differ diff --git a/local/modules/ColissimoPickupPoint/templates/frontOffice/default/assets/img/CIT.png b/local/modules/ColissimoPickupPoint/templates/frontOffice/default/assets/img/CIT.png new file mode 100644 index 00000000..50818ede Binary files /dev/null and b/local/modules/ColissimoPickupPoint/templates/frontOffice/default/assets/img/CIT.png differ diff --git a/local/modules/ColissimoPickupPoint/templates/frontOffice/default/assets/img/dom-small.png b/local/modules/ColissimoPickupPoint/templates/frontOffice/default/assets/img/dom-small.png new file mode 100644 index 00000000..19c5d941 Binary files /dev/null and b/local/modules/ColissimoPickupPoint/templates/frontOffice/default/assets/img/dom-small.png differ diff --git a/local/modules/ColissimoPickupPoint/templates/frontOffice/default/assets/img/maison.png b/local/modules/ColissimoPickupPoint/templates/frontOffice/default/assets/img/maison.png new file mode 100644 index 00000000..c1685e2e Binary files /dev/null and b/local/modules/ColissimoPickupPoint/templates/frontOffice/default/assets/img/maison.png differ diff --git a/local/modules/ColissimoPickupPoint/templates/frontOffice/default/assets/img/mobilite-reduite.gif b/local/modules/ColissimoPickupPoint/templates/frontOffice/default/assets/img/mobilite-reduite.gif new file mode 100644 index 00000000..f2505d74 Binary files /dev/null and b/local/modules/ColissimoPickupPoint/templates/frontOffice/default/assets/img/mobilite-reduite.gif differ diff --git a/local/modules/ColissimoPickupPoint/templates/frontOffice/default/assets/img/parking.gif b/local/modules/ColissimoPickupPoint/templates/frontOffice/default/assets/img/parking.gif new file mode 100644 index 00000000..5bdacaea Binary files /dev/null and b/local/modules/ColissimoPickupPoint/templates/frontOffice/default/assets/img/parking.gif differ diff --git a/local/modules/ColissimoPickupPoint/templates/frontOffice/default/assets/img/pret-manutention.gif b/local/modules/ColissimoPickupPoint/templates/frontOffice/default/assets/img/pret-manutention.gif new file mode 100644 index 00000000..05843992 Binary files /dev/null and b/local/modules/ColissimoPickupPoint/templates/frontOffice/default/assets/img/pret-manutention.gif differ diff --git a/local/modules/ColissimoPickupPoint/templates/frontOffice/default/colissimo-pickup-point.html b/local/modules/ColissimoPickupPoint/templates/frontOffice/default/colissimo-pickup-point.html new file mode 100644 index 00000000..e70228f0 --- /dev/null +++ b/local/modules/ColissimoPickupPoint/templates/frontOffice/default/colissimo-pickup-point.html @@ -0,0 +1,487 @@ + +{loop type="delivery" name="colissimopickuppoint" id=$module force_return="true" country=$country} + + +
    +
    + {* Point relais *} + {* Check if Colissimo webservice is up *} + {assign var="isColissimoPickupPointUp" value=0} + {colissimoPickupPointDeliveryPrice country=$country}

    {$isValidMode}

    + {if $isValidMode !== false} + {loop name="is.colissimo.pickup.point.up" type="colissimo.pickup.point.around"}{/loop} + {ifloop rel="is.colissimo.pickup.point.up"} +
    +
    + {intl l="Near you" d='colissimopickuppoint.fo.default'} / {$deliveryPrice} {currency attr="symbol"} +
    +
    + + +
    +
    + + +
    +
    + {images file="assets/img/BPR.png" source="ColissimoPickupPoint"} + + {/images} +
    {intl l="Post office" d='colissimopickuppoint.fo.default'}
    +

    {intl l="Delivery in one of the 10,000 collection points La Poste in France or in a post office in Europe." d='colissimopickuppoint.fo.default'}

    + +
    + +
    +
    +
    + + +
    +
    + {images file="assets/img/A2P.png" source="ColissimoPickupPoint"} + + {/images} +
    {intl l="Pickup shop" d='colissimopickuppoint.fo.default'}
    +

    {intl l="Delivery in one of the 7,500 shops in the PICKUP network." d='colissimopickuppoint.fo.default'}

    + +
    + +
    +
    +
    + + +
    +
    + {images file="assets/img/CIT.png" source="ColissimoPickupPoint"} + + {/images} +
    {intl l="Automatic pickup point" d='colissimopickuppoint.fo.default'}
    +

    {intl l="Delivery in France in one of the 500 automatic instructions 7/7 and 24h/24." d='colissimopickuppoint.fo.default'}

    + +
    + +
    +
    +
    +
    +
    + +
    +
    + +
    +
    +
    + + +
    +
    +
    +
    +
    +
    + +
    +
    +

    {intl l="Search Colissimo relay in a city" d='colissimopickuppoint.fo.default'}

    + +
    +
    + + +
    +
    + + +
    +
    + + +
    +
    + +
    +
    + +
    +
    + +
    +
    +
    +
    + + + +
    + +
    +
    + {/ifloop} + {/if} +
    +
    + + + + +{/loop} \ No newline at end of file diff --git a/local/modules/ColissimoPickupPoint/templates/frontOffice/default/delivery-address.html b/local/modules/ColissimoPickupPoint/templates/frontOffice/default/delivery-address.html new file mode 100644 index 00000000..3c1fd2e3 --- /dev/null +++ b/local/modules/ColissimoPickupPoint/templates/frontOffice/default/delivery-address.html @@ -0,0 +1,29 @@ +{assign var="addresslooptype" value="address"} + +{loop type="colissimo.pickup.point.id" name="colissimo.pickup.point.id.invoice"} + {if $module == {order attr="delivery_module"}} + {assign var="addresslooptype" value="address.colissimo.pickup.point"} + {/if} +{/loop} + +{loop type=$addresslooptype name="delivery-address" id={order attr="delivery_address"}} +
    +
    {intl l="Delivery address"}
    +
    + {loop type="title" name="customer.title.info" id=$TITLE}{$SHORT}{/loop} {$LASTNAME|upper} {$FIRSTNAME|ucwords} + {$COMPANY} +
    + {$ADDRESS1}
    + {if $ADDRESS2 != ""} + {$ADDRESS2}
    + {/if} + {if $ADDRESS3 != ""} + {$ADDRESS3}
    + {/if} + {$ZIPCODE} + {$CITY}, {loop type="country" name="customer.country.info" id=$COUNTRY}{$TITLE}{/loop}
    + {$CELLPHONE} +
    +
    +
    +{/loop} \ No newline at end of file diff --git a/local/modules/ColissimoPickupPoint/templates/frontOffice/default/getSpecificLocationColissimoPickupPoint.html b/local/modules/ColissimoPickupPoint/templates/frontOffice/default/getSpecificLocationColissimoPickupPoint.html new file mode 100755 index 00000000..e0169101 --- /dev/null +++ b/local/modules/ColissimoPickupPoint/templates/frontOffice/default/getSpecificLocationColissimoPickupPoint.html @@ -0,0 +1,36 @@ +{literal} +{ +{/literal} +"locations": +[ +{loop type="colissimo.pickup.point.around" name="delivery-selection-colissimo-pickup-point" countryid=$_countryid_ zipcode=$_zipcode_ city=$_city_ address=$_address_} + {literal} + { + {/literal} + "name": "{$nom}", + "lat": {$coordGeolocalisationLatitude}, + "lng": {$coordGeolocalisationLongitude}, + "id": "{$identifiant}", + "address": "{$adresse1}", + "zipcode": "{$codePostal}", + "city": "{$localite}", + "countrycode" : "{$codePays}", + "distance": "{$distance}", + "type": "{$typeDePoint}", + "monday": "{$horairesOuvertureLundi}", + "tuesday": "{$horairesOuvertureMardi}", + "wednesday": "{$horairesOuvertureMercredi}", + "thursday": "{$horairesOuvertureJeudi}", + "friday": "{$horairesOuvertureVendredi}", + "saturday": "{$horairesOuvertureSamedi}", + "sunday": "{$horairesOuvertureDimanche}", + "disabledPerson": "{$accesPersonneMobiliteReduite}" + {literal} + } + {/literal} + {if $LOOP_COUNT < $LOOP_TOTAL},{/if} +{/loop} +] +{literal} +} +{/literal} \ No newline at end of file diff --git a/local/modules/ColissimoPickupPoint/templates/pdf/default/delivery_mode_infos.html b/local/modules/ColissimoPickupPoint/templates/pdf/default/delivery_mode_infos.html new file mode 100644 index 00000000..d41111bb --- /dev/null +++ b/local/modules/ColissimoPickupPoint/templates/pdf/default/delivery_mode_infos.html @@ -0,0 +1,14 @@ +{loop type='colissimo.pickup.point.order_address' name='colissimo.pickup.point.order_address' id=$delivery_address_id} +

    + {intl l='Delivered at a relay.' d='colissimo.pickup.point.pdf.default'}

    + {intl l='Relay address:' d='colissimo.pickup.point.pdf.default'} + {loop name='order_address' type='order_address' id=$delivery_address_id} +

    {$COMPANY}
    + {$ADDRESS1} {$ADDRESS2} {$ADDRESS3}
    + {$ZIPCODE} {$CITY}
    + {loop type="country" name="country_delivery" id=$COUNTRY}{$TITLE}{/loop} +
    + {/loop} + {elseloop rel='order_address'} {intl l='no address' d='colissimo.pickup.point.pdf.default'}{/elseloop} +

    +{/loop}