from datetime import date, timedelta
from itertools import zip_longest

from flask import Blueprint, abort, flash, redirect, render_template, request, url_for

from .. import check_branch, currency_decimals, has, login_required, write_required
from ..db import commit, placeholders, q, x
from ..i18n import t
from ..ledger import INVOICE_KINDS, AccountingError, audit, check_journal, compute_invoice_line, create_refund, \
    invoice_residuals, now, payment_state, post_invoice, unpost_invoice
from ..money import to_int
from ..ledger import VENDOR_REF_LABEL, check_number_kept, check_vendor_ref, company, cross_rate, rate_on
from ..stock import invoice_needs_picking
from ..projects import cost_centre as project_cost_centre, options as project_options, parse as parse_project
from ..attachments import counts as attachment_counts, remove_all as remove_attachments
from ..costcentres import check_lines as check_cost_centres, options as cost_centre_options, \
    parse as parse_cost_centre
from .common import apply_search, partner_search, product_search, accounts_list, branch_map, default_branch, journals_for, list_filters, partners_list, \
    taxes_list, user_id

bp = Blueprint("invoices", __name__, url_prefix="/invoices")


def kind_or_404(kind):
    if kind not in INVOICE_KINDS:
        abort(404)
    return INVOICE_KINDS[kind]


def is_sale(kind):
    return kind.startswith("out_")


def get_invoice(inv_id):
    inv = q("SELECT i.*, p.name_en AS pname_en, p.name_ar AS pname_ar, p.vat_no AS pvat, p.address AS paddress, "
            "j.code AS jcode, pj.code AS pj_code, pj.name_en AS pj_en, pj.name_ar AS pj_ar FROM invoices i "
            "JOIN partners p ON p.id = i.partner_id JOIN journals j ON j.id = i.journal_id "
            "LEFT JOIN projects pj ON pj.id = i.project_id WHERE i.id = ?", (inv_id,), one=True)
    if not inv:
        abort(404)
    check_branch(inv["branch_id"])
    return inv


def auto_picking(inv_id):
    """Posting a document with stock products and no order behind it prepares the goods movement at once
    (vendor bill -> receipt, customer invoice -> delivery, credit note / vendor refund -> return). It waits as
    "Ready" in Inventory until the storekeeper validates it, so goods are counted only when they really move."""
    if not has("inventory") or not invoice_needs_picking(inv_id):
        return None
    from ..stock import create_invoice_picking
    try:
        pk = create_invoice_picking(inv_id, user_id())
    except AccountingError:
        return None  # e.g. the branch has no warehouse: the "Create Receipt" button stays on the document
    num = q("SELECT number, kind FROM pickings WHERE id = ?", (pk,), one=True)
    where = {"in": t("Receipts"), "out": t("Deliveries"), "return_in": t("Customer Returns"),
             "return_out": t("Vendor Returns")}.get(num["kind"], "")
    flash(f"{num['number']} " + t("is ready in") + f" {t('Inventory')} → {where}. " +
          t("Validate it when the goods move."), "info")
    return pk


