[31/07/2025] Installation des modules ColissimoPickupPoint et ColissimoHomeDelivery pour utilisation correcte du module ColissimoLabel

This commit is contained in:
2025-07-31 07:41:24 +02:00
parent 560c150141
commit 191b4a16e5
219 changed files with 37054 additions and 0 deletions

View File

@@ -0,0 +1,362 @@
<?php
/*************************************************************************************/
/* 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. */
/*************************************************************************************/
namespace ColissimoHomeDelivery;
use ColissimoHomeDelivery\Model\ColissimoHomeDeliveryAreaFreeshippingQuery;
use ColissimoHomeDelivery\Model\ColissimoHomeDeliveryFreeshippingQuery;
use ColissimoHomeDelivery\Model\ColissimoHomeDeliveryPriceSlices;
use PDO;
use ColissimoHomeDelivery\Model\ColissimoHomeDeliveryPriceSlicesQuery;
use Propel\Runtime\ActiveQuery\Criteria;
use Propel\Runtime\Connection\ConnectionInterface;
use Propel\Runtime\Propel;
use Symfony\Component\Finder\Finder;
use Thelia\Install\Database;
use Thelia\Model\ConfigQuery;
use Thelia\Model\Country;
use Thelia\Model\CountryArea;
use Thelia\Model\Message;
use Thelia\Model\MessageQuery;
use Thelia\Model\ModuleQuery;
use Thelia\Module\AbstractDeliveryModule;
use Thelia\Module\Exception\DeliveryException;
class ColissimoHomeDelivery extends AbstractDeliveryModule
{
/** @var string */
const DOMAIN_NAME = 'colissimohomedelivery';
// The shipping confirmation message identifier
const CONFIRMATION_MESSAGE_NAME = 'order_confirmation_colissimo_home_delivery';
// Configuration parameters
const COLISSIMO_USERNAME = 'colissimo_home_delivery_username';
const COLISSIMO_PASSWORD = 'colissimo_home_delivery_password';
const AFFRANCHISSEMENT_ENDPOINT_URL = 'affranchissement_endpoint_url';
const ACTIVATE_DETAILED_DEBUG = 'activate_detailed_debug';
/**
* @param ConnectionInterface|null $con
* @throws \Propel\Runtime\Exception\PropelException
*/
public function postActivation(ConnectionInterface $con = null)
{
// Create table if required.
try {
ColissimoHomeDeliveryPriceSlicesQuery::create()->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";
}
}

View File

@@ -0,0 +1,38 @@
<?xml version="1.0" encoding="UTF-8" ?>
<config xmlns="http://thelia.net/schema/dic/config"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://thelia.net/schema/dic/config http://thelia.net/schema/dic/config/thelia-1.0.xsd">
<loops>
<loop name="colissimo.homedelivery.price-slices" class="ColissimoHomeDelivery\Loop\PriceSlicesLoop" />
<loop name="colissimo.homedelivery.freeshipping" class="ColissimoHomeDelivery\Loop\ColissimoHomeDeliveryFreeShippingLoop" />
<loop name="colissimo.homedelivery.area.freeshipping" class="ColissimoHomeDelivery\Loop\ColissimoHomeDeliveryAreaFreeShippingLoop" />
</loops>
<forms>
<form name="colissimo.homedelivery.configuration.form" class="ColissimoHomeDelivery\Form\ConfigurationForm" />
<form name="colissimo.homedelivery.freeshipping.form" class="ColissimoHomeDelivery\Form\FreeShippingForm" />
</forms>
<services>
<service id="colissimo.homedelivery.notification_mail" class="ColissimoHomeDelivery\EventListeners\ShippingNotificationSender">
<argument type="service" id="thelia.parser" />
<argument type="service" id="mailer"/>
<tag name="kernel.event_subscriber"/>
</service>
<service id="api.colissimo.homedelivery" class="ColissimoHomeDelivery\EventListeners\APIListener" scope="request">
<argument type="service" id="service_container"/>
<tag name="kernel.event_subscriber"/>
</service>
</services>
<hooks>
<hook id="colissimo.homedelivery.hooks" class="ColissimoHomeDelivery\Hook\HookManager">
<tag name="hook.event_listener" event="module.configuration" type="back" method="onModuleConfigure" />
<tag name="hook.event_listener" event="module.config-js" type="back" method="onModuleConfigJs" />
<tag name="hook.event_listener" event="order-delivery.extra" />
<tag name="hook.event_listener" event="main.head-bottom" />
</hook>
</hooks>
</config>

View File

@@ -0,0 +1,24 @@
<?xml version="1.0" encoding="UTF-8"?>
<module xmlns="http://thelia.net/schema/dic/module"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://thelia.net/schema/dic/module http://thelia.net/schema/dic/module/module-2_2.xsd">
<fullnamespace>ColissimoHomeDelivery\ColissimoHomeDelivery</fullnamespace>
<descriptive locale="en_US">
<title>Home delivery with Colissimo</title>
</descriptive>
<descriptive locale="fr_FR">
<title>Livraison à domicile avec Colissimo</title>
</descriptive>
<languages>
<language>en_US</language>
<language>fr_FR</language>
</languages>
<version>1.0.2</version>
<author>
<name>Thelia</name>
<email>info@thelia.net</email>
</author>
<type>delivery</type>
<thelia>2.3.3</thelia>
<stability>other</stability>
</module>

View File

@@ -0,0 +1,29 @@
<?xml version="1.0" encoding="UTF-8" ?>
<routes xmlns="http://symfony.com/schema/routing"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://symfony.com/schema/routing http://symfony.com/schema/routing/routing-1.0.xsd">
<route id="colissimo.home.delivery.config" path="/admin/module/ColissimoHomeDelivery/configure">
<default key="_controller">ColissimoHomeDelivery\Controller\ConfigurationController::configure</default>
</route>
<!-- Price Slices -->
<route id="colissimo.home.delivery.toggle.freeshipping" path="/admin/module/ColissimoHomeDelivery/freeshipping" methods="post">
<default key="_controller">ColissimoHomeDelivery\Controller\FreeShippingController::toggleFreeShippingActivation</default>
</route>
<route id="colissimo.home.delivery.edit.areafreeshipping" path="/admin/module/ColissimoHomeDelivery/area_freeshipping" methods="post">
<default key="_controller">ColissimoHomeDelivery\Controller\FreeShippingController::setAreaFreeShipping</default>
</route>
<route id="colissimo.home.delivery.add.price-slice" path="/admin/module/ColissimoHomeDelivery/price-slice/save" methods="post">
<default key="_controller">ColissimoHomeDelivery\Controller\PriceSliceController::savePriceSliceAction</default>
</route>
<route id="colissimo.home.delivery.update.price-slice" path="/admin/module/ColissimoHomeDelivery/price-slice/delete" methods="post">
<default key="_controller">ColissimoHomeDelivery\Controller\PriceSliceController::deletePriceSliceAction</default>
</route>
</routes>

View File

@@ -0,0 +1,34 @@
<?xml version="1.0" encoding="UTF-8"?>
<database defaultIdMethod="native" name="thelia"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="../../../../core/vendor/propel/propel/resources/xsd/database.xsd" >
<table name="colissimo_home_delivery_price_slices" namespace="ColissimoHomeDelivery\Model">
<column autoIncrement="true" name="id" primaryKey="true" required="true" type="INTEGER" />
<column name="area_id" type="INTEGER" required="true"/>
<column name="max_weight" type="FLOAT"/>
<column name="max_price" type="FLOAT"/>
<column name="shipping" type="FLOAT" required="true"/>
<foreign-key foreignTable="area" name="fk_colissimo_home_delivery_price_slices_area_id" onDelete="RESTRICT" onUpdate="RESTRICT">
<reference foreign="id" local="area_id" />
</foreign-key>
</table>
<table name="colissimo_home_delivery_freeshipping" namespace="ColissimoHomeDelivery\Model">
<column name="id" primaryKey="true" required="true" type="INTEGER" />
<column name="active" type="BOOLEAN" default="0"/>
<column name="freeshipping_from" size="18" scale="2" type="DECIMAL" />
</table>
<table name="colissimo_home_delivery_area_freeshipping" namespace="ColissimoHomeDelivery\Model">
<column name="id" primaryKey="true" required="true" type="INTEGER" />
<column name="area_id" required="true" type="INTEGER" />
<column name="cart_amount" defaultValue="0.00" size="18" scale="2" type="DECIMAL" />
<foreign-key foreignTable="area" name="fk_colissimo_home_delivery_area_freeshipping_area_id" onDelete="RESTRICT" onUpdate="RESTRICT">
<reference foreign="id" local="area_id" />
</foreign-key>
</table>
<external-schema filename="local/config/schema.xml" referenceOnly="true" />
</database>

View File

@@ -0,0 +1,2 @@
# Sqlfile -> Database map
thelia.sql=thelia

View File

@@ -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;

View File

@@ -0,0 +1,80 @@
<?php
/*************************************************************************************/
/* Copyright (c) Franck Allimant, CQFDev */
/* email : thelia@cqfdev.fr */
/* web : http://www.cqfdev.fr */
/* */
/* For the full copyright and license information, please view the LICENSE */
/* file that was distributed with this source code. */
/*************************************************************************************/
/**
* Created by Franck Allimant, CQFDev <franck@cqfdev.fr>
* 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 ]));
}
}

View File

@@ -0,0 +1,123 @@
<?php
/*************************************************************************************/
/* */
/* Thelia */
/* */
/* Copyright (c) OpenStudio */
/* email : info@thelia.net */
/* web : http://www.thelia.net */
/* */
/* This program is free software; you can redistribute it and/or modify */
/* it under the terms of the GNU General Public License as published by */
/* the Free Software Foundation; either version 3 of the License */
/* */
/* This program is distributed in the hope that it will be useful, */
/* but WITHOUT ANY WARRANTY; without even the implied warranty of */
/* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the */
/* GNU General Public License for more details. */
/* */
/* You should have received a copy of the GNU General Public License */
/* along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* */
/*************************************************************************************/
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'));
}
}

View File

@@ -0,0 +1,68 @@
<?php
/*************************************************************************************/
/* Copyright (c) Franck Allimant, CQFDev */
/* email : thelia@cqfdev.fr */
/* web : http://www.cqfdev.fr */
/* */
/* For the full copyright and license information, please view the LICENSE */
/* file that was distributed with this source code. */
/*************************************************************************************/
/**
* Created by Franck Allimant, CQFDev <franck@cqfdev.fr>
* 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;
}
}
}

View File

@@ -0,0 +1,184 @@
<?php
namespace ColissimoHomeDelivery\Controller;
use ColissimoHomeDelivery\ColissimoHomeDelivery;
use ColissimoHomeDelivery\Model\ColissimoHomeDeliveryPriceSlices;
use ColissimoHomeDelivery\Model\ColissimoHomeDeliveryPriceSlicesQuery;
use Propel\Runtime\Map\TableMap;
use Thelia\Controller\Admin\BaseAdminController;
use Thelia\Core\Security\AccessManager;
class PriceSliceController extends BaseAdminController
{
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 savePriceSliceAction()
{
$response = $this->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));
}
}

View File

@@ -0,0 +1,99 @@
<?php
namespace ColissimoHomeDelivery\EventListeners;
use ColissimoHomeDelivery\ColissimoHomeDelivery;
use OpenApi\Events\DeliveryModuleOptionEvent;
use OpenApi\Events\OpenApiEvents;
use OpenApi\Model\Api\DeliveryModuleOption;
use OpenApi\Model\Api\ModelFactory;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Thelia\Core\Translation\Translator;
use Thelia\Model\CountryArea;
use Thelia\Module\Exception\DeliveryException;
class APIListener implements EventSubscriberInterface
{
/** @var ContainerInterface */
protected $container;
/**
* APIListener constructor.
* @param ContainerInterface $container We need the container because we use a service from another module
* which is not mandatory, and using its service without it being installed will crash
*/
public function __construct(ContainerInterface $container)
{
$this->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;
}
}

View File

@@ -0,0 +1,78 @@
<?php
/*************************************************************************************/
/* Copyright (c) Franck Allimant, CQFDev */
/* email : thelia@cqfdev.fr */
/* web : http://www.cqfdev.fr */
/* */
/* For the full copyright and license information, please view the LICENSE */
/* file that was distributed with this source code. */
/*************************************************************************************/
/**
* Created by Franck Allimant, CQFDev <franck@cqfdev.fr>
* 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()
]
);
}
}
}
}

View File

@@ -0,0 +1,95 @@
<?php
/*************************************************************************************/
/* Copyright (c) Franck Allimant, CQFDev */
/* email : thelia@cqfdev.fr */
/* web : http://www.cqfdev.fr */
/* */
/* For the full copyright and license information, please view the LICENSE */
/* file that was distributed with this source code. */
/*************************************************************************************/
/**
* Created by Franck Allimant, CQFDev <franck@cqfdev.fr>
* 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 daccé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 daccé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
)
]
]
)
;
}
}

View File

@@ -0,0 +1,88 @@
<?php
/*************************************************************************************/
/* */
/* Thelia */
/* */
/* Copyright (c) OpenStudio */
/* email : info@thelia.net */
/* web : http://www.thelia.net */
/* */
/* This program is free software; you can redistribute it and/or modify */
/* it under the terms of the GNU General Public License as published by */
/* the Free Software Foundation; either version 3 of the License */
/* */
/* This program is distributed in the hope that it will be useful, */
/* but WITHOUT ANY WARRANTY; without even the implied warranty of */
/* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the */
/* GNU General Public License for more details. */
/* */
/* You should have received a copy of the GNU General Public License */
/* along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* */
/*************************************************************************************/
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";
}
}

View File

