<?php /** * 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\Translator; use QUI\Utils\Security\Orthos; QUI::$Ajax->registerFunction( 'package_quiqqer_coupons_ajax_create', function ($attributes) { $attributes = Orthos::clearArray(json_decode($attributes, true)); if (!empty($attributes['code'])) { $attributes['code'] = html_entity_decode($attributes['code']); } if (!empty($attributes['title'])) { $attributes['title'] = html_entity_decode($attributes['title']); } try { $amount = 1; if (!empty($attributes['amount'])) { $amount = (int)$attributes['amount']; unset($attributes['amount']); } // Check required fields $requiredFields = [ 'discountAmount' ]; foreach ($requiredFields as $field) { if (!isset($attributes[$field])) { throw new CouponCodeException([ 'quiqqer/coupons', 'exception.ajax.create.missing_field' ]); } } // Create discount $discountType = match ($attributes['discountType']) { 'percentage' => DiscountsHandler::DISCOUNT_TYPE_PERCENT, default => DiscountsHandler::DISCOUNT_TYPE_CURRENCY, }; $Discounts = DiscountsHandler::getInstance(); $NewDiscount = $Discounts->createChild([ 'active' => 1, 'discount' => (float)$attributes['discountAmount'], 'discount_type' => $discountType, ]); $L = QUI::getLocale(); for ($i = 0; $i < $amount; $i++) { $NewCouponCode = Handler::createCouponCode([$NewDiscount->getId()], $attributes); if ($i === 0) { Translator::update( 'quiqqer/discount', 'discount.' . $NewDiscount->getId() . '.title', 'quiqqer/discount', [ 'de' => $L->getByLang('de', 'quiqqer/coupons', 'Discount.default_title', [ 'couponCode' => $NewCouponCode->getCode() ]), 'en' => $L->getByLang('en', 'quiqqer/coupons', 'Discount.default_title', [ 'couponCode' => $NewCouponCode->getCode() ]) ] ); Translator::publish('quiqqer/discount'); } } } catch (CouponCodeException $Exception) { QUI::getMessagesHandler()->addError( QUI::getLocale()->get( 'quiqqer/coupons', 'message.ajax.create.error', [ 'error' => $Exception->getMessage() ] ) ); return false; } catch (QUI\Permissions\Exception $Exception) { throw $Exception; } catch (Exception $Exception) { QUI\System\Log::writeException($Exception); QUI::getMessagesHandler()->addError( QUI::getLocale()->get( 'quiqqer/coupons', 'message.ajax.general_error' ) ); return false; } QUI::getMessagesHandler()->addSuccess( QUI::getLocale()->get( 'quiqqer/coupons', 'message.ajax.create.success' ) ); return true; }, ['attributes'], 'Permission::checkAdminUser' );