// Developer Hub

Technical Flows · Architecture · Sprint Worksheets · Task Assignments · Platform Documentation

React Native Node.js / TS PostgreSQL WatermelonDB Docker AWS ECS Nginx BullMQ
🏃 Sprint
01

Authentication & Token Flow

OAuth 2.0 · JWT (15m) · Refresh (7d) · Mobile biometrics

🔑 OAuth 2.0 + JWT Pipeline

Client Request
Web / RN App
SSO?
IdP (Entra/Okta)
Auth Code Grant
Issue Tokens
JWT 15m + Refresh 7d
HTTP-only cookie
Session Active
Bearer token on requests
JWT Expired

POST /auth/refresh → rotate both tokens → retry original request

Refresh Expired

Force re-auth → full OAuth handshake → new token pair

📱 Mobile Biometric Unlock

App Foreground
Keychain/Keystore check
Session?
FaceID / PIN
react-native-biometrics
Decrypt DB
WatermelonDB unlocked
02

RBAC Middleware

JWT claims extraction · role check · route policy enforcement

Request Authorization Pipeline

req.headers.auth
Bearer <jwt>
jwt.verify()
Extract {role, perms[]}
rbacGuard()
Check route.requiredRole
OK?
next()
200 → handler
403 Forbidden

Log attempt → audit_log table → rate-limit alert if 5+ fails in 10m

03

Phase 1: HIS Ingestion Pipeline

Upload → S3 → SQS/BullMQ → Worker → PostgreSQL batch insert

📤 Async Ingestion Flow

1

POST /api/audit/{id}/upload

Multer middleware → validate file type (csv/xlsx) → stream to S3 multipart → return 202 Accepted

2

Publish to Queue Async

SQS.sendMessage({ s3Key, auditSessionId, uploadedBy }) — or BullMQ.add('ingest', payload)

3

Ingestion Worker Process

S3.getObject() → createReadStream() → csv-parser/exceljs → sanitize rows → validate batchId format → normalize dates to ISO 8601

4

Batch INSERT with COPY

pg COPY protocol for 50K+ rows → link to audit_session_id → raw lines in JSONB column → status = READY

04

Phase 2: Mobile Execution

WatermelonDB pull → offline scan → UUID v4 idempotency → pending_sync queue

📱 Offline Scan Flow

1

Pull Catalog Online

GET /sync/pull?last_pulled_at={ts} → Sync Engine returns delta → WatermelonDB.database.sync()

2

Scan Barcode Offline

react-native-camera / Bluetooth HID → lookup localDB.get('items', barcode) → display item → prompt qty

3

Additive Duplicate Handling

Same barcode scanned? → scan_records.update(r => r.qty += newQty) — never overwrite. Prevents data loss.

4

Local Persist

scan_records.create({ id: uuidv4(), barcode, qty, zone_id, session_id, status: 'pending_sync', ts })

5

Bulk Push Online

NetInfo.addEventListener → POST /sync/push { changes: [...] } — exponential backoff (1s→2s→4s→8s)

05

Phase 3: Sync Engine & Variance

Additive merge · UUID dedup · Δ = expected − physical

🔄 Additive Merge & Dedup

Device A push
50× paracetamol
Sync Engine
ON CONFLICT(uuid) DO NOTHING
SUM(qty)
GROUP BY batch_id, session_id
total = 80
physical_counts table

📊 Variance Engine (Close Audit)

PATCH /audit/{id}/close
Lock session
SELECT e.qty - p.qty AS delta
JOIN expected ON batch
Δ ?
Δ=0 MATCH

status='verified'

Δ>0 SHORTAGE

Flag by threshold tier

Δ<0 OVERAGE

Possible HIS error

EXPIRED

expiry_date < NOW()

06

Phase 4: Reports & Export

Aggregate → financial calc → dashboard → CSV export → HIS feedback

📈 Report Pipeline

shortages[]
missing_qty per batch
× unit_cost
FROM his_items
Σ leakage
SUM(delta * cost)
GET /reports/{id}
JSON + CSV export
07

System Architecture

4-tier: Edge → Gateway → App → Data

🏗️ Architecture Tiers

Edge — React Native
RN AppiOS + Android
WatermelonDBSQLite + sync primitives
Sync ManagerNetInfo + backoff queue
Gateway — Nginx
NginxSSL term · rate limit · routing · WS
App — Docker (ECS)
Core APIExpress/TS — auth, CRUD
Sync EnginePush/Pull + merge
Ingestion WorkerCSV stream parser
Data
PostgreSQL (RDS)ACID · JSONB · replicas
S3Raw file archive
SQS/BullMQJob queue
08

Security Layers

Defense-in-depth · append-only ledger · KMS encryption

🛡️ Defense in Depth

Network — TLS 1.3 · Rate Limit

Nginx enforces HTTPS only · brute-force detection

Auth — OAuth 2.0 · RBAC

Short JWT · rotating refresh · middleware on every route

Storage — KMS · Keychain

EBS/RDS encrypted · mobile Keychain/Keystore · S3 SSE

Audit — Append-Only Ledger

No UPDATE/DELETE on scan_records · soft-delete + version column · full history

09

API Endpoint Reference

Key REST endpoints for the PharmaAudit platform

MethodEndpointDescriptionAuth
POST/auth/loginOAuth login initiationPublic
POST/auth/refreshRotate JWT + refresh tokenCookie
POST/api/auditCreate audit sessionAdmin
POST/api/audit/{id}/uploadUpload HIS file (CSV/Excel)Admin
PATCH/api/audit/{id}/closeLock session + run varianceAdmin
GET/sync/pullPull catalog delta for mobileJWT
POST/sync/pushPush scan records from mobileJWT
GET/api/reports/{id}Fetch report (JSON + CSV)JWT

📋 Sprint Planning Board

4 Sprints · 8 Weeks · Sprint Methodology

Sprint
Owner
Priority
Status
42 / 42 tasks
😕 No tasks match your filters. Try adjusting or resetting.
Progress

Sprint Progress Overview

Sprint 1
0%
Sprint 2
0%
Sprint 3
0%
Sprint 4
0%

🏃 Sprint 1 — Foundation & Auth (2 weeks)

Week 1–2 · Project Scaffold + IAM
IDTaskOwnerPriorityStatusNotes
S1-01Initialize RN project + monorepo structureDev 1CriticalTo DoNx or Turborepo, shared types package
S1-02Setup Express/TS API boilerplateDev 1CriticalTo DoESLint, Prettier, Jest, Docker compose
S1-03PostgreSQL schema v1 + migrationsDev 1CriticalTo Dousers, roles, audit_sessions, zones, items
S1-04OAuth 2.0 login flow + JWT issuanceDev 1CriticalTo Dopassport.js or custom, refresh rotation
S1-05RBAC middleware + route guardsDev 1HighTo Dorole-based decorators for routes
S1-06Web login UI + SSO redirect flowDev 2HighTo DoReact + react-router, token storage
S1-07Mobile login UI + biometric unlockDev 2HighTo Doreact-native-biometrics, Keychain
S1-08Docker Compose for local dev envDev 1MediumTo DoAPI + PG + Redis containers
S1-09CI pipeline (GitHub Actions)Dev 1MediumTo DoLint → Test → Build → Docker push

🏃 Sprint 2 — Ingestion & Dashboard (2 weeks)

Week 3–4 · HIS Upload + Admin UI + Zones
IDTaskOwnerPriorityStatusNotes
S2-01S3 upload endpoint (Multer → S3)Dev 1CriticalTo DoMultipart stream, return 202
S2-02BullMQ setup + IngestFile jobDev 1CriticalTo DoQueue config, retry policy, DLQ
S2-03Ingestion worker — CSV/Excel parseDev 1CriticalTo Docsv-parser + exceljs, stream from S3
S2-04Batch INSERT with pg COPYDev 1HighTo Do50K+ rows performance
S2-05Audit session CRUD APIDev 1HighTo DoState machine: DRAFT→READY→ACTIVE→CLOSED
S2-06Zone CRUD APIDev 1MediumTo DoFacility → Zone hierarchy
S2-07Dashboard — Audit session manager UIDev 2HighTo DoList, create, config, publish button
S2-08Dashboard — File upload + progress UIDev 2HighTo DoDrag-drop, progress bar, validation
S2-09Dashboard — Zone management UIDev 2MediumTo DoCRUD form + zone tree view
S2-10Dashboard — User admin pageDev 2MediumTo DoCreate user, assign role, deactivate
S2-11Variance threshold config API + UIDev 1MediumTo DoRules engine: minor/standard/critical

🏃 Sprint 3 — Mobile Scan & Sync (2 weeks)

Week 5–6 · Offline Scan + WatermelonDB Sync Protocol
IDTaskOwnerPriorityStatusNotes
S3-01WatermelonDB schema + modelsDev 1CriticalTo Doitems, scan_records, zones, sessions
S3-02Sync Engine — pull endpointDev 1CriticalTo DoGET /sync/pull?last_pulled_at= → delta
S3-03Sync Engine — push endpointDev 1CriticalTo DoPOST /sync/push + UUID dedup + additive merge
S3-04Mobile — catalog pull + offline storeDev 1CriticalTo Dodatabase.sync() integration
S3-05Mobile — barcode scanner UIDev 2CriticalTo DoCamera scanner + BT HID support
S3-06Mobile — scan record creation + additive logicDev 1HighTo Douuidv4(), pending_sync status, qty increment
S3-07Mobile — zone selector UIDev 2HighTo DoPicker from local DB zones
S3-08Mobile — auto-push Sync ManagerDev 1HighTo DoNetInfo listener + exponential backoff
S3-09Contract tests: Mobile ↔ Sync EngineDev 1HighTo DoPact or snapshot-based
S3-10Sync concurrency load testDev 1MediumTo DoSimulate 20+ devices pushing at once

🏃 Sprint 4 — Reporting, Polish & Deploy (2 weeks)

Week 7–8 · Variance Engine + Reports + Infrastructure
IDTaskOwnerPriorityStatusNotes
S4-01Variance calculation engine (close audit)Dev 1CriticalTo DoSQL: expected - SUM(physical) → delta per batch
S4-02Financial leakage aggregationDev 1CriticalTo DoSUM(delta * unit_cost) by category/zone
S4-03Report API endpointsDev 1HighTo DoGET /reports/{id} → JSON + CSV download
S4-04CSV/Excel export serviceDev 1HighTo Doexceljs streaming write → S3 or direct
S4-05Dashboard — Reports UI + chartsDev 2CriticalTo DoRecharts: bar, pie, trend line. Export btn
S4-06Dashboard — Executive summary viewDev 2HighTo DoRead-only KPI cards, financial impact
S4-07Dashboard — Variance drilldown tableDev 2HighTo DoFilter by zone, status, severity
S4-08Nginx config + SSL + rate limitingDev 1HighTo DoProduction nginx.conf, certbot
S4-09AWS ECS deployment (Terraform/CDK)Dev 1HighTo DoECS tasks, RDS, S3, SQS provisioning
S4-10E2E testing — full audit cycleDev 1CriticalTo DoUpload → scan → sync → close → report
S4-11Append-only ledger / soft-delete implDev 1MediumTo DoVersion column + updated_at trigger
S4-12Mobile — scan history UI + sync statusDev 2MediumTo DoList of scans with pending/synced badge
Dependencies

Cross-Team Dependency Chain

Tasks that block other work — coordinate handoffs.

🔗 Critical Path Dependencies

Sprint 1 → Sprint 2

S1-04 Auth + JWT
S1-06 Web Login UI
S1-07 Mobile Login
S1-02 API Boilerplate
S1-03 DB Schema v1
S2-05 Audit CRUD

Sprint 2 → Sprint 3

S2-01 S3 Upload
S2-03 CSV Worker
S3-02 Sync Pull
S3-04 Mobile Pull
S2-06 Zone API
S3-07 Zone Selector

Sprint 3 → Sprint 4

S3-03 Sync Push
S4-01 Variance Engine
S4-02 Leakage Calc
S4-05 Reports UI

📊 Task Distribution Summary

DeveloperSprint 1Sprint 2Sprint 3Sprint 4Total
Dev 1 (BE + Basic FE)7 tasks7 tasks8 tasks8 tasks30 tasks
Dev 2 (UI/UX FE)2 tasks4 tasks2 tasks4 tasks12 tasks
Senior (Oversight)Reviews only

👥 Team & Modules

Team Structure · Module Ownership · Roles & Responsibilities

Team

Development Team (3 Engineers)

👨‍💻

Developer 1

Complete Backend & Basic Frontend
⏰ Full-Time
Node.js Express/TS PostgreSQL TypeScript React Native WatermelonDB BullMQ Docker OAuth/JWT AWS/Nginx CI/CD
🎨

Developer 2

All UI/UX Frontend
⏰ Full-Time
React Native React.js Tailwind CSS Figma TypeScript Recharts UX Research Component Library
🧠

Senior Developer

Oversight Only — Reviews & Guidance
⏳ Part-Time · Multi-Project
Architecture Code Review PR Approvals Technical Guidance Blocker Resolution Sprint Planning
Methodology

Sprint Methodology

Sprint timeboxes for planning · Daily standups · PR reviews by Senior

🏃 Sprint Structure

  • 2-week sprint cycles
  • Sprint planning at start
  • Sprint review + retro at end
  • Tasks scoped to sprint backlog
  • Senior reviews all PRs

📋 Workflow Rules

  • Daily standups (15 min)
  • Max 3 tasks in progress per dev
  • Critical tasks prioritized first
  • Blockers escalated to Senior
  • Continuous delivery flow
Modules

Module Ownership Map

Each module has a primary owner. Senior Dev reviews all PRs.

📱 Mobile App (React Native)

Owner: Dev 1 · UI: Dev 2 · Review: Senior
  • Barcode scanner integration
  • WatermelonDB schema & models
  • Offline scan logic + sync
  • Local encryption hooks
  • Push notification handler

🖥️ Web Dashboard (React)

Owner: Dev 2 · API: Dev 1 · Review: Senior
  • Login / SSO UI flow
  • Audit session management pages
  • HIS file upload component
  • Reports & charts (Recharts)
  • User management admin pages

🔌 Core Audit API

Owner: Dev 1 · Review: Senior
  • Express routes + controllers
  • PostgreSQL schemas & migrations
  • File upload endpoint (Multer→S3)
  • Audit session state machine
  • Report generation queries

📥 Ingestion Worker

Owner: Dev 1 · Review: Senior
  • BullMQ job consumer
  • CSV/Excel stream parser
  • Data sanitization pipeline
  • Batch INSERT via pg COPY
  • Error handling + dead-letter queue

🔄 Sync Engine

Owner: Dev 1 · Review: Senior
  • WatermelonDB push/pull protocol
  • Additive merge resolver
  • UUID deduplication logic
  • Sync conflict audit logging
  • Mobile ↔ Server contract tests

🔐 Auth & IAM Module

Owner: Dev 1 · UI: Dev 2 · Review: Senior
  • OAuth 2.0 + SSO integration
  • JWT issuance + refresh rotation
  • RBAC middleware
  • Mobile biometric flow
  • Keychain/Keystore encryption

📖 Platform Documentation

RBAC Permissions · Page Field Specs · Mobile Modules · Web Modules · Database Schema

Roles

Role Definitions

5 platform roles with hierarchical access levels

⚡ Super Admin

Highest privilege. Configures environment variables, API keys, models, feature flags, infrastructure settings. Full system + DevOps access.

🛡️ Admin

Full system control. Manages pharmacies, users, audit sessions, configuration. Can access everything except infrastructure.

📊 Manager

Pharmacy-level management. Creates audits, manages zones, reviews reports. Cannot manage users or system settings.

📱 Auditor

Field operator. Scans barcodes, enters quantities, syncs data. Read-only on reports. No admin access.

👁️ Executive

Read-only oversight. Views dashboards, reports, financial summaries. Cannot modify any data.

RBAC

Permission Matrix — CRUD Access

Create · Read · Update · Delete permissions per role per resource

✓ Full Full access
◉ Read Read only
⊘ Own Own records only
No access
Resource / Action ⚡ Super Admin 🛡️ Admin 📊 Manager 📱 Auditor 👁️ Executive
CRUD CRUD CRUD CRUD CRUD
🏥 Pharmacies / Facilities
📍 Zones
👤 Users
📝 Audit Sessions
📤 HIS File Upload
📦 HIS Items / Catalog
🔍 Scan Records
📊 Variance Data
📈 Reports
📥 Export (CSV/Excel/PDF)
📊 Dashboard (KPIs)
⚙️ System Settings
🎚️ Variance Thresholds
📜 Audit Trail / Logs
🔔 Notifications
🔄 Sync Management
🔑 Environment Variables / Secrets
🧠 Model / AI Configuration
🏗️ Infrastructure / Deployment
🚩 Feature Flags / Toggles
💾 Backup & Restore
🔒 API Keys & Rate Limits
Access

Feature Access by Role

Which screens and features each role can access

Feature / Screen ⚡ Super Admin 🛡️ Admin 📊 Manager 📱 Auditor 👁️ Executive
Web Dashboard Login
Mobile App Login
Admin Dashboard
Manager Dashboard
Executive Dashboard
Pharmacy Management
Zone Management
User Management
Audit Session Manager
HIS File Upload
Barcode Scanner (Mobile)
Manual Scan Entry (Mobile)
Scan History
Sync Status
Variance Analysis
Reports & Analytics
Export Center
Settings & Configuration
Audit Trail / Activity Log
Notification Settings
Expiry Alert Management
🔧 Environment Variables Config
🤖 Model Configuration (AI/ML)
🚀 Feature Flags / Toggles
🏢 Tenant / Organization Mgmt
📡 Infrastructure Monitoring
Fields

Page & Screen Field Specifications

Every field on every page — type, validation, required status

Required field
Optional field

🔐 Login Page (Web & Mobile)

emailstring · email format
passwordstring · min 8 chars
remember_meboolean · checkbox
sso_providerenum · google | azure
biometric_tokenstring · mobile only
device_idstring · auto-captured

🏥 Pharmacy / Facility Management

pharmacy_namestring · max 200 chars
license_numberstring · unique
pharmacy_typeenum · hospital | retail | warehouse
address_line_1string · max 500
address_line_2string · max 500
citystring · max 100
statestring · max 100
pin_codestring · 6 digits
contact_personstring · full name
contact_phonestring · E.164 format
contact_emailstring · email format
statusenum · active | inactive | suspended
gst_numberstring · 15 chars GSTIN
drug_license_nostring · DL number
notestext · max 1000

📍 Zone Management

zone_namestring · max 100
zone_codestring · unique per pharmacy
pharmacy_idFK → pharmacies.id
floor_buildingstring · location within facility
descriptiontext · max 500
statusenum · active | inactive
sort_orderinteger · display order

👤 User Management

full_namestring · max 200
emailstring · unique · email format
phonestring · E.164 · unique
roleenum · super_admin | admin | manager | auditor | executive
assigned_pharmacies[]FK[] → pharmacies.id
statusenum · active | inactive | locked
employee_idstring · org employee code
departmentstring · max 100
profile_imagefile · jpg/png · max 2MB
last_login_attimestamp · auto · read-only

📝 Audit Session

session_idUUID · auto-generated
session_namestring · max 200
pharmacy_idFK → pharmacies.id
audit_typeenum · full | partial | expiry_only
start_datedate · ISO 8601
end_datedate · must be ≥ start_date
statusenum · DRAFT | READY | ACTIVE | CLOSED | APPROVED
created_byFK → users.id · auto
zones[]FK[] → zones.id · selected zones
assigned_auditors[]FK[] → users.id
variance_threshold_idFK → variance_thresholds.id
notestext · max 2000
closed_attimestamp · auto on close
approved_byFK → users.id · on approval

📤 HIS File Upload

filefile · .csv / .xlsx / .xls
audit_session_idFK → audit_sessions.id
pharmacy_idFK → pharmacies.id
file_typeenum · csv | xlsx | xls
uploaded_byFK → users.id · auto
upload_datetimestamp · auto
file_size_bytesinteger · auto-calculated
row_countinteger · after processing
processing_statusenum · queued | processing | done | failed
error_logJSONB · parsing errors array
s3_keystring · S3 object key

💊 HIS Item / Medication Master (Imported from HIS)

product_namestring · medication name
barcode_idstring · EAN-13 / Code-128
batch_numberstring · manufacturer batch
grn_numberstring · Goods Receipt Note #
expiry_datedate · ISO 8601
mfg_datedate · manufacture date
categorystring · drug category
sub_categorystring · sub-classification
unit_costdecimal(10,2) · per unit price
mrpdecimal(10,2) · max retail price
pack_sizeinteger · units per pack
uomstring · unit of measure (strip/bottle/vial)
manufacturerstring · company name
supplierstring · distributor name
expected_qtyinteger · HIS expected count
zone_idFK → zones.id · storage location
shelf_locationstring · rack/shelf identifier
schedule_typeenum · H | H1 | X | G · drug schedule
is_narcoticboolean · controlled substance flag
hsn_codestring · tax classification

🔍 Scan Record (Mobile Capture)

scan_idUUID v4 · client-generated
barcodestring · scanned barcode value
product_namestring · auto-lookup from catalog
batch_numberstring · matched from catalog
quantity_scannedinteger · physical count entered
zone_idFK → zones.id · selected zone
session_idFK → audit_sessions.id
auditor_idFK → users.id · auto
scanned_attimestamp · device local time
sync_statusenum · pending_sync | synced | conflict
device_idstring · device identifier
scan_methodenum · camera | bluetooth_hid | manual
gps_latdecimal · latitude (optional)
gps_lngdecimal · longitude (optional)
notestext · auditor remarks
photo_urlstring · evidence photo S3 key

📊 Variance Record (Computed on Audit Close)

variance_idUUID · auto-generated
session_idFK → audit_sessions.id
item_namestring · product name
barcodestring · item barcode
batch_numberstring · batch ref
expected_qtyinteger · from HIS
physical_qtyinteger · SUM(scanned)
variance_deltainteger · expected − physical
variance_pctdecimal · (Δ / expected) × 100
variance_statusenum · match | shortage | overage | expired
severityenum · minor | standard | critical
unit_costdecimal · from HIS item
financial_impactdecimal · Δ × unit_cost
zone_idFK → zones.id
categorystring · drug category

📈 Report Record

report_idUUID · auto-generated
report_typeenum · variance | financial | expiry | summary
session_idFK → audit_sessions.id
pharmacy_idFK → pharmacies.id
generated_byFK → users.id · auto
generated_attimestamp · auto
report_dataJSONB · aggregated data
export_urlstring · S3 download link
export_formatenum · json | csv | xlsx | pdf

⚙️ System Configuration

threshold_minordecimal · % (default: 2%)
threshold_standarddecimal · % (default: 5%)
threshold_criticaldecimal · % (default: 10%)
sync_frequency_secinteger · auto-push interval
session_timeout_mininteger · JWT expiry mins
max_upload_size_mbinteger · HIS file limit
enable_gps_trackingboolean · mobile location
enable_photo_evidenceboolean · scan photo capture
notification_channelsenum[] · email | sms | push
audit_trail_retention_daysinteger · log retention period
Mobile

📱 Mobile Application Modules

React Native · iOS + Android · WatermelonDB · Offline-First

🔐 Login & Authentication

Email/password login, SSO redirect, biometric unlock (Face ID / Fingerprint), secure token storage in Keychain/Keystore.

Email Login SSO / OAuth Biometric Unlock Keychain Storage Auto-Logout PIN Fallback
Manager Auditor

📊 Dashboard (My Assignments)

Overview of assigned audit sessions, pending scans count, sync status indicator, quick-action cards for active audits.

Active Audits Pending Scans Sync Status Quick Actions Last Sync Time
Manager Auditor

📋 Audit Session List

Browse assigned audit sessions with status badges (DRAFT, READY, ACTIVE, CLOSED). Tap to enter scanning mode for active sessions.

Session Cards Status Badges Pharmacy Info Zone Count Progress % Date Range
Manager Auditor

📍 Zone Selector

Pick the zone you're auditing from the local DB list. Zones are synced from server. Each scan is tagged to the selected zone.

Zone Picker Zone Details Scan Count/Zone Floor/Building Search/Filter
Auditor

📷 Barcode Scanner

Camera-based barcode scanning (EAN-13, Code-128, QR) with Bluetooth HID scanner support. Auto-lookup from local catalog, quantity prompt, additive duplicate handling.

Camera Scan BT HID Support Auto-Lookup Qty Prompt Additive Merge Flash Toggle Vibration Feedback Sound Alert
Auditor

✏️ Manual Entry Form

Manually enter barcode/product when scanner fails. Search catalog by name, select batch, enter quantity. Same additive logic applies.

Barcode Input Product Search Batch Selector Qty Input Notes Field Photo Attach
Auditor

📜 Scan History

View all scans for the current session. Shows product, qty, zone, timestamp, sync status badge (pending/synced/conflict). Swipe to edit qty.

Scan List Sync Badges Edit Quantity Filter by Zone Search Total Counter
Manager Auditor

🔄 Sync Manager

Background sync engine with NetInfo listener. Auto-push when online, exponential backoff on failure. Shows queue depth and last sync timestamp.

Auto-Push Queue Depth Retry Logic Conflict View Manual Sync Last Sync Time Network Status
Auditor

📴 Offline Mode

Full offline capability. All scanning works without internet. Data stored in WatermelonDB (SQLite). Visual indicator shows offline status. Queues all changes for sync.

Offline Scan Local Catalog Pending Queue Status Banner Auto-Resume
Auditor

⚠️ Expiry Alerts

Highlights items nearing expiry during scan. Color-coded warnings: red (expired), amber (≤30 days), yellow (≤90 days). Push notifications for tracked items.

Expiry Highlight Color Warnings Push Alerts Expiry List Sort by Date
Manager Auditor

👤 Profile & Settings

View profile, change password, manage biometric preferences, set notification preferences, view app version, clear local cache.

Profile View Change Password Biometric Toggle Notifications Cache Clear App Version Logout
Manager Auditor

🔔 Push Notifications

Receive real-time alerts for new audit assignments, sync failures, expiry warnings, and session status changes. Badge count on app icon.

Assignment Alerts Sync Failures Expiry Warnings Status Changes Badge Count
Manager Auditor
Web

🖥️ Web Application Modules

React.js · Tailwind CSS · Recharts · Role-Based Views

🔐 Login / SSO

Web login page with email/password, Google SSO, Azure AD integration. Redirect-based OAuth flow with PKCE. Session persistence with httpOnly cookies.

Email Login Google SSO Azure AD PKCE Flow Remember Me Password Reset
Super Admin Admin Manager Executive

🛡️ Admin Dashboard

System-wide overview: total pharmacies, active audits, user counts, recent activity feed, system health indicators, quick-action buttons.

KPI Cards Activity Feed System Health Quick Actions User Online Count Sync Queue Depth
Super Admin Admin

📊 Manager Dashboard

Pharmacy-scoped view: assigned pharmacy KPIs, active audit progress, zone completion rates, pending reviews, auditor performance metrics.

Pharmacy KPIs Audit Progress Zone Heatmap Auditor Stats Pending Reviews Expiry Alerts
Super Admin Manager

👁️ Executive Dashboard

Read-only high-level view: financial impact summaries, cross-pharmacy comparisons, trend charts, leakage aggregation, compliance scores.

Financial Summary Trend Charts Pharmacy Compare Leakage Totals Compliance Score Export PDF
Super Admin Executive

🏥 Pharmacy Management

CRUD interface for pharmacies/facilities. Add, edit, deactivate pharmacies. View pharmacy details, zones, assigned users, audit history.

Create Pharmacy Edit Details Deactivate View Zones Assigned Users Audit History License Upload
Super Admin Admin

📍 Zone Management

Create and manage zones within pharmacies. Tree-view hierarchy, zone codes, floor/building assignment, status toggle, sort ordering.

Create Zone Edit Zone Delete Zone Tree View Drag Reorder Bulk Import
Super Admin Admin Manager

👤 User Management

Create, edit, deactivate users. Assign roles (Super Admin/Admin/Manager/Auditor/Executive), map to pharmacies, reset passwords, view login history.

Create User Assign Role Map Pharmacies Reset Password Deactivate Login History Bulk Import CSV
Super Admin Admin

📝 Audit Session Manager

Full lifecycle management: create session, configure zones, upload HIS file, publish to auditors, monitor progress, close audit, approve results.

Create Session Zone Config HIS Upload Publish Monitor Progress Close Audit Approve State Machine
Super Admin Admin Manager

📤 HIS File Upload

Drag-and-drop file upload with validation. Supports CSV/XLSX. Real-time progress bar, row count preview, error log display, re-upload capability.

Drag & Drop CSV/XLSX Progress Bar Validation Error Log Row Preview Re-Upload
Super Admin Admin Manager

📡 Audit Monitoring (Live)

Real-time view of active audit progress. Zone completion percentages, auditor activity feed, scan rate charts, WebSocket-powered live updates.

Live Progress Zone Completion Activity Feed Scan Rate Chart WebSocket Auditor Locations
Super Admin Admin Manager

📊 Variance Analysis

Detailed variance drilldown after audit close. Filter by zone, category, severity. Sortable table with shortage/overage/expired highlighting.

Variance Table Zone Filter Category Filter Severity Filter Sort Columns Financial Impact Export
Super Admin Admin Manager Executive

📈 Reports & Analytics

Interactive charts and reports. Bar charts for variance by zone, pie charts for category breakdown, trend lines for audit-over-audit comparison.

Bar Charts Pie Charts Trend Lines Date Range Pharmacy Compare Recharts Tabular View
Super Admin Admin Manager Executive

📥 Export Center

Download reports in multiple formats. Generate CSV, Excel (styled), PDF with letterhead. Scheduled report emails. Bulk export across audits.

CSV Export Excel Export PDF Export Scheduled Email Bulk Download Template Select
Super Admin Admin Manager Executive

⚙️ Settings & Configuration

System-wide settings: variance thresholds, notification channels, sync intervals, upload limits, GPS/photo toggles, audit trail retention.

Thresholds Notifications Sync Config Upload Limits Feature Toggles Retention Policy
Super Admin Admin

📜 Audit Trail / Activity Log

Immutable activity log showing all user actions, data changes, login events. Filterable by user, action type, date range. Append-only — no deletions.

Action Log User Filter Date Filter Action Types IP Address Append Only Export Log
Super Admin Admin

🔔 Notification Center

In-app notification panel. Real-time alerts for audit events, file processing status, sync errors, expiry warnings. Mark read/unread, notification preferences.

In-App Alerts Email Digest Read/Unread Preferences Event Types Clear All
Super Admin Admin Manager Executive

🔧 Environment Variables

Manage all environment configurations: API keys, database URLs, third-party service credentials, runtime parameters. Masked values with reveal toggle. Change history tracking.

Key-Value Editor Masked Values Change History Import/Export Env Profiles Validation
Super Admin

🤖 Model Configuration (AI/ML)

Configure AI/ML model endpoints, parameters, and thresholds. Manage model versions, A/B testing configs, inference settings, token budgets, and fallback strategies.

