feat(M08-B): 增加保洁结算单和超时回收
This commit is contained in:
@@ -53,6 +53,30 @@ interface FinishedOrderRow extends RowDataPacket {
|
||||
storeId: string;
|
||||
roomId: string;
|
||||
}
|
||||
interface SettlementCandidateRow extends RowDataPacket {
|
||||
id: string;
|
||||
storeId: string;
|
||||
cleanerUserId: string;
|
||||
rewardCents: number;
|
||||
completedAt: Date | null;
|
||||
}
|
||||
interface SettlementRow extends RowDataPacket {
|
||||
id: string;
|
||||
settlementNo: string;
|
||||
cleanerUserId: string;
|
||||
cleanerName: string;
|
||||
storeId: string | null;
|
||||
storeName: string | null;
|
||||
status: 'DRAFT' | 'CONFIRMED' | 'PAID' | 'CANCELLED';
|
||||
taskCount: number;
|
||||
totalRewardCents: number;
|
||||
periodStart: Date | null;
|
||||
periodEnd: Date | null;
|
||||
confirmedAt: Date | null;
|
||||
paidAt: Date | null;
|
||||
note: string;
|
||||
createdAt: Date;
|
||||
}
|
||||
|
||||
export class CleaningTaskRepository {
|
||||
constructor(private readonly pool: MySqlPool) {}
|
||||
@@ -173,6 +197,154 @@ export class CleaningTaskRepository {
|
||||
return this.listByWhere(where, [input.tenantId], input.page, input.pageSize, 't.completed_at ASC, t.id ASC');
|
||||
}
|
||||
|
||||
async listSettlements(input: CleaningActor & {
|
||||
page: number; pageSize: number; status?: 'DRAFT' | 'CONFIRMED' | 'PAID' | 'CANCELLED';
|
||||
}) {
|
||||
this.assertSettlement(input.access, 'read');
|
||||
const where = [
|
||||
's.tenant_id = ?',
|
||||
's.deleted_at IS NULL',
|
||||
storeScopeSql(input.access, 'COALESCE(s.store_id, 0)')
|
||||
];
|
||||
const params: Array<string | number> = [input.tenantId];
|
||||
if (input.status) {
|
||||
where.push('s.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(*) AS total FROM qipai_cleaning_settlements s WHERE ${whereSql}`,
|
||||
params
|
||||
);
|
||||
const [rows] = await this.pool.execute<SettlementRow[]>(
|
||||
`SELECT s.id, s.settlement_no AS settlementNo,
|
||||
s.cleaner_user_id AS cleanerUserId, u.nickname AS cleanerName,
|
||||
s.store_id AS storeId, st.name AS storeName, s.status,
|
||||
s.task_count AS taskCount, s.total_reward_cents AS totalRewardCents,
|
||||
s.period_start AS periodStart, s.period_end AS periodEnd,
|
||||
s.confirmed_at AS confirmedAt, s.paid_at AS paidAt,
|
||||
s.note, s.created_at AS createdAt
|
||||
FROM qipai_cleaning_settlements s
|
||||
INNER JOIN qipai_users u ON u.tenant_id = s.tenant_id AND u.id = s.cleaner_user_id
|
||||
LEFT JOIN qipai_stores st ON st.tenant_id = s.tenant_id AND st.id = s.store_id
|
||||
WHERE ${whereSql}
|
||||
ORDER BY s.created_at DESC, s.id DESC
|
||||
LIMIT ? OFFSET ?`,
|
||||
[...params, input.pageSize, offset]
|
||||
);
|
||||
return {
|
||||
items: rows.map(publicSettlement),
|
||||
total: Number(counts[0]?.total ?? 0),
|
||||
page: input.page,
|
||||
pageSize: input.pageSize
|
||||
};
|
||||
}
|
||||
|
||||
async generateSettlement(input: CleaningActor & {
|
||||
cleanerUserId: string; storeId?: string; note?: string;
|
||||
}) {
|
||||
this.assertSettlement(input.access, 'write');
|
||||
return this.transaction(async (connection) => {
|
||||
const scopeSql = storeScopeSql(input.access, 't.store_id');
|
||||
const params: Array<string | number> = [input.tenantId, input.cleanerUserId];
|
||||
const storeFilter = input.storeId ? 'AND t.store_id = ?' : '';
|
||||
if (input.storeId) params.push(input.storeId);
|
||||
const [tasks] = await connection.execute<SettlementCandidateRow[]>(
|
||||
`SELECT t.id, t.store_id AS storeId, t.cleaner_user_id AS cleanerUserId,
|
||||
t.reward_cents AS rewardCents, t.completed_at AS completedAt
|
||||
FROM qipai_cleaning_tasks t
|
||||
WHERE t.tenant_id = ? AND t.cleaner_user_id = ?
|
||||
AND t.status = 'COMPLETED' AND t.settled_at IS NULL AND t.deleted_at IS NULL
|
||||
${storeFilter} AND ${scopeSql}
|
||||
ORDER BY t.completed_at ASC, t.id ASC
|
||||
FOR UPDATE`,
|
||||
params
|
||||
);
|
||||
if (tasks.length === 0) throw new CleaningTaskError('CLEANING_SETTLEMENT_EMPTY');
|
||||
const storeIds = Array.from(new Set(tasks.map((task) => String(task.storeId))));
|
||||
const totalRewardCents = tasks.reduce((sum, task) => sum + Number(task.rewardCents), 0);
|
||||
const periodStart = minDate(tasks.map((task) => task.completedAt));
|
||||
const periodEnd = maxDate(tasks.map((task) => task.completedAt));
|
||||
const settlementNo = `CLS-${Date.now()}-${input.cleanerUserId}`;
|
||||
const [created] = await connection.execute<ResultSetHeader>(
|
||||
`INSERT INTO qipai_cleaning_settlements
|
||||
(tenant_id, settlement_no, cleaner_user_id, store_id, status, task_count,
|
||||
total_reward_cents, period_start, period_end, generated_by, note)
|
||||
VALUES (?, ?, ?, ?, 'DRAFT', ?, ?, ?, ?, ?, ?)`,
|
||||
[
|
||||
input.tenantId, settlementNo, input.cleanerUserId,
|
||||
storeIds.length === 1 ? storeIds[0] : null,
|
||||
tasks.length, totalRewardCents, periodStart, periodEnd,
|
||||
input.userId, input.note ?? ''
|
||||
]
|
||||
);
|
||||
const settlementId = String(created.insertId);
|
||||
for (const task of tasks) {
|
||||
await connection.execute(
|
||||
`INSERT INTO qipai_cleaning_settlement_items
|
||||
(tenant_id, settlement_id, task_id, reward_cents)
|
||||
VALUES (?, ?, ?, ?)`,
|
||||
[input.tenantId, settlementId, task.id, Number(task.rewardCents)]
|
||||
);
|
||||
}
|
||||
await connection.execute(
|
||||
`UPDATE qipai_cleaning_tasks
|
||||
SET status = 'SETTLED', settled_at = UTC_TIMESTAMP(3)
|
||||
WHERE tenant_id = ? AND id IN (${tasks.map(() => '?').join(',')})`,
|
||||
[input.tenantId, ...tasks.map((task) => task.id)]
|
||||
);
|
||||
for (const task of tasks) {
|
||||
await this.recordEventWithConnection(
|
||||
connection, input, String(task.id), 'COMPLETED', 'SETTLED', 'SETTLE', settlementNo
|
||||
);
|
||||
}
|
||||
return this.getSettlement(connection, input.tenantId, settlementId);
|
||||
});
|
||||
}
|
||||
|
||||
async confirmSettlement(input: CleaningActor & { settlementId: string; note?: string }) {
|
||||
this.assertSettlement(input.access, 'write');
|
||||
return this.transaction(async (connection) => {
|
||||
const [result] = await connection.execute<ResultSetHeader>(
|
||||
`UPDATE qipai_cleaning_settlements s
|
||||
SET s.status = 'CONFIRMED', s.confirmed_by = ?, s.confirmed_at = UTC_TIMESTAMP(3),
|
||||
s.note = CASE WHEN ? = '' THEN s.note ELSE ? END
|
||||
WHERE s.tenant_id = ? AND s.id = ? AND s.status = 'DRAFT' AND s.deleted_at IS NULL
|
||||
AND ${storeScopeSql(input.access, 'COALESCE(s.store_id, 0)')}`,
|
||||
[input.userId, input.note ?? '', input.note ?? '', input.tenantId, input.settlementId]
|
||||
);
|
||||
if (result.affectedRows !== 1) throw new CleaningTaskError('CLEANING_SETTLEMENT_STATUS_CONFLICT');
|
||||
return this.getSettlement(connection, input.tenantId, input.settlementId);
|
||||
});
|
||||
}
|
||||
|
||||
async reclaimTimeouts(input: CleaningActor & { olderThanMinutes: number; limit: number }) {
|
||||
this.assertCleaner(input.access, 'write');
|
||||
const [rows] = await this.pool.execute<RowDataPacket[]>(
|
||||
`SELECT id FROM qipai_cleaning_tasks t
|
||||
WHERE t.tenant_id = ? AND t.status IN ('CLAIMED', 'STARTED')
|
||||
AND t.updated_at < TIMESTAMPADD(MINUTE, -?, UTC_TIMESTAMP(3))
|
||||
AND t.deleted_at IS NULL AND ${storeScopeSql(input.access, 't.store_id')}
|
||||
ORDER BY t.updated_at ASC, t.id ASC
|
||||
LIMIT ?`,
|
||||
[input.tenantId, input.olderThanMinutes, input.limit]
|
||||
);
|
||||
const ids = rows.map((row) => String(row.id));
|
||||
if (ids.length === 0) return { reclaimed: 0, taskIds: [] as string[] };
|
||||
await this.pool.execute(
|
||||
`UPDATE qipai_cleaning_tasks
|
||||
SET status = 'WAITING', cleaner_user_id = NULL, claimed_at = NULL,
|
||||
started_at = NULL, reject_reason = ''
|
||||
WHERE tenant_id = ? AND id IN (${ids.map(() => '?').join(',')})`,
|
||||
[input.tenantId, ...ids]
|
||||
);
|
||||
for (const taskId of ids) {
|
||||
await this.recordEvent(input, taskId, 'CLAIMED', 'WAITING', 'TIMEOUT_RECLAIM', '');
|
||||
}
|
||||
return { reclaimed: ids.length, taskIds: ids };
|
||||
}
|
||||
|
||||
async submit(input: CleaningActor & { taskId: string; photoUrls: string[]; note?: string }) {
|
||||
this.assertCleaner(input.access, 'write');
|
||||
if (input.photoUrls.length === 0) throw new CleaningTaskError('CLEANING_PHOTO_REQUIRED');
|
||||
@@ -417,6 +589,24 @@ export class CleaningTaskRepository {
|
||||
);
|
||||
}
|
||||
|
||||
private async recordEventWithConnection(
|
||||
connection: PoolConnection,
|
||||
input: CleaningActor,
|
||||
taskId: string,
|
||||
from: CleaningTaskStatus,
|
||||
to: CleaningTaskStatus,
|
||||
action: string,
|
||||
note: string
|
||||
) {
|
||||
await connection.execute(
|
||||
`INSERT IGNORE INTO qipai_cleaning_task_events
|
||||
(tenant_id, task_id, from_status, to_status, action, actor_id, trace_id, note, metadata)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, JSON_OBJECT())`,
|
||||
[input.tenantId, taskId, from, to, action, input.userId,
|
||||
`${input.traceId}-${taskId}`.slice(0, 128), note.slice(0, 512)]
|
||||
);
|
||||
}
|
||||
|
||||
private assertCleaner(access: AccessProfile, mode: 'read' | 'write') {
|
||||
const permission = mode === 'read' ? 'cleaning.task.read' : 'cleaning.task.write';
|
||||
if (!access.capabilities.includes(permission)
|
||||
@@ -425,6 +615,53 @@ export class CleaningTaskRepository {
|
||||
throw new CleaningTaskError('CLEANING_TASK_FORBIDDEN');
|
||||
}
|
||||
}
|
||||
|
||||
private assertSettlement(access: AccessProfile, mode: 'read' | 'write') {
|
||||
const permission = mode === 'read' ? 'cleaning.settlement.read' : 'cleaning.settlement.write';
|
||||
if (!access.capabilities.includes(permission)
|
||||
&& !access.capabilities.includes('tenant.manage')
|
||||
&& !access.roles.includes('PLATFORM_ADMIN')) {
|
||||
throw new CleaningTaskError('CLEANING_SETTLEMENT_FORBIDDEN');
|
||||
}
|
||||
}
|
||||
|
||||
private async getSettlement(
|
||||
connection: Pick<MySqlPool, 'execute'> | PoolConnection,
|
||||
tenantId: string,
|
||||
settlementId: string
|
||||
) {
|
||||
const [rows] = await connection.execute<SettlementRow[]>(
|
||||
`SELECT s.id, s.settlement_no AS settlementNo,
|
||||
s.cleaner_user_id AS cleanerUserId, u.nickname AS cleanerName,
|
||||
s.store_id AS storeId, st.name AS storeName, s.status,
|
||||
s.task_count AS taskCount, s.total_reward_cents AS totalRewardCents,
|
||||
s.period_start AS periodStart, s.period_end AS periodEnd,
|
||||
s.confirmed_at AS confirmedAt, s.paid_at AS paidAt,
|
||||
s.note, s.created_at AS createdAt
|
||||
FROM qipai_cleaning_settlements s
|
||||
INNER JOIN qipai_users u ON u.tenant_id = s.tenant_id AND u.id = s.cleaner_user_id
|
||||
LEFT JOIN qipai_stores st ON st.tenant_id = s.tenant_id AND st.id = s.store_id
|
||||
WHERE s.tenant_id = ? AND s.id = ? AND s.deleted_at IS NULL`,
|
||||
[tenantId, settlementId]
|
||||
);
|
||||
if (!rows[0]) throw new CleaningTaskError('CLEANING_SETTLEMENT_NOT_FOUND');
|
||||
return publicSettlement(rows[0]);
|
||||
}
|
||||
|
||||
private async transaction<T>(work: (connection: PoolConnection) => Promise<T>) {
|
||||
const connection = await this.pool.getConnection();
|
||||
try {
|
||||
await connection.beginTransaction();
|
||||
const result = await work(connection);
|
||||
await connection.commit();
|
||||
return result;
|
||||
} catch (error) {
|
||||
await connection.rollback();
|
||||
throw error;
|
||||
} finally {
|
||||
connection.release();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function storeScopeSql(access: AccessProfile, storeExpression: string) {
|
||||
@@ -462,6 +699,38 @@ function publicTask(row: CleaningTaskRow) {
|
||||
};
|
||||
}
|
||||
|
||||
function publicSettlement(row: SettlementRow) {
|
||||
return {
|
||||
id: String(row.id),
|
||||
settlementNo: row.settlementNo,
|
||||
cleanerUserId: String(row.cleanerUserId),
|
||||
cleanerName: row.cleanerName,
|
||||
storeId: row.storeId === null ? null : String(row.storeId),
|
||||
storeName: row.storeName,
|
||||
status: row.status,
|
||||
taskCount: Number(row.taskCount),
|
||||
totalRewardCents: Number(row.totalRewardCents),
|
||||
periodStart: row.periodStart,
|
||||
periodEnd: row.periodEnd,
|
||||
confirmedAt: row.confirmedAt,
|
||||
paidAt: row.paidAt,
|
||||
note: row.note,
|
||||
createdAt: row.createdAt
|
||||
};
|
||||
}
|
||||
|
||||
function minDate(values: Array<Date | null>) {
|
||||
const dates = values.filter((value): value is Date => value instanceof Date);
|
||||
if (dates.length === 0) return null;
|
||||
return new Date(Math.min(...dates.map((date) => date.getTime())));
|
||||
}
|
||||
|
||||
function maxDate(values: Array<Date | null>) {
|
||||
const dates = values.filter((value): value is Date => value instanceof Date);
|
||||
if (dates.length === 0) return null;
|
||||
return new Date(Math.max(...dates.map((date) => date.getTime())));
|
||||
}
|
||||
|
||||
function parseJsonArray(value: string | string[] | null): string[] {
|
||||
if (Array.isArray(value)) return value.map(String);
|
||||
if (!value) return [];
|
||||
|
||||
@@ -45,7 +45,8 @@ const migrationFiles: Record<MigrationDirection, readonly string[]> = {
|
||||
'database/migrations/2026062422_m07b_recharge_plans.up.sql',
|
||||
'database/migrations/2026062423_m07c_benefits.up.sql',
|
||||
'database/migrations/2026062524_m08a_recharge_wechat.up.sql',
|
||||
'database/migrations/2026062525_m08b_cleaner_tasks.up.sql'
|
||||
'database/migrations/2026062525_m08b_cleaner_tasks.up.sql',
|
||||
'database/migrations/2026062626_m08b_cleaning_settlements.up.sql'
|
||||
],
|
||||
verify: [
|
||||
'database/migrations/2026061601_m01b_core_schema.verify.sql',
|
||||
@@ -72,9 +73,11 @@ const migrationFiles: Record<MigrationDirection, readonly string[]> = {
|
||||
'database/migrations/2026062422_m07b_recharge_plans.verify.sql',
|
||||
'database/migrations/2026062423_m07c_benefits.verify.sql',
|
||||
'database/migrations/2026062524_m08a_recharge_wechat.verify.sql',
|
||||
'database/migrations/2026062525_m08b_cleaner_tasks.verify.sql'
|
||||
'database/migrations/2026062525_m08b_cleaner_tasks.verify.sql',
|
||||
'database/migrations/2026062626_m08b_cleaning_settlements.verify.sql'
|
||||
],
|
||||
down: [
|
||||
'database/migrations/2026062626_m08b_cleaning_settlements.down.sql',
|
||||
'database/migrations/2026062525_m08b_cleaner_tasks.down.sql',
|
||||
'database/migrations/2026062524_m08a_recharge_wechat.down.sql',
|
||||
'database/migrations/2026062423_m07c_benefits.down.sql',
|
||||
@@ -239,7 +242,8 @@ export async function executeMigrationPlan(
|
||||
1, 1, 1, 4, 7, 1,
|
||||
1, 1, 7, 7, 1,
|
||||
5, 10, 7, 3, 1,
|
||||
2, 8, 4, 3, 1
|
||||
2, 8, 4, 3, 1,
|
||||
2, 9, 5, 2, 1
|
||||
][index] ?? 1;
|
||||
if (!Array.isArray(result) || result.length < minimumRows) {
|
||||
throw new Error(
|
||||
|
||||
@@ -27,11 +27,31 @@ const assignSchema = z.object({
|
||||
}).strict();
|
||||
const completeSchema = z.object({ note: z.string().trim().max(512).optional() }).strict();
|
||||
const rejectSchema = z.object({ reason: z.string().trim().min(1).max(512) }).strict();
|
||||
const settlementStatusSchema = z.enum(['DRAFT', 'CONFIRMED', 'PAID', 'CANCELLED']);
|
||||
const settlementListSchema = z.object({
|
||||
page: z.coerce.number().int().min(1).default(1),
|
||||
pageSize: z.coerce.number().int().min(1).max(50).default(20),
|
||||
status: settlementStatusSchema.optional()
|
||||
});
|
||||
const settlementParamsSchema = z.object({ settlementId: z.string().regex(/^[1-9]\d{0,19}$/) });
|
||||
const settlementGenerateSchema = z.object({
|
||||
cleanerUserId: z.string().regex(/^[1-9]\d{0,19}$/),
|
||||
storeId: z.string().regex(/^[1-9]\d{0,19}$/).optional(),
|
||||
note: z.string().trim().max(512).optional()
|
||||
}).strict();
|
||||
const settlementConfirmSchema = z.object({
|
||||
note: z.string().trim().max(512).optional()
|
||||
}).strict();
|
||||
const reclaimSchema = z.object({
|
||||
olderThanMinutes: z.coerce.number().int().min(5).max(1440).default(60),
|
||||
limit: z.coerce.number().int().min(1).max(100).default(20)
|
||||
});
|
||||
|
||||
export interface CleaningRouteOptions {
|
||||
repository: Pick<CleaningTaskRepository,
|
||||
'listHall' | 'listMine' | 'listManage' | 'claim' | 'start' | 'rework' | 'submit'
|
||||
| 'assign' | 'complete' | 'reject' | 'settlementCandidates'
|
||||
| 'listSettlements' | 'generateSettlement' | 'confirmSettlement' | 'reclaimTimeouts'
|
||||
| 'assertCanUploadPhoto' | 'stats'>;
|
||||
mediaStorage?: MediaStorage;
|
||||
authRepository: Pick<AuthRepository, 'validateSession'>;
|
||||
@@ -109,6 +129,18 @@ export async function registerCleaningRoutes(
|
||||
}));
|
||||
});
|
||||
|
||||
app.get('/admin-api/cleaning/settlements', async (request, reply) => {
|
||||
const actor = await requireActor(request, reply, options, 'read');
|
||||
if (!actor) return;
|
||||
const query = settlementListSchema.safeParse(request.query);
|
||||
if (!query.success) return invalid(reply, request.traceId);
|
||||
return handle(reply, request.traceId, async () => ({
|
||||
code: 0,
|
||||
data: await options.repository.listSettlements({ ...actor, ...query.data }),
|
||||
traceId: request.traceId
|
||||
}));
|
||||
});
|
||||
|
||||
app.post('/app-api/cleaning/tasks/:taskId/claim', async (request, reply) => {
|
||||
const actor = await requireActor(request, reply, options, 'write');
|
||||
if (!actor) return;
|
||||
@@ -239,6 +271,47 @@ export async function registerCleaningRoutes(
|
||||
traceId: request.traceId
|
||||
}));
|
||||
});
|
||||
|
||||
app.post('/admin-api/cleaning/reclaim-timeouts', async (request, reply) => {
|
||||
const actor = await requireActor(request, reply, options, 'write');
|
||||
if (!actor) return;
|
||||
const body = reclaimSchema.safeParse(request.body ?? {});
|
||||
if (!body.success) return invalid(reply, request.traceId);
|
||||
return handle(reply, request.traceId, async () => ({
|
||||
code: 0,
|
||||
data: await options.repository.reclaimTimeouts({ ...actor, ...body.data }),
|
||||
traceId: request.traceId
|
||||
}));
|
||||
});
|
||||
|
||||
app.post('/admin-api/cleaning/settlements', async (request, reply) => {
|
||||
const actor = await requireActor(request, reply, options, 'write');
|
||||
if (!actor) return;
|
||||
const body = settlementGenerateSchema.safeParse(request.body ?? {});
|
||||
if (!body.success) return invalid(reply, request.traceId);
|
||||
return handle(reply, request.traceId, async () => reply.status(201).send({
|
||||
code: 0,
|
||||
data: await options.repository.generateSettlement({ ...actor, ...body.data }),
|
||||
traceId: request.traceId
|
||||
}));
|
||||
});
|
||||
|
||||
app.post('/admin-api/cleaning/settlements/:settlementId/confirm', async (request, reply) => {
|
||||
const actor = await requireActor(request, reply, options, 'write');
|
||||
if (!actor) return;
|
||||
const params = settlementParamsSchema.safeParse(request.params);
|
||||
const body = settlementConfirmSchema.safeParse(request.body ?? {});
|
||||
if (!params.success || !body.success) return invalid(reply, request.traceId);
|
||||
return handle(reply, request.traceId, async () => ({
|
||||
code: 0,
|
||||
data: await options.repository.confirmSettlement({
|
||||
...actor,
|
||||
settlementId: params.data.settlementId,
|
||||
note: body.data.note
|
||||
}),
|
||||
traceId: request.traceId
|
||||
}));
|
||||
});
|
||||
}
|
||||
|
||||
async function requireActor(
|
||||
@@ -290,7 +363,8 @@ async function handle(reply: FastifyReply, traceId: string, work: () => Promise<
|
||||
});
|
||||
}
|
||||
if (!(error instanceof CleaningTaskError)) throw error;
|
||||
const statusCode = error.code === 'CLEANING_TASK_FORBIDDEN' ? 403 : 409;
|
||||
const statusCode = error.code === 'CLEANING_TASK_FORBIDDEN'
|
||||
|| error.code === 'CLEANING_SETTLEMENT_FORBIDDEN' ? 403 : 409;
|
||||
return reply.status(statusCode).send({
|
||||
code: error.code,
|
||||
message: 'The cleaning task request cannot be completed.',
|
||||
|
||||
@@ -41,7 +41,10 @@ const app = await buildApp({
|
||||
return userId === '31'
|
||||
? {
|
||||
roles: ['CLEANER'],
|
||||
capabilities: ['cleaning.task.read', 'cleaning.task.write', 'cleaning.statistics.read'],
|
||||
capabilities: [
|
||||
'cleaning.task.read', 'cleaning.task.write', 'cleaning.statistics.read',
|
||||
'cleaning.settlement.read', 'cleaning.settlement.write'
|
||||
],
|
||||
storeIds: ['11']
|
||||
}
|
||||
: { roles: ['CUSTOMER'], capabilities: ['profile.read'], storeIds: [] };
|
||||
@@ -95,6 +98,22 @@ const app = await buildApp({
|
||||
calls.push(['settlementCandidates', input]);
|
||||
return { items: [task('COMPLETED')], total: 1, page: input.page, pageSize: input.pageSize };
|
||||
},
|
||||
async listSettlements(input) {
|
||||
calls.push(['listSettlements', input]);
|
||||
return { items: [settlementResponse(input.status || 'DRAFT')], total: 1, page: input.page, pageSize: input.pageSize };
|
||||
},
|
||||
async generateSettlement(input) {
|
||||
calls.push(['generateSettlement', input]);
|
||||
return settlementResponse('DRAFT');
|
||||
},
|
||||
async confirmSettlement(input) {
|
||||
calls.push(['confirmSettlement', input]);
|
||||
return settlementResponse('CONFIRMED');
|
||||
},
|
||||
async reclaimTimeouts(input) {
|
||||
calls.push(['reclaimTimeouts', input]);
|
||||
return { reclaimed: 2, taskIds: ['101', '102'] };
|
||||
},
|
||||
async stats(input) {
|
||||
calls.push(['stats', input]);
|
||||
return { byStatus: { SUBMITTED: 2 }, pendingSettlementCents: 1200 };
|
||||
@@ -232,6 +251,45 @@ const settlement = await app.inject({
|
||||
assert.equal(settlement.statusCode, 200);
|
||||
assert.equal(calls.at(-1)[0], 'settlementCandidates');
|
||||
|
||||
const settlementList = await app.inject({
|
||||
method: 'GET',
|
||||
url: '/admin-api/cleaning/settlements?status=DRAFT',
|
||||
headers: { authorization: `Bearer ${token}` }
|
||||
});
|
||||
assert.equal(settlementList.statusCode, 200);
|
||||
assert.equal(calls.at(-1)[0], 'listSettlements');
|
||||
assert.equal(calls.at(-1)[1].status, 'DRAFT');
|
||||
|
||||
const generatedSettlement = await app.inject({
|
||||
method: 'POST',
|
||||
url: '/admin-api/cleaning/settlements',
|
||||
headers: { authorization: `Bearer ${token}` },
|
||||
payload: { cleanerUserId: '31', storeId: '11', note: 'weekly settlement' }
|
||||
});
|
||||
assert.equal(generatedSettlement.statusCode, 201);
|
||||
assert.equal(calls.at(-1)[0], 'generateSettlement');
|
||||
assert.equal(calls.at(-1)[1].cleanerUserId, '31');
|
||||
|
||||
const confirmedSettlement = await app.inject({
|
||||
method: 'POST',
|
||||
url: '/admin-api/cleaning/settlements/501/confirm',
|
||||
headers: { authorization: `Bearer ${token}` },
|
||||
payload: { note: 'confirmed' }
|
||||
});
|
||||
assert.equal(confirmedSettlement.statusCode, 200);
|
||||
assert.equal(calls.at(-1)[0], 'confirmSettlement');
|
||||
assert.equal(calls.at(-1)[1].settlementId, '501');
|
||||
|
||||
const reclaimed = await app.inject({
|
||||
method: 'POST',
|
||||
url: '/admin-api/cleaning/reclaim-timeouts',
|
||||
headers: { authorization: `Bearer ${token}` },
|
||||
payload: { olderThanMinutes: 30, limit: 10 }
|
||||
});
|
||||
assert.equal(reclaimed.statusCode, 200);
|
||||
assert.equal(calls.at(-1)[0], 'reclaimTimeouts');
|
||||
assert.equal(calls.at(-1)[1].olderThanMinutes, 30);
|
||||
|
||||
const stats = await app.inject({
|
||||
method: 'GET',
|
||||
url: '/app-api/cleaning/stats',
|
||||
@@ -269,3 +327,22 @@ function task(status) {
|
||||
photoUrls: []
|
||||
};
|
||||
}
|
||||
|
||||
function settlementResponse(status) {
|
||||
return {
|
||||
id: '501',
|
||||
settlementNo: 'CLS-20260626-0001',
|
||||
cleanerUserId: '31',
|
||||
cleanerName: 'Cleaner',
|
||||
storeId: '11',
|
||||
storeName: 'Test Store',
|
||||
status,
|
||||
taskCount: 2,
|
||||
totalRewardCents: 1200,
|
||||
periodStart: new Date(),
|
||||
periodEnd: new Date(),
|
||||
confirmedAt: status === 'CONFIRMED' ? new Date() : null,
|
||||
paidAt: null,
|
||||
note: ''
|
||||
};
|
||||
}
|
||||
|
||||
@@ -84,6 +84,9 @@ const rechargeWechatVerifySql = read('database/migrations/2026062524_m08a_rechar
|
||||
const cleaningUpSql = read('database/migrations/2026062525_m08b_cleaner_tasks.up.sql');
|
||||
const cleaningDownSql = read('database/migrations/2026062525_m08b_cleaner_tasks.down.sql');
|
||||
const cleaningVerifySql = read('database/migrations/2026062525_m08b_cleaner_tasks.verify.sql');
|
||||
const cleaningSettlementUpSql = read('database/migrations/2026062626_m08b_cleaning_settlements.up.sql');
|
||||
const cleaningSettlementDownSql = read('database/migrations/2026062626_m08b_cleaning_settlements.down.sql');
|
||||
const cleaningSettlementVerifySql = read('database/migrations/2026062626_m08b_cleaning_settlements.verify.sql');
|
||||
|
||||
const coreTables = [
|
||||
'qipai_schema_migrations',
|
||||
@@ -398,4 +401,15 @@ assert.match(cleaningUpSql, /uq_qipai_cleaning_task_order/);
|
||||
assert.match(cleaningUpSql, /cleaning\.task\.write/);
|
||||
assert.match(cleaningUpSql, /cleaning\.statistics\.read/);
|
||||
|
||||
for (const table of ['qipai_cleaning_settlements', 'qipai_cleaning_settlement_items']) {
|
||||
assert.match(cleaningSettlementUpSql, new RegExp(`CREATE TABLE IF NOT EXISTS ${table}`));
|
||||
assert.match(cleaningSettlementDownSql, new RegExp(`DROP TABLE IF EXISTS ${table}`));
|
||||
assert.match(cleaningSettlementVerifySql, new RegExp(`'${table}'`));
|
||||
}
|
||||
assert.match(cleaningSettlementUpSql, /settlement_no VARCHAR\(64\) NOT NULL/);
|
||||
assert.match(cleaningSettlementUpSql, /total_reward_cents INT UNSIGNED NOT NULL/);
|
||||
assert.match(cleaningSettlementUpSql, /uq_qipai_cleaning_settlement_item_task/);
|
||||
assert.match(cleaningSettlementUpSql, /cleaning\.settlement\.read/);
|
||||
assert.match(cleaningSettlementUpSql, /cleaning\.settlement\.write/);
|
||||
|
||||
console.log('PASS: M01-B through M08-B migration contracts are present.');
|
||||
|
||||
@@ -35,7 +35,8 @@ assert.match(plan.file, /2026062220_m06c_iot_messages\.up\.sql/);
|
||||
assert.match(plan.file, /2026062421_m07a_wallet_ledger\.up\.sql/);
|
||||
assert.match(plan.file, /2026062422_m07b_recharge_plans\.up\.sql/);
|
||||
assert.match(plan.file, /2026062524_m08a_recharge_wechat\.up\.sql/);
|
||||
assert.match(plan.file, /2026062525_m08b_cleaner_tasks\.up\.sql$/);
|
||||
assert.match(plan.file, /2026062525_m08b_cleaner_tasks\.up\.sql/);
|
||||
assert.match(plan.file, /2026062626_m08b_cleaning_settlements\.up\.sql$/);
|
||||
assert.match(plan.checksum, /^[a-f0-9]{64}$/);
|
||||
assert.ok(plan.statements.length >= 11);
|
||||
|
||||
|
||||
Reference in New Issue
Block a user