Skip to main content

JanSamadhan platform documentation

Professional documentation for product, engineering, and operations teams.

This page consolidates system intent, architecture, lifecycle guarantees, and operational behavior in one readable reference. It is designed for high scanning speed while preserving technical depth.

NOTE: JanSamadhan is a Private R&D Prototype. This platform is a technology demonstration and is not an official government service.

Technical docsArchitecture-firstRole workflowsAPI and DB referenceOps readiness

Executive Snapshot

High-speed briefing on platform scope, guarantees, and why this implementation is operationally distinct.

Complaint categories

42+

Mapped across major Delhi civic authorities.

Authority zones

9

Department-aware routing and visibility.

API endpoints

56+

FastAPI, Next.js handlers, and AI service.

RLS policies

28

Department isolation at database layer.

Role portals

4

Citizen, Authority, Worker, and Admin.

Voice languages

10

Multilingual STT for complaint intake.

Core design principle: high-impact rules are enforced at transaction and database policy level, not only at interface level.

Problem Definition

The system addresses fragmentation, low transparency, duplicate noise, and weak closure accountability in civic operations.

The operational failure mode in legacy civic systems is not only ticket intake. It is the disconnected chain from complaint submission to assignment, field execution, and closure verification.

Citizens lose confidence when timelines are opaque. Authorities lose efficiency when duplicates flood the queue. Workers lose time when location and context are weak. This documentation focuses on structural controls that directly address those gaps.

Pain pointGround realityDesign response
No single windowCitizens must already know which department handles which issue.Unified intake with AI-assisted category and authority prediction.
Zero visibilityComplaints disappear without status context or timeline confidence.Lifecycle state machine with immutable ticket history.
Duplicate noiseOne pothole can create dozens of separate complaints.PostGIS radius-based dedup with upvote merge behavior.
Language barrierEnglish-only forms block broad participation.Hindi and multilingual voice ingestion via STT pipeline.
No spatial intelligenceAuthorities cannot identify hotspot clusters early.DIGIPIN + map-first dashboards + nearby complaint discovery.
Worker context gapField teams get vague assignments with little proof context.Mobile-first worker dashboard with maps, SLA timer, and proof upload.
Jurisdiction overlapWrong-department routing delays closure and accountability.Department-scoped authority view enforced by JWT-backed RLS.

Platform Solution

Four role portals share one lifecycle model, one source of truth, and enforcement controls at the database layer.

Citizen portal

Complaint filing via Seva, voice, map pin, status tracking, and rating loop.

Authority dashboard

Department-scoped triage, worker assignment, escalation, and internal notes.

Worker interface

Mobile-first web task execution with navigation, SLA countdown, and proof upload.

Admin control panel

Cross-system moderation, analytics, CCTV oversight, and account governance.

One citizen-facing intake surface, isolated authority views, and centralized governance data for admin operations.

Why This Is Different

Differentiators are tied to enforceable implementation choices, not cosmetic feature claims.

CapabilityImplementationOperational impact
AI complaint intakeGemini classifies category, severity, and likely authority from free text.Reduces form friction and improves first-route accuracy.
DIGIPIN location identity10-character India Post code generated from pin-selected coordinates.Improves field navigation precision and address stability.
PostGIS duplicate suppression20m radius check before insert; existing complaint can be upvoted instead.Prevents spam-like duplication and amplifies signal quality.
DB-level department isolationRLS policies enforce row visibility using role and department claims.Blocks cross-department leakage even if UI logic is bypassed.
Race-safe assignmentFOR UPDATE locking inside assignment RPC.Prevents concurrent worker double-assignment.
Auto-escalation on breachCron-callable RPC escalates overdue in-progress tickets.Removes dependency on manual deadline monitoring.
CCTV reliability engineBurst-based multi-frame consensus before auto ticket creation.Reduces false positives from single noisy frames.
Immutable audit trailTicket history rows persist key state and action transitions.Improves traceability for citizen trust and admin review.

End-to-End Complaint Journey

A deterministic lifecycle path from citizen intake to field proof and confirmation feedback.

  1. Citizen reports issue in Hindi, English, or voice through Seva or manual form.
  2. System enriches payload with category, severity, authority hint, and DIGIPIN coordinates.
  3. Duplicate check runs with PostGIS distance logic before complaint creation.
  4. Ticket is created with SLA deadline and notification payloads for citizen tracking.
  5. Authority dashboard surfaces ticket in department-scoped queue and assigns field worker.
  6. Worker navigates to location, updates status, and uploads proof evidence on completion.
  7. Citizen receives closure message and can confirm or reopen within policy limits.
  8. Ticket history preserves every transition for analytics and accountability.
