"""家庭支付核对的十一组构造输入;金额均为整数分,显示元时保留两位。 仅用标准库,不联网、不读取项目文件;复制到空目录也可直接运行。 本模型是教学核算,不是银行去重、合同解释或身份识别服务。 """ from pathlib import Path from fractions import Fraction import json def yuan(cents): return f'{cents // 100}.{cents % 100:02d}' if cents >= 0 else '-' + yuan(-cents) def observation_graph(rows, verified): groups, pending = {}, [] for row in rows: key = row['hard_id'] if not key or row['account_ref'] not in verified: pending.append(row['source_row']) continue groups.setdefault(key, []).append(row) events, conflicts = [], [] for key, items in sorted(groups.items()): if len({(r['cents'], verified[r['account_ref']]) for r in items}) != 1: conflicts.append(key) continue events.append({'hard_id': key, 'event': 'E-' + key, 'account': verified[items[0]['account_ref']], 'cents': items[0]['cents'], 'observations': [r['source_row'] for r in items]}) return {'events': events, 'pending': pending, 'conflicts': conflicts, 'confirmed_consumption_cents': sum(e['cents'] for e in events), 'raw_observation_sum_cents': sum(r['cents'] for r in rows)} def split_tender(price, coupon, legs, opening): closing = {k: opening[k] - v for k, v in legs.items()} cash = sum(v for k, v in legs.items() if k != 'bonus') return {'price_cents': price, 'coupon_cents': coupon, 'cash_paid_cents': cash, 'bonus_used_cents': legs.get('bonus', 0), 'settled_cents': sum(legs.values()), 'closing': closing, 'residual_cents': price - coupon - sum(legs.values())} def clearing(orders, batches, matrix): rows = [] for o in orders: paid = sum(matrix[o['id']]) due = 0 if o['cancelled'] else o['cents'] rows.append({'order': o['id'], 'listed_cents': o['cents'], 'due_cents': due, 'payments': matrix[o['id']], 'paid_cents': paid, 'balance_cents': due-paid, 'status': '已取消' if o['cancelled'] else ('已结清' if paid == due else '未付清')}) cols = [{'batch': b['id'], 'actual_cents': b['cents'], 'allocated_cents': sum(matrix[o['id']][j] for o in orders), 'residual_cents': b['cents']-sum(matrix[o['id']][j] for o in orders)} for j, b in enumerate(batches)] return {'rows': rows, 'columns': cols} def allocate(items, discount): total = sum(i['cents'] for i in items) quotas = [Fraction(discount*i['cents'], total) for i in items] floors = [q.numerator//q.denominator for q in quotas] remainders = [q-f for q, f in zip(quotas, floors)] left = discount-sum(floors) priority = sorted(range(len(items)), key=lambda j: (-remainders[j], items[j]['id'])) extras = set(priority[:left]) rows = [{'item': i['id'], 'category': i['category'], 'price_cents': i['cents'], 'quota_cents_fraction': str(quotas[j]), 'floor_cents': floors[j], 'remainder_fraction': str(remainders[j]), 'extra_cent': int(j in extras), 'discount_cents': floors[j]+int(j in extras), 'net_cents': i['cents']-floors[j]-int(j in extras)} for j, i in enumerate(items)] categories = {} for r in rows: categories[r['category']] = categories.get(r['category'], 0)+r['net_cents'] return {'rows': rows, 'remaining_cents': left, 'priority': [items[j]['id'] for j in priority], 'categories_cents': categories, 'net_total_cents': sum(r['net_cents'] for r in rows)} def refund(items, returned, give_coupon): rows = [] for i in items: returned_item = i['id'] in returned cash = i['price_cents']-i['discount_cents'] if returned_item else 0 coupon = i['discount_cents'] if returned_item and give_coupon else 0 rows.append(dict(i, returned=returned_item, cash_refund_cents=cash, coupon_return_cents=coupon, retained_cash_cost_cents=0 if returned_item else i['price_cents']-i['discount_cents'])) original = sum(i['price_cents']-i['discount_cents'] for i in items) cash_back = sum(r['cash_refund_cents'] for r in rows) return {'rows': rows, 'cash_refund_cents': cash_back, 'coupon_return_cents': sum(r['coupon_return_cents'] for r in rows), 'remaining_cash_cost_cents': original-cash_back, 'wrong_price_refund_excess_cents': sum(i['discount_cents'] for i in items if i['id'] in returned)} def authorization(opening, events): book, holds, rows = opening, {}, [] rows.append({'event': '期初', 'book_cents': book, 'hold_cents': 0, 'available_cents': book}) for e in events: kind, key, value = e['kind'], e['id'], e['cents'] if kind == 'hold': holds[key] = holds.get(key, 0)+value elif kind == 'capture': if value > holds.get(key, 0): raise ValueError('捕获不能超过该笔剩余冻结') book -= value holds[key] -= value elif kind == 'release': if value > holds.get(key, 0): raise ValueError('释放不能超过该笔剩余冻结') holds[key] -= value else: raise ValueError('未知状态') frozen = sum(holds.values()) rows.append({'event': e['label'], 'book_cents': book, 'hold_cents': frozen, 'available_cents': book-frozen}) return rows def cashback(price, reward, steps): cash_back = confirmed = 0 rows = [] for s in steps: if s == '确认': confirmed = reward elif s == '到账': if not confirmed: raise ValueError('本构造要求先确认后到账') cash_back = reward rows.append({'step': s, 'confirmed_cents': confirmed, 'received_cents': cash_back, 'receivable_cents': confirmed-cash_back, 'cash_net_out_cents': price-cash_back, 'confirmed_net_cost_cents': price-confirmed, 'net_cost_view_expense_cents': price-confirmed, 'separate_view_expense_cents': price, 'separate_view_incentive_cents': confirmed, 'cash_change_cents': -price+cash_back}) return rows def wallet(paid, bonus, uses, bonus_first): p, b, rows = paid, bonus, [] for use in uses: if use > p+b: raise ValueError('消费超过剩余权益') if bonus_first: ub = min(b, use); up = use-ub else: up = min(p, use); ub = use-up p -= up; b -= ub rows.append({'use_cents': use, 'paid_used_cents': up, 'bonus_used_cents': ub, 'paid_balance_cents': p, 'bonus_balance_cents': b, 'display_balance_cents': p+b, 'accumulated_paid_cost_cents': paid-p}) return rows def points(opening, earned, redeemed, expired, per_yuan, price, cap_percent=20): if redeemed % per_yuan: raise ValueError('仅支持整元兑换单位') balance = opening+earned-redeemed-expired if balance < 0: raise ValueError('积分不足') discount = redeemed//per_yuan*100 if discount > price: raise ValueError('抵扣超过订单') if discount*100 > price*cap_percent: raise ValueError('抵扣超过构造上限') states = [opening, opening+earned, opening+earned-redeemed, balance] return {'point_states': states, 'closing_points': balance, 'discount_cents': discount, 'cash_paid_cents': price-discount, 'order_cents': price, 'quantity_residual': opening+earned-redeemed-expired-balance} def evidence_candidates(receipts, statements, aliases): rows = [] for r in receipts: candidates, rejected = [], [] for s in statements: basic = r['date'] == s['date'] and r['cents'] == s['cents'] identity = (r['store'], r['branch'], s['merchant'], s['terminal']) in aliases if basic and identity: candidates.append(s['row']) elif basic: rejected.append(s['row']) status = '唯一支持' if len(candidates) == 1 else ('多候选冲突' if candidates else '证据不足') rows.append({'receipt': r['row'], 'candidates': candidates, 'same_amount_date_without_alias': rejected, 'status': status, 'action': '保留原行,人工核实,不合并'}) for row in rows: row['shared_claim_conflict'] = sorted({other['receipt'] for other in rows if other is not row and set(row['candidates']) & set(other['candidates'])}) return rows def installment(principal, scheduled, fee, events): unbilled, billed, fee_due, cash, rows = principal, 0, 0, 0, [] for e in events: if e['kind'] == 'bill': unbilled -= scheduled; billed += scheduled; fee_due += fee elif e['kind'] == 'pay': if e['principal_cents'] > billed or e['fee_cents'] > fee_due: raise ValueError('还款超过本构造已出账余额') billed -= e['principal_cents']; fee_due -= e['fee_cents'] cash += e['principal_cents']+e['fee_cents'] rows.append({'date': e['date'], 'event': e['kind'], 'billed_principal_cents': billed, 'unbilled_principal_cents': unbilled, 'total_principal_cents': billed+unbilled, 'billed_fee_due_cents': fee_due, 'cumulative_cash_paid_cents': cash, 'statement_due_cents': billed+fee_due}) return rows def build(): out = {} obs = [dict(source_row=s, hard_id=i, account_ref=a, cents=c) for s, i, a, c in [('pay.csv:2','T101','pay-card-A',6800), ('bank.csv:8','T101','bank-A',6800), ('pay-copy.csv:2','T101','pay-card-A',6800), ('pay.csv:3','T102','pay-card-A',6800), ('bank.csv:9','T102','bank-A',6800), ('bank.csv:10','','bank-A',6800)]] refs = {'pay-card-A':'本人储蓄卡A', 'bank-A':'本人储蓄卡A'} altered = [dict(r) for r in obs]; altered[1]['cents'] += 100 out['DJ4-089'] = {'input': {'money_unit':'整数分','date':'2026-11-02','observations':obs,'verified_refs':refs}, 'output': observation_graph(obs, refs), 'contrast': observation_graph(altered, refs)} legs = {'wallet_paid':7000,'bank':16000,'bonus':2000} opening = {'wallet_paid':10000,'bank':50000,'bonus':3000} out['DJ4-090'] = {'input':{'price_cents':30000,'coupon_cents':5000,'legs':legs,'opening':opening}, 'output':split_tender(30000,5000,legs,opening), 'contrast':split_tender(30000,5000,{'wallet_paid':9000,'bank':16000,'bonus':0},opening)} orders = [{'id':'A','cents':12000,'cancelled':False}, {'id':'B','cents':8000,'cancelled':False}, {'id':'C','cents':5000,'cancelled':False}, {'id':'D','cents':4000,'cancelled':False}, {'id':'E','cents':6000,'cancelled':True}] batches = [{'id':'P1','cents':25000}, {'id':'P2','cents':1500}] matrix = {'A':[12000,0],'B':[8000,0],'C':[5000,0],'D':[0,1500],'E':[0,0]} bad = {k:list(v) for k,v in matrix.items()}; bad['C'][0]=0 out['DJ4-091'] = {'input':{'orders':orders,'batches':batches,'matrix':matrix}, 'output':clearing(orders,batches,matrix),'contrast':clearing(orders,batches,bad)} items = [{'id':'A','category':'食品','cents':1000}, {'id':'B','category':'日用','cents':1000}, {'id':'C','category':'食品','cents':1000}] out['DJ4-092'] = {'input':{'items':items,'discount_cents':100,'tie_break':'余数降序,商品ID升序'}, 'output':allocate(items,100),'contrast':allocate(items,101)} ref_items = [{'id':'R1','price_cents':12000,'discount_cents':2400}, {'id':'R2','price_cents':8000,'discount_cents':1600}] out['DJ4-093'] = {'input':{'items':ref_items,'returned':['R1'],'coupon_returns':True}, 'output':refund(ref_items,['R1'],True), 'contrast':refund(ref_items,['R1'],False)} events = [dict(kind=k,id=i,cents=c,label=l) for k,i,c,l in [('hold','H1',150000,'11月1日冻结H1'),('capture','H1',90000,'11月3日捕获900'), ('release','H1',60000,'11月4日释放H1余量'),('hold','H2',40000,'11月5日冻结H2'), ('release','H2',40000,'11月6日撤销H2')]] delayed = [dict(e) for e in events if e['label'] != '11月4日释放H1余量'] out['DJ4-094'] = {'input':{'opening_cents':500000,'events':events,'capture_reduces_hold':True}, 'output':authorization(500000,events),'contrast':authorization(500000,delayed)} out['DJ4-095'] = {'input':{'price_cents':50000,'reward_cents':3000,'steps':['购买','确认','到账'], 'step_dates':['2026-11-08','2026-11-12','2026-11-15'], 'confirmed_irrevocable':True}, 'output':cashback(50000,3000,['购买','确认','到账']), 'contrast':cashback(50000,3000,['购买'])} out['DJ4-096'] = {'input':{'paid_cents':10000,'bonus_cents':2000,'uses_cents':[1500,4500]}, 'output':wallet(10000,2000,[1500,4500],True), 'contrast':wallet(10000,2000,[1500,4500],False)} out['DJ4-097'] = {'input':{'opening_points':1200,'earned_points':300,'redeemed_points':800, 'expired_points':100,'points_per_yuan':100,'price_cents':5800}, 'output':points(1200,300,800,100,100,5800), 'contrast':points(1200,300,800,100,200,5800)} receipts = [dict(row=i,store=s,branch=b,date=d,cents=c) for i,s,b,d,c in [('R1','青禾','东店','2026-11-01',2800),('R2','小林','南店','2026-11-02',3600), ('R3','青禾','西店','2026-11-01',2800),('R4','未知店','无','2026-11-03',4900)]] statements = [dict(row=i,merchant=m,terminal=t,date=d,cents=c) for i,m,t,d,c in [('S1','甲餐饮','T1','2026-11-01',2800),('S2','乙餐饮','T2','2026-11-02',3600), ('S3','乙餐饮','T2','2026-11-02',3600),('S4','丙零售','T4','2026-11-03',4900)]] aliases = [('青禾','东店','甲餐饮','T1'),('小林','南店','乙餐饮','T2')] out['DJ4-098'] = {'input':{'receipts':receipts,'statements':statements,'documented_aliases':aliases}, 'output':evidence_candidates(receipts,statements,aliases), 'contrast':evidence_candidates(receipts,statements,aliases+[('青禾','西店','甲餐饮','T1')])} inst_events = [{'date':'2026-11-01','kind':'bill'}, {'date':'2026-11-20','kind':'pay','principal_cents':150000,'fee_cents':3000}, {'date':'2026-12-01','kind':'bill'}, {'date':'2026-12-20','kind':'pay','principal_cents':200000,'fee_cents':3000}, {'date':'2027-01-01','kind':'bill'}, {'date':'2027-01-20','kind':'pay','principal_cents':250000,'fee_cents':3000}] regular = [dict(e) for e in inst_events] regular[1]['principal_cents']=200000 regular[-1]['principal_cents']=200000 out['DJ4-099'] = {'input':{'principal_cents':600000,'period_principal_cents':200000, 'billed_period_fee_cents':3000,'events':inst_events, 'future_fee_not_yet_due':True}, 'output':installment(600000,200000,3000,inst_events), 'contrast':installment(600000,200000,3000,regular)} changes = { 'DJ4-089': {'observations': altered, 'change': '仅银行T101观察增加100分,冲突组暂停确认'}, 'DJ4-090': {'legs': {'wallet_paid':9000,'bank':16000,'bonus':0}, 'change':'赠送不可用,由实付钱包补2000分'}, 'DJ4-091': {'matrix':bad, 'change':'只删除C对P1的5000分映射,不修改原订单和扣款'}, 'DJ4-092': {'discount_cents':101, 'change':'优惠增加1分'}, 'DJ4-093': {'coupon_returns':False, 'change':'同额现金退款但不恢复券'}, 'DJ4-094': {'events':delayed, 'change':'观察期内不释放H1剩余冻结'}, 'DJ4-095': {'steps':['购买'], 'change':'资格未确认且未到账'}, 'DJ4-096': {'bonus_first':False, 'change':'改先实付后赠送'}, 'DJ4-097': {'points_per_yuan':200, 'change':'只改变兑换比例'}, 'DJ4-098': {'documented_aliases':aliases+[('青禾','西店','甲餐饮','T1')], 'change':'新增西店声明,反查共享候选'}, 'DJ4-099': {'events':regular, 'change':'各期足额还200000分,其他条款不变'}, } terms = { 'DJ4-089': {'id_namespace_verified':True,'same_day':'2026-11-02','single_bank_source':True}, 'DJ4-090': {'date':'2026-11-03','bonus_not_cash':True,'all_legs_completed':True}, 'DJ4-091': {'dates':['2026-11-04','2026-11-05'],'no_discount_or_fee':True,'cancelled_before_payment':True}, 'DJ4-092': {'date':'2026-11-06','all_items_eligible':True,'basis':'原价','no_shipping_or_other_discount':True}, 'DJ4-093': {'purchase_date':'2026-11-07','return_date':'2026-11-09','cash_receipt_date':'2026-11-10', 'coupon_valid_until':'2026-11-30','coupon_nonwithdrawable':True,'remaining_item_not_repriced':True}, 'DJ4-094': {'debit_account':True,'no_other_holds':True,'no_fee_or_overdraft':True}, 'DJ4-095': {'cash_reward':True,'no_future_conditions_after_confirmation':True}, 'DJ4-096': {'topup_date':'2026-11-10','use_dates':['2026-11-11','2026-11-14'],'bonus_first':True, 'bonus_expiry':'2026-11-30','both_balances_not_withdrawable_in_window':True}, 'DJ4-097': {'dates':['2026-11-15','2026-11-16','2026-11-18','2026-11-20'], 'cap_percent':20,'no_points_earned_on_this_purchase':True,'cash_value_of_remaining_points':None}, 'DJ4-098': {'hard_id_available':False,'automatic_merge':False,'alias_scope':'指定门店、终端与样本日期'}, 'DJ4-099': {'purchase_date':'2026-10-25','shortfall_allowed_until_final_payment':True, 'no_late_interest_or_fee':True,'fee_confirmed_only_on_bill':True}, } for identifier, record in out.items(): record['input']['money_unit'] = '整数分;展示元保留两位;积分为整数点' record['input']['terms'] = terms[identifier] record['contrast_input'] = changes[identifier] return out if __name__ == '__main__': result = build() assert len(result) == 11 with Path(__file__).with_suffix('.json').open('w',encoding='utf-8',newline='\n') as handle: json.dump(result, handle, ensure_ascii=False, indent=2, sort_keys=True) handle.write('\n')