feat(M04-C): 完成续费换房与订单调整
This commit is contained in:
@@ -0,0 +1,126 @@
|
||||
import type { FastifyInstance, FastifyReply } from 'fastify';
|
||||
import { z } from 'zod';
|
||||
import type { AuthRepository } from '../auth/auth-repository.js';
|
||||
import { authenticateAccessToken } from '../auth/authenticate.js';
|
||||
import type { AccessProfile } from '../auth/rbac-repository.js';
|
||||
import {
|
||||
OrderManagementError, type OrderManagementRepository
|
||||
} from '../orders/order-management-repository.js';
|
||||
import type { OrderActor } from '../orders/order-state-repository.js';
|
||||
|
||||
const paramsSchema = z.object({ orderId: z.string().regex(/^[1-9]\d{0,19}$/) });
|
||||
const renewSchema = z.object({
|
||||
endAt: z.coerce.date(),
|
||||
pricingPolicy: z.enum(['CURRENT', 'LOCKED']).default('CURRENT'),
|
||||
reason: z.string().min(1).max(512)
|
||||
}).strict();
|
||||
const roomSchema = z.object({
|
||||
roomId: z.string().regex(/^[1-9]\d{0,19}$/),
|
||||
reason: z.string().min(1).max(512)
|
||||
}).strict();
|
||||
const timeSchema = z.object({
|
||||
startAt: z.coerce.date().optional(),
|
||||
endAt: z.coerce.date().optional(),
|
||||
reason: z.string().min(1).max(512)
|
||||
}).strict().refine((value) => value.startAt || value.endAt);
|
||||
const noteSchema = z.object({ note: z.string().min(1).max(512) }).strict();
|
||||
|
||||
export interface OrderManagementRouteOptions {
|
||||
repository: Pick<OrderManagementRepository,
|
||||
'renew' | 'changeRoom' | 'adjustTime' | 'note' | 'cancellationQuote'>;
|
||||
authRepository: Pick<AuthRepository, 'validateSession'>;
|
||||
accessControl: { getAccessProfile(tenantId: string, userId: string): Promise<AccessProfile> };
|
||||
jwtSecret: string;
|
||||
}
|
||||
|
||||
export async function registerOrderManagementRoutes(
|
||||
app: FastifyInstance, options: OrderManagementRouteOptions
|
||||
) {
|
||||
app.get('/app-api/orders/:orderId/cancellation-quote', async (request, reply) => {
|
||||
const auth = await authenticate(request.headers.authorization, options);
|
||||
const params = paramsSchema.safeParse(request.params);
|
||||
if (!auth) return unauthorized(reply, request.traceId);
|
||||
if (!params.success) return invalid(reply, request.traceId);
|
||||
return handle(reply, request.traceId, async () => ({
|
||||
code: 0,
|
||||
data: await options.repository.cancellationQuote(
|
||||
auth.tenantId, auth.userId, params.data.orderId
|
||||
),
|
||||
traceId: request.traceId
|
||||
}));
|
||||
});
|
||||
|
||||
const adminActions = [
|
||||
['renew', renewSchema, (actor: OrderActor, orderId: string, body: z.infer<typeof renewSchema>) =>
|
||||
options.repository.renew(actor, orderId, body)],
|
||||
['change-room', roomSchema, (actor: OrderActor, orderId: string, body: z.infer<typeof roomSchema>) =>
|
||||
options.repository.changeRoom(actor, orderId, body)],
|
||||
['adjust-time', timeSchema, (actor: OrderActor, orderId: string, body: z.infer<typeof timeSchema>) =>
|
||||
options.repository.adjustTime(actor, orderId, body)],
|
||||
['note', noteSchema, (actor: OrderActor, orderId: string, body: z.infer<typeof noteSchema>) =>
|
||||
options.repository.note(actor, orderId, body.note)]
|
||||
] as const;
|
||||
|
||||
for (const [path, schema, execute] of adminActions) {
|
||||
app.post(`/admin-api/orders/:orderId/${path}`, async (request, reply) => {
|
||||
const auth = await authenticate(request.headers.authorization, options);
|
||||
const params = paramsSchema.safeParse(request.params);
|
||||
const body = schema.safeParse(request.body);
|
||||
if (!auth) return unauthorized(reply, request.traceId);
|
||||
if (!params.success || !body.success) return invalid(reply, request.traceId);
|
||||
const actor = {
|
||||
tenantId: auth.tenantId, userId: auth.userId, actorType: 'USER' as const,
|
||||
source: 'ADMIN' as const, traceId: request.traceId, ip: request.ip,
|
||||
userAgent: request.headers['user-agent'] ?? '', access: auth.access
|
||||
};
|
||||
return handle(reply, request.traceId, async () => ({
|
||||
code: 0,
|
||||
data: await execute(actor, params.data.orderId, body.data as never),
|
||||
traceId: request.traceId
|
||||
}));
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
async function authenticate(
|
||||
authorization: string | undefined, options: OrderManagementRouteOptions
|
||||
) {
|
||||
const result = await authenticateAccessToken(
|
||||
authorization, options.authRepository, options.jwtSecret
|
||||
);
|
||||
if (!result) return null;
|
||||
const tenantId = result.session.tenantId;
|
||||
const userId = result.session.user.id;
|
||||
return {
|
||||
tenantId, userId,
|
||||
access: await options.accessControl.getAccessProfile(tenantId, userId)
|
||||
};
|
||||
}
|
||||
|
||||
async function handle(reply: FastifyReply, traceId: string, work: () => Promise<unknown>) {
|
||||
try {
|
||||
return await work();
|
||||
} catch (error) {
|
||||
if (!(error instanceof OrderManagementError)) throw error;
|
||||
const status = error.code === 'ORDER_NOT_FOUND' || error.code === 'ROOM_NOT_FOUND' ? 404
|
||||
: error.code === 'TIME_SLOT_CONFLICT' ? 409
|
||||
: error.code.includes('FORBIDDEN') ? 403 : 400;
|
||||
return reply.status(status).send({
|
||||
code: error.code,
|
||||
message: 'The requested order adjustment is not available.',
|
||||
traceId
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
function unauthorized(reply: FastifyReply, traceId: string) {
|
||||
return reply.status(401).send({
|
||||
code: 'AUTH_SESSION_INVALID', message: 'Authentication required.', traceId
|
||||
});
|
||||
}
|
||||
|
||||
function invalid(reply: FastifyReply, traceId: string) {
|
||||
return reply.status(400).send({
|
||||
code: 'INVALID_ORDER_ADJUSTMENT', message: 'The order adjustment is invalid.', traceId
|
||||
});
|
||||
}
|
||||
@@ -19,6 +19,9 @@ export interface OrderStateRouteOptions {
|
||||
authRepository: Pick<AuthRepository, 'validateSession'>;
|
||||
accessControl: { getAccessProfile(tenantId: string, userId: string): Promise<AccessProfile> };
|
||||
jwtSecret: string;
|
||||
cancellationPolicy?: {
|
||||
cancellationQuote(tenantId: string, userId: string, orderId: string): Promise<unknown>;
|
||||
};
|
||||
}
|
||||
|
||||
export async function registerOrderStateRoutes(
|
||||
@@ -44,15 +47,19 @@ export async function registerOrderStateRoutes(
|
||||
const body = cancelSchema.safeParse(request.body ?? {});
|
||||
if (!auth) return unauthorized(reply, request.traceId);
|
||||
if (!params.success || !body.success) return invalid(reply, request.traceId);
|
||||
return handle(reply, request.traceId, async () => ({
|
||||
code: 0,
|
||||
data: await options.repository.transition({
|
||||
return handle(reply, request.traceId, async () => {
|
||||
const cancellation = options.cancellationPolicy
|
||||
? await options.cancellationPolicy.cancellationQuote(
|
||||
auth.tenantId, auth.userId, params.data.orderId
|
||||
)
|
||||
: null;
|
||||
const transition = await options.repository.transition({
|
||||
tenantId: auth.tenantId, userId: auth.userId, actorType: 'USER',
|
||||
source: 'APP', traceId: request.traceId, ip: request.ip,
|
||||
userAgent: request.headers['user-agent'] ?? '', access: auth.access
|
||||
}, params.data.orderId, 'CANCEL', body.data.reason),
|
||||
traceId: request.traceId
|
||||
}));
|
||||
}, params.data.orderId, 'CANCEL', body.data.reason);
|
||||
return { code: 0, data: { transition, cancellation }, traceId: request.traceId };
|
||||
});
|
||||
});
|
||||
|
||||
app.post('/admin-api/orders/:orderId/actions', async (request, reply) => {
|
||||
|
||||
@@ -11,6 +11,9 @@ const requestSchema = z.object({
|
||||
endAt: z.coerce.date(),
|
||||
pricingMode: z.enum(['HOURLY', 'OVERNIGHT', 'FULL_DAY']).default('HOURLY')
|
||||
}).refine((value) => value.endAt > value.startAt);
|
||||
const adminReserveSchema = requestSchema.and(z.object({
|
||||
userId: z.string().regex(/^[1-9]\d{0,19}$/)
|
||||
}));
|
||||
|
||||
export interface PricingRouteOptions {
|
||||
repository: Pick<PricingRepository, 'quote' | 'reserve' | 'releaseExpired'>;
|
||||
@@ -69,6 +72,36 @@ export async function registerPricingRoutes(app: FastifyInstance, options: Prici
|
||||
traceId: request.traceId
|
||||
};
|
||||
});
|
||||
|
||||
app.post('/admin-api/orders/reserve-on-behalf', async (request, reply) => {
|
||||
const auth = await authenticate(request.headers.authorization, options);
|
||||
const body = adminReserveSchema.safeParse(request.body);
|
||||
if (!auth) return unauthorized(reply, request.traceId);
|
||||
if (!body.success) return invalid(reply, request.traceId);
|
||||
const access = await options.accessControl.getAccessProfile(auth.tenantId, auth.userId);
|
||||
const unrestricted = access.capabilities.includes('tenant.manage')
|
||||
|| access.roles.includes('PLATFORM_ADMIN');
|
||||
if (!unrestricted && !access.capabilities.includes('store.operation.write')) {
|
||||
return reply.status(403).send({
|
||||
code: 'ORDER_MANAGEMENT_FORBIDDEN',
|
||||
message: 'Order management permission is required.',
|
||||
traceId: request.traceId
|
||||
});
|
||||
}
|
||||
return handle(reply, request.traceId, async () => reply.status(201).send({
|
||||
code: 0,
|
||||
data: await options.repository.reserve({
|
||||
tenantId: auth.tenantId,
|
||||
userId: body.data.userId,
|
||||
roomId: body.data.roomId,
|
||||
startAt: body.data.startAt,
|
||||
endAt: body.data.endAt,
|
||||
pricingMode: body.data.pricingMode,
|
||||
allowedStoreIds: unrestricted ? null : access.storeIds
|
||||
}),
|
||||
traceId: request.traceId
|
||||
}));
|
||||
});
|
||||
}
|
||||
|
||||
async function authenticate(
|
||||
|
||||
Reference in New Issue
Block a user