Example target outcome: issue reported, routed, assigned, resolved with proof, and citizen-confirmed within SLA.

Trust and Accountability

Key guarantees are anchored in policies, triggers, and transactional functions that are hard to bypass.

  • No duplicate ticket is inserted for the same category inside configured distance checks.
  • Invalid lifecycle transitions are blocked by trigger-level checks before commit.
  • Authorities cannot query complaints outside their department scope via RLS.
  • Assignment race conditions are blocked with row locks in assignment RPC logic.
  • SLA breach escalation can run from cron without frontend or API availability.
  • Severity escalation from community upvotes is monotonic and never decreases.
  • DIGIPIN location encoding does not require an online geocoding API call.

Core Systems Breakdown

Subsystem-level view of intake, spatial logic, escalation, surveillance, engagement, and governance.

SystemBehaviorOperational value
AI intake and Seva chatbotClassifies complaint text, proposes category and priority, supports multilingual prompts.Higher completion rate for non-technical citizens.
DIGIPIN and map intelligenceConverts pin location to stable code and supports map-driven workflow routing.Accurate field navigation and geospatial analytics.
Duplicate and upvote engineIdentifies proximity duplicates and shifts users to vote-based amplification.Cleaner queue quality and better prioritization signal.
SLA and escalation engineEvaluates deadlines and escalates pending tickets via background function.Consistent deadline governance with minimal manual intervention.
CCTV and verification loopAnalyzes camera bursts, proposes incidents, supports repaired/not-repaired verification.Extends detection coverage beyond manual citizen reports.
Gamification and walletAwards points for constructive participation and applies penalties for abuse.Promotes participation while deterring spam behavior.
Notification pipelineSends email and WhatsApp events with deep links and closure prompts.Maintains citizen loop continuity after submission.
Admin analytics and governanceAggregates platform metrics, department performance, and operational health.Supports planning, staffing, and policy interventions.

Role Flows and Boundaries

Responsibilities and boundaries per role to preserve clarity, safety, and operational ownership.

RoleCan doCannot do
CitizenCreate complaints, track status, upvote, rate resolution, reopen within policy.Assign workers, view internal authority notes, change department ownership.
AuthorityReview department tickets, assign workers, escalate, add internal notes.View other departments when RLS constraints are active.
WorkerView assigned tickets, update status, upload proof, request materials.Self-assign tickets or access unrelated workers' queues.
AdminCross-platform moderation, analytics, user management, and CCTV operations.Bypass accountability records; ticket history remains auditable.

System Architecture

Layered architecture with explicit boundaries for client, APIs, data, integrations, and cloud runtime.

LayerStackNotes
ClientNext.js 15 + React 19Role-specific portals, map workflows, and citizen-facing accountability views.
Application APIsFastAPI + Next.js route handlers + AI microserviceComplaint intake, role workflows, notifications, CCTV processing, and admin controls.
DataPostgreSQL 15 + PostGIS + Supabase Storage + RedisRLS, triggers, RPC transactions, spatial indexing, and cache/session support.
External integrationsGoogle Gemini, Sarvam STT, Mappls, WhatsApp Cloud API, ResendGemini use assumes paid API access; no free-tier dependency is documented.
InfrastructureGCP Cloud Run + Cloud Build + Secret ManagerThree-service deployment topology with containerized release workflow.

Data Model and RPCs

Enums, triggers, RLS, and RPC transactions form the core integrity model of the platform.

complaint_statusseverity_levelworker_availability

Core setup sequence: define enum types, create dependency-ordered tables, apply spatial indexes, register triggers, create RPC functions, then enable and verify RLS policies.

RPCPurpose
check_for_duplicate_report20m duplicate detection before complaint insert.
find_duplicate_complaints_v2Extended duplicate scan with status and radius controls.
increment_upvote_countAtomic upvote plus effective severity recalculation.
assign_worker_to_complaintAssignment with row locking for race protection.
check_sla_breachesEscalates overdue assigned or in-progress complaints.
nearest_urgent_complaintProximity and urgency-aware dispatch helper.
get_nearby_complaintsDistance-ranked complaint discovery for maps.
award_pointsGamification point updates in a single transaction.
redeem_rewardAtomic reward redemption and balance validation.
update_complaint_status_citizenCitizen confirm/reopen action with policy checks.

