refactor prices schema, add missing shared files

This commit is contained in:
Jurgis Sakalauskas
2025-10-14 13:30:44 +03:00
parent b20ab30ece
commit 1039c90918
13 changed files with 161 additions and 401 deletions
+3 -15
View File
@@ -1,12 +1,8 @@
import type { PaginatedResponse } from '@shared/models/pagination'; import type { PaginatedResponse } from '@shared/models/pagination';
import type { import type { ItemPrice, PriceCondition } from '@shared/models/item-price';
ItemPrice,
PriceCondition,
PriceSourceType
} from '@shared/models/item-price';
import { apiFetch } from './http-client'; import { apiFetch } from './http-client';
export type { PriceCondition, PriceSourceType }; export type { PriceCondition };
export type ItemPricesResponse = PaginatedResponse<ItemPrice>; export type ItemPricesResponse = PaginatedResponse<ItemPrice>;
@@ -47,13 +43,9 @@ export interface CreateItemPricePayload {
condition: PriceCondition; condition: PriceCondition;
amount: number; amount: number;
currency: string; currency: string;
sourceType: PriceSourceType;
sourceUrl?: string | null; sourceUrl?: string | null;
sourceUrlId?: string | null; sourceUrlId?: string | null;
sourceNote?: string | null;
note?: string | null; note?: string | null;
observedAt?: string;
isPrimary?: boolean;
} }
interface SingleItemPriceResponse { interface SingleItemPriceResponse {
@@ -72,13 +64,9 @@ export const createItemPrice = async (
condition: payload.condition, condition: payload.condition,
amount: payload.amount, amount: payload.amount,
currency: payload.currency, currency: payload.currency,
sourceType: payload.sourceType,
sourceUrl: payload.sourceUrl ?? null, sourceUrl: payload.sourceUrl ?? null,
sourceUrlId: payload.sourceUrlId ?? null, sourceUrlId: payload.sourceUrlId ?? null,
sourceNote: payload.sourceNote ?? null, note: payload.note ?? null
note: payload.note ?? null,
observedAt: payload.observedAt ?? null,
isPrimary: payload.isPrimary ?? false
} }
} }
); );
@@ -1,9 +1,8 @@
import { FormEvent, useMemo, useState } from 'react'; import { FormEvent, useMemo, useState } from 'react';
import { useCreateItemPriceMutation, useItemPricesQuery } from '../../query/item-prices'; import { useCreateItemPriceMutation, useItemPricesQuery } from '../../query/item-prices';
import type { PriceCondition, PriceSourceType } from '../../api/item-prices'; import type { PriceCondition } from '../../api/item-prices';
const priceConditionOptions: PriceCondition[] = ['new', 'used']; const priceConditionOptions: PriceCondition[] = ['new', 'used'];
const priceSourceOptions: PriceSourceType[] = ['url', 'manual'];
interface ItemPricesPanelProps { interface ItemPricesPanelProps {
itemId: string; itemId: string;
@@ -13,12 +12,8 @@ export function ItemPricesPanel({ itemId }: ItemPricesPanelProps) {
const [condition, setCondition] = useState<PriceCondition>('new'); const [condition, setCondition] = useState<PriceCondition>('new');
const [amount, setAmount] = useState(''); const [amount, setAmount] = useState('');
const [currency, setCurrency] = useState('USD'); const [currency, setCurrency] = useState('USD');
const [sourceType, setSourceType] = useState<PriceSourceType>('manual');
const [sourceUrl, setSourceUrl] = useState(''); const [sourceUrl, setSourceUrl] = useState('');
const [note, setNote] = useState(''); const [note, setNote] = useState('');
const [sourceNote, setSourceNote] = useState('');
const [observedAt, setObservedAt] = useState('');
const [isPrimary, setIsPrimary] = useState(true);
const [formError, setFormError] = useState<string | null>(null); const [formError, setFormError] = useState<string | null>(null);
const pricesQuery = useItemPricesQuery(itemId, true); const pricesQuery = useItemPricesQuery(itemId, true);
@@ -46,20 +41,13 @@ export function ItemPricesPanel({ itemId }: ItemPricesPanelProps) {
condition, condition,
amount: parsedAmount, amount: parsedAmount,
currency: currency.trim().toUpperCase(), currency: currency.trim().toUpperCase(),
sourceType, sourceUrl: sourceUrl.trim() ? sourceUrl.trim() : null,
sourceUrl: sourceType === 'url' ? (sourceUrl.trim() || null) : null, note: note.trim() ? note.trim() : null
note: note.trim() ? note.trim() : null,
sourceNote: sourceNote.trim() ? sourceNote.trim() : null,
observedAt: observedAt ? new Date(observedAt).toISOString() : undefined,
isPrimary
}); });
setAmount(''); setAmount('');
setSourceUrl(''); setSourceUrl('');
setNote(''); setNote('');
setSourceNote('');
setObservedAt('');
setIsPrimary(true);
} catch (error) { } catch (error) {
setFormError((error as Error).message); setFormError((error as Error).message);
} }
@@ -130,7 +118,6 @@ export function ItemPricesPanel({ itemId }: ItemPricesPanelProps) {
</div> </div>
</div> </div>
<div className="flex items-center gap-3">
<div className="flex flex-col gap-1.5"> <div className="flex flex-col gap-1.5">
<label className="text-xs font-medium text-slate-600" htmlFor={`price-currency-${itemId}`}> <label className="text-xs font-medium text-slate-600" htmlFor={`price-currency-${itemId}`}>
Currency Currency
@@ -147,53 +134,6 @@ export function ItemPricesPanel({ itemId }: ItemPricesPanelProps) {
/> />
</div> </div>
<div className="flex items-center gap-2 pt-5">
<input
id={`price-primary-${itemId}`}
type="checkbox"
checked={isPrimary}
onChange={(event) => setIsPrimary(event.target.checked)}
className="h-4 w-4 rounded border-slate-300 text-blue-600 focus:ring-blue-500"
/>
<label className="text-xs font-medium text-slate-600" htmlFor={`price-primary-${itemId}`}>
Mark as current best price
</label>
</div>
</div>
<div className="grid grid-cols-2 gap-3">
<div className="flex flex-col gap-1.5">
<label className="text-xs font-medium text-slate-600" htmlFor={`price-source-type-${itemId}`}>
Source Type
</label>
<select
id={`price-source-type-${itemId}`}
value={sourceType}
onChange={(event) => setSourceType(event.target.value as PriceSourceType)}
className="rounded-md border border-slate-300 px-2 py-2 text-sm shadow-sm focus:border-blue-500 focus:outline-none focus:ring-2 focus:ring-blue-200"
>
{priceSourceOptions.map((option) => (
<option key={option} value={option}>
{option}
</option>
))}
</select>
</div>
<div className="flex flex-col gap-1.5">
<label className="text-xs font-medium text-slate-600" htmlFor={`price-observed-${itemId}`}>
Observed At
</label>
<input
id={`price-observed-${itemId}`}
type="datetime-local"
value={observedAt}
onChange={(event) => setObservedAt(event.target.value)}
className="rounded-md border border-slate-300 px-2 py-2 text-sm shadow-sm focus:border-blue-500 focus:outline-none focus:ring-2 focus:ring-blue-200"
/>
</div>
</div>
{sourceType === 'url' ? (
<div className="flex flex-col gap-1.5"> <div className="flex flex-col gap-1.5">
<label className="text-xs font-medium text-slate-600" htmlFor={`price-source-url-${itemId}`}> <label className="text-xs font-medium text-slate-600" htmlFor={`price-source-url-${itemId}`}>
Source URL Source URL
@@ -205,22 +145,6 @@ export function ItemPricesPanel({ itemId }: ItemPricesPanelProps) {
onChange={(event) => setSourceUrl(event.target.value)} onChange={(event) => setSourceUrl(event.target.value)}
className="rounded-md border border-slate-300 px-2 py-2 text-sm shadow-sm focus:border-blue-500 focus:outline-none focus:ring-2 focus:ring-blue-200" className="rounded-md border border-slate-300 px-2 py-2 text-sm shadow-sm focus:border-blue-500 focus:outline-none focus:ring-2 focus:ring-blue-200"
placeholder="https://shop.example.com/deal" placeholder="https://shop.example.com/deal"
required
/>
</div>
) : null}
<div className="flex flex-col gap-1.5">
<label className="text-xs font-medium text-slate-600" htmlFor={`price-source-note-${itemId}`}>
Source Note
</label>
<input
id={`price-source-note-${itemId}`}
type="text"
value={sourceNote}
onChange={(event) => setSourceNote(event.target.value)}
className="rounded-md border border-slate-300 px-2 py-2 text-sm shadow-sm focus:border-blue-500 focus:outline-none focus:ring-2 focus:ring-blue-200"
placeholder="Amazon seller"
/> />
</div> </div>
@@ -263,20 +187,11 @@ export function ItemPricesPanel({ itemId }: ItemPricesPanelProps) {
<span className="font-semibold text-slate-900"> <span className="font-semibold text-slate-900">
{price.condition} {price.amount.toFixed(2)} {price.currency} {price.condition} {price.amount.toFixed(2)} {price.currency}
</span> </span>
{price.isPrimary ? (
<span className="rounded-full bg-blue-50 px-3 py-1 text-xs font-semibold uppercase tracking-wide text-blue-600">
Primary
</span>
) : null}
</header> </header>
<dl className="mt-2 space-y-1 text-xs text-slate-600"> <dl className="mt-2 space-y-1 text-xs text-slate-600">
<div>
<dt className="font-medium text-slate-500">Source</dt>
<dd className="capitalize">{price.sourceType}</dd>
</div>
{price.sourceUrl ? ( {price.sourceUrl ? (
<div> <div>
<dt className="font-medium text-slate-500">URL</dt> <dt className="font-medium text-slate-500">Source URL</dt>
<dd> <dd>
<a <a
href={price.sourceUrl} href={price.sourceUrl}
@@ -289,12 +204,6 @@ export function ItemPricesPanel({ itemId }: ItemPricesPanelProps) {
</dd> </dd>
</div> </div>
) : null} ) : null}
{price.sourceNote ? (
<div>
<dt className="font-medium text-slate-500">Source Note</dt>
<dd>{price.sourceNote}</dd>
</div>
) : null}
{price.note ? ( {price.note ? (
<div> <div>
<dt className="font-medium text-slate-500">Notes</dt> <dt className="font-medium text-slate-500">Notes</dt>
@@ -302,9 +211,15 @@ export function ItemPricesPanel({ itemId }: ItemPricesPanelProps) {
</div> </div>
) : null} ) : null}
<div> <div>
<dt className="font-medium text-slate-500">Observed</dt> <dt className="font-medium text-slate-500">Created</dt>
<dd>{new Date(price.observedAt).toLocaleString()}</dd> <dd>{new Date(price.createdAt).toLocaleString()}</dd>
</div> </div>
{price.updatedAt !== price.createdAt ? (
<div>
<dt className="font-medium text-slate-500">Updated</dt>
<dd>{new Date(price.updatedAt).toLocaleString()}</dd>
</div>
) : null}
</dl> </dl>
</article> </article>
))} ))}
@@ -43,13 +43,10 @@ export const createItemPrice = async (req: Request, res: Response) => {
const itemId = parseUuid(req.params.itemId, 'itemId'); const itemId = parseUuid(req.params.itemId, 'itemId');
const payload = parseItemPriceCreatePayload(req.body); const payload = parseItemPriceCreatePayload(req.body);
let sourceUrlId: string | null = null; const sourceUrlId = await resolveUrlId({
if (payload.sourceType === 'url') {
sourceUrlId = await resolveUrlId({
sourceUrlId: payload.sourceUrlId, sourceUrlId: payload.sourceUrlId,
sourceUrl: payload.sourceUrl sourceUrl: payload.sourceUrl
}); });
}
try { try {
const price = await createItemPriceRepo({ const price = await createItemPriceRepo({
@@ -57,12 +54,8 @@ export const createItemPrice = async (req: Request, res: Response) => {
condition: payload.condition, condition: payload.condition,
amount: payload.amount, amount: payload.amount,
currency: payload.currency, currency: payload.currency,
sourceType: payload.sourceType,
sourceUrlId, sourceUrlId,
sourceNote: payload.sourceNote, note: payload.note
note: payload.note,
observedAt: payload.observedAt,
isPrimary: payload.isPrimary
}); });
res.status(201).json({ data: price }); res.status(201).json({ data: price });
@@ -106,9 +99,7 @@ export const updateItemPrice = async (req: Request, res: Response) => {
'sourceUrlId' 'sourceUrlId'
); );
if (payload.sourceType === 'manual') { if (hasSourceUrlField || hasSourceUrlIdField) {
sourceUrlId = null;
} else if (payload.sourceType === 'url' || hasSourceUrlField || hasSourceUrlIdField) {
sourceUrlId = await resolveUrlId({ sourceUrlId = await resolveUrlId({
sourceUrlId: payload.sourceUrlId ?? null, sourceUrlId: payload.sourceUrlId ?? null,
sourceUrl: payload.sourceUrl ?? null sourceUrl: payload.sourceUrl ?? null
@@ -119,12 +110,8 @@ export const updateItemPrice = async (req: Request, res: Response) => {
condition: payload.condition, condition: payload.condition,
amount: payload.amount, amount: payload.amount,
currency: payload.currency, currency: payload.currency,
sourceType: payload.sourceType,
sourceUrlId, sourceUrlId,
sourceNote: payload.sourceNote, note: payload.note
note: payload.note,
observedAt: payload.observedAt,
isPrimary: payload.isPrimary
}); });
if (!price) { if (!price) {
+11 -1
View File
@@ -1,4 +1,8 @@
import { createUrl, findUrlById } from '../db/urls-repository.js'; import {
createUrl,
findUrlById,
findUrlByValue
} from '../db/urls-repository.js';
import { HttpError } from '../errors/http-error.js'; import { HttpError } from '../errors/http-error.js';
import { normalizeUrl } from '../utils/url-normalizer.js'; import { normalizeUrl } from '../utils/url-normalizer.js';
@@ -10,8 +14,14 @@ export const resolveUrlId = async (params: {
if (params.sourceUrl) { if (params.sourceUrl) {
const normalized = normalizeUrl(params.sourceUrl); const normalized = normalizeUrl(params.sourceUrl);
const existing = await findUrlByValue(normalized);
if (existing) {
urlId = existing.id;
} else {
const url = await createUrl({ url: normalized }); const url = await createUrl({ url: normalized });
urlId = url.id; urlId = url.id;
}
} else if (urlId) { } else if (urlId) {
const existing = await findUrlById(urlId); const existing = await findUrlById(urlId);
if (!existing) { if (!existing) {
+5 -75
View File
@@ -1,4 +1,4 @@
import type { ItemPrice, PriceCondition, PriceSourceType } from '@shared/models/item-price'; import type { ItemPrice, PriceCondition } from '@shared/models/item-price';
import { pool, query } from './pool.js'; import { pool, query } from './pool.js';
const priceColumns = ` const priceColumns = `
@@ -7,12 +7,8 @@ const priceColumns = `
p.condition, p.condition,
p.amount, p.amount,
p.currency, p.currency,
p.source_type,
p.source_url_id, p.source_url_id,
p.source_note,
p.note, p.note,
p.observed_at,
p.is_primary,
p.created_at, p.created_at,
p.updated_at, p.updated_at,
u.url AS source_url u.url AS source_url
@@ -24,12 +20,8 @@ export interface ItemPriceRow {
condition: PriceCondition; condition: PriceCondition;
amount: string; amount: string;
currency: string; currency: string;
source_type: PriceSourceType;
source_url_id: string | null; source_url_id: string | null;
source_note: string | null;
note: string | null; note: string | null;
observed_at: Date;
is_primary: boolean;
created_at: Date; created_at: Date;
updated_at: Date; updated_at: Date;
source_url: string | null; source_url: string | null;
@@ -43,13 +35,9 @@ const mapItemPriceRow = (row: ItemPriceRow): ItemPriceRecord => ({
condition: row.condition, condition: row.condition,
amount: Number(row.amount), amount: Number(row.amount),
currency: row.currency, currency: row.currency,
sourceType: row.source_type,
sourceUrlId: row.source_url_id, sourceUrlId: row.source_url_id,
sourceUrl: row.source_url, sourceUrl: row.source_url,
sourceNote: row.source_note,
note: row.note, note: row.note,
observedAt: row.observed_at.toISOString(),
isPrimary: row.is_primary,
createdAt: row.created_at.toISOString(), createdAt: row.created_at.toISOString(),
updatedAt: row.updated_at.toISOString() updatedAt: row.updated_at.toISOString()
}); });
@@ -83,7 +71,7 @@ export const listItemPrices = async (
FROM item_prices p FROM item_prices p
LEFT JOIN urls u ON u.id = p.source_url_id LEFT JOIN urls u ON u.id = p.source_url_id
WHERE ${filters.join(' AND ')} WHERE ${filters.join(' AND ')}
ORDER BY p.observed_at DESC ORDER BY p.created_at DESC
LIMIT $${limitIndex} LIMIT $${limitIndex}
OFFSET $${offsetIndex} OFFSET $${offsetIndex}
`, `,
@@ -98,12 +86,8 @@ export interface CreateItemPriceParams {
condition: PriceCondition; condition: PriceCondition;
amount: number; amount: number;
currency: string; currency: string;
sourceType: PriceSourceType;
sourceUrlId: string | null; sourceUrlId: string | null;
sourceNote: string | null;
note: string | null; note: string | null;
observedAt?: string;
isPrimary: boolean;
} }
export const createItemPrice = async ( export const createItemPrice = async (
@@ -113,17 +97,6 @@ export const createItemPrice = async (
try { try {
await client.query('BEGIN'); await client.query('BEGIN');
if (params.isPrimary) {
await client.query(
`
UPDATE item_prices
SET is_primary = FALSE
WHERE item_id = $1 AND condition = $2
`,
[params.itemId, params.condition]
);
}
const result = await client.query<{ id: string }>( const result = await client.query<{ id: string }>(
` `
INSERT INTO item_prices ( INSERT INTO item_prices (
@@ -131,14 +104,10 @@ export const createItemPrice = async (
condition, condition,
amount, amount,
currency, currency,
source_type,
source_url_id, source_url_id,
source_note, note
note,
observed_at,
is_primary
) )
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, COALESCE($9, NOW()), $10) VALUES ($1, $2, $3, $4, $5, $6)
RETURNING id RETURNING id
`, `,
[ [
@@ -146,12 +115,8 @@ export const createItemPrice = async (
params.condition, params.condition,
params.amount, params.amount,
params.currency, params.currency,
params.sourceType,
params.sourceUrlId, params.sourceUrlId,
params.sourceNote, params.note
params.note,
params.observedAt ?? null,
params.isPrimary
] ]
); );
@@ -202,12 +167,8 @@ export interface UpdateItemPriceParams {
condition?: PriceCondition; condition?: PriceCondition;
amount?: number; amount?: number;
currency?: string; currency?: string;
sourceType?: PriceSourceType;
sourceUrlId?: string | null; sourceUrlId?: string | null;
sourceNote?: string | null;
note?: string | null; note?: string | null;
observedAt?: string;
isPrimary?: boolean;
} }
export const updateItemPrice = async ( export const updateItemPrice = async (
@@ -234,7 +195,6 @@ export const updateItemPrice = async (
return null; return null;
} }
const existing = existingResult.rows[0];
const fields: string[] = []; const fields: string[] = [];
const values: unknown[] = []; const values: unknown[] = [];
@@ -250,30 +210,14 @@ export const updateItemPrice = async (
values.push(params.currency); values.push(params.currency);
fields.push(`currency = $${values.length}`); fields.push(`currency = $${values.length}`);
} }
if (params.sourceType !== undefined) {
values.push(params.sourceType);
fields.push(`source_type = $${values.length}`);
}
if (params.sourceUrlId !== undefined) { if (params.sourceUrlId !== undefined) {
values.push(params.sourceUrlId); values.push(params.sourceUrlId);
fields.push(`source_url_id = $${values.length}`); fields.push(`source_url_id = $${values.length}`);
} }
if (params.sourceNote !== undefined) {
values.push(params.sourceNote);
fields.push(`source_note = $${values.length}`);
}
if (params.note !== undefined) { if (params.note !== undefined) {
values.push(params.note); values.push(params.note);
fields.push(`note = $${values.length}`); fields.push(`note = $${values.length}`);
} }
if (params.observedAt !== undefined) {
values.push(params.observedAt);
fields.push(`observed_at = COALESCE($${values.length}, NOW())`);
}
if (params.isPrimary !== undefined) {
values.push(params.isPrimary);
fields.push(`is_primary = $${values.length}`);
}
if (fields.length > 0) { if (fields.length > 0) {
values.push(id); values.push(id);
@@ -289,20 +233,6 @@ export const updateItemPrice = async (
); );
} }
const newCondition = params.condition ?? existing.condition;
const newIsPrimary = params.isPrimary ?? existing.is_primary;
if (newIsPrimary) {
await client.query(
`
UPDATE item_prices
SET is_primary = FALSE
WHERE item_id = $1 AND condition = $2 AND id <> $3
`,
[existing.item_id, newCondition, id]
);
}
const updatedResult = await client.query<ItemPriceRow>( const updatedResult = await client.query<ItemPriceRow>(
` `
SELECT ${priceColumns} SELECT ${priceColumns}
+9 -1
View File
@@ -212,7 +212,15 @@ export const getItemById = async (id: string): Promise<ItemRecord | null> => {
MAX(ip.amount) AS max_amount, MAX(ip.amount) AS max_amount,
COUNT(*)::INT AS total_count, COUNT(*)::INT AS total_count,
COUNT(DISTINCT ip.currency)::INT AS currency_count, COUNT(DISTINCT ip.currency)::INT AS currency_count,
MIN(ip.currency) AS currency MIN(ip.currency) AS currency,
MIN(CASE WHEN ip.condition = 'new' THEN ip.amount END) AS min_new_amount,
COUNT(CASE WHEN ip.condition = 'new' THEN 1 END)::INT AS new_count,
COUNT(DISTINCT CASE WHEN ip.condition = 'new' THEN ip.currency END)::INT AS new_currency_count,
MIN(CASE WHEN ip.condition = 'new' THEN ip.currency END) AS new_currency,
MIN(CASE WHEN ip.condition = 'used' THEN ip.amount END) AS min_used_amount,
COUNT(CASE WHEN ip.condition = 'used' THEN 1 END)::INT AS used_count,
COUNT(DISTINCT CASE WHEN ip.condition = 'used' THEN ip.currency END)::INT AS used_currency_count,
MIN(CASE WHEN ip.condition = 'used' THEN ip.currency END) AS used_currency
FROM item_prices ip FROM item_prices ip
WHERE ip.item_id = i.id WHERE ip.item_id = i.id
) price_summary ON TRUE ) price_summary ON TRUE
@@ -14,15 +14,6 @@ export const migration: Migration = {
END$$; END$$;
`); `);
await client.query(`
DO $$
BEGIN
CREATE TYPE price_source AS ENUM ('url', 'manual');
EXCEPTION
WHEN duplicate_object THEN NULL;
END$$;
`);
await client.query(` await client.query(`
CREATE TABLE IF NOT EXISTS item_prices ( CREATE TABLE IF NOT EXISTS item_prices (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(), id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
@@ -30,19 +21,11 @@ export const migration: Migration = {
condition price_condition NOT NULL, condition price_condition NOT NULL,
amount NUMERIC(12, 2) NOT NULL CHECK (amount >= 0), amount NUMERIC(12, 2) NOT NULL CHECK (amount >= 0),
currency CHAR(3) NOT NULL, currency CHAR(3) NOT NULL,
source_type price_source NOT NULL,
source_url_id UUID REFERENCES urls(id) ON DELETE SET NULL, source_url_id UUID REFERENCES urls(id) ON DELETE SET NULL,
source_note TEXT,
note TEXT, note TEXT,
observed_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
is_primary BOOLEAN NOT NULL DEFAULT FALSE,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
CHECK (char_length(currency) = 3), CHECK (char_length(currency) = 3)
CHECK (
(source_type = 'manual'::price_source AND source_url_id IS NULL)
OR (source_type = 'url'::price_source AND source_url_id IS NOT NULL)
)
); );
`); `);
@@ -53,15 +36,5 @@ export const migration: Migration = {
await client.query(` await client.query(`
CREATE INDEX IF NOT EXISTS item_prices_source_url_id_idx ON item_prices (source_url_id); CREATE INDEX IF NOT EXISTS item_prices_source_url_id_idx ON item_prices (source_url_id);
`); `);
await client.query(`
CREATE INDEX IF NOT EXISTS item_prices_observed_at_idx ON item_prices (observed_at);
`);
await client.query(`
CREATE UNIQUE INDEX IF NOT EXISTS item_prices_primary_condition_idx
ON item_prices (item_id, condition)
WHERE is_primary = TRUE;
`);
} }
}; };
+1
View File
@@ -2,6 +2,7 @@ import type { ErrorRequestHandler } from 'express';
import { HttpError } from '../errors/http-error.js'; import { HttpError } from '../errors/http-error.js';
export const errorHandler: ErrorRequestHandler = (error, _req, res, _next) => { export const errorHandler: ErrorRequestHandler = (error, _req, res, _next) => {
void _next;
if (error instanceof HttpError) { if (error instanceof HttpError) {
res.status(error.status).json({ res.status(error.status).json({
error: { error: {
+20 -140
View File
@@ -1,18 +1,12 @@
import type { PriceCondition, PriceSourceType } from '@shared/models/item-price'; import type { PriceCondition } from '@shared/models/item-price';
import { HttpError } from '../errors/http-error.js'; import { HttpError } from '../errors/http-error.js';
import { parseUuid } from './common.js'; import { parseUuid } from './common.js';
const priceConditions = new Set<PriceCondition>(['new', 'used']); const priceConditions = new Set<PriceCondition>(['new', 'used']);
const priceSources = new Set<PriceSourceType>(['url', 'manual']);
const isPriceCondition = (value: unknown): value is PriceCondition => { const isPriceCondition = (value: unknown): value is PriceCondition => {
return typeof value === 'string' && priceConditions.has(value as PriceCondition); return typeof value === 'string' && priceConditions.has(value as PriceCondition);
}; };
const isPriceSourceType = (value: unknown): value is PriceSourceType => {
return typeof value === 'string' && priceSources.has(value as PriceSourceType);
};
const normalizeCurrency = (value: unknown): string => { const normalizeCurrency = (value: unknown): string => {
if (typeof value !== 'string' || value.trim().length !== 3) { if (typeof value !== 'string' || value.trim().length !== 3) {
throw new HttpError(400, 'currency must be a 3-letter code'); throw new HttpError(400, 'currency must be a 3-letter code');
@@ -20,34 +14,13 @@ const normalizeCurrency = (value: unknown): string => {
return value.trim().toUpperCase(); return value.trim().toUpperCase();
}; };
const parseObservedAt = (value: unknown): string | undefined => {
if (value === undefined) {
return undefined;
}
if (value === null) {
throw new HttpError(400, 'observedAt cannot be null');
}
if (typeof value !== 'string') {
throw new HttpError(400, 'observedAt must be an ISO datetime string');
}
const date = new Date(value);
if (Number.isNaN(date.valueOf())) {
throw new HttpError(400, 'observedAt must be a valid ISO datetime string');
}
return date.toISOString();
};
export interface ItemPriceCreateInput { export interface ItemPriceCreateInput {
condition: PriceCondition; condition: PriceCondition;
amount: number; amount: number;
currency: string; currency: string;
sourceType: PriceSourceType;
sourceUrlId: string | null; sourceUrlId: string | null;
sourceUrl: string | null; sourceUrl: string | null;
sourceNote: string | null;
note: string | null; note: string | null;
observedAt: string | undefined;
isPrimary: boolean;
} }
export type ItemPriceUpdateInput = Partial<ItemPriceCreateInput>; export type ItemPriceUpdateInput = Partial<ItemPriceCreateInput>;
@@ -59,12 +32,19 @@ const parseAmount = (value: unknown): number => {
return value; return value;
}; };
const parseSourceNote = (value: unknown): string | null => { const parseSourceUrlId = (value: unknown): string | null => {
if (value === undefined || value === null) { if (value === undefined || value === null) {
return null; return null;
} }
if (typeof value !== 'string') { return parseUuid(value, 'sourceUrlId');
throw new HttpError(400, 'sourceNote must be a string or null'); };
const parseSourceUrl = (value: unknown): string | null => {
if (value === undefined || value === null) {
return null;
}
if (typeof value !== 'string' || value.trim().length === 0) {
throw new HttpError(400, 'sourceUrl must be a non-empty string');
} }
return value; return value;
}; };
@@ -79,60 +59,6 @@ const parseNote = (value: unknown): string | null => {
return value; return value;
}; };
const parseIsPrimary = (value: unknown): boolean => {
if (value === undefined) {
return false;
}
if (typeof value !== 'boolean') {
throw new HttpError(400, 'isPrimary must be a boolean');
}
return value;
};
const parseSourceFields = (
sourceType: PriceSourceType,
sourceUrlIdValue: unknown,
sourceUrlValue: unknown
): { sourceUrlId: string | null; sourceUrl: string | null } => {
if (sourceType === 'manual') {
if (sourceUrlIdValue !== undefined && sourceUrlIdValue !== null) {
throw new HttpError(
400,
'sourceUrlId cannot be provided when sourceType is manual'
);
}
if (sourceUrlValue !== undefined && sourceUrlValue !== null) {
throw new HttpError(
400,
'sourceUrl cannot be provided when sourceType is manual'
);
}
return { sourceUrlId: null, sourceUrl: null };
}
let sourceUrlId: string | null = null;
if (sourceUrlIdValue !== undefined && sourceUrlIdValue !== null) {
sourceUrlId = parseUuid(sourceUrlIdValue, 'sourceUrlId');
}
let sourceUrl: string | null = null;
if (sourceUrlValue !== undefined && sourceUrlValue !== null) {
if (typeof sourceUrlValue !== 'string' || sourceUrlValue.trim().length === 0) {
throw new HttpError(400, 'sourceUrl must be a non-empty string');
}
sourceUrl = sourceUrlValue;
}
if (!sourceUrlId && !sourceUrl) {
throw new HttpError(
400,
'sourceUrl or sourceUrlId must be provided when sourceType is url'
);
}
return { sourceUrlId, sourceUrl };
};
export const parseItemPriceCreatePayload = ( export const parseItemPriceCreatePayload = (
payload: unknown payload: unknown
): ItemPriceCreateInput => { ): ItemPriceCreateInput => {
@@ -144,40 +70,22 @@ export const parseItemPriceCreatePayload = (
condition, condition,
amount, amount,
currency, currency,
sourceType,
sourceUrlId, sourceUrlId,
sourceUrl, sourceUrl,
sourceNote, note
note,
observedAt,
isPrimary
} = payload as Record<string, unknown>; } = payload as Record<string, unknown>;
if (!isPriceCondition(condition)) { if (!isPriceCondition(condition)) {
throw new HttpError(400, 'condition must be one of new, used'); throw new HttpError(400, 'condition must be one of new, used');
} }
if (!isPriceSourceType(sourceType)) {
throw new HttpError(400, 'sourceType must be one of url, manual');
}
const source = parseSourceFields(
sourceType,
sourceUrlId,
sourceUrl
);
return { return {
condition, condition,
amount: parseAmount(amount), amount: parseAmount(amount),
currency: normalizeCurrency(currency), currency: normalizeCurrency(currency),
sourceType, sourceUrlId: parseSourceUrlId(sourceUrlId),
sourceUrlId: source.sourceUrlId, sourceUrl: parseSourceUrl(sourceUrl),
sourceUrl: source.sourceUrl, note: parseNote(note)
sourceNote: parseSourceNote(sourceNote),
note: parseNote(note),
observedAt: parseObservedAt(observedAt),
isPrimary: parseIsPrimary(isPrimary)
}; };
}; };
@@ -193,13 +101,9 @@ export const parseItemPriceUpdatePayload = (
condition, condition,
amount, amount,
currency, currency,
sourceType,
sourceUrlId, sourceUrlId,
sourceUrl, sourceUrl,
sourceNote, note
note,
observedAt,
isPrimary
} = payload as Record<string, unknown>; } = payload as Record<string, unknown>;
if (condition !== undefined) { if (condition !== undefined) {
@@ -217,42 +121,18 @@ export const parseItemPriceUpdatePayload = (
result.currency = normalizeCurrency(currency); result.currency = normalizeCurrency(currency);
} }
if (sourceType !== undefined) { if (sourceUrlId !== undefined) {
if (!isPriceSourceType(sourceType)) { result.sourceUrlId = parseSourceUrlId(sourceUrlId);
throw new HttpError(400, 'sourceType must be one of url, manual');
}
result.sourceType = sourceType;
} }
if (sourceUrlId !== undefined || sourceUrl !== undefined) { if (sourceUrl !== undefined) {
const type = result.sourceType ?? (isPriceSourceType(sourceType) ? sourceType : undefined); result.sourceUrl = parseSourceUrl(sourceUrl);
if (!type) {
throw new HttpError(
400,
'sourceType must be provided when changing sourceUrl or sourceUrlId'
);
}
const parsed = parseSourceFields(type, sourceUrlId, sourceUrl);
result.sourceUrlId = parsed.sourceUrlId;
result.sourceUrl = parsed.sourceUrl;
}
if (sourceNote !== undefined) {
result.sourceNote = parseSourceNote(sourceNote);
} }
if (note !== undefined) { if (note !== undefined) {
result.note = parseNote(note); result.note = parseNote(note);
} }
if (observedAt !== undefined) {
result.observedAt = parseObservedAt(observedAt);
}
if (isPrimary !== undefined) {
result.isPrimary = parseIsPrimary(isPrimary);
}
if (Object.keys(result).length === 0) { if (Object.keys(result).length === 0) {
throw new HttpError(400, 'At least one field must be provided for update'); throw new HttpError(400, 'At least one field must be provided for update');
} }
+14
View File
@@ -0,0 +1,14 @@
export type PriceCondition = 'new' | 'used';
export interface ItemPrice {
id: string;
itemId: string;
condition: PriceCondition;
amount: number;
currency: string;
sourceUrlId: string | null;
sourceUrl: string | null;
note: string | null;
createdAt: string;
updatedAt: string;
}
+32
View File
@@ -0,0 +1,32 @@
export type ItemStatus = 'active' | 'rejected';
export interface ItemPriceSummary {
minAmount: number;
maxAmount: number;
currency: string | null;
priceCount: number;
hasMixedCurrency: boolean;
newMinAmount: number | null;
newCount: number;
newCurrency: string | null;
newHasMixedCurrency: boolean;
usedMinAmount: number | null;
usedCount: number;
usedCurrency: string | null;
usedHasMixedCurrency: boolean;
}
export interface Item {
id: string;
projectId: string;
manufacturer: string | null;
model: string;
sourceUrlId: string | null;
sourceUrl: string | null;
status: ItemStatus;
note: string | null;
attributes: Record<string, unknown>;
createdAt: string;
updatedAt: string;
priceSummary: ItemPriceSummary | null;
}
+10
View File
@@ -0,0 +1,10 @@
export interface PaginationMeta {
limit: number;
offset: number;
count: number;
}
export interface PaginatedResponse<T> {
data: T[];
meta: PaginationMeta;
}
+12
View File
@@ -0,0 +1,12 @@
export type ProjectStatus = 'active' | 'archived';
export interface Project {
id: string;
name: string;
description: string | null;
status: ProjectStatus;
attributes: string[];
priorityRules: unknown;
createdAt: string;
updatedAt: string;
}