Pharmacy Audit Platform

Complete System Flow Diagrams โ€” Architecture, Data Flows & Security

React Native Node.js / TypeScript PostgreSQL WatermelonDB Docker / AWS Nginx
01

Authentication & Security (IAM)

OAuth 2.0 flow with JWT tokens, refresh tokens, and mobile biometric session unlock.

๐Ÿ”‘ Primary Authentication Flow

User Opens App / Dashboard
Web or Mobile client
SSO Enabled?
Identity Provider
Entra ID / Okta / Email+Password
OAuth 2.0 Token Exchange
Authorization Code Grant
Backend Issues Tokens
JWT (15 min) + Refresh Token (7 days)

๐Ÿ”„ Token Lifecycle & Refresh

Client Makes API Request
Attach JWT in Authorization header
JWT Valid?
โœ“ Allow Request
Process normally (JWT valid)
JWT Expired Path

Client sends HTTP-only refresh token โ†’ Backend validates โ†’ Issues new JWT (15 min) + rotates refresh token โ†’ Client retries original request.

Refresh Token Expired

Both tokens expired โ†’ User redirected to full re-authentication flow โ†’ New OAuth 2.0 handshake required.

๐Ÿ“ฑ Mobile App Session (Edge Security)

App Reopened / Backgrounded
Session still active in Keychain/Keystore
Active Session?
Biometric / PIN Prompt
FaceID ยท Fingerprint ยท 4-digit PIN
Verified?
โœ“ Resume Session
Decrypt local WatermelonDB store
Biometric Fails 3ร—

Local session invalidated โ†’ Full re-authentication via OAuth 2.0 required โ†’ Previous local encryption keys rotated.

๐Ÿ”’ Data Encryption at Rest

Physical Scan Data
Barcode, Qty, Timestamp, Zone
WatermelonDB (SQLite)
Local database on device
Encrypted at Rest
iOS Keychain ยท Android Keystore
Secure Hardware Enclave
AES-256 device-bound keys
02

Role-Based Access Control (RBAC)

Strict permission model ensuring users only access what their job function requires.

๐Ÿ‘ฅ RBAC Permission Matrix

๐Ÿ›ก๏ธ System Admin (IT)

Platform: Web Dashboard
  • Create & edit user accounts
  • Assign RBAC roles & profiles
  • Configure SSO / Entra ID / Okta
  • Manage HIS connection settings
  • View system health & error logs
  • Cannot alter audit inventory data
  • Cannot view financial reports

๐Ÿ“‹ Pharmacy Manager

Platform: Web Dashboard
  • Create new audit sessions
  • Upload HIS data (CSV/Excel)
  • Define facility zones & areas
  • Set variance tolerance thresholds
  • Activate / publish audits
  • Review discrepancies & variances
  • Approve & close final reports

๐Ÿ“ฒ Floor Auditor

Platform: Mobile App
  • Download active audit catalogs
  • Full offline scanning mode
  • Scan barcodes / QR codes
  • Input physical stock counts
  • Sync data when online
  • Cannot view expected financial values
  • Cannot modify audit parameters

๐Ÿ“Š Executive / C-Suite

Platform: Web Dashboard (Read-Only)
  • View summary dashboards
  • View financial insights
  • Access historical trend reports
  • Export reports to PDF/Excel
  • Cannot create or modify audits
  • Cannot manage users or config

โšก RBAC Enforcement Flow

Incoming API Request
Any authenticated user
Extract JWT Claims
user_id, role, permissions[]
RBAC Middleware
Check role against route policy
Allowed?
โœ“ 200 OK โ€” Execute
Process business logic
Access Denied

403 Forbidden โ†’ Log unauthorized access attempt โ†’ Alert if repeated (brute-force detection).

03

System Configurables & Master Data

Administrative setup required before any audit can run โ€” mapping software to physical reality.

๐Ÿฅ Facility & Zone Mapping Flow

Manager Logs In
Web Dashboard
Define Facility
"City General Hospital"
Create Zones
Main Pharmacy ยท ICU Ward ยท Cold Storage A ยท Aisle 4
Zones Saved to DB
Available for audit sessions & mobile app