@bp.route("/<kind>")
@login_required
def index(kind):
    kind_or_404(kind)
    f = list_filters()
    rows = []
    if f["branch_ids"]:
        sql = (f"SELECT i.*, p.name_en AS pname_en, p.name_ar AS pname_ar FROM invoices i "
               f"JOIN partners p ON p.id = i.partner_id "
               f"WHERE i.kind = ? AND i.branch_id IN ({placeholders(f['branch_ids'])})")
        args = [kind] + list(f["branch_ids"])
        itype = request.args.get("type")
        if kind == "out_invoice" and itype:
            sql += " AND i.invoice_type = ?"
            args.append(itype)
        elif kind == "out_invoice":
            sql += " AND i.invoice_type != 'proforma'"  # proformas have their own list
        if f["date_from"]:
            sql += " AND i.date >= ?"
            args.append(f["date_from"])
        if f["date_to"]:
            sql += " AND i.date <= ?"
            args.append(f["date_to"])
        if f["state"] in ("draft", "posted", "cancelled"):
            sql += " AND i.state = ?"
            args.append(f["state"])
        vendor_doc = kind.startswith("in_")
        sql, args = apply_search(f, sql, args, [
            ("number", "Number", "i.number LIKE ?", "text"),
            ("partner", "Vendor" if vendor_doc else "Customer", partner_search("p"), "text"),
            ("ref", ("Vendor credit note no." if kind == "in_refund" else "Vendor invoice no.") if vendor_doc
             else "Customer reference", "i.ref LIKE ?", "text"),
            ("product", "Product", product_search("invoice_lines", "invoice_id", "i.id"), "text"),
            ("notes", "Notes", "i.notes LIKE ?", "text"),
            ("amount", "Amount", "i.amount_total = ?", "amount")])
        rows = [dict(r) for r in q(sql + " ORDER BY i.date DESC, i.id DESC LIMIT 1000", args)]
        res = invoice_residuals([r["id"] for r in rows if r["state"] == "posted"])
        clips = attachment_counts("invoice", [r["id"] for r in rows])
        today = date.today().isoformat()
        for r in rows:
            r["residual"] = res.get(r["id"], 0)
            r["files"] = clips.get(r["id"], 0)
            r["pay_state"] = payment_state(r, r["residual"])
            r["overdue"] = r["pay_state"] in ("not_paid", "partial") and (r["due_date"] or r["date"]) < today
        pay = request.args.get("payment")
        if pay:
            rows = [r for r in rows if r["pay_state"] == pay or (pay == "overdue" and r["overdue"])]
    from ..invoicetypes import TYPES
    return render_template("invoices/list.html", rows=rows, kind=kind, info=INVOICE_KINDS[kind], f=f,
                           itype=request.args.get("type", ""), types=TYPES,
                           branches=branch_map(), payment=request.args.get("payment", ""))


def parse_lines(form, decimals, project_cc=None):
    lines = []
    taxes = {r["id"]: r for r in q("SELECT * FROM taxes")}
    rows = zip_longest(form.getlist("description"), form.getlist("account_id"), form.getlist("quantity"),
                       form.getlist("price_unit"), form.getlist("tax_id"), form.getlist("product_id"),
                       form.getlist("order_line_id"), form.getlist("cost_centre_id"), fillvalue="")
    for seq, (desc, acc, qty, price, tax, prod, oline, cc) in enumerate(rows):
        if not desc and not acc and not price and not prod:
            continue
        if not acc:
            raise AccountingError(t("Every line needs an account."))
        try:
            qty_f = float(qty or 1)
            price_i = to_int(price)
        except ValueError:
            raise AccountingError(t("invalid number"))
        tax_id = int(tax) if tax else None
        sub, tax_amt = compute_invoice_line(qty_f, price_i, taxes[tax_id]["rate"] if tax_id else 0, decimals)
        lines.append({"sequence": seq, "description": desc, "account_id": int(acc), "quantity": qty_f,
                      "price_unit": price_i, "tax_id": tax_id, "subtotal": sub, "tax_amount": tax_amt,
                      "product_id": int(prod) if prod else None, "order_line_id": int(oline) if oline else None,
                      "cost_centre_id": parse_cost_centre(cc)})
    if project_cc:  # income and expense lines of a project document go to the project's cost centre
        from ..costcentres import needs_cost_centre
        for ln in lines:
            if not ln["cost_centre_id"] and needs_cost_centre(ln["account_id"]):
                ln["cost_centre_id"] = project_cc
    check_cost_centres(lines)
    return lines


