A Next-Generation Pharmaceutical Supply Chain & Manufacturing Backend
Built with Spring Boot, PostgreSQL, and Spring AI
- π The Idea: What is PharmaChain?
- ποΈ System Architecture
- ποΈ Database Schema & Data Flow
- π€ AI Copilot Architecture
- β¨ Core Features
- π οΈ Tech Stack
- π Project Structure
- π Getting Started
- π Demo Accounts
- π€ AI Capabilities Example
PharmaChain is a comprehensive software backend designed for the Pharmaceutical Manufacturing Industry.
In the real world, making medicine is highly regulated by organizations like the FDA. You can't just sell medicine if it hasn't passed Quality Control (QC), and you can't say it was manufactured in the future.
PharmaChain handles this entire lifecycle:
- Procurement: Buying raw materials.
- Manufacturing: Dispensing those materials to create finished medicine batches.
- Quality Control: Enforcing strict laboratory tests. If a batch fails QC, it cannot be sold.
- Commerce: Selling the finished goods to distributors and hospitals.
- AI Compliance Copilot: An intelligent AI assistant built right into the app that can answer questions about live database inventory (e.g., "What is our current shortage?") and explain complex compliance rules using real regulatory documents.
We use PostgreSQL Database Triggers to enforce strict FDA-style compliance at the absolute lowest level. The Spring Boot backend acts as a fast, secure, and smart REST API layer on top of this impenetrable database.
PharmaChain follows a robust 3-tier architecture with an embedded AI inference layer, designed for enterprise-grade scalability and strict regulatory compliance.
graph TD
%% Client Tier
subgraph Client_Tier [Client Tier]
ReactUI[React + TypeScript UI<br>Vite / TailwindCSS]
Dashboards[Real-Time Dashboards<br>Inventory/Expiry/Financial]
ReactUI --- Dashboards
end
%% Application Tier
subgraph Application_Tier [Application Tier - Spring Boot 3.3]
Security[Security Layer<br>JWT / @PreAuthorize]
Controllers[REST Controllers<br>17 API Endpoints]
Services[Service Layer<br>Business Logic]
subgraph AICopilot [AI Copilot System]
SpringAI[Spring AI ChatClient]
Groq[Groq LLM API]
Tools["@Tool DB Queries"]
RAG[pgvector RAG Advisor]
SpringAI --> Groq
SpringAI --> Tools
SpringAI --> RAG
end
Security --> Controllers
Controllers --> Services
Controllers --> AICopilot
end
%% Data Tier
subgraph Data_Tier [Data Tier - PostgreSQL 16]
DB[(PostgreSQL Core)]
Triggers[FDA Compliance Triggers]
Views[Real-time Views]
PGVector[(pgvector<br>Compliance Docs)]
DB --- Triggers
DB --- Views
end
%% AI Inference Tier
subgraph AI_Tier [AI Inference Tier]
Ollama[Local Ollama<br>nomic-embed-text]
end
%% Connections
Client_Tier ==>|HTTP / REST + JWT| Application_Tier
Services ==>|JPA / Hibernate| Data_Tier
Tools -.->|JDBC| Views
RAG -.->|Similarity Search| PGVector
RAG <==>|Generate Embeddings| Ollama
classDef ui fill:#61DAFB,stroke:#333,stroke-width:2px,color:#000;
classDef spring fill:#6DB33F,stroke:#333,stroke-width:2px,color:#fff;
classDef db fill:#336791,stroke:#333,stroke-width:2px,color:#fff;
classDef ai fill:#FF9900,stroke:#333,stroke-width:2px,color:#fff;
class ReactUI,Dashboards ui;
class Security,Controllers,Services spring;
class DB,PGVector,Triggers,Views db;
class Groq,Ollama,AICopilot ai;
PharmaChain's database is the core of the system. The real business rules live in PostgreSQL triggers, making them impossible to bypass via the API.
erDiagram
MATERIAL_MASTER ||--o{ MATERIAL_DISPENSING : "dispenses"
MATERIAL_MASTER ||--o{ WAREHOUSE : "stored in"
BATCH_MASTER ||--o{ MATERIAL_DISPENSING : "consumes"
BATCH_MASTER ||--o{ QC_REPORT : "tested by"
BATCH_MASTER ||--o{ FG_TRANSACTIONS : "sold via"
BATCH_MASTER ||--o{ RECALL_LOG : "tracked in"
PRODUCT_MASTER ||--o{ BATCH_MASTER : "produces"
EMPLOYEE_MASTER ||--o{ PRODUCTION_LOG : "operated by"
EQUIPMENT_MASTER ||--o{ PRODUCTION_LOG : "used in"
ACCOUNT_MASTER ||--o{ TRANSACTIONS : "bills to/from"
APP_USER ||--o{ EMPLOYEE_MASTER : "authenticates"
BATCH_MASTER {
string batch_no PK
string product_id FK
date mfg_date
date expiry_date
string qc_status
}
WAREHOUSE {
string lot_number PK
string material_id FK
decimal stock_qty
string status
}
trg_deduct_stock_on_dispense: BEFORE INSERT onMaterial_Dispensing. Atomically subtracts stock; raises an exception if stock goes negative.trg_prevent_sale_without_qc: BEFORE INSERT onFG_Transactions. Raises an exception if batch QC status is not 'PASS'.trg_prevent_future_mfg_date: BEFORE INSERT/UPDATE onBatch_Master. Ensures no future manufacturing dates.trg_set_expiry_date: BEFORE INSERT onBatch_Master. Auto-calculatesExpiry_Datebased on product shelf life.trg_material_qc_auto_update: AFTER INSERT onQC_Report. Updates Warehouse lot status to APPROVED/REJECTED based on material tests.
The AI Copilot uses a dual-pathway RAG + Tool Calling architecture. Every question is handled by exactly the right mechanism:
flowchart TD
User([User Prompt<br>e.g., 'What is our inventory shortage?']) --> ChatClient[Spring AI ChatClient]
subgraph AI_Engine [AI Decision Engine]
ChatClient -->|LLM Reasoning| Groq(Groq API<br>LLaMA/Gemma)
Groq -->|Needs Live Data| ToolCalling{Tool Calling}
Groq -->|Needs Compliance Info| RAG{RAG Pathway}
end
subgraph Live_Data [PostgreSQL Live Data Tools]
ToolCalling -->|"@Tool"| Inv(getInventoryShortage)
ToolCalling -->|"@Tool"| Exp(getExpiryRisk)
ToolCalling -->|"@Tool"| Trace(getBatchTraceability)
Inv --> V_Inv[(v_inventory_shortage view)]
Exp --> V_Exp[(v_expiry_risk view)]
Trace --> V_Trace[(v_batch_traceability view)]
end
subgraph Compliance_RAG [Compliance Document RAG]
RAG --> Embed[Ollama Embeddings]
Embed --> PGV[(pgvector<br>FDA Guidelines PDF Chunks)]
end
subgraph Web_Search [External Information]
ToolCalling -->|"@Tool"| Web(searchMedicineInfo / searchFdaGuidelines)
Web --> Internet((Live Web/FDA.gov))
end
V_Inv --> Synthesis
V_Exp --> Synthesis
V_Trace --> Synthesis
PGV --> Synthesis
Internet --> Synthesis
Synthesis[Groq LLM Context Synthesis] --> Response([Formatted Markdown Response<br>with Tables & Citations])
- π Role-Based Security (JWT): Strict access control. A Warehouse Manager can create batches, but only a QC Analyst can submit lab results.
- π Database-Level FDA Compliance: Triggers ensure you can't sell untested batches, and stock is automatically deducted when manufacturing.
- π€ Spring AI Copilot (RAG + Tools): Ask the system natural questions. It reads live database records (using Tool Calling) and compliance PDFs (using pgvector embeddings) to give you accurate answers.
- π Real-Time Dashboards: Track expiring batches, inventory shortages, and full traceability trees for any batch.
- π¨ Emergency Recalls: A single SQL stored procedure instantly quarantines a batch and tracks the recall reason.
- Backend: Java 21, Spring Boot 3, Spring Data JPA, Spring Security (JWT)
- AI & ML: Spring AI, Groq (LLM), Ollama (Local Embeddings), pgvector
- Database: PostgreSQL 16 (with custom triggers, views, and functions)
- Frontend: React, TypeScript, Vite, Tailwind CSS (located in
/frontend) - Infrastructure: Docker, Docker Compose, GitHub Actions (CI/CD)
π PharmaChain/
βββ π db/ # Database Scripts
β βββ π 01_schema_and_data.sql # Tables, Triggers, Views, and Seed Data
β βββ π 02_security_schema.sql # Login/Auth Tables and Demo Accounts
βββ π frontend/ # React User Interface
β βββ π src/ # React Source Code
β βββ π package.json # Node Dependencies
β βββ π tailwind.config.js # Styling Configuration
βββ π src/ # Spring Boot Backend
β βββ π main/
β βββ π java/com/pharmachain/ # Java Source Code
β β βββ π ai/ # π€ Spring AI Copilot & Tools
β β βββ π controller/ # π REST API Endpoints
β β βββ π entity/ # π¦ Database Models
β β βββ π security/ # π JWT Authentication
β β βββ π service/ # βοΈ Business Logic
β βββ π resources/
β βββ π compliance-docs/ # π FDA PDFs (Vectorized for AI RAG)
β βββ π application.yml # Spring Configuration
βββ π docker-compose.yml # Container Orchestration
βββ π pom.xml # Maven Dependencies
βββ π start_backend.ps1 # Windows Script to Start Backend
βββ π test_ai.ps1 # Windows Script to Test AI Copilot
βββ π README.md # You are here!
- Java 21 & Maven 3.9+
- Docker (to run the database)
- Node.js (to run the frontend)
- A Groq API Key (for the AI to work)
Use Docker Compose to spin up the PostgreSQL database (which includes the pgvector extension for our AI).
docker compose up -dLoad the schema and seed data:
psql -h localhost -U postgres -d pharmachain -f db/01_schema_and_data.sql
psql -h localhost -U postgres -d pharmachain -f db/02_security_schema.sqlSet your AI API Key and start Spring Boot:
export GROQ_API_KEY="your_api_key_here"
mvn spring-boot:run(Windows users can simply run .\start_backend.ps1)
The backend API will run on http://localhost:8081.
In a new terminal window, navigate to the frontend folder and start the React app:
cd frontend
npm install
npm run devYour user interface is now live at http://localhost:5173!
Use these accounts to log into the system and explore different roles:
| Username | Password | Role | Description |
|---|---|---|---|
admin |
Admin@123 |
ADMIN | Can do everything. |
qc.analyst |
Qc@12345 |
QC_ANALYST | Submits lab results and handles recalls. |
wh.manager |
Wh@12345 |
WAREHOUSE_MANAGER | Manages inventory and dispenses materials. |
sales.rep |
Sales@123 |
SALES | Records sales to hospitals and distributors. |
auditor |
Audit@123 |
AUDITOR | Strictly Read-Only access. |
Once logged in, try asking the AI Copilot:
"What is our current inventory shortage for raw materials?"
How it works:
- The AI understands your question.
- It decides it needs real data, so it executes the
getInventoryShortageJava Tool. - The Tool queries the live PostgreSQL View
v_inventory_shortage. - The AI formats the result into a beautiful, human-readable table.