Skip to content

Repository files navigation

πŸ’Š PharmaChain

A Next-Generation Pharmaceutical Supply Chain & Manufacturing Backend

Java 21 Spring Boot 3 Spring AI PostgreSQL 16 pgvector React Docker CI/CD

Built with Spring Boot, PostgreSQL, and Spring AI


πŸ“‹ Table of Contents


🌟 The Idea: What is PharmaChain?

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:

  1. Procurement: Buying raw materials.
  2. Manufacturing: Dispensing those materials to create finished medicine batches.
  3. Quality Control: Enforcing strict laboratory tests. If a batch fails QC, it cannot be sold.
  4. Commerce: Selling the finished goods to distributors and hospitals.
  5. 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.


πŸ—οΈ System Architecture

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;
Loading

πŸ—„οΈ Database Schema & Data Flow

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
    }
Loading

πŸ›‘ FDA Compliance Database Triggers

  1. trg_deduct_stock_on_dispense: BEFORE INSERT on Material_Dispensing. Atomically subtracts stock; raises an exception if stock goes negative.
  2. trg_prevent_sale_without_qc: BEFORE INSERT on FG_Transactions. Raises an exception if batch QC status is not 'PASS'.
  3. trg_prevent_future_mfg_date: BEFORE INSERT/UPDATE on Batch_Master. Ensures no future manufacturing dates.
  4. trg_set_expiry_date: BEFORE INSERT on Batch_Master. Auto-calculates Expiry_Date based on product shelf life.
  5. trg_material_qc_auto_update: AFTER INSERT on QC_Report. Updates Warehouse lot status to APPROVED/REJECTED based on material tests.

πŸ€– AI Copilot Architecture

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])
Loading

✨ Core Features

  • πŸ” 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.

πŸ› οΈ Tech Stack

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

πŸ“‚ Project Structure

πŸ“ 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!

πŸš€ Getting Started

1. Prerequisites

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

2. Start the Database

Use Docker Compose to spin up the PostgreSQL database (which includes the pgvector extension for our AI).

docker compose up -d

Load 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.sql

3. Start the Backend

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

4. Start the Frontend

In a new terminal window, navigate to the frontend folder and start the React app:

cd frontend
npm install
npm run dev

Your user interface is now live at http://localhost:5173!


πŸ” Demo Accounts

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.

πŸ€– AI Capabilities Example

Once logged in, try asking the AI Copilot:

"What is our current inventory shortage for raw materials?"

How it works:

  1. The AI understands your question.
  2. It decides it needs real data, so it executes the getInventoryShortage Java Tool.
  3. The Tool queries the live PostgreSQL View v_inventory_shortage.
  4. The AI formats the result into a beautiful, human-readable table.

Built with ❀️ for Modern Pharmaceutical Operations

About

A 3-tier enterprise backend managing the pharmaceutical manufacturing lifecycle. Built with Java 21, Spring Boot 3, and React, it enforces strict FDA compliance via PostgreSQL triggers and features an embedded Spring AI compliance copilot. It includes secure JWT workflows for all operations, full batch traceability, and real-time stock dashboards.

Topics

Resources

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages