Newer
Older
*
* @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;
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']);
}
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();
'active' => 1,
'discount' => (float)$attributes['discountAmount'],
'discount_type' => $discountType,
]);
$L = QUI::getLocale();
$NewCouponCode = Handler::createCouponCode([$NewDiscount->getId()], $attributes);
if ($i === 0) {
Translator::update(
'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');
QUI::getMessagesHandler()->addError(
QUI::getLocale()->get(
)
);
return false;
} catch (QUI\Permissions\Exception $Exception) {
throw $Exception;
} catch (Exception $Exception) {
QUI\System\Log::writeException($Exception);
QUI::getMessagesHandler()->addError(
QUI::getLocale()->get(
'message.ajax.general_error'
)
);
return false;
}
QUI::getMessagesHandler()->addSuccess(
QUI::getLocale()->get(
'message.ajax.create.success'
)
);
return true;
},