from pathlib import Path import csv,json,platform,datetime,sys HERE=Path(__file__).resolve().parent def clean(value):return str(value or '').strip() def read_csv(root,name): with (root/'input'/f'{name}.csv').open(encoding='utf-8-sig',newline='') as f:return list(csv.DictReader(f)) REPORT_HEADERS=['반납행', '대여번호', '연결자산', '구성품', '수량', '현재반납포함', '사유'] def compute(root=HERE): loans={};issues=[] for r in read_csv(root,'loans'): loan=clean(r.get('loan'));asset=clean(r.get('asset')) if not loan or not asset:raise ValueError('loan_asset_relation_missing') if loan in loans and loans[loan]!=asset:raise ValueError('loan_asset_relation_conflict:'+loan) loans[loan]=asset current_rows=read_csv(root,'current_loan') if len(current_rows)!=1:raise ValueError('one_current_loan_required') current=current_rows[0];current_loan=clean(current.get('loan'));current_asset=clean(current.get('asset')) if loans.get(current_loan)!=current_asset or not current_asset:raise ValueError('current_loan_asset_mismatch') kit={} for r in read_csv(root,'kit'): if clean(r.get('asset'))==current_asset: part=clean(r.get('part'));q=int(clean(r.get('expected_qty'))) if not part or q<0:raise ValueError('invalid_kit_quantity') kit[part]=kit.get(part,0)+q if not kit:raise ValueError('no_current_asset_kit') returned={};accepted_rows=0;report_rows=[] for i,r in enumerate(read_csv(root,'returned'),1): loan=clean(r.get('loan'));part=clean(r.get('part'));asset=loans.get(loan,'');reason='';include=False if loan not in loans:reason='등록되지 않은 대여번호' elif loan!=current_loan:reason='현재 대여가 아님' elif asset!=current_asset:reason='현재 자산과 불일치' elif part not in kit:reason='키트에 없는 구성품' else: try:q=int(clean(r.get('qty'))) except ValueError:q=-1 if q<0:reason='수량 미확인 또는 음수' else:returned[part]=returned.get(part,0)+q;accepted_rows+=1;include=True;reason='현재 대여·자산에 연결' if not include:issues.append({'row':i,'loan':loan,'part':part,'reason':reason}) report_rows.append([i,loan,asset,part,r.get('qty',''),'포함' if include else '제외·검토',reason]) missing={part:q-returned.get(part,0) for part,q in kit.items() if returned.get(part,0)0 queue=[r for r in read_csv(root,'queue') if clean(r.get('asset'))==current_asset] actual={'expected_piece_total':sum(kit.values()),'returned_piece_total':sum(returned.values()),'missing_parts':missing,'return_event_exists':accepted_rows>0,'available_for_next_loan':ready,'needs_contact':[r['loan'] for r in queue] if not ready else []} return actual,report_rows,{'current_loan':current_loan,'current_asset':current_asset,'accepted_return_rows':accepted_rows,'excluded_return_rows':issues,'count_scope':'Only quantities of the current loan and its registered asset. No physical receipt,condition or identity verification.'} def run(root=HERE): actual,rows,details=compute(root) expected=json.loads((root/'expected/report.json').read_text(encoding='utf-8')) checks=[{'field':k,'pass':actual.get(k)==v,'actual':actual.get(k),'expected':v} for k,v in expected.items()] passed=all(c['pass'] for c in checks) and set(actual)==set(expected) report={'lab_id':root.name,'synthetic_fixture':True,'environment':{'python':platform.python_version(),'platform':platform.system(),'processor':'Python standard library'},'run_utc':datetime.datetime.now(datetime.timezone.utc).isoformat(),'status':'PASS' if passed else 'FAIL','assertion_count':len(checks),'actual':actual,'assertions':checks,'details':details,'limits':'Synthetic record checks only;not a real building inspection,safety/legal verdict,Excel app test,physical receipt or authenticity verification.'} (root/'results.json').write_text(json.dumps(report,ensure_ascii=False,indent=2),encoding='utf-8') (root/'actual.json').write_text(json.dumps(actual,ensure_ascii=False,indent=2),encoding='utf-8') with (root/'results.csv').open('w',encoding='utf-8-sig',newline='') as f: w=csv.writer(f);w.writerow(REPORT_HEADERS);w.writerows(rows) print(json.dumps(report,ensure_ascii=False,indent=2)) return report if __name__=='__main__': report=run() if report['status']!='PASS':raise SystemExit(1)