feat(admin): create and batch-generate coupons in dialogs
- Move "新建优惠码" / "批量生成" into header-launched <dialog>s - Extract forms into PayCouponsForms trait with shared rule fields, hints, validation and currency/percent unit switching - Generated codes card gets a copy-all button; list codes copy on click - Drop old inline forms, render_generated_dump and the unread aksrt_coupon_generated redirect arg Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
1 parent
92a3c2b8c7
commit
4f6e17ba5e
4 files changed
+459
-158
No files matched your search
@@ -0,0 +1,54 @@
|
||||
/* 优惠码(aksrt_coupons):页头按钮 + 新建/批量生成弹窗。复用 native-ui.css 的 --an-* 令牌,规则限定在本页类名下。 */
|
||||
.aksrt-coupons-page [hidden],
|
||||
.aksrt-coupon-dialog [hidden] { display: none !important; }
|
||||
.aksrt-coupons-page .aksrt-native-header__actions .button,
|
||||
.aksrt-coupon-generated .aksrt-native-card__actions .button { display: inline-flex; align-items: center; gap: 5px; }
|
||||
.aksrt-coupons-page .aksrt-native-header__actions .dashicons { margin: 0; font-size: 17px; line-height: 20px; }
|
||||
.aksrt-coupon-generated .aksrt-native-card__actions .dashicons { margin: 0; font-size: 14px; width: 14px; height: 14px; }
|
||||
|
||||
/* ---------- 列表 ---------- */
|
||||
.aksrt-coupons-page .wp-list-table { min-width: 1000px; }
|
||||
.aksrt-coupons-page .wp-list-table td { vertical-align: middle; overflow-wrap: anywhere; }
|
||||
.aksrt-coupon-code { display: inline-flex; align-items: center; gap: 5px; max-width: 100%; padding: 4px 7px; color: var(--an-text); background: var(--an-bg-soft); border: 1px solid transparent; border-radius: 5px; text-align: left; font-size: 13px; overflow-wrap: anywhere; cursor: pointer; }
|
||||
.aksrt-coupon-code .dashicons { flex: none; width: 14px; height: 14px; color: var(--an-muted); font-size: 14px; }
|
||||
.aksrt-coupon-code:hover { color: var(--an-primary); background: var(--an-primary-soft); border-color: var(--an-primary); }
|
||||
.aksrt-coupon-code:focus-visible { outline: 2px solid var(--an-primary); outline-offset: 2px; }
|
||||
.aksrt-coupon-generated textarea { margin-top: 8px; resize: vertical; }
|
||||
|
||||
/* ---------- 弹窗 ---------- */
|
||||
html.aksrt-coupons-modal-open { overflow: hidden; }
|
||||
.aksrt-coupon-dialog { width: min(720px, calc(100vw - 32px)); max-width: none; max-height: calc(100vh - 48px); max-height: calc(100dvh - 48px); margin: auto; padding: 0; overflow: hidden; color: var(--an-text-2); background: var(--an-card); border: 0; border-radius: var(--an-radius); box-shadow: 0 16px 64px rgba(15, 23, 42, .2); }
|
||||
.aksrt-coupon-dialog::backdrop { background: rgba(15, 23, 42, .45); }
|
||||
.aksrt-coupon-dialog__frame { display: flex; flex-direction: column; max-height: inherit; margin: 0; }
|
||||
.aksrt-coupon-dialog__head { display: flex; flex: none; align-items: flex-start; justify-content: space-between; gap: 16px; padding: 20px 24px 18px; border-bottom: 1px solid var(--an-border-soft); }
|
||||
.aksrt-coupon-dialog .aksrt-coupon-dialog__head h2 { margin: 0; padding: 0; color: var(--an-text); font-size: 18px; font-weight: 600; line-height: 1.5; }
|
||||
.aksrt-coupon-dialog__head p { margin: 5px 0 0; font-size: 13px; line-height: 1.6; }
|
||||
.aksrt-coupon-dialog__close { display: inline-flex; flex: none; align-items: center; justify-content: center; width: 32px; height: 32px; padding: 0; color: var(--an-text-2); background: transparent; border: 0; border-radius: var(--an-radius-sm); cursor: pointer; }
|
||||
.aksrt-coupon-dialog__close:hover { color: var(--an-text); background: var(--an-bg-soft); }
|
||||
.aksrt-coupon-dialog__body { min-height: 0; padding: 20px 24px 24px; overflow-y: auto; overscroll-behavior: contain; }
|
||||
.aksrt-coupon-dialog__foot { display: flex; flex: none; justify-content: flex-end; gap: 8px; padding: 14px 24px; background: var(--an-card); border-top: 1px solid var(--an-border-soft); }
|
||||
.aksrt-coupon-dialog__foot .button { min-width: 110px; }
|
||||
.aksrt-coupon-dialog .button:disabled { opacity: .65; cursor: not-allowed; }
|
||||
.aksrt-coupon-dialog :is(a, button, input, select, textarea):focus-visible { outline: 2px solid var(--an-primary); outline-offset: 2px; }
|
||||
.aksrt-coupon-dialog .aksrt-native-form-grid { grid-template-columns: repeat(2, minmax(0, 1fr)); }
|
||||
.aksrt-coupon-dialog .aksrt-coupon-batch-grid { grid-template-columns: repeat(3, minmax(0, 1fr)); }
|
||||
.aksrt-coupon-dialog .aksrt-coupon-section { margin: 0 0 12px; color: var(--an-text); font-size: 14px; font-weight: 600; line-height: 1.5; }
|
||||
.aksrt-coupon-dialog .aksrt-coupon-section ~ .aksrt-coupon-section { margin-top: 22px; padding-top: 18px; border-top: 1px solid var(--an-border-soft); }
|
||||
|
||||
.aksrt-coupon-inline { display: flex; align-items: center; gap: 6px; }
|
||||
.aksrt-coupon-inline input { flex: 1 1 auto; min-width: 0; }
|
||||
.aksrt-coupon-unit { flex: none; min-width: 1.2em; color: var(--an-muted); }
|
||||
|
||||
/* ---------- 复制提示 ---------- */
|
||||
.aksrt-coupon-toast { position: fixed; right: 24px; bottom: 24px; z-index: 100000; max-width: min(360px, calc(100vw - 48px)); padding: 10px 14px; color: #fff; background: rgba(15, 23, 42, .9); border-radius: var(--an-radius-sm); font-size: 13px; opacity: 0; transform: translateY(8px); transition: opacity .2s, transform .2s; pointer-events: none; }
|
||||
.aksrt-coupon-toast.is-visible { opacity: 1; transform: none; }
|
||||
|
||||
@media (max-width: 600px) {
|
||||
.aksrt-coupon-dialog { width: calc(100vw - 24px); max-height: calc(100dvh - 24px); }
|
||||
.aksrt-coupon-dialog__head,
|
||||
.aksrt-coupon-dialog__body,
|
||||
.aksrt-coupon-dialog__foot { padding-left: 16px; padding-right: 16px; }
|
||||
.aksrt-coupon-dialog .aksrt-native-form-grid,
|
||||
.aksrt-coupon-dialog .aksrt-coupon-batch-grid { grid-template-columns: 1fr; }
|
||||
.aksrt-coupon-dialog__foot .button { flex: 1; min-width: 0; }
|
||||
}
|
||||
@@ -0,0 +1,145 @@
|
||||
/** 优惠码:新建/批量生成弹窗、类型与范围联动、防重复提交、点击复制。仅本页入队。 */
|
||||
(function () {
|
||||
'use strict';
|
||||
|
||||
var root = document.querySelector('.aksrt-coupons-page');
|
||||
if (!root) return;
|
||||
var toast = root.querySelector('[data-aksrt-coupon-toast]');
|
||||
var toastTimer;
|
||||
var forms = Array.from(root.querySelectorAll('[data-aksrt-coupon-form]'));
|
||||
|
||||
function notify(key) {
|
||||
if (!toast) return;
|
||||
clearTimeout(toastTimer);
|
||||
toast.textContent = toast.getAttribute('data-' + key);
|
||||
toast.classList.add('is-visible');
|
||||
toastTimer = setTimeout(function () { toast.classList.remove('is-visible'); }, 3000);
|
||||
}
|
||||
|
||||
/** 类型切换面值的步长/上限与单位;「全部商品」时范围 ID 禁用,否则必填。 */
|
||||
function syncForm(form) {
|
||||
var type = form.elements.type;
|
||||
var value = form.elements.value;
|
||||
var unit = form.querySelector('[data-aksrt-coupon-unit]');
|
||||
if (type && value) {
|
||||
var percent = type.value === 'percent';
|
||||
value.step = percent ? '1' : '0.01';
|
||||
if (percent) value.max = '100'; else value.removeAttribute('max');
|
||||
if (unit) unit.textContent = unit.getAttribute(percent ? 'data-percent' : 'data-fixed');
|
||||
}
|
||||
var scope = form.elements.scope_type;
|
||||
var ids = form.elements.scope_ids;
|
||||
if (scope && ids) {
|
||||
var all = scope.value === '';
|
||||
ids.disabled = all;
|
||||
ids.required = !all;
|
||||
}
|
||||
}
|
||||
|
||||
function lockScroll() {
|
||||
document.documentElement.classList.toggle('aksrt-coupons-modal-open', !!root.querySelector('dialog[open]'));
|
||||
}
|
||||
|
||||
root.querySelectorAll('.aksrt-coupon-dialog').forEach(function (dialog) {
|
||||
if (typeof dialog.showModal !== 'function') return;
|
||||
var opener = null;
|
||||
var startedOutside = false;
|
||||
var form = dialog.querySelector('form');
|
||||
|
||||
function outside(event) {
|
||||
var rect = dialog.getBoundingClientRect();
|
||||
return event.clientX < rect.left || event.clientX > rect.right || event.clientY < rect.top || event.clientY > rect.bottom;
|
||||
}
|
||||
function requestClose() {
|
||||
if (!form.dataset.submitting) dialog.close();
|
||||
}
|
||||
|
||||
root.querySelectorAll('[data-aksrt-dialog-open="' + dialog.id + '"]').forEach(function (button) {
|
||||
button.addEventListener('click', function () {
|
||||
opener = button;
|
||||
syncForm(form);
|
||||
dialog.showModal();
|
||||
lockScroll();
|
||||
});
|
||||
});
|
||||
dialog.querySelectorAll('[data-aksrt-dialog-close]').forEach(function (button) {
|
||||
button.addEventListener('click', requestClose);
|
||||
});
|
||||
dialog.addEventListener('pointerdown', function (event) {
|
||||
startedOutside = event.target === dialog && outside(event);
|
||||
});
|
||||
dialog.addEventListener('click', function (event) {
|
||||
if (startedOutside && event.target === dialog && outside(event)) requestClose();
|
||||
startedOutside = false;
|
||||
});
|
||||
dialog.addEventListener('cancel', function (event) {
|
||||
if (form.dataset.submitting) event.preventDefault();
|
||||
});
|
||||
dialog.addEventListener('close', function () {
|
||||
lockScroll();
|
||||
if (opener && opener.isConnected) opener.focus();
|
||||
opener = null;
|
||||
});
|
||||
});
|
||||
|
||||
forms.forEach(function (form) {
|
||||
var submit = form.querySelector('[data-aksrt-coupon-submit]');
|
||||
if (submit) submit.setAttribute('data-idle-label', submit.textContent);
|
||||
form.addEventListener('change', function () { syncForm(form); });
|
||||
form.addEventListener('submit', function (event) {
|
||||
if (form.dataset.submitting) {
|
||||
event.preventDefault();
|
||||
return;
|
||||
}
|
||||
form.dataset.submitting = '1';
|
||||
if (submit) {
|
||||
submit.textContent = form.getAttribute('data-busy-label');
|
||||
// 延后禁用:同步禁用 submit 按钮会让部分浏览器丢掉这次提交。
|
||||
setTimeout(function () { submit.disabled = true; }, 0);
|
||||
}
|
||||
});
|
||||
syncForm(form);
|
||||
});
|
||||
|
||||
root.addEventListener('click', async function (event) {
|
||||
var button = event.target.closest('[data-clipboard-text]');
|
||||
if (!button) return;
|
||||
var value = button.getAttribute('data-clipboard-text');
|
||||
try {
|
||||
if (navigator.clipboard && window.isSecureContext) {
|
||||
await navigator.clipboard.writeText(value);
|
||||
} else {
|
||||
var input = document.createElement('textarea');
|
||||
input.value = value;
|
||||
input.className = 'screen-reader-text';
|
||||
root.appendChild(input);
|
||||
input.select();
|
||||
var copied = false;
|
||||
try {
|
||||
copied = document.execCommand('copy');
|
||||
} finally {
|
||||
input.remove();
|
||||
button.focus();
|
||||
}
|
||||
if (!copied) throw new Error('copy');
|
||||
}
|
||||
notify('copied');
|
||||
} catch (error) {
|
||||
notify('copy-failed');
|
||||
}
|
||||
});
|
||||
|
||||
// bfcache 返回时恢复按钮,避免表单停在提交中状态。
|
||||
window.addEventListener('pageshow', function () {
|
||||
forms.forEach(function (form) {
|
||||
var submit = form.querySelector('[data-aksrt-coupon-submit]');
|
||||
delete form.dataset.submitting;
|
||||
if (submit) {
|
||||
submit.disabled = false;
|
||||
submit.textContent = submit.getAttribute('data-idle-label');
|
||||
}
|
||||
syncForm(form);
|
||||
});
|
||||
lockScroll();
|
||||
});
|
||||
})();
|
||||
+60
-158
@@ -9,8 +9,12 @@ defined('ABSPATH') || exit;
|
||||
|
||||
class PayCoupons {
|
||||
|
||||
public const CAPABILITY = 'manage_options';
|
||||
public const PAGE_SLUG = 'aksrt_coupons';
|
||||
use PayCouponsForms;
|
||||
|
||||
public const CAPABILITY = 'manage_options';
|
||||
public const PAGE_SLUG = 'aksrt_coupons';
|
||||
public const CREATE_DIALOG = 'aksrt-coupon-create';
|
||||
public const BATCH_DIALOG = 'aksrt-coupon-batch';
|
||||
|
||||
private static $instance = null;
|
||||
|
||||
@@ -25,6 +29,7 @@ class PayCoupons {
|
||||
if (!is_admin()) {
|
||||
return;
|
||||
}
|
||||
add_action('admin_enqueue_scripts', [$this, 'enqueue_assets']);
|
||||
add_action('admin_post_aksrt_pay_create_coupon', [$this, 'handle_create_coupon']);
|
||||
add_action('admin_post_aksrt_pay_batch_coupons', [$this, 'handle_batch_coupons']);
|
||||
add_action('admin_post_aksrt_pay_update_coupon', [$this, 'handle_update_coupon']);
|
||||
@@ -32,18 +37,34 @@ class PayCoupons {
|
||||
add_action('admin_post_aksrt_pay_enable_coupon', [$this, 'handle_enable_coupon']);
|
||||
}
|
||||
|
||||
public function enqueue_assets(): void {
|
||||
$page = isset($_GET['page']) ? sanitize_key((string) wp_unslash($_GET['page'])) : '';
|
||||
if ($page !== self::PAGE_SLUG) {
|
||||
return;
|
||||
}
|
||||
$css = '/assets/css/admin/coupons.css';
|
||||
$js = '/assets/js/admin-coupons.js';
|
||||
wp_enqueue_style('aksrt-admin-coupons', AKSRT_URI . $css, [NativeUi::STYLE_HANDLE], (string) filemtime(AKSRT_DIR . $css));
|
||||
wp_enqueue_script('aksrt-admin-coupons', AKSRT_URI . $js, [], (string) filemtime(AKSRT_DIR . $js), true);
|
||||
}
|
||||
|
||||
public function render_page(): void {
|
||||
$this->ensure_cap();
|
||||
|
||||
NativeUi::page_open();
|
||||
$ready = class_exists('\AKSRT\Payment\Coupon');
|
||||
NativeUi::page_open('aksrt-coupons-page');
|
||||
NativeUi::header(
|
||||
__('优惠码', 'aksrt'),
|
||||
__('创建、批量生成与管理结算优惠码。配置项仍在 AKSRT 主题设置 SPA。', 'aksrt'),
|
||||
'dashicons-tickets-alt'
|
||||
'dashicons-tickets-alt',
|
||||
$ready ? [
|
||||
['label' => __('新建优惠码', 'aksrt'), 'dialog' => self::CREATE_DIALOG, 'primary' => true, 'icon' => 'dashicons-plus-alt2'],
|
||||
['label' => __('批量生成', 'aksrt'), 'dialog' => self::BATCH_DIALOG, 'icon' => 'dashicons-randomize'],
|
||||
] : []
|
||||
);
|
||||
$this->render_flash();
|
||||
|
||||
if (!class_exists('\AKSRT\Payment\Coupon')) {
|
||||
if (!$ready) {
|
||||
echo '<div class="notice notice-error"><p>' . esc_html__('优惠码模块未初始化。', 'aksrt') . '</p></div>';
|
||||
NativeUi::page_close();
|
||||
return;
|
||||
@@ -59,156 +80,41 @@ class PayCoupons {
|
||||
echo '<div class="notice notice-error"><p>' . esc_html__('优惠码不存在。', 'aksrt') . '</p></div>';
|
||||
}
|
||||
|
||||
$this->render_create_form();
|
||||
$this->render_batch_form();
|
||||
$this->render_generated_dump();
|
||||
$this->render_generated_codes();
|
||||
$this->render_list($svc);
|
||||
$this->render_create_dialog();
|
||||
$this->render_batch_dialog();
|
||||
echo '<div class="aksrt-coupon-toast" role="status" aria-live="polite" data-aksrt-coupon-toast'
|
||||
. ' data-copied="' . esc_attr__('已复制到剪贴板', 'aksrt') . '"'
|
||||
. ' data-copy-failed="' . esc_attr__('自动复制失败,请手动选中后复制。', 'aksrt') . '"></div>';
|
||||
|
||||
NativeUi::page_close();
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string,mixed> $row
|
||||
*/
|
||||
private function render_edit_form(array $row): void {
|
||||
$id = (int) ($row['id'] ?? 0);
|
||||
$scope = is_array($row['product_scope'] ?? null) ? $row['product_scope'] : [];
|
||||
$scope_type = sanitize_key((string) ($scope['type'] ?? ''));
|
||||
$scope_ids = array_map('intval', (array) ($scope['ids'] ?? []));
|
||||
$expires = (string) ($row['expires_at'] ?? '');
|
||||
$expires_local = $expires !== '' ? str_replace(' ', 'T', substr($expires, 0, 16)) : '';
|
||||
|
||||
$title = sprintf(
|
||||
/* translators: %d coupon id */
|
||||
__('编辑优惠码 #%d', 'aksrt'),
|
||||
$id
|
||||
);
|
||||
$back = NativeUi::button_link(__('返回列表', 'aksrt'), $this->page_url(), false, 'dashicons-arrow-left-alt');
|
||||
|
||||
NativeUi::card_open($title, $back);
|
||||
echo '<form method="post" action="' . esc_url(admin_url('admin-post.php')) . '">';
|
||||
echo '<input type="hidden" name="action" value="aksrt_pay_update_coupon" />';
|
||||
echo '<input type="hidden" name="coupon_id" value="' . esc_attr((string) $id) . '" />';
|
||||
wp_nonce_field('aksrt_pay_update_coupon_' . $id);
|
||||
echo '<div class="aksrt-native-form-grid">';
|
||||
$this->field(__('代码', 'aksrt'), '<input type="text" value="' . esc_attr((string) ($row['code'] ?? '')) . '" readonly />');
|
||||
$this->field(__('类型', 'aksrt'), $this->type_select((string) ($row['type'] ?? '')));
|
||||
$this->field(__('面值', 'aksrt'), '<input type="number" step="0.01" name="value" value="' . esc_attr((string) ($row['value'] ?? 0)) . '" />');
|
||||
$this->field(__('最低消费', 'aksrt'), '<input type="number" step="0.01" name="min_amount" value="' . esc_attr((string) ($row['min_amount'] ?? 0)) . '" />');
|
||||
$this->field(__('最高优惠(百分比用)', 'aksrt'), '<input type="number" step="0.01" name="max_discount" value="' . esc_attr((string) ($row['max_discount'] ?? 0)) . '" />');
|
||||
$this->field(__('总次数(0=不限)', 'aksrt'), '<input type="number" name="usage_limit" value="' . esc_attr((string) ($row['usage_limit'] ?? 0)) . '" />');
|
||||
$this->field(__('每人限次(0=不限)', 'aksrt'), '<input type="number" name="per_user_limit" value="' . esc_attr((string) ($row['per_user_limit'] ?? 0)) . '" />');
|
||||
$this->scope_fields($scope_type, implode(',', $scope_ids));
|
||||
$this->field(__('过期时间', 'aksrt'), '<input type="datetime-local" name="expires_at" value="' . esc_attr($expires_local) . '" />');
|
||||
echo '</div>';
|
||||
echo '<div class="aksrt-native-form-foot">';
|
||||
submit_button(__('保存修改', 'aksrt'), 'primary', '', false);
|
||||
echo '</div>';
|
||||
echo '</form>';
|
||||
NativeUi::card_close();
|
||||
}
|
||||
|
||||
private function render_create_form(): void {
|
||||
NativeUi::card_open(__('新建优惠码', 'aksrt'));
|
||||
echo '<form method="post" action="' . esc_url(admin_url('admin-post.php')) . '">';
|
||||
echo '<input type="hidden" name="action" value="aksrt_pay_create_coupon" />';
|
||||
wp_nonce_field('aksrt_pay_create_coupon');
|
||||
echo '<div class="aksrt-native-form-grid">';
|
||||
$this->field(__('代码', 'aksrt'), '<input type="text" name="code" required />');
|
||||
$this->field(__('类型', 'aksrt'), $this->type_select(''));
|
||||
$this->field(__('面值', 'aksrt'), '<input type="number" step="0.01" name="value" value="0" />');
|
||||
$this->field(__('最低消费', 'aksrt'), '<input type="number" step="0.01" name="min_amount" value="0" />');
|
||||
$this->field(__('最高优惠(百分比用)', 'aksrt'), '<input type="number" step="0.01" name="max_discount" value="0" />');
|
||||
$this->field(__('总次数(0=不限)', 'aksrt'), '<input type="number" name="usage_limit" value="0" />');
|
||||
$this->field(__('每人限次(0=不限)', 'aksrt'), '<input type="number" name="per_user_limit" value="0" />');
|
||||
$this->scope_fields('', '');
|
||||
$this->field(__('过期时间', 'aksrt'), '<input type="datetime-local" name="expires_at" />');
|
||||
echo '</div>';
|
||||
echo '<div class="aksrt-native-form-foot">';
|
||||
submit_button(__('创建', 'aksrt'), 'primary', '', false);
|
||||
echo '</div>';
|
||||
echo '</form>';
|
||||
NativeUi::card_close();
|
||||
}
|
||||
|
||||
private function render_batch_form(): void {
|
||||
echo '<details class="aksrt-native-card aksrt-native-collapse">';
|
||||
echo '<summary><span class="dashicons dashicons-randomize" aria-hidden="true"></span>' . esc_html__('批量生成优惠码', 'aksrt') . '</summary>';
|
||||
echo '<div class="aksrt-native-card__body">';
|
||||
echo '<form method="post" action="' . esc_url(admin_url('admin-post.php')) . '">';
|
||||
echo '<input type="hidden" name="action" value="aksrt_pay_batch_coupons" />';
|
||||
wp_nonce_field('aksrt_pay_batch_coupons');
|
||||
echo '<div class="aksrt-native-form-grid">';
|
||||
$this->field(__('数量', 'aksrt'), '<input type="number" name="count" min="1" max="100" value="10" />');
|
||||
$this->field(__('长度', 'aksrt'), '<input type="number" name="length" min="6" max="24" value="10" />');
|
||||
$this->field(__('前缀', 'aksrt'), '<input type="text" name="prefix" value="" />');
|
||||
$this->field(__('类型', 'aksrt'), $this->type_select('fixed'));
|
||||
$this->field(__('面值', 'aksrt'), '<input type="number" step="0.01" name="value" value="10" />');
|
||||
$this->field(__('最低消费', 'aksrt'), '<input type="number" step="0.01" name="min_amount" value="0" />');
|
||||
$this->field(__('最高优惠', 'aksrt'), '<input type="number" step="0.01" name="max_discount" value="0" />');
|
||||
$this->field(__('总次数(0=不限)', 'aksrt'), '<input type="number" name="usage_limit" value="1" />');
|
||||
$this->field(__('每人限次', 'aksrt'), '<input type="number" name="per_user_limit" value="1" />');
|
||||
$this->scope_fields('', '');
|
||||
$this->field(__('过期时间', 'aksrt'), '<input type="datetime-local" name="expires_at" />');
|
||||
echo '</div>';
|
||||
echo '<div class="aksrt-native-form-foot">';
|
||||
submit_button(__('批量生成', 'aksrt'), 'secondary', '', false);
|
||||
echo '</div>';
|
||||
echo '</form>';
|
||||
echo '</div>';
|
||||
echo '</details>';
|
||||
}
|
||||
|
||||
/** 单字段单元(.aksrt-native-field);$html 为调用方已转义的控件片段。 */
|
||||
private function field(string $label, string $html, bool $wide = false): void {
|
||||
echo '<div class="aksrt-native-field' . ($wide ? ' is-wide' : '') . '">';
|
||||
echo '<span class="aksrt-native-field__label">' . esc_html($label) . '</span>';
|
||||
echo $html; // phpcs:ignore WordPress.Security.EscapeOutput -- 调用方已转义。
|
||||
echo '</div>';
|
||||
}
|
||||
|
||||
private function type_select(string $current): string {
|
||||
$html = '<select name="type">';
|
||||
foreach (['fixed' => __('固定金额', 'aksrt'), 'percent' => __('折扣百分比', 'aksrt')] as $k => $label) {
|
||||
$html .= sprintf('<option value="%s"%s>%s</option>', esc_attr($k), selected($current, $k, false), esc_html($label));
|
||||
/** 批量生成后一次性展示本批代码(transient 读取即删),附「复制全部」。 */
|
||||
private function render_generated_codes(): void {
|
||||
$key = 'aksrt_pay_coupon_codes_' . get_current_user_id();
|
||||
$codes = get_transient($key);
|
||||
if (!is_array($codes) || !$codes) {
|
||||
return;
|
||||
}
|
||||
return $html . '</select>';
|
||||
}
|
||||
|
||||
private function scope_fields(string $selected_type, string $ids_text): void {
|
||||
$select = '<select name="scope_type">';
|
||||
foreach ([
|
||||
'' => __('全部商品', 'aksrt'),
|
||||
'include' => __('仅指定商品 ID', 'aksrt'),
|
||||
'exclude' => __('排除商品 ID', 'aksrt'),
|
||||
'category' => __('指定分类 ID', 'aksrt'),
|
||||
] as $k => $label) {
|
||||
$select .= sprintf('<option value="%s"%s>%s</option>', esc_attr($k), selected($selected_type, $k, false), esc_html($label));
|
||||
}
|
||||
$select .= '</select>';
|
||||
$this->field(__('适用范围', 'aksrt'), $select);
|
||||
$this->field(
|
||||
__('范围 ID', 'aksrt'),
|
||||
'<input type="text" name="scope_ids" value="' . esc_attr($ids_text) . '" placeholder="' . esc_attr__('逗号分隔,如 12,34', 'aksrt') . '" />'
|
||||
);
|
||||
}
|
||||
|
||||
private function render_generated_dump(): void {
|
||||
if (!empty($_GET['aksrt_coupon_generated'])) {
|
||||
$generated = (int) $_GET['aksrt_coupon_generated'];
|
||||
echo '<div class="notice notice-success"><p>' . esc_html(sprintf(
|
||||
delete_transient($key);
|
||||
$text = implode("\n", array_map('strval', $codes));
|
||||
$copy = '<button type="button" class="button button-small" data-clipboard-text="' . esc_attr($text) . '">'
|
||||
. '<span class="dashicons dashicons-admin-page" aria-hidden="true"></span>' . esc_html__('复制全部', 'aksrt') . '</button>';
|
||||
NativeUi::card_open(
|
||||
sprintf(
|
||||
/* translators: %d count */
|
||||
__('成功生成 %d 个优惠码。', 'aksrt'),
|
||||
$generated
|
||||
)) . '</p></div>';
|
||||
}
|
||||
$generated_codes = get_transient('aksrt_pay_coupon_codes_' . get_current_user_id());
|
||||
if (is_array($generated_codes) && $generated_codes) {
|
||||
delete_transient('aksrt_pay_coupon_codes_' . get_current_user_id());
|
||||
NativeUi::card_open(__('本次生成优惠码(请及时复制保存)', 'aksrt'));
|
||||
echo '<textarea class="large-text code" rows="' . esc_attr((string) min(12, max(3, count($generated_codes)))) . '" readonly onclick="this.select();">' . esc_textarea(implode("\n", $generated_codes)) . '</textarea>';
|
||||
NativeUi::card_close();
|
||||
}
|
||||
__('本次生成的 %d 个优惠码', 'aksrt'),
|
||||
count($codes)
|
||||
),
|
||||
$copy,
|
||||
false,
|
||||
'aksrt-coupon-generated'
|
||||
);
|
||||
echo '<p class="aksrt-native-field__hint">' . esc_html__('离开或刷新本页后不再显示,请及时复制保存。', 'aksrt') . '</p>';
|
||||
echo '<textarea class="large-text code" rows="' . esc_attr((string) min(12, max(3, count($codes)))) . '" readonly aria-label="' . esc_attr__('本次生成的优惠码', 'aksrt') . '">' . esc_textarea($text) . '</textarea>';
|
||||
NativeUi::card_close();
|
||||
}
|
||||
|
||||
private function render_list(\AKSRT\Payment\Coupon $svc): void {
|
||||
@@ -265,7 +171,7 @@ class PayCoupons {
|
||||
echo '<th>ID</th><th>' . esc_html__('代码', 'aksrt') . '</th><th>' . esc_html__('类型', 'aksrt') . '</th><th>' . esc_html__('面值', 'aksrt') . '</th><th>' . esc_html__('门槛/封顶', 'aksrt') . '</th><th>' . esc_html__('范围', 'aksrt') . '</th><th>' . esc_html__('已用/上限/每人', 'aksrt') . '</th><th>' . esc_html__('状态', 'aksrt') . '</th><th>' . esc_html__('过期', 'aksrt') . '</th><th>' . esc_html__('操作', 'aksrt') . '</th>';
|
||||
echo '</tr></thead><tbody>';
|
||||
if (!$items) {
|
||||
echo NativeUi::empty_row(10, __('暂无优惠码', 'aksrt'), __('在上方创建或批量生成优惠码。', 'aksrt')); // phpcs:ignore WordPress.Security.EscapeOutput -- 内部构造,已转义。
|
||||
echo NativeUi::empty_row(10, __('暂无优惠码', 'aksrt'), __('点击右上角「新建优惠码」或「批量生成」添加。', 'aksrt')); // phpcs:ignore WordPress.Security.EscapeOutput -- 内部构造,已转义。
|
||||
}
|
||||
foreach ($items as $row) {
|
||||
$id = (int) ($row['id'] ?? 0);
|
||||
@@ -273,7 +179,9 @@ class PayCoupons {
|
||||
$row_type = (string) ($row['type'] ?? '');
|
||||
echo '<tr>';
|
||||
echo '<td>' . esc_html((string) $id) . '</td>';
|
||||
echo '<td><code>' . esc_html((string) ($row['code'] ?? '')) . '</code></td>';
|
||||
$code = (string) ($row['code'] ?? '');
|
||||
echo '<td><button type="button" class="aksrt-coupon-code aksrt-native-mono" data-clipboard-text="' . esc_attr($code) . '" aria-label="' . esc_attr(sprintf(__('复制优惠码 %s', 'aksrt'), $code)) . '">'
|
||||
. esc_html($code) . '<span class="dashicons dashicons-admin-page" aria-hidden="true"></span></button></td>';
|
||||
echo '<td>' . esc_html($type_labels[$row_type] ?? $row_type) . '</td>';
|
||||
echo '<td>' . esc_html((string) ($row['value'] ?? '')) . ($row_type === 'percent' ? '%' : '') . '</td>';
|
||||
echo '<td>' . esc_html((string) ($row['min_amount'] ?? 0)) . ' / ' . esc_html((string) ($row['max_discount'] ?? 0)) . '</td>';
|
||||
@@ -346,8 +254,6 @@ class PayCoupons {
|
||||
check_admin_referer('aksrt_pay_batch_coupons');
|
||||
|
||||
$ok = false;
|
||||
$created = 0;
|
||||
$codes = [];
|
||||
if (class_exists('\AKSRT\Payment\Coupon')) {
|
||||
$result = \AKSRT\Payment\Coupon::get_instance()->batch_create([
|
||||
'type' => sanitize_key((string) wp_unslash($_POST['type'] ?? 'fixed')),
|
||||
@@ -359,18 +265,14 @@ class PayCoupons {
|
||||
'product_scope' => $this->parse_product_scope_from_request(),
|
||||
'expires_at' => $this->normalize_expires_from_request(),
|
||||
], (int) ($_POST['count'] ?? 10), (int) ($_POST['length'] ?? 10), sanitize_text_field((string) wp_unslash($_POST['prefix'] ?? '')));
|
||||
$created = (int) ($result['created'] ?? 0);
|
||||
$codes = is_array($result['codes'] ?? null) ? $result['codes'] : [];
|
||||
$ok = $created > 0;
|
||||
$ok = (int) ($result['created'] ?? 0) > 0;
|
||||
if ($ok) {
|
||||
set_transient('aksrt_pay_coupon_codes_' . get_current_user_id(), $codes, 10 * MINUTE_IN_SECONDS);
|
||||
}
|
||||
}
|
||||
|
||||
wp_safe_redirect($this->page_url([
|
||||
'aksrt_pay_msg' => $ok ? 'coupon_batch_ok' : 'coupon_batch_failed',
|
||||
'aksrt_coupon_generated' => $created,
|
||||
]));
|
||||
wp_safe_redirect($this->page_url(['aksrt_pay_msg' => $ok ? 'coupon_batch_ok' : 'coupon_batch_failed']));
|
||||
exit;
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,200 @@
|
||||
<?php
|
||||
/**
|
||||
* 优惠码:新建 / 批量生成弹窗与编辑表单。
|
||||
*
|
||||
* 作为 flat sibling trait 被 PayCoupons 使用(PSR-4:trait 必须与宿主类同目录)。
|
||||
* 两个弹窗由页头按钮(data-aksrt-dialog-open)打开,交互在 admin-coupons.js;
|
||||
* 三张表单共用 render_rule_fields() 输出的优惠规则字段。
|
||||
*
|
||||
* @package AKSRT
|
||||
*/
|
||||
|
||||
namespace AKSRT\Admin\Native;
|
||||
|
||||
defined('ABSPATH') || exit;
|
||||
|
||||
trait PayCouponsForms {
|
||||
|
||||
private function render_create_dialog(): void {
|
||||
$this->dialog_open(
|
||||
self::CREATE_DIALOG,
|
||||
__('新建优惠码', 'aksrt'),
|
||||
__('手动指定一个优惠码,用户结算时输入即可抵扣。', 'aksrt'),
|
||||
'aksrt_pay_create_coupon'
|
||||
);
|
||||
echo '<div class="aksrt-native-form-grid">';
|
||||
$this->field(
|
||||
__('代码', 'aksrt'),
|
||||
'<input type="text" name="code" maxlength="60" required autofocus autocomplete="off" spellcheck="false" class="aksrt-native-mono">',
|
||||
__('需全站唯一,最多 60 个字符。', 'aksrt'),
|
||||
true
|
||||
);
|
||||
$this->render_rule_fields([
|
||||
'type' => 'fixed',
|
||||
'value' => '',
|
||||
'min_amount' => '0',
|
||||
'max_discount' => '0',
|
||||
'usage_limit' => '0',
|
||||
'per_user_limit' => '0',
|
||||
]);
|
||||
echo '</div>';
|
||||
$this->dialog_close(__('创建优惠码', 'aksrt'));
|
||||
}
|
||||
|
||||
private function render_batch_dialog(): void {
|
||||
$this->dialog_open(
|
||||
self::BATCH_DIALOG,
|
||||
__('批量生成优惠码', 'aksrt'),
|
||||
__('按相同规则随机生成一批优惠码,生成后会在页面上列出供复制。', 'aksrt'),
|
||||
'aksrt_pay_batch_coupons'
|
||||
);
|
||||
echo '<h3 class="aksrt-coupon-section">' . esc_html__('生成规则', 'aksrt') . '</h3>';
|
||||
echo '<div class="aksrt-native-form-grid aksrt-coupon-batch-grid">';
|
||||
$this->field(__('数量', 'aksrt'), '<input type="number" name="count" min="1" max="100" step="1" value="10" required autofocus>', __('单次 1–100 个。', 'aksrt'));
|
||||
$this->field(__('随机位数', 'aksrt'), '<input type="number" name="length" min="6" max="24" step="1" value="10" required>', __('6–24 位,不含前缀。', 'aksrt'));
|
||||
$this->field(__('前缀', 'aksrt'), '<input type="text" name="prefix" maxlength="36" autocomplete="off" spellcheck="false" class="aksrt-native-mono">', __('选填,如 VIP2026-。', 'aksrt'));
|
||||
echo '</div>';
|
||||
echo '<h3 class="aksrt-coupon-section">' . esc_html__('优惠规则', 'aksrt') . '</h3>';
|
||||
echo '<div class="aksrt-native-form-grid">';
|
||||
$this->render_rule_fields([
|
||||
'type' => 'fixed',
|
||||
'value' => '10',
|
||||
'min_amount' => '0',
|
||||
'max_discount' => '0',
|
||||
'usage_limit' => '1',
|
||||
'per_user_limit' => '1',
|
||||
]);
|
||||
echo '</div>';
|
||||
$this->dialog_close(__('批量生成', 'aksrt'));
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string,mixed> $row
|
||||
*/
|
||||
private function render_edit_form(array $row): void {
|
||||
$id = (int) ($row['id'] ?? 0);
|
||||
$scope = is_array($row['product_scope'] ?? null) ? $row['product_scope'] : [];
|
||||
$expires = (string) ($row['expires_at'] ?? '');
|
||||
|
||||
$title = sprintf(
|
||||
/* translators: %d coupon id */
|
||||
__('编辑优惠码 #%d', 'aksrt'),
|
||||
$id
|
||||
);
|
||||
$back = NativeUi::button_link(__('返回列表', 'aksrt'), $this->page_url(), false, 'dashicons-arrow-left-alt');
|
||||
|
||||
NativeUi::card_open($title, $back);
|
||||
echo '<form method="post" action="' . esc_url(admin_url('admin-post.php')) . '" data-aksrt-coupon-form data-busy-label="' . esc_attr__('正在保存…', 'aksrt') . '">';
|
||||
echo '<input type="hidden" name="action" value="aksrt_pay_update_coupon" />';
|
||||
echo '<input type="hidden" name="coupon_id" value="' . esc_attr((string) $id) . '" />';
|
||||
wp_nonce_field('aksrt_pay_update_coupon_' . $id);
|
||||
echo '<div class="aksrt-native-form-grid">';
|
||||
$this->field(__('代码', 'aksrt'), '<input type="text" value="' . esc_attr((string) ($row['code'] ?? '')) . '" readonly class="aksrt-native-mono" />', __('代码创建后不可修改。', 'aksrt'));
|
||||
$this->render_rule_fields([
|
||||
'type' => (string) ($row['type'] ?? 'fixed'),
|
||||
'value' => (string) ($row['value'] ?? ''),
|
||||
'min_amount' => (string) ($row['min_amount'] ?? '0'),
|
||||
'max_discount' => (string) ($row['max_discount'] ?? '0'),
|
||||
'usage_limit' => (string) ($row['usage_limit'] ?? '0'),
|
||||
'per_user_limit' => (string) ($row['per_user_limit'] ?? '0'),
|
||||
'scope_type' => sanitize_key((string) ($scope['type'] ?? '')),
|
||||
'scope_ids' => implode(',', array_map('intval', (array) ($scope['ids'] ?? []))),
|
||||
'expires_at' => $expires !== '' ? str_replace(' ', 'T', substr($expires, 0, 16)) : '',
|
||||
]);
|
||||
echo '</div>';
|
||||
echo '<div class="aksrt-native-form-foot">';
|
||||
echo '<button type="submit" class="button button-primary" data-aksrt-coupon-submit>' . esc_html__('保存修改', 'aksrt') . '</button>';
|
||||
echo '</div>';
|
||||
echo '</form>';
|
||||
NativeUi::card_close();
|
||||
}
|
||||
|
||||
/**
|
||||
* 三张表单共用的优惠规则字段;类型与范围的联动由 admin-coupons.js 处理。
|
||||
*
|
||||
* @param array<string,string> $v
|
||||
*/
|
||||
private function render_rule_fields(array $v): void {
|
||||
$type = ($v['type'] ?? '') === 'percent' ? 'percent' : 'fixed';
|
||||
$percent = $type === 'percent';
|
||||
$currency = $this->currency_symbol();
|
||||
|
||||
$this->field(__('类型', 'aksrt'), $this->type_select($type));
|
||||
$this->field(
|
||||
__('面值', 'aksrt'),
|
||||
'<span class="aksrt-coupon-inline"><input type="number" name="value" min="0" step="' . ($percent ? '1' : '0.01') . '"' . ($percent ? ' max="100"' : '')
|
||||
. ' value="' . esc_attr($v['value'] ?? '') . '" required>'
|
||||
. '<span class="aksrt-coupon-unit" data-aksrt-coupon-unit data-fixed="' . esc_attr($currency) . '" data-percent="%">' . esc_html($percent ? '%' : $currency) . '</span></span>',
|
||||
__('固定金额直接抵扣;折扣百分比填 20 表示减免 20%(0–100 的整数)。', 'aksrt')
|
||||
);
|
||||
$this->field(__('最低消费', 'aksrt'), $this->money_input('min_amount', $v['min_amount'] ?? '0'), __('订单金额达到该值才可使用,0 表示无门槛。', 'aksrt'));
|
||||
$this->field(__('最高优惠', 'aksrt'), $this->money_input('max_discount', $v['max_discount'] ?? '0'), __('折扣百分比的封顶金额,0 表示不封顶。', 'aksrt'));
|
||||
$this->field(__('总次数', 'aksrt'), '<input type="number" name="usage_limit" min="0" step="1" value="' . esc_attr($v['usage_limit'] ?? '0') . '">', __('所有用户合计可用次数,0 表示不限。', 'aksrt'));
|
||||
$this->field(__('每人限次', 'aksrt'), '<input type="number" name="per_user_limit" min="0" step="1" value="' . esc_attr($v['per_user_limit'] ?? '0') . '">', __('单个用户可用次数,0 表示不限。', 'aksrt'));
|
||||
|
||||
$select = '<select name="scope_type">';
|
||||
foreach ([
|
||||
'' => __('全部商品', 'aksrt'),
|
||||
'include' => __('仅指定商品 ID', 'aksrt'),
|
||||
'exclude' => __('排除商品 ID', 'aksrt'),
|
||||
'category' => __('指定分类 ID', 'aksrt'),
|
||||
] as $k => $label) {
|
||||
$select .= sprintf('<option value="%s"%s>%s</option>', esc_attr($k), selected($v['scope_type'] ?? '', $k, false), esc_html($label));
|
||||
}
|
||||
$select .= '</select>';
|
||||
$this->field(__('适用范围', 'aksrt'), $select);
|
||||
$this->field(
|
||||
__('范围 ID', 'aksrt'),
|
||||
'<input type="text" name="scope_ids" value="' . esc_attr($v['scope_ids'] ?? '') . '" placeholder="' . esc_attr__('如 12,34', 'aksrt') . '" autocomplete="off">',
|
||||
__('逗号分隔;选择「全部商品」时无需填写。', 'aksrt')
|
||||
);
|
||||
$this->field(
|
||||
__('过期时间', 'aksrt'),
|
||||
'<input type="datetime-local" name="expires_at" value="' . esc_attr($v['expires_at'] ?? '') . '">',
|
||||
__('留空表示永不过期。', 'aksrt')
|
||||
);
|
||||
}
|
||||
|
||||
private function money_input(string $name, string $value): string {
|
||||
return '<input type="number" name="' . esc_attr($name) . '" min="0" step="0.01" value="' . esc_attr($value) . '">';
|
||||
}
|
||||
|
||||
private function type_select(string $current): string {
|
||||
$html = '<select name="type">';
|
||||
foreach (['fixed' => __('固定金额', 'aksrt'), 'percent' => __('折扣百分比', 'aksrt')] as $k => $label) {
|
||||
$html .= sprintf('<option value="%s"%s>%s</option>', esc_attr($k), selected($current, $k, false), esc_html($label));
|
||||
}
|
||||
return $html . '</select>';
|
||||
}
|
||||
|
||||
/** 单字段单元(.aksrt-native-field);$html 为调用方已转义的控件片段。 */
|
||||
private function field(string $label, string $html, string $hint = '', bool $wide = false): void {
|
||||
echo '<label class="aksrt-native-field' . ($wide ? ' is-wide' : '') . '">';
|
||||
echo '<span class="aksrt-native-field__label">' . esc_html($label) . '</span>';
|
||||
echo $html; // phpcs:ignore WordPress.Security.EscapeOutput -- 调用方已转义。
|
||||
if ($hint !== '') {
|
||||
echo '<small class="aksrt-native-field__hint">' . esc_html($hint) . '</small>';
|
||||
}
|
||||
echo '</label>';
|
||||
}
|
||||
|
||||
private function dialog_open(string $id, string $title, string $description, string $action): void {
|
||||
echo '<dialog class="aksrt-coupon-dialog" id="' . esc_attr($id) . '" aria-labelledby="' . esc_attr($id) . '-title" aria-describedby="' . esc_attr($id) . '-description">';
|
||||
echo '<form method="post" action="' . esc_url(admin_url('admin-post.php')) . '" class="aksrt-coupon-dialog__frame" data-aksrt-coupon-form data-busy-label="' . esc_attr__('正在提交…', 'aksrt') . '">';
|
||||
echo '<input type="hidden" name="action" value="' . esc_attr($action) . '">';
|
||||
wp_nonce_field($action);
|
||||
echo '<header class="aksrt-coupon-dialog__head"><div><h2 id="' . esc_attr($id) . '-title">' . esc_html($title) . '</h2><p id="' . esc_attr($id) . '-description">' . esc_html($description) . '</p></div>';
|
||||
echo '<button type="button" class="aksrt-coupon-dialog__close" data-aksrt-dialog-close aria-label="' . esc_attr__('关闭弹窗', 'aksrt') . '"><span class="dashicons dashicons-no-alt" aria-hidden="true"></span></button></header>';
|
||||
echo '<div class="aksrt-coupon-dialog__body">';
|
||||
}
|
||||
|
||||
private function dialog_close(string $submit_label): void {
|
||||
echo '</div><footer class="aksrt-coupon-dialog__foot"><button type="button" class="button" data-aksrt-dialog-close>' . esc_html__('取消', 'aksrt') . '</button>';
|
||||
echo '<button type="submit" class="button button-primary" data-aksrt-coupon-submit>' . esc_html($submit_label) . '</button></footer></form></dialog>';
|
||||
}
|
||||
|
||||
private function currency_symbol(): string {
|
||||
$paid = \AKSRT\Settings\Settings::get_paid_content_settings();
|
||||
return (string) ($paid['display']['currency_symbol'] ?? '¥');
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user