API Surface

Representative endpoint inventory across FastAPI, Next.js routes, and environment contract requirements.

FastAPI core endpoints

EndpointMethodPurpose
/analyzePOSTAI-assisted complaint preview and routing suggestion.
/confirmPOSTComplaint creation, routing, dedup, and notifications.
/citizen/ticketsGETCitizen ticket feed with status visibility.
/citizen/nearbyGETMap-based nearby issue discovery.
/api/authority/assignPATCHAuthority worker assignment operation.
/api/authority/dashboardGETAuthority queue and SLA dashboard data.
/api/worker/dashboardGETWorker task list and execution context.
/api/admin/analyticsGETPlatform-level operational analytics.
/whatsapp/webhookGET/POSTWhatsApp verification and bot message handling.
/cctv/analyze_livePOSTCCTV frame burst analysis with reliability checks.
/cctv/verifyPOSTVerification feedback for camera-detected incidents.

Next.js app route handlers

EndpointMethodPurpose
/api/complaintsPOST/PATCHComplaint create, update, and upvote operations.
/api/chatPOSTGemini proxy with fallback model handling.
/api/sttPOSTSarvam STT proxy for multilingual voice submission.
/api/verify-recaptchaPOSTServer-side captcha verification.
/api/citizen/walletGET/POSTWallet points, rewards, and redemption state.
/api/citizen/leaderboardGETPublic engagement leaderboard data.
/api/admin/authoritiesGET/POST/PATCHAuthority account management.
/api/admin/workersGET/POST/PATCHWorker account management.
/api/admin/complaints/spamPOSTSpam moderation and penalty flow.
/api/admin/system/sync-walletsPOSTBackfill wallet balances for existing users.

Key environment variables

VariablePurpose
NEXT_PUBLIC_SUPABASE_URLSupabase project URL for client access.
NEXT_PUBLIC_SUPABASE_ANON_KEYPublic key for browser-level Supabase operations.
SUPABASE_SERVICE_ROLE_KEYPrivileged server-side key for administrative actions.
GEMINI_API_KEYGoogle Gemini key for paid API usage.
GEMINI_PRIMARY_MODELOptional primary model override.
GEMINI_FALLBACK_MODELFallback model for quota/model errors.
MAPPLS_API_KEYIndia-focused geocoding and map enrichment.
NEXT_PUBLIC_API_URLBackend API base URL consumed by web clients.
NEXT_PUBLIC_RECAPTCHA_SITE_KEYPublic reCAPTCHA site key.
RECAPTCHA_SECRET_KEYServer-side captcha verification key.
SARVAM_API_KEYSpeech-to-text service authentication.
RESEND_API_KEYTransactional email service key.
FRONTEND_BASE_URLCanonical deep-link origin for messages and notifications.
AI_SERVICE_URLAI service endpoint for CCTV proxy operations.
REDIS_URLCache and session backend URL.
WHATSAPP_TOKENMeta WhatsApp Cloud API token.
WHATSAPP_PHONE_NUMBER_IDWhatsApp sender configuration.
WHATSAPP_VERIFY_TOKENWebhook verification token.

Security and Integrity

Security model combines authentication, RLS, anti-abuse controls, and enforceable transition integrity.

ControlDetail
RLS role isolationRow access constrained by role and department claims.
Status transition validationTrigger checks block invalid status transitions.
Captcha abuse preventionServer-side reCAPTCHA verification for public intake paths.
Assignment lock safetyFOR UPDATE locking prevents concurrent assignment conflicts.
Audit trail persistenceState and action records retained for review and governance.
Secret managementRuntime secret injection through cloud secret stores.
Moderation and penaltiesSpam flagging and wallet penalties deter abuse patterns.
Security guarantees are strongest when enforcement resides in DB policy and transaction logic, not just client code.

Operations and Deployment

Operational model is containerized and split across web, API, and AI services with cloud-native deployment controls.

Deployment topology uses three services: web, API, and AI. Local simulation uses Docker Compose, while production uses Cloud Run with Cloud Build and managed secret injection.

