feat(M08-B): 补保洁照片上传和自动建单
This commit is contained in:
@@ -1,4 +1,4 @@
|
||||
import type { ResultSetHeader, RowDataPacket } from 'mysql2/promise';
|
||||
import type { PoolConnection, ResultSetHeader, RowDataPacket } from 'mysql2/promise';
|
||||
import type { AccessProfile } from '../auth/rbac-repository.js';
|
||||
import type { MySqlPool } from '../db/mysql.js';
|
||||
|
||||
@@ -47,6 +47,12 @@ 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 }
|
||||
interface FinishedOrderRow extends RowDataPacket {
|
||||
id: string;
|
||||
orderNo: string;
|
||||
storeId: string;
|
||||
roomId: string;
|
||||
}
|
||||
|
||||
export class CleaningTaskRepository {
|
||||
constructor(private readonly pool: MySqlPool) {}
|
||||
@@ -98,17 +104,84 @@ export class CleaningTaskRepository {
|
||||
return this.moveMine(input, 'CLAIMED', 'STARTED', 'START', 'started_at', '');
|
||||
}
|
||||
|
||||
async rework(input: CleaningActor & { taskId: string }) {
|
||||
return this.moveMine(input, 'REJECTED', 'STARTED', 'REWORK', 'started_at', '', {
|
||||
photo_urls_json: JSON.stringify([]),
|
||||
reject_reason: ''
|
||||
});
|
||||
}
|
||||
|
||||
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)) }
|
||||
this.assertCleaner(input.access, 'write');
|
||||
if (input.photoUrls.length === 0) throw new CleaningTaskError('CLEANING_PHOTO_REQUIRED');
|
||||
const [rows] = await this.pool.execute<CurrentStatusRow[]>(
|
||||
`SELECT status, cleaner_user_id AS cleanerUserId
|
||||
FROM qipai_cleaning_tasks
|
||||
WHERE tenant_id = ? AND id = ? AND cleaner_user_id = ? AND deleted_at IS NULL`,
|
||||
[input.tenantId, input.taskId, input.userId]
|
||||
);
|
||||
return task;
|
||||
const current = rows[0];
|
||||
if (!current || !['STARTED', 'REJECTED'].includes(current.status)) {
|
||||
throw new CleaningTaskError('CLEANING_TASK_STATUS_CONFLICT');
|
||||
}
|
||||
const [result] = await this.pool.execute<ResultSetHeader>(
|
||||
`UPDATE qipai_cleaning_tasks
|
||||
SET status = 'SUBMITTED', submitted_at = UTC_TIMESTAMP(3),
|
||||
photo_urls_json = ?, reject_reason = ''
|
||||
WHERE tenant_id = ? AND id = ? AND cleaner_user_id = ? AND status = ?
|
||||
AND deleted_at IS NULL`,
|
||||
[JSON.stringify(input.photoUrls.slice(0, 9)), input.tenantId, input.taskId,
|
||||
input.userId, current.status]
|
||||
);
|
||||
if (result.affectedRows !== 1) throw new CleaningTaskError('CLEANING_TASK_STATUS_CONFLICT');
|
||||
await this.recordEvent(input, input.taskId, current.status, 'SUBMITTED', 'SUBMIT', input.note ?? '');
|
||||
return this.getMineTask(input, input.taskId);
|
||||
}
|
||||
|
||||
async assertCanUploadPhoto(input: CleaningActor & { taskId: string }) {
|
||||
this.assertCleaner(input.access, 'write');
|
||||
const [rows] = await this.pool.execute<CurrentStatusRow[]>(
|
||||
`SELECT status, cleaner_user_id AS cleanerUserId
|
||||
FROM qipai_cleaning_tasks
|
||||
WHERE tenant_id = ? AND id = ? AND cleaner_user_id = ? AND status IN ('STARTED', 'REJECTED')
|
||||
AND deleted_at IS NULL`,
|
||||
[input.tenantId, input.taskId, input.userId]
|
||||
);
|
||||
if (!rows[0]) throw new CleaningTaskError('CLEANING_TASK_STATUS_CONFLICT');
|
||||
}
|
||||
|
||||
async createForFinishedOrder(
|
||||
connection: PoolConnection,
|
||||
input: { tenantId: string; orderId: string; actorId: string; traceId: string }
|
||||
) {
|
||||
const [orders] = await connection.execute<FinishedOrderRow[]>(
|
||||
`SELECT id, order_no AS orderNo, store_id AS storeId, room_id AS roomId
|
||||
FROM qipai_orders
|
||||
WHERE tenant_id = ? AND id = ? AND status = 'FINISHED' AND deleted_at IS NULL
|
||||
LIMIT 1`,
|
||||
[input.tenantId, input.orderId]
|
||||
);
|
||||
const order = orders[0];
|
||||
if (!order) throw new CleaningTaskError('CLEANING_ORDER_NOT_FINISHED');
|
||||
const taskNo = `CLN-${order.orderNo}`;
|
||||
const [result] = await connection.execute<ResultSetHeader>(
|
||||
`INSERT IGNORE INTO qipai_cleaning_tasks
|
||||
(tenant_id, store_id, room_id, order_id, task_no, status, priority,
|
||||
reward_cents, requirement, photo_urls_json)
|
||||
VALUES (?, ?, ?, ?, ?, 'WAITING', 5, 0, '订单结束后保洁', JSON_ARRAY())`,
|
||||
[input.tenantId, order.storeId, order.roomId, input.orderId, taskNo]
|
||||
);
|
||||
if (result.affectedRows === 1) {
|
||||
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)
|
||||
SELECT tenant_id, id, NULL, 'WAITING', 'AUTO_CREATE', ?, ?, '订单结束自动创建保洁任务',
|
||||
JSON_OBJECT('orderId', ?)
|
||||
FROM qipai_cleaning_tasks
|
||||
WHERE tenant_id = ? AND order_id = ?`,
|
||||
[input.actorId, input.traceId, input.orderId, input.tenantId, input.orderId]
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
async stats(input: CleaningActor) {
|
||||
@@ -181,19 +254,26 @@ export class CleaningTaskRepository {
|
||||
action: string,
|
||||
timestampColumn: 'started_at' | 'submitted_at',
|
||||
note: string,
|
||||
extra?: { photo_urls_json: string }
|
||||
extra?: { photo_urls_json?: string; reject_reason?: 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 extraAssignments: string[] = [];
|
||||
const extraParams: Array<string | number> = [];
|
||||
if (extra?.photo_urls_json !== undefined) {
|
||||
extraAssignments.push('photo_urls_json = ?');
|
||||
extraParams.push(extra.photo_urls_json);
|
||||
}
|
||||
if (extra?.reject_reason !== undefined) {
|
||||
extraAssignments.push('reject_reason = ?');
|
||||
extraParams.push(extra.reject_reason);
|
||||
}
|
||||
const setExtra = extraAssignments.length > 0 ? `, ${extraAssignments.join(', ')}` : '';
|
||||
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]
|
||||
[to, ...extraParams, input.tenantId, input.taskId, input.userId, from]
|
||||
);
|
||||
if (result.affectedRows !== 1) throw new CleaningTaskError('CLEANING_TASK_STATUS_CONFLICT');
|
||||
await this.recordEvent(input, input.taskId, from, to, action, note);
|
||||
|
||||
@@ -74,7 +74,13 @@ export class OrderStateError extends Error {
|
||||
export class OrderStateRepository {
|
||||
constructor(
|
||||
private readonly pool: MySqlPool,
|
||||
private readonly benefits?: Pick<MarketingBenefitService, 'releaseReservedInTransaction'>
|
||||
private readonly benefits?: Pick<MarketingBenefitService, 'releaseReservedInTransaction'>,
|
||||
private readonly cleaningTasks?: {
|
||||
createForFinishedOrder(
|
||||
connection: PoolConnection,
|
||||
input: { tenantId: string; orderId: string; actorId: string; traceId: string }
|
||||
): Promise<void>;
|
||||
}
|
||||
) {}
|
||||
|
||||
async transition(actor: OrderActor, orderId: string, action: OrderAction, reason = '') {
|
||||
@@ -103,6 +109,14 @@ export class OrderStateRepository {
|
||||
[targetStatus, nextVersion, actor.tenantId, orderId]
|
||||
);
|
||||
await this.applyReservationState(connection, actor.tenantId, orderId, targetStatus);
|
||||
if (targetStatus === 'FINISHED' && this.cleaningTasks) {
|
||||
await this.cleaningTasks.createForFinishedOrder(connection, {
|
||||
tenantId: actor.tenantId,
|
||||
orderId,
|
||||
actorId: actor.userId,
|
||||
traceId: actor.traceId
|
||||
});
|
||||
}
|
||||
const [result] = await connection.execute<ResultSetHeader>(
|
||||
`INSERT INTO qipai_order_status_history
|
||||
(tenant_id, order_id, from_status, to_status, action, actor_type,
|
||||
|
||||
@@ -3,6 +3,7 @@ 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 { MediaStorage, MediaValidationError } from '../content/media-storage.js';
|
||||
import {
|
||||
CleaningTaskError,
|
||||
cleaningTaskStatuses,
|
||||
@@ -22,7 +23,9 @@ const submitSchema = z.object({
|
||||
});
|
||||
|
||||
export interface CleaningRouteOptions {
|
||||
repository: Pick<CleaningTaskRepository, 'listHall' | 'listMine' | 'claim' | 'start' | 'submit' | 'stats'>;
|
||||
repository: Pick<CleaningTaskRepository,
|
||||
'listHall' | 'listMine' | 'claim' | 'start' | 'rework' | 'submit' | 'assertCanUploadPhoto' | 'stats'>;
|
||||
mediaStorage?: MediaStorage;
|
||||
authRepository: Pick<AuthRepository, 'validateSession'>;
|
||||
accessControl: { getAccessProfile(tenantId: string, userId: string): Promise<AccessProfile> };
|
||||
jwtSecret: string;
|
||||
@@ -32,6 +35,14 @@ export async function registerCleaningRoutes(
|
||||
app: FastifyInstance,
|
||||
options: CleaningRouteOptions
|
||||
): Promise<void> {
|
||||
if (options.mediaStorage && !app.hasContentTypeParser('application/octet-stream')) {
|
||||
app.addContentTypeParser(
|
||||
'application/octet-stream',
|
||||
{ parseAs: 'buffer', bodyLimit: 8 * 1024 * 1024 },
|
||||
(_request, body, done) => done(null, body)
|
||||
);
|
||||
}
|
||||
|
||||
app.get('/app-api/cleaning/tasks/hall', async (request, reply) => {
|
||||
const actor = await requireActor(request, reply, options, 'read');
|
||||
if (!actor) return;
|
||||
@@ -90,6 +101,43 @@ export async function registerCleaningRoutes(
|
||||
}));
|
||||
});
|
||||
|
||||
app.post('/app-api/cleaning/tasks/:taskId/rework', async (request, reply) => {
|
||||
const actor = await requireActor(request, reply, options, 'write');
|
||||
if (!actor) return;
|
||||
const params = paramsSchema.safeParse(request.params);
|
||||
if (!params.success) return invalid(reply, request.traceId);
|
||||
return handle(reply, request.traceId, async () => ({
|
||||
code: 0,
|
||||
data: await options.repository.rework({ ...actor, taskId: params.data.taskId }),
|
||||
traceId: request.traceId
|
||||
}));
|
||||
});
|
||||
|
||||
app.post('/app-api/cleaning/tasks/:taskId/photos', async (request, reply) => {
|
||||
if (!options.mediaStorage) return reply.status(501).send({
|
||||
code: 'CLEANING_PHOTO_UPLOAD_UNAVAILABLE',
|
||||
message: 'Cleaning photo upload is not configured.',
|
||||
traceId: request.traceId
|
||||
});
|
||||
const actor = await requireActor(request, reply, options, 'write');
|
||||
if (!actor) return;
|
||||
const params = paramsSchema.safeParse(request.params);
|
||||
const originalName = singleHeader(request.headers['x-file-name']);
|
||||
if (!params.success || !originalName || !Buffer.isBuffer(request.body)) {
|
||||
return invalid(reply, request.traceId);
|
||||
}
|
||||
return handle(reply, request.traceId, async () => {
|
||||
await options.repository.assertCanUploadPhoto({ ...actor, taskId: params.data.taskId });
|
||||
const image = await options.mediaStorage!.storeImage({
|
||||
tenantId: actor.tenantId,
|
||||
originalName,
|
||||
contentType: singleHeader(request.headers['x-image-content-type']) ?? '',
|
||||
body: request.body as Buffer
|
||||
});
|
||||
return reply.status(201).send({ code: 0, data: image, traceId: request.traceId });
|
||||
});
|
||||
});
|
||||
|
||||
app.post('/app-api/cleaning/tasks/:taskId/submit', async (request, reply) => {
|
||||
const actor = await requireActor(request, reply, options, 'write');
|
||||
if (!actor) return;
|
||||
@@ -150,6 +198,13 @@ async function handle(reply: FastifyReply, traceId: string, work: () => Promise<
|
||||
try {
|
||||
return await work();
|
||||
} catch (error) {
|
||||
if (error instanceof MediaValidationError) {
|
||||
return reply.status(400).send({
|
||||
code: error.code,
|
||||
message: 'The cleaning task request cannot be completed.',
|
||||
traceId
|
||||
});
|
||||
}
|
||||
if (!(error instanceof CleaningTaskError)) throw error;
|
||||
const statusCode = error.code === 'CLEANING_TASK_FORBIDDEN' ? 403 : 409;
|
||||
return reply.status(statusCode).send({
|
||||
@@ -160,6 +215,10 @@ async function handle(reply: FastifyReply, traceId: string, work: () => Promise<
|
||||
}
|
||||
}
|
||||
|
||||
function singleHeader(value: string | string[] | undefined) {
|
||||
return Array.isArray(value) ? value[0] : value;
|
||||
}
|
||||
|
||||
function invalid(reply: FastifyReply, traceId: string) {
|
||||
return reply.status(400).send({
|
||||
code: 'INVALID_CLEANING_TASK_REQUEST',
|
||||
|
||||
@@ -46,6 +46,7 @@ const accessControl = new RbacRepository(pool);
|
||||
const orderManagementRepository = new OrderManagementRepository(pool);
|
||||
const walletLedgerService = new WalletLedgerService(pool);
|
||||
const marketingBenefits = new MarketingBenefitService(pool);
|
||||
const cleaningTaskRepository = new CleaningTaskRepository(pool);
|
||||
const paymentRepository = new PaymentRepository(pool, walletLedgerService, marketingBenefits);
|
||||
const wechatCredentials = parseWechatPayCredentials(config.payment.wechatCredentialsJson);
|
||||
const wechatPayClient = new WechatPayClient(new FetchWechatPayTransport());
|
||||
@@ -103,7 +104,7 @@ const app = await buildApp({
|
||||
jwtSecret: config.auth.jwtSecret
|
||||
},
|
||||
orderState: {
|
||||
repository: new OrderStateRepository(pool, marketingBenefits),
|
||||
repository: new OrderStateRepository(pool, marketingBenefits, cleaningTaskRepository),
|
||||
authRepository,
|
||||
accessControl,
|
||||
jwtSecret: config.auth.jwtSecret,
|
||||
@@ -187,7 +188,8 @@ const app = await buildApp({
|
||||
jwtSecret: config.auth.jwtSecret
|
||||
},
|
||||
cleaning: {
|
||||
repository: new CleaningTaskRepository(pool),
|
||||
repository: cleaningTaskRepository,
|
||||
mediaStorage: new MediaStorage(resolve(process.cwd(), 'shared', 'uploads')),
|
||||
authRepository,
|
||||
accessControl,
|
||||
jwtSecret: config.auth.jwtSecret
|
||||
|
||||
Reference in New Issue
Block a user