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 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 | 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 28x 28x 28x 28x 9x 9x 9x 8x 9x 1x 1x 9x 9x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 175x 2x 2x 175x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 18x 175x 175x 175x 175x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 28x 1x | import { PANEL } from '@/constants/common';
import { useAppContext } from '@/context';
import { i18n } from '@/helpers/i18n';
import {
matchPercentageSortingFn,
priceSortingFn,
puritySortingFn,
quantitySortingFn,
unitPriceSortingFn,
} from '@/helpers/sorting';
import { formatTimestamp, generatePageSizes } from '@/helpers/utils';
import { getAllPriceSeries } from '@/utils/idbCache';
import ArrowBackIcon from '@mui/icons-material/ArrowBack';
import ChevronLeftIcon from '@mui/icons-material/ChevronLeft';
import ChevronRightIcon from '@mui/icons-material/ChevronRight';
import FirstPageIcon from '@mui/icons-material/FirstPage';
import LastPageIcon from '@mui/icons-material/LastPage';
import { FormControl, IconButton, Link, MenuItem, TableRow, Typography } from '@mui/material';
import {
type ColumnDef,
type FilterFn,
flexRender,
getCoreRowModel,
getPaginationRowModel,
getSortedRowModel,
type SortingState,
useReactTable,
} from '@tanstack/react-table';
import { FC, useEffect, useMemo, useState } from 'react';
import ArrowDropDownIcon from '../../icons/ArrowDropDownIcon';
import ArrowDropUpIcon from '../../icons/ArrowDropUpIcon';
import { formatUsd, PriceTrend } from '../SearchPanel/PriceTrendGraph';
import {
BackButton,
EmptyStateCell,
HeaderCellContent,
NavigationContainer,
PageSizeContainer,
PageSizeSelect,
PaginationContainer,
SearchResultsTable,
SortableTableHeaderCell,
SortIndicator,
StyledTableBody,
StyledTableCell,
StyledTableHead,
StyledTableRow,
} from '../StyledComponents';
import styles from './PriceHistoryPanel.module.scss';
import { buildPriceChangeRows, type PriceChangeRow } from './priceHistoryRows';
import { Logger } from '@/utils/Logger';
import { getErrorMessage } from '@/helpers/exceptions';
const logger = new Logger('PriceHistoryPanel');
/**
* Stand-in for the `multiSelect`/`includeHierarchy`/`inNumberRangeHierarchy`
* filter ids that `SortingFns`/`FilterFns` (augmented project-wide in
* `src/types/tanstack.d.ts` for the results table) make required on every
* `useReactTable()` call. No column in this panel sets a `filterFn` to one of
* these ids, so it's never actually invoked.
* @returns Always `true`.
* @source
*/
const unusedFilterFn: FilterFn<PriceChangeRow> = () => true;
/**
* Full-panel, sortable log of every price change ChemPal has ever recorded
* across every supplier and product — one row per change, newest first by
* default. Only available in advanced mode; wired up the same way as
* `StatsPanel`: a `PANEL.PRICE_HISTORY` entry in the app's panel switch,
* reached from the speed-dial menu, hidden the moment advanced mode turns off.
*
* Reads the full `price_history` IndexedDB store via {@link getAllPriceSeries}
* and flattens it with `buildPriceChangeRows` — series with only one
* recorded price (never changed) contribute no rows, so this view answers
* "which products actually do have price changes logged".
* @category Components
* @example
* ```tsx
* <PriceHistoryPanel />
* ```
* @source
*/
const PriceHistoryPanel: FC = () => {
const appContext = useAppContext();
const [rows, setRows] = useState<PriceChangeRow[]>([]);
const [sorting, setSorting] = useState<SortingState>([{ id: 'changedAt', desc: true }]);
useEffect(() => {
const loadRows = async () => {
try {
const entries = await getAllPriceSeries();
setRows(buildPriceChangeRows(entries));
} catch (error) {
logger.warn(`Failed to load price history: ${getErrorMessage(error)}`, { error });
}
};
void loadRows();
}, []);
const userSettings = appContext.userSettings;
const columns = useMemo<ColumnDef<PriceChangeRow, unknown>[]>(
() => [
{
id: 'changedAt',
header: i18n('price_history_panel_col_date'),
accessorFn: (row) => row.changedAt,
cell: ({ getValue }) => formatTimestamp(getValue<number>()),
size: 150,
},
{
id: 'supplier',
header: i18n('column_supplier'),
accessorKey: 'supplier',
size: 140,
},
{
id: 'title',
header: i18n('column_title'),
accessorKey: 'title',
cell: ({ row }) =>
row.original.permalink ? (
<Link href={row.original.permalink} target="_blank" rel="noopener noreferrer">
{row.original.title}
</Link>
) : (
row.original.title
),
size: 260,
},
{
id: 'oldPriceUsd',
header: i18n('price_history_panel_col_old_price'),
accessorFn: (row) => row.oldPriceUsd,
cell: ({ getValue }) => formatUsd(getValue<number>(), userSettings),
size: 110,
},
{
id: 'newPriceUsd',
header: i18n('price_history_panel_col_new_price'),
accessorFn: (row) => row.newPriceUsd,
cell: ({ getValue }) => formatUsd(getValue<number>(), userSettings),
size: 110,
},
{
id: 'change',
header: i18n('column_price_change'),
accessorFn: (row) => row.pctChange,
cell: ({ row }) => (
<PriceTrend
points={[
{ t: row.original.changedAt - 1, usd: row.original.oldPriceUsd },
{ t: row.original.changedAt, usd: row.original.newPriceUsd },
]}
userSettings={userSettings}
/>
),
size: 150,
},
],
[userSettings],
);
const table = useReactTable({
data: rows,
columns,
state: { sorting },
onSortingChange: setSorting,
getCoreRowModel: getCoreRowModel(),
getSortedRowModel: getSortedRowModel(),
getPaginationRowModel: getPaginationRowModel(),
initialState: { pagination: { pageSize: 25 } },
// Required by the project-wide `SortingFns`/`FilterFns` augmentation (see
// `unusedFilterFn`); none of these ids are used by this panel's columns.
sortingFns: {
matchPercentage: matchPercentageSortingFn,
priceSortingFn,
puritySortingFn,
quantitySortingFn,
unitPriceSortingFn,
},
filterFns: {
multiSelect: unusedFilterFn,
includeHierarchy: unusedFilterFn,
inNumberRangeHierarchy: unusedFilterFn,
},
});
const totalRowCount = rows.length;
return (
<div className={styles['price-history-panel']}>
<div className={styles['price-history-panel__top-header']}>
<div className={styles['header-left']}>
{appContext.setPanel && (
<BackButton
onClick={() => appContext.setPanel!(PANEL.SEARCH_HOME)}
size="small"
aria-label={i18n('common_back_to_search')}
>
<ArrowBackIcon />
</BackButton>
)}
<Typography variant="subtitle2">{i18n('price_history_panel_title')}</Typography>
</div>
</div>
<div className={styles['price-history-panel__content']}>
<SearchResultsTable>
<StyledTableHead>
{table.getHeaderGroups().map((headerGroup) => (
<TableRow key={headerGroup.id}>
{headerGroup.headers.map((header) => (
<SortableTableHeaderCell
key={header.id}
canSort={header.column.getCanSort()}
cellWidth={header.getSize()}
onClick={header.column.getToggleSortingHandler()}
>
<HeaderCellContent>
{flexRender(header.column.columnDef.header, header.getContext())}
{header.column.getCanSort() && (
<SortIndicator>
{
{
asc: <ArrowDropUpIcon />,
desc: <ArrowDropDownIcon />,
}[String(header.column.getIsSorted())]
}
</SortIndicator>
)}
</HeaderCellContent>
</SortableTableHeaderCell>
))}
</TableRow>
))}
</StyledTableHead>
<StyledTableBody>
{table.getRowModel().rows.length > 0 ? (
table.getRowModel().rows.map((row) => (
<StyledTableRow key={row.id}>
{row.getVisibleCells().map((cell) => (
<StyledTableCell key={cell.id}>
{flexRender(cell.column.columnDef.cell, cell.getContext())}
</StyledTableCell>
))}
</StyledTableRow>
))
) : (
<TableRow>
<EmptyStateCell colSpan={columns.length}>
{i18n('price_history_panel_empty')}
</EmptyStateCell>
</TableRow>
)}
</StyledTableBody>
</SearchResultsTable>
{totalRowCount > 10 && (
<PaginationContainer>
<PageSizeContainer>
<Typography variant="body2">{i18n('results_show')}:</Typography>
<FormControl size="small">
<PageSizeSelect
value={table.getState().pagination.pageSize}
onChange={(e) => table.setPageSize(Number(e.target.value))}
aria-label={i18n('results_rows_per_page_aria')}
>
{generatePageSizes(totalRowCount, 10, 5).map((pageSize) => (
<MenuItem key={pageSize} value={pageSize}>
{pageSize === totalRowCount ? i18n('results_all') : pageSize}
</MenuItem>
))}
</PageSizeSelect>
</FormControl>
<Typography variant="body2">{i18n('results_rows')}</Typography>
</PageSizeContainer>
<Typography variant="body2">
{i18n('results_page_of_total', [
String(table.getState().pagination.pageIndex + 1),
String(table.getPageCount()),
])}{' '}
{i18n('results_total', [String(totalRowCount)])}
</Typography>
<NavigationContainer>
<IconButton
onClick={() => table.setPageIndex(0)}
disabled={!table.getCanPreviousPage()}
size="small"
>
<FirstPageIcon />
</IconButton>
<IconButton
onClick={() => table.previousPage()}
disabled={!table.getCanPreviousPage()}
size="small"
>
<ChevronLeftIcon />
</IconButton>
<IconButton
onClick={() => table.nextPage()}
disabled={!table.getCanNextPage()}
size="small"
>
<ChevronRightIcon />
</IconButton>
<IconButton
onClick={() => table.setPageIndex(table.getPageCount() - 1)}
disabled={!table.getCanNextPage()}
size="small"
>
<LastPageIcon />
</IconButton>
</NavigationContainer>
</PaginationContainer>
)}
</div>
</div>
);
};
export default PriceHistoryPanel;
|