Skip to content

8. Schedulers, Automation, Energy News, Tenders & Event Notifications

Repository: Backend (planovi-backend) • Rule Prefix: BR-CRON • Documented Rules: 5 • Open [TEAM_WHY_NEEDED] Questions: 4

1. Business Purpose & Actors

Handles database-driven job dispatching (run-scheduler), Jarvis reminder/overdue alerts & Gmail dispatch (reminder-scheduler), Polish energy-market RSS aggregation (fetch-energy-news), AI-powered public tender matching (tender-cron), cooperative meeting invitations/updates/cancellations (send-event-invitation), and public one-click email opt-out (unsubscribe).

  • Actors: External cron / service_role (run-scheduler, reminder-scheduler, tender-cron), public Flutter news widget (fetch-energy-news), cooperative staff (send-event-invitation), and email recipients (unsubscribe).

2. All Features & End-to-End Flows

  1. Job Scheduler (run-scheduler/index.ts): validateAuth -> reads system_settings (setting_key/setting_value); exits if scheduler_enabled === false -> loads system_jobs (job_status = 'active') -> for each due job ((now - last_run_at)/1000 >= interval_seconds), logs job_execution_logs (running), loops up to 1 + retry_attempts POSTing to hardcoded http://host.docker.internal:54321/functions/v1/${job.function_name} with empty headers: {}, sleeping retry_backoff_seconds * 1000 ms inline between failures and inserting job_failures.
  2. Jarvis Reminder Scheduler (reminder-scheduler/index.ts): validateAuth -> 3 phases against reminders (status = 'pending'):
    • Pre-Reminders (pre_reminder_sent = false, pre_reminder_time <= now): inserts jarvis_history (type: 'reminder_alert') + sends Gmail (via Google OAuth user_google_tokens refreshed at < expires_at - 60s or RPC get_user_provider_token) to created_by AND assigned_to_user_id -> sets pre_reminder_sent = true.
    • Main Reminders (reminder_sent = false, scheduled_time ∈ [now - 30m, now]): inserts jarvis_history (type: 'reminder_alarm', play_alarm: true) + sends Gmail to creator & assignee -> sets status = 'completed', reminder_sent = true, is_notified = true.
    • Overdue Reminders (reminder_sent = false, scheduled_time < now - 30m): inserts jarvis_history (type: 'reminder_alarm', is_overdue: true) + sends Gmail to created_by ONLY -> sets status = 'overdue', reminder_sent = true.
  3. Energy News RSS Proxy (fetch-energy-news/index.ts): Public stateless endpoint (Cache-Control: public, max-age=900, always HTTP 200). Waterfall with 8000ms timeout & Chrome 120 User-Agent: wysokienapiecie.pl/feed/ -> cire.pl/rss.xml -> Google News PL RSS. Regex-parses up to MAX_ITEMS = 6, truncates to 300 chars, tags severity = 'warning' on 14 Polish keywords else 'info', returns static Polish fallback on failure.
  4. Tender Matching Cron (tender-cron/index.ts): validateAuth -> reads active tender_profiles -> evaluates against 2 hardcoded expired mock tenders (TND-2026-001, TND-2026-002) via gemini-2.5-flash (temperature: 0.1, JSON output) -> deduplicates tender_matches by (company_id, title) -> inserts with status = 'new'.
  5. Meeting Invitations (send-event-invitation/index.ts): requireUser + requireStaff(meeting.company_id, "OTHERS") -> loads event_meetings (404) + event_invitations -> supports mode ∈ {'invite','update','cancel','uninvite'} (uninvite requires user_ids; reset_responses resets response='pending' on update) -> downloads optional PDF from governance_documents (invite/update, non-fatal) -> inserts in-app notifications (notification_type: "general") -> emails via Resend (_shared/email.ts) skipping missing email & email_opt_out, sleeping 550ms per email (~1.8 req/s) -> updates event_invitations.email_status on invite mode only.
  6. Public Unsubscribe (unsubscribe/index.ts): Public GET ?token= -> looks up onboarding_tokens.token (ignores expires_at; 400 missing, 404 unknown) -> idempotently sets user_profiles.email_opt_out = true -> returns Polish dark-mode HTML confirmation page.