@bp.route("/<kind>/new", methods=["GET", "POST"])
@bp.route("/<kind>/<int:inv_id>/edit", methods=["GET", "POST"])
@write_required
def form(kind, inv_id=None):
    info = kind_or_404(kind)
    inv = get_invoice(inv_id) if inv_id else None
    if inv and inv["state"] != "draft":
        flash(t("Only draft documents can be edited."), "error")
        return redirect(url_for("invoices.view", inv_id=inv_id))
    lines = [dict(r) for r in q("SELECT * FROM invoice_lines WHERE invoice_id = ? AND advance_invoice_id IS NULL "
                                "ORDER BY sequence, id", (inv_id,))] if inv else []
    orig_id = inv_id
    if request.method == "POST":
        fm = request.form
        try:
            branch_id = check_branch(fm["branch_id"])
            check_journal(branch_id, int(fm["journal_id"]))
            if inv:
                check_number_kept(inv["number"], inv["branch_id"], branch_id, inv["journal_id"], int(fm["journal_id"]),
                                  inv["date"], fm["date"])
            if not fm.get("partner_id"):
                raise AccountingError(t("Choose a partner."))
            branch = q("SELECT * FROM branches WHERE id = ?", (branch_id,), one=True)
            currency = fm.get("currency") or None
            if currency == branch["currency"]:
                currency = None
            rate = 1.0
            if currency:
                try:
                    rate = float(fm.get("rate") or 0) or cross_rate(currency, branch["currency"], fm["date"])
                except ValueError:
                    raise AccountingError(t("Enter the exchange rate."))
                if rate <= 0:
                    raise AccountingError(t("Enter the exchange rate."))
            project_id = parse_project(fm.get("project_id"), branch_id, dict(inv).get("project_id") if inv else None)
            from ..invoicetypes import FORM_TYPES, prepare_lines
            itype = (dict(inv).get("invoice_type") or "standard") if inv else "standard"
            if kind == "out_invoice" and itype in FORM_TYPES + ("",):
                itype = fm.get("invoice_type") if fm.get("invoice_type") in FORM_TYPES else "standard"
            keep = [dict(r) for r in q("SELECT * FROM invoice_lines WHERE invoice_id = ? AND advance_invoice_id IS NOT NULL",
                                       (orig_id,))] if orig_id else []
            lines = prepare_lines(itype, parse_lines(fm, currency_decimals(currency or branch["currency"]),
                                                     project_cost_centre(project_id)))
            if itype not in ("standard", "progress"):
                keep = []
            lines += keep  # advance deductions stay; they are managed on the invoice page
            origin_id = int(fm["origin_id"]) if itype == "debit_note" and fm.get("origin_id") else \
                (dict(inv).get("origin_id") if inv else None)
            if not lines:
                raise AccountingError(t("Add at least one line."))
            vendor_ref = check_vendor_ref(int(fm["partner_id"]), kind, fm.get("ref"), orig_id,
                                          posting=fm.get("action") == "post")
            untaxed = sum(ln["subtotal"] for ln in lines)
            tax = sum(ln["tax_amount"] for ln in lines)
            vals = (branch_id, int(fm["journal_id"]), int(fm["partner_id"]), fm["date"],
                    fm.get("due_date") or fm["date"], vendor_ref if kind.startswith("in_") else fm.get("ref"), fm.get("notes"), untaxed, tax, untaxed + tax,
                    currency, rate, fm.get("terms"), project_id, itype, origin_id if itype == "debit_note" or kind.endswith("refund") else None,
                    fm.get("note_reason") if itype == "debit_note" else None)
            if inv:
                x("UPDATE invoices SET branch_id=?, journal_id=?, partner_id=?, date=?, due_date=?, ref=?, notes=?, "
                  "amount_untaxed=?, amount_tax=?, amount_total=?, currency=?, rate=?, terms=?, project_id=?, invoice_type=?, "
                  "origin_id=?, note_reason=? WHERE id = ?",
                  vals + (inv_id,))
                x("DELETE FROM invoice_lines WHERE invoice_id = ?", (inv_id,))
            else:
                inv_id = x("INSERT INTO invoices (branch_id, journal_id, partner_id, date, due_date, ref, notes, "
                           "amount_untaxed, amount_tax, amount_total, currency, rate, terms, project_id, invoice_type, origin_id, "
                           "note_reason, kind, state, created_by, created_at) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,'draft',?,?)",
                           vals + (kind, user_id(), now()))
            for ln in lines:
                x("INSERT INTO invoice_lines (invoice_id, sequence, description, account_id, quantity, price_unit, "
                  "tax_id, subtotal, tax_amount, product_id, order_line_id, cost_centre_id, advance_invoice_id) "
                  "VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)",
                  (inv_id, ln["sequence"], ln["description"], ln["account_id"], ln["quantity"], ln["price_unit"],
                   ln["tax_id"], ln["subtotal"], ln["tax_amount"], ln.get("product_id"), ln.get("order_line_id"),
                   ln.get("cost_centre_id"), ln.get("advance_invoice_id")))
            audit(user_id(), "save", "invoice", inv_id)
            if fm.get("action") == "post":
                post_invoice(inv_id, user_id())
                auto_picking(inv_id)
            commit()
            flash(t("Saved."), "success")
            return redirect(url_for("invoices.view", inv_id=inv_id))
        except AccountingError as e:
            from ..db import get_db
            get_db().rollback()
            flash(str(e), "error")
            inv = dict(fm.items())
            inv["id"] = orig_id
            inv["number"] = None
            lines = [{"description": d, "account_id": int(a) if a else None, "quantity": qq,
                      "price_unit": to_int(p) if p.replace(".", "", 1).isdigit() else 0, "tax_id": int(tx) if tx else None,
                      "product_id": int(pr) if pr else None, "order_line_id": int(ol) if ol else None,
                      "cost_centre_id": int(cc) if cc else None}
                     for d, a, qq, p, tx, pr, ol, cc in zip_longest(
                         fm.getlist("description"), fm.getlist("account_id"), fm.getlist("quantity"),
                         fm.getlist("price_unit"), fm.getlist("tax_id"), fm.getlist("product_id"),
                         fm.getlist("order_line_id"), fm.getlist("cost_centre_id"), fillvalue="")]
    if request.method == "GET" and not inv_id and request.args.get("copy", type=int):
        # Duplicate: a new draft with the original's partner, terms and lines, dated today
        src = get_invoice(request.args.get("copy", type=int))
        if src["kind"] != kind:
            abort(404)
        from ..invoicetypes import FORM_TYPES
        inv = dict(src)
        days = (date.fromisoformat(src["due_date"]) - date.fromisoformat(src["date"])).days if src["due_date"] else 0
        inv.update(id=None, number=None, state="draft", date=date.today().isoformat(),
                   due_date=(date.today() + timedelta(days=max(days, 0))).isoformat(),
                   ref="", invoice_type=src["invoice_type"] if src["invoice_type"] in FORM_TYPES else "standard",
                   origin_id=None, note_reason=None)
        lines = [dict(r, order_line_id=None) for r in q(
            "SELECT * FROM invoice_lines WHERE invoice_id = ? AND advance_invoice_id IS NULL ORDER BY sequence, id",
            (src["id"],))]
        flash(t("Copy of") + f" {src['number'] or t('Draft')}. " + t("Check it and save."), "info")
    branches = branch_map()
    jtype = "sale" if is_sale(kind) else "purchase"
    partners = partners_list(info["partner_type"])
    today = date.today()
    return render_template("invoices/form.html", inv=inv, lines=lines, kind=kind, info=info, branches=branches,
                           journals=journals_for(list(branches), [jtype]), accounts=accounts_list(),
                           partners=partners, taxes=taxes_list("sale" if is_sale(kind) else "purchase"),
                           products=q("SELECT * FROM products WHERE active = 1 ORDER BY code, name_en"),
                           grni=company()["grni_account_id"], cost_centres=cost_centre_options(),
                           projects=project_options(dict(inv).get("project_id") if inv else request.args.get("project", type=int)),
                           invoice_types=invoice_type_options(), itype_pre=request.args.get("type"),
                           origin_invoices=q("SELECT i.id, i.number, i.partner_id, i.date, i.amount_total FROM invoices i "
                                             "WHERE i.kind = 'out_invoice' AND i.state = 'posted' AND i.invoice_type "
                                             "NOT IN ('advance', 'proforma') ORDER BY i.date DESC LIMIT 500") if kind == "out_invoice" else [],
                           project_pre=request.args.get("project", type=int),
                           default_branch=default_branch(), today=today.isoformat(),
                           currencies=q("SELECT * FROM currencies WHERE active = 1 ORDER BY code"),
                           rates=latest_rates(), branch_currencies={str(b): v["currency"] for b, v in branches.items()},
                           due=(today + timedelta(days=30)).isoformat())


