Skip to content

feat: daily report by ai - #87

Merged
hmbanan666 merged 1 commit into
mainfrom
daily-report
Aug 21, 2025
Merged

feat: daily report by ai#87
hmbanan666 merged 1 commit into
mainfrom
daily-report

Conversation

@hmbanan666

@hmbanan666 hmbanan666 commented Aug 21, 2025

Copy link
Copy Markdown
Collaborator

Summary by CodeRabbit

  • New Features
    • Automated weekday 17:00 AI-generated daily report summarizing completed tasks, posted to the team’s Telegram group. Messages are multi-paragraph, emoji-enhanced, and written in Russian.
  • Chores
    • Added environment variables to configure the AI model and the target Telegram group ID.

@hmbanan666 hmbanan666 self-assigned this Aug 21, 2025
@coderabbitai

coderabbitai Bot commented Aug 21, 2025

Copy link
Copy Markdown

Walkthrough

Adds env/config keys for AI and Telegram, introduces a scheduled Nitro task (Mon–Fri 17:00) that compiles completed tasks, generates a daily report via OpenAI using a Pro model, and posts it to a Telegram team group. Adds a repository method to list recently completed tasks.

Changes

Cohort / File(s) Summary of Changes
Env and runtime config
apps/web-app/.env.example, apps/web-app/nuxt.config.ts
Added NUXT_AI_MODEL_PRO and NUXT_TELEGRAM_TEAM_GROUP_ID env examples; wired ai.modelPro and telegram.teamGroupId in runtime config; added a Nitro schedule '0 17 * * 1-5' -> ai:daily-report.
Scheduled AI report task
apps/web-app/server/tasks/ai/daily-report.ts
New task ai:daily-report: fetches today’s completed tasks, calls OpenAI chat completions with model from config, constructs a Russian daily summary, and conditionally sends it to a Telegram group via Atrium bot; returns { result: true } with error handling.
Database repository
packages/database/src/repository/task.ts
Added Task.listCompletedToday(): queries tasks completed within the last 12 hours, ordered by updatedAt desc.

Sequence Diagram(s)

sequenceDiagram
    autonumber
    actor Cron as Nitro Scheduler (Mon–Fri 17:00)
    participant Task as ai:daily-report Task
    participant Repo as Task Repository
    participant AI as OpenAI API
    participant TG as Telegram Bot API

    Cron->>Task: Trigger run()
    Task->>Repo: listCompletedToday()
    Repo-->>Task: Completed tasks (name, desc, timestamps)
    Task->>AI: chat.completions (model=ai.modelPro, system+user msgs)
    AI-->>Task: finalMessage (summary text)
    alt finalMessage present
        Task->>TG: sendMessage(teamGroupId, finalMessage)
        TG-->>Task: OK
    else empty message
        Note right of Task: Skip sending
    end
    Task-->>Cron: { result: true }
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

Poem

A rabbit at five taps its tiny clock,
Gathers the tasks from the burrowed stock.
Whispers to clouds, the OpenAI sky,
Sprinkles emojis, lets reports fly.
To Telegram warrens the updates hop—
Another day’s dig, tick-tock, non-stop. 🐇✨

Tip

🔌 Remote MCP (Model Context Protocol) integration is now available!

Pro plan users can now connect to remote MCP servers from the Integrations page. Connect with popular remote MCPs such as Notion and Linear to add more context to your reviews and chats.

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch daily-report

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

CodeRabbit Commands (Invoked using PR/Issue comments)

Type @coderabbitai help to get the list of available commands.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Status, Documentation and Community

  • Visit our Status Page to check the current availability of CodeRabbit.
  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@sonarqubecloud

Copy link
Copy Markdown

@hmbanan666
hmbanan666 merged commit 75e24b9 into main Aug 21, 2025
7 of 8 checks passed
@hmbanan666
hmbanan666 deleted the daily-report branch August 21, 2025 15:30

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🧹 Nitpick comments (14)
apps/web-app/.env.example (2)

21-21: Add sample value and brief guidance for NUXT_AI_MODEL_PRO.

Looks good. Consider adding a short comment/example (e.g., "gpt-4o-mini" or your hosted model name) to reduce misconfiguration during deploys.

Apply this diff to add a hint:

 NUXT_AI_MODEL=
-NUXT_AI_MODEL_PRO=
+NUXT_AI_MODEL_PRO=
+# e.g. gpt-4o, gpt-4o-mini, or your vendor-specific Pro model

25-29: Reorder Telegram keys to satisfy dotenv-linter and keep grouping logical.

dotenv-linter warns about key order. Reordering is harmless and keeps the section tidy.

 # Telegram
 NUXT_TELEGRAM_ADMIN_ID=
