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
@@ -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');
}