3. Hard Business Rules, Validations, Calculations & Edge Cases (BR-CRON)

  • BR-CRON-01 (Scheduler Kill Switch & Retry): system_settings.scheduler_enabled === false halts execution; due jobs run up to 1 + retry_attempts with inline retry_backoff_seconds sleep (run-scheduler/index.ts:50-67,173-407).
  • BR-CRON-02 (30-Minute Main vs Overdue Split & Recipient Scope): reminder-scheduler:295,407-564: scheduled_time >= now - 30m fires Main (status='completed', creator + assignee); < now - 30m fires Overdue (status='overdue', creator only). OAuth token refresh buffer = 60s.
  • BR-CRON-03 (News Limits & Severity Keywords): MAX_ITEMS = 6, 300-char excerpt, 8000ms fetch timeout, max-age=900 cache, 14 Polish WARNING_KEYWORDS -> 'warning', else 'info'.
  • BR-CRON-04 (Meeting Link Allowlist & Resend Pacing): send-event-invitation: panel_url strictly matches ^https:\/\/(dev-)?panel\.planovi\.app$ (fallback https://panel.planovi.app); 550ms inter-email sleep stays under Resend’s 2 req/s limit; email_opt_out suppresses email while preserving in-app notifications.
  • BR-CRON-05 (Token-Only Unsubscribe): unsubscribe resolves ONLY onboarding_tokens.token (ignoring expires_at) and sets user_profiles.email_opt_out = true.

4. State Machines & Data Lifecycle

  • job_execution_logs.execution_status: 'running' -> 'retrying' -> 'success' | 'failed' (final_failure: true).
  • reminders.status: 'pending' -> 'completed' (main fired) | 'overdue' (>30m late) | snoozed back to 'pending' via Jarvis.
  • event_invitations.email_status: 'queued' | 'failed' -> 'sent' | 'failed' | 'no_email' (also used for email_opt_out).

5. Technical Contract

  • Endpoints: run-scheduler, reminder-scheduler, fetch-energy-news, tender-cron, send-event-invitation, unsubscribe.
  • Tables: system_settings, system_jobs, job_execution_logs, job_failures, reminders, jarvis_history, user_google_tokens (+ RPC get_user_provider_token), tender_profiles, tender_matches, event_meetings, event_invitations, notifications, onboarding_tokens, user_profiles.
  • External APIs: Google OAuth + Gmail API (reminder-scheduler), WysokieNapiecie/CIRE/Google News RSS (fetch-energy-news), Gemini gemini-2.5-flash (tender-cron), Resend (send-event-invitation).

6. Cross-Repository Dependencies

Caller -> CalleeProtocol & AuthExact Endpoint / Contract
reminder-scheduler -> planovi-flutter-app (via jarvis_history)DB table contractEmits `action_widget.type: ‘reminder_alert’
planovi-flutter-app -> fetch-energy-news & send-event-invitationHTTPS GET/POST / Public & User JWTNews widget JSON; Meeting invite/update/cancel/uninvite
grant-portal-access, send-rejection-notice, send-account-updated-notice -> unsubscribePublic GET linkBROKEN: those 3 pass ?token=<user_profile_id> which 404s on unsubscribe

7. Why It Works This Way

  • reminder-scheduler emits 'reminder_alarm' + is_overdue: true: Comment (lines 529-532) notes Flutter’s _buildActionWidget lacks a 'reminder_overdue' case.
  • send-event-invitation 550ms sleep: Stays under Resend’s 2 req/s default rate limit (line 370).
  • [TEAM_WHY_NEEDED: Is run-scheduler superseded by pg_cron? It hardcodes http://host.docker.internal:54321, sends empty headers, and conflicts with system_settings schema used by ai-energy-balancer/generate-monthly-invoices.]
  • [TEAM_WHY_NEEDED: Where are cron schedules for reminder-scheduler and tender-cron configured? No migration or workflow defines them.]
  • [TEAM_WHY_NEEDED: Is tender-cron an abandoned prototype? Its mock tenders expired in May–June 2026.]
  • [TEAM_WHY_NEEDED: Why does send-event-invitation gate on RBAC team_declarations|OTHERS instead of a governance/calendar module, and omit an unsubscribe footer link?]

8. Debugging, Logs & Common Failure Modes

Symptom / Error MessageRoot Cause in CodeHow to Verify / Exact Query or LogFix
run-scheduler fails every job in cloud/staging with DNS error or 401Hardcoded http://host.docker.internal:54321/functions/v1/... with headers: {} (run-scheduler:188-195); no job lock; requires both SUPABASE_* & ENERGY_SUPABASE_*Check job_failures tableReplace with pg_cron or read SUPABASE_URL + pass x-cron-secret
Any authenticated user can trigger global crons & burn GEMINI_API_KEYrun-scheduler, reminder-scheduler, tender-cron call validateAuth(req) with default allowUser: trueCall with standard user JWTPass { allowServiceRole: true, allowCronSecret: true, allowUser: false }
reminder-scheduler refreshes Google OAuth on every run & corrupts emojis/HTMLreminder-scheduler:64-67 never updates expires_at; double-encoded mojibake (⠰, 🔔); unescaped HTML & raw Subject: MIME headerInspect user_google_tokens.expires_at & sent Gmail sourcePersist expires_at, fix UTF-8, escape HTML & RFC 2047 encode Subject
fetch-energy-news returns fallback even when CIRE / Google News are healthyfetch-energy-news:178-225 only falls back on thrown errors; HTTP 200 WAF HTML or 0 parsed items short-circuits straight to fallbackCall fetch-energy-news when primary returns Cloudflare HTMLContinue waterfall loop on WAF HTML or 0 items
tender-cron crashes or duplicates matches foreverprofile.industry_keywords.join crashes if null; unguarded JSON.parse; .single() on dedup returns null if >1 row existsInspect tender_matches duplicatesNull-guard inputs, use .limit(1).maybeSingle(), replace mock tenders
Large meetings (>120 invitees) time out in send-event-invitationSequential 550ms sleep + per-user DB queries exceed worker budget; no_email response double-counts opted_out (line 382)Check event_invitations stuck in 'queued'Batch DB writes / use Resend batch API; fix no_email counter