Merge branch 'master' of github.com:thelia/thelia

This commit is contained in:
Manuel Raynaud
2013-09-16 10:17:35 +02:00
41 changed files with 1760 additions and 1295 deletions

View File

@@ -23,10 +23,16 @@
namespace Thelia\Action;
use Symfony\Component\Config\Definition\Exception\Exception;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Thelia\Constraint\ConstraintFactory;
use Thelia\Core\Event\Coupon\CouponConsumeEvent;
use Thelia\Core\Event\Coupon\CouponCreateOrUpdateEvent;
use Thelia\Core\Event\TheliaEvents;
use Thelia\Core\HttpFoundation\Request;
use Thelia\Coupon\CouponFactory;
use Thelia\Coupon\CouponManager;
use Thelia\Coupon\Type\CouponInterface;
use Thelia\Model\Coupon as CouponModel;
/**
@@ -45,7 +51,7 @@ class Coupon extends BaseAction implements EventSubscriberInterface
/**
* Occurring when a Coupon is about to be created
*
* @param CouponCreateOrUpdateEvent $event Event creation or update Event
* @param CouponCreateOrUpdateEvent $event Event creation or update Coupon
*/
public function create(CouponCreateOrUpdateEvent $event)
{
@@ -57,7 +63,7 @@ class Coupon extends BaseAction implements EventSubscriberInterface
/**
* Occurring when a Coupon is about to be updated
*
* @param CouponCreateOrUpdateEvent $event Event creation or update Event
* @param CouponCreateOrUpdateEvent $event Event creation or update Coupon
*/
public function update(CouponCreateOrUpdateEvent $event)
{
@@ -69,7 +75,7 @@ class Coupon extends BaseAction implements EventSubscriberInterface
/**
* Occurring when a Coupon rule is about to be updated
*
* @param CouponCreateOrUpdateEvent $event Event creation or update Event
* @param CouponCreateOrUpdateEvent $event Event creation or update Coupon Rule
*/
public function updateRule(CouponCreateOrUpdateEvent $event)
{
@@ -81,11 +87,43 @@ class Coupon extends BaseAction implements EventSubscriberInterface
/**
* Occurring when a Coupon rule is about to be consumed
*
* @param CouponCreateOrUpdateEvent $event Event creation or update Event
* @param CouponConsumeEvent $event Event consuming Coupon
*/
public function consume(CouponCreateOrUpdateEvent $event)
public function consume(CouponConsumeEvent $event)
{
// @todo implements
$totalDiscount = 0;
/** @var CouponFactory $couponFactory */
$couponFactory = $this->container->get('thelia.coupon.factory');
/** @var CouponManager $couponManager */
$couponManager = $this->container->get('thelia.coupon.manager');
/** @var CouponInterface $coupon */
$coupon = $couponFactory->buildCouponFromCode($event->getCode());
$isValid = $coupon->isMatching();
if ($isValid) {
/** @var Request $request */
$request = $this->container->get('request');
$consumedCoupons = $request->getSession()->getConsumedCoupons();
if (!isset($consumedCoupons) || !$consumedCoupons) {
$consumedCoupons = array();
}
// Prevent accumulation of the same Coupon on a Checkout
$consumedCoupons[$event->getCode()] = $event->getCode();
$request->getSession()->setConsumedCoupons($consumedCoupons);
$totalDiscount = $couponManager->getDiscount();
// @todo modify Cart total discount
}
$event->setIsValid($isValid);
$event->setDiscount($totalDiscount);
}
/**
@@ -165,8 +203,6 @@ class Coupon extends BaseAction implements EventSubscriberInterface
return array(
TheliaEvents::COUPON_CREATE => array("create", 128),
TheliaEvents::COUPON_UPDATE => array("update", 128),
TheliaEvents::COUPON_DISABLE => array("disable", 128),
TheliaEvents::COUPON_ENABLE => array("enable", 128),
TheliaEvents::COUPON_CONSUME => array("consume", 128),
TheliaEvents::COUPON_RULE_UPDATE => array("updateRule", 128)
);

View File

@@ -235,6 +235,8 @@
<service id="thelia.constraint.factory" class="Thelia\Constraint\ConstraintFactory">
<argument type="service" id="service_container" />
</service>
<service id="thelia.constraint.validator" class="Thelia\Constraint\ConstraintValidator">
</service>
<service id="thelia.constraint.rule.available_for_everyone" class="Thelia\Constraint\Rule\AvailableForEveryoneManager">
<argument type="service" id="thelia.adapter" />
<tag name="thelia.coupon.addRule"/>

View File

@@ -103,25 +103,27 @@
<!-- Route to the Coupon controller (process Coupon browsing) -->
<route id="admin.coupon.list" path="/admin/coupon">
<route id="admin.coupon.list" path="/admin/coupon/">
<default key="_controller">Thelia\Controller\Admin\CouponController::browseAction</default>
</route>
<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>
</route>
<route id="admin.coupon.update" path="/admin/coupon/update/{couponId}">
<route id="admin.coupon.update" path="/admin/coupon/update/{couponId}/">
<default key="_controller">Thelia\Controller\Admin\CouponController::updateAction</default>
</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>
</route>
<route id="admin.coupon.rule.input" path="/admin/coupon/rule/{ruleId}">
<route id="admin.coupon.rule.input" path="/admin/coupon/rule/{ruleId}/">
<default key="_controller">Thelia\Controller\Admin\CouponController::getRuleInputAction</default>
</route>
<route id="admin.coupon.rule.update" path="/admin/coupon/{couponId}/rule/update/">
<default key="_controller">Thelia\Controller\Admin\CouponController::updateRulesAction</default>
</route>
<route id="admin.coupon.consume" path="/admin/coupon/consume/{couponCode}/">
<default key="_controller">Thelia\Controller\Admin\CouponController::consumeAction</default>
</route>
<!-- Routes to the Config (system variables) controller -->

View File

@@ -25,6 +25,7 @@ namespace Thelia\Constraint;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\Serializer\Encoder\JsonEncoder;
use Thelia\Constraint\Rule\AvailableForEveryoneManager;
use Thelia\Constraint\Rule\AvailableForTotalAmountManager;
use Thelia\Constraint\Rule\CouponRuleInterface;
use Thelia\Constraint\Rule\SerializableRule;
@@ -74,11 +75,22 @@ class ConstraintFactory
*/
public function serializeCouponRuleCollection(CouponRuleCollection $collection)
{
if ($collection->isEmpty()) {
/** @var CouponRuleInterface $ruleNoCondition */
$ruleNoCondition = $this->container->get(
'thelia.constraint.rule.available_for_everyone'
);
$collection->add($ruleNoCondition);
}
$serializableRules = array();
$rules = $collection->getRules();
if ($rules !== null) {
/** @var $rule CouponRuleInterface */
foreach ($rules as $rule) {
// Remove all rule if the "no condition" rule is found
// if ($rule->getServiceId() == 'thelia.constraint.rule.available_for_everyone') {
// return base64_encode(json_encode(array($rule->getSerializableRule())));
// }
$serializableRules[] = $rule->getSerializableRule();
}
}

View File

@@ -52,7 +52,7 @@ class ConstraintValidator
*
* @return bool
*/
public function test(CouponRuleCollection $rules)
public function isMatching(CouponRuleCollection $rules)
{
$isMatching = true;
/** @var CouponRuleInterface $rule */

View File

@@ -25,7 +25,6 @@ namespace Thelia\Constraint\Rule;
use Symfony\Component\Intl\Exception\NotImplementedException;
use Symfony\Component\Translation\Translator;
use Thelia\Constraint\ConstraintValidator;
use Thelia\Coupon\CouponAdapterInterface;
use Thelia\Constraint\Validator\PriceParam;
use Thelia\Constraint\Validator\RuleValidator;
@@ -168,13 +167,12 @@ class AvailableForTotalAmountManager extends CouponRuleAbstract
return false;
}
$constrainValidator = new ConstraintValidator();
$constraint1 =$constrainValidator->variableOpComparison(
$constraint1 = $this->constraintValidator->variableOpComparison(
$this->adapter->getCartTotalPrice(),
$this->operators[self::INPUT1],
$this->values[self::INPUT1]
);
$constraint2 =$constrainValidator->variableOpComparison(
$constraint2 = $this->constraintValidator->variableOpComparison(
$this->adapter->getCheckoutCurrency(),
$this->operators[self::INPUT2],
$this->values[self::INPUT2]

View File

@@ -126,8 +126,7 @@ class AvailableForXArticlesManager extends CouponRuleAbstract
*/
public function isMatching()
{
$constrainValidator = new ConstraintValidator();
$constraint1 =$constrainValidator->variableOpComparison(
$constraint1 = $this->constraintValidator->variableOpComparison(
$this->adapter->getNbArticlesInCart(),
$this->operators[self::INPUT1],
$this->values[self::INPUT1]

View File

@@ -82,6 +82,7 @@ abstract class CouponRuleAbstract implements CouponRuleInterface
{
$this->adapter = $adapter;
$this->translator = $adapter->getTranslator();
$this->constraintValidator = $adapter->getConstraintValidator();
}
// /**

View File

@@ -133,21 +133,21 @@ abstract class Operators
break;
case self::INFERIOR_OR_EQUAL:
$ret = $translator->trans(
'inferior or equals to',
'inferior or equal to',
array(),
'constraint'
);
break;
case self::EQUAL:
$ret = $translator->trans(
'equals to',
'equal to',
array(),
'constraint'
);
break;
case self::SUPERIOR_OR_EQUAL:
$ret = $translator->trans(
'superior or equals to',
'superior or equal to',
array(),
'constraint'
);

View File

@@ -30,6 +30,7 @@ use Thelia\Constraint\ConstraintFactoryTest;
use Thelia\Constraint\Rule\AvailableForTotalAmount;
use Thelia\Constraint\Rule\CouponRuleInterface;
use Thelia\Constraint\Validator\PriceParam;
use Thelia\Core\Event\Coupon\CouponConsumeEvent;
use Thelia\Core\Event\Coupon\CouponCreateEvent;
use Thelia\Core\Event\Coupon\CouponCreateOrUpdateEvent;
use Thelia\Core\Event\Coupon\CouponEvent;
@@ -39,6 +40,7 @@ use Thelia\Core\Security\Exception\AuthenticationException;
use Thelia\Core\Security\Exception\AuthorizationException;
use Thelia\Core\Translation\Translator;
use Thelia\Coupon\CouponAdapterInterface;
use Thelia\Coupon\CouponFactory;
use Thelia\Coupon\CouponManager;
use Thelia\Coupon\CouponRuleCollection;
use Thelia\Coupon\Type\CouponInterface;
@@ -72,7 +74,54 @@ class CouponController extends BaseAdminController
{
$this->checkAuth('ADMIN', 'admin.coupon.view');
return $this->render('coupon-list');
$args['urlReadCoupon'] = $this->getRoute(
'admin.coupon.read',
array('couponId' => 'couponId'),
Router::ABSOLUTE_URL
);
$args['urlEditCoupon'] = $this->getRoute(
'admin.coupon.update',
array('couponId' => 'couponId'),
Router::ABSOLUTE_URL
);
$args['urlCreateCoupon'] = $this->getRoute(
'admin.coupon.create',
array(),
Router::ABSOLUTE_URL
);
return $this->render('coupon-list', $args);
}
/**
* Manage Coupons read display
*
* @param int $couponId Coupon Id
*
* @return \Symfony\Component\HttpFoundation\Response
*/
public function readAction($couponId)
{
$this->checkAuth('ADMIN', 'admin.coupon.read');
// Database request repeated in the loop but cached
$search = CouponQuery::create();
$coupon = $search->findOneById($couponId);
if ($coupon === null) {
return $this->pageNotFound();
}
$args['couponId'] = $couponId;
$args['urlEditCoupon'] = $this->getRoute(
'admin.coupon.update',
array('couponId' => $couponId),
Router::ABSOLUTE_URL
);
return $this->render('coupon-read', $args);
}
/**
@@ -93,7 +142,7 @@ class CouponController extends BaseAdminController
$i18n = new I18n();
/** @var Lang $lang */
$lang = $this->getSession()->get('lang');
$lang = $this->getSession()->getLang();
$eventToDispatch = TheliaEvents::COUPON_CREATE;
if ($this->getRequest()->isMethod('POST')) {
@@ -108,10 +157,12 @@ class CouponController extends BaseAdminController
// If no input for expirationDate, now + 2 months
$defaultDate = new \DateTime();
$args['defaultDate'] = $defaultDate->modify('+2 month')
->format($lang->getDateFormat());
->format('Y-m-d');
}
$args['formAction'] = 'admin/coupon/create';
$args['dateFormat'] = $this->getSession()->getLang()->getDateFormat();
$args['availableCoupons'] = $this->getAvailableCoupons();
$args['formAction'] = 'admin/coupon/create/';
return $this->render(
'coupon-create',
@@ -135,7 +186,7 @@ class CouponController extends BaseAdminController
}
/** @var Coupon $coupon */
$coupon = CouponQuery::create()->findOneById($couponId);
$coupon = CouponQuery::create()->findPk($couponId);
if (!$coupon) {
$this->pageNotFound();
}
@@ -148,6 +199,7 @@ class CouponController extends BaseAdminController
$lang = $this->getSession()->getLang();
$eventToDispatch = TheliaEvents::COUPON_UPDATE;
// Create
if ($this->getRequest()->isMethod('POST')) {
$this->validateCreateOrUpdateForm(
$i18n,
@@ -156,9 +208,9 @@ class CouponController extends BaseAdminController
'updated',
'update'
);
} else {
// Prepare the data that will hydrate the form
} else { // Update
// Prepare the data that will hydrate the form
/** @var ConstraintFactory $constraintFactory */
$constraintFactory = $this->container->get('thelia.constraint.factory');
$rules = $constraintFactory->unserializeCouponRuleCollection(
@@ -173,7 +225,7 @@ class CouponController extends BaseAdminController
'shortDescription' => $coupon->getShortDescription(),
'description' => $coupon->getDescription(),
'isEnabled' => ($coupon->getIsEnabled() == 1),
'expirationDate' => $coupon->getExpirationDate($lang->getDateFormat()),
'expirationDate' => $coupon->getExpirationDate('Y-m-d'),
'isAvailableOnSpecialOffers' => ($coupon->getIsAvailableOnSpecialOffers() == 1),
'isCumulative' => ($coupon->getIsCumulative() == 1),
'isRemovingPostage' => ($coupon->getIsRemovingPostage() == 1),
@@ -202,7 +254,7 @@ class CouponController extends BaseAdminController
// Pass it to the parser
$this->getParserContext()->addForm($changeForm);
}
$args['couponCode'] = $coupon->getCode();
$args['availableCoupons'] = $this->getAvailableCoupons();
$args['availableRules'] = $this->getAvailableRules();
$args['urlAjaxGetRuleInput'] = $this->getRoute(
@@ -222,123 +274,6 @@ class CouponController extends BaseAdminController
return $this->render('coupon-update', $args);
}
// /**
// * Manage Coupons Rule creation display
// *
// * @param int $couponId Coupon id
// *
// * @return \Symfony\Component\HttpFoundation\Response
// */
// public function createRuleAction($couponId)
// {
// // Check current user authorization
// $response = $this->checkAuth('admin.coupon.update');
// if ($response !== null) {
// return $response;
// }
//
// /** @var Coupon $coupon */
// $coupon = CouponQuery::create()->findOneById($couponId);
// if (!$coupon) {
// $this->pageNotFound();
// }
//
// // Parameters given to the template
// $args = array();
//
// $i18n = new I18n();
// /** @var Lang $lang */
// $lang = $this->getSession()->get('lang');
// $eventToDispatch = TheliaEvents::COUPON_RULE_CREATE;
//
// if ($this->getRequest()->isMethod('POST')) {
// $this->validateCreateOrUpdateForm(
// $i18n,
// $lang,
// $eventToDispatch,
// 'updated',
// 'update'
// );
// } else {
// // Prepare the data that will hydrate the form
//
// /** @var ConstraintFactory $constraintFactory */
// $constraintFactory = $this->container->get('thelia.constraint.factory');
//
// $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' => $constraintFactory->unserializeCouponRuleCollection($coupon->getSerializedRules()),
// 'locale' => $coupon->getLocale(),
// );
//
// /** @var CouponAdapterInterface $adapter */
// $adapter = $this->container->get('thelia.adapter');
// /** @var Translator $translator */
// $translator = $this->container->get('thelia.translator');
//
// $args['rulesObject'] = array();
// /** @var CouponRuleInterface $rule */
// foreach ($coupon->getRules()->getRules() as $rule) {
// $args['rulesObject'][] = array(
// 'name' => $rule->getName($translator),
// 'tooltip' => $rule->getToolTip($translator),
// 'validators' => $rule->getValidators()
// );
// }
//
// $args['rules'] = $this->cleanRuleForTemplate($coupon->getRules()->getRules());
//
// // 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
// );
// }
/**
* Manage Coupons read display
*
* @param int $couponId Coupon Id
*
* @return \Symfony\Component\HttpFoundation\Response
*/
public function readAction($couponId)
{
$this->checkAuth('ADMIN', 'admin.coupon.read');
// Database request repeated in the loop but cached
$search = CouponQuery::create();
$coupon = $search->findOneById($couponId);
if ($coupon === null) {
return $this->pageNotFound();
}
return $this->render('coupon-read', array('couponId' => $couponId));
}
/**
* Manage Coupons read display
*
@@ -350,17 +285,7 @@ class CouponController extends BaseAdminController
{
$this->checkAuth('ADMIN', 'admin.coupon.read');
if ($this->isDebug()) {
if (!$this->getRequest()->isXmlHttpRequest()) {
$this->redirect(
$this->getRoute(
'admin',
array(),
Router::ABSOLUTE_URL
)
);
}
}
$this->checkXmlHttpRequest();
/** @var ConstraintFactory $constraintFactory */
$constraintFactory = $this->container->get('thelia.constraint.factory');
@@ -391,17 +316,7 @@ class CouponController extends BaseAdminController
{
$this->checkAuth('ADMIN', 'admin.coupon.read');
if ($this->isDebug()) {
if (!$this->getRequest()->isXmlHttpRequest()) {
$this->redirect(
$this->getRoute(
'admin',
array(),
Router::ABSOLUTE_URL
)
);
}
}
$this->checkXmlHttpRequest();
$search = CouponQuery::create();
/** @var Coupon $coupon */
@@ -475,6 +390,29 @@ class CouponController extends BaseAdminController
);
}
/**
* Test Coupon consuming
*
* @param string $couponCode Coupon code
*
*/
public function consumeAction($couponCode)
{
// @todo remove (event dispatcher testing purpose)
$couponConsumeEvent = new CouponConsumeEvent($couponCode);
$eventToDispatch = TheliaEvents::COUPON_CONSUME;
// Dispatch Event to the Action
$this->dispatch(
$eventToDispatch,
$couponConsumeEvent
);
var_dump('test', $couponConsumeEvent->getCode(), $couponConsumeEvent->getDiscount(), $couponConsumeEvent->getIsValid());
exit();
}
/**
* Build a Coupon from its form
*
@@ -535,7 +473,7 @@ class CouponController extends BaseAdminController
/**
* Validate the CreateOrUpdate form
*
* @param string $i18n Local code (fr_FR)
* @param I18n $i18n Local code (fr_FR)
* @param Lang $lang Local variables container
* @param string $eventToDispatch Event which will activate actions
* @param string $log created|edited
@@ -543,7 +481,7 @@ class CouponController extends BaseAdminController
*
* @return $this
*/
protected function validateCreateOrUpdateForm($i18n, $lang, $eventToDispatch, $log, $action)
protected function validateCreateOrUpdateForm(I18n $i18n, Lang $lang, $eventToDispatch, $log, $action)
{
// Create the form from the request
$creationForm = new CouponCreationForm($this->getRequest());
@@ -563,7 +501,7 @@ class CouponController extends BaseAdminController
$data['shortDescription'],
$data['description'],
$data['isEnabled'],
$i18n->getDateTimeFromForm($lang, $data['expirationDate']),
\DateTime::createFromFormat('Y-m-d', $data['expirationDate']),
$data['isAvailableOnSpecialOffers'],
$data['isCumulative'],
$data['isRemovingPostage'],
@@ -651,17 +589,17 @@ class CouponController extends BaseAdminController
/** @var CouponManager $couponManager */
$couponManager = $this->container->get('thelia.coupon.manager');
$availableCoupons = $couponManager->getAvailableCoupons();
$cleanedRules = array();
$cleanedCoupons = array();
/** @var CouponInterface $availableCoupon */
foreach ($availableCoupons as $availableCoupon) {
$rule = array();
$rule['serviceId'] = $availableCoupon->getServiceId();
$rule['name'] = $availableCoupon->getName();
$rule['toolTip'] = $availableCoupon->getToolTip();
$cleanedRules[] = $rule;
$cleanedCoupons[] = $rule;
}
return $cleanedRules;
return $cleanedCoupons;
}
/**

View File

@@ -127,7 +127,7 @@ class BaseController extends ContainerAware
/**
* Returns the session from the current request
*
* @return \Symfony\Component\HttpFoundation\Session\SessionInterface
* @return \Thelia\Core\HttpFoundation\Session\Session
*/
protected function getSession()
{

View File

@@ -22,6 +22,8 @@
/**********************************************************************************/
namespace Thelia\Core\Event\Coupon;
use Thelia\Core\Event\ActionEvent;
use Thelia\Coupon\CouponRuleCollection;
use Thelia\Model\Coupon;
/**
@@ -29,75 +31,112 @@ use Thelia\Model\Coupon;
* Date: 8/29/13
* Time: 3:45 PM
*
* Occurring when a Coupon is disabled
* Occurring when a Coupon is consumed
*
* @package Coupon
* @author Guillaume MOREL <gmorel@openstudio.fr>
*
*/
class CouponDisableEvent extends ActionEvent
class CouponConsumeEvent extends ActionEvent
{
/** @var int Coupon id */
protected $couponId;
/** @var string Coupon code */
protected $code = null;
/** @var Coupon Coupon being disabled */
protected $disabledCoupon;
/** @var float Total discount given by this coupon */
protected $discount = 0;
/** @var bool If Coupon is valid or if Customer meets coupon conditions */
protected $isValid = null;
/**
* Constructor
*
* @param int $id Coupon Id
* @param string $code Coupon code
* @param float $discount Total discount given by this coupon
* @param bool $isValid If Coupon is valid or
* if Customer meets coupon conditions
*/
public function __construct($id)
function __construct($code, $discount = null, $isValid = null)
{
$this->id = $id;
$this->code = $code;
$this->discount = $discount;
$this->isValid = $isValid;
}
/**
* Get Coupon id
* Set Coupon code
*
* @return int
*/
public function getId()
{
return $this->id;
}
/**
* Set Coupon id
*
* @param int $id Coupon id
* @param string $code Coupon code
*
* @return $this
*/
public function setId($id)
public function setCode($code)
{
$this->id = $id;
$this->code = $code;
return $this;
}
/**
* Get Coupon being disabled
* Get Coupon code
*
* @return Coupon
* @return string
*/
public function getDisabledCoupon()
public function getCode()
{
return $this->disabledCoupon;
return $this->code;
}
/**
* Set Coupon to be disabled
* Set total discount given by this coupon
*
* @param Coupon $disabledCoupon Coupon to disable
* @param float $discount Total discount given by this coupon
*
* @return $this
*/
public function setDisabledCoupon(Coupon $disabledCoupon)
public function setDiscount($discount)
{
$this->disabledCoupon = $disabledCoupon;
$this->discount = $discount;
return $this;
}
/**
* Get total discount given by this coupon
*
* @return float
*/
public function getDiscount()
{
return $this->discount;
}
/**
* Set if Coupon is valid or if Customer meets coupon conditions
*
* @param boolean $isValid if Coupon is valid or
* if Customer meets coupon conditions
*
* @return $this
*/
public function setIsValid($isValid)
{
$this->isValid = $isValid;
return $this;
}
/**
* Get if Coupon is valid or if Customer meets coupon conditions
*
* @return boolean
*/
public function getIsValid()
{
return $this->isValid;
}
}

View File

@@ -1,103 +0,0 @@
<?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\Coupon;
use Thelia\Model\Coupon;
/**
* Created by JetBrains PhpStorm.
* Date: 8/29/13
* Time: 3:45 PM
*
* Occurring when a Coupon is enabled
*
* @package Coupon
* @author Guillaume MOREL <gmorel@openstudio.fr>
*
*/
class CouponEnableEvent extends ActionEvent
{
/** @var int Coupon id */
protected $couponId;
/** @var Coupon Coupon being enabled */
protected $enabledCoupon;
/**
* Constructor
*
* @param int $id Coupon Id
*/
public function __construct($id)
{
$this->id = $id;
}
/**
* Get Coupon id
*
* @return int
*/
public function getId()
{
return $this->id;
}
/**
* Set Coupon id
*
* @param int $id Coupon id
*
* @return $this
*/
public function setId($id)
{
$this->id = $id;
return $this;
}
/**
* Get Coupon being enabled
*
* @return Coupon
*/
public function getEnabledCoupon()
{
return $this->enabledCoupon;
}
/**
* Set Coupon to be enabled
*
* @param Coupon $enabledCoupon Coupon to enabled
*
* @return $this
*/
public function setEnabledCoupon(Coupon $enabledCoupon)
{
$this->enabledCoupon = $enabledCoupon;
return $this;
}
}

View File

@@ -258,36 +258,6 @@ final class TheliaEvents
*/
const AFTER_UPDATE_COUPON = "action.after_update_coupon";
/**
* Sent when disabling a Coupon
*/
const COUPON_DISABLE = "action.disable_coupon";
/**
* Sent just before a successful disable of a new Coupon in the database.
*/
const BEFORE_DISABLE_COUPON = "action.before_disable_coupon";
/**
* Sent just after a successful disable of a new Coupon in the database.
*/
const AFTER_DISABLE_COUPON = "action.after_disable_coupon";
/**
* Sent when enabling a Coupon
*/
const COUPON_ENABLE = "action.enable_coupon";
/**
* Sent just before a successful enable of a new Coupon in the database.
*/
const BEFORE_ENABLE_COUPON = "action.before_enable_coupon";
/**
* Sent just after a successful enable of a new Coupon in the database.
*/
const AFTER_ENABLE_COUPON = "action.after_enable_coupon";
/**
* Sent when attempting to use a Coupon
*/

View File

@@ -55,4 +55,15 @@ class Request extends BaseRequest
return $uri . $additionalQs;
}
/**
* Gets the Session.
*
* @return \Thelia\Core\HttpFoundation\Session\Session The session
* @api
*/
public function getSession()
{
return parent::getSession();
}
}

View File

@@ -220,4 +220,29 @@ class Session extends BaseSession
{
return $this->get("thelia.delivery_id");
}
/**
* Set consumed coupons by the Customer
*
* @param array $couponsCode An array of Coupon code
*
* @return $this
*/
public function setConsumedCoupons(array $couponsCode)
{
$this->set('thelia.consumed_coupons', $couponsCode);
return $this;
}
/**
* Get Customer consumed coupons
*
* @return array $couponsCode An array of Coupon code
*/
public function getConsumedCoupons()
{
return $this->get('thelia.consumed_coupons');
}
}

View File

@@ -24,6 +24,7 @@
namespace Thelia\Core\Template\Loop;
use Propel\Runtime\ActiveQuery\Criteria;
use Propel\Runtime\Util\PropelModelPager;
use Thelia\Constraint\ConstraintFactory;
use Thelia\Constraint\Rule\CouponRuleInterface;
use Thelia\Core\HttpFoundation\Request;
@@ -34,9 +35,11 @@ use Thelia\Core\Template\Element\LoopResultRow;
use Thelia\Core\Template\Loop\Argument\ArgumentCollection;
use Thelia\Core\Template\Loop\Argument\Argument;
use Thelia\Coupon\Type\CouponInterface;
use Thelia\Model\CouponQuery;
use Thelia\Model\Coupon as MCoupon;
use Thelia\Type;
use Thelia\Type\BooleanOrBothType;
/**
* Created by JetBrains PhpStorm.
@@ -52,17 +55,22 @@ use Thelia\Type;
class Coupon extends BaseI18nLoop
{
/**
* Define all args used in your loop
*
* @return ArgumentCollection
*/
protected function getArgDefinitions()
{
return new ArgumentCollection(
Argument::createIntListTypeArgument('id')
Argument::createIntListTypeArgument('id'),
Argument::createBooleanOrBothTypeArgument('is_enabled', 1)
);
}
/**
* @param $pagination
* Execute Loop
*
* @param PropelModelPager $pagination
*
* @return \Thelia\Core\Template\Element\LoopResult
*/
@@ -74,11 +82,16 @@ class Coupon extends BaseI18nLoop
$locale = $this->configureI18nProcessing($search, array('TITLE', 'DESCRIPTION', 'SHORT_DESCRIPTION'));
$id = $this->getId();
$isEnabled = $this->getIsEnabled();
if (null !== $id) {
$search->filterById($id, Criteria::IN);
}
if ($isEnabled != BooleanOrBothType::ANY) {
$search->filterByIsEnabled($isEnabled ? 1 : 0);
}
// Perform search
$coupons = $this->search($search, $pagination);
@@ -98,9 +111,30 @@ class Coupon extends BaseI18nLoop
$coupon->getSerializedRules()
);
/** @var CouponInterface $couponManager */
$couponManager = $this->container->get($coupon->getType());
$couponManager->set(
$this->container->get('thelia.adapter'),
$coupon->getCode(),
$coupon->getTitle(),
$coupon->getShortDescription(),
$coupon->getDescription(),
$coupon->getAmount(),
$coupon->getIsCumulative(),
$coupon->getIsRemovingPostage(),
$coupon->getIsAvailableOnSpecialOffers(),
$coupon->getIsEnabled(),
$coupon->getMaxUsage(),
$coupon->getExpirationDate()
);
$now = time();
$datediff = $coupon->getExpirationDate()->getTimestamp() - $now;
$daysLeftBeforeExpiration = floor($datediff/(60*60*24));
$cleanedRules = array();
/** @var CouponRuleInterface $rule */
foreach ($rules->getRules() as $key => $rule) {
foreach ($rules->getRules() as $rule) {
$cleanedRules[] = $rule->getToolTip();
}
$loopResultRow->set("ID", $coupon->getId())
@@ -114,9 +148,13 @@ class Coupon extends BaseI18nLoop
->set("USAGE_LEFT", $coupon->getMaxUsage())
->set("IS_CUMULATIVE", $coupon->getIsCumulative())
->set("IS_REMOVING_POSTAGE", $coupon->getIsRemovingPostage())
->set("IS_AVAILABLE_ON_SPECIAL_OFFERS", $coupon->getIsAvailableOnSpecialOffers())
->set("IS_ENABLED", $coupon->getIsEnabled())
->set("AMOUNT", $coupon->getAmount())
->set("APPLICATION_CONDITIONS", $cleanedRules);
->set("APPLICATION_CONDITIONS", $cleanedRules)
->set("TOOLTIP", $couponManager->getToolTip())
->set("DAY_LEFT_BEFORE_EXPIRATION", $daysLeftBeforeExpiration)
->set("SERVICE_ID", $couponManager->getServiceId());
$loopResult->addRow($loopResultRow);
}

View File

@@ -155,4 +155,18 @@ interface CouponAdapterInterface
*/
public function getMainCurrency();
/**
* Return request
*
* @return Request
*/
public function getRequest();
/**
* Return Constraint Validator
*
* @return ConstraintValidator
*/
public function getConstraintValidator();
}

View File

@@ -27,9 +27,14 @@ use Symfony\Component\DependencyInjection\Container;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\Translation\Translator;
use Symfony\Component\Translation\TranslatorInterface;
use Thelia\Constraint\ConstraintValidator;
use Thelia\Core\HttpFoundation\Request;
use Thelia\Core\Security\SecurityContext;
use Thelia\Coupon\Type\CouponInterface;
use Thelia\Model\Coupon;
use Thelia\Model\CouponQuery;
use Thelia\Cart\CartTrait;
use Thelia\Model\Currency;
/**
* Created by JetBrains PhpStorm.
@@ -43,6 +48,10 @@ use Thelia\Model\CouponQuery;
*/
class CouponBaseAdapter implements CouponAdapterInterface
{
use CartTrait {
CartTrait::getCart as getCartFromTrait;
}
/** @var ContainerInterface Service Container */
protected $container = null;
@@ -66,7 +75,7 @@ class CouponBaseAdapter implements CouponAdapterInterface
*/
public function getCart()
{
// TODO: Implement getCart() method.
return $this->getCartFromTrait($this->getRequest());
}
/**
@@ -86,7 +95,7 @@ class CouponBaseAdapter implements CouponAdapterInterface
*/
public function getCustomer()
{
// TODO: Implement getCustomer() method.
return $this->container->get('thelia.securityContext')->getCustomerUser();
}
/**
@@ -122,11 +131,11 @@ class CouponBaseAdapter implements CouponAdapterInterface
/**
* Return the Checkout currency EUR|USD
*
* @return string
* @return Currency
*/
public function getCheckoutCurrency()
{
// TODO: Implement getCheckoutCurrency() method.
$this->getRequest()->getSession()->getCurrency();
}
@@ -147,9 +156,14 @@ class CouponBaseAdapter implements CouponAdapterInterface
*/
public function getCurrentCoupons()
{
// @todo implement
// $consumedCoupons = $this->getRequest()->getSession()->getConsumedCoupons();
// @todo convert coupon code to coupon Interface
$couponFactory = $this->container->get('thelia.coupon.factory');
// @todo Get from Session
// @todo get from cart
$couponCodes = array('XMAS', 'SPRINGBREAK');
$coupons = array();
@@ -208,7 +222,7 @@ class CouponBaseAdapter implements CouponAdapterInterface
*/
public function getContainer()
{
// TODO: Implement getContainer() method.
return $this->container;
}
/**
@@ -232,4 +246,24 @@ class CouponBaseAdapter implements CouponAdapterInterface
{
// TODO: Implement getMainCurrency() method.
}
/**
* Return request
*
* @return Request
*/
public function getRequest()
{
return $this->container->get('request');
}
/**
* Return Constraint Validator
*
* @return ConstraintValidator
*/
public function getConstraintValidator()
{
return $this->container->get('thelia.constraint.validator');
}
}

View File

@@ -183,6 +183,7 @@ class CouponManager
$discount = 0.00;
/** @var CouponInterface $coupon */
foreach ($coupons as $coupon) {
// @todo modify Cart with discount for each cart item
$discount += $coupon->getDiscount($this->adapter);
}

View File

@@ -26,6 +26,7 @@ namespace Thelia\Coupon\Type;
use Symfony\Component\Intl\Exception\NotImplementedException;
use Thelia\Constraint\ConstraintManager;
use Thelia\Constraint\ConstraintValidator;
use Thelia\Core\Translation\Translator;
use Thelia\Coupon\CouponAdapterInterface;
use Thelia\Coupon\CouponRuleCollection;
use Thelia\Coupon\RuleOrganizerInterface;
@@ -44,9 +45,6 @@ use Thelia\Exception\InvalidRuleException;
*/
abstract class CouponAbstract implements CouponInterface
{
/** @var string Service Id */
protected $serviceId = null;
/** @var CouponAdapterInterface Provide necessary value from Thelia */
protected $adapter = null;
@@ -62,9 +60,19 @@ abstract class CouponAbstract implements CouponInterface
/** @var ConstraintValidator Constraint validator */
protected $constraintValidator = null;
/** @var string Service Id */
protected $serviceId = null;
/** @var float Amount that will be removed from the Checkout (Coupon Effect) */
protected $amount = 0;
/** @var string Coupon code (ex: XMAS) */
protected $code = null;
/** @var string Coupon title (ex: Coupon for XMAS) */
protected $title = null;
@@ -74,6 +82,8 @@ abstract class CouponAbstract implements CouponInterface
/** @var string Coupon description */
protected $description = null;
/** @var bool if Coupon is enabled */
protected $isEnabled = false;
@@ -86,9 +96,6 @@ abstract class CouponAbstract implements CouponInterface
/** @var bool if Coupon is removing postage */
protected $isRemovingPostage = false;
/** @var float Amount that will be removed from the Checkout (Coupon Effect) */
protected $amount = 0;
/** @var int Max time a Coupon can be used (-1 = unlimited) */
protected $maxUsage = -1;
@@ -105,6 +112,7 @@ abstract class CouponAbstract implements CouponInterface
{
$this->adapter = $adapter;
$this->translator = $adapter->getTranslator();
$this->constraintValidator = $adapter->getConstraintValidator();
}
/**
@@ -220,17 +228,6 @@ abstract class CouponAbstract implements CouponInterface
return $this;
}
/**
* Check if the current Coupon is matching its conditions (Rules)
* Thelia variables are given by the CouponAdapterInterface
*
* @return bool
*/
public function isMatching()
{
return $this->constraintValidator->test($this->rules);
}
/**
* Return Coupon expiration date
*
@@ -302,4 +299,16 @@ abstract class CouponAbstract implements CouponInterface
}
/**
* Check if the current Coupon is matching its conditions (Rules)
* Thelia variables are given by the CouponAdapterInterface
*
* @return bool
*/
public function isMatching()
{
return $this->constraintValidator->isMatching($this->rules);
}
}

View File

@@ -39,6 +39,27 @@ use Thelia\Coupon\CouponRuleCollection;
*/
interface CouponInterface
{
/**
* Get I18n name
*
* @return string
*/
public function getName();
/**
* Get I18n tooltip
*
* @return string
*/
public function getToolTip();
/**
* Get Coupon Manager service Id
*
* @return string
*/
public function getServiceId();
/**
* Set Coupon
*
@@ -114,18 +135,7 @@ interface CouponInterface
*/
public function isRemovingPostage();
/**
* Return effects generated by the coupon
* A positive value
*
* Effects could also affect something else than the final Checkout price
* CouponAdapter $adapter could be use to directly pass a Session value
* some would wish to modify
* Hence affecting a wide variety of Thelia elements
*
* @return float Amount removed from the Total Checkout
*/
public function getDiscount();
/**
* Return condition to validate the Coupon or not
@@ -134,14 +144,6 @@ interface CouponInterface
*/
public function getRules();
/**
* Check if the current Coupon is matching its conditions (Rules)
* Thelia variables are given by the CouponAdapterInterface
*
* @return bool
*/
public function isMatching();
/**
* Replace the existing Rules by those given in parameter
* If one Rule is badly implemented, no Rule will be added
@@ -191,25 +193,26 @@ interface CouponInterface
*/
public function isExpired();
/**
* Get I18n name
*
* @return string
*/
public function getName();
/**
* Get I18n tooltip
* Return effects generated by the coupon
* A positive value
*
* @return string
* Effects could also affect something else than the final Checkout price
* CouponAdapter $adapter could be use to directly pass a Session value
* some would wish to modify
* Hence affecting a wide variety of Thelia elements
*
* @return float Amount removed from the Total Checkout
*/
public function getToolTip();
public function getDiscount();
/**
* Get Coupon Manager service Id
* Check if the current Coupon is matching its conditions (Rules)
* Thelia variables are given by the CouponAdapterInterface
*
* @return string
* @return bool
*/
public function getServiceId();
public function isMatching();
}

View File

@@ -23,7 +23,11 @@
namespace Thelia\Form;
use Symfony\Component\Validator\Constraints\Date;
use Symfony\Component\Validator\Constraints\DateTime;
use Symfony\Component\Validator\Constraints\GreaterThanOrEqual;
use Symfony\Component\Validator\Constraints\NotBlank;
use Symfony\Component\Validator\Constraints\NotEqualTo;
/**
* Created by JetBrains PhpStorm.
@@ -68,7 +72,6 @@ class CouponCreationForm extends BaseForm
'shortDescription',
'text',
array(
'invalid_message' => 'test',
'constraints' => array(
new NotBlank()
)
@@ -78,7 +81,6 @@ class CouponCreationForm extends BaseForm
'description',
'textarea',
array(
'invalid_message' => 'test',
'constraints' => array(
new NotBlank()
)
@@ -88,16 +90,23 @@ class CouponCreationForm extends BaseForm
'effect',
'text',
array(
'invalid_message' => 'test',
'constraints' => array(
new NotBlank()
new NotBlank(),
new NotEqualTo(
array(
'value' => -1
)
)
)
)
)
->add(
'amount',
'money',
array()
array(
'constraints' => array(
new NotBlank()
))
)
->add(
'isEnabled',
@@ -109,7 +118,8 @@ class CouponCreationForm extends BaseForm
'text',
array(
'constraints' => array(
new NotBlank()
new NotBlank(),
new Date()
)
)
)
@@ -133,7 +143,12 @@ class CouponCreationForm extends BaseForm
'text',
array(
'constraints' => array(
new NotBlank()
new NotBlank(),
new GreaterThanOrEqual(
array(
'value' => -1
)
)
)
)
)

View File

@@ -76,7 +76,6 @@ class Coupon extends BaseCoupon
->setType($effect)
->setAmount($amount)
->setIsRemovingPostage($isRemovingPostage)
->setType($amount)
->setIsEnabled($isEnabled)
->setExpirationDate($expirationDate)
->setIsAvailableOnSpecialOffers($isAvailableOnSpecialOffers)

View File

@@ -79,7 +79,7 @@ class ConstraintValidatorTest extends \PHPUnit_Framework_TestCase
$rules = new CouponRuleCollection();
$rules->add($rule1);
$isValid = $ConstraintValidator->test($rules);
$isValid = $ConstraintValidator->isMatching($rules);
$expected = true;
$actual =$isValid;
@@ -113,7 +113,7 @@ class ConstraintValidatorTest extends \PHPUnit_Framework_TestCase
$rules = new CouponRuleCollection();
$rules->add($rule1);
$isValid = $ConstraintValidator->test($rules);
$isValid = $ConstraintValidator->isMatching($rules);
$expected = false;
$actual =$isValid;
@@ -160,7 +160,7 @@ class ConstraintValidatorTest extends \PHPUnit_Framework_TestCase
$rules->add($rule1);
$rules->add($rule2);
$isValid = $ConstraintValidator->test($rules);
$isValid = $ConstraintValidator->isMatching($rules);
$expected = true;
$actual =$isValid;
@@ -207,7 +207,7 @@ class ConstraintValidatorTest extends \PHPUnit_Framework_TestCase
$rules->add($rule1);
$rules->add($rule2);
$isValid = $ConstraintValidator->test($rules);
$isValid = $ConstraintValidator->isMatching($rules);
$expected = false;
$actual =$isValid;