Share Executive Dashboard with Client
Hides internal SC / VC navigation, download instructions, and file uploaders
Advisor Note / Executive Summary (Optional)
Dataset Scope to Include
Choose whether to share the full report or only your active filtered view.
All Loaded Data
Filtered View Only
Instant Shareable Client URL #client=...
Ready for Slack / Email
Compresses aggregated SKU metrics directly into an encrypted-style URL hash with zero server storage. Anyone with the link sees the interactive Client View.
Large dataset detected: URL may be truncated by some email clients.
We recommend Method 2 (Interactive Client HTML) below for full fidelity, or you can copy a compact Top-150 Highest-Cost SKUs link.
Copy Top-150 SKU Summary Link Instead
URL Length: 0 characters • 0 aggregated SKU-tier records
Download Interactive Client Dashboard .html
Unlimited SKUs • Works Offline
Generates a self-contained HTML file with the client’s dataset baked in and locked into Client Presentation Mode. Ideal for 10,000+ SKU reports or email/Slack file attachments.
Download Client Dashboard (.html)
Preview Mode
You are previewing exact Client Presentation Mode (internal menus & uploaders are hidden).
Exit Client Preview
Inventory & FBA Fees
/
Aged Inventory Surcharge
Active
Snapshot: -
Analyze FBA long-term storage surcharges, chronological age tiers, and stranded exposure
Share with Client
Clear / New File
Hub Overview
100% Client-Side Browser Processing — Zero Server Uploads
Analyze Amazon FBA & Inventory fee reports instantly in your browser and generate clean, read-only executive client views in one click.
Upcoming Slots
Modular reports/
Inventory & FBA Fees Modules
Click an active module to launch or view modular setup instructions
Developer Quick Guide: Adding reports/*.html Modules
2-step workflow for GitHub + Cloudflare Pages automatic deployment
Step 1 • Add Standalone HTML File to reports/
Save each new report analyzer as a self-contained HTML file inside the reports/ folder in your repository so tools stay cleanly isolated:
amazon-internal-tools/
├── index.html <-- Main Analytics Hub Shell
└── reports/
└── low-inventory-fees.html <-- Next Standalone Report Tool
Step 2 • Activate in TOOLS_CONFIG
Copy Config
In index.html, update the module's entry inside TOOLS_CONFIG from status: 'soon' to status: 'active':
{
id: 'low-inventory-fees',
name: 'Low Inventory Level Fees',
category: 'Inventory & FBA Fees',
status: 'active', // Changed from 'soon' to 'active'
type: 'iframe',
path: 'reports/low-inventory-fees.html'
}
Commit to GitHub — Cloudflare Pages deploys your live update automatically in ~15 seconds.
How to Download This Report from Seller Central
Hide Steps
2
Select the Event Month and Year you want to analyze, request/download the .csv (or .xlsx) report, and drop the file below.
Missing Required Report Columns
Seller Central → Fulfillment → Aged Inventory Surcharge Report
Drop your raw Amazon .csv , .xlsx , or .xls file below to inspect multi-currency surcharges, 365+ day inventory, and shareable client insights.
Load Sample Data (US & CA)
Back to Loaded Report
100% Client-Side
Zero server uploads; processed in memory.
1-Click Client Sharing
Shareable URL hash or offline Client HTML.
Multi-Currency Safe
USD & CAD totals are never mixed.
All Countries
All Currencies
All Age Tiers
All Conditions
Total Surcharge Charged
Snapshot: -
Strictly separated per currency
Total Units & Unique SKUs Charged
units charged
0 unique SKUs
Across 0 report rows
365+ Days Severe Aging Exposure
365+, 366–455 & 456+ tiers
Filter 365+ Days
0 units across 0 SKUs
No Listing / Stranded Exposure
Condition ≠ New
Filter Stranded
0 units across 0 SKUs
Surcharge by Age Tier
Chronological order • Click any bar to filter table to that tier
USD
Top 10 Highest-Cost SKUs
Hover bars for product title, ASIN & charged unit breakdown
Currency:
USD
Grouped by SKU
Raw Rows
Aggregated per SKU + Country + Currency
Export CSV
Export Excel (.xlsx)
No inventory rows match your current filters.
Reset All Filters
Previous
Page 1 of 1
Next
Report Module File Not Found
This tool is set to status: 'active' and type: 'iframe', expecting the file at reports/low-inventory-fees.html.
# Expected repository structure:
├── index.html
└── reports/low-inventory-fees.html
Back to Hub Overview
Coming Soon — Ready for reports/low-inventory-fees.html
Analyze FBA Low-Inventory-Level Fee charges, historical days of supply, and fee impact per SKU.
Expected Seller Central Report
Seller Central → Fulfillment → FBA Inventory / Economics → Low-Inventory-Level Fee
How to Activate This Module
1. Add your standalone HTML file to reports/
Place the completed analyzer file in your GitHub repository at:
reports/low-inventory-fees.html
2. Set status: 'active' in TOOLS_CONFIG
Open Aged Inventory Surcharge
Back to Hub Overview
\n' + docClone.outerHTML;
const blob = new Blob([finalHtml], { type: 'text/html;charset=utf-8;' });
const url = URL.createObjectURL(blob);
const link = document.createElement('a');
const slugBrand = (brand || 'client')
.toLowerCase()
.replace(/[^a-z0-9]+/g, '-')
.replace(/^-|-$/g, '') || 'client';
const slugPeriod = (period || new Date().toISOString().slice(0, 7))
.toLowerCase()
.replace(/[^a-z0-9]+/g, '-')
.replace(/^-|-$/g, '');
link.href = url;
link.download = `${slugBrand}-aged-inventory-report-${slugPeriod}.html`;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
URL.revokeObjectURL(url);
showToast('Downloaded standalone interactive Client HTML dashboard!', 'success');
}
// =======================================================================
// SIDEBAR, HUB OVERVIEW & VIEW ROUTER
// =======================================================================
function renderSidebar() {
const query = state.sidebarSearch.trim().toLowerCase();
const categories = [];
const grouped = {};
for (const tool of TOOLS_CONFIG) {
if (query) {
const hay = `${tool.name} ${tool.category} ${tool.description}`.toLowerCase();
if (!hay.includes(query)) continue;
}
if (!grouped[tool.category]) {
grouped[tool.category] = [];
categories.push(tool.category);
}
grouped[tool.category].push(tool);
}
if (categories.length === 0) {
dom.sidebarNav.innerHTML = `No matching tools found.
`;
return;
}
dom.sidebarNav.innerHTML = categories.map(cat => {
const itemsHtml = grouped[cat].map(tool => {
const isSelected = state.activeToolId === tool.id;
const isLive = tool.status === 'active';
const btnClasses = isSelected
? 'bg-amber-500/15 text-amber-300 border-amber-500/30 font-semibold'
: 'text-slate-300 hover:bg-hub-sidebarHover hover:text-white border-transparent font-medium';
const statusBadge = isLive
? ` `
: `Soon `;
return `
${getToolIconSvg(tool.icon)}
${escapeHtml(tool.name)}
${statusBadge}
`;
}).join('');
return `
${escapeHtml(cat)}
${itemsHtml}
`;
}).join('');
dom.sidebarNav.querySelectorAll('button[data-tool-id]').forEach(btn => {
btn.addEventListener('click', () => {
selectTool(btn.getAttribute('data-tool-id'));
closeMobileSidebar();
});
});
}
function renderOverview() {
const modules = TOOLS_CONFIG.filter(t => t.id !== 'overview');
const activeCount = modules.filter(t => t.status === 'active').length;
const soonCount = modules.filter(t => t.status !== 'active').length;
dom.statActiveTools.textContent = String(activeCount);
dom.statSoonTools.textContent = String(soonCount);
dom.overviewCardsGrid.innerHTML = modules.map(tool => {
const isLive = tool.status === 'active';
const badge = isLive
? ` Active `
: `Coming Soon — Ready for ${escapeHtml(tool.path)} `;
const actionLabel = isLive ? 'Launch Analyzer →' : 'View Module Slot & Setup';
const actionStyle = isLive
? 'bg-slate-900 hover:bg-slate-800 text-white'
: 'bg-slate-100 hover:bg-slate-200 text-slate-700';
return `
${escapeHtml(tool.category)}
${badge}
${getToolIconSvg(tool.icon)}
${escapeHtml(tool.name)}
${escapeHtml(tool.description)}
Source: ${escapeHtml(tool.reportSource)}
${actionLabel}
`;
}).join('');
dom.overviewCardsGrid.querySelectorAll('button[data-launch-id]').forEach(btn => {
btn.addEventListener('click', () => {
selectTool(btn.getAttribute('data-launch-id'));
});
});
}
async function selectTool(toolId) {
if (state.clientMode.active) return;
const tool = TOOLS_CONFIG.find(t => t.id === toolId) || TOOLS_CONFIG[1];
state.activeToolId = tool.id;
if (history.replaceState) {
history.replaceState(null, '', `#${tool.id}`);
}
renderSidebar();
// Update Topbar
dom.topbarCategory.textContent = tool.category;
dom.topbarTitle.textContent = tool.name;
dom.topbarSubtitle.textContent = tool.description;
if (tool.status === 'active') {
dom.topbarBadge.className = 'inline-flex items-center gap-1 text-[11px] font-semibold px-2 py-0.5 rounded-full bg-emerald-50 text-emerald-700 border border-emerald-200';
dom.topbarBadge.innerHTML = ` Active`;
} else {
dom.topbarBadge.className = 'inline-flex items-center gap-1 text-[11px] font-semibold px-2 py-0.5 rounded-full bg-slate-100 text-slate-600 border border-slate-200';
dom.topbarBadge.textContent = 'Soon';
}
// Hide all views & contextual topbar controls
dom.viewOverview.classList.add('hidden');
dom.viewAgedInventory.classList.add('hidden');
dom.viewIframe.classList.add('hidden');
dom.viewSoon.classList.add('hidden');
dom.btnShareClientTop.classList.add('hidden');
dom.btnShareClientTop.classList.remove('inline-flex');
dom.btnClearNewTop.classList.add('hidden');
dom.btnClearNewTop.classList.remove('inline-flex');
dom.topbarSnapshotBadge.classList.add('hidden');
dom.topbarSnapshotBadge.classList.remove('inline-flex');
dom.iframeActions.classList.add('hidden');
dom.iframeActions.classList.remove('flex');
if (tool.id === 'overview') {
renderOverview();
dom.viewOverview.classList.remove('hidden');
return;
}
if (tool.status !== 'active') {
renderSoonView(tool);
dom.viewSoon.classList.remove('hidden');
return;
}
if (tool.type === 'builtin' && tool.id === 'aged-inventory') {
dom.viewAgedInventory.classList.remove('hidden');
if (state.ai.rawData.length > 0) {
dom.btnShareClientTop.classList.remove('hidden');
dom.btnShareClientTop.classList.add('inline-flex');
dom.btnClearNewTop.classList.remove('hidden');
dom.btnClearNewTop.classList.add('inline-flex');
dom.topbarSnapshotBadge.textContent = `Snapshot: ${state.ai.snapshotLabel}`;
dom.topbarSnapshotBadge.classList.remove('hidden');
dom.topbarSnapshotBadge.classList.add('inline-flex');
renderAiCharts(getFilteredAiRows());
}
return;
}
if (tool.type === 'iframe' && tool.path) {
dom.viewIframe.classList.remove('hidden');
dom.iframeActions.classList.remove('hidden');
dom.iframeActions.classList.add('flex');
dom.btnOpenIframeTab.href = tool.path;
loadExternalToolFrame(tool);
}
}
async function loadExternalToolFrame(tool) {
dom.iframeMissingFallback.classList.add('hidden');
dom.iframeFallbackTitle.textContent = `${tool.name} — Ready for ${tool.path}`;
dom.iframeFallbackPath.textContent = tool.path;
dom.iframeFallbackTree.textContent = `└── ${tool.path}`;
if (window.location.protocol.startsWith('http')) {
try {
const resp = await fetch(tool.path, { method: 'HEAD' });
if (!resp.ok) {
dom.toolFrame.src = 'about:blank';
dom.iframeMissingFallback.classList.remove('hidden');
return;
}
} catch (err) {
dom.toolFrame.src = 'about:blank';
dom.iframeMissingFallback.classList.remove('hidden');
return;
}
}
dom.toolFrame.src = tool.path;
}
function renderSoonView(tool) {
const targetPath = tool.path || `reports/${tool.id}.html`;
dom.soonReadyBadge.textContent = `Coming Soon — Ready for ${targetPath}`;
dom.soonTitle.textContent = tool.name;
dom.soonDesc.textContent = tool.description;
dom.soonReportSource.textContent = tool.reportSource;
dom.soonFilePath.textContent = targetPath;
dom.soonCodePreview.textContent =
`{
id: '${tool.id}',
name: '${tool.name}',
category: '${tool.category}',
status: 'active', // <-- Flip from 'soon' to 'active'
type: 'iframe',
path: '${targetPath}'
}`;
}
function openMobileSidebar() {
dom.sidebar.classList.remove('-translate-x-full');
dom.sidebarBackdrop.classList.remove('hidden');
}
function closeMobileSidebar() {
dom.sidebar.classList.add('-translate-x-full');
dom.sidebarBackdrop.classList.add('hidden');
}
function toggleSidebar() {
const isDesktop = window.innerWidth >= 1024;
if (isDesktop) {
state.sidebarCollapsedDesktop = !state.sidebarCollapsedDesktop;
dom.sidebar.classList.toggle('lg:hidden', state.sidebarCollapsedDesktop);
setTimeout(() => {
if (state.ai.charts.ageTier) state.ai.charts.ageTier.resize();
if (state.ai.charts.topSkus) state.ai.charts.topSkus.resize();
}, 320);
} else {
if (dom.sidebar.classList.contains('-translate-x-full')) {
openMobileSidebar();
} else {
closeMobileSidebar();
}
}
}
// =======================================================================
// AGED INVENTORY SURCHARGE ANALYZER LOGIC
// =======================================================================
function getAgeTierSortOrder(tier) {
if (!tier) return 99999;
const str = String(tier).trim();
const match = str.match(/\d+/);
if (!match) return 99999;
const base = parseInt(match[0], 10);
// Ensures 181-210 ... 331-365 (331) -> 365+ (365.5) -> 366-455 (366) -> 456+ (456.5)
return str.includes('+') ? base + 0.5 : base;
}
function sortAgeTiersChronologically(tiers) {
return [...tiers].sort((a, b) => getAgeTierSortOrder(a) - getAgeTierSortOrder(b));
}
function isSevereAgedTier(tier) {
const order = getAgeTierSortOrder(tier);
return order >= 365 && order < 99999;
}
function isNonNewCondition(cond) {
const norm = String(cond || '').trim().toLowerCase();
return norm === 'no listing' || norm !== 'new';
}
function getCurrencyPalette(currency, idx = 0) {
return CURRENCY_PALETTE[currency] || FALLBACK_PALETTE[idx % FALLBACK_PALETTE.length];
}
function renderAgeTierBadge(tier) {
const safe = escapeHtml(tier || 'Unknown');
const val = getAgeTierSortOrder(tier);
if (val >= 456 && val < 99999) {
return `${safe} `;
}
if (val >= 365 && val < 99999) {
return `${safe} `;
}
if (val >= 271 && val < 365) {
return `${safe} `;
}
return `${safe} `;
}
function renderConditionBadge(cond) {
const raw = String(cond || '-').trim();
const label = state.clientMode.active && raw.toLowerCase() === 'no listing' ? 'Unlisted' : raw;
const safe = escapeHtml(label);
if (isNonNewCondition(raw)) {
return ` ${safe} `;
}
return `${safe} `;
}
/** Flexibly normalize headers and validate Amazon Aged Inventory Surcharge rows */
function validateAndNormalizeRows(rawRows) {
if (!Array.isArray(rawRows) || rawRows.length === 0) {
return {
valid: false,
errorTitle: 'Empty Report File',
errorMessage: 'The selected file contains no data rows. Please upload a valid Amazon Aged Inventory Surcharge Report.'
};
}
const headerKeys = Object.keys(rawRows[0] || {}).map(k =>
String(k).replace(/^\uFEFF/, '').trim().toLowerCase().replace(/[\s_]+/g, '-')
);
const missing = REQUIRED_AGED_COLUMNS.filter(req => !headerKeys.includes(req));
if (missing.length > 0) {
return {
valid: false,
errorTitle: 'Missing Required Amazon Report Columns',
errorMessage: `Missing required column(s): ${missing.join(', ')}. Expected columns include snapshot-date, sku, fnsku, asin, product-name, condition, per-unit-volume, currency, volume-unit, country, qty-charged, amount-charged, surcharge-age-tier, rate-surcharge.`
};
}
const normalized = [];
for (let i = 0; i < rawRows.length; i++) {
const raw = rawRows[i];
if (!raw || typeof raw !== 'object') continue;
const map = {};
for (const key of Object.keys(raw)) {
const cleanKey = String(key).replace(/^\uFEFF/, '').trim().toLowerCase().replace(/[\s_]+/g, '-');
map[cleanKey] = raw[key];
}
const sku = String(map['sku'] ?? '').trim();
const asin = String(map['asin'] ?? '').trim();
const qtyCharged = parseNum(map['qty-charged']);
const amountCharged = parseNum(map['amount-charged']);
if (!sku && !asin && qtyCharged === 0 && amountCharged === 0) continue;
const country = String(map['country'] || 'US').trim().toUpperCase();
const currency = String(map['currency'] || 'USD').trim().toUpperCase();
const rawTier = String(map['surcharge-age-tier'] || 'Unknown').trim();
const cleanTier = rawTier.replace(/\s*days$/i, '').trim() || 'Unknown';
const perUnitVolume = parseNum(map['per-unit-volume']);
normalized.push({
snapshotDate: String(map['snapshot-date'] ?? '').trim(),
sku: sku || '-',
fnsku: String(map['fnsku'] ?? '-').trim() || '-',
asin: asin || '-',
productName: String(map['product-name'] ?? '-').trim() || '-',
condition: String(map['condition'] ?? 'New').trim() || 'New',
perUnitVolume: perUnitVolume,
totalRowVolume: perUnitVolume * qtyCharged,
currency: currency,
volumeUnit: String(map['volume-unit'] ?? 'cubic feet').trim(),
country: country,
qtyCharged: qtyCharged,
amountCharged: amountCharged,
ageTier: cleanTier,
rateSurcharge: parseNum(map['rate-surcharge'])
});
}
if (normalized.length === 0) {
return {
valid: false,
errorTitle: 'No Chargeable Records Found',
errorMessage: 'Report headers were recognized, but all data rows were blank.'
};
}
return { valid: true, rows: normalized };
}
/** Read CSV (ArrayBuffer -> fatal UTF-8 -> Windows-1252 fallback) or Excel */
async function handleAgedInventoryFile(file) {
if (!file) return;
hideValidationError();
const ext = file.name.split('.').pop().toLowerCase();
if (!['csv', 'xlsx', 'xls', 'txt'].includes(ext)) {
showValidationError('Unsupported File Format', `File "${file.name}" is not supported. Please select a .csv, .xlsx, or .xls report.`);
return;
}
try {
const buffer = await file.arrayBuffer();
if (ext === 'csv' || ext === 'txt') {
let csvText = '';
let encodingLabel = 'UTF-8';
try {
const utf8Decoder = new TextDecoder('utf-8', { fatal: true });
csvText = utf8Decoder.decode(buffer);
} catch (encodingErr) {
const win1252Decoder = new TextDecoder('windows-1252');
csvText = win1252Decoder.decode(buffer);
encodingLabel = 'Windows-1252 (Fallback)';
}
const parsed = Papa.parse(csvText, {
header: true,
skipEmptyLines: 'greedy',
dynamicTyping: false
});
if (parsed.errors && parsed.errors.length > 0 && (!parsed.data || parsed.data.length === 0)) {
showValidationError('CSV Parsing Error', 'Could not parse CSV file structure. Please verify the file is valid.');
return;
}
const result = validateAndNormalizeRows(parsed.data);
if (!result.valid) {
showValidationError(result.errorTitle, result.errorMessage);
return;
}
activateAgedDataset(result.rows, file.name, encodingLabel);
} else {
const workbook = XLSX.read(buffer, { type: 'array' });
if (!workbook.SheetNames || workbook.SheetNames.length === 0) {
showValidationError('Empty Excel Workbook', 'No worksheets were found in the uploaded Excel file.');
return;
}
const firstSheet = workbook.Sheets[workbook.SheetNames[0]];
const jsonRows = XLSX.utils.sheet_to_json(firstSheet, { defval: '' });
const result = validateAndNormalizeRows(jsonRows);
if (!result.valid) {
showValidationError(result.errorTitle, result.errorMessage);
return;
}
activateAgedDataset(result.rows, file.name, `Excel (${ext.toUpperCase()})`);
}
} catch (err) {
console.error(err);
showValidationError('File Processing Error', `Failed to read "${file.name}": ${err.message}`);
}
}
/** Realistic Multi-Currency Sample Dataset (US + CA, USD + CAD, New + No Listing, 271-300 through 456+ & earlier tiers) */
function loadSampleData() {
hideValidationError();
const sample = [
{
'snapshot-date': '2026-10-15T00:00:00+00:00',
'sku': 'CHEF-KNIFE-SET-8PC',
'fnsku': 'X001KNIFE8',
'asin': 'B08XYZ1001',
'product-name': 'Chef’s Forged German Stainless Steel Kitchen Knife Block Set (8-Piece)',
'condition': 'New',
'per-unit-volume': 0.28,
'currency': 'USD',
'volume-unit': 'cubic feet',
'country': 'US',
'qty-charged': 42,
'amount-charged': 485.10,
'surcharge-age-tier': '456+',
'rate-surcharge': 6.90
},
{
'snapshot-date': '2026-10-15T00:00:00+00:00',
'sku': 'CHEF-KNIFE-SET-8PC',
'fnsku': 'X001KNIFE8',
'asin': 'B08XYZ1001',
'product-name': 'Chef’s Forged German Stainless Steel Kitchen Knife Block Set (8-Piece)',
'condition': 'New',
'per-unit-volume': 0.28,
'currency': 'USD',
'volume-unit': 'cubic feet',
'country': 'US',
'qty-charged': 24,
'amount-charged': 148.20,
'surcharge-age-tier': '366-455',
'rate-surcharge': 5.45
},
{
'snapshot-date': '2026-10-15T00:00:00+00:00',
'sku': 'PARKA-WINTER-BLK-XL',
'fnsku': 'X002PARKA9',
'asin': 'B09LMN2002',
'product-name': 'Men’s Waterproof Thermal Down Winter Parka Coat — Obsidian Black (XL)',
'condition': 'No Listing',
'per-unit-volume': 0.52,
'currency': 'USD',
'volume-unit': 'cubic feet',
'country': 'US',
'qty-charged': 26,
'amount-charged': 372.40,
'surcharge-age-tier': '456+',
'rate-surcharge': 6.90
},
{
'snapshot-date': '2026-10-15T00:00:00+00:00',
'sku': 'CAMP-TENT-4P-INSTANT',
'fnsku': 'X005TENT4P',
'asin': 'B08WXY5005',
'product-name': '4-Person Waterproof Instant Cabin Tent with Reinforced Rainfly',
'condition': 'New',
'per-unit-volume': 1.15,
'currency': 'USD',
'volume-unit': 'cubic feet',
'country': 'US',
'qty-charged': 14,
'amount-charged': 289.65,
'surcharge-age-tier': '365+',
'rate-surcharge': 5.45
},
{
'snapshot-date': '2026-10-15T00:00:00+00:00',
'sku': 'ORTHO-DOGBED-XXL-GRY',
'fnsku': 'X008DOGBED',
'asin': 'B097898008',
'product-name': 'Orthopedic Cooling Gel Memory Foam Dog Sofa Bed — Slate Gray (XXL)',
'condition': 'New',
'per-unit-volume': 0.92,
'currency': 'USD',
'volume-unit': 'cubic feet',
'country': 'US',
'qty-charged': 18,
'amount-charged': 218.80,
'surcharge-age-tier': '331-365',
'rate-surcharge': 4.30
},
{
'snapshot-date': '2026-10-15T00:00:00+00:00',
'sku': 'YOGA-MAT-CORK-PRO',
'fnsku': 'X003YOGAMT',
'asin': 'B07QRS3003',
'product-name': 'Natural Cork & Rubber Non-Slip Alignment Yoga Mat (6mm Thick)',
'condition': 'New',
'per-unit-volume': 0.31,
'currency': 'USD',
'volume-unit': 'cubic feet',
'country': 'US',
'qty-charged': 56,
'amount-charged': 162.40,
'surcharge-age-tier': '301-330',
'rate-surcharge': 4.05
},
{
'snapshot-date': '2026-10-15T00:00:00+00:00',
'sku': 'USBC-DOCK-12IN1-ALU',
'fnsku': 'X006USBDOC',
'asin': 'B0B1236006',
'product-name': '12-in-1 Dual 4K HDMI USB-C Laptop Docking Station with 100W PD',
'condition': 'No Listing',
'per-unit-volume': 0.04,
'currency': 'USD',
'volume-unit': 'cubic feet',
'country': 'US',
'qty-charged': 110,
'amount-charged': 126.50,
'surcharge-age-tier': '271-300',
'rate-surcharge': 3.80
},
{
'snapshot-date': '2026-10-15T00:00:00+00:00',
'sku': 'LED-TASK-LAMP-QI',
'fnsku': 'X004LAMPQI',
'asin': 'B09TUV4004',
'product-name': 'Architect Clamp LED Desk Lamp with 15W Fast Wireless Charger',
'condition': 'New',
'per-unit-volume': 0.21,
'currency': 'USD',
'volume-unit': 'cubic feet',
'country': 'US',
'qty-charged': 48,
'amount-charged': 94.80,
'surcharge-age-tier': '241-270',
'rate-surcharge': 3.30
},
{
'snapshot-date': '2026-10-15T00:00:00+00:00',
'sku': 'ESPRESSO-TAMPER-58MM',
'fnsku': 'X009TAMPER',
'asin': 'B08ESP8008',
'product-name': 'Calibrated Spring-Loaded 58.5mm Stainless Steel Espresso Tamper',
'condition': 'New',
'per-unit-volume': 0.03,
'currency': 'USD',
'volume-unit': 'cubic feet',
'country': 'US',
'qty-charged': 135,
'amount-charged': 61.25,
'surcharge-age-tier': '211-240',
'rate-surcharge': 1.00
},
{
'snapshot-date': '2026-10-15T00:00:00+00:00',
'sku': 'PACKING-CUBES-6SET-NVY',
'fnsku': 'X010CUBES6',
'asin': 'B07TRV9009',
'product-name': 'Ultralight Compression Travel Packing Cubes Organizer (Set of 6, Navy)',
'condition': 'New',
'per-unit-volume': 0.08,
'currency': 'USD',
'volume-unit': 'cubic feet',
'country': 'US',
'qty-charged': 92,
'amount-charged': 46.00,
'surcharge-age-tier': '181-210',
'rate-surcharge': 0.50
},
// Canada Marketplace (CAD) rows
{
'snapshot-date': '2026-10-15T00:00:00+00:00',
'sku': 'PARKA-WINTER-BLK-XL-CA',
'fnsku': 'X002PARKCA',
'asin': 'B09LMN2002',
'product-name': 'Men’s Waterproof Thermal Down Winter Parka Coat — Obsidian Black (CA)',
'condition': 'No Listing',
'per-unit-volume': 0.015,
'currency': 'CAD',
'volume-unit': 'cubic meters',
'country': 'CA',
'qty-charged': 15,
'amount-charged': 184.50,
'surcharge-age-tier': '456+',
'rate-surcharge': 240.00
},
{
'snapshot-date': '2026-10-15T00:00:00+00:00',
'sku': 'YOGA-MAT-CORK-PRO-CA',
'fnsku': 'X003YOGACA',
'asin': 'B07QRS3003',
'product-name': 'Natural Cork & Rubber Non-Slip Alignment Yoga Mat (CA)',
'condition': 'New',
'per-unit-volume': 0.009,
'currency': 'CAD',
'volume-unit': 'cubic meters',
'country': 'CA',
'qty-charged': 32,
'amount-charged': 114.20,
'surcharge-age-tier': '366-455',
'rate-surcharge': 190.00
},
{
'snapshot-date': '2026-10-15T00:00:00+00:00',
'sku': 'LED-TASK-LAMP-QI-CA',
'fnsku': 'X004LAMPCA',
'asin': 'B09TUV4004',
'product-name': 'Architect Clamp LED Desk Lamp with 15W Fast Wireless Charger (CA)',
'condition': 'New',
'per-unit-volume': 0.006,
'currency': 'CAD',
'volume-unit': 'cubic meters',
'country': 'CA',
'qty-charged': 28,
'amount-charged': 56.80,
'surcharge-age-tier': '271-300',
'rate-surcharge': 125.00
},
{
'snapshot-date': '2026-10-15T00:00:00+00:00',
'sku': 'PACKING-CUBES-6SET-CA',
'fnsku': 'X010CUBECA',
'asin': 'B07TRV9009',
'product-name': 'Ultralight Compression Travel Packing Cubes Organizer (CA)',
'condition': 'New',
'per-unit-volume': 0.002,
'currency': 'CAD',
'volume-unit': 'cubic meters',
'country': 'CA',
'qty-charged': 50,
'amount-charged': 22.98,
'surcharge-age-tier': '301-330',
'rate-surcharge': 155.00
}
];
const validated = validateAndNormalizeRows(sample);
activateAgedDataset(
validated.rows,
'sample_aged_inventory_surcharge_US_CA.csv',
'Sample Dataset (UTF-8)'
);
}
function activateAgedDataset(rows, fileName, encodingLabel, suppressToast = false) {
state.ai.rawData = rows;
state.ai.fileName = fileName;
state.ai.encodingUsed = encodingLabel;
state.ai.filters = {
search: '',
country: 'ALL',
currency: 'ALL',
ageTier: 'ALL',
condition: 'ALL'
};
state.ai.tierChartCurrency = 'ALL';
state.ai.pagination.page = 1;
state.ai.sort = { column: 'amountCharged', direction: 'desc' };
dom.filterSearch.value = '';
const snapshotDates = [...new Set(rows.map(r => r.snapshotDate.split('T')[0]).filter(Boolean))].sort();
state.ai.snapshotLabel = snapshotDates.length === 1
? snapshotDates[0]
: snapshotDates.length > 1
? `${snapshotDates[0]} → ${snapshotDates[snapshotDates.length - 1]}`
: 'N/A';
// Pre-fill Share Period input with derived month/year
dom.sharePeriodInput.value = deriveFriendlyPeriodLabel(state.ai.snapshotLabel);
populateAiDropdowns();
// Update Metadata Badges
dom.aiMetaFilename.textContent = fileName;
dom.aiMetaSnapshot.textContent = `Snapshot: ${state.ai.snapshotLabel}`;
dom.kpiSnapshotPill.textContent = `Snapshot: ${state.ai.snapshotLabel}`;
dom.aiMetaEncoding.textContent = encodingLabel;
const currencies = [...new Set(rows.map(r => r.currency))].sort();
dom.aiMetaSummary.textContent = `${formatInt(rows.length)} rows loaded • Currencies: ${currencies.join(', ')}`;
// Show Dashboard & Header Badges
dom.aiUploadSection.classList.add('hidden');
dom.aiDashboardSection.classList.remove('hidden');
dom.btnCancelReupload.classList.remove('hidden');
if (!state.clientMode.active && state.activeToolId === 'aged-inventory') {
dom.btnShareClientTop.classList.remove('hidden');
dom.btnShareClientTop.classList.add('inline-flex');
dom.btnClearNewTop.classList.remove('hidden');
dom.btnClearNewTop.classList.add('inline-flex');
dom.topbarSnapshotBadge.textContent = `Snapshot: ${state.ai.snapshotLabel}`;
dom.topbarSnapshotBadge.classList.remove('hidden');
dom.topbarSnapshotBadge.classList.add('inline-flex');
}
renderAiAll();
if (!suppressToast) {
showToast(`Loaded ${formatInt(rows.length)} rows from ${fileName}`, 'success');
}
}
function clearLoadedReport() {
if (state.clientMode.active) return;
hideValidationError();
state.ai.rawData = [];
state.ai.fileName = '';
state.ai.snapshotLabel = '-';
if (state.ai.charts.ageTier) {
state.ai.charts.ageTier.destroy();
state.ai.charts.ageTier = null;
}
if (state.ai.charts.topSkus) {
state.ai.charts.topSkus.destroy();
state.ai.charts.topSkus = null;
}
dom.aiDashboardSection.classList.add('hidden');
dom.aiUploadSection.classList.remove('hidden');
dom.btnCancelReupload.classList.add('hidden');
dom.btnShareClientTop.classList.add('hidden');
dom.btnShareClientTop.classList.remove('inline-flex');
dom.btnClearNewTop.classList.add('hidden');
dom.btnClearNewTop.classList.remove('inline-flex');
dom.topbarSnapshotBadge.classList.add('hidden');
dom.topbarSnapshotBadge.classList.remove('inline-flex');
}
function populateAiDropdowns() {
const rows = state.ai.rawData;
// Country Dropdown
const countries = [...new Set(rows.map(r => r.country))].sort();
dom.filterCountry.innerHTML = `All Countries (${countries.length}) ` +
countries.map(c => `${escapeHtml(c)} `).join('');
dom.filterCountry.value = state.ai.filters.country;
// Currency Dropdown
const currencies = [...new Set(rows.map(r => r.currency))].sort();
dom.filterCurrency.innerHTML = `All Currencies (${currencies.length}) ` +
currencies.map(c => `${escapeHtml(c)} `).join('');
dom.filterCurrency.value = state.ai.filters.currency;
// Default Top SKU Chart Currency
const totalsByCurr = {};
rows.forEach(r => { totalsByCurr[r.currency] = (totalsByCurr[r.currency] || 0) + r.amountCharged; });
state.ai.topSkuCurrency = [...currencies].sort((a, b) => (totalsByCurr[b] || 0) - (totalsByCurr[a] || 0))[0] || 'USD';
// Chronological Age Tiers Dropdown
const tiers = sortAgeTiersChronologically([...new Set(rows.map(r => r.ageTier))]);
dom.filterAgeTier.innerHTML =
`All Age Tiers ` +
`365+ / 366-455 / 456+ Days ` +
tiers.map(t => `${escapeHtml(t)} days `).join('');
dom.filterAgeTier.value = state.ai.filters.ageTier;
// Condition Dropdown
const conditions = [...new Set(rows.map(r => r.condition))].sort();
const hasNonNew = conditions.some(isNonNewCondition);
const nonNewLabel = state.clientMode.active ? 'Unlisted / Action Needed' : 'Stranded / Non-New (≠ New)';
dom.filterCondition.innerHTML =
`All Conditions ` +
(hasNonNew ? `${escapeHtml(nonNewLabel)} ` : '') +
conditions.map(c => `${escapeHtml(c)} `).join('');
dom.filterCondition.value = state.ai.filters.condition;
}
function getFilteredAiRows() {
const { search, country, currency, ageTier, condition } = state.ai.filters;
const q = search.trim().toLowerCase();
return state.ai.rawData.filter(r => {
if (country !== 'ALL' && r.country !== country) return false;
if (currency !== 'ALL' && r.currency !== currency) return false;
if (ageTier === 'SEVERE_365') {
if (!isSevereAgedTier(r.ageTier)) return false;
} else if (ageTier !== 'ALL' && r.ageTier !== ageTier) {
return false;
}
if (condition === 'NON_NEW') {
if (!isNonNewCondition(r.condition)) return false;
} else if (condition !== 'ALL' && r.condition !== condition) {
return false;
}
if (q) {
const hay = `${r.sku} ${r.asin} ${r.fnsku} ${r.productName}`.toLowerCase();
if (!hay.includes(q)) return false;
}
return true;
});
}
function groupAiRowsBySku(rows) {
const map = new Map();
for (const r of rows) {
const key = `${r.sku}__${r.country}__${r.currency}`;
if (!map.has(key)) {
map.set(key, {
sku: r.sku,
asin: r.asin,
fnsku: r.fnsku,
productName: r.productName,
country: r.country,
currency: r.currency,
qtyCharged: 0,
amountCharged: 0,
totalVolume: 0,
volumeUnit: r.volumeUnit,
rates: [],
ageTiersSet: new Set(),
conditionsSet: new Set(),
rowCount: 0
});
}
const g = map.get(key);
g.qtyCharged += r.qtyCharged;
g.amountCharged += r.amountCharged;
g.totalVolume += r.totalRowVolume;
if (r.rateSurcharge > 0) g.rates.push(r.rateSurcharge);
g.ageTiersSet.add(r.ageTier);
g.conditionsSet.add(r.condition);
g.rowCount += 1;
}
return Array.from(map.values()).map(item => {
const sortedTiers = sortAgeTiersChronologically(Array.from(item.ageTiersSet));
const condList = Array.from(item.conditionsSet);
const maxRate = item.rates.length > 0 ? Math.max(...item.rates) : 0;
return {
...item,
ageTiers: sortedTiers,
ageTierText: sortedTiers.join(', '),
maxAgeTierOrder: Math.max(...sortedTiers.map(getAgeTierSortOrder)),
conditions: condList,
conditionText: condList.join(', '),
maxRate: maxRate
};
});
}
function sortAiDisplayRows(rows) {
const { column, direction } = state.ai.sort;
const mult = direction === 'asc' ? 1 : -1;
return [...rows].sort((a, b) => {
let valA, valB;
if (column === 'ageTier') {
valA = state.ai.viewMode === 'grouped' ? a.maxAgeTierOrder : getAgeTierSortOrder(a.ageTier);
valB = state.ai.viewMode === 'grouped' ? b.maxAgeTierOrder : getAgeTierSortOrder(b.ageTier);
} else if (column === 'condition') {
valA = state.ai.viewMode === 'grouped' ? a.conditionText : a.condition;
valB = state.ai.viewMode === 'grouped' ? b.conditionText : b.condition;
} else if (column === 'volume') {
valA = state.ai.viewMode === 'grouped' ? a.totalVolume : a.perUnitVolume;
valB = state.ai.viewMode === 'grouped' ? b.totalVolume : b.perUnitVolume;
} else if (column === 'rateSurcharge') {
valA = state.ai.viewMode === 'grouped' ? a.maxRate : a.rateSurcharge;
valB = state.ai.viewMode === 'grouped' ? b.maxRate : b.rateSurcharge;
} else {
valA = a[column];
valB = b[column];
}
if (typeof valA === 'number' && typeof valB === 'number') {
return (valA - valB) * mult;
}
return String(valA ?? '').localeCompare(String(valB ?? ''), 'en', { sensitivity: 'base' }) * mult;
});
}
/** Render strict per-currency breakdown stack (never summing across currencies) */
function buildPerCurrencyStackHtml(totalsMap, sizeClass = 'text-xl sm:text-2xl') {
const currencies = Object.keys(totalsMap).sort();
if (currencies.length === 0) {
const fallbackCurr = state.ai.filters.currency !== 'ALL' ? state.ai.filters.currency : 'USD';
return ``;
}
if (currencies.length === 1) {
const c = currencies[0];
return ``;
}
return currencies.map(c => `
`).join('');
}
function renderAiAll() {
const filteredRows = getFilteredAiRows();
renderFilterPills();
renderAiKpis(filteredRows);
renderAiCharts(filteredRows);
renderAiTable(filteredRows);
}
function renderFilterPills() {
const f = state.ai.filters;
const pills = [];
if (f.search.trim()) {
pills.push({ key: 'search', label: `Search: "${f.search.trim()}"` });
}
if (f.country !== 'ALL') {
pills.push({ key: 'country', label: `Country: ${f.country}` });
}
if (f.currency !== 'ALL') {
pills.push({ key: 'currency', label: `Currency: ${f.currency}` });
}
if (f.ageTier !== 'ALL') {
const tierLabel = f.ageTier === 'SEVERE_365' ? '365+ / 366-455 / 456+ Days' : `${f.ageTier} Days`;
pills.push({ key: 'ageTier', label: `Age Tier: ${tierLabel}` });
}
if (f.condition !== 'ALL') {
const condLabel = f.condition === 'NON_NEW'
? (state.clientMode.active ? 'Unlisted / Action Needed' : 'Condition ≠ New')
: f.condition;
pills.push({ key: 'condition', label: `Condition: ${condLabel}` });
}
if (pills.length === 0) {
dom.activeFiltersBar.classList.add('hidden');
dom.activeFiltersBar.classList.remove('flex');
dom.activeFilterPills.innerHTML = '';
return;
}
dom.activeFiltersBar.classList.remove('hidden');
dom.activeFiltersBar.classList.add('flex');
dom.activeFilterPills.innerHTML =
`Active Filters: ` +
pills.map(p => `
${escapeHtml(p.label)}
×
`).join('');
dom.activeFilterPills.querySelectorAll('button[data-remove-pill]').forEach(btn => {
btn.addEventListener('click', () => {
const key = btn.getAttribute('data-remove-pill');
if (key === 'search') {
state.ai.filters.search = '';
dom.filterSearch.value = '';
} else {
state.ai.filters[key] = 'ALL';
if (key === 'country') dom.filterCountry.value = 'ALL';
if (key === 'currency') dom.filterCurrency.value = 'ALL';
if (key === 'ageTier') dom.filterAgeTier.value = 'ALL';
if (key === 'condition') dom.filterCondition.value = 'ALL';
}
state.ai.pagination.page = 1;
renderAiAll();
});
});
}
function renderAiKpis(filteredRows) {
const totalByCurr = {};
let totalUnits = 0;
const distinctSkus = new Set();
const severe365ByCurr = {};
const severe365Skus = new Set();
let severe365Units = 0;
const nonNewByCurr = {};
const nonNewSkus = new Set();
let nonNewUnits = 0;
for (const r of filteredRows) {
totalByCurr[r.currency] = (totalByCurr[r.currency] || 0) + r.amountCharged;
totalUnits += r.qtyCharged;
distinctSkus.add(`${r.sku}__${r.country}`);
if (isSevereAgedTier(r.ageTier)) {
severe365ByCurr[r.currency] = (severe365ByCurr[r.currency] || 0) + r.amountCharged;
severe365Skus.add(`${r.sku}__${r.country}`);
severe365Units += r.qtyCharged;
}
if (isNonNewCondition(r.condition)) {
nonNewByCurr[r.currency] = (nonNewByCurr[r.currency] || 0) + r.amountCharged;
nonNewSkus.add(`${r.sku}__${r.country}`);
nonNewUnits += r.qtyCharged;
}
}
// KPI 1: Total Surcharge Charged
dom.kpiTotalSurcharge.innerHTML = buildPerCurrencyStackHtml(totalByCurr, 'text-2xl sm:text-3xl');
const currKeys = Object.keys(totalByCurr).sort();
if (currKeys.length === 1 && totalUnits > 0) {
const c = currKeys[0];
dom.kpiTotalSurchargeSub.textContent = `Avg ${formatMoney(totalByCurr[c] / totalUnits, c)} per charged unit`;
} else if (currKeys.length > 1) {
dom.kpiTotalSurchargeSub.textContent = `Separated across ${currKeys.join(' & ')} (never combined)`;
} else {
dom.kpiTotalSurchargeSub.textContent = 'No surcharge records in current filter';
}
// KPI 2: Total Units & Unique SKUs Charged
dom.kpiChargedUnits.textContent = formatInt(totalUnits);
dom.kpiAffectedSkus.textContent = `${formatInt(distinctSkus.size)} unique SKU${distinctSkus.size === 1 ? '' : 's'}`;
dom.kpiVolumeSub.textContent = `Across ${formatInt(filteredRows.length)} report record${filteredRows.length === 1 ? '' : 's'}`;
// KPI 3: 365+ Days Severe Aging Exposure
dom.kpi365Cost.innerHTML = buildPerCurrencyStackHtml(severe365ByCurr, 'text-xl sm:text-2xl');
dom.kpi365Sub.textContent = `${formatInt(severe365Units)} units across ${formatInt(severe365Skus.size)} SKU${severe365Skus.size === 1 ? '' : 's'}`;
// KPI 4: No Listing / Stranded Exposure
dom.kpiNoListingCost.innerHTML = buildPerCurrencyStackHtml(nonNewByCurr, 'text-xl sm:text-2xl');
dom.kpiNoListingSub.textContent = `${formatInt(nonNewUnits)} units across ${formatInt(nonNewSkus.size)} SKU${nonNewSkus.size === 1 ? '' : 's'}`;
}
function renderAiCharts(filteredRows) {
renderAgeTierBarChart(filteredRows);
renderTopSkusHorizontalChart(filteredRows);
}
function renderAgeTierBarChart(filteredRows) {
const availableCurrencies = [...new Set(filteredRows.map(r => r.currency))].sort();
// Currency selector on Age Tier chart when multiple currencies are present
if (availableCurrencies.length > 1) {
if (state.ai.tierChartCurrency !== 'ALL' && !availableCurrencies.includes(state.ai.tierChartCurrency)) {
state.ai.tierChartCurrency = 'ALL';
}
dom.tierChartCurrencySelect.classList.remove('hidden');
dom.chartTierCurrencies.classList.add('hidden');
dom.tierChartCurrencySelect.innerHTML =
`All (${availableCurrencies.join(' / ')}) ` +
availableCurrencies.map(c => `${escapeHtml(c)} Only `).join('');
} else {
dom.tierChartCurrencySelect.classList.add('hidden');
dom.chartTierCurrencies.classList.remove('hidden');
dom.chartTierCurrencies.textContent = availableCurrencies.length ? availableCurrencies[0] : 'No Data';
}
const chartRows = state.ai.tierChartCurrency !== 'ALL' && availableCurrencies.length > 1
? filteredRows.filter(r => r.currency === state.ai.tierChartCurrency)
: filteredRows;
const tiers = sortAgeTiersChronologically([...new Set(chartRows.map(r => r.ageTier))]);
const currencies = [...new Set(chartRows.map(r => r.currency))].sort();
const unitsLookup = {};
const amountLookup = {};
for (const r of chartRows) {
const k = `${r.ageTier}__${r.currency}`;
unitsLookup[k] = (unitsLookup[k] || 0) + r.qtyCharged;
amountLookup[k] = (amountLookup[k] || 0) + r.amountCharged;
}
const datasets = currencies.map((curr, idx) => {
const pal = getCurrencyPalette(curr, idx);
return {
label: curr,
data: tiers.map(tier => Number((amountLookup[`${tier}__${curr}`] || 0).toFixed(2))),
backgroundColor: pal.bg,
borderColor: pal.border,
borderWidth: 1,
borderRadius: 6,
maxBarThickness: 46
};
});
if (state.ai.charts.ageTier) {
state.ai.charts.ageTier.destroy();
}
state.ai.charts.ageTier = new Chart(dom.canvasAgeTier.getContext('2d'), {
type: 'bar',
data: {
labels: tiers,
datasets
},
options: {
responsive: true,
maintainAspectRatio: false,
onClick: (_evt, elements) => {
if (!elements || elements.length === 0) return;
const clickedTier = tiers[elements[0].index];
if (!clickedTier) return;
if (state.ai.filters.ageTier === clickedTier) {
state.ai.filters.ageTier = 'ALL';
dom.filterAgeTier.value = 'ALL';
showToast('Cleared age tier bar filter.', 'info');
} else {
state.ai.filters.ageTier = clickedTier;
dom.filterAgeTier.value = clickedTier;
showToast(`Filtered table to Age Tier: ${clickedTier} days`, 'info');
}
state.ai.pagination.page = 1;
renderAiAll();
},
onHover: (evt, chartEls) => {
if (evt.native && evt.native.target) {
evt.native.target.style.cursor = chartEls.length ? 'pointer' : 'default';
}
},
interaction: {
mode: 'index',
intersect: false
},
plugins: {
legend: {
display: currencies.length > 1,
position: 'top',
labels: {
usePointStyle: true,
boxWidth: 8,
font: { family: 'Inter', size: 12, weight: '600' }
}
},
tooltip: {
backgroundColor: '#0f172a',
titleFont: { family: 'Inter', size: 12, weight: '700' },
bodyFont: { family: 'Inter', size: 12 },
padding: 12,
cornerRadius: 8,
callbacks: {
title: (items) => `Age Tier: ${items[0].label} Days (Click to filter)`,
label: (ctx) => {
const tier = tiers[ctx.dataIndex];
const curr = ctx.dataset.label;
const units = unitsLookup[`${tier}__${curr}`] || 0;
return ` ${formatMoney(ctx.parsed.y, curr)} (${formatInt(units)} units)`;
}
}
}
},
scales: {
x: {
grid: { display: false },
ticks: { font: { family: 'Inter', size: 11, weight: '600' }, color: '#475569' }
},
y: {
beginAtZero: true,
grid: { color: '#f1f5f9' },
ticks: {
font: { family: 'Inter', size: 11 },
color: '#64748b',
callback: (val) => formatInt(val)
}
}
}
}
});
}
function renderTopSkusHorizontalChart(filteredRows) {
const availableCurrencies = [...new Set(filteredRows.map(r => r.currency))].sort();
if (availableCurrencies.length === 0) {
dom.topSkuCurrencySelect.innerHTML = `N/A `;
dom.topSkuCurrencySelect.disabled = true;
} else {
dom.topSkuCurrencySelect.disabled = availableCurrencies.length <= 1;
if (!availableCurrencies.includes(state.ai.topSkuCurrency)) {
state.ai.topSkuCurrency = availableCurrencies[0];
}
dom.topSkuCurrencySelect.innerHTML = availableCurrencies
.map(c => `${escapeHtml(c)} `)
.join('');
dom.topSkuCurrencySelect.value = state.ai.topSkuCurrency;
}
const activeCurr = state.ai.topSkuCurrency;
const currRows = filteredRows.filter(r => r.currency === activeCurr);
const top10 = groupAiRowsBySku(currRows)
.sort((a, b) => b.amountCharged - a.amountCharged)
.slice(0, 10);
const pal = getCurrencyPalette(activeCurr, 0);
const labels = top10.map(item => {
const shortSku = item.sku.length > 22 ? item.sku.slice(0, 20) + '…' : item.sku;
return `${shortSku} (${item.country})`;
});
if (state.ai.charts.topSkus) {
state.ai.charts.topSkus.destroy();
}
state.ai.charts.topSkus = new Chart(dom.canvasTopSkus.getContext('2d'), {
type: 'bar',
data: {
labels,
datasets: [{
label: `Surcharge (${activeCurr})`,
data: top10.map(g => Number(g.amountCharged.toFixed(2))),
backgroundColor: pal.bg,
borderColor: pal.border,
borderWidth: 1,
borderRadius: 6,
barThickness: 18
}]
},
options: {
indexAxis: 'y',
responsive: true,
maintainAspectRatio: false,
plugins: {
legend: { display: false },
tooltip: {
backgroundColor: '#0f172a',
titleFont: { family: 'Inter', size: 12, weight: '700' },
bodyFont: { family: 'Inter', size: 12 },
padding: 12,
cornerRadius: 8,
callbacks: {
title: (items) => {
const g = top10[items[0].dataIndex];
return `${g.sku} • ASIN: ${g.asin} (${g.country})`;
},
label: (ctx) => {
const g = top10[ctx.dataIndex];
const title = g.productName.length > 68 ? g.productName.slice(0, 68) + '…' : g.productName;
return [
`Product: ${title}`,
`Surcharge: ${formatMoney(g.amountCharged, g.currency)}`,
`Units Charged: ${formatInt(g.qtyCharged)}`,
`Age Tiers: ${g.ageTierText}`
];
}
}
}
},
scales: {
x: {
beginAtZero: true,
grid: { color: '#f1f5f9' },
ticks: {
font: { family: 'Inter', size: 11 },
color: '#64748b',
callback: (val) => formatInt(val)
}
},
y: {
grid: { display: false },
ticks: { font: { family: 'Inter', size: 11, weight: '600' }, color: '#334155' }
}
}
}
});
}
function getAiTableColumns() {
if (state.ai.viewMode === 'grouped') {
return [
{ key: 'sku', label: 'SKU / ASIN', align: 'left' },
{ key: 'productName', label: 'Product Name', align: 'left' },
{ key: 'country', label: 'Country', align: 'center' },
{ key: 'condition', label: 'Condition', align: 'left' },
{ key: 'ageTier', label: 'Age Tier(s)', align: 'left' },
{ key: 'qtyCharged', label: 'Units Charged', align: 'right' },
{ key: 'volume', label: 'Total Volume', align: 'right' },
{ key: 'amountCharged', label: 'Total Surcharge', align: 'right' }
];
}
return [
{ key: 'snapshotDate', label: 'Snapshot Date', align: 'left' },
{ key: 'sku', label: 'SKU / FNSKU', align: 'left' },
{ key: 'asin', label: 'ASIN', align: 'left' },
{ key: 'productName', label: 'Product Name', align: 'left' },
{ key: 'country', label: 'Country', align: 'center' },
{ key: 'condition', label: 'Condition', align: 'left' },
{ key: 'ageTier', label: 'Age Tier', align: 'left' },
{ key: 'volume', label: 'Unit Volume', align: 'right' },
{ key: 'qtyCharged', label: 'Units Charged', align: 'right' },
{ key: 'rateSurcharge', label: 'Rate', align: 'right' },
{ key: 'amountCharged', label: 'Amount Charged', align: 'right' }
];
}
function renderAsinLinkHtml(asin, country) {
const url = getAsinUrl(asin, country);
if (!url) return `- `;
return `${escapeHtml(asin)} `;
}
function renderAiTable(filteredRows) {
const baseRows = state.ai.viewMode === 'grouped'
? groupAiRowsBySku(filteredRows)
: filteredRows;
const sortedRows = sortAiDisplayRows(baseRows);
const total = sortedRows.length;
const pageSize = state.ai.pagination.pageSize;
const totalPages = Math.max(1, Math.ceil(total / pageSize));
if (state.ai.pagination.page > totalPages) {
state.ai.pagination.page = totalPages;
}
const start = (state.ai.pagination.page - 1) * pageSize;
const end = Math.min(start + pageSize, total);
const pageData = sortedRows.slice(start, end);
// Render Sortable Headers
const cols = getAiTableColumns();
dom.aiTableHead.innerHTML = `
${cols.map(col => {
const active = state.ai.sort.column === col.key;
const arrow = active ? (state.ai.sort.direction === 'asc' ? '▲' : '▼') : '⇅';
const alignCls = col.align === 'right' ? 'text-right' : col.align === 'center' ? 'text-center' : 'text-left';
return `
`;
}).join('')}
`;
dom.aiTableHead.querySelectorAll('th[data-sort-col]').forEach(th => {
th.addEventListener('click', () => {
const key = th.getAttribute('data-sort-col');
if (state.ai.sort.column === key) {
state.ai.sort.direction = state.ai.sort.direction === 'asc' ? 'desc' : 'asc';
} else {
state.ai.sort.column = key;
state.ai.sort.direction = ['qtyCharged', 'volume', 'amountCharged', 'rateSurcharge', 'ageTier'].includes(key) ? 'desc' : 'asc';
}
state.ai.pagination.page = 1;
renderAiTable(getFilteredAiRows());
});
});
if (total === 0) {
dom.aiTableBody.innerHTML = '';
dom.aiTableEmpty.classList.remove('hidden');
} else {
dom.aiTableEmpty.classList.add('hidden');
if (state.ai.viewMode === 'grouped') {
dom.aiTableBody.innerHTML = pageData.map(r => `
${escapeHtml(r.sku)}
${renderAsinLinkHtml(r.asin, r.country)}
${r.rowCount > 1 ? `(${r.rowCount} tiers) ` : ''}
${escapeHtml(r.productName)}
FNSKU: ${escapeHtml(r.fnsku)}
${escapeHtml(r.country)}
${r.conditions.map(renderConditionBadge).join('')}
${r.ageTiers.map(renderAgeTierBadge).join('')}
${formatInt(r.qtyCharged)}
${formatDec(r.totalVolume, 2)}
${escapeHtml(r.volumeUnit)}
`).join('');
} else {
dom.aiTableBody.innerHTML = pageData.map(r => `
${escapeHtml(r.snapshotDate.split('T')[0] || '-')}
${escapeHtml(r.sku)}
FNSKU: ${escapeHtml(r.fnsku)}
${renderAsinLinkHtml(r.asin, r.country)}
${escapeHtml(r.productName)}
${escapeHtml(r.country)}
${renderConditionBadge(r.condition)}
${renderAgeTierBadge(r.ageTier)}
${formatDec(r.perUnitVolume, 3)}
${escapeHtml(r.volumeUnit)}
${formatInt(r.qtyCharged)}
${formatDec(r.rateSurcharge, 2)}
`).join('');
}
}
dom.aiPaginationSummary.textContent = total === 0
? 'Showing 0 results'
: `Showing ${formatInt(start + 1)}–${formatInt(end)} of ${formatInt(total)} ${state.ai.viewMode === 'grouped' ? 'grouped SKUs' : 'raw rows'}`;
dom.aiPageIndicator.textContent = `Page ${state.ai.pagination.page} of ${totalPages}`;
dom.btnPagePrev.disabled = state.ai.pagination.page <= 1;
dom.btnPageNext.disabled = state.ai.pagination.page >= totalPages;
}
// =======================================================================
// CLEAN ENGLISH EXPORTS (CSV & EXCEL .XLSX)
// =======================================================================
function buildExportRecords() {
const filtered = getFilteredAiRows();
const base = state.ai.viewMode === 'grouped' ? groupAiRowsBySku(filtered) : filtered;
const sorted = sortAiDisplayRows(base);
if (state.ai.viewMode === 'grouped') {
return sorted.map(r => ({
'SKU': r.sku,
'ASIN': r.asin,
'FNSKU': r.fnsku,
'Product Name': r.productName,
'Country': r.country,
'Currency': r.currency,
'Condition(s)': r.conditionText,
'Age Tier(s)': r.ageTierText,
'Units Charged': r.qtyCharged,
'Total Volume': Number(r.totalVolume.toFixed(4)),
'Volume Unit': r.volumeUnit,
'Total Surcharge Charged': Number(r.amountCharged.toFixed(2)),
'Amazon Listing URL': getAsinUrl(r.asin, r.country) || ''
}));
}
return sorted.map(r => ({
'Snapshot Date': r.snapshotDate.split('T')[0] || r.snapshotDate,
'SKU': r.sku,
'FNSKU': r.fnsku,
'ASIN': r.asin,
'Product Name': r.productName,
'Condition': r.condition,
'Country': r.country,
'Currency': r.currency,
'Surcharge Age Tier': r.ageTier,
'Per-Unit Volume': r.perUnitVolume,
'Volume Unit': r.volumeUnit,
'Units Charged': r.qtyCharged,
'Rate Surcharge': r.rateSurcharge,
'Amount Charged': Number(r.amountCharged.toFixed(2)),
'Amazon Listing URL': getAsinUrl(r.asin, r.country) || ''
}));
}
function exportFilteredCsv() {
const records = buildExportRecords();
if (records.length === 0) {
showToast('No filtered rows available to export.', 'warning');
return;
}
const csv = Papa.unparse(records);
const blob = new Blob(['\uFEFF' + csv], { type: 'text/csv;charset=utf-8;' });
const url = URL.createObjectURL(blob);
const link = document.createElement('a');
const suffix = state.ai.viewMode === 'grouped' ? 'grouped_by_sku' : 'raw_rows';
link.href = url;
link.download = `aged_inventory_surcharge_${suffix}_${new Date().toISOString().slice(0, 10)}.csv`;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
URL.revokeObjectURL(url);
showToast(`Exported ${formatInt(records.length)} rows to CSV.`, 'success');
}
function exportFilteredXlsx() {
const records = buildExportRecords();
if (records.length === 0) {
showToast('No filtered rows available to export.', 'warning');
return;
}
try {
const ws = XLSX.utils.json_to_sheet(records);
const wb = XLSX.utils.book_new();
const sheetTitle = state.ai.viewMode === 'grouped' ? 'Grouped by SKU' : 'Raw Rows';
XLSX.utils.book_append_sheet(wb, ws, sheetTitle);
const suffix = state.ai.viewMode === 'grouped' ? 'grouped_by_sku' : 'raw_rows';
XLSX.writeFile(wb, `aged_inventory_surcharge_${suffix}_${new Date().toISOString().slice(0, 10)}.xlsx`);
showToast(`Exported ${formatInt(records.length)} rows to Excel (.xlsx).`, 'success');
} catch (err) {
console.error(err);
showToast('Failed to generate Excel workbook.', 'error');
}
}
function resetAllAiFilters() {
state.ai.filters = {
search: '',
country: 'ALL',
currency: 'ALL',
ageTier: 'ALL',
condition: 'ALL'
};
dom.filterSearch.value = '';
dom.filterCountry.value = 'ALL';
dom.filterCurrency.value = 'ALL';
dom.filterAgeTier.value = 'ALL';
dom.filterCondition.value = 'ALL';
state.ai.pagination.page = 1;
renderAiAll();
}
// =======================================================================
// EVENT LISTENERS & INITIALIZATION
// =======================================================================
dom.btnToggleSidebar.addEventListener('click', toggleSidebar);
dom.btnCloseMobileSidebar.addEventListener('click', closeMobileSidebar);
dom.sidebarBackdrop.addEventListener('click', closeMobileSidebar);
dom.brandHomeBtn.addEventListener('click', () => selectTool('overview'));
dom.btnGotoOverview.addEventListener('click', () => selectTool('overview'));
dom.btnFallbackBack.addEventListener('click', () => selectTool('overview'));
dom.btnSoonOverview.addEventListener('click', () => selectTool('overview'));
dom.btnSoonOpenAged.addEventListener('click', () => selectTool('aged-inventory'));
dom.btnCloseError.addEventListener('click', hideValidationError);
// Seller Central Instructions Collapsible Toggle
dom.btnToggleScInstructions.addEventListener('click', () => {
state.scInstructionsOpen = !state.scInstructionsOpen;
dom.scInstructionsBody.classList.toggle('hidden', !state.scInstructionsOpen);
dom.scInstructionsChevron.classList.toggle('rotate-180', !state.scInstructionsOpen);
dom.scInstructionsToggleLabel.textContent = state.scInstructionsOpen ? 'Hide Steps' : 'Show Steps';
});
// Share Modal Listeners
dom.btnShareClientTop.addEventListener('click', openShareModal);
dom.btnShareClientInline.addEventListener('click', openShareModal);
dom.btnCloseShareModal.addEventListener('click', closeShareModal);
dom.btnDoneShareModal.addEventListener('click', closeShareModal);
dom.shareModalBackdrop.addEventListener('click', closeShareModal);
['input', 'change'].forEach(evt => {
dom.shareBrandInput.addEventListener(evt, refreshShareModalOutputs);
dom.sharePeriodInput.addEventListener(evt, refreshShareModalOutputs);
dom.shareNoteInput.addEventListener(evt, refreshShareModalOutputs);
});
dom.btnScopeAll.addEventListener('click', () => {
state.share.scope = 'all';
dom.btnScopeAll.className = 'px-3 py-1.5 rounded-lg text-xs font-bold bg-white text-slate-900 shadow-xs transition-all cursor-pointer';
dom.btnScopeFiltered.className = 'px-3 py-1.5 rounded-lg text-xs font-semibold text-slate-600 hover:text-slate-900 transition-all cursor-pointer';
refreshShareModalOutputs();
});
dom.btnScopeFiltered.addEventListener('click', () => {
if (getFilteredAiRows().length === 0) {
showToast('Filtered view is currently empty.', 'warning');
return;
}
state.share.scope = 'filtered';
dom.btnScopeFiltered.className = 'px-3 py-1.5 rounded-lg text-xs font-bold bg-white text-slate-900 shadow-xs transition-all cursor-pointer';
dom.btnScopeAll.className = 'px-3 py-1.5 rounded-lg text-xs font-semibold text-slate-600 hover:text-slate-900 transition-all cursor-pointer';
refreshShareModalOutputs();
});
dom.btnCopyShareUrl.addEventListener('click', () => {
refreshShareModalOutputs();
copyTextToClipboard(state.share.fullUrl, 'Client Share URL copied to clipboard!');
});
dom.btnCopyTop150Url.addEventListener('click', () => {
if (state.share.top150Url) {
copyTextToClipboard(state.share.top150Url, 'Top-150 SKU Summary Client URL copied!');
}
});
dom.btnDownloadClientHtml.addEventListener('click', downloadStandaloneClientHtml);
dom.btnPreviewClientMode.addEventListener('click', () => {
const sourceRows = getShareSourceRows();
if (sourceRows.length === 0) {
showToast('No rows available to preview.', 'warning');
return;
}
// Backup full internal dataset so user can exit preview seamlessly
state.clientMode.backupInternalRows = [...state.ai.rawData];
state.clientMode.backupFileName = state.ai.fileName;
state.clientMode.backupEncoding = state.ai.encodingUsed;
state.clientMode.backupSnapshot = state.ai.snapshotLabel;
const payload = buildCompactClientPayload(sourceRows, {
brand: dom.shareBrandInput.value || '',
period: dom.sharePeriodInput.value || deriveFriendlyPeriodLabel(state.ai.snapshotLabel),
note: dom.shareNoteInput.value || ''
});
const expanded = expandCompactClientPayload(payload);
closeShareModal();
enterClientPresentationMode(expanded, true);
showToast('Switched to Client Presentation Preview.', 'info');
});
dom.btnExitClientPreview.addEventListener('click', exitLocalClientPreview);
dom.sidebarSearch.addEventListener('input', (e) => {
state.sidebarSearch = e.target.value;
renderSidebar();
});
dom.btnReloadIframe.addEventListener('click', () => {
const tool = TOOLS_CONFIG.find(t => t.id === state.activeToolId);
if (tool && tool.path) {
loadExternalToolFrame(tool);
showToast(`Reloaded ${tool.name}`, 'info');
}
});
dom.btnToggleDevGuide.addEventListener('click', () => {
state.devGuideOpen = !state.devGuideOpen;
dom.devGuideBody.classList.toggle('hidden', !state.devGuideOpen);
dom.devGuideChevron.classList.toggle('rotate-180', !state.devGuideOpen);
});
dom.btnCopyConfigSnippet.addEventListener('click', () => {
copyTextToClipboard(dom.configSnippetCode.textContent, 'TOOLS_CONFIG snippet copied!');
});
// Drag & Drop + File Input
['dragenter', 'dragover'].forEach(evtName => {
dom.aiDropZone.addEventListener(evtName, (e) => {
e.preventDefault();
e.stopPropagation();
dom.aiDropZone.classList.add('border-hub-amber', 'bg-amber-50/50');
});
});
['dragleave', 'drop'].forEach(evtName => {
dom.aiDropZone.addEventListener(evtName, (e) => {
e.preventDefault();
e.stopPropagation();
dom.aiDropZone.classList.remove('border-hub-amber', 'bg-amber-50/50');
});
});
dom.aiDropZone.addEventListener('drop', (e) => {
const files = e.dataTransfer?.files;
if (files && files.length > 0) {
handleAgedInventoryFile(files[0]);
}
});
dom.aiFileInput.addEventListener('change', (e) => {
if (e.target.files && e.target.files.length > 0) {
handleAgedInventoryFile(e.target.files[0]);
e.target.value = '';
}
});
dom.btnLoadSample.addEventListener('click', loadSampleData);
dom.btnClearNewTop.addEventListener('click', clearLoadedReport);
dom.btnClearFileInline.addEventListener('click', clearLoadedReport);
dom.btnCancelReupload.addEventListener('click', () => {
hideValidationError();
dom.aiUploadSection.classList.add('hidden');
dom.aiDashboardSection.classList.remove('hidden');
});
// Interactive Filters
let searchDebounce = null;
dom.filterSearch.addEventListener('input', (e) => {
clearTimeout(searchDebounce);
searchDebounce = setTimeout(() => {
state.ai.filters.search = e.target.value;
state.ai.pagination.page = 1;
renderAiAll();
}, 150);
});
dom.filterCountry.addEventListener('change', (e) => {
state.ai.filters.country = e.target.value;
state.ai.pagination.page = 1;
renderAiAll();
});
dom.filterCurrency.addEventListener('change', (e) => {
state.ai.filters.currency = e.target.value;
if (e.target.value !== 'ALL') {
state.ai.topSkuCurrency = e.target.value;
state.ai.tierChartCurrency = e.target.value;
} else {
state.ai.tierChartCurrency = 'ALL';
}
state.ai.pagination.page = 1;
renderAiAll();
});
dom.filterAgeTier.addEventListener('change', (e) => {
state.ai.filters.ageTier = e.target.value;
state.ai.pagination.page = 1;
renderAiAll();
});
dom.filterCondition.addEventListener('change', (e) => {
state.ai.filters.condition = e.target.value;
state.ai.pagination.page = 1;
renderAiAll();
});
// Quick Action KPI Filter Buttons
dom.btnFilter365.addEventListener('click', () => {
if (state.ai.filters.ageTier === 'SEVERE_365') {
state.ai.filters.ageTier = 'ALL';
dom.filterAgeTier.value = 'ALL';
showToast('Cleared 365+ days quick filter.', 'info');
} else {
state.ai.filters.ageTier = 'SEVERE_365';
dom.filterAgeTier.value = 'SEVERE_365';
showToast('Filtered to 365+ / 366-455 / 456+ days inventory.', 'info');
}
state.ai.pagination.page = 1;
renderAiAll();
});
dom.btnFilterNoListing.addEventListener('click', () => {
const noListingOpt = Array.from(dom.filterCondition.options).find(
o => o.value.toLowerCase() === 'no listing'
);
const nonNewOpt = Array.from(dom.filterCondition.options).find(
o => o.value === 'NON_NEW'
);
const targetVal = noListingOpt ? noListingOpt.value : (nonNewOpt ? 'NON_NEW' : null);
if (!targetVal) {
showToast('All items in this report are in active "New" condition!', 'success');
return;
}
if (state.ai.filters.condition === targetVal) {
state.ai.filters.condition = 'ALL';
dom.filterCondition.value = 'ALL';
showToast('Cleared filter.', 'info');
} else {
state.ai.filters.condition = targetVal;
dom.filterCondition.value = targetVal;
showToast(
state.clientMode.active
? 'Filtered to Unlisted / Action Needed SKUs.'
: 'Filtered to Stranded / No Listing inventory.',
'info'
);
}
state.ai.pagination.page = 1;
renderAiAll();
});
dom.btnResetAllFilters.addEventListener('click', resetAllAiFilters);
dom.btnPillsReset.addEventListener('click', resetAllAiFilters);
dom.btnEmptyClearFilters.addEventListener('click', resetAllAiFilters);
// Chart Currency Selectors
dom.tierChartCurrencySelect.addEventListener('change', (e) => {
state.ai.tierChartCurrency = e.target.value;
renderAgeTierBarChart(getFilteredAiRows());
});
dom.topSkuCurrencySelect.addEventListener('change', (e) => {
state.ai.topSkuCurrency = e.target.value;
renderTopSkusHorizontalChart(getFilteredAiRows());
});
// View Mode Toggle (Grouped by SKU vs Raw Rows)
function setAiViewMode(mode) {
state.ai.viewMode = mode;
state.ai.pagination.page = 1;
if (mode === 'grouped') {
dom.btnModeGrouped.className = 'px-3.5 py-1.5 rounded-lg text-xs sm:text-sm font-semibold transition-all bg-white text-slate-900 shadow-xs cursor-pointer';
dom.btnModeDetailed.className = 'px-3.5 py-1.5 rounded-lg text-xs sm:text-sm font-semibold transition-all text-slate-600 hover:text-slate-900 cursor-pointer';
dom.tableModeHint.textContent = 'Aggregated per SKU + Country + Currency';
} else {
dom.btnModeDetailed.className = 'px-3.5 py-1.5 rounded-lg text-xs sm:text-sm font-semibold transition-all bg-white text-slate-900 shadow-xs cursor-pointer';
dom.btnModeGrouped.className = 'px-3.5 py-1.5 rounded-lg text-xs sm:text-sm font-semibold transition-all text-slate-600 hover:text-slate-900 cursor-pointer';
dom.tableModeHint.textContent = 'Showing all individual report rows';
}
renderAiTable(getFilteredAiRows());
}
dom.btnModeGrouped.addEventListener('click', () => setAiViewMode('grouped'));
dom.btnModeDetailed.addEventListener('click', () => setAiViewMode('detailed'));
// Pagination
dom.aiPageSize.addEventListener('change', (e) => {
state.ai.pagination.pageSize = parseInt(e.target.value, 10) || 25;
state.ai.pagination.page = 1;
renderAiTable(getFilteredAiRows());
});
dom.btnPagePrev.addEventListener('click', () => {
if (state.ai.pagination.page > 1) {
state.ai.pagination.page -= 1;
renderAiTable(getFilteredAiRows());
}
});
dom.btnPageNext.addEventListener('click', () => {
state.ai.pagination.page += 1;
renderAiTable(getFilteredAiRows());
});
// Exports (Internal & Client Header buttons)
dom.btnExportCsv.addEventListener('click', exportFilteredCsv);
dom.btnExportXlsx.addEventListener('click', exportFilteredXlsx);
dom.btnClientExportCsv.addEventListener('click', exportFilteredCsv);
dom.btnClientExportXlsx.addEventListener('click', exportFilteredXlsx);
// Try parsing #client=... hash or window.__PRELOADED_CLIENT_DATA__
function tryLoadClientModeFromSource() {
// 1. Check standalone preloaded HTML snapshot first
if (window.__PRELOADED_CLIENT_DATA__ && typeof window.__PRELOADED_CLIENT_DATA__ === 'object') {
const expanded = expandCompactClientPayload(window.__PRELOADED_CLIENT_DATA__);
if (expanded && expanded.rows.length > 0) {
enterClientPresentationMode(expanded, false);
return true;
}
}
// 2. Check URL hash (#client=...)
const hash = window.location.hash || '';
if (hash.startsWith('#client=')) {
const encoded = hash.slice('#client='.length).trim();
if (encoded) {
try {
const jsonStr = window.LZString
? window.LZString.decompressFromEncodedURIComponent(encoded)
: decodeURIComponent(encoded);
if (jsonStr) {
const parsed = JSON.parse(jsonStr);
const expanded = expandCompactClientPayload(parsed);
if (expanded && expanded.rows.length > 0) {
enterClientPresentationMode(expanded, false);
return true;
}
}
} catch (err) {
console.error('Failed to decode #client share link:', err);
showToast('Could not decode client share link — opening standard workspace.', 'error');
}
}
}
return false;
}
// Initialize Hub (Supports direct hash changes for #client=... links too)
function initHub() {
if (tryLoadClientModeFromSource()) {
return;
}
applyClientModeUI(false);
const hashId = (window.location.hash || '').replace('#', '').trim();
const matchingTool = TOOLS_CONFIG.find(t => t.id === hashId);
selectTool(matchingTool ? matchingTool.id : 'aged-inventory');
}
window.addEventListener('hashchange', () => {
if ((window.location.hash || '').startsWith('#client=')) {
tryLoadClientModeFromSource();
}
});
initHub();
})();