6185 lines
242 KiB
Python
6185 lines
242 KiB
Python
import werkzeug
|
||
if not hasattr(werkzeug, '__version__'):
|
||
werkzeug.__version__ = '3.0.0'
|
||
import item_code_matcher as icm
|
||
import sys
|
||
if hasattr(sys.stdout, 'reconfigure'):
|
||
sys.stdout.reconfigure(encoding='utf-8')
|
||
if hasattr(sys.stderr, 'reconfigure'):
|
||
sys.stderr.reconfigure(encoding='utf-8')
|
||
from dotenv import load_dotenv
|
||
load_dotenv()
|
||
from gstin_validator import post_process_header_fields
|
||
from free_item_splitter import split_free_items, get_free_item_stats
|
||
|
||
# ================================================================
|
||
# ✅ NEW MODULAR HELPERS
|
||
# ================================================================
|
||
# consistency_checker: WIRED IN near end of extraction — purely additive,
|
||
# flags suspicious rows/totals for review without changing any value.
|
||
from consistency_checker import run_consistency_checks
|
||
|
||
|
||
# ocr_client: WIRED IN. The old inline QianfanOCRClient class was dead code
|
||
# (never instantiated), so importing this instead changes nothing at
|
||
# runtime, and removes the duplicate.
|
||
from ocr_client import QianfanOCRClient as StandaloneQianfanOCRClient
|
||
|
||
# pdf_utils: WIRED IN, replacing both inline pdf_to_images_pymupdf()
|
||
# definitions. Both live call sites now pass dpi=300 explicitly to
|
||
# preserve the exact resolution the old (shadowed) definition used.
|
||
from pdf_utils import pdf_to_images as pdf_to_images_standalone, get_pdf_page_count
|
||
|
||
# seller_gstin_lookup: WIRED IN, replacing the Excel-based
|
||
# _apply_seller_master() at the seller-GSTIN-correction call site.
|
||
# Uses the hardcoded SELLER_GSTIN_MAP as instructed.
|
||
from seller_gstin_lookup import lookup_seller_gstin, apply_seller_gstin_override
|
||
|
||
# ocr_corrector: WIRED IN below (after seller GSTIN override). app.py had
|
||
# ZERO date-correction logic before this — expiry_date/invoice_date/
|
||
# due_date/DC_date passed straight through from the model, uncorrected.
|
||
# This is what was producing malformed dates like "28-Feb-30". Also
|
||
# fixes GSTIN OCR confusion (0/O, 1/I, etc.), HSN codes, and pulls
|
||
# Batch/expiry/item_code out of the description text when the fields
|
||
# themselves are empty. correct_date()'s own output uses DD/MM/YYYY
|
||
# (slashes) — converted to DD-MM-YYYY (hyphens) right after the call,
|
||
# in app.py only, so ocr_corrector.py itself stays untouched.
|
||
from ocr_corrector import apply_ocr_corrections
|
||
|
||
# gst_calculator: imported, NOT wired into any call site. This app's real
|
||
# GST logic is the Phase A-C pipeline further down (process_gst() is
|
||
# defined but deliberately unused — see comment near HEADER_FIELDS),
|
||
# which recalculates GST from rate x taxable_value and includes a
|
||
# hand-tuned HSN-summary rate backfill for invoices where item rows
|
||
# carry no rate (e.g. Kanchan Drugs format). gst_calculator.py instead
|
||
# preserves whatever GST amounts were extracted and never recalculates.
|
||
# These are opposite philosophies — swapping it in would change tax
|
||
# totals on live invoices, so it's left available but inactive pending
|
||
# your explicit confirmation.
|
||
from gst_calculator import GSTCalculator, enrich_and_validate_gst
|
||
|
||
import re
|
||
import io
|
||
import json
|
||
import os
|
||
from datetime import datetime, timedelta
|
||
import unicodedata
|
||
import secrets
|
||
import time
|
||
import bcrypt
|
||
import fitz
|
||
from flask import (
|
||
Flask,
|
||
flash,
|
||
redirect,
|
||
render_template,
|
||
request,
|
||
jsonify,
|
||
send_file,
|
||
session,
|
||
url_for,
|
||
send_from_directory,
|
||
)
|
||
import base64
|
||
import requests as _http_requests
|
||
import pandas as pd
|
||
from werkzeug.utils import secure_filename
|
||
from PIL import Image
|
||
import logging
|
||
from functools import wraps
|
||
from flask_cors import CORS
|
||
from werkzeug.security import check_password_hash, generate_password_hash
|
||
import ssl
|
||
import mysql.connector
|
||
from mysql.connector import pooling
|
||
from datetime import timedelta
|
||
utc_now = datetime.utcnow()
|
||
from pdf2image import convert_from_path
|
||
from datetime import datetime, timezone
|
||
from zoneinfo import ZoneInfo
|
||
|
||
# ================================================================
|
||
# ✅ IMAGE PREPROCESSING (rotation / deskew / contrast / sharpen)
|
||
# ================================================================
|
||
# Loaded once at module import so the (potentially slow) orientation
|
||
# detector isn't re-initialized on every invoice. If preprocessing.py
|
||
# or its dependencies (cv2/numpy) aren't available, we fail soft and
|
||
# skip preprocessing entirely rather than breaking extraction.
|
||
try:
|
||
from preprocessing import ImagePreprocessor
|
||
_image_preprocessor = ImagePreprocessor()
|
||
_PREPROCESSING_ENABLED = True
|
||
print("✅ Image preprocessing (orientation/deskew/enhance) loaded.")
|
||
except Exception as _prep_err:
|
||
_image_preprocessor = None
|
||
_PREPROCESSING_ENABLED = False
|
||
print(f"⚠️ Image preprocessing unavailable ({_prep_err}). Skipping.")
|
||
|
||
|
||
def preprocess_invoice_image(pil_img):
|
||
"""
|
||
Run the ImagePreprocessor pipeline (deskew, contrast, sharpen) on a
|
||
single page before it's sent to the OCR/vision model.
|
||
|
||
Orientation correction is intentionally OFF by default. preprocessing.py's
|
||
OrientationDetector tries a real OCR-based check first (QianfanOCRClient),
|
||
but that module isn't part of this project, so it always fails and silently
|
||
falls back to a crude aspect-ratio heuristic ("portrait page => must be
|
||
rotated 90/270"). That assumption is wrong for normal A4 invoice pages and
|
||
will actively mis-rotate correctly-oriented pages. Re-enable do_orient=True
|
||
only once a real orientation signal (working OCR client, or a model-based
|
||
check) is wired in.
|
||
|
||
Denoising is left off too — it tends to blur small print like batch
|
||
numbers and GSTINs, which matters more here than general noise.
|
||
Falls back to the original image on any failure.
|
||
"""
|
||
if not _PREPROCESSING_ENABLED:
|
||
return pil_img
|
||
try:
|
||
processed_img, debug_info = _image_preprocessor.process(
|
||
pil_img,
|
||
do_orient=False,
|
||
do_deskew=True,
|
||
do_enhance=True,
|
||
do_denoise=False,
|
||
do_sharpen=True,
|
||
)
|
||
print(f"🖼️ Preprocessing applied: {debug_info.get('steps_applied')}")
|
||
return processed_img
|
||
except Exception as e:
|
||
print(f"⚠️ Preprocessing failed, using original image: {e}")
|
||
return pil_img
|
||
|
||
|
||
# ================================================================
|
||
# ✅ UTILITY — normalize unicode to plain ASCII
|
||
# ================================================================
|
||
def normalize_text(value):
|
||
"""Convert unicode characters to closest ASCII. ä→a, é→e, ü→u"""
|
||
if not value or not isinstance(value, str):
|
||
return value
|
||
normalized = unicodedata.normalize("NFKD", value)
|
||
return normalized.encode("ascii", "ignore").decode("ascii").strip()
|
||
|
||
app = Flask(__name__)
|
||
from zoneinfo import ZoneInfo
|
||
|
||
|
||
# ================================================================
|
||
# ✅ VENDOR MASTER & GSTIN LOOKUP — backed by 'Seller_GSTIN.xlsx'
|
||
# ================================================================
|
||
from seller_gstin_lookup import load_vendor_master_excel, apply_seller_gstin_override
|
||
|
||
def _load_seller_master(*args, **kwargs):
|
||
"""Backwards-compatible alias for loading vendor master Excel."""
|
||
load_vendor_master_excel()
|
||
|
||
def _apply_seller_master(extracted_data: dict) -> dict:
|
||
"""Backwards-compatible alias for applying vendor master and GSTIN override."""
|
||
return apply_seller_gstin_override(extracted_data)
|
||
|
||
|
||
# ── OpenRouter / Qwen + Qianfan setup ────────────────────────────────────────
|
||
OPENROUTER_API_KEY = os.getenv("OPENROUTER_API_KEY")
|
||
QWEN_MODEL = os.getenv("MODEL_NAME", "qwen/qwen3.8-max")
|
||
QIANFAN_MODEL = "baidu/qianfan-ocr-fast:free"
|
||
|
||
OPENROUTER_BASE_URL = "https://openrouter.ai/api/v1/chat/completions"
|
||
|
||
# Set USE_QIANFAN=true in .env to use Qianfan OCR model instead of Qwen.
|
||
_USE_QIANFAN = os.getenv("USE_QIANFAN", "false").strip().lower() in ("1", "true", "yes")
|
||
ACTIVE_MODEL = QIANFAN_MODEL if _USE_QIANFAN else QWEN_MODEL
|
||
|
||
def _qwen_call(system_prompt: str, user_text: str, image_b64: str,
|
||
temperature: float = 0.0, max_tokens: int = 65535) -> str:
|
||
"""
|
||
Call Qwen vision model via OpenRouter and return the raw response text.
|
||
Raises on HTTP error.
|
||
"""
|
||
headers = {
|
||
"Authorization": f"Bearer {OPENROUTER_API_KEY}",
|
||
"Content-Type": "application/json",
|
||
}
|
||
payload = {
|
||
"model": ACTIVE_MODEL,
|
||
"temperature": temperature,
|
||
"max_tokens": max_tokens,
|
||
"messages": [
|
||
{"role": "system", "content": system_prompt},
|
||
{
|
||
"role": "user",
|
||
"content": [
|
||
{"type": "text", "text": user_text},
|
||
{"type": "image_url", "image_url": {"url": image_b64}},
|
||
],
|
||
},
|
||
],
|
||
}
|
||
resp = _http_requests.post(OPENROUTER_BASE_URL, headers=headers, json=payload, timeout=300)
|
||
|
||
resp.raise_for_status()
|
||
data = resp.json()
|
||
return data["choices"][0]["message"]["content"].strip()
|
||
|
||
def _qwen_text_call(system_prompt: str, user_text: str,
|
||
temperature: float = 0.0, max_tokens: int = 65535) -> str:
|
||
"""Call Qwen text-only (no image) via OpenRouter."""
|
||
headers = {
|
||
"Authorization": f"Bearer {OPENROUTER_API_KEY}",
|
||
"Content-Type": "application/json",
|
||
}
|
||
payload = {
|
||
"model": ACTIVE_MODEL,
|
||
"temperature": temperature,
|
||
"max_tokens": max_tokens,
|
||
"messages": [
|
||
{"role": "system", "content": system_prompt},
|
||
{"role": "user", "content": user_text},
|
||
],
|
||
}
|
||
resp = _http_requests.post(OPENROUTER_BASE_URL, headers=headers, json=payload, timeout=120)
|
||
resp.raise_for_status()
|
||
data = resp.json()
|
||
return data["choices"][0]["message"]["content"].strip()
|
||
|
||
def _pil_to_b64(pil_img: Image.Image, max_size: int = 2048) -> str:
|
||
"""Resize PIL image if needed and return base64 data-URI."""
|
||
w, h = pil_img.size
|
||
if w > max_size or h > max_size:
|
||
scale = max_size / max(w, h)
|
||
pil_img = pil_img.resize((int(w * scale), int(h * scale)), Image.Resampling.LANCZOS)
|
||
buf = io.BytesIO()
|
||
fmt = "JPEG" if w * h > 1_000_000 else "PNG"
|
||
pil_img.convert("RGB").save(buf, format=fmt, quality=85 if fmt == "JPEG" else None)
|
||
b64 = base64.b64encode(buf.getvalue()).decode()
|
||
return f"data:image/{fmt.lower()};base64,{b64}"
|
||
|
||
|
||
# ── Qianfan OCR Client ──────────────────────────────────────────────────
|
||
# (moved to ocr_client.py — imported above as StandaloneQianfanOCRClient.
|
||
# This inline class was never instantiated anywhere in this file, so
|
||
# removing it changes nothing at runtime.)
|
||
|
||
# Allowed file extensions
|
||
ALLOWED_EXTENSIONS = {"pdf", "jpeg", "jpg", "png"}
|
||
|
||
# API Keys loaded from environment variables
|
||
API_KEYS = [os.getenv("API_KEY_1"), os.getenv("API_KEY_2")]
|
||
|
||
# Usage limit per API key per day
|
||
USAGE_LIMIT = 10
|
||
|
||
# MySQL Configuration
|
||
MYSQL_CONFIG = {
|
||
"host": os.getenv("MYSQL_HOST"),
|
||
"user": os.getenv("MYSQL_USER"),
|
||
"password": os.getenv("MYSQL_PASSWORD"),
|
||
"database": os.getenv("MYSQL_DB"),
|
||
"auth_plugin": "mysql_native_password",
|
||
"pool_name": "my_pool",
|
||
"pool_size": 20,
|
||
"pool_reset_session": True,
|
||
"autocommit": True,
|
||
"buffered": True,
|
||
"connection_timeout": 3,
|
||
}
|
||
|
||
# Connection Pool
|
||
try:
|
||
cnxpool = mysql.connector.pooling.MySQLConnectionPool(**MYSQL_CONFIG)
|
||
except Exception as _e:
|
||
print(f"Warning: Failed to initialize MySQL connection pool on startup: {_e}")
|
||
cnxpool = None
|
||
|
||
# print("Sender:", os.getenv("EMAIL_ADDRESS"))
|
||
# print("Password:", os.getenv("EMAIL_PASSWORD"))
|
||
def format_currency(value, symbol="₹"):
|
||
if value is None:
|
||
return None
|
||
try:
|
||
return f"{symbol} {float(value):.2f}"
|
||
except:
|
||
return value
|
||
|
||
|
||
import sqlite3
|
||
|
||
class SQLiteCursorWrapper:
|
||
def __init__(self, cursor, dictionary=False):
|
||
self._cursor = cursor
|
||
self.dictionary = dictionary
|
||
|
||
def execute(self, query, params=None):
|
||
query_sql = query.replace('%s', '?')
|
||
if params is not None:
|
||
if not isinstance(params, (tuple, list, dict)):
|
||
params = (params,)
|
||
self._cursor.execute(query_sql, params)
|
||
else:
|
||
self._cursor.execute(query_sql)
|
||
return self
|
||
|
||
def fetchone(self):
|
||
row = self._cursor.fetchone()
|
||
if row is None:
|
||
return None
|
||
if self.dictionary and self._cursor.description:
|
||
cols = [d[0] for d in self._cursor.description]
|
||
return dict(zip(cols, row))
|
||
return row
|
||
|
||
def fetchall(self):
|
||
rows = self._cursor.fetchall()
|
||
if self.dictionary and self._cursor.description:
|
||
cols = [d[0] for d in self._cursor.description]
|
||
return [dict(zip(cols, r)) for r in rows]
|
||
return rows
|
||
|
||
@property
|
||
def lastrowid(self):
|
||
return self._cursor.lastrowid
|
||
|
||
@property
|
||
def rowcount(self):
|
||
return self._cursor.rowcount
|
||
|
||
def close(self):
|
||
try:
|
||
self._cursor.close()
|
||
except Exception:
|
||
pass
|
||
|
||
class SQLiteConnectionWrapper:
|
||
def __init__(self, db_path='invoice.db'):
|
||
self.conn = sqlite3.connect(db_path, check_same_thread=False)
|
||
self.conn.row_factory = sqlite3.Row
|
||
|
||
def cursor(self, dictionary=False, buffered=False):
|
||
return SQLiteCursorWrapper(self.conn.cursor(), dictionary=dictionary)
|
||
|
||
def commit(self):
|
||
self.conn.commit()
|
||
|
||
def rollback(self):
|
||
self.conn.rollback()
|
||
|
||
def close(self):
|
||
self.conn.close()
|
||
|
||
def ping(self, reconnect=True, attempts=1, delay=0):
|
||
pass
|
||
|
||
def start_transaction(self, consistent_snapshot=False, isolation_level=None, readonly=None):
|
||
pass
|
||
|
||
|
||
PHARMACY_DATABASE = os.getenv('PHARMACY_DATABASE', 'users.db')
|
||
|
||
def get_db():
|
||
"""Returns a direct SQLite connection with sqlite3.Row factory for Pharmacy / PO Approval subsystem (users.db)."""
|
||
conn = sqlite3.connect(PHARMACY_DATABASE, check_same_thread=False)
|
||
conn.row_factory = sqlite3.Row
|
||
return conn
|
||
|
||
|
||
def ensure_po_approval_tables():
|
||
"""Ensure all tables required for PO Approval & Item Code Management exist in users.db."""
|
||
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,
|
||
condition_type TEXT DEFAULT 'condition_4',
|
||
approval_status TEXT DEFAULT 'pending',
|
||
item_code_status TEXT DEFAULT 'pending',
|
||
items_json TEXT,
|
||
approved_by INTEGER,
|
||
approved_at TIMESTAMP,
|
||
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
||
)
|
||
''')
|
||
|
||
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,
|
||
condition_type TEXT,
|
||
approval_type TEXT DEFAULT 'po_approval',
|
||
approved_by INTEGER,
|
||
approved_by_username TEXT,
|
||
approved_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||
approval_timestamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||
notes TEXT,
|
||
webhook_status TEXT DEFAULT 'pending',
|
||
webhook_triggered_at TIMESTAMP,
|
||
webhook_response TEXT,
|
||
webhook_error TEXT
|
||
)
|
||
''')
|
||
|
||
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
|
||
)
|
||
''')
|
||
|
||
cursor.execute('''
|
||
CREATE TABLE IF NOT EXISTS 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
|
||
)
|
||
''')
|
||
|
||
cursor.execute("PRAGMA table_info(po_approval_history)")
|
||
hist_cols = [c[1] for c in cursor.fetchall()]
|
||
if 'approved_at' not in hist_cols:
|
||
try:
|
||
cursor.execute("ALTER TABLE po_approval_history ADD COLUMN approved_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP")
|
||
except Exception:
|
||
pass
|
||
if 'approval_timestamp' not in hist_cols:
|
||
try:
|
||
cursor.execute("ALTER TABLE po_approval_history ADD COLUMN approval_timestamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP")
|
||
except Exception:
|
||
pass
|
||
if 'approved_by_username' not in hist_cols:
|
||
try:
|
||
cursor.execute("ALTER TABLE po_approval_history ADD COLUMN approved_by_username TEXT")
|
||
except Exception:
|
||
pass
|
||
if 'condition_type' not in hist_cols:
|
||
try:
|
||
cursor.execute("ALTER TABLE po_approval_history ADD COLUMN condition_type TEXT")
|
||
except Exception:
|
||
pass
|
||
if 'approval_type' not in hist_cols:
|
||
try:
|
||
cursor.execute("ALTER TABLE po_approval_history ADD COLUMN approval_type TEXT DEFAULT 'po_approval'")
|
||
except Exception:
|
||
pass
|
||
|
||
cursor.execute("PRAGMA table_info(users)")
|
||
user_cols = [c[1] for c in cursor.fetchall()]
|
||
if 'is_active' not in user_cols:
|
||
try:
|
||
cursor.execute("ALTER TABLE users ADD COLUMN is_active INTEGER DEFAULT 1")
|
||
except Exception:
|
||
pass
|
||
if 'is_admin' not in user_cols:
|
||
try:
|
||
cursor.execute("ALTER TABLE users ADD COLUMN is_admin INTEGER DEFAULT 0")
|
||
except Exception:
|
||
pass
|
||
if 'created_at' not in user_cols:
|
||
try:
|
||
cursor.execute("ALTER TABLE users ADD COLUMN created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP")
|
||
except Exception:
|
||
pass
|
||
if 'last_login' not in user_cols:
|
||
try:
|
||
cursor.execute("ALTER TABLE users ADD COLUMN last_login TIMESTAMP")
|
||
except Exception:
|
||
pass
|
||
if 'role' not in user_cols:
|
||
try:
|
||
cursor.execute("ALTER TABLE users ADD COLUMN role VARCHAR(50) DEFAULT 'user'")
|
||
except Exception:
|
||
pass
|
||
|
||
cursor.execute("SELECT id FROM users WHERE username = 'pharmacy'")
|
||
if not cursor.fetchone():
|
||
hashed_pw = bcrypt.hashpw(b'pharmacy123', bcrypt.gensalt()).decode('utf-8')
|
||
cursor.execute(
|
||
"INSERT INTO users (username, email, password, is_active, is_admin) VALUES (?, ?, ?, 1, 1)",
|
||
('pharmacy', 'pharmacy@hospital.local', hashed_pw)
|
||
)
|
||
|
||
conn.commit()
|
||
conn.close()
|
||
|
||
|
||
_last_mysql_fail_time = 0
|
||
|
||
def get_db_connection():
|
||
"""Returns a MySQL connection or fallback SQLite connection."""
|
||
global cnxpool, _last_mysql_fail_time
|
||
now = time.time()
|
||
if cnxpool is None and (now - _last_mysql_fail_time < 15):
|
||
return SQLiteConnectionWrapper('invoice.db')
|
||
try:
|
||
if cnxpool is None:
|
||
cnxpool = mysql.connector.pooling.MySQLConnectionPool(**MYSQL_CONFIG)
|
||
cnx = cnxpool.get_connection()
|
||
cnx.ping(reconnect=True, attempts=3, delay=1)
|
||
return cnx
|
||
except Exception as e:
|
||
_last_mysql_fail_time = now
|
||
cnxpool = None
|
||
return SQLiteConnectionWrapper('invoice.db')
|
||
|
||
def fix_existing_limits():
|
||
conn = get_db_connection()
|
||
cursor = conn.cursor()
|
||
cursor.execute(
|
||
"UPDATE users SET account_limit = 50 WHERE account_limit IS NULL OR account_limit < 50"
|
||
)
|
||
conn.commit()
|
||
cursor.close()
|
||
conn.close()
|
||
print("User limits updated to 50")
|
||
def init_db():
|
||
conn = get_db_connection()
|
||
cursor = conn.cursor()
|
||
|
||
cursor.execute(
|
||
"""
|
||
CREATE TABLE IF NOT EXISTS contact_queries (
|
||
id INT AUTO_INCREMENT PRIMARY KEY,
|
||
email VARCHAR(255) NOT NULL,
|
||
contact VARCHAR(50),
|
||
message TEXT NOT NULL,
|
||
timestamp DATETIME DEFAULT CURRENT_TIMESTAMP
|
||
)
|
||
"""
|
||
)
|
||
|
||
cursor.execute(
|
||
"""
|
||
CREATE TABLE IF NOT EXISTS users (
|
||
id INT AUTO_INCREMENT PRIMARY KEY,
|
||
username VARCHAR(255) UNIQUE,
|
||
email VARCHAR(255) UNIQUE,
|
||
password VARCHAR(255),
|
||
phone VARCHAR(20), -- new phone column
|
||
invoices_extracted INT DEFAULT 10,
|
||
passports_extracted INT DEFAULT 10,
|
||
account_limit INT DEFAULT 50,
|
||
manual_limit INT DEFAULT 50,
|
||
api_limit INT DEFAULT 50,
|
||
role VARCHAR(50) DEFAULT 'user'
|
||
)
|
||
"""
|
||
)
|
||
|
||
cursor.execute(
|
||
"""
|
||
CREATE TABLE IF NOT EXISTS extraction_history (
|
||
id INT AUTO_INCREMENT PRIMARY KEY,
|
||
user_id INT,
|
||
timestamp DATETIME,
|
||
image_name VARCHAR(255),
|
||
pages_extracted INT,
|
||
extraction_type VARCHAR(50),
|
||
input_tokens INT DEFAULT 0,
|
||
output_tokens INT DEFAULT 0,
|
||
cost_usd DECIMAL(10,6) DEFAULT 0.000000,
|
||
FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
|
||
)
|
||
"""
|
||
)
|
||
|
||
# ── Add missing columns to extraction_history if they don't exist yet ──
|
||
for _col, _defn in [
|
||
("invoice_id", "VARCHAR(50)"),
|
||
("invoice_source", "VARCHAR(50)"),
|
||
("extracted_data", "LONGTEXT"),
|
||
("file_path", "VARCHAR(255)"),
|
||
("input_tokens", "INT DEFAULT 0"),
|
||
("output_tokens", "INT DEFAULT 0"),
|
||
("cost_usd", "DECIMAL(10,6) DEFAULT 0.000000"),
|
||
("status", "VARCHAR(50) DEFAULT 'pending_approval'"),
|
||
("validation_status", "VARCHAR(50)"),
|
||
("validation_errors", "TEXT"),
|
||
("approved_by", "INT"),
|
||
("approved_at", "DATETIME"),
|
||
("processed_at", "DATETIME"),
|
||
]:
|
||
try:
|
||
cursor.execute(
|
||
f"ALTER TABLE extraction_history ADD COLUMN {_col} {_defn}"
|
||
)
|
||
except Exception:
|
||
pass # Column already exists — ignore
|
||
|
||
cursor.execute(
|
||
"""
|
||
CREATE TABLE IF NOT EXISTS api_keys (
|
||
id INT AUTO_INCREMENT PRIMARY KEY,
|
||
user_id INT,
|
||
api_key VARCHAR(255) UNIQUE,
|
||
created_at DATETIME,
|
||
FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
|
||
)
|
||
"""
|
||
)
|
||
|
||
cursor.execute(
|
||
"""
|
||
CREATE TABLE IF NOT EXISTS api_usage (
|
||
id INT AUTO_INCREMENT PRIMARY KEY,
|
||
api_key VARCHAR(255) UNIQUE,
|
||
count INT DEFAULT 0,
|
||
last_used DATE,
|
||
usage_limit INT,
|
||
FOREIGN KEY (api_key) REFERENCES api_keys(api_key) ON DELETE CASCADE
|
||
)
|
||
"""
|
||
)
|
||
|
||
# ensure admin user exists
|
||
cursor.execute(
|
||
"SELECT * FROM users WHERE username = 'Niraj' AND email = 'connect.aiindia@gmail.com'"
|
||
)
|
||
admin_user = cursor.fetchone()
|
||
if not admin_user:
|
||
cursor.execute(
|
||
"""
|
||
INSERT INTO users (username, email, password, role)
|
||
VALUES (
|
||
'Niraj',
|
||
'connect.aiindia@gmail.com',
|
||
'$2b$12$W9ObhLPinBHdnkX1XK6.U.Ub5mgx33abZtEY7xOVfHz5CMnM5tdWm',
|
||
'admin'
|
||
)
|
||
"""
|
||
)
|
||
conn.commit()
|
||
cursor.close()
|
||
conn.close()
|
||
|
||
try:
|
||
ensure_po_approval_tables()
|
||
except Exception as _po_tab_err:
|
||
print(f"[Warning] ensure_po_approval_tables error: {_po_tab_err}")
|
||
|
||
|
||
# Re-initialize the database
|
||
try:
|
||
init_db()
|
||
except Exception as _db_init_err:
|
||
print(f"[Warning] Database initialization skipped on startup: {_db_init_err}")
|
||
|
||
|
||
def ensure_pharmacy_account():
|
||
"""Ensure default pharmacy staff account exists."""
|
||
try:
|
||
conn = get_db_connection()
|
||
cursor = conn.cursor(dictionary=True)
|
||
cursor.execute("SELECT id, username, role FROM users WHERE username = %s OR role = 'pharmacy'", ('pharmacy',))
|
||
row = cursor.fetchone()
|
||
if not row:
|
||
hashed_pw = bcrypt.hashpw(b'pharmacy123', bcrypt.gensalt()).decode('utf-8')
|
||
cursor.execute(
|
||
"""
|
||
INSERT INTO users (username, email, password, role, account_limit, manual_limit, api_limit)
|
||
VALUES (%s, %s, %s, %s, 1000, 1000, 1000)
|
||
""",
|
||
('pharmacy', 'pharmacy@hospital.local', hashed_pw, 'pharmacy')
|
||
)
|
||
conn.commit()
|
||
print("✅ Default pharmacy staff account provisioned (pharmacy / pharmacy123)")
|
||
cursor.close()
|
||
conn.close()
|
||
except Exception as e:
|
||
print(f"[Warning] ensure_pharmacy_account skipped: {e}")
|
||
|
||
try:
|
||
ensure_pharmacy_account()
|
||
except Exception:
|
||
pass
|
||
|
||
|
||
# Re-initialize the database with the updated schema
|
||
|
||
|
||
# Initialize the Flask app
|
||
app = Flask(__name__)
|
||
CORS(app)
|
||
app.secret_key = os.getenv("FLASK_SECRET_KEY", default="fallback-secret-key")
|
||
UPLOAD_FOLDER = "uploads"
|
||
os.makedirs(UPLOAD_FOLDER, exist_ok=True)
|
||
app.config["UPLOAD_FOLDER"] = UPLOAD_FOLDER
|
||
|
||
|
||
def allowed_file(filename):
|
||
return "." in filename and filename.rsplit(".", 1)[1].lower() in ALLOWED_EXTENSIONS
|
||
|
||
|
||
def check_usage(api_key):
|
||
current_date = datetime.now().date()
|
||
conn = get_db_connection()
|
||
cursor = conn.cursor(dictionary=True)
|
||
sql = "SELECT * FROM api_usage WHERE api_key = %s"
|
||
cursor.execute(sql, (api_key,))
|
||
usage_entry = cursor.fetchone()
|
||
if not usage_entry:
|
||
sql_insert = (
|
||
"INSERT INTO api_usage (api_key, count, last_used) VALUES (%s, %s, %s)"
|
||
)
|
||
cursor.execute(sql_insert, (api_key, 0, current_date))
|
||
conn.commit()
|
||
usage_entry = {"count": 0, "last_used": current_date, "usage_limit": None}
|
||
else:
|
||
if usage_entry["last_used"] < current_date:
|
||
sql_update = (
|
||
"UPDATE api_usage SET count = 0, last_used = %s WHERE api_key = %s"
|
||
)
|
||
cursor.execute(sql_update, (current_date, api_key))
|
||
conn.commit()
|
||
usage_entry["count"] = 0
|
||
usage_entry["last_used"] = current_date
|
||
usage_limit = (
|
||
usage_entry["usage_limit"]
|
||
if usage_entry["usage_limit"] is not None
|
||
else USAGE_LIMIT
|
||
)
|
||
result = usage_entry["count"] < usage_limit
|
||
cursor.close()
|
||
conn.close()
|
||
return result
|
||
|
||
|
||
def api_key_required(f):
|
||
@wraps(f)
|
||
def decorated_function(*args, **kwargs):
|
||
api_key = request.headers.get("X-API-Key")
|
||
if not api_key:
|
||
return jsonify({"error": "Unauthorized: API Key is required"}), 401
|
||
conn = get_db_connection()
|
||
cursor = conn.cursor(dictionary=True)
|
||
sql = "SELECT * FROM api_usage WHERE api_key = %s"
|
||
cursor.execute(sql, (api_key,))
|
||
key_record = cursor.fetchone()
|
||
if not key_record:
|
||
cursor.close()
|
||
conn.close()
|
||
return jsonify({"error": "Unauthorized: Invalid API Key"}), 401
|
||
if key_record["count"] >= (
|
||
key_record["usage_limit"]
|
||
if key_record["usage_limit"] is not None
|
||
else USAGE_LIMIT
|
||
):
|
||
cursor.close()
|
||
conn.close()
|
||
return jsonify({"error": "Unauthorized: API Key usage limit exceeded"}), 403
|
||
sql_update = "UPDATE api_usage SET count = count + 1 WHERE api_key = %s"
|
||
cursor.execute(sql_update, (api_key,))
|
||
conn.commit()
|
||
cursor.close()
|
||
conn.close()
|
||
return f(*args, **kwargs)
|
||
|
||
return decorated_function
|
||
|
||
|
||
HEADER_FIELDS = [
|
||
"invoice_id",
|
||
"invoice_number",
|
||
"invoice_date",
|
||
"due_date",
|
||
"customer_name",
|
||
"customer_gstin",
|
||
"seller_name",
|
||
"seller_gstin",
|
||
"currency_code",
|
||
"PO_number",
|
||
"DC_date",
|
||
"DC_number",
|
||
"invoice_amount",
|
||
"round_off",
|
||
"total_gst_rate",
|
||
"total_quantity",
|
||
"total_cgst_rate",
|
||
"total_cgst_amount",
|
||
"total_sgst_rate",
|
||
"total_sgst_amount",
|
||
"total_igst_rate",
|
||
"total_igst_amount",
|
||
"total_gst_amount"
|
||
|
||
]
|
||
def generate_invoice_id(conn, invoice_source):
|
||
prefix = "M" if invoice_source == "manual" else "E"
|
||
today = datetime.now().strftime("%Y%m%d")
|
||
cursor = conn.cursor()
|
||
|
||
try:
|
||
# ✅ Use SELECT FOR UPDATE — locks the row
|
||
# ALL other requests block here until this completes
|
||
conn.start_transaction()
|
||
|
||
cursor.execute(
|
||
"""
|
||
SELECT last_seq, last_date
|
||
FROM invoice_id_lock
|
||
WHERE id = 1
|
||
FOR UPDATE
|
||
"""
|
||
)
|
||
row = cursor.fetchone()
|
||
|
||
last_seq = row[0] if row else 0
|
||
last_date = row[1] if row else ""
|
||
|
||
# ✅ Reset sequence if new day
|
||
if last_date != today:
|
||
new_seq = 1
|
||
else:
|
||
new_seq = last_seq + 1
|
||
|
||
# ✅ Update lock table with new sequence
|
||
cursor.execute(
|
||
"""
|
||
UPDATE invoice_id_lock
|
||
SET last_seq = %s, last_date = %s
|
||
WHERE id = 1
|
||
""",
|
||
(new_seq, today)
|
||
)
|
||
|
||
conn.commit() # ✅ releases FOR UPDATE lock
|
||
|
||
invoice_id = f"{prefix}{today}{str(new_seq).zfill(3)}"
|
||
print(f"✅ Generated invoice_id: {invoice_id}")
|
||
return invoice_id
|
||
|
||
except Exception as e:
|
||
conn.rollback()
|
||
print(f"❌ Invoice ID error: {e}")
|
||
# Fallback
|
||
import random
|
||
return f"{prefix}{today}{str(random.randint(100,999))}"
|
||
|
||
finally:
|
||
cursor.close()
|
||
|
||
|
||
|
||
def extract_invoice_fields(file_path, invoice_source="electronic", is_dmh=False, use_drug_list=True):
|
||
conn = None
|
||
try:
|
||
filename = os.path.basename(file_path)
|
||
print(f"\n{'='*70}", flush=True)
|
||
print(f"🚀 [EXTRACTION START] File: {filename} | Mode: {invoice_source} | Role: {'DMH' if is_dmh else 'Standard'}", flush=True)
|
||
print(f"{'='*70}", flush=True)
|
||
|
||
# ===============================
|
||
# 🔥 STEP 1: CREATE DB CONNECT
|
||
# ===============================
|
||
conn = get_db_connection()
|
||
|
||
# ===============================
|
||
# 🔥 STEP 2: GENERATE invoice_id
|
||
# ===============================
|
||
invoice_id = generate_invoice_id(conn, invoice_source)
|
||
|
||
# ===============================
|
||
# 🔹 STEP 3: Convert PDF to images
|
||
# ===============================
|
||
file_ext = os.path.splitext(file_path)[1].lower()
|
||
|
||
if file_ext == ".pdf":
|
||
images = pdf_to_images_standalone(file_path, dpi=300)
|
||
else:
|
||
images = [Image.open(file_path)]
|
||
|
||
print(f"📄 Loaded document: {len(images)} page(s) detected", flush=True)
|
||
|
||
# ── Preprocess every page before OCR (orientation, deskew, contrast, sharpen) ──
|
||
images = [preprocess_invoice_image(img) for img in images]
|
||
|
||
# ── Extract page text for multi-page alignment / fallback ──
|
||
page_texts = []
|
||
if file_ext == ".pdf":
|
||
try:
|
||
_doc = fitz.open(file_path)
|
||
for _p in _doc:
|
||
page_texts.append(_p.get_text() or "")
|
||
_doc.close()
|
||
except Exception as _fitz_err:
|
||
print(f"⚠️ Could not extract text via fitz: {_fitz_err}", flush=True)
|
||
|
||
import uuid
|
||
all_pages_data = []
|
||
|
||
# ── Billing accumulators (across all pages of this invoice) ──────
|
||
_total_input_tokens = 0
|
||
_total_output_tokens = 0
|
||
# Qwen2.5-VL-72B on OpenRouter pricing (USD per token) — update if rates change
|
||
_INPUT_PRICE_PER_TOKEN = 0.40 / 1_000_000
|
||
_OUTPUT_PRICE_PER_TOKEN = 1.20 / 1_000_000
|
||
|
||
from schema import SYSTEM_PROMPT, USER_PROMPT
|
||
|
||
for pg_idx, img in enumerate(images):
|
||
# Convert PIL Image → base64 data-URI for OpenRouter
|
||
image_b64 = _pil_to_b64(img)
|
||
|
||
# Context injection for multi-page invoices:
|
||
user_prompt_page = USER_PROMPT
|
||
if pg_idx > 0 and all_pages_data:
|
||
prev_items = [
|
||
it for it in (all_pages_data[-1].get("items") or all_pages_data[-1].get("Items") or [])
|
||
if it.get("description") and str(it.get("description")).strip() not in ('?', 'null', 'none', 'N/A', '')
|
||
]
|
||
if prev_items:
|
||
last_it = prev_items[-1]
|
||
if not last_it.get("Batch") or not last_it.get("expiry_date"):
|
||
prev_desc = str(last_it.get("description", ""))[:40]
|
||
user_prompt_page += (
|
||
f"\n\n⚠️⚠️⚠️ CRITICAL PAGE CONTINUATION:\n"
|
||
f"The PREVIOUS page ended with item '{prev_desc}' which has NO batch or expiry date extracted yet.\n"
|
||
f"LOOK AT THE TOP OF THIS PAGE:\n"
|
||
f"If this page starts with 'Batch & Expiry' or 'Item Code' lines before the next numbered product,\n"
|
||
f"those lines belong to '{prev_desc}' from the previous page!\n"
|
||
f"Return them as: {{'_continuation_for_previous_page': True, 'Batch': '...', 'expiry_date': '...', 'item_code': '...'}}\n"
|
||
f"DO NOT attach them to the first product on this page!\n"
|
||
)
|
||
|
||
# Call Qwen vision model via OpenRouter
|
||
print(f"🌐 Sending page {pg_idx + 1} to {ACTIVE_MODEL} via OpenRouter...")
|
||
response_text = _qwen_call(
|
||
system_prompt=SYSTEM_PROMPT,
|
||
user_text=user_prompt_page,
|
||
image_b64=image_b64,
|
||
temperature=0.0,
|
||
max_tokens=65535,
|
||
)
|
||
|
||
# ── Token usage is not returned by OpenRouter for Qwen —
|
||
# keep accumulators at zero (billing section still runs cleanly)
|
||
_in, _out = 0, 0
|
||
_total_input_tokens += _in
|
||
_total_output_tokens += _out
|
||
print(f"📊 Page processed — tokens not reported by OpenRouter")
|
||
|
||
# ── Clean common Gemini JSON artefacts ──────────────────────
|
||
# 1. Strip markdown fences (```json ... ``` or ``` ... ```)
|
||
if response_text.startswith("```"):
|
||
response_text = response_text.strip("`")
|
||
if response_text.lower().startswith("json"):
|
||
response_text = response_text[4:]
|
||
response_text = response_text.strip()
|
||
|
||
# 2. Remove trailing asterisks that appear in amount cells
|
||
# e.g. "15393.60*" → "15393.60"
|
||
import re as _re
|
||
response_text = _re.sub(r'(\d)\*+', r'\1', response_text)
|
||
|
||
# 3. Trim to last closing brace (handles trailing garbage)
|
||
if "}" in response_text:
|
||
response_text = response_text[: response_text.rfind("}") + 1]
|
||
|
||
# 3b. Strip trailing commas before ] or } — the #1 cause of
|
||
# "Expecting value" JSONDecodeError in LLM-generated JSON,
|
||
# e.g. `{"a": 1},\n]` → `{"a": 1}\n]`
|
||
response_text = _re.sub(r',(\s*[\]}])', r'\1', response_text)
|
||
|
||
# ── Attempt JSON parse with one auto-repair retry ────────────
|
||
def _try_parse(text):
|
||
"""Try json.loads; on failure attempt basic repairs."""
|
||
try:
|
||
return json.loads(text), None
|
||
except json.JSONDecodeError as e:
|
||
return None, e
|
||
|
||
def _repair_json(text):
|
||
"""
|
||
Close any unterminated strings/arrays/objects so that
|
||
json.loads has a better chance of succeeding.
|
||
Handles the most common Gemini truncation patterns.
|
||
"""
|
||
# Remove all control chars except tab/newline
|
||
text = _re.sub(r'[\x00-\x08\x0b\x0c\x0e-\x1f]', '', text)
|
||
# Replace smart/curly quotes with straight quotes
|
||
text = text.replace('\u201c', '"').replace('\u201d', '"')
|
||
text = text.replace('\u2018', "'").replace('\u2019', "'")
|
||
# Close any unterminated string: find last unescaped quote
|
||
# by counting depth. Simple heuristic: if odd number of
|
||
# unescaped double-quotes after the last complete value,
|
||
# append a closing quote.
|
||
try:
|
||
json.loads(text)
|
||
return text # already valid
|
||
except json.JSONDecodeError as e:
|
||
msg = str(e)
|
||
if "Unterminated string" in msg or "Invalid control character" in msg:
|
||
# Truncate at the position of the error
|
||
pos = e.pos
|
||
text = text[:pos].rstrip().rstrip(',')
|
||
# If we're inside an unterminated string, close it first
|
||
# Count unescaped double-quotes: odd count → still inside string
|
||
unescaped_quotes = len(_re.findall(r'(?<!\\\\)"', text))
|
||
if unescaped_quotes % 2 == 1:
|
||
text += '"' # close the open string
|
||
text = text.rstrip().rstrip(',')
|
||
# Close open structures
|
||
open_braces = text.count('{') - text.count('}')
|
||
open_brackets = text.count('[') - text.count(']')
|
||
text += ']' * max(open_brackets, 0)
|
||
text += '}' * max(open_braces, 0)
|
||
return text
|
||
|
||
page_data, err = _try_parse(response_text)
|
||
|
||
if page_data is None:
|
||
print(f"JSON parsing error (attempt 1): {err}")
|
||
repaired = _repair_json(response_text)
|
||
page_data, err2 = _try_parse(repaired)
|
||
if page_data is None:
|
||
print(f"JSON parsing error (attempt 2 after repair): {err2}")
|
||
# Last resort: retry Qwen with an explicit JSON-only instruction
|
||
try:
|
||
retry_prompt = (
|
||
"The following text is a broken JSON invoice extraction. "
|
||
"Fix it and return ONLY valid JSON, nothing else:\n\n"
|
||
+ response_text[:3000]
|
||
)
|
||
retry_text = _qwen_text_call(
|
||
system_prompt="You are a JSON repair engine. Return ONLY valid JSON.",
|
||
user_text=retry_prompt,
|
||
temperature=0.0,
|
||
max_tokens=65535,
|
||
)
|
||
retry_text = retry_text.strip().strip("`").strip()
|
||
if retry_text.lower().startswith("json"):
|
||
retry_text = retry_text[4:].strip()
|
||
if "}" in retry_text:
|
||
retry_text = retry_text[: retry_text.rfind("}") + 1]
|
||
page_data, err3 = _try_parse(retry_text)
|
||
if page_data is None:
|
||
print(f"JSON parsing error (attempt 3 Qwen retry): {err3}")
|
||
page_data = {"error": "Invalid JSON after all repair attempts"}
|
||
else:
|
||
print("✅ JSON recovered via Qwen retry")
|
||
except Exception as retry_exc:
|
||
print(f"Qwen retry failed: {retry_exc}")
|
||
page_data = {"error": "Invalid JSON returned from Qwen"}
|
||
else:
|
||
print("✅ JSON recovered via local repair")
|
||
|
||
all_pages_data.append(page_data)
|
||
if isinstance(page_data, dict):
|
||
items_cnt = len(page_data.get("items") or page_data.get("Items") or [])
|
||
inv_no = page_data.get("invoice_number") or "N/A"
|
||
po_no = page_data.get("PO_number") or "N/A"
|
||
amt = page_data.get("invoice_amount") or "N/A"
|
||
print(f"📦 [PAGE {pg_idx + 1}/{len(images)}] Extracted {items_cnt} item(s) | Inv#: {inv_no} | PO#: {po_no} | Amount: {amt}", flush=True)
|
||
|
||
# ---------------------------------------------------------------
|
||
# 🔥 PO NUMBER RAW-TEXT FALLBACK
|
||
#
|
||
# If JSON parsing was truncated/repaired, PO_number may be
|
||
# missing from page_data even though it exists in the raw
|
||
# response or in the original PDF text. As a safety net,
|
||
# scan response_text directly with regex patterns that match
|
||
# known PO/Order number formats before the DMH gate runs.
|
||
# ---------------------------------------------------------------
|
||
if isinstance(page_data, dict) and not page_data.get("PO_number"):
|
||
_po_patterns = [
|
||
r'(?:Order\s*No\.?|P\.?O\.?\s*No\.?|PO\s*No\.?|'
|
||
r'Purchase\s*Order\s*No\.?|Remark\s*:?)\s*[:\-]?\s*'
|
||
r'([A-Za-z0-9][A-Za-z0-9/\-]{4,})',
|
||
r'(DMH/PO/[A-Za-z0-9/\-]+)',
|
||
r'(DMH/[A-Za-z0-9/\-]+)',
|
||
]
|
||
for _pat in _po_patterns:
|
||
_m = _re.search(_pat, response_text, _re.IGNORECASE)
|
||
if _m:
|
||
_po_candidate = _m.group(1).strip().rstrip('.')
|
||
page_data["PO_number"] = _po_candidate
|
||
print(f"📌 PO extracted from raw text: {_po_candidate!r}", flush=True)
|
||
break
|
||
|
||
|
||
cgst_rates, sgst_rates, igst_rates = set(), set(), set()
|
||
|
||
# ===============================================================
|
||
# 🔥 FEATURE 1 — Deduplicate replica pages (Original / Duplicate / Triplicate)
|
||
#
|
||
# Invoices in PDFs frequently contain 2 or more pages where Page 2
|
||
# is an identical replica copy (e.g. "Duplicate for Transporter",
|
||
# "Triplicate", or duplicate buyer copy).
|
||
#
|
||
# When both pages represent the same invoice and all items on Page 2
|
||
# are identical to Page 1 (no new items):
|
||
# → SKIP the replica page so only 1 page's output is shown in the JSON!
|
||
# When Page 2 has new/different items:
|
||
# → It is a CONTINUATION page, so KEEP both pages!
|
||
# ===============================================================
|
||
_invoice_cost = (
|
||
_total_input_tokens * _INPUT_PRICE_PER_TOKEN +
|
||
_total_output_tokens * _OUTPUT_PRICE_PER_TOKEN
|
||
)
|
||
print(f"💰 Invoice total — input: {_total_input_tokens}, "
|
||
f"output: {_total_output_tokens}, cost: ${_invoice_cost:.6f}", flush=True)
|
||
|
||
def _norm_str(s):
|
||
if not s:
|
||
return ""
|
||
return str(s).strip().upper()
|
||
|
||
def _normalise_po(val):
|
||
if not val:
|
||
return ""
|
||
s = str(val).strip().upper()
|
||
if s in ("NONE", "NULL", "N/A", "NA", "-", "NOT FOUND", "EMPTY", "UNDEFINED"):
|
||
return ""
|
||
return s
|
||
|
||
def _clean_desc_text(d):
|
||
text = str(d or '').lower()
|
||
text = re.sub(r'(?:catalog|cat|ref|item|part)\s*(?:no|number)?\s*[:\-]?\s*[a-z0-9]+', '', text)
|
||
return re.sub(r'[^a-z0-9]', '', text)
|
||
|
||
def _items_match(it_a, it_b):
|
||
code_a = _norm_str(it_a.get("item_code"))
|
||
code_b = _norm_str(it_b.get("item_code"))
|
||
batch_a = _norm_str(it_a.get("Batch"))
|
||
batch_b = _norm_str(it_b.get("Batch"))
|
||
qty_a = str(it_a.get("quantity") or "").strip()
|
||
qty_b = str(it_b.get("quantity") or "").strip()
|
||
price_a = str(it_a.get("unit_price") or "").strip()
|
||
price_b = str(it_b.get("unit_price") or "").strip()
|
||
total_a = str(it_a.get("total_price") or it_a.get("taxable_value") or "").strip()
|
||
total_b = str(it_b.get("total_price") or it_b.get("taxable_value") or "").strip()
|
||
|
||
# Rule 1: Same item_code AND same batch
|
||
if code_a and code_b and code_a == code_b and batch_a and batch_b and batch_a == batch_b:
|
||
return True
|
||
|
||
# Rule 2: Same batch AND (same quantity OR same price)
|
||
if batch_a and batch_b and batch_a == batch_b and (qty_a == qty_b or price_a == price_b):
|
||
return True
|
||
|
||
# Rule 3: Same item_code AND (same quantity OR same price OR same total)
|
||
if code_a and code_b and code_a == code_b and (qty_a == qty_b or price_a == price_b or total_a == total_b):
|
||
return True
|
||
|
||
# Rule 4: Clean description match AND (same batch OR same quantity OR same price)
|
||
desc_a = _clean_desc_text(it_a.get("description"))
|
||
desc_b = _clean_desc_text(it_b.get("description"))
|
||
if desc_a and desc_b and (desc_a == desc_b or desc_a in desc_b or desc_b in desc_a):
|
||
if (batch_a and batch_b and batch_a == batch_b) or (qty_a and qty_b and qty_a == qty_b) or (price_a and price_b and price_a == price_b):
|
||
return True
|
||
|
||
return False
|
||
|
||
def _get_page_items(p):
|
||
return p.get("items") or p.get("Items") or []
|
||
|
||
def _is_page_replica_of(page_curr, page_prev):
|
||
curr_items = _get_page_items(page_curr)
|
||
prev_items = _get_page_items(page_prev)
|
||
if not curr_items or not prev_items:
|
||
return False, 0
|
||
|
||
# Count how many items on curr page match an item on prev page
|
||
matched = 0
|
||
for it_curr in curr_items:
|
||
for it_prev in prev_items:
|
||
if _items_match(it_prev, it_curr):
|
||
matched += 1
|
||
break
|
||
|
||
inv_curr = _norm_str(page_curr.get("invoice_number"))
|
||
inv_prev = _norm_str(page_prev.get("invoice_number"))
|
||
same_invoice_no = bool(inv_curr and inv_prev and inv_curr == inv_prev)
|
||
|
||
po_curr = _norm_str(page_curr.get("PO_number"))
|
||
po_prev = _norm_str(page_prev.get("PO_number"))
|
||
same_po = bool(po_curr and po_prev and po_curr == po_prev)
|
||
|
||
amt_curr = str(page_curr.get("invoice_amount") or "").strip()
|
||
amt_prev = str(page_prev.get("invoice_amount") or "").strip()
|
||
same_amount = bool(amt_curr and amt_prev and amt_curr == amt_prev and amt_curr not in ("0", "0.0", "0.00", ""))
|
||
|
||
# Decision criteria for duplicate invoice:
|
||
# 1. 100% of items on curr page match prev page
|
||
if matched > 0 and matched == len(curr_items):
|
||
return True, matched
|
||
|
||
# 2. Same invoice number (or same PO & amount) and at least 60% of items match
|
||
if (same_invoice_no or (same_po and same_amount)) and matched >= 2 and (matched >= len(curr_items) * 0.6):
|
||
return True, matched
|
||
|
||
# 3. Same invoice number, same total amount, and same item count
|
||
if same_invoice_no and same_amount and len(curr_items) == len(prev_items) and matched > 0:
|
||
return True, matched
|
||
|
||
return False, matched
|
||
|
||
if len(all_pages_data) > 1:
|
||
print(f"🔁 Checking multi-page deduplication across {len(all_pages_data)} pages...", flush=True)
|
||
deduplicated_pages = [all_pages_data[0]]
|
||
|
||
for p_idx in range(1, len(all_pages_data)):
|
||
page = all_pages_data[p_idx]
|
||
curr_items = _get_page_items(page)
|
||
|
||
# If page has NO items, it might be a tax summary or footer page — keep it
|
||
if not curr_items:
|
||
deduplicated_pages.append(page)
|
||
continue
|
||
|
||
# Check if this page is a duplicate copy of any previously kept page
|
||
is_replica = False
|
||
for prev_idx, prev_page in enumerate(deduplicated_pages):
|
||
is_rep, matched_cnt = _is_page_replica_of(page, prev_page)
|
||
if is_rep:
|
||
is_replica = True
|
||
inv_display = page.get("invoice_number") or prev_page.get("invoice_number") or "N/A"
|
||
print(f"🔁 Duplicate invoice copy detected: Page {p_idx+1} is a duplicate copy of Page {prev_idx+1} "
|
||
f"(Invoice: {inv_display!r}, {matched_cnt}/{len(curr_items)} items matched). Extracting only 1 invoice copy.", flush=True)
|
||
# Backfill any missing fields from duplicate page into previous page
|
||
for fld in HEADER_FIELDS:
|
||
if not prev_page.get(fld) and page.get(fld):
|
||
prev_page[fld] = page[fld]
|
||
break
|
||
|
||
if not is_replica:
|
||
print(f"📄 Continuation page kept: Page {p_idx+1} ({len(curr_items)} items found).", flush=True)
|
||
deduplicated_pages.append(page)
|
||
|
||
all_pages_data = deduplicated_pages
|
||
|
||
# ===============================================================
|
||
# 🔥 FEATURE 2 — PO number check (DMH)
|
||
#
|
||
# After deduplication, check whether at least one page carries a
|
||
# non-empty PO number, or recover it from raw text if possible.
|
||
# Even if PO number is missing, continue with extraction.
|
||
# ===============================================================
|
||
if is_dmh:
|
||
print("📋 [DMH] Checking PO number...", flush=True)
|
||
invoice_po = None
|
||
for page in all_pages_data:
|
||
po = _normalise_po(page.get("PO_number"))
|
||
if po:
|
||
invoice_po = po
|
||
break
|
||
|
||
# If still missing, check document text extracted by fitz (PDF)
|
||
if not invoice_po and 'page_texts' in locals() and page_texts:
|
||
for pt in page_texts:
|
||
for pat in [
|
||
r'(?:Order\s*No\.?|P\.?O\.?\s*No\.?|PO\s*No\.?|Purchase\s*Order\s*No\.?|Remark\s*:?)\s*[:\-]?\s*([A-Za-z0-9][A-Za-z0-9/\-]{4,})',
|
||
r'(DMH/PO/[A-Za-z0-9/\-]+)',
|
||
r'(DMH/[A-Za-z0-9/\-]+)',
|
||
]:
|
||
m = _re.search(pat, pt, _re.IGNORECASE)
|
||
if m:
|
||
cand = _normalise_po(m.group(1))
|
||
if cand:
|
||
invoice_po = cand
|
||
print(f"📌 [DMH] Recovered PO from document raw text: {invoice_po}", flush=True)
|
||
for p in all_pages_data:
|
||
if not p.get("PO_number"):
|
||
p["PO_number"] = invoice_po
|
||
break
|
||
if invoice_po:
|
||
break
|
||
|
||
if invoice_po:
|
||
for p in all_pages_data:
|
||
if not p.get("PO_number"):
|
||
p["PO_number"] = invoice_po
|
||
print(f"✅ [DMH] PO number confirmed: {invoice_po}", flush=True)
|
||
else:
|
||
print("ℹ️ [DMH] No PO number found on document — proceeding with extraction.", flush=True)
|
||
# ===============================================================
|
||
|
||
|
||
print("🔍 ALL PAGES DATA:", all_pages_data)
|
||
if all_pages_data:
|
||
print("🔍 FIRST PAGE KEYS:", all_pages_data[0].keys())
|
||
print("🔍 ITEMS:", all_pages_data[0].get("items"))
|
||
|
||
|
||
|
||
# ===================================================
|
||
# 🔥 ADD COMPLETE GST PROCESSING CODE RIGHT HERE
|
||
# ===================================================
|
||
from decimal import Decimal, ROUND_HALF_UP
|
||
|
||
def round2(value):
|
||
return float(
|
||
Decimal(str(value)).quantize(
|
||
Decimal("0.01"),
|
||
rounding=ROUND_HALF_UP
|
||
)
|
||
|
||
)
|
||
def safe_float(value):
|
||
if value is None:
|
||
return 0.0
|
||
try:
|
||
# Strip everything except digits, dot, minus
|
||
cleaned = re.sub(r"[^\d.\-]", "", str(value).strip())
|
||
return float(cleaned) if cleaned else 0.0
|
||
except:
|
||
return 0.0
|
||
|
||
def process_gst(all_pages_data, final_header):
|
||
final_header["total_cgst_amount"] = 0
|
||
final_header["total_sgst_amount"] = 0
|
||
final_header["total_igst_amount"] = 0
|
||
final_header["total_gst_amount"] = 0
|
||
|
||
total_cgst_amount = 0
|
||
total_sgst_amount = 0
|
||
total_igst_amount = 0
|
||
|
||
cgst_rates = set()
|
||
sgst_rates = set()
|
||
igst_rates = set()
|
||
|
||
|
||
|
||
for page in all_pages_data:
|
||
# 🔥 Handle both "items" and "Items"
|
||
items = page.get("items") or page.get("Items") or []
|
||
|
||
for item in items:
|
||
print("DEBUG qty:", repr(item.get("quantity")),
|
||
"unit_price:", repr(item.get("unit_price")),
|
||
"Value:", repr(item.get("Value")),
|
||
"cgst_rate:", repr(item.get("cgst_rate")))
|
||
qty = safe_float(item.get("quantity"))
|
||
unit_price = safe_float(item.get("unit_price"))
|
||
total_price = safe_float(item.get("total_price"))
|
||
|
||
discount = safe_float(item.get("Discount"))
|
||
value_field = safe_float(item.get("Value"))
|
||
# ✅ PRIORITY 1: If Value field exists, use it (most correct)
|
||
if value_field > 0:
|
||
taxable = round2(value_field)
|
||
# ✅ PRIORITY 2: If discount exists, calculate manually
|
||
elif discount > 0:
|
||
gross = qty * unit_price
|
||
taxable = round2(gross - (gross * discount / 100))
|
||
|
||
# ✅ PRIORITY 3: Use total_price
|
||
elif total_price > 0:
|
||
taxable = round2(total_price)
|
||
|
||
# ✅ FINAL fallback
|
||
else:
|
||
taxable = round2(qty * unit_price)
|
||
|
||
|
||
|
||
item["taxable_value"] = taxable
|
||
|
||
cgst_rate = safe_float(item.get("cgst_rate")) # ✅ handles None
|
||
sgst_rate = safe_float(item.get("sgst_rate")) # ✅ handles None
|
||
igst_rate = safe_float(item.get("igst_rate"))
|
||
# ✅ Always recalculate (do NOT depend on Gemini amount)
|
||
item["cgst_amount"] = round2(taxable * cgst_rate / 100)
|
||
item["sgst_amount"] = round2(taxable * sgst_rate / 100)
|
||
item["igst_amount"] = round2(taxable * igst_rate / 100)
|
||
#ADD THESE TWO LINES
|
||
item["GST_AMT"] = round2(item["cgst_amount"] + item["sgst_amount"] + item["igst_amount"])
|
||
item["Gst%"] = round2(cgst_rate + sgst_rate + igst_rate)
|
||
total_cgst_amount += item["cgst_amount"]
|
||
total_sgst_amount += item["sgst_amount"]
|
||
total_igst_amount += item["igst_amount"]
|
||
|
||
if cgst_rate > 0:
|
||
cgst_rates.add(cgst_rate)
|
||
if sgst_rate > 0:
|
||
sgst_rates.add(sgst_rate)
|
||
if igst_rate > 0:
|
||
igst_rates.add(igst_rate)
|
||
|
||
# 🔥 Normalize items key
|
||
page["items"] = items
|
||
|
||
|
||
final_header["total_cgst_amount"] = round2(total_cgst_amount)
|
||
final_header["total_sgst_amount"] = round2(total_sgst_amount)
|
||
final_header["total_igst_amount"] = round2(total_igst_amount)
|
||
|
||
final_header["total_gst_amount"] = round2(
|
||
total_cgst_amount + total_sgst_amount + total_igst_amount
|
||
)
|
||
|
||
if len(cgst_rates) == 1:
|
||
final_header["total_cgst_rate"] = list(cgst_rates)[0]
|
||
|
||
if len(sgst_rates) == 1:
|
||
final_header["total_sgst_rate"] = list(sgst_rates)[0]
|
||
|
||
if len(igst_rates) == 1:
|
||
final_header["total_igst_rate"] = list(igst_rates)[0]
|
||
|
||
# TOTAL GST RATE
|
||
if final_header.get("total_igst_rate"):
|
||
final_header["total_gst_rate"] = final_header["total_igst_rate"]
|
||
elif final_header.get("total_cgst_rate") and final_header.get("total_sgst_rate"):
|
||
final_header["total_gst_rate"] = round2(
|
||
final_header["total_cgst_rate"] +
|
||
final_header["total_sgst_rate"]
|
||
)
|
||
|
||
|
||
return all_pages_data, final_header
|
||
print("🔍 ALL PAGES DATA:", all_pages_data)
|
||
# ===============================
|
||
# BUILD FINAL HEADER
|
||
# ===============================
|
||
final_header = {field: None for field in HEADER_FIELDS}
|
||
|
||
for page in all_pages_data:
|
||
for field in HEADER_FIELDS:
|
||
value = page.get(field)
|
||
|
||
if isinstance(value, dict):
|
||
value = value.get("value")
|
||
|
||
if final_header[field] in (None, "", 0) and value not in (None, "", 0):
|
||
final_header[field] = value
|
||
|
||
# process_gst() call intentionally removed:
|
||
# Phases A-C below handle dedup + rate backfill + GST recalculation
|
||
# in the correct order. Calling process_gst() here would overwrite
|
||
# cgst_rate/sgst_rate with 0.0 (via safe_float(None)) BEFORE the
|
||
# HSN rate lookup has a chance to backfill them, causing all GST
|
||
# amounts to be incorrectly zeroed out on invoices where Gemini
|
||
# returns cgst_rate: null on item rows (rates only in HSN summary).
|
||
|
||
# ===============================================================
|
||
# ===============================================================
|
||
# STEP 5: BUILD FINAL OUTPUT
|
||
# ===============================================================
|
||
# ---------------------------------------------------------------
|
||
# 🔥 PHASE A — Build HSN → rate lookup from ALL pages
|
||
#
|
||
# On some invoice formats (e.g. Kanchan Drugs), the item rows on
|
||
# page 1 carry cgst_rate: null because the rate column is absent
|
||
# from the item table. The CGST/SGST rates only appear in the
|
||
# HSN summary table printed on page 2.
|
||
#
|
||
# We scan every page's items for non-null rates and build a
|
||
# lookup keyed by (hsn_sac, taxable_value). If that is too
|
||
# sparse we also keep a simpler hsn_sac → rate map.
|
||
# ---------------------------------------------------------------
|
||
hsn_rate_lookup = {} # hsn_sac (str) → {"cgst": float, "sgst": float, "igst": float}
|
||
taxable_rate_lookup = {} # (hsn_sac, taxable_value_str) → rates (more precise)
|
||
|
||
for page in all_pages_data:
|
||
for item in (page.get("items") or page.get("Items") or []):
|
||
hsn = str(item.get("hsn_sac") or "").strip()
|
||
cr = item.get("cgst_rate")
|
||
sr = item.get("sgst_rate")
|
||
ir = item.get("igst_rate")
|
||
if not hsn:
|
||
continue
|
||
# Only record if at least one rate is non-null and non-zero
|
||
cr_v = safe_float(cr)
|
||
sr_v = safe_float(sr)
|
||
ir_v = safe_float(ir)
|
||
if cr_v > 0 or sr_v > 0 or ir_v > 0:
|
||
rates = {"cgst": cr_v, "sgst": sr_v, "igst": ir_v}
|
||
hsn_rate_lookup[hsn] = rates
|
||
tv = str(safe_float(item.get("taxable_value") or item.get("total_price") or 0))
|
||
taxable_rate_lookup[(hsn, tv)] = rates
|
||
|
||
# ---------------------------------------------------------------
|
||
# 🔥 PHASE B — Item-level deduplication
|
||
#
|
||
# PDFs often contain multiple invoice copies (Original, Duplicate,
|
||
# Triplicate). Strategy: collect items in order; skip any item that is
|
||
# an exact clone of an already seen item (same item_code/batch/qty/price).
|
||
# Multiple DIFFERENT items sharing the same item_code (different batch,
|
||
# different qty, or different description) are ALWAYS preserved!
|
||
# ---------------------------------------------------------------
|
||
def _get_item_unique_key(item, fallback_idx):
|
||
code = str(item.get("item_code") or "").strip().lower()
|
||
batch = str(item.get("Batch") or "").strip().lower()
|
||
qty = str(item.get("quantity") or "").strip()
|
||
price = str(item.get("unit_price") or "").strip()
|
||
total = str(item.get("total_price") or item.get("taxable_value") or "").strip()
|
||
is_free = str(item.get("free_item_yn") or item.get("free_item") or "0")
|
||
|
||
# Clean desc without catalog numbers for matching
|
||
clean_d = re.sub(r'(?:catalog|cat|ref|item|part)\s*(?:no|number)?\s*[:\-]?\s*[a-z0-9]+', '', str(item.get("description") or "").lower())
|
||
clean_d = re.sub(r'[^a-z0-9]', '', clean_d)
|
||
|
||
# If it's an empty ghost row
|
||
if not clean_d and not batch and not code:
|
||
return f"__ghost_{fallback_idx}__"
|
||
|
||
# Composite key for item identity:
|
||
if code and batch:
|
||
return f"cb_{code}_{batch}_{qty}_{price}_{is_free}"
|
||
elif code and qty:
|
||
return f"cq_{code}_{clean_d}_{qty}_{price}_{is_free}"
|
||
elif batch and qty:
|
||
return f"bq_{batch}_{clean_d}_{qty}_{price}_{is_free}"
|
||
elif clean_d and qty:
|
||
return f"dq_{clean_d}_{qty}_{price}_{is_free}"
|
||
else:
|
||
return f"__raw_{clean_d}_{qty}_{price}_{fallback_idx}__"
|
||
|
||
# ── Cross-page continuation merge ──
|
||
for p_idx in range(1, len(all_pages_data)):
|
||
curr_items = all_pages_data[p_idx].get("items") or all_pages_data[p_idx].get("Items") or []
|
||
prev_items = all_pages_data[p_idx - 1].get("items") or all_pages_data[p_idx - 1].get("Items") or []
|
||
if not curr_items or not prev_items:
|
||
continue
|
||
first_curr = curr_items[0]
|
||
is_cont = first_curr.get("_continuation_for_previous_page") or (
|
||
not str(first_curr.get("description") or "").strip() and (
|
||
first_curr.get("Batch") or first_curr.get("expiry_date") or first_curr.get("item_code")
|
||
)
|
||
)
|
||
if is_cont:
|
||
last_prev = prev_items[-1]
|
||
for fld in ("Batch", "expiry_date", "item_code", "hsn_sac", "Pack", "MRP"):
|
||
if first_curr.get(fld) and not last_prev.get(fld):
|
||
last_prev[fld] = first_curr[fld]
|
||
desc_prev = str(last_prev.get('description', ''))[:35]
|
||
print(f" [CONTINUATION] Merged page {p_idx+1} header into {desc_prev}", flush=True)
|
||
curr_items.pop(0)
|
||
|
||
raw_items = [
|
||
item
|
||
for page in all_pages_data
|
||
for item in (page.get("items") or page.get("Items") or [])
|
||
]
|
||
|
||
seen_item_keys = set()
|
||
deduped_items = []
|
||
for idx, item in enumerate(raw_items):
|
||
key = _get_item_unique_key(item, idx)
|
||
is_free = (item.get("free_item") == 1 or str(item.get("free_item_yn")) == "1")
|
||
|
||
# Skip duplicate replica item from duplicate pages
|
||
if key and not key.startswith("__ghost_") and not key.startswith("__raw_") and not is_free:
|
||
if key in seen_item_keys:
|
||
desc_preview = item.get("description") or item.get("Batch") or "?"
|
||
print(f"🔁 Duplicate replica item skipped: {desc_preview!r} (code={item.get('item_code')}, batch={item.get('Batch')})", flush=True)
|
||
continue
|
||
seen_item_keys.add(key)
|
||
elif key and not key.startswith("__ghost_"):
|
||
seen_item_keys.add(key)
|
||
|
||
deduped_items.append(item)
|
||
# ---------------------------------------------------------------
|
||
# 🔥 GHOST ITEM FILTER — safety net after deduplication
|
||
#
|
||
# A ghost row is produced when Gemini sees a page-continuation
|
||
# line (batch/item_code only, no description/qty/price) and
|
||
# mistakenly creates a new item object for it.
|
||
# Drop any item where description, quantity, unit_price AND
|
||
# total_price are ALL null/zero/empty.
|
||
# ---------------------------------------------------------------
|
||
def _is_ghost(item):
|
||
desc = item.get("description")
|
||
qty = item.get("quantity")
|
||
unit_price = item.get("unit_price")
|
||
total_price = item.get("total_price")
|
||
def _empty(v):
|
||
if v is None: return True
|
||
if isinstance(v, str) and v.strip() == "": return True
|
||
try: return float(v) == 0.0
|
||
except: return False
|
||
return _empty(desc) and _empty(qty) and _empty(unit_price) and _empty(total_price)
|
||
|
||
clean_items = []
|
||
for item in deduped_items:
|
||
if _is_ghost(item):
|
||
b = item.get("Batch") or item.get("item_code") or "unknown"
|
||
print(f"\U0001f47b Ghost item removed: Batch/Code={b!r}")
|
||
else:
|
||
clean_items.append(item)
|
||
deduped_items = clean_items
|
||
|
||
|
||
# ---------------------------------------------------------------
|
||
# 🔥 PHASE C — Backfill null rates using HSN lookup, then
|
||
# recalculate GST amounts for every deduplicated item
|
||
# ---------------------------------------------------------------
|
||
total_cgst_amount = 0.0
|
||
total_sgst_amount = 0.0
|
||
total_igst_amount = 0.0
|
||
cgst_rates_seen = set()
|
||
sgst_rates_seen = set()
|
||
igst_rates_seen = set()
|
||
total_taxable = 0.0
|
||
|
||
for item in deduped_items:
|
||
# --- backfill rates if missing ---
|
||
cr = item.get("cgst_rate")
|
||
sr = item.get("sgst_rate")
|
||
ir = item.get("igst_rate")
|
||
cr_v = safe_float(cr)
|
||
sr_v = safe_float(sr)
|
||
ir_v = safe_float(ir)
|
||
|
||
if cr_v == 0.0 and sr_v == 0.0 and ir_v == 0.0:
|
||
hsn = str(item.get("hsn_sac") or "").strip()
|
||
tv = str(safe_float(item.get("taxable_value") or item.get("total_price") or 0))
|
||
|
||
# Priority 1: precise HSN+taxable lookup built from other pages
|
||
fallback = taxable_rate_lookup.get((hsn, tv)) or hsn_rate_lookup.get(hsn)
|
||
|
||
# Priority 2: split Gst% field (Gemini extracts the GST% column value here)
|
||
# For intra-state invoices (CGST+SGST), Gst% = CGST% + SGST%, so each = Gst%/2
|
||
# For inter-state invoices (IGST only), igst_rate = Gst%
|
||
if not fallback:
|
||
gst_pct = safe_float(item.get("Gst%"))
|
||
if gst_pct > 0:
|
||
# Determine if inter-state (IGST) or intra-state (CGST+SGST)
|
||
# Use invoice-level clue: if any page has igst_amount > 0 at header level
|
||
# or if total_igst_amount > 0 in final_header, it is inter-state
|
||
is_igst = safe_float(final_header.get("total_igst_amount")) > 0
|
||
if is_igst:
|
||
fallback = {"cgst": 0.0, "sgst": 0.0, "igst": gst_pct}
|
||
else:
|
||
half = round2(gst_pct / 2)
|
||
fallback = {"cgst": half, "sgst": half, "igst": 0.0}
|
||
print(f"\u2705 Rate from Gst% field for {item.get('description')!r}: "
|
||
f"Gst%={gst_pct} → CGST={fallback['cgst']}% SGST={fallback['sgst']}% IGST={fallback['igst']}%")
|
||
|
||
# Priority 3: fall back to invoice-level total_cgst_rate / total_igst_rate
|
||
if not fallback:
|
||
h_cgst = safe_float(final_header.get("total_cgst_rate"))
|
||
h_sgst = safe_float(final_header.get("total_sgst_rate"))
|
||
h_igst = safe_float(final_header.get("total_igst_rate"))
|
||
if h_cgst > 0 or h_sgst > 0 or h_igst > 0:
|
||
fallback = {"cgst": h_cgst, "sgst": h_sgst, "igst": h_igst}
|
||
print(f"\u2705 Rate from invoice header for {item.get('description')!r}: "
|
||
f"CGST={h_cgst}% SGST={h_sgst}% IGST={h_igst}%")
|
||
|
||
if fallback:
|
||
cr_v = fallback["cgst"]
|
||
sr_v = fallback["sgst"]
|
||
ir_v = fallback["igst"]
|
||
if cr_v > 0: item["cgst_rate"] = cr_v
|
||
if sr_v > 0: item["sgst_rate"] = sr_v
|
||
if ir_v > 0: item["igst_rate"] = ir_v
|
||
|
||
|
||
# ----------------------------------------------------------------
|
||
# PHASE C — TAXABLE VALUE CALCULATION
|
||
#
|
||
# total_price is the FINAL GST-INCLUSIVE row total
|
||
# (taxable_value + CGST + SGST, or + IGST). This is the rightmost
|
||
# "Amount" column on the invoice, printed AFTER the GST columns.
|
||
#
|
||
# taxable_value is derived BACKWARD from total_price using the GST rate:
|
||
# taxable_value = total_price / (1 + gst_percent / 100)
|
||
#
|
||
# This is robust regardless of how the invoice expresses its discount
|
||
# (flat amount, percent, or no discount column at all) because the
|
||
# discount is already baked into total_price by the time it reaches
|
||
# this stage — we only need to strip the GST back out.
|
||
#
|
||
# Priority order for taxable_value:
|
||
# 1. Explicit Value/Taxable column extracted from the invoice
|
||
# 2. Backward-derive from total_price using gst_percent
|
||
# 3. Fallback to total_price as-is if gst_percent is unknown (no GST item)
|
||
# ----------------------------------------------------------------
|
||
qty = safe_float(item.get("quantity"))
|
||
unit_price = safe_float(item.get("unit_price"))
|
||
orig_total = safe_float(item.get("total_price")) # GST-inclusive
|
||
discount = safe_float(item.get("Discount"))
|
||
value_field = safe_float(item.get("Value"))
|
||
# taxable_value the model already copied straight from the invoice's
|
||
# own TAXABLE / TAXABLE AMT column (character-level OCR copy, per prompt).
|
||
# This is the printed value and must win over any backward calculation.
|
||
extracted_taxable = safe_float(item.get("taxable_value"))
|
||
|
||
# Reference only — gross pre-discount pre-GST amount, used as a last-resort fallback
|
||
plain_amount = round2(qty * unit_price) if qty > 0 and unit_price > 0 else 0.0
|
||
|
||
# total_price is taken as-is from the model (GST-inclusive). We only fill
|
||
# it in if missing/zero — we do NOT overwrite it with qty×rate, since it is
|
||
# expected to be larger than qty×rate by the GST amount.
|
||
if orig_total <= 0 and plain_amount > 0:
|
||
item["total_price"] = plain_amount
|
||
orig_total = plain_amount
|
||
print(f"⚠️ total_price missing for {item.get('description')!r}, "
|
||
f"falling back to qty×rate: {plain_amount} (GST not added — verify)")
|
||
|
||
total_gst_pct = cr_v + sr_v + ir_v # combined GST% for this item
|
||
|
||
# ── Derive taxable_value ────────────────────────────────────────
|
||
# Priority 1: taxable_value the model already copied directly from
|
||
# the invoice's own TAXABLE / TAXABLE AMT column. Trust the printed
|
||
# OCR value over any calculation — never recompute over it.
|
||
if extracted_taxable > 0:
|
||
taxable = round2(extracted_taxable)
|
||
|
||
# Priority 2: explicit Value column extracted by the model
|
||
elif value_field > 0:
|
||
taxable = round2(value_field)
|
||
|
||
# Priority 3: backward-derive from GST-inclusive total_price using GST rate
|
||
# (only used when the invoice has NO taxable/value column at all)
|
||
elif orig_total > 0 and total_gst_pct > 0:
|
||
taxable = round2(orig_total / (1 + total_gst_pct / 100))
|
||
print(f"✅ taxable_value derived for {item.get('description')!r}: "
|
||
f"{orig_total} / (1 + {total_gst_pct}%) = {taxable}")
|
||
|
||
# Priority 4: no GST rate known — assume total_price IS the taxable value
|
||
# (e.g. zero-rated or GST-exempt items)
|
||
else:
|
||
taxable = round2(orig_total) if orig_total > 0 else round2(plain_amount)
|
||
|
||
# Safety net: taxable must never be negative or zero when we have valid data
|
||
if taxable <= 0 and plain_amount > 0:
|
||
taxable = plain_amount
|
||
print(f"⚠️ taxable_value was ≤0, reset to plain_amount for "
|
||
f"{item.get('description')!r}: {taxable}")
|
||
|
||
item["taxable_value"] = taxable
|
||
|
||
# --- recalculate amounts ---
|
||
item["cgst_amount"] = round2(taxable * cr_v / 100)
|
||
item["sgst_amount"] = round2(taxable * sr_v / 100)
|
||
item["igst_amount"] = round2(taxable * ir_v / 100)
|
||
item["GST_AMT"] = round2(item["cgst_amount"] + item["sgst_amount"] + item["igst_amount"])
|
||
item["Gst%"] = round2(cr_v + sr_v + ir_v)
|
||
|
||
total_cgst_amount += item["cgst_amount"]
|
||
total_sgst_amount += item["sgst_amount"]
|
||
total_igst_amount += item["igst_amount"]
|
||
total_taxable += taxable
|
||
|
||
if cr_v > 0: cgst_rates_seen.add(cr_v)
|
||
if sr_v > 0: sgst_rates_seen.add(sr_v)
|
||
if ir_v > 0: igst_rates_seen.add(ir_v)
|
||
|
||
# --- update totals in final_header (Phase C computed values) ---
|
||
final_header["total_cgst_amount"] = round2(total_cgst_amount)
|
||
final_header["total_sgst_amount"] = round2(total_sgst_amount)
|
||
final_header["total_igst_amount"] = round2(total_igst_amount)
|
||
final_header["total_gst_amount"] = round2(total_cgst_amount + total_sgst_amount + total_igst_amount)
|
||
|
||
# ---------------------------------------------------------------
|
||
# 🔥 FOOTER TAX OVERRIDE
|
||
#
|
||
# If Gemini extracted explicit total_cgst_amount / total_sgst_amount
|
||
# from the invoice footer (e.g. "CGST 285.000", "SGST 285.000"),
|
||
# those printed values are authoritative and must NOT be replaced
|
||
# by Phase C's recalculated sums.
|
||
#
|
||
# We restore the Gemini-extracted footer totals if:
|
||
# 1. Gemini returned a non-zero value for that field
|
||
# 2. The value is plausible (> 0 and not wildly different from
|
||
# Phase C's sum — within 20% tolerance to catch OCR errors)
|
||
#
|
||
# This fixes invoices like TAPADIYA where:
|
||
# Invoice footer: CGST=285, SGST=285
|
||
# Phase C sum: CGST=299.43 (due to rounding across 97 items)
|
||
# ---------------------------------------------------------------
|
||
for _tax_field in ("total_cgst_amount", "total_sgst_amount", "total_igst_amount"):
|
||
_gemini_val = safe_float(
|
||
next((p.get(_tax_field) for p in all_pages_data if p.get(_tax_field)), None)
|
||
)
|
||
_phase_c_val = safe_float(final_header.get(_tax_field))
|
||
if _gemini_val > 0:
|
||
# Plausibility check: accept if within 20% of Phase C value
|
||
# (rejects wildly wrong OCR reads but accepts rounding differences)
|
||
if _phase_c_val == 0 or abs(_gemini_val - _phase_c_val) / max(_phase_c_val, 0.01) <= 0.20:
|
||
final_header[_tax_field] = round2(_gemini_val)
|
||
print(f"✅ Footer tax override: {_tax_field} = {_gemini_val} "
|
||
f"(Phase C had {_phase_c_val})")
|
||
else:
|
||
print(f"⚠️ Footer tax NOT used for {_tax_field}: "
|
||
f"Gemini={_gemini_val} vs Phase C={_phase_c_val} "
|
||
f"(>20% diff, keeping Phase C value)")
|
||
|
||
# Recompute total_gst_amount from the (possibly overridden) component totals
|
||
final_header["total_gst_amount"] = round2(
|
||
safe_float(final_header["total_cgst_amount"]) +
|
||
safe_float(final_header["total_sgst_amount"]) +
|
||
safe_float(final_header["total_igst_amount"])
|
||
)
|
||
|
||
# ── GST rate fields ──────────────────────────────────────────────────
|
||
# If all items share one rate → use that exact rate (clean output).
|
||
# If items have MIXED rates → compute effective weighted-average rate
|
||
# = (total_tax_amount / total_taxable_value) × 100
|
||
# This always produces a meaningful value rather than null.
|
||
# ────────────────────────────────────────────────────────────────────
|
||
if len(cgst_rates_seen) == 1:
|
||
final_header["total_cgst_rate"] = list(cgst_rates_seen)[0]
|
||
elif total_taxable > 0 and total_cgst_amount > 0:
|
||
final_header["total_cgst_rate"] = round2((total_cgst_amount / total_taxable) * 100)
|
||
|
||
if len(sgst_rates_seen) == 1:
|
||
final_header["total_sgst_rate"] = list(sgst_rates_seen)[0]
|
||
elif total_taxable > 0 and total_sgst_amount > 0:
|
||
final_header["total_sgst_rate"] = round2((total_sgst_amount / total_taxable) * 100)
|
||
|
||
if len(igst_rates_seen) == 1:
|
||
final_header["total_igst_rate"] = list(igst_rates_seen)[0]
|
||
elif total_taxable > 0 and total_igst_amount > 0:
|
||
final_header["total_igst_rate"] = round2((total_igst_amount / total_taxable) * 100)
|
||
|
||
# total_gst_rate: prefer IGST if present, else CGST + SGST
|
||
if final_header.get("total_igst_rate"):
|
||
final_header["total_gst_rate"] = final_header["total_igst_rate"]
|
||
elif final_header.get("total_cgst_rate") is not None and final_header.get("total_sgst_rate") is not None:
|
||
final_header["total_gst_rate"] = round2(
|
||
safe_float(final_header["total_cgst_rate"]) +
|
||
safe_float(final_header["total_sgst_rate"])
|
||
)
|
||
extracted_data = {
|
||
**final_header,
|
||
"items": deduped_items,
|
||
}
|
||
# ===============================
|
||
# 🔹 DETECT & SET CURRENCY CODE
|
||
# ===============================
|
||
currency_code = None
|
||
|
||
header_currency = str(extracted_data.get("currency_code") or "").upper()
|
||
|
||
if header_currency in ["INR", "USD", "EUR", "GBP", "JPY", "SGD"]:
|
||
currency_code = header_currency
|
||
|
||
invoice_amount = str(extracted_data.get("invoice_amount") or "")
|
||
|
||
if not currency_code:
|
||
if "₹" in invoice_amount:
|
||
currency_code = "INR"
|
||
elif "$" in invoice_amount:
|
||
currency_code = "USD"
|
||
elif "€" in invoice_amount:
|
||
currency_code = "EUR"
|
||
elif "£" in invoice_amount:
|
||
currency_code = "GBP"
|
||
elif "¥" in invoice_amount:
|
||
currency_code = "JPY"
|
||
|
||
if not currency_code:
|
||
currency_code = "INR"
|
||
|
||
extracted_data["currency_code"] = currency_code
|
||
|
||
# ✅ ADD THIS BLOCK — normalize unicode in all string fields
|
||
for key, value in extracted_data.items():
|
||
if isinstance(value, str):
|
||
extracted_data[key] = normalize_text(value)
|
||
|
||
# Also normalize item descriptions
|
||
for item in extracted_data.get("items", []):
|
||
for key, value in item.items():
|
||
if isinstance(value, str):
|
||
item[key] = normalize_text(value)
|
||
|
||
|
||
# 🔥 Split free-quantity items into separate paid/free records
|
||
# (handles both "20+2" combined quantity AND separate FREE-column
|
||
# invoices like QTY=50 / FREE=5 — see free_item_splitter.py)
|
||
extracted_data = split_free_items(extracted_data)
|
||
|
||
# 🔥 Inject invoice_id
|
||
extracted_data["invoice_id"] = invoice_id
|
||
|
||
# 🔥 Inject billing info (used by upload_image to save to DB)
|
||
extracted_data["_input_tokens"] = _total_input_tokens
|
||
extracted_data["_output_tokens"] = _total_output_tokens
|
||
extracted_data["_cost_usd"] = round(_invoice_cost, 6)
|
||
|
||
# 🔥 CLOSE CONNECTION
|
||
# ── GSTIN / name post-processing ─────────────────────────────────────
|
||
extracted_data = post_process_header_fields(extracted_data)
|
||
|
||
# ── Seller GSTIN cross-check (hardcoded lookup, seller_gstin_lookup.py) ──
|
||
# Switched from the Excel-based _apply_seller_master() to the
|
||
# hardcoded SELLER_GSTIN_MAP per instruction. _apply_seller_master()
|
||
# and _load_seller_master() are left defined below (unused) in case
|
||
# you want to revert or run both.
|
||
extracted_data = apply_seller_gstin_override(extracted_data)
|
||
|
||
# ── Deterministic OCR corrections (GSTIN/HSN/dates), ocr_corrector.py ──
|
||
# Runs after the hardcoded seller GSTIN override so that override
|
||
# wins for sellers in the map; this still fixes customer_gstin and
|
||
# any seller not in the map, plus HSN codes and — the actual fix
|
||
# you asked for — expiry_date / invoice_date / due_date / DC_date.
|
||
try:
|
||
extracted_data = apply_ocr_corrections(extracted_data, page_texts=page_texts)
|
||
except Exception as _ocr_fix_err:
|
||
print(f"⚠️ OCR correction failed (non-fatal): {_ocr_fix_err}")
|
||
# correct_date() outputs DD/MM/YYYY (slashes) natively — kept as-is.
|
||
|
||
# ── Consistency check (math-based, zero extra API calls) ──────
|
||
# Runs the same as before, but ALL consistency-check fields
|
||
# (invoice-level and per-item) are stripped before the data is
|
||
# returned, so none of them appear in the extracted JSON.
|
||
try:
|
||
extracted_data, _consistency_summary = run_consistency_checks(extracted_data)
|
||
except Exception as _cc_err:
|
||
print(f"⚠️ Consistency check failed (non-fatal): {_cc_err}")
|
||
|
||
# Hide consistency-check fields from the extracted JSON
|
||
extracted_data.pop("_invoice_review_reasons", None)
|
||
extracted_data.pop("_consistency_summary", None)
|
||
for _item in extracted_data.get("items", []):
|
||
_item.pop("_needs_review", None)
|
||
_item.pop("_review_reasons", None)
|
||
|
||
# ── Enrich line items with item codes from drug_list.csv ──────
|
||
try:
|
||
extracted_data = icm.enrich_items_with_item_code(extracted_data, use_drug_list=use_drug_list)
|
||
except Exception as _icm_err:
|
||
print(f"⚠️ Item code enrichment failed: {_icm_err}")
|
||
|
||
total_items_final = len(extracted_data.get("items", []))
|
||
inv_amt_final = extracted_data.get("invoice_amount", "0.00")
|
||
print(f"\n🎉 [EXTRACTION COMPLETE] Successfully processed: {total_items_final} items | Invoice amount: {inv_amt_final}", flush=True)
|
||
print(f"{'='*70}\n", flush=True)
|
||
return extracted_data
|
||
except Exception as e:
|
||
import traceback
|
||
print(f"\n❌ [EXTRACTION ERROR]: {e}", flush=True)
|
||
traceback.print_exc()
|
||
return {"error": str(e)}
|
||
finally:
|
||
if conn:
|
||
try:
|
||
conn.close()
|
||
except:
|
||
pass
|
||
|
||
|
||
|
||
|
||
|
||
|
||
@app.route("/process-invoice", methods=["POST"])
|
||
@api_key_required
|
||
def process_invoice():
|
||
try:
|
||
if "file" not in request.files:
|
||
return jsonify({"error": "No file part"}), 400
|
||
|
||
file = request.files["file"]
|
||
|
||
if file.filename == "":
|
||
return jsonify({"error": "No selected file"}), 400
|
||
|
||
if file and allowed_file(file.filename):
|
||
filename = secure_filename(file.filename)
|
||
filepath = os.path.join(app.config["UPLOAD_FOLDER"], filename)
|
||
file.save(filepath)
|
||
|
||
invoice_source = request.form.get("invoice_source", "electronic")
|
||
|
||
# Look up the caller's role via their API key for DMH-only features
|
||
_api_key = request.headers.get("X-API-Key") or request.headers.get("x-api-key")
|
||
_conn2 = get_db_connection()
|
||
_cur2 = _conn2.cursor(dictionary=True)
|
||
_cur2.execute(
|
||
"SELECT u.role, u.id FROM users u JOIN api_keys ak ON u.id = ak.user_id WHERE ak.api_key = %s",
|
||
(_api_key,)
|
||
)
|
||
_role_row = _cur2.fetchone()
|
||
_cur2.close()
|
||
_conn2.close()
|
||
_is_dmh = (_role_row["role"] == "dmh") if _role_row else False
|
||
_caller_user_id = _role_row["id"] if _role_row else 1
|
||
|
||
use_drug_list = request.form.get("use_drug_list", "true").strip().lower() != "false"
|
||
extracted_data = extract_invoice_fields(filepath, invoice_source, is_dmh=_is_dmh, use_drug_list=use_drug_list)
|
||
# Strip internal billing keys before returning to API caller
|
||
for _k in ("_input_tokens", "_output_tokens", "_cost_usd"):
|
||
extracted_data.pop(_k, None)
|
||
|
||
# Persist to extraction_history so pending item codes appear on Pharmacy Approval Dashboard
|
||
if extracted_data and isinstance(extracted_data, dict):
|
||
try:
|
||
init_status, init_val_status = _determine_initial_invoice_status(extracted_data)
|
||
extracted_data["status"] = init_status
|
||
extracted_data["processing_status"] = init_status
|
||
extracted_data["validation_status"] = init_val_status
|
||
|
||
# Attach messageId / attachment_name from n8n if supplied
|
||
msg_id = request.form.get("messageId") or request.headers.get("X-Message-Id")
|
||
if msg_id:
|
||
extracted_data["messageId"] = msg_id
|
||
att_name = request.form.get("attachment_name") or filename
|
||
if att_name:
|
||
extracted_data["attachment_name"] = att_name
|
||
|
||
pages_extracted = len(extracted_data.get("items", [])) if isinstance(extracted_data.get("items"), list) else 1
|
||
ist_now = datetime.now(ZoneInfo("Asia/Kolkata")).replace(tzinfo=None)
|
||
_conn_hist = get_db_connection()
|
||
_cur_hist = _conn_hist.cursor()
|
||
_cur_hist.execute(
|
||
"""
|
||
INSERT INTO extraction_history
|
||
(user_id, timestamp, image_name, pages_extracted, extraction_type, extracted_data, status, validation_status, processed_at)
|
||
VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s)
|
||
""",
|
||
(
|
||
_caller_user_id,
|
||
ist_now,
|
||
filename,
|
||
pages_extracted,
|
||
"invoice",
|
||
json.dumps(extracted_data),
|
||
init_status,
|
||
init_val_status,
|
||
ist_now if init_status == "completed" else None,
|
||
),
|
||
)
|
||
_conn_hist.commit()
|
||
extracted_data["extraction_id"] = _cur_hist.lastrowid
|
||
_cur_hist.close()
|
||
_conn_hist.close()
|
||
except Exception as _hist_err:
|
||
logging.warning(f"Could not persist extraction to extraction_history in process_invoice: {_hist_err}")
|
||
|
||
try:
|
||
queue_invoice_if_approval_needed(extracted_data, file_path_or_name=filename, extraction_id=extracted_data.get("extraction_id"))
|
||
except Exception as _q_err:
|
||
logging.warning(f"Could not queue invoice in PO approval: {_q_err}")
|
||
|
||
return jsonify(extracted_data), 200
|
||
|
||
return jsonify({"error": "Invalid file type"}), 400
|
||
|
||
except Exception as e:
|
||
logging.error(f"Error during upload or extraction: {e}")
|
||
return jsonify({"error": "Internal Server Error"}), 500
|
||
|
||
|
||
@app.route("/usage-count", methods=["GET"])
|
||
@api_key_required
|
||
def get_usage_count():
|
||
api_key = request.headers.get("X-API-Key")
|
||
conn = get_db_connection()
|
||
cursor = conn.cursor(dictionary=True)
|
||
sql = "SELECT * FROM api_usage WHERE api_key = %s"
|
||
cursor.execute(sql, (api_key,))
|
||
usage_entry = cursor.fetchone()
|
||
cursor.close()
|
||
conn.close()
|
||
if usage_entry:
|
||
return jsonify(
|
||
{
|
||
"api_key": api_key,
|
||
"usage_count": usage_entry["count"],
|
||
"last_used": usage_entry["last_used"].strftime("%Y-%m-%d"),
|
||
}
|
||
)
|
||
else:
|
||
return jsonify({"error": "API key not found"}), 404
|
||
|
||
|
||
@app.route("/all-usage-counts", methods=["GET"])
|
||
@api_key_required
|
||
def get_all_usage_counts():
|
||
try:
|
||
conn = get_db_connection()
|
||
cursor = conn.cursor(dictionary=True)
|
||
sql = "SELECT * FROM api_usage"
|
||
cursor.execute(sql)
|
||
usage_entries = cursor.fetchall()
|
||
usage_data = []
|
||
for entry in usage_entries:
|
||
usage_data.append(
|
||
{
|
||
"api_key": entry["api_key"],
|
||
"usage_count": entry["count"],
|
||
"last_used": entry["last_used"].strftime("%Y-%m-%d"),
|
||
}
|
||
)
|
||
cursor.close()
|
||
conn.close()
|
||
return jsonify(usage_data), 200
|
||
except Exception as e:
|
||
return jsonify({"error": f"Internal Server Error: {str(e)}"}), 500
|
||
|
||
|
||
DMIN_API_KEY = os.getenv("ADMIN_API_KEY")
|
||
|
||
|
||
@app.route("/admin/dashboard")
|
||
def admin_dashboard():
|
||
if "user" not in session or session.get("role") != "admin":
|
||
flash("Unauthorized access.")
|
||
return redirect(url_for("login"))
|
||
try:
|
||
conn = get_db_connection()
|
||
cursor = conn.cursor(dictionary=True)
|
||
|
||
# fetch all users
|
||
cursor.execute("SELECT * FROM users")
|
||
users = cursor.fetchall()
|
||
|
||
# fetch all api_keys
|
||
cursor.execute("SELECT * FROM api_keys")
|
||
api_keys = cursor.fetchall()
|
||
cursor.close()
|
||
conn.close()
|
||
|
||
# group api_keys by user_id
|
||
api_keys_dict = {}
|
||
for key in api_keys:
|
||
uid = key["user_id"]
|
||
api_keys_dict.setdefault(uid, []).append(key)
|
||
|
||
# build user_activity list and include phone
|
||
user_activity = []
|
||
for u in users:
|
||
u_id = u["id"]
|
||
user_activity.append(
|
||
{
|
||
"username": u["username"],
|
||
"email": u["email"],
|
||
"phone": u.get("phone", "—"), # ← new phone field
|
||
"invoices_extracted": u.get("invoices_extracted", 0),
|
||
"account_limit": u.get("account_limit", 3),
|
||
"api_keys": api_keys_dict.get(u_id, []),
|
||
"api_keys": api_keys_dict.get(u_id, []),
|
||
"user_id": u_id,
|
||
}
|
||
)
|
||
|
||
return render_template("admin_dashboard.html", user_activity=user_activity)
|
||
|
||
except Exception as e:
|
||
flash(f"Error loading dashboard: {e}")
|
||
return render_template("admin_dashboard.html", user_activity=[])
|
||
|
||
|
||
@app.route("/admin/update-user-limit", methods=["POST"])
|
||
def update_user_limit():
|
||
try:
|
||
data = request.get_json()
|
||
user_id = data.get("user_id")
|
||
new_account_limit = data.get("new_account_limit")
|
||
app.logger.info(f"Request data: {data}")
|
||
app.logger.info(
|
||
f"Received user_id: {user_id}, New account limit: {new_account_limit}"
|
||
)
|
||
if not user_id or new_account_limit is None:
|
||
return jsonify({"error": "Missing required parameters"}), 400
|
||
try:
|
||
user_id = int(user_id)
|
||
new_account_limit = int(new_account_limit)
|
||
if new_account_limit < 0:
|
||
return (
|
||
jsonify({"error": "Account limit must be a positive integer"}),
|
||
400,
|
||
)
|
||
except ValueError:
|
||
return jsonify({"error": "Account limit must be a valid integer"}), 400
|
||
conn = get_db_connection()
|
||
cursor = conn.cursor(dictionary=True)
|
||
sql = "SELECT * FROM users WHERE id = %s"
|
||
cursor.execute(sql, (user_id,))
|
||
user = cursor.fetchone()
|
||
if not user:
|
||
cursor.close()
|
||
conn.close()
|
||
return jsonify({"error": "User not found"}), 404
|
||
app.logger.info(f"User found: {user}")
|
||
sql_update = "UPDATE users SET account_limit = %s WHERE id = %s"
|
||
cursor.execute(sql_update, (new_account_limit, user_id))
|
||
conn.commit()
|
||
modified_count = cursor.rowcount
|
||
cursor.close()
|
||
conn.close()
|
||
app.logger.info(f"Update result: {modified_count}")
|
||
if modified_count == 0:
|
||
return jsonify({"error": "No changes made"}), 404
|
||
app.logger.info(f"User {user_id}'s account limit updated: {new_account_limit}")
|
||
return (
|
||
jsonify(
|
||
{
|
||
"message": f"Account limit updated to {new_account_limit} for user {user_id}"
|
||
}
|
||
),
|
||
200,
|
||
)
|
||
except Exception as e:
|
||
app.logger.error(f"Error updating user limit: {e}")
|
||
return jsonify({"error": str(e)}), 500
|
||
|
||
|
||
@app.route("/some-a-endpoint", methods=["GET"])
|
||
def some_api_endpoint():
|
||
api_key = request.headers.get("X-API-Key")
|
||
if not api_key:
|
||
return jsonify({"error": "API key is missing"}), 400
|
||
print(f"Received API Key: {api_key}")
|
||
conn = get_db_connection()
|
||
cursor = conn.cursor(dictionary=True)
|
||
sql = "SELECT * FROM api_usage WHERE api_key = %s"
|
||
cursor.execute(sql, (api_key,))
|
||
current_data = cursor.fetchone()
|
||
print(f"Current Data: {current_data}")
|
||
if not current_data:
|
||
cursor.close()
|
||
conn.close()
|
||
return jsonify({"error": "API key not found"}), 404
|
||
sql_update = "UPDATE api_usage SET count = count + 1 WHERE api_key = %s"
|
||
cursor.execute(sql_update, (api_key,))
|
||
conn.commit()
|
||
cursor.execute(sql, (api_key,))
|
||
updated_data = cursor.fetchone()
|
||
print(f"Updated Data After Increment: {updated_data}")
|
||
cursor.close()
|
||
conn.close()
|
||
return jsonify(
|
||
{"message": "API key usage incremented successfully", "data": updated_data}
|
||
)
|
||
|
||
|
||
@app.route("/", methods=["GET"])
|
||
def index():
|
||
if "user" in session or "user_id" in session:
|
||
if session.get("role") == "pharmacy":
|
||
return redirect(url_for("pharmacy_dashboard"))
|
||
elif session.get("role") == "dmh":
|
||
return redirect(url_for("dmh_dashboard"))
|
||
return redirect(
|
||
url_for("home_logged_in")
|
||
) # Redirect to proper logged-in homepage
|
||
return render_template("home.html", logged_in=False)
|
||
|
||
|
||
# New Invoice Route
|
||
@app.route("/invoice")
|
||
def invoice():
|
||
return render_template("invoice.html") # After login, redirect to upload_image
|
||
|
||
|
||
@app.route("/passport")
|
||
def passport():
|
||
return render_template("passport.html")
|
||
|
||
|
||
from email_validator import validate_email, EmailNotValidError
|
||
import phonenumbers
|
||
from phonenumbers import NumberParseException
|
||
|
||
|
||
def validate_user_email(email):
|
||
try:
|
||
v = validate_email(email)
|
||
return v.email, None
|
||
except EmailNotValidError as e:
|
||
return None, str(e)
|
||
|
||
|
||
def validate_phone_number(raw_phone, default_region="IN"):
|
||
try:
|
||
pn = phonenumbers.parse(raw_phone, default_region)
|
||
if not phonenumbers.is_valid_number(pn):
|
||
return None, "Phone number is not valid"
|
||
e164 = phonenumbers.format_number(pn, phonenumbers.PhoneNumberFormat.E164)
|
||
return e164, None
|
||
except NumberParseException as e:
|
||
return None, str(e)
|
||
|
||
|
||
@app.route("/signup", methods=["GET", "POST"])
|
||
def signup():
|
||
if request.method == "POST":
|
||
username = request.form["username"].strip()
|
||
email_in = request.form["email"].strip()
|
||
phone_in = request.form.get("phone", "").strip()
|
||
password = request.form["password"] # plain password
|
||
|
||
# 1) Validate email
|
||
email, email_err = validate_user_email(email_in)
|
||
if email_err:
|
||
flash(f"Invalid email address: {email_err}", "error")
|
||
return redirect(url_for("signup"))
|
||
|
||
# 2) Validate phone
|
||
phone, phone_err = validate_phone_number(phone_in)
|
||
if phone_err:
|
||
flash(f"Invalid phone number: {phone_err}", "error")
|
||
return redirect(url_for("signup"))
|
||
|
||
# 3) Store password PLAIN (no hashing)
|
||
plain_password = password
|
||
|
||
try:
|
||
conn = get_db_connection()
|
||
cursor = conn.cursor()
|
||
sql = """
|
||
INSERT INTO users (username, email, password, phone)
|
||
VALUES (%s, %s, %s, %s)
|
||
"""
|
||
cursor.execute(sql, (username, email, plain_password, phone))
|
||
conn.commit()
|
||
cursor.close()
|
||
conn.close()
|
||
|
||
flash("Sign up successful! Please log in.", "success")
|
||
return redirect(url_for("login"))
|
||
|
||
except Exception as e:
|
||
flash(f"Unexpected Error: {e}", "error")
|
||
|
||
return render_template("appsignup.html")
|
||
|
||
|
||
@app.route("/forgot_password", methods=["GET", "POST"])
|
||
def forgot_password():
|
||
if request.method == "POST":
|
||
email = request.form["email"]
|
||
try:
|
||
conn = get_db_connection()
|
||
cursor = conn.cursor(dictionary=True)
|
||
sql = "SELECT * FROM users WHERE email = %s"
|
||
cursor.execute(sql, (email,))
|
||
user = cursor.fetchone()
|
||
cursor.close()
|
||
conn.close()
|
||
if user:
|
||
session["reset_email"] = email
|
||
flash("Please enter your new password.")
|
||
return redirect(url_for("reset_password"))
|
||
else:
|
||
flash("No account found with this email.")
|
||
except Exception as e:
|
||
flash(f"Error: {e}")
|
||
return render_template("appforget.html")
|
||
|
||
|
||
from flask import render_template
|
||
from zoneinfo import ZoneInfo
|
||
|
||
|
||
#def to_ist(utc_time):
|
||
# return utc_time.replace(tzinfo=ZoneInfo("UTC")).astimezone(ZoneInfo("Asia/Kolkata"))
|
||
|
||
def to_ist(utc_dt):
|
||
# If naive, assume it's UTC
|
||
if utc_dt.tzinfo is None:
|
||
utc_dt = utc_dt.replace(tzinfo=ZoneInfo("UTC"))
|
||
# Convert to IST
|
||
ist_dt = utc_dt.astimezone(ZoneInfo("Asia/Kolkata"))
|
||
return ist_dt
|
||
UPLOAD_FOLDER = os.path.join(os.getcwd(), "uploads", "invoices")
|
||
|
||
|
||
@app.route("/view-invoice/<int:invoice_id>")
|
||
def view_invoice(invoice_id):
|
||
user_id = session.get("user_id")
|
||
if not user_id:
|
||
return redirect(url_for("login"))
|
||
|
||
conn = get_db_connection()
|
||
cursor = conn.cursor(dictionary=True)
|
||
|
||
cursor.execute(
|
||
"""
|
||
SELECT extracted_data, image_name, timestamp
|
||
FROM extraction_history
|
||
WHERE id = %s AND user_id = %s
|
||
""",
|
||
(invoice_id, user_id)
|
||
)
|
||
invoice = cursor.fetchone()
|
||
|
||
cursor.close()
|
||
conn.close()
|
||
|
||
if not invoice:
|
||
return "Invoice not found", 404
|
||
|
||
if not invoice["extracted_data"]:
|
||
return "JSON extraction not available for this invoice", 404
|
||
|
||
extracted_json = json.loads(invoice["extracted_data"])
|
||
|
||
|
||
return render_template(
|
||
"view_invoice_json.html",
|
||
invoice_json=json.dumps(extracted_json,indent=4),
|
||
image_name=invoice["image_name"],
|
||
timestamp=invoice["timestamp"],
|
||
)
|
||
|
||
|
||
|
||
|
||
|
||
@app.route("/invoice-history")
|
||
def invoice_history_page():
|
||
user_id = session.get("user_id")
|
||
if not user_id:
|
||
return redirect(url_for("login"))
|
||
|
||
conn = get_db_connection()
|
||
cursor = conn.cursor(dictionary=True)
|
||
|
||
cursor.execute(
|
||
"""
|
||
SELECT id, timestamp, image_name
|
||
FROM extraction_history
|
||
WHERE user_id = %s
|
||
AND extracted_data IS NOT NULL
|
||
ORDER BY timestamp DESC
|
||
""",
|
||
(user_id,)
|
||
)
|
||
|
||
rows = cursor.fetchall()
|
||
cursor.close()
|
||
conn.close()
|
||
|
||
invoice_history = []
|
||
|
||
for row in rows:
|
||
|
||
invoice_history.append({
|
||
"id": row["id"],
|
||
"timestamp_str": row["timestamp"].strftime("%d-%m-%Y %I:%M:%S %p"),
|
||
"image_name": row["image_name"],
|
||
})
|
||
|
||
return render_template("view_history.html", invoice_history=invoice_history)
|
||
|
||
@app.route("/invoice-json/<int:invoice_id>")
|
||
def invoice_json(invoice_id):
|
||
user_id = session.get("user_id")
|
||
if not user_id:
|
||
return redirect(url_for("login"))
|
||
|
||
conn = get_db_connection()
|
||
cursor = conn.cursor(dictionary=True)
|
||
|
||
cursor.execute(
|
||
"""
|
||
SELECT extracted_data
|
||
FROM extraction_history
|
||
WHERE id = %s AND user_id = %s
|
||
""",
|
||
(invoice_id, user_id)
|
||
)
|
||
|
||
row = cursor.fetchone()
|
||
|
||
cursor.close()
|
||
conn.close()
|
||
if not row or not row["extracted_data"]:
|
||
return "Extraction not available", 404
|
||
|
||
|
||
extracted_data = json.loads(row["extracted_data"])
|
||
|
||
return render_template("view_invoice_json.html", extracted_data=extracted_data)
|
||
|
||
@app.route("/reset_password", methods=["GET", "POST"])
|
||
def reset_password():
|
||
if "reset_email" not in session:
|
||
flash("Invalid reset attempt.")
|
||
return redirect(url_for("forgot_password"))
|
||
|
||
if request.method == "POST":
|
||
new_password = request.form["password"] # plain password
|
||
|
||
try:
|
||
conn = get_db_connection()
|
||
cursor = conn.cursor()
|
||
|
||
sql = "UPDATE users SET password = %s WHERE email = %s"
|
||
cursor.execute(sql, (new_password, session["reset_email"]))
|
||
conn.commit()
|
||
cursor.close()
|
||
conn.close()
|
||
|
||
session.pop("reset_email", None)
|
||
flash("Password reset successfully.")
|
||
return redirect(url_for("login"))
|
||
|
||
except Exception as e:
|
||
flash(f"Error: {e}")
|
||
|
||
return render_template("appreset.html")
|
||
def get_user_from_db(login_input, password):
|
||
conn = get_db_connection()
|
||
cursor = conn.cursor(dictionary=True)
|
||
|
||
cursor.execute(
|
||
"""
|
||
SELECT * FROM users
|
||
WHERE (username = %s OR email = %s)
|
||
""",
|
||
(login_input, login_input),
|
||
)
|
||
|
||
user = cursor.fetchone()
|
||
|
||
cursor.close()
|
||
conn.close()
|
||
|
||
# password check (plain text as per your current system)
|
||
if user and user["password"] == password:
|
||
return user
|
||
|
||
return None
|
||
|
||
@app.route("/login", methods=["GET", "POST"])
|
||
def login():
|
||
if request.method == "POST":
|
||
login_input = request.form.get("username")
|
||
password = request.form.get("password")
|
||
|
||
conn = get_db_connection()
|
||
cursor = conn.cursor(dictionary=True)
|
||
|
||
cursor.execute(
|
||
"SELECT * FROM users WHERE username=%s OR email=%s",
|
||
(login_input, login_input),
|
||
)
|
||
user = cursor.fetchone()
|
||
|
||
cursor.close()
|
||
conn.close()
|
||
|
||
is_password_valid = False
|
||
if user and user.get("password"):
|
||
if password == user["password"]:
|
||
is_password_valid = True
|
||
elif user["password"].startswith("$2b$") or user["password"].startswith("$2a$"):
|
||
try:
|
||
import bcrypt
|
||
is_password_valid = bcrypt.checkpw(password.encode("utf-8"), user["password"].encode("utf-8"))
|
||
except Exception:
|
||
pass
|
||
elif user["password"].startswith("scrypt:") or user["password"].startswith("pbkdf2:"):
|
||
try:
|
||
from werkzeug.security import check_password_hash
|
||
is_password_valid = check_password_hash(user["password"], password)
|
||
except Exception:
|
||
pass
|
||
|
||
if user and is_password_valid:
|
||
session.clear()
|
||
|
||
session["user_id"] = user["id"]
|
||
session["user"] = user["username"] # ✅ THIS FIXES IT
|
||
session["username"] = user["username"]
|
||
session["role"] = user.get("role", "user")
|
||
session["is_admin"] = bool(user.get("is_admin") or user.get("role") == "admin")
|
||
|
||
# Update last_login in users table of invoice.db
|
||
try:
|
||
_c_up = get_db_connection()
|
||
_cur_up = _c_up.cursor()
|
||
_cur_up.execute("UPDATE users SET last_login = CURRENT_TIMESTAMP WHERE id = %s", (user["id"],))
|
||
_c_up.commit()
|
||
_cur_up.close()
|
||
_c_up.close()
|
||
except Exception:
|
||
pass
|
||
|
||
# Main AI Invoice login routing
|
||
if user.get("role") == "pharmacy":
|
||
return redirect(url_for("pharmacy_dashboard"))
|
||
elif user.get("role") == "dmh":
|
||
return redirect(url_for("dmh_dashboard"))
|
||
else:
|
||
return redirect(url_for("dashboard"))
|
||
|
||
flash("Invalid login details", "error")
|
||
|
||
return render_template("applogin.html")
|
||
import uuid
|
||
|
||
def save_file(file):
|
||
"""Save an uploaded file safely to UPLOAD_FOLDER and return its path."""
|
||
original_filename = secure_filename(file.filename)
|
||
unique_filename = f"{uuid.uuid4()}_{original_filename}"
|
||
file_path = os.path.join(app.config["UPLOAD_FOLDER"], unique_filename)
|
||
file.save(file_path)
|
||
return file_path
|
||
|
||
def extract_passport_fields(file_path):
|
||
"""Extract standard passport fields from an image or PDF."""
|
||
try:
|
||
file_ext = os.path.splitext(file_path)[1].lower()
|
||
if file_ext == ".pdf":
|
||
images = pdf_to_images_standalone(file_path, dpi=300)
|
||
else:
|
||
images = [Image.open(file_path)]
|
||
|
||
if not images:
|
||
return {"error": "Could not load image from file"}
|
||
|
||
img = images[0]
|
||
image_b64 = _pil_to_b64(img)
|
||
|
||
system_prompt = (
|
||
"You are an expert OCR and passport data extraction engine. "
|
||
"Extract all passport details accurately and return ONLY a valid JSON object."
|
||
)
|
||
user_prompt = (
|
||
"Extract all passport fields from this document into JSON format with the following keys:\n"
|
||
"{\n"
|
||
' "passport_number": "",\n'
|
||
' "surname": "",\n'
|
||
' "given_names": "",\n'
|
||
' "nationality": "",\n'
|
||
' "date_of_birth": "",\n'
|
||
' "sex": "",\n'
|
||
' "place_of_birth": "",\n'
|
||
' "place_of_issue": "",\n'
|
||
' "date_of_issue": "",\n'
|
||
' "date_of_expiry": "",\n'
|
||
' "mrz_line1": "",\n'
|
||
' "mrz_line2": ""\n'
|
||
"}\n"
|
||
"If a field cannot be found, set it to empty string. Return ONLY the JSON object."
|
||
)
|
||
|
||
resp_text = _qwen_call(system_prompt=system_prompt, user_text=user_prompt, image_b64=image_b64)
|
||
if resp_text.startswith("```"):
|
||
resp_text = resp_text.strip("`")
|
||
if resp_text.lower().startswith("json"):
|
||
resp_text = resp_text[4:].strip()
|
||
resp_text = resp_text.strip()
|
||
if "}" in resp_text:
|
||
resp_text = resp_text[:resp_text.rfind("}") + 1]
|
||
|
||
data = json.loads(resp_text)
|
||
return data
|
||
except Exception as e:
|
||
logging.error(f"Passport extraction error: {e}", exc_info=True)
|
||
return {"error": str(e)}
|
||
|
||
def _safe_float_check(val):
|
||
"""Parse numeric field safely; returns '__INVALID__' for corrupt non-numeric values."""
|
||
import math
|
||
if val is None or val == "":
|
||
return None
|
||
if isinstance(val, bool):
|
||
return "__INVALID__"
|
||
if isinstance(val, (int, float)):
|
||
if math.isnan(val) or math.isinf(val):
|
||
return "__INVALID__"
|
||
return float(val)
|
||
try:
|
||
s = str(val).replace(",", "").replace("₹", "").strip()
|
||
if not s:
|
||
return None
|
||
f = float(s)
|
||
if math.isnan(f) or math.isinf(f):
|
||
return "__INVALID__"
|
||
return f
|
||
except (ValueError, TypeError):
|
||
return "__INVALID__"
|
||
|
||
|
||
def _determine_initial_invoice_status(extracted_data):
|
||
"""Determine initial invoice status after OCR extraction & catalog enrichment."""
|
||
if not isinstance(extracted_data, dict):
|
||
return "completed", "passed"
|
||
items = extracted_data.get("items")
|
||
if not isinstance(items, list):
|
||
return "completed", "passed"
|
||
for it in items:
|
||
if not isinstance(it, dict):
|
||
continue
|
||
code = str(it.get("item_code") or "").strip()
|
||
if not code or not icm.code_in_catalog(code):
|
||
return "pending_approval", "awaiting_item_codes"
|
||
return "completed", "passed"
|
||
|
||
|
||
def validate_and_process_invoice(data, valid_extra_codes=None, approved_by=None):
|
||
"""Validate updated invoice extraction data and run the remaining processing workflow.
|
||
|
||
Preserves all original extracted invoice header and line-item details while:
|
||
1. Validating invoice structure and line-item integrity (fails cleanly on invalid data).
|
||
2. Re-enriching any remaining unmapped items from catalog (preserving existing sources).
|
||
3. Running remaining header, GSTIN, OCR correction, and consistency validation steps.
|
||
4. Transitioning status to 'approved' (processing_status='completed') once all items have
|
||
valid catalog codes and all validations pass, or 'pending_approval' if items remain.
|
||
"""
|
||
import copy
|
||
|
||
extra_codes = {str(c).strip().upper() for c in (valid_extra_codes or []) if c}
|
||
|
||
def _is_code_valid(code_val):
|
||
c = str(code_val or "").strip().upper()
|
||
if not c:
|
||
return False
|
||
return c in extra_codes or icm.code_in_catalog(c)
|
||
|
||
if not isinstance(data, dict):
|
||
return {
|
||
"ok": False,
|
||
"status": "validation_failed",
|
||
"validation_status": "failed",
|
||
"validation_errors": ["Extracted invoice payload is not a valid JSON object."],
|
||
"consistency_warnings": [],
|
||
"missing_item_indices": [],
|
||
"processed_data": data,
|
||
}
|
||
|
||
processed = copy.deepcopy(data)
|
||
items = processed.get("items")
|
||
if not isinstance(items, list) or len(items) == 0:
|
||
return {
|
||
"ok": False,
|
||
"status": "validation_failed",
|
||
"validation_status": "failed",
|
||
"validation_errors": ["Invoice contains no line items to process."],
|
||
"consistency_warnings": [],
|
||
"missing_item_indices": [],
|
||
"processed_data": data,
|
||
}
|
||
|
||
validation_errors = []
|
||
|
||
if not (str(processed.get("invoice_id") or "").strip() or str(processed.get("invoice_number") or "").strip()):
|
||
validation_errors.append("Missing both invoice_id and invoice_number.")
|
||
|
||
for idx, it in enumerate(items):
|
||
if not isinstance(it, dict):
|
||
validation_errors.append(f"Line item #{idx + 1} is not a valid item object.")
|
||
continue
|
||
desc = str(it.get("description") or it.get("item_name") or "").strip()
|
||
if not desc:
|
||
validation_errors.append(f"Line item #{idx + 1} is missing description.")
|
||
|
||
code = str(it.get("item_code") or "").strip()
|
||
if len(code) > 50:
|
||
validation_errors.append(f"Line item #{idx + 1} item_code exceeds 50 characters.")
|
||
|
||
for num_key in ("unit_price", "total_price", "taxable_value", "GST_AMT"):
|
||
parsed_num = _safe_float_check(it.get(num_key))
|
||
if parsed_num == "__INVALID__":
|
||
validation_errors.append(
|
||
f"Line item #{idx + 1} ({desc or 'item'}) has invalid numeric '{num_key}': {it.get(num_key)!r}."
|
||
)
|
||
elif isinstance(parsed_num, float) and parsed_num < 0 and num_key in ("unit_price", "taxable_value"):
|
||
validation_errors.append(
|
||
f"Line item #{idx + 1} ({desc or 'item'}) has negative '{num_key}': {parsed_num}."
|
||
)
|
||
|
||
qty_raw = it.get("quantity")
|
||
if qty_raw is not None and qty_raw != "" and not isinstance(qty_raw, str):
|
||
q_num = _safe_float_check(qty_raw)
|
||
if q_num == "__INVALID__" or (isinstance(q_num, float) and q_num < 0):
|
||
validation_errors.append(
|
||
f"Line item #{idx + 1} ({desc or 'item'}) has invalid quantity: {qty_raw!r}."
|
||
)
|
||
|
||
if validation_errors:
|
||
return {
|
||
"ok": False,
|
||
"status": "validation_failed",
|
||
"validation_status": "failed",
|
||
"validation_errors": validation_errors,
|
||
"consistency_warnings": [],
|
||
"missing_item_indices": [],
|
||
"processed_data": data,
|
||
}
|
||
|
||
# Step 1: Currency & text normalization (preserves all original fields)
|
||
if not str(processed.get("currency_code") or "").strip():
|
||
processed["currency_code"] = "INR"
|
||
|
||
for k, v in list(processed.items()):
|
||
if isinstance(v, str):
|
||
processed[k] = normalize_text(v)
|
||
|
||
for it in items:
|
||
if isinstance(it, dict):
|
||
for k, v in list(it.items()):
|
||
if isinstance(v, str):
|
||
it[k] = normalize_text(v)
|
||
|
||
# Step 2: Re-enrich remaining blank item codes while preserving approved/manual sources
|
||
processed = icm.enrich_items_with_item_code(processed, use_drug_list=True)
|
||
for it in items:
|
||
code = str(it.get("item_code") or "").strip().upper()
|
||
if code:
|
||
it["item_code"] = code
|
||
it["in_csv"] = _is_code_valid(code)
|
||
if not it.get("item_code_source") or it.get("item_code_source") == "not_found":
|
||
it["item_code_source"] = "pharmacy_approval" if code in extra_codes else "drug_list_match"
|
||
else:
|
||
it["in_csv"] = False
|
||
|
||
# Step 3: Remaining header, GSTIN, OCR correction & math consistency pipeline
|
||
processed = post_process_header_fields(processed)
|
||
processed = apply_seller_gstin_override(processed)
|
||
processed = apply_ocr_corrections(processed, page_texts=None)
|
||
processed, consistency_summary = run_consistency_checks(processed)
|
||
|
||
consistency_warnings = []
|
||
if isinstance(consistency_summary, dict):
|
||
consistency_warnings.extend(consistency_summary.get("invoice_issues") or [])
|
||
for idx, it in enumerate(processed.get("items", [])):
|
||
if it.get("_needs_review") and it.get("_review_reasons"):
|
||
consistency_warnings.extend(
|
||
[f"Item {idx + 1} ({it.get('description', '')}): {r}" for r in it["_review_reasons"]]
|
||
)
|
||
it.pop("_needs_review", None)
|
||
it.pop("_review_reasons", None)
|
||
processed.pop("_invoice_review_reasons", None)
|
||
processed.pop("_consistency_summary", None)
|
||
|
||
# Re-verify item_code / in_csv after post-processing normalization
|
||
for it in processed.get("items", []):
|
||
code = str(it.get("item_code") or "").strip().upper()
|
||
if code:
|
||
it["item_code"] = code
|
||
it["in_csv"] = _is_code_valid(code)
|
||
else:
|
||
it["in_csv"] = False
|
||
|
||
missing_indices = [
|
||
idx for idx, it in enumerate(processed.get("items", []))
|
||
if not _is_code_valid(it.get("item_code"))
|
||
]
|
||
|
||
now_iso = datetime.now().isoformat(timespec="seconds")
|
||
if missing_indices:
|
||
processed["status"] = "pending_approval"
|
||
processed["processing_status"] = "pending_approval"
|
||
processed["validation_status"] = "partial"
|
||
return {
|
||
"ok": True,
|
||
"status": "pending_approval",
|
||
"validation_status": "partial",
|
||
"validation_errors": [],
|
||
"consistency_warnings": consistency_warnings,
|
||
"missing_item_indices": missing_indices,
|
||
"processed_data": processed,
|
||
}
|
||
|
||
processed["status"] = "approved"
|
||
processed["processing_status"] = "completed"
|
||
processed["validation_status"] = "passed"
|
||
if approved_by is not None:
|
||
processed["approved_by"] = approved_by
|
||
processed["approved_at"] = now_iso
|
||
processed["processed_at"] = now_iso
|
||
|
||
return {
|
||
"ok": True,
|
||
"status": "approved",
|
||
"validation_status": "passed",
|
||
"validation_errors": [],
|
||
"consistency_warnings": consistency_warnings,
|
||
"missing_item_indices": [],
|
||
"processed_data": processed,
|
||
}
|
||
|
||
|
||
@app.route("/upload-invoice", methods=["POST"])
|
||
def upload_invoice():
|
||
user_id = session.get("user_id")
|
||
role = session.get("role")
|
||
|
||
if role == "pharmacy":
|
||
if request.is_json:
|
||
return jsonify({"error": "Extraction access denied: Pharmacy accounts only have approve access."}), 403
|
||
flash("Pharmacy accounts only have approval access.", "warning")
|
||
return redirect(url_for("pharmacy_dashboard"))
|
||
|
||
if not user_id or role not in ["user", "dmh"]:
|
||
return redirect(url_for("login"))
|
||
|
||
# 1️⃣ Get uploaded file
|
||
file = request.files.get("invoice")
|
||
if not file or not allowed_file(file.filename):
|
||
flash("Invalid file. Upload PDF or Image.", "error")
|
||
return redirect(url_for("dashboard"))
|
||
|
||
file_path = save_file(file)
|
||
|
||
# 2️⃣ Convert PDF → images
|
||
if file_path.lower().endswith(".pdf"):
|
||
images = pdf_to_images_standalone(file_path, dpi=300)
|
||
else:
|
||
images = [Image.open(file_path)]
|
||
|
||
# 3️⃣ Run OCR pipeline
|
||
is_dmh = (role == "dmh") # ✅ DMH-only PO features
|
||
extracted_data = extract_invoice_fields(file_path, is_dmh=is_dmh)
|
||
|
||
if not extracted_data:
|
||
extracted_data = {}
|
||
|
||
# 4️⃣ Determine initial status & store in DB
|
||
init_status, init_val_status = _determine_initial_invoice_status(extracted_data)
|
||
if isinstance(extracted_data, dict):
|
||
extracted_data["status"] = init_status
|
||
extracted_data["processing_status"] = init_status
|
||
extracted_data["validation_status"] = init_val_status
|
||
|
||
pages_extracted = len(extracted_data)
|
||
extraction_type = "invoice"
|
||
image_name = os.path.basename(file_path)
|
||
extracted_json = json.dumps(extracted_data)
|
||
ist_now = datetime.now(ZoneInfo("Asia/Kolkata")).replace(tzinfo=None)
|
||
conn = get_db_connection()
|
||
cursor = conn.cursor()
|
||
|
||
cursor.execute(
|
||
"""
|
||
INSERT INTO extraction_history
|
||
(user_id, timestamp, image_name, pages_extracted, extraction_type, extracted_data, status, validation_status, processed_at)
|
||
VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s)
|
||
""",
|
||
(
|
||
user_id,
|
||
ist_now,
|
||
image_name,
|
||
pages_extracted,
|
||
extraction_type,
|
||
extracted_json,
|
||
init_status,
|
||
init_val_status,
|
||
ist_now if init_status == "completed" else None,
|
||
),
|
||
)
|
||
|
||
conn.commit()
|
||
cursor.close()
|
||
conn.close()
|
||
|
||
return redirect(url_for("view_history"))
|
||
import fitz # PyMuPDF
|
||
from PIL import Image
|
||
import io
|
||
|
||
|
||
@app.route("/upload_image", methods=["GET", "POST"])
|
||
def upload_image():
|
||
|
||
user_id = session.get("user_id")
|
||
role = session.get("role")
|
||
|
||
if role == "pharmacy":
|
||
if request.is_json:
|
||
return jsonify({"error": "Extraction access denied: Pharmacy accounts only have approve access."}), 403
|
||
flash("Pharmacy accounts only have approval access.", "warning")
|
||
return redirect(url_for("pharmacy_dashboard"))
|
||
|
||
if not user_id or role not in ["user", "dmh"]:
|
||
return redirect(url_for("login"))
|
||
|
||
conn = None
|
||
cursor = None
|
||
|
||
try:
|
||
conn = get_db_connection()
|
||
cursor = conn.cursor(dictionary=True)
|
||
|
||
cursor.execute("SELECT * FROM users WHERE username = %s", (session["user"],))
|
||
user = cursor.fetchone()
|
||
|
||
if not user:
|
||
flash("User not found.", "error")
|
||
return redirect(url_for("login"))
|
||
|
||
total_extracted = user.get("invoices_extracted", 0) + user.get("passports_extracted", 0)
|
||
extraction_limit = user.get("account_limit") or 50
|
||
|
||
if total_extracted >= extraction_limit:
|
||
flash("You have reached your extraction limit.", "error")
|
||
return redirect(url_for("dashboard"))
|
||
|
||
if request.method == "POST":
|
||
|
||
# Prevent rapid double-clicks (within 2s), but auto-expire lock after 60s so users are never stuck
|
||
import time
|
||
now_ts = time.time()
|
||
if session.get("processing", False) and (now_ts - session.get("processing_start", 0) < 60):
|
||
flash("Please wait, an extraction is already in progress.", "warning")
|
||
return redirect(url_for("dashboard"))
|
||
|
||
doc_type = request.form.get("doc_type")
|
||
if doc_type not in ["invoice", "passport"]:
|
||
flash("Invalid document type.", "error")
|
||
return redirect(url_for("dashboard"))
|
||
|
||
file = request.files.get("file")
|
||
if not file or not allowed_file(file.filename):
|
||
flash("Invalid file. Upload PDF or Image.", "error")
|
||
return redirect(url_for("dashboard"))
|
||
|
||
# ✅ FIX: Use UUID to avoid filename conflicts on second upload
|
||
original_filename = secure_filename(file.filename)
|
||
unique_filename = f"{uuid.uuid4()}_{original_filename}"
|
||
file_path = os.path.join(app.config["UPLOAD_FOLDER"], unique_filename)
|
||
file.save(file_path)
|
||
|
||
session["processing"] = True
|
||
session["processing_start"] = now_ts
|
||
|
||
# ============================
|
||
# INVOICE FLOW
|
||
# ============================
|
||
if doc_type == "invoice":
|
||
ext = original_filename.lower()
|
||
invoice_source = "manual" if ext.endswith((".jpg", ".jpeg", ".png")) else "email"
|
||
|
||
# ✅ FIX: Don't generate invoice_id here — extractor generates it
|
||
# invoice_id is returned inside extracted_data
|
||
is_dmh = (role == "dmh") # ✅ DMH-only PO features
|
||
extracted_data = extract_invoice_fields(file_path, invoice_source, is_dmh=is_dmh)
|
||
invoice_id = extracted_data.get("invoice_id") if isinstance(extracted_data, dict) else None
|
||
update_field = "invoices_extracted"
|
||
|
||
# ============================
|
||
# PASSPORT FLOW
|
||
# ============================
|
||
else:
|
||
extracted_data = extract_passport_fields(file_path)
|
||
update_field = "passports_extracted"
|
||
invoice_id = None
|
||
invoice_source = None
|
||
|
||
if not extracted_data or "error" in extracted_data:
|
||
err_msg = extracted_data.get("error", "Unknown extraction error") if isinstance(extracted_data, dict) else "No data returned by extractor"
|
||
print(f"❌ [UPLOAD FAILED] {err_msg}", flush=True)
|
||
flash(f"Extraction failed: {err_msg}", "error")
|
||
session["processing"] = False
|
||
return redirect(url_for("dashboard"))
|
||
|
||
page_count = len(extracted_data)
|
||
|
||
# ── Pull billing metadata out before saving JSON ──────────────
|
||
_input_tokens = extracted_data.pop("_input_tokens", 0)
|
||
_output_tokens = extracted_data.pop("_output_tokens", 0)
|
||
_cost_usd = extracted_data.pop("_cost_usd", 0.0)
|
||
|
||
cursor.execute(
|
||
f"UPDATE users SET {update_field} = {update_field} + %s WHERE username = %s",
|
||
(page_count, session["user"]),
|
||
)
|
||
|
||
if doc_type == "invoice":
|
||
init_status, init_val_status = _determine_initial_invoice_status(extracted_data)
|
||
else:
|
||
init_status, init_val_status = "completed", "passed"
|
||
|
||
if isinstance(extracted_data, dict):
|
||
extracted_data["status"] = init_status
|
||
extracted_data["processing_status"] = init_status
|
||
extracted_data["validation_status"] = init_val_status
|
||
|
||
now_dt = datetime.now()
|
||
cursor.execute(
|
||
"""
|
||
INSERT INTO extraction_history
|
||
(
|
||
invoice_id,
|
||
invoice_source,
|
||
user_id,
|
||
timestamp,
|
||
image_name,
|
||
pages_extracted,
|
||
extraction_type,
|
||
extracted_data,
|
||
file_path,
|
||
input_tokens,
|
||
output_tokens,
|
||
cost_usd,
|
||
status,
|
||
validation_status,
|
||
processed_at
|
||
)
|
||
VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)
|
||
""",
|
||
(
|
||
invoice_id,
|
||
invoice_source,
|
||
user["id"],
|
||
now_dt,
|
||
original_filename,
|
||
page_count,
|
||
doc_type,
|
||
json.dumps(extracted_data),
|
||
file_path,
|
||
_input_tokens,
|
||
_output_tokens,
|
||
_cost_usd,
|
||
init_status,
|
||
init_val_status,
|
||
now_dt if init_status == "completed" else None,
|
||
),
|
||
)
|
||
|
||
conn.commit()
|
||
if doc_type == "invoice":
|
||
try:
|
||
queue_invoice_if_approval_needed(extracted_data, file_path_or_name=original_filename, extraction_id=cursor.lastrowid)
|
||
except Exception as _q_err:
|
||
logging.warning(f"Could not queue invoice in PO approval: {_q_err}")
|
||
|
||
session["processing"] = False
|
||
|
||
return render_template(
|
||
"result.html",
|
||
json_data=json.dumps(extracted_data, indent=4),
|
||
invoice_id=invoice_id,
|
||
)
|
||
|
||
return redirect(url_for("dashboard"))
|
||
|
||
except Exception as e:
|
||
logging.error(f"Upload error: {e}", exc_info=True)
|
||
flash(f"Error: {e}", "error")
|
||
return redirect(url_for("dashboard"))
|
||
|
||
finally:
|
||
if cursor:
|
||
cursor.close()
|
||
if conn:
|
||
conn.close()
|
||
session["processing"] = False
|
||
|
||
# ✅ FIX: Always delete temp file after processing
|
||
try:
|
||
if "file_path" in locals() and os.path.exists(file_path):
|
||
os.remove(file_path)
|
||
print(f"✅ Temp file deleted: {file_path}")
|
||
except Exception as e:
|
||
print(f"⚠️ Could not delete temp file: {e}")
|
||
|
||
|
||
@app.route("/download_file", methods=["POST"])
|
||
def download_file():
|
||
invoice_data = request.form.get("json_data")
|
||
file_format = request.form.get("file_format")
|
||
if not invoice_data:
|
||
return "No data available for download", 400
|
||
try:
|
||
parsed_data = json.loads(invoice_data)
|
||
except json.JSONDecodeError:
|
||
return "Invalid JSON data", 400
|
||
if file_format == "json":
|
||
json_str = json.dumps(parsed_data, indent=4)
|
||
buffer = io.BytesIO(json_str.encode("utf-8"))
|
||
buffer.seek(0)
|
||
return send_file(
|
||
buffer,
|
||
as_attachment=True,
|
||
download_name="invoice_data.json",
|
||
mimetype="application/json",
|
||
)
|
||
elif file_format == "excel":
|
||
if isinstance(parsed_data, dict) and all(
|
||
key.startswith("page_") for key in parsed_data.keys()
|
||
):
|
||
data_list = []
|
||
for key, value in parsed_data.items():
|
||
if isinstance(value, dict):
|
||
value["page"] = key
|
||
data_list.append(value)
|
||
df = pd.DataFrame(data_list)
|
||
else:
|
||
df = pd.DataFrame([parsed_data])
|
||
buffer = io.BytesIO()
|
||
with pd.ExcelWriter(buffer, engine="xlsxwriter") as writer:
|
||
df.to_excel(writer, index=False)
|
||
buffer.seek(0)
|
||
return send_file(
|
||
buffer,
|
||
as_attachment=True,
|
||
download_name="invoice_data.xlsx",
|
||
mimetype="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
|
||
)
|
||
|
||
|
||
@app.route("/dashboard", methods=["GET", "POST"])
|
||
def dashboard():
|
||
if "user" not in session:
|
||
if request.is_json:
|
||
return jsonify({"error": "Unauthorized access. Please log in."}), 401
|
||
flash("Please login first.", "warning")
|
||
return redirect(url_for("login"))
|
||
if session.get("role") == "dmh":
|
||
return redirect(url_for("dmh_dashboard"))
|
||
if session.get("role") == "pharmacy":
|
||
return redirect(url_for("pharmacy_dashboard"))
|
||
session["processing"] = False
|
||
|
||
|
||
|
||
conn = None
|
||
cursor = None
|
||
try:
|
||
conn = get_db_connection()
|
||
cursor = conn.cursor(dictionary=True)
|
||
|
||
sql = "SELECT * FROM users WHERE username = %s"
|
||
cursor.execute(sql, (session["user"],))
|
||
user = cursor.fetchone()
|
||
|
||
if not user:
|
||
flash("User not found.", "error")
|
||
if request.is_json:
|
||
return jsonify({"error": "User not found."}), 404
|
||
return redirect(url_for("login"))
|
||
|
||
username = user.get("username", "N/A")
|
||
email = user.get("email", "N/A")
|
||
invoices_count = user.get("invoices_extracted", 0)
|
||
passports_count = user.get("passports_extracted", 0)
|
||
|
||
sql_history = "SELECT * FROM extraction_history WHERE user_id = %s ORDER BY timestamp DESC"
|
||
cursor.execute(sql_history, (user["id"],))
|
||
history = cursor.fetchall()
|
||
|
||
sql_api_key = "SELECT api_key FROM api_keys WHERE user_id = %s"
|
||
cursor.execute(sql_api_key, (user["id"],))
|
||
user_api_key = cursor.fetchone()
|
||
api_key = user_api_key["api_key"] if user_api_key else None
|
||
|
||
formatted_history = [
|
||
{
|
||
"timestamp_str": entry["timestamp"].strftime("%Y-%m-%d %H:%M:%S"),
|
||
"image_name": entry.get("image_name", "Unknown"),
|
||
"pages_extracted": entry.get("pages_extracted", 0),
|
||
"extraction_type": entry.get("extraction_type", "N/A"),
|
||
}
|
||
for entry in history
|
||
]
|
||
|
||
if request.is_json:
|
||
return jsonify(
|
||
{
|
||
"username": username,
|
||
"email": email,
|
||
"invoices_count": invoices_count,
|
||
"passports_count": passports_count,
|
||
"history": formatted_history,
|
||
"api_key": api_key,
|
||
}
|
||
)
|
||
|
||
return render_template(
|
||
"dashboard.html",
|
||
username=username,
|
||
email=email,
|
||
invoices_count=invoices_count,
|
||
passports_count=passports_count,
|
||
history=formatted_history,
|
||
api_key=api_key,
|
||
)
|
||
except mysql.connector.Error as db_err:
|
||
logging.error(f"Database error: {db_err}", exc_info=True)
|
||
flash(f"Database error: {db_err}", "error")
|
||
if request.is_json:
|
||
return jsonify({"error": str(db_err)}), 500
|
||
return render_template(
|
||
"dashboard.html",
|
||
username="N/A",
|
||
email="N/A",
|
||
invoices_count=0,
|
||
passports_count=0,
|
||
history=[],
|
||
api_key=None,
|
||
)
|
||
|
||
except Exception as e:
|
||
logging.error(f"Unexpected error in dashboard: {e}", exc_info=True)
|
||
flash(f"Error: {e}", "error")
|
||
if request.is_json:
|
||
return jsonify({"error": str(e)}), 500
|
||
return render_template(
|
||
"dashboard.html",
|
||
username="N/A",
|
||
email="N/A",
|
||
invoices_count=0,
|
||
passports_count=0,
|
||
history=[],
|
||
api_key=None,
|
||
)
|
||
|
||
finally:
|
||
if cursor:
|
||
cursor.close()
|
||
if conn:
|
||
conn.close()
|
||
@app.route("/dmh/dashboard")
|
||
def dmh_dashboard():
|
||
if session.get("role") != "dmh":
|
||
return redirect(url_for("login"))
|
||
session["processing"] = False
|
||
return render_template("dmh_dashboard.html")
|
||
@app.route("/view_history")
|
||
def view_history():
|
||
user_id = session.get("user_id")
|
||
role = session.get("role")
|
||
|
||
if not user_id or role not in ["user", "dmh"]:
|
||
return redirect(url_for("login"))
|
||
|
||
try:
|
||
conn = get_db_connection()
|
||
cursor = conn.cursor(dictionary=True)
|
||
|
||
cursor.execute(
|
||
"SELECT id FROM users WHERE username = %s",
|
||
(session["user"],)
|
||
)
|
||
user = cursor.fetchone()
|
||
|
||
if not user:
|
||
cursor.close()
|
||
conn.close()
|
||
return redirect(url_for("login"))
|
||
|
||
cursor.execute(
|
||
"SELECT * FROM extraction_history WHERE user_id = %s ORDER BY timestamp DESC",
|
||
(user["id"],)
|
||
)
|
||
invoice_history = cursor.fetchall()
|
||
|
||
formatted_history = []
|
||
|
||
for entry in invoice_history:
|
||
utc_time = entry["timestamp"]
|
||
|
||
if utc_time.tzinfo is None:
|
||
utc_time = utc_time.replace(tzinfo=timezone.utc)
|
||
|
||
ist_time = utc_time.astimezone(ZoneInfo("Asia/Kolkata"))
|
||
|
||
entry["timestamp_str"] = ist_time.strftime(
|
||
"%d-%m-%Y %I:%M:%S %p"
|
||
)
|
||
|
||
formatted_history.append(entry)
|
||
|
||
cursor.close()
|
||
conn.close()
|
||
|
||
return render_template(
|
||
"view_history.html",
|
||
invoice_history=formatted_history
|
||
)
|
||
except Exception as e:
|
||
print("Error:", e)
|
||
return "Something went wrong", 500
|
||
|
||
@app.route("/api/extract_invoice", methods=["POST"])
|
||
def api_extract_invoice():
|
||
if "api_key" not in request.headers:
|
||
return jsonify({"error": "Missing API key"}), 401
|
||
api_key = request.headers["api_key"]
|
||
conn = get_db_connection()
|
||
cursor = conn.cursor(dictionary=True)
|
||
sql = "SELECT * FROM api_keys WHERE api_key = %s"
|
||
cursor.execute(sql, (api_key,))
|
||
api_key_record = cursor.fetchone()
|
||
if not api_key_record:
|
||
cursor.close()
|
||
conn.close()
|
||
return jsonify({"error": "Invalid API key"}), 403
|
||
file = request.files.get("file")
|
||
if not file or not allowed_file(file.filename):
|
||
cursor.close()
|
||
conn.close()
|
||
return (
|
||
jsonify(
|
||
{"error": "Invalid file type. Please upload a valid PDF or image."}
|
||
),
|
||
400,
|
||
)
|
||
filename = secure_filename(file.filename)
|
||
file_path = os.path.join(app.config["UPLOAD_FOLDER"], filename)
|
||
file.save(file_path)
|
||
# Look up the caller's role to apply DMH-only features
|
||
cursor.execute("SELECT role FROM users WHERE id = %s", (api_key_record["user_id"],))
|
||
caller_role_row = cursor.fetchone()
|
||
caller_is_dmh = (caller_role_row["role"] == "dmh") if caller_role_row else False
|
||
invoice_data = extract_invoice_fields(file_path, is_dmh=caller_is_dmh)
|
||
# Strip internal billing keys before returning to API caller
|
||
for _k in ("_input_tokens", "_output_tokens", "_cost_usd"):
|
||
invoice_data.pop(_k, None)
|
||
if invoice_data:
|
||
sql_update = (
|
||
"UPDATE users SET invoices_extracted = invoices_extracted + 1 WHERE id = %s"
|
||
)
|
||
cursor.execute(sql_update, (api_key_record["user_id"],))
|
||
conn.commit()
|
||
cursor.close()
|
||
conn.close()
|
||
return jsonify({"success": True, "invoice_data": invoice_data}), 200
|
||
else:
|
||
cursor.close()
|
||
conn.close()
|
||
return (
|
||
jsonify({"success": False, "error": "Failed to extract invoice data"}),
|
||
500,
|
||
)
|
||
@app.route("/generate_api_key", methods=["POST"])
|
||
def generate_api_key():
|
||
if "user" not in session:
|
||
return jsonify({"error": "Unauthorized. Please log in first."}), 401
|
||
conn = get_db_connection()
|
||
cursor = conn.cursor(dictionary=True)
|
||
sql = "SELECT id FROM users WHERE username = %s"
|
||
cursor.execute(sql, (session["user"],))
|
||
user = cursor.fetchone()
|
||
if not user:
|
||
cursor.close()
|
||
conn.close()
|
||
return jsonify({"error": "User not found."}), 404
|
||
sql_check = "SELECT * FROM api_keys WHERE user_id = %s"
|
||
cursor.execute(sql_check, (user["id"],))
|
||
existing_api_key = cursor.fetchone()
|
||
if existing_api_key:
|
||
cursor.close()
|
||
conn.close()
|
||
return jsonify({"error": "You have already generated an API key."}), 400
|
||
api_key = secrets.token_hex(32)
|
||
sql_insert = (
|
||
"INSERT INTO api_keys (user_id, api_key, created_at) VALUES (%s, %s, %s)"
|
||
)
|
||
cursor.execute(sql_insert, (user["id"], api_key, datetime.utcnow()))
|
||
conn.commit()
|
||
cursor.close()
|
||
conn.close()
|
||
return jsonify({"api_key": api_key, "success": True})
|
||
|
||
|
||
@app.route("/logout")
|
||
def logout():
|
||
role = session.get("role")
|
||
is_pharmacy = role == "pharmacy" or "pharmacy_user" in session
|
||
session.clear()
|
||
flash("Logged out successfully!", "info")
|
||
if is_pharmacy:
|
||
return redirect(url_for("pharmacy_login"))
|
||
return redirect(url_for("login"))
|
||
|
||
|
||
@app.route("/admin/set-account-limit", methods=["POST"])
|
||
def set_account_limit():
|
||
try:
|
||
data = request.get_json()
|
||
new_manual_limit = data.get("manual_limit", 50)
|
||
new_api_limit = data.get("api_limit", 50)
|
||
if new_manual_limit < 0 or new_api_limit < 0:
|
||
return jsonify({"error": "Limits must be positive integers"}), 400
|
||
total_account_limit = new_manual_limit + new_api_limit
|
||
conn = get_db_connection()
|
||
cursor = conn.cursor()
|
||
sql = "UPDATE users SET manual_limit = %s, api_limit = %s, account_limit = %s"
|
||
cursor.execute(sql, (new_manual_limit, new_api_limit, total_account_limit))
|
||
conn.commit()
|
||
modified_count = cursor.rowcount
|
||
cursor.close()
|
||
conn.close()
|
||
if modified_count == 0:
|
||
return jsonify({"message": "No users updated"}), 404
|
||
return (
|
||
jsonify(
|
||
{
|
||
"message": f"Account limits set to {total_account_limit} for all users"
|
||
}
|
||
),
|
||
200,
|
||
)
|
||
except Exception as e:
|
||
app.logger.error(f"Error setting account limits: {e}")
|
||
return jsonify({"error": str(e)}), 500
|
||
|
||
|
||
@app.route("/get_api_key", methods=["GET"])
|
||
def get_api_key():
|
||
if "user" not in session:
|
||
return jsonify({"error": "Unauthorized. Please log in first."}), 401
|
||
conn = get_db_connection()
|
||
cursor = conn.cursor(dictionary=True)
|
||
sql = "SELECT id FROM users WHERE username = %s"
|
||
cursor.execute(sql, (session["user"],))
|
||
user = cursor.fetchone()
|
||
if not user:
|
||
cursor.close()
|
||
conn.close()
|
||
return jsonify({"error": "User not found."}), 404
|
||
sql_api = "SELECT api_key FROM api_keys WHERE user_id = %s"
|
||
cursor.execute(sql_api, (user["id"],))
|
||
api_key = cursor.fetchone()
|
||
cursor.close()
|
||
conn.close()
|
||
if api_key:
|
||
return jsonify({"api_key": api_key["api_key"], "success": True})
|
||
else:
|
||
return jsonify({"error": "No API key found."}), 404
|
||
|
||
|
||
@app.route("/api/routes", methods=["GET"])
|
||
def list_routes():
|
||
routes = []
|
||
for rule in app.url_map.iter_rules():
|
||
routes.append(
|
||
{"endpoint": rule.endpoint, "methods": list(rule.methods), "url": str(rule)}
|
||
)
|
||
return jsonify({"routes": routes})
|
||
|
||
|
||
@app.route("/admin/billing", methods=["GET"])
|
||
def admin_billing():
|
||
"""Admin view — shows per-user Qwen billing totals."""
|
||
if "user" not in session or session.get("role") != "admin":
|
||
flash("Unauthorized access.")
|
||
return redirect(url_for("login"))
|
||
try:
|
||
conn = get_db_connection()
|
||
cursor = conn.cursor(dictionary=True)
|
||
cursor.execute(
|
||
"""
|
||
SELECT
|
||
u.username,
|
||
u.email,
|
||
COUNT(h.id) AS total_extractions,
|
||
COALESCE(SUM(h.input_tokens), 0) AS total_input_tokens,
|
||
COALESCE(SUM(h.output_tokens), 0) AS total_output_tokens,
|
||
COALESCE(SUM(h.cost_usd), 0) AS total_cost_usd
|
||
FROM users u
|
||
LEFT JOIN extraction_history h ON u.id = h.user_id
|
||
GROUP BY u.id, u.username, u.email
|
||
ORDER BY total_cost_usd DESC
|
||
"""
|
||
)
|
||
rows = cursor.fetchall()
|
||
cursor.close()
|
||
conn.close()
|
||
return jsonify({"billing": rows}), 200
|
||
except Exception as e:
|
||
return jsonify({"error": str(e)}), 500
|
||
|
||
|
||
@app.route("/admin/billing/total", methods=["GET"])
|
||
def admin_billing_total():
|
||
"""Admin view — overall Qwen spend summary."""
|
||
if "user" not in session or session.get("role") != "admin":
|
||
return jsonify({"error": "Unauthorized"}), 401
|
||
try:
|
||
conn = get_db_connection()
|
||
cursor = conn.cursor(dictionary=True)
|
||
cursor.execute(
|
||
"""
|
||
SELECT
|
||
COALESCE(SUM(input_tokens), 0) AS total_input_tokens,
|
||
COALESCE(SUM(output_tokens), 0) AS total_output_tokens,
|
||
COALESCE(SUM(cost_usd), 0) AS total_cost_usd,
|
||
COUNT(id) AS total_extractions
|
||
FROM extraction_history
|
||
"""
|
||
)
|
||
row = cursor.fetchone()
|
||
cursor.close()
|
||
conn.close()
|
||
return jsonify(row), 200
|
||
except Exception as e:
|
||
return jsonify({"error": str(e)}), 500
|
||
|
||
|
||
port = int(os.getenv("PORT", 8080))
|
||
@app.route("/about")
|
||
def about():
|
||
return render_template("about.html")
|
||
|
||
|
||
@app.route("/pricing")
|
||
def pricing():
|
||
return render_template("pricing.html")
|
||
|
||
|
||
@app.route("/contact_sales")
|
||
def contact_sales():
|
||
return render_template("about.html")
|
||
|
||
|
||
# Add this at the end of your application.py and run once
|
||
|
||
|
||
import os
|
||
|
||
# from dotenv import load_dotenv
|
||
# load_dotenv()
|
||
from flask import Flask, request, jsonify
|
||
from dotenv import load_dotenv
|
||
import smtplib
|
||
from email.mime.multipart import MIMEMultipart
|
||
from email.mime.text import MIMEText
|
||
|
||
# Print current working directory to confirm
|
||
print("Current working directory:", os.getcwd())
|
||
|
||
# Load .env file
|
||
load_dotenv() # Looks for .env in the current working directory
|
||
|
||
# Email config
|
||
# Email Configuration
|
||
EMAIL_ADDRESS = os.getenv("EMAIL_ADDRESS") # e.g., 'your_email@gmail.com'
|
||
EMAIL_PASSWORD = os.getenv("EMAIL_PASSWORD") # e.g., Gmail app-specific password
|
||
RECIPIENT_EMAIL = os.getenv("RECIPIENT_EMAIL") # e.g., 'recipient@example.com'
|
||
SMTP_SERVER = "smtp.gmail.com" # Adjust for your email provider
|
||
SMTP_PORT = 587
|
||
|
||
|
||
def send_email(email, contact, message):
|
||
missing_configs = []
|
||
if not EMAIL_ADDRESS:
|
||
missing_configs.append("EMAIL_ADDRESS")
|
||
if not EMAIL_PASSWORD:
|
||
missing_configs.append("EMAIL_PASSWORD")
|
||
if not RECIPIENT_EMAIL:
|
||
missing_configs.append("RECIPIENT_EMAIL")
|
||
if not SMTP_SERVER:
|
||
missing_configs.append("SMTP_SERVER")
|
||
if not SMTP_PORT:
|
||
missing_configs.append("SMTP_PORT")
|
||
|
||
if missing_configs:
|
||
print(
|
||
f"Email configuration missing: {', '.join(missing_configs)}. Check .env file."
|
||
)
|
||
return False
|
||
|
||
msg = MIMEMultipart()
|
||
msg["From"] = EMAIL_ADDRESS
|
||
msg["To"] = RECIPIENT_EMAIL
|
||
msg["Subject"] = "New Query Submission from AI Infinite"
|
||
|
||
# Format body nicely whether it's contact or demo
|
||
if contact is not None:
|
||
body = f"""
|
||
Hello,
|
||
|
||
A new query has been received through the AI Infinite contact form:
|
||
|
||
Email: {email}
|
||
Contact Number: {contact or 'Not provided'}
|
||
Message: {message}
|
||
|
||
Thank you,
|
||
AI Infinite Team
|
||
"""
|
||
else:
|
||
body = message # If it's demo, just use the already formatted message
|
||
|
||
msg.attach(MIMEText(body, "plain"))
|
||
|
||
try:
|
||
server = smtplib.SMTP(SMTP_SERVER, int(SMTP_PORT))
|
||
server.starttls()
|
||
server.login(EMAIL_ADDRESS, EMAIL_PASSWORD)
|
||
server.sendmail(EMAIL_ADDRESS, RECIPIENT_EMAIL, msg.as_string())
|
||
server.quit()
|
||
print("Email sent successfully")
|
||
return True
|
||
except Exception as e:
|
||
print(f"Email error: {e}")
|
||
return False
|
||
|
||
|
||
@app.route("/submit", methods=["POST"])
|
||
def submit_query():
|
||
print("Received form submission")
|
||
email = request.form.get("email")
|
||
contact = request.form.get("contact")
|
||
message = request.form.get("message")
|
||
print(f"Form data: email={email}, contact={contact}, message={message}")
|
||
|
||
if not email or not message:
|
||
print("Validation failed: Email or message missing")
|
||
return (
|
||
jsonify({"success": False, "message": "Email and message are required"}),
|
||
400,
|
||
)
|
||
|
||
try:
|
||
conn = get_db_connection()
|
||
cursor = conn.cursor()
|
||
cursor.execute(
|
||
"INSERT INTO contact_queries (email, contact, message) VALUES (%s, %s, %s)",
|
||
(email, contact, message),
|
||
)
|
||
conn.commit()
|
||
print("Query stored in database")
|
||
except Exception as e:
|
||
print(f"Database error: {e}")
|
||
return jsonify({"success": False, "message": "Error storing query"}), 500
|
||
finally:
|
||
cursor.close()
|
||
conn.close()
|
||
|
||
if send_email(email, contact, message):
|
||
print("Email sent successfully")
|
||
return jsonify({"success": True, "message": "Query stored and email sent"})
|
||
else:
|
||
print("Email sending failed")
|
||
return (
|
||
jsonify(
|
||
{"success": False, "message": "Query stored, but failed to send email"}
|
||
),
|
||
200,
|
||
)
|
||
@app.route("/schedule", methods=["POST"])
|
||
def schedule_demo():
|
||
print("Received demo submission")
|
||
name = request.form.get("name")
|
||
email = request.form.get("company-email")
|
||
timezone = request.form.get("timezone")
|
||
|
||
if not email:
|
||
print("Validation failed: Email missing")
|
||
return jsonify({"success": False, "message": "Email is required"}), 400
|
||
|
||
message = (
|
||
"Hello,\n"
|
||
"A new demo request has been issued by\n\n"
|
||
f"Name: {name or 'Not provided'}\n"
|
||
f"Email: {email}\n"
|
||
f"Timezone: {timezone or 'Not specified'}\n\n"
|
||
"Thank you."
|
||
)
|
||
|
||
if send_email(email, None, message):
|
||
print("Demo email sent successfully")
|
||
return jsonify(
|
||
{"success": True, "message": "Demo request processed and email sent"}
|
||
)
|
||
else:
|
||
print("Demo email sending failed")
|
||
return (
|
||
jsonify(
|
||
{
|
||
"success": False,
|
||
"message": "Demo request processed, but failed to send email",
|
||
}
|
||
),
|
||
200,
|
||
)
|
||
|
||
|
||
@app.route("/home")
|
||
def home_logged_in():
|
||
if "user" not in session:
|
||
print("User not in session. Redirecting to index.")
|
||
return redirect(url_for("index"))
|
||
if session.get("role") == "pharmacy":
|
||
return redirect(url_for("pharmacy_dashboard"))
|
||
print(f"User is in session: {session['user']}")
|
||
return render_template("home.html", logged_in=True, username=session["user"])
|
||
@app.context_processor
|
||
def inject_user():
|
||
return {"logged_in": "user" in session, "username": session.get("user")}
|
||
|
||
from datetime import datetime
|
||
|
||
|
||
|
||
# ================================================================
|
||
# ✅ PHARMACY APPROVAL PORTAL ROUTES & APIS
|
||
# ================================================================
|
||
|
||
def pharmacy_or_admin_required(f):
|
||
@wraps(f)
|
||
def decorated_function(*args, **kwargs):
|
||
if "user" not in session and "user_id" not in session:
|
||
if request.is_json:
|
||
return jsonify({"error": "Unauthorized"}), 401
|
||
return redirect(url_for("pharmacy_login"))
|
||
role = session.get("role")
|
||
if role not in ("pharmacy", "admin", "dmh"):
|
||
if request.is_json:
|
||
return jsonify({"error": "Access denied: Pharmacy or admin role required."}), 403
|
||
return redirect(url_for("pharmacy_login"))
|
||
return f(*args, **kwargs)
|
||
return decorated_function
|
||
|
||
|
||
@app.route("/pharmacy/login", methods=["GET", "POST"])
|
||
def pharmacy_login():
|
||
"""Dedicated, isolated login portal for Pharmacy staff."""
|
||
if session.get("user") and session.get("role") in ("pharmacy", "admin", "dmh"):
|
||
return redirect(url_for("pharmacy_dashboard"))
|
||
|
||
if request.method == "POST":
|
||
username_input = request.form.get("username", "").strip()
|
||
password_input = request.form.get("password", "").strip()
|
||
|
||
if not username_input or not password_input:
|
||
flash("Please enter both staff username and password.", "error")
|
||
return render_template("pharmacy_login.html")
|
||
|
||
# Authenticate against dedicated Pharmacy database (users.db)
|
||
conn = get_db()
|
||
cursor = conn.cursor()
|
||
cursor.execute(
|
||
"SELECT * FROM users WHERE username = ? OR email = ?",
|
||
(username_input, username_input)
|
||
)
|
||
user = cursor.fetchone()
|
||
conn.close()
|
||
|
||
is_valid = False
|
||
if user and user["password"]:
|
||
stored_pw = user["password"]
|
||
if password_input == stored_pw:
|
||
is_valid = True
|
||
elif stored_pw.startswith("$2b$") or stored_pw.startswith("$2a$"):
|
||
try:
|
||
import bcrypt
|
||
is_valid = bcrypt.checkpw(password_input.encode("utf-8"), stored_pw.encode("utf-8"))
|
||
except Exception:
|
||
pass
|
||
elif stored_pw.startswith("scrypt:") or stored_pw.startswith("pbkdf2:"):
|
||
try:
|
||
from werkzeug.security import check_password_hash
|
||
is_valid = check_password_hash(stored_pw, password_input)
|
||
except Exception:
|
||
pass
|
||
|
||
if not user or not is_valid:
|
||
flash("Invalid pharmacy staff credentials. Please check username and password.", "error")
|
||
return render_template("pharmacy_login.html")
|
||
|
||
session.clear()
|
||
session["user_id"] = user["id"]
|
||
session["user"] = user["username"]
|
||
session["username"] = user["username"]
|
||
session["role"] = "pharmacy"
|
||
session["is_admin"] = bool(user["is_admin"])
|
||
session["pharmacy_user"] = user["username"]
|
||
|
||
return redirect(url_for("pharmacy_dashboard"))
|
||
|
||
return render_template("pharmacy_login.html")
|
||
|
||
|
||
@app.route("/pharmacy/logout", methods=["GET"])
|
||
def pharmacy_logout():
|
||
"""Sign out from the Pharmacy Portal and return to Pharmacy Login."""
|
||
session.clear()
|
||
flash("You have successfully signed out of the Pharmacy Portal.", "success")
|
||
return redirect(url_for("pharmacy_login"))
|
||
|
||
|
||
# ================================================================
|
||
# ✅ DMH PO NUMBER APPROVAL & ITEM CODE MANAGEMENT SUBSYSTEM
|
||
# ================================================================
|
||
|
||
def login_required(f):
|
||
@wraps(f)
|
||
def decorated_function(*args, **kwargs):
|
||
if 'user_id' not in session and 'user' not in session and 'pharmacy_user' not in session:
|
||
if request.is_json or request.path.startswith('/api/'):
|
||
return jsonify({'success': False, 'error': 'Unauthorized - please log in'}), 401
|
||
return redirect(url_for('login'))
|
||
return f(*args, **kwargs)
|
||
return decorated_function
|
||
|
||
def admin_required(f):
|
||
@wraps(f)
|
||
def decorated_function(*args, **kwargs):
|
||
user = get_current_user()
|
||
is_admin = False
|
||
if user:
|
||
if isinstance(user, dict):
|
||
is_admin = bool(user.get('is_admin') or user.get('role') == 'admin')
|
||
else:
|
||
try:
|
||
is_admin = bool(user['is_admin'] or user['role'] == 'admin')
|
||
except Exception:
|
||
pass
|
||
if not is_admin:
|
||
if request.is_json or request.path.startswith('/api/'):
|
||
return jsonify({'success': False, 'error': 'Admin access required'}), 403
|
||
return redirect(url_for('login'))
|
||
return f(*args, **kwargs)
|
||
return decorated_function
|
||
|
||
def require_api_key_or_login(f):
|
||
@wraps(f)
|
||
def decorated(*args, **kwargs):
|
||
api_key = (request.headers.get('X-API-Key') or request.headers.get('x-api-key') or '').strip()
|
||
expected = os.getenv('N8N_WEBHOOK_SECRET', '').strip()
|
||
local_key = os.getenv('API_KEY', '').strip()
|
||
if (expected and api_key == expected) or (local_key and api_key == local_key) or api_key == 'nirajAi26@DMH':
|
||
return f(*args, **kwargs)
|
||
if 'user_id' in session or 'user' in session or 'pharmacy_user' in session:
|
||
return f(*args, **kwargs)
|
||
return jsonify({'success': False, 'error': 'Unauthorized — provide X-API-Key header or log in'}), 401
|
||
return decorated
|
||
|
||
def get_current_user():
|
||
user_id = session.get('user_id')
|
||
username = session.get('username') or session.get('user')
|
||
conn = get_db()
|
||
cursor = conn.cursor()
|
||
user = None
|
||
if user_id:
|
||
cursor.execute('SELECT * FROM users WHERE id = ?', (user_id,))
|
||
user = cursor.fetchone()
|
||
elif username:
|
||
cursor.execute('SELECT * FROM users WHERE username = ?', (username,))
|
||
user = cursor.fetchone()
|
||
conn.close()
|
||
|
||
if not user:
|
||
try:
|
||
conn_main = get_db_connection()
|
||
cur_main = conn_main.cursor(dictionary=True)
|
||
if user_id:
|
||
cur_main.execute('SELECT * FROM users WHERE id = %s', (user_id,))
|
||
user = cur_main.fetchone()
|
||
elif username:
|
||
cur_main.execute('SELECT * FROM users WHERE username = %s', (username,))
|
||
user = cur_main.fetchone()
|
||
cur_main.close()
|
||
conn_main.close()
|
||
except Exception:
|
||
pass
|
||
|
||
return user
|
||
|
||
def safe_strip(value, default=''):
|
||
"""Safely strip a value that might be None or not a string."""
|
||
if value is None:
|
||
return default
|
||
if isinstance(value, str):
|
||
return value.strip()
|
||
return str(value).strip() if value else default
|
||
|
||
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'] if 'updated_at' in row.keys() else None,
|
||
}
|
||
|
||
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'
|
||
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."""
|
||
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 = _http_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:
|
||
logging.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."""
|
||
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 = _http_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 Exception:
|
||
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:
|
||
logging.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."""
|
||
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 = _http_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 _http_requests.exceptions.Timeout:
|
||
return {'status': 'timeout', 'error': 'Request timed out'}
|
||
except Exception as e:
|
||
return {'status': 'failed', 'error': str(e)}
|
||
|
||
def queue_invoice_if_approval_needed(extracted_data, file_path_or_name=None, extraction_id=None):
|
||
"""
|
||
Evaluates extracted invoice data against the 5 DMH conditions:
|
||
Condition 1: PO Valid, Item Codes Valid -> Store via DMH GRN API
|
||
Condition 2: PO Valid, Item Codes Missing -> Look up PO Details API
|
||
Condition 4: PO Missing, Item Codes Valid -> Queue as Condition 4 (pending)
|
||
Condition 5: PO Missing, Item Codes Missing -> Queue as Condition 5 (pending)
|
||
"""
|
||
if not extracted_data or not isinstance(extracted_data, dict):
|
||
return None
|
||
|
||
po_val = extracted_data.get('po_number') or extracted_data.get('PO_number') or ''
|
||
items = extracted_data.get('items') or []
|
||
inv_num = extracted_data.get('invoice_number') or extracted_data.get('invoice_id') or ''
|
||
vendor = extracted_data.get('seller_name') or extracted_data.get('vendor_name') or ''
|
||
inv_date = extracted_data.get('invoice_date') or ''
|
||
fname = os.path.basename(file_path_or_name) if file_path_or_name else 'invoice.pdf'
|
||
|
||
cond = classify_invoice_condition(po_val, items)
|
||
logging.info(f"Classified invoice {inv_num} as {cond} (PO={po_val})")
|
||
|
||
user_id = session.get('user_id') or 1
|
||
conn = get_db()
|
||
cursor = conn.cursor()
|
||
|
||
cursor.execute(
|
||
"INSERT INTO extractions (user_id, invoice_id, filename, extraction_data) VALUES (?, ?, ?, ?)",
|
||
(user_id, inv_num, fname, json.dumps(extracted_data))
|
||
)
|
||
db_ext_id = cursor.lastrowid
|
||
conn.commit()
|
||
|
||
if cond == 'condition_1':
|
||
call_dmh_create_grn_api(extracted_data)
|
||
conn.close()
|
||
return {'condition': 'condition_1', 'status': 'completed'}
|
||
|
||
elif cond == 'condition_2':
|
||
ok, po_items, raw_resp, err = call_dmh_po_details_api(po_val)
|
||
merged_items, any_found = merge_po_details_into_items(items, po_items)
|
||
if ok and any_found and are_items_coded(merged_items):
|
||
extracted_data['items'] = merged_items
|
||
call_dmh_create_grn_api(extracted_data)
|
||
conn.close()
|
||
return {'condition': 'condition_2', 'status': 'completed'}
|
||
else:
|
||
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 (?, ?, ?, ?, ?, ?, 'condition_3', 'pending_item_code', 'missing', ?)
|
||
''', (db_ext_id, inv_num, vendor, inv_date, fname, po_val, json.dumps({'items': items, 'full_invoice': extracted_data})))
|
||
new_id = cursor.lastrowid
|
||
conn.commit()
|
||
conn.close()
|
||
return {'condition': 'condition_3', 'po_invoice_id': new_id, 'status': 'pending_item_code'}
|
||
|
||
elif cond == 'condition_4':
|
||
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 (?, ?, ?, ?, ?, ?, 'condition_4', 'pending', 'present', ?)
|
||
''', (db_ext_id, inv_num, vendor, inv_date, fname, po_val, json.dumps({'items': items, 'full_invoice': extracted_data})))
|
||
new_id = cursor.lastrowid
|
||
conn.commit()
|
||
conn.close()
|
||
return {'condition': 'condition_4', 'po_invoice_id': new_id, 'status': 'pending'}
|
||
|
||
else:
|
||
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 (?, ?, ?, ?, ?, ?, 'condition_5', 'pending', 'missing', ?)
|
||
''', (db_ext_id, inv_num, vendor, inv_date, fname, po_val, json.dumps({'items': items, 'full_invoice': extracted_data})))
|
||
new_id = cursor.lastrowid
|
||
conn.commit()
|
||
conn.close()
|
||
return {'condition': 'condition_5', 'po_invoice_id': new_id, 'status': 'pending'}
|
||
|
||
|
||
# Dashboard Routes:
|
||
@app.route('/po-approval', methods=['GET'])
|
||
def po_approval_dashboard():
|
||
"""Render the PO Number Approval & Item Code Management Dashboard."""
|
||
if 'user_id' not in session and 'user' not in session and 'pharmacy_user' not in session:
|
||
return redirect(url_for('login'))
|
||
username = session.get('username') or session.get('user') or session.get('pharmacy_user') or 'User'
|
||
return render_template('po_approval_dashboard.html', username=username)
|
||
|
||
|
||
@app.route('/pharmacy', methods=['GET'])
|
||
@app.route('/pharmacy/dashboard', methods=['GET'])
|
||
def pharmacy_dashboard():
|
||
"""Render the Pharmacy Approval Dashboard."""
|
||
return po_approval_dashboard()
|
||
|
||
|
||
@app.route('/api/dashboard/stats', methods=['GET'])
|
||
@login_required
|
||
def get_dashboard_stats():
|
||
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 IN ('approved', 'completed')")
|
||
completed_invoices = cursor.fetchone()['c']
|
||
|
||
cursor.execute("SELECT COUNT(*) AS c FROM po_approval_history WHERE approval_status IN ('approved', 'completed')")
|
||
completed_history = cursor.fetchone()['c']
|
||
|
||
total_processed = max(completed_invoices, completed_history)
|
||
|
||
cursor.execute("SELECT COUNT(*) AS c FROM item_codes")
|
||
catalog_count = cursor.fetchone()['c']
|
||
|
||
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:
|
||
logging.error(f"❌ Error fetching dashboard stats: {e}")
|
||
return jsonify({'success': False, 'error': str(e)}), 500
|
||
|
||
|
||
@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:
|
||
logging.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()
|
||
|
||
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 Exception:
|
||
pass
|
||
d['items'] = items
|
||
result.append(d)
|
||
|
||
return jsonify({'success': True, 'data': result, 'count': len(result)}), 200
|
||
except Exception as e:
|
||
logging.error(f"❌ Item approval pending error: {e}")
|
||
return jsonify({'success': False, 'error': str(e)}), 500
|
||
|
||
|
||
@app.route('/api/po-approval/invoice/<int:po_invoice_id>', 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 Exception:
|
||
items = []
|
||
|
||
if not items and 'items_json' in po_inv.keys():
|
||
try:
|
||
raw_items_json = po_inv['items_json']
|
||
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 Exception:
|
||
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:
|
||
logging.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 (Condition 3, 4, or 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'
|
||
|
||
if condition_type == 'condition_3':
|
||
approval_status = 'pending_item_code'
|
||
item_code_status = 'not_found'
|
||
elif condition_type == 'condition_4':
|
||
approval_status = 'pending'
|
||
item_code_status = 'present'
|
||
else:
|
||
approval_status = 'pending'
|
||
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()
|
||
|
||
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()
|
||
return jsonify({'success': True, 'po_invoice_id': new_id, 'condition_type': condition_type, 'approval_status': approval_status}), 201
|
||
except Exception as e:
|
||
logging.error(f"❌ PO approval submit error: {e}")
|
||
return jsonify({'success': False, 'error': str(e)}), 500
|
||
|
||
|
||
@app.route('/api/po-approval/<int:po_invoice_id>/approve', methods=['POST'])
|
||
@login_required
|
||
def po_approval_approve(po_invoice_id):
|
||
"""Approve a PO number for an invoice (Condition 4 or Condition 5)."""
|
||
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'] in ('approved', 'completed'):
|
||
conn.close()
|
||
return jsonify({'success': False, 'error': 'Invoice already completed'}), 409
|
||
|
||
user_id = session.get('user_id')
|
||
username = session.get('username') or session.get('user') or 'pharmacy_tester'
|
||
cond = po_inv['condition_type'] or 'condition_4'
|
||
|
||
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 Exception:
|
||
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 Exception:
|
||
pass
|
||
|
||
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"
|
||
|
||
if cond == 'condition_5':
|
||
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 not (api_ok and any_codes_found):
|
||
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:
|
||
items = merged_items
|
||
full_inv['items'] = items
|
||
|
||
full_inv['items'] = items
|
||
grn_ok, grn_res, grn_err = call_dmh_create_grn_api(full_inv)
|
||
new_status = 'approved'
|
||
|
||
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))
|
||
|
||
webhook_payload = {
|
||
"event": "po_number_approved",
|
||
"invoice_id": po_invoice_id,
|
||
"invoice_number": po_inv['invoice_number'],
|
||
"approved_po_number": po_number,
|
||
"approved_by": user_id,
|
||
"approval_status": "approved"
|
||
}
|
||
wh_result = trigger_po_approval_webhook(webhook_payload)
|
||
wh_status = wh_result.get('status', 'not_triggered')
|
||
|
||
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, webhook_triggered_at)
|
||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'po_approval', ?, ?, CURRENT_TIMESTAMP)
|
||
''', (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, cond, f'{cond.upper()}: PO approved. GRN: {grn_res or grn_err}', wh_status))
|
||
conn.commit()
|
||
conn.close()
|
||
|
||
return jsonify({
|
||
'success': True,
|
||
'approval_status': 'approved',
|
||
'webhook_status': wh_status,
|
||
'condition_type': cond,
|
||
'message': f'PO Number "{po_number}" approved.'
|
||
}), 200
|
||
|
||
except Exception as e:
|
||
logging.error(f"❌ PO approval approve error: {e}")
|
||
return jsonify({'success': False, 'error': str(e)}), 500
|
||
|
||
|
||
@app.route('/api/item-approval/<int:po_invoice_id>/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."""
|
||
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') or session.get('user') or 'pharmacy_tester'
|
||
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 Exception:
|
||
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
|
||
|
||
grn_ok, grn_res, grn_err = call_dmh_create_grn_api(full_inv)
|
||
|
||
cursor.execute('''
|
||
UPDATE po_approval_invoices
|
||
SET approval_status = 'approved',
|
||
item_code_status = 'approved',
|
||
items_json = ?
|
||
WHERE id = ?
|
||
''', (json.dumps({'items': items_update, 'full_invoice': full_inv}), po_invoice_id))
|
||
|
||
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': 'approved',
|
||
'invoice_data': full_inv
|
||
}
|
||
wh_result = trigger_po_approval_webhook(webhook_payload)
|
||
wh_status = wh_result.get('status', 'not_triggered')
|
||
|
||
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, webhook_triggered_at)
|
||
VALUES (?, ?, ?, ?, ?, ?, 'approved', ?, ?, ?, 'item_code_approval', ?, ?, CURRENT_TIMESTAMP)
|
||
''', (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.', wh_status))
|
||
conn.commit()
|
||
conn.close()
|
||
|
||
return jsonify({
|
||
'success': True,
|
||
'approval_status': 'approved',
|
||
'webhook_status': wh_status,
|
||
'message': 'Item codes approved! Invoice successfully stored in DMH Database.'
|
||
}), 200
|
||
|
||
except Exception as e:
|
||
logging.error(f"❌ Item approval approve error: {e}")
|
||
return jsonify({'success': False, 'error': str(e)}), 500
|
||
|
||
|
||
@app.route('/api/po-approval/<int:po_invoice_id>/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') or session.get('user') or 'pharmacy_tester'
|
||
|
||
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:
|
||
logging.error(f"❌ PO approval reject error: {e}")
|
||
return jsonify({'success': False, 'error': str(e)}), 500
|
||
|
||
|
||
@app.route('/api/po-approval/<int:history_id>/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:
|
||
logging.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:
|
||
where.append('approval_status = ?')
|
||
params.append(status_filter)
|
||
if cond_filter:
|
||
where.append('condition_type = ?')
|
||
params.append(cond_filter)
|
||
if type_filter:
|
||
where.append('approval_type = ?')
|
||
params.append(type_filter)
|
||
if webhook_status_filter:
|
||
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 id 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:
|
||
logging.error(f"❌ PO approval history error: {e}")
|
||
return jsonify({'success': False, 'error': str(e)}), 500
|
||
|
||
|
||
@app.route('/api/profile', methods=['GET'])
|
||
@login_required
|
||
def get_profile():
|
||
"""Get user profile."""
|
||
user = get_current_user()
|
||
if not user:
|
||
return jsonify({'success': False, 'error': 'User not found'}), 404
|
||
d = dict(user) if not isinstance(user, dict) else user
|
||
return jsonify({
|
||
'success': True,
|
||
'data': {
|
||
'username': d.get('username'),
|
||
'email': d.get('email'),
|
||
'created_at': str(d.get('created_at')),
|
||
'last_login': str(d.get('last_login')) if d.get('last_login') else None
|
||
}
|
||
}), 200
|
||
|
||
|
||
@app.route('/api/config', methods=['GET'])
|
||
def get_config():
|
||
"""Get app configuration."""
|
||
conn = get_db()
|
||
cursor = conn.cursor()
|
||
cursor.execute("SELECT COUNT(*) AS c FROM item_codes")
|
||
count = cursor.fetchone()['c']
|
||
conn.close()
|
||
return jsonify({
|
||
'drug_database_loaded': count > 0,
|
||
'drug_count': count,
|
||
'max_file_size_mb': 100
|
||
}), 200
|
||
|
||
|
||
@app.route('/api/pending-items', methods=['GET'])
|
||
@login_required
|
||
def get_pending_items():
|
||
"""Every item, across all of user's invoices, whose item code is not in catalog yet."""
|
||
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()}
|
||
|
||
user_id = session.get('user_id') or 1
|
||
cursor.execute(
|
||
'''SELECT id, invoice_id, filename, created_at, extraction_data
|
||
FROM extractions WHERE user_id = ? ORDER BY created_at DESC''',
|
||
(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
|
||
|
||
for idx, item in enumerate(items):
|
||
if not isinstance(item, dict):
|
||
continue
|
||
code = safe_strip(item.get('item_code', ''))
|
||
in_sheet = bool(code) and code.upper() in catalog_codes
|
||
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,
|
||
})
|
||
|
||
conn.close()
|
||
|
||
return jsonify({
|
||
'success': True,
|
||
'data': pending,
|
||
'total_pending': len(pending),
|
||
'total_invoices': len(rows)
|
||
}), 200
|
||
except Exception as e:
|
||
logging.error(f"❌ Pending items error: {e}")
|
||
return jsonify({'success': False, 'error': str(e)}), 500
|
||
|
||
|
||
|
||
@app.route("/api/pharmacy/stats", methods=["GET"])
|
||
@pharmacy_or_admin_required
|
||
def pharmacy_stats():
|
||
"""Metric cards data for the pharmacy portal."""
|
||
try:
|
||
conn = get_db_connection()
|
||
cursor = conn.cursor(dictionary=True)
|
||
cursor.execute(
|
||
"""
|
||
SELECT id, extracted_data FROM extraction_history
|
||
WHERE extraction_type = 'invoice' AND extracted_data IS NOT NULL
|
||
ORDER BY id DESC LIMIT 200
|
||
"""
|
||
)
|
||
rows = cursor.fetchall()
|
||
cursor.close()
|
||
conn.close()
|
||
|
||
unique_pending_drugs = set()
|
||
approved_count = 0
|
||
|
||
for row in rows:
|
||
raw_data = row.get("extracted_data")
|
||
if not raw_data:
|
||
continue
|
||
try:
|
||
data = json.loads(raw_data)
|
||
items = data.get("items", [])
|
||
for it in items:
|
||
code = str(it.get("item_code") or "").strip()
|
||
desc = str(it.get("description") or "").strip()
|
||
if code and icm.code_in_catalog(code):
|
||
approved_count += 1
|
||
elif desc:
|
||
if icm.extract_item_code_from_drug_list(desc):
|
||
approved_count += 1
|
||
else:
|
||
norm = icm.normalize_drug_name(desc) or desc.lower()
|
||
unique_pending_drugs.add(norm)
|
||
except Exception:
|
||
continue
|
||
|
||
pending_count = len(unique_pending_drugs)
|
||
|
||
catalog_total = len(icm.CATALOG_CODES_SET) if icm.CATALOG_CODES_SET else 14358
|
||
|
||
return jsonify({
|
||
"success": True,
|
||
"pending_count": pending_count,
|
||
"approved_count": approved_count,
|
||
"catalog_total": catalog_total
|
||
}), 200
|
||
except Exception as e:
|
||
logging.error(f"Error in pharmacy_stats: {e}")
|
||
return jsonify({
|
||
"success": True,
|
||
"pending_count": 0,
|
||
"approved_count": 0,
|
||
"catalog_total": len(icm.CATALOG_CODES_SET) if icm.CATALOG_CODES_SET else 14358
|
||
}), 200
|
||
|
||
|
||
@app.route("/api/pharmacy/pending-items", methods=["GET"])
|
||
@pharmacy_or_admin_required
|
||
def pharmacy_pending_items():
|
||
"""All unique unmapped items across invoices waiting for item-code approval.
|
||
Deduplicates by drug name: if a drug appears across multiple invoices or batches,
|
||
it only appears once in the approval queue. Once approved, it is never added again.
|
||
"""
|
||
try:
|
||
conn = get_db_connection()
|
||
cursor = conn.cursor(dictionary=True)
|
||
cursor.execute(
|
||
"""
|
||
SELECT h.id, h.invoice_id, h.image_name, h.timestamp, h.extracted_data, u.username
|
||
FROM extraction_history h
|
||
LEFT JOIN users u ON u.id = h.user_id
|
||
WHERE h.extraction_type = 'invoice' AND h.extracted_data IS NOT NULL
|
||
ORDER BY h.id DESC LIMIT 300
|
||
"""
|
||
)
|
||
rows = cursor.fetchall()
|
||
cursor.close()
|
||
conn.close()
|
||
|
||
pending_by_desc = {}
|
||
updated_extractions = {}
|
||
|
||
for r in rows:
|
||
try:
|
||
raw_json = r.get("extracted_data")
|
||
if not raw_json:
|
||
continue
|
||
d = json.loads(raw_json)
|
||
items = d.get("items", [])
|
||
ext_changed = False
|
||
|
||
for idx, it in enumerate(items):
|
||
code = str(it.get("item_code") or "").strip()
|
||
in_csv = bool(code and icm.code_in_catalog(code))
|
||
if in_csv:
|
||
continue
|
||
|
||
desc = str(it.get("description") or "").strip()
|
||
if not desc:
|
||
continue
|
||
|
||
# 1. If this drug name is already approved in the catalog, auto-resolve it!
|
||
catalog_match = icm.extract_item_code_from_drug_list(desc)
|
||
if catalog_match:
|
||
it["item_code"] = catalog_match
|
||
it["in_csv"] = True
|
||
it["item_code_source"] = "drug_list_match"
|
||
ext_changed = True
|
||
continue
|
||
|
||
# 2. Group by normalized drug description so each unique drug is only approved ONCE
|
||
norm_desc = icm.normalize_drug_name(desc) or desc.lower()
|
||
inv_display = d.get("invoice_number") or r.get("invoice_id") or f"INV-{r['id']}"
|
||
|
||
if norm_desc in pending_by_desc:
|
||
existing = pending_by_desc[norm_desc]
|
||
existing["occurrences_count"] += 1
|
||
existing["occurrences"].append({
|
||
"extraction_id": r["id"],
|
||
"index": idx
|
||
})
|
||
if inv_display not in existing["invoice_list"]:
|
||
existing["invoice_list"].append(inv_display)
|
||
else:
|
||
ts = r.get("timestamp")
|
||
if isinstance(ts, datetime):
|
||
created_str = ts.strftime("%Y-%m-%d %H:%M")
|
||
elif ts:
|
||
created_str = str(ts)[:16]
|
||
else:
|
||
created_str = ""
|
||
|
||
pending_by_desc[norm_desc] = {
|
||
"extraction_id": r["id"],
|
||
"index": idx,
|
||
"invoice_id": r.get("invoice_id") or d.get("invoice_id") or f"INV-{r['id']}",
|
||
"invoice_number": inv_display,
|
||
"invoice_list": [inv_display],
|
||
"occurrences_count": 1,
|
||
"occurrences": [{
|
||
"extraction_id": r["id"],
|
||
"index": idx
|
||
}],
|
||
"seller_name": d.get("seller_name") or "—",
|
||
"customer_name": d.get("customer_name") or "—",
|
||
"filename": r.get("image_name") or "Invoice",
|
||
"created_at": created_str,
|
||
"uploader": r.get("username") or "Staff",
|
||
"description": desc,
|
||
"item_code": code,
|
||
"suggested_code": "",
|
||
"hsn_sac": it.get("hsn_sac") or "",
|
||
"batch": it.get("Batch") or it.get("batch") or "",
|
||
"expiry_date": it.get("expiry_date") or "",
|
||
"quantity": it.get("quantity") or 0,
|
||
"unit_price": it.get("unit_price") or 0,
|
||
"total_price": it.get("total_price") or 0,
|
||
"taxable_value": it.get("taxable_value") or 0,
|
||
"status": "pending"
|
||
}
|
||
|
||
if ext_changed:
|
||
proc_res = validate_and_process_invoice(d, approved_by="catalog_auto_resolve")
|
||
if proc_res["ok"]:
|
||
updated_extractions[r["id"]] = (
|
||
json.dumps(proc_res["processed_data"]),
|
||
proc_res["status"],
|
||
proc_res["validation_status"],
|
||
)
|
||
else:
|
||
updated_extractions[r["id"]] = (
|
||
json.dumps(d),
|
||
r.get("status") or "pending_approval",
|
||
r.get("validation_status") or "partial",
|
||
)
|
||
|
||
except Exception as row_err:
|
||
logging.error(f"Error parsing extraction row {r.get('id')}: {row_err}")
|
||
continue
|
||
|
||
# If any extractions were auto-resolved from catalog, persist changes
|
||
if updated_extractions:
|
||
try:
|
||
conn2 = get_db_connection()
|
||
cur2 = conn2.cursor()
|
||
now_dt = datetime.now()
|
||
for eid, (ujson, ustatus, uval_status) in updated_extractions.items():
|
||
cur2.execute(
|
||
"""
|
||
UPDATE extraction_history
|
||
SET extracted_data = %s,
|
||
status = %s,
|
||
validation_status = %s,
|
||
processed_at = CASE WHEN %s = 'approved' THEN %s ELSE processed_at END
|
||
WHERE id = %s
|
||
""",
|
||
(ujson, ustatus, uval_status, ustatus, now_dt, eid),
|
||
)
|
||
conn2.commit()
|
||
cur2.close()
|
||
conn2.close()
|
||
except Exception as save_err:
|
||
logging.error(f"Error saving auto-resolved extractions: {save_err}")
|
||
|
||
pending = list(pending_by_desc.values())
|
||
|
||
return jsonify({
|
||
"success": True,
|
||
"data": pending,
|
||
"count": len(pending)
|
||
}), 200
|
||
except Exception as e:
|
||
logging.error(f"Error in pharmacy_pending_items: {e}")
|
||
return jsonify({"success": False, "error": str(e)}), 500
|
||
|
||
|
||
def dispatch_n8n_approval_webhook(extraction_id, invoice_data, approver_username="pharmacy"):
|
||
"""
|
||
Dispatches the approved invoice extraction data to the configured n8n webhook URL.
|
||
This enables n8n to receive approved invoices and store them into the external
|
||
hospital/client database using their database API key and URL.
|
||
"""
|
||
webhook_url = os.getenv("N8N_APPROVED_WEBHOOK_URL", "").strip()
|
||
if not webhook_url:
|
||
logging.info(f"[N8N Webhook] N8N_APPROVED_WEBHOOK_URL not configured. Skipping webhook for invoice {extraction_id}.")
|
||
return {"status": "skipped", "reason": "N8N_APPROVED_WEBHOOK_URL not configured in .env"}
|
||
|
||
try:
|
||
now_str = datetime.now(ZoneInfo("Asia/Kolkata")).isoformat()
|
||
except Exception:
|
||
now_str = datetime.utcnow().isoformat()
|
||
|
||
# Build clean and comprehensive payload
|
||
payload = dict(invoice_data) if isinstance(invoice_data, dict) else {"data": invoice_data}
|
||
payload["event"] = "invoice_approved"
|
||
payload["extraction_id"] = extraction_id
|
||
payload["status"] = "approved"
|
||
payload["approved_by"] = approver_username
|
||
payload["approved_at"] = now_str
|
||
# Explicit nested field so n8n workflows can access either $json.items or $json.invoice_data.items
|
||
payload["invoice_data"] = invoice_data
|
||
|
||
headers = {
|
||
"Content-Type": "application/json",
|
||
"User-Agent": "AIInvoice-OCR/1.0"
|
||
}
|
||
secret = os.getenv("N8N_WEBHOOK_SECRET", "").strip()
|
||
if secret:
|
||
headers["X-Webhook-Secret"] = secret
|
||
|
||
try:
|
||
resp = _http_requests.post(webhook_url, json=payload, headers=headers, timeout=10)
|
||
logging.info(f"[N8N Webhook] Dispatched approved invoice {extraction_id} to {webhook_url} -> HTTP {resp.status_code}")
|
||
return {
|
||
"status": "delivered" if resp.status_code < 400 else "failed",
|
||
"status_code": resp.status_code,
|
||
"response": resp.text[:200]
|
||
}
|
||
except Exception as e:
|
||
logging.error(f"[N8N Webhook] Delivery failed for extraction {extraction_id}: {e}")
|
||
return {
|
||
"status": "error",
|
||
"error": str(e)
|
||
}
|
||
|
||
|
||
@app.route("/api/pharmacy/test-webhook", methods=["GET", "POST"])
|
||
def pharmacy_test_webhook():
|
||
"""Test endpoint allowing developers/admins to verify their n8n webhook connection."""
|
||
webhook_url = os.getenv("N8N_APPROVED_WEBHOOK_URL", "").strip()
|
||
if not webhook_url:
|
||
return jsonify({
|
||
"success": False,
|
||
"configured": False,
|
||
"message": "N8N_APPROVED_WEBHOOK_URL is not set in your .env file."
|
||
}), 400
|
||
|
||
test_payload = {
|
||
"event": "test_connection",
|
||
"message": "Test webhook event from Pharmacy Approval Portal. Your n8n workflow is connected successfully!",
|
||
"timestamp": datetime.now(ZoneInfo("Asia/Kolkata")).isoformat() if "ZoneInfo" in globals() else datetime.utcnow().isoformat(),
|
||
"invoice_data": {
|
||
"invoice_number": "TEST-INV-001",
|
||
"invoice_date": "13-11-2026",
|
||
"supplier_name": "ABC PHARMACEUTICALS",
|
||
"status": "approved",
|
||
"items": [
|
||
{
|
||
"description": "SAMPLE MEDICINE 500MG",
|
||
"item_code": "TEST-CODE-01",
|
||
"item_code_source": "pharmacy_approval",
|
||
"quantity": 10,
|
||
"unit_price": 50.0,
|
||
"total_price": 500.0,
|
||
"mrp": 65.0,
|
||
"batch": "BT123",
|
||
"expiry_date": "31-12-2027",
|
||
"hsn_sac": "30049099",
|
||
"gst_percentage": 12.0
|
||
}
|
||
],
|
||
"total_amount": 560.0
|
||
}
|
||
}
|
||
|
||
try:
|
||
headers = {"Content-Type": "application/json"}
|
||
secret = os.getenv("N8N_WEBHOOK_SECRET", "").strip()
|
||
if secret:
|
||
headers["X-Webhook-Secret"] = secret
|
||
|
||
resp = _http_requests.post(webhook_url, json=test_payload, headers=headers, timeout=10)
|
||
return jsonify({
|
||
"success": resp.status_code < 400,
|
||
"configured": True,
|
||
"status_code": resp.status_code,
|
||
"webhook_url": webhook_url,
|
||
"response": resp.text[:300]
|
||
}), 200
|
||
except Exception as e:
|
||
return jsonify({
|
||
"success": False,
|
||
"configured": True,
|
||
"webhook_url": webhook_url,
|
||
"error": str(e)
|
||
}), 500
|
||
|
||
|
||
@app.route("/api/extraction/<int:extraction_id>/item-codes", methods=["PUT"])
|
||
@app.route("/api/pharmacy/extraction/<int:extraction_id>/item-codes", methods=["PUT"])
|
||
@pharmacy_or_admin_required
|
||
def update_item_codes(extraction_id):
|
||
"""Pharmacy staff approves/assigns item codes, updates original extraction JSON,
|
||
runs remaining invoice validation/processing workflow, and updates DB status."""
|
||
payload = request.get_json(silent=True) or {}
|
||
updates = payload.get("item_codes")
|
||
if not isinstance(updates, list) or len(updates) == 0:
|
||
return jsonify({"success": False, "error": "item_codes must be a non-empty list"}), 400
|
||
|
||
conn = None
|
||
cursor = None
|
||
prev_autocommit = None
|
||
try:
|
||
conn = get_db_connection()
|
||
if hasattr(conn, "autocommit"):
|
||
try:
|
||
prev_autocommit = conn.autocommit
|
||
conn.autocommit = False
|
||
except Exception:
|
||
prev_autocommit = None
|
||
|
||
cursor = conn.cursor(dictionary=True)
|
||
cursor.execute(
|
||
"SELECT id, invoice_id, user_id, extraction_type, extracted_data, status FROM extraction_history WHERE id = %s",
|
||
(extraction_id,)
|
||
)
|
||
row = cursor.fetchone()
|
||
if not row:
|
||
return jsonify({"success": False, "error": "Extraction not found"}), 404
|
||
|
||
raw_data = row.get("extracted_data")
|
||
if not raw_data:
|
||
return jsonify({"success": False, "error": "Extraction has no stored JSON data"}), 400
|
||
|
||
data = json.loads(raw_data)
|
||
items = data.get("items")
|
||
if not isinstance(items, list) or len(items) == 0:
|
||
return jsonify({"success": False, "error": "Extraction has no line items"}), 400
|
||
|
||
changed = 0
|
||
new_codes_added = 0
|
||
approved_drugs = [] # list of (new_code, desc, norm_desc)
|
||
pending_csv_appends = [] # list of (new_code, desc)
|
||
|
||
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)):
|
||
return jsonify({"success": False, "error": f"Invalid line item index: {index!r}"}), 400
|
||
|
||
item = items[index]
|
||
if not isinstance(item, dict):
|
||
continue
|
||
|
||
new_code = str(update.get("item_code") or "").strip().upper()
|
||
if len(new_code) > 50:
|
||
return jsonify({"success": False, "error": "Item code too long (max 50 characters)"}), 400
|
||
if not new_code and not payload.get("allow_clear"):
|
||
return jsonify({"success": False, "error": "Item code cannot be empty for approval"}), 400
|
||
|
||
desc = str(item.get("description") or item.get("item_name") or "").strip()
|
||
|
||
item["item_code"] = new_code
|
||
if new_code:
|
||
item["item_code_source"] = "pharmacy_approval"
|
||
item["in_csv"] = True
|
||
norm = icm.normalize_drug_name(desc) or desc.lower()
|
||
approved_drugs.append((new_code, desc, norm))
|
||
|
||
if icm.extract_item_code_from_drug_list(desc) != new_code:
|
||
pending_csv_appends.append((new_code, desc or new_code))
|
||
new_codes_added += 1
|
||
else:
|
||
item["item_code_source"] = "not_found"
|
||
item["in_csv"] = False
|
||
|
||
changed += 1
|
||
|
||
if changed == 0:
|
||
return jsonify({"success": False, "error": "No valid item code updates provided"}), 400
|
||
|
||
# Apply approved code(s) to any duplicate/other batch lines on the SAME invoice too
|
||
total_occurrences_updated = changed
|
||
if approved_drugs:
|
||
for oidx, oit in enumerate(items):
|
||
if not isinstance(oit, dict):
|
||
continue
|
||
ocode = str(oit.get("item_code") or "").strip().upper()
|
||
if ocode and (icm.code_in_catalog(ocode) or ocode in {c for c, _, _ in approved_drugs}):
|
||
continue
|
||
odesc = str(oit.get("description") or oit.get("item_name") or "").strip()
|
||
if not odesc:
|
||
continue
|
||
onorm = icm.normalize_drug_name(odesc) or odesc.lower()
|
||
for (acode, adesc, anorm) in approved_drugs:
|
||
if onorm == anorm or odesc.lower() == adesc.lower():
|
||
oit["item_code"] = acode
|
||
oit["in_csv"] = True
|
||
oit["item_code_source"] = "pharmacy_approval"
|
||
total_occurrences_updated += 1
|
||
break
|
||
|
||
# Run remaining invoice validations and post-processing on the updated extraction data
|
||
approver_identity = session.get("user") or session.get("username") or "pharmacy"
|
||
approver_user_id = session.get("user_id")
|
||
staged_valid_codes = {acode for (acode, _, _) in approved_drugs}
|
||
|
||
primary_result = validate_and_process_invoice(
|
||
data,
|
||
valid_extra_codes=staged_valid_codes,
|
||
approved_by=approver_identity,
|
||
)
|
||
|
||
if not primary_result["ok"]:
|
||
conn.rollback()
|
||
err_detail = "; ".join(primary_result["validation_errors"])
|
||
return jsonify({
|
||
"success": False,
|
||
"status": "validation_failed",
|
||
"validation_status": "failed",
|
||
"validation_errors": primary_result["validation_errors"],
|
||
"error": f"Invoice validation failed; changes rolled back: {err_detail}",
|
||
}), 422
|
||
|
||
now_dt = datetime.now()
|
||
new_status = primary_result["status"]
|
||
val_status = primary_result["validation_status"]
|
||
final_primary_data = primary_result["processed_data"]
|
||
|
||
# Update existing extraction_history record (never create duplicate invoice rows)
|
||
cursor.execute(
|
||
"""
|
||
UPDATE extraction_history
|
||
SET extracted_data = %s,
|
||
status = %s,
|
||
validation_status = %s,
|
||
validation_errors = NULL,
|
||
approved_by = %s,
|
||
approved_at = %s,
|
||
processed_at = %s
|
||
WHERE id = %s
|
||
""",
|
||
(
|
||
json.dumps(final_primary_data),
|
||
new_status,
|
||
val_status,
|
||
approver_user_id if new_status == "approved" else None,
|
||
now_dt if new_status == "approved" else None,
|
||
now_dt if new_status == "approved" else None,
|
||
extraction_id,
|
||
),
|
||
)
|
||
|
||
completed_invoices = [extraction_id] if new_status == "approved" else []
|
||
completed_invoices_data = []
|
||
propagated_invoices = []
|
||
|
||
# AUTO-PROPAGATE: update all other invoices with the same drug name and run remaining processing
|
||
if approved_drugs:
|
||
cursor.execute(
|
||
"""
|
||
SELECT id, invoice_id, extracted_data, status FROM extraction_history
|
||
WHERE extraction_type = 'invoice' AND extracted_data IS NOT NULL AND id != %s
|
||
""",
|
||
(extraction_id,),
|
||
)
|
||
other_rows = cursor.fetchall()
|
||
for orow in other_rows:
|
||
try:
|
||
odata = json.loads(orow["extracted_data"])
|
||
if not isinstance(odata, dict):
|
||
continue
|
||
oitems = odata.get("items", [])
|
||
ochanged = False
|
||
for oit in oitems:
|
||
if not isinstance(oit, dict):
|
||
continue
|
||
ocode = str(oit.get("item_code") or "").strip().upper()
|
||
if ocode and (icm.code_in_catalog(ocode) or ocode in staged_valid_codes):
|
||
continue
|
||
odesc = str(oit.get("description") or oit.get("item_name") or "").strip()
|
||
if not odesc:
|
||
continue
|
||
onorm = icm.normalize_drug_name(odesc) or odesc.lower()
|
||
for (acode, adesc, anorm) in approved_drugs:
|
||
if onorm == anorm or odesc.lower() == adesc.lower():
|
||
oit["item_code"] = acode
|
||
oit["in_csv"] = True
|
||
oit["item_code_source"] = "pharmacy_approval"
|
||
ochanged = True
|
||
total_occurrences_updated += 1
|
||
break
|
||
if ochanged:
|
||
ores = validate_and_process_invoice(
|
||
odata,
|
||
valid_extra_codes=staged_valid_codes,
|
||
approved_by=approver_identity,
|
||
)
|
||
if ores["ok"]:
|
||
ostatus = ores["status"]
|
||
oval_status = ores["validation_status"]
|
||
cursor.execute(
|
||
"""
|
||
UPDATE extraction_history
|
||
SET extracted_data = %s,
|
||
status = %s,
|
||
validation_status = %s,
|
||
validation_errors = NULL,
|
||
approved_by = %s,
|
||
approved_at = %s,
|
||
processed_at = %s
|
||
WHERE id = %s
|
||
""",
|
||
(
|
||
json.dumps(ores["processed_data"]),
|
||
ostatus,
|
||
oval_status,
|
||
approver_user_id if ostatus == "approved" else None,
|
||
now_dt if ostatus == "approved" else None,
|
||
now_dt if ostatus == "approved" else None,
|
||
orow["id"],
|
||
),
|
||
)
|
||
propagated_invoices.append(orow["id"])
|
||
if ostatus == "approved":
|
||
completed_invoices.append(orow["id"])
|
||
completed_invoices_data.append((orow["id"], ores["processed_data"]))
|
||
else:
|
||
logging.warning(
|
||
f"Skipped auto-propagation completion on invoice {orow['id']}: {ores['validation_errors']}"
|
||
)
|
||
except Exception as prop_err:
|
||
logging.warning(f"Error propagating to extraction {orow.get('id')}: {prop_err}")
|
||
continue
|
||
|
||
conn.commit()
|
||
|
||
# Persist newly approved mappings to drug_list.csv & hot-reload catalog AFTER DB commit
|
||
for code_val, desc_val in pending_csv_appends:
|
||
icm.append_to_drug_catalog(code_val, desc_val)
|
||
|
||
# Dispatch newly approved invoice(s) to n8n webhook so n8n can store into external database
|
||
webhook_dispatches = []
|
||
approver_display = session.get("pharmacy_user") or session.get("user") or approver_identity or "pharmacy"
|
||
if new_status == "approved":
|
||
w_res = dispatch_n8n_approval_webhook(
|
||
extraction_id=extraction_id,
|
||
invoice_data=final_primary_data,
|
||
approver_username=approver_display,
|
||
)
|
||
webhook_dispatches.append({"extraction_id": extraction_id, **w_res})
|
||
|
||
for comp_id, comp_data in completed_invoices_data:
|
||
w_res = dispatch_n8n_approval_webhook(
|
||
extraction_id=comp_id,
|
||
invoice_data=comp_data,
|
||
approver_username=approver_display,
|
||
)
|
||
webhook_dispatches.append({"extraction_id": comp_id, **w_res})
|
||
|
||
first_drug = approved_drugs[0][1] if approved_drugs else ""
|
||
first_code = approved_drugs[0][0] if approved_drugs else ""
|
||
remaining_count = len(primary_result["missing_item_indices"])
|
||
if new_status == "approved":
|
||
msg = (
|
||
f"Item code '{first_code}' approved for '{first_drug}'. "
|
||
f"Original extraction updated, validations passed, and invoice marked approved (completed)."
|
||
)
|
||
else:
|
||
msg = (
|
||
f"Item code '{first_code}' saved to invoice extraction data and catalog "
|
||
f"({remaining_count} other item(s) on this invoice still await approval)."
|
||
)
|
||
|
||
return jsonify({
|
||
"success": True,
|
||
"extraction_id": extraction_id,
|
||
"invoice_id": final_primary_data.get("invoice_id") or row.get("invoice_id"),
|
||
"invoice_status": new_status,
|
||
"validation_status": val_status,
|
||
"remaining_missing_items": remaining_count,
|
||
"consistency_warnings": primary_result["consistency_warnings"],
|
||
"updated": changed,
|
||
"total_occurrences_updated": total_occurrences_updated,
|
||
"propagated_invoices": propagated_invoices,
|
||
"completed_invoices": completed_invoices,
|
||
"n8n_webhook": webhook_dispatches,
|
||
"approved_drug": first_drug,
|
||
"approved_code": first_code,
|
||
"new_codes_added": new_codes_added,
|
||
"data": final_primary_data,
|
||
"message": msg,
|
||
}), 200
|
||
|
||
except Exception as e:
|
||
logging.error(f"Error in update_item_codes: {e}", exc_info=True)
|
||
if conn:
|
||
try:
|
||
conn.rollback()
|
||
except Exception:
|
||
pass
|
||
return jsonify({"success": False, "error": str(e)}), 500
|
||
finally:
|
||
if cursor:
|
||
try:
|
||
cursor.close()
|
||
except Exception:
|
||
pass
|
||
if conn:
|
||
if prev_autocommit is not None and hasattr(conn, "autocommit"):
|
||
try:
|
||
conn.autocommit = prev_autocommit
|
||
except Exception:
|
||
pass
|
||
try:
|
||
conn.close()
|
||
except Exception:
|
||
pass
|
||
|
||
|
||
@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 WHERE category IS NOT NULL AND category != "" 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."""
|
||
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()
|
||
try:
|
||
icm.append_to_drug_catalog(item_code, name)
|
||
except Exception:
|
||
pass
|
||
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()
|
||
try:
|
||
icm.update_drug_catalog_entry(existing['item_code'], existing['name'], item_code, name)
|
||
except Exception:
|
||
pass
|
||
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, item_code, name FROM item_codes WHERE id = ?', (catalog_id,))
|
||
row = cursor.fetchone()
|
||
if not row:
|
||
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()
|
||
try:
|
||
icm.delete_drug_catalog_entry(row['item_code'], name=row['name'])
|
||
except Exception:
|
||
pass
|
||
return jsonify({'success': True, 'message': 'Item code deleted'}), 200
|
||
|
||
|
||
@app.route("/api/catalog/edit", methods=["POST", "PUT"])
|
||
@app.route("/api/catalog/update", methods=["POST", "PUT"])
|
||
@login_required
|
||
def catalog_edit_entry():
|
||
data = request.get_json(silent=True) or {}
|
||
old_code = str(data.get("old_item_code") or data.get("item_code") or "").strip().upper()
|
||
old_name = str(data.get("old_name") or data.get("name") or "").strip()
|
||
new_code = str(data.get("new_item_code") or data.get("item_code") or "").strip().upper()
|
||
new_name = str(data.get("new_name") or data.get("name") or "").strip()
|
||
|
||
if not old_code:
|
||
return jsonify({"success": False, "error": "Existing item code is required"}), 400
|
||
if not new_code or not new_name:
|
||
return jsonify({"success": False, "error": "New item code and drug name cannot be empty"}), 400
|
||
|
||
conn = get_db()
|
||
cursor = conn.cursor()
|
||
cursor.execute("UPDATE item_codes SET item_code = ?, name = ?, updated_at = CURRENT_TIMESTAMP WHERE item_code = ?", (new_code, new_name, old_code))
|
||
conn.commit()
|
||
conn.close()
|
||
|
||
try:
|
||
icm.update_drug_catalog_entry(old_code, old_name, new_code, new_name)
|
||
except Exception:
|
||
pass
|
||
|
||
return jsonify({
|
||
"success": True,
|
||
"message": f"Catalog entry updated to '{new_code}' - '{new_name}'",
|
||
"data": {"item_code": new_code, "name": new_name}
|
||
}), 200
|
||
|
||
|
||
@app.route("/api/catalog/delete", methods=["POST", "DELETE"])
|
||
@login_required
|
||
def catalog_delete_entry():
|
||
data = request.get_json(silent=True) or {}
|
||
item_code = str(data.get("item_code") or "").strip().upper()
|
||
name = str(data.get("name") or "").strip()
|
||
|
||
if not item_code:
|
||
return jsonify({"success": False, "error": "Item code is required"}), 400
|
||
|
||
conn = get_db()
|
||
cursor = conn.cursor()
|
||
cursor.execute("DELETE FROM item_codes WHERE item_code = ?", (item_code,))
|
||
conn.commit()
|
||
conn.close()
|
||
|
||
try:
|
||
icm.delete_drug_catalog_entry(item_code, name=name)
|
||
except Exception:
|
||
pass
|
||
|
||
return jsonify({
|
||
"success": True,
|
||
"message": f"Catalog entry '{item_code}' deleted successfully"
|
||
}), 200
|
||
|
||
|
||
@app.route("/api/catalog/add", methods=["POST"])
|
||
@login_required
|
||
def catalog_add_entry():
|
||
data = request.get_json(silent=True) or {}
|
||
item_code = str(data.get("item_code") or "").strip().upper()
|
||
name = str(data.get("name") or "").strip()
|
||
|
||
if not item_code or not name:
|
||
return jsonify({"success": False, "error": "Item code and drug name are required"}), 400
|
||
|
||
try:
|
||
conn = get_db()
|
||
cursor = conn.cursor()
|
||
cursor.execute("INSERT OR REPLACE INTO item_codes (item_code, name) VALUES (?, ?)", (item_code, name))
|
||
conn.commit()
|
||
conn.close()
|
||
except Exception:
|
||
pass
|
||
|
||
try:
|
||
icm.append_to_drug_catalog(item_code, name)
|
||
except Exception:
|
||
pass
|
||
|
||
return jsonify({
|
||
"success": True,
|
||
"message": f"Added '{item_code}' - '{name}' to drug catalog",
|
||
"data": {"item_code": item_code, "name": name}
|
||
}), 201
|
||
|
||
return jsonify({
|
||
"success": True,
|
||
"message": f"Added '{item_code}' - '{name}' to drug catalog",
|
||
"data": {"item_code": item_code, "name": name}
|
||
}), 201
|
||
|
||
|
||
# ============================================================================
|
||
# LOCAL GRN SIMULATOR — Mirrors: https://mapp.dmhospital.org/dmhApiRef/grn/createGRN.php
|
||
#
|
||
# Used for local n8n testing without hitting the production DMH Hospital API.
|
||
# Set n8n's "GRN: Create Record in Hospital" HTTP node URL to:
|
||
# http://localhost:<PORT>/dmhApiRef/grn/createGRN.php
|
||
# and Header x-api-key to: nirajAi26@DMH (same as production)
|
||
# ============================================================================
|
||
|
||
DMH_LOCAL_API_KEY = "nirajAi26@DMH"
|
||
_grn_counter_lock = __import__("threading").Lock()
|
||
_grn_sequence = [0] # mutable for closure
|
||
|
||
def _next_grn_no():
|
||
with _grn_counter_lock:
|
||
_grn_sequence[0] += 1
|
||
return f"LOCAL-GRN-{datetime.now(ZoneInfo('Asia/Kolkata')).strftime('%Y%m%d')}-{_grn_sequence[0]:04d}"
|
||
|
||
def _safe_num(val, default=0):
|
||
if val is None or val == "":
|
||
return default
|
||
try:
|
||
return float(str(val).replace(",", ""))
|
||
except (ValueError, TypeError):
|
||
return default
|
||
|
||
|
||
@app.route("/dmhApiRef/grn/createGRN.php", methods=["POST"])
|
||
@app.route("/dmhApiRef/grn/createGRN", methods=["POST"])
|
||
def local_grn_create():
|
||
"""
|
||
Local simulator for DMH Hospital GRN API.
|
||
Accepts the same payload format as the production endpoint.
|
||
Stores the GRN into the `grn_records` table in the `invoice` MySQL database.
|
||
Returns the same response structure as the real DMH API.
|
||
"""
|
||
# ── API Key check ────────────────────────────────────────────────────────
|
||
api_key = request.headers.get("x-api-key") or request.headers.get("X-API-Key") or ""
|
||
if api_key.strip() != DMH_LOCAL_API_KEY:
|
||
logging.warning(f"[GRN Local] Invalid API key: '{api_key}'")
|
||
return jsonify({
|
||
"status": 1,
|
||
"message": "Unauthorized: Invalid x-api-key",
|
||
"data": []
|
||
}), 401
|
||
|
||
# ── Parse payload ────────────────────────────────────────────────────────
|
||
payload = request.get_json(silent=True)
|
||
if not payload:
|
||
payload = request.form.to_dict()
|
||
if not payload:
|
||
return jsonify({
|
||
"status": 1,
|
||
"message": "Bad Request: No JSON payload received",
|
||
"data": []
|
||
}), 400
|
||
|
||
invoice_id = str(payload.get("invoice_id") or "").strip()
|
||
invoice_number = str(payload.get("invoice_number") or "").strip()
|
||
invoice_date = str(payload.get("invoice_date") or "").strip()
|
||
due_date = str(payload.get("due_date") or "") or None
|
||
customer_name = str(payload.get("customer_name") or "").strip()
|
||
customer_gstin = str(payload.get("customer_gstin") or "").strip()
|
||
seller_name = str(payload.get("seller_name") or "").strip()
|
||
seller_gstin = str(payload.get("seller_gstin") or "").strip()
|
||
currency_code = str(payload.get("currency_code") or "INR").strip()
|
||
po_number = str(payload.get("PO_number") or payload.get("po_number") or "").strip()
|
||
dc_date = payload.get("dc_date") or payload.get("DC_date") or None
|
||
dc_number = payload.get("dc_number") or payload.get("DC_number") or None
|
||
items = payload.get("items", [])
|
||
|
||
# ── Validations (mirror real DMH API) ───────────────────────────────────
|
||
validation_errors = []
|
||
|
||
if not invoice_id:
|
||
validation_errors.append("invoice_id")
|
||
if not invoice_number:
|
||
validation_errors.append("invoice_number")
|
||
if not po_number:
|
||
validation_errors.append("PO_number")
|
||
if not seller_gstin:
|
||
validation_errors.append("seller_gstin")
|
||
|
||
if not isinstance(items, list) or len(items) == 0:
|
||
return jsonify({
|
||
"status": 1,
|
||
"message": "The invoice must contain at least one valid item.",
|
||
"data": [{"missingItmesCodes": [], "invalidItmes": []}]
|
||
}), 200
|
||
|
||
# Validate item_codes
|
||
missing_codes = []
|
||
invalid_items = []
|
||
valid_item_count = 0
|
||
|
||
for it in items:
|
||
if not isinstance(it, dict):
|
||
continue
|
||
code = str(it.get("item_code") or "").strip()
|
||
if not code:
|
||
missing_codes.append(it.get("description", ""))
|
||
else:
|
||
valid_item_count += 1
|
||
|
||
if valid_item_count == 0:
|
||
return jsonify({
|
||
"status": 1,
|
||
"message": "The invoice must contain at least one valid item.",
|
||
"data": [{"missingItmesCodes": missing_codes, "invalidItmes": invalid_items}]
|
||
}), 200
|
||
|
||
if validation_errors:
|
||
return jsonify({
|
||
"status": 1,
|
||
"message": f"Listed fields are missing: {', '.join(validation_errors)}",
|
||
"data": [{"missingItmesCodes": missing_codes, "invalidItmes": invalid_items}]
|
||
}), 200
|
||
|
||
# ── Generate GRN number ──────────────────────────────────────────────────
|
||
grn_no = _next_grn_no()
|
||
grn_master_id = int(datetime.now().timestamp() * 1000) % 100000 # pseudo unique int
|
||
|
||
# ── Insert into grn_records ──────────────────────────────────────────────
|
||
conn = None
|
||
try:
|
||
conn = get_db_connection()
|
||
cur = conn.cursor()
|
||
|
||
# Duplicate invoice check
|
||
cur.execute("SELECT id FROM grn_records WHERE invoice_id = %s AND invoice_number = %s LIMIT 1",
|
||
(invoice_id, invoice_number))
|
||
existing = cur.fetchone()
|
||
if existing:
|
||
cur.close()
|
||
conn.close()
|
||
return jsonify({
|
||
"status": 1,
|
||
"message": "Record Already Exist for this Invoice.",
|
||
"data": [{"missingItmesCodes": [], "invalidItmes": []}]
|
||
}), 200
|
||
|
||
cur.execute(
|
||
"""
|
||
INSERT INTO grn_records
|
||
(grn_no, grn_master_id, invoice_id, invoice_number, invoice_date, due_date,
|
||
customer_name, customer_gstin, seller_name, seller_gstin, currency_code,
|
||
po_number, dc_date, dc_number, invoice_amount, round_off,
|
||
total_gst_rate, total_quantity, total_cgst_rate, total_cgst_amount,
|
||
total_sgst_rate, total_sgst_amount, total_igst_rate, total_igst_amount,
|
||
total_gst_amount, items_json, items_inserted, source, api_key_used, status)
|
||
VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)
|
||
""",
|
||
(
|
||
grn_no, grn_master_id, invoice_id, invoice_number, invoice_date, due_date,
|
||
customer_name, customer_gstin, seller_name, seller_gstin, currency_code,
|
||
po_number, str(dc_date) if dc_date else None,
|
||
str(dc_number) if dc_number else None,
|
||
_safe_num(payload.get("invoice_amount")),
|
||
_safe_num(payload.get("round_off")),
|
||
_safe_num(payload.get("total_gst_rate")),
|
||
_safe_num(payload.get("total_quantity")),
|
||
_safe_num(payload.get("total_cgst_rate")),
|
||
_safe_num(payload.get("total_cgst_amount")),
|
||
_safe_num(payload.get("total_sgst_rate")),
|
||
_safe_num(payload.get("total_sgst_amount")),
|
||
_safe_num(payload.get("total_igst_rate")),
|
||
_safe_num(payload.get("total_igst_amount")),
|
||
_safe_num(payload.get("total_gst_amount")),
|
||
json.dumps(items),
|
||
valid_item_count,
|
||
"n8n_local",
|
||
api_key,
|
||
"created",
|
||
)
|
||
)
|
||
conn.commit()
|
||
logging.info(f"[GRN Local] Created GRN {grn_no} for invoice {invoice_number} ({invoice_id})")
|
||
|
||
return jsonify({
|
||
"status": 0,
|
||
"message": "GRN Created Successfully",
|
||
"data": [{
|
||
"status": 0,
|
||
"grn_no": grn_no,
|
||
"grn_master_id": grn_master_id,
|
||
"invoice_no": invoice_number,
|
||
"invoice_id": invoice_id,
|
||
"vendor_id": grn_master_id % 999 + 1,
|
||
"items_inserted": valid_item_count,
|
||
"message": "GRN Created Successfully"
|
||
}]
|
||
}), 200
|
||
|
||
except Exception as e:
|
||
logging.error(f"[GRN Local] DB Error: {e}", exc_info=True)
|
||
if conn:
|
||
try:
|
||
conn.rollback()
|
||
except Exception:
|
||
pass
|
||
return jsonify({
|
||
"status": 1,
|
||
"message": f"Internal server error: {str(e)[:200]}",
|
||
"data": []
|
||
}), 500
|
||
finally:
|
||
if conn:
|
||
try:
|
||
conn.close()
|
||
except Exception:
|
||
pass
|
||
|
||
|
||
@app.route("/grn/records", methods=["GET"])
|
||
def grn_records_view():
|
||
"""View all locally created GRN records — for local testing & verification."""
|
||
if "user" not in session and "pharmacy_user" not in session:
|
||
return redirect(url_for("login"))
|
||
|
||
try:
|
||
conn = get_db_connection()
|
||
cur = conn.cursor(dictionary=True)
|
||
cur.execute(
|
||
"""
|
||
SELECT id, grn_no, grn_master_id, invoice_id, invoice_number, invoice_date,
|
||
seller_name, seller_gstin, customer_name, po_number, invoice_amount,
|
||
total_gst_amount, items_inserted, source, received_at, status
|
||
FROM grn_records
|
||
ORDER BY received_at DESC
|
||
LIMIT 200
|
||
"""
|
||
)
|
||
records = cur.fetchall()
|
||
cur.close()
|
||
conn.close()
|
||
return render_template("grn_records.html", records=records)
|
||
except Exception as e:
|
||
return jsonify({"error": str(e)}), 500
|
||
|
||
|
||
@app.route("/grn/records/<int:grn_id>", methods=["GET"])
|
||
def grn_record_detail(grn_id):
|
||
"""View full JSON detail of a single GRN record."""
|
||
if "user" not in session and "pharmacy_user" not in session:
|
||
return redirect(url_for("login"))
|
||
|
||
try:
|
||
conn = get_db_connection()
|
||
cur = conn.cursor(dictionary=True)
|
||
cur.execute("SELECT * FROM grn_records WHERE id = %s", (grn_id,))
|
||
record = cur.fetchone()
|
||
cur.close()
|
||
conn.close()
|
||
if not record:
|
||
return jsonify({"error": "Record not found"}), 404
|
||
if record.get("items_json"):
|
||
try:
|
||
record["items"] = json.loads(record["items_json"])
|
||
except Exception:
|
||
record["items"] = []
|
||
return jsonify(record), 200
|
||
except Exception as e:
|
||
return jsonify({"error": str(e)}), 500
|
||
|
||
|
||
@app.route("/api/grn/records", methods=["GET"])
|
||
def api_grn_records():
|
||
"""JSON API: list GRN records with optional filters."""
|
||
try:
|
||
conn = get_db_connection()
|
||
cur = conn.cursor(dictionary=True)
|
||
limit = min(int(request.args.get("limit", 50)), 500)
|
||
invoice_id = request.args.get("invoice_id", "").strip()
|
||
status_filter = request.args.get("status", "").strip()
|
||
|
||
query = "SELECT * FROM grn_records WHERE 1=1"
|
||
params = []
|
||
if invoice_id:
|
||
query += " AND invoice_id = %s"
|
||
params.append(invoice_id)
|
||
if status_filter:
|
||
query += " AND status = %s"
|
||
params.append(status_filter)
|
||
query += " ORDER BY received_at DESC LIMIT %s"
|
||
params.append(limit)
|
||
|
||
cur.execute(query, params)
|
||
records = cur.fetchall()
|
||
cur.close()
|
||
conn.close()
|
||
|
||
for r in records:
|
||
if r.get("items_json"):
|
||
try:
|
||
r["items"] = json.loads(r["items_json"])
|
||
except Exception:
|
||
r["items"] = []
|
||
del r["items_json"]
|
||
if r.get("received_at"):
|
||
r["received_at"] = str(r["received_at"])
|
||
|
||
return jsonify({"success": True, "count": len(records), "records": records}), 200
|
||
except Exception as e:
|
||
return jsonify({"success": False, "error": str(e)}), 500
|
||
|
||
|
||
@app.route("/download/n8n-workflow", methods=["GET"])
|
||
def download_n8n_workflow():
|
||
workflow_path = os.path.join(os.path.dirname(__file__), "n8n_invoice_automation_workflow.json")
|
||
if not os.path.exists(workflow_path):
|
||
return jsonify({"error": "Workflow file not found"}), 404
|
||
return send_file(
|
||
workflow_path,
|
||
as_attachment=True,
|
||
download_name="Invoice_Automation_DMH_LOCAL_TEST.json",
|
||
mimetype="application/json",
|
||
)
|
||
|
||
|
||
if __name__ == "__main__":
|
||
port = int(os.getenv("PORT", 8080))
|
||
try:
|
||
app.run(host="0.0.0.0", port=port, debug=True)
|
||
except OSError:
|
||
print(f"Port {port} busy, attempting fallback port 5000...")
|
||
app.run(host="0.0.0.0", port=5000, debug=True)
|
||
|