@@ -0,0 +1,65 @@
<?php
/*************************************************************************************/
/* Copyright (c) Franck Allimant, CQFDev */
/* email : thelia@cqfdev.fr */
/* web : http://www.cqfdev.fr */
/* */
/* For the full copyright and license information, please view the LICENSE */
/* file that was distributed with this source code. */
/*************************************************************************************/
/**
* Created by Franck Allimant, CQFDev <franck@cqfdev.fr>
* 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'));
}
}

View File

@@ -0,0 +1,29 @@
<?php
return array(
'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',
'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',
);

View File

@@ -0,0 +1,30 @@
<?php
return array(
'Actions' => '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',
);

View File

@@ -0,0 +1,15 @@
<?php
return array(
'<a href="https://www.colissimo.fr/portail_colissimo/suivreResultat.do?parcelnumber=%package">Click here</a> to track your shipment. You can also enter the tracking number on <a href="https://www.laposte.fr/outils/suivre-vos-envois">https://www.laposte.fr/outils/suivre-vos-envois</a>' => '<a href="https://www.colissimo.fr/portail_colissimo/suivreResultat.do?parcelnumber=%package">Click here</a> to track your shipment. You can also enter the tracking number on <a href="https://www.laposte.fr/outils/suivre-vos-envois">https://www.laposte.fr/outils/suivre-vos-envois</a>',
'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 <a href="#">www.yourshop.com</a>' => 'Thank you for your shopping with us and hope to see you soon on <a href="#">www.yourshop.com</a>',
'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',
);

View File

@@ -0,0 +1,15 @@
<?php
return array(
'<a href="https://www.colissimo.fr/portail_colissimo/suivreResultat.do?parcelnumber=%package">Click here</a> to track your shipment. You can also enter the tracking number on <a href="https://www.laposte.fr/outils/suivre-vos-envois">https://www.laposte.fr/outils/suivre-vos-envois</a>' => '<a href="https://www.colissimo.fr/portail_colissimo/suivreResultat.do?parcelnumber=%package">Cliquez ici</a> pour suivre l\'acheminement. Vous pouvez aussi entrer le numéro de suivi sur <a href="https://www.laposte.fr/outils/suivre-vos-envois">https://www.laposte.fr/outils/suivre-vos-envois</a>',
'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 <a href="#">www.yourshop.com</a>' => 'Nous vous remercions pour votre achat et espérons vous revoir très vite sur <a href="#">www.votreboutique.com</a>',
'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',
);

View File

@@ -0,0 +1,22 @@
<?php
return array(
'Activate free shipping: ' => '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 daccé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 daccé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',
);

View File

@@ -0,0 +1,22 @@
<?php
return array(
'Activate free shipping: ' => '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 daccéder à votre espace client à l\'adresse https://www.colissimo.fr/entreprise' => 'Le mot de passe qui vous permet daccéder à votre espace client à l\'adresse https://www.colissimo.fr/entreprise',
'Nom d\'utilisateur Colissimo. C\'est l\'identifiants qui vous permet daccéder à votre espace client à l\'adresse https://www.colissimo.fr/entreprise' => 'Nom d\'utilisateur Colissimo. C\'est l\'identifiants qui vous permet daccé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',
);

View File

@@ -0,0 +1,6 @@
<?php
return array(
'Message Avec signature' => 'Je souhaite bénéficier d\'une remise avec signature (<b>coût forfaitaire de %surcout %unite</b>)',
'Titre Avec signature' => 'Supplément',
);

View File

@@ -0,0 +1,23 @@
<?php
return array(
'Comm. code' => '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}',
);

View File

@@ -0,0 +1,23 @@
<?php
return array(
'Comm. code' => '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}',
);

View File

@@ -0,0 +1,54 @@
<?php
namespace ColissimoHomeDelivery\Loop;
use ColissimoHomeDelivery\Model\ColissimoHomeDeliveryAreaFreeshipping;
use ColissimoHomeDelivery\Model\ColissimoHomeDeliveryAreaFreeshippingQuery;
use Thelia\Core\Template\Element\BaseLoop;
use Thelia\Core\Template\Element\LoopResult;
use Thelia\Core\Template\Element\LoopResultRow;
use Thelia\Core\Template\Element\PropelSearchLoopInterface;
use Thelia\Core\Template\Loop\Argument\Argument;
use Thelia\Core\Template\Loop\Argument\ArgumentCollection;
class ColissimoHomeDeliveryAreaFreeShippingLoop extends BaseLoop implements PropelSearchLoopInterface
{
/**
* @return ArgumentCollection
*/
protected function getArgDefinitions()
{
return new ArgumentCollection(
Argument::createIntTypeArgument('area_id')
);
}
public function buildModelCriteria()
{
$areaId = $this->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;
}
}

View File

