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
- Job Scheduler (
run-scheduler/index.ts):validateAuth-> readssystem_settings(setting_key/setting_value); exits ifscheduler_enabled === false-> loadssystem_jobs(job_status = 'active') -> for each due job ((now - last_run_at)/1000 >= interval_seconds), logsjob_execution_logs(running), loops up to1 + retry_attemptsPOSTing to hardcodedhttp://host.docker.internal:54321/functions/v1/${job.function_name}with emptyheaders: {}, sleepingretry_backoff_seconds * 1000ms inline between failures and insertingjob_failures. - Jarvis Reminder Scheduler (
reminder-scheduler/index.ts):validateAuth-> 3 phases againstreminders(status = 'pending'):- Pre-Reminders (
pre_reminder_sent = false,pre_reminder_time <= now): insertsjarvis_history(type: 'reminder_alert') + sends Gmail (via Google OAuthuser_google_tokensrefreshed at< expires_at - 60sor RPCget_user_provider_token) tocreated_byANDassigned_to_user_id-> setspre_reminder_sent = true. - Main Reminders (
reminder_sent = false,scheduled_time ∈ [now - 30m, now]): insertsjarvis_history(type: 'reminder_alarm',play_alarm: true) + sends Gmail to creator & assignee -> setsstatus = 'completed',reminder_sent = true,is_notified = true. - Overdue Reminders (
reminder_sent = false,scheduled_time < now - 30m): insertsjarvis_history(type: 'reminder_alarm',is_overdue: true) + sends Gmail tocreated_byONLY -> setsstatus = 'overdue',reminder_sent = true.
- Pre-Reminders (
- Energy News RSS Proxy (
fetch-energy-news/index.ts): Public stateless endpoint (Cache-Control: public, max-age=900, always HTTP200). Waterfall with8000mstimeout & Chrome 120User-Agent:wysokienapiecie.pl/feed/->cire.pl/rss.xml-> Google News PL RSS. Regex-parses up toMAX_ITEMS = 6, truncates to300chars, tagsseverity = 'warning'on 14 Polish keywords else'info', returns static Polish fallback on failure. - Tender Matching Cron (
tender-cron/index.ts):validateAuth-> reads activetender_profiles-> evaluates against 2 hardcoded expired mock tenders (TND-2026-001,TND-2026-002) viagemini-2.5-flash(temperature: 0.1, JSON output) -> deduplicatestender_matchesby(company_id, title)-> inserts withstatus = 'new'. - Meeting Invitations (
send-event-invitation/index.ts):requireUser+requireStaff(meeting.company_id, "OTHERS")-> loadsevent_meetings(404) +event_invitations-> supportsmode ∈ {'invite','update','cancel','uninvite'}(uninviterequiresuser_ids;reset_responsesresetsresponse='pending'onupdate) -> downloads optional PDF fromgovernance_documents(invite/update, non-fatal) -> inserts in-appnotifications(notification_type: "general") -> emails via Resend (_shared/email.ts) skipping missing email &email_opt_out, sleeping550msper email (~1.8 req/s) -> updatesevent_invitations.email_statusoninvitemode only. - Public Unsubscribe (
unsubscribe/index.ts): PublicGET ?token=-> looks uponboarding_tokens.token(ignoresexpires_at;400missing,404unknown) -> idempotently setsuser_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 === falsehalts execution; due jobs run up to1 + retry_attemptswith inlineretry_backoff_secondssleep (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 - 30mfires Main (status='completed', creator + assignee);< now - 30mfires Overdue (status='overdue', creator only). OAuth token refresh buffer =60s.BR-CRON-03(News Limits & Severity Keywords):MAX_ITEMS = 6,300-char excerpt,8000msfetch timeout,max-age=900cache, 14 PolishWARNING_KEYWORDS->'warning', else'info'.BR-CRON-04(Meeting Link Allowlist & Resend Pacing):send-event-invitation:panel_urlstrictly matches^https:\/\/(dev-)?panel\.planovi\.app$(fallbackhttps://panel.planovi.app);550msinter-email sleep stays under Resend’s 2 req/s limit;email_opt_outsuppresses email while preserving in-appnotifications.BR-CRON-05(Token-Only Unsubscribe):unsubscriberesolves ONLYonboarding_tokens.token(ignoringexpires_at) and setsuser_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 foremail_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(+ RPCget_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), Geminigemini-2.5-flash(tender-cron), Resend (send-event-invitation).
6. Cross-Repository Dependencies
| Caller -> Callee | Protocol & Auth | Exact Endpoint / Contract |
|---|---|---|
reminder-scheduler -> planovi-flutter-app (via jarvis_history) | DB table contract | Emits `action_widget.type: ‘reminder_alert’ |
planovi-flutter-app -> fetch-energy-news & send-event-invitation | HTTPS GET/POST / Public & User JWT | News widget JSON; Meeting invite/update/cancel/uninvite |
grant-portal-access, send-rejection-notice, send-account-updated-notice -> unsubscribe | Public GET link | BROKEN: those 3 pass ?token=<user_profile_id> which 404s on unsubscribe |
7. Why It Works This Way
reminder-scheduleremits'reminder_alarm'+is_overdue: true: Comment (lines 529-532) notes Flutter’s_buildActionWidgetlacks a'reminder_overdue'case.send-event-invitation550ms 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 Message | Root Cause in Code | How to Verify / Exact Query or Log | Fix |
|---|---|---|---|
run-scheduler fails every job in cloud/staging with DNS error or 401 | Hardcoded http://host.docker.internal:54321/functions/v1/... with headers: {} (run-scheduler:188-195); no job lock; requires both SUPABASE_* & ENERGY_SUPABASE_* | Check job_failures table | Replace with pg_cron or read SUPABASE_URL + pass x-cron-secret |
Any authenticated user can trigger global crons & burn GEMINI_API_KEY | run-scheduler, reminder-scheduler, tender-cron call validateAuth(req) with default allowUser: true | Call with standard user JWT | Pass { allowServiceRole: true, allowCronSecret: true, allowUser: false } |
reminder-scheduler refreshes Google OAuth on every run & corrupts emojis/HTML | reminder-scheduler:64-67 never updates expires_at; double-encoded mojibake (⠰, 🔔); unescaped HTML & raw Subject: MIME header | Inspect user_google_tokens.expires_at & sent Gmail source | Persist expires_at, fix UTF-8, escape HTML & RFC 2047 encode Subject |
fetch-energy-news returns fallback even when CIRE / Google News are healthy | fetch-energy-news:178-225 only falls back on thrown errors; HTTP 200 WAF HTML or 0 parsed items short-circuits straight to fallback | Call fetch-energy-news when primary returns Cloudflare HTML | Continue waterfall loop on WAF HTML or 0 items |
tender-cron crashes or duplicates matches forever | profile.industry_keywords.join crashes if null; unguarded JSON.parse; .single() on dedup returns null if >1 row exists | Inspect tender_matches duplicates | Null-guard inputs, use .limit(1).maybeSingle(), replace mock tenders |
Large meetings (>120 invitees) time out in send-event-invitation | Sequential 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 |