-NUXT_TELEGRAM_WASABI_BOT_ID=
 NUXT_TELEGRAM_ATRIUM_BOT_ID=
+NUXT_TELEGRAM_WASABI_BOT_ID=
 NUXT_TELEGRAM_TEAM_GROUP_ID=

Optional: add a hint that TEAM_GROUP_ID should be a numeric chat id (often negative for supergroups) or a channel username.

-NUXT_TELEGRAM_TEAM_GROUP_ID=
+NUXT_TELEGRAM_TEAM_GROUP_ID=
+# e.g. -1001234567890 or @your_channel
packages/database/src/repository/task.ts (3)

70-75: Method name vs. logic: “today” but using a rolling 12-hour window.

The method name suggests calendar-day semantics, but the query uses now() - 12 hours. That will miss work completed earlier in the morning if the job runs at 17:00. Either align the query to “today” (midnight to now, DB timezone) or rename/parameterize the method.

Option A — true “today” window (uses DB timezone):

   static async listCompletedToday() {
     return useDatabase().query.tasks.findMany({
-      where: (tasks, { gte }) => gte(tasks.completedAt, sql`now() - interval '12 hour'`),
-      orderBy: (tasks, { desc }) => desc(tasks.updatedAt),
+      where: (tasks, { gte }) => gte(tasks.completedAt, sql`date_trunc('day', now())`),
+      orderBy: (tasks, { desc }) => desc(tasks.completedAt),
     })
   }

Option B — keep rolling window but make it explicit and reusable:

-  static async listCompletedToday() {
-    return useDatabase().query.tasks.findMany({
-      where: (tasks, { gte }) => gte(tasks.completedAt, sql`now() - interval '12 hour'`),
-      orderBy: (tasks, { desc }) => desc(tasks.updatedAt),
-    })
-  }
+  static async listCompletedSince(hours = 12) {
+    return useDatabase().query.tasks.findMany({
+      where: (tasks, { gte }) => gte(tasks.completedAt, sql`now() - interval '${sql.raw(String(hours))} hour'`),
+      orderBy: (tasks, { desc }) => desc(tasks.completedAt),
+    })
+  }

Note: If production expects a specific local timezone (e.g., MSK), consider using date_trunc('day', timezone('…', now())) to avoid UTC drift.


70-75: Prefer ordering by completedAt and projecting only used columns.

The report uses completedAt, name, description, report. Ordering by updatedAt can reshuffle items after edits. Projecting only necessary columns reduces payload.

-    return useDatabase().query.tasks.findMany({
-      where: (tasks, { gte }) => gte(tasks.completedAt, sql`now() - interval '12 hour'`),
-      orderBy: (tasks, { desc }) => desc(tasks.updatedAt),
-    })
+    return useDatabase().query.tasks.findMany({
+      columns: {
+        completedAt: tasks.completedAt,
+        name: tasks.name,
+        description: tasks.description,
+        report: tasks.report,
+      },
+      where: (tasks, { gte }) => gte(tasks.completedAt, sql`now() - interval '12 hour'`),
+      orderBy: (tasks, { desc }) => desc(tasks.completedAt),
+    })

70-75: Indexing suggestion: add an index on tasks.completed_at for this query.

If the table grows, filtering by completed_at will benefit from an index. Consider a composite index if you routinely order by completed_at DESC.

Example migration (PostgreSQL):

CREATE INDEX IF NOT EXISTS idx_tasks_completed_at ON tasks (completed_at DESC);
apps/web-app/nuxt.config.ts (3)

15-21: ai.modelPro key: ensure presence and dev fallback.

If ai.modelPro is empty in some environments, consider falling back to ai.model to avoid task failures in non-prod.

You can enforce at task runtime:

-        model: ai.modelPro,
+        model: ai.modelPro || ai.model,

(See daily-report task comment for full snippet.)


22-27: telegram.teamGroupId: type/format check.

teamGroupId is often a negative int for supergroups or a @channel. Validate it at startup to avoid silent no-ops from Telegram API.

Optional runtime guard (e.g., in task):

  • If falsy, skip posting with a warning.
  • If numeric string, keep as string (Telegram accepts string), but ensure no stray spaces.

46-51: Cron timezone clarification and deploy parity.

Nitro scheduledTasks run according to the server/runtime timezone. Verify that "0 17 * * 1-5" corresponds to 17:00 in your target business timezone in production. If you deploy in UTC, this will run at 17:00 UTC.

Options:

  • Set TZ in the runtime environment to your business timezone.
  • Or run via per-env schedules, e.g., using env var substitution.
  • Or compute “today” relative to timezone (see repository comment) so 17:00 UTC still produces the correct local-day report.
