""" 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) # Absolute Base Directory for robust VPS hosting BASE_DIR = os.path.dirname(os.path.abspath(__file__)) # Configuration app.secret_key = os.getenv('SECRET_KEY', 'your-secret-key-here') app.config['UPLOAD_FOLDER'] = os.path.join(BASE_DIR, 'uploads') app.config['MAX_CONTENT_LENGTH'] = 100 * 1024 * 1024 app.config['PERMANENT_SESSION_LIFETIME'] = timedelta(days=7) # Create required folders for folder_name in ['uploads', 'logs', 'templates']: folder_path = os.path.join(BASE_DIR, folder_name) if not os.path.exists(folder_path): os.makedirs(folder_path, exist_ok=True) # Setup logging logging.basicConfig(level=logging.INFO) logger = logging.getLogger(__name__) # ================================================================ # ✅ DATABASE SETUP # ================================================================ DATABASE = os.path.join(BASE_DIR, '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() CSV_PATH = os.path.join(BASE_DIR, 'drug_list.csv') if count > 0 or not os.path.exists(CSV_PATH): return try: df = pd.read_csv(CSV_PATH) 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() def ensure_po_approval_tables(): """Create PO approval tables if they don't exist. Safe to call every startup.""" conn = get_db() cursor = conn.cursor() cursor.execute(''' CREATE TABLE IF NOT EXISTS po_approval_invoices ( id INTEGER PRIMARY KEY AUTOINCREMENT, extraction_id INTEGER, invoice_number TEXT, vendor_name TEXT, invoice_date TEXT, invoice_filename TEXT, po_number_original TEXT, po_number_approved TEXT, approved_by INTEGER, approved_at TIMESTAMP, item_code_status TEXT DEFAULT 'missing', approval_status TEXT DEFAULT 'pending', created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, FOREIGN KEY (extraction_id) REFERENCES extractions(id) ) ''') cursor.execute(''' CREATE TABLE IF NOT EXISTS po_approval_history ( id INTEGER PRIMARY KEY AUTOINCREMENT, po_invoice_id INTEGER NOT NULL, extraction_id INTEGER, invoice_number TEXT, vendor_name TEXT, po_number_previous TEXT, po_number_approved TEXT, approval_status TEXT NOT NULL, approved_by INTEGER, approved_by_username TEXT, approval_timestamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP, webhook_status TEXT DEFAULT 'not_triggered', webhook_response TEXT, webhook_error TEXT, webhook_triggered_at TIMESTAMP, item_code_status TEXT DEFAULT 'pending', item_code_retrieved TEXT, notes TEXT, FOREIGN KEY (po_invoice_id) REFERENCES po_approval_invoices(id), FOREIGN KEY (approved_by) REFERENCES users(id) ) ''') cursor.execute('CREATE INDEX IF NOT EXISTS idx_po_approval_invoices_status ON po_approval_invoices(approval_status)') cursor.execute('CREATE INDEX IF NOT EXISTS idx_po_approval_invoices_extraction ON po_approval_invoices(extraction_id)') cursor.execute('CREATE INDEX IF NOT EXISTS idx_po_approval_history_invoice ON po_approval_history(po_invoice_id)') # Safe migration: add condition_type column if it doesn't exist try: cursor.execute("ALTER TABLE po_approval_invoices ADD COLUMN condition_type TEXT DEFAULT 'condition_3'") logger.info("✅ Migrated: added condition_type column to po_approval_invoices") except Exception: pass # Column already exists # Safe migration: add items_json column if it doesn't exist try: cursor.execute("ALTER TABLE po_approval_invoices ADD COLUMN items_json TEXT DEFAULT '[]'") logger.info("✅ Migrated: added items_json column to po_approval_invoices") except Exception: pass # Column already exists # Safe migration: add webhook_status column if it doesn't exist try: cursor.execute("ALTER TABLE po_approval_invoices ADD COLUMN webhook_status TEXT DEFAULT 'not_triggered'") logger.info("✅ Migrated: added webhook_status column to po_approval_invoices") except Exception: pass # Safe migration: add condition_type column to po_approval_history try: cursor.execute("ALTER TABLE po_approval_history ADD COLUMN condition_type TEXT") logger.info("✅ Migrated: added condition_type column to po_approval_history") except Exception: pass # Safe migration: add approval_type column to po_approval_history try: cursor.execute("ALTER TABLE po_approval_history ADD COLUMN approval_type TEXT DEFAULT 'po_approval'") logger.info("✅ Migrated: added approval_type column to po_approval_history") except Exception: pass conn.commit() conn.close() ensure_po_approval_tables() # ================================================================ # ✅ 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 require_api_key_or_login(f): """Allow M2M calls with X-API-Key header OR regular browser session login. Used by endpoints that n8n calls directly (e.g. /api/po-approval/submit).""" @wraps(f) def decorated(*args, **kwargs): api_key = request.headers.get('X-API-Key', '').strip() expected = os.getenv('N8N_WEBHOOK_SECRET', '').strip() # Accept API key if configured and matches if expected and api_key == expected: return f(*args, **kwargs) # Accept regular session login if 'user_id' in session: return f(*args, **kwargs) return jsonify({'success': False, 'error': 'Unauthorized — provide X-API-Key header or log in'}), 401 return decorated 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'(? 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 = os.path.join(BASE_DIR, '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() is_admin = bool(user['is_admin']) if (user and 'is_admin' in user.keys()) else False return render_template('dashboard.html', username=user['username'], is_admin=is_admin) @app.route('/admin') @login_required @admin_required def admin_dashboard(): """Admin dashboard - per-day, per-user counts + user management + live queues""" 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() # Get live queue stats cursor.execute("SELECT COUNT(*) AS c FROM po_approval_invoices WHERE approval_status = 'pending_po'") pending_po = cursor.fetchone()['c'] cursor.execute("SELECT COUNT(*) AS c FROM po_approval_invoices WHERE approval_status = 'pending_item_code'") pending_item_code = cursor.fetchone()['c'] cursor.execute("SELECT COUNT(*) AS c FROM po_approval_invoices WHERE approval_status IN ('completed', 'approved')") completed_inv = cursor.fetchone()['c'] cursor.execute("SELECT COUNT(*) AS c FROM po_approval_history WHERE approval_status IN ('completed', 'approved')") completed_hist = cursor.fetchone()['c'] total_processed = max(completed_inv, completed_hist) cursor.execute(''' SELECT id, po_invoice_id, extraction_id, invoice_number, vendor_name, po_number_previous, po_number_approved, approval_status, approved_by, approved_by_username, approval_timestamp, webhook_status, item_code_status, notes, condition_type, approval_type FROM po_approval_history ORDER BY approval_timestamp DESC ''') po_history_rows = cursor.fetchall() conn.close() stats = build_admin_stats(rows, po_history_rows=po_history_rows) today_str = datetime.now().strftime('%Y-%m-%d') summary = build_summary(stats, today_str) current_user = get_current_user() catalog_count = len(DRUG_DATABASE) if DRUG_DATABASE else 14324 system_info = { 'po_details_url': os.getenv('DMH_PO_DETAILS_API_URL', 'https://mapp.dmhospital.org/dmhApiRef/po/getPoDetails.php'), 'grn_url': 'https://mapp.dmhospital.org/dmhApiRef/grn/createGRN.php', 'n8n_webhook_url': os.getenv('N8N_APPROVED_WEBHOOK_URL', 'Not Configured'), 'pharmacy_dashboard_url': os.getenv('PHARMACY_DASHBOARD_URL', 'http://localhost:5000'), 'environment': 'Production' if not app.debug else 'Development' } queue_stats = { 'pending_po_count': pending_po, 'pending_item_code_count': pending_item_code, 'total_processed_count': total_processed, 'catalog_count': catalog_count, 'total_users_count': len(all_users) } return render_template( 'admin_dashboard.html', stats=stats, summary=summary, today=today_str, all_users=all_users, current_user=current_user, queue_stats=queue_stats, system_info=system_info ) @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() or {} username = data.get('username', '').strip() email = data.get('email', '').strip() password = data.get('password', '') is_admin = 1 if data.get('is_admin') else 0 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, ?) ''', (username, email, hashed_password, is_admin)) 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() or {} 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 in ['admin', 'dmh']: return jsonify({'success': False, 'message': f'Cannot delete protected administrator account "{username}"'}), 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 @app.route('/api/admin/reset-password', methods=['POST']) @login_required @admin_required def admin_reset_password(): """Admin endpoint to reset any user's password""" try: data = request.get_json() or {} username = data.get('username', '').strip() new_password = data.get('new_password', '') if not username or not new_password: return jsonify({'success': False, 'message': 'Username and new password are required'}), 400 if len(new_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 = ?', (username,)) user = cursor.fetchone() if not user: conn.close() return jsonify({'success': False, 'message': f'User "{username}" not found'}), 404 hashed = generate_password_hash(new_password) cursor.execute('UPDATE users SET password = ? WHERE id = ?', (hashed, user['id'])) conn.commit() conn.close() return jsonify({'success': True, 'message': f'Password for "{username}" updated successfully'}), 200 except Exception as e: return jsonify({'success': False, 'message': str(e)}), 500 @app.route('/api/admin/toggle-admin', methods=['POST']) @login_required @admin_required def admin_toggle_admin(): """Admin endpoint to promote or demote a user's admin role""" try: data = request.get_json() or {} username = data.get('username', '').strip() is_admin_flag = 1 if data.get('is_admin') else 0 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 modify your own administrator role'}), 400 conn = get_db() cursor = conn.cursor() cursor.execute('UPDATE users SET is_admin = ? WHERE username = ?', (is_admin_flag, username)) conn.commit() conn.close() role_label = 'ADMIN' if is_admin_flag else 'PHARMACY STAFF' return jsonify({'success': True, 'message': f'User "{username}" role updated to {role_label}'}), 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/', 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/', 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 # ============================================================= # 🚀 5-CONDITION DECISION MATRIX EVALUATION # ============================================================= condition_evaluated = 'condition_1' routing_status = 'completed' routing_message = '' po_invoice_id_created = None try: po_num_val = safe_strip( enriched_data.get('po_number') or enriched_data.get('purchase_order_number') or enriched_data.get('PO_number') or '' ) items_list = enriched_data.get('items') or [] inv_num_val = safe_strip(enriched_data.get('invoice_number') or enriched_data.get('invoice_id') or '') vendor_val = safe_strip(enriched_data.get('vendor_name') or enriched_data.get('seller_name') or '') inv_date_val = safe_strip(enriched_data.get('invoice_date') or '') # Ensure hospital GSTIN enriched_data['customer_gstin'] = "27AAATL1944N1ZA" enriched_data['PO_number'] = po_num_val initial_cond = classify_invoice_condition(po_num_val, items_list) conn_matrix = get_db() cur_matrix = conn_matrix.cursor() # --------------------------------------------------------- # CONDITION 1: PO & Item Code Present -> Direct Store # --------------------------------------------------------- if initial_cond == 'condition_1': condition_evaluated = 'condition_1' grn_ok, grn_res, grn_err = call_dmh_create_grn_api(enriched_data) routing_status = 'completed' routing_message = 'Condition 1: PO Number and Item Codes present. Stored directly in DMH Database.' cur_matrix.execute(''' INSERT INTO po_approval_history (po_invoice_id, extraction_id, invoice_number, vendor_name, po_number_approved, approval_status, condition_type, notes, webhook_status) VALUES (0, ?, ?, ?, ?, 'completed', 'condition_1', ?, 'not_triggered') ''', (extraction_id, inv_num_val, vendor_val, po_num_val, routing_message)) conn_matrix.commit() # --------------------------------------------------------- # CONDITION 2 or 3: PO Present, Item Code Missing # --------------------------------------------------------- elif initial_cond == 'condition_2': api_ok, po_items, raw_resp, api_err = call_dmh_po_details_api(po_num_val) merged_items, any_codes_found = merge_po_details_into_items(items_list, po_items) if api_ok and any_codes_found: # CONDITION 2: Item Code retrieved from PO Details -> Store directly condition_evaluated = 'condition_2' enriched_data['items'] = merged_items grn_ok, grn_res, grn_err = call_dmh_create_grn_api(enriched_data) routing_status = 'completed' routing_message = 'Condition 2: Item codes retrieved from DMH PO Details API. Stored in DMH Database.' cur_matrix.execute(''' INSERT INTO po_approval_history (po_invoice_id, extraction_id, invoice_number, vendor_name, po_number_approved, approval_status, condition_type, notes, webhook_status) VALUES (0, ?, ?, ?, ?, 'completed', 'condition_2', ?, 'not_triggered') ''', (extraction_id, inv_num_val, vendor_val, po_num_val, routing_message)) conn_matrix.commit() else: # CONDITION 3: Item Code not found in API -> Manual Item Code Approval condition_evaluated = 'condition_3' routing_status = 'pending_item_code' routing_message = 'Condition 3: PO Number present but item codes not found in API. Routed to Manual Item Code Approval queue.' cur_matrix.execute(''' INSERT INTO po_approval_invoices (extraction_id, invoice_number, vendor_name, invoice_date, invoice_filename, po_number_original, po_number_approved, condition_type, approval_status, item_code_status, items_json) VALUES (?, ?, ?, ?, ?, ?, ?, 'condition_3', 'pending_item_code', 'not_found', ?) ''', (extraction_id, inv_num_val, vendor_val, inv_date_val, file.filename, po_num_val, po_num_val, json.dumps({'items': items_list, 'full_invoice': enriched_data}))) po_invoice_id_created = cur_matrix.lastrowid conn_matrix.commit() # --------------------------------------------------------- # CONDITION 4: PO Missing/Invalid, Item Code Present # --------------------------------------------------------- elif initial_cond == 'condition_4': condition_evaluated = 'condition_4' routing_status = 'pending_po' routing_message = 'Condition 4: PO Number missing or invalid. Routed to Manual PO Number Approval queue.' cur_matrix.execute(''' INSERT INTO po_approval_invoices (extraction_id, invoice_number, vendor_name, invoice_date, invoice_filename, po_number_original, condition_type, approval_status, item_code_status, items_json) VALUES (?, ?, ?, ?, ?, ?, 'condition_4', 'pending_po', 'present', ?) ''', (extraction_id, inv_num_val, vendor_val, inv_date_val, file.filename, po_num_val, json.dumps({'items': items_list, 'full_invoice': enriched_data}))) po_invoice_id_created = cur_matrix.lastrowid conn_matrix.commit() # --------------------------------------------------------- # CONDITION 5: PO Missing/Invalid, Item Code Not Present # --------------------------------------------------------- elif initial_cond == 'condition_5': condition_evaluated = 'condition_5' routing_status = 'pending_po' routing_message = 'Condition 5: PO Number and Item Codes both missing. Routed to Manual PO Number Approval queue.' cur_matrix.execute(''' INSERT INTO po_approval_invoices (extraction_id, invoice_number, vendor_name, invoice_date, invoice_filename, po_number_original, condition_type, approval_status, item_code_status, items_json) VALUES (?, ?, ?, ?, ?, ?, 'condition_5', 'pending_po', 'missing', ?) ''', (extraction_id, inv_num_val, vendor_val, inv_date_val, file.filename, po_num_val, json.dumps({'items': items_list, 'full_invoice': enriched_data}))) po_invoice_id_created = cur_matrix.lastrowid conn_matrix.commit() conn_matrix.close() except Exception as ce: logger.error(f"❌ 5-Condition evaluation error: {ce}") return jsonify({ 'success': True, 'data': enriched_data, 'extraction_id': extraction_id, 'condition_evaluated': condition_evaluated, 'routing_status': routing_status, 'routing_message': routing_message, 'po_invoice_id': po_invoice_id_created, 'message': routing_message or 'Invoice processed 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/') @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//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/dashboard/stats', methods=['GET']) @login_required def get_dashboard_stats(): """Summary statistics for the dashboard cards: - pending_po_count: Invoices waiting for PO Number Approval (Conditions 4 & 5) - pending_item_code_count: Invoices waiting for Item Code Approval (Conditions 3 & 5) - total_processed_count: Invoices completed and stored in DMH Database - total_catalog_count: Standardized items in Drug Master Catalog """ try: conn = get_db() cursor = conn.cursor() cursor.execute("SELECT COUNT(*) AS c FROM po_approval_invoices WHERE approval_status IN ('pending', 'pending_po')") pending_po = cursor.fetchone()['c'] cursor.execute("SELECT COUNT(*) AS c FROM po_approval_invoices WHERE approval_status = 'pending_item_code'") pending_item = cursor.fetchone()['c'] cursor.execute("SELECT COUNT(*) AS c FROM po_approval_invoices WHERE approval_status = 'completed'") completed_invoices = cursor.fetchone()['c'] cursor.execute("SELECT COUNT(*) AS c FROM po_approval_history WHERE approval_status = 'completed'") completed_history = cursor.fetchone()['c'] total_processed = max(completed_invoices, completed_history) catalog_count = len(DRUG_DATABASE) if DRUG_DATABASE else 14324 conn.close() return jsonify({ 'success': True, 'pending_po_count': pending_po, 'pending_item_code_count': pending_item, 'total_processed_count': total_processed, 'total_catalog_count': catalog_count }), 200 except Exception as e: logger.error(f"❌ Error fetching dashboard stats: {e}") return jsonify({'success': False, 'error': str(e)}), 500 @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 # ================================================================ # ✅ PO NUMBER APPROVAL # ================================================================ # ================================================================ # ✅ DMH 5-CONDITION INTEGRATION HELPERS & API CLIENTS # ================================================================ def is_po_valid(po_str): """Check if PO Number is present, non-empty, and valid.""" if not po_str: return False clean = str(po_str).strip().lower() return len(clean) > 0 and clean not in ('', 'n/a', 'na', '-', '0', 'null', 'nil', 'none', 'undefined', 'not found') def are_items_coded(items_list): """Check if all items on the invoice have non-empty item codes.""" if not items_list or not isinstance(items_list, list): return False for i in items_list: if not isinstance(i, dict): return False code = str(i.get('item_code', '')).strip() source = str(i.get('item_code_source', '')).strip().lower() if not code or source == 'not_found': return False return True def classify_invoice_condition(po_str, items_list): """Evaluate invoice against DMH 5-Condition Decision Matrix: - Condition 1: PO Present & Valid, Item Code Present (in invoice) - Condition 2: PO Present & Valid, Item Code Missing (will attempt API) - Condition 4: PO Missing/Invalid, Item Code Present - Condition 5: PO Missing/Invalid, Item Code Not Present (Condition 3 is reached when Condition 2 API lookup yields no item codes) """ po_ok = is_po_valid(po_str) items_ok = are_items_coded(items_list) if po_ok and items_ok: return 'condition_1' elif po_ok and not items_ok: return 'condition_2' # may become condition_3 if API lookup fails elif not po_ok and items_ok: return 'condition_4' else: return 'condition_5' def call_dmh_po_details_api(po_number): """Call DMH PO Details API using PO Number to retrieve item codes. Returns: (success: bool, items: list, raw_response: dict or None, error: str or None) """ po_url = os.getenv('DMH_PO_DETAILS_API_URL', 'https://mapp.dmhospital.org/dmhApiRef/po/getPoDetails.php').strip() po_key = os.getenv('DMH_PO_DETAILS_API_KEY', 'nirajAi26@DMH').strip() if not po_url or not po_number: return False, [], None, "Missing URL or PO Number" try: resp = requests.get( po_url, params={'po_number': po_number}, headers={'x-api-key': po_key, 'Accept': 'application/json'}, timeout=15 ) if resp.status_code == 200: data = resp.json() items = [] if isinstance(data, dict): items = data.get('items') or data.get('data', {}).get('items') or [] elif isinstance(data, list): items = data return True, items, data, None else: return False, [], None, f"HTTP {resp.status_code}: {resp.text[:200]}" except Exception as e: logger.error(f"❌ DMH PO Details API error: {e}") return False, [], None, str(e) def call_dmh_create_grn_api(invoice_data): """Store invoice details directly in DMH Database via createGRN.php. Returns: (success: bool, response_dict: dict or None, error: str or None) """ grn_url = os.getenv('DMH_GRN_API_URL', 'https://mapp.dmhospital.org/dmhApiRef/grn/createGRN.php').strip() grn_key = os.getenv('DMH_GRN_API_KEY', 'nirajAi26@DMH').strip() try: resp = requests.post( grn_url, json=invoice_data, headers={'x-api-key': grn_key, 'Content-Type': 'application/json'}, timeout=20 ) if 200 <= resp.status_code < 300: try: res_data = resp.json() except: res_data = {'raw': resp.text[:500]} return True, res_data, None else: return False, None, f"HTTP {resp.status_code}: {resp.text[:300]}" except Exception as e: logger.error(f"❌ DMH Create GRN API error: {e}") return False, None, str(e) def merge_po_details_into_items(invoice_items, po_items): """Match items from PO details with invoice items by description/name. Returns: (enriched_items: list, any_found: bool) """ if not po_items: return invoice_items, False code_map = {} for pi in po_items: if not isinstance(pi, dict): continue key = safe_strip(pi.get('description') or pi.get('item_name') or pi.get('name') or '').lower() code = safe_strip(pi.get('item_code') or pi.get('code') or '') if key and code: code_map[key] = code any_found = False merged = [] for item in (invoice_items or []): if not isinstance(item, dict): continue new_item = dict(item) existing_code = safe_strip(new_item.get('item_code', '')) if not existing_code: desc_key = safe_strip(new_item.get('description', '')).lower() matched_code = code_map.get(desc_key, '') if matched_code: new_item['item_code'] = matched_code new_item['item_code_source'] = 'po_details_api' any_found = True else: any_found = True merged.append(new_item) return merged, any_found def trigger_po_approval_webhook(payload_dict): """Send JSON payload to DMH_PO_APPROVAL_WEBHOOK_URL. Returns status dict.""" webhook_url = os.getenv('DMH_PO_APPROVAL_WEBHOOK_URL', '').strip() if not webhook_url: return {'status': 'not_configured', 'message': 'Webhook URL not configured'} try: resp = requests.post(webhook_url, json=payload_dict, timeout=10) if 200 <= resp.status_code < 300: return {'status': 'success', 'http_status': resp.status_code} else: return {'status': 'failed', 'http_status': resp.status_code, 'error': resp.text[:500]} except requests.exceptions.Timeout: return {'status': 'timeout', 'error': 'Request timed out'} except Exception as e: return {'status': 'failed', 'error': str(e)} @app.route('/api/po-approval/pending', methods=['GET']) @login_required def po_approval_pending(): """Return all invoices waiting for Manual PO Number Approval (Conditions 4 and 5).""" try: conn = get_db() cursor = conn.cursor() cursor.execute(''' SELECT p.id, p.extraction_id, p.invoice_number, p.vendor_name, p.invoice_date, p.invoice_filename, p.po_number_original, p.item_code_status, p.approval_status, p.created_at, COALESCE(p.condition_type, 'condition_4') AS condition_type FROM po_approval_invoices p WHERE p.approval_status IN ('pending', 'pending_po') ORDER BY p.created_at DESC ''') rows = cursor.fetchall() conn.close() return jsonify({'success': True, 'data': [dict(r) for r in rows], 'count': len(rows)}), 200 except Exception as e: logger.error(f"❌ PO approval pending error: {e}") return jsonify({'success': False, 'error': str(e)}), 500 @app.route('/api/item-approval/pending', methods=['GET']) @login_required def item_approval_pending(): """Return all invoices waiting for Manual Item Code Approval (Conditions 3 and 5).""" try: conn = get_db() cursor = conn.cursor() cursor.execute(''' SELECT p.id, p.extraction_id, p.invoice_number, p.vendor_name, p.invoice_date, p.invoice_filename, p.po_number_original, p.po_number_approved, p.item_code_status, p.approval_status, p.created_at, COALESCE(p.condition_type, 'condition_3') AS condition_type, p.items_json FROM po_approval_invoices p WHERE p.approval_status = 'pending_item_code' ORDER BY p.created_at DESC ''') rows = cursor.fetchall() conn.close() # Format items for each invoice result = [] for r in rows: d = dict(r) items = [] try: raw_json = json.loads(d.get('items_json') or '[]') if isinstance(raw_json, dict): items = raw_json.get('items', []) elif isinstance(raw_json, list): items = raw_json except: pass d['items'] = items result.append(d) return jsonify({'success': True, 'data': result, 'count': len(result)}), 200 except Exception as e: logger.error(f"❌ Item approval pending error: {e}") return jsonify({'success': False, 'error': str(e)}), 500 @app.route('/api/po-approval/invoice/', methods=['GET']) @login_required def po_approval_invoice_detail(po_invoice_id): """Return full details of one po_approval_invoices record + items.""" try: conn = get_db() cursor = conn.cursor() cursor.execute('SELECT * FROM po_approval_invoices WHERE id = ?', (po_invoice_id,)) po_inv = cursor.fetchone() if not po_inv: conn.close() return jsonify({'success': False, 'error': 'PO approval invoice not found'}), 404 items = [] full_invoice = None if po_inv['extraction_id']: cursor.execute('SELECT extraction_data FROM extractions WHERE id = ?', (po_inv['extraction_id'],)) ext_row = cursor.fetchone() if ext_row and ext_row['extraction_data']: try: ext_data = json.loads(ext_row['extraction_data']) items = ext_data.get('items', []) if isinstance(ext_data, dict) else [] full_invoice = ext_data except (TypeError, ValueError): items = [] if not items: try: raw_items_json = po_inv['items_json'] if 'items_json' in po_inv.keys() else '[]' parsed_raw = json.loads(raw_items_json or '[]') if isinstance(parsed_raw, dict): items = parsed_raw.get('items', []) full_invoice = parsed_raw.get('full_invoice') elif isinstance(parsed_raw, list): items = parsed_raw except (TypeError, ValueError): items = [] conn.close() result = dict(po_inv) result['condition_type'] = result.get('condition_type') or 'condition_4' return jsonify({'success': True, 'data': result, 'items': items, 'full_invoice': full_invoice}), 200 except Exception as e: logger.error(f"❌ PO approval invoice detail error: {e}") return jsonify({'success': False, 'error': str(e)}), 500 @app.route('/api/po-approval/submit', methods=['POST']) @require_api_key_or_login def po_approval_submit(): """Submit an invoice into the approval queue from n8n or external integration. Supports Condition 3, 4, and 5.""" try: data = request.get_json(silent=True) or {} extraction_id = data.get('extraction_id') invoice_number = safe_strip(data.get('invoice_number', '')) vendor_name = safe_strip(data.get('vendor_name', '')) invoice_date = safe_strip(data.get('invoice_date', '')) invoice_filename = safe_strip(data.get('invoice_filename', '')) po_number_original = safe_strip(data.get('po_number_original', '')) condition_type = safe_strip(data.get('condition_type', 'condition_4')) if condition_type not in ('condition_1', 'condition_2', 'condition_3', 'condition_4', 'condition_5'): condition_type = 'condition_4' # Set approval_status based on condition: # Condition 3: Item codes missing, PO already present -> pending_item_code # Condition 4 & 5: PO missing -> pending_po if condition_type == 'condition_3': approval_status = 'pending_item_code' item_code_status = 'not_found' elif condition_type == 'condition_4': approval_status = 'pending_po' item_code_status = 'present' else: approval_status = 'pending_po' item_code_status = 'missing' items_json_raw = data.get('items', []) full_invoice_raw = data.get('full_invoice') items_payload = {'items': items_json_raw, 'full_invoice': full_invoice_raw} if full_invoice_raw else items_json_raw items_json_str = json.dumps(items_payload) conn = get_db() cursor = conn.cursor() # Deduplication check if invoice_number: cursor.execute( "SELECT id, approval_status FROM po_approval_invoices WHERE invoice_number = ? AND approval_status IN ('pending', 'pending_po', 'pending_item_code')", (invoice_number,) ) existing = cursor.fetchone() if existing: conn.close() return jsonify({'success': True, 'po_invoice_id': existing['id'], 'duplicate': True, 'message': f'Invoice {invoice_number} already pending in queue'}), 200 cursor.execute(''' INSERT INTO po_approval_invoices (extraction_id, invoice_number, vendor_name, invoice_date, invoice_filename, po_number_original, condition_type, approval_status, item_code_status, items_json) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?) ''', (extraction_id, invoice_number, vendor_name, invoice_date, invoice_filename, po_number_original, condition_type, approval_status, item_code_status, items_json_str)) new_id = cursor.lastrowid conn.commit() conn.close() logger.info(f"✅ PO approval queued: #{new_id} | {invoice_number} | {condition_type} | status={approval_status}") return jsonify({'success': True, 'po_invoice_id': new_id, 'condition_type': condition_type, 'approval_status': approval_status}), 201 except Exception as e: logger.error(f"❌ PO approval submit error: {e}") return jsonify({'success': False, 'error': str(e)}), 500 @app.route('/api/po-approval//approve', methods=['POST']) @login_required def po_approval_approve(po_invoice_id): """Approve a PO number for an invoice (Condition 4 or Condition 5). - If Condition 4: Marks Completed and calls DMH createGRN API + webhook. - If Condition 5: Calls DMH PO Details API. If item code found -> Completed + GRN; if item code NOT found -> moves to Manual Item Code Approval queue (pending_item_code). """ try: data = request.get_json(silent=True) or {} po_number = safe_strip(data.get('po_number', '')) if not po_number: return jsonify({'success': False, 'error': 'PO Number is required'}), 400 conn = get_db() cursor = conn.cursor() cursor.execute('SELECT * FROM po_approval_invoices WHERE id = ?', (po_invoice_id,)) po_inv = cursor.fetchone() if not po_inv: conn.close() return jsonify({'success': False, 'error': 'Invoice not found in approval queue'}), 404 if po_inv['approval_status'] == 'completed': conn.close() return jsonify({'success': False, 'error': 'Invoice already completed'}), 409 user_id = session.get('user_id') username = session.get('username', '') cond = po_inv['condition_type'] or 'condition_4' # Extract items and full invoice payload items = [] full_inv = {} try: raw_parsed = json.loads(po_inv['items_json'] or '{}') if isinstance(raw_parsed, dict): items = raw_parsed.get('items', []) full_inv = raw_parsed.get('full_invoice') or {} elif isinstance(raw_parsed, list): items = raw_parsed except: pass if not full_inv and po_inv['extraction_id']: cursor.execute('SELECT extraction_data FROM extractions WHERE id = ?', (po_inv['extraction_id'],)) ext_row = cursor.fetchone() if ext_row and ext_row['extraction_data']: try: full_inv = json.loads(ext_row['extraction_data']) items = full_inv.get('items', items) except: pass # Ensure full_inv structure full_inv['PO_number'] = po_number full_inv['invoice_number'] = full_inv.get('invoice_number') or po_inv['invoice_number'] full_inv['seller_name'] = full_inv.get('seller_name') or po_inv['vendor_name'] full_inv['customer_gstin'] = full_inv.get('customer_gstin') or "27AAATL1944N1ZA" # ------------------------------------------------------------- # BRANCH: CONDITION 4 (PO Missing, Item Code Present) # ------------------------------------------------------------- if cond == 'condition_4': full_inv['items'] = items # Direct Store into DMH Database grn_ok, grn_res, grn_err = call_dmh_create_grn_api(full_inv) new_status = 'completed' if grn_ok else 'completed' # Marked completed after approval cursor.execute(''' UPDATE po_approval_invoices SET approval_status = ?, po_number_approved = ?, approved_by = ?, approved_at = CURRENT_TIMESTAMP WHERE id = ? ''', (new_status, po_number, user_id, po_invoice_id)) # Audit history cursor.execute(''' INSERT INTO po_approval_history (po_invoice_id, extraction_id, invoice_number, vendor_name, po_number_previous, po_number_approved, approval_status, approved_by, approved_by_username, condition_type, approval_type, notes, webhook_status) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, 'condition_4', 'po_approval', ?, 'not_triggered') ''', (po_invoice_id, po_inv['extraction_id'], po_inv['invoice_number'], po_inv['vendor_name'], po_inv['po_number_original'], po_number, new_status, user_id, username, f'Condition 4: PO approved. Stored in DMH Database. GRN: {grn_res or grn_err}')) history_id = cursor.lastrowid conn.commit() # Trigger Webhook for n8n webhook_payload = { 'event': 'po_number_approved', 'condition_type': 'condition_4', 'invoice_id': po_invoice_id, 'invoice_number': po_inv['invoice_number'], 'vendor_name': po_inv['vendor_name'], 'approved_po_number': po_number, 'approved_by': user_id, 'approved_by_username': username, 'approval_status': 'completed', 'invoice_data': full_inv } wh_result = trigger_po_approval_webhook(webhook_payload) cursor.execute('UPDATE po_approval_history SET webhook_status = ?, webhook_triggered_at = CURRENT_TIMESTAMP WHERE id = ?', (wh_result['status'], history_id)) conn.commit() conn.close() return jsonify({ 'success': True, 'approval_status': 'completed', 'condition_type': 'condition_4', 'message': f'PO Number "{po_number}" approved. Invoice successfully stored in DMH Database.' }), 200 # ------------------------------------------------------------- # BRANCH: CONDITION 5 (PO Missing & Item Code Missing) # ------------------------------------------------------------- elif cond == 'condition_5': # Call DMH PO Details API using the approved PO Number api_ok, po_items, raw_resp, api_err = call_dmh_po_details_api(po_number) merged_items, any_codes_found = merge_po_details_into_items(items, po_items) if api_ok and any_codes_found: # Decision: Item Code Found? YES -> Store in DMH Database -> Completed full_inv['items'] = merged_items grn_ok, grn_res, grn_err = call_dmh_create_grn_api(full_inv) new_status = 'completed' cursor.execute(''' UPDATE po_approval_invoices SET approval_status = ?, po_number_approved = ?, item_code_status = 'retrieved', approved_by = ?, approved_at = CURRENT_TIMESTAMP, items_json = ? WHERE id = ? ''', (new_status, po_number, user_id, json.dumps({'items': merged_items, 'full_invoice': full_inv}), po_invoice_id)) cursor.execute(''' INSERT INTO po_approval_history (po_invoice_id, extraction_id, invoice_number, vendor_name, po_number_previous, po_number_approved, approval_status, approved_by, approved_by_username, condition_type, approval_type, notes, webhook_status) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, 'condition_5', 'po_approval', ?, 'not_triggered') ''', (po_invoice_id, po_inv['extraction_id'], po_inv['invoice_number'], po_inv['vendor_name'], po_inv['po_number_original'], po_number, new_status, user_id, username, f'Condition 5: PO approved, Item codes retrieved from API. Stored in DMH Database.')) history_id = cursor.lastrowid conn.commit() webhook_payload = { 'event': 'po_number_approved', 'condition_type': 'condition_5', 'invoice_id': po_invoice_id, 'invoice_number': po_inv['invoice_number'], 'approved_po_number': po_number, 'approved_by': user_id, 'approval_status': 'completed', 'invoice_data': full_inv } wh_result = trigger_po_approval_webhook(webhook_payload) cursor.execute('UPDATE po_approval_history SET webhook_status = ? WHERE id = ?', (wh_result['status'], history_id)) conn.commit() conn.close() return jsonify({ 'success': True, 'approval_status': 'completed', 'condition_type': 'condition_5', 'message': f'PO Number approved and item codes retrieved from DMH PO Details API. Stored in DMH Database.' }), 200 else: # Decision: Item Code Found? NO -> Move to Manual Item Code Approval Queue new_status = 'pending_item_code' cursor.execute(''' UPDATE po_approval_invoices SET approval_status = ?, po_number_approved = ?, item_code_status = 'not_found', approved_by = ?, approved_at = CURRENT_TIMESTAMP, items_json = ? WHERE id = ? ''', (new_status, po_number, user_id, json.dumps({'items': items, 'full_invoice': full_inv}), po_invoice_id)) cursor.execute(''' INSERT INTO po_approval_history (po_invoice_id, extraction_id, invoice_number, vendor_name, po_number_previous, po_number_approved, approval_status, approved_by, approved_by_username, condition_type, approval_type, notes, webhook_status) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, 'condition_5', 'po_approval', ?, 'not_triggered') ''', (po_invoice_id, po_inv['extraction_id'], po_inv['invoice_number'], po_inv['vendor_name'], po_inv['po_number_original'], po_number, new_status, user_id, username, f'Condition 5: PO approved ({po_number}), but Item Codes NOT found in API. Escalated to Manual Item Code Approval queue.')) conn.commit() conn.close() return jsonify({ 'success': True, 'approval_status': 'pending_item_code', 'condition_type': 'condition_5', 'escalated_to_item_code': True, 'message': f'PO Number "{po_number}" approved, but item codes were NOT found in the DMH PO Details API. Invoice moved to Manual Item Code Approval queue.' }), 200 else: conn.close() return jsonify({'success': False, 'error': f'Invalid condition type: {cond}'}), 400 except Exception as e: logger.error(f"❌ PO approval approve error: {e}") return jsonify({'success': False, 'error': str(e)}), 500 @app.route('/api/item-approval//approve', methods=['POST']) @login_required def item_approval_approve(po_invoice_id): """Approve manual item codes for an invoice in Condition 3 or Condition 5. Once item codes are approved, stores the completed invoice in the DMH Database.""" try: data = request.get_json(silent=True) or {} items_update = data.get('items', []) if not items_update or not isinstance(items_update, list): return jsonify({'success': False, 'error': 'Items array is required'}), 400 conn = get_db() cursor = conn.cursor() cursor.execute('SELECT * FROM po_approval_invoices WHERE id = ?', (po_invoice_id,)) po_inv = cursor.fetchone() if not po_inv: conn.close() return jsonify({'success': False, 'error': 'Invoice not found'}), 404 user_id = session.get('user_id') username = session.get('username', '') cond = po_inv['condition_type'] or 'condition_3' full_inv = {} try: raw_parsed = json.loads(po_inv['items_json'] or '{}') if isinstance(raw_parsed, dict): full_inv = raw_parsed.get('full_invoice') or {} except: pass full_inv['PO_number'] = po_inv['po_number_approved'] or po_inv['po_number_original'] full_inv['invoice_number'] = full_inv.get('invoice_number') or po_inv['invoice_number'] full_inv['seller_name'] = full_inv.get('seller_name') or po_inv['vendor_name'] full_inv['customer_gstin'] = full_inv.get('customer_gstin') or "27AAATL1944N1ZA" full_inv['items'] = items_update # Store in DMH Database grn_ok, grn_res, grn_err = call_dmh_create_grn_api(full_inv) cursor.execute(''' UPDATE po_approval_invoices SET approval_status = 'completed', item_code_status = 'approved', items_json = ? WHERE id = ? ''', (json.dumps({'items': items_update, 'full_invoice': full_inv}), po_invoice_id)) cursor.execute(''' INSERT INTO po_approval_history (po_invoice_id, extraction_id, invoice_number, vendor_name, po_number_previous, po_number_approved, approval_status, approved_by, approved_by_username, condition_type, approval_type, notes, webhook_status) VALUES (?, ?, ?, ?, ?, ?, 'completed', ?, ?, ?, 'item_code_approval', ?, 'not_triggered') ''', (po_invoice_id, po_inv['extraction_id'], po_inv['invoice_number'], po_inv['vendor_name'], po_inv['po_number_original'], full_inv['PO_number'], user_id, username, cond, f'{cond.upper()}: Manual Item Codes approved. Stored in DMH Database.')) history_id = cursor.lastrowid conn.commit() # Trigger webhook webhook_payload = { 'event': 'item_code_approved', 'condition_type': cond, 'invoice_id': po_invoice_id, 'invoice_number': po_inv['invoice_number'], 'approved_po_number': full_inv['PO_number'], 'approved_by': user_id, 'approval_status': 'completed', 'invoice_data': full_inv } wh_result = trigger_po_approval_webhook(webhook_payload) cursor.execute('UPDATE po_approval_history SET webhook_status = ? WHERE id = ?', (wh_result['status'], history_id)) conn.commit() conn.close() return jsonify({ 'success': True, 'approval_status': 'completed', 'message': f'Item codes approved! Invoice successfully stored in DMH Database.' }), 200 except Exception as e: logger.error(f"❌ Item approval approve error: {e}") return jsonify({'success': False, 'error': str(e)}), 500 @app.route('/api/po-approval//reject', methods=['POST']) @login_required def po_approval_reject(po_invoice_id): """Reject an invoice and log audit history.""" try: data = request.get_json(silent=True) or {} notes = safe_strip(data.get('notes', '')) conn = get_db() cursor = conn.cursor() cursor.execute('SELECT * FROM po_approval_invoices WHERE id = ?', (po_invoice_id,)) po_inv = cursor.fetchone() if not po_inv: conn.close() return jsonify({'success': False, 'error': 'Invoice not found'}), 404 user_id = session.get('user_id') username = session.get('username', '') cursor.execute( "UPDATE po_approval_invoices SET approval_status = 'rejected' WHERE id = ?", (po_invoice_id,) ) cursor.execute(''' INSERT INTO po_approval_history (po_invoice_id, extraction_id, invoice_number, vendor_name, po_number_previous, po_number_approved, approval_status, approved_by, approved_by_username, condition_type, notes) VALUES (?, ?, ?, ?, ?, NULL, 'rejected', ?, ?, ?, ?) ''', ( po_invoice_id, po_inv['extraction_id'], po_inv['invoice_number'], po_inv['vendor_name'], po_inv['po_number_original'], user_id, username, po_inv['condition_type'], notes or 'Rejected by pharmacy user' )) conn.commit() conn.close() return jsonify({'success': True, 'approval_status': 'rejected', 'message': 'Invoice rejected.'}), 200 except Exception as e: logger.error(f"❌ PO approval reject error: {e}") return jsonify({'success': False, 'error': str(e)}), 500 @app.route('/api/po-approval//retry-webhook', methods=['POST']) @login_required def po_approval_retry_webhook(history_id): """Retry sending the webhook for an approval history record.""" try: conn = get_db() cursor = conn.cursor() cursor.execute('SELECT * FROM po_approval_history WHERE id = ?', (history_id,)) row = cursor.fetchone() if not row: conn.close() return jsonify({'success': False, 'error': 'History record not found'}), 404 webhook_payload = { 'event': 'po_number_approved', 'condition_type': row['condition_type'] or 'condition_4', 'invoice_id': row['po_invoice_id'], 'invoice_number': row['invoice_number'], 'vendor_name': row['vendor_name'], 'approved_po_number': row['po_number_approved'], 'approved_by': row['approved_by'], 'approved_by_username': row['approved_by_username'], 'approval_status': row['approval_status'], } wh_result = trigger_po_approval_webhook(webhook_payload) wh_response_text = json.dumps(wh_result) if wh_result.get('status') == 'success' else None wh_error_text = wh_result.get('error') or wh_result.get('message') cursor.execute(''' UPDATE po_approval_history SET webhook_status = ?, webhook_response = ?, webhook_error = ?, webhook_triggered_at = CURRENT_TIMESTAMP WHERE id = ? ''', (wh_result['status'], wh_response_text, wh_error_text, history_id)) conn.commit() conn.close() return jsonify({'success': True, 'webhook_status': wh_result['status']}), 200 except Exception as e: logger.error(f"❌ PO approval retry webhook error: {e}") return jsonify({'success': False, 'error': str(e)}), 500 @app.route('/api/po-approval/history', methods=['GET']) @login_required def po_approval_history(): """Paginated PO and Item Code approval history with Condition 1-5 filters.""" try: status_filter = request.args.get('status', '').strip() cond_filter = request.args.get('condition_type', '').strip() type_filter = request.args.get('approval_type', '').strip() webhook_status_filter = request.args.get('webhook_status', '').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 status_filter and status_filter != 'all': where.append('approval_status = ?') params.append(status_filter) if cond_filter and cond_filter != 'all': where.append('condition_type = ?') params.append(cond_filter) if type_filter and type_filter != 'all': where.append('approval_type = ?') params.append(type_filter) if webhook_status_filter and webhook_status_filter != 'all': where.append('webhook_status = ?') params.append(webhook_status_filter) where_clause = ('WHERE ' + ' AND '.join(where)) if where else '' conn = get_db() cursor = conn.cursor() cursor.execute(f'SELECT COUNT(*) AS c FROM po_approval_history {where_clause}', params) total = cursor.fetchone()['c'] offset = (page - 1) * per_page cursor.execute( f'SELECT * FROM po_approval_history {where_clause} ORDER BY approval_timestamp DESC LIMIT ? OFFSET ?', params + [per_page, offset] ) rows = cursor.fetchall() conn.close() return jsonify({ 'success': True, 'data': [dict(r) for r in rows], 'total': total, 'page': page, 'per_page': per_page, 'has_more': offset + len(rows) < total, }), 200 except Exception as e: logger.error(f"❌ PO approval history error: {e}") return jsonify({'success': False, 'error': str(e)}), 500 @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 )