- Base create/update coupon in backoffice
This commit is contained in:
gmorel
2013-09-04 19:22:20 +02:00
parent f399b1de2e
commit 23a4ff26c8
8 changed files with 226 additions and 108 deletions

View File

@@ -92,7 +92,7 @@ class Coupon extends BaseAction implements EventSubscriberInterface
$event->isCumulative(), $event->isCumulative(),
$event->getMaxUsage(), $event->getMaxUsage(),
$event->getRules(), $event->getRules(),
$event->getLang() $event->getLocale()
); );
$event->setCoupon($coupon); $event->setCoupon($coupon);

View File

@@ -42,6 +42,11 @@
<tag name="kernel.event_subscriber"/> <tag name="kernel.event_subscriber"/>
</service> </service>
<service id="thelia.action.coupon" class="Thelia\Action\Coupon">
<argument type="service" id="service_container"/>
<tag name="kernel.event_subscriber"/>
</service>
<service id="thelia.action.currency" class="Thelia\Action\Currency"> <service id="thelia.action.currency" class="Thelia\Action\Currency">
<argument type="service" id="service_container"/> <argument type="service" id="service_container"/>
<tag name="kernel.event_subscriber"/> <tag name="kernel.event_subscriber"/>

View File

@@ -52,8 +52,8 @@
<route id="admin.coupon.create" path="/admin/coupon/create"> <route id="admin.coupon.create" path="/admin/coupon/create">
<default key="_controller">Thelia\Controller\Admin\CouponController::createAction</default> <default key="_controller">Thelia\Controller\Admin\CouponController::createAction</default>
</route> </route>
<route id="admin.coupon.edit" path="/admin/coupon/edit/{couponId}"> <route id="admin.coupon.update" path="/admin/coupon/update/{couponId}">
<default key="_controller">Thelia\Controller\Admin\CouponController::editAction</default> <default key="_controller">Thelia\Controller\Admin\CouponController::updateAction</default>
</route> </route>
<route id="admin.coupon.read" path="/admin/coupon/read/{couponId}"> <route id="admin.coupon.read" path="/admin/coupon/read/{couponId}">
<default key="_controller">Thelia\Controller\Admin\CouponController::readAction</default> <default key="_controller">Thelia\Controller\Admin\CouponController::readAction</default>

View File