def invoice_type_options():
    from ..invoicetypes import FORM_TYPES, TYPES
    return [(k, TYPES[k][0]) for k in FORM_TYPES if k != "progress" or has("projects")]


def latest_rates():
    """Group-currency value of one unit of each active currency today (for the form's rate suggestion)."""
    out = {}
    for c in q("SELECT code FROM currencies WHERE active = 1"):
        try:
            out[c["code"]] = rate_on(c["code"], date.today().isoformat())
        except AccountingError:
            pass
    return out


def invoice_context(inv_id):
    inv = get_invoice(inv_id)
    lines = q("SELECT il.*, a.code, a.name_en AS aname_en, a.name_ar AS aname_ar, tx.name_en AS tname_en, "
              "tx.name_ar AS tname_ar, tx.rate AS trate, pr.code AS pcode, pr.name_en AS prname_en, "
              "pr.name_ar AS prname_ar, cc.code AS cc_code FROM invoice_lines il JOIN accounts a ON a.id = il.account_id "
              "LEFT JOIN cost_centres cc ON cc.id = il.cost_centre_id "
              "LEFT JOIN taxes tx ON tx.id = il.tax_id LEFT JOIN products pr ON pr.id = il.product_id "
              "WHERE il.invoice_id = ? ORDER BY il.sequence, il.id", (inv_id,))
    residual = invoice_residuals([inv_id]).get(inv_id, inv["amount_total"])
    payments = q("SELECT p.*, j.code AS jcode FROM payments p JOIN journals j ON j.id = p.journal_id "
                 "WHERE p.invoice_id = ? ORDER BY p.date", (inv_id,))
    branch = q("SELECT * FROM branches WHERE id = ?", (inv["branch_id"],), one=True)
    order = q("SELECT id, number FROM orders WHERE id = ?", (inv["order_id"],), one=True) if inv["order_id"] else None
    pickings = q("SELECT * FROM pickings WHERE invoice_id = ? ORDER BY id", (inv_id,))
    origin = q("SELECT id, number FROM invoices WHERE id = ?", (inv["origin_id"],), one=True) if inv["origin_id"] else None
    refunds = q("SELECT id, number, kind, state FROM invoices WHERE origin_id = ? ORDER BY id", (inv_id,))
    from ..invoicetypes import deductions, open_advances, title
    advances = open_advances(inv["partner_id"], inv["branch_id"], inv["currency"], inv_id) \
        if inv["kind"] == "out_invoice" and inv["state"] == "draft" and inv["invoice_type"] in ("standard", "progress") else []
    converted = q("SELECT id, number FROM invoices WHERE proforma_id = ? ORDER BY id DESC LIMIT 1", (inv_id,), one=True)
    proforma = q("SELECT id, number FROM invoices WHERE id = ?", (inv["proforma_id"],), one=True) if inv["proforma_id"] else None
    used_by = q("SELECT DISTINCT i.id, i.number, i.state FROM invoice_lines il JOIN invoices i ON i.id = il.invoice_id "
                "WHERE il.advance_invoice_id = ?", (inv_id,)) if inv["invoice_type"] == "advance" else []
    return {"inv": inv, "lines": lines, "residual": residual, "order": order, "pickings": pickings,
            "origin": origin, "refunds": [r for r in refunds if r["kind"] == "out_refund" or r["kind"] == "in_refund"],
            "debit_notes": [r for r in refunds if r["kind"] == "out_invoice"], "doc_title": title(inv),
            "advances": advances, "deductions": deductions(inv_id), "converted": converted, "proforma": proforma,
            "used_by": used_by,
            "needs_picking": inv["state"] == "posted" and invoice_needs_picking(inv_id), "pay_state": payment_state(inv, residual),
            "payments": payments, "branch": branch, "info": INVOICE_KINDS[inv["kind"]], "kind": inv["kind"]}


