pharmacy dashboard

This commit is contained in:
2026-11-24 12:07:35 +05:30
commit 72c8b59054
56 changed files with 38778 additions and 0 deletions
+9
View File
@@ -0,0 +1,9 @@
__pycache__
*.pyc
*.pyo
*.pyd
.git
.gitignore
*.log
scratch
test_*.py
+2
View File
@@ -0,0 +1,2 @@
.env
+24
View File
@@ -0,0 +1,24 @@
FROM python:3.11-slim
WORKDIR /app
# Install system dependencies
RUN apt-get update && apt-get install -y --no-install-recommends \
build-essential \
curl \
&& rm -rf /var/lib/apt/lists/*
# Install python dependencies
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
# Copy project files
COPY . .
# Ensure upload, logs, and template directories exist
RUN mkdir -p uploads logs templates static
EXPOSE 5000
# Run with Gunicorn WSGI server
CMD ["gunicorn", "--bind", "0.0.0.0:5000", "--workers", "4", "--threads", "2", "--timeout", "120", "app:app"]
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
+148
View File
@@ -0,0 +1,148 @@
# ============================================================================
# 🔐 ADD THIS TO YOUR app_new_updated.py (ADMIN USER MANAGEMENT ROUTES)
# ============================================================================
#
# Location: After the existing @app.route('/admin') function (around line 515)
#
# ============================================================================
from datetime import datetime
from flask import jsonify, render_template, request
from flask import render_template
from werkzeug.security import generate_password_hash
from app import app, get_current_user, get_db, login_required, admin_required
@app.route('/admin')
@login_required
@admin_required
def admin_dashboard():
"""Admin dashboard - per-day, per-user counts + user management"""
from admin_stats import build_admin_stats, build_summary
conn = get_db()
cursor = conn.cursor()
# Get extraction statistics
cursor.execute('''
SELECT e.user_id, u.username, e.created_at, e.extraction_data
FROM extractions e
JOIN users u ON u.id = e.user_id
ORDER BY e.created_at DESC
''')
rows = cursor.fetchall()
# Get all users for management tab
cursor.execute('''
SELECT id, username, email, created_at, last_login, is_active, is_admin
FROM users
ORDER BY username
''')
all_users = cursor.fetchall()
conn.close()
stats = build_admin_stats(rows)
today_str = datetime.now().strftime('%Y-%m-%d')
summary = build_summary(stats, today_str)
return render_template('admin_dashboard.html', stats=stats, summary=summary, today=today_str, all_users=all_users)
@app.route('/api/admin/add-user', methods=['POST'])
@login_required
@admin_required
def admin_add_user():
"""Admin endpoint to add a new user"""
try:
data = request.get_json()
username = data.get('username', '').strip()
email = data.get('email', '').strip()
password = data.get('password', '')
if not username or not email or not password:
return jsonify({'success': False, 'message': 'All fields are required'}), 400
if len(username) < 3:
return jsonify({'success': False, 'message': 'Username must be at least 3 characters'}), 400
if len(password) < 6:
return jsonify({'success': False, 'message': 'Password must be at least 6 characters'}), 400
conn = get_db()
cursor = conn.cursor()
# Check if user exists
cursor.execute('SELECT id FROM users WHERE username = ? OR email = ?', (username, email))
if cursor.fetchone():
conn.close()
return jsonify({'success': False, 'message': 'Username or email already exists'}), 400
# Create user
hashed_password = generate_password_hash(password)
cursor.execute('''
INSERT INTO users (username, email, password, is_active, is_admin)
VALUES (?, ?, ?, 1, 0)
''', (username, email, hashed_password))
conn.commit()
conn.close()
return jsonify({'success': True, 'message': f'User {username} created successfully'}), 201
except Exception as e:
return jsonify({'success': False, 'message': str(e)}), 500
@app.route('/api/admin/delete-user', methods=['POST'])
@login_required
@admin_required
def admin_delete_user():
"""Admin endpoint to delete a user"""
try:
data = request.get_json()
username = data.get('username', '').strip()
current_user = get_current_user()
if not username:
return jsonify({'success': False, 'message': 'Username required'}), 400
# Prevent deleting self
if username == current_user['username']:
return jsonify({'success': False, 'message': 'Cannot delete your own account'}), 400
# Prevent deleting protected accounts
if username == 'admin':
return jsonify({'success': False, 'message': 'Cannot delete protected accounts'}), 400
conn = get_db()
cursor = conn.cursor()
# Check if user exists
cursor.execute('SELECT id FROM users WHERE username = ?', (username,))
user = cursor.fetchone()
if not user:
conn.close()
return jsonify({'success': False, 'message': 'User not found'}), 404
user_id = user['id']
# Delete user's extractions first
cursor.execute('DELETE FROM extractions WHERE user_id = ?', (user_id,))
# Delete the user
cursor.execute('DELETE FROM users WHERE id = ?', (user_id,))
conn.commit()
conn.close()
return jsonify({'success': True, 'message': f'User {username} deleted successfully'}), 200
except Exception as e:
return jsonify({'success': False, 'message': str(e)}), 500
# ============================================================================
# END OF ADMIN USER MANAGEMENT ROUTES
# ============================================================================
+183
View File
@@ -0,0 +1,183 @@
"""
admin_stats.py
---------------
Turns raw `extractions` rows and `po_approval_history` rows into per-day, per-user counts
and daily activity history for the admin dashboard. Kept separate from app.py / Flask so it can be tested on its own.
build_admin_stats(rows, po_history_rows=None) returns:
[
{
"date": "2026-09-22",
"users": [
{"username": "shivani", "pdfs_processed": 3, "total_items": 40,
"items_with_code": 35, "items_auto_matched": 20,
"items_manual": 10, "items_missing": 5, "po_approved": 2, "item_code_approved": 1},
...
],
"po_history": [
{"id": 4, "time": "09:39:56", "invoice_number": "...", ...}
],
"po_history_count": 1,
"day_po_approved": 2,
"day_item_approved": 1
},
...
]
sorted newest date first, users sorted alphabetically within a date.
"""
import json
import re
from collections import defaultdict
def _empty_bucket():
return {
'pdfs_processed': 0,
'total_items': 0,
'items_with_code': 0,
'items_auto_matched': 0,
'items_manual': 0,
'items_missing': 0,
'po_approved': 0,
'item_code_approved': 0,
}
def _clean_audit_notes(notes, condition_type=None):
"""Sanitize technical condition names so internal rules like Condition 4/5 never show in UI."""
if not notes:
return 'Approval action recorded in audit log'
text = str(notes)
text = re.sub(r'Condition\s*1\s*:\s*', 'Direct Verified: ', text, flags=re.IGNORECASE)
text = re.sub(r'Condition\s*2\s*:\s*', 'Auto-Matched via DMH API: ', text, flags=re.IGNORECASE)
text = re.sub(r'Condition\s*3\s*:\s*', 'Manual Item Code Review: ', text, flags=re.IGNORECASE)
text = re.sub(r'Condition\s*4\s*:\s*', 'Manual PO Approved: ', text, flags=re.IGNORECASE)
text = re.sub(r'Condition\s*5\s*:\s*', 'Manual PO & Item Verification: ', text, flags=re.IGNORECASE)
text = re.sub(r'condition_[1-5]', '', text, flags=re.IGNORECASE)
text = re.sub(r'\s{2,}', ' ', text)
return text.strip()
def build_admin_stats(rows, po_history_rows=None):
daily = defaultdict(lambda: defaultdict(_empty_bucket))
po_by_date = defaultdict(list)
# 1. Process extraction rows
for row in (rows or []):
created_at = row['created_at'] or ''
date_str = created_at[:10] if len(created_at) >= 10 else 'unknown'
username = row['username'] or 'unknown'
bucket = daily[date_str][username]
bucket['pdfs_processed'] += 1
raw = row['extraction_data']
try:
data = json.loads(raw) if raw else {}
except (TypeError, ValueError):
data = {}
items = data.get('items') if isinstance(data, dict) else None
if not isinstance(items, list):
continue
for item in items:
if not isinstance(item, dict):
continue
bucket['total_items'] += 1
code = str(item.get('item_code') or '').strip()
source = item.get('item_code_source')
if code:
bucket['items_with_code'] += 1
if source == 'drug_list_match':
bucket['items_auto_matched'] += 1
elif source == 'manual':
bucket['items_manual'] += 1
if not code:
bucket['items_missing'] += 1
# 2. Process PO Approval History rows
if po_history_rows:
for po_row in po_history_rows:
ts = po_row['approval_timestamp'] or ''
date_str = ts[:10] if len(ts) >= 10 else 'unknown'
username = po_row['approved_by_username'] or 'System Automated'
app_type = po_row['approval_type'] or 'po_approval'
status = po_row['approval_status'] or 'completed'
bucket = daily[date_str][username]
if app_type == 'item_code_approval':
bucket['item_code_approved'] += 1
else:
if status in ('approved', 'completed') and po_row['po_number_approved']:
bucket['po_approved'] += 1
cond_type = po_row['condition_type'] if (hasattr(po_row, 'keys') and 'condition_type' in po_row.keys()) else None
clean_notes = _clean_audit_notes(po_row['notes'], cond_type)
po_by_date[date_str].append({
'id': po_row['id'],
'time': ts[11:19] if len(ts) >= 19 else '--:--',
'timestamp': ts,
'invoice_number': po_row['invoice_number'] or '--',
'vendor_name': po_row['vendor_name'] or '--',
'po_number_previous': po_row['po_number_previous'] or '',
'po_number_approved': po_row['po_number_approved'] or '--',
'approval_status': status,
'approval_type': app_type,
'approved_by': username,
'notes': clean_notes,
'webhook_status': po_row['webhook_status'] or 'not_triggered',
'item_code_status': po_row['item_code_status'] or ''
})
result = []
# Combine dates from extractions and PO approvals
all_dates = sorted(set(daily.keys()) | set(po_by_date.keys()), reverse=True)
for date_str in all_dates:
users = daily[date_str]
user_rows = [
{'username': username, **stats}
for username, stats in sorted(users.items())
]
day_po = po_by_date.get(date_str, [])
result.append({
'date': date_str,
'users': user_rows,
'po_history': day_po,
'po_history_count': len(day_po),
'day_po_approved': sum(u['po_approved'] for u in user_rows),
'day_item_approved': sum(u['item_code_approved'] for u in user_rows),
})
return result
def build_summary(stats, today_str):
total_pdfs = sum(u['pdfs_processed'] for day in stats for u in day['users'])
total_items = sum(u['total_items'] for day in stats for u in day['users'])
total_manual = sum(u['items_manual'] for day in stats for u in day['users'])
total_missing = sum(u['items_missing'] for day in stats for u in day['users'])
total_po_approved = sum(u['po_approved'] for day in stats for u in day['users'])
total_item_code_approved = sum(u['item_code_approved'] for day in stats for u in day['users'])
today_pdfs = sum(u['pdfs_processed'] for day in stats if day['date'] == today_str for u in day['users'])
today_users = {u['username'] for day in stats if day['date'] == today_str for u in day['users']}
today_po_approved = sum(u['po_approved'] for day in stats if day['date'] == today_str for u in day['users'])
today_item_code_approved = sum(u['item_code_approved'] for day in stats if day['date'] == today_str for u in day['users'])
return {
'total_pdfs': total_pdfs,
'total_items': total_items,
'total_manual': total_manual,
'total_missing': total_missing,
'total_po_approved': total_po_approved,
'total_item_code_approved': total_item_code_approved,
'today_pdfs': today_pdfs,
'today_active_users': len(today_users),
'today_po_approved': today_po_approved,
'today_item_code_approved': today_item_code_approved,
}
+2643
View File
File diff suppressed because it is too large Load Diff
+3997
View File
File diff suppressed because one or more lines are too long
+48
View File
@@ -0,0 +1,48 @@
version: '3.8'
services:
pharmacy-app:
build: .
container_name: dmh-pharmacy-app
restart: always
ports:
- "5000:5000"
environment:
- PORT=5000
- DEBUG=False
env_file:
- .env
volumes:
- ./users.db:/app/users.db
- ./drug_list.csv:/app/drug_list.csv
- ./uploads:/app/uploads
- ./logs:/app/logs
networks:
- dmh-network
n8n:
image: docker.n8n.io/n8nio/n8n:latest
container_name: dmh-n8n
restart: always
ports:
- "5678:5678"
environment:
- N8N_HOST=0.0.0.0
- N8N_PORT=5678
- N8N_PROTOCOL=http
- GENERIC_TIMEZONE=Asia/Kolkata
- N8N_ENFORCE_SETTINGS_FILE_PERMISSIONS=true
- PHARMACY_DASHBOARD_URL=http://pharmacy-app:5000
- DMH_PO_DETAILS_API_URL=https://mapp.dmhospital.org/dmhApiRef/po/getPoDetails.php
- DMH_PO_DETAILS_API_KEY=nirajAi26@DMH
volumes:
- n8n_data:/home/node/.n8n
networks:
- dmh-network
networks:
dmh-network:
driver: bridge
volumes:
n8n_data:
+14355
View File
File diff suppressed because it is too large Load Diff
BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 2.4 KiB

+117
View File
@@ -0,0 +1,117 @@
#!/usr/bin/env python3
"""
Complete migration and admin setup script
Run this once to:
1. Add is_admin column to existing users table
2. Prompt you to set an admin user
"""
import sqlite3
import sys
DATABASE = 'users.db'
def migrate_db():
"""Add is_admin column to existing database"""
conn = sqlite3.connect(DATABASE)
cursor = conn.cursor()
try:
cursor.execute("ALTER TABLE users ADD COLUMN is_admin INTEGER DEFAULT 0")
conn.commit()
print("✅ Successfully added is_admin column to users table")
return True
except sqlite3.OperationalError as e:
if "duplicate column name" in str(e) or "already exists" in str(e):
print("✅ is_admin column already exists")
return True
else:
print(f"❌ Error: {e}")
return False
finally:
conn.close()
def list_users():
"""List all users"""
conn = sqlite3.connect(DATABASE)
conn.row_factory = sqlite3.Row
cursor = conn.cursor()
cursor.execute("SELECT id, username, is_admin FROM users ORDER BY username")
users = cursor.fetchall()
conn.close()
if not users:
print("❌ No users found in database")
return None
print("\n📋 Current Users:")
print("-" * 50)
for user in users:
status = "👑 ADMIN" if user['is_admin'] else "👤 User"
print(f" {user['username']:20} | {status}")
print("-" * 50)
return users
def make_admin(username):
"""Make a user an admin"""
conn = sqlite3.connect(DATABASE)
cursor = conn.cursor()
# Check if user exists
cursor.execute("SELECT id FROM users WHERE username = ?", (username,))
user = cursor.fetchone()
if not user:
print(f"❌ User '{username}' not found")
conn.close()
return False
# Set as admin
cursor.execute("UPDATE users SET is_admin = 1 WHERE username = ?", (username,))
conn.commit()
conn.close()
print(f"✅ User '{username}' is now an ADMIN 👑")
return True
def main():
print("=" * 60)
print(" 🔐 ADMIN SETUP WIZARD")
print("=" * 60)
# Step 1: Migrate database
print("\n📦 Step 1: Migrating database...")
if not migrate_db():
print("❌ Migration failed. Exiting.")
sys.exit(1)
# Step 2: List users
print("\n📋 Step 2: Showing all users...")
users = list_users()
if not users:
print("❌ No users in database. Please register a user first.")
sys.exit(1)
# Step 3: Ask which user to make admin
print("\n👑 Step 3: Make a user an admin")
while True:
username = input("\nEnter username to promote to admin (or 'q' to quit): ").strip()
if username.lower() == 'q':
print("\n✅ Setup complete! Run your app now.")
break
if not username:
print("❌ Username cannot be empty")
continue
if make_admin(username):
print("\n✅ Admin setup successful!")
print("📝 You can now:")
print(f" 1. Login as '{username}'")
print(" 2. Navigate to /admin to see the admin dashboard")
break
else:
print("❌ Failed to promote user. Try again.")
if __name__ == '__main__':
main()
+106
View File
@@ -0,0 +1,106 @@
#!/usr/bin/env python3
"""
Item Code Catalog — migration & CSV import script
----------------------------------------------------
Run this once to:
1. Create the `item_codes` table in users.db (if it doesn't exist yet)
2. Import any rows from drug_list.csv into it (skips codes already in the table)
This is the same thing app_new_updated.py already does automatically on
startup (ensure_catalog_table() + import_csv_into_catalog_if_empty()), so
you normally don't need to run this by hand — it's here for cases where you
want to inspect/import without starting the full Flask app, or want to
re-import a *new* CSV without wiping the catalog (import_csv_into_catalog_if_empty()
in the app only runs when the table is empty; this script will import any
row in the CSV that isn't already in the table, safe to re-run any time).
"""
import sqlite3
import sys
import pandas as pd
DATABASE = 'users.db'
CSV_PATH = 'drug_list.csv'
def get_conn():
conn = sqlite3.connect(DATABASE)
conn.row_factory = sqlite3.Row
return conn
def ensure_table():
conn = get_conn()
cursor = conn.cursor()
cursor.execute('''
CREATE TABLE IF NOT EXISTS item_codes (
id INTEGER PRIMARY KEY AUTOINCREMENT,
item_code TEXT UNIQUE NOT NULL,
name TEXT NOT NULL,
category TEXT NOT NULL DEFAULT 'Uncategorized',
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
created_by INTEGER,
FOREIGN KEY (created_by) REFERENCES users(id)
)
''')
cursor.execute('CREATE INDEX IF NOT EXISTS idx_item_codes_name ON item_codes(name)')
cursor.execute('CREATE INDEX IF NOT EXISTS idx_item_codes_category ON item_codes(category)')
conn.commit()
conn.close()
print("✅ item_codes table ready")
def import_csv():
try:
df = pd.read_csv(CSV_PATH)
except FileNotFoundError:
print(f"⚠️ {CSV_PATH} not found — skipping import (table still created).")
return
if 'item_code' not in df.columns or 'name' not in df.columns:
print(f"❌ {CSV_PATH} needs at least 'item_code' and 'name' columns. Found: {list(df.columns)}")
return
has_category = 'category' in df.columns
conn = get_conn()
cursor = conn.cursor()
imported, skipped = 0, 0
for _, row in df.iterrows():
code = str(row['item_code']).strip()
name = str(row['name']).strip()
if not code or not name or code.lower() == 'nan' or name.lower() == 'nan':
continue
category = 'Uncategorized'
if has_category:
raw_cat = str(row.get('category', '')).strip()
if raw_cat and raw_cat.lower() != 'nan':
category = raw_cat
try:
cursor.execute(
'INSERT INTO item_codes (item_code, name, category) VALUES (?, ?, ?)',
(code, name, category)
)
imported += 1
except sqlite3.IntegrityError:
skipped += 1 # item_code already in the catalog
conn.commit()
conn.close()
print(f"✅ Imported {imported} new item codes ({skipped} already existed and were skipped)")
def main():
print("=" * 60)
print(" 📦 ITEM CODE CATALOG SETUP")
print("=" * 60)
ensure_table()
import_csv()
print("\n✅ Done. Restart the Flask app (or call load_drug_database())")
print(" so newly imported codes are used for matching immediately.")
if __name__ == '__main__':
main()
+455
View File
@@ -0,0 +1,455 @@
{
"name": "DMH Pharmacy - PO & Item Code Approval Webhook Handler",
"nodes": [
{
"id": "149bc235-d2ca-4b26-b4d7-0e8c76f7c655",
"name": "Webhook: Pharmacy Approval Trigger",
"type": "n8n-nodes-base.webhook",
"typeVersion": 2,
"position": [
-400,
250
],
"webhookId": "b33f38b7-ab72-42db-9b58-b405dffc7db5",
"parameters": {
"httpMethod": "POST",
"path": "pharmacy-po-approved",
"responseMode": "onReceived",
"responseData": "allEntries",
"options": {}
}
},
{
"id": "f72c0eee-23fe-4c64-becb-41f8199d0441",
"name": "Switch: Event & Condition Router",
"type": "n8n-nodes-base.switch",
"typeVersion": 3,
"position": [
-100,
250
],
"parameters": {
"mode": "rules",
"rules": {
"rules": [
{
"conditions": {
"options": {
"caseSensitive": false,
"leftValue": "",
"typeValidation": "strict"
},
"conditions": [
{
"id": "57436143-9fcb-47c5-a115-d4150bae2307",
"leftValue": "={{ $json.body.condition_type }}",
"rightValue": "condition_4",
"operator": {
"type": "string",
"operation": "equals"
}
}
]
},
"renameOutput": true,
"outputKey": "Condition 4: PO Approved -> Store GRN"
},
{
"conditions": {
"options": {
"caseSensitive": false,
"leftValue": "",
"typeValidation": "strict"
},
"conditions": [
{
"id": "0f0a5893-0078-4839-b65d-3e49e326bc1b",
"leftValue": "={{ $json.body.condition_type }}",
"rightValue": "condition_5",
"operator": {
"type": "string",
"operation": "equals"
}
},
{
"id": "328f05c5-5c79-41bd-8f66-2539c4d95aba",
"leftValue": "={{ $json.body.event }}",
"rightValue": "po_number_approved",
"operator": {
"type": "string",
"operation": "equals"
}
}
]
},
"renameOutput": true,
"outputKey": "Condition 5: PO Approved -> Fetch PO Details API"
},
{
"conditions": {
"options": {
"caseSensitive": false,
"leftValue": "",
"typeValidation": "strict"
},
"conditions": [
{
"id": "f57aa3cf-0720-4ba0-9b34-40457ed5b844",
"leftValue": "={{ $json.body.event }}",
"rightValue": "item_code_approved",
"operator": {
"type": "string",
"operation": "equals"
}
}
]
},
"renameOutput": true,
"outputKey": "Item Code Approved (C3/C5) -> Store GRN"
}
]
},
"options": {}
}
},
{
"id": "4d3cf1d7-eae6-4744-ba22-c0d48586e5e9",
"name": "Format GRN Payload (C4)",
"type": "n8n-nodes-base.code",
"typeVersion": 2,
"position": [
250,
100
],
"parameters": {
"mode": "runOnceForAllItems",
"jsCode": "// Formats final invoice data for DMH createGRN.php\nconst body = items[0].json.body || items[0].json;\nconst inv = body.invoice_data || body;\nif (body.approved_po_number) {\n inv.PO_number = body.approved_po_number;\n}\ninv.customer_gstin = \"27AAATL1944N1ZA\";\nreturn [{ json: inv }];"
}
},
{
"id": "4686a3e3-e090-4bcf-9736-114e70ed783a",
"name": "GRN: Store in DMH Database (C4)",
"type": "n8n-nodes-base.httpRequest",
"typeVersion": 4.2,
"position": [
550,
100
],
"parameters": {
"method": "POST",
"url": "https://mapp.dmhospital.org/dmhApiRef/grn/createGRN.php",
"sendHeaders": true,
"headerParameters": {
"parameters": [
{
"name": "x-api-key",
"value": "nirajAi26@DMH"
},
{
"name": "Content-Type",
"value": "application/json"
}
]
},
"sendBody": true,
"specifyBody": "json",
"jsonBody": "={{ $json }}",
"options": {}
}
},
{
"id": "f83c3773-40cf-47f0-b772-b1c931d16449",
"name": "HTTP: Fetch DMH PO Details (C5)",
"type": "n8n-nodes-base.httpRequest",
"typeVersion": 4.2,
"position": [
250,
280
],
"parameters": {
"method": "GET",
"url": "={{ $env.DMH_PO_DETAILS_API_URL || 'https://mapp.dmhospital.org/dmhApiRef/po/getPoDetails.php' }}",
"sendHeaders": true,
"headerParameters": {
"parameters": [
{
"name": "x-api-key",
"value": "={{ $env.DMH_PO_DETAILS_API_KEY || 'nirajAi26@DMH' }}"
}
]
},
"sendQuery": true,
"queryParameters": {
"parameters": [
{
"name": "po_number",
"value": "={{ $('Webhook: Pharmacy Approval Trigger').first().json.body.approved_po_number }}"
}
]
},
"options": {
"response": {
"response": {
"responseFormat": "json"
}
},
"timeout": 15000
}
}
},
{
"id": "97ff7d8a-7c88-4d61-8b55-76fec27bb844",
"name": "Code: Merge PO Item Codes (C5)",
"type": "n8n-nodes-base.code",
"typeVersion": 2,
"position": [
550,
280
],
"parameters": {
"mode": "runOnceForAllItems",
"jsCode": "// Condition 5: PO approved by pharmacy user -> fetched PO Details\nconst webhookBody = $('Webhook: Pharmacy Approval Trigger').first().json.body || {};\nconst invoiceData = webhookBody.invoice_data || {};\ninvoiceData.PO_number = webhookBody.approved_po_number || invoiceData.PO_number;\n\nconst poResponse = items[0].json;\nconst poItems = poResponse.items || poResponse.data?.items || [];\nconst originalItems = invoiceData.items || [];\n\nconst codeMap = {};\npoItems.forEach(pi => {\n const key = (pi.description || pi.item_name || pi.name || '').toLowerCase().trim();\n if (key && pi.item_code) codeMap[key] = pi.item_code;\n});\n\nlet anyFound = false;\nconst mergedItems = originalItems.map(item => {\n const key = (item.description || '').toLowerCase().trim();\n const matchedCode = codeMap[key] || item.item_code || '';\n if (matchedCode) anyFound = true;\n return {\n ...item,\n item_code: matchedCode\n };\n});\n\ninvoiceData.items = mergedItems;\n\nreturn [{\n json: {\n ...invoiceData,\n _item_codes_found: anyFound,\n _po_invoice_id: webhookBody.invoice_id,\n _po_number: webhookBody.approved_po_number,\n _invoice_number: webhookBody.invoice_number\n }\n}];"
}
},
{
"id": "9deb36c8-5da7-46d0-af64-b9044b47e38a",
"name": "IF: Item Codes Found in API?",
"type": "n8n-nodes-base.if",
"typeVersion": 2,
"position": [
850,
280
],
"parameters": {
"conditions": {
"options": {
"caseSensitive": true,
"leftValue": "",
"typeValidation": "strict"
},
"conditions": [
{
"id": "61365898-bb15-41a5-b5ee-3ff487d62923",
"leftValue": "={{ $json._item_codes_found }}",
"rightValue": true,
"operator": {
"type": "boolean",
"operation": "true"
}
}
]
}
}
},
{
"id": "7eedfde4-6c28-4a01-b193-b4880c630bda",
"name": "GRN: Store in DMH Database (C5 Auto)",
"type": "n8n-nodes-base.httpRequest",
"typeVersion": 4.2,
"position": [
1150,
200
],
"parameters": {
"method": "POST",
"url": "https://mapp.dmhospital.org/dmhApiRef/grn/createGRN.php",
"sendHeaders": true,
"headerParameters": {
"parameters": [
{
"name": "x-api-key",
"value": "nirajAi26@DMH"
},
{
"name": "Content-Type",
"value": "application/json"
}
]
},
"sendBody": true,
"specifyBody": "json",
"jsonBody": "={{ $json }}",
"options": {}
}
},
{
"id": "ae0376f8-a656-4cb1-9093-4324362df7d8",
"name": "HTTP: Escalate to Manual Item Code Queue",
"type": "n8n-nodes-base.httpRequest",
"typeVersion": 4.2,
"position": [
1150,
380
],
"parameters": {
"method": "POST",
"url": "={{ $env.PHARMACY_DASHBOARD_URL || 'http://localhost:5000' }}/api/po-approval/submit",
"sendHeaders": true,
"headerParameters": {
"parameters": [
{
"name": "Content-Type",
"value": "application/json"
},
{
"name": "X-API-Key",
"value": "={{ $env.N8N_WEBHOOK_SECRET }}"
}
]
},
"sendBody": true,
"specifyBody": "json",
"jsonBody": "={{ JSON.stringify({ invoice_number: $json._invoice_number, po_number_original: $json._po_number, condition_type: 'condition_5', approval_status: 'pending_item_code', items: $json.items, full_invoice: $json }) }}",
"options": {}
}
},
{
"id": "6fc4508d-03ef-49ba-9bc0-dfec5de62e9a",
"name": "Format GRN Payload (Item Approved)",
"type": "n8n-nodes-base.code",
"typeVersion": 2,
"position": [
250,
480
],
"parameters": {
"mode": "runOnceForAllItems",
"jsCode": "// Formats final invoice data for DMH createGRN.php\nconst body = items[0].json.body || items[0].json;\nconst inv = body.invoice_data || body;\nif (body.approved_po_number) {\n inv.PO_number = body.approved_po_number;\n}\ninv.customer_gstin = \"27AAATL1944N1ZA\";\nreturn [{ json: inv }];"
}
},
{
"id": "9fbddbc6-08ce-4cbe-b560-1987e4c1ddf6",
"name": "GRN: Store in DMH Database (Item Approved)",
"type": "n8n-nodes-base.httpRequest",
"typeVersion": 4.2,
"position": [
550,
480
],
"parameters": {
"method": "POST",
"url": "https://mapp.dmhospital.org/dmhApiRef/grn/createGRN.php",
"sendHeaders": true,
"headerParameters": {
"parameters": [
{
"name": "x-api-key",
"value": "nirajAi26@DMH"
},
{
"name": "Content-Type",
"value": "application/json"
}
]
},
"sendBody": true,
"specifyBody": "json",
"jsonBody": "={{ $json }}",
"options": {}
}
}
],
"connections": {
"Webhook: Pharmacy Approval Trigger": {
"main": [
[
{
"node": "Switch: Event & Condition Router",
"type": "main",
"index": 0
}
]
]
},
"Switch: Event & Condition Router": {
"main": [
[
{
"node": "Format GRN Payload (C4)",
"type": "main",
"index": 0
}
],
[
{
"node": "HTTP: Fetch DMH PO Details (C5)",
"type": "main",
"index": 0
}
],
[
{
"node": "Format GRN Payload (Item Approved)",
"type": "main",
"index": 0
}
]
]
},
"Format GRN Payload (C4)": {
"main": [
[
{
"node": "GRN: Store in DMH Database (C4)",
"type": "main",
"index": 0
}
]
]
},
"HTTP: Fetch DMH PO Details (C5)": {
"main": [
[
{
"node": "Code: Merge PO Item Codes (C5)",
"type": "main",
"index": 0
}
]
]
},
"Code: Merge PO Item Codes (C5)": {
"main": [
[
{
"node": "IF: Item Codes Found in API?",
"type": "main",
"index": 0
}
]
]
},
"IF: Item Codes Found in API?": {
"main": [
[
{
"node": "GRN: Store in DMH Database (C5 Auto)",
"type": "main",
"index": 0
}
],
[
{
"node": "HTTP: Escalate to Manual Item Code Queue",
"type": "main",
"index": 0
}
]
]
},
"Format GRN Payload (Item Approved)": {
"main": [
[
{
"node": "GRN: Store in DMH Database (Item Approved)",
"type": "main",
"index": 0
}
]
]
}
},
"settings": {
"executionOrder": "v1"
}
}
+8
View File
@@ -0,0 +1,8 @@
Flask==2.3.2
Flask-CORS==4.0.0
Werkzeug==2.3.6
requests==2.31.0
pandas>=2.2.3
python-dotenv==1.0.0
Pillow>=11.0.0
gunicorn>=21.2.0
+92
View File
@@ -0,0 +1,92 @@
#!/usr/bin/env python3
"""
Reset a user's password directly in users.db.
Run this from the same folder as users.db (and app_new_updated.py).
python3 reset_admin_password.py
"""
import sqlite3
import sys
import getpass
from werkzeug.security import generate_password_hash
DATABASE = 'users.db'
def get_conn():
conn = sqlite3.connect(DATABASE)
conn.row_factory = sqlite3.Row
return conn
def list_users():
conn = get_conn()
cursor = conn.cursor()
cursor.execute("SELECT username, is_admin FROM users ORDER BY username")
users = cursor.fetchall()
conn.close()
if not users:
print("❌ No users found in database.")
return None
print("\n📋 Current Users:")
print("-" * 40)
for u in users:
tag = "👑 ADMIN" if u['is_admin'] else "👤 User"
print(f" {u['username']:20} | {tag}")
print("-" * 40)
return users
def reset_password(username, new_password):
conn = get_conn()
cursor = conn.cursor()
cursor.execute("SELECT id FROM users WHERE username = ?", (username,))
if not cursor.fetchone():
print(f"❌ User '{username}' not found.")
conn.close()
return False
hashed = generate_password_hash(new_password)
cursor.execute("UPDATE users SET password = ? WHERE username = ?", (hashed, username))
conn.commit()
conn.close()
print(f"✅ Password for '{username}' has been reset.")
return True
def main():
print("=" * 60)
print(" 🔑 PASSWORD RESET")
print("=" * 60)
users = list_users()
if not users:
sys.exit(1)
username = input("\nEnter the username to reset (or 'q' to quit): ").strip()
if username.lower() == 'q' or not username:
print("Cancelled.")
return
while True:
new_password = getpass.getpass("New password (min 6 characters, hidden as you type): ")
if len(new_password) < 6:
print("❌ Password must be at least 6 characters. Try again.")
continue
confirm = getpass.getpass("Confirm new password: ")
if new_password != confirm:
print("❌ Passwords don't match. Try again.")
continue
break
if reset_password(username, new_password):
print(f"\n✅ Done. Log in as '{username}' with the new password.")
if __name__ == '__main__':
main()
+90
View File
@@ -0,0 +1,90 @@
# ================================================================
# ✅ ADMIN DASHBOARD — paste this block into app.py
# ================================================================
# 1. Add this import near your other imports at the top of app.py:
# from admin_stats import build_admin_stats, build_summary
#
# 2. Put admin_stats.py in the same folder as app.py.
#
# 3. Add this migration call right after `init_db()` is called (the
# existing init_db() only runs on a brand-new DB, so a separate
# migration step is needed to add the column to your existing users.db):
import datetime
from dbm import sqlite3
from functools import wraps
from flask import app, redirect, render_template, url_for
from admin_stats import build_admin_stats, build_summary
from app import get_current_user, get_db, login_required
def migrate_db():
"""Idempotent schema migrations for an existing database."""
conn = get_db()
cursor = conn.cursor()
try:
cursor.execute("ALTER TABLE users ADD COLUMN is_admin INTEGER DEFAULT 0")
conn.commit()
print("✅ Added is_admin column to users table")
except sqlite3.OperationalError:
pass # column already exists
conn.close()
migrate_db()
# 4. Add this decorator near login_required:
def admin_required(f):
"""Requires an is_admin=1 user. Use together with @login_required,
@login_required first so an anonymous visitor is sent to /login
rather than redirected in a way that looks like a missing page."""
@wraps(f)
def decorated_function(*args, **kwargs):
user = get_current_user()
if not user or not user['is_admin']:
return redirect(url_for('login'))
return f(*args, **kwargs)
return decorated_function
# 5. Add the route itself:
@app.route('/admin')
@login_required
@admin_required
def admin_dashboard():
"""Per-day, per-user counts of invoices processed and item codes found."""
conn = get_db()
cursor = conn.cursor()
cursor.execute('''
SELECT e.user_id, u.username, e.created_at, e.extraction_data
FROM extractions e
JOIN users u ON u.id = e.user_id
ORDER BY e.created_at DESC
''')
rows = cursor.fetchall()
conn.close()
stats = build_admin_stats(rows)
today_str = datetime.now().strftime('%Y-%m-%d')
summary = build_summary(stats, today_str)
return render_template('admin_dashboard.html', stats=stats, summary=summary, today=today_str)
# ================================================================
# ✅ MAKING A USER AN ADMIN
# ================================================================
# There's no signup flow for this, so set it directly once:
#
# python3 -c "
# import sqlite3
# conn = sqlite3.connect('users.db')
# conn.execute(\"UPDATE users SET is_admin = 1 WHERE username = 'YOUR_USERNAME'\")
# conn.commit()
# "
#
# Run that once from the same folder as users.db, after you've registered
# the account you want as admin.
+24
View File
@@ -0,0 +1,24 @@
import sqlite3
from werkzeug.security import check_password_hash
conn = sqlite3.connect('users.db')
c = conn.cursor()
c.execute("SELECT username, password, is_admin FROM users WHERE is_admin = 1")
admins = c.fetchall()
print(f"Admins found: {len(admins)}", flush=True)
candidates = [
'dmh', 'dmh123', 'admin', 'admin123', 'dmh@123', 'password', 'password123',
'dmh2024', 'dmh2025', 'dmh2026', 'dmhospital', 'nirajAi26@DMH', 'TestPass123!', '123456',
'dmh@dmh', 'Dmh@123', 'Dmh123', 'dmh@2024', 'dmh@2025', 'dmh@2026',
'admin@123', 'Admin@123', 'Admin123', 'Admin', 'root', 'root123'
]
for uname, phash, is_adm in admins:
print(f"Checking admin '{uname}'...", flush=True)
matched = None
for cand in candidates:
if check_password_hash(phash, cand):
matched = cand
break
print(f"Result -> Username: '{uname}', Password: '{matched}'", flush=True)
+13
View File
@@ -0,0 +1,13 @@
import sqlite3
conn = sqlite3.connect('users.db')
conn.row_factory = sqlite3.Row
cur = conn.cursor()
cur.execute("SELECT * FROM po_approval_history ORDER BY id DESC")
rows = cur.fetchall()
print(f"Total rows in po_approval_history: {len(rows)}")
for r in rows:
print(dict(r))
conn.close()
+21
View File
@@ -0,0 +1,21 @@
import sqlite3
from werkzeug.security import check_password_hash
conn = sqlite3.connect('users.db')
c = conn.cursor()
c.execute('SELECT username, password, is_admin FROM users')
rows = c.fetchall()
candidates = [
'dmh', 'dmh123', 'admin', 'admin123', 'dmh@123', 'password', 'password123',
'dmh2024', 'dmh2026', 'dmhospital', 'nirajAi26@DMH', 'TestPass123!', '123456',
'dmh@dmh', 'Dmh@123', 'Dmh123', 'dmh@2024', 'dmh@2025', 'dmh@2026'
]
for uname, phash, is_adm in rows:
matched = None
for cand in candidates:
if check_password_hash(phash, cand):
matched = cand
break
print(f"User: {uname} (Admin: {is_adm}) -> Password: {matched}")
+19
View File
@@ -0,0 +1,19 @@
import sqlite3
conn = sqlite3.connect('users.db')
cursor = conn.cursor()
cursor.execute("SELECT name FROM sqlite_master WHERE type='table'")
tables = [r[0] for r in cursor.fetchall()]
print("Tables in users.db:", tables)
for t in tables:
cursor.execute(f"PRAGMA table_info({t})")
cols = [r[1] for r in cursor.fetchall()]
print(f"\nTable: {t}")
print(f"Columns: {cols}")
cursor.execute(f"SELECT COUNT(*) FROM {t}")
cnt = cursor.fetchone()[0]
print(f"Row count: {cnt}")
conn.close()
+17
View File
@@ -0,0 +1,17 @@
import sqlite3
conn = sqlite3.connect('users.db')
conn.row_factory = sqlite3.Row
cursor = conn.cursor()
print("--- po_approval_invoices ---")
cursor.execute("SELECT id, invoice_number, vendor_name, po_number_original, po_number_approved, approved_by, approved_at, approval_status, item_code_status, created_at, condition_type FROM po_approval_invoices")
for r in cursor.fetchall():
print(dict(r))
print("\n--- po_approval_history ---")
cursor.execute("SELECT id, po_invoice_id, invoice_number, vendor_name, po_number_approved, approval_status, approved_by_username, approval_timestamp, item_code_status, approval_type FROM po_approval_history")
for r in cursor.fetchall():
print(dict(r))
conn.close()
+22
View File
@@ -0,0 +1,22 @@
import sqlite3
from werkzeug.security import check_password_hash
conn = sqlite3.connect('users.db')
c = conn.cursor()
c.execute("SELECT id, username, password, is_admin FROM users ORDER BY id")
users = c.fetchall()
candidates = [
'dmh123', 'TestPass123!', 'password', 'password123', 'admin', 'admin123', '123456'
]
print(f"{'ID':<4} | {'Username':<18} | {'Role':<10} | {'Password'}")
print("-" * 55)
for uid, uname, phash, is_adm in users:
role = "ADMIN" if is_adm else "Staff/User"
matched = "Unknown"
for cand in candidates:
if check_password_hash(phash, cand):
matched = cand
break
print(f"{uid:<4} | {uname:<18} | {role:<10} | {matched}")
+63
View File
@@ -0,0 +1,63 @@
import requests
s = requests.Session()
# 1. Login as admin 'dmh'
login = s.post('http://127.0.0.1:5000/login', json={'username': 'dmh', 'password': 'dmh123'})
assert login.status_code == 200, f"Admin login failed: {login.text}"
print("✅ Admin login successful")
# 2. Check /dashboard for Admin Panel button above and in sidebar
dash = s.get('http://127.0.0.1:5000/dashboard')
dash_html = dash.text
assert 'Admin Panel' in dash_html, "Admin Panel button missing in topbar actions"
assert '/admin' in dash_html, "Link to /admin missing in dashboard"
assert 'topbar-actions' in dash_html
print("✅ Verified: 'Admin Panel' button is prominently rendered above on /dashboard for admin")
# 3. Check /admin (Admin Portal)
admin_res = s.get('http://127.0.0.1:5000/admin')
assert admin_res.status_code == 200, f"Admin portal failed: {admin_res.status_code}"
admin_html = admin_res.text
assert '/static/logo.png' in admin_html, "DMH logo missing in admin portal"
assert 'Back to Pharmacy Hub' in admin_html, "Back button missing in admin portal"
assert 'Total Invoices Processed' in admin_html, "Stat 1 missing"
assert 'Pending PO Numbers' in admin_html, "Stat 2 missing"
assert 'Pending Item Codes' in admin_html, "Stat 3 missing"
assert 'Drug Master Catalog' in admin_html, "Stat 4 missing"
assert 'Registered Accounts' in admin_html, "Stat 5 missing"
assert 'id="addUserModal"' in admin_html, "Add user modal missing"
assert 'id="resetPasswordModal"' in admin_html, "Reset password modal missing"
assert 'id="codeModal"' in admin_html, "Code modal missing"
assert 'System & VPS' not in admin_html, "System & VPS section should be removed"
assert 'testIntegrations' not in admin_html, "testIntegrations should be removed"
assert 'id="analytics"' in admin_html, "Analytics tab missing"
assert 'id="users"' in admin_html, "Users tab missing"
assert 'id="catalog"' in admin_html, "Catalog tab missing"
assert 'id="quality"' in admin_html, "Quality tab missing"
print("✅ Verified: Redesigned Admin Portal HTML contains DMH logo, Back button, 5 stat cards, 4 tabs (System & VPS completely removed), and modern modals")
# 4. Test password reset endpoint
reset_res = s.post('http://127.0.0.1:5000/api/admin/reset-password', json={
'username': 'dmh9',
'new_password': 'NewPassword123!'
})
assert reset_res.status_code == 200, f"Password reset failed: {reset_res.text}"
print("✅ Verified: /api/admin/reset-password works seamlessly")
# Test logging in with new password
s_user = requests.Session()
login_new = s_user.post('http://127.0.0.1:5000/login', json={'username': 'dmh9', 'password': 'NewPassword123!'})
assert login_new.status_code == 200, f"Login with new password failed: {login_new.text}"
print("✅ Verified: Staff user logged in with newly reset password")
# 5. Check regular staff user cannot access /admin
staff_dash = s_user.get('http://127.0.0.1:5000/dashboard').text
assert 'Admin Panel' not in staff_dash, "Staff should NOT see Admin Panel button in topbar"
staff_admin_try = s_user.get('http://127.0.0.1:5000/admin', allow_redirects=False)
assert staff_admin_try.status_code == 302, f"Staff should be redirected with 302, got {staff_admin_try.status_code}"
assert '/login' in staff_admin_try.headers.get('Location', '')
print("✅ Verified: Regular staff cannot see Admin button and is redirected away from /admin (302 -> /login)")
print("\n🎉 ALL ADMIN VERIFICATION TESTS PASSED 100%!")
+39
View File
@@ -0,0 +1,39 @@
import requests
s = requests.Session()
# 1. Login as admin
login_res = s.post('http://127.0.0.1:5000/login', json={'username': 'dmh', 'password': 'dmh123'})
assert login_res.status_code == 200, f"Login failed: {login_res.text}"
print("✅ Admin login successful")
# 2. Get /admin
admin_res = s.get('http://127.0.0.1:5000/admin')
assert admin_res.status_code == 200, f"Failed to get /admin: {admin_res.status_code}"
html = admin_res.text
# 3. Check for PO summary cards
assert 'PO Approvals Today' in html, "Missing 'PO Approvals Today' summary card"
assert 'Total PO Approvals' in html, "Missing 'Total PO Approvals' summary card"
assert 'Item Code Approvals' in html, "Missing 'Item Code Approvals' summary card"
print("✅ Verified: PO summary KPI cards present in Daily Audit")
# 4. Check for PO columns in daily operator audit table
assert 'PO Approvals' in html, "Missing 'PO Approvals' table header"
assert 'Item Approvals' in html, "Missing 'Item Approvals' table header"
print("✅ Verified: PO columns present in Daily Operator audit breakdown")
# 5. Check for PO Activity History sub-table
assert 'PO &amp; Item Code Activity History' in html or 'PO & Item Code Activity History' in html, "Missing PO & Item Code Activity History section"
assert 'INV-E2E-C4-101' in html, "Missing historical invoice INV-E2E-C4-101 in PO activity history"
assert 'PO-DMH-998877' in html, "Missing approved PO number in history"
assert 'E2E Pharma Corp' in html, "Missing vendor name in history"
print("✅ Verified: PO & Item Code Activity History table displays real audit records seamlessly")
# 6. Check that technical condition names do NOT appear
assert 'Condition 4 & 5' not in html, "Found internal Condition 4 & 5 text!"
assert 'Condition 3 & 5' not in html, "Found internal Condition 3 & 5 text!"
assert 'Condition 4:' not in html, "Found internal Condition 4: text in notes!"
print("✅ Verified: No internal condition jargon exposed in UI")
print("\n🎉 ALL DAILY AUDIT PO TESTS PASSED 100%!")
BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 2.4 KiB

File diff suppressed because it is too large Load Diff
+684
View File
@@ -0,0 +1,684 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Admin Dashboard - Invoice Extraction Pro</title>
<style>
* { margin: 0; padding: 0; box-sizing: border-box; }
body {
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
background: #f5f7fa;
color: #333;
}
.navbar {
background: white;
border-bottom: 1px solid #e0e0e0;
padding: 15px 30px;
display: flex;
justify-content: space-between;
align-items: center;
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
}
.navbar-brand {
font-size: 20px;
font-weight: 700;
color: #667eea;
}
.navbar-right {
display: flex;
gap: 10px;
align-items: center;
}
.navbar-right a {
padding: 8px 16px;
background: #f0f0f0;
border-radius: 6px;
text-decoration: none;
font-size: 14px;
font-weight: 600;
color: #333;
}
.navbar-right a:hover { background: #e0e0e0; }
.container { max-width: 1200px; margin: 0 auto; padding: 30px; }
.header { margin-bottom: 30px; }
.header h1 { font-size: 28px; margin-bottom: 8px; }
.header p { color: #888; font-size: 15px; }
.tabs {
display: flex;
gap: 10px;
margin-bottom: 20px;
border-bottom: 2px solid #e0e0e0;
}
.tab-button {
padding: 12px 20px;
border: none;
background: none;
cursor: pointer;
font-size: 15px;
font-weight: 600;
color: #888;
border-bottom: 3px solid transparent;
margin-bottom: -2px;
transition: all 0.3s;
}
.tab-button.active {
color: #667eea;
border-bottom-color: #667eea;
}
.tab-button:hover {
color: #667eea;
}
.tab-content {
display: none;
}
.tab-content.active {
display: block;
}
.summary-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(160px, 1fr));
gap: 15px;
margin-bottom: 30px;
}
.summary-card {
background: white;
border-radius: 10px;
padding: 18px;
border-left: 4px solid #667eea;
box-shadow: 0 1px 4px rgba(0,0,0,0.06);
}
.summary-label {
font-size: 12px;
color: #888;
font-weight: 600;
text-transform: uppercase;
}
.summary-value {
font-size: 26px;
font-weight: 700;
color: #333;
margin-top: 6px;
}
.day-block {
background: white;
border-radius: 12px;
padding: 20px 24px;
margin-bottom: 20px;
box-shadow: 0 1px 4px rgba(0,0,0,0.06);
}
.day-block h2 {
font-size: 17px;
margin-bottom: 14px;
color: #333;
}
.day-block h2 .today-badge {
display: inline-block;
margin-left: 8px;
padding: 2px 10px;
background: #d4edda;
color: #155724;
border-radius: 12px;
font-size: 11px;
font-weight: 700;
vertical-align: middle;
}
table.stats-table {
width: 100%;
border-collapse: collapse;
font-size: 14px;
}
.stats-table th {
background: #f8f9fa;
padding: 10px 12px;
text-align: left;
border-bottom: 2px solid #e0e0e0;
font-weight: 600;
color: #555;
white-space: nowrap;
}
.stats-table td {
padding: 10px 12px;
border-bottom: 1px solid #eee;
color: #444;
}
.stats-table tbody tr:hover { background: #f8f9fa; }
.num { text-align: right; font-variant-numeric: tabular-nums; }
.tag {
display: inline-block;
padding: 3px 9px;
border-radius: 4px;
font-size: 11px;
font-weight: 700;
}
.tag.matched { background: #d4edda; color: #155724; }
.tag.manual { background: #e2d9f3; color: #4b2a85; }
.tag.missing { background: #f8d7da; color: #721c24; }
.empty-state {
text-align: center;
padding: 60px 20px;
color: #999;
}
.empty-state-icon { font-size: 42px; margin-bottom: 12px; }
/* User Management Styles */
.user-management-section {
background: white;
border-radius: 12px;
padding: 20px 24px;
margin-bottom: 20px;
box-shadow: 0 1px 4px rgba(0,0,0,0.06);
}
.management-header {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 20px;
}
.management-header h3 {
font-size: 18px;
color: #333;
}
.btn {
padding: 8px 16px;
border: none;
border-radius: 6px;
cursor: pointer;
font-size: 13px;
font-weight: 600;
transition: all 0.3s;
}
.btn-primary {
background: #667eea;
color: white;
}
.btn-primary:hover {
background: #5568d3;
}
.btn-danger {
background: #dc3545;
color: white;
font-size: 12px;
padding: 4px 8px;
}
.btn-danger:hover {
background: #c82333;
}
.users-table {
width: 100%;
border-collapse: collapse;
font-size: 14px;
}
.users-table th {
background: #f8f9fa;
padding: 12px;
text-align: left;
border-bottom: 2px solid #e0e0e0;
font-weight: 600;
color: #555;
}
.users-table td {
padding: 12px;
border-bottom: 1px solid #eee;
}
.users-table tbody tr:hover {
background: #f8f9fa;
}
.admin-badge {
display: inline-block;
padding: 3px 8px;
background: #ffc107;
color: #000;
border-radius: 4px;
font-size: 11px;
font-weight: 700;
}
.modal {
display: none;
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: rgba(0,0,0,0.5);
z-index: 1000;
align-items: center;
justify-content: center;
}
.modal.active {
display: flex;
}
.modal-content {
background: white;
border-radius: 12px;
padding: 30px;
width: 90%;
max-width: 500px;
box-shadow: 0 10px 40px rgba(0,0,0,0.2);
}
.modal-header {
font-size: 20px;
font-weight: 700;
margin-bottom: 20px;
color: #333;
}
.modal-close {
float: right;
font-size: 24px;
cursor: pointer;
color: #888;
}
.modal-close:hover {
color: #333;
}
.form-group {
margin-bottom: 15px;
}
.form-group label {
display: block;
margin-bottom: 5px;
font-weight: 600;
color: #333;
font-size: 14px;
}
.form-group input {
width: 100%;
padding: 10px;
border: 1px solid #ddd;
border-radius: 6px;
font-size: 14px;
}
.form-group input:focus {
outline: none;
border-color: #667eea;
box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
}
.modal-buttons {
display: flex;
gap: 10px;
justify-content: flex-end;
margin-top: 20px;
}
.modal-buttons button {
padding: 10px 20px;
border: none;
border-radius: 6px;
cursor: pointer;
font-weight: 600;
font-size: 14px;
}
.btn-cancel {
background: #e0e0e0;
color: #333;
}
.btn-cancel:hover {
background: #d0d0d0;
}
.message {
padding: 12px 16px;
border-radius: 6px;
margin-bottom: 15px;
font-size: 14px;
}
.message.success {
background: #d4edda;
color: #155724;
border: 1px solid #c3e6cb;
}
.message.error {
background: #f8d7da;
color: #721c24;
border: 1px solid #f5c6cb;
}
@media (max-width: 700px) {
.container { padding: 15px; }
.stats-table { font-size: 12px; }
.stats-table th, .stats-table td { padding: 7px 8px; }
.management-header {
flex-direction: column;
gap: 15px;
}
}
</style>
</head>
<body>
<nav class="navbar">
<div class="navbar-brand"> Admin Dashboard — Invoice Pro</div>
<div class="navbar-right">
<a href="{{ url_for('dashboard') }}">← Back to Dashboard</a>
<a href="{{ url_for('logout') }}">Logout</a>
</div>
</nav>
<div class="container">
<div class="header">
<h1>Admin Dashboard</h1>
<p>Manage users and view invoice processing statistics</p>
</div>
<!-- Tab Navigation -->
<div class="tabs">
<button class="tab-button active" onclick="switchTab('statistics')">📊 Statistics</button>
<button class="tab-button" onclick="switchTab('users')">👥 User Management</button>
</div>
<!-- Statistics Tab -->
<div id="statistics" class="tab-content active">
<div class="summary-grid">
<div class="summary-card">
<div class="summary-label">PDFs Today</div>
<div class="summary-value">{{ summary.today_pdfs }}</div>
</div>
<div class="summary-card">
<div class="summary-label">Active Users Today</div>
<div class="summary-value">{{ summary.today_active_users }}</div>
</div>
<div class="summary-card">
<div class="summary-label">Total PDFs Processed</div>
<div class="summary-value">{{ summary.total_pdfs }}</div>
</div>
<div class="summary-card">
<div class="summary-label">Total Items Seen</div>
<div class="summary-value">{{ summary.total_items }}</div>
</div>
<div class="summary-card">
<div class="summary-label">Item Codes Added Manually</div>
<div class="summary-value">{{ summary.total_manual }}</div>
</div>
<div class="summary-card">
<div class="summary-label">Items Still Missing a Code</div>
<div class="summary-value">{{ summary.total_missing }}</div>
</div>
</div>
{% if stats %}
{% for day in stats %}
<div class="day-block">
<h2>
{{ day.date }}
{% if day.date == today %}<span class="today-badge">TODAY</span>{% endif %}
</h2>
<table class="stats-table">
<thead>
<tr>
<th>User</th>
<th class="num">PDFs</th>
<th class="num">Items</th>
<th class="num">With Code</th>
<th class="num">Auto-Matched</th>
<th class="num">Manual</th>
<th class="num">Missing</th>
</tr>
</thead>
<tbody>
{% for u in day.users %}
<tr>
<td>{{ u.username }}</td>
<td class="num">{{ u.pdfs_processed }}</td>
<td class="num">{{ u.total_items }}</td>
<td class="num">{{ u.items_with_code }}</td>
<td class="num"><span class="tag matched">{{ u.items_auto_matched }}</span></td>
<td class="num"><span class="tag manual">{{ u.items_manual }}</span></td>
<td class="num">
{% if u.items_missing > 0 %}<span class="tag missing">{{ u.items_missing }}</span>
{% else %}0{% endif %}
</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
{% endfor %}
{% else %}
<div class="day-block">
<div class="empty-state">
<div class="empty-state-icon">📭</div>
<p>No invoices have been processed yet.</p>
</div>
</div>
{% endif %}
</div>
<!-- User Management Tab -->
<div id="users" class="tab-content">
<div id="messageContainer"></div>
<div class="user-management-section">
<div class="management-header">
<h3>👥 Registered Users</h3>
<button class="btn btn-primary" onclick="openAddUserModal()">+ Add New User</button>
</div>
{% if all_users %}
<table class="users-table">
<thead>
<tr>
<th>Username</th>
<th>Email</th>
<th>Registered</th>
<th>Last Login</th>
<th>Status</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
{% for user in all_users %}
<tr>
<td>
<strong>{{ user.username }}</strong>
{% if user.is_admin %}<span class="admin-badge">👑 ADMIN</span>{% endif %}
</td>
<td>{{ user.email }}</td>
<td>{{ user.created_at[:10] if user.created_at else 'N/A' }}</td>
<td>{{ user.last_login[:10] if user.last_login else 'Never' }}</td>
<td>
{% if user.is_active %}
<span style="color: #28a745;">✓ Active</span>
{% else %}
<span style="color: #dc3545;">✗ Inactive</span>
{% endif %}
</td>
<td>
{% if user.username != 'admin' %}
<button class="btn btn-danger" onclick="deleteUser('{{ user.username }}')">Delete</button>
{% else %}
<span style="color: #888; font-size: 12px;">Protected</span>
{% endif %}
</td>
</tr>
{% endfor %}
</tbody>
</table>
{% else %}
<div class="empty-state">
<div class="empty-state-icon">👥</div>
<p>No users registered yet.</p>
</div>
{% endif %}
</div>
</div>
</div>
<!-- Add User Modal -->
<div id="addUserModal" class="modal">
<div class="modal-content">
<span class="modal-close" onclick="closeAddUserModal()">&times;</span>
<div class="modal-header">Add New User</div>
<form onsubmit="submitAddUser(event)">
<div class="form-group">
<label>Username</label>
<input type="text" id="newUsername" required placeholder="Enter username">
</div>
<div class="form-group">
<label>Email</label>
<input type="email" id="newEmail" required placeholder="Enter email">
</div>
<div class="form-group">
<label>Password</label>
<input type="password" id="newPassword" required placeholder="Enter password">
</div>
<div class="form-group">
<label>Confirm Password</label>
<input type="password" id="newPasswordConfirm" required placeholder="Confirm password">
</div>
<div class="modal-buttons">
<button type="button" class="btn btn-cancel" onclick="closeAddUserModal()">Cancel</button>
<button type="submit" class="btn btn-primary">Add User</button>
</div>
</form>
</div>
</div>
<script>
function switchTab(tabName) {
// Hide all tabs
document.querySelectorAll('.tab-content').forEach(tab => tab.classList.remove('active'));
document.querySelectorAll('.tab-button').forEach(btn => btn.classList.remove('active'));
// Show selected tab
document.getElementById(tabName).classList.add('active');
event.target.classList.add('active');
}
function openAddUserModal() {
document.getElementById('addUserModal').classList.add('active');
}
function closeAddUserModal() {
document.getElementById('addUserModal').classList.remove('active');
document.getElementById('addUserForm')?.reset();
}
function submitAddUser(event) {
event.preventDefault();
const username = document.getElementById('newUsername').value;
const email = document.getElementById('newEmail').value;
const password = document.getElementById('newPassword').value;
const passwordConfirm = document.getElementById('newPasswordConfirm').value;
if (password !== passwordConfirm) {
showMessage('Passwords do not match!', 'error');
return;
}
fetch('/api/admin/add-user', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
username: username,
email: email,
password: password
})
})
.then(response => response.json())
.then(data => {
if (data.success) {
showMessage('User added successfully!', 'success');
closeAddUserModal();
setTimeout(() => location.reload(), 1500);
} else {
showMessage(data.message || 'Failed to add user', 'error');
}
})
.catch(error => {
showMessage('Error: ' + error.message, 'error');
});
}
function deleteUser(username) {
if (confirm(`Are you sure you want to delete user "${username}"? This cannot be undone.`)) {
fetch('/api/admin/delete-user', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
username: username
})
})
.then(response => response.json())
.then(data => {
if (data.success) {
showMessage('User deleted successfully!', 'success');
setTimeout(() => location.reload(), 1500);
} else {
showMessage(data.message || 'Failed to delete user', 'error');
}
})
.catch(error => {
showMessage('Error: ' + error.message, 'error');
});
}
}
function showMessage(message, type) {
const container = document.getElementById('messageContainer');
container.innerHTML = `<div class="message ${type}">${message}</div>`;
setTimeout(() => container.innerHTML = '', 5000);
}
</script>
</body>
</html>
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+796
View File
@@ -0,0 +1,796 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Invoice Extraction with Item Code Enrichment</title>
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
min-height: 100vh;
display: flex;
justify-content: center;
align-items: center;
padding: 20px;
}
.container {
background: white;
border-radius: 10px;
box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3);
max-width: 1000px;
width: 100%;
padding: 40px;
}
.header {
text-align: center;
margin-bottom: 40px;
}
.header h1 {
color: #333;
font-size: 28px;
margin-bottom: 10px;
}
.header p {
color: #666;
font-size: 16px;
}
.upload-section {
background: #f8f9fa;
border: 2px dashed #667eea;
border-radius: 8px;
padding: 40px;
text-align: center;
cursor: pointer;
transition: all 0.3s ease;
margin-bottom: 30px;
}
.upload-section:hover {
border-color: #764ba2;
background: #f0f2ff;
}
.upload-section.dragover {
border-color: #764ba2;
background: #e8ebff;
}
.upload-icon {
font-size: 48px;
margin-bottom: 15px;
}
.upload-section p {
color: #666;
font-size: 16px;
margin-bottom: 10px;
}
.upload-section .file-input {
display: none;
}
.upload-btn {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
color: white;
border: none;
padding: 12px 30px;
border-radius: 5px;
cursor: pointer;
font-size: 16px;
font-weight: 600;
transition: transform 0.2s;
}
.upload-btn:hover {
transform: translateY(-2px);
}
.upload-btn:active {
transform: translateY(0);
}
.button-group {
display: flex;
gap: 15px;
justify-content: center;
flex-wrap: wrap;
}
.secondary-btn {
background: #e9ecef;
color: #333;
border: none;
padding: 12px 30px;
border-radius: 5px;
cursor: pointer;
font-size: 16px;
font-weight: 600;
transition: all 0.2s;
}
.secondary-btn:hover {
background: #dee2e6;
transform: translateY(-2px);
}
.loading {
display: none;
text-align: center;
padding: 40px;
}
.spinner {
display: inline-block;
width: 40px;
height: 40px;
border: 4px solid #f3f3f3;
border-top: 4px solid #667eea;
border-radius: 50%;
animation: spin 1s linear infinite;
margin-bottom: 20px;
}
@keyframes spin {
0% { transform: rotate(0deg); }
100% { transform: rotate(360deg); }
}
.loading p {
color: #666;
font-size: 16px;
}
.results {
display: none;
margin-top: 40px;
}
.results.show {
display: block;
}
.result-header {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 20px;
padding-bottom: 15px;
border-bottom: 2px solid #e9ecef;
}
.result-header h2 {
color: #333;
font-size: 22px;
}
.success-badge {
background: #d4edda;
color: #155724;
padding: 8px 16px;
border-radius: 20px;
font-size: 14px;
font-weight: 600;
}
.error-badge {
background: #f8d7da;
color: #721c24;
padding: 8px 16px;
border-radius: 20px;
font-size: 14px;
font-weight: 600;
}
.metadata {
background: #f8f9fa;
padding: 15px;
border-radius: 5px;
margin-bottom: 20px;
font-size: 14px;
color: #666;
}
.metadata p {
margin: 8px 0;
}
.metadata strong {
color: #333;
}
.json-display {
background: #1e1e1e;
color: #d4d4d4;
padding: 20px;
border-radius: 5px;
overflow-x: auto;
font-family: 'Courier New', monospace;
font-size: 12px;
line-height: 1.6;
max-height: 600px;
overflow-y: auto;
}
.json-display::-webkit-scrollbar {
width: 8px;
height: 8px;
}
.json-display::-webkit-scrollbar-track {
background: #2d2d2d;
}
.json-display::-webkit-scrollbar-thumb {
background: #555;
border-radius: 4px;
}
.json-display::-webkit-scrollbar-thumb:hover {
background: #777;
}
.tabs {
display: flex;
gap: 10px;
margin-bottom: 20px;
border-bottom: 2px solid #e9ecef;
}
.tab {
padding: 12px 20px;
cursor: pointer;
border-bottom: 3px solid transparent;
color: #666;
font-weight: 600;
transition: all 0.2s;
}
.tab:hover {
color: #667eea;
}
.tab.active {
color: #667eea;
border-bottom-color: #667eea;
}
.tab-content {
display: none;
}
.tab-content.active {
display: block;
}
.items-table {
width: 100%;
border-collapse: collapse;
font-size: 14px;
}
.items-table th {
background: #f8f9fa;
padding: 12px;
text-align: left;
border-bottom: 2px solid #dee2e6;
color: #333;
font-weight: 600;
}
.items-table td {
padding: 12px;
border-bottom: 1px solid #dee2e6;
color: #666;
}
.items-table tbody tr:hover {
background: #f8f9fa;
}
.item-code-tag {
display: inline-block;
padding: 4px 8px;
border-radius: 3px;
font-size: 12px;
font-weight: 600;
}
.item-code-api {
background: #d1ecf1;
color: #0c5460;
}
.item-code-matched {
background: #d4edda;
color: #155724;
}
.item-code-missing {
background: #f8d7da;
color: #721c24;
}
.action-buttons {
display: flex;
gap: 10px;
justify-content: center;
margin-top: 30px;
flex-wrap: wrap;
}
.copy-btn {
background: #6c757d;
color: white;
border: none;
padding: 10px 20px;
border-radius: 5px;
cursor: pointer;
font-size: 14px;
font-weight: 600;
transition: all 0.2s;
}
.copy-btn:hover {
background: #5a6268;
}
.download-btn {
background: #28a745;
color: white;
border: none;
padding: 10px 20px;
border-radius: 5px;
cursor: pointer;
font-size: 14px;
font-weight: 600;
transition: all 0.2s;
}
.download-btn:hover {
background: #218838;
}
.error-message {
background: #f8d7da;
border: 1px solid #f5c6cb;
color: #721c24;
padding: 15px;
border-radius: 5px;
margin-top: 20px;
display: none;
}
.error-message.show {
display: block;
}
.success-message {
background: #d4edda;
border: 1px solid #c3e6cb;
color: #155724;
padding: 15px;
border-radius: 5px;
margin-top: 20px;
display: none;
}
.success-message.show {
display: block;
}
.info-message {
background: #d1ecf1;
border: 1px solid #bee5eb;
color: #0c5460;
padding: 15px;
border-radius: 5px;
margin-bottom: 20px;
}
@media (max-width: 768px) {
.container {
padding: 20px;
}
.header h1 {
font-size: 24px;
}
.upload-section {
padding: 30px 20px;
}
.button-group {
flex-direction: column;
}
.upload-btn, .secondary-btn {
width: 100%;
}
.tabs {
flex-wrap: wrap;
}
.items-table {
font-size: 12px;
}
.items-table th, .items-table td {
padding: 8px;
}
}
.stat {
display: inline-block;
margin: 0 15px;
padding: 10px 15px;
background: #f8f9fa;
border-radius: 5px;
color: #666;
font-size: 14px;
}
.stat strong {
color: #667eea;
font-size: 18px;
}
</style>
</head>
<body>
<div class="container">
<div class="header">
<h1>📋 Invoice Extraction & Item Code Enrichment</h1>
<p>Upload invoices and automatically extract item codes from your drug database</p>
</div>
<div class="upload-section" id="uploadSection">
<div class="upload-icon">📄</div>
<p>Drag and drop your invoice PDF here, or click to select</p>
<button class="upload-btn" onclick="document.getElementById('fileInput').click()">
Choose File
</button>
<input
type="file"
id="fileInput"
class="file-input"
accept=".pdf,.png,.jpg,.jpeg"
onchange="handleFileSelect(event)"
>
<p style="margin-top: 15px; color: #999; font-size: 12px;">
Supported: PDF, PNG, JPG, JPEG • Max: 100MB
</p>
</div>
<div class="loading" id="loading">
<div class="spinner"></div>
<p>Extracting invoice data...</p>
<p style="font-size: 12px; color: #999; margin-top: 10px;">This may take a few moments</p>
</div>
<div class="error-message" id="errorMessage"></div>
<div class="success-message" id="successMessage"></div>
<div class="results" id="results">
<div class="result-header">
<h2>Extraction Results</h2>
<div id="resultBadge"></div>
</div>
<div class="metadata">
<p><strong>Upload ID:</strong> <span id="uploadId">-</span></p>
<p><strong>Timestamp:</strong> <span id="timestamp">-</span></p>
<p><strong>Filename:</strong> <span id="filename">-</span></p>
<div style="margin-top: 10px;">
<span class="stat"><strong id="totalItems">0</strong> Total Items</span>
<span class="stat"><strong id="itemsWithCode">0</strong> With Codes</span>
<span class="stat"><strong id="itemsMatched">0</strong> Matched from DB</span>
</div>
</div>
<div class="tabs">
<div class="tab active" onclick="switchTab('headers')">📋 Header Fields</div>
<div class="tab" onclick="switchTab('items')">📦 Line Items</div>
<div class="tab" onclick="switchTab('raw')">📄 Raw JSON</div>
</div>
<div id="headers" class="tab-content active">
<div id="headerFields"></div>
</div>
<div id="items" class="tab-content">
<table class="items-table">
<thead>
<tr>
<th>Description</th>
<th>Quantity</th>
<th>Unit Price</th>
<th>Item Code</th>
<th>Source</th>
</tr>
</thead>
<tbody id="itemsTable">
</tbody>
</table>
</div>
<div id="raw" class="tab-content">
<div class="json-display" id="jsonDisplay"></div>
</div>
<div class="action-buttons">
<button class="copy-btn" onclick="copyToClipboard()">📋 Copy JSON</button>
<button class="download-btn" onclick="downloadJSON()">⬇️ Download JSON</button>
<button class="secondary-btn" onclick="resetForm()">🔄 Extract Another</button>
</div>
</div>
</div>
<script>
let lastExtractedData = null;
let selectedFile = null;
// Drag and drop
const uploadSection = document.getElementById('uploadSection');
uploadSection.addEventListener('dragover', (e) => {
e.preventDefault();
uploadSection.classList.add('dragover');
});
uploadSection.addEventListener('dragleave', () => {
uploadSection.classList.remove('dragover');
});
uploadSection.addEventListener('drop', (e) => {
e.preventDefault();
uploadSection.classList.remove('dragover');
const files = e.dataTransfer.files;
if (files.length > 0) {
handleFile(files[0]);
}
});
function handleFileSelect(event) {
const files = event.target.files;
if (files.length > 0) {
handleFile(files[0]);
}
}
function handleFile(file) {
const validTypes = ['application/pdf', 'image/png', 'image/jpeg'];
if (!validTypes.includes(file.type)) {
showError('Invalid file type. Please upload PDF, PNG, or JPG');
return;
}
if (file.size > 100 * 1024 * 1024) {
showError('File size exceeds 100MB limit');
return;
}
selectedFile = file;
uploadInvoice();
}
async function uploadInvoice() {
if (!selectedFile) return;
const formData = new FormData();
formData.append('file', selectedFile);
document.getElementById('loading').style.display = 'block';
document.getElementById('results').classList.remove('show');
hideMessages();
try {
const response = await fetch('/api/upload', {
method: 'POST',
body: formData
});
const result = await response.json();
if (response.ok && result.success) {
lastExtractedData = result.data;
displayResults(result.data);
showSuccess('Invoice extracted and enriched successfully!');
} else {
showError(result.error || 'Failed to extract invoice');
}
} catch (error) {
console.error('Error:', error);
showError('Network error. Please try again.');
} finally {
document.getElementById('loading').style.display = 'none';
}
}
function displayResults(data) {
// Update metadata
document.getElementById('uploadId').textContent = data._metadata?.upload_id || '-';
document.getElementById('timestamp').textContent = new Date(data._metadata?.upload_timestamp).toLocaleString();
document.getElementById('filename').textContent = data._metadata?.original_filename || '-';
// Calculate statistics
const items = data.items || [];
const itemsWithCode = items.filter(i => i.item_code).length;
const itemsMatched = items.filter(i => i.item_code_source === 'drug_list_match').length;
document.getElementById('totalItems').textContent = items.length;
document.getElementById('itemsWithCode').textContent = itemsWithCode;
document.getElementById('itemsMatched').textContent = itemsMatched;
// Set badge
const badge = document.getElementById('resultBadge');
if (items.length > 0 && itemsWithCode === items.length) {
badge.innerHTML = '<span class="success-badge">✓ All items have codes</span>';
} else if (itemsWithCode > 0) {
badge.innerHTML = `<span class="success-badge">✓ ${itemsWithCode}/${items.length} items have codes</span>`;
} else {
badge.innerHTML = '<span class="error-badge">⚠ Some items missing codes</span>';
}
// Display header fields
displayHeaderFields(data);
// Display items table
displayItemsTable(items);
// Display raw JSON
document.getElementById('jsonDisplay').textContent = JSON.stringify(data, null, 2);
// Show results section
document.getElementById('results').classList.add('show');
}
function displayHeaderFields(data) {
const headerContainer = document.getElementById('headerFields');
const headerFields = [
'invoice_id', 'date', 'seller_name', 'seller_gstin',
'buyer_name', 'buyer_gstin', 'total_quantity',
'total_taxable_amount', 'total_gst_amount', 'invoice_amount'
];
let html = '<table class="items-table" style="margin-bottom: 20px;"><tbody>';
headerFields.forEach(field => {
if (field in data) {
const value = data[field];
const displayValue = value !== null ? String(value) : 'N/A';
html += `
<tr>
<td style="font-weight: 600; width: 30%;">${field}</td>
<td>${displayValue}</td>
</tr>
`;
}
});
html += '</tbody></table>';
headerContainer.innerHTML = html;
}
function displayItemsTable(items) {
const tbody = document.getElementById('itemsTable');
tbody.innerHTML = '';
items.forEach((item, index) => {
const code = item.item_code || '-';
const source = item.item_code_source || 'unknown';
let sourceTag = 'item-code-missing';
let sourceText = 'Not Found';
if (source === 'api_extracted') {
sourceTag = 'item-code-api';
sourceText = 'API Extracted';
} else if (source === 'drug_list_match') {
sourceTag = 'item-code-matched';
sourceText = 'Matched from DB';
}
const row = document.createElement('tr');
row.innerHTML = `
<td>${item.description || '-'}</td>
<td>${item.quantity || '-'}</td>
<td>${item.unit_price || '-'}</td>
<td><strong>${code}</strong></td>
<td><span class="item-code-tag ${sourceTag}">${sourceText}</span></td>
`;
tbody.appendChild(row);
});
}
function switchTab(tabName) {
// Hide all tabs
document.querySelectorAll('.tab-content').forEach(tab => {
tab.classList.remove('active');
});
document.querySelectorAll('.tab').forEach(tab => {
tab.classList.remove('active');
});
// Show selected tab
document.getElementById(tabName).classList.add('active');
event.target.classList.add('active');
}
function copyToClipboard() {
const json = JSON.stringify(lastExtractedData, null, 2);
navigator.clipboard.writeText(json).then(() => {
showSuccess('JSON copied to clipboard!');
}).catch(err => {
showError('Failed to copy to clipboard');
});
}
function downloadJSON() {
const json = JSON.stringify(lastExtractedData, null, 2);
const blob = new Blob([json], { type: 'application/json' });
const url = window.URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = `invoice_${lastExtractedData._metadata?.upload_id || 'export'}.json`;
a.click();
window.URL.revokeObjectURL(url);
}
function resetForm() {
selectedFile = null;
lastExtractedData = null;
document.getElementById('fileInput').value = '';
document.getElementById('results').classList.remove('show');
hideMessages();
document.getElementById('uploadSection').style.display = 'block';
}
function showError(message) {
const errorDiv = document.getElementById('errorMessage');
errorDiv.textContent = '❌ ' + message;
errorDiv.classList.add('show');
}
function showSuccess(message) {
const successDiv = document.getElementById('successMessage');
successDiv.textContent = '✓ ' + message;
successDiv.classList.add('show');
setTimeout(() => {
successDiv.classList.remove('show');
}, 5000);
}
function hideMessages() {
document.getElementById('errorMessage').classList.remove('show');
document.getElementById('successMessage').classList.remove('show');
}
// Load config on page load
window.addEventListener('load', async () => {
try {
const response = await fetch('/api/config');
const config = await response.json();
console.log('✅ Application loaded', config);
} catch (error) {
console.error('Error loading config:', error);
}
});
</script>
</body>
</html>
+332
View File
@@ -0,0 +1,332 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Sign In</title>
<style>
:root {
--primary: #0284c7;
--primary-hover: #0369a1;
--primary-focus-ring: rgba(2, 132, 199, 0.2);
--surface: #ffffff;
--background: #f8fafc;
--border: #e2e8f0;
--border-focus: #0284c7;
--text-primary: #0f172a;
--text-secondary: #475569;
--text-muted: #64748b;
--danger: #dc2626;
--danger-bg: #fef2f2;
--danger-border: #fecaca;
--success: #059669;
--success-bg: #ecfdf5;
--success-border: #a7f3d0;
--radius: 8px;
}
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
background-color: var(--background);
color: var(--text-primary);
min-height: 100vh;
display: flex;
align-items: center;
justify-content: center;
padding: 24px 16px;
line-height: 1.5;
}
.auth-card {
background-color: var(--surface);
border: 1px solid var(--border);
border-radius: var(--radius);
box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.05), 0 2px 4px -2px rgba(0, 0, 0, 0.05);
width: 100%;
max-width: 420px;
padding: 40px 32px;
}
/* Dedicated Logo Placeholder Area */
.logo-placeholder-container {
display: flex;
justify-content: center;
margin-bottom: 24px;
}
.logo-placeholder {
display: flex;
align-items: center;
justify-content: center;
margin-bottom: 8px;
}
.logo-placeholder img {
max-height: 72px;
height: 68px;
width: auto;
object-fit: contain;
display: block;
}
.auth-header {
text-align: center;
margin-bottom: 32px;
}
.auth-header h1 {
font-size: 20px;
font-weight: 600;
color: var(--text-primary);
letter-spacing: -0.01em;
margin-bottom: 6px;
}
.auth-header p {
font-size: 14px;
color: var(--text-secondary);
}
.form-group {
margin-bottom: 20px;
}
label {
display: block;
margin-bottom: 6px;
color: var(--text-primary);
font-weight: 500;
font-size: 13px;
}
input[type="text"],
input[type="password"] {
width: 100%;
padding: 10px 14px;
border: 1px solid #cbd5e1;
border-radius: 6px;
font-size: 14px;
color: var(--text-primary);
background-color: #ffffff;
transition: border-color 0.15s ease, box-shadow 0.15s ease;
font-family: inherit;
}
input[type="text"]:focus,
input[type="password"]:focus {
outline: none;
border-color: var(--border-focus);
box-shadow: 0 0 0 3px var(--primary-focus-ring);
}
.submit-btn {
width: 100%;
padding: 11px 16px;
background-color: var(--primary);
color: #ffffff;
border: none;
border-radius: 6px;
font-size: 14px;
font-weight: 600;
cursor: pointer;
transition: background-color 0.15s ease;
margin-top: 8px;
}
.submit-btn:hover {
background-color: var(--primary-hover);
}
.submit-btn:disabled {
opacity: 0.6;
cursor: not-allowed;
}
.links-row {
display: flex;
justify-content: space-between;
align-items: center;
margin-top: 16px;
font-size: 13px;
}
.links-row a,
.auth-footer a {
color: var(--primary);
text-decoration: none;
font-weight: 500;
}
.links-row a:hover,
.auth-footer a:hover {
text-decoration: underline;
}
.auth-footer {
text-align: center;
margin-top: 28px;
padding-top: 20px;
border-top: 1px solid var(--border);
font-size: 13px;
color: var(--text-secondary);
}
.message {
padding: 10px 14px;
border-radius: 6px;
margin-bottom: 20px;
font-size: 13px;
display: none;
line-height: 1.4;
}
.message.error {
background-color: var(--danger-bg);
color: var(--danger);
border: 1px solid var(--danger-border);
display: block;
}
.message.success {
background-color: var(--success-bg);
color: var(--success);
border: 1px solid var(--success-border);
display: block;
}
.loading {
display: none;
text-align: center;
color: var(--text-secondary);
font-size: 13px;
margin-bottom: 12px;
}
.spinner {
display: inline-block;
width: 14px;
height: 14px;
border: 2px solid var(--border);
border-top: 2px solid var(--primary);
border-radius: 50%;
animation: spin 0.6s linear infinite;
margin-right: 8px;
vertical-align: middle;
}
@keyframes spin {
to { transform: rotate(360deg); }
}
@media (max-width: 480px) {
.auth-card {
padding: 28px 20px;
}
}
</style>
</head>
<body>
<div class="auth-card">
<div class="logo-placeholder-container">
<div class="logo-placeholder" id="logoPlaceholder">
<img src="{{ url_for('static', filename='logo.png') }}" alt="Logo">
</div>
</div>
<div class="auth-header">
<h1>Sign In</h1>
<p>Access your management dashboard</p>
</div>
<div id="message" class="message"></div>
<form id="loginForm">
<div class="form-group">
<label for="username">Username</label>
<input type="text" id="username" name="username" placeholder="Enter username" autocomplete="username" required>
</div>
<div class="form-group">
<label for="password">Password</label>
<input type="password" id="password" name="password" placeholder="Enter password" autocomplete="current-password" required>
</div>
<div class="loading" id="loading">
<span class="spinner"></span>
Authenticating...
</div>
<button type="submit" class="submit-btn" id="submitBtn">Sign In</button>
</form>
<div class="links-row">
<a href="#" onclick="showForgot(event)">Forgot password?</a>
</div>
<div class="auth-footer">
Do not have an account? <a href="/register">Register</a>
</div>
</div>
<script>
document.getElementById('loginForm').addEventListener('submit', async (e) => {
e.preventDefault();
const username = document.getElementById('username').value.trim();
const password = document.getElementById('password').value;
const messageDiv = document.getElementById('message');
const loading = document.getElementById('loading');
const submitBtn = document.getElementById('submitBtn');
if (!username || !password) {
showMessage('Please fill in all fields', 'error');
return;
}
loading.style.display = 'block';
submitBtn.disabled = true;
try {
const response = await fetch('/login', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ username, password })
});
const data = await response.json();
if (response.ok) {
showMessage('Sign in successful. Redirecting...', 'success');
setTimeout(() => {
window.location.href = '/dashboard';
}, 800);
} else {
showMessage(data.message || 'Invalid username or password', 'error');
}
} catch (error) {
showMessage('Connection error. Please try again.', 'error');
} finally {
loading.style.display = 'none';
submitBtn.disabled = false;
}
});
function showMessage(text, type) {
const messageDiv = document.getElementById('message');
messageDiv.textContent = text;
messageDiv.className = `message ${type}`;
}
function showForgot(e) {
if (e) e.preventDefault();
alert('Password reset assistance is managed by the system administrator. Please contact your administrative team.');
}
</script>
</body>
</html>
+367
View File
@@ -0,0 +1,367 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Create Account</title>
<style>
:root {
--primary: #0284c7;
--primary-hover: #0369a1;
--primary-focus-ring: rgba(2, 132, 199, 0.2);
--surface: #ffffff;
--background: #f8fafc;
--border: #e2e8f0;
--border-focus: #0284c7;
--text-primary: #0f172a;
--text-secondary: #475569;
--text-muted: #64748b;
--danger: #dc2626;
--danger-bg: #fef2f2;
--danger-border: #fecaca;
--success: #059669;
--success-bg: #ecfdf5;
--success-border: #a7f3d0;
--radius: 8px;
}
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
background-color: var(--background);
color: var(--text-primary);
min-height: 100vh;
display: flex;
align-items: center;
justify-content: center;
padding: 32px 16px;
line-height: 1.5;
}
.auth-card {
background-color: var(--surface);
border: 1px solid var(--border);
border-radius: var(--radius);
box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.05), 0 2px 4px -2px rgba(0, 0, 0, 0.05);
width: 100%;
max-width: 480px;
padding: 40px 32px;
}
/* Dedicated Logo Placeholder Area */
.logo-placeholder-container {
display: flex;
justify-content: center;
margin-bottom: 24px;
}
.logo-placeholder {
display: flex;
align-items: center;
justify-content: center;
margin-bottom: 8px;
}
.logo-placeholder img {
max-height: 72px;
height: 68px;
width: auto;
object-fit: contain;
display: block;
}
.auth-header {
text-align: center;
margin-bottom: 28px;
}
.auth-header h1 {
font-size: 20px;
font-weight: 600;
color: var(--text-primary);
letter-spacing: -0.01em;
margin-bottom: 6px;
}
.auth-header p {
font-size: 14px;
color: var(--text-secondary);
}
.form-group {
margin-bottom: 18px;
}
.form-row {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 16px;
}
label {
display: block;
margin-bottom: 6px;
color: var(--text-primary);
font-weight: 500;
font-size: 13px;
}
input[type="text"],
input[type="email"],
input[type="password"] {
width: 100%;
padding: 10px 14px;
border: 1px solid #cbd5e1;
border-radius: 6px;
font-size: 14px;
color: var(--text-primary);
background-color: #ffffff;
transition: border-color 0.15s ease, box-shadow 0.15s ease;
font-family: inherit;
}
input[type="text"]:focus,
input[type="email"]:focus,
input[type="password"]:focus {
outline: none;
border-color: var(--border-focus);
box-shadow: 0 0 0 3px var(--primary-focus-ring);
}
.helper-text {
font-size: 12px;
color: var(--text-muted);
margin-top: 5px;
}
.submit-btn {
width: 100%;
padding: 11px 16px;
background-color: var(--primary);
color: #ffffff;
border: none;
border-radius: 6px;
font-size: 14px;
font-weight: 600;
cursor: pointer;
transition: background-color 0.15s ease;
margin-top: 10px;
}
.submit-btn:hover {
background-color: var(--primary-hover);
}
.submit-btn:disabled {
opacity: 0.6;
cursor: not-allowed;
}
.auth-footer {
text-align: center;
margin-top: 28px;
padding-top: 20px;
border-top: 1px solid var(--border);
font-size: 13px;
color: var(--text-secondary);
}
.auth-footer a {
color: var(--primary);
text-decoration: none;
font-weight: 500;
}
.auth-footer a:hover {
text-decoration: underline;
}
.message {
padding: 10px 14px;
border-radius: 6px;
margin-bottom: 20px;
font-size: 13px;
display: none;
line-height: 1.4;
}
.message.error {
background-color: var(--danger-bg);
color: var(--danger);
border: 1px solid var(--danger-border);
display: block;
}
.message.success {
background-color: var(--success-bg);
color: var(--success);
border: 1px solid var(--success-border);
display: block;
}
.loading {
display: none;
text-align: center;
color: var(--text-secondary);
font-size: 13px;
margin-bottom: 12px;
}
.spinner {
display: inline-block;
width: 14px;
height: 14px;
border: 2px solid var(--border);
border-top: 2px solid var(--primary);
border-radius: 50%;
animation: spin 0.6s linear infinite;
margin-right: 8px;
vertical-align: middle;
}
@keyframes spin {
to { transform: rotate(360deg); }
}
@media (max-width: 480px) {
.auth-card {
padding: 28px 20px;
}
.form-row {
grid-template-columns: 1fr;
gap: 0;
}
}
</style>
</head>
<body>
<div class="auth-card">
<div class="logo-placeholder-container">
<div class="logo-placeholder" id="logoPlaceholder">
<img src="{{ url_for('static', filename='logo.png') }}" alt="Logo">
</div>
</div>
<div class="auth-header">
<h1>Create Account</h1>
<p>Register a new user account</p>
</div>
<div id="message" class="message"></div>
<form id="registerForm">
<div class="form-row">
<div class="form-group">
<label for="username">Username</label>
<input type="text" id="username" name="username" placeholder="Choose username" autocomplete="username" required>
</div>
<div class="form-group">
<label for="email">Email</label>
<input type="email" id="email" name="email" placeholder="user@domain.com" autocomplete="email" required>
</div>
</div>
<div class="form-row">
<div class="form-group">
<label for="password">Password</label>
<input type="password" id="password" name="password" placeholder="Minimum 6 characters" autocomplete="new-password" required>
<div class="helper-text">Minimum 6 characters</div>
</div>
<div class="form-group">
<label for="confirm">Confirm Password</label>
<input type="password" id="confirm" name="confirm_password" placeholder="Confirm password" autocomplete="new-password" required>
</div>
</div>
<div class="loading" id="loading">
<span class="spinner"></span>
Creating account...
</div>
<button type="submit" class="submit-btn" id="submitBtn">Register</button>
</form>
<div class="auth-footer">
Already have an account? <a href="/login">Sign In</a>
</div>
</div>
<script>
document.getElementById('registerForm').addEventListener('submit', async (e) => {
e.preventDefault();
const username = document.getElementById('username').value.trim();
const email = document.getElementById('email').value.trim();
const password = document.getElementById('password').value;
const confirmPassword = document.getElementById('confirm').value;
const messageDiv = document.getElementById('message');
const loading = document.getElementById('loading');
const submitBtn = document.getElementById('submitBtn');
// Validation
if (!username || !email || !password || !confirmPassword) {
showMessage('Please fill in all fields', 'error');
return;
}
if (password.length < 6) {
showMessage('Password must be at least 6 characters', 'error');
return;
}
if (password !== confirmPassword) {
showMessage('Passwords do not match', 'error');
return;
}
if (!email.includes('@')) {
showMessage('Please enter a valid email address', 'error');
return;
}
loading.style.display = 'block';
submitBtn.disabled = true;
try {
const response = await fetch('/register', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
username,
email,
password,
confirm_password: confirmPassword
})
});
const data = await response.json();
if (response.ok) {
showMessage('Account created successfully. Redirecting to sign in...', 'success');
setTimeout(() => {
window.location.href = '/login';
}, 1200);
} else {
showMessage(data.message || 'Registration failed', 'error');
}
} catch (error) {
showMessage('Connection error. Please try again.', 'error');
} finally {
loading.style.display = 'none';
submitBtn.disabled = false;
}
});
function showMessage(msg, type) {
const messageDiv = document.getElementById('message');
messageDiv.textContent = msg;
messageDiv.className = `message ${type}`;
}
</script>
</body>
</html>
BIN
View File
Binary file not shown.
+40
View File
@@ -0,0 +1,40 @@
import requests
api_key = "971dcea6c47445f6f7405fa2d14e116b1d81dae6c10330571e8d4220c013b523"
file_path = "test.pdf"
# Try with Bearer
try:
with open(file_path, 'rb') as f:
response = requests.post(
'https://aiinfinite.in/process-invoice',
files={'file': f},
headers={'Authorization': f'Bearer {api_key}'}
)
print(f"Bearer: {response.status_code}")
except Exception as e:
print(f"Bearer error: {e}")
# Try without Bearer
try:
with open(file_path, 'rb') as f:
response = requests.post(
'https://aiinfinite.in/process-invoice',
files={'file': f},
headers={'Authorization': api_key}
)
print(f"Key only: {response.status_code}")
except Exception as e:
print(f"Key only error: {e}")
# Try as X-API-Key
try:
with open(file_path, 'rb') as f:
response = requests.post(
'https://aiinfinite.in/process-invoice',
files={'file': f},
headers={'X-API-Key': api_key}
)
print(f"X-API-Key: {response.status_code}")
except Exception as e:
print(f"X-API-Key error: {e}")
+351
View File
@@ -0,0 +1,351 @@
#!/usr/bin/env python3
"""
Comprehensive End-to-End Test for DMH Pharmacy Dashboard:
PO Number Approval & Item Code Management
Tests all 13 steps defined in Section 11.
"""
import os
import sys
import json
import sqlite3
import threading
from http.server import HTTPServer, BaseHTTPRequestHandler
from werkzeug.security import generate_password_hash
# Ensure test uses app.py
from app import app, get_db, ensure_po_approval_tables
# Setup Mock Webhook Server to capture n8n webhook calls
webhook_requests = []
webhook_response_code = 200
class MockWebhookHandler(BaseHTTPRequestHandler):
def do_POST(self):
content_length = int(self.headers.get('Content-Length', 0))
post_data = self.rfile.read(content_length)
try:
payload = json.loads(post_data.decode('utf-8'))
except Exception:
payload = post_data.decode('utf-8')
webhook_requests.append({
'path': self.path,
'headers': dict(self.headers),
'payload': payload
})
self.send_response(webhook_response_code)
self.send_header('Content-Type', 'application/json')
self.end_headers()
self.wfile.write(json.dumps({'received': True, 'status': 'ok'}).encode('utf-8'))
def log_message(self, format, *args):
pass # Quiet logging
def start_mock_webhook_server(port=9988):
server = HTTPServer(('127.0.0.1', port), MockWebhookHandler)
thread = threading.Thread(target=server.serve_forever, daemon=True)
thread.start()
return server
def run_tests():
global webhook_response_code
print("=" * 70)
print("🧪 STARTING DMH PO NUMBER APPROVAL & ITEM CODE VERIFICATION")
print("=" * 70)
# 1. Start mock webhook server
mock_port = 9988
mock_server = start_mock_webhook_server(mock_port)
mock_webhook_url = f"http://127.0.0.1:{mock_port}/webhook/dmh-po-approval"
os.environ['DMH_PO_APPROVAL_WEBHOOK_URL'] = mock_webhook_url
print(f"✅ Mock n8n Webhook Server running on {mock_webhook_url}")
# 2. Setup test client and test user
app.config['TESTING'] = True
client = app.test_client()
# Create/ensure a test pharmacy user in DB
conn = get_db()
cursor = conn.cursor()
cursor.execute("SELECT id FROM users WHERE username = 'pharmacy_tester'")
existing_user = cursor.fetchone()
if not existing_user:
cursor.execute(
"INSERT INTO users (username, email, password, is_active, is_admin) VALUES (?, ?, ?, 1, 0)",
('pharmacy_tester', 'tester@dmh.org', generate_password_hash('TestPass123!'))
)
conn.commit()
user_id = cursor.lastrowid
else:
user_id = existing_user['id']
conn.close()
# Log in session for test client
with client.session_transaction() as sess:
sess['user_id'] = user_id
sess['username'] = 'pharmacy_tester'
print(f"✅ Authenticated as test user (id={user_id}, username='pharmacy_tester')")
# -------------------------------------------------------------
# Step 1 & 2: Condition 3 identification & Auto-submission
# (PO number missing/empty AND item code missing from invoice)
# -------------------------------------------------------------
print("\n--- Testing Step 1 & 2: Condition 3 Identification ---")
mock_invoice_data = {
'invoice_id': 'INV-TEST-2026-001',
'invoice_number': 'INV-TEST-2026-001',
'vendor_name': 'Apex Pharma Distributors',
'invoice_date': '2026-11-20',
'po_number': '', # MISSING PO
'items': [
{
'description': 'UNKNOWN MEDICATION XYZ 500MG',
'quantity': 100,
'unit_price': 45.50,
'item_code': '',
'item_code_source': 'not_found', # MISSING ITEM CODE
'in_csv': False
}
]
}
# Store extraction in extractions table
conn = get_db()
cursor = conn.cursor()
cursor.execute(
"INSERT INTO extractions (user_id, invoice_id, filename, extraction_data) VALUES (?, ?, ?, ?)",
(user_id, 'INV-TEST-2026-001', 'test_invoice_cond3.pdf', json.dumps(mock_invoice_data))
)
conn.commit()
extraction_id = cursor.lastrowid
conn.close()
# Submit to PO approval queue (mimics upload auto-submit logic)
submit_resp = client.post('/api/po-approval/submit', json={
'extraction_id': extraction_id,
'invoice_number': 'INV-TEST-2026-001',
'vendor_name': 'Apex Pharma Distributors',
'invoice_date': '2026-11-20',
'invoice_filename': 'test_invoice_cond3.pdf',
'po_number_original': ''
})
assert submit_resp.status_code in (200, 201), f"Submit failed: {submit_resp.data}"
submit_data = submit_resp.get_json()
po_invoice_id = submit_data['po_invoice_id']
print(f"✅ Condition 3 record queued in po_approval_invoices with ID: {po_invoice_id}")
# Test duplicate submission prevention
dup_resp = client.post('/api/po-approval/submit', json={
'extraction_id': extraction_id,
'invoice_number': 'INV-TEST-2026-001',
'vendor_name': 'Apex Pharma Distributors',
'invoice_date': '2026-11-20',
'invoice_filename': 'test_invoice_cond3.pdf',
'po_number_original': ''
})
dup_data = dup_resp.get_json()
assert dup_data.get('duplicate') is True and dup_data.get('po_invoice_id') == po_invoice_id
print("✅ Duplicate submission prevention verified")
# -------------------------------------------------------------
# Step 3: Pending PO Number Approval List
# -------------------------------------------------------------
print("\n--- Testing Step 3: Pending PO Approval Listing ---")
pending_resp = client.get('/api/po-approval/pending')
assert pending_resp.status_code == 200
pending_list = pending_resp.get_json()['data']
matching_pending = [p for p in pending_list if p['id'] == po_invoice_id]
assert len(matching_pending) == 1, "Invoice not found in pending list!"
p_item = matching_pending[0]
assert p_item['invoice_number'] == 'INV-TEST-2026-001'
assert p_item['vendor_name'] == 'Apex Pharma Distributors'
assert p_item['approval_status'] == 'pending'
print(f"✅ Invoice correctly listed in Pending PO Approvals ({p_item['invoice_number']})")
# -------------------------------------------------------------
# Step 4: Invoice Details and Line Items
# -------------------------------------------------------------
print("\n--- Testing Step 4: Invoice Details & Items ---")
detail_resp = client.get(f'/api/po-approval/invoice/{po_invoice_id}')
assert detail_resp.status_code == 200
detail_data = detail_resp.get_json()
assert detail_data['data']['invoice_number'] == 'INV-TEST-2026-001'
assert len(detail_data['items']) == 1
assert detail_data['items'][0]['description'] == 'UNKNOWN MEDICATION XYZ 500MG'
print(f"✅ Invoice details retrieved with {len(detail_data['items'])} line items")
# -------------------------------------------------------------
# Step 5 & 6: Validation, Manual PO Entry and Approval
# -------------------------------------------------------------
print("\n--- Testing Step 5 & 6: Validation and Manual PO Approval ---")
# Test empty PO rejection
empty_po_resp = client.post(f'/api/po-approval/{po_invoice_id}/approve', json={'po_number': ' '})
assert empty_po_resp.status_code == 400
print("✅ Empty PO Number correctly rejected (HTTP 400)")
# Clear captured webhook requests
webhook_requests.clear()
webhook_response_code = 200
# Submit valid PO approval
test_po_num = "PO-DMH-98765"
approve_resp = client.post(f'/api/po-approval/{po_invoice_id}/approve', json={'po_number': test_po_num})
assert approve_resp.status_code == 200
appr_res = approve_resp.get_json()
assert appr_res['success'] is True
assert appr_res['approval_status'] == 'approved'
assert appr_res['webhook_status'] == 'success'
print(f"✅ Approval submitted successfully with PO: {test_po_num}")
# -------------------------------------------------------------
# Step 7 & 8: Verify DB persistence & Audit fields
# -------------------------------------------------------------
print("\n--- Testing Step 7 & 8: Database Persistence & User Audit ---")
conn = get_db()
cursor = conn.cursor()
cursor.execute("SELECT * FROM po_approval_invoices WHERE id = ?", (po_invoice_id,))
inv_row = cursor.fetchone()
assert inv_row['approval_status'] == 'approved'
assert inv_row['po_number_approved'] == test_po_num
assert inv_row['approved_by'] == user_id
assert inv_row['approved_at'] is not None
cursor.execute("SELECT * FROM po_approval_history WHERE po_invoice_id = ?", (po_invoice_id,))
hist_rows = cursor.fetchall()
assert len(hist_rows) >= 1
latest_hist = hist_rows[-1]
assert latest_hist['po_number_approved'] == test_po_num
assert latest_hist['approved_by'] == user_id
assert latest_hist['approved_by_username'] == 'pharmacy_tester'
assert latest_hist['webhook_status'] == 'success'
conn.close()
print(f"✅ Database verified: PO={inv_row['po_number_approved']}, user_id={inv_row['approved_by']}, time={inv_row['approved_at']}")
# -------------------------------------------------------------
# Step 9 & 10: Verify n8n Webhook Trigger & Payload
# -------------------------------------------------------------
print("\n--- Testing Step 9 & 10: n8n Webhook Payload & Status ---")
assert len(webhook_requests) == 1, f"Expected 1 webhook call, got {len(webhook_requests)}"
wh_call = webhook_requests[0]
expected_payload = {
"event": "po_number_approved",
"invoice_id": po_invoice_id,
"invoice_number": "INV-TEST-2026-001",
"approved_po_number": test_po_num,
"approved_by": user_id,
"approval_status": "approved"
}
assert wh_call['payload'] == expected_payload, f"Payload mismatch: {wh_call['payload']} vs {expected_payload}"
print(f"✅ Webhook payload verified: {json.dumps(wh_call['payload'], indent=2)}")
# Test duplicate approval blocked
dup_appr = client.post(f'/api/po-approval/{po_invoice_id}/approve', json={'po_number': 'PO-ANOTHER'})
assert dup_appr.status_code == 409
print("✅ Duplicate approval prevented (HTTP 409)")
# -------------------------------------------------------------
# Step 11: PO Approval History Audit Trail
# -------------------------------------------------------------
print("\n--- Testing Step 11: PO Approval History Verification ---")
hist_resp = client.get('/api/po-approval/history?status=approved')
assert hist_resp.status_code == 200
hist_list = hist_resp.get_json()['data']
found_in_history = [h for h in hist_list if h['po_invoice_id'] == po_invoice_id]
assert len(found_in_history) >= 1
print(f"✅ History listing verified ({len(found_in_history)} record(s) for this invoice)")
# -------------------------------------------------------------
# Step 12: Webhook Failure and Safe Retry
# -------------------------------------------------------------
print("\n--- Testing Step 12: Webhook Failure & Retry Logic ---")
# Create another test invoice for failure test
conn = get_db()
cursor = conn.cursor()
cursor.execute(
"INSERT INTO extractions (user_id, invoice_id, filename, extraction_data) VALUES (?, ?, ?, ?)",
(user_id, 'INV-TEST-FAIL-002', 'test_fail.pdf', json.dumps(mock_invoice_data))
)
fail_ext_id = cursor.lastrowid
cursor.execute('''
INSERT INTO po_approval_invoices
(extraction_id, invoice_number, vendor_name, invoice_date, invoice_filename, po_number_original)
VALUES (?, 'INV-TEST-FAIL-002', 'Beta Med', '2026-11-21', 'test_fail.pdf', '')
''', (fail_ext_id,))
fail_po_id = cursor.lastrowid
conn.commit()
conn.close()
# Simulate webhook failure (HTTP 500 from webhook server)
webhook_response_code = 500
fail_approve_resp = client.post(f'/api/po-approval/{fail_po_id}/approve', json={'po_number': 'PO-FAIL-111'})
assert fail_approve_resp.status_code == 200
fail_data = fail_approve_resp.get_json()
assert fail_data['approval_status'] == 'approved'
assert fail_data['webhook_status'] == 'failed'
print("✅ Approved record preserved even when webhook returns HTTP 500 (safe failure)")
# Retrieve history record ID for retry
conn = get_db()
cursor = conn.cursor()
cursor.execute("SELECT id FROM po_approval_history WHERE po_invoice_id = ?", (fail_po_id,))
fail_hist_id = cursor.fetchone()['id']
conn.close()
# Test retry with webhook server restored to HTTP 200
webhook_response_code = 200
retry_resp = client.post(f'/api/po-approval/{fail_hist_id}/retry-webhook')
assert retry_resp.status_code == 200
retry_data = retry_resp.get_json()
assert retry_data['webhook_status'] == 'success'
print("✅ Webhook retry succeeded and updated history status to 'success'")
# Test rejection flow
conn = get_db()
cursor = conn.cursor()
cursor.execute('''
INSERT INTO po_approval_invoices
(extraction_id, invoice_number, vendor_name, invoice_date, invoice_filename, po_number_original)
VALUES (?, 'INV-TEST-REJECT-003', 'Gamma Supplies', '2026-11-22', 'test_rej.pdf', '')
''', (fail_ext_id,))
rej_po_id = cursor.lastrowid
conn.commit()
conn.close()
rej_resp = client.post(f'/api/po-approval/{rej_po_id}/reject', json={'notes': 'Wrong vendor invoice'})
assert rej_resp.status_code == 200
assert rej_resp.get_json()['approval_status'] == 'rejected'
print("✅ Rejection flow verified")
# -------------------------------------------------------------
# Step 13: Existing Item Code Management Logic Continues Working
# -------------------------------------------------------------
print("\n--- Testing Step 13: Existing Item Code Management ---")
cat_resp = client.get('/api/catalog?per_page=5')
assert cat_resp.status_code == 200
cat_data = cat_resp.get_json()
assert cat_data['success'] is True
assert cat_data['total'] > 0
print(f"✅ Catalog browsing active: {cat_data['total']} item codes available")
auto_resp = client.get('/api/catalog/autocomplete?q=para')
assert auto_resp.status_code == 200
auto_data = auto_resp.get_json()
assert auto_data['success'] is True
print(f"✅ Catalog autocomplete active: returned {len(auto_data['data'])} suggestions")
cats_resp = client.get('/api/catalog/categories')
assert cats_resp.status_code == 200
print(f"✅ Catalog categories active: {len(cats_resp.get_json()['data'])} categories")
pending_items_resp = client.get('/api/pending-items')
assert pending_items_resp.status_code == 200
print("✅ Existing Item Code pending approval queue active")
print("\n" + "=" * 70)
print("🎉 ALL 13 TEST STEPS PASSED SUCCESSFULLY!")
print("=" * 70)
if __name__ == '__main__':
run_tests()
File diff suppressed because it is too large Load Diff
Binary file not shown.
BIN
View File
Binary file not shown.