import json, urllib.request

PB = "http://localhost:8102"

def post(path, data, token=None):
    req = urllib.request.Request(PB + path, data=json.dumps(data).encode(),
        headers={"Content-Type": "application/json", **({"Authorization": token} if token else {})})
    return json.load(urllib.request.urlopen(req))

def get(path, token=None):
    req = urllib.request.Request(PB + path, headers={"Authorization": token} if token else {})
    return json.load(urllib.request.urlopen(req))

tok = post("/api/collections/_superusers/auth-with-password",
           {"identity": "edelmar.edd@gmail.com", "password": "564712564712"})["token"]

# Facturas con su pedido expandido
fac = get("/api/collections/facturas/records?perPage=20&expand=pedido", tok)
print("=== FACTURAS ===")
for f in fac["items"]:
    ped = f.get("expand", {}).get("pedido", {})
    print(f"  nro_cbte={f['nro_cbte']:>4}  pedido_id={f.get('pedido','-'):<16} codigo={ped.get('codigo','-'):<12} numero={ped.get('numero','-')}  imp={f['imp_total']}")

# Movimientos ingreso con numero_pedido no vacio
mov = get("/api/collections/movimientos/records?perPage=30&filter=" + urllib.parse.quote('tipo="ingreso" && numero_pedido!=""'), tok)
print(f"\n=== MOVIMIENTOS ingreso con numero_pedido (mostrando {len(mov['items'])}) ===")
for m in mov["items"][:15]:
    print(f"  numero_pedido='{m['numero_pedido']}'  monto={m['monto']}  fecha={m.get('fecha','')}")
print(f"\nTotal movimientos ingreso con numero_pedido: {mov['totalItems']}")