@@ -68,8 +68,6 @@ class CouponController extends BaseAdminController
/** /**
* Manage Coupons creation display * Manage Coupons creation display
* *
* @param array $args GET arguments
*
* @return \Symfony\Component\HttpFoundation\Response * @return \Symfony\Component\HttpFoundation\Response
*/ */
public function createAction() public function createAction()
@@ -80,96 +78,106 @@ class CouponController extends BaseAdminController
return $response; return $response;
} }
$message = false; // Parameters given to the template
$args = array();
// Create the form from the request $i18n = new I18n();
$creationForm = new CouponCreationForm($this->getRequest()); /** @var Lang $lang */
$lang = $this->getSession()->get('lang');
$eventToDispatch = TheliaEvents::COUPON_CREATE;
if ($this->getRequest()->isMethod('POST')) { if ($this->getRequest()->isMethod('POST')) {
try { $this->validateCreateOrUpdateForm(
// Check the form against constraints violations $i18n,
$form = $this->validateForm($creationForm, 'POST'); $lang,
$i18n = new I18n(); $eventToDispatch,
/** @var Lang $lang */ 'created',
$lang = $this->getSession()->get('lang'); 'creation'
);
// Get the form field values } else {
$data = $form->getData(); // If no input for expirationDate, now + 2 months
$couponEvent = new CouponCreateOrUpdateEvent( $defaultDate = new \DateTime();
$data['code'], $args['defaultDate'] = $defaultDate->modify('+2 month')
$data['title'], ->format($lang->getDateFormat());
$data['amount'],
$data['effect'],
$data['shortDescription'],
$data['description'],
$data['isEnabled'],
$i18n->getDateTimeFromForm($lang, $data['expirationDate']),
$data['isAvailableOnSpecialOffers'],
$data['isCumulative'],
$data['isRemovingPostage'],
$data['maxUsage'],
array(),
$data['locale']
);
$this->dispatch(
TheliaEvents::COUPON_CREATE,
$couponEvent
);
$this->adminLogAppend(
sprintf(
'Coupon %s (ID ) created',
$couponEvent->getTitle()
// $couponEvent->getCoupon()->getId()
)
);
// @todo redirect if successful
} catch (FormValidationException $e) {
// Invalid data entered
$message = 'Please check your input:';
$this->logError('creation', $message, $e);
} catch (\Exception $e) {
// Any other error
$message = 'Sorry, an error occurred:';
$this->logError('creation', $message, $e);
}
if ($message !== false) {
// Mark the form as with error
$creationForm->setErrorMessage($message);
// Send the form and the error to the parser
$this->getParserContext()
->addForm($creationForm)
->setGeneralError($message);
}
} }
$formAction = 'admin/coupon/create'; $args['formAction'] = 'admin/coupon/create';
return $this->render( return $this->render(
'coupon-create', 'coupon-create',
array( $args
'formAction' => $formAction
)
); );
} }
/** /**
* Manage Coupons edition display * Manage Coupons edition display
* *
* @param array $args GET arguments * @param int $couponId Coupon id
* *
* @return \Symfony\Component\HttpFoundation\Response * @return \Symfony\Component\HttpFoundation\Response
*/ */
public function editAction($couponId) public function updateAction($couponId)
{ {
$this->checkAuth('ADMIN', 'admin.coupon.edit'); // Check current user authorization
$response = $this->checkAuth('admin.coupon.update');
if ($response !== null) {
return $response;
}
$formAction = 'admin/coupon/edit/' . $couponId; /** @var Coupon $coupon */
$coupon = CouponQuery::create()->findOneById($couponId);
if (!$coupon) {
$this->pageNotFound();
}
return $this->render('coupon-edit', array('formAction' => $formAction)); // Parameters given to the template
$args = array();
$i18n = new I18n();
/** @var Lang $lang */
$lang = $this->getSession()->get('lang');
$eventToDispatch = TheliaEvents::COUPON_UPDATE;
if ($this->getRequest()->isMethod('POST')) {
$this->validateCreateOrUpdateForm(
$i18n,
$lang,
$eventToDispatch,
'updated',
'update'
);
} else {
// Prepare the data that will hydrate the form
$data = array(
'code' => $coupon->getCode(),
'title' => $coupon->getTitle(),
'amount' => $coupon->getAmount(),
'effect' => $coupon->getType(),
'shortDescription' => $coupon->getShortDescription(),
'description' => $coupon->getDescription(),
'isEnabled' => ($coupon->getIsEnabled() == 1),
'expirationDate' => $coupon->getExpirationDate($lang->getDateFormat()),
'isAvailableOnSpecialOffers' => ($coupon->getIsAvailableOnSpecialOffers() == 1),
'isCumulative' => ($coupon->getIsCumulative() == 1),
'isRemovingPostage' => ($coupon->getIsRemovingPostage() == 1),
'maxUsage' => $coupon->getMaxUsage(),
'rules' => new CouponRuleCollection(array()),
'locale' => $coupon->getLocale(),
);
// Setup the object form
$changeForm = new CouponCreationForm($this->getRequest(), 'form', $data);
// Pass it to the parser
$this->getParserContext()->addForm($changeForm);
}
$args['formAction'] = 'admin/coupon/update/' . $couponId;
return $this->render(
'coupon-update',
$args
);
} }
/** /**
@@ -251,4 +259,90 @@ class CouponController extends BaseAdminController
return $this; return $this;
} }
/**
* Validate the CreateOrUpdate form
*
* @param string $i18n Local code (fr_FR)
* @param Lang $lang Local variables container
* @param string $eventToDispatch Event which will activate actions
* @param string $log created|edited
* @param string $action creation|edition
*
* @return $this
*/
protected function validateCreateOrUpdateForm($i18n, $lang, $eventToDispatch, $log, $action)
{
// Create the form from the request
$creationForm = new CouponCreationForm($this->getRequest());
$message = false;
try {
// Check the form against constraints violations
$form = $this->validateForm($creationForm, 'POST');
// Get the form field values
$data = $form->getData();
$couponEvent = new CouponCreateOrUpdateEvent(
$data['code'],
$data['title'],
$data['amount'],
$data['effect'],
$data['shortDescription'],
$data['description'],
$data['isEnabled'],
$i18n->getDateTimeFromForm($lang, $data['expirationDate']),
$data['isAvailableOnSpecialOffers'],
$data['isCumulative'],
$data['isRemovingPostage'],
$data['maxUsage'],
new CouponRuleCollection(array()),
$data['locale']
);
// Dispatch Event to the Action
$this->dispatch(
$eventToDispatch,
$couponEvent
);
$this->adminLogAppend(
sprintf(
'Coupon %s (ID ) ' . $log,
$couponEvent->getTitle(),
$couponEvent->getCoupon()->getId()
)
);
$this->redirect(
str_replace(
'{id}',
$couponEvent->getCoupon()->getId(),
$creationForm->getSuccessUrl()
)
);
} catch (FormValidationException $e) {
// Invalid data entered
$message = 'Please check your input:';
$this->logError($action, $message, $e);
} catch (\Exception $e) {
// Any other error
$message = 'Sorry, an error occurred:';
$this->logError($action, $message, $e);
}
if ($message !== false) {
// Mark the form as with error
$creationForm->setErrorMessage($message);
// Send the form and the error to the parser
$this->getParserContext()
->addForm($creationForm)
->setGeneralError($message);
}
return $this;
}
} }

View File

@@ -22,7 +22,6 @@
/**********************************************************************************/ /**********************************************************************************/
namespace Thelia\Core\Event\Coupon; namespace Thelia\Core\Event\Coupon;
use Symfony\Component\EventDispatcher\Event;
use Thelia\Core\Event\ActionEvent; use Thelia\Core\Event\ActionEvent;
use Thelia\Coupon\CouponRuleCollection; use Thelia\Coupon\CouponRuleCollection;
use Thelia\Model\Coupon; use Thelia\Model\Coupon;
@@ -83,7 +82,7 @@ class CouponCreateOrUpdateEvent extends ActionEvent
protected $effect; protected $effect;
/** @var string Language code ISO (ex: fr_FR) */ /** @var string Language code ISO (ex: fr_FR) */
protected $lang = null; protected $locale = null;
/** /**
* Constructor * Constructor
@@ -101,7 +100,7 @@ class CouponCreateOrUpdateEvent extends ActionEvent
* @param boolean $isRemovingPostage Is removing Postage * @param boolean $isRemovingPostage Is removing Postage
* @param int $maxUsage Coupon quantity * @param int $maxUsage Coupon quantity
* @param CouponRuleCollection $rules CouponRuleInterface to add * @param CouponRuleCollection $rules CouponRuleInterface to add
* @param string $lang Coupon Language code ISO (ex: fr_FR) * @param string $locale Coupon Language code ISO (ex: fr_FR)
*/ */
function __construct( function __construct(
$code, $code,
@@ -117,7 +116,7 @@ class CouponCreateOrUpdateEvent extends ActionEvent
$isRemovingPostage, $isRemovingPostage,
$maxUsage, $maxUsage,
$rules, $rules,
$lang $locale
) { ) {
$this->amount = $amount; $this->amount = $amount;
$this->code = $code; $this->code = $code;
@@ -132,7 +131,7 @@ class CouponCreateOrUpdateEvent extends ActionEvent
$this->shortDescription = $shortDescription; $this->shortDescription = $shortDescription;
$this->title = $title; $this->title = $title;
$this->effect = $effect; $this->effect = $effect;
$this->lang = $lang; $this->locale = $locale;
} }
/** /**
@@ -214,7 +213,13 @@ class CouponCreateOrUpdateEvent extends ActionEvent
*/ */
public function getRules() public function getRules()
{ {
return clone $this->rules; if ($this->rules === null || !is_object($this->rules)) {
$rules = $this->rules;
} else {
$rules = clone $this->rules;
}
return $rules;
} }
/** /**
@@ -273,20 +278,28 @@ class CouponCreateOrUpdateEvent extends ActionEvent
* *
* @return string * @return string
*/ */
public function getLang() public function getLocale()
{ {
return $this->lang; return $this->locale;
} }
/** /**
* @param \Thelia\Model\Coupon $coupon * Set Coupon Model
*
* @param \Thelia\Model\Coupon $coupon Coupon Model
*
* @return $this
*/ */
public function setCoupon($coupon) public function setCoupon($coupon)
{ {
$this->coupon = $coupon; $this->coupon = $coupon;
return $this;
} }
/** /**
* Return Coupon Model
*
* @return \Thelia\Model\Coupon * @return \Thelia\Model\Coupon
*/ */
public function getCoupon() public function getCoupon()

View File

@@ -44,6 +44,9 @@ use Thelia\Model\Map\CouponTableMap;
class Coupon extends BaseCoupon class Coupon extends BaseCoupon
{ {
use \Thelia\Model\Tools\ModelEventDispatcherTrait;
/** /**
* Constructor * Constructor
* *
@@ -60,9 +63,9 @@ class Coupon extends BaseCoupon
* @param boolean $isRemovingPostage Is removing Postage * @param boolean $isRemovingPostage Is removing Postage
* @param int $maxUsage Coupon quantity * @param int $maxUsage Coupon quantity
* @param CouponRuleCollection $rules CouponRuleInterface to add * @param CouponRuleCollection $rules CouponRuleInterface to add
* @param string $lang Coupon Language code ISO (ex: fr_FR) * @param string $locale Coupon Language code ISO (ex: fr_FR)
*/ */
function createOrUpdate($code, $title, $amount, $effect, $shortDescription, $description, $isEnabled, $expirationDate, $isAvailableOnSpecialOffers, $isCumulative, $maxUsage, $rules, $lang = null) function createOrUpdate($code, $title, $amount, $effect, $shortDescription, $description, $isEnabled, $expirationDate, $isAvailableOnSpecialOffers, $isCumulative, $maxUsage, $rules, $locale = null)
{ {
$this->setCode($code) $this->setCode($code)
->setTitle($title) ->setTitle($title)
@@ -79,8 +82,8 @@ class Coupon extends BaseCoupon
->setRules($rules); ->setRules($rules);
// Set object language (i18n) // Set object language (i18n)
if (!is_null($lang)) { if (!is_null($locale)) {
$this->setLang($lang); $this->setLocale($locale);
} }
$con = Propel::getWriteConnection(CouponTableMap::DATABASE_NAME); $con = Propel::getWriteConnection(CouponTableMap::DATABASE_NAME);

View File

@@ -1,6 +1,6 @@
{extends file="admin-layout.tpl"} {extends file="admin-layout.tpl"}
{block name="check-permissions"}admin.coupon.edit{/block} {block name="check-permissions"}admin.coupon.update{/block}
{block name="page-title"}{intl l='Edit coupon'}{/block} {block name="page-title"}{intl l='Update coupon'}{/block}
{block name="main-content"} {block name="main-content"}
<section id="wrapper" class="container"> <section id="wrapper" class="container">
@@ -12,10 +12,10 @@
</nav> </nav>
<div class="page-header"> <div class="page-header">
<h1>Coupons : <small>Add a coupon</small></h1> <h1>Coupons : <small>Update a coupon</small></h1>
</div> </div>
{form name="thelia.admin.coupon.edit"} {form name="thelia.admin.coupon.creation"}
{include file='coupon/form.html' formAction={url path={$formAction}} form=$form} {include file='coupon/form.html' formAction={url path={$formAction}} form=$form}
{/form} {/form}

View File

@@ -10,6 +10,10 @@
<input type="hidden" name="{$name}" value="{if $value}{$value}{else}{$edit_language_locale}{/if}" /> <input type="hidden" name="{$name}" value="{if $value}{$value}{else}{$edit_language_locale}{/if}" />
{/form_field} {/form_field}
{form_field form=$form field='success_url'}
<input type="hidden" name="{$name}" value="{url path='/admin/coupon/read/{id}'}" />
{/form_field}
<div class="span4"> <div class="span4">
<div class="control-group"> <div class="control-group">
<label for="code">Code :</label> <label for="code">Code :</label>
@@ -30,9 +34,8 @@
<div class="control-group"> <div class="control-group">
<label for="enabled" class="checkbox"> <label for="enabled" class="checkbox">
{form_field form=$form field='isEnabled'} {form_field form=$form field='isEnabled'}
<input id="enabled" type="checkbox" name="{$name}" {if $value}checked{/if} > <input id="enabled" type="checkbox" name="{$name}" {if $value}value="1" checked{else}value="0"{/if} >
{if $error}{$message}{/if} {if $error}{$message}{/if}
value = {$value}
{/form_field} {/form_field}
Is enabled ? Is enabled ?
</label> </label>
@@ -41,7 +44,7 @@
<div class="control-group"> <div class="control-group">
<label for="available-on-special-offers" class="checkbox"> <label for="available-on-special-offers" class="checkbox">
{form_field form=$form field='isAvailableOnSpecialOffers'} {form_field form=$form field='isAvailableOnSpecialOffers'}
<input id="available-on-special-offers" type="checkbox" name="{$name}" {if $value}checked{/if} > <input id="available-on-special-offers" type="checkbox" name="{$name}" {if $value}value="1" checked{else}value="0"{/if} >
{if $error}{$message}{/if} {if $error}{$message}{/if}
{/form_field} {/form_field}
Is available on special offers ? Is available on special offers ?
@@ -51,7 +54,7 @@
<div class="control-group"> <div class="control-group">
<label for="cumulative" class="checkbox"> <label for="cumulative" class="checkbox">
{form_field form=$form field='isCumulative'} {form_field form=$form field='isCumulative'}
<input id="cumulative" type="checkbox" name="{$name}" {if $value}checked{/if} > <input id="cumulative" type="checkbox" name="{$name}" {if $value}value="1" checked{else}value="0"{/if} >
{if $error}{$message}{/if} {if $error}{$message}{/if}
{/form_field} {/form_field}
Is cumulative ? Is cumulative ?
@@ -61,7 +64,7 @@
<div class="control-group"> <div class="control-group">
<label for="renoving-postage" class="checkbox"> <label for="renoving-postage" class="checkbox">
{form_field form=$form field='isRemovingPostage'} {form_field form=$form field='isRemovingPostage'}
<input id="renoving-postage" type="checkbox" name="{$name}" {if $value}checked{/if} > <input id="renoving-postage" type="checkbox" name="{$name}" {if $value}value="1" checked{else}value="0"{/if} >
{if $error}{$message}{/if} {if $error}{$message}{/if}
{/form_field} {/form_field}
Is removing postage ? Is removing postage ?
@@ -72,7 +75,7 @@
<label for="expiration-date">Expiration date :</label> <label for="expiration-date">Expiration date :</label>
<div class="input-append date" data-date="12/02/2012" data-date-format="dd/mm/yyyy"> <div class="input-append date" data-date="12/02/2012" data-date-format="dd/mm/yyyy">
{form_field form=$form field='expirationDate'} {form_field form=$form field='expirationDate'}
<input type="text" id="expiration-date" name="{$name}" value="{$value}"> <input type="text" id="expiration-date" name="{$name}" value="{if $defaultDate}{$defaultDate}{else}{$value}{/if}">
{if $error}{$message}{/if} {if $error}{$message}{/if}
{/form_field} {/form_field}
<span class="add-on"><span class="icon-th"></span></span> <span class="add-on"><span class="icon-th"></span></span>
@@ -82,7 +85,7 @@
<div class="control-group"> <div class="control-group">
<label for="max-usage">Max usage :</label> <label for="max-usage">Max usage :</label>
<label for="is-unlimited" class="checkbox"> <label for="is-unlimited" class="checkbox">
<input id="is-unlimited" type="checkbox" name="{$name}" {if $value}checked{/if} > <input id="is-unlimited" type="checkbox" name="is-unlimited" checked >
Is unlimited ? Is unlimited ?
</label> </label>
{form_field form=$form field='maxUsage'} {form_field form=$form field='maxUsage'}
@@ -117,24 +120,24 @@
{if $error}{$message}{/if} {if $error}{$message}{/if}
{/form_field} {/form_field}
</div> </div>
<div class="control-group"> {*<div class="control-group">*}
<label for="category">Category :</label> {*<label for="category">Category :</label>*}
{*form_field form=$form field='category'*} {*form_field form=$form field='category'*}
<select name="{$name}" value="{$value}" id="category"> {*<select name="{$name}" value="{$value}" id="category">*}
<option value="1">Category 1</option> {*<option value="1">Category 1</option>*}
<option value="1">Category 2</option> {*<option value="1">Category 2</option>*}
<option value="1">Category 3</option> {*<option value="1">Category 3</option>*}
</select> {*</select>*}
{*if $error}{$message}{/if}*} {*if $error}{$message}{/if}*}
{*/form_field*} {*/form_field*}
</div> {*</div>*}
</div> </div>
</div> </div>
<div class="control-group"> <div class="control-group">
<label for="short-description">Short description :</label> <label for="short-description">Short description :</label>
{form_field form=$form field='shortDescription'} {form_field form=$form field='shortDescription'}
<textarea id="short-description" name="{$name}" value="{$value}" placeholder="short description" class="span12" rows="5"></textarea> <textarea id="short-description" name="{$name}" placeholder="short description" class="span12" rows="5">{$value nofilter}</textarea>
{if $error}{$message}{/if} {if $error}{$message}{/if}
{/form_field} {/form_field}
</div> </div>