complete AreaController

This commit is contained in:
Manuel Raynaud
2013-10-11 16:48:15 +02:00
38 changed files with 2223 additions and 100 deletions

View File

@@ -197,6 +197,7 @@ class Order extends BaseAction implements EventSubscriberInterface
$taxRuleI18n = I18n::forceI18nRetrieving($this->getSession()->getLang()->getLocale(), 'TaxRule', $product->getTaxRuleId());
$taxDetail = $product->getTaxRule()->getTaxDetail(
$product,
$taxCountry,
$cartItem->getPrice(),
$cartItem->getPromoPrice(),

View File

@@ -0,0 +1,162 @@
<?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 Thelia\Action;
use Propel\Runtime\ActiveQuery\Criteria;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Thelia\Core\Event\Tax\TaxRuleEvent;
use Thelia\Core\Event\TheliaEvents;
use Thelia\Model\TaxRuleCountry;
use Thelia\Model\TaxRuleCountryQuery;
use Thelia\Model\TaxRule as TaxRuleModel;
use Thelia\Model\TaxRuleQuery;
class TaxRule extends BaseAction implements EventSubscriberInterface
{
/**
* @param TaxRuleEvent $event
*/
public function create(TaxRuleEvent $event)
{
$product = new TaxRuleModel();
$product
->setDispatcher($this->getDispatcher())
->setRef($event->getRef())
->setTitle($event->getTitle())
->setLocale($event->getLocale())
->setVisible($event->getVisible())
// Set the default tax rule to this product
->setTaxRule(TaxRuleQuery::create()->findOneByIsDefault(true))
//public function create($defaultCategoryId, $basePrice, $priceCurrencyId, $taxRuleId, $baseWeight) {
->create(
$event->getDefaultCategory(),
$event->getBasePrice(),
$event->getCurrencyId(),
$event->getTaxRuleId(),
$event->getBaseWeight()
);
;
$event->setTaxRule($product);
}
/**
* @param TaxRuleEvent $event
*/
public function update(TaxRuleEvent $event)
{
if (null !== $taxRule = TaxRuleQuery::create()->findPk($event->getId())) {
$taxRule
->setLocale($event->getLocale())
->setTitle($event->getTitle())
->setDescription($event->getDescription())
->save()
;
$event->setTaxRule($taxRule);
}
}
/**
* @param TaxRuleEvent $event
*/
public function updateTaxes(TaxRuleEvent $event)
{
if (null !== $taxRule = TaxRuleQuery::create()->findPk($event->getId())) {
$taxList = json_decode($event->getTaxList(), true);
/* clean the current tax rule for the countries */
TaxRuleCountryQuery::create()
->filterByTaxRule($taxRule)
->filterByCountryId($event->getCountryList(), Criteria::IN)
->delete();
/* for each country */
foreach($event->getCountryList() as $country) {
$position = 1;
/* on applique les nouvelles regles */
foreach($taxList as $tax) {
if(is_array($tax)) {
foreach($tax as $samePositionTax) {
$taxModel = new TaxRuleCountry();
$taxModel->setTaxRule($taxRule)
->setCountryId($country)
->setTaxId($samePositionTax)
->setPosition($position);
$taxModel->save();
}
} else {
$taxModel = new TaxRuleCountry();
$taxModel->setTaxRule($taxRule)
->setCountryId($country)
->setTaxId($tax)
->setPosition($position);
$taxModel->save();
}
$position++;
}
}
$event->setTaxRule($taxRule);
}
}
/**
* @param TaxRuleEvent $event
*/
public function delete(TaxRuleEvent $event)
{
if (null !== $taxRule = TaxRuleQuery::create()->findPk($event->getId())) {
$taxRule
->delete()
;
$event->setTaxRule($taxRule);
}
}
/**
* {@inheritDoc}
*/
public static function getSubscribedEvents()
{
return array(
TheliaEvents::TAX_RULE_CREATE => array("create", 128),
TheliaEvents::TAX_RULE_UPDATE => array("update", 128),
TheliaEvents::TAX_RULE_TAXES_UPDATE => array("updateTaxes", 128),
TheliaEvents::TAX_RULE_DELETE => array("delete", 128),
);
}
}

View File

@@ -106,6 +106,11 @@
<tag name="kernel.event_subscriber"/>
</service>
<service id="thelia.action.taxrule" class="Thelia\Action\TaxRule">
<argument type="service" id="service_container"/>
<tag name="kernel.event_subscriber"/>
</service>
<service id="thelia.action.content" class="Thelia\Action\Content">
<argument type="service" id="service_container"/>
<tag name="kernel.event_subscriber"/>

View File

@@ -46,7 +46,9 @@
<loop class="Thelia\Core\Template\Loop\Message" name="message"/>
<loop class="Thelia\Core\Template\Loop\Delivery" name="delivery"/>
<loop class="Thelia\Core\Template\Loop\Template" name="template"/> <!-- This is product templates ;-) -->
<loop class="Thelia\Core\Template\Loop\Tax" name="tax"/>
<loop class="Thelia\Core\Template\Loop\TaxRule" name="tax-rule"/>
<loop class="Thelia\Core\Template\Loop\TaxRuleCountry" name="tax-rule-country"/>
</loops>
<forms>
@@ -112,6 +114,9 @@
<form name="thelia.admin.featureav.creation" class="Thelia\Form\FeatureAvCreationForm"/>
<form name="thelia.admin.taxrule.modification" class="Thelia\Form\TaxRuleModificationForm"/>
<form name="thelia.admin.taxrule.taxlistupdate" class="Thelia\Form\TaxRuleTaxListUpdateForm"/>
<form name="thelia.admin.template.creation" class="Thelia\Form\TemplateCreationForm"/>
<form name="thelia.admin.template.modification" class="Thelia\Form\TemplateModificationForm"/>

View File

@@ -691,9 +691,9 @@
<default key="_controller">Thelia\Controller\Admin\AreaController::defaultAction</default>
</route>
<route id="admin.configuration.shipping-configuration.update.view" path="/admin/configuration/shipping_configuration/update/{shipping_configuration_id}" methods="get">
<route id="admin.configuration.shipping-configuration.update.view" path="/admin/configuration/shipping_configuration/update/{area_id}" methods="get">
<default key="_controller">Thelia\Controller\Admin\AreaController::updateAction</default>
<requirement key="shipping_configuration_id">\d+</requirement>
<requirement key="area_id">\d+</requirement>
</route>
<!-- end shipping routes management -->
@@ -793,6 +793,31 @@
<!-- end Modules rule management -->
<!-- taxe rules management -->
<route id="admin.configuration.taxes-rules.list" path="/admin/configuration/taxes_rules">
<default key="_controller">Thelia\Controller\Admin\TaxRuleController::defaultAction</default>
</route>
<route id="admin.configuration.taxes-rules.update" path="/admin/configuration/taxes_rules/update/{tax_rule_id}">
<default key="_controller">Thelia\Controller\Admin\TaxRuleController::updateAction</default>
<requirement key="tax_rule_id">\d+</requirement>
</route>
<route id="admin.configuration.taxes-rules.save" path="/admin/configuration/taxes_rules/save">
<default key="_controller">Thelia\Controller\Admin\TaxRuleController::processUpdateAction</default>
</route>
<route id="admin.configuration.taxes-rules.saveTaxes" path="/admin/configuration/taxes_rules/saveTaxes">
<default key="_controller">Thelia\Controller\Admin\TaxRuleController::processUpdateTaxesAction</default>
</route>
<route id="admin.configuration.taxes-rules.delete" path="/admin/configuration/taxes_rules/delete">
<default key="_controller">Thelia\Controller\Admin\TaxRuleController::deleteAction</default>
</route>
<!-- end tax rules management -->
<!-- The default route, to display a template -->

View File

@@ -22,10 +22,14 @@
/*************************************************************************************/
namespace Thelia\Controller\Admin;
use Thelia\Core\Event\Area\AreaCreateEvent;
use Thelia\Core\Event\Area\AreaDeleteEvent;
use Thelia\Core\Event\Area\AreaUpdateEvent;
use Thelia\Core\Event\TheliaEvents;
use Thelia\Form\Area\AreaCreateForm;
use Thelia\Form\Area\AreaModificationForm;
use Thelia\Model\AreaQuery;
/**
* Class AreaController
@@ -34,18 +38,6 @@ use Thelia\Form\Area\AreaCreateForm;
*/
class AreaController extends AbstractCrudController
{
/* public function indexAction()
{
if (null !== $response = $this->checkAuth("admin.shipping-configuration.view")) return $response;
return $this->render("shipping-configuration", array("display_shipping_configuration" => 20));
}
public function updateAction($shipping_configuration_id)
{
return $this->render("shipping-configuration-edit", array(
"shipping_configuration_id" => $shipping_configuration_id
));
}*/
public function __construct()
{
@@ -65,6 +57,11 @@ class AreaController extends AbstractCrudController
);
}
protected function getAreaId()
{
return $this->getRequest()->get('area_id', 0);
}
/**
* Return the creation form for this object
*/
@@ -78,7 +75,7 @@ class AreaController extends AbstractCrudController
*/
protected function getUpdateForm()
{
return new AreaCreateForm($this->getRequest());
return new AreaModificationForm($this->getRequest());
}
/**
@@ -88,7 +85,11 @@ class AreaController extends AbstractCrudController
*/
protected function hydrateObjectForm($object)
{
// TODO: Implement hydrateObjectForm() method.
$data = array(
'name' => $object->getName()
);
return new AreaModificationForm($this->getRequest(), 'form', $data);
}
/**
@@ -129,27 +130,27 @@ class AreaController extends AbstractCrudController
*/
protected function getDeleteEvent()
{
// TODO: Implement getDeleteEvent() method.
return new AreaDeleteEvent($this->getAreaId());
}
/**
* Return true if the event contains the object, e.g. the action has updated the object in the event.
*
* @param unknown $event
* @param \Thelia\Core\Event\Area\AreaEvent $event
*/
protected function eventContainsObject($event)
{
// TODO: Implement eventContainsObject() method.
return $event->hasArea();
}
/**
* Get the created object from an event.
*
* @param unknown $createEvent
* @param \Thelia\Core\Event\Area\AreaEvent $event
*/
protected function getObjectFromEvent($event)
{
// TODO: Implement getObjectFromEvent() method.
return $event->getArea();
}
/**
@@ -157,27 +158,27 @@ class AreaController extends AbstractCrudController
*/
protected function getExistingObject()
{
// TODO: Implement getExistingObject() method.
return AreaQuery::create()->findPk($this->getAreaId());
}
/**
* Returns the object label form the object event (name, title, etc.)
*
* @param unknown $object
* @param \Thelia\Model\Area $object
*/
protected function getObjectLabel($object)
{
// TODO: Implement getObjectLabel() method.
return $object->getName();
}
/**
* Returns the object ID from the object
*
* @param unknown $object
* @param \Thelia\Model\Area $object
*/
protected function getObjectId($object)
{
// TODO: Implement getObjectId() method.
return $object->getId();
}
/**
@@ -195,7 +196,9 @@ class AreaController extends AbstractCrudController
*/
protected function renderEditionTemplate()
{
// TODO: Implement renderEditionTemplate() method.
return $this->render('shipping-configuration-edit',array(
'area_id' => $this->getAreaId()
));
}
/**
@@ -203,7 +206,10 @@ class AreaController extends AbstractCrudController
*/
protected function redirectToEditionTemplate()
{
// TODO: Implement redirectToEditionTemplate() method.
$this->redirectToRoute('admin.configuration.shipping-configuration.update.view', array(), array(
"area_id" => $this->getAreaId()
)
);
}
/**
@@ -211,6 +217,6 @@ class AreaController extends AbstractCrudController
*/
protected function redirectToListTemplate()
{
return $this->render("shipping-configuration");
$this->redirectToRoute('admin.configuration.shipping-configuration.default');
}
}

View File

@@ -39,24 +39,6 @@ use Thelia\Model\CountryQuery;
class CountryController extends AbstractCrudController
{
/**
* @param string $objectName the lower case object name. Example. "message"
*
* @param string $defaultListOrder the default object list order, or null if list is not sortable. Example: manual
* @param string $orderRequestParameterName Name of the request parameter that set the list order (null if list is not sortable)
*
* @param string $viewPermissionIdentifier the 'view' permission identifier. Example: "admin.configuration.message.view"
* @param string $createPermissionIdentifier the 'create' permission identifier. Example: "admin.configuration.message.create"
* @param string $updatePermissionIdentifier the 'update' permission identifier. Example: "admin.configuration.message.update"
* @param string $deletePermissionIdentifier the 'delete' permission identifier. Example: "admin.configuration.message.delete"
*
* @param string $createEventIdentifier the dispatched create TheliaEvent identifier. Example: TheliaEvents::MESSAGE_CREATE
* @param string $updateEventIdentifier the dispatched update TheliaEvent identifier. Example: TheliaEvents::MESSAGE_UPDATE
* @param string $deleteEventIdentifier the dispatched delete TheliaEvent identifier. Example: TheliaEvents::MESSAGE_DELETE
*
* @param string $visibilityToggleEventIdentifier the dispatched visibility toggle TheliaEvent identifier, or null if the object has no visible options. Example: TheliaEvents::MESSAGE_TOGGLE_VISIBILITY
* @param string $changePositionEventIdentifier the dispatched position change TheliaEvent identifier, or null if the object has no position. Example: TheliaEvents::MESSAGE_UPDATE_POSITION
*/
public function __construct()
{
parent::__construct(

View File

@@ -0,0 +1,270 @@
<?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 Thelia\Controller\Admin;
use Thelia\Core\Event\Tax\TaxRuleEvent;
use Thelia\Core\Event\TheliaEvents;
use Thelia\Form\TaxRuleCreationForm;
use Thelia\Form\TaxRuleModificationForm;
use Thelia\Form\TaxRuleTaxListUpdateForm;
use Thelia\Model\CountryQuery;
use Thelia\Model\TaxRuleQuery;
class TaxRuleController extends AbstractCrudController
{
public function __construct()
{
parent::__construct(
'taxrule',
'manual',
'order',
'admin.configuration.taxrule.view',
'admin.configuration.taxrule.create',
'admin.configuration.taxrule.update',
'admin.configuration.taxrule.delete',
TheliaEvents::TAX_RULE_CREATE,
TheliaEvents::TAX_RULE_UPDATE,
TheliaEvents::TAX_RULE_DELETE
);
}
protected function getCreationForm()
{
return new TaxRuleCreationForm($this->getRequest());
}
protected function getUpdateForm()
{
return new TaxRuleModificationForm($this->getRequest());
}
protected function getCreationEvent($formData)
{
$event = new TaxRuleEvent();
/* @todo fill event */
return $event;
}
protected function getUpdateEvent($formData)
{
$event = new TaxRuleEvent();
$event->setLocale($formData['locale']);
$event->setId($formData['id']);
$event->setTitle($formData['title']);
$event->setDescription($formData['description']);
return $event;
}
protected function getUpdateTaxListEvent($formData)
{
$event = new TaxRuleEvent();
$event->setId($formData['id']);
$event->setTaxList($formData['tax_list']);
$event->setCountryList($formData['country_list']);
return $event;
}
protected function getDeleteEvent()
{
$event = new TaxRuleEvent();
$event->setId(
$this->getRequest()->get('tax_rule_id', 0)
);
return $event;
}
protected function eventContainsObject($event)
{
return $event->hasTaxRule();
}
protected function hydrateObjectForm($object)
{
$data = array(
'id' => $object->getId(),
'locale' => $object->getLocale(),
'title' => $object->getTitle(),
'description' => $object->getDescription(),
);
// Setup the object form
return new TaxRuleModificationForm($this->getRequest(), "form", $data);
}
protected function hydrateTaxUpdateForm($object)
{
$data = array(
'id' => $object->getId(),
);
// Setup the object form
return new TaxRuleTaxListUpdateForm($this->getRequest(), "form", $data);
}
protected function getObjectFromEvent($event)
{
return $event->hasTaxRule() ? $event->getTaxRule() : null;
}
protected function getExistingObject()
{
return TaxRuleQuery::create()
->joinWithI18n($this->getCurrentEditionLocale())
->findOneById($this->getRequest()->get('tax_rule_id'));
}
protected function getObjectLabel($object)
{
return $object->getTitle();
}
protected function getObjectId($object)
{
return $object->getId();
}
protected function getViewArguments($country = null)
{
return array(
'tab' => $this->getRequest()->get('tab', 'data'),
'country' => $country === null ? $this->getRequest()->get('country', CountryQuery::create()->findOneByByDefault(1)->getId()) : $country,
);
}
protected function getRouteArguments()
{
return array(
'tax_rule_id' => $this->getRequest()->get('tax_rule_id'),
);
}
protected function renderListTemplate($currentOrder)
{
// We always return to the feature edition form
return $this->render(
'taxes-rules',
array()
);
}
protected function renderEditionTemplate()
{
// We always return to the feature edition form
return $this->render('tax-rule-edit', array_merge($this->getViewArguments(), $this->getRouteArguments()));
}
protected function redirectToEditionTemplate($request = null, $country = null)
{
// We always return to the feature edition form
$this->redirectToRoute(
"admin.configuration.taxes-rules.update",
$this->getViewArguments($country),
$this->getRouteArguments()
);
}
protected function redirectToListTemplate()
{
$this->redirectToRoute(
"admin.configuration.taxes-rules.list"
);
}
public function updateAction()
{
if (null !== $response = $this->checkAuth($this->updatePermissionIdentifier)) return $response;
$object = $this->getExistingObject();
if ($object != null) {
// Hydrate the form abd pass it to the parser
$changeTaxesForm = $this->hydrateTaxUpdateForm($object);
// Pass it to the parser
$this->getParserContext()->addForm($changeTaxesForm);
}
return parent::updateAction();
}
public function processUpdateTaxesAction()
{
// Check current user authorization
if (null !== $response = $this->checkAuth('admin.configuration.taxrule.update')) return $response;
$error_msg = false;
// Create the form from the request
$changeForm = new TaxRuleTaxListUpdateForm($this->getRequest());
try {
// Check the form against constraints violations
$form = $this->validateForm($changeForm, "POST");
// Get the form field values
$data = $form->getData();
$changeEvent = $this->getUpdateTaxListEvent($data);
$this->dispatch(TheliaEvents::TAX_RULE_TAXES_UPDATE, $changeEvent);
if (! $this->eventContainsObject($changeEvent))
throw new \LogicException(
$this->getTranslator()->trans("No %obj was updated.", array('%obj', $this->objectName)));
// Log object modification
if (null !== $changedObject = $this->getObjectFromEvent($changeEvent)) {
$this->adminLogAppend(sprintf("%s %s (ID %s) modified", ucfirst($this->objectName), $this->getObjectLabel($changedObject), $this->getObjectId($changedObject)));
}
if ($response == null) {
$this->redirectToEditionTemplate($this->getRequest(), isset($data['country_list'][0]) ? $data['country_list'][0] : null);
} else {
return $response;
}
} catch (FormValidationException $ex) {
// Form cannot be validated
$error_msg = $this->createStandardFormValidationErrorMessage($ex);
} catch (\Exception $ex) {
// Any other error
$error_msg = $ex->getMessage();
}
$this->setupFormErrorContext($this->getTranslator()->trans("%obj modification", array('%obj' => 'taxrule')), $error_msg, $changeForm, $ex);
// At this point, the form has errors, and should be redisplayed.
return $this->renderEditionTemplate();
}
}

View File

@@ -31,10 +31,35 @@ namespace Thelia\Core\Event\Area;
*/
class AreaDeleteEvent extends AreaEvent
{
/**
* @var int area id
*/
protected $area_id;
public function __construct($area_id)
{
$this->area_id = $area_id;
}
/**
* @param null $area_id
*
* @return $this
*/
public function setAreaId($area_id)
{
$this->area_id = $area_id;
return $this;
}
/**
* @return null
*/
public function getAreaId()
{
return $this->area_id;
}
}

View File

@@ -0,0 +1,122 @@
<?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 Thelia\Core\Event\Tax;
use Thelia\Core\Event\ActionEvent;
use Thelia\Model\TaxRule;
class TaxRuleEvent extends ActionEvent
{
protected $taxRule = null;
protected $locale;
protected $id;
protected $title;
protected $description;
protected $countryList;
protected $taxList;
public function __construct(TaxRule $taxRule = null)
{
$this->taxRule = $taxRule;
}
public function hasTaxRule()
{
return ! is_null($this->taxRule);
}
public function getTaxRule()
{
return $this->taxRule;
}
public function setTaxRule(TaxRule $taxRule)
{
$this->taxRule = $taxRule;
return $this;
}
public function setDescription($description)
{
$this->description = $description;
}
public function getDescription()
{
return $this->description;
}
public function setId($id)
{
$this->id = $id;
}
public function getId()
{
return $this->id;
}
public function setTitle($title)
{
$this->title = $title;
}
public function getTitle()
{
return $this->title;
}
public function setLocale($locale)
{
$this->locale = $locale;
}
public function getLocale()
{
return $this->locale;
}
public function setCountryList($countryList)
{
$this->countryList = $countryList;
}
public function getCountryList()
{
return $this->countryList;
}
public function setTaxList($taxList)
{
$this->taxList = $taxList;
}
public function getTaxList()
{
return $this->taxList;
}
}

View File

@@ -525,6 +525,14 @@ final class TheliaEvents
const CHANGE_DEFAULT_CURRENCY = 'action.changeDefaultCurrency';
// -- Tax Rules management ---------------------------------------------
const TAX_RULE_CREATE = "action.createTaxRule";
const TAX_RULE_UPDATE = "action.updateTaxRule";
const TAX_RULE_DELETE = "action.deleteTaxRule";
const TAX_RULE_SET_DEFAULT = "action.setDefaultTaxRule";
const TAX_RULE_TAXES_UPDATE = "action.updateTaxesTaxRule";
// -- Product templates management -----------------------------------------
const TEMPLATE_CREATE = "action.createTemplate";

View File

@@ -113,6 +113,7 @@ class Country extends BaseI18nLoop
->set("CHAPO", $country->getVirtualColumn('i18n_CHAPO'))
->set("DESCRIPTION", $country->getVirtualColumn('i18n_DESCRIPTION'))
->set("POSTSCRIPTUM", $country->getVirtualColumn('i18n_POSTSCRIPTUM'))
->set("IS_DEFAULT", $country->getByDefault() === 1 ? "1" : "0")
->set("ISOCODE", $country->getIsocode())
->set("ISOALPHA2", $country->getIsoalpha2())
->set("ISOALPHA3", $country->getIsoalpha3())

View File

@@ -0,0 +1,167 @@
<?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 Thelia\Core\Template\Loop;
use Propel\Runtime\ActiveQuery\Criteria;
use Thelia\Core\Template\Element\BaseI18nLoop;
use Thelia\Core\Template\Element\LoopResult;
use Thelia\Core\Template\Element\LoopResultRow;
use Thelia\Core\Template\Loop\Argument\ArgumentCollection;
use Thelia\Core\Template\Loop\Argument\Argument;
use Thelia\Model\Base\TaxRuleCountryQuery;
use Thelia\Type\TypeCollection;
use Thelia\Type;
use Thelia\Model\TaxQuery;
/**
*
* Tax loop
*
*
* Class Tax
* @package Thelia\Core\Template\Loop
* @author Etienne Roudeix <eroudeix@openstudio.fr>
*/
class Tax extends BaseI18nLoop
{
public $timestampable = true;
/**
* @return ArgumentCollection
*/
protected function getArgDefinitions()
{
return new ArgumentCollection(
Argument::createIntListTypeArgument('id'),
Argument::createIntListTypeArgument('exclude'),
Argument::createIntListTypeArgument('tax_rule'),
Argument::createIntListTypeArgument('exclude_tax_rule'),
Argument::createIntTypeArgument('country'),
new Argument(
'order',
new TypeCollection(
new Type\EnumListType(array('id', 'id_reverse', 'alpha', 'alpha_reverse'))
),
'alpha'
)
);
}
/**
* @param $pagination
*
* @return \Thelia\Core\Template\Element\LoopResult
*/
public function exec(&$pagination)
{
$search = TaxQuery::create();
/* manage translations */
$locale = $this->configureI18nProcessing($search, array('TITLE', 'DESCRIPTION'));
$id = $this->getId();
if (null !== $id) {
$search->filterById($id, Criteria::IN);
}
$exclude = $this->getExclude();
if (null !== $exclude) {
$search->filterById($exclude, Criteria::NOT_IN);
}
$country = $this->getCountry();
$taxRule = $this->getTax_rule();
if(null !== $taxRule && null !== $country) {
$search->filterByTaxRuleCountry(
TaxRuleCountryQuery::create()
->filterByCountryId($country, Criteria::EQUAL)
->filterByTaxRuleId($taxRule, Criteria::IN)
->find(),
Criteria::IN
);
}
$excludeTaxRule = $this->getExclude_tax_rule();
if(null !== $excludeTaxRule && null !== $country) {
$excludedTaxes = TaxRuleCountryQuery::create()
->filterByCountryId($country, Criteria::EQUAL)
->filterByTaxRuleId($excludeTaxRule, Criteria::IN)
->find();
/*DOES NOT WORK
* $search->filterByTaxRuleCountry(
$excludedTaxes,
Criteria::NOT_IN
);*/
foreach($excludedTaxes as $excludedTax) {
$search->filterByTaxRuleCountry($excludedTax, Criteria::NOT_EQUAL);
}
}
$orders = $this->getOrder();
foreach ($orders as $order) {
switch ($order) {
case "id":
$search->orderById(Criteria::ASC);
break;
case "id_reverse":
$search->orderById(Criteria::DESC);
break;
case "alpha":
$search->addAscendingOrderByColumn('i18n_TITLE');
break;
case "alpha_reverse":
$search->addDescendingOrderByColumn('i18n_TITLE');
break;
}
}
/* perform search */
$taxes = $this->search($search, $pagination);
$loopResult = new LoopResult($taxes);
foreach ($taxes as $tax) {
$loopResultRow = new LoopResultRow($loopResult, $tax, $this->versionable, $this->timestampable, $this->countable);
$loopResultRow
->set("ID" , $tax->getId())
->set("IS_TRANSLATED" , $tax->getVirtualColumn('IS_TRANSLATED'))
->set("LOCALE" , $locale)
->set("TITLE" , $tax->getVirtualColumn('i18n_TITLE'))
->set("DESCRIPTION" , $tax->getVirtualColumn('i18n_DESCRIPTION'))
;
$loopResult->addRow($loopResultRow);
}
return $loopResult;
}
}

View File

@@ -0,0 +1,162 @@
<?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 Thelia\Core\Template\Loop;
use Propel\Runtime\ActiveQuery\Criteria;
use Propel\Runtime\ActiveQuery\Join;
use Thelia\Core\Template\Element\BaseI18nLoop;
use Thelia\Core\Template\Element\LoopResult;
use Thelia\Core\Template\Element\LoopResultRow;
use Thelia\Core\Template\Loop\Argument\ArgumentCollection;
use Thelia\Core\Template\Loop\Argument\Argument;
use Thelia\Model\Map\CountryTableMap;
use Thelia\Model\Map\TaxRuleCountryTableMap;
use Thelia\Model\Map\TaxTableMap;
use Thelia\Type\TypeCollection;
use Thelia\Type;
use Thelia\Model\TaxRuleCountryQuery;
/**
*
* TaxRuleCountry loop
*
*
* Class TaxRuleCountry
* @package Thelia\Core\Template\Loop
* @author Etienne Roudeix <eroudeix@openstudio.fr>
*/
class TaxRuleCountry extends BaseI18nLoop
{
public $timestampable = true;
/**
* @return ArgumentCollection
*/
protected function getArgDefinitions()
{
return new ArgumentCollection(
Argument::createIntTypeArgument('country'),
Argument::createIntListTypeArgument('taxes'),
Argument::createIntTypeArgument('tax_rule', null, true)
);
}
/**
* @param $pagination
*
* @return \Thelia\Core\Template\Element\LoopResult
*/
public function exec(&$pagination)
{
$search = TaxRuleCountryQuery::create();
$country = $this->getCountry();
$taxes = $this->getTaxes();
if((null === $country && null === $taxes)) {
throw new \InvalidArgumentException('You must provide either `country` or `taxes` parameter in tax-rule-country loop');
}
if((null === $country && null !== $taxes)) {
throw new \InvalidArgumentException('You must provide `country` parameter with `taxes` parameter in tax-rule-country loop');
}
if(null !== $taxes) {
$search->groupByCountryId();
$originalCountryJoin = new Join();
$originalCountryJoin->addExplicitCondition(TaxRuleCountryTableMap::TABLE_NAME, 'TAX_RULE_ID', null, TaxRuleCountryTableMap::TABLE_NAME, 'TAX_RULE_ID', 'origin');
$originalCountryJoin->addExplicitCondition(TaxRuleCountryTableMap::TABLE_NAME, 'TAX_ID', null, TaxRuleCountryTableMap::TABLE_NAME, 'TAX_ID', 'origin');
$originalCountryJoin->addExplicitCondition(TaxRuleCountryTableMap::TABLE_NAME, 'POSITION', null, TaxRuleCountryTableMap::TABLE_NAME, 'POSITION', 'origin');
$originalCountryJoin->addExplicitCondition(TaxRuleCountryTableMap::TABLE_NAME, 'COUNTRY_ID', null, TaxRuleCountryTableMap::TABLE_NAME, 'COUNTRY_ID', 'origin', Criteria::NOT_EQUAL);
$originalCountryJoin->setJoinType(Criteria::LEFT_JOIN);
$search->addJoinObject($originalCountryJoin, 's_to_o');
$search->where('`origin`.`COUNTRY_ID`' . Criteria::EQUAL . '?', $country, \PDO::PARAM_INT);
$search->having('COUNT(*)=?', count($taxes), \PDO::PARAM_INT);
/* manage tax translation */
$this->configureI18nProcessing(
$search,
array('TITLE', 'CHAPO', 'DESCRIPTION', 'POSTSCRIPTUM'),
CountryTableMap::TABLE_NAME,
'COUNTRY_ID'
);
} elseif(null !== $country) {
$search->filterByCountryId($country);
/* manage tax translation */
$this->configureI18nProcessing(
$search,
array('TITLE', 'DESCRIPTION'),
TaxTableMap::TABLE_NAME,
'TAX_ID'
);
}
$taxRule = $this->getTax_rule();
$search->filterByTaxRuleId($taxRule);
$search->orderByPosition(Criteria::ASC);
/* perform search */
$taxRuleCountries = $this->search($search, $pagination);
$loopResult = new LoopResult($taxRuleCountries);
foreach ($taxRuleCountries as $taxRuleCountry) {
$loopResultRow = new LoopResultRow($loopResult, $taxRuleCountry, $this->versionable, $this->timestampable, $this->countable);
if(null !== $taxes) {
$loopResultRow
->set("TAX_RULE" , $taxRuleCountry->getTaxRuleId())
->set("COUNTRY" , $taxRuleCountry->getCountryId())
->set("COUNTRY_TITLE" , $taxRuleCountry->getVirtualColumn(CountryTableMap::TABLE_NAME . '_i18n_TITLE'))
->set("COUNTRY_CHAPO" , $taxRuleCountry->getVirtualColumn(CountryTableMap::TABLE_NAME . '_i18n_CHAPO'))
->set("COUNTRY_DESCRIPTION" , $taxRuleCountry->getVirtualColumn(CountryTableMap::TABLE_NAME . '_i18n_DESCRIPTION'))
->set("COUNTRY_POSTSCRIPTUM" , $taxRuleCountry->getVirtualColumn(CountryTableMap::TABLE_NAME . '_i18n_POSTSCRIPTUM'))
;
}elseif(null !== $country) {
$loopResultRow
->set("TAX_RULE" , $taxRuleCountry->getTaxRuleId())
->set("COUNTRY" , $taxRuleCountry->getCountryId())
->set("TAX" , $taxRuleCountry->getTaxId())
->set("POSITION" , $taxRuleCountry->getPosition())
->set("TAX_TITLE" , $taxRuleCountry->getVirtualColumn(TaxTableMap::TABLE_NAME . '_i18n_TITLE'))
->set("TAX_DESCRIPTION" , $taxRuleCountry->getVirtualColumn(TaxTableMap::TABLE_NAME . '_i18n_DESCRIPTION'))
;
}
$loopResult->addRow($loopResultRow);
}
return $loopResult;
}
}

View File

@@ -163,16 +163,16 @@ class DataAccessFunctions extends AbstractSmartyPlugin
public function countryDataAccess($params, $smarty)
{
if (array_key_exists('defaultCountry', self::$dataAccessCache)) {
$defaultCountry = self::$dataAccessCache['defaultCountry'];
} else {
$defaultCountry = CountryQuery::create()->findOneByByDefault(1);
self::$dataAccessCache['defaultCountry'] = $defaultCountry;
}
switch ($params["attr"]) {
switch ($params["ask"]) {
case "default":
return $defaultCountry->getId();
/*if (array_key_exists('defaultCountry', self::$dataAccessCache)) {
$defaultCountry = self::$dataAccessCache['defaultCountry'];
} else {
$defaultCountry = CountryQuery::create()->findOneByByDefault(1);
self::$dataAccessCache['defaultCountry'] = $defaultCountry;
}*/
$defaultCountry = CountryQuery::create()->filterByByDefault(1)->limit(1);
return $this->dataAccessWithI18n("defaultCountry", $params, $defaultCountry);
}
}

View File

@@ -182,7 +182,8 @@ $this->assignFieldValues($template, $formFieldView->vars["full_name"], $fieldVar
public function renderHiddenFormField($params, \Smarty_Internal_Template $template)
{
$field = '<input type="hidden" name="%s" value="%s">';
$attrFormat = '%s="%s"';
$field = '<input type="hidden" name="%s" value="%s" %s>';
$instance = $this->getInstanceFromParams($params);
@@ -192,7 +193,13 @@ $this->assignFieldValues($template, $formFieldView->vars["full_name"], $fieldVar
foreach ($formView->getIterator() as $row) {
if ($this->isHidden($row) && $row->isRendered() === false) {
$return .= sprintf($field, $row->vars["full_name"], $row->vars["value"]);
$attributeList = array();
if(isset($row->vars["attr"])) {
foreach($row->vars["attr"] as $attrKey => $attrValue) {
$attributeList[] = sprintf($attrFormat, $attrKey, $attrValue);
}
}
$return .= sprintf($field, $row->vars["full_name"], $row->vars["value"], implode(' ', $attributeList));
}
}

View File

@@ -40,9 +40,12 @@ class TaxEngineException extends \RuntimeException
const UNDEFINED_REQUIREMENTS = 504;
const UNDEFINED_REQUIREMENT_VALUE = 505;
const UNDEFINED_TAX_RULE = 506;
const NO_TAX_IN_TAX_RULES_COLLECTION = 507;
const BAD_AMOUNT_FORMAT = 601;
const FEATURE_BAD_EXPECTED_VALUE = 701;
public function __construct($message, $code = null, $previous = null)
{
if ($code === null) {

View File

@@ -0,0 +1,45 @@
<?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 Thelia\Form;
use Symfony\Component\Validator\Constraints;
use Symfony\Component\Validator\Constraints\NotBlank;
use Thelia\Core\Translation\Translator;
use Thelia\Model\CountryQuery;
class TaxRuleCreationForm extends BaseForm
{
protected function buildForm($change_mode = false)
{
$this->formBuilder
->add("locale", "text", array(
"constraints" => array(new NotBlank())
))
;
}
public function getName()
{
return "thelia_tax_rule_creation";
}
}

View File

@@ -0,0 +1,71 @@
<?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 Thelia\Form;
use Symfony\Component\Validator\Constraints;
use Symfony\Component\Validator\ExecutionContextInterface;
use Thelia\Model\TaxRuleQuery;
class TaxRuleModificationForm extends TaxRuleCreationForm
{
use StandardDescriptionFieldsTrait;
protected function buildForm()
{
parent::buildForm(true);
$this->formBuilder
->add("id", "hidden", array(
"required" => true,
"constraints" => array(
new Constraints\NotBlank(),
new Constraints\Callback(
array(
"methods" => array(
array($this, "verifyTaxRuleId"),
),
)
),
)
))
;
// Add standard description fields
$this->addStandardDescFields(array('postscriptum', 'chapo', 'locale'));
}
public function getName()
{
return "thelia_tax_rule_modification";
}
public function verifyTaxRuleId($value, ExecutionContextInterface $context)
{
$taxRule = TaxRuleQuery::create()
->findPk($value);
if (null === $taxRule) {
$context->addViolation("Tax rule ID not found");
}
}
}

View File

@@ -0,0 +1,127 @@
<?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 Thelia\Form;
use Symfony\Component\Validator\Constraints;
use Symfony\Component\Validator\ExecutionContextInterface;
use Thelia\Model\CountryQuery;
use Thelia\Model\TaxQuery;
use Thelia\Model\TaxRuleQuery;
use Thelia\Type\JsonType;
class TaxRuleTaxListUpdateForm extends BaseForm
{
protected function buildForm()
{
$countryList = array();
foreach(CountryQuery::create()->find() as $country) {
$countryList[$country->getId()] = $country->getId();
}
$this->formBuilder
->add("id", "hidden", array(
"required" => true,
"constraints" => array(
new Constraints\NotBlank(),
new Constraints\Callback(
array(
"methods" => array(
array($this, "verifyTaxRuleId"),
),
)
),
)
))
->add("tax_list", "hidden", array(
"required" => true,
"attr" => array(
"id" => 'tax_list',
),
"constraints" => array(
new Constraints\Callback(
array(
"methods" => array(
array($this, "verifyTaxList"),
),
)
),
)
))
->add("country_list", "choice", array(
"choices" => $countryList,
"required" => true,
"multiple" => true,
"constraints" => array(
new Constraints\NotBlank(),
)
))
;
}
public function getName()
{
return "thelia_tax_rule_taxlistupdate";
}
public function verifyTaxRuleId($value, ExecutionContextInterface $context)
{
$taxRule = TaxRuleQuery::create()
->findPk($value);
if (null === $taxRule) {
$context->addViolation("Tax rule ID not found");
}
}
public function verifyTaxList($value, ExecutionContextInterface $context)
{
$jsonType = new JsonType();
if(!$jsonType->isValid($value)) {
$context->addViolation("Tax list is not valid JSON");
}
$taxList = json_decode($value, true);
/* check we have 2 level max */
foreach($taxList as $taxLevel1) {
if(is_array($taxLevel1)) {
foreach($taxLevel1 as $taxLevel2) {
if(is_array($taxLevel2)) {
$context->addViolation("Bad tax list JSON");
} else {
$taxModel = TaxQuery::create()->findPk($taxLevel2);
if (null === $taxModel) {
$context->addViolation("Tax ID not found in tax list JSON");
}
}
}
} else {
$taxModel = TaxQuery::create()->findPk($taxLevel1);
if (null === $taxModel) {
$context->addViolation("Tax ID not found in tax list JSON");
}
}
}
}
}

View File

@@ -16,14 +16,14 @@ class TaxRule extends BaseTaxRule
*
* @return OrderProductTaxCollection
*/
public function getTaxDetail(Country $country, $untaxedAmount, $untaxedPromoAmount, $askedLocale = null)
public function getTaxDetail(Product $product, Country $country, $untaxedAmount, $untaxedPromoAmount, $askedLocale = null)
{
$taxCalculator = new Calculator();
$taxCollection = new OrderProductTaxCollection();
$taxCalculator->loadTaxRule($this, $country)->getTaxedPrice($untaxedAmount, $taxCollection, $askedLocale);
$taxCalculator->loadTaxRule($this, $country, $product)->getTaxedPrice($untaxedAmount, $taxCollection, $askedLocale);
$promoTaxCollection = new OrderProductTaxCollection();
$taxCalculator->loadTaxRule($this, $country)->getTaxedPrice($untaxedPromoAmount, $promoTaxCollection, $askedLocale);
$taxCalculator->loadTaxRule($this, $country, $product)->getTaxedPrice($untaxedPromoAmount, $promoTaxCollection, $askedLocale);
foreach($taxCollection as $index => $tax) {
$tax->setPromoAmount($promoTaxCollection->getKey($index)->getAmount());

View File

@@ -76,7 +76,7 @@ class Calculator
return $this;
}
public function loadTaxRule(TaxRule $taxRule, Country $country)
public function loadTaxRule(TaxRule $taxRule, Country $country, Product $product)
{
$this->product = null;
$this->country = null;
@@ -88,8 +88,12 @@ class Calculator
if($country->getId() === null) {
throw new TaxEngineException('Country id is empty in Calculator::loadTaxRule', TaxEngineException::UNDEFINED_COUNTRY);
}
if($product->getId() === null) {
throw new TaxEngineException('Product id is empty in Calculator::load', TaxEngineException::UNDEFINED_PRODUCT);
}
$this->country = $country;
$this->product = $product;
$this->taxRulesCollection = $this->taxRuleQuery->getTaxCalculatorCollection($taxRule, $country);
@@ -117,7 +121,11 @@ class Calculator
public function getTaxedPrice($untaxedPrice, &$taxCollection = null, $askedLocale = null)
{
if(null === $this->taxRulesCollection) {
throw new TaxEngineException('Tax rules collection is empty in Calculator::getTaxAmount', TaxEngineException::UNDEFINED_TAX_RULES_COLLECTION);
throw new TaxEngineException('Tax rules collection is empty in Calculator::getTaxedPrice', TaxEngineException::UNDEFINED_TAX_RULES_COLLECTION);
}
if(null === $this->product) {
throw new TaxEngineException('Product is empty in Calculator::getTaxedPrice', TaxEngineException::UNDEFINED_PRODUCT);
}
if(false === filter_var($untaxedPrice, FILTER_VALIDATE_FLOAT)) {
@@ -143,7 +151,7 @@ class Calculator
$currentPosition = $position;
}
$taxAmount = round($taxType->calculate($taxedPrice), 2);
$taxAmount = round($taxType->calculate($this->product, $taxedPrice), 2);
$currentTax += $taxAmount;
if(null !== $taxCollection) {
@@ -167,12 +175,20 @@ class Calculator
throw new TaxEngineException('Tax rules collection is empty in Calculator::getTaxAmount', TaxEngineException::UNDEFINED_TAX_RULES_COLLECTION);
}
if(null === $this->product) {
throw new TaxEngineException('Product is empty in Calculator::getTaxedPrice', TaxEngineException::UNDEFINED_PRODUCT);
}
if(false === filter_var($taxedPrice, FILTER_VALIDATE_FLOAT)) {
throw new TaxEngineException('BAD AMOUNT FORMAT', TaxEngineException::BAD_AMOUNT_FORMAT);
}
$taxRule = $this->taxRulesCollection->getLast();
if(null === $taxRule) {
throw new TaxEngineException('Tax rules collection got no tax ', TaxEngineException::NO_TAX_IN_TAX_RULES_COLLECTION);
}
$untaxedPrice = $taxedPrice;
$currentPosition = (int)$taxRule->getTaxRuleCountryPosition();
$currentFixTax = 0;
@@ -192,7 +208,7 @@ class Calculator
$currentPosition = $position;
}
$currentFixTax += $taxType->fixAmountRetriever();
$currentFixTax += $taxType->fixAmountRetriever($this->product);
$currentTaxFactor += $taxType->pricePercentRetriever();

View File

@@ -23,6 +23,7 @@
namespace Thelia\TaxEngine\TaxType;
use Thelia\Exception\TaxEngineException;
use Thelia\Model\Product;
use Thelia\Type\TypeInterface;
/**
@@ -34,14 +35,17 @@ abstract class BaseTaxType
{
protected $requirements = null;
public abstract function calculate($untaxedPrice);
public abstract function pricePercentRetriever();
public abstract function fixAmountRetriever();
public abstract function fixAmountRetriever(Product $product);
public abstract function getRequirementsList();
public function calculate(Product $product, $untaxedPrice)
{
return $untaxedPrice * $this->pricePercentRetriever() + $this->fixAmountRetriever($product);
}
public function loadRequirements($requirementsValues)
{
$this->requirements = $this->getRequirementsList();

View File

@@ -0,0 +1,68 @@
<?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 Thelia\TaxEngine\TaxType;
use Thelia\Exception\TaxEngineException;
use Thelia\Model\FeatureProductQuery;
use Thelia\Model\Product;
use Thelia\Type\FloatType;
use Thelia\Type\ModelValidIdType;
/**
*
* @author Etienne Roudeix <eroudeix@openstudio.fr>
*
*/
class FeatureFixAmountTaxType extends BaseTaxType
{
public function pricePercentRetriever()
{
return 0;
}
public function fixAmountRetriever(Product $product)
{
$featureId = $this->getRequirement("feature");
$query = FeatureProductQuery::create()
->filterByProduct($product)
->filterByFeatureId($featureId)
->findOne();
$taxAmount = $query->getFreeTextValue();
$testInt = new FloatType();
if(!$testInt->isValid($taxAmount)) {
throw new TaxEngineException('Feature value does not match FLOAT format', TaxEngineException::FEATURE_BAD_EXPECTED_VALUE);
}
return $taxAmount;
}
public function getRequirementsList()
{
return array(
'feature' => new ModelValidIdType('Feature'),
);
}
}

View File

@@ -23,7 +23,7 @@
namespace Thelia\TaxEngine\TaxType;
use Thelia\Type\FloatToFloatArrayType;
use Thelia\Type\ModelType;
use Thelia\Type\ModelValidIdType;
/**
*
@@ -32,17 +32,12 @@ use Thelia\Type\ModelType;
*/
class featureSlicePercentTaxType extends BaseTaxType
{
public function calculate($untaxedPrice)
{
}
public function pricePercentRetriever()
{
}
public function fixAmountRetriever()
public function fixAmountRetriever(\Thelia\Model\Product $product)
{
}
@@ -50,7 +45,7 @@ class featureSlicePercentTaxType extends BaseTaxType
public function getRequirementsList()
{
return array(
'featureId' => new ModelType('Currency'),
'featureId' => new ModelValidIdType('Currency'),
'slices' => new FloatToFloatArrayType(),
);
}

View File

@@ -31,17 +31,12 @@ use Thelia\Type\FloatType;
*/
class FixAmountTaxType extends BaseTaxType
{
public function calculate($untaxedPrice)
{
return $this->getRequirement("amount");
}
public function pricePercentRetriever()
{
return 0;
}
public function fixAmountRetriever()
public function fixAmountRetriever(\Thelia\Model\Product $product)
{
return $this->getRequirement("amount");
}

View File

@@ -31,17 +31,12 @@ use Thelia\Type\FloatType;
*/
class PricePercentTaxType extends BaseTaxType
{
public function calculate($untaxedPrice)
{
return $untaxedPrice * $this->getRequirement("percent") * 0.01;
}
public function pricePercentRetriever()
{
return ($this->getRequirement("percent") * 0.01);
}
public function fixAmountRetriever()
public function fixAmountRetriever(\Thelia\Model\Product $product)
{
return 0;
}

View File

@@ -347,7 +347,7 @@ class OrderTest extends \PHPUnit_Framework_TestCase
/* check tax */
$orderProductTaxList = $orderProduct->getOrderProductTaxes();
foreach ($cartItem->getProduct()->getTaxRule()->getTaxDetail($validDeliveryAddress->getCountry(), $cartItem->getPrice(), $cartItem->getPromoPrice()) as $index => $tax) {
foreach ($cartItem->getProduct()->getTaxRule()->getTaxDetail($cartItem->getProduct(), $validDeliveryAddress->getCountry(), $cartItem->getPrice(), $cartItem->getPromoPrice()) as $index => $tax) {
$orderProductTax = $orderProductTaxList[$index];
$this->assertEquals($tax->getAmount(), $orderProductTax->getAmount());
$this->assertEquals($tax->getPromoAmount(), $orderProductTax->getPromoAmount());

View File

@@ -126,14 +126,64 @@ class CalculatorTest extends \PHPUnit_Framework_TestCase
{
$taxRulesCollection = new ObjectCollection();
$aProduct = ProductQuery::create()->findOne();
if(null === $aProduct) {
return;
}
$calculator = new Calculator();
$rewritingUrlQuery = $this->getProperty('taxRulesCollection');
$rewritingUrlQuery->setValue($calculator, $taxRulesCollection);
$product = $this->getProperty('product');
$product->setValue($calculator, $aProduct);
$calculator->getTaxedPrice('foo');
}
/**
* @expectedException \Thelia\Exception\TaxEngineException
* @expectedExceptionCode 501
*/
public function testGetUntaxedPriceAndGetTaxAmountFromTaxedPriceWithNoProductLoaded()
{
$taxRulesCollection = new ObjectCollection();
$taxRulesCollection->setModel('\Thelia\Model\Tax');
$calculator = new Calculator();
$rewritingUrlQuery = $this->getProperty('taxRulesCollection');
$rewritingUrlQuery->setValue($calculator, $taxRulesCollection);
$calculator->getTaxAmountFromTaxedPrice(600.95);
}
/**
* @expectedException \Thelia\Exception\TaxEngineException
* @expectedExceptionCode 507
*/
public function testGetUntaxedPriceAndGetTaxAmountFromTaxedPriceWithEmptyTaxRuleCollection()
{
$taxRulesCollection = new ObjectCollection();
$taxRulesCollection->setModel('\Thelia\Model\Tax');
$aProduct = ProductQuery::create()->findOne();
if(null === $aProduct) {
return;
}
$calculator = new Calculator();
$rewritingUrlQuery = $this->getProperty('taxRulesCollection');
$rewritingUrlQuery->setValue($calculator, $taxRulesCollection);
$product = $this->getProperty('product');
$product->setValue($calculator, $aProduct);
$calculator->getTaxAmountFromTaxedPrice(600.95);
}
public function testGetTaxedPriceAndGetTaxAmountFromUntaxedPrice()
{
$taxRulesCollection = new ObjectCollection();
@@ -163,11 +213,19 @@ class CalculatorTest extends \PHPUnit_Framework_TestCase
->setVirtualColumn('taxRuleCountryPosition', 3);
$taxRulesCollection->append($tax);
$aProduct = ProductQuery::create()->findOne();
if(null === $aProduct) {
return;
}
$calculator = new Calculator();
$rewritingUrlQuery = $this->getProperty('taxRulesCollection');
$rewritingUrlQuery->setValue($calculator, $taxRulesCollection);
$product = $this->getProperty('product');
$product->setValue($calculator, $aProduct);
$taxAmount = $calculator->getTaxAmountFromUntaxedPrice(500);
$taxedPrice = $calculator->getTaxedPrice(500);
@@ -211,11 +269,19 @@ class CalculatorTest extends \PHPUnit_Framework_TestCase
->setVirtualColumn('taxRuleCountryPosition', 3);
$taxRulesCollection->append($tax);
$aProduct = ProductQuery::create()->findOne();
if(null === $aProduct) {
return;
}
$calculator = new Calculator();
$rewritingUrlQuery = $this->getProperty('taxRulesCollection');
$rewritingUrlQuery->setValue($calculator, $taxRulesCollection);
$product = $this->getProperty('product');
$product->setValue($calculator, $aProduct);
$taxAmount = $calculator->getTaxAmountFromTaxedPrice(600.95);
$untaxedPrice = $calculator->getUntaxedPrice(600.95);

View File

@@ -0,0 +1,70 @@
<?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 Thelia\Type;
use Propel\Runtime\ActiveQuery\ModelCriteria;
use Thelia\Exception\TypeException;
/**
*
* @author Etienne Roudeix <eroudeix@openstudio.fr>
*
*/
class ModelValidIdType implements TypeInterface
{
protected $expectedModelActiveRecordQuery = null;
/**
* @param $expectedModelActiveRecord
* @throws TypeException
*/
public function __construct($expectedModelActiveRecord)
{
$class = '\\Thelia\\Model\\' . $expectedModelActiveRecord . 'Query';
if (!(class_exists($class) || !new $class instanceof ModelCriteria)) {
throw new TypeException('MODEL NOT FOUND', TypeException::MODEL_NOT_FOUND);
}
$this->expectedModelActiveRecordQuery = $class;
}
public function getType()
{
return 'Model valid Id type';
}
public function isValid($value)
{
$queryClass = $this->expectedModelActiveRecordQuery;
return null !== $queryClass::create()->findPk($value);
}
public function getFormattedValue($value)
{
$queryClass = $this->expectedModelActiveRecordQuery;
return $this->isValid($value) ? $queryClass::create()->findPk($value) : null;
}
}