apps/web-app/server/tasks/ai/daily-report.ts (6)

14-21: Short-circuit when there’s nothing to report.

Avoid a paid LLM call when no tasks qualify.

-      const preparedTasks = tasks.map((task) => ({
+      const preparedTasks = tasks.map((task) => ({
         completedAt: task.completedAt,
         name: task.name,
         description: task.description,
         report: task.report,
       }))
+
+      if (preparedTasks.length === 0) {
+        return { result: true }
+      }

22-26: Add basic client safety: validate config and set sane defaults.

Guard against missing ai.apiKey/baseUrl/model and consider a modest timeout/retry policy to avoid hanging tasks.

-      const client = new OpenAI({
-        apiKey: ai.apiKey,
-        baseURL: ai.baseUrl,
-      })
+      if (!ai.apiKey || !ai.modelPro) {
+        console.warn('[ai:daily-report] Missing AI configuration (apiKey/modelPro). Skipping.');
+        return { result: true }
+      }
+      const client = new OpenAI({
+        apiKey: ai.apiKey,
+        baseURL: ai.baseUrl,
+      })

Optional: use ai.modelPro || ai.model for dev fallback (see nuxt.config.ts comment).


27-39: Right-size the LLM call and cap cost; limit payload size.

Add max_tokens/temperature and cap the number/length of items to keep requests predictable. Telegram also has a 4096-char message limit; keeping output concise helps.

-      const response = await client.chat.completions.create({
+      const limitedTasks = preparedTasks.slice(0, 50) // hard cap; tune as needed
+      const response = await client.chat.completions.create({
         model: ai.modelPro,
         messages: [
           {
             role: 'system',
             content: 'Ты работаешь в компании "Суши Love", которая является сетью доставки суши. В 3-5 абзацах расскажи что сегодня было сделано, лучшие моменты. Отвечай на русском. Не бойся использовать emoji',
           },
           {
             role: 'user',
-            content: JSON.stringify(preparedTasks),
+            content: JSON.stringify(limitedTasks),
           },
         ],
+        temperature: 0.7,
+        max_tokens: 800,
       })

41-47: Harden response handling and respect Telegram’s 4096-character limit.

choices[0] can be undefined; Telegram messages longer than 4096 chars must be split.

-      const finalMessage = response.choices[0].message.content
-      if (!finalMessage) {
+      const finalMessage = response.choices?.[0]?.message?.content?.trim()
+      if (!finalMessage) {
         return { result: true }
       }
-
-      await useAtriumBot().api.sendMessage(telegram.teamGroupId, finalMessage)
+      const MAX_LEN = 4096
+      const chunks = finalMessage.match(new RegExp(`[\s\S]{1,${MAX_LEN}}`, 'g')) || []
+      const bot = useAtriumBot()
+      for (const chunk of chunks) {
+        await bot.api.sendMessage(telegram.teamGroupId, chunk)
+      }

14-21: Data minimization and potential PII leakage to LLM.

description/report may include sensitive details. Redact obvious secrets or restrict fields before sending to the vendor LLM; consider a self-hosted model for sensitive orgs.

Examples:

  • Drop fields known to contain credentials/URLs.
  • Add a simple redactor: mask 16+ digit numbers, tokens, and URLs before JSON.stringify.

5-9: Idempotency / duplicate posting safeguards.

If the task retries (transient errors) you may post duplicates. Consider adding a dedupe cache keyed by the report date or the hash of finalMessage.

Approach:

  • Compute hash of finalMessage; store in KV/cache for N hours; skip if seen.
  • Alternatively, include the calendar date in the prompt and only post once per day per environment.
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 854e4d4 and ed02f62.

📒 Files selected for processing (4)
  • apps/web-app/.env.example (1 hunks)
  • apps/web-app/nuxt.config.ts (3 hunks)
  • apps/web-app/server/tasks/ai/daily-report.ts (1 hunks)
  • packages/database/src/repository/task.ts (1 hunks)
🧰 Additional context used
🧬 Code graph analysis (2)
packages/database/src/repository/task.ts (1)
packages/database/src/tables.ts (1)
  • tasks (336-348)
apps/web-app/server/tasks/ai/daily-report.ts (2)
packages/database/src/tables.ts (1)
  • tasks (336-348)
apps/web-app/server/services/telegram/atrium-bot.ts (1)
  • useAtriumBot (95-101)
🪛 dotenv-linter (3.3.0)
apps/web-app/.env.example

[warning] 27-27: [UnorderedKey] The NUXT_TELEGRAM_ATRIUM_BOT_ID key should go before the NUXT_TELEGRAM_WASABI_BOT_ID key

(UnorderedKey)


[warning] 28-28: [UnorderedKey] The NUXT_TELEGRAM_TEAM_GROUP_ID key should go before the NUXT_TELEGRAM_WASABI_BOT_ID key

(UnorderedKey)

⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
  • GitHub Check: build

Comment on lines +5 to +53
export default defineTask({
meta: {
name: 'ai:daily-report',
description: 'Prepare and post daily report to Telegram group',
},
async run() {
try {
const { ai, telegram } = useRuntimeConfig()

const tasks = await repository.task.listCompletedToday()
const preparedTasks = tasks.map((task) => ({
completedAt: task.completedAt,
name: task.name,
description: task.description,
report: task.report,
}))

const client = new OpenAI({
apiKey: ai.apiKey,
baseURL: ai.baseUrl,
})

const response = await client.chat.completions.create({
model: ai.modelPro,
messages: [
{
role: 'system',
content: 'Ты работаешь в компании "Суши Love", которая является сетью доставки суши. В 3-5 абзацах расскажи что сегодня было сделано, лучшие моменты. Отвечай на русском. Не бойся использовать emoji',
},
{
role: 'user',
content: JSON.stringify(preparedTasks),
},
],
})

const finalMessage = response.choices[0].message.content
if (!finalMessage) {
return { result: true }
}

await useAtriumBot().api.sendMessage(telegram.teamGroupId, finalMessage)
} catch (error) {
errorResolver(error)
}

return { result: true }
},
})

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Verification agent

🧩 Analysis chain

Verification helper: locate errorResolver and confirm defineTask availability.

Run this to check if errorResolver exists and whether defineTask is globally provided elsewhere.


🏁 Script executed:

#!/bin/bash
# Find errorResolver definition(s)
rg -nP -C2 '\b(errorResolver)\b' --type ts --type tsx

# Check existing tasks for import patterns (to infer defineTask usage)
rg -nP -C2 'defineTask\(' apps --type ts --type tsx

# Ensure new config keys are referenced elsewhere
rg -nP -C2 '\bmodelPro\b|\bteamGroupId\b'

Length of output: 1438


🏁 Script executed:

#!/bin/bash
# Display the import section of the task file to check for defineTask and errorResolver imports
sed -n '1,30p' apps/web-app/server/tasks/ai/daily-report.ts

# Search across the repo for any import of defineTask or errorResolver
rg -nE "import.*(defineTask|errorResolver)" -C2 .

# Find where errorResolver is defined in the codebase
rg -n "function errorResolver" -C2 .

# Locate all occurrences of defineTask (to see how it's used/imported elsewhere)
rg -n "defineTask" -C2 .

Length of output: 4909


Missing import of errorResolver in daily-report task

The daily-report.ts task invokes errorResolver(error) in its catch block but never imports it, causing a reference error at compile/runtime.

• File: apps/web-app/server/tasks/ai/daily-report.ts
– Around line 46: errorResolver(error) is called without importing errorResolver.

• Since other tasks in this app use defineTask without import, you don’t need to import defineTask—it’s provided globally by the task runner plugin.

Please add at the top of the file:

import { errorResolver } from '~~/server/utils/error'
🤖 Prompt for AI Agents
In apps/web-app/server/tasks/ai/daily-report.ts around lines 5 to 53, the catch
block calls errorResolver(error) but errorResolver is not imported, causing a
reference error; fix by adding an import for errorResolver at the top of the
file (for example: import { errorResolver } from '~~/server/utils/error') so the
error handler is available when exceptions are caught.

Comment on lines +47 to +51
} catch (error) {
errorResolver(error)
}

return { result: true }

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Undefined symbol: errorResolver results in a runtime/compile error.

errorResolver is not imported or defined in this file. The task will fail at runtime.

Quick fix: log and return failure result to signal the scheduler.

-    } catch (error) {
-      errorResolver(error)
-    }
-
-    return { result: true }
+    } catch (error) {
+      console.error('[ai:daily-report]', error)
+      return { result: false }
+    }

If a shared errorResolver exists, import and use it instead:

import { errorResolver } from '~~/server/utils/error-resolver'
🤖 Prompt for AI Agents
In apps/web-app/server/tasks/ai/daily-report.ts around lines 47 to 51, the catch
block calls an undefined symbol errorResolver which causes a compile/runtime
error; fix by either importing the shared helper (add an import like the
suggested path at the top of the file if it exists) and call it, or if no shared
helper is available replace the call with logging the error (e.g.,
console.error/processLogger.error) and return a failure result ({ result: false
}) so the scheduler knows the task failed.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant