feat(M08-A): 接入顾客端订单查询
This commit is contained in:
@@ -33,6 +33,9 @@ import { registerPricingRoutes, type PricingRouteOptions } from './routes/pricin
|
||||
import {
|
||||
registerOrderStateRoutes, type OrderStateRouteOptions
|
||||
} from './routes/order-state.js';
|
||||
import {
|
||||
registerOrderQueryRoutes, type OrderQueryRouteOptions
|
||||
} from './routes/order-query.js';
|
||||
import {
|
||||
registerOrderManagementRoutes, type OrderManagementRouteOptions
|
||||
} from './routes/order-management.js';
|
||||
@@ -58,6 +61,7 @@ export interface BuildAppOptions {
|
||||
storeAccess?: StoreAccessRouteOptions;
|
||||
pricing?: PricingRouteOptions;
|
||||
orderState?: OrderStateRouteOptions;
|
||||
orderQuery?: OrderQueryRouteOptions;
|
||||
orderManagement?: OrderManagementRouteOptions;
|
||||
orderShare?: OrderShareRouteOptions;
|
||||
payment?: PaymentRouteOptions;
|
||||
@@ -137,6 +141,9 @@ export async function buildApp(options: BuildAppOptions = {}): Promise<FastifyIn
|
||||
if (options.orderState) {
|
||||
await registerOrderStateRoutes(app, options.orderState);
|
||||
}
|
||||
if (options.orderQuery) {
|
||||
await registerOrderQueryRoutes(app, options.orderQuery);
|
||||
}
|
||||
if (options.orderManagement) {
|
||||
await registerOrderManagementRoutes(app, options.orderManagement);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,163 @@
|
||||
import type { RowDataPacket } from 'mysql2/promise';
|
||||
import type { AccessProfile } from '../auth/rbac-repository.js';
|
||||
import type { MySqlPool } from '../db/mysql.js';
|
||||
import type { OrderStatus } from './order-state-repository.js';
|
||||
|
||||
export class OrderQueryError extends Error {
|
||||
constructor(public readonly code: string) { super(code); }
|
||||
}
|
||||
|
||||
export interface OrderQueryAccess {
|
||||
tenantId: string;
|
||||
userId: string;
|
||||
access: AccessProfile;
|
||||
}
|
||||
|
||||
interface OrderListRow extends RowDataPacket {
|
||||
id: string;
|
||||
orderNo: string;
|
||||
storeId: string;
|
||||
storeName: string;
|
||||
roomId: string;
|
||||
roomName: string;
|
||||
roomNo: string;
|
||||
status: OrderStatus;
|
||||
startAt: Date;
|
||||
endAt: Date;
|
||||
totalAmountCents: number;
|
||||
paidAmountCents: number;
|
||||
latestPaymentId: string | null;
|
||||
latestPaymentProvider: string | null;
|
||||
latestPaymentStatus: string | null;
|
||||
createdAt: Date;
|
||||
}
|
||||
|
||||
interface CountRow extends RowDataPacket { total: number }
|
||||
|
||||
export class OrderQueryRepository {
|
||||
constructor(private readonly pool: MySqlPool) {}
|
||||
|
||||
async listMine(input: OrderQueryAccess & {
|
||||
page: number;
|
||||
pageSize: number;
|
||||
status?: OrderStatus;
|
||||
}) {
|
||||
const where = [
|
||||
'o.tenant_id = ?',
|
||||
'o.deleted_at IS NULL',
|
||||
'(a.user_id = ? OR ' + managerScopeSql(input.access, 'o.store_id') + ')'
|
||||
];
|
||||
const params: Array<string | number> = [input.tenantId, input.userId];
|
||||
if (input.status) {
|
||||
where.push('o.status = ?');
|
||||
params.push(input.status);
|
||||
}
|
||||
const whereSql = where.join(' AND ');
|
||||
const offset = (input.page - 1) * input.pageSize;
|
||||
const [counts] = await this.pool.execute<CountRow[]>(
|
||||
`SELECT COUNT(DISTINCT o.id) AS total
|
||||
FROM qipai_orders o
|
||||
LEFT JOIN qipai_order_user_access a
|
||||
ON a.tenant_id = o.tenant_id AND a.order_id = o.id AND a.revoked_at IS NULL
|
||||
WHERE ${whereSql}`,
|
||||
params
|
||||
);
|
||||
const [rows] = await this.pool.execute<OrderListRow[]>(
|
||||
`SELECT DISTINCT o.id, o.order_no AS orderNo, o.store_id AS storeId, s.name AS storeName,
|
||||
o.room_id AS roomId, r.name AS roomName, r.room_no AS roomNo,
|
||||
o.status, o.start_at AS startAt, o.end_at AS endAt,
|
||||
o.total_amount_cents AS totalAmountCents,
|
||||
o.paid_amount_cents AS paidAmountCents, p.id AS latestPaymentId,
|
||||
p.provider AS latestPaymentProvider, p.status AS latestPaymentStatus,
|
||||
o.created_at AS createdAt
|
||||
FROM qipai_orders o
|
||||
INNER JOIN qipai_stores s ON s.tenant_id = o.tenant_id AND s.id = o.store_id
|
||||
INNER JOIN qipai_rooms r ON r.tenant_id = o.tenant_id AND r.id = o.room_id
|
||||
LEFT JOIN qipai_order_user_access a
|
||||
ON a.tenant_id = o.tenant_id AND a.order_id = o.id AND a.revoked_at IS NULL
|
||||
LEFT JOIN qipai_payments p
|
||||
ON p.tenant_id = o.tenant_id AND p.order_id = o.id
|
||||
AND p.id = (
|
||||
SELECT MAX(p2.id) FROM qipai_payments p2
|
||||
WHERE p2.tenant_id = o.tenant_id AND p2.order_id = o.id
|
||||
AND p2.deleted_at IS NULL
|
||||
)
|
||||
WHERE ${whereSql}
|
||||
ORDER BY o.created_at DESC, o.id DESC
|
||||
LIMIT ? OFFSET ?`,
|
||||
[...params, input.pageSize, offset]
|
||||
);
|
||||
return {
|
||||
items: rows.map(publicOrder),
|
||||
total: Number(counts[0]?.total ?? 0),
|
||||
page: input.page,
|
||||
pageSize: input.pageSize
|
||||
};
|
||||
}
|
||||
|
||||
async getMine(input: OrderQueryAccess & { orderId: string }) {
|
||||
const result = await this.listMine({ ...input, page: 1, pageSize: 1 });
|
||||
const order = result.items.find((item) => item.id === input.orderId);
|
||||
if (order) return order;
|
||||
const [rows] = await this.pool.execute<OrderListRow[]>(
|
||||
`SELECT o.id, o.order_no AS orderNo, o.store_id AS storeId, s.name AS storeName,
|
||||
o.room_id AS roomId, r.name AS roomName, r.room_no AS roomNo,
|
||||
o.status, o.start_at AS startAt, o.end_at AS endAt,
|
||||
o.total_amount_cents AS totalAmountCents,
|
||||
o.paid_amount_cents AS paidAmountCents, p.id AS latestPaymentId,
|
||||
p.provider AS latestPaymentProvider, p.status AS latestPaymentStatus,
|
||||
o.created_at AS createdAt
|
||||
FROM qipai_orders o
|
||||
INNER JOIN qipai_stores s ON s.tenant_id = o.tenant_id AND s.id = o.store_id
|
||||
INNER JOIN qipai_rooms r ON r.tenant_id = o.tenant_id AND r.id = o.room_id
|
||||
LEFT JOIN qipai_order_user_access a
|
||||
ON a.tenant_id = o.tenant_id AND a.order_id = o.id AND a.revoked_at IS NULL
|
||||
LEFT JOIN qipai_payments p
|
||||
ON p.tenant_id = o.tenant_id AND p.order_id = o.id
|
||||
AND p.id = (
|
||||
SELECT MAX(p2.id) FROM qipai_payments p2
|
||||
WHERE p2.tenant_id = o.tenant_id AND p2.order_id = o.id
|
||||
AND p2.deleted_at IS NULL
|
||||
)
|
||||
WHERE o.tenant_id = ? AND o.id = ? AND o.deleted_at IS NULL
|
||||
AND (a.user_id = ? OR ${managerScopeSql(input.access, 'o.store_id')})
|
||||
LIMIT 1`,
|
||||
[input.tenantId, input.orderId, input.userId]
|
||||
);
|
||||
if (!rows[0]) throw new OrderQueryError('ORDER_NOT_FOUND');
|
||||
return publicOrder(rows[0]);
|
||||
}
|
||||
}
|
||||
|
||||
function publicOrder(row: OrderListRow) {
|
||||
return {
|
||||
id: String(row.id),
|
||||
orderNo: row.orderNo,
|
||||
storeId: String(row.storeId),
|
||||
storeName: row.storeName,
|
||||
roomId: String(row.roomId),
|
||||
roomName: row.roomName,
|
||||
roomNo: row.roomNo,
|
||||
status: row.status,
|
||||
startAt: row.startAt,
|
||||
endAt: row.endAt,
|
||||
totalAmountCents: row.totalAmountCents,
|
||||
paidAmountCents: row.paidAmountCents,
|
||||
latestPayment: row.latestPaymentId === null ? null : {
|
||||
id: String(row.latestPaymentId),
|
||||
provider: row.latestPaymentProvider,
|
||||
status: row.latestPaymentStatus
|
||||
},
|
||||
createdAt: row.createdAt
|
||||
};
|
||||
}
|
||||
|
||||
function managerScopeSql(access: AccessProfile, storeExpression: string) {
|
||||
if (access.capabilities.includes('tenant.manage') || access.roles.includes('PLATFORM_ADMIN')) {
|
||||
return '1 = 1';
|
||||
}
|
||||
if (!access.capabilities.includes('store.operation.read') || access.storeIds.length === 0) {
|
||||
return '1 = 0';
|
||||
}
|
||||
return `${storeExpression} IN (${access.storeIds.map((id) => Number(id)).join(',')})`;
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
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 {
|
||||
OrderQueryError,
|
||||
type OrderQueryRepository
|
||||
} from '../orders/order-query-repository.js';
|
||||
import { type OrderStatus } from '../orders/order-state-repository.js';
|
||||
|
||||
const orderStatuses = [
|
||||
'DRAFT', 'PENDING_PAYMENT', 'PAID', 'RESERVED', 'IN_PROGRESS',
|
||||
'FINISHED', 'CANCELLED', 'REFUNDING', 'REFUNDED', 'CLOSED'
|
||||
] as const satisfies readonly OrderStatus[];
|
||||
const listSchema = z.object({
|
||||
page: z.coerce.number().int().min(1).default(1),
|
||||
pageSize: z.coerce.number().int().min(1).max(50).default(20),
|
||||
status: z.enum(orderStatuses).optional()
|
||||
});
|
||||
const paramsSchema = z.object({ orderId: z.string().regex(/^[1-9]\d{0,19}$/) });
|
||||
|
||||
export interface OrderQueryRouteOptions {
|
||||
repository: Pick<OrderQueryRepository, 'listMine' | 'getMine'>;
|
||||
authRepository: Pick<AuthRepository, 'validateSession'>;
|
||||
accessControl: { getAccessProfile(tenantId: string, userId: string): Promise<AccessProfile> };
|
||||
jwtSecret: string;
|
||||
}
|
||||
|
||||
export async function registerOrderQueryRoutes(
|
||||
app: FastifyInstance,
|
||||
options: OrderQueryRouteOptions
|
||||
) {
|
||||
app.get('/app-api/orders', async (request, reply) => {
|
||||
const auth = await authenticate(request.headers.authorization, options);
|
||||
const query = listSchema.safeParse(request.query);
|
||||
if (!auth) return unauthorized(reply, request.traceId);
|
||||
if (!query.success) return invalid(reply, request.traceId);
|
||||
return {
|
||||
code: 0,
|
||||
data: await options.repository.listMine({ ...auth, ...query.data }),
|
||||
traceId: request.traceId
|
||||
};
|
||||
});
|
||||
|
||||
app.get('/app-api/orders/:orderId', 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.getMine({ ...auth, orderId: params.data.orderId }),
|
||||
traceId: request.traceId
|
||||
}));
|
||||
});
|
||||
}
|
||||
|
||||
async function authenticate(
|
||||
authorization: string | undefined,
|
||||
options: OrderQueryRouteOptions
|
||||
) {
|
||||
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 OrderQueryError)) throw error;
|
||||
return reply.status(404).send({
|
||||
code: error.code,
|
||||
message: 'The requested order 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_QUERY',
|
||||
message: 'The order query is invalid.',
|
||||
traceId
|
||||
});
|
||||
}
|
||||
@@ -16,6 +16,7 @@ import { PricingRepository } from './orders/pricing-repository.js';
|
||||
import { OrderStateRepository } from './orders/order-state-repository.js';
|
||||
import { OrderManagementRepository } from './orders/order-management-repository.js';
|
||||
import { OrderShareRepository } from './orders/order-share-repository.js';
|
||||
import { OrderQueryRepository } from './orders/order-query-repository.js';
|
||||
import { PaymentRepository } from './payments/payment-repository.js';
|
||||
import {
|
||||
FetchWechatPayTransport, parseWechatPayCredentials, WechatPayClient
|
||||
@@ -100,6 +101,12 @@ const app = await buildApp({
|
||||
jwtSecret: config.auth.jwtSecret,
|
||||
cancellationPolicy: orderManagementRepository
|
||||
},
|
||||
orderQuery: {
|
||||
repository: new OrderQueryRepository(pool),
|
||||
authRepository,
|
||||
accessControl,
|
||||
jwtSecret: config.auth.jwtSecret
|
||||
},
|
||||
orderManagement: {
|
||||
repository: orderManagementRepository,
|
||||
authRepository,
|
||||
|
||||
Reference in New Issue
Block a user