โš™๏ธ Variance Tolerance Threshold Configuration

Manager Sets Rules
Configurable per category
Variance Amount?
โ‰ค $5.00 โ†’ Minor Variance
Auto-accepted, logged only
$5.01 โ€“ $49.99

Standard Review โ€” Flagged in dashboard for manager review. May require zone re-count.

โ‰ฅ $50.00 โ€” Critical Review

Escalated Alert โ€” Immediate notification to Pharmacy Manager. Requires investigation before audit closure.

๐Ÿ“ Audit Session Creation & Lifecycle

Create Audit Event
"Q3 Full Inventory"
Assign Session ID
UUID generated โ€” tags all scans
Status: DRAFT
Not visible to mobile
Upload HIS + Config Zones
Attach expected stock data
Status: ACTIVE
Manager clicks "Publish" โ€” visible on mobile
04

Phase 1: Initiation & Ingestion

HIS file upload, background parsing, data sanitization, and audit activation on the web dashboard.

๐Ÿ“ค HIS File Upload & Processing Pipeline

1

File Upload

Pharmacy Manager uploads HIS export (CSV/Excel) via web dashboard. File contains Expected Stock, Batch IDs, Expiry Dates, and Unit Costs.

2

API Accepts & Queues Async

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).

3

Ingestion Worker Processes

Background worker picks up the job, streams file from S3 (no memory bloat), strips invalid characters, normalizes data, validates batch IDs & date formats.

4

Batch Insert to PostgreSQL

Sanitized "Expected Stock" records are batch-inserted into the database, linked to the Audit Session ID. Status updates to READY.

5

Audit Activation

Manager reviews ingested data summary, clicks "Publish Audit". Session status changes to ACTIVE โ€” now visible to Floor Auditors on mobile.

05

Phase 2: Execution (Mobile Application)

Offline-first barcode scanning, local storage, and edge conflict handling on the pharmacy floor.

๐Ÿ“ฑ Floor Auditor โ€” Scan & Count Flow

1

Session Init Online

Auditor logs in, selects the active Audit Session. App downloads the Expected Stock catalog to local WatermelonDB. last_pulled_at timestamp recorded.

2

Select Physical Zone Offline

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.

3

Scan Barcode Offline

Device camera or paired Bluetooth scanner reads barcode. App retrieves item from local DB โ†’ displays name, batch, expiry. Auditor inputs physical quantity count.

4

Duplicate Scan Handling Offline

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.

5

Local Save & Queue Offline

Each scan record receives a UUID v4 (idempotency key), status set to pending_sync, timestamped. Stored encrypted in WatermelonDB. Auditor repeats Steps 2โ€“5.

6

Bulk Data Push Online

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.

06

Phase 3: Synchronization & Resolution

Backend data merge, concurrency resolution, and variance calculation engine.

๐Ÿ”„ Sync & Concurrency Resolution Pipeline

Device A Pushes
Auditor 1: 50ร— Paracetamol in Zone A
Sync Engine
Validates UUIDs, checks idempotency
Additive Merge
SUM all counts per batch: 50 + 30 = 80
Total Physical Count
80 units in PostgreSQL
Device B Pushes
Auditor 2: 30ร— Paracetamol in Zone B

๐Ÿ“Š Variance Calculation Engine

Manager Clicks "Close Audit"
No more syncs accepted
Reconciliation Script
ฮ” = Expected โˆ’ Physical
Delta Value?
ฮ” = 0 โ†’ Match โœ“

Expected equals physical count. Item marked as Verified. No action required.

ฮ” > 0 โ†’ Shortage โš ๏ธ

Physical count is less than expected. Flagged by severity tier. Potential revenue leakage.

ฮ” < 0 โ†’ Overage ๐Ÿ“ฆ

Physical count exceeds expected. May indicate unrecorded deliveries or HIS data errors.

Expired Stock ๐Ÿšซ

Items past expiry date. Flagged for immediate removal and disposal documentation.

