feat(M08-B): 接入保洁任务端基础流程
This commit is contained in:
@@ -0,0 +1,286 @@
|
||||
import type { ResultSetHeader, RowDataPacket } from 'mysql2/promise';
|
||||
import type { AccessProfile } from '../auth/rbac-repository.js';
|
||||
import type { MySqlPool } from '../db/mysql.js';
|
||||
|
||||
export const cleaningTaskStatuses = [
|
||||
'WAITING', 'CLAIMED', 'STARTED', 'SUBMITTED', 'COMPLETED',
|
||||
'REJECTED', 'EXEMPT', 'SETTLED', 'CANCELLED'
|
||||
] as const;
|
||||
export type CleaningTaskStatus = typeof cleaningTaskStatuses[number];
|
||||
|
||||
export class CleaningTaskError extends Error {
|
||||
constructor(public readonly code: string) { super(code); }
|
||||
}
|
||||
|
||||
export interface CleaningActor {
|
||||
tenantId: string;
|
||||
userId: string;
|
||||
access: AccessProfile;
|
||||
traceId: string;
|
||||
}
|
||||
|
||||
interface CleaningTaskRow extends RowDataPacket {
|
||||
id: string;
|
||||
taskNo: string;
|
||||
storeId: string;
|
||||
storeName: string;
|
||||
roomId: string;
|
||||
roomName: string;
|
||||
roomNo: string;
|
||||
orderId: string | null;
|
||||
orderNo: string | null;
|
||||
status: CleaningTaskStatus;
|
||||
cleanerUserId: string | null;
|
||||
priority: number;
|
||||
rewardCents: number;
|
||||
requirement: string;
|
||||
photoUrlsJson: string | string[] | null;
|
||||
rejectReason: string;
|
||||
claimedAt: Date | null;
|
||||
startedAt: Date | null;
|
||||
submittedAt: Date | null;
|
||||
completedAt: Date | null;
|
||||
createdAt: Date;
|
||||
updatedAt: Date;
|
||||
}
|
||||
interface CountRow extends RowDataPacket { total: number }
|
||||
interface StatusCountRow extends RowDataPacket { status: CleaningTaskStatus; total: number }
|
||||
interface AmountRow extends RowDataPacket { amount: number | null }
|
||||
interface CurrentStatusRow extends RowDataPacket { status: CleaningTaskStatus; cleanerUserId: string | null }
|
||||
|
||||
export class CleaningTaskRepository {
|
||||
constructor(private readonly pool: MySqlPool) {}
|
||||
|
||||
async listHall(input: CleaningActor & { page: number; pageSize: number; status?: CleaningTaskStatus }) {
|
||||
this.assertCleaner(input.access, 'read');
|
||||
const status = input.status ?? 'WAITING';
|
||||
const where = [
|
||||
't.tenant_id = ?',
|
||||
't.deleted_at IS NULL',
|
||||
't.status = ?',
|
||||
storeScopeSql(input.access, 't.store_id')
|
||||
];
|
||||
const params: Array<string | number> = [input.tenantId, status];
|
||||
return this.listByWhere(where, params, input.page, input.pageSize, 't.priority ASC, t.created_at ASC');
|
||||
}
|
||||
|
||||
async listMine(input: CleaningActor & { page: number; pageSize: number; status?: CleaningTaskStatus }) {
|
||||
this.assertCleaner(input.access, 'read');
|
||||
const where = [
|
||||
't.tenant_id = ?',
|
||||
't.deleted_at IS NULL',
|
||||
't.cleaner_user_id = ?'
|
||||
];
|
||||
const params: Array<string | number> = [input.tenantId, input.userId];
|
||||
if (input.status) {
|
||||
where.push('t.status = ?');
|
||||
params.push(input.status);
|
||||
}
|
||||
return this.listByWhere(where, params, input.page, input.pageSize, 't.updated_at DESC, t.id DESC');
|
||||
}
|
||||
|
||||
async claim(input: CleaningActor & { taskId: string }) {
|
||||
this.assertCleaner(input.access, 'write');
|
||||
await this.assertStoreVisible(input, input.taskId);
|
||||
const [result] = await this.pool.execute<ResultSetHeader>(
|
||||
`UPDATE qipai_cleaning_tasks
|
||||
SET status = 'CLAIMED', cleaner_user_id = ?, claimed_at = UTC_TIMESTAMP(3)
|
||||
WHERE tenant_id = ? AND id = ? AND status = 'WAITING' AND cleaner_user_id IS NULL
|
||||
AND deleted_at IS NULL`,
|
||||
[input.userId, input.tenantId, input.taskId]
|
||||
);
|
||||
if (result.affectedRows !== 1) throw new CleaningTaskError('CLEANING_TASK_NOT_CLAIMABLE');
|
||||
await this.recordEvent(input, input.taskId, 'WAITING', 'CLAIMED', 'CLAIM', '');
|
||||
return this.getMineTask(input, input.taskId);
|
||||
}
|
||||
|
||||
async start(input: CleaningActor & { taskId: string }) {
|
||||
return this.moveMine(input, 'CLAIMED', 'STARTED', 'START', 'started_at', '');
|
||||
}
|
||||
|
||||
async submit(input: CleaningActor & { taskId: string; photoUrls: string[]; note?: string }) {
|
||||
const task = await this.moveMine(
|
||||
input,
|
||||
'STARTED',
|
||||
'SUBMITTED',
|
||||
'SUBMIT',
|
||||
'submitted_at',
|
||||
input.note ?? '',
|
||||
{ photo_urls_json: JSON.stringify(input.photoUrls.slice(0, 9)) }
|
||||
);
|
||||
return task;
|
||||
}
|
||||
|
||||
async stats(input: CleaningActor) {
|
||||
this.assertCleaner(input.access, 'read');
|
||||
const [counts] = await this.pool.execute<StatusCountRow[]>(
|
||||
`SELECT status, COUNT(*) AS total
|
||||
FROM qipai_cleaning_tasks
|
||||
WHERE tenant_id = ? AND cleaner_user_id = ? AND deleted_at IS NULL
|
||||
GROUP BY status`,
|
||||
[input.tenantId, input.userId]
|
||||
);
|
||||
const [amountRows] = await this.pool.execute<AmountRow[]>(
|
||||
`SELECT COALESCE(SUM(reward_cents), 0) AS amount
|
||||
FROM qipai_cleaning_tasks
|
||||
WHERE tenant_id = ? AND cleaner_user_id = ? AND status IN ('SUBMITTED', 'COMPLETED')
|
||||
AND settled_at IS NULL AND deleted_at IS NULL`,
|
||||
[input.tenantId, input.userId]
|
||||
);
|
||||
return {
|
||||
byStatus: Object.fromEntries(counts.map((row) => [row.status, Number(row.total)])),
|
||||
pendingSettlementCents: Number(amountRows[0]?.amount ?? 0)
|
||||
};
|
||||
}
|
||||
|
||||
private async listByWhere(
|
||||
where: string[],
|
||||
params: Array<string | number>,
|
||||
page: number,
|
||||
pageSize: number,
|
||||
orderBy: string
|
||||
) {
|
||||
const whereSql = where.join(' AND ');
|
||||
const offset = (page - 1) * pageSize;
|
||||
const [counts] = await this.pool.execute<CountRow[]>(
|
||||
`SELECT COUNT(*) AS total FROM qipai_cleaning_tasks t WHERE ${whereSql}`,
|
||||
params
|
||||
);
|
||||
const [rows] = await this.pool.execute<CleaningTaskRow[]>(
|
||||
`SELECT t.id, t.task_no AS taskNo, t.store_id AS storeId, s.name AS storeName,
|
||||
t.room_id AS roomId, r.name AS roomName, r.room_no AS roomNo,
|
||||
t.order_id AS orderId, o.order_no AS orderNo, t.status,
|
||||
t.cleaner_user_id AS cleanerUserId, t.priority, t.reward_cents AS rewardCents,
|
||||
t.requirement, t.photo_urls_json AS photoUrlsJson, t.reject_reason AS rejectReason,
|
||||
t.claimed_at AS claimedAt, t.started_at AS startedAt,
|
||||
t.submitted_at AS submittedAt, t.completed_at AS completedAt,
|
||||
t.created_at AS createdAt, t.updated_at AS updatedAt
|
||||
FROM qipai_cleaning_tasks t
|
||||
INNER JOIN qipai_stores s ON s.tenant_id = t.tenant_id AND s.id = t.store_id
|
||||
INNER JOIN qipai_rooms r ON r.tenant_id = t.tenant_id AND r.id = t.room_id
|
||||
LEFT JOIN qipai_orders o ON o.tenant_id = t.tenant_id AND o.id = t.order_id
|
||||
WHERE ${whereSql}
|
||||
ORDER BY ${orderBy}
|
||||
LIMIT ? OFFSET ?`,
|
||||
[...params, pageSize, offset]
|
||||
);
|
||||
return { items: rows.map(publicTask), total: Number(counts[0]?.total ?? 0), page, pageSize };
|
||||
}
|
||||
|
||||
private async getMineTask(input: CleaningActor, taskId: string) {
|
||||
const result = await this.listMine({ ...input, page: 1, pageSize: 50 });
|
||||
const task = result.items.find((item) => item.id === taskId);
|
||||
if (!task) throw new CleaningTaskError('CLEANING_TASK_NOT_FOUND');
|
||||
return task;
|
||||
}
|
||||
|
||||
private async moveMine(
|
||||
input: CleaningActor & { taskId: string },
|
||||
from: CleaningTaskStatus,
|
||||
to: CleaningTaskStatus,
|
||||
action: string,
|
||||
timestampColumn: 'started_at' | 'submitted_at',
|
||||
note: string,
|
||||
extra?: { photo_urls_json: string }
|
||||
) {
|
||||
this.assertCleaner(input.access, 'write');
|
||||
const setExtra = extra ? ', photo_urls_json = ?' : '';
|
||||
const params: Array<string | number> = extra
|
||||
? [extra.photo_urls_json, input.tenantId, input.taskId, input.userId, from]
|
||||
: [input.tenantId, input.taskId, input.userId, from];
|
||||
const [result] = await this.pool.execute<ResultSetHeader>(
|
||||
`UPDATE qipai_cleaning_tasks
|
||||
SET status = ?, ${timestampColumn} = UTC_TIMESTAMP(3)${setExtra}
|
||||
WHERE tenant_id = ? AND id = ? AND cleaner_user_id = ? AND status = ?
|
||||
AND deleted_at IS NULL`,
|
||||
[to, ...params]
|
||||
);
|
||||
if (result.affectedRows !== 1) throw new CleaningTaskError('CLEANING_TASK_STATUS_CONFLICT');
|
||||
await this.recordEvent(input, input.taskId, from, to, action, note);
|
||||
return this.getMineTask(input, input.taskId);
|
||||
}
|
||||
|
||||
private async assertStoreVisible(input: CleaningActor, taskId: string) {
|
||||
if (input.access.capabilities.includes('tenant.manage') || input.access.roles.includes('PLATFORM_ADMIN')) return;
|
||||
const [rows] = await this.pool.execute<RowDataPacket[]>(
|
||||
`SELECT store_id AS storeId FROM qipai_cleaning_tasks
|
||||
WHERE tenant_id = ? AND id = ? AND deleted_at IS NULL`,
|
||||
[input.tenantId, taskId]
|
||||
);
|
||||
const storeId = rows[0]?.storeId;
|
||||
if (!storeId || !input.access.storeIds.includes(String(storeId))) {
|
||||
throw new CleaningTaskError('CLEANING_TASK_FORBIDDEN');
|
||||
}
|
||||
}
|
||||
|
||||
private async recordEvent(
|
||||
input: CleaningActor,
|
||||
taskId: string,
|
||||
from: CleaningTaskStatus,
|
||||
to: CleaningTaskStatus,
|
||||
action: string,
|
||||
note: string
|
||||
) {
|
||||
await this.pool.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, 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)
|
||||
&& !access.capabilities.includes('tenant.manage')
|
||||
&& !access.roles.includes('PLATFORM_ADMIN')) {
|
||||
throw new CleaningTaskError('CLEANING_TASK_FORBIDDEN');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function storeScopeSql(access: AccessProfile, storeExpression: string) {
|
||||
if (access.capabilities.includes('tenant.manage') || access.roles.includes('PLATFORM_ADMIN')) {
|
||||
return '1 = 1';
|
||||
}
|
||||
if (access.storeIds.length === 0) return '1 = 0';
|
||||
return `${storeExpression} IN (${access.storeIds.map((id) => Number(id)).join(',')})`;
|
||||
}
|
||||
|
||||
function publicTask(row: CleaningTaskRow) {
|
||||
return {
|
||||
id: String(row.id),
|
||||
taskNo: row.taskNo,
|
||||
storeId: String(row.storeId),
|
||||
storeName: row.storeName,
|
||||
roomId: String(row.roomId),
|
||||
roomName: row.roomName,
|
||||
roomNo: row.roomNo,
|
||||
orderId: row.orderId === null ? null : String(row.orderId),
|
||||
orderNo: row.orderNo,
|
||||
status: row.status,
|
||||
cleanerUserId: row.cleanerUserId === null ? null : String(row.cleanerUserId),
|
||||
priority: Number(row.priority),
|
||||
rewardCents: Number(row.rewardCents),
|
||||
requirement: row.requirement,
|
||||
photoUrls: parseJsonArray(row.photoUrlsJson),
|
||||
rejectReason: row.rejectReason,
|
||||
claimedAt: row.claimedAt,
|
||||
startedAt: row.startedAt,
|
||||
submittedAt: row.submittedAt,
|
||||
completedAt: row.completedAt,
|
||||
createdAt: row.createdAt,
|
||||
updatedAt: row.updatedAt
|
||||
};
|
||||
}
|
||||
|
||||
function parseJsonArray(value: string | string[] | null): string[] {
|
||||
if (Array.isArray(value)) return value.map(String);
|
||||
if (!value) return [];
|
||||
try {
|
||||
const parsed = JSON.parse(value);
|
||||
return Array.isArray(parsed) ? parsed.map(String) : [];
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user