Add seller-owned pricing observation persistence, median market valuation calculation, admin routes, contracts, validation, migration, and focused tests.
This commit is contained in:
@@ -0,0 +1,43 @@
|
||||
import { and, desc, eq } from 'drizzle-orm';
|
||||
|
||||
import { inventoryItems, marketValuations, pricingObservations, products } from '../../../infrastructure/database/schema.js';
|
||||
|
||||
export function createPricingRepository(db) {
|
||||
return {
|
||||
async addObservationForSeller({ observation, sellerId }) {
|
||||
const [ownedItem] = await db
|
||||
.select({ id: inventoryItems.id, productId: inventoryItems.productId })
|
||||
.from(inventoryItems)
|
||||
.innerJoin(products, eq(products.id, inventoryItems.productId))
|
||||
.where(and(eq(inventoryItems.id, observation.inventoryItemId), eq(products.sellerId, sellerId)));
|
||||
if (!ownedItem || ownedItem.productId !== observation.productId) return { status: 'NOT_FOUND' };
|
||||
const [created] = await db.insert(pricingObservations).values(observation).returning();
|
||||
return { status: 'CREATED', observation: created };
|
||||
},
|
||||
|
||||
async calculateForSeller({ inventoryItemId, sellerId, strategy = 'MEDIAN' }) {
|
||||
const [ownedItem] = await db
|
||||
.select({ id: inventoryItems.id })
|
||||
.from(inventoryItems)
|
||||
.innerJoin(products, eq(products.id, inventoryItems.productId))
|
||||
.where(and(eq(inventoryItems.id, inventoryItemId), eq(products.sellerId, sellerId)));
|
||||
if (!ownedItem) return { status: 'NOT_FOUND' };
|
||||
const observations = await db.select().from(pricingObservations)
|
||||
.where(and(eq(pricingObservations.inventoryItemId, inventoryItemId), eq(pricingObservations.isOutlier, false)))
|
||||
.orderBy(desc(pricingObservations.observedAt));
|
||||
if (!observations.length) return { status: 'NO_DATA' };
|
||||
const prices = observations.map(({ priceMinor }) => priceMinor).sort((left, right) => left - right);
|
||||
const middle = Math.floor(prices.length / 2);
|
||||
const valueMinor = prices.length % 2 ? prices[middle] : Math.round((prices[middle - 1] + prices[middle]) / 2);
|
||||
const [valuation] = await db.insert(marketValuations).values({
|
||||
inventoryItemId,
|
||||
valueMinor,
|
||||
currency: 'USD',
|
||||
strategy,
|
||||
confidence: observations.length === 1 ? 'LOW' : 'MEDIUM',
|
||||
sourceCount: observations.length,
|
||||
}).returning();
|
||||
return { status: 'CALCULATED', valuation, observations };
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
import { toAdminMarketValuationDto, toAdminPricingObservationDto } from '@pokemon-inventory/contracts/pricing';
|
||||
import { createPricingObservationSchema } from '@pokemon-inventory/validation/pricing';
|
||||
|
||||
import { createApplicationError } from '../../../shared/errors/application-error.js';
|
||||
|
||||
function validationError(reply, result) {
|
||||
return reply.code(400).send({
|
||||
error: {
|
||||
code: 'VALIDATION_ERROR',
|
||||
message: 'Request validation failed.',
|
||||
details: result.error.issues.map(({ message, path }) => ({ message, path })),
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export async function registerAdminPricingRoutes(app, options) {
|
||||
const {
|
||||
authenticateAdmin = async () => { throw createApplicationError('UNAUTHORIZED', 'Authentication is required.', 401); },
|
||||
authorizeUnsafeRequest,
|
||||
sessionCookieName = 'pokemon_inventory_session',
|
||||
pricingService,
|
||||
} = options;
|
||||
|
||||
app.addHook('preHandler', async (request) => {
|
||||
const admin = await authenticateAdmin(request);
|
||||
if (!admin?.sellerId) throw createApplicationError('UNAUTHORIZED', 'Authentication is required.', 401);
|
||||
request.admin = admin;
|
||||
});
|
||||
|
||||
app.post('/pricing/observations', async (request, reply) => {
|
||||
await authorizeUnsafeRequest?.(request.cookies[sessionCookieName], request.headers['x-csrf-token']);
|
||||
const result = createPricingObservationSchema.safeParse(request.body);
|
||||
if (!result.success) return validationError(reply, result);
|
||||
const observation = await pricingService.addObservation({ ...result.data, sellerId: request.admin.sellerId });
|
||||
return reply.code(201).send({ data: toAdminPricingObservationDto(observation) });
|
||||
});
|
||||
|
||||
app.post('/inventory/:id/valuation', async (request, reply) => {
|
||||
const valuation = await pricingService.calculate({ sellerId: request.admin.sellerId, inventoryItemId: request.params.id });
|
||||
return reply.code(200).send({ data: toAdminMarketValuationDto(valuation) });
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
import { createPricingObservation } from '../domain/pricing-observation.js';
|
||||
import { createApplicationError } from '../../../shared/errors/application-error.js';
|
||||
|
||||
export function createPricingService({ pricingRepository }) {
|
||||
return {
|
||||
async addObservation({ sellerId, ...input }) {
|
||||
const observation = createPricingObservation(input);
|
||||
const result = await pricingRepository.addObservationForSeller({ observation, sellerId });
|
||||
if (result.status === 'NOT_FOUND') throw createApplicationError('INVENTORY_NOT_FOUND', 'Inventory item was not found.', 404);
|
||||
return result.observation;
|
||||
},
|
||||
|
||||
async calculate({ sellerId, inventoryItemId }) {
|
||||
const result = await pricingRepository.calculateForSeller({ sellerId, inventoryItemId });
|
||||
if (result.status === 'NOT_FOUND') throw createApplicationError('INVENTORY_NOT_FOUND', 'Inventory item was not found.', 404);
|
||||
if (result.status === 'NO_DATA') throw createApplicationError('PRICING_DATA_UNAVAILABLE', 'No pricing observations are available.', 404);
|
||||
return result;
|
||||
},
|
||||
};
|
||||
}
|
||||
Reference in New Issue
Block a user