Download tasks/billing-queue-handback/solution/solve.py from reactive-labs/odoo-back-office: direct link, hf CLI and curl.
- Browser
- Download file 11 kB
-
https://huggingface.co/datasets/reactive-labs/odoo-back-office/resolve/main/tasks/billing-queue-handback/solution/solve.py
- Command line
-
hf download hf://datasets/reactive-labs/odoo-back-office/tasks/billing-queue-handback/solution/solve.py
-
curl -L -o solve.py https://huggingface.co/datasets/reactive-labs/odoo-back-office/resolve/main/tasks/billing-queue-handback/solution/solve.py
11 kB
| #!/usr/bin/env python3 | |
| """Reference solution and wrong solutions for billing-queue-handback (stdlib only). | |
| Lily Chen takes the December billing queue back from Nadia Burke. Daniel's close checklist rev. 4 (PDF on the | |
| Miscellaneous Operations journal) has the billing rules: invoice from the sales order, invoice date = the date the | |
| goods shipped, nothing warehouse flagged as not shipped, a delivery invoiced twice keeps the order's invoice and the | |
| other is reversed by credit note (a posted invoice is never deleted), drafts nobody will post are deleted. | |
| Modes: | |
| ref the reference. | |
| today invoices the delivered orders but dates every invoice today (12/31), and leaves the drafts and the | |
| posted duplicate alone. | |
| miss right on the routine billing and the Larchmont draft, but leaves Rosa's five per-store Greenmarket | |
| drafts (Nadia "hasn't touched" them) and never notices the Hoboken manual invoice duplicating the | |
| order's invoice. | |
| cancel the reference, except the Hoboken manual invoice is reset to draft and cancelled instead of reversed. | |
| wrongone the reference, except it reverses the order's invoice INV/2026/00481 and keeps Rosa's manual one. | |
| canceldrafts the reference, except Rosa's six drafts are cancelled (with a note) instead of deleted. Full marks. | |
| handcn the reference, except the credit note for the Hoboken manual invoice is keyed by hand (same lines, no | |
| reversal link) and matched to it. Full marks. | |
| """ | |
| import json | |
| import os | |
| import re | |
| import sys | |
| import urllib.error | |
| import urllib.request | |
| from datetime import datetime, timedelta | |
| URL = os.environ.get("ODOO_URL", "http://odoo:8069") | |
| KEY = os.environ.get("ODOO_KEY") or "e0634eeb156d5e2d11fc07dd62d48912814411b8" # lchen | |
| TODAY = "2026-12-31" | |
| def o(model, method, **kw): | |
| req = urllib.request.Request( | |
| f"{URL}/json/2/{model}/{method}", data=json.dumps(kw).encode(), | |
| headers={"Authorization": f"bearer {KEY}", "X-Odoo-Database": "company", | |
| "Content-Type": "application/json"}) | |
| try: | |
| with urllib.request.urlopen(req, timeout=180) as r: | |
| return json.load(r) | |
| except urllib.error.HTTPError as e: | |
| sys.exit(f"{model}.{method}: HTTP {e.code} {e.read().decode()[:1500]}") | |
| def text(html): | |
| return re.sub(r"\s+", " ", re.sub(r"<[^>]+>", " ", html or "")).strip() | |
| def one(model, domain, fields=("id",)): | |
| r = o(model, "search_read", domain=domain, fields=list(fields)) | |
| if len(r) != 1: | |
| sys.exit(f"{model} {domain}: {len(r)} records") | |
| return r[0] | |
| def local_date(utc): | |
| # New Jersey: EST in December (UTC-5) | |
| return (datetime.strptime(utc, "%Y-%m-%d %H:%M:%S") - timedelta(hours=5)).strftime("%Y-%m-%d") | |
| mode = sys.argv[1] if len(sys.argv) > 1 else "ref" | |
| # ---------------------------------------------------------------- 1. drafts in the queue | |
| drafts = o("account.move", "search_read", domain=[["move_type", "=", "out_invoice"], ["state", "=", "draft"]], | |
| fields=["partner_id", "ref", "invoice_origin", "amount_total", "invoice_date"]) | |
| to_delete = [] | |
| for d in drafts: | |
| if d["invoice_origin"]: | |
| # an order's draft: nothing left to bill on it once the delivery came back | |
| so = one("sale.order", [["name", "=", d["invoice_origin"]]], ["order_line"]) | |
| lines = o("sale.order.line", "read", ids=so["order_line"], fields=["qty_delivered"]) | |
| if all(l["qty_delivered"] == 0 for l in lines): | |
| to_delete.append((d, "order taken back in full")) | |
| else: | |
| # a hand-keyed draft "<customer PO> store N": the order's own invoice for that PO is already posted | |
| po = re.match(r"(.*?) store \d+$", d["ref"] or "") | |
| assert po, d | |
| billed = o("account.move", "search_read", domain=[["move_type", "=", "out_invoice"], ["state", "=", "posted"], | |
| ["ref", "=", po.group(1)], ["invoice_origin", "!=", False]], | |
| fields=["name", "amount_total"]) | |
| assert len(billed) == 1, (d, billed) | |
| to_delete.append((d, f"duplicates {billed[0]['name']}")) | |
| assert len(to_delete) == 6, to_delete | |
| for d, why in to_delete: | |
| store = "store" in (d["ref"] or "") | |
| if mode == "today": | |
| continue | |
| if mode == "miss" and store: | |
| continue | |
| if mode == "canceldrafts": | |
| o("account.move", "message_post", ids=[d["id"]], body=f"Cancelled at billing-queue cleanup: {why}.", | |
| message_type="comment", subtype_xmlid="mail.mt_note") | |
| o("account.move", "button_cancel", ids=[d["id"]]) | |
| else: | |
| o("account.move", "unlink", ids=[d["id"]]) | |
| print("deleted draft", d["partner_id"][1], d["ref"], d["amount_total"], "-", why) | |
| # ---------------------------------------------------------------- 2. posted manual invoices that duplicate an order's | |
| manual = o("account.move", "search_read", | |
| domain=[["move_type", "=", "out_invoice"], ["state", "=", "posted"], ["invoice_origin", "=", False], | |
| ["invoice_date", ">=", "2026-12-01"]], | |
| fields=["name", "partner_id", "ref", "amount_total", "journal_id", "payment_state"]) | |
| dups = [] | |
| for m in manual: | |
| twin = o("account.move", "search_read", | |
| domain=[["move_type", "=", "out_invoice"], ["state", "=", "posted"], ["id", "!=", m["id"]], | |
| ["partner_id", "=", m["partner_id"][0]], ["ref", "=", m["ref"]], ["invoice_origin", "!=", False]], | |
| fields=["name", "amount_total", "invoice_origin"]) | |
| if twin and abs(twin[0]["amount_total"] - m["amount_total"]) < 0.005: | |
| dups.append((m, twin[0])) | |
| assert len(dups) == 1, dups | |
| manual_inv, order_inv = dups[0] | |
| if mode == "handcn": | |
| src = one("account.move", [["id", "=", manual_inv["id"]]], ["invoice_line_ids"]) | |
| lines = [[0, 0, {"product_id": l["product_id"] and l["product_id"][0], "name": l["name"], "quantity": l["quantity"], | |
| "price_unit": l["price_unit"], "account_id": l["account_id"][0], "tax_ids": [[6, 0, l["tax_ids"]]]}] | |
| for l in o("account.move.line", "read", ids=src["invoice_line_ids"], | |
| fields=["product_id", "name", "quantity", "price_unit", "account_id", "tax_ids", "display_type"]) | |
| if l["display_type"] == "product"] | |
| cn = o("account.move", "create", vals_list=[{ | |
| "move_type": "out_refund", "partner_id": manual_inv["partner_id"][0], "invoice_date": TODAY, | |
| "journal_id": manual_inv["journal_id"][0], "ref": f"Credit for {manual_inv['name']} (duplicate of {order_inv['name']})", | |
| "invoice_line_ids": lines}])[0] | |
| o("account.move", "action_post", ids=[cn]) | |
| rec = o("account.move.line", "search", domain=[["move_id", "=", cn], ["account_type", "=", "asset_receivable"]]) | |
| o("account.move", "js_assign_outstanding_line", ids=[manual_inv["id"]], line_id=rec[0]) | |
| print("hand-keyed credit note for", manual_inv["name"], manual_inv["amount_total"]) | |
| if mode in ("ref", "cancel", "wrongone", "canceldrafts"): | |
| if mode == "cancel": | |
| o("account.move", "button_draft", ids=[manual_inv["id"]]) | |
| o("account.move", "button_cancel", ids=[manual_inv["id"]]) | |
| print("cancelled", manual_inv["name"]) | |
| else: | |
| target = manual_inv if mode in ("ref", "canceldrafts") else one("account.move", [["name", "=", order_inv["name"]]], | |
| ["name", "journal_id", "amount_total"]) | |
| keep = order_inv["name"] if mode in ("ref", "canceldrafts") else manual_inv["name"] | |
| wiz = o("account.move.reversal", "create", vals_list=[{ | |
| "move_ids": [[6, 0, [target["id"]]]], "date": TODAY, "journal_id": target["journal_id"][0], | |
| "reason": f"Duplicate of {keep} (same delivery invoiced twice)"}], | |
| context={"active_model": "account.move", "active_ids": [target["id"]]}) | |
| o("account.move.reversal", "refund_moves", ids=wiz) | |
| cn = one("account.move", [["reversed_entry_id", "=", target["id"]], ["state", "=", "draft"]])["id"] | |
| o("account.move", "action_post", ids=[cn]) | |
| if one("account.move", [["id", "=", target["id"]]], ["payment_state"])["payment_state"] not in ("reversed", "paid"): | |
| rec = o("account.move.line", "search", domain=[["move_id", "=", cn], ["account_type", "=", "asset_receivable"]]) | |
| o("account.move", "js_assign_outstanding_line", ids=[target["id"]], line_id=rec[0]) | |
| print("credit note for", target["name"], target["amount_total"]) | |
| # ---------------------------------------------------------------- 3. delivered orders not yet invoiced | |
| sos = o("sale.order", "search_read", domain=[["state", "=", "sale"], ["invoice_status", "=", "to invoice"]], | |
| fields=["name", "partner_id", "picking_ids", "order_line"], order="name") | |
| billed = [] | |
| for so in sos: | |
| lines = o("sale.order.line", "read", ids=so["order_line"], fields=["qty_to_invoice"]) | |
| if any(l["qty_to_invoice"] < 0 for l in lines) or not any(l["qty_to_invoice"] > 0 for l in lines): | |
| continue # returns waiting for their credit (a separate batch), or nothing to bill | |
| picks = o("stock.picking", "search_read", domain=[["id", "in", so["picking_ids"]], ["picking_type_code", "=", "outgoing"], | |
| ["state", "=", "done"]], fields=["name", "date_done"], | |
| order="date_done desc") | |
| notes = o("mail.message", "search_read", | |
| domain=["|", "&", ["model", "=", "sale.order"], ["res_id", "=", so["id"]], | |
| "&", ["model", "=", "stock.picking"], ["res_id", "in", so["picking_ids"]], | |
| ["message_type", "=", "comment"]], fields=["date", "body"], order="date desc, id desc") | |
| latest = [text(n["body"]) for n in notes] | |
| flagged = [n for n in latest if re.search(r"don't invoice|hold the invoice", n, re.I)] | |
| cleared = [n for n in latest if re.search(r"go ahead and invoice", n, re.I)] | |
| if flagged and not (cleared and latest.index(cleared[0]) < latest.index(flagged[0])): | |
| print("not billed:", so["name"], so["partner_id"][1], "-", flagged[0][:80]) | |
| continue | |
| w = o("sale.advance.payment.inv", "create", vals_list=[{"advance_payment_method": "delivered", | |
| "sale_order_ids": [[6, 0, [so["id"]]]]}], | |
| context={"active_model": "sale.order", "active_ids": [so["id"]]}) | |
| o("sale.advance.payment.inv", "create_invoices", ids=w) | |
| inv = one("account.move", [["move_type", "=", "out_invoice"], ["state", "=", "draft"], | |
| ["invoice_origin", "=", so["name"]]], ["amount_total"]) | |
| ship = local_date(picks[0]["date_done"]) | |
| o("account.move", "write", ids=[inv["id"]], vals={"invoice_date": TODAY if mode == "today" else ship}) | |
| o("account.move", "action_post", ids=[inv["id"]]) | |
| billed.append((so["name"], so["partner_id"][1], inv["amount_total"], ship)) | |
| for b in billed: | |
| print("invoiced %s %-30s %10.2f shipped %s" % b) | |