feat(M08-B): 接入保洁任务端基础流程
This commit is contained in:
@@ -50,6 +50,7 @@ import {
|
||||
} from './routes/device-control.js';
|
||||
import { registerMemberRoutes, type MemberRouteOptions } from './routes/members.js';
|
||||
import { registerRechargeRoutes, type RechargeRouteOptions } from './routes/recharge.js';
|
||||
import { registerCleaningRoutes, type CleaningRouteOptions } from './routes/cleaning.js';
|
||||
|
||||
export interface BuildAppOptions {
|
||||
config?: AppConfig;
|
||||
@@ -72,6 +73,7 @@ export interface BuildAppOptions {
|
||||
deviceControl?: DeviceControlRouteOptions;
|
||||
members?: MemberRouteOptions;
|
||||
recharge?: RechargeRouteOptions;
|
||||
cleaning?: CleaningRouteOptions;
|
||||
}
|
||||
|
||||
declare module 'fastify' {
|
||||
@@ -170,6 +172,9 @@ export async function buildApp(options: BuildAppOptions = {}): Promise<FastifyIn
|
||||
if (options.recharge) {
|
||||
await registerRechargeRoutes(app, options.recharge);
|
||||
}
|
||||
if (options.cleaning) {
|
||||
await registerCleaningRoutes(app, options.cleaning);
|
||||
}
|
||||
|
||||
return app;
|
||||
}
|
||||
|
||||
@@ -36,13 +36,20 @@ export class RbacRepository {
|
||||
SELECT ?, r.id, p.id FROM qipai_roles r
|
||||
INNER JOIN qipai_permissions p ON
|
||||
(r.code = 'CUSTOMER' AND p.code IN ('profile.read', 'order.self.read'))
|
||||
OR (r.code = 'CLEANER'
|
||||
AND p.code IN ('profile.read', 'cleaning.task.read',
|
||||
'cleaning.task.write', 'cleaning.statistics.read'))
|
||||
OR (r.code = 'STORE_ADMIN'
|
||||
AND p.code IN ('user.read', 'staff.manage', 'session.reset',
|
||||
'store.operation.read', 'store.operation.write',
|
||||
'device.read', 'device.write'))
|
||||
'device.read', 'device.write',
|
||||
'cleaning.task.read', 'cleaning.task.write',
|
||||
'cleaning.statistics.read'))
|
||||
OR (r.code IN ('TENANT_ADMIN', 'PLATFORM_ADMIN')
|
||||
AND p.code IN ('user.read', 'staff.manage', 'session.reset', 'tenant.manage',
|
||||
'device.read', 'device.write'))
|
||||
'device.read', 'device.write',
|
||||
'cleaning.task.read', 'cleaning.task.write',
|
||||
'cleaning.statistics.read'))
|
||||
WHERE r.tenant_id = ?`,
|
||||
[tenantId, tenantId]
|
||||
);
|
||||
|
||||
@@ -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 [];
|
||||
}
|
||||
}
|
||||
@@ -44,7 +44,8 @@ const migrationFiles: Record<MigrationDirection, readonly string[]> = {
|
||||
'database/migrations/2026062421_m07a_wallet_ledger.up.sql',
|
||||
'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/2026062524_m08a_recharge_wechat.up.sql',
|
||||
'database/migrations/2026062525_m08b_cleaner_tasks.up.sql'
|
||||
],
|
||||
verify: [
|
||||
'database/migrations/2026061601_m01b_core_schema.verify.sql',
|
||||
@@ -70,9 +71,11 @@ const migrationFiles: Record<MigrationDirection, readonly string[]> = {
|
||||
'database/migrations/2026062421_m07a_wallet_ledger.verify.sql',
|
||||
'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/2026062524_m08a_recharge_wechat.verify.sql',
|
||||
'database/migrations/2026062525_m08b_cleaner_tasks.verify.sql'
|
||||
],
|
||||
down: [
|
||||
'database/migrations/2026062525_m08b_cleaner_tasks.down.sql',
|
||||
'database/migrations/2026062524_m08a_recharge_wechat.down.sql',
|
||||
'database/migrations/2026062423_m07c_benefits.down.sql',
|
||||
'database/migrations/2026062422_m07b_recharge_plans.down.sql',
|
||||
@@ -235,7 +238,8 @@ export async function executeMigrationPlan(
|
||||
3, 3, 9, 1,
|
||||
1, 1, 1, 4, 7, 1,
|
||||
1, 1, 7, 7, 1,
|
||||
5, 10, 7, 3, 1
|
||||
5, 10, 7, 3, 1,
|
||||
2, 8, 4, 3, 1
|
||||
][index] ?? 1;
|
||||
if (!Array.isArray(result) || result.length < minimumRows) {
|
||||
throw new Error(
|
||||
|
||||
@@ -0,0 +1,169 @@
|
||||
import type { FastifyInstance, FastifyReply, FastifyRequest } 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 {
|
||||
CleaningTaskError,
|
||||
cleaningTaskStatuses,
|
||||
type CleaningActor,
|
||||
type CleaningTaskRepository
|
||||
} from '../cleaning/cleaning-task-repository.js';
|
||||
|
||||
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(cleaningTaskStatuses).optional()
|
||||
});
|
||||
const paramsSchema = z.object({ taskId: z.string().regex(/^[1-9]\d{0,19}$/) });
|
||||
const submitSchema = z.object({
|
||||
photoUrls: z.array(z.string().url()).max(9).default([]),
|
||||
note: z.string().trim().max(512).optional()
|
||||
});
|
||||
|
||||
export interface CleaningRouteOptions {
|
||||
repository: Pick<CleaningTaskRepository, 'listHall' | 'listMine' | 'claim' | 'start' | 'submit' | 'stats'>;
|
||||
authRepository: Pick<AuthRepository, 'validateSession'>;
|
||||
accessControl: { getAccessProfile(tenantId: string, userId: string): Promise<AccessProfile> };
|
||||
jwtSecret: string;
|
||||
}
|
||||
|
||||
export async function registerCleaningRoutes(
|
||||
app: FastifyInstance,
|
||||
options: CleaningRouteOptions
|
||||
): Promise<void> {
|
||||
app.get('/app-api/cleaning/tasks/hall', async (request, reply) => {
|
||||
const actor = await requireActor(request, reply, options, 'read');
|
||||
if (!actor) return;
|
||||
const query = listSchema.safeParse(request.query);
|
||||
if (!query.success) return invalid(reply, request.traceId);
|
||||
return handle(reply, request.traceId, async () => ({
|
||||
code: 0,
|
||||
data: await options.repository.listHall({ ...actor, ...query.data }),
|
||||
traceId: request.traceId
|
||||
}));
|
||||
});
|
||||
|
||||
app.get('/app-api/cleaning/tasks/mine', async (request, reply) => {
|
||||
const actor = await requireActor(request, reply, options, 'read');
|
||||
if (!actor) return;
|
||||
const query = listSchema.safeParse(request.query);
|
||||
if (!query.success) return invalid(reply, request.traceId);
|
||||
return handle(reply, request.traceId, async () => ({
|
||||
code: 0,
|
||||
data: await options.repository.listMine({ ...actor, ...query.data }),
|
||||
traceId: request.traceId
|
||||
}));
|
||||
});
|
||||
|
||||
app.get('/app-api/cleaning/stats', async (request, reply) => {
|
||||
const actor = await requireActor(request, reply, options, 'read');
|
||||
if (!actor) return;
|
||||
return handle(reply, request.traceId, async () => ({
|
||||
code: 0,
|
||||
data: await options.repository.stats(actor),
|
||||
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;
|
||||
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.claim({ ...actor, taskId: params.data.taskId }),
|
||||
traceId: request.traceId
|
||||
}));
|
||||
});
|
||||
|
||||
app.post('/app-api/cleaning/tasks/:taskId/start', 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.start({ ...actor, taskId: params.data.taskId }),
|
||||
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;
|
||||
const params = paramsSchema.safeParse(request.params);
|
||||
const body = submitSchema.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.submit({
|
||||
...actor,
|
||||
taskId: params.data.taskId,
|
||||
photoUrls: body.data.photoUrls,
|
||||
note: body.data.note
|
||||
}),
|
||||
traceId: request.traceId
|
||||
}));
|
||||
});
|
||||
}
|
||||
|
||||
async function requireActor(
|
||||
request: FastifyRequest,
|
||||
reply: FastifyReply,
|
||||
options: CleaningRouteOptions,
|
||||
mode: 'read' | 'write'
|
||||
): Promise<CleaningActor | null> {
|
||||
const auth = await authenticateAccessToken(
|
||||
request.headers.authorization,
|
||||
options.authRepository,
|
||||
options.jwtSecret
|
||||
);
|
||||
if (!auth) {
|
||||
reply.status(401).send({
|
||||
code: 'AUTH_SESSION_INVALID', message: 'Authentication required.', traceId: request.traceId
|
||||
});
|
||||
return null;
|
||||
}
|
||||
const access = await options.accessControl.getAccessProfile(auth.session.tenantId, auth.session.user.id);
|
||||
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')) {
|
||||
reply.status(403).send({
|
||||
code: 'CLEANING_TASK_FORBIDDEN',
|
||||
message: 'Cleaning task permission is required.',
|
||||
traceId: request.traceId
|
||||
});
|
||||
return null;
|
||||
}
|
||||
return {
|
||||
tenantId: auth.session.tenantId,
|
||||
userId: auth.session.user.id,
|
||||
access,
|
||||
traceId: request.traceId
|
||||
};
|
||||
}
|
||||
|
||||
async function handle(reply: FastifyReply, traceId: string, work: () => Promise<unknown>) {
|
||||
try {
|
||||
return await work();
|
||||
} catch (error) {
|
||||
if (!(error instanceof CleaningTaskError)) throw error;
|
||||
const statusCode = error.code === 'CLEANING_TASK_FORBIDDEN' ? 403 : 409;
|
||||
return reply.status(statusCode).send({
|
||||
code: error.code,
|
||||
message: 'The cleaning task request cannot be completed.',
|
||||
traceId
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
function invalid(reply: FastifyReply, traceId: string) {
|
||||
return reply.status(400).send({
|
||||
code: 'INVALID_CLEANING_TASK_REQUEST',
|
||||
message: 'The cleaning task request is invalid.',
|
||||
traceId
|
||||
});
|
||||
}
|
||||
@@ -37,6 +37,7 @@ import { MemberProfileService } from './wallets/member-profile-service.js';
|
||||
import { RechargeService } from './wallets/recharge-service.js';
|
||||
import { WalletLedgerService } from './wallets/wallet-ledger-service.js';
|
||||
import { MarketingBenefitService } from './wallets/marketing-benefit-service.js';
|
||||
import { CleaningTaskRepository } from './cleaning/cleaning-task-repository.js';
|
||||
|
||||
const config = loadConfig();
|
||||
const pool = createMySqlPool(config);
|
||||
@@ -184,6 +185,12 @@ const app = await buildApp({
|
||||
authRepository,
|
||||
accessControl,
|
||||
jwtSecret: config.auth.jwtSecret
|
||||
},
|
||||
cleaning: {
|
||||
repository: new CleaningTaskRepository(pool),
|
||||
authRepository,
|
||||
accessControl,
|
||||
jwtSecret: config.auth.jwtSecret
|
||||
}
|
||||
});
|
||||
app.addHook('onClose', async () => {
|
||||
|
||||
Reference in New Issue
Block a user