Complete System Flow Diagrams โ Architecture, Data Flows & Security
OAuth 2.0 flow with JWT tokens, refresh tokens, and mobile biometric session unlock.
Client sends HTTP-only refresh token โ Backend validates โ Issues new JWT (15 min) + rotates refresh token โ Client retries original request.
Both tokens expired โ User redirected to full re-authentication flow โ New OAuth 2.0 handshake required.
Local session invalidated โ Full re-authentication via OAuth 2.0 required โ Previous local encryption keys rotated.
Strict permission model ensuring users only access what their job function requires.
403 Forbidden โ Log unauthorized access attempt โ Alert if repeated (brute-force detection).
Administrative setup required before any audit can run โ mapping software to physical reality.
Standard Review โ Flagged in dashboard for manager review. May require zone re-count.
Escalated Alert โ Immediate notification to Pharmacy Manager. Requires investigation before audit closure.
HIS file upload, background parsing, data sanitization, and audit activation on the web dashboard.
Pharmacy Manager uploads HIS export (CSV/Excel) via web dashboard. File contains Expected Stock, Batch IDs, Expiry Dates, and Unit Costs.
Core API returns 202 Accepted immediately. Raw file is uploaded to AWS S3 for secure storage. An IngestFile job is published to the message queue (SQS/BullMQ).
Background worker picks up the job, streams file from S3 (no memory bloat), strips invalid characters, normalizes data, validates batch IDs & date formats.
Sanitized "Expected Stock" records are batch-inserted into the database, linked to the Audit Session ID. Status updates to READY.
Manager reviews ingested data summary, clicks "Publish Audit". Session status changes to ACTIVE โ now visible to Floor Auditors on mobile.
Offline-first barcode scanning, local storage, and edge conflict handling on the pharmacy floor.
Auditor logs in, selects the active Audit Session. App downloads the Expected Stock catalog to local WatermelonDB. last_pulled_at timestamp recorded.
Auditor moves to physical location (e.g., "ICU Ward", "Cold Storage A") and selects that zone in the app. All subsequent scans are tagged with this zone.
Device camera or paired Bluetooth scanner reads barcode. App retrieves item from local DB โ displays name, batch, expiry. Auditor inputs physical quantity count.
Additive Model: If the same barcode is scanned twice in the same session, the app increments the local count rather than overwriting. Prevents data loss from accidental re-scans.
Each scan record receives a UUID v4 (idempotency key), status set to pending_sync, timestamped. Stored encrypted in WatermelonDB. Auditor repeats Steps 2โ5.
When network detected (react-native-netinfo), Sync Manager initiates bulk POST with exponential backoff. All pending_sync records pushed to backend. Status flipped to synced.
Backend data merge, concurrency resolution, and variance calculation engine.
Expected equals physical count. Item marked as Verified. No action required.
Physical count is less than expected. Flagged by severity tier. Potential revenue leakage.
Physical count exceeds expected. May indicate unrecorded deliveries or HIS data errors.
Items past expiry date. Flagged for immediate removal and disposal documentation.
Variance aggregation, financial mapping, revenue leakage calculation, and data export.
Containerized, cloud-native 4-tier architecture with offline-first edge nodes.
Pre-audit data pipeline โ from CSV upload to structured PostgreSQL records.
Pharmacy Manager uploads HIS export file (CSV or Excel) through the web dashboard file upload interface.
Core API uploads the raw, unmodified file to S3 for secure long-term storage and auditability. Bucket versioning enabled.
API publishes an IngestFile event to the message queue (SQS/BullMQ). Returns 202 Accepted to the client immediately โ no blocking.
Worker picks up the job, streams file from S3 (avoids loading 50K+ rows into memory). Parses, sanitizes, validates batch IDs, normalizes date formats.
Structured "Expected Stock" records batch-inserted with ACID compliance. Each row linked to Audit Session ID. Raw lines optionally stored in JSONB for traceability.
WatermelonDB pull (download catalog) and push (upload scans) with idempotency guarantees.
Defense-in-depth strategy with encryption, immutable audit trails, and strict access controls.
Enforced TLS 1.3 across all endpoints ยท No unencrypted HTTP past Nginx ยท Rate limiting & brute-force mitigation
OAuth 2.0 + JWT (15-min lifespan) ยท Rotating refresh tokens ยท RBAC middleware on every endpoint ยท SSO integration
AWS KMS encryption for EBS & RDS ยท Mobile data encrypted via Keychain/Keystore ยท S3 server-side encryption
Append-only ledger model ยท Strict soft deletes ยท Every state reconstructable ยท Immutable scan history ยท Full traceability
Containerized approach using Docker, AWS, and managed services for high availability.
Each service (API, Sync Engine, Ingestion Worker) runs in its own container for isolation and consistent deployments.
DockerScalable hosting via AWS ECS/EKS. Auto-scaling groups respond to sync traffic spikes during audit events.
AWS ECS / EKSReverse proxy handles load balancing, SSL/TLS termination, rate limiting, and WebSocket routing.
NginxManaged database with automated backups, point-in-time recovery, and ACID compliance for all transactions.
AWS RDSDurable object storage for raw HIS files, audit reports, and long-term compliance archives.
AWS S3Decouples heavy processing from API. Ensures file ingestion and report generation never block user requests.
SQS / BullMQHorizontal scaling strategy as the platform grows across multiple pharmacies and hospitals.
Single container instance per service. One PostgreSQL primary. Handles dozens of concurrent auditors.
Horizontal scale-out of API & Sync Engine behind Nginx load balancer. Database connection pooling (PgBouncer).
PostgreSQL Read Replicas for analytics queries. Dedicated Sync Engine fleet. CDN for static dashboard assets.
Multi-region deployment. Database geo-replication. Regional API endpoints for latency optimization.
Complex analytical queries (revenue leakage reports, trend analysis) never degrade the performance of active sync operations on the pharmacy floor.
Pharmacy Audit Management Platform โ System Flow Diagrams
Generated April 2026 ยท All diagrams reflect the complete system specification