|
| 1 | +import process from 'node:process' |
| 2 | +import { repository } from '@roll-stack/database' |
| 3 | +import { format } from 'date-fns' |
| 4 | +import { ru } from 'date-fns/locale/ru' |
| 5 | +import OpenAI from 'openai' |
| 6 | + |
| 7 | +const logger = useLogger('task:ai:weekly-report') |
| 8 | + |
| 9 | +export default defineTask({ |
| 10 | + meta: { |
| 11 | + name: 'ai:weekly-report', |
| 12 | + description: 'Prepare and post weekly report', |
| 13 | + }, |
| 14 | + async run() { |
| 15 | + if (process.env.NODE_ENV !== 'production') { |
| 16 | + logger.info('Skipping task in non-production environment') |
| 17 | + return { result: true } |
| 18 | + } |
| 19 | + |
| 20 | + try { |
| 21 | + const { ai } = useRuntimeConfig() |
| 22 | + |
| 23 | + const tasks = await repository.task.listCompletedThisWeek() |
| 24 | + const staff = await repository.user.findStaff() |
| 25 | + |
| 26 | + function preparePerformer(performerId: string | null) { |
| 27 | + const user = staff.find((user) => user.id === performerId) |
| 28 | + if (!user) { |
| 29 | + return null |
| 30 | + } |
| 31 | + |
| 32 | + return { |
| 33 | + name: user?.name, |
| 34 | + surname: user?.surname, |
| 35 | + caption: user?.caption, |
| 36 | + completedTasksCount: tasks.filter((task) => task.performerId === user?.id).length, |
| 37 | + } |
| 38 | + } |
| 39 | + |
| 40 | + const preparedTasks = tasks.map((task) => { |
| 41 | + const performer = preparePerformer(task.performerId) |
| 42 | + |
| 43 | + return { |
| 44 | + completedAt: task.completedAt, |
| 45 | + name: task.name, |
| 46 | + description: task.description, |
| 47 | + report: task.report, |
| 48 | + performer, |
| 49 | + } |
| 50 | + }) |
| 51 | + |
| 52 | + const client = new OpenAI({ |
| 53 | + apiKey: ai.apiKey, |
| 54 | + baseURL: ai.baseUrl, |
| 55 | + timeout: 120000, |
| 56 | + maxRetries: 2, |
| 57 | + }) |
| 58 | + |
| 59 | + const response = await client.chat.completions.create({ |
| 60 | + model: ai.modelPro, |
| 61 | + messages: [ |
| 62 | + { |
| 63 | + role: 'system', |
| 64 | + content: ai.weeklyReportPrompt, |
| 65 | + }, |
| 66 | + { |
| 67 | + role: 'user', |
| 68 | + content: JSON.stringify(preparedTasks), |
| 69 | + }, |
| 70 | + ], |
| 71 | + }) |
| 72 | + |
| 73 | + const finalMessage = response.choices[0].message.content |
| 74 | + if (!finalMessage) { |
| 75 | + return { result: true } |
| 76 | + } |
| 77 | + |
| 78 | + // Flow item |
| 79 | + const week = format(new Date(), 'w', { locale: ru }) |
| 80 | + await repository.flow.createItem({ |
| 81 | + type: 'weekly_task_report', |
| 82 | + title: `Задачи за неделю ${week}`, |
| 83 | + description: finalMessage, |
| 84 | + }) |
| 85 | + } catch (error) { |
| 86 | + errorResolver(error) |
| 87 | + } |
| 88 | + |
| 89 | + return { result: true } |
| 90 | + }, |
| 91 | +}) |
0 commit comments