""" Vendor Master & GSTIN Lookup (Dynamic Excel-backed) --------------------------------------------------- Uses 'Seller_GSTIN.xlsx' as the authoritative vendor master. Features: 1. Loads all approved vendors, supplier codes, and GSTINs on startup. 2. Multi-tier matching (exact, alias, substring, token overlap) to find the authoritative GSTIN even with OCR typos in the invoice vendor name. 3. If a vendor is found: overrides/enriches seller_gstin with the authoritative GSTIN. 4. If a vendor is NOT found: - Extracts and shows the vendor name & GSTIN from OCR. - Automatically appends the new vendor to 'Seller_GSTIN.xlsx' so future invoices will recognize it immediately. """ import os import sys if hasattr(sys.stdout, 'reconfigure'): try: sys.stdout.reconfigure(encoding='utf-8') except Exception: pass if hasattr(sys.stderr, 'reconfigure'): try: sys.stderr.reconfigure(encoding='utf-8') except Exception: pass import re import unicodedata import threading from typing import Optional, Dict, Any, List import openpyxl try: from langsmith import traceable except ImportError: def traceable(*args, **kwargs): def decorator(fn): return fn return decorator try: from gstin_validator import validate_and_fix_gstin except ImportError: def validate_and_fix_gstin(raw, label='GSTIN'): if not raw: return None cleaned = re.sub(r'[\s\-\./]', '', str(raw)).upper() return cleaned # Thread safety lock for reading/writing the vendor Excel file _EXCEL_LOCK = threading.Lock() # Candidate filenames for the vendor master sheet VENDOR_EXCEL_CANDIDATES = [ "Seller_GSTIN.xlsx", "LIST OF VENDOR WITH GST.xlsx", "LIST OF VENDOR WITH GST (1).xlsx", "list of vendor.xlsx", "list of vendor .xlsx", ] _VENDOR_FILE_PATH: Optional[str] = None _VENDOR_ENTRIES: List[Dict[str, Any]] = [] _VENDOR_LOOKUP: Dict[str, Dict[str, Any]] = {} _LAST_LOAD_TIME: float = 0 # Stop words to ignore during fuzzy token matching _STOP_WORDS = { "PVT", "LTD", "LIMITED", "PRIVATE", "LLP", "ENTERPRISES", "ENTERPRISE", "SERVICES", "PHARMA", "PHARMACEUTICALS", "PHARMACEUTICAL", "CORPORATION", "DISTRIBUTORS", "DISTRIBUTOR", "AGENCIES", "AGENCY", "MEDISALES", "HEALTHCARE", "SOLUTIONS", "MARKETING", "LIFE", "SCIENCES", "LIFESCIENCES", "MEDICAL", "STORE", "STORES", "AND", "&", "CO", "COMPANY", "INDIA" } # Known aliases and edge-case overrides SELLER_GSTIN_MAP: Dict[str, str] = { "PHARMACEA LINK": "27AALFP5376P1ZA", "PHARMACEALINK": "27AALFP5376P1ZA", "AADESH PHARMACEUTICAL": "27ABLFA7017P1ZX", "AADESH PHARMACEUUTICAL": "27ABLFA7017P1ZX", "AADESH PHARMACEUTICALS": "27ABLFA7017P1ZX", "PROGRESS HEALTHCARE MEDICAL SERVICES LLP": "27AAVFP0728M1ZK", "PROGRESS HEALTHCARE & MEDICAL SERVICES LLP": "27AAVFP0728M1ZK", "SHLOKA ENTERPRISES": "27AIWPA8054A1ZA", "CRITICAL CARE SYSTEMS": "27AADFC3319B1Z1", "HEALTHCARE ENTERPRISES": "27AFTPK0484L1ZT", "KALPAK MARKETING PVT LTD": "27AABCK2267K1ZD", "KALPAK MARKETING PRIVATE LIMITED": "27AABCK2267K1ZD", "AVIAN WELLNESS PVT LTD": "27AAOCA5119K1ZD", "AVIAN WELLNESS PVTLTD": "27AAOCA5119K1ZD", "AVIAN WELLNESS PRIVATE LIMITED": "27AAOCA5119K1ZD", "NEW SALAKSHMI MEDISALES LLP": "27AAOFN3880H1ZT", "TAPADIYA DISTRIBUTORS": "27AABFT1696C1Z8", "AAKANKSHA LOGISTICS PVT LTD": "27AACCA2971K1ZJ", "AAKANKSHA LOGISTICS PRIVATE LIMITED": "27AACCA2971K1ZJ", "KANCHAN DRUGS PRIVATE LIMITED": "27AAACK7501K1ZJ", "KANCHAN DRUGS PVT LTD": "27AAACK7501K1ZJ", "SAIRAJ DISTRIBUTORS": "27ADLFS9893D1ZC", "MILTON LIFECARE PRIVATE LIMITED": "27AAFCM2670J1ZA", "MILTON LIFECARE PVT LTD": "27AAFCM2670J1ZA", "KUNDAN DISTRIBUTORS PVT LTD": "27AAHCK2490E1ZJ", "KUNDAN DISTRIBUTORS PRIVATE LIMITED": "27AAHCK2490E1ZJ", "NITIN AGENCY PHARMACEUTICAL DISTRIBUTORS": "27AACFN3926C1ZK", "NITIN AGENCY": "27AACFN3926C1ZK", "YOGA ENTERPRISES": "27AAZPP8101A1ZL", "SCORIA INCORPORATION": "27AAUPD9798E1ZX", "ARIHANT BIOPHARMA CORPORATION": "27AAJFA9526G1ZA", "CHEMSEARCH": "27AAIFC6533C1ZO", "SPANDAN HEALTHCARE": "27AFIPD4405P1ZA", "MATRIX BIOMEDICS PVT LTD": "27AADCM2647P1ZZ", "MATRIX BIOMEDICS PRIVATE LIMITED": "27AADCM2647P1ZZ", "SANJEEVANI ENTERPRISE 25 26": "27ACDFS6564Q1Z9", "SANJEEVANI ENTERPRISE 2526": "27ACDFS6564Q1Z9", "SANJEEVANI ENTERPRISE": "27ACDFS6564Q1Z9", "ARIHANT CHEMIST LLP": "27ABLFA7907J1Z2", "TAPADIYA LIFE SCIENCES": "27AAFFT4132P1ZS", "E BIOREMEDIES LTD": "27AADCE3683M1Z7", "E BIOREMEDIES LIMITED": "27AADCE3683M1Z7", "ONENESS ENTERPRISES": "27BGMPM8256M1ZJ", "ONENESS ENTERPRISES FY 2025 26": "27BGMPM8256M1ZJ", "ONENESS ENTERPRISES FY 202526": "27BGMPM8256M1ZJ", "VIHAAN ENTERPRISES": "27AAVPP4610L1Z4", "PRANAV MEDICARE 2025 2027": "27AUVPS6762N1ZB", "PRANAV MEDICARE 2025 2026": "27AUVPS6762N1ZB", "PRANAV MEDICARE": "27AUVPS6762N1ZB", "DEENANATH MEDICAL STORES": "27AAATL1944N1ZA", "RAVI MEDICO": "27AAUPR1161Q1ZD", "GALAXY ALLIANCE LLP": "27AAYFG6456C1ZY", "MIS HEALTHCARE PVT LTD": "27AAHCM2065M1Z5", "MIS HEALTHCARE PRIVATE LIMITED": "27AAHCM2065M1Z5", "HEALTHLINE PRIVATE LIMITED": "29AABCH3719P1ZU", "HEALTHLINE PVT LTD": "29AABCH3719P1ZU", "ASSOCIATED THERAPEUTIC CARE PVT LTD": "27AALCA3876G1ZD", "ASSOCIATED THERAPEUTIC CARE PRIVATE LIMITED": "27AALCA3876G1ZD", "SHREE VENKATESH AGENCIES": "27ACSFS1246C1Z2", "KDB SURGI PHARMA": "27AAIFK8419R1ZG", "KDB SURGIPHARMA": "27AAIFK8419R1ZG", "CHANDULAL R MEHTA": "27AAKPC8047A1ZB", } def _find_vendor_file() -> Optional[str]: """Find the path of the vendor master Excel file.""" base_dir = os.path.dirname(os.path.abspath(__file__)) for candidate in VENDOR_EXCEL_CANDIDATES: full_path = os.path.join(base_dir, candidate) if os.path.exists(full_path): return full_path # Check parent directory as fallback parent_dir = os.path.dirname(base_dir) for candidate in VENDOR_EXCEL_CANDIDATES: full_path = os.path.join(parent_dir, candidate) if os.path.exists(full_path): return full_path return None def _normalise(name: str) -> str: """ UPPERCASE, strip diacritics (ä→a, etc.), collapse whitespace, strip punctuation so minor OCR variations still match. """ if not name: return "" name = unicodedata.normalize('NFKD', str(name)) name = ''.join(c for c in name if not unicodedata.combining(c)) name = name.upper() name = re.sub(r"[.\-,&'/\\]", " ", name) name = re.sub(r"\s+", " ", name).strip() return name def _significant_tokens(norm_name: str) -> set: """Extract significant tokens ignoring common stop words.""" tokens = {t for t in norm_name.split() if len(t) > 1 and t not in _STOP_WORDS} return tokens def load_vendor_master_excel(force: bool = False) -> None: """ Load approved vendors from the Excel master file into in-memory lookup. """ global _VENDOR_FILE_PATH, _VENDOR_ENTRIES, _VENDOR_LOOKUP, _LAST_LOAD_TIME with _EXCEL_LOCK: file_path = _find_vendor_file() if not file_path: print("⚠️ Vendor master Excel file not found. Falling back to built-in vendor map.") _VENDOR_FILE_PATH = os.path.join(os.path.dirname(os.path.abspath(__file__)), "Seller_GSTIN.xlsx") return _VENDOR_FILE_PATH = file_path try: # Load with data_only=True to evaluate formulas like =VLOOKUP(...) wb = openpyxl.load_workbook(file_path, data_only=True) ws = wb.active # Detect header row and column positions header_row = None name_col = None gst_col = None sr_col = None code_col = None for r in range(1, min(10, ws.max_row + 1)): row_vals = [str(ws.cell(r, c).value or '').strip().upper() for c in range(1, max(ws.max_column + 1, 10))] has_vendor = any("VENDOR" in v or "NAME" in v for v in row_vals) has_gst = any("GST" in v for v in row_vals) if has_vendor or has_gst: header_row = r for c_idx, val in enumerate(row_vals, start=1): if "GST" in val and not gst_col: gst_col = c_idx elif ("VENDOR" in val or "NAME" in val) and not name_col: name_col = c_idx elif ("SR" in val or "S.NO" in val) and not sr_col: sr_col = c_idx elif "CODE" in val and not code_col: code_col = c_idx if name_col and gst_col: break if not header_row: header_row = 2 # Fallbacks if columns not identified by headers if not name_col and not gst_col: name_col, gst_col = 1, 2 # Prevent column overlap if sr_col in (name_col, gst_col): sr_col = None if code_col in (name_col, gst_col): code_col = None entries = [] lookup = {} for r in range(header_row + 1, ws.max_row + 1): sr_val = ws.cell(r, sr_col).value if sr_col else None code_val = ws.cell(r, code_col).value if code_col else None name_val = ws.cell(r, name_col).value if name_col else None gst_val = ws.cell(r, gst_col).value if gst_col else None if not name_val: continue raw_name = str(name_val or "").strip() if not raw_name: continue raw_gstin = str(gst_val or "").strip().upper() if raw_gstin in ("NONE", "NAN", "NULL"): raw_gstin = "" # Clean GSTIN clean_gstin = re.sub(r'[^A-Z0-9]', '', raw_gstin) entry = { "row_index": r, "sr_no": sr_val, "supplier_code": str(code_val or "").strip() if code_val else "", "name": raw_name, "norm_name": _normalise(raw_name), "gstin": clean_gstin, } entries.append(entry) if entry["norm_name"]: lookup[entry["norm_name"]] = entry # Also seed any SELLER_GSTIN_MAP entries if not present for alias_name, gstin in SELLER_GSTIN_MAP.items(): norm_alias = _normalise(alias_name) if norm_alias not in lookup: lookup[norm_alias] = { "row_index": None, "sr_no": None, "supplier_code": "MAP", "name": alias_name, "norm_name": norm_alias, "gstin": gstin, } _VENDOR_ENTRIES = entries _VENDOR_LOOKUP = lookup _LAST_LOAD_TIME = os.path.getmtime(file_path) if os.path.exists(file_path) else 0 print(f"✅ Vendor master loaded: {len(entries)} vendors from '{os.path.basename(file_path)}' (lookup keys: {len(lookup)})") except Exception as e: print(f"⚠️ Error loading vendor master Excel ({file_path}): {e}") def lookup_vendor(seller_name: str) -> Optional[Dict[str, Any]]: """ Search for a vendor in the vendor master. Matching Strategy: 1. Exact normalized name match. 2. Known alias / SELLER_GSTIN_MAP match. 3. Substring match: lookup key inside seller_name, or seller_name inside lookup key. 4. Significant token overlap match. """ if not seller_name: return None if not _VENDOR_LOOKUP: load_vendor_master_excel() norm_query = _normalise(seller_name) if not norm_query: return None # 1. Exact normalized match if norm_query in _VENDOR_LOOKUP: return _VENDOR_LOOKUP[norm_query] # 2. Check SELLER_GSTIN_MAP direct match if norm_query in SELLER_GSTIN_MAP: return {"name": seller_name, "gstin": SELLER_GSTIN_MAP[norm_query], "supplier_code": "MAP"} # 3. Substring matching # Best substring: prefer candidate with maximum length match best_candidate = None best_match_len = 0 for norm_key, entry in _VENDOR_LOOKUP.items(): if len(norm_key) < 3: continue # Key is inside extracted name (e.g. "KANCHAN DRUGS" in "KANCHAN DRUGS PRIVATE LIMITED") if norm_key in norm_query: if len(norm_key) > best_match_len: best_match_len = len(norm_key) best_candidate = entry # Extracted name is inside Key elif norm_query in norm_key and len(norm_query) >= 4: if len(norm_query) > best_match_len: best_match_len = len(norm_query) best_candidate = entry if best_candidate: return best_candidate # 4. Token overlap matching query_tokens = _significant_tokens(norm_query) if len(query_tokens) >= 2: for norm_key, entry in _VENDOR_LOOKUP.items(): entry_tokens = _significant_tokens(norm_key) if entry_tokens and (query_tokens.issubset(entry_tokens) or entry_tokens.issubset(query_tokens)): return entry return None def lookup_seller_gstin(seller_name: str) -> Optional[str]: """ Backwards-compatible function: returns just the GSTIN string for *seller_name*, or None if not found in the vendor master. """ match = lookup_vendor(seller_name) return match.get("gstin") if match else None def add_vendor_to_excel(seller_name: str, gstin: str, supplier_code: Optional[str] = None) -> bool: """ Dynamically append a new vendor and GSTIN into the Excel master file. Also updates in-memory cache immediately. """ clean_name = str(seller_name or "").strip() if not clean_name or len(clean_name) < 3: return False # Ignore obvious invoice header false positives generic_false_positives = { "TAX INVOICE", "INVOICE", "BILL OF SUPPLY", "ORIGINAL FOR RECIPIENT", "DUPLICATE FOR TRANSPORTER", "PURCHASE ORDER", "CASH MEMO", "RETAIL INVOICE" } if _normalise(clean_name) in generic_false_positives: return False clean_gstin = re.sub(r'[^A-Z0-9]', '', str(gstin or "").upper()) with _EXCEL_LOCK: file_path = _VENDOR_FILE_PATH or _find_vendor_file() if not file_path: file_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "Seller_GSTIN.xlsx") norm_name = _normalise(clean_name) if norm_name in _VENDOR_LOOKUP: existing = _VENDOR_LOOKUP[norm_name] if existing.get("gstin"): print(f"[VENDOR EXCEL] Vendor '{clean_name}' already exists with GSTIN '{existing.get('gstin')}'. Skipping duplicate addition.") return False try: wb = openpyxl.load_workbook(file_path, data_only=False) ws = wb.active # Detect column positions in worksheet name_col = None gst_col = None sr_col = None code_col = None for r in range(1, min(10, ws.max_row + 1)): row_vals = [str(ws.cell(r, c).value or '').strip().upper() for c in range(1, max(ws.max_column + 1, 10))] has_vendor = any("VENDOR" in v or "NAME" in v for v in row_vals) has_gst = any("GST" in v for v in row_vals) if has_vendor or has_gst: for c_idx, val in enumerate(row_vals, start=1): if "GST" in val and not gst_col: gst_col = c_idx elif ("VENDOR" in val or "NAME" in val) and not name_col: name_col = c_idx elif ("SR" in val or "S.NO" in val) and not sr_col: sr_col = c_idx elif "CODE" in val and not code_col: code_col = c_idx if name_col and gst_col: break if not name_col and not gst_col: name_col, gst_col = 1, 2 # Prevent column overlap if sr_col in (name_col, gst_col): sr_col = None if code_col in (name_col, gst_col): code_col = None # Find true last row last_row = 2 max_sr = 0 for r in range(2, ws.max_row + 1): val_sr = ws.cell(r, sr_col).value if sr_col else None val_name = ws.cell(r, name_col).value if name_col else None if val_sr is not None or val_name is not None: last_row = r try: if val_sr and int(val_sr) > max_sr: max_sr = int(val_sr) except (ValueError, TypeError): pass new_row = last_row + 1 new_sr = max_sr + 1 if sr_col else None code = supplier_code or (f"S-AUTO{new_sr}" if new_sr else "") if sr_col: ws.cell(new_row, sr_col, new_sr) if code_col: ws.cell(new_row, code_col, code) ws.cell(new_row, name_col, clean_name) ws.cell(new_row, gst_col, clean_gstin) wb.save(file_path) # Update in-memory entries new_entry = { "row_index": new_row, "sr_no": new_sr, "supplier_code": code, "name": clean_name, "norm_name": norm_name, "gstin": clean_gstin, } _VENDOR_ENTRIES.append(new_entry) _VENDOR_LOOKUP[norm_name] = new_entry print(f"💾 [VENDOR EXCEL] Successfully appended new vendor to '{os.path.basename(file_path)}':") print(f" Row: {new_row} | SR: {new_sr} | Code: {code} | Name: '{clean_name}' | GSTIN: '{clean_gstin}'") return True except PermissionError: print(f"⚠️ [VENDOR EXCEL] Could not write to '{file_path}' (file is open in another program like Excel).") # Keep in-memory so subsequent queries still benefit new_entry = { "row_index": None, "sr_no": None, "supplier_code": supplier_code or "S-AUTO", "name": clean_name, "norm_name": norm_name, "gstin": clean_gstin, } _VENDOR_LOOKUP[norm_name] = new_entry return False except Exception as e: print(f"⚠️ [VENDOR EXCEL] Failed to append vendor to Excel: {e}") return False @traceable(name="apply_seller_gstin_override", tags=["override", "seller-gstin"]) def apply_seller_gstin_override(data: dict) -> dict: """ Checks the vendor name against the vendor master Excel file ('Seller_GSTIN.xlsx'): 1. If found in the Excel file: - Fetches authoritative GSTIN from Excel and overrides data['seller_gstin']. - Also fills or updates vendor details. 2. If NOT found in the Excel file: - Retains the OCR-extracted seller_name and seller_gstin for display. - Automatically appends the new vendor to the Excel file so it's remembered. """ seller_name = (data.get("seller_name") or "").strip() extracted_gstin = (data.get("seller_gstin") or "").strip() if not seller_name: return data match = lookup_vendor(seller_name) if match and match.get("gstin"): authoritative_gstin = match["gstin"] canonical_name = match.get("name") or seller_name if extracted_gstin == authoritative_gstin: print(f"[VENDOR EXCEL] ✅ Verified in Excel: '{seller_name}' -> {authoritative_gstin}") else: print(f"[VENDOR EXCEL] 🔧 Found in Excel for '{seller_name}'. Overriding GSTIN:") print(f" Extracted : '{extracted_gstin}'") print(f" Excel GSTIN: '{authoritative_gstin}' ({canonical_name})") data["seller_gstin"] = authoritative_gstin # Optionally enrich canonical name if not empty if canonical_name and not data.get("seller_name"): data["seller_name"] = canonical_name else: # Vendor not found in the Excel file! print(f"[VENDOR EXCEL] 🔍 Vendor '{seller_name}' not in Excel file. Preserving OCR extraction.") # Clean/validate extracted GSTIN clean_extracted_gstin = "" if extracted_gstin: clean_extracted_gstin = validate_and_fix_gstin(extracted_gstin, label="NewSeller") or extracted_gstin data["seller_gstin"] = clean_extracted_gstin # Store to Excel file dynamically add_vendor_to_excel(seller_name=seller_name, gstin=clean_extracted_gstin) return data # Auto-load on initial import load_vendor_master_excel()