feat(admin): replace ticket dialogs with in-page views
Ticket handling on users.php?page=aksrt_tickets no longer uses dialogs. The list, the workspace (?id=N) and the assisted create form (?view=new) are server-rendered page views that carry the list filters and page for going back. Writes still go through the ticket REST routes; on success the page reloads with a native notice, and unsent drafts in other forms survive the reload via sessionStorage. Uncertain or conflicting writes lock every form and only offer a reload. Remove dead code: UsersMenusTicketsDialogs, the aksrt_ticket_view AJAX read and its nonce, dialog CSS/JS (backdrop, scroll lock, focus return, read races) and the dialog runtime test. Fix the create link carrying an unclamped page number on out-of-range list pages. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
1 parent
48e54dc115
commit
d86a85e6a6
13 files changed
+720
-1264
No files matched your search
@@ -1,686 +0,0 @@
|
||||
'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';
|
||||
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, 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}`, 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', 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', 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', 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', 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', 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);
|
||||
});
|
||||
}
|
||||
});
|
||||
@@ -3,8 +3,6 @@
|
||||
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); }
|
||||
@@ -25,19 +23,12 @@ namespace {
|
||||
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 {
|
||||
@@ -108,7 +99,7 @@ namespace AKSRT\Core {
|
||||
}
|
||||
namespace {
|
||||
$root = dirname(__DIR__, 2);
|
||||
foreach (['NativeUi', 'AdminListPagination', 'UsersMenusTicketsList', 'UsersMenusTicketsDialogs', 'UsersMenusTicketsDetail', 'UsersMenusTicketsCenter'] as $file) {
|
||||
foreach (['NativeUi', 'AdminListPagination', 'UsersMenusTicketsList', 'UsersMenusTicketsCreate', 'UsersMenusTicketsDetail', 'UsersMenusTicketsCenter'] as $file) {
|
||||
require $root . '/src/Admin/Native/' . $file . '.php';
|
||||
}
|
||||
require $root . '/src/Ticket/TicketQuery.php';
|
||||
@@ -129,38 +120,31 @@ namespace {
|
||||
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');
|
||||
function render_page(TicketPage $page, array $get): string {
|
||||
$_GET = $get;
|
||||
ob_start();
|
||||
$page->render_tickets_page();
|
||||
return (string) ob_get_clean();
|
||||
}
|
||||
$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;
|
||||
$repo = \AKSRT\Ticket\TicketRepository::class;
|
||||
$page = new TicketPage();
|
||||
$list = render_page($page, ['status' => 'handling', 'ticket_type_id' => 1, 's' => 'needle', 'paged' => 99]);
|
||||
$initial = ['queries' => $repo::$queries, 'counts' => $repo::$counts, 'detail_reads' => $repo::$reads, 'reply_reads' => $repo::$replies_read];
|
||||
$list_queries = count($repo::$queries);
|
||||
$open = render_page($page, ['id' => 21, 'status' => 'pending', 's' => 'not in list', 'paged' => 3, 'aksrt_ticket_msg' => 'reply']);
|
||||
$closed = render_page($page, ['id' => 99]);
|
||||
$missing = render_page($page, ['id' => 404]);
|
||||
$detail_list_queries = count($repo::$queries) - $list_queries;
|
||||
$create = render_page($page, ['view' => 'new', 'status' => 'pending', 'paged' => 2]);
|
||||
$bogus_notice = render_page($page, ['id' => 21, 'aksrt_ticket_msg' => '<script>']);
|
||||
\AKSRT\Ticket\TicketTypeService::$empty = true;
|
||||
ob_start();
|
||||
$page->render_tickets_page();
|
||||
$no_types = ob_get_clean();
|
||||
$no_types = render_page($page, ['view' => 'new']);
|
||||
\AKSRT\Ticket\TicketTypeService::$empty = false;
|
||||
\AKSRT\Ticket\TicketSettings::$orders = false;
|
||||
ob_start();
|
||||
$page->render_tickets_page();
|
||||
$no_orders = ob_get_clean();
|
||||
$no_orders = render_page($page, ['view' => 'new']);
|
||||
$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);
|
||||
echo json_encode(compact('list', 'initial', 'open', 'closed', 'missing', 'detail_list_queries', 'create', 'bogus_notice', '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);
|
||||
}
|
||||
@@ -13,82 +13,94 @@ function rendered() {
|
||||
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, /aksrt-ticket-detail-description/);
|
||||
assert.match(html, /id="aksrt-ticket-create-description"/);
|
||||
assert.doesNotMatch(html, /<details|detail-row|data-aksrt-ticket-detail="/);
|
||||
test('list view links to page views and renders no dialogs or eager conversations', () => {
|
||||
const { list, initial } = rendered();
|
||||
assert.doesNotMatch(list, /<dialog|data-aksrt-dialog-open|aria-haspopup="dialog"/);
|
||||
assert.match(list, /aksrt-native-header__actions[^]*href="[^"]*page=aksrt_tickets&view=new&status=handling&ticket_type_id=1&s=needle&paged=2"/);
|
||||
assert.match(list, /<a class="row-title" href="[^"]*page=aksrt_tickets&id=21&status=handling&ticket_type_id=1&s=needle&paged=2"/);
|
||||
assert.doesNotMatch(list, /data-aksrt-ticket-detail=|data-aksrt-ticket-form=/);
|
||||
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&ticket_type_id=1&s=needle/);
|
||||
assert.match(list, /status=closed&ticket_type_id=1&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"/);
|
||||
assert.equal(open.data.description, undefined);
|
||||
assert.match(open.data.panel, /<dt>工单号<\/dt><dd>TK-00021<\/dd>/);
|
||||
test('workspace loads by ID independent of list filters and keeps the list context for going back', () => {
|
||||
const { open, closed, detail_list_queries: listQueries } = rendered();
|
||||
assert.equal(listQueries, 0, 'workspace must not query the list');
|
||||
assert.match(open, /<h1 class="aksrt-native-header__title">[^]*Question <svg onload=alert\(1\)><\/h1>/);
|
||||
assert.match(open, /href="[^"]*page=aksrt_tickets&status=pending&s=not\+in\+list&paged=3"[^>]*>[^]*返回工单列表/);
|
||||
assert.match(open, /data-aksrt-ticket-detail="21"/);
|
||||
for (const action of ['reply', 'status', 'note']) assert.ok(open.includes(`data-aksrt-ticket-form="${action}"`));
|
||||
assert.match(open, /action="https:\/\/example.test\/wp-json\/aksrt\/v1\/admin\/tickets\/21\/notes"/);
|
||||
assert.match(open, /data-aksrt-ticket-close-confirm/);
|
||||
assert.match(open, /value="closed" data-closed="1"/);
|
||||
assert.match(open, /<dt>工单号<\/dt><dd>TK-00021<\/dd>/);
|
||||
assert.match(open, /data-aksrt-ticket-feedback/);
|
||||
assert.match(closed, /data-aksrt-ticket-detail="99"/);
|
||||
assert.match(closed, /aksrt-ticket-detail__closed/);
|
||||
assert.match(closed, /data-aksrt-ticket-form="note"/);
|
||||
assert.doesNotMatch(closed, /data-aksrt-ticket-form="(?:reply|status)"/);
|
||||
for (const html of [open, closed]) assert.doesNotMatch(html, /<dialog|data-aksrt-dialog-close/);
|
||||
});
|
||||
|
||||
test('result codes render as one native notice and unknown codes are ignored', () => {
|
||||
const { open, closed, bogus_notice: bogus } = rendered();
|
||||
assert.match(open, /<div class="notice notice-success is-dismissible"><p>回复已发送,用户将收到通知。<\/p><\/div>/);
|
||||
assert.doesNotMatch(closed, /notice-success/);
|
||||
assert.doesNotMatch(bogus, /class="notice\b/);
|
||||
assert.doesNotMatch(bogus, /<script>/);
|
||||
});
|
||||
|
||||
test('ticket information owns the only status editor and closed tickets stay read-only', () => {
|
||||
const { open, closed } = rendered();
|
||||
const sidebarCards = panel => {
|
||||
const sidebar = panel.match(/<aside\b[^>]*>([\s\S]*?)<\/aside>/)?.[1] || '';
|
||||
const sidebarCards = html => {
|
||||
const sidebar = html.match(/<aside\b[^>]*>([\s\S]*?)<\/aside>/)?.[1] || '';
|
||||
return [...sidebar.matchAll(/<section class="aksrt-ticket-detail__card(?: [^"]+)?">([\s\S]*?)<\/section>/g)].map(match => match[1]);
|
||||
};
|
||||
const cards = sidebarCards(open.data.panel);
|
||||
const cards = sidebarCards(open);
|
||||
assert.equal(cards.length, 2, 'only ticket information and internal notes remain');
|
||||
const info = cards[0];
|
||||
assert.match(info, /<h3>工单信息<\/h3>/);
|
||||
assert.match(info, /data-aksrt-ticket-form="status"/);
|
||||
assert.match(info, /data-aksrt-ticket-assign/);
|
||||
assert.match(info, /保存工单信息/);
|
||||
assert.doesNotMatch(open.data.panel, /<h3[^>]*>处理工单<\/h3>/);
|
||||
assert.doesNotMatch(info, /aksrt-ticket-badge/);
|
||||
for (const [name, label] of [['status', '状态'], ['ticket_type_id', '部门'], ['admin_id', '跟进人']]) {
|
||||
const id = `aksrt-ticket-${name}-21`;
|
||||
assert.ok(info.includes(`<label for="${id}">${label}</label>`));
|
||||
assert.ok(info.includes(`<select id="${id}" name="${name}"`));
|
||||
assert.equal((open.data.panel.match(new RegExp(`name="${name}"`, 'g')) || []).length, 1);
|
||||
assert.equal((open.match(new RegExp(`name="${name}"`, 'g')) || []).length, 1);
|
||||
}
|
||||
assert.match(cards[1], /内部备注/);
|
||||
const closedInfo = sidebarCards(closed.data.panel)[0];
|
||||
const closedInfo = sidebarCards(closed)[0];
|
||||
assert.match(closedInfo, /<h3>工单信息<\/h3>/);
|
||||
assert.match(closedInfo, /aksrt-ticket-badge/);
|
||||
assert.doesNotMatch(closedInfo, /<form|<select|data-aksrt-ticket-assign|保存工单信息/);
|
||||
});
|
||||
|
||||
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('missing ticket renders an empty state with a way back and no forms', () => {
|
||||
const { missing } = rendered();
|
||||
assert.match(missing, /工单不存在/);
|
||||
assert.match(missing, /返回工单列表/);
|
||||
assert.doesNotMatch(missing, /data-aksrt-ticket-form|data-aksrt-ticket-detail/);
|
||||
});
|
||||
|
||||
test('create page is a full-page form that posts to REST and returns to the list context', () => {
|
||||
const { create } = rendered();
|
||||
assert.doesNotMatch(create, /<dialog|data-aksrt-dialog/);
|
||||
assert.match(create, /<form method="post" action="https:\/\/example.test\/wp-json\/aksrt\/v1\/admin\/tickets" class="aksrt-tickets-admin__create-form" data-aksrt-ticket-form="create">/);
|
||||
for (const name of ['user_id', 'ticket_type_id', 'title', 'order_number', 'content']) assert.ok(create.includes(`name="${name}"`), name);
|
||||
assert.match(create, /data-aksrt-ticket-feedback/);
|
||||
const back = /href="[^"]*page=aksrt_tickets&status=pending&paged=2"/g;
|
||||
assert.equal((create.match(back) || []).length, 2, 'header back link and cancel both keep the list context');
|
||||
});
|
||||
|
||||
test('real rendering escapes user content, quotes and metadata', () => {
|
||||
const { html, open } = rendered();
|
||||
const all = html + open.data.panel;
|
||||
const { list, open } = rendered();
|
||||
const all = list + open;
|
||||
assert.match(all, /Question <svg onload=alert\(1\)>/);
|
||||
assert.match(all, /Description <script>alert\(1\)<\/script>/);
|
||||
assert.match(all, /Secret <script>alert\(1\)<\/script>/);
|
||||
@@ -103,6 +115,7 @@ test('missing departments and disabled order links have explicit creation states
|
||||
assert.match(noTypes, /尚未配置工单部门/);
|
||||
assert.doesNotMatch(noTypes, /data-aksrt-ticket-form="create"/);
|
||||
assert.match(noTypes, /前往工单配置/);
|
||||
assert.match(noOrders, /data-aksrt-ticket-form="create"/);
|
||||
assert.doesNotMatch(noOrders, /name="order_number"/);
|
||||
});
|
||||
|
||||
|
||||
@@ -0,0 +1,344 @@
|
||||
'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 scriptPath = path.resolve(__dirname, '../../assets/js/admin-tickets.js');
|
||||
const strings = { saving: 'Saving', saveFailed: 'Save failed', uncertain: 'Unknown result', required: 'Required', tooLong: 'Too long' };
|
||||
const REST = 'https://site.test/wp-json/aksrt/v1/admin/tickets';
|
||||
|
||||
function makeRuntime({ href = 'https://site.test/wp-admin/users.php?page=aksrt_tickets&id=41', page = 'detail', storage = {} } = {}) {
|
||||
const ids = new Map();
|
||||
const document = { activeElement: null };
|
||||
|
||||
class Element {
|
||||
constructor(tag, attrs = {}) {
|
||||
this.tagName = tag.toUpperCase();
|
||||
this.attrs = { ...attrs };
|
||||
this.dataset = {};
|
||||
for (const [name, value] of Object.entries(attrs)) {
|
||||
const match = name.match(/^data-(.+)$/);
|
||||
if (match) this.dataset[match[1].replace(/-([a-z])/g, (_, c) => c.toUpperCase())] = String(value);
|
||||
}
|
||||
this.children = [];
|
||||
this.parentElement = null;
|
||||
this.listeners = {};
|
||||
this.id = attrs.id || '';
|
||||
this.name = attrs.name || '';
|
||||
this.type = attrs.type || (this.tagName === 'TEXTAREA' ? 'textarea' : '');
|
||||
this.action = attrs.action || '';
|
||||
this.required = Object.hasOwn(attrs, 'required');
|
||||
this.hidden = Object.hasOwn(attrs, 'hidden');
|
||||
this.maxLength = attrs.maxlength === undefined ? -1 : Number(attrs.maxlength);
|
||||
this.disabled = false;
|
||||
this.checked = false;
|
||||
this.validity = '';
|
||||
this.textContent = '';
|
||||
this.selectionStart = 0;
|
||||
this.selectionEnd = 0;
|
||||
this.scrollTop = 0;
|
||||
this.scrollHeight = 100;
|
||||
this.clientHeight = 40;
|
||||
this._value = String(attrs.value ?? '');
|
||||
this.selectedIndex = 0;
|
||||
const classes = new Set(String(attrs.class || '').split(/\s+/).filter(Boolean));
|
||||
this.classList = {
|
||||
contains: (name) => classes.has(name),
|
||||
toggle: (name, on) => { if (on) classes.add(name); else classes.delete(name); },
|
||||
};
|
||||
if (this.id) ids.set(this.id, this);
|
||||
}
|
||||
get options() { return this.children.filter((child) => child.tagName === 'OPTION'); }
|
||||
get value() { return this.tagName === 'SELECT' ? this.options[this.selectedIndex]?.value ?? '' : this._value; }
|
||||
set value(value) {
|
||||
this._value = String(value);
|
||||
if (this.tagName === 'SELECT') this.selectedIndex = this.options.findIndex((option) => option.value === this._value);
|
||||
}
|
||||
get form() { return this.closest('form'); }
|
||||
append(child) { child.parentElement = this; this.children.push(child); return child; }
|
||||
addEventListener(type, callback) { (this.listeners[type] ||= []).push(callback); }
|
||||
fire(type, values = {}) {
|
||||
const event = { target: this, defaultPrevented: false, preventDefault() { this.defaultPrevented = true; }, ...values };
|
||||
(this.listeners[type] || []).forEach((callback) => callback(event));
|
||||
return event;
|
||||
}
|
||||
querySelectorAll(selector) {
|
||||
const parts = expandIs(selector).split(',').map((part) => part.trim()).filter(Boolean);
|
||||
const found = new Set();
|
||||
const visit = (node) => node.children.forEach((child) => {
|
||||
if (parts.some((part) => matches(child, part))) found.add(child);
|
||||
visit(child);
|
||||
});
|
||||
visit(this);
|
||||
return [...found];
|
||||
}
|
||||
querySelector(selector) { return this.querySelectorAll(selector)[0] || null; }
|
||||
closest(selector) {
|
||||
for (let node = this; node; node = node.parentElement) if (node.matches(selector)) return node;
|
||||
return null;
|
||||
}
|
||||
matches(selector) { return expandIs(selector).split(',').some((part) => matches(this, part.trim())); }
|
||||
getAttribute(name) { return this.attrs[name] ?? null; }
|
||||
setAttribute(name, value) { this.attrs[name] = String(value); }
|
||||
focus() { document.activeElement = this; }
|
||||
setCustomValidity(message) { this.validity = message; }
|
||||
setSelectionRange(start, end) { this.selectionStart = start; this.selectionEnd = end; }
|
||||
reportValidity() {
|
||||
return this.querySelectorAll('input, select, textarea').every((control) => {
|
||||
if (control.validity) return false;
|
||||
if (!control.required) return true;
|
||||
return control.type === 'checkbox' ? control.checked : control.value.trim() !== '';
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// 把 `A :is(x, y), B` 展开成 `A x, B, A y, B`;结果去重。
|
||||
function expandIs(selector) {
|
||||
const match = selector.match(/^(.*?):is\(([^)]*)\)(.*)$/);
|
||||
return match ? match[2].split(',').map((part) => match[1] + part.trim() + match[3]).join(', ') : selector;
|
||||
}
|
||||
|
||||
function matches(element, selector) {
|
||||
const parts = selector.split(/\s+/);
|
||||
if (!matchesSimple(element, parts.pop())) return false;
|
||||
let ancestor = element.parentElement;
|
||||
while (parts.length) {
|
||||
const part = parts.pop();
|
||||
while (ancestor && !matchesSimple(ancestor, part)) ancestor = ancestor.parentElement;
|
||||
if (!ancestor) return false;
|
||||
ancestor = ancestor.parentElement;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
function matchesSimple(element, selector) {
|
||||
const tag = selector.match(/^[a-z][\w-]*/i)?.[0];
|
||||
if (tag && element.tagName !== tag.toUpperCase()) return false;
|
||||
for (const [, className] of selector.matchAll(/\.([\w-]+)/g)) if (!element.classList.contains(className)) return false;
|
||||
for (const [, name, expected] of selector.matchAll(/\[([^\]=]+)(?:="([^"]*)")?\]/g)) {
|
||||
if (!Object.hasOwn(element.attrs, name)) return false;
|
||||
if (expected !== undefined && String(element.attrs[name]) !== expected) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
const el = (tag, attrs, parent) => parent.append(new Element(tag, attrs));
|
||||
const select = (parent, attrs, choices, selected = '') => {
|
||||
const node = el('select', attrs, parent);
|
||||
choices.forEach(([value, extra = {}]) => el('option', { value, ...extra }, node));
|
||||
node.value = selected;
|
||||
return node;
|
||||
};
|
||||
|
||||
const root = new Element('div', { class: 'aksrt-tickets-admin' });
|
||||
const feedback = el('div', { 'data-aksrt-ticket-feedback': '', hidden: '' }, root);
|
||||
el('p', {}, feedback);
|
||||
el('button', { type: 'button', 'data-aksrt-ticket-reload': '', hidden: '' }, feedback);
|
||||
const nodes = { root, feedback };
|
||||
|
||||
if (page === 'detail') {
|
||||
const detail = el('div', { 'data-aksrt-ticket-detail': '41' }, root);
|
||||
nodes.latest = el('button', { type: 'button', 'data-aksrt-ticket-latest': '', hidden: '' }, detail);
|
||||
nodes.conversation = el('div', { class: 'aksrt-ticket-conversation__scroll' }, detail);
|
||||
const reply = nodes.reply = el('form', { action: `${REST}/41/reply`, 'data-aksrt-ticket-form': 'reply' }, detail);
|
||||
nodes.replyText = el('textarea', { id: 'aksrt-ticket-reply-41', name: 'content', required: '', maxlength: '24', 'data-aksrt-ticket-editor': '' }, reply);
|
||||
nodes.replyCount = el('span', { 'data-aksrt-ticket-counter': 'aksrt-ticket-reply-41' }, reply);
|
||||
nodes.prereply = select(reply, { 'data-aksrt-ticket-prereply': 'aksrt-ticket-reply-41' }, [[''], ['short'], ['01234567890123456789012345']]);
|
||||
el('button', { type: 'submit' }, reply);
|
||||
const section = el('section', {}, detail);
|
||||
nodes.assign = el('button', { type: 'button', 'data-aksrt-ticket-assign': '' }, section);
|
||||
const status = nodes.status = el('form', { action: `${REST}/41/status`, 'data-aksrt-ticket-form': 'status' }, section);
|
||||
nodes.statusSelect = select(status, { name: 'status', 'data-aksrt-ticket-status': '' }, [['pending', { 'data-closed': '0' }], ['handling', { 'data-closed': '0' }], ['closed', { 'data-closed': '1' }]], 'pending');
|
||||
select(status, { name: 'ticket_type_id', required: '' }, [['3'], ['6']], '3');
|
||||
nodes.admin = select(status, { name: 'admin_id' }, [['0'], ['7'], ['44']], '7');
|
||||
nodes.warning = el('div', { 'data-aksrt-ticket-close-warning': '', hidden: '' }, status);
|
||||
nodes.confirm = el('input', { type: 'checkbox', 'data-aksrt-ticket-close-confirm': '' }, nodes.warning);
|
||||
nodes.statusSubmit = el('button', { type: 'submit' }, status);
|
||||
const note = nodes.note = el('form', { action: `${REST}/41/notes`, 'data-aksrt-ticket-form': 'note' }, detail);
|
||||
nodes.noteText = el('textarea', { id: 'aksrt-ticket-note-41', name: 'content', required: '', maxlength: '24', 'data-aksrt-ticket-editor': '' }, note);
|
||||
el('button', { type: 'submit' }, note);
|
||||
} else {
|
||||
const create = nodes.create = el('form', { action: REST, 'data-aksrt-ticket-form': 'create' }, root);
|
||||
el('input', { type: 'number', name: 'user_id', required: '' }, create);
|
||||
select(create, { name: 'ticket_type_id', required: '' }, [[''], ['3']], '');
|
||||
el('input', { type: 'text', name: 'title', required: '' }, create);
|
||||
el('textarea', { id: 'aksrt-ticket-create-content', name: 'content', required: '', maxlength: '500', 'data-aksrt-ticket-editor': '' }, create);
|
||||
el('button', { type: 'submit' }, create);
|
||||
}
|
||||
|
||||
document.querySelector = (selector) => (selector === '.aksrt-tickets-admin' ? root : null);
|
||||
document.getElementById = (id) => ids.get(id) || null;
|
||||
|
||||
const store = new Map(Object.entries(storage));
|
||||
const window = new Element('window');
|
||||
Object.assign(window, {
|
||||
AKSRTAdminTickets: { restNonce: 'rest-nonce', currentUser: 44, strings },
|
||||
location: { href, assigned: null, reloads: 0, assign(url) { this.assigned = url; }, reload() { this.reloads += 1; } },
|
||||
history: { state: null, replaceState(_state, _title, url) { window.location.href = url; } },
|
||||
sessionStorage: { getItem: (key) => store.get(key) ?? null, setItem: (key, value) => store.set(key, String(value)), removeItem: (key) => store.delete(key) },
|
||||
});
|
||||
|
||||
const fetchCalls = [];
|
||||
const fetch = (url, options) => new Promise((resolve, reject) => fetchCalls.push({ url, options, resolve, reject }));
|
||||
vm.runInNewContext(fs.readFileSync(scriptPath, 'utf8'), { document, window, fetch, URL, AbortController, setTimeout, clearTimeout }, { filename: scriptPath });
|
||||
return { ...nodes, document, window, store, fetchCalls };
|
||||
}
|
||||
|
||||
const reply = (data, status = 200) => ({ ok: status >= 200 && status < 300, status, json: async () => data });
|
||||
const tick = () => new Promise((resolve) => setTimeout(resolve, 5));
|
||||
const type = (rt, field, value) => { field.value = value; rt.root.fire('input', { target: field }); };
|
||||
const submit = (rt, form) => rt.root.fire('submit', { target: form });
|
||||
const unload = (rt) => rt.window.fire('beforeunload', { returnValue: undefined });
|
||||
|
||||
test('a successful reply posts JSON to REST, then reloads the workspace with a result code and stashes other drafts', async () => {
|
||||
const rt = makeRuntime({ href: 'https://site.test/wp-admin/users.php?page=aksrt_tickets&id=41&status=pending&paged=3' });
|
||||
type(rt, rt.noteText, 'pending note');
|
||||
type(rt, rt.replyText, 'hello');
|
||||
const event = submit(rt, rt.reply);
|
||||
assert.equal(event.defaultPrevented, true);
|
||||
assert.equal(rt.fetchCalls.length, 1);
|
||||
const call = rt.fetchCalls[0];
|
||||
assert.equal(call.url, `${REST}/41/reply`);
|
||||
assert.equal(call.options.method, 'POST');
|
||||
assert.equal(call.options.headers['X-WP-Nonce'], 'rest-nonce');
|
||||
assert.deepEqual(JSON.parse(call.options.body), { content: 'hello' });
|
||||
assert.equal(rt.replyText.disabled, true, 'form locked while saving');
|
||||
submit(rt, rt.reply);
|
||||
assert.equal(rt.fetchCalls.length, 1, 'duplicate submit ignored');
|
||||
|
||||
call.resolve(reply({ success: true, data: { reply_id: 9 } }));
|
||||
await tick();
|
||||
const next = new URL(rt.window.location.assigned);
|
||||
assert.equal(next.searchParams.get('id'), '41');
|
||||
assert.equal(next.searchParams.get('aksrt_ticket_msg'), 'reply');
|
||||
assert.equal(next.searchParams.get('status'), 'pending');
|
||||
assert.equal(next.searchParams.get('paged'), '3');
|
||||
assert.deepEqual(JSON.parse(rt.store.get('aksrt-ticket-drafts-41')), { note: { content: 'pending note' } });
|
||||
assert.equal(unload(rt).defaultPrevented, false, 'navigation after save is not blocked');
|
||||
});
|
||||
|
||||
test('after the reload, stashed drafts are restored once and the result code is stripped from the URL', () => {
|
||||
const rt = makeRuntime({
|
||||
href: 'https://site.test/wp-admin/users.php?page=aksrt_tickets&id=41&aksrt_ticket_msg=reply',
|
||||
storage: { 'aksrt-ticket-drafts-41': JSON.stringify({ note: { content: 'keep me' } }) },
|
||||
});
|
||||
assert.equal(rt.noteText.value, 'keep me');
|
||||
assert.equal(rt.store.has('aksrt-ticket-drafts-41'), false);
|
||||
assert.equal(new URL(rt.window.location.href).searchParams.has('aksrt_ticket_msg'), false);
|
||||
assert.equal(new URL(rt.window.location.href).searchParams.get('id'), '41');
|
||||
assert.equal(unload(rt).defaultPrevented, true, 'a restored draft still counts as unsaved');
|
||||
});
|
||||
|
||||
test('create posts to the collection route and opens the new ticket workspace with the list context kept', async () => {
|
||||
const rt = makeRuntime({ page: 'create', href: 'https://site.test/wp-admin/users.php?page=aksrt_tickets&view=new&status=pending&paged=2' });
|
||||
const form = rt.create;
|
||||
form.querySelector('[name="user_id"]').value = '12';
|
||||
form.querySelector('[name="ticket_type_id"]').value = '3';
|
||||
type(rt, form.querySelector('[name="title"]'), 'Login fails');
|
||||
type(rt, form.querySelector('[name="content"]'), 'Details');
|
||||
submit(rt, form);
|
||||
assert.equal(rt.fetchCalls[0].url, REST);
|
||||
assert.deepEqual(JSON.parse(rt.fetchCalls[0].options.body), { user_id: '12', ticket_type_id: '3', title: 'Login fails', content: 'Details' });
|
||||
rt.fetchCalls[0].resolve(reply({ success: true, data: { id: 77 } }));
|
||||
await tick();
|
||||
const next = new URL(rt.window.location.assigned);
|
||||
assert.equal(next.searchParams.has('view'), false);
|
||||
assert.equal(next.searchParams.get('id'), '77');
|
||||
assert.equal(next.searchParams.get('aksrt_ticket_msg'), 'created');
|
||||
assert.equal(next.searchParams.get('status'), 'pending');
|
||||
assert.equal(next.searchParams.get('paged'), '2');
|
||||
});
|
||||
|
||||
test('whitespace-only content is rejected before any request', () => {
|
||||
const rt = makeRuntime();
|
||||
type(rt, rt.replyText, ' ');
|
||||
submit(rt, rt.reply);
|
||||
assert.equal(rt.fetchCalls.length, 0);
|
||||
assert.equal(rt.replyText.validity, strings.required);
|
||||
});
|
||||
|
||||
test('a confirmed validation error keeps the form editable and shows the server message without a reload button', async () => {
|
||||
const rt = makeRuntime();
|
||||
type(rt, rt.replyText, 'hello');
|
||||
submit(rt, rt.reply);
|
||||
rt.fetchCalls[0].resolve(reply({ code: 'aksrt_ticket_reply_content', message: 'Bad content', data: { status: 400 } }, 400));
|
||||
await tick();
|
||||
assert.equal(rt.window.location.assigned, null);
|
||||
assert.equal(rt.feedback.hidden, false);
|
||||
assert.equal(rt.feedback.querySelector('p').textContent, 'Bad content');
|
||||
assert.equal(rt.feedback.querySelector('[data-aksrt-ticket-reload]').hidden, true);
|
||||
assert.equal(rt.replyText.disabled, false);
|
||||
assert.equal(rt.replyText.value, 'hello');
|
||||
submit(rt, rt.reply);
|
||||
assert.equal(rt.fetchCalls.length, 2, 'retry allowed after a confirmed failure');
|
||||
});
|
||||
|
||||
for (const [label, settle] of [
|
||||
['an unknown network result', (call) => call.reject(new TypeError('network'))],
|
||||
['a 409 state conflict', (call) => call.resolve(reply({ code: 'aksrt_ticket_closed', message: 'Closed', data: { status: 409 } }, 409))],
|
||||
['a 404 missing ticket', (call) => call.resolve(reply({ code: 'aksrt_ticket_missing', message: 'Missing', data: { status: 404 } }, 404))],
|
||||
]) {
|
||||
test(`${label} locks every write form and only offers a page reload`, async () => {
|
||||
const rt = makeRuntime();
|
||||
type(rt, rt.replyText, 'hello');
|
||||
submit(rt, rt.reply);
|
||||
settle(rt.fetchCalls[0]);
|
||||
await tick();
|
||||
const reload = rt.feedback.querySelector('[data-aksrt-ticket-reload]');
|
||||
assert.equal(reload.hidden, false);
|
||||
for (const control of [rt.replyText, rt.noteText, rt.statusSelect, rt.statusSubmit, rt.assign]) assert.equal(control.disabled, true);
|
||||
submit(rt, rt.note);
|
||||
assert.equal(rt.fetchCalls.length, 1, 'no write after the result became uncertain');
|
||||
rt.root.fire('click', { target: reload });
|
||||
assert.equal(rt.window.location.reloads, 1);
|
||||
assert.equal(unload(rt).defaultPrevented, false, 'the explicit reload is not blocked');
|
||||
});
|
||||
}
|
||||
|
||||
test('closing requires the confirmation checkbox', async () => {
|
||||
const rt = makeRuntime();
|
||||
rt.statusSelect.value = 'handling';
|
||||
rt.root.fire('change', { target: rt.statusSelect });
|
||||
assert.equal(rt.warning.hidden, true);
|
||||
rt.statusSelect.value = 'closed';
|
||||
rt.root.fire('change', { target: rt.statusSelect });
|
||||
assert.equal(rt.warning.hidden, false);
|
||||
assert.equal(rt.confirm.required, true);
|
||||
submit(rt, rt.status);
|
||||
assert.equal(rt.fetchCalls.length, 0);
|
||||
rt.confirm.checked = true;
|
||||
submit(rt, rt.status);
|
||||
assert.deepEqual(JSON.parse(rt.fetchCalls[0].options.body), { status: 'closed', ticket_type_id: '3', admin_id: '7' });
|
||||
});
|
||||
|
||||
test('“assign to me” selects the current admin, moves pending to handling and focuses save', () => {
|
||||
const rt = makeRuntime();
|
||||
rt.root.fire('click', { target: rt.assign });
|
||||
assert.equal(rt.admin.value, '44');
|
||||
assert.equal(rt.statusSelect.value, 'handling');
|
||||
assert.equal(rt.document.activeElement, rt.statusSubmit);
|
||||
assert.equal(rt.fetchCalls.length, 0, 'assigning only fills the form');
|
||||
});
|
||||
|
||||
test('an overlong prereply is rejected without changing the editor; a fitting one is inserted', () => {
|
||||
const rt = makeRuntime();
|
||||
rt.prereply.value = '01234567890123456789012345';
|
||||
rt.root.fire('change', { target: rt.prereply });
|
||||
assert.equal(rt.replyText.value, '');
|
||||
assert.equal(rt.feedback.querySelector('p').textContent, strings.tooLong);
|
||||
assert.equal(rt.prereply.value, '');
|
||||
rt.prereply.value = 'short';
|
||||
rt.root.fire('change', { target: rt.prereply });
|
||||
assert.equal(rt.replyText.value, 'short');
|
||||
assert.equal(rt.replyCount.textContent, '5 / 24');
|
||||
});
|
||||
|
||||
test('leaving with unsaved input is guarded; a clean page leaves freely', () => {
|
||||
const rt = makeRuntime();
|
||||
assert.equal(unload(rt).defaultPrevented, false);
|
||||
type(rt, rt.replyText, 'draft');
|
||||
assert.equal(unload(rt).defaultPrevented, true);
|
||||
});
|
||||
Reference in new issue
Block a user