Files
wordpress-theme-aksrt/tests/admin/ticket-dialog-runtime.test.cjs
T
kate522andClaude Opus 5 7f1a0dbeb4 fix(admin): remove duplicate ticket dialog subtitle
Keep the ticket number and status in the sidebar only, remove the unused header description payload and bindings, and update dialog regression coverage.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-10-31 11:34:21 +08:00

687 lines
31 KiB
JavaScript

'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);
});
}
});