Add acquisition persistence, cost-basis calculation, seller-scoped admin routes, contracts, validation, migration, and focused application/HTTP tests.
This commit is contained in:
@@ -15,6 +15,7 @@ import { registerPublicProductRoutes } from '../modules/products/routes/public-p
|
||||
import { registerPublicSearchRoutes } from '../modules/search/routes/public-search-routes.js';
|
||||
import { registerPublicSellerRoutes } from '../modules/sellers/routes/public-seller-routes.js';
|
||||
import { registerAdminSaleRoutes } from '../modules/sales/routes/admin-sale-routes.js';
|
||||
import { registerAdminAcquisitionRoutes } from '../modules/acquisitions/routes/admin-acquisition-routes.js';
|
||||
|
||||
export function buildApp(dependencies) {
|
||||
const app = Fastify();
|
||||
@@ -66,6 +67,10 @@ export function buildApp(dependencies) {
|
||||
...dependencies,
|
||||
prefix: '/api/v1/admin',
|
||||
});
|
||||
app.register(registerAdminAcquisitionRoutes, {
|
||||
...dependencies,
|
||||
prefix: '/api/v1/admin',
|
||||
});
|
||||
app.register(registerPublicSearchRoutes, {
|
||||
...dependencies,
|
||||
prefix: '/api/v1',
|
||||
|
||||
@@ -39,6 +39,8 @@ import { createSellerRepository } from '../modules/sellers/repositories/seller-r
|
||||
import { createPublicSellerService } from '../modules/sellers/services/public-seller-service.js';
|
||||
import { createSaleRepository } from '../modules/sales/repositories/sale-repository.js';
|
||||
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';
|
||||
|
||||
function parsePort(value) {
|
||||
const port = Number.parseInt(value ?? '3000', 10);
|
||||
@@ -63,6 +65,7 @@ async function startServer() {
|
||||
const sellerRepository = createSellerRepository(database.db);
|
||||
const conditionRepository = createConditionRepository(database.db);
|
||||
const saleRepository = createSaleRepository(database.db);
|
||||
const acquisitionRepository = createAcquisitionRepository(database.db);
|
||||
const userRepository = createUserRepository(database.db);
|
||||
const sessionRepository = createSessionRepository(database.db);
|
||||
const passwordResetRepository = createPasswordResetRepository(database.db);
|
||||
@@ -119,6 +122,7 @@ async function startServer() {
|
||||
}),
|
||||
listingService: createListingService({ listingRepository, inventoryImageRepository }),
|
||||
saleService: createSaleService({ saleRepository }),
|
||||
acquisitionService: createAcquisitionService({ acquisitionRepository }),
|
||||
publicListingService: createPublicListingService({ listingRepository, publicImageService }),
|
||||
productService: createProductService({ productRepository }),
|
||||
publicProductService: createPublicProductService({ productRepository }),
|
||||
|
||||
@@ -242,6 +242,25 @@ export const inventoryItems = pgTable('inventory_items', {
|
||||
...timestamps,
|
||||
});
|
||||
|
||||
export const acquisitions = pgTable('acquisitions', {
|
||||
id: uuid('id').defaultRandom().primaryKey(),
|
||||
inventoryItemId: uuid('inventory_item_id')
|
||||
.notNull()
|
||||
.references(() => inventoryItems.id),
|
||||
method: text('method').notNull(),
|
||||
costMinor: integer('cost_minor').notNull(),
|
||||
currency: text('currency').notNull(),
|
||||
date: text('date'),
|
||||
source: text('source'),
|
||||
location: text('location'),
|
||||
shippingMinor: integer('shipping_minor').default(0).notNull(),
|
||||
taxMinor: integer('tax_minor').default(0).notNull(),
|
||||
otherFeesMinor: integer('other_fees_minor').default(0).notNull(),
|
||||
estimatedTradeValueMinor: integer('estimated_trade_value_minor').default(0).notNull(),
|
||||
notes: text('notes'),
|
||||
...timestamps,
|
||||
});
|
||||
|
||||
export const inventoryImages = pgTable(
|
||||
'inventory_images',
|
||||
{
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
import { and, desc, eq } from 'drizzle-orm';
|
||||
|
||||
import { acquisitions, inventoryItems, products } from '../../../infrastructure/database/schema.js';
|
||||
|
||||
export function createAcquisitionRepository(db) {
|
||||
return {
|
||||
async createForSeller({ acquisition, sellerId }) {
|
||||
return db.transaction(async (transaction) => {
|
||||
const [ownedItem] = await transaction
|
||||
.select({ id: inventoryItems.id })
|
||||
.from(inventoryItems)
|
||||
.innerJoin(products, eq(products.id, inventoryItems.productId))
|
||||
.where(and(eq(inventoryItems.id, acquisition.inventoryItemId), eq(products.sellerId, sellerId)));
|
||||
|
||||
if (!ownedItem) return { status: 'NOT_FOUND' };
|
||||
const [created] = await transaction.insert(acquisitions).values(acquisition).returning();
|
||||
return { status: 'CREATED', acquisition: created };
|
||||
});
|
||||
},
|
||||
|
||||
async listBySellerId(sellerId) {
|
||||
return db
|
||||
.select({ acquisition: acquisitions })
|
||||
.from(acquisitions)
|
||||
.innerJoin(inventoryItems, eq(inventoryItems.id, acquisitions.inventoryItemId))
|
||||
.innerJoin(products, eq(products.id, inventoryItems.productId))
|
||||
.where(eq(products.sellerId, sellerId))
|
||||
.orderBy(desc(acquisitions.createdAt))
|
||||
.then((rows) => rows.map(({ acquisition }) => acquisition));
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
import { toAdminAcquisitionDto } from '@pokemon-inventory/contracts/acquisition';
|
||||
import { createAcquisitionSchema } from '@pokemon-inventory/validation/acquisition';
|
||||
|
||||
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 registerAdminAcquisitionRoutes(app, options) {
|
||||
const {
|
||||
authenticateAdmin = async () => { throw createApplicationError('UNAUTHORIZED', 'Authentication is required.', 401); },
|
||||
authorizeUnsafeRequest,
|
||||
sessionCookieName = 'pokemon_inventory_session',
|
||||
acquisitionService,
|
||||
} = 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.get('/acquisitions', async (request) => ({
|
||||
data: (await acquisitionService.list({ sellerId: request.admin.sellerId })).map(toAdminAcquisitionDto),
|
||||
}));
|
||||
|
||||
app.post('/acquisitions', async (request, reply) => {
|
||||
await authorizeUnsafeRequest?.(request.cookies[sessionCookieName], request.headers['x-csrf-token']);
|
||||
const result = createAcquisitionSchema.safeParse(request.body);
|
||||
if (!result.success) return validationError(reply, result);
|
||||
|
||||
const acquisition = await acquisitionService.create({ ...result.data, sellerId: request.admin.sellerId });
|
||||
return reply.code(201).send({ data: toAdminAcquisitionDto(acquisition) });
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
import { createAcquisition, calculateAcquisitionCostBasis } from '../domain/acquisition.js';
|
||||
import { createApplicationError } from '../../../shared/errors/application-error.js';
|
||||
|
||||
export function createAcquisitionService({ acquisitionRepository }) {
|
||||
return {
|
||||
async create({ sellerId, ...input }) {
|
||||
const acquisition = createAcquisition(input);
|
||||
const result = await acquisitionRepository.createForSeller({ acquisition, sellerId });
|
||||
if (result.status === 'NOT_FOUND') {
|
||||
throw createApplicationError('INVENTORY_NOT_FOUND', 'Inventory item was not found.', 404);
|
||||
}
|
||||
|
||||
return {
|
||||
...result.acquisition,
|
||||
costBasisMinor: calculateAcquisitionCostBasis(acquisition),
|
||||
};
|
||||
},
|
||||
|
||||
async list({ sellerId }) {
|
||||
return acquisitionRepository.listBySellerId(sellerId);
|
||||
},
|
||||
};
|
||||
}
|
||||
Reference in New Issue
Block a user