"""Bounded quote matching and Decimal arithmetic, independent of Flask/models.""" from decimal import Decimal, ROUND_HALF_UP import re from .pricing import parse_shipping_intent, detect_dim_unit, dims_to_cm, shipping_region US = re.compile(r'美国|美西|美中|美东|洛杉矶|纽约|芝加哥|休斯顿|萨凡纳|' r'(? (charge or Decimal(12)): continue if key not in groups or Decimal(rate['min_weight']) > Decimal(groups[key]['min_weight']): groups[key] = rate return list(groups.values()) def number(value, places=2): return format(Decimal(value).quantize(Decimal(10)**-places, rounding=ROUND_HALF_UP), 'f').rstrip('0').rstrip('.') if places else str(value) def render_rates(intent, book, destinations, remote_fees): lines = [] if intent['weight']: lines.append(f"美国 {number(intent['weight'])}KG 基础运费:") else: lines.append('美国线路报价:') for destination, fees in zip(destinations, remote_fees): rates = match_rates(intent, book, destination) if not rates: lines.append(f"{destination['label']}:当前资料没有匹配的线路价格,提供目的仓码或邮编可继续查询。") continue if destination['label'] != '美国': lines.append(destination['label']+':') grouped = {} for rate in rates: key = (rate['service'], rate['origin'], rate['unit'], rate['tax']) grouped.setdefault(key, []).append(rate) for (service, origin, unit, tax), rows in grouped.items(): parts = [] for rate in rows: amount = quantity(intent,rate) price = Decimal(rate['price']) rate_text = f"{rate['zone']} " if rate['zone'] and not destination['zone'] else '' rate_text += f"{number(price)}元/{'KG' if unit == 'kg' else 'CBM'}" if amount is not None: total = amount*price if fees and fees['fee'] is not None and rate['kind'] == 'parcel': total += amount*Decimal(fees['fee']) rate_text += f",{number(amount,3)}{'KG' if unit == 'kg' else 'CBM'} = {number(total)}元" parts.append(rate_text) eta = re.sub(r'\s*无时效赔偿', '', rows[0]['eta']).strip() lines.append(f"- {service} · {origin} · {'包税' if tax=='included' else '不包税'}:"+';'.join(parts) + (f'({eta})' if eta else '')) if fees: if fees['fee'] is None: lines.append('该邮编属于遥远地址,派送附加费需单独确认。') else: lines.append(f"海派已计入偏远附加费 {number(fees['fee'])}元/KG。") if not any(intent.get(key) for key in ('warehouse','postal')): lines.append('发我目的仓码或邮编,可继续匹配到仓线路。') if not intent['weight'] and not intent['cbm'] and not intent['dims']: lines.append('货物多少公斤、几箱?') elif not intent['boxes'] or not intent['dims']: lines.append('请补充箱数、每箱重量和尺寸,继续核算计费重及超重超尺寸费用。') return '\n'.join(lines)