Files
2026-10-13 16:00:15 +05:30

1465 lines
52 KiB
Python

"""
Invoice Extraction with Item Code Enrichment - Pro Version
WITH USER AUTHENTICATION & DATABASE
Features:
- User Registration & Login
- Database Integration (SQLite)
- Modern Professional UI
- User Sessions
- Secure Password Handling
"""
from flask import Flask, render_template, request, jsonify, redirect, url_for, session
from flask_cors import CORS
from werkzeug.utils import secure_filename
from werkzeug.security import generate_password_hash, check_password_hash
import os
import re
import copy
import requests
import json
import csv
import threading
import pandas as pd
from datetime import datetime, timedelta
import secrets
from difflib import SequenceMatcher
import logging
import sqlite3
from functools import wraps
# ================================================================
# ✅ FLASK SETUP
# ================================================================
app = Flask(__name__)
CORS(app)
# Configuration
app.secret_key = os.getenv('SECRET_KEY', 'your-secret-key-here')
app.config['UPLOAD_FOLDER'] = 'uploads'
app.config['MAX_CONTENT_LENGTH'] = 100 * 1024 * 1024
app.config['PERMANENT_SESSION_LIFETIME'] = timedelta(days=7)
# Create required folders
for folder in ['uploads', 'logs', 'templates']:
if not os.path.exists(folder):
os.makedirs(folder)
app.config['UPLOAD_FOLDER'] = 'uploads'
# Setup logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
# ================================================================
# ✅ DATABASE SETUP
# ================================================================
DATABASE = 'users.db'
def get_db():
"""Get database connection"""
conn = sqlite3.connect(DATABASE)
conn.row_factory = sqlite3.Row
return conn
def init_db():
"""Initialize database with tables"""
if not os.path.exists(DATABASE):
conn = get_db()
cursor = conn.cursor()
# Users table
cursor.execute('''
CREATE TABLE users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
username TEXT UNIQUE NOT NULL,
email TEXT UNIQUE NOT NULL,
password TEXT NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
last_login TIMESTAMP,
is_active INTEGER DEFAULT 1,
is_admin INTEGER DEFAULT 0
)
''')
# Extractions table
cursor.execute('''
CREATE TABLE extractions (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id INTEGER NOT NULL,
invoice_id TEXT,
filename TEXT,
extraction_data TEXT,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (user_id) REFERENCES users(id)
)
''')
conn.commit()
conn.close()
print("✅ Database initialized")
def ensure_catalog_table():
"""Create the item_codes catalog table if it doesn't exist yet.
Safe to call every startup, unlike init_db() which only runs once."""
conn = get_db()
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()
def import_csv_into_catalog_if_empty():
"""One-time convenience: if the catalog table is empty and drug_list.csv
exists, seed the catalog from it so existing data isn't lost when moving
from the CSV-only workflow to the DB-backed catalog."""
conn = get_db()
cursor = conn.cursor()
cursor.execute('SELECT COUNT(*) AS c FROM item_codes')
count = cursor.fetchone()['c']
conn.close()
if count > 0 or not os.path.exists('drug_list.csv'):
return
try:
df = pd.read_csv('drug_list.csv')
if 'item_code' not in df.columns or 'name' not in df.columns:
return
has_category = 'category' in df.columns
conn = get_db()
cursor = conn.cursor()
imported = 0
for _, row in df.iterrows():
code = str(row['item_code']).strip()
name = str(row['name']).strip()
if not code or not name:
continue
category = str(row['category']).strip() if has_category and str(row.get('category', '')).strip() else 'Uncategorized'
try:
cursor.execute(
'INSERT INTO item_codes (item_code, name, category) VALUES (?, ?, ?)',
(code, name, category)
)
imported += 1
except sqlite3.IntegrityError:
continue # duplicate item_code, skip
conn.commit()
conn.close()
print(f"✅ Imported {imported} item codes from drug_list.csv into catalog")
except Exception as e:
print(f"⚠️ Catalog CSV import skipped: {e}")
# Initialize database on startup
init_db()
ensure_catalog_table()
import_csv_into_catalog_if_empty()
# ================================================================
# ✅ AUTHENTICATION DECORATORS
# ================================================================
def login_required(f):
"""Decorator to require login"""
@wraps(f)
def decorated_function(*args, **kwargs):
if 'user_id' not in session:
return redirect(url_for('login'))
return f(*args, **kwargs)
return decorated_function
def admin_required(f):
"""Decorator to require admin access"""
@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
def get_current_user():
"""Get current logged-in user"""
if 'user_id' not in session:
return None
conn = get_db()
cursor = conn.cursor()
cursor.execute('SELECT * FROM users WHERE id = ?', (session['user_id'],))
user = cursor.fetchone()
conn.close()
return user
# ================================================================
# ✅ DRUG DATABASE CACHE
# ================================================================
DRUG_DATABASE = None
# ---- Matching rules --------------------------------------------------------
# Drugs that differ only by strength (TELMA BETA 20 / 30 / 40) look ~90% alike
# as text but are different products with different item codes. So a fuzzy
# match is only allowed when the numbers (strengths) agree, and the text must
# be very similar. Anything less certain is left blank rather than guessed.
FUZZY_THRESHOLD = 0.85 # minimum text similarity for a fuzzy match (0-1)
AMBIGUITY_MARGIN = 0.01 # two different codes scoring this close = don't guess
_NUMBER_RE = re.compile(r'\d+(?:\.\d+)?')
# Dosage-form words. They are removed before comparing names, but kept as a
# separate attribute so TAB never matches SYRUP / CAP never matches INJ.
_FORM_WORDS = {
'tab': 'tablet', 'tabs': 'tablet', 'tablet': 'tablet', 'tablets': 'tablet',
'cap': 'capsule', 'caps': 'capsule', 'capsule': 'capsule', 'capsules': 'capsule',
'syp': 'syrup', 'syr': 'syrup', 'syrup': 'syrup',
'inj': 'injection', 'injection': 'injection',
'susp': 'suspension', 'suspension': 'suspension',
'drop': 'drops', 'drops': 'drops',
'cream': 'cream', 'gel': 'gel', 'lotion': 'lotion', 'powder': 'powder',
'oint': 'ointment', 'ointment': 'ointment', 'sachet': 'sachet',
}
def normalize_drug_name(text):
"""Lower-case and clean an invoice / CSV drug name:
drops units glued to numbers (50 MG -> 50), pack marks (10's -> 10),
and turns punctuation into single spaces. Decimals like 12.5 are kept."""
text = str(text).strip().lower()
text = re.sub(r'(?<=\d)\s*(?:mg|mcg|gm|g|ml|iu)\b', '', text) # 50mg / 50 MG -> 50
text = re.sub(r"(?<=\d)\s*'?s\b", '', text) # 10's / 10s -> 10
text = re.sub(r'[^a-z0-9.]+', ' ', text)
text = re.sub(r'(?<!\d)\.|\.(?!\d)', ' ', text) # dots that are not decimal points
return re.sub(r'\s+', ' ', text).strip()
def parse_drug_name(text):
"""Split a drug name into the parts that matter for matching:
name - the drug's words only, e.g. 'telma beta'
numbers - strengths / pack sizes, e.g. {'40', '12.5'}
forms - dosage forms, e.g. {'tablet'}
'EPTUS - 50 MG' -> name 'eptus', numbers {'50'}, forms set()
'EPTUS TAB 50MG' -> name 'eptus', numbers {'50'}, forms {'tablet'}"""
normalized = normalize_drug_name(text)
numbers = set(_NUMBER_RE.findall(normalized))
words = _NUMBER_RE.sub(' ', normalized).split()
forms = {_FORM_WORDS[w] for w in words if w in _FORM_WORDS}
name_words = [w for w in words if w not in _FORM_WORDS]
return {'name': ' '.join(name_words), 'numbers': numbers, 'forms': forms}
def load_drug_database():
"""Load the item code catalog (item_codes table) into memory for matching.
This is the DB-backed replacement for the old CSV-only workflow; call this
again any time the catalog changes (add/edit/delete/import) so matching
picks up the change immediately without a restart."""
global DRUG_DATABASE
try:
conn = sqlite3.connect(DATABASE)
conn.row_factory = sqlite3.Row
cursor = conn.cursor()
cursor.execute('SELECT item_code, name, category FROM item_codes')
rows = cursor.fetchall()
conn.close()
DRUG_DATABASE = {}
for row in rows:
drug_name = str(row['name']).strip().lower()
item_code = str(row['item_code']).strip().upper()
DRUG_DATABASE[drug_name] = {
'item_code': item_code,
'name': row['name'],
'category': row['category'],
'parsed': parse_drug_name(row['name']),
}
print(f"✅ Loaded {len(DRUG_DATABASE)} item codes from catalog")
return True
except Exception as e:
print(f"❌ Error loading item code catalog: {e}")
DRUG_DATABASE = {}
return False
load_drug_database()
# ================================================================
# ✅ UTILITY FUNCTIONS
# ================================================================
def safe_strip(value, default=''):
"""Safely strip a value that might be None"""
if value is None:
return default
if isinstance(value, str):
return value.strip()
return str(value).strip() if value else default
def similarity_ratio(a, b):
"""Calculate similarity between two strings"""
if not a or not b:
return 0
return SequenceMatcher(None, a.lower(), b.lower()).ratio()
def extract_item_code_from_drug_list(drug_description):
"""Find the item code for a drug, or None if there is no confident match.
1. Exact match on the raw name.
2. Otherwise the invoice line and each CSV drug are split into
name / strengths / dosage form (see parse_drug_name) and a CSV drug is
a candidate only if ALL of these hold:
- dosage form: not contradicting (TAB vs SYRUP is rejected;
a form missing on either side is fine)
- strength: every number in the CSV name also appears in the invoice
line (TELMA BETA 20 never matches an invoice line for 25)
- name: identical words, or - same number of words and spelling
similarity >= FUZZY_THRESHOLD (typos OK, TELMA vs TELMA H is not)
3. Best candidate wins; if two different codes are equally good, return
None instead of guessing.
"""
if not drug_description or not DRUG_DATABASE:
return None
drug_desc = safe_strip(drug_description).lower()
if not drug_desc:
return None
# 1. Exact match
if drug_desc in DRUG_DATABASE:
return DRUG_DATABASE[drug_desc]['item_code']
invoice = parse_drug_name(drug_desc)
if not invoice['name']:
return None
invoice_word_count = len(invoice['name'].split())
# 2. Collect candidates
scored = []
for data in DRUG_DATABASE.values():
cand = data['parsed']
# Dosage form guard
if invoice['forms'] and cand['forms'] and invoice['forms'] != cand['forms']:
continue
# Strength guard
if not cand['numbers'].issubset(invoice['numbers']):
continue
# Name check
if cand['name'] == invoice['name']:
score = 1.0
elif len(cand['name'].split()) == invoice_word_count:
score = similarity_ratio(invoice['name'], cand['name'])
if score < FUZZY_THRESHOLD:
continue
else:
continue
scored.append((score, len(cand['numbers']), data))
if not scored:
return None
# 3. Best = highest name score, then the candidate that matched more strengths
scored.sort(key=lambda entry: (entry[0], entry[1]), reverse=True)
best_score, best_specificity, best = scored[0]
if len(scored) > 1:
runner_score, runner_specificity, runner = scored[1]
is_tie = (best_score - runner_score <= AMBIGUITY_MARGIN
and best_specificity == runner_specificity)
if is_tie and runner['item_code'] != best['item_code']:
logger.info(f"⚠️ Ambiguous match for '{drug_description}': "
f"'{best['name']}' vs '{runner['name']}' - leaving blank")
return None
return best['item_code']
def call_invoice_extraction_api(file_path):
"""Call invoice extraction API"""
try:
logger.info(f"📤 Calling invoice extraction API")
with open(file_path, 'rb') as f:
files = {'file': f}
headers = {
'X-API-Key': os.getenv('INVOICE_API_KEY')
}
response = requests.post(
f"{os.getenv('INVOICE_API_URL')}",
files=files,
headers=headers,
timeout=1800
)
response.raise_for_status()
extracted_data = response.json()
logger.info(f"✅ API Response received")
return extracted_data
except Exception as e:
logger.error(f"❌ API request error: {e}")
return None
# ================================================================
# ✅ CSV CATALOG HELPERS (green/red "in CSV" status + auto-append)
# ================================================================
CSV_PATH = 'drug_list.csv'
_csv_lock = threading.Lock()
def code_in_catalog(code, cursor=None):
"""True if this item code already exists in the catalog (case-insensitive)."""
code = safe_strip(code).upper()
if not code:
return False
own_conn = None
if cursor is None:
own_conn = get_db()
cursor = own_conn.cursor()
try:
cursor.execute('SELECT 1 FROM item_codes WHERE UPPER(item_code) = ? LIMIT 1', (code,))
return cursor.fetchone() is not None
finally:
if own_conn:
own_conn.close()
def append_to_drug_csv(item_code, name, category='Uncategorized'):
"""Append one row to drug_list.csv, matching whatever column order the file
already uses. Returns (True, None) on success or (False, reason) on failure.
Fails softly (e.g. file open in Excel) so the catalog insert still stands."""
try:
with _csv_lock:
fieldnames = None
needs_newline = False
if os.path.exists(CSV_PATH) and os.path.getsize(CSV_PATH) > 0:
with open(CSV_PATH, 'r', newline='', encoding='utf-8-sig', errors='replace') as f:
fieldnames = next(csv.reader(f), None)
with open(CSV_PATH, 'rb') as f:
f.seek(-1, os.SEEK_END)
needs_newline = f.read(1) not in (b'\n', b'\r')
write_header = not fieldnames
if write_header:
fieldnames = ['item_code', 'name', 'category']
values = {'item_code': item_code, 'name': name, 'category': category}
row = [values.get(col.strip().lower(), '') for col in fieldnames]
with open(CSV_PATH, 'a', newline='', encoding='utf-8') as f:
if needs_newline:
f.write('\r\n')
writer = csv.writer(f)
if write_header:
writer.writerow(fieldnames)
writer.writerow(row)
return True, None
except PermissionError:
return False, 'drug_list.csv could not be updated because it is open in another program (e.g. Excel). Close it and re-add the code.'
except Exception as e:
logger.error(f"❌ CSV append failed: {e}")
return False, f'drug_list.csv could not be updated ({e}).'
def enrich_extracted_data(extracted_data, use_drug_list=True):
"""Enrich extracted invoice data with item codes.
Every item also gets `in_csv` (True/False): whether its code exists in the
catalog / drug_list.csv. The dashboard uses it for the green/red boxes.
use_drug_list=False skips the drug_list.csv matching: codes read from the
invoice are kept (source 'api_extracted') and every other item is left
blank (source 'not_found') so the user can enter it manually.
"""
if not extracted_data or 'items' not in extracted_data:
return extracted_data
items = extracted_data.get('items', [])
for item in items:
if not isinstance(item, dict):
continue
existing_code = safe_strip(item.get('item_code', ''))
if not existing_code:
if not use_drug_list:
item['item_code_source'] = 'not_found'
item['in_csv'] = False
continue
description = item.get('description', '')
matched_code = extract_item_code_from_drug_list(description)
if matched_code:
item['item_code'] = matched_code
item['item_code_source'] = 'drug_list_match'
logger.info(f"✅ Item code enriched: {description} → {matched_code}")
else:
item['item_code_source'] = 'not_found'
else:
item['item_code_source'] = 'api_extracted'
item['in_csv'] = code_in_catalog(item.get('item_code', ''))
return extracted_data
# ================================================================
# ✅ AUTHENTICATION ROUTES
# ================================================================
@app.route('/register', methods=['GET', 'POST'])
def register():
"""User registration"""
if request.method == 'POST':
data = request.get_json()
username = data.get('username', '').strip()
email = data.get('email', '').strip()
password = data.get('password', '')
confirm_password = data.get('confirm_password', '')
# Validation
if not username or not email or not password:
return jsonify({'success': False, 'message': 'All fields required'}), 400
if password != confirm_password:
return jsonify({'success': False, 'message': 'Passwords do not match'}), 400
if len(password) < 6:
return jsonify({'success': False, 'message': 'Password must be at least 6 characters'}), 400
try:
conn = get_db()
cursor = conn.cursor()
hashed_password = generate_password_hash(password)
cursor.execute(
'INSERT INTO users (username, email, password) VALUES (?, ?, ?)',
(username, email, hashed_password)
)
conn.commit()
conn.close()
return jsonify({'success': True, 'message': 'Registration successful'}), 201
except sqlite3.IntegrityError:
return jsonify({'success': False, 'message': 'Username or email already exists'}), 400
except Exception as e:
return jsonify({'success': False, 'message': str(e)}), 500
return render_template('register.html')
@app.route('/login', methods=['GET', 'POST'])
def login():
"""User login"""
if request.method == 'POST':
data = request.get_json()
username = data.get('username', '').strip()
password = data.get('password', '')
if not username or not password:
return jsonify({'success': False, 'message': 'Username and password required'}), 400
try:
conn = get_db()
cursor = conn.cursor()
cursor.execute('SELECT * FROM users WHERE username = ?', (username,))
user = cursor.fetchone()
if user and check_password_hash(user['password'], password):
# Update last login
cursor.execute(
'UPDATE users SET last_login = CURRENT_TIMESTAMP WHERE id = ?',
(user['id'],)
)
conn.commit()
session['user_id'] = user['id']
session['username'] = user['username']
session.permanent = True
conn.close()
return jsonify({'success': True, 'message': 'Login successful'}), 200
else:
conn.close()
return jsonify({'success': False, 'message': 'Invalid username or password'}), 401
except Exception as e:
return jsonify({'success': False, 'message': str(e)}), 500
return render_template('login.html')
@app.route('/logout')
def logout():
"""User logout"""
session.clear()
return redirect(url_for('login'))
# ================================================================
# ✅ MAIN ROUTES
# ================================================================
@app.route('/')
def index():
"""Home page - redirect to login or dashboard"""
if 'user_id' in session:
return redirect(url_for('dashboard'))
return redirect(url_for('login'))
@app.route('/dashboard')
@login_required
def dashboard():
"""Main dashboard"""
user = get_current_user()
return render_template('dashboard.html', username=user['username'])
@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()
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()
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()
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
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()
cursor.execute(
'SELECT id, username, email, created_at, last_login, is_active, is_admin FROM users WHERE username = ?',
(username,)
)
new_user = cursor.fetchone()
conn.close()
return jsonify({
'success': True,
'message': f'User {username} created successfully',
'user': dict(new_user) if new_user else None
}), 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
if username == current_user['username']:
return jsonify({'success': False, 'message': 'Cannot delete your own account'}), 400
if username == 'admin':
return jsonify({'success': False, 'message': 'Cannot delete protected accounts'}), 400
conn = get_db()
cursor = conn.cursor()
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']
cursor.execute('DELETE FROM extractions WHERE user_id = ?', (user_id,))
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
# ================================================================
# ✅ ITEM CODE CATALOG (Catalog / Autocomplete / Categories)
# ================================================================
def catalog_row_to_dict(row):
return {
'id': row['id'],
'item_code': row['item_code'],
'name': row['name'],
'category': row['category'],
'created_at': row['created_at'],
'updated_at': row['updated_at'],
}
@app.route('/api/catalog', methods=['GET'])
@login_required
def catalog_list():
"""List / search / filter the item code catalog.
Query params: q (search name or code), category, page (1-based), per_page (default 50, max 200)."""
q = request.args.get('q', '').strip()
category = request.args.get('category', '').strip()
try:
page = max(1, int(request.args.get('page', 1)))
except ValueError:
page = 1
try:
per_page = min(200, max(1, int(request.args.get('per_page', 50))))
except ValueError:
per_page = 50
where = []
params = []
if q:
where.append('(name LIKE ? OR item_code LIKE ?)')
params.extend([f'%{q}%', f'%{q}%'])
if category:
where.append('category = ?')
params.append(category)
where_clause = ('WHERE ' + ' AND '.join(where)) if where else ''
conn = get_db()
cursor = conn.cursor()
cursor.execute(f'SELECT COUNT(*) AS c FROM item_codes {where_clause}', params)
total = cursor.fetchone()['c']
offset = (page - 1) * per_page
cursor.execute(
f'SELECT * FROM item_codes {where_clause} ORDER BY name ASC LIMIT ? OFFSET ?',
params + [per_page, offset]
)
rows = cursor.fetchall()
conn.close()
return jsonify({
'success': True,
'data': [catalog_row_to_dict(r) for r in rows],
'total': total,
'page': page,
'per_page': per_page,
'has_more': offset + len(rows) < total
}), 200
@app.route('/api/catalog/categories', methods=['GET'])
@login_required
def catalog_categories():
"""Distinct list of categories currently in use, for filter dropdowns."""
conn = get_db()
cursor = conn.cursor()
cursor.execute('SELECT DISTINCT category FROM item_codes ORDER BY category ASC')
categories = [r['category'] for r in cursor.fetchall()]
conn.close()
return jsonify({'success': True, 'data': categories}), 200
@app.route('/api/catalog/autocomplete', methods=['GET'])
@login_required
def catalog_autocomplete():
"""Lightweight autocomplete for the manual item-code entry box.
Matches on name or item code, prefix matches ranked first. Query: q, limit (default 8, max 20)."""
q = request.args.get('q', '').strip()
try:
limit = min(20, max(1, int(request.args.get('limit', 8))))
except ValueError:
limit = 8
if not q:
return jsonify({'success': True, 'data': []}), 200
conn = get_db()
cursor = conn.cursor()
cursor.execute(
'''SELECT item_code, name, category FROM item_codes
WHERE name LIKE ? OR item_code LIKE ?
ORDER BY
CASE WHEN name LIKE ? OR item_code LIKE ? THEN 0 ELSE 1 END,
name ASC
LIMIT ?''',
(f'%{q}%', f'%{q}%', f'{q}%', f'{q}%', limit)
)
rows = cursor.fetchall()
conn.close()
return jsonify({
'success': True,
'data': [{'item_code': r['item_code'], 'name': r['name'], 'category': r['category']} for r in rows]
}), 200
@app.route('/api/catalog', methods=['POST'])
@login_required
@admin_required
def catalog_add():
"""Admin: add a new item code to the catalog."""
data = request.get_json(silent=True) or {}
item_code = safe_strip(data.get('item_code', '')).upper()
name = safe_strip(data.get('name', ''))
category = safe_strip(data.get('category', '')) or 'Uncategorized'
if not item_code or not name:
return jsonify({'success': False, 'message': 'Item code and name are required'}), 400
if len(item_code) > 50:
return jsonify({'success': False, 'message': 'Item code too long (max 50 characters)'}), 400
try:
conn = get_db()
cursor = conn.cursor()
cursor.execute(
'INSERT INTO item_codes (item_code, name, category, created_by) VALUES (?, ?, ?, ?)',
(item_code, name, category, session.get('user_id'))
)
conn.commit()
new_id = cursor.lastrowid
conn.close()
load_drug_database() # refresh in-memory matcher immediately
return jsonify({'success': True, 'message': f'Item code {item_code} added', 'id': new_id}), 201
except sqlite3.IntegrityError:
return jsonify({'success': False, 'message': f'Item code {item_code} already exists'}), 400
except Exception as e:
return jsonify({'success': False, 'message': str(e)}), 500
@app.route('/api/catalog/<int:catalog_id>', methods=['PUT'])
@login_required
@admin_required
def catalog_update(catalog_id):
"""Admin: edit an existing catalog entry."""
data = request.get_json(silent=True) or {}
conn = get_db()
cursor = conn.cursor()
cursor.execute('SELECT * FROM item_codes WHERE id = ?', (catalog_id,))
existing = cursor.fetchone()
if not existing:
conn.close()
return jsonify({'success': False, 'message': 'Item code not found'}), 404
item_code = safe_strip(data.get('item_code', existing['item_code'])).upper()
name = safe_strip(data.get('name', existing['name'])) or existing['name']
category = safe_strip(data.get('category', existing['category'])) or 'Uncategorized'
if not item_code:
conn.close()
return jsonify({'success': False, 'message': 'Item code cannot be empty'}), 400
try:
cursor.execute(
'''UPDATE item_codes SET item_code = ?, name = ?, category = ?, updated_at = CURRENT_TIMESTAMP
WHERE id = ?''',
(item_code, name, category, catalog_id)
)
conn.commit()
conn.close()
load_drug_database()
return jsonify({'success': True, 'message': 'Item code updated'}), 200
except sqlite3.IntegrityError:
conn.close()
return jsonify({'success': False, 'message': f'Item code {item_code} already exists'}), 400
except Exception as e:
conn.close()
return jsonify({'success': False, 'message': str(e)}), 500
@app.route('/api/catalog/<int:catalog_id>', methods=['DELETE'])
@login_required
@admin_required
def catalog_delete(catalog_id):
"""Admin: remove a catalog entry."""
conn = get_db()
cursor = conn.cursor()
cursor.execute('SELECT id FROM item_codes WHERE id = ?', (catalog_id,))
if not cursor.fetchone():
conn.close()
return jsonify({'success': False, 'message': 'Item code not found'}), 404
cursor.execute('DELETE FROM item_codes WHERE id = ?', (catalog_id,))
conn.commit()
conn.close()
load_drug_database()
return jsonify({'success': True, 'message': 'Item code deleted'}), 200
# ================================================================
# ✅ QUALITY METRICS + ITEMS TO REVIEW
# ================================================================
@app.route('/api/admin/quality-stats', methods=['GET'])
@login_required
@admin_required
def admin_quality_stats():
"""Catalog size/category breakdown + overall extraction completeness,
for the admin Quality tab's summary cards."""
conn = get_db()
cursor = conn.cursor()
cursor.execute('SELECT COUNT(*) AS c FROM item_codes')
total_codes = cursor.fetchone()['c']
cursor.execute('SELECT category, COUNT(*) AS c FROM item_codes GROUP BY category ORDER BY c DESC')
by_category = [{'category': r['category'], 'count': r['c']} for r in cursor.fetchall()]
cursor.execute('SELECT extraction_data FROM extractions')
rows = cursor.fetchall()
conn.close()
total_items = with_code = auto_matched = manual = missing = 0
for row in rows:
try:
data = json.loads(row['extraction_data']) if row['extraction_data'] else {}
except (TypeError, ValueError):
continue
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
total_items += 1
code = safe_strip(item.get('item_code', ''))
source = item.get('item_code_source')
if code:
with_code += 1
else:
missing += 1
if source == 'drug_list_match':
auto_matched += 1
elif source == 'manual':
manual += 1
completion_pct = round((with_code / total_items) * 100, 1) if total_items else 0.0
return jsonify({
'success': True,
'data': {
'catalog_total_codes': total_codes,
'catalog_by_category': by_category,
'total_items': total_items,
'items_with_code': with_code,
'items_auto_matched': auto_matched,
'items_manual': manual,
'items_missing': missing,
'completion_pct': completion_pct,
}
}), 200
@app.route('/api/admin/items-to-review', methods=['GET'])
@login_required
@admin_required
def admin_items_to_review():
"""Items across all users' extractions that still have no item code,
newest first, so admins know exactly what's left to fix. Query: limit (default 100, max 500)."""
try:
limit = min(500, max(1, int(request.args.get('limit', 100))))
except ValueError:
limit = 100
conn = get_db()
cursor = conn.cursor()
cursor.execute('''
SELECT e.id, e.filename, e.created_at, u.username, 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()
to_review = []
for row in rows:
try:
data = json.loads(row['extraction_data']) if row['extraction_data'] else {}
except (TypeError, ValueError):
continue
items = data.get('items') if isinstance(data, dict) else None
if not isinstance(items, list):
continue
for idx, item in enumerate(items):
if not isinstance(item, dict):
continue
code = safe_strip(item.get('item_code', ''))
if code:
continue
to_review.append({
'extraction_id': row['id'],
'index': idx,
'username': row['username'],
'filename': row['filename'],
'created_at': row['created_at'],
'description': item.get('description', ''),
})
if len(to_review) >= limit:
break
if len(to_review) >= limit:
break
return jsonify({'success': True, 'data': to_review, 'count': len(to_review)}), 200
@app.route('/api/upload', methods=['POST'])
@login_required
def upload_invoice():
"""Handle invoice upload and extraction"""
try:
if 'file' not in request.files:
return jsonify({'success': False, 'error': 'No file provided'}), 400
file = request.files['file']
if file.filename == '':
return jsonify({'success': False, 'error': 'No file selected'}), 400
# Validate file
ALLOWED_EXTENSIONS = {'pdf', 'png', 'jpg', 'jpeg'}
if not ('.' in file.filename and file.filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS):
return jsonify({'success': False, 'error': 'File type not allowed'}), 400
# Save file
timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')
unique_id = secrets.token_hex(4)
filename = secure_filename(f"{timestamp}_{unique_id}_{file.filename}")
filepath = os.path.join(app.config['UPLOAD_FOLDER'], filename)
file.save(filepath)
print(f"📁 File saved: {filename}")
# Extract from API
print(f"🔄 Calling invoice extraction API...")
extracted_data = call_invoice_extraction_api(filepath)
if extracted_data is None:
return jsonify({'success': False, 'error': 'Failed to extract invoice'}), 500
# Keep an untouched copy of the API response BEFORE enrichment.
# enrich_extracted_data() modifies the dict in place, so a deep copy is required.
raw_api_response = copy.deepcopy(extracted_data)
# Drug-list (CSV) matching is on by default. The Manual Item Codes tab
# sends enrich=false so items without a code on the invoice stay blank.
use_drug_list = request.form.get('enrich', 'true').strip().lower() != 'false'
# Enrich with item codes
print(f"🔍 Enriching with item codes (drug list matching: {use_drug_list})...")
enriched_data = enrich_extracted_data(extracted_data, use_drug_list=use_drug_list)
# Add metadata
enriched_data['_metadata'] = {
'upload_timestamp': datetime.now().isoformat(),
'original_filename': file.filename,
'upload_id': unique_id,
'enrichment_status': 'completed' if use_drug_list else 'skipped_manual_entry'
}
# Original API response, shown in the "JSON" view on the dashboard
# (saved to the DB too, so it also works from History)
enriched_data['_raw_api_response'] = raw_api_response
# Save to database
extraction_id = None
try:
conn = get_db()
cursor = conn.cursor()
cursor.execute(
'''INSERT INTO extractions (user_id, invoice_id, filename, extraction_data)
VALUES (?, ?, ?, ?)''',
(session['user_id'],
enriched_data.get('invoice_id', 'Unknown'),
file.filename,
json.dumps(enriched_data))
)
extraction_id = cursor.lastrowid
conn.commit()
conn.close()
except Exception as e:
print(f"⚠️ Database error: {e}")
# Delete temp file
try:
os.remove(filepath)
except:
pass
return jsonify({
'success': True,
'data': enriched_data,
'extraction_id': extraction_id,
'message': 'Invoice extracted and enriched successfully'
}), 200
except Exception as e:
logger.error(f"❌ Upload error: {e}")
return jsonify({'success': False, 'error': str(e)}), 500
@app.route('/api/history')
@login_required
def get_history():
"""Get user's extraction history"""
try:
conn = get_db()
cursor = conn.cursor()
cursor.execute(
'''SELECT id, invoice_id, filename, created_at FROM extractions
WHERE user_id = ? ORDER BY created_at DESC LIMIT 50''',
(session['user_id'],)
)
extractions = cursor.fetchall()
# The list above is capped at 50 rows; `total` is the real count
cursor.execute('SELECT COUNT(*) AS n FROM extractions WHERE user_id = ?', (session['user_id'],))
total = cursor.fetchone()['n']
conn.close()
return jsonify({
'success': True,
'data': [dict(e) for e in extractions],
'total': total
}), 200
except Exception as e:
return jsonify({'success': False, 'error': str(e)}), 500
@app.route('/api/pending-items')
@login_required
def get_pending_items():
"""Every item, across ALL of this user's invoices, whose item code is not in
the sheet/catalog yet. This is the persistent approval queue: an item stays
here until someone approves a code for it.
Before listing, the queue is refreshed against the current catalog:
- an item with a code that now exists in the catalog is marked in_csv
- an item with no code whose description now matches the catalog is
auto-filled (so approving a code once clears the same item on older invoices)
Updated extractions are saved back.
"""
try:
conn = get_db()
cursor = conn.cursor()
cursor.execute('SELECT UPPER(item_code) AS c FROM item_codes')
catalog_codes = {r['c'] for r in cursor.fetchall()}
cursor.execute(
'''SELECT id, invoice_id, filename, created_at, extraction_data
FROM extractions WHERE user_id = ? ORDER BY created_at DESC''',
(session['user_id'],)
)
rows = cursor.fetchall()
pending = []
for row in rows:
try:
data = json.loads(row['extraction_data']) if row['extraction_data'] else {}
except (TypeError, ValueError):
continue
items = data.get('items') if isinstance(data, dict) else None
if not isinstance(items, list):
continue
dirty = False
for idx, item in enumerate(items):
if not isinstance(item, dict):
continue
code = safe_strip(item.get('item_code', ''))
if not code:
matched = extract_item_code_from_drug_list(item.get('description', ''))
if matched:
item['item_code'] = code = matched
item['item_code_source'] = 'drug_list_match'
dirty = True
in_sheet = bool(code) and code.upper() in catalog_codes
if item.get('in_csv') is not in_sheet:
item['in_csv'] = in_sheet
dirty = True
if not in_sheet:
pending.append({
'extraction_id': row['id'],
'index': idx,
'invoice_id': row['invoice_id'] or data.get('invoice_id') or '',
'filename': row['filename'],
'created_at': row['created_at'],
'description': item.get('description', ''),
'quantity': item.get('quantity', ''),
'unit_price': item.get('unit_price', ''),
'item_code': code,
})
if dirty:
cursor.execute(
'UPDATE extractions SET extraction_data = ? WHERE id = ? AND user_id = ?',
(json.dumps(data), row['id'], session['user_id'])
)
conn.commit()
conn.close()
return jsonify({
'success': True,
'data': pending,
'total_pending': len(pending),
'total_invoices': len(rows)
}), 200
except Exception as e:
logger.error(f"❌ Pending items error: {e}")
return jsonify({'success': False, 'error': str(e)}), 500
@app.route('/api/extraction/<int:extraction_id>')
@login_required
def get_extraction(extraction_id):
"""Get specific extraction"""
try:
conn = get_db()
cursor = conn.cursor()
cursor.execute(
'''SELECT extraction_data FROM extractions
WHERE id = ? AND user_id = ?''',
(extraction_id, session['user_id'])
)
result = cursor.fetchone()
conn.close()
if result:
data = json.loads(result['extraction_data'])
return jsonify({'success': True, 'data': data}), 200
else:
return jsonify({'success': False, 'error': 'Not found'}), 404
except Exception as e:
return jsonify({'success': False, 'error': str(e)}), 500
@app.route('/api/extraction/<int:extraction_id>/item-codes', methods=['PUT'])
@login_required
def update_item_codes(extraction_id):
"""Save item codes entered manually by the user.
Body: {"item_codes": [{"index": 0, "item_code": "ABC123"}, ...]}
`index` is the item's position in the extraction's `items` list.
Changed items get item_code_source = 'manual' (or 'not_found' if cleared).
The stored `_raw_api_response` is never modified.
"""
MAX_ITEM_CODE_LENGTH = 50
payload = request.get_json(silent=True) or {}
updates = payload.get('item_codes')
if not isinstance(updates, list):
return jsonify({'success': False, 'error': 'item_codes must be a list'}), 400
conn = get_db()
try:
cursor = conn.cursor()
cursor.execute(
'''SELECT extraction_data FROM extractions
WHERE id = ? AND user_id = ?''',
(extraction_id, session['user_id'])
)
row = cursor.fetchone()
if not row:
return jsonify({'success': False, 'error': 'Not found'}), 404
data = json.loads(row['extraction_data'])
items = data.get('items')
if not isinstance(items, list):
return jsonify({'success': False, 'error': 'This extraction has no items'}), 400
changed = 0
new_rows = [] # (code, name) pairs added to the catalog in this request
csv_warning = None
for update in updates:
if not isinstance(update, dict):
continue
index = update.get('index')
if not isinstance(index, int) or isinstance(index, bool) or not (0 <= index < len(items)):
continue
item = items[index]
if not isinstance(item, dict):
continue
new_code = safe_strip(update.get('item_code', ''))
if len(new_code) > MAX_ITEM_CODE_LENGTH:
return jsonify({
'success': False,
'error': f'Item code too long (max {MAX_ITEM_CODE_LENGTH} characters)'
}), 400
old_code = safe_strip(item.get('item_code', ''))
# Unchanged code that is already in the CSV -> nothing to do.
# Unchanged code that is NOT in the CSV yet -> fall through so
# "Approve" can add it.
if new_code == old_code and (not new_code or item.get('in_csv') is True):
continue
item['item_code'] = new_code
if new_code != old_code:
item['item_code_source'] = 'manual' if new_code else 'not_found'
if new_code:
if not code_in_catalog(new_code, cursor):
item_name = safe_strip(item.get('description', '')) or new_code
cursor.execute(
'''INSERT INTO item_codes (item_code, name, category, created_by)
VALUES (?, ?, ?, ?)''',
(new_code.upper(), item_name, 'Uncategorized', session['user_id'])
)
new_rows.append((new_code.upper(), item_name))
item['in_csv'] = True
else:
item['in_csv'] = False
changed += 1
if changed:
metadata = data.get('_metadata')
if not isinstance(metadata, dict):
metadata = {}
data['_metadata'] = metadata
metadata['manual_edit_at'] = datetime.now().isoformat()
cursor.execute(
'''UPDATE extractions SET extraction_data = ?
WHERE id = ? AND user_id = ?''',
(json.dumps(data), extraction_id, session['user_id'])
)
conn.commit()
# Brand-new codes: refresh the in-memory matcher and append to drug_list.csv
if new_rows:
load_drug_database()
for code, item_name in new_rows:
ok, reason = append_to_drug_csv(code, item_name)
if not ok:
csv_warning = reason
return jsonify({
'success': True,
'data': data,
'updated': changed,
'new_codes_added': len(new_rows),
'csv_warning': csv_warning,
'message': f'{changed} item code(s) saved'
}), 200
except Exception as e:
logger.error(f"❌ Item code update error: {e}")
return jsonify({'success': False, 'error': str(e)}), 500
finally:
conn.close()
@app.route('/api/profile')
@login_required
def get_profile():
"""Get user profile"""
user = get_current_user()
return jsonify({
'success': True,
'data': {
'username': user['username'],
'email': user['email'],
'created_at': user['created_at'],
'last_login': user['last_login']
}
}), 200
@app.route('/api/config')
def get_config():
"""Get app configuration"""
return jsonify({
'drug_database_loaded': DRUG_DATABASE is not None,
'drug_count': len(DRUG_DATABASE) if DRUG_DATABASE else 0,
'max_file_size_mb': app.config['MAX_CONTENT_LENGTH'] // (1024 * 1024)
}), 200
@app.errorhandler(404)
def not_found(error):
return jsonify({'error': 'Not found'}), 404
@app.errorhandler(500)
def server_error(error):
logger.error(f"Server error: {error}")
return jsonify({'error': 'Internal server error'}), 500
# ================================================================
# ✅ MAIN
# ================================================================
if __name__ == '__main__':
port = int(os.getenv('PORT', 5000))
debug = os.getenv('DEBUG', 'False') == 'True'
print("=" * 70)
print("🚀 Invoice Extraction with Item Code Enrichment - PRO")
print("=" * 70)
print(f"📍 Running on http://0.0.0.0:{port}")
print(f"💊 Drug Database: {len(DRUG_DATABASE) if DRUG_DATABASE else 0} drugs loaded")
print(f"🔐 User Authentication: Enabled")
print("=" * 70)
app.run(
host='0.0.0.0',
port=port,
debug=debug
)