Initial
Takes in a file, process it and output a new file with additional columns.
This commit is contained in:
@@ -0,0 +1,826 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
$latestBatchRowCount = (int) ($latestBatchRowCount ?? 0);
|
||||
$hasData = $latestBatch !== null && $latestBatchRowCount > 0;
|
||||
|
||||
function h(mixed $value): string
|
||||
{
|
||||
return htmlspecialchars((string) ($value ?? ''), ENT_QUOTES, 'UTF-8');
|
||||
}
|
||||
|
||||
function flashClasses(?array $flash): string
|
||||
{
|
||||
$type = (string) ($flash['type'] ?? 'info');
|
||||
|
||||
return match ($type) {
|
||||
'success' => 'border-emerald-200 bg-emerald-50 text-emerald-900',
|
||||
'danger' => 'border-rose-200 bg-rose-50 text-rose-900',
|
||||
'warning' => 'border-amber-200 bg-amber-50 text-amber-900',
|
||||
default => 'border-sky-200 bg-sky-50 text-sky-900',
|
||||
};
|
||||
}
|
||||
?>
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<title><?= h($appName) ?></title>
|
||||
<link rel="preconnect" href="https://fonts.googleapis.com">
|
||||
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
|
||||
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800&display=swap" rel="stylesheet">
|
||||
<script>
|
||||
tailwind = {
|
||||
config: {
|
||||
theme: {
|
||||
extend: {
|
||||
fontFamily: {
|
||||
sans: ['Inter', 'ui-sans-serif', 'system-ui'],
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
};
|
||||
</script>
|
||||
<script src="https://cdn.tailwindcss.com"></script>
|
||||
<link href="https://cdn.jsdelivr.net/npm/ag-grid-community/styles/ag-theme-quartz.css" rel="stylesheet">
|
||||
<link href="<?= h(asset_url('styles.css')) ?>" rel="stylesheet">
|
||||
<style>
|
||||
.cell-flag-positive { background-color: #dcfce7; color: #166534; font-weight: 600; }
|
||||
.cell-flag-negative { background-color: #fee2e2; color: #991b1b; font-weight: 600; }
|
||||
|
||||
.pin-toggle-btn {
|
||||
display: inline-flex; align-items: center; justify-content: center;
|
||||
width: 28px; height: 28px; border-radius: 4px; border: 1px solid transparent;
|
||||
color: #94a3b8; background: transparent; cursor: pointer; transition: all .12s ease;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
.pin-toggle-btn:hover { background: #f1f5f9; color: #475569; }
|
||||
.pin-toggle-btn.is-pinned { color: #fff; background: #0284c7; }
|
||||
.pin-toggle-btn.is-pinned:hover { background: #0369a1; }
|
||||
|
||||
.pinnable-header {
|
||||
display: flex; align-items: center; justify-content: space-between;
|
||||
width: 100%; gap: 6px;
|
||||
}
|
||||
.pinnable-header__label {
|
||||
overflow: hidden; text-overflow: ellipsis; white-space: break-spaces;
|
||||
cursor: pointer; min-width: 0;
|
||||
}
|
||||
.pinnable-header__buttons {
|
||||
display: flex; align-items: center; gap: 2px; flex-shrink: 0;
|
||||
}
|
||||
.pin-toggle-btn--header { width: 22px; height: 22px; }
|
||||
.pin-toggle-btn--header svg { width: 11px; height: 11px; }
|
||||
.filter-toggle-btn.is-active { color: #fff; background: #f59e0b; }
|
||||
.filter-toggle-btn.is-active:hover { background: #d97706; }
|
||||
|
||||
#blurToggleButton.is-active { border-color: transparent; background: #0f172a; color: #fff; }
|
||||
#blurToggleButton.is-active:hover { background: #1e293b; }
|
||||
|
||||
#fullDataGrid.is-privacy-blurred { filter: blur(7px); transition: filter .15s ease; }
|
||||
|
||||
.excel-filter { display: flex; flex-direction: column; width: 240px; padding: 10px; gap: 8px; font-family: inherit; }
|
||||
.excel-filter__search-input {
|
||||
width: 100%; box-sizing: border-box; border: 1px solid #e2e8f0; border-radius: 8px;
|
||||
padding: 6px 10px; font-size: 13px; outline: none;
|
||||
}
|
||||
.excel-filter__search-input:focus { border-color: #38bdf8; box-shadow: 0 0 0 3px rgba(56,189,248,.15); }
|
||||
.excel-filter__actions { display: flex; justify-content: space-between; }
|
||||
.excel-filter__link { background: none; border: none; color: #0284c7; font-size: 12px; font-weight: 600; cursor: pointer; padding: 0; }
|
||||
.excel-filter__link:hover { text-decoration: underline; }
|
||||
.excel-filter__list { max-height: 220px; overflow-y: auto; border: 1px solid #e2e8f0; border-radius: 8px; padding: 4px; }
|
||||
.excel-filter__item { display: flex; align-items: center; gap: 8px; padding: 4px 6px; font-size: 13px; border-radius: 6px; cursor: pointer; }
|
||||
.excel-filter__item:hover { background: #f8fafc; }
|
||||
.excel-filter__loading { padding: 8px 6px; font-size: 12px; color: #94a3b8; }
|
||||
.excel-filter__footer { display: flex; justify-content: flex-end; }
|
||||
.excel-filter__apply {
|
||||
background: #0284c7; color: #fff; border: none; border-radius: 8px;
|
||||
padding: 6px 14px; font-size: 13px; font-weight: 600; cursor: pointer;
|
||||
}
|
||||
.excel-filter__apply:hover { background: #0369a1; }
|
||||
</style>
|
||||
</head>
|
||||
<body class="datatable-page min-h-screen bg-slate-100 text-slate-900 antialiased">
|
||||
<div class="app-shell">
|
||||
<?php require __DIR__ . '/partials/navbar.php'; ?>
|
||||
|
||||
<div class="hidden mx-auto max-w-7xl px-4 py-4 lg:px-8 lg:py-6">
|
||||
<section class="mb-4 overflow-hidden rounded-md border border-white/70 bg-white/90 shadow-[0_24px_80px_rgba(15,23,42,0.08)] backdrop-blur">
|
||||
<div class="p-6 sm:p-8 lg:p-10">
|
||||
<div class="flex flex-col gap-8 lg:flex-row lg:items-end lg:justify-between">
|
||||
<div class="max-w-3xl">
|
||||
<span class="inline-flex items-center rounded-md bg-slate-900 px-3 py-1 text-xs font-semibold uppercase tracking-[0.2em] text-white">AG Grid</span>
|
||||
<h1 class="mt-4 text-4xl font-semibold tracking-tight sm:text-5xl"><?= h($appName) ?></h1>
|
||||
<p class="mt-4 max-w-2xl text-base leading-7 text-slate-600 sm:text-lg">
|
||||
Browse the latest imported batch with server-side search, sorting, and column filters.
|
||||
</p>
|
||||
</div>
|
||||
<div class="rounded-md border border-slate-200/80 bg-slate-50/80 px-6 py-5 text-left lg:min-w-72 lg:text-right">
|
||||
<div class="text-xs font-semibold uppercase tracking-[0.24em] text-slate-500">Rows in latest batch</div>
|
||||
<div class="mt-2 text-5xl font-semibold tracking-tight text-slate-900"><?= number_format($latestBatchRowCount) ?></div>
|
||||
<div class="mt-2 text-sm text-slate-500">Rows are loaded from the server only as needed.</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<?php if ($flash !== null): ?>
|
||||
<div class="mb-4 rounded-md border px-4 py-3 text-sm font-medium shadow-sm <?= h(flashClasses($flash)) ?>">
|
||||
<?= h($flash['message'] ?? '') ?>
|
||||
</div>
|
||||
<?php endif; ?>
|
||||
</div>
|
||||
|
||||
<div class="mx-auto max-w-full px-2 py-6">
|
||||
<div class="hidden mb-4 flex flex-col gap-3 xl:flex-row xl:items-center xl:justify-between">
|
||||
<div>
|
||||
<h2 class="hidden text-2xl font-semibold tracking-tight">Imported data</h2>
|
||||
<p class="hidden mt-2 text-sm leading-6 text-slate-500">
|
||||
<?= $hasData ? 'AG Grid streams rows from the server and applies column filters without loading the whole batch into memory.' : 'No imported data yet. Upload a workbook to populate the grid.' ?>
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
||||
<?php if ($hasData): ?>
|
||||
<div class="mb-4 flex flex-col gap-3 lg:flex-row lg:items-center lg:justify-between">
|
||||
<div class="flex flex-col gap-2 md:flex-row md:items-center">
|
||||
<div class="flex min-w-0 items-center overflow-hidden rounded-md border border-slate-200 bg-white shadow-sm">
|
||||
<span class="px-4 py-2 text-sm font-semibold text-slate-500">Search</span>
|
||||
<input
|
||||
id="tableSearchInput"
|
||||
type="search"
|
||||
class="w-full min-w-0 border-0 bg-transparent px-0 py-2 pr-4 text-sm text-slate-700 outline-none placeholder:text-slate-400"
|
||||
placeholder="Search imported rows"
|
||||
autocomplete="off"
|
||||
>
|
||||
</div>
|
||||
|
||||
<div class="relative">
|
||||
<button
|
||||
class="inline-flex items-center rounded-md border border-slate-200 bg-white px-4 py-2 text-sm font-semibold text-slate-700 shadow-sm transition hover:bg-slate-50"
|
||||
type="button"
|
||||
id="columnVisibilityButton"
|
||||
aria-expanded="false"
|
||||
>
|
||||
Columns
|
||||
</button>
|
||||
|
||||
<div
|
||||
id="columnVisibilityMenu"
|
||||
class="invisible absolute left-0 z-20 mt-2 w-80 rounded-md border border-slate-200 bg-white p-4 opacity-0 shadow-[0_20px_60px_rgba(15,23,42,0.12)] transition duration-150"
|
||||
>
|
||||
<div class="mb-3">
|
||||
<input
|
||||
id="columnVisibilitySearch"
|
||||
type="search"
|
||||
class="w-full rounded-md border border-slate-200 bg-slate-50 px-4 py-2 text-sm outline-none placeholder:text-slate-400 focus:border-sky-400 focus:ring-4 focus:ring-sky-100"
|
||||
placeholder="Filter columns"
|
||||
autocomplete="off"
|
||||
>
|
||||
</div>
|
||||
<div id="columnVisibilityItems" class="max-h-96 space-y-1 overflow-y-auto pr-1"></div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
||||
<div class="flex flex-col items-start gap-2 lg:items-end">
|
||||
<div class="flex items-center gap-4 text-xs font-medium text-slate-500">
|
||||
<span class="flex items-center gap-1.5"><span class="h-2.5 w-2.5 rounded-md bg-emerald-200"></span>Y / N<span class="h-2.5 w-2.5 rounded-md bg-rose-200"></span></span>
|
||||
<span class="flex items-center gap-1.5"><span class="h-2.5 w-2.5 rounded-md bg-emerald-200"></span>F / D<span class="h-2.5 w-2.5 rounded-md bg-rose-200"></span></span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div id="fullDataGrid" class="ag-theme-quartz datagrid-shell" style="height: 85vh; min-height: 620px; width: 100%;"></div>
|
||||
<?php else: ?>
|
||||
<div class="rounded-md border border-dashed border-slate-300 bg-slate-50/70 p-10 text-center">
|
||||
<div class="text-2xl font-semibold text-slate-900">No data loaded</div>
|
||||
<p class="mt-3 text-sm leading-6 text-slate-500">Choose an Excel workbook and run the import to display the latest processed rows here.</p>
|
||||
</div>
|
||||
<?php endif; ?>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script src="https://cdn.jsdelivr.net/npm/ag-grid-community/dist/ag-grid-community.min.js"></script>
|
||||
<script>
|
||||
window.APP_CONFIG = {
|
||||
tableDataUrl: window.location.pathname + '?view=table&action=grid-data'
|
||||
};
|
||||
|
||||
document.addEventListener('DOMContentLoaded', () => {
|
||||
const gridElement = document.getElementById('fullDataGrid');
|
||||
if (!gridElement) {
|
||||
return;
|
||||
}
|
||||
|
||||
const searchInput = document.getElementById('tableSearchInput');
|
||||
const visibilityButton = document.getElementById('columnVisibilityButton');
|
||||
const visibilityMenu = document.getElementById('columnVisibilityMenu');
|
||||
const visibilitySearch = document.getElementById('columnVisibilitySearch');
|
||||
const visibilityItems = document.getElementById('columnVisibilityItems');
|
||||
const blurToggleButton = document.getElementById('blurToggleButton');
|
||||
const headerLabels = <?= json_encode(array_values($tableHeaders), JSON_THROW_ON_ERROR) ?>;
|
||||
|
||||
// Move these columns to appear right before "DSP" instead of their
|
||||
// default import order.
|
||||
['US/ex-US sale', 'Actual/Accrual'].forEach((header) => {
|
||||
const fromIndex = headerLabels.indexOf(header);
|
||||
if (fromIndex === -1) {
|
||||
return;
|
||||
}
|
||||
headerLabels.splice(fromIndex, 1);
|
||||
const dspIndex = headerLabels.indexOf('DSP');
|
||||
headerLabels.splice(dspIndex === -1 ? headerLabels.length : dspIndex, 0, header);
|
||||
});
|
||||
|
||||
let gridApi = null;
|
||||
let currentSearch = searchInput ? searchInput.value.trim() : '';
|
||||
let searchTimer = null;
|
||||
|
||||
const escapeHtml = (value) => String(value).replace(/[&<>"']/g, (character) => {
|
||||
switch (character) {
|
||||
case '&':
|
||||
return '&';
|
||||
case '<':
|
||||
return '<';
|
||||
case '>':
|
||||
return '>';
|
||||
case '"':
|
||||
return '"';
|
||||
case '\'':
|
||||
return ''';
|
||||
default:
|
||||
return character;
|
||||
}
|
||||
});
|
||||
|
||||
const closeVisibilityMenu = () => {
|
||||
if (!visibilityMenu || !visibilityButton) {
|
||||
return;
|
||||
}
|
||||
|
||||
visibilityMenu.classList.add('invisible', 'opacity-0', 'pointer-events-none');
|
||||
visibilityMenu.classList.remove('visible', 'opacity-100');
|
||||
visibilityButton.setAttribute('aria-expanded', 'false');
|
||||
};
|
||||
|
||||
const openVisibilityMenu = () => {
|
||||
if (!visibilityMenu || !visibilityButton) {
|
||||
return;
|
||||
}
|
||||
|
||||
visibilityMenu.classList.remove('invisible', 'opacity-0', 'pointer-events-none');
|
||||
visibilityMenu.classList.add('visible', 'opacity-100');
|
||||
visibilityButton.setAttribute('aria-expanded', 'true');
|
||||
};
|
||||
|
||||
const toggleVisibilityMenu = () => {
|
||||
if (!visibilityMenu || visibilityMenu.classList.contains('invisible')) {
|
||||
openVisibilityMenu();
|
||||
return;
|
||||
}
|
||||
|
||||
closeVisibilityMenu();
|
||||
};
|
||||
|
||||
const currencyHeaderPattern = /usd/i;
|
||||
const flagHeaderPattern = /flag$/i;
|
||||
const FLAG_POSITIVE = new Set(['Y', 'F']);
|
||||
const FLAG_NEGATIVE = new Set(['N', 'D']);
|
||||
|
||||
const formatCurrency = (value) => {
|
||||
if (value === null || value === undefined || value === '') {
|
||||
return '';
|
||||
}
|
||||
const number = Number(value);
|
||||
if (!Number.isFinite(number)) {
|
||||
return String(value);
|
||||
}
|
||||
const formatted = Math.abs(number).toLocaleString('en-US', {
|
||||
minimumFractionDigits: 2,
|
||||
maximumFractionDigits: 2,
|
||||
});
|
||||
return number < 0 ? `(${formatted})` : formatted;
|
||||
};
|
||||
|
||||
// --- Pinned columns ---------------------------------------------------
|
||||
// Each data column gets a pin toggle in its header (see PinnableHeader
|
||||
// component below). Clicking it sets that column's AG Grid `pinned`
|
||||
// state to 'left' or null via applyColumnState. This is native AG Grid
|
||||
// column pinning, so it works correctly with horizontal scroll,
|
||||
// resizing, and column reordering out of the box.
|
||||
const pinnedColumnIds = new Set();
|
||||
|
||||
const isColumnPinned = (colId) => pinnedColumnIds.has(colId);
|
||||
|
||||
const toggleColumnPin = (colId) => {
|
||||
if (!gridApi) {
|
||||
return;
|
||||
}
|
||||
|
||||
const willPin = !isColumnPinned(colId);
|
||||
if (willPin) {
|
||||
pinnedColumnIds.add(colId);
|
||||
} else {
|
||||
pinnedColumnIds.delete(colId);
|
||||
}
|
||||
|
||||
gridApi.applyColumnState({
|
||||
state: [{ colId, pinned: willPin ? 'left' : null }],
|
||||
defaultState: { pinned: null },
|
||||
});
|
||||
|
||||
// Refresh the header so the pin icon reflects the new state.
|
||||
gridApi.refreshHeader();
|
||||
};
|
||||
|
||||
const pinIconSvg = '<svg viewBox="0 0 24 24" width="13" height="13" fill="currentColor"><path d="M14.7 2.5a1 1 0 0 1 1.4 0l5.4 5.4a1 1 0 0 1 0 1.4l-1.5 1.5a1 1 0 0 1-1.4 0l-.3-.3-2.8 2.8.6 3.6a1 1 0 0 1-.27.9l-.9.9a1 1 0 0 1-1.42 0l-3.3-3.3-4.6 4.6a1 1 0 0 1-1.42-1.42l4.6-4.6-3.3-3.3a1 1 0 0 1 0-1.42l.9-.9a1 1 0 0 1 .9-.27l3.6.6 2.8-2.8-.3-.3a1 1 0 0 1 0-1.4Z"/></svg>';
|
||||
const filterIconSvg = '<svg viewBox="0 0 24 24" width="12" height="12" fill="currentColor"><path d="M3 4a1 1 0 0 1 1-1h16a1 1 0 0 1 .8 1.6l-6.3 8.2v6a1 1 0 0 1-.5.87l-3 1.7A1 1 0 0 1 9.5 21v-8.2L3.2 4.6A1 1 0 0 1 3 4Z"/></svg>';
|
||||
|
||||
// Custom header component: renders the default header label/sort icon
|
||||
// plus a pin toggle button. Registered per-column via headerComponent.
|
||||
class PinnableHeader {
|
||||
init(params) {
|
||||
this.params = params;
|
||||
this.eGui = document.createElement('div');
|
||||
this.eGui.className = 'pinnable-header';
|
||||
|
||||
this.eLabel = document.createElement('span');
|
||||
this.eLabel.className = 'pinnable-header__label';
|
||||
this.eLabel.textContent = params.displayName;
|
||||
|
||||
this.eButton = document.createElement('button');
|
||||
this.eButton.type = 'button';
|
||||
this.eButton.className = 'pin-toggle-btn pin-toggle-btn--header';
|
||||
this.eButton.innerHTML = pinIconSvg;
|
||||
this.updateButtonState();
|
||||
|
||||
this.onClick = (event) => {
|
||||
event.stopPropagation();
|
||||
toggleColumnPin(params.column.getColId());
|
||||
};
|
||||
this.eButton.addEventListener('click', this.onClick);
|
||||
|
||||
this.eGui.appendChild(this.eLabel);
|
||||
|
||||
this.eButtons = document.createElement('div');
|
||||
this.eButtons.className = 'pinnable-header__buttons';
|
||||
|
||||
// A custom headerComponent replaces AG Grid's built-in header
|
||||
// entirely, including the filter funnel icon it would normally
|
||||
// add — so for any column that has a filter, add our own
|
||||
// funnel button that opens that column's filter popup.
|
||||
if (params.column.getColDef().filter) {
|
||||
this.eFilterButton = document.createElement('button');
|
||||
this.eFilterButton.type = 'button';
|
||||
this.eFilterButton.className = 'pin-toggle-btn pin-toggle-btn--header filter-toggle-btn';
|
||||
this.eFilterButton.innerHTML = filterIconSvg;
|
||||
this.updateFilterButtonState();
|
||||
|
||||
this.onFilterClick = (event) => {
|
||||
event.stopPropagation();
|
||||
params.api.showColumnFilter(params.column.getColId());
|
||||
};
|
||||
this.eFilterButton.addEventListener('click', this.onFilterClick);
|
||||
this.eButtons.appendChild(this.eFilterButton);
|
||||
}
|
||||
|
||||
this.eButtons.appendChild(this.eButton);
|
||||
this.eGui.appendChild(this.eButtons);
|
||||
|
||||
// Allow clicking the label to sort, same as a default header.
|
||||
this.onLabelClick = () => params.progressSort();
|
||||
this.eLabel.addEventListener('click', this.onLabelClick);
|
||||
}
|
||||
|
||||
updateButtonState() {
|
||||
const pinned = isColumnPinned(this.params.column.getColId());
|
||||
this.eButton.classList.toggle('is-pinned', pinned);
|
||||
this.eButton.title = pinned ? 'Unpin column' : 'Pin column to left';
|
||||
}
|
||||
|
||||
updateFilterButtonState() {
|
||||
if (!this.eFilterButton) {
|
||||
return;
|
||||
}
|
||||
const isActive = this.params.column.isFilterActive();
|
||||
this.eFilterButton.classList.toggle('is-active', isActive);
|
||||
this.eFilterButton.title = isActive ? 'Filter active — click to edit' : 'Filter this column';
|
||||
}
|
||||
|
||||
getGui() {
|
||||
return this.eGui;
|
||||
}
|
||||
|
||||
refresh() {
|
||||
this.updateButtonState();
|
||||
this.updateFilterButtonState();
|
||||
return true;
|
||||
}
|
||||
|
||||
destroy() {
|
||||
this.eButton.removeEventListener('click', this.onClick);
|
||||
this.eLabel.removeEventListener('click', this.onLabelClick);
|
||||
if (this.eFilterButton) {
|
||||
this.eFilterButton.removeEventListener('click', this.onFilterClick);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// --- Excel-style "select values" filter --------------------------------
|
||||
// AG Grid Community doesn't ship the Set Filter (that's Enterprise-only),
|
||||
// so this is a hand-rolled equivalent. It needs a matching backend
|
||||
// endpoint: same tableDataUrl, with distinctColumn / distinctSearch
|
||||
// params, returning { values: [...] }. The grid-data endpoint also
|
||||
// needs to treat a filterModel entry of { filterType: 'set', values }
|
||||
// as an IN-list match rather than a text "contains" match.
|
||||
class ExcelStyleFilter {
|
||||
init(params) {
|
||||
this.params = params;
|
||||
this.selected = new Set();
|
||||
this.values = [];
|
||||
this.eGui = document.createElement('div');
|
||||
this.eGui.className = 'excel-filter';
|
||||
this.eGui.innerHTML = `
|
||||
<div class="excel-filter__search">
|
||||
<input type="search" placeholder="Search values" class="excel-filter__search-input">
|
||||
</div>
|
||||
<div class="excel-filter__actions">
|
||||
<button type="button" data-action="select-all" class="excel-filter__link">Select all</button>
|
||||
<button type="button" data-action="clear" class="excel-filter__link">Clear</button>
|
||||
</div>
|
||||
<div class="excel-filter__list"></div>
|
||||
<div class="excel-filter__footer">
|
||||
<button type="button" data-action="apply" class="excel-filter__apply">Apply</button>
|
||||
</div>
|
||||
`;
|
||||
|
||||
this.eList = this.eGui.querySelector('.excel-filter__list');
|
||||
this.eSearch = this.eGui.querySelector('.excel-filter__search-input');
|
||||
|
||||
this.eSearch.addEventListener('input', () => {
|
||||
window.clearTimeout(this._searchTimer);
|
||||
this._searchTimer = window.setTimeout(() => this.loadValues(this.eSearch.value.trim()), 200);
|
||||
});
|
||||
|
||||
this.eGui.querySelector('[data-action="select-all"]').addEventListener('click', () => {
|
||||
this.values.forEach((value) => this.selected.add(value));
|
||||
this.renderList();
|
||||
});
|
||||
|
||||
this.eGui.querySelector('[data-action="clear"]').addEventListener('click', () => {
|
||||
this.selected.clear();
|
||||
this.renderList();
|
||||
});
|
||||
|
||||
this.eGui.querySelector('[data-action="apply"]').addEventListener('click', () => {
|
||||
this.params.filterChangedCallback();
|
||||
});
|
||||
|
||||
this.loadValues('');
|
||||
}
|
||||
|
||||
getGui() {
|
||||
return this.eGui;
|
||||
}
|
||||
|
||||
async loadValues(searchTerm) {
|
||||
this.eList.innerHTML = '<div class="excel-filter__loading">Loading values…</div>';
|
||||
try {
|
||||
const url = new URL(window.APP_CONFIG.tableDataUrl, window.location.origin);
|
||||
url.searchParams.set('distinctColumn', this.params.colDef.colId);
|
||||
url.searchParams.set('distinctSearch', searchTerm ?? '');
|
||||
const response = await fetch(url.toString(), { headers: { Accept: 'application/json' } });
|
||||
const payload = await response.json();
|
||||
this.values = Array.isArray(payload.values) ? payload.values : [];
|
||||
this.renderList();
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
this.eList.innerHTML = '<div class="excel-filter__loading">Could not load values</div>';
|
||||
}
|
||||
}
|
||||
|
||||
renderList() {
|
||||
this.eList.innerHTML = this.values.map((value) => `
|
||||
<label class="excel-filter__item">
|
||||
<input type="checkbox" value="${escapeHtml(value)}" ${this.selected.has(value) ? 'checked' : ''}>
|
||||
<span>${value === '' ? '(blank)' : escapeHtml(value)}</span>
|
||||
</label>
|
||||
`).join('');
|
||||
|
||||
this.eList.querySelectorAll('input[type="checkbox"]').forEach((checkbox) => {
|
||||
checkbox.addEventListener('change', (event) => {
|
||||
if (event.target.checked) {
|
||||
this.selected.add(event.target.value);
|
||||
} else {
|
||||
this.selected.delete(event.target.value);
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
isFilterActive() {
|
||||
return this.selected.size > 0;
|
||||
}
|
||||
|
||||
getModel() {
|
||||
return this.isFilterActive()
|
||||
? { filterType: 'set', values: Array.from(this.selected) }
|
||||
: null;
|
||||
}
|
||||
|
||||
setModel(model) {
|
||||
this.selected = new Set(model?.values ?? []);
|
||||
this.renderList();
|
||||
}
|
||||
|
||||
doesFilterPass() {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
// ======================================================================
|
||||
// FEATURE TOGGLES — flip these to `false` to switch a feature off
|
||||
// without deleting any of the code below.
|
||||
// ======================================================================
|
||||
const ENABLE_CURRENCY_FORMATTING = true; // controls Net Value USD formatting (2dp, brackets for negatives)
|
||||
const ENABLE_FLAG_COLOURS = true; // controls green/red cell colours on *Flag columns
|
||||
|
||||
const columnDefs = [
|
||||
// {
|
||||
// colId: 'row_number',
|
||||
// headerName: 'Row',
|
||||
// field: 'row_number',
|
||||
// width: 110,
|
||||
// pinned: 'left',
|
||||
// lockPinned: true,
|
||||
// sortable: true,
|
||||
// filter: 'agNumberColumnFilter',
|
||||
// floatingFilter: false,
|
||||
// resizable: true,
|
||||
// sort: 'asc',
|
||||
// suppressHeaderMenuButton: false,
|
||||
// suppressMovable: true,
|
||||
// },
|
||||
...headerLabels.map((header) => {
|
||||
const isCurrency = currencyHeaderPattern.test(header);
|
||||
const isFlag = flagHeaderPattern.test(header);
|
||||
|
||||
const columnDef = {
|
||||
colId: header,
|
||||
headerName: header,
|
||||
headerComponent: PinnableHeader,
|
||||
valueGetter: (params) => (params.data ? (params.data[header] ?? '') : ''),
|
||||
minWidth: isCurrency ? 140 : 160,
|
||||
sortable: true,
|
||||
resizable: true,
|
||||
suppressHeaderMenuButton: false,
|
||||
hide: header === 'x',
|
||||
};
|
||||
|
||||
if (isCurrency) {
|
||||
columnDef.filter = 'agNumberColumnFilter';
|
||||
columnDef.floatingFilter = false;
|
||||
|
||||
// --- NET VALUE USD FORMATTING ---------------------------
|
||||
// Set ENABLE_CURRENCY_FORMATTING (above) to false to show
|
||||
// the raw numeric value instead of the 2dp/bracket format.
|
||||
if (ENABLE_CURRENCY_FORMATTING) {
|
||||
columnDef.valueFormatter = (params) => formatCurrency(params.value);
|
||||
columnDef.cellClass = 'text-right font-mono tabular-nums';
|
||||
}
|
||||
// --- END NET VALUE USD FORMATTING -----------------------
|
||||
} else {
|
||||
columnDef.filter = ExcelStyleFilter;
|
||||
columnDef.floatingFilter = false;
|
||||
}
|
||||
|
||||
// --- FLAG COLOURS (Y/F green, N/D red) ----------------------
|
||||
// Set ENABLE_FLAG_COLOURS (above) to false to disable the
|
||||
// green/red cell backgrounds on columns ending in "Flag".
|
||||
if (isFlag && ENABLE_FLAG_COLOURS) {
|
||||
columnDef.cellClassRules = {
|
||||
'cell-flag-positive': (params) => FLAG_POSITIVE.has(String(params.value).trim().toUpperCase()),
|
||||
'cell-flag-negative': (params) => FLAG_NEGATIVE.has(String(params.value).trim().toUpperCase()),
|
||||
};
|
||||
}
|
||||
// --- END FLAG COLOURS ----------------------------------------
|
||||
|
||||
return columnDef;
|
||||
}),
|
||||
];
|
||||
|
||||
const datasource = {
|
||||
getRows: async (params) => {
|
||||
const url = new URL(window.APP_CONFIG.tableDataUrl, window.location.origin);
|
||||
url.searchParams.set('startRow', String(params.startRow ?? 0));
|
||||
url.searchParams.set('endRow', String(params.endRow ?? ((params.startRow ?? 0) + 100)));
|
||||
url.searchParams.set('search', currentSearch);
|
||||
url.searchParams.set('sortModel', JSON.stringify(params.sortModel ?? []));
|
||||
url.searchParams.set('filterModel', JSON.stringify(params.filterModel ?? {}));
|
||||
|
||||
try {
|
||||
const response = await fetch(url.toString(), {
|
||||
headers: {
|
||||
Accept: 'application/json',
|
||||
},
|
||||
});
|
||||
const payload = await response.json();
|
||||
|
||||
if (!response.ok || payload.error) {
|
||||
throw new Error(payload.error || `Request failed (${response.status})`);
|
||||
}
|
||||
|
||||
const rows = Array.isArray(payload.rows) ? payload.rows : [];
|
||||
const lastRow = Number.isFinite(Number(payload.lastRow)) ? Number(payload.lastRow) : rows.length;
|
||||
params.successCallback(rows, lastRow);
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
params.failCallback();
|
||||
}
|
||||
},
|
||||
};
|
||||
|
||||
const setDatasource = () => {
|
||||
if (!gridApi) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (typeof gridApi.setGridOption === 'function') {
|
||||
gridApi.setGridOption('datasource', datasource);
|
||||
return;
|
||||
}
|
||||
|
||||
if (typeof gridApi.setDatasource === 'function') {
|
||||
gridApi.setDatasource(datasource);
|
||||
}
|
||||
};
|
||||
|
||||
const refreshGrid = () => {
|
||||
if (!gridApi) {
|
||||
return;
|
||||
}
|
||||
|
||||
setDatasource();
|
||||
|
||||
if (typeof gridApi.refreshInfiniteCache === 'function') {
|
||||
gridApi.refreshInfiniteCache();
|
||||
return;
|
||||
}
|
||||
|
||||
if (typeof gridApi.purgeInfiniteCache === 'function') {
|
||||
gridApi.purgeInfiniteCache();
|
||||
}
|
||||
};
|
||||
|
||||
const updateVisibilityMenu = () => {
|
||||
if (!visibilityItems) {
|
||||
return;
|
||||
}
|
||||
|
||||
const items = columnDefs
|
||||
.filter((column) => column.colId !== 'row_number')
|
||||
.map((column) => `
|
||||
<label class="flex cursor-pointer items-center gap-3 rounded-md px-3 py-2 text-sm text-slate-700 transition hover:bg-slate-50">
|
||||
<input class="h-4 w-4 rounded border-slate-300 text-sky-600 focus:ring-sky-500" type="checkbox" data-col-id="${escapeHtml(column.colId)}" ${column.hide ? '' : 'checked'}>
|
||||
<span class="min-w-0 flex-1 truncate">${escapeHtml(column.headerName ?? column.colId)}</span>
|
||||
</label>
|
||||
`);
|
||||
|
||||
visibilityItems.innerHTML = items.join('');
|
||||
visibilityItems.querySelectorAll('input[type="checkbox"][data-col-id]').forEach((checkbox) => {
|
||||
checkbox.addEventListener('change', function () {
|
||||
if (!gridApi) {
|
||||
return;
|
||||
}
|
||||
|
||||
const colId = this.getAttribute('data-col-id');
|
||||
gridApi.applyColumnState({
|
||||
state: [
|
||||
{
|
||||
colId,
|
||||
hide: !this.checked,
|
||||
},
|
||||
],
|
||||
applyOrder: false,
|
||||
});
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
const updateVisibilitySearch = () => {
|
||||
if (!visibilitySearch || !visibilityItems) {
|
||||
return;
|
||||
}
|
||||
|
||||
const filter = visibilitySearch.value.trim().toLowerCase();
|
||||
visibilityItems.querySelectorAll('label').forEach((item) => {
|
||||
const text = item.textContent.trim().toLowerCase();
|
||||
item.classList.toggle('hidden', filter !== '' && !text.includes(filter));
|
||||
});
|
||||
};
|
||||
|
||||
if (searchInput) {
|
||||
searchInput.addEventListener('input', function () {
|
||||
window.clearTimeout(searchTimer);
|
||||
currentSearch = this.value.trim();
|
||||
searchTimer = window.setTimeout(() => refreshGrid(), 180);
|
||||
});
|
||||
}
|
||||
|
||||
if (visibilityButton) {
|
||||
visibilityButton.addEventListener('click', (event) => {
|
||||
event.stopPropagation();
|
||||
toggleVisibilityMenu();
|
||||
});
|
||||
}
|
||||
|
||||
if (visibilityMenu) {
|
||||
visibilityMenu.addEventListener('click', (event) => event.stopPropagation());
|
||||
}
|
||||
|
||||
if (visibilitySearch) {
|
||||
visibilitySearch.addEventListener('input', updateVisibilitySearch);
|
||||
}
|
||||
|
||||
if (blurToggleButton) {
|
||||
const BLUR_STORAGE_KEY = 'warner:tableBlurred';
|
||||
|
||||
const setBlurred = (blurred) => {
|
||||
gridElement.classList.toggle('is-privacy-blurred', blurred);
|
||||
blurToggleButton.setAttribute('aria-pressed', String(blurred));
|
||||
blurToggleButton.classList.toggle('is-active', blurred);
|
||||
const label = blurToggleButton.querySelector('[data-blur-label]');
|
||||
if (label) {
|
||||
label.textContent = blurred ? 'Unblur data' : 'Blur data';
|
||||
}
|
||||
try {
|
||||
window.localStorage.setItem(BLUR_STORAGE_KEY, blurred ? '1' : '0');
|
||||
} catch (error) {
|
||||
// Ignore storage errors (e.g. private browsing).
|
||||
}
|
||||
};
|
||||
|
||||
let initiallyBlurred = false;
|
||||
try {
|
||||
initiallyBlurred = window.localStorage.getItem(BLUR_STORAGE_KEY) === '1';
|
||||
} catch (error) {
|
||||
initiallyBlurred = false;
|
||||
}
|
||||
setBlurred(initiallyBlurred);
|
||||
|
||||
blurToggleButton.addEventListener('click', () => {
|
||||
setBlurred(!gridElement.classList.contains('is-privacy-blurred'));
|
||||
});
|
||||
}
|
||||
|
||||
document.addEventListener('click', (event) => {
|
||||
if (visibilityMenu && visibilityButton && !visibilityMenu.contains(event.target) && !visibilityButton.contains(event.target)) {
|
||||
closeVisibilityMenu();
|
||||
}
|
||||
});
|
||||
|
||||
const gridOptions = {
|
||||
columnDefs,
|
||||
defaultColDef: {
|
||||
sortable: true,
|
||||
resizable: true,
|
||||
filter: true,
|
||||
floatingFilter: false,
|
||||
suppressHeaderMenuButton: false,
|
||||
minWidth: 140,
|
||||
},
|
||||
rowModelType: 'infinite',
|
||||
cacheBlockSize: 100,
|
||||
maxBlocksInCache: 5,
|
||||
infiniteInitialRowCount: 1,
|
||||
pagination: true,
|
||||
paginationPageSize: 100,
|
||||
animateRows: false,
|
||||
datasource,
|
||||
getRowId: (params) => String(params.data?.row_number ?? ''),
|
||||
onGridReady: (params) => {
|
||||
gridApi = params.api;
|
||||
setDatasource();
|
||||
updateVisibilityMenu();
|
||||
refreshGrid();
|
||||
},
|
||||
// Refreshes header icons (funnel active-state) whenever any filter
|
||||
// changes, including from the custom Excel-style filter popup.
|
||||
onFilterChanged: () => {
|
||||
if (gridApi) {
|
||||
gridApi.refreshHeader();
|
||||
}
|
||||
},
|
||||
};
|
||||
|
||||
agGrid.createGrid(gridElement, gridOptions);
|
||||
});
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
Reference in New Issue
Block a user