Skip to content
Code-Schnipsel Gruppen Projekte

Revisionen vergleichen

Änderungen werden so angezeigt, als ob die Quellrevision mit der Zielrevision zusammengeführt würde. Erfahre mehr über den Vergleich von Revisionen.

Quelle

Zielprojekt auswählen
No results found

Ziel

Zielprojekt auswählen
  • quiqqer/coupons
1 Ergebnis
Änderungen anzeigen
Commits auf Quelle (6)
werden angezeigt mit 377 Ergänzungen und 344 Löschungen
include:
- project: 'quiqqer/stabilization/semantic-release'
file: '/ci-templates/.gitlab-ci.yml'
GPL-3.0+
\ No newline at end of file
...@@ -13,9 +13,9 @@ ...@@ -13,9 +13,9 @@
QUI::$Ajax->registerFunction( QUI::$Ajax->registerFunction(
'package_quiqqer_coupons_ajax_backend_getCouponPrice', 'package_quiqqer_coupons_ajax_backend_getCouponPrice',
function ($couponId, $vat) { function ($couponId, $vat) {
$Coupon = QUI\ERP\Coupons\Handler::getCouponCode($couponId); $Coupon = QUI\ERP\Coupons\Handler::getCouponCode($couponId);
$discounts = $Coupon->getDiscounts(); $discounts = $Coupon->getDiscounts();
$price = 0; $price = 0;
foreach ($discounts as $Discount) { foreach ($discounts as $Discount) {
$PriceFactor = $Discount->toPriceFactor(); $PriceFactor = $Discount->toPriceFactor();
......
<?php <?php
use QUI\ERP\Coupons\CouponCodeException;
use QUI\ERP\Coupons\Handler;
use QUI\ERP\Discount\Handler as DiscountsHandler;
use QUI\Utils\Security\Orthos;
/** /**
* Create new CouponCode(s) * Create new CouponCode(s)
* *
* @param array $attributes * @param array $attributes
* @return bool - success * @return bool - success
*/ */
use QUI\ERP\Coupons\CouponCodeException;
use QUI\ERP\Coupons\Handler;
use QUI\ERP\Discount\Handler as DiscountsHandler;
use QUI\Utils\Security\Orthos;
QUI::$Ajax->registerFunction( QUI::$Ajax->registerFunction(
'package_quiqqer_coupons_ajax_create', 'package_quiqqer_coupons_ajax_create',
function ($attributes) { function ($attributes) {
...@@ -25,7 +26,7 @@ function ($attributes) { ...@@ -25,7 +26,7 @@ function ($attributes) {
} }
try { try {
$amount = 1; $amount = 1;
$couponCodes = []; $couponCodes = [];
if (!empty($attributes['amount'])) { if (!empty($attributes['amount'])) {
...@@ -57,10 +58,10 @@ function ($attributes) { ...@@ -57,10 +58,10 @@ function ($attributes) {
$discountType = DiscountsHandler::DISCOUNT_TYPE_CURRENCY; $discountType = DiscountsHandler::DISCOUNT_TYPE_CURRENCY;
} }
$Discounts = DiscountsHandler::getInstance(); $Discounts = DiscountsHandler::getInstance();
$NewDiscount = $Discounts->createChild([ $NewDiscount = $Discounts->createChild([
'active' => 1, 'active' => 1,
'discount' => (float)$attributes['discountAmount'], 'discount' => (float)$attributes['discountAmount'],
'discount_type' => $discountType, 'discount_type' => $discountType,
]); ]);
......
...@@ -4,7 +4,6 @@ ...@@ -4,7 +4,6 @@
* This file contains package_quiqqer_coupons_ajax_delete * This file contains package_quiqqer_coupons_ajax_delete
*/ */
use QUI\ERP\Coupons\CouponCodeException;
use QUI\ERP\Coupons\Handler; use QUI\ERP\Coupons\Handler;
use QUI\ERP\Discount\EventHandling as DiscountEvents; use QUI\ERP\Discount\EventHandling as DiscountEvents;
...@@ -18,7 +17,7 @@ ...@@ -18,7 +17,7 @@
'package_quiqqer_coupons_ajax_frontend_redeem', 'package_quiqqer_coupons_ajax_frontend_redeem',
function ($code, $orderHash) { function ($code, $orderHash) {
try { try {
$code = Handler::sanitizeCode($code); $code = Handler::sanitizeCode($code);
$CouponCode = Handler::getCouponCodeByCode($code); $CouponCode = Handler::getCouponCodeByCode($code);
$CouponCode->checkRedemption(QUI::getUserBySession()); $CouponCode->checkRedemption(QUI::getUserBySession());
} catch (QUI\ERP\Coupons\CouponCodeException $Exception) { } catch (QUI\ERP\Coupons\CouponCodeException $Exception) {
...@@ -40,13 +39,13 @@ function ($code, $orderHash) { ...@@ -40,13 +39,13 @@ function ($code, $orderHash) {
return false; return false;
} }
$Order = QUI\ERP\Order\Handler::getInstance()->getOrderByHash($orderHash); $Order = QUI\ERP\Order\Handler::getInstance()->getOrderByHash($orderHash);
$productCount = $Order->getArticles()->count(); $productCount = $Order->getArticles()->count();
$calculations = $Order->getArticles()->getCalculations(); $calculations = $Order->getArticles()->getCalculations();
$subSum = $calculations['subSum']; $subSum = $calculations['subSum'];
$sum = $calculations['sum']; $sum = $calculations['sum'];
$discounts = $CouponCode->getDiscounts(); $discounts = $CouponCode->getDiscounts();
foreach ($discounts as $Discount) { foreach ($discounts as $Discount) {
if (!DiscountEvents::isDiscountUsableWithQuantity($Discount, $productCount)) { if (!DiscountEvents::isDiscountUsableWithQuantity($Discount, $productCount)) {
......
...@@ -12,7 +12,7 @@ ...@@ -12,7 +12,7 @@
QUI::$Ajax->registerFunction( QUI::$Ajax->registerFunction(
'package_quiqqer_coupons_ajax_frontend_removeCoupons', 'package_quiqqer_coupons_ajax_frontend_removeCoupons',
function ($orderHash) { function ($orderHash) {
$Order = QUI\ERP\Order\Handler::getInstance()->getOrderByHash($orderHash); $Order = QUI\ERP\Order\Handler::getInstance()->getOrderByHash($orderHash);
$Articles = $Order->getArticles(); $Articles = $Order->getArticles();
foreach ($Articles as $index => $Article) { foreach ($Articles as $index => $Article) {
......
...@@ -5,9 +5,9 @@ ...@@ -5,9 +5,9 @@
*/ */
use QUI\ERP\Coupons\Handler; use QUI\ERP\Coupons\Handler;
use QUI\Utils\Security\Orthos;
use QUI\Utils\Grid;
use QUI\Permissions\Permission; use QUI\Permissions\Permission;
use QUI\Utils\Grid;
use QUI\Utils\Security\Orthos;
/** /**
* Get list of CouponCodes * Get list of CouponCodes
...@@ -21,9 +21,9 @@ function ($searchParams) { ...@@ -21,9 +21,9 @@ function ($searchParams) {
Permission::hasPermission(Handler::PERMISSION_VIEW); Permission::hasPermission(Handler::PERMISSION_VIEW);
$searchParams = Orthos::clearArray(\json_decode($searchParams, true)); $searchParams = Orthos::clearArray(\json_decode($searchParams, true));
$couponCodes = []; $couponCodes = [];
$Users = QUI::getUsers(); $Users = QUI::getUsers();
$L = QUI::getLocale(); $L = QUI::getLocale();
try { try {
foreach (Handler::search($searchParams) as $CouponCode) { foreach (Handler::search($searchParams) as $CouponCode) {
...@@ -40,7 +40,7 @@ function ($searchParams) { ...@@ -40,7 +40,7 @@ function ($searchParams) {
$couponCode['usages'][$k]['userName'] = $User->getUsername(); $couponCode['usages'][$k]['userName'] = $User->getUsername();
// Date // Date
$Date = new DateTime($usage['date']); $Date = new DateTime($usage['date']);
$couponCode['usages'][$k]['date'] = $L->formatDate($Date->getTimestamp()); $couponCode['usages'][$k]['date'] = $L->formatDate($Date->getTimestamp());
} }
......
...@@ -3,8 +3,12 @@ ...@@ -3,8 +3,12 @@
namespace QUI\ERP\Coupons; namespace QUI\ERP\Coupons;
use QUI; use QUI;
use QUI\Exception;
use QUI\Utils\System\File; use QUI\Utils\System\File;
use function basename;
use function call_user_func;
/** /**
* Class CodeGenerator * Class CodeGenerator
* *
...@@ -16,11 +20,11 @@ class CodeGenerator ...@@ -16,11 +20,11 @@ class CodeGenerator
* Generate a new, random Invite Code * Generate a new, random Invite Code
* *
* @return string * @return string
* @throws \QUI\Exception * @throws Exception
*/ */
public static function generate() public static function generate(): string
{ {
$generator = '\\QUI\\ERP\\Coupons\\CodeGenerators\\'.self::getCurrentGenerator(); $generator = '\\QUI\\ERP\\Coupons\\CodeGenerators\\' . self::getCurrentGenerator();
$Config = QUI::getPackage('quiqqer/coupons')->getConfig(); $Config = QUI::getPackage('quiqqer/coupons')->getConfig();
$prefix = $Config->get('settings', 'prefix'); $prefix = $Config->get('settings', 'prefix');
...@@ -29,18 +33,18 @@ public static function generate() ...@@ -29,18 +33,18 @@ public static function generate()
$prefix = ''; $prefix = '';
} }
return \call_user_func($generator.'::generate', $prefix); return call_user_func($generator . '::generate', $prefix);
} }
/** /**
* Get CodeGenerator that is currently set * Get CodeGenerator that is currently set
* *
* @return string - FQ class name * @return string - FQ class name
* @throws \QUI\Exception * @throws Exception
*/ */
protected static function getCurrentGenerator() protected static function getCurrentGenerator(): string
{ {
$Config = QUI::getPackage('quiqqer/coupons')->getConfig(); $Config = QUI::getPackage('quiqqer/coupons')->getConfig();
$currentGenerator = $Config->get('settings', 'codeGenerator'); $currentGenerator = $Config->get('settings', 'codeGenerator');
if (empty($currentGenerator)) { if (empty($currentGenerator)) {
...@@ -54,15 +58,15 @@ protected static function getCurrentGenerator() ...@@ -54,15 +58,15 @@ protected static function getCurrentGenerator()
* Get list of all available CodeGenerators * Get list of all available CodeGenerators
* *
* @return array * @return array
* @throws \QUI\Exception * @throws Exception
*/ */
public static function getList() public static function getList(): array
{ {
$dir = QUI::getPackage('quiqqer/coupons')->getDir().'src/QUI/ERP/Coupons/CodeGenerators'; $dir = QUI::getPackage('quiqqer/coupons')->getDir() . 'src/QUI/ERP/Coupons/CodeGenerators';
$generators = []; $generators = [];
foreach (File::readDir($dir, true) as $file) { foreach (File::readDir($dir, true) as $file) {
$generators[] = \basename($file, '.php'); $generators[] = basename($file, '.php');
} }
return $generators; return $generators;
......
...@@ -9,6 +9,10 @@ ...@@ -9,6 +9,10 @@
use QUI\ERP\Coupons\CodeGeneratorInterface; use QUI\ERP\Coupons\CodeGeneratorInterface;
use QUI\ERP\Coupons\Handler; use QUI\ERP\Coupons\Handler;
use function array_merge;
use function random_int;
use function range;
/** /**
* Class SimpleString * Class SimpleString
* *
...@@ -25,11 +29,11 @@ class SimpleString implements CodeGeneratorInterface ...@@ -25,11 +29,11 @@ class SimpleString implements CodeGeneratorInterface
* @return string * @return string
* @throws \Exception * @throws \Exception
*/ */
public static function generate($prefix = '') public static function generate($prefix = ''): string
{ {
$characters = \array_merge( $characters = array_merge(
\range('A', 'Z'), range('A', 'Z'),
\range(0, 9) range(0, 9)
); );
$count = count($characters) - 1; $count = count($characters) - 1;
...@@ -38,7 +42,7 @@ public static function generate($prefix = '') ...@@ -38,7 +42,7 @@ public static function generate($prefix = '')
$code = $prefix; $code = $prefix;
for ($i = 0; $i < self::CODE_LENGTH; $i++) { for ($i = 0; $i < self::CODE_LENGTH; $i++) {
$code .= $characters[\random_int(0, $count)]; $code .= $characters[random_int(0, $count)];
} }
} while (Handler::existsCode($code)); } while (Handler::existsCode($code));
......
...@@ -13,8 +13,8 @@ class Uuid implements CodeGeneratorInterface ...@@ -13,8 +13,8 @@ class Uuid implements CodeGeneratorInterface
* @param string $prefix (optional) * @param string $prefix (optional)
* @return string * @return string
*/ */
public static function generate($prefix = '') public static function generate($prefix = ''): string
{ {
return $prefix.UuidCreator::uuid1()->toString(); return $prefix . UuidCreator::uuid1()->toString();
} }
} }
...@@ -16,6 +16,7 @@ ...@@ -16,6 +16,7 @@
use function is_array; use function is_array;
use function is_null; use function is_null;
use function json_decode; use function json_decode;
use function json_encode;
use function method_exists; use function method_exists;
/** /**
...@@ -28,7 +29,7 @@ class CouponCode ...@@ -28,7 +29,7 @@ class CouponCode
* *
* @var int * @var int
*/ */
protected $id; protected int $id;
/** /**
* Actual code * Actual code
...@@ -68,16 +69,16 @@ class CouponCode ...@@ -68,16 +69,16 @@ class CouponCode
/** /**
* Creation Date * Creation Date
* *
* @var \DateTime * @var DateTime|null
*/ */
protected $CreateDate; protected ?DateTime $CreateDate = null;
/** /**
* Date until the CouponCode is valid * Date until the CouponCode is valid
* *
* @var \DateTime * @var DateTime|null
*/ */
protected $ValidUntilDate = null; protected ?DateTime $ValidUntilDate = null;
/** /**
* CouponCode title * CouponCode title
...@@ -106,13 +107,13 @@ class CouponCode ...@@ -106,13 +107,13 @@ class CouponCode
* @param int $id - Invite Code ID * @param int $id - Invite Code ID
* *
* @throws CouponCodeException * @throws CouponCodeException
* @throws \Exception * @throws Exception
*/ */
public function __construct(int $id) public function __construct(int $id)
{ {
try { try {
$result = QUI::getDataBase()->fetch([ $result = QUI::getDataBase()->fetch([
'from' => Handler::getTable(), 'from' => Handler::getTable(),
'where' => [ 'where' => [
'id' => $id 'id' => $id
] ]
...@@ -141,8 +142,8 @@ public function __construct(int $id) ...@@ -141,8 +142,8 @@ public function __construct(int $id)
$data = current($result); $data = current($result);
$this->id = (int)$data['id']; $this->id = (int)$data['id'];
$this->code = $data['code']; $this->code = $data['code'];
$this->title = $data['title']; $this->title = $data['title'];
if (!empty($data['usages'])) { if (!empty($data['usages'])) {
...@@ -192,7 +193,7 @@ public function getCode(): string ...@@ -192,7 +193,7 @@ public function getCode(): string
} }
/** /**
* @return \DateTime * @return DateTime
*/ */
public function getCreateDate(): DateTime public function getCreateDate(): DateTime
{ {
...@@ -210,7 +211,7 @@ public function getUsages(): array ...@@ -210,7 +211,7 @@ public function getUsages(): array
} }
/** /**
* @return \DateTime|null * @return DateTime|null
*/ */
public function getValidUntilDate(): ?DateTime public function getValidUntilDate(): ?DateTime
{ {
...@@ -240,7 +241,7 @@ public function getDiscountIds(): array ...@@ -240,7 +241,7 @@ public function getDiscountIds(): array
*/ */
public function getDiscounts(): array public function getDiscounts(): array
{ {
$discounts = []; $discounts = [];
$DiscountHandler = DiscountHandler::getInstance(); $DiscountHandler = DiscountHandler::getInstance();
foreach ($this->discountIds as $discountId) { foreach ($this->discountIds as $discountId) {
...@@ -275,13 +276,13 @@ public function getGroupIds(): array ...@@ -275,13 +276,13 @@ public function getGroupIds(): array
* *
* Hint: This may invalidate the code for future use * Hint: This may invalidate the code for future use
* *
* @param QUI\Users\User $User - The user that redeems the CouponCode [if omitted use Session User] * @param QUI\Interfaces\Users\User $User - The user that redeems the CouponCode [if omitted use Session User]
* @param QUI\ERP\Order\Order $Order (optional) - Link redemption to a specific Order * @param QUI\ERP\Order\Order|null $Order (optional) - Link redemption to a specific Order
* @return void * @return void
* @throws CouponCodeException * @throws CouponCodeException
* @throws QUI\Exception * @throws QUI\Exception
*/ */
public function redeem($User = null, $Order = null) public function redeem(QUI\Interfaces\Users\User $User = null, QUI\ERP\Order\Order $Order = null)
{ {
if (is_null($User)) { if (is_null($User)) {
$User = QUI::getUserBySession(); $User = QUI::getUserBySession();
...@@ -292,8 +293,8 @@ public function redeem($User = null, $Order = null) ...@@ -292,8 +293,8 @@ public function redeem($User = null, $Order = null)
$Now = new DateTime(); $Now = new DateTime();
$usage = [ $usage = [
'userId' => $User->getId(), 'userId' => $User->getId(),
'date' => $Now->format('Y-m-d H:i:s'), 'date' => $Now->format('Y-m-d H:i:s'),
'orderPrefixedId' => false 'orderPrefixedId' => false
]; ];
...@@ -305,7 +306,7 @@ public function redeem($User = null, $Order = null) ...@@ -305,7 +306,7 @@ public function redeem($User = null, $Order = null)
QUI::getDataBase()->update( QUI::getDataBase()->update(
Handler::getTable(), Handler::getTable(),
['usages' => \json_encode($this->usages)], ['usages' => json_encode($this->usages)],
['id' => $this->id] ['id' => $this->id]
); );
...@@ -314,7 +315,7 @@ public function redeem($User = null, $Order = null) ...@@ -314,7 +315,7 @@ public function redeem($User = null, $Order = null)
QUI::getEvents()->fireEvent( QUI::getEvents()->fireEvent(
'quiqqerCouponsRedeem', 'quiqqerCouponsRedeem',
[ [
'User' => $User, 'User' => $User,
'CouponCode' => $this 'CouponCode' => $this
] ]
); );
...@@ -327,7 +328,7 @@ public function redeem($User = null, $Order = null) ...@@ -327,7 +328,7 @@ public function redeem($User = null, $Order = null)
* @return void * @return void
* @throws CouponCodeException - Thrown if not redeemable by the given User * @throws CouponCodeException - Thrown if not redeemable by the given User
*/ */
public function checkRedemption($User) public function checkRedemption(QUI\Interfaces\Users\User $User)
{ {
if (!$this->isValid()) { if (!$this->isValid()) {
throw new CouponCodeException([ throw new CouponCodeException([
...@@ -337,8 +338,8 @@ public function checkRedemption($User) ...@@ -337,8 +338,8 @@ public function checkRedemption($User)
} }
$DiscountHandler = DiscountHandler::getInstance(); $DiscountHandler = DiscountHandler::getInstance();
$discountsValid = false; $discountsValid = false;
$discountError = false; $discountError = false;
foreach ($this->discountIds as $discountId) { foreach ($this->discountIds as $discountId) {
try { try {
...@@ -396,8 +397,10 @@ public function checkRedemption($User) ...@@ -396,8 +397,10 @@ public function checkRedemption($User)
// Restriction to QUIQQER user(s) // Restriction to QUIQQER user(s)
if (!empty($this->userIds)) { if (!empty($this->userIds)) {
if (in_array($User->getId(), $this->userIds)) { if (in_array($User->getId(), $this->userIds)) {
if ($this->maxUsages !== Handler::MAX_USAGE_UNLIMITED if (
&& $this->hasUserRedeemed($User)) { $this->maxUsages !== Handler::MAX_USAGE_UNLIMITED
&& $this->hasUserRedeemed($User)
) {
throw new CouponCodeException([ throw new CouponCodeException([
'quiqqer/coupons', 'quiqqer/coupons',
'exception.CouponCode.already_used' 'exception.CouponCode.already_used'
...@@ -423,8 +426,10 @@ public function checkRedemption($User) ...@@ -423,8 +426,10 @@ public function checkRedemption($User)
} }
if ($userInGroup) { if ($userInGroup) {
if ($this->maxUsages !== Handler::MAX_USAGE_UNLIMITED if (
&& $this->hasUserRedeemed($User)) { $this->maxUsages !== Handler::MAX_USAGE_UNLIMITED
&& $this->hasUserRedeemed($User)
) {
throw new CouponCodeException([ throw new CouponCodeException([
'quiqqer/coupons', 'quiqqer/coupons',
'exception.CouponCode.already_used' 'exception.CouponCode.already_used'
...@@ -445,15 +450,15 @@ public function checkRedemption($User) ...@@ -445,15 +450,15 @@ public function checkRedemption($User)
* @param OrderInterface|null $Order * @param OrderInterface|null $Order
* @throws CouponCodeException * @throws CouponCodeException
*/ */
public function checkOrderRedemption($Order) public function checkOrderRedemption(?OrderInterface $Order)
{ {
if ($Order === null) { if ($Order === null) {
return; return;
} }
$DiscountHandler = DiscountHandler::getInstance(); $DiscountHandler = DiscountHandler::getInstance();
$discountsValid = false; $discountsValid = false;
$discountError = false; $discountError = false;
foreach ($this->discountIds as $discountId) { foreach ($this->discountIds as $discountId) {
try { try {
...@@ -491,11 +496,11 @@ public function checkOrderRedemption($Order) ...@@ -491,11 +496,11 @@ public function checkOrderRedemption($Order)
/** /**
* Check if the given User can redeem this CouponCode * Check if the given User can redeem this CouponCode
* *
* @param QUI\Users\User $User - If omitted, use session user * @param QUI\Interfaces\Users\User $User - If omitted, use session user
* @param OrderInterface $Order * @param OrderInterface|null $Order
* @return bool * @return bool
*/ */
public function isRedeemable($User = null, $Order = null): bool public function isRedeemable(QUI\Interfaces\Users\User $User = null, OrderInterface $Order = null): bool
{ {
try { try {
$this->checkRedemption($User); $this->checkRedemption($User);
...@@ -549,7 +554,7 @@ public function hasUserRedeemed(QUI\Interfaces\Users\User $User): bool ...@@ -549,7 +554,7 @@ public function hasUserRedeemed(QUI\Interfaces\Users\User $User): bool
* Permanently delete this CouponCode * Permanently delete this CouponCode
* *
* @return void * @return void
* @throws \QUI\Permissions\Exception * @throws QUI\Permissions\Exception
*/ */
public function delete() public function delete()
{ {
...@@ -584,17 +589,17 @@ public function delete() ...@@ -584,17 +589,17 @@ public function delete()
public function toArray(): array public function toArray(): array
{ {
$data = [ $data = [
'id' => $this->getId(), 'id' => $this->getId(),
'code' => $this->getCode(), 'code' => $this->getCode(),
'userIds' => $this->userIds, 'userIds' => $this->userIds,
'groupIds' => $this->groupIds, 'groupIds' => $this->groupIds,
'createDate' => $this->getCreateDate()->format('Y-m-d H:i:s'), 'createDate' => $this->getCreateDate()->format('Y-m-d H:i:s'),
'usages' => $this->usages, 'usages' => $this->usages,
'validUntilDate' => false, 'validUntilDate' => false,
'title' => $this->getTitle() ?: false, 'title' => $this->getTitle() ?: false,
'isValid' => $this->isValid(), 'isValid' => $this->isValid(),
'maxUsages' => $this->maxUsages, 'maxUsages' => $this->maxUsages,
'discountIds' => $this->discountIds 'discountIds' => $this->discountIds
]; ];
$ValidUntilDate = $this->getValidUntilDate(); $ValidUntilDate = $this->getValidUntilDate();
...@@ -673,10 +678,10 @@ public function addToOrder(QUI\ERP\Order\OrderInProcess $Order) ...@@ -673,10 +678,10 @@ public function addToOrder(QUI\ERP\Order\OrderInProcess $Order)
} }
$priceFactors = []; $priceFactors = [];
$articles = []; $articles = [];
$calculations = $Order->getArticles()->getCalculations(); $calculations = $Order->getArticles()->getCalculations();
$vatArray = $calculations['vatArray']; $vatArray = $calculations['vatArray'];
$vat = false; $vat = false;
if (count($vatArray) === 1) { if (count($vatArray) === 1) {
$vat = array_key_first($vatArray); $vat = array_key_first($vatArray);
...@@ -716,16 +721,16 @@ public function addToOrder(QUI\ERP\Order\OrderInProcess $Order) ...@@ -716,16 +721,16 @@ public function addToOrder(QUI\ERP\Order\OrderInProcess $Order)
// @todo wenn fest preis (zb 10$), dann eigener produkt typ hinzufügen // @todo wenn fest preis (zb 10$), dann eigener produkt typ hinzufügen
$articles[] = new QUI\ERP\Accounting\Articles\Text([ $articles[] = new QUI\ERP\Accounting\Articles\Text([
'id' => '-', 'id' => '-',
'articleNo' => $Coupon->getCode(), 'articleNo' => $Coupon->getCode(),
'title' => $PriceFactor->getTitle(), 'title' => $PriceFactor->getTitle(),
'description' => '', 'description' => '',
'unitPrice' => 0, 'unitPrice' => 0,
'control' => '', 'control' => '',
'quantity' => 1, 'quantity' => 1,
'customData' => [ 'customData' => [
'package' => 'quiqqer/coupon', 'package' => 'quiqqer/coupon',
'code' => $Coupon->getCode() 'code' => $Coupon->getCode()
] ]
]); ]);
} }
...@@ -741,7 +746,7 @@ public function addToOrder(QUI\ERP\Order\OrderInProcess $Order) ...@@ -741,7 +746,7 @@ public function addToOrder(QUI\ERP\Order\OrderInProcess $Order)
*/ */
$isInArticles = function ($Article) use ($Order) { $isInArticles = function ($Article) use ($Order) {
$articles = $Order->getArticles(); $articles = $Order->getArticles();
$code = $Article->getCustomData()['code']; $code = $Article->getCustomData()['code'];
foreach ($articles as $Entry) { foreach ($articles as $Entry) {
if (!method_exists($Entry, 'getCustomData')) { if (!method_exists($Entry, 'getCustomData')) {
......
...@@ -66,7 +66,8 @@ public static function onAdminLoadFooter() ...@@ -66,7 +66,8 @@ public static function onAdminLoadFooter()
*/ */
public static function templateOrderProcessBasketEnd(Collector $Collector, $Basket, $Order) public static function templateOrderProcessBasketEnd(Collector $Collector, $Basket, $Order)
{ {
if (!($Basket instanceof Basket) if (
!($Basket instanceof Basket)
&& !($Basket instanceof QUI\ERP\Order\Basket\BasketOrder) && !($Basket instanceof QUI\ERP\Order\Basket\BasketOrder)
) { ) {
return; return;
...@@ -157,8 +158,8 @@ public static function onQuiqqerOrderBasketRemovePos( ...@@ -157,8 +158,8 @@ public static function onQuiqqerOrderBasketRemovePos(
} }
$Article = $Order->getArticles()->getArticle($pos); $Article = $Order->getArticles()->getArticle($pos);
$customData = $Article->getCustomData(); $customData = $Article->getCustomData();
$orderCoupons = $Order->getDataEntry('quiqqer-coupons'); $orderCoupons = $Order->getDataEntry('quiqqer-coupons');
$articleCouponCode = false; $articleCouponCode = false;
...@@ -230,7 +231,7 @@ public static function onQuiqqerOrderBasketToOrder( ...@@ -230,7 +231,7 @@ public static function onQuiqqerOrderBasketToOrder(
QUI\ERP\Order\AbstractOrder $Order, QUI\ERP\Order\AbstractOrder $Order,
QUI\ERP\Products\Product\ProductList $Products QUI\ERP\Products\Product\ProductList $Products
) { ) {
$coupons = $Order->getDataEntry('quiqqer-coupons'); $coupons = $Order->getDataEntry('quiqqer-coupons');
$sessionCoupons = QUI::getSession()->get('quiqqer-coupons'); $sessionCoupons = QUI::getSession()->get('quiqqer-coupons');
if (!is_array($coupons)) { if (!is_array($coupons)) {
...@@ -254,19 +255,20 @@ public static function onQuiqqerOrderBasketToOrder( ...@@ -254,19 +255,20 @@ public static function onQuiqqerOrderBasketToOrder(
} }
$PriceFactors = $Products->getPriceFactors(); $PriceFactors = $Products->getPriceFactors();
$products = $Products->toArray(); $products = $Products->toArray();
$productCount = $Products->count(); $productCount = $Products->count();
$subSum = $products['calculations']['subSum']; $subSum = $products['calculations']['subSum'];
$checkRedeemable = !$Order->isSuccessful(); // if order is successful we dont need a check $checkRedeemable = !$Order->isSuccessful(); // if order is successful we dont need a check
$OrderInProcess = $Order->getAttribute('OrderInProcess'); $OrderInProcess = $Order->getAttribute('OrderInProcess');
$added = false; $added = false;
if ($Order->getAttribute('inOrderCreation')) { if ($Order->getAttribute('inOrderCreation')) {
$checkRedeemable = false; $checkRedeemable = false;
} }
if ($OrderInProcess instanceof QUI\ERP\Order\OrderInProcess if (
$OrderInProcess instanceof QUI\ERP\Order\OrderInProcess
&& $OrderInProcess->getAttribute('inOrderCreation') && $OrderInProcess->getAttribute('inOrderCreation')
) { ) {
$checkRedeemable = false; $checkRedeemable = false;
...@@ -307,13 +309,13 @@ public static function onQuiqqerOrderBasketToOrder( ...@@ -307,13 +309,13 @@ public static function onQuiqqerOrderBasketToOrder(
]) ])
); );
$scope = $Discount->getAttribute('scope'); $scope = $Discount->getAttribute('scope');
$isUnique = $scope === QUI\ERP\Discount\Handler::DISCOUNT_SCOPE_UNIQUE; $isUnique = $scope === QUI\ERP\Discount\Handler::DISCOUNT_SCOPE_UNIQUE;
$everyProduct = $scope === QUI\ERP\Discount\Handler::DISCOUNT_SCOPE_EVERY_PRODUCT; $everyProduct = $scope === QUI\ERP\Discount\Handler::DISCOUNT_SCOPE_EVERY_PRODUCT;
if ($everyProduct || $isUnique) { if ($everyProduct || $isUnique) {
// add to the product // add to the product
$products = $Products->getProducts(); $products = $Products->getProducts();
$alreadyAdded = false; $alreadyAdded = false;
foreach ($products as $Product) { foreach ($products as $Product) {
...@@ -327,7 +329,7 @@ public static function onQuiqqerOrderBasketToOrder( ...@@ -327,7 +329,7 @@ public static function onQuiqqerOrderBasketToOrder(
if ($Product instanceof QUI\ERP\Products\Product\UniqueProduct) { if ($Product instanceof QUI\ERP\Products\Product\UniqueProduct) {
$Product->getPriceFactors()->add($PriceFactor); $Product->getPriceFactors()->add($PriceFactor);
$added = true; $added = true;
$alreadyAdded = true; $alreadyAdded = true;
} }
} }
...@@ -386,7 +388,7 @@ protected static function addSessionCouponsToOrder($Order, $coupons) ...@@ -386,7 +388,7 @@ protected static function addSessionCouponsToOrder($Order, $coupons)
} }
// coupons as article if not added // coupons as article if not added
$Articles = $Order->getArticles(); $Articles = $Order->getArticles();
$isInArticles = function ($code) use ($Articles) { $isInArticles = function ($code) use ($Articles) {
foreach ($Articles as $Article) { foreach ($Articles as $Article) {
$customData = $Article->getCustomData(); $customData = $Article->getCustomData();
...@@ -423,7 +425,7 @@ protected static function addCouponToOrder($Order, $coupon) ...@@ -423,7 +425,7 @@ protected static function addCouponToOrder($Order, $coupon)
$CouponCode->checkRedemption(QUI::getUserBySession()); $CouponCode->checkRedemption(QUI::getUserBySession());
$CouponCode->checkOrderRedemption($Order); $CouponCode->checkOrderRedemption($Order);
$coupons = $Order->getDataEntry('quiqqer-coupons'); $coupons = $Order->getDataEntry('quiqqer-coupons');
$coupons[] = $code; $coupons[] = $code;
$coupons = array_unique($coupons); $coupons = array_unique($coupons);
...@@ -455,29 +457,29 @@ public static function removeCouponsFromSession() ...@@ -455,29 +457,29 @@ public static function removeCouponsFromSession()
protected static function createProductFields() protected static function createProductFields()
{ {
$fields = [ $fields = [
CouponProductsHandler::PRODUCT_FIELD_ID_TRANSFERABLE => [ CouponProductsHandler::PRODUCT_FIELD_ID_TRANSFERABLE => [
'title' => [ 'title' => [
'de' => 'Gutschein-Code ist übertragbar', 'de' => 'Gutschein-Code ist übertragbar',
'en' => 'Coupon code is transferable' 'en' => 'Coupon code is transferable'
], ],
'description' => [ 'description' => [
'de' => 'Übertragbare Gutscheine sind auch von anderen Personen als dem Käufer einlösbar.' 'de' => 'Übertragbare Gutscheine sind auch von anderen Personen als dem Käufer einlösbar.'
. ' Nicht übertragbare Gutscheine können nur vom Käufer eingelöst werden, wenn dieser' . ' Nicht übertragbare Gutscheine können nur vom Käufer eingelöst werden, wenn dieser'
. ' eingeloggt ist.', . ' eingeloggt ist.',
'en' => 'Transferable coupons are also redeemable by persons other than the buyer.' 'en' => 'Transferable coupons are also redeemable by persons other than the buyer.'
. ' Non-transferable vouchers can only be redeemed by the buyer when logged in.' . ' Non-transferable vouchers can only be redeemed by the buyer when logged in.'
], ],
'type' => Fields::TYPE_BOOL, 'type' => Fields::TYPE_BOOL,
'public' => false, 'public' => false,
'standard' => false, 'standard' => false,
'requiredField' => false 'requiredField' => false
], ],
CouponProductsHandler::PRODUCT_FIELD_ID_SEND_MAIL => [ CouponProductsHandler::PRODUCT_FIELD_ID_SEND_MAIL => [
'title' => [ 'title' => [
'de' => 'Gutschein-Code per E-Mail senden', 'de' => 'Gutschein-Code per E-Mail senden',
'en' => 'Send coupon code via email' 'en' => 'Send coupon code via email'
], ],
'description' => [ 'description' => [
'de' => 'Der Gutschein-Code wird dem Käufer per E-Mail gesendet. Gilt nicht, wenn der Benutzer zw.' 'de' => 'Der Gutschein-Code wird dem Käufer per E-Mail gesendet. Gilt nicht, wenn der Benutzer zw.'
. ' Post- und Mail-Versand wählen kann und den Postversand auswählt.' . ' Post- und Mail-Versand wählen kann und den Postversand auswählt.'
. ' Wird der Gutschein auch als PDF-Datei generiert, wird die PDF-Datei an diese E-Mail angehanden.', . ' Wird der Gutschein auch als PDF-Datei generiert, wird die PDF-Datei an diese E-Mail angehanden.',
...@@ -485,17 +487,17 @@ protected static function createProductFields() ...@@ -485,17 +487,17 @@ protected static function createProductFields()
. ' choose between email and mail delivery type and chooses delivery by mail.' . ' choose between email and mail delivery type and chooses delivery by mail.'
. ' If the coupon is also generated as a PDF file, the file is attached to this email.' . ' If the coupon is also generated as a PDF file, the file is attached to this email.'
], ],
'type' => Fields::TYPE_BOOL, 'type' => Fields::TYPE_BOOL,
'public' => false, 'public' => false,
'standard' => false, 'standard' => false,
'requiredField' => false 'requiredField' => false
], ],
CouponProductsHandler::PRODUCT_FIELD_ID_GENERATE_PDF => [ CouponProductsHandler::PRODUCT_FIELD_ID_GENERATE_PDF => [
'title' => [ 'title' => [
'de' => 'Gutschein-Code als PDF bereitstellen', 'de' => 'Gutschein-Code als PDF bereitstellen',
'en' => 'Provide coupon code as PDF' 'en' => 'Provide coupon code as PDF'
], ],
'description' => [ 'description' => [
'de' => 'Der Gutschein wird auch als PDF-Datei erstellt und dem Käufer (je nach Wahl) per E-Mail gesendet.' 'de' => 'Der Gutschein wird auch als PDF-Datei erstellt und dem Käufer (je nach Wahl) per E-Mail gesendet.'
. ' Zusätzlich wird die PDF-Datei dem Käufer in seinem Frontend-Profil (sofern eingerichtet)' . ' Zusätzlich wird die PDF-Datei dem Käufer in seinem Frontend-Profil (sofern eingerichtet)'
. ' bereitgestellt.', . ' bereitgestellt.',
...@@ -503,51 +505,51 @@ protected static function createProductFields() ...@@ -503,51 +505,51 @@ protected static function createProductFields()
. ' via email. Additionally, the PDF file is made available via the customers frontend profile' . ' via email. Additionally, the PDF file is made available via the customers frontend profile'
. ' (if set up).' . ' (if set up).'
], ],
'type' => Fields::TYPE_BOOL, 'type' => Fields::TYPE_BOOL,
'public' => false, 'public' => false,
'standard' => false, 'standard' => false,
'requiredField' => false 'requiredField' => false
], ],
CouponProductsHandler::PRODUCT_FIELD_ID_COUPON_AMOUNT => [ CouponProductsHandler::PRODUCT_FIELD_ID_COUPON_AMOUNT => [
'title' => [ 'title' => [
'de' => 'Gutschein Wert', 'de' => 'Gutschein Wert',
'en' => 'Coupon amount' 'en' => 'Coupon amount'
], ],
'type' => Fields::TYPE_FLOAT, 'type' => Fields::TYPE_FLOAT,
'public' => false, 'public' => false,
'standard' => false, 'standard' => false,
'requiredField' => true 'requiredField' => true
], ],
CouponProductsHandler::PRODUCT_FIELD_ID_DAYS_VALID => [ CouponProductsHandler::PRODUCT_FIELD_ID_DAYS_VALID => [
'title' => [ 'title' => [
'de' => 'Gutschein-Code Gültigkeit (Tage)', 'de' => 'Gutschein-Code Gültigkeit (Tage)',
'en' => 'Coupon code validity (days)' 'en' => 'Coupon code validity (days)'
], ],
'type' => Fields::TYPE_INT, 'type' => Fields::TYPE_INT,
'public' => false, 'public' => false,
'standard' => false, 'standard' => false,
'requiredField' => true 'requiredField' => true
], ],
CouponProductsHandler::PRODUCT_FIELD_ID_COUPON_DESCRIPTION => [ CouponProductsHandler::PRODUCT_FIELD_ID_COUPON_DESCRIPTION => [
'title' => [ 'title' => [
'de' => 'Gutschein-Beschreibung', 'de' => 'Gutschein-Beschreibung',
'en' => 'Coupon description' 'en' => 'Coupon description'
], ],
'description' => [ 'description' => [
'de' => 'Diese Beschreibung taucht unter dem Titel "GUTSCHEIN" auf der generierten PDF-Datei auf.', 'de' => 'Diese Beschreibung taucht unter dem Titel "GUTSCHEIN" auf der generierten PDF-Datei auf.',
'en' => 'This description appears under the title caption "COUPON" on the generated PDF file.' 'en' => 'This description appears under the title caption "COUPON" on the generated PDF file.'
], ],
'type' => Fields::TYPE_INPUT_MULTI_LANG, 'type' => Fields::TYPE_INPUT_MULTI_LANG,
'public' => false, 'public' => false,
'standard' => false, 'standard' => false,
'requiredField' => false 'requiredField' => false
], ],
CouponProductsHandler::PRODUCT_FIELD_ID_IS_SINGLE_PURPOSE_COUPON => [ CouponProductsHandler::PRODUCT_FIELD_ID_IS_SINGLE_PURPOSE_COUPON => [
'title' => [ 'title' => [
'de' => 'Ist Einzweck-Gutschein (Besteuerung bei Gutschein-Kauf)', 'de' => 'Ist Einzweck-Gutschein (Besteuerung bei Gutschein-Kauf)',
'en' => 'Is single purpose coupon (taxation on voucher purchase)' 'en' => 'Is single purpose coupon (taxation on voucher purchase)'
], ],
'description' => [ 'description' => [
'de' => 'Einzweck-Gutscheine sind solche, bei denen die Besteuerung und der Leistungsort bereits' 'de' => 'Einzweck-Gutscheine sind solche, bei denen die Besteuerung und der Leistungsort bereits'
. ' beim Gutschein-Kauf feststehen. Beispiel: Gutschein für eine Massage in einem Spa.' . ' beim Gutschein-Kauf feststehen. Beispiel: Gutschein für eine Massage in einem Spa.'
. ' Alles andere (wie z.B. Wertgutscheine für den Einsatz unabhängig vom Artikel) sind' . ' Alles andere (wie z.B. Wertgutscheine für den Einsatz unabhängig vom Artikel) sind'
...@@ -557,59 +559,59 @@ protected static function createProductFields() ...@@ -557,59 +559,59 @@ protected static function createProductFields()
. ' Everything else (such as money value coupons for use regardless of the item) are' . ' Everything else (such as money value coupons for use regardless of the item) are'
. ' multi-purpose coupons and are not taxed at the time of purchase.' . ' multi-purpose coupons and are not taxed at the time of purchase.'
], ],
'type' => Fields::TYPE_BOOL, 'type' => Fields::TYPE_BOOL,
'public' => false, 'public' => false,
'standard' => false, 'standard' => false,
'requiredField' => false 'requiredField' => false
], ],
CouponProductsHandler::PRODUCT_FIELD_ID_USER_DELIVERY_TYPE_SELECT => [ CouponProductsHandler::PRODUCT_FIELD_ID_USER_DELIVERY_TYPE_SELECT => [
'title' => [ 'title' => [
'de' => 'Gutschein - Versand', 'de' => 'Gutschein - Versand',
'en' => 'Coupon delivery' 'en' => 'Coupon delivery'
], ],
'type' => Fields::TYPE_ATTRIBUTE_LIST, 'type' => Fields::TYPE_ATTRIBUTE_LIST,
'public' => true, 'public' => true,
'standard' => false, 'standard' => false,
'requiredField' => true, 'requiredField' => true,
'options' => [ 'options' => [
'entries' => [ 'entries' => [
[ [
'title' => [ 'title' => [
'de' => 'per E - Mail', 'de' => 'per E - Mail',
'en' => 'via email' 'en' => 'via email'
], ],
'sum' => 0, 'sum' => 0,
'type' => ErpCalc::CALCULATION_COMPLEMENT, 'type' => ErpCalc::CALCULATION_COMPLEMENT,
'selected' => true, 'selected' => true,
'userinput' => false 'userinput' => false
], ],
[ [
'title' => [ 'title' => [
'de' => 'per Post', 'de' => 'per Post',
'en' => 'via mail' 'en' => 'via mail'
], ],
'sum' => 0, 'sum' => 0,
'type' => ErpCalc::CALCULATION_COMPLEMENT, 'type' => ErpCalc::CALCULATION_COMPLEMENT,
'selected' => false, 'selected' => false,
'userinput' => false 'userinput' => false
] ]
] ]
] ]
], ],
CouponProductsHandler::PRODUCT_FIELD_ID_USER_DELIVERY_TYPE_SELECT_ALLOW => [ CouponProductsHandler::PRODUCT_FIELD_ID_USER_DELIVERY_TYPE_SELECT_ALLOW => [
'title' => [ 'title' => [
'de' => 'Kunde darf Gutschein - Versandart wählen', 'de' => 'Kunde darf Gutschein - Versandart wählen',
'en' => 'Customer can choose coupon delivery type' 'en' => 'Customer can choose coupon delivery type'
], ],
'description' => [ 'description' => [
'de' => 'Ist diese Funktion aktiviert, kann der Kunde beim Artikel im Shop wählen, ob der Gutschein' 'de' => 'Ist diese Funktion aktiviert, kann der Kunde beim Artikel im Shop wählen, ob der Gutschein'
. ' per E - Mail oder Post versandt werden soll.', . ' per E - Mail oder Post versandt werden soll.',
'en' => 'if this option is enabled, the customer can choose at the article in the store whether the' 'en' => 'if this option is enabled, the customer can choose at the article in the store whether the'
. ' coupon should be sent by e - mail or by(physical) mail.' . ' coupon should be sent by e - mail or by(physical) mail.'
], ],
'type' => Fields::TYPE_BOOL, 'type' => Fields::TYPE_BOOL,
'public' => false, 'public' => false,
'standard' => false, 'standard' => false,
'requiredField' => false 'requiredField' => false
] ]
]; ];
...@@ -626,15 +628,15 @@ protected static function createProductFields() ...@@ -626,15 +628,15 @@ protected static function createProductFields()
try { try {
Fields::createField([ Fields::createField([
'id' => $fieldId, 'id' => $fieldId,
'type' => $field['type'], 'type' => $field['type'],
'titles' => $field['title'], 'titles' => $field['title'],
'workingtitles' => $field['title'], 'workingtitles' => $field['title'],
'description' => !empty($field['description']) ? $field['description'] : null, 'description' => !empty($field['description']) ? $field['description'] : null,
'systemField' => 0, 'systemField' => 0,
'standardField' => !empty($field['standard']) ? 1 : 0, 'standardField' => !empty($field['standard']) ? 1 : 0,
'publicField' => !empty($field['public']) ? 1 : 0, 'publicField' => !empty($field['public']) ? 1 : 0,
'options' => !empty($field['options']) ? $field['options'] : null, 'options' => !empty($field['options']) ? $field['options'] : null,
'requiredField' => !empty($field['requiredField']) ? 1 : 0 'requiredField' => !empty($field['requiredField']) ? 1 : 0
]); ]);
} catch (Exception $Exception) { } catch (Exception $Exception) {
...@@ -664,23 +666,23 @@ public static function onQuiqqerProductsProductCreate(ProductInterface $Product) ...@@ -664,23 +666,23 @@ public static function onQuiqqerProductsProductCreate(ProductInterface $Product)
return; return;
} }
$isDigital = $Product instanceof DigitalCouponProductType; $isDigital = $Product instanceof DigitalCouponProductType;
$UniqueProduct = $Product->createUniqueProduct(); $UniqueProduct = $Product->createUniqueProduct();
$UniqueProduct->calc(); $UniqueProduct->calc();
$fields = [ $fields = [
// CouponProductsHandler::PRODUCT_FIELD_ID_TRANSFERABLE => true, // CouponProductsHandler::PRODUCT_FIELD_ID_TRANSFERABLE => true,
CouponProductsHandler::PRODUCT_FIELD_ID_COUPON_AMOUNT => $UniqueProduct->getPrice()->getValue(), CouponProductsHandler::PRODUCT_FIELD_ID_COUPON_AMOUNT => $UniqueProduct->getPrice()->getValue(),
CouponProductsHandler::PRODUCT_FIELD_ID_DAYS_VALID => 1095, // 3 years CouponProductsHandler::PRODUCT_FIELD_ID_DAYS_VALID => 1095, // 3 years
CouponProductsHandler::PRODUCT_FIELD_ID_IS_SINGLE_PURPOSE_COUPON => false CouponProductsHandler::PRODUCT_FIELD_ID_IS_SINGLE_PURPOSE_COUPON => false
]; ];
// Digital coupons get some extra fields // Digital coupons get some extra fields
if ($isDigital) { if ($isDigital) {
$fields[CouponProductsHandler::PRODUCT_FIELD_ID_SEND_MAIL] = true; $fields[CouponProductsHandler::PRODUCT_FIELD_ID_SEND_MAIL] = true;
$fields[CouponProductsHandler::PRODUCT_FIELD_ID_GENERATE_PDF] = true; $fields[CouponProductsHandler::PRODUCT_FIELD_ID_GENERATE_PDF] = true;
$fields[CouponProductsHandler::PRODUCT_FIELD_ID_USER_DELIVERY_TYPE_SELECT] = false; $fields[CouponProductsHandler::PRODUCT_FIELD_ID_USER_DELIVERY_TYPE_SELECT] = false;
$fields[CouponProductsHandler::PRODUCT_FIELD_ID_COUPON_DESCRIPTION] = null; $fields[CouponProductsHandler::PRODUCT_FIELD_ID_COUPON_DESCRIPTION] = null;
} }
foreach ($fields as $fieldId => $value) { foreach ($fields as $fieldId => $value) {
...@@ -733,7 +735,7 @@ public static function onQuiqqerProductsProductActivate(ProductInterface $Produc ...@@ -733,7 +735,7 @@ public static function onQuiqqerProductsProductActivate(ProductInterface $Produc
} }
$productTaxTypeId = (int)$Product->getFieldValue(Fields::FIELD_VAT); $productTaxTypeId = (int)$Product->getFieldValue(Fields::FIELD_VAT);
$noVatTaxTypes = QUI\ERP\Coupons\Products\Handler::getNoVatTaxTypes(); $noVatTaxTypes = QUI\ERP\Coupons\Products\Handler::getNoVatTaxTypes();
foreach ($noVatTaxTypes as $TaxType) { foreach ($noVatTaxTypes as $TaxType) {
if ($TaxType->getId() === $productTaxTypeId) { if ($TaxType->getId() === $productTaxTypeId) {
...@@ -746,7 +748,7 @@ public static function onQuiqqerProductsProductActivate(ProductInterface $Produc ...@@ -746,7 +748,7 @@ public static function onQuiqqerProductsProductActivate(ProductInterface $Produc
'exception.CouponProduct.no_vat_tax_type_required', 'exception.CouponProduct.no_vat_tax_type_required',
[ [
'productTitle' => $Product->getTitle(), 'productTitle' => $Product->getTitle(),
'productId' => $Product->getId() 'productId' => $Product->getId()
] ]
]); ]);
} }
......
...@@ -2,10 +2,21 @@ ...@@ -2,10 +2,21 @@
namespace QUI\ERP\Coupons; namespace QUI\ERP\Coupons;
use DateInterval;
use DateTime;
use Exception;
use PDO;
use QUI; use QUI;
use QUI\ERP\Discount\Handler as DiscountHandler;
use QUI\Utils\Grid; use QUI\Utils\Grid;
use QUI\Utils\Security\Orthos; use QUI\Utils\Security\Orthos;
use QUI\ERP\Discount\Handler as DiscountHandler;
use function current;
use function explode;
use function implode;
use function is_null;
use function json_encode;
use function preg_replace;
/** /**
* Class Handler * Class Handler
...@@ -34,7 +45,7 @@ class Handler ...@@ -34,7 +45,7 @@ class Handler
* *
* @var CouponCode[] * @var CouponCode[]
*/ */
protected static $couponCodes = []; protected static array $couponCodes = [];
/** /**
* Get CouponCode * Get CouponCode
...@@ -43,7 +54,7 @@ class Handler ...@@ -43,7 +54,7 @@ class Handler
* @return CouponCode * @return CouponCode
* @throws CouponCodeException * @throws CouponCodeException
*/ */
public static function getCouponCode($id) public static function getCouponCode(int $id): CouponCode
{ {
if (isset(self::$couponCodes[$id])) { if (isset(self::$couponCodes[$id])) {
return self::$couponCodes[$id]; return self::$couponCodes[$id];
...@@ -61,18 +72,19 @@ public static function getCouponCode($id) ...@@ -61,18 +72,19 @@ public static function getCouponCode($id)
* @return CouponCode * @return CouponCode
* *
* @throws CouponCodeException * @throws CouponCodeException
* @throws QUI\Database\Exception
*/ */
public static function getCouponCodeByCode($code) public static function getCouponCodeByCode(string $code): CouponCode
{ {
$result = QUI::getDataBase()->fetch([ $result = QUI::getDataBase()->fetch([
'select' => [ 'select' => [
'id' 'id'
], ],
'from' => self::getTable(), 'from' => self::getTable(),
'where' => [ 'where' => [
'code' => $code 'code' => $code
], ],
'limit' => 1 'limit' => 1
]); ]);
if (empty($result)) { if (empty($result)) {
...@@ -95,9 +107,9 @@ public static function getCouponCodeByCode($code) ...@@ -95,9 +107,9 @@ public static function getCouponCodeByCode($code)
* @param array $settings (optional) - If omitted a random default CouponCode is generated * @param array $settings (optional) - If omitted a random default CouponCode is generated
* @return CouponCode * @return CouponCode
* *
* @throws \Exception * @throws Exception
*/ */
public static function createCouponCode($discountIds, $settings = []) public static function createCouponCode(array $discountIds, array $settings = []): CouponCode
{ {
$DiscountHandler = DiscountHandler::getInstance(); $DiscountHandler = DiscountHandler::getInstance();
...@@ -112,19 +124,19 @@ public static function createCouponCode($discountIds, $settings = []) ...@@ -112,19 +124,19 @@ public static function createCouponCode($discountIds, $settings = [])
foreach ($discountIds as $discountId) { foreach ($discountIds as $discountId) {
try { try {
$DiscountHandler->getChild($discountId); $DiscountHandler->getChild($discountId);
} catch (\Exception $Exception) { } catch (Exception $Exception) {
throw new CouponCodeException([ throw new CouponCodeException([
'quiqqer/coupons', 'quiqqer/coupons',
'exception.Handler.discount_error', 'exception.Handler.discount_error',
[ [
'discountId' => $discountId, 'discountId' => $discountId,
'error' => $Exception->getMessage() 'error' => $Exception->getMessage()
] ]
]); ]);
} }
} }
$Now = new \DateTime(); $Now = new DateTime();
if (!empty($settings['code'])) { if (!empty($settings['code'])) {
if (self::existsCode($settings['code'])) { if (self::existsCode($settings['code'])) {
...@@ -149,24 +161,24 @@ public static function createCouponCode($discountIds, $settings = []) ...@@ -149,24 +161,24 @@ public static function createCouponCode($discountIds, $settings = [])
} }
$couponCode = [ $couponCode = [
'title' => empty($settings['title']) ? null : $settings['title'], 'title' => empty($settings['title']) ? null : $settings['title'],
'createDate' => $Now->format('Y-m-d H:i:s'), 'createDate' => $Now->format('Y-m-d H:i:s'),
'code' => $code, 'code' => $code,
'maxUsages' => $maxUsages, 'maxUsages' => $maxUsages,
'discountIds' => \json_encode($discountIds) 'discountIds' => json_encode($discountIds)
]; ];
if (!empty($settings['validUntilDate'])) { if (!empty($settings['validUntilDate'])) {
$ValidUntil = new \DateTime($settings['validUntilDate']); $ValidUntil = new DateTime($settings['validUntilDate']);
$couponCode['validUntilDate'] = $ValidUntil->format('Y-m-d H:i:s'); $couponCode['validUntilDate'] = $ValidUntil->format('Y-m-d H:i:s');
} }
if (!empty($settings['userIds'])) { if (!empty($settings['userIds'])) {
$couponCode['userIds'] = \json_encode(\explode(",", $settings['userIds'])); $couponCode['userIds'] = json_encode(explode(",", $settings['userIds']));
} }
if (!empty($settings['groupIds'])) { if (!empty($settings['groupIds'])) {
$couponCode['groupIds'] = \json_encode(\explode(",", $settings['groupIds'])); $couponCode['groupIds'] = json_encode(explode(",", $settings['groupIds']));
} }
QUI::getDataBase()->insert( QUI::getDataBase()->insert(
...@@ -185,9 +197,9 @@ public static function createCouponCode($discountIds, $settings = []) ...@@ -185,9 +197,9 @@ public static function createCouponCode($discountIds, $settings = [])
* @param array $settings (optional) - If omitted a random default CouponCode is generated * @param array $settings (optional) - If omitted a random default CouponCode is generated
* @return CouponCode * @return CouponCode
* *
* @throws \Exception * @throws Exception
*/ */
public static function editCouponCode($id, $discountIds, $settings = []) public static function editCouponCode(int $id, array $discountIds, array $settings = []): CouponCode
{ {
QUI\Permissions\Permission::checkPermission(self::PERMISSION_EDIT); QUI\Permissions\Permission::checkPermission(self::PERMISSION_EDIT);
...@@ -208,23 +220,25 @@ public static function editCouponCode($id, $discountIds, $settings = []) ...@@ -208,23 +220,25 @@ public static function editCouponCode($id, $discountIds, $settings = [])
foreach ($discountIds as $discountId) { foreach ($discountIds as $discountId) {
try { try {
$DiscountHandler->getChild($discountId); $DiscountHandler->getChild($discountId);
} catch (\Exception $Exception) { } catch (Exception $Exception) {
throw new CouponCodeException([ throw new CouponCodeException([
'quiqqer/coupons', 'quiqqer/coupons',
'exception.Handler.discount_error', 'exception.Handler.discount_error',
[ [
'discountId' => $discountId, 'discountId' => $discountId,
'error' => $Exception->getMessage() 'error' => $Exception->getMessage()
] ]
]); ]);
} }
} }
$Now = new \DateTime(); $Now = new DateTime();
if (!empty($settings['code'])) { if (!empty($settings['code'])) {
if ($CouponCode->getCode() !== $settings['code'] if (
&& self::existsCode($settings['code'])) { $CouponCode->getCode() !== $settings['code']
&& self::existsCode($settings['code'])
) {
throw new CouponCodeException([ throw new CouponCodeException([
'quiqqer/coupons', 'quiqqer/coupons',
'exception.Handler.code_already_exists', 'exception.Handler.code_already_exists',
...@@ -246,28 +260,28 @@ public static function editCouponCode($id, $discountIds, $settings = []) ...@@ -246,28 +260,28 @@ public static function editCouponCode($id, $discountIds, $settings = [])
} }
$couponCode = [ $couponCode = [
'title' => empty($settings['title']) ? null : $settings['title'], 'title' => empty($settings['title']) ? null : $settings['title'],
'createDate' => $Now->format('Y-m-d H:i:s'), 'createDate' => $Now->format('Y-m-d H:i:s'),
'code' => $code, 'code' => $code,
'maxUsages' => $maxUsages, 'maxUsages' => $maxUsages,
'discountIds' => \json_encode($discountIds) 'discountIds' => json_encode($discountIds)
]; ];
if (!empty($settings['validUntilDate'])) { if (!empty($settings['validUntilDate'])) {
$ValidUntil = new \DateTime($settings['validUntilDate']); $ValidUntil = new DateTime($settings['validUntilDate']);
$couponCode['validUntilDate'] = $ValidUntil->format('Y-m-d H:i:s'); $couponCode['validUntilDate'] = $ValidUntil->format('Y-m-d H:i:s');
} else { } else {
$couponCode['validUntilDate'] = null; $couponCode['validUntilDate'] = null;
} }
if (!empty($settings['userIds'])) { if (!empty($settings['userIds'])) {
$couponCode['userIds'] = \json_encode(\explode(",", $settings['userIds'])); $couponCode['userIds'] = json_encode(explode(",", $settings['userIds']));
} else { } else {
$couponCode['userIds'] = null; $couponCode['userIds'] = null;
} }
if (!empty($settings['groupIds'])) { if (!empty($settings['groupIds'])) {
$couponCode['groupIds'] = \json_encode(\explode(",", $settings['groupIds'])); $couponCode['groupIds'] = json_encode(explode(",", $settings['groupIds']));
} else { } else {
$couponCode['groupIds'] = null; $couponCode['groupIds'] = null;
} }
...@@ -289,11 +303,11 @@ public static function editCouponCode($id, $discountIds, $settings = []) ...@@ -289,11 +303,11 @@ public static function editCouponCode($id, $discountIds, $settings = [])
* @return CouponCode[]|int * @return CouponCode[]|int
* @throws CouponCodeException * @throws CouponCodeException
*/ */
public static function search($searchParams, $countOnly = false) public static function search(array $searchParams, bool $countOnly = false)
{ {
$couponCodes = []; $couponCodes = [];
$Grid = new Grid($searchParams); $Grid = new Grid($searchParams);
$gridParams = $Grid->parseDBParams($searchParams); $gridParams = $Grid->parseDBParams($searchParams);
$binds = []; $binds = [];
$where = []; $where = [];
...@@ -304,7 +318,7 @@ public static function search($searchParams, $countOnly = false) ...@@ -304,7 +318,7 @@ public static function search($searchParams, $countOnly = false)
$sql = "SELECT id"; $sql = "SELECT id";
} }
$sql .= " FROM `".self::getTable()."`"; $sql .= " FROM `" . self::getTable() . "`";
if (!empty($searchParams['search'])) { if (!empty($searchParams['search'])) {
$searchColumns = [ $searchColumns = [
...@@ -316,49 +330,46 @@ public static function search($searchParams, $countOnly = false) ...@@ -316,49 +330,46 @@ public static function search($searchParams, $countOnly = false)
$whereOr = []; $whereOr = [];
foreach ($searchColumns as $searchColumn) { foreach ($searchColumns as $searchColumn) {
$whereOr[] = '`'.$searchColumn.'` LIKE :search'; $whereOr[] = '`' . $searchColumn . '` LIKE :search';
} }
if (!empty($whereOr)) { if (!empty($whereOr)) {
$where[] = '('.\implode(' OR ', $whereOr).')'; $where[] = '(' . implode(' OR ', $whereOr) . ')';
$binds['search'] = [ $binds['search'] = [
'value' => '%'.$searchParams['search'].'%', 'value' => '%' . $searchParams['search'] . '%',
'type' => \PDO::PARAM_STR 'type' => PDO::PARAM_STR
]; ];
} }
} }
// build WHERE query string // build WHERE query string
if (!empty($where)) { if (!empty($where)) {
$sql .= " WHERE ".\implode(" AND ", $where); $sql .= " WHERE " . implode(" AND ", $where);
} }
// ORDER // ORDER
if (!empty($searchParams['sortOn']) if (!empty($searchParams['sortOn'])) {
) {
$sortOn = Orthos::clear($searchParams['sortOn']); $sortOn = Orthos::clear($searchParams['sortOn']);
$order = "ORDER BY ".$sortOn; $order = "ORDER BY " . $sortOn;
if (isset($searchParams['sortBy']) && if (!empty($searchParams['sortBy'])) {
!empty($searchParams['sortBy']) $order .= " " . Orthos::clear($searchParams['sortBy']);
) {
$order .= " ".Orthos::clear($searchParams['sortBy']);
} else { } else {
$order .= " ASC"; $order .= " ASC";
} }
$sql .= " ".$order; $sql .= " " . $order;
} else { } else {
$sql .= " ORDER BY id DESC"; $sql .= " ORDER BY id DESC";
} }
// LIMIT // LIMIT
if (!empty($gridParams['limit']) && !$countOnly) { if (!empty($gridParams['limit']) && !$countOnly) {
$sql .= " LIMIT ".$gridParams['limit']; $sql .= " LIMIT " . $gridParams['limit'];
} else { } else {
if (!$countOnly) { if (!$countOnly) {
$sql .= " LIMIT ".(int)20; $sql .= " LIMIT " . 20;
} }
} }
...@@ -366,22 +377,22 @@ public static function search($searchParams, $countOnly = false) ...@@ -366,22 +377,22 @@ public static function search($searchParams, $countOnly = false)
// bind search values // bind search values
foreach ($binds as $var => $bind) { foreach ($binds as $var => $bind) {
$Stmt->bindValue(':'.$var, $bind['value'], $bind['type']); $Stmt->bindValue(':' . $var, $bind['value'], $bind['type']);
} }
try { try {
$Stmt->execute(); $Stmt->execute();
$result = $Stmt->fetchAll(\PDO::FETCH_ASSOC); $result = $Stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (\Exception $Exception) { } catch (Exception $Exception) {
QUI\System\Log::addError( QUI\System\Log::addError(
self::class.' :: search() -> '.$Exception->getMessage() self::class . ' :: search() -> ' . $Exception->getMessage()
); );
return []; return [];
} }
if ($countOnly) { if ($countOnly) {
return (int)\current(\current($result)); return (int)current(current($result));
} }
foreach ($result as $row) { foreach ($result as $row) {
...@@ -392,20 +403,22 @@ public static function search($searchParams, $countOnly = false) ...@@ -392,20 +403,22 @@ public static function search($searchParams, $countOnly = false)
} }
/** /**
* Check if an invite code already eixsts * Check if a CouponCode exists by its code
* *
* @param string $code * @param string $code The code of the CouponCode
* @return bool * @return bool Returns true if the CouponCode exists, false otherwise
*
* @throws QUI\Database\Exception
*/ */
public static function existsCode($code) public static function existsCode(string $code): bool
{ {
$result = QUI::getDataBase()->fetch([ $result = QUI::getDataBase()->fetch([
'select' => 'id', 'select' => 'id',
'from' => self::getTable(), 'from' => self::getTable(),
'where' => [ 'where' => [
'code' => $code 'code' => $code
], ],
'limit' => 1 'limit' => 1
]); ]);
return !empty($result); return !empty($result);
...@@ -419,7 +432,7 @@ public static function existsCode($code) ...@@ -419,7 +432,7 @@ public static function existsCode($code)
public static function getRegistrationSite() public static function getRegistrationSite()
{ {
try { try {
$Conf = QUI::getPackage('quiqqer/coupons')->getConfig(); $Conf = QUI::getPackage('quiqqer/coupons')->getConfig();
$regSite = $Conf->get('settings', 'registrationSite'); $regSite = $Conf->get('settings', 'registrationSite');
} catch (QUI\Exception $Exception) { } catch (QUI\Exception $Exception) {
QUI\System\Log::writeDebugException($Exception); QUI\System\Log::writeDebugException($Exception);
...@@ -433,7 +446,7 @@ public static function getRegistrationSite() ...@@ -433,7 +446,7 @@ public static function getRegistrationSite()
try { try {
return QUI\Projects\Site\Utils::getSiteByLink($regSite); return QUI\Projects\Site\Utils::getSiteByLink($regSite);
} catch (\Exception $Exception) { } catch (Exception $Exception) {
return false; return false;
} }
} }
...@@ -441,28 +454,27 @@ public static function getRegistrationSite() ...@@ -441,28 +454,27 @@ public static function getRegistrationSite()
/** /**
* Deletes all CouponCodes that are expired * Deletes all CouponCodes that are expired
* *
* @param int $days (optional) - Delete expired Codes that are older than X days [default: delete all] * @param int|null $days (optional) - Delete expired Codes that are older than X days [default: delete all]
* @return void * @return void
* *
* @throws \Exception * @throws Exception
*/ */
public static function deleteExpiredCouponCodes($days = null) public static function deleteExpiredCouponCodes(int $days = null)
{ {
$Now = new \DateTime(); $Now = new DateTime();
$where = [ $where = [
'validUntilDate' => [ 'validUntilDate' => [
'type' => '<=', 'type' => '<=',
'value' => $Now->format('Y-m-d H:i:s') 'value' => $Now->format('Y-m-d H:i:s')
] ]
]; ];
if (!\is_null($days)) { if (!is_null($days)) {
$days = (int)$days; $OldDate = new DateTime();
$OldDate = new \DateTime(); $OldDate->sub(new DateInterval('P' . $days . 'D'));
$OldDate->sub(new \DateInterval('P'.$days.'D'));
$where['validUntilDate'] = [ $where['validUntilDate'] = [
'type' => '<=', 'type' => '<=',
'value' => $OldDate->format('Y-m-d H:i:s') 'value' => $OldDate->format('Y-m-d H:i:s')
]; ];
} }
...@@ -476,27 +488,26 @@ public static function deleteExpiredCouponCodes($days = null) ...@@ -476,27 +488,26 @@ public static function deleteExpiredCouponCodes($days = null)
/** /**
* Deletes all CouponCodes that have been redeemed * Deletes all CouponCodes that have been redeemed
* *
* @param int $days (optional) - Delete redeemed Codes that are older than X days [default: delete all] * @param int|null $days (optional) - Delete redeemed Codes that are older than X days [default: delete all]
* @return void * @return void
* *
* @throws \Exception * @throws Exception
*/ */
public static function deleteRedeemedCouponCodes($days = null) public static function deleteRedeemedCouponCodes(int $days = null)
{ {
$where = [ $where = [
'useDate' => [ 'useDate' => [
'type' => 'NOT', 'type' => 'NOT',
'value' => null 'value' => null
] ]
]; ];
if (!\is_null($days)) { if (!is_null($days)) {
$days = (int)$days; $OldDate = new DateTime();
$OldDate = new \DateTime(); $OldDate->sub(new DateInterval('P' . $days . 'D'));
$OldDate->sub(new \DateInterval('P'.$days.'D'));
$where['useDate'] = [ $where['useDate'] = [
'type' => '<=', 'type' => '<=',
'value' => $OldDate->format('Y-m-d H:i:s') 'value' => $OldDate->format('Y-m-d H:i:s')
]; ];
} }
...@@ -513,9 +524,9 @@ public static function deleteRedeemedCouponCodes($days = null) ...@@ -513,9 +524,9 @@ public static function deleteRedeemedCouponCodes($days = null)
* @param string $code * @param string $code
* @return string * @return string
*/ */
public static function sanitizeCode($code) public static function sanitizeCode(string $code): string
{ {
return \preg_replace('#[^A-Za-z0-9\.\-_\*&$% ]#i', '', $code); return preg_replace('#[^A-Za-z0-9\.\-_\*&$% ]#i', '', $code);
} }
/** /**
...@@ -523,7 +534,7 @@ public static function sanitizeCode($code) ...@@ -523,7 +534,7 @@ public static function sanitizeCode($code)
* *
* @return string * @return string
*/ */
public static function getTable() public static function getTable(): string
{ {
return QUI::getDBTableName('quiqqer_coupons'); return QUI::getDBTableName('quiqqer_coupons');
} }
......
...@@ -52,7 +52,7 @@ public function __construct($pid, $product = []) ...@@ -52,7 +52,7 @@ public function __construct($pid, $product = [])
* @param QUI\Locale $Locale * @param QUI\Locale $Locale
* @return string * @return string
*/ */
public static function getTypeTitle($Locale = null) public static function getTypeTitle($Locale = null): string
{ {
if ($Locale === null) { if ($Locale === null) {
$Locale = QUI::getLocale(); $Locale = QUI::getLocale();
...@@ -65,7 +65,7 @@ public static function getTypeTitle($Locale = null) ...@@ -65,7 +65,7 @@ public static function getTypeTitle($Locale = null)
* @param QUI\Locale $Locale * @param QUI\Locale $Locale
* @return string * @return string
*/ */
public static function getTypeDescription($Locale = null) public static function getTypeDescription($Locale = null): string
{ {
if ($Locale === null) { if ($Locale === null) {
$Locale = QUI::getLocale(); $Locale = QUI::getLocale();
......
...@@ -3,14 +3,14 @@ ...@@ -3,14 +3,14 @@
namespace QUI\ERP\Coupons\Products; namespace QUI\ERP\Coupons\Products;
use QUI; use QUI;
use QUI\ERP\Products\Product\Product; use QUI\ERP\Coupons\CouponCode;
use QUI\ERP\Coupons\Handler as CouponsHandler;
use QUI\ERP\Customer\CustomerFiles;
use QUI\ERP\Discount\Discount; use QUI\ERP\Discount\Discount;
use QUI\ERP\Discount\Handler as DiscountHandler; use QUI\ERP\Discount\Handler as DiscountHandler;
use QUI\ERP\Coupons\Handler as CouponsHandler;
use QUI\ERP\Coupons\CouponCode;
use QUI\ERP\Products\Handler\Products as ProductsHandler; use QUI\ERP\Products\Handler\Products as ProductsHandler;
use QUI\ERP\Products\Product\Product;
use QUI\HtmlToPdf\Document; use QUI\HtmlToPdf\Document;
use QUI\ERP\Customer\CustomerFiles;
/** /**
* Class Handler * Class Handler
...@@ -22,14 +22,14 @@ class Handler ...@@ -22,14 +22,14 @@ class Handler
/** /**
* Special fields for coupon products * Special fields for coupon products
*/ */
const PRODUCT_FIELD_ID_TRANSFERABLE = 670; const PRODUCT_FIELD_ID_TRANSFERABLE = 670;
const PRODUCT_FIELD_ID_GENERATE_PDF = 671; const PRODUCT_FIELD_ID_GENERATE_PDF = 671;
const PRODUCT_FIELD_ID_COUPON_AMOUNT = 672; const PRODUCT_FIELD_ID_COUPON_AMOUNT = 672;
const PRODUCT_FIELD_ID_DAYS_VALID = 673; const PRODUCT_FIELD_ID_DAYS_VALID = 673;
const PRODUCT_FIELD_ID_COUPON_DESCRIPTION = 674; const PRODUCT_FIELD_ID_COUPON_DESCRIPTION = 674;
const PRODUCT_FIELD_ID_IS_SINGLE_PURPOSE_COUPON = 675; const PRODUCT_FIELD_ID_IS_SINGLE_PURPOSE_COUPON = 675;
const PRODUCT_FIELD_ID_SEND_MAIL = 676; const PRODUCT_FIELD_ID_SEND_MAIL = 676;
const PRODUCT_FIELD_ID_USER_DELIVERY_TYPE_SELECT = 678; const PRODUCT_FIELD_ID_USER_DELIVERY_TYPE_SELECT = 678;
const PRODUCT_FIELD_ID_USER_DELIVERY_TYPE_SELECT_ALLOW = 679; const PRODUCT_FIELD_ID_USER_DELIVERY_TYPE_SELECT_ALLOW = 679;
/** /**
...@@ -56,12 +56,14 @@ public static function createCouponCodesFromOrder(QUI\ERP\Order\AbstractOrder $O ...@@ -56,12 +56,14 @@ public static function createCouponCodesFromOrder(QUI\ERP\Order\AbstractOrder $O
$Product = ProductsHandler::getProduct($Article->getId()); $Product = ProductsHandler::getProduct($Article->getId());
// Only parse coupon products // Only parse coupon products
if (!($Product instanceof DigitalCouponProductType) && if (
!($Product instanceof PhysicalCouponProductType)) { !($Product instanceof DigitalCouponProductType) &&
!($Product instanceof PhysicalCouponProductType)
) {
continue; continue;
} }
$CouponCode = self::createCouponCodeFromProduct($Product, $Order, $Customer); $CouponCode = self::createCouponCodeFromProduct($Product, $Order, $Customer);
$couponFilePathCustomerDir = null; $couponFilePathCustomerDir = null;
$Order->addHistory( $Order->addHistory(
...@@ -69,9 +71,9 @@ public static function createCouponCodesFromOrder(QUI\ERP\Order\AbstractOrder $O ...@@ -69,9 +71,9 @@ public static function createCouponCodesFromOrder(QUI\ERP\Order\AbstractOrder $O
'quiqqer/coupons', 'quiqqer/coupons',
'DownloadProduct.Order.history.coupon_code', 'DownloadProduct.Order.history.coupon_code',
[ [
'couponCode' => $CouponCode->getCode(), 'couponCode' => $CouponCode->getCode(),
'productTitle' => $Product->getTitle(), 'productTitle' => $Product->getTitle(),
'productId' => $Product->getId(), 'productId' => $Product->getId(),
'couponAmount' => $Currency->format( 'couponAmount' => $Currency->format(
$Product->getFieldValue(self::PRODUCT_FIELD_ID_COUPON_AMOUNT) $Product->getFieldValue(self::PRODUCT_FIELD_ID_COUPON_AMOUNT)
) )
...@@ -98,11 +100,11 @@ public static function createCouponCodesFromOrder(QUI\ERP\Order\AbstractOrder $O ...@@ -98,11 +100,11 @@ public static function createCouponCodesFromOrder(QUI\ERP\Order\AbstractOrder $O
'DownloadProduct.pdf.filename', 'DownloadProduct.pdf.filename',
[ [
'productTitle' => \str_replace(' ', '_', $productTitelSanitized), 'productTitle' => \str_replace(' ', '_', $productTitelSanitized),
'date' => \date('Y_m_d') 'date' => \date('Y_m_d')
] ]
); );
$fileName .= '__'.\mb_substr($Order->getHash(), 0, 6); $fileName .= '__' . \mb_substr($Order->getHash(), 0, 6);
$newCouponPdfFile = \str_replace(\basename($couponPdfFile, '.pdf'), $fileName, $couponPdfFile); $newCouponPdfFile = \str_replace(\basename($couponPdfFile, '.pdf'), $fileName, $couponPdfFile);
...@@ -112,8 +114,8 @@ public static function createCouponCodesFromOrder(QUI\ERP\Order\AbstractOrder $O ...@@ -112,8 +114,8 @@ public static function createCouponCodesFromOrder(QUI\ERP\Order\AbstractOrder $O
CustomerFiles::addFileToCustomer($Customer->getId(), $newCouponPdfFile); CustomerFiles::addFileToCustomer($Customer->getId(), $newCouponPdfFile);
CustomerFiles::addFileToDownloadEntry($Customer->getId(), \basename($newCouponPdfFile)); CustomerFiles::addFileToDownloadEntry($Customer->getId(), \basename($newCouponPdfFile));
$customerDir = CustomerFiles::getFolderPath($Customer); $customerDir = CustomerFiles::getFolderPath($Customer);
$couponFilePathCustomerDir = $customerDir.DIRECTORY_SEPARATOR.\basename($newCouponPdfFile); $couponFilePathCustomerDir = $customerDir . DIRECTORY_SEPARATOR . \basename($newCouponPdfFile);
} }
// Send coupon via email // Send coupon via email
...@@ -148,7 +150,7 @@ public static function createCouponCodesFromOrder(QUI\ERP\Order\AbstractOrder $O ...@@ -148,7 +150,7 @@ public static function createCouponCodesFromOrder(QUI\ERP\Order\AbstractOrder $O
'quiqqer/coupons', 'quiqqer/coupons',
'DownloadProduct.Order.history.coupon_code_send_mail', 'DownloadProduct.Order.history.coupon_code_send_mail',
[ [
'couponCode' => $CouponCode->getCode(), 'couponCode' => $CouponCode->getCode(),
'customerMail' => QUI\ERP\Customer\Utils::getInstance()->getEmailByCustomer($Customer) 'customerMail' => QUI\ERP\Customer\Utils::getInstance()->getEmailByCustomer($Customer)
] ]
) )
...@@ -180,13 +182,13 @@ protected static function createCouponCodeFromProduct( ...@@ -180,13 +182,13 @@ protected static function createCouponCodeFromProduct(
QUI\ERP\Order\AbstractOrder $Order, QUI\ERP\Order\AbstractOrder $Order,
QUI\Interfaces\Users\User $User QUI\Interfaces\Users\User $User
): CouponCode { ): CouponCode {
$Discount = self::createDiscountFromProduct($Product); $Discount = self::createDiscountFromProduct($Product);
$couponAttributes = [ $couponAttributes = [
'title' => QUI::getSystemLocale()->get( 'title' => QUI::getSystemLocale()->get(
'quiqqer/coupons', 'quiqqer/coupons',
'ProductCoupon.coupon_title', 'ProductCoupon.coupon_title',
[ [
'orderId' => $Order->getPrefixedId(), 'orderId' => $Order->getPrefixedId(),
'productId' => $Product->getId() 'productId' => $Product->getId()
] ]
), ),
...@@ -200,7 +202,7 @@ protected static function createCouponCodeFromProduct( ...@@ -200,7 +202,7 @@ protected static function createCouponCodeFromProduct(
$daysValid = 1095; // 3 years; $daysValid = 1095; // 3 years;
} }
$ValidUntil = \date_create('+ '.$daysValid.' days'); $ValidUntil = \date_create('+ ' . $daysValid . ' days');
$couponAttributes['validUntilDate'] = $ValidUntil->format('Y-m-d'); $couponAttributes['validUntilDate'] = $ValidUntil->format('Y-m-d');
// Transferable (=usable by other users or guests) // Transferable (=usable by other users or guests)
...@@ -242,28 +244,28 @@ protected static function createDiscountFromProduct(Product $Product): Discount ...@@ -242,28 +244,28 @@ protected static function createDiscountFromProduct(Product $Product): Discount
/** @var Discount $NewDiscount */ /** @var Discount $NewDiscount */
$NewDiscount = $Handler->createChild([ $NewDiscount = $Handler->createChild([
'active' => 1, 'active' => 1,
'discount' => $discountAmount, 'discount' => $discountAmount,
'discount_type' => DiscountHandler::DISCOUNT_TYPE_CURRENCY, 'discount_type' => DiscountHandler::DISCOUNT_TYPE_CURRENCY,
'hidden' => 1, 'hidden' => 1,
'scope' => DiscountHandler::DISCOUNT_SCOPE_GRAND_TOTAL 'scope' => DiscountHandler::DISCOUNT_SCOPE_GRAND_TOTAL
]); ]);
$L = new QUI\Locale(); $L = new QUI\Locale();
$discountTitle = []; $discountTitle = [];
foreach (QUI::availableLanguages() as $lang) { foreach (QUI::availableLanguages() as $lang) {
$L->setCurrent($lang); $L->setCurrent($lang);
$discountTitle[$lang] = $L->get('quiqqer/coupons', 'Discount.default_title.product', [ $discountTitle[$lang] = $L->get('quiqqer/coupons', 'Discount.default_title.product', [
'productId' => $Product->getId(), 'productId' => $Product->getId(),
'productTitle' => $Product->getTitle($L) 'productTitle' => $Product->getTitle($L)
]); ]);
} }
\QUI\Translator::update( \QUI\Translator::update(
'quiqqer/discount', 'quiqqer/discount',
'discount.'.$NewDiscount->getId().'.title', 'discount.' . $NewDiscount->getId() . '.title',
'quiqqer/discount', 'quiqqer/discount',
$discountTitle $discountTitle
); );
...@@ -293,20 +295,22 @@ public static function createCouponCodePdf(CouponCode $CouponCode, Product $Prod ...@@ -293,20 +295,22 @@ public static function createCouponCodePdf(CouponCode $CouponCode, Product $Prod
$Engine = QUI::getTemplateManager()->getEngine(); $Engine = QUI::getTemplateManager()->getEngine();
$Engine->assign(\array_merge( $Engine->assign(
[ \array_merge(
'CouponCode' => $CouponCode, [
'Product' => $Product->getViewFrontend(), 'CouponCode' => $CouponCode,
], 'Product' => $Product->getViewFrontend(),
self::getCouponViewData($CouponCode, $Product) ],
)); self::getCouponViewData($CouponCode, $Product)
)
);
$tplDir = QUI::getPackage('quiqqer/coupons')->getDir().'templates/'; $tplDir = QUI::getPackage('quiqqer/coupons')->getDir() . 'templates/';
try { try {
$Document->setHeaderHTML($Engine->fetch($tplDir.'CouponCode.header.html')); $Document->setHeaderHTML($Engine->fetch($tplDir . 'CouponCode.header.html'));
$Document->setContentHTML($Engine->fetch($tplDir.'CouponCode.body.html')); $Document->setContentHTML($Engine->fetch($tplDir . 'CouponCode.body.html'));
$Document->setFooterHTML($Engine->fetch($tplDir.'CouponCode.footer.html')); $Document->setFooterHTML($Engine->fetch($tplDir . 'CouponCode.footer.html'));
} catch (\Exception $Exception) { } catch (\Exception $Exception) {
QUI\System\Log::writeException($Exception); QUI\System\Log::writeException($Exception);
} }
...@@ -334,8 +338,8 @@ public static function sendCouponMail( ...@@ -334,8 +338,8 @@ public static function sendCouponMail(
if (empty($recipient)) { if (empty($recipient)) {
QUI\System\Log::addWarning( QUI\System\Log::addWarning(
'Cannot send coupon code e-mail to customer #'.$Customer->getUniqueId().' because user has no' 'Cannot send coupon code e-mail to customer #' . $Customer->getUniqueId() . ' because user has no'
.' email address!' . ' email address!'
); );
return; return;
...@@ -377,9 +381,9 @@ public static function sendCouponMail( ...@@ -377,9 +381,9 @@ public static function sendCouponMail(
\array_merge( \array_merge(
$couponViewData, $couponViewData,
[ [
'customerName' => $Customer->getName(), 'customerName' => $Customer->getName(),
'company' => QUI\ERP\Defaults::conf('company', 'name'), 'company' => QUI\ERP\Defaults::conf('company', 'name'),
'transferableInfo' => $transferableInfo, 'transferableInfo' => $transferableInfo,
'profileDownloadInfo' => $profileDownloadInfo 'profileDownloadInfo' => $profileDownloadInfo
] ]
) )
...@@ -401,15 +405,15 @@ public static function sendCouponMail( ...@@ -401,15 +405,15 @@ public static function sendCouponMail(
*/ */
protected static function getCouponViewData(CouponCode $CouponCode, Product $Product): array protected static function getCouponViewData(CouponCode $CouponCode, Product $Product): array
{ {
$discounts = $CouponCode->getDiscounts(); $discounts = $CouponCode->getDiscounts();
$Discount = $discounts[0]; $Discount = $discounts[0];
$Currency = QUI\ERP\Defaults::getCurrency(); $Currency = QUI\ERP\Defaults::getCurrency();
$DiscountAmount = new QUI\ERP\Money\Price($Discount->getAttribute('discount'), $Currency); $DiscountAmount = new QUI\ERP\Money\Price($Discount->getAttribute('discount'), $Currency);
$Locale = QUI::getLocale(); $Locale = QUI::getLocale();
// Check if coupon is restricted to specific user // Check if coupon is restricted to specific user
$User = false; $User = false;
$restrictedToUserIds = $CouponCode->getUserIds(); $restrictedToUserIds = $CouponCode->getUserIds();
if (!empty($restrictedToUserIds)) { if (!empty($restrictedToUserIds)) {
...@@ -417,8 +421,8 @@ protected static function getCouponViewData(CouponCode $CouponCode, Product $Pro ...@@ -417,8 +421,8 @@ protected static function getCouponViewData(CouponCode $CouponCode, Product $Pro
} }
// Parse valid until date // Parse valid until date
$dateFormat = QUI\ERP\Defaults::getDateFormat(); $dateFormat = QUI\ERP\Defaults::getDateFormat();
$ValidUntilDate = $CouponCode->getValidUntilDate(); $ValidUntilDate = $CouponCode->getValidUntilDate();
$validUntilDateFormatted = '-'; $validUntilDateFormatted = '-';
if ($ValidUntilDate) { if ($ValidUntilDate) {
...@@ -429,15 +433,15 @@ protected static function getCouponViewData(CouponCode $CouponCode, Product $Pro ...@@ -429,15 +433,15 @@ protected static function getCouponViewData(CouponCode $CouponCode, Product $Pro
} }
return [ return [
'isTransferable' => empty($User), 'isTransferable' => empty($User),
'couponCode' => $CouponCode->getCode(), 'couponCode' => $CouponCode->getCode(),
'productTitle' => $Product->getTitle(), 'productTitle' => $Product->getTitle(),
'userName' => $User ? $User->getName() : false, 'userName' => $User ? $User->getName() : false,
'couponDescription' => $Product->getFieldValueByLocale( 'couponDescription' => $Product->getFieldValueByLocale(
self::PRODUCT_FIELD_ID_COUPON_DESCRIPTION self::PRODUCT_FIELD_ID_COUPON_DESCRIPTION
), ),
'discountAmountFormatted' => $DiscountAmount->getDisplayPrice(), 'discountAmountFormatted' => $DiscountAmount->getDisplayPrice(),
'createDateFormatted' => $Locale->formatDate( 'createDateFormatted' => $Locale->formatDate(
$CouponCode->getCreateDate()->getTimestamp(), $CouponCode->getCreateDate()->getTimestamp(),
$dateFormat $dateFormat
), ),
...@@ -456,8 +460,8 @@ protected static function getCouponViewData(CouponCode $CouponCode, Product $Pro ...@@ -456,8 +460,8 @@ protected static function getCouponViewData(CouponCode $CouponCode, Product $Pro
public static function getNoVatTaxTypes(): array public static function getNoVatTaxTypes(): array
{ {
$noVatTaxTypes = []; $noVatTaxTypes = [];
$TaxHandler = QUI\ERP\Tax\Handler::getInstance(); $TaxHandler = QUI\ERP\Tax\Handler::getInstance();
$taxTypes = $TaxHandler->getTaxTypes(); $taxTypes = $TaxHandler->getTaxTypes();
/** @var QUI\ERP\Tax\TaxType $TaxType */ /** @var QUI\ERP\Tax\TaxType $TaxType */
foreach ($taxTypes as $TaxType) { foreach ($taxTypes as $TaxType) {
......
...@@ -3,7 +3,6 @@ ...@@ -3,7 +3,6 @@
namespace QUI\ERP\Coupons\Products; namespace QUI\ERP\Coupons\Products;
use QUI; use QUI;
use QUI\ERP\Products\Product\Types\DigitalProduct;
/** /**
* Class PhysicalCouponProductType * Class PhysicalCouponProductType
...@@ -52,7 +51,7 @@ public function __construct($pid, $product = []) ...@@ -52,7 +51,7 @@ public function __construct($pid, $product = [])
* @param QUI\Locale $Locale * @param QUI\Locale $Locale
* @return string * @return string
*/ */
public static function getTypeTitle($Locale = null) public static function getTypeTitle($Locale = null): string
{ {
if ($Locale === null) { if ($Locale === null) {
$Locale = QUI::getLocale(); $Locale = QUI::getLocale();
...@@ -65,7 +64,7 @@ public static function getTypeTitle($Locale = null) ...@@ -65,7 +64,7 @@ public static function getTypeTitle($Locale = null)
* @param QUI\Locale $Locale * @param QUI\Locale $Locale
* @return string * @return string
*/ */
public static function getTypeDescription($Locale = null) public static function getTypeDescription($Locale = null): string
{ {
if ($Locale === null) { if ($Locale === null) {
$Locale = QUI::getLocale(); $Locale = QUI::getLocale();
......