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 {
ItemPrice,
PriceCondition,
PriceSourceType
} from '@shared/models/item-price';
import type { ItemPrice, PriceCondition } from '@shared/models/item-price';
import { apiFetch } from './http-client';
export type { PriceCondition, PriceSourceType };
export type { PriceCondition };
export type ItemPricesResponse = PaginatedResponse<ItemPrice>;
@@ -47,13 +43,9 @@ export interface CreateItemPricePayload {
condition: PriceCondition;
amount: number;
currency: string;
sourceType: PriceSourceType;
sourceUrl?: string | null;
sourceUrlId?: string | null;
sourceNote?: string | null;
note?: string | null;
observedAt?: string;
isPrimary?: boolean;
}
interface SingleItemPriceResponse {
@@ -72,13 +64,9 @@ export const createItemPrice = async (
condition: payload.condition,
amount: payload.amount,
currency: payload.currency,
sourceType: payload.sourceType,
sourceUrl: payload.sourceUrl ?? null,
sourceUrlId: payload.sourceUrlId ?? null,
sourceNote: payload.sourceNote ?? null,
note: payload.note ?? null,
observedAt: payload.observedAt ?? null,
isPrimary: payload.isPrimary ?? false
note: payload.note ?? null
}
}
);
@@ -1,9 +1,8 @@
import { FormEvent, useMemo, useState } from 'react';
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 priceSourceOptions: PriceSourceType[] = ['url', 'manual'];
interface ItemPricesPanelProps {
itemId: string;
@@ -13,12 +12,8 @@ export function ItemPricesPanel({ itemId }: ItemPricesPanelProps) {
const [condition, setCondition] = useState<PriceCondition>('new');
const [amount, setAmount] = useState('');
const [currency, setCurrency] = useState('USD');
const [sourceType, setSourceType] = useState<PriceSourceType>('manual');
const [sourceUrl, setSourceUrl] = 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 pricesQuery = useItemPricesQuery(itemId, true);
@@ -46,20 +41,13 @@ export function ItemPricesPanel({ itemId }: ItemPricesPanelProps) {
condition,
amount: parsedAmount,
currency: currency.trim().toUpperCase(),
sourceType,
sourceUrl: sourceType === 'url' ? (sourceUrl.trim() || null) : null,
note: note.trim() ? note.trim() : null,
sourceNote: sourceNote.trim() ? sourceNote.trim() : null,
observedAt: observedAt ? new Date(observedAt).toISOString() : undefined,
isPrimary
sourceUrl: sourceUrl.trim() ? sourceUrl.trim() : null,
note: note.trim() ? note.trim() : null
});
setAmount('');
setSourceUrl('');
setNote('');
setSourceNote('');
setObservedAt('');
setIsPrimary(true);
} catch (error) {
setFormError((error as Error).message);
}
@@ -130,97 +118,33 @@ export function ItemPricesPanel({ itemId }: ItemPricesPanelProps) {
</div>
</div>
<div className="flex items-center gap-3">
<div className="flex flex-col gap-1.5">
<label className="text-xs font-medium text-slate-600" htmlFor={`price-currency-${itemId}`}>
Currency
</label>
<input
id={`price-currency-${itemId}`}
type="text"
value={currency}
onChange={(event) => setCurrency(event.target.value.toUpperCase())}
maxLength={3}
className="uppercase 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="USD"
required
/>
</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">
<label className="text-xs font-medium text-slate-600" htmlFor={`price-source-url-${itemId}`}>
Source URL
</label>
<input
id={`price-source-url-${itemId}`}
type="url"
value={sourceUrl}
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"
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 className="text-xs font-medium text-slate-600" htmlFor={`price-currency-${itemId}`}>
Currency
</label>
<input
id={`price-source-note-${itemId}`}
id={`price-currency-${itemId}`}
type="text"
value={sourceNote}
onChange={(event) => setSourceNote(event.target.value)}
value={currency}
onChange={(event) => setCurrency(event.target.value.toUpperCase())}
maxLength={3}
className="uppercase 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="USD"
required
/>
</div>
<div className="flex flex-col gap-1.5">
<label className="text-xs font-medium text-slate-600" htmlFor={`price-source-url-${itemId}`}>
Source URL
</label>
<input
id={`price-source-url-${itemId}`}
type="url"
value={sourceUrl}
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"
placeholder="Amazon seller"
placeholder="https://shop.example.com/deal"
/>
</div>
@@ -263,20 +187,11 @@ export function ItemPricesPanel({ itemId }: ItemPricesPanelProps) {
<span className="font-semibold text-slate-900">
{price.condition} {price.amount.toFixed(2)} {price.currency}
</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>
<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 ? (
<div>
<dt className="font-medium text-slate-500">URL</dt>
<dt className="font-medium text-slate-500">Source URL</dt>
<dd>
<a
href={price.sourceUrl}
@@ -289,12 +204,6 @@ export function ItemPricesPanel({ itemId }: ItemPricesPanelProps) {
</dd>
</div>
) : null}
{price.sourceNote ? (
<div>
<dt className="font-medium text-slate-500">Source Note</dt>
<dd>{price.sourceNote}</dd>
</div>
) : null}
{price.note ? (
<div>
<dt className="font-medium text-slate-500">Notes</dt>
@@ -302,9 +211,15 @@ export function ItemPricesPanel({ itemId }: ItemPricesPanelProps) {
</div>
) : null}
<div>
<dt className="font-medium text-slate-500">Observed</dt>
<dd>{new Date(price.observedAt).toLocaleString()}</dd>
<dt className="font-medium text-slate-500">Created</dt>
<dd>{new Date(price.createdAt).toLocaleString()}</dd>
</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>
</article>
))}
@@ -43,13 +43,10 @@ export const createItemPrice = async (req: Request, res: Response) => {
const itemId = parseUuid(req.params.itemId, 'itemId');
const payload = parseItemPriceCreatePayload(req.body);
let sourceUrlId: string | null = null;
if (payload.sourceType === 'url') {
sourceUrlId = await resolveUrlId({
sourceUrlId: payload.sourceUrlId,
sourceUrl: payload.sourceUrl
});
}
const sourceUrlId = await resolveUrlId({
sourceUrlId: payload.sourceUrlId,
sourceUrl: payload.sourceUrl
});
try {
const price = await createItemPriceRepo({
@@ -57,12 +54,8 @@ export const createItemPrice = async (req: Request, res: Response) => {
condition: payload.condition,
amount: payload.amount,
currency: payload.currency,
sourceType: payload.sourceType,
sourceUrlId,
sourceNote: payload.sourceNote,
note: payload.note,
observedAt: payload.observedAt,
isPrimary: payload.isPrimary
note: payload.note
});
res.status(201).json({ data: price });
@@ -106,9 +99,7 @@ export const updateItemPrice = async (req: Request, res: Response) => {
'sourceUrlId'
);
if (payload.sourceType === 'manual') {
sourceUrlId = null;
} else if (payload.sourceType === 'url' || hasSourceUrlField || hasSourceUrlIdField) {
if (hasSourceUrlField || hasSourceUrlIdField) {
sourceUrlId = await resolveUrlId({
sourceUrlId: payload.sourceUrlId ?? null,
sourceUrl: payload.sourceUrl ?? null
@@ -119,12 +110,8 @@ export const updateItemPrice = async (req: Request, res: Response) => {
condition: payload.condition,
amount: payload.amount,
currency: payload.currency,
sourceType: payload.sourceType,
sourceUrlId,
sourceNote: payload.sourceNote,
note: payload.note,
observedAt: payload.observedAt,
isPrimary: payload.isPrimary
note: payload.note
});
if (!price) {
+13 -3
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 { normalizeUrl } from '../utils/url-normalizer.js';
@@ -10,8 +14,14 @@ export const resolveUrlId = async (params: {
if (params.sourceUrl) {
const normalized = normalizeUrl(params.sourceUrl);
const url = await createUrl({ url: normalized });
urlId = url.id;
const existing = await findUrlByValue(normalized);
if (existing) {
urlId = existing.id;
} else {
const url = await createUrl({ url: normalized });
urlId = url.id;
}
} else if (urlId) {
const existing = await findUrlById(urlId);
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';
const priceColumns = `
@@ -7,12 +7,8 @@ const priceColumns = `
p.condition,
p.amount,
p.currency,
p.source_type,
p.source_url_id,
p.source_note,
p.note,
p.observed_at,
p.is_primary,
p.created_at,
p.updated_at,
u.url AS source_url
@@ -24,12 +20,8 @@ export interface ItemPriceRow {
condition: PriceCondition;
amount: string;
currency: string;
source_type: PriceSourceType;
source_url_id: string | null;
source_note: string | null;
note: string | null;
observed_at: Date;
is_primary: boolean;
created_at: Date;
updated_at: Date;
source_url: string | null;
@@ -43,13 +35,9 @@ const mapItemPriceRow = (row: ItemPriceRow): ItemPriceRecord => ({
condition: row.condition,
amount: Number(row.amount),
currency: row.currency,
sourceType: row.source_type,
sourceUrlId: row.source_url_id,
sourceUrl: row.source_url,
sourceNote: row.source_note,
note: row.note,
observedAt: row.observed_at.toISOString(),
isPrimary: row.is_primary,
createdAt: row.created_at.toISOString(),
updatedAt: row.updated_at.toISOString()
});
@@ -83,7 +71,7 @@ export const listItemPrices = async (
FROM item_prices p
LEFT JOIN urls u ON u.id = p.source_url_id
WHERE ${filters.join(' AND ')}
ORDER BY p.observed_at DESC
ORDER BY p.created_at DESC
LIMIT $${limitIndex}
OFFSET $${offsetIndex}
`,
@@ -98,12 +86,8 @@ export interface CreateItemPriceParams {
condition: PriceCondition;
amount: number;
currency: string;
sourceType: PriceSourceType;
sourceUrlId: string | null;
sourceNote: string | null;
note: string | null;
observedAt?: string;
isPrimary: boolean;
}
export const createItemPrice = async (
@@ -113,17 +97,6 @@ export const createItemPrice = async (
try {
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 }>(
`
INSERT INTO item_prices (
@@ -131,14 +104,10 @@ export const createItemPrice = async (
condition,
amount,
currency,
source_type,
source_url_id,
source_note,
note,
observed_at,
is_primary
note
)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, COALESCE($9, NOW()), $10)
VALUES ($1, $2, $3, $4, $5, $6)
RETURNING id
`,
[
@@ -146,12 +115,8 @@ export const createItemPrice = async (
params.condition,
params.amount,
params.currency,
params.sourceType,
params.sourceUrlId,
params.sourceNote,
params.note,
params.observedAt ?? null,
params.isPrimary
params.note
]
);
@@ -202,12 +167,8 @@ export interface UpdateItemPriceParams {
condition?: PriceCondition;
amount?: number;
currency?: string;
sourceType?: PriceSourceType;
sourceUrlId?: string | null;
sourceNote?: string | null;
note?: string | null;
observedAt?: string;
isPrimary?: boolean;
}
export const updateItemPrice = async (
@@ -234,7 +195,6 @@ export const updateItemPrice = async (
return null;
}
const existing = existingResult.rows[0];
const fields: string[] = [];
const values: unknown[] = [];
@@ -250,30 +210,14 @@ export const updateItemPrice = async (
values.push(params.currency);
fields.push(`currency = $${values.length}`);
}
if (params.sourceType !== undefined) {
values.push(params.sourceType);
fields.push(`source_type = $${values.length}`);
}
if (params.sourceUrlId !== undefined) {
values.push(params.sourceUrlId);
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) {
values.push(params.note);
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) {
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>(
`
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,
COUNT(*)::INT AS total_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
WHERE ip.item_id = i.id
) price_summary ON TRUE
@@ -14,15 +14,6 @@ export const migration: Migration = {
END$$;
`);
await client.query(`
DO $$
BEGIN
CREATE TYPE price_source AS ENUM ('url', 'manual');
EXCEPTION
WHEN duplicate_object THEN NULL;
END$$;
`);
await client.query(`
CREATE TABLE IF NOT EXISTS item_prices (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
@@ -30,19 +21,11 @@ export const migration: Migration = {
condition price_condition NOT NULL,
amount NUMERIC(12, 2) NOT NULL CHECK (amount >= 0),
currency CHAR(3) NOT NULL,
source_type price_source NOT NULL,
source_url_id UUID REFERENCES urls(id) ON DELETE SET NULL,
source_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(),
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
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)
)
CHECK (char_length(currency) = 3)
);
`);
@@ -53,15 +36,5 @@ export const migration: Migration = {
await client.query(`
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';
export const errorHandler: ErrorRequestHandler = (error, _req, res, _next) => {
void _next;
if (error instanceof HttpError) {
res.status(error.status).json({
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 { parseUuid } from './common.js';
const priceConditions = new Set<PriceCondition>(['new', 'used']);
const priceSources = new Set<PriceSourceType>(['url', 'manual']);
const isPriceCondition = (value: unknown): value is 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 => {
if (typeof value !== 'string' || value.trim().length !== 3) {
throw new HttpError(400, 'currency must be a 3-letter code');
@@ -20,34 +14,13 @@ const normalizeCurrency = (value: unknown): string => {
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 {
condition: PriceCondition;
amount: number;
currency: string;
sourceType: PriceSourceType;
sourceUrlId: string | null;
sourceUrl: string | null;
sourceNote: string | null;
note: string | null;
observedAt: string | undefined;
isPrimary: boolean;
}
export type ItemPriceUpdateInput = Partial<ItemPriceCreateInput>;
@@ -59,12 +32,19 @@ const parseAmount = (value: unknown): number => {
return value;
};
const parseSourceNote = (value: unknown): string | null => {
const parseSourceUrlId = (value: unknown): string | null => {
if (value === undefined || value === null) {
return null;
}
if (typeof value !== 'string') {
throw new HttpError(400, 'sourceNote must be a string or null');
return parseUuid(value, 'sourceUrlId');
};
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;
};
@@ -79,60 +59,6 @@ const parseNote = (value: unknown): string | null => {
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 = (
payload: unknown
): ItemPriceCreateInput => {
@@ -144,40 +70,22 @@ export const parseItemPriceCreatePayload = (
condition,
amount,
currency,
sourceType,
sourceUrlId,
sourceUrl,
sourceNote,
note,
observedAt,
isPrimary
note
} = payload as Record<string, unknown>;
if (!isPriceCondition(condition)) {
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 {
condition,
amount: parseAmount(amount),
currency: normalizeCurrency(currency),
sourceType,
sourceUrlId: source.sourceUrlId,
sourceUrl: source.sourceUrl,
sourceNote: parseSourceNote(sourceNote),
note: parseNote(note),
observedAt: parseObservedAt(observedAt),
isPrimary: parseIsPrimary(isPrimary)
sourceUrlId: parseSourceUrlId(sourceUrlId),
sourceUrl: parseSourceUrl(sourceUrl),
note: parseNote(note)
};
};
@@ -193,13 +101,9 @@ export const parseItemPriceUpdatePayload = (
condition,
amount,
currency,
sourceType,
sourceUrlId,
sourceUrl,
sourceNote,
note,
observedAt,
isPrimary
note
} = payload as Record<string, unknown>;
if (condition !== undefined) {
@@ -217,42 +121,18 @@ export const parseItemPriceUpdatePayload = (
result.currency = normalizeCurrency(currency);
}
if (sourceType !== undefined) {
if (!isPriceSourceType(sourceType)) {
throw new HttpError(400, 'sourceType must be one of url, manual');
}
result.sourceType = sourceType;
if (sourceUrlId !== undefined) {
result.sourceUrlId = parseSourceUrlId(sourceUrlId);
}
if (sourceUrlId !== undefined || sourceUrl !== undefined) {
const type = result.sourceType ?? (isPriceSourceType(sourceType) ? sourceType : undefined);
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 (sourceUrl !== undefined) {
result.sourceUrl = parseSourceUrl(sourceUrl);
}
if (note !== undefined) {
result.note = parseNote(note);
}
if (observedAt !== undefined) {
result.observedAt = parseObservedAt(observedAt);
}
if (isPrimary !== undefined) {
result.isPrimary = parseIsPrimary(isPrimary);
}
if (Object.keys(result).length === 0) {
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;
}