npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@team-bitbot/core

v1.0.0

Published

P-MACS Core SDK - Pharmacy - Management and Control System

Downloads

70

Readme

@team-bitbot/core

P-MACS Core SDK - Pharmacy Management and Control System with AI-powered LangChain Tools

npm version License: MIT Tests

A comprehensive TypeScript SDK for hospital pharmacy management featuring 27 LangChain-powered AI tools for inventory management, expiry tracking, forecasting, analytics, and procurement.

✨ Features

  • 🤖 27 AI-Powered Tools - LangChain-integrated tools for pharmacy operations
  • 📦 Inventory Management - Real-time stock tracking with safety stock alerts
  • ⏰ Expiry Tracking - FEFO (First Expiry First Out) recommendations
  • 📊 Analytics - Top/slow movers, usage patterns, seasonal trends
  • 🔮 Forecasting - Predictive analytics for stock-out prevention
  • 💰 Procurement - Automated purchase order generation
  • 🔒 Role-Based Access - Nurse, Pharmacist, and Admin permissions
  • 📈 100% Test Coverage - All 235 tests passing

📦 Installation

npm install @team-bitbot/core @langchain/core @langchain/openai langchain

Peer Dependencies

This package requires the following peer dependencies:

{
  "@langchain/core": "^0.3.0",
  "@langchain/openai": "^0.3.0",
  "langchain": "^0.3.0"
}

🚀 Quick Start

import { createAllTools, CSVDatabaseAdapter } from '@team-bitbot/core';

// Initialize database adapter
const db = new CSVDatabaseAdapter('./data');

// Create tools for a pharmacist user
const tools = createAllTools({
  db: db,
  userRole: 'Pharmacist',
  userId: 'P001'
});

// Use tools with LangChain
import { ChatOpenAI } from '@langchain/openai';
import { AgentExecutor, createOpenAIFunctionsAgent } from 'langchain/agents';
import { ChatPromptTemplate } from '@langchain/core/prompts';

const llm = new ChatOpenAI({
  modelName: 'gpt-4o',
  temperature: 0
});

const prompt = ChatPromptTemplate.fromMessages([
  ['system', 'You are a pharmacy management assistant.'],
  ['human', '{input}'],
  ['placeholder', '{agent_scratchpad}'],
]);

const agent = await createOpenAIFunctionsAgent({
  llm,
  tools,
  prompt,
});

const executor = new AgentExecutor({
  agent,
  tools,
});

const result = await executor.invoke({
  input: 'What drugs are expiring in the next 30 days?'
});

console.log(result.output);

🛠️ Available Tools

Inventory Management (9 tools)

  • get_full_inventory - Complete inventory overview with filters
  • lookup_inventory - Search specific drugs
  • update_inventory - Modify stock levels
  • list_ward_stock - View ward-specific inventory
  • get_location_list - List all storage locations
  • get_transaction_history - Audit trail
  • manage_user_access - User permissions (Admin only)
  • And more...

Expiry Management (4 tools)

  • check_expiring_drugs - Find drugs nearing expiry
  • get_fefo_recommendations - First Expiry First Out guidance
  • get_expired_items_report - Generate expiry reports
  • get_batch_report - Batch-specific expiry tracking

Analytics (6 tools)

  • get_top_movers_report - High-usage drugs
  • get_slow_movers_report - Low-usage drugs with financial impact
  • get_usage_analytics - Usage patterns
  • get_shortage_alerts - Stock-out warnings
  • get_stockout_risk_report - Risk assessments
  • get_restock_recommendation - Automated reorder suggestions

Forecasting (4 tools)

  • detect_seasonal_patterns - Identify usage trends
  • predict_stockout_date - Forecast stock depletion
  • recalculate_all_safety_stocks - Dynamic safety stock optimization

Procurement (4 tools)

  • generate_purchase_order - Automated PO generation
  • estimate_order_value - Budget planning
  • And more...

📚 Core Concepts

Database Adapters

import { CSVDatabaseAdapter, CachedDatabaseAdapter } from '@team-bitbot/core';

// Basic CSV adapter
const baseDb = new CSVDatabaseAdapter('./data');

// Cached adapter for better performance
const db = new CachedDatabaseAdapter(baseDb);

Role-Based Access Control

import { getToolsByPermission } from '@team-bitbot/core';

const allTools = createAllTools({ db, userRole: 'Nurse', userId: 'N001' });

// Filter tools by role
const nurseTools = getToolsByPermission(allTools, 'Nurse'); // 8 tools
const pharmacistTools = getToolsByPermission(allTools, 'Pharmacist'); // 22 tools
const adminTools = getToolsByPermission(allTools, 'Admin'); // 27 tools

Data Models

