feat(admin): streamline ticket management with dialogs

Move on-behalf ticket creation into a header dialog and load ticket handling on demand. Reuse the admin REST write path, preserve drafts and filters, and cover dialog and server boundaries with regression tests.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
kate522andClaude Opus 5 committed 2026-10-31 11:25:56 +08:00
1 parent b45fd161f0
commit 264015b7e9
16 files changed
+2178 -1048

No files matched your search

+281
View File
@@ -0,0 +1,281 @@
<?php
/**
* 工单管理 REST harness:直接驱动真实 TicketRestAdmin 回调,无 WordPress / 数据库依赖。
*
* Usage: php tests/admin/ticket-admin-rest-harness.php
*/
namespace {
define('ABSPATH', __DIR__ . '/');
final class WP_Error {
public function __construct(
public string $code = '',
public string $message = '',
public array $data = []
) {}
}
final class WP_REST_Request {
public function __construct(private array $params = []) {}
public function get_param(string $key) { return $this->params[$key] ?? null; }
public function has_param(string $key): bool { return array_key_exists($key, $this->params); }
}
function __($text, $domain = null): string { return (string) $text; }
function is_wp_error($value): bool { return $value instanceof WP_Error; }
function rest_ensure_response($data) { return $data; }
function sanitize_key($value): string { return strtolower(preg_replace('/[^a-z0-9_\-]/', '', (string) $value)); }
function sanitize_text_field($value): string { return trim(strip_tags((string) $value)); }
function sanitize_textarea_field($value): string { return trim(strip_tags((string) $value)); }
function absint($value): int { return abs((int) $value); }
function current_time($type = 'mysql'): string { return '2026-10-31 12:34:56'; }
function get_current_user_id(): int { return 99; }
function current_user_can($capability): bool { return $capability === 'manage_options'; }
function get_userdata($user_id) {
$user_id = (int) $user_id;
return in_array($user_id, [10, 11, 12, 99], true) ? (object) ['ID' => $user_id] : false;
}
function user_can($user, $capability): bool {
$GLOBALS['ticket_rest_user_can_calls'][] = [(int) $user, (string) $capability];
return (int) $user === 11 && $capability === 'manage_options';
}
}
namespace AKSRT\Ticket {
final class TicketSettings {
public static bool $order_link_enabled = false;
public static function order_link_enabled(): bool { return self::$order_link_enabled; }
public static function title_max(): int { return 80; }
public static function content_max(): int { return 1000; }
public static function reply_max(): int { return 5; }
}
final class TicketStatusService {
public const KEY_CLOSED = 'closed';
public const KEY_ADMIN_REPLIED = 'admin_replied';
private const STATUSES = [
'pending' => false,
'handling' => false,
'admin_replied' => false,
'closed' => true,
];
public static function exists(string $status): bool { return array_key_exists($status, self::STATUSES); }
public static function is_closed(string $status): bool { return !empty(self::STATUSES[$status]); }
public static function can_transition(string $from, string $to): bool {
if (!self::exists($to)) {
return false;
}
if ($from === $to) {
return true;
}
if (self::is_closed($from) || ($from === 'pending' && $to === self::KEY_CLOSED)) {
return false;
}
return true;
}
}
final class TicketTypeService {
public static function exists(int $id): bool { return in_array($id, [3, 4], true); }
}
final class TicketRepository {
private static ?self $instance = null;
public static array $tickets = [];
public static array $creates = [];
public static array $updates = [];
private static int $next_id = 100;
public static function get_instance(): self { return self::$instance ??= new self(); }
public function find(int $id): ?array { return self::$tickets[$id] ?? null; }
public function update_fields(int $id, array $fields): bool {
self::$updates[] = ['id' => $id, 'fields' => $fields];
if (!isset(self::$tickets[$id])) {
return false;
}
self::$tickets[$id] = array_merge(self::$tickets[$id], $fields);
return true;
}
public function create(array $fields): int {
self::$creates[] = $fields;
$id = self::$next_id++;
self::$tickets[$id] = array_merge(['id' => $id], $fields);
return $id;
}
}
final class TicketNotifier {
public static array $closed = [];
public static array $user_replied = [];
public static function closed(array $ticket, string $actor): void { self::$closed[] = [$ticket, $actor]; }
public static function user_replied(array $ticket): void { self::$user_replied[] = $ticket; }
}
final class TicketNumber {
public static function generate(): string { return 'T20261031123456'; }
}
final class TicketAttachment {
public static function sanitize($value): array { return is_array($value) ? $value : []; }
public static function encode(array $value): string { return (string) json_encode($value); }
}
final class TicketNoteService {
public static array $created = [];
public static function for_ticket(int $ticket_id): array { return []; }
public static function create(int $ticket_id, string $content, int $admin_id): int {
self::$created[] = compact('ticket_id', 'content', 'admin_id');
return count(self::$created);
}
}
}
namespace AKSRT\Attachment {
final class PendingUploads {
public static function claim_urls(array $attachment, int $user_id): void {}
}
}
namespace {
require_once dirname(__DIR__, 2) . '/src/Ticket/TicketConfigRest.php';
require_once dirname(__DIR__, 2) . '/src/Ticket/TicketRestAdmin.php';
$failures = [];
$check = static function (string $label, bool $condition) use (&$failures): void {
if (!$condition) {
$failures[] = $label;
}
};
$reset = static function (): void {
\AKSRT\Ticket\TicketRepository::$tickets = [
1 => ['id' => 1, 'status' => 'handling', 'ticket_type_id' => 3, 'admin_id' => 11],
2 => ['id' => 2, 'status' => 'closed', 'ticket_type_id' => 3, 'admin_id' => 11],
3 => ['id' => 3, 'status' => 'handling', 'ticket_type_id' => 3, 'admin_id' => 11],
];
\AKSRT\Ticket\TicketRepository::$creates = [];
\AKSRT\Ticket\TicketRepository::$updates = [];
\AKSRT\Ticket\TicketNotifier::$closed = [];
\AKSRT\Ticket\TicketNotifier::$user_replied = [];
\AKSRT\Ticket\TicketNoteService::$created = [];
\AKSRT\Ticket\TicketSettings::$order_link_enabled = false;
$GLOBALS['ticket_rest_user_can_calls'] = [];
};
$admin = new \AKSRT\Ticket\TicketRestAdmin();
$error_code = static fn($value): string => $value instanceof \WP_Error ? $value->code : '';
// Explicit admin_id=0 clears assignment and status updates always touch updated_at.
$reset();
$response = $admin->set_status(new \WP_REST_Request(['id' => 1, 'status' => 'handling', 'admin_id' => 0]));
$saved = \AKSRT\Ticket\TicketRepository::$tickets[1] ?? [];
$check('解除指派接受 admin_id=0', !\is_wp_error($response) && ($saved['admin_id'] ?? null) === 0);
$check('状态更新写入 updated_at', ($saved['updated_at'] ?? '') === '2026-10-31 12:34:56');
// Invalid department returns an explicit error and performs no write.
$reset();
$response = $admin->set_status(new \WP_REST_Request(['id' => 1, 'status' => 'handling', 'ticket_type_id' => 999]));
$check('非法部门返回明确错误', $error_code($response) === 'aksrt_ticket_type');
$check('非法部门不写入任何字段', \AKSRT\Ticket\TicketRepository::$updates === []);
// Existing assignees may lose admin capability; retaining the same ID isn't a new assignment.
$reset();
\AKSRT\Ticket\TicketRepository::$tickets[1]['admin_id'] = 12;
$response = $admin->set_status(new \WP_REST_Request([
'id' => 1,
'status' => 'admin_replied',
'ticket_type_id' => 4,
'admin_id' => 12,
]));
$saved = \AKSRT\Ticket\TicketRepository::$tickets[1] ?? [];
$check('保留已失去管理员权限的原跟进人仍可更新状态和部门', !\is_wp_error($response)
&& ($saved['status'] ?? null) === 'admin_replied'
&& ($saved['ticket_type_id'] ?? null) === 4
&& ($saved['admin_id'] ?? null) === 12);
$check('保留原跟进人不视为新指派', $GLOBALS['ticket_rest_user_can_calls'] === []);
// A valid department must not be partially persisted when assignment validation fails.
$reset();
$response = $admin->set_status(new \WP_REST_Request([
'id' => 1,
'status' => 'handling',
'ticket_type_id' => 4,
'admin_id' => 12,
]));
$check('无 manage_options 的用户不能被指派', $error_code($response) === 'aksrt_ticket_admin');
$check('管理员校验失败时部门也不被部分写入', \AKSRT\Ticket\TicketRepository::$updates === []);
$check('目标管理员必须通过 manage_options 校验', in_array([12, 'manage_options'], $GLOBALS['ticket_rest_user_can_calls'], true));
$reset();
$response = $admin->set_status(new \WP_REST_Request([
'id' => 1,
'status' => 'handling',
'admin_id' => 777,
]));
$check('不存在的管理员返回明确错误', $error_code($response) === 'aksrt_ticket_admin');
$check('不存在的管理员不会触发写入', \AKSRT\Ticket\TicketRepository::$updates === []);
$reset();
\AKSRT\Ticket\TicketRepository::$tickets[1]['admin_id'] = 12;
$response = $admin->set_status(new \WP_REST_Request([
'id' => 1,
'status' => 'handling',
'admin_id' => 11,
]));
$check('具备 manage_options 的管理员可被指派', !\is_wp_error($response)
&& in_array([11, 'manage_options'], $GLOBALS['ticket_rest_user_can_calls'], true)
&& (\AKSRT\Ticket\TicketRepository::$tickets[1]['admin_id'] ?? null) === 11);
// Only the first open -> closed transition sends a close notification.
$reset();
$first_close = $admin->set_status(new \WP_REST_Request(['id' => 3, 'status' => 'closed']));
$second_close = $admin->set_status(new \WP_REST_Request(['id' => 3, 'status' => 'closed']));
$check('首次关闭成功', !\is_wp_error($first_close));
$check('同状态再次提交不重发关闭通知', count(\AKSRT\Ticket\TicketNotifier::$closed) === 1);
// Order association follows the feature switch.
$reset();
\AKSRT\Ticket\TicketSettings::$order_link_enabled = false;
$admin->create_ticket(new \WP_REST_Request([
'user_id' => 10,
'title' => '代客提交标题',
'ticket_type_id' => 3,
'content' => '这是问题描述内容',
'order_number' => 'ORD-1',
]));
$check('关闭订单关联时忽略订单号', (\AKSRT\Ticket\TicketRepository::$creates[0]['order_number'] ?? null) === '');
\AKSRT\Ticket\TicketSettings::$order_link_enabled = true;
$admin->create_ticket(new \WP_REST_Request([
'user_id' => 10,
'title' => '代客提交标题',
'ticket_type_id' => 3,
'content' => '这是问题描述内容',
'order_number' => '<b>ORD-2</b>',
]));
$check('开启订单关联时保存已消毒订单号', (\AKSRT\Ticket\TicketRepository::$creates[1]['order_number'] ?? null) === 'ORD-2');
// Internal note writes enforce existence, trim, non-empty and configured maximum length.
$reset();
$missing = $admin->create_note(new \WP_REST_Request(['id' => 777, 'content' => 'valid']));
$empty = $admin->create_note(new \WP_REST_Request(['id' => 1, 'content' => " \n\t "]));
$long = $admin->create_note(new \WP_REST_Request(['id' => 1, 'content' => '123456']));
$valid = $admin->create_note(new \WP_REST_Request(['id' => 1, 'content' => ' memo ']));
$created = \AKSRT\Ticket\TicketNoteService::$created;
$check('备注工单不存在时返回 404', $error_code($missing) === 'aksrt_ticket_missing');
$check('备注拒绝空内容', $error_code($empty) === 'aksrt_ticket_note_content');
$check('备注拒绝超长内容', $error_code($long) === 'aksrt_ticket_note_content');
$check('备注 trim 后保存', !\is_wp_error($valid) && ($created[0]['content'] ?? null) === 'memo');
$check('无效备注未调用创建服务', count($created) === 1);
if ($failures) {
echo "Ticket admin REST harness FAILED\n";
foreach ($failures as $failure) {
echo ' - ' . $failure . "\n";
}
exit(1);
}
echo "Ticket admin REST harness passed\n";
}
+14
View File
@@ -0,0 +1,14 @@
'use strict';
const assert = require('node:assert/strict');
const { execFileSync } = require('node:child_process');
const path = require('node:path');
const test = require('node:test');
const root = path.resolve(__dirname, '../..');
const harness = path.join(root, 'tests', 'admin', 'ticket-admin-rest-harness.php');
test('工单管理 REST 校验与通知边界通过 PHP stub harness', () => {
const output = execFileSync('php', [harness], { encoding: 'utf8' });
assert.match(output, /Ticket admin REST harness passed/);
});
+688
View File
@@ -0,0 +1,688 @@
'use strict';
const assert = require('node:assert/strict');
const fs = require('node:fs');
const path = require('node:path');
const test = require('node:test');
const vm = require('node:vm');
const rootDir = path.resolve(__dirname, '../..');
const scriptPath = path.join(rootDir, 'assets', 'js', 'admin-tickets.js');
const strings = {
loading: 'Loading', saving: 'Saving', loadFailed: 'Load failed', saveFailed: 'Save failed',
uncertain: 'Unknown result; reload to verify', refreshFailed: 'Saved, but refresh failed',
discard: 'Discard changes?', required: 'Required', tooLong: 'Too long', created: 'Created',
reply: 'Reply sent', status: 'Status saved', note: 'Note added',
};
function makeRuntime({ href = 'https://site.test/wp-admin/users.php?page=aksrt_tickets', views = [41] } = {}) {
const ids = new Map();
const fetchCalls = [];
const document = { activeElement: null };
class Element {
constructor(tagName = 'div', attrs = {}) {
this.tagName = tagName.toUpperCase();
this.attrs = { ...attrs };
this.dataset = {};
Object.entries(attrs).forEach(([name, value]) => {
const match = name.match(/^data-(.+)$/);
if (match) this.dataset[match[1].replace(/-([a-z])/g, (_, letter) => letter.toUpperCase())] = String(value);
});
this.children = [];
this.parentElement = null;
this.listeners = new Map();
this.disabled = false;
this.hidden = Object.hasOwn(attrs, 'hidden');
this.required = Object.hasOwn(attrs, 'required');
this.checked = Object.hasOwn(attrs, 'checked');
this.isConnected = true;
this.open = false;
this.validity = '';
this.selectionStart = 0;
this.selectionEnd = 0;
this.scrollTop = 0;
this.scrollHeight = 0;
this._value = String(attrs.value ?? '');
this.defaultValue = this._value;
this.maxLength = attrs.maxlength === undefined ? -1 : Number(attrs.maxlength);
this.type = attrs.type || '';
this.name = attrs.name || '';
this.id = attrs.id || '';
this.action = attrs.action || '';
this.textContent = attrs.textContent || '';
this._innerHTML = '';
this.classNames = new Set(String(attrs.class || '').split(/\s+/).filter(Boolean));
this.classList = {
add: (name) => this.classNames.add(name),
remove: (name) => this.classNames.delete(name),
contains: (name) => this.classNames.has(name),
toggle: (name, force) => {
const enabled = force === undefined ? !this.classNames.has(name) : Boolean(force);
if (enabled) this.classNames.add(name); else this.classNames.delete(name);
return enabled;
},
};
this.isPanel = false;
if (this.id) ids.set(this.id, this);
}
get value() {
if (this.tagName === 'SELECT' && this.options && this.selectedIndex >= 0) {
return this.options[this.selectedIndex]?.value ?? '';
}
return this._value;
}
set value(value) {
this._value = String(value ?? '');
if (this.tagName === 'SELECT' && this.options) {
this.selectedIndex = this.options.findIndex((option) => option.value === this._value);
}
}
get innerHTML() { return this._innerHTML; }
set innerHTML(value) {
this._innerHTML = String(value);
this.children = [];
if (this.isPanel && this._innerHTML) buildDetailPanel(this, this._innerHTML);
}
appendChild(child) {
child.parentElement = this;
child.form = this.tagName === 'FORM' ? this : (this.form || null);
this.children.push(child);
child.children.forEach((nested) => { nested.form = child.tagName === 'FORM' ? child : child.form; });
return child;
}
addEventListener(type, callback, options = {}) {
const entries = this.listeners.get(type) || [];
entries.push({ callback, once: Boolean(options && options.once) });
this.listeners.set(type, entries);
}
fire(type, values = {}) {
const event = {
target: this,
defaultPrevented: false,
preventDefault() { this.defaultPrevented = true; },
...values,
};
const entries = [...(this.listeners.get(type) || [])];
entries.forEach(({ callback, once }) => {
callback(event);
if (once) {
const current = this.listeners.get(type) || [];
this.listeners.set(type, current.filter((entry) => entry.callback !== callback));
}
});
return event;
}
querySelector(selector) { return this.querySelectorAll(selector)[0] || null; }
querySelectorAll(selector) {
const selectors = selector.split(',').map((part) => part.trim()).filter(Boolean);
const found = [];
const visit = (node) => {
node.children.forEach((child) => {
if (selectors.some((part) => matchesSelector(child, part))) found.push(child);
visit(child);
});
};
visit(this);
return found;
}
closest(selector) {
for (let node = this; node; node = node.parentElement) {
if (selector.split(',').some((part) => matchesSelector(node, part.trim()))) return node;
}
return null;
}
matches(selector) { return selector.split(',').some((part) => matchesSelector(this, part.trim())); }
focus() { document.activeElement = this; }
setCustomValidity(message) { this.validity = message; }
setSelectionRange(start, end) { this.selectionStart = start; this.selectionEnd = end; }
getAttribute(name) { return this.attrs[name] === undefined ? null : String(this.attrs[name]); }
setAttribute(name, value) { this.attrs[name] = String(value); }
removeAttribute(name) { delete this.attrs[name]; }
replaceChildren() { this.children = []; this._innerHTML = ''; }
getBoundingClientRect() { return { left: 100, top: 100, right: 500, bottom: 500 }; }
}
function matchesSelector(element, selector) {
const parts = selector.trim().split(/\s+/);
if (!matchesSimple(element, parts[parts.length - 1])) return false;
let ancestor = element.parentElement;
for (let index = parts.length - 2; index >= 0; index -= 1) {
while (ancestor && !matchesSimple(ancestor, parts[index])) ancestor = ancestor.parentElement;
if (!ancestor) return false;
ancestor = ancestor.parentElement;
}
return true;
}
function matchesSimple(element, selector) {
const tag = selector.match(/^[a-zA-Z][\w-]*/)?.[0];
if (tag && element.tagName !== tag.toUpperCase()) return false;
const id = selector.match(/#([\w-]+)/)?.[1];
if (id && element.id !== id) return false;
for (const [, name, doubleValue, singleValue, bareValue] of selector.matchAll(/\[([^\]=]+)(?:=(?:"([^"]*)"|'([^']*)'|([^\]]+)))?\]/g)) {
if (!Object.hasOwn(element.attrs, name)) return false;
const expected = doubleValue ?? singleValue ?? bareValue;
if (expected !== undefined && String(element.attrs[name]) !== expected) return false;
}
for (const [, className] of selector.matchAll(/\.([\w-]+)/g)) {
if (!element.classList.contains(className)) return false;
}
return true;
}
function el(tag, attrs = {}, parent = null) {
const item = new Element(tag, attrs);
if (parent) parent.appendChild(item);
return item;
}
function field(tag, name, value, parent, extra = {}) {
const attrs = { value, ...extra };
if (name) attrs.name = name;
const item = el(tag, attrs, parent);
item.defaultValue = String(value ?? '');
item.type = attrs.type || (tag === 'textarea' ? 'textarea' : 'text');
item.form = parent.tagName === 'FORM' ? parent : parent.form;
return item;
}
function selectField(name, choices, selected, parent, extra = {}) {
const attrs = { ...extra };
if (name) attrs.name = name;
const select = el('select', attrs, parent);
select.options = choices.map(([value, label, attrs = {}]) => {
const option = el('option', { value, textContent: label, ...attrs }, select);
option.value = String(value);
option.defaultSelected = String(value) === String(selected);
return option;
});
select.defaultValue = String(selected);
select.value = selected;
select.form = parent.tagName === 'FORM' ? parent : parent.form;
return select;
}
function configureForm(form) {
form.reset = () => {
form.querySelectorAll('input, select, textarea').forEach((control) => {
if (control.tagName === 'SELECT') {
const selected = control.options.find((option) => option.defaultSelected) || control.options[0];
control.value = selected ? selected.value : '';
} else {
control.value = control.defaultValue;
if (control.type === 'checkbox') control.checked = control.defaultChecked || false;
}
control.validity = '';
});
};
form.reportValidity = () => form.querySelectorAll('input, select, textarea').every((control) => {
if (control.validity) return false;
if (!control.required) return true;
if (control.type === 'checkbox') return control.checked;
return String(control.value).trim() !== '';
});
}
function feedbackBox(parent) {
const box = el('div', { 'data-aksrt-ticket-feedback': '', hidden: '' }, parent);
el('p', {}, box);
el('button', { type: 'button', 'data-aksrt-ticket-retry': '', hidden: '' }, box);
return box;
}
const root = el('main', { class: 'aksrt-tickets-admin' });
const list = el('div', { 'data-aksrt-ticket-list': '' }, root);
const createOpener = el('button', { 'data-aksrt-dialog-open': 'aksrt-ticket-create-dialog' }, root);
const viewsById = new Map();
views.forEach((id) => {
const button = el('button', { 'data-aksrt-ticket-view': String(id) }, root);
viewsById.set(String(id), button);
});
const createDialog = el('dialog', { id: 'aksrt-ticket-create-dialog' }, root);
const createFrame = el('div', {}, createDialog);
el('h2', { id: 'aksrt-ticket-create-title', autofocus: '' }, createFrame);
feedbackBox(createDialog);
const createForm = el('form', { action: 'https://site.test/wp-json/aksrt/v1/admin/tickets', 'data-aksrt-ticket-form': 'create' }, createFrame);
field('input', 'user_id', '', createForm, { type: 'number', required: '' });
selectField('ticket_type_id', [['', 'Choose'], ['3', 'Support']], '3', createForm, { required: '' });
field('input', 'title', '', createForm, { type: 'text', required: '', maxlength: '120' });
field('textarea', 'content', '', createForm, { required: '', maxlength: '500', id: 'aksrt-ticket-create-content' });
el('span', { 'data-aksrt-ticket-counter': 'aksrt-ticket-create-content' }, createForm);
el('button', { type: 'button', 'data-aksrt-dialog-close': '' }, createFrame);
el('button', { type: 'submit' }, createForm);
configureForm(createForm);
const detailDialog = el('dialog', { id: 'aksrt-ticket-detail-dialog' }, root);
const detailFrame = el('div', {}, detailDialog);
const detailTitle = el('h2', { id: 'aksrt-ticket-detail-title', autofocus: '' }, detailFrame);
detailTitle.textContent = 'Ticket detail';
const detailDescription = el('p', { id: 'aksrt-ticket-detail-description' }, detailFrame);
detailDescription.textContent = 'View the conversation';
feedbackBox(detailDialog);
const panel = el('div', { 'data-aksrt-ticket-panel': '' }, detailFrame);
panel.isPanel = true;
el('button', { type: 'button', 'data-aksrt-dialog-close': '' }, detailFrame);
[createDialog, detailDialog].forEach((dialog) => {
dialog.showModal = () => {
dialog.open = true;
dialog.querySelector('[autofocus]')?.focus();
};
dialog.close = () => {
if (!dialog.open) return;
dialog.open = false;
setTimeout(() => dialog.fire('close'), 0);
};
});
function buildDetailPanel(host, marker) {
const [, idText, initialStatus = 'pending'] = marker.match(/ticket:(\d+)(?::([\w-]+))?/) || [];
const id = Number(idText || 1);
const detail = el('section', { 'data-aksrt-ticket-detail': String(id) }, host);
const conversation = el('section', { class: 'aksrt-ticket-conversation' }, detail);
el('button', { type: 'button', 'data-aksrt-ticket-latest': '' }, conversation);
const scroll = el('div', { class: 'aksrt-ticket-conversation__scroll' }, conversation);
scroll.scrollHeight = 100;
const replyForm = el('form', { action: `https://site.test/wp-json/aksrt/v1/admin/tickets/${id}/reply`, 'data-aksrt-ticket-form': 'reply' }, detail);
const replyFieldId = `aksrt-ticket-reply-${id}`;
const reply = field('textarea', 'content', '', replyForm, { id: replyFieldId, required: '', maxlength: '24', 'data-aksrt-ticket-editor': '' });
reply.selectionStart = reply.selectionEnd = 0;
el('span', { 'data-aksrt-ticket-counter': replyFieldId }, replyForm);
const prereply = selectField('', [['', 'Choose reply'], ['short', 'Short'], ['01234567890123456789012345', 'Too long']], '', replyForm, { id: `${replyFieldId}-pre`, 'data-aksrt-ticket-prereply': replyFieldId });
prereply.dataset.aksrtTicketPrereply = replyFieldId;
el('button', { type: 'submit' }, replyForm);
configureForm(replyForm);
const statusSection = el('section', {}, detail);
el('button', { type: 'button', 'data-aksrt-ticket-assign': '' }, statusSection);
const statusForm = el('form', { action: `https://site.test/wp-json/aksrt/v1/admin/tickets/${id}/status`, 'data-aksrt-ticket-form': 'status' }, statusSection);
selectField('status', [
['pending', 'Pending'], ['handling', 'Handling'], ['closed', 'Closed', { 'data-closed': '1' }],
], initialStatus, statusForm, { 'data-aksrt-ticket-status': '' });
selectField('ticket_type_id', [['3', 'Support'], ['6', 'Billing']], '3', statusForm, { required: '' });
selectField('admin_id', [['0', 'Unassigned'], ['7', 'Admin'], ['44', 'Current']], '7', statusForm);
const warning = el('div', { 'data-aksrt-ticket-close-warning': '', hidden: '' }, statusForm);
const confirm = field('input', '', '', warning, { type: 'checkbox', 'data-aksrt-ticket-close-confirm': '' });
confirm.type = 'checkbox';
confirm.checked = false;
confirm.defaultChecked = false;
el('button', { type: 'submit' }, statusForm);
configureForm(statusForm);
const noteForm = el('form', { action: `https://site.test/wp-json/aksrt/v1/admin/tickets/${id}/notes`, 'data-aksrt-ticket-form': 'note' }, detail);
field('textarea', 'content', '', noteForm, { id: `aksrt-ticket-note-${id}`, required: '', maxlength: '24', 'data-aksrt-ticket-editor': '' });
el('span', { 'data-aksrt-ticket-counter': `aksrt-ticket-note-${id}` }, noteForm);
el('button', { type: 'submit' }, noteForm);
configureForm(noteForm);
}
const documentElement = el('html');
document.querySelector = (selector) => selector === '.aksrt-tickets-admin' ? root : null;
document.getElementById = (id) => ids.get(id) || null;
document.documentElement = documentElement;
const window = new Element('window');
window.AKSRTAdminTickets = {
ajaxUrl: 'https://site.test/wp-admin/admin-ajax.php',
readNonce: 'read-nonce', restNonce: 'rest-nonce', currentUser: 44, strings,
};
window.location = {
href,
reloadCount: 0,
reload() { this.reloadCount += 1; },
};
window.history = {
state: null,
replaceState(_state, _title, nextUrl) { window.location.href = nextUrl; },
};
window.confirmAnswer = false;
window.confirmCalls = [];
window.confirm = (message) => {
window.confirmCalls.push(message);
return window.confirmAnswer;
};
const fetch = (url, options) => new Promise((resolve, reject) => {
fetchCalls.push({ url: String(url), options, resolve, reject });
});
vm.runInNewContext(fs.readFileSync(scriptPath, 'utf8'), {
document, window, fetch, URL, AbortController, setTimeout, clearTimeout,
}, { filename: scriptPath });
return { document, window, root, list, createDialog, detailDialog, createForm, createOpener, detailTitle, detailDescription, panel, viewsById, fetchCalls };
}
function response(data, status = 200) {
return { ok: status >= 200 && status < 300, status, json: async () => data };
}
function resolveFetch(runtime, index, data, status = 200) {
runtime.fetchCalls[index].resolve(response(data, status));
}
function rejectFetch(runtime, index, error = new Error('network disconnected')) {
runtime.fetchCalls[index].reject(error);
}
function tick() { return new Promise((resolve) => setTimeout(resolve, 5)); }
function fireSubmit(runtime, form) {
return runtime.root.fire('submit', { target: form });
}
function formsIn(runtime) {
return {
reply: runtime.panel.querySelector('[data-aksrt-ticket-form="reply"]'),
status: runtime.panel.querySelector('[data-aksrt-ticket-form="status"]'),
note: runtime.panel.querySelector('[data-aksrt-ticket-form="note"]'),
};
}
function loadDetail(runtime, id = 41, status = 'pending') {
const opener = runtime.viewsById.get(String(id));
assert.ok(opener, `missing opener for ${id}`);
runtime.root.fire('click', { target: opener });
assert.equal(runtime.fetchCalls.length, 1);
resolveFetch(runtime, 0, { success: true, data: { panel: `ticket:${id}:${status}`, title: `Ticket ${id}`, description: `#${id}`, page: 1 } });
return tick();
}
function setField(form, selector, value) {
const field = form.querySelector(selector);
assert.ok(field, `missing field ${selector}`);
field.value = value;
return field;
}
function submitBody(call) { return JSON.parse(call.options.body); }
test('create modal opens with scroll lock, cancels dirty close, resets, and returns focus', async () => {
const runtime = makeRuntime();
runtime.root.fire('click', { target: runtime.createOpener });
assert.equal(runtime.createDialog.open, true);
assert.equal(runtime.document.documentElement.classList.contains('aksrt-ticket-modal-open'), true);
assert.equal(runtime.document.activeElement.id, 'aksrt-ticket-create-title');
const title = runtime.createForm.querySelector('[name="title"]');
title.value = 'Unsaved title';
runtime.root.fire('input', { target: title });
const closeButton = runtime.createDialog.querySelector('[data-aksrt-dialog-close]');
runtime.createDialog.fire('click', { target: closeButton });
assert.equal(runtime.createDialog.open, true);
assert.deepEqual(runtime.window.confirmCalls, [strings.discard]);
runtime.window.confirmAnswer = true;
runtime.createDialog.fire('click', { target: closeButton });
assert.equal(runtime.createDialog.open, false);
await tick();
assert.equal(runtime.document.documentElement.classList.contains('aksrt-ticket-modal-open'), false);
assert.equal(runtime.document.activeElement, runtime.createOpener);
assert.equal(title.value, '');
});
test('detail load ignores a response that arrives after cancellation', async () => {
const runtime = makeRuntime();
runtime.root.fire('click', { target: runtime.viewsById.get('41') });
const pending = runtime.fetchCalls[0];
assert.match(pending.url, /id=41/);
const cancelled = runtime.detailDialog.fire('cancel');
assert.equal(cancelled.defaultPrevented, true);
await tick();
assert.equal(runtime.detailDialog.open, false);
assert.equal(pending.options.signal.aborted, true);
resolveFetch(runtime, 0, { success: true, data: { panel: 'ticket:41', title: 'Late title', description: 'Late', page: 1 } });
await tick();
assert.equal(runtime.panel.querySelector('[data-aksrt-ticket-form]'), null);
assert.equal(runtime.detailTitle.textContent, 'Ticket detail');
assert.equal(new URL(runtime.window.location.href).searchParams.has('id'), false);
});
test('deep link loads an ID even when it is absent from the current list', async () => {
const runtime = makeRuntime({
views: [41],
href: 'https://site.test/wp-admin/users.php?page=aksrt_tickets&id=987&status=pending&ticket_type_id=6&s=network&paged=3',
});
assert.equal(runtime.detailDialog.open, true);
assert.equal(runtime.viewsById.has('987'), false);
assert.equal(runtime.fetchCalls.length, 1);
const read = new URL(runtime.fetchCalls[0].url);
assert.equal(read.searchParams.get('action'), 'aksrt_ticket_view');
assert.equal(read.searchParams.get('nonce'), 'read-nonce');
assert.equal(read.searchParams.get('id'), '987');
assert.equal(read.searchParams.get('status'), 'pending');
assert.equal(read.searchParams.get('ticket_type_id'), '6');
assert.equal(read.searchParams.get('s'), 'network');
assert.equal(read.searchParams.get('paged'), '3');
resolveFetch(runtime, 0, { success: true, data: { panel: 'ticket:987', title: 'Ticket 987', description: '#987', page: 3 } });
await tick();
assert.equal(runtime.panel.querySelector('[data-aksrt-ticket-detail="987"]') !== null, true);
});
test('create POST uses the REST nonce, locks duplicates, and keeps inputs after a confirmed error', async () => {
const runtime = makeRuntime();
runtime.root.fire('click', { target: runtime.createOpener });
setField(runtime.createForm, '[name="user_id"]', '19');
setField(runtime.createForm, '[name="title"]', 'Broken keyboard');
setField(runtime.createForm, '[name="content"]', 'The key sticks');
fireSubmit(runtime, runtime.createForm);
assert.equal(runtime.fetchCalls.length, 1);
const call = runtime.fetchCalls[0];
assert.equal(call.options.method, 'POST');
assert.equal(call.options.headers['X-WP-Nonce'], 'rest-nonce');
assert.deepEqual(submitBody(call), { user_id: '19', ticket_type_id: '3', title: 'Broken keyboard', content: 'The key sticks' });
assert.equal(runtime.createForm.querySelector('[name="title"]').disabled, true);
fireSubmit(runtime, runtime.createForm);
assert.equal(runtime.fetchCalls.length, 1);
resolveFetch(runtime, 0, { success: false, message: 'Invalid user' }, 400);
await tick();
assert.equal(runtime.createForm.querySelector('[name="title"]').disabled, false);
assert.equal(runtime.createForm.querySelector('[name="title"]').value, 'Broken keyboard');
assert.equal(runtime.createDialog.querySelector('[data-aksrt-ticket-feedback] p').textContent, 'Invalid user');
assert.equal(runtime.createDialog.querySelector('[data-aksrt-ticket-retry]').hidden, true);
});
test('successful create waits for its asynchronous close event before opening the new detail', async () => {
const runtime = makeRuntime();
runtime.root.fire('click', { target: runtime.createOpener });
setField(runtime.createForm, '[name="user_id"]', '19');
setField(runtime.createForm, '[name="title"]', 'New issue');
setField(runtime.createForm, '[name="content"]', 'Details');
fireSubmit(runtime, runtime.createForm);
resolveFetch(runtime, 0, { success: true, data: { id: 303 } });
await tick();
assert.equal(runtime.createDialog.open, false);
assert.equal(runtime.fetchCalls.length, 2);
assert.equal(runtime.detailDialog.open, true);
assert.equal(runtime.document.documentElement.classList.contains('aksrt-ticket-modal-open'), true);
resolveFetch(runtime, 1, { success: true, data: { panel: 'ticket:303', title: 'New issue', description: '#303', list: 'updated rows', page: 1 } });
await tick();
assert.equal(runtime.panel.querySelector('[data-aksrt-ticket-detail="303"]') !== null, true);
assert.equal(runtime.list.innerHTML, 'updated rows');
assert.equal(runtime.detailDialog.open, true);
assert.equal(runtime.document.documentElement.classList.contains('aksrt-ticket-modal-open'), true);
});
test('reply, status, and note saves refresh detail and list while restoring other drafts', async (t) => {
for (const kind of ['reply', 'status', 'note']) {
await t.test(`${kind} save`, async () => {
const runtime = makeRuntime();
await loadDetail(runtime);
let forms = formsIn(runtime);
setField(forms.reply, '[name="content"]', 'Draft reply');
setField(forms.status, '[name="status"]', 'handling');
setField(forms.status, '[name="ticket_type_id"]', '6');
setField(forms.status, '[name="admin_id"]', '44');
setField(forms.note, '[name="content"]', 'Draft note');
runtime.root.fire('change', { target: forms.status.querySelector('[name="status"]') });
fireSubmit(runtime, forms[kind]);
assert.equal(runtime.fetchCalls.length, 2);
const post = runtime.fetchCalls[1];
assert.equal(post.options.method, 'POST');
assert.equal(post.options.headers['X-WP-Nonce'], 'rest-nonce');
const body = submitBody(post);
if (kind === 'status') assert.deepEqual(body, { status: 'handling', ticket_type_id: '6', admin_id: '44' });
else assert.deepEqual(body, { content: kind === 'reply' ? 'Draft reply' : 'Draft note' });
resolveFetch(runtime, 1, { success: true, data: { saved: true } });
await tick();
assert.equal(runtime.fetchCalls.length, 3);
const statusAfterSave = kind === 'status' ? 'handling' : 'pending';
resolveFetch(runtime, 2, {
success: true,
data: { panel: `ticket:41:${statusAfterSave}`, title: 'Ticket 41', description: '#41', list: `rows-after-${kind}`, page: 1 },
});
await tick();
forms = formsIn(runtime);
assert.equal(runtime.list.innerHTML, `rows-after-${kind}`);
if (kind !== 'reply') assert.equal(forms.reply.querySelector('[name="content"]').value, 'Draft reply');
if (kind !== 'status') {
assert.equal(forms.status.querySelector('[name="status"]').value, 'handling');
assert.equal(forms.status.querySelector('[name="ticket_type_id"]').value, '6');
assert.equal(forms.status.querySelector('[name="admin_id"]').value, '44');
}
if (kind !== 'note') assert.equal(forms.note.querySelector('[name="content"]').value, 'Draft note');
if (kind === 'reply') assert.equal(forms.reply.querySelector('[name="content"]').value, '');
assert.equal(runtime.detailDialog.querySelector('[data-aksrt-ticket-feedback] p').textContent, strings[kind]);
});
}
});
test('closing requires checkbox confirmation, and “assign to me” selects the current handler', async () => {
const runtime = makeRuntime();
await loadDetail(runtime);
const forms = formsIn(runtime);
const statusForm = forms.status;
const status = statusForm.querySelector('[name="status"]');
const confirm = statusForm.querySelector('[data-aksrt-ticket-close-confirm]');
status.value = 'closed';
runtime.root.fire('change', { target: status });
assert.equal(statusForm.querySelector('[data-aksrt-ticket-close-warning]').hidden, false);
assert.equal(confirm.required, true);
assert.equal(confirm.checked, false);
const blocked = fireSubmit(runtime, statusForm);
assert.equal(blocked.defaultPrevented, true);
assert.equal(runtime.fetchCalls.length, 1);
confirm.checked = true;
assert.equal(statusForm.reportValidity(), true);
status.value = 'pending';
runtime.root.fire('change', { target: status });
status.value = 'pending';
const assign = runtime.panel.querySelector('[data-aksrt-ticket-assign]');
runtime.root.fire('click', { target: assign });
assert.equal(statusForm.querySelector('[name="admin_id"]').value, '44');
assert.equal(status.value, 'handling');
assert.equal(runtime.document.activeElement, statusForm.querySelector('[type="submit"]'));
});
test('an overlong prereply is rejected without changing the editor', async () => {
const runtime = makeRuntime();
await loadDetail(runtime);
const reply = formsIn(runtime).reply;
const editor = reply.querySelector('textarea');
editor.value = 'Existing text';
editor.selectionStart = 4;
editor.selectionEnd = 4;
const preset = reply.querySelector('[data-aksrt-ticket-prereply]');
preset.value = '01234567890123456789012345';
runtime.root.fire('change', { target: preset });
assert.equal(editor.value, 'Existing text');
assert.equal(preset.value, '');
assert.equal(runtime.detailDialog.querySelector('[data-aksrt-ticket-feedback] p').textContent, strings.tooLong);
});
test('a saved write followed by a failed refresh retries only the read', async () => {
const runtime = makeRuntime();
await loadDetail(runtime);
const forms = formsIn(runtime);
setField(forms.reply, '[name="content"]', 'Send once');
setField(forms.note, '[name="content"]', 'Keep this draft');
fireSubmit(runtime, forms.reply);
resolveFetch(runtime, 1, { success: true, data: { reply_id: 2 } });
await tick();
assert.equal(runtime.fetchCalls.length, 3);
assert.equal(runtime.fetchCalls[2].options.method, undefined);
resolveFetch(runtime, 2, { success: false, message: 'Read temporarily failed' }, 500);
await tick();
assert.equal(runtime.detailDialog.querySelector('[data-aksrt-ticket-feedback] p').textContent, strings.refreshFailed);
assert.equal(runtime.fetchCalls.filter((call) => call.options.method === 'POST').length, 1);
const retry = runtime.detailDialog.querySelector('[data-aksrt-ticket-retry]');
assert.equal(retry.hidden, false);
runtime.root.fire('click', { target: retry });
assert.equal(runtime.fetchCalls.length, 4);
assert.equal(runtime.fetchCalls[3].options.method, undefined);
resolveFetch(runtime, 3, { success: true, data: { panel: 'ticket:41', title: 'Ticket 41', description: '#41', list: 'fresh rows', page: 1 } });
await tick();
assert.equal(runtime.fetchCalls.filter((call) => call.options.method === 'POST').length, 1);
assert.equal(formsIn(runtime).note.querySelector('[name="content"]').value, 'Keep this draft');
});
test('an unknown write result requires a full refresh check and is not retried automatically', async () => {
const runtime = makeRuntime();
await loadDetail(runtime);
const replyForm = formsIn(runtime).reply;
setField(replyForm, '[name="content"]', 'May have been sent');
fireSubmit(runtime, replyForm);
rejectFetch(runtime, 1);
await tick();
assert.equal(runtime.detailDialog.querySelector('[data-aksrt-ticket-feedback] p').textContent, strings.uncertain);
assert.equal(runtime.detailDialog.querySelector('[data-aksrt-ticket-retry]').hidden, false);
assert.equal(runtime.fetchCalls.filter((call) => call.options.method === 'POST').length, 1);
runtime.root.fire('click', { target: runtime.detailDialog.querySelector('[data-aksrt-ticket-retry]') });
assert.equal(runtime.window.location.reloadCount, 1);
assert.equal(runtime.fetchCalls.filter((call) => call.options.method === 'POST').length, 1);
});
test('deleted or inaccessible tickets lock stale forms and route retries to reload', async (t) => {
const read = makeRuntime();
read.root.fire('click', { target: read.viewsById.get('41') });
resolveFetch(read, 0, { success: false, message: 'Ticket missing' }, 404);
await tick();
assert.equal(new URL(read.window.location.href).searchParams.has('id'), false);
const readRetry = read.detailDialog.querySelector('[data-aksrt-ticket-retry]');
assert.equal(readRetry.hidden, false);
read.root.fire('click', { target: readRetry });
assert.equal(read.window.location.reloadCount, 1);
for (const status of [404, 403]) {
await t.test(`write ${status}`, async () => {
const runtime = makeRuntime();
await loadDetail(runtime);
const reply = formsIn(runtime).reply;
setField(reply, '[name="content"]', 'Reply once');
fireSubmit(runtime, reply);
resolveFetch(runtime, 1, { success: false, message: 'Ticket unavailable' }, status);
await tick();
assert.equal(reply.querySelector('textarea').disabled, true);
assert.equal(runtime.fetchCalls.filter((call) => call.options.method === 'POST').length, 1);
const retry = runtime.detailDialog.querySelector('[data-aksrt-ticket-retry]');
assert.equal(retry.hidden, false);
if (status === 404) assert.equal(new URL(runtime.window.location.href).searchParams.has('id'), false);
fireSubmit(runtime, reply);
assert.equal(runtime.fetchCalls.length, 2);
runtime.root.fire('click', { target: retry });
assert.equal(runtime.window.location.reloadCount, 1);
assert.equal(runtime.fetchCalls.length, 2);
});
}
});
@@ -0,0 +1,166 @@
<?php
/** Runs the real native renderers and query builder without a WordPress installation. */
namespace {
define('ABSPATH', __DIR__);
define('ARRAY_A', 'ARRAY_A');
$GLOBALS['allowed'] = true;
$GLOBALS['valid_nonce'] = true;
function __($text, $domain = '') { return $text; }
function esc_html($text) { return htmlspecialchars((string) $text, ENT_QUOTES, 'UTF-8'); }
function esc_attr($text) { return esc_html($text); }
function esc_html__($text, $domain = '') { return esc_html($text); }
function esc_attr__($text, $domain = '') { return esc_attr($text); }
function esc_url($url) { return preg_match('~^(https?://|#)~', (string) $url) ? esc_attr($url) : ''; }
function wpautop($text) { return '<p>' . str_replace("\n\n", '</p><p>', $text) . '</p>'; }
function sanitize_key($text) { return preg_replace('/[^a-z0-9_\-]/', '', strtolower((string) $text)); }
function sanitize_text_field($text) { return trim(strip_tags((string) $text)); }
function wp_unslash($text) { return stripslashes((string) $text); }
function absint($value) { return abs((int) $value); }
function selected($a, $b, $echo = true) { return (string) $a === (string) $b ? ' selected="selected"' : ''; }
function number_format_i18n($number) { return number_format($number); }
function admin_url($path) { return 'https://example.test/wp-admin/' . $path; }
function rest_url($path) { return 'https://example.test/wp-json/' . $path; }
function get_current_user_id() { return 7; }
function wp_get_current_user() { return (object) ['ID' => 7, 'display_name' => 'Operator']; }
function get_users($args) { return [(object) ['ID' => 7, 'display_name' => 'Operator'], (object) ['ID' => 8, 'display_name' => 'Second']]; }
function get_edit_user_link($id) { return admin_url('user-edit.php?user_id=' . $id); }
function aksrt_get_avatar_url($id, $size) { return 'https://example.test/avatar/' . $id; }
function current_user_can($cap) { return $GLOBALS['allowed']; }
function check_ajax_referer($action, $key, $die) { return $action === 'aksrt_ticket_view' && $key === 'nonce' && $GLOBALS['valid_nonce']; }
function add_query_arg($args, $url, $base = null) {
if (!is_array($args)) { $args = [$args => $url]; $url = $base; }
$parts = parse_url($url);
parse_str($parts['query'] ?? '', $query);
return $parts['scheme'] . '://' . $parts['host'] . ($parts['path'] ?? '') . '?' . http_build_query(array_merge($query, $args));
}
class JsonReply extends \Exception {
public function __construct(public array $payload, public int $status) { parent::__construct(); }
}
function wp_send_json_success($data) { throw new JsonReply(['success' => true, 'data' => $data], 200); }
function wp_send_json_error($data, $status) { throw new JsonReply(['success' => false, 'data' => $data], $status); }
}
namespace AKSRT\Ticket {
class TicketSettings {
public static bool $orders = true;
public static function title_max() { return 100; }
public static function content_max() { return 1000; }
public static function reply_max() { return 500; }
public static function order_link_enabled() { return self::$orders; }
}
class TicketTypeService {
public static bool $empty = false;
public static function all() { return self::$empty ? [] : [['id' => 1, 'name' => 'Support <script>']]; }
}
class TicketStatusService {
public const KEY_PENDING = 'pending';
public const KEY_USER_REPLIED = 'user_replied';
public static function all() {
return [
['status_key' => 'pending', 'name' => '待接单', 'is_closed' => 0, 'color' => '#f0a020'],
['status_key' => 'handling', 'name' => '处理中', 'is_closed' => 0, 'color' => '#18a058'],
['status_key' => 'closed', 'name' => '已关闭', 'is_closed' => 1, 'color' => '#999999'],
['status_key' => 'archived', 'name' => '已归档', 'is_closed' => 1, 'color' => '#999999'],
];
}
public static function map() { return array_column(self::all(), null, 'status_key'); }
public static function can_transition($from, $to) { return $from !== 'closed' && !($from === 'pending' && $to === 'closed'); }
}
class TicketPrereplyService {
public static function all() { return [['content' => 'Preset <script>alert(1)</script>']]; }
}
class TicketNoteService {
public static function for_ticket($id) { return [['admin_name' => 'Admin <img>', 'created_at' => '2026-10-31', 'content' => 'Secret <script>alert(1)</script>']]; }
}
class TicketRepository {
public static array $queries = [];
public static array $counts = [];
public static int $reads = 0;
public static int $replies_read = 0;
public static function get_instance() { static $repo; return $repo ??= new self(); }
public function sample($id = 21) {
return [
'id' => $id, 'ticket_num' => 'TK-000' . $id, 'title' => 'Question <svg onload=alert(1)>',
'user_id' => 12, 'user_name' => 'User <b>x</b>', 'admin_id' => 7, 'admin_name' => 'Operator',
'ticket_type_id' => 1, 'ticket_type_name' => 'Support <script>',
'status' => $id === 99 ? 'closed' : 'handling', 'status_label' => $id === 99 ? '已关闭' : '处理中', 'status_color' => '#18a058', 'is_closed' => $id === 99,
'content' => 'Description <script>alert(1)</script>', 'attachment' => ['https://example.test/image.jpg'],
'post_time' => '2026-10-30 12:00:00', 'last_reply_time' => '', 'post_admin_id' => 7,
'order_number' => 'ORDER-1', 'urge_count' => 1, 'last_urge_time' => '2026-10-31 11:00:00',
];
}
public function find($id) { self::$reads++; return $id === 404 ? null : $this->sample($id); }
public function paginate($args, $admin) {
self::$queries[] = $args;
return ['items' => $args['offset'] > 20 ? [] : [$this->sample()], 'total' => 21];
}
public function statistic($args, $admin) { self::$counts[] = $args; return ['pending' => 2, 'handling' => 4, 'closed' => 6, 'archived' => 3]; }
public function replies($id) {
self::$replies_read++;
return [
['author_type' => 'system', 'content' => '催单', 'created_at' => '2026-10-31'],
['author_type' => 'user', 'author_id' => 12, 'author_name' => 'User', 'content' => 'Reply <script>', 'created_at' => '2026-10-31', 'attachment' => [], 'quote' => ['is_deleted' => true, 'content' => 'Deleted']],
];
}
}
}
namespace AKSRT\Core {
class DBMigrator { public static function table($name) { return 'wp_aksrt_' . $name; } }
}
namespace {
$root = dirname(__DIR__, 2);
foreach (['NativeUi', 'AdminListPagination', 'UsersMenusTicketsList', 'UsersMenusTicketsDialogs', 'UsersMenusTicketsDetail', 'UsersMenusTicketsCenter'] as $file) {
require $root . '/src/Admin/Native/' . $file . '.php';
}
require $root . '/src/Ticket/TicketQuery.php';
class TicketPage {
use \AKSRT\Admin\Native\UsersMenusTicketsCenter;
public const CAPABILITY = 'manage_options';
private function ensure_cap() {}
}
class QueryProbe {
use \AKSRT\Ticket\TicketQuery;
public function where($args) { return $this->ticket_where($args, true); }
public function counts($args) { return $this->ticket_statistic($args, true); }
}
class FakeDb {
public array $params = [];
public string $sql = '';
public function esc_like($text) { return addcslashes($text, '_%\\'); }
public function prepare($sql, $params) { $this->sql = $sql; $this->params = $params; return $sql; }
public function get_results($sql, $format) { return [['status' => 'closed', 'total' => 2]]; }
}
$page = new TicketPage();
$_GET = ['status' => 'handling', 'ticket_type_id' => 1, 's' => 'needle', 'paged' => 99, 'id' => 99];
ob_start();
$page->render_tickets_page();
$html = ob_get_clean();
$initial = ['queries' => \AKSRT\Ticket\TicketRepository::$queries, 'counts' => \AKSRT\Ticket\TicketRepository::$counts, 'detail_reads' => \AKSRT\Ticket\TicketRepository::$reads, 'reply_reads' => \AKSRT\Ticket\TicketRepository::$replies_read];
function view($page, array $args) {
$_GET = $args;
try { $page->ajax_ticket_view(); } catch (JsonReply $reply) { return ['status' => $reply->status] + $reply->payload; }
throw new \RuntimeException('Expected JSON response');
}
$closed = view($page, ['id' => 99, 'status' => 'pending', 's' => 'not in list', 'refresh_list' => 1, 'paged' => 99]);
$open = view($page, ['id' => 21]);
$missing = view($page, ['id' => 404]);
$GLOBALS['allowed'] = false;
$denied = view($page, ['id' => 21]);
$GLOBALS['allowed'] = true;
$GLOBALS['valid_nonce'] = false;
$nonce = view($page, ['id' => 21]);
$GLOBALS['valid_nonce'] = true;
\AKSRT\Ticket\TicketTypeService::$empty = true;
ob_start();
$page->render_tickets_page();
$no_types = ob_get_clean();
\AKSRT\Ticket\TicketTypeService::$empty = false;
\AKSRT\Ticket\TicketSettings::$orders = false;
ob_start();
$page->render_tickets_page();
$no_orders = ob_get_clean();
$GLOBALS['wpdb'] = new FakeDb();
$query = new QueryProbe();
$where = $query->where([]);
$statistic = $query->counts(['status' => ['pending', 'handling', 'closed', 'archived'], 'ticket_type_id' => 1, 'keywords' => 'needle']);
echo json_encode(compact('html', 'initial', 'closed', 'open', 'missing', 'denied', 'nonce', 'no_types', 'no_orders', 'where', 'statistic') + ['count_sql' => $GLOBALS['wpdb']->sql, 'count_params' => $GLOBALS['wpdb']->params], JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
}
+86
View File
@@ -0,0 +1,86 @@
'use strict';
const assert = require('node:assert/strict');
const path = require('node:path');
const { spawnSync } = require('node:child_process');
const test = require('node:test');
let fixture;
function rendered() {
if (!fixture) {
const run = spawnSync(process.env.PHP_BINARY || 'php', [path.join(__dirname, 'ticket-native-render-harness.php')], { encoding: 'utf8' });
assert.equal(run.status, 0, run.stderr || run.stdout);
fixture = JSON.parse(run.stdout);
}
return fixture;
}
test('page renders header creation action and one of each dialog, without eagerly reading conversations', () => {
const { html, initial } = rendered();
assert.equal((html.match(/<dialog /g) || []).length, 2);
assert.match(html, /aksrt-native-header__actions[^]*data-aksrt-dialog-open="aksrt-ticket-create-dialog"/);
assert.match(html, /aria-controls="aksrt-ticket-detail-dialog"/);
assert.doesNotMatch(html, /<details|detail-row|data-aksrt-ticket-detail="/);
assert.equal(initial.detail_reads, 0);
assert.equal(initial.reply_reads, 0);
assert.equal(initial.queries.at(-1).offset, 20);
assert.equal(initial.queries.at(-1).limit, 20);
assert.deepEqual(initial.counts[0], { status: ['pending', 'handling', 'closed', 'archived'], ticket_type_id: 1, keywords: 'needle' });
assert.match(html, /status=closed&amp;ticket_type_id=1&amp;s=needle/);
});
test('detail is independently loaded even for a closed ticket outside current filters', () => {
const { closed, open } = rendered();
assert.equal(closed.status, 200);
assert.equal(closed.data.page, 2);
assert.match(closed.data.panel, /data-aksrt-ticket-detail="99"/);
assert.match(closed.data.panel, /aksrt-ticket-detail__closed/);
assert.match(closed.data.panel, /data-aksrt-ticket-form="note"/);
assert.doesNotMatch(closed.data.panel, /data-aksrt-ticket-form="(?:reply|status)"/);
assert.match(closed.data.list, /data-aksrt-ticket-view="21"/);
for (const action of ['reply', 'status', 'note']) assert.ok(open.data.panel.includes(`data-aksrt-ticket-form="${action}"`));
assert.match(open.data.panel, /action="https:\/\/example.test\/wp-json\/aksrt\/v1\/admin\/tickets\/21\/notes"/);
assert.match(open.data.panel, /data-aksrt-ticket-close-confirm/);
assert.match(open.data.panel, /value="closed" data-closed="1"/);
});
test('read handler enforces capability, nonce and record existence', () => {
const { missing, denied, nonce } = rendered();
assert.equal(missing.status, 404);
assert.equal(denied.status, 403);
assert.equal(nonce.status, 403);
for (const result of [missing, denied, nonce]) {
assert.equal(result.success, false);
assert.equal(result.data.panel, undefined);
assert.equal(result.data.list, undefined);
}
});
test('real rendering escapes user content, quotes and metadata', () => {
const { html, open } = rendered();
const all = html + open.data.panel;
assert.match(all, /Question &lt;svg onload=alert\(1\)&gt;/);
assert.match(all, /Description &lt;script&gt;alert\(1\)&lt;\/script&gt;/);
assert.match(all, /Secret &lt;script&gt;alert\(1\)&lt;\/script&gt;/);
assert.match(all, /原回复已删除/);
assert.match(all, /target="_blank" rel="noopener noreferrer"/);
assert.doesNotMatch(all, /<script>|<svg onload|<img>/);
assert.doesNotMatch(all, /admin-post.php|name="ticket_action"|name="_wpnonce"/);
});
test('missing departments and disabled order links have explicit creation states', () => {
const { no_types: noTypes, no_orders: noOrders } = rendered();
assert.match(noTypes, /尚未配置工单部门/);
assert.doesNotMatch(noTypes, /data-aksrt-ticket-form="create"/);
assert.match(noTypes, /前往工单配置/);
assert.doesNotMatch(noOrders, /name="order_number"/);
});
test('query builder excludes every terminal state and filtered counts use the same conditions', () => {
const { where, count_sql: sql, count_params: params, statistic } = rendered();
assert.match(where[0], /status NOT IN \(%s, %s\)/);
assert.deepEqual(where[1], ['closed', 'archived']);
assert.match(sql, /status IN \(%s, %s, %s, %s\)/);
assert.match(sql, /ticket_type_id = %d/);
assert.match(sql, /ticket_num LIKE %s OR title LIKE %s/);
assert.deepEqual(params, ['pending', 'handling', 'closed', 'archived', 1, '%needle%', '%needle%']);
assert.equal(statistic.closed, 2);
});