@bp.route("/view/<int:inv_id>")
@login_required
def view(inv_id):
    return render_template("invoices/view.html", **invoice_context(inv_id))


@bp.route("/print/<int:inv_id>")
@login_required
def print_view(inv_id):
    return render_template("invoices/print.html", **invoice_context(inv_id))


@bp.route("/view/<int:inv_id>/<action>", methods=["POST"])
@write_required
def action(inv_id, action):
    inv = get_invoice(inv_id)
    try:
        if action == "post":
            check_vendor_ref(inv["partner_id"], inv["kind"], inv["ref"], inv_id, posting=True)
            post_invoice(inv_id, user_id())
            auto_picking(inv_id)
        elif action == "draft" and inv["state"] in ("posted", "cancelled"):
            unpost_invoice(inv_id, "draft", user_id())
        elif action in ("issue_proforma", "convert", "debit_note", "deduct_advance", "remove_deduction"):
            from .. import invoicetypes as it
            if action == "issue_proforma":
                it.issue_proforma(inv_id, user_id())
            elif action == "remove_deduction":
                it.remove_deduction(inv_id, int(request.form["line_id"]), user_id())
            elif action == "deduct_advance":
                it.deduct_advance(inv_id, int(request.form["advance_id"]), to_int(request.form.get("amount") or 0), user_id())
            else:
                new_id = it.convert_proforma(inv_id, date.today().isoformat(), user_id()) if action == "convert" \
                    else it.create_debit_note(inv_id, user_id())
                commit()
                flash(t("Draft tax invoice created from the proforma. Check it and post it.") if action == "convert"
                      else t("Draft debit note created. Enter the additional amount, then post it."), "success")
                return redirect(url_for("invoices.form", kind="out_invoice", inv_id=new_id) if action == "debit_note"
                                else url_for("invoices.view", inv_id=new_id))
        elif action == "cancel" and inv["state"] in ("posted", "draft", "proforma"):
            unpost_invoice(inv_id, "cancelled", user_id())
        elif action == "refund":
            new_id = create_refund(inv_id, user_id())
            commit()
            flash(t("Draft created from the original. Change the quantities to what is being returned, then post it."),
                  "success")
            return redirect(url_for("invoices.form", kind=q("SELECT kind FROM invoices WHERE id = ?", (new_id,),
                                                             one=True)["kind"], inv_id=new_id))
        elif action == "delete" and inv["state"] == "draft" and not inv["number"]:
            # a deleted progress invoice frees its milestone for billing again
            x("UPDATE project_milestones SET invoice_id = NULL, state = 'done' WHERE invoice_id = ?", (inv_id,))
            x("DELETE FROM invoices WHERE id = ?", (inv_id,))
            remove_attachments("invoice", inv_id)
            audit(user_id(), "delete", "invoice", inv_id)
            commit()
            flash(t("Deleted."), "success")
            return redirect(url_for("invoices.index", kind=inv["kind"]))
        else:
            raise AccountingError(t("This action is not allowed in the current state."))
        commit()
        flash(t("Done."), "success")
    except (AccountingError, ValueError) as e:
        from ..db import get_db
        get_db().rollback()
        flash(str(e), "error")
    return redirect(url_for("invoices.view", inv_id=inv_id))


def invoice_pdf_bytes(ctx):
    from ..pdf import invoice_pdf
    inv = ctx["inv"]
    partner = q("SELECT * FROM partners WHERE id = ?", (inv["partner_id"],), one=True)
    return invoice_pdf(company(), inv, ctx["lines"], ctx["branch"], partner, currency_decimals(inv["currency"] or ctx["branch"]["currency"]),
                       ctx["residual"])


def invoice_file_name(inv):
    return f"{(inv['number'] or 'Draft').replace('/', '-')}.pdf"


@bp.route("/pdf/<int:inv_id>")
@login_required
def pdf(inv_id):
    from flask import Response
    ctx = invoice_context(inv_id)
    disposition = "attachment" if request.args.get("download") else "inline"
    return Response(invoice_pdf_bytes(ctx), mimetype="application/pdf",
                    headers={"Content-Disposition": f'{disposition}; filename="{invoice_file_name(ctx["inv"])}"'})


def email_defaults(ctx):
    """To, subject and message for sending a posted document to its partner."""
    from ..i18n import nm
    from ..money import fmt
    inv, info = ctx["inv"], ctx["info"]
    partner = q("SELECT * FROM partners WHERE id = ?", (inv["partner_id"],), one=True)
    co = nm(company())
    amount = f"{ctx['branch']['currency']} {fmt(inv['amount_total'], currency_decimals(ctx['branch']['currency']))}"
    body = (f"{t('Dear')} {nm(partner)},\n\n{t('Please find attached')} {t(info['label']).lower()} {inv['number']} "
            f"{t('dated')} {inv['date']} {t('for')} {amount}"
            + (f", {t('due on')} {inv['due_date']}" if inv["due_date"] and inv["kind"] == "out_invoice" else "")
            + f".\n\n{t('Kind regards')},\n{co}")
    return {"to": partner["email"] or "", "cc": "", "subject": f"{t(info['label'])} {inv['number']} — {co}", "body": body}


