Add seller-owned pricing observation persistence, median market valuation calculation, admin routes, contracts, validation, migration, and focused tests.
This commit is contained in:
@@ -17,6 +17,7 @@ import { registerPublicSellerRoutes } from '../modules/sellers/routes/public-sel
|
||||
import { registerAdminSaleRoutes } from '../modules/sales/routes/admin-sale-routes.js';
|
||||
import { registerAdminAcquisitionRoutes } from '../modules/acquisitions/routes/admin-acquisition-routes.js';
|
||||
import { registerAdminDashboardRoutes } from '../modules/dashboard/routes/admin-dashboard-routes.js';
|
||||
import { registerAdminPricingRoutes } from '../modules/pricing/routes/admin-pricing-routes.js';
|
||||
|
||||
export function buildApp(dependencies) {
|
||||
const app = Fastify();
|
||||
@@ -76,6 +77,10 @@ export function buildApp(dependencies) {
|
||||
...dependencies,
|
||||
prefix: '/api/v1/admin',
|
||||
});
|
||||
app.register(registerAdminPricingRoutes, {
|
||||
...dependencies,
|
||||
prefix: '/api/v1/admin',
|
||||
});
|
||||
app.register(registerPublicSearchRoutes, {
|
||||
...dependencies,
|
||||
prefix: '/api/v1',
|
||||
|
||||
@@ -42,6 +42,8 @@ import { createSaleService } from '../modules/sales/services/sale-service.js';
|
||||
import { createAcquisitionRepository } from '../modules/acquisitions/repositories/acquisition-repository.js';
|
||||
import { createAcquisitionService } from '../modules/acquisitions/services/acquisition-service.js';
|
||||
import { createDashboardService } from '../modules/dashboard/services/dashboard-service.js';
|
||||
import { createPricingRepository } from '../modules/pricing/repositories/pricing-repository.js';
|
||||
import { createPricingService } from '../modules/pricing/services/pricing-service.js';
|
||||
|
||||
function parsePort(value) {
|
||||
const port = Number.parseInt(value ?? '3000', 10);
|
||||
@@ -67,6 +69,7 @@ async function startServer() {
|
||||
const conditionRepository = createConditionRepository(database.db);
|
||||
const saleRepository = createSaleRepository(database.db);
|
||||
const acquisitionRepository = createAcquisitionRepository(database.db);
|
||||
const pricingRepository = createPricingRepository(database.db);
|
||||
const userRepository = createUserRepository(database.db);
|
||||
const sessionRepository = createSessionRepository(database.db);
|
||||
const passwordResetRepository = createPasswordResetRepository(database.db);
|
||||
@@ -131,6 +134,7 @@ async function startServer() {
|
||||
saleService: createSaleService({ saleRepository }),
|
||||
acquisitionService: createAcquisitionService({ acquisitionRepository }),
|
||||
}),
|
||||
pricingService: createPricingService({ pricingRepository }),
|
||||
publicListingService: createPublicListingService({ listingRepository, publicImageService }),
|
||||
productService: createProductService({ productRepository }),
|
||||
publicProductService: createPublicProductService({ productRepository }),
|
||||
|
||||
@@ -261,6 +261,34 @@ export const acquisitions = pgTable('acquisitions', {
|
||||
...timestamps,
|
||||
});
|
||||
|
||||
export const pricingObservations = pgTable('pricing_observations', {
|
||||
id: uuid('id').defaultRandom().primaryKey(),
|
||||
productId: uuid('product_id').notNull().references(() => products.id),
|
||||
inventoryItemId: uuid('inventory_item_id').notNull().references(() => inventoryItems.id),
|
||||
providerId: text('provider_id').notNull(),
|
||||
priceMinor: integer('price_minor').notNull(),
|
||||
currency: text('currency').notNull(),
|
||||
sourceIdentifier: text('source_identifier').notNull(),
|
||||
conditionId: uuid('condition_id').notNull().references(() => conditions.id),
|
||||
sourceUrl: text('source_url'),
|
||||
qualityScore: integer('quality_score'),
|
||||
isOutlier: boolean('is_outlier').default(false).notNull(),
|
||||
outlierReason: text('outlier_reason'),
|
||||
observedAt: timestamp('observed_at', { withTimezone: true }).defaultNow().notNull(),
|
||||
...timestamps,
|
||||
}, (table) => [index('pricing_observations_inventory_item_id_index').on(table.inventoryItemId)]);
|
||||
|
||||
export const marketValuations = pgTable('market_valuations', {
|
||||
id: uuid('id').defaultRandom().primaryKey(),
|
||||
inventoryItemId: uuid('inventory_item_id').notNull().references(() => inventoryItems.id),
|
||||
valueMinor: integer('value_minor').notNull(),
|
||||
currency: text('currency').notNull(),
|
||||
strategy: text('strategy').notNull(),
|
||||
confidence: text('confidence').notNull(),
|
||||
sourceCount: integer('source_count').notNull(),
|
||||
calculatedAt: timestamp('calculated_at', { withTimezone: true }).defaultNow().notNull(),
|
||||
});
|
||||
|
||||
export const inventoryImages = pgTable(
|
||||
'inventory_images',
|
||||
{
|
||||
|
||||
@@ -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