# -*- coding: utf-8 -*-
# Vol.15受注店に invoice 情報を紐づけ（請求書管理.json と vol15.invoiceKey で結合）。
# 経理連絡項目：issued(発行済?)/deliveryMethod(持参|送付)/sendProgress(済|未)/needsAccounting/collectionMethod(振込|集金)/mado(窓口)/amountIncl/invoiceNo
import json, os
B=os.path.dirname(os.path.abspath(__file__))
M=os.path.join(B,"meiten-master.json")
INV=os.path.join(B,"..","mvp","source","請求書管理.json")
j=json.load(open(M,encoding="utf-8"))
rows=json.load(open(INV,encoding="utf-8"))
hdr=rows[0]; idx={h:i for i,h in enumerate(hdr)}
def g(r,name):
    i=idx.get(name);
    return (r[i] if i is not None and i<len(r) else "") or ""
keymap={}
for r in rows[1:]:
    keymap[g(r,"キー(自動)")]=r

seeded=0; recv=0
for s in j["stores"]:
    v=s.get("vol15") or {}
    if v.get("status")!="受注": continue
    recv+=1
    r=keymap.get(v.get("invoiceKey"))
    if r:
        coll=g(r,"集金方法") or "振込"
        s["invoice"]={
            "issue":15,
            "issued": (g(r,"ステータス")=="発行済"),
            "deliveryMethod": None,                 # 持参 / 送付 （営業が選ぶ）
            "sendProgress": ("済" if "済" in g(r,"送付進捗") else "未"),
            "needsAccounting": False,                # 経理依頼が必要か
            "collectionMethod": ("集金" if "集金" in coll else "振込"),
            "mado": g(r,"窓口担当(○○様)"),
            "amountIncl": g(r,"合計(税込)"),
            "invoiceNo": g(r,"請求書番号"),
            "slot": g(r,"品名") and (v.get("slot") or g(r,"備考(メニュー)")),
        }
        # 窓口担当を店レベルにも（御社担当・編集可）
        if g(r,"窓口担当(○○様)") and not s.get("contactPerson"):
            s["contactPerson"]=g(r,"窓口担当(○○様)")
        seeded+=1
    else:
        s["invoice"]={"issue":15,"issued":False,"deliveryMethod":None,"sendProgress":"未",
                      "needsAccounting":False,"collectionMethod":"振込","mado":v.get("mado") or "","amountIncl":"","invoiceNo":""}
json.dump(j,open(M,"w",encoding="utf-8"),ensure_ascii=False,indent=2)
print(f"Vol.15受注={recv} / invoice紐づけ(請求書管理一致)={seeded}")
