365 lines
14 KiB
Python
365 lines
14 KiB
Python
"""
|
|
Free Item Splitter - Splits items with free quantities into separate records
|
|
"""
|
|
|
|
from typing import List, Dict, Any, Optional, Tuple
|
|
import copy
|
|
import re
|
|
|
|
try:
|
|
from langsmith import traceable
|
|
except ImportError:
|
|
def traceable(*args, **kwargs):
|
|
def decorator(fn):
|
|
return fn
|
|
return decorator
|
|
|
|
|
|
def _to_float(val: Any) -> Optional[float]:
|
|
"""Safely convert any value (int, float, string like '2', '2.0', ' 2 ') to float."""
|
|
if val is None:
|
|
return None
|
|
if isinstance(val, (int, float)):
|
|
return float(val)
|
|
try:
|
|
cleaned = re.sub(r'[^\d.]', '', str(val)).strip()
|
|
return float(cleaned) if cleaned else None
|
|
except (ValueError, TypeError):
|
|
return None
|
|
|
|
|
|
def _format_qty(val: Any) -> Any:
|
|
"""Format quantity: integer if whole number (e.g. 20 instead of 20.0), else float."""
|
|
if val is None:
|
|
return 0
|
|
if isinstance(val, (int, float)):
|
|
if float(val).is_integer():
|
|
return int(val)
|
|
return round(float(val), 2)
|
|
num = _to_float(val)
|
|
if num is not None:
|
|
if num.is_integer():
|
|
return int(num)
|
|
return round(num, 2)
|
|
return val
|
|
|
|
|
|
def _parse_plus_qty(qty_val: Any) -> Optional[Tuple[float, float]]:
|
|
"""Parse '20+2' or '20 + 2' into (paid=20.0, free=2.0)."""
|
|
if not qty_val:
|
|
return None
|
|
s = str(qty_val).strip()
|
|
if '+' not in s:
|
|
return None
|
|
parts = s.split('+')
|
|
if len(parts) >= 2:
|
|
# OCR common letter replacements in numbers
|
|
p1 = parts[0].strip().replace('S', '5').replace('s', '5').replace('O', '0').replace('o', '0')
|
|
p2 = parts[1].strip().replace('S', '5').replace('s', '5').replace('O', '0').replace('o', '0')
|
|
n1 = _to_float(p1)
|
|
n2 = _to_float(p2)
|
|
if n1 is not None and n2 is not None:
|
|
return n1, n2
|
|
return None
|
|
|
|
|
|
def _extract_free_from_description(desc: str) -> Optional[Tuple[Optional[float], float]]:
|
|
"""
|
|
Check if description contains free patterns like:
|
|
- '10+1 FREE' or '10+2 SCHEME' or '(10+1)'
|
|
- 'FREE: 2' or 'FREE QTY: 2' or '2 FREE'
|
|
- 'SCHEME 10+1' or 'BONUS: 1'
|
|
Returns (paid_qty_from_desc, free_qty) or None.
|
|
Never triggers on medicine dosage/composition like '500+125 MG'.
|
|
"""
|
|
if not desc or not isinstance(desc, str):
|
|
return None
|
|
|
|
# Skip dosage/strength expressions like 500+125 MG, 325 + 37.5 MG, 5% + 0.9%
|
|
if re.search(r'\d+\s*\+\s*\d+\s*(?:mg|ml|gm|mcg|%|iu|tab|cap|vial|pcs)\b', desc, re.IGNORECASE):
|
|
return None
|
|
|
|
# Pattern: 10+1 FREE or 10+2 SCHEME or 10+1 BONUS
|
|
m_plus_explicit = re.search(
|
|
r'\(?\s*(\d+(?:\.\d+)?)\s*\+\s*(\d+(?:\.\d+)?)\s*(?:FREE|SCHEME|SCH|BONUS|OFFER)\b\)?',
|
|
desc,
|
|
re.IGNORECASE
|
|
)
|
|
if m_plus_explicit:
|
|
p1 = _to_float(m_plus_explicit.group(1))
|
|
p2 = _to_float(m_plus_explicit.group(2))
|
|
if p1 is not None and p2 is not None and p2 > 0:
|
|
return p1, p2
|
|
|
|
# Pattern in brackets: e.g. (10+1) or (20+2) without dosage units
|
|
m_plus_bracket = re.search(r'\(\s*(\d+(?:\.\d+)?)\s*\+\s*(\d+(?:\.\d+)?)\s*\)', desc, re.IGNORECASE)
|
|
if m_plus_bracket:
|
|
p1 = _to_float(m_plus_bracket.group(1))
|
|
p2 = _to_float(m_plus_bracket.group(2))
|
|
if p1 is not None and p2 is not None and p2 > 0:
|
|
return p1, p2
|
|
|
|
# Pattern: FREE: 2 or FREE QTY: 2 or SCHEME: 1
|
|
m_free = re.search(r'(?:FREE|SCHEME|BONUS|F\.?QTY|DISC\.?\s*QTY)[:\s=-]+(\d+(?:\.\d+)?)\b', desc, re.IGNORECASE)
|
|
if m_free:
|
|
f_qty = _to_float(m_free.group(1))
|
|
if f_qty is not None and f_qty > 0:
|
|
return None, f_qty
|
|
|
|
# Pattern: 2 FREE or 1 FREE
|
|
m_trail = re.search(r'(?:^|[\s(,])(\d+(?:\.\d+)?)\s*(?:FREE|SCHEME|BONUS)\b', desc, re.IGNORECASE)
|
|
if m_trail:
|
|
f_qty = _to_float(m_trail.group(1))
|
|
if f_qty is not None and f_qty > 0:
|
|
return None, f_qty
|
|
|
|
return None
|
|
|
|
|
|
def _extract_free_quantity(item: Dict[str, Any]) -> Optional[float]:
|
|
"""Extract free quantity from any known free/scheme/bonus field."""
|
|
for k in (
|
|
'free_quantity', 'free_qty', 'free', 'Free', 'FREE',
|
|
'scheme_qty', 'scheme_quantity', 'disc_qty', 'discount_qty',
|
|
'bonus_qty', 'bonus', 'f_qty', 'f_quantity'
|
|
):
|
|
v = item.get(k)
|
|
if v is not None:
|
|
f = _to_float(v)
|
|
if f is not None and f > 0:
|
|
return f
|
|
return None
|
|
|
|
|
|
def create_item_record(base_item: Dict[str, Any], new_qty: Any, is_free: bool) -> Dict[str, Any]:
|
|
"""
|
|
Create an item record (paid or free).
|
|
ALL DATA SAME as base item, except:
|
|
- quantity = new_qty (formatted as int if whole number)
|
|
- free_item = 1 if is_free else 0
|
|
- free_item_yn = "1" if is_free else "0"
|
|
"""
|
|
new_item = copy.deepcopy(base_item)
|
|
new_item['quantity'] = _format_qty(new_qty)
|
|
new_item['free_item'] = 1 if is_free else 0
|
|
new_item['free_item_yn'] = "1" if is_free else "0"
|
|
for k in (
|
|
'free_quantity', 'free_qty', 'free', 'Free', 'FREE',
|
|
'scheme_qty', 'scheme_quantity', 'disc_qty', 'discount_qty',
|
|
'bonus_qty', 'bonus', 'f_qty', 'f_quantity'
|
|
):
|
|
new_item.pop(k, None)
|
|
return new_item
|
|
|
|
|
|
# Backward-compatible alias
|
|
create_proportional_item = create_item_record
|
|
|
|
|
|
@traceable(name="split_free_items", tags=["items", "splitting"])
|
|
def split_free_items(data: Dict[str, Any]) -> Dict[str, Any]:
|
|
"""
|
|
Apply free item splitting and non-repeatable conditions:
|
|
1. When free item is mentioned:
|
|
Show repeated:
|
|
- Paid item: quantity=paid_qty, free_item=0, free_item_yn="0"
|
|
- Free item: quantity=free_qty mentioned (or 1), free_item=1, free_item_yn="1"
|
|
and all other fields EXACTLY as they are from the item above!
|
|
2. When free item is not mentioned:
|
|
- Exactly ONE record: free_item=0, free_item_yn="0"
|
|
- That item CANNOT be repeatable (strictly deduplicated and never repeated).
|
|
"""
|
|
items = data.get('items', [])
|
|
if not items:
|
|
return data
|
|
|
|
def _norm_desc(d: Any) -> str:
|
|
return re.sub(r'[^a-z0-9]', '', str(d or '').lower())
|
|
|
|
def _is_empty(v: Any) -> bool:
|
|
if v is None:
|
|
return True
|
|
return str(v).strip().lower() in ('', 'none', 'null', 'n/a', '?', '-', 'undefined')
|
|
|
|
def _is_free_flagged(it: Dict[str, Any]) -> bool:
|
|
return str(it.get('free_item_yn')) == "1" or str(it.get('free_item')) == "1"
|
|
|
|
# ── PRE-PASS: Merge two-row free item format ──────────────────────────────
|
|
merged_items = []
|
|
skip_next = False
|
|
|
|
for i, item in enumerate(items):
|
|
if skip_next:
|
|
skip_next = False
|
|
continue
|
|
|
|
qty = item.get('quantity')
|
|
qty_num = _to_float(qty) if not (isinstance(qty, str) and '+' in str(qty)) else None
|
|
is_zero_qty = (qty_num is not None and qty_num == 0)
|
|
is_free_flag = _is_free_flagged(item)
|
|
|
|
if is_zero_qty and is_free_flag and i + 1 < len(items):
|
|
next_item = items[i + 1]
|
|
next_desc = _norm_desc(next_item.get('description'))
|
|
this_desc = _norm_desc(item.get('description'))
|
|
|
|
if next_desc and this_desc and next_desc == this_desc:
|
|
next_qty_num = _to_float(next_item.get('quantity'))
|
|
if next_qty_num and next_qty_num > 0:
|
|
free_qty_value = _extract_free_quantity(item) or _to_float(item.get('quantity'))
|
|
if not free_qty_value or free_qty_value <= 0:
|
|
skip_next = False
|
|
continue
|
|
merged = copy.deepcopy(next_item)
|
|
merged['free_quantity'] = free_qty_value
|
|
merged['free_item'] = 1
|
|
merged['free_item_yn'] = "1"
|
|
merged_items.append(merged)
|
|
skip_next = True
|
|
continue
|
|
|
|
# Drop standalone zero-quantity ghost records (qty=0, no free_quantity and not free)
|
|
if is_zero_qty and not _extract_free_quantity(item) and not is_free_flag:
|
|
continue
|
|
|
|
merged_items.append(item)
|
|
|
|
items = merged_items
|
|
|
|
# ── SPLIT PASS: Free item mentioned repeats with free_item=1 and fields as above ──
|
|
new_items: List[Dict[str, Any]] = []
|
|
|
|
for item in items:
|
|
qty_raw = item.get('quantity')
|
|
free_qty_num = _extract_free_quantity(item)
|
|
desc = item.get('description') or ''
|
|
is_free_flag = _is_free_flagged(item)
|
|
|
|
# Case 1: "20+2" format in quantity column
|
|
plus_parsed = _parse_plus_qty(qty_raw)
|
|
if plus_parsed:
|
|
paid_q, free_q = plus_parsed
|
|
if free_q > 0:
|
|
paid_item = create_item_record(item, paid_q, is_free=False)
|
|
free_item = create_item_record(paid_item, free_q, is_free=True)
|
|
new_items.append(paid_item)
|
|
new_items.append(free_item)
|
|
continue
|
|
else:
|
|
paid_item = create_item_record(item, paid_q, is_free=False)
|
|
new_items.append(paid_item)
|
|
continue
|
|
|
|
# Case 2: Separate free quantity column (e.g. quantity=20, free_quantity=2)
|
|
if free_qty_num is not None and free_qty_num > 0:
|
|
paid_qty_num = _to_float(qty_raw)
|
|
if paid_qty_num is None:
|
|
paid_qty_num = 0
|
|
paid_item = create_item_record(item, paid_qty_num, is_free=False)
|
|
free_item = create_item_record(paid_item, free_qty_num, is_free=True)
|
|
new_items.append(paid_item)
|
|
new_items.append(free_item)
|
|
continue
|
|
|
|
# Case 3: Free quantity mentioned in description (e.g. "DOLO 650 (10+1 FREE)")
|
|
desc_parsed = _extract_free_from_description(desc)
|
|
if desc_parsed:
|
|
d_paid, d_free = desc_parsed
|
|
if d_free > 0:
|
|
cur_qty = _to_float(qty_raw) or 0
|
|
paid_q = d_paid if d_paid is not None else cur_qty
|
|
paid_item = create_item_record(item, paid_q, is_free=False)
|
|
free_item = create_item_record(paid_item, d_free, is_free=True)
|
|
new_items.append(paid_item)
|
|
new_items.append(free_item)
|
|
continue
|
|
|
|
# Case 4: Free item flagged (free_item=1 or free_item_yn="1")
|
|
if is_free_flag:
|
|
# Look for previous matching item above to copy all fields verbatim
|
|
prev_match = None
|
|
curr_norm = _norm_desc(desc)
|
|
if curr_norm and new_items:
|
|
for prev_it in reversed(new_items):
|
|
if _norm_desc(prev_it.get('description')) == curr_norm:
|
|
prev_match = prev_it
|
|
break
|
|
|
|
free_q = free_qty_num or _to_float(qty_raw) or 1
|
|
if prev_match:
|
|
# Copy all fields as it is above which item is mentioned free item
|
|
free_item = create_item_record(prev_match, free_q, is_free=True)
|
|
new_items.append(free_item)
|
|
else:
|
|
# Standalone free item row
|
|
free_item = create_item_record(item, free_q, is_free=True)
|
|
new_items.append(free_item)
|
|
continue
|
|
|
|
# Case 5: Standard item (NO free item mentioned)
|
|
item_copy = create_item_record(item, qty_raw, is_free=False)
|
|
new_items.append(item_copy)
|
|
|
|
# ── PRESERVE ALL ITEMS (allow multiple items with same item_code / description) ──
|
|
final_items: List[Dict[str, Any]] = []
|
|
seen_exact_clones: set = set()
|
|
|
|
for it in new_items:
|
|
is_free = (it.get('free_item') == 1 or str(it.get('free_item_yn')) == "1")
|
|
|
|
if is_free:
|
|
# Free items are always preserved
|
|
final_items.append(it)
|
|
continue
|
|
|
|
# Multiple items with the SAME item code (e.g. 2 batches, different quantities,
|
|
# or separate rows of the same code) MUST ALL be kept on the JSON!
|
|
code = str(it.get('item_code') or '').strip().upper()
|
|
if code:
|
|
final_items.append(it)
|
|
continue
|
|
|
|
# For items without an item_code, only drop if it is an exact 100% clone
|
|
desc_norm = _norm_desc(it.get('description'))
|
|
batch = str(it.get('Batch') or '').strip().upper()
|
|
qty = str(it.get('quantity') or '').strip()
|
|
price = str(it.get('unit_price') or '').strip()
|
|
total = str(it.get('total_price') or '').strip()
|
|
|
|
clone_key = (desc_norm, batch, qty, price, total)
|
|
if desc_norm and clone_key in seen_exact_clones:
|
|
print(f"[FREE-SPLIT] Exact duplicate clone skipped: {it.get('description')!r} (Batch={batch})")
|
|
continue
|
|
|
|
seen_exact_clones.add(clone_key)
|
|
final_items.append(it)
|
|
|
|
data['items'] = final_items
|
|
return data
|
|
|
|
|
|
def get_free_item_stats(data: Dict[str, Any], total_before: Optional[int] = None) -> Dict[str, Any]:
|
|
"""
|
|
Get statistics about free items in the invoice.
|
|
|
|
Returns:
|
|
Dict with free item counts and details (including total_items_before/after)
|
|
"""
|
|
items = data.get('items', [])
|
|
total_items = len(items)
|
|
free_items = [
|
|
item for item in items
|
|
if str(item.get('free_item_yn')) == "1" or str(item.get('free_item')) == "1"
|
|
]
|
|
free_count = len(free_items)
|
|
paid_count = total_items - free_count
|
|
|
|
return {
|
|
'total_items': total_items,
|
|
'total_items_before': total_before if total_before is not None else paid_count,
|
|
'total_items_after': total_items,
|
|
'paid_items': paid_count,
|
|
'free_items': free_count,
|
|
'has_free_items': free_count > 0
|
|
}
|