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 [];
|
||||
|
||||
Reference in New Issue
Block a user