import type { EnrichedInventoryItem, Transaction } from '@team-bitbot/core';

// Enriched inventory with computed fields
interface EnrichedInventoryItem {
  drugId: string;
  drugName: string;
  qtyOnHand: number;
  safetyStock: number;
  status: 'adequate' | 'low' | 'critical' | 'stockout' | 'expired';
  category: 'controlled' | 'standard' | 'refrigerated';
  daysRemaining: number | null;
  avgDailyUse: number;
  // ... and more
}

🎯 Use Cases

1. Expiry Management

const expiringTool = tools.find(t => t.name === 'check_expiring_drugs');
const result = await expiringTool.invoke({ days: 30 });
const data = JSON.parse(result);

console.log(`Found ${data.summary.totalExpiring} drugs expiring in 30 days`);
data.expiringDrugs.forEach(drug => {
  console.log(`${drug.drugName} at ${drug.location}: ${drug.daysRemaining} days`);
});

2. Stock Alerts

const alertsTool = tools.find(t => t.name === 'get_shortage_alerts');
const result = await alertsTool.invoke({});
const data = JSON.parse(result);

if (data.alertLevel === 'critical') {
  console.log(`URGENT: ${data.summary.criticalShortages} critical shortages!`);
}

3. Analytics

const topMoversTool = tools.find(t => t.name === 'get_top_movers_report');
const result = await topMoversTool.invoke({ days: 30, topN: 10 });
const data = JSON.parse(result);

data.topMovers.forEach(drug => {
  console.log(`${drug.rank}. ${drug.drugName}: ${drug.avgDailyUsage} units/day`);
});

🧪 Testing

The package includes comprehensive tests with 100% pass rate:

npm test        # Run all tests
npm run test:watch  # Watch mode

Test Coverage:

  • 24 test files
  • 235 tests passing
  • 100% pass rate

📖 API Reference

Main Exports

// Database Adapters
export { CSVDatabaseAdapter } from './database/CSVAdapter';
export { CachedDatabaseAdapter } from './database/CachedAdapter';

// Tool Creation
export { createAllTools, getToolsByPermission } from './tools';

// Types
export type { DatabaseAdapter } from './database/CSVAdapter';
export type { EnrichedInventoryItem, Transaction, User } from './types';

// Utilities
export { enrichInventoryItem } from './database/models';
export { detectSeasonality, calculateSafetyStock } from './utils/forecasting';

Subpath Imports

// Tools only
import { createAllTools } from '@team-bitbot/core/tools';

// Database only
import { CSVDatabaseAdapter } from '@team-bitbot/core/database';

🔧 Configuration

Data Directory Structure

data/
├── inventory_master.csv      # Main inventory
├── transaction_logs.csv      # Transaction history
├── user_access.csv          # User accounts
├── access_logs.csv          # Audit logs
└── archived_logs/           # Historical data

CSV Format Examples

inventory_master.csv:

drug_id,drug_name,location,qty_on_hand,safety_stock,unit_cost,expiry_date,batch_lot
D001,Paracetamol,Main-Pharmacy,500,100,0.50,2025-12-31,BATCH001

transaction_logs.csv:

txn_id,timestamp,drug_id,action,qty_change,location,emp_id,notes
T001,2024-01-15T10:30:00Z,D001,USE,-10,ICU,N001,Patient dispensing

🌟 Advanced Features

Custom Database Adapter

Implement your own database backend:

import type { DatabaseAdapter } from '@team-bitbot/core';

class MySQLAdapter implements DatabaseAdapter {
  async loadInventory() {
    // Your MySQL query
  }

  async loadTransactions(days: number) {
    // Your implementation
  }

  // ... implement all methods
}

Caching

Built-in caching for performance:

import { CachedDatabaseAdapter } from '@team-bitbot/core';

const cachedDb = new CachedDatabaseAdapter(baseDb);
// Automatic 5-minute cache for inventory and transactions

Authentication

import { PasswordHasher } from '@team-bitbot/core/auth';

const hasher = new PasswordHasher();
const hashed = await hasher.hash('password123');
const isValid = await hasher.verify('password123', hashed);

📊 Performance

  • Package Size: 129 KB (gzipped)
  • Unpacked Size: 659 KB
  • Build Outputs: ESM + CJS + TypeScript definitions
  • Tree-shakeable: Yes
  • Side Effects: None

🤝 Contributing

Contributions welcome! This package powers critical healthcare operations, so we maintain high standards:

  1. All tests must pass (100% required)
  2. TypeScript strict mode
  3. Comprehensive test coverage for new features
  4. Clear documentation

📄 License

MIT License - see LICENSE file for details

🔗 Links

🙏 Acknowledgments

Built with:

📞 Support


Made with ❤️ for healthcare professionals worldwide