import type { VariablesContext } from "../middlewares.ts"; export class ReminderService { private c: VariablesContext; constructor(context: VariablesContext) { this.c = context; } /** * 检查即将超时的工单并发送提醒 * @param hoursBefore 超前多少小时提醒 */ async checkUpcomingDeadlines(hoursBefore = 2): Promise { const apiClient = this.c.get('apiClient'); const now = new Date(); const deadlineThreshold = new Date(now.getTime() + hoursBefore * 60 * 60 * 1000); // 获取即将超时的工单 // 获取6小时内已提醒的工单ID const remindedOrders = await apiClient.database.table('work_order_reminders') .where('reminded_at', '>=', new Date(now.getTime() - 6 * 60 * 60 * 1000).toISOString()) .select('work_order_id'); const orders = await apiClient.database.table('work_orders') .where('status', 'in_progress') .where('deadline', '<=', deadlineThreshold.toISOString()) .where('deadline', '>', now.toISOString()) .whereNot('id', 'in', remindedOrders.map(o => o.work_order_id)) .select(); for (const order of orders) { // 发送提醒 await this.sendReminder(order); // 记录提醒日志 await apiClient.database.table('work_order_reminders').insert({ work_order_id: order.id, reminded_at: now, deadline: order.deadline, recipient_id: order.assignee_id, created_at: now }); } } /** * 发送超时提醒通知 * @param order 工单信息 */ private async sendReminder(order: any): Promise { const apiClient = this.c.get('apiClient'); // 这里实现实际的通知逻辑,例如: // 1. 发送站内消息 await apiClient.database.table('messages').insert({ user_id: order.assignee_id, title: `工单即将超时: #${order.id}`, content: `您的工单 #${order.id} 将在2小时内超时,请及时处理`, created_at: apiClient.database.fn.now() }); // 2. 记录系统日志 await apiClient.database.table('system_logs').insert({ action: 'work_order_reminder', target_id: order.id, user_id: 0, // system details: JSON.stringify({ order_id: order.id, assignee_id: order.assignee_id, deadline: order.deadline }), created_at: apiClient.database.fn.now() }); } /** * 检查已超时工单 */ async checkTimeoutOrders(): Promise { const apiClient = this.c.get('apiClient'); const now = new Date(); const orders = await apiClient.database.table('work_orders') .where('status', 'in_progress') .where('deadline', '<', now.toISOString()) .select(); for (const order of orders) { // 记录超时日志 await apiClient.database.table('work_order_timeout_logs').insert({ work_order_id: order.id, timeout_at: now, created_at: now }); // 更新超时计数 await apiClient.database.table('work_orders') .where('id', order.id) .update({ timeout_count: apiClient.database.raw('timeout_count + 1'), updated_at: now }); } } }