tax rule edition

This commit is contained in:
Etienne Roudeix
2013-10-11 11:09:23 +02:00
parent c1a8c27dee
commit 763026700d
11 changed files with 290 additions and 92 deletions

View File

@@ -23,9 +23,12 @@
namespace Thelia\Action; namespace Thelia\Action;
use Propel\Runtime\ActiveQuery\Criteria;
use Symfony\Component\EventDispatcher\EventSubscriberInterface; use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Thelia\Core\Event\Tax\TaxRuleEvent; use Thelia\Core\Event\Tax\TaxRuleEvent;
use Thelia\Core\Event\TheliaEvents; use Thelia\Core\Event\TheliaEvents;
use Thelia\Model\TaxRuleCountry;
use Thelia\Model\TaxRuleCountryQuery;
use Thelia\Model\TaxRule as TaxRuleModel; use Thelia\Model\TaxRule as TaxRuleModel;
use Thelia\Model\TaxRuleQuery; use Thelia\Model\TaxRuleQuery;
@@ -83,6 +86,51 @@ class TaxRule extends BaseAction implements EventSubscriberInterface
} }
} }
/**
* @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 * @param TaxRuleEvent $event
*/ */
@@ -106,6 +154,7 @@ class TaxRule extends BaseAction implements EventSubscriberInterface
return array( return array(
TheliaEvents::TAX_RULE_CREATE => array("create", 128), TheliaEvents::TAX_RULE_CREATE => array("create", 128),
TheliaEvents::TAX_RULE_UPDATE => array("update", 128), TheliaEvents::TAX_RULE_UPDATE => array("update", 128),
TheliaEvents::TAX_RULE_TAXES_UPDATE => array("updateTaxes", 128),
TheliaEvents::TAX_RULE_DELETE => array("delete", 128), TheliaEvents::TAX_RULE_DELETE => array("delete", 128),
); );

View File

@@ -114,6 +114,7 @@
<form name="thelia.admin.featureav.creation" class="Thelia\Form\FeatureAvCreationForm"/> <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.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.creation" class="Thelia\Form\TemplateCreationForm"/>
<form name="thelia.admin.template.modification" class="Thelia\Form\TemplateModificationForm"/> <form name="thelia.admin.template.modification" class="Thelia\Form\TemplateModificationForm"/>

View File

@@ -792,6 +792,10 @@
<default key="_controller">Thelia\Controller\Admin\TaxRuleController::processUpdateAction</default> <default key="_controller">Thelia\Controller\Admin\TaxRuleController::processUpdateAction</default>
</route> </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"> <route id="admin.configuration.taxes-rules.delete" path="/admin/configuration/taxes_rules/delete">
<default key="_controller">Thelia\Controller\Admin\TaxRuleController::deleteAction</default> <default key="_controller">Thelia\Controller\Admin\TaxRuleController::deleteAction</default>
</route> </route>

View File