@bp.route("/bulk", methods=["POST"])
@write_required
def bulk():
    """Actions on the rows ticked in a list: post drafts, download PDFs (one zip), email to each partner."""
    import io
    import zipfile
    from flask import Response
    from ..db import get_db
    from ..mailer import send
    ids = [int(v) for v in request.form.getlist("ids") if v.isdigit()][:500]
    action = request.form.get("action")
    back = request.referrer if (request.referrer or "").startswith(request.host_url) else url_for("home.index")
    if not ids:
        flash(t("Tick at least one row."), "error")
        return redirect(back)
    done, problems = 0, []
    if action == "pdf":
        buf = io.BytesIO()
        with zipfile.ZipFile(buf, "w", zipfile.ZIP_DEFLATED) as z:
            for i in ids:
                ctx = invoice_context(i)
                if ctx["inv"]["state"] == "draft" and not ctx["inv"]["number"]:
                    continue
                z.writestr(invoice_file_name(ctx["inv"]), invoice_pdf_bytes(ctx))
                done += 1
        if not done:
            flash(t("Only posted documents have a PDF."), "error")
            return redirect(back)
        return Response(buf.getvalue(), mimetype="application/zip",
                        headers={"Content-Disposition": f'attachment; filename="documents-{date.today().isoformat()}.zip"'})
    db = get_db()
    for i in ids:
        inv = get_invoice(i)
        label = inv["number"] or f"{t('Draft')} #{i}"
        db.execute("SAVEPOINT bulk_one")
        try:
            if action == "post":
                if inv["state"] != "draft":
                    db.execute("RELEASE bulk_one")
                    continue
                check_vendor_ref(inv["partner_id"], inv["kind"], inv["ref"], i, posting=True)
                post_invoice(i, user_id())
                auto_picking(i)
            elif action == "email":
                if inv["state"] != "posted":
                    raise AccountingError(t("Only posted documents can be sent."))
                ctx = invoice_context(i)
                form = email_defaults(ctx)
                if not form["to"]:
                    raise AccountingError(t("The partner has no email address."))
                send(form["to"], form["subject"], form["body"],
                     [(invoice_file_name(ctx["inv"]), invoice_pdf_bytes(ctx), "application/pdf")], kind="invoice",
                     model="invoice", record_id=i, partner_id=inv["partner_id"], user_id=user_id())
            else:
                abort(400)
            db.execute("RELEASE bulk_one")
            done += 1
        except AccountingError as e:
            db.execute("ROLLBACK TO bulk_one")
            db.execute("RELEASE bulk_one")
            problems.append(f"{label}: {e}")
    commit()
    verb = {"post": t("posted"), "email": t("emailed")}.get(action, "")
    if done:
        flash(f"{done} " + t("documents") + f" {verb}.", "success")
    for p_ in problems[:10]:
        flash(p_, "error")
    if len(problems) > 10:
        flash(f"… {len(problems) - 10} " + t("more"), "error")
    return redirect(back)