Model Endpoints Version Control A/B Testing Parameters Token Budgets Fallback Config
Super Admin

🚀 Feature Flags / Toggles

Enable/disable features per tenant, role, or environment. Gradual rollouts with percentage controls, scheduled activations, kill switches for emergencies.

Toggle Controls Per-Tenant Gradual Rollout Scheduled Kill Switch Audit Log
Super Admin

🏢 Tenant / Organization Mgmt

Multi-tenant administration: create/manage organizations, configure tenant-specific settings, data isolation policies, billing tiers, storage quotas, and admin user provisioning.

Create Tenant Billing Tiers Storage Quotas Data Isolation Provision Admin Usage Analytics
Super Admin
Schema

🗄️ PostgreSQL Database Schema

Core tables · Column types · Primary & Foreign keys · Constraints

PK Primary Key
FK Foreign Key
TYPE Data Type

👤 users

PK id UUID
full_name VARCHAR(200)
email VARCHAR(255) UNIQUE
phone VARCHAR(20) UNIQUE
password_hash VARCHAR(255)
role ENUM(super_admin,admin,manager,auditor,executive)
status ENUM(active,inactive,locked)
last_login_at TIMESTAMPTZ
created_at TIMESTAMPTZ DEFAULT NOW()
updated_at TIMESTAMPTZ

🏥 pharmacies

PK id UUID
name VARCHAR(200)
license_number VARCHAR(100) UNIQUE
pharmacy_type ENUM(hospital,retail,warehouse)
address JSONB
contact_person VARCHAR(200)
contact_phone VARCHAR(20)
contact_email VARCHAR(255)
status ENUM(active,inactive,suspended)
created_at TIMESTAMPTZ DEFAULT NOW()

📍 zones

PK id UUID
FK pharmacy_id UUID → pharmacies.id
zone_name VARCHAR(100)
zone_code VARCHAR(20) UNIQUE/pharmacy
floor_building VARCHAR(100)
status ENUM(active,inactive)
sort_order INTEGER DEFAULT 0

📝 audit_sessions

PK id UUID
FK pharmacy_id UUID → pharmacies.id
session_name VARCHAR(200)
audit_type ENUM(full,partial,expiry_only)
start_date DATE
end_date DATE
status ENUM(DRAFT,READY,ACTIVE,CLOSED,APPROVED)
FK created_by UUID → users.id
closed_at TIMESTAMPTZ
FK approved_by UUID → users.id
notes TEXT
created_at TIMESTAMPTZ DEFAULT NOW()

💊 his_items (Imported Medication Catalog)

PK id UUID
FK session_id UUID → audit_sessions.id
product_name VARCHAR(300)
barcode_id VARCHAR(50) INDEX
batch_number VARCHAR(100)
grn_number VARCHAR(100)
expiry_date DATE INDEX
mfg_date DATE
category VARCHAR(100)
unit_cost DECIMAL(10,2)
expected_qty INTEGER
pack_size INTEGER
uom VARCHAR(20)
manufacturer VARCHAR(200)
raw_row JSONB

🔍 scan_records (Append-Only — NO UPDATE/DELETE)

PK id UUID (client-generated)
FK session_id UUID → audit_sessions.id
FK zone_id UUID → zones.id
FK auditor_id UUID → users.id
barcode VARCHAR(50) INDEX
batch_number VARCHAR(100)
quantity INTEGER NOT NULL
scan_method ENUM(camera,bluetooth_hid,manual)
device_id VARCHAR(100)
scanned_at TIMESTAMPTZ
synced_at TIMESTAMPTZ
version INTEGER DEFAULT 1

📊 variance_results

PK id UUID
FK session_id UUID → audit_sessions.id
FK his_item_id UUID → his_items.id
expected_qty INTEGER
physical_qty INTEGER
variance_delta INTEGER
variance_pct DECIMAL(5,2)
status ENUM(match,shortage,overage,expired)
severity ENUM(minor,standard,critical)
financial_impact DECIMAL(12,2)
computed_at TIMESTAMPTZ DEFAULT NOW()

📜 audit_log (Immutable Ledger)

PK id BIGSERIAL
FK user_id UUID → users.id
action VARCHAR(50)
resource_type VARCHAR(50)
resource_id UUID
changes JSONB
ip_address INET
user_agent TEXT
created_at TIMESTAMPTZ DEFAULT NOW()

PharmaAudit — Developer Hub · Technical Flows & Sprint Worksheets

April 2026 · 4 Sprints · 3 Engineers · 42 Tasks