forked from Shared/esg
Add health check and retry logic and circuit breaker
This commit is contained in:
@@ -0,0 +1,638 @@
|
||||
(function () {
|
||||
'use strict';
|
||||
|
||||
const state = {
|
||||
accessToken: localStorage.getItem('esg.accessToken'),
|
||||
refreshToken: localStorage.getItem('esg.refreshToken'),
|
||||
profile: null,
|
||||
inquirySchema: null,
|
||||
rawMode: false,
|
||||
batchRunning: false,
|
||||
batchStopRequested: false,
|
||||
batchResults: [],
|
||||
};
|
||||
const $ = (id) => document.getElementById(id);
|
||||
|
||||
// These examples intentionally mirror the @ApiProperty examples and DTO validation rules.
|
||||
const INQUIRY_FORMS = {
|
||||
person: {
|
||||
description: 'PersonInquiryRequestDto — examples match Swagger.',
|
||||
fields: [
|
||||
{ key: 'nationalCode', label: 'National code', example: '0012345678', required: true, description: 'Iranian national code (10 digits)', pattern: '\\d{10}' },
|
||||
{ key: 'birthDate', label: 'Birth date', example: '1378-11-24', required: true, description: 'Jalali birth date (YYYY-MM-DD)', pattern: '\\d{4}-\\d{2}-\\d{2}' },
|
||||
{ key: 'dateHasPostfix', label: 'Date postfix flag', example: 0, defaultValue: 0, type: 'number', description: 'Optional civil registration date postfix flag' },
|
||||
],
|
||||
},
|
||||
realEstate: {
|
||||
description: 'RealEstateRequestDto — both values must be 10 digits.',
|
||||
fields: [
|
||||
{ key: 'nationalCode', label: 'National code', example: '5098961130', required: true, description: 'Iranian national code (10 digits)', pattern: '\\d{10}' },
|
||||
{ key: 'postalCode', label: 'Postal code', example: '1349689554', required: true, description: 'Postal code (10 digits)', pattern: '\\d{10}' },
|
||||
],
|
||||
},
|
||||
sheba: {
|
||||
description: 'SayahRequestDto — accountOwnerType is 1 for a natural person.',
|
||||
fields: [
|
||||
{ key: 'accountOwnerType', label: 'Account owner type', example: '1', defaultValue: '1', description: '1 for natural person' },
|
||||
{ key: 'nationalCode', label: 'National code', example: '4311402422', required: true, description: 'Iranian national code (10 digits)', pattern: '\\d{10}' },
|
||||
{ key: 'legalId', label: 'Legal entity ID', example: '', includeEmpty: true, description: 'Use an empty string for natural persons' },
|
||||
{ key: 'sheba', label: 'Sheba', example: 'IR800560611828005105117001', required: true, description: 'Iranian Sheba ID (26 characters)', pattern: 'IR\\d{24}' },
|
||||
],
|
||||
},
|
||||
shahkar: {
|
||||
description: 'ShahkarRequestDto — national code and Iranian mobile number.',
|
||||
fields: [
|
||||
{ key: 'nationalCode', label: 'National code', example: '4311402422', required: true, description: 'Iranian national code (10 digits)', pattern: '\\d{10}' },
|
||||
{ key: 'mobileNo', label: 'Mobile number', example: '09226187419', required: true, description: 'Iranian mobile number', pattern: '09\\d{9}' },
|
||||
],
|
||||
},
|
||||
postalCode: {
|
||||
description: 'PostalCodeRequestDto — exactly 10 digits.',
|
||||
fields: [
|
||||
{ key: 'postalCode', label: 'Postal code', example: '1234567890', required: true, description: 'Postal code (10 digits)', pattern: '\\d{10}' },
|
||||
],
|
||||
},
|
||||
legalPerson: {
|
||||
description: 'This endpoint accepts a provider-specific JSON object; use JSON mode.',
|
||||
rawOnly: true,
|
||||
example: {},
|
||||
},
|
||||
carByPlate: {
|
||||
description: 'CarByPlateRequestDto — plate components are sent separately.',
|
||||
fields: [
|
||||
{ key: 'nationalCode', label: 'National code', example: '4311402422', required: true, description: 'Owner national code (10 digits)', pattern: '\\d{10}' },
|
||||
{ key: 'plk1', label: 'Plate left digits', example: '12', required: true, description: 'Two digits on the left side of the plate', pattern: '\\d{2}' },
|
||||
{ key: 'plk2', label: 'Plate letter', example: 'ب', required: true, description: 'Middle plate letter' },
|
||||
{ key: 'plk3', label: 'Plate right digits', example: '345', required: true, description: 'Three digits on the right side of the plate', pattern: '\\d{3}' },
|
||||
{ key: 'plksrl', label: 'Plate serial', example: '67', required: true, description: 'Plate serial / region code' },
|
||||
],
|
||||
},
|
||||
carByChassis: {
|
||||
description: 'CarByChassisRequestDto — owner national code and VIN/chassis.',
|
||||
fields: [
|
||||
{ key: 'nationalCode', label: 'National code', example: '4311402422', required: true, description: 'Owner national code (10 digits)', pattern: '\\d{10}' },
|
||||
{ key: 'chassisNo', label: 'Chassis / VIN', example: 'IRFC89R2VSY976455', required: true, description: 'Vehicle chassis number or VIN' },
|
||||
],
|
||||
},
|
||||
thirdPartyCar: {
|
||||
description: 'Uses CarByPlateRequestDto for the third-party car route.',
|
||||
fields: [
|
||||
{ key: 'nationalCode', label: 'National code', example: '4311402422', required: true, description: 'Owner national code (10 digits)', pattern: '\\d{10}' },
|
||||
{ key: 'plk1', label: 'Plate left digits', example: '12', required: true, description: 'Two digits on the left side of the plate', pattern: '\\d{2}' },
|
||||
{ key: 'plk2', label: 'Plate letter', example: 'ب', required: true, description: 'Middle plate letter' },
|
||||
{ key: 'plk3', label: 'Plate right digits', example: '345', required: true, description: 'Three digits on the right side of the plate', pattern: '\\d{3}' },
|
||||
{ key: 'plksrl', label: 'Plate serial', example: '67', required: true, description: 'Plate serial / region code' },
|
||||
],
|
||||
},
|
||||
policyByChassis: {
|
||||
description: 'PolicyByChassisRequestDto — vehicle chassis number.',
|
||||
fields: [
|
||||
{ key: 'chassisNo', label: 'Chassis number', example: 'NAAM01E15HK123456', required: true, description: 'Vehicle chassis number' },
|
||||
],
|
||||
},
|
||||
policyByPlate: {
|
||||
description: 'PolicyByPlateRequestDto — plate components and owner national code.',
|
||||
fields: [
|
||||
{ key: 'nationalCode', label: 'National code', example: '4311402422', required: true, description: 'Owner national code (10 digits)', pattern: '\\d{10}' },
|
||||
{ key: 'plk1', label: 'Plate left digits', example: '12', required: true, description: 'Two digits on the left side of the plate', pattern: '\\d{2}' },
|
||||
{ key: 'plk2', label: 'Plate letter', example: 'ب', required: true, description: 'Middle plate letter' },
|
||||
{ key: 'plk3', label: 'Plate right digits', example: '345', required: true, description: 'Three digits on the right side of the plate', pattern: '\\d{3}' },
|
||||
{ key: 'plksrl', label: 'Plate serial', example: '67', required: true, description: 'Plate serial' },
|
||||
],
|
||||
},
|
||||
policyByNationalCode: {
|
||||
description: 'PolicyByNationalCodeRequestDto — exactly 10 digits.',
|
||||
fields: [
|
||||
{ key: 'nationalCode', label: 'National code', example: '4311402422', required: true, description: 'Iranian national code (10 digits)', pattern: '\\d{10}' },
|
||||
],
|
||||
},
|
||||
};
|
||||
|
||||
function showError(message, target) { $(target).textContent = message || ''; }
|
||||
function setSession(tokens) {
|
||||
state.accessToken = tokens.accessToken;
|
||||
state.refreshToken = tokens.refreshToken;
|
||||
localStorage.setItem('esg.accessToken', state.accessToken);
|
||||
localStorage.setItem('esg.refreshToken', state.refreshToken);
|
||||
}
|
||||
function clearSession() {
|
||||
state.accessToken = null; state.refreshToken = null; state.profile = null;
|
||||
localStorage.removeItem('esg.accessToken'); localStorage.removeItem('esg.refreshToken');
|
||||
$('loginView').classList.remove('hidden'); $('appView').classList.add('hidden');
|
||||
}
|
||||
async function request(path, options, retried) {
|
||||
const headers = Object.assign({ Accept: 'application/json' }, (options && options.headers) || {});
|
||||
if (options && options.body && !headers['Content-Type']) headers['Content-Type'] = 'application/json';
|
||||
if (state.accessToken) headers.Authorization = 'Bearer ' + state.accessToken;
|
||||
const response = await fetch(path, Object.assign({}, options || {}, { headers }));
|
||||
const text = await response.text();
|
||||
let body; try { body = text ? JSON.parse(text) : null; } catch (_) { body = text; }
|
||||
if (response.status === 401 && state.refreshToken && !retried) {
|
||||
const refreshed = await fetch('/auth/refresh', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ refreshToken: state.refreshToken }) });
|
||||
if (refreshed.ok) { setSession(await refreshed.json()); return request(path, options, true); }
|
||||
clearSession();
|
||||
}
|
||||
if (!response.ok) {
|
||||
const error = new Error(body && body.error && body.error.message ? body.error.message : (body && body.message) || ('Request failed (' + response.status + ')'));
|
||||
error.body = body;
|
||||
error.status = response.status;
|
||||
throw error;
|
||||
}
|
||||
return body;
|
||||
}
|
||||
function pretty(value) {
|
||||
if (typeof value !== 'string') {
|
||||
return JSON.stringify(value, (_, item) => (isXml(item) ? formatXml(item) : item), 2);
|
||||
}
|
||||
const trimmed = value.trim();
|
||||
if (!trimmed.startsWith('<')) { try { return JSON.stringify(JSON.parse(trimmed), null, 2); } catch (_) { return value; } }
|
||||
return formatXml(trimmed);
|
||||
}
|
||||
function isXml(value) {
|
||||
return typeof value === 'string' && /^\s*(?:<\?xml\b|<!--[\s\S]*?-->|<[A-Za-z_][\w:.-]*(?:\s[^>]*)?>)/.test(value);
|
||||
}
|
||||
function formatXml(value) {
|
||||
const trimmed = String(value).trim();
|
||||
if (!isXml(trimmed)) return trimmed;
|
||||
const tokens = trimmed
|
||||
.replace(/>\s*</g, '><')
|
||||
.replace(/</g, '\n<')
|
||||
.split('\n')
|
||||
.map((token) => token.trim())
|
||||
.filter(Boolean);
|
||||
let depth = 0;
|
||||
return tokens.map((token) => {
|
||||
const closing = /^<\//.test(token);
|
||||
const selfClosing = /\/\s*>$/.test(token) || /^<\?/.test(token) || /^<!/.test(token);
|
||||
if (closing) depth = Math.max(0, depth - 1);
|
||||
const line = ' '.repeat(depth) + token;
|
||||
if (!closing && !selfClosing && /^<[^>]+>$/.test(token)) depth += 1;
|
||||
return line;
|
||||
}).join('\n');
|
||||
}
|
||||
function xmlToJson(value) {
|
||||
const documentNode = new DOMParser().parseFromString(String(value), 'application/xml');
|
||||
if (documentNode.querySelector('parsererror')) throw new Error('XML could not be parsed.');
|
||||
const convert = (node) => {
|
||||
const attributes = {};
|
||||
for (const attribute of Array.from(node.attributes || [])) attributes[attribute.name] = attribute.value;
|
||||
const children = Array.from(node.childNodes || []).filter((child) => child.nodeType === 1);
|
||||
const text = Array.from(node.childNodes || [])
|
||||
.filter((child) => child.nodeType === 3 || child.nodeType === 4)
|
||||
.map((child) => child.nodeValue || '')
|
||||
.join('')
|
||||
.trim();
|
||||
if (!children.length) {
|
||||
if (!Object.keys(attributes).length) return text;
|
||||
return { '@attributes': attributes, ...(text ? { '#text': text } : {}) };
|
||||
}
|
||||
const result = {};
|
||||
if (Object.keys(attributes).length) result['@attributes'] = attributes;
|
||||
for (const child of children) {
|
||||
const key = child.nodeName;
|
||||
const childValue = convert(child);
|
||||
if (result[key] === undefined) result[key] = childValue;
|
||||
else result[key] = Array.isArray(result[key]) ? [...result[key], childValue] : [result[key], childValue];
|
||||
}
|
||||
if (text) result['#text'] = text;
|
||||
return result;
|
||||
};
|
||||
return { [documentNode.documentElement.nodeName]: convert(documentNode.documentElement) };
|
||||
}
|
||||
function createXmlViewer(label, value) {
|
||||
const section = document.createElement('section'); section.className = 'xml-viewer';
|
||||
const toolbar = document.createElement('div'); toolbar.className = 'xml-toolbar';
|
||||
const title = document.createElement('span'); title.className = 'detail-label'; title.textContent = label;
|
||||
const actions = document.createElement('div'); actions.className = 'xml-actions';
|
||||
const toggle = document.createElement('button'); toggle.type = 'button'; toggle.className = 'ghost';
|
||||
const jsonToggle = document.createElement('button'); jsonToggle.type = 'button'; jsonToggle.className = 'ghost';
|
||||
const output = document.createElement('pre'); output.className = 'xml-output';
|
||||
const searchRow = document.createElement('div'); searchRow.className = 'xml-search';
|
||||
const searchInput = document.createElement('input'); searchInput.type = 'search'; searchInput.placeholder = 'Search this XML…'; searchInput.setAttribute('aria-label', `Search ${label}`);
|
||||
const previous = document.createElement('button'); previous.type = 'button'; previous.className = 'ghost'; previous.textContent = '↑'; previous.title = 'Previous match';
|
||||
const next = document.createElement('button'); next.type = 'button'; next.className = 'ghost'; next.textContent = '↓'; next.title = 'Next match';
|
||||
const matchCount = document.createElement('span'); matchCount.className = 'xml-match-count'; matchCount.textContent = 'No search';
|
||||
let mode = 'formatted';
|
||||
let currentText = '';
|
||||
let activeMatch = 0;
|
||||
const escapeHtml = (text) => text.replace(/[&<>"']/g, (character) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[character]));
|
||||
const escapeRegex = (text) => text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
||||
const renderSearch = () => {
|
||||
const query = searchInput.value.trim();
|
||||
if (!query) { output.textContent = currentText; matchCount.textContent = 'No search'; return; }
|
||||
const expression = new RegExp(escapeRegex(query), 'gi');
|
||||
let count = 0;
|
||||
output.innerHTML = escapeHtml(currentText).replace(expression, (match) => `<mark data-match="${count++}">${match}</mark>`);
|
||||
const matches = Array.from(output.querySelectorAll('mark'));
|
||||
if (!matches.length) { matchCount.textContent = '0 matches'; return; }
|
||||
activeMatch = Math.min(activeMatch, matches.length - 1);
|
||||
matches[activeMatch].classList.add('active-match'); matches[activeMatch].scrollIntoView({ block: 'center' });
|
||||
matchCount.textContent = `${activeMatch + 1} / ${matches.length}`;
|
||||
};
|
||||
const moveMatch = (direction) => {
|
||||
const matches = output.querySelectorAll('mark');
|
||||
if (!matches.length) return;
|
||||
activeMatch = (activeMatch + direction + matches.length) % matches.length;
|
||||
renderSearch();
|
||||
};
|
||||
const render = () => {
|
||||
if (mode === 'json') {
|
||||
try { currentText = JSON.stringify(xmlToJson(value), null, 2); }
|
||||
catch (error) { currentText = `Unable to transform XML to JSON: ${error.message}`; }
|
||||
} else currentText = mode === 'formatted' ? formatXml(value) : String(value);
|
||||
toggle.textContent = mode === 'raw' ? 'Format XML' : 'Show raw XML';
|
||||
jsonToggle.textContent = mode === 'json' ? 'Show XML' : 'Transform to JSON';
|
||||
renderSearch();
|
||||
};
|
||||
toggle.addEventListener('click', (event) => { event.stopPropagation(); mode = mode === 'raw' ? 'formatted' : 'raw'; render(); });
|
||||
jsonToggle.addEventListener('click', (event) => { event.stopPropagation(); mode = mode === 'json' ? 'formatted' : 'json'; render(); });
|
||||
searchInput.addEventListener('input', () => { activeMatch = 0; renderSearch(); });
|
||||
previous.addEventListener('click', (event) => { event.stopPropagation(); moveMatch(-1); });
|
||||
next.addEventListener('click', (event) => { event.stopPropagation(); moveMatch(1); });
|
||||
searchRow.append(searchInput, previous, next, matchCount);
|
||||
actions.append(toggle, jsonToggle); toolbar.append(title, actions); section.append(toolbar, searchRow, output); render();
|
||||
return section;
|
||||
}
|
||||
function newKey() { return 'ui-' + Date.now() + '-' + Math.random().toString(36).slice(2, 9); }
|
||||
function fieldsToPayload() {
|
||||
const payload = {};
|
||||
(state.inquirySchema.fields || []).forEach((field) => {
|
||||
const input = $('inquiryFields').querySelector('[data-field="' + field.key + '"]');
|
||||
if (!input) return;
|
||||
const value = input.value;
|
||||
if (value === '' && !field.includeEmpty) return;
|
||||
payload[field.key] = field.type === 'number' && value !== '' ? Number(value) : value;
|
||||
});
|
||||
return payload;
|
||||
}
|
||||
function syncFieldsToJson() {
|
||||
if (!state.inquirySchema || state.inquirySchema.rawOnly || state.rawMode) return;
|
||||
$('inquiryPayload').value = JSON.stringify(fieldsToPayload(), null, 2);
|
||||
}
|
||||
function applyJsonToFields() {
|
||||
if (!state.inquirySchema || state.inquirySchema.rawOnly) return true;
|
||||
let payload;
|
||||
try { payload = JSON.parse($('inquiryPayload').value || '{}'); } catch (_) { showError('JSON payload is not valid.', 'appError'); return false; }
|
||||
if (!payload || Array.isArray(payload) || typeof payload !== 'object') { showError('JSON payload must be an object.', 'appError'); return false; }
|
||||
(state.inquirySchema.fields || []).forEach((field) => {
|
||||
const input = $('inquiryFields').querySelector('[data-field="' + field.key + '"]');
|
||||
if (input) input.value = payload[field.key] == null ? '' : String(payload[field.key]);
|
||||
});
|
||||
return true;
|
||||
}
|
||||
function setRawMode(enabled) {
|
||||
if (!state.inquirySchema || state.inquirySchema.rawOnly) return;
|
||||
if (enabled) {
|
||||
syncFieldsToJson();
|
||||
state.rawMode = true;
|
||||
$('inquiryFields').querySelectorAll('input').forEach((input) => { input.disabled = true; });
|
||||
$('fieldMode').classList.add('hidden'); $('rawMode').classList.remove('hidden');
|
||||
$('toggleRawButton').textContent = 'Use form fields';
|
||||
return;
|
||||
}
|
||||
if (!applyJsonToFields()) return;
|
||||
state.rawMode = false;
|
||||
$('inquiryFields').querySelectorAll('input').forEach((input) => { input.disabled = false; });
|
||||
$('fieldMode').classList.remove('hidden'); $('rawMode').classList.add('hidden');
|
||||
$('toggleRawButton').textContent = 'Use JSON mode';
|
||||
syncFieldsToJson();
|
||||
}
|
||||
function renderInquiryForm() {
|
||||
const schema = INQUIRY_FORMS[$('inquiryType').value];
|
||||
state.inquirySchema = schema;
|
||||
state.rawMode = Boolean(schema.rawOnly);
|
||||
$('inquiryHint').textContent = schema.description;
|
||||
$('inquiryFields').replaceChildren();
|
||||
$('inquiryPayload').value = JSON.stringify(schema.example || {}, null, 2);
|
||||
$('toggleRawButton').disabled = Boolean(schema.rawOnly);
|
||||
$('applyJsonButton').classList.toggle('hidden', Boolean(schema.rawOnly));
|
||||
if (schema.rawOnly) {
|
||||
$('fieldMode').classList.add('hidden'); $('rawMode').classList.remove('hidden');
|
||||
return;
|
||||
}
|
||||
(schema.fields || []).forEach((field) => {
|
||||
const label = document.createElement('label');
|
||||
label.append(document.createTextNode(field.label + (field.required ? ' *' : '')));
|
||||
const input = document.createElement('input');
|
||||
input.type = field.type || 'text';
|
||||
input.dataset.field = field.key;
|
||||
input.value = field.defaultValue == null ? String(field.example ?? '') : String(field.defaultValue);
|
||||
input.placeholder = String(field.example ?? '');
|
||||
input.required = Boolean(field.required);
|
||||
if (field.pattern) input.pattern = field.pattern;
|
||||
input.addEventListener('input', syncFieldsToJson);
|
||||
const hint = document.createElement('small');
|
||||
hint.className = 'field-hint';
|
||||
hint.textContent = field.description + (field.example !== undefined ? ' Example: ' + field.example : '');
|
||||
label.append(input, hint);
|
||||
$('inquiryFields').append(label);
|
||||
});
|
||||
$('fieldMode').classList.remove('hidden'); $('rawMode').classList.add('hidden');
|
||||
$('toggleRawButton').textContent = 'Use JSON mode';
|
||||
syncFieldsToJson();
|
||||
}
|
||||
async function loadHealth() {
|
||||
try {
|
||||
const result = await request('/health/ready');
|
||||
const ok = result.status === 'ok';
|
||||
const dot = $('healthStatus').querySelector('.status-dot');
|
||||
dot.className = 'status-dot ' + (ok ? 'ok' : 'error');
|
||||
$('healthStatus').querySelector('span:last-child').textContent = ok ? 'Ready' : 'Degraded';
|
||||
$('healthOutput').textContent = pretty(result);
|
||||
} catch (error) {
|
||||
const dot = $('healthStatus').querySelector('.status-dot');
|
||||
dot.className = 'status-dot error';
|
||||
$('healthStatus').querySelector('span:last-child').textContent = 'Unavailable';
|
||||
$('healthOutput').textContent = pretty(error.body || error.message);
|
||||
}
|
||||
}
|
||||
async function loadMetrics() {
|
||||
const summary = await request('/inquiry-logs/summary');
|
||||
$('metricTotal').textContent = summary.total ?? '—'; $('metricEvaluated').textContent = summary.evaluated ?? '—'; $('metricSuccess').textContent = summary.successRate == null ? '—' : (Number(summary.successRate) * 100).toFixed(1) + '%'; $('metricFailure').textContent = summary.failure ?? '—'; $('metricNoMatch').textContent = summary.noMatch ?? '—'; $('metricDuration').textContent = summary.averageDuration == null ? '—' : Math.round(summary.averageDuration) + ' ms';
|
||||
}
|
||||
async function loadLogs() {
|
||||
const result = await request('/inquiry-logs?limit=40&page=1'); const body = $('logsBody'); body.replaceChildren();
|
||||
(result.data || []).forEach((log) => {
|
||||
const row = document.createElement('tr');
|
||||
row.className = 'data-row'; row.tabIndex = 0; row.setAttribute('aria-expanded', 'false');
|
||||
[log.createdAt ? new Date(log.createdAt).toLocaleString() : '—', log.inquiryType, log.provider, log.status, log.duration + ' ms', log.trackingCode].forEach((value, index) => {
|
||||
const cell = document.createElement('td');
|
||||
if (index === 0) { const toggle = document.createElement('span'); toggle.className = 'row-toggle'; toggle.textContent = '▶'; toggle.setAttribute('aria-hidden', 'true'); cell.append(toggle); }
|
||||
cell.append(document.createTextNode(value));
|
||||
if (index === 3) cell.className = log.status === 'SUCCESS' ? 'status-success' : (log.status === 'NO_MATCH' ? 'status-neutral' : 'status-failure');
|
||||
row.appendChild(cell);
|
||||
});
|
||||
const detailRow = createDetailRow(6, log);
|
||||
bindDetailToggle(row, detailRow);
|
||||
body.append(row, detailRow);
|
||||
});
|
||||
}
|
||||
function createDetailRow(colspan, value) {
|
||||
const detailRow = document.createElement('tr'); detailRow.className = 'detail-row hidden';
|
||||
const cell = document.createElement('td'); cell.colSpan = colspan;
|
||||
const panel = document.createElement('div'); panel.className = 'detail-panel';
|
||||
detailRow.renderValue = (nextValue) => renderDetailPanel(panel, nextValue);
|
||||
renderDetailPanel(panel, value);
|
||||
cell.appendChild(panel); detailRow.appendChild(cell);
|
||||
return detailRow;
|
||||
}
|
||||
function renderDetailPanel(panel, value) {
|
||||
panel.replaceChildren();
|
||||
const outboundRequests = Array.isArray(value?.outboundRequests) ? value.outboundRequests : [];
|
||||
if (outboundRequests.length) {
|
||||
const heading = document.createElement('p'); heading.className = 'detail-heading';
|
||||
heading.textContent = `Outbound calls (${outboundRequests.length})`;
|
||||
panel.appendChild(heading);
|
||||
outboundRequests.forEach((trace, index) => {
|
||||
const call = document.createElement('section'); call.className = 'outbound-call';
|
||||
const title = document.createElement('div'); title.className = 'outbound-call-title';
|
||||
title.textContent = `${index + 1}. ${(trace.method || 'GET').toUpperCase()} ${trace.url || '—'}${trace.status ? ` · HTTP ${trace.status}` : trace.error ? ` · ${trace.error}` : ''}`;
|
||||
call.appendChild(title);
|
||||
const curlLabel = document.createElement('span'); curlLabel.className = 'detail-label'; curlLabel.textContent = 'Safe cURL (credentials redacted)';
|
||||
call.appendChild(curlLabel);
|
||||
const curlRow = document.createElement('div'); curlRow.className = 'curl-row';
|
||||
const curl = document.createElement('textarea'); curl.readOnly = true; curl.rows = 4; curl.value = trace.curl || `curl --request ${(trace.method || 'GET').toUpperCase()} '${trace.url || ''}'`;
|
||||
const copy = document.createElement('button'); copy.type = 'button'; copy.className = 'ghost copy-curl'; copy.textContent = 'Copy cURL';
|
||||
copy.addEventListener('click', async (event) => {
|
||||
event.stopPropagation();
|
||||
try { await navigator.clipboard.writeText(curl.value); copy.textContent = 'Copied'; } catch (_) {
|
||||
curl.focus(); curl.select(); document.execCommand('copy'); copy.textContent = 'Copied';
|
||||
}
|
||||
window.setTimeout(() => { copy.textContent = 'Copy cURL'; }, 1400);
|
||||
});
|
||||
curlRow.append(curl, copy); call.appendChild(curlRow);
|
||||
if (isXml(trace.requestBody)) call.appendChild(createXmlViewer('Request XML', trace.requestBody));
|
||||
if (trace.responseBody !== undefined || trace.error) {
|
||||
if (isXml(trace.responseBody)) call.appendChild(createXmlViewer('Response XML', trace.responseBody));
|
||||
else {
|
||||
const response = document.createElement('pre'); response.className = 'outbound-response';
|
||||
response.textContent = trace.error ? `${trace.error}\n\n${pretty(trace.responseBody)}` : pretty(trace.responseBody);
|
||||
call.appendChild(response);
|
||||
}
|
||||
}
|
||||
panel.appendChild(call);
|
||||
});
|
||||
}
|
||||
const fullDetails = document.createElement('details'); fullDetails.className = 'full-detail';
|
||||
const summary = document.createElement('summary'); summary.textContent = 'Show complete masked gateway record';
|
||||
const output = document.createElement('pre'); output.textContent = pretty(value);
|
||||
fullDetails.append(summary, output); panel.appendChild(fullDetails);
|
||||
}
|
||||
function bindDetailToggle(row, detailRow, onExpand) {
|
||||
let loaded = false;
|
||||
const toggle = () => {
|
||||
const expanded = row.getAttribute('aria-expanded') === 'true';
|
||||
row.setAttribute('aria-expanded', String(!expanded)); detailRow.classList.toggle('hidden', expanded);
|
||||
if (!expanded && !loaded && onExpand) { loaded = true; onExpand(); }
|
||||
};
|
||||
row.addEventListener('click', toggle);
|
||||
row.addEventListener('keydown', (event) => { if (event.key === 'Enter' || event.key === ' ') { event.preventDefault(); toggle(); } });
|
||||
}
|
||||
function firstValue(source, keys) {
|
||||
for (const key of keys) {
|
||||
if (source && source[key] !== undefined && source[key] !== null && source[key] !== '') return source[key];
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
function normalizeBatchRecord(value, index) {
|
||||
const raw = value && typeof value === 'object' ? value : {};
|
||||
const source = (raw.request && typeof raw.request === 'object' ? raw.request : raw.payload && typeof raw.payload === 'object' ? raw.payload : raw);
|
||||
const plateObject = source.plate && typeof source.plate === 'object' ? source.plate : {};
|
||||
const directPlate = firstValue(source, ['plate', 'Plate', 'licensePlate', 'license_plate']);
|
||||
const plateText = directPlate && typeof directPlate === 'object' ? firstValue(plateObject, ['value', 'number']) : (directPlate ?? firstValue(plateObject, ['value', 'number']));
|
||||
let plk1 = firstValue(source, ['plk1', 'Plk1', 'plk01', 'platePart1', 'plate1', 'plaque_2', 'پلاک1']);
|
||||
let plk2 = firstValue(source, ['plk2', 'Plk2', 'plateLetter', 'plate_letter', 'plate2', 'letter', 'پلاک2']);
|
||||
let plk3 = firstValue(source, ['plk3', 'Plk3', 'platePart3', 'plate3', 'plaque_3', 'پلاک3']);
|
||||
let plksrl = firstValue(source, ['plksrl', 'PlkSrl', 'plkSrl', 'plateSerial', 'plate_serial', 'plate4', 'iran', 'پلاک4']);
|
||||
if (typeof plateText === 'string') {
|
||||
const compactPlate = plateText.replace(/[\s\-_/|]/g, '');
|
||||
const plateMatch = compactPlate.match(/^(\d{2})([^\d])(\d{3})(\d{2})$/u);
|
||||
if (plateMatch) {
|
||||
plk1 = plk1 ?? plateMatch[1]; plk2 = plk2 ?? plateMatch[2]; plk3 = plk3 ?? plateMatch[3]; plksrl = plksrl ?? plateMatch[4];
|
||||
}
|
||||
}
|
||||
const payload = {
|
||||
nationalCode: String(firstValue(source, ['nationalCode', 'NationalCode', 'national_code', 'nationalId', 'NationalId', 'NIN', 'nin', 'کدملی', 'کد ملی']) ?? '').trim(),
|
||||
plk1: String(plk1 ?? firstValue(plateObject, ['plk1', 'Plk1', 'part1']) ?? '').trim(),
|
||||
plk2: String(plk2 ?? firstValue(plateObject, ['plk2', 'Plk2', 'letter']) ?? '').trim(),
|
||||
plk3: String(plk3 ?? firstValue(plateObject, ['plk3', 'Plk3', 'part3']) ?? '').trim(),
|
||||
plksrl: String(plksrl ?? firstValue(plateObject, ['plksrl', 'PlkSrl', 'serial']) ?? '').trim(),
|
||||
};
|
||||
const missing = Object.entries(payload).filter(([, item]) => !item).map(([key]) => key);
|
||||
return {
|
||||
index: index + 1,
|
||||
raw,
|
||||
payload,
|
||||
parseError: missing.length > 0 ? `Missing field(s): ${missing.join(', ')}` : undefined,
|
||||
};
|
||||
}
|
||||
function parseBatchInput(text) {
|
||||
let parsed;
|
||||
try {
|
||||
parsed = JSON.parse(text);
|
||||
} catch (_) {
|
||||
const lines = text.split(/\r?\n/).map((line) => line.trim()).filter(Boolean);
|
||||
if (!lines.length) throw new Error('Batch input is empty.');
|
||||
try { parsed = lines.map((line) => JSON.parse(line)); } catch (_) { throw new Error('Batch input is not valid JSON.'); }
|
||||
}
|
||||
const records = Array.isArray(parsed) ? parsed : Array.isArray(parsed?.records) ? parsed.records : Array.isArray(parsed?.items) ? parsed.items : Array.isArray(parsed?.data) ? parsed.data : [parsed];
|
||||
if (!records.length) throw new Error('Batch input contains no records.');
|
||||
return records.map(normalizeBatchRecord);
|
||||
}
|
||||
function selectedBatchEndpoints() {
|
||||
return Array.from(document.querySelectorAll('input[name="batchEndpoint"]:checked')).map((input) => input.value);
|
||||
}
|
||||
function addBatchResult(result) {
|
||||
state.batchResults.push(result);
|
||||
const row = document.createElement('tr');
|
||||
row.className = 'data-row'; row.tabIndex = 0; row.setAttribute('aria-expanded', 'false');
|
||||
const inputLabel = result.payload ? `${result.payload.nationalCode} / ${result.payload.plk1}${result.payload.plk2}${result.payload.plk3}${result.payload.plksrl}` : '—';
|
||||
const values = [result.index, inputLabel, result.endpoint || '—', result.status, result.trackingCode || '—', result.message || '—'];
|
||||
values.forEach((value, index) => {
|
||||
const cell = document.createElement('td');
|
||||
if (index === 0) { const toggle = document.createElement('span'); toggle.className = 'row-toggle'; toggle.textContent = '▶'; toggle.setAttribute('aria-hidden', 'true'); cell.append(toggle); }
|
||||
cell.append(document.createTextNode(value));
|
||||
if (index === 3) { const noMatch = ['NO_MATCH', 'INQUIRY_NO_MATCH', 'CAR_POLICY_NOT_FOUND', 'RECORD_NOT_FOUND', 'REAL_ESTATE_NOT_FOUND', 'SHAHKAR_NO_MATCH', 'SHEBA_MISMATCH'].includes(result.status); cell.className = result.status === 'SUCCESS' ? 'status-success' : (noMatch ? 'status-neutral' : 'status-failure'); }
|
||||
row.appendChild(cell);
|
||||
});
|
||||
const detailRow = createDetailRow(6, result);
|
||||
bindDetailToggle(row, detailRow, () => {
|
||||
if (!result.trackingCode) return;
|
||||
request(`/inquiry-logs?trackingCode=${encodeURIComponent(result.trackingCode)}&limit=1&page=1`)
|
||||
.then((logResult) => {
|
||||
const log = logResult && logResult.data && logResult.data[0];
|
||||
if (log && typeof detailRow.renderValue === 'function') {
|
||||
detailRow.renderValue({ ...result, outboundRequests: log.outboundRequests, gatewayLog: log });
|
||||
}
|
||||
})
|
||||
.catch(() => undefined);
|
||||
});
|
||||
$('batchResultsBody').append(row, detailRow);
|
||||
}
|
||||
function updateBatchSummary(completed, total) {
|
||||
$('batchProgress').value = total ? completed / total : 0;
|
||||
const success = state.batchResults.filter((item) => item.status === 'SUCCESS').length; const noMatch = state.batchResults.filter((item) => ['NO_MATCH', 'INQUIRY_NO_MATCH', 'CAR_POLICY_NOT_FOUND', 'RECORD_NOT_FOUND', 'REAL_ESTATE_NOT_FOUND', 'SHAHKAR_NO_MATCH', 'SHEBA_MISMATCH'].includes(item.status)).length; const operational = completed - success - noMatch; $('batchSummary').textContent = `${completed} / ${total} completed · ${success} success · ${noMatch} no-match · ${operational} operational failure${operational === 1 ? '' : 's'}`;
|
||||
}
|
||||
function wait(milliseconds) {
|
||||
return milliseconds > 0 ? new Promise((resolve) => setTimeout(resolve, milliseconds)) : Promise.resolve();
|
||||
}
|
||||
async function runBatchTest() {
|
||||
if (state.batchRunning) return;
|
||||
const endpoints = selectedBatchEndpoints();
|
||||
if (!endpoints.length) { showError('Select at least one plate endpoint.', 'appError'); return; }
|
||||
let records;
|
||||
try { records = parseBatchInput($('batchPayload').value.trim()); } catch (error) { showError(error.message, 'appError'); return; }
|
||||
const delay = Math.min(10000, Math.max(0, Number($('batchDelay').value) || 0));
|
||||
const total = records.length * endpoints.length;
|
||||
if (total > 50 && !window.confirm(`Run ${total} requests (${records.length} record(s) × ${endpoints.length} endpoint(s))?`)) return;
|
||||
let completed = 0;
|
||||
state.batchRunning = true; state.batchStopRequested = false; state.batchResults = [];
|
||||
$('batchResultsBody').replaceChildren(); $('batchOutput').textContent = 'Running batch… click any completed row to inspect its response.'; $('batchProgress').classList.remove('hidden'); $('runBatchButton').disabled = true; $('stopBatchButton').classList.remove('hidden');
|
||||
updateBatchSummary(0, total);
|
||||
try {
|
||||
for (const record of records) {
|
||||
for (const endpoint of endpoints) {
|
||||
if (state.batchStopRequested) break;
|
||||
let result;
|
||||
if (record.parseError) {
|
||||
result = { index: record.index, payload: record.payload, endpoint, status: 'INVALID_INPUT', message: record.parseError };
|
||||
} else {
|
||||
try {
|
||||
const body = await request('/inquiry/' + endpoint, { method: 'POST', headers: { 'Idempotency-Key': `batch-${Date.now()}-${record.index}-${endpoint}` }, body: JSON.stringify(record.payload) });
|
||||
result = { index: record.index, payload: record.payload, endpoint, status: body.success ? 'SUCCESS' : (body.error?.code || 'NO_MATCH'), trackingCode: body.trackingCode, message: body.success ? (body.message || 'Completed') : (body.error?.messageFa || body.error?.message || 'Inquiry returned no result'), response: body };
|
||||
} catch (error) {
|
||||
result = { index: record.index, payload: record.payload, endpoint, status: 'REQUEST_ERROR', message: error.message, response: error.body };
|
||||
}
|
||||
}
|
||||
addBatchResult(result); completed += 1; updateBatchSummary(completed, total); await wait(delay);
|
||||
}
|
||||
if (state.batchStopRequested) break;
|
||||
}
|
||||
$('batchOutput').textContent = 'Batch finished. Click any row to inspect its full request and response.';
|
||||
if (state.batchStopRequested) $('batchSummary').textContent += ' · stopped by user';
|
||||
await Promise.allSettled([loadMetrics(), loadLogs()]);
|
||||
} finally {
|
||||
state.batchRunning = false; state.batchStopRequested = false; $('runBatchButton').disabled = false; $('stopBatchButton').disabled = false; $('stopBatchButton').classList.add('hidden');
|
||||
}
|
||||
}
|
||||
async function clearInquiryLogs() {
|
||||
if (!window.confirm('Delete every inquiry log from MongoDB? This cannot be undone.')) return;
|
||||
try {
|
||||
const result = await request('/inquiry-logs', { method: 'DELETE' });
|
||||
$('logsBody').replaceChildren(); $('logOutput').textContent = 'Inquiry logs were cleared.';
|
||||
showError(`Deleted ${result.deletedCount || 0} inquiry log(s).`, 'appError');
|
||||
await loadMetrics();
|
||||
} catch (error) { showError(error.message, 'appError'); }
|
||||
}
|
||||
async function loadDashboard() {
|
||||
showError('', 'appError');
|
||||
const results = await Promise.allSettled([loadHealth(), loadMetrics(), loadLogs()]);
|
||||
const failed = results.find((result) => result.status === 'rejected');
|
||||
if (failed) showError(failed.reason && failed.reason.message ? failed.reason.message : 'Some dashboard data could not be loaded.', 'appError');
|
||||
}
|
||||
function setupCollapsiblePanels() {
|
||||
document.querySelectorAll('#appView .panel').forEach((panel, index) => {
|
||||
const heading = panel.querySelector(':scope > .panel-heading');
|
||||
if (!heading || heading.dataset.collapsibleReady) return;
|
||||
heading.dataset.collapsibleReady = 'true';
|
||||
const title = heading.querySelector('h2')?.textContent?.trim() || `Panel ${index + 1}`;
|
||||
const key = `esg.dashboard.panel.${title.toLowerCase().replace(/[^a-z0-9]+/g, '-')}`;
|
||||
const content = document.createElement('div'); content.className = 'panel-content';
|
||||
let node = heading.nextSibling;
|
||||
while (node) { const next = node.nextSibling; content.appendChild(node); node = next; }
|
||||
panel.appendChild(content);
|
||||
const collapse = document.createElement('button');
|
||||
collapse.type = 'button'; collapse.className = 'icon-button panel-collapse'; collapse.title = `Collapse ${title}`;
|
||||
collapse.setAttribute('aria-label', `Collapse ${title}`);
|
||||
const applyState = (collapsed, persist) => {
|
||||
panel.classList.toggle('panel-collapsed', collapsed); content.hidden = collapsed;
|
||||
collapse.textContent = collapsed ? '+' : '−';
|
||||
collapse.title = `${collapsed ? 'Expand' : 'Collapse'} ${title}`;
|
||||
collapse.setAttribute('aria-label', `${collapsed ? 'Expand' : 'Collapse'} ${title}`);
|
||||
collapse.setAttribute('aria-expanded', String(!collapsed));
|
||||
if (persist) { try { localStorage.setItem(key, collapsed ? 'collapsed' : 'open'); } catch (_) {} }
|
||||
};
|
||||
collapse.addEventListener('click', (event) => { event.stopPropagation(); applyState(!panel.classList.contains('panel-collapsed'), true); });
|
||||
heading.appendChild(collapse);
|
||||
let collapsed = false;
|
||||
try { collapsed = localStorage.getItem(key) === 'collapsed'; } catch (_) {}
|
||||
applyState(collapsed, false);
|
||||
});
|
||||
}
|
||||
async function login(event) {
|
||||
event.preventDefault(); showError('', 'loginError');
|
||||
try { const tokens = await request('/auth/login', { method: 'POST', body: JSON.stringify({ username: $('username').value, password: $('password').value }) }, true); setSession(tokens); const profile = await request('/auth/profile'); if (!profile || profile.role !== 'SUPER_ADMIN') throw new Error('This console is restricted to SUPER_ADMIN.'); state.profile = profile; $('profileLabel').textContent = profile.username + ' · SUPER_ADMIN'; $('loginView').classList.add('hidden'); $('appView').classList.remove('hidden'); $('idempotencyKey').value = newKey(); await loadDashboard(); }
|
||||
catch (error) { clearSession(); showError(error.message, 'loginError'); }
|
||||
}
|
||||
async function submitInquiry(event) {
|
||||
event.preventDefault(); showError('', 'appError');
|
||||
try {
|
||||
const payload = state.rawMode ? JSON.parse($('inquiryPayload').value || '{}') : fieldsToPayload();
|
||||
const result = await request('/inquiry/' + $('inquiryType').value, { method: 'POST', headers: { 'Idempotency-Key': $('idempotencyKey').value || newKey() }, body: JSON.stringify(payload) });
|
||||
$('inquiryOutput').textContent = pretty(result); $('idempotencyKey').value = newKey();
|
||||
await Promise.allSettled([loadMetrics(), loadLogs()]);
|
||||
} catch (error) { $('inquiryOutput').textContent = error.message; showError(error.message, 'appError'); }
|
||||
}
|
||||
$('loginForm').addEventListener('submit', login);
|
||||
$('inquiryForm').addEventListener('submit', submitInquiry);
|
||||
$('inquiryType').addEventListener('change', renderInquiryForm);
|
||||
$('toggleRawButton').addEventListener('click', () => setRawMode(!state.rawMode));
|
||||
$('applyJsonButton').addEventListener('click', () => { if (applyJsonToFields()) setRawMode(false); });
|
||||
$('logoutButton').addEventListener('click', async () => { try { await request('/auth/logout', { method: 'POST' }); } catch (_) {} clearSession(); });
|
||||
$('refreshHealth').addEventListener('click', loadHealth);
|
||||
$('refreshMetrics').addEventListener('click', () => loadMetrics().catch((error) => showError(error.message, 'appError')));
|
||||
$('refreshLogs').addEventListener('click', () => loadLogs().catch((error) => showError(error.message, 'appError')));
|
||||
$('clearLogsButton').addEventListener('click', clearInquiryLogs);
|
||||
$('batchFile').addEventListener('change', async (event) => {
|
||||
const file = event.target.files && event.target.files[0];
|
||||
if (!file) return;
|
||||
try { $('batchPayload').value = await file.text(); $('batchOutput').textContent = `Loaded ${file.name}. Click Run batch test to begin.`; } catch (_) { showError('Unable to read the selected batch file.', 'appError'); }
|
||||
});
|
||||
$('runBatchButton').addEventListener('click', runBatchTest);
|
||||
$('stopBatchButton').addEventListener('click', () => { state.batchStopRequested = true; $('stopBatchButton').disabled = true; });
|
||||
setupCollapsiblePanels();
|
||||
$('idempotencyKey').value = newKey();
|
||||
renderInquiryForm();
|
||||
if (state.accessToken) { request('/auth/profile').then((profile) => { if (profile.role !== 'SUPER_ADMIN') throw new Error('SUPER_ADMIN required'); state.profile = profile; $('profileLabel').textContent = profile.username + ' · SUPER_ADMIN'; $('loginView').classList.add('hidden'); $('appView').classList.remove('hidden'); return loadDashboard(); }).catch(clearSession); }
|
||||
setInterval(() => { if (!document.getElementById('appView').classList.contains('hidden')) loadHealth().catch(() => undefined); }, 30000);
|
||||
})();
|
||||
@@ -0,0 +1,132 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||
<meta name="color-scheme" content="dark light" />
|
||||
<title>Inquiry Gateway Console</title>
|
||||
<link rel="stylesheet" href="/dashboard/styles.css" />
|
||||
<script defer src="/dashboard/app.js"></script>
|
||||
</head>
|
||||
<body>
|
||||
<main class="shell">
|
||||
<section id="loginView" class="auth-card">
|
||||
<div class="brand-mark">ESG</div>
|
||||
<p class="eyebrow">External Services Gateway</p>
|
||||
<h1>Operations console</h1>
|
||||
<p class="muted">Sign in with the seeded SUPER_ADMIN account to inspect health, logs, and inquiries.</p>
|
||||
<form id="loginForm" class="stack">
|
||||
<label>Username<input id="username" name="username" autocomplete="username" required /></label>
|
||||
<label>Password<input id="password" name="password" type="password" autocomplete="current-password" required /></label>
|
||||
<button class="primary" type="submit">Sign in</button>
|
||||
</form>
|
||||
<p id="loginError" class="error" role="alert"></p>
|
||||
</section>
|
||||
|
||||
<section id="appView" class="hidden">
|
||||
<header class="topbar">
|
||||
<div>
|
||||
<p class="eyebrow">External Services Gateway</p>
|
||||
<h1>Operations console</h1>
|
||||
</div>
|
||||
<div class="topbar-actions">
|
||||
<span id="profileLabel" class="pill"></span>
|
||||
<button id="logoutButton" class="ghost" type="button">Sign out</button>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<div id="appError" class="error banner" role="alert"></div>
|
||||
|
||||
<section class="grid two">
|
||||
<article class="panel health-panel">
|
||||
<div class="panel-heading"><h2>System health</h2><button id="refreshHealth" class="icon-button" type="button" title="Refresh health">↻</button></div>
|
||||
<div id="healthStatus" class="health-status"><span class="status-dot"></span><span>Loading…</span></div>
|
||||
<pre id="healthOutput" class="code compact">Loading readiness details…</pre>
|
||||
</article>
|
||||
<article class="panel">
|
||||
<div class="panel-heading"><h2>Inquiry metrics</h2><button id="refreshMetrics" class="icon-button" type="button" title="Refresh metrics">↻</button></div>
|
||||
<div class="metric-grid">
|
||||
<div><span>Total requests</span><strong id="metricTotal">—</strong></div>
|
||||
<div><span>Evaluated</span><strong id="metricEvaluated">—</strong></div>
|
||||
<div><span>Success rate*</span><strong id="metricSuccess">—</strong></div>
|
||||
<div><span>Operational failures</span><strong id="metricFailure">—</strong></div>
|
||||
<div><span>No-match results</span><strong id="metricNoMatch">—</strong></div>
|
||||
<div><span>Avg duration</span><strong id="metricDuration">—</strong></div>
|
||||
</div>
|
||||
<p class="metric-note">* Success rate excludes valid provider responses with no matching policy or owner.</p>
|
||||
</article>
|
||||
</section>
|
||||
|
||||
<section class="panel">
|
||||
<div class="panel-heading"><div><p class="eyebrow">Manual request</p><h2>Run an inquiry</h2></div></div>
|
||||
<form id="inquiryForm" class="inquiry-form">
|
||||
<label>Inquiry type
|
||||
<select id="inquiryType">
|
||||
<option value="person">Person</option>
|
||||
<option value="realEstate">Real estate</option>
|
||||
<option value="sheba">Sheba</option>
|
||||
<option value="shahkar">Shahkar</option>
|
||||
<option value="postalCode">Postal code</option>
|
||||
<option value="legalPerson">Legal person</option>
|
||||
<option value="carByPlate">Car by plate</option>
|
||||
<option value="carByChassis">Car by chassis</option>
|
||||
<option value="thirdPartyCar">Third-party car</option>
|
||||
<option value="policyByChassis">Policy by chassis</option>
|
||||
<option value="policyByPlate">Policy by plate</option>
|
||||
<option value="policyByNationalCode">Policy by national code</option>
|
||||
</select>
|
||||
</label>
|
||||
<label>Idempotency key <input id="idempotencyKey" /></label>
|
||||
<div class="request-toolbar wide">
|
||||
<span id="inquiryHint" class="muted"></span>
|
||||
<button id="toggleRawButton" class="ghost" type="button">Use JSON mode</button>
|
||||
</div>
|
||||
<div id="fieldMode" class="wide">
|
||||
<div id="inquiryFields" class="form-fields"></div>
|
||||
</div>
|
||||
<div id="rawMode" class="wide hidden">
|
||||
<label>JSON payload
|
||||
<textarea id="inquiryPayload" rows="9" spellcheck="false"></textarea>
|
||||
</label>
|
||||
<button id="applyJsonButton" class="ghost" type="button">Apply JSON to form fields</button>
|
||||
</div>
|
||||
<button class="primary" type="submit">Send inquiry</button>
|
||||
</form>
|
||||
<pre id="inquiryOutput" class="code response-box">The formatted response will appear here.</pre>
|
||||
</section>
|
||||
|
||||
<section class="panel">
|
||||
<div class="panel-heading"><div><p class="eyebrow">Batch input</p><h2>Test plate inquiries from JSON</h2></div></div>
|
||||
<p class="muted">Choose a JSON or TXT file, or paste a JSON array. For Parsian third-party plate inquiries, use <strong>Car by plate</strong>; the other routes remain available only for diagnostics.</p>
|
||||
<div class="batch-controls">
|
||||
<label>JSON/TXT file<input id="batchFile" type="file" accept=".json,.txt,application/json,text/plain" /></label>
|
||||
<label>Delay between requests (ms)<input id="batchDelay" type="number" min="0" max="10000" step="100" value="0" /></label>
|
||||
</div>
|
||||
<label class="wide">Input preview / paste JSON
|
||||
<textarea id="batchPayload" rows="8" spellcheck="false" placeholder='[{"nationalCode":"4311402422","plk1":"12","plk2":"ب","plk3":"345","plksrl":"67"}]'></textarea>
|
||||
</label>
|
||||
<div class="endpoint-list">
|
||||
<span class="muted">Endpoints</span>
|
||||
<label class="checkbox"><input type="checkbox" name="batchEndpoint" value="carByPlate" checked /> Car by plate</label>
|
||||
<label class="checkbox"><input type="checkbox" name="batchEndpoint" value="thirdPartyCar" /> Third-party car (diagnostic)</label>
|
||||
<label class="checkbox"><input type="checkbox" name="batchEndpoint" value="policyByPlate" /> Policy by plate (diagnostic)</label>
|
||||
</div>
|
||||
<div class="batch-actions">
|
||||
<button id="runBatchButton" class="primary" type="button">Run batch test</button>
|
||||
<button id="stopBatchButton" class="ghost hidden" type="button">Stop after current request</button>
|
||||
<span id="batchSummary" class="muted"></span>
|
||||
</div>
|
||||
<progress id="batchProgress" class="batch-progress hidden" max="1" value="0"></progress>
|
||||
<div class="table-wrap"><table><thead><tr><th>#</th><th>Input</th><th>Endpoint</th><th>Status</th><th>Tracking code</th><th>Message</th></tr></thead><tbody id="batchResultsBody"></tbody></table></div>
|
||||
<p id="batchOutput" class="table-hint" role="status">Click a request row to expand its full response.</p>
|
||||
</section>
|
||||
|
||||
<section class="panel">
|
||||
<div class="panel-heading"><div><p class="eyebrow">MongoDB audit trail</p><h2>Recent inquiry logs</h2></div><div class="panel-actions"><button id="refreshLogs" class="ghost" type="button">Refresh logs</button><button id="clearLogsButton" class="danger" type="button">Clear all logs</button></div></div>
|
||||
<div class="table-wrap"><table><thead><tr><th>Time</th><th>Type</th><th>Provider</th><th>Status</th><th>Duration</th><th>Tracking code</th></tr></thead><tbody id="logsBody"></tbody></table></div>
|
||||
<p id="logOutput" class="table-hint" role="status">Click a request row to expand its masked request and response.</p>
|
||||
</section>
|
||||
</section>
|
||||
</main>
|
||||
</body>
|
||||
</html>
|
||||
@@ -1,122 +0,0 @@
|
||||
[{
|
||||
"_id": {
|
||||
"$oid": "6a14565497877e39cf0bd2c6"
|
||||
},
|
||||
"fullName": "Soheil Dev",
|
||||
"username": "superadmin",
|
||||
"email": "supadmin@esg.com",
|
||||
"password": "$2b$12$Cgq3Am2nkqWS7mP5.c.KfuOO25e4/MsXe9TYlg1rze7wupJBZvEK.",
|
||||
"role": "SUPER_ADMIN",
|
||||
"clientType": "INTERNAL",
|
||||
"appName": "inquiry-gateway",
|
||||
"clientName": "Internal",
|
||||
"isActive": true,
|
||||
"isBlocked": false,
|
||||
"apiKey": "esg_4abbdf6e7a2b1981eede7e1971e85bf6613f7bedac74df4ff598d4b90b1ccac8",
|
||||
"allowedInquiries": [],
|
||||
"requestLimitPerMinute": 60,
|
||||
"requestLimitPerDay": 10000,
|
||||
"totalRequests": 0,
|
||||
"passwordChangedAt": {
|
||||
"$date": "2026-06-07T12:30:24.507Z"
|
||||
},
|
||||
"createdAt": {
|
||||
"$date": "2026-05-25T14:01:56.946Z"
|
||||
},
|
||||
"updatedAt": {
|
||||
"$date": "2026-06-07T12:30:34.133Z"
|
||||
},
|
||||
"__v": 0,
|
||||
"lastLoginAt": {
|
||||
"$date": "2026-06-07T12:30:34.133Z"
|
||||
},
|
||||
"refreshToken": "$2b$12$DdaCLkcbyihUA3JNLF2bB.9MvFDg/i1759S23CE38K4hFk8ST3L4O"
|
||||
},
|
||||
{
|
||||
"_id": {
|
||||
"$oid": "6a145802fd0ee991759157bf"
|
||||
},
|
||||
"fullName": "Tejarat Nou",
|
||||
"username": "tejaratnou",
|
||||
"email": "tejaratnou@esg.com",
|
||||
"mobile": "09999985840",
|
||||
"password": "$2b$12$bpvwOsUD9WBBfIDq46PJRuXXRQTcUF7d3EW98PvnxS08qLLCeKk52",
|
||||
"role": "USER",
|
||||
"clientType": "EXTERNAL",
|
||||
"appName": "Beno",
|
||||
"clientName": "Tejarat Nou Insurance Company Ltd",
|
||||
"isActive": true,
|
||||
"isBlocked": false,
|
||||
"apiKey": "esg_2fbab4a8fbef69427f214d0c2a37b4644bb455ff8d4c79a4985d90ce4461ff9a",
|
||||
"allowedInquiries": [
|
||||
"PERSON_INQUIRY"
|
||||
],
|
||||
"requestLimitPerMinute": 60,
|
||||
"requestLimitPerDay": 10000,
|
||||
"totalRequests": 4,
|
||||
"passwordChangedAt": {
|
||||
"$date": "2026-05-25T14:09:06.257Z"
|
||||
},
|
||||
"createdBy": {
|
||||
"$oid": "6a14565497877e39cf0bd2c6"
|
||||
},
|
||||
"createdAt": {
|
||||
"$date": "2026-05-25T14:09:06.259Z"
|
||||
},
|
||||
"updatedAt": {
|
||||
"$date": "2026-06-03T09:51:00.311Z"
|
||||
},
|
||||
"__v": 0,
|
||||
"lastLoginAt": {
|
||||
"$date": "2026-06-03T09:46:17.215Z"
|
||||
}
|
||||
},
|
||||
{
|
||||
"_id": {
|
||||
"$oid": "6a256575c028f57a8b3f57a5"
|
||||
},
|
||||
"fullName": "Moallem INS",
|
||||
"username": "moallem",
|
||||
"email": "moallem@esg.com",
|
||||
"mobile": "09226187419",
|
||||
"password": "$2b$12$HlGWxFk3dLufl1t.ofTW9O5jWRaV0b./pOakjLDCKuJyvAnvMHsKq",
|
||||
"role": "USER",
|
||||
"clientType": "EXTERNAL",
|
||||
"appName": "Moallem",
|
||||
"clientName": "Moallem Insurance Company Ltd",
|
||||
"isActive": true,
|
||||
"isBlocked": false,
|
||||
"apiKey": "esg_33bd4f811e04476e8fd871230e025829717e274415de4b1b9939a11deb459cd3",
|
||||
"allowedInquiries": [
|
||||
"PERSON_INQUIRY",
|
||||
"POSTAL_CODE_INQUIRY",
|
||||
"REAL_ESTATE_INQUIRY",
|
||||
"SHEBA_INQUIRY",
|
||||
"SHAHKAR_INQUIRY",
|
||||
"LEGAL_PERSON_INQUIRY",
|
||||
"CAR_PLATE_INQUIRY",
|
||||
"POLICY_BY_CHASSIS_INQUIRY",
|
||||
"POLICY_BY_PLATE_INQUIRY",
|
||||
"POLICY_BY_NATIONAL_CODE_INQUIRY"
|
||||
],
|
||||
"requestLimitPerMinute": 60,
|
||||
"requestLimitPerDay": 10000,
|
||||
"totalRequests": 1,
|
||||
"passwordChangedAt": {
|
||||
"$date": "2026-06-07T12:35:01.128Z"
|
||||
},
|
||||
"createdBy": {
|
||||
"$oid": "6a14565497877e39cf0bd2c6"
|
||||
},
|
||||
"createdAt": {
|
||||
"$date": "2026-06-07T12:35:01.131Z"
|
||||
},
|
||||
"updatedAt": {
|
||||
"$date": "2026-06-07T12:35:24.717Z"
|
||||
},
|
||||
"__v": 0,
|
||||
"refreshToken": "$2b$12$OpA7uoyG3ACfeVVweOBCL.8R7laFx0tkU1vRdI9DEUJE0eFIEI5Cu",
|
||||
"lastLoginAt": {
|
||||
"$date": "2026-06-07T12:35:13.319Z"
|
||||
}
|
||||
}]
|
||||
@@ -0,0 +1,116 @@
|
||||
:root {
|
||||
color-scheme: dark;
|
||||
--bg: #0b1020;
|
||||
--bg-soft: #121a2d;
|
||||
--panel: rgba(19, 29, 49, 0.84);
|
||||
--line: rgba(148, 163, 184, 0.2);
|
||||
--text: #e5edf8;
|
||||
--muted: #96a8c0;
|
||||
--accent: #65d8b2;
|
||||
--accent-strong: #20b486;
|
||||
--danger: #ff8f8f;
|
||||
--shadow: 0 24px 70px rgba(0, 0, 0, 0.28);
|
||||
}
|
||||
|
||||
* { box-sizing: border-box; }
|
||||
body { margin: 0; min-height: 100vh; background: radial-gradient(circle at top right, #1c3450 0, var(--bg) 48%); color: var(--text); font: 15px/1.5 Inter, ui-sans-serif, system-ui, -apple-system, sans-serif; }
|
||||
button, input, select, textarea { font: inherit; }
|
||||
button { cursor: pointer; }
|
||||
.shell { width: min(1240px, calc(100% - 32px)); margin: 0 auto; padding: 40px 0 72px; }
|
||||
.hidden { display: none !important; }
|
||||
.auth-card { width: min(440px, 100%); margin: 10vh auto 0; padding: 36px; background: var(--panel); border: 1px solid var(--line); border-radius: 24px; box-shadow: var(--shadow); backdrop-filter: blur(16px); }
|
||||
.brand-mark { width: 48px; height: 48px; display: grid; place-items: center; border-radius: 14px; background: linear-gradient(135deg, var(--accent), #67a7ff); color: #08131f; font-weight: 900; letter-spacing: .08em; }
|
||||
.eyebrow { margin: 0 0 4px; color: var(--accent); font-size: 11px; font-weight: 800; letter-spacing: .16em; text-transform: uppercase; }
|
||||
h1, h2, p { margin-top: 0; }
|
||||
h1 { margin-bottom: 8px; font-size: clamp(28px, 4vw, 44px); letter-spacing: -.04em; }
|
||||
h2 { margin-bottom: 0; font-size: 18px; }
|
||||
.muted { color: var(--muted); }
|
||||
.stack, .inquiry-form { display: grid; gap: 16px; }
|
||||
label { display: grid; gap: 7px; color: var(--muted); font-size: 13px; font-weight: 700; }
|
||||
input, select, textarea { width: 100%; border: 1px solid var(--line); border-radius: 10px; padding: 11px 12px; background: rgba(6, 12, 26, .66); color: var(--text); outline: none; }
|
||||
input:focus, select:focus, textarea:focus { border-color: var(--accent); box-shadow: 0 0 0 3px rgba(101, 216, 178, .14); }
|
||||
textarea { resize: vertical; font: 13px/1.5 ui-monospace, SFMono-Regular, Menlo, monospace; }
|
||||
button { border: 0; border-radius: 10px; padding: 10px 16px; color: var(--text); background: rgba(148, 163, 184, .14); }
|
||||
button:hover { filter: brightness(1.12); }
|
||||
.primary { background: linear-gradient(135deg, var(--accent-strong), #2d9ee8); color: #05131a; font-weight: 800; }
|
||||
.ghost, .icon-button { border: 1px solid var(--line); background: transparent; }
|
||||
.danger { border: 1px solid rgba(255, 143, 143, .45); background: rgba(255, 95, 95, .12); color: var(--danger); }
|
||||
.icon-button { padding: 5px 10px; font-size: 20px; }
|
||||
.topbar, .panel-heading { display: flex; align-items: center; justify-content: space-between; gap: 16px; }
|
||||
.panel-actions, .batch-actions, .endpoint-list { display: flex; align-items: center; flex-wrap: wrap; gap: 10px; }
|
||||
.topbar { margin-bottom: 24px; }
|
||||
.topbar h1 { margin-bottom: 0; }
|
||||
.topbar-actions { display: flex; align-items: center; gap: 10px; }
|
||||
.pill { border: 1px solid rgba(101, 216, 178, .35); border-radius: 999px; padding: 6px 10px; color: var(--accent); font-size: 12px; }
|
||||
.grid { display: grid; gap: 18px; margin-bottom: 18px; }
|
||||
.grid.two { grid-template-columns: repeat(2, minmax(0, 1fr)); }
|
||||
.panel { margin-bottom: 18px; padding: 22px; overflow: hidden; background: var(--panel); border: 1px solid var(--line); border-radius: 18px; box-shadow: 0 12px 38px rgba(0,0,0,.14); }
|
||||
.panel-content[hidden] { display: none; }
|
||||
.panel-collapse { flex: 0 0 auto; min-width: 34px; padding: 2px 9px; font-size: 20px; line-height: 1.2; }
|
||||
.panel-collapsed { padding-bottom: 14px; }
|
||||
.health-status { display: flex; align-items: center; gap: 8px; margin: 20px 0 12px; font-weight: 800; }
|
||||
.status-dot { width: 10px; height: 10px; border-radius: 50%; background: var(--muted); }
|
||||
.status-dot.ok { background: var(--accent); box-shadow: 0 0 14px var(--accent); }
|
||||
.status-dot.error { background: var(--danger); box-shadow: 0 0 14px var(--danger); }
|
||||
.code { margin: 16px 0 0; padding: 16px; overflow: auto; border: 1px solid var(--line); border-radius: 12px; background: #07101e; color: #b9d4ee; white-space: pre-wrap; word-break: break-word; }
|
||||
.compact { max-height: 260px; font-size: 12px; }
|
||||
.response-box { min-height: 160px; }
|
||||
.metric-grid { display: grid; grid-template-columns: repeat(3, 1fr); gap: 12px; margin-top: 20px; }
|
||||
.metric-grid div { padding: 16px; border: 1px solid var(--line); border-radius: 12px; background: rgba(6, 12, 26, .34); }
|
||||
.metric-grid span { display: block; color: var(--muted); font-size: 12px; }
|
||||
.metric-grid strong { display: block; margin-top: 4px; font-size: 24px; }
|
||||
.metric-note { margin: 14px 0 0; color: var(--muted); font-size: 11px; }
|
||||
.inquiry-form { grid-template-columns: repeat(2, minmax(0, 1fr)); margin-top: 20px; }
|
||||
.inquiry-form .wide, .inquiry-form button { grid-column: 1 / -1; }
|
||||
.request-toolbar { display: flex; align-items: center; justify-content: space-between; gap: 12px; }
|
||||
.form-fields { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 16px; }
|
||||
.batch-controls { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 16px; margin: 18px 0; }
|
||||
.endpoint-list { margin: 16px 0; }
|
||||
.checkbox { display: inline-flex; grid-template-columns: auto 1fr; align-items: center; gap: 7px; color: var(--text); font-weight: 600; }
|
||||
.checkbox input { width: auto; accent-color: var(--accent-strong); }
|
||||
.batch-actions { margin: 16px 0; }
|
||||
.batch-progress { width: 100%; height: 8px; margin: 4px 0 12px; accent-color: var(--accent-strong); }
|
||||
.field-hint { color: var(--muted); font-size: 11px; font-weight: 500; }
|
||||
#rawMode { display: grid; gap: 12px; }
|
||||
#rawMode button { justify-self: start; }
|
||||
.table-wrap { overflow-x: auto; margin-top: 18px; }
|
||||
table { width: 100%; border-collapse: collapse; min-width: 720px; }
|
||||
th, td { padding: 12px 10px; border-bottom: 1px solid var(--line); text-align: left; white-space: nowrap; }
|
||||
th { color: var(--muted); font-size: 11px; letter-spacing: .08em; text-transform: uppercase; }
|
||||
tbody tr.data-row { cursor: pointer; }
|
||||
tbody tr.data-row:hover { background: rgba(101, 216, 178, .07); }
|
||||
tbody tr.data-row:focus { outline: 2px solid var(--accent); outline-offset: -2px; }
|
||||
.row-toggle { display: inline-block; width: 1.1em; margin-right: 4px; color: var(--accent); transition: transform .16s ease; }
|
||||
.data-row[aria-expanded="true"] .row-toggle { transform: rotate(90deg); }
|
||||
.detail-row td { padding: 0 10px 14px; background: rgba(6, 12, 26, .28); }
|
||||
.detail-panel { margin: 0; padding: 14px; border: 1px solid var(--line); border-radius: 10px; background: #07101e; }
|
||||
.detail-panel pre { margin: 0; max-height: 420px; overflow: auto; color: #b9d4ee; white-space: pre-wrap; word-break: break-word; font: 12px/1.5 ui-monospace, SFMono-Regular, Menlo, monospace; }
|
||||
.detail-heading { margin: 0 0 10px; color: var(--accent); font-size: 12px; font-weight: 800; }
|
||||
.outbound-call { margin-top: 10px; padding: 12px; border: 1px solid var(--line); border-radius: 9px; background: rgba(19, 29, 49, .68); }
|
||||
.outbound-call-title { margin-bottom: 8px; overflow-wrap: anywhere; color: var(--text); font: 12px/1.45 ui-monospace, SFMono-Regular, Menlo, monospace; }
|
||||
.detail-label { display: block; margin-bottom: 5px; color: var(--muted); font-size: 11px; }
|
||||
.curl-row { display: flex; align-items: flex-start; gap: 8px; }
|
||||
.curl-row textarea { min-height: 84px; color: #b9d4ee; font-size: 11px; }
|
||||
.copy-curl { flex: 0 0 auto; white-space: nowrap; }
|
||||
.xml-viewer { margin-top: 10px; border: 1px solid var(--line); border-radius: 8px; background: rgba(6, 12, 26, .5); }
|
||||
.xml-toolbar { display: flex; align-items: center; justify-content: space-between; gap: 8px; padding: 8px 10px; border-bottom: 1px solid var(--line); }
|
||||
.xml-toolbar .detail-label { margin: 0; color: var(--accent); font-weight: 800; }
|
||||
.xml-actions { display: flex; flex-wrap: wrap; gap: 6px; }
|
||||
.xml-toolbar button { padding: 5px 9px; font-size: 12px; }
|
||||
.xml-search { display: flex; align-items: center; gap: 6px; padding: 8px 10px; border-bottom: 1px solid var(--line); }
|
||||
.xml-search input { min-width: 180px; padding: 6px 9px; font-size: 12px; }
|
||||
.xml-search button { min-width: 30px; padding: 5px 8px; font-size: 12px; }
|
||||
.xml-match-count { min-width: 64px; color: var(--muted); font-size: 11px; text-align: right; }
|
||||
.xml-output mark { border-radius: 3px; background: rgba(250, 204, 21, .35); color: inherit; }
|
||||
.xml-output mark.active-match { outline: 2px solid var(--accent); background: rgba(101, 216, 178, .35); }
|
||||
.xml-output { max-height: 360px !important; padding: 12px !important; }
|
||||
.outbound-response { margin-top: 10px !important; max-height: 180px !important; }
|
||||
.full-detail { margin-top: 12px; }
|
||||
.full-detail summary { cursor: pointer; color: var(--muted); font-size: 12px; }
|
||||
.table-hint { margin: 12px 0 0; color: var(--muted); font-size: 12px; }
|
||||
.status-success { color: var(--accent); }
|
||||
.status-neutral { color: #f6c85f; }
|
||||
.status-failure { color: var(--danger); }
|
||||
.error { min-height: 20px; color: var(--danger); }
|
||||
.banner { margin: 0 0 16px; }
|
||||
@media (max-width: 780px) { .shell { width: min(100% - 20px, 680px); padding-top: 20px; } .grid.two, .inquiry-form, .form-fields, .batch-controls, .metric-grid { grid-template-columns: 1fr; } .inquiry-form .wide, .inquiry-form button { grid-column: auto; } .request-toolbar { align-items: flex-start; flex-direction: column; } .topbar { align-items: flex-start; flex-direction: column; } .topbar-actions, .panel-actions { width: 100%; justify-content: space-between; } .panel { padding: 16px; } }
|
||||
Reference in New Issue
Block a user