Merge with master

This commit is contained in:
touffies
2013-10-02 11:20:48 +02:00
600 changed files with 33563 additions and 13429 deletions

View File

@@ -25,7 +25,6 @@ namespace Thelia\Controller\Admin;
use Thelia\Form\Exception\FormValidationException;
use Thelia\Core\Event\UpdatePositionEvent;
use Thelia\Core\Event\ToggleVisibilityEvent;
/**
* An abstract CRUD controller for Thelia ADMIN, to manage basic CRUD operations on a givent object.
@@ -53,13 +52,13 @@ abstract class AbstractCrudController extends BaseAdminController
protected $visibilityToggleEventIdentifier;
protected $changePositionEventIdentifier;
/**
* @param string $objectName the lower case object name. Example. "message"
*
* @param string $defaultListOrder the default object list order, or null if list is not sortable. Example: manual
* @param string $defaultListOrder the default object list order, or null if list is not sortable. Example: manual
* @param string $orderRequestParameterName Name of the request parameter that set the list order (null if list is not sortable)
*
* @param string $viewPermissionIdentifier the 'view' permission identifier. Example: "admin.configuration.message.view"
* @param string $viewPermissionIdentifier the 'view' permission identifier. Example: "admin.configuration.message.view"
* @param string $createPermissionIdentifier the 'create' permission identifier. Example: "admin.configuration.message.create"
* @param string $updatePermissionIdentifier the 'update' permission identifier. Example: "admin.configuration.message.update"
* @param string $deletePermissionIdentifier the 'delete' permission identifier. Example: "admin.configuration.message.delete"
@@ -69,7 +68,7 @@ abstract class AbstractCrudController extends BaseAdminController
* @param string $deleteEventIdentifier the dispatched delete TheliaEvent identifier. Example: TheliaEvents::MESSAGE_DELETE
*
* @param string $visibilityToggleEventIdentifier the dispatched visibility toggle TheliaEvent identifier, or null if the object has no visible options. Example: TheliaEvents::MESSAGE_TOGGLE_VISIBILITY
* @param string $changePositionEventIdentifier the dispatched position change TheliaEvent identifier, or null if the object has no position. Example: TheliaEvents::MESSAGE_UPDATE_POSITION
* @param string $changePositionEventIdentifier the dispatched position change TheliaEvent identifier, or null if the object has no position. Example: TheliaEvents::MESSAGE_UPDATE_POSITION
*/
public function __construct(
$objectName,
@@ -108,94 +107,93 @@ abstract class AbstractCrudController extends BaseAdminController
/**
* Return the creation form for this object
*/
protected abstract function getCreationForm();
abstract protected function getCreationForm();
/**
* Return the update form for this object
*/
protected abstract function getUpdateForm();
abstract protected function getUpdateForm();
/**
* Hydrate the update form for this object, before passing it to the update template
*
* @param unknown $object
*/
protected abstract function hydrateObjectForm($object);
abstract protected function hydrateObjectForm($object);
/**
* Creates the creation event with the provided form data
*
* @param unknown $formData
*/
protected abstract function getCreationEvent($formData);
abstract protected function getCreationEvent($formData);
/**
* Creates the update event with the provided form data
*
* @param unknown $formData
*/
protected abstract function getUpdateEvent($formData);
abstract protected function getUpdateEvent($formData);
/**
* Creates the delete event with the provided form data
*/
protected abstract function getDeleteEvent();
abstract protected function getDeleteEvent();
/**
* Return true if the event contains the object, e.g. the action has updated the object in the event.
*
* @param unknown $event
*/
protected abstract function eventContainsObject($event);
abstract protected function eventContainsObject($event);
/**
* Get the created object from an event.
*
* @param unknown $createEvent
*/
protected abstract function getObjectFromEvent($event);
abstract protected function getObjectFromEvent($event);
/**
* Load an existing object from the database
*/
protected abstract function getExistingObject();
abstract protected function getExistingObject();
/**
* Returns the object label form the object event (name, title, etc.)
*
* @param unknown $object
*/
protected abstract function getObjectLabel($object);
abstract protected function getObjectLabel($object);
/**
* Returns the object ID from the object
*
* @param unknown $object
*/
protected abstract function getObjectId($object);
abstract protected function getObjectId($object);
/**
* Render the main list template
*
* @param unknown $currentOrder, if any, null otherwise.
*/
protected abstract function renderListTemplate($currentOrder);
abstract protected function renderListTemplate($currentOrder);
/**
* Render the edition template
*/
protected abstract function renderEditionTemplate();
abstract protected function renderEditionTemplate();
/**
* Redirect to the edition template
*/
protected abstract function redirectToEditionTemplate();
abstract protected function redirectToEditionTemplate();
/**
* Redirect to the list template
*/
protected abstract function redirectToListTemplate();
abstract protected function redirectToListTemplate();
protected function createUpdatePositionEvent($positionChangeMode, $positionValue)
{
@@ -210,7 +208,7 @@ abstract class AbstractCrudController extends BaseAdminController
/**
* Put in this method post object creation processing if required.
*
* @param unknown $createEvent the create event
* @param unknown $createEvent the create event
* @return Response a response, or null to continue normal processing
*/
protected function performAdditionalCreateAction($createEvent)
@@ -221,7 +219,7 @@ abstract class AbstractCrudController extends BaseAdminController
/**
* Put in this method post object update processing if required.
*
* @param unknown $updateEvent the update event
* @param unknown $updateEvent the update event
* @return Response a response, or null to continue normal processing
*/
protected function performAdditionalUpdateAction($updateEvent)
@@ -232,7 +230,7 @@ abstract class AbstractCrudController extends BaseAdminController
/**
* Put in this method post object delete processing if required.
*
* @param unknown $deleteEvent the delete event
* @param unknown $deleteEvent the delete event
* @return Response a response, or null to continue normal processing
*/
protected function performAdditionalDeleteAction($deleteEvent)
@@ -243,7 +241,7 @@ abstract class AbstractCrudController extends BaseAdminController
/**
* Put in this method post object position change processing if required.
*
* @param unknown $deleteEvent the delete event
* @param unknown $deleteEvent the delete event
* @return Response a response, or null to continue normal processing
*/
protected function performAdditionalUpdatePositionAction($positionChangeEvent)
@@ -281,7 +279,6 @@ abstract class AbstractCrudController extends BaseAdminController
public function defaultAction()
{
if (null !== $response = $this->checkAuth($this->viewPermissionIdentifier)) return $response;
return $this->renderList();
}
@@ -322,22 +319,19 @@ abstract class AbstractCrudController extends BaseAdminController
$response = $this->performAdditionalCreateAction($createEvent);
if ($response == null) {
if ($response == null) {
// Substitute _ID_ in the URL with the ID of the created object
$successUrl = str_replace('_ID_', $this->getObjectId($createdObject), $creationForm->getSuccessUrl());
// Redirect to the success URL
$this->redirect($successUrl);
}
else {
} else {
return $response;
}
}
catch (FormValidationException $ex) {
} catch (FormValidationException $ex) {
// Form cannot be validated
$error_msg = $this->createStandardFormValidationErrorMessage($ex);
}
catch (\Exception $ex) {
} catch (\Exception $ex) {
// Any other error
$error_msg = $ex->getMessage();
}
@@ -422,16 +416,13 @@ abstract class AbstractCrudController extends BaseAdminController
// Redirect to the success URL
$this->redirect($changeForm->getSuccessUrl());
}
else {
} else {
return $response;
}
}
catch (FormValidationException $ex) {
} catch (FormValidationException $ex) {
// Form cannot be validated
$error_msg = $this->createStandardFormValidationErrorMessage($ex);
}
catch (\Exception $ex) {
} catch (\Exception $ex) {
// Any other error
$error_msg = $ex->getMessage();
}
@@ -445,6 +436,8 @@ abstract class AbstractCrudController extends BaseAdminController
/**
* Update object position (only for objects whichsupport that)
*
* FIXME: integrate with genericUpdatePositionAction
*/
public function updatePositionAction()
{
@@ -466,8 +459,7 @@ abstract class AbstractCrudController extends BaseAdminController
$event = $this->createUpdatePositionEvent($mode, $position);
$this->dispatch($this->changePositionEventIdentifier, $event);
}
catch (\Exception $ex) {
} catch (\Exception $ex) {
// Any error
return $this->errorPage($ex);
}
@@ -476,12 +468,42 @@ abstract class AbstractCrudController extends BaseAdminController
if ($response == null) {
$this->redirectToListTemplate();
}
else {
} else {
return $response;
}
}
protected function genericUpdatePositionAction($object, $eventName, $doFinalRedirect = true)
{
// Check current user authorization
if (null !== $response = $this->checkAuth($this->updatePermissionIdentifier)) return $response;
if ($object != null) {
try {
$mode = $this->getRequest()->get('mode', null);
if ($mode == 'up')
$mode = UpdatePositionEvent::POSITION_UP;
else if ($mode == 'down')
$mode = UpdatePositionEvent::POSITION_DOWN;
else
$mode = UpdatePositionEvent::POSITION_ABSOLUTE;
$position = $this->getRequest()->get('position', null);
$event = new UpdatePositionEvent($object->getId(), $mode, $position);
$this->dispatch($eventName, $event);
} catch (\Exception $ex) {
// Any error
return $this->errorPage($ex);
}
}
if ($doFinalRedirect) $this->redirectToEditionTemplate();
}
/**
* Online status toggle (only for object which support it)
*/
@@ -492,9 +514,6 @@ abstract class AbstractCrudController extends BaseAdminController
$changeEvent = $this->createToggleVisibilityEvent($this->getRequest());
// Create and dispatch the change event
$changeEvent->setIsDefault(true);
try {
$this->dispatch($this->visibilityToggleEventIdentifier, $changeEvent);
} catch (\Exception $ex) {
@@ -502,7 +521,7 @@ abstract class AbstractCrudController extends BaseAdminController
return $this->errorPage($ex);
}
$this->redirectToListTemplate();
return $this->nullResponse();
}
/**

View File

@@ -23,10 +23,6 @@
namespace Thelia\Controller\Admin;
use Thelia\Core\Security\Authentication\AdminTokenAuthenticator;
use Thelia\Model\ConfigQuery;
use Thelia\Core\Security\Exception\TokenAuthenticationException;
class AdminController extends BaseAdminController
{
public function indexAction()
@@ -36,6 +32,6 @@ class AdminController extends BaseAdminController
public function updateAction()
{
return $this->render("profile-edit");
return $this->render("profile-edit");
}
}

View File

@@ -23,10 +23,10 @@
namespace Thelia\Controller\Admin;
use Thelia\Core\Event\AttributeAvDeleteEvent;
use Thelia\Core\Event\Attribute\AttributeAvDeleteEvent;
use Thelia\Core\Event\TheliaEvents;
use Thelia\Core\Event\AttributeAvUpdateEvent;
use Thelia\Core\Event\AttributeAvCreateEvent;
use Thelia\Core\Event\Attribute\AttributeAvUpdateEvent;
use Thelia\Core\Event\Attribute\AttributeAvCreateEvent;
use Thelia\Model\AttributeAvQuery;
use Thelia\Form\AttributeAvModificationForm;
use Thelia\Form\AttributeAvCreationForm;
@@ -193,4 +193,4 @@ class AttributeAvController extends AbstractCrudController
$this->getViewArguments()
);
}
}
}

View File

@@ -23,18 +23,18 @@
namespace Thelia\Controller\Admin;
use Thelia\Core\Event\AttributeDeleteEvent;
use Thelia\Core\Event\Attribute\AttributeDeleteEvent;
use Thelia\Core\Event\TheliaEvents;
use Thelia\Core\Event\AttributeUpdateEvent;
use Thelia\Core\Event\AttributeCreateEvent;
use Thelia\Core\Event\Attribute\AttributeUpdateEvent;
use Thelia\Core\Event\Attribute\AttributeCreateEvent;
use Thelia\Model\AttributeQuery;
use Thelia\Form\AttributeModificationForm;
use Thelia\Form\AttributeCreationForm;
use Thelia\Core\Event\UpdatePositionEvent;
use Thelia\Model\AttributeAv;
use Thelia\Model\AttributeAvQuery;
use Thelia\Core\Event\AttributeAvUpdateEvent;
use Thelia\Core\Event\AttributeEvent;
use Thelia\Core\Event\Attribute\AttributeAvUpdateEvent;
use Thelia\Core\Event\Attribute\AttributeEvent;
/**
* Manages attributes
@@ -113,7 +113,7 @@ class AttributeController extends AbstractCrudController
if ($attr_values !== null) {
foreach($attr_values as $id => $value) {
foreach ($attr_values as $id => $value) {
$event = new AttributeAvUpdateEvent($id);
@@ -168,7 +168,7 @@ class AttributeController extends AbstractCrudController
$attr_array = array();
foreach($attr_av_list as $attr_av) {
foreach ($attr_av_list as $attr_av) {
$attr_array[$attr_av->getId()] = $attr_av->getTitle();
}
@@ -262,8 +262,7 @@ class AttributeController extends AbstractCrudController
$this->dispatch($eventType, $event);
}
}
catch (\Exception $ex) {
} catch (\Exception $ex) {
// Any error
return $this->errorPage($ex);
}
@@ -286,4 +285,4 @@ class AttributeController extends AbstractCrudController
{
return $this->addRemoveFromAllTemplates(TheliaEvents::ATTRIBUTE_ADD_TO_ALL_TEMPLATES);
}
}
}

View File

@@ -42,6 +42,7 @@ use Thelia\Log\Tlog;
use Symfony\Component\Routing\Router;
use Thelia\Model\Admin;
use Thelia\Core\Security\Token\CookieTokenProvider;
use Thelia\Model\CurrencyQuery;
class BaseAdminController extends BaseController
{
@@ -250,6 +251,23 @@ class BaseAdminController extends BaseController
$this->redirect(URL::getInstance()->absoluteUrl($this->getRoute($routeId), $urlParameters));
}
/**
* Get the current edition currency ID, checking if a change was requested in the current request.
*/
protected function getCurrentEditionCurrency()
{
// Return the new language if a change is required.
if (null !== $edit_currency_id = $this->getRequest()->get('edit_currency_id', null)) {
if (null !== $edit_currency = CurrencyQuery::create()->findOneById($edit_currency_id)) {
return $edit_currency;
}
}
// Otherwise return the lang stored in session.
return $this->getSession()->getAdminEditionCurrency();
}
/**
* Get the current edition lang ID, checking if a change was requested in the current request.
*/
@@ -275,20 +293,19 @@ class BaseAdminController extends BaseController
return $this->getCurrentEditionLang()->getLocale();
}
/**
* Return the current list order identifier for a given object name,
* updating in using the current request.
*
* @param unknown $objectName the object name (e.g. 'attribute', 'message')
* @param unknown $objectName the object name (e.g. 'attribute', 'message')
* @param unknown $requestParameterName the name of the request parameter that defines the list order
* @param unknown $defaultListOrder the default order to use, if none is defined
* @param string $updateSession if true, the session will be updated with the current order.
* @param unknown $defaultListOrder the default order to use, if none is defined
* @param string $updateSession if true, the session will be updated with the current order.
*
* @return String the current liste order.
*/
protected function getListOrderFromSession($objectName, $requestParameterName, $defaultListOrder, $updateSession = true) {
protected function getListOrderFromSession($objectName, $requestParameterName, $defaultListOrder, $updateSession = true)
{
$order = $defaultListOrder;
$orderSessionIdentifier = sprintf("admin.%s.currentListOrder", $objectName);
@@ -300,7 +317,6 @@ class BaseAdminController extends BaseController
);
if ($updateSession) $this->getSession()->set($orderSessionIdentifier, $order);
return $order;
}
@@ -335,8 +351,8 @@ class BaseAdminController extends BaseController
/** Clear the remember me cookie.
*
*/
protected function clearRememberMeCookie() {
protected function clearRememberMeCookie()
{
$ctp = new CookieTokenProvider();
$cookieName = ConfigQuery::read('admin_remember_me_cookie_name', 'armcn');
@@ -376,6 +392,9 @@ class BaseAdminController extends BaseController
// Find the current edit language ID
$edition_language = $this->getCurrentEditionLang();
// Find the current edit currency ID
$edition_currency = $this->getCurrentEditionCurrency();
// Prepare common template variables
$args = array_merge($args, array(
'locale' => $session->getLang()->getLocale(),
@@ -385,11 +404,16 @@ class BaseAdminController extends BaseController
'edit_language_id' => $edition_language->getId(),
'edit_language_locale' => $edition_language->getLocale(),
'edit_currency_id' => $edition_currency->getId(),
'current_url' => $this->getRequest()->getUri()
));
// Update the current edition language in session
$this->getSession()->setAdminEditionLang($edition_language);
// Update the current edition language & currency in session
$this->getSession()
->setAdminEditionLang($edition_language)
->setAdminEditionCurrency($edition_currency)
;
// Render the template.
try {

View File

@@ -23,18 +23,18 @@
namespace Thelia\Controller\Admin;
use Thelia\Core\Event\CategoryDeleteEvent;
use Symfony\Component\HttpFoundation\Response;
use Thelia\Core\Event\Category\CategoryDeleteEvent;
use Thelia\Core\Event\TheliaEvents;
use Thelia\Core\Event\CategoryUpdateEvent;
use Thelia\Core\Event\CategoryCreateEvent;
use Thelia\Core\Event\Category\CategoryUpdateEvent;
use Thelia\Core\Event\Category\CategoryCreateEvent;
use Thelia\Model\CategoryQuery;
use Thelia\Form\CategoryModificationForm;
use Thelia\Form\CategoryCreationForm;
use Thelia\Core\Event\UpdatePositionEvent;
use Thelia\Core\Event\CategoryToggleVisibilityEvent;
use Thelia\Core\Event\CategoryDeleteContentEvent;
use Thelia\Core\Event\CategoryAddContentEvent;
use Thelia\Model\CategoryAssociatedContent;
use Thelia\Core\Event\Category\CategoryToggleVisibilityEvent;
use Thelia\Core\Event\Category\CategoryDeleteContentEvent;
use Thelia\Core\Event\Category\CategoryAddContentEvent;
use Thelia\Model\FolderQuery;
use Thelia\Model\ContentQuery;
use Propel\Runtime\ActiveQuery\Criteria;
@@ -47,7 +47,8 @@ use Thelia\Model\CategoryAssociatedContentQuery;
*/
class CategoryController extends AbstractCrudController
{
public function __construct() {
public function __construct()
{
parent::__construct(
'category',
'manual',
@@ -66,15 +67,18 @@ class CategoryController extends AbstractCrudController
);
}
protected function getCreationForm() {
protected function getCreationForm()
{
return new CategoryCreationForm($this->getRequest());
}
protected function getUpdateForm() {
protected function getUpdateForm()
{
return new CategoryModificationForm($this->getRequest());
}
protected function getCreationEvent($formData) {
protected function getCreationEvent($formData)
{
$createEvent = new CategoryCreateEvent();
$createEvent
@@ -87,7 +91,8 @@ class CategoryController extends AbstractCrudController
return $createEvent;
}
protected function getUpdateEvent($formData) {
protected function getUpdateEvent($formData)
{
$changeEvent = new CategoryUpdateEvent($formData['id']);
// Create and dispatch the change event
@@ -105,8 +110,8 @@ class CategoryController extends AbstractCrudController
return $changeEvent;
}
protected function createUpdatePositionEvent($positionChangeMode, $positionValue) {
protected function createUpdatePositionEvent($positionChangeMode, $positionValue)
{
return new UpdatePositionEvent(
$this->getRequest()->get('category_id', null),
$positionChangeMode,
@@ -114,16 +119,18 @@ class CategoryController extends AbstractCrudController
);
}
protected function getDeleteEvent() {
protected function getDeleteEvent()
{
return new CategoryDeleteEvent($this->getRequest()->get('category_id', 0));
}
protected function eventContainsObject($event) {
protected function eventContainsObject($event)
{
return $event->hasCategory();
}
protected function hydrateObjectForm($object) {
protected function hydrateObjectForm($object)
{
// Prepare the data that will hydrate the form
$data = array(
'id' => $object->getId(),
@@ -141,21 +148,25 @@ class CategoryController extends AbstractCrudController
return new CategoryModificationForm($this->getRequest(), "form", $data);
}
protected function getObjectFromEvent($event) {
protected function getObjectFromEvent($event)
{
return $event->hasCategory() ? $event->getCategory() : null;
}
protected function getExistingObject() {
protected function getExistingObject()
{
return CategoryQuery::create()
->joinWithI18n($this->getCurrentEditionLocale())
->findOneById($this->getRequest()->get('category_id', 0));
}
protected function getObjectLabel($object) {
protected function getObjectLabel($object)
{
return $object->getTitle();
}
protected function getObjectId($object) {
protected function getObjectId($object)
{
return $object->getId();
}
@@ -168,8 +179,8 @@ class CategoryController extends AbstractCrudController
);
}
protected function renderListTemplate($currentOrder) {
protected function renderListTemplate($currentOrder)
{
// Get product order
$product_order = $this->getListOrderFromSession('product', 'product_order', 'manual');
@@ -181,19 +192,21 @@ class CategoryController extends AbstractCrudController
));
}
protected function redirectToListTemplate() {
protected function redirectToListTemplate()
{
$this->redirectToRoute(
'admin.categories.default',
array('category_id' => $this->getRequest()->get('category_id', 0))
);
}
protected function renderEditionTemplate() {
protected function renderEditionTemplate()
{
return $this->render('category-edit', $this->getEditionArguments());
}
protected function redirectToEditionTemplate() {
protected function redirectToEditionTemplate()
{
$this->redirectToRoute("admin.categories.update", $this->getEditionArguments());
}
@@ -255,8 +268,8 @@ class CategoryController extends AbstractCrudController
return null;
}
public function getAvailableRelatedContentAction($categoryId, $folderId) {
public function getAvailableRelatedContentAction($categoryId, $folderId)
{
$result = array();
$folders = FolderQuery::create()->filterById($folderId)->find();
@@ -271,7 +284,7 @@ class CategoryController extends AbstractCrudController
;
if ($list !== null) {
foreach($list as $item) {
foreach ($list as $item) {
$result[] = array('id' => $item->getId(), 'title' => $item->getTitle());
}
}
@@ -280,8 +293,8 @@ class CategoryController extends AbstractCrudController
return $this->jsonResponse(json_encode($result));
}
public function addRelatedContentAction() {
public function addRelatedContentAction()
{
// Check current user authorization
if (null !== $response = $this->checkAuth("admin.categories.update")) return $response;
@@ -296,8 +309,7 @@ class CategoryController extends AbstractCrudController
try {
$this->dispatch(TheliaEvents::CATEGORY_ADD_CONTENT, $event);
}
catch (\Exception $ex) {
} catch (\Exception $ex) {
// Any error
return $this->errorPage($ex);
}
@@ -306,8 +318,41 @@ class CategoryController extends AbstractCrudController
$this->redirectToEditionTemplate();
}
public function deleteRelatedContentAction() {
/**
* Add category pictures
*
* @return \Symfony\Component\HttpFoundation\Response
*/
public function addRelatedPictureAction()
{
// Check current user authorization
if (null !== $response = $this->checkAuth("admin.categories.update")) {
return $response;
}
// $content_id = intval($this->getRequest()->get('content_id'));
//
// if ($content_id > 0) {
//
// $event = new CategoryAddContentEvent(
// $this->getExistingObject(),
// $content_id
// );
//
// try {
// $this->dispatch(TheliaEvents::CATEGORY_ADD_CONTENT, $event);
// }
// catch (\Exception $ex) {
// // Any error
// return $this->errorPage($ex);
// }
// }
$this->redirectToEditionTemplate();
}
public function deleteRelatedContentAction()
{
// Check current user authorization
if (null !== $response = $this->checkAuth("admin.categories.update")) return $response;
@@ -322,8 +367,7 @@ class CategoryController extends AbstractCrudController
try {
$this->dispatch(TheliaEvents::CATEGORY_REMOVE_CONTENT, $event);
}
catch (\Exception $ex) {
} catch (\Exception $ex) {
// Any error
return $this->errorPage($ex);
}
@@ -331,4 +375,5 @@ class CategoryController extends AbstractCrudController
$this->redirectToEditionTemplate();
}
}

View File

@@ -23,14 +23,13 @@
namespace Thelia\Controller\Admin;
use Thelia\Core\Event\ConfigDeleteEvent;
use Thelia\Core\Event\Config\ConfigDeleteEvent;
use Thelia\Core\Event\TheliaEvents;
use Thelia\Core\Event\ConfigUpdateEvent;
use Thelia\Core\Event\ConfigCreateEvent;
use Thelia\Core\Event\Config\ConfigUpdateEvent;
use Thelia\Core\Event\Config\ConfigCreateEvent;
use Thelia\Model\ConfigQuery;
use Thelia\Form\ConfigModificationForm;
use Thelia\Form\ConfigCreationForm;
use Thelia\Core\Event\UpdatePositionEvent;
/**
* Manages variables
@@ -39,7 +38,8 @@ use Thelia\Core\Event\UpdatePositionEvent;
*/
class ConfigController extends AbstractCrudController
{
public function __construct() {
public function __construct()
{
parent::__construct(
'variable',
'name',
@@ -58,15 +58,18 @@ class ConfigController extends AbstractCrudController
);
}
protected function getCreationForm() {
protected function getCreationForm()
{
return new ConfigCreationForm($this->getRequest());
}
protected function getUpdateForm() {
protected function getUpdateForm()
{
return new ConfigModificationForm($this->getRequest());
}
protected function getCreationEvent($data) {
protected function getCreationEvent($data)
{
$createEvent = new ConfigCreateEvent();
$createEvent
@@ -78,11 +81,11 @@ class ConfigController extends AbstractCrudController
->setSecured($data['secured'])
;
return $createEvent;
}
protected function getUpdateEvent($data) {
protected function getUpdateEvent($data)
{
$changeEvent = new ConfigUpdateEvent($data['id']);
// Create and dispatch the change event
@@ -101,16 +104,18 @@ class ConfigController extends AbstractCrudController
return $changeEvent;
}
protected function getDeleteEvent() {
protected function getDeleteEvent()
{
return new ConfigDeleteEvent($this->getRequest()->get('variable_id'));
}
protected function eventContainsObject($event) {
protected function eventContainsObject($event)
{
return $event->hasConfig();
}
protected function hydrateObjectForm($object) {
protected function hydrateObjectForm($object)
{
// Prepare the data that will hydrate the form
$data = array(
'id' => $object->getId(),
@@ -129,40 +134,48 @@ class ConfigController extends AbstractCrudController
return new ConfigModificationForm($this->getRequest(), "form", $data);
}
protected function getObjectFromEvent($event) {
protected function getObjectFromEvent($event)
{
return $event->hasConfig() ? $event->getConfig() : null;
}
protected function getExistingObject() {
protected function getExistingObject()
{
return ConfigQuery::create()
->joinWithI18n($this->getCurrentEditionLocale())
->findOneById($this->getRequest()->get('variable_id'));
}
protected function getObjectLabel($object) {
protected function getObjectLabel($object)
{
return $object->getName();
}
protected function getObjectId($object) {
protected function getObjectId($object)
{
return $object->getId();
}
protected function renderListTemplate($currentOrder) {
protected function renderListTemplate($currentOrder)
{
return $this->render('variables', array('order' => $currentOrder));
}
protected function renderEditionTemplate() {
protected function renderEditionTemplate()
{
return $this->render('variable-edit', array('variable_id' => $this->getRequest()->get('variable_id')));
}
protected function redirectToEditionTemplate() {
protected function redirectToEditionTemplate()
{
$this->redirectToRoute(
"admin.configuration.variables.update",
array('variable_id' => $this->getRequest()->get('variable_id'))
);
}
protected function redirectToListTemplate() {
protected function redirectToListTemplate()
{
$this->redirectToRoute('admin.configuration.variables.default');
}
@@ -188,4 +201,4 @@ class ConfigController extends AbstractCrudController
$this->redirectToRoute('admin.configuration.variables.default');
}
}
}

View File

@@ -0,0 +1,405 @@
<?php
/*************************************************************************************/
/* */
/* Thelia */
/* */
/* Copyright (c) OpenStudio */
/* email : info@thelia.net */
/* web : http://www.thelia.net */
/* */
/* This program is free software; you can redistribute it and/or modify */
/* it under the terms of the GNU General Public License as published by */
/* the Free Software Foundation; either version 3 of the License */
/* */
/* This program is distributed in the hope that it will be useful, */
/* but WITHOUT ANY WARRANTY; without even the implied warranty of */
/* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the */
/* GNU General Public License for more details. */
/* */
/* You should have received a copy of the GNU General Public License */
/* along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* */
/*************************************************************************************/
namespace Thelia\Controller\Admin;
use Thelia\Core\Event\Content\ContentAddFolderEvent;
use Thelia\Core\Event\Content\ContentCreateEvent;
use Thelia\Core\Event\Content\ContentDeleteEvent;
use Thelia\Core\Event\Content\ContentRemoveFolderEvent;
use Thelia\Core\Event\Content\ContentToggleVisibilityEvent;
use Thelia\Core\Event\Content\ContentUpdateEvent;
use Thelia\Core\Event\TheliaEvents;
use Thelia\Core\Event\UpdatePositionEvent;
use Thelia\Form\ContentCreationForm;
use Thelia\Form\ContentModificationForm;
use Thelia\Model\ContentQuery;
/**
* Class ContentController
* @package Thelia\Controller\Admin
* @author manuel raynaud <mraynaud@openstudio.fr>
*/
class ContentController extends AbstractCrudController
{
public function __construct()
{
parent::__construct(
'content',
'manual',
'content_order',
'admin.content.default',
'admin.content.create',
'admin.content.update',
'admin.content.delete',
TheliaEvents::CONTENT_CREATE,
TheliaEvents::CONTENT_UPDATE,
TheliaEvents::CONTENT_DELETE,
TheliaEvents::CONTENT_TOGGLE_VISIBILITY,
TheliaEvents::CONTENT_UPDATE_POSITION
);
}
/**
* controller adding content to additional folder
*
* @return mixed|\Symfony\Component\HttpFoundation\Response
*/
public function addAdditionalFolderAction()
{
// Check current user authorization
if (null !== $response = $this->checkAuth('admin.content.update')) return $response;
$folder_id = intval($this->getRequest()->request->get('additional_folder_id'));
if ($folder_id > 0) {
$event = new ContentAddFolderEvent(
$this->getExistingObject(),
$folder_id
);
try {
$this->dispatch(TheliaEvents::CONTENT_ADD_FOLDER, $event);
} catch (\Exception $e) {
return $this->errorPage($e);
}
}
$this->redirectToEditionTemplate();
}
/**
* controller removing additional folder to a content
*
* @return mixed|\Symfony\Component\HttpFoundation\Response
*/
public function removeAdditionalFolderAction()
{
// Check current user authorization
if (null !== $response = $this->checkAuth('admin.content.update')) return $response;
$folder_id = intval($this->getRequest()->request->get('additional_folder_id'));
if ($folder_id > 0) {
$event = new ContentRemoveFolderEvent(
$this->getExistingObject(),
$folder_id
);
try {
$this->dispatch(TheliaEvents::CONTENT_REMOVE_FOLDER, $event);
} catch (\Exception $e) {
return $this->errorPage($e);
}
}
$this->redirectToEditionTemplate();
}
/**
* Return the creation form for this object
*/
protected function getCreationForm()
{
return new ContentCreationForm($this->getRequest());
}
/**
* Return the update form for this object
*/
protected function getUpdateForm()
{
return new ContentModificationForm($this->getRequest());
}
/**
* Hydrate the update form for this object, before passing it to the update template
*
* @param \Thelia\Form\ContentModificationForm $object
*/
protected function hydrateObjectForm($object)
{
// Prepare the data that will hydrate the form
$data = array(
'id' => $object->getId(),
'locale' => $object->getLocale(),
'title' => $object->getTitle(),
'chapo' => $object->getChapo(),
'description' => $object->getDescription(),
'postscriptum' => $object->getPostscriptum(),
'visible' => $object->getVisible(),
'url' => $object->getRewrittenUrl($this->getCurrentEditionLocale()),
);
// Setup the object form
return new ContentModificationForm($this->getRequest(), "form", $data);
}
/**
* Creates the creation event with the provided form data
*
* @param unknown $formData
*/
protected function getCreationEvent($formData)
{
$contentCreateEvent = new ContentCreateEvent();
$contentCreateEvent
->setLocale($formData['locale'])
->setDefaultFolder($formData['default_folder'])
->setTitle($formData['title'])
->setVisible($formData['visible'])
;
return $contentCreateEvent;
}
/**
* Creates the update event with the provided form data
*
* @param unknown $formData
*/
protected function getUpdateEvent($formData)
{
$contentUpdateEvent = new ContentUpdateEvent($formData['id']);
$contentUpdateEvent
->setLocale($formData['locale'])
->setTitle($formData['title'])
->setChapo($formData['chapo'])
->setDescription($formData['description'])
->setPostscriptum($formData['postscriptum'])
->setVisible($formData['visible'])
->setUrl($formData['url'])
->setDefaultFolder($formData['default_folder']);
return $contentUpdateEvent;
}
/**
* Creates the delete event with the provided form data
*/
protected function getDeleteEvent()
{
return new ContentDeleteEvent($this->getRequest()->get('content_id'));
}
/**
* Return true if the event contains the object, e.g. the action has updated the object in the event.
*
* @param \Thelia\Core\Event\Content\ContentEvent $event
*/
protected function eventContainsObject($event)
{
return $event->hasContent();
}
/**
* Get the created object from an event.
*
* @param $event \Thelia\Core\Event\Content\ContentEvent
*
* @return null|\Thelia\Model\Content
*/
protected function getObjectFromEvent($event)
{
return $event->getContent();
}
/**
* Load an existing object from the database
*
* @return \Thelia\Model\Content
*/
protected function getExistingObject()
{
return ContentQuery::create()
->joinWithI18n($this->getCurrentEditionLocale())
->findOneById($this->getRequest()->get('content_id', 0));
}
/**
* Returns the object label form the object event (name, title, etc.)
*
* @param $object \Thelia\Model\Content
*
* @return string content title
*
*/
protected function getObjectLabel($object)
{
return $object->getTitle();
}
/**
* Returns the object ID from the object
*
* @param $object \Thelia\Model\Content
*
* @return int content id
*/
protected function getObjectId($object)
{
return $object->getId();
}
protected function getFolderId()
{
$folderId = $this->getRequest()->get('folder_id', null);
if (null === $folderId) {
$content = $this->getExistingObject();
if ($content) {
$folderId = $content->getDefaultFolderId();
}
}
return $folderId ?: 0;
}
/**
* Render the main list template
*
* @param unknown $currentOrder, if any, null otherwise.
*/
protected function renderListTemplate($currentOrder)
{
$this->getListOrderFromSession('content', 'content_order', 'manual');
return $this->render('folders',
array(
'content_order' => $currentOrder,
'parent' => $this->getFolderId()
));
}
protected function getEditionArguments()
{
return array(
'content_id' => $this->getRequest()->get('content_id', 0),
'current_tab' => $this->getRequest()->get('current_tab', 'general'),
'folder_id' => $this->getFolderId(),
);
}
/**
* Render the edition template
*/
protected function renderEditionTemplate()
{
return $this->render('content-edit', $this->getEditionArguments());
}
/**
* Redirect to the edition template
*/
protected function redirectToEditionTemplate()
{
$this->redirect($this->getRoute('admin.content.update', $this->getEditionArguments()));
}
/**
* Redirect to the list template
*/
protected function redirectToListTemplate()
{
$this->redirectToRoute(
'admin.content.default',
array('parent' => $this->getFolderId())
);
}
/**
* @param \Thelia\Core\Event\Content\ContentUpdateEvent $updateEvent
* @return Response|void
*/
protected function performAdditionalUpdateAction($updateEvent)
{
if ($this->getRequest()->get('save_mode') != 'stay') {
// Redirect to parent category list
$this->redirectToRoute(
'admin.folders.default',
array('parent' => $this->getFolderId())
);
}
}
/**
* Put in this method post object delete processing if required.
*
* @param \Thelia\Core\Event\Content\ContentDeleteEvent $deleteEvent the delete event
* @return Response a response, or null to continue normal processing
*/
protected function performAdditionalDeleteAction($deleteEvent)
{
// Redirect to parent category list
$this->redirectToRoute(
'admin.folders.default',
array('parent' => $deleteEvent->getDefaultFolderId())
);
}
/**
* @param $event \Thelia\Core\Event\UpdatePositionEvent
* @return null|Response
*/
protected function performAdditionalUpdatePositionAction($event)
{
if (null !== $content = ContentQuery::create()->findPk($event->getObjectId())) {
// Redirect to parent category list
$this->redirectToRoute(
'admin.folders.default',
array('parent' => $content->getDefaultFolderId())
);
}
return null;
}
/**
* @param $positionChangeMode
* @param $positionValue
* @return UpdatePositionEvent|void
*/
protected function createUpdatePositionEvent($positionChangeMode, $positionValue)
{
return new UpdatePositionEvent(
$this->getRequest()->get('content_id', null),
$positionChangeMode,
$positionValue
);
}
/**
* @return ContentToggleVisibilityEvent|void
*/
protected function createToggleVisibilityEvent()
{
return new ContentToggleVisibilityEvent($this->getExistingObject());
}
}

View File

@@ -43,10 +43,10 @@ class CountryController extends BaseAdminController
* @return mixed|\Symfony\Component\HttpFoundation\Response
*/
public function updateAction($country_id)
{
{
return $this->render("country-edit", array(
"country_id" => $country_id
));
}
}
}

View File

@@ -25,24 +25,14 @@ namespace Thelia\Controller\Admin;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Router;
use Thelia\Constraint\ConstraintFactory;
use Thelia\Constraint\ConstraintFactoryTest;
use Thelia\Constraint\Rule\AvailableForTotalAmount;
use Thelia\Constraint\Rule\CouponRuleInterface;
use Thelia\Constraint\Validator\PriceParam;
use Thelia\Condition\ConditionFactory;
use Thelia\Condition\ConditionManagerInterface;
use Thelia\Core\Event\Condition\ConditionCreateOrUpdateEvent;
use Thelia\Core\Event\Coupon\CouponConsumeEvent;
use Thelia\Core\Event\Coupon\CouponCreateEvent;
use Thelia\Core\Event\Coupon\CouponCreateOrUpdateEvent;
use Thelia\Core\Event\Coupon\CouponEvent;
use Thelia\Core\Event\TheliaEvents;
use Thelia\Core\HttpFoundation\Session\Session;
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\ConditionCollection;
use Thelia\Coupon\Type\CouponInterface;
use Thelia\Form\CouponCreationForm;
use Thelia\Form\Exception\FormValidationException;
@@ -76,13 +66,13 @@ class CouponController extends BaseAdminController
$args['urlReadCoupon'] = $this->getRoute(
'admin.coupon.read',
array('couponId' => 'couponId'),
array('couponId' => 0),
Router::ABSOLUTE_URL
);
$args['urlEditCoupon'] = $this->getRoute(
'admin.coupon.update',
array('couponId' => 'couponId'),
array('couponId' => 0),
Router::ABSOLUTE_URL
);
@@ -162,7 +152,7 @@ class CouponController extends BaseAdminController
$args['dateFormat'] = $this->getSession()->getLang()->getDateFormat();
$args['availableCoupons'] = $this->getAvailableCoupons();
$args['formAction'] = 'admin/coupon/create/';
$args['formAction'] = 'admin/coupon/create';
return $this->render(
'coupon-create',
@@ -187,8 +177,9 @@ class CouponController extends BaseAdminController
/** @var Coupon $coupon */
$coupon = CouponQuery::create()->findPk($couponId);
if (!$coupon) {
$this->pageNotFound();
if (null === $coupon) {
return $this->pageNotFound();
}
// Parameters given to the template
@@ -199,7 +190,7 @@ class CouponController extends BaseAdminController
$lang = $this->getSession()->getLang();
$eventToDispatch = TheliaEvents::COUPON_UPDATE;
// Create
// Update
if ($this->getRequest()->isMethod('POST')) {
$this->validateCreateOrUpdateForm(
$i18n,
@@ -208,20 +199,23 @@ class CouponController extends BaseAdminController
'updated',
'update'
);
} else { // Update
} else {
// Display
// Prepare the data that will hydrate the form
/** @var ConstraintFactory $constraintFactory */
$constraintFactory = $this->container->get('thelia.constraint.factory');
$rules = $constraintFactory->unserializeCouponRuleCollection(
$coupon->getSerializedRules()
/** @var ConditionFactory $conditionFactory */
$conditionFactory = $this->container->get('thelia.condition.factory');
$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(),
'amount' => $coupon->getAmount(),
'effect' => $coupon->getType(),
'type' => $coupon->getType(),
'shortDescription' => $coupon->getShortDescription(),
'description' => $coupon->getDescription(),
'isEnabled' => ($coupon->getIsEnabled() == 1),
@@ -230,23 +224,23 @@ class CouponController extends BaseAdminController
'isCumulative' => ($coupon->getIsCumulative() == 1),
'isRemovingPostage' => ($coupon->getIsRemovingPostage() == 1),
'maxUsage' => $coupon->getMaxUsage(),
'rules' => $rules,
'conditions' => $conditions,
'locale' => $coupon->getLocale(),
);
$args['rulesObject'] = array();
$args['conditionsObject'] = array();
/** @var CouponRuleInterface $rule */
foreach ($rules->getRules() as $rule) {
$args['rulesObject'][] = array(
'serviceId' => $rule->getServiceId(),
'name' => $rule->getName(),
'tooltip' => $rule->getToolTip(),
'validators' => $rule->getValidators()
/** @var ConditionManagerInterface $condition */
foreach ($conditions->getConditions() as $condition) {
$args['conditionsObject'][] = array(
'serviceId' => $condition->getServiceId(),
'name' => $condition->getName(),
'tooltip' => $condition->getToolTip(),
'validators' => $condition->getValidators()
);
}
$args['rules'] = $this->cleanRuleForTemplate($rules);
$args['conditions'] = $this->cleanConditionForTemplate($conditions);
// Setup the object form
$changeForm = new CouponCreationForm($this->getRequest(), 'form', $data);
@@ -256,20 +250,20 @@ class CouponController extends BaseAdminController
}
$args['couponCode'] = $coupon->getCode();
$args['availableCoupons'] = $this->getAvailableCoupons();
$args['availableRules'] = $this->getAvailableRules();
$args['urlAjaxGetRuleInput'] = $this->getRoute(
'admin.coupon.rule.input',
array('ruleId' => 'ruleId'),
$args['availableConditions'] = $this->getAvailableConditions();
$args['urlAjaxGetConditionInput'] = $this->getRoute(
'admin.coupon.condition.input',
array('conditionId' => 'conditionId'),
Router::ABSOLUTE_URL
);
$args['urlAjaxUpdateRules'] = $this->getRoute(
'admin.coupon.rule.update',
$args['urlAjaxUpdateConditions'] = $this->getRoute(
'admin.coupon.condition.update',
array('couponId' => $couponId),
Router::ABSOLUTE_URL
);
$args['formAction'] = 'admin/coupon/update/' . $couponId;
$args['formAction'] = 'admin/coupon/update' . $couponId;
return $this->render('coupon-update', $args);
}
@@ -277,34 +271,33 @@ class CouponController extends BaseAdminController
/**
* Manage Coupons read display
*
* @param string $ruleId Rule service id
* @param string $conditionId Condition service id
*
* @return \Symfony\Component\HttpFoundation\Response
*/
public function getRuleInputAction($ruleId)
public function getConditionInputAction($conditionId)
{
$this->checkAuth('ADMIN', 'admin.coupon.read');
$this->checkXmlHttpRequest();
/** @var ConstraintFactory $constraintFactory */
$constraintFactory = $this->container->get('thelia.constraint.factory');
$inputs = $constraintFactory->getInputs($ruleId);
/** @var ConditionFactory $conditionFactory */
$conditionFactory = $this->container->get('thelia.condition.factory');
$inputs = $conditionFactory->getInputs($conditionId);
if ($inputs === null) {
return $this->pageNotFound();
}
return $this->render(
'coupon/rule-input-ajax',
'coupon/condition-input-ajax',
array(
'ruleId' => $ruleId,
'conditionId' => $conditionId,
'inputs' => $inputs
)
);
}
/**
* Manage Coupons read display
*
@@ -312,7 +305,7 @@ class CouponController extends BaseAdminController
*
* @return \Symfony\Component\HttpFoundation\Response
*/
public function updateRulesAction($couponId)
public function updateConditionsAction($couponId)
{
$this->checkAuth('ADMIN', 'admin.coupon.read');
@@ -326,64 +319,51 @@ class CouponController extends BaseAdminController
return $this->pageNotFound();
}
$rules = new CouponRuleCollection();
$conditions = new ConditionCollection();
/** @var ConstraintFactory $constraintFactory */
$constraintFactory = $this->container->get('thelia.constraint.factory');
$rulesReceived = json_decode($this->getRequest()->get('rules'));
foreach ($rulesReceived as $ruleReceived) {
$rule = $constraintFactory->build(
$ruleReceived->serviceId,
(array) $ruleReceived->operators,
(array) $ruleReceived->values
/** @var ConditionFactory $conditionFactory */
$conditionFactory = $this->container->get('thelia.condition.factory');
$conditionsReceived = json_decode($this->getRequest()->get('conditions'));
foreach ($conditionsReceived as $conditionReceived) {
$condition = $conditionFactory->build(
$conditionReceived->serviceId,
(array) $conditionReceived->operators,
(array) $conditionReceived->values
);
$rules->add(clone $rule);
$conditions->add(clone $condition);
}
$coupon->setSerializedRules(
$constraintFactory->serializeCouponRuleCollection($rules)
);
// $coupon->setSerializedConditions(
// $conditionFactory->serializeCouponConditionCollection($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(),
$rules,
$coupon->getLocale()
$conditionEvent = new ConditionCreateOrUpdateEvent(
$conditions
);
$couponEvent->setCoupon($coupon);
$conditionEvent->setCouponModel($coupon);
$eventToDispatch = TheliaEvents::COUPON_RULE_UPDATE;
$eventToDispatch = TheliaEvents::COUPON_CONDITION_UPDATE;
// Dispatch Event to the Action
$this->dispatch(
$eventToDispatch,
$couponEvent
$conditionEvent
);
$this->adminLogAppend(
sprintf(
'Coupon %s (ID %s) rules updated',
$couponEvent->getTitle(),
$couponEvent->getCoupon()->getId()
'Coupon %s (ID %s) conditions updated',
$conditionEvent->getCouponModel()->getTitle(),
$conditionEvent->getCouponModel()->getServiceId()
)
);
$cleanedRules = $this->cleanRuleForTemplate($rules);
$cleanedConditions = $this->cleanConditionForTemplate($conditions);
return $this->render(
'coupon/rules',
'coupon/conditions',
array(
'couponId' => $couponId,
'rules' => $cleanedRules,
'conditions' => $cleanedConditions,
'urlEdit' => $couponId,
'urlDelete' => $couponId
)
@@ -395,6 +375,8 @@ class CouponController extends BaseAdminController
*
* @param string $couponCode Coupon code
*
* @todo remove (event dispatcher testing purpose)
*
*/
public function consumeAction($couponCode)
{
@@ -431,8 +413,8 @@ class CouponController extends BaseAdminController
$couponBeingCreated->setAmount($data['amount']);
$couponBeingCreated->setIsEnabled($data['isEnabled']);
$couponBeingCreated->setExpirationDate($data['expirationDate']);
$couponBeingCreated->setSerializedRules(
new CouponRuleCollection(
$couponBeingCreated->setSerializedConditions(
new ConditionCollection(
array()
)
);
@@ -488,26 +470,14 @@ class CouponController extends BaseAdminController
$message = false;
try {
// Check the form against constraints violations
// Check the form against conditions 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'],
\DateTime::createFromFormat('Y-m-d', $data['expirationDate']),
$data['isAvailableOnSpecialOffers'],
$data['isCumulative'],
$data['isRemovingPostage'],
$data['maxUsage'],
new CouponRuleCollection(array()),
$data['locale']
$data['code'], $data['title'], $data['amount'], $data['type'], $data['shortDescription'], $data['description'], $data['isEnabled'], \DateTime::createFromFormat('Y-m-d', $data['expirationDate']), $data['isAvailableOnSpecialOffers'], $data['isCumulative'], $data['isRemovingPostage'], $data['maxUsage'], $data['locale']
);
// Dispatch Event to the Action
@@ -535,7 +505,6 @@ class CouponController extends BaseAdminController
} catch (FormValidationException $e) {
// Invalid data entered
$message = 'Please check your input:';
$this->logError($action, $message, $e);
} catch (\Exception $e) {
// Any other error
@@ -557,26 +526,26 @@ class CouponController extends BaseAdminController
}
/**
* Get all available rules
* Get all available conditions
*
* @return array
*/
protected function getAvailableRules()
protected function getAvailableConditions()
{
/** @var CouponManager $couponManager */
$couponManager = $this->container->get('thelia.coupon.manager');
$availableRules = $couponManager->getAvailableRules();
$cleanedRules = array();
/** @var CouponRuleInterface $availableRule */
foreach ($availableRules as $availableRule) {
$rule = array();
$rule['serviceId'] = $availableRule->getServiceId();
$rule['name'] = $availableRule->getName();
$rule['toolTip'] = $availableRule->getToolTip();
$cleanedRules[] = $rule;
$availableConditions = $couponManager->getAvailableConditions();
$cleanedConditions = array();
/** @var ConditionManagerInterface $availableCondition */
foreach ($availableConditions as $availableCondition) {
$condition = array();
$condition['serviceId'] = $availableCondition->getServiceId();
$condition['name'] = $availableCondition->getName();
$condition['toolTip'] = $availableCondition->getToolTip();
$cleanedConditions[] = $condition;
}
return $cleanedRules;
return $cleanedConditions;
}
/**
@@ -592,53 +561,54 @@ class CouponController extends BaseAdminController
$cleanedCoupons = array();
/** @var CouponInterface $availableCoupon */
foreach ($availableCoupons as $availableCoupon) {
$rule = array();
$rule['serviceId'] = $availableCoupon->getServiceId();
$rule['name'] = $availableCoupon->getName();
$rule['toolTip'] = $availableCoupon->getToolTip();
$cleanedCoupons[] = $rule;
$condition = array();
$condition['serviceId'] = $availableCoupon->getServiceId();
$condition['name'] = $availableCoupon->getName();
$condition['toolTip'] = $availableCoupon->getToolTip();
$cleanedCoupons[] = $condition;
}
return $cleanedCoupons;
}
/**
* @param $rules
* Clean condition for template
*
* @param ConditionCollection $conditions Condition collection
*
* @return array
*/
protected function cleanRuleForTemplate($rules)
protected function cleanConditionForTemplate(ConditionCollection $conditions)
{
$cleanedRules = array();
/** @var $rule CouponRuleInterface */
foreach ($rules->getRules() as $rule) {
$cleanedRules[] = $rule->getToolTip();
$cleanedConditions = array();
/** @var $condition ConditionManagerInterface */
foreach ($conditions->getConditions() as $condition) {
$cleanedConditions[] = $condition->getToolTip();
}
return $cleanedRules;
return $cleanedConditions;
}
// /**
// * Validation Rule creation
// * Validation Condition creation
// *
// * @param string $type Rule class type
// * @param string $operator Rule operator (<, >, =, etc)
// * @param array $values Rules values
// * @param string $type Condition class type
// * @param string $operator Condition operator (<, >, =, etc)
// * @param array $values Condition values
// *
// * @return bool
// */
// protected function validateRulesCreation($type, $operator, $values)
// protected function validateConditionsCreation($type, $operator, $values)
// {
// /** @var CouponAdapterInterface $adapter */
// /** @var AdapterInterface $adapter */
// $adapter = $this->container->get('thelia.adapter');
// $validator = new PriceParam()
// try {
// $rule = new AvailableForTotalAmount($adapter, $validators);
// $rule = new $type($adapter, $validators);
// $condition = new AvailableForTotalAmount($adapter, $validators);
// $condition = new $type($adapter, $validators);
// } catch (\Exception $e) {
// return false;
// }
// }
}

View File

@@ -23,10 +23,10 @@
namespace Thelia\Controller\Admin;
use Thelia\Core\Event\CurrencyDeleteEvent;
use Thelia\Core\Event\Currency\CurrencyDeleteEvent;
use Thelia\Core\Event\TheliaEvents;
use Thelia\Core\Event\CurrencyUpdateEvent;
use Thelia\Core\Event\CurrencyCreateEvent;
use Thelia\Core\Event\Currency\CurrencyUpdateEvent;
use Thelia\Core\Event\Currency\CurrencyCreateEvent;
use Thelia\Model\CurrencyQuery;
use Thelia\Form\CurrencyModificationForm;
use Thelia\Form\CurrencyCreationForm;
@@ -39,7 +39,8 @@ use Thelia\Core\Event\UpdatePositionEvent;
*/
class CurrencyController extends AbstractCrudController
{
public function __construct() {
public function __construct()
{
parent::__construct(
'currency',
'manual',
@@ -58,15 +59,18 @@ class CurrencyController extends AbstractCrudController
);
}
protected function getCreationForm() {
protected function getCreationForm()
{
return new CurrencyCreationForm($this->getRequest());
}
protected function getUpdateForm() {
protected function getUpdateForm()
{
return new CurrencyModificationForm($this->getRequest());
}
protected function getCreationEvent($formData) {
protected function getCreationEvent($formData)
{
$createEvent = new CurrencyCreateEvent();
$createEvent
@@ -80,7 +84,8 @@ class CurrencyController extends AbstractCrudController
return $createEvent;
}
protected function getUpdateEvent($formData) {
protected function getUpdateEvent($formData)
{
$changeEvent = new CurrencyUpdateEvent($formData['id']);
// Create and dispatch the change event
@@ -95,8 +100,8 @@ class CurrencyController extends AbstractCrudController
return $changeEvent;
}
protected function createUpdatePositionEvent($positionChangeMode, $positionValue) {
protected function createUpdatePositionEvent($positionChangeMode, $positionValue)
{
return new UpdatePositionEvent(
$this->getRequest()->get('currency_id', null),
$positionChangeMode,
@@ -104,16 +109,18 @@ class CurrencyController extends AbstractCrudController
);
}
protected function getDeleteEvent() {
protected function getDeleteEvent()
{
return new CurrencyDeleteEvent($this->getRequest()->get('currency_id'));
}
protected function eventContainsObject($event) {
protected function eventContainsObject($event)
{
return $event->hasCurrency();
}
protected function hydrateObjectForm($object) {
protected function hydrateObjectForm($object)
{
// Prepare the data that will hydrate the form
$data = array(
'id' => $object->getId(),
@@ -128,44 +135,51 @@ class CurrencyController extends AbstractCrudController
return new CurrencyModificationForm($this->getRequest(), "form", $data);
}
protected function getObjectFromEvent($event) {
protected function getObjectFromEvent($event)
{
return $event->hasCurrency() ? $event->getCurrency() : null;
}
protected function getExistingObject() {
protected function getExistingObject()
{
return CurrencyQuery::create()
->joinWithI18n($this->getCurrentEditionLocale())
->findOneById($this->getRequest()->get('currency_id'));
}
protected function getObjectLabel($object) {
protected function getObjectLabel($object)
{
return $object->getName();
}
protected function getObjectId($object) {
protected function getObjectId($object)
{
return $object->getId();
}
protected function renderListTemplate($currentOrder) {
protected function renderListTemplate($currentOrder)
{
return $this->render('currencies', array('order' => $currentOrder));
}
protected function renderEditionTemplate() {
protected function renderEditionTemplate()
{
return $this->render('currency-edit', array('currency_id' => $this->getRequest()->get('currency_id')));
}
protected function redirectToEditionTemplate() {
protected function redirectToEditionTemplate()
{
$this->redirectToRoute(
"admin.configuration.currencies.update",
array('currency_id' => $this->getRequest()->get('currency_id'))
);
}
protected function redirectToListTemplate() {
protected function redirectToListTemplate()
{
$this->redirectToRoute('admin.configuration.currencies.default');
}
/**
* Update currencies rates
*/

View File

@@ -24,8 +24,8 @@
namespace Thelia\Controller\Admin;
use Propel\Runtime\Exception\PropelException;
use Symfony\Component\Form\Form;
use Thelia\Core\Event\CustomerCreateOrUpdateEvent;
use Thelia\Core\Event\CustomerEvent;
use Thelia\Core\Event\Customer\CustomerCreateOrUpdateEvent;
use Thelia\Core\Event\Customer\CustomerEvent;
use Thelia\Core\Event\TheliaEvents;
use Thelia\Form\CustomerModification;
use Thelia\Form\Exception\FormValidationException;
@@ -48,10 +48,9 @@ class CustomerController extends BaseAdminController
public function viewAction($customer_id)
{
if (null !== $response = $this->checkAuth("admin.customer.view")) return $response;
return $this->render("customer-edit", array(
"customer_id" => $customer_id
));
return $this->render("customer-edit", array(
"customer_id" => $customer_id
));
}
/**
@@ -71,8 +70,8 @@ class CustomerController extends BaseAdminController
try {
$customer = CustomerQuery::create()->findPk($customer_id);
if(null === $customer) {
throw new \InvalidArgumentException(sprintf("%d customer id does not exists", $customer_id));
if (null === $customer) {
throw new \InvalidArgumentException(sprintf("%d customer id does not exist", $customer_id));
}
$form = $this->validateForm($customerModification);
@@ -86,7 +85,7 @@ class CustomerController extends BaseAdminController
$this->adminLogAppend(sprintf("Customer with Ref %s (ID %d) modified", $customerUpdated->getRef() , $customerUpdated->getId()));
if($this->getRequest()->get("save_mode") == "close") {
if ($this->getRequest()->get("save_mode") == "close") {
$this->redirectToRoute("admin.customers");
} else {
$this->redirectSuccess($customerModification);
@@ -126,14 +125,14 @@ class CustomerController extends BaseAdminController
$customer_id = $this->getRequest()->get("customer_id");
$customer = CustomerQuery::create()->findPk($customer_id);
if(null === $customer) {
throw new \InvalidArgumentException(Translator::getInstance("The customer you want to delete does not exists"));
if (null === $customer) {
throw new \InvalidArgumentException(Translator::getInstance("The customer you want to delete does not exist"));
}
$event = new CustomerEvent($customer);
$this->dispatch(TheliaEvents::CUSTOMER_DELETEACCOUNT, $event);
} catch(\Exception $e) {
} catch (\Exception $e) {
$message = $e->getMessage();
}
@@ -151,7 +150,7 @@ class CustomerController extends BaseAdminController
/**
* @param $data
* @return CustomerCreateOrUpdateEvent
* @return \Thelia\Core\Event\Customer\CustomerCreateOrUpdateEvent
*/
private function createEventInstance($data)
{
@@ -178,4 +177,4 @@ class CustomerController extends BaseAdminController
return $customerCreateEvent;
}
}
}

View File

@@ -23,10 +23,10 @@
namespace Thelia\Controller\Admin;
use Thelia\Core\Event\FeatureAvDeleteEvent;
use Thelia\Core\Event\Feature\FeatureAvDeleteEvent;
use Thelia\Core\Event\TheliaEvents;
use Thelia\Core\Event\FeatureAvUpdateEvent;
use Thelia\Core\Event\FeatureAvCreateEvent;
use Thelia\Core\Event\Feature\FeatureAvUpdateEvent;
use Thelia\Core\Event\Feature\FeatureAvCreateEvent;
use Thelia\Model\FeatureAvQuery;
use Thelia\Form\FeatureAvModificationForm;
use Thelia\Form\FeatureAvCreationForm;
@@ -193,4 +193,4 @@ class FeatureAvController extends AbstractCrudController
$this->getViewArguments()
);
}
}
}

View File

@@ -23,18 +23,18 @@
namespace Thelia\Controller\Admin;
use Thelia\Core\Event\FeatureDeleteEvent;
use Thelia\Core\Event\Feature\FeatureDeleteEvent;
use Thelia\Core\Event\TheliaEvents;
use Thelia\Core\Event\FeatureUpdateEvent;
use Thelia\Core\Event\FeatureCreateEvent;
use Thelia\Core\Event\Feature\FeatureUpdateEvent;
use Thelia\Core\Event\Feature\FeatureCreateEvent;
use Thelia\Model\FeatureQuery;
use Thelia\Form\FeatureModificationForm;
use Thelia\Form\FeatureCreationForm;
use Thelia\Core\Event\UpdatePositionEvent;
use Thelia\Model\FeatureAv;
use Thelia\Model\FeatureAvQuery;
use Thelia\Core\Event\FeatureAvUpdateEvent;
use Thelia\Core\Event\FeatureEvent;
use Thelia\Core\Event\Feature\FeatureAvUpdateEvent;
use Thelia\Core\Event\Feature\FeatureEvent;
/**
* Manages features
@@ -113,7 +113,7 @@ class FeatureController extends AbstractCrudController
if ($attr_values !== null) {
foreach($attr_values as $id => $value) {
foreach ($attr_values as $id => $value) {
$event = new FeatureAvUpdateEvent($id);
@@ -168,7 +168,7 @@ class FeatureController extends AbstractCrudController
$attr_array = array();
foreach($attr_av_list as $attr_av) {
foreach ($attr_av_list as $attr_av) {
$attr_array[$attr_av->getId()] = $attr_av->getTitle();
}
@@ -262,8 +262,7 @@ class FeatureController extends AbstractCrudController
$this->dispatch($eventType, $event);
}
}
catch (\Exception $ex) {
} catch (\Exception $ex) {
// Any error
return $this->errorPage($ex);
}
@@ -286,4 +285,4 @@ class FeatureController extends AbstractCrudController
{
return $this->addRemoveFromAllTemplates(TheliaEvents::FEATURE_ADD_TO_ALL_TEMPLATES);
}
}
}

View File

@@ -0,0 +1,671 @@
<?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 Propel\Runtime\Exception\PropelException;
use Symfony\Component\HttpFoundation\File\UploadedFile;
use Symfony\Component\HttpFoundation\Response;
use Thelia\Core\Event\Document\DocumentCreateOrUpdateEvent;
use Thelia\Core\Event\Document\DocumentDeleteEvent;
use Thelia\Core\Event\Image\ImageCreateOrUpdateEvent;
use Thelia\Core\Event\Image\ImageDeleteEvent;
use Thelia\Core\Event\TheliaEvents;
use Thelia\Form\Exception\FormValidationException;
use Thelia\Log\Tlog;
use Thelia\Model\CategoryDocument;
use Thelia\Model\CategoryImage;
use Thelia\Model\ContentDocument;
use Thelia\Model\ContentImage;
use Thelia\Model\FolderDocument;
use Thelia\Model\FolderImage;
use Thelia\Model\ProductDocument;
use Thelia\Model\ProductImage;
use Thelia\Tools\FileManager;
use Thelia\Tools\Rest\ResponseRest;
/**
* Created by JetBrains PhpStorm.
* Date: 8/19/13
* Time: 3:24 PM
*
* Control View and Action (Model) via Events
* Control Files and Images
*
* @package File
* @author Guillaume MOREL <gmorel@openstudio.fr>
*
*/
class FileController extends BaseAdminController
{
/**
* Manage how a image collection has to be saved
*
* @param int $parentId Parent id owning images being saved
* @param string $parentType Parent Type owning images being saved
*
* @return Response
*/
public function saveImageAjaxAction($parentId, $parentType)
{
$this->checkAuth('ADMIN', 'admin.image.save');
$this->checkXmlHttpRequest();
if ($this->isParentTypeValid($parentType)) {
if ($this->getRequest()->isMethod('POST')) {
/** @var UploadedFile $fileBeingUploaded */
$fileBeingUploaded = $this->getRequest()->files->get('file');
$fileManager = new FileManager($this->container);
// Validate if file is too big
if ($fileBeingUploaded->getError() == 1) {
$message = $this->getTranslator()
->trans(
'File is too heavy, please retry with a file having a size less than %size%.',
array('%size%' => ini_get('post_max_size')),
'image'
);
return new ResponseRest($message, 'text', 403);
}
// Validate if it is a image or file
if (!$fileManager->isImage($fileBeingUploaded->getMimeType())) {
$message = $this->getTranslator()
->trans(
'You can only upload images (.png, .jpg, .jpeg, .gif)',
array(),
'image'
);
return new ResponseRest($message, 'text', 415);
}
$parentModel = $fileManager->getParentFileModel($parentType, $parentId);
$imageModel = $fileManager->getImageModel($parentType);
if ($parentModel === null || $imageModel === null || $fileBeingUploaded === null) {
return new Response('', 404);
}
$defaultTitle = $parentModel->getTitle();
$imageModel->setParentId($parentId);
$imageModel->setTitle($defaultTitle);
$imageCreateOrUpdateEvent = new ImageCreateOrUpdateEvent(
$parentType,
$parentId
);
$imageCreateOrUpdateEvent->setModelImage($imageModel);
$imageCreateOrUpdateEvent->setUploadedFile($fileBeingUploaded);
$imageCreateOrUpdateEvent->setParentName($parentModel->getTitle());
// Dispatch Event to the Action
$this->dispatch(
TheliaEvents::IMAGE_SAVE,
$imageCreateOrUpdateEvent
);
return new ResponseRest(array('status' => true, 'message' => ''));
}
}
return new Response('', 404);
}
/**
* Manage how a document collection has to be saved
*
* @param int $parentId Parent id owning documents being saved
* @param string $parentType Parent Type owning documents being saved
*
* @return Response
*/
public function saveDocumentAjaxAction($parentId, $parentType)
{
$this->checkAuth('ADMIN', 'admin.document.save');
$this->checkXmlHttpRequest();
if ($this->isParentTypeValid($parentType)) {
if ($this->getRequest()->isMethod('POST')) {
/** @var UploadedFile $fileBeingUploaded */
$fileBeingUploaded = $this->getRequest()->files->get('file');
$fileManager = new FileManager($this->container);
// Validate if file is too big
if ($fileBeingUploaded->getError() == 1) {
$message = $this->getTranslator()
->trans(
'File is too heavy, please retry with a file having a size less than %size%.',
array('%size%' => ini_get('post_max_size')),
'document'
);
return new ResponseRest($message, 'text', 403);
}
$parentModel = $fileManager->getParentFileModel($parentType, $parentId);
$documentModel = $fileManager->getDocumentModel($parentType);
if ($parentModel === null || $documentModel === null || $fileBeingUploaded === null) {
return new Response('', 404);
}
$documentModel->setParentId($parentId);
$documentModel->setTitle($fileBeingUploaded->getClientOriginalName());
$documentCreateOrUpdateEvent = new DocumentCreateOrUpdateEvent(
$parentType,
$parentId
);
$documentCreateOrUpdateEvent->setModelDocument($documentModel);
$documentCreateOrUpdateEvent->setUploadedFile($fileBeingUploaded);
$documentCreateOrUpdateEvent->setParentName($parentModel->getTitle());
// Dispatch Event to the Action
$this->dispatch(
TheliaEvents::DOCUMENT_SAVE,
$documentCreateOrUpdateEvent
);
return new ResponseRest(array('status' => true, 'message' => ''));
}
}
return new Response('', 404);
}
/**
* Manage how a image list will be displayed in AJAX
*
* @param int $parentId Parent id owning images being saved
* @param string $parentType Parent Type owning images being saved
*
* @return Response
*/
public function getImageListAjaxAction($parentId, $parentType)
{
$this->checkAuth('ADMIN', 'admin.image.save');
$this->checkXmlHttpRequest();
$args = array('imageType' => $parentType, 'parentId' => $parentId);
return $this->render('includes/image-upload-list-ajax', $args);
}
/**
* Manage how a document list will be displayed in AJAX
*
* @param int $parentId Parent id owning documents being saved
* @param string $parentType Parent Type owning documents being saved
*
* @return Response
*/
public function getDocumentListAjaxAction($parentId, $parentType)
{
$this->checkAuth('ADMIN', 'admin.document.save');
$this->checkXmlHttpRequest();
$args = array('documentType' => $parentType, 'parentId' => $parentId);
return $this->render('includes/document-upload-list-ajax', $args);
}
/**
* Manage how an image list will be uploaded in AJAX
*
* @param int $parentId Parent id owning images being saved
* @param string $parentType Parent Type owning images being saved
*
* @return Response
*/
public function getImageFormAjaxAction($parentId, $parentType)
{
$this->checkAuth('ADMIN', 'admin.image.save');
$this->checkXmlHttpRequest();
$args = array('imageType' => $parentType, 'parentId' => $parentId);
return $this->render('includes/image-upload-form', $args);
}
/**
* Manage how an document list will be uploaded in AJAX
*
* @param int $parentId Parent id owning documents being saved
* @param string $parentType Parent Type owning documents being saved
*
* @return Response
*/
public function getDocumentFormAjaxAction($parentId, $parentType)
{
$this->checkAuth('ADMIN', 'admin.document.save');
$this->checkXmlHttpRequest();
$args = array('documentType' => $parentType, 'parentId' => $parentId);
return $this->render('includes/document-upload-form', $args);
}
/**
* Manage how an image is viewed
*
* @param int $imageId Parent id owning images being saved
* @param string $parentType Parent Type owning images being saved
*
* @return Response
*/
public function viewImageAction($imageId, $parentType)
{
if (null !== $response = $this->checkAuth('admin.image.view')) {
return $response;
}
try {
$fileManager = new FileManager($this->container);
$image = $fileManager->getImageModelQuery($parentType)->findPk($imageId);
$redirectUrl = $fileManager->getRedirectionUrl($parentType, $image->getParentId(), FileManager::FILE_TYPE_IMAGES);
return $this->render('image-edit', array(
'imageId' => $imageId,
'imageType' => $parentType,
'redirectUrl' => $redirectUrl,
'formId' => $fileManager->getFormId($parentType, FileManager::FILE_TYPE_IMAGES)
));
} catch (\Exception $e) {
$this->pageNotFound();
}
}
/**
* Manage how an document is viewed
*
* @param int $documentId Parent id owning images being saved
* @param string $parentType Parent Type owning images being saved
*
* @return Response
*/
public function viewDocumentAction($documentId, $parentType)
{
if (null !== $response = $this->checkAuth('admin.document.view')) {
return $response;
}
try {
$fileManager = new FileManager($this->container);
$document = $fileManager->getDocumentModelQuery($parentType)->findPk($documentId);
$redirectUrl = $fileManager->getRedirectionUrl($parentType, $document->getParentId(), FileManager::FILE_TYPE_DOCUMENTS);
return $this->render('document-edit', array(
'documentId' => $documentId,
'documentType' => $parentType,
'redirectUrl' => $redirectUrl,
'formId' => $fileManager->getFormId($parentType, FileManager::FILE_TYPE_DOCUMENTS)
));
} catch (\Exception $e) {
$this->pageNotFound();
}
}
/**
* Manage how an image is updated
*
* @param int $imageId Parent id owning images being saved
* @param string $parentType Parent Type owning images being saved
*
* @return Response
*/
public function updateImageAction($imageId, $parentType)
{
if (null !== $response = $this->checkAuth('admin.image.update')) {
return $response;
}
$message = false;
$fileManager = new FileManager($this->container);
$imageModification = $fileManager->getImageForm($parentType, $this->getRequest());
try {
$image = $fileManager->getImageModelQuery($parentType)->findPk($imageId);
$oldImage = clone $image;
if (null === $image) {
throw new \InvalidArgumentException(sprintf('%d image id does not exist', $imageId));
}
$form = $this->validateForm($imageModification);
$event = $this->createImageEventInstance($parentType, $image, $form->getData());
$event->setOldModelImage($oldImage);
$files = $this->getRequest()->files;
$fileForm = $files->get($imageModification->getName());
if (isset($fileForm['file'])) {
$event->setUploadedFile($fileForm['file']);
}
$this->dispatch(TheliaEvents::IMAGE_UPDATE, $event);
$imageUpdated = $event->getModelImage();
$this->adminLogAppend(sprintf('Image with Ref %s (ID %d) modified', $imageUpdated->getTitle(), $imageUpdated->getId()));
if ($this->getRequest()->get('save_mode') == 'close') {
$this->redirectToRoute('admin.images');
} else {
$this->redirectSuccess($imageModification);
}
} catch (FormValidationException $e) {
$message = sprintf('Please check your input: %s', $e->getMessage());
} catch (PropelException $e) {
$message = $e->getMessage();
} catch (\Exception $e) {
$message = sprintf('Sorry, an error occurred: %s', $e->getMessage().' '.$e->getFile());
}
if ($message !== false) {
Tlog::getInstance()->error(sprintf('Error during image editing : %s.', $message));
$imageModification->setErrorMessage($message);
$this->getParserContext()
->addForm($imageModification)
->setGeneralError($message);
}
$redirectUrl = $fileManager->getRedirectionUrl($parentType, $image->getParentId(), FileManager::FILE_TYPE_IMAGES);
return $this->render('image-edit', array(
'imageId' => $imageId,
'imageType' => $parentType,
'redirectUrl' => $redirectUrl,
'formId' => $fileManager->getFormId($parentType, FileManager::FILE_TYPE_IMAGES)
));
}
/**
* Manage how an document is updated
*
* @param int $documentId Parent id owning documents being saved
* @param string $parentType Parent Type owning documents being saved
*
* @return Response
*/
public function updateDocumentAction($documentId, $parentType)
{
if (null !== $response = $this->checkAuth('admin.document.update')) {
return $response;
}
$message = false;
$fileManager = new FileManager($this->container);
$documentModification = $fileManager->getDocumentForm($parentType, $this->getRequest());
try {
$document = $fileManager->getDocumentModelQuery($parentType)->findPk($documentId);
$oldDocument = clone $document;
if (null === $document) {
throw new \InvalidArgumentException(sprintf('%d document id does not exist', $documentId));
}
$form = $this->validateForm($documentModification);
$event = $this->createDocumentEventInstance($parentType, $document, $form->getData());
$event->setOldModelDocument($oldDocument);
$files = $this->getRequest()->files;
$fileForm = $files->get($documentModification->getName());
if (isset($fileForm['file'])) {
$event->setUploadedFile($fileForm['file']);
}
$this->dispatch(TheliaEvents::DOCUMENT_UPDATE, $event);
$documentUpdated = $event->getModelDocument();
$this->adminLogAppend(sprintf('Document with Ref %s (ID %d) modified', $documentUpdated->getTitle(), $documentUpdated->getId()));
if ($this->getRequest()->get('save_mode') == 'close') {
$this->redirectToRoute('admin.documents');
} else {
$this->redirectSuccess($documentModification);
}
} catch (FormValidationException $e) {
$message = sprintf('Please check your input: %s', $e->getMessage());
} catch (PropelException $e) {
$message = $e->getMessage();
} catch (\Exception $e) {
$message = sprintf('Sorry, an error occurred: %s', $e->getMessage().' '.$e->getFile());
}
if ($message !== false) {
Tlog::getInstance()->error(sprintf('Error during document editing : %s.', $message));
$documentModification->setErrorMessage($message);
$this->getParserContext()
->addForm($documentModification)
->setGeneralError($message);
}
$redirectUrl = $fileManager->getRedirectionUrl($parentType, $document->getParentId(), FileManager::FILE_TYPE_DOCUMENTS);
return $this->render('document-edit', array(
'documentId' => $documentId,
'documentType' => $parentType,
'redirectUrl' => $redirectUrl,
'formId' => $fileManager->getFormId($parentType, FileManager::FILE_TYPE_DOCUMENTS)
));
}
/**
* Manage how a image has to be deleted (AJAX)
*
* @param int $imageId Parent id owning image being deleted
* @param string $parentType Parent Type owning image being deleted
*
* @return Response
*/
public function deleteImageAction($imageId, $parentType)
{
$this->checkAuth('ADMIN', 'admin.image.delete');
$this->checkXmlHttpRequest();
$fileManager = new FileManager($this->container);
$imageModelQuery = $fileManager->getImageModelQuery($parentType);
$model = $imageModelQuery->findPk($imageId);
if ($model == null) {
return $this->pageNotFound();
}
// Feed event
$imageDeleteEvent = new ImageDeleteEvent(
$model,
$parentType
);
// Dispatch Event to the Action
$this->dispatch(
TheliaEvents::IMAGE_DELETE,
$imageDeleteEvent
);
$message = $this->getTranslator()
->trans(
'Images deleted successfully',
array(),
'image'
);
return new Response($message);
}
/**
* Manage how a document has to be deleted (AJAX)
*
* @param int $documentId Parent id owning document being deleted
* @param string $parentType Parent Type owning document being deleted
*
* @return Response
*/
public function deleteDocumentAction($documentId, $parentType)
{
$this->checkAuth('ADMIN', 'admin.document.delete');
$this->checkXmlHttpRequest();
$fileManager = new FileManager($this->container);
$documentModelQuery = $fileManager->getDocumentModelQuery($parentType);
$model = $documentModelQuery->findPk($documentId);
if ($model == null) {
return $this->pageNotFound();
}
// Feed event
$documentDeleteEvent = new DocumentDeleteEvent(
$model,
$parentType
);
// Dispatch Event to the Action
$this->dispatch(
TheliaEvents::DOCUMENT_DELETE,
$documentDeleteEvent
);
$message = $this->getTranslator()
->trans(
'Document deleted successfully',
array(),
'document'
);
return new Response($message);
}
/**
* Log error message
*
* @param string $parentType Parent type
* @param string $action Creation|Update|Delete
* @param string $message Message to log
* @param \Exception $e Exception to log
*
* @return $this
*/
protected function logError($parentType, $action, $message, $e)
{
Tlog::getInstance()->error(
sprintf(
'Error during ' . $parentType . ' ' . $action . ' process : %s. Exception was %s',
$message,
$e->getMessage()
)
);
return $this;
}
/**
* Check if parent type is valid or not
*
* @param string $parentType Parent type
*
* @return bool
*/
public function isParentTypeValid($parentType)
{
return (in_array($parentType, FileManager::getAvailableTypes()));
}
/**
* Create Image Event instance
*
* @param string $parentType Parent Type owning images being saved
* @param CategoryImage|ProductImage|ContentImage|FolderImage $model Image model
* @param array $data Post data
*
* @return ImageCreateOrUpdateEvent
*/
protected function createImageEventInstance($parentType, $model, $data)
{
$imageCreateEvent = new ImageCreateOrUpdateEvent($parentType, null);
if (isset($data['title'])) {
$model->setTitle($data['title']);
}
if (isset($data['chapo'])) {
$model->setChapo($data['chapo']);
}
if (isset($data['description'])) {
$model->setDescription($data['description']);
}
if (isset($data['file'])) {
$model->setFile($data['file']);
}
if (isset($data['postscriptum'])) {
$model->setPostscriptum($data['postscriptum']);
}
$imageCreateEvent->setModelImage($model);
return $imageCreateEvent;
}
/**
* Create Document Event instance
*
* @param string $parentType Parent Type owning documents being saved
* @param CategoryDocument|ProductDocument|ContentDocument|FolderDocument $model Document model
* @param array $data Post data
*
* @return DocumentCreateOrUpdateEvent
*/
protected function createDocumentEventInstance($parentType, $model, $data)
{
$documentCreateEvent = new DocumentCreateOrUpdateEvent($parentType, null);
if (isset($data['title'])) {
$model->setTitle($data['title']);
}
if (isset($data['chapo'])) {
$model->setChapo($data['chapo']);
}
if (isset($data['description'])) {
$model->setDescription($data['description']);
}
if (isset($data['file'])) {
$model->setFile($data['file']);
}
if (isset($data['postscriptum'])) {
$model->setPostscriptum($data['postscriptum']);
}
$documentCreateEvent->setModelDocument($model);
return $documentCreateEvent;
}
}

View File

@@ -22,25 +22,308 @@
/*************************************************************************************/
namespace Thelia\Controller\Admin;
use Thelia\Core\Event\Folder\FolderCreateEvent;
use Thelia\Core\Event\Folder\FolderDeleteEvent;
use Thelia\Core\Event\Folder\FolderToggleVisibilityEvent;
use Thelia\Core\Event\Folder\FolderUpdateEvent;
use Thelia\Core\Event\TheliaEvents;
use Thelia\Core\Event\UpdatePositionEvent;
use Thelia\Form\FolderCreationForm;
use Thelia\Form\FolderModificationForm;
use Thelia\Model\FolderQuery;
/**
* Class FolderController
* @package Thelia\Controller\Admin
* @author Manuel Raynaud <mraynaud@openstudio.fr>
*/
class FolderController extends BaseAdminController
class FolderController extends AbstractCrudController
{
public function indexAction()
public function __construct()
{
if (null !== $response = $this->checkAuth("admin.folder.view")) return $response;
return $this->render("folders", array("display_folder" => 20));
parent::__construct(
'folder',
'manual',
'folder_order',
'admin.folder.default',
'admin.folder.create',
'admin.folder.update',
'admin.folder.delete',
TheliaEvents::FOLDER_CREATE,
TheliaEvents::FOLDER_UPDATE,
TheliaEvents::FOLDER_DELETE,
TheliaEvents::FOLDER_TOGGLE_VISIBILITY,
TheliaEvents::FOLDER_UPDATE_POSITION
);
}
public function updateAction($folder_id)
/**
* Return the creation form for this object
*/
protected function getCreationForm()
{
return new FolderCreationForm($this->getRequest());
}
/**
* Return the update form for this object
*/
protected function getUpdateForm()
{
return new FolderModificationForm($this->getRequest());
}
/**
* Hydrate the update form for this object, before passing it to the update template
*
* @param \Thelia\Model\Folder $object
*/
protected function hydrateObjectForm($object)
{
// Prepare the data that will hydrate the form
$data = array(
'id' => $object->getId(),
'locale' => $object->getLocale(),
'title' => $object->getTitle(),
'chapo' => $object->getChapo(),
'description' => $object->getDescription(),
'postscriptum' => $object->getPostscriptum(),
'visible' => $object->getVisible(),
'url' => $object->getRewrittenUrl($this->getCurrentEditionLocale()),
'parent' => $object->getParent()
);
// Setup the object form
return new FolderModificationForm($this->getRequest(), "form", $data);
}
/**
* Creates the creation event with the provided form data
*
* @param unknown $formData
*/
protected function getCreationEvent($formData)
{
$creationEvent = new FolderCreateEvent();
$creationEvent
->setLocale($formData['locale'])
->setTitle($formData['title'])
->setVisible($formData['visible'])
->setParent($formData['parent']);
return $creationEvent;
}
/**
* Creates the update event with the provided form data
*
* @param unknown $formData
*/
protected function getUpdateEvent($formData)
{
$updateEvent = new FolderUpdateEvent($formData['id']);
$updateEvent
->setLocale($formData['locale'])
->setTitle($formData['title'])
->setChapo($formData['chapo'])
->setDescription($formData['description'])
->setPostscriptum($formData['postscriptum'])
->setVisible($formData['visible'])
->setUrl($formData['url'])
->setParent($formData['parent'])
;
return $updateEvent;
}
/**
* Creates the delete event with the provided form data
*/
protected function getDeleteEvent()
{
return new FolderDeleteEvent($this->getRequest()->get('folder_id'), 0);
}
/**
* @return \Thelia\Core\Event\Folder\FolderToggleVisibilityEvent|void
*/
protected function createToggleVisibilityEvent()
{
return new FolderToggleVisibilityEvent($this->getExistingObject());
}
/**
* @param $positionChangeMode
* @param $positionValue
* @return UpdatePositionEvent|void
*/
protected function createUpdatePositionEvent($positionChangeMode, $positionValue)
{
return new UpdatePositionEvent(
$this->getRequest()->get('folder_id', null),
$positionChangeMode,
$positionValue
);
}
/**
* Return true if the event contains the object, e.g. the action has updated the object in the event.
*
* @param \Thelia\Core\Event\Folder\FolderEvent $event
*/
protected function eventContainsObject($event)
{
return $event->hasFolder();
}
/**
* Get the created object from an event.
*
* @param $event \Thelia\Core\Event\Folder\FolderEvent $event
*
* @return null|\Thelia\Model\Folder
*/
protected function getObjectFromEvent($event)
{
return $event->hasFolder() ? $event->getFolder() : null;
}
/**
* Load an existing object from the database
*/
protected function getExistingObject()
{
return FolderQuery::create()
->joinWithI18n($this->getCurrentEditionLocale())
->findOneById($this->getRequest()->get('folder_id', 0));
}
/**
* Returns the object label form the object event (name, title, etc.)
*
* @param unknown $object
*/
protected function getObjectLabel($object)
{
return $object->getTitle();
}
/**
* Returns the object ID from the object
*
* @param unknown $object
*/
protected function getObjectId($object)
{
return $object->getId();
}
/**
* Render the main list template
*
* @param unknown $currentOrder, if any, null otherwise.
*/
protected function renderListTemplate($currentOrder)
{
// Get content order
$content_order = $this->getListOrderFromSession('content', 'content_order', 'manual');
return $this->render('folders',
array(
'folder_order' => $currentOrder,
'content_order' => $content_order,
'parent' => $this->getRequest()->get('parent', 0)
));
}
/**
* Render the edition template
*/
protected function renderEditionTemplate()
{
return $this->render('folder-edit', $this->getEditionArguments());
}
protected function getEditionArguments()
{
return array(
'folder_id' => $this->getRequest()->get('folder_id', 0),
'current_tab' => $this->getRequest()->get('current_tab', 'general')
);
}
/**
* @param \Thelia\Core\Event\Folder\FolderUpdateEvent $updateEvent
* @return Response|void
*/
protected function performAdditionalUpdateAction($updateEvent)
{
if ($this->getRequest()->get('save_mode') != 'stay') {
// Redirect to parent category list
$this->redirectToRoute(
'admin.folders.default',
array('parent' => $updateEvent->getFolder()->getParent())
);
}
}
/**
* Put in this method post object delete processing if required.
*
* @param \Thelia\Core\Event\Folder\FolderDeleteEvent $deleteEvent the delete event
* @return Response a response, or null to continue normal processing
*/
protected function performAdditionalDeleteAction($deleteEvent)
{
// Redirect to parent category list
$this->redirectToRoute(
'admin.folders.default',
array('parent' => $deleteEvent->getFolder()->getParent())
);
}
/**
* @param $event \Thelia\Core\Event\UpdatePositionEvent
* @return null|Response
*/
protected function performAdditionalUpdatePositionAction($event)
{
return $this->render("folder-edit", array(
"folder_id" => $folder_id
));
$folder = FolderQuery::create()->findPk($event->getObjectId());
if ($folder != null) {
// Redirect to parent category list
$this->redirectToRoute(
'admin.folders.default',
array('parent' => $folder->getParent())
);
}
return null;
}
}
/**
* Redirect to the edition template
*/
protected function redirectToEditionTemplate()
{
$this->redirect($this->getRoute('admin.folders.update', $this->getEditionArguments()));
}
/**
* Redirect to the list template
*/
protected function redirectToListTemplate()
{
$this->redirectToRoute(
'admin.folders.default',
array('parent' => $this->getRequest()->get('parent', 0))
);
}
}

View File

@@ -23,9 +23,9 @@
namespace Thelia\Controller\Admin;
use Thelia\Core\Event\MessageDeleteEvent;
use Thelia\Core\Event\TheliaEvents;use Thelia\Core\Event\MessageUpdateEvent;
use Thelia\Core\Event\MessageCreateEvent;
use Thelia\Core\Event\Message\MessageDeleteEvent;
use Thelia\Core\Event\TheliaEvents;use Thelia\Core\Event\Message\MessageUpdateEvent;
use Thelia\Core\Event\Message\MessageCreateEvent;
use Thelia\Model\MessageQuery;
use Thelia\Form\MessageModificationForm;
use Thelia\Form\MessageCreationForm;

View File

@@ -35,12 +35,11 @@ class ModuleController extends BaseAdminController
if (null !== $response = $this->checkAuth("admin.module.view")) return $response;
return $this->render("modules", array("display_module" => 20));
}
public function updateAction($module_id)
{
return $this->render("module-edit", array(
"module_id" => $module_id
));
return $this->render("module-edit", array(
"module_id" => $module_id
));
}
}
}

View File

@@ -23,6 +23,15 @@
namespace Thelia\Controller\Admin;
use Thelia\Core\Event\Order\OrderAddressEvent;
use Thelia\Core\Event\Order\OrderEvent;
use Thelia\Core\Event\TheliaEvents;
use Thelia\Form\OrderUpdateAddress;
use Thelia\Model\Base\OrderAddressQuery;
use Thelia\Model\OrderQuery;
use Thelia\Model\OrderStatusQuery;
use Thelia\Tools\URL;
/**
* Class OrderController
* @package Thelia\Controller\Admin
@@ -38,10 +47,150 @@ class OrderController extends BaseAdminController
public function viewAction($order_id)
{
return $this->render("order-edit", array(
"order_id" => $order_id
));
return $this->render("order-edit", array(
"order_id" => $order_id
));
}
}
public function updateStatus($order_id = null)
{
if (null !== $response = $this->checkAuth("admin.order.update")) return $response;
$message = null;
try {
if ($order_id !== null) {
$order_id = $order_id;
} else {
$order_id = $this->getRequest()->get("order_id");
}
$order = OrderQuery::create()->findPk($order_id);
$statusId = $this->getRequest()->request->get("status_id");
$status = OrderStatusQuery::create()->findPk($statusId);
if (null === $order) {
throw new \InvalidArgumentException("The order you want to update status does not exist");
}
if (null === $status) {
throw new \InvalidArgumentException("The status you want to set to the order does not exist");
}
$event = new OrderEvent($order);
$event->setStatus($statusId);
$this->dispatch(TheliaEvents::ORDER_UPDATE_STATUS, $event);
} catch (\Exception $e) {
$message = $e->getMessage();
}
$params = array();
if ($message) {
$params["update_status_error_message"] = $message;
}
$browsedPage = $this->getRequest()->get("order_page");
if ($browsedPage) {
$params["order_page"] = $browsedPage;
$this->redirectToRoute("admin.order.list", $params);
} else {
$params["order_id"] = $order_id;
$params["tab"] = $this->getRequest()->get("tab", 'cart');
$this->redirect(URL::getInstance()->absoluteUrl($this->getRoute("admin.order.update.view", $params)));
}
}
public function updateDeliveryRef($order_id)
{
if (null !== $response = $this->checkAuth("admin.order.update")) return $response;
$message = null;
try {
$order = OrderQuery::create()->findPk($order_id);
$deliveryRef = $this->getRequest()->get("delivery_ref");
if (null === $order) {
throw new \InvalidArgumentException("The order you want to update status does not exist");
}
$event = new OrderEvent($order);
$event->setDeliveryRef($deliveryRef);
$this->dispatch(TheliaEvents::ORDER_UPDATE_DELIVERY_REF, $event);
} catch (\Exception $e) {
$message = $e->getMessage();
}
$params = array();
if ($message) {
$params["update_status_error_message"] = $message;
}
$params["order_id"] = $order_id;
$params["tab"] = $this->getRequest()->get("tab", 'bill');
$this->redirect(URL::getInstance()->absoluteUrl($this->getRoute("admin.order.update.view", $params)));
}
public function updateAddress($order_id)
{
if (null !== $response = $this->checkAuth("admin.order.update")) return $response;
$message = null;
$orderUpdateAddress = new OrderUpdateAddress($this->getRequest());
try {
$order = OrderQuery::create()->findPk($order_id);
if (null === $order) {
throw new \InvalidArgumentException("The order you want to update does not exist");
}
$form = $this->validateForm($orderUpdateAddress, "post");
$orderAddress = OrderAddressQuery::create()->findPk($form->get("id")->getData());
if ($orderAddress->getId() !== $order->getInvoiceOrderAddressId() && $orderAddress->getId() !== $order->getDeliveryOrderAddressId()) {
throw new \InvalidArgumentException("The order address you want to update does not belong to the current order not exist");
}
$event = new OrderAddressEvent(
$form->get("title")->getData(),
$form->get("firstname")->getData(),
$form->get("lastname")->getData(),
$form->get("address1")->getData(),
$form->get("address2")->getData(),
$form->get("address3")->getData(),
$form->get("zipcode")->getData(),
$form->get("city")->getData(),
$form->get("country")->getData(),
$form->get("phone")->getData(),
$form->get("company")->getData()
);
$event->setOrderAddress($orderAddress);
$event->setOrder($order);
$this->dispatch(TheliaEvents::ORDER_UPDATE_ADDRESS, $event);
} catch (\Exception $e) {
$message = $e->getMessage();
}
$params = array();
if ($message) {
$params["update_status_error_message"] = $message;
}
$params["order_id"] = $order_id;
$params["tab"] = $this->getRequest()->get("tab", 'bill');
$this->redirect(URL::getInstance()->absoluteUrl($this->getRoute("admin.order.update.view", $params)));
}
}

View File

@@ -23,26 +23,29 @@
namespace Thelia\Controller\Admin;
use Thelia\Core\Event\ProductDeleteEvent;
use Thelia\Core\Event\Product\ProductAddCategoryEvent;
use Thelia\Core\Event\Product\ProductDeleteCategoryEvent;
use Thelia\Core\Event\Product\ProductDeleteEvent;
use Thelia\Core\Event\TheliaEvents;
use Thelia\Core\Event\ProductUpdateEvent;
use Thelia\Core\Event\ProductCreateEvent;
use Thelia\Core\Event\Product\ProductUpdateEvent;
use Thelia\Core\Event\Product\ProductCreateEvent;
use Thelia\Model\ProductQuery;
use Thelia\Form\ProductModificationForm;
use Thelia\Form\ProductCreationForm;
use Thelia\Core\Event\UpdatePositionEvent;
use Thelia\Core\Event\ProductToggleVisibilityEvent;
use Thelia\Core\Event\ProductDeleteContentEvent;
use Thelia\Core\Event\ProductAddContentEvent;
use Thelia\Model\ProductAssociatedContent;
use Thelia\Core\Event\Product\ProductToggleVisibilityEvent;
use Thelia\Core\Event\Product\ProductDeleteContentEvent;
use Thelia\Core\Event\Product\ProductAddContentEvent;
use Thelia\Model\FolderQuery;
use Thelia\Model\ContentQuery;
use Propel\Runtime\ActiveQuery\Criteria;
use Thelia\Model\ProductAssociatedContentQuery;
use Thelia\Model\AccessoryQuery;
use Thelia\Model\CategoryQuery;
use Thelia\Core\Event\ProductAddAccessoryEvent;
use Thelia\Core\Event\ProductDeleteAccessoryEvent;
use Thelia\Core\Event\Product\ProductAddAccessoryEvent;
use Thelia\Core\Event\Product\ProductDeleteAccessoryEvent;
use Thelia\Model\ProductSaleElementsQuery;
/**
* Manages products
@@ -72,6 +75,35 @@ class ProductController extends AbstractCrudController
);
}
/**
* Attributes ajax tab loading
*/
public function loadAttributesAjaxTabAction()
{
return $this->render(
'ajax/product-attributes-tab',
array(
'product_id' => $this->getRequest()->get('product_id', 0),
)
);
}
/**
* Related information ajax tab loading
*/
public function loadRelatedAjaxTabAction()
{
return $this->render(
'ajax/product-related-tab',
array(
'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)
)
);
}
protected function getCreationForm()
{
return new ProductCreationForm($this->getRequest());
@@ -92,6 +124,10 @@ class ProductController extends AbstractCrudController
->setLocale($formData['locale'])
->setDefaultCategory($formData['default_category'])
->setVisible($formData['visible'])
->setBasePrice($formData['price'])
->setBaseWeight($formData['weight'])
->setCurrencyId($formData['currency'])
->setTaxRuleId($formData['tax_rule'])
;
return $createEvent;
@@ -110,8 +146,8 @@ class ProductController extends AbstractCrudController
->setPostscriptum($formData['postscriptum'])
->setVisible($formData['visible'])
->setUrl($formData['url'])
->setParent($formData['parent'])
;
->setDefaultCategory($formData['default_category'])
;
return $changeEvent;
}
@@ -137,9 +173,15 @@ class ProductController extends AbstractCrudController
protected function hydrateObjectForm($object)
{
// Get the default produc sales element
$salesElement = ProductSaleElementsQuery::create()->filterByProduct($object)->filterByIsDefault(true)->findOne();
// $prices = $salesElement->getProductPrices();
// Prepare the data that will hydrate the form
$data = array(
'id' => $object->getId(),
'ref' => $object->getRef(),
'locale' => $object->getLocale(),
'title' => $object->getTitle(),
'chapo' => $object->getChapo(),
@@ -148,6 +190,8 @@ class ProductController extends AbstractCrudController
'visible' => $object->getVisible(),
'url' => $object->getRewrittenUrl($this->getCurrentEditionLocale()),
'default_category' => $object->getDefaultCategoryId()
// A terminer pour les prix
);
// Setup the object form
@@ -179,15 +223,16 @@ class ProductController extends AbstractCrudController
protected function getEditionArguments()
{
return array(
'category_id' => $this->getCategoryId(),
'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),
'category_id' => $this->getCategoryId(),
'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')
);
}
protected function getCategoryId() {
protected function getCategoryId()
{
// Trouver le category_id, soit depuis la reques, souit depuis le produit courant
$category_id = $this->getRequest()->get('category_id', null);
@@ -298,7 +343,7 @@ class ProductController extends AbstractCrudController
;
if ($list !== null) {
foreach($list as $item) {
foreach ($list as $item) {
$result[] = array('id' => $item->getId(), 'title' => $item->getTitle());
}
}
@@ -324,8 +369,7 @@ class ProductController extends AbstractCrudController
try {
$this->dispatch(TheliaEvents::PRODUCT_ADD_CONTENT, $event);
}
catch (\Exception $ex) {
} catch (\Exception $ex) {
// Any error
return $this->errorPage($ex);
}
@@ -351,8 +395,7 @@ class ProductController extends AbstractCrudController
try {
$this->dispatch(TheliaEvents::PRODUCT_REMOVE_CONTENT, $event);
}
catch (\Exception $ex) {
} catch (\Exception $ex) {
// Any error
return $this->errorPage($ex);
}
@@ -361,7 +404,6 @@ class ProductController extends AbstractCrudController
$this->redirectToEditionTemplate();
}
// -- Accessories management ----------------------------------------------
public function getAvailableAccessoriesAction($productId, $categoryId)
@@ -380,7 +422,7 @@ class ProductController extends AbstractCrudController
;
if ($list !== null) {
foreach($list as $item) {
foreach ($list as $item) {
$result[] = array('id' => $item->getId(), 'title' => $item->getTitle());
}
}
@@ -405,8 +447,7 @@ class ProductController extends AbstractCrudController
try {
$this->dispatch(TheliaEvents::PRODUCT_ADD_ACCESSORY, $event);
}
catch (\Exception $ex) {
} catch (\Exception $ex) {
// Any error
return $this->errorPage($ex);
}
@@ -417,7 +458,6 @@ class ProductController extends AbstractCrudController
public function deleteAccessoryAction()
{
// Check current user authorization
if (null !== $response = $this->checkAuth("admin.products.update")) return $response;
@@ -432,8 +472,7 @@ class ProductController extends AbstractCrudController
try {
$this->dispatch(TheliaEvents::PRODUCT_REMOVE_ACCESSORY, $event);
}
catch (\Exception $ex) {
} catch (\Exception $ex) {
// Any error
return $this->errorPage($ex);
}
@@ -443,30 +482,293 @@ class ProductController extends AbstractCrudController
}
/**
* Update accessory position (only for objects whichsupport that)
* Update accessory position
*/
public function updateAccessoryPositionAction()
{
$accessory = AccessoryQuery::create()->findPk($this->getRequest()->get('accessory_id', null));
return $this->genericUpdatePositionAction(
$accessory,
TheliaEvents::PRODUCT_UPDATE_ACCESSORY_POSITION
);
}
/**
* Update related content position
*/
public function updateContentPositionAction()
{
$content = ProductAssociatedContentQuery::create()->findPk($this->getRequest()->get('content_id', null));
return $this->genericUpdatePositionAction(
$content,
TheliaEvents::PRODUCT_UPDATE_CONTENT_POSITION
);
}
/**
* Change product template for a given product.
*
* @param unknown $productId
*/
public function setProductTemplateAction($productId)
{
// Check current user authorization
if (null !== $response = $this->checkAuth('admin.products.update')) return $response;
try {
$mode = $this->getRequest()->get('mode', null);
$product = ProductQuery::create()->findPk($productId);
if ($mode == 'up')
$mode = UpdatePositionEvent::POSITION_UP;
else if ($mode == 'down')
$mode = UpdatePositionEvent::POSITION_DOWN;
else
$mode = UpdatePositionEvent::POSITION_ABSOLUTE;
if ($product != null) {
$position = $this->getRequest()->get('position', null);
$template_id = intval($this->getRequest()->get('template_id', 0));
$event = new UpdatePositionEvent($mode, $position);
$this->dispatch(TheliaEvents::PRODUCT_UPDATE_ACCESSORY_POSITION, $event);
$this->dispatch(
TheliaEvents::PRODUCT_SET_TEMPLATE,
new ProductSetTemplateEvent($product, $template_id)
);
}
catch (\Exception $ex) {
$this->redirectToEditionTemplate();
}
/**
* Update product attributes and features
*/
public function updateAttributesAndFeaturesAction($productId)
{
$product = ProductQuery::create()->findPk($productId);
if ($product != null) {
$featureTemplate = FeatureTemplateQuery::create()->filterByTemplateId($product->getTemplateId())->find();
if ($featureTemplate !== null) {
// Get all features for the template attached to this product
$allFeatures = FeatureQuery::create()
->filterByFeatureTemplate($featureTemplate)
->find();
$updatedFeatures = array();
// Update all features values, starting with feature av. values
$featureValues = $this->getRequest()->get('feature_value', array());
foreach ($featureValues as $featureId => $featureValueList) {
// Delete all features av. for this feature.
$event = new FeatureProductDeleteEvent($productId, $featureId);
$this->dispatch(TheliaEvents::PRODUCT_FEATURE_DELETE_VALUE, $event);
// Add then all selected values
foreach ($featureValueList as $featureValue) {
$event = new FeatureProductUpdateEvent($productId, $featureId, $featureValue);
$this->dispatch(TheliaEvents::PRODUCT_FEATURE_UPDATE_VALUE, $event);
}
$updatedFeatures[] = $featureId;
}
// Update then features text values
$featureTextValues = $this->getRequest()->get('feature_text_value', array());
foreach ($featureTextValues as $featureId => $featureValue) {
// considere empty text as empty feature value (e.g., we will delete it)
if (empty($featureValue)) continue;
$event = new FeatureProductUpdateEvent($productId, $featureId, $featureValue, true);
$this->dispatch(TheliaEvents::PRODUCT_FEATURE_UPDATE_VALUE, $event);
$updatedFeatures[] = $featureId;
}
// Delete features which don't have any values
foreach ($allFeatures as $feature) {
if (! in_array($feature->getId(), $updatedFeatures)) {
$event = new FeatureProductDeleteEvent($productId, $feature->getId());
$this->dispatch(TheliaEvents::PRODUCT_FEATURE_DELETE_VALUE, $event);
}
}
}
}
// 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 category/product list
$this->redirectToListTemplate();
}
public function addAdditionalCategoryAction()
{
// Check current user authorization
if (null !== $response = $this->checkAuth("admin.products.update")) return $response;
$category_id = intval($this->getRequest()->request->get('additional_category_id'));
if ($category_id > 0) {
$event = new ProductAddCategoryEvent(
$this->getExistingObject(),
$category_id
);
try {
$this->dispatch(TheliaEvents::PRODUCT_ADD_CATEGORY, $event);
} catch (\Exception $ex) {
// Any error
return $this->errorPage($ex);
}
}
$this->redirectToEditionTemplate();
}
public function deleteAdditionalCategoryAction()
{
// Check current user authorization
if (null !== $response = $this->checkAuth("admin.products.update")) return $response;
$category_id = intval($this->getRequest()->get('additional_category_id'));
if ($category_id > 0) {
$event = new ProductDeleteCategoryEvent(
$this->getExistingObject(),
$category_id
);
try {
$this->dispatch(TheliaEvents::PRODUCT_REMOVE_CATEGORY, $event);
} catch (\Exception $ex) {
// Any error
return $this->errorPage($ex);
}
}
$this->redirectToEditionTemplate();
}
// -- Product combination management ---------------------------------------
public function getAttributeValuesAction($productId, $attributeId)
{
$result = array();
// Get attribute for this product
$attribute = AttributeQuery::create()->findPk($attributeId);
if ($attribute !== null) {
$values = AttributeAvQuery::create()
->joinWithI18n($this->getCurrentEditionLocale())
->filterByAttribute($attribute)
->find();
;
if ($values !== null) {
foreach ($values as $value) {
$result[] = array('id' => $value->getId(), 'title' => $value->getTitle());
}
}
}
return $this->jsonResponse(json_encode($result));
}
public function addAttributeValueToCombinationAction($productId, $attributeAvId, $combination)
{
$result = array();
// Get attribute for this product
$attributeAv = AttributeAvQuery::create()->joinWithI18n($this->getCurrentEditionLocale())->findPk($attributeAvId);
if ($attributeAv !== null) {
$addIt = true;
$attribute = $attributeAv->getAttribute();
// Check if this attribute is not already present
$combinationArray = explode(',', $combination);
foreach ($combinationArray as $id) {
$attrAv = AttributeAvQuery::create()->joinWithI18n($this->getCurrentEditionLocale())->findPk($id);
if ($attrAv !== null) {
if ($attrAv->getAttributeId() == $attribute->getId()) {
$result['error'] = $this->getTranslator()->trans(
'A value for attribute "%name" is already present in the combination',
array('%name' => $attribute->getTitle())
);
$addIt = false;
}
$result[] = array('id' => $attrAv->getId(), 'title' => $attrAv->getAttribute()->getTitle() . " : " . $attrAv->getTitle());
}
}
if ($addIt) $result[] = array('id' => $attributeAv->getId(), 'title' => $attribute->getTitle() . " : " . $attributeAv->getTitle());
}
return $this->jsonResponse(json_encode($result));
}
/**
* A a new combination to a product
*/
public function addCombinationAction()
{
// Check current user authorization
if (null !== $response = $this->checkAuth("admin.products.update")) return $response;
$event = new ProductCreateCombinationEvent(
$this->getExistingObject(),
$this->getRequest()->get('combination_attributes', array()),
$this->getCurrentEditionCurrency()->getId()
);
try {
$this->dispatch(TheliaEvents::PRODUCT_ADD_COMBINATION, $event);
} catch (\Exception $ex) {
// Any error
return $this->errorPage($ex);
}
$this->redirectToEditionTemplate();
}
/**
* A a new combination to a product
*/
public function deleteCombinationAction()
{
// Check current user authorization
if (null !== $response = $this->checkAuth("admin.products.update")) return $response;
$event = new ProductDeleteCombinationEvent(
$this->getExistingObject(),
$this->getRequest()->get('product_sale_element_id',0)
);
try {
$this->dispatch(TheliaEvents::PRODUCT_DELETE_COMBINATION, $event);
} catch (\Exception $ex) {
// Any error
return $this->errorPage($ex);
}

View File

@@ -31,9 +31,7 @@ use Thelia\Tools\URL;
use Thelia\Tools\Redirect;
use Thelia\Core\Event\TheliaEvents;
use Thelia\Core\Security\Authentication\AdminTokenAuthenticator;
use Thelia\Core\Security\UserProvider\TokenProvider;
use Symfony\Component\HttpFoundation\Cookie;
use Thelia\Core\Security\UserProvider\CookieTokenProvider;
use Thelia\Core\Security\Exception\TokenAuthenticationException;
class SessionController extends BaseAdminController
@@ -59,8 +57,7 @@ class SessionController extends BaseAdminController
// Render the home page
return $this->render("home");
}
catch (TokenAuthenticationException $ex) {
} catch (TokenAuthenticationException $ex) {
$this->adminLogAppend("Token based authentication failed.");
// Clear the cookie

View File

@@ -35,12 +35,11 @@ class ShippingConfigurationController extends BaseAdminController
if (null !== $response = $this->checkAuth("admin.shipping-configuration.view")) return $response;
return $this->render("shipping-configuration", array("display_shipping_configuration" => 20));
}
public function updateAction($shipping_configuration_id)
{
return $this->render("shipping-configuration-edit", array(
"shipping_configuration_id" => $shipping_configuration_id
));
}
}
}

View File

@@ -35,12 +35,11 @@ class ShippingZoneController extends BaseAdminController
if (null !== $response = $this->checkAuth("admin.shipping-zones.view")) return $response;
return $this->render("shipping-zones", array("display_shipping_zone" => 20));
}
public function updateAction($shipping_zones_id)
{
return $this->render("shipping-zones-edit", array(
"shipping_zones_id" => $shipping_zones_id
));
return $this->render("shipping-zones-edit", array(
"shipping_zones_id" => $shipping_zones_id
));
}
}
}

View File

@@ -23,22 +23,19 @@
namespace Thelia\Controller\Admin;
use Thelia\Core\Event\TemplateDeleteEvent;
use Thelia\Core\Event\Template\TemplateDeleteEvent;
use Thelia\Core\Event\TheliaEvents;
use Thelia\Core\Event\TemplateUpdateEvent;
use Thelia\Core\Event\TemplateCreateEvent;
use Thelia\Core\Event\Template\TemplateUpdateEvent;
use Thelia\Core\Event\Template\TemplateCreateEvent;
use Thelia\Model\TemplateQuery;
use Thelia\Form\TemplateModificationForm;
use Thelia\Form\TemplateCreationForm;
use Thelia\Core\Event\UpdatePositionEvent;
use Thelia\Model\TemplateAv;
use Thelia\Model\TemplateAvQuery;
use Thelia\Core\Event\TemplateAvUpdateEvent;
use Thelia\Core\Event\TemplateEvent;
use Thelia\Core\Event\TemplateDeleteAttributeEvent;
use Thelia\Core\Event\TemplateAddAttributeEvent;
use Thelia\Core\Event\TemplateAddFeatureEvent;
use Thelia\Core\Event\TemplateDeleteFeatureEvent;
use Thelia\Core\Event\Template\TemplateDeleteAttributeEvent;
use Thelia\Core\Event\Template\TemplateAddAttributeEvent;
use Thelia\Core\Event\Template\TemplateAddFeatureEvent;
use Thelia\Core\Event\Template\TemplateDeleteFeatureEvent;
use Thelia\Model\FeatureTemplateQuery;
use Thelia\Model\AttributeTemplateQuery;
/**
* Manages product templates
@@ -100,7 +97,6 @@ class TemplateController extends AbstractCrudController
;
// Add feature and attributes list
return $changeEvent;
}
@@ -197,22 +193,24 @@ class TemplateController extends AbstractCrudController
return null;
}
public function getAjaxFeaturesAction() {
public function getAjaxFeaturesAction()
{
return $this->render(
'ajax/template-feature-list',
array('template_id' => $this->getRequest()->get('template_id'))
);
}
public function getAjaxAttributesAction() {
public function getAjaxAttributesAction()
{
return $this->render(
'ajax/template-attribute-list',
array('template_id' => $this->getRequest()->get('template_id'))
);
}
public function addAttributeAction() {
public function addAttributeAction()
{
// Check current user authorization
if (null !== $response = $this->checkAuth("admin.configuration.template.attribute.add")) return $response;
@@ -235,8 +233,8 @@ class TemplateController extends AbstractCrudController
$this->redirectToEditionTemplate();
}
public function deleteAttributeAction() {
public function deleteAttributeAction()
{
// Check current user authorization
if (null !== $response = $this->checkAuth("admin.configuration.template.attribute.delete")) return $response;
@@ -255,8 +253,23 @@ class TemplateController extends AbstractCrudController
$this->redirectToEditionTemplate();
}
public function addFeatureAction() {
public function updateAttributePositionAction()
{
// Find attribute_template
$attributeTemplate = AttributeTemplateQuery::create()
->filterByTemplateId($this->getRequest()->get('template_id', null))
->filterByAttributeId($this->getRequest()->get('attribute_id', null))
->findOne()
;
return $this->genericUpdatePositionAction(
$attributeTemplate,
TheliaEvents::TEMPLATE_CHANGE_ATTRIBUTE_POSITION
);
}
public function addFeatureAction()
{
// Check current user authorization
if (null !== $response = $this->checkAuth("admin.configuration.template.feature.add")) return $response;
@@ -279,8 +292,8 @@ class TemplateController extends AbstractCrudController
$this->redirectToEditionTemplate();
}
public function deleteFeatureAction() {
public function deleteFeatureAction()
{
// Check current user authorization
if (null !== $response = $this->checkAuth("admin.configuration.template.feature.delete")) return $response;
@@ -299,4 +312,18 @@ class TemplateController extends AbstractCrudController
$this->redirectToEditionTemplate();
}
}
public function updateFeaturePositionAction()
{
// Find feature_template
$featureTemplate = FeatureTemplateQuery::create()
->filterByTemplateId($this->getRequest()->get('template_id', null))
->filterByFeatureId($this->getRequest()->get('feature_id', null))
->findOne()
;
return $this->genericUpdatePositionAction(
$featureTemplate,
TheliaEvents::TEMPLATE_CHANGE_FEATURE_POSITION
);
}
}

View File

@@ -286,7 +286,7 @@ class BaseController extends ContainerAware
*/
protected function checkXmlHttpRequest()
{
if(false === $this->getRequest()->isXmlHttpRequest() && false === $this->isDebug()) {
if (false === $this->getRequest()->isXmlHttpRequest() && false === $this->isDebug()) {
$this->accessDenied();
}
}
@@ -300,6 +300,7 @@ class BaseController extends ContainerAware
public function getMailer()
{
$mailer = $this->container->get('mailer');
return $mailer->getSwiftMailer();
}
}

View File

@@ -22,15 +22,14 @@
/*************************************************************************************/
namespace Thelia\Controller\Front;
use Thelia\Core\Event\AddressCreateOrUpdateEvent;
use Thelia\Core\Event\AddressEvent;
use Thelia\Core\Event\Address\AddressCreateOrUpdateEvent;
use Thelia\Core\Event\Address\AddressEvent;
use Thelia\Core\Event\TheliaEvents;
use Thelia\Form\AddressCreateForm;
use Thelia\Form\AddressUpdateForm;
use Thelia\Form\Exception\FormValidationException;
use Thelia\Model\AddressQuery;
use Thelia\Model\Customer;
use Thelia\Tools\URL;
/**
* Class AddressController
@@ -51,10 +50,8 @@ class AddressController extends BaseFrontController
$this->checkAuth();
$this->checkXmlHttpRequest();
}
/**
* Create controller.
* Check if customer is logged in
@@ -103,7 +100,7 @@ class AddressController extends BaseFrontController
$customer = $this->getSecurityContext()->getCustomerUser();
$address = AddressQuery::create()->findPk($address_id);
if(!$address || $customer->getId() != $address->getCustomerId()) {
if (!$address || $customer->getId() != $address->getCustomerId()) {
$this->redirectToRoute("home");
}
@@ -117,7 +114,6 @@ class AddressController extends BaseFrontController
$addressUpdate = new AddressUpdateForm($request);
try {
$customer = $this->getSecurityContext()->getCustomerUser();
@@ -164,7 +160,7 @@ class AddressController extends BaseFrontController
$customer = $this->getSecurityContext()->getCustomerUser();
$address = AddressQuery::create()->findPk($address_id);
if(!$address || $customer->getId() != $address->getCustomerId()) {
if (!$address || $customer->getId() != $address->getCustomerId()) {
$this->redirectToRoute("home");
}

View File

@@ -24,6 +24,8 @@ namespace Thelia\Controller\Front;
use Symfony\Component\Routing\Router;
use Thelia\Controller\BaseController;
use Thelia\Model\AddressQuery;
use Thelia\Model\ModuleQuery;
use Thelia\Tools\URL;
class BaseFrontController extends BaseController
@@ -53,7 +55,7 @@ class BaseFrontController extends BaseController
public function checkAuth()
{
if($this->getSecurityContext()->hasCustomerUser() === false) {
if ($this->getSecurityContext()->hasCustomerUser() === false) {
$this->redirectToRoute("customer.login.view");
}
}
@@ -61,7 +63,7 @@ class BaseFrontController extends BaseController
protected function checkCartNotEmpty()
{
$cart = $this->getSession()->getCart();
if($cart===null || $cart->countCartItems() == 0) {
if ($cart===null || $cart->countCartItems() == 0) {
$this->redirectToRoute("cart.view");
}
}
@@ -69,7 +71,7 @@ class BaseFrontController extends BaseController
protected function checkValidDelivery()
{
$order = $this->getSession()->getOrder();
if(null === $order || null === $order->chosenDeliveryAddress || null === $order->getDeliveryModuleId()) {
if (null === $order || null === $order->chosenDeliveryAddress || null === $order->getDeliveryModuleId() || null === AddressQuery::create()->findPk($order->chosenDeliveryAddress) || null === ModuleQuery::create()->findPk($order->getDeliveryModuleId())) {
$this->redirectToRoute("order.delivery");
}
}
@@ -77,7 +79,7 @@ class BaseFrontController extends BaseController
protected function checkValidInvoice()
{
$order = $this->getSession()->getOrder();
if(null === $order || null === $order->chosenInvoiceAddress || null === $order->getPaymentModuleId()) {
if (null === $order || null === $order->chosenInvoiceAddress || null === $order->getPaymentModuleId() || null === AddressQuery::create()->findPk($order->chosenInvoiceAddress) || null === ModuleQuery::create()->findPk($order->getPaymentModuleId())) {
$this->redirectToRoute("order.invoice");
}
}

View File

@@ -24,7 +24,7 @@ namespace Thelia\Controller\Front;
use Propel\Runtime\Exception\PropelException;
use Thelia\Form\Exception\FormValidationException;
use Thelia\Core\Event\CartEvent;
use Thelia\Core\Event\Cart\CartEvent;
use Thelia\Core\Event\TheliaEvents;
use Symfony\Component\HttpFoundation\Request;
use Thelia\Form\CartAdd;
@@ -102,7 +102,7 @@ class CartController extends BaseFrontController
/**
* use Thelia\Cart\CartTrait for searching current cart or create a new one
*
* @return CartEvent
* @return \Thelia\Core\Event\Cart\CartEvent
*/
protected function getCartEvent()
{

View File

@@ -22,8 +22,8 @@
/*************************************************************************************/
namespace Thelia\Controller\Front;
use Thelia\Core\Event\CustomerCreateOrUpdateEvent;
use Thelia\Core\Event\CustomerLoginEvent;
use Thelia\Core\Event\Customer\CustomerCreateOrUpdateEvent;
use Thelia\Core\Event\Customer\CustomerLoginEvent;
use Thelia\Core\Event\LostPasswordEvent;
use Thelia\Core\Security\Authentication\CustomerUsernamePasswordFormAuthenticator;
use Thelia\Core\Security\Exception\AuthenticationException;
@@ -104,7 +104,7 @@ class CustomerController extends BaseFrontController
$this->processLogin($customerCreateEvent->getCustomer());
$cart = $this->getCart($this->getRequest());
if($cart->getCartItems()->count() > 0) {
if ($cart->getCartItems()->count() > 0) {
$this->redirectToRoute("cart.view");
} else {
$this->redirectSuccess($customerCreation);
@@ -257,7 +257,7 @@ class CustomerController extends BaseFrontController
/**
* @param $data
* @return CustomerCreateOrUpdateEvent
* @return \Thelia\Core\Event\Customer\CustomerCreateOrUpdateEvent
*/
private function createEventInstance($data)
{

View File

@@ -23,8 +23,9 @@
namespace Thelia\Controller\Front;
use Propel\Runtime\Exception\PropelException;
use Thelia\Exception\TheliaProcessException;
use Thelia\Form\Exception\FormValidationException;
use Thelia\Core\Event\OrderEvent;
use Thelia\Core\Event\Order\OrderEvent;
use Thelia\Core\Event\TheliaEvents;
use Symfony\Component\HttpFoundation\Request;
use Thelia\Form\OrderDelivery;
@@ -32,9 +33,10 @@ use Thelia\Form\OrderPayment;
use Thelia\Log\Tlog;
use Thelia\Model\AddressQuery;
use Thelia\Model\AreaDeliveryModuleQuery;
use Thelia\Model\CountryQuery;
use Thelia\Model\Base\OrderQuery;
use Thelia\Model\ModuleQuery;
use Thelia\Model\Order;
use Thelia\Tools\URL;
/**
* Class OrderController
@@ -66,7 +68,7 @@ class OrderController extends BaseFrontController
/* check that the delivery address belongs to the current customer */
$deliveryAddress = AddressQuery::create()->findPk($deliveryAddressId);
if($deliveryAddress->getCustomerId() !== $this->getSecurityContext()->getCustomerUser()->getId()) {
if ($deliveryAddress->getCustomerId() !== $this->getSecurityContext()->getCustomerUser()->getId()) {
throw new \Exception("Delivery address does not belong to the current customer");
}
@@ -78,11 +80,8 @@ class OrderController extends BaseFrontController
throw new \Exception("Delivery module cannot be use with selected delivery address");
}
/* try to get postage amount */
/* get postage amount */
$moduleReflection = new \ReflectionClass($deliveryModule->getFullNamespace());
if ($moduleReflection->isSubclassOf("Thelia\Module\DeliveryModuleInterface") === false) {
throw new \RuntimeException(sprintf("delivery module %s is not a Thelia\Module\DeliveryModuleInterface", $deliveryModule->getCode()));
}
$moduleInstance = $moduleReflection->newInstance();
$postage = $moduleInstance->getPostage($deliveryAddress->getCountry());
@@ -139,7 +138,7 @@ class OrderController extends BaseFrontController
/* check that the invoice address belongs to the current customer */
$invoiceAddress = AddressQuery::create()->findPk($invoiceAddressId);
if($invoiceAddress->getCustomerId() !== $this->getSecurityContext()->getCustomerUser()->getId()) {
if ($invoiceAddress->getCustomerId() !== $this->getSecurityContext()->getCustomerUser()->getId()) {
throw new \Exception("Invoice address does not belong to the current customer");
}
@@ -190,6 +189,36 @@ class OrderController extends BaseFrontController
$orderEvent = $this->getOrderEvent();
$this->getDispatcher()->dispatch(TheliaEvents::ORDER_PAY, $orderEvent);
$placedOrder = $orderEvent->getPlacedOrder();
if (null !== $placedOrder && null !== $placedOrder->getId()) {
/* order has been placed */
$this->redirect(URL::getInstance()->absoluteUrl($this->getRoute('order.placed', array('order_id' => $orderEvent->getPlacedOrder()->getId()))));
} else {
/* order has not been placed */
$this->redirectToRoute("cart.view");
}
}
public function orderPlaced($order_id)
{
/* check if the placed order matched the customer */
$placedOrder = OrderQuery::create()->findPk(
$this->getRequest()->attributes->get('order_id')
);
if (null === $placedOrder) {
throw new TheliaProcessException("No placed order", TheliaProcessException::NO_PLACED_ORDER, $placedOrder);
}
$customer = $this->getSecurityContext()->getCustomerUser();
if (null === $customer || $placedOrder->getCustomerId() !== $customer->getId()) {
throw new TheliaProcessException("Received placed order id does not belong to the current customer", TheliaProcessException::PLACED_ORDER_ID_BAD_CURRENT_CUSTOMER, $placedOrder);
}
$this->getParserContext()->set("placed_order_id", $placedOrder->getId());
}
protected function getOrderEvent()