@@ -0,0 +1,51 @@
<?php
namespace ColissimoHomeDelivery\Loop;
use ColissimoHomeDelivery\Model\ColissimoHomeDeliveryFreeshipping;
use ColissimoHomeDelivery\Model\ColissimoHomeDeliveryFreeshippingQuery;
use Thelia\Core\Template\Element\BaseLoop;
use Thelia\Core\Template\Element\LoopResult;
use Thelia\Core\Template\Element\LoopResultRow;
use Thelia\Core\Template\Element\PropelSearchLoopInterface;
use Thelia\Core\Template\Loop\Argument\Argument;
use Thelia\Core\Template\Loop\Argument\ArgumentCollection;
class ColissimoHomeDeliveryFreeShippingLoop extends BaseLoop implements PropelSearchLoopInterface
{
/**
* @return ArgumentCollection
*/
protected function getArgDefinitions()
{
return new ArgumentCollection(
Argument::createIntTypeArgument('id')
);
}
public function buildModelCriteria()
{
if (null === $isFreeShippingActive = ColissimoHomeDeliveryFreeshippingQuery::create()->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;
}
}

View File

@@ -0,0 +1,56 @@
<?php
namespace ColissimoHomeDelivery\Loop;
use ColissimoHomeDelivery\Model\ColissimoHomeDeliveryPriceSlicesQuery;
use Thelia\Core\Template\Element\BaseLoop;
use Thelia\Core\Template\Element\LoopResult;
use Thelia\Core\Template\Element\LoopResultRow;
use Thelia\Core\Template\Element\PropelSearchLoopInterface;
use Thelia\Core\Template\Loop\Argument\Argument;
use Thelia\Core\Template\Loop\Argument\ArgumentCollection;
use function mysql_xdevapi\getSession;
class PriceSlicesLoop extends BaseLoop implements PropelSearchLoopInterface
{
/**
* @return ArgumentCollection
*/
protected function getArgDefinitions()
{
return new ArgumentCollection(
Argument::createIntTypeArgument('area_id', null, true)
);
}
public function buildModelCriteria()
{
$areaId = $this->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;
}
}

View File

@@ -0,0 +1,519 @@
<?php
namespace ColissimoHomeDelivery\Model\Base;
use \Exception;
use \PDO;
use ColissimoHomeDelivery\Model\ColissimoHomeDeliveryAreaFreeshipping as ChildColissimoHomeDeliveryAreaFreeshipping;
use ColissimoHomeDelivery\Model\ColissimoHomeDeliveryAreaFreeshippingQuery as ChildColissimoHomeDeliveryAreaFreeshippingQuery;
use ColissimoHomeDelivery\Model\Map\ColissimoHomeDeliveryAreaFreeshippingTableMap;
use Propel\Runtime\Propel;
use Propel\Runtime\ActiveQuery\Criteria;
use Propel\Runtime\ActiveQuery\ModelCriteria;
use Propel\Runtime\ActiveQuery\ModelJoin;
use Propel\Runtime\Collection\Collection;
use Propel\Runtime\Collection\ObjectCollection;
use Propel\Runtime\Connection\ConnectionInterface;
use Propel\Runtime\Exception\PropelException;
use Thelia\Model\Area;
/**
* Base class that represents a query for the 'colissimo_home_delivery_area_freeshipping' table.
*
*
*
* @method ChildColissimoHomeDeliveryAreaFreeshippingQuery orderById($order = Criteria::ASC) Order by the id column
* @method ChildColissimoHomeDeliveryAreaFreeshippingQuery orderByAreaId($order = Criteria::ASC) Order by the area_id column
* @method ChildColissimoHomeDeliveryAreaFreeshippingQuery orderByCartAmount($order = Criteria::ASC) Order by the cart_amount column
*
* @method ChildColissimoHomeDeliveryAreaFreeshippingQuery groupById() Group by the id column
* @method ChildColissimoHomeDeliveryAreaFreeshippingQuery groupByAreaId() Group by the area_id column
* @method ChildColissimoHomeDeliveryAreaFreeshippingQuery groupByCartAmount() Group by the cart_amount column
*
* @method ChildColissimoHomeDeliveryAreaFreeshippingQuery leftJoin($relation) Adds a LEFT JOIN clause to the query
* @method ChildColissimoHomeDeliveryAreaFreeshippingQuery rightJoin($relation) Adds a RIGHT JOIN clause to the query
* @method ChildColissimoHomeDeliveryAreaFreeshippingQuery innerJoin($relation) Adds a INNER JOIN clause to the query
*
* @method ChildColissimoHomeDeliveryAreaFreeshippingQuery leftJoinArea($relationAlias = null) Adds a LEFT JOIN clause to the query using the Area relation
* @method ChildColissimoHomeDeliveryAreaFreeshippingQuery rightJoinArea($relationAlias = null) Adds a RIGHT JOIN clause to the query using the Area relation
* @method ChildColissimoHomeDeliveryAreaFreeshippingQuery innerJoinArea($relationAlias = null) Adds a INNER JOIN clause to the query using the Area relation
*
* @method ChildColissimoHomeDeliveryAreaFreeshipping findOne(ConnectionInterface $con = null) Return the first ChildColissimoHomeDeliveryAreaFreeshipping matching the query
* @method ChildColissimoHomeDeliveryAreaFreeshipping findOneOrCreate(ConnectionInterface $con = null) Return the first ChildColissimoHomeDeliveryAreaFreeshipping matching the query, or a new ChildColissimoHomeDeliveryAreaFreeshipping object populated from the query conditions when no match is found
*
* @method ChildColissimoHomeDeliveryAreaFreeshipping findOneById(int $id) Return the first ChildColissimoHomeDeliveryAreaFreeshipping filtered by the id column
* @method ChildColissimoHomeDeliveryAreaFreeshipping findOneByAreaId(int $area_id) Return the first ChildColissimoHomeDeliveryAreaFreeshipping filtered by the area_id column
* @method ChildColissimoHomeDeliveryAreaFreeshipping findOneByCartAmount(string $cart_amount) Return the first ChildColissimoHomeDeliveryAreaFreeshipping filtered by the cart_amount column
*
* @method array findById(int $id) Return ChildColissimoHomeDeliveryAreaFreeshipping objects filtered by the id column
* @method array findByAreaId(int $area_id) Return ChildColissimoHomeDeliveryAreaFreeshipping objects filtered by the area_id column
* @method array findByCartAmount(string $cart_amount) Return ChildColissimoHomeDeliveryAreaFreeshipping objects filtered by the cart_amount column
*
*/
abstract class ColissimoHomeDeliveryAreaFreeshippingQuery extends ModelCriteria
{
/**
* Initializes internal state of \ColissimoHomeDelivery\Model\Base\ColissimoHomeDeliveryAreaFreeshippingQuery object.
*
* @param string $dbName The database name
* @param string $modelName The phpName of a model, e.g. 'Book'
* @param string $modelAlias The alias for the model in this query, e.g. 'b'
*/
public function __construct($dbName = 'thelia', $modelName = '\\ColissimoHomeDelivery\\Model\\ColissimoHomeDeliveryAreaFreeshipping', $modelAlias = null)
{
parent::__construct($dbName, $modelName, $modelAlias);
}
/**
* Returns a new ChildColissimoHomeDeliveryAreaFreeshippingQuery object.
*
* @param string $modelAlias The alias of a model in the query
* @param Criteria $criteria Optional Criteria to build the query from
*
* @return ChildColissimoHomeDeliveryAreaFreeshippingQuery
*/
public static function create($modelAlias = null, $criteria = null)
{
if ($criteria instanceof \ColissimoHomeDelivery\Model\ColissimoHomeDeliveryAreaFreeshippingQuery) {
return $criteria;
}
$query = new \ColissimoHomeDelivery\Model\ColissimoHomeDeliveryAreaFreeshippingQuery();
if (null !== $modelAlias) {
$query->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.
*
* <code>
* $obj = $c->findPk(12, $con);
* </code>
*
* @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
* <code>
* $objs = $c->findPks(array(12, 56, 832), $con);
* </code>
* @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:
* <code>
* $query->filterById(1234); // WHERE id = 1234
* $query->filterById(array(12, 34)); // WHERE id IN (12, 34)
* $query->filterById(array('min' => 12)); // WHERE id > 12
* </code>
*
* @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:
* <code>
* $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
* </code>
*
* @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:
* <code>
* $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
* </code>
*
* @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

View File

@@ -0,0 +1,420 @@
<?php
namespace ColissimoHomeDelivery\Model\Base;
use \Exception;
use \PDO;
use ColissimoHomeDelivery\Model\ColissimoHomeDeliveryFreeshipping as ChildColissimoHomeDeliveryFreeshipping;
use ColissimoHomeDelivery\Model\ColissimoHomeDeliveryFreeshippingQuery as ChildColissimoHomeDeliveryFreeshippingQuery;
use ColissimoHomeDelivery\Model\Map\ColissimoHomeDeliveryFreeshippingTableMap;
use Propel\Runtime\Propel;
use Propel\Runtime\ActiveQuery\Criteria;
use Propel\Runtime\ActiveQuery\ModelCriteria;
use Propel\Runtime\Connection\ConnectionInterface;
use Propel\Runtime\Exception\PropelException;
/**
* Base class that represents a query for the 'colissimo_home_delivery_freeshipping' table.
*
*
*
* @method ChildColissimoHomeDeliveryFreeshippingQuery orderById($order = Criteria::ASC) Order by the id column
* @method ChildColissimoHomeDeliveryFreeshippingQuery orderByActive($order = Criteria::ASC) Order by the active column
* @method ChildColissimoHomeDeliveryFreeshippingQuery orderByFreeshippingFrom($order = Criteria::ASC) Order by the freeshipping_from column
*
* @method ChildColissimoHomeDeliveryFreeshippingQuery groupById() Group by the id column
* @method ChildColissimoHomeDeliveryFreeshippingQuery groupByActive() Group by the active column
* @method ChildColissimoHomeDeliveryFreeshippingQuery groupByFreeshippingFrom() Group by the freeshipping_from column
*
* @method ChildColissimoHomeDeliveryFreeshippingQuery leftJoin($relation) Adds a LEFT JOIN clause to the query
* @method ChildColissimoHomeDeliveryFreeshippingQuery rightJoin($relation) Adds a RIGHT JOIN clause to the query
* @method ChildColissimoHomeDeliveryFreeshippingQuery innerJoin($relation) Adds a INNER JOIN clause to the query
*
* @method ChildColissimoHomeDeliveryFreeshipping findOne(ConnectionInterface $con = null) Return the first ChildColissimoHomeDeliveryFreeshipping matching the query
* @method ChildColissimoHomeDeliveryFreeshipping findOneOrCreate(ConnectionInterface $con = null) Return the first ChildColissimoHomeDeliveryFreeshipping matching the query, or a new ChildColissimoHomeDeliveryFreeshipping object populated from the query conditions when no match is found
*
* @method ChildColissimoHomeDeliveryFreeshipping findOneById(int $id) Return the first ChildColissimoHomeDeliveryFreeshipping filtered by the id column
* @method ChildColissimoHomeDeliveryFreeshipping findOneByActive(boolean $active) Return the first ChildColissimoHomeDeliveryFreeshipping filtered by the active column
* @method ChildColissimoHomeDeliveryFreeshipping findOneByFreeshippingFrom(string $freeshipping_from) Return the first ChildColissimoHomeDeliveryFreeshipping filtered by the freeshipping_from column
*
* @method array findById(int $id) Return ChildColissimoHomeDeliveryFreeshipping objects filtered by the id column
* @method array findByActive(boolean $active) Return ChildColissimoHomeDeliveryFreeshipping objects filtered by the active column
* @method array findByFreeshippingFrom(string $freeshipping_from) Return ChildColissimoHomeDeliveryFreeshipping objects filtered by the freeshipping_from column
*
*/
abstract class ColissimoHomeDeliveryFreeshippingQuery extends ModelCriteria
{
/**
* Initializes internal state of \ColissimoHomeDelivery\Model\Base\ColissimoHomeDeliveryFreeshippingQuery object.
*
* @param string $dbName The database name
* @param string $modelName The phpName of a model, e.g. 'Book'
* @param string $modelAlias The alias for the model in this query, e.g. 'b'
*/
public function __construct($dbName = 'thelia', $modelName = '\\ColissimoHomeDelivery\\Model\\ColissimoHomeDeliveryFreeshipping', $modelAlias = null)
{
parent::__construct($dbName, $modelName, $modelAlias);
}
/**
* Returns a new ChildColissimoHomeDeliveryFreeshippingQuery object.
*
* @param string $modelAlias The alias of a model in the query
* @param Criteria $criteria Optional Criteria to build the query from
*
* @return ChildColissimoHomeDeliveryFreeshippingQuery
*/
public static function create($modelAlias = null, $criteria = null)
{
if ($criteria instanceof \ColissimoHomeDelivery\Model\ColissimoHomeDeliveryFreeshippingQuery) {
return $criteria;
}
$query = new \ColissimoHomeDelivery\Model\ColissimoHomeDeliveryFreeshippingQuery();
if (null !== $modelAlias) {
$query->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.
*
* <code>
* $obj = $c->findPk(12, $con);
* </code>
*
* @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
* <code>
* $objs = $c->findPks(array(12, 56, 832), $con);
* </code>
* @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:
* <code>
* $query->filterById(1234); // WHERE id = 1234
* $query->filterById(array(12, 34)); // WHERE id IN (12, 34)
* $query->filterById(array('min' => 12)); // WHERE id > 12
* </code>
*
* @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:
* <code>
* $query->filterByActive(true); // WHERE active = true
* $query->filterByActive('yes'); // WHERE active = true
* </code>
*
* @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:
* <code>
* $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
* </code>
*
* @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

View File

@@ -0,0 +1,609 @@
<?php
namespace ColissimoHomeDelivery\Model\Base;
use \Exception;
use \PDO;
use ColissimoHomeDelivery\Model\ColissimoHomeDeliveryPriceSlices as ChildColissimoHomeDeliveryPriceSlices;
use ColissimoHomeDelivery\Model\ColissimoHomeDeliveryPriceSlicesQuery as ChildColissimoHomeDeliveryPriceSlicesQuery;
use ColissimoHomeDelivery\Model\Map\ColissimoHomeDeliveryPriceSlicesTableMap;
use Propel\Runtime\Propel;
use Propel\Runtime\ActiveQuery\Criteria;
use Propel\Runtime\ActiveQuery\ModelCriteria;
use Propel\Runtime\ActiveQuery\ModelJoin;
use Propel\Runtime\Collection\Collection;
use Propel\Runtime\Collection\ObjectCollection;
use Propel\Runtime\Connection\ConnectionInterface;
use Propel\Runtime\Exception\PropelException;
use Thelia\Model\Area;
/**
* Base class that represents a query for the 'colissimo_home_delivery_price_slices' table.
*
*
*
* @method ChildColissimoHomeDeliveryPriceSlicesQuery orderById($order = Criteria::ASC) Order by the id column
* @method ChildColissimoHomeDeliveryPriceSlicesQuery orderByAreaId($order = Criteria::ASC) Order by the area_id column
* @method ChildColissimoHomeDeliveryPriceSlicesQuery orderByMaxWeight($order = Criteria::ASC) Order by the max_weight column
* @method ChildColissimoHomeDeliveryPriceSlicesQuery orderByMaxPrice($order = Criteria::ASC) Order by the max_price column
* @method ChildColissimoHomeDeliveryPriceSlicesQuery orderByShipping($order = Criteria::ASC) Order by the shipping column
*
* @method ChildColissimoHomeDeliveryPriceSlicesQuery groupById() Group by the id column
* @method ChildColissimoHomeDeliveryPriceSlicesQuery groupByAreaId() Group by the area_id column
* @method ChildColissimoHomeDeliveryPriceSlicesQuery groupByMaxWeight() Group by the max_weight column
* @method ChildColissimoHomeDeliveryPriceSlicesQuery groupByMaxPrice() Group by the max_price column
* @method ChildColissimoHomeDeliveryPriceSlicesQuery groupByShipping() Group by the shipping column
*
* @method ChildColissimoHomeDeliveryPriceSlicesQuery leftJoin($relation) Adds a LEFT JOIN clause to the query
* @method ChildColissimoHomeDeliveryPriceSlicesQuery rightJoin($relation) Adds a RIGHT JOIN clause to the query
* @method ChildColissimoHomeDeliveryPriceSlicesQuery innerJoin($relation) Adds a INNER JOIN clause to the query
*
* @method ChildColissimoHomeDeliveryPriceSlicesQuery leftJoinArea($relationAlias = null) Adds a LEFT JOIN clause to the query using the Area relation
* @method ChildColissimoHomeDeliveryPriceSlicesQuery rightJoinArea($relationAlias = null) Adds a RIGHT JOIN clause to the query using the Area relation
* @method ChildColissimoHomeDeliveryPriceSlicesQuery innerJoinArea($relationAlias = null) Adds a INNER JOIN clause to the query using the Area relation
*
* @method ChildColissimoHomeDeliveryPriceSlices findOne(ConnectionInterface $con = null) Return the first ChildColissimoHomeDeliveryPriceSlices matching the query
* @method ChildColissimoHomeDeliveryPriceSlices findOneOrCreate(ConnectionInterface $con = null) Return the first ChildColissimoHomeDeliveryPriceSlices matching the query, or a new ChildColissimoHomeDeliveryPriceSlices object populated from the query conditions when no match is found
*
* @method ChildColissimoHomeDeliveryPriceSlices findOneById(int $id) Return the first ChildColissimoHomeDeliveryPriceSlices filtered by the id column
* @method ChildColissimoHomeDeliveryPriceSlices findOneByAreaId(int $area_id) Return the first ChildColissimoHomeDeliveryPriceSlices filtered by the area_id column
* @method ChildColissimoHomeDeliveryPriceSlices findOneByMaxWeight(double $max_weight) Return the first ChildColissimoHomeDeliveryPriceSlices filtered by the max_weight column
* @method ChildColissimoHomeDeliveryPriceSlices findOneByMaxPrice(double $max_price) Return the first ChildColissimoHomeDeliveryPriceSlices filtered by the max_price column
* @method ChildColissimoHomeDeliveryPriceSlices findOneByShipping(double $shipping) Return the first ChildColissimoHomeDeliveryPriceSlices filtered by the shipping column
*
* @method array findById(int $id) Return ChildColissimoHomeDeliveryPriceSlices objects filtered by the id column
* @method array findByAreaId(int $area_id) Return ChildColissimoHomeDeliveryPriceSlices objects filtered by the area_id column
* @method array findByMaxWeight(double $max_weight) Return ChildColissimoHomeDeliveryPriceSlices objects filtered by the max_weight column
* @method array findByMaxPrice(double $max_price) Return ChildColissimoHomeDeliveryPriceSlices objects filtered by the max_price column
* @method array findByShipping(double $shipping) Return ChildColissimoHomeDeliveryPriceSlices objects filtered by the shipping column
*
*/
abstract class ColissimoHomeDeliveryPriceSlicesQuery extends ModelCriteria
{
/**
* Initializes internal state of \ColissimoHomeDelivery\Model\Base\ColissimoHomeDeliveryPriceSlicesQuery object.
*
* @param string $dbName The database name
* @param string $modelName The phpName of a model, e.g. 'Book'
* @param string $modelAlias The alias for the model in this query, e.g. 'b'
*/
public function __construct($dbName = 'thelia', $modelName = '\\ColissimoHomeDelivery\\Model\\ColissimoHomeDeliveryPriceSlices', $modelAlias = null)
{
parent::__construct($dbName, $modelName, $modelAlias);
}
/**
* Returns a new ChildColissimoHomeDeliveryPriceSlicesQuery object.
*
* @param string $modelAlias The alias of a model in the query
* @param Criteria $criteria Optional Criteria to build the query from
*
* @return ChildColissimoHomeDeliveryPriceSlicesQuery
*/
public static function create($modelAlias = null, $criteria = null)
{
if ($criteria instanceof \ColissimoHomeDelivery\Model\ColissimoHomeDeliveryPriceSlicesQuery) {
return $criteria;
}
$query = new \ColissimoHomeDelivery\Model\ColissimoHomeDeliveryPriceSlicesQuery();
if (null !== $modelAlias) {
$query->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.
*
* <code>
* $obj = $c->findPk(12, $con);
* </code>
*
* @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
* <code>
* $objs = $c->findPks(array(12, 56, 832), $con);
* </code>
* @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:
* <code>
* $query->filterById(1234); // WHERE id = 1234
* $query->filterById(array(12, 34)); // WHERE id IN (12, 34)
* $query->filterById(array('min' => 12)); // WHERE id > 12
* </code>
*
* @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:
* <code>
* $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
* </code>
*
* @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:
* <code>
* $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
* </code>
*
* @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:
* <code>
* $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
* </code>
*
* @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:
* <code>
* $query->filterByShipping(1234); // WHERE shipping = 1234
* $query->filterByShipping(array(12, 34)); // WHERE shipping IN (12, 34)
* $query->filterByShipping(array('min' => 12)); // WHERE shipping > 12
* </code>
*
* @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

View File

@@ -0,0 +1,10 @@
<?php
namespace ColissimoHomeDelivery\Model;
use ColissimoHomeDelivery\Model\Base\ColissimoHomeDeliveryAreaFreeshipping as BaseColissimoHomeDeliveryAreaFreeshipping;
class ColissimoHomeDeliveryAreaFreeshipping extends BaseColissimoHomeDeliveryAreaFreeshipping
{
}

View File

@@ -0,0 +1,21 @@
<?php
namespace ColissimoHomeDelivery\Model;
use ColissimoHomeDelivery\Model\Base\ColissimoHomeDeliveryAreaFreeshippingQuery as BaseColissimoHomeDeliveryAreaFreeshippingQuery;
/**
* Skeleton subclass for performing query and update operations on the 'colissimo_home_delivery_area_freeshipping' table.
*
*
*
* You should add additional methods to this class to meet the
* application requirements. This class will only be generated as
* long as it does not already exist in the output directory.
*
*/
class ColissimoHomeDeliveryAreaFreeshippingQuery extends BaseColissimoHomeDeliveryAreaFreeshippingQuery
{
} // ColissimoHomeDeliveryAreaFreeshippingQuery

View File

@@ -0,0 +1,10 @@
<?php
namespace ColissimoHomeDelivery\Model;
use ColissimoHomeDelivery\Model\Base\ColissimoHomeDeliveryFreeshipping as BaseColissimoHomeDeliveryFreeshipping;
class ColissimoHomeDeliveryFreeshipping extends BaseColissimoHomeDeliveryFreeshipping
{
}

View File

@@ -0,0 +1,21 @@
<?php
namespace ColissimoHomeDelivery\Model;
use ColissimoHomeDelivery\Model\Base\ColissimoHomeDeliveryFreeshippingQuery as BaseColissimoHomeDeliveryFreeshippingQuery;
/**
* Skeleton subclass for performing query and update operations on the 'colissimo_home_delivery_freeshipping' table.
*
*
*
* You should add additional methods to this class to meet the
* application requirements. This class will only be generated as
* long as it does not already exist in the output directory.
*
*/
class ColissimoHomeDeliveryFreeshippingQuery extends BaseColissimoHomeDeliveryFreeshippingQuery
{
} // ColissimoHomeDeliveryFreeshippingQuery

View File

@@ -0,0 +1,10 @@
<?php
namespace ColissimoHomeDelivery\Model;
use ColissimoHomeDelivery\Model\Base\ColissimoHomeDeliveryPriceSlices as BaseColissimoHomeDeliveryPriceSlices;
class ColissimoHomeDeliveryPriceSlices extends BaseColissimoHomeDeliveryPriceSlices
{
}

View File

@@ -0,0 +1,21 @@
<?php
namespace ColissimoHomeDelivery\Model;
use ColissimoHomeDelivery\Model\Base\ColissimoHomeDeliveryPriceSlicesQuery as BaseColissimoHomeDeliveryPriceSlicesQuery;
/**
* Skeleton subclass for performing query and update operations on the 'colissimo_home_delivery_price_slices' table.
*
*
*
* You should add additional methods to this class to meet the
* application requirements. This class will only be generated as
* long as it does not already exist in the output directory.
*
*/
class ColissimoHomeDeliveryPriceSlicesQuery extends BaseColissimoHomeDeliveryPriceSlicesQuery
{
} // ColissimoHomeDeliveryPriceSlicesQuery

View File

@@ -0,0 +1,415 @@
<?php
namespace ColissimoHomeDelivery\Model\Map;
use ColissimoHomeDelivery\Model\ColissimoHomeDeliveryAreaFreeshipping;
use ColissimoHomeDelivery\Model\ColissimoHomeDeliveryAreaFreeshippingQuery;
use Propel\Runtime\Propel;
use Propel\Runtime\ActiveQuery\Criteria;
use Propel\Runtime\ActiveQuery\InstancePoolTrait;
use Propel\Runtime\Connection\ConnectionInterface;
use Propel\Runtime\DataFetcher\DataFetcherInterface;
use Propel\Runtime\Exception\PropelException;
use Propel\Runtime\Map\RelationMap;
use Propel\Runtime\Map\TableMap;
use Propel\Runtime\Map\TableMapTrait;
/**
* This class defines the structure of the 'colissimo_home_delivery_area_freeshipping' table.
*
*
*
* This map class is used by Propel to do runtime db structure discovery.
* For example, the createSelectSql() method checks the type of a given column used in an
* ORDER BY clause to know whether it needs to apply SQL to make the ORDER BY case-insensitive
* (i.e. if it's a text column type).
*
*/
class ColissimoHomeDeliveryAreaFreeshippingTableMap extends TableMap
{
use InstancePoolTrait;
use TableMapTrait;
/**
* The (dot-path) name of this class
*/
const CLASS_NAME = 'ColissimoHomeDelivery.Model.Map.ColissimoHomeDeliveryAreaFreeshippingTableMap';
/**
* The default database name for this class
*/
const DATABASE_NAME = 'thelia';
/**
* The table name for this class
*/
const TABLE_NAME = 'colissimo_home_delivery_area_freeshipping';
/**
* The related Propel class for this table
*/
const OM_CLASS = '\\ColissimoHomeDelivery\\Model\\ColissimoHomeDeliveryAreaFreeshipping';
/**
* A class that can be returned by this tableMap
*/
const CLASS_DEFAULT = 'ColissimoHomeDelivery.Model.ColissimoHomeDeliveryAreaFreeshipping';
/**
* The total number of columns
*/
const NUM_COLUMNS = 3;
/**
* The number of lazy-loaded columns
*/
const NUM_LAZY_LOAD_COLUMNS = 0;
/**
* The number of columns to hydrate (NUM_COLUMNS - NUM_LAZY_LOAD_COLUMNS)
*/
const NUM_HYDRATE_COLUMNS = 3;
/**
* the column name for the ID field
*/
const ID = 'colissimo_home_delivery_area_freeshipping.ID';
/**
* the column name for the AREA_ID field
*/
const AREA_ID = 'colissimo_home_delivery_area_freeshipping.AREA_ID';
/**
* the column name for the CART_AMOUNT field
*/
const CART_AMOUNT = 'colissimo_home_delivery_area_freeshipping.CART_AMOUNT';
/**
* The default string format for model objects of the related table
*/
const DEFAULT_STRING_FORMAT = 'YAML';
/**
* holds an array of fieldnames
*
* first dimension keys are the type constants
* e.g. self::$fieldNames[self::TYPE_PHPNAME][0] = 'Id'
*/
protected static $fieldNames = array (
self::TYPE_PHPNAME => 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();

View File

@@ -0,0 +1,414 @@
<?php
namespace ColissimoHomeDelivery\Model\Map;
use ColissimoHomeDelivery\Model\ColissimoHomeDeliveryFreeshipping;
use ColissimoHomeDelivery\Model\ColissimoHomeDeliveryFreeshippingQuery;
use Propel\Runtime\Propel;
use Propel\Runtime\ActiveQuery\Criteria;
use Propel\Runtime\ActiveQuery\InstancePoolTrait;
use Propel\Runtime\Connection\ConnectionInterface;
use Propel\Runtime\DataFetcher\DataFetcherInterface;
use Propel\Runtime\Exception\PropelException;
use Propel\Runtime\Map\RelationMap;
use Propel\Runtime\Map\TableMap;
use Propel\Runtime\Map\TableMapTrait;
/**
* This class defines the structure of the 'colissimo_home_delivery_freeshipping' table.
*
*
*
* This map class is used by Propel to do runtime db structure discovery.
* For example, the createSelectSql() method checks the type of a given column used in an
* ORDER BY clause to know whether it needs to apply SQL to make the ORDER BY case-insensitive
* (i.e. if it's a text column type).
*
*/
class ColissimoHomeDeliveryFreeshippingTableMap extends TableMap
{
use InstancePoolTrait;
use TableMapTrait;
/**
* The (dot-path) name of this class
*/
const CLASS_NAME = 'ColissimoHomeDelivery.Model.Map.ColissimoHomeDeliveryFreeshippingTableMap';
/**
* The default database name for this class
*/
const DATABASE_NAME = 'thelia';
/**
* The table name for this class
*/
const TABLE_NAME = 'colissimo_home_delivery_freeshipping';
/**
* The related Propel class for this table
*/
const OM_CLASS = '\\ColissimoHomeDelivery\\Model\\ColissimoHomeDeliveryFreeshipping';
/**
* A class that can be returned by this tableMap
*/
const CLASS_DEFAULT = 'ColissimoHomeDelivery.Model.ColissimoHomeDeliveryFreeshipping';
/**
* The total number of columns
*/
const NUM_COLUMNS = 3;
/**
* The number of lazy-loaded columns
*/
const NUM_LAZY_LOAD_COLUMNS = 0;
/**
* The number of columns to hydrate (NUM_COLUMNS - NUM_LAZY_LOAD_COLUMNS)
*/
const NUM_HYDRATE_COLUMNS = 3;
/**
* the column name for the ID field
*/
const ID = 'colissimo_home_delivery_freeshipping.ID';
/**
* the column name for the ACTIVE field
*/
const ACTIVE = 'colissimo_home_delivery_freeshipping.ACTIVE';
/**
* the column name for the FREESHIPPING_FROM field
*/
const FREESHIPPING_FROM = 'colissimo_home_delivery_freeshipping.FREESHIPPING_FROM';
/**
* The default string format for model objects of the related table
*/
const DEFAULT_STRING_FORMAT = 'YAML';
/**
* holds an array of fieldnames
*
* first dimension keys are the type constants
* e.g. self::$fieldNames[self::TYPE_PHPNAME][0] = 'Id'
*/
protected static $fieldNames = array (
self::TYPE_PHPNAME => 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();

View File

@@ -0,0 +1,435 @@
<?php
namespace ColissimoHomeDelivery\Model\Map;
use ColissimoHomeDelivery\Model\ColissimoHomeDeliveryPriceSlices;
use ColissimoHomeDelivery\Model\ColissimoHomeDeliveryPriceSlicesQuery;
use Propel\Runtime\Propel;
use Propel\Runtime\ActiveQuery\Criteria;
use Propel\Runtime\ActiveQuery\InstancePoolTrait;
use Propel\Runtime\Connection\ConnectionInterface;
use Propel\Runtime\DataFetcher\DataFetcherInterface;
use Propel\Runtime\Exception\PropelException;
use Propel\Runtime\Map\RelationMap;
use Propel\Runtime\Map\TableMap;
use Propel\Runtime\Map\TableMapTrait;
/**
* This class defines the structure of the 'colissimo_home_delivery_price_slices' table.
*
*
*
* This map class is used by Propel to do runtime db structure discovery.
* For example, the createSelectSql() method checks the type of a given column used in an
* ORDER BY clause to know whether it needs to apply SQL to make the ORDER BY case-insensitive
* (i.e. if it's a text column type).
*
*/
class ColissimoHomeDeliveryPriceSlicesTableMap extends TableMap
{
use InstancePoolTrait;
use TableMapTrait;
/**
* The (dot-path) name of this class
*/
const CLASS_NAME = 'ColissimoHomeDelivery.Model.Map.ColissimoHomeDeliveryPriceSlicesTableMap';
/**
* The default database name for this class
*/
const DATABASE_NAME = 'thelia';
/**
* The table name for this class
*/
const TABLE_NAME = 'colissimo_home_delivery_price_slices';
/**
* The related Propel class for this table
*/
const OM_CLASS = '\\ColissimoHomeDelivery\\Model\\ColissimoHomeDeliveryPriceSlices';
/**
* A class that can be returned by this tableMap
*/
const CLASS_DEFAULT = 'ColissimoHomeDelivery.Model.ColissimoHomeDeliveryPriceSlices';
/**
* The total number of columns
*/
const NUM_COLUMNS = 5;
/**
* The number of lazy-loaded columns
*/
const NUM_LAZY_LOAD_COLUMNS = 0;
/**
* The number of columns to hydrate (NUM_COLUMNS - NUM_LAZY_LOAD_COLUMNS)
*/
const NUM_HYDRATE_COLUMNS = 5;
/**
* the column name for the ID field
*/
const ID = 'colissimo_home_delivery_price_slices.ID';
/**
* the column name for the AREA_ID field
*/
const AREA_ID = 'colissimo_home_delivery_price_slices.AREA_ID';
/**
* the column name for the MAX_WEIGHT field
*/
const MAX_WEIGHT = 'colissimo_home_delivery_price_slices.MAX_WEIGHT';
/**
* the column name for the MAX_PRICE field
*/
const MAX_PRICE = 'colissimo_home_delivery_price_slices.MAX_PRICE';
/**
* the column name for the SHIPPING field
*/
const SHIPPING = 'colissimo_home_delivery_price_slices.SHIPPING';
/**
* The default string format for model objects of the related table
*/
const DEFAULT_STRING_FORMAT = 'YAML';
/**
* holds an array of fieldnames
*
* first dimension keys are the type constants
* e.g. self::$fieldNames[self::TYPE_PHPNAME][0] = 'Id'
*/
protected static $fieldNames = array (
self::TYPE_PHPNAME => 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();

View File

@@ -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 ```<thelia_root>/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 |

View File

@@ -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"
}
}

View File

@@ -0,0 +1,166 @@
{javascripts file='assets/js/bootstrap-switch/bootstrap-switch.js'}
<script src='{$asset_url}'></script>
{/javascripts}
{javascripts file='assets/js/libs/underscore-min.js'}
<script src="{$asset_url}"></script>
{/javascripts}
<script>
var config = {
'urlAdd': '{url path="/admin/module/ColissimoHomeDelivery/price-slice/save"}',
'urlDelete': '{url path="/admin/module/ColissimoHomeDelivery/price-slice/delete"}',
'urlSave': '{url path="/admin/module/ColissimoHomeDelivery/price-slice/save"}'
};
$(document).ready(function() {
var checkboxes = [];
// Price slice
var tpl = _.template($("#tpl-slice").html());
var showMessage = function showMessage(message) {
$('#colissimo_home_delivery_dialog')
.find('.modal-body')
.html(message)
.end()
.modal("show");
};
var getSliceData = function getSliceData($slice) {
var data = {
id: $slice.data("id"),
area: $slice.data("area"),
shipping: $slice.find(".js-slice-shipping").first().val(),
maxPrice: $slice.find(".js-slice-max-price").first().val(),
maxWeight: $slice.find(".js-slice-max-weight").first().val()
};
return data;
};
// add new slice
$('.js-slice-add').on('click', function(){
var $slice = $(this).parents('tr').first();
var data = getSliceData($slice);
$.ajax({
type: "POST",
dataType: 'json',
data: data,
url: config.urlAdd
}).done(function(data, textStatus, jqXHR){
var sliceHtml = '';
if (data.success) {
// reset form
$slice.find('input').val('');
// add slice
sliceHtml = tpl(data.slice);
$(sliceHtml).insertBefore($slice);
} else {
showMessage(data.message.join('<br>'));
}
}).fail(function(jqXHR, textStatus, errorThrown){
console.log(jqXHR);
showMessage(jqXHR.responseText);
});
});
// save new slice
$('.slices').on('click', '.js-slice-save', function(){
var $slice = $(this).parents('tr').first();
var data = getSliceData($slice);
$.ajax({
type: "POST",
dataType: 'json',
data: data,
url: config.urlAdd
}).done(function(data, textStatus, jqXHR){
if (!data.success) {
showMessage(data.message.join('<br>'));
} else {
var sliceHtml = tpl(data.slice);
$(sliceHtml).insertBefore($slice);
$slice.remove();
// $slice.find('.js-slice-save').removeClass('btn-success');
}
}).fail(function(jqXHR, textStatus, errorThrown){
console.log(jqXHR);
showMessage(jqXHR.responseText);
});
});
$('.slices').on('change', '.js-slice input', function() {
$(this).parents('tr').first().find('.js-slice-save').addClass('btn-success');
});
// delete new slice
$('.slices').on('click', '.js-slice-delete', function(){
var $slice = $(this).parents('tr').first();
var data = getSliceData($slice);
$.ajax({
type: "POST",
dataType: 'json',
data: data,
url: config.urlDelete
}).done(function(data, textStatus, jqXHR){
var sliceHtml = '';
if (data.success) {
$slice.remove();
} else {
showMessage(data.message);
}
}).fail(function(jqXHR, textStatus, errorThrown){
console.log(jqXHR);
showMessage(jqXHR.responseText);
});
});
// add new slice
$('.js-slice input').on('change', function(){
});
$(".freeshipping-activation-ColissimoHomeDelivery").bootstrapSwitch();
$(".freeshipping-activation-ColissimoHomeDelivery").on("switch-change", function(e, data){
var is_checked = data.value;
var form = $("#freeshippingform");
$('body').append('<div class="modal-backdrop fade in" id="loading-event"><div class="loading"></div></div>');
$.ajax({
url: form.attr('action'),
type: form.attr('method'),
data: form.serialize(),
}).done(function(){
$("#loading-event").remove();
}).fail(function(jqXHR, textStatus, errorThrown){
$('#freeshipping-failed-body').html(jqXHR.responseJSON.error);
$("#freeshipping-failed").modal("show");
});
});
$("#freeshippingform").submit(function(e, data){
var form = $("#freeshippingform");
$('body').append('<div class="modal-backdrop fade in" id="loading-event"><div class="loading"></div></div>');
$.ajax({
url: form.attr('action'),
type: form.attr('method'),
data: form.serialize(),
}).done(function(){
$("#loading-event").remove();
}).fail(function(jqXHR, textStatus, errorThrown){
$('#freeshipping-failed-body').html(jqXHR.responseJSON.error);
$("#freeshipping-failed").modal("show");
});
});
});
</script>

View File

@@ -0,0 +1,286 @@
{if isset($smarty.get.tab)}
{$tab=$smarty.get.tab}
{else}
{$tab='prices-dom'}
{/if}
<style>
input[type=number]
{
min-width:100px;
}
</style>
<div class="row">
<div class="col-md-12">
<div class="general-block-decorator">
<div class="row">
<div class="col-md-12">
<ul id="tabbed-menu" class="nav nav-tabs">
<li class="{if $tab eq "prices-dom"}active{/if}"><a data-toggle="tab" href="#prices-dom">{intl l="Price slices (Dom)" d='colissimo.home.delivery.bo.default'}</a> </li>
<li class="{if $tab eq "config"}active{/if}"><a data-toggle="tab" href="#config">{intl l="Configuration" d='colissimo.home.delivery.bo.default'}</a> </li>
</ul>
<div class="tab-content">
<!-- I have no idea why but I can't delete this without breaking the page -->
<div id="labels" class="tab-pane {if $tab eq "labels"}active{/if} form-container">
</div>
<div id="config" class="tab-pane {if $tab eq "config"}active{/if} form-container">
<br>
<div class="title">
{intl l="Colissimo Web service configuration" d='colissimo.home.delivery.bo.default'}
</div>
{form name="colissimo.homedelivery.configuration.form"}
{if $form_error}<div class="alert alert-danger">{$form_error_message}</div>{/if}
<form action="{url path="/admin/module/ColissimoHomeDelivery/configure"}" method="post">
{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}
<div class="alert alert-danger">{$form_error_message}</div>
{/if}
{if $smarty.get.success}
<div class="alert alert-success">Les données de configuration ont été mises à jour.</div>
{/if}
<div class="panel panel-default">
<div class="panel-heading">
<div class="panel-title">{intl d='colissimo.home.delivery.bo.default' l="Configuration du service"}</div>
</div>
<div class="panel-body">
<div class="row" style="margin-top: 20px;">
<div class="col-md-6">
{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}
</div>
<div class="col-md-6">
{render_form_field field="affranchissement_endpoint_url" value=$affranchissement_endpoint_url}
{render_form_field field="activate_detailed_debug" value=$activate_detailed_debug}
</div>
</div>
</div>
</div>
</form>
{/form}
</div>
<div id="prices-dom" class="tab-pane {if $tab eq "prices-dom"}active{/if} form-container">
<br>
<div class="title">
{intl l="Price slices for domicile delivery" d='colissimo.home.delivery.bo.default'}
</div>
<!-- ********* FREE SHIPPING BUTTON ********* -->
<div class="row">
<!-- checkbox free shipping -->
{assign var="isColissimoHomeDeliveryFreeshipping" value=0}
{form name="colissimo.homedelivery.freeshipping.form"}
<form action='{url path="/admin/module/ColissimoHomeDelivery/freeshipping"}' method="post" id="freeshippingform">
<div class="col-md-4">
{form_hidden_fields form=$form}
{form_field form=$form field="freeshipping"}
<label>
{intl l="Activate total free shipping " d="colissimo.home.delivery.bo.default"}
</label>
<div class="switch-small freeshipping-activation-ColissimoHomeDelivery" data-on="success" data-off="danger" data-on-label="<i class='glyphicon glyphicon-ok-circle'></i>" data-off-label="<i class='glyphicon glyphicon-remove-circle'></i>">
{loop type="colissimo.homedelivery.freeshipping" name="freeshipping_colissimo_home_delivery"}
<input type="checkbox" name="{$name}" value="true" {if $FREESHIPPING_ACTIVE}checked{assign var="isColissimoHomeDeliveryFreeshipping" value=1}{/if} />
{/loop}
</div>
{/form_field}
</div>
<div class="col-md-6" id="freeshipping-from">
<div class="input-group">
{form_field form=$form field="freeshipping_from"}
{loop type="colissimo.homedelivery.freeshipping" name="freeshipping_colissimo_home_delivery"}
<span class="input-group-addon {if $FREESHIPPING_FROM}alert-success{/if}">{intl l="Or activate free shipping from (€) :" d="colissimo.home.delivery.bo.default"}</span>
<input type="number" name="{$name}" class="form-control" value="{$value}" step="0.01">
{/loop}
{/form_field}
<span class="input-group-btn">
<button class="btn btn-default" type="submit">{intl l="Save"}</button>
</span>
</div>
</div>
</form>
{/form}
</div>
<br>
<!-- **************************************** -->
<div class="alert alert-info">
{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'}
</div>
<div class="slices form-container">
{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}
<div class="col-md-12">
<div class="table-responsive">
<table class="table table-striped table-condensed table-left-aligned">
<thead>
<tr>
<th>
<label class="clearfix">
<small>{intl d='colissimo.home.delivery.bo.default' l="Area : "}</small> {$NAME}
</label>
</th>
<th width="40%">
<div id="area-freeshipping-{$area_id}" {if $isColissimoHomeDeliveryFreeshipping eq 1} style="display:none;" {/if}>
<form action="{url path="/admin/module/ColissimoHomeDelivery/area_freeshipping"}" method="post">
<div class="input-group">
<span class="input-group-addon {if $area_id }alert-success{/if}">{intl l="Activate free shipping from (€) :" d="colissimo.home.delivery.bo.default"}</span>
<input type="hidden" name="area-id" value="{$area_id}">
<input type="hidden" name="delivery-mode" value="{$deliveryModeId}">
{ifloop rel="area_freeshipping"}
{loop type="colissimo.homedelivery.area.freeshipping" name="area_freeshipping" area_id=$area_id}
<input type="number" step="0.01" name="cart-amount" class="form-control" value="{$CART_AMOUNT}">
{/loop}
{/ifloop}
{elseloop rel="area_freeshipping"}
<input type="number" step="0.01" name="cart-amount" class="form-control" value="">
{/elseloop}
<span class="input-group-btn">
<button class="btn btn-default" type="submit">{intl l="Save"}</button>
</span>
</div>
</form>
</div>
</th>
</tr>
</thead>
<thead>
<tr>
<th class="col-md-3">{intl l="Weight up to ... kg" d='colissimo.home.delivery.bo.default'}</th>
<th class="col-md-3">{intl l="Untaxed Price up to ... ($)" d='colissimo.home.delivery.bo.default'}</th>
<th class="col-md-5">{intl l="Shipping Price ($)" d='colissimo.home.delivery.bo.default'}</th>
<th class="col-md-1">{intl l="Actions" d='colissimo.home.delivery.bo.default'}</th>
</tr>
</thead>
<tbody>
{loop type="colissimo.homedelivery.price-slices" name="colissimo_home_delivery_area_$ID" area_id={$area_id} }
<tr class="js-slice" data-area="{$area_id}" data-id="{$SLICE_ID}" >
<th class="col-md-3">
<input type="text" data-field="max-weight" class="form-control js-slice-max-weight" value="{$MAX_WEIGHT}" data-old="{$MAX_WEIGHT}" />
</th>
<th class="col-md-3">
<input type="text" data-field="max-price" class="form-control js-slice-max-price" value="{$MAX_PRICE}" data-old="{$MAX_PRICE}" />
</th>
<th class="col-md-5">
<input type="text" data-field="shipping" class="form-control js-slice-shipping" value="{$SHIPPING}" data-old="{$SHIPPING}" />
</th>
<th class="col-md-1">
<div class="btn-group">
{loop type="auth" name="can_change" role="ADMIN" module="customdelivery" access="UPDATE"}
<a class="btn btn-default btn-xs js-slice-save" title="{intl d='colissimo.home.delivery.bo.default' l='Save this price slice'}">
<span class="glyphicon glyphicon-floppy-disk"></span>
</a>
{/loop}
{loop type="auth" name="can_change" role="ADMIN" module="customdelivery" access="DELETE"}
<a class="btn btn-default btn-xs js-slice-delete" title="{intl d='colissimo.home.delivery.bo.default' l='Delete this price slice'}" data-id="{$ID}">
<span class="glyphicon glyphicon-trash"></span>
</a>
{/loop}
</div>
</th>
</tr>
{/loop}
{* New slice *}
{loop type="auth" name="can_change" role="ADMIN" module="colissimohomedelivery" access="CREATE"}
<tr class="js-slice-new" data-area="{$area_id}" data-id="0">
<th class="col-md-3">
<input type="text" data-field="max-weight" class="form-control js-slice-max-weight" value="" />
</th>
<th class="col-md-3">
<input type="text" data-field="max-price" class="form-control js-slice-max-price" value="" />
</th>
<th class="col-md-5">
<input type="text" data-field="shipping" class="form-control js-slice-shipping" value="" />
</th>
<th class="col-md-1">
<a class="btn btn-default btn-xs js-slice-add" title="{intl d='colissimo.home.delivery.bo.default' l='Add this price slice'}" >
<span class="glyphicon glyphicon-plus"></span>
</a>
</th>
</tr>
{/loop}
</tbody>
</table>
</div>
</div>
{/loop}
{elseloop rel="area_loop"}
<div class="col-md-12">
<div class="alert alert-warning">
{intl d='colissimo.home.delivery.bo.default' l="You should first attribute shipping zones to the modules: "}
<a href="{url path="/admin/configuration/shipping_zones/update/$module_id"}">
{intl d='colissimo.home.delivery.bo.default' l="manage shipping zones"}
</a>
</div>
</div>
{/elseloop}
{/loop}
</div>
</div>
{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 *}
<script id="tpl-slice" type="text/html">
<tr class="js-slice" data-area="<%=areaId %>" data-id="<%=id %>">
<th class="col-md-3">
<input type="text" data-field="max-weight" class="form-control js-slice-max-weight" value="<%=maxWeight %>" data-old="<%=maxWeight %>" />
</th>
<th class="col-md-3">
<input type="text" data-field="max-price" class="form-control js-slice-max-price" value="<%=maxPrice %>" data-old="<%=maxPrice %>" />
</th>
<th class="col-md-5">
<input type="text" data-field="shipping" class="form-control js-slice-shipping" value="<%=shipping %>" data-old="<%=shipping %>" />
</th>
<th class="col-md-1">
<div class="btn-group">
{loop type="auth" name="can_change" role="ADMIN" module="colissimohomedelivery" access="UPDATE"}
<a class="btn btn-default btn-xs js-slice-save" title="{intl d='colissimo.home.delivery.bo.default' l='Save this price slice'}">
<span class="glyphicon glyphicon-floppy-disk"></span>
</a>
{/loop}
{loop type="auth" name="can_change" role="ADMIN" module="colissimohomedelivery" access="DELETE"}
<a class="btn btn-default btn-xs js-slice-delete" title="{intl d='colissimo.home.delivery.bo.default' l='Delete this price slice'}" data-id="<%=id %>">
<span class="glyphicon glyphicon-trash"></span>
</a>
{/loop}
</div>
</th>
</tr>
</script>
</div>
</div>
</div>

View File

@@ -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}
<p>{if {$TITLE} == 9}{intl l="Dear Mr. "}
{else}{intl l="Dear Ms. "}
{/if}
{$FIRSTNAME} {$LASTNAME},
</p>
{/loop}
<p>{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"} <strong>{$package}</strong>.</p>
<p>{intl l='<a href="https://www.colissimo.fr/portail_colissimo/suivreResultat.do?parcelnumber=%package">Click here</a> to track your shipment. You can also enter the tracking number on <a href="https://www.laposte.fr/outils/suivre-vos-envois">https://www.laposte.fr/outils/suivre-vos-envois</a>' package=$package}</p>
<p>{intl l='Thank you for your shopping with us and hope to see you soon on <a href="#">www.yourshop.com</a>'}</p>
<p>{intl l="Your on-line store Manager"}<br/>
{intl l="Your shop"}</p>
{/block}

View File

@@ -0,0 +1 @@
{intl l="Please display this message in HTML"}

View File

@@ -0,0 +1,8 @@
#point-colissimo-homedelivery .panel-body {
padding: 10px !important;
}
#point-colissimo-homedelivery .panel-body span {
color: red;
padding-left: 10px !important;
}

View File

@@ -0,0 +1,27 @@
<tr display="">
<td colspan="3">
<div id="point-colissimo-homedelivery">
<div class="panel panel-default">
<div class="panel-heading">
<strong>{intl l="Titre Avec signature" d="colissimohomedelivery.fo.default"}</strong>
</div>
<div class="panel-body">
<input type="checkbox" id="choix-remise" name="remise-avec-signature">&nbsp;<span>{intl l="Message Avec signature" d="colissimohomedelivery.fo.default" surcout={config key="surcout_remise_avec_signature"} unite={currency attr="symbol"}}</span>
</div>
</div>
</td>
</tr>
<script>
$(function(){
/*
$('#choix-remise').on('click', function() {
if ($("#choix-remise").is(':checked')) {
$("#delivery-module-{$module_id} > div.price").text("10 €");
}
});
*/
});
</script>

View File

@@ -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}
<style>
body, table, .footer {
font-size: 10px;
color: #000;
line-height: 12px;
}
.footer {
text-align: center;
margin-bottom: 10px;
font-size: 10px;
}
.logo img {
width: 250px;
}
table {
border-collapse: collapse;
width: 100%;
}
tr {
width: 100%;
}
td {
vertical-align: top;
}
.borders {
border: 0.2px solid #9d9d9c;
}
.titre-container {
margin-bottom: 5mm;
}
.titre-container .titre {
font-size: 5mm;
text-transform: uppercase;
font-weight: bold;
}
.right {
text-align: right;
}
h3 {
font-size: 10px;
font-weight: bold;
}
{
hook name = "invoice.css"
}
.goods tr td, .goods tr th {
padding: 1mm;
}
.recap p {
margin: 2mm 0;
padding: 0;
}
</style>
{/literal}
<page backtop="10mm" backleft="10mm" backright="10mm" backbottom="10mm">
<page_header>
</page_header>
<page_footer>
<div class="footer">
{intl l="{$store_name} - {$store_address1} - Phone : {$store_phone}"}
<br>
{intl l="{$store_description} - Legal numbers (ex: SIRET)"}
<br>
{intl l="Shop - Email : {$store_email} - Phone : {$store_phone}"}
</div>
</page_footer>
{$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}
<table>
<col style="width: 60%; padding: 0; margin: 0; padding-right: 2mm;">
<col style="width: 40%; padding: 0; margin: 0; padding-left: 2mm;">
<tr>
<td>
</td>
<td>
<table>
<col style="width: 100%; padding: 2mm;">
<tr>
<td class="borders titre">Sender</td>
</tr>
<tr>
<td class="borders">
<p>
{$store_name}
{$store_address1}<br>
{if $store_address2!=null} {$store_address2} <br> {/if}
{if $store_address3!=null} {$store_address3} <br> {/if}
{$store_zipcode} {$store_city}<br>
{$store_country}<br>
</p>
</td>
</tr>
</table>
</td>
</tr>
</table>
<div class="titre-container">
<div class="titre">Commercial Invoice</div>
Date: {format_date date=$INVOICE_DATE output="date"}<br>
Invoice number: {$REF}
</div>
<div class="bloc-adresse">
<table>
<col style="width: 50%; padding: 0; margin: 0; padding-right: 2mm;">
<col style="width: 50%; padding: 0; margin: 0; padding-left: 2mm;">
<tr>
<td>
<table>
<col style="width: 100%; padding: 2mm;">
<tr>
<td class="borders titre">Delivery address</td>
</tr>
<tr>
<td class="borders" height="92">
<p>
{loop type="order_address" name="delivery_address" id=$DELIVERY_ADDRESS}
{loop type="title" name="order-invoice-address-title" id=$TITLE}{$LONG} {/loop} {$FIRSTNAME} {$LASTNAME}
<br/>
{if ! empty($COMPANY)}
{$COMPANY}
<br/>
{/if}
{$ADDRESS1} {$ADDRESS2} {$ADDRESS3}
<br/>
{$ZIPCODE} {$CITY}
<br/>
{loop type="country" name="country_delivery" id=$COUNTRY}{$TITLE}{/loop}
<br/>
{$PHONE}
{/loop}
</p>
</td>
</tr>
</table>
</td>
<td>
<table>
<col style="width: 100%; padding: 2mm;">
<tr>
<td class="borders titre">Invoice address</td>
</tr>
<tr>
<td class="borders" height="92">
<p>
{loop type="order_address" name="delivery_address" id=$INVOICE_ADDRESS}
{loop type="title" name="order-invoice-address-title" id=$TITLE}{$LONG} {/loop}{$FIRSTNAME} {$LASTNAME}
<br/>
{if ! empty($COMPANY)}
{$COMPANY}
<br/>
{/if}
{$ADDRESS1} {$ADDRESS2} {$ADDRESS3}
<br/>
{$ZIPCODE} {$CITY}
<br/>
{loop type="country" name="country_delivery" id=$COUNTRY}{$TITLE}{/loop}
<br/>
{$PHONE} {$MOBILE}
{/loop}
<br/>
{loop type="customer" name="customer_email" id=$CUSTOMER current="0"}
{$EMAIL}
{/loop}
</p>
</td>
</tr>
</table>
</td>
</tr>
</table>
</div>
{$totalValue = $TOTAL_TAXED_AMOUNT - $POSTAGE_UNTAXED}
{$itemCount = 0}
<!-- le tableau des produits -->
<table class="goods" cellspacing="0" cellpadding="0" style="padding-top: 20px; width: 100%; margin-bottom: 0;">
<col style="width: 40%;"/>
<col style="width: 5%; "/>
<col style="width: 10%;"/>
<col style="width: 13%;"/>
<col style="width: 15%;"/>
<col style="width: 7%;"/>
<col style="width: 10%;"/>
<tr class="table-1">
<td class="borders titre">{intl l="Full Description of Goods"}</td>
<td class="borders titre right">{intl l="Quantity"}</td>
<td class="borders titre right">{intl l="Unit value"}</td>
<td class="borders titre right">{intl l="Subtotal value"}</td>
<td class="borders titre right">{intl l="Unit net weight"}</td>
<td class="borders titre">{intl l="Country"}</td>
<td class="borders titre">{intl l="Comm. code"}</td>
</tr>
{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}
<tr class="table-2">
<td class="borders" style="line-height:14px;">
{$itemCount = $itemCount + $QUANTITY}
{$TITLE}
{ifloop rel="combinations"}
<br>
{loop type="order_product_attribute_combination" name="combinations" order_product=$ID}
- {$ATTRIBUTE_TITLE} - {$ATTRIBUTE_AVAILABILITY_TITLE}
<br>
{/loop}
{/ifloop}
{loop type="marquage.orderproduct" name="gravures" order_product_id=$ID}
{loop type="marquage.police" name="police" id=$POLICE}
{$nomPolice = $NOM}
{/loop}
<br/>
{intl l='Engraving '}:
<br/>
- {intl l='Font '}: {$nomPolice}
<br/>
- {intl l='Position '}: {$POSITION}
<br/>
- {intl l='Style '}: {$TYPE}
<br/>
- {intl l='Your text '}: {$TEXTE}
{/loop}
</td>
<td class="borders right">{$QUANTITY}</td>
<td class="borders right">{format_money number=$realTaxedPrice symbol=$orderCurrencySymbol}</td>
<td class="borders right">{format_money number={$realTaxedPrice * $QUANTITY} symbol=$orderCurrencySymbol}</td>
<td class="borders right">{$WEIGHT}</td>
<td class="borders">France</td>
<td class="borders">&nbsp;</td>
</tr>
{/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"})}
<tr class="table-2">
<td class="borders" style="line-height:14px;">{intl l="Free samples "}: {$ECHANTILLON_1}
, {$ECHANTILLON_2}</td>
<td class="borders right">1</td>
<td class="borders right">{format_money number=$prixEchantillons}</td>
<td class="borders right">{format_money number=$prixEchantillons}</td>
<td class="borders right"></td>
<td class="borders">France</td>
<td class="borders">&nbsp;</td>
{$totalValue = $totalValue + $prixEchantillons}
{$itemCount = $itemCount + 1}
</tr>
{/if}
{if ! empty($CADEAU)}
{$prixCadeau = floatval({config key="tarif_cadeau_export"})}
<tr class="table-2">
<td class="borders" style="line-height:14px;">{intl l="Your gift "}: {$CADEAU}</td>
<td class="borders right">1</td>
<td class="borders right">{format_money number=$prixCadeau}</td>
<td class="borders right">{format_money number=$prixCadeau}</td>
<td class="borders right"></td>
<td class="borders">France</td>
<td class="borders">&nbsp;</td>
{* A changer si besoin *}
{$totalValue = $totalValue + $prixCadeau}
{$itemCount = $itemCount + 1}
</tr>
{/if}
{/loop}
</table>
{if $POSTAGE_TAX_RULE_TITLE}
{$taxes[$POSTAGE_TAX_RULE_TITLE][] = $POSTAGE_TAX}
{/if}
<table class="recap" align="right" cellspacing="0" cellpadding="0" style="width: 100%;">
<col style="width: 40%; padding: 2mm;"/>
<col style="width: 30%; padding: 2mm;"/>
<col style="width: 30%; padding: 2mm;"/>
<tr>
<td style="border-right: 0.2px solid #9d9d9c;">&nbsp;</td>
<td class="borders">
<p>Total declared value : {format_money number={$totalValue} symbol=$orderCurrency}</p>
<p>Total units: {$itemCount}</p>
</td>
<td class="borders">
<p>Total Net Weight: {$WEIGHT} kg(s)</p>
{* Mettre une estimation du poids brut *}
<p>Total Gross Weight: {$WEIGHT + 0} kg(s)</p>
</td>
</tr>
</table>
<table class="recap" align="right" cellspacing="0" cellpadding="0" style="width: 100%; margin-top: 10mm">
<col style="width: 50%; padding: 2mm;"/>
<col style="width: 50%; padding: 2mm;"/>
<tr>
<td>
<p>Type of Export: permanent</p>
<p>Reason for Export</p>
</td>
<td>
<p>Currency Code :{$orderCurrency}</p>
<p>Terms of Trade : DAP</p>
<p>City Name of liability</p>
</td>
</tr>
</table>
<table class="recap" align="right" cellspacing="0" cellpadding="0" style="width: 100%; margin-top: 10mm">
<col style="width: 50%; padding: 2mm;"/>
<col style="width: 50%; padding: 2mm;"/>
<tr>
<td>
<p>Signature: {intl l="Sender's name"}</p>
<p>Airwaybill Number:</p>
</td>
<td>
<p>Company Stamp: {$store_name}</p>
<p>{$store_zipcode} {$store_city}</p>
</td>
</tr>
</table>
{/loop}
</page>

View File

@@ -0,0 +1,410 @@
<?php
/*************************************************************************************/
/* 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. */
/*************************************************************************************/
namespace ColissimoLabel;
use ColissimoHomeDelivery\ColissimoHomeDelivery;
use ColissimoLabel\Request\Helper\OutputFormat;
use ColissimoLabel\Request\Helper\Service;
use ColissimoPickupPoint\ColissimoPickupPoint;
use ColissimoWs\ColissimoWs;
use Propel\Runtime\Connection\ConnectionInterface;
use Propel\Runtime\Exception\PropelException;
use SoColissimo\SoColissimo;
use Symfony\Component\Filesystem\Filesystem;
use Symfony\Component\Finder\Finder;
use Thelia\Model\ConfigQuery;
use Thelia\Model\ModuleQuery;
use Thelia\Model\Order;
use Thelia\Module\BaseModule;
use Thelia\Install\Database;
/**
* @author Gilles Bourgeat >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));
}
}

View File

@@ -0,0 +1,60 @@
<?xml version="1.0" encoding="UTF-8" ?>
<config xmlns="http://thelia.net/schema/dic/config"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://thelia.net/schema/dic/config http://thelia.net/schema/dic/config/thelia-1.0.xsd">
<loops>
<loop name="colissimolabel.orders-not-sent" class="ColissimoLabel\Loop\OrdersNotSentLoop" />
<loop name="colissimolabel.label-info" class="ColissimoLabel\Loop\ColissimoLabelInfo" />
</loops>
<forms>
<form name="colissimolabel.configure" class="ColissimoLabel\Form\ConfigureColissimoLabel" />
<form name="colissimolabel_export_form" class="ColissimoLabel\Form\LabelGenerationForm" />
</forms>
<commands>
<!--
<command class="ColissimoLabel\Command\MySuperCommand" />
-->
</commands>
<services>
<service id="colissimolabel.update.oder.address.listener" class="ColissimoLabel\EventListeners\UpdateDeliveryAddressListener">
<argument type="service" id="event_dispatcher"/>
<argument type="service" id="service_container"/>
<tag name="kernel.event_subscriber"/>
</service>
<service id="colissimolabel.generate.label.service" class="ColissimoLabel\Service\LabelService">
<argument type="service" id="event_dispatcher"/>
</service>
<service id="picking.colissimolabel.generate.label.listener" class="ColissimoLabel\EventListeners\GenerateLabelListener">
<argument type="service" id="colissimolabel.generate.label.service"/>
<tag name="kernel.event_subscriber"/>
</service>
</services>
<hooks>
<hook id="colissimo.label.hook.back.order_edit" class="ColissimoLabel\Hook\Back\OrderEditHook">
<tag name="hook.event_listener" event="order.edit-js" type="back" method="onOrderEditJs" />
</hook>
<hook id="colissimo.label.hook.hook.main.in.top.menu.items" class="ColissimoLabel\Hook\Back\MenuHook">
<tag name="hook.event_listener" event="main.in-top-menu-items" type="back" />
</hook>
</hooks>
<!--
<exports>
</exports>
-->
<!--
<imports>
</imports>
-->
</config>

View File

@@ -0,0 +1,24 @@
<?xml version="1.0" encoding="UTF-8"?>
<module xmlns="http://thelia.net/schema/dic/module"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://thelia.net/schema/dic/module http://thelia.net/schema/dic/module/module-2_2.xsd">
<fullnamespace>ColissimoLabel\ColissimoLabel</fullnamespace>
<descriptive locale="en_US">
<title>Generate the delivery labels for Colissimo</title>
</descriptive>
<descriptive locale="fr_FR">
<title>Genérer les étiquettes de livraison pour Colissimo</title>
</descriptive>
<languages>
<language>en_US</language>
<language>fr_FR</language>
</languages>
<version>1.0.4</version>
<author>
<name>Gilles Bourgeat</name>
<email>gbourgeat@openstudio.fr</email>
</author>
<type>classic</type>
<thelia>2.2.0</thelia>
<stability>beta</stability>
</module>

View File

@@ -0,0 +1,63 @@
<?xml version="1.0" encoding="UTF-8" ?>
<routes xmlns="http://symfony.com/schema/routing"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://symfony.com/schema/routing http://symfony.com/schema/routing/routing-1.0.xsd">
<route id="colissimolabel.export" path="/admin/module/colissimolabel/export">
<default key="_controller">ColissimoLabel\Controller\Admin\OrderController::generateLabelAction</default>
</route>
<route id="colissimolabel.get_zip" path="/admin/module/colissimolabel/labels-zip/{base64EncodedZipFilename}">
<default key="_controller">ColissimoLabel\Controller\Admin\OrderController::getLabelZip</default>
<requirement key="base64ZipFilePath">[A-Za-z0-9]+</requirement>
</route>
<route id="colissimolabel.admin.get.label" path="/admin/module/colissimolabel/label/{number}">
<default key="_controller">ColissimoLabel\Controller\Admin\OrderController::getLabelAction</default>
<requirement key="number">[0-9A-Z]+</requirement>
</route>
<route id="colissimolabel.admin.get.customs.invoice" path="/admin/module/colissimolabel/customs-invoice/{orderId}">
<default key="_controller">ColissimoLabel\Controller\Admin\OrderController::getCustomsInvoiceAction</default>
<requirement key="orderId">[0-9A-Z]+</requirement>
</route>
<route id="colissimolabel.admin.delete.label" path="/admin/module/colissimolabel/label/delete/{number}" methods="get">
<default key="_controller">ColissimoLabel\Controller\Admin\OrderController::deleteLabelAction</default>
<requirement key="number">[0-9A-Z]+</requirement>
</route>
<route id="colissimolabel.admin.get.list-labels" path="/admin/module/colissimolabel/order/{orderId}/ajax-get-labels" methods="get">
<default key="_controller">ColissimoLabel\Controller\Admin\OrderController::getOrderLabelsAction</default>
<requirement key="id">[0-9]+</requirement>
</route>
<route id="colissimolabel.admin.bordereau.list" path="/admin/module/colissimolabel/bordereaux" methods="get">
<default key="_controller">ColissimoLabel\Controller\Admin\BordereauController::listBordereauAction</default>
</route>
<route id="colissimolabel.admin.configuration" path="/admin/module/colissimolabel/configuration" methods="get">
<default key="_controller">ColissimoLabel\Controller\Admin\ConfigurationController::renderConfigPageAction</default>
</route>
<route id="colissimolabel.admin.configuration.save" path="/admin/module/colissimolabel/configuration/save" methods="post">
<default key="_controller">ColissimoLabel\Controller\Admin\ConfigurationController::saveConfig</default>
</route>
<route id="colissimolabel.admin.labels" path="/admin/module/colissimolabel/labels" methods="get">
<default key="_controller">ColissimoLabel\Controller\Admin\BordereauController::listLabelsAction</default>
</route>
<route id="colissimolabel.admin.bordereau.generate" path="/admin/module/colissimolabel/bordereau/generate" methods="get">
<default key="_controller">ColissimoLabel\Controller\Admin\BordereauController::generateBordereauAction</default>
</route>
<route id="colissimolabel.admin.bordereau.download" path="/admin/module/colissimolabel/bordereau/download" methods="get">
<default key="_controller">ColissimoLabel\Controller\Admin\BordereauController::downloadBordereauAction</default>
</route>
<route id="colissimolabel.admin.bordereau.delete" path="/admin/module/colissimolabel/bordereau/delete">
<default key="_controller">ColissimoLabel\Controller\Admin\BordereauController::deleteBordereauAction</default>
</route>
</routes>

View File

@@ -0,0 +1,26 @@
<?xml version="1.0" encoding="UTF-8"?>
<database defaultIdMethod="native" name="thelia"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="../../../../vendor/propel/propel/resources/xsd/database.xsd" >
<table name="colissimo_label" namespace="ColissimoLabel\Model">
<column autoIncrement="true" name="id" primaryKey="true" required="true" type="INTEGER" /> <!-- Old -->
<column name="order_id" type="INTEGER" required="true" /> <!-- Old -->
<column name="order_ref" type="VARCHAR" size="255" required="true"/> <!-- New -->
<column name="error" type="BOOLEAN" required="true" default="0" /> <!-- New -->
<column name="error_message" type="VARCHAR" size="255" default="" /> <!-- New -->
<column name="tracking_number" type="VARCHAR" size="255" /> <!-- Old - To Remove & change to tracking number -->
<column name="label_type" type="VARCHAR" size="4" /> <!-- New -->
<column name="weight" type="DECIMAL" scale="2" size="6" defaultValue="0.00" /> <!-- Old -->
<column name="signed" type="BOOLEAN" required="true" default="0" /> <!-- Old : Ex tinyint without default value -->
<column name="with_customs_invoice" type="BOOLEAN" required="true" default="0" /> <!-- New -->
<foreign-key foreignTable="order" onDelete="CASCADE" onUpdate="RESTRICT">
<reference local="order_id" foreign="id" />
</foreign-key>
<behavior name="timestampable" />
</table>
<external-schema filename="local/config/schema.xml" referenceOnly="true" />
</database>

View File

@@ -0,0 +1,2 @@
# Sqlfile -> Database map
thelia.sql=thelia

View File

@@ -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;

View File

@@ -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;

View File

@@ -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;

View File

@@ -0,0 +1,194 @@
<?php
namespace ColissimoLabel\Controller\Admin;
use ColissimoLabel\ColissimoLabel;
use ColissimoLabel\Model\ColissimoLabel as ColissimoLabelModel;
use ColissimoLabel\Model\ColissimoLabelQuery;
use ColissimoLabel\Request\Helper\BordereauRequestAPIConfiguration;
use ColissimoLabel\Service\SOAPService;
use ColissimoWs\Model\ColissimowsLabel;
use ColissimoWs\Model\ColissimowsLabelQuery;
use Propel\Runtime\ActiveQuery\Criteria;
use Symfony\Component\Filesystem\Filesystem;
use Symfony\Component\Finder\Finder;
use Symfony\Component\HttpFoundation\BinaryFileResponse;
use Symfony\Component\HttpFoundation\ResponseHeaderBag;
use Thelia\Action\File;
use Thelia\Controller\Admin\AdminController;
use Thelia\Core\HttpFoundation\Request;
use Thelia\Model\ModuleQuery;
class BordereauController extends AdminController
{
/**
* Render the bordereau list page
*
* @param null $error
* @return \Thelia\Core\HttpFoundation\Response
*/
public function listBordereauAction($error = null)
{
/** We make sure the folders exist, and create them otherwise */
ColissimoLabel::checkLabelFolder();
$lastBordereauDate = ColissimoLabel::getConfigValue(ColissimoLabel::CONFIG_KEY_LAST_BORDEREAU_DATE);
/** We get every bordereau file from the bordereau folder */
$finder = new Finder();
$finder->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("<messageContent>", $data);
$errorMessage = explode("</messageContent>", $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();
}
}

View File

@@ -0,0 +1,72 @@
<?php
namespace ColissimoLabel\Controller\Admin;
use ColissimoLabel\ColissimoLabel;
use ColissimoLabel\Form\ConfigureColissimoLabel;
use Thelia\Controller\Admin\AdminController;
use Thelia\Core\Security\AccessManager;
use Thelia\Core\Security\Resource\AdminResources;
use Thelia\Core\Translation\Translator;
use Thelia\Tools\URL;
class ConfigurationController extends AdminController
{
public function renderConfigPageAction() {
(new \ColissimoLabel\ColissimoLabel)->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();
}
}
}

View File

@@ -0,0 +1,368 @@
<?php
namespace ColissimoLabel\Controller\Admin;
use ColissimoLabel\ColissimoLabel;
use ColissimoLabel\Event\ColissimoLabelEvents;
use ColissimoLabel\Event\LabelEvent;
use ColissimoLabel\Event\LabelRequestEvent;
use ColissimoLabel\Model\ColissimoLabel as ColissimoLabelModel;
use ColissimoLabel\Model\ColissimoLabelQuery;
use ColissimoLabel\Request\Helper\BordereauRequestAPIConfiguration;
use ColissimoLabel\Service\SOAPService;
use ColissimoLabel\Request\Helper\LabelRequestAPIConfiguration;
use ColissimoLabel\Request\LabelRequest;
use ColissimoPickupPoint\Model\OrderAddressColissimoPickupPointQuery;
use ColissimoWs\Controller\LabelController;
use ColissimoWs\Model\ColissimowsLabelQuery;
use Propel\Runtime\Exception\PropelException;
use SoColissimo\Model\OrderAddressSocolissimoQuery as OrderAddressSoColissimoPickupPointQuery;
use Symfony\Component\Filesystem\Filesystem;
use Symfony\Component\Finder\Finder;
use Symfony\Component\HttpFoundation\BinaryFileResponse;
use Symfony\Component\HttpFoundation\ResponseHeaderBag;
use Symfony\Component\HttpFoundation\StreamedResponse;
use Thelia\Controller\Admin\AdminController;
use Thelia\Core\Event\Order\OrderEvent;
use Thelia\Core\Event\TheliaEvents;
use Thelia\Core\HttpFoundation\JsonResponse;
use Thelia\Core\HttpFoundation\Request;
use Thelia\Core\HttpFoundation\Response;
use Thelia\Core\Security\AccessManager;
use Thelia\Core\Security\Resource\AdminResources;
use Thelia\Exception\TheliaProcessException;
use Thelia\Model\ConfigQuery;
use Thelia\Model\ModuleQuery;
use Thelia\Model\OrderQuery;
use Thelia\Model\OrderStatusQuery;
use Thelia\Tools\URL;
class OrderController extends AdminController
{
public function generateLabelAction(Request $request)
{
if (null !== $response = $this->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');
}
}

View File

@@ -0,0 +1,11 @@
<?php
namespace ColissimoLabel\Event;
/**
* @author Gilles Bourgeat >gilles.bourgeat@gmail.com>
*/
class ColissimoLabelEvents
{
const LABEL_REQUEST = 'ColissimoLabel.labelRequest';
}

View File

@@ -0,0 +1,98 @@
<?php
namespace ColissimoLabel\Event;
use ColissimoLabel\Model\ColissimoLabel;
use Thelia\Core\Event\ActionEvent;
class LabelEvent extends ActionEvent
{
/** @var int */
protected $orderId;
/** @var ColissimoLabel */
protected $colissimoLabel = null;
/** @var float|null */
protected $weight = null;
/** @var bool|null */
protected $signed = null;
/**
* LabelEvent constructor.
* @param int $orderId
*/
public function __construct($orderId)
{
$this->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;
}
}

View File

@@ -0,0 +1,24 @@
<?php
namespace ColissimoLabel\Event;
use ColissimoLabel\Request\LabelRequest;
use Symfony\Component\EventDispatcher\Event;
/**
* @author Gilles Bourgeat >gilles.bourgeat@gmail.com>
*/
class LabelRequestEvent extends Event
{
protected $labelRequest;
public function __construct(LabelRequest $labelRequest)
{
$this->labelRequest = $labelRequest;
}
public function getLabelRequest()
{
return $this->labelRequest;
}
}

View File

@@ -0,0 +1,57 @@
<?php
namespace ColissimoLabel\EventListeners;
use ColissimoLabel\Service\LabelService;
use Picking\Event\GenerateLabelEvent;
use Picking\Picking;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Thelia\Controller\Admin\BaseAdminController;
/**
* Class GenerateLabelListener
*
* This class is used only when you have the Picking module
*
* @package ColissimoLabel\EventListeners
*/
class GenerateLabelListener extends BaseAdminController implements EventSubscriberInterface
{
protected $labelService;
/**
* @param LabelService $labelService
*/
public function __construct(LabelService $labelService)
{
$this->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;
}
}

View File

@@ -0,0 +1,274 @@
<?php
/**
* Created by PhpStorm.
* User: nicolasbarbey
* Date: 14/08/2020
* Time: 11:07
*/
namespace ColissimoLabel\EventListeners;
use ColissimoLabel\ColissimoLabel as ColissimoLabelModule;
use ColissimoLabel\Event\ColissimoLabelEvents;
use ColissimoLabel\Event\LabelRequestEvent;
use ColissimoLabel\Model\ColissimoLabel;
use ColissimoLabel\Model\ColissimoLabelQuery;
use ColissimoLabel\Request\Helper\LabelRequestAPIConfiguration;
use ColissimoLabel\Request\LabelRequest;
use ColissimoLabel\Service\SOAPService;
use ColissimoPickupPoint\Model\OrderAddressColissimoPickupPointQuery;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\Filesystem\Filesystem;
use Symfony\Component\Finder\Finder;
use Thelia\Controller\Admin\BaseAdminController;
use Thelia\Core\Event\Order\OrderAddressEvent;
use Thelia\Core\Event\TheliaEvents;
use Thelia\Core\HttpFoundation\Request;
use Thelia\Model\ConfigQuery;
use Thelia\Model\ModuleQuery;
use ColissimoWs\Model\ColissimowsLabelQuery;
use Thelia\Model\Order;
use SoColissimo\Model\OrderAddressSocolissimoQuery as OrderAddressSoColissimoPickupPointQuery;
class UpdateDeliveryAddressListener extends BaseAdminController implements EventSubscriberInterface
{
protected $dispatcher;
protected $container;
/**
* UpdateDeliveryAddressListener constructor.
* @param Request|null $request
* @param EventDispatcherInterface|null $dispatcher
* @param ContainerInterface $container
*/
public function __construct(EventDispatcherInterface $dispatcher = null, ContainerInterface $container = null)
{
$this->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]
];
}
}

View File

@@ -0,0 +1,9 @@
<?php
namespace ColissimoLabel\Exception;
/**
* @author Gilles Bourgeat >gilles.bourgeat@gmail.com>
*/
class Exception extends \Exception
{
}

View File

@@ -0,0 +1,9 @@
<?php
namespace ColissimoLabel\Exception;
/**
* @author Gilles Bourgeat >gilles.bourgeat@gmail.com>
*/
class InvalidArgumentException extends \InvalidArgumentException
{
}

View File

@@ -0,0 +1,217 @@
<?php
namespace ColissimoLabel\Form;
use ColissimoLabel\ColissimoLabel;
use ColissimoLabel\Request\Helper\OutputFormat;
use Symfony\Component\Form\Extension\Core\Type\CheckboxType;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Validator\Constraints\NotBlank;
use Thelia\Core\Translation\Translator;
use Thelia\Form\BaseForm;
class ConfigureColissimoLabel extends BaseForm
{
protected function buildForm()
{
$translator = Translator::getInstance();
$this->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';
}
}

View File

@@ -0,0 +1,75 @@
<?php
namespace ColissimoLabel\Form;
use ColissimoLabel\ColissimoLabel;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Form\Extension\Core\Type\CollectionType;
use Thelia\Core\Translation\Translator;
use Thelia\Form\BaseForm;
class LabelGenerationForm extends BaseForm
{
protected function buildForm()
{
$this->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";
}
}

View File

@@ -0,0 +1,17 @@
<?php
namespace ColissimoLabel\Hook\Back;
use Thelia\Core\Event\Hook\HookRenderEvent;
use Thelia\Core\Hook\BaseHook;
class MenuHook extends BaseHook
{
public function onMainInTopMenuItems(HookRenderEvent $event)
{
$event->add(
$this->render('colissimo-label/hook/main.in.top.menu.items.html', [])
);
}
}

View File

@@ -0,0 +1,18 @@
<?php
namespace ColissimoLabel\Hook\Back;
use ColissimoLabel\ColissimoLabel;
use Thelia\Core\Event\Hook\HookRenderEvent;
use Thelia\Core\Hook\BaseHook;
/**
* @author Gilles Bourgeat >gilles.bourgeat@gmail.com>
*/
class OrderEditHook extends BaseHook
{
public function onOrderEditJs(HookRenderEvent $event)
{
$event->add($this->render('colissimo-label/hook/order-edit-js.html'));
}
}

View File

@@ -0,0 +1,59 @@
<?php
return array(
'/kg' => '/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',
);

View File

@@ -0,0 +1,59 @@
<?php
return array(
'/kg' => '/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',
);

View File

@@ -0,0 +1,29 @@
<?php
return array(
'Account number' => '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',
);

View File

@@ -0,0 +1,29 @@
<?php
return array(
'Account number' => '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',
);

View File

@@ -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.

View File

@@ -0,0 +1,129 @@
<?php
namespace ColissimoLabel\Loop;
use ColissimoLabel\Model\ColissimoLabelQuery;
use ColissimoLabel\Model\ColissimoLabel as ColissimoLabelModel;
use ColissimoLabel\ColissimoLabel;
use ColissimoWs\ColissimoWs;
use ColissimoWs\Model\ColissimowsLabel;
use ColissimoWs\Model\ColissimowsLabelQuery;
use Symfony\Component\Finder\Finder;
use Thelia\Core\Template\Element\BaseLoop;
use Thelia\Core\Template\Element\LoopResult;
use Thelia\Core\Template\Element\LoopResultRow;
use Thelia\Core\Template\Element\PropelSearchLoopInterface;
use Thelia\Core\Template\Loop\Argument\Argument;
use Thelia\Core\Template\Loop\Argument\ArgumentCollection;
use Thelia\Model\ModuleQuery;
use Thelia\Model\OrderQuery;
use Thelia\Tools\URL;
/**
* @method int getOrderId()
*/
class ColissimoLabelInfo extends BaseLoop implements PropelSearchLoopInterface
{
/**
* @return ArgumentCollection
*/
protected function getArgDefinitions()
{
return new ArgumentCollection(
Argument::createIntTypeArgument('order_id', null, true)
);
}
public function buildModelCriteria()
{
$search = ColissimoLabelQuery::create()
->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;
}
}

View File

@@ -0,0 +1,73 @@
<?php
namespace ColissimoLabel\Loop;
use ColissimoLabel\ColissimoLabel;
use Propel\Runtime\ActiveQuery\Criteria;
use Thelia\Core\Template\Loop\Argument\Argument;
use Thelia\Core\Template\Loop\Argument\ArgumentCollection;
use Thelia\Core\Template\Loop\Order;
use Thelia\Model\ModuleQuery;
use Thelia\Model\OrderQuery;
use Thelia\Model\OrderStatus;
use Thelia\Model\OrderStatusQuery;
class OrdersNotSentLoop 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()
{
/** Get an array composed of the paid and processing order statuses */
$status = OrderStatusQuery::create()
->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;
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,904 @@
<?php
namespace ColissimoLabel\Model\Base;
use \Exception;
use \PDO;
use ColissimoLabel\Model\ColissimoLabel as ChildColissimoLabel;
use ColissimoLabel\Model\ColissimoLabelQuery as ChildColissimoLabelQuery;
use ColissimoLabel\Model\Map\ColissimoLabelTableMap;
use Propel\Runtime\Propel;
use Propel\Runtime\ActiveQuery\Criteria;
use Propel\Runtime\ActiveQuery\ModelCriteria;
use Propel\Runtime\ActiveQuery\ModelJoin;
use Propel\Runtime\Collection\Collection;
use Propel\Runtime\Collection\ObjectCollection;
use Propel\Runtime\Connection\ConnectionInterface;
use Propel\Runtime\Exception\PropelException;
use Thelia\Model\Order;
/**
* Base class that represents a query for the 'colissimo_label' table.
*
*
*
* @method ChildColissimoLabelQuery orderById($order = Criteria::ASC) Order by the id column
* @method ChildColissimoLabelQuery orderByOrderId($order = Criteria::ASC) Order by the order_id column
* @method ChildColissimoLabelQuery orderByOrderRef($order = Criteria::ASC) Order by the order_ref column
* @method ChildColissimoLabelQuery orderByError($order = Criteria::ASC) Order by the error column
* @method ChildColissimoLabelQuery orderByErrorMessage($order = Criteria::ASC) Order by the error_message column
* @method ChildColissimoLabelQuery orderByTrackingNumber($order = Criteria::ASC) Order by the tracking_number column
* @method ChildColissimoLabelQuery orderByLabelType($order = Criteria::ASC) Order by the label_type column
* @method ChildColissimoLabelQuery orderByWeight($order = Criteria::ASC) Order by the weight column
* @method ChildColissimoLabelQuery orderBySigned($order = Criteria::ASC) Order by the signed column
* @method ChildColissimoLabelQuery orderByWithCustomsInvoice($order = Criteria::ASC) Order by the with_customs_invoice column
* @method ChildColissimoLabelQuery orderByCreatedAt($order = Criteria::ASC) Order by the created_at column
* @method ChildColissimoLabelQuery orderByUpdatedAt($order = Criteria::ASC) Order by the updated_at column
*
* @method ChildColissimoLabelQuery groupById() Group by the id column
* @method ChildColissimoLabelQuery groupByOrderId() Group by the order_id column
* @method ChildColissimoLabelQuery groupByOrderRef() Group by the order_ref column
* @method ChildColissimoLabelQuery groupByError() Group by the error column
* @method ChildColissimoLabelQuery groupByErrorMessage() Group by the error_message column
* @method ChildColissimoLabelQuery groupByTrackingNumber() Group by the tracking_number column
* @method ChildColissimoLabelQuery groupByLabelType() Group by the label_type column
* @method ChildColissimoLabelQuery groupByWeight() Group by the weight column
* @method ChildColissimoLabelQuery groupBySigned() Group by the signed column
* @method ChildColissimoLabelQuery groupByWithCustomsInvoice() Group by the with_customs_invoice column
* @method ChildColissimoLabelQuery groupByCreatedAt() Group by the created_at column
* @method ChildColissimoLabelQuery groupByUpdatedAt() Group by the updated_at column
*
* @method ChildColissimoLabelQuery leftJoin($relation) Adds a LEFT JOIN clause to the query
* @method ChildColissimoLabelQuery rightJoin($relation) Adds a RIGHT JOIN clause to the query
* @method ChildColissimoLabelQuery innerJoin($relation) Adds a INNER JOIN clause to the query
*
* @method ChildColissimoLabelQuery leftJoinOrder($relationAlias = null) Adds a LEFT JOIN clause to the query using the Order relation
* @method ChildColissimoLabelQuery rightJoinOrder($relationAlias = null) Adds a RIGHT JOIN clause to the query using the Order relation
* @method ChildColissimoLabelQuery innerJoinOrder($relationAlias = null) Adds a INNER JOIN clause to the query using the Order relation
*
* @method ChildColissimoLabel findOne(ConnectionInterface $con = null) Return the first ChildColissimoLabel matching the query
* @method ChildColissimoLabel findOneOrCreate(ConnectionInterface $con = null) Return the first ChildColissimoLabel matching the query, or a new ChildColissimoLabel object populated from the query conditions when no match is found
*
* @method ChildColissimoLabel findOneById(int $id) Return the first ChildColissimoLabel filtered by the id column
* @method ChildColissimoLabel findOneByOrderId(int $order_id) Return the first ChildColissimoLabel filtered by the order_id column
* @method ChildColissimoLabel findOneByOrderRef(string $order_ref) Return the first ChildColissimoLabel filtered by the order_ref column
* @method ChildColissimoLabel findOneByError(boolean $error) Return the first ChildColissimoLabel filtered by the error column
* @method ChildColissimoLabel findOneByErrorMessage(string $error_message) Return the first ChildColissimoLabel filtered by the error_message column
* @method ChildColissimoLabel findOneByTrackingNumber(string $tracking_number) Return the first ChildColissimoLabel filtered by the tracking_number column
* @method ChildColissimoLabel findOneByLabelType(string $label_type) Return the first ChildColissimoLabel filtered by the label_type column
* @method ChildColissimoLabel findOneByWeight(string $weight) Return the first ChildColissimoLabel filtered by the weight column
* @method ChildColissimoLabel findOneBySigned(boolean $signed) Return the first ChildColissimoLabel filtered by the signed column
* @method ChildColissimoLabel findOneByWithCustomsInvoice(boolean $with_customs_invoice) Return the first ChildColissimoLabel filtered by the with_customs_invoice column
* @method ChildColissimoLabel findOneByCreatedAt(string $created_at) Return the first ChildColissimoLabel filtered by the created_at column
* @method ChildColissimoLabel findOneByUpdatedAt(string $updated_at) Return the first ChildColissimoLabel filtered by the updated_at column
*
* @method array findById(int $id) Return ChildColissimoLabel objects filtered by the id column
* @method array findByOrderId(int $order_id) Return ChildColissimoLabel objects filtered by the order_id column
* @method array findByOrderRef(string $order_ref) Return ChildColissimoLabel objects filtered by the order_ref column
* @method array findByError(boolean $error) Return ChildColissimoLabel objects filtered by the error column
* @method array findByErrorMessage(string $error_message) Return ChildColissimoLabel objects filtered by the error_message column
* @method array findByTrackingNumber(string $tracking_number) Return ChildColissimoLabel objects filtered by the tracking_number column
* @method array findByLabelType(string $label_type) Return ChildColissimoLabel objects filtered by the label_type column
* @method array findByWeight(string $weight) Return ChildColissimoLabel objects filtered by the weight column
* @method array findBySigned(boolean $signed) Return ChildColissimoLabel objects filtered by the signed column
* @method array findByWithCustomsInvoice(boolean $with_customs_invoice) Return ChildColissimoLabel objects filtered by the with_customs_invoice column
* @method array findByCreatedAt(string $created_at) Return ChildColissimoLabel objects filtered by the created_at column
* @method array findByUpdatedAt(string $updated_at) Return ChildColissimoLabel objects filtered by the updated_at column
*
*/
abstract class ColissimoLabelQuery extends ModelCriteria
{
/**
* Initializes internal state of \ColissimoLabel\Model\Base\ColissimoLabelQuery object.
*
* @param string $dbName The database name
* @param string $modelName The phpName of a model, e.g. 'Book'
* @param string $modelAlias The alias for the model in this query, e.g. 'b'
*/
public function __construct($dbName = 'thelia', $modelName = '\\ColissimoLabel\\Model\\ColissimoLabel', $modelAlias = null)
{
parent::__construct($dbName, $modelName, $modelAlias);
}
/**
* Returns a new ChildColissimoLabelQuery object.
*
* @param string $modelAlias The alias of a model in the query
* @param Criteria $criteria Optional Criteria to build the query from
*
* @return ChildColissimoLabelQuery
*/
public static function create($modelAlias = null, $criteria = null)
{
if ($criteria instanceof \ColissimoLabel\Model\ColissimoLabelQuery) {
return $criteria;
}
$query = new \ColissimoLabel\Model\ColissimoLabelQuery();
if (null !== $modelAlias) {
$query->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.
*
* <code>
* $obj = $c->findPk(12, $con);
* </code>
*
* @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
* <code>
* $objs = $c->findPks(array(12, 56, 832), $con);
* </code>
* @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:
* <code>
* $query->filterById(1234); // WHERE id = 1234
* $query->filterById(array(12, 34)); // WHERE id IN (12, 34)
* $query->filterById(array('min' => 12)); // WHERE id > 12
* </code>
*
* @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:
* <code>
* $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
* </code>
*
* @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:
* <code>
* $query->filterByOrderRef('fooValue'); // WHERE order_ref = 'fooValue'
* $query->filterByOrderRef('%fooValue%'); // WHERE order_ref LIKE '%fooValue%'
* </code>
*
* @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:
* <code>
* $query->filterByError(true); // WHERE error = true
* $query->filterByError('yes'); // WHERE error = true
* </code>
*
* @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:
* <code>
* $query->filterByErrorMessage('fooValue'); // WHERE error_message = 'fooValue'
* $query->filterByErrorMessage('%fooValue%'); // WHERE error_message LIKE '%fooValue%'
* </code>
*
* @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:
* <code>
* $query->filterByTrackingNumber('fooValue'); // WHERE tracking_number = 'fooValue'
* $query->filterByTrackingNumber('%fooValue%'); // WHERE tracking_number LIKE '%fooValue%'
* </code>
*
* @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:
* <code>
* $query->filterByLabelType('fooValue'); // WHERE label_type = 'fooValue'
* $query->filterByLabelType('%fooValue%'); // WHERE label_type LIKE '%fooValue%'
* </code>
*
* @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:
* <code>
* $query->filterByWeight(1234); // WHERE weight = 1234
* $query->filterByWeight(array(12, 34)); // WHERE weight IN (12, 34)
* $query->filterByWeight(array('min' => 12)); // WHERE weight > 12
* </code>
*
* @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:
* <code>
* $query->filterBySigned(true); // WHERE signed = true
* $query->filterBySigned('yes'); // WHERE signed = true
* </code>
*
* @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:
* <code>
* $query->filterByWithCustomsInvoice(true); // WHERE with_customs_invoice = true
* $query->filterByWithCustomsInvoice('yes'); // WHERE with_customs_invoice = true
* </code>
*
* @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:
* <code>
* $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'
* </code>
*
* @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:
* <code>
* $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'
* </code>
*
* @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

View File

@@ -0,0 +1,10 @@
<?php
namespace ColissimoLabel\Model;
use ColissimoLabel\Model\Base\ColissimoLabel as BaseColissimoLabel;
class ColissimoLabel extends BaseColissimoLabel
{
}

View File

@@ -0,0 +1,21 @@
<?php
namespace ColissimoLabel\Model;
use ColissimoLabel\Model\Base\ColissimoLabelQuery as BaseColissimoLabelQuery;
/**
* Skeleton subclass for performing query and update operations on the 'colissimo_label' table.
*
*
*
* You should add additional methods to this class to meet the
* application requirements. This class will only be generated as
* long as it does not already exist in the output directory.
*
*/
class ColissimoLabelQuery extends BaseColissimoLabelQuery
{
} // ColissimoLabelQuery

View File

@@ -0,0 +1,504 @@
<?php
namespace ColissimoLabel\Model\Map;
use ColissimoLabel\Model\ColissimoLabel;
use ColissimoLabel\Model\ColissimoLabelQuery;
use Propel\Runtime\Propel;
use Propel\Runtime\ActiveQuery\Criteria;
use Propel\Runtime\ActiveQuery\InstancePoolTrait;
use Propel\Runtime\Connection\ConnectionInterface;
use Propel\Runtime\DataFetcher\DataFetcherInterface;
use Propel\Runtime\Exception\PropelException;
use Propel\Runtime\Map\RelationMap;
use Propel\Runtime\Map\TableMap;
use Propel\Runtime\Map\TableMapTrait;
/**
* This class defines the structure of the 'colissimo_label' table.
*
*
*
* This map class is used by Propel to do runtime db structure discovery.
* For example, the createSelectSql() method checks the type of a given column used in an
* ORDER BY clause to know whether it needs to apply SQL to make the ORDER BY case-insensitive
* (i.e. if it's a text column type).
*
*/
class ColissimoLabelTableMap extends TableMap
{
use InstancePoolTrait;
use TableMapTrait;
/**
* The (dot-path) name of this class
*/
const CLASS_NAME = 'ColissimoLabel.Model.Map.ColissimoLabelTableMap';
/**
* The default database name for this class
*/
const DATABASE_NAME = 'thelia';
/**
* The table name for this class
*/
const TABLE_NAME = 'colissimo_label';
/**
* The related Propel class for this table
*/
const OM_CLASS = '\\ColissimoLabel\\Model\\ColissimoLabel';
/**
* A class that can be returned by this tableMap
*/
const CLASS_DEFAULT = 'ColissimoLabel.Model.ColissimoLabel';
/**
* The total number of columns
*/
const NUM_COLUMNS = 12;
/**
* The number of lazy-loaded columns
*/
const NUM_LAZY_LOAD_COLUMNS = 0;
/**
* The number of columns to hydrate (NUM_COLUMNS - NUM_LAZY_LOAD_COLUMNS)
*/
const NUM_HYDRATE_COLUMNS = 12;
/**
* the column name for the ID field
*/
const ID = 'colissimo_label.ID';
/**
* the column name for the ORDER_ID field
*/
const ORDER_ID = 'colissimo_label.ORDER_ID';
/**
* the column name for the ORDER_REF field
*/
const ORDER_REF = 'colissimo_label.ORDER_REF';
/**
* the column name for the ERROR field
*/
const ERROR = 'colissimo_label.ERROR';
/**
* the column name for the ERROR_MESSAGE field
*/
const ERROR_MESSAGE = 'colissimo_label.ERROR_MESSAGE';
/**
* the column name for the TRACKING_NUMBER field
*/
const TRACKING_NUMBER = 'colissimo_label.TRACKING_NUMBER';
/**
* the column name for the LABEL_TYPE field
*/
const LABEL_TYPE = 'colissimo_label.LABEL_TYPE';
/**
* the column name for the WEIGHT field
*/
const WEIGHT = 'colissimo_label.WEIGHT';
/**
* the column name for the SIGNED field
*/
const SIGNED = 'colissimo_label.SIGNED';
/**
* the column name for the WITH_CUSTOMS_INVOICE field
*/
const WITH_CUSTOMS_INVOICE = 'colissimo_label.WITH_CUSTOMS_INVOICE';
/**
* the column name for the CREATED_AT field
*/
const CREATED_AT = 'colissimo_label.CREATED_AT';
/**
* the column name for the UPDATED_AT field
*/
const UPDATED_AT = 'colissimo_label.UPDATED_AT';
/**
* The default string format for model objects of the related table
*/
const DEFAULT_STRING_FORMAT = 'YAML';
/**
* holds an array of fieldnames
*
* first dimension keys are the type constants
* e.g. self::$fieldNames[self::TYPE_PHPNAME][0] = 'Id'
*/
protected static $fieldNames = array (
self::TYPE_PHPNAME => 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();

View File

@@ -0,0 +1,84 @@
# ColissimoLabel
Allows you to generate labels for orders passed through SoColissimo and ColissimoWs.
## Installation
### Manually
* Copy the module into ```<thelia_root>/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.

View File

@@ -0,0 +1,132 @@
<?php
namespace ColissimoLabel\Request;
use ColissimoLabel\ColissimoLabel;
use ColissimoLabel\Request\Helper\Letter;
use ColissimoLabel\Request\Helper\OutputFormat;
/**
* @author Gilles Bourgeat >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()
]
],
]
]);
}
}

View File

@@ -0,0 +1,57 @@
<?php
namespace ColissimoLabel\Request;
/**
* @author Gilles Bourgeat >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()
];
}
}

View File

@@ -0,0 +1,119 @@
<?php
namespace ColissimoLabel\Request\Helper;
use ColissimoLabel\ColissimoLabel;
use Thelia\Model\ConfigQuery;
/**
* @author Gilles Bourgeat >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;
}
}

View File

@@ -0,0 +1,289 @@
<?php
namespace ColissimoLabel\Request\Helper;
/**
* @author Gilles Bourgeat >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;
}
}

View File

@@ -0,0 +1,44 @@
<?php
namespace ColissimoLabel\Request\Helper;
/**
* @author Gilles Bourgeat >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;
}
}

View File

@@ -0,0 +1,161 @@
<?php
namespace ColissimoLabel\Request\Helper;
use ColissimoLabel\ColissimoLabel;
use Thelia\Model\CountryQuery;
use Thelia\Model\Order;
class Article
{
protected $description = '';
protected $quantity = 0;
protected $weight = 0;
protected $value = 0;
protected $hsCode = '';
protected $currency = 'EUR';
protected $authorizedCurrencies = [
'USD',
'EUR',
'CHF',
'GBP',
'CNY',
'JPY',
'CAD',
'AUD',
'HKD',
];
public function __construct($description, $quantity, $weight, $value, $hsCode, $currency)
{
$this->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;
}
}

View File

@@ -0,0 +1,16 @@
<?php
namespace ColissimoLabel\Request\Helper;
/**
* @author Gilles Bourgeat >gilles.bourgeat@gmail.com>
*/
class BordereauRequestAPIConfiguration extends APIConfiguration
{
public function __construct()
{
parent::__construct();
$this->setMethod('generateBordereauByParcelsNumbers');
}
}

View File

@@ -0,0 +1,78 @@
<?php
namespace ColissimoLabel\Request\Helper;
class CustomsDeclarations
{
protected $includeCustomsDeclarations = false;
protected $articles = [];
protected $category = 3;
public function __construct($includeCustomsDeclarations, $category, $articles)
{
$this->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;
}
}

View File

@@ -0,0 +1,16 @@
<?php
namespace ColissimoLabel\Request\Helper;
/**
* @author Gilles Bourgeat >gilles.bourgeat@gmail.com>
*/
class LabelRequestAPIConfiguration extends APIConfiguration
{
public function __construct()
{
parent::__construct();
$this->setMethod('generateLabel');
}
}

View File

@@ -0,0 +1,78 @@
<?php
namespace ColissimoLabel\Request\Helper;
/**
* @author Gilles Bourgeat >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;
}
}

View File

@@ -0,0 +1,87 @@
<?php
namespace ColissimoLabel\Request\Helper;
use ColissimoLabel\Exception\InvalidArgumentException;
/**
* @author Gilles Bourgeat >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;
}
}

Some files were not shown because too many files have changed in this diff Show More