Pre-release checks should validate complaint intake, assignment transactions, deep-link generation, notification channels, and AI-service health before rollout approval.

  • Validate FRONTEND_BASE_URL before sending any notification links.
  • Ensure pending_closure migration is applied in the target database.
  • Verify model and API credentials are loaded from secret manager.
  • Run smoke checks for /analyze, /confirm, /api/authority/assign, and /cctv/analyze_live.

Failure Handling / Edge Cases

Production posture requires explicit responses to common failure and abuse scenarios.

ScenarioSystem response
Gemini quota or model failureFallback to manual submission or fallback model path.
Duplicate complaint attemptPre-submit dedup guides citizen to upvote existing ticket.
Worker unavailable mid-taskAuthority can reassign; overdue tickets escalate automatically.
SLA breach with no manual reviewCron RPC escalates to high-priority authority queue.
Single-frame CCTV false positiveBurst consensus threshold suppresses low-confidence incidents.
Spam submission burstsCaptcha, moderation queue, and penalties limit abuse impact.
Broken deep linkFRONTEND_BASE_URL validation and UUID-based detail links.
Concurrent assignment attemptsSecond transaction is rejected by lock conflict semantics.

Comparative Positioning

Comparison against common grievance baseline behavior across accessibility, governance, and closure reliability.

DimensionLegacy portalsJanSamadhan
Language and accessibilityEnglish-heavy forms with high form literacy requirement.Hindi and multilingual voice-assisted intake with guided flow.
Duplicate handlingRepeated records for same incident in dense areas.Distance-aware dedup and upvote aggregation.
Department isolationSoft segregation; frequent routing confusion.RLS-backed department boundaries and role isolation.
SLA governanceManual follow-up and limited breach visibility.Automated escalation and dashboard-level breach surfacing.
Resolution proofClosure may happen without contextual field evidence.Worker proof artifacts and closure confirmation loop.
Citizen accountability viewSparse status context.Trackable lifecycle with audit-friendly status history.

Current Scope and Limits

Live, partial, and planned items are separated to prevent ambiguity about production readiness.

FeatureStatusNotes
Citizen, Authority, Worker, Admin portalsLiveRole-specific production interfaces are active.
Seva chatbot and multilingual voice intakeLiveGemini and Sarvam flows are integrated in active runtime.
DIGIPIN and map-first workflowsLiveComplaint creation and worker navigation pipelines use map coordinates.
WhatsApp intake and closure loopLive (v1)Menu-driven intake and closure reminders are shipped.
CCTV reliability and verificationLiveBurst analysis and verification outcomes are available.
Infrastructure-as-code scaffoldingPartialFolder scaffolds exist; full Terraform rollout remains pending.
Service worker offline cachingPlannedPlanned enhancement; worker portal is currently web mobile-first, not a PWA.
Multi-city rolloutPlannedCurrent scope emphasizes Delhi confidence before expansion.
CPGRAMS bridge integrationPlannedFuture interoperability phase.
Worker operations currently use a mobile-first web dashboard. A dedicated worker PWA is not shipped in current scope.

Roadmap

Roadmap phases are additive and move from city confidence to interoperability and scale.

Phase 1

Delhi pilot with all role portals and core governance controls.

Status: Complete

Phase 2

City expansion playbook for Mumbai, Bengaluru, and Chennai.

Status: Planned

Phase 3

Offline caching and resilience improvements for low-connectivity areas.

Status: Planned

Phase 4

WhatsApp conversational depth expansion beyond v1 flow.

Status: In progress

Phase 5

Cross-platform escalation bridge and inter-jurisdiction routing.

Status: Planned

Phase 6

Future DIGIPIN API alignment and national-scale integrations.

Status: Planned

Glossary

Plain-language definitions for recurring technical terms used throughout this document.

TermPlain meaningTechnical meaning
DIGIPINIndia's location code system.10-character location identity from India Post used for precise mapping.
RLSDatabase row-level access walls.PostgreSQL policy layer that constrains row visibility by role claims.
PostGISSpatial extension for PostgreSQL.Adds geospatial functions such as distance checks for dedup logic.
SLAComplaint deadline contract.Timing policy for escalation, prioritization, and closure accountability.
RPCAtomic database function call.Server-side function that runs as a single transaction.
FOR UPDATERow reservation lock.Concurrency control used during worker assignment operations.
YOLOReal-time vision model.Model family used for CCTV incident detection in AI service workflows.
pending_closureWaiting for citizen confirmation.Lifecycle state between worker resolution and citizen final closure decision.