integrated pharmacy dashboard with aiinvoice
This commit is contained in:
Binary file not shown.
File diff suppressed because one or more lines are too long
@@ -14353,3 +14353,9 @@ BHARTI01,paracetamol (10mg) + thiocolchicoside (10mg)(null mg)Tablet
|
|||||||
DMH01,Ajay + Vishal(20 mg)Tablet
|
DMH01,Ajay + Vishal(20 mg)Tablet
|
||||||
JPL002,
|
JPL002,
|
||||||
MET137,Methylcobalamin(1500mcg)+l-methylfolate(10mg)+pyridoxal-5-phosphate(5mg) Film coated tablet
|
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
|
||||||
|
|||||||
|
Can't render this file because it is too large.
|
@@ -361,4 +361,4 @@ def get_free_item_stats(data: Dict[str, Any], total_before: Optional[int] = None
|
|||||||
'paid_items': paid_count,
|
'paid_items': paid_count,
|
||||||
'free_items': free_count,
|
'free_items': free_count,
|
||||||
'has_free_items': free_count > 0
|
'has_free_items': free_count > 0
|
||||||
}
|
}
|
||||||
BIN
Binary file not shown.
Binary file not shown.
+220
-4
@@ -28,11 +28,13 @@ Design notes (why matches are refused rather than guessed):
|
|||||||
import os
|
import os
|
||||||
import re
|
import re
|
||||||
import logging
|
import logging
|
||||||
|
import threading
|
||||||
from difflib import SequenceMatcher
|
from difflib import SequenceMatcher
|
||||||
|
|
||||||
logger = logging.getLogger(__name__)
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
DRUG_DATABASE = None # dict: lowercase raw name -> {'item_code','name','parsed'}
|
DRUG_DATABASE = None # dict: lowercase raw name -> {'item_code','name','parsed'}
|
||||||
|
CATALOG_CODES_SET = set() # set of uppercase item codes present in catalog
|
||||||
|
|
||||||
# ---- Tunables ---------------------------------------------------------
|
# ---- Tunables ---------------------------------------------------------
|
||||||
FUZZY_THRESHOLD = 0.85 # minimum spelling similarity for a fuzzy match (0-1)
|
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}
|
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
|
"""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."""
|
the CSV is updated) — just re-run it, no restart needed."""
|
||||||
global DRUG_DATABASE
|
global DRUG_DATABASE, CATALOG_CODES_SET
|
||||||
import pandas as pd
|
import pandas as pd
|
||||||
|
|
||||||
if not os.path.exists(csv_path):
|
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),
|
'parsed': parse_drug_name(name),
|
||||||
}
|
}
|
||||||
DRUG_DATABASE = db
|
DRUG_DATABASE = db
|
||||||
|
CATALOG_CODES_SET = {v['item_code'] for v in db.values()}
|
||||||
logger.info(f"✅ Loaded {len(db)} drugs from {csv_path}")
|
logger.info(f"✅ Loaded {len(db)} drugs from {csv_path}")
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.error(f"❌ Failed to load {csv_path}: {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):
|
def extract_item_code_from_drug_list(drug_description):
|
||||||
"""Return the item_code for a drug, or None if there's no confident match."""
|
"""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:
|
if not drug_description or not DRUG_DATABASE:
|
||||||
return None
|
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'))
|
existing = safe_strip(item.get('item_code'))
|
||||||
if existing:
|
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
|
continue
|
||||||
|
|
||||||
if not use_drug_list:
|
if not use_drug_list:
|
||||||
item['item_code_source'] = 'not_found'
|
item['item_code_source'] = 'not_found'
|
||||||
|
item['in_csv'] = False
|
||||||
continue
|
continue
|
||||||
|
|
||||||
matched = extract_item_code_from_drug_list(item.get('description'))
|
matched = extract_item_code_from_drug_list(item.get('description'))
|
||||||
if matched:
|
if matched:
|
||||||
item['item_code'] = matched
|
item['item_code'] = matched
|
||||||
item['item_code_source'] = 'drug_list_match'
|
item['item_code_source'] = 'drug_list_match'
|
||||||
|
item['in_csv'] = True
|
||||||
else:
|
else:
|
||||||
item['item_code_source'] = 'not_found'
|
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
|
||||||
|
|||||||
@@ -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" }
|
||||||
|
]
|
||||||
|
}
|
||||||
@@ -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"
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
|
||||||
Binary file not shown.
|
After Width: | Height: | Size: 2.4 KiB |
@@ -263,7 +263,13 @@
|
|||||||
<div class="switch-auth">
|
<div class="switch-auth">
|
||||||
<p>Don't have an account? <a href="{{ url_for('signup') }}" class="btn-link">Create Account</a></p>
|
<p>Don't have an account? <a href="{{ url_for('signup') }}" class="btn-link">Create Account</a></p>
|
||||||
<p><a href="{{ url_for('forgot_password') }}" class="btn-link">Forgot Password?</a></p>
|
<p><a href="{{ url_for('forgot_password') }}" class="btn-link">Forgot Password?</a></p>
|
||||||
<p class="security-note"><i class="fas fa-lock"></i> Secured with SSL Encryption</p>
|
<div style="margin-top: 14px; padding-top: 14px; border-top: 1px solid #e5e7eb;">
|
||||||
|
<p style="margin-bottom: 4px; font-size: 0.9rem; color: #4b5563;">Hospital Pharmacy Staff?</p>
|
||||||
|
<a href="{{ url_for('pharmacy_login') }}" style="color: #0284c7; font-weight: 600; text-decoration: none; font-size: 0.95rem;">
|
||||||
|
Sign In via Dedicated Pharmacy Portal →
|
||||||
|
</a>
|
||||||
|
</div>
|
||||||
|
<p class="security-note" style="margin-top: 14px;"><i class="fas fa-lock"></i> Secured with SSL Encryption</p>
|
||||||
</div>
|
</div>
|
||||||
</form>
|
</form>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -0,0 +1,279 @@
|
|||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="en">
|
||||||
|
<head>
|
||||||
|
<meta charset="UTF-8">
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||||
|
<title>Local GRN Records — Test Dashboard</title>
|
||||||
|
<style>
|
||||||
|
:root {
|
||||||
|
--primary: #0284c7;
|
||||||
|
--success: #059669;
|
||||||
|
--danger: #dc2626;
|
||||||
|
--warning: #d97706;
|
||||||
|
--bg: #f8fafc;
|
||||||
|
--surface: #ffffff;
|
||||||
|
--border: #e2e8f0;
|
||||||
|
--text: #0f172a;
|
||||||
|
--muted: #64748b;
|
||||||
|
--radius: 8px;
|
||||||
|
}
|
||||||
|
* { margin: 0; padding: 0; box-sizing: border-box; }
|
||||||
|
body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif; background: var(--bg); color: var(--text); font-size: 14px; }
|
||||||
|
.topbar {
|
||||||
|
background: var(--surface);
|
||||||
|
border-bottom: 1px solid var(--border);
|
||||||
|
padding: 14px 32px;
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: space-between;
|
||||||
|
position: sticky;
|
||||||
|
top: 0;
|
||||||
|
z-index: 100;
|
||||||
|
}
|
||||||
|
.topbar-title { font-size: 16px; font-weight: 700; color: var(--text); display: flex; align-items: center; gap: 10px; }
|
||||||
|
.local-pill {
|
||||||
|
background: #fef9c3;
|
||||||
|
border: 1px solid #fde68a;
|
||||||
|
color: #92400e;
|
||||||
|
font-size: 11px;
|
||||||
|
font-weight: 700;
|
||||||
|
padding: 3px 10px;
|
||||||
|
border-radius: 999px;
|
||||||
|
letter-spacing: 0.5px;
|
||||||
|
text-transform: uppercase;
|
||||||
|
}
|
||||||
|
.back-link { color: var(--primary); text-decoration: none; font-size: 13px; }
|
||||||
|
.back-link:hover { text-decoration: underline; }
|
||||||
|
.container { max-width: 1400px; margin: 0 auto; padding: 32px 24px; }
|
||||||
|
.page-header { margin-bottom: 24px; }
|
||||||
|
.page-header h1 { font-size: 22px; font-weight: 700; margin-bottom: 6px; }
|
||||||
|
.page-header p { color: var(--muted); font-size: 13px; }
|
||||||
|
|
||||||
|
/* Stat Cards */
|
||||||
|
.stats { display: grid; grid-template-columns: repeat(auto-fit, minmax(160px, 1fr)); gap: 16px; margin-bottom: 28px; }
|
||||||
|
.stat-card { background: var(--surface); border: 1px solid var(--border); border-radius: var(--radius); padding: 18px 20px; }
|
||||||
|
.stat-label { font-size: 11px; font-weight: 600; text-transform: uppercase; letter-spacing: 0.5px; color: var(--muted); margin-bottom: 8px; }
|
||||||
|
.stat-value { font-size: 28px; font-weight: 700; }
|
||||||
|
.stat-value.success { color: var(--success); }
|
||||||
|
.stat-value.danger { color: var(--danger); }
|
||||||
|
.stat-value.primary { color: var(--primary); }
|
||||||
|
|
||||||
|
/* Endpoint Info */
|
||||||
|
.endpoint-box {
|
||||||
|
background: #0f172a;
|
||||||
|
color: #e2e8f0;
|
||||||
|
border-radius: var(--radius);
|
||||||
|
padding: 18px 24px;
|
||||||
|
margin-bottom: 28px;
|
||||||
|
font-family: 'Courier New', monospace;
|
||||||
|
font-size: 13px;
|
||||||
|
}
|
||||||
|
.endpoint-box .label { color: #94a3b8; margin-bottom: 8px; font-size: 11px; text-transform: uppercase; letter-spacing: 0.5px; font-family: sans-serif; }
|
||||||
|
.endpoint-box .url { color: #34d399; font-weight: 600; }
|
||||||
|
.endpoint-box .key { color: #fbbf24; }
|
||||||
|
.endpoint-box .sep { color: #475569; margin: 0 8px; }
|
||||||
|
|
||||||
|
/* Table */
|
||||||
|
.table-wrap { background: var(--surface); border: 1px solid var(--border); border-radius: var(--radius); overflow: hidden; }
|
||||||
|
.table-toolbar { padding: 14px 20px; border-bottom: 1px solid var(--border); display: flex; align-items: center; justify-content: space-between; gap: 12px; }
|
||||||
|
.table-toolbar h2 { font-size: 14px; font-weight: 600; }
|
||||||
|
.search-box { padding: 7px 12px; border: 1px solid var(--border); border-radius: 6px; font-size: 13px; width: 240px; outline: none; }
|
||||||
|
.search-box:focus { border-color: var(--primary); }
|
||||||
|
|
||||||
|
table { width: 100%; border-collapse: collapse; }
|
||||||
|
thead th { background: #f1f5f9; font-size: 11px; font-weight: 700; text-transform: uppercase; letter-spacing: 0.4px; color: var(--muted); padding: 10px 14px; text-align: left; white-space: nowrap; border-bottom: 1px solid var(--border); }
|
||||||
|
tbody tr { border-bottom: 1px solid var(--border); transition: background 0.1s; cursor: pointer; }
|
||||||
|
tbody tr:last-child { border-bottom: none; }
|
||||||
|
tbody tr:hover { background: #f8fafc; }
|
||||||
|
tbody td { padding: 10px 14px; font-size: 13px; vertical-align: middle; }
|
||||||
|
.badge { display: inline-block; padding: 2px 8px; border-radius: 999px; font-size: 11px; font-weight: 600; }
|
||||||
|
.badge.success { background: #d1fae5; color: #065f46; }
|
||||||
|
.badge.local { background: #dbeafe; color: #1e40af; }
|
||||||
|
.badge.pending { background: #fef3c7; color: #92400e; }
|
||||||
|
|
||||||
|
/* Modal */
|
||||||
|
.modal-overlay { display: none; position: fixed; inset: 0; background: rgba(0,0,0,0.45); z-index: 1000; align-items: center; justify-content: center; }
|
||||||
|
.modal-overlay.open { display: flex; }
|
||||||
|
.modal { background: var(--surface); border-radius: var(--radius); width: 90%; max-width: 760px; max-height: 85vh; display: flex; flex-direction: column; }
|
||||||
|
.modal-header { padding: 18px 24px; border-bottom: 1px solid var(--border); display: flex; align-items: center; justify-content: space-between; }
|
||||||
|
.modal-header h3 { font-size: 15px; font-weight: 700; }
|
||||||
|
.modal-close { background: none; border: none; font-size: 20px; cursor: pointer; color: var(--muted); line-height: 1; }
|
||||||
|
.modal-body { padding: 20px 24px; overflow-y: auto; }
|
||||||
|
pre { background: #0f172a; color: #e2e8f0; border-radius: 6px; padding: 16px; font-size: 12px; white-space: pre-wrap; word-break: break-all; line-height: 1.6; }
|
||||||
|
|
||||||
|
/* Refresh badge */
|
||||||
|
.refresh-btn { padding: 7px 14px; background: var(--primary); color: white; border: none; border-radius: 6px; font-size: 13px; cursor: pointer; }
|
||||||
|
.refresh-btn:hover { background: #0369a1; }
|
||||||
|
|
||||||
|
.empty { padding: 48px 24px; text-align: center; color: var(--muted); }
|
||||||
|
.empty p { font-size: 15px; margin-bottom: 6px; }
|
||||||
|
.empty small { font-size: 12px; }
|
||||||
|
</style>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<div class="topbar">
|
||||||
|
<div class="topbar-title">
|
||||||
|
GRN Records
|
||||||
|
<span class="local-pill">Local Test</span>
|
||||||
|
</div>
|
||||||
|
<a href="/dashboard" class="back-link">Back to Dashboard</a>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="container">
|
||||||
|
<div class="page-header">
|
||||||
|
<h1>Local GRN Test Records</h1>
|
||||||
|
<p>All GRNs received from your local n8n workflow. These are stored in the <strong>invoice</strong> database, table <strong>grn_records</strong>.</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- Endpoint Info Box -->
|
||||||
|
<div class="endpoint-box">
|
||||||
|
<div class="label">n8n HTTP Node — Point these to your local server</div>
|
||||||
|
<div>
|
||||||
|
<span style="color:#94a3b8">OCR Endpoint :</span>
|
||||||
|
<span class="url">http://localhost:8080/process-invoice</span>
|
||||||
|
<span class="sep">|</span>
|
||||||
|
<span style="color:#94a3b8">Header :</span>
|
||||||
|
<span class="key">x-api-key: 971dcea6c47445f6f7405fa2d14e116b1d81dae6c10330571e8d4220c013b523</span>
|
||||||
|
</div>
|
||||||
|
<div style="margin-top:8px">
|
||||||
|
<span style="color:#94a3b8">GRN Endpoint :</span>
|
||||||
|
<span class="url">http://localhost:8080/dmhApiRef/grn/createGRN.php</span>
|
||||||
|
<span class="sep">|</span>
|
||||||
|
<span style="color:#94a3b8">Header :</span>
|
||||||
|
<span class="key">x-api-key: nirajAi26@DMH</span>
|
||||||
|
</div>
|
||||||
|
<div style="margin-top:8px">
|
||||||
|
<span style="color:#94a3b8">JSON API :</span>
|
||||||
|
<span class="url">GET http://localhost:8080/api/grn/records</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- Stats -->
|
||||||
|
{% set total = records | length %}
|
||||||
|
{% set success_count = records | selectattr('status', 'equalto', 'created') | list | length %}
|
||||||
|
<div class="stats">
|
||||||
|
<div class="stat-card">
|
||||||
|
<div class="stat-label">Total GRNs</div>
|
||||||
|
<div class="stat-value primary">{{ total }}</div>
|
||||||
|
</div>
|
||||||
|
<div class="stat-card">
|
||||||
|
<div class="stat-label">Created</div>
|
||||||
|
<div class="stat-value success">{{ success_count }}</div>
|
||||||
|
</div>
|
||||||
|
<div class="stat-card">
|
||||||
|
<div class="stat-label">Total Items</div>
|
||||||
|
<div class="stat-value primary">{{ records | sum(attribute='items_inserted') }}</div>
|
||||||
|
</div>
|
||||||
|
<div class="stat-card">
|
||||||
|
<div class="stat-label">Unique Sellers</div>
|
||||||
|
<div class="stat-value primary">{{ records | map(attribute='seller_name') | unique | list | length }}</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- Table -->
|
||||||
|
<div class="table-wrap">
|
||||||
|
<div class="table-toolbar">
|
||||||
|
<h2>GRN Records (last 200)</h2>
|
||||||
|
<div style="display:flex;gap:10px;align-items:center">
|
||||||
|
<input type="text" class="search-box" id="searchBox" placeholder="Search GRN, invoice, seller..." oninput="filterTable()">
|
||||||
|
<button class="refresh-btn" onclick="location.reload()">Refresh</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{% if records %}
|
||||||
|
<div style="overflow-x:auto">
|
||||||
|
<table id="grnTable">
|
||||||
|
<thead>
|
||||||
|
<tr>
|
||||||
|
<th>GRN No</th>
|
||||||
|
<th>Invoice Number</th>
|
||||||
|
<th>Invoice ID</th>
|
||||||
|
<th>Seller Name</th>
|
||||||
|
<th>PO Number</th>
|
||||||
|
<th>Amount (₹)</th>
|
||||||
|
<th>Items</th>
|
||||||
|
<th>Source</th>
|
||||||
|
<th>Received At</th>
|
||||||
|
<th>Status</th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody>
|
||||||
|
{% for r in records %}
|
||||||
|
<tr onclick="showDetail({{ r.id }})">
|
||||||
|
<td><strong>{{ r.grn_no }}</strong></td>
|
||||||
|
<td>{{ r.invoice_number or '—' }}</td>
|
||||||
|
<td style="color:var(--muted);font-size:12px">{{ r.invoice_id or '—' }}</td>
|
||||||
|
<td>{{ r.seller_name or '—' }}</td>
|
||||||
|
<td style="font-size:12px">{{ r.po_number or '—' }}</td>
|
||||||
|
<td style="text-align:right"><strong>{{ "%.2f"|format(r.invoice_amount|float) if r.invoice_amount else '0.00' }}</strong></td>
|
||||||
|
<td style="text-align:center">{{ r.items_inserted }}</td>
|
||||||
|
<td><span class="badge local">{{ r.source or 'n8n' }}</span></td>
|
||||||
|
<td style="color:var(--muted);font-size:12px">{{ r.received_at }}</td>
|
||||||
|
<td><span class="badge success">{{ r.status }}</span></td>
|
||||||
|
</tr>
|
||||||
|
{% endfor %}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
{% else %}
|
||||||
|
<div class="empty">
|
||||||
|
<p>No GRN records yet.</p>
|
||||||
|
<small>Run your n8n workflow with the local endpoint to see records appear here.</small>
|
||||||
|
</div>
|
||||||
|
{% endif %}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- Detail Modal -->
|
||||||
|
<div class="modal-overlay" id="detailModal">
|
||||||
|
<div class="modal">
|
||||||
|
<div class="modal-header">
|
||||||
|
<h3 id="modalTitle">GRN Detail</h3>
|
||||||
|
<button class="modal-close" onclick="closeModal()">×</button>
|
||||||
|
</div>
|
||||||
|
<div class="modal-body">
|
||||||
|
<pre id="modalContent">Loading...</pre>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<script>
|
||||||
|
function showDetail(id) {
|
||||||
|
document.getElementById('modalTitle').textContent = 'Loading...';
|
||||||
|
document.getElementById('modalContent').textContent = 'Loading...';
|
||||||
|
document.getElementById('detailModal').classList.add('open');
|
||||||
|
|
||||||
|
fetch('/grn/records/' + id)
|
||||||
|
.then(r => r.json())
|
||||||
|
.then(data => {
|
||||||
|
document.getElementById('modalTitle').textContent = 'GRN: ' + (data.grn_no || 'N/A');
|
||||||
|
document.getElementById('modalContent').textContent = JSON.stringify(data, null, 2);
|
||||||
|
})
|
||||||
|
.catch(e => {
|
||||||
|
document.getElementById('modalContent').textContent = 'Error: ' + e;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function closeModal() {
|
||||||
|
document.getElementById('detailModal').classList.remove('open');
|
||||||
|
}
|
||||||
|
|
||||||
|
document.getElementById('detailModal').addEventListener('click', function(e) {
|
||||||
|
if (e.target === this) closeModal();
|
||||||
|
});
|
||||||
|
|
||||||
|
document.addEventListener('keydown', function(e) {
|
||||||
|
if (e.key === 'Escape') closeModal();
|
||||||
|
});
|
||||||
|
|
||||||
|
function filterTable() {
|
||||||
|
const q = document.getElementById('searchBox').value.toLowerCase();
|
||||||
|
const rows = document.querySelectorAll('#grnTable tbody tr');
|
||||||
|
rows.forEach(row => {
|
||||||
|
row.style.display = row.textContent.toLowerCase().includes(q) ? '' : 'none';
|
||||||
|
});
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
|
|
||||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,239 @@
|
|||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="en">
|
||||||
|
<head>
|
||||||
|
<meta charset="UTF-8">
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||||
|
<title>Pharmacy Staff Login</title>
|
||||||
|
<style>
|
||||||
|
:root {
|
||||||
|
--primary: #0284c7;
|
||||||
|
--primary-hover: #0369a1;
|
||||||
|
--primary-light: #f0f9ff;
|
||||||
|
--primary-border: #bae6fd;
|
||||||
|
--background: #f8fafc;
|
||||||
|
--surface: #ffffff;
|
||||||
|
--border: #e2e8f0;
|
||||||
|
--border-hover: #cbd5e1;
|
||||||
|
--text-primary: #0f172a;
|
||||||
|
--text-secondary: #475569;
|
||||||
|
--text-muted: #94a3b8;
|
||||||
|
--danger: #dc2626;
|
||||||
|
--danger-bg: #fef2f2;
|
||||||
|
--danger-border: #fecaca;
|
||||||
|
--radius-sm: 4px;
|
||||||
|
--radius: 6px;
|
||||||
|
--radius-lg: 8px;
|
||||||
|
--shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.08), 0 2px 4px -2px rgba(0, 0, 0, 0.05);
|
||||||
|
}
|
||||||
|
|
||||||
|
* {
|
||||||
|
margin: 0;
|
||||||
|
padding: 0;
|
||||||
|
box-sizing: border-box;
|
||||||
|
}
|
||||||
|
|
||||||
|
body {
|
||||||
|
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
|
||||||
|
background-color: var(--background);
|
||||||
|
color: var(--text-primary);
|
||||||
|
min-height: 100vh;
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
justify-content: center;
|
||||||
|
align-items: center;
|
||||||
|
padding: 24px 16px;
|
||||||
|
-webkit-font-smoothing: antialiased;
|
||||||
|
}
|
||||||
|
|
||||||
|
.login-card {
|
||||||
|
background-color: var(--surface);
|
||||||
|
border: 1px solid var(--border);
|
||||||
|
border-radius: var(--radius-lg);
|
||||||
|
box-shadow: var(--shadow);
|
||||||
|
width: 100%;
|
||||||
|
max-width: 440px;
|
||||||
|
padding: 36px 32px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.header-section {
|
||||||
|
text-align: center;
|
||||||
|
margin-bottom: 28px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.logo-slot {
|
||||||
|
height: 60px;
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
margin-bottom: 16px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.logo-slot img {
|
||||||
|
max-height: 58px;
|
||||||
|
width: auto;
|
||||||
|
object-fit: contain;
|
||||||
|
}
|
||||||
|
|
||||||
|
.portal-badge {
|
||||||
|
display: inline-block;
|
||||||
|
font-size: 11px;
|
||||||
|
font-weight: 700;
|
||||||
|
letter-spacing: 0.6px;
|
||||||
|
text-transform: uppercase;
|
||||||
|
padding: 4px 10px;
|
||||||
|
background-color: var(--primary-light);
|
||||||
|
color: var(--primary);
|
||||||
|
border: 1px solid var(--primary-border);
|
||||||
|
border-radius: 9999px;
|
||||||
|
margin-bottom: 12px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.portal-title {
|
||||||
|
font-size: 20px;
|
||||||
|
font-weight: 700;
|
||||||
|
color: var(--text-primary);
|
||||||
|
letter-spacing: -0.2px;
|
||||||
|
margin-bottom: 6px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.portal-subtitle {
|
||||||
|
font-size: 13px;
|
||||||
|
color: var(--text-secondary);
|
||||||
|
line-height: 1.4;
|
||||||
|
}
|
||||||
|
|
||||||
|
.form-group {
|
||||||
|
margin-bottom: 18px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.form-label {
|
||||||
|
display: block;
|
||||||
|
font-size: 13px;
|
||||||
|
font-weight: 600;
|
||||||
|
color: var(--text-secondary);
|
||||||
|
margin-bottom: 6px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.form-input {
|
||||||
|
width: 100%;
|
||||||
|
padding: 10px 12px;
|
||||||
|
font-size: 14px;
|
||||||
|
font-family: inherit;
|
||||||
|
color: var(--text-primary);
|
||||||
|
background-color: #ffffff;
|
||||||
|
border: 1px solid var(--border);
|
||||||
|
border-radius: var(--radius);
|
||||||
|
outline: none;
|
||||||
|
transition: all 0.15s ease;
|
||||||
|
}
|
||||||
|
|
||||||
|
.form-input:focus {
|
||||||
|
border-color: var(--primary);
|
||||||
|
box-shadow: 0 0 0 3px rgba(2, 132, 199, 0.15);
|
||||||
|
}
|
||||||
|
|
||||||
|
.btn-submit {
|
||||||
|
width: 100%;
|
||||||
|
padding: 11px 16px;
|
||||||
|
font-size: 14px;
|
||||||
|
font-weight: 600;
|
||||||
|
font-family: inherit;
|
||||||
|
color: #ffffff;
|
||||||
|
background-color: var(--primary);
|
||||||
|
border: 1px solid var(--primary);
|
||||||
|
border-radius: var(--radius);
|
||||||
|
cursor: pointer;
|
||||||
|
transition: background-color 0.15s ease;
|
||||||
|
margin-top: 6px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.btn-submit:hover {
|
||||||
|
background-color: var(--primary-hover);
|
||||||
|
border-color: var(--primary-hover);
|
||||||
|
}
|
||||||
|
|
||||||
|
.btn-submit:active {
|
||||||
|
transform: translateY(1px);
|
||||||
|
}
|
||||||
|
|
||||||
|
.alert-error {
|
||||||
|
background-color: var(--danger-bg);
|
||||||
|
border: 1px solid var(--danger-border);
|
||||||
|
color: var(--danger);
|
||||||
|
padding: 10px 12px;
|
||||||
|
border-radius: var(--radius);
|
||||||
|
font-size: 13px;
|
||||||
|
margin-bottom: 20px;
|
||||||
|
line-height: 1.4;
|
||||||
|
}
|
||||||
|
|
||||||
|
.footer-note {
|
||||||
|
margin-top: 24px;
|
||||||
|
padding-top: 18px;
|
||||||
|
border-top: 1px solid var(--border);
|
||||||
|
text-align: center;
|
||||||
|
font-size: 12px;
|
||||||
|
color: var(--text-muted);
|
||||||
|
line-height: 1.5;
|
||||||
|
}
|
||||||
|
|
||||||
|
.footer-note strong {
|
||||||
|
color: var(--text-secondary);
|
||||||
|
}
|
||||||
|
|
||||||
|
.back-link {
|
||||||
|
display: block;
|
||||||
|
margin-top: 10px;
|
||||||
|
color: var(--primary);
|
||||||
|
text-decoration: none;
|
||||||
|
font-size: 12px;
|
||||||
|
font-weight: 500;
|
||||||
|
}
|
||||||
|
|
||||||
|
.back-link:hover {
|
||||||
|
text-decoration: underline;
|
||||||
|
}
|
||||||
|
</style>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<div class="login-card">
|
||||||
|
<div class="header-section">
|
||||||
|
<div class="logo-slot">
|
||||||
|
<img src="/static/logo.png" alt="Hospital Logo" onerror="this.src='/static/logos/logo.png';">
|
||||||
|
</div>
|
||||||
|
<span class="portal-badge">Pharmacy Department</span>
|
||||||
|
<h1 class="portal-title">Item-Code Approval Portal</h1>
|
||||||
|
<p class="portal-subtitle">Dedicated authentication for pharmacy personnel to review and verify invoice drug item codes.</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{% with messages = get_flashed_messages(with_categories=true) %}
|
||||||
|
{% if messages %}
|
||||||
|
{% for category, message in messages %}
|
||||||
|
<div class="alert-error">{{ message }}</div>
|
||||||
|
{% endfor %}
|
||||||
|
{% endif %}
|
||||||
|
{% endwith %}
|
||||||
|
|
||||||
|
<form action="/pharmacy/login" method="POST">
|
||||||
|
<div class="form-group">
|
||||||
|
<label for="username" class="form-label">Staff Username</label>
|
||||||
|
<input type="text" id="username" name="username" class="form-input" placeholder="e.g. pharmacy" required autocomplete="username" autofocus>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="form-group">
|
||||||
|
<label for="password" class="form-label">Password</label>
|
||||||
|
<input type="password" id="password" name="password" class="form-input" placeholder="••••••••" required autocomplete="current-password">
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<button type="submit" class="btn-submit">Sign In to Pharmacy Portal</button>
|
||||||
|
</form>
|
||||||
|
|
||||||
|
<div class="footer-note">
|
||||||
|
<strong>Restricted Access</strong><br>
|
||||||
|
This portal is restricted to authorized pharmacy staff with approval privileges. Invoice extraction and billing users must use the standard portal.
|
||||||
|
<a href="/login" class="back-link">Go to Standard Billing Login</a>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
|
|
||||||
File diff suppressed because it is too large
Load Diff
+354
@@ -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()
|
||||||
@@ -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)
|
||||||
|
|
||||||
Reference in New Issue
Block a user