This commit is contained in:
Michaël Espeche
2014-06-25 15:26:56 +02:00
621 changed files with 23665 additions and 2990 deletions

5
.gitignore vendored
View File

@@ -42,3 +42,8 @@ templates/*
!templates/email/
!templates/frontOffice/
!templates/pdf/
#Ignore CodeKit
codekit-config.json
config.codekit
.codekit-cache

View File

@@ -10,6 +10,8 @@ env:
- DB_USER=root
before_script:
- sudo apt-get update -qq
- sudo apt-get install -y language-pack-fr language-pack-fr-base
- phpenv config-add travis.php.ini
- composer self-update
- composer install --prefer-dist --dev

View File

@@ -1,4 +1,13 @@
#2.0.3
- New coupon type: Free product if selected products are in the cart.
#2.0.2
- Coupon UI has been redesigned.
- New coupon types:
- Constant discount on selected products
- Constant discount on products of selected categories
- Percentage discount on selected products
- Percentage discount on products of selected categories
- New coupon conditions :
- Start date
- Billing country
@@ -12,7 +21,15 @@
- class event : Thelia\Core\Event\SessionEvent
- example : Thelia\Core\EventListener\SessionListener
- Creation of Thelia\Core\TheliakernelEvents class for referencing kernel event
- Add new command line that refresh modules list `Thelia module:refresh`
- Coupon internals have been simplified and improved.
- Error messages are displayed in install process
- Add pagination on catalog page in Back-Office
- Add Hong Kong to country list
- Fixed issue #452 when installing Thelia on database with special characters
- implement search on content, folder and category loop.
- all form are documented
- template exists for managing google sitemap : sitemap.html
#2.0.1
- possibility to apply a permanent discount on a customer

View File

@@ -33,13 +33,14 @@
"simplepie/simplepie": "dev-master",
"imagine/imagine": "0.*",
"symfony/icu": "1.0",
"swiftmailer/swiftmailer": "5.0.*",
"swiftmailer/swiftmailer": "5.2.*",
"symfony/serializer": "2.3.*",
"ensepar/html2pdf": "1.0.1",
"symfony/finder": "~2.2"
"symfony/finder": "~2.2",
"symfony/browser-kit": "2.3.*"
},
"require-dev": {
"phpunit/phpunit": "3.7.*",
"phpunit/phpunit": "4.1.*",
"fzaninotto/faker": "dev-master",
"maximebf/debugbar": "dev-master"
},

532
composer.lock generated
View File

@@ -1,9 +1,10 @@
{
"_readme": [
"This file locks the dependencies of your project to a known state",
"Read more about it at http://getcomposer.org/doc/01-basic-usage.md#composer-lock-the-lock-file"
"Read more about it at http://getcomposer.org/doc/01-basic-usage.md#composer-lock-the-lock-file",
"This file is @generated automatically"
],
"hash": "d1e1c31ed8e38f2282ab431898cf8b08",
"hash": "4606e1d72b13b6b8fa84dca5f7bac16b",
"packages": [
{
"name": "doctrine/cache",
@@ -607,25 +608,28 @@
},
{
"name": "swiftmailer/swiftmailer",
"version": "v5.0.2",
"version": "v5.2.1",
"source": {
"type": "git",
"url": "https://github.com/swiftmailer/swiftmailer.git",
"reference": "f3917ecef35a4e4d98b303eb9fee463bc983f379"
"reference": "2b9af56cc676c338d52fca4c657e5bdff73bb7af"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/swiftmailer/swiftmailer/zipball/f3917ecef35a4e4d98b303eb9fee463bc983f379",
"reference": "f3917ecef35a4e4d98b303eb9fee463bc983f379",
"url": "https://api.github.com/repos/swiftmailer/swiftmailer/zipball/2b9af56cc676c338d52fca4c657e5bdff73bb7af",
"reference": "2b9af56cc676c338d52fca4c657e5bdff73bb7af",
"shasum": ""
},
"require": {
"php": ">=5.2.4"
},
"require-dev": {
"mockery/mockery": "~0.9.1"
},
"type": "library",
"extra": {
"branch-alias": {
"dev-master": "5.1-dev"
"dev-master": "5.2-dev"
}
},
"autoload": {
@@ -640,7 +644,9 @@
"authors": [
{
"name": "Fabien Potencier",
"email": "fabien@symfony.com"
"email": "fabien@symfony.com",
"homepage": "http://fabien.potencier.org",
"role": "Lead Developer"
},
{
"name": "Chris Corbyn"
@@ -652,7 +658,7 @@
"mail",
"mailer"
],
"time": "2013-08-30 12:35:21"
"time": "2014-06-13 11:44:54"
},
{
"name": "symfony-cmf/routing",
@@ -703,6 +709,63 @@
],
"time": "2013-03-25 15:02:40"
},
{
"name": "symfony/browser-kit",
"version": "v2.3.13",
"target-dir": "Symfony/Component/BrowserKit",
"source": {
"type": "git",
"url": "https://github.com/symfony/BrowserKit.git",
"reference": "97563874c24b65ea8d31b82fe051a161caf83e10"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/symfony/BrowserKit/zipball/97563874c24b65ea8d31b82fe051a161caf83e10",
"reference": "97563874c24b65ea8d31b82fe051a161caf83e10",
"shasum": ""
},
"require": {
"php": ">=5.3.3",
"symfony/dom-crawler": "~2.0"
},
"require-dev": {
"symfony/css-selector": "~2.0",
"symfony/process": "~2.0"
},
"suggest": {
"symfony/process": ""
},
"type": "library",
"extra": {
"branch-alias": {
"dev-master": "2.3-dev"
}
},
"autoload": {
"psr-0": {
"Symfony\\Component\\BrowserKit\\": ""
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Fabien Potencier",
"email": "fabien@symfony.com",
"homepage": "http://fabien.potencier.org",
"role": "Lead Developer"
},
{
"name": "Symfony Community",
"homepage": "http://symfony.com/contributors"
}
],
"description": "Symfony BrowserKit Component",
"homepage": "http://symfony.com",
"time": "2014-04-18 20:35:25"
},
{
"name": "symfony/class-loader",
"version": "v2.2.6",
@@ -902,6 +965,61 @@
"homepage": "http://symfony.com",
"time": "2013-07-21 09:38:59"
},
{
"name": "symfony/dom-crawler",
"version": "v2.4.4",
"target-dir": "Symfony/Component/DomCrawler",
"source": {
"type": "git",
"url": "https://github.com/symfony/DomCrawler.git",
"reference": "e94b29c7cac964e58c406408d238ceeaa3604e78"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/symfony/DomCrawler/zipball/e94b29c7cac964e58c406408d238ceeaa3604e78",
"reference": "e94b29c7cac964e58c406408d238ceeaa3604e78",
"shasum": ""
},
"require": {
"php": ">=5.3.3"
},
"require-dev": {
"symfony/css-selector": "~2.0"
},
"suggest": {
"symfony/css-selector": ""
},
"type": "library",
"extra": {
"branch-alias": {
"dev-master": "2.4-dev"
}
},
"autoload": {
"psr-0": {
"Symfony\\Component\\DomCrawler\\": ""
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Fabien Potencier",
"email": "fabien@symfony.com",
"homepage": "http://fabien.potencier.org",
"role": "Lead Developer"
},
{
"name": "Symfony Community",
"homepage": "http://symfony.com/contributors"
}
],
"description": "Symfony DomCrawler Component",
"homepage": "http://symfony.com",
"time": "2014-04-18 20:37:09"
},
{
"name": "symfony/event-dispatcher",
"version": "v2.2.6",
@@ -1959,40 +2077,44 @@
},
{
"name": "phpunit/php-code-coverage",
"version": "1.2.12",
"version": "2.0.8",
"source": {
"type": "git",
"url": "https://github.com/sebastianbergmann/php-code-coverage.git",
"reference": "1.2.12"
"reference": "58401826c8cfc8fd689b60026e91c337df374bca"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/sebastianbergmann/php-code-coverage/zipball/1.2.12",
"reference": "1.2.12",
"url": "https://api.github.com/repos/sebastianbergmann/php-code-coverage/zipball/58401826c8cfc8fd689b60026e91c337df374bca",
"reference": "58401826c8cfc8fd689b60026e91c337df374bca",
"shasum": ""
},
"require": {
"php": ">=5.3.3",
"phpunit/php-file-iterator": ">=1.3.0@stable",
"phpunit/php-text-template": ">=1.1.1@stable",
"phpunit/php-token-stream": ">=1.1.3@stable"
"phpunit/php-file-iterator": "~1.3.1",
"phpunit/php-text-template": "~1.2.0",
"phpunit/php-token-stream": "~1.2.2",
"sebastian/environment": "~1.0.0",
"sebastian/version": "~1.0.3"
},
"require-dev": {
"phpunit/phpunit": "3.7.*@dev"
"ext-xdebug": ">=2.1.4",
"phpunit/phpunit": "~4.0.14"
},
"suggest": {
"ext-dom": "*",
"ext-xdebug": ">=2.0.5"
"ext-xdebug": ">=2.2.1",
"ext-xmlwriter": "*"
},
"type": "library",
"extra": {
"branch-alias": {
"dev-master": "1.2.x-dev"
"dev-master": "2.0.x-dev"
}
},
"autoload": {
"classmap": [
"PHP/"
"src/"
]
},
"notification-url": "https://packagist.org/downloads/",
@@ -2016,20 +2138,20 @@
"testing",
"xunit"
],
"time": "2013-07-06 06:26:16"
"time": "2014-05-26 14:55:24"
},
{
"name": "phpunit/php-file-iterator",
"version": "1.3.3",
"version": "1.3.4",
"source": {
"type": "git",
"url": "git://github.com/sebastianbergmann/php-file-iterator.git",
"reference": "1.3.3"
"url": "https://github.com/sebastianbergmann/php-file-iterator.git",
"reference": "acd690379117b042d1c8af1fafd61bde001bf6bb"
},
"dist": {
"type": "zip",
"url": "https://github.com/sebastianbergmann/php-file-iterator/zipball/1.3.3",
"reference": "1.3.3",
"url": "https://api.github.com/repos/sebastianbergmann/php-file-iterator/zipball/acd690379117b042d1c8af1fafd61bde001bf6bb",
"reference": "acd690379117b042d1c8af1fafd61bde001bf6bb",
"shasum": ""
},
"require": {
@@ -2056,25 +2178,25 @@
}
],
"description": "FilterIterator implementation that filters files based on a list of suffixes.",
"homepage": "http://www.phpunit.de/",
"homepage": "https://github.com/sebastianbergmann/php-file-iterator/",
"keywords": [
"filesystem",
"iterator"
],
"time": "2012-10-11 04:44:38"
"time": "2013-10-10 15:34:57"
},
{
"name": "phpunit/php-text-template",
"version": "1.1.4",
"version": "1.2.0",
"source": {
"type": "git",
"url": "git://github.com/sebastianbergmann/php-text-template.git",
"reference": "1.1.4"
"url": "https://github.com/sebastianbergmann/php-text-template.git",
"reference": "206dfefc0ffe9cebf65c413e3d0e809c82fbf00a"
},
"dist": {
"type": "zip",
"url": "https://github.com/sebastianbergmann/php-text-template/zipball/1.1.4",
"reference": "1.1.4",
"url": "https://api.github.com/repos/sebastianbergmann/php-text-template/zipball/206dfefc0ffe9cebf65c413e3d0e809c82fbf00a",
"reference": "206dfefc0ffe9cebf65c413e3d0e809c82fbf00a",
"shasum": ""
},
"require": {
@@ -2105,7 +2227,7 @@
"keywords": [
"template"
],
"time": "2012-10-31 11:15:28"
"time": "2014-01-30 17:20:04"
},
{
"name": "phpunit/php-timer",
@@ -2153,16 +2275,16 @@
},
{
"name": "phpunit/php-token-stream",
"version": "1.2.0",
"version": "1.2.2",
"source": {
"type": "git",
"url": "https://github.com/sebastianbergmann/php-token-stream.git",
"reference": "1.2.0"
"reference": "ad4e1e23ae01b483c16f600ff1bebec184588e32"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/sebastianbergmann/php-token-stream/zipball/1.2.0",
"reference": "1.2.0",
"url": "https://api.github.com/repos/sebastianbergmann/php-token-stream/zipball/ad4e1e23ae01b483c16f600ff1bebec184588e32",
"reference": "ad4e1e23ae01b483c16f600ff1bebec184588e32",
"shasum": ""
},
"require": {
@@ -2199,56 +2321,56 @@
"keywords": [
"tokenizer"
],
"time": "2013-08-04 05:57:48"
"time": "2014-03-03 05:10:30"
},
{
"name": "phpunit/phpunit",
"version": "3.7.24",
"version": "4.1.3",
"source": {
"type": "git",
"url": "https://github.com/sebastianbergmann/phpunit.git",
"reference": "3.7.24"
"reference": "939cb801b3b2aa253aedd0b279f40bb8f35cec91"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/sebastianbergmann/phpunit/zipball/3.7.24",
"reference": "3.7.24",
"url": "https://api.github.com/repos/sebastianbergmann/phpunit/zipball/939cb801b3b2aa253aedd0b279f40bb8f35cec91",
"reference": "939cb801b3b2aa253aedd0b279f40bb8f35cec91",
"shasum": ""
},
"require": {
"ext-dom": "*",
"ext-json": "*",
"ext-pcre": "*",
"ext-reflection": "*",
"ext-spl": "*",
"php": ">=5.3.3",
"phpunit/php-code-coverage": "~1.2.1",
"phpunit/php-file-iterator": ">=1.3.1",
"phpunit/php-text-template": ">=1.1.1",
"phpunit/php-timer": ">=1.0.4",
"phpunit/phpunit-mock-objects": "~1.2.0",
"phpunit/php-code-coverage": "~2.0",
"phpunit/php-file-iterator": "~1.3.1",
"phpunit/php-text-template": "~1.2",
"phpunit/php-timer": "~1.0.2",
"phpunit/phpunit-mock-objects": "~2.1",
"sebastian/comparator": "~1.0",
"sebastian/diff": "~1.1",
"sebastian/environment": "~1.0",
"sebastian/exporter": "~1.0",
"sebastian/version": "~1.0",
"symfony/yaml": "~2.0"
},
"require-dev": {
"pear-pear/pear": "1.9.4"
},
"suggest": {
"ext-json": "*",
"ext-simplexml": "*",
"ext-tokenizer": "*",
"phpunit/php-invoker": ">=1.1.0,<1.2.0"
"phpunit/php-invoker": "~1.1"
},
"bin": [
"composer/bin/phpunit"
"phpunit"
],
"type": "library",
"extra": {
"branch-alias": {
"dev-master": "3.7.x-dev"
"dev-master": "4.1.x-dev"
}
},
"autoload": {
"classmap": [
"PHPUnit/"
"src/"
]
},
"notification-url": "https://packagist.org/downloads/",
@@ -2273,33 +2395,41 @@
"testing",
"xunit"
],
"time": "2013-08-09 06:58:24"
"time": "2014-06-11 14:15:47"
},
{
"name": "phpunit/phpunit-mock-objects",
"version": "1.2.3",
"version": "2.1.4",
"source": {
"type": "git",
"url": "git://github.com/sebastianbergmann/phpunit-mock-objects.git",
"reference": "1.2.3"
"url": "https://github.com/sebastianbergmann/phpunit-mock-objects.git",
"reference": "1a894a16b6c15fcdc5ef2b110f0e6233952c9b0f"
},
"dist": {
"type": "zip",
"url": "https://github.com/sebastianbergmann/phpunit-mock-objects/archive/1.2.3.zip",
"reference": "1.2.3",
"url": "https://api.github.com/repos/sebastianbergmann/phpunit-mock-objects/zipball/1a894a16b6c15fcdc5ef2b110f0e6233952c9b0f",
"reference": "1a894a16b6c15fcdc5ef2b110f0e6233952c9b0f",
"shasum": ""
},
"require": {
"php": ">=5.3.3",
"phpunit/php-text-template": ">=1.1.1@stable"
"phpunit/php-text-template": "~1.2"
},
"require-dev": {
"phpunit/phpunit": "~4.1"
},
"suggest": {
"ext-soap": "*"
},
"type": "library",
"extra": {
"branch-alias": {
"dev-master": "2.1.x-dev"
}
},
"autoload": {
"classmap": [
"PHPUnit/"
"src/"
]
},
"notification-url": "https://packagist.org/downloads/",
@@ -2322,7 +2452,275 @@
"mock",
"xunit"
],
"time": "2013-01-13 10:24:48"
"time": "2014-06-07 16:22:57"
},
{
"name": "sebastian/comparator",
"version": "1.0.0",
"source": {
"type": "git",
"url": "https://github.com/sebastianbergmann/comparator.git",
"reference": "f7069ee51fa9fb6c038e16a9d0e3439f5449dcf2"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/sebastianbergmann/comparator/zipball/f7069ee51fa9fb6c038e16a9d0e3439f5449dcf2",
"reference": "f7069ee51fa9fb6c038e16a9d0e3439f5449dcf2",
"shasum": ""
},
"require": {
"php": ">=5.3.3",
"sebastian/diff": "~1.1",
"sebastian/exporter": "~1.0"
},
"require-dev": {
"phpunit/phpunit": "~4.1"
},
"type": "library",
"extra": {
"branch-alias": {
"dev-master": "1.0.x-dev"
}
},
"autoload": {
"classmap": [
"src/"
]
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"BSD-3-Clause"
],
"authors": [
{
"name": "Sebastian Bergmann",
"email": "sebastian@phpunit.de",
"role": "lead"
},
{
"name": "Jeff Welch",
"email": "whatthejeff@gmail.com"
},
{
"name": "Volker Dusch",
"email": "github@wallbash.com"
},
{
"name": "Bernhard Schussek",
"email": "bschussek@2bepublished.at"
}
],
"description": "Provides the functionality to compare PHP values for equality",
"homepage": "http://www.github.com/sebastianbergmann/comparator",
"keywords": [
"comparator",
"compare",
"equality"
],
"time": "2014-05-02 07:05:58"
},
{
"name": "sebastian/diff",
"version": "1.1.0",
"source": {
"type": "git",
"url": "https://github.com/sebastianbergmann/diff.git",
"reference": "1e091702a5a38e6b4c1ba9ca816e3dd343df2e2d"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/sebastianbergmann/diff/zipball/1e091702a5a38e6b4c1ba9ca816e3dd343df2e2d",
"reference": "1e091702a5a38e6b4c1ba9ca816e3dd343df2e2d",
"shasum": ""
},
"require": {
"php": ">=5.3.3"
},
"type": "library",
"extra": {
"branch-alias": {
"dev-master": "1.1-dev"
}
},
"autoload": {
"classmap": [
"src/"
]
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"BSD-3-Clause"
],
"authors": [
{
"name": "Sebastian Bergmann",
"email": "sebastian@phpunit.de",
"role": "lead"
},
{
"name": "Kore Nordmann",
"email": "mail@kore-nordmann.de"
}
],
"description": "Diff implementation",
"homepage": "http://www.github.com/sebastianbergmann/diff",
"keywords": [
"diff"
],
"time": "2013-08-03 16:46:33"
},
{
"name": "sebastian/environment",
"version": "1.0.0",
"source": {
"type": "git",
"url": "https://github.com/sebastianbergmann/environment.git",
"reference": "79517609ec01139cd7e9fded0dd7ce08c952ef6a"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/sebastianbergmann/environment/zipball/79517609ec01139cd7e9fded0dd7ce08c952ef6a",
"reference": "79517609ec01139cd7e9fded0dd7ce08c952ef6a",
"shasum": ""
},
"require": {
"php": ">=5.3.3"
},
"require-dev": {
"phpunit/phpunit": "4.0.*@dev"
},
"type": "library",
"extra": {
"branch-alias": {
"dev-master": "1.0.x-dev"
}
},
"autoload": {
"classmap": [
"src/"
]
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"BSD-3-Clause"
],
"authors": [
{
"name": "Sebastian Bergmann",
"email": "sebastian@phpunit.de",
"role": "lead"
}
],
"description": "Provides functionality to handle HHVM/PHP environments",
"homepage": "http://www.github.com/sebastianbergmann/environment",
"keywords": [
"Xdebug",
"environment",
"hhvm"
],
"time": "2014-02-18 16:17:19"
},
{
"name": "sebastian/exporter",
"version": "1.0.1",
"source": {
"type": "git",
"url": "https://github.com/sebastianbergmann/exporter.git",
"reference": "1f9a98e6f5dfe0524cb8c6166f7c82f3e9ae1529"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/sebastianbergmann/exporter/zipball/1f9a98e6f5dfe0524cb8c6166f7c82f3e9ae1529",
"reference": "1f9a98e6f5dfe0524cb8c6166f7c82f3e9ae1529",
"shasum": ""
},
"require": {
"php": ">=5.3.3"
},
"require-dev": {
"phpunit/phpunit": "4.0.*@dev"
},
"type": "library",
"extra": {
"branch-alias": {
"dev-master": "1.0.x-dev"
}
},
"autoload": {
"classmap": [
"src/"
]
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"BSD-3-Clause"
],
"authors": [
{
"name": "Sebastian Bergmann",
"email": "sebastian@phpunit.de",
"role": "lead"
},
{
"name": "Jeff Welch",
"email": "whatthejeff@gmail.com"
},
{
"name": "Volker Dusch",
"email": "github@wallbash.com"
},
{
"name": "Adam Harvey",
"email": "aharvey@php.net",
"role": "Lead"
},
{
"name": "Bernhard Schussek",
"email": "bschussek@2bepublished.at"
}
],
"description": "Provides the functionality to export PHP variables for visualization",
"homepage": "http://www.github.com/sebastianbergmann/exporter",
"keywords": [
"export",
"exporter"
],
"time": "2014-02-16 08:26:31"
},
{
"name": "sebastian/version",
"version": "1.0.3",
"source": {
"type": "git",
"url": "https://github.com/sebastianbergmann/version.git",
"reference": "b6e1f0cf6b9e1ec409a0d3e2f2a5fb0998e36b43"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/sebastianbergmann/version/zipball/b6e1f0cf6b9e1ec409a0d3e2f2a5fb0998e36b43",
"reference": "b6e1f0cf6b9e1ec409a0d3e2f2a5fb0998e36b43",
"shasum": ""
},
"type": "library",
"autoload": {
"classmap": [
"src/"
]
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"BSD-3-Clause"
],
"authors": [
{
"name": "Sebastian Bergmann",
"email": "sebastian@phpunit.de",
"role": "lead"
}
],
"description": "Library that helps with managing the version number of Git-hosted PHP projects",
"homepage": "https://github.com/sebastianbergmann/version",
"time": "2014-03-07 15:35:33"
}
],
"aliases": [

View File

@@ -32,6 +32,5 @@ if (!file_exists(THELIA_CONF_DIR . 'database.yml') && !defined('THELIA_INSTALL_M
} else {
$request = \Thelia\Core\HttpFoundation\Request::createFromGlobals();
header('Location: '.$request->getUriForPath('/install'));
exit;
}
}

View File

@@ -79,7 +79,7 @@ class Address extends BaseAction implements EventSubscriberInterface
->save()
;
if ($event->getIsDefault()) {
if ($event->getIsDefault() && !$addressModel->getIsDefault()) {
$addressModel->makeItDefault();
}

View File

@@ -109,6 +109,17 @@ class Coupon extends BaseAction implements EventSubscriberInterface
$this->createOrUpdateCondition($modelCoupon, $event);
}
/**
* Clear all coupons in session.
*/
public function clearAllCoupons()
{
// Tell coupons to clear any data they may have stored
$this->couponManager->clear();
$this->request->getSession()->setConsumedCoupons(array());
}
/**
* Occurring when a Coupon condition is about to be consumed
*
@@ -139,21 +150,22 @@ class Coupon extends BaseAction implements EventSubscriberInterface
$consumedCoupons[$event->getCode()] = $event->getCode();
$this->request->getSession()->setConsumedCoupons($consumedCoupons);
$totalDiscount = $this->couponManager->getDiscount();
$this->request
->getSession()
->getCart()
->setDiscount($totalDiscount)
->save();
$this->request
->getSession()
->getOrder()
->setDiscount($totalDiscount)
;
}
}
$totalDiscount = $this->couponManager->getDiscount();
$this->request
->getSession()
->getCart()
->setDiscount($totalDiscount)
->save();
$this->request
->getSession()
->getOrder()
->setDiscount($totalDiscount)
;
}
}
$event->setIsValid($isValid);
@@ -339,7 +351,8 @@ class Coupon extends BaseAction implements EventSubscriberInterface
}
}
$this->request->getSession()->setConsumedCoupons(array());
// Clear all coupons.
$event->getDispatcher()->dispatch(TheliaEvents::COUPON_CLEAR_ALL);
}
/**
@@ -368,6 +381,7 @@ class Coupon extends BaseAction implements EventSubscriberInterface
TheliaEvents::COUPON_CREATE => array("create", 128),
TheliaEvents::COUPON_UPDATE => array("update", 128),
TheliaEvents::COUPON_CONSUME => array("consume", 128),
TheliaEvents::COUPON_CLEAR_ALL => array("clearAllCoupons", 128),
TheliaEvents::COUPON_CONDITION_UPDATE => array("updateCondition", 128),
TheliaEvents::ORDER_SET_POSTAGE => array("testFreePostage", 132),
TheliaEvents::ORDER_BEFORE_PAYMENT => array("afterOrder", 128),

View File

@@ -0,0 +1,54 @@
<?php
/*************************************************************************************/
/* This file is part of the Thelia package. */
/* */
/* Copyright (c) OpenStudio */
/* email : dev@thelia.net */
/* web : http://www.thelia.net */
/* */
/* For the full copyright and license information, please view the LICENSE.txt */
/* file that was distributed with this source code. */
/*************************************************************************************/
namespace Thelia\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Thelia\Module\ModuleManagement;
/**
* Class ModuleRefreshCommand
* Refresh modules list
*
* @package Thelia\Command
* @author Jérôme Billiras <jbilliras@openstudio.fr>
*/
class ModuleRefreshCommand extends ContainerAwareCommand
{
protected function configure()
{
$this
->setName('module:refresh')
->setDescription('Refresh modules list');
}
protected function execute(InputInterface $input, OutputInterface $output)
{
try {
$moduleManagement = new ModuleManagement;
$moduleManagement->updateModules();
} catch (\Exception $e) {
throw new \RuntimeException(sprintf('Refresh modules list fail with Exception : [%d] %s', $e->getCode(), $e->getMessage()));
}
if (method_exists($output, 'renderBlock')) {
$output->renderBlock([
'',
'Modules list successfully refreshed',
''
],
'bg=green;fg=black'
);
}
}
}

View File

@@ -55,6 +55,8 @@ class StartDate extends ConditionAbstract
*/
public function setValidatorsFromForm(array $operators, array $values)
{
$this->checkComparisonOperatorValue($operators, self::START_DATE);
if (! isset($values[self::START_DATE])) {
$values[self::START_DATE] = time();
}
@@ -125,10 +127,6 @@ class StartDate extends ConditionAbstract
*/
public function getSummary()
{
$i18nOperator = Operators::getI18n(
$this->translator, $this->operators[self::START_DATE]
);
$date = new \DateTime();
$date->setTimestamp($this->values[self::START_DATE]);
$strDate = $date->format($this->getDateFormat());

View File

@@ -50,6 +50,7 @@ return array(
'Cart item count is' => 'Cart item count is',
'Cart total amount' => 'Cart total amount',
'Cart total amount is' => 'Cart total amount is',
'Catalog' => 'Catalog',
'Category title *' => 'Category title *',
'Cellphone' => 'Cellphone',
'Chapo' => 'Chapo',
@@ -85,7 +86,6 @@ return array(
'Description' => 'Description',
'Detailed description' => 'Detailed description',
'Disabled' => 'Disabled',
'Discount amount' => 'Discount amount',
'Document deleted successfully' => 'Document deleted successfully',
'Document position updated' => 'Document position updated',
'EAN Code' => 'EAN Code',
@@ -112,13 +112,18 @@ return array(
'First Name' => 'First Name',
'Firstname' => 'Firstname',
'Fixed Amount Discount' => 'Fixed Amount Discount',
'Fixed amount discount on selected categories' => 'Fixed amount discount on selected categories',
'Fixed amount discount for selected attribute values' => 'Fixed amount discount for selected attribute values',
'Fixed amount discount for selected categories' => 'Fixed amount discount for selected categories',
'Fixed amount discount for selected products' => 'Fixed amount discount for selected products',
'Folder' => 'Folder',
'Folder title *' => 'Folder title *',
'For one ore more customers' => 'For one ore more customers',
'Free product when buying one or more selected products' => 'Free product when buying one or more selected products',
'Full Name' => 'Full Name',
'Greater than' => 'Greater than',
'Greater than or equals' => 'Greater than or equals',
'HTML Message' => 'HTML Message',
'Home' => 'Home',
'Host' => 'Host',
'I would like to receive the newsletter or the latest news.' => 'I would like to receive the newsletter or the latest news.',
'ISO 4217 code *' => 'ISO 4217 code *',
@@ -190,13 +195,22 @@ return array(
'Password *' => 'Password *',
'Password confirmation' => 'Password confirmation',
'Per customer' => 'Per customer',
'Percent Discount' => 'Percent Discount',
'Percentage discount for selected attribute values' => 'Percentage discount for selected attribute values',
'Percentage discount for selected categories' => 'Percentage discount for selected categories',
'Percentage discount for selected products' => 'Percentage discount for selected products',
'Percentage of the product price' => 'Percentage of the product price',
'Phone' => 'Phone',
'Please accept the Terms and conditions in order to register.' => 'Please accept the Terms and conditions in order to register.',
'Please check your input: %error' => 'Please check your input: %error',
'Please enter your email address' => 'Please enter your email address',
'Please enter your password' => 'Please enter your password',
'Please select a category' => 'Please select a category',
'Please select an attribute' => 'Please select an attribute',
'Please select at least one attribute value' => 'Please select at least one attribute value',
'Please select at least one category' => 'Please select at least one category',
'Please select at least one product' => 'Please select at least one product',
'Please select the category of the offred product' => 'Please select the category of the offred product',
'Please select the offered product' => 'Please select the offered product',
'Please specify either \'path\' or \'file\' parameter in {url} function.' => 'Please specify either \'path\' or \'file\' parameter in {url} function.',
'Port' => 'Port',
'Post Scriptum' => 'Post Scriptum',
@@ -284,8 +298,14 @@ return array(
'This category is online.' => 'This category is online.',
'This condition is always true' => 'This condition is always true',
'This content is online.' => 'This content is online.',
'This coupon adds a free product to the cart if one of the selected products is in the cart.' => 'This coupon adds a free product to the cart if one of the selected products is in the cart.',
'This coupon does not exists' => 'This coupon does not exists',
'This coupon subtracts the specified amount from the order total for each product of the selected categories. If the discount is greater than the total order, the customer will only pay the shipping, or nothing if the coupon also provides free shipping.' => 'This coupon subtracts the specified amount from the order total for each product of the selected categories. If the discount is greater than the total order, the customer will only pay the shipping, or nothing if the coupon also provides free shipping.',
'This coupon subtracts from the order total a percentage of the price of each product which belongs to the selected categories. If the discount is greater than the total order, the customer will only pay the shipping, or nothing if the coupon also provides free shipping.' => 'This coupon subtracts from the order total a percentage of the price of each product which belongs to the selected categories. If the discount is greater than the total order, the customer will only pay the shipping, or nothing if the coupon also provides free shipping.',
'This coupon subtracts from the order total the specified percentage of each product price which uses the selected attribute values. If the discount is greater than the total order, the customer will only pay the shipping, or nothing if the coupon also provides free shipping.' => 'This coupon subtracts from the order total the specified percentage of each product price which uses the selected attribute values. If the discount is greater than the total order, the customer will only pay the shipping, or nothing if the coupon also provides free shipping.',
'This coupon subtracts from the order total the specified percentage of each selected product price. If the discount is greater than the total order, the customer will only pay the shipping, or nothing if the coupon also provides free shipping.' => 'This coupon subtracts from the order total the specified percentage of each selected product price. If the discount is greater than the total order, the customer will only pay the shipping, or nothing if the coupon also provides free shipping.',
'This coupon subtracts the specified amount from the order total for each product which belongs to the selected categories. If the discount is greater than the total order, the customer will only pay the shipping, or nothing if the coupon also provides free shipping.' => 'This coupon subtracts the specified amount from the order total for each product which belongs to the selected categories. If the discount is greater than the total order, the customer will only pay the shipping, or nothing if the coupon also provides free shipping.',
'This coupon subtracts the specified amount from the order total for each product which uses the selected attribute values. If the discount is greater than the total order, the customer will only pay the shipping, or nothing if the coupon also provides free shipping.' => 'This coupon subtracts the specified amount from the order total for each product which uses the selected attribute values. If the discount is greater than the total order, the customer will only pay the shipping, or nothing if the coupon also provides free shipping.',
'This coupon subtracts the specified amount from the order total for each selected product. If the discount is greater than the total order, the customer will only pay the shipping, or nothing if the coupon also provides free shipping.' => 'This coupon subtracts the specified amount from the order total for each selected product. If the discount is greater than the total order, the customer will only pay the shipping, or nothing if the coupon also provides free shipping.',
'This coupon will offert a flat percentage off a shopper\'s entire order (not applied to shipping costs or tax rates). If the discount is greater than the total order corst, the customer will only pay the shipping, or nothing if the coupon also provides free shipping.' => 'This coupon will offert a flat percentage off a shopper\'s entire order (not applied to shipping costs or tax rates). If the discount is greater than the total order corst, the customer will only pay the shipping, or nothing if the coupon also provides free shipping.',
'This coupon will subtracts a set amount from the total cost of an order. If the discount is greater than the total order corst, the customer will only pay the shipping, or nothing if the coupon also provides free shipping.' => 'This coupon will subtracts a set amount from the total cost of an order. If the discount is greater than the total order corst, the customer will only pay the shipping, or nothing if the coupon also provides free shipping.',
'This email already exists.' => 'This email already exists.',
@@ -316,6 +336,8 @@ return array(
'Username *' => 'Username *',
'Valid only from %date% to the coupon expiration date' => 'Valide à partir du %date% jusqu\'à la date d\'expiration',
'Value' => 'Value',
'Value %val for Discount Amount is invalid. Please enter a positive value.' => 'Value %val for Discount Amount is invalid. Please enter a positive value.',
'Value %val for Percent Discount is invalid. Please enter a positive value between 1 and 100.' => 'Value %val for Percent Discount is invalid. Please enter a positive value between 1 and 100.',
'Value *' => 'Value *',
'Warnings' => 'Warnings',
'Weight' => 'Weight',

View File

@@ -50,6 +50,7 @@ return array(
'Cart item count is' => 'Le nombre d\'articles dans le panier est',
'Cart total amount' => 'Montant total du panier',
'Cart total amount is' => 'Le total du panier est',
'Catalog' => 'Catalogue',
'Category title *' => 'Titre de la catégorie *',
'Cellphone' => 'Numéro de portable',
'Chapo' => 'Chapeau',
@@ -85,7 +86,6 @@ return array(
'Description' => 'Description',
'Detailed description' => 'Description détaillée',
'Disabled' => 'Désactivé',
'Discount amount' => 'Montant de la remise',
'Document deleted successfully' => 'Le document a été supprimé.',
'Document position updated' => 'La position du document a été modfiée',
'EAN Code' => 'Code EAN',
@@ -112,12 +112,18 @@ return array(
'First Name' => 'Prénom',
'Firstname' => 'Prénom',
'Fixed Amount Discount' => 'Remise d\'un montant fixe',
'Fixed amount discount for selected attribute values' => 'Remise constante pour certaines valeurs de déclinaison',
'Fixed amount discount for selected categories' => 'Remise fixe pour certaines catégories',
'Fixed amount discount for selected products' => 'Remise fixe pour certains produits',
'Folder' => 'Dossier',
'Folder title *' => 'Titre du dossier *',
'For one ore more customers' => 'Valable pour un ou plusieurs clients',
'Free product when buying one or more selected products' => 'Un produit offert pour l\'achat d\'un ou plusieurs produits',
'Full Name' => 'Nom complet',
'Greater than' => 'Supérieur à',
'Greater than or equals' => 'Supérieur ou égal à',
'HTML Message' => 'Message au format HTML',
'Home' => 'Accueil',
'Host' => 'Nom de l\'hôte',
'I would like to receive the newsletter or the latest news.' => 'Je souhaite recevoir la lettre d\'information ou les dernières actualités.',
'ISO 4217 code *' => 'Code ISO 4217 *',
@@ -189,19 +195,28 @@ return array(
'Password *' => 'Mot de passe *',
'Password confirmation' => 'Confirmation du mot de passe.',
'Per customer' => 'Par client',
'Percent Discount' => 'Remise en pourcentage de la commande',
'Percentage discount for selected attribute values' => 'Remise en pourcentage pour certaines valeurs de déclinaison',
'Percentage discount for selected categories' => 'Remise en pourcentage pour certaines catégories',
'Percentage discount for selected products' => 'Remise en pourcentage pour certains produits',
'Percentage of the product price' => 'Pourcentage du prix du produit',
'Phone' => 'Téléphone',
'Please accept the Terms and conditions in order to register.' => 'Veuillez accepter les termes et conditions pour vous inscrire.',
'Please check your input: %error' => 'Merci de vérifier votre saisie: %error',
'Please enter your email address' => 'Renseignez votre adresse mail',
'Please enter your password' => 'Entrez votre mot de passe.',
'Please select a category' => 'Merci de choisir une catégorie',
'Please select an attribute' => 'Merci de choisir une déclinaison',
'Please select at least one attribute value' => 'Merci de choisir au moins une valeur de déclinaison',
'Please select at least one category' => 'Merci de choisir au moins une catégorie.',
'Please select at least one product' => 'Merci de choisir au moins un produit',
'Please select the category of the offred product' => 'Merci de choisir la catégorie du produit offert',
'Please select the offered product' => 'Merci de choisir le produit offert',
'Please specify either \'path\' or \'file\' parameter in {url} function.' => 'Veuillez spécifier soit le paramètre \'chemin\' ou \'fichier\' dans la fonction {url}',
'Port' => 'Port',
'Post Scriptum' => 'Post-scriptum',
'Postage' => 'Frais de livraison',
'Preferred locale' => 'locale souhaitée',
'Prevent mailing template modification or deletion, except for super-admin' => 'Prévenir la suppression ou la modification ds templates de mail, excepté pour les super-administrateurs.',
'Prevent mailing template modification or deletion, except for super-admin' => 'Prévenir la suppression ou la modification des templates de mail, excepté pour les super-administrateurs.',
'Prevent variable modification or deletion, except for super-admin' => 'Prévenir la suppression ou la modification de variables, excepté pour les super-administrateurs.',
'Price currency *' => 'Devise *',
'Processing cancelation of payment for order ref. %ref' => 'Traitement de l\'annulation du paiement de la commande %ref, ID %id',
@@ -254,7 +269,7 @@ return array(
'Store configuration failed.' => 'Erreur de configuration du magasin.',
'Store email address' => 'Adresse mail du magasin',
'Store logs into text file' => 'Conserver les logs dans des fichiers texte',
'Store logs into text file, up to a certian size, then a new file is created' => 'Sauvegarder les logs dans un fichier texte. A partir d\'une certaine taille un nouveau fichier est crée',
'Store logs into text file, up to a certian size, then a new file is created' => 'Sauvegarder les logs dans un fichier texte. A partir d\'une certaine taille un nouveau fichier est créé',
'Store name' => 'Nom du magasin',
'Street Address' => 'Adresse',
'Street Address ' => 'Rue',
@@ -283,7 +298,14 @@ return array(
'This category is online.' => 'Cette catégorie est en ligne.',
'This condition is always true' => 'Cette condition est troujours vérifiée',
'This content is online.' => 'Ce contenu est en ligne.',
'This coupon adds a free product to the cart if one of the selected products is in the cart.' => 'Ce coupon ajoute un produit gratuit (sous forme de remise) au panier, si un des produits indiqués est présent dans le panier.',
'This coupon does not exists' => 'Ce code promo n\'existe pas',
'This coupon subtracts from the order total a percentage of the price of each product which belongs to the selected categories. If the discount is greater than the total order, the customer will only pay the shipping, or nothing if the coupon also provides free shipping.' => 'Ce code promo retire du total de la commande le pourcentage indiqué du prix de chacun des produits appartenant aux catégories sélectionnées. Si la remise est supérieure au total de la commande, seul le port sera dû, à moins que le code promo n\'offre aussi le port.',
'This coupon subtracts from the order total the specified percentage of each product price which uses the selected attribute values. If the discount is greater than the total order, the customer will only pay the shipping, or nothing if the coupon also provides free shipping.' => 'Ce code promo retire du total de la commande le pourcentage indiqué du prix de chacun des produits ayant au moins une des valeurs de déclinaisons indiquées. Si la remise est supérieure au total de la commande, seul le port sera dû, à moins que le code promo n\'offre aussi le port.',
'This coupon subtracts from the order total the specified percentage of each selected product price. If the discount is greater than the total order, the customer will only pay the shipping, or nothing if the coupon also provides free shipping.' => 'Ce code promo retire du total de la commande le pourcentage indiqué du prix de chacun des produits sélectionnés. Si la remise est supérieure au total de la commande, seul le port sera dû, à moins que le code promo n\'offre aussi le port.',
'This coupon subtracts the specified amount from the order total for each product which belongs to the selected categories. If the discount is greater than the total order, the customer will only pay the shipping, or nothing if the coupon also provides free shipping.' => 'Ce code promo retire le montant indiqué du total de la commande pour chacun des produits appartenant aux catégories sélectionnées. Si la remise est supérieure au total de la commande, seul le port sera dû, à moins que le code promo n\'offre aussi le port.',
'This coupon subtracts the specified amount from the order total for each product which uses the selected attribute values. If the discount is greater than the total order, the customer will only pay the shipping, or nothing if the coupon also provides free shipping.' => 'Ce code promo retire le montant indiqué du total de la commande pour chacun des produits ayant au moins une des valeurs de déclinaisons indiquées. Si la remise est supérieure au total de la commande, seul le port sera dû, à moins que le code promo n\'offre aussi le port.',
'This coupon subtracts the specified amount from the order total for each selected product. If the discount is greater than the total order, the customer will only pay the shipping, or nothing if the coupon also provides free shipping.' => 'Ce code promo retire le montant indiqué du total de la commande pour chacun des produits sélectionnés. Si la remise est supérieure au total de la commande, seul le port sera dû, à moins que le code promo n\'offre aussi le port.',
'This coupon will offert a flat percentage off a shopper\'s entire order (not applied to shipping costs or tax rates). If the discount is greater than the total order corst, the customer will only pay the shipping, or nothing if the coupon also provides free shipping.' => 'Ce code promo retire le pourcentage indiqué du total de la commande, hors frais de port et taxes. Si la remise est supérieur au total de la commande, seul le port sera facturé, à moins que le code promo n\'offre aussi les frais port.',
'This coupon will subtracts a set amount from the total cost of an order. If the discount is greater than the total order corst, the customer will only pay the shipping, or nothing if the coupon also provides free shipping.' => 'Ce code promo retire le montant indiqué du total de la commande, hors frais de port et taxes. Si la remise est supérieur au total de la commande, seul le port sera facturé, à moins que le code promo n\'offre aussi les frais port.',
'This email already exists.' => 'Cette adresse email existe déjà',
@@ -314,6 +336,8 @@ return array(
'Username *' => 'Nom d\'utilisateur *',
'Valid only from %date% to the coupon expiration date' => 'Valide à partir de %date% jusqu\'à la date d\'expoiration',
'Value' => 'Valeur',
'Value %val for Discount Amount is invalid. Please enter a positive value.' => 'La valeur %val pour le montant de la remise est invalide. Merci d\'indiquer une valeur positive.',
'Value %val for Percent Discount is invalid. Please enter a positive value between 1 and 100.' => 'La valeur %val pour le pourcentage de remise est invalide. Merci d\'indiquer un nombre entre 1 et 100',
'Value *' => 'Valeur *',
'Warnings' => 'Avertissements',
'Weight' => 'Poids',

View File

@@ -11,6 +11,7 @@
<command class="Thelia\Command\ModuleGenerateCommand"/>
<command class="Thelia\Command\ModuleGenerateModelCommand"/>
<command class="Thelia\Command\ModuleGenerateSqlCommand"/>
<command class="Thelia\Command\ModuleRefreshCommand"/>
<command class="Thelia\Command\ModuleActivateCommand"/>
<command class="Thelia\Command\ModuleDeactivateCommand"/>
<command class="Thelia\Command\CreateAdminUser"/>

View File

@@ -36,6 +36,41 @@
<tag name="thelia.coupon.addCoupon"/>
</service>
<service id="thelia.coupon.type.remove_percentage_on_categories" class="Thelia\Coupon\Type\RemovePercentageOnCategories">
<argument type="service" id="thelia.facade" />
<tag name="thelia.coupon.addCoupon"/>
</service>
<service id="thelia.coupon.type.remove_amount_on_products" class="Thelia\Coupon\Type\RemoveAmountOnProducts">
<argument type="service" id="thelia.facade" />
<tag name="thelia.coupon.addCoupon"/>
</service>
<service id="thelia.coupon.type.remove_percentage_on_products" class="Thelia\Coupon\Type\RemovePercentageOnProducts">
<argument type="service" id="thelia.facade" />
<tag name="thelia.coupon.addCoupon"/>
</service>
<service id="thelia.coupon.type.remove_percentage_on_products" class="Thelia\Coupon\Type\RemovePercentageOnProducts">
<argument type="service" id="thelia.facade" />
<tag name="thelia.coupon.addCoupon"/>
</service>
<service id="thelia.coupon.type.remove_amount_on_attribute_av" class="Thelia\Coupon\Type\RemoveAmountOnAttributeValues">
<argument type="service" id="thelia.facade" />
<tag name="thelia.coupon.addCoupon"/>
</service>
<service id="thelia.coupon.type.remove_percentage_on_attribute_av" class="Thelia\Coupon\Type\RemovePercentageOnAttributeValues">
<argument type="service" id="thelia.facade" />
<tag name="thelia.coupon.addCoupon"/>
</service>
<service id="thelia.coupon.type.free_product" class="Thelia\Coupon\Type\FreeProduct">
<argument type="service" id="thelia.facade" />
<tag name="thelia.coupon.addCoupon"/>
</service>
<!-- Condition module -->
<service id="thelia.condition.factory" class="Thelia\Condition\ConditionFactory">

View File

@@ -16,7 +16,7 @@
<default key="_controller">Thelia\Controller\Admin\HomeController::defaultAction</default>
</route>
<route id="admin.home.view" path="/admin/latest-thelia-version">
<route id="admin.home.latestVersion" path="/admin/latest-thelia-version">
<default key="_controller">Thelia\Controller\Admin\HomeController::getLatestTheliaVersion</default>
</route>
@@ -466,7 +466,7 @@
<default key="_controller">Thelia\Controller\Admin\ContentController::createAction</default>
</route>
<route id="admin.content.update" path="admin/content/update/{content_id}">
<route id="admin.content.update" path="/admin/content/update/{content_id}">
<default key="_controller">Thelia\Controller\Admin\ContentController::updateAction</default>
<requirement key="content_id">\d+</requirement>
</route>
@@ -1165,7 +1165,7 @@
</route>
<route id="export.customer.newsletter" path="/admin/export/customer/newsletter">
<default key="_controller">Thelia\Controller\Admin\CustomerExportController::NewsletterExportAction</default>
<default key="_controller">Thelia\Controller\Admin\CustomerExportController::newsletterExportAction</default>
</route>
<!-- The default route, to display a template -->

View File

@@ -0,0 +1,28 @@
<?xml version="1.0" encoding="UTF-8" ?>
<config xmlns="http://thelia.net/schema/dic/config"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://thelia.net/schema/dic/config http://thelia.net/schema/dic/config/thelia-1.0.xsd">
<parameters>
<parameter key="test.client.class">Thelia\Core\HttpKernel\Client</parameter>
<parameter key="test.client.parameters" type="collection"></parameter>
<parameter key="test.client.history.class">Symfony\Component\BrowserKit\History</parameter>
<parameter key="test.client.cookiejar.class">Symfony\Component\BrowserKit\CookieJar</parameter>
</parameters>
<services>
<service id="test.client" class="%test.client.class%" scope="prototype">
<argument type="service" id="kernel" />
<argument>%test.client.parameters%</argument>
<argument type="service" id="test.client.history" />
<argument type="service" id="test.client.cookiejar" />
</service>
<service id="test.client.history" class="%test.client.history.class%" scope="prototype" />
<service id="test.client.cookiejar" class="%test.client.cookiejar.class%" scope="prototype" />
</services>
</config>

View File

@@ -23,7 +23,6 @@ use Thelia\Model\ConfigQuery;
use Symfony\Component\HttpKernel\HttpKernelInterface;
use Thelia\Core\Security\Exception\AuthenticationException;
use Thelia\Tools\URL;
use Thelia\Tools\Redirect;
use Thelia\Model\AdminLog;
use Thelia\Model\LangQuery;

View File

@@ -169,7 +169,8 @@ class CategoryController extends AbstractSeoCrudController
return array(
'category_id' => $this->getRequest()->get('category_id', 0),
'folder_id' => $this->getRequest()->get('folder_id', 0),
'current_tab' => $this->getRequest()->get('current_tab', 'general')
'current_tab' => $this->getRequest()->get('current_tab', 'general'),
'page' => $this->getRequest()->get('page', 1)
);
}
@@ -182,14 +183,17 @@ class CategoryController extends AbstractSeoCrudController
array(
'category_order' => $currentOrder,
'product_order' => $product_order,
'category_id' => $this->getRequest()->get('category_id', 0)
'category_id' => $this->getRequest()->get('category_id', 0),
'page' => $this->getRequest()->get('page', 1)
));
}
protected function redirectToListTemplate()
{
$category_id = $this->getRequest()->get('category_id', 0);
$this->redirectToListTemplateWithId($category_id);
$this->redirectToRoute('admin.categories', array(
'category_id' => $this->getRequest()->get('category_id', 0),
'page' => $this->getRequest()->get('page', 1))
);
}
protected function redirectToListTemplateWithId($category_id)

View File

@@ -20,6 +20,7 @@ use Thelia\Core\Event\TheliaEvents;
use Thelia\Core\Security\AccessManager;
use Thelia\Form\CountryCreationForm;
use Thelia\Form\CountryModificationForm;
use Thelia\Log\Tlog;
use Thelia\Model\CountryQuery;
/**
@@ -228,7 +229,7 @@ class CountryController extends AbstractCrudController
public function toggleDefaultAction()
{
if (null !== $response = $this->checkAuth($this->resourceCode, array(), AccessManager::UPDATE)) return $response;
$content = null;
if (null !== $country_id = $this->getRequest()->get('country_id')) {
$toogleDefaultEvent = new CountryToggleDefaultEvent($country_id);
try {
@@ -238,7 +239,7 @@ class CountryController extends AbstractCrudController
return $this->nullResponse();
}
} catch (\Exception $ex) {
$content = $ex->getMessage();
Tlog::getInstance()->error($ex->getMessage());
}
}

View File

@@ -13,7 +13,7 @@
namespace Thelia\Controller\Admin;
use Symfony\Component\Form\Form;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Router;
use Thelia\Condition\ConditionFactory;
@@ -25,9 +25,7 @@ use Thelia\Core\Security\AccessManager;
use Thelia\Coupon\CouponFactory;
use Thelia\Coupon\CouponManager;
use Thelia\Condition\ConditionCollection;
use Thelia\Coupon\Type\CouponAbstract;
use Thelia\Coupon\Type\CouponInterface;
use Thelia\Coupon\Type\RemoveXPercent;
use Thelia\Form\CouponCreationForm;
use Thelia\Form\Exception\FormValidationException;
use Thelia\Log\Tlog;
@@ -37,6 +35,7 @@ use Thelia\Model\CouponModule;
use Thelia\Model\CouponQuery;
use Thelia\Model\LangQuery;
use Thelia\Tools\Rest\ResponseRest;
use Thelia\Tools\URL;
/**
* Control View and Action (Model) via Events
@@ -80,11 +79,13 @@ class CouponController extends BaseAdminController
$eventToDispatch = TheliaEvents::COUPON_CREATE;
if ($this->getRequest()->isMethod('POST')) {
$this->validateCreateOrUpdateForm(
if(null !== $response = $this->validateCreateOrUpdateForm(
$eventToDispatch,
'created',
'creation'
);
)){
return $response;
}
} else {
// If no input for expirationDate, now + 2 months
$defaultDate = new \DateTime();
@@ -139,12 +140,14 @@ class CouponController extends BaseAdminController
// Update
if ($this->getRequest()->isMethod('POST')) {
$this->validateCreateOrUpdateForm(
if (null !== $response = $this->validateCreateOrUpdateForm(
$eventToDispatch,
'updated',
'update',
$coupon
);
)) {
return $response;
}
} else {
// Display
// Prepare the data that will hydrate the form
@@ -199,6 +202,7 @@ class CouponController extends BaseAdminController
}
$args['couponCode'] = $coupon->getCode();
$args['couponType'] = $coupon->getType();
$args['availableCoupons'] = $this->getAvailableCoupons();
$args['couponInputsHtml'] = $couponManager->drawBackOfficeInputs();
$args['urlAjaxAdminCouponDrawInputs'] = $this->getRoute(
@@ -475,7 +479,7 @@ class CouponController extends BaseAdminController
{
// Create the form from the request
$couponForm = new CouponCreationForm($this->getRequest());
$response = null;
$message = false;
try {
// Check the form against conditions violations
@@ -499,20 +503,19 @@ class CouponController extends BaseAdminController
);
if ($this->getRequest()->get('save_mode') == 'stay') {
$this->redirect(
str_replace(
'{id}',
$couponEvent->getCouponModel()->getId(),
$couponForm->getSuccessUrl()
)
$response = RedirectResponse::create(str_replace(
'{id}',
$couponEvent->getCouponModel()->getId(),
$couponForm->getSuccessUrl()
));
} else {
// Redirect to the success URL
$response = RedirectResponse::create(
URL::getInstance()->absoluteUrl($this->getRoute('admin.coupon.list'))
);
exit();
}
// Redirect to the success URL
$this->redirectToRoute('admin.coupon.list');
} catch (FormValidationException $ex) {
// Invalid data entered
$message = $this->createStandardFormValidationErrorMessage($ex);
@@ -534,7 +537,7 @@ class CouponController extends BaseAdminController
->setGeneralError($message);
}
return $this;
return $response;
}
/**
@@ -577,7 +580,7 @@ class CouponController extends BaseAdminController
$condition['serviceId'] = $availableCoupon->getServiceId();
$condition['name'] = $availableCoupon->getName();
$condition['toolTip'] = $availableCoupon->getToolTip();
// $condition['inputName'] = $availableCoupon->getInputName();
$cleanedCoupons[] = $condition;
}
@@ -624,17 +627,23 @@ class CouponController extends BaseAdminController
return $response;
}
$this->checkXmlHttpRequest();
if (! empty($couponServiceId)) {
$this->checkXmlHttpRequest();
/** @var CouponInterface $coupon */
$couponManager = $this->container->get($couponServiceId);
/** @var CouponInterface $coupon */
$couponManager = $this->container->get($couponServiceId);
if (!$couponManager instanceof CouponInterface) {
$this->pageNotFound();
if (!$couponManager instanceof CouponInterface) {
$this->pageNotFound();
}
$response = new ResponseRest($couponManager->drawBackOfficeInputs());
} else {
// Return an empty response if the service ID is not defined
// Typically, when the user chooses "Please select a coupon type"
$response = new ResponseRest('');
}
$response = new ResponseRest($couponManager->drawBackOfficeInputs());
return $response;
}
@@ -676,35 +685,6 @@ class CouponController extends BaseAdminController
}
/**
* Add percentage logic if found in the Coupon post data
*
* @param array $effects Effect parameters to populate
* @param array $extendedInputNames Extended Inputs to manage
*
* @return array Populated effect with percentage
*/
protected function addExtendedLogic(array $effects, array $extendedInputNames)
{
/** @var Request $request */
$request = $this->container->get('request');
$postData = $request->request;
// Validate quantity input
if ($postData->has(RemoveXPercent::INPUT_EXTENDED__NAME)) {
$extentedPostData = $postData->get(RemoveXPercent::INPUT_EXTENDED__NAME);
foreach ($extendedInputNames as $extendedInputName) {
if (isset($extentedPostData[$extendedInputName])) {
$inputValue = $extentedPostData[$extendedInputName];
$effects[$extendedInputName] = $inputValue;
}
}
}
return $effects;
}
/**
* Feed the Coupon Create or Update event with the User inputs
*
@@ -718,16 +698,15 @@ class CouponController extends BaseAdminController
// Get the form field values
$data = $form->getData();
$serviceId = $data['type'];
/** @var CouponInterface $couponManager */
$couponManager = $this->container->get($serviceId);
$effects = [CouponAbstract::INPUT_AMOUNT_NAME => $data[CouponAbstract::INPUT_AMOUNT_NAME]];
$effects = $this->addExtendedLogic($effects, $couponManager->getExtendedInputs());
/** @var CouponInterface $coupon */
$coupon = $this->container->get($serviceId);
$couponEvent = new CouponCreateOrUpdateEvent(
$data['code'],
$serviceId,
$data['title'],
$effects,
$coupon->getEffects($data),
$data['shortDescription'],
$data['description'],
$data['isEnabled'],

View File

@@ -25,7 +25,7 @@ use Thelia\Model\NewsletterQuery;
class CustomerExportController extends BaseAdminController
{
public function NewsletterExportAction()
public function newsletterExportAction()
{
if (null !== $response = $this->checkAuth([AdminResources::EXPORT_CUSTOMER_NEWSLETTER], [], [AccessManager::VIEW])) {
return $response;

View File

@@ -31,10 +31,12 @@ use Thelia\Model\ContentDocument;
use Thelia\Model\ContentImage;
use Thelia\Model\FolderDocument;
use Thelia\Model\FolderImage;
use Thelia\Model\Lang;
use Thelia\Model\ProductDocument;
use Thelia\Model\ProductImage;
use Thelia\Tools\FileManager;
use Thelia\Tools\Rest\ResponseRest;
use Thelia\Tools\URL;
/**
* Created by JetBrains PhpStorm.
@@ -182,6 +184,7 @@ class FileController extends BaseAdminController
}
$documentModel->setParentId($parentId);
$documentModel->setLocale(Lang::getDefaultLanguage()->getLocale());
$documentModel->setTitle($fileBeingUploaded->getClientOriginalName());
$documentCreateOrUpdateEvent = new DocumentCreateOrUpdateEvent(
@@ -309,7 +312,8 @@ class FileController extends BaseAdminController
'imageId' => $imageId,
'imageType' => $parentType,
'redirectUrl' => $redirectUrl,
'formId' => $fileManager->getFormId($parentType, FileManager::FILE_TYPE_IMAGES)
'formId' => $fileManager->getFormId($parentType, FileManager::FILE_TYPE_IMAGES),
'breadcrumb' => $image->getBreadcrumb($this->getRouter($this->getCurrentRouter()), $this->container, 'images')
));
} catch (\Exception $e) {
$this->pageNotFound();
@@ -338,7 +342,8 @@ class FileController extends BaseAdminController
'documentId' => $documentId,
'documentType' => $parentType,
'redirectUrl' => $redirectUrl,
'formId' => $fileManager->getFormId($parentType, FileManager::FILE_TYPE_DOCUMENTS)
'formId' => $fileManager->getFormId($parentType, FileManager::FILE_TYPE_DOCUMENTS),
'breadcrumb' => $document->getBreadcrumb($this->getRouter($this->getCurrentRouter()), $this->container, 'documents')
));
} catch (\Exception $e) {
$this->pageNotFound();
@@ -389,7 +394,7 @@ class FileController extends BaseAdminController
$this->adminLogAppend(AdminResources::retrieve($parentType), AccessManager::UPDATE, sprintf('Image with Ref %s (ID %d) modified', $imageUpdated->getTitle(), $imageUpdated->getId()));
if ($this->getRequest()->get('save_mode') == 'close') {
$this->redirectToRoute('admin.images');
$this->redirect(URL::getInstance()->absoluteUrl($fileManager->getRedirectionUrl($parentType, $image->getParentId(), FileManager::FILE_TYPE_IMAGES)));
} else {
$this->redirectSuccess($imageModification);
}
@@ -466,7 +471,7 @@ class FileController extends BaseAdminController
$this->adminLogAppend(AdminResources::retrieve($parentType), AccessManager::UPDATE, sprintf('Document with Ref %s (ID %d) modified', $documentUpdated->getTitle(), $documentUpdated->getId()));
if ($this->getRequest()->get('save_mode') == 'close') {
$this->redirectToRoute('admin.documents');
$this->redirect(URL::getInstance()->absoluteUrl($fileManager->getRedirectionUrl($parentType, $document->getParentId(), FileManager::FILE_TYPE_DOCUMENTS)));
} else {
$this->redirectSuccess($documentModification);
}

View File

@@ -361,7 +361,8 @@ class ProductController extends AbstractSeoCrudController
'product_id' => $this->getRequest()->get('product_id', 0),
'folder_id' => $this->getRequest()->get('folder_id', 0),
'accessory_category_id' => $this->getRequest()->get('accessory_category_id', 0),
'current_tab' => $this->getRequest()->get('current_tab', 'general')
'current_tab' => $this->getRequest()->get('current_tab', 'general'),
'page' => $this->getRequest()->get('page', 1)
);
}
@@ -386,7 +387,8 @@ class ProductController extends AbstractSeoCrudController
return $this->render('categories',
array(
'product_order' => $currentOrder,
'category_id' => $this->getCategoryId()
'category_id' => $this->getCategoryId(),
'page' => $this->getRequest()->get('page', 1)
));
}
@@ -394,7 +396,10 @@ class ProductController extends AbstractSeoCrudController
{
$this->redirectToRoute(
'admin.products.default',
array('category_id' => $this->getCategoryId())
array(
'category_id' => $this->getCategoryId(),
'page' => $this->getRequest()->get('page', 1)
)
);
}
@@ -438,18 +443,6 @@ class ProductController extends AbstractSeoCrudController
);
}
protected function performAdditionalUpdateAction($updateEvent)
{
if ($this->getRequest()->get('save_mode') != 'stay') {
// Redirect to parent product list
$this->redirectToRoute(
'admin.categories.default',
array('category_id' => $this->getCategoryId())
);
}
}
protected function performAdditionalUpdatePositionAction($positionEvent)
{
// Redirect to parent product list

View File

@@ -181,13 +181,6 @@ class TranslationsController extends BaseAdminController
case 'ma' :
$template = new TemplateDefinition($item_name, TemplateDefinition::EMAIL);
break;
default:
/*
throw new \InvalidArgumentException(
$this->getTranslator()->trans("Undefined translation type: %item", ['%item' => $item_to_translate])
);
*/
}
if ($template) {

View File

@@ -291,7 +291,7 @@ abstract class BaseController extends ContainerAware
protected function getRouteFromRouter($routerName, $routeId, $parameters = array(), $referenceType = Router::ABSOLUTE_URL)
{
/** @var Router $router */
$router = $this->container->get($routerName);
$router = $this->getRouter($routerName);
if ($router == null) {
throw new \InvalidArgumentException(sprintf("Router '%s' does not exists.", $routerName));
@@ -300,6 +300,15 @@ abstract class BaseController extends ContainerAware
return $router->generate($routeId, $parameters, $referenceType);
}
/**
* @param $routerName
* @return Router
*/
protected function getRouter($routerName)
{
return $this->container->get($routerName);
}
/**
* Return a 404 error
* @throws \Symfony\Component\HttpKernel\Exception\NotFoundHttpException

View File

@@ -14,6 +14,7 @@ namespace Thelia\Core\Event\Cart;
use Thelia\Core\Event\ActionEvent;
use Thelia\Model\Cart;
use Thelia\Model\CartItem;
class CartEvent extends ActionEvent
{
@@ -31,7 +32,8 @@ class CartEvent extends ActionEvent
}
/**
* @param mixed $append
* @param bool $append
* @return CartEvent
*/
public function setAppend($append)
{
@@ -41,7 +43,7 @@ class CartEvent extends ActionEvent
}
/**
* @return mixed
* @return bool
*/
public function getAppend()
{
@@ -49,7 +51,8 @@ class CartEvent extends ActionEvent
}
/**
* @param mixed $cartItem
* @param CartItem $cartItem
* @return CartEvent
*/
public function setCartItem($cartItem)
{
@@ -59,7 +62,7 @@ class CartEvent extends ActionEvent
}
/**
* @return mixed
* @return CartItem
*/
public function getCartItem()
{
@@ -67,7 +70,8 @@ class CartEvent extends ActionEvent
}
/**
* @param mixed $newness
* @param bool $newness
* @return CartEvent
*/
public function setNewness($newness)
{
@@ -77,7 +81,7 @@ class CartEvent extends ActionEvent
}
/**
* @return mixed
* @return bool
*/
public function getNewness()
{
@@ -85,7 +89,8 @@ class CartEvent extends ActionEvent
}
/**
* @param mixed $product
* @param int $product the product ID
* @return CartEvent
*/
public function setProduct($product)
{
@@ -95,7 +100,7 @@ class CartEvent extends ActionEvent
}
/**
* @return mixed
* @return int the product ID
*/
public function getProduct()
{
@@ -103,7 +108,8 @@ class CartEvent extends ActionEvent
}
/**
* @param mixed $productSaleElementsId
* @param int $productSaleElementsId
* @return CartEvent
*/
public function setProductSaleElementsId($productSaleElementsId)
{
@@ -113,7 +119,7 @@ class CartEvent extends ActionEvent
}
/**
* @return mixed
* @return int
*/
public function getProductSaleElementsId()
{
@@ -121,7 +127,8 @@ class CartEvent extends ActionEvent
}
/**
* @param mixed $quantity
* @param int $quantity
* @return CartEvent
*/
public function setQuantity($quantity)
{
@@ -131,7 +138,7 @@ class CartEvent extends ActionEvent
}
/**
* @return mixed
* @return int
*/
public function getQuantity()
{

View File

@@ -14,7 +14,6 @@ namespace Thelia\Core\Event\Coupon;
use Thelia\Core\Event\ActionEvent;
use Thelia\Condition\ConditionCollection;
use Thelia\Model\Coupon;
use Thelia\Model\Exception\InvalidArgumentException;
/**
* Occurring when a Coupon is created or updated
@@ -327,10 +326,9 @@ class CouponCreateOrUpdateEvent extends ActionEvent
*/
public function setEffects(array $effects)
{
if (null === $effects['amount']) {
throw new InvalidArgumentException('Missing key \'amount\' in Coupon effect ready to be serialized array');
}
$this->amount = $effects['amount'];
// Amount is now optionnal.
$this->amount = isset($effects['amount']) ? $effects['amount'] : 0;
$this->effects = $effects;
}

View File

@@ -14,7 +14,6 @@ namespace Thelia\Core\Event;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
/**
* Class SessionEvent
* @package Thelia\Core\Event
@@ -71,5 +70,4 @@ class SessionEvent extends ActionEvent
return $this->session;
}
}
}

View File

@@ -464,6 +464,11 @@ final class TheliaEvents
*/
const COUPON_CONSUME = "action.consume_coupon";
/**
* Sent when all coupons in the current session should be cleared
*/
const COUPON_CLEAR_ALL = "action.clear_all_coupon";
/**
* Sent just before an attempt to use a Coupon
*/

View File

@@ -21,7 +21,6 @@ use Thelia\Core\HttpFoundation\Session\Session;
use Thelia\Core\TheliaKernelEvents;
use Thelia\Model\ConfigQuery;
/**
* Class SessionListener
* @package Thelia\Core\EventListener
@@ -79,4 +78,4 @@ class SessionListener implements EventSubscriberInterface
]
];
}
}
}

View File

@@ -25,7 +25,6 @@ use Thelia\Core\Template\Exception\ResourceNotFoundException;
use Thelia\Core\Template\TemplateHelper;
use Thelia\Exception\OrderException;
use Thelia\Tools\Redirect;
use Thelia\Core\Security\Exception\AuthenticationException;

View File

@@ -0,0 +1,43 @@
<?php
/*************************************************************************************/
/* This file is part of the Thelia package. */
/* */
/* Copyright (c) OpenStudio */
/* email : dev@thelia.net */
/* web : http://www.thelia.net */
/* */
/* For the full copyright and license information, please view the LICENSE.txt */
/* file that was distributed with this source code. */
/*************************************************************************************/
namespace Thelia\Core\HttpKernel;
use Symfony\Component\HttpKernel\Client as BaseClient;
use Thelia\Core\HttpFoundation\Request;
use Symfony\Component\BrowserKit\Request as DomRequest;
/**
* Class Client
* @package Thelia\Core\HttpKernel
* @author Manuel Raynaud <mraynaud@openstudio.fr>
*/
class Client extends BaseClient
{
/**
* Converts the BrowserKit request to a HttpKernel request.
*
* @param DomRequest $request A Request instance
*
* @return Request A Request instance
*/
protected function filterRequest(DomRequest $request)
{
$httpRequest = Request::create($request->getUri(), $request->getMethod(), $request->getParameters(), $request->getCookies(), $request->getFiles(), $request->getServer(), $request->getContent());
$httpRequest->files->replace($this->filterFiles($httpRequest->files->all()));
return $httpRequest;
}
}

View File

@@ -82,9 +82,9 @@ class Cart extends BaseLoop implements ArraySearchLoopInterface
public function parseResults(LoopResult $loopResult)
{
$taxCountry = $this->container->get('thelia.taxEngine')->getDeliveryCountry();
$locale = $this->request->getSession()->getLang()->getLocale();
foreach ($loopResult->getResultDataCollection() as $cartItem) {
$product = $cartItem->getProduct();
$product = $cartItem->getProduct(null, $locale);
$productSaleElement = $cartItem->getProductSaleElements();
$loopResultRow = new LoopResultRow();

View File

@@ -18,6 +18,7 @@ use Thelia\Core\Template\Element\LoopResult;
use Thelia\Core\Template\Element\LoopResultRow;
use Thelia\Core\Template\Element\PropelSearchLoopInterface;
use Thelia\Core\Template\Element\SearchLoopInterface;
use Thelia\Core\Template\Loop\Argument\ArgumentCollection;
use Thelia\Core\Template\Loop\Argument\Argument;
@@ -51,7 +52,7 @@ use Thelia\Model\ProductQuery;
* @author Manuel Raynaud <mraynaud@openstudio.fr>
* @author Etienne Roudeix <eroudeix@openstudio.fr>
*/
class Category extends BaseI18nLoop implements PropelSearchLoopInterface
class Category extends BaseI18nLoop implements PropelSearchLoopInterface, SearchLoopInterface
{
protected $timestampable = true;
protected $versionable = true;
@@ -83,6 +84,23 @@ class Category extends BaseI18nLoop implements PropelSearchLoopInterface
);
}
/**
* @return array of available field to search in
*/
public function getSearchIn()
{
return [
"title"
];
}
public function doSearch(&$search, $searchTerm, $searchIn, $searchCriteria)
{
$search->_and();
$search->where("CASE WHEN NOT ISNULL(`requested_locale_i18n`.ID) THEN `requested_locale_i18n`.`TITLE` ELSE `default_locale_i18n`.`TITLE` END ".$searchCriteria." ?", $searchTerm, \PDO::PARAM_STR);
}
public function buildModelCriteria()
{
$search = CategoryQuery::create();
@@ -172,9 +190,6 @@ class Category extends BaseI18nLoop implements PropelSearchLoopInterface
}
}
/* @todo */
$notEmpty = $this->getNot_empty();
return $search;
}

View File

@@ -18,6 +18,7 @@ use Thelia\Core\Template\Element\LoopResult;
use Thelia\Core\Template\Element\LoopResultRow;
use Thelia\Core\Template\Element\PropelSearchLoopInterface;
use Thelia\Core\Template\Element\SearchLoopInterface;
use Thelia\Core\Template\Loop\Argument\ArgumentCollection;
use Thelia\Core\Template\Loop\Argument\Argument;
@@ -37,7 +38,7 @@ use Thelia\Type\BooleanOrBothType;
* @package Thelia\Core\Template\Loop
* @author Etienne Roudeix <eroudeix@openstudio.fr>
*/
class Content extends BaseI18nLoop implements PropelSearchLoopInterface
class Content extends BaseI18nLoop implements PropelSearchLoopInterface, SearchLoopInterface
{
protected $timestampable = true;
protected $versionable = true;
@@ -60,7 +61,20 @@ class Content extends BaseI18nLoop implements PropelSearchLoopInterface
new Argument(
'order',
new TypeCollection(
new Type\EnumListType(array('alpha', 'alpha-reverse', 'manual', 'manual_reverse', 'random', 'given_id', 'created', 'created_reverse', 'updated', 'updated_reverse'))
new Type\EnumListType(
array(
'alpha',
'alpha-reverse',
'manual',
'manual_reverse',
'random',
'given_id',
'created',
'created_reverse',
'updated',
'updated_reverse'
)
)
),
'alpha'
),
@@ -69,6 +83,23 @@ class Content extends BaseI18nLoop implements PropelSearchLoopInterface
);
}
/**
* @return array of available field to search in
*/
public function getSearchIn()
{
return [
"title"
];
}
public function doSearch(&$search, $searchTerm, $searchIn, $searchCriteria)
{
$search->_and();
$search->where("CASE WHEN NOT ISNULL(`requested_locale_i18n`.ID) THEN `requested_locale_i18n`.`TITLE` ELSE `default_locale_i18n`.`TITLE` END ".$searchCriteria." ?", $searchTerm, \PDO::PARAM_STR);
}
public function buildModelCriteria()
{

View File

@@ -152,11 +152,6 @@ class Coupon extends BaseI18nLoop implements PropelSearchLoopInterface
/** @var ConditionFactory $conditionFactory */
$conditionFactory = $this->container->get('thelia.condition.factory');
/** @var Request $request */
$request = $this->container->get('request');
/** @var Lang $lang */
$lang = $request->getSession()->getLang();
/** @var MCoupon $coupon */
foreach ($loopResult->getResultDataCollection() as $coupon) {

View File

@@ -237,7 +237,7 @@ class Document extends BaseI18nLoop implements PropelSearchLoopInterface
$loopResultRow
->set("ID" , $result->getId())
->set("LOCALE" , $this->locale)
->set("DOCUMENT_URL" , $event->getFileUrl())
->set("DOCUMENT_URL" , $event->getDocumentUrl())
->set("DOCUMENT_PATH" , $event->getDocumentPath())
->set("ORIGINAL_DOCUMENT_PATH", $source_filepath)
->set("TITLE" , $result->getVirtualColumn('i18n_TITLE'))

View File

@@ -18,6 +18,7 @@ use Thelia\Core\Template\Element\LoopResult;
use Thelia\Core\Template\Element\LoopResultRow;
use Thelia\Core\Template\Element\PropelSearchLoopInterface;
use Thelia\Core\Template\Element\SearchLoopInterface;
use Thelia\Core\Template\Loop\Argument\ArgumentCollection;
use Thelia\Core\Template\Loop\Argument\Argument;
@@ -33,7 +34,7 @@ use Thelia\Type\BooleanOrBothType;
* @package Thelia\Core\Template\Loop
* @author Etienne Roudeix <eroudeix@openstudio.fr>
*/
class Folder extends BaseI18nLoop implements PropelSearchLoopInterface
class Folder extends BaseI18nLoop implements PropelSearchLoopInterface, SearchLoopInterface
{
protected $timestampable = true;
protected $versionable = true;
@@ -62,6 +63,23 @@ class Folder extends BaseI18nLoop implements PropelSearchLoopInterface
);
}
/**
* @return array of available field to search in
*/
public function getSearchIn()
{
return [
"title"
];
}
public function doSearch(&$search, $searchTerm, $searchIn, $searchCriteria)
{
$search->_and();
$search->where("CASE WHEN NOT ISNULL(`requested_locale_i18n`.ID) THEN `requested_locale_i18n`.`TITLE` ELSE `default_locale_i18n`.`TITLE` END ".$searchCriteria." ?", $searchTerm, \PDO::PARAM_STR);
}
public function buildModelCriteria()
{
$search = FolderQuery::create();
@@ -139,9 +157,6 @@ class Folder extends BaseI18nLoop implements PropelSearchLoopInterface
}
}
/* @todo */
$notEmpty = $this->getNot_empty();
return $search;
}

View File

@@ -41,7 +41,8 @@ class OrderProduct extends BaseLoop implements PropelSearchLoopInterface
protected function getArgDefinitions()
{
return new ArgumentCollection(
Argument::createIntTypeArgument('order', null, true)
Argument::createIntTypeArgument('order', null, true),
Argument::createIntListTypeArgument('id')
);
}
@@ -58,6 +59,10 @@ class OrderProduct extends BaseLoop implements PropelSearchLoopInterface
$search->filterByOrderId($order, Criteria::EQUAL);
if (null !== $this->getId()) {
$search->filterById($this->getId(), Criteria::IN);
}
$search->orderById(Criteria::ASC);
return $search;

View File

@@ -43,18 +43,7 @@ class Assets extends AbstractSmartyPlugin
public function blockJavascripts($params, $content, \Smarty_Internal_Template $template, &$repeat)
{
try {
return $this->assetManager->processSmartyPluginCall('js', $params, $content, $template, $repeat);
} catch (\Exception $e) {
$catchException = $this->getNormalizedParam($params, array('catchException'));
if ($catchException == "true") {
$repeat = false;
return null;
} else {
throw $e;
}
}
return $this->assetManager->processSmartyPluginCall('js', $params, $content, $template, $repeat);
}
public function blockImages($params, $content, \Smarty_Internal_Template $template, &$repeat)

View File

@@ -402,7 +402,7 @@ class DataAccessFunctions extends AbstractSmartyPlugin
return $noGetterData[$keyAttribute];
}
$getter = sprintf("get%s", ucfirst($attribute));
$getter = sprintf("get%s", $this->underscoreToCamelcase($attribute));
if (method_exists($data, $getter)) {
$return = $data->$getter();
@@ -427,6 +427,27 @@ class DataAccessFunctions extends AbstractSmartyPlugin
return '';
}
/**
* Transcode an underscored string into a camel-cased string, eg. default_folder into DefaultFolder
*
* @param string $str the string to convert from underscore to camel-case
*
* @return string the camel cased string.
*/
private function underscoreToCamelcase($str)
{
// Split string in words.
$words = explode('_', strtolower($str));
$return = '';
foreach ($words as $word) {
$return .= ucfirst(trim($word));
}
return $return;
}
/**
* Define the various smarty plugins hendled by this class
*

View File

@@ -50,6 +50,7 @@ class Format extends AbstractSmartyPlugin
*
* ex :
* {format_date date=$dateTimeObject format="Y-m-d H:i:s"} will output the format with specific format
* {format_date date=$dateTimeObject format="%e %B %Y" locale="fr_FR"} will output the format with specific format (see strftime() function)
* {format_date date=$dateTimeObject output="date"} will output the date using the default date system format
* {format_date date=$dateTimeObject} will output with the default datetime system format
*
@@ -86,7 +87,32 @@ class Format extends AbstractSmartyPlugin
$format = DateTimeFormat::getInstance($this->request)->getFormat($this->getParam($params, "output", null));
}
return $date->format($format);
$locale = $this->getParam($params,'locale', false);
if (false === $locale) {
$value = $date->format($format);
} else {
$value = $this->formatDateWithLocale($date, $locale, $format);
}
return $value;
}
private function formatDateWithLocale(\DateTime $date, $locale, $format)
{
if (function_exists('setlocale')) {
// Save the current locale
$systemLocale = setlocale('LC_TIME', 0);
setlocale('LC_TIME', $locale);
$localizedDate = strftime($format, $date->getTimestamp());
// Restore the locale
setlocale('LC_TIME', $systemLocale);
return $localizedDate;
} else {
// setlocale() function not available => error
throw new SmartyPluginException("The setlocale() function is not available on your system.");
}
}
/**

View File

@@ -47,20 +47,26 @@ class Translation extends AbstractSmartyPlugin
*/
public function translate($params, &$smarty)
{
// All parameters other than 'l' and 'd' are supposed to be variables. Build an array of var => value pairs
// All parameters other than 'l' and 'd' and 'js' are supposed to be variables. Build an array of var => value pairs
// and pass it to the translator
$vars = array();
foreach ($params as $name => $value) {
if ($name != 'l' && $name != 'd') $vars["%$name"] = $value;
if ($name != 'l' && $name != 'd' && $name != 'js') $vars["%$name"] = $value;
}
return $this->translator->trans(
$str = $this->translator->trans(
$this->getParam($params, 'l'),
$vars,
$this->getParam($params, 'd', $this->defaultTranslationDomain)
);
}
if ($this->getParam($params, 'js', 0)) {
$str = preg_replace("/(['\"])/", "\\\\$1", $str);
}
return $str;
}
/**
* Define the various smarty plugins handled by this class

View File

@@ -152,9 +152,9 @@ class UrlGenerator extends AbstractSmartyPlugin
protected function getNavigateToValues()
{
return array(
"current" => "getCurrentUrl",
"return_to" => "getReturnToUrl",
"index" => "getIndexUrl",
"current" => "getCurrentUrl",
"previous" => "getPreviousUrl",
"index" => "getIndexUrl",
);
}
@@ -167,7 +167,7 @@ class UrlGenerator extends AbstractSmartyPlugin
$navigateToValues = $this->getNavigateToValues();
if (!array_key_exists($to, $navigateToValues)) {
throw new \InvalidArgumentException("Incorrect value for parameter `to` in `navigate` substitution.");
throw new \InvalidArgumentException(sprintf("Incorrect value `%s` for parameter `to` in `navigate` substitution.", $to));
}
return $navigateToValues[$to];
@@ -178,7 +178,7 @@ class UrlGenerator extends AbstractSmartyPlugin
return $this->request->getUri();
}
protected function getReturnToUrl()
protected function getPreviousUrl()
{
return URL::getInstance()->absoluteUrl($this->request->getSession()->getReturnToUrl());
}

View File

@@ -60,13 +60,13 @@ class TemplateHelper
$tplVar = 'active-front-template';
break;
case TemplateDefinition::BACK_OFFICE:
$tplVar = 'active-front-template';
$tplVar = 'active-admin-template';
break;
case TemplateDefinition::PDF:
$tplVar = 'active-front-template';
$tplVar = 'active-pdf-template';
break;
case TemplateDefinition::EMAIL:
$tplVar = 'active-front-template';
$tplVar = 'active-mail-template';
break;
}

View File

@@ -21,35 +21,33 @@ namespace Thelia\Core;
* @author Manuel Raynaud <mraynaud@openstudio.fr>
*/
use Propel\Runtime\Connection\ConnectionManagerSingle;
use Propel\Runtime\Connection\ConnectionWrapper;
use Propel\Runtime\Propel;
use Symfony\Component\Config\FileLocator;
use Symfony\Component\Config\Loader\LoaderInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Definition;
use Symfony\Component\DependencyInjection\ParameterBag\ParameterBag;
use Symfony\Component\DependencyInjection\Reference;
use Symfony\Component\Finder\Finder;
use Symfony\Component\HttpKernel\Kernel;
use Symfony\Component\Config\Loader\LoaderInterface;
use Symfony\Component\Yaml\Yaml;
use Symfony\Component\DependencyInjection\ParameterBag\ParameterBag;
use Thelia\Core\Event\TheliaEvents;
use Thelia\Config\DatabaseConfiguration;
use Thelia\Config\DefinePropel;
use Thelia\Core\DependencyInjection\Loader\XmlFileLoader;
use Thelia\Core\Event\TheliaEvents;
use Thelia\Core\Template\ParserInterface;
use Thelia\Core\Template\TemplateDefinition;
use Thelia\Core\DependencyInjection\Loader\XmlFileLoader;
use Symfony\Component\Config\FileLocator;
use Propel\Runtime\Propel;
use Propel\Runtime\Connection\ConnectionManagerSingle;
use Thelia\Core\Template\TemplateHelper;
use Thelia\Log\Tlog;
use Thelia\Model\Module;
use Thelia\Model\ModuleQuery;
class Thelia extends Kernel
{
const THELIA_VERSION = '2.0.1';
const THELIA_VERSION = '2.0.2';
public function init()
{
@@ -143,7 +141,7 @@ class Thelia extends Kernel
}
}
} catch (\UnexpectedValueException $ex) {
// The directory does not exists, ignore it.
// The directory does not exists, ignore it.
}
}
@@ -162,12 +160,13 @@ class Thelia extends Kernel
->depth(0)
->in(THELIA_ROOT . "/core/lib/Thelia/Config/Resources");
/** @var \SplFileInfo $file */
foreach ($finder as $file) {
$loader->load($file->getBaseName());
}
if (defined("THELIA_INSTALL_MODE") === false) {
$modules = \Thelia\Model\ModuleQuery::getActivated();
$modules = ModuleQuery::getActivated();
$translationDirs = array();
@@ -233,12 +232,16 @@ class Thelia extends Kernel
$translationDirs[$module->getFrontOfficeTemplateTranslationDomain($template->getName())] =
$module->getAbsoluteFrontOfficeI18nTemplatePath($template->getName());
}
$this->addStandardModuleTemplatesToParserEnvironment($parser, $module);
} catch (\InvalidArgumentException $e) {
Tlog::getInstance()->addError(
sprintf("Failed to load module %s: %s", $module->getCode(), $e->getMessage()), $e
);
throw $e;
}
}

View File

@@ -20,7 +20,6 @@ use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpKernel\Controller\ControllerResolverInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Symfony\Component\HttpFoundation\Session;
use Thelia\Core\Event\Currency\CurrencyChangeEvent;
use Thelia\Core\Event\SessionEvent;

View File

@@ -12,7 +12,6 @@
namespace Thelia\Core;
/**
* Class TheliaKernelEvents
* @package Thelia\Core
@@ -23,4 +22,4 @@ final class TheliaKernelEvents
const SESSION = "thelia_kernel.session";
}
}

View File

@@ -14,7 +14,6 @@ namespace Thelia\Core\Translation;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\Translation\Translator as BaseTranslator;
use Thelia\Log\Tlog;
class Translator extends BaseTranslator
{
@@ -74,14 +73,9 @@ class Translator extends BaseTranslator
$this->loadCatalogue($locale);
}
if (! $this->catalogues[$locale]->has((string) $id, $domain)) {
}
if ($this->catalogues[$locale]->has((string) $id, $domain)) {
return parent::trans($id, $parameters, $domain, $locale);
} else {
//Tlog::getInstance()->addWarning("Undefined translation: locale: $locale, domain: $domain, ID: $id");
if ($return_default_if_not_available)
return strtr($id, $parameters);

View File

@@ -21,6 +21,7 @@ use Thelia\Core\HttpFoundation\Request;
use Thelia\Core\Template\ParserInterface;
use Thelia\Core\Template\TemplateHelper;
use Thelia\Model\AddressQuery;
use Thelia\Model\Country;
use Thelia\Model\Coupon;
use Thelia\Model\CouponQuery;
use Thelia\Cart\CartTrait;
@@ -118,17 +119,43 @@ class BaseFacade implements FacadeInterface
*
* @return float
*/
public function getCartTotalPrice()
public function getCartTotalPrice($withItemsInPromo = true)
{
return $this->getRequest()->getSession()->getCart()->getTotalAmount();
$total = 0;
$cartItems = $this->getRequest()->getSession()->getCart()->getCartItems();
foreach ($cartItems as $cartItem) {
if ($withItemsInPromo || ! $cartItem->getPromo()) {
$total += $cartItem->getRealPrice() * $cartItem->getQuantity();
}
}
return $total;
}
public function getCartTotalTaxPrice()
public function getCartTotalTaxPrice($withItemsInPromo = true)
{
$taxCountry = $this->getContainer()->get('thelia.taxEngine')->getDeliveryCountry();
$cartItems = $this->getRequest()->getSession()->getCart()->getCartItems();
return $this->getCart()->getTaxedAmount($taxCountry, false);
$total = 0;
foreach ($cartItems as $cartItem) {
if ($withItemsInPromo || ! $cartItem->getPromo()) {
$total += $cartItem->getRealTaxedPrice($taxCountry) * $cartItem->getQuantity();
}
}
return $total;
}
/**
* @return Country the delivery country
*/
public function getDeliveryCountry()
{
return $this->getContainer()->get('thelia.taxEngine')->getDeliveryCountry();
}
/**

View File

@@ -69,7 +69,7 @@ class CouponFactory
}
// Check coupon usage count
if ($couponModel->getUsagesLeft($this->facade->getCustomer()->getId()) <= 0) {
if (! $couponModel->isUsageUnlimited() && $couponModel->getUsagesLeft($this->facade->getCustomer()->getId()) <= 0) {
throw new CouponNoUsageLeftException($couponCode);
}

View File

@@ -58,14 +58,15 @@ class CouponManager
/**
* Get Discount for the given Coupons
*
* @api
* @return float checkout discount
*/
public function getDiscount()
{
$discount = 0.00;
$coupons = $this->facade->getCurrentCoupons();
if (count($coupons) > 0) {
$couponsKept = $this->sortCoupons($coupons);
@@ -73,6 +74,7 @@ class CouponManager
// Just In Case test
$checkoutTotalPrice = $this->facade->getCartTotalTaxPrice();
if ($discount >= $checkoutTotalPrice) {
$discount = $checkoutTotalPrice;
}
@@ -83,6 +85,9 @@ class CouponManager
/**
* Check if there is a Coupon removing Postage
*
* @param Order $order the order for which we have to check if postage is free
*
* @return bool
*/
public function isCouponRemovingPostage(Order $order)
@@ -266,6 +271,19 @@ class CouponManager
return $this->availableConditions;
}
/**
* Clear all data kept by coupons
*/
public function clear()
{
$coupons = $this->facade->getCurrentCoupons();
/** @var CouponInterface $coupon */
foreach ($coupons as $coupon) {
$coupon->clear();
}
}
/**
* Decrement this coupon quantity
*
@@ -278,57 +296,61 @@ class CouponManager
*/
public function decrementQuantity(Coupon $coupon, $customerId = null)
{
$ret = false;
if ($coupon->isUsageUnlimited()) {
$ret = true;
} else {
$ret = false;
try {
try {
$usageLeft = $coupon->getUsagesLeft($customerId);
$usageLeft = $coupon->getUsagesLeft($customerId);
if ($usageLeft > 0) {
if ($usageLeft > 0) {
// If the coupon usage is per user, add an entry to coupon customer usage count table
if ($coupon->getPerCustomerUsageCount()) {
// If the coupon usage is per user, add an entry to coupon customer usage count table
if ($coupon->getPerCustomerUsageCount()) {
if (null == $customerId) {
throw new \LogicException("Customer should not be null at this time.");
}
if (null == $customerId) {
throw new \LogicException("Customer should not be null at this time.");
}
$ccc = CouponCustomerCountQuery::create()
->filterByCouponId($coupon->getId())
->filterByCustomerId($customerId)
->findOne()
;
$ccc = CouponCustomerCountQuery::create()
->filterByCouponId($coupon->getId())
->filterByCustomerId($customerId)
->findOne()
;
if ($ccc === null) {
$ccc = new CouponCustomerCount();
if ($ccc === null) {
$ccc = new CouponCustomerCount();
$ccc
->setCustomerId($customerId)
->setCouponId($coupon->getId())
->setCount(0);
}
$newCount = 1 + $ccc->getCount();
$ccc
->setCustomerId($customerId)
->setCouponId($coupon->getId())
->setCount(0);
->setCount($newCount)
->save()
;
$ret = $usageLeft - $newCount;
} else {
$usageLeft--;
$coupon->setMaxUsage($usageLeft);
$coupon->save();
$ret = $usageLeft;
}
$newCount = 1 + $ccc->getCount();
$ccc
->setCount($newCount)
->save()
;
$ret = $usageLeft - $newCount;
} else {
$usageLeft--;
$coupon->setMaxUsage($usageLeft);
$coupon->save();
$ret = $usageLeft;
}
} catch (\Exception $ex) {
// Just log the problem.
Tlog::getInstance()->addError(sprintf("Failed to decrement coupon %s: %s", $coupon->getCode(), $ex->getMessage()));
}
} catch (\Exception $ex) {
// Just log the problem.
Tlog::getInstance()->addError(sprintf("Failed to decrement coupon %s: %s", $coupon->getCode(), $ex->getMessage()));
}
return $ret;

View File

@@ -18,6 +18,7 @@ use Symfony\Component\Translation\TranslatorInterface;
use Thelia\Condition\ConditionEvaluator;
use Thelia\Core\HttpFoundation\Request;
use Thelia\Core\Template\ParserInterface;
use Thelia\Model\Country;
use Thelia\Model\Coupon;
/**
@@ -51,6 +52,11 @@ interface FacadeInterface
*/
public function getDeliveryAddress();
/**
* @return Country the delivery country
*/
public function getDeliveryCountry();
/**
* Return an Customer a CouponManager can process
*
@@ -68,17 +74,19 @@ interface FacadeInterface
/**
* Return Products total price
* CartTotalPrice = Checkout total - discount - postage
* @param bool $withItemsInPromo true (default) if item in promotion should be included in the total, false otherwise.
*
* @return float
*/
public function getCartTotalPrice();
public function getCartTotalPrice($withItemsInPromo = true);
/**
* Return Product total tax price
* @param bool $withItemsInPromo true (default) if item in promotion should be included in the total, false otherwise.
*
* @return float
*/
public function getCartTotalTaxPrice();
public function getCartTotalTaxPrice($withItemsInPromo = true);
/**
* Return the Checkout currency EUR|USD

View File

@@ -0,0 +1,128 @@
<?php
/*************************************************************************************/
/* This file is part of the Thelia package. */
/* */
/* Copyright (c) OpenStudio */
/* email : dev@thelia.net */
/* web : http://www.thelia.net */
/* */
/* For the full copyright and license information, please view the LICENSE.txt */
/* file that was distributed with this source code. */
/*************************************************************************************/
namespace Thelia\Coupon\Type;
use Thelia\Coupon\FacadeInterface;
use Thelia\Model\CartItem;
/**
* Allow to remove an amount from the checkout total
*
* @package Coupon
* @author Franck Allimant <franck@cqfdev.fr>
*/
abstract class AbstractRemove extends CouponAbstract implements AmountAndPercentageCouponInterface
{
/**
* Set the value of specific coupon fields.
*
* @param Array $effects the Coupon effects params
*/
abstract public function setFieldsValue($effects);
/**
* Get the discount for a specific cart item.
*
* @param CartItem $cartItem the cart item
* @return float the discount value
*/
abstract public function getCartItemDiscount($cartItem);
/**
* @inheritdoc
*/
public function set(
FacadeInterface $facade,
$code,
$title,
$shortDescription,
$description,
array $effects,
$isCumulative,
$isRemovingPostage,
$isAvailableOnSpecialOffers,
$isEnabled,
$maxUsage,
\DateTime $expirationDate,
$freeShippingForCountries,
$freeShippingForModules,
$perCustomerUsageCount
)
{
parent::set(
$facade, $code, $title, $shortDescription, $description, $effects,
$isCumulative, $isRemovingPostage, $isAvailableOnSpecialOffers, $isEnabled, $maxUsage, $expirationDate,
$freeShippingForCountries,
$freeShippingForModules,
$perCustomerUsageCount
);
$this->setFieldsValue($effects);
return $this;
}
/**
* @inheritdoc
*/
public function exec()
{
// This coupon subtracts the specified amount from the order total
// for each product of the selected categories.
$discount = 0;
$cartItems = $this->facade->getCart()->getCartItems();
/** @var CartItem $cartItem */
foreach ($cartItems as $cartItem) {
if (! $cartItem->getPromo() || $this->isAvailableOnSpecialOffers()) {
$categories = $cartItem->getProduct()->getCategories();
/** @var Category $category */
foreach ($categories as $category) {
if (in_array($category->getId(), $this->category_list)) {
$discount += $this->getCartItemDiscount($cartItem);
break;
}
}
}
}
return $discount;
}
/**
* @inheritdoc
*/
public function drawBaseBackOfficeInputs($templateName, $otherFields)
{
return $this->facade->getParser()->render($templateName, $otherFields);
}
/**
* @inheritdoc
*/
public function getBaseFieldList($otherFields)
{
return array_merge($otherFields);
}
/**
* @inheritdoc
*/
public function checkBaseCouponFieldValue($fieldName, $fieldValue)
{
return $fieldValue;
}
}

View File

@@ -0,0 +1,180 @@
<?php
/*************************************************************************************/
/* This file is part of the Thelia package. */
/* */
/* Copyright (c) OpenStudio */
/* email : dev@thelia.net */
/* web : http://www.thelia.net */
/* */
/* For the full copyright and license information, please view the LICENSE.txt */
/* file that was distributed with this source code. */
/*************************************************************************************/
namespace Thelia\Coupon\Type;
use Thelia\Core\Translation\Translator;
use Thelia\Coupon\FacadeInterface;
use Thelia\Model\AttributeCombination;
use Thelia\Model\CartItem;
/**
* The base class to process a discount related to Attribute values.
*
* @package Coupon
* @author Franck Allimant <franck@cqfdev.fr>
*/
abstract class AbstractRemoveOnAttributeValues extends CouponAbstract implements AmountAndPercentageCouponInterface
{
const ATTRIBUTES_AV_LIST = 'attribute_avs';
const ATTRIBUTE = 'attribute_id';
public $attributeAvList = array();
public $attribute = 0;
/**
* Set the value of specific coupon fields.
* @param Array $effects the Coupon effects params
*/
abstract public function setFieldsValue($effects);
/**
* Get the discount for a specific cart item.
*
* @param CartItem $cartItem the cart item
* @return float the discount value
*/
abstract public function getCartItemDiscount($cartItem);
/**
* @inheritdoc
*/
public function set(
FacadeInterface $facade,
$code,
$title,
$shortDescription,
$description,
array $effects,
$isCumulative,
$isRemovingPostage,
$isAvailableOnSpecialOffers,
$isEnabled,
$maxUsage,
\DateTime $expirationDate,
$freeShippingForCountries,
$freeShippingForModules,
$perCustomerUsageCount
)
{
parent::set(
$facade, $code, $title, $shortDescription, $description, $effects,
$isCumulative, $isRemovingPostage, $isAvailableOnSpecialOffers, $isEnabled, $maxUsage, $expirationDate,
$freeShippingForCountries,
$freeShippingForModules,
$perCustomerUsageCount
);
$this->attributeAvList = isset($effects[self::ATTRIBUTES_AV_LIST]) ? $effects[self::ATTRIBUTES_AV_LIST] : array();
if (! is_array($this->attributeAvList)) $this->attributeAvList = array($this->attributeAvList);
$this->attribute = isset($effects[self::ATTRIBUTE]) ? $effects[self::ATTRIBUTE] : 0;
$this->setFieldsValue($effects);
return $this;
}
/**
* @inheritdoc
*/
public function exec()
{
// This coupon subtracts the specified amount from the order total
// for each product which uses the selected attributes
$discount = 0;
$cartItems = $this->facade->getCart()->getCartItems();
/** @var CartItem $cartItem */
foreach ($cartItems as $cartItem) {
if (! $cartItem->getPromo() || $this->isAvailableOnSpecialOffers()) {
$productSaleElements = $cartItem->getProductSaleElements();
$combinations = $productSaleElements->getAttributeCombinations();
/** @var AttributeCombination $combination */
foreach ($combinations as $combination) {
$attrValue = $combination->getAttributeAvId();
if (in_array($attrValue, $this->attributeAvList)) {
$discount += $this->getCartItemDiscount($cartItem);
break;
}
}
}
}
return $discount;
}
/**
* Renders the template which implements coupon specific user-input,
* using the provided template file, and a list of specific input fields.
*
* @param string $templateName the path to the template
* @param array $otherFields the list of additional fields fields
*
* @return string the rendered template.
*/
public function drawBaseBackOfficeInputs($templateName, $otherFields)
{
return $this->facade->getParser()->render($templateName, array_merge($otherFields, [
// The attributes list field
'attribute_field_name' => $this->makeCouponFieldName(self::ATTRIBUTE),
'attribute_value' => $this->attribute,
// The attributes list field
'attribute_av_field_name' => $this->makeCouponFieldName(self::ATTRIBUTES_AV_LIST),
'attribute_av_values' => $this->attributeAvList
]));
}
/**
* @inheritdoc
*/
public function getBaseFieldList($otherFields)
{
return array_merge($otherFields, [self::ATTRIBUTE, self::ATTRIBUTES_AV_LIST]);
}
/**
* @inheritdoc
*/
public function checkBaseCouponFieldValue($fieldName, $fieldValue)
{
if ($fieldName === self::ATTRIBUTE) {
if (empty($fieldValue)) {
throw new \InvalidArgumentException(
Translator::getInstance()->trans(
'Please select an attribute'
)
);
}
} elseif ($fieldName === self::ATTRIBUTES_AV_LIST) {
if (empty($fieldValue)) {
throw new \InvalidArgumentException(
Translator::getInstance()->trans(
'Please select at least one attribute value'
)
);
}
}
return $fieldValue;
}
}

View File

@@ -0,0 +1,152 @@
<?php
/*************************************************************************************/
/* This file is part of the Thelia package. */
/* */
/* Copyright (c) OpenStudio */
/* email : dev@thelia.net */
/* web : http://www.thelia.net */
/* */
/* For the full copyright and license information, please view the LICENSE.txt */
/* file that was distributed with this source code. */
/*************************************************************************************/
namespace Thelia\Coupon\Type;
use Thelia\Core\Translation\Translator;
use Thelia\Coupon\FacadeInterface;
use Thelia\Model\CartItem;
/**
* Allow to remove an amount from the checkout total
*
* @package Coupon
* @author Franck Allimant <franck@cqfdev.fr>
*/
abstract class AbstractRemoveOnCategories extends CouponAbstract implements AmountAndPercentageCouponInterface
{
const CATEGORIES_LIST = 'categories';
protected $category_list = array();
/**
* Set the value of specific coupon fields.
*
* @param Array $effects the Coupon effects params
*/
abstract public function setFieldsValue($effects);
/**
* Get the discount for a specific cart item.
*
* @param CartItem $cartItem the cart item
* @return float the discount value
*/
abstract public function getCartItemDiscount($cartItem);
/**
* @inheritdoc
*/
public function set(
FacadeInterface $facade,
$code,
$title,
$shortDescription,
$description,
array $effects,
$isCumulative,
$isRemovingPostage,
$isAvailableOnSpecialOffers,
$isEnabled,
$maxUsage,
\DateTime $expirationDate,
$freeShippingForCountries,
$freeShippingForModules,
$perCustomerUsageCount
)
{
parent::set(
$facade, $code, $title, $shortDescription, $description, $effects,
$isCumulative, $isRemovingPostage, $isAvailableOnSpecialOffers, $isEnabled, $maxUsage, $expirationDate,
$freeShippingForCountries,
$freeShippingForModules,
$perCustomerUsageCount
);
$this->category_list = isset($effects[self::CATEGORIES_LIST]) ? $effects[self::CATEGORIES_LIST] : array();
if (! is_array($this->category_list)) $this->category_list = array($this->category_list);
$this->setFieldsValue($effects);
return $this;
}
/**
* @inheritdoc
*/
public function exec()
{
// This coupon subtracts the specified amount from the order total
// for each product of the selected categories.
$discount = 0;
$cartItems = $this->facade->getCart()->getCartItems();
/** @var CartItem $cartItem */
foreach ($cartItems as $cartItem) {
if (! $cartItem->getPromo() || $this->isAvailableOnSpecialOffers()) {
$categories = $cartItem->getProduct()->getCategories();
/** @var Category $category */
foreach ($categories as $category) {
if (in_array($category->getId(), $this->category_list)) {
$discount += $this->getCartItemDiscount($cartItem);
break;
}
}
}
}
return $discount;
}
/**
* @inheritdoc
*/
public function drawBaseBackOfficeInputs($templateName, $otherFields)
{
return $this->facade->getParser()->render($templateName, array_merge($otherFields, [
// The categories list field
'categories_field_name' => $this->makeCouponFieldName(self::CATEGORIES_LIST),
'categories_values' => $this->category_list
]));
}
/**
* @inheritdoc
*/
public function getBaseFieldList($otherFields)
{
return array_merge($otherFields, [self::CATEGORIES_LIST]);
}
/**
* @inheritdoc
*/
public function checkBaseCouponFieldValue($fieldName, $fieldValue)
{
if ($fieldName === self::CATEGORIES_LIST) {
if (empty($fieldValue)) {
throw new \InvalidArgumentException(
Translator::getInstance()->trans(
'Please select at least one category'
)
);
}
}
return $fieldValue;
}
}

View File

@@ -0,0 +1,162 @@
<?php
/*************************************************************************************/
/* This file is part of the Thelia package. */
/* */
/* Copyright (c) OpenStudio */
/* email : dev@thelia.net */
/* web : http://www.thelia.net */
/* */
/* For the full copyright and license information, please view the LICENSE.txt */
/* file that was distributed with this source code. */
/*************************************************************************************/
namespace Thelia\Coupon\Type;
use Thelia\Core\Translation\Translator;
use Thelia\Coupon\FacadeInterface;
use Thelia\Model\CartItem;
/**
* Allow to remove an amount from the checkout total
*
* @package Coupon
* @author Franck Allimant <franck@cqfdev.fr>
*/
abstract class AbstractRemoveOnProducts extends CouponAbstract implements AmountAndPercentageCouponInterface
{
const CATEGORY_ID = 'category_id';
const PRODUCTS_LIST = 'products';
public $category_id = 0;
public $product_list = array();
/**
* Set the value of specific coupon fields.
*
* @param Array $effects the Coupon effects params
*/
abstract public function setFieldsValue($effects);
/**
* Get the discount for a specific cart item.
*
* @param CartItem $cartItem the cart item
* @return float the discount value
*/
abstract public function getCartItemDiscount($cartItem);
/**
* @inheritdoc
*/
public function set(
FacadeInterface $facade,
$code,
$title,
$shortDescription,
$description,
array $effects,
$isCumulative,
$isRemovingPostage,
$isAvailableOnSpecialOffers,
$isEnabled,
$maxUsage,
\DateTime $expirationDate,
$freeShippingForCountries,
$freeShippingForModules,
$perCustomerUsageCount
)
{
parent::set(
$facade, $code, $title, $shortDescription, $description, $effects,
$isCumulative, $isRemovingPostage, $isAvailableOnSpecialOffers, $isEnabled, $maxUsage, $expirationDate,
$freeShippingForCountries,
$freeShippingForModules,
$perCustomerUsageCount
);
$this->product_list = isset($effects[self::PRODUCTS_LIST]) ? $effects[self::PRODUCTS_LIST] : array();
if (! is_array($this->product_list)) $this->product_list = array($this->product_list);
$this->category_id = isset($effects[self::CATEGORY_ID]) ? $effects[self::CATEGORY_ID] : 0;
$this->setFieldsValue($effects);
return $this;
}
/**
* @inheritdoc
*/
public function exec()
{
// This coupon subtracts the specified amount from the order total
// for each product of the selected products.
$discount = 0;
$cartItems = $this->facade->getCart()->getCartItems();
/** @var CartItem $cartItem */
foreach ($cartItems as $cartItem) {
if (in_array($cartItem->getProduct()->getId(), $this->product_list)) {
if (! $cartItem->getPromo() || $this->isAvailableOnSpecialOffers()) {
$discount += $this->getCartItemDiscount($cartItem);
}
}
}
return $discount;
}
/**
* @inheritdoc
*/
public function drawBaseBackOfficeInputs($templateName, $otherFields)
{
return $this->facade->getParser()->render($templateName, array_merge($otherFields, [
// The category ID field
'category_id_field_name' => $this->makeCouponFieldName(self::CATEGORY_ID),
'category_id_value' => $this->category_id,
// The products list field
'products_field_name' => $this->makeCouponFieldName(self::PRODUCTS_LIST),
'products_values' => $this->product_list,
'products_values_csv' => implode(', ', $this->product_list)
]));
}
/**
* @inheritdoc
*/
public function getBaseFieldList($otherFields)
{
return array_merge($otherFields, [self::CATEGORY_ID, self::PRODUCTS_LIST]);
}
/**
* @inheritdoc
*/
public function checkBaseCouponFieldValue($fieldName, $fieldValue)
{
if ($fieldName === self::CATEGORY_ID) {
if (empty($fieldValue)) {
throw new \InvalidArgumentException(
Translator::getInstance()->trans(
'Please select a category'
)
);
}
} elseif ($fieldName === self::PRODUCTS_LIST) {
if (empty($fieldValue)) {
throw new \InvalidArgumentException(
Translator::getInstance()->trans(
'Please select at least one product'
)
);
}
}
return $fieldValue;
}
}

View File

@@ -0,0 +1,59 @@
<?php
/*************************************************************************************/
/* This file is part of the Thelia package. */
/* */
/* Copyright (c) OpenStudio */
/* email : dev@thelia.net */
/* web : http://www.thelia.net */
/* */
/* For the full copyright and license information, please view the LICENSE.txt */
/* file that was distributed with this source code. */
/*************************************************************************************/
namespace Thelia\Coupon\Type;
/**
* Represents a Coupon ready to be processed in a Checkout process
*
* @package Coupon
* @author Guillaume MOREL <gmorel@openstudio.fr>
*
*/
interface AmountAndPercentageCouponInterface
{
/**
* Set the value of specific coupon fields.
* @param Array $effects the Coupon effects params
*/
public function setFieldsValue($effects);
/**
* Get the discount for a specific cart item.
*
* @param CartItem $cartItem the cart item
* @return float the discount value
*/
public function getCartItemDiscount($cartItem);
/**
* Renders the template which implements coupon specific user-input,
* using the provided template file, and a list of specific input fields.
*
* @param string $templateName the path to the template
* @param array $otherFields the list of additional fields fields
*
* @return string the rendered template.
*/
public function drawBaseBackOfficeInputs($templateName, $otherFields);
/**
* @inheritdoc
*/
public function getBaseFieldList($otherFields);
/**
*
*/
public function checkBaseCouponFieldValue($fieldName, $fieldValue);
}

View File

@@ -0,0 +1,93 @@
<?php
/*************************************************************************************/
/* This file is part of the Thelia package. */
/* */
/* Copyright (c) OpenStudio */
/* email : dev@thelia.net */
/* web : http://www.thelia.net */
/* */
/* For the full copyright and license information, please view the LICENSE.txt */
/* file that was distributed with this source code. */
/*************************************************************************************/
namespace Thelia\Coupon\Type;
use Thelia\Core\Translation\Translator;
/**
* A trait to manage a coupon which removes a constant amount from the order total.
* Should be used on coupons classes which implements AmountAndPercentageCouponInterface
*
* Class AmountCouponTrait
* @author Franck Allimant <franck@cqfdev.fr>
* @package Thelia\Coupon\Type
*/
Trait AmountCouponTrait {
// The amount is already defined in CouponAbstract, and should not be redefined here.
// protected $amount = 0;
/**
* Should return the amount field name, defined in the parent class.
*
* @return string the percentage field name
*/
abstract protected function getAmountFieldName();
/**
* @inheritdoc
*/
protected function setFieldsValue($effects)
{
$this->amount = $effects[$this->getAmountFieldName()];
}
/**
* @inheritdoc
*/
public function getCartItemDiscount($cartItem)
{
return $cartItem->getQuantity() * $this->amount;
}
/**
* @inheritdoc
*/
public function callDrawBackOfficeInputs($templateName)
{
return $this->drawBaseBackOfficeInputs($templateName, [
'amount_field_name' => $this->makeCouponFieldName($this->getAmountFieldName()),
'amount_value' => $this->amount
]);
}
/**
* @inheritdoc
*/
protected function getFieldList()
{
return $this->getBaseFieldList([$this->getAmountFieldName()]);
}
/**
* @inheritdoc
*/
protected function checkCouponFieldValue($fieldName, $fieldValue)
{
$this->checkBaseCouponFieldValue($fieldName, $fieldValue);
if ($fieldName === $this->getAmountFieldName()) {
if (floatval($fieldValue) < 0) {
throw new \InvalidArgumentException(
Translator::getInstance()->trans(
'Value %val for Discount Amount is invalid. Please enter a positive value.',
[ '%val' => $fieldValue]
)
);
}
}
return $fieldValue;
}
}

View File

@@ -17,6 +17,7 @@ use Thelia\Condition\ConditionEvaluator;
use Thelia\Condition\ConditionOrganizerInterface;
use Thelia\Core\Translation\Translator;
use Thelia\Coupon\FacadeInterface;
use Thelia\Form\CouponCreationForm;
use Thelia\Model\CouponCountry;
use Thelia\Model\CouponModule;
@@ -29,12 +30,21 @@ use Thelia\Model\CouponModule;
*/
abstract class CouponAbstract implements CouponInterface
{
const INPUT_EXTENDED__NAME = 'thelia_coupon_creation_extended';
/**
* The dataset name for all coupon specific input fields, that do not appear in the CouPonCreationForm form.
*
* In the input form, these fields have to be created like:
*
* thelia_coupon_specific[my_field, thelia_coupon_creation_extended[my_other_field]
*
* use the makeCouponField() method to do that safely.
*/
const COUPON_DATASET_NAME = 'coupon_specific';
const INPUT_AMOUNT_NAME = 'amount';
/** @var array Extended Inputs to manage */
protected $extendedInputs = array();
/**
* A standard 'amount' filed name, thant can be used in coupons which extends this class
*/
const AMOUNT_FIELD_NAME = 'amount';
/** @var FacadeInterface Provide necessary value from Thelia */
protected $facade = null;
@@ -161,7 +171,8 @@ abstract class CouponAbstract implements CouponInterface
$this->facade = $facade;
$this->effects = $effects;
$this->amount = $effects[self::INPUT_AMOUNT_NAME];
// Amount is now optional.
$this->amount = isset($effects[self::AMOUNT_FIELD_NAME]) ? $effects[self::AMOUNT_FIELD_NAME] : 0;
$this->freeShippingForCountries = $freeShippingForCountries;
$this->freeShippingForModules = $freeShippingForModules;
@@ -267,10 +278,7 @@ abstract class CouponAbstract implements CouponInterface
}
/**
* Return effects generated by the coupon
* A negative value
*
* @return float Amount removed from the Total Checkout
* @inheritdoc
*/
public function exec()
{
@@ -383,6 +391,19 @@ abstract class CouponAbstract implements CouponInterface
return $this->conditionEvaluator->isMatching($this->conditions);
}
/**
* This is the field label than will be displayed in the form.
* This method should be overridden to be useful.
*
* For backward compatibility only.
*
* @return string
*/
public function getInputName()
{
return "Please override getInputName() method";
}
/**
* Draw the input displayed in the BackOffice
* allowing Admin to set its Coupon effect
@@ -394,19 +415,96 @@ abstract class CouponAbstract implements CouponInterface
{
return $this->facade->getParser()->render('coupon/type-fragments/remove-x.html', [
'label' => $this->getInputName(),
'fieldName' => self::INPUT_AMOUNT_NAME,
'fieldId' => self::AMOUNT_FIELD_NAME,
'fieldName' => $this->makeCouponFieldName(self::AMOUNT_FIELD_NAME),
'value' => $this->amount
]);
}
/**
* Get all extended inputs name to manage
* This methods checks a field value. If the field has a correct value, this value is returned
* Otherwise, an InvalidArgumentException describing the problem should be thrown.
*
* This method should be ovveriden to be useful.
*
* @param $fieldName
* @param $fieldValue
* @return mixed
* @throws \InvalidArgumentException if the field valiue is not valid.
*/
public function getExtendedInputs()
protected function checkCouponFieldValue($fieldName, $fieldValue)
{
return $this->extendedInputs;
return $fieldValue;
}
/**
* A helper to get the value of a standard field name
*
* @param string $fieldName the field name
* @param array $data the input form data (e.g. $form->getData())
* @param mixed $defaultValue the default value if the field is not found.
*
* @return mixed the input value, or the default one
*
* @throws \InvalidArgumentException if the field is not found, and no default value has been defined.
*/
protected function getCouponFieldValue($fieldName, $data, $defaultValue = null)
{
if (isset($data[self::COUPON_DATASET_NAME][$fieldName])) {
return $this->checkCouponFieldValue(
$fieldName,
$data[self::COUPON_DATASET_NAME][$fieldName]
);
} elseif (null !== $defaultValue) {
return $defaultValue;
} else {
throw new \InvalidArgumentException(sprintf("The coupon field name %s was not found in the coupon form", $fieldName));
}
}
/**
* A helper to create an standard field name that will be used in the coupon form
*
* @param string $fieldName the field name
* @return string the complete name, ready to be used in a form.
*/
protected function makeCouponFieldName($fieldName)
{
return sprintf("%s[%s][%s]", CouponCreationForm::COUPON_CREATION_FORM_NAME, self::COUPON_DATASET_NAME, $fieldName);
}
/**
* Return a list of the fields name for this coupon.
*
* @return array
*/
protected function getFieldList()
{
return [self::AMOUNT_FIELD_NAME];
}
/**
* Create the effect array from the list of fields
*
* @param array $data the input form data (e.g. $form->getData())
* @return array a filedName => fieldValue array
*/
public function getEffects($data)
{
$effects = [];
foreach ($this->getFieldList() as $fieldName) {
$effects[$fieldName] = $this->getCouponFieldValue($fieldName, $data);
}
return $effects;
}
/**
* @inheritdoc
*/
public function clear()
{
// Does nothing. Override this function as needed.
}
}

View File

@@ -220,13 +220,6 @@ interface CouponInterface
*/
public function drawBackOfficeInputs();
/**
* Get all extended inputs name to manage
*
* @return mixed
*/
public function getExtendedInputs();
/**
* @return ObjectCollection list of country IDs for which shipping is free. All if empty
*/
@@ -236,4 +229,19 @@ interface CouponInterface
* @return ObjectCollection list of module IDs for which shipping is free. All if empty
*/
public function getFreeShippingForModules();
/**
* Create the effect array from the list of fields
*
* @param array $data the input form data (e.g. $form->getData())
*
* @return array a filedName => fieldValue array
*/
public function getEffects($data);
/**
* Clear all the data the coupon may have stored, called after an order is completed.
*/
public function clear();
}

View File

@@ -0,0 +1,338 @@
<?php
/*************************************************************************************/
/* This file is part of the Thelia package. */
/* */
/* Copyright (c) OpenStudio */
/* email : dev@thelia.net */
/* web : http://www.thelia.net */
/* */
/* For the full copyright and license information, please view the LICENSE.txt */
/* file that was distributed with this source code. */
/*************************************************************************************/
namespace Thelia\Coupon\Type;
use Thelia\Core\Event\Cart\CartEvent;
use Thelia\Core\Event\TheliaEvents;
use Thelia\Core\Translation\Translator;
use Thelia\Model\CartItem;
use Thelia\Model\CartItemQuery;
use Thelia\Model\Product;
use Thelia\Model\ProductQuery;
/**
* Allow to remove an amount from the checkout total
*
* @package Coupon
* @author Franck Allimant <franck@cqfdev.fr>
*/
class FreeProduct extends AbstractRemoveOnProducts
{
const OFFERED_PRODUCT_ID = 'offered_product_id';
const OFFERED_CATEGORY_ID = 'offered_category_id';
/** @var string Service Id */
protected $serviceId = 'thelia.coupon.type.free_product';
protected $offeredProductId;
protected $offeredCategoryId;
/**
* This constant is user to mark a free product as in the process of being added to the cart,
* but the CartItem ID is not yet been defined.
*/
const ADD_TO_CART_IN_PROCESS = -1;
/**
* @inheritdoc
*/
public function setFieldsValue($effects)
{
$this->offeredProductId = $effects[self::OFFERED_PRODUCT_ID];
$this->offeredCategoryId = $effects[self::OFFERED_CATEGORY_ID];
}
/**
* @inheritdoc
*/
public function getCartItemDiscount($cartItem)
{
// This method is not used, we use our own implementation of exec();
return 0;
}
/**
* @return string The session variable where the cart item IDs for the free products are stored
*/
protected function getSessionVarName()
{
return "coupon.free_product.cart_items." . $this->getCode();
}
/**
* Return the cart item id which contains the free product related to a given product
*
* @param Product $product the product in the cart which triggered the discount
*
* @return bool|int|CartItem the cart item which contains the free product, or false if the product is no longer in the cart, or ADD_TO_CART_IN_PROCESS if the adding process is not finished
*/
protected function getRelatedCartItem($product)
{
$cartItemIdList = $this->facade->getRequest()->getSession()->get(
$this->getSessionVarName(),
array()
);
if (isset($cartItemIdList[$product->getId()])) {
$cartItemId = $cartItemIdList[$product->getId()];
if ($cartItemId == self::ADD_TO_CART_IN_PROCESS) {
return self::ADD_TO_CART_IN_PROCESS;
} elseif (null !== $cartItem = CartItemQuery::create()->findPk($cartItemId)) {
return $cartItem;
}
} else {
// Maybe the product we're offering is already in the cart ? Search it.
$cartItems = $this->facade->getCart()->getCartItems();
/** @var CartItem $cartItem */
foreach ($cartItems as $cartItem) {
if ($cartItem->getProduct()->getId() == $this->offeredProductId) {
// We found the product. Store its cart item as the free product container.
$this->setRelatedCartItem($product, $cartItem->getId());
return $cartItem;
}
}
}
return false;
}
/**
* Set the cart item id which contains the free product related to a given product
*
* @param Product $product the product in the cart which triggered the discount
* @param bool|int $cartItemId the cart item ID which contains the free product, or just true if the free product is not yet added.
*/
protected function setRelatedCartItem($product, $cartItemId)
{
$cartItemIdList = $this->facade->getRequest()->getSession()->get(
$this->getSessionVarName(),
array()
);
if (! is_array($cartItemIdList)) $cartItemIdList = array();
$cartItemIdList[$product->getId()] = $cartItemId;
$this->facade->getRequest()->getSession()->set(
$this->getSessionVarName(),
$cartItemIdList
);
}
/**
* Get the product id / cart item id list.
*
* @return array an array where the free product ID is the key, and the related cart item id the value.
*/
protected function getFreeProductsCartItemIds()
{
return $this->facade->getRequest()->getSession()->get(
$this->getSessionVarName(),
array()
);
}
/**
* Clear the session variable.
*/
protected function clearFreeProductsCartItemIds()
{
return $this->facade->getRequest()->getSession()->remove($this->getSessionVarName());
}
/**
* We overload this method here to remove the free products when the
* coupons conditions are no longer met.
*
* @inheritdoc
*/
public function isMatching()
{
$match = parent::isMatching();
if (! $match) {
// Cancel coupon effect (but no not remove the product)
$this->clearFreeProductsCartItemIds();
}
return $match;
}
/**
* @inheritdoc
*/
public function exec()
{
$discount = 0;
$cartItems = $this->facade->getCart()->getCartItems();
/** @var Product $eligibleProduct */
$eligibleProduct = null;
/** @var CartItem $cartItem */
foreach ($cartItems as $cartItem) {
if (in_array($cartItem->getProduct()->getId(), $this->product_list)) {
if (! $cartItem->getPromo() || $this->isAvailableOnSpecialOffers()) {
$eligibleProduct = $cartItem;
break;
}
}
}
if ($eligibleProduct !== null) {
// Get the cart item for the eligible product
$freeProductCartItem = $this->getRelatedCartItem($eligibleProduct);
// We add the free product it only if it not yet in the cart.
if ($freeProductCartItem === false) {
if (null !== $freeProduct = ProductQuery::create()->findPk($this->offeredProductId)) {
// Store in the session that the free product is added to the cart,
// so that we don't enter the following infinite loop :
//
// 1) exec() adds a product by firing a CART_ADDITEM event,
// 2) the event is processed by Action\Coupon::updateOrderDiscount(),
// 3) Action\Coupon::updateOrderDiscount() calls CouponManager::getDiscount()
// 4) CouponManager::getDiscount() calls exec() -> Infinite loop !!
// Store a marker first, we do not have the cart item id yet.
$this->setRelatedCartItem($eligibleProduct, self::ADD_TO_CART_IN_PROCESS);
$cartEvent = new CartEvent($this->facade->getCart());
$cartEvent->setNewness(true);
$cartEvent->setAppend(false);
$cartEvent->setQuantity(1);
$cartEvent->setProductSaleElementsId($freeProduct->getDefaultSaleElements()->getId());
$cartEvent->setProduct($this->offeredProductId);
$this->facade->getDispatcher()->dispatch(TheliaEvents::CART_ADDITEM, $cartEvent);
// Store the final cart item ID.
$this->setRelatedCartItem($eligibleProduct, $cartEvent->getCartItem()->getId());
$freeProductCartItem = $cartEvent->getCartItem();
}
}
if ($freeProductCartItem instanceof CartItem) {
// The discount is the product price.
$discount = $freeProductCartItem->getPromo() ?
$freeProductCartItem->getPromoPrice() : $freeProductCartItem->getPrice();
}
}
// No eligible product was found !
else {
// Remove all free products for this coupon, but no not remove the product from the cart.
$this->clearFreeProductsCartItemIds();
}
return $discount;
}
/**
* @inheritdoc
*/
protected function getFieldList()
{
return $this->getBaseFieldList([self::OFFERED_CATEGORY_ID, self::OFFERED_PRODUCT_ID]);
}
/**
* @inheritdoc
*/
protected function checkCouponFieldValue($fieldName, $fieldValue)
{
$this->checkBaseCouponFieldValue($fieldName, $fieldValue);
if ($fieldName === self::OFFERED_PRODUCT_ID) {
if (floatval($fieldValue) < 0) {
throw new \InvalidArgumentException(
Translator::getInstance()->trans(
'Please select the offered product'
)
);
}
} elseif ($fieldName === self::OFFERED_CATEGORY_ID) {
if (empty($fieldValue)) {
throw new \InvalidArgumentException(
Translator::getInstance()->trans(
'Please select the category of the offred product'
)
);
}
}
return $fieldValue;
}
/**
* Get I18n name
*
* @return string
*/
public function getName()
{
return $this->facade
->getTranslator()
->trans('Free product when buying one or more selected products', array(), 'coupon');
}
/**
* @inheritdoc
*/
public function getToolTip()
{
$toolTip = $this->facade
->getTranslator()
->trans(
'This coupon adds a free product to the cart if one of the selected products is in the cart.',
array(),
'coupon'
);
return $toolTip;
}
/**
* @inheritdoc
*/
public function drawBackOfficeInputs()
{
return $this->drawBaseBackOfficeInputs("coupon/type-fragments/free-product.html", [
'offered_category_field_name' => $this->makeCouponFieldName(self::OFFERED_CATEGORY_ID),
'offered_category_value' => $this->offeredCategoryId,
'offered_product_field_name' => $this->makeCouponFieldName(self::OFFERED_PRODUCT_ID),
'offered_product_value' => $this->offeredProductId
]);
}
/**
* @inheritdoc
*/
public function clear()
{
// Clear the session variable when the coupon is cleared.
$this->clearFreeProductsCartItemIds();
}
}

View File

@@ -0,0 +1,93 @@
<?php
/*************************************************************************************/
/* This file is part of the Thelia package. */
/* */
/* Copyright (c) OpenStudio */
/* email : dev@thelia.net */
/* web : http://www.thelia.net */
/* */
/* For the full copyright and license information, please view the LICENSE.txt */
/* file that was distributed with this source code. */
/*************************************************************************************/
namespace Thelia\Coupon\Type;
use Thelia\Core\Translation\Translator;
/**
* A trait to manage a coupon which removes a percentage of cart items from the order total.
* Should be used on coupons classes which implements AmountAndPercentageCouponInterface
*
* Class PercentageCouponTrait
* @author Franck Allimant <franck@cqfdev.fr>
* @package Thelia\Coupon\Type
*/
Trait PercentageCouponTrait {
public $percentage = 0;
/**
* Should return the percentage field name, defined in the parent class.
*
* @return string the percentage field name
*/
abstract protected function getPercentageFieldName();
/**
* @inheritdoc
*/
protected function setFieldsValue($effects)
{
$this->percentage = $effects[$this->getPercentageFieldName()];
}
/**
* @inheritdoc
*/
public function getCartItemDiscount($cartItem)
{
return $cartItem->getQuantity() * $cartItem->getPrice() * ($this->percentage / 100);
}
/**
* @inheritdoc
*/
public function callDrawBackOfficeInputs($templateName)
{
return $this->drawBaseBackOfficeInputs($templateName, [
'percentage_field_name' => $this->makeCouponFieldName($this->getPercentageFieldName()),
'percentage_value' => $this->percentage,
]);
}
/**
* @inheritdoc
*/
protected function getFieldList()
{
return $this->getBaseFieldList([$this->getPercentageFieldName()]);
}
/**
* @inheritdoc
*/
protected function checkCouponFieldValue($fieldName, $fieldValue)
{
$this->checkBaseCouponFieldValue($fieldName, $fieldValue);
if ($fieldName === $this->getPercentageFieldName()) {
$pcent = floatval($fieldValue);
if ($pcent <= 0 || $pcent > 100) {
throw new \InvalidArgumentException(
Translator::getInstance()->trans(
'Value %val for Percent Discount is invalid. Please enter a positive value between 1 and 100.',
[ '%val' => $fieldValue]
)
);
}
}
return $fieldValue;
}
}

View File

@@ -0,0 +1,65 @@
<?php
/*************************************************************************************/
/* This file is part of the Thelia package. */
/* */
/* Copyright (c) OpenStudio */
/* email : dev@thelia.net */
/* web : http://www.thelia.net */
/* */
/* For the full copyright and license information, please view the LICENSE.txt */
/* file that was distributed with this source code. */
/*************************************************************************************/
namespace Thelia\Coupon\Type;
/**
* Allow to remove an amount from the checkout total
*
* @package Coupon
* @author Franck Allimant <franck@cqfdev.fr>
*/
class RemoveAmountOnAttributeValues extends AbstractRemoveOnAttributeValues
{
use AmountCouponTrait;
/** @var string Service Id */
protected $serviceId = 'thelia.coupon.type.remove_amount_on_attribute_av';
protected function getAmountFieldName()
{
return self::AMOUNT_FIELD_NAME;
}
/**
* @inheritdoc
*/
public function getName()
{
return $this->facade
->getTranslator()
->trans('Fixed amount discount for selected attribute values', array(), 'coupon');
}
/**
* @inheritdoc
*/
public function getToolTip()
{
$toolTip = $this->facade
->getTranslator()
->trans(
'This coupon subtracts the specified amount from the order total for each product which uses the selected attribute values. If the discount is greater than the total order, the customer will only pay the shipping, or nothing if the coupon also provides free shipping.',
array(),
'coupon'
);
return $toolTip;
}
/**
* @inheritdoc
*/
public function drawBackOfficeInputs()
{
return $this->callDrawBackOfficeInputs('coupon/type-fragments/remove-amount-on-attributes.html');
}
}

View File

@@ -0,0 +1,66 @@
<?php
/*************************************************************************************/
/* This file is part of the Thelia package. */
/* */
/* Copyright (c) OpenStudio */
/* email : dev@thelia.net */
/* web : http://www.thelia.net */
/* */
/* For the full copyright and license information, please view the LICENSE.txt */
/* file that was distributed with this source code. */
/*************************************************************************************/
namespace Thelia\Coupon\Type;
/**
* Allow to remove an amount from the checkout total
*
* @package Coupon
* @author Franck Allimant <franck@cqfdev.fr>
*/
class RemoveAmountOnCategories extends AbstractRemoveOnCategories
{
use AmountCouponTrait;
/** @var string Service Id */
protected $serviceId = 'thelia.coupon.type.remove_amount_on_categories';
protected function getAmountFieldName()
{
return self::AMOUNT_FIELD_NAME;
}
/**
* @inheritdoc
*/
public function getName()
{
return $this->facade
->getTranslator()
->trans('Fixed amount discount for selected categories', array(), 'coupon');
}
/**
* @inheritdoc
*/
public function getToolTip()
{
$toolTip = $this->facade
->getTranslator()
->trans(
'This coupon subtracts the specified amount from the order total for each product which belongs to the selected categories. If the discount is greater than the total order, the customer will only pay the shipping, or nothing if the coupon also provides free shipping.',
array(),
'coupon'
);
return $toolTip;
}
/**
* @inheritdoc
*/
public function drawBackOfficeInputs()
{
return $this->callDrawBackOfficeInputs('coupon/type-fragments/remove-amount-on-categories.html');
}
}

View File

@@ -0,0 +1,70 @@
<?php
/*************************************************************************************/
/* This file is part of the Thelia package. */
/* */
/* Copyright (c) OpenStudio */
/* email : dev@thelia.net */
/* web : http://www.thelia.net */
/* */
/* For the full copyright and license information, please view the LICENSE.txt */
/* file that was distributed with this source code. */
/*************************************************************************************/
namespace Thelia\Coupon\Type;
use Thelia\Model\Product;
/**
* Allow to remove an amount from the checkout total
*
* @package Coupon
* @author Franck Allimant <franck@cqfdev.fr>
*/
class RemoveAmountOnProducts extends AbstractRemoveOnProducts
{
use AmountCouponTrait;
/** @var string Service Id */
protected $serviceId = 'thelia.coupon.type.remove_amount_on_products';
protected function getAmountFieldName()
{
return self::AMOUNT_FIELD_NAME;
}
/**
* Get I18n name
*
* @return string
*/
public function getName()
{
return $this->facade
->getTranslator()
->trans('Fixed amount discount for selected products', array(), 'coupon');
}
/**
* @inheritdoc
*/
public function getToolTip()
{
$toolTip = $this->facade
->getTranslator()
->trans(
'This coupon subtracts the specified amount from the order total for each selected product. If the discount is greater than the total order, the customer will only pay the shipping, or nothing if the coupon also provides free shipping.',
array(),
'coupon'
);
return $toolTip;
}
/**
* @inheritdoc
*/
public function drawBackOfficeInputs()
{
return $this->callDrawBackOfficeInputs('coupon/type-fragments/remove-amount-on-products.html');
}
}

View File

@@ -0,0 +1,71 @@
<?php
/*************************************************************************************/
/* This file is part of the Thelia package. */
/* */
/* Copyright (c) OpenStudio */
/* email : dev@thelia.net */
/* web : http://www.thelia.net */
/* */
/* For the full copyright and license information, please view the LICENSE.txt */
/* file that was distributed with this source code. */
/*************************************************************************************/
namespace Thelia\Coupon\Type;
/**
* Allow to remove an amount from the checkout total
*
* @package Coupon
* @author Franck Allimant <franck@cqfdev.fr>
*/
class RemovePercentageOnAttributeValues extends AbstractRemoveOnAttributeValues
{
const PERCENTAGE = 'percentage';
use PercentageCouponTrait;
/** @var string Service Id */
protected $serviceId = 'thelia.coupon.type.remove_percentage_on_attribute_av';
/**
* @inheritdoc
*/
protected function getPercentageFieldName()
{
return self::PERCENTAGE;
}
/**
* @inheritdoc
*/
public function getName()
{
return $this->facade
->getTranslator()
->trans('Percentage discount for selected attribute values', array(), 'coupon');
}
/**
* @inheritdoc
*/
public function getToolTip()
{
$toolTip = $this->facade
->getTranslator()
->trans(
'This coupon subtracts from the order total the specified percentage of each product price which uses the selected attribute values. If the discount is greater than the total order, the customer will only pay the shipping, or nothing if the coupon also provides free shipping.',
array(),
'coupon'
);
return $toolTip;
}
/**
* @inheritdoc
*/
public function drawBackOfficeInputs()
{
return $this->callDrawBackOfficeInputs('coupon/type-fragments/remove-percentage-on-attributes.html');
}
}

View File

@@ -0,0 +1,68 @@
<?php
/*************************************************************************************/
/* This file is part of the Thelia package. */
/* */
/* Copyright (c) OpenStudio */
/* email : dev@thelia.net */
/* web : http://www.thelia.net */
/* */
/* For the full copyright and license information, please view the LICENSE.txt */
/* file that was distributed with this source code. */
/*************************************************************************************/
namespace Thelia\Coupon\Type;
/**
* @author Franck Allimant <franck@cqfdev.fr>
*/
class RemovePercentageOnCategories extends AbstractRemoveOnCategories
{
const PERCENTAGE = 'percentage';
use PercentageCouponTrait;
/** @var string Service Id */
protected $serviceId = 'thelia.coupon.type.remove_percentage_on_categories';
/**
* @inheritdoc
*/
protected function getPercentageFieldName()
{
return self::PERCENTAGE;
}
/**
* @inheritdoc
*/
public function getName()
{
return $this->facade
->getTranslator()
->trans('Percentage discount for selected categories', array(), 'coupon');
}
/**
* @inheritdoc
*/
public function getToolTip()
{
$toolTip = $this->facade
->getTranslator()
->trans(
'This coupon subtracts from the order total a percentage of the price of each product which belongs to the selected categories. If the discount is greater than the total order, the customer will only pay the shipping, or nothing if the coupon also provides free shipping.',
array(),
'coupon'
);
return $toolTip;
}
/**
* @inheritdoc
*/
public function drawBackOfficeInputs()
{
return $this->callDrawBackOfficeInputs('coupon/type-fragments/remove-percentage-on-categories.html');
}
}

View File

@@ -0,0 +1,75 @@
<?php
/*************************************************************************************/
/* This file is part of the Thelia package. */
/* */
/* Copyright (c) OpenStudio */
/* email : dev@thelia.net */
/* web : http://www.thelia.net */
/* */
/* For the full copyright and license information, please view the LICENSE.txt */
/* file that was distributed with this source code. */
/*************************************************************************************/
namespace Thelia\Coupon\Type;
use Thelia\Model\Product;
/**
* Allow to remove an amount from the checkout total
*
* @package Coupon
* @author Franck Allimant <franck@cqfdev.fr>
*/
class RemovePercentageOnProducts extends AbstractRemoveOnProducts
{
const PERCENTAGE = 'percentage';
use PercentageCouponTrait;
/** @var string Service Id */
protected $serviceId = 'thelia.coupon.type.remove_percentage_on_products';
/**
* @inheritdoc
*/
protected function getPercentageFieldName()
{
return self::PERCENTAGE;
}
/**
* Get I18n name
*
* @return string
*/
public function getName()
{
return $this->facade
->getTranslator()
->trans('Percentage discount for selected products', array(), 'coupon');
}
/**
* @inheritdoc
*/
public function getToolTip()
{
$toolTip = $this->facade
->getTranslator()
->trans(
'This coupon subtracts from the order total the specified percentage of each selected product price. If the discount is greater than the total order, the customer will only pay the shipping, or nothing if the coupon also provides free shipping.',
array(),
'coupon'
);
return $toolTip;
}
/**
* @inheritdoc
*/
public function drawBackOfficeInputs()
{
return $this->callDrawBackOfficeInputs('coupon/type-fragments/remove-percentage-on-products.html');
}
}

View File

@@ -16,18 +16,23 @@ namespace Thelia\Coupon\Type;
* Allow to remove an amount from the checkout total
*
* @package Coupon
* @author Guillaume MOREL <gmorel@openstudio.fr>
* @author Guillaume MOREL <gmorel@openstudio.fr>, Franck Allimant <franck@cqfdev.fr>
*
*/
class RemoveXAmount extends CouponAbstract
class RemoveXAmount extends AbstractRemove
{
use AmountCouponTrait;
/** @var string Service Id */
protected $serviceId = 'thelia.coupon.type.remove_x_amount';
protected function getAmountFieldName()
{
return self::AMOUNT_FIELD_NAME;
}
/**
* Get I18n name
*
* @return string
* @inheritdoc
*/
public function getName()
{
@@ -37,21 +42,7 @@ class RemoveXAmount extends CouponAbstract
}
/**
* Get I18n amount input name
*
* @return string
*/
public function getInputName()
{
return $this->facade
->getTranslator()
->trans('Discount amount', array(), 'coupon');
}
/**
* Get I18n tooltip
*
* @return string
* @inheritdoc
*/
public function getToolTip()
{
@@ -66,12 +57,19 @@ class RemoveXAmount extends CouponAbstract
return $toolTip;
}
/**
* @inheritdoc
*/
public function exec()
{
return $this->amount;
}
/**
* @inheritdoc
*/
public function drawBackOfficeInputs()
{
return $this->facade->getParser()->render('coupon/type-fragments/remove-x-amount.html', [
'label' => $this->getInputName(),
'fieldName' => self::INPUT_AMOUNT_NAME,
'value' => $this->amount
]);
return $this->callDrawBackOfficeInputs('coupon/type-fragments/remove-x-amount.html');
}
}

View File

@@ -12,85 +12,30 @@
namespace Thelia\Coupon\Type;
use Thelia\Coupon\FacadeInterface;
/**
* @package Coupon
* @author Guillaume MOREL <gmorel@openstudio.fr>
* @author Guillaume MOREL <gmorel@openstudio.fr>, Franck Allimant <franck@cqfdev.fr>
*
*/
class RemoveXPercent extends CouponAbstract
class RemoveXPercent extends AbstractRemove
{
const INPUT_PERCENTAGE_NAME = 'percentage';
use PercentageCouponTrait;
/** @var string Service Id */
protected $serviceId = 'thelia.coupon.type.remove_x_percent';
/** @var float Percentage removed from the Cart */
protected $percentage = 0;
/** @var array Extended Inputs to manage */
protected $extendedInputs = array(
self::INPUT_PERCENTAGE_NAME
);
/**
* @inheritdoc
*/
public function set(
FacadeInterface $facade,
$code,
$title,
$shortDescription,
$description,
array $effects,
$isCumulative,
$isRemovingPostage,
$isAvailableOnSpecialOffers,
$isEnabled,
$maxUsage,
\DateTime $expirationDate,
$freeShippingForCountries,
$freeShippingForModules,
$perCustomerUsageCount
)
protected function getPercentageFieldName()
{
parent::set(
$facade, $code, $title, $shortDescription, $description, $effects,
$isCumulative, $isRemovingPostage, $isAvailableOnSpecialOffers, $isEnabled, $maxUsage, $expirationDate,
$freeShippingForCountries,
$freeShippingForModules,
$perCustomerUsageCount
);
$this->percentage = $effects[self::INPUT_PERCENTAGE_NAME];
return $this;
return self::INPUT_PERCENTAGE_NAME;
}
/**
* Return effects generated by the coupon
* A negative value
*
* @throws \Thelia\Exception\MissingFacadeException
* @throws \InvalidArgumentException
* @return float
*/
public function exec()
{
if ($this->percentage >= 100) {
throw new \InvalidArgumentException(
'Percentage must be inferior to 100'
);
}
return round($this->facade->getCartTotalTaxPrice() * $this->percentage/100, 2);
}
/**
* Get I18n name
*
* @return string
* @inheritdoc
*/
public function getName()
{
@@ -100,21 +45,7 @@ class RemoveXPercent extends CouponAbstract
}
/**
* Get I18n amount input name
*
* @return string
*/
public function getInputName()
{
return $this->facade
->getTranslator()
->trans('Percent Discount', array(), 'coupon');
}
/**
* Get I18n tooltip
*
* @return string
* @inheritdoc
*/
public function getToolTip()
{
@@ -130,19 +61,18 @@ class RemoveXPercent extends CouponAbstract
}
/**
* Draw the input displayed in the BackOffice
* allowing Admin to set its Coupon effect
*
* @return string HTML string
* @inheritdoc
*/
public function exec()
{
return round($this->facade->getCartTotalTaxPrice($this->isAvailableOnSpecialOffers()) * $this->percentage/100, 2);
}
/**
* @inheritdoc
*/
public function drawBackOfficeInputs()
{
return $this->facade->getParser()->render('coupon/type-fragments/remove-x-percent.html', [
'label' => $this->getInputName(),
'typeKey' => self::INPUT_AMOUNT_NAME,
'fieldId' => self::INPUT_PERCENTAGE_NAME,
'fieldName' => self::INPUT_EXTENDED__NAME,
'value' => $this->percentage
]);
return $this->callDrawBackOfficeInputs('coupon/type-fragments/remove-x-percent.html');
}
}

View File

@@ -33,6 +33,8 @@ use Thelia\Module\BaseModule;
*/
class CouponCreationForm extends BaseForm
{
const COUPON_CREATION_FORM_NAME = 'thelia_coupon_creation';
/**
* Build Coupon form
*
@@ -110,14 +112,6 @@ class CouponCreationForm extends BaseForm
)
)
)
->add(
'amount',
'money',
array(
'constraints' => array(
new NotBlank()
))
)
->add(
'isEnabled',
'text',
@@ -198,7 +192,12 @@ class CouponCreationForm extends BaseForm
new NotBlank()
)
)
);
)
->add('coupon_specific', 'collection', array(
'allow_add' => true,
'allow_delete' => true,
))
;
}
/**
@@ -226,6 +225,6 @@ class CouponCreationForm extends BaseForm
*/
public function getName()
{
return 'thelia_coupon_creation';
return self::COUPON_CREATION_FORM_NAME;
}
}

View File

@@ -66,19 +66,15 @@ class OrderDelivery extends BaseForm
public function verifyDeliveryModule($value, ExecutionContextInterface $context)
{
$module = ModuleQuery::create()
->filterByType(BaseModule::DELIVERY_MODULE_TYPE)
->filterByActivate(1)
->filterById($value)
->filterActivatedByTypeAndId(BaseModule::DELIVERY_MODULE_TYPE, $value)
->findOne();
if (null === $module) {
$context->addViolation(Translator::getInstance()->trans("Delivery module ID not found"));
} else {
if (! $module->isDeliveryModule()) {
$context->addViolation(
sprintf(Translator::getInstance()->trans("delivery module %s is not a Thelia\Module\DeliveryModuleInterface"), $module->getCode())
);
}
} elseif (! $module->isDeliveryModule()) {
$context->addViolation(
sprintf(Translator::getInstance()->trans("delivery module %s is not a Thelia\Module\DeliveryModuleInterface"), $module->getCode())
);
}
}

View File

@@ -66,16 +66,12 @@ class OrderPayment extends BaseForm
public function verifyPaymentModule($value, ExecutionContextInterface $context)
{
$module = ModuleQuery::create()
->filterByType(BaseModule::PAYMENT_MODULE_TYPE)
->filterByActivate(1)
->filterById($value)
->filterActivatedByTypeAndId(BaseModule::PAYMENT_MODULE_TYPE, $value)
->findOne();
if (null === $module) {
$context->addViolation("Payment module ID not found");
}
if (! $module->isPayementModule()) {
} elseif (! $module->isPayementModule()) {
$context->addViolation(
sprintf(Translator::getInstance()->trans("payment module %s is not a Thelia\Module\PaymentModuleInterface"), $module->getCode())
);

View File

@@ -12,8 +12,6 @@
namespace Thelia\Install;
use RecursiveDirectoryIterator;
use RecursiveIteratorIterator;
use Symfony\Component\Translation\TranslatorInterface;
use Thelia\Core\Translation\Translator;
@@ -175,14 +173,6 @@ class CheckPermission extends BaseInstall
*/
protected function makeDirectoryWritable($directory)
{
chmod($directory, 0777);
$iterator = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($directory)
);
foreach ($iterator as $item) {
chmod($item, 0777);
}
return (is_writable(THELIA_ROOT . $directory) === true);
}

View File

@@ -65,7 +65,7 @@ class Database
public function insertSql($dbName = null, array $extraSqlFiles = null)
{
if ($dbName) {
$this->connection->query(sprintf("use %s", $dbName));
$this->connection->query(sprintf("use `%s`", $dbName));
}
$sql = array();
@@ -146,7 +146,7 @@ class Database
{
$this->execute(
sprintf(
"CREATE DATABASE IF NOT EXISTS %s CHARACTER SET utf8",
"CREATE DATABASE IF NOT EXISTS `%s` CHARACTER SET utf8",
$dbName
)
);

View File

@@ -33,6 +33,7 @@ class Update
'4' => '2.0.0-RC1',
'5' => '2.0.0',
'6' => '2.0.1',
'7' => '2.0.2',
);
protected function isLatestVersion($version)
@@ -48,7 +49,6 @@ class Update
$logger = Tlog::getInstance();
$logger->setLevel(Tlog::DEBUG);
$success = true;
$updatedVersions = array();
$currentVersion = ConfigQuery::read('thelia_version');

View File

@@ -111,6 +111,7 @@ class Admin extends BaseAdmin implements UserInterface
public function eraseCredentials()
{
parent::setPassword(null);
$this->resetModified();
}
/**

View File

@@ -35,7 +35,10 @@ use Thelia\Model\OrderProductQuery as ChildOrderProductQuery;
use Thelia\Model\OrderQuery as ChildOrderQuery;
use Thelia\Model\OrderStatus as ChildOrderStatus;
use Thelia\Model\OrderStatusQuery as ChildOrderStatusQuery;
use Thelia\Model\OrderVersion as ChildOrderVersion;
use Thelia\Model\OrderVersionQuery as ChildOrderVersionQuery;
use Thelia\Model\Map\OrderTableMap;
use Thelia\Model\Map\OrderVersionTableMap;
abstract class Order implements ActiveRecordInterface
{
@@ -185,6 +188,25 @@ abstract class Order implements ActiveRecordInterface
*/
protected $updated_at;
/**
* The value for the version field.
* Note: this column has a database default value of: 0
* @var int
*/
protected $version;
/**
* The value for the version_created_at field.
* @var string
*/
protected $version_created_at;
/**
* The value for the version_created_by field.
* @var string
*/
protected $version_created_by;
/**
* @var Currency
*/
@@ -237,6 +259,12 @@ abstract class Order implements ActiveRecordInterface
protected $collOrderCoupons;
protected $collOrderCouponsPartial;
/**
* @var ObjectCollection|ChildOrderVersion[] Collection to store aggregation of ChildOrderVersion objects.
*/
protected $collOrderVersions;
protected $collOrderVersionsPartial;
/**
* Flag to prevent endless save loop, if this object is referenced
* by another object which falls in this transaction.
@@ -245,6 +273,14 @@ abstract class Order implements ActiveRecordInterface
*/
protected $alreadyInSave = false;
// versionable behavior
/**
* @var bool
*/
protected $enforceVersion = false;
/**
* An array of objects scheduled for deletion.
* @var ObjectCollection
@@ -257,11 +293,30 @@ abstract class Order implements ActiveRecordInterface
*/
protected $orderCouponsScheduledForDeletion = null;
/**
* An array of objects scheduled for deletion.
* @var ObjectCollection
*/
protected $orderVersionsScheduledForDeletion = null;
/**
* Applies default values to this object.
* This method should be called from the object's constructor (or
* equivalent initialization method).
* @see __construct()
*/
public function applyDefaultValues()
{
$this->version = 0;
}
/**
* Initializes internal state of Thelia\Model\Base\Order object.
* @see applyDefaults()
*/
public function __construct()
{
$this->applyDefaultValues();
}
/**
@@ -751,6 +806,48 @@ abstract class Order implements ActiveRecordInterface
}
}
/**
* Get the [version] column value.
*
* @return int
*/
public function getVersion()
{
return $this->version;
}
/**
* Get the [optionally formatted] temporal [version_created_at] column value.
*
*
* @param string $format The date/time format string (either date()-style or strftime()-style).
* If format is NULL, then the raw \DateTime object will be returned.
*
* @return mixed Formatted date/time value as string or \DateTime object (if format is NULL), NULL if column is NULL, and 0 if column value is 0000-00-00 00:00:00
*
* @throws PropelException - if unable to parse/validate the date/time value.
*/
public function getVersionCreatedAt($format = NULL)
{
if ($format === null) {
return $this->version_created_at;
} else {
return $this->version_created_at instanceof \DateTime ? $this->version_created_at->format($format) : null;
}
}
/**
* Get the [version_created_by] column value.
*
* @return string
*/
public function getVersionCreatedBy()
{
return $this->version_created_by;
}
/**
* Set the value of [id] column.
*
@@ -1182,6 +1279,69 @@ abstract class Order implements ActiveRecordInterface
return $this;
} // setUpdatedAt()
/**
* Set the value of [version] column.
*
* @param int $v new value
* @return \Thelia\Model\Order The current object (for fluent API support)
*/
public function setVersion($v)
{
if ($v !== null) {
$v = (int) $v;
}
if ($this->version !== $v) {
$this->version = $v;
$this->modifiedColumns[OrderTableMap::VERSION] = true;
}
return $this;
} // setVersion()
/**
* Sets the value of [version_created_at] column to a normalized version of the date/time value specified.
*
* @param mixed $v string, integer (timestamp), or \DateTime value.
* Empty strings are treated as NULL.
* @return \Thelia\Model\Order The current object (for fluent API support)
*/
public function setVersionCreatedAt($v)
{
$dt = PropelDateTime::newInstance($v, null, '\DateTime');
if ($this->version_created_at !== null || $dt !== null) {
if ($dt !== $this->version_created_at) {
$this->version_created_at = $dt;
$this->modifiedColumns[OrderTableMap::VERSION_CREATED_AT] = true;
}
} // if either are not null
return $this;
} // setVersionCreatedAt()
/**
* Set the value of [version_created_by] column.
*
* @param string $v new value
* @return \Thelia\Model\Order The current object (for fluent API support)
*/
public function setVersionCreatedBy($v)
{
if ($v !== null) {
$v = (string) $v;
}
if ($this->version_created_by !== $v) {
$this->version_created_by = $v;
$this->modifiedColumns[OrderTableMap::VERSION_CREATED_BY] = true;
}
return $this;
} // setVersionCreatedBy()
/**
* Indicates whether the columns in this object are only set to default values.
*
@@ -1192,6 +1352,10 @@ abstract class Order implements ActiveRecordInterface
*/
public function hasOnlyDefaultValues()
{
if ($this->version !== 0) {
return false;
}
// otherwise, everything was equal, so return TRUE
return true;
} // hasOnlyDefaultValues()
@@ -1284,6 +1448,18 @@ abstract class Order implements ActiveRecordInterface
$col = null;
}
$this->updated_at = (null !== $col) ? PropelDateTime::newInstance($col, null, '\DateTime') : null;
$col = $row[TableMap::TYPE_NUM == $indexType ? 19 + $startcol : OrderTableMap::translateFieldName('Version', TableMap::TYPE_PHPNAME, $indexType)];
$this->version = (null !== $col) ? (int) $col : null;
$col = $row[TableMap::TYPE_NUM == $indexType ? 20 + $startcol : OrderTableMap::translateFieldName('VersionCreatedAt', TableMap::TYPE_PHPNAME, $indexType)];
if ($col === '0000-00-00 00:00:00') {
$col = null;
}
$this->version_created_at = (null !== $col) ? PropelDateTime::newInstance($col, null, '\DateTime') : null;
$col = $row[TableMap::TYPE_NUM == $indexType ? 21 + $startcol : OrderTableMap::translateFieldName('VersionCreatedBy', TableMap::TYPE_PHPNAME, $indexType)];
$this->version_created_by = (null !== $col) ? (string) $col : null;
$this->resetModified();
$this->setNew(false);
@@ -1292,7 +1468,7 @@ abstract class Order implements ActiveRecordInterface
$this->ensureConsistency();
}
return $startcol + 19; // 19 = OrderTableMap::NUM_HYDRATE_COLUMNS.
return $startcol + 22; // 22 = OrderTableMap::NUM_HYDRATE_COLUMNS.
} catch (Exception $e) {
throw new PropelException("Error populating \Thelia\Model\Order object", 0, $e);
@@ -1389,6 +1565,8 @@ abstract class Order implements ActiveRecordInterface
$this->collOrderCoupons = null;
$this->collOrderVersions = null;
} // if (deep)
}
@@ -1457,6 +1635,14 @@ abstract class Order implements ActiveRecordInterface
$isInsert = $this->isNew();
try {
$ret = $this->preSave($con);
// versionable behavior
if ($this->isVersioningNecessary()) {
$this->setVersion($this->isNew() ? 1 : $this->getLastVersionNumber($con) + 1);
if (!$this->isColumnModified(OrderTableMap::VERSION_CREATED_AT)) {
$this->setVersionCreatedAt(time());
}
$createVersion = true; // for postSave hook
}
if ($isInsert) {
$ret = $ret && $this->preInsert($con);
// timestampable behavior
@@ -1481,6 +1667,10 @@ abstract class Order implements ActiveRecordInterface
$this->postUpdate($con);
}
$this->postSave($con);
// versionable behavior
if (isset($createVersion)) {
$this->addVersion($con);
}
OrderTableMap::addInstanceToPool($this);
} else {
$affectedRows = 0;
@@ -1617,6 +1807,23 @@ abstract class Order implements ActiveRecordInterface
}
}
if ($this->orderVersionsScheduledForDeletion !== null) {
if (!$this->orderVersionsScheduledForDeletion->isEmpty()) {
\Thelia\Model\OrderVersionQuery::create()
->filterByPrimaryKeys($this->orderVersionsScheduledForDeletion->getPrimaryKeys(false))
->delete($con);
$this->orderVersionsScheduledForDeletion = null;
}
}
if ($this->collOrderVersions !== null) {
foreach ($this->collOrderVersions as $referrerFK) {
if (!$referrerFK->isDeleted() && ($referrerFK->isNew() || $referrerFK->isModified())) {
$affectedRows += $referrerFK->save($con);
}
}
}
$this->alreadyInSave = false;
}
@@ -1700,6 +1907,15 @@ abstract class Order implements ActiveRecordInterface
if ($this->isColumnModified(OrderTableMap::UPDATED_AT)) {
$modifiedColumns[':p' . $index++] = '`UPDATED_AT`';
}
if ($this->isColumnModified(OrderTableMap::VERSION)) {
$modifiedColumns[':p' . $index++] = '`VERSION`';
}
if ($this->isColumnModified(OrderTableMap::VERSION_CREATED_AT)) {
$modifiedColumns[':p' . $index++] = '`VERSION_CREATED_AT`';
}
if ($this->isColumnModified(OrderTableMap::VERSION_CREATED_BY)) {
$modifiedColumns[':p' . $index++] = '`VERSION_CREATED_BY`';
}
$sql = sprintf(
'INSERT INTO `order` (%s) VALUES (%s)',
@@ -1768,6 +1984,15 @@ abstract class Order implements ActiveRecordInterface
case '`UPDATED_AT`':
$stmt->bindValue($identifier, $this->updated_at ? $this->updated_at->format("Y-m-d H:i:s") : null, PDO::PARAM_STR);
break;
case '`VERSION`':
$stmt->bindValue($identifier, $this->version, PDO::PARAM_INT);
break;
case '`VERSION_CREATED_AT`':
$stmt->bindValue($identifier, $this->version_created_at ? $this->version_created_at->format("Y-m-d H:i:s") : null, PDO::PARAM_STR);
break;
case '`VERSION_CREATED_BY`':
$stmt->bindValue($identifier, $this->version_created_by, PDO::PARAM_STR);
break;
}
}
$stmt->execute();
@@ -1887,6 +2112,15 @@ abstract class Order implements ActiveRecordInterface
case 18:
return $this->getUpdatedAt();
break;
case 19:
return $this->getVersion();
break;
case 20:
return $this->getVersionCreatedAt();
break;
case 21:
return $this->getVersionCreatedBy();
break;
default:
return null;
break;
@@ -1935,6 +2169,9 @@ abstract class Order implements ActiveRecordInterface
$keys[16] => $this->getLangId(),
$keys[17] => $this->getCreatedAt(),
$keys[18] => $this->getUpdatedAt(),
$keys[19] => $this->getVersion(),
$keys[20] => $this->getVersionCreatedAt(),
$keys[21] => $this->getVersionCreatedBy(),
);
$virtualColumns = $this->virtualColumns;
foreach ($virtualColumns as $key => $virtualColumn) {
@@ -1972,6 +2209,9 @@ abstract class Order implements ActiveRecordInterface
if (null !== $this->collOrderCoupons) {
$result['OrderCoupons'] = $this->collOrderCoupons->toArray(null, true, $keyType, $includeLazyLoadColumns, $alreadyDumpedObjects);
}
if (null !== $this->collOrderVersions) {
$result['OrderVersions'] = $this->collOrderVersions->toArray(null, true, $keyType, $includeLazyLoadColumns, $alreadyDumpedObjects);
}
}
return $result;
@@ -2063,6 +2303,15 @@ abstract class Order implements ActiveRecordInterface
case 18:
$this->setUpdatedAt($value);
break;
case 19:
$this->setVersion($value);
break;
case 20:
$this->setVersionCreatedAt($value);
break;
case 21:
$this->setVersionCreatedBy($value);
break;
} // switch()
}
@@ -2106,6 +2355,9 @@ abstract class Order implements ActiveRecordInterface
if (array_key_exists($keys[16], $arr)) $this->setLangId($arr[$keys[16]]);
if (array_key_exists($keys[17], $arr)) $this->setCreatedAt($arr[$keys[17]]);
if (array_key_exists($keys[18], $arr)) $this->setUpdatedAt($arr[$keys[18]]);
if (array_key_exists($keys[19], $arr)) $this->setVersion($arr[$keys[19]]);
if (array_key_exists($keys[20], $arr)) $this->setVersionCreatedAt($arr[$keys[20]]);
if (array_key_exists($keys[21], $arr)) $this->setVersionCreatedBy($arr[$keys[21]]);
}
/**
@@ -2136,6 +2388,9 @@ abstract class Order implements ActiveRecordInterface
if ($this->isColumnModified(OrderTableMap::LANG_ID)) $criteria->add(OrderTableMap::LANG_ID, $this->lang_id);
if ($this->isColumnModified(OrderTableMap::CREATED_AT)) $criteria->add(OrderTableMap::CREATED_AT, $this->created_at);
if ($this->isColumnModified(OrderTableMap::UPDATED_AT)) $criteria->add(OrderTableMap::UPDATED_AT, $this->updated_at);
if ($this->isColumnModified(OrderTableMap::VERSION)) $criteria->add(OrderTableMap::VERSION, $this->version);
if ($this->isColumnModified(OrderTableMap::VERSION_CREATED_AT)) $criteria->add(OrderTableMap::VERSION_CREATED_AT, $this->version_created_at);
if ($this->isColumnModified(OrderTableMap::VERSION_CREATED_BY)) $criteria->add(OrderTableMap::VERSION_CREATED_BY, $this->version_created_by);
return $criteria;
}
@@ -2217,6 +2472,9 @@ abstract class Order implements ActiveRecordInterface
$copyObj->setLangId($this->getLangId());
$copyObj->setCreatedAt($this->getCreatedAt());
$copyObj->setUpdatedAt($this->getUpdatedAt());
$copyObj->setVersion($this->getVersion());
$copyObj->setVersionCreatedAt($this->getVersionCreatedAt());
$copyObj->setVersionCreatedBy($this->getVersionCreatedBy());
if ($deepCopy) {
// important: temporarily setNew(false) because this affects the behavior of
@@ -2235,6 +2493,12 @@ abstract class Order implements ActiveRecordInterface
}
}
foreach ($this->getOrderVersions() as $relObj) {
if ($relObj !== $this) { // ensure that we don't try to copy a reference to ourselves
$copyObj->addOrderVersion($relObj->copy($deepCopy));
}
}
} // if ($deepCopy)
if ($makeNew) {
@@ -2690,6 +2954,9 @@ abstract class Order implements ActiveRecordInterface
if ('OrderCoupon' == $relationName) {
return $this->initOrderCoupons();
}
if ('OrderVersion' == $relationName) {
return $this->initOrderVersions();
}
}
/**
@@ -3128,6 +3395,227 @@ abstract class Order implements ActiveRecordInterface
return $this;
}
/**
* Clears out the collOrderVersions collection
*
* This does not modify the database; however, it will remove any associated objects, causing
* them to be refetched by subsequent calls to accessor method.
*
* @return void
* @see addOrderVersions()
*/
public function clearOrderVersions()
{
$this->collOrderVersions = null; // important to set this to NULL since that means it is uninitialized
}
/**
* Reset is the collOrderVersions collection loaded partially.
*/
public function resetPartialOrderVersions($v = true)
{
$this->collOrderVersionsPartial = $v;
}
/**
* Initializes the collOrderVersions collection.
*
* By default this just sets the collOrderVersions collection to an empty array (like clearcollOrderVersions());
* however, you may wish to override this method in your stub class to provide setting appropriate
* to your application -- for example, setting the initial array to the values stored in database.
*
* @param boolean $overrideExisting If set to true, the method call initializes
* the collection even if it is not empty
*
* @return void
*/
public function initOrderVersions($overrideExisting = true)
{
if (null !== $this->collOrderVersions && !$overrideExisting) {
return;
}
$this->collOrderVersions = new ObjectCollection();
$this->collOrderVersions->setModel('\Thelia\Model\OrderVersion');
}
/**
* Gets an array of ChildOrderVersion objects which contain a foreign key that references this object.
*
* If the $criteria is not null, it is used to always fetch the results from the database.
* Otherwise the results are fetched from the database the first time, then cached.
* Next time the same method is called without $criteria, the cached collection is returned.
* If this ChildOrder is new, it will return
* an empty collection or the current collection; the criteria is ignored on a new object.
*
* @param Criteria $criteria optional Criteria object to narrow the query
* @param ConnectionInterface $con optional connection object
* @return Collection|ChildOrderVersion[] List of ChildOrderVersion objects
* @throws PropelException
*/
public function getOrderVersions($criteria = null, ConnectionInterface $con = null)
{
$partial = $this->collOrderVersionsPartial && !$this->isNew();
if (null === $this->collOrderVersions || null !== $criteria || $partial) {
if ($this->isNew() && null === $this->collOrderVersions) {
// return empty collection
$this->initOrderVersions();
} else {
$collOrderVersions = ChildOrderVersionQuery::create(null, $criteria)
->filterByOrder($this)
->find($con);
if (null !== $criteria) {
if (false !== $this->collOrderVersionsPartial && count($collOrderVersions)) {
$this->initOrderVersions(false);
foreach ($collOrderVersions as $obj) {
if (false == $this->collOrderVersions->contains($obj)) {
$this->collOrderVersions->append($obj);
}
}
$this->collOrderVersionsPartial = true;
}
reset($collOrderVersions);
return $collOrderVersions;
}
if ($partial && $this->collOrderVersions) {
foreach ($this->collOrderVersions as $obj) {
if ($obj->isNew()) {
$collOrderVersions[] = $obj;
}
}
}
$this->collOrderVersions = $collOrderVersions;
$this->collOrderVersionsPartial = false;
}
}
return $this->collOrderVersions;
}
/**
* Sets a collection of OrderVersion objects related by a one-to-many relationship
* to the current object.
* It will also schedule objects for deletion based on a diff between old objects (aka persisted)
* and new objects from the given Propel collection.
*
* @param Collection $orderVersions A Propel collection.
* @param ConnectionInterface $con Optional connection object
* @return ChildOrder The current object (for fluent API support)
*/
public function setOrderVersions(Collection $orderVersions, ConnectionInterface $con = null)
{
$orderVersionsToDelete = $this->getOrderVersions(new Criteria(), $con)->diff($orderVersions);
//since at least one column in the foreign key is at the same time a PK
//we can not just set a PK to NULL in the lines below. We have to store
//a backup of all values, so we are able to manipulate these items based on the onDelete value later.
$this->orderVersionsScheduledForDeletion = clone $orderVersionsToDelete;
foreach ($orderVersionsToDelete as $orderVersionRemoved) {
$orderVersionRemoved->setOrder(null);
}
$this->collOrderVersions = null;
foreach ($orderVersions as $orderVersion) {
$this->addOrderVersion($orderVersion);
}
$this->collOrderVersions = $orderVersions;
$this->collOrderVersionsPartial = false;
return $this;
}
/**
* Returns the number of related OrderVersion objects.
*
* @param Criteria $criteria
* @param boolean $distinct
* @param ConnectionInterface $con
* @return int Count of related OrderVersion objects.
* @throws PropelException
*/
public function countOrderVersions(Criteria $criteria = null, $distinct = false, ConnectionInterface $con = null)
{
$partial = $this->collOrderVersionsPartial && !$this->isNew();
if (null === $this->collOrderVersions || null !== $criteria || $partial) {
if ($this->isNew() && null === $this->collOrderVersions) {
return 0;
}
if ($partial && !$criteria) {
return count($this->getOrderVersions());
}
$query = ChildOrderVersionQuery::create(null, $criteria);
if ($distinct) {
$query->distinct();
}
return $query
->filterByOrder($this)
->count($con);
}
return count($this->collOrderVersions);
}
/**
* Method called to associate a ChildOrderVersion object to this object
* through the ChildOrderVersion foreign key attribute.
*
* @param ChildOrderVersion $l ChildOrderVersion
* @return \Thelia\Model\Order The current object (for fluent API support)
*/
public function addOrderVersion(ChildOrderVersion $l)
{
if ($this->collOrderVersions === null) {
$this->initOrderVersions();
$this->collOrderVersionsPartial = true;
}
if (!in_array($l, $this->collOrderVersions->getArrayCopy(), true)) { // only add it if the **same** object is not already associated
$this->doAddOrderVersion($l);
}
return $this;
}
/**
* @param OrderVersion $orderVersion The orderVersion object to add.
*/
protected function doAddOrderVersion($orderVersion)
{
$this->collOrderVersions[]= $orderVersion;
$orderVersion->setOrder($this);
}
/**
* @param OrderVersion $orderVersion The orderVersion object to remove.
* @return ChildOrder The current object (for fluent API support)
*/
public function removeOrderVersion($orderVersion)
{
if ($this->getOrderVersions()->contains($orderVersion)) {
$this->collOrderVersions->remove($this->collOrderVersions->search($orderVersion));
if (null === $this->orderVersionsScheduledForDeletion) {
$this->orderVersionsScheduledForDeletion = clone $this->collOrderVersions;
$this->orderVersionsScheduledForDeletion->clear();
}
$this->orderVersionsScheduledForDeletion[]= clone $orderVersion;
$orderVersion->setOrder(null);
}
return $this;
}
/**
* Clears the current object and sets all attributes to their default values
*/
@@ -3152,8 +3640,12 @@ abstract class Order implements ActiveRecordInterface
$this->lang_id = null;
$this->created_at = null;
$this->updated_at = null;
$this->version = null;
$this->version_created_at = null;
$this->version_created_by = null;
$this->alreadyInSave = false;
$this->clearAllReferences();
$this->applyDefaultValues();
$this->resetModified();
$this->setNew(true);
$this->setDeleted(false);
@@ -3181,10 +3673,16 @@ abstract class Order implements ActiveRecordInterface
$o->clearAllReferences($deep);
}
}
if ($this->collOrderVersions) {
foreach ($this->collOrderVersions as $o) {
$o->clearAllReferences($deep);
}
}
} // if ($deep)
$this->collOrderProducts = null;
$this->collOrderCoupons = null;
$this->collOrderVersions = null;
$this->aCurrency = null;
$this->aCustomer = null;
$this->aOrderAddressRelatedByInvoiceOrderAddressId = null;
@@ -3219,6 +3717,316 @@ abstract class Order implements ActiveRecordInterface
return $this;
}
// versionable behavior
/**
* Enforce a new Version of this object upon next save.
*
* @return \Thelia\Model\Order
*/
public function enforceVersioning()
{
$this->enforceVersion = true;
return $this;
}
/**
* Checks whether the current state must be recorded as a version
*
* @return boolean
*/
public function isVersioningNecessary($con = null)
{
if ($this->alreadyInSave) {
return false;
}
if ($this->enforceVersion) {
return true;
}
if (ChildOrderQuery::isVersioningEnabled() && ($this->isNew() || $this->isModified()) || $this->isDeleted()) {
return true;
}
return false;
}
/**
* Creates a version of the current object and saves it.
*
* @param ConnectionInterface $con the connection to use
*
* @return ChildOrderVersion A version object
*/
public function addVersion($con = null)
{
$this->enforceVersion = false;
$version = new ChildOrderVersion();
$version->setId($this->getId());
$version->setRef($this->getRef());
$version->setCustomerId($this->getCustomerId());
$version->setInvoiceOrderAddressId($this->getInvoiceOrderAddressId());
$version->setDeliveryOrderAddressId($this->getDeliveryOrderAddressId());
$version->setInvoiceDate($this->getInvoiceDate());
$version->setCurrencyId($this->getCurrencyId());
$version->setCurrencyRate($this->getCurrencyRate());
$version->setTransactionRef($this->getTransactionRef());
$version->setDeliveryRef($this->getDeliveryRef());
$version->setInvoiceRef($this->getInvoiceRef());
$version->setDiscount($this->getDiscount());
$version->setPostage($this->getPostage());
$version->setPaymentModuleId($this->getPaymentModuleId());
$version->setDeliveryModuleId($this->getDeliveryModuleId());
$version->setStatusId($this->getStatusId());
$version->setLangId($this->getLangId());
$version->setCreatedAt($this->getCreatedAt());
$version->setUpdatedAt($this->getUpdatedAt());
$version->setVersion($this->getVersion());
$version->setVersionCreatedAt($this->getVersionCreatedAt());
$version->setVersionCreatedBy($this->getVersionCreatedBy());
$version->setOrder($this);
$version->save($con);
return $version;
}
/**
* Sets the properties of the current object to the value they had at a specific version
*
* @param integer $versionNumber The version number to read
* @param ConnectionInterface $con The connection to use
*
* @return ChildOrder The current object (for fluent API support)
*/
public function toVersion($versionNumber, $con = null)
{
$version = $this->getOneVersion($versionNumber, $con);
if (!$version) {
throw new PropelException(sprintf('No ChildOrder object found with version %d', $version));
}
$this->populateFromVersion($version, $con);
return $this;
}
/**
* Sets the properties of the current object to the value they had at a specific version
*
* @param ChildOrderVersion $version The version object to use
* @param ConnectionInterface $con the connection to use
* @param array $loadedObjects objects that been loaded in a chain of populateFromVersion calls on referrer or fk objects.
*
* @return ChildOrder The current object (for fluent API support)
*/
public function populateFromVersion($version, $con = null, &$loadedObjects = array())
{
$loadedObjects['ChildOrder'][$version->getId()][$version->getVersion()] = $this;
$this->setId($version->getId());
$this->setRef($version->getRef());
$this->setCustomerId($version->getCustomerId());
$this->setInvoiceOrderAddressId($version->getInvoiceOrderAddressId());
$this->setDeliveryOrderAddressId($version->getDeliveryOrderAddressId());
$this->setInvoiceDate($version->getInvoiceDate());
$this->setCurrencyId($version->getCurrencyId());
$this->setCurrencyRate($version->getCurrencyRate());
$this->setTransactionRef($version->getTransactionRef());
$this->setDeliveryRef($version->getDeliveryRef());
$this->setInvoiceRef($version->getInvoiceRef());
$this->setDiscount($version->getDiscount());
$this->setPostage($version->getPostage());
$this->setPaymentModuleId($version->getPaymentModuleId());
$this->setDeliveryModuleId($version->getDeliveryModuleId());
$this->setStatusId($version->getStatusId());
$this->setLangId($version->getLangId());
$this->setCreatedAt($version->getCreatedAt());
$this->setUpdatedAt($version->getUpdatedAt());
$this->setVersion($version->getVersion());
$this->setVersionCreatedAt($version->getVersionCreatedAt());
$this->setVersionCreatedBy($version->getVersionCreatedBy());
return $this;
}
/**
* Gets the latest persisted version number for the current object
*
* @param ConnectionInterface $con the connection to use
*
* @return integer
*/
public function getLastVersionNumber($con = null)
{
$v = ChildOrderVersionQuery::create()
->filterByOrder($this)
->orderByVersion('desc')
->findOne($con);
if (!$v) {
return 0;
}
return $v->getVersion();
}
/**
* Checks whether the current object is the latest one
*
* @param ConnectionInterface $con the connection to use
*
* @return Boolean
*/
public function isLastVersion($con = null)
{
return $this->getLastVersionNumber($con) == $this->getVersion();
}
/**
* Retrieves a version object for this entity and a version number
*
* @param integer $versionNumber The version number to read
* @param ConnectionInterface $con the connection to use
*
* @return ChildOrderVersion A version object
*/
public function getOneVersion($versionNumber, $con = null)
{
return ChildOrderVersionQuery::create()
->filterByOrder($this)
->filterByVersion($versionNumber)
->findOne($con);
}
/**
* Gets all the versions of this object, in incremental order
*
* @param ConnectionInterface $con the connection to use
*
* @return ObjectCollection A list of ChildOrderVersion objects
*/
public function getAllVersions($con = null)
{
$criteria = new Criteria();
$criteria->addAscendingOrderByColumn(OrderVersionTableMap::VERSION);
return $this->getOrderVersions($criteria, $con);
}
/**
* Compares the current object with another of its version.
* <code>
* print_r($book->compareVersion(1));
* => array(
* '1' => array('Title' => 'Book title at version 1'),
* '2' => array('Title' => 'Book title at version 2')
* );
* </code>
*
* @param integer $versionNumber
* @param string $keys Main key used for the result diff (versions|columns)
* @param ConnectionInterface $con the connection to use
* @param array $ignoredColumns The columns to exclude from the diff.
*
* @return array A list of differences
*/
public function compareVersion($versionNumber, $keys = 'columns', $con = null, $ignoredColumns = array())
{
$fromVersion = $this->toArray();
$toVersion = $this->getOneVersion($versionNumber, $con)->toArray();
return $this->computeDiff($fromVersion, $toVersion, $keys, $ignoredColumns);
}
/**
* Compares two versions of the current object.
* <code>
* print_r($book->compareVersions(1, 2));
* => array(
* '1' => array('Title' => 'Book title at version 1'),
* '2' => array('Title' => 'Book title at version 2')
* );
* </code>
*
* @param integer $fromVersionNumber
* @param integer $toVersionNumber
* @param string $keys Main key used for the result diff (versions|columns)
* @param ConnectionInterface $con the connection to use
* @param array $ignoredColumns The columns to exclude from the diff.
*
* @return array A list of differences
*/
public function compareVersions($fromVersionNumber, $toVersionNumber, $keys = 'columns', $con = null, $ignoredColumns = array())
{
$fromVersion = $this->getOneVersion($fromVersionNumber, $con)->toArray();
$toVersion = $this->getOneVersion($toVersionNumber, $con)->toArray();
return $this->computeDiff($fromVersion, $toVersion, $keys, $ignoredColumns);
}
/**
* Computes the diff between two versions.
* <code>
* print_r($book->computeDiff(1, 2));
* => array(
* '1' => array('Title' => 'Book title at version 1'),
* '2' => array('Title' => 'Book title at version 2')
* );
* </code>
*
* @param array $fromVersion An array representing the original version.
* @param array $toVersion An array representing the destination version.
* @param string $keys Main key used for the result diff (versions|columns).
* @param array $ignoredColumns The columns to exclude from the diff.
*
* @return array A list of differences
*/
protected function computeDiff($fromVersion, $toVersion, $keys = 'columns', $ignoredColumns = array())
{
$fromVersionNumber = $fromVersion['Version'];
$toVersionNumber = $toVersion['Version'];
$ignoredColumns = array_merge(array(
'Version',
'VersionCreatedAt',
'VersionCreatedBy',
), $ignoredColumns);
$diff = array();
foreach ($fromVersion as $key => $value) {
if (in_array($key, $ignoredColumns)) {
continue;
}
if ($toVersion[$key] != $value) {
switch ($keys) {
case 'versions':
$diff[$fromVersionNumber][$key] = $value;
$diff[$toVersionNumber][$key] = $toVersion[$key];
break;
default:
$diff[$key] = array(
$fromVersionNumber => $value,
$toVersionNumber => $toVersion[$key],
);
break;
}
}
}
return $diff;
}
/**
* retrieve the last $number versions.
*
* @param Integer $number the number of record to return.
* @return PropelCollection|array \Thelia\Model\OrderVersion[] List of \Thelia\Model\OrderVersion objects
*/
public function getLastVersions($number = 10, $criteria = null, $con = null)
{
$criteria = ChildOrderVersionQuery::create(null, $criteria);
$criteria->addDescendingOrderByColumn(OrderVersionTableMap::VERSION);
$criteria->limit($number);
return $this->getOrderVersions($criteria, $con);
}
/**
* Code to be run before persisting the object
* @param ConnectionInterface $con

View File

@@ -40,6 +40,9 @@ use Thelia\Model\Map\OrderTableMap;
* @method ChildOrderQuery orderByLangId($order = Criteria::ASC) Order by the lang_id column
* @method ChildOrderQuery orderByCreatedAt($order = Criteria::ASC) Order by the created_at column
* @method ChildOrderQuery orderByUpdatedAt($order = Criteria::ASC) Order by the updated_at column
* @method ChildOrderQuery orderByVersion($order = Criteria::ASC) Order by the version column
* @method ChildOrderQuery orderByVersionCreatedAt($order = Criteria::ASC) Order by the version_created_at column
* @method ChildOrderQuery orderByVersionCreatedBy($order = Criteria::ASC) Order by the version_created_by column
*
* @method ChildOrderQuery groupById() Group by the id column
* @method ChildOrderQuery groupByRef() Group by the ref column
@@ -60,6 +63,9 @@ use Thelia\Model\Map\OrderTableMap;
* @method ChildOrderQuery groupByLangId() Group by the lang_id column
* @method ChildOrderQuery groupByCreatedAt() Group by the created_at column
* @method ChildOrderQuery groupByUpdatedAt() Group by the updated_at column
* @method ChildOrderQuery groupByVersion() Group by the version column
* @method ChildOrderQuery groupByVersionCreatedAt() Group by the version_created_at column
* @method ChildOrderQuery groupByVersionCreatedBy() Group by the version_created_by column
*
* @method ChildOrderQuery leftJoin($relation) Adds a LEFT JOIN clause to the query
* @method ChildOrderQuery rightJoin($relation) Adds a RIGHT JOIN clause to the query
@@ -105,6 +111,10 @@ use Thelia\Model\Map\OrderTableMap;
* @method ChildOrderQuery rightJoinOrderCoupon($relationAlias = null) Adds a RIGHT JOIN clause to the query using the OrderCoupon relation
* @method ChildOrderQuery innerJoinOrderCoupon($relationAlias = null) Adds a INNER JOIN clause to the query using the OrderCoupon relation
*
* @method ChildOrderQuery leftJoinOrderVersion($relationAlias = null) Adds a LEFT JOIN clause to the query using the OrderVersion relation
* @method ChildOrderQuery rightJoinOrderVersion($relationAlias = null) Adds a RIGHT JOIN clause to the query using the OrderVersion relation
* @method ChildOrderQuery innerJoinOrderVersion($relationAlias = null) Adds a INNER JOIN clause to the query using the OrderVersion relation
*
* @method ChildOrder findOne(ConnectionInterface $con = null) Return the first ChildOrder matching the query
* @method ChildOrder findOneOrCreate(ConnectionInterface $con = null) Return the first ChildOrder matching the query, or a new ChildOrder object populated from the query conditions when no match is found
*
@@ -127,6 +137,9 @@ use Thelia\Model\Map\OrderTableMap;
* @method ChildOrder findOneByLangId(int $lang_id) Return the first ChildOrder filtered by the lang_id column
* @method ChildOrder findOneByCreatedAt(string $created_at) Return the first ChildOrder filtered by the created_at column
* @method ChildOrder findOneByUpdatedAt(string $updated_at) Return the first ChildOrder filtered by the updated_at column
* @method ChildOrder findOneByVersion(int $version) Return the first ChildOrder filtered by the version column
* @method ChildOrder findOneByVersionCreatedAt(string $version_created_at) Return the first ChildOrder filtered by the version_created_at column
* @method ChildOrder findOneByVersionCreatedBy(string $version_created_by) Return the first ChildOrder filtered by the version_created_by column
*
* @method array findById(int $id) Return ChildOrder objects filtered by the id column
* @method array findByRef(string $ref) Return ChildOrder objects filtered by the ref column
@@ -147,11 +160,21 @@ use Thelia\Model\Map\OrderTableMap;
* @method array findByLangId(int $lang_id) Return ChildOrder objects filtered by the lang_id column
* @method array findByCreatedAt(string $created_at) Return ChildOrder objects filtered by the created_at column
* @method array findByUpdatedAt(string $updated_at) Return ChildOrder objects filtered by the updated_at column
* @method array findByVersion(int $version) Return ChildOrder objects filtered by the version column
* @method array findByVersionCreatedAt(string $version_created_at) Return ChildOrder objects filtered by the version_created_at column
* @method array findByVersionCreatedBy(string $version_created_by) Return ChildOrder objects filtered by the version_created_by column
*
*/
abstract class OrderQuery extends ModelCriteria
{
// versionable behavior
/**
* Whether the versioning is enabled
*/
static $isVersioningEnabled = true;
/**
* Initializes internal state of \Thelia\Model\Base\OrderQuery object.
*
@@ -235,7 +258,7 @@ abstract class OrderQuery extends ModelCriteria
*/
protected function findPkSimple($key, $con)
{
$sql = 'SELECT `ID`, `REF`, `CUSTOMER_ID`, `INVOICE_ORDER_ADDRESS_ID`, `DELIVERY_ORDER_ADDRESS_ID`, `INVOICE_DATE`, `CURRENCY_ID`, `CURRENCY_RATE`, `TRANSACTION_REF`, `DELIVERY_REF`, `INVOICE_REF`, `DISCOUNT`, `POSTAGE`, `PAYMENT_MODULE_ID`, `DELIVERY_MODULE_ID`, `STATUS_ID`, `LANG_ID`, `CREATED_AT`, `UPDATED_AT` FROM `order` WHERE `ID` = :p0';
$sql = 'SELECT `ID`, `REF`, `CUSTOMER_ID`, `INVOICE_ORDER_ADDRESS_ID`, `DELIVERY_ORDER_ADDRESS_ID`, `INVOICE_DATE`, `CURRENCY_ID`, `CURRENCY_RATE`, `TRANSACTION_REF`, `DELIVERY_REF`, `INVOICE_REF`, `DISCOUNT`, `POSTAGE`, `PAYMENT_MODULE_ID`, `DELIVERY_MODULE_ID`, `STATUS_ID`, `LANG_ID`, `CREATED_AT`, `UPDATED_AT`, `VERSION`, `VERSION_CREATED_AT`, `VERSION_CREATED_BY` FROM `order` WHERE `ID` = :p0';
try {
$stmt = $con->prepare($sql);
$stmt->bindValue(':p0', $key, PDO::PARAM_INT);
@@ -1077,6 +1100,119 @@ abstract class OrderQuery extends ModelCriteria
return $this->addUsingAlias(OrderTableMap::UPDATED_AT, $updatedAt, $comparison);
}
/**
* Filter the query on the version column
*
* Example usage:
* <code>
* $query->filterByVersion(1234); // WHERE version = 1234
* $query->filterByVersion(array(12, 34)); // WHERE version IN (12, 34)
* $query->filterByVersion(array('min' => 12)); // WHERE version > 12
* </code>
*
* @param mixed $version The value to use as filter.
* Use scalar values for equality.
* Use array values for in_array() equivalent.
* Use associative array('min' => $minValue, 'max' => $maxValue) for intervals.
* @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL
*
* @return ChildOrderQuery The current query, for fluid interface
*/
public function filterByVersion($version = null, $comparison = null)
{
if (is_array($version)) {
$useMinMax = false;
if (isset($version['min'])) {
$this->addUsingAlias(OrderTableMap::VERSION, $version['min'], Criteria::GREATER_EQUAL);
$useMinMax = true;
}
if (isset($version['max'])) {
$this->addUsingAlias(OrderTableMap::VERSION, $version['max'], Criteria::LESS_EQUAL);
$useMinMax = true;
}
if ($useMinMax) {
return $this;
}
if (null === $comparison) {
$comparison = Criteria::IN;
}
}
return $this->addUsingAlias(OrderTableMap::VERSION, $version, $comparison);
}
/**
* Filter the query on the version_created_at column
*
* Example usage:
* <code>
* $query->filterByVersionCreatedAt('2011-03-14'); // WHERE version_created_at = '2011-03-14'
* $query->filterByVersionCreatedAt('now'); // WHERE version_created_at = '2011-03-14'
* $query->filterByVersionCreatedAt(array('max' => 'yesterday')); // WHERE version_created_at > '2011-03-13'
* </code>
*
* @param mixed $versionCreatedAt The value to use as filter.
* Values can be integers (unix timestamps), DateTime objects, or strings.
* Empty strings are treated as NULL.
* Use scalar values for equality.
* Use array values for in_array() equivalent.
* Use associative array('min' => $minValue, 'max' => $maxValue) for intervals.
* @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL
*
* @return ChildOrderQuery The current query, for fluid interface
*/
public function filterByVersionCreatedAt($versionCreatedAt = null, $comparison = null)
{
if (is_array($versionCreatedAt)) {
$useMinMax = false;
if (isset($versionCreatedAt['min'])) {
$this->addUsingAlias(OrderTableMap::VERSION_CREATED_AT, $versionCreatedAt['min'], Criteria::GREATER_EQUAL);
$useMinMax = true;
}
if (isset($versionCreatedAt['max'])) {
$this->addUsingAlias(OrderTableMap::VERSION_CREATED_AT, $versionCreatedAt['max'], Criteria::LESS_EQUAL);
$useMinMax = true;
}
if ($useMinMax) {
return $this;
}
if (null === $comparison) {
$comparison = Criteria::IN;
}
}
return $this->addUsingAlias(OrderTableMap::VERSION_CREATED_AT, $versionCreatedAt, $comparison);
}
/**
* Filter the query on the version_created_by column
*
* Example usage:
* <code>
* $query->filterByVersionCreatedBy('fooValue'); // WHERE version_created_by = 'fooValue'
* $query->filterByVersionCreatedBy('%fooValue%'); // WHERE version_created_by LIKE '%fooValue%'
* </code>
*
* @param string $versionCreatedBy The value to use as filter.
* Accepts wildcards (* and % trigger a LIKE)
* @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL
*
* @return ChildOrderQuery The current query, for fluid interface
*/
public function filterByVersionCreatedBy($versionCreatedBy = null, $comparison = null)
{
if (null === $comparison) {
if (is_array($versionCreatedBy)) {
$comparison = Criteria::IN;
} elseif (preg_match('/[\%\*]/', $versionCreatedBy)) {
$versionCreatedBy = str_replace('*', '%', $versionCreatedBy);
$comparison = Criteria::LIKE;
}
}
return $this->addUsingAlias(OrderTableMap::VERSION_CREATED_BY, $versionCreatedBy, $comparison);
}
/**
* Filter the query by a related \Thelia\Model\Currency object
*
@@ -1823,6 +1959,79 @@ abstract class OrderQuery extends ModelCriteria
->useQuery($relationAlias ? $relationAlias : 'OrderCoupon', '\Thelia\Model\OrderCouponQuery');
}
/**
* Filter the query by a related \Thelia\Model\OrderVersion object
*
* @param \Thelia\Model\OrderVersion|ObjectCollection $orderVersion the related object to use as filter
* @param string $comparison Operator to use for the column comparison, defaults to Criteria::EQUAL
*
* @return ChildOrderQuery The current query, for fluid interface
*/
public function filterByOrderVersion($orderVersion, $comparison = null)
{
if ($orderVersion instanceof \Thelia\Model\OrderVersion) {
return $this
->addUsingAlias(OrderTableMap::ID, $orderVersion->getId(), $comparison);
} elseif ($orderVersion instanceof ObjectCollection) {
return $this
->useOrderVersionQuery()
->filterByPrimaryKeys($orderVersion->getPrimaryKeys())
->endUse();
} else {
throw new PropelException('filterByOrderVersion() only accepts arguments of type \Thelia\Model\OrderVersion or Collection');
}
}
/**
* Adds a JOIN clause to the query using the OrderVersion relation
*
* @param string $relationAlias optional alias for the relation
* @param string $joinType Accepted values are null, 'left join', 'right join', 'inner join'
*
* @return ChildOrderQuery The current query, for fluid interface
*/
public function joinOrderVersion($relationAlias = null, $joinType = Criteria::INNER_JOIN)
{
$tableMap = $this->getTableMap();
$relationMap = $tableMap->getRelation('OrderVersion');
// create a ModelJoin object for this join
$join = new ModelJoin();
$join->setJoinType($joinType);
$join->setRelationMap($relationMap, $this->useAliasInSQL ? $this->getModelAlias() : null, $relationAlias);
if ($previousJoin = $this->getPreviousJoin()) {
$join->setPreviousJoin($previousJoin);
}
// add the ModelJoin to the current object
if ($relationAlias) {
$this->addAlias($relationAlias, $relationMap->getRightTable()->getName());
$this->addJoinObject($join, $relationAlias);
} else {
$this->addJoinObject($join, 'OrderVersion');
}
return $this;
}
/**
* Use the OrderVersion relation OrderVersion object
*
* @see useQuery()
*
* @param string $relationAlias optional alias for the relation,
* to be used as main alias in the secondary query
* @param string $joinType Accepted values are null, 'left join', 'right join', 'inner join'
*
* @return \Thelia\Model\OrderVersionQuery A secondary query class using the current class as primary query
*/
public function useOrderVersionQuery($relationAlias = null, $joinType = Criteria::INNER_JOIN)
{
return $this
->joinOrderVersion($relationAlias, $joinType)
->useQuery($relationAlias ? $relationAlias : 'OrderVersion', '\Thelia\Model\OrderVersionQuery');
}
/**
* Exclude object from result
*
@@ -1980,4 +2189,32 @@ abstract class OrderQuery extends ModelCriteria
return $this->addAscendingOrderByColumn(OrderTableMap::CREATED_AT);
}
// versionable behavior
/**
* Checks whether versioning is enabled
*
* @return boolean
*/
static public function isVersioningEnabled()
{
return self::$isVersioningEnabled;
}
/**
* Enables versioning
*/
static public function enableVersioning()
{
self::$isVersioningEnabled = true;
}
/**
* Disables versioning
*/
static public function disableVersioning()
{
self::$isVersioningEnabled = false;
}
} // OrderQuery

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,28 @@
<?php
/*************************************************************************************/
/* This file is part of the Thelia package. */
/* */
/* Copyright (c) OpenStudio */
/* email : dev@thelia.net */
/* web : http://www.thelia.net */
/* */
/* For the full copyright and license information, please view the LICENSE.txt */
/* file that was distributed with this source code. */
/*************************************************************************************/
namespace Thelia\Model\Breadcrumb;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\Routing\Router;
interface BreadcrumbInterface
{
/**
*
* return the complete breadcrumb for a given resource.
*
* @return array
*/
public function getBreadcrumb(Router $router, ContainerInterface $container, $tab);
}

View File

@@ -0,0 +1,84 @@
<?php
/*************************************************************************************/
/* This file is part of the Thelia package. */
/* */
/* Copyright (c) OpenStudio */
/* email : dev@thelia.net */
/* web : http://www.thelia.net */
/* */
/* For the full copyright and license information, please view the LICENSE.txt */
/* file that was distributed with this source code. */
/*************************************************************************************/
namespace Thelia\Model\Breadcrumb;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\Routing\Router;
use Thelia\Core\Template\Loop\CategoryPath;
use Thelia\Core\Translation\Translator;
trait CatalogBreadcrumbTrait
{
public function getBaseBreadcrumb(Router $router, ContainerInterface $container, $categoryId, &$locale)
{
$translator = Translator::getInstance();
$catalogUrl = $router->generate('admin.catalog', [], Router::ABSOLUTE_URL);
$breadcrumb = [
$translator->trans('Home', [], 'bo.default') => $router->generate('admin.home.view', [], Router::ABSOLUTE_URL),
$translator->trans('Catalog', [], 'bo.default') => $catalogUrl,
];
$categoryPath = new CategoryPath($container);
$categoryPath->initializeArgs([
'category' => $categoryId,
'visible' => '*'
]);
$results = $categoryPath->buildArray();
foreach ($results as $result) {
$breadcrumb[$result['TITLE']] = sprintf("%s?category_id=%d",$catalogUrl, $result['ID']);
}
$locale = $result['LOCALE'];
return $breadcrumb;
}
public function getProductBreadcrumb(Router $router, ContainerInterface $container, $tab)
{
$product = $this->getProduct();
$locale = null;
$breadcrumb = $this->getBaseBreadcrumb($router, $container, $product->getDefaultCategoryId(), $locale);
$product->setLocale($locale);
$breadcrumb[$product->getTitle()] = sprintf("%s?product_id=%d&current_tab=%s",
$router->generate('admin.products.update', [], Router::ABSOLUTE_URL),
$product->getId(),
$tab
);
return $breadcrumb;
}
public function getCategoryBreadcrumb(Router $router, ContainerInterface $container, $tab)
{
$locale = null;
$category = $this->getCategory();
$breadcrumb = $this->getBaseBreadcrumb($router, $container, $this->getParentId(), $locale);
$category->setLocale($locale);
$breadcrumb[$category->getTitle()] = sprintf("%s?category_id=%d&current_tab=%s",
$router->generate('admin.categories.update',[], Router::ABSOLUTE_URL),
$category->getId(),
$tab
);
return $breadcrumb;
}
}

View File

@@ -0,0 +1,85 @@
<?php
/*************************************************************************************/
/* This file is part of the Thelia package. */
/* */
/* Copyright (c) OpenStudio */
/* email : dev@thelia.net */
/* web : http://www.thelia.net */
/* */
/* For the full copyright and license information, please view the LICENSE.txt */
/* file that was distributed with this source code. */
/*************************************************************************************/
namespace Thelia\Model\Breadcrumb;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\Routing\Router;
use Thelia\Core\Template\Loop\FolderPath;
use Thelia\Core\Translation\Translator;
trait FolderBreadcrumbTrait
{
public function getBaseBreadcrumb(Router $router, ContainerInterface $container, $folderId, &$locale)
{
$translator = Translator::getInstance();
$catalogUrl = $router->generate('admin.catalog', [], Router::ABSOLUTE_URL);
$breadcrumb = [
$translator->trans('Home', [], 'bo.default') => $router->generate('admin.home.view', [], Router::ABSOLUTE_URL),
$translator->trans('Folder', [], 'bo.default') => $catalogUrl,
];
$folderPath = new FolderPath($container);
$folderPath->initializeArgs([
'folder' => $folderId,
'visible' => '*'
]);
$results = $folderPath->buildArray();
foreach ($results as $result) {
$breadcrumb[$result['TITLE']] = sprintf("%s?folder_id=%d",
$router->generate('admin.folders.default',[], Router::ABSOLUTE_URL),
$result['ID']
);
}
$locale = $result['LOCALE'];
return $breadcrumb;
}
public function getFolderBreadcrumb($router, $container, $tab)
{
$locale = null;
$folder = $this->getFolder();
$breadcrumb = $this->getBaseBreadcrumb($router, $container, $this->getParentId(), $locale);
$folder->setLocale($locale);
$breadcrumb[$folder->getTitle()] = sprintf("%s?current_tab=%s",
$router->generate('admin.folders.update',['folder_id' => $folder->getId()], Router::ABSOLUTE_URL),
$tab
);
return $breadcrumb;
}
public function getContentBreadcrumb(Router $router, ContainerInterface $container, $tab)
{
$content = $this->getContent();
$locale = null;
$breadcrumb = $this->getBaseBreadcrumb($router, $container, $content->getDefaultFolderId(), $locale);
$content->setLocale($locale);
$breadcrumb[$content->getTitle()] = sprintf("%s?current_tab=%s",
$router->generate('admin.content.update', ['content_id' => $content->getId()], Router::ABSOLUTE_URL),
$tab
);
return $breadcrumb;
}
}

View File

@@ -44,7 +44,6 @@ class Cart extends BaseCart
}
$cart->save();
$currentDateTime = new \DateTime();
foreach ($cartItems as $cartItem) {
$product = $cartItem->getProduct();

View File

@@ -89,6 +89,23 @@ class CartItem extends BaseCartItem
return $this->getPromo() == 1 ? $this->getPromoPrice() : $this->getPrice();
}
public function getProduct(ConnectionInterface $con = null, $locale = null)
{
$product = parent::getProduct($con);
$translation = $product->getTranslation($locale);
if ($translation->isNew()) {
if (ConfigQuery::getDefaultLangWhenNoTranslationAvailable()) {
$locale = Lang::getDefaultLanguage()->getLocale();
}
}
$product->setLocale($locale);
return $product;
}
public function getRealTaxedPrice(Country $country)
{
return $this->getPromo() == 1 ? $this->getTaxedPromoPrice($country) : $this->getTaxedPrice($country);

View File

@@ -2,13 +2,20 @@
namespace Thelia\Model;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\Routing\Router;
use Thelia\Model\Base\CategoryDocument as BaseCategoryDocument;
use Propel\Runtime\Connection\ConnectionInterface;
use Thelia\Model\Breadcrumb\BreadcrumbInterface;
use Thelia\Model\Breadcrumb\CatalogBreadcrumbTrait;
use Thelia\Model\Tools\PositionManagementTrait;
use Thelia\Model\Tools\ModelEventDispatcherTrait;
class CategoryDocument extends BaseCategoryDocument
class CategoryDocument extends BaseCategoryDocument implements BreadcrumbInterface
{
use \Thelia\Model\Tools\ModelEventDispatcherTrait;
use \Thelia\Model\Tools\PositionManagementTrait;
use ModelEventDispatcherTrait;
use PositionManagementTrait;
use CatalogBreadcrumbTrait;
/**
* Calculate next position relative to our parent
@@ -62,4 +69,15 @@ class CategoryDocument extends BaseCategoryDocument
return true;
}
/**
*
* return the complete breadcrumb for a given resource.
*
* @return array
*/
public function getBreadcrumb(Router $router, ContainerInterface $container, $tab)
{
return $this->getCategoryBreadcrumb($router, $container, $tab);
}
}

View File

@@ -2,13 +2,20 @@
namespace Thelia\Model;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\Routing\Router;
use Thelia\Model\Base\CategoryImage as BaseCategoryImage;
use Propel\Runtime\Connection\ConnectionInterface;
use Thelia\Model\Breadcrumb\BreadcrumbInterface;
use Thelia\Model\Breadcrumb\CatalogBreadcrumbTrait;
use Thelia\Model\Tools\ModelEventDispatcherTrait;
use Thelia\Model\Tools\PositionManagementTrait;
class CategoryImage extends BaseCategoryImage
class CategoryImage extends BaseCategoryImage implements BreadcrumbInterface
{
use \Thelia\Model\Tools\ModelEventDispatcherTrait;
use \Thelia\Model\Tools\PositionManagementTrait;
use ModelEventDispatcherTrait;
use PositionManagementTrait;
use CatalogBreadcrumbTrait;
/**
* Calculate next position relative to our parent
@@ -62,4 +69,15 @@ class CategoryImage extends BaseCategoryImage
return true;
}
/**
*
* return the complete breadcrumb for a given resource.
*
* @return array
*/
public function getBreadcrumb(Router $router, ContainerInterface $container, $tab)
{
return $this->getCategoryBreadcrumb($router, $container, $tab);
}
}

View File

@@ -73,6 +73,11 @@ class ConfigQuery extends BaseConfigQuery
return true;
}
public static function getConfiguredShopUrl()
{
return ConfigQuery::read("url_site", '');
}
public static function getDefaultLangWhenNoTranslationAvailable()
{
return ConfigQuery::read("default_lang_without_translation", 1);

View File

@@ -2,13 +2,18 @@
namespace Thelia\Model;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\Routing\Router;
use Thelia\Model\Base\ContentDocument as BaseContentDocument;
use Propel\Runtime\Connection\ConnectionInterface;
use Thelia\Model\Breadcrumb\BreadcrumbInterface;
use Thelia\Model\Breadcrumb\FolderBreadcrumbTrait;
class ContentDocument extends BaseContentDocument
class ContentDocument extends BaseContentDocument implements BreadcrumbInterface
{
use \Thelia\Model\Tools\ModelEventDispatcherTrait;
use \Thelia\Model\Tools\PositionManagementTrait;
use FolderBreadcrumbTrait;
/**
* Calculate next position relative to our parent
@@ -62,4 +67,15 @@ class ContentDocument extends BaseContentDocument
return true;
}
/**
*
* return the complete breadcrumb for a given resource.
*
* @return array
*/
public function getBreadcrumb(Router $router, ContainerInterface $container, $tab)
{
return $this->getContentBreadcrumb($router, $container, $tab);
}
}

View File

@@ -2,13 +2,18 @@
namespace Thelia\Model;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\Routing\Router;
use Thelia\Model\Base\ContentImage as BaseContentImage;
use Propel\Runtime\Connection\ConnectionInterface;
use Thelia\Model\Breadcrumb\BreadcrumbInterface;
use Thelia\Model\Breadcrumb\FolderBreadcrumbTrait;
class ContentImage extends BaseContentImage
class ContentImage extends BaseContentImage implements BreadcrumbInterface
{
use \Thelia\Model\Tools\ModelEventDispatcherTrait;
use \Thelia\Model\Tools\PositionManagementTrait;
use FolderBreadcrumbTrait;
/**
* Calculate next position relative to our parent
@@ -62,4 +67,15 @@ class ContentImage extends BaseContentImage
return true;
}
/**
*
* return the complete breadcrumb for a given resource.
*
* @return array
*/
public function getBreadcrumb(Router $router, ContainerInterface $container, $tab)
{
return $this->getContentBreadcrumb($router, $container, $tab);
}
}

View File

@@ -41,6 +41,9 @@ use Thelia\Model\Tools\ModelEventDispatcherTrait;
class Coupon extends BaseCoupon
{
// Define the value of an unlimited coupon usage.
const UNLIMITED_COUPON_USE = -1;
use ModelEventDispatcherTrait;
/**
@@ -184,7 +187,8 @@ class Coupon extends BaseCoupon
*/
public function getAmount()
{
$amount = $this->getEffects()['amount'];
// Amount is now optional
$amount = isset($this->getEffects()['amount']) ? $this->getEffects()['amount'] : 0;
return floatval($amount);
}
@@ -199,10 +203,6 @@ class Coupon extends BaseCoupon
{
$effects = $this->unserializeEffects($this->getSerializedEffects());
if (null === $effects['amount']) {
throw new InvalidArgumentException('Missing key \'amount\' in Coupon effect coming from database');
}
return $effects;
}
@@ -210,18 +210,12 @@ class Coupon extends BaseCoupon
* Get the Coupon effects
*
* @param array $effects Effect ready to be serialized
* Needs at least the key 'amount'
* with the amount removed from the cart
*
* @throws Exception\InvalidArgumentException
* @return $this
*/
public function setEffects(array $effects)
{
if (null === $effects['amount']) {
throw new InvalidArgumentException('Missing key \'amount\' in Coupon effect ready to be serialized array');
}
$this->setSerializedEffects($this->serializeEffects($effects));
return $this;
@@ -274,6 +268,10 @@ class Coupon extends BaseCoupon
return CouponModuleQuery::create()->filterByCouponId($this->getId())->find();
}
public function isUsageUnlimited()
{
return $this->getMaxUsage() == self::UNLIMITED_COUPON_USE;
}
/**
* Get coupon usage left, either overall, or per customer.
*

View File

@@ -2,13 +2,18 @@
namespace Thelia\Model;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\Routing\Router;
use Thelia\Model\Base\FolderDocument as BaseFolderDocument;
use Propel\Runtime\Connection\ConnectionInterface;
use Thelia\Model\Breadcrumb\BreadcrumbInterface;
use Thelia\Model\Breadcrumb\FolderBreadcrumbTrait;
class FolderDocument extends BaseFolderDocument
class FolderDocument extends BaseFolderDocument implements BreadcrumbInterface
{
use \Thelia\Model\Tools\ModelEventDispatcherTrait;
use \Thelia\Model\Tools\PositionManagementTrait;
use FolderBreadcrumbTrait;
/**
* Calculate next position relative to our parent
@@ -62,4 +67,9 @@ class FolderDocument extends BaseFolderDocument
return true;
}
public function getBreadcrumb(Router $router, ContainerInterface $container, $tab)
{
return $this->getFolderBreadcrumb($router, $container, $tab);
}
}

View File

@@ -2,13 +2,18 @@
namespace Thelia\Model;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\Routing\Router;
use Thelia\Model\Base\FolderImage as BaseFolderImage;
use Propel\Runtime\Connection\ConnectionInterface;
use Thelia\Model\Breadcrumb\BreadcrumbInterface;
use Thelia\Model\Breadcrumb\FolderBreadcrumbTrait;
class FolderImage extends BaseFolderImage
class FolderImage extends BaseFolderImage implements BreadcrumbInterface
{
use \Thelia\Model\Tools\ModelEventDispatcherTrait;
use \Thelia\Model\Tools\PositionManagementTrait;
use FolderBreadcrumbTrait;
/**
* Calculate next position relative to our parent
@@ -62,4 +67,15 @@ class FolderImage extends BaseFolderImage
return true;
}
/**
*
* return the complete breadcrumb for a given resource.
*
* @return array
*/
public function getBreadcrumb(Router $router, ContainerInterface $container, $tab)
{
return $this->getFolderBreadcrumb($router, $container, $tab);
}
}

View File

@@ -17,6 +17,9 @@ use Thelia\Model\Map\LangTableMap;
class Lang extends BaseLang
{
use \Thelia\Model\Tools\ModelEventDispatcherTrait;
protected static $defaultLanguage;
/**
* Return the default language object, using a local variable to cache it.
*
@@ -24,10 +27,13 @@ class Lang extends BaseLang
*/
public static function getDefaultLanguage()
{
$default_lang = LangQuery::create()->findOneByByDefault(1);
if (null === self::$defaultLanguage) {
self::$defaultLanguage = LangQuery::create()->findOneByByDefault(1);
if ($default_lang == null) throw new \RuntimeException("No default language is defined. Please define one.");
return $default_lang;
if (self::$defaultLanguage == null) throw new \RuntimeException("No default language is defined. Please define one.");
}
return self::$defaultLanguage;
}
public function toggleDefault()

View File

@@ -58,7 +58,7 @@ class OrderTableMap extends TableMap
/**
* The total number of columns
*/
const NUM_COLUMNS = 19;
const NUM_COLUMNS = 22;
/**
* The number of lazy-loaded columns
@@ -68,7 +68,7 @@ class OrderTableMap extends TableMap
/**
* The number of columns to hydrate (NUM_COLUMNS - NUM_LAZY_LOAD_COLUMNS)
*/
const NUM_HYDRATE_COLUMNS = 19;
const NUM_HYDRATE_COLUMNS = 22;
/**
* the column name for the ID field
@@ -165,6 +165,21 @@ class OrderTableMap extends TableMap
*/
const UPDATED_AT = 'order.UPDATED_AT';
/**
* the column name for the VERSION field
*/
const VERSION = 'order.VERSION';
/**
* the column name for the VERSION_CREATED_AT field
*/
const VERSION_CREATED_AT = 'order.VERSION_CREATED_AT';
/**
* the column name for the VERSION_CREATED_BY field
*/
const VERSION_CREATED_BY = 'order.VERSION_CREATED_BY';
/**
* The default string format for model objects of the related table
*/
@@ -177,12 +192,12 @@ class OrderTableMap extends TableMap
* e.g. self::$fieldNames[self::TYPE_PHPNAME][0] = 'Id'
*/
protected static $fieldNames = array (
self::TYPE_PHPNAME => array('Id', 'Ref', 'CustomerId', 'InvoiceOrderAddressId', 'DeliveryOrderAddressId', 'InvoiceDate', 'CurrencyId', 'CurrencyRate', 'TransactionRef', 'DeliveryRef', 'InvoiceRef', 'Discount', 'Postage', 'PaymentModuleId', 'DeliveryModuleId', 'StatusId', 'LangId', 'CreatedAt', 'UpdatedAt', ),
self::TYPE_STUDLYPHPNAME => array('id', 'ref', 'customerId', 'invoiceOrderAddressId', 'deliveryOrderAddressId', 'invoiceDate', 'currencyId', 'currencyRate', 'transactionRef', 'deliveryRef', 'invoiceRef', 'discount', 'postage', 'paymentModuleId', 'deliveryModuleId', 'statusId', 'langId', 'createdAt', 'updatedAt', ),
self::TYPE_COLNAME => array(OrderTableMap::ID, OrderTableMap::REF, OrderTableMap::CUSTOMER_ID, OrderTableMap::INVOICE_ORDER_ADDRESS_ID, OrderTableMap::DELIVERY_ORDER_ADDRESS_ID, OrderTableMap::INVOICE_DATE, OrderTableMap::CURRENCY_ID, OrderTableMap::CURRENCY_RATE, OrderTableMap::TRANSACTION_REF, OrderTableMap::DELIVERY_REF, OrderTableMap::INVOICE_REF, OrderTableMap::DISCOUNT, OrderTableMap::POSTAGE, OrderTableMap::PAYMENT_MODULE_ID, OrderTableMap::DELIVERY_MODULE_ID, OrderTableMap::STATUS_ID, OrderTableMap::LANG_ID, OrderTableMap::CREATED_AT, OrderTableMap::UPDATED_AT, ),
self::TYPE_RAW_COLNAME => array('ID', 'REF', 'CUSTOMER_ID', 'INVOICE_ORDER_ADDRESS_ID', 'DELIVERY_ORDER_ADDRESS_ID', 'INVOICE_DATE', 'CURRENCY_ID', 'CURRENCY_RATE', 'TRANSACTION_REF', 'DELIVERY_REF', 'INVOICE_REF', 'DISCOUNT', 'POSTAGE', 'PAYMENT_MODULE_ID', 'DELIVERY_MODULE_ID', 'STATUS_ID', 'LANG_ID', 'CREATED_AT', 'UPDATED_AT', ),
self::TYPE_FIELDNAME => array('id', 'ref', 'customer_id', 'invoice_order_address_id', 'delivery_order_address_id', 'invoice_date', 'currency_id', 'currency_rate', 'transaction_ref', 'delivery_ref', 'invoice_ref', 'discount', 'postage', 'payment_module_id', 'delivery_module_id', 'status_id', 'lang_id', 'created_at', 'updated_at', ),
self::TYPE_NUM => array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, )
self::TYPE_PHPNAME => array('Id', 'Ref', 'CustomerId', 'InvoiceOrderAddressId', 'DeliveryOrderAddressId', 'InvoiceDate', 'CurrencyId', 'CurrencyRate', 'TransactionRef', 'DeliveryRef', 'InvoiceRef', 'Discount', 'Postage', 'PaymentModuleId', 'DeliveryModuleId', 'StatusId', 'LangId', 'CreatedAt', 'UpdatedAt', 'Version', 'VersionCreatedAt', 'VersionCreatedBy', ),
self::TYPE_STUDLYPHPNAME => array('id', 'ref', 'customerId', 'invoiceOrderAddressId', 'deliveryOrderAddressId', 'invoiceDate', 'currencyId', 'currencyRate', 'transactionRef', 'deliveryRef', 'invoiceRef', 'discount', 'postage', 'paymentModuleId', 'deliveryModuleId', 'statusId', 'langId', 'createdAt', 'updatedAt', 'version', 'versionCreatedAt', 'versionCreatedBy', ),
self::TYPE_COLNAME => array(OrderTableMap::ID, OrderTableMap::REF, OrderTableMap::CUSTOMER_ID, OrderTableMap::INVOICE_ORDER_ADDRESS_ID, OrderTableMap::DELIVERY_ORDER_ADDRESS_ID, OrderTableMap::INVOICE_DATE, OrderTableMap::CURRENCY_ID, OrderTableMap::CURRENCY_RATE, OrderTableMap::TRANSACTION_REF, OrderTableMap::DELIVERY_REF, OrderTableMap::INVOICE_REF, OrderTableMap::DISCOUNT, OrderTableMap::POSTAGE, OrderTableMap::PAYMENT_MODULE_ID, OrderTableMap::DELIVERY_MODULE_ID, OrderTableMap::STATUS_ID, OrderTableMap::LANG_ID, OrderTableMap::CREATED_AT, OrderTableMap::UPDATED_AT, OrderTableMap::VERSION, OrderTableMap::VERSION_CREATED_AT, OrderTableMap::VERSION_CREATED_BY, ),
self::TYPE_RAW_COLNAME => array('ID', 'REF', 'CUSTOMER_ID', 'INVOICE_ORDER_ADDRESS_ID', 'DELIVERY_ORDER_ADDRESS_ID', 'INVOICE_DATE', 'CURRENCY_ID', 'CURRENCY_RATE', 'TRANSACTION_REF', 'DELIVERY_REF', 'INVOICE_REF', 'DISCOUNT', 'POSTAGE', 'PAYMENT_MODULE_ID', 'DELIVERY_MODULE_ID', 'STATUS_ID', 'LANG_ID', 'CREATED_AT', 'UPDATED_AT', 'VERSION', 'VERSION_CREATED_AT', 'VERSION_CREATED_BY', ),
self::TYPE_FIELDNAME => array('id', 'ref', 'customer_id', 'invoice_order_address_id', 'delivery_order_address_id', 'invoice_date', 'currency_id', 'currency_rate', 'transaction_ref', 'delivery_ref', 'invoice_ref', 'discount', 'postage', 'payment_module_id', 'delivery_module_id', 'status_id', 'lang_id', 'created_at', 'updated_at', 'version', 'version_created_at', 'version_created_by', ),
self::TYPE_NUM => array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, )
);
/**
@@ -192,12 +207,12 @@ class OrderTableMap extends TableMap
* e.g. self::$fieldKeys[self::TYPE_PHPNAME]['Id'] = 0
*/
protected static $fieldKeys = array (
self::TYPE_PHPNAME => array('Id' => 0, 'Ref' => 1, 'CustomerId' => 2, 'InvoiceOrderAddressId' => 3, 'DeliveryOrderAddressId' => 4, 'InvoiceDate' => 5, 'CurrencyId' => 6, 'CurrencyRate' => 7, 'TransactionRef' => 8, 'DeliveryRef' => 9, 'InvoiceRef' => 10, 'Discount' => 11, 'Postage' => 12, 'PaymentModuleId' => 13, 'DeliveryModuleId' => 14, 'StatusId' => 15, 'LangId' => 16, 'CreatedAt' => 17, 'UpdatedAt' => 18, ),
self::TYPE_STUDLYPHPNAME => array('id' => 0, 'ref' => 1, 'customerId' => 2, 'invoiceOrderAddressId' => 3, 'deliveryOrderAddressId' => 4, 'invoiceDate' => 5, 'currencyId' => 6, 'currencyRate' => 7, 'transactionRef' => 8, 'deliveryRef' => 9, 'invoiceRef' => 10, 'discount' => 11, 'postage' => 12, 'paymentModuleId' => 13, 'deliveryModuleId' => 14, 'statusId' => 15, 'langId' => 16, 'createdAt' => 17, 'updatedAt' => 18, ),
self::TYPE_COLNAME => array(OrderTableMap::ID => 0, OrderTableMap::REF => 1, OrderTableMap::CUSTOMER_ID => 2, OrderTableMap::INVOICE_ORDER_ADDRESS_ID => 3, OrderTableMap::DELIVERY_ORDER_ADDRESS_ID => 4, OrderTableMap::INVOICE_DATE => 5, OrderTableMap::CURRENCY_ID => 6, OrderTableMap::CURRENCY_RATE => 7, OrderTableMap::TRANSACTION_REF => 8, OrderTableMap::DELIVERY_REF => 9, OrderTableMap::INVOICE_REF => 10, OrderTableMap::DISCOUNT => 11, OrderTableMap::POSTAGE => 12, OrderTableMap::PAYMENT_MODULE_ID => 13, OrderTableMap::DELIVERY_MODULE_ID => 14, OrderTableMap::STATUS_ID => 15, OrderTableMap::LANG_ID => 16, OrderTableMap::CREATED_AT => 17, OrderTableMap::UPDATED_AT => 18, ),
self::TYPE_RAW_COLNAME => array('ID' => 0, 'REF' => 1, 'CUSTOMER_ID' => 2, 'INVOICE_ORDER_ADDRESS_ID' => 3, 'DELIVERY_ORDER_ADDRESS_ID' => 4, 'INVOICE_DATE' => 5, 'CURRENCY_ID' => 6, 'CURRENCY_RATE' => 7, 'TRANSACTION_REF' => 8, 'DELIVERY_REF' => 9, 'INVOICE_REF' => 10, 'DISCOUNT' => 11, 'POSTAGE' => 12, 'PAYMENT_MODULE_ID' => 13, 'DELIVERY_MODULE_ID' => 14, 'STATUS_ID' => 15, 'LANG_ID' => 16, 'CREATED_AT' => 17, 'UPDATED_AT' => 18, ),
self::TYPE_FIELDNAME => array('id' => 0, 'ref' => 1, 'customer_id' => 2, 'invoice_order_address_id' => 3, 'delivery_order_address_id' => 4, 'invoice_date' => 5, 'currency_id' => 6, 'currency_rate' => 7, 'transaction_ref' => 8, 'delivery_ref' => 9, 'invoice_ref' => 10, 'discount' => 11, 'postage' => 12, 'payment_module_id' => 13, 'delivery_module_id' => 14, 'status_id' => 15, 'lang_id' => 16, 'created_at' => 17, 'updated_at' => 18, ),
self::TYPE_NUM => array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, )
self::TYPE_PHPNAME => array('Id' => 0, 'Ref' => 1, 'CustomerId' => 2, 'InvoiceOrderAddressId' => 3, 'DeliveryOrderAddressId' => 4, 'InvoiceDate' => 5, 'CurrencyId' => 6, 'CurrencyRate' => 7, 'TransactionRef' => 8, 'DeliveryRef' => 9, 'InvoiceRef' => 10, 'Discount' => 11, 'Postage' => 12, 'PaymentModuleId' => 13, 'DeliveryModuleId' => 14, 'StatusId' => 15, 'LangId' => 16, 'CreatedAt' => 17, 'UpdatedAt' => 18, 'Version' => 19, 'VersionCreatedAt' => 20, 'VersionCreatedBy' => 21, ),
self::TYPE_STUDLYPHPNAME => array('id' => 0, 'ref' => 1, 'customerId' => 2, 'invoiceOrderAddressId' => 3, 'deliveryOrderAddressId' => 4, 'invoiceDate' => 5, 'currencyId' => 6, 'currencyRate' => 7, 'transactionRef' => 8, 'deliveryRef' => 9, 'invoiceRef' => 10, 'discount' => 11, 'postage' => 12, 'paymentModuleId' => 13, 'deliveryModuleId' => 14, 'statusId' => 15, 'langId' => 16, 'createdAt' => 17, 'updatedAt' => 18, 'version' => 19, 'versionCreatedAt' => 20, 'versionCreatedBy' => 21, ),
self::TYPE_COLNAME => array(OrderTableMap::ID => 0, OrderTableMap::REF => 1, OrderTableMap::CUSTOMER_ID => 2, OrderTableMap::INVOICE_ORDER_ADDRESS_ID => 3, OrderTableMap::DELIVERY_ORDER_ADDRESS_ID => 4, OrderTableMap::INVOICE_DATE => 5, OrderTableMap::CURRENCY_ID => 6, OrderTableMap::CURRENCY_RATE => 7, OrderTableMap::TRANSACTION_REF => 8, OrderTableMap::DELIVERY_REF => 9, OrderTableMap::INVOICE_REF => 10, OrderTableMap::DISCOUNT => 11, OrderTableMap::POSTAGE => 12, OrderTableMap::PAYMENT_MODULE_ID => 13, OrderTableMap::DELIVERY_MODULE_ID => 14, OrderTableMap::STATUS_ID => 15, OrderTableMap::LANG_ID => 16, OrderTableMap::CREATED_AT => 17, OrderTableMap::UPDATED_AT => 18, OrderTableMap::VERSION => 19, OrderTableMap::VERSION_CREATED_AT => 20, OrderTableMap::VERSION_CREATED_BY => 21, ),
self::TYPE_RAW_COLNAME => array('ID' => 0, 'REF' => 1, 'CUSTOMER_ID' => 2, 'INVOICE_ORDER_ADDRESS_ID' => 3, 'DELIVERY_ORDER_ADDRESS_ID' => 4, 'INVOICE_DATE' => 5, 'CURRENCY_ID' => 6, 'CURRENCY_RATE' => 7, 'TRANSACTION_REF' => 8, 'DELIVERY_REF' => 9, 'INVOICE_REF' => 10, 'DISCOUNT' => 11, 'POSTAGE' => 12, 'PAYMENT_MODULE_ID' => 13, 'DELIVERY_MODULE_ID' => 14, 'STATUS_ID' => 15, 'LANG_ID' => 16, 'CREATED_AT' => 17, 'UPDATED_AT' => 18, 'VERSION' => 19, 'VERSION_CREATED_AT' => 20, 'VERSION_CREATED_BY' => 21, ),
self::TYPE_FIELDNAME => array('id' => 0, 'ref' => 1, 'customer_id' => 2, 'invoice_order_address_id' => 3, 'delivery_order_address_id' => 4, 'invoice_date' => 5, 'currency_id' => 6, 'currency_rate' => 7, 'transaction_ref' => 8, 'delivery_ref' => 9, 'invoice_ref' => 10, 'discount' => 11, 'postage' => 12, 'payment_module_id' => 13, 'delivery_module_id' => 14, 'status_id' => 15, 'lang_id' => 16, 'created_at' => 17, 'updated_at' => 18, 'version' => 19, 'version_created_at' => 20, 'version_created_by' => 21, ),
self::TYPE_NUM => array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, )
);
/**
@@ -235,6 +250,9 @@ class OrderTableMap extends TableMap
$this->addForeignKey('LANG_ID', 'LangId', 'INTEGER', 'lang', 'ID', true, null, null);
$this->addColumn('CREATED_AT', 'CreatedAt', 'TIMESTAMP', false, null, null);
$this->addColumn('UPDATED_AT', 'UpdatedAt', 'TIMESTAMP', false, null, null);
$this->addColumn('VERSION', 'Version', 'INTEGER', false, null, 0);
$this->addColumn('VERSION_CREATED_AT', 'VersionCreatedAt', 'TIMESTAMP', false, null, null);
$this->addColumn('VERSION_CREATED_BY', 'VersionCreatedBy', 'VARCHAR', false, 100, null);
} // initialize()
/**
@@ -252,6 +270,7 @@ class OrderTableMap extends TableMap
$this->addRelation('Lang', '\\Thelia\\Model\\Lang', RelationMap::MANY_TO_ONE, array('lang_id' => 'id', ), 'RESTRICT', 'RESTRICT');
$this->addRelation('OrderProduct', '\\Thelia\\Model\\OrderProduct', RelationMap::ONE_TO_MANY, array('id' => 'order_id', ), 'CASCADE', 'RESTRICT', 'OrderProducts');
$this->addRelation('OrderCoupon', '\\Thelia\\Model\\OrderCoupon', RelationMap::ONE_TO_MANY, array('id' => 'order_id', ), 'CASCADE', 'RESTRICT', 'OrderCoupons');
$this->addRelation('OrderVersion', '\\Thelia\\Model\\OrderVersion', RelationMap::ONE_TO_MANY, array('id' => 'id', ), 'CASCADE', null, 'OrderVersions');
} // buildRelations()
/**
@@ -264,6 +283,7 @@ class OrderTableMap extends TableMap
{
return array(
'timestampable' => array('create_column' => 'created_at', 'update_column' => 'updated_at', ),
'versionable' => array('version_column' => 'version', 'version_table' => '', 'log_created_at' => 'true', 'log_created_by' => 'true', 'log_comment' => 'false', 'version_created_at_column' => 'version_created_at', 'version_created_by_column' => 'version_created_by', 'version_comment_column' => 'version_comment', ),
);
} // getBehaviors()
/**
@@ -275,6 +295,7 @@ class OrderTableMap extends TableMap
// since one or more of them may be deleted by ON DELETE CASCADE/SETNULL rule.
OrderProductTableMap::clearInstancePool();
OrderCouponTableMap::clearInstancePool();
OrderVersionTableMap::clearInstancePool();
}
/**
@@ -434,6 +455,9 @@ class OrderTableMap extends TableMap
$criteria->addSelectColumn(OrderTableMap::LANG_ID);
$criteria->addSelectColumn(OrderTableMap::CREATED_AT);
$criteria->addSelectColumn(OrderTableMap::UPDATED_AT);
$criteria->addSelectColumn(OrderTableMap::VERSION);
$criteria->addSelectColumn(OrderTableMap::VERSION_CREATED_AT);
$criteria->addSelectColumn(OrderTableMap::VERSION_CREATED_BY);
} else {
$criteria->addSelectColumn($alias . '.ID');
$criteria->addSelectColumn($alias . '.REF');
@@ -454,6 +478,9 @@ class OrderTableMap extends TableMap
$criteria->addSelectColumn($alias . '.LANG_ID');
$criteria->addSelectColumn($alias . '.CREATED_AT');
$criteria->addSelectColumn($alias . '.UPDATED_AT');
$criteria->addSelectColumn($alias . '.VERSION');
$criteria->addSelectColumn($alias . '.VERSION_CREATED_AT');
$criteria->addSelectColumn($alias . '.VERSION_CREATED_BY');
}
}

View File

@@ -0,0 +1,626 @@
<?php
namespace Thelia\Model\Map;
use Propel\Runtime\Propel;
use Propel\Runtime\ActiveQuery\Criteria;
use Propel\Runtime\ActiveQuery\InstancePoolTrait;
use Propel\Runtime\Connection\ConnectionInterface;
use Propel\Runtime\DataFetcher\DataFetcherInterface;
use Propel\Runtime\Exception\PropelException;
use Propel\Runtime\Map\RelationMap;
use Propel\Runtime\Map\TableMap;
use Propel\Runtime\Map\TableMapTrait;
use Thelia\Model\OrderVersion;
use Thelia\Model\OrderVersionQuery;
/**
* This class defines the structure of the 'order_version' table.
*
*
*
* This map class is used by Propel to do runtime db structure discovery.
* For example, the createSelectSql() method checks the type of a given column used in an
* ORDER BY clause to know whether it needs to apply SQL to make the ORDER BY case-insensitive
* (i.e. if it's a text column type).
*
*/
class OrderVersionTableMap extends TableMap
{
use InstancePoolTrait;
use TableMapTrait;
/**
* The (dot-path) name of this class
*/
const CLASS_NAME = 'Thelia.Model.Map.OrderVersionTableMap';
/**
* The default database name for this class
*/
const DATABASE_NAME = 'thelia';
/**
* The table name for this class
*/
const TABLE_NAME = 'order_version';
/**
* The related Propel class for this table
*/
const OM_CLASS = '\\Thelia\\Model\\OrderVersion';
/**
* A class that can be returned by this tableMap
*/
const CLASS_DEFAULT = 'Thelia.Model.OrderVersion';
/**
* The total number of columns
*/
const NUM_COLUMNS = 22;
/**
* The number of lazy-loaded columns
*/
const NUM_LAZY_LOAD_COLUMNS = 0;
/**
* The number of columns to hydrate (NUM_COLUMNS - NUM_LAZY_LOAD_COLUMNS)
*/
const NUM_HYDRATE_COLUMNS = 22;
/**
* the column name for the ID field
*/
const ID = 'order_version.ID';
/**
* the column name for the REF field
*/
const REF = 'order_version.REF';
/**
* the column name for the CUSTOMER_ID field
*/
const CUSTOMER_ID = 'order_version.CUSTOMER_ID';
/**
* the column name for the INVOICE_ORDER_ADDRESS_ID field
*/
const INVOICE_ORDER_ADDRESS_ID = 'order_version.INVOICE_ORDER_ADDRESS_ID';
/**
* the column name for the DELIVERY_ORDER_ADDRESS_ID field
*/
const DELIVERY_ORDER_ADDRESS_ID = 'order_version.DELIVERY_ORDER_ADDRESS_ID';
/**
* the column name for the INVOICE_DATE field
*/
const INVOICE_DATE = 'order_version.INVOICE_DATE';
/**
* the column name for the CURRENCY_ID field
*/
const CURRENCY_ID = 'order_version.CURRENCY_ID';
/**
* the column name for the CURRENCY_RATE field
*/
const CURRENCY_RATE = 'order_version.CURRENCY_RATE';
/**
* the column name for the TRANSACTION_REF field
*/
const TRANSACTION_REF = 'order_version.TRANSACTION_REF';
/**
* the column name for the DELIVERY_REF field
*/
const DELIVERY_REF = 'order_version.DELIVERY_REF';
/**
* the column name for the INVOICE_REF field
*/
const INVOICE_REF = 'order_version.INVOICE_REF';
/**
* the column name for the DISCOUNT field
*/
const DISCOUNT = 'order_version.DISCOUNT';
/**
* the column name for the POSTAGE field
*/
const POSTAGE = 'order_version.POSTAGE';
/**
* the column name for the PAYMENT_MODULE_ID field
*/
const PAYMENT_MODULE_ID = 'order_version.PAYMENT_MODULE_ID';
/**
* the column name for the DELIVERY_MODULE_ID field
*/
const DELIVERY_MODULE_ID = 'order_version.DELIVERY_MODULE_ID';
/**
* the column name for the STATUS_ID field
*/
const STATUS_ID = 'order_version.STATUS_ID';
/**
* the column name for the LANG_ID field
*/
const LANG_ID = 'order_version.LANG_ID';
/**
* the column name for the CREATED_AT field
*/
const CREATED_AT = 'order_version.CREATED_AT';
/**
* the column name for the UPDATED_AT field
*/
const UPDATED_AT = 'order_version.UPDATED_AT';
/**
* the column name for the VERSION field
*/
const VERSION = 'order_version.VERSION';
/**
* the column name for the VERSION_CREATED_AT field
*/
const VERSION_CREATED_AT = 'order_version.VERSION_CREATED_AT';
/**
* the column name for the VERSION_CREATED_BY field
*/
const VERSION_CREATED_BY = 'order_version.VERSION_CREATED_BY';
/**
* The default string format for model objects of the related table
*/
const DEFAULT_STRING_FORMAT = 'YAML';
/**
* holds an array of fieldnames
*
* first dimension keys are the type constants
* e.g. self::$fieldNames[self::TYPE_PHPNAME][0] = 'Id'
*/
protected static $fieldNames = array (
self::TYPE_PHPNAME => array('Id', 'Ref', 'CustomerId', 'InvoiceOrderAddressId', 'DeliveryOrderAddressId', 'InvoiceDate', 'CurrencyId', 'CurrencyRate', 'TransactionRef', 'DeliveryRef', 'InvoiceRef', 'Discount', 'Postage', 'PaymentModuleId', 'DeliveryModuleId', 'StatusId', 'LangId', 'CreatedAt', 'UpdatedAt', 'Version', 'VersionCreatedAt', 'VersionCreatedBy', ),
self::TYPE_STUDLYPHPNAME => array('id', 'ref', 'customerId', 'invoiceOrderAddressId', 'deliveryOrderAddressId', 'invoiceDate', 'currencyId', 'currencyRate', 'transactionRef', 'deliveryRef', 'invoiceRef', 'discount', 'postage', 'paymentModuleId', 'deliveryModuleId', 'statusId', 'langId', 'createdAt', 'updatedAt', 'version', 'versionCreatedAt', 'versionCreatedBy', ),
self::TYPE_COLNAME => array(OrderVersionTableMap::ID, OrderVersionTableMap::REF, OrderVersionTableMap::CUSTOMER_ID, OrderVersionTableMap::INVOICE_ORDER_ADDRESS_ID, OrderVersionTableMap::DELIVERY_ORDER_ADDRESS_ID, OrderVersionTableMap::INVOICE_DATE, OrderVersionTableMap::CURRENCY_ID, OrderVersionTableMap::CURRENCY_RATE, OrderVersionTableMap::TRANSACTION_REF, OrderVersionTableMap::DELIVERY_REF, OrderVersionTableMap::INVOICE_REF, OrderVersionTableMap::DISCOUNT, OrderVersionTableMap::POSTAGE, OrderVersionTableMap::PAYMENT_MODULE_ID, OrderVersionTableMap::DELIVERY_MODULE_ID, OrderVersionTableMap::STATUS_ID, OrderVersionTableMap::LANG_ID, OrderVersionTableMap::CREATED_AT, OrderVersionTableMap::UPDATED_AT, OrderVersionTableMap::VERSION, OrderVersionTableMap::VERSION_CREATED_AT, OrderVersionTableMap::VERSION_CREATED_BY, ),
self::TYPE_RAW_COLNAME => array('ID', 'REF', 'CUSTOMER_ID', 'INVOICE_ORDER_ADDRESS_ID', 'DELIVERY_ORDER_ADDRESS_ID', 'INVOICE_DATE', 'CURRENCY_ID', 'CURRENCY_RATE', 'TRANSACTION_REF', 'DELIVERY_REF', 'INVOICE_REF', 'DISCOUNT', 'POSTAGE', 'PAYMENT_MODULE_ID', 'DELIVERY_MODULE_ID', 'STATUS_ID', 'LANG_ID', 'CREATED_AT', 'UPDATED_AT', 'VERSION', 'VERSION_CREATED_AT', 'VERSION_CREATED_BY', ),
self::TYPE_FIELDNAME => array('id', 'ref', 'customer_id', 'invoice_order_address_id', 'delivery_order_address_id', 'invoice_date', 'currency_id', 'currency_rate', 'transaction_ref', 'delivery_ref', 'invoice_ref', 'discount', 'postage', 'payment_module_id', 'delivery_module_id', 'status_id', 'lang_id', 'created_at', 'updated_at', 'version', 'version_created_at', 'version_created_by', ),
self::TYPE_NUM => array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, )
);
/**
* holds an array of keys for quick access to the fieldnames array
*
* first dimension keys are the type constants
* e.g. self::$fieldKeys[self::TYPE_PHPNAME]['Id'] = 0
*/
protected static $fieldKeys = array (
self::TYPE_PHPNAME => array('Id' => 0, 'Ref' => 1, 'CustomerId' => 2, 'InvoiceOrderAddressId' => 3, 'DeliveryOrderAddressId' => 4, 'InvoiceDate' => 5, 'CurrencyId' => 6, 'CurrencyRate' => 7, 'TransactionRef' => 8, 'DeliveryRef' => 9, 'InvoiceRef' => 10, 'Discount' => 11, 'Postage' => 12, 'PaymentModuleId' => 13, 'DeliveryModuleId' => 14, 'StatusId' => 15, 'LangId' => 16, 'CreatedAt' => 17, 'UpdatedAt' => 18, 'Version' => 19, 'VersionCreatedAt' => 20, 'VersionCreatedBy' => 21, ),
self::TYPE_STUDLYPHPNAME => array('id' => 0, 'ref' => 1, 'customerId' => 2, 'invoiceOrderAddressId' => 3, 'deliveryOrderAddressId' => 4, 'invoiceDate' => 5, 'currencyId' => 6, 'currencyRate' => 7, 'transactionRef' => 8, 'deliveryRef' => 9, 'invoiceRef' => 10, 'discount' => 11, 'postage' => 12, 'paymentModuleId' => 13, 'deliveryModuleId' => 14, 'statusId' => 15, 'langId' => 16, 'createdAt' => 17, 'updatedAt' => 18, 'version' => 19, 'versionCreatedAt' => 20, 'versionCreatedBy' => 21, ),
self::TYPE_COLNAME => array(OrderVersionTableMap::ID => 0, OrderVersionTableMap::REF => 1, OrderVersionTableMap::CUSTOMER_ID => 2, OrderVersionTableMap::INVOICE_ORDER_ADDRESS_ID => 3, OrderVersionTableMap::DELIVERY_ORDER_ADDRESS_ID => 4, OrderVersionTableMap::INVOICE_DATE => 5, OrderVersionTableMap::CURRENCY_ID => 6, OrderVersionTableMap::CURRENCY_RATE => 7, OrderVersionTableMap::TRANSACTION_REF => 8, OrderVersionTableMap::DELIVERY_REF => 9, OrderVersionTableMap::INVOICE_REF => 10, OrderVersionTableMap::DISCOUNT => 11, OrderVersionTableMap::POSTAGE => 12, OrderVersionTableMap::PAYMENT_MODULE_ID => 13, OrderVersionTableMap::DELIVERY_MODULE_ID => 14, OrderVersionTableMap::STATUS_ID => 15, OrderVersionTableMap::LANG_ID => 16, OrderVersionTableMap::CREATED_AT => 17, OrderVersionTableMap::UPDATED_AT => 18, OrderVersionTableMap::VERSION => 19, OrderVersionTableMap::VERSION_CREATED_AT => 20, OrderVersionTableMap::VERSION_CREATED_BY => 21, ),
self::TYPE_RAW_COLNAME => array('ID' => 0, 'REF' => 1, 'CUSTOMER_ID' => 2, 'INVOICE_ORDER_ADDRESS_ID' => 3, 'DELIVERY_ORDER_ADDRESS_ID' => 4, 'INVOICE_DATE' => 5, 'CURRENCY_ID' => 6, 'CURRENCY_RATE' => 7, 'TRANSACTION_REF' => 8, 'DELIVERY_REF' => 9, 'INVOICE_REF' => 10, 'DISCOUNT' => 11, 'POSTAGE' => 12, 'PAYMENT_MODULE_ID' => 13, 'DELIVERY_MODULE_ID' => 14, 'STATUS_ID' => 15, 'LANG_ID' => 16, 'CREATED_AT' => 17, 'UPDATED_AT' => 18, 'VERSION' => 19, 'VERSION_CREATED_AT' => 20, 'VERSION_CREATED_BY' => 21, ),
self::TYPE_FIELDNAME => array('id' => 0, 'ref' => 1, 'customer_id' => 2, 'invoice_order_address_id' => 3, 'delivery_order_address_id' => 4, 'invoice_date' => 5, 'currency_id' => 6, 'currency_rate' => 7, 'transaction_ref' => 8, 'delivery_ref' => 9, 'invoice_ref' => 10, 'discount' => 11, 'postage' => 12, 'payment_module_id' => 13, 'delivery_module_id' => 14, 'status_id' => 15, 'lang_id' => 16, 'created_at' => 17, 'updated_at' => 18, 'version' => 19, 'version_created_at' => 20, 'version_created_by' => 21, ),
self::TYPE_NUM => array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, )
);
/**
* Initialize the table attributes and columns
* Relations are not initialized by this method since they are lazy loaded
*
* @return void
* @throws PropelException
*/
public function initialize()
{
// attributes
$this->setName('order_version');
$this->setPhpName('OrderVersion');
$this->setClassName('\\Thelia\\Model\\OrderVersion');
$this->setPackage('Thelia.Model');
$this->setUseIdGenerator(false);
// columns
$this->addForeignPrimaryKey('ID', 'Id', 'INTEGER' , 'order', 'ID', true, null, null);
$this->addColumn('REF', 'Ref', 'VARCHAR', false, 45, null);
$this->addColumn('CUSTOMER_ID', 'CustomerId', 'INTEGER', true, null, null);
$this->addColumn('INVOICE_ORDER_ADDRESS_ID', 'InvoiceOrderAddressId', 'INTEGER', true, null, null);
$this->addColumn('DELIVERY_ORDER_ADDRESS_ID', 'DeliveryOrderAddressId', 'INTEGER', true, null, null);
$this->addColumn('INVOICE_DATE', 'InvoiceDate', 'DATE', false, null, null);
$this->addColumn('CURRENCY_ID', 'CurrencyId', 'INTEGER', true, null, null);
$this->addColumn('CURRENCY_RATE', 'CurrencyRate', 'FLOAT', true, null, null);
$this->addColumn('TRANSACTION_REF', 'TransactionRef', 'VARCHAR', false, 100, null);
$this->addColumn('DELIVERY_REF', 'DeliveryRef', 'VARCHAR', false, 100, null);
$this->addColumn('INVOICE_REF', 'InvoiceRef', 'VARCHAR', false, 100, null);
$this->addColumn('DISCOUNT', 'Discount', 'FLOAT', false, null, null);
$this->addColumn('POSTAGE', 'Postage', 'FLOAT', true, null, null);
$this->addColumn('PAYMENT_MODULE_ID', 'PaymentModuleId', 'INTEGER', true, null, null);
$this->addColumn('DELIVERY_MODULE_ID', 'DeliveryModuleId', 'INTEGER', true, null, null);
$this->addColumn('STATUS_ID', 'StatusId', 'INTEGER', true, null, null);
$this->addColumn('LANG_ID', 'LangId', 'INTEGER', true, null, null);
$this->addColumn('CREATED_AT', 'CreatedAt', 'TIMESTAMP', false, null, null);
$this->addColumn('UPDATED_AT', 'UpdatedAt', 'TIMESTAMP', false, null, null);
$this->addPrimaryKey('VERSION', 'Version', 'INTEGER', true, null, 0);
$this->addColumn('VERSION_CREATED_AT', 'VersionCreatedAt', 'TIMESTAMP', false, null, null);
$this->addColumn('VERSION_CREATED_BY', 'VersionCreatedBy', 'VARCHAR', false, 100, null);
} // initialize()
/**
* Build the RelationMap objects for this table relationships
*/
public function buildRelations()
{
$this->addRelation('Order', '\\Thelia\\Model\\Order', RelationMap::MANY_TO_ONE, array('id' => 'id', ), 'CASCADE', null);
} // buildRelations()
/**
* Adds an object to the instance pool.
*
* Propel keeps cached copies of objects in an instance pool when they are retrieved
* from the database. In some cases you may need to explicitly add objects
* to the cache in order to ensure that the same objects are always returned by find*()
* and findPk*() calls.
*
* @param \Thelia\Model\OrderVersion $obj A \Thelia\Model\OrderVersion object.
* @param string $key (optional) key to use for instance map (for performance boost if key was already calculated externally).
*/
public static function addInstanceToPool($obj, $key = null)
{
if (Propel::isInstancePoolingEnabled()) {
if (null === $key) {
$key = serialize(array((string) $obj->getId(), (string) $obj->getVersion()));
} // if key === null
self::$instances[$key] = $obj;
}
}
/**
* Removes an object from the instance pool.
*
* Propel keeps cached copies of objects in an instance pool when they are retrieved
* from the database. In some cases -- especially when you override doDelete
* methods in your stub classes -- you may need to explicitly remove objects
* from the cache in order to prevent returning objects that no longer exist.
*
* @param mixed $value A \Thelia\Model\OrderVersion object or a primary key value.
*/
public static function removeInstanceFromPool($value)
{
if (Propel::isInstancePoolingEnabled() && null !== $value) {
if (is_object($value) && $value instanceof \Thelia\Model\OrderVersion) {
$key = serialize(array((string) $value->getId(), (string) $value->getVersion()));
} elseif (is_array($value) && count($value) === 2) {
// assume we've been passed a primary key";
$key = serialize(array((string) $value[0], (string) $value[1]));
} elseif ($value instanceof Criteria) {
self::$instances = [];
return;
} else {
$e = new PropelException("Invalid value passed to removeInstanceFromPool(). Expected primary key or \Thelia\Model\OrderVersion object; got " . (is_object($value) ? get_class($value) . ' object.' : var_export($value, true)));
throw $e;
}
unset(self::$instances[$key]);
}
}
/**
* Retrieves a string version of the primary key from the DB resultset row that can be used to uniquely identify a row in this table.
*
* For tables with a single-column primary key, that simple pkey value will be returned. For tables with
* a multi-column primary key, a serialize()d version of the primary key will be returned.
*
* @param array $row resultset row.
* @param int $offset The 0-based offset for reading from the resultset row.
* @param string $indexType One of the class type constants TableMap::TYPE_PHPNAME, TableMap::TYPE_STUDLYPHPNAME
* TableMap::TYPE_COLNAME, TableMap::TYPE_FIELDNAME, TableMap::TYPE_NUM
*/
public static function getPrimaryKeyHashFromRow($row, $offset = 0, $indexType = TableMap::TYPE_NUM)
{
// If the PK cannot be derived from the row, return NULL.
if ($row[TableMap::TYPE_NUM == $indexType ? 0 + $offset : static::translateFieldName('Id', TableMap::TYPE_PHPNAME, $indexType)] === null && $row[TableMap::TYPE_NUM == $indexType ? 19 + $offset : static::translateFieldName('Version', TableMap::TYPE_PHPNAME, $indexType)] === null) {
return null;
}
return serialize(array((string) $row[TableMap::TYPE_NUM == $indexType ? 0 + $offset : static::translateFieldName('Id', TableMap::TYPE_PHPNAME, $indexType)], (string) $row[TableMap::TYPE_NUM == $indexType ? 19 + $offset : static::translateFieldName('Version', TableMap::TYPE_PHPNAME, $indexType)]));
}
/**
* Retrieves the primary key from the DB resultset row
* For tables with a single-column primary key, that simple pkey value will be returned. For tables with
* a multi-column primary key, an array of the primary key columns will be returned.
*
* @param array $row resultset row.
* @param int $offset The 0-based offset for reading from the resultset row.
* @param string $indexType One of the class type constants TableMap::TYPE_PHPNAME, TableMap::TYPE_STUDLYPHPNAME
* TableMap::TYPE_COLNAME, TableMap::TYPE_FIELDNAME, TableMap::TYPE_NUM
*
* @return mixed The primary key of the row
*/
public static function getPrimaryKeyFromRow($row, $offset = 0, $indexType = TableMap::TYPE_NUM)
{
return $pks;
}
/**
* The class that the tableMap will make instances of.
*
* If $withPrefix is true, the returned path
* uses a dot-path notation which is translated into a path
* relative to a location on the PHP include_path.
* (e.g. path.to.MyClass -> 'path/to/MyClass.php')
*
* @param boolean $withPrefix Whether or not to return the path with the class name
* @return string path.to.ClassName
*/
public static function getOMClass($withPrefix = true)
{
return $withPrefix ? OrderVersionTableMap::CLASS_DEFAULT : OrderVersionTableMap::OM_CLASS;
}
/**
* Populates an object of the default type or an object that inherit from the default.
*
* @param array $row row returned by DataFetcher->fetch().
* @param int $offset The 0-based offset for reading from the resultset row.
* @param string $indexType The index type of $row. Mostly DataFetcher->getIndexType().
One of the class type constants TableMap::TYPE_PHPNAME, TableMap::TYPE_STUDLYPHPNAME
* TableMap::TYPE_COLNAME, TableMap::TYPE_FIELDNAME, TableMap::TYPE_NUM.
*
* @throws PropelException Any exceptions caught during processing will be
* rethrown wrapped into a PropelException.
* @return array (OrderVersion object, last column rank)
*/
public static function populateObject($row, $offset = 0, $indexType = TableMap::TYPE_NUM)
{
$key = OrderVersionTableMap::getPrimaryKeyHashFromRow($row, $offset, $indexType);
if (null !== ($obj = OrderVersionTableMap::getInstanceFromPool($key))) {
// We no longer rehydrate the object, since this can cause data loss.
// See http://www.propelorm.org/ticket/509
// $obj->hydrate($row, $offset, true); // rehydrate
$col = $offset + OrderVersionTableMap::NUM_HYDRATE_COLUMNS;
} else {
$cls = OrderVersionTableMap::OM_CLASS;
$obj = new $cls();
$col = $obj->hydrate($row, $offset, false, $indexType);
OrderVersionTableMap::addInstanceToPool($obj, $key);
}
return array($obj, $col);
}
/**
* The returned array will contain objects of the default type or
* objects that inherit from the default.
*
* @param DataFetcherInterface $dataFetcher
* @return array
* @throws PropelException Any exceptions caught during processing will be
* rethrown wrapped into a PropelException.
*/
public static function populateObjects(DataFetcherInterface $dataFetcher)
{
$results = array();
// set the class once to avoid overhead in the loop
$cls = static::getOMClass(false);
// populate the object(s)
while ($row = $dataFetcher->fetch()) {
$key = OrderVersionTableMap::getPrimaryKeyHashFromRow($row, 0, $dataFetcher->getIndexType());
if (null !== ($obj = OrderVersionTableMap::getInstanceFromPool($key))) {
// We no longer rehydrate the object, since this can cause data loss.
// See http://www.propelorm.org/ticket/509
// $obj->hydrate($row, 0, true); // rehydrate
$results[] = $obj;
} else {
$obj = new $cls();
$obj->hydrate($row);
$results[] = $obj;
OrderVersionTableMap::addInstanceToPool($obj, $key);
} // if key exists
}
return $results;
}
/**
* Add all the columns needed to create a new object.
*
* Note: any columns that were marked with lazyLoad="true" in the
* XML schema will not be added to the select list and only loaded
* on demand.
*
* @param Criteria $criteria object containing the columns to add.
* @param string $alias optional table alias
* @throws PropelException Any exceptions caught during processing will be
* rethrown wrapped into a PropelException.
*/
public static function addSelectColumns(Criteria $criteria, $alias = null)
{
if (null === $alias) {
$criteria->addSelectColumn(OrderVersionTableMap::ID);
$criteria->addSelectColumn(OrderVersionTableMap::REF);
$criteria->addSelectColumn(OrderVersionTableMap::CUSTOMER_ID);
$criteria->addSelectColumn(OrderVersionTableMap::INVOICE_ORDER_ADDRESS_ID);
$criteria->addSelectColumn(OrderVersionTableMap::DELIVERY_ORDER_ADDRESS_ID);
$criteria->addSelectColumn(OrderVersionTableMap::INVOICE_DATE);
$criteria->addSelectColumn(OrderVersionTableMap::CURRENCY_ID);
$criteria->addSelectColumn(OrderVersionTableMap::CURRENCY_RATE);
$criteria->addSelectColumn(OrderVersionTableMap::TRANSACTION_REF);
$criteria->addSelectColumn(OrderVersionTableMap::DELIVERY_REF);
$criteria->addSelectColumn(OrderVersionTableMap::INVOICE_REF);
$criteria->addSelectColumn(OrderVersionTableMap::DISCOUNT);
$criteria->addSelectColumn(OrderVersionTableMap::POSTAGE);
$criteria->addSelectColumn(OrderVersionTableMap::PAYMENT_MODULE_ID);
$criteria->addSelectColumn(OrderVersionTableMap::DELIVERY_MODULE_ID);
$criteria->addSelectColumn(OrderVersionTableMap::STATUS_ID);
$criteria->addSelectColumn(OrderVersionTableMap::LANG_ID);
$criteria->addSelectColumn(OrderVersionTableMap::CREATED_AT);
$criteria->addSelectColumn(OrderVersionTableMap::UPDATED_AT);
$criteria->addSelectColumn(OrderVersionTableMap::VERSION);
$criteria->addSelectColumn(OrderVersionTableMap::VERSION_CREATED_AT);
$criteria->addSelectColumn(OrderVersionTableMap::VERSION_CREATED_BY);
} else {
$criteria->addSelectColumn($alias . '.ID');
$criteria->addSelectColumn($alias . '.REF');
$criteria->addSelectColumn($alias . '.CUSTOMER_ID');
$criteria->addSelectColumn($alias . '.INVOICE_ORDER_ADDRESS_ID');
$criteria->addSelectColumn($alias . '.DELIVERY_ORDER_ADDRESS_ID');
$criteria->addSelectColumn($alias . '.INVOICE_DATE');
$criteria->addSelectColumn($alias . '.CURRENCY_ID');
$criteria->addSelectColumn($alias . '.CURRENCY_RATE');
$criteria->addSelectColumn($alias . '.TRANSACTION_REF');
$criteria->addSelectColumn($alias . '.DELIVERY_REF');
$criteria->addSelectColumn($alias . '.INVOICE_REF');
$criteria->addSelectColumn($alias . '.DISCOUNT');
$criteria->addSelectColumn($alias . '.POSTAGE');
$criteria->addSelectColumn($alias . '.PAYMENT_MODULE_ID');
$criteria->addSelectColumn($alias . '.DELIVERY_MODULE_ID');
$criteria->addSelectColumn($alias . '.STATUS_ID');
$criteria->addSelectColumn($alias . '.LANG_ID');
$criteria->addSelectColumn($alias . '.CREATED_AT');
$criteria->addSelectColumn($alias . '.UPDATED_AT');
$criteria->addSelectColumn($alias . '.VERSION');
$criteria->addSelectColumn($alias . '.VERSION_CREATED_AT');
$criteria->addSelectColumn($alias . '.VERSION_CREATED_BY');
}
}
/**
* Returns the TableMap related to this object.
* This method is not needed for general use but a specific application could have a need.
* @return TableMap
* @throws PropelException Any exceptions caught during processing will be
* rethrown wrapped into a PropelException.
*/
public static function getTableMap()
{
return Propel::getServiceContainer()->getDatabaseMap(OrderVersionTableMap::DATABASE_NAME)->getTable(OrderVersionTableMap::TABLE_NAME);
}
/**
* Add a TableMap instance to the database for this tableMap class.
*/
public static function buildTableMap()
{
$dbMap = Propel::getServiceContainer()->getDatabaseMap(OrderVersionTableMap::DATABASE_NAME);
if (!$dbMap->hasTable(OrderVersionTableMap::TABLE_NAME)) {
$dbMap->addTableObject(new OrderVersionTableMap());
}
}
/**
* Performs a DELETE on the database, given a OrderVersion or Criteria object OR a primary key value.
*
* @param mixed $values Criteria or OrderVersion object or primary key or array of primary keys
* which is used to create the DELETE statement
* @param ConnectionInterface $con the connection to use
* @return int The number of affected rows (if supported by underlying database driver). This includes CASCADE-related rows
* if supported by native driver or if emulated using Propel.
* @throws PropelException Any exceptions caught during processing will be
* rethrown wrapped into a PropelException.
*/
public static function doDelete($values, ConnectionInterface $con = null)
{
if (null === $con) {
$con = Propel::getServiceContainer()->getWriteConnection(OrderVersionTableMap::DATABASE_NAME);
}
if ($values instanceof Criteria) {
// rename for clarity
$criteria = $values;
} elseif ($values instanceof \Thelia\Model\OrderVersion) { // it's a model object
// create criteria based on pk values
$criteria = $values->buildPkeyCriteria();
} else { // it's a primary key, or an array of pks
$criteria = new Criteria(OrderVersionTableMap::DATABASE_NAME);
// primary key is composite; we therefore, expect
// the primary key passed to be an array of pkey values
if (count($values) == count($values, COUNT_RECURSIVE)) {
// array is not multi-dimensional
$values = array($values);
}
foreach ($values as $value) {
$criterion = $criteria->getNewCriterion(OrderVersionTableMap::ID, $value[0]);
$criterion->addAnd($criteria->getNewCriterion(OrderVersionTableMap::VERSION, $value[1]));
$criteria->addOr($criterion);
}
}
$query = OrderVersionQuery::create()->mergeWith($criteria);
if ($values instanceof Criteria) { OrderVersionTableMap::clearInstancePool();
} elseif (!is_object($values)) { // it's a primary key, or an array of pks
foreach ((array) $values as $singleval) { OrderVersionTableMap::removeInstanceFromPool($singleval);
}
}
return $query->delete($con);
}
/**
* Deletes all rows from the order_version table.
*
* @param ConnectionInterface $con the connection to use
* @return int The number of affected rows (if supported by underlying database driver).
*/
public static function doDeleteAll(ConnectionInterface $con = null)
{
return OrderVersionQuery::create()->doDeleteAll($con);
}
/**
* Performs an INSERT on the database, given a OrderVersion or Criteria object.
*
* @param mixed $criteria Criteria or OrderVersion object containing data that is used to create the INSERT statement.
* @param ConnectionInterface $con the ConnectionInterface connection to use
* @return mixed The new primary key.
* @throws PropelException Any exceptions caught during processing will be
* rethrown wrapped into a PropelException.
*/
public static function doInsert($criteria, ConnectionInterface $con = null)
{
if (null === $con) {
$con = Propel::getServiceContainer()->getWriteConnection(OrderVersionTableMap::DATABASE_NAME);
}
if ($criteria instanceof Criteria) {
$criteria = clone $criteria; // rename for clarity
} else {
$criteria = $criteria->buildCriteria(); // build Criteria from OrderVersion object
}
// Set the correct dbName
$query = OrderVersionQuery::create()->mergeWith($criteria);
try {
// use transaction because $criteria could contain info
// for more than one table (I guess, conceivably)
$con->beginTransaction();
$pk = $query->doInsert($con);
$con->commit();
} catch (PropelException $e) {
$con->rollBack();
throw $e;
}
return $pk;
}
} // OrderVersionTableMap
// This is the static code needed to register the TableMap for this table with the main Propel class.
//
OrderVersionTableMap::buildTableMap();

View File

@@ -75,8 +75,6 @@ class Message extends BaseMessage
{
$body = false;
//$mail_template_path = TemplateHelper::getInstance()->getActiveMailTemplate()->getAbsolutePath() . DS;
// Try to get the body from template file, if a file is defined
if (! empty($template)) {
try {

View File

@@ -3,6 +3,7 @@
namespace Thelia\Model;
use Thelia\Model\Base\ModuleQuery as BaseModuleQuery;
use Thelia\Module\BaseModule;
/**
* Skeleton subclass for performing query and update operations on the 'module' table.
@@ -24,7 +25,7 @@ class ModuleQuery extends BaseModuleQuery
{
if (null === self::$activated) {
self::$activated = self::create()
->filterByActivate(1)
->filterByActivate(BaseModule::IS_ACTIVATED)
->orderByPosition()
->find();
}
@@ -37,4 +38,17 @@ class ModuleQuery extends BaseModuleQuery
self::$activated = null;
}
/**
* @param int $moduleType the module type : classic, payment or delivery. Use BaseModule constant here.
* @param int $id the module id
* @return ModuleQuery
*/
public function filterActivatedByTypeAndId($moduleType, $id)
{
return $this
->filterByType($moduleType)
->filterByActivate(BaseModule::IS_ACTIVATED)
->filterById($id);
}
} // ModuleQuery

Some files were not shown because too many files have changed in this diff Show More