Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 | 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 61x 61x 61x 1x 12x 12x 12x 12x 12x 1x 1x 1x 1x 1x 1x 1x 1x 1x 61x 61x 61x 61x 61x 1x 61x 61x 17x 11x 11x 17x 17x 1x 1x 27x 27x 14x 14x 14x 14x 27x 18x 18x 18x 18x 18x 18x 14x 14x 14x 14x 18x 18x 18x 14x 14x 14x 14x 26x 27x 1x 14x 14x 14x 14x 14x 14x 14x 14x 1x 1x 1x 7x 7x 1x 1x 1x 32x 32x 1x 1x 1x 5x 5x 1x 1x 1x 15x 15x 1x 1x 1x 2x 2x 1x 1x 1x 13x 13x 13x 13x 13x 13x 1x 1x 1x 2x 2x 2x 2x 2x 2x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x | /**
* Utility for persisting per-supplier, per-day search statistics
* in IndexedDB via the `supplierStats` object store.
*
* Each day gets its own record keyed by `YYYY-MM-DD`.
*
* Uses an in-memory buffer to avoid race conditions from concurrent
* fire-and-forget writes. Flushes to IndexedDB on a debounced timer.
*
* All stat calls use `supplierName` from SupplierBase (e.g. "Carolina"),
* NOT the class name (e.g. "SupplierCarolina"), to keep keys consistent.
*
* Cached responses do NOT increment HTTP or product counts.
* Auto-prunes entries older than 30 days on each flush.
*
* @category Utils
* @source
*/
import { toDateKey } from '@/helpers/supplierStats';
import {
getSupplierStatsEntry,
putSupplierStatsEntry,
getAllSupplierStats,
deleteSupplierStatsEntries,
clearSupplierStats as idbClearSupplierStats,
} from '@/utils/idbCache';
import { Logger } from '@/utils/Logger';
import { getErrorMessage } from '@/helpers/exceptions';
const logger = new Logger('SupplierStatsStore');
const RETENTION_DAYS = 30;
const FLUSH_DELAY_MS = 500;
/** In-memory pending increments, keyed by date:supplier:field */
const pendingIncrements: Map<string, number> = new Map();
let flushTimer: ReturnType<typeof setTimeout> | null = null;
/**
* Returns today's date as YYYY-MM-DD for data grouping, in local time. These
* buckets are user-facing (the panel's "Today" filter and daily chart), so they
* follow the user's calendar rather than UTC.
*/
function todayDateKey(): string {
return toDateKey(new Date());
}
/** Get the cutoff date key for pruning */
function getCutoffDateKey(): string {
const cutoff = new Date();
cutoff.setDate(cutoff.getDate() - RETENTION_DAYS);
return toDateKey(cutoff);
}
const EMPTY_STATS: SupplierDayStats = {
searchQueryCount: 0,
successCount: 0,
failureCount: 0,
uniqueProductCount: 0,
parseErrorCount: 0,
};
/**
* Buffer an increment in memory and schedule a debounced flush to storage.
* @source
*/
function bufferIncrement(supplier: string, field: keyof SupplierDayStats): void {
const key = `${todayDateKey()}:${supplier}:${field}`;
pendingIncrements.set(key, (pendingIncrements.get(key) ?? 0) + 1);
scheduleFlush();
}
/** Schedule a flush if one isn't already pending */
function scheduleFlush(): void {
if (flushTimer !== null) return;
flushTimer = setTimeout(() => {
flushTimer = null;
flushToStorage();
}, FLUSH_DELAY_MS);
}
/**
* Apply all pending increments to IndexedDB. Groups by date so each day's
* data goes to its own record in the `supplierStats` object store.
* @source
*/
async function flushToStorage(): Promise<void> {
if (pendingIncrements.size === 0) return;
const batch = new Map(pendingIncrements);
pendingIncrements.clear();
// Group increments by date
const byDate: Record<string, Array<[string, string, keyof SupplierDayStats, number]>> = {};
for (const [key, delta] of batch) {
// Keys are built internally by bufferIncrement as `date:supplier:field`, so the
// tuple shape is guaranteed; split() only ever returns the wider string[] type.
const [date, supplier, field] = key.split(':') as [string, string, keyof SupplierDayStats];
if (!byDate[date]) byDate[date] = [];
byDate[date].push([date, supplier, field, delta]);
}
try {
for (const dateKey of Object.keys(byDate)) {
const existing = (await getSupplierStatsEntry(dateKey)) ?? {};
for (const [, supplier, field, delta] of byDate[dateKey]) {
if (!existing[supplier]) existing[supplier] = { ...EMPTY_STATS };
existing[supplier][field] += delta;
}
await putSupplierStatsEntry(dateKey, existing);
}
// Prune old entries
await pruneOldEntries();
} catch (error) {
logger.warn(`Failed to flush supplier stats: ${getErrorMessage(error)}`, { error });
for (const [key, delta] of batch) {
pendingIncrements.set(key, (pendingIncrements.get(key) ?? 0) + delta);
}
scheduleFlush();
}
}
/** Remove records older than RETENTION_DAYS */
async function pruneOldEntries(): Promise<void> {
const cutoff = getCutoffDateKey();
try {
const allStats = await getAllSupplierStats();
const keysToRemove = Object.keys(allStats).filter((dateKey) => dateKey < cutoff);
if (keysToRemove.length > 0) {
await deleteSupplierStatsEntries(keysToRemove);
}
} catch (error) {
logger.warn(`Failed to prune old supplier stats: ${getErrorMessage(error)}`, { error });
}
}
/**
* Increment search query count (called once per supplier at start of execute())
* @category Utils
*/
export function incrementSearchQueryCount(supplier: string): void {
bufferIncrement(supplier, 'searchQueryCount');
}
/**
* Increment successful HTTP connection count (HTTP 2xx, non-cached)
* @category Utils
*/
export function incrementSuccess(supplier: string): void {
bufferIncrement(supplier, 'successCount');
}
/**
* Increment failed HTTP connection count (HTTP 4xx/5xx, network errors, non-cached)
* @category Utils
*/
export function incrementFailure(supplier: string): void {
bufferIncrement(supplier, 'failureCount');
}
/**
* Increment unique product count (called when a non-cached product detail is fetched)
* @category Utils
*/
export function incrementProductCount(supplier: string): void {
bufferIncrement(supplier, 'uniqueProductCount');
}
/**
* Increment parse/processing error count (called when product processing throws)
* @category Utils
*/
export function incrementParseError(supplier: string): void {
bufferIncrement(supplier, 'parseErrorCount');
}
/**
* Read all stats from IndexedDB, returning the SupplierStatsData shape:
* `{ [dateKey]: { [supplier]: SupplierDayStats } }`. Recording runs in every
* build; only the stats *UI* is gated (dev builds, or advanced mode).
* @category Utils
* @source
*/
export async function getStats(): Promise<SupplierStatsData> {
// Flush any pending increments first
await flushToStorage();
try {
return await getAllSupplierStats();
} catch (error) {
logger.warn(`Failed to read supplier stats: ${getErrorMessage(error)}`, { error });
return {};
}
}
/**
* Force any buffered increments to IndexedDB immediately, bypassing the debounce
* timer. Call this at points where the buffer would otherwise be at risk of never
* flushing — e.g. once a search finishes, since the popup can be closed (and its
* JS context destroyed) at any moment afterward.
* @category Utils
* @source
*/
export async function flushPendingStats(): Promise<void> {
if (flushTimer !== null) {
clearTimeout(flushTimer);
flushTimer = null;
}
await flushToStorage();
}
// The popup's JS context is destroyed the instant it loses focus/closes, taking any
// pending debounce timer and unflushed increments with it. Flushing on `hidden` is a
// best-effort backstop for increments made mid-search, before performSearch's own
// flush (see useSearch.ts) gets a chance to run.
if (typeof document !== 'undefined') {
document.addEventListener('visibilitychange', () => {
if (document.hidden) {
void flushPendingStats();
}
});
}
/**
* Clear all stats — removes all records from the supplierStats store.
* @category Utils
*/
export async function clearStats(): Promise<void> {
pendingIncrements.clear();
try {
await idbClearSupplierStats();
} catch (error) {
logger.warn(`Failed to clear supplier stats: ${getErrorMessage(error)}`, { error });
}
}
|