@bp.route("/email/<int:inv_id>", methods=["GET", "POST"])
@write_required
def email(inv_id):
    from ..mailer import configured, send
    ctx = invoice_context(inv_id)
    inv, info = ctx["inv"], ctx["info"]
    if inv["state"] != "posted":
        flash(t("Only posted documents can be sent."), "error")
        return redirect(url_for("invoices.view", inv_id=inv_id))
    form = email_defaults(ctx)
    if request.method == "POST":
        form = {k: request.form.get(k, "") for k in form}
        try:
            send(form["to"], form["subject"], form["body"],
                 [(invoice_file_name(inv), invoice_pdf_bytes(ctx), "application/pdf")], cc=form["cc"], kind="invoice",
                 model="invoice", record_id=inv_id, partner_id=inv["partner_id"], user_id=user_id())
            commit()
            flash(t("Email sent."), "success")
            return redirect(url_for("invoices.view", inv_id=inv_id))
        except AccountingError as e:
            commit()  # keep the failed attempt in the email log
            flash(str(e), "error")
    return render_template("emails/compose.html", form=form, attachment=invoice_file_name(inv), mail_ready=configured(),
                           title=t("Email") + " " + (inv["number"] or ""), back=url_for("invoices.view", inv_id=inv_id),
                           hidden={})


@bp.route("/advances")
@login_required
def advances():
    """Customer advances invoiced, with what has been deducted on final invoices and what is left."""
    from .. import context_branch_ids
    from ..exports import Report, respond
    from ..i18n import nm
    from ..invoicetypes import advance_used
    ids = context_branch_ids()
    rows = []
    if ids:
        for a in q(f"SELECT i.*, p.name_en AS pname_en, p.name_ar AS pname_ar, b.currency AS bcur FROM invoices i "
                   f"JOIN partners p ON p.id = i.partner_id JOIN branches b ON b.id = i.branch_id WHERE i.kind = 'out_invoice' "
                   f"AND i.invoice_type = 'advance' AND i.state = 'posted' AND i.branch_id IN ({placeholders(ids)}) "
                   f"ORDER BY i.date DESC", list(ids)):
            used = advance_used(a["id"], posted_only=True)
            rows.append({**dict(a), "used": used, "left": a["amount_untaxed"] - used,
                         "residual": invoice_residuals([a["id"]]).get(a["id"], 0)})
    if request.args.get("open"):
        rows = [r for r in rows if r["left"] > 0]
    if request.args.get("export"):
        rep = Report("Customer Advances", [t("Amounts before VAT")], landscape=True)
        rep.column(t("Number")).column(t("Date")).column(t("Customer"), width=2).column(t("Advance"), "num") \
            .column(t("Deducted"), "num").column(t("Left to deduct"), "num").column(t("Not yet paid"), "num")
        for r in rows:
            rep.row([r["number"], r["date"], nm({"name_en": r["pname_en"], "name_ar": r["pname_ar"]}), r["amount_untaxed"],
                     r["used"], r["left"], r["residual"]])
        rep.row([t("Total"), "", "", sum(r["amount_untaxed"] for r in rows), sum(r["used"] for r in rows),
                 sum(r["left"] for r in rows), sum(r["residual"] for r in rows)], "grand")
        out = respond(rep, "customer-advances")
        if out:
            return out
    return render_template("invoices/advances.html", rows=rows, open_only=bool(request.args.get("open")))
