            totals=defaultdict(int);shipped={};reversals=defaultdict(int)
            for r in output['events']:
                qty=r['quantity'];check('每个事件数量为正整数',isinstance(qty,int) and not isinstance(qty,bool) and qty>0)
                if r['type']=='ship':shipped[r['id']]=r;totals[r['order']]+=qty
                else:
                    original=shipped.get(r['reverse_of']);check('冲销对应真实发货且订单相同',original is not None and original['order']==r['order']);reversals[r['reverse_of']]+=qty;check('累计冲销不超过原单',reversals[r['reverse_of']]<=original['quantity']);totals[r['order']]-=qty
            rows=[{'order':oid,'ordered':qty,'net_shipped':totals[oid],'remaining':qty-totals[oid]} for oid,qty in data['ordered'].items()]
            check('三次发货减冲销净数量8',rows[0]['net_shipped']==8);check('剩余2件不重复算订单总量',rows[0]['remaining']==2);cout('shipment-ledger.csv',output['events']);cout('order-balance.csv',rows);result={'orders':rows}
