# Telegram Platform Architecture

Date: 2026-05-26

## Purpose

Telegram in ECOLE ECOIN is implemented as a platform layer for:

- secure user linking
- security alerts
- student notifications
- admin alerts
- interaction tracking
- future engagement and marketing expansion

It is not allowed to mutate finance or enrollment state directly from Telegram handlers.

## Module Ownership

Primary module path:

- `app/Domain/Telegram/`

Owns:

- telegram accounts
- link tokens
- bot linking flow
- webhook interaction tracking
- telegram notification queue
- telegram deep links

Does not own:

- finance workflows
- enrollment mutations
- attendance mutations

Those stay inside their owner modules and Telegram reacts through listeners and queued jobs.

## Core Data Model

Tables:

- `telegram_accounts`
- `telegram_link_tokens`
- `telegram_notifications`
- `telegram_interactions`

Compatibility:

- old `telegram_identities` remains supported
- successful linking synchronizes both `telegram_accounts` and `telegram_identities`
- existing messaging flows can keep working while the platform transitions to the new module

## Linking Flow

1. authenticated user opens `/account/telegram/link`
2. platform creates a short-lived single-use token
3. platform redirects to an in-app wait page owned by that token
4. the wait page opens `https://t.me/{bot_username}?start={token}` and polls token status
5. Telegram webhook receives either `/start` or `/start {token}`
6. if token is present, it is validated and consumed
7. telegram account is linked to the platform user
8. `is_verified` is set
9. interaction is logged
10. the wait page turns into success or expiry state without requiring a manual refresh

Security controls:

- token expiration
- single-use enforcement
- duplicate-account blocking
- webhook secret validation
- rate limiting on link generation

UX guardrails:

- `/start` without token no longer fails silently; the bot replies with instructions to return to the platform and restart linking
- successful linking sends an immediate bot confirmation, rather than depending only on queued delivery

## Security Model

Security alerts are raised through:

- `App\Domain\Telegram\Events\SecurityAlertRaised`

Current initial alert sources:

- login success
- failed login
- password reset

The auth listener logs the event first, then dispatches the Telegram security event after commit.

Telegram listeners:

- do not reset passwords
- do not expose secrets
- do not send credentials

Password recovery is now implemented as:

1. a public request endpoint receives an email address
2. if the user exists and has a verified Telegram account, the platform creates a broker reset token
3. the platform builds a short-lived signed reset URL
4. the URL is delivered through Telegram only
5. the reset form accepts a new password and completes reset through Laravel's password broker

This keeps passwords out of Telegram and preserves native `PasswordReset` lifecycle events.

## Notification Model

Notification queue table:

- `telegram_notifications`

Notification delivery job:

- `SendTelegramPlatformNotificationJob`

Properties:

- queued
- retryable
- idempotent via `idempotency_key` in payload
- template-driven via `message_templates`

## Student and Admin Notifications

Current initial wired events:

- `EnrollmentCreated`
- `EventRegistrationCreated`
- `PaymentConfirmed`
- `SecurityAlertRaised`

Current initial outputs:

- student enrollment created
- student payment approved
- student webinar registration confirmations
- student attendance reminders for scheduled sessions
- admin new enrollment alert
- admin webinar registration alerts to the configured Telegram admin chat
- user security alerts
- instructor attendance-required alerts for newly created attendance sessions
- webinar reminders and replay nudges

## Deep Links

Deep links use a signed redirect route:

- `telegram.deep-link.redirect`

The route:

- verifies the signature
- records a `deep_link` interaction
- redirects only to allowed application targets

Telegram callback interactions are also supported for safe, non-mutating help actions.
Current initial callback:

- webinar help callback -> record interaction -> respond with join-webinar, webinar list, and support links when registration context is available
- attendance help callback -> record interaction -> respond with attendance, schedule, and support links
- payment help callback -> record interaction -> respond with payment, upload-receipt, and support links when available

Marketing-ready hooks now also include:

- `campaign_key` inside Telegram notification payloads for key student journeys
- `campaign` propagation into signed Telegram deep links
- admin filtering/export by campaign tag
- top-campaign visibility in Telegram ops reporting

This prepares future funnels and recovery campaigns without introducing a full automation engine now.

Role-aware command shortcuts also support:

- richer student `/help` shortcuts for platform, payments, webinars, and forgot-password recovery
- student `/attendance` and `/webinars` shortcut bundles that stay consistent with reminder notifications and help callbacks
- `/reset` to trigger the existing signed Telegram password-reset flow without exposing any password in chat
- instructor `/help` with dashboard, schedule, and forgot-password shortcuts

Webinar join links also support `meeting_provider = custom` when a concrete `meeting_join_url` exists. This keeps Telegram webinar shortcuts usable for operational webinar setups that are not keyed as Zoom or Google Meet.

## Templates

Telegram templates are seeded through `MessageTemplatesSeeder`.

Current initial keys:

- `telegram_link_success`
- `telegram_help`
- `telegram_schedule_shortcut`
- `telegram_payments_shortcut`
- `telegram_attendance_shortcut`
- `telegram_webinars_shortcut`
- `telegram_notifications_shortcut`
- `telegram_enrollment_created`
- `telegram_payment_approved`
- `telegram_login_alert`
- `telegram_admin_new_enrollment`
- `telegram_password_reset`
- `telegram_instructor_attendance_required`
- `telegram_student_attendance_reminder`
- `telegram_webinar_registered`
- `telegram_admin_webinar_registration_alert`
- `telegram_webinar_reminder`
- `telegram_webinar_replay`

Locales:

- `ar`
- `fr`

## Admin Operations

Telegram is now operationally visible inside the admin workspace through:

- `/admin/telegram`
- `/admin/telegram/accounts`
- `/admin/telegram/notifications`
- `/admin/telegram/templates`
- `/admin/telegram/campaigns`
- `/admin/telegram/settings`

These screens are read-focused operational pages for:

- dashboard visibility of accounts, delivery, failures, and interactions
- ops-first Telegram workspace navigation
- export of dashboard summary as JSON
- export of masked notification logs as CSV with operational filters
- manual campaign launchpad with masked audience preview and queue-only execution
- campaign launch guardrails with visible batch cap and launch summary
- recent campaign preview/queue history inside the admin launchpad
- export of campaign preview and queue history as CSV
- linked vs unlinked account review
- verification visibility
- last interaction visibility
- notification queue monitoring
- failure review
- failed notification retry
- masked payload preview
- telegram template editing and preview
- bot identity and delivery setting management

Security posture for admin UI:

- route-level permission checks
- masked PII by default unless the viewer has PII access
- no direct password, token, or raw secret exposure
- stored bot token and webhook secret remain encrypted through `SiteSetting`
- no direct business mutation from these screens

## Privacy Considerations

- no passwords are sent in Telegram
- no raw secrets are sent to users
- webhook secret is validated when configured
- account linking is tokenized and auditable
- interactions are logged without storing sensitive credentials

## Future Expansion

Planned future slices:

- attendance reminders and confirm actions
- role-aware instructor shortcuts
- drip campaign orchestration on top of the event bus

## Operational Notes

Environment-backed defaults are supported for:

- `TELEGRAM_BOT_TOKEN`
- `TELEGRAM_BOT_USERNAME`
- `TELEGRAM_ADMIN_CHAT_ID`
- `TELEGRAM_PARSE_MODE`
- `TELEGRAM_RATE_LIMIT_PER_MIN`
- `TELEGRAM_WEBHOOK_SECRET`
- `TELEGRAM_LINK_EXPIRES_MINUTES`
- `TELEGRAM_SECURITY_ALERTS_ENABLED`
- `TELEGRAM_STUDENT_NOTIFICATIONS_ENABLED`
- `TELEGRAM_ADMIN_NOTIFICATIONS_ENABLED`