@@ -27,6 +27,7 @@ use Thelia\Core\Event\Tax\TaxRuleEvent;
use Thelia\Core\Event\TheliaEvents; use Thelia\Core\Event\TheliaEvents;
use Thelia\Form\TaxRuleCreationForm; use Thelia\Form\TaxRuleCreationForm;
use Thelia\Form\TaxRuleModificationForm; use Thelia\Form\TaxRuleModificationForm;
use Thelia\Form\TaxRuleTaxListUpdateForm;
use Thelia\Model\CountryQuery; use Thelia\Model\CountryQuery;
use Thelia\Model\TaxRuleQuery; use Thelia\Model\TaxRuleQuery;
@@ -71,9 +72,7 @@ class TaxRuleController extends AbstractCrudController
protected function getUpdateEvent($formData) protected function getUpdateEvent($formData)
{ {
$event = new TaxRuleEvent( $event = new TaxRuleEvent();
TaxRuleQuery::create()->findPk($formData['id'])
);
$event->setLocale($formData['locale']); $event->setLocale($formData['locale']);
$event->setId($formData['id']); $event->setId($formData['id']);
@@ -83,6 +82,17 @@ class TaxRuleController extends AbstractCrudController
return $event; 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() protected function getDeleteEvent()
{ {
$event = new TaxRuleEvent(); $event = new TaxRuleEvent();
@@ -112,6 +122,16 @@ class TaxRuleController extends AbstractCrudController
return new TaxRuleModificationForm($this->getRequest(), "form", $data); 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) protected function getObjectFromEvent($event)
{ {
return $event->hasTaxRule() ? $event->getTaxRule() : null; return $event->hasTaxRule() ? $event->getTaxRule() : null;
@@ -134,11 +154,11 @@ class TaxRuleController extends AbstractCrudController
return $object->getId(); return $object->getId();
} }
protected function getViewArguments() protected function getViewArguments($country = null)
{ {
return array( return array(
'tab' => $this->getRequest()->get('tab', 'data'), 'tab' => $this->getRequest()->get('tab', 'data'),
'country' => $this->getRequest()->get('country', CountryQuery::create()->findOneByByDefault(1)->getIsoalpha3()), 'country' => $country === null ? $this->getRequest()->get('country', CountryQuery::create()->findOneByByDefault(1)->getId()) : $country,
); );
} }
@@ -164,12 +184,12 @@ class TaxRuleController extends AbstractCrudController
return $this->render('tax-rule-edit', array_merge($this->getViewArguments(), $this->getRouteArguments())); return $this->render('tax-rule-edit', array_merge($this->getViewArguments(), $this->getRouteArguments()));
} }
protected function redirectToEditionTemplate() protected function redirectToEditionTemplate($request = null, $country = null)
{ {
// We always return to the feature edition form // We always return to the feature edition form
$this->redirectToRoute( $this->redirectToRoute(
"admin.configuration.taxes-rules.update", "admin.configuration.taxes-rules.update",
$this->getViewArguments(), $this->getViewArguments($country),
$this->getRouteArguments() $this->getRouteArguments()
); );
} }
@@ -181,4 +201,70 @@ class TaxRuleController extends AbstractCrudController
); );
} }
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

@@ -33,6 +33,8 @@ class TaxRuleEvent extends ActionEvent
protected $id; protected $id;
protected $title; protected $title;
protected $description; protected $description;
protected $countryList;
protected $taxList;
public function __construct(TaxRule $taxRule = null) public function __construct(TaxRule $taxRule = null)
{ {
@@ -95,4 +97,26 @@ class TaxRuleEvent extends ActionEvent
{ {
return $this->locale; 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

@@ -509,6 +509,7 @@ final class TheliaEvents
const TAX_RULE_UPDATE = "action.updateTaxRule"; const TAX_RULE_UPDATE = "action.updateTaxRule";
const TAX_RULE_DELETE = "action.deleteTaxRule"; const TAX_RULE_DELETE = "action.deleteTaxRule";
const TAX_RULE_SET_DEFAULT = "action.setDefaultTaxRule"; const TAX_RULE_SET_DEFAULT = "action.setDefaultTaxRule";
const TAX_RULE_TAXES_UPDATE = "action.updateTaxesTaxRule";
// -- Product templates management ----------------------------------------- // -- Product templates management -----------------------------------------

View File

@@ -182,7 +182,8 @@ $this->assignFieldValues($template, $formFieldView->vars["full_name"], $fieldVar
public function renderHiddenFormField($params, \Smarty_Internal_Template $template) 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); $instance = $this->getInstanceFromParams($params);
@@ -192,7 +193,13 @@ $this->assignFieldValues($template, $formFieldView->vars["full_name"], $fieldVar
foreach ($formView->getIterator() as $row) { foreach ($formView->getIterator() as $row) {
if ($this->isHidden($row) && $row->isRendered() === false) { 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

@@ -35,17 +35,6 @@ class TaxRuleCreationForm extends BaseForm
->add("locale", "text", array( ->add("locale", "text", array(
"constraints" => array(new NotBlank()) "constraints" => array(new NotBlank())
)) ))
->add("country", "text", array(
"constraints" => array(
new Constraints\Callback(
array(
"methods" => array(
array($this, "verifyCountry"),
),
)
),
),
))
; ;
} }
@@ -53,14 +42,4 @@ class TaxRuleCreationForm extends BaseForm
{ {
return "thelia_tax_rule_creation"; return "thelia_tax_rule_creation";
} }
public function verifyCountry($value, ExecutionContextInterface $context)
{
$country = CountryQuery::create()
->findOneByIsoalpha3($value);
if (null === $country) {
$context->addViolation("Country ISOALPHA3 not found");
}
}
} }

View File

@@ -48,26 +48,6 @@ class TaxRuleModificationForm extends TaxRuleCreationForm
), ),
) )
)) ))
->add("tab", "text", array(
"constraints" => array(
new Constraints\Choice(
array(
'choices' => array('data', 'taxes'),
)
)
),
))
->add("country", "text", array(
"constraints" => array(
new Constraints\Callback(
array(
"methods" => array(
array($this, "verifyCountry"),
),
)
),
)
))
; ;
// Add standard description fields // Add standard description fields

View File

@@ -24,15 +24,19 @@ namespace Thelia\Form;
use Symfony\Component\Validator\Constraints; use Symfony\Component\Validator\Constraints;
use Symfony\Component\Validator\ExecutionContextInterface; use Symfony\Component\Validator\ExecutionContextInterface;
use Thelia\Model\CountryQuery;
use Thelia\Model\TaxQuery;
use Thelia\Model\TaxRuleQuery; use Thelia\Model\TaxRuleQuery;
use Thelia\Type\JsonType;
class TaxRuleModificationForm extends TaxRuleCreationForm class TaxRuleTaxListUpdateForm extends BaseForm
{ {
use StandardDescriptionFieldsTrait;
protected function buildForm() protected function buildForm()
{ {
parent::buildForm(true); $countryList = array();
foreach(CountryQuery::create()->find() as $country) {
$countryList[$country->getId()] = $country->getId();
}
$this->formBuilder $this->formBuilder
->add("id", "hidden", array( ->add("id", "hidden", array(
@@ -48,35 +52,35 @@ class TaxRuleModificationForm extends TaxRuleCreationForm
), ),
) )
)) ))
->add("tab", "text", array( ->add("tax_list", "hidden", array(
"constraints" => array( "required" => true,
new Constraints\Choice( "attr" => array(
array( "id" => 'tax_list',
'choices' => array('data', 'taxes'),
)
)
), ),
))
->add("country", "text", array(
"constraints" => array( "constraints" => array(
new Constraints\Callback( new Constraints\Callback(
array( array(
"methods" => array( "methods" => array(
array($this, "verifyCountry"), array($this, "verifyTaxList"),
), ),
) )
), ),
) )
)) ))
->add("country_list", "choice", array(
"choices" => $countryList,
"required" => true,
"multiple" => true,
"constraints" => array(
new Constraints\NotBlank(),
)
))
; ;
// Add standard description fields
$this->addStandardDescFields(array('postscriptum', 'chapo', 'locale'));
} }
public function getName() public function getName()
{ {
return "thelia_tax_rule_modification"; return "thelia_tax_rule_taxlistupdate";
} }
public function verifyTaxRuleId($value, ExecutionContextInterface $context) public function verifyTaxRuleId($value, ExecutionContextInterface $context)
@@ -88,4 +92,36 @@ class TaxRuleModificationForm extends TaxRuleCreationForm
$context->addViolation("Tax rule ID not found"); $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

@@ -6,7 +6,7 @@
{block name="main-content"} {block name="main-content"}
{assign oder_tab {$smarty.get.tab|default:"data"}} {assign oder_tab {$smarty.get.tab|default:$smarty.post.tab|default:'data'}}
{assign asked_country {$smarty.get.country|default:{country ask="default" attr="id"}}} {assign asked_country {$smarty.get.country|default:{country ask="default" attr="id"}}}
<div class="taxes-rules edit-taxes-rules"> <div class="taxes-rules edit-taxes-rules">
@@ -152,13 +152,23 @@
</p> </p>
{/if} {/if}
<div class="drag" data-id="{$TAX}">{$TAX_TITLE} - {$POSITION}</div> <div class="drag" data-id="{$TAX}">{$TAX_TITLE}</div>
{if $LOOP_COUNT == $LOOP_TOTAL} {if $LOOP_COUNT == $LOOP_TOTAL}
</div> </div>
{/if} {/if}
{/loop} {/loop}
{elseloop rel="existing-tax-list"}
<div class="drop-group droppable add-to-group">
<p class="drop-message">
<span class="glyphicon glyphicon-plus"></span>
<span class="message">{intl l="Add tax to this group"}</span>
</p>
</div>
{/elseloop}
</div> </div>
<div class="panel-footer droppable create-group"> <div class="panel-footer droppable create-group">
<p class="drop-message"> <p class="drop-message">
@@ -168,7 +178,7 @@
</div> </div>
</div> </div>
<a href="#confirmation_dialog" data-toggle="modal" id="apply-taxes-rules" class="btn btn-default btn-primary btn-block"><span class="glyphicon glyphicon-check"></span> {intl l="Apply"}</a> <a href="#tax_list_update_dialog" data-toggle="modal" id="apply-taxes-rules" class="btn btn-default btn-primary btn-block"><span class="glyphicon glyphicon-check"></span> {intl l="Apply"}</a>
</div> </div>
<div class="col-md-6"> <div class="col-md-6">
@@ -204,48 +214,64 @@
</div> </div>
{* Confirmation dialog *} {* Confirmation dialog *}
{form name="thelia.admin.taxrule.taxlistupdate"}
{if $form_error_message}
{$taxUpdateError = true}
{else}
{$taxUpdateError = false}
{/if}
{* Capture the dialog body, to pass it to the generic dialog *}
{capture "tax_list_update_dialog"}
{capture "confirmation_dialog"}
<form action="" method="post">
<input type="hidden" name="tax_rule_id" value="{$tax_rule_id}"> <input type="hidden" name="tax_rule_id" value="{$tax_rule_id}">
<input id="tax_list" type="hidden" name="tax_list"> <input type="hidden" name="tab" value="taxes">
{form_hidden_fields form=$form}
{form_field form=$form field='country_list'}
<p>{intl l="Tax rule taxes will be update for the following countries :"}</p> <p>{intl l="Tax rule taxes will be update for the following countries :"}</p>
<div class="form-group"> <div class="form-group">
<select name="" id="" data-toggle="selectpicker" multiple> <select name="{$name}" data-toggle="selectpicker" multiple>
{loop type="country" name="country-list"} {loop type="country" name="country-list"}
<option value="{$ID}" {if in_array($ID, $matchedCountries)}selected="selected"{/if}>{$TITLE}</option> <option value='{$ID}' {if (!$value AND in_array($ID, $matchedCountries)) OR ($value AND in_array($ID, $value))}selected="selected"{/if}>{$TITLE}</option>
{/loop} {/loop}
</select> </select>
</div> </div>
</form>
{/capture} {/form_field}
{include {/capture}
file = "includes/generic-create-dialog.html"
dialog_id = "confirmation_dialog" {include
dialog_title = {intl l="Edit tax rule taxes"} file = "includes/generic-create-dialog.html"
dialog_body = {$smarty.capture.confirmation_dialog nofilter}
dialog_ok_label = {intl l="Edit tax rule taxes"} dialog_id = "tax_list_update_dialog"
dialog_title = {intl l="Update tax rule taxes"}
dialog_body = {$smarty.capture.tax_list_update_dialog nofilter}
form_action = {url path='/admin/categories/create'} dialog_ok_label = {intl l="Edit tax rule taxes"}
dialog_cancel_label = {intl l="Cancel"}
form_error_message = $form_error_message form_action = {url path="/admin/configuration/taxes_rules/saveTaxes"}
} form_enctype = {form_enctype form=$form}
form_error_message = $form_error_message
}
{/form}
{/block} {/block}
{block name="javascript-initialization"} {block name="javascript-initialization"}
{javascripts file='assets/js/bootstrap-select/bootstrap-select.js'} {javascripts file='assets/js/bootstrap-select/bootstrap-select.js'}
<script src="{$asset_url}"></script> <script src='{$asset_url}'></script>
{/javascripts} {/javascripts}
{javascripts file='assets/js/main.js'} {javascripts file='assets/js/main.js'}
<script src="{$asset_url}"></script> <script src='{$asset_url}'></script>
{/javascripts} {/javascripts}
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script> <script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
@@ -253,11 +279,15 @@
<script> <script>
$(function() { $(function() {
{if $taxUpdateError == true}
$('#tax_list_update_dialog').modal();
{/if}
{literal}
$('#country-selector').change(function(e) { $('#country-selector').change(function(e) {
$('#country-selector-form').submit(); $('#country-selector-form').submit();
}); });
{literal}
// Cache jQuery Objects // Cache jQuery Objects
var $group = $('#panel'); var $group = $('#panel');
var $list = $('#panel-list'); var $list = $('#panel-list');
@@ -294,7 +324,7 @@
// Default options for sortabble // Default options for sortabble
var sortOptions = { var sortOptions = {
cursor: 'move', cursor: 'move',
items: 'div', cancel: '.drop-message',
update: function( event, ui ){ update: function( event, ui ){
// Check if we have an empty group // Check if we have an empty group
var $zone = $('.add-to-group', $group); var $zone = $('.add-to-group', $group);
@@ -357,6 +387,7 @@
} }
}); });
{/literal} {/literal}
}); });