integrated pharmacy dashboard with aiinvoice
This commit is contained in:
+220
-4
@@ -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
|
||||
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
|
||||
|
||||
Reference in New Issue
Block a user