diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml new file mode 100644 index 0000000000000000000000000000000000000000..b8d20acb6c365ad8036a7b36d47dabd876d08efa --- /dev/null +++ b/.gitlab-ci.yml @@ -0,0 +1,3 @@ +include: + - project: 'quiqqer/stabilization/semantic-release' + file: '/ci-templates/.gitlab-ci.yml' diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..57cd60a5af2567fefadef1c99f241dbbb207183d --- /dev/null +++ b/LICENSE @@ -0,0 +1 @@ +GPL-3.0+ \ No newline at end of file diff --git a/ajax/backend/getCouponPrice.php b/ajax/backend/getCouponPrice.php index 0c21d5e61d8cbe42a4b2309d4c1bd7c09e9fa506..7f6cd3a13e3a9e823dc3795656277ee3f6510de9 100644 --- a/ajax/backend/getCouponPrice.php +++ b/ajax/backend/getCouponPrice.php @@ -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(); diff --git a/ajax/create.php b/ajax/create.php index 20391131e20aee71c5a7e69b66df99912e023297..d3c9297a26bae45c973006f7f36fa888313b9019 100644 --- a/ajax/create.php +++ b/ajax/create.php @@ -1,16 +1,17 @@ <?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, ]); diff --git a/ajax/frontend/redeem.php b/ajax/frontend/redeem.php index 740b4a274404ee0bf37846d9b9b91decee7d9835..ac93c3b9ae9582069fcf38538bc3048dee9943b1 100644 --- a/ajax/frontend/redeem.php +++ b/ajax/frontend/redeem.php @@ -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)) { diff --git a/ajax/frontend/removeCoupons.php b/ajax/frontend/removeCoupons.php index d9a48571cdc220110001b1b68293615d56286163..19d7c9bbefe1a42ff2c7f3df46640da868480eab 100644 --- a/ajax/frontend/removeCoupons.php +++ b/ajax/frontend/removeCoupons.php @@ -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) { diff --git a/ajax/getList.php b/ajax/getList.php index 856b5349866e31f98121d0e1e8d12db043a3b36a..23a6489d551d3b22a48611175069ece395174d94 100644 --- a/ajax/getList.php +++ b/ajax/getList.php @@ -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()); } diff --git a/src/QUI/ERP/Coupons/CodeGenerator.php b/src/QUI/ERP/Coupons/CodeGenerator.php index 378d4faf742a271f141fb22eef3b620fbf845b08..99b4052f29e1c7108701d304f8d805ff05693e8f 100644 --- a/src/QUI/ERP/Coupons/CodeGenerator.php +++ b/src/QUI/ERP/Coupons/CodeGenerator.php @@ -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; diff --git a/src/QUI/ERP/Coupons/CodeGenerators/SimpleString.php b/src/QUI/ERP/Coupons/CodeGenerators/SimpleString.php index bc17f69204c8d2d0287e56e4958c31aab07c211f..060098deb26547bd67be13046ffea1bc04adc79d 100644 --- a/src/QUI/ERP/Coupons/CodeGenerators/SimpleString.php +++ b/src/QUI/ERP/Coupons/CodeGenerators/SimpleString.php @@ -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)); diff --git a/src/QUI/ERP/Coupons/CodeGenerators/Uuid.php b/src/QUI/ERP/Coupons/CodeGenerators/Uuid.php index 1efeb2c07fb1db5934d7a2fb7a223842ce71b4db..662b3c23d6ef3e4bd3d8bf9884fdcdebbda94297 100644 --- a/src/QUI/ERP/Coupons/CodeGenerators/Uuid.php +++ b/src/QUI/ERP/Coupons/CodeGenerators/Uuid.php @@ -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(); } } diff --git a/src/QUI/ERP/Coupons/CouponCode.php b/src/QUI/ERP/Coupons/CouponCode.php index 038cd06fef09e1109777381e03ad9a32d1df082a..479324527a8eb2db5d7e76cab257cc65d2e4eb64 100644 --- a/src/QUI/ERP/Coupons/CouponCode.php +++ b/src/QUI/ERP/Coupons/CouponCode.php @@ -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')) { diff --git a/src/QUI/ERP/Coupons/Events.php b/src/QUI/ERP/Coupons/Events.php index 7a1a2ed8ce97cf48e12baf739f910912ec50e081..8c6495d8ea14dcd6274649bb349177cf63624591 100644 --- a/src/QUI/ERP/Coupons/Events.php +++ b/src/QUI/ERP/Coupons/Events.php @@ -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() ] ]); } diff --git a/src/QUI/ERP/Coupons/Handler.php b/src/QUI/ERP/Coupons/Handler.php index cd62db5fc92318aeac6522c1012d74c9c86cf4cf..83bbc92819a776f07cbf5fd5efbf5eeccd5ba926 100644 --- a/src/QUI/ERP/Coupons/Handler.php +++ b/src/QUI/ERP/Coupons/Handler.php @@ -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'); } diff --git a/src/QUI/ERP/Coupons/Products/DigitalCouponProductType.php b/src/QUI/ERP/Coupons/Products/DigitalCouponProductType.php index 311d5164a0367136066af89afdd935bdadb379bd..87109fa20e350e7018950d3263773b6291d113a7 100644 --- a/src/QUI/ERP/Coupons/Products/DigitalCouponProductType.php +++ b/src/QUI/ERP/Coupons/Products/DigitalCouponProductType.php @@ -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(); diff --git a/src/QUI/ERP/Coupons/Products/Handler.php b/src/QUI/ERP/Coupons/Products/Handler.php index ce8da5a09f7c43a17461c1c3f4d287a93e2f6130..a4647378a0c72f4b13703a5dbf2b0e14e3379ac2 100644 --- a/src/QUI/ERP/Coupons/Products/Handler.php +++ b/src/QUI/ERP/Coupons/Products/Handler.php @@ -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) { diff --git a/src/QUI/ERP/Coupons/Products/PhysicalCouponProductType.php b/src/QUI/ERP/Coupons/Products/PhysicalCouponProductType.php index 3359de5d3fd837b385a2563774e734324d903de2..c9975338a5e06beb2aab14f2cce5ae4e2ae702b9 100644 --- a/src/QUI/ERP/Coupons/Products/PhysicalCouponProductType.php +++ b/src/QUI/ERP/Coupons/Products/PhysicalCouponProductType.php @@ -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();