feat(invite-code): admin page rebuilt as server-rendered three-view ops UI

对齐参考主题的邀请码运营页 UI/UX(布局与交互模式为自研实现):
- 三视图切换:列表 / 添加邀请码 / 导出邀请码(page-title-action 按钮)
- 列表:subsubsub 状态筛选(全部/未使用/已使用)、关键字搜索、批量删除、
  可排序表头(邀请码/创建时间/更新时间/状态/标识,orderby 箭头)、
  点击复制邀请码 + 复制成功浮层、标识点击定位、分页条
- 状态列:未使用(蓝)/已使用(红)+使用者链接,复用使用记录表
- 添加视图:添加方式按钮组(系统自动生成/导入邀请码)、生成数量(默认20/上限1000)、
  标识(默认 invita_YmdHis)、使用奖励字段集(经验值/积分/余额/VIP+赠送时长依赖显示)、
  高级选项折叠(自定义位数)、导入区格式说明与数据示例
- 导出视图:状态选择 + 文本文档/Excel表格 双格式 + 文本分隔符
- 传输层从 fetch+JSON 改为 admin_post 表单提交 + 回跳提示;
  管理端 REST 全部移除(保留公开 verify),死代码清理
- 建表新增 updated_at(消费/生成/导入维护),列表'更新时间'列与默认排序依据
- 契约测试 357→358 项固化新架构
This commit is contained in:
2026-09-21 21:31:16 +08:00
parent a5f0484466
commit 8d9cca2fe5
5 changed files with 605 additions and 431 deletions
+335 -259
View File
@@ -1,6 +1,9 @@
<?php
/**
* Native invite-code operations.
* Native invite-code operations page.
*
* 视图结构(列表 / 添加 / 导出)对齐参考主题的运营后台交互:
* 服务端渲染 + 表单提交 + 结果回跳提示,无 AJAX 依赖。
*
* @package AKSRT
*/
@@ -15,279 +18,352 @@ trait UsersMenusInviteCode {
if (!current_user_can('edit_users')) {
wp_die(esc_html__('您没有权限访问此页面。', 'aksrt'));
}
$endpoint = rest_url('aksrt/v1/invite-codes');
$nonce = wp_create_nonce('wp_rest');
$service = \AKSRT\Payment\InviteCode::get_instance();
$this_url = admin_url('users.php?page=aksrt_invite_codes');
$tab = isset($_GET['tab']) ? sanitize_key((string) wp_unslash($_GET['tab'])) : '';
if (!in_array($tab, ['add', 'export'], true)) {
$tab = '';
}
$nonce = wp_create_nonce('aksrt_invite_admin');
// 功能未启用提示(置顶橙色提醒)。
$settings = $service->registration_settings();
if (empty($settings['enabled'])) {
$settings_url = admin_url('admin.php?page=aksrt-settings');
echo '<div class="notice notice-warning"><p style="color:#fb590a;">'
. esc_html__('注意:邀请码功能暂未启用。您可以在', 'aksrt')
. ' <a href="' . esc_url($settings_url) . '">' . esc_html__('登录注册设置', 'aksrt') . '</a> '
. esc_html__('中启用此功能', 'aksrt')
. '</p></div>';
}
// 操作结果回跳提示:标题 + 说明,成功 / 错误两种形态。
$inv_title = isset($_GET['aksrt_inv_title']) ? sanitize_text_field(rawurldecode((string) wp_unslash($_GET['aksrt_inv_title']))) : '';
$inv_msg = isset($_GET['aksrt_inv_msg']) ? sanitize_text_field(rawurldecode((string) wp_unslash($_GET['aksrt_inv_msg']))) : '';
$inv_type = isset($_GET['aksrt_inv_type']) && $_GET['aksrt_inv_type'] === 'error' ? 'error' : 'success';
if ($inv_title !== '') {
echo '<div class="notice notice-' . esc_attr($inv_type) . ' is-dismissible"><h3>' . esc_html($inv_title) . '</h3>'
. ($inv_msg !== '' ? '<p>' . esc_html($inv_msg) . '</p>' : '') . '</div>';
}
?>
<div class="wrap" id="aksrt-invite-ops">
<h1><?php esc_html_e('邀请码管理', 'aksrt'); ?></h1>
<p><?php esc_html_e('一次性邀请码用于控制注册并发放注册奖励。每个码可限制使用次数与有效期,奖励在注册(或完成邮箱验证)后自动发放。', 'aksrt'); ?></p>
<h2><?php esc_html_e('批量生成', 'aksrt'); ?></h2>
<div class="tablenav top">
<div class="alignleft actions">
<label for="aksrt-inv-count"><?php esc_html_e('数量', 'aksrt'); ?></label>
<input type="number" id="aksrt-inv-count" min="1" max="500" value="10" class="small-text">
<label for="aksrt-inv-max-uses"><?php esc_html_e('每码可用次数', 'aksrt'); ?></label>
<input type="number" id="aksrt-inv-max-uses" min="0" max="9999" value="1" class="small-text">
<label for="aksrt-inv-exp-days"><?php esc_html_e('有效天数', 'aksrt'); ?></label>
<input type="number" id="aksrt-inv-exp-days" min="0" max="3650" value="30" class="small-text">
<label for="aksrt-inv-points"><?php esc_html_e('积分奖励', 'aksrt'); ?></label>
<input type="number" id="aksrt-inv-points" min="0" value="0" class="small-text">
<label for="aksrt-inv-balance"><?php esc_html_e('余额奖励(元)', 'aksrt'); ?></label>
<input type="number" id="aksrt-inv-balance" min="0" step="0.01" value="0" class="small-text">
<label for="aksrt-inv-vip-level"><?php esc_html_e('赠VIP', 'aksrt'); ?></label>
<select id="aksrt-inv-vip-level">
<option value="0"><?php esc_html_e('不赠送', 'aksrt'); ?></option>
<option value="1"><?php esc_html_e('一级', 'aksrt'); ?></option>
<option value="2"><?php esc_html_e('二级', 'aksrt'); ?></option>
</select>
<label for="aksrt-inv-vip-days"><?php esc_html_e('VIP天数', 'aksrt'); ?></label>
<input type="number" id="aksrt-inv-vip-days" min="0" value="0" class="small-text">
<label for="aksrt-inv-level-points"><?php esc_html_e('等级积分', 'aksrt'); ?></label>
<input type="number" id="aksrt-inv-level-points" min="0" value="0" class="small-text">
<label for="aksrt-inv-remark"><?php esc_html_e('备注', 'aksrt'); ?></label>
<input type="text" id="aksrt-inv-remark" maxlength="191" class="regular-text">
<button type="button" class="button button-primary" id="aksrt-inv-generate"><?php esc_html_e('生成', 'aksrt'); ?></button>
<button type="button" class="button" id="aksrt-inv-import-toggle"><?php esc_html_e('导入', 'aksrt'); ?></button>
<a class="button" id="aksrt-inv-export" href="<?php echo esc_url(add_query_arg('_wpnonce', $nonce, rest_url('aksrt/v1/invite-codes/export'))); ?>"><?php esc_html_e('导出 CSV', 'aksrt'); ?></a>
<a class="button" id="aksrt-inv-export-text" href="<?php echo esc_url(add_query_arg('_wpnonce', $nonce, rest_url('aksrt/v1/invite-codes/export-text'))); ?>"><?php esc_html_e('导出文本', 'aksrt'); ?></a>
</div>
</div>
<div id="aksrt-inv-import-panel" style="display:none;">
<p>
<?php esc_html_e('一行一个邀请码,单行格式:', 'aksrt'); ?>
<code><?php esc_html_e('邀请码 分隔符 奖励 分隔符 标识', 'aksrt'); ?></code>
(<?php esc_html_e('第三段标识将作为备注保存', 'aksrt'); ?>)
</p>
<p>
<?php esc_html_e('奖励参数串(与 Zibll 兼容):', 'aksrt'); ?>
<code>points=20&balance=30&vip=1&vip_time=5&level_integral=100</code>
<?php esc_html_e(',无需奖励填', 'aksrt'); ?> <code><?php esc_html_e('无', 'aksrt'); ?></code><?php esc_html_e('。示例:', 'aksrt'); ?><code>93FW0XAY 无 没有奖励</code>
</p>
<p>
<label for="aksrt-inv-import-division"><?php esc_html_e('分隔符', 'aksrt'); ?></label>
<input type="text" id="aksrt-inv-import-division" value=" " maxlength="4" class="small-text">
<label for="aksrt-inv-import-max-uses"><?php esc_html_e('每码可用次数', 'aksrt'); ?></label>
<input type="number" id="aksrt-inv-import-max-uses" min="0" max="9999" value="1" class="small-text">
<label for="aksrt-inv-import-exp-days"><?php esc_html_e('有效天数', 'aksrt'); ?></label>
<input type="number" id="aksrt-inv-import-exp-days" min="0" max="3650" value="0" class="small-text">
</p>
<p><textarea id="aksrt-inv-import-data" rows="8" class="large-text code" style="resize:both;" placeholder="93FW0XAY 无 没有奖励&#10;P86NPWKI points=10&#10;AUF9D2B4 balance=30&amp;vip=1&amp;vip_time=5"></textarea></p>
<p><button type="button" class="button button-primary" id="aksrt-inv-import-submit"><?php esc_html_e('开始导入', 'aksrt'); ?></button></p>
</div>
<div id="aksrt-inv-generated" style="display:none;">
<p><strong><?php esc_html_e('本批邀请码(点击复制):', 'aksrt'); ?></strong></p>
<p id="aksrt-inv-codes" style="user-select:all;word-break:break-all;"></p>
</div>
<h2><?php esc_html_e('邀请码列表', 'aksrt'); ?></h2>
<div class="tablenav top">
<div class="alignleft actions">
<select id="aksrt-inv-status">
<option value=""><?php esc_html_e('全部状态', 'aksrt'); ?></option>
<option value="active"><?php esc_html_e('启用', 'aksrt'); ?></option>
<option value="disabled"><?php esc_html_e('禁用', 'aksrt'); ?></option>
</select>
<input type="search" id="aksrt-inv-search" placeholder="<?php esc_attr_e('搜索邀请码或批次', 'aksrt'); ?>">
<button type="button" class="button" id="aksrt-inv-filter"><?php esc_html_e('筛选', 'aksrt'); ?></button>
</div>
</div>
<div id="aksrt-inv-notice" role="status" aria-live="polite"></div>
<table class="wp-list-table widefat fixed striped">
<thead><tr>
<th><?php esc_html_e('邀请码', 'aksrt'); ?></th>
<th><?php esc_html_e('批次', 'aksrt'); ?></th>
<th><?php esc_html_e('备注', 'aksrt'); ?></th>
<th><?php esc_html_e('奖励', 'aksrt'); ?></th>
<th style="text-align:right;"><?php esc_html_e('已用/上限', 'aksrt'); ?></th>
<th><?php esc_html_e('使用者', 'aksrt'); ?></th>
<th><?php esc_html_e('状态', 'aksrt'); ?></th>
<th><?php esc_html_e('过期时间', 'aksrt'); ?></th>
<th><?php esc_html_e('创建时间', 'aksrt'); ?></th>
<th><?php esc_html_e('操作', 'aksrt'); ?></th>
</tr></thead>
<tbody id="aksrt-inv-rows"><tr><td colspan="10"><?php esc_html_e('正在加载…', 'aksrt'); ?></td></tr></tbody>
</table>
<div class="tablenav bottom"><div class="tablenav-pages" id="aksrt-inv-pages"></div></div>
<div class="wrap aksrt-inv-page">
<style>
/* 排序箭头:默认弱化,悬停加强。 */
.aksrt-inv-page .orderby-but { position: relative; display: inline-block; }
.aksrt-inv-page .orderby-but > a { opacity: .4; position: absolute; transform: translateY(-3px); transition: .3s; }
.aksrt-inv-page .orderby-but > a + a { transform: translateY(6px); }
.aksrt-inv-page .orderby-but:hover a { opacity: .6; }
.aksrt-inv-page .orderby-but > a:hover { opacity: 1; }
/* 选项字段布局:左标题右控件,行间分隔线。 */
.aksrt-inv-field { display: flex; align-items: flex-start; padding: 14px 0; border-bottom: 1px solid #f0f0f1; }
.aksrt-inv-field > label { flex: 0 0 170px; font-weight: 600; padding-top: 4px; }
.aksrt-inv-field > .aksrt-inv-control { flex: 1; }
.aksrt-inv-field .description { display: block; margin-top: 4px; color: #646970; }
.aksrt-inv-submessage { background: #fff8e5; border-left: 4px solid #ffb900; box-shadow: 0 1px 1px rgba(0,0,0,.08); padding: 10px 14px; margin: 12px 0; }
.aksrt-inv-submessage li { list-style: disc; margin-left: 18px; }
.aksrt-inv-btnset label { display: inline-block; margin-right: -1px; border: 1px solid #2271b1; background: #fff; padding: 4px 14px; cursor: pointer; }
.aksrt-inv-btnset label:first-child { border-radius: 4px 0 0 4px; }
.aksrt-inv-btnset label:last-child { border-radius: 0 4px 4px 0; }
.aksrt-inv-btnset input { display: none; }
.aksrt-inv-btnset label.on { background: #2271b1; color: #fff; }
.aksrt-inv-switch { display: inline-flex; align-items: center; gap: 6px; cursor: pointer; }
.aksrt-inv-switch input { margin: 0; }
.aksrt-inv-mini { width: 80px; }
.aksrt-inv-submit { background: linear-gradient(135deg, #2f9bff, #2271b1) !important; border-color: #2271b1 !important; color: #fff !important; padding: 4px 24px !important; border-radius: 4px !important; }
.aksrt-inv-code { cursor: pointer; }
.aksrt-inv-toast { position: fixed; top: 42px; left: 50%; transform: translateX(-50%); background: rgba(0,0,0,.75); color: #fff; padding: 8px 22px; border-radius: 4px; font-size: 13px; display: none; z-index: 100100; }
.aksrt-inv-unit { color: #646970; margin-left: 4px; }
</style>
<?php if ($tab === '') : ?>
<?php $this->render_invite_codes_list($service, $this_url, $nonce); ?>
<?php elseif ($tab === 'add') : ?>
<?php $this->render_invite_codes_add($this_url, $nonce); ?>
<?php else : ?>
<?php $this->render_invite_codes_export($this_url, $nonce); ?>
<?php endif; ?>
</div>
<div class="aksrt-inv-toast" id="aksrt-inv-toast"><?php esc_html_e('复制成功', 'aksrt'); ?></div>
<script>
(() => {
const init = () => {
const root = document.getElementById('aksrt-invite-ops');
if (!root || root.dataset.aksrtInviteReady === '1') return;
root.dataset.aksrtInviteReady = '1';
const endpoint = <?php echo wp_json_encode($endpoint); ?>;
const nonce = <?php echo wp_json_encode($nonce); ?>;
const rows = root.querySelector('#aksrt-inv-rows');
const pages = root.querySelector('#aksrt-inv-pages');
const notice = root.querySelector('#aksrt-inv-notice');
const search = root.querySelector('#aksrt-inv-search');
const status = root.querySelector('#aksrt-inv-status');
const filter = root.querySelector('#aksrt-inv-filter');
const generated = root.querySelector('#aksrt-inv-generated');
const generatedCodes = root.querySelector('#aksrt-inv-codes');
let currentPage = 1;
const escapeHtml = (value) => String(value ?? '').replace(/[&<>'"]/g, (char) => ({
'&': '&amp;', '<': '&lt;', '>': '&gt;', "'": '&#039;', '"': '&quot;'
})[char]);
const setNotice = (message, isError = false) => {
notice.className = message ? `notice notice-${isError ? 'error' : 'success'} inline` : '';
notice.innerHTML = message ? `<p>${escapeHtml(message)}</p>` : '';
};
const request = async (url, options = {}) => {
const response = await fetch(url, {
credentials: 'same-origin',
...options,
headers: { 'X-WP-Nonce': nonce, 'Content-Type': 'application/json', ...(options.headers || {}) },
// 依赖切换:添加方式 / 高级选项 / VIP 时长。
const sync = () => {
document.querySelectorAll('[data-aksrt-inv-dep]').forEach((el) => {
const [name, value] = el.dataset.aksrtInvDep.split('=');
const input = document.querySelector(`[name="${name}"]:checked`) || document.querySelector(`[name="${name}"]`);
const show = input ? String(input.type === 'checkbox' ? (input.checked ? '1' : '') : input.value) === value : false;
el.style.display = show ? '' : 'none';
});
document.querySelectorAll('.aksrt-inv-btnset').forEach((group) => {
group.querySelectorAll('label').forEach((label) => label.classList.toggle('on', label.querySelector('input').checked));
});
const payload = await response.json().catch(() => ({}));
if (!response.ok) throw new Error(payload.message || '<?php echo esc_js(__('请求失败', 'aksrt')); ?>');
return payload;
};
const rewardText = (rewards) => {
const parts = [];
if (Number(rewards.points) > 0) parts.push(`<?php echo esc_js(__('积分', 'aksrt')); ?>+${rewards.points}`);
if (Number(rewards.balance_minor) > 0) parts.push(`<?php echo esc_js(__('余额', 'aksrt')); ?>+${(Number(rewards.balance_minor) / 100).toFixed(2)}`);
if (Number(rewards.vip_level) > 0 && Number(rewards.vip_days) > 0) parts.push(`VIP${rewards.vip_level}×${rewards.vip_days}${'<?php echo esc_js(__('天', 'aksrt')); ?>'}`);
if (Number(rewards.level_points) > 0) parts.push(`<?php echo esc_js(__('等级积分', 'aksrt')); ?>+${rewards.level_points}`);
return parts.join(' / ') || '—';
};
const statusText = (item) => item.expired
? '<?php echo esc_js(__('已过期', 'aksrt')); ?>'
: ({active: '<?php echo esc_js(__('启用', 'aksrt')); ?>', disabled: '<?php echo esc_js(__('禁用', 'aksrt')); ?>'}[item.status] || item.status);
const load = async (page = 1) => {
currentPage = page;
setNotice('');
rows.innerHTML = '<tr><td colspan="10"><?php echo esc_js(__('正在加载…', 'aksrt')); ?></td></tr>';
const url = new URL(endpoint);
url.searchParams.set('page', String(page));
url.searchParams.set('per_page', '20');
if (status.value) url.searchParams.set('status', status.value);
if (search.value.trim()) url.searchParams.set('search', search.value.trim());
document.addEventListener('change', sync);
// 点击复制邀请码,悬浮提示结果。
const toast = document.getElementById('aksrt-inv-toast');
document.addEventListener('click', async (event) => {
const target = event.target.closest('[data-clipboard-text]');
if (!target) return;
try {
const data = await request(url.toString());
rows.innerHTML = data.items.length ? data.items.map((item) => `
<tr>
<td><code style="user-select:all;">${escapeHtml(item.code)}</code></td>
<td><small>${escapeHtml(item.batch_id || '—')}</small></td>
<td>${escapeHtml(item.remark || '—')}</td>
<td>${escapeHtml(rewardText(item.rewards))}</td>
<td style="text-align:right;">${Number(item.used_count)}/${item.max_uses > 0 ? Number(item.max_uses) : '∞'}</td>
<td>${(item.recent_users || []).map((u) => escapeHtml(u.name)).join('、') || '—'}</td>
<td>${escapeHtml(statusText(item))}</td>
<td>${item.expires_at ? escapeHtml(item.expires_at) : '—'}</td>
<td>${escapeHtml(item.created_at)}</td>
<td>${item.status === 'active' && !item.expired
? `<button class="button" data-inv-action="disable" data-inv-id="${Number(item.id)}"><?php echo esc_js(__('禁用', 'aksrt')); ?></button>`
: `<button class="button" data-inv-action="enable" data-inv-id="${Number(item.id)}"><?php echo esc_js(__('启用', 'aksrt')); ?></button>`}</td>
</tr>`).join('') : '<tr><td colspan="10"><?php echo esc_js(__('暂无邀请码', 'aksrt')); ?></td></tr>';
pages.innerHTML = Array.from({length: Number(data.max_pages || 1)}, (_, index) => {
const number = index + 1;
return `<button type="button" class="button ${number === Number(data.page) ? 'button-primary' : ''}" data-inv-page="${number}">${number}</button>`;
}).join(' ');
await navigator.clipboard.writeText(target.dataset.clipboardText);
if (toast) { toast.style.display = 'block'; setTimeout(() => { toast.style.display = 'none'; }, 1200); }
} catch (error) {
rows.innerHTML = '<tr><td colspan="10"><?php echo esc_js(__('邀请码数据加载失败', 'aksrt')); ?></td></tr>';
setNotice(error.message, true);
}
};
root.querySelector('#aksrt-inv-generate').addEventListener('click', async (event) => {
const button = event.currentTarget;
button.disabled = true;
try {
const data = await request(`${endpoint}/generate`, {
method: 'POST',
body: JSON.stringify({
count: Number(root.querySelector('#aksrt-inv-count').value) || 1,
max_uses: Number(root.querySelector('#aksrt-inv-max-uses').value) || 0,
expires_days: Number(root.querySelector('#aksrt-inv-exp-days').value) || 0,
remark: root.querySelector('#aksrt-inv-remark').value.trim(),
rewards: {
points: Number(root.querySelector('#aksrt-inv-points').value) || 0,
balance: Number(root.querySelector('#aksrt-inv-balance').value) || 0,
vip_level: Number(root.querySelector('#aksrt-inv-vip-level').value) || 0,
vip_days: Number(root.querySelector('#aksrt-inv-vip-days').value) || 0,
level_points: Number(root.querySelector('#aksrt-inv-level-points').value) || 0,
},
}),
});
generated.style.display = '';
generatedCodes.textContent = data.codes.join(', ');
setNotice(`<?php echo esc_js(__('已生成', 'aksrt')); ?> ${data.count} <?php echo esc_js(__('个邀请码', 'aksrt')); ?>`);
await load(1);
} catch (error) {
setNotice(error.message, true);
} finally {
button.disabled = false;
const range = document.createRange();
range.selectNodeContents(target);
const selection = getSelection();
selection.removeAllRanges();
selection.addRange(range);
}
});
root.querySelector('#aksrt-inv-import-toggle').addEventListener('click', (event) => {
const panel = root.querySelector('#aksrt-inv-import-panel');
panel.style.display = panel.style.display === 'none' ? '' : 'none';
event.currentTarget.setAttribute('aria-expanded', panel.style.display === 'none' ? 'false' : 'true');
});
root.querySelector('#aksrt-inv-import-submit').addEventListener('click', async (event) => {
const button = event.currentTarget;
const data = root.querySelector('#aksrt-inv-import-data').value;
if (!data.trim()) { setNotice('<?php echo esc_js(__('请粘贴需要导入的数据', 'aksrt')); ?>', true); return; }
button.disabled = true;
try {
const result = await request(`${endpoint}/import`, {
method: 'POST',
body: JSON.stringify({
data,
division: root.querySelector('#aksrt-inv-import-division').value || ' ',
max_uses: Number(root.querySelector('#aksrt-inv-import-max-uses').value) || 0,
expires_days: Number(root.querySelector('#aksrt-inv-import-exp-days').value) || 0,
}),
});
const failedDetail = (result.failed_codes || []).length
? `,<?php echo esc_js(__('失败:', 'aksrt')); ?>${result.failed_codes.join('、')}`
: '';
setNotice(`<?php echo esc_js(__('导入完成:成功', 'aksrt')); ?> ${result.imported} <?php echo esc_js(__('个', 'aksrt')); ?>` +
(result.failed ? `,<?php echo esc_js(__('失败', 'aksrt')); ?> ${result.failed} <?php echo esc_js(__('个', 'aksrt')); ?>` : '') + failedDetail,
result.failed > 0);
root.querySelector('#aksrt-inv-import-data').value = '';
await load(1);
} catch (error) {
setNotice(error.message, true);
} finally {
button.disabled = false;
}
});
filter.addEventListener('click', () => load(1));
search.addEventListener('keydown', (event) => { if (event.key === 'Enter') load(1); });
root.addEventListener('click', async (event) => {
const pageButton = event.target.closest('[data-inv-page]');
if (pageButton) return load(Number(pageButton.dataset.invPage));
const button = event.target.closest('[data-inv-action]');
if (!button) return;
button.disabled = true;
try {
await request(`${endpoint}/${Number(button.dataset.invId)}/${button.dataset.invAction}`, { method: 'POST', body: '{}' });
setNotice('<?php echo esc_js(__('邀请码状态已更新', 'aksrt')); ?>');
await load(currentPage);
} catch (error) {
setNotice(error.message, true);
button.disabled = false;
}
});
load();
};
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', init, { once: true });
document.addEventListener('DOMContentLoaded', sync, { once: true });
} else {
init();
sync();
}
})();
</script>
<?php
}
/** 列表视图:状态筛选、搜索、批量删除、排序、分页。 */
private function render_invite_codes_list(\AKSRT\Payment\InviteCode $service, string $this_url, string $nonce): void {
// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- 只读列表查询。
$status = in_array(($_GET['status'] ?? 'all'), ['all', 'unused', 'used'], true) ? (string) $_GET['status'] : 'all';
// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- 只读列表查询。
$s = isset($_GET['s']) ? sanitize_text_field((string) wp_unslash($_GET['s'])) : '';
// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- 只读列表查询。
$remark = isset($_GET['remark']) ? sanitize_text_field((string) wp_unslash($_GET['remark'])) : '';
$data = $service->list_codes([
'page' => isset($_GET['paged']) ? max(1, (int) $_GET['paged']) : 1, // phpcs:ignore WordPress.Security.NonceVerification.Recommended
'status' => $status,
's' => $s,
'remark' => $remark,
'orderby' => isset($_GET['orderby']) ? sanitize_key((string) wp_unslash($_GET['orderby'])) : '', // phpcs:ignore WordPress.Security.NonceVerification.Recommended
'desc' => isset($_GET['desc']) ? sanitize_key((string) wp_unslash($_GET['desc'])) : '', // phpcs:ignore WordPress.Security.NonceVerification.Recommended
]);
echo '<h1 class="wp-heading-inline">' . esc_html__('邀请码管理', 'aksrt') . '</h1>';
echo '<a href="' . esc_url(add_query_arg('tab', 'add', $this_url)) . '" class="page-title-action">' . esc_html__('添加邀请码', 'aksrt') . '</a>';
echo '<a href="' . esc_url(add_query_arg('tab', 'export', $this_url)) . '" class="page-title-action" style="margin-left:6px;">' . esc_html__('导出邀请码', 'aksrt') . '</a>';
echo '<hr class="wp-header-end">';
// 顶部筛选行:左侧状态链接(搜索时改为提示语),右侧搜索表单。
$search_html = '<div style="float:right;">
<form method="get"><input type="hidden" name="page" value="aksrt_invite_codes">
<input type="text" name="s" value="' . esc_attr($s) . '" placeholder="' . esc_attr__('搜索邀请码', 'aksrt') . '">
<button type="submit" class="button">' . esc_html__('提交', 'aksrt') . '</button></form></div>';
echo '<div style="margin:12px 0;min-height:32px;">';
echo '<ul class="subsubsub" style="float:left;margin:0 0 8px;">';
if ($s !== '') {
echo '<li style="display:inline-block;background:#fff8e5;border:1px solid #ffb900;padding:2px 10px;">'
. esc_html(sprintf(__('搜索 “%s” 的内容', 'aksrt'), $s)) . '</li>';
} else {
$links = [
'all' => __('全部', 'aksrt'),
'unused' => __('未使用', 'aksrt'),
'used' => __('已使用', 'aksrt'),
];
$parts = [];
foreach ($links as $key => $label) {
$url = $key === 'all' ? $this_url : add_query_arg('status', $key, $this_url);
$parts[] = '<li><a href="' . esc_url($url) . '"' . ($key === $status ? ' style="font-weight:600;"' : '') . '>' . esc_html($label) . '</a></li>';
}
echo implode(' | ', $parts); // phpcs:ignore WordPress.Security.EscapeOutput -- 各项均已转义。
}
echo '</ul>' . $search_html . '</div><div class="clear"></div>'; // phpcs:ignore WordPress.Security.EscapeOutput -- 静态结构。
// 可排序列:code / created_at / updated_at / used_count / remark。
$columns = [
['width' => '6%', 'key' => 'code', 'name' => __('邀请码', 'aksrt')],
['width' => '10%', 'key' => '', 'name' => __('使用奖励', 'aksrt')],
['width' => '10%', 'key' => 'created_at', 'name' => __('创建时间', 'aksrt')],
['width' => '10%', 'key' => 'updated_at', 'name' => __('更新时间', 'aksrt')],
['width' => '6%', 'key' => 'used_count', 'name' => __('状态', 'aksrt')],
['width' => '12%', 'key' => 'remark', 'name' => __('标识', 'aksrt')],
];
echo '<form method="post" action="' . esc_url(admin_url('admin-post.php')) . '">';
echo '<input type="hidden" name="action" value="aksrt_invite_delete">';
echo '<input type="hidden" name="aksrt_nonce" value="' . esc_attr($nonce) . '">';
echo '<div class="bulkactions" style="margin:10px 0;">
<select name="bulk_action" id="bulk-action-selector-top">
<option value="-1">' . esc_html__('批量操作', 'aksrt') . '</option>
<option value="delete">' . esc_html__('删除', 'aksrt') . '</option>
</select>
<button type="submit" class="button action" onclick="return this.form.bulk_action.value===\'delete\'||confirm(' . wp_json_encode(__('请先选择“删除”操作', 'aksrt')) . ');">' . esc_html__('应用', 'aksrt') . '</button>
</div>';
echo '<div style="overflow-y:auto;width:100%;">';
echo '<table class="widefat fixed striped posts table table-bordered" style="min-width:1000px;"><thead><tr>';
echo '<td id="cb" class="manage-column column-cb check-column" style="width:2%;"><input id="cb-select-all-1" type="checkbox" onclick="document.querySelectorAll(\'tbody [name=&quot;action_id[]&quot;]\').forEach(c=>c.checked=this.checked)"></td>';
foreach ($columns as $column) {
$arrows = '';
if ($column['key'] !== '') {
$up = add_query_arg(['orderby' => $column['key'], 'desc' => 'ASC'], $this_url);
$down = add_query_arg(['orderby' => $column['key'], 'desc' => 'DESC'], $this_url);
$arrows = '<span class="orderby-but"><a title="' . esc_attr__('降序', 'aksrt') . '" href="' . esc_url($down) . '"><span class="dashicons dashicons-arrow-up"></span></a>'
. '<a title="' . esc_attr__('升序', 'aksrt') . '" href="' . esc_url($up) . '"><span class="dashicons dashicons-arrow-down"></span></a></span>';
}
echo '<th style="width:' . esc_attr($column['width']) . ';">' . esc_html($column['name']) . $arrows . '</th>'; // phpcs:ignore WordPress.Security.EscapeOutput -- 箭头为静态结构。
}
echo '</tr></thead><tbody>';
if ($data['items'] === []) {
echo '<tr><td colspan="7" style="color:#ff4a4a;text-align:center;">' . esc_html__('未找到对应内容,或暂无内容', 'aksrt') . '</td></tr>';
} else {
foreach ($data['items'] as $item) {
$used = (int) $item['used_count'];
$max_uses = (int) $item['max_uses'];
echo '<tr>';
echo '<th scope="row" class="check-column"><input type="checkbox" name="action_id[]" value="' . esc_attr((string) $item['id']) . '"></th>';
echo '<td><span class="aksrt-inv-code" data-clipboard-text="' . esc_attr($item['code']) . '" title="' . esc_attr__('点击复制', 'aksrt') . '">' . esc_html($item['code']) . '</span></td>';
echo '<td><div style="font-size:12px;">' . wp_kses((string) $item['reward_text'], ['br' => []]) . '</div></td>';
echo '<td>' . esc_html($item['created_at']) . '</td>';
echo '<td>' . esc_html($item['updated_at']) . '</td>';
if ($used === 0) {
echo '<td><span style="color:#3d7ffd;">' . esc_html__('未使用', 'aksrt') . '</span></td>';
} else {
$label = $max_uses > 0 && $used < $max_uses ? sprintf(__('已使用 %1$d/%2$d', 'aksrt'), $used, $max_uses) : __('已使用', 'aksrt');
echo '<td><span style="color:#f93b3b;">' . esc_html($label) . '</span>';
foreach ((array) $item['recent_users'] as $user) {
$user_link = get_edit_user_link((int) $user['user_id']);
echo '<br><a target="_blank" href="' . esc_url($user_link) . '">' . esc_html($user['name']) . '</a>';
}
echo '</td>';
}
echo '<td>';
if ($item['remark'] !== '') {
echo '<a href="' . esc_url(add_query_arg('remark', $item['remark'], $this_url)) . '">' . esc_html($item['remark']) . '</a>';
}
echo '</td></tr>';
}
}
echo '</tbody></table></div></form><div class="clear"></div>';
// 分页条:总数 + 页码链接。
$total = (int) $data['total'];
$max_pages = (int) $data['max_pages'];
echo '<div class="tablenav bottom"><div class="tablenav-pages" style="display:flex;align-items:center;gap:6px;">';
echo '<span class="displaying-num">' . esc_html(sprintf(__('共 %s 项', 'aksrt'), number_format_i18n($total))) . '</span>';
if ($max_pages > 1) {
echo paginate_links([
'base' => add_query_arg('paged', '%#%'),
'format' => '',
'current' => (int) $data['page'],
'total' => $max_pages,
'type' => 'plain',
'prev_text' => '«',
'next_text' => '»',
]); // phpcs:ignore WordPress.Security.EscapeOutput -- paginate_links 自行转义。
}
echo '</div></div>';
}
/** 添加视图:系统自动生成 / 文本导入 二选一。 */
private function render_invite_codes_add(string $this_url, string $nonce): void {
echo '<h1 class="wp-heading-inline">' . esc_html__('添加邀请码', 'aksrt') . '</h1>';
echo '<a href="' . esc_url($this_url) . '" class="page-title-action">' . esc_html__('返回列表', 'aksrt') . '</a>';
echo '<hr class="wp-header-end">';
echo '<form method="post" action="' . esc_url(admin_url('admin-post.php')) . '" style="max-width:860px;">';
echo '<input type="hidden" name="action" value="aksrt_invite_add">';
echo '<input type="hidden" name="aksrt_nonce" value="' . esc_attr($nonce) . '">';
echo '<div class="aksrt-inv-submessage"><p><b>' . esc_html__('在此添加邀请码', 'aksrt') . '</b></p><ul>'
. '<li>' . esc_html__('如果您已经准备好了邀请码资料,请选择导入的方式添加', 'aksrt') . '</li>'
. '<li>' . esc_html__('您也可以采用系统生成的方式,自动批量添加邀请码', 'aksrt') . '</li></ul></div>';
// 添加方式(按钮组二选一)。
echo '<div class="aksrt-inv-field"><label>' . esc_html__('添加方式', 'aksrt') . '</label><div class="aksrt-inv-control"><div class="aksrt-inv-btnset">'
. '<label><input type="radio" name="add_type" value="auto" checked>' . esc_html__('系统自动生成', 'aksrt') . '</label>'
. '<label><input type="radio" name="add_type" value="import">' . esc_html__('导入邀请码', 'aksrt') . '</label>'
. '</div></div></div>';
// 自动生成区。
echo '<div data-aksrt-inv-dep="add_type=auto">';
echo '<div class="aksrt-inv-field"><label for="aksrt-inv-num">' . esc_html__('生成数量', 'aksrt') . '</label><div class="aksrt-inv-control">'
. '<input type="number" id="aksrt-inv-num" name="auto_num" value="20" min="1" max="1000" step="10" class="small-text"><span class="aksrt-inv-unit">' . esc_html__('个', 'aksrt') . '</span>'
. '<span class="description">' . esc_html__('需要生成多少个邀请码(单次生成数量太多可能会对服务器性能造成影响)', 'aksrt') . '</span></div></div>';
echo '<div class="aksrt-inv-field"><label for="aksrt-inv-remarks">' . esc_html__('标识', 'aksrt') . '</label><div class="aksrt-inv-control">'
. '<input type="text" id="aksrt-inv-remarks" name="auto_remarks" value="' . esc_attr('invita_' . current_time('YmdHis')) . '" class="regular-text">'
. '<span class="description">' . esc_html__('对生成的邀请码做标记标识,方便后期查找管理', 'aksrt') . '</span></div></div>';
$this->render_invite_reward_fields();
echo '<div class="aksrt-inv-field"><label for="aksrt-inv-top">' . esc_html__('高级选项', 'aksrt') . '</label><div class="aksrt-inv-control">'
. '<label class="aksrt-inv-switch"><input type="checkbox" id="aksrt-inv-top" name="auto_top_s" value="1"><span>' . esc_html__('开启', 'aksrt') . '</span></label></div></div>';
echo '<div data-aksrt-inv-dep="auto_top_s=1" style="display:none;">';
echo '<div class="aksrt-inv-field"><label for="aksrt-inv-len">' . esc_html__('自定义位数', 'aksrt') . '</label><div class="aksrt-inv-control">'
. '<input type="number" id="aksrt-inv-len" name="auto_rand_password_limit" value="8" min="1" max="50" step="2" class="small-text"><span class="aksrt-inv-unit">' . esc_html__('位数', 'aksrt') . '</span>'
. '<span class="description">' . esc_html__('自定义自动生成的长度(不能太短,太短可能会出现重复)', 'aksrt') . '</span></div></div>';
echo '</div></div>';
// 导入区。
echo '<div data-aksrt-inv-dep="add_type=import" style="display:none;">';
echo '<div class="aksrt-inv-submessage"><p><b>' . esc_html__('导入邀请码', 'aksrt') . '</b></p><ul>'
. '<li>' . esc_html__('一行一个邀请码,单行格式为:', 'aksrt') . '<code>' . esc_html__('邀请码 奖励 标识', 'aksrt') . '</code></li>'
. '<li>' . esc_html__('邀请码、奖励、标识默认使用空格分割,您可以在下方自定义分割符号,与您的数据对应即可', 'aksrt') . '</li>'
. '<li>' . esc_html__('奖励格式为:', 'aksrt') . '<code>level_integral=10&points=20&balance=30&vip=1&vip_time=5</code>,' . esc_html__('无需奖励填', 'aksrt') . ' <code>' . esc_html__('无', 'aksrt') . '</code></li>'
. '<li>' . esc_html__('单次导入数量太多可能会对服务器性能造成影响', 'aksrt') . '</li></ul>'
. '<p><b>' . esc_html__('数据示例', 'aksrt') . '</b><br>'
. '<code>93FW0XAY ' . esc_html__('无', 'aksrt') . '</code> ' . esc_html__('没有奖励', 'aksrt') . '<br>'
. '<code>P86NPWKI level_integral=100</code> ' . esc_html__('奖励100经验值', 'aksrt') . '<br>'
. '<code>P86NPWKI points=10</code> ' . esc_html__('奖励10积分', 'aksrt') . '<br>'
. '<code>auF9D2B4 balance=30&vip=1&vip_time=5</code> ' . esc_html__('奖励余额30和5天1级会员', 'aksrt') . '</p></div>';
echo '<div class="aksrt-inv-field"><label for="aksrt-import-data">' . esc_html__('邀请码数据', 'aksrt') . '</label><div class="aksrt-inv-control">'
. '<textarea id="aksrt-import-data" name="import_data" rows="10" class="large-text code" style="resize:both;"></textarea></div></div>';
echo '<div class="aksrt-inv-field"><label for="aksrt-import-division">' . esc_html__('自定义分隔符号', 'aksrt') . '</label><div class="aksrt-inv-control">'
. '<input type="text" id="aksrt-import-division" name="import_division" value=" " maxlength="4" class="aksrt-inv-mini">'
. '<span class="description">' . esc_html__('邀请码和奖励之间分割符号(默认为空格分割)', 'aksrt') . '</span></div></div>';
echo '</div>';
echo '<div class="aksrt-inv-field"><label></label><div class="aksrt-inv-control">'
. '<button type="submit" class="button button-primary aksrt-inv-submit">' . esc_html__('确认提交', 'aksrt') . '</button></div></div>';
echo '</form>';
}
/** 使用奖励字段集:经验值 / 积分 / 余额 / VIP 会员与赠送时长。 */
private function render_invite_reward_fields(): void {
echo '<div class="aksrt-inv-field"><label>' . esc_html__('使用奖励', 'aksrt') . '</label><div class="aksrt-inv-control">';
echo '<div style="display:flex;flex-wrap:wrap;gap:12px;">'
. '<span><label>' . esc_html__('经验值', 'aksrt') . ' <input type="number" name="level_integral" value="0" min="0" class="small-text"></label></span>'
. '<span><label>' . esc_html__('积分', 'aksrt') . ' <input type="number" name="points" value="0" min="0" class="small-text"></label></span>'
. '<span><label>' . esc_html__('余额', 'aksrt') . ' <input type="number" name="balance" value="0" min="0" step="0.01" class="small-text"> ' . esc_html__('元', 'aksrt') . '</label></span>'
. '</div>';
echo '<div style="margin-top:8px;"><label>' . esc_html__('VIP会员', 'aksrt') . ' '
. '<label style="font-weight:400;margin:0 8px;"><input type="radio" name="vip" value="" checked>' . esc_html__('无', 'aksrt') . '</label>'
. '<label style="font-weight:400;margin:0 8px;"><input type="radio" name="vip" value="1">' . esc_html__('一级', 'aksrt') . '</label>'
. '<label style="font-weight:400;margin:0 8px;"><input type="radio" name="vip" value="2">' . esc_html__('二级', 'aksrt') . '</label>'
. '</label></div>';
echo '<div data-aksrt-inv-dep="vip=1" style="margin-top:8px;display:none;"><label>' . esc_html__('会员赠送时长', 'aksrt')
. ' <input type="number" name="vip_time" value="0" min="0" class="small-text"> <span class="aksrt-inv-unit">' . esc_html__('天', 'aksrt') . '</span></label>'
. '<span class="description">' . esc_html__('仅在上方选择 VIP 会员等级后生效', 'aksrt') . '</span></div>';
echo '</div></div>';
}
/** 导出视图:状态 / 格式 选择后提交下载。 */
private function render_invite_codes_export(string $this_url, string $nonce): void {
echo '<h1 class="wp-heading-inline">' . esc_html__('导出邀请码', 'aksrt') . '</h1>';
echo '<a href="' . esc_url($this_url) . '" class="page-title-action">' . esc_html__('返回列表', 'aksrt') . '</a>';
echo '<hr class="wp-header-end">';
echo '<form method="get" action="' . esc_url(admin_url('admin-post.php')) . '" style="max-width:860px;">';
echo '<input type="hidden" name="action" value="aksrt_invite_export">';
echo '<input type="hidden" name="aksrt_nonce" value="' . esc_attr($nonce) . '">';
echo '<div class="aksrt-inv-field"><label>' . esc_html__('选择状态', 'aksrt') . '</label><div class="aksrt-inv-control">'
. '<label style="font-weight:400;margin-right:16px;"><input type="radio" name="status" value="all" checked>' . esc_html__('全部', 'aksrt') . '</label>'
. '<label style="font-weight:400;margin-right:16px;"><input type="radio" name="status" value="unused">' . esc_html__('未使用', 'aksrt') . '</label>'
. '<label style="font-weight:400;margin-right:16px;"><input type="radio" name="status" value="used">' . esc_html__('已使用', 'aksrt') . '</label>'
. '</div></div>';
echo '<div class="aksrt-inv-field"><label>' . esc_html__('导出格式', 'aksrt') . '</label><div class="aksrt-inv-control">'
. '<label style="font-weight:400;margin-right:16px;"><input type="radio" name="export_format" value="text">' . esc_html__('文本文档', 'aksrt') . '</label>'
. '<label style="font-weight:400;margin-right:16px;"><input type="radio" name="export_format" value="xls" checked>' . esc_html__('Excel表格', 'aksrt') . '</label>'
. '</div></div>';
echo '<div data-aksrt-inv-dep="export_format=text" style="display:none;">';
echo '<div class="aksrt-inv-field"><label>' . esc_html__('分隔符号', 'aksrt') . '</label><div class="aksrt-inv-control">'
. '<input type="text" name="text_division" value=" " maxlength="4" class="aksrt-inv-mini">'
. '<span class="description">' . esc_html__('邀请码和奖励之间分割符号(默认为空格分割)', 'aksrt') . '</span></div></div>';
echo '</div>';
echo '<div class="aksrt-inv-field"><label></label><div class="aksrt-inv-control">'
. '<button type="submit" class="button button-primary aksrt-inv-submit">' . esc_html__('确认提交', 'aksrt') . '</button></div></div>';
echo '</form>';
}
}