diff --git a/Seller_GSTIN.xlsx b/Seller_GSTIN.xlsx index 5252ff3..3c160bb 100644 Binary files a/Seller_GSTIN.xlsx and b/Seller_GSTIN.xlsx differ diff --git a/app.py b/app.py index 1c207fc..dd37808 100644 --- a/app.py +++ b/app.py @@ -1,3 +1,6 @@ +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'): @@ -16,6 +19,7 @@ from free_item_splitter import split_free_items, get_free_item_stats # 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. @@ -161,6 +165,7 @@ def normalize_text(value): app = Flask(__name__) from zoneinfo import ZoneInfo + # ================================================================ # ✅ VENDOR MASTER & GSTIN LOOKUP — backed by 'Seller_GSTIN.xlsx' # ================================================================ @@ -174,10 +179,12 @@ 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.7-plus") +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. @@ -210,6 +217,7 @@ def _qwen_call(system_prompt: str, user_text: str, image_b64: str, ], } 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() @@ -274,7 +282,7 @@ MYSQL_CONFIG = { "pool_reset_session": True, "autocommit": True, "buffered": True, - "connection_timeout": 30, + "connection_timeout": 3, } # Connection Pool @@ -345,6 +353,7 @@ class SQLiteCursorWrapper: 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) @@ -365,9 +374,164 @@ class SQLiteConnectionWrapper: 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 + 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) @@ -375,7 +539,8 @@ def get_db_connection(): cnx.ping(reconnect=True, attempts=3, delay=1) return cnx except Exception as e: - print(f"MySQL unavailable ({e}). Using SQLite fallback database ('invoice.db').") + _last_mysql_fail_time = now + cnxpool = None return SQLiteConnectionWrapper('invoice.db') def fix_existing_limits(): @@ -439,11 +604,21 @@ def init_db(): """ ) - # ── Add billing columns to existing table if they don't exist yet ── + # ── Add missing columns to extraction_history if they don't exist yet ── for _col, _defn in [ - ("input_tokens", "INT DEFAULT 0"), - ("output_tokens", "INT DEFAULT 0"), - ("cost_usd", "DECIMAL(10,6) DEFAULT 0.000000"), + ("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( @@ -483,7 +658,7 @@ def init_db(): ) admin_user = cursor.fetchone() if not admin_user: - cursor.execute( + cursor.execute( """ INSERT INTO users (username, email, password, role) VALUES ( @@ -492,12 +667,16 @@ def init_db(): '$2b$12$W9ObhLPinBHdnkX1XK6.U.Ub5mgx33abZtEY7xOVfHz5CMnM5tdWm', 'admin' ) - """ - ) - conn.commit() + """ + ) + conn.commit() + cursor.close() + conn.close() - 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 @@ -507,6 +686,35 @@ 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 @@ -673,7 +881,7 @@ def generate_invoice_id(conn, invoice_source): -def extract_invoice_fields(file_path, invoice_source="electronic", is_dmh=False): +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) @@ -1062,18 +1270,14 @@ def extract_invoice_fields(file_path, invoice_source="electronic", is_dmh=False) all_pages_data = deduplicated_pages # =============================================================== - # 🔥 FEATURE 2 — PO number required gate (DMH ONLY) + # 🔥 FEATURE 2 — PO number check (DMH) # # After deduplication, check whether at least one page carries a - # non-empty PO number. If not, reject the whole invoice and - # return a clear error — do NOT proceed with extraction. - # - # This logic runs ONLY for DMH users (is_dmh=True). - # Regular users are not affected and their invoices are processed - # regardless of whether a PO number is present. + # 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] Validating PO number requirement...", flush=True) + print("📋 [DMH] Checking PO number...", flush=True) invoice_po = None for page in all_pages_data: po = _normalise_po(page.get("PO_number")) @@ -1102,13 +1306,13 @@ def extract_invoice_fields(file_path, invoice_source="electronic", is_dmh=False) if invoice_po: break - if not invoice_po: - print("❌ [DMH] Invoice rejected — no PO number found on document.", flush=True) - return { - "error": "Invoice rejected: PO number is missing. Only invoices with a valid PO number are processed for DMH." - } - - print(f"✅ [DMH] PO number confirmed: {invoice_po}", flush=True) + 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) # =============================================================== @@ -1747,6 +1951,12 @@ def extract_invoice_fields(file_path, invoice_source="electronic", is_dmh=False) _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) @@ -1789,23 +1999,75 @@ def process_invoice(): 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") + _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 FROM users u JOIN api_keys ak ON u.id = ak.user_id WHERE ak.api_key = %s", + "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 - extracted_data = extract_invoice_fields(filepath, invoice_source, is_dmh=_is_dmh) + 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 @@ -2001,7 +2263,11 @@ def some_api_endpoint(): @app.route("/", methods=["GET"]) def index(): - if "user" in session: + 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 @@ -2313,14 +2579,37 @@ def login(): 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") - if user["role"] == "dmh": + 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")) @@ -2328,19 +2617,312 @@ def login(): flash("Invalid login details", "error") return render_template("applogin.html") -import uuid +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["invoice"] + 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 @@ -2356,33 +2938,43 @@ def upload_invoice(): if not extracted_data: extracted_data = {} - # 4️⃣ Store in DB + # 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() + conn = get_db_connection() cursor = conn.cursor() cursor.execute( """ INSERT INTO extraction_history - (user_id, timestamp, image_name, pages_extracted, extraction_type, extracted_data) - VALUES (%s, %s, %s, %s, %s, %s) + (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(), + ist_now, image_name, pages_extracted, extraction_type, - extracted_json + extracted_json, + init_status, + init_val_status, + ist_now if init_status == "completed" else None, ), ) - db.commit() + conn.commit() cursor.close() + conn.close() return redirect(url_for("view_history")) import fitz # PyMuPDF @@ -2396,6 +2988,12 @@ 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")) @@ -2490,6 +3088,17 @@ def upload_image(): (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 @@ -2505,15 +3114,18 @@ def upload_image(): file_path, input_tokens, output_tokens, - cost_usd + cost_usd, + status, + validation_status, + processed_at ) - VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s) + VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s) """, ( invoice_id, invoice_source, user["id"], - datetime.now(), + now_dt, original_filename, page_count, doc_type, @@ -2522,10 +3134,19 @@ def upload_image(): _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( @@ -2610,6 +3231,8 @@ def dashboard(): 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 @@ -2856,9 +3479,13 @@ def generate_api_key(): @app.route("/logout") def logout(): - session.pop("user", None) - flash("Logged out successfully!") - return redirect(url_for("index")) + 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"]) @@ -3170,6 +3797,8 @@ 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 @@ -3180,10 +3809,2377 @@ 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/', 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//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//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//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//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//item-codes", methods=["PUT"]) +@app.route("/api/pharmacy/extraction//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/', 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/', 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:/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/", 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) \ No newline at end of file + app.run(host="0.0.0.0", port=5000, debug=True) + \ No newline at end of file diff --git a/automation_dmh_outlook.json b/automation_dmh_outlook.json new file mode 100644 index 0000000..57d4595 --- /dev/null +++ b/automation_dmh_outlook.json @@ -0,0 +1,3997 @@ +{ + "updatedAt": "2026-11-18T10:29:49.476Z", + "createdAt": "2026-09-15T07:46:14.929Z", + "id": "EyAw3kSLbeIEnpyf", + "name": "Invoice Automation-DMH Hospital Final Outlook", + "description": null, + "active": true, + "isArchived": false, + "nodes": [ + { + "parameters": { + "operation": "append", + "documentId": { + "__rl": true, + "value": "=1cwLXlwmCPC7zUVOIQFWwRED4uqF3WZHVagGbBtKyVgQ", + "mode": "id" + }, + "sheetName": { + "__rl": true, + "value": 1691973413, + "mode": "list", + "cachedResultName": "Daily Logs", + "cachedResultUrl": "https://docs.google.com/spreadsheets/d/1cwLXlwmCPC7zUVOIQFWwRED4uqF3WZHVagGbBtKyVgQ/edit#gid=1691973413" + }, + "columns": { + "mappingMode": "defineBelow", + "value": { + "Date": "={{ $json.date }}", + "Time": "={{ $json.time }}", + "Attachment Name": "={{ $json.attachment_name }}", + "Status": "={{ $json.status }}", + "GRN Message ": "={{ $json.grn_message }}", + "Complete Error / Null Values": "={{ $json.complete_error }}" + }, + "matchingColumns": [], + "schema": [ + { + "id": "Sr No.", + "displayName": "Sr No.", + "required": false, + "defaultMatch": false, + "display": true, + "type": "string", + "canBeUsedToMatch": true, + "removed": false + }, + { + "id": "Date", + "displayName": "Date", + "required": false, + "defaultMatch": false, + "display": true, + "type": "string", + "canBeUsedToMatch": true + }, + { + "id": "Time", + "displayName": "Time", + "required": false, + "defaultMatch": false, + "display": true, + "type": "string", + "canBeUsedToMatch": true + }, + { + "id": "Attachment Name", + "displayName": "Attachment Name", + "required": false, + "defaultMatch": false, + "display": true, + "type": "string", + "canBeUsedToMatch": true + }, + { + "id": "Customer Name", + "displayName": "Customer Name", + "required": false, + "defaultMatch": false, + "display": true, + "type": "string", + "canBeUsedToMatch": true + }, + { + "id": "Invoice Amount (₹)", + "displayName": "Invoice Amount (₹)", + "required": false, + "defaultMatch": false, + "display": true, + "type": "string", + "canBeUsedToMatch": true + }, + { + "id": "Invoice ID", + "displayName": "Invoice ID", + "required": false, + "defaultMatch": false, + "display": true, + "type": "string", + "canBeUsedToMatch": true + }, + { + "id": "Seller Name", + "displayName": "Seller Name", + "required": false, + "defaultMatch": false, + "display": true, + "type": "string", + "canBeUsedToMatch": true + }, + { + "id": "Status", + "displayName": "Status", + "required": false, + "defaultMatch": false, + "display": true, + "type": "string", + "canBeUsedToMatch": true + }, + { + "id": "GRN Message ", + "displayName": "GRN Message ", + "required": false, + "defaultMatch": false, + "display": true, + "type": "string", + "canBeUsedToMatch": true + }, + { + "id": "Seller GSTIN", + "displayName": "Seller GSTIN", + "required": false, + "defaultMatch": false, + "display": true, + "type": "string", + "canBeUsedToMatch": true + }, + { + "id": "Free Goods", + "displayName": "Free Goods", + "required": false, + "defaultMatch": false, + "display": true, + "type": "string", + "canBeUsedToMatch": true + }, + { + "id": "Complete Error / Null Values", + "displayName": "Complete Error / Null Values", + "required": false, + "defaultMatch": false, + "display": true, + "type": "string", + "canBeUsedToMatch": true + } + ], + "attemptToConvertTypes": false, + "convertFieldsToString": false + }, + "options": {} + }, + "type": "n8n-nodes-base.googleSheets", + "typeVersion": 4.7, + "position": [ + -1792, + 384 + ], + "id": "1550194a-e54a-4b53-8b77-aa2f3a946d74", + "name": "Append row in sheet1", + "credentials": { + "googleSheetsOAuth2Api": { + "id": "OGnPiaQp3eu9tWvW", + "name": "Google Sheets account" + } + } + }, + { + "parameters": { + "pollTimes": { + "item": [ + { + "mode": "everyMinute" + } + ] + }, + "filters": { + "foldersToInclude": [ + "AQMkADAwATM0MDAAMi1hYzgzLTQxMQAyLTAwAi0wMAoALgAAA3R9Z7-WZCBHqvG_09flPEoBAJRkAPlTP4RNsddkpsHybkoAAAJoYgAAAA==", + "AQMkADAwATM0MDAAMi1hYzgzLTQxMQAyLTAwAi0wMAoALgAAA3R9Z7-WZCBHqvG_09flPEoBAJRkAPlTP4RNsddkpsHybkoAAAJodQAAAA==", + "AQMkADAwATM0MDAAMi1hYzgzLTQxMQAyLTAwAi0wMAoALgAAA3R9Z7-WZCBHqvG_09flPEoBAJRkAPlTP4RNsddkpsHybkoAAAIBFgAAAA==" + ] + }, + "options": { + "downloadAttachments": true + } + }, + "type": "n8n-nodes-base.microsoftOutlookTrigger", + "typeVersion": 1, + "position": [ + -4832, + 1056 + ], + "id": "be7ad802-919e-41d8-bd76-d0291e5640dd", + "name": "Watch New_Invoice Label1", + "credentials": { + "microsoftOutlookOAuth2Api": { + "id": "neYqnH7A2WPe5lTs", + "name": "Microsoft Outlook account" + } + } + }, + { + "parameters": { + "promptType": "define", + "text": "=Email Subject:\n{{$json.subject}}\n\nEmail Body:\n{{$json.bodyPreview || $json.body.content}}\n\nSender Email:\n{{ $json.from }}\n\nAttachment File Name:\n{{$binary.attachment_0.fileName}}\n\nAttachment MIME Type:\n{{$binary.attachment_0.mimeType}}\n", + "needsFallback": true, + "options": { + "systemMessage": "You are an invoice recognition agent operating inside an automated workflow.\n\nYou will receive:\nEmail subject\nEmail body content (plain text or HTML converted to text)\nSender email address and name\nAttachment file name\nAttachment MIME type\n\nYour task:\nDetermine whether the email and its attachment should be treated as a BUSINESS INVOICE.\n\nClassification rules:\nClassify the email as an invoice if ANY billing, payment, receipt, tax, or business transaction context is present.\nThe word \"invoice\" may or may not appear explicitly.\nAttachment file names containing company or brand names (for example: BISLERI.pdf, TATA.pdf, AMAZON.pdf, A+V+TRADING.pdf) may represent invoices.\nIf the attachment MIME type is \"application/pdf\" and the email context is business-related, classify it as an invoice.\nIf there is reasonable doubt, classify the email as an invoice.\n\nHard constraints:\nDo NOT read or analyze PDF binary content.\nDo NOT perform OCR.\nDo NOT extract invoice numbers, dates, or amounts.\nNEVER return null or undefined.\nALWAYS return all fields.\nNEVER include markdown formatting.\nNEVER wrap the output in ```json or ``` blocks.\nNEVER include explanations, headings, or extra text.\n\nOutput requirements:\nReturn ONLY a single valid JSON object.\nThe response must start with { and end with }.\nThe output must be directly parseable using JSON.parse().\n\nReturn the response in this EXACT format:\n\n{\n \"is_invoice\": true or false,\n \"confidence\": \"high\" or \"medium\" or \"low\",\n \"reason\": \"\"\n}" + } + }, + "type": "@n8n/n8n-nodes-langchain.agent", + "typeVersion": 2.2, + "position": [ + -3488, + 960 + ], + "id": "f43530ad-adfa-41ba-b3e2-59c500b8931e", + "name": "AI: Classify Invoice1", + "alwaysOutputData": false, + "notesInFlow": false, + "retryOnFail": true, + "onError": "continueRegularOutput" + }, + { + "parameters": { + "method": "POST", + "url": "https://aiinfinite.in/process-invoice", + "sendHeaders": true, + "headerParameters": { + "parameters": [ + { + "name": "x-api-key", + "value": "971dcea6c47445f6f7405fa2d14e116b1d81dae6c10330571e8d4220c013b523" + } + ] + }, + "sendBody": true, + "contentType": "multipart-form-data", + "bodyParameters": { + "parameters": [ + { + "parameterType": "formBinaryData", + "name": "file", + "inputDataFieldName": "=file" + } + ] + }, + "options": {} + }, + "type": "n8n-nodes-base.httpRequest", + "typeVersion": 4.2, + "position": [ + -1568, + 192 + ], + "id": "bc668542-9d9c-4096-9750-777b7012a29b", + "name": "OCR: Extract Invoice Data2", + "alwaysOutputData": false, + "retryOnFail": true, + "waitBetweenTries": 5000, + "maxTries": 3, + "onError": "continueRegularOutput" + }, + { + "parameters": { + "mode": "combine", + "combineBy": "combineByPosition", + "options": {} + }, + "type": "n8n-nodes-base.merge", + "typeVersion": 3.2, + "position": [ + -3136, + 912 + ], + "id": "c3974a60-9c2b-476b-9283-7eb744b4501e", + "name": "Merge: Email + AI Classification1" + }, + { + "parameters": { + "operation": "getAll", + "limit": 3, + "filtersUI": { + "values": { + "filters": { + "foldersToInclude": [ + "AQMkADAwATM0MDAAMi1hYzgzLTQxMQAyLTAwAi0wMAoALgAAA3R9Z7-WZCBHqvG_09flPEoBAJRkAPlTP4RNsddkpsHybkoAAAJoYgAAAA==", + "AQMkADAwATM0MDAAMi1hYzgzLTQxMQAyLTAwAi0wMAoALgAAA3R9Z7-WZCBHqvG_09flPEoBAJRkAPlTP4RNsddkpsHybkoAAAIBFgAAAA==" + ] + } + } + }, + "options": { + "downloadAttachments": true + } + }, + "type": "n8n-nodes-base.microsoftOutlook", + "typeVersion": 2, + "position": [ + -4608, + 1056 + ], + "id": "939a1916-4d96-4550-9482-fd51209d060a", + "name": "Fetch Emails from New_Invoice (max 3)1", + "executeOnce": true, + "webhookId": "977ad40e-7150-4f6a-a351-e29c08eb4f97", + "credentials": { + "microsoftOutlookOAuth2Api": { + "id": "neYqnH7A2WPe5lTs", + "name": "Microsoft Outlook account" + } + } + }, + { + "parameters": { + "options": {} + }, + "type": "n8n-nodes-base.splitInBatches", + "typeVersion": 3, + "position": [ + -4384, + 1056 + ], + "id": "d71ef907-462d-4c40-bb01-2476d9cb7bf3", + "name": "Loop: Each Email2" + }, + { + "parameters": {}, + "type": "n8n-nodes-base.noOp", + "name": "End: No More Emails1", + "typeVersion": 1, + "position": [ + -4160, + 1104 + ], + "id": "90ad177b-23a6-41d0-86fe-fd3f3725e6d8" + }, + { + "parameters": { + "operation": "update", + "messageId": { + "__rl": true, + "value": "={{ $json.id }}", + "mode": "id" + }, + "updateFields": { + "folderId": { + "__rl": true, + "value": "AQMkADAwATM0MDAAMi1hYzgzLTQxMQAyLTAwAi0wMAoALgAAA3R9Z7-WZCBHqvG_09flPEoBAJRkAPlTP4RNsddkpsHybkoAAAJocQAAAA==", + "mode": "list", + "cachedResultName": "Processing", + "cachedResultUrl": "https://outlook.office365.com/mail/AQMkADAwATM0MDAAMi1hYzgzLTQxMQAyLTAwAi0wMAoALgAAA3R9Z7%2FWZCBHqvG_09flPEoBAJRkAPlTP4RNsddkpsHybkoAAAJocQAAAA%3D%3D" + } + } + }, + "type": "n8n-nodes-base.microsoftOutlook", + "typeVersion": 2, + "position": [ + -4160, + 912 + ], + "id": "aaab2e62-0622-4bbd-b3d1-648fcb06b290", + "name": "Label: Add Processing2", + "webhookId": "5d0319e0-f28f-4f7a-a562-038cd721cf91", + "credentials": { + "microsoftOutlookOAuth2Api": { + "id": "neYqnH7A2WPe5lTs", + "name": "Microsoft Outlook account" + } + }, + "onError": "continueRegularOutput" + }, + { + "parameters": { + "operation": "move", + "messageId": { + "__rl": true, + "value": "={{ $('Fetch Emails from New_Invoice (max 3)1').item.json.id }}", + "mode": "id" + }, + "folderId": { + "__rl": true, + "value": "AQMkADAwATM0MDAAMi1hYzgzLTQxMQAyLTAwAi0wMAoALgAAA3R9Z7-WZCBHqvG_09flPEoBAJRkAPlTP4RNsddkpsHybkoAAAJocQAAAA==", + "mode": "list", + "cachedResultName": "Processing", + "cachedResultUrl": "https://outlook.office365.com/mail/AQMkADAwATM0MDAAMi1hYzgzLTQxMQAyLTAwAi0wMAoALgAAA3R9Z7%2FWZCBHqvG_09flPEoBAJRkAPlTP4RNsddkpsHybkoAAAJocQAAAA%3D%3D" + } + }, + "type": "n8n-nodes-base.microsoftOutlook", + "typeVersion": 2, + "position": [ + -3936, + 912 + ], + "id": "584c67c7-ff4d-4b72-8a91-a94fe1c6ad4b", + "name": "Label: Remove New_Invoice1", + "webhookId": "e16ef4d9-e84c-4127-aafa-6f61cbdb9ba0", + "credentials": { + "microsoftOutlookOAuth2Api": { + "id": "neYqnH7A2WPe5lTs", + "name": "Microsoft Outlook account" + } + }, + "disabled": true + }, + { + "parameters": { + "operation": "get", + "messageId": { + "__rl": true, + "mode": "id", + "value": "={{ $json.id }}" + }, + "options": { + "downloadAttachments": true + } + }, + "type": "n8n-nodes-base.microsoftOutlook", + "typeVersion": 2, + "position": [ + -3712, + 912 + ], + "id": "8f05ea79-5bef-42c3-aef3-fc99f97397e8", + "name": "Fetch Full Email + Attachments2", + "webhookId": "74750b5a-de62-4326-888d-2d36ef832e5f", + "credentials": { + "microsoftOutlookOAuth2Api": { + "id": "neYqnH7A2WPe5lTs", + "name": "Microsoft Outlook account" + } + } + }, + { + "parameters": { + "jsCode": "// ═══════════════════════════════════════════════════════════════════\n// MASTER PARSE AI OUTPUT — Production Grade — Never-Fail Strategy\n//\n// Handles ALL known Gemini / Groq / LangChain output formats:\n// 1. Standard string in output field\n// 2. output field is already a parsed Object\n// 3. output field is an Array (unwraps first element)\n// 4. Double-nested output.output\n// 5. JSON wrapped in ```json ... ``` markdown fences\n// 6. JSON buried inside explanatory text (extracts all {} blocks)\n// 7. Malformed / unclosed JSON (regex fallback)\n// 8. is_invoice as boolean true/false\n// 9. is_invoice as string \"true\"/\"false\"/\"True\"/\"yes\"/\"1\"\n// 10. is_invoice as number 1/0\n// 11. Alternative field names: isInvoice, invoice, type, classification\n// 12. Confidence values: \"HIGH\", \"high\", \"Medium\", \"certain\", \"low\"\n// 13. text / content / message / result field instead of output\n// 14. LangChain wrapped format (lc/kwargs/content)\n// 15. Agent-level errors (quota, API down, 429, etc.)\n// 16. BOM characters and non-printable chars in output\n// 17. Partial / truncated JSON (regex field extraction)\n//\n// CLASSIFICATION OUTPUT (Switch node reads this):\n// \"invoice\" → process as invoice\n// \"not_invoice\" → skip, label as not-invoice\n// \"error\" → log error, do not process\n// ═══════════════════════════════════════════════════════════════════\n\nreturn items.map(item => {\n\n let classification = 'error';\n let confidence = 'low';\n let ai_reason = '';\n let error_detail = '';\n\n try {\n\n // ══════════════════════════════════════════════════════════════\n // STAGE 1 — Agent-level error check\n // Catches: Gemini quota, API key invalid, network timeout, 429\n // ══════════════════════════════════════════════════════════════\n if (item.json.error) {\n const errVal = item.json.error;\n const errStr = typeof errVal === 'object'\n ? (errVal.message || JSON.stringify(errVal))\n : String(errVal);\n error_detail = 'AGENT_ERROR: ' + errStr.slice(0, 300);\n classification = 'error';\n return buildOutput(item, classification, confidence, ai_reason, error_detail);\n }\n\n // ══════════════════════════════════════════════════════════════\n // STAGE 2 — Find raw content from all possible field paths\n // Try: output → text → content → message → result → response\n // ══════════════════════════════════════════════════════════════\n const FIELD_PATHS = ['output', 'text', 'content', 'message', 'result', 'response'];\n let raw = null;\n let parsed = null; // set if we already have a parsed object\n\n for (const path of FIELD_PATHS) {\n const val = item.json[path];\n if (val === null || val === undefined || val === '') continue;\n raw = val;\n break;\n }\n\n if (raw === null) {\n // Last resort: check if item.json itself IS the parsed object\n if (item.json.is_invoice !== undefined) {\n parsed = item.json;\n raw = null;\n } else {\n error_detail = 'NO_OUTPUT_FIELD: checked output/text/content/message/result';\n classification = 'error';\n return buildOutput(item, classification, confidence, ai_reason, error_detail);\n }\n }\n\n // ══════════════════════════════════════════════════════════════\n // STAGE 3 — Unwrap arrays and nested objects\n // ══════════════════════════════════════════════════════════════\n if (parsed === null && raw !== null) {\n // Unwrap Array → take first element\n if (Array.isArray(raw)) {\n raw = raw[0];\n }\n\n // If raw is an Object (n8n pre-parsed the JSON)\n if (raw !== null && typeof raw === 'object') {\n // Check for LangChain format: {lc: 1, kwargs: {content: \"...\"}}\n if (raw.kwargs && raw.kwargs.content !== undefined) {\n raw = raw.kwargs.content;\n\n // Check for double-nested output field\n } else if (raw.output !== undefined) {\n raw = raw.output;\n // raw might still be an object — check again\n if (raw !== null && typeof raw === 'object') {\n if (Array.isArray(raw)) raw = raw[0];\n if (raw !== null && typeof raw === 'object') {\n parsed = raw;\n raw = null;\n }\n }\n\n } else {\n // Object IS the parsed result\n parsed = raw;\n raw = null;\n }\n }\n }\n\n // ══════════════════════════════════════════════════════════════\n // STAGE 4 — Parse JSON from string (multi-attempt strategy)\n // ══════════════════════════════════════════════════════════════\n if (parsed === null && raw !== null) {\n const rawStr = String(raw);\n\n if (rawStr.trim() === '') {\n error_detail = 'EMPTY_AI_RESPONSE';\n classification = 'error';\n return buildOutput(item, classification, confidence, ai_reason, error_detail);\n }\n\n // ── Clean the string ──────────────────────────────────────\n let cleaned = rawStr\n .replace(/\\uFEFF/g, '') // BOM character\n .replace(/[\\x00-\\x08\\x0B\\x0C\\x0E-\\x1F]/g, '') // control chars (keep \\n \\r \\t)\n .replace(/```json\\s*/gi, '') // opening ```json fence\n .replace(/```\\s*/g, '') // closing ``` fence\n .trim();\n\n // ── Attempt 1: Direct JSON.parse of entire cleaned string ──\n parsed = tryParse(cleaned);\n\n // ── Attempt 2: Extract first complete { ... } block ───────\n if (!parsed) {\n const block = extractJsonBlock(cleaned, 'first');\n if (block) parsed = tryParse(block);\n }\n\n // ── Attempt 3: Extract the JSON block CONTAINING is_invoice ─\n if (!parsed) {\n const block = extractJsonBlockWithKey(cleaned, 'is_invoice');\n if (block) parsed = tryParse(block);\n }\n\n // ── Attempt 4: Extract LAST { ... } block ─────────────────\n if (!parsed) {\n const block = extractJsonBlock(cleaned, 'last');\n if (block) parsed = tryParse(block);\n }\n\n // ── Attempt 5: Try ALL { ... } blocks ─────────────────────\n if (!parsed) {\n const blocks = extractAllJsonBlocks(cleaned);\n for (const block of blocks) {\n const p = tryParse(block);\n if (p && (p.is_invoice !== undefined || p.isInvoice !== undefined)) {\n parsed = p;\n break;\n }\n }\n if (!parsed && blocks.length > 0) {\n parsed = tryParse(blocks[0]); // take first even if no is_invoice key\n }\n }\n\n // ── Attempt 6: Regex field extraction (malformed JSON) ────\n if (!parsed) {\n parsed = regexExtract(cleaned);\n }\n\n if (!parsed) {\n error_detail = 'ALL_PARSE_ATTEMPTS_FAILED: ' + cleaned.slice(0, 200);\n classification = 'error';\n return buildOutput(item, classification, confidence, ai_reason, error_detail);\n }\n }\n\n // ══════════════════════════════════════════════════════════════\n // STAGE 5 — Extract is_invoice from parsed object\n // Try all known field name variants\n // ══════════════════════════════════════════════════════════════\n const IS_INVOICE_FIELDS = [\n 'is_invoice', 'isInvoice', 'is_Invoice', 'IS_INVOICE',\n 'invoice', 'is_invoice_document', 'invoiceDetected'\n ];\n\n let rawFlag = undefined;\n let usedField = '';\n\n for (const field of IS_INVOICE_FIELDS) {\n if (parsed[field] !== undefined) {\n rawFlag = parsed[field];\n usedField = field;\n break;\n }\n }\n\n // ── Try classification/type fields (value-based check) ──────\n if (rawFlag === undefined) {\n const typeVal = String(parsed.classification || parsed.type || parsed.category || '').toLowerCase();\n if (typeVal.includes('invoice')) { rawFlag = true; }\n else if (typeVal.includes('not') ||\n typeVal.includes('skip') ||\n typeVal.includes('other')) { rawFlag = false; }\n }\n\n // ── If still not found, scan the raw text for patterns ──────\n if (rawFlag === undefined && raw) {\n const rawLower = String(raw).toLowerCase();\n const m = rawLower.match(/\"is_invoice\"\\s*:\\s*(true|false|\"true\"|\"false\"|1|0)/);\n if (m) {\n rawFlag = (m[1] === 'true' || m[1] === '\"true\"' || m[1] === '1');\n }\n }\n\n if (rawFlag === undefined) {\n error_detail = 'IS_INVOICE_FIELD_NOT_FOUND. Parsed object: ' + JSON.stringify(parsed).slice(0, 200);\n classification = 'error';\n\n } else {\n // ══════════════════════════════════════════════════════════\n // STAGE 6 — Normalize is_invoice to definitive boolean\n // ══════════════════════════════════════════════════════════\n const flag = String(rawFlag).toLowerCase().trim();\n\n if (['true', '1', 'yes', 'y', 'correct', 'affirmative', 'confirmed'].includes(flag)) {\n classification = 'invoice';\n\n } else if (['false', '0', 'no', 'n', 'incorrect', 'negative', 'not'].includes(flag)) {\n classification = 'not_invoice';\n\n } else {\n error_detail = 'UNEXPECTED_IS_INVOICE_VALUE: \"' + String(rawFlag) + '\"';\n classification = 'error';\n }\n }\n\n // ══════════════════════════════════════════════════════════════\n // STAGE 7 — Extract confidence and reason\n // ══════════════════════════════════════════════════════════════\n if (parsed) {\n // Confidence: normalize to \"high\" | \"medium\" | \"low\"\n const rawConf = String(parsed.confidence || parsed.certainty || parsed.score || 'low').toLowerCase().trim();\n if (['high', 'very_high', 'certain', 'definite', 'strong'].some(v => rawConf.includes(v))) {\n confidence = 'high';\n } else if (['medium', 'moderate', 'mid', 'possible', 'likely'].some(v => rawConf.includes(v))) {\n confidence = 'medium';\n } else {\n confidence = 'low';\n }\n\n // Reason: try multiple field names\n ai_reason = String(\n parsed.reason || parsed.explanation || parsed.rationale ||\n parsed.description || parsed.detail || ''\n ).slice(0, 500);\n }\n\n } catch (e) {\n error_detail = error_detail || ('UNCAUGHT_EXCEPTION: ' + e.message);\n classification = 'error';\n }\n\n return buildOutput(item, classification, confidence, ai_reason, error_detail);\n\n});\n\n// ══════════════════════════════════════════════════════════════════\n// HELPER FUNCTIONS\n// ══════════════════════════════════════════════════════════════════\n\nfunction buildOutput(item, classification, confidence, ai_reason, error_detail) {\n return {\n json: {\n ...item.json,\n classification,\n confidence,\n ai_reason,\n error_detail\n },\n binary: item.binary\n };\n}\n\nfunction tryParse(str) {\n try {\n if (!str || str.trim() === '') return null;\n const result = JSON.parse(str.trim());\n // Must be an object, not array/primitive\n if (result && typeof result === 'object' && !Array.isArray(result)) return result;\n if (Array.isArray(result) && result.length > 0 && typeof result[0] === 'object') return result[0];\n return null;\n } catch(e) {\n return null;\n }\n}\n\nfunction extractJsonBlock(str, which) {\n // Find matching { } block accounting for nesting\n const results = extractAllJsonBlocks(str);\n if (results.length === 0) return null;\n return which === 'last' ? results[results.length - 1] : results[0];\n}\n\nfunction extractAllJsonBlocks(str) {\n const blocks = [];\n let depth = 0, start = -1;\n for (let i = 0; i < str.length; i++) {\n if (str[i] === '{') {\n if (depth === 0) start = i;\n depth++;\n } else if (str[i] === '}') {\n depth--;\n if (depth === 0 && start !== -1) {\n blocks.push(str.slice(start, i + 1));\n start = -1;\n }\n }\n }\n return blocks;\n}\n\nfunction extractJsonBlockWithKey(str, key) {\n const blocks = extractAllJsonBlocks(str);\n for (const block of blocks) {\n if (block.includes('\"' + key + '\"') || block.includes(\"'\" + key + \"'\")) {\n return block;\n }\n }\n return null;\n}\n\nfunction regexExtract(str) {\n // Last resort: use regex to pull specific fields directly from string\n // even if the JSON is malformed or truncated\n try {\n const result = {};\n let found = false;\n\n // Extract is_invoice\n const mInv = str.match(/\"is_invoice\"\\s*:\\s*(true|false|\"true\"|\"false\"|\"yes\"|\"no\"|1|0)/i);\n if (mInv) {\n const v = mInv[1].replace(/\"/g, '').toLowerCase();\n result.is_invoice = ['true', 'yes', '1'].includes(v);\n found = true;\n }\n\n // Extract confidence\n const mConf = str.match(/\"confidence\"\\s*:\\s*\"([^\"]+)\"/i);\n if (mConf) result.confidence = mConf[1];\n\n // Extract reason\n const mReason = str.match(/\"reason\"\\s*:\\s*\"([^\"]+)\"/i);\n if (mReason) result.reason = mReason[1];\n\n return found ? result : null;\n } catch(e) {\n return null;\n }\n}\n" + }, + "type": "n8n-nodes-base.code", + "typeVersion": 2, + "position": [ + -2464, + 320 + ], + "id": "e76f2124-e8b2-4b52-86c5-0ab65b6068cf", + "name": "Parse AI Output2", + "retryOnFail": true, + "executeOnce": false, + "alwaysOutputData": true, + "notesInFlow": true + }, + { + "parameters": { + "assignments": { + "assignments": [ + { + "id": "00093515-229c-432c-9c8d-a2ef09acf369", + "name": "messageId", + "value": "={{$json.id}}", + "type": "string" + } + ] + }, + "includeOtherFields": true, + "options": {} + }, + "type": "n8n-nodes-base.set", + "typeVersion": 3.4, + "position": [ + -3424, + 672 + ], + "id": "a5f2223b-6f10-4437-81dc-9a34d57996d0", + "name": "Set messageId Field1" + }, + { + "parameters": { + "operation": "move", + "messageId": "={{ $json.messageId }}", + "folderId": { + "__rl": true, + "value": "AQMkADAwATM0MDAAMi1hYzgzLTQxMQAyLTAwAi0wMAoALgAAA3R9Z7-WZCBHqvG_09flPEoBAJRkAPlTP4RNsddkpsHybkoAAAJocgAAAA==", + "mode": "list", + "cachedResultName": "Not_invoice", + "cachedResultUrl": "https://outlook.office365.com/mail/AQMkADAwATM0MDAAMi1hYzgzLTQxMQAyLTAwAi0wMAoALgAAA3R9Z7%2FWZCBHqvG_09flPEoBAJRkAPlTP4RNsddkpsHybkoAAAJocgAAAA%3D%3D" + } + }, + "type": "n8n-nodes-base.microsoftOutlook", + "typeVersion": 2, + "position": [ + -2016, + 576 + ], + "id": "0c59ac0e-ca75-45bd-b731-3aae0faed96f", + "name": "Label: Add Not_Invoice2", + "webhookId": "d4398f49-ea88-4a89-8f2d-cffbda551562", + "credentials": { + "microsoftOutlookOAuth2Api": { + "id": "neYqnH7A2WPe5lTs", + "name": "Microsoft Outlook account" + } + }, + "onError": "continueRegularOutput" + }, + { + "parameters": { + "operation": "move", + "messageId": { + "__rl": true, + "value": "={{ $('Flatten Data for Log2').item.json.messageId }}", + "mode": "" + }, + "folderId": { + "__rl": true, + "value": "AQMkADAwATM0MDAAMi1hYzgzLTQxMQAyLTAwAi0wMAoALgAAA3R9Z7-WZCBHqvG_09flPEoBAJRkAPlTP4RNsddkpsHybkoAAAJocwAAAA==", + "mode": "list", + "cachedResultName": "Invoice_Sucess", + "cachedResultUrl": "https://outlook.office365.com/mail/AQMkADAwATM0MDAAMi1hYzgzLTQxMQAyLTAwAi0wMAoALgAAA3R9Z7%2FWZCBHqvG_09flPEoBAJRkAPlTP4RNsddkpsHybkoAAAJocwAAAA%3D%3D" + } + }, + "type": "n8n-nodes-base.microsoftOutlook", + "typeVersion": 2, + "position": [ + 0, + 0 + ], + "id": "bf5b1548-e75b-40d4-9b2d-a534708db65e", + "name": "Label: Add Invoice_Done2", + "webhookId": "e3a226f8-3b0f-4e68-a8d9-b881d60341ac", + "credentials": { + "microsoftOutlookOAuth2Api": { + "id": "neYqnH7A2WPe5lTs", + "name": "Microsoft Outlook account" + } + }, + "onError": "continueRegularOutput" + }, + { + "parameters": { + "operation": "move", + "messageId": "={{ $('Set messageId Field1').item.json.messageId }}", + "folderId": { + "__rl": true, + "value": "AQMkADAwATM0MDAAMi1hYzgzLTQxMQAyLTAwAi0wMAoALgAAA3R9Z7-WZCBHqvG_09flPEoBAJRkAPlTP4RNsddkpsHybkoAAAJodAAAAA==", + "mode": "list", + "cachedResultName": "Invoice_Failed", + "cachedResultUrl": "https://outlook.office365.com/mail/AQMkADAwATM0MDAAMi1hYzgzLTQxMQAyLTAwAi0wMAoALgAAA3R9Z7%2FWZCBHqvG_09flPEoBAJRkAPlTP4RNsddkpsHybkoAAAJodAAAAA%3D%3D" + } + }, + "type": "n8n-nodes-base.microsoftOutlook", + "typeVersion": 2, + "position": [ + -672, + 384 + ], + "id": "651c1889-e980-4870-a309-35e23ea51aed", + "name": "Label: Add Invoice_failed2", + "webhookId": "8f38dce4-4702-49e4-8a0f-7882a573aacf", + "credentials": { + "microsoftOutlookOAuth2Api": { + "id": "neYqnH7A2WPe5lTs", + "name": "Microsoft Outlook account" + } + }, + "onError": "continueRegularOutput" + }, + { + "parameters": { + "conditions": { + "options": { + "caseSensitive": true, + "leftValue": "", + "typeValidation": "strict", + "version": 2 + }, + "conditions": [ + { + "id": "78e67355-b3ff-448c-b597-35b7e0709267", + "leftValue": "={{\n !($json.error && $json.error.includes(\"429\")) &&\n !$json.error &&\n ($json.invoice_number ?? \"\") !== \"\"\n}}", + "rightValue": "", + "operator": { + "type": "boolean", + "operation": "true", + "singleValue": true + } + } + ], + "combinator": "and" + }, + "options": {} + }, + "type": "n8n-nodes-base.if", + "typeVersion": 2.2, + "position": [ + -1344, + 192 + ], + "id": "c7004bf2-bb80-4eea-8384-54cbd6baae84", + "name": "OCR Extraction Valid?2" + }, + { + "parameters": { + "method": "POST", + "url": "https://mapp.dmhospital.org/dmhApiRef/grn/createGRN.php", + "sendHeaders": true, + "headerParameters": { + "parameters": [ + { + "name": "x-api-key", + "value": "nirajAi26@DMH" + }, + { + "name": "Content-Type", + "value": "application/json" + } + ] + }, + "sendBody": true, + "specifyBody": "json", + "jsonBody": "={{$json}}", + "options": {} + }, + "type": "n8n-nodes-base.httpRequest", + "typeVersion": 4.2, + "position": [ + -400, + 96 + ], + "id": "4372d6a1-b4d9-4a1f-b522-c3399044ce33", + "name": "GRN: Create Record in Hospital2", + "retryOnFail": false, + "onError": "continueRegularOutput" + }, + { + "parameters": { + "jsCode": "function cleanNumber(val) {\n if (val === null || val === undefined) return 0;\n\n return Number(\n val\n .toString()\n .replace(/[^\\d.-]/g, \"\") // remove commas, brackets, symbols\n ) || 0;\n}\n\nreturn items.map(item => {\n\n const inv = item.json;\n\n return {\n json: {\n\n // ── HEADER ────────────────────────────────────────────────────────────\n invoice_id: inv.invoice_id ?? \"\",\n invoice_number: inv.invoice_number ?? \"\",\n invoice_date: inv.invoice_date ?? \"\",\n due_date: inv.due_date ?? \"\",\n seller_name: inv.seller_name ?? \"\",\n PO_number: inv.PO_number ?? \"\",\n\n invoice_amount: cleanNumber(inv.invoice_amount),\n currency_code: inv.currency_code ?? \"INR\",\n\n seller_gstin: inv.seller_gstin ?? \"\",\n customer_name: inv.customer_name ?? \"\",\n\n // ⚠️ HARDCODED — OCR frequently misreads or omits the hospital GSTIN.\n // This is always DEENANATH MEDICAL STORES (DMH Hospital Pharmacy).\n // Never trust the OCR value for this field.\n customer_gstin: \"27AAATL1944N1ZA\",\n\n dc_date: inv.DC_date ?? \"\",\n dc_number: inv.DC_number ?? \"\",\n\n round_off: cleanNumber(inv.round_off),\n\n total_gst_rate: cleanNumber(inv.total_gst_rate),\n total_quantity: cleanNumber(inv.total_quantity),\n\n total_cgst_rate: cleanNumber(inv.total_cgst_rate),\n total_cgst_amount: cleanNumber(inv.total_cgst_amount),\n\n total_sgst_rate: cleanNumber(inv.total_sgst_rate),\n total_sgst_amount: cleanNumber(inv.total_sgst_amount),\n\n total_igst_rate: cleanNumber(inv.total_igst_rate),\n total_igst_amount: cleanNumber(inv.total_igst_amount),\n\n total_gst_amount: cleanNumber(inv.total_gst_amount),\n\n // ── ITEMS ─────────────────────────────────────────────────────────────\n items: (inv.items ?? []).map(i => ({\n\n item_code: i.item_code ?? \"\",\n Batch: i.Batch ?? \"\",\n\n quantity: cleanNumber(i.quantity),\n free_item_yn: cleanNumber(i.free_item_yn),\n\n unit_price: cleanNumber(i.unit_price),\n total_price: cleanNumber(i.total_price),\n\n Discount: cleanNumber(i.Discount),\n MRP: cleanNumber(i.MRP),\n\n description: i.description ?? \"\",\n Pack: i.Pack ?? \"\",\n hsn_sac: i.hsn_sac ?? \"\",\n expiry_date: i.expiry_date ?? \"\",\n\n cgst_rate: cleanNumber(i.cgst_rate),\n cgst_amount: cleanNumber(i.cgst_amount),\n\n sgst_rate: cleanNumber(i.sgst_rate),\n sgst_amount: cleanNumber(i.sgst_amount),\n\n igst_rate: cleanNumber(i.igst_rate),\n igst_amount: cleanNumber(i.igst_amount),\n\n GST_AMT: cleanNumber(i.GST_AMT),\n\n // Added missing fields\n taxable_value: cleanNumber(i.taxable_value),\n \"Gst%\": cleanNumber(i[\"Gst%\"]),\n Value: cleanNumber(i.Value),\n reference_number: i.reference_number ?? \"\"\n\n }))\n\n }\n };\n});" + }, + "type": "n8n-nodes-base.code", + "typeVersion": 2, + "position": [ + -1480, + 96 + ], + "id": "6f82a7b4-9dbf-4e9c-a6c4-6a4a52efc6e3", + "name": "Normalize Invoice Fields2" + }, + { + "parameters": { + "conditions": { + "options": { + "caseSensitive": true, + "leftValue": "", + "typeValidation": "strict", + "version": 2 + }, + "conditions": [ + { + "id": "b97ce590-39e2-4792-b38e-972bfd18e0fd", + "leftValue": "={{ $('Flatten Data for Log2').item.json.grn_success }}", + "rightValue": "", + "operator": { + "type": "boolean", + "operation": "true", + "singleValue": true + } + } + ], + "combinator": "and" + }, + "options": {} + }, + "type": "n8n-nodes-base.if", + "typeVersion": 2.2, + "position": [ + -224, + 96 + ], + "id": "477bad63-5dad-4f11-bfdb-8f21c9cb801e", + "name": "GRN Created Successfully?2" + }, + { + "parameters": { + "jsCode": "const newItems = [];\n\nfor (const item of items) {\n\n const binaries = item.binary || {};\n const keys = Object.keys(binaries);\n\n if (keys.length > 0) {\n\n for (const key of keys) {\n\n // ── GET filename before binary is consumed ──────────────\n const attachment_name = binaries[key].fileName || '';\n\n newItems.push({\n json: {\n ...item.json,\n attachment_name: attachment_name // ← ONLY NEW LINE\n },\n binary: {\n file: binaries[key]\n }\n });\n }\n\n } else {\n\n let parsedOutput = {};\n try {\n parsedOutput = JSON.parse(item.json.output || '{}');\n } catch (e) {\n parsedOutput = {};\n }\n\n newItems.push({\n json: {\n ...item.json,\n ...parsedOutput,\n attachment_name: '' // ← ONLY NEW LINE\n }\n });\n }\n}\n\nreturn newItems;" + }, + "type": "n8n-nodes-base.code", + "typeVersion": 2, + "position": [ + -2912, + 912 + ], + "id": "b019335c-9a06-417b-95bb-862fcfa1a8fc", + "name": "Split: One Item Per Attachment3", + "alwaysOutputData": true, + "retryOnFail": true + }, + { + "parameters": { + "options": {} + }, + "type": "n8n-nodes-base.splitInBatches", + "typeVersion": 3, + "position": [ + -2688, + 912 + ], + "id": "7cb557ad-cb6d-45d4-99e9-8966e310b493", + "name": "Loop: Each Attachment2" + }, + { + "parameters": { + "amount": 1 + }, + "type": "n8n-nodes-base.wait", + "typeVersion": 1.1, + "position": [ + -1792, + 192 + ], + "id": "dab6bfb7-215a-4ccd-8964-333200305739", + "name": "Wait 7s Before OCR2", + "webhookId": "66577e6f-2f40-4a0b-a701-b0b535c018e2" + }, + { + "parameters": { + "jsCode": "// =======================================================================\n// Flatten Data for Log2 — v5.0\n// Node: Flatten Data for Log2\n//\n// PURPOSE:\n// Parse GRN API responses safely, including unexpected/new error formats.\n//\n// SUPPORTED ERROR MESSAGE LOCATIONS:\n// message\n// error\n// detail\n// reason\n// description\n// statusText\n// error.message\n// error.detail\n// error.description\n// data.message\n// data.error\n// data.detail\n// data[0].message\n// data[0].error\n// data[0].detail\n// data[0] as string\n// JSON-stringified error objects\n//\n// IMPORTANT:\n// Never returns null / undefined / [object Object] as grn_message.\n// =======================================================================\n\n\n// ───────────────────────────────────────────────────────────────────────\n// Helper: safe word-boundary HTTP status code check\n// ───────────────────────────────────────────────────────────────────────\n\nfunction hasHttpCode(text, code) {\n const c = String(code).replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n return new RegExp('(^|[^0-9])' + c + '([^0-9]|$)').test(\n String(text || '')\n );\n}\n\n\n// ───────────────────────────────────────────────────────────────────────\n// Helper: safely convert any value to useful text\n// ───────────────────────────────────────────────────────────────────────\n\nfunction safeText(value) {\n if (value === null || value === undefined) return '';\n\n if (typeof value === 'string') {\n return value.trim();\n }\n\n if (typeof value === 'number' || typeof value === 'boolean') {\n return String(value);\n }\n\n if (Array.isArray(value)) {\n const parts = value\n .map(v => safeText(v))\n .filter(Boolean);\n\n return parts.join(' | ').trim();\n }\n\n if (typeof value === 'object') {\n // Try common message fields first\n const keys = [\n 'message',\n 'error',\n 'detail',\n 'reason',\n 'description',\n 'statusText',\n 'msg',\n 'error_message',\n 'errorMessage'\n ];\n\n for (const key of keys) {\n if (value[key] !== undefined && value[key] !== null) {\n const result = safeText(value[key]);\n if (result) return result;\n }\n }\n\n // Last resort: JSON\n try {\n return JSON.stringify(value);\n } catch (e) {\n return '';\n }\n }\n\n return '';\n}\n\n\n// ───────────────────────────────────────────────────────────────────────\n// Helper: recursively extract a meaningful error message\n// ───────────────────────────────────────────────────────────────────────\n\nfunction extractErrorMessage(source, depth = 0) {\n\n if (source === null || source === undefined) {\n return '';\n }\n\n // Prevent infinite recursion\n if (depth > 6) {\n return '';\n }\n\n // Direct string\n if (typeof source === 'string') {\n\n const str = source.trim();\n\n if (!str) return '';\n\n // If string itself contains JSON, try parsing it\n if (\n (str.startsWith('{') && str.endsWith('}')) ||\n (str.startsWith('[') && str.endsWith(']'))\n ) {\n try {\n const parsed = JSON.parse(str);\n const nested = extractErrorMessage(parsed, depth + 1);\n\n if (nested) return nested;\n } catch (e) {\n // Not valid JSON — use original string\n }\n }\n\n return str;\n }\n\n // Number / boolean\n if (\n typeof source === 'number' ||\n typeof source === 'boolean'\n ) {\n return String(source);\n }\n\n // Array\n if (Array.isArray(source)) {\n\n // Prefer meaningful string values\n for (const item of source) {\n const result = extractErrorMessage(item, depth + 1);\n\n if (result) {\n return result;\n }\n }\n\n return '';\n }\n\n // Object\n if (typeof source === 'object') {\n\n // Most useful keys first\n const priorityKeys = [\n 'message',\n 'error',\n 'detail',\n 'reason',\n 'description',\n 'statusText',\n 'msg',\n 'error_message',\n 'errorMessage',\n 'response',\n 'body',\n 'data'\n ];\n\n for (const key of priorityKeys) {\n\n if (\n Object.prototype.hasOwnProperty.call(source, key) &&\n source[key] !== null &&\n source[key] !== undefined\n ) {\n\n const result = extractErrorMessage(\n source[key],\n depth + 1\n );\n\n if (result) {\n return result;\n }\n }\n }\n\n // Search any remaining keys\n for (const key of Object.keys(source)) {\n\n if (priorityKeys.includes(key)) {\n continue;\n }\n\n const result = extractErrorMessage(\n source[key],\n depth + 1\n );\n\n if (result) {\n return result;\n }\n }\n }\n\n return '';\n}\n\n\n// ───────────────────────────────────────────────────────────────────────\n// Helper: extract which specific header/item fields are missing\n// ───────────────────────────────────────────────────────────────────────\n\nfunction extractMissingFields(cb) {\n\n const fields = [];\n\n if (cb.includes('po_number'))\n fields.push('PO_number');\n\n if (cb.includes('invoice_amount'))\n fields.push('invoice_amount');\n\n if (cb.includes('invoice_id'))\n fields.push('invoice_id');\n\n if (cb.includes('item_code'))\n fields.push('item_code');\n\n if (cb.includes('item_id'))\n fields.push('item_id');\n\n if (cb.includes('batch'))\n fields.push('Batch');\n\n if (cb.includes('quantity'))\n fields.push('quantity');\n\n return fields;\n}\n\n\n// ───────────────────────────────────────────────────────────────────────\n// Helper: get item-code arrays from any supported structure\n// ───────────────────────────────────────────────────────────────────────\n\nfunction getArrayFromSources(sources, fieldNames) {\n\n for (const source of sources) {\n\n if (!source || typeof source !== 'object') {\n continue;\n }\n\n for (const field of fieldNames) {\n\n if (Array.isArray(source[field])) {\n return source[field];\n }\n }\n }\n\n return [];\n}\n\n\n// ───────────────────────────────────────────────────────────────────────\n// Error classifier\n// ───────────────────────────────────────────────────────────────────────\n\nfunction classifyError(\n grnMsg,\n fullErrorRaw,\n missingCodes,\n invalidCodes\n) {\n\n const text = String(\n (grnMsg || '') +\n ' ' +\n (fullErrorRaw || '')\n );\n\n const cb = text.toLowerCase();\n\n const raw =\n String(grnMsg || '').trim() ||\n String(fullErrorRaw || '').trim() ||\n 'Unknown API error';\n\n if (!cb.trim()) {\n return {\n owner: 'DMH',\n category: 'Other / Unclassified Error',\n detail: 'Unknown API error'\n };\n }\n\n const hasMissing =\n Array.isArray(missingCodes) &&\n missingCodes.length > 0;\n\n const hasInvalid =\n Array.isArray(invalidCodes) &&\n invalidCodes.length > 0;\n\n\n // ─────────────────────────────────────────────────────────────────────\n // DMH: MySQL Pool Exhausted\n // ─────────────────────────────────────────────────────────────────────\n\n if (\n cb.includes('pool exhausted') ||\n cb.includes('mysql.connector.errors.poolerror') ||\n cb.includes('too many connections') ||\n (\n cb.includes('connection refused') &&\n cb.includes('mysql')\n )\n ) {\n return {\n owner: 'DMH',\n category: 'MySQL Pool Exhausted',\n detail: raw\n };\n }\n\n\n // ─────────────────────────────────────────────────────────────────────\n // AI INDIA: Timeout / Gateway\n // ─────────────────────────────────────────────────────────────────────\n\n if (\n hasHttpCode(text, 504) ||\n cb.includes('gateway time-out') ||\n cb.includes('gateway timeout') ||\n cb.includes('etimedout') ||\n cb.includes('econnrefused') ||\n cb.includes('socket hang up') ||\n cb.includes('300000ms') ||\n cb.includes('deadline expired') ||\n cb.includes('connect timeout') ||\n cb.includes('read timeout') ||\n cb.includes('request timed out') ||\n cb.includes('timeout')\n ) {\n return {\n owner: 'AI INDIA',\n category: 'API Timeout / Gateway Error',\n detail: raw\n };\n }\n\n\n // ─────────────────────────────────────────────────────────────────────\n // AI INDIA: Invalid File Type\n // ─────────────────────────────────────────────────────────────────────\n\n if (\n (\n hasHttpCode(text, 400) &&\n cb.includes('invalid file type')\n ) ||\n cb.includes('unsupported file type') ||\n cb.includes('file type not supported')\n ) {\n return {\n owner: 'AI INDIA',\n category: 'Invalid File Type (400)',\n detail: raw\n };\n }\n\n\n // ─────────────────────────────────────────────────────────────────────\n // AI INDIA: File Too Large\n // ─────────────────────────────────────────────────────────────────────\n\n if (\n hasHttpCode(text, 413) ||\n cb.includes('request entity too large') ||\n cb.includes('payload too large') ||\n cb.includes('file size exceeds') ||\n cb.includes('file too large')\n ) {\n return {\n owner: 'AI INDIA',\n category: 'File Too Large (413)',\n detail: raw\n };\n }\n\n\n // ─────────────────────────────────────────────────────────────────────\n // AI INDIA: Gemini / API Key / Quota\n // ─────────────────────────────────────────────────────────────────────\n\n if (\n hasHttpCode(text, 401) ||\n hasHttpCode(text, 403) ||\n hasHttpCode(text, 429) ||\n cb.includes('generativelanguage.googleapis') ||\n cb.includes('api error: forbidden') ||\n cb.includes('api error: service unavailable') ||\n cb.includes('fetch failed') ||\n cb.includes('unauthorized: api key') ||\n cb.includes('invalid api key') ||\n cb.includes('quota') ||\n cb.includes('rate limit') ||\n cb.includes('resource has been exhausted')\n ) {\n return {\n owner: 'AI INDIA',\n category: 'Gemini API Error (Quota / Auth)',\n detail: raw\n };\n }\n\n\n // ─────────────────────────────────────────────────────────────────────\n // AI INDIA: OCR Server Crash\n // ─────────────────────────────────────────────────────────────────────\n\n if (\n hasHttpCode(text, 500) &&\n (\n cb.includes('internal server error') ||\n cb.includes('nginx') ||\n cb.includes('werkzeug') ||\n cb.includes('traceback') ||\n cb.includes('application error') ||\n cb.includes('server error')\n )\n ) {\n return {\n owner: 'AI INDIA',\n category: 'OCR Server Internal Crash (500)',\n detail: raw\n };\n }\n\n\n // ─────────────────────────────────────────────────────────────────────\n // AI INDIA: Invalid Image Format\n // ─────────────────────────────────────────────────────────────────────\n\n if (\n cb.includes('pil') ||\n cb.includes('pngimageplugin') ||\n cb.includes('cannot identify image') ||\n cb.includes('image file is truncated') ||\n cb.includes('invalid image') ||\n cb.includes('unsupported image')\n ) {\n return {\n owner: 'AI INDIA',\n category: 'Invalid Image Format (PIL Error)',\n detail: raw\n };\n }\n\n\n // ─────────────────────────────────────────────────────────────────────\n // AI INDIA: No Binary File Attached\n // ─────────────────────────────────────────────────────────────────────\n\n if (\n (\n cb.includes('binary file') &&\n cb.includes('none was found')\n ) ||\n cb.includes('no file was uploaded') ||\n cb.includes('missing file attachment') ||\n cb.includes('file not found') ||\n cb.includes('no binary data')\n ) {\n return {\n owner: 'AI INDIA',\n category: 'No Binary File Found',\n detail: raw\n };\n }\n\n\n // ─────────────────────────────────────────────────────────────────────\n // DMH: CSV File\n // ─────────────────────────────────────────────────────────────────────\n\n if (cb.includes('csv')) {\n return {\n owner: 'DMH',\n category: 'Invalid File Format — CSV Not Supported',\n detail: raw\n };\n }\n\n\n // ─────────────────────────────────────────────────────────────────────\n // AI INDIA: OCR Extraction Failed\n // ─────────────────────────────────────────────────────────────────────\n\n if (\n cb.includes('ocr extraction failed') ||\n cb.includes('ocr extraction') ||\n cb.includes('unknown processing error') ||\n cb.includes('extraction failed') ||\n cb.includes('could not extract') ||\n cb.includes('parse failure') ||\n cb.includes('ocr_parse_error') ||\n cb.includes('pdf parse') ||\n cb.includes('failed to parse') ||\n cb.includes('parsing failed') ||\n cb.includes('unable to extract')\n ) {\n return {\n owner: 'AI INDIA',\n category: 'OCR Extraction Failed',\n detail: raw\n };\n }\n\n\n // ─────────────────────────────────────────────────────────────────────\n // DMH: Duplicate Invoice\n // ─────────────────────────────────────────────────────────────────────\n\n if (\n cb.includes('record already exist') ||\n cb.includes('already exist') ||\n cb.includes('duplicate invoice') ||\n cb.includes('duplicate entry') ||\n cb.includes('already exists') ||\n cb.includes('invoice already')\n ) {\n return {\n owner: 'DMH',\n category: 'Duplicate Invoice',\n detail: raw\n };\n }\n\n\n // ─────────────────────────────────────────────────────────────────────\n // DMH: No Valid Items\n // ─────────────────────────────────────────────────────────────────────\n\n if (\n cb.includes(\n 'the invoice must contain at least one valid item'\n ) ||\n cb.includes('no valid items') ||\n cb.includes('zero valid item') ||\n cb.includes('all items are invalid') ||\n cb.includes('valid item not found') ||\n cb.includes('no valid item found')\n ) {\n\n if (hasMissing && hasInvalid) {\n\n return {\n owner: 'DMH',\n category:\n 'Missing Item Codes (' +\n missingCodes.length +\n ') + Invalid Item Codes (' +\n invalidCodes.length +\n ') — Not Registered in DMH',\n detail: raw\n };\n }\n\n\n if (hasMissing) {\n\n return {\n owner: 'DMH',\n category:\n 'Missing Item Codes (' +\n missingCodes.length +\n ') — Items Not Registered in DMH',\n detail: raw\n };\n }\n\n\n if (hasInvalid) {\n\n return {\n owner: 'DMH',\n category:\n 'Invalid Item Codes (' +\n invalidCodes.length +\n ') — Items Not Registered in DMH',\n detail: raw\n };\n }\n\n\n return {\n owner: 'DMH',\n category: 'No Valid Items in Invoice',\n detail: raw\n };\n }\n\n\n // ─────────────────────────────────────────────────────────────────────\n // DMH: Vendor Not Found\n // ─────────────────────────────────────────────────────────────────────\n\n if (\n cb.includes('vendor details not found') &&\n !cb.includes('po details not found') &&\n !cb.includes('po number does not contain') &&\n !cb.includes('phrmcy') &&\n !cb.includes('dmhmss') &&\n !cb.includes('not valid!!!') &&\n !cb.includes('po_number')\n ) {\n\n return {\n owner: 'DMH',\n category: 'Vendor Not Found',\n detail: raw\n };\n }\n\n\n // ─────────────────────────────────────────────────────────────────────\n // DMH: PO Not Found / Invalid PO\n // ─────────────────────────────────────────────────────────────────────\n\n if (\n cb.includes('po details not found') ||\n cb.includes('not valid!!!') ||\n cb.includes('phrmcy') ||\n cb.includes('dmhmss') ||\n cb.includes('does not contain either') ||\n cb.includes('invalid purchase order') ||\n cb.includes('po not found') ||\n cb.includes('invalid po') ||\n cb.includes('purchase order not found')\n ) {\n\n return {\n owner: 'DMH',\n category: 'PO Not Found / Invalid PO Number',\n detail: raw\n };\n }\n\n\n // ─────────────────────────────────────────────────────────────────────\n // DMH: Item Fields Missing\n // ─────────────────────────────────────────────────────────────────────\n\n if (\n cb.includes('listed fields are missing from item list') ||\n cb.includes('item_code') ||\n cb.includes('item_id') ||\n (\n cb.includes('batch') &&\n (\n cb.includes('missing') ||\n cb.includes('required') ||\n cb.includes('invalid')\n )\n ) ||\n (\n cb.includes('quantity') &&\n (\n cb.includes('missing') ||\n cb.includes('required') ||\n cb.includes('invalid')\n )\n )\n ) {\n\n const missing = extractMissingFields(cb);\n\n const missingStr =\n missing.length\n ? missing.join(', ')\n : 'unspecified item fields';\n\n return {\n owner: 'DMH',\n category:\n 'Item Fields Missing — ' +\n missingStr,\n detail: raw\n };\n }\n\n\n // ─────────────────────────────────────────────────────────────────────\n // DMH: Header Fields Missing\n // ─────────────────────────────────────────────────────────────────────\n\n if (\n cb.includes('listed fields are missing') ||\n cb.includes('po_number') ||\n (\n cb.includes('invoice_amount') &&\n cb.includes('missing')\n ) ||\n (\n cb.includes('invoice_id') &&\n cb.includes('missing')\n )\n ) {\n\n const missing = extractMissingFields(cb);\n\n const missingStr =\n missing.length\n ? missing.join(', ')\n : 'unspecified header fields';\n\n return {\n owner: 'DMH',\n category:\n 'Header Fields Missing — ' +\n missingStr,\n detail: raw\n };\n }\n\n\n // ─────────────────────────────────────────────────────────────────────\n // DMH: GSTIN / GST Mismatch\n // ─────────────────────────────────────────────────────────────────────\n\n if (\n cb.includes('gstin mismatch') ||\n cb.includes('gst mismatch') ||\n cb.includes('gstin validation') ||\n cb.includes('invalid gstin')\n ) {\n\n return {\n owner: 'DMH',\n category: 'GSTIN Mismatch / Validation Error',\n detail: raw\n };\n }\n\n\n // ─────────────────────────────────────────────────────────────────────\n // Fallback\n // ─────────────────────────────────────────────────────────────────────\n\n return {\n owner: 'DMH',\n category: 'Other / Unclassified Error',\n detail: raw\n };\n}\n\n\n// ───────────────────────────────────────────────────────────────────────\n// Build complete_error\n// ───────────────────────────────────────────────────────────────────────\n\nfunction buildCompleteError(\n grnMsg,\n missingCodes,\n invalidCodes,\n fallbackRaw\n) {\n\n const message =\n String(grnMsg || '').trim() ||\n String(fallbackRaw || '').trim() ||\n 'Unknown API error';\n\n const c = classifyError(\n message,\n fallbackRaw || '',\n missingCodes,\n invalidCodes\n );\n\n if (!c) {\n return '';\n }\n\n const divider =\n '─────────────────────────────────';\n\n const lines = [\n 'Error Type : ' + c.category,\n 'Error From : [' + c.owner + ']',\n divider,\n 'Raw API error : ' + message\n ];\n\n return lines.join('\\n');\n}\n\n\n// ───────────────────────────────────────────────────────────────────────\n// Resolve messageId\n// ───────────────────────────────────────────────────────────────────────\n\nfunction resolveMessageId(item) {\n\n // Source 1\n try {\n\n const v =\n $('Set messageId Field1')\n .item\n .json\n .messageId;\n\n if (v) {\n return String(v);\n }\n\n } catch (e) {}\n\n\n // Source 2\n try {\n\n const v =\n $('Switch2')\n .item\n .json\n .id;\n\n if (v) {\n return String(v);\n }\n\n } catch (e) {}\n\n\n // Source 3\n if (\n item.json &&\n item.json.messageId\n ) {\n return String(item.json.messageId);\n }\n\n\n // Source 4\n if (\n item.json &&\n item.json.id\n ) {\n return String(item.json.id);\n }\n\n\n return '';\n}\n\n\n// ═══════════════════════════════════════════════════════════════════════\n// MAIN\n// ═══════════════════════════════════════════════════════════════════════\n\nconst output = [];\n\nitems.forEach(item => {\n\n // ─────────────────────────────────────────────────────────────────────\n // IST Timestamp\n // ─────────────────────────────────────────────────────────────────────\n\n const now = new Date();\n\n const date =\n now.toLocaleDateString(\n 'en-CA',\n {\n timeZone: 'Asia/Kolkata'\n }\n );\n\n const time =\n now.toLocaleTimeString(\n 'en-IN',\n {\n timeZone: 'Asia/Kolkata',\n hour12: true\n }\n );\n\n\n // ─────────────────────────────────────────────────────────────────────\n // messageId\n // ─────────────────────────────────────────────────────────────────────\n\n const messageId =\n resolveMessageId(item);\n\n\n // ─────────────────────────────────────────────────────────────────────\n // GRN root object\n // ─────────────────────────────────────────────────────────────────────\n\n const grn =\n item.json || {};\n\n const httpStatus =\n grn.status;\n\n\n // ─────────────────────────────────────────────────────────────────────\n // Parse data\n // ─────────────────────────────────────────────────────────────────────\n\n const grnDataRaw =\n Array.isArray(grn.data) &&\n grn.data.length > 0\n ? grn.data[0]\n : null;\n\n\n // ─────────────────────────────────────────────────────────────────────\n // Build possible sources\n // ─────────────────────────────────────────────────────────────────────\n\n const sources = [];\n\n if (grnDataRaw !== null) {\n sources.push(grnDataRaw);\n }\n\n if (\n grn.data &&\n typeof grn.data === 'object'\n ) {\n sources.push(grn.data);\n }\n\n sources.push(grn);\n\n\n // ─────────────────────────────────────────────────────────────────────\n // Extract GRN data object\n // ─────────────────────────────────────────────────────────────────────\n\n let grnData = {};\n\n if (\n grnDataRaw &&\n typeof grnDataRaw === 'object' &&\n !Array.isArray(grnDataRaw)\n ) {\n\n grnData = grnDataRaw;\n\n } else if (\n grn.data &&\n typeof grn.data === 'object' &&\n !Array.isArray(grn.data)\n ) {\n\n grnData = grn.data;\n }\n\n\n // ─────────────────────────────────────────────────────────────────────\n // NEW ROBUST MESSAGE EXTRACTION\n // ─────────────────────────────────────────────────────────────────────\n\n let grnMsg =\n extractErrorMessage(grnDataRaw);\n\n\n if (!grnMsg) {\n grnMsg =\n extractErrorMessage(grn.data);\n }\n\n\n if (!grnMsg) {\n grnMsg =\n extractErrorMessage(grn.message);\n }\n\n\n if (!grnMsg) {\n grnMsg =\n extractErrorMessage(grn.error);\n }\n\n\n if (!grnMsg) {\n grnMsg =\n extractErrorMessage(grn.detail);\n }\n\n\n if (!grnMsg) {\n grnMsg =\n extractErrorMessage(grn.reason);\n }\n\n\n if (!grnMsg) {\n grnMsg =\n extractErrorMessage(grn.description);\n }\n\n\n if (!grnMsg) {\n grnMsg =\n extractErrorMessage(grn.statusText);\n }\n\n\n // Absolute fallback\n if (!grnMsg) {\n grnMsg = 'Unknown API error';\n }\n\n\n // ─────────────────────────────────────────────────────────────────────\n // Missing / Invalid item codes\n // ─────────────────────────────────────────────────────────────────────\n\n const missingCodes =\n getArrayFromSources(\n sources,\n [\n 'missingItmesCodes',\n 'missingItemsCodes',\n 'missing_item_codes',\n 'missingItemCodes',\n 'missing_items',\n 'missingItems'\n ]\n );\n\n\n const invalidCodes =\n getArrayFromSources(\n sources,\n [\n 'invalidItmes',\n 'invalidItems',\n 'invalid_item_codes',\n 'invalidItemCodes',\n 'invalid_items'\n ]\n );\n\n\n // ─────────────────────────────────────────────────────────────────────\n // HTTP status\n // ─────────────────────────────────────────────────────────────────────\n\n const http_status_code =\n typeof httpStatus === 'number'\n ? httpStatus\n : parseInt(httpStatus, 10) || 0;\n\n\n // ─────────────────────────────────────────────────────────────────────\n // GRN success\n // ─────────────────────────────────────────────────────────────────────\n\n const httpOk =\n http_status_code === 200;\n\n const grnOk =\n grnData.status === 0 ||\n grnData.status === '0';\n\n const grn_success =\n httpOk && grnOk;\n\n const status =\n grn_success\n ? '✅ SUCCESS'\n : '❌ FAILED';\n\n\n // ─────────────────────────────────────────────────────────────────────\n // Invoice fields\n // ─────────────────────────────────────────────────────────────────────\n\n let inv = {};\n\n try {\n\n inv =\n $('Normalize Invoice Fields2')\n .item\n .json || {};\n\n } catch (e) {\n\n inv = {};\n }\n\n\n // ─────────────────────────────────────────────────────────────────────\n // Attachment name\n // ─────────────────────────────────────────────────────────────────────\n\n let attachment_name = '';\n\n try {\n\n attachment_name =\n $('Split: One Item Per Attachment3')\n .item\n .json\n .attachment_name || '';\n\n } catch (e) {\n\n attachment_name = '';\n }\n\n\n // ─────────────────────────────────────────────────────────────────────\n // Free Goods\n // ─────────────────────────────────────────────────────────────────────\n\n const invoiceItems =\n Array.isArray(inv.items)\n ? inv.items\n : [];\n\n const hasFreeGoods =\n invoiceItems.some(\n i =>\n String(\n i &&\n i.free_item_yn\n ) === '1'\n );\n\n const free_goods =\n hasFreeGoods\n ? 'Yes'\n : 'No';\n\n\n // ─────────────────────────────────────────────────────────────────────\n // Complete error\n // ─────────────────────────────────────────────────────────────────────\n\n let complete_error = '';\n\n\n if (grn_success) {\n\n const auditParts = [];\n\n if (grnData.grn_no) {\n auditParts.push(\n 'GRN No: ' +\n grnData.grn_no\n );\n }\n\n if (grnData.grn_master_id) {\n auditParts.push(\n 'GRN Master ID: ' +\n grnData.grn_master_id\n );\n }\n\n if (\n grnData.items_inserted !== undefined &&\n grnData.items_inserted !== null\n ) {\n auditParts.push(\n 'Items Inserted: ' +\n grnData.items_inserted\n );\n }\n\n if (grnData.vendor_id) {\n auditParts.push(\n 'Vendor ID: ' +\n grnData.vendor_id\n );\n }\n\n if (grnData.invoice_no) {\n auditParts.push(\n 'Invoice No (DMH): ' +\n grnData.invoice_no\n );\n }\n\n complete_error =\n auditParts.length\n ? auditParts.join(' | ')\n : '';\n\n } else {\n\n complete_error =\n buildCompleteError(\n grnMsg,\n missingCodes,\n invalidCodes,\n JSON.stringify(grn)\n );\n }\n\n\n // ─────────────────────────────────────────────────────────────────────\n // Output\n // ─────────────────────────────────────────────────────────────────────\n\n output.push({\n\n json: {\n\n // Timestamp\n date,\n time,\n\n\n // Invoice identity\n invoice_id:\n inv.invoice_id || '',\n\n invoice_number:\n inv.invoice_number || '',\n\n invoice_date:\n inv.invoice_date || '',\n\n seller_name:\n inv.seller_name || '',\n\n seller_gstin:\n inv.seller_gstin || '',\n\n customer_name:\n inv.customer_name || '',\n\n invoice_amount:\n inv.invoice_amount ?? 0,\n\n attachment_name,\n\n\n // GRN result\n status,\n\n grn_success,\n\n http_status_code,\n\n grn_message:\n grnMsg || 'Unknown API error',\n\n\n // Error detail\n complete_error,\n\n\n // Traceability\n free_goods,\n\n messageId\n }\n });\n\n});\n\n\nreturn output;" + }, + "type": "n8n-nodes-base.code", + "typeVersion": 2, + "position": [ + -672, + 96 + ], + "id": "864137a6-b9cb-4e21-bcc2-1f2543d04fda", + "name": "Flatten Data for Log2", + "onError": "continueRegularOutput" + }, + { + "parameters": { + "operation": "append", + "documentId": { + "__rl": true, + "value": "1cwLXlwmCPC7zUVOIQFWwRED4uqF3WZHVagGbBtKyVgQ", + "mode": "list", + "cachedResultName": "Invoice_Tracker_NEW", + "cachedResultUrl": "https://docs.google.com/spreadsheets/d/1cwLXlwmCPC7zUVOIQFWwRED4uqF3WZHVagGbBtKyVgQ/edit?usp=drivesdk" + }, + "sheetName": { + "__rl": true, + "value": 1691973413, + "mode": "list", + "cachedResultName": "Daily Logs", + "cachedResultUrl": "https://docs.google.com/spreadsheets/d/1cwLXlwmCPC7zUVOIQFWwRED4uqF3WZHVagGbBtKyVgQ/edit#gid=1691973413" + }, + "columns": { + "mappingMode": "defineBelow", + "value": { + "Date": "={{ $json.date }}", + "Time": "={{ $json.time }}", + "Status": "={{ $json.status }}", + "Complete Error / Null Values": "={{ $json.complete_error }}", + "Attachment Name": "={{ $('Wait 7s Before OCR2').item.json.attachment_name }}" + }, + "matchingColumns": [], + "schema": [ + { + "id": "Sr No.", + "displayName": "Sr No.", + "required": false, + "defaultMatch": false, + "display": true, + "type": "string", + "canBeUsedToMatch": true, + "removed": false + }, + { + "id": "Date", + "displayName": "Date", + "required": false, + "defaultMatch": false, + "display": true, + "type": "string", + "canBeUsedToMatch": true + }, + { + "id": "Time", + "displayName": "Time", + "required": false, + "defaultMatch": false, + "display": true, + "type": "string", + "canBeUsedToMatch": true + }, + { + "id": "Attachment Name", + "displayName": "Attachment Name", + "required": false, + "defaultMatch": false, + "display": true, + "type": "string", + "canBeUsedToMatch": true, + "removed": false + }, + { + "id": "Customer Name", + "displayName": "Customer Name", + "required": false, + "defaultMatch": false, + "display": true, + "type": "string", + "canBeUsedToMatch": true + }, + { + "id": "Invoice Amount (₹)", + "displayName": "Invoice Amount (₹)", + "required": false, + "defaultMatch": false, + "display": true, + "type": "string", + "canBeUsedToMatch": true + }, + { + "id": "Invoice ID", + "displayName": "Invoice ID", + "required": false, + "defaultMatch": false, + "display": true, + "type": "string", + "canBeUsedToMatch": true, + "removed": false + }, + { + "id": "Seller Name", + "displayName": "Seller Name", + "required": false, + "defaultMatch": false, + "display": true, + "type": "string", + "canBeUsedToMatch": true + }, + { + "id": "Status", + "displayName": "Status", + "required": false, + "defaultMatch": false, + "display": true, + "type": "string", + "canBeUsedToMatch": true + }, + { + "id": "GRN Message ", + "displayName": "GRN Message ", + "required": false, + "defaultMatch": false, + "display": true, + "type": "string", + "canBeUsedToMatch": true, + "removed": false + }, + { + "id": "Seller GSTIN", + "displayName": "Seller GSTIN", + "required": false, + "defaultMatch": false, + "display": true, + "type": "string", + "canBeUsedToMatch": true + }, + { + "id": "Free Goods", + "displayName": "Free Goods", + "required": false, + "defaultMatch": false, + "display": true, + "type": "string", + "canBeUsedToMatch": true, + "removed": false + }, + { + "id": "Complete Error / Null Values", + "displayName": "Complete Error / Null Values", + "required": false, + "defaultMatch": false, + "display": true, + "type": "string", + "canBeUsedToMatch": true, + "removed": false + } + ], + "attemptToConvertTypes": false, + "convertFieldsToString": false + }, + "options": { + "cellFormat": "USER_ENTERED", + "useAppend": true + } + }, + "type": "n8n-nodes-base.googleSheets", + "typeVersion": 4.7, + "position": [ + -896, + 384 + ], + "id": "b12ab90f-240b-4845-ac94-dada14ce001f", + "name": "Append row in sheet5", + "credentials": { + "googleSheetsOAuth2Api": { + "id": "OGnPiaQp3eu9tWvW", + "name": "Google Sheets account" + } + }, + "onError": "continueRegularOutput" + }, + { + "parameters": { + "jsCode": "// ═══════════════════════════════════════════════════════════════\n// Flatten AI Classification Error for Log\n// Placed BEFORE: Append row in sheet1\n// Receives: Switch2 → error route (classification = \"error\")\n//\n// This fires when the AI provider completely fails to classify\n// the email — API down, quota hit, empty response, parse failure.\n//\n// Uses IDENTICAL complete_error format as Flatten Data for Log2:\n// Error Type : API Blocked — Project Suspended (403)\n// Error From : [AI INDIA]\n// ─────────────────────────────────\n// Raw API error : AGENT_ERROR: 403 PERMISSION_DENIED...\n//\n// NOTE: Category labels are intentionally generic (\"API Error...\")\n// and do NOT mention the underlying provider name (e.g. Gemini)\n// in the output. The raw error text in \"Raw API error\" is left\n// untouched since that's just the upstream message, not a label.\n// ═══════════════════════════════════════════════════════════════\n\n// ── Error classifier ──────────────────────────────────────────\nfunction classifyAIError(errorDetail) {\n const text = String(errorDetail || '');\n const cb = text.toLowerCase();\n\n function hasCode(code) {\n const c = String(code).replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n return new RegExp('(^|[^0-9])' + c + '([^0-9]|$)').test(text);\n }\n\n // 403 Lightning Dunning (most specific — before generic 403)\n if (hasCode(403) && cb.includes('lightning dunning'))\n return { owner: 'AI INDIA', category: 'API Blocked — Project Suspended (403)' };\n\n // 403 / 401 / Permission denied\n if (hasCode(403) || hasCode(401) || cb.includes('permission_denied') || cb.includes('forbidden'))\n return { owner: 'AI INDIA', category: 'API Permission Denied (403)' };\n\n // 429 / Quota / Rate limit\n if (hasCode(429) || cb.includes('quota') || cb.includes('rate limit') ||\n cb.includes('too many requests') || cb.includes('resource has been exhausted') ||\n cb.includes('generate_requests_per_model_per_day'))\n return { owner: 'AI INDIA', category: 'API Quota / Rate Limit (429)' };\n\n // 504 / Timeout\n if (hasCode(504) || cb.includes('gateway timeout') || cb.includes('etimedout') ||\n cb.includes('socket hang up') || cb.includes('300000ms') || cb.includes('deadline expired'))\n return { owner: 'AI INDIA', category: 'API Timeout (504)' };\n\n // 500 server error\n if (hasCode(500) || cb.includes('internal server error'))\n return { owner: 'AI INDIA', category: 'API Server Error (500)' };\n\n // Empty / no response\n if (cb.includes('empty_ai_response') || cb.includes('empty'))\n return { owner: 'AI INDIA', category: 'API Returned Empty Response' };\n\n // JSON / parse failure\n if (cb.includes('no_json_found') || cb.includes('parse_exception') ||\n cb.includes('json_parse_failed') || cb.includes('all_parse_attempts_failed'))\n return { owner: 'AI INDIA', category: 'API Response — JSON Parse Failed' };\n\n // Missing is_invoice field\n if (cb.includes('missing_is_invoice') || cb.includes('is_invoice_field_not_found'))\n return { owner: 'AI INDIA', category: 'API Response — Missing is_invoice Field' };\n\n // Agent-level error\n if (cb.includes('agent_error'))\n return { owner: 'AI INDIA', category: 'API Agent Error' };\n\n // Fallback\n return { owner: 'AI INDIA', category: 'AI Classification Error — Unclassified' };\n}\n\n// ── Build complete_error block ─────────────────────────────────\nfunction buildCompleteError(errorDetail) {\n const c = classifyAIError(errorDetail);\n const divider = '─────────────────────────────────';\n return [\n 'Error Type : ' + c.category,\n 'Error From : [' + c.owner + ']',\n divider,\n 'Raw API error : ' + (errorDetail || '(no error detail)')\n ].join('\\n');\n}\n\n// ── Resolve messageId — 4-source fallback ─────────────────────\nfunction resolveMessageId(item) {\n try { const v = $('Set messageId Field1').item.json.messageId; if (v) return String(v); } catch(e) {}\n try { const v = $('Switch2').item.json.id; if (v) return String(v); } catch(e) {}\n if (item.json.messageId) return String(item.json.messageId);\n if (item.json.id) return String(item.json.id);\n return '';\n}\n\n// ══════════════════════════════════════════════════════════════\n// MAIN\n// ══════════════════════════════════════════════════════════════\n\nconst output = [];\n\nitems.forEach(item => {\n\n const data = item.json;\n\n // IST Timestamp\n const now = new Date();\n const date = now.toLocaleDateString('en-CA', { timeZone: 'Asia/Kolkata' });\n const time = now.toLocaleTimeString('en-IN', { timeZone: 'Asia/Kolkata', hour12: true });\n\n const messageId = resolveMessageId(item);\n\n // Attachment name\n let attachment_name = '';\n try { attachment_name = $('Split: One Item Per Attachment3').item.json.attachment_name || ''; } catch(e) {}\n if (!attachment_name) attachment_name = data.attachment_name || '';\n\n // Read CORRECT field set by Parse AI Output (not data.error!)\n const errorDetail = data.error_detail || data.error || 'AI_CLASSIFICATION_FAILED';\n const complete_error = buildCompleteError(errorDetail);\n\n output.push({\n json: {\n // Timestamp\n date,\n time,\n\n // Invoice fields — all blank (AI never got to OCR)\n invoice_id: '',\n invoice_number: '',\n invoice_date: '',\n seller_name: '',\n seller_gstin: '',\n customer_name: '',\n invoice_amount: 0,\n attachment_name,\n\n // Status\n status: '❌ FAILED',\n grn_message: 'AI Classification Failed — Invoice not processed',\n\n // Error block — same format as all other rows\n complete_error,\n\n // Traceability\n messageId\n }\n });\n\n});\n\nreturn output;" + }, + "type": "n8n-nodes-base.code", + "typeVersion": 2, + "position": [ + -2016, + 384 + ], + "id": "88f8d70f-f8b0-4462-bf46-478f26a507df", + "name": "Code in JavaScript6", + "onError": "continueRegularOutput" + }, + { + "parameters": { + "rules": { + "values": [ + { + "conditions": { + "options": { + "caseSensitive": true, + "leftValue": "", + "typeValidation": "strict", + "version": 3 + }, + "conditions": [ + { + "leftValue": "={{ $json.classification }}", + "rightValue": "invoice", + "operator": { + "type": "string", + "operation": "equals" + }, + "id": "a4a14d24-2846-4497-85b2-d76b08ee5f3f" + } + ], + "combinator": "and" + } + }, + { + "conditions": { + "options": { + "caseSensitive": true, + "leftValue": "", + "typeValidation": "strict", + "version": 3 + }, + "conditions": [ + { + "id": "6e8cef57-3eb1-458e-a82c-82f914ff3ffb", + "leftValue": "={{ $json.classification }}", + "rightValue": "error", + "operator": { + "type": "string", + "operation": "equals" + } + } + ], + "combinator": "and" + } + }, + { + "conditions": { + "options": { + "caseSensitive": true, + "leftValue": "", + "typeValidation": "strict", + "version": 3 + }, + "conditions": [ + { + "id": "d6db0eb2-e8fa-4b20-b475-6b78e2bbb39e", + "leftValue": "={{ $json.classification }}", + "rightValue": "not_invoice", + "operator": { + "type": "string", + "operation": "equals" + } + } + ], + "combinator": "and" + } + } + ] + }, + "options": { + "fallbackOutput": "extra" + } + }, + "type": "n8n-nodes-base.switch", + "typeVersion": 3.4, + "position": [ + -2240, + 288 + ], + "id": "334b80a6-4e59-44b6-a627-536fc65ea1cd", + "name": "Switch2" + }, + { + "parameters": { + "operation": "move", + "messageId": "={{ $('Flatten Data for Log2').item.json.messageId }}", + "folderId": { + "__rl": true, + "value": "AQMkADAwATM0MDAAMi1hYzgzLTQxMQAyLTAwAi0wMAoALgAAA3R9Z7-WZCBHqvG_09flPEoBAJRkAPlTP4RNsddkpsHybkoAAAJodAAAAA==", + "mode": "list", + "cachedResultName": "Invoice_Failed", + "cachedResultUrl": "https://outlook.office365.com/mail/AQMkADAwATM0MDAAMi1hYzgzLTQxMQAyLTAwAi0wMAoALgAAA3R9Z7%2FWZCBHqvG_09flPEoBAJRkAPlTP4RNsddkpsHybkoAAAJodAAAAA%3D%3D" + } + }, + "type": "n8n-nodes-base.microsoftOutlook", + "typeVersion": 2, + "position": [ + 0, + 288 + ], + "id": "6ee14313-3f3a-447e-a7d5-cf15a29f972b", + "name": "Failed To add2", + "webhookId": "0d4c72df-2457-4462-aa2f-b53949022df8", + "credentials": { + "microsoftOutlookOAuth2Api": { + "id": "neYqnH7A2WPe5lTs", + "name": "Microsoft Outlook account" + } + }, + "onError": "continueRegularOutput" + }, + { + "parameters": { + "model": "openai/gpt-oss-120b", + "options": {} + }, + "type": "@n8n/n8n-nodes-langchain.lmChatGroq", + "typeVersion": 1, + "position": [ + -3360, + 1184 + ], + "id": "69adb603-b839-49a8-a652-79c28fc2dcdb", + "name": "Groq Chat Model1", + "credentials": { + "groqApi": { + "id": "5STjMY6aZDMipq2f", + "name": "Groq account" + } + } + }, + { + "parameters": { + "jsCode": "// ─── Filter: Skip Non-OCR-able Files ─────────────────────────────\n// Allows ONLY PDF, image, and CSV attachments to reach the next node.\n// Other files (DOCX, TXT, EML etc.) are dropped silently.\n// An empty output from this node = no call generated = safe no-op.\n// ──────────────────────────────────────────────────────────────────────\nconst ALLOWED_MIME_TYPES = [\n 'application/pdf',\n 'image/jpeg',\n 'image/jpg',\n 'image/png',\n 'image/tiff',\n 'image/webp',\n 'image/bmp',\n 'image/gif',\n 'text/csv', // ← added\n 'application/csv' // ← added (some systems send this for .csv)\n];\nconst ALLOWED_EXTENSIONS = [\n '.pdf', '.jpg', '.jpeg', '.png',\n '.tiff', '.tif', '.webp', '.bmp', '.gif',\n '.csv' // ← added\n];\nconst filtered = items.filter(item => {\n const binary = item.binary?.file;\n // ── No binary at all → skip (text-only email path) ──────────────\n if (!binary) {\n return false;\n }\n const mimeType = (binary.mimeType || '').toLowerCase();\n const fileName = (binary.fileName || item.json.attachment_name || '').toLowerCase();\n const lastDot = fileName.lastIndexOf('.');\n const ext = lastDot !== -1 ? fileName.slice(lastDot) : '';\n const isAllowedMime = ALLOWED_MIME_TYPES.some(m => mimeType.includes(m));\n const isAllowedExt = ALLOWED_EXTENSIONS.includes(ext);\n if (!isAllowedMime && !isAllowedExt) {\n console.log('[OCR-FILTER] BLOCKED | file: ' + (binary.fileName || 'unknown') + ' | mime: ' + (mimeType || 'none') + ' | ext: ' + (ext || 'none') + ' | Reason: not PDF, image, or CSV format');\n return false;\n }\n return true;\n});\n// Return empty array cleanly if nothing passes the filter\nreturn filtered;" + }, + "type": "n8n-nodes-base.code", + "typeVersion": 2, + "position": [ + -2016, + 192 + ], + "id": "90bed578-8c62-4c6b-a1d3-e10639a0f051", + "name": "Filter: Skip Non-OCR-able Files", + "disabled": true, + "onError": "continueRegularOutput" + }, + { + "parameters": { + "operation": "append", + "documentId": { + "__rl": true, + "value": "1cwLXlwmCPC7zUVOIQFWwRED4uqF3WZHVagGbBtKyVgQ", + "mode": "list", + "cachedResultName": "Invoice_Tracker_NEW", + "cachedResultUrl": "https://docs.google.com/spreadsheets/d/1cwLXlwmCPC7zUVOIQFWwRED4uqF3WZHVagGbBtKyVgQ/edit?usp=drivesdk" + }, + "sheetName": { + "__rl": true, + "value": 1691973413, + "mode": "list", + "cachedResultName": "Daily Logs", + "cachedResultUrl": "https://docs.google.com/spreadsheets/d/1cwLXlwmCPC7zUVOIQFWwRED4uqF3WZHVagGbBtKyVgQ/edit#gid=1691973413" + }, + "columns": { + "mappingMode": "defineBelow", + "value": { + "Date": "={{ $json.date }}", + "Time": "={{ $json.time }}", + "Attachment Name": "={{ $json.attachment_name }}", + "Invoice ID": "={{ $json.invoice_id }}", + "Customer Name": "={{ $json.customer_name }}", + "Invoice Amount (₹)": "={{ $json.invoice_amount }}", + "Seller Name": "={{ $json.seller_name }}", + "Status": "={{ $json.status }}", + "GRN Message ": "={{ $json.grn_message }}", + "Seller GSTIN": "={{ $json.seller_gstin }}", + "Free Goods": "={{ $json.free_goods }}", + "Complete Error / Null Values": "={{ $json.complete_error }}" + }, + "matchingColumns": [], + "schema": [ + { + "id": "Sr No.", + "displayName": "Sr No.", + "required": false, + "defaultMatch": false, + "display": true, + "type": "string", + "canBeUsedToMatch": true, + "removed": false + }, + { + "id": "Date", + "displayName": "Date", + "required": false, + "defaultMatch": false, + "display": true, + "type": "string", + "canBeUsedToMatch": true + }, + { + "id": "Time", + "displayName": "Time", + "required": false, + "defaultMatch": false, + "display": true, + "type": "string", + "canBeUsedToMatch": true + }, + { + "id": "Attachment Name", + "displayName": "Attachment Name", + "required": false, + "defaultMatch": false, + "display": true, + "type": "string", + "canBeUsedToMatch": true + }, + { + "id": "Customer Name", + "displayName": "Customer Name", + "required": false, + "defaultMatch": false, + "display": true, + "type": "string", + "canBeUsedToMatch": true + }, + { + "id": "Invoice Amount (₹)", + "displayName": "Invoice Amount (₹)", + "required": false, + "defaultMatch": false, + "display": true, + "type": "string", + "canBeUsedToMatch": true + }, + { + "id": "Invoice ID", + "displayName": "Invoice ID", + "required": false, + "defaultMatch": false, + "display": true, + "type": "string", + "canBeUsedToMatch": true + }, + { + "id": "Seller Name", + "displayName": "Seller Name", + "required": false, + "defaultMatch": false, + "display": true, + "type": "string", + "canBeUsedToMatch": true + }, + { + "id": "Status", + "displayName": "Status", + "required": false, + "defaultMatch": false, + "display": true, + "type": "string", + "canBeUsedToMatch": true + }, + { + "id": "GRN Message ", + "displayName": "GRN Message ", + "required": false, + "defaultMatch": false, + "display": true, + "type": "string", + "canBeUsedToMatch": true + }, + { + "id": "Seller GSTIN", + "displayName": "Seller GSTIN", + "required": false, + "defaultMatch": false, + "display": true, + "type": "string", + "canBeUsedToMatch": true + }, + { + "id": "Free Goods", + "displayName": "Free Goods", + "required": false, + "defaultMatch": false, + "display": true, + "type": "string", + "canBeUsedToMatch": true + }, + { + "id": "Complete Error / Null Values", + "displayName": "Complete Error / Null Values", + "required": false, + "defaultMatch": false, + "display": true, + "type": "string", + "canBeUsedToMatch": true + } + ], + "attemptToConvertTypes": false, + "convertFieldsToString": false + }, + "options": {} + }, + "type": "n8n-nodes-base.googleSheets", + "typeVersion": 4.7, + "position": [ + -448, + 96 + ], + "id": "54fc0189-5a1a-402b-93a0-9f575f730f32", + "name": "Log to Google Sheets (Daily Logs)2", + "retryOnFail": false, + "maxTries": 3, + "credentials": { + "googleSheetsOAuth2Api": { + "id": "OGnPiaQp3eu9tWvW", + "name": "Google Sheets account" + } + } + }, + { + "parameters": { + "options": { + "temperature": 0.4 + } + }, + "type": "@n8n/n8n-nodes-langchain.lmChatGoogleGemini", + "typeVersion": 1, + "position": [ + -3488, + 1184 + ], + "id": "5b645a7b-acc2-46f6-88e5-82d8d79a8986", + "name": "Google Gemini Chat Model", + "credentials": { + "googlePalmApi": { + "id": "8wBnH32SbKmjkfYp", + "name": "Google Gemini(PaLM) Api account" + } + } + }, + { + "parameters": { + "jsCode": "// ═══════════════════════════════════════════════════════════════════\n// Flatten OCR Error for Log\n// Placed BEFORE: Append row in sheet5\n// Receives: OCR Extraction Valid?2 → FALSE branch\n//\n// Produces the SAME complete_error format as Flatten Data for Log2:\n//\n// Error Type : Invalid File Type (400)\n// Error From : [DMH]\n// ─────────────────────────────────\n// Raw API error : 400 - {\"error\":\"Invalid file type\"}\n//\n// Correctly classifies all OCR errors including:\n// 403 PERMISSION_DENIED → AI INDIA (Server Issue)\n// 400 Invalid file type → DMH\n// 504 Gateway Timeout → AI INDIA\n// 500 Server Crash → AI INDIA\n// PIL image error → AI INDIA\n// PO number missing → DMH\n// Duplicate Invoice → DMH\n// ═══════════════════════════════════════════════════════════════════\n\n// ── Helper: safe word-boundary HTTP status code check ────────────\n// Prevents \"400\" matching \"14005\" or UNKNOWN_ERROR400 from the prefix\nfunction hasHttpCode(text, code) {\n const c = String(code).replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n return new RegExp('(^|[^0-9])' + c + '([^0-9]|$)').test(String(text || ''));\n}\n\n// ── Error classifier ───────────────────────────────────────────────\n// Returns: { owner: \"AI INDIA\"|\"DMH\", category: string, detail: string }\nfunction classifyError(rawError) {\n const text = String(rawError || '');\n const cb = text.toLowerCase();\n const raw = text.trim();\n\n if (!cb.trim()) return { owner: 'AI INDIA', category: 'Unknown OCR Error', detail: '(no error message)' };\n\n // ── DMH: Invalid File Type (400) ───────────────────────────────\n // File format not accepted — DMH responsibility\n if (hasHttpCode(text, 400) && cb.includes('invalid file type'))\n return { owner: 'DMH', category: 'Invalid File Type (400)', detail: raw };\n\n // ── DMH: PO Number Missing ──────────────────────────────────────\n // Invoice rejected due to missing PO — DMH responsibility\n if (cb.includes('po number') || cb.includes('po number is missing') ||\n cb.includes('invoice rejected') || cb.includes('valid po number'))\n return { owner: 'DMH', category: 'Invoice Rejected — PO Number Missing', detail: raw };\n\n // ── DMH: Duplicate Invoice ──────────────────────────────────────\n if (cb.includes('duplicate invoice') || cb.includes('already processed') ||\n cb.includes('already exists'))\n return { owner: 'DMH', category: 'Duplicate Invoice', detail: raw };\n\n // ── AI INDIA: Server Issue (Lightning Dunning) ──────────────────\n // Most specific 403 check — must come BEFORE generic 403\n if (hasHttpCode(text, 403) && cb.includes('lightning dunning'))\n return { owner: 'AI INDIA', category: 'API Blocked — Server Issue (403)', detail: raw };\n\n // ── AI INDIA: Server Issue Permission Denied / Quota / Auth ────\n if (hasHttpCode(text, 403) || hasHttpCode(text, 401) || hasHttpCode(text, 429) ||\n cb.includes('permission_denied') ||\n cb.includes('generativelanguage.googleapis') ||\n cb.includes('quota') || cb.includes('rate limit') ||\n cb.includes('resource has been exhausted') ||\n cb.includes('unauthorized') || cb.includes('forbidden'))\n return { owner: 'AI INDIA', category: 'API Error — Server Issue', detail: raw };\n\n // ── AI INDIA: Generic 400 Bad Request ──────────────────────────\n if (hasHttpCode(text, 400))\n return { owner: 'AI INDIA', category: 'Bad Request to OCR API (400)', detail: raw };\n\n // ── AI INDIA: Timeout / Gateway ────────────────────────────────\n if (hasHttpCode(text, 504) ||\n cb.includes('gateway time-out') || cb.includes('gateway timeout') ||\n cb.includes('etimedout') || cb.includes('econnrefused') ||\n cb.includes('socket hang up') || cb.includes('300000ms') ||\n cb.includes('deadline expired') || cb.includes('connect timeout') ||\n cb.includes('read timeout'))\n return { owner: 'AI INDIA', category: 'OCR API Timeout / Gateway Error (504)', detail: raw };\n\n // ── AI INDIA: File Too Large (413) ─────────────────────────────\n if (hasHttpCode(text, 413) || cb.includes('request entity too large') ||\n cb.includes('payload too large') || cb.includes('file size exceeds'))\n return { owner: 'AI INDIA', category: 'File Too Large (413)', detail: raw };\n\n // ── AI INDIA: Server Crash (500) ───────────────────────────────\n if (hasHttpCode(text, 500) &&\n (cb.includes('internal server error') || cb.includes('nginx') ||\n cb.includes('werkzeug') || cb.includes('traceback')))\n return { owner: 'AI INDIA', category: 'OCR Server Internal Crash (500)', detail: raw };\n\n // ── AI INDIA: Invalid Image Format (PIL) ───────────────────────\n if (cb.includes('pil') || cb.includes('pngimageplugin') ||\n cb.includes('cannot identify image') || cb.includes('image file is truncated'))\n return { owner: 'AI INDIA', category: 'Invalid Image Format (PIL Error)', detail: raw };\n\n // ── AI INDIA: No Binary File ────────────────────────────────────\n if ((cb.includes('binary file') && cb.includes('none was found')) ||\n cb.includes('no file was uploaded') || cb.includes('missing file attachment'))\n return { owner: 'AI INDIA', category: 'No Binary File Found', detail: raw };\n\n // ── AI INDIA: OCR Extraction Failed ────────────────────────────\n if (cb.includes('ocr extraction failed') || cb.includes('extraction failed') ||\n cb.includes('could not extract') || cb.includes('parse failure') ||\n cb.includes('ocr_parse_error') || cb.includes('pdf parse') ||\n cb.includes('unknown processing error'))\n return { owner: 'AI INDIA', category: 'OCR Extraction Failed', detail: raw };\n\n // ── AI INDIA: OCR — Missing invoice_number (validation fail) ───\n if (cb.includes('invoice_number') || cb.includes('invoice number'))\n return { owner: 'AI INDIA', category: 'OCR — invoice_number Missing or Empty', detail: raw };\n\n // ── Fallback ────────────────────────────────────────────────────\n return { owner: 'AI INDIA', category: 'OCR Error — Unclassified', detail: raw };\n}\n\n// ── Build complete_error block ──────────────────────────────────────\n//\n// Error Type : Invalid File Type (400)\n// Error From : [DMH]\n// ─────────────────────────────────\n// Raw API error : 400 - {\"error\":\"Invalid file type\"}\n//\nfunction buildCompleteError(rawError) {\n const c = classifyError(rawError);\n const divider = '─────────────────────────────────';\n return [\n 'Error Type : ' + c.category,\n 'Error From : [' + c.owner + ']',\n divider,\n 'Raw API error : ' + (c.detail || '(no raw message)')\n ].join('\\n');\n}\n\n// ── Resolve messageId — 4-source fallback ──────────────────────────\nfunction resolveMessageId(item) {\n try { const v = $('Set messageId Field1').item.json.messageId; if (v) return String(v); } catch(e) {}\n try { const v = $('Switch2').item.json.id; if (v) return String(v); } catch(e) {}\n if (item.json.messageId) return String(item.json.messageId);\n if (item.json.id) return String(item.json.id);\n return '';\n}\n\n// ── Normalize raw error from item.json.error ───────────────────────\nfunction extractRawError(data) {\n if (!data.error) return '(no error message)';\n if (typeof data.error === 'string') return data.error;\n if (typeof data.error === 'object') {\n return data.error.message || data.error.description || JSON.stringify(data.error);\n }\n return String(data.error);\n}\n\n// ════════════════════════════════════════════════════════════════════\n// MAIN\n// ════════════════════════════════════════════════════════════════════\n\nconst output = [];\n\nitems.forEach(item => {\n\n const data = item.json;\n\n // ── IST Timestamp ──────────────────────────────────────────────\n const now = new Date();\n const date = now.toLocaleDateString('en-CA', { timeZone: 'Asia/Kolkata' });\n const time = now.toLocaleTimeString('en-IN', { timeZone: 'Asia/Kolkata', hour12: true });\n\n // ── messageId ──────────────────────────────────────────────────\n const messageId = resolveMessageId(item);\n\n // ── Attachment name ────────────────────────────────────────────\n let attachment_name = '';\n try { attachment_name = $('Split: One Item Per Attachment3').item.json.attachment_name || ''; } catch(e) {}\n if (!attachment_name) attachment_name = data.attachment_name || '';\n\n // ── Build error string ─────────────────────────────────────────\n const rawError = extractRawError(data);\n const complete_error = buildCompleteError(rawError);\n\n // ── Output — SAME columns as main sheet ───────────────────────\n output.push({\n json: {\n // Timestamp\n date,\n time,\n\n // Invoice fields — all blank (OCR failed, nothing extracted)\n invoice_id: '',\n invoice_number: '',\n invoice_date: '',\n seller_name: '',\n seller_gstin: '',\n customer_name: '',\n invoice_amount: 0,\n attachment_name,\n\n // Status\n status: '❌ FAILED',\n grn_message: 'OCR Extraction Failed — Server Issue — Invoice not processed',\n\n // Error block\n complete_error,\n\n // Traceability\n messageId\n }\n });\n\n});\n\nreturn output;" + }, + "type": "n8n-nodes-base.code", + "typeVersion": 2, + "position": [ + -1120, + 384 + ], + "id": "6402173a-44c3-4233-b394-0581d4f47f89", + "name": "Flatten OCR Error for Log", + "onError": "continueRegularOutput" + }, + { + "id": "3b533f17-2607-4b4d-80d2-f37ff47d30c0", + "name": "Router: Classify Invoice Condition", + "type": "n8n-nodes-base.code", + "typeVersion": 2, + "position": [ + -1120, + 96 + ], + "parameters": { + "mode": "runOnceForEachItem", + "jsCode": "function isPOValid(po) {\n if (!po) return false;\n const s = po.toString().trim().toLowerCase();\n return s.length > 0 && !['n/a','na','-','0','null','nil','none','undefined','not found',''].includes(s);\n}\n\nreturn items.map(item => {\n const inv = item.json;\n const po_present = isPOValid(inv.PO_number);\n const itemList = Array.isArray(inv.items) ? inv.items : [];\n const item_code_present = itemList.length > 0 && itemList.every(i => (i.item_code || '').toString().trim() !== '');\n\n let route = 1;\n if (po_present && item_code_present) {\n route = 1; // Condition 1: Direct GRN\n } else if (po_present && !item_code_present) {\n route = 2; // Condition 2 or 3: Fetch PO Details API first\n } else if (!po_present && item_code_present) {\n route = 4; // Condition 4: Manual PO Approval Queue\n } else {\n route = 5; // Condition 5: Manual PO Approval Queue\n }\n\n return {\n json: {\n ...inv,\n _route: route,\n _po_present: po_present,\n _item_code_present: item_code_present\n }\n };\n});" + } + }, + { + "id": "ba1e5bd5-01a7-4266-82bb-4576c57199e6", + "name": "Switch: 4-Way Condition Router", + "type": "n8n-nodes-base.switch", + "typeVersion": 3, + "position": [ + -800, + 96 + ], + "parameters": { + "mode": "rules", + "rules": { + "rules": [ + { + "conditions": { + "options": { + "caseSensitive": true, + "leftValue": "", + "typeValidation": "strict" + }, + "conditions": [ + { + "id": "b017fe4a-1f29-41e6-a01d-1c400e5e2211", + "leftValue": "={{ $json._route }}", + "rightValue": 1, + "operator": { + "type": "number", + "operation": "equals" + } + } + ] + }, + "renameOutput": true, + "outputKey": "Condition 1 — Direct GRN" + }, + { + "conditions": { + "options": { + "caseSensitive": true, + "leftValue": "", + "typeValidation": "strict" + }, + "conditions": [ + { + "id": "cd47adf8-aea5-4a6e-9b1e-92225ebab209", + "leftValue": "={{ $json._route }}", + "rightValue": 2, + "operator": { + "type": "number", + "operation": "equals" + } + } + ] + }, + "renameOutput": true, + "outputKey": "Condition 2/3 — Fetch PO Details" + }, + { + "conditions": { + "options": { + "caseSensitive": true, + "leftValue": "", + "typeValidation": "strict" + }, + "conditions": [ + { + "id": "73178f10-c3c2-4df2-b1d1-eecd2aeb4bf1", + "leftValue": "={{ $json._route }}", + "rightValue": 4, + "operator": { + "type": "number", + "operation": "equals" + } + } + ] + }, + "renameOutput": true, + "outputKey": "Condition 4 — Manual PO Approval" + }, + { + "conditions": { + "options": { + "caseSensitive": true, + "leftValue": "", + "typeValidation": "strict" + }, + "conditions": [ + { + "id": "49a06089-1d42-436d-923d-ddbf0318e889", + "leftValue": "={{ $json._route }}", + "rightValue": 5, + "operator": { + "type": "number", + "operation": "equals" + } + } + ] + }, + "renameOutput": true, + "outputKey": "Condition 5 — Manual PO & Item Approval" + } + ] + }, + "options": {} + } + }, + { + "id": "5376696e-1a21-41d3-96fa-30766c45e72b", + "name": "HTTP: Fetch DMH PO Details", + "type": "n8n-nodes-base.httpRequest", + "typeVersion": 4.2, + "position": [ + -800, + -200 + ], + "parameters": { + "method": "GET", + "url": "={{ $env.DMH_PO_DETAILS_API_URL || 'https://mapp.dmhospital.org/dmhApiRef/po/getPoDetails.php' }}", + "sendHeaders": true, + "headerParameters": { + "parameters": [ + { + "name": "x-api-key", + "value": "={{ $env.DMH_PO_DETAILS_API_KEY || 'nirajAi26@DMH' }}" + } + ] + }, + "sendQuery": true, + "queryParameters": { + "parameters": [ + { + "name": "po_number", + "value": "={{ $json.PO_number }}" + } + ] + }, + "options": { + "response": { + "response": { + "responseFormat": "json" + } + }, + "timeout": 15000 + } + } + }, + { + "id": "3a164cf6-4572-458f-b6aa-f0a5e4797536", + "name": "Code: Merge PO Item Codes", + "type": "n8n-nodes-base.code", + "typeVersion": 2, + "position": [ + -400, + -200 + ], + "parameters": { + "mode": "runOnceForEachItem", + "jsCode": "// Merges item codes from DMH PO Details API\n// If item codes are found -> _condition = 2 (Proceed to GRN)\n// If item codes NOT found -> _condition = 3 (Route to Manual Item Code Approval)\nreturn items.map(item => {\n const inv = item.json;\n const poResponse = inv.data || inv;\n const poItems = poResponse.items || poResponse.data?.items || [];\n const originalItems = inv.items || [];\n\n const codeMap = {};\n poItems.forEach(pi => {\n const key = (pi.description || pi.item_name || pi.name || '').toLowerCase().trim();\n if (key && pi.item_code) codeMap[key] = pi.item_code;\n });\n\n let anyFound = false;\n const mergedItems = originalItems.map(oi => {\n const key = (oi.description || '').toLowerCase().trim();\n const foundCode = codeMap[key] || oi.item_code || '';\n if (foundCode) anyFound = true;\n return {\n ...oi,\n item_code: foundCode\n };\n });\n\n const condition = anyFound ? 2 : 3;\n return {\n json: {\n ...inv,\n items: mergedItems,\n _condition: condition,\n _item_codes_found: anyFound\n }\n };\n});" + } + }, + { + "id": "0bd30100-a417-44eb-bbec-b087bab1b6fd", + "name": "HTTP: Post to Pharmacy Dashboard (C3)", + "type": "n8n-nodes-base.httpRequest", + "typeVersion": 4.2, + "position": [ + -800, + 300 + ], + "parameters": { + "method": "POST", + "url": "={{ $env.PHARMACY_DASHBOARD_URL || 'http://localhost:5000' }}/api/po-approval/submit", + "sendHeaders": true, + "headerParameters": { + "parameters": [ + { + "name": "Content-Type", + "value": "application/json" + }, + { + "name": "X-API-Key", + "value": "={{ $env.N8N_WEBHOOK_SECRET }}" + } + ] + }, + "sendBody": true, + "specifyBody": "json", + "jsonBody": "={{ JSON.stringify({ extraction_id: null, invoice_number: $json.invoice_number, vendor_name: $json.seller_name, invoice_date: $json.invoice_date, invoice_filename: $json.invoice_id || '', po_number_original: $json.PO_number, condition_type: 'condition_3', items: $json.items, full_invoice: $json }) }}", + "options": { + "timeout": 15000 + } + } + }, + { + "id": "eeb4a3d1-6fce-4f87-87c9-45546945ae89", + "name": "HTTP: Post to Pharmacy Dashboard (C4)", + "type": "n8n-nodes-base.httpRequest", + "typeVersion": 4.2, + "position": [ + -800, + 500 + ], + "parameters": { + "method": "POST", + "url": "={{ $env.PHARMACY_DASHBOARD_URL || 'http://localhost:5000' }}/api/po-approval/submit", + "sendHeaders": true, + "headerParameters": { + "parameters": [ + { + "name": "Content-Type", + "value": "application/json" + }, + { + "name": "X-API-Key", + "value": "={{ $env.N8N_WEBHOOK_SECRET }}" + } + ] + }, + "sendBody": true, + "specifyBody": "json", + "jsonBody": "={{ JSON.stringify({ extraction_id: null, invoice_number: $json.invoice_number, vendor_name: $json.seller_name, invoice_date: $json.invoice_date, invoice_filename: $json.invoice_id || '', po_number_original: $json.PO_number, condition_type: 'condition_4', items: $json.items, full_invoice: $json }) }}", + "options": { + "timeout": 15000 + } + } + }, + { + "id": "11137476-ca21-4bd6-9d7e-d4f6af3097b1", + "name": "Switch: Condition 2 vs 3", + "type": "n8n-nodes-base.switch", + "typeVersion": 3, + "position": [ + -100, + -200 + ], + "parameters": { + "mode": "rules", + "rules": { + "rules": [ + { + "conditions": { + "options": { + "caseSensitive": true, + "leftValue": "", + "typeValidation": "strict" + }, + "conditions": [ + { + "id": "fb7b7103-90f0-4e73-9706-2e8ac1d549e0", + "leftValue": "={{ $json._condition }}", + "rightValue": 2, + "operator": { + "type": "number", + "operation": "equals" + } + } + ] + }, + "renameOutput": true, + "outputKey": "Condition 2 (Codes Found -> GRN)" + }, + { + "conditions": { + "options": { + "caseSensitive": true, + "leftValue": "", + "typeValidation": "strict" + }, + "conditions": [ + { + "id": "52755876-80b6-496a-bc22-278a76bfc4af", + "leftValue": "={{ $json._condition }}", + "rightValue": 3, + "operator": { + "type": "number", + "operation": "equals" + } + } + ] + }, + "renameOutput": true, + "outputKey": "Condition 3 (Codes Not Found -> Pharmacy Dashboard)" + } + ] + }, + "options": {} + } + }, + { + "id": "7b477b4b-d4b5-4fb7-8e23-8023cc84714e", + "name": "HTTP: Post to Pharmacy Dashboard (C5)", + "type": "n8n-nodes-base.httpRequest", + "typeVersion": 4.2, + "position": [ + -800, + 700 + ], + "parameters": { + "method": "POST", + "url": "={{ $env.PHARMACY_DASHBOARD_URL || 'http://localhost:5000' }}/api/po-approval/submit", + "sendHeaders": true, + "headerParameters": { + "parameters": [ + { + "name": "Content-Type", + "value": "application/json" + }, + { + "name": "X-API-Key", + "value": "={{ $env.N8N_WEBHOOK_SECRET }}" + } + ] + }, + "sendBody": true, + "specifyBody": "json", + "jsonBody": "={{ JSON.stringify({ extraction_id: null, invoice_number: $json.invoice_number, vendor_name: $json.seller_name, invoice_date: $json.invoice_date, invoice_filename: $json.invoice_id || '', po_number_original: $json.PO_number, condition_type: 'condition_5', items: $json.items, full_invoice: $json }) }}", + "options": { + "timeout": 15000 + } + } + } + ], + "connections": { + "Append row in sheet1": { + "main": [ + [ + { + "node": "Loop: Each Attachment2", + "type": "main", + "index": 0 + } + ] + ] + }, + "Watch New_Invoice Label1": { + "main": [ + [ + { + "node": "Fetch Emails from New_Invoice (max 3)1", + "type": "main", + "index": 0 + } + ] + ] + }, + "AI: Classify Invoice1": { + "main": [ + [ + { + "node": "Merge: Email + AI Classification1", + "type": "main", + "index": 1 + } + ] + ] + }, + "OCR: Extract Invoice Data2": { + "main": [ + [ + { + "node": "OCR Extraction Valid?2", + "type": "main", + "index": 0 + } + ] + ] + }, + "Merge: Email + AI Classification1": { + "main": [ + [ + { + "node": "Split: One Item Per Attachment3", + "type": "main", + "index": 0 + } + ] + ] + }, + "Fetch Emails from New_Invoice (max 3)1": { + "main": [ + [ + { + "node": "Loop: Each Email2", + "type": "main", + "index": 0 + } + ] + ] + }, + "Loop: Each Email2": { + "main": [ + [ + { + "node": "Label: Add Processing2", + "type": "main", + "index": 0 + } + ], + [ + { + "node": "End: No More Emails1", + "type": "main", + "index": 0 + } + ] + ] + }, + "End: No More Emails1": { + "main": [ + [ + { + "node": "Loop: Each Email2", + "type": "main", + "index": 0 + } + ] + ] + }, + "Label: Add Processing2": { + "main": [ + [ + { + "node": "Label: Remove New_Invoice1", + "type": "main", + "index": 0 + } + ] + ] + }, + "Label: Remove New_Invoice1": { + "main": [ + [ + { + "node": "Fetch Full Email + Attachments2", + "type": "main", + "index": 0 + } + ] + ] + }, + "Fetch Full Email + Attachments2": { + "main": [ + [ + { + "node": "Set messageId Field1", + "type": "main", + "index": 0 + }, + { + "node": "AI: Classify Invoice1", + "type": "main", + "index": 0 + } + ] + ] + }, + "Parse AI Output2": { + "main": [ + [ + { + "node": "Switch2", + "type": "main", + "index": 0 + } + ] + ] + }, + "Set messageId Field1": { + "main": [ + [ + { + "node": "Merge: Email + AI Classification1", + "type": "main", + "index": 0 + } + ] + ] + }, + "Label: Add Not_Invoice2": { + "main": [ + [ + { + "node": "Loop: Each Attachment2", + "type": "main", + "index": 0 + } + ] + ] + }, + "Label: Add Invoice_Done2": { + "main": [ + [ + { + "node": "Loop: Each Attachment2", + "type": "main", + "index": 0 + } + ] + ] + }, + "Label: Add Invoice_failed2": { + "main": [ + [ + { + "node": "Loop: Each Attachment2", + "type": "main", + "index": 0 + } + ] + ] + }, + "OCR Extraction Valid?2": { + "main": [ + [ + { + "node": "Normalize Invoice Fields2", + "type": "main", + "index": 0 + } + ], + [ + { + "node": "Flatten OCR Error for Log", + "type": "main", + "index": 0 + } + ] + ] + }, + "GRN: Create Record in Hospital2": { + "main": [ + [ + { + "node": "Flatten Data for Log2", + "type": "main", + "index": 0 + } + ] + ] + }, + "Normalize Invoice Fields2": { + "main": [ + [ + { + "node": "Router: Classify Invoice Condition", + "type": "main", + "index": 0 + } + ] + ] + }, + "GRN Created Successfully?2": { + "main": [ + [ + { + "node": "Label: Add Invoice_Done2", + "type": "main", + "index": 0 + } + ], + [ + { + "node": "Failed To add2", + "type": "main", + "index": 0 + } + ] + ] + }, + "Split: One Item Per Attachment3": { + "main": [ + [ + { + "node": "Loop: Each Attachment2", + "type": "main", + "index": 0 + } + ] + ] + }, + "Loop: Each Attachment2": { + "main": [ + [], + [ + { + "node": "Parse AI Output2", + "type": "main", + "index": 0 + } + ] + ] + }, + "Wait 7s Before OCR2": { + "main": [ + [ + { + "node": "OCR: Extract Invoice Data2", + "type": "main", + "index": 0 + } + ] + ] + }, + "Flatten Data for Log2": { + "main": [ + [ + { + "node": "Log to Google Sheets (Daily Logs)2", + "type": "main", + "index": 0 + } + ] + ] + }, + "Append row in sheet5": { + "main": [ + [ + { + "node": "Label: Add Invoice_failed2", + "type": "main", + "index": 0 + } + ] + ] + }, + "Code in JavaScript6": { + "main": [ + [ + { + "node": "Append row in sheet1", + "type": "main", + "index": 0 + } + ] + ] + }, + "Switch2": { + "main": [ + [ + { + "node": "Filter: Skip Non-OCR-able Files", + "type": "main", + "index": 0 + } + ], + [ + { + "node": "Code in JavaScript6", + "type": "main", + "index": 0 + } + ], + [ + { + "node": "Label: Add Not_Invoice2", + "type": "main", + "index": 0 + } + ], + [ + { + "node": "Code in JavaScript6", + "type": "main", + "index": 0 + } + ] + ] + }, + "Filter: Skip Non-OCR-able Files": { + "main": [ + [ + { + "node": "Wait 7s Before OCR2", + "type": "main", + "index": 0 + } + ] + ] + }, + "Failed To add2": { + "main": [ + [ + { + "node": "Loop: Each Attachment2", + "type": "main", + "index": 0 + } + ] + ] + }, + "Groq Chat Model1": { + "ai_languageModel": [ + [ + { + "node": "AI: Classify Invoice1", + "type": "ai_languageModel", + "index": 1 + } + ] + ] + }, + "Log to Google Sheets (Daily Logs)2": { + "main": [ + [ + { + "node": "GRN Created Successfully?2", + "type": "main", + "index": 0 + } + ] + ] + }, + "Google Gemini Chat Model": { + "ai_languageModel": [ + [ + { + "node": "AI: Classify Invoice1", + "type": "ai_languageModel", + "index": 0 + } + ] + ] + }, + "Flatten OCR Error for Log": { + "main": [ + [ + { + "node": "Append row in sheet5", + "type": "main", + "index": 0 + } + ] + ] + }, + "Router: Classify Invoice Condition": { + "main": [ + [ + { + "node": "Switch: 4-Way Condition Router", + "type": "main", + "index": 0 + } + ] + ] + }, + "Switch: 4-Way Condition Router": { + "main": [ + [ + { + "node": "GRN: Create Record in Hospital2", + "type": "main", + "index": 0 + } + ], + [ + { + "node": "HTTP: Fetch DMH PO Details", + "type": "main", + "index": 0 + } + ], + [ + { + "node": "HTTP: Post to Pharmacy Dashboard (C4)", + "type": "main", + "index": 0 + } + ], + [ + { + "node": "HTTP: Post to Pharmacy Dashboard (C5)", + "type": "main", + "index": 0 + } + ] + ] + }, + "HTTP: Fetch DMH PO Details": { + "main": [ + [ + { + "node": "Code: Merge PO Item Codes", + "type": "main", + "index": 0 + } + ] + ] + }, + "Code: Merge PO Item Codes": { + "main": [ + [ + { + "node": "Switch: Condition 2 vs 3", + "type": "main", + "index": 0 + } + ] + ] + }, + "HTTP: Post to Pharmacy Dashboard (C3)": { + "main": [ + [] + ] + }, + "HTTP: Post to Pharmacy Dashboard (C4)": { + "main": [ + [] + ] + }, + "Switch: Condition 2 vs 3": { + "main": [ + [ + { + "node": "GRN: Create Record in Hospital2", + "type": "main", + "index": 0 + } + ], + [ + { + "node": "HTTP: Post to Pharmacy Dashboard (C3)", + "type": "main", + "index": 0 + } + ] + ] + }, + "HTTP: Post to Pharmacy Dashboard (C5)": { + "main": [ + [] + ] + } + }, + "settings": { + "executionOrder": "v1", + "binaryMode": "separate", + "timeSavedMode": "fixed", + "saveExecutionProgress": true, + "callerPolicy": "workflowsFromSameOwner", + "availableInMCP": false + }, + "staticData": { + "node:Watch New_Invoice Label1": { + "lastTimeChecked": "2026-11-18T15:51:37.013+05:30" + } + }, + "meta": { + "templateCredsSetupCompleted": true + }, + "nodeGroups": [], + "pinData": { + "Watch New_Invoice Label1": [ + { + "json": { + "id": "AQMkADAwATM0MDAAMi1hYzgzLTQxMQAyLTAwAi0wMAoARgAAA3R9Z7-WZCBHqvG_09flPEoHAJRkAPlTP4RNsddkpsHybkoAAAJoYgAAAJRkAPlTP4RNsddkpsHybkoAAAA5XQWtAAAA", + "conversationId": "AQQkADAwATM0MDAAMi1hYzgzLTQxMQAyLTAwAi0wMAoAEADgrABTb8JpRr-DRXapa6y6", + "subject": "Fw: Invoice", + "bodyPreview": "________________________________\r\nFrom: Kalpak Marketing Pvt. Ltd. \r\nSent: Friday, October 9, 2026 12:10 PM\r\nTo: MSS Purchase \r\nSubject: Invoice\r\n\r\nCAUTION: This email originated from outside of", + "from": "msspurchase@dmhospital.org", + "to": [ + "mss.receipt@dmhospital.org" + ], + "categories": [], + "hasAttachments": true + }, + "binary": { + "attachment_0": { + "mimeType": "application/pdf", + "fileType": "pdf", + "fileExtension": "pdf", + "data": "database", + "fileName": "New Doc 10-09-2026 12.10.pdf", + "id": "database:bca5fe77-cc9d-4e80-932f-62a367cd86a8", + "fileSize": "617 kB", + "bytes": 617324 + } + }, + "pairedItem": { + "item": 0 + } + } + ] + }, + "versionId": "76305287-8e74-4038-9a85-a6f909fc5b2d", + "activeVersionId": "e33393f4-a186-4ea6-8ab3-61c482ec228f", + "versionCounter": 93, + "triggerCount": 1, + "sourceWorkflowId": null, + "shared": [ + { + "updatedAt": "2026-09-15T07:46:14.929Z", + "createdAt": "2026-09-15T07:46:14.929Z", + "role": "workflow:owner", + "workflowId": "EyAw3kSLbeIEnpyf", + "projectId": "U9SnIeRl7eF0hSQX", + "project": { + "updatedAt": "2026-09-15T07:47:28.147Z", + "createdAt": "2026-09-15T07:43:05.605Z", + "id": "U9SnIeRl7eF0hSQX", + "name": "Invoice Aiindia ", + "type": "personal", + "icon": null, + "description": null, + "customTelemetryTags": [], + "creatorId": "9f578e99-f4de-457a-8344-b8c82fadc25d" + } + } + ], + "tags": [ + { + "updatedAt": "2026-09-15T07:46:09.800Z", + "createdAt": "2026-09-15T07:46:09.800Z", + "id": "Nca3jDpPX9nLSq7y", + "name": "production" + }, + { + "updatedAt": "2026-09-15T07:46:09.831Z", + "createdAt": "2026-09-15T07:46:09.831Z", + "id": "otaGZ3WSkv1hyy2B", + "name": "lead-intelligence" + }, + { + "updatedAt": "2026-09-15T07:46:09.831Z", + "createdAt": "2026-09-15T07:46:09.831Z", + "id": "q9n74oMLardp0TCD", + "name": "outlook" + }, + { + "updatedAt": "2026-09-15T07:46:09.838Z", + "createdAt": "2026-09-15T07:46:09.838Z", + "id": "TK1XnjFEsfCQ77ir", + "name": "SEO" + }, + { + "updatedAt": "2026-09-15T07:46:09.840Z", + "createdAt": "2026-09-15T07:46:09.840Z", + "id": "f3VP6ad1R0CDm31u", + "name": "v9-final" + }, + { + "updatedAt": "2026-09-15T07:46:09.844Z", + "createdAt": "2026-09-15T07:46:09.844Z", + "id": "841y4IviYcHFNWIM", + "name": "v25" + } + ], + "parentFolder": null, + "activeVersion": { + "updatedAt": "2026-10-10T10:33:00.659Z", + "createdAt": "2026-10-10T10:01:16.335Z", + "versionId": "e33393f4-a186-4ea6-8ab3-61c482ec228f", + "workflowId": "EyAw3kSLbeIEnpyf", + "nodes": [ + { + "parameters": { + "operation": "append", + "documentId": { + "__rl": true, + "value": "=1cwLXlwmCPC7zUVOIQFWwRED4uqF3WZHVagGbBtKyVgQ", + "mode": "id" + }, + "sheetName": { + "__rl": true, + "value": 1691973413, + "mode": "list", + "cachedResultName": "Daily Logs", + "cachedResultUrl": "https://docs.google.com/spreadsheets/d/1cwLXlwmCPC7zUVOIQFWwRED4uqF3WZHVagGbBtKyVgQ/edit#gid=1691973413" + }, + "columns": { + "mappingMode": "defineBelow", + "value": { + "Date": "={{ $json.date }}", + "Time": "={{ $json.time }}", + "Attachment Name": "={{ $json.attachment_name }}", + "Status": "={{ $json.status }}", + "GRN Message ": "={{ $json.grn_message }}", + "Complete Error / Null Values": "={{ $json.complete_error }}" + }, + "matchingColumns": [], + "schema": [ + { + "id": "Sr No.", + "displayName": "Sr No.", + "required": false, + "defaultMatch": false, + "display": true, + "type": "string", + "canBeUsedToMatch": true, + "removed": false + }, + { + "id": "Date", + "displayName": "Date", + "required": false, + "defaultMatch": false, + "display": true, + "type": "string", + "canBeUsedToMatch": true + }, + { + "id": "Time", + "displayName": "Time", + "required": false, + "defaultMatch": false, + "display": true, + "type": "string", + "canBeUsedToMatch": true + }, + { + "id": "Attachment Name", + "displayName": "Attachment Name", + "required": false, + "defaultMatch": false, + "display": true, + "type": "string", + "canBeUsedToMatch": true + }, + { + "id": "Customer Name", + "displayName": "Customer Name", + "required": false, + "defaultMatch": false, + "display": true, + "type": "string", + "canBeUsedToMatch": true + }, + { + "id": "Invoice Amount (₹)", + "displayName": "Invoice Amount (₹)", + "required": false, + "defaultMatch": false, + "display": true, + "type": "string", + "canBeUsedToMatch": true + }, + { + "id": "Invoice ID", + "displayName": "Invoice ID", + "required": false, + "defaultMatch": false, + "display": true, + "type": "string", + "canBeUsedToMatch": true + }, + { + "id": "Seller Name", + "displayName": "Seller Name", + "required": false, + "defaultMatch": false, + "display": true, + "type": "string", + "canBeUsedToMatch": true + }, + { + "id": "Status", + "displayName": "Status", + "required": false, + "defaultMatch": false, + "display": true, + "type": "string", + "canBeUsedToMatch": true + }, + { + "id": "GRN Message ", + "displayName": "GRN Message ", + "required": false, + "defaultMatch": false, + "display": true, + "type": "string", + "canBeUsedToMatch": true + }, + { + "id": "Seller GSTIN", + "displayName": "Seller GSTIN", + "required": false, + "defaultMatch": false, + "display": true, + "type": "string", + "canBeUsedToMatch": true + }, + { + "id": "Free Goods", + "displayName": "Free Goods", + "required": false, + "defaultMatch": false, + "display": true, + "type": "string", + "canBeUsedToMatch": true + }, + { + "id": "Complete Error / Null Values", + "displayName": "Complete Error / Null Values", + "required": false, + "defaultMatch": false, + "display": true, + "type": "string", + "canBeUsedToMatch": true + } + ], + "attemptToConvertTypes": false, + "convertFieldsToString": false + }, + "options": {} + }, + "type": "n8n-nodes-base.googleSheets", + "typeVersion": 4.7, + "position": [ + -1792, + 384 + ], + "id": "1550194a-e54a-4b53-8b77-aa2f3a946d74", + "name": "Append row in sheet1", + "credentials": { + "googleSheetsOAuth2Api": { + "id": "OGnPiaQp3eu9tWvW", + "name": "Google Sheets account" + } + } + }, + { + "parameters": { + "pollTimes": { + "item": [ + { + "mode": "everyMinute" + } + ] + }, + "filters": { + "foldersToInclude": [ + "AQMkADAwATM0MDAAMi1hYzgzLTQxMQAyLTAwAi0wMAoALgAAA3R9Z7-WZCBHqvG_09flPEoBAJRkAPlTP4RNsddkpsHybkoAAAJoYgAAAA==", + "AQMkADAwATM0MDAAMi1hYzgzLTQxMQAyLTAwAi0wMAoALgAAA3R9Z7-WZCBHqvG_09flPEoBAJRkAPlTP4RNsddkpsHybkoAAAJodQAAAA==", + "AQMkADAwATM0MDAAMi1hYzgzLTQxMQAyLTAwAi0wMAoALgAAA3R9Z7-WZCBHqvG_09flPEoBAJRkAPlTP4RNsddkpsHybkoAAAIBFgAAAA==" + ] + }, + "options": { + "downloadAttachments": true + } + }, + "type": "n8n-nodes-base.microsoftOutlookTrigger", + "typeVersion": 1, + "position": [ + -4832, + 1056 + ], + "id": "be7ad802-919e-41d8-bd76-d0291e5640dd", + "name": "Watch New_Invoice Label1", + "credentials": { + "microsoftOutlookOAuth2Api": { + "id": "neYqnH7A2WPe5lTs", + "name": "Microsoft Outlook account" + } + } + }, + { + "parameters": { + "promptType": "define", + "text": "=Email Subject:\n{{$json.subject}}\n\nEmail Body:\n{{$json.bodyPreview || $json.body.content}}\n\nSender Email:\n{{ $json.from }}\n\nAttachment File Name:\n{{$binary.attachment_0.fileName}}\n\nAttachment MIME Type:\n{{$binary.attachment_0.mimeType}}\n", + "needsFallback": true, + "options": { + "systemMessage": "You are an invoice recognition agent operating inside an automated workflow.\n\nYou will receive:\nEmail subject\nEmail body content (plain text or HTML converted to text)\nSender email address and name\nAttachment file name\nAttachment MIME type\n\nYour task:\nDetermine whether the email and its attachment should be treated as a BUSINESS INVOICE.\n\nClassification rules:\nClassify the email as an invoice if ANY billing, payment, receipt, tax, or business transaction context is present.\nThe word \"invoice\" may or may not appear explicitly.\nAttachment file names containing company or brand names (for example: BISLERI.pdf, TATA.pdf, AMAZON.pdf, A+V+TRADING.pdf) may represent invoices.\nIf the attachment MIME type is \"application/pdf\" and the email context is business-related, classify it as an invoice.\nIf there is reasonable doubt, classify the email as an invoice.\n\nHard constraints:\nDo NOT read or analyze PDF binary content.\nDo NOT perform OCR.\nDo NOT extract invoice numbers, dates, or amounts.\nNEVER return null or undefined.\nALWAYS return all fields.\nNEVER include markdown formatting.\nNEVER wrap the output in ```json or ``` blocks.\nNEVER include explanations, headings, or extra text.\n\nOutput requirements:\nReturn ONLY a single valid JSON object.\nThe response must start with { and end with }.\nThe output must be directly parseable using JSON.parse().\n\nReturn the response in this EXACT format:\n\n{\n \"is_invoice\": true or false,\n \"confidence\": \"high\" or \"medium\" or \"low\",\n \"reason\": \"\"\n}" + } + }, + "type": "@n8n/n8n-nodes-langchain.agent", + "typeVersion": 2.2, + "position": [ + -3488, + 960 + ], + "id": "f43530ad-adfa-41ba-b3e2-59c500b8931e", + "name": "AI: Classify Invoice1", + "alwaysOutputData": false, + "notesInFlow": false, + "retryOnFail": true, + "onError": "continueRegularOutput" + }, + { + "parameters": { + "method": "POST", + "url": "https://aiinfinite.in/process-invoice", + "sendHeaders": true, + "headerParameters": { + "parameters": [ + { + "name": "x-api-key", + "value": "971dcea6c47445f6f7405fa2d14e116b1d81dae6c10330571e8d4220c013b523" + } + ] + }, + "sendBody": true, + "contentType": "multipart-form-data", + "bodyParameters": { + "parameters": [ + { + "parameterType": "formBinaryData", + "name": "file", + "inputDataFieldName": "=file" + } + ] + }, + "options": {} + }, + "type": "n8n-nodes-base.httpRequest", + "typeVersion": 4.2, + "position": [ + -1568, + 192 + ], + "id": "bc668542-9d9c-4096-9750-777b7012a29b", + "name": "OCR: Extract Invoice Data2", + "alwaysOutputData": false, + "retryOnFail": true, + "waitBetweenTries": 5000, + "maxTries": 3, + "onError": "continueRegularOutput" + }, + { + "parameters": { + "mode": "combine", + "combineBy": "combineByPosition", + "options": {} + }, + "type": "n8n-nodes-base.merge", + "typeVersion": 3.2, + "position": [ + -3136, + 912 + ], + "id": "c3974a60-9c2b-476b-9283-7eb744b4501e", + "name": "Merge: Email + AI Classification1" + }, + { + "parameters": { + "operation": "getAll", + "limit": 3, + "filtersUI": { + "values": { + "filters": { + "foldersToInclude": [ + "AQMkADAwATM0MDAAMi1hYzgzLTQxMQAyLTAwAi0wMAoALgAAA3R9Z7-WZCBHqvG_09flPEoBAJRkAPlTP4RNsddkpsHybkoAAAJoYgAAAA==", + "AQMkADAwATM0MDAAMi1hYzgzLTQxMQAyLTAwAi0wMAoALgAAA3R9Z7-WZCBHqvG_09flPEoBAJRkAPlTP4RNsddkpsHybkoAAAIBFgAAAA==" + ] + } + } + }, + "options": { + "downloadAttachments": true + } + }, + "type": "n8n-nodes-base.microsoftOutlook", + "typeVersion": 2, + "position": [ + -4608, + 1056 + ], + "id": "939a1916-4d96-4550-9482-fd51209d060a", + "name": "Fetch Emails from New_Invoice (max 3)1", + "executeOnce": true, + "webhookId": "977ad40e-7150-4f6a-a351-e29c08eb4f97", + "credentials": { + "microsoftOutlookOAuth2Api": { + "id": "neYqnH7A2WPe5lTs", + "name": "Microsoft Outlook account" + } + } + }, + { + "parameters": { + "options": {} + }, + "type": "n8n-nodes-base.splitInBatches", + "typeVersion": 3, + "position": [ + -4384, + 1056 + ], + "id": "d71ef907-462d-4c40-bb01-2476d9cb7bf3", + "name": "Loop: Each Email2" + }, + { + "parameters": {}, + "type": "n8n-nodes-base.noOp", + "name": "End: No More Emails1", + "typeVersion": 1, + "position": [ + -4160, + 1104 + ], + "id": "90ad177b-23a6-41d0-86fe-fd3f3725e6d8" + }, + { + "parameters": { + "operation": "update", + "messageId": { + "__rl": true, + "value": "={{ $json.id }}", + "mode": "id" + }, + "updateFields": { + "folderId": { + "__rl": true, + "value": "AQMkADAwATM0MDAAMi1hYzgzLTQxMQAyLTAwAi0wMAoALgAAA3R9Z7-WZCBHqvG_09flPEoBAJRkAPlTP4RNsddkpsHybkoAAAJocQAAAA==", + "mode": "list", + "cachedResultName": "Processing", + "cachedResultUrl": "https://outlook.office365.com/mail/AQMkADAwATM0MDAAMi1hYzgzLTQxMQAyLTAwAi0wMAoALgAAA3R9Z7%2FWZCBHqvG_09flPEoBAJRkAPlTP4RNsddkpsHybkoAAAJocQAAAA%3D%3D" + } + } + }, + "type": "n8n-nodes-base.microsoftOutlook", + "typeVersion": 2, + "position": [ + -4160, + 912 + ], + "id": "aaab2e62-0622-4bbd-b3d1-648fcb06b290", + "name": "Label: Add Processing2", + "webhookId": "5d0319e0-f28f-4f7a-a562-038cd721cf91", + "credentials": { + "microsoftOutlookOAuth2Api": { + "id": "neYqnH7A2WPe5lTs", + "name": "Microsoft Outlook account" + } + }, + "onError": "continueRegularOutput" + }, + { + "parameters": { + "operation": "move", + "messageId": { + "__rl": true, + "value": "={{ $('Fetch Emails from New_Invoice (max 3)1').item.json.id }}", + "mode": "id" + }, + "folderId": { + "__rl": true, + "value": "AQMkADAwATM0MDAAMi1hYzgzLTQxMQAyLTAwAi0wMAoALgAAA3R9Z7-WZCBHqvG_09flPEoBAJRkAPlTP4RNsddkpsHybkoAAAJocQAAAA==", + "mode": "list", + "cachedResultName": "Processing", + "cachedResultUrl": "https://outlook.office365.com/mail/AQMkADAwATM0MDAAMi1hYzgzLTQxMQAyLTAwAi0wMAoALgAAA3R9Z7%2FWZCBHqvG_09flPEoBAJRkAPlTP4RNsddkpsHybkoAAAJocQAAAA%3D%3D" + } + }, + "type": "n8n-nodes-base.microsoftOutlook", + "typeVersion": 2, + "position": [ + -3936, + 912 + ], + "id": "584c67c7-ff4d-4b72-8a91-a94fe1c6ad4b", + "name": "Label: Remove New_Invoice1", + "webhookId": "e16ef4d9-e84c-4127-aafa-6f61cbdb9ba0", + "credentials": { + "microsoftOutlookOAuth2Api": { + "id": "neYqnH7A2WPe5lTs", + "name": "Microsoft Outlook account" + } + }, + "disabled": true + }, + { + "parameters": { + "operation": "get", + "messageId": { + "__rl": true, + "mode": "id", + "value": "={{ $json.id }}" + }, + "options": { + "downloadAttachments": true + } + }, + "type": "n8n-nodes-base.microsoftOutlook", + "typeVersion": 2, + "position": [ + -3712, + 912 + ], + "id": "8f05ea79-5bef-42c3-aef3-fc99f97397e8", + "name": "Fetch Full Email + Attachments2", + "webhookId": "74750b5a-de62-4326-888d-2d36ef832e5f", + "credentials": { + "microsoftOutlookOAuth2Api": { + "id": "neYqnH7A2WPe5lTs", + "name": "Microsoft Outlook account" + } + } + }, + { + "parameters": { + "jsCode": "// ═══════════════════════════════════════════════════════════════════\n// MASTER PARSE AI OUTPUT — Production Grade — Never-Fail Strategy\n//\n// Handles ALL known Gemini / Groq / LangChain output formats:\n// 1. Standard string in output field\n// 2. output field is already a parsed Object\n// 3. output field is an Array (unwraps first element)\n// 4. Double-nested output.output\n// 5. JSON wrapped in ```json ... ``` markdown fences\n// 6. JSON buried inside explanatory text (extracts all {} blocks)\n// 7. Malformed / unclosed JSON (regex fallback)\n// 8. is_invoice as boolean true/false\n// 9. is_invoice as string \"true\"/\"false\"/\"True\"/\"yes\"/\"1\"\n// 10. is_invoice as number 1/0\n// 11. Alternative field names: isInvoice, invoice, type, classification\n// 12. Confidence values: \"HIGH\", \"high\", \"Medium\", \"certain\", \"low\"\n// 13. text / content / message / result field instead of output\n// 14. LangChain wrapped format (lc/kwargs/content)\n// 15. Agent-level errors (quota, API down, 429, etc.)\n// 16. BOM characters and non-printable chars in output\n// 17. Partial / truncated JSON (regex field extraction)\n//\n// CLASSIFICATION OUTPUT (Switch node reads this):\n// \"invoice\" → process as invoice\n// \"not_invoice\" → skip, label as not-invoice\n// \"error\" → log error, do not process\n// ═══════════════════════════════════════════════════════════════════\n\nreturn items.map(item => {\n\n let classification = 'error';\n let confidence = 'low';\n let ai_reason = '';\n let error_detail = '';\n\n try {\n\n // ══════════════════════════════════════════════════════════════\n // STAGE 1 — Agent-level error check\n // Catches: Gemini quota, API key invalid, network timeout, 429\n // ══════════════════════════════════════════════════════════════\n if (item.json.error) {\n const errVal = item.json.error;\n const errStr = typeof errVal === 'object'\n ? (errVal.message || JSON.stringify(errVal))\n : String(errVal);\n error_detail = 'AGENT_ERROR: ' + errStr.slice(0, 300);\n classification = 'error';\n return buildOutput(item, classification, confidence, ai_reason, error_detail);\n }\n\n // ══════════════════════════════════════════════════════════════\n // STAGE 2 — Find raw content from all possible field paths\n // Try: output → text → content → message → result → response\n // ══════════════════════════════════════════════════════════════\n const FIELD_PATHS = ['output', 'text', 'content', 'message', 'result', 'response'];\n let raw = null;\n let parsed = null; // set if we already have a parsed object\n\n for (const path of FIELD_PATHS) {\n const val = item.json[path];\n if (val === null || val === undefined || val === '') continue;\n raw = val;\n break;\n }\n\n if (raw === null) {\n // Last resort: check if item.json itself IS the parsed object\n if (item.json.is_invoice !== undefined) {\n parsed = item.json;\n raw = null;\n } else {\n error_detail = 'NO_OUTPUT_FIELD: checked output/text/content/message/result';\n classification = 'error';\n return buildOutput(item, classification, confidence, ai_reason, error_detail);\n }\n }\n\n // ══════════════════════════════════════════════════════════════\n // STAGE 3 — Unwrap arrays and nested objects\n // ══════════════════════════════════════════════════════════════\n if (parsed === null && raw !== null) {\n // Unwrap Array → take first element\n if (Array.isArray(raw)) {\n raw = raw[0];\n }\n\n // If raw is an Object (n8n pre-parsed the JSON)\n if (raw !== null && typeof raw === 'object') {\n // Check for LangChain format: {lc: 1, kwargs: {content: \"...\"}}\n if (raw.kwargs && raw.kwargs.content !== undefined) {\n raw = raw.kwargs.content;\n\n // Check for double-nested output field\n } else if (raw.output !== undefined) {\n raw = raw.output;\n // raw might still be an object — check again\n if (raw !== null && typeof raw === 'object') {\n if (Array.isArray(raw)) raw = raw[0];\n if (raw !== null && typeof raw === 'object') {\n parsed = raw;\n raw = null;\n }\n }\n\n } else {\n // Object IS the parsed result\n parsed = raw;\n raw = null;\n }\n }\n }\n\n // ══════════════════════════════════════════════════════════════\n // STAGE 4 — Parse JSON from string (multi-attempt strategy)\n // ══════════════════════════════════════════════════════════════\n if (parsed === null && raw !== null) {\n const rawStr = String(raw);\n\n if (rawStr.trim() === '') {\n error_detail = 'EMPTY_AI_RESPONSE';\n classification = 'error';\n return buildOutput(item, classification, confidence, ai_reason, error_detail);\n }\n\n // ── Clean the string ──────────────────────────────────────\n let cleaned = rawStr\n .replace(/\\uFEFF/g, '') // BOM character\n .replace(/[\\x00-\\x08\\x0B\\x0C\\x0E-\\x1F]/g, '') // control chars (keep \\n \\r \\t)\n .replace(/```json\\s*/gi, '') // opening ```json fence\n .replace(/```\\s*/g, '') // closing ``` fence\n .trim();\n\n // ── Attempt 1: Direct JSON.parse of entire cleaned string ──\n parsed = tryParse(cleaned);\n\n // ── Attempt 2: Extract first complete { ... } block ───────\n if (!parsed) {\n const block = extractJsonBlock(cleaned, 'first');\n if (block) parsed = tryParse(block);\n }\n\n // ── Attempt 3: Extract the JSON block CONTAINING is_invoice ─\n if (!parsed) {\n const block = extractJsonBlockWithKey(cleaned, 'is_invoice');\n if (block) parsed = tryParse(block);\n }\n\n // ── Attempt 4: Extract LAST { ... } block ─────────────────\n if (!parsed) {\n const block = extractJsonBlock(cleaned, 'last');\n if (block) parsed = tryParse(block);\n }\n\n // ── Attempt 5: Try ALL { ... } blocks ─────────────────────\n if (!parsed) {\n const blocks = extractAllJsonBlocks(cleaned);\n for (const block of blocks) {\n const p = tryParse(block);\n if (p && (p.is_invoice !== undefined || p.isInvoice !== undefined)) {\n parsed = p;\n break;\n }\n }\n if (!parsed && blocks.length > 0) {\n parsed = tryParse(blocks[0]); // take first even if no is_invoice key\n }\n }\n\n // ── Attempt 6: Regex field extraction (malformed JSON) ────\n if (!parsed) {\n parsed = regexExtract(cleaned);\n }\n\n if (!parsed) {\n error_detail = 'ALL_PARSE_ATTEMPTS_FAILED: ' + cleaned.slice(0, 200);\n classification = 'error';\n return buildOutput(item, classification, confidence, ai_reason, error_detail);\n }\n }\n\n // ══════════════════════════════════════════════════════════════\n // STAGE 5 — Extract is_invoice from parsed object\n // Try all known field name variants\n // ══════════════════════════════════════════════════════════════\n const IS_INVOICE_FIELDS = [\n 'is_invoice', 'isInvoice', 'is_Invoice', 'IS_INVOICE',\n 'invoice', 'is_invoice_document', 'invoiceDetected'\n ];\n\n let rawFlag = undefined;\n let usedField = '';\n\n for (const field of IS_INVOICE_FIELDS) {\n if (parsed[field] !== undefined) {\n rawFlag = parsed[field];\n usedField = field;\n break;\n }\n }\n\n // ── Try classification/type fields (value-based check) ──────\n if (rawFlag === undefined) {\n const typeVal = String(parsed.classification || parsed.type || parsed.category || '').toLowerCase();\n if (typeVal.includes('invoice')) { rawFlag = true; }\n else if (typeVal.includes('not') ||\n typeVal.includes('skip') ||\n typeVal.includes('other')) { rawFlag = false; }\n }\n\n // ── If still not found, scan the raw text for patterns ──────\n if (rawFlag === undefined && raw) {\n const rawLower = String(raw).toLowerCase();\n const m = rawLower.match(/\"is_invoice\"\\s*:\\s*(true|false|\"true\"|\"false\"|1|0)/);\n if (m) {\n rawFlag = (m[1] === 'true' || m[1] === '\"true\"' || m[1] === '1');\n }\n }\n\n if (rawFlag === undefined) {\n error_detail = 'IS_INVOICE_FIELD_NOT_FOUND. Parsed object: ' + JSON.stringify(parsed).slice(0, 200);\n classification = 'error';\n\n } else {\n // ══════════════════════════════════════════════════════════\n // STAGE 6 — Normalize is_invoice to definitive boolean\n // ══════════════════════════════════════════════════════════\n const flag = String(rawFlag).toLowerCase().trim();\n\n if (['true', '1', 'yes', 'y', 'correct', 'affirmative', 'confirmed'].includes(flag)) {\n classification = 'invoice';\n\n } else if (['false', '0', 'no', 'n', 'incorrect', 'negative', 'not'].includes(flag)) {\n classification = 'not_invoice';\n\n } else {\n error_detail = 'UNEXPECTED_IS_INVOICE_VALUE: \"' + String(rawFlag) + '\"';\n classification = 'error';\n }\n }\n\n // ══════════════════════════════════════════════════════════════\n // STAGE 7 — Extract confidence and reason\n // ══════════════════════════════════════════════════════════════\n if (parsed) {\n // Confidence: normalize to \"high\" | \"medium\" | \"low\"\n const rawConf = String(parsed.confidence || parsed.certainty || parsed.score || 'low').toLowerCase().trim();\n if (['high', 'very_high', 'certain', 'definite', 'strong'].some(v => rawConf.includes(v))) {\n confidence = 'high';\n } else if (['medium', 'moderate', 'mid', 'possible', 'likely'].some(v => rawConf.includes(v))) {\n confidence = 'medium';\n } else {\n confidence = 'low';\n }\n\n // Reason: try multiple field names\n ai_reason = String(\n parsed.reason || parsed.explanation || parsed.rationale ||\n parsed.description || parsed.detail || ''\n ).slice(0, 500);\n }\n\n } catch (e) {\n error_detail = error_detail || ('UNCAUGHT_EXCEPTION: ' + e.message);\n classification = 'error';\n }\n\n return buildOutput(item, classification, confidence, ai_reason, error_detail);\n\n});\n\n// ══════════════════════════════════════════════════════════════════\n// HELPER FUNCTIONS\n// ══════════════════════════════════════════════════════════════════\n\nfunction buildOutput(item, classification, confidence, ai_reason, error_detail) {\n return {\n json: {\n ...item.json,\n classification,\n confidence,\n ai_reason,\n error_detail\n },\n binary: item.binary\n };\n}\n\nfunction tryParse(str) {\n try {\n if (!str || str.trim() === '') return null;\n const result = JSON.parse(str.trim());\n // Must be an object, not array/primitive\n if (result && typeof result === 'object' && !Array.isArray(result)) return result;\n if (Array.isArray(result) && result.length > 0 && typeof result[0] === 'object') return result[0];\n return null;\n } catch(e) {\n return null;\n }\n}\n\nfunction extractJsonBlock(str, which) {\n // Find matching { } block accounting for nesting\n const results = extractAllJsonBlocks(str);\n if (results.length === 0) return null;\n return which === 'last' ? results[results.length - 1] : results[0];\n}\n\nfunction extractAllJsonBlocks(str) {\n const blocks = [];\n let depth = 0, start = -1;\n for (let i = 0; i < str.length; i++) {\n if (str[i] === '{') {\n if (depth === 0) start = i;\n depth++;\n } else if (str[i] === '}') {\n depth--;\n if (depth === 0 && start !== -1) {\n blocks.push(str.slice(start, i + 1));\n start = -1;\n }\n }\n }\n return blocks;\n}\n\nfunction extractJsonBlockWithKey(str, key) {\n const blocks = extractAllJsonBlocks(str);\n for (const block of blocks) {\n if (block.includes('\"' + key + '\"') || block.includes(\"'\" + key + \"'\")) {\n return block;\n }\n }\n return null;\n}\n\nfunction regexExtract(str) {\n // Last resort: use regex to pull specific fields directly from string\n // even if the JSON is malformed or truncated\n try {\n const result = {};\n let found = false;\n\n // Extract is_invoice\n const mInv = str.match(/\"is_invoice\"\\s*:\\s*(true|false|\"true\"|\"false\"|\"yes\"|\"no\"|1|0)/i);\n if (mInv) {\n const v = mInv[1].replace(/\"/g, '').toLowerCase();\n result.is_invoice = ['true', 'yes', '1'].includes(v);\n found = true;\n }\n\n // Extract confidence\n const mConf = str.match(/\"confidence\"\\s*:\\s*\"([^\"]+)\"/i);\n if (mConf) result.confidence = mConf[1];\n\n // Extract reason\n const mReason = str.match(/\"reason\"\\s*:\\s*\"([^\"]+)\"/i);\n if (mReason) result.reason = mReason[1];\n\n return found ? result : null;\n } catch(e) {\n return null;\n }\n}\n" + }, + "type": "n8n-nodes-base.code", + "typeVersion": 2, + "position": [ + -2464, + 320 + ], + "id": "e76f2124-e8b2-4b52-86c5-0ab65b6068cf", + "name": "Parse AI Output2", + "retryOnFail": true, + "executeOnce": false, + "alwaysOutputData": true, + "notesInFlow": true + }, + { + "parameters": { + "assignments": { + "assignments": [ + { + "id": "00093515-229c-432c-9c8d-a2ef09acf369", + "name": "messageId", + "value": "={{$json.id}}", + "type": "string" + } + ] + }, + "includeOtherFields": true, + "options": {} + }, + "type": "n8n-nodes-base.set", + "typeVersion": 3.4, + "position": [ + -3424, + 672 + ], + "id": "a5f2223b-6f10-4437-81dc-9a34d57996d0", + "name": "Set messageId Field1" + }, + { + "parameters": { + "operation": "move", + "messageId": "={{ $json.messageId }}", + "folderId": { + "__rl": true, + "value": "AQMkADAwATM0MDAAMi1hYzgzLTQxMQAyLTAwAi0wMAoALgAAA3R9Z7-WZCBHqvG_09flPEoBAJRkAPlTP4RNsddkpsHybkoAAAJocgAAAA==", + "mode": "list", + "cachedResultName": "Not_invoice", + "cachedResultUrl": "https://outlook.office365.com/mail/AQMkADAwATM0MDAAMi1hYzgzLTQxMQAyLTAwAi0wMAoALgAAA3R9Z7%2FWZCBHqvG_09flPEoBAJRkAPlTP4RNsddkpsHybkoAAAJocgAAAA%3D%3D" + } + }, + "type": "n8n-nodes-base.microsoftOutlook", + "typeVersion": 2, + "position": [ + -2016, + 576 + ], + "id": "0c59ac0e-ca75-45bd-b731-3aae0faed96f", + "name": "Label: Add Not_Invoice2", + "webhookId": "d4398f49-ea88-4a89-8f2d-cffbda551562", + "credentials": { + "microsoftOutlookOAuth2Api": { + "id": "neYqnH7A2WPe5lTs", + "name": "Microsoft Outlook account" + } + }, + "onError": "continueRegularOutput" + }, + { + "parameters": { + "operation": "move", + "messageId": { + "__rl": true, + "value": "={{ $('Flatten Data for Log2').item.json.messageId }}", + "mode": "" + }, + "folderId": { + "__rl": true, + "value": "AQMkADAwATM0MDAAMi1hYzgzLTQxMQAyLTAwAi0wMAoALgAAA3R9Z7-WZCBHqvG_09flPEoBAJRkAPlTP4RNsddkpsHybkoAAAJocwAAAA==", + "mode": "list", + "cachedResultName": "Invoice_Sucess", + "cachedResultUrl": "https://outlook.office365.com/mail/AQMkADAwATM0MDAAMi1hYzgzLTQxMQAyLTAwAi0wMAoALgAAA3R9Z7%2FWZCBHqvG_09flPEoBAJRkAPlTP4RNsddkpsHybkoAAAJocwAAAA%3D%3D" + } + }, + "type": "n8n-nodes-base.microsoftOutlook", + "typeVersion": 2, + "position": [ + 0, + 0 + ], + "id": "bf5b1548-e75b-40d4-9b2d-a534708db65e", + "name": "Label: Add Invoice_Done2", + "webhookId": "e3a226f8-3b0f-4e68-a8d9-b881d60341ac", + "credentials": { + "microsoftOutlookOAuth2Api": { + "id": "neYqnH7A2WPe5lTs", + "name": "Microsoft Outlook account" + } + }, + "onError": "continueRegularOutput" + }, + { + "parameters": { + "operation": "move", + "messageId": "={{ $('Set messageId Field1').item.json.messageId }}", + "folderId": { + "__rl": true, + "value": "AQMkADAwATM0MDAAMi1hYzgzLTQxMQAyLTAwAi0wMAoALgAAA3R9Z7-WZCBHqvG_09flPEoBAJRkAPlTP4RNsddkpsHybkoAAAJodAAAAA==", + "mode": "list", + "cachedResultName": "Invoice_Failed", + "cachedResultUrl": "https://outlook.office365.com/mail/AQMkADAwATM0MDAAMi1hYzgzLTQxMQAyLTAwAi0wMAoALgAAA3R9Z7%2FWZCBHqvG_09flPEoBAJRkAPlTP4RNsddkpsHybkoAAAJodAAAAA%3D%3D" + } + }, + "type": "n8n-nodes-base.microsoftOutlook", + "typeVersion": 2, + "position": [ + -672, + 384 + ], + "id": "651c1889-e980-4870-a309-35e23ea51aed", + "name": "Label: Add Invoice_failed2", + "webhookId": "8f38dce4-4702-49e4-8a0f-7882a573aacf", + "credentials": { + "microsoftOutlookOAuth2Api": { + "id": "neYqnH7A2WPe5lTs", + "name": "Microsoft Outlook account" + } + }, + "onError": "continueRegularOutput" + }, + { + "parameters": { + "conditions": { + "options": { + "caseSensitive": true, + "leftValue": "", + "typeValidation": "strict", + "version": 2 + }, + "conditions": [ + { + "id": "78e67355-b3ff-448c-b597-35b7e0709267", + "leftValue": "={{\n !($json.error && $json.error.includes(\"429\")) &&\n !$json.error &&\n ($json.invoice_number ?? \"\") !== \"\"\n}}", + "rightValue": "", + "operator": { + "type": "boolean", + "operation": "true", + "singleValue": true + } + } + ], + "combinator": "and" + }, + "options": {} + }, + "type": "n8n-nodes-base.if", + "typeVersion": 2.2, + "position": [ + -1344, + 192 + ], + "id": "c7004bf2-bb80-4eea-8384-54cbd6baae84", + "name": "OCR Extraction Valid?2" + }, + { + "parameters": { + "method": "POST", + "url": "https://mapp.dmhospital.org/dmhApiRef/grn/createGRN.php", + "sendHeaders": true, + "headerParameters": { + "parameters": [ + { + "name": "x-api-key", + "value": "nirajAi26@DMH" + }, + { + "name": "Content-Type", + "value": "application/json" + } + ] + }, + "sendBody": true, + "specifyBody": "json", + "jsonBody": "={{$json}}", + "options": {} + }, + "type": "n8n-nodes-base.httpRequest", + "typeVersion": 4.2, + "position": [ + -896, + 96 + ], + "id": "4372d6a1-b4d9-4a1f-b522-c3399044ce33", + "name": "GRN: Create Record in Hospital2", + "retryOnFail": false, + "onError": "continueRegularOutput" + }, + { + "parameters": { + "jsCode": "function cleanNumber(val) {\n if (val === null || val === undefined) return 0;\n\n return Number(\n val\n .toString()\n .replace(/[^\\d.-]/g, \"\") // remove commas, brackets, symbols\n ) || 0;\n}\n\nreturn items.map(item => {\n\n const inv = item.json;\n\n return {\n json: {\n\n // ── HEADER ────────────────────────────────────────────────────────────\n invoice_id: inv.invoice_id ?? \"\",\n invoice_number: inv.invoice_number ?? \"\",\n invoice_date: inv.invoice_date ?? \"\",\n due_date: inv.due_date ?? \"\",\n seller_name: inv.seller_name ?? \"\",\n PO_number: inv.PO_number ?? \"\",\n\n invoice_amount: cleanNumber(inv.invoice_amount),\n currency_code: inv.currency_code ?? \"INR\",\n\n seller_gstin: inv.seller_gstin ?? \"\",\n customer_name: inv.customer_name ?? \"\",\n\n // ⚠️ HARDCODED — OCR frequently misreads or omits the hospital GSTIN.\n // This is always DEENANATH MEDICAL STORES (DMH Hospital Pharmacy).\n // Never trust the OCR value for this field.\n customer_gstin: \"27AAATL1944N1ZA\",\n\n dc_date: inv.DC_date ?? \"\",\n dc_number: inv.DC_number ?? \"\",\n\n round_off: cleanNumber(inv.round_off),\n\n total_gst_rate: cleanNumber(inv.total_gst_rate),\n total_quantity: cleanNumber(inv.total_quantity),\n\n total_cgst_rate: cleanNumber(inv.total_cgst_rate),\n total_cgst_amount: cleanNumber(inv.total_cgst_amount),\n\n total_sgst_rate: cleanNumber(inv.total_sgst_rate),\n total_sgst_amount: cleanNumber(inv.total_sgst_amount),\n\n total_igst_rate: cleanNumber(inv.total_igst_rate),\n total_igst_amount: cleanNumber(inv.total_igst_amount),\n\n total_gst_amount: cleanNumber(inv.total_gst_amount),\n\n // ── ITEMS ─────────────────────────────────────────────────────────────\n items: (inv.items ?? []).map(i => ({\n\n item_code: i.item_code ?? \"\",\n Batch: i.Batch ?? \"\",\n\n quantity: cleanNumber(i.quantity),\n free_item_yn: cleanNumber(i.free_item_yn),\n\n unit_price: cleanNumber(i.unit_price),\n total_price: cleanNumber(i.total_price),\n\n Discount: cleanNumber(i.Discount),\n MRP: cleanNumber(i.MRP),\n\n description: i.description ?? \"\",\n Pack: i.Pack ?? \"\",\n hsn_sac: i.hsn_sac ?? \"\",\n expiry_date: i.expiry_date ?? \"\",\n\n cgst_rate: cleanNumber(i.cgst_rate),\n cgst_amount: cleanNumber(i.cgst_amount),\n\n sgst_rate: cleanNumber(i.sgst_rate),\n sgst_amount: cleanNumber(i.sgst_amount),\n\n igst_rate: cleanNumber(i.igst_rate),\n igst_amount: cleanNumber(i.igst_amount),\n\n GST_AMT: cleanNumber(i.GST_AMT),\n\n // Added missing fields\n taxable_value: cleanNumber(i.taxable_value),\n \"Gst%\": cleanNumber(i[\"Gst%\"]),\n Value: cleanNumber(i.Value),\n reference_number: i.reference_number ?? \"\"\n\n }))\n\n }\n };\n});" + }, + "type": "n8n-nodes-base.code", + "typeVersion": 2, + "position": [ + -1120, + 96 + ], + "id": "6f82a7b4-9dbf-4e9c-a6c4-6a4a52efc6e3", + "name": "Normalize Invoice Fields2" + }, + { + "parameters": { + "conditions": { + "options": { + "caseSensitive": true, + "leftValue": "", + "typeValidation": "strict", + "version": 2 + }, + "conditions": [ + { + "id": "b97ce590-39e2-4792-b38e-972bfd18e0fd", + "leftValue": "={{ $('Flatten Data for Log2').item.json.grn_success }}", + "rightValue": "", + "operator": { + "type": "boolean", + "operation": "true", + "singleValue": true + } + } + ], + "combinator": "and" + }, + "options": {} + }, + "type": "n8n-nodes-base.if", + "typeVersion": 2.2, + "position": [ + -224, + 96 + ], + "id": "477bad63-5dad-4f11-bfdb-8f21c9cb801e", + "name": "GRN Created Successfully?2" + }, + { + "parameters": { + "jsCode": "const newItems = [];\n\nfor (const item of items) {\n\n const binaries = item.binary || {};\n const keys = Object.keys(binaries);\n\n if (keys.length > 0) {\n\n for (const key of keys) {\n\n // ── GET filename before binary is consumed ──────────────\n const attachment_name = binaries[key].fileName || '';\n\n newItems.push({\n json: {\n ...item.json,\n attachment_name: attachment_name // ← ONLY NEW LINE\n },\n binary: {\n file: binaries[key]\n }\n });\n }\n\n } else {\n\n let parsedOutput = {};\n try {\n parsedOutput = JSON.parse(item.json.output || '{}');\n } catch (e) {\n parsedOutput = {};\n }\n\n newItems.push({\n json: {\n ...item.json,\n ...parsedOutput,\n attachment_name: '' // ← ONLY NEW LINE\n }\n });\n }\n}\n\nreturn newItems;" + }, + "type": "n8n-nodes-base.code", + "typeVersion": 2, + "position": [ + -2912, + 912 + ], + "id": "b019335c-9a06-417b-95bb-862fcfa1a8fc", + "name": "Split: One Item Per Attachment3", + "alwaysOutputData": true, + "retryOnFail": true + }, + { + "parameters": { + "options": {} + }, + "type": "n8n-nodes-base.splitInBatches", + "typeVersion": 3, + "position": [ + -2688, + 912 + ], + "id": "7cb557ad-cb6d-45d4-99e9-8966e310b493", + "name": "Loop: Each Attachment2" + }, + { + "parameters": { + "amount": 1 + }, + "type": "n8n-nodes-base.wait", + "typeVersion": 1.1, + "position": [ + -1792, + 192 + ], + "id": "dab6bfb7-215a-4ccd-8964-333200305739", + "name": "Wait 7s Before OCR2", + "webhookId": "66577e6f-2f40-4a0b-a701-b0b535c018e2" + }, + { + "parameters": { + "jsCode": "// =======================================================================\n// Flatten Data for Log2 — v5.0\n// Node: Flatten Data for Log2\n//\n// PURPOSE:\n// Parse GRN API responses safely, including unexpected/new error formats.\n//\n// SUPPORTED ERROR MESSAGE LOCATIONS:\n// message\n// error\n// detail\n// reason\n// description\n// statusText\n// error.message\n// error.detail\n// error.description\n// data.message\n// data.error\n// data.detail\n// data[0].message\n// data[0].error\n// data[0].detail\n// data[0] as string\n// JSON-stringified error objects\n//\n// IMPORTANT:\n// Never returns null / undefined / [object Object] as grn_message.\n// =======================================================================\n\n\n// ───────────────────────────────────────────────────────────────────────\n// Helper: safe word-boundary HTTP status code check\n// ───────────────────────────────────────────────────────────────────────\n\nfunction hasHttpCode(text, code) {\n const c = String(code).replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n return new RegExp('(^|[^0-9])' + c + '([^0-9]|$)').test(\n String(text || '')\n );\n}\n\n\n// ───────────────────────────────────────────────────────────────────────\n// Helper: safely convert any value to useful text\n// ───────────────────────────────────────────────────────────────────────\n\nfunction safeText(value) {\n if (value === null || value === undefined) return '';\n\n if (typeof value === 'string') {\n return value.trim();\n }\n\n if (typeof value === 'number' || typeof value === 'boolean') {\n return String(value);\n }\n\n if (Array.isArray(value)) {\n const parts = value\n .map(v => safeText(v))\n .filter(Boolean);\n\n return parts.join(' | ').trim();\n }\n\n if (typeof value === 'object') {\n // Try common message fields first\n const keys = [\n 'message',\n 'error',\n 'detail',\n 'reason',\n 'description',\n 'statusText',\n 'msg',\n 'error_message',\n 'errorMessage'\n ];\n\n for (const key of keys) {\n if (value[key] !== undefined && value[key] !== null) {\n const result = safeText(value[key]);\n if (result) return result;\n }\n }\n\n // Last resort: JSON\n try {\n return JSON.stringify(value);\n } catch (e) {\n return '';\n }\n }\n\n return '';\n}\n\n\n// ───────────────────────────────────────────────────────────────────────\n// Helper: recursively extract a meaningful error message\n// ───────────────────────────────────────────────────────────────────────\n\nfunction extractErrorMessage(source, depth = 0) {\n\n if (source === null || source === undefined) {\n return '';\n }\n\n // Prevent infinite recursion\n if (depth > 6) {\n return '';\n }\n\n // Direct string\n if (typeof source === 'string') {\n\n const str = source.trim();\n\n if (!str) return '';\n\n // If string itself contains JSON, try parsing it\n if (\n (str.startsWith('{') && str.endsWith('}')) ||\n (str.startsWith('[') && str.endsWith(']'))\n ) {\n try {\n const parsed = JSON.parse(str);\n const nested = extractErrorMessage(parsed, depth + 1);\n\n if (nested) return nested;\n } catch (e) {\n // Not valid JSON — use original string\n }\n }\n\n return str;\n }\n\n // Number / boolean\n if (\n typeof source === 'number' ||\n typeof source === 'boolean'\n ) {\n return String(source);\n }\n\n // Array\n if (Array.isArray(source)) {\n\n // Prefer meaningful string values\n for (const item of source) {\n const result = extractErrorMessage(item, depth + 1);\n\n if (result) {\n return result;\n }\n }\n\n return '';\n }\n\n // Object\n if (typeof source === 'object') {\n\n // Most useful keys first\n const priorityKeys = [\n 'message',\n 'error',\n 'detail',\n 'reason',\n 'description',\n 'statusText',\n 'msg',\n 'error_message',\n 'errorMessage',\n 'response',\n 'body',\n 'data'\n ];\n\n for (const key of priorityKeys) {\n\n if (\n Object.prototype.hasOwnProperty.call(source, key) &&\n source[key] !== null &&\n source[key] !== undefined\n ) {\n\n const result = extractErrorMessage(\n source[key],\n depth + 1\n );\n\n if (result) {\n return result;\n }\n }\n }\n\n // Search any remaining keys\n for (const key of Object.keys(source)) {\n\n if (priorityKeys.includes(key)) {\n continue;\n }\n\n const result = extractErrorMessage(\n source[key],\n depth + 1\n );\n\n if (result) {\n return result;\n }\n }\n }\n\n return '';\n}\n\n\n// ───────────────────────────────────────────────────────────────────────\n// Helper: extract which specific header/item fields are missing\n// ───────────────────────────────────────────────────────────────────────\n\nfunction extractMissingFields(cb) {\n\n const fields = [];\n\n if (cb.includes('po_number'))\n fields.push('PO_number');\n\n if (cb.includes('invoice_amount'))\n fields.push('invoice_amount');\n\n if (cb.includes('invoice_id'))\n fields.push('invoice_id');\n\n if (cb.includes('item_code'))\n fields.push('item_code');\n\n if (cb.includes('item_id'))\n fields.push('item_id');\n\n if (cb.includes('batch'))\n fields.push('Batch');\n\n if (cb.includes('quantity'))\n fields.push('quantity');\n\n return fields;\n}\n\n\n// ───────────────────────────────────────────────────────────────────────\n// Helper: get item-code arrays from any supported structure\n// ───────────────────────────────────────────────────────────────────────\n\nfunction getArrayFromSources(sources, fieldNames) {\n\n for (const source of sources) {\n\n if (!source || typeof source !== 'object') {\n continue;\n }\n\n for (const field of fieldNames) {\n\n if (Array.isArray(source[field])) {\n return source[field];\n }\n }\n }\n\n return [];\n}\n\n\n// ───────────────────────────────────────────────────────────────────────\n// Error classifier\n// ───────────────────────────────────────────────────────────────────────\n\nfunction classifyError(\n grnMsg,\n fullErrorRaw,\n missingCodes,\n invalidCodes\n) {\n\n const text = String(\n (grnMsg || '') +\n ' ' +\n (fullErrorRaw || '')\n );\n\n const cb = text.toLowerCase();\n\n const raw =\n String(grnMsg || '').trim() ||\n String(fullErrorRaw || '').trim() ||\n 'Unknown API error';\n\n if (!cb.trim()) {\n return {\n owner: 'DMH',\n category: 'Other / Unclassified Error',\n detail: 'Unknown API error'\n };\n }\n\n const hasMissing =\n Array.isArray(missingCodes) &&\n missingCodes.length > 0;\n\n const hasInvalid =\n Array.isArray(invalidCodes) &&\n invalidCodes.length > 0;\n\n\n // ─────────────────────────────────────────────────────────────────────\n // DMH: MySQL Pool Exhausted\n // ─────────────────────────────────────────────────────────────────────\n\n if (\n cb.includes('pool exhausted') ||\n cb.includes('mysql.connector.errors.poolerror') ||\n cb.includes('too many connections') ||\n (\n cb.includes('connection refused') &&\n cb.includes('mysql')\n )\n ) {\n return {\n owner: 'DMH',\n category: 'MySQL Pool Exhausted',\n detail: raw\n };\n }\n\n\n // ─────────────────────────────────────────────────────────────────────\n // AI INDIA: Timeout / Gateway\n // ─────────────────────────────────────────────────────────────────────\n\n if (\n hasHttpCode(text, 504) ||\n cb.includes('gateway time-out') ||\n cb.includes('gateway timeout') ||\n cb.includes('etimedout') ||\n cb.includes('econnrefused') ||\n cb.includes('socket hang up') ||\n cb.includes('300000ms') ||\n cb.includes('deadline expired') ||\n cb.includes('connect timeout') ||\n cb.includes('read timeout') ||\n cb.includes('request timed out') ||\n cb.includes('timeout')\n ) {\n return {\n owner: 'AI INDIA',\n category: 'API Timeout / Gateway Error',\n detail: raw\n };\n }\n\n\n // ─────────────────────────────────────────────────────────────────────\n // AI INDIA: Invalid File Type\n // ─────────────────────────────────────────────────────────────────────\n\n if (\n (\n hasHttpCode(text, 400) &&\n cb.includes('invalid file type')\n ) ||\n cb.includes('unsupported file type') ||\n cb.includes('file type not supported')\n ) {\n return {\n owner: 'AI INDIA',\n category: 'Invalid File Type (400)',\n detail: raw\n };\n }\n\n\n // ─────────────────────────────────────────────────────────────────────\n // AI INDIA: File Too Large\n // ─────────────────────────────────────────────────────────────────────\n\n if (\n hasHttpCode(text, 413) ||\n cb.includes('request entity too large') ||\n cb.includes('payload too large') ||\n cb.includes('file size exceeds') ||\n cb.includes('file too large')\n ) {\n return {\n owner: 'AI INDIA',\n category: 'File Too Large (413)',\n detail: raw\n };\n }\n\n\n // ─────────────────────────────────────────────────────────────────────\n // AI INDIA: Gemini / API Key / Quota\n // ─────────────────────────────────────────────────────────────────────\n\n if (\n hasHttpCode(text, 401) ||\n hasHttpCode(text, 403) ||\n hasHttpCode(text, 429) ||\n cb.includes('generativelanguage.googleapis') ||\n cb.includes('api error: forbidden') ||\n cb.includes('api error: service unavailable') ||\n cb.includes('fetch failed') ||\n cb.includes('unauthorized: api key') ||\n cb.includes('invalid api key') ||\n cb.includes('quota') ||\n cb.includes('rate limit') ||\n cb.includes('resource has been exhausted')\n ) {\n return {\n owner: 'AI INDIA',\n category: 'Gemini API Error (Quota / Auth)',\n detail: raw\n };\n }\n\n\n // ─────────────────────────────────────────────────────────────────────\n // AI INDIA: OCR Server Crash\n // ─────────────────────────────────────────────────────────────────────\n\n if (\n hasHttpCode(text, 500) &&\n (\n cb.includes('internal server error') ||\n cb.includes('nginx') ||\n cb.includes('werkzeug') ||\n cb.includes('traceback') ||\n cb.includes('application error') ||\n cb.includes('server error')\n )\n ) {\n return {\n owner: 'AI INDIA',\n category: 'OCR Server Internal Crash (500)',\n detail: raw\n };\n }\n\n\n // ─────────────────────────────────────────────────────────────────────\n // AI INDIA: Invalid Image Format\n // ─────────────────────────────────────────────────────────────────────\n\n if (\n cb.includes('pil') ||\n cb.includes('pngimageplugin') ||\n cb.includes('cannot identify image') ||\n cb.includes('image file is truncated') ||\n cb.includes('invalid image') ||\n cb.includes('unsupported image')\n ) {\n return {\n owner: 'AI INDIA',\n category: 'Invalid Image Format (PIL Error)',\n detail: raw\n };\n }\n\n\n // ─────────────────────────────────────────────────────────────────────\n // AI INDIA: No Binary File Attached\n // ─────────────────────────────────────────────────────────────────────\n\n if (\n (\n cb.includes('binary file') &&\n cb.includes('none was found')\n ) ||\n cb.includes('no file was uploaded') ||\n cb.includes('missing file attachment') ||\n cb.includes('file not found') ||\n cb.includes('no binary data')\n ) {\n return {\n owner: 'AI INDIA',\n category: 'No Binary File Found',\n detail: raw\n };\n }\n\n\n // ─────────────────────────────────────────────────────────────────────\n // DMH: CSV File\n // ─────────────────────────────────────────────────────────────────────\n\n if (cb.includes('csv')) {\n return {\n owner: 'DMH',\n category: 'Invalid File Format — CSV Not Supported',\n detail: raw\n };\n }\n\n\n // ─────────────────────────────────────────────────────────────────────\n // AI INDIA: OCR Extraction Failed\n // ─────────────────────────────────────────────────────────────────────\n\n if (\n cb.includes('ocr extraction failed') ||\n cb.includes('ocr extraction') ||\n cb.includes('unknown processing error') ||\n cb.includes('extraction failed') ||\n cb.includes('could not extract') ||\n cb.includes('parse failure') ||\n cb.includes('ocr_parse_error') ||\n cb.includes('pdf parse') ||\n cb.includes('failed to parse') ||\n cb.includes('parsing failed') ||\n cb.includes('unable to extract')\n ) {\n return {\n owner: 'AI INDIA',\n category: 'OCR Extraction Failed',\n detail: raw\n };\n }\n\n\n // ─────────────────────────────────────────────────────────────────────\n // DMH: Duplicate Invoice\n // ─────────────────────────────────────────────────────────────────────\n\n if (\n cb.includes('record already exist') ||\n cb.includes('already exist') ||\n cb.includes('duplicate invoice') ||\n cb.includes('duplicate entry') ||\n cb.includes('already exists') ||\n cb.includes('invoice already')\n ) {\n return {\n owner: 'DMH',\n category: 'Duplicate Invoice',\n detail: raw\n };\n }\n\n\n // ─────────────────────────────────────────────────────────────────────\n // DMH: No Valid Items\n // ─────────────────────────────────────────────────────────────────────\n\n if (\n cb.includes(\n 'the invoice must contain at least one valid item'\n ) ||\n cb.includes('no valid items') ||\n cb.includes('zero valid item') ||\n cb.includes('all items are invalid') ||\n cb.includes('valid item not found') ||\n cb.includes('no valid item found')\n ) {\n\n if (hasMissing && hasInvalid) {\n\n return {\n owner: 'DMH',\n category:\n 'Missing Item Codes (' +\n missingCodes.length +\n ') + Invalid Item Codes (' +\n invalidCodes.length +\n ') — Not Registered in DMH',\n detail: raw\n };\n }\n\n\n if (hasMissing) {\n\n return {\n owner: 'DMH',\n category:\n 'Missing Item Codes (' +\n missingCodes.length +\n ') — Items Not Registered in DMH',\n detail: raw\n };\n }\n\n\n if (hasInvalid) {\n\n return {\n owner: 'DMH',\n category:\n 'Invalid Item Codes (' +\n invalidCodes.length +\n ') — Items Not Registered in DMH',\n detail: raw\n };\n }\n\n\n return {\n owner: 'DMH',\n category: 'No Valid Items in Invoice',\n detail: raw\n };\n }\n\n\n // ─────────────────────────────────────────────────────────────────────\n // DMH: Vendor Not Found\n // ─────────────────────────────────────────────────────────────────────\n\n if (\n cb.includes('vendor details not found') &&\n !cb.includes('po details not found') &&\n !cb.includes('po number does not contain') &&\n !cb.includes('phrmcy') &&\n !cb.includes('dmhmss') &&\n !cb.includes('not valid!!!') &&\n !cb.includes('po_number')\n ) {\n\n return {\n owner: 'DMH',\n category: 'Vendor Not Found',\n detail: raw\n };\n }\n\n\n // ─────────────────────────────────────────────────────────────────────\n // DMH: PO Not Found / Invalid PO\n // ─────────────────────────────────────────────────────────────────────\n\n if (\n cb.includes('po details not found') ||\n cb.includes('not valid!!!') ||\n cb.includes('phrmcy') ||\n cb.includes('dmhmss') ||\n cb.includes('does not contain either') ||\n cb.includes('invalid purchase order') ||\n cb.includes('po not found') ||\n cb.includes('invalid po') ||\n cb.includes('purchase order not found')\n ) {\n\n return {\n owner: 'DMH',\n category: 'PO Not Found / Invalid PO Number',\n detail: raw\n };\n }\n\n\n // ─────────────────────────────────────────────────────────────────────\n // DMH: Item Fields Missing\n // ─────────────────────────────────────────────────────────────────────\n\n if (\n cb.includes('listed fields are missing from item list') ||\n cb.includes('item_code') ||\n cb.includes('item_id') ||\n (\n cb.includes('batch') &&\n (\n cb.includes('missing') ||\n cb.includes('required') ||\n cb.includes('invalid')\n )\n ) ||\n (\n cb.includes('quantity') &&\n (\n cb.includes('missing') ||\n cb.includes('required') ||\n cb.includes('invalid')\n )\n )\n ) {\n\n const missing = extractMissingFields(cb);\n\n const missingStr =\n missing.length\n ? missing.join(', ')\n : 'unspecified item fields';\n\n return {\n owner: 'DMH',\n category:\n 'Item Fields Missing — ' +\n missingStr,\n detail: raw\n };\n }\n\n\n // ─────────────────────────────────────────────────────────────────────\n // DMH: Header Fields Missing\n // ─────────────────────────────────────────────────────────────────────\n\n if (\n cb.includes('listed fields are missing') ||\n cb.includes('po_number') ||\n (\n cb.includes('invoice_amount') &&\n cb.includes('missing')\n ) ||\n (\n cb.includes('invoice_id') &&\n cb.includes('missing')\n )\n ) {\n\n const missing = extractMissingFields(cb);\n\n const missingStr =\n missing.length\n ? missing.join(', ')\n : 'unspecified header fields';\n\n return {\n owner: 'DMH',\n category:\n 'Header Fields Missing — ' +\n missingStr,\n detail: raw\n };\n }\n\n\n // ─────────────────────────────────────────────────────────────────────\n // DMH: GSTIN / GST Mismatch\n // ─────────────────────────────────────────────────────────────────────\n\n if (\n cb.includes('gstin mismatch') ||\n cb.includes('gst mismatch') ||\n cb.includes('gstin validation') ||\n cb.includes('invalid gstin')\n ) {\n\n return {\n owner: 'DMH',\n category: 'GSTIN Mismatch / Validation Error',\n detail: raw\n };\n }\n\n\n // ─────────────────────────────────────────────────────────────────────\n // Fallback\n // ─────────────────────────────────────────────────────────────────────\n\n return {\n owner: 'DMH',\n category: 'Other / Unclassified Error',\n detail: raw\n };\n}\n\n\n// ───────────────────────────────────────────────────────────────────────\n// Build complete_error\n// ───────────────────────────────────────────────────────────────────────\n\nfunction buildCompleteError(\n grnMsg,\n missingCodes,\n invalidCodes,\n fallbackRaw\n) {\n\n const message =\n String(grnMsg || '').trim() ||\n String(fallbackRaw || '').trim() ||\n 'Unknown API error';\n\n const c = classifyError(\n message,\n fallbackRaw || '',\n missingCodes,\n invalidCodes\n );\n\n if (!c) {\n return '';\n }\n\n const divider =\n '─────────────────────────────────';\n\n const lines = [\n 'Error Type : ' + c.category,\n 'Error From : [' + c.owner + ']',\n divider,\n 'Raw API error : ' + message\n ];\n\n return lines.join('\\n');\n}\n\n\n// ───────────────────────────────────────────────────────────────────────\n// Resolve messageId\n// ───────────────────────────────────────────────────────────────────────\n\nfunction resolveMessageId(item) {\n\n // Source 1\n try {\n\n const v =\n $('Set messageId Field1')\n .item\n .json\n .messageId;\n\n if (v) {\n return String(v);\n }\n\n } catch (e) {}\n\n\n // Source 2\n try {\n\n const v =\n $('Switch2')\n .item\n .json\n .id;\n\n if (v) {\n return String(v);\n }\n\n } catch (e) {}\n\n\n // Source 3\n if (\n item.json &&\n item.json.messageId\n ) {\n return String(item.json.messageId);\n }\n\n\n // Source 4\n if (\n item.json &&\n item.json.id\n ) {\n return String(item.json.id);\n }\n\n\n return '';\n}\n\n\n// ═══════════════════════════════════════════════════════════════════════\n// MAIN\n// ═══════════════════════════════════════════════════════════════════════\n\nconst output = [];\n\nitems.forEach(item => {\n\n // ─────────────────────────────────────────────────────────────────────\n // IST Timestamp\n // ─────────────────────────────────────────────────────────────────────\n\n const now = new Date();\n\n const date =\n now.toLocaleDateString(\n 'en-CA',\n {\n timeZone: 'Asia/Kolkata'\n }\n );\n\n const time =\n now.toLocaleTimeString(\n 'en-IN',\n {\n timeZone: 'Asia/Kolkata',\n hour12: true\n }\n );\n\n\n // ─────────────────────────────────────────────────────────────────────\n // messageId\n // ─────────────────────────────────────────────────────────────────────\n\n const messageId =\n resolveMessageId(item);\n\n\n // ─────────────────────────────────────────────────────────────────────\n // GRN root object\n // ─────────────────────────────────────────────────────────────────────\n\n const grn =\n item.json || {};\n\n const httpStatus =\n grn.status;\n\n\n // ─────────────────────────────────────────────────────────────────────\n // Parse data\n // ─────────────────────────────────────────────────────────────────────\n\n const grnDataRaw =\n Array.isArray(grn.data) &&\n grn.data.length > 0\n ? grn.data[0]\n : null;\n\n\n // ─────────────────────────────────────────────────────────────────────\n // Build possible sources\n // ─────────────────────────────────────────────────────────────────────\n\n const sources = [];\n\n if (grnDataRaw !== null) {\n sources.push(grnDataRaw);\n }\n\n if (\n grn.data &&\n typeof grn.data === 'object'\n ) {\n sources.push(grn.data);\n }\n\n sources.push(grn);\n\n\n // ─────────────────────────────────────────────────────────────────────\n // Extract GRN data object\n // ─────────────────────────────────────────────────────────────────────\n\n let grnData = {};\n\n if (\n grnDataRaw &&\n typeof grnDataRaw === 'object' &&\n !Array.isArray(grnDataRaw)\n ) {\n\n grnData = grnDataRaw;\n\n } else if (\n grn.data &&\n typeof grn.data === 'object' &&\n !Array.isArray(grn.data)\n ) {\n\n grnData = grn.data;\n }\n\n\n // ─────────────────────────────────────────────────────────────────────\n // NEW ROBUST MESSAGE EXTRACTION\n // ─────────────────────────────────────────────────────────────────────\n\n let grnMsg =\n extractErrorMessage(grnDataRaw);\n\n\n if (!grnMsg) {\n grnMsg =\n extractErrorMessage(grn.data);\n }\n\n\n if (!grnMsg) {\n grnMsg =\n extractErrorMessage(grn.message);\n }\n\n\n if (!grnMsg) {\n grnMsg =\n extractErrorMessage(grn.error);\n }\n\n\n if (!grnMsg) {\n grnMsg =\n extractErrorMessage(grn.detail);\n }\n\n\n if (!grnMsg) {\n grnMsg =\n extractErrorMessage(grn.reason);\n }\n\n\n if (!grnMsg) {\n grnMsg =\n extractErrorMessage(grn.description);\n }\n\n\n if (!grnMsg) {\n grnMsg =\n extractErrorMessage(grn.statusText);\n }\n\n\n // Absolute fallback\n if (!grnMsg) {\n grnMsg = 'Unknown API error';\n }\n\n\n // ─────────────────────────────────────────────────────────────────────\n // Missing / Invalid item codes\n // ─────────────────────────────────────────────────────────────────────\n\n const missingCodes =\n getArrayFromSources(\n sources,\n [\n 'missingItmesCodes',\n 'missingItemsCodes',\n 'missing_item_codes',\n 'missingItemCodes',\n 'missing_items',\n 'missingItems'\n ]\n );\n\n\n const invalidCodes =\n getArrayFromSources(\n sources,\n [\n 'invalidItmes',\n 'invalidItems',\n 'invalid_item_codes',\n 'invalidItemCodes',\n 'invalid_items'\n ]\n );\n\n\n // ─────────────────────────────────────────────────────────────────────\n // HTTP status\n // ─────────────────────────────────────────────────────────────────────\n\n const http_status_code =\n typeof httpStatus === 'number'\n ? httpStatus\n : parseInt(httpStatus, 10) || 0;\n\n\n // ─────────────────────────────────────────────────────────────────────\n // GRN success\n // ─────────────────────────────────────────────────────────────────────\n\n const httpOk =\n http_status_code === 200;\n\n const grnOk =\n grnData.status === 0 ||\n grnData.status === '0';\n\n const grn_success =\n httpOk && grnOk;\n\n const status =\n grn_success\n ? '✅ SUCCESS'\n : '❌ FAILED';\n\n\n // ─────────────────────────────────────────────────────────────────────\n // Invoice fields\n // ─────────────────────────────────────────────────────────────────────\n\n let inv = {};\n\n try {\n\n inv =\n $('Normalize Invoice Fields2')\n .item\n .json || {};\n\n } catch (e) {\n\n inv = {};\n }\n\n\n // ─────────────────────────────────────────────────────────────────────\n // Attachment name\n // ─────────────────────────────────────────────────────────────────────\n\n let attachment_name = '';\n\n try {\n\n attachment_name =\n $('Split: One Item Per Attachment3')\n .item\n .json\n .attachment_name || '';\n\n } catch (e) {\n\n attachment_name = '';\n }\n\n\n // ─────────────────────────────────────────────────────────────────────\n // Free Goods\n // ─────────────────────────────────────────────────────────────────────\n\n const invoiceItems =\n Array.isArray(inv.items)\n ? inv.items\n : [];\n\n const hasFreeGoods =\n invoiceItems.some(\n i =>\n String(\n i &&\n i.free_item_yn\n ) === '1'\n );\n\n const free_goods =\n hasFreeGoods\n ? 'Yes'\n : 'No';\n\n\n // ─────────────────────────────────────────────────────────────────────\n // Complete error\n // ─────────────────────────────────────────────────────────────────────\n\n let complete_error = '';\n\n\n if (grn_success) {\n\n const auditParts = [];\n\n if (grnData.grn_no) {\n auditParts.push(\n 'GRN No: ' +\n grnData.grn_no\n );\n }\n\n if (grnData.grn_master_id) {\n auditParts.push(\n 'GRN Master ID: ' +\n grnData.grn_master_id\n );\n }\n\n if (\n grnData.items_inserted !== undefined &&\n grnData.items_inserted !== null\n ) {\n auditParts.push(\n 'Items Inserted: ' +\n grnData.items_inserted\n );\n }\n\n if (grnData.vendor_id) {\n auditParts.push(\n 'Vendor ID: ' +\n grnData.vendor_id\n );\n }\n\n if (grnData.invoice_no) {\n auditParts.push(\n 'Invoice No (DMH): ' +\n grnData.invoice_no\n );\n }\n\n complete_error =\n auditParts.length\n ? auditParts.join(' | ')\n : '';\n\n } else {\n\n complete_error =\n buildCompleteError(\n grnMsg,\n missingCodes,\n invalidCodes,\n JSON.stringify(grn)\n );\n }\n\n\n // ─────────────────────────────────────────────────────────────────────\n // Output\n // ─────────────────────────────────────────────────────────────────────\n\n output.push({\n\n json: {\n\n // Timestamp\n date,\n time,\n\n\n // Invoice identity\n invoice_id:\n inv.invoice_id || '',\n\n invoice_number:\n inv.invoice_number || '',\n\n invoice_date:\n inv.invoice_date || '',\n\n seller_name:\n inv.seller_name || '',\n\n seller_gstin:\n inv.seller_gstin || '',\n\n customer_name:\n inv.customer_name || '',\n\n invoice_amount:\n inv.invoice_amount ?? 0,\n\n attachment_name,\n\n\n // GRN result\n status,\n\n grn_success,\n\n http_status_code,\n\n grn_message:\n grnMsg || 'Unknown API error',\n\n\n // Error detail\n complete_error,\n\n\n // Traceability\n free_goods,\n\n messageId\n }\n });\n\n});\n\n\nreturn output;" + }, + "type": "n8n-nodes-base.code", + "typeVersion": 2, + "position": [ + -672, + 96 + ], + "id": "864137a6-b9cb-4e21-bcc2-1f2543d04fda", + "name": "Flatten Data for Log2", + "onError": "continueRegularOutput" + }, + { + "parameters": { + "operation": "append", + "documentId": { + "__rl": true, + "value": "1cwLXlwmCPC7zUVOIQFWwRED4uqF3WZHVagGbBtKyVgQ", + "mode": "list", + "cachedResultName": "Invoice_Tracker_NEW", + "cachedResultUrl": "https://docs.google.com/spreadsheets/d/1cwLXlwmCPC7zUVOIQFWwRED4uqF3WZHVagGbBtKyVgQ/edit?usp=drivesdk" + }, + "sheetName": { + "__rl": true, + "value": 1691973413, + "mode": "list", + "cachedResultName": "Daily Logs", + "cachedResultUrl": "https://docs.google.com/spreadsheets/d/1cwLXlwmCPC7zUVOIQFWwRED4uqF3WZHVagGbBtKyVgQ/edit#gid=1691973413" + }, + "columns": { + "mappingMode": "defineBelow", + "value": { + "Date": "={{ $json.date }}", + "Time": "={{ $json.time }}", + "Status": "={{ $json.status }}", + "Complete Error / Null Values": "={{ $json.complete_error }}", + "Attachment Name": "={{ $('Wait 7s Before OCR2').item.json.attachment_name }}" + }, + "matchingColumns": [], + "schema": [ + { + "id": "Sr No.", + "displayName": "Sr No.", + "required": false, + "defaultMatch": false, + "display": true, + "type": "string", + "canBeUsedToMatch": true, + "removed": false + }, + { + "id": "Date", + "displayName": "Date", + "required": false, + "defaultMatch": false, + "display": true, + "type": "string", + "canBeUsedToMatch": true + }, + { + "id": "Time", + "displayName": "Time", + "required": false, + "defaultMatch": false, + "display": true, + "type": "string", + "canBeUsedToMatch": true + }, + { + "id": "Attachment Name", + "displayName": "Attachment Name", + "required": false, + "defaultMatch": false, + "display": true, + "type": "string", + "canBeUsedToMatch": true, + "removed": false + }, + { + "id": "Customer Name", + "displayName": "Customer Name", + "required": false, + "defaultMatch": false, + "display": true, + "type": "string", + "canBeUsedToMatch": true + }, + { + "id": "Invoice Amount (₹)", + "displayName": "Invoice Amount (₹)", + "required": false, + "defaultMatch": false, + "display": true, + "type": "string", + "canBeUsedToMatch": true + }, + { + "id": "Invoice ID", + "displayName": "Invoice ID", + "required": false, + "defaultMatch": false, + "display": true, + "type": "string", + "canBeUsedToMatch": true, + "removed": false + }, + { + "id": "Seller Name", + "displayName": "Seller Name", + "required": false, + "defaultMatch": false, + "display": true, + "type": "string", + "canBeUsedToMatch": true + }, + { + "id": "Status", + "displayName": "Status", + "required": false, + "defaultMatch": false, + "display": true, + "type": "string", + "canBeUsedToMatch": true + }, + { + "id": "GRN Message ", + "displayName": "GRN Message ", + "required": false, + "defaultMatch": false, + "display": true, + "type": "string", + "canBeUsedToMatch": true, + "removed": false + }, + { + "id": "Seller GSTIN", + "displayName": "Seller GSTIN", + "required": false, + "defaultMatch": false, + "display": true, + "type": "string", + "canBeUsedToMatch": true + }, + { + "id": "Free Goods", + "displayName": "Free Goods", + "required": false, + "defaultMatch": false, + "display": true, + "type": "string", + "canBeUsedToMatch": true, + "removed": false + }, + { + "id": "Complete Error / Null Values", + "displayName": "Complete Error / Null Values", + "required": false, + "defaultMatch": false, + "display": true, + "type": "string", + "canBeUsedToMatch": true, + "removed": false + } + ], + "attemptToConvertTypes": false, + "convertFieldsToString": false + }, + "options": { + "cellFormat": "USER_ENTERED", + "useAppend": true + } + }, + "type": "n8n-nodes-base.googleSheets", + "typeVersion": 4.7, + "position": [ + -896, + 384 + ], + "id": "b12ab90f-240b-4845-ac94-dada14ce001f", + "name": "Append row in sheet5", + "credentials": { + "googleSheetsOAuth2Api": { + "id": "OGnPiaQp3eu9tWvW", + "name": "Google Sheets account" + } + }, + "onError": "continueRegularOutput" + }, + { + "parameters": { + "jsCode": "// ═══════════════════════════════════════════════════════════════\n// Flatten AI Classification Error for Log\n// Placed BEFORE: Append row in sheet1\n// Receives: Switch2 → error route (classification = \"error\")\n//\n// This fires when the AI provider completely fails to classify\n// the email — API down, quota hit, empty response, parse failure.\n//\n// Uses IDENTICAL complete_error format as Flatten Data for Log2:\n// Error Type : API Blocked — Project Suspended (403)\n// Error From : [AI INDIA]\n// ─────────────────────────────────\n// Raw API error : AGENT_ERROR: 403 PERMISSION_DENIED...\n//\n// NOTE: Category labels are intentionally generic (\"API Error...\")\n// and do NOT mention the underlying provider name (e.g. Gemini)\n// in the output. The raw error text in \"Raw API error\" is left\n// untouched since that's just the upstream message, not a label.\n// ═══════════════════════════════════════════════════════════════\n\n// ── Error classifier ──────────────────────────────────────────\nfunction classifyAIError(errorDetail) {\n const text = String(errorDetail || '');\n const cb = text.toLowerCase();\n\n function hasCode(code) {\n const c = String(code).replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n return new RegExp('(^|[^0-9])' + c + '([^0-9]|$)').test(text);\n }\n\n // 403 Lightning Dunning (most specific — before generic 403)\n if (hasCode(403) && cb.includes('lightning dunning'))\n return { owner: 'AI INDIA', category: 'API Blocked — Project Suspended (403)' };\n\n // 403 / 401 / Permission denied\n if (hasCode(403) || hasCode(401) || cb.includes('permission_denied') || cb.includes('forbidden'))\n return { owner: 'AI INDIA', category: 'API Permission Denied (403)' };\n\n // 429 / Quota / Rate limit\n if (hasCode(429) || cb.includes('quota') || cb.includes('rate limit') ||\n cb.includes('too many requests') || cb.includes('resource has been exhausted') ||\n cb.includes('generate_requests_per_model_per_day'))\n return { owner: 'AI INDIA', category: 'API Quota / Rate Limit (429)' };\n\n // 504 / Timeout\n if (hasCode(504) || cb.includes('gateway timeout') || cb.includes('etimedout') ||\n cb.includes('socket hang up') || cb.includes('300000ms') || cb.includes('deadline expired'))\n return { owner: 'AI INDIA', category: 'API Timeout (504)' };\n\n // 500 server error\n if (hasCode(500) || cb.includes('internal server error'))\n return { owner: 'AI INDIA', category: 'API Server Error (500)' };\n\n // Empty / no response\n if (cb.includes('empty_ai_response') || cb.includes('empty'))\n return { owner: 'AI INDIA', category: 'API Returned Empty Response' };\n\n // JSON / parse failure\n if (cb.includes('no_json_found') || cb.includes('parse_exception') ||\n cb.includes('json_parse_failed') || cb.includes('all_parse_attempts_failed'))\n return { owner: 'AI INDIA', category: 'API Response — JSON Parse Failed' };\n\n // Missing is_invoice field\n if (cb.includes('missing_is_invoice') || cb.includes('is_invoice_field_not_found'))\n return { owner: 'AI INDIA', category: 'API Response — Missing is_invoice Field' };\n\n // Agent-level error\n if (cb.includes('agent_error'))\n return { owner: 'AI INDIA', category: 'API Agent Error' };\n\n // Fallback\n return { owner: 'AI INDIA', category: 'AI Classification Error — Unclassified' };\n}\n\n// ── Build complete_error block ─────────────────────────────────\nfunction buildCompleteError(errorDetail) {\n const c = classifyAIError(errorDetail);\n const divider = '─────────────────────────────────';\n return [\n 'Error Type : ' + c.category,\n 'Error From : [' + c.owner + ']',\n divider,\n 'Raw API error : ' + (errorDetail || '(no error detail)')\n ].join('\\n');\n}\n\n// ── Resolve messageId — 4-source fallback ─────────────────────\nfunction resolveMessageId(item) {\n try { const v = $('Set messageId Field1').item.json.messageId; if (v) return String(v); } catch(e) {}\n try { const v = $('Switch2').item.json.id; if (v) return String(v); } catch(e) {}\n if (item.json.messageId) return String(item.json.messageId);\n if (item.json.id) return String(item.json.id);\n return '';\n}\n\n// ══════════════════════════════════════════════════════════════\n// MAIN\n// ══════════════════════════════════════════════════════════════\n\nconst output = [];\n\nitems.forEach(item => {\n\n const data = item.json;\n\n // IST Timestamp\n const now = new Date();\n const date = now.toLocaleDateString('en-CA', { timeZone: 'Asia/Kolkata' });\n const time = now.toLocaleTimeString('en-IN', { timeZone: 'Asia/Kolkata', hour12: true });\n\n const messageId = resolveMessageId(item);\n\n // Attachment name\n let attachment_name = '';\n try { attachment_name = $('Split: One Item Per Attachment3').item.json.attachment_name || ''; } catch(e) {}\n if (!attachment_name) attachment_name = data.attachment_name || '';\n\n // Read CORRECT field set by Parse AI Output (not data.error!)\n const errorDetail = data.error_detail || data.error || 'AI_CLASSIFICATION_FAILED';\n const complete_error = buildCompleteError(errorDetail);\n\n output.push({\n json: {\n // Timestamp\n date,\n time,\n\n // Invoice fields — all blank (AI never got to OCR)\n invoice_id: '',\n invoice_number: '',\n invoice_date: '',\n seller_name: '',\n seller_gstin: '',\n customer_name: '',\n invoice_amount: 0,\n attachment_name,\n\n // Status\n status: '❌ FAILED',\n grn_message: 'AI Classification Failed — Invoice not processed',\n\n // Error block — same format as all other rows\n complete_error,\n\n // Traceability\n messageId\n }\n });\n\n});\n\nreturn output;" + }, + "type": "n8n-nodes-base.code", + "typeVersion": 2, + "position": [ + -2016, + 384 + ], + "id": "88f8d70f-f8b0-4462-bf46-478f26a507df", + "name": "Code in JavaScript6", + "onError": "continueRegularOutput" + }, + { + "parameters": { + "rules": { + "values": [ + { + "conditions": { + "options": { + "caseSensitive": true, + "leftValue": "", + "typeValidation": "strict", + "version": 3 + }, + "conditions": [ + { + "leftValue": "={{ $json.classification }}", + "rightValue": "invoice", + "operator": { + "type": "string", + "operation": "equals" + }, + "id": "a4a14d24-2846-4497-85b2-d76b08ee5f3f" + } + ], + "combinator": "and" + } + }, + { + "conditions": { + "options": { + "caseSensitive": true, + "leftValue": "", + "typeValidation": "strict", + "version": 3 + }, + "conditions": [ + { + "id": "6e8cef57-3eb1-458e-a82c-82f914ff3ffb", + "leftValue": "={{ $json.classification }}", + "rightValue": "error", + "operator": { + "type": "string", + "operation": "equals" + } + } + ], + "combinator": "and" + } + }, + { + "conditions": { + "options": { + "caseSensitive": true, + "leftValue": "", + "typeValidation": "strict", + "version": 3 + }, + "conditions": [ + { + "id": "d6db0eb2-e8fa-4b20-b475-6b78e2bbb39e", + "leftValue": "={{ $json.classification }}", + "rightValue": "not_invoice", + "operator": { + "type": "string", + "operation": "equals" + } + } + ], + "combinator": "and" + } + } + ] + }, + "options": { + "fallbackOutput": "extra" + } + }, + "type": "n8n-nodes-base.switch", + "typeVersion": 3.4, + "position": [ + -2240, + 288 + ], + "id": "334b80a6-4e59-44b6-a627-536fc65ea1cd", + "name": "Switch2" + }, + { + "parameters": { + "operation": "move", + "messageId": "={{ $('Flatten Data for Log2').item.json.messageId }}", + "folderId": { + "__rl": true, + "value": "AQMkADAwATM0MDAAMi1hYzgzLTQxMQAyLTAwAi0wMAoALgAAA3R9Z7-WZCBHqvG_09flPEoBAJRkAPlTP4RNsddkpsHybkoAAAJodAAAAA==", + "mode": "list", + "cachedResultName": "Invoice_Failed", + "cachedResultUrl": "https://outlook.office365.com/mail/AQMkADAwATM0MDAAMi1hYzgzLTQxMQAyLTAwAi0wMAoALgAAA3R9Z7%2FWZCBHqvG_09flPEoBAJRkAPlTP4RNsddkpsHybkoAAAJodAAAAA%3D%3D" + } + }, + "type": "n8n-nodes-base.microsoftOutlook", + "typeVersion": 2, + "position": [ + 0, + 288 + ], + "id": "6ee14313-3f3a-447e-a7d5-cf15a29f972b", + "name": "Failed To add2", + "webhookId": "0d4c72df-2457-4462-aa2f-b53949022df8", + "credentials": { + "microsoftOutlookOAuth2Api": { + "id": "neYqnH7A2WPe5lTs", + "name": "Microsoft Outlook account" + } + }, + "onError": "continueRegularOutput" + }, + { + "parameters": { + "model": "openai/gpt-oss-120b", + "options": {} + }, + "type": "@n8n/n8n-nodes-langchain.lmChatGroq", + "typeVersion": 1, + "position": [ + -3360, + 1184 + ], + "id": "69adb603-b839-49a8-a652-79c28fc2dcdb", + "name": "Groq Chat Model1", + "credentials": { + "groqApi": { + "id": "5STjMY6aZDMipq2f", + "name": "Groq account" + } + } + }, + { + "parameters": { + "jsCode": "// ─── Filter: Skip Non-OCR-able Files ─────────────────────────────\n// Allows ONLY PDF, image, and CSV attachments to reach the next node.\n// Other files (DOCX, TXT, EML etc.) are dropped silently.\n// An empty output from this node = no call generated = safe no-op.\n// ──────────────────────────────────────────────────────────────────────\nconst ALLOWED_MIME_TYPES = [\n 'application/pdf',\n 'image/jpeg',\n 'image/jpg',\n 'image/png',\n 'image/tiff',\n 'image/webp',\n 'image/bmp',\n 'image/gif',\n 'text/csv', // ← added\n 'application/csv' // ← added (some systems send this for .csv)\n];\nconst ALLOWED_EXTENSIONS = [\n '.pdf', '.jpg', '.jpeg', '.png',\n '.tiff', '.tif', '.webp', '.bmp', '.gif',\n '.csv' // ← added\n];\nconst filtered = items.filter(item => {\n const binary = item.binary?.file;\n // ── No binary at all → skip (text-only email path) ──────────────\n if (!binary) {\n return false;\n }\n const mimeType = (binary.mimeType || '').toLowerCase();\n const fileName = (binary.fileName || item.json.attachment_name || '').toLowerCase();\n const lastDot = fileName.lastIndexOf('.');\n const ext = lastDot !== -1 ? fileName.slice(lastDot) : '';\n const isAllowedMime = ALLOWED_MIME_TYPES.some(m => mimeType.includes(m));\n const isAllowedExt = ALLOWED_EXTENSIONS.includes(ext);\n if (!isAllowedMime && !isAllowedExt) {\n console.log('[OCR-FILTER] BLOCKED | file: ' + (binary.fileName || 'unknown') + ' | mime: ' + (mimeType || 'none') + ' | ext: ' + (ext || 'none') + ' | Reason: not PDF, image, or CSV format');\n return false;\n }\n return true;\n});\n// Return empty array cleanly if nothing passes the filter\nreturn filtered;" + }, + "type": "n8n-nodes-base.code", + "typeVersion": 2, + "position": [ + -2016, + 192 + ], + "id": "90bed578-8c62-4c6b-a1d3-e10639a0f051", + "name": "Filter: Skip Non-OCR-able Files", + "disabled": true, + "onError": "continueRegularOutput" + }, + { + "parameters": { + "operation": "append", + "documentId": { + "__rl": true, + "value": "1cwLXlwmCPC7zUVOIQFWwRED4uqF3WZHVagGbBtKyVgQ", + "mode": "list", + "cachedResultName": "Invoice_Tracker_NEW", + "cachedResultUrl": "https://docs.google.com/spreadsheets/d/1cwLXlwmCPC7zUVOIQFWwRED4uqF3WZHVagGbBtKyVgQ/edit?usp=drivesdk" + }, + "sheetName": { + "__rl": true, + "value": 1691973413, + "mode": "list", + "cachedResultName": "Daily Logs", + "cachedResultUrl": "https://docs.google.com/spreadsheets/d/1cwLXlwmCPC7zUVOIQFWwRED4uqF3WZHVagGbBtKyVgQ/edit#gid=1691973413" + }, + "columns": { + "mappingMode": "defineBelow", + "value": { + "Date": "={{ $json.date }}", + "Time": "={{ $json.time }}", + "Attachment Name": "={{ $json.attachment_name }}", + "Invoice ID": "={{ $json.invoice_id }}", + "Customer Name": "={{ $json.customer_name }}", + "Invoice Amount (₹)": "={{ $json.invoice_amount }}", + "Seller Name": "={{ $json.seller_name }}", + "Status": "={{ $json.status }}", + "GRN Message ": "={{ $json.grn_message }}", + "Seller GSTIN": "={{ $json.seller_gstin }}", + "Free Goods": "={{ $json.free_goods }}", + "Complete Error / Null Values": "={{ $json.complete_error }}" + }, + "matchingColumns": [], + "schema": [ + { + "id": "Sr No.", + "displayName": "Sr No.", + "required": false, + "defaultMatch": false, + "display": true, + "type": "string", + "canBeUsedToMatch": true, + "removed": false + }, + { + "id": "Date", + "displayName": "Date", + "required": false, + "defaultMatch": false, + "display": true, + "type": "string", + "canBeUsedToMatch": true + }, + { + "id": "Time", + "displayName": "Time", + "required": false, + "defaultMatch": false, + "display": true, + "type": "string", + "canBeUsedToMatch": true + }, + { + "id": "Attachment Name", + "displayName": "Attachment Name", + "required": false, + "defaultMatch": false, + "display": true, + "type": "string", + "canBeUsedToMatch": true + }, + { + "id": "Customer Name", + "displayName": "Customer Name", + "required": false, + "defaultMatch": false, + "display": true, + "type": "string", + "canBeUsedToMatch": true + }, + { + "id": "Invoice Amount (₹)", + "displayName": "Invoice Amount (₹)", + "required": false, + "defaultMatch": false, + "display": true, + "type": "string", + "canBeUsedToMatch": true + }, + { + "id": "Invoice ID", + "displayName": "Invoice ID", + "required": false, + "defaultMatch": false, + "display": true, + "type": "string", + "canBeUsedToMatch": true + }, + { + "id": "Seller Name", + "displayName": "Seller Name", + "required": false, + "defaultMatch": false, + "display": true, + "type": "string", + "canBeUsedToMatch": true + }, + { + "id": "Status", + "displayName": "Status", + "required": false, + "defaultMatch": false, + "display": true, + "type": "string", + "canBeUsedToMatch": true + }, + { + "id": "GRN Message ", + "displayName": "GRN Message ", + "required": false, + "defaultMatch": false, + "display": true, + "type": "string", + "canBeUsedToMatch": true + }, + { + "id": "Seller GSTIN", + "displayName": "Seller GSTIN", + "required": false, + "defaultMatch": false, + "display": true, + "type": "string", + "canBeUsedToMatch": true + }, + { + "id": "Free Goods", + "displayName": "Free Goods", + "required": false, + "defaultMatch": false, + "display": true, + "type": "string", + "canBeUsedToMatch": true + }, + { + "id": "Complete Error / Null Values", + "displayName": "Complete Error / Null Values", + "required": false, + "defaultMatch": false, + "display": true, + "type": "string", + "canBeUsedToMatch": true + } + ], + "attemptToConvertTypes": false, + "convertFieldsToString": false + }, + "options": {} + }, + "type": "n8n-nodes-base.googleSheets", + "typeVersion": 4.7, + "position": [ + -448, + 96 + ], + "id": "54fc0189-5a1a-402b-93a0-9f575f730f32", + "name": "Log to Google Sheets (Daily Logs)2", + "retryOnFail": false, + "maxTries": 3, + "credentials": { + "googleSheetsOAuth2Api": { + "id": "OGnPiaQp3eu9tWvW", + "name": "Google Sheets account" + } + } + }, + { + "parameters": { + "options": { + "temperature": 0.4 + } + }, + "type": "@n8n/n8n-nodes-langchain.lmChatGoogleGemini", + "typeVersion": 1, + "position": [ + -3488, + 1184 + ], + "id": "5b645a7b-acc2-46f6-88e5-82d8d79a8986", + "name": "Google Gemini Chat Model", + "credentials": { + "googlePalmApi": { + "id": "8wBnH32SbKmjkfYp", + "name": "Google Gemini(PaLM) Api account" + } + } + }, + { + "parameters": { + "jsCode": "// ═══════════════════════════════════════════════════════════════════\n// Flatten OCR Error for Log\n// Placed BEFORE: Append row in sheet5\n// Receives: OCR Extraction Valid?2 → FALSE branch\n//\n// Produces the SAME complete_error format as Flatten Data for Log2:\n//\n// Error Type : Invalid File Type (400)\n// Error From : [DMH]\n// ─────────────────────────────────\n// Raw API error : 400 - {\"error\":\"Invalid file type\"}\n//\n// Correctly classifies all OCR errors including:\n// 403 PERMISSION_DENIED → AI INDIA (Server Issue)\n// 400 Invalid file type → DMH\n// 504 Gateway Timeout → AI INDIA\n// 500 Server Crash → AI INDIA\n// PIL image error → AI INDIA\n// PO number missing → DMH\n// Duplicate Invoice → DMH\n// ═══════════════════════════════════════════════════════════════════\n\n// ── Helper: safe word-boundary HTTP status code check ────────────\n// Prevents \"400\" matching \"14005\" or UNKNOWN_ERROR400 from the prefix\nfunction hasHttpCode(text, code) {\n const c = String(code).replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n return new RegExp('(^|[^0-9])' + c + '([^0-9]|$)').test(String(text || ''));\n}\n\n// ── Error classifier ───────────────────────────────────────────────\n// Returns: { owner: \"AI INDIA\"|\"DMH\", category: string, detail: string }\nfunction classifyError(rawError) {\n const text = String(rawError || '');\n const cb = text.toLowerCase();\n const raw = text.trim();\n\n if (!cb.trim()) return { owner: 'AI INDIA', category: 'Unknown OCR Error', detail: '(no error message)' };\n\n // ── DMH: Invalid File Type (400) ───────────────────────────────\n // File format not accepted — DMH responsibility\n if (hasHttpCode(text, 400) && cb.includes('invalid file type'))\n return { owner: 'DMH', category: 'Invalid File Type (400)', detail: raw };\n\n // ── DMH: PO Number Missing ──────────────────────────────────────\n // Invoice rejected due to missing PO — DMH responsibility\n if (cb.includes('po number') || cb.includes('po number is missing') ||\n cb.includes('invoice rejected') || cb.includes('valid po number'))\n return { owner: 'DMH', category: 'Invoice Rejected — PO Number Missing', detail: raw };\n\n // ── DMH: Duplicate Invoice ──────────────────────────────────────\n if (cb.includes('duplicate invoice') || cb.includes('already processed') ||\n cb.includes('already exists'))\n return { owner: 'DMH', category: 'Duplicate Invoice', detail: raw };\n\n // ── AI INDIA: Server Issue (Lightning Dunning) ──────────────────\n // Most specific 403 check — must come BEFORE generic 403\n if (hasHttpCode(text, 403) && cb.includes('lightning dunning'))\n return { owner: 'AI INDIA', category: 'API Blocked — Server Issue (403)', detail: raw };\n\n // ── AI INDIA: Server Issue Permission Denied / Quota / Auth ────\n if (hasHttpCode(text, 403) || hasHttpCode(text, 401) || hasHttpCode(text, 429) ||\n cb.includes('permission_denied') ||\n cb.includes('generativelanguage.googleapis') ||\n cb.includes('quota') || cb.includes('rate limit') ||\n cb.includes('resource has been exhausted') ||\n cb.includes('unauthorized') || cb.includes('forbidden'))\n return { owner: 'AI INDIA', category: 'API Error — Server Issue', detail: raw };\n\n // ── AI INDIA: Generic 400 Bad Request ──────────────────────────\n if (hasHttpCode(text, 400))\n return { owner: 'AI INDIA', category: 'Bad Request to OCR API (400)', detail: raw };\n\n // ── AI INDIA: Timeout / Gateway ────────────────────────────────\n if (hasHttpCode(text, 504) ||\n cb.includes('gateway time-out') || cb.includes('gateway timeout') ||\n cb.includes('etimedout') || cb.includes('econnrefused') ||\n cb.includes('socket hang up') || cb.includes('300000ms') ||\n cb.includes('deadline expired') || cb.includes('connect timeout') ||\n cb.includes('read timeout'))\n return { owner: 'AI INDIA', category: 'OCR API Timeout / Gateway Error (504)', detail: raw };\n\n // ── AI INDIA: File Too Large (413) ─────────────────────────────\n if (hasHttpCode(text, 413) || cb.includes('request entity too large') ||\n cb.includes('payload too large') || cb.includes('file size exceeds'))\n return { owner: 'AI INDIA', category: 'File Too Large (413)', detail: raw };\n\n // ── AI INDIA: Server Crash (500) ───────────────────────────────\n if (hasHttpCode(text, 500) &&\n (cb.includes('internal server error') || cb.includes('nginx') ||\n cb.includes('werkzeug') || cb.includes('traceback')))\n return { owner: 'AI INDIA', category: 'OCR Server Internal Crash (500)', detail: raw };\n\n // ── AI INDIA: Invalid Image Format (PIL) ───────────────────────\n if (cb.includes('pil') || cb.includes('pngimageplugin') ||\n cb.includes('cannot identify image') || cb.includes('image file is truncated'))\n return { owner: 'AI INDIA', category: 'Invalid Image Format (PIL Error)', detail: raw };\n\n // ── AI INDIA: No Binary File ────────────────────────────────────\n if ((cb.includes('binary file') && cb.includes('none was found')) ||\n cb.includes('no file was uploaded') || cb.includes('missing file attachment'))\n return { owner: 'AI INDIA', category: 'No Binary File Found', detail: raw };\n\n // ── AI INDIA: OCR Extraction Failed ────────────────────────────\n if (cb.includes('ocr extraction failed') || cb.includes('extraction failed') ||\n cb.includes('could not extract') || cb.includes('parse failure') ||\n cb.includes('ocr_parse_error') || cb.includes('pdf parse') ||\n cb.includes('unknown processing error'))\n return { owner: 'AI INDIA', category: 'OCR Extraction Failed', detail: raw };\n\n // ── AI INDIA: OCR — Missing invoice_number (validation fail) ───\n if (cb.includes('invoice_number') || cb.includes('invoice number'))\n return { owner: 'AI INDIA', category: 'OCR — invoice_number Missing or Empty', detail: raw };\n\n // ── Fallback ────────────────────────────────────────────────────\n return { owner: 'AI INDIA', category: 'OCR Error — Unclassified', detail: raw };\n}\n\n// ── Build complete_error block ──────────────────────────────────────\n//\n// Error Type : Invalid File Type (400)\n// Error From : [DMH]\n// ─────────────────────────────────\n// Raw API error : 400 - {\"error\":\"Invalid file type\"}\n//\nfunction buildCompleteError(rawError) {\n const c = classifyError(rawError);\n const divider = '─────────────────────────────────';\n return [\n 'Error Type : ' + c.category,\n 'Error From : [' + c.owner + ']',\n divider,\n 'Raw API error : ' + (c.detail || '(no raw message)')\n ].join('\\n');\n}\n\n// ── Resolve messageId — 4-source fallback ──────────────────────────\nfunction resolveMessageId(item) {\n try { const v = $('Set messageId Field1').item.json.messageId; if (v) return String(v); } catch(e) {}\n try { const v = $('Switch2').item.json.id; if (v) return String(v); } catch(e) {}\n if (item.json.messageId) return String(item.json.messageId);\n if (item.json.id) return String(item.json.id);\n return '';\n}\n\n// ── Normalize raw error from item.json.error ───────────────────────\nfunction extractRawError(data) {\n if (!data.error) return '(no error message)';\n if (typeof data.error === 'string') return data.error;\n if (typeof data.error === 'object') {\n return data.error.message || data.error.description || JSON.stringify(data.error);\n }\n return String(data.error);\n}\n\n// ════════════════════════════════════════════════════════════════════\n// MAIN\n// ════════════════════════════════════════════════════════════════════\n\nconst output = [];\n\nitems.forEach(item => {\n\n const data = item.json;\n\n // ── IST Timestamp ──────────────────────────────────────────────\n const now = new Date();\n const date = now.toLocaleDateString('en-CA', { timeZone: 'Asia/Kolkata' });\n const time = now.toLocaleTimeString('en-IN', { timeZone: 'Asia/Kolkata', hour12: true });\n\n // ── messageId ──────────────────────────────────────────────────\n const messageId = resolveMessageId(item);\n\n // ── Attachment name ────────────────────────────────────────────\n let attachment_name = '';\n try { attachment_name = $('Split: One Item Per Attachment3').item.json.attachment_name || ''; } catch(e) {}\n if (!attachment_name) attachment_name = data.attachment_name || '';\n\n // ── Build error string ─────────────────────────────────────────\n const rawError = extractRawError(data);\n const complete_error = buildCompleteError(rawError);\n\n // ── Output — SAME columns as main sheet ───────────────────────\n output.push({\n json: {\n // Timestamp\n date,\n time,\n\n // Invoice fields — all blank (OCR failed, nothing extracted)\n invoice_id: '',\n invoice_number: '',\n invoice_date: '',\n seller_name: '',\n seller_gstin: '',\n customer_name: '',\n invoice_amount: 0,\n attachment_name,\n\n // Status\n status: '❌ FAILED',\n grn_message: 'OCR Extraction Failed — Server Issue — Invoice not processed',\n\n // Error block\n complete_error,\n\n // Traceability\n messageId\n }\n });\n\n});\n\nreturn output;" + }, + "type": "n8n-nodes-base.code", + "typeVersion": 2, + "position": [ + -1120, + 384 + ], + "id": "6402173a-44c3-4233-b394-0581d4f47f89", + "name": "Flatten OCR Error for Log", + "onError": "continueRegularOutput" + } + ], + "connections": { + "Append row in sheet1": { + "main": [ + [ + { + "node": "Loop: Each Attachment2", + "type": "main", + "index": 0 + } + ] + ] + }, + "Watch New_Invoice Label1": { + "main": [ + [ + { + "node": "Fetch Emails from New_Invoice (max 3)1", + "type": "main", + "index": 0 + } + ] + ] + }, + "AI: Classify Invoice1": { + "main": [ + [ + { + "node": "Merge: Email + AI Classification1", + "type": "main", + "index": 1 + } + ] + ] + }, + "OCR: Extract Invoice Data2": { + "main": [ + [ + { + "node": "OCR Extraction Valid?2", + "type": "main", + "index": 0 + } + ] + ] + }, + "Merge: Email + AI Classification1": { + "main": [ + [ + { + "node": "Split: One Item Per Attachment3", + "type": "main", + "index": 0 + } + ] + ] + }, + "Fetch Emails from New_Invoice (max 3)1": { + "main": [ + [ + { + "node": "Loop: Each Email2", + "type": "main", + "index": 0 + } + ] + ] + }, + "Loop: Each Email2": { + "main": [ + [ + { + "node": "Label: Add Processing2", + "type": "main", + "index": 0 + } + ], + [ + { + "node": "End: No More Emails1", + "type": "main", + "index": 0 + } + ] + ] + }, + "End: No More Emails1": { + "main": [ + [ + { + "node": "Loop: Each Email2", + "type": "main", + "index": 0 + } + ] + ] + }, + "Label: Add Processing2": { + "main": [ + [ + { + "node": "Label: Remove New_Invoice1", + "type": "main", + "index": 0 + } + ] + ] + }, + "Label: Remove New_Invoice1": { + "main": [ + [ + { + "node": "Fetch Full Email + Attachments2", + "type": "main", + "index": 0 + } + ] + ] + }, + "Fetch Full Email + Attachments2": { + "main": [ + [ + { + "node": "Set messageId Field1", + "type": "main", + "index": 0 + }, + { + "node": "AI: Classify Invoice1", + "type": "main", + "index": 0 + } + ] + ] + }, + "Parse AI Output2": { + "main": [ + [ + { + "node": "Switch2", + "type": "main", + "index": 0 + } + ] + ] + }, + "Set messageId Field1": { + "main": [ + [ + { + "node": "Merge: Email + AI Classification1", + "type": "main", + "index": 0 + } + ] + ] + }, + "Label: Add Not_Invoice2": { + "main": [ + [ + { + "node": "Loop: Each Attachment2", + "type": "main", + "index": 0 + } + ] + ] + }, + "Label: Add Invoice_Done2": { + "main": [ + [ + { + "node": "Loop: Each Attachment2", + "type": "main", + "index": 0 + } + ] + ] + }, + "Label: Add Invoice_failed2": { + "main": [ + [ + { + "node": "Loop: Each Attachment2", + "type": "main", + "index": 0 + } + ] + ] + }, + "OCR Extraction Valid?2": { + "main": [ + [ + { + "node": "Normalize Invoice Fields2", + "type": "main", + "index": 0 + } + ], + [ + { + "node": "Flatten OCR Error for Log", + "type": "main", + "index": 0 + } + ] + ] + }, + "GRN: Create Record in Hospital2": { + "main": [ + [ + { + "node": "Flatten Data for Log2", + "type": "main", + "index": 0 + } + ] + ] + }, + "Normalize Invoice Fields2": { + "main": [ + [ + { + "node": "GRN: Create Record in Hospital2", + "type": "main", + "index": 0 + } + ] + ] + }, + "GRN Created Successfully?2": { + "main": [ + [ + { + "node": "Label: Add Invoice_Done2", + "type": "main", + "index": 0 + } + ], + [ + { + "node": "Failed To add2", + "type": "main", + "index": 0 + } + ] + ] + }, + "Split: One Item Per Attachment3": { + "main": [ + [ + { + "node": "Loop: Each Attachment2", + "type": "main", + "index": 0 + } + ] + ] + }, + "Loop: Each Attachment2": { + "main": [ + [], + [ + { + "node": "Parse AI Output2", + "type": "main", + "index": 0 + } + ] + ] + }, + "Wait 7s Before OCR2": { + "main": [ + [ + { + "node": "OCR: Extract Invoice Data2", + "type": "main", + "index": 0 + } + ] + ] + }, + "Flatten Data for Log2": { + "main": [ + [ + { + "node": "Log to Google Sheets (Daily Logs)2", + "type": "main", + "index": 0 + } + ] + ] + }, + "Append row in sheet5": { + "main": [ + [ + { + "node": "Label: Add Invoice_failed2", + "type": "main", + "index": 0 + } + ] + ] + }, + "Code in JavaScript6": { + "main": [ + [ + { + "node": "Append row in sheet1", + "type": "main", + "index": 0 + } + ] + ] + }, + "Switch2": { + "main": [ + [ + { + "node": "Filter: Skip Non-OCR-able Files", + "type": "main", + "index": 0 + } + ], + [ + { + "node": "Code in JavaScript6", + "type": "main", + "index": 0 + } + ], + [ + { + "node": "Label: Add Not_Invoice2", + "type": "main", + "index": 0 + } + ], + [ + { + "node": "Code in JavaScript6", + "type": "main", + "index": 0 + } + ] + ] + }, + "Filter: Skip Non-OCR-able Files": { + "main": [ + [ + { + "node": "Wait 7s Before OCR2", + "type": "main", + "index": 0 + } + ] + ] + }, + "Failed To add2": { + "main": [ + [ + { + "node": "Loop: Each Attachment2", + "type": "main", + "index": 0 + } + ] + ] + }, + "Groq Chat Model1": { + "ai_languageModel": [ + [ + { + "node": "AI: Classify Invoice1", + "type": "ai_languageModel", + "index": 1 + } + ] + ] + }, + "Log to Google Sheets (Daily Logs)2": { + "main": [ + [ + { + "node": "GRN Created Successfully?2", + "type": "main", + "index": 0 + } + ] + ] + }, + "Google Gemini Chat Model": { + "ai_languageModel": [ + [ + { + "node": "AI: Classify Invoice1", + "type": "ai_languageModel", + "index": 0 + } + ] + ] + }, + "Flatten OCR Error for Log": { + "main": [ + [ + { + "node": "Append row in sheet5", + "type": "main", + "index": 0 + } + ] + ] + } + }, + "nodeGroups": [], + "authors": "Invoice Aiindia", + "name": "Version e33393f4", + "description": "", + "autosaved": true, + "workflowPublishHistory": [ + { + "createdAt": "2026-10-10T10:33:00.631Z", + "id": 35, + "workflowId": "EyAw3kSLbeIEnpyf", + "versionId": "e33393f4-a186-4ea6-8ab3-61c482ec228f", + "event": "activated", + "userId": "9f578e99-f4de-457a-8344-b8c82fadc25d" + } + ] + }, + "scopes": [ + "execution:reveal", + "workflow:create", + "workflow:delete", + "workflow:disableRedaction", + "workflow:enableRedaction", + "workflow:execute", + "workflow:execute-chat", + "workflow:export", + "workflow:import", + "workflow:list", + "workflow:move", + "workflow:publish", + "workflow:read", + "workflow:share", + "workflow:unpublish", + "workflow:unshare", + "workflow:update" + ], + "checksum": "7c94d68081bd1bfd43b80829df06849c5f0e7c71004c5ba0492cdbd91f5c1b59" +} \ No newline at end of file diff --git a/drug_list.csv b/drug_list.csv index 37db547..4751897 100644 --- a/drug_list.csv +++ b/drug_list.csv @@ -14353,3 +14353,9 @@ BHARTI01,paracetamol (10mg) + thiocolchicoside (10mg)(null mg)Tablet DMH01,Ajay + Vishal(20 mg)Tablet JPL002, MET137,Methylcobalamin(1500mcg)+l-methylfolate(10mg)+pyridoxal-5-phosphate(5mg) Film coated tablet +SR-06-0058,SWAN MARTIN SKIN GRAFTING BLADE 5% GST +AL-03-0099,SURGICARE NEURO PF 6.5 +AL-09-8765,RESOURC HIPRO VANILLA 400G +SR-02-2310,CATHETER L6JR35 LA 6F 100CM JR35 +AL-03-0989,RESOURCE RENAL VANILLA 400G +AL-03-0336,ROLLER BAND 10CM*12MTR diff --git a/free_item_splitter.py b/free_item_splitter.py index 01871a7..23d6e1e 100644 --- a/free_item_splitter.py +++ b/free_item_splitter.py @@ -361,4 +361,4 @@ def get_free_item_stats(data: Dict[str, Any], total_before: Optional[int] = None 'paid_items': paid_count, 'free_items': free_count, 'has_free_items': free_count > 0 - } + } \ No newline at end of file diff --git a/invoice.db b/invoice.db index ac6ca7a..4c1fcc8 100644 Binary files a/invoice.db and b/invoice.db differ diff --git a/item-code.7z b/item-code.7z new file mode 100644 index 0000000..637ea3c Binary files /dev/null and b/item-code.7z differ diff --git a/item_code_matcher.py b/item_code_matcher.py index 759d109..02c14cd 100644 --- a/item_code_matcher.py +++ b/item_code_matcher.py @@ -28,11 +28,13 @@ Design notes (why matches are refused rather than guessed): import os import re import logging +import threading from difflib import SequenceMatcher logger = logging.getLogger(__name__) DRUG_DATABASE = None # dict: lowercase raw name -> {'item_code','name','parsed'} +CATALOG_CODES_SET = set() # set of uppercase item codes present in catalog # ---- Tunables --------------------------------------------------------- FUZZY_THRESHOLD = 0.85 # minimum spelling similarity for a fuzzy match (0-1) @@ -86,10 +88,12 @@ def parse_drug_name(text): return {'name': ' '.join(name_words), 'numbers': numbers, 'forms': forms} -def load_drug_database(csv_path='drug_list.csv'): +def load_drug_database(csv_path=None): + if csv_path is None: + csv_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'drug_list.csv') """Load the CSV into memory. Safe to call again to reload (e.g. after the CSV is updated) — just re-run it, no restart needed.""" - global DRUG_DATABASE + global DRUG_DATABASE, CATALOG_CODES_SET import pandas as pd if not os.path.exists(csv_path): @@ -116,6 +120,7 @@ def load_drug_database(csv_path='drug_list.csv'): 'parsed': parse_drug_name(name), } DRUG_DATABASE = db + CATALOG_CODES_SET = {v['item_code'] for v in db.values()} logger.info(f"✅ Loaded {len(db)} drugs from {csv_path}") except Exception as e: logger.error(f"❌ Failed to load {csv_path}: {e}") @@ -125,6 +130,8 @@ def load_drug_database(csv_path='drug_list.csv'): def extract_item_code_from_drug_list(drug_description): """Return the item_code for a drug, or None if there's no confident match.""" + if DRUG_DATABASE is None: + load_drug_database() if not drug_description or not DRUG_DATABASE: return None @@ -203,18 +210,227 @@ def enrich_items_with_item_code(extracted_data, use_drug_list=True): existing = safe_strip(item.get('item_code')) if existing: - item['item_code_source'] = 'invoice' + if not item.get('item_code_source') or item.get('item_code_source') == 'not_found': + item['item_code_source'] = 'invoice' + item['in_csv'] = code_in_catalog(existing) continue if not use_drug_list: item['item_code_source'] = 'not_found' + item['in_csv'] = False continue matched = extract_item_code_from_drug_list(item.get('description')) if matched: item['item_code'] = matched item['item_code_source'] = 'drug_list_match' + item['in_csv'] = True else: item['item_code_source'] = 'not_found' + item['in_csv'] = False - return extracted_data \ No newline at end of file + return extracted_data + + +def code_in_catalog(code): + """Check if code exists in the catalog.""" + global CATALOG_CODES_SET + if not code: + return False + if not CATALOG_CODES_SET: + load_drug_database() + return str(code).strip().upper() in CATALOG_CODES_SET + + +_catalog_lock = threading.Lock() + +def append_to_drug_catalog(item_code, name, csv_path=None): + """Safely append a verified item code to drug_list.csv and hot-reload.""" + global DRUG_DATABASE, CATALOG_CODES_SET + import csv + + if csv_path is None: + csv_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'drug_list.csv') + + code_clean = str(item_code).strip().upper() + name_clean = str(name).strip() + + if not code_clean: + return False + + # Check if this exact description already matches this item code in catalog + if extract_item_code_from_drug_list(name_clean) == code_clean: + return True + + with _catalog_lock: + try: + file_exists = os.path.exists(csv_path) + with open(csv_path, 'a', newline='', encoding='utf-8') as f: + writer = csv.writer(f) + if not file_exists or os.path.getsize(csv_path) == 0: + writer.writerow(['item_code', 'name']) + writer.writerow([code_clean, name_clean]) + + load_drug_database(csv_path) + logger.info(f"✅ Appended item code to {csv_path}: {code_clean} - {name_clean}") + return True + except Exception as e: + logger.error(f"❌ Failed to append item code to {csv_path}: {e}") + return False + + +def update_drug_catalog_entry(old_item_code, old_name, new_item_code, new_name, csv_path=None): + """Safely update an existing item code / drug name in drug_list.csv and hot-reload.""" + global DRUG_DATABASE, CATALOG_CODES_SET + import csv + + if csv_path is None: + csv_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'drug_list.csv') + + old_code_clean = str(old_item_code or '').strip().upper() + old_name_clean = str(old_name or '').strip() + new_code_clean = str(new_item_code or '').strip().upper() + new_name_clean = str(new_name or '').strip() + + if not old_code_clean: + return False, "Existing item code is required" + if not new_code_clean or not new_name_clean: + return False, "New item code and drug name cannot be empty" + + if not os.path.exists(csv_path): + return False, f"File {csv_path} not found" + + with _catalog_lock: + try: + rows = [] + updated = False + with open(csv_path, 'r', newline='', encoding='utf-8-sig', errors='replace') as f: + reader = csv.reader(f) + header = next(reader, None) + if not header: + return False, "CSV file is empty" + rows.append(header) + header_lower = [h.strip().lower() for h in header] + code_idx = header_lower.index('item_code') if 'item_code' in header_lower else 0 + name_idx = header_lower.index('name') if 'name' in header_lower else 1 + + for row in reader: + if len(row) <= max(code_idx, name_idx): + rows.append(row) + continue + r_code = row[code_idx].strip().upper() + r_name = row[name_idx].strip() + if r_code == old_code_clean and (not old_name_clean or r_name.lower() == old_name_clean.lower()): + row[code_idx] = new_code_clean + row[name_idx] = new_name_clean + updated = True + rows.append(row) + + if not updated: + return False, f"Catalog item '{old_code_clean}' not found" + + with open(csv_path, 'w', newline='', encoding='utf-8') as f: + writer = csv.writer(f) + writer.writerows(rows) + + load_drug_database(csv_path) + logger.info(f"✅ Updated catalog entry in {csv_path}: {old_code_clean} -> {new_code_clean} ({new_name_clean})") + return True, None + except Exception as e: + logger.error(f"❌ Failed to update catalog entry in {csv_path}: {e}") + return False, str(e) + + +def delete_drug_catalog_entry(item_code, name=None, csv_path=None): + """Safely delete an item code entry from drug_list.csv and hot-reload.""" + global DRUG_DATABASE, CATALOG_CODES_SET + import csv + + if csv_path is None: + csv_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'drug_list.csv') + + code_clean = str(item_code or '').strip().upper() + name_clean = str(name or '').strip() + + if not code_clean: + return False, "Item code is required" + + if not os.path.exists(csv_path): + return False, f"File {csv_path} not found" + + with _catalog_lock: + try: + rows = [] + deleted = False + with open(csv_path, 'r', newline='', encoding='utf-8-sig', errors='replace') as f: + reader = csv.reader(f) + header = next(reader, None) + if not header: + return False, "CSV file is empty" + rows.append(header) + header_lower = [h.strip().lower() for h in header] + code_idx = header_lower.index('item_code') if 'item_code' in header_lower else 0 + name_idx = header_lower.index('name') if 'name' in header_lower else 1 + + for row in reader: + if len(row) <= max(code_idx, name_idx): + rows.append(row) + continue + r_code = row[code_idx].strip().upper() + r_name = row[name_idx].strip() + if r_code == code_clean and (not name_clean or r_name.lower() == name_clean.lower()): + deleted = True + continue + rows.append(row) + + if not deleted: + return False, f"Catalog item '{code_clean}' not found" + + with open(csv_path, 'w', newline='', encoding='utf-8') as f: + writer = csv.writer(f) + writer.writerows(rows) + + load_drug_database(csv_path) + logger.info(f"✅ Deleted catalog entry from {csv_path}: {code_clean} ({name_clean})") + return True, None + except Exception as e: + logger.error(f"❌ Failed to delete catalog entry from {csv_path}: {e}") + return False, str(e) + + +def search_drug_catalog(query, limit=50): + """Search drug catalog by code or description with prefix-first ranking.""" + global DRUG_DATABASE, CATALOG_CODES_SET + if DRUG_DATABASE is None: + load_drug_database() + + if not DRUG_DATABASE: + return [] + + q = str(query or '').strip().lower() + if not q: + return [ + {'item_code': item['item_code'], 'name': item['name'], 'category': 'General'} + for item in list(DRUG_DATABASE.values())[:limit] + ] + + matches = [] + for item in DRUG_DATABASE.values(): + code_str = str(item.get('item_code', '')).lower() + name_str = str(item.get('name', '')).lower() + if q in code_str or q in name_str: + is_prefix = code_str.startswith(q) or name_str.startswith(q) + matches.append((0 if is_prefix else 1, item)) + + matches.sort(key=lambda x: (x[0], x[1]['name'])) + return [ + {'item_code': m[1]['item_code'], 'name': m[1]['name'], 'category': 'General'} + for m in matches[:limit] + ] + + +# Preload drug catalog on import +try: + load_drug_database() +except Exception: + pass diff --git a/n8n_invoice_automation_workflow.json b/n8n_invoice_automation_workflow.json new file mode 100644 index 0000000..b8856e0 --- /dev/null +++ b/n8n_invoice_automation_workflow.json @@ -0,0 +1,877 @@ +{ + "name": "Invoice Automation-DMH Hospital LOCAL TEST", + "nodes": [ + { + "parameters": { + "pollTimes": { + "item": [ + { + "mode": "everyMinute" + } + ] + }, + "filters": { + "foldersToInclude": [ + "AQMkADAwATM0MDAAMi1hYzgzLTQxMQAyLTAwAi0wMAoALgAAA3R9Z7-WZCBHqvG_09flPEoBAJRkAPlTP4RNsddkpsHybkoAAAJoYgAAAA==", + "AQMkADAwATM0MDAAMi1hYzgzLTQxMQAyLTAwAi0wMAoALgAAA3R9Z7-WZCBHqvG_09flPEoBAJRkAPlTP4RNsddkpsHybkoAAAJodQAAAA==", + "AQMkADAwATM0MDAAMi1hYzgzLTQxMQAyLTAwAi0wMAoALgAAA3R9Z7-WZCBHqvG_09flPEoBAJRkAPlTP4RNsddkpsHybkoAAAIBFgAAAA==" + ] + }, + "options": { + "downloadAttachments": true + } + }, + "type": "n8n-nodes-base.microsoftOutlookTrigger", + "typeVersion": 1, + "position": [-4832, 1056], + "id": "be7ad802-919e-41d8-bd76-d0291e5640dd", + "name": "Watch New_Invoice Label1", + "credentials": { + "microsoftOutlookOAuth2Api": { + "id": "neYqnH7A2WPe5lTs", + "name": "Microsoft Outlook account" + } + } + }, + { + "parameters": { + "operation": "getAll", + "limit": 3, + "filtersUI": { + "values": { + "filters": { + "foldersToInclude": [ + "AQMkADAwATM0MDAAMi1hYzgzLTQxMQAyLTAwAi0wMAoALgAAA3R9Z7-WZCBHqvG_09flPEoBAJRkAPlTP4RNsddkpsHybkoAAAJoYgAAAA==", + "AQMkADAwATM0MDAAMi1hYzgzLTQxMQAyLTAwAi0wMAoALgAAA3R9Z7-WZCBHqvG_09flPEoBAJRkAPlTP4RNsddkpsHybkoAAAIBFgAAAA==" + ] + } + } + }, + "options": { + "downloadAttachments": true + } + }, + "type": "n8n-nodes-base.microsoftOutlook", + "typeVersion": 2, + "position": [-4608, 1056], + "id": "939a1916-4d96-4550-9482-fd51209d060a", + "name": "Fetch Emails from New_Invoice (max 3)1", + "executeOnce": true, + "credentials": { + "microsoftOutlookOAuth2Api": { + "id": "neYqnH7A2WPe5lTs", + "name": "Microsoft Outlook account" + } + } + }, + { + "parameters": { + "options": {} + }, + "type": "n8n-nodes-base.splitInBatches", + "typeVersion": 3, + "position": [-4384, 1056], + "id": "d71ef907-462d-4c40-bb01-2476d9cb7bf3", + "name": "Loop: Each Email2" + }, + { + "parameters": {}, + "type": "n8n-nodes-base.noOp", + "name": "End: No More Emails1", + "typeVersion": 1, + "position": [-4160, 1104], + "id": "90ad177b-23a6-41d0-86fe-fd3f3725e6d8" + }, + { + "parameters": { + "operation": "update", + "messageId": { + "__rl": true, + "value": "={{ $json.id }}", + "mode": "id" + }, + "updateFields": { + "folderId": { + "__rl": true, + "value": "AQMkADAwATM0MDAAMi1hYzgzLTQxMQAyLTAwAi0wMAoALgAAA3R9Z7-WZCBHqvG_09flPEoBAJRkAPlTP4RNsddkpsHybkoAAAJocQAAAA==", + "mode": "list", + "cachedResultName": "Processing" + } + } + }, + "type": "n8n-nodes-base.microsoftOutlook", + "typeVersion": 2, + "position": [-4160, 912], + "id": "aaab2e62-0622-4bbd-b3d1-648fcb06b290", + "name": "Label: Add Processing2", + "credentials": { + "microsoftOutlookOAuth2Api": { + "id": "neYqnH7A2WPe5lTs", + "name": "Microsoft Outlook account" + } + }, + "onError": "continueRegularOutput" + }, + { + "parameters": { + "operation": "move", + "messageId": { + "__rl": true, + "value": "={{ $('Fetch Emails from New_Invoice (max 3)1').item.json.id }}", + "mode": "id" + }, + "folderId": { + "__rl": true, + "value": "AQMkADAwATM0MDAAMi1hYzgzLTQxMQAyLTAwAi0wMAoALgAAA3R9Z7-WZCBHqvG_09flPEoBAJRkAPlTP4RNsddkpsHybkoAAAJocQAAAA==", + "mode": "list", + "cachedResultName": "Processing" + } + }, + "type": "n8n-nodes-base.microsoftOutlook", + "typeVersion": 2, + "position": [-3936, 912], + "id": "584c67c7-ff4d-4b72-8a91-a94fe1c6ad4b", + "name": "Label: Remove New_Invoice1", + "credentials": { + "microsoftOutlookOAuth2Api": { + "id": "neYqnH7A2WPe5lTs", + "name": "Microsoft Outlook account" + } + }, + "disabled": true + }, + { + "parameters": { + "operation": "get", + "messageId": { + "__rl": true, + "mode": "id", + "value": "={{ $json.id }}" + }, + "options": { + "downloadAttachments": true + } + }, + "type": "n8n-nodes-base.microsoftOutlook", + "typeVersion": 2, + "position": [-3712, 912], + "id": "8f05ea79-5bef-42c3-aef3-fc99f97397e8", + "name": "Fetch Full Email + Attachments2", + "credentials": { + "microsoftOutlookOAuth2Api": { + "id": "neYqnH7A2WPe5lTs", + "name": "Microsoft Outlook account" + } + } + }, + { + "parameters": { + "assignments": { + "assignments": [ + { + "id": "00093515-229c-432c-9c8d-a2ef09acf369", + "name": "messageId", + "value": "={{$json.id}}", + "type": "string" + } + ] + }, + "includeOtherFields": true, + "options": {} + }, + "type": "n8n-nodes-base.set", + "typeVersion": 3.4, + "position": [-3424, 672], + "id": "a5f2223b-6f10-4437-81dc-9a34d57996d0", + "name": "Set messageId Field1" + }, + { + "parameters": { + "promptType": "define", + "text": "=Email Subject:\n{{$json.subject}}\n\nEmail Body:\n{{$json.bodyPreview || $json.body.content}}\n\nSender Email:\n{{ $json.from }}\n\nAttachment File Name:\n{{$binary.attachment_0.fileName}}\n\nAttachment MIME Type:\n{{$binary.attachment_0.mimeType}}\n", + "needsFallback": true, + "options": { + "systemMessage": "You are an invoice recognition agent operating inside an automated workflow.\n\nYou will receive:\nEmail subject\nEmail body content (plain text or HTML converted to text)\nSender email address and name\nAttachment file name\nAttachment MIME type\n\nYour task:\nDetermine whether the email and its attachment should be treated as a BUSINESS INVOICE.\n\nClassification rules:\nClassify the email as an invoice if ANY billing, payment, receipt, tax, or business transaction context is present.\nThe word \"invoice\" may or may not appear explicitly.\nAttachment file names containing company or brand names (for example: BISLERI.pdf, TATA.pdf, AMAZON.pdf, A+V+TRADING.pdf) may represent invoices.\nIf the attachment MIME type is \"application/pdf\" and the email context is business-related, classify it as an invoice.\nIf there is reasonable doubt, classify the email as an invoice.\n\nHard constraints:\nDo NOT read or analyze PDF binary content.\nDo NOT perform OCR.\nDo NOT extract invoice numbers, dates, or amounts.\nNEVER return null or undefined.\nALWAYS return all fields.\nNEVER include markdown formatting.\nNEVER wrap the output in ```json or ``` blocks.\nNEVER include explanations, headings, or extra text.\n\nOutput requirements:\nReturn ONLY a single valid JSON object.\nThe response must start with { and end with }.\nThe output must be directly parseable using JSON.parse().\n\nReturn the response in this EXACT format:\n\n{\n \"is_invoice\": true or false,\n \"confidence\": \"high\" or \"medium\" or \"low\",\n \"reason\": \"\"\n}" + } + }, + "type": "@n8n/n8n-nodes-langchain.agent", + "typeVersion": 2.2, + "position": [-3488, 960], + "id": "f43530ad-adfa-41ba-b3e2-59c500b8931e", + "name": "AI: Classify Invoice1", + "alwaysOutputData": false, + "retryOnFail": true, + "onError": "continueRegularOutput" + }, + { + "parameters": { + "mode": "combine", + "combineBy": "combineByPosition", + "options": {} + }, + "type": "n8n-nodes-base.merge", + "typeVersion": 3.2, + "position": [-3136, 912], + "id": "c3974a60-9c2b-476b-9283-7eb744b4501e", + "name": "Merge: Email + AI Classification1" + }, + { + "parameters": { + "jsCode": "const newItems = [];\n\nfor (const item of items) {\n\n const binaries = item.binary || {};\n const keys = Object.keys(binaries);\n\n if (keys.length > 0) {\n\n for (const key of keys) {\n\n const attachment_name = binaries[key].fileName || '';\n\n newItems.push({\n json: {\n ...item.json,\n attachment_name: attachment_name\n },\n binary: {\n file: binaries[key]\n }\n });\n }\n\n } else {\n\n let parsedOutput = {};\n try {\n parsedOutput = JSON.parse(item.json.output || '{}');\n } catch (e) {\n parsedOutput = {};\n }\n\n newItems.push({\n json: {\n ...item.json,\n ...parsedOutput,\n attachment_name: ''\n }\n });\n }\n}\n\nreturn newItems;" + }, + "type": "n8n-nodes-base.code", + "typeVersion": 2, + "position": [-2912, 912], + "id": "b019335c-9a06-417b-95bb-862fcfa1a8fc", + "name": "Split: One Item Per Attachment3", + "alwaysOutputData": true, + "retryOnFail": true + }, + { + "parameters": { + "options": {} + }, + "type": "n8n-nodes-base.splitInBatches", + "typeVersion": 3, + "position": [-2688, 912], + "id": "7cb557ad-cb6d-45d4-99e9-8966e310b493", + "name": "Loop: Each Attachment2" + }, + { + "parameters": { + "jsCode": "// Parse AI classification output — full production-grade parser\nreturn items.map(item => {\n\n let classification = 'error';\n let confidence = 'low';\n let ai_reason = '';\n let error_detail = '';\n\n try {\n if (item.json.error) {\n const errStr = typeof item.json.error === 'object' ? (item.json.error.message || JSON.stringify(item.json.error)) : String(item.json.error);\n error_detail = 'AGENT_ERROR: ' + errStr.slice(0, 300);\n classification = 'error';\n return { json: { ...item.json, classification, confidence, ai_reason, error_detail }, binary: item.binary };\n }\n\n const FIELD_PATHS = ['output', 'text', 'content', 'message', 'result', 'response'];\n let raw = null;\n let parsed = null;\n\n for (const path of FIELD_PATHS) {\n const val = item.json[path];\n if (val === null || val === undefined || val === '') continue;\n raw = val;\n break;\n }\n\n if (raw === null) {\n if (item.json.is_invoice !== undefined) { parsed = item.json; raw = null; }\n else { error_detail = 'NO_OUTPUT_FIELD'; classification = 'error'; return { json: { ...item.json, classification, confidence, ai_reason, error_detail }, binary: item.binary }; }\n }\n\n if (parsed === null && raw !== null) {\n if (Array.isArray(raw)) raw = raw[0];\n if (raw !== null && typeof raw === 'object') {\n if (raw.kwargs && raw.kwargs.content !== undefined) { raw = raw.kwargs.content; }\n else if (raw.output !== undefined) { raw = raw.output; if (raw !== null && typeof raw === 'object') { parsed = raw; raw = null; } }\n else { parsed = raw; raw = null; }\n }\n }\n\n if (parsed === null && raw !== null) {\n let cleaned = String(raw).replace(/\\uFEFF/g, '').replace(/```json\\s*/gi, '').replace(/```\\s*/g, '').trim();\n try { const r = JSON.parse(cleaned); if (r && typeof r === 'object' && !Array.isArray(r)) parsed = r; } catch(e) {}\n if (!parsed) {\n const m = cleaned.match(/\"is_invoice\"\\s*:\\s*(true|false)/i);\n if (m) parsed = { is_invoice: m[1] === 'true', confidence: 'low', reason: '' };\n }\n if (!parsed) { error_detail = 'PARSE_FAILED: ' + cleaned.slice(0, 200); classification = 'error'; return { json: { ...item.json, classification, confidence, ai_reason, error_detail }, binary: item.binary }; }\n }\n\n if (parsed) {\n const rawFlag = parsed.is_invoice !== undefined ? parsed.is_invoice : (parsed.isInvoice !== undefined ? parsed.isInvoice : undefined);\n if (rawFlag === undefined) { error_detail = 'IS_INVOICE_NOT_FOUND'; classification = 'error'; }\n else {\n const flag = String(rawFlag).toLowerCase().trim();\n if (['true','1','yes'].includes(flag)) classification = 'invoice';\n else if (['false','0','no'].includes(flag)) classification = 'not_invoice';\n else { error_detail = 'UNEXPECTED_VALUE: ' + rawFlag; classification = 'error'; }\n }\n const rawConf = String(parsed.confidence || 'low').toLowerCase();\n if (['high','certain','definite'].some(v => rawConf.includes(v))) confidence = 'high';\n else if (['medium','moderate','likely'].some(v => rawConf.includes(v))) confidence = 'medium';\n else confidence = 'low';\n ai_reason = String(parsed.reason || parsed.explanation || '').slice(0, 500);\n }\n\n } catch (e) { error_detail = 'UNCAUGHT: ' + e.message; classification = 'error'; }\n\n return { json: { ...item.json, classification, confidence, ai_reason, error_detail }, binary: item.binary };\n});" + }, + "type": "n8n-nodes-base.code", + "typeVersion": 2, + "position": [-2464, 320], + "id": "e76f2124-e8b2-4b52-86c5-0ab65b6068cf", + "name": "Parse AI Output2", + "alwaysOutputData": true + }, + { + "parameters": { + "rules": { + "values": [ + { + "conditions": { + "conditions": [{ "leftValue": "={{ $json.classification }}", "rightValue": "invoice", "operator": { "type": "string", "operation": "equals" } }], + "combinator": "and" + } + }, + { + "conditions": { + "conditions": [{ "id": "err", "leftValue": "={{ $json.classification }}", "rightValue": "error", "operator": { "type": "string", "operation": "equals" } }], + "combinator": "and" + } + }, + { + "conditions": { + "conditions": [{ "id": "ni", "leftValue": "={{ $json.classification }}", "rightValue": "not_invoice", "operator": { "type": "string", "operation": "equals" } }], + "combinator": "and" + } + } + ] + }, + "options": { "fallbackOutput": "extra" } + }, + "type": "n8n-nodes-base.switch", + "typeVersion": 3.4, + "position": [-2240, 288], + "id": "334b80a6-4e59-44b6-a627-536fc65ea1cd", + "name": "Switch2" + }, + { + "parameters": { + "amount": 1 + }, + "type": "n8n-nodes-base.wait", + "typeVersion": 1.1, + "position": [-1792, 192], + "id": "dab6bfb7-215a-4ccd-8964-333200305739", + "name": "Wait 7s Before OCR2" + }, + { + "parameters": { + "method": "POST", + "url": "=http://localhost:{{ $env.LOCAL_APP_PORT || 8080 }}/process-invoice", + "sendHeaders": true, + "headerParameters": { + "parameters": [ + { + "name": "x-api-key", + "value": "971dcea6c47445f6f7405fa2d14e116b1d81dae6c10330571e8d4220c013b523" + } + ] + }, + "sendBody": true, + "contentType": "multipart-form-data", + "bodyParameters": { + "parameters": [ + { + "parameterType": "formBinaryData", + "name": "file", + "inputDataFieldName": "=file" + }, + { + "name": "messageId", + "value": "={{ $('Set messageId Field1').item.json.messageId }}" + }, + { + "name": "attachment_name", + "value": "={{ $('Split: One Item Per Attachment3').item.json.attachment_name }}" + } + ] + }, + "options": {} + }, + "type": "n8n-nodes-base.httpRequest", + "typeVersion": 4.2, + "position": [-1568, 192], + "id": "bc668542-9d9c-4096-9750-777b7012a29b", + "name": "OCR: Extract Invoice Data2 [LOCAL]", + "alwaysOutputData": false, + "retryOnFail": true, + "waitBetweenTries": 5000, + "maxTries": 3, + "onError": "continueRegularOutput" + }, + { + "parameters": { + "conditions": { + "conditions": [ + { + "id": "valid-ocr", + "leftValue": "={{\n !($json.error && $json.error.includes(\"429\")) &&\n !$json.error &&\n ($json.invoice_number ?? \"\") !== \"\"\n}}", + "rightValue": "", + "operator": { "type": "boolean", "operation": "true", "singleValue": true } + } + ], + "combinator": "and" + }, + "options": {} + }, + "type": "n8n-nodes-base.if", + "typeVersion": 2.2, + "position": [-1344, 192], + "id": "c7004bf2-bb80-4eea-8384-54cbd6baae84", + "name": "OCR Extraction Valid?2" + }, + { + "parameters": { + "jsCode": "function cleanNumber(val) {\n if (val === null || val === undefined) return 0;\n return Number(val.toString().replace(/[^\\d.-]/g, '')) || 0;\n}\n\nreturn items.map(item => {\n const inv = item.json;\n\n return {\n json: {\n invoice_id: inv.invoice_id ?? '',\n invoice_number: inv.invoice_number ?? '',\n invoice_date: inv.invoice_date ?? '',\n due_date: inv.due_date ?? '',\n seller_name: inv.seller_name ?? '',\n PO_number: inv.PO_number ?? '',\n invoice_amount: cleanNumber(inv.invoice_amount),\n currency_code: inv.currency_code ?? 'INR',\n seller_gstin: inv.seller_gstin ?? '',\n customer_name: inv.customer_name ?? '',\n customer_gstin: '27AAATL1944N1ZA',\n dc_date: inv.DC_date ?? '',\n dc_number: inv.DC_number ?? '',\n round_off: cleanNumber(inv.round_off),\n total_gst_rate: cleanNumber(inv.total_gst_rate),\n total_quantity: cleanNumber(inv.total_quantity),\n total_cgst_rate: cleanNumber(inv.total_cgst_rate),\n total_cgst_amount: cleanNumber(inv.total_cgst_amount),\n total_sgst_rate: cleanNumber(inv.total_sgst_rate),\n total_sgst_amount: cleanNumber(inv.total_sgst_amount),\n total_igst_rate: cleanNumber(inv.total_igst_rate),\n total_igst_amount: cleanNumber(inv.total_igst_amount),\n total_gst_amount: cleanNumber(inv.total_gst_amount),\n items: (inv.items ?? []).map(i => ({\n item_code: i.item_code ?? '',\n Batch: i.Batch ?? '',\n quantity: cleanNumber(i.quantity),\n free_item_yn: cleanNumber(i.free_item_yn),\n unit_price: cleanNumber(i.unit_price),\n total_price: cleanNumber(i.total_price),\n Discount: cleanNumber(i.Discount),\n MRP: cleanNumber(i.MRP),\n description: i.description ?? '',\n Pack: i.Pack ?? '',\n hsn_sac: i.hsn_sac ?? '',\n expiry_date: i.expiry_date ?? '',\n cgst_rate: cleanNumber(i.cgst_rate),\n cgst_amount: cleanNumber(i.cgst_amount),\n sgst_rate: cleanNumber(i.sgst_rate),\n sgst_amount: cleanNumber(i.sgst_amount),\n igst_rate: cleanNumber(i.igst_rate),\n igst_amount: cleanNumber(i.igst_amount),\n GST_AMT: cleanNumber(i.GST_AMT),\n taxable_value: cleanNumber(i.taxable_value),\n 'Gst%': cleanNumber(i['Gst%']),\n Value: cleanNumber(i.Value),\n reference_number: i.reference_number ?? ''\n }))\n }\n };\n});" + }, + "type": "n8n-nodes-base.code", + "typeVersion": 2, + "position": [-1120, 96], + "id": "6f82a7b4-9dbf-4e9c-a6c4-6a4a52efc6e3", + "name": "Normalize Invoice Fields2" + }, + { + "parameters": { + "method": "POST", + "url": "=http://localhost:{{ $env.LOCAL_APP_PORT || 8080 }}/dmhApiRef/grn/createGRN.php", + "sendHeaders": true, + "headerParameters": { + "parameters": [ + { + "name": "x-api-key", + "value": "nirajAi26@DMH" + }, + { + "name": "Content-Type", + "value": "application/json" + } + ] + }, + "sendBody": true, + "specifyBody": "json", + "jsonBody": "={{$json}}", + "options": {} + }, + "type": "n8n-nodes-base.httpRequest", + "typeVersion": 4.2, + "position": [-896, 96], + "id": "4372d6a1-b4d9-4a1f-b522-c3399044ce33", + "name": "GRN: Create Record in Hospital2 [LOCAL]", + "retryOnFail": false, + "onError": "continueRegularOutput" + }, + { + "parameters": { + "jsCode": "// Flatten GRN result + build complete_error identical to production\nfunction safeText(value) {\n if (value === null || value === undefined) return '';\n if (typeof value === 'string') return value.trim();\n if (typeof value === 'number' || typeof value === 'boolean') return String(value);\n if (Array.isArray(value)) return value.map(v => safeText(v)).filter(Boolean).join(' | ');\n if (typeof value === 'object') {\n for (const key of ['message','error','detail','reason','description','statusText']) {\n if (value[key] !== undefined && value[key] !== null) { const r = safeText(value[key]); if (r) return r; }\n }\n try { return JSON.stringify(value); } catch(e) { return ''; }\n }\n return '';\n}\n\nconst output = [];\n\nitems.forEach(item => {\n const now = new Date();\n const date = now.toLocaleDateString('en-CA', { timeZone: 'Asia/Kolkata' });\n const time = now.toLocaleTimeString('en-IN', { timeZone: 'Asia/Kolkata', hour12: true });\n\n let messageId = '';\n try { messageId = $('Set messageId Field1').item.json.messageId || ''; } catch(e) {}\n\n let attachment_name = '';\n try { attachment_name = $('Split: One Item Per Attachment3').item.json.attachment_name || ''; } catch(e) {}\n\n const grn = item.json || {};\n const http_status_code = typeof grn.status === 'number' ? grn.status : parseInt(grn.status, 10) || 0;\n const grnDataRaw = Array.isArray(grn.data) && grn.data.length > 0 ? grn.data[0] : null;\n const grnData = (grnDataRaw && typeof grnDataRaw === 'object' && !Array.isArray(grnDataRaw)) ? grnDataRaw : (grn.data && typeof grn.data === 'object' && !Array.isArray(grn.data) ? grn.data : {});\n\n let grnMsg = safeText(grnDataRaw) || safeText(grn.data) || safeText(grn.message) || safeText(grn.error) || 'Unknown API error';\n\n const httpOk = http_status_code === 200;\n const grnOk = grnData.status === 0 || grnData.status === '0';\n const grn_success = httpOk && grnOk;\n\n let inv = {};\n try { inv = $('Normalize Invoice Fields2').item.json || {}; } catch(e) {}\n\n const invoiceItems = Array.isArray(inv.items) ? inv.items : [];\n const hasFreeGoods = invoiceItems.some(i => String(i && i.free_item_yn) === '1');\n\n let complete_error = '';\n if (grn_success) {\n const parts = [];\n if (grnData.grn_no) parts.push('GRN No: ' + grnData.grn_no);\n if (grnData.grn_master_id) parts.push('GRN Master ID: ' + grnData.grn_master_id);\n if (grnData.items_inserted !== undefined) parts.push('Items Inserted: ' + grnData.items_inserted);\n if (grnData.vendor_id) parts.push('Vendor ID: ' + grnData.vendor_id);\n if (grnData.invoice_no) parts.push('Invoice No (DMH): ' + grnData.invoice_no);\n complete_error = parts.join(' | ');\n } else {\n complete_error = 'Error Type : GRN Creation Failed\\nError From : [LOCAL DMH]\\n─────────────────────────────────\\nRaw API error : ' + (grnMsg || 'Unknown error');\n }\n\n output.push({\n json: {\n date,\n time,\n invoice_id: inv.invoice_id || '',\n invoice_number: inv.invoice_number || '',\n invoice_date: inv.invoice_date || '',\n seller_name: inv.seller_name || '',\n seller_gstin: inv.seller_gstin || '',\n customer_name: inv.customer_name || '',\n invoice_amount: inv.invoice_amount ?? 0,\n attachment_name,\n status: grn_success ? '✅ SUCCESS' : '❌ FAILED',\n grn_success,\n http_status_code,\n grn_message: grnMsg || 'Unknown API error',\n complete_error,\n free_goods: hasFreeGoods ? 'Yes' : 'No',\n messageId,\n grn_no: grnData.grn_no || '',\n grn_master_id: grnData.grn_master_id || '',\n items_inserted: grnData.items_inserted || 0\n }\n });\n});\n\nreturn output;" + }, + "type": "n8n-nodes-base.code", + "typeVersion": 2, + "position": [-672, 96], + "id": "864137a6-b9cb-4e21-bcc2-1f2543d04fda", + "name": "Flatten Data for Log2", + "onError": "continueRegularOutput" + }, + { + "parameters": { + "conditions": { + "conditions": [ + { + "id": "grn-ok", + "leftValue": "={{ $('Flatten Data for Log2').item.json.grn_success }}", + "rightValue": "", + "operator": { "type": "boolean", "operation": "true", "singleValue": true } + } + ], + "combinator": "and" + }, + "options": {} + }, + "type": "n8n-nodes-base.if", + "typeVersion": 2.2, + "position": [-224, 96], + "id": "477bad63-5dad-4f11-bfdb-8f21c9cb801e", + "name": "GRN Created Successfully?2" + }, + { + "parameters": { + "operation": "append", + "documentId": { + "__rl": true, + "value": "1cwLXlwmCPC7zUVOIQFWwRED4uqF3WZHVagGbBtKyVgQ", + "mode": "id" + }, + "sheetName": { + "__rl": true, + "value": 1691973413, + "mode": "list", + "cachedResultName": "Daily Logs" + }, + "columns": { + "mappingMode": "defineBelow", + "value": { + "Date": "={{ $json.date }}", + "Time": "={{ $json.time }}", + "Attachment Name": "={{ $json.attachment_name }}", + "Invoice ID": "={{ $json.invoice_id }}", + "Customer Name": "={{ $json.customer_name }}", + "Invoice Amount (₹)": "={{ $json.invoice_amount }}", + "Seller Name": "={{ $json.seller_name }}", + "Status": "={{ $json.status }}", + "GRN Message ": "={{ $json.grn_message }}", + "Seller GSTIN": "={{ $json.seller_gstin }}", + "Free Goods": "={{ $json.free_goods }}", + "Complete Error / Null Values": "={{ $json.complete_error }}" + }, + "matchingColumns": [], + "schema": [ + { "id": "Sr No.", "displayName": "Sr No.", "type": "string", "canBeUsedToMatch": true }, + { "id": "Date", "displayName": "Date", "type": "string", "canBeUsedToMatch": true }, + { "id": "Time", "displayName": "Time", "type": "string", "canBeUsedToMatch": true }, + { "id": "Attachment Name", "displayName": "Attachment Name", "type": "string", "canBeUsedToMatch": true }, + { "id": "Customer Name", "displayName": "Customer Name", "type": "string", "canBeUsedToMatch": true }, + { "id": "Invoice Amount (₹)", "displayName": "Invoice Amount (₹)", "type": "string", "canBeUsedToMatch": true }, + { "id": "Invoice ID", "displayName": "Invoice ID", "type": "string", "canBeUsedToMatch": true }, + { "id": "Seller Name", "displayName": "Seller Name", "type": "string", "canBeUsedToMatch": true }, + { "id": "Status", "displayName": "Status", "type": "string", "canBeUsedToMatch": true }, + { "id": "GRN Message ", "displayName": "GRN Message ", "type": "string", "canBeUsedToMatch": true }, + { "id": "Seller GSTIN", "displayName": "Seller GSTIN", "type": "string", "canBeUsedToMatch": true }, + { "id": "Free Goods", "displayName": "Free Goods", "type": "string", "canBeUsedToMatch": true }, + { "id": "Complete Error / Null Values", "displayName": "Complete Error / Null Values", "type": "string", "canBeUsedToMatch": true } + ], + "attemptToConvertTypes": false, + "convertFieldsToString": false + }, + "options": {} + }, + "type": "n8n-nodes-base.googleSheets", + "typeVersion": 4.7, + "position": [-448, 96], + "id": "54fc0189-5a1a-402b-93a0-9f575f730f32", + "name": "Log to Google Sheets (Daily Logs)2", + "credentials": { + "googleSheetsOAuth2Api": { + "id": "OGnPiaQp3eu9tWvW", + "name": "Google Sheets account" + } + } + }, + { + "parameters": { + "operation": "move", + "messageId": "={{ $('Flatten Data for Log2').item.json.messageId }}", + "folderId": { + "__rl": true, + "value": "AQMkADAwATM0MDAAMi1hYzgzLTQxMQAyLTAwAi0wMAoALgAAA3R9Z7-WZCBHqvG_09flPEoBAJRkAPlTP4RNsddkpsHybkoAAAJocwAAAA==", + "mode": "list", + "cachedResultName": "Invoice_Sucess" + } + }, + "type": "n8n-nodes-base.microsoftOutlook", + "typeVersion": 2, + "position": [0, 0], + "id": "bf5b1548-e75b-40d4-9b2d-a534708db65e", + "name": "Label: Add Invoice_Done2", + "credentials": { + "microsoftOutlookOAuth2Api": { + "id": "neYqnH7A2WPe5lTs", + "name": "Microsoft Outlook account" + } + }, + "onError": "continueRegularOutput" + }, + { + "parameters": { + "operation": "move", + "messageId": "={{ $('Flatten Data for Log2').item.json.messageId }}", + "folderId": { + "__rl": true, + "value": "AQMkADAwATM0MDAAMi1hYzgzLTQxMQAyLTAwAi0wMAoALgAAA3R9Z7-WZCBHqvG_09flPEoBAJRkAPlTP4RNsddkpsHybkoAAAJodAAAAA==", + "mode": "list", + "cachedResultName": "Invoice_Failed" + } + }, + "type": "n8n-nodes-base.microsoftOutlook", + "typeVersion": 2, + "position": [0, 288], + "id": "6ee14313-3f3a-447e-a7d5-cf15a29f972b", + "name": "Failed To add2", + "credentials": { + "microsoftOutlookOAuth2Api": { + "id": "neYqnH7A2WPe5lTs", + "name": "Microsoft Outlook account" + } + }, + "onError": "continueRegularOutput" + }, + { + "parameters": { + "operation": "move", + "messageId": "={{ $('Set messageId Field1').item.json.messageId }}", + "folderId": { + "__rl": true, + "value": "AQMkADAwATM0MDAAMi1hYzgzLTQxMQAyLTAwAi0wMAoALgAAA3R9Z7-WZCBHqvG_09flPEoBAJRkAPlTP4RNsddkpsHybkoAAAJodAAAAA==", + "mode": "list", + "cachedResultName": "Invoice_Failed" + } + }, + "type": "n8n-nodes-base.microsoftOutlook", + "typeVersion": 2, + "position": [-672, 384], + "id": "651c1889-e980-4870-a309-35e23ea51aed", + "name": "Label: Add Invoice_failed2", + "credentials": { + "microsoftOutlookOAuth2Api": { + "id": "neYqnH7A2WPe5lTs", + "name": "Microsoft Outlook account" + } + }, + "onError": "continueRegularOutput" + }, + { + "parameters": { + "operation": "move", + "messageId": "={{ $json.messageId }}", + "folderId": { + "__rl": true, + "value": "AQMkADAwATM0MDAAMi1hYzgzLTQxMQAyLTAwAi0wMAoALgAAA3R9Z7-WZCBHqvG_09flPEoBAJRkAPlTP4RNsddkpsHybkoAAAJocgAAAA==", + "mode": "list", + "cachedResultName": "Not_invoice" + } + }, + "type": "n8n-nodes-base.microsoftOutlook", + "typeVersion": 2, + "position": [-2016, 576], + "id": "0c59ac0e-ca75-45bd-b731-3aae0faed96f", + "name": "Label: Add Not_Invoice2", + "credentials": { + "microsoftOutlookOAuth2Api": { + "id": "neYqnH7A2WPe5lTs", + "name": "Microsoft Outlook account" + } + }, + "onError": "continueRegularOutput" + }, + { + "parameters": { + "jsCode": "// Flatten OCR error — same format as production\nconst output = [];\nitems.forEach(item => {\n const now = new Date();\n const date = now.toLocaleDateString('en-CA', { timeZone: 'Asia/Kolkata' });\n const time = now.toLocaleTimeString('en-IN', { timeZone: 'Asia/Kolkata', hour12: true });\n let messageId = '';\n try { messageId = $('Set messageId Field1').item.json.messageId || ''; } catch(e) {}\n let attachment_name = '';\n try { attachment_name = $('Split: One Item Per Attachment3').item.json.attachment_name || ''; } catch(e) {}\n const data = item.json;\n const rawError = data.error ? (typeof data.error === 'string' ? data.error : (data.error.message || JSON.stringify(data.error))) : '(no error message)';\n output.push({\n json: {\n date, time,\n invoice_id: '', invoice_number: '', invoice_date: '',\n seller_name: '', seller_gstin: '', customer_name: '',\n invoice_amount: 0, attachment_name,\n status: '❌ FAILED',\n grn_message: 'OCR Extraction Failed — Invoice not processed',\n complete_error: 'Error Type : OCR Extraction Failed\\nError From : [AI INDIA]\\n─────────────────────────────────\\nRaw API error : ' + rawError,\n free_goods: 'No',\n messageId\n }\n });\n});\nreturn output;" + }, + "type": "n8n-nodes-base.code", + "typeVersion": 2, + "position": [-1120, 384], + "id": "6402173a-44c3-4233-b394-0581d4f47f89", + "name": "Flatten OCR Error for Log", + "onError": "continueRegularOutput" + }, + { + "parameters": { + "operation": "append", + "documentId": { + "__rl": true, + "value": "1cwLXlwmCPC7zUVOIQFWwRED4uqF3WZHVagGbBtKyVgQ", + "mode": "id" + }, + "sheetName": { + "__rl": true, + "value": 1691973413, + "mode": "list", + "cachedResultName": "Daily Logs" + }, + "columns": { + "mappingMode": "defineBelow", + "value": { + "Date": "={{ $json.date }}", + "Time": "={{ $json.time }}", + "Status": "={{ $json.status }}", + "Complete Error / Null Values": "={{ $json.complete_error }}", + "Attachment Name": "={{ $('Wait 7s Before OCR2').item.json.attachment_name }}" + }, + "matchingColumns": [], + "schema": [ + { "id": "Date", "displayName": "Date", "type": "string" }, + { "id": "Time", "displayName": "Time", "type": "string" }, + { "id": "Attachment Name", "displayName": "Attachment Name", "type": "string" }, + { "id": "Status", "displayName": "Status", "type": "string" }, + { "id": "Complete Error / Null Values","displayName": "Complete Error / Null Values","type": "string" } + ] + }, + "options": {} + }, + "type": "n8n-nodes-base.googleSheets", + "typeVersion": 4.7, + "position": [-896, 384], + "id": "b12ab90f-240b-4845-ac94-dada14ce001f", + "name": "Append row in sheet5", + "credentials": { + "googleSheetsOAuth2Api": { + "id": "OGnPiaQp3eu9tWvW", + "name": "Google Sheets account" + } + }, + "onError": "continueRegularOutput" + }, + { + "parameters": { + "jsCode": "// Flatten AI classification error\nconst output = [];\nitems.forEach(item => {\n const now = new Date();\n const date = now.toLocaleDateString('en-CA', { timeZone: 'Asia/Kolkata' });\n const time = now.toLocaleTimeString('en-IN', { timeZone: 'Asia/Kolkata', hour12: true });\n let messageId = '';\n try { messageId = $('Set messageId Field1').item.json.messageId || ''; } catch(e) {}\n let attachment_name = '';\n try { attachment_name = $('Split: One Item Per Attachment3').item.json.attachment_name || ''; } catch(e) {}\n const errorDetail = item.json.error_detail || item.json.error || 'AI_CLASSIFICATION_FAILED';\n output.push({\n json: {\n date, time,\n invoice_id: '', invoice_number: '', invoice_date: '',\n seller_name: '', seller_gstin: '', customer_name: '',\n invoice_amount: 0, attachment_name,\n status: '❌ FAILED',\n grn_message: 'AI Classification Failed — Invoice not processed',\n complete_error: 'Error Type : AI Classification Error\\nError From : [AI INDIA]\\n─────────────────────────────────\\nRaw API error : ' + (errorDetail || '(no error detail)'),\n messageId\n }\n });\n});\nreturn output;" + }, + "type": "n8n-nodes-base.code", + "typeVersion": 2, + "position": [-2016, 384], + "id": "88f8d70f-f8b0-4462-bf46-478f26a507df", + "name": "Code in JavaScript6", + "onError": "continueRegularOutput" + }, + { + "parameters": { + "operation": "append", + "documentId": { + "__rl": true, + "value": "1cwLXlwmCPC7zUVOIQFWwRED4uqF3WZHVagGbBtKyVgQ", + "mode": "id" + }, + "sheetName": { + "__rl": true, + "value": 1691973413, + "mode": "list", + "cachedResultName": "Daily Logs" + }, + "columns": { + "mappingMode": "defineBelow", + "value": { + "Date": "={{ $json.date }}", + "Time": "={{ $json.time }}", + "Attachment Name": "={{ $json.attachment_name }}", + "Status": "={{ $json.status }}", + "GRN Message ": "={{ $json.grn_message }}", + "Complete Error / Null Values": "={{ $json.complete_error }}" + }, + "matchingColumns": [], + "schema": [ + { "id": "Date", "displayName": "Date", "type": "string" }, + { "id": "Time", "displayName": "Time", "type": "string" }, + { "id": "Attachment Name", "displayName": "Attachment Name", "type": "string" }, + { "id": "Status", "displayName": "Status", "type": "string" }, + { "id": "GRN Message ", "displayName": "GRN Message ", "type": "string" }, + { "id": "Complete Error / Null Values","displayName": "Complete Error / Null Values","type": "string" } + ] + }, + "options": {} + }, + "type": "n8n-nodes-base.googleSheets", + "typeVersion": 4.7, + "position": [-1792, 384], + "id": "1550194a-e54a-4b53-8b77-aa2f3a946d74", + "name": "Append row in sheet1", + "credentials": { + "googleSheetsOAuth2Api": { + "id": "OGnPiaQp3eu9tWvW", + "name": "Google Sheets account" + } + } + }, + { + "parameters": { + "model": "openai/gpt-oss-120b", + "options": {} + }, + "type": "@n8n/n8n-nodes-langchain.lmChatGroq", + "typeVersion": 1, + "position": [-3360, 1184], + "id": "69adb603-b839-49a8-a652-79c28fc2dcdb", + "name": "Groq Chat Model1", + "credentials": { + "groqApi": { + "id": "5STjMY6aZDMipq2f", + "name": "Groq account" + } + } + }, + { + "parameters": { + "options": { + "temperature": 0.4 + } + }, + "type": "@n8n/n8n-nodes-langchain.lmChatGoogleGemini", + "typeVersion": 1, + "position": [-3488, 1184], + "id": "5b645a7b-acc2-46f6-88e5-82d8d79a8986", + "name": "Google Gemini Chat Model", + "credentials": { + "googlePalmApi": { + "id": "8wBnH32SbKmjkfYp", + "name": "Google Gemini(PaLM) Api account" + } + } + } + ], + "connections": { + "Watch New_Invoice Label1": { + "main": [[{ "node": "Fetch Emails from New_Invoice (max 3)1", "type": "main", "index": 0 }]] + }, + "Fetch Emails from New_Invoice (max 3)1": { + "main": [[{ "node": "Loop: Each Email2", "type": "main", "index": 0 }]] + }, + "Loop: Each Email2": { + "main": [ + [{ "node": "Label: Add Processing2", "type": "main", "index": 0 }], + [{ "node": "End: No More Emails1", "type": "main", "index": 0 }] + ] + }, + "End: No More Emails1": { + "main": [[{ "node": "Loop: Each Email2", "type": "main", "index": 0 }]] + }, + "Label: Add Processing2": { + "main": [[{ "node": "Label: Remove New_Invoice1", "type": "main", "index": 0 }]] + }, + "Label: Remove New_Invoice1": { + "main": [[{ "node": "Fetch Full Email + Attachments2", "type": "main", "index": 0 }]] + }, + "Fetch Full Email + Attachments2": { + "main": [[ + { "node": "Set messageId Field1", "type": "main", "index": 0 }, + { "node": "AI: Classify Invoice1", "type": "main", "index": 0 } + ]] + }, + "Set messageId Field1": { + "main": [[{ "node": "Merge: Email + AI Classification1", "type": "main", "index": 0 }]] + }, + "AI: Classify Invoice1": { + "main": [[{ "node": "Merge: Email + AI Classification1", "type": "main", "index": 1 }]] + }, + "Merge: Email + AI Classification1": { + "main": [[{ "node": "Split: One Item Per Attachment3", "type": "main", "index": 0 }]] + }, + "Split: One Item Per Attachment3": { + "main": [[{ "node": "Loop: Each Attachment2", "type": "main", "index": 0 }]] + }, + "Loop: Each Attachment2": { + "main": [ + [], + [{ "node": "Parse AI Output2", "type": "main", "index": 0 }] + ] + }, + "Parse AI Output2": { + "main": [[{ "node": "Switch2", "type": "main", "index": 0 }]] + }, + "Switch2": { + "main": [ + [{ "node": "Wait 7s Before OCR2", "type": "main", "index": 0 }], + [{ "node": "Code in JavaScript6", "type": "main", "index": 0 }], + [{ "node": "Label: Add Not_Invoice2","type": "main", "index": 0 }], + [{ "node": "Code in JavaScript6", "type": "main", "index": 0 }] + ] + }, + "Wait 7s Before OCR2": { + "main": [[{ "node": "OCR: Extract Invoice Data2 [LOCAL]", "type": "main", "index": 0 }]] + }, + "OCR: Extract Invoice Data2 [LOCAL]": { + "main": [[{ "node": "OCR Extraction Valid?2", "type": "main", "index": 0 }]] + }, + "OCR Extraction Valid?2": { + "main": [ + [{ "node": "Normalize Invoice Fields2", "type": "main", "index": 0 }], + [{ "node": "Flatten OCR Error for Log", "type": "main", "index": 0 }] + ] + }, + "Normalize Invoice Fields2": { + "main": [[{ "node": "GRN: Create Record in Hospital2 [LOCAL]", "type": "main", "index": 0 }]] + }, + "GRN: Create Record in Hospital2 [LOCAL]": { + "main": [[{ "node": "Flatten Data for Log2", "type": "main", "index": 0 }]] + }, + "Flatten Data for Log2": { + "main": [[{ "node": "Log to Google Sheets (Daily Logs)2", "type": "main", "index": 0 }]] + }, + "Log to Google Sheets (Daily Logs)2": { + "main": [[{ "node": "GRN Created Successfully?2", "type": "main", "index": 0 }]] + }, + "GRN Created Successfully?2": { + "main": [ + [{ "node": "Label: Add Invoice_Done2", "type": "main", "index": 0 }], + [{ "node": "Failed To add2", "type": "main", "index": 0 }] + ] + }, + "Label: Add Invoice_Done2": { + "main": [[{ "node": "Loop: Each Attachment2", "type": "main", "index": 0 }]] + }, + "Failed To add2": { + "main": [[{ "node": "Loop: Each Attachment2", "type": "main", "index": 0 }]] + }, + "Flatten OCR Error for Log": { + "main": [[{ "node": "Append row in sheet5", "type": "main", "index": 0 }]] + }, + "Append row in sheet5": { + "main": [[{ "node": "Label: Add Invoice_failed2", "type": "main", "index": 0 }]] + }, + "Label: Add Invoice_failed2": { + "main": [[{ "node": "Loop: Each Attachment2", "type": "main", "index": 0 }]] + }, + "Code in JavaScript6": { + "main": [[{ "node": "Append row in sheet1", "type": "main", "index": 0 }]] + }, + "Append row in sheet1": { + "main": [[{ "node": "Loop: Each Attachment2", "type": "main", "index": 0 }]] + }, + "Label: Add Not_Invoice2": { + "main": [[{ "node": "Loop: Each Attachment2", "type": "main", "index": 0 }]] + }, + "Groq Chat Model1": { + "ai_languageModel": [[{ "node": "AI: Classify Invoice1", "type": "ai_languageModel", "index": 1 }]] + }, + "Google Gemini Chat Model": { + "ai_languageModel": [[{ "node": "AI: Classify Invoice1", "type": "ai_languageModel", "index": 0 }]] + } + }, + "active": false, + "settings": { + "executionOrder": "v1", + "binaryMode": "separate", + "saveExecutionProgress": true, + "callerPolicy": "workflowsFromSameOwner" + }, + "meta": { + "templateCredsSetupCompleted": true, + "instanceId": "09595d0d13dc9d2efef972a58e0990aff52b4fcad58caade8fb67afbc50891ba", + "_local_test_note": "LOCAL TEST VERSION — OCR and GRN endpoints point to localhost:8080. Switch to production by replacing localhost URLs with aiinfinite.in and mapp.dmhospital.org." + }, + "tags": [ + { "id": "local-test", "name": "local-test" }, + { "id": "production", "name": "production" } + ] +} diff --git a/po_approval_workflow.json b/po_approval_workflow.json new file mode 100644 index 0000000..fcd178e --- /dev/null +++ b/po_approval_workflow.json @@ -0,0 +1,455 @@ +{ + "name": "DMH Pharmacy - PO & Item Code Approval Webhook Handler", + "nodes": [ + { + "id": "149bc235-d2ca-4b26-b4d7-0e8c76f7c655", + "name": "Webhook: Pharmacy Approval Trigger", + "type": "n8n-nodes-base.webhook", + "typeVersion": 2, + "position": [ + -400, + 250 + ], + "webhookId": "b33f38b7-ab72-42db-9b58-b405dffc7db5", + "parameters": { + "httpMethod": "POST", + "path": "pharmacy-po-approved", + "responseMode": "onReceived", + "responseData": "allEntries", + "options": {} + } + }, + { + "id": "f72c0eee-23fe-4c64-becb-41f8199d0441", + "name": "Switch: Event & Condition Router", + "type": "n8n-nodes-base.switch", + "typeVersion": 3, + "position": [ + -100, + 250 + ], + "parameters": { + "mode": "rules", + "rules": { + "rules": [ + { + "conditions": { + "options": { + "caseSensitive": false, + "leftValue": "", + "typeValidation": "strict" + }, + "conditions": [ + { + "id": "57436143-9fcb-47c5-a115-d4150bae2307", + "leftValue": "={{ $json.body.condition_type }}", + "rightValue": "condition_4", + "operator": { + "type": "string", + "operation": "equals" + } + } + ] + }, + "renameOutput": true, + "outputKey": "Condition 4: PO Approved -> Store GRN" + }, + { + "conditions": { + "options": { + "caseSensitive": false, + "leftValue": "", + "typeValidation": "strict" + }, + "conditions": [ + { + "id": "0f0a5893-0078-4839-b65d-3e49e326bc1b", + "leftValue": "={{ $json.body.condition_type }}", + "rightValue": "condition_5", + "operator": { + "type": "string", + "operation": "equals" + } + }, + { + "id": "328f05c5-5c79-41bd-8f66-2539c4d95aba", + "leftValue": "={{ $json.body.event }}", + "rightValue": "po_number_approved", + "operator": { + "type": "string", + "operation": "equals" + } + } + ] + }, + "renameOutput": true, + "outputKey": "Condition 5: PO Approved -> Fetch PO Details API" + }, + { + "conditions": { + "options": { + "caseSensitive": false, + "leftValue": "", + "typeValidation": "strict" + }, + "conditions": [ + { + "id": "f57aa3cf-0720-4ba0-9b34-40457ed5b844", + "leftValue": "={{ $json.body.event }}", + "rightValue": "item_code_approved", + "operator": { + "type": "string", + "operation": "equals" + } + } + ] + }, + "renameOutput": true, + "outputKey": "Item Code Approved (C3/C5) -> Store GRN" + } + ] + }, + "options": {} + } + }, + { + "id": "4d3cf1d7-eae6-4744-ba22-c0d48586e5e9", + "name": "Format GRN Payload (C4)", + "type": "n8n-nodes-base.code", + "typeVersion": 2, + "position": [ + 250, + 100 + ], + "parameters": { + "mode": "runOnceForAllItems", + "jsCode": "// Formats final invoice data for DMH createGRN.php\nconst body = items[0].json.body || items[0].json;\nconst inv = body.invoice_data || body;\nif (body.approved_po_number) {\n inv.PO_number = body.approved_po_number;\n}\ninv.customer_gstin = \"27AAATL1944N1ZA\";\nreturn [{ json: inv }];" + } + }, + { + "id": "4686a3e3-e090-4bcf-9736-114e70ed783a", + "name": "GRN: Store in DMH Database (C4)", + "type": "n8n-nodes-base.httpRequest", + "typeVersion": 4.2, + "position": [ + 550, + 100 + ], + "parameters": { + "method": "POST", + "url": "https://mapp.dmhospital.org/dmhApiRef/grn/createGRN.php", + "sendHeaders": true, + "headerParameters": { + "parameters": [ + { + "name": "x-api-key", + "value": "nirajAi26@DMH" + }, + { + "name": "Content-Type", + "value": "application/json" + } + ] + }, + "sendBody": true, + "specifyBody": "json", + "jsonBody": "={{ $json }}", + "options": {} + } + }, + { + "id": "f83c3773-40cf-47f0-b772-b1c931d16449", + "name": "HTTP: Fetch DMH PO Details (C5)", + "type": "n8n-nodes-base.httpRequest", + "typeVersion": 4.2, + "position": [ + 250, + 280 + ], + "parameters": { + "method": "GET", + "url": "={{ $env.DMH_PO_DETAILS_API_URL || 'https://mapp.dmhospital.org/dmhApiRef/po/getPoDetails.php' }}", + "sendHeaders": true, + "headerParameters": { + "parameters": [ + { + "name": "x-api-key", + "value": "={{ $env.DMH_PO_DETAILS_API_KEY || 'nirajAi26@DMH' }}" + } + ] + }, + "sendQuery": true, + "queryParameters": { + "parameters": [ + { + "name": "po_number", + "value": "={{ $('Webhook: Pharmacy Approval Trigger').first().json.body.approved_po_number }}" + } + ] + }, + "options": { + "response": { + "response": { + "responseFormat": "json" + } + }, + "timeout": 15000 + } + } + }, + { + "id": "97ff7d8a-7c88-4d61-8b55-76fec27bb844", + "name": "Code: Merge PO Item Codes (C5)", + "type": "n8n-nodes-base.code", + "typeVersion": 2, + "position": [ + 550, + 280 + ], + "parameters": { + "mode": "runOnceForAllItems", + "jsCode": "// Condition 5: PO approved by pharmacy user -> fetched PO Details\nconst webhookBody = $('Webhook: Pharmacy Approval Trigger').first().json.body || {};\nconst invoiceData = webhookBody.invoice_data || {};\ninvoiceData.PO_number = webhookBody.approved_po_number || invoiceData.PO_number;\n\nconst poResponse = items[0].json;\nconst poItems = poResponse.items || poResponse.data?.items || [];\nconst originalItems = invoiceData.items || [];\n\nconst codeMap = {};\npoItems.forEach(pi => {\n const key = (pi.description || pi.item_name || pi.name || '').toLowerCase().trim();\n if (key && pi.item_code) codeMap[key] = pi.item_code;\n});\n\nlet anyFound = false;\nconst mergedItems = originalItems.map(item => {\n const key = (item.description || '').toLowerCase().trim();\n const matchedCode = codeMap[key] || item.item_code || '';\n if (matchedCode) anyFound = true;\n return {\n ...item,\n item_code: matchedCode\n };\n});\n\ninvoiceData.items = mergedItems;\n\nreturn [{\n json: {\n ...invoiceData,\n _item_codes_found: anyFound,\n _po_invoice_id: webhookBody.invoice_id,\n _po_number: webhookBody.approved_po_number,\n _invoice_number: webhookBody.invoice_number\n }\n}];" + } + }, + { + "id": "9deb36c8-5da7-46d0-af64-b9044b47e38a", + "name": "IF: Item Codes Found in API?", + "type": "n8n-nodes-base.if", + "typeVersion": 2, + "position": [ + 850, + 280 + ], + "parameters": { + "conditions": { + "options": { + "caseSensitive": true, + "leftValue": "", + "typeValidation": "strict" + }, + "conditions": [ + { + "id": "61365898-bb15-41a5-b5ee-3ff487d62923", + "leftValue": "={{ $json._item_codes_found }}", + "rightValue": true, + "operator": { + "type": "boolean", + "operation": "true" + } + } + ] + } + } + }, + { + "id": "7eedfde4-6c28-4a01-b193-b4880c630bda", + "name": "GRN: Store in DMH Database (C5 Auto)", + "type": "n8n-nodes-base.httpRequest", + "typeVersion": 4.2, + "position": [ + 1150, + 200 + ], + "parameters": { + "method": "POST", + "url": "https://mapp.dmhospital.org/dmhApiRef/grn/createGRN.php", + "sendHeaders": true, + "headerParameters": { + "parameters": [ + { + "name": "x-api-key", + "value": "nirajAi26@DMH" + }, + { + "name": "Content-Type", + "value": "application/json" + } + ] + }, + "sendBody": true, + "specifyBody": "json", + "jsonBody": "={{ $json }}", + "options": {} + } + }, + { + "id": "ae0376f8-a656-4cb1-9093-4324362df7d8", + "name": "HTTP: Escalate to Manual Item Code Queue", + "type": "n8n-nodes-base.httpRequest", + "typeVersion": 4.2, + "position": [ + 1150, + 380 + ], + "parameters": { + "method": "POST", + "url": "={{ $env.PHARMACY_DASHBOARD_URL || 'http://localhost:5000' }}/api/po-approval/submit", + "sendHeaders": true, + "headerParameters": { + "parameters": [ + { + "name": "Content-Type", + "value": "application/json" + }, + { + "name": "X-API-Key", + "value": "={{ $env.N8N_WEBHOOK_SECRET }}" + } + ] + }, + "sendBody": true, + "specifyBody": "json", + "jsonBody": "={{ JSON.stringify({ invoice_number: $json._invoice_number, po_number_original: $json._po_number, condition_type: 'condition_5', approval_status: 'pending_item_code', items: $json.items, full_invoice: $json }) }}", + "options": {} + } + }, + { + "id": "6fc4508d-03ef-49ba-9bc0-dfec5de62e9a", + "name": "Format GRN Payload (Item Approved)", + "type": "n8n-nodes-base.code", + "typeVersion": 2, + "position": [ + 250, + 480 + ], + "parameters": { + "mode": "runOnceForAllItems", + "jsCode": "// Formats final invoice data for DMH createGRN.php\nconst body = items[0].json.body || items[0].json;\nconst inv = body.invoice_data || body;\nif (body.approved_po_number) {\n inv.PO_number = body.approved_po_number;\n}\ninv.customer_gstin = \"27AAATL1944N1ZA\";\nreturn [{ json: inv }];" + } + }, + { + "id": "9fbddbc6-08ce-4cbe-b560-1987e4c1ddf6", + "name": "GRN: Store in DMH Database (Item Approved)", + "type": "n8n-nodes-base.httpRequest", + "typeVersion": 4.2, + "position": [ + 550, + 480 + ], + "parameters": { + "method": "POST", + "url": "https://mapp.dmhospital.org/dmhApiRef/grn/createGRN.php", + "sendHeaders": true, + "headerParameters": { + "parameters": [ + { + "name": "x-api-key", + "value": "nirajAi26@DMH" + }, + { + "name": "Content-Type", + "value": "application/json" + } + ] + }, + "sendBody": true, + "specifyBody": "json", + "jsonBody": "={{ $json }}", + "options": {} + } + } + ], + "connections": { + "Webhook: Pharmacy Approval Trigger": { + "main": [ + [ + { + "node": "Switch: Event & Condition Router", + "type": "main", + "index": 0 + } + ] + ] + }, + "Switch: Event & Condition Router": { + "main": [ + [ + { + "node": "Format GRN Payload (C4)", + "type": "main", + "index": 0 + } + ], + [ + { + "node": "HTTP: Fetch DMH PO Details (C5)", + "type": "main", + "index": 0 + } + ], + [ + { + "node": "Format GRN Payload (Item Approved)", + "type": "main", + "index": 0 + } + ] + ] + }, + "Format GRN Payload (C4)": { + "main": [ + [ + { + "node": "GRN: Store in DMH Database (C4)", + "type": "main", + "index": 0 + } + ] + ] + }, + "HTTP: Fetch DMH PO Details (C5)": { + "main": [ + [ + { + "node": "Code: Merge PO Item Codes (C5)", + "type": "main", + "index": 0 + } + ] + ] + }, + "Code: Merge PO Item Codes (C5)": { + "main": [ + [ + { + "node": "IF: Item Codes Found in API?", + "type": "main", + "index": 0 + } + ] + ] + }, + "IF: Item Codes Found in API?": { + "main": [ + [ + { + "node": "GRN: Store in DMH Database (C5 Auto)", + "type": "main", + "index": 0 + } + ], + [ + { + "node": "HTTP: Escalate to Manual Item Code Queue", + "type": "main", + "index": 0 + } + ] + ] + }, + "Format GRN Payload (Item Approved)": { + "main": [ + [ + { + "node": "GRN: Store in DMH Database (Item Approved)", + "type": "main", + "index": 0 + } + ] + ] + } + }, + "settings": { + "executionOrder": "v1" + } +} \ No newline at end of file diff --git a/sample_invoice_output.json b/sample_invoice_output.json new file mode 100644 index 0000000..20b594d --- /dev/null +++ b/sample_invoice_output.json @@ -0,0 +1,82 @@ +{ + "invoice_id": "E20261105064", + "invoice_number": "RET/29169", + "invoice_date": "28/10/2026", + "due_date": "26/12/2026", + "customer_name": "DEENANATH MEDICAL STORES", + "customer_gstin": "27AAATL1944N1ZA", + "seller_name": "ROHIT ENTERPRISES", + "seller_gstin": "27ABKPK9282D1ZD", + "currency_code": "INR", + "PO_number": "DMH/PO/phrmcy/2026-27/18147", + "DC_date": null, + "DC_number": null, + "invoice_amount": "27919.00", + "round_off": null, + "total_gst_rate": 5.0, + "total_quantity": 7000, + "total_cgst_rate": 2.5, + "total_cgst_amount": 664.74, + "total_sgst_rate": 2.5, + "total_sgst_amount": 664.74, + "total_igst_rate": null, + "total_igst_amount": 0.0, + "total_gst_amount": 1329.48, + "items": [ + { + "description": "AHPL WATER FOR INJ 10 ML", + "Pack": "1200X1", + "Batch": "2504979", + "quantity": 1000, + "free_item": 0, + "free_item_yn": "0", + "unit_price": 2.07, + "total_price": 2070.0, + "reference_number": null, + "hsn_sac": "30049099", + "item_code": "AL-02-1167", + "expiry_date": "31/12/2030", + "Discount": null, + "Discount_type": null, + "Value": null, + "Gst%": 5.0, + "MRP": 2.59, + "cgst_rate": 2.5, + "cgst_amount": 51.75, + "sgst_rate": 2.5, + "sgst_amount": 51.75, + "igst_rate": null, + "igst_amount": 0.0, + "GST_AMT": 103.5, + "taxable_value": 2070.0 + }, + { + "description": "B.B.OMNIVAN 10ML.DUO 21G.", + "Pack": "UNIT", + "Batch": "26H06M8201", + "quantity": 6000, + "free_item": 0, + "free_item_yn": "0", + "unit_price": 4.17, + "total_price": 25020.0, + "reference_number": null, + "hsn_sac": "90183100", + "item_code": "SR-03-0076", + "expiry_date": "31/07/2031", + "Discount": 2.0, + "Discount_type": "percent", + "Value": null, + "Gst%": 5.0, + "MRP": 29.49, + "cgst_rate": 2.5, + "cgst_amount": 612.99, + "sgst_rate": 2.5, + "sgst_amount": 612.99, + "igst_rate": null, + "igst_amount": 0.0, + "GST_AMT": 1225.98, + "taxable_value": 24519.6 + } + ] +} + diff --git a/static/logo.png b/static/logo.png new file mode 100644 index 0000000..9b02c93 Binary files /dev/null and b/static/logo.png differ diff --git a/templates/applogin.html b/templates/applogin.html index b3c192d..8593a72 100644 --- a/templates/applogin.html +++ b/templates/applogin.html @@ -263,7 +263,13 @@

Don't have an account? Create Account

Forgot Password?

-

Secured with SSL Encryption

+ +

Secured with SSL Encryption

diff --git a/templates/grn_records.html b/templates/grn_records.html new file mode 100644 index 0000000..1c97013 --- /dev/null +++ b/templates/grn_records.html @@ -0,0 +1,279 @@ + + + + + + Local GRN Records — Test Dashboard + + + +
+
+ GRN Records + Local Test +
+ Back to Dashboard +
+ +
+ + + +
+
n8n HTTP Node — Point these to your local server
+
+ OCR Endpoint : + http://localhost:8080/process-invoice + | + Header : + x-api-key: 971dcea6c47445f6f7405fa2d14e116b1d81dae6c10330571e8d4220c013b523 +
+
+ GRN Endpoint : + http://localhost:8080/dmhApiRef/grn/createGRN.php + | + Header : + x-api-key: nirajAi26@DMH +
+
+ JSON API : + GET http://localhost:8080/api/grn/records +
+
+ + + {% set total = records | length %} + {% set success_count = records | selectattr('status', 'equalto', 'created') | list | length %} +
+
+
Total GRNs
+
{{ total }}
+
+
+
Created
+
{{ success_count }}
+
+
+
Total Items
+
{{ records | sum(attribute='items_inserted') }}
+
+
+
Unique Sellers
+
{{ records | map(attribute='seller_name') | unique | list | length }}
+
+
+ + +
+
+

GRN Records (last 200)

+
+ + +
+
+ + {% if records %} +
+ + + + + + + + + + + + + + + + + {% for r in records %} + + + + + + + + + + + + + {% endfor %} + +
GRN NoInvoice NumberInvoice IDSeller NamePO NumberAmount (₹)ItemsSourceReceived AtStatus
{{ r.grn_no }}{{ r.invoice_number or '—' }}{{ r.invoice_id or '—' }}{{ r.seller_name or '—' }}{{ r.po_number or '—' }}{{ "%.2f"|format(r.invoice_amount|float) if r.invoice_amount else '0.00' }}{{ r.items_inserted }}{{ r.source or 'n8n' }}{{ r.received_at }}{{ r.status }}
+
+ {% else %} +
+

No GRN records yet.

+ Run your n8n workflow with the local endpoint to see records appear here. +
+ {% endif %} +
+
+ + + + + + + + diff --git a/templates/pharmacy_dashboard.html b/templates/pharmacy_dashboard.html new file mode 100644 index 0000000..a066687 --- /dev/null +++ b/templates/pharmacy_dashboard.html @@ -0,0 +1,2505 @@ + + + + + + DMH Hospital Pharmacy — PO Approval & Item Code Management + + + +
+ + + + +
+ +
+
+

Manual PO Number Approval

+

Review and approve Purchase Order numbers for pending invoices

+
+
+ +
+
+ +
+ +
+ +
+
+ + + + + + + + Queue 1 +
+
0
+
Pending PO Number Approval
+
Invoices awaiting PO number verification
+
+ + +
+
+ + + + + + + Queue 2 +
+
0
+
Pending Item Code Approval
+
Invoices awaiting standardized item codes
+
+ + +
+
+ + + + + + + Stored in DMH +
+
0
+
Total Invoices Processed
+
Completed & stored to DMH Database
+
+ + +
+
+ + + + + + + + Master DB +
+
14,324
+
Drug Master Catalog
+
Standardized item codes available
+
+
+ + + + +
+
+
+
+

Invoices Awaiting PO Number Approval

+ 0 Invoices Pending +
+

These invoices have missing or unverified PO Numbers. Review the extracted line items and provide the validated Purchase Order Number.

+
+ + + + + + + + + + + + + + + + + +
Invoice No.Vendor NameInvoice DateFilenameQueue ReasonPO StatusItem Code StatusApproval StatusAction
Loading pending PO invoices...
+
+
+
+ + + + +
+
+
+
+

Invoices Awaiting Item Code Approval

+ 0 Invoices Pending +
+

These invoices have a verified PO Number, but item codes require manual mapping. Review the invoice details and assign standardized item codes from the Drug Master catalog.

+
+ + + + + + + + + + + + + + + + + +
Invoice No.Vendor NameInvoice DateFilenameApproved POQueue ReasonItem Code StatusApproval StatusAction
Loading pending item code invoices...
+
+
+
+ + + + +
+
+
+

Approval History & Audit Trail

+ Permanent System Record +
+

Permanent audit record of all PO Number approvals, Item Code approvals, and automated GRN records stored in the DMH Database.

+ + +
+ + + + +
+ +
+ + + + + + + + + + + + + + + + + + +
Invoice No.VendorTypeProcessing FlowPO NumberStatusApproved ByDate & TimeWebhook / GRNAudit Details / Notes
Loading audit history...
+
+
+
+ + + + +
+
+
+
+

Drug Master Database Catalog

+
+
+

Standardized item codes and medication database (14,324 items). Used by the automated matching engine and manual item code assignment.

+ +
+ + + +
+ +
+ + + + + + + + + + + + +
Item CodeDrug Name / DescriptionCategoryActions
Loading catalog items...
+
+
+
+ + + + +
+
+
+

User Account Details

+
+ +
+
+ +
+
+
+ + + + + + + + + + + + + + + + + + + + + + diff --git a/templates/pharmacy_login.html b/templates/pharmacy_login.html new file mode 100644 index 0000000..8581ffd --- /dev/null +++ b/templates/pharmacy_login.html @@ -0,0 +1,239 @@ + + + + + + Pharmacy Staff Login + + + + + + + diff --git a/templates/po_approval_dashboard.html b/templates/po_approval_dashboard.html new file mode 100644 index 0000000..a066687 --- /dev/null +++ b/templates/po_approval_dashboard.html @@ -0,0 +1,2505 @@ + + + + + + DMH Hospital Pharmacy — PO Approval & Item Code Management + + + +
+ + + + +
+ +
+
+

Manual PO Number Approval

+

Review and approve Purchase Order numbers for pending invoices

+
+
+ +
+
+ +
+ +
+ +
+
+ + + + + + + + Queue 1 +
+
0
+
Pending PO Number Approval
+
Invoices awaiting PO number verification
+
+ + +
+
+ + + + + + + Queue 2 +
+
0
+
Pending Item Code Approval
+
Invoices awaiting standardized item codes
+
+ + +
+
+ + + + + + + Stored in DMH +
+
0
+
Total Invoices Processed
+
Completed & stored to DMH Database
+
+ + +
+
+ + + + + + + + Master DB +
+
14,324
+
Drug Master Catalog
+
Standardized item codes available
+
+
+ + + + +
+
+
+
+

Invoices Awaiting PO Number Approval

+ 0 Invoices Pending +
+

These invoices have missing or unverified PO Numbers. Review the extracted line items and provide the validated Purchase Order Number.

+
+ + + + + + + + + + + + + + + + + +
Invoice No.Vendor NameInvoice DateFilenameQueue ReasonPO StatusItem Code StatusApproval StatusAction
Loading pending PO invoices...
+
+
+
+ + + + +
+
+
+
+

Invoices Awaiting Item Code Approval

+ 0 Invoices Pending +
+

These invoices have a verified PO Number, but item codes require manual mapping. Review the invoice details and assign standardized item codes from the Drug Master catalog.

+
+ + + + + + + + + + + + + + + + + +
Invoice No.Vendor NameInvoice DateFilenameApproved POQueue ReasonItem Code StatusApproval StatusAction
Loading pending item code invoices...
+
+
+
+ + + + +
+
+
+

Approval History & Audit Trail

+ Permanent System Record +
+

Permanent audit record of all PO Number approvals, Item Code approvals, and automated GRN records stored in the DMH Database.

+ + +
+ + + + +
+ +
+ + + + + + + + + + + + + + + + + + +
Invoice No.VendorTypeProcessing FlowPO NumberStatusApproved ByDate & TimeWebhook / GRNAudit Details / Notes
Loading audit history...
+
+
+
+ + + + +
+
+
+
+

Drug Master Database Catalog

+
+
+

Standardized item codes and medication database (14,324 items). Used by the automated matching engine and manual item code assignment.

+ +
+ + + +
+ +
+ + + + + + + + + + + + +
Item CodeDrug Name / DescriptionCategoryActions
Loading catalog items...
+
+
+
+ + + + +
+
+
+

User Account Details

+
+ +
+
+ +
+
+
+ + + + + + + + + + + + + + + + + + + + + + diff --git a/test_po_flow.py b/test_po_flow.py new file mode 100644 index 0000000..53d7657 --- /dev/null +++ b/test_po_flow.py @@ -0,0 +1,354 @@ +#!/usr/bin/env python3 +""" +Comprehensive End-to-End Test for DMH Pharmacy Dashboard: +PO Number Approval & Item Code Management +Tests all 13 steps defined in Section 11. +""" + +import os +import sys +import json +import sqlite3 +import threading +from http.server import HTTPServer, BaseHTTPRequestHandler +import werkzeug +if not hasattr(werkzeug, '__version__'): + werkzeug.__version__ = '3.0.0' +from werkzeug.security import generate_password_hash + +# Ensure test uses app.py +from app import app, get_db, ensure_po_approval_tables + +# Setup Mock Webhook Server to capture n8n webhook calls +webhook_requests = [] +webhook_response_code = 200 + +class MockWebhookHandler(BaseHTTPRequestHandler): + def do_POST(self): + content_length = int(self.headers.get('Content-Length', 0)) + post_data = self.rfile.read(content_length) + try: + payload = json.loads(post_data.decode('utf-8')) + except Exception: + payload = post_data.decode('utf-8') + + webhook_requests.append({ + 'path': self.path, + 'headers': dict(self.headers), + 'payload': payload + }) + + self.send_response(webhook_response_code) + self.send_header('Content-Type', 'application/json') + self.end_headers() + self.wfile.write(json.dumps({'received': True, 'status': 'ok'}).encode('utf-8')) + + def log_message(self, format, *args): + pass # Quiet logging + +def start_mock_webhook_server(port=9988): + server = HTTPServer(('127.0.0.1', port), MockWebhookHandler) + thread = threading.Thread(target=server.serve_forever, daemon=True) + thread.start() + return server + +def run_tests(): + global webhook_response_code + print("=" * 70) + print("🧪 STARTING DMH PO NUMBER APPROVAL & ITEM CODE VERIFICATION") + print("=" * 70) + + # 1. Start mock webhook server + mock_port = 9988 + mock_server = start_mock_webhook_server(mock_port) + mock_webhook_url = f"http://127.0.0.1:{mock_port}/webhook/dmh-po-approval" + os.environ['DMH_PO_APPROVAL_WEBHOOK_URL'] = mock_webhook_url + print(f"✅ Mock n8n Webhook Server running on {mock_webhook_url}") + + # 2. Setup test client and test user + app.config['TESTING'] = True + client = app.test_client() + + # Create/ensure a test pharmacy user in DB + conn = get_db() + cursor = conn.cursor() + cursor.execute("SELECT id FROM users WHERE username = 'pharmacy_tester'") + existing_user = cursor.fetchone() + if not existing_user: + cursor.execute( + "INSERT INTO users (username, email, password, is_active, is_admin) VALUES (?, ?, ?, 1, 0)", + ('pharmacy_tester', 'tester@dmh.org', generate_password_hash('TestPass123!')) + ) + conn.commit() + user_id = cursor.lastrowid + else: + user_id = existing_user['id'] + conn.close() + + # Log in session for test client + with client.session_transaction() as sess: + sess['user_id'] = user_id + sess['username'] = 'pharmacy_tester' + print(f"✅ Authenticated as test user (id={user_id}, username='pharmacy_tester')") + + # ------------------------------------------------------------- + # Step 1 & 2: Condition 3 identification & Auto-submission + # (PO number missing/empty AND item code missing from invoice) + # ------------------------------------------------------------- + print("\n--- Testing Step 1 & 2: Condition 3 Identification ---") + mock_invoice_data = { + 'invoice_id': 'INV-TEST-2026-001', + 'invoice_number': 'INV-TEST-2026-001', + 'vendor_name': 'Apex Pharma Distributors', + 'invoice_date': '2026-11-20', + 'po_number': '', # MISSING PO + 'items': [ + { + 'description': 'UNKNOWN MEDICATION XYZ 500MG', + 'quantity': 100, + 'unit_price': 45.50, + 'item_code': '', + 'item_code_source': 'not_found', # MISSING ITEM CODE + 'in_csv': False + } + ] + } + + # Store extraction in extractions table + conn = get_db() + cursor = conn.cursor() + cursor.execute( + "INSERT INTO extractions (user_id, invoice_id, filename, extraction_data) VALUES (?, ?, ?, ?)", + (user_id, 'INV-TEST-2026-001', 'test_invoice_cond3.pdf', json.dumps(mock_invoice_data)) + ) + conn.commit() + extraction_id = cursor.lastrowid + conn.close() + + # Submit to PO approval queue (mimics upload auto-submit logic) + submit_resp = client.post('/api/po-approval/submit', json={ + 'extraction_id': extraction_id, + 'invoice_number': 'INV-TEST-2026-001', + 'vendor_name': 'Apex Pharma Distributors', + 'invoice_date': '2026-11-20', + 'invoice_filename': 'test_invoice_cond3.pdf', + 'po_number_original': '' + }) + assert submit_resp.status_code in (200, 201), f"Submit failed: {submit_resp.data}" + submit_data = submit_resp.get_json() + po_invoice_id = submit_data['po_invoice_id'] + print(f"✅ Condition 3 record queued in po_approval_invoices with ID: {po_invoice_id}") + + # Test duplicate submission prevention + dup_resp = client.post('/api/po-approval/submit', json={ + 'extraction_id': extraction_id, + 'invoice_number': 'INV-TEST-2026-001', + 'vendor_name': 'Apex Pharma Distributors', + 'invoice_date': '2026-11-20', + 'invoice_filename': 'test_invoice_cond3.pdf', + 'po_number_original': '' + }) + dup_data = dup_resp.get_json() + assert dup_data.get('duplicate') is True and dup_data.get('po_invoice_id') == po_invoice_id + print("✅ Duplicate submission prevention verified") + + # ------------------------------------------------------------- + # Step 3: Pending PO Number Approval List + # ------------------------------------------------------------- + print("\n--- Testing Step 3: Pending PO Approval Listing ---") + pending_resp = client.get('/api/po-approval/pending') + assert pending_resp.status_code == 200 + pending_list = pending_resp.get_json()['data'] + matching_pending = [p for p in pending_list if p['id'] == po_invoice_id] + assert len(matching_pending) == 1, "Invoice not found in pending list!" + p_item = matching_pending[0] + assert p_item['invoice_number'] == 'INV-TEST-2026-001' + assert p_item['vendor_name'] == 'Apex Pharma Distributors' + assert p_item['approval_status'] == 'pending' + print(f"✅ Invoice correctly listed in Pending PO Approvals ({p_item['invoice_number']})") + + # ------------------------------------------------------------- + # Step 4: Invoice Details and Line Items + # ------------------------------------------------------------- + print("\n--- Testing Step 4: Invoice Details & Items ---") + detail_resp = client.get(f'/api/po-approval/invoice/{po_invoice_id}') + assert detail_resp.status_code == 200 + detail_data = detail_resp.get_json() + assert detail_data['data']['invoice_number'] == 'INV-TEST-2026-001' + assert len(detail_data['items']) == 1 + assert detail_data['items'][0]['description'] == 'UNKNOWN MEDICATION XYZ 500MG' + print(f"✅ Invoice details retrieved with {len(detail_data['items'])} line items") + + # ------------------------------------------------------------- + # Step 5 & 6: Validation, Manual PO Entry and Approval + # ------------------------------------------------------------- + print("\n--- Testing Step 5 & 6: Validation and Manual PO Approval ---") + # Test empty PO rejection + empty_po_resp = client.post(f'/api/po-approval/{po_invoice_id}/approve', json={'po_number': ' '}) + assert empty_po_resp.status_code == 400 + print("✅ Empty PO Number correctly rejected (HTTP 400)") + + # Clear captured webhook requests + webhook_requests.clear() + webhook_response_code = 200 + + # Submit valid PO approval + test_po_num = "PO-DMH-98765" + approve_resp = client.post(f'/api/po-approval/{po_invoice_id}/approve', json={'po_number': test_po_num}) + assert approve_resp.status_code == 200 + appr_res = approve_resp.get_json() + assert appr_res['success'] is True + assert appr_res['approval_status'] == 'approved' + assert appr_res['webhook_status'] == 'success' + print(f"✅ Approval submitted successfully with PO: {test_po_num}") + + # ------------------------------------------------------------- + # Step 7 & 8: Verify DB persistence & Audit fields + # ------------------------------------------------------------- + print("\n--- Testing Step 7 & 8: Database Persistence & User Audit ---") + conn = get_db() + cursor = conn.cursor() + cursor.execute("SELECT * FROM po_approval_invoices WHERE id = ?", (po_invoice_id,)) + inv_row = cursor.fetchone() + assert inv_row['approval_status'] == 'approved' + assert inv_row['po_number_approved'] == test_po_num + assert inv_row['approved_by'] == user_id + assert inv_row['approved_at'] is not None + + cursor.execute("SELECT * FROM po_approval_history WHERE po_invoice_id = ?", (po_invoice_id,)) + hist_rows = cursor.fetchall() + assert len(hist_rows) >= 1 + latest_hist = hist_rows[-1] + assert latest_hist['po_number_approved'] == test_po_num + assert latest_hist['approved_by'] == user_id + assert latest_hist['approved_by_username'] == 'pharmacy_tester' + assert latest_hist['webhook_status'] == 'success' + conn.close() + print(f"✅ Database verified: PO={inv_row['po_number_approved']}, user_id={inv_row['approved_by']}, time={inv_row['approved_at']}") + + # ------------------------------------------------------------- + # Step 9 & 10: Verify n8n Webhook Trigger & Payload + # ------------------------------------------------------------- + print("\n--- Testing Step 9 & 10: n8n Webhook Payload & Status ---") + assert len(webhook_requests) == 1, f"Expected 1 webhook call, got {len(webhook_requests)}" + wh_call = webhook_requests[0] + expected_payload = { + "event": "po_number_approved", + "invoice_id": po_invoice_id, + "invoice_number": "INV-TEST-2026-001", + "approved_po_number": test_po_num, + "approved_by": user_id, + "approval_status": "approved" + } + assert wh_call['payload'] == expected_payload, f"Payload mismatch: {wh_call['payload']} vs {expected_payload}" + print(f"✅ Webhook payload verified: {json.dumps(wh_call['payload'], indent=2)}") + + # Test duplicate approval blocked + dup_appr = client.post(f'/api/po-approval/{po_invoice_id}/approve', json={'po_number': 'PO-ANOTHER'}) + assert dup_appr.status_code == 409 + print("✅ Duplicate approval prevented (HTTP 409)") + + # ------------------------------------------------------------- + # Step 11: PO Approval History Audit Trail + # ------------------------------------------------------------- + print("\n--- Testing Step 11: PO Approval History Verification ---") + hist_resp = client.get('/api/po-approval/history?status=approved') + assert hist_resp.status_code == 200 + hist_list = hist_resp.get_json()['data'] + found_in_history = [h for h in hist_list if h['po_invoice_id'] == po_invoice_id] + assert len(found_in_history) >= 1 + print(f"✅ History listing verified ({len(found_in_history)} record(s) for this invoice)") + + # ------------------------------------------------------------- + # Step 12: Webhook Failure and Safe Retry + # ------------------------------------------------------------- + print("\n--- Testing Step 12: Webhook Failure & Retry Logic ---") + # Create another test invoice for failure test + conn = get_db() + cursor = conn.cursor() + cursor.execute( + "INSERT INTO extractions (user_id, invoice_id, filename, extraction_data) VALUES (?, ?, ?, ?)", + (user_id, 'INV-TEST-FAIL-002', 'test_fail.pdf', json.dumps(mock_invoice_data)) + ) + fail_ext_id = cursor.lastrowid + cursor.execute(''' + INSERT INTO po_approval_invoices + (extraction_id, invoice_number, vendor_name, invoice_date, invoice_filename, po_number_original) + VALUES (?, 'INV-TEST-FAIL-002', 'Beta Med', '2026-11-21', 'test_fail.pdf', '') + ''', (fail_ext_id,)) + fail_po_id = cursor.lastrowid + conn.commit() + conn.close() + + # Simulate webhook failure (HTTP 500 from webhook server) + webhook_response_code = 500 + fail_approve_resp = client.post(f'/api/po-approval/{fail_po_id}/approve', json={'po_number': 'PO-FAIL-111'}) + assert fail_approve_resp.status_code == 200 + fail_data = fail_approve_resp.get_json() + assert fail_data['approval_status'] == 'approved' + assert fail_data['webhook_status'] == 'failed' + print("✅ Approved record preserved even when webhook returns HTTP 500 (safe failure)") + + # Retrieve history record ID for retry + conn = get_db() + cursor = conn.cursor() + cursor.execute("SELECT id FROM po_approval_history WHERE po_invoice_id = ?", (fail_po_id,)) + fail_hist_id = cursor.fetchone()['id'] + conn.close() + + # Test retry with webhook server restored to HTTP 200 + webhook_response_code = 200 + retry_resp = client.post(f'/api/po-approval/{fail_hist_id}/retry-webhook') + assert retry_resp.status_code == 200 + retry_data = retry_resp.get_json() + assert retry_data['webhook_status'] == 'success' + print("✅ Webhook retry succeeded and updated history status to 'success'") + + # Test rejection flow + conn = get_db() + cursor = conn.cursor() + cursor.execute(''' + INSERT INTO po_approval_invoices + (extraction_id, invoice_number, vendor_name, invoice_date, invoice_filename, po_number_original) + VALUES (?, 'INV-TEST-REJECT-003', 'Gamma Supplies', '2026-11-22', 'test_rej.pdf', '') + ''', (fail_ext_id,)) + rej_po_id = cursor.lastrowid + conn.commit() + conn.close() + + rej_resp = client.post(f'/api/po-approval/{rej_po_id}/reject', json={'notes': 'Wrong vendor invoice'}) + assert rej_resp.status_code == 200 + assert rej_resp.get_json()['approval_status'] == 'rejected' + print("✅ Rejection flow verified") + + # ------------------------------------------------------------- + # Step 13: Existing Item Code Management Logic Continues Working + # ------------------------------------------------------------- + print("\n--- Testing Step 13: Existing Item Code Management ---") + cat_resp = client.get('/api/catalog?per_page=5') + assert cat_resp.status_code == 200 + cat_data = cat_resp.get_json() + assert cat_data['success'] is True + assert cat_data['total'] > 0 + print(f"✅ Catalog browsing active: {cat_data['total']} item codes available") + + auto_resp = client.get('/api/catalog/autocomplete?q=para') + assert auto_resp.status_code == 200 + auto_data = auto_resp.get_json() + assert auto_data['success'] is True + print(f"✅ Catalog autocomplete active: returned {len(auto_data['data'])} suggestions") + + cats_resp = client.get('/api/catalog/categories') + assert cats_resp.status_code == 200 + print(f"✅ Catalog categories active: {len(cats_resp.get_json()['data'])} categories") + + pending_items_resp = client.get('/api/pending-items') + assert pending_items_resp.status_code == 200 + print("✅ Existing Item Code pending approval queue active") + + print("\n" + "=" * 70) + print("🎉 ALL 13 TEST STEPS PASSED SUCCESSFULLY!") + print("=" * 70) + +if __name__ == '__main__': + run_tests() diff --git a/test_webhook_aiinvoice.py b/test_webhook_aiinvoice.py new file mode 100644 index 0000000..9436afc --- /dev/null +++ b/test_webhook_aiinvoice.py @@ -0,0 +1,57 @@ +import os +import sys +import werkzeug +if not hasattr(werkzeug, "__version__"): + werkzeug.__version__ = "3.0.0" + +os.environ["N8N_APPROVED_WEBHOOK_URL"] = "" + +import app as aiinvoice_app +from unittest.mock import patch, MagicMock + +print("Testing e:\\aiinvoice test-webhook endpoint with empty URL...", flush=True) +with aiinvoice_app.app.test_request_context(): + res = aiinvoice_app.pharmacy_test_webhook() + resp_obj, status = res + assert status == 400 + assert resp_obj.json.get("configured") is False + print("Passed: returns 400 and configured=False when empty.", flush=True) + +test_invoice = { + "invoice_id": "INV-TEST-999", + "invoice_number": "TEST/2026/01", + "supplier": "TEST PHARMA", + "items": [ + {"description": "PARACETAMOL 500MG", "item_code": "PARA-500", "quantity": 10} + ] +} + +print("Testing dispatch_n8n_approval_webhook with mocked n8n...", flush=True) +with patch.dict(os.environ, {"N8N_APPROVED_WEBHOOK_URL": "https://n8n.example.com/webhook/invoice-approved", "N8N_WEBHOOK_SECRET": "my-secret-123"}): + with patch("requests.post") as mock_post: + mock_resp = MagicMock() + mock_resp.status_code = 200 + mock_resp.text = '{"status":"received"}' + mock_post.return_value = mock_resp + + result = aiinvoice_app.dispatch_n8n_approval_webhook( + extraction_id=999, + invoice_data=test_invoice, + approver_username="pharmacy_lead" + ) + print("Webhook result:", result, flush=True) + assert result["status"] == "delivered", f"Expected delivered, got {result}" + assert mock_post.called + call_args = mock_post.call_args + payload = call_args[1]["json"] + headers = call_args[1]["headers"] + assert payload["event"] == "invoice_approved" + assert payload["extraction_id"] == 999 + assert payload["status"] == "approved" + assert payload["approved_by"] == "pharmacy_lead" + assert payload["invoice_data"]["invoice_id"] == "INV-TEST-999" + assert headers.get("X-Webhook-Secret") == "my-secret-123" + print("Passed: webhook payload structured accurately with event, status, approver, headers, and invoice_data.", flush=True) + +print("\nAIINVOICE TEST PASSED SUCCESSFULLY!", flush=True) + diff --git a/users.db b/users.db new file mode 100644 index 0000000..8666f23 Binary files /dev/null and b/users.db differ