feat(M08-A): 接入顾客端订单查询
This commit is contained in:
@@ -17,7 +17,7 @@
|
||||
"db:migrate:verify": "npm run build && node dist/db/migrate-cli.js verify",
|
||||
"db:migrate:down": "npm run build && node dist/db/migrate-cli.js down",
|
||||
"test:mysql:migration": "npm run build && node tests/mysql-migration-roundtrip.test.mjs",
|
||||
"test": "npm run build && node tests/backend-contract.test.mjs && node tests/mqtt-service.test.mjs && node tests/migration-contract.test.mjs && node tests/mysql-pool-contract.test.mjs && node tests/migration-runner.test.mjs && node tests/legacy-money.test.mjs && node tests/legacy-read-repository.test.mjs && node tests/task-repository.test.mjs && node tests/platform-config-repository.test.mjs && node tests/auth.test.mjs && node tests/rbac.test.mjs && node tests/user-management.test.mjs && node tests/store-room.test.mjs && node tests/content-management.test.mjs && node tests/store-discovery.test.mjs && node tests/store-access.test.mjs && node tests/pricing.test.mjs && node tests/order-state.test.mjs && node tests/order-management.test.mjs && node tests/order-share.test.mjs && node tests/payment.test.mjs && node tests/wechat-pay.test.mjs && node tests/third-party.test.mjs && node tests/profit-sharing.test.mjs && node tests/device.test.mjs && node tests/iot-protocol.test.mjs && node tests/device-control.test.mjs && node tests/order-device-automation.test.mjs && node tests/hardware-smoke-runner.test.mjs && node tests/wallet-ledger.test.mjs && node tests/recharge-service.test.mjs && node tests/marketing-benefit-service.test.mjs && node tests/member-profile-service.test.mjs"
|
||||
"test": "npm run build && node tests/backend-contract.test.mjs && node tests/mqtt-service.test.mjs && node tests/migration-contract.test.mjs && node tests/mysql-pool-contract.test.mjs && node tests/migration-runner.test.mjs && node tests/legacy-money.test.mjs && node tests/legacy-read-repository.test.mjs && node tests/task-repository.test.mjs && node tests/platform-config-repository.test.mjs && node tests/auth.test.mjs && node tests/rbac.test.mjs && node tests/user-management.test.mjs && node tests/store-room.test.mjs && node tests/content-management.test.mjs && node tests/store-discovery.test.mjs && node tests/store-access.test.mjs && node tests/pricing.test.mjs && node tests/order-state.test.mjs && node tests/order-query.test.mjs && node tests/order-management.test.mjs && node tests/order-share.test.mjs && node tests/payment.test.mjs && node tests/wechat-pay.test.mjs && node tests/third-party.test.mjs && node tests/profit-sharing.test.mjs && node tests/device.test.mjs && node tests/iot-protocol.test.mjs && node tests/device-control.test.mjs && node tests/order-device-automation.test.mjs && node tests/hardware-smoke-runner.test.mjs && node tests/wallet-ledger.test.mjs && node tests/recharge-service.test.mjs && node tests/marketing-benefit-service.test.mjs && node tests/member-profile-service.test.mjs"
|
||||
},
|
||||
"dependencies": {
|
||||
"@fastify/cors": "^11.2.0",
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -0,0 +1,113 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import { buildApp } from '../dist/app.js';
|
||||
import { signAccessToken } from '../dist/auth/jwt.js';
|
||||
|
||||
const secret = 'test-only-order-query-jwt-secret-32';
|
||||
const token = signAccessToken({
|
||||
sub: '21',
|
||||
sid: '5c4d3af8-c63c-4edb-bf95-b84127bb3f6e',
|
||||
tid: '7',
|
||||
aid: '9',
|
||||
rv: 1
|
||||
}, secret, 900);
|
||||
const authRepository = {
|
||||
async validateSession() {
|
||||
return {
|
||||
id: '5c4d3af8-c63c-4edb-bf95-b84127bb3f6e',
|
||||
tenantId: '7',
|
||||
platformAppId: '9',
|
||||
expiresAt: new Date(Date.now() + 60000),
|
||||
user: {
|
||||
id: '21',
|
||||
tenantId: '7',
|
||||
userType: 'CUSTOMER',
|
||||
status: 'ACTIVE',
|
||||
roleVersion: 1,
|
||||
nickname: '',
|
||||
avatarUrl: '',
|
||||
phone: ''
|
||||
}
|
||||
};
|
||||
}
|
||||
};
|
||||
let listInput;
|
||||
let detailInput;
|
||||
const app = await buildApp({
|
||||
orderQuery: {
|
||||
jwtSecret: secret,
|
||||
authRepository,
|
||||
accessControl: {
|
||||
async getAccessProfile() {
|
||||
return { roles: ['CUSTOMER'], capabilities: [], storeIds: [] };
|
||||
}
|
||||
},
|
||||
repository: {
|
||||
async listMine(input) {
|
||||
listInput = input;
|
||||
return {
|
||||
items: [{
|
||||
id: '31',
|
||||
orderNo: 'QP202606240001',
|
||||
storeName: '近店',
|
||||
roomName: '青竹房',
|
||||
status: 'PENDING_PAYMENT',
|
||||
totalAmountCents: 3600,
|
||||
latestPayment: null
|
||||
}],
|
||||
total: 1,
|
||||
page: input.page,
|
||||
pageSize: input.pageSize
|
||||
};
|
||||
},
|
||||
async getMine(input) {
|
||||
detailInput = input;
|
||||
return {
|
||||
id: input.orderId,
|
||||
orderNo: 'QP202606240001',
|
||||
storeName: '近店',
|
||||
roomName: '青竹房',
|
||||
status: 'PENDING_PAYMENT',
|
||||
totalAmountCents: 3600,
|
||||
latestPayment: null
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
const listed = await app.inject({
|
||||
method: 'GET',
|
||||
url: '/app-api/orders?page=2&pageSize=5&status=PENDING_PAYMENT',
|
||||
headers: { authorization: `Bearer ${token}` }
|
||||
});
|
||||
assert.equal(listed.statusCode, 200);
|
||||
assert.equal(listed.json().data.items[0].id, '31');
|
||||
assert.equal(listInput.tenantId, '7');
|
||||
assert.equal(listInput.userId, '21');
|
||||
assert.equal(listInput.page, 2);
|
||||
assert.equal(listInput.pageSize, 5);
|
||||
assert.equal(listInput.status, 'PENDING_PAYMENT');
|
||||
|
||||
const detail = await app.inject({
|
||||
method: 'GET',
|
||||
url: '/app-api/orders/31',
|
||||
headers: { authorization: `Bearer ${token}` }
|
||||
});
|
||||
assert.equal(detail.statusCode, 200);
|
||||
assert.equal(detailInput.orderId, '31');
|
||||
|
||||
const unauthenticated = await app.inject({
|
||||
method: 'GET',
|
||||
url: '/app-api/orders'
|
||||
});
|
||||
assert.equal(unauthenticated.statusCode, 401);
|
||||
|
||||
const invalid = await app.inject({
|
||||
method: 'GET',
|
||||
url: '/app-api/orders?pageSize=999',
|
||||
headers: { authorization: `Bearer ${token}` }
|
||||
});
|
||||
assert.equal(invalid.statusCode, 400);
|
||||
|
||||
await app.close();
|
||||
console.log('PASS: M08-A customer order query routes expose scoped list and detail.');
|
||||
Reference in New Issue
Block a user