๐Ÿ”‘ Idempotency & Retry Safety

Mobile Sends Scan Batch
Each record has UUID v4
Network Drops?
Retry with Same UUIDs
Exponential backoff: 1s โ†’ 2s โ†’ 4s
Backend Deduplicates
UUID exists? โ†’ Skip. New? โ†’ Insert.
Zero Duplicate Counts
Data integrity guaranteed
07

Phase 4: Reporting & Analytics

Variance aggregation, financial mapping, revenue leakage calculation, and data export.

๐Ÿ“ˆ Report Generation Pipeline

Audit Closed
Final reconciliation complete
Aggregate Deltas
Group by: Status, Zone, Category
Categorize Variances
Match ยท Shortage ยท Overage ยท Expired
Generate Reports
Dashboard + downloadable files

๐Ÿ’ฐ Financial Impact & Revenue Leakage

Shortage Items
Missing qty per batch
ร— Unit Cost (from HIS)
Missing Qty ร— Price = Loss per item
Total Revenue Leakage
ฮฃ all shortage losses
Executive Dashboard
C-Suite financial summary view

๐Ÿ“ Data Export & HIS Feedback Loop

Finalized Audit Data
All variances approved
Export to CSV/Excel
Formatted for HIS import schema
Feed Back to HIS
Correct master inventory records
HIS Records Updated
Inventory accuracy restored
08

System Architecture

Containerized, cloud-native 4-tier architecture with offline-first edge nodes.

๐Ÿ—๏ธ High-Level Architecture Diagram

A. Edge Tier โ€” Mobile Client
React Native App iOS & Android cross-platform
WatermelonDB Optimized local relational DB with sync primitives
Sync Manager Network monitor + Store-and-Forward queue + Exponential Backoff
Barcode Scanner Camera + Bluetooth scanner integration
HTTPS / TLS 1.3
B. Gateway & Load Balancing Tier
Nginx Reverse Proxy SSL termination ยท Rate limiting ยท Request routing ยท WebSocket support
C. Application Tier โ€” Dockerized Services (ECS/EKS)
Core Audit API Node.js/TypeScript โ€” Auth, Sessions, CRUD
Sync Engine WatermelonDB push/pull โ€” Additive merge & conflict resolution
Ingestion Worker Background CSV/Excel parser โ€” Async from queue
D. Data Tier
PostgreSQL (AWS RDS) ACID transactions ยท JSONB ยท Automated backups ยท Read Replicas
AWS S3 Raw HIS file storage ยท Audit trail archive
AWS SQS / BullMQ Message queue โ€” Decouples API from heavy tasks
09

Critical Data Flow: HIS Ingestion

Pre-audit data pipeline โ€” from CSV upload to structured PostgreSQL records.

๐Ÿ“„ HIS File Ingestion Pipeline

1

Admin Uploads CSV

Pharmacy Manager uploads HIS export file (CSV or Excel) through the web dashboard file upload interface.

2

Raw File โ†’ AWS S3

Core API uploads the raw, unmodified file to S3 for secure long-term storage and auditability. Bucket versioning enabled.

3

Publish IngestFile Event

API publishes an IngestFile event to the message queue (SQS/BullMQ). Returns 202 Accepted to the client immediately โ€” no blocking.

4

Ingestion Worker Streams from S3

Worker picks up the job, streams file from S3 (avoids loading 50K+ rows into memory). Parses, sanitizes, validates batch IDs, normalizes date formats.

5

Batch Insert โ†’ PostgreSQL

Structured "Expected Stock" records batch-inserted with ACID compliance. Each row linked to Audit Session ID. Raw lines optionally stored in JSONB for traceability.

10

Critical Data Flow: Two-Phase Synchronization

WatermelonDB pull (download catalog) and push (upload scans) with idempotency guarantees.

โฌ‡๏ธ Phase A: The Pull (Download Catalog)

Mobile App
Sends last_pulled_at timestamp
Sync Engine
Queries PostgreSQL for changes since timestamp
Delta Response
Only created/updated rows since last sync
WatermelonDB Updated
Local catalog ready for offline use

โฌ†๏ธ Phase B: The Push (Upload Scans)

Network Detected
react-native-netinfo triggers
Collect pending_sync
All local records with UUID v4 keys
Bulk POST to Sync Engine
Exponential backoff on failure
UUID Dedup Check
Prevents double-counting on retry
Records Persisted
Status โ†’ synced โœ“
11

Security & Compliance Posture

Defense-in-depth strategy with encryption, immutable audit trails, and strict access controls.

๐Ÿ›ก๏ธ Security Layers (Defense in Depth)

Layer 1 โ€” Network Perimeter

Enforced TLS 1.3 across all endpoints ยท No unencrypted HTTP past Nginx ยท Rate limiting & brute-force mitigation

Layer 2 โ€” Authentication & Authorization

OAuth 2.0 + JWT (15-min lifespan) ยท Rotating refresh tokens ยท RBAC middleware on every endpoint ยท SSO integration

Layer 3 โ€” Data Protection

AWS KMS encryption for EBS & RDS ยท Mobile data encrypted via Keychain/Keystore ยท S3 server-side encryption

Layer 4 โ€” Audit Trail & Compliance

Append-only ledger model ยท Strict soft deletes ยท Every state reconstructable ยท Immutable scan history ยท Full traceability

๐Ÿ“œ Immutable Audit Trail Flow

User Modifies Record
Edit count or expected stock
โš ๏ธ No Overwrite
Original row is never modified
Append New Version
New row with version++, timestamp, user_id
Full History Preserved
Any state reconstructable for compliance
12

Deployment & Infrastructure

Containerized approach using Docker, AWS, and managed services for high availability.

โ˜๏ธ Infrastructure Components

๐Ÿณ

Docker Containers

Each service (API, Sync Engine, Ingestion Worker) runs in its own container for isolation and consistent deployments.

Docker
โ˜๏ธ

AWS Cloud

Scalable hosting via AWS ECS/EKS. Auto-scaling groups respond to sync traffic spikes during audit events.

AWS ECS / EKS
๐Ÿ”€

Nginx Gateway

Reverse proxy handles load balancing, SSL/TLS termination, rate limiting, and WebSocket routing.

Nginx
๐Ÿ—„๏ธ

PostgreSQL (RDS)

Managed database with automated backups, point-in-time recovery, and ACID compliance for all transactions.

AWS RDS
๐Ÿ“ฆ

AWS S3 Storage

Durable object storage for raw HIS files, audit reports, and long-term compliance archives.

AWS S3
๐Ÿ“ฌ

Message Queue

Decouples heavy processing from API. Ensures file ingestion and report generation never block user requests.

SQS / BullMQ

๐Ÿš€ CI/CD Deployment Pipeline

Code Push
Git push to main branch
CI Pipeline
Lint ยท Test ยท Security scan
Docker Build
Build & tag container images
Push to ECR
AWS Container Registry
Rolling Deploy
Zero-downtime via ECS/EKS
13

Scalability Path

Horizontal scaling strategy as the platform grows across multiple pharmacies and hospitals.

๐Ÿ“ˆ Scaling Strategy

๐Ÿฅ

Single Hospital

Single container instance per service. One PostgreSQL primary. Handles dozens of concurrent auditors.

๐Ÿฅ๐Ÿฅ

Multi-Facility

Horizontal scale-out of API & Sync Engine behind Nginx load balancer. Database connection pooling (PgBouncer).

๐Ÿฅ๐Ÿฅ๐Ÿฅ

Enterprise Scale

PostgreSQL Read Replicas for analytics queries. Dedicated Sync Engine fleet. CDN for static dashboard assets.

๐ŸŒ

Regional / Global

Multi-region deployment. Database geo-replication. Regional API endpoints for latency optimization.

๐Ÿ“– Read Replica Pattern for Analytics

Active Sync Operations
Write-heavy (audit floor)
PostgreSQL Primary
All writes go here
Streaming Replication
Async replication to replica
Read Replica
Dashboard & analytics queries routed here
Benefit

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