Merge with master

This commit is contained in:
touffies
2013-10-24 16:52:03 +02:00
741 changed files with 169402 additions and 4971 deletions

View File

@@ -0,0 +1,201 @@
<?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\Security\AccessManager;
use Thelia\Core\Security\Resource\AdminResources;
use Thelia\Core\Event\Administrator\AdministratorEvent;
use Thelia\Core\Event\TheliaEvents;
use Thelia\Form\AdministratorCreationForm;
use Thelia\Form\AdministratorModificationForm;
use Thelia\Model\AdminQuery;
class AdministratorController extends AbstractCrudController
{
public function __construct()
{
parent::__construct(
'administrator',
'manual',
'order',
AdminResources::ADMINISTRATOR,
TheliaEvents::ADMINISTRATOR_CREATE,
TheliaEvents::ADMINISTRATOR_UPDATE,
TheliaEvents::ADMINISTRATOR_DELETE
);
}
protected function getCreationForm()
{
return new AdministratorCreationForm($this->getRequest());
}
protected function getUpdateForm()
{
return new AdministratorModificationForm($this->getRequest());
}
protected function getCreationEvent($formData)
{
$event = new AdministratorEvent();
$event->setLogin($formData['login']);
$event->setFirstname($formData['firstname']);
$event->setLastname($formData['lastname']);
$event->setPassword($formData['password']);
$event->setProfile($formData['profile'] ? : null);
return $event;
}
protected function getUpdateEvent($formData)
{
$event = new AdministratorEvent();
$event->setId($formData['id']);
$event->setLogin($formData['login']);
$event->setFirstname($formData['firstname']);
$event->setLastname($formData['lastname']);
$event->setPassword($formData['password']);
$event->setProfile($formData['profile'] ? : null);
return $event;
}
protected function getDeleteEvent()
{
$event = new AdministratorEvent();
$event->setId(
$this->getRequest()->get('administrator_id', 0)
);
return $event;
}
protected function eventContainsObject($event)
{
return $event->hasAdministrator();
}
protected function hydrateObjectForm($object)
{
$data = array(
'id' => $object->getId(),
'firstname' => $object->getFirstname(),
'lastname' => $object->getLastname(),
'login' => $object->getLogin(),
'profile' => $object->getProfileId(),
);
// Setup the object form
return new AdministratorModificationForm($this->getRequest(), "form", $data);
}
protected function hydrateResourceUpdateForm($object)
{
$data = array(
'id' => $object->getId(),
);
// Setup the object form
return new AdministratorUpdateResourceAccessForm($this->getRequest(), "form", $data);
}
protected function hydrateModuleUpdateForm($object)
{
$data = array(
'id' => $object->getId(),
);
// Setup the object form
return new AdministratorUpdateModuleAccessForm($this->getRequest(), "form", $data);
}
protected function getObjectFromEvent($event)
{
return $event->hasAdministrator() ? $event->getAdministrator() : null;
}
protected function getExistingObject()
{
return AdminQuery::create()
->joinWithI18n($this->getCurrentEditionLocale())
->findOneById($this->getRequest()->get('administrator_id'));
}
protected function getObjectLabel($object)
{
return $object->getLogin();
}
protected function getObjectId($object)
{
return $object->getId();
}
protected function renderListTemplate($currentOrder)
{
// We always return to the feature edition form
return $this->render(
'administrators',
array()
);
}
protected function renderEditionTemplate()
{
// We always return to the feature edition form
return $this->render('administrators');
}
protected function redirectToEditionTemplate()
{
// We always return to the feature edition form
$this->redirectToListTemplate();
}
protected function performAdditionalCreateAction($updateEvent)
{
// We always return to the feature edition form
$this->redirectToListTemplate();
}
protected function performAdditionalUpdateAction($updateEvent)
{
// We always return to the feature edition form
$this->redirectToListTemplate();
}
protected function redirectToListTemplate()
{
$this->redirectToRoute(
"admin.configuration.administrators.view"
);
}
}

View File

@@ -97,14 +97,17 @@ class BaseAdminController extends BaseController
*
* @return \Symfony\Component\HttpFoundation\Response
*/
protected function errorPage($message)
protected function errorPage($message, $status = 500)
{
if ($message instanceof \Exception) {
$message = $this->getTranslator()->trans("Sorry, an error occured: %msg", array('%msg' => $message->getMessage()));
}
return $this->render('general_error', array(
"error_message" => $message)
return $this->render('general_error',
array(
"error_message" => $message
),
$status
);
}
@@ -128,12 +131,12 @@ class BaseAdminController extends BaseController
}
// Log the problem
$this->adminLogAppend("User is not granted for permissions %s", implode(", ", $permArr));
$this->adminLogAppend("User is not granted for resources %s with accesses %s", implode(", ", $resources), implode(", ", $accesses));
// Generate the proper response
$response = new Response();
return $this->errorPage($this->getTranslator()->trans("Sorry, you're not allowed to perform this action"));
return $this->errorPage($this->getTranslator()->trans("Sorry, you're not allowed to perform this action"), 403);
}
/*
@@ -366,14 +369,13 @@ class BaseAdminController extends BaseController
* Render the given template, and returns the result as an Http Response.
*
* @param $templateName the complete template name, with extension
* @param array $args the template arguments
* @param array $args the template arguments
* @param int $status http code status
* @return \Symfony\Component\HttpFoundation\Response
*/
protected function render($templateName, $args = array())
protected function render($templateName, $args = array(), $status = 200)
{
$response = new Response();
return $response->setContent($this->renderRaw($templateName, $args));
return Response::create($this->renderRaw($templateName, $args), $status);
}
/**
@@ -430,7 +432,7 @@ class BaseAdminController extends BaseController
Redirect::exec(URL::getInstance()->absoluteUrl($ex->getLoginTemplate()));
} catch (AuthorizationException $ex) {
// User is not allowed to perform the required action. Return the error page instead of the requested page.
return $this->errorPage($this->getTranslator()->trans("Sorry, you are not allowed to perform this action."));
return $this->errorPage($this->getTranslator()->trans("Sorry, you are not allowed to perform this action."), 403);
}
}
}

View File

@@ -251,6 +251,6 @@ class CountryController extends AbstractCrudController
}
return $this->nullResponse($content, 500);
return $this->nullResponse(500);
}
}

View File

@@ -28,8 +28,6 @@ use Symfony\Component\Routing\Router;
use Thelia\Condition\ConditionFactory;
use Thelia\Condition\ConditionManagerInterface;
use Thelia\Core\Security\Resource\AdminResources;
use Thelia\Core\Event\Condition\ConditionCreateOrUpdateEvent;
use Thelia\Core\Event\Coupon\CouponConsumeEvent;
use Thelia\Core\Event\Coupon\CouponCreateOrUpdateEvent;
use Thelia\Core\Event\TheliaEvents;
use Thelia\Core\Security\AccessManager;
@@ -209,10 +207,7 @@ class CouponController extends BaseAdminController
$conditions = $conditionFactory->unserializeConditionCollection(
$coupon->getSerializedConditions()
);
var_dump($coupon->getIsEnabled());;
var_dump($coupon->getIsAvailableOnSpecialOffers());;
var_dump($coupon->getIsCumulative());;
var_dump($coupon->getIsRemovingPostage());;
$data = array(
'code' => $coupon->getCode(),
'title' => $coupon->getTitle(),
@@ -220,11 +215,11 @@ var_dump($coupon->getIsRemovingPostage());;
'type' => $coupon->getType(),
'shortDescription' => $coupon->getShortDescription(),
'description' => $coupon->getDescription(),
'isEnabled' => ($coupon->getIsEnabled() == 1),
'isEnabled' => $coupon->getIsEnabled(),
'expirationDate' => $coupon->getExpirationDate('Y-m-d'),
'isAvailableOnSpecialOffers' => ($coupon->getIsAvailableOnSpecialOffers() == 1),
'isCumulative' => ($coupon->getIsCumulative() == 1),
'isRemovingPostage' => ($coupon->getIsRemovingPostage() == 1),
'isAvailableOnSpecialOffers' => $coupon->getIsAvailableOnSpecialOffers(),
'isCumulative' => $coupon->getIsCumulative(),
'isRemovingPostage' => $coupon->getIsRemovingPostage(),
'maxUsage' => $coupon->getMaxUsage(),
'conditions' => $conditions,
'locale' => $coupon->getLocale(),
@@ -265,7 +260,7 @@ var_dump($coupon->getIsRemovingPostage());;
Router::ABSOLUTE_URL
);
$args['formAction'] = 'admin/coupon/update' . $couponId;
$args['formAction'] = 'admin/coupon/update/' . $couponId;
return $this->render('coupon-update', $args);
}
@@ -335,27 +330,36 @@ var_dump($coupon->getIsRemovingPostage());;
$conditions->add(clone $condition);
}
// $coupon->setSerializedConditions(
// $conditionFactory->serializeCouponConditionCollection($conditions)
// );
$conditionEvent = new ConditionCreateOrUpdateEvent(
$conditions
$couponEvent = new CouponCreateOrUpdateEvent(
$coupon->getCode(),
$coupon->getTitle(),
$coupon->getAmount(),
$coupon->getType(),
$coupon->getShortDescription(),
$coupon->getDescription(),
$coupon->getIsEnabled(),
$coupon->getExpirationDate(),
$coupon->getIsAvailableOnSpecialOffers(),
$coupon->getIsCumulative(),
$coupon->getIsRemovingPostage(),
$coupon->getMaxUsage(),
$coupon->getLocale()
);
$conditionEvent->setCouponModel($coupon);
$couponEvent->setCouponModel($coupon);
$couponEvent->setConditions($conditions);
$eventToDispatch = TheliaEvents::COUPON_CONDITION_UPDATE;
// Dispatch Event to the Action
$this->dispatch(
$eventToDispatch,
$conditionEvent
$couponEvent
);
$this->adminLogAppend(
sprintf(
'Coupon %s (ID %s) conditions updated',
$conditionEvent->getCouponModel()->getTitle(),
$conditionEvent->getCouponModel()->getServiceId()
$couponEvent->getCouponModel()->getTitle(),
$couponEvent->getCouponModel()->getType()
)
);
@@ -372,31 +376,6 @@ var_dump($coupon->getIsRemovingPostage());;
);
}
/**
* Test Coupon consuming
*
* @param string $couponCode Coupon code
*
* @todo remove (event dispatcher testing purpose)
*
*/
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
*
@@ -492,14 +471,14 @@ var_dump($coupon->getIsRemovingPostage());;
sprintf(
'Coupon %s (ID ) ' . $log,
$couponEvent->getTitle(),
$couponEvent->getCoupon()->getId()
$couponEvent->getCouponModel()->getId()
)
);
$this->redirect(
str_replace(
'{id}',
$couponEvent->getCoupon()->getId(),
$couponEvent->getCouponModel()->getId(),
$creationForm->getSuccessUrl()
)
);
@@ -591,26 +570,4 @@ var_dump($coupon->getIsRemovingPostage());;
return $cleanedConditions;
}
// /**
// * Validation Condition creation
// *
// * @param string $type Condition class type
// * @param string $operator Condition operator (<, >, =, etc)
// * @param array $values Condition values
// *
// * @return bool
// */
// protected function validateConditionsCreation($type, $operator, $values)
// {
// /** @var AdapterInterface $adapter */
// $adapter = $this->container->get('thelia.adapter');
// $validator = new PriceParam()
// try {
// $condition = new AvailableForTotalAmount($adapter, $validators);
// $condition = new $type($adapter, $validators);
// } catch (\Exception $e) {
// return false;
// }
// }
}

View File

@@ -48,10 +48,7 @@ class FolderController extends AbstractCrudController
'manual',
'folder_order',
AdminResources::FOLDER_VIEW,
AdminResources::FOLDER_CREATE,
AdminResources::FOLDER_UPDATE,
AdminResources::FOLDER_DELETE,
AdminResources::FOLDER,
TheliaEvents::FOLDER_CREATE,
TheliaEvents::FOLDER_UPDATE,

View File

@@ -0,0 +1,329 @@
<?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 Symfony\Component\Form\Form;
use Thelia\Core\Event\Lang\LangCreateEvent;
use Thelia\Core\Event\Lang\LangDefaultBehaviorEvent;
use Thelia\Core\Event\Lang\LangDeleteEvent;
use Thelia\Core\Event\Lang\LangToggleDefaultEvent;
use Thelia\Core\Event\Lang\LangUpdateEvent;
use Thelia\Core\Event\TheliaEvents;
use Thelia\Core\Security\AccessManager;
use Thelia\Core\Security\Resource\AdminResources;
use Thelia\Form\Exception\FormValidationException;
use Thelia\Form\Lang\LangCreateForm;
use Thelia\Form\Lang\LangDefaultBehaviorForm;
use Thelia\Form\Lang\LangUpdateForm;
use Thelia\Form\Lang\LangUrlEvent;
use Thelia\Form\Lang\LangUrlForm;
use Thelia\Model\ConfigQuery;
use Thelia\Model\LangQuery;
/**
* Class LangController
* @package Thelia\Controller\Admin
* @author Manuel Raynaud <mraynaud@openstudio.fr>
*/
class LangController extends BaseAdminController
{
public function defaultAction()
{
if (null !== $response = $this->checkAuth(AdminResources::LANGUAGE, AccessManager::VIEW)) return $response;
return $this->renderDefault();
}
public function renderDefault(array $param = array())
{
$data = array();
foreach (LangQuery::create()->find() as $lang) {
$data[LangUrlForm::LANG_PREFIX.$lang->getId()] = $lang->getUrl();
}
$langUrlForm = new LangUrlForm($this->getRequest(), 'form', $data);
$this->getParserContext()->addForm($langUrlForm);
return $this->render('languages', array_merge($param, array(
'lang_without_translation' => ConfigQuery::getDefaultLangWhenNoTranslationAvailable(),
'one_domain_per_lang' => ConfigQuery::read("one_domain_foreach_lang", false)
)));
}
public function updateAction($lang_id)
{
if (null !== $response = $this->checkAuth(AdminResources::LANGUAGE, AccessManager::UPDATE)) return $response;
$this->checkXmlHttpRequest();
$lang = LangQuery::create()->findPk($lang_id);
$langForm = new LangUpdateForm($this->getRequest(), 'form', array(
'id' => $lang->getId(),
'title' => $lang->getTitle(),
'code' => $lang->getCode(),
'locale' => $lang->getLocale(),
'date_format' => $lang->getDateFormat(),
'time_format' => $lang->getTimeFormat()
));
$this->getParserContext()->addForm($langForm);
return $this->render('ajax/language-update-modal', array(
'lang_id' => $lang_id
));
}
public function processUpdateAction($lang_id)
{
if (null !== $response = $this->checkAuth(AdminResources::LANGUAGE, AccessManager::UPDATE)) return $response;
$error_msg = false;
$langForm = new LangUpdateForm($this->getRequest());
try {
$form = $this->validateForm($langForm);
$event = new LangUpdateEvent($form->get('id')->getData());
$event = $this->hydrateEvent($event, $form);
$this->dispatch(TheliaEvents::LANG_UPDATE, $event);
if (false === $event->hasLang()) {
throw new \LogicException(
$this->getTranslator()->trans("No %obj was updated.", array('%obj', 'Lang')));
}
$changedObject = $event->getLang();
$this->adminLogAppend(sprintf("%s %s (ID %s) modified", 'Lang', $changedObject->getTitle(), $changedObject->getId()));
$this->redirectToRoute('/admin/configuration/languages');
} catch(\Exception $e) {
$error_msg = $e->getMessage();
}
return $this->renderDefault();
}
protected function hydrateEvent($event,Form $form)
{
return $event
->setTitle($form->get('title')->getData())
->setCode($form->get('code')->getData())
->setLocale($form->get('locale')->getData())
->setDateFormat($form->get('date_format')->getData())
->setTimeFormat($form->get('time_format')->getData())
;
}
public function toggleDefaultAction($lang_id)
{
if (null !== $response = $this->checkAuth(AdminResources::LANGUAGE, AccessManager::UPDATE)) return $response;
$this->checkXmlHttpRequest();
$error = false;
try {
$event = new LangToggleDefaultEvent($lang_id);
$this->dispatch(TheliaEvents::LANG_TOGGLEDEFAULT, $event);
if (false === $event->hasLang()) {
throw new \LogicException(
$this->getTranslator()->trans("No %obj was updated.", array('%obj', 'Lang')));
}
$changedObject = $event->getLang();
$this->adminLogAppend(sprintf("%s %s (ID %s) modified", 'Lang', $changedObject->getTitle(), $changedObject->getId()));
} catch (\Exception $e) {
\Thelia\Log\Tlog::getInstance()->error(sprintf("Error on changing default languages with message : %s", $e->getMessage()));
$error = $e->getMessage();
}
if($error) {
return $this->nullResponse(500);
} else {
return $this->nullResponse();
}
}
public function addAction()
{
if (null !== $response = $this->checkAuth(AdminResources::LANGUAGE, AccessManager::CREATE)) return $response;
$createForm = new LangCreateForm($this->getRequest());
$error_msg = false;
try {
$form = $this->validateForm($createForm);
$createEvent = new LangCreateEvent();
$createEvent = $this->hydrateEvent($createEvent, $form);
$this->dispatch(TheliaEvents::LANG_CREATE, $createEvent);
if (false === $createEvent->hasLang()) {
throw new \LogicException(
$this->getTranslator()->trans("No %obj was updated.", array('%obj', 'Lang')));
}
$createdObject = $createEvent->getLang();
$this->adminLogAppend(sprintf("%s %s (ID %s) created", 'Lang', $createdObject->getTitle(), $createdObject->getId()));
$this->redirectToRoute('admin.configuration.languages');
} 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 creation", array('%obj' => 'Lang')), $error_msg, $createForm, $ex);
// At this point, the form has error, and should be redisplayed.
return $this->renderDefault();
}
public function deleteAction()
{
if (null !== $response = $this->checkAuth(AdminResources::LANGUAGE, AccessManager::DELETE)) return $response;
$error_msg = false;
try {
$deleteEvent = new LangDeleteEvent($this->getRequest()->get('language_id', 0));
$this->dispatch(TheliaEvents::LANG_DELETE, $deleteEvent);
$this->redirectToRoute('admin.configuration.languages');
} catch (\Exception $ex) {
\Thelia\Log\Tlog::getInstance()->error(sprintf("error during language removal with message : %s", $ex->getMessage()));
$error_msg = $ex->getMessage();
}
return $this->renderDefault(array(
'error_delete_message' => $error_msg
));
}
public function defaultBehaviorAction()
{
if (null !== $response = $this->checkAuth(AdminResources::LANGUAGE, AccessManager::UPDATE)) return $response;
$error_msg = false;
$behaviorForm = new LangDefaultBehaviorForm($this->getRequest());
try {
$form = $this->validateForm($behaviorForm);
$event = new LangDefaultBehaviorEvent($form->get('behavior')->getData());
$this->dispatch(TheliaEvents::LANG_DEFAULTBEHAVIOR, $event);
$this->redirectToRoute('admin.configuration.languages');
} 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 creation", array('%obj' => 'Lang')), $error_msg, $behaviorForm, $ex);
// At this point, the form has error, and should be redisplayed.
return $this->renderDefault();
}
public function domainAction()
{
if (null !== $response = $this->checkAuth(AdminResources::LANGUAGE, AccessManager::UPDATE)) return $response;
$error_msg = false;
$langUrlForm = new LangUrlForm($this->getRequest());
try {
$form = $this->validateForm($langUrlForm);
$data = $form->getData();
$event = new LangUrlEvent();
foreach ($data as $key => $value) {
$pos= strpos($key, LangUrlForm::LANG_PREFIX);
if(false !== strpos($key, LangUrlForm::LANG_PREFIX)) {
$event->addUrl(substr($key,strlen(LangUrlForm::LANG_PREFIX)), $value);
}
}
$this->dispatch(TheliaEvents::LANG_URL, $event);
$this->redirectToRoute('admin.configuration.languages');
} 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 creation", array('%obj' => 'Lang')), $error_msg, $langUrlForm, $ex);
// At this point, the form has error, and should be redisplayed.
return $this->renderDefault();
}
public function activateDomainAction()
{
$this->domainActivation(1);
}
public function deactivateDomainAction()
{
$this->domainActivation(0);
}
private function domainActivation($activate)
{
if (null !== $response = $this->checkAuth(AdminResources::LANGUAGE, AccessManager::UPDATE)) return $response;
$error_msg = false;
ConfigQuery::create()
->filterByName('one_domain_foreach_lang')
->update(array('Value' => $activate));
$this->redirectToRoute('admin.configuration.languages');
}
}

View File

@@ -48,6 +48,23 @@ use Thelia\Model\CategoryQuery;
use Thelia\Core\Event\Product\ProductAddAccessoryEvent;
use Thelia\Core\Event\Product\ProductDeleteAccessoryEvent;
use Thelia\Model\ProductSaleElementsQuery;
use Thelia\Core\Event\ProductSaleElement\ProductSaleElementDeleteEvent;
use Thelia\Core\Event\ProductSaleElement\ProductSaleElementUpdateEvent;
use Thelia\Core\Event\ProductSaleElement\ProductSaleElementCreateEvent;
use Thelia\Model\AttributeQuery;
use Thelia\Model\AttributeAvQuery;
use Thelia\Form\ProductSaleElementUpdateForm;
use Thelia\Model\ProductSaleElements;
use Thelia\Model\ProductPriceQuery;
use Thelia\Form\ProductDefaultSaleElementUpdateForm;
use Thelia\Model\ProductPrice;
use Thelia\Model\Currency;
use Symfony\Component\HttpFoundation\JsonResponse;
use Thelia\TaxEngine\Calculator;
use Thelia\Model\Country;
use Thelia\Model\CountryQuery;
use Thelia\Model\TaxRuleQuery;
use Thelia\Tools\NumberFormat;
/**
* Manages products
@@ -172,10 +189,58 @@ class ProductController extends AbstractCrudController
protected function hydrateObjectForm($object)
{
// Get the default produc sales element
$salesElement = ProductSaleElementsQuery::create()->filterByProduct($object)->filterByIsDefault(true)->findOne();
$defaultPseData = $combinationPseData = array();
// $prices = $salesElement->getProductPrices();
// Find product's sale elements
$saleElements = ProductSaleElementsQuery::create()
->filterByProduct($object)
->find();
foreach($saleElements as $saleElement) {
// Get the product price for the current currency
$productPrice = ProductPriceQuery::create()
->filterByCurrency($this->getCurrentEditionCurrency())
->filterByProductSaleElements($saleElement)
->findOne()
;
if ($productPrice == null) $productPrice = new ProductPrice();
$isDefaultPse = count($saleElement->getAttributeCombinations()) == 0;
// If this PSE has no combination -> this is the default one
// affect it to the thelia.admin.product_sale_element.update form
if ($isDefaultPse) {
$defaultPseData = array(
"product_id" => $object->getId(),
"product_sale_element_id" => $saleElement->getId(),
"reference" => $saleElement->getRef(),
"price" => $productPrice->getPrice(),
"use_exchange_rate" => $productPrice->getFromDefaultCurrency() ? 1 : 0,
"tax_rule" => $object->getTaxRuleId(),
"currency" => $productPrice->getCurrencyId(),
"weight" => $saleElement->getWeight(),
"quantity" => $saleElement->getQuantity(),
"sale_price" => $productPrice->getPromoPrice(),
"onsale" => $saleElement->getPromo() > 0 ? 1 : 0,
"isnew" => $saleElement->getNewness() > 0 ? 1 : 0,
"isdefault" => $saleElement->getIsDefault() > 0 ? 1 : 0,
"ean_code" => $saleElement->getEanCode()
);
}
else {
}
$defaultPseForm = new ProductDefaultSaleElementUpdateForm($this->getRequest(), "form", $defaultPseData);
$this->getParserContext()->addForm($defaultPseForm);
$combinationPseForm = new ProductSaleElementUpdateForm($this->getRequest(), "form", $combinationPseData);
$this->getParserContext()->addForm($combinationPseForm);
}
// Prepare the data that will hydrate the form
$data = array(
@@ -226,7 +291,7 @@ class ProductController extends AbstractCrudController
'product_id' => $this->getRequest()->get('product_id', 0),
'folder_id' => $this->getRequest()->get('folder_id', 0),
'accessory_category_id' => $this->getRequest()->get('accessory_category_id', 0),
'current_tab' => $this->getRequest()->get('current_tab', 'general')
'current_tab' => $this->getRequest()->get('current_tab', 'general')
);
}
@@ -730,20 +795,21 @@ class ProductController extends AbstractCrudController
/**
* A a new combination to a product
*/
public function addCombinationAction()
public function addProductSaleElementAction()
{
// Check current user authorization
if (null !== $response = $this->checkAuth($this->resourceCode, AccessManager::UPDATE)) return $response;
$event = new ProductCreateCombinationEvent(
$event = new ProductSaleElementCreateEvent(
$this->getExistingObject(),
$this->getRequest()->get('combination_attributes', array()),
$this->getCurrentEditionCurrency()->getId()
);
try {
$this->dispatch(TheliaEvents::PRODUCT_ADD_COMBINATION, $event);
} catch (\Exception $ex) {
$this->dispatch(TheliaEvents::PRODUCT_ADD_PRODUCT_SALE_ELEMENT, $event);
}
catch (\Exception $ex) {
// Any error
return $this->errorPage($ex);
}
@@ -751,23 +817,23 @@ class ProductController extends AbstractCrudController
$this->redirectToEditionTemplate();
}
/**
* A a new combination to a product
*/
public function deleteCombinationAction()
public function deleteProductSaleElementAction()
{
// Check current user authorization
if (null !== $response = $this->checkAuth($this->resourceCode, AccessManager::UPDATE)) return $response;
$event = new ProductDeleteCombinationEvent(
$this->getExistingObject(),
$this->getRequest()->get('product_sale_element_id',0)
$event = new ProductSaleElementDeleteEvent(
$this->getRequest()->get('product_sale_element_id',0),
$this->getCurrentEditionCurrency()->getId()
);
try {
$this->dispatch(TheliaEvents::PRODUCT_DELETE_COMBINATION, $event);
} catch (\Exception $ex) {
$this->dispatch(TheliaEvents::PRODUCT_DELETE_PRODUCT_SALE_ELEMENT, $event);
}
catch (\Exception $ex) {
// Any error
return $this->errorPage($ex);
}
@@ -775,4 +841,124 @@ class ProductController extends AbstractCrudController
$this->redirectToEditionTemplate();
}
/**
* Change a product sale element
*/
protected function processProductSaleElementUpdate($changeForm) {
// Check current user authorization
if (null !== $response = $this->checkAuth("admin.products.update")) return $response;
$error_msg = false;
try {
// Check the form against constraints violations
$form = $this->validateForm($changeForm, "POST");
// Get the form field values
$data = $form->getData();
$event = new ProductSaleElementUpdateEvent(
$this->getExistingObject(),
$data['product_sale_element_id']
);
$event
->setReference($data['reference'])
->setPrice($data['price'])
->setCurrencyId($data['currency'])
->setWeight($data['weight'])
->setQuantity($data['quantity'])
->setSalePrice($data['sale_price'])
->setOnsale($data['onsale'])
->setIsnew($data['isnew'])
->setIsdefault($data['isdefault'])
->setEanCode($data['ean_code'])
->setTaxrule($data['tax_rule'])
;
$this->dispatch(TheliaEvents::PRODUCT_UPDATE_PRODUCT_SALE_ELEMENT, $event);
// Log object modification
if (null !== $changedObject = $event->getProductSaleElement()) {
$this->adminLogAppend(sprintf("Product Sale Element (ID %s) for product reference %s modified", $changedObject->getId(), $event->getProduct()->getRef()));
}
// If we have to stay on the same page, do not redirect to the succesUrl, just redirect to the edit page again.
if ($this->getRequest()->get('save_mode') == 'stay') {
$this->redirectToEditionTemplate($this->getRequest());
}
// Redirect to the success URL
$this->redirect($changeForm->getSuccessUrl());
}
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("ProductSaleElement modification"), $error_msg, $changeForm, $ex);
// At this point, the form has errors, and should be redisplayed.
return $this->renderEditionTemplate();
}
/**
* Change a product sale element attached to a combination
*/
public function updateProductSaleElementAction() {
return $this->processProductSaleElementUpdate(
new ProductSaleElementUpdateForm($this->getRequest())
);
}
/**
* Update default product sale element (not attached to any combination)
*/
public function updateProductDefaultSaleElementAction() {
return $this->processProductSaleElementUpdate(
new ProductDefaultSaleElementUpdateForm($this->getRequest())
);
}
public function priceCaclulator() {
$price = floatval($this->getRequest()->get('price', 0));
$tax_rule = intval($this->getRequest()->get('tax_rule_id', 0)); // The tax rule ID
$action = $this->getRequest()->get('action', ''); // With ot without tax
$convert = intval($this->getRequest()->get('convert_from_default_currency', 0));
$calc = new Calculator();
$calc->loadTaxRule(
TaxRuleQuery::create()->findPk($tax_rule),
Country::getShopLocation()
);
if ($action == 'to_tax') {
$return_price = $calc->getTaxedPrice($price);
}
else if ($action == 'from_tax') {
$return_price = $calc->getUntaxedPrice($price);
}
else {
$return_price = $price;
}
if ($convert != 0) {
$return_price = $prix * Currency::getDefaultCurrency()->getRate();
}
// Format the number using '.', to perform further calculation
$return_price = NumberFormat::getInstance($this->getRequest())->format($return_price, null, '.');
return new JsonResponse(array('result' => $return_price));
}
}

View File

@@ -23,12 +23,15 @@
namespace Thelia\Controller\Admin;
use Thelia\Core\Security\AccessManager;
use Thelia\Core\Security\Resource\AdminResources;
use Thelia\Core\Event\Profile\ProfileEvent;
use Thelia\Core\Event\TheliaEvents;
use Thelia\Form\ProfileCreationForm;
use Thelia\Form\ProfileModificationForm;
use Thelia\Form\ProfileProfileListUpdateForm;
use Thelia\Form\ProfileUpdateModuleAccessForm;
use Thelia\Form\ProfileUpdateResourceAccessForm;
use Thelia\Model\ProfileQuery;
class ProfileController extends AbstractCrudController
@@ -116,6 +119,26 @@ class ProfileController extends AbstractCrudController
return new ProfileModificationForm($this->getRequest(), "form", $data);
}
protected function hydrateResourceUpdateForm($object)
{
$data = array(
'id' => $object->getId(),
);
// Setup the object form
return new ProfileUpdateResourceAccessForm($this->getRequest(), "form", $data);
}
protected function hydrateModuleUpdateForm($object)
{
$data = array(
'id' => $object->getId(),
);
// Setup the object form
return new ProfileUpdateModuleAccessForm($this->getRequest(), "form", $data);
}
protected function getObjectFromEvent($event)
{
return $event->hasProfile() ? $event->getProfile() : null;
@@ -197,14 +220,47 @@ class ProfileController extends AbstractCrudController
);
}
protected function checkRequirements($formData)
public function updateAction()
{
$type = $formData['type'];
if (null !== $response = $this->checkAuth($this->resourceCode, AccessManager::UPDATE)) return $response;
$object = $this->getExistingObject();
if ($object != null) {
// Hydrate the form and pass it to the parser
$resourceAccessForm = $this->hydrateResourceUpdateForm($object);
$moduleAccessForm = $this->hydrateModuleUpdateForm($object);
// Pass it to the parser
$this->getParserContext()->addForm($resourceAccessForm);
$this->getParserContext()->addForm($moduleAccessForm);
}
return parent::updateAction();
}
protected function getRequirements($type, $formData)
protected function getUpdateResourceAccessEvent($formData)
{
$event = new ProfileEvent();
$event->setId($formData['id']);
$event->setResourceAccess($this->getResourceAccess($formData));
return $event;
}
protected function getUpdateModuleAccessEvent($formData)
{
$event = new ProfileEvent();
$event->setId($formData['id']);
$event->setModuleAccess($this->getModuleAccess($formData));
return $event;
}
protected function getResourceAccess($formData)
{
$requirements = array();
foreach($formData as $data => $value) {
@@ -212,15 +268,137 @@ class ProfileController extends AbstractCrudController
continue;
}
$couple = explode(':', $data);
$explosion = explode(':', $data);
if(count($couple) != 2 || $couple[0] != $type) {
$prefix = array_shift ( $explosion );
if($prefix != ProfileUpdateResourceAccessForm::RESOURCE_ACCESS_FIELD_PREFIX) {
continue;
}
$requirements[$couple[1]] = $value;
$requirements[implode('.', $explosion)] = $value;
}
return $requirements;
}
protected function getModuleAccess($formData)
{
$requirements = array();
foreach($formData as $data => $value) {
if(!strstr($data, ':')) {
continue;
}
$explosion = explode(':', $data);
$prefix = array_shift ( $explosion );
if($prefix != ProfileUpdateModuleAccessForm::MODULE_ACCESS_FIELD_PREFIX) {
continue;
}
$requirements[implode('.', $explosion)] = $value;
}
return $requirements;
}
public function processUpdateResourceAccess()
{
// Check current user authorization
if (null !== $response = $this->checkAuth($this->resourceCode, AccessManager::UPDATE)) return $response;
$error_msg = false;
// Create the form from the request
$changeForm = new ProfileUpdateResourceAccessForm($this->getRequest());
try {
// Check the form against constraints violations
$form = $this->validateForm($changeForm, "POST");
// Get the form field values
$data = $form->getData();
$changeEvent = $this->getUpdateResourceAccessEvent($data);
$this->dispatch(TheliaEvents::PROFILE_RESOURCE_ACCESS_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();
}
public function processUpdateModuleAccess()
{
// Check current user authorization
if (null !== $response = $this->checkAuth($this->resourceCode, AccessManager::UPDATE)) return $response;
$error_msg = false;
// Create the form from the request
$changeForm = new ProfileUpdateModuleAccessForm($this->getRequest());
try {
// Check the form against constraints violations
$form = $this->validateForm($changeForm, "POST");
// Get the form field values
$data = $form->getData();
$changeEvent = $this->getUpdateModuleAccessEvent($data);
$this->dispatch(TheliaEvents::PROFILE_MODULE_ACCESS_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

@@ -0,0 +1,93 @@
<?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\Form\TestForm;
/**
* Manages variables
*
* @author Franck Allimant <franck@cqfdev.fr>
*/
class TestController extends BaseAdminController
{
/**
* Load a object for modification, and display the edit template.
*
* @return Symfony\Component\HttpFoundation\Response the response
*/
public function updateAction()
{
// Prepare the data that will hydrate the form
$data = array(
'title' => "test title",
'test' => array('a', 'b', 'toto' => 'c')
);
// Setup the object form
$changeForm = new TestForm($this->getRequest(), "form", $data);
// Pass it to the parser
$this->getParserContext()->addForm($changeForm);
return $this->render('test-form');
}
/**
* Save changes on a modified object, and either go back to the object list, or stay on the edition page.
*
* @return Symfony\Component\HttpFoundation\Response the response
*/
public function processUpdateAction()
{
$error_msg = false;
// Create the form from the request
$changeForm = new TestForm($this->getRequest());
try {
// Check the form against constraints violations
$form = $this->validateForm($changeForm, "POST");
// Get the form field values
$data = $form->getData();
echo "data=";
var_dump($data);
}
catch (FormValidationException $ex) {
// Form cannot be validated
$error_msg = $this->createStandardFormValidationErrorMessage($ex);
}
catch (\Exception $ex) {
// Any other error
$error_msg = $ex->getMessage();
}
echo "Error = $error_msg";
exit;
}
}

View File

@@ -57,8 +57,10 @@ class BaseController extends ContainerAware
/**
* Return an empty response (after an ajax request, for example)
* @param int $status
* @return \Symfony\Component\HttpFoundation\Response
*/
protected function nullResponse($content = null, $status = 200)
protected function nullResponse($status = 200)
{
return new Response(null, $status);
}
@@ -160,8 +162,12 @@ class BaseController extends ContainerAware
}
foreach ($form->all() as $child) {
if (!$child->isValid()) {
$errors .= $this->getErrorMessages($child) . ', ';
$fieldName = $child->getConfig()->getOption('label', $child->getName());
$errors .= sprintf("[%s] %s, ", $fieldName, $this->getErrorMessages($child));
}
}
@@ -190,13 +196,15 @@ class BaseController extends ContainerAware
$errorMessage = null;
if ($form->get("error_message")->getData() != null) {
$errorMessage = $form->get("error_message")->getData();
} else {
}
else {
$errorMessage = sprintf("Missing or invalid data: %s", $this->getErrorMessages($form));
}
throw new FormValidationException($errorMessage);
}
} else {
}
else {
throw new FormValidationException(sprintf("Wrong form method, %s expected.", $expectedMethod));
}
}
@@ -221,7 +229,8 @@ class BaseController extends ContainerAware
{
if ($form != null) {
$url = $form->getSuccessUrl();
} else {
}
else {
$url = $this->getRequest()->get("success_url");
}

View File

@@ -81,7 +81,7 @@ class CartController extends BaseFrontController
$cartEvent->setQuantity($this->getRequest()->get("quantity"));
try {
$this->getDispatcher()->dispatch(TheliaEvents::CART_UPDATEITEM, $cartEvent);
$this->dispatch(TheliaEvents::CART_UPDATEITEM, $cartEvent);
$this->redirectSuccess();
} catch (PropelException $e) {

View File

@@ -0,0 +1,95 @@
<?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\Front;
use Propel\Runtime\Exception\PropelException;
use Thelia\Core\Event\Coupon\CouponConsumeEvent;
use Thelia\Exception\TheliaProcessException;
use Thelia\Form\CouponCode;
use Thelia\Form\Exception\FormValidationException;
use Thelia\Core\Event\Order\OrderEvent;
use Thelia\Core\Event\TheliaEvents;
use Symfony\Component\HttpFoundation\Request;
use Thelia\Form\OrderDelivery;
use Thelia\Form\OrderPayment;
use Thelia\Log\Tlog;
use Thelia\Model\AddressQuery;
use Thelia\Model\AreaDeliveryModuleQuery;
use Thelia\Model\Base\OrderQuery;
use Thelia\Model\ModuleQuery;
use Thelia\Model\Order;
use Thelia\Tools\URL;
/**
* Class CouponController
* @package Thelia\Controller\Front
* @author Guillaume MOREL <gmorel@openstudio.fr>
*/
class CouponController extends BaseFrontController
{
/**
* Test Coupon consuming
*/
public function consumeAction()
{
$this->checkAuth();
$this->checkCartNotEmpty();
$message = false;
$couponCodeForm = new CouponCode($this->getRequest());
try {
$form = $this->validateForm($couponCodeForm, 'post');
$couponCode = $form->get('coupon-code')->getData();
if (null === $couponCode || empty($couponCode)) {
$message = true;
throw new \Exception('Coupon code can\'t be empty');
}
$couponConsumeEvent = new CouponConsumeEvent($couponCode);
// Dispatch Event to the Action
$this->getDispatcher()->dispatch(TheliaEvents::COUPON_CONSUME, $couponConsumeEvent);
} catch (FormValidationException $e) {
$message = sprintf('Please check your coupon code: %s', $e->getMessage());
} catch (PropelException $e) {
$this->getParserContext()->setGeneralError($e->getMessage());
} catch (\Exception $e) {
$message = sprintf('Sorry, an error occurred: %s', $e->getMessage());
}
if ($message !== false) {
Tlog::getInstance()->error(sprintf("Error during order delivery process : %s. Exception was %s", $message, $e->getMessage()));
$couponCodeForm->setErrorMessage($message);
$this->getParserContext()
->addForm($couponCodeForm)
->setGeneralError($message);
}
}
}