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