From cbe2c465ddcdfcf2695d4daad96e21726fdc1433 Mon Sep 17 00:00:00 2001 From: Dries Peeters Date: Sat, 14 Nov 2026 08:12:07 +0100 Subject: [PATCH 1/9] fix(invoicing): lock payment accounting and clarify invoice statuses Separate lifecycle status from payment settlement, stop marking drafts overdue, recompute paid amounts from the payment ledger, and treat overpayments explicitly so the dashboard and payment flows stay consistent. --- app/constants.py | 13 ++- app/repositories/invoice_repository.py | 19 +++- app/routes/api_v1_payments.py | 6 +- app/routes/main.py | 3 +- app/services/checkout_service.py | 14 +-- app/services/payment_gateway_service.py | 20 ++-- app/services/payment_service.py | 104 +++++++++++++++----- app/templates/invoices/_invoices_list.html | 2 + tests/test_invoices.py | 69 +++++++++++++ tests/test_scheduled_invoice_reports.py | 76 ++++++++++++++ tests/test_services/test_payment_service.py | 24 +++++ 11 files changed, 300 insertions(+), 50 deletions(-) diff --git a/app/constants.py b/app/constants.py index bffa1b098..233b5fda3 100644 --- a/app/constants.py +++ b/app/constants.py @@ -34,20 +34,18 @@ class ProjectStatus(Enum): class InvoiceStatus(Enum): - """Invoice status values""" + """Invoice lifecycle status values (not payment settlement).""" DRAFT = "draft" + ISSUED = "issued" SENT = "sent" PAID = "paid" OVERDUE = "overdue" CANCELLED = "cancelled" - PARTIALLY_PAID = "partially_paid" - FULLY_PAID = "fully_paid" - OVERPAID = "overpaid" class PaymentStatus(Enum): - """Payment status values""" + """Invoice payment settlement status values""" UNPAID = "unpaid" PARTIALLY_PAID = "partially_paid" @@ -161,8 +159,13 @@ class WebhookEvent(Enum): PROJECT_UPDATED = "project.updated" PROJECT_DELETED = "project.deleted" INVOICE_CREATED = "invoice.created" + INVOICE_UPDATED = "invoice.updated" + INVOICE_DELETED = "invoice.deleted" INVOICE_SENT = "invoice.sent" INVOICE_PAID = "invoice.paid" + INVOICE_OVERDUE = "invoice.overdue" + CREDIT_NOTE_CREATED = "credit_note.created" + PAYMENT_REFUNDED = "payment.refunded" TASK_CREATED = "task.created" TASK_UPDATED = "task.updated" TASK_DELETED = "task.deleted" diff --git a/app/repositories/invoice_repository.py b/app/repositories/invoice_repository.py index f8853b748..75b061989 100644 --- a/app/repositories/invoice_repository.py +++ b/app/repositories/invoice_repository.py @@ -52,10 +52,25 @@ def get_by_status(self, status: str, include_relations: bool = False) -> List[In return query.order_by(Invoice.issue_date.desc()).all() def get_overdue(self, include_relations: bool = False) -> List[Invoice]: - """Get overdue invoices""" + """Get overdue invoices (past due, not fully paid).""" today = date.today() + # PARTIALLY_PAID lives on PaymentStatus, not InvoiceStatus (lifecycle). + # Treat sent/issued/overdue invoices that are still unpaid or partially paid. query = self.model.query.filter( - Invoice.due_date < today, Invoice.status.in_([InvoiceStatus.SENT.value, InvoiceStatus.PARTIALLY_PAID.value]) + Invoice.due_date < today, + Invoice.status.in_( + [ + InvoiceStatus.SENT.value, + InvoiceStatus.ISSUED.value, + InvoiceStatus.OVERDUE.value, + ] + ), + Invoice.payment_status.in_( + [ + PaymentStatus.UNPAID.value, + PaymentStatus.PARTIALLY_PAID.value, + ] + ), ) if include_relations: diff --git a/app/routes/api_v1_payments.py b/app/routes/api_v1_payments.py index fede6bccc..54e7f2428 100644 --- a/app/routes/api_v1_payments.py +++ b/app/routes/api_v1_payments.py @@ -99,7 +99,11 @@ def create_payment(): trigger_payment_sync(result.get("payment")) except Exception: pass - return jsonify({"message": "Payment created successfully", "payment": result["payment"].to_dict()}), 201 + payload = {"message": "Payment created successfully", "payment": result["payment"].to_dict()} + if result.get("warning"): + payload["warning"] = result["warning"] + payload["overpayment"] = True + return jsonify(payload), 201 @api_v1_payments_bp.route("/payments/", methods=["PUT", "PATCH"]) diff --git a/app/routes/main.py b/app/routes/main.py index 3b4b05f8b..b1b1d1b96 100644 --- a/app/routes/main.py +++ b/app/routes/main.py @@ -389,8 +389,9 @@ def dashboard(): if is_module_enabled("invoices") and (current_user.is_admin or current_user.has_permission("create_invoices")): overdue_rows = ( Invoice.query.filter( - Invoice.status.in_(["sent", "overdue", "partially_paid"]), + Invoice.status.in_(["sent", "issued", "overdue"]), Invoice.due_date < today_date, + Invoice.payment_status.in_(["unpaid", "partially_paid"]), ) .order_by(Invoice.due_date.asc()) .all() diff --git a/app/services/checkout_service.py b/app/services/checkout_service.py index 357ddaf33..11a3c1453 100644 --- a/app/services/checkout_service.py +++ b/app/services/checkout_service.py @@ -67,6 +67,8 @@ def complete_webhook(self, gateway, payload: bytes, headers: dict): "payment_intent.succeeded", "checkout.session.completed", "PAYMENT.CAPTURE.COMPLETED", + # Mollie payment statuses that indicate a successful payment + "paid", ): return {"success": True, "message": "ignored", "status": 200} @@ -151,17 +153,17 @@ def _ensure_payment_ledger(self, webhook, gateway): if not invoice: return None - payment = Payment( + from app.services.payment_service import PaymentService + + result = PaymentService().create_payment( invoice_id=webhook.invoice_id, amount=webhook.amount or Decimal("0"), - currency=(webhook.currency or invoice.currency_code or "EUR").upper(), payment_date=date.today(), + received_by=invoice.created_by or 0, + currency=(webhook.currency or invoice.currency_code or "EUR").upper(), method=gateway.provider, reference=webhook.transaction_id, status="completed", - received_by=invoice.created_by, gateway_transaction_id=webhook.transaction_id, ) - db.session.add(payment) - safe_commit("checkout_payment_ledger", {"invoice_id": webhook.invoice_id}) - return payment + return result.get("payment") diff --git a/app/services/payment_gateway_service.py b/app/services/payment_gateway_service.py index b55fb3172..44040b12b 100644 --- a/app/services/payment_gateway_service.py +++ b/app/services/payment_gateway_service.py @@ -180,15 +180,13 @@ def update_transaction_status( if error_code: transaction.error_code = error_code - # Update invoice if payment completed or failed + # Invoice amount_paid is owned by Payment ledger rows (CheckoutService / + # PaymentService). Do not bump amount_paid here — that double-counted + # with the Payment row created after the webhook. if status == "completed" and old_status != "completed": invoice = Invoice.query.get(transaction.invoice_id) - if invoice: - invoice.amount_paid = (invoice.amount_paid or Decimal("0")) + transaction.amount - if invoice.amount_paid >= invoice.total_amount: - invoice.payment_status = "fully_paid" - invoice.status = "paid" - invoice.payment_date = now_in_app_timezone().date() + if invoice and not invoice.payment_date: + invoice.payment_date = now_in_app_timezone().date() if not safe_commit("update_transaction_status", {"transaction_id": transaction_id}): return {"success": False, "message": "Could not update transaction due to a database error."} @@ -203,9 +201,15 @@ def update_transaction_status( }, ) invoice = Invoice.query.get(transaction.invoice_id) - if invoice and invoice.payment_status == "fully_paid": + if invoice and invoice.payment_status in ("fully_paid", "overpaid"): + from app.utils.invoice_events import emit_invoice_event from app.utils.workflow_bridge import fire_invoice_paid_workflow + emit_invoice_event( + WebhookEvent.INVOICE_PAID.value, + invoice, + transaction_id=transaction.id, + ) fire_invoice_paid_workflow(invoice, invoice.created_by or 0) elif status == "failed": emit_event( diff --git a/app/services/payment_service.py b/app/services/payment_service.py index f0e7da087..9320d2be6 100644 --- a/app/services/payment_service.py +++ b/app/services/payment_service.py @@ -72,6 +72,13 @@ def create_payment( # Calculate net amount payment.calculate_net_amount() + overpayment_warning = None + outstanding = invoice.outstanding_amount + if status == "completed" and amount > outstanding and outstanding >= 0: + overpayment_warning = ( + f"Payment of {amount} exceeds outstanding amount of {outstanding}; invoice will be marked overpaid." + ) + # Update invoice payment status if payment is completed if status == "completed": # Flush so the new payment is counted once by the total below, as @@ -80,14 +87,9 @@ def create_payment( db.session.flush() total_payments = self.payment_repo.get_total_for_invoice(invoice_id) invoice.amount_paid = total_payments - - # Update payment status - if invoice.amount_paid >= invoice.total_amount: - invoice.payment_status = "fully_paid" - elif invoice.amount_paid > 0: - invoice.payment_status = "partially_paid" - else: - invoice.payment_status = "unpaid" + invoice.update_payment_status() + if invoice.payment_status in ("fully_paid", "overpaid"): + invoice.status = "paid" if not safe_commit("create_payment", {"invoice_id": invoice_id, "received_by": received_by}): return { @@ -99,9 +101,11 @@ def create_payment( # Emit domain event emit_event("payment.created", {"payment_id": payment.id, "invoice_id": invoice_id, "amount": float(amount)}) - if status == "completed" and invoice.payment_status == "fully_paid": + if status == "completed" and invoice.payment_status in ("fully_paid", "overpaid"): + from app.utils.invoice_events import emit_invoice_event from app.utils.workflow_bridge import fire_invoice_paid_workflow + emit_invoice_event(WebhookEvent.INVOICE_PAID.value, invoice, payment_id=payment.id) fire_invoice_paid_workflow(invoice, received_by) # Notify client about payment received @@ -128,7 +132,47 @@ def create_payment( "Failed to send client survey for payment %s: %s", payment.id, e, exc_info=True ) - return {"success": True, "message": "Payment created successfully", "payment": payment} + # Send payment receipt email to client if configured and email is available + if status == "completed" and invoice.client_email: + try: + self._send_receipt_email(invoice, payment) + except Exception as exc: + import logging as _logging + + _logging.getLogger(__name__).error( + "Failed to send payment receipt email for payment %s: %s", payment.id, exc, exc_info=True + ) + + result = {"success": True, "message": "Payment created successfully", "payment": payment} + if overpayment_warning: + result["warning"] = overpayment_warning + result["overpayment"] = True + return result + + def _send_receipt_email(self, invoice, payment) -> None: + """Send a payment receipt email to the invoice client. Errors are silently logged.""" + from app.models import Settings + + settings = Settings.get_settings() + # Respect optional setting flag (default True when attribute missing) + send_flag = getattr(settings, "send_payment_receipt_email", True) + if not send_flag: + return + + from app.utils.email import send_template_email + + send_template_email( + to=invoice.client_email, + subject=f"Payment Receipt — Invoice {invoice.invoice_number}", + template="email/payment_receipt.html", + client_name=invoice.client_name or "", + invoice_number=invoice.invoice_number or str(invoice.id), + amount=payment.amount, + currency=payment.currency or invoice.currency_code or "EUR", + payment_date=str(payment.payment_date), + payment_method=payment.method or "", + reference=payment.reference or "", + ) def get_invoice_payments(self, invoice_id: int) -> List[Payment]: """Get all payments for an invoice""" @@ -150,6 +194,7 @@ def update_payment(self, payment_id: int, user_id: int, **kwargs) -> Dict[str, A return {"success": False, "message": "Payment not found", "error": "not_found"} was_completed = payment.status == "completed" + previous_status = payment.status # Update fields for field in ("currency", "method", "reference", "notes", "status"): @@ -163,6 +208,7 @@ def update_payment(self, payment_id: int, user_id: int, **kwargs) -> Dict[str, A # Recalculate net amount payment.calculate_net_amount() + became_fully_paid = False # Recompute the invoice whenever the payment counts or used to count: # a completed payment moved to refunded, failed or pending must drop # out of amount_paid, as it does in delete_payment. @@ -170,14 +216,12 @@ def update_payment(self, payment_id: int, user_id: int, **kwargs) -> Dict[str, A db.session.flush() total_payments = self.payment_repo.get_total_for_invoice(payment.invoice_id) payment.invoice.amount_paid = total_payments - - # Update payment status (same order as delete_payment) - if payment.invoice.amount_paid <= 0: - payment.invoice.payment_status = "unpaid" - elif payment.invoice.amount_paid >= payment.invoice.total_amount: - payment.invoice.payment_status = "fully_paid" - else: - payment.invoice.payment_status = "partially_paid" + payment.invoice.update_payment_status() + if payment.invoice.payment_status in ("fully_paid", "overpaid"): + payment.invoice.status = "paid" + became_fully_paid = True + elif payment.invoice.status == "paid" and payment.invoice.payment_status == "partially_paid": + payment.invoice.status = "sent" if not safe_commit("update_payment", {"payment_id": payment_id, "user_id": user_id}): return { @@ -186,6 +230,16 @@ def update_payment(self, payment_id: int, user_id: int, **kwargs) -> Dict[str, A "error": "database_error", } + if payment.status == "refunded" and previous_status != "refunded": + from app.utils.invoice_events import emit_payment_event + + emit_payment_event(WebhookEvent.PAYMENT_REFUNDED.value, payment) + + if became_fully_paid and payment.invoice: + from app.utils.invoice_events import emit_invoice_event + + emit_invoice_event(WebhookEvent.INVOICE_PAID.value, payment.invoice, payment_id=payment.id) + return {"success": True, "message": "Payment updated successfully", "payment": payment} def delete_payment(self, payment_id: int, user_id: int) -> Dict[str, Any]: @@ -213,15 +267,11 @@ def delete_payment(self, payment_id: int, user_id: int) -> Dict[str, Any]: if invoice: total_payments = self.payment_repo.get_total_for_invoice(invoice_id) invoice.amount_paid = total_payments - - # No remaining payment means unpaid regardless of the invoice total - # (a 0 total must not read as "fully_paid" when nothing was paid). - if invoice.amount_paid <= 0: - invoice.payment_status = "unpaid" - elif invoice.amount_paid >= invoice.total_amount: - invoice.payment_status = "fully_paid" - else: - invoice.payment_status = "partially_paid" + invoice.update_payment_status() + if invoice.payment_status in ("fully_paid", "overpaid"): + invoice.status = "paid" + elif invoice.status == "paid" and invoice.payment_status != "fully_paid": + invoice.status = "sent" if not safe_commit("delete_payment", {"payment_id": payment_id, "user_id": user_id}): return { diff --git a/app/templates/invoices/_invoices_list.html b/app/templates/invoices/_invoices_list.html index 5dd5eef8d..a365ab7ff 100644 --- a/app/templates/invoices/_invoices_list.html +++ b/app/templates/invoices/_invoices_list.html @@ -118,9 +118,11 @@

View + {% if invoice.status == 'draft' %} Edit + {% endif %} Download PDF diff --git a/tests/test_invoices.py b/tests/test_invoices.py index f592c73e0..818a1925f 100644 --- a/tests/test_invoices.py +++ b/tests/test_invoices.py @@ -2423,3 +2423,72 @@ def test_delete_invoice_with_complex_data_smoke(app, client, user, project): # Verify invoice and all related data are deleted assert Invoice.query.get(invoice_id) is None + + +@pytest.mark.routes +def test_edit_sent_invoice_locks_financial_fields(app, client, user, project): + """Sent invoices cannot change amounts or line items; notes/due date still update.""" + with client.session_transaction() as sess: + sess["_user_id"] = str(user.id) + sess["_fresh"] = True + + cl = ClientFactory(name="Lock Test Client", email="lock@test.com") + db.session.commit() + + inv = InvoiceFactory( + invoice_number="INV-LOCK-001", + project_id=project.id, + client_name=cl.name, + client_id=cl.id, + due_date=date.today() + timedelta(days=14), + created_by=user.id, + tax_rate=Decimal("10.00"), + notes="Original notes", + terms="Original terms", + client_email="lock@test.com", + ) + # Invoice.__init__ ignores status kwargs from the factory + inv.status = "sent" + db.session.commit() + InvoiceItemFactory( + invoice_id=inv.id, description="Line A", quantity=Decimal("2.00"), unit_price=Decimal("50.00") + ) + db.session.commit() + inv.calculate_totals() + db.session.commit() + original_total = inv.total_amount + original_tax = inv.tax_rate + + resp = client.post( + f"/invoices/{inv.id}/edit", + data={ + "client_name": "Hacked Name", + "client_email": "hacked@test.com", + "client_address": inv.client_address or "", + "due_date": (date.today() + timedelta(days=30)).strftime("%Y-%m-%d"), + "tax_rate": "99.00", + "notes": "Updated notes only", + "terms": "Updated terms", + "description[]": ["Should Not Apply"], + "quantity[]": ["99"], + "unit_price[]": ["999"], + }, + follow_redirects=True, + ) + assert resp.status_code == 200 + db.session.refresh(inv) + assert inv.client_name == cl.name + assert inv.tax_rate == original_tax + assert inv.total_amount == original_total + assert inv.notes == "Updated notes only" + assert inv.terms == "Updated terms" + assert inv.due_date == date.today() + timedelta(days=30) + assert inv.items.count() == 1 + + +def test_invoice_status_enum_has_issued(app): + from app.constants import InvoiceStatus, PaymentStatus + + assert InvoiceStatus.ISSUED.value == "issued" + assert "partially_paid" not in {s.value for s in InvoiceStatus} + assert PaymentStatus.OVERPAID.value == "overpaid" diff --git a/tests/test_scheduled_invoice_reports.py b/tests/test_scheduled_invoice_reports.py index 8ecb0301a..2023e2283 100644 --- a/tests/test_scheduled_invoice_reports.py +++ b/tests/test_scheduled_invoice_reports.py @@ -44,3 +44,79 @@ def test_generate_report_data_uses_invoice_data_source(app, invoice_report_view) data = service._generate_report_data(view, config, user_id=user.id) assert data.get("message") != "Invoice reports not yet implemented" assert "data" in data + + +def test_check_overdue_skips_draft_and_paid(app, user, project): + """Overdue job must not mark draft invoices overdue, and must skip fully paid.""" + from datetime import date, timedelta + from decimal import Decimal + + from app import db + from app.models import Invoice + from app.utils.scheduled_tasks import check_overdue_invoices + from factories import ClientFactory, InvoiceFactory + + client = ClientFactory(name="Overdue Job Client") + db.session.commit() + past = date.today() - timedelta(days=10) + + draft = InvoiceFactory( + invoice_number="INV-OD-DRAFT", + project_id=project.id, + client_id=client.id, + client_name=client.name, + created_by=user.id, + due_date=past, + total_amount=Decimal("100.00"), + ) + draft.status = "draft" + draft.payment_status = "unpaid" + + sent = InvoiceFactory( + invoice_number="INV-OD-SENT", + project_id=project.id, + client_id=client.id, + client_name=client.name, + created_by=user.id, + due_date=past, + total_amount=Decimal("100.00"), + ) + sent.status = "sent" + sent.payment_status = "unpaid" + + paid = InvoiceFactory( + invoice_number="INV-OD-PAID", + project_id=project.id, + client_id=client.id, + client_name=client.name, + created_by=user.id, + due_date=past, + total_amount=Decimal("100.00"), + ) + paid.status = "sent" + paid.payment_status = "fully_paid" + paid.amount_paid = Decimal("100.00") + + issued = InvoiceFactory( + invoice_number="INV-OD-ISSUED", + project_id=project.id, + client_id=client.id, + client_name=client.name, + created_by=user.id, + due_date=past, + total_amount=Decimal("100.00"), + ) + issued.status = "issued" + issued.payment_status = "unpaid" + db.session.commit() + + check_overdue_invoices() + db.session.refresh(draft) + db.session.refresh(sent) + db.session.refresh(paid) + db.session.refresh(issued) + + assert draft.status == "draft" + assert sent.status == "overdue" + assert paid.status == "sent" + assert issued.status == "overdue" diff --git a/tests/test_services/test_payment_service.py b/tests/test_services/test_payment_service.py index 32fdeba92..d9a838a66 100644 --- a/tests/test_services/test_payment_service.py +++ b/tests/test_services/test_payment_service.py @@ -89,3 +89,27 @@ def test_get_total_paid(self, db_session, invoice, user): total = service.get_total_paid(invoice.id) assert total == Decimal("100.00") + + +def test_create_payment_sets_overpaid_status(db_session, invoice, user): + """Overpaying an invoice sets payment_status to overpaid and returns a warning.""" + invoice.total_amount = Decimal("100.00") + invoice.amount_paid = Decimal("0") + invoice.payment_status = "unpaid" + db_session.commit() + + service = PaymentService() + result = service.create_payment( + invoice_id=invoice.id, + amount=Decimal("150.00"), + payment_date=date.today(), + received_by=user.id, + ) + + assert result["success"] is True + assert result.get("overpayment") is True + assert "warning" in result + db_session.refresh(invoice) + assert invoice.payment_status == "overpaid" + assert invoice.amount_paid == Decimal("150.00") + assert invoice.status == "paid" From 83b1c75bd5c1e539e0756d2035782f5a1940e006 Mon Sep 17 00:00:00 2001 From: Dries Peeters Date: Sat, 14 Nov 2026 08:12:07 +0100 Subject: [PATCH 2/9] feat(invoicing): add per-line tax rates, discounts, and ordering Support mixed VAT rates and allowances on invoice lines, keep a tax breakdown for Peppol/CII/FatturaPA/XRechnung exports, and lock financial edits on non-draft invoices while still allowing notes and due-date updates. --- app/integrations/peppol.py | 215 ++++++++- app/models/invoice.py | 218 ++++++++- app/routes/invoices.py | 127 +++++- app/schemas/invoice_schema.py | 7 + app/services/invoice_service.py | 42 +- app/templates/invoices/create.html | 8 + app/templates/invoices/edit.html | 111 ++++- app/templates/invoices/pdf_default.html | 37 +- app/utils/cii_invoice.py | 111 ++++- app/utils/fatturapa.py | 175 ++++++- app/utils/xrechnung.py | 23 + .../210_invoice_line_tax_discounts.py | 90 ++++ tests/test_invoice_line_tax_discounts.py | 431 ++++++++++++++++++ 13 files changed, 1515 insertions(+), 80 deletions(-) create mode 100644 migrations/versions/210_invoice_line_tax_discounts.py create mode 100644 tests/test_invoice_line_tax_discounts.py diff --git a/app/integrations/peppol.py b/app/integrations/peppol.py index c831e312c..152cc2946 100644 --- a/app/integrations/peppol.py +++ b/app/integrations/peppol.py @@ -256,26 +256,48 @@ def build_peppol_ubl_invoice_xml( _party(inv_el, "AccountingSupplierParty", supplier) _party(inv_el, "AccountingCustomerParty", customer) - # Tax total (best-effort based on current Invoice model fields) + # Tax total — use tax_breakdown() for multi-rate support, fall back to flat rate tax_total = ET.SubElement(inv_el, cac + "TaxTotal") tax_amount_el = ET.SubElement(tax_total, cbc + "TaxAmount") tax_amount_el.set("currencyID", currency) tax_amount_el.text = _money(getattr(invoice, "tax_amount", 0)) tax_rate = Decimal(str(getattr(invoice, "tax_rate", 0) or 0)) - tax_sub = ET.SubElement(tax_total, cac + "TaxSubtotal") - taxable_amount_el = ET.SubElement(tax_sub, cbc + "TaxableAmount") - taxable_amount_el.set("currencyID", currency) - taxable_amount_el.text = _money(getattr(invoice, "subtotal", 0)) - tax_sub_amount_el = ET.SubElement(tax_sub, cbc + "TaxAmount") - tax_sub_amount_el.set("currencyID", currency) - tax_sub_amount_el.text = _money(getattr(invoice, "tax_amount", 0)) - - tax_cat = ET.SubElement(tax_sub, cac + "TaxCategory") - _text(tax_cat, cbc + "ID", "S" if tax_rate > 0 else "Z") - _text(tax_cat, cbc + "Percent", _money(tax_rate)) - tax_scheme = ET.SubElement(tax_cat, cac + "TaxScheme") - _text(tax_scheme, cbc + "ID", "VAT") + try: + breakdown = invoice.tax_breakdown() if hasattr(invoice, "tax_breakdown") else [] + except Exception: + breakdown = [] + + if breakdown: + for grp in breakdown: + tax_sub = ET.SubElement(tax_total, cac + "TaxSubtotal") + taxable_amount_el = ET.SubElement(tax_sub, cbc + "TaxableAmount") + taxable_amount_el.set("currencyID", currency) + taxable_amount_el.text = _money(grp["taxable"]) + tax_sub_amount_el = ET.SubElement(tax_sub, cbc + "TaxAmount") + tax_sub_amount_el.set("currencyID", currency) + tax_sub_amount_el.text = _money(grp["tax"]) + tax_cat = ET.SubElement(tax_sub, cac + "TaxCategory") + grp_rate = Decimal(str(grp.get("rate", 0))) + grp_cat = grp.get("category") or ("S" if grp_rate > 0 else "Z") + _text(tax_cat, cbc + "ID", grp_cat) + _text(tax_cat, cbc + "Percent", _money(grp_rate)) + tax_scheme = ET.SubElement(tax_cat, cac + "TaxScheme") + _text(tax_scheme, cbc + "ID", "VAT") + else: + # Fallback: single subtotal + tax_sub = ET.SubElement(tax_total, cac + "TaxSubtotal") + taxable_amount_el = ET.SubElement(tax_sub, cbc + "TaxableAmount") + taxable_amount_el.set("currencyID", currency) + taxable_amount_el.text = _money(getattr(invoice, "subtotal", 0)) + tax_sub_amount_el = ET.SubElement(tax_sub, cbc + "TaxAmount") + tax_sub_amount_el.set("currencyID", currency) + tax_sub_amount_el.text = _money(getattr(invoice, "tax_amount", 0)) + tax_cat = ET.SubElement(tax_sub, cac + "TaxCategory") + _text(tax_cat, cbc + "ID", "S" if tax_rate > 0 else "Z") + _text(tax_cat, cbc + "Percent", _money(tax_rate)) + tax_scheme = ET.SubElement(tax_cat, cac + "TaxScheme") + _text(tax_scheme, cbc + "ID", "VAT") # Monetary totals legal_total = ET.SubElement(inv_el, cac + "LegalMonetaryTotal") @@ -306,7 +328,14 @@ def build_peppol_ubl_invoice_xml( # Invoice lines (items + expenses + extra goods) line_id = 1 - def _add_line(description: str, quantity: Any, unit_price: Any, line_total: Any) -> None: + def _add_line( + description: str, + quantity: Any, + unit_price: Any, + line_total: Any, + line_tax_rate: Optional[Decimal] = None, + line_vat_category: Optional[str] = None, + ) -> None: nonlocal line_id il = ET.SubElement(inv_el, cac + "InvoiceLine") _text(il, cbc + "ID", str(line_id)) @@ -320,11 +349,12 @@ def _add_line(description: str, quantity: Any, unit_price: Any, line_total: Any) item_el = ET.SubElement(il, cac + "Item") _text(item_el, cbc + "Name", description[:200]) - # Each line needs exactly one ClassifiedTaxCategory (BT-151, BR-CO-04/UBL-SR-48); - # mirrors the document-level VAT category so BR-S-01/BR-S-08 tie out. + # Each line needs exactly one ClassifiedTaxCategory (BT-151, BR-CO-04/UBL-SR-48) + eff_rate = line_tax_rate if line_tax_rate is not None else tax_rate + eff_cat = line_vat_category or ("S" if eff_rate > 0 else "Z") line_tax_cat = ET.SubElement(item_el, cac + "ClassifiedTaxCategory") - _text(line_tax_cat, cbc + "ID", "S" if tax_rate > 0 else "Z") - _text(line_tax_cat, cbc + "Percent", _money(tax_rate)) + _text(line_tax_cat, cbc + "ID", eff_cat) + _text(line_tax_cat, cbc + "Percent", _money(eff_rate)) line_tax_scheme = ET.SubElement(line_tax_cat, cac + "TaxScheme") _text(line_tax_scheme, cbc + "ID", "VAT") @@ -338,11 +368,20 @@ def _add_line(description: str, quantity: Any, unit_price: Any, line_total: Any) # Invoice items try: for it in list(getattr(invoice, "items", []) or []): + _it_tax = None + if getattr(it, "tax_rate", None) is not None: + _it_tax = Decimal(str(it.tax_rate)) + _it_cat = getattr(it, "vat_category", None) or None + _line_total = getattr(it, "line_net", None) + if _line_total is None: + _line_total = getattr(it, "total_amount", 0) _add_line( description=getattr(it, "description", "Item"), quantity=getattr(it, "quantity", 1), unit_price=getattr(it, "unit_price", 0), - line_total=getattr(it, "total_amount", 0), + line_total=_line_total, + line_tax_rate=_it_tax, + line_vat_category=_it_cat, ) except Exception: pass @@ -453,3 +492,139 @@ def send_ubl_via_access_point( raise PeppolAccessPointError(f"Access point returned HTTP {resp.status_code}: {data}") return {"status_code": resp.status_code, "data": data} + + +def build_peppol_ubl_credit_note_xml( + credit_note, + invoice, + supplier: PeppolParty, + customer: PeppolParty, +) -> Tuple[str, str]: + """Build a Peppol BIS 3 UBL CreditNote (document type 381) with BillingReference. + + Returns (xml_string, document_id). + """ + nsmap = { + "": "urn:oasis:names:specification:ubl:schema:xsd:CreditNote-2", + "cac": "urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2", + "cbc": "urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2", + } + # ElementTree does not support default nsmap the same way; use Clark notation. + ubl_ns = "urn:oasis:names:specification:ubl:schema:xsd:CreditNote-2" + cac = "{urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2}" + cbc = "{urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2}" + + root = ET.Element(f"{{{ubl_ns}}}CreditNote") + root.set("xmlns", ubl_ns) + root.set("xmlns:cac", "urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2") + root.set("xmlns:cbc", "urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2") + + _text(root, cbc + "CustomizationID", PEPPOL_BIS3_CUSTOMIZATION_ID) + _text(root, cbc + "ProfileID", PEPPOL_BIS3_PROFILE_ID) + doc_id = getattr(credit_note, "credit_number", None) or str(getattr(credit_note, "id", "")) + _text(root, cbc + "ID", doc_id) + + issue_date = getattr(credit_note, "issue_date", None) or date.today() + if hasattr(issue_date, "isoformat"): + _text(root, cbc + "IssueDate", issue_date.isoformat()) + + _text(root, cbc + "CreditNoteTypeCode", "381") + + notes = getattr(credit_note, "reason", None) or getattr(credit_note, "notes", None) + if notes: + _text(root, cbc + "Note", notes) + + currency = getattr(credit_note, "currency_code", None) or getattr(invoice, "currency_code", None) or "EUR" + _text(root, cbc + "DocumentCurrencyCode", currency) + + # Billing reference to original invoice + inv_number = getattr(invoice, "invoice_number", None) or str(getattr(invoice, "id", "")) + billing_ref = ET.SubElement(root, cac + "BillingReference") + inv_doc_ref = ET.SubElement(billing_ref, cac + "InvoiceDocumentReference") + _text(inv_doc_ref, cbc + "ID", inv_number) + inv_issue = getattr(invoice, "issue_date", None) + if inv_issue and hasattr(inv_issue, "isoformat"): + _text(inv_doc_ref, cbc + "IssueDate", inv_issue.isoformat()) + + _party(root, "AccountingSupplierParty", supplier) + _party(root, "AccountingCustomerParty", customer) + + tax_total = ET.SubElement(root, cac + "TaxTotal") + tax_amount_el = ET.SubElement(tax_total, cbc + "TaxAmount") + tax_amount_el.set("currencyID", currency) + tax_amount_el.text = _money(getattr(credit_note, "tax_amount", 0) or 0) + + tax_rate = Decimal(str(getattr(credit_note, "tax_rate", 0) or getattr(invoice, "tax_rate", 0) or 0)) + tax_sub = ET.SubElement(tax_total, cac + "TaxSubtotal") + taxable_amount_el = ET.SubElement(tax_sub, cbc + "TaxableAmount") + taxable_amount_el.set("currencyID", currency) + taxable_amount_el.text = _money(getattr(credit_note, "subtotal", 0) or 0) + tax_sub_amount_el = ET.SubElement(tax_sub, cbc + "TaxAmount") + tax_sub_amount_el.set("currencyID", currency) + tax_sub_amount_el.text = _money(getattr(credit_note, "tax_amount", 0) or 0) + tax_cat = ET.SubElement(tax_sub, cac + "TaxCategory") + _text(tax_cat, cbc + "ID", "S" if tax_rate > 0 else "Z") + _text(tax_cat, cbc + "Percent", _money(tax_rate)) + tax_scheme = ET.SubElement(tax_cat, cac + "TaxScheme") + _text(tax_scheme, cbc + "ID", "VAT") + + legal_total = ET.SubElement(root, cac + "LegalMonetaryTotal") + for tag, val in ( + ("LineExtensionAmount", getattr(credit_note, "subtotal", 0) or 0), + ("TaxExclusiveAmount", getattr(credit_note, "subtotal", 0) or 0), + ("TaxInclusiveAmount", getattr(credit_note, "total_amount", 0) or getattr(credit_note, "amount", 0) or 0), + ("PayableAmount", getattr(credit_note, "total_amount", 0) or getattr(credit_note, "amount", 0) or 0), + ): + el = ET.SubElement(legal_total, cbc + tag) + el.set("currencyID", currency) + el.text = _money(val) + + items = credit_note.items.all() if hasattr(credit_note.items, "all") else list(credit_note.items or []) + items = sorted(items, key=lambda x: getattr(x, "position", 0) or 0) + for idx, item in enumerate(items, start=1): + cl = ET.SubElement(root, cac + "CreditNoteLine") + _text(cl, cbc + "ID", str(idx)) + qty_el = ET.SubElement(cl, cbc + "CreditedQuantity") + qty_el.set("unitCode", "C62") + qty_el.text = _qty(getattr(item, "quantity", 1)) + lea = ET.SubElement(cl, cbc + "LineExtensionAmount") + lea.set("currencyID", currency) + lea.text = _money(getattr(item, "total_amount", 0)) + item_el = ET.SubElement(cl, cac + "Item") + _text(item_el, cbc + "Name", getattr(item, "description", "") or f"Line {idx}") + line_tax_cat = ET.SubElement(item_el, cac + "ClassifiedTaxCategory") + item_rate = Decimal(str(item.tax_rate if getattr(item, "tax_rate", None) is not None else tax_rate)) + _text(line_tax_cat, cbc + "ID", "S" if item_rate > 0 else "Z") + _text(line_tax_cat, cbc + "Percent", _money(item_rate)) + ts = ET.SubElement(line_tax_cat, cac + "TaxScheme") + _text(ts, cbc + "ID", "VAT") + price = ET.SubElement(cl, cac + "Price") + pa = ET.SubElement(price, cbc + "PriceAmount") + pa.set("currencyID", currency) + pa.text = _money(getattr(item, "unit_price", 0)) + + if not items: + # Amount-only credit: single synthetic line + cl = ET.SubElement(root, cac + "CreditNoteLine") + _text(cl, cbc + "ID", "1") + qty_el = ET.SubElement(cl, cbc + "CreditedQuantity") + qty_el.set("unitCode", "C62") + qty_el.text = "1.00" + lea = ET.SubElement(cl, cbc + "LineExtensionAmount") + lea.set("currencyID", currency) + amount = getattr(credit_note, "subtotal", None) or getattr(credit_note, "amount", 0) or 0 + lea.text = _money(amount) + item_el = ET.SubElement(cl, cac + "Item") + _text(item_el, cbc + "Name", getattr(credit_note, "reason", None) or "Credit") + line_tax_cat = ET.SubElement(item_el, cac + "ClassifiedTaxCategory") + _text(line_tax_cat, cbc + "ID", "S" if tax_rate > 0 else "Z") + _text(line_tax_cat, cbc + "Percent", _money(tax_rate)) + ts = ET.SubElement(line_tax_cat, cac + "TaxScheme") + _text(ts, cbc + "ID", "VAT") + price = ET.SubElement(cl, cac + "Price") + pa = ET.SubElement(price, cbc + "PriceAmount") + pa.set("currencyID", currency) + pa.text = _money(amount) + + xml_bytes = ET.tostring(root, encoding="utf-8", xml_declaration=True) + return xml_bytes.decode("utf-8"), doc_id diff --git a/app/models/invoice.py b/app/models/invoice.py index fd0f4bc8b..892e77314 100644 --- a/app/models/invoice.py +++ b/app/models/invoice.py @@ -58,10 +58,19 @@ class Invoice(db.Model): vat_exemption_reason = db.Column(db.Text, nullable=True) vat_exemption_code = db.Column(db.String(50), nullable=True) + # Invoice-level discounts (applied after line discounts, before tax) + discount_percent = db.Column(db.Numeric(5, 2), nullable=True, default=0) + discount_amount = db.Column(db.Numeric(10, 2), nullable=True, default=0) + # Italian public-administration procurement codes (FatturaPA DatiOrdineAcquisto) cig = db.Column(db.String(15), nullable=True) cup = db.Column(db.String(15), nullable=True) + # Reminder policy (optional per-invoice override; falls back to client then default) + reminder_policy_id = db.Column(db.Integer, db.ForeignKey("reminder_policies.id"), nullable=True) + # Accumulated late fees added by the reminder service + late_fee_amount = db.Column(db.Numeric(10, 2), nullable=False, default=0) + # Metadata created_by = db.Column(db.Integer, db.ForeignKey("users.id"), nullable=False) created_at = db.Column(db.DateTime, default=datetime.utcnow, nullable=False) @@ -114,6 +123,10 @@ def __init__(self, invoice_number, project_id, client_name, due_date, created_by self.vat_exemption_code = kwargs.get("vat_exemption_code") self.cig = kwargs.get("cig") self.cup = kwargs.get("cup") + if "discount_percent" in kwargs and kwargs.get("discount_percent") is not None: + self.discount_percent = Decimal(str(kwargs["discount_percent"])) + if "discount_amount" in kwargs and kwargs.get("discount_amount") is not None: + self.discount_amount = Decimal(str(kwargs["discount_amount"])) if "subtotal" in kwargs and kwargs.get("subtotal") is not None: self.subtotal = Decimal(str(kwargs["subtotal"])) if "tax_amount" in kwargs and kwargs.get("tax_amount") is not None: @@ -127,7 +140,7 @@ def __repr__(self): @property def is_overdue(self): """Check if invoice is overdue""" - return self.status in ["sent", "overdue"] and datetime.utcnow().date() > self.due_date + return self.status in ["sent", "issued", "overdue"] and datetime.utcnow().date() > self.due_date @property def days_overdue(self): @@ -148,9 +161,10 @@ def is_partially_paid(self): @property def outstanding_amount(self): - """Calculate outstanding amount""" + """Calculate outstanding amount including any accrued late fees.""" credits_total = sum((c.amount for c in self.credits), Decimal("0")) if self.credits else Decimal("0") - return self.total_amount - (self.amount_paid or 0) - credits_total + late_fee = Decimal(str(self.late_fee_amount or 0)) + return self.total_amount + late_fee - (self.amount_paid or 0) - credits_total @property def payment_percentage(self): @@ -251,21 +265,143 @@ def release_invoiced_costs_and_expenses(self): db.session.delete(consumption) def calculate_totals(self): - """Calculate invoice totals from items, extra goods, and expenses""" + """Calculate invoice totals from items, extra goods, and expenses. + + Supports per-line tax rates (item.tax_rate), per-line discounts + (item.discount_percent / item.discount_amount), and invoice-level + discounts (self.discount_percent / self.discount_amount). + + Groups taxable amounts by (vat_category, rate) so multi-rate invoices + produce a correct tax_breakdown() for e-invoice exporters. + """ # Optionally apply tax rules before totals (failures logged inside helper) self._apply_tax_rules_if_any() - items_total = sum(item.total_amount for item in self.items) - goods_total = sum(good.total_amount for good in self.extra_goods) - expenses_total = sum(expense.total_amount for expense in self.expenses) - subtotal = items_total + goods_total + expenses_total + + # --- Per-item line nets --- + items_net = Decimal("0") + # Build tax groups keyed by (vat_category, rate) + tax_groups: dict = {} + inv_tax_rate = Decimal(str(self.tax_rate or 0)) + inv_vat_cat = (self.vat_category or "S").upper() + + try: + for item in self.items: + lnet = item.line_net + items_net += lnet + rate = item.effective_tax_rate(self) + cat = (item.vat_category or inv_vat_cat).upper() + key = (cat, rate) + tax_groups[key] = tax_groups.get(key, Decimal("0")) + lnet + except Exception: + # Fallback: use stored total_amount for each item without grouping + items_net = sum(item.total_amount for item in self.items) + tax_groups = {(inv_vat_cat, inv_tax_rate): items_net} + + # --- Goods & expenses use invoice-level tax --- + goods_total = Decimal("0") + expenses_total = Decimal("0") + try: + goods_total = sum(good.total_amount for good in self.extra_goods) + except Exception: + pass + try: + expenses_total = sum(expense.total_amount for expense in self.expenses) + except Exception: + pass + + inv_other = goods_total + expenses_total + if inv_other: + key = (inv_vat_cat, inv_tax_rate) + tax_groups[key] = tax_groups.get(key, Decimal("0")) + inv_other + + combined_net = items_net + goods_total + expenses_total + + # --- Invoice-level discount --- + inv_disc = Decimal(str(self.discount_amount or 0)) + if not inv_disc: + inv_disc_pct = Decimal(str(self.discount_percent or 0)) + if inv_disc_pct and combined_net: + inv_disc = combined_net * (inv_disc_pct / 100) + + subtotal = combined_net - inv_disc self.subtotal = subtotal - self.tax_amount = subtotal * (self.tax_rate / 100) + + # Distribute invoice discount proportionally across tax groups + if inv_disc and combined_net: + disc_ratio = inv_disc / combined_net + tax_groups = {k: v * (1 - disc_ratio) for k, v in tax_groups.items()} + + # --- Compute tax --- + tax_amount = Decimal("0") + for (cat, rate), taxable in tax_groups.items(): + tax_amount += taxable * (rate / 100) + + self.tax_amount = tax_amount.quantize(Decimal("0.01")) self.total_amount = subtotal + self.tax_amount # Update status if overdue if self.status == "sent" and self.is_overdue: self.status = "overdue" + def tax_breakdown(self): + """Return per-rate tax grouping suitable for e-invoice exporters. + + Returns a list of dicts sorted by (category, rate): + [{"category": "S", "rate": 20.0, "taxable": 100.00, "tax": 20.00}, ...] + """ + inv_tax_rate = Decimal(str(self.tax_rate or 0)) + inv_vat_cat = (self.vat_category or "S").upper() + groups: dict = {} + + try: + for item in self.items: + lnet = item.line_net + rate = item.effective_tax_rate(self) + cat = (item.vat_category or inv_vat_cat).upper() + key = (cat, rate) + groups[key] = groups.get(key, Decimal("0")) + lnet + except Exception: + groups = {(inv_vat_cat, inv_tax_rate): sum(item.total_amount for item in self.items)} + + try: + goods_total = sum(good.total_amount for good in self.extra_goods) + except Exception: + goods_total = Decimal("0") + try: + expenses_total = sum(expense.total_amount for expense in self.expenses) + except Exception: + expenses_total = Decimal("0") + + inv_other = goods_total + expenses_total + if inv_other: + key = (inv_vat_cat, inv_tax_rate) + groups[key] = groups.get(key, Decimal("0")) + inv_other + + # Apply invoice discount proportionally + combined = sum(groups.values()) + inv_disc = Decimal(str(self.discount_amount or 0)) + if not inv_disc: + inv_disc_pct = Decimal(str(self.discount_percent or 0)) + if inv_disc_pct and combined: + inv_disc = combined * (inv_disc_pct / 100) + if inv_disc and combined: + disc_ratio = inv_disc / combined + groups = {k: v * (1 - disc_ratio) for k, v in groups.items()} + + result = [] + for (cat, rate), taxable in sorted(groups.items(), key=lambda x: (x[0][0], float(x[0][1]))): + taxable_q = taxable.quantize(Decimal("0.01")) + tax_q = (taxable * (rate / 100)).quantize(Decimal("0.01")) + result.append( + { + "category": cat, + "rate": float(rate), + "taxable": float(taxable_q), + "tax": float(tax_q), + } + ) + return result + def _apply_tax_rules_if_any(self): """Apply matching tax rule to set `tax_rate` if applicable. Chooses the most specific active rule by client->project->country/region. @@ -328,6 +464,8 @@ def to_dict(self): "tax_rate": float(self.tax_rate), "tax_amount": float(self.tax_amount), "total_amount": float(self.total_amount), + "discount_percent": float(self.discount_percent) if self.discount_percent else 0, + "discount_amount": float(self.discount_amount) if self.discount_amount else 0, "vat_category": getattr(self, "vat_category", None), "vat_exemption_reason": getattr(self, "vat_exemption_reason", None), "vat_exemption_code": getattr(self, "vat_exemption_code", None), @@ -371,6 +509,17 @@ class InvoiceItem(db.Model): unit_price = db.Column(db.Numeric(10, 2), nullable=False) # Hourly rate total_amount = db.Column(db.Numeric(10, 2), nullable=False) + # Per-line tax (nullable → falls back to invoice.tax_rate) + tax_rate = db.Column(db.Numeric(5, 2), nullable=True) + vat_category = db.Column(db.String(5), nullable=True) + + # Per-line discounts (discount_amount takes priority over discount_percent) + discount_percent = db.Column(db.Numeric(5, 2), nullable=True, default=0) + discount_amount = db.Column(db.Numeric(10, 2), nullable=True, default=0) + + # Ordering (lower = first) + position = db.Column(db.Integer, nullable=True, default=0) + # Time entry reference (optional) time_entry_ids = db.Column(db.Text, nullable=True) # Comma-separated IDs @@ -387,13 +536,31 @@ class InvoiceItem(db.Model): warehouse = db.relationship("Warehouse", foreign_keys=[warehouse_id], lazy="joined") def __init__( - self, invoice_id, description, quantity, unit_price, time_entry_ids=None, stock_item_id=None, warehouse_id=None + self, + invoice_id, + description, + quantity, + unit_price, + time_entry_ids=None, + stock_item_id=None, + warehouse_id=None, + tax_rate=None, + vat_category=None, + discount_percent=None, + discount_amount=None, + position=0, ): self.invoice_id = invoice_id self.description = description self.quantity = Decimal(str(quantity)) self.unit_price = Decimal(str(unit_price)) - self.total_amount = self.quantity * self.unit_price + self.tax_rate = Decimal(str(tax_rate)) if tax_rate is not None else None + self.vat_category = vat_category + self.discount_percent = Decimal(str(discount_percent)) if discount_percent is not None else Decimal("0") + self.discount_amount = Decimal(str(discount_amount)) if discount_amount is not None else Decimal("0") + self.position = int(position) if position is not None else 0 + # total_amount = line net after discount + self.total_amount = self.line_net self.time_entry_ids = time_entry_ids self.stock_item_id = stock_item_id self.warehouse_id = warehouse_id @@ -402,6 +569,30 @@ def __init__( def __repr__(self): return f"" + @property + def line_discount_total(self) -> Decimal: + """The absolute discount amount applied to this line.""" + disc_amt = Decimal(str(self.discount_amount or 0)) + if disc_amt: + return disc_amt + disc_pct = Decimal(str(self.discount_percent or 0)) + if disc_pct: + gross = Decimal(str(self.quantity or 0)) * Decimal(str(self.unit_price or 0)) + return gross * (disc_pct / 100) + return Decimal("0") + + @property + def line_net(self) -> Decimal: + """Net line amount after discount (qty × unit_price − line_discount_total).""" + gross = Decimal(str(self.quantity or 0)) * Decimal(str(self.unit_price or 0)) + return gross - self.line_discount_total + + def effective_tax_rate(self, invoice) -> Decimal: + """Return this item's tax rate, falling back to the invoice-level rate.""" + if self.tax_rate is not None: + return Decimal(str(self.tax_rate)) + return Decimal(str(getattr(invoice, "tax_rate", 0) or 0)) + @property def task_name_from_time_entries(self): """Task name from first linked time entry, or None for project-level groups.""" @@ -429,6 +620,11 @@ def to_dict(self): "quantity": float(self.quantity), "unit_price": float(self.unit_price), "total_amount": float(self.total_amount), + "tax_rate": float(self.tax_rate) if self.tax_rate is not None else None, + "vat_category": self.vat_category, + "discount_percent": float(self.discount_percent) if self.discount_percent else 0, + "discount_amount": float(self.discount_amount) if self.discount_amount else 0, + "position": self.position or 0, "time_entry_ids": self.time_entry_ids, "stock_item_id": self.stock_item_id, "warehouse_id": self.warehouse_id, diff --git a/app/routes/invoices.py b/app/routes/invoices.py index 9902e2b4d..4843225fe 100644 --- a/app/routes/invoices.py +++ b/app/routes/invoices.py @@ -134,6 +134,16 @@ def create_invoice(): flash(_("Invalid tax rate format"), "error") return render_template("invoices/create.html") + # Invoice-level discount (optional) + try: + discount_percent = Decimal(request.form.get("discount_percent", "0") or "0") + except Exception: + discount_percent = Decimal("0") + try: + discount_amount = Decimal(request.form.get("discount_amount", "0") or "0") + except Exception: + discount_amount = Decimal("0") + # Get project project = Project.query.get(project_id) if not project: @@ -200,6 +210,8 @@ def create_invoice(): vat_exemption_code=vat_exemption_code, cig=cig, cup=cup, + discount_percent=discount_percent, + discount_amount=discount_amount, ) db.session.add(invoice) @@ -450,7 +462,34 @@ def edit_invoice(invoice_id): flash(_("You do not have permission to edit this invoice"), "error") return redirect(url_for("invoices.list_invoices")) + financial_locked = invoice.status != "draft" + if request.method == "POST": + # Non-draft invoices are immutable for financial fields (GoBD-style). + # Only notes, terms and due date may still be updated; use a credit note + # for corrections to amounts or line items. + if financial_locked: + due_date_str = request.form.get("due_date", "").strip() + if due_date_str: + try: + invoice.due_date = datetime.strptime(due_date_str, "%Y-%m-%d").date() + except ValueError: + flash(_("Invalid due date"), "error") + return redirect(url_for("invoices.edit_invoice", invoice_id=invoice.id)) + invoice.notes = request.form.get("notes", "").strip() + invoice.terms = request.form.get("terms", "").strip() + if not safe_commit("edit_invoice_locked", {"invoice_id": invoice.id}): + flash(_("Could not update invoice due to a database error. Please check server logs."), "error") + return redirect(url_for("invoices.edit_invoice", invoice_id=invoice.id)) + flash( + _( + "Only notes, terms and due date were updated. Sent invoices cannot change " + "amounts or line items — issue a credit note instead." + ), + "warning", + ) + return redirect(url_for("invoices.view_invoice", invoice_id=invoice.id)) + # Update invoice details invoice.client_name = request.form.get("client_name", "").strip() invoice.client_email = request.form.get("client_email", "").strip() @@ -470,12 +509,27 @@ def edit_invoice(invoice_id): invoice.notes = request.form.get("notes", "").strip() invoice.terms = request.form.get("terms", "").strip() + # Read invoice-level discount (draft only since we're in the full edit path) + try: + invoice.discount_percent = Decimal(request.form.get("discount_percent", "0") or "0") + except Exception: + invoice.discount_percent = Decimal("0") + try: + invoice.discount_amount = Decimal(request.form.get("discount_amount", "0") or "0") + except Exception: + invoice.discount_amount = Decimal("0") + # Update items item_ids = request.form.getlist("item_id[]") descriptions = request.form.getlist("description[]") quantities = request.form.getlist("quantity[]") unit_prices = request.form.getlist("unit_price[]") item_time_entry_ids_list = request.form.getlist("item_time_entry_ids[]") + item_tax_rates = request.form.getlist("item_tax_rate[]") + item_vat_categories = request.form.getlist("item_vat_category[]") + item_discount_percents = request.form.getlist("item_discount_percent[]") + item_discount_amounts = request.form.getlist("item_discount_amount[]") + item_positions = request.form.getlist("item_position[]") # Remove existing items invoice.items.delete() @@ -521,6 +575,41 @@ def edit_invoice(invoice_id): else None ) + # Per-line tax / discount / position + _item_tax_rate = None + if i < len(item_tax_rates) and item_tax_rates[i].strip(): + try: + _item_tax_rate = Decimal(item_tax_rates[i].strip()) + except Exception: + _item_tax_rate = None + + _item_vat_cat = None + if i < len(item_vat_categories) and item_vat_categories[i].strip(): + _item_vat_cat = item_vat_categories[i].strip().upper() or None + if _item_vat_cat and _item_vat_cat not in ("S", "Z", "E", "AE", "K", "G", "O", "L", "M"): + _item_vat_cat = None + + _disc_pct = Decimal("0") + if i < len(item_discount_percents) and item_discount_percents[i].strip(): + try: + _disc_pct = Decimal(item_discount_percents[i].strip()) + except Exception: + _disc_pct = Decimal("0") + + _disc_amt = Decimal("0") + if i < len(item_discount_amounts) and item_discount_amounts[i].strip(): + try: + _disc_amt = Decimal(item_discount_amounts[i].strip()) + except Exception: + _disc_amt = Decimal("0") + + _position = i # default to form order + if i < len(item_positions) and item_positions[i].strip(): + try: + _position = int(item_positions[i].strip()) + except Exception: + _position = i + item = InvoiceItem( invoice_id=invoice.id, description=descriptions[i].strip(), @@ -529,6 +618,11 @@ def edit_invoice(invoice_id): time_entry_ids=time_entry_ids_val, stock_item_id=stock_item_id_val, warehouse_id=warehouse_id_val, + tax_rate=_item_tax_rate, + vat_category=_item_vat_cat, + discount_percent=_disc_pct, + discount_amount=_disc_amt, + position=_position, ) db.session.add(item) except ValueError: @@ -647,6 +741,7 @@ def edit_invoice(invoice_id): "invoices/edit.html", invoice=invoice, projects=Project.query.filter_by(status="active").order_by(Project.name).all(), + financial_locked=False, ) flash(_("Invoice updated successfully"), "success") @@ -689,6 +784,7 @@ def edit_invoice(invoice_id): warehouses=warehouses, stock_items_json=stock_items_json, warehouses_json=warehouses_json, + financial_locked=financial_locked, ) @@ -859,6 +955,23 @@ def update_invoice_status(invoice_id): except Exception as survey_exc: current_app.logger.debug("Client survey on invoice paid skipped: %s", survey_exc) + try: + from app.constants import WebhookEvent + from app.utils.invoice_events import emit_invoice_event + + emit_invoice_event( + WebhookEvent.INVOICE_UPDATED.value, + invoice, + previous_status=previous_status, + new_status=new_status, + ) + if new_status == "sent" and previous_status != "sent": + emit_invoice_event(WebhookEvent.INVOICE_SENT.value, invoice) + if new_status == "paid" and previous_status != "paid": + emit_invoice_event(WebhookEvent.INVOICE_PAID.value, invoice) + except Exception: + current_app.logger.debug("Failed to emit invoice status webhook for %s", invoice.id, exc_info=True) + try: log_event( "invoice.status_changed", @@ -889,12 +1002,24 @@ def delete_invoice(invoice_id): return redirect(url_for("invoices.edit_invoice", invoice_id=invoice.id)) invoice_number = invoice.invoice_number + invoice_id_for_event = invoice.id invoice.release_invoiced_costs_and_expenses() db.session.delete(invoice) - if not safe_commit("delete_invoice", {"invoice_id": invoice.id}): + if not safe_commit("delete_invoice", {"invoice_id": invoice_id_for_event}): flash(_("Could not delete invoice due to a database error. Please check server logs."), "error") return redirect(url_for("invoices.list_invoices")) + try: + from app.constants import WebhookEvent + from app.utils.event_bus import emit_event + + emit_event( + WebhookEvent.INVOICE_DELETED.value, + {"invoice_id": invoice_id_for_event, "invoice_number": invoice_number}, + ) + except Exception: + current_app.logger.debug("Failed to emit invoice.deleted for %s", invoice_id_for_event, exc_info=True) + flash(f"Invoice {invoice_number} deleted successfully", "success") return redirect(url_for("invoices.list_invoices")) diff --git a/app/schemas/invoice_schema.py b/app/schemas/invoice_schema.py index 0be51ee60..f5daebec6 100644 --- a/app/schemas/invoice_schema.py +++ b/app/schemas/invoice_schema.py @@ -18,6 +18,11 @@ class InvoiceItemSchema(Schema): quantity = fields.Decimal(required=True, places=2) unit_price = fields.Decimal(required=True, places=2) amount = fields.Decimal(required=True, places=2) + tax_rate = fields.Decimal(allow_none=True, places=2) + vat_category = fields.Str(allow_none=True) + discount_percent = fields.Decimal(allow_none=True, places=2, load_default=0) + discount_amount = fields.Decimal(allow_none=True, places=2, load_default=0) + position = fields.Int(allow_none=True, load_default=0) class InvoiceSchema(Schema): @@ -38,6 +43,8 @@ class InvoiceSchema(Schema): tax_rate = fields.Decimal(required=True, places=2) tax_amount = fields.Decimal(required=True, places=2) total_amount = fields.Decimal(required=True, places=2) + discount_percent = fields.Decimal(allow_none=True, places=2, load_default=0) + discount_amount = fields.Decimal(allow_none=True, places=2, load_default=0) currency_code = fields.Str(required=True, validate=validate.Length(equal=3)) notes = fields.Str(allow_none=True) terms = fields.Str(allow_none=True) diff --git a/app/services/invoice_service.py b/app/services/invoice_service.py index c48e9bdc0..d15bffc97 100644 --- a/app/services/invoice_service.py +++ b/app/services/invoice_service.py @@ -495,6 +495,7 @@ def update_invoice(self, invoice_id: int, user_id: int, **kwargs) -> Dict[str, A if "currency_code" in kwargs: invoice.currency_code = kwargs["currency_code"] # status transitions only when explicitly allowed (e.g. cancel soft-delete) + previous_status = invoice.status if "status" in kwargs and kwargs.get("_allow_status"): invoice.status = kwargs["status"] @@ -505,6 +506,12 @@ def update_invoice(self, invoice_id: int, user_id: int, **kwargs) -> Dict[str, A "error": "database_error", } + from app.utils.invoice_events import emit_invoice_event + + emit_invoice_event(WebhookEvent.INVOICE_UPDATED.value, invoice) + if invoice.status == "sent" and previous_status != "sent": + emit_invoice_event(WebhookEvent.INVOICE_SENT.value, invoice) + return {"success": True, "message": "Invoice updated successfully", "invoice": invoice} def delete_invoice(self, invoice_id: int, user_id: int) -> Dict[str, Any]: @@ -526,6 +533,7 @@ def delete_invoice(self, invoice_id: int, user_id: int) -> Dict[str, Any]: "error": "invalid_status", } + invoice_number = invoice.invoice_number invoice.release_invoiced_costs_and_expenses() db.session.delete(invoice) @@ -536,6 +544,11 @@ def delete_invoice(self, invoice_id: int, user_id: int) -> Dict[str, Any]: "error": "database_error", } + emit_event( + WebhookEvent.INVOICE_DELETED.value, + {"invoice_id": invoice_id, "invoice_number": invoice_number}, + ) + return {"success": True, "message": "Invoice deleted successfully"} def list_invoices( @@ -1118,7 +1131,7 @@ def set_invoice_items( } invoice.items.delete() - for row in items: + for idx, row in enumerate(items): description = (row.get("description") or "").strip() if not description: continue @@ -1127,12 +1140,39 @@ def set_invoice_items( unit_price = Decimal(str(row.get("unit_price", 0))) except (InvalidOperation, TypeError, ValueError): return {"success": False, "message": "Invalid quantity or unit_price", "error": "validation"} + + # Optional per-line fields + _tax_rate = None + if row.get("tax_rate") is not None: + try: + _tax_rate = Decimal(str(row["tax_rate"])) + except (InvalidOperation, TypeError, ValueError): + _tax_rate = None + _vat_category = row.get("vat_category") or None + try: + _disc_pct = Decimal(str(row.get("discount_percent") or 0)) + except (InvalidOperation, TypeError, ValueError): + _disc_pct = Decimal("0") + try: + _disc_amt = Decimal(str(row.get("discount_amount") or 0)) + except (InvalidOperation, TypeError, ValueError): + _disc_amt = Decimal("0") + try: + _position = int(row.get("position", idx)) + except (TypeError, ValueError): + _position = idx + item = InvoiceItem( invoice_id=invoice.id, description=description, quantity=quantity, unit_price=unit_price, time_entry_ids=row.get("time_entry_ids"), + tax_rate=_tax_rate, + vat_category=_vat_category, + discount_percent=_disc_pct, + discount_amount=_disc_amt, + position=_position, ) db.session.add(item) diff --git a/app/templates/invoices/create.html b/app/templates/invoices/create.html index 186f32c64..cb14cbad6 100644 --- a/app/templates/invoices/create.html +++ b/app/templates/invoices/create.html @@ -77,6 +77,14 @@ +
+ + +
+
+ + +
diff --git a/app/templates/invoices/edit.html b/app/templates/invoices/edit.html index 4fbdf5680..d08db374b 100644 --- a/app/templates/invoices/edit.html +++ b/app/templates/invoices/edit.html @@ -12,6 +12,13 @@ {% endset %} {{ page_header('fas fa-file-invoice', _('Edit Invoice') ~ ' ' ~ invoice.invoice_number, subtitle_text=_('Update invoice details, items, and terms'), actions_html=actions, breadcrumbs=[{'text': _('Invoices'), 'url': url_for('invoices.list_invoices')}, {'text': _('Edit Invoice')}]) }} +{% if financial_locked %} +
+ + {{ _('This invoice is no longer a draft. Only notes, terms and due date can be changed. Issue a credit note to correct amounts or line items.') }} +
+{% endif %} +
@@ -20,11 +27,11 @@
- +
- +
@@ -32,7 +39,15 @@
- + +
+
+ + +
+
+ +
@@ -109,10 +124,12 @@

{% for item in invoice.items %} -
+
+
+ {% if item.time_entry_ids %} {# Time-based item: show Project and Task #}
@@ -166,6 +183,41 @@

+ {# Per-line advanced: tax rate, discounts, reorder #} +
+ {{ _('Line:') }} + + + + + + + + +
+
{# /invoice-item-row outer #} {% endfor %}
@@ -573,10 +625,15 @@

{{ _('Quick Actions') }}

}); } + // Determine position for new row (after existing items) + const existingRows = itemsContainer.querySelectorAll('.invoice-item-row'); + const newPos = existingRows.length; row.innerHTML = ` +
+
+ + + + + + + +
`; itemsContainer.appendChild(row); @@ -698,12 +773,40 @@

{{ _('Quick Actions') }}

row.style.transform = 'scale(0.95)'; setTimeout(() => { row.remove(); + _renumberItemPositions(); calculateTotals(); }, 200); } } + // Move up / down handlers + if (e.target.closest('.item-move-up') || e.target.closest('.item-move-down')) { + const btn = e.target.closest('.item-move-up') || e.target.closest('.item-move-down'); + const row = btn.closest('.invoice-item-row'); + if (!row) return; + const container = row.parentElement; + if (btn.classList.contains('item-move-up')) { + const prev = row.previousElementSibling; + if (prev && prev.classList.contains('invoice-item-row')) { + container.insertBefore(row, prev); + } + } else { + const next = row.nextElementSibling; + if (next && next.classList.contains('invoice-item-row')) { + container.insertBefore(next, row); + } + } + _renumberItemPositions(); + } }); + function _renumberItemPositions() { + const rows = itemsContainer ? itemsContainer.querySelectorAll('.invoice-item-row') : []; + rows.forEach((row, idx) => { + const posInput = row.querySelector('input[name="item_position[]"]'); + if (posInput) posInput.value = idx; + }); + } + // Add expense button - redirect to generate from time page which includes expenses const addExpenseBtn = document.getElementById('add-expense'); addExpenseBtn && addExpenseBtn.addEventListener('click', function() { diff --git a/app/templates/invoices/pdf_default.html b/app/templates/invoices/pdf_default.html index b7fbd44a9..79be9c393 100644 --- a/app/templates/invoices/pdf_default.html +++ b/app/templates/invoices/pdf_default.html @@ -100,10 +100,18 @@

{{ settings.company_name|e }}

{% set count = item.time_entry_ids.split(',')|length %}
{% endif %} + {% if item.discount_percent and item.discount_percent > 0 %} +
{{ _('Discount: %(pct).2f%%', pct=item.discount_percent) }} + {% elif item.discount_amount and item.discount_amount > 0 %} +
{{ _('Discount: -%(amt)s', amt=format_money(item.discount_amount)) }} + {% endif %} + {% if item.tax_rate is not none and item.tax_rate != invoice.tax_rate %} +
{{ _('Tax: %(rate).2f%%', rate=item.tax_rate) }} + {% endif %} {{ '%.2f' % item.quantity }} {{ format_money(item.unit_price) }} - {{ format_money(item.total_amount) }} + {{ format_money(item.line_net) }} {% endfor %} {% for expense in invoice.expenses %} @@ -153,12 +161,33 @@

{{ settings.company_name|e }}

{{ _('Subtotal:') }} {{ format_money(invoice.subtotal) }} - {% if invoice.tax_rate > 0 %} + {% if invoice.discount_amount and invoice.discount_amount > 0 %} + + {{ _('Invoice Discount:') }} + -{{ format_money(invoice.discount_amount) }} + + {% elif invoice.discount_percent and invoice.discount_percent > 0 %} - {{ _('Tax (%(rate).2f%%):', rate=invoice.tax_rate) }} - {{ format_money(invoice.tax_amount) }} + {{ _('Invoice Discount (%(pct).2f%%):', pct=invoice.discount_percent) }} + {% endif %} + {% if invoice.tax_amount > 0 %} + {% set breakdown = invoice.tax_breakdown() %} + {% if breakdown|length > 1 %} + {% for grp in breakdown %} + + {{ _('VAT %(cat)s %(rate).2f%%:', cat=grp.category, rate=grp.rate) }} + {{ format_money(grp.tax) }} + + {% endfor %} + {% else %} + + {{ _('Tax (%(rate).2f%%):', rate=invoice.tax_rate) }} + {{ format_money(invoice.tax_amount) }} + + {% endif %} + {% endif %} {{ _('Total Amount:') }} {{ format_money(invoice.total_amount) }} diff --git a/app/utils/cii_invoice.py b/app/utils/cii_invoice.py index 221d3ed76..9e0d10fa0 100644 --- a/app/utils/cii_invoice.py +++ b/app/utils/cii_invoice.py @@ -267,10 +267,13 @@ def build_cii_invoice_xml( buyer: CIIParty, guideline_id: str = FACTURX_GUIDELINE_EN16931, settings: Any = None, + type_code: str = "380", ) -> Tuple[str, str]: """ Build a CII CrossIndustryInvoice XML for Factur-X / ZUGFeRD. + ``type_code`` is EN 16931 BT-3 (380 = invoice, 381 = credit note). + Returns: (xml_string_utf8, sha256_hex) """ @@ -296,7 +299,7 @@ def build_cii_invoice_xml( ram + "ID", getattr(invoice, "invoice_number", None) or str(getattr(invoice, "id", "")), ) - _text_el(doc, ram + "TypeCode", "380") + _text_el(doc, ram + "TypeCode", type_code or "380") issue_date = getattr(invoice, "issue_date", None) or date.today() issue_dt = _sub(doc, ram + "IssueDateTime") @@ -322,7 +325,15 @@ def build_cii_invoice_xml( line_id = 1 line_items_holder: list = [] # collect then insert — we'll build lines into a temp list of elements - def _add_line(description: str, quantity: Any, unit_price: Any, line_total: Any, item: Any = None) -> None: + def _add_line( + description: str, + quantity: Any, + unit_price: Any, + line_total: Any, + item: Any = None, + line_tax_rate: Any = None, + line_vat_category: Optional[str] = None, + ) -> None: nonlocal line_id li = ET.Element(ram + "IncludedSupplyChainTradeLineItem") @@ -344,8 +355,10 @@ def _add_line(description: str, quantity: Any, unit_price: Any, line_total: Any, line_settle = _sub(li, ram + "SpecifiedLineTradeSettlement") line_tax = _sub(line_settle, ram + "ApplicableTradeTax") _text_el(line_tax, ram + "TypeCode", "VAT") - _text_el(line_tax, ram + "CategoryCode", tax_category) - _text_el(line_tax, ram + "RateApplicablePercent", _money(tax_rate)) + eff_rate = line_tax_rate if line_tax_rate is not None else tax_rate + eff_cat = line_vat_category or tax_category + _text_el(line_tax, ram + "CategoryCode", eff_cat) + _text_el(line_tax, ram + "RateApplicablePercent", _money(eff_rate)) # Line-level tax must NOT carry exemption reasons line_totals = _sub(line_settle, ram + "SpecifiedTradeSettlementLineMonetarySummation") @@ -357,12 +370,21 @@ def _add_line(description: str, quantity: Any, unit_price: Any, line_total: Any, # Invoice items try: for it in list(getattr(invoice, "items", []) or []): + _it_tax = None + if getattr(it, "tax_rate", None) is not None: + _it_tax = Decimal(str(it.tax_rate)) + _it_cat = getattr(it, "vat_category", None) or None + _line_total = getattr(it, "line_net", None) + if _line_total is None: + _line_total = getattr(it, "total_amount", 0) _add_line( description=getattr(it, "description", "Item"), quantity=getattr(it, "quantity", 1), unit_price=getattr(it, "unit_price", 0), - line_total=getattr(it, "total_amount", 0), + line_total=_line_total, item=it, + line_tax_rate=_it_tax, + line_vat_category=_it_cat, ) except Exception: pass @@ -446,19 +468,39 @@ def _add_line(description: str, quantity: Any, unit_price: Any, line_total: Any, inst = _sub(pm, ram + "PayeeSpecifiedCreditorFinancialInstitution") _text_el(inst, ram + "BICID", bic.replace(" ", "")) - # Tax summary — element order: - # CalculatedAmount, TypeCode, ExemptionReason, BasisAmount, CategoryCode, - # ExemptionReasonCode, RateApplicablePercent - tax_el = _sub(settlement, ram + "ApplicableTradeTax") - _money_el(tax_el, ram + "CalculatedAmount", getattr(invoice, "tax_amount", 0)) - _text_el(tax_el, ram + "TypeCode", "VAT") - if exemption_reason: - _text_el(tax_el, ram + "ExemptionReason", exemption_reason) - _money_el(tax_el, ram + "BasisAmount", getattr(invoice, "subtotal", 0)) - _text_el(tax_el, ram + "CategoryCode", tax_category) - if exemption_code: - _text_el(tax_el, ram + "ExemptionReasonCode", exemption_code) - _text_el(tax_el, ram + "RateApplicablePercent", _money(tax_rate)) + # Tax summary — use tax_breakdown() for multi-rate; fall back to single group + try: + breakdown = invoice.tax_breakdown() if hasattr(invoice, "tax_breakdown") else [] + except Exception: + breakdown = [] + + if breakdown: + for grp in breakdown: + tax_el = _sub(settlement, ram + "ApplicableTradeTax") + _money_el(tax_el, ram + "CalculatedAmount", grp["tax"]) + _text_el(tax_el, ram + "TypeCode", "VAT") + grp_cat = grp.get("category") or tax_category + grp_rate = Decimal(str(grp.get("rate", 0))) + # Only emit exemption info if it matches the invoice-level exemption category + if grp_cat in _EXEMPTION_CATEGORIES and exemption_reason: + _text_el(tax_el, ram + "ExemptionReason", exemption_reason) + _money_el(tax_el, ram + "BasisAmount", grp["taxable"]) + _text_el(tax_el, ram + "CategoryCode", grp_cat) + if grp_cat in _EXEMPTION_CATEGORIES and exemption_code: + _text_el(tax_el, ram + "ExemptionReasonCode", exemption_code) + _text_el(tax_el, ram + "RateApplicablePercent", _money(grp_rate)) + else: + # Fallback: single tax block + tax_el = _sub(settlement, ram + "ApplicableTradeTax") + _money_el(tax_el, ram + "CalculatedAmount", getattr(invoice, "tax_amount", 0)) + _text_el(tax_el, ram + "TypeCode", "VAT") + if exemption_reason: + _text_el(tax_el, ram + "ExemptionReason", exemption_reason) + _money_el(tax_el, ram + "BasisAmount", getattr(invoice, "subtotal", 0)) + _text_el(tax_el, ram + "CategoryCode", tax_category) + if exemption_code: + _text_el(tax_el, ram + "ExemptionReasonCode", exemption_code) + _text_el(tax_el, ram + "RateApplicablePercent", _money(tax_rate)) # Payment terms (due date) due_date = getattr(invoice, "due_date", None) @@ -486,3 +528,36 @@ def _add_line(description: str, quantity: Any, unit_price: Any, line_total: Any, xml_bytes = ET.tostring(root, encoding="utf-8", xml_declaration=True) sha256_hex = hashlib.sha256(xml_bytes).hexdigest() return xml_bytes.decode("utf-8"), sha256_hex + + +def build_cii_credit_note_xml(credit_note, invoice, seller: CIIParty, buyer: CIIParty, settings=None) -> Tuple[str, str]: + """Build CII XML for a credit note (TypeCode 381) referencing the original invoice.""" + + class _Shim: + def __init__(self, cn, inv): + self.invoice_number = cn.credit_number + self.issue_date = cn.issue_date or getattr(inv, "issue_date", None) + self.due_date = None + self.currency_code = cn.currency_code or getattr(inv, "currency_code", "EUR") + self.tax_rate = cn.tax_rate if cn.tax_rate is not None else getattr(inv, "tax_rate", 0) + self.tax_amount = cn.tax_amount or 0 + self.subtotal = cn.subtotal if cn.subtotal is not None else cn.amount + self.total_amount = cn.total_amount if cn.total_amount is not None else cn.amount + self.amount_paid = 0 + self.notes = cn.reason or cn.notes + self.buyer_reference = getattr(inv, "buyer_reference", None) + self.vat_category = cn.vat_category or getattr(inv, "vat_category", None) + self.items = list(cn.items.all() if hasattr(cn.items, "all") else list(cn.items or [])) + self.extra_goods = [] + self.expenses = [] + + def tax_breakdown(self): + from decimal import Decimal + + rate = Decimal(str(self.tax_rate or 0)) + taxable = Decimal(str(self.subtotal or 0)) + tax = Decimal(str(self.tax_amount or 0)) + cat = self.vat_category or ("S" if rate > 0 else "Z") + return [{"category": cat, "rate": rate, "taxable": taxable, "tax": tax}] + + return build_cii_invoice_xml(_Shim(credit_note, invoice), seller, buyer, settings=settings, type_code="381") diff --git a/app/utils/fatturapa.py b/app/utils/fatturapa.py index 1fe6d0177..6b83bac31 100644 --- a/app/utils/fatturapa.py +++ b/app/utils/fatturapa.py @@ -31,6 +31,13 @@ _BASE36 = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ" +def resolve_natura_for_category(vat_category: str, rate: Decimal) -> str: + """Return FatturaPA Natura code for a given EN 16931 VAT category and rate.""" + if rate and rate > 0: + return "" # taxed line, no Natura needed + return _VAT_CATEGORY_TO_NATURA.get((vat_category or "").upper(), "") + + def fatturapa_export_available() -> bool: return True @@ -281,12 +288,18 @@ def _collect_lines(invoice: Any) -> List[Dict[str, Any]]: lines: List[Dict[str, Any]] = [] try: for it in list(getattr(invoice, "items", []) or []): + line_total = getattr(it, "line_net", None) + if line_total is None: + line_total = getattr(it, "total_amount", 0) or 0 lines.append( { "description": _strip(getattr(it, "description", None)) or "Item", "quantity": getattr(it, "quantity", 1) or 1, "unit_price": getattr(it, "unit_price", 0) or 0, - "line_total": getattr(it, "total_amount", 0) or 0, + "line_total": line_total, + "line_tax_rate": getattr(it, "tax_rate", None), + "discount_percent": getattr(it, "discount_percent", None), + "discount_amount": getattr(it, "discount_amount", None), } ) except Exception: @@ -490,30 +503,63 @@ def build_fatturapa_xml( _set_text(det, "PrezzoUnitario", _unit_price(line["unit_price"])) line_total = Decimal(str(line["line_total"] or 0)) taxable_sum += line_total + # Per-line discount (ScontoMaggiorazione) if present + line_disc_pct = Decimal(str(line.get("discount_percent") or 0)) + line_disc_amt = Decimal(str(line.get("discount_amount") or 0)) + if line_disc_pct or line_disc_amt: + sc = _sub(det, "ScontoMaggiorazione") + _set_text(sc, "Tipo", "SC") # SC = sconto (discount) + if line_disc_pct: + _set_text(sc, "Percentuale", _money(line_disc_pct)) + if line_disc_amt: + _set_text(sc, "Importo", _money(line_disc_amt)) _set_text(det, "PrezzoTotale", _money(line_total)) - _set_text(det, "AliquotaIVA", _money(tax_rate)) - if natura: - _set_text(det, "Natura", natura) + line_tax_rate = Decimal(str(line.get("line_tax_rate") or tax_rate)) + _set_text(det, "AliquotaIVA", _money(line_tax_rate)) + line_natura = line.get("natura") or natura + if line_natura: + _set_text(det, "Natura", line_natura) - # Prefer invoice subtotal when present + # Try per-rate DatiRiepilogo via tax_breakdown() try: - inv_sub = Decimal(str(getattr(invoice, "subtotal", None) or taxable_sum)) + breakdown = invoice.tax_breakdown() if hasattr(invoice, "tax_breakdown") else [] except Exception: - inv_sub = taxable_sum - try: - inv_tax = Decimal(str(getattr(invoice, "tax_amount", None) or 0)) - except Exception: - inv_tax = (inv_sub * tax_rate / Decimal("100")).quantize(Decimal("0.01"), rounding=ROUND_HALF_UP) - - riep = _sub(beni, "DatiRiepilogo") - _set_text(riep, "AliquotaIVA", _money(tax_rate)) - if natura: - _set_text(riep, "Natura", natura) - _set_text(riep, "ImponibileImporto", _money(inv_sub)) - _set_text(riep, "Imposta", _money(inv_tax)) - _set_text(riep, "EsigibilitaIVA", "I") - if rif_norm: - _set_text(riep, "RiferimentoNormativo", rif_norm[:100]) + breakdown = [] + + if breakdown: + for grp in breakdown: + grp_rate = Decimal(str(grp.get("rate", 0))) + grp_cat = grp.get("category") or ("" if grp_rate > 0 else "O") + grp_natura = resolve_natura_for_category(grp_cat, grp_rate) if grp_cat != "S" else "" + riep = _sub(beni, "DatiRiepilogo") + _set_text(riep, "AliquotaIVA", _money(grp_rate)) + if grp_natura: + _set_text(riep, "Natura", grp_natura) + _set_text(riep, "ImponibileImporto", _money(grp["taxable"])) + _set_text(riep, "Imposta", _money(grp["tax"])) + _set_text(riep, "EsigibilitaIVA", "I") + if rif_norm and grp_natura: + _set_text(riep, "RiferimentoNormativo", rif_norm[:100]) + else: + # Fallback: single DatiRiepilogo block + try: + inv_sub = Decimal(str(getattr(invoice, "subtotal", None) or taxable_sum)) + except Exception: + inv_sub = taxable_sum + try: + inv_tax = Decimal(str(getattr(invoice, "tax_amount", None) or 0)) + except Exception: + inv_tax = (inv_sub * tax_rate / Decimal("100")).quantize(Decimal("0.01"), rounding=ROUND_HALF_UP) + + riep = _sub(beni, "DatiRiepilogo") + _set_text(riep, "AliquotaIVA", _money(tax_rate)) + if natura: + _set_text(riep, "Natura", natura) + _set_text(riep, "ImponibileImporto", _money(inv_sub)) + _set_text(riep, "Imposta", _money(inv_tax)) + _set_text(riep, "EsigibilitaIVA", "I") + if rif_norm: + _set_text(riep, "RiferimentoNormativo", rif_norm[:100]) # Payment iban = _strip(getattr(settings, "company_iban", None)) @@ -535,3 +581,90 @@ def build_fatturapa_xml( filename = build_fatturapa_filename(transmitter, progressivo) sha256_hex = hashlib.sha256(xml_str.encode("utf-8")).hexdigest() return xml_str, filename, sha256_hex + + +def build_fatturapa_credit_note_xml(credit_note, invoice, settings, client=None) -> Tuple[bytes, str]: + """Build a FatturaPA XML credit note (TipoDocumento TD04) with DatiFattureCollegate. + + Returns (xml_bytes, filename). + """ + # Reuse the invoice builder then patch document type + linked invoice reference. + # build_fatturapa_xml expects an invoice-like object; we temporarily adapt via a shim. + class _CNAsInvoice: + def __init__(self, cn, inv): + self.id = cn.id + self.invoice_number = cn.credit_number + self.issue_date = cn.issue_date or getattr(inv, "issue_date", None) + self.due_date = None + self.currency_code = cn.currency_code or getattr(inv, "currency_code", "EUR") + self.tax_rate = cn.tax_rate if cn.tax_rate is not None else getattr(inv, "tax_rate", 0) + self.tax_amount = cn.tax_amount or 0 + self.subtotal = cn.subtotal if cn.subtotal is not None else cn.amount + self.total_amount = cn.total_amount if cn.total_amount is not None else cn.amount + self.vat_category = cn.vat_category or getattr(inv, "vat_category", None) + self.vat_exemption_reason = getattr(inv, "vat_exemption_reason", None) + self.vat_exemption_code = getattr(inv, "vat_exemption_code", None) + self.client_name = getattr(inv, "client_name", None) + self.client_id = getattr(inv, "client_id", None) + self.cig = getattr(inv, "cig", None) + self.cup = getattr(inv, "cup", None) + self.buyer_reference = getattr(inv, "buyer_reference", None) + self._items = list(cn.items.all() if hasattr(cn.items, "all") else list(cn.items or [])) + self._inv = inv + + @property + def items(self): + return self._items + + @property + def extra_goods(self): + return [] + + @property + def expenses(self): + return [] + + def tax_breakdown(self): + rate = Decimal(str(self.tax_rate or 0)) + taxable = Decimal(str(self.subtotal or 0)) + tax = Decimal(str(self.tax_amount or 0)) + cat = self.vat_category or ("S" if rate > 0 else "Z") + return [{"category": cat, "rate": rate, "taxable": taxable, "tax": tax}] + + shim = _CNAsInvoice(credit_note, invoice) + progressivo = progressivo_from_id(getattr(credit_note, "id", 1) or 1) + xml_str, filename, _sha = build_fatturapa_xml(shim, settings, client, progressivo) + + # Patch TipoDocumento TD01 → TD04 and inject DatiFattureCollegate + root = ET.fromstring(xml_str.encode("utf-8") if isinstance(xml_str, str) else xml_str) + for el in root.iter(): + if el.tag.endswith("TipoDocumento") and el.text == "TD01": + el.text = "TD04" + break + + # Insert DatiFattureCollegate under DatiGenerali + for el in root.iter(): + if el.tag.endswith("DatiGenerali"): + linked = ET.Element("DatiFattureCollegate") + id_doc = ET.SubElement(linked, "IdDocumento") + id_doc.text = (_strip(getattr(invoice, "invoice_number", None)) or "1")[:20] + inv_issue = getattr(invoice, "issue_date", None) + if inv_issue and hasattr(inv_issue, "isoformat"): + data_el = ET.SubElement(linked, "Data") + data_el.text = inv_issue.isoformat() + # Insert after DatiGeneraliDocumento if present + inserted = False + for i, child in enumerate(list(el)): + if child.tag.endswith("DatiGeneraliDocumento"): + el.insert(i + 1, linked) + inserted = True + break + if not inserted: + el.append(linked) + break + + out = ET.tostring(root, encoding="utf-8", xml_declaration=True) + # Keep filename but mark as credit note in Progressivo when possible + if filename and not filename.upper().endswith(".XML"): + filename = filename + ".xml" + return out, filename diff --git a/app/utils/xrechnung.py b/app/utils/xrechnung.py index 6af384eba..3778d2325 100644 --- a/app/utils/xrechnung.py +++ b/app/utils/xrechnung.py @@ -383,3 +383,26 @@ def build_minimal_xrechnung_xml(invoice: Any, *, seller_name: str, buyer_name: s ) xml, _ = build_xrechnung_ubl_invoice_xml(inv, settings, client) return xml + + +def build_xrechnung_ubl_credit_note_xml(credit_note, invoice, settings, client) -> Tuple[str, str]: + """Build XRechnung-flavoured UBL CreditNote (type 381) from Peppol credit note XML.""" + import hashlib + + from app.integrations.peppol import build_peppol_ubl_credit_note_xml + + buyer_reference = effective_buyer_reference(invoice, client) + supplier = build_supplier_party(settings) + customer = build_customer_party(invoice, client, buyer_reference) + xml, _doc_id = build_peppol_ubl_credit_note_xml(credit_note, invoice, supplier, customer) + # Patch CustomizationID to XRechnung 3.0 + try: + root = ET.fromstring(xml.encode("utf-8")) + for el in root.iter(): + if el.tag.endswith("CustomizationID"): + el.text = XRECHNUNG_30_CUSTOMIZATION_ID + break + xml = ET.tostring(root, encoding="utf-8", xml_declaration=True).decode("utf-8") + except Exception: + pass + return xml, hashlib.sha256(xml.encode("utf-8")).hexdigest() diff --git a/migrations/versions/210_invoice_line_tax_discounts.py b/migrations/versions/210_invoice_line_tax_discounts.py new file mode 100644 index 000000000..7fe3ce6b2 --- /dev/null +++ b/migrations/versions/210_invoice_line_tax_discounts.py @@ -0,0 +1,90 @@ +"""Add per-line tax, discounts, and position to invoice items; add invoice-level discounts. + +Revision ID: 210_invoice_line_tax_discounts +Revises: 209_add_fatturapa_sdi + +Adds: + invoice_items: tax_rate, vat_category, discount_percent, discount_amount, position + invoices: discount_percent, discount_amount +""" + +import sqlalchemy as sa +from alembic import op +from sqlalchemy import inspect + +revision = "210_invoice_line_tax_discounts" +down_revision = "209_add_fatturapa_sdi" +branch_labels = None +depends_on = None + + +def _has_column(inspector, table_name: str, column_name: str) -> bool: + try: + return column_name in {c["name"] for c in inspector.get_columns(table_name)} + except Exception: + # Table may not exist yet during partial upgrades. + return False + + +def _add_column_if_missing(inspector, table_name: str, column: sa.Column) -> None: + if not _has_column(inspector, table_name, column.name): + op.add_column(table_name, column) + + +def upgrade(): + bind = op.get_bind() + inspector = inspect(bind) + + # invoice_items: per-line tax rate, VAT category, discounts, ordering + _add_column_if_missing( + inspector, + "invoice_items", + sa.Column("tax_rate", sa.Numeric(5, 2), nullable=True), + ) + _add_column_if_missing( + inspector, + "invoice_items", + sa.Column("vat_category", sa.String(length=5), nullable=True), + ) + _add_column_if_missing( + inspector, + "invoice_items", + sa.Column("discount_percent", sa.Numeric(5, 2), nullable=True, server_default="0"), + ) + _add_column_if_missing( + inspector, + "invoice_items", + sa.Column("discount_amount", sa.Numeric(10, 2), nullable=True, server_default="0"), + ) + _add_column_if_missing( + inspector, + "invoice_items", + sa.Column("position", sa.Integer(), nullable=True, server_default="0"), + ) + + # invoices: invoice-level discounts + inspector = inspect(bind) + _add_column_if_missing( + inspector, + "invoices", + sa.Column("discount_percent", sa.Numeric(5, 2), nullable=True, server_default="0"), + ) + _add_column_if_missing( + inspector, + "invoices", + sa.Column("discount_amount", sa.Numeric(10, 2), nullable=True, server_default="0"), + ) + + +def downgrade(): + bind = op.get_bind() + inspector = inspect(bind) + + for col in ("discount_percent", "discount_amount"): + if _has_column(inspector, "invoices", col): + op.drop_column("invoices", col) + + inspector = inspect(bind) + for col in ("position", "discount_amount", "discount_percent", "vat_category", "tax_rate"): + if _has_column(inspector, "invoice_items", col): + op.drop_column("invoice_items", col) diff --git a/tests/test_invoice_line_tax_discounts.py b/tests/test_invoice_line_tax_discounts.py new file mode 100644 index 000000000..ae232dc87 --- /dev/null +++ b/tests/test_invoice_line_tax_discounts.py @@ -0,0 +1,431 @@ +"""Tests for Phase 2 invoice line items: per-line tax, discounts, ordering. + +Covers: + - No discounts → same totals as before + - Per-line discount (percent and amount) + - Invoice-level discount + - Mixed tax rates → correct tax_breakdown() and totals + - position ordering + - effective_tax_rate fallback +""" + +from datetime import date, timedelta +from decimal import Decimal + +import pytest + +from app import db +from app.models import Client, Invoice, InvoiceItem, Project, Settings, User +from factories import ClientFactory, ProjectFactory, UserFactory + + +# --------------------------------------------------------------------------- +# Helpers / fixtures +# --------------------------------------------------------------------------- + +@pytest.fixture +def base_user(app): + u = UserFactory(username="disc_test_user", role="admin") + db.session.commit() + return u + + +@pytest.fixture +def base_client(app): + c = ClientFactory(name="Discount Test Client") + db.session.commit() + return c + + +@pytest.fixture +def base_project(app, base_client): + p = ProjectFactory( + name="Discount Test Project", + client_id=base_client.id, + billable=True, + hourly_rate=Decimal("100.00"), + ) + db.session.commit() + return p + + +def make_invoice(user, project, client, **kwargs) -> Invoice: + inv = Invoice( + invoice_number=f"INV-DISC-{id(kwargs)}", + project_id=project.id, + client_name="Test", + due_date=date.today() + timedelta(days=30), + created_by=user.id, + client_id=client.id, + **kwargs, + ) + db.session.add(inv) + db.session.flush() + return inv + + +def add_item(invoice, description, quantity, unit_price, **kwargs) -> InvoiceItem: + item = InvoiceItem( + invoice_id=invoice.id, + description=description, + quantity=quantity, + unit_price=unit_price, + **kwargs, + ) + db.session.add(item) + return item + + +# --------------------------------------------------------------------------- +# 1. No discounts → same totals as before +# --------------------------------------------------------------------------- + +@pytest.mark.invoices +def test_no_discounts_same_as_before(app, base_user, base_project, base_client): + """Without any discounts the totals should equal qty×price + tax as before.""" + inv = make_invoice(base_user, base_project, base_client, tax_rate=Decimal("20")) + add_item(inv, "Dev", Decimal("10"), Decimal("100")) # 1000 + add_item(inv, "Design", Decimal("5"), Decimal("80")) # 400 + db.session.commit() + + inv.calculate_totals() + + assert inv.subtotal == Decimal("1400.00") + assert inv.tax_amount == Decimal("280.00") + assert inv.total_amount == Decimal("1680.00") + + +@pytest.mark.invoices +def test_no_discounts_zero_tax(app, base_user, base_project, base_client): + """Zero tax rate → subtotal == total_amount.""" + inv = make_invoice(base_user, base_project, base_client, tax_rate=Decimal("0")) + add_item(inv, "Service", Decimal("3"), Decimal("50")) + db.session.commit() + inv.calculate_totals() + assert inv.subtotal == Decimal("150.00") + assert inv.tax_amount == Decimal("0.00") + assert inv.total_amount == Decimal("150.00") + + +# --------------------------------------------------------------------------- +# 2. Per-line discount +# --------------------------------------------------------------------------- + +@pytest.mark.invoices +def test_line_discount_percent(app, base_user, base_project, base_client): + """Per-line 10% discount reduces line net correctly.""" + inv = make_invoice(base_user, base_project, base_client, tax_rate=Decimal("20")) + add_item(inv, "Dev", Decimal("10"), Decimal("100"), discount_percent=Decimal("10")) + # line gross = 1000, disc = 100, net = 900 + db.session.commit() + + item = inv.items.first() + assert item.line_discount_total == Decimal("100.00") + assert item.line_net == Decimal("900.00") + # total_amount on item is set at construction + assert item.total_amount == Decimal("900.00") + + inv.calculate_totals() + assert inv.subtotal == Decimal("900.00") + assert inv.tax_amount == Decimal("180.00") + assert inv.total_amount == Decimal("1080.00") + + +@pytest.mark.invoices +def test_line_discount_amount(app, base_user, base_project, base_client): + """Per-line fixed discount_amount takes priority over discount_percent.""" + inv = make_invoice(base_user, base_project, base_client, tax_rate=Decimal("10")) + add_item( + inv, "Item", Decimal("5"), Decimal("200"), + discount_amount=Decimal("50"), discount_percent=Decimal("99"), # amount wins + ) + # gross = 1000, disc_amount = 50, net = 950 + db.session.commit() + + item = inv.items.first() + assert item.line_discount_total == Decimal("50.00") + assert item.line_net == Decimal("950.00") + + inv.calculate_totals() + assert inv.subtotal == Decimal("950.00") + assert inv.tax_amount == Decimal("95.00") + assert inv.total_amount == Decimal("1045.00") + + +@pytest.mark.invoices +def test_line_no_discount(app, base_user, base_project, base_client): + """Item with neither discount field set has zero discount.""" + inv = make_invoice(base_user, base_project, base_client, tax_rate=Decimal("0")) + item = add_item(inv, "X", Decimal("2"), Decimal("100")) + db.session.commit() + assert item.line_discount_total == Decimal("0") + assert item.line_net == Decimal("200.00") + + +# --------------------------------------------------------------------------- +# 3. Invoice-level discount +# --------------------------------------------------------------------------- + +@pytest.mark.invoices +def test_invoice_discount_percent(app, base_user, base_project, base_client): + """Invoice-level 5% discount applied after line totals, before tax.""" + inv = make_invoice( + base_user, base_project, base_client, + tax_rate=Decimal("20"), + discount_percent=Decimal("5"), + ) + add_item(inv, "A", Decimal("10"), Decimal("100")) # 1000 + db.session.commit() + + inv.calculate_totals() + # combined net = 1000, disc = 50, subtotal = 950, tax = 190 + assert inv.subtotal == Decimal("950.00") + assert inv.tax_amount == Decimal("190.00") + assert inv.total_amount == Decimal("1140.00") + + +@pytest.mark.invoices +def test_invoice_discount_amount(app, base_user, base_project, base_client): + """Invoice-level fixed discount_amount applied before tax.""" + inv = make_invoice( + base_user, base_project, base_client, + tax_rate=Decimal("10"), + discount_amount=Decimal("100"), + ) + add_item(inv, "A", Decimal("2"), Decimal("500")) # 1000 + db.session.commit() + + inv.calculate_totals() + assert inv.subtotal == Decimal("900.00") + assert inv.tax_amount == Decimal("90.00") + assert inv.total_amount == Decimal("990.00") + + +@pytest.mark.invoices +def test_invoice_discount_amount_wins_over_percent(app, base_user, base_project, base_client): + """When both discount_amount and discount_percent set, amount wins.""" + inv = make_invoice( + base_user, base_project, base_client, + tax_rate=Decimal("0"), + discount_amount=Decimal("50"), + discount_percent=Decimal("99"), # should be ignored + ) + add_item(inv, "A", Decimal("1"), Decimal("200")) + db.session.commit() + inv.calculate_totals() + assert inv.subtotal == Decimal("150.00") + + +@pytest.mark.invoices +def test_combined_line_and_invoice_discount(app, base_user, base_project, base_client): + """Line discount applied first, then invoice discount on the combined net.""" + inv = make_invoice( + base_user, base_project, base_client, + tax_rate=Decimal("20"), + discount_percent=Decimal("10"), + ) + # item gross=1000, 20% line disc → net 800 + add_item(inv, "A", Decimal("10"), Decimal("100"), discount_percent=Decimal("20")) + db.session.commit() + + inv.calculate_totals() + # combined_net=800, invoice_disc=80, subtotal=720, tax=144 + assert inv.subtotal == Decimal("720.00") + assert inv.tax_amount == Decimal("144.00") + assert inv.total_amount == Decimal("864.00") + + +# --------------------------------------------------------------------------- +# 4. Mixed tax rates → tax_breakdown() and totals +# --------------------------------------------------------------------------- + +@pytest.mark.invoices +def test_mixed_tax_rates_breakdown(app, base_user, base_project, base_client): + """Items with different tax rates produce correct tax_breakdown() entries.""" + inv = make_invoice(base_user, base_project, base_client, tax_rate=Decimal("20")) + # Item1: net 500 @ 20% → tax 100 + add_item(inv, "Standard", Decimal("5"), Decimal("100"), tax_rate=Decimal("20")) + # Item2: net 200 @ 10% → tax 20 + add_item(inv, "Reduced", Decimal("2"), Decimal("100"), tax_rate=Decimal("10")) + # Item3: net 100 @ 0% (exempt) → tax 0 + add_item(inv, "Exempt", Decimal("1"), Decimal("100"), tax_rate=Decimal("0"), vat_category="E") + db.session.commit() + + inv.calculate_totals() + + assert inv.subtotal == Decimal("800.00") + assert inv.tax_amount == Decimal("120.00") # 100+20+0 + assert inv.total_amount == Decimal("920.00") + + bd = inv.tax_breakdown() + # Should have 3 groups + assert len(bd) == 3 + by_rate = {grp["rate"]: grp for grp in bd} + assert abs(by_rate[20.0]["taxable"] - 500.0) < 0.01 + assert abs(by_rate[20.0]["tax"] - 100.0) < 0.01 + assert abs(by_rate[10.0]["taxable"] - 200.0) < 0.01 + assert abs(by_rate[10.0]["tax"] - 20.0) < 0.01 + assert abs(by_rate[0.0]["taxable"] - 100.0) < 0.01 + assert abs(by_rate[0.0]["tax"] - 0.0) < 0.01 + + +@pytest.mark.invoices +def test_mixed_tax_rates_with_invoice_discount(app, base_user, base_project, base_client): + """Invoice discount is distributed proportionally across rate groups.""" + inv = make_invoice( + base_user, base_project, base_client, + tax_rate=Decimal("20"), + discount_percent=Decimal("10"), + ) + add_item(inv, "A", Decimal("10"), Decimal("100"), tax_rate=Decimal("20")) # 1000 + add_item(inv, "B", Decimal("10"), Decimal("100"), tax_rate=Decimal("10")) # 1000 + db.session.commit() + + inv.calculate_totals() + # combined=2000, disc=200, subtotal=1800 + assert inv.subtotal == Decimal("1800.00") + # each group taxable after 10% disc: + # 20% group: 1000*0.9=900, tax=180 + # 10% group: 1000*0.9=900, tax=90 + expected_tax = Decimal("270.00") + assert inv.tax_amount == expected_tax + assert inv.total_amount == Decimal("2070.00") + + bd = inv.tax_breakdown() + by_rate = {grp["rate"]: grp for grp in bd} + assert abs(by_rate[20.0]["taxable"] - 900.0) < 0.01 + assert abs(by_rate[10.0]["taxable"] - 900.0) < 0.01 + + +# --------------------------------------------------------------------------- +# 5. effective_tax_rate fallback +# --------------------------------------------------------------------------- + +@pytest.mark.invoices +def test_effective_tax_rate_fallback(app, base_user, base_project, base_client): + """Item without tax_rate falls back to invoice.tax_rate.""" + inv = make_invoice(base_user, base_project, base_client, tax_rate=Decimal("19")) + item = add_item(inv, "A", Decimal("1"), Decimal("100")) + db.session.commit() + + assert item.tax_rate is None + assert item.effective_tax_rate(inv) == Decimal("19") + + +@pytest.mark.invoices +def test_effective_tax_rate_per_line_overrides(app, base_user, base_project, base_client): + """Item with explicit tax_rate uses it over invoice.tax_rate.""" + inv = make_invoice(base_user, base_project, base_client, tax_rate=Decimal("20")) + item = add_item(inv, "A", Decimal("1"), Decimal("100"), tax_rate=Decimal("7")) + db.session.commit() + + assert item.effective_tax_rate(inv) == Decimal("7") + + +# --------------------------------------------------------------------------- +# 6. Position ordering +# --------------------------------------------------------------------------- + +@pytest.mark.invoices +def test_item_position_stored(app, base_user, base_project, base_client): + """Items retain their position value.""" + inv = make_invoice(base_user, base_project, base_client, tax_rate=Decimal("0")) + add_item(inv, "First", Decimal("1"), Decimal("1"), position=0) + add_item(inv, "Second", Decimal("1"), Decimal("2"), position=1) + add_item(inv, "Third", Decimal("1"), Decimal("3"), position=2) + db.session.commit() + + items = list(inv.items.order_by(InvoiceItem.position)) + assert [item.description for item in items] == ["First", "Second", "Third"] + + +@pytest.mark.invoices +def test_item_position_default_zero(app, base_user, base_project, base_client): + """Items with no position set default to 0.""" + inv = make_invoice(base_user, base_project, base_client, tax_rate=Decimal("0")) + item = add_item(inv, "X", Decimal("1"), Decimal("1")) + db.session.commit() + assert item.position == 0 + + +# --------------------------------------------------------------------------- +# 7. to_dict includes new fields +# --------------------------------------------------------------------------- + +@pytest.mark.invoices +def test_invoice_to_dict_new_fields(app, base_user, base_project, base_client): + """Invoice.to_dict() includes discount_percent and discount_amount.""" + inv = make_invoice( + base_user, base_project, base_client, + tax_rate=Decimal("20"), + discount_percent=Decimal("5"), + discount_amount=Decimal("0"), + ) + db.session.commit() + d = inv.to_dict() + assert "discount_percent" in d + assert "discount_amount" in d + assert d["discount_percent"] == 5.0 + + +@pytest.mark.invoices +def test_item_to_dict_new_fields(app, base_user, base_project, base_client): + """InvoiceItem.to_dict() includes tax_rate, discount_percent, discount_amount, position.""" + inv = make_invoice(base_user, base_project, base_client, tax_rate=Decimal("20")) + item = add_item( + inv, "X", Decimal("2"), Decimal("50"), + tax_rate=Decimal("7"), + discount_percent=Decimal("10"), + position=3, + ) + db.session.commit() + d = item.to_dict() + assert d["tax_rate"] == 7.0 + assert d["discount_percent"] == 10.0 + assert d["position"] == 3 + + +# --------------------------------------------------------------------------- +# 8. Backward compatibility: existing items with null discounts unchanged +# --------------------------------------------------------------------------- + +@pytest.mark.invoices +def test_backward_compat_null_discounts(app, base_user, base_project, base_client): + """Items without discount fields behave exactly as before (no change to totals).""" + inv = make_invoice(base_user, base_project, base_client, tax_rate=Decimal("20")) + # Create items without any new fields (old-style) + item1 = InvoiceItem( + invoice_id=inv.id, description="A", quantity=Decimal("10"), unit_price=Decimal("75") + ) + item2 = InvoiceItem( + invoice_id=inv.id, description="B", quantity=Decimal("5"), unit_price=Decimal("100") + ) + db.session.add(item1) + db.session.add(item2) + db.session.commit() + + inv.calculate_totals() + # 10*75=750, 5*100=500, subtotal=1250, tax@20%=250 + assert inv.subtotal == Decimal("1250.00") + assert inv.tax_amount == Decimal("250.00") + assert inv.total_amount == Decimal("1500.00") + + +# --------------------------------------------------------------------------- +# 9. tax_breakdown() with single rate returns one entry +# --------------------------------------------------------------------------- + +@pytest.mark.invoices +def test_tax_breakdown_single_rate(app, base_user, base_project, base_client): + """Single tax rate produces a single breakdown entry.""" + inv = make_invoice(base_user, base_project, base_client, tax_rate=Decimal("19")) + add_item(inv, "A", Decimal("1"), Decimal("100")) + add_item(inv, "B", Decimal("2"), Decimal("50")) + db.session.commit() + inv.calculate_totals() + + bd = inv.tax_breakdown() + assert len(bd) == 1 + assert bd[0]["rate"] == 19.0 + assert abs(bd[0]["taxable"] - 200.0) < 0.01 + assert abs(bd[0]["tax"] - 38.0) < 0.01 From 9bea24678bbea03bad02b9f4f55e5f6e74370833 Mon Sep 17 00:00:00 2001 From: Dries Peeters Date: Sat, 14 Nov 2026 08:12:07 +0100 Subject: [PATCH 3/9] feat(invoicing): add reminder policies and late-fee dunning Introduce reusable reminder levels with optional fixed or annual late fees, wire the daily overdue job to send each due level once, and expose admin and per-client policy controls plus invoice reminder history. --- app/models/client.py | 3 + app/models/reminder_policy.py | 83 +++++ app/routes/clients.py | 24 +- app/routes/reminder_policies.py | 143 ++++++++ app/services/invoice_reminder_service.py | 270 ++++++++++++++ app/templates/clients/edit.html | 16 + app/templates/email/invoice_reminder.html | 47 +++ app/templates/reminder_policies/edit.html | 129 +++++++ app/templates/reminder_policies/list.html | 51 +++ app/utils/scheduled_tasks.py | 28 +- .../versions/211_invoice_reminder_policies.py | 115 ++++++ tests/test_invoice_reminders.py | 339 ++++++++++++++++++ 12 files changed, 1246 insertions(+), 2 deletions(-) create mode 100644 app/models/reminder_policy.py create mode 100644 app/routes/reminder_policies.py create mode 100644 app/services/invoice_reminder_service.py create mode 100644 app/templates/email/invoice_reminder.html create mode 100644 app/templates/reminder_policies/edit.html create mode 100644 app/templates/reminder_policies/list.html create mode 100644 migrations/versions/211_invoice_reminder_policies.py create mode 100644 tests/test_invoice_reminders.py diff --git a/app/models/client.py b/app/models/client.py index eef6cbaa4..d7a6a8b0d 100644 --- a/app/models/client.py +++ b/app/models/client.py @@ -57,6 +57,9 @@ class Client(db.Model): # Custom fields for flexible data storage (e.g., debtor_number, ERP IDs, etc.) custom_fields = db.Column(db.JSON, nullable=True) + # Optional reminder policy override (falls back to system default) + reminder_policy_id = db.Column(db.Integer, db.ForeignKey("reminder_policies.id"), nullable=True) + # Relationships projects = db.relationship("Project", backref="client_obj", lazy="dynamic", cascade="all, delete-orphan") time_entries = db.relationship("TimeEntry", backref="client", lazy="dynamic", cascade="all, delete-orphan") diff --git a/app/models/reminder_policy.py b/app/models/reminder_policy.py new file mode 100644 index 000000000..733646050 --- /dev/null +++ b/app/models/reminder_policy.py @@ -0,0 +1,83 @@ +"""Models for invoice reminder policies and policy levels.""" + +from datetime import datetime +from decimal import Decimal + +from app import db + + +class ReminderPolicy(db.Model): + """A named set of reminder levels that can be applied to clients/invoices.""" + + __tablename__ = "reminder_policies" + + id = db.Column(db.Integer, primary_key=True) + name = db.Column(db.String(100), nullable=False) + active = db.Column(db.Boolean, default=True, nullable=False) + is_default = db.Column(db.Boolean, default=False, nullable=False) + created_at = db.Column(db.DateTime, default=datetime.utcnow, nullable=False) + updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False) + + # Relationships + levels = db.relationship( + "ReminderPolicyLevel", + backref="policy", + lazy="dynamic", + cascade="all, delete-orphan", + order_by="ReminderPolicyLevel.sort_order", + ) + + def __repr__(self): + return f"" + + @classmethod + def get_default(cls): + """Return the first active policy with is_default=True, or None.""" + return cls.query.filter_by(is_default=True, active=True).first() + + def to_dict(self): + return { + "id": self.id, + "name": self.name, + "active": self.active, + "is_default": self.is_default, + "created_at": self.created_at.isoformat() if self.created_at else None, + "updated_at": self.updated_at.isoformat() if self.updated_at else None, + "levels": [lv.to_dict() for lv in self.levels], + } + + +class ReminderPolicyLevel(db.Model): + """A single trigger level within a reminder policy.""" + + __tablename__ = "reminder_policy_levels" + + id = db.Column(db.Integer, primary_key=True) + policy_id = db.Column( + db.Integer, db.ForeignKey("reminder_policies.id", ondelete="CASCADE"), nullable=False, index=True + ) + # negative = before due date, positive = after due date (days) + days_offset = db.Column(db.Integer, nullable=False) + template_name = db.Column(db.String(100), nullable=True) + # 'fixed' | 'percent_annual' | null + late_fee_type = db.Column(db.String(20), nullable=True) + late_fee_value = db.Column(db.Numeric(10, 2), nullable=True) + sort_order = db.Column(db.Integer, default=0, nullable=False) + active = db.Column(db.Boolean, default=True, nullable=False) + created_at = db.Column(db.DateTime, default=datetime.utcnow, nullable=False) + updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False) + + def __repr__(self): + return f"" + + def to_dict(self): + return { + "id": self.id, + "policy_id": self.policy_id, + "days_offset": self.days_offset, + "template_name": self.template_name, + "late_fee_type": self.late_fee_type, + "late_fee_value": float(self.late_fee_value) if self.late_fee_value is not None else None, + "sort_order": self.sort_order, + "active": self.active, + } diff --git a/app/routes/clients.py b/app/routes/clients.py index d7a583c5d..b1f416d72 100644 --- a/app/routes/clients.py +++ b/app/routes/clients.py @@ -784,6 +784,16 @@ def edit_client(client_id): client.portal_username = None client.portal_password_hash = None + # Reminder policy (Phase 4) + rp_id_raw = request.form.get("reminder_policy_id", "").strip() + if rp_id_raw: + try: + client.reminder_policy_id = int(rp_id_raw) + except ValueError: + client.reminder_policy_id = None + else: + client.reminder_policy_id = None + client.updated_at = datetime.utcnow() if not safe_commit("edit_client", {"client_id": client.id}): @@ -799,7 +809,19 @@ def edit_client(client_id): # Load active custom field definitions for the form custom_field_definitions = CustomFieldDefinition.get_active_definitions() - return render_template("clients/edit.html", client=client, custom_field_definitions=custom_field_definitions) + # Load reminder policies for the dropdown (Phase 4) + try: + from app.models.reminder_policy import ReminderPolicy as _RP + + reminder_policies = _RP.query.filter_by(active=True).order_by(_RP.name).all() + except Exception: + reminder_policies = [] + return render_template( + "clients/edit.html", + client=client, + custom_field_definitions=custom_field_definitions, + reminder_policies=reminder_policies, + ) @clients_bp.route("/clients//send-portal-password-email", methods=["POST"]) diff --git a/app/routes/reminder_policies.py b/app/routes/reminder_policies.py new file mode 100644 index 000000000..8c494effa --- /dev/null +++ b/app/routes/reminder_policies.py @@ -0,0 +1,143 @@ +"""Admin UI routes for reminder policies (Phase 4 – invoicing gaps).""" + +from flask import Blueprint, flash, redirect, render_template, request, url_for +from flask_login import login_required + +from app import db +from app.models.reminder_policy import ReminderPolicy, ReminderPolicyLevel +from app.utils.permissions import admin_or_permission_required + +reminder_policies_bp = Blueprint("reminder_policies", __name__) + + +@reminder_policies_bp.route("/admin/reminder-policies") +@login_required +@admin_or_permission_required("access_admin") +def list_policies(): + policies = ReminderPolicy.query.order_by(ReminderPolicy.is_default.desc(), ReminderPolicy.name).all() + return render_template("reminder_policies/list.html", policies=policies) + + +@reminder_policies_bp.route("/admin/reminder-policies/create", methods=["GET", "POST"]) +@login_required +@admin_or_permission_required("access_admin") +def create_policy(): + if request.method == "POST": + name = (request.form.get("name") or "").strip() + if not name: + flash("Policy name is required.", "error") + return redirect(url_for("reminder_policies.create_policy")) + + is_default = bool(request.form.get("is_default")) + if is_default: + # Unset any existing default + ReminderPolicy.query.filter_by(is_default=True).update({"is_default": False}) + + policy = ReminderPolicy(name=name, is_default=is_default) + db.session.add(policy) + db.session.flush() # get policy.id + + _save_levels(policy, request.form) + db.session.commit() + flash(f"Reminder policy '{name}' created.", "success") + return redirect(url_for("reminder_policies.list_policies")) + + return render_template("reminder_policies/edit.html", policy=None) + + +@reminder_policies_bp.route("/admin/reminder-policies//edit", methods=["GET", "POST"]) +@login_required +@admin_or_permission_required("access_admin") +def edit_policy(policy_id): + policy = ReminderPolicy.query.get_or_404(policy_id) + + if request.method == "POST": + name = (request.form.get("name") or "").strip() + if not name: + flash("Policy name is required.", "error") + return redirect(url_for("reminder_policies.edit_policy", policy_id=policy_id)) + + is_default = bool(request.form.get("is_default")) + if is_default and not policy.is_default: + ReminderPolicy.query.filter_by(is_default=True).update({"is_default": False}) + + policy.name = name + policy.active = bool(request.form.get("active")) + policy.is_default = is_default + + # Replace all levels + for lv in policy.levels.all(): + db.session.delete(lv) + db.session.flush() + + _save_levels(policy, request.form) + db.session.commit() + flash(f"Reminder policy '{name}' updated.", "success") + return redirect(url_for("reminder_policies.list_policies")) + + return render_template("reminder_policies/edit.html", policy=policy) + + +@reminder_policies_bp.route("/admin/reminder-policies//delete", methods=["POST"]) +@login_required +@admin_or_permission_required("access_admin") +def delete_policy(policy_id): + policy = ReminderPolicy.query.get_or_404(policy_id) + db.session.delete(policy) + db.session.commit() + flash(f"Reminder policy '{policy.name}' deleted.", "success") + return redirect(url_for("reminder_policies.list_policies")) + + +# --------------------------------------------------------------------------- +# Helpers +# --------------------------------------------------------------------------- + +def _save_levels(policy: ReminderPolicy, form) -> None: + """Parse multi-level form data and add ReminderPolicyLevel rows.""" + # Levels are submitted as: + # level_days_offset[] level_template_name[] level_late_fee_type[] + # level_late_fee_value[] level_sort_order[] level_active[] + offsets = form.getlist("level_days_offset[]") + templates = form.getlist("level_template_name[]") + fee_types = form.getlist("level_late_fee_type[]") + fee_values = form.getlist("level_late_fee_value[]") + sort_orders = form.getlist("level_sort_order[]") + actives = form.getlist("level_active[]") + + for idx, offset_str in enumerate(offsets): + offset_str = offset_str.strip() + if not offset_str: + continue + try: + days_offset = int(offset_str) + except ValueError: + continue + + fee_type = fee_types[idx].strip() if idx < len(fee_types) else "" + fee_value_str = fee_values[idx].strip() if idx < len(fee_values) else "" + sort_order_str = sort_orders[idx].strip() if idx < len(sort_orders) else "0" + active_val = actives[idx] if idx < len(actives) else "0" + + from decimal import Decimal, InvalidOperation + + try: + fee_value = Decimal(fee_value_str) if fee_value_str else None + except InvalidOperation: + fee_value = None + + try: + sort_order = int(sort_order_str) + except ValueError: + sort_order = idx + + lv = ReminderPolicyLevel( + policy_id=policy.id, + days_offset=days_offset, + template_name=templates[idx].strip() if idx < len(templates) else None, + late_fee_type=fee_type or None, + late_fee_value=fee_value, + sort_order=sort_order, + active=bool(active_val and active_val != "0"), + ) + db.session.add(lv) diff --git a/app/services/invoice_reminder_service.py b/app/services/invoice_reminder_service.py new file mode 100644 index 000000000..a86ffb042 --- /dev/null +++ b/app/services/invoice_reminder_service.py @@ -0,0 +1,270 @@ +"""Invoice reminder and late-fee service (Phase 4). + +Resolves the reminder policy for each unpaid invoice, checks which policy +levels are due today, fires email reminders, logs sends to +InvoiceReminderSchedule, and optionally applies late fees. +""" + +from __future__ import annotations + +import logging +from datetime import date, datetime +from decimal import Decimal, ROUND_HALF_UP +from typing import Optional + +logger = logging.getLogger(__name__) + +# Cap annual interest at 100 % to avoid runaway compound rounding +_MAX_ANNUAL_PERCENT = Decimal("100") + + +def resolve_policy(invoice): + """Return the ReminderPolicy for *invoice* (invoice > client > system default). + + Returns None when no policy is configured anywhere. + """ + from app.models.reminder_policy import ReminderPolicy + + # 1. Per-invoice override + if getattr(invoice, "reminder_policy_id", None): + policy = ReminderPolicy.query.get(invoice.reminder_policy_id) + if policy and policy.active: + return policy + + # 2. Client-level policy + client = getattr(invoice, "client", None) + if client is None and getattr(invoice, "client_id", None): + from app.models import Client + + client = Client.query.get(invoice.client_id) + + if client and getattr(client, "reminder_policy_id", None): + policy = ReminderPolicy.query.get(client.reminder_policy_id) + if policy and policy.active: + return policy + + # 3. System default + return ReminderPolicy.get_default() + + +def process_due_reminders(today: Optional[date] = None) -> int: + """Find and send all reminder levels that are due today. + + For each unpaid invoice (status in sent/issued/overdue) whose policy has + a level where ``(today - due_date).days >= days_offset`` and no + InvoiceReminderSchedule row for that (invoice_id, days_offset) has been + sent yet, we: + + 1. Send an email to the client. + 2. Create / update an InvoiceReminderSchedule row (last_sent_at = now). + 3. Log an InvoiceEmail record. + 4. Optionally apply late fee. + + Returns the total number of reminders sent. + """ + from app import db + from app.models import Invoice, InvoiceEmail + from app.models.payments import InvoiceReminderSchedule + + if today is None: + try: + from app.utils.timezone import now_in_app_timezone + + today = now_in_app_timezone().date() + except Exception: + today = date.today() + + invoices = Invoice.query.filter( + Invoice.status.in_(["sent", "issued", "overdue"]), + Invoice.payment_status != "fully_paid", + ).all() + + sent_total = 0 + for invoice in invoices: + try: + sent_total += _process_invoice(invoice, today, db, InvoiceReminderSchedule, InvoiceEmail) + except Exception as exc: + logger.error("Reminder processing failed for invoice %s: %s", invoice.id, exc, exc_info=True) + try: + db.session.rollback() + except Exception: + pass + + return sent_total + + +# --------------------------------------------------------------------------- +# Internal helpers +# --------------------------------------------------------------------------- + +def _process_invoice(invoice, today, db, InvoiceReminderSchedule, InvoiceEmail) -> int: + """Process reminder levels for a single invoice. Returns # sent.""" + policy = resolve_policy(invoice) + if policy is None: + return 0 + + levels = [lv for lv in policy.levels if lv.active] + if not levels: + return 0 + + due_date = invoice.due_date + if due_date is None: + return 0 + + days_since_due = (today - due_date).days # negative = before due + + sent = 0 + for level in levels: + # Level fires when days_since_due >= level.days_offset + if days_since_due < level.days_offset: + continue + + # Check whether this level was already sent for this invoice + existing = InvoiceReminderSchedule.query.filter_by( + invoice_id=invoice.id, + days_offset=level.days_offset, + ).first() + + if existing and existing.last_sent_at is not None: + continue # already sent – idempotent + + # Send email + success = _send_reminder_email(invoice, level) + + # Upsert InvoiceReminderSchedule row + if existing is None: + existing = InvoiceReminderSchedule( + invoice_id=invoice.id, + days_offset=level.days_offset, + template_name=level.template_name, + active=True, + ) + db.session.add(existing) + + existing.last_sent_at = datetime.utcnow() + existing.template_name = level.template_name + + # Log InvoiceEmail + if success: + recipient = _get_recipient(invoice) + if recipient: + ie = InvoiceEmail( + invoice_id=invoice.id, + recipient_email=recipient, + subject=_reminder_subject(invoice, level), + sent_by=invoice.created_by, + status="sent", + ) + db.session.add(ie) + + # Apply late fee (once per level, idempotent via last_sent_at check above) + _apply_late_fee(invoice, level, days_since_due) + + try: + db.session.commit() + except Exception as exc: + logger.error("DB commit failed for invoice %s level %s: %s", invoice.id, level.id, exc) + db.session.rollback() + continue + + sent += 1 + logger.info( + "Sent reminder for invoice %s (offset=%s, policy=%s)", + invoice.invoice_number, + level.days_offset, + policy.name, + ) + + return sent + + +def _get_recipient(invoice) -> Optional[str]: + """Return the best email address for the invoice client.""" + if invoice.client_email: + return invoice.client_email + client = getattr(invoice, "client", None) + if client and getattr(client, "email", None): + return client.email + return None + + +def _reminder_subject(invoice, level) -> str: + days = abs(level.days_offset) + if level.days_offset >= 0: + return f"Payment reminder – invoice {invoice.invoice_number} ({days} day{'s' if days != 1 else ''} overdue)" + return f"Upcoming invoice due – {invoice.invoice_number} (due in {days} day{'s' if days != 1 else ''})" + + +def _send_reminder_email(invoice, level) -> bool: + """Send the reminder email. Returns True on success, False on failure.""" + try: + from flask import current_app + + recipient = _get_recipient(invoice) + if not recipient: + logger.warning("No recipient email for invoice %s, skipping reminder", invoice.invoice_number) + return False + + subject = _reminder_subject(invoice, level) + days_offset = level.days_offset + + # Try to use send_invoice_email (attaches PDF) first; fall back to plain email + try: + from app.utils.email import send_invoice_email + + success, _, message = send_invoice_email(invoice, recipient) + if not success: + raise RuntimeError(message) + return True + except Exception as exc: + logger.debug("send_invoice_email failed (%s), falling back to plain reminder", exc) + + # Fallback: plain-text reminder + try: + from app.utils.email import send_template_email + from app.utils.urls import safe_external_url_for + + invoice_url = safe_external_url_for("invoices.view_invoice", invoice_id=invoice.id) + send_template_email( + to=recipient, + subject=subject, + template="email/invoice_reminder.html", + invoice=invoice, + days_offset=days_offset, + invoice_url=invoice_url, + ) + return True + except Exception as exc: + logger.warning("Fallback reminder email failed for invoice %s: %s", invoice.invoice_number, exc) + return False + + except Exception as exc: + logger.error("Unexpected error sending reminder for invoice %s: %s", invoice.invoice_number, exc) + return False + + +def _apply_late_fee(invoice, level, days_since_due: int) -> None: + """Add a late fee to invoice.late_fee_amount based on the level config.""" + if not level.late_fee_type or level.late_fee_value is None: + return + + fee_value = Decimal(str(level.late_fee_value)) + if fee_value <= 0: + return + + current_fee = Decimal(str(invoice.late_fee_amount or 0)) + + if level.late_fee_type == "fixed": + invoice.late_fee_amount = current_fee + fee_value + + elif level.late_fee_type == "percent_annual": + # Daily interest = annual_rate / 365 + # Applied once per level trigger (days_since_due already >= level.days_offset) + # Outstanding base = total_amount (pre-late-fee) to avoid compounding + annual_rate = min(fee_value, _MAX_ANNUAL_PERCENT) / Decimal("100") + daily_rate = annual_rate / Decimal("365") + base = Decimal(str(invoice.total_amount or 0)) + # Cap application period to actual days overdue (at most days_since_due) + days = max(days_since_due, 1) + interest = (base * daily_rate * days).quantize(Decimal("0.01"), rounding=ROUND_HALF_UP) + invoice.late_fee_amount = current_fee + interest diff --git a/app/templates/clients/edit.html b/app/templates/clients/edit.html index aef205925..f646073f2 100644 --- a/app/templates/clients/edit.html +++ b/app/templates/clients/edit.html @@ -190,6 +190,22 @@

{{ _('Client Portal Access') }}

+ {# ── Reminder Policy ─────────────────────────────────────────── #} +
+ + +

+ {{ _('Override the reminder schedule for invoices sent to this client.') }} +

+
+
{{ _('Cancel') }} diff --git a/app/templates/email/invoice_reminder.html b/app/templates/email/invoice_reminder.html new file mode 100644 index 000000000..426f00c8f --- /dev/null +++ b/app/templates/email/invoice_reminder.html @@ -0,0 +1,47 @@ + + + + + + + +
+

{% if days_offset >= 0 %}Payment Reminder{% else %}Upcoming Invoice Due{% endif %}

+
+
+

Dear {% if invoice.client %}{{ invoice.client.name }}{% else %}{{ invoice.client_name }}{% endif %},

+ + {% if days_offset >= 0 %} +

This is a friendly reminder that invoice {{ invoice.invoice_number }} is + {% if days_offset == 0 %}due today{% else %}{{ days_offset }} day{{ 's' if days_offset != 1 }} overdue{% endif %}. +

+ {% else %} +

This is a reminder that invoice {{ invoice.invoice_number }} is due in + {{ days_offset | abs }} day{{ 's' if (days_offset | abs) != 1 }}. +

+ {% endif %} + +
+ Invoice: {{ invoice.invoice_number }}
+ Amount due: {{ invoice.currency_code }} {{ "%.2f"|format(invoice.outstanding_amount) }}
+ Due date: {{ invoice.due_date }}
+ {% if invoice.late_fee_amount and invoice.late_fee_amount > 0 %} + Late fee accrued: {{ invoice.currency_code }} {{ "%.2f"|format(invoice.late_fee_amount) }}
+ {% endif %} +
+ + {% if invoice_url %} +

View Invoice

+ {% endif %} + +

Please arrange payment at your earliest convenience. If you have already paid, please disregard this reminder.

+

Thank you,
The TimeTracker Team

+
+ + diff --git a/app/templates/reminder_policies/edit.html b/app/templates/reminder_policies/edit.html new file mode 100644 index 000000000..1355072d7 --- /dev/null +++ b/app/templates/reminder_policies/edit.html @@ -0,0 +1,129 @@ +{% extends "base.html" %} +{% block title %}{{ 'Edit' if policy else 'New' }} Reminder Policy{% endblock %} +{% block content %} +
+

{{ 'Edit' if policy else 'New' }} Reminder Policy

+ + {% with messages = get_flashed_messages(with_categories=true) %} + {% for category, message in messages %} +
{{ message }}
+ {% endfor %} + {% endwith %} + +
+ + +
+
+ + +
+
+ + +
+
+ +

Levels

+

+ Days offset: negative = before due date, positive = after due date. +

+ +
+ {% set existing_levels = policy.levels.all() if policy else [] %} + {% for lv in existing_levels %} +
+
+
+ + +
+
+ + +
+
+ + +
+
+ + +
+
+ + +
+
+ +
+
+ +
+ {% endfor %} +
+ + + +
+ + Cancel +
+
+
+ + +{% endblock %} diff --git a/app/templates/reminder_policies/list.html b/app/templates/reminder_policies/list.html new file mode 100644 index 000000000..78c0f1746 --- /dev/null +++ b/app/templates/reminder_policies/list.html @@ -0,0 +1,51 @@ +{% extends "base.html" %} +{% block title %}Reminder Policies{% endblock %} +{% block content %} +
+
+

Reminder Policies

+ + New Policy +
+ + {% with messages = get_flashed_messages(with_categories=true) %} + {% for category, message in messages %} +
{{ message }}
+ {% endfor %} + {% endwith %} + + {% if policies %} +
+ + + + + + + + + + + + {% for policy in policies %} + + + + + + + + {% endfor %} + +
NameActiveDefaultLevelsActions
{{ policy.name }}{{ '✓' if policy.active else '✗' }}{{ '✓' if policy.is_default else '' }}{{ policy.levels.count() }} + Edit +
+ + +
+
+
+ {% else %} +

No reminder policies defined yet.

+ {% endif %} +
+{% endblock %} diff --git a/app/utils/scheduled_tasks.py b/app/utils/scheduled_tasks.py index 331ca660c..c022526cf 100644 --- a/app/utils/scheduled_tasks.py +++ b/app/utils/scheduled_tasks.py @@ -87,7 +87,11 @@ def check_overdue_invoices(): # Calendar "today" in app timezone (not UTC / host local) today = now_in_app_timezone().date() - overdue_invoices = Invoice.query.filter(Invoice.due_date < today, Invoice.status.in_(["draft", "sent"])).all() + overdue_invoices = Invoice.query.filter( + Invoice.due_date < today, + Invoice.status.in_(["sent", "issued"]), + Invoice.payment_status != "fully_paid", + ).all() logger.info(f"Found {len(overdue_invoices)} overdue invoices") @@ -97,6 +101,17 @@ def check_overdue_invoices(): if invoice.status != "overdue": invoice.status = "overdue" db.session.commit() + try: + from app.constants import WebhookEvent + from app.utils.invoice_events import emit_invoice_event + + emit_invoice_event(WebhookEvent.INVOICE_OVERDUE.value, invoice) + except Exception as emit_exc: + logger.debug( + "Failed to emit invoice.overdue for %s: %s", + invoice.invoice_number, + emit_exc, + ) # Get users to notify (creator and admins) users_to_notify = set() @@ -138,6 +153,17 @@ def check_overdue_invoices(): ) logger.info(f"Sent {notifications_sent} overdue invoice notifications") + + # --- Phase 4: multi-level reminder sends & late fees --- + try: + from app.services.invoice_reminder_service import process_due_reminders + + reminders_sent = process_due_reminders(today=today) + if reminders_sent: + logger.info("Invoice reminder service sent %d reminder(s)", reminders_sent) + except Exception as reminder_exc: + logger.error("Invoice reminder service failed: %s", reminder_exc, exc_info=True) + return notifications_sent except Exception as e: diff --git a/migrations/versions/211_invoice_reminder_policies.py b/migrations/versions/211_invoice_reminder_policies.py new file mode 100644 index 000000000..53113a3b5 --- /dev/null +++ b/migrations/versions/211_invoice_reminder_policies.py @@ -0,0 +1,115 @@ +"""Add reminder_policies, reminder_policy_levels tables; FK on clients/invoices; +late_fee_amount on invoices. + +Revision ID: 211_invoice_reminder_policies +Revises: 210_invoice_line_tax_discounts +""" + +import sqlalchemy as sa +from alembic import op +from sqlalchemy import inspect + +revision = "211_invoice_reminder_policies" +down_revision = "210_invoice_line_tax_discounts" +branch_labels = None +depends_on = None + + +def _has_table(inspector, name: str) -> bool: + try: + return name in inspector.get_table_names() + except Exception: + return False + + +def _has_column(inspector, table_name: str, column_name: str) -> bool: + try: + return column_name in {c["name"] for c in inspector.get_columns(table_name)} + except Exception: + return False + + +def _add_column_if_missing(inspector, table_name: str, column: sa.Column) -> None: + if not _has_column(inspector, table_name, column.name): + op.add_column(table_name, column) + + +def upgrade(): + bind = op.get_bind() + inspector = inspect(bind) + + # ── reminder_policies ─────────────────────────────────────────────────── + if not _has_table(inspector, "reminder_policies"): + op.create_table( + "reminder_policies", + sa.Column("id", sa.Integer(), nullable=False), + sa.Column("name", sa.String(length=100), nullable=False), + sa.Column("active", sa.Boolean(), nullable=False, server_default=sa.true()), + sa.Column("is_default", sa.Boolean(), nullable=False, server_default=sa.false()), + sa.Column("created_at", sa.DateTime(), nullable=False), + sa.Column("updated_at", sa.DateTime(), nullable=False), + sa.PrimaryKeyConstraint("id"), + ) + + # ── reminder_policy_levels ─────────────────────────────────────────────── + if not _has_table(inspector, "reminder_policy_levels"): + op.create_table( + "reminder_policy_levels", + sa.Column("id", sa.Integer(), nullable=False), + sa.Column("policy_id", sa.Integer(), nullable=False), + sa.Column("days_offset", sa.Integer(), nullable=False), + sa.Column("template_name", sa.String(length=100), nullable=True), + sa.Column( + "late_fee_type", + sa.String(length=20), + nullable=True, + ), # 'fixed' | 'percent_annual' | null + sa.Column("late_fee_value", sa.Numeric(10, 2), nullable=True), + sa.Column("sort_order", sa.Integer(), nullable=False, server_default="0"), + sa.Column("active", sa.Boolean(), nullable=False, server_default=sa.true()), + sa.Column("created_at", sa.DateTime(), nullable=False), + sa.Column("updated_at", sa.DateTime(), nullable=False), + sa.ForeignKeyConstraint(["policy_id"], ["reminder_policies.id"], ondelete="CASCADE"), + sa.PrimaryKeyConstraint("id"), + ) + + # ── clients.reminder_policy_id (nullable FK) ───────────────────────────── + _add_column_if_missing( + inspector, + "clients", + sa.Column("reminder_policy_id", sa.Integer(), sa.ForeignKey("reminder_policies.id"), nullable=True), + ) + + # ── invoices.reminder_policy_id (nullable FK) ──────────────────────────── + _add_column_if_missing( + inspector, + "invoices", + sa.Column("reminder_policy_id", sa.Integer(), sa.ForeignKey("reminder_policies.id"), nullable=True), + ) + + # ── invoices.late_fee_amount ────────────────────────────────────────────── + _add_column_if_missing( + inspector, + "invoices", + sa.Column("late_fee_amount", sa.Numeric(10, 2), nullable=False, server_default="0"), + ) + + +def downgrade(): + bind = op.get_bind() + inspector = inspect(bind) + + if _has_column(inspector, "invoices", "late_fee_amount"): + op.drop_column("invoices", "late_fee_amount") + + if _has_column(inspector, "invoices", "reminder_policy_id"): + op.drop_column("invoices", "reminder_policy_id") + + if _has_column(inspector, "clients", "reminder_policy_id"): + op.drop_column("clients", "reminder_policy_id") + + if _has_table(inspector, "reminder_policy_levels"): + op.drop_table("reminder_policy_levels") + + if _has_table(inspector, "reminder_policies"): + op.drop_table("reminder_policies") diff --git a/tests/test_invoice_reminders.py b/tests/test_invoice_reminders.py new file mode 100644 index 000000000..ac003fc1b --- /dev/null +++ b/tests/test_invoice_reminders.py @@ -0,0 +1,339 @@ +"""Tests for Phase 4 invoice reminder service (reminders & late fees). + +Covers: +- Level fires once (idempotent via last_sent_at) +- Draft invoice skipped +- Fully-paid invoice skipped +- Late fee (fixed) applied once +- Late fee (percent_annual) applied +- resolve_policy resolution order: invoice > client > default +""" + +from __future__ import annotations + +import pytest +from datetime import date, datetime +from decimal import Decimal + + +# --------------------------------------------------------------------------- +# Helpers to create minimal DB rows +# --------------------------------------------------------------------------- + +def _create_project(db, user, client): + from app.models import Project + + p = Project( + name="Test Project", + client=client.name, + created_by=user.id, + ) + p.client_id = client.id + db.session.add(p) + db.session.flush() + return p + + +def _create_client(db, user, name="Test Client", reminder_policy_id=None): + from app.models import Client + + c = Client( + name=name, + created_by=user.id, + ) + if reminder_policy_id: + c.reminder_policy_id = reminder_policy_id + db.session.add(c) + db.session.flush() + return c + + +def _create_invoice(db, user, project, client, due_date, status="sent", payment_status="unpaid"): + from app.models import Invoice + + inv = Invoice( + invoice_number=f"INV-TEST-{id(due_date)}", + project_id=project.id, + client_name=client.name, + client_email="client@example.com", + due_date=due_date, + created_by=user.id, + client_id=client.id, + ) + inv.status = status + inv.payment_status = payment_status + inv.total_amount = Decimal("1000.00") + inv.subtotal = Decimal("1000.00") + inv.tax_amount = Decimal("0.00") + inv.amount_paid = Decimal("0.00") + inv.late_fee_amount = Decimal("0.00") + db.session.add(inv) + db.session.flush() + return inv + + +def _create_policy(db, name="Test Policy", is_default=False): + from app.models.reminder_policy import ReminderPolicy, ReminderPolicyLevel + + policy = ReminderPolicy(name=name, active=True, is_default=is_default) + db.session.add(policy) + db.session.flush() + return policy + + +def _add_level(db, policy, days_offset, late_fee_type=None, late_fee_value=None, sort_order=0): + from app.models.reminder_policy import ReminderPolicyLevel + + lv = ReminderPolicyLevel( + policy_id=policy.id, + days_offset=days_offset, + active=True, + sort_order=sort_order, + late_fee_type=late_fee_type, + late_fee_value=Decimal(str(late_fee_value)) if late_fee_value is not None else None, + ) + db.session.add(lv) + db.session.flush() + return lv + + +# --------------------------------------------------------------------------- +# Tests +# --------------------------------------------------------------------------- + + +class TestProcessDueReminders: + def test_level_fires_once(self, app, user): + """A level whose days_offset is reached is fired exactly once.""" + with app.app_context(): + from app import db + from app.models.payments import InvoiceReminderSchedule + from app.services.invoice_reminder_service import process_due_reminders + + # due date was 5 days ago + today = date(2024, 6, 10) + due = date(2024, 6, 5) + + client = _create_client(db, user) + project = _create_project(db, user, client) + policy = _create_policy(db, "FireOnce") + _add_level(db, policy, days_offset=1) # fires 1+ day overdue + client.reminder_policy_id = policy.id + db.session.commit() + + inv = _create_invoice(db, user, project, client, due_date=due) + db.session.commit() + + # First run – should fire + count1 = process_due_reminders(today=today) + assert count1 >= 1 + + # Second run on same day – must NOT fire again + count2 = process_due_reminders(today=today) + assert count2 == 0, "Level should not fire twice for the same invoice+offset" + + def test_draft_skipped(self, app, user): + """Draft invoices are never processed.""" + with app.app_context(): + from app import db + from app.services.invoice_reminder_service import process_due_reminders + + today = date(2024, 6, 10) + due = date(2024, 6, 1) # very overdue + + client = _create_client(db, user, name="Draft Client") + project = _create_project(db, user, client) + policy = _create_policy(db, "DraftPolicy", is_default=True) + _add_level(db, policy, days_offset=0) + db.session.commit() + + inv = _create_invoice(db, user, project, client, due_date=due, status="draft") + db.session.commit() + + count = process_due_reminders(today=today) + # The draft invoice must not be in the result (other invoices may exist) + # We verify by checking no schedule row was created for this draft invoice + from app.models.payments import InvoiceReminderSchedule + rows = InvoiceReminderSchedule.query.filter_by(invoice_id=inv.id).all() + assert rows == [], "No reminder schedule rows should be created for a draft invoice" + + def test_paid_skipped(self, app, user): + """Fully-paid invoices are never processed.""" + with app.app_context(): + from app import db + from app.services.invoice_reminder_service import process_due_reminders + + today = date(2024, 6, 10) + due = date(2024, 6, 1) + + client = _create_client(db, user, name="Paid Client") + project = _create_project(db, user, client) + policy = _create_policy(db, "PaidPolicy", is_default=True) + _add_level(db, policy, days_offset=0) + db.session.commit() + + inv = _create_invoice( + db, user, project, client, + due_date=due, status="overdue", payment_status="fully_paid" + ) + inv.amount_paid = inv.total_amount + db.session.commit() + + from app.models.payments import InvoiceReminderSchedule + # Clear any rows that may have been added by other tests + InvoiceReminderSchedule.query.filter_by(invoice_id=inv.id).delete() + db.session.commit() + + process_due_reminders(today=today) + rows = InvoiceReminderSchedule.query.filter_by(invoice_id=inv.id).all() + assert rows == [], "Fully-paid invoice must not receive reminder" + + def test_late_fee_fixed_applied_once(self, app, user): + """Fixed late fee is added exactly once to invoice.late_fee_amount.""" + with app.app_context(): + from app import db + from app.services.invoice_reminder_service import process_due_reminders + from app.models import Invoice + + today = date(2024, 6, 10) + due = date(2024, 6, 5) + + client = _create_client(db, user, name="Fee Client Fixed") + project = _create_project(db, user, client) + policy = _create_policy(db, "FixedFeePolicy") + _add_level(db, policy, days_offset=1, late_fee_type="fixed", late_fee_value=50) + client.reminder_policy_id = policy.id + db.session.commit() + + inv = _create_invoice(db, user, project, client, due_date=due) + inv_id = inv.id + db.session.commit() + + # First run: late fee should be applied + process_due_reminders(today=today) + db.session.expire_all() + inv = Invoice.query.get(inv_id) + assert inv.late_fee_amount == Decimal("50.00"), ( + f"Expected late_fee_amount=50, got {inv.late_fee_amount}" + ) + + # Second run: late fee must NOT be added again + process_due_reminders(today=today) + db.session.expire_all() + inv = Invoice.query.get(inv_id) + assert inv.late_fee_amount == Decimal("50.00"), ( + "Late fee must only be applied once per level" + ) + + def test_late_fee_percent_annual_applied(self, app, user): + """Percent-annual late fee is computed and added.""" + with app.app_context(): + from app import db + from app.services.invoice_reminder_service import process_due_reminders + from app.models import Invoice + + today = date(2024, 6, 10) + due = date(2024, 6, 5) # 5 days overdue + + client = _create_client(db, user, name="Fee Client Percent") + project = _create_project(db, user, client) + policy = _create_policy(db, "PercentFeePolicy") + _add_level(db, policy, days_offset=1, late_fee_type="percent_annual", late_fee_value=36.5) + client.reminder_policy_id = policy.id + db.session.commit() + + inv = _create_invoice(db, user, project, client, due_date=due) + inv_id = inv.id + db.session.commit() + + process_due_reminders(today=today) + db.session.expire_all() + inv = Invoice.query.get(inv_id) + + # 36.5% annual / 365 = 0.1% per day; 5 days * 0.001 * 1000 = 5.00 + assert inv.late_fee_amount > Decimal("0"), "Late fee should be positive" + assert inv.late_fee_amount == Decimal("5.00"), ( + f"Expected 5.00, got {inv.late_fee_amount}" + ) + + +class TestResolvePolicy: + def test_invoice_level_wins_over_client(self, app, user): + """Invoice-level policy overrides client-level policy.""" + with app.app_context(): + from app import db + from app.models.reminder_policy import ReminderPolicy + from app.services.invoice_reminder_service import resolve_policy + + client = _create_client(db, user, name="RC Client") + project = _create_project(db, user, client) + + policy_client = _create_policy(db, "Client Policy") + policy_invoice = _create_policy(db, "Invoice Policy") + client.reminder_policy_id = policy_client.id + db.session.commit() + + due = date(2024, 6, 10) + inv = _create_invoice(db, user, project, client, due_date=due) + inv.reminder_policy_id = policy_invoice.id + db.session.commit() + + resolved = resolve_policy(inv) + assert resolved is not None + assert resolved.id == policy_invoice.id + + def test_client_level_wins_over_default(self, app, user): + """Client policy overrides system default.""" + with app.app_context(): + from app import db + from app.services.invoice_reminder_service import resolve_policy + + policy_default = _create_policy(db, "Default Policy", is_default=True) + policy_client = _create_policy(db, "Client Policy 2") + client = _create_client(db, user, name="RC Client 2", reminder_policy_id=policy_client.id) + project = _create_project(db, user, client) + db.session.commit() + + due = date(2024, 6, 10) + inv = _create_invoice(db, user, project, client, due_date=due) + db.session.commit() + + resolved = resolve_policy(inv) + assert resolved is not None + assert resolved.id == policy_client.id + + def test_fallback_to_default(self, app, user): + """When no invoice/client policy, fall back to system default.""" + with app.app_context(): + from app import db + from app.services.invoice_reminder_service import resolve_policy + + policy_default = _create_policy(db, "Default Policy 3", is_default=True) + client = _create_client(db, user, name="RC Client 3") + project = _create_project(db, user, client) + db.session.commit() + + due = date(2024, 6, 10) + inv = _create_invoice(db, user, project, client, due_date=due) + db.session.commit() + + resolved = resolve_policy(inv) + assert resolved is not None + assert resolved.id == policy_default.id + + +class TestOutstandingAmount: + def test_late_fee_included_in_outstanding(self, app, user): + """outstanding_amount = total + late_fee - amount_paid - credits.""" + with app.app_context(): + from app import db + + client = _create_client(db, user, name="OA Client") + project = _create_project(db, user, client) + due = date(2024, 6, 10) + inv = _create_invoice(db, user, project, client, due_date=due) + inv.late_fee_amount = Decimal("25.00") + db.session.commit() + db.session.refresh(inv) + + assert inv.outstanding_amount == Decimal("1025.00") From 6f6f3bc22e075e5d27bb67a73709388570d90b84 Mon Sep 17 00:00:00 2001 From: Dries Peeters Date: Sat, 14 Nov 2026 08:12:07 +0100 Subject: [PATCH 4/9] feat(invoicing): add end-to-end credit notes with e-invoice exports Extend credit notes with line items and numbering, add create/issue/PDF UI, and export Peppol UBL 381, CII 381, XRechnung, and FatturaPA TD04 documents linked back to the original invoice. --- app/blueprint_registry.py | 16 ++ app/models/__init__.py | 6 +- app/models/payments.py | 165 +++++++++++- app/routes/credit_notes.py | 247 ++++++++++++++++++ app/services/credit_note_service.py | 228 ++++++++++++++++ app/templates/credit_notes/list.html | 47 ++++ app/templates/credit_notes/view.html | 75 ++++++ app/templates/invoices/view.html | 148 +++++++++++ app/utils/credit_note_pdf.py | 77 ++++++ app/utils/invoice_numbering.py | 39 +++ .../versions/212_credit_notes_extended.py | 86 ++++++ tests/test_api_credit_notes_v1.py | 33 +++ tests/test_credit_notes.py | 110 ++++++++ 13 files changed, 1274 insertions(+), 3 deletions(-) create mode 100644 app/routes/credit_notes.py create mode 100644 app/services/credit_note_service.py create mode 100644 app/templates/credit_notes/list.html create mode 100644 app/templates/credit_notes/view.html create mode 100644 app/utils/credit_note_pdf.py create mode 100644 migrations/versions/212_credit_notes_extended.py create mode 100644 tests/test_credit_notes.py diff --git a/app/blueprint_registry.py b/app/blueprint_registry.py index a749f618d..07ce932db 100644 --- a/app/blueprint_registry.py +++ b/app/blueprint_registry.py @@ -308,6 +308,22 @@ def register_all_blueprints(app, logger=None): app.register_blueprint(custom_reports_bp) app.register_blueprint(salesman_reports_bp) + # Phase 4 – invoice reminder policies + try: + from app.routes.reminder_policies import reminder_policies_bp + + app.register_blueprint(reminder_policies_bp) + except Exception: + _log.exception("Could not register reminder_policies blueprint") + + # Phase 3 – credit notes + try: + from app.routes.credit_notes import credit_notes_bp + + app.register_blueprint(credit_notes_bp) + except Exception: + _log.exception("Could not register credit_notes blueprint") + _register_optional_blueprints(app, _log) diff --git a/app/models/__init__.py b/app/models/__init__.py index 2600540b5..e36ba8317 100644 --- a/app/models/__init__.py +++ b/app/models/__init__.py @@ -67,7 +67,7 @@ from .milestone import Milestone from .oauth_app import OAuthAccessToken, OAuthApplication, OAuthAuthorizationCode from .payment_gateway import PaymentGateway, PaymentTransaction -from .payments import CreditNote, InvoiceReminderSchedule, Payment +from .payments import CreditNote, CreditNoteItem, InvoiceReminderSchedule, Payment from .payroll_export_template import PayrollExportTemplate from .payroll_sync_log import PayrollSyncLog from .per_diem import PerDiem, PerDiemRate @@ -86,6 +86,7 @@ from .quote_version import QuoteVersion from .rate_override import RateOverride from .recurring_block import RecurringBlock +from .reminder_policy import ReminderPolicy, ReminderPolicyLevel from .recurring_invoice import RecurringInvoice from .recurring_project_cost import RecurringProjectCost from .recurring_task import RecurringTask @@ -146,6 +147,8 @@ "Geofence", "GeofencePolicy", "RecurringBlock", + "ReminderPolicy", + "ReminderPolicyLevel", "RateOverride", "SavedFilter", "ProjectCost", @@ -157,6 +160,7 @@ "PayrollExportTemplate", "PayrollSyncLog", "CreditNote", + "CreditNoteItem", "InvoiceReminderSchedule", "SavedReportView", "SharedReportLink", diff --git a/app/models/payments.py b/app/models/payments.py index 3ec78127b..c03427d76 100644 --- a/app/models/payments.py +++ b/app/models/payments.py @@ -1,4 +1,4 @@ -from datetime import datetime +from datetime import datetime, date as _date from decimal import Decimal from app import db @@ -71,15 +71,176 @@ class CreditNote(db.Model): id = db.Column(db.Integer, primary_key=True) invoice_id = db.Column(db.Integer, db.ForeignKey("invoices.id"), nullable=False, index=True) credit_number = db.Column(db.String(50), unique=True, nullable=False, index=True) - amount = db.Column(db.Numeric(10, 2), nullable=False) + # Legacy flat amount field — preserved for backward compat; new code uses total_amount. + amount = db.Column(db.Numeric(10, 2), nullable=False, default=0) reason = db.Column(db.Text, nullable=True) created_by = db.Column(db.Integer, db.ForeignKey("users.id"), nullable=False) created_at = db.Column(db.DateTime, default=datetime.utcnow, nullable=False) updated_at = db.Column(db.DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False) + # Extended fields (migration 212) + status = db.Column(db.String(20), default="draft", nullable=False) + issue_date = db.Column(db.Date, nullable=True) + currency_code = db.Column(db.String(3), nullable=True, default="EUR") + subtotal = db.Column(db.Numeric(10, 2), nullable=True, default=0) + tax_amount = db.Column(db.Numeric(10, 2), nullable=True, default=0) + total_amount = db.Column(db.Numeric(10, 2), nullable=True, default=0) + tax_rate = db.Column(db.Numeric(5, 2), nullable=True, default=0) + vat_category = db.Column(db.String(5), nullable=True) + notes = db.Column(db.Text, nullable=True) + + # Relationships + items = db.relationship( + "CreditNoteItem", backref="credit_note", lazy="dynamic", cascade="all, delete-orphan" + ) + creator = db.relationship("User", backref="created_credit_notes", foreign_keys=[created_by]) + def __repr__(self): return f"" + # ------------------------------------------------------------------ + # Totals + # ------------------------------------------------------------------ + + def calculate_totals(self): + """Recalculate subtotal / tax_amount / total_amount from line items. + + Falls back to the legacy `amount` field when there are no items. + """ + line_items = self.items.all() if hasattr(self.items, "all") else list(self.items or []) + if not line_items: + # Legacy flat-amount mode + subtotal = Decimal(str(self.amount or 0)) + rate = Decimal(str(self.tax_rate or 0)) + tax = (subtotal * rate / 100).quantize(Decimal("0.01")) + self.subtotal = subtotal + self.tax_amount = tax + self.total_amount = subtotal + tax + return + + subtotal = Decimal("0") + tax_total = Decimal("0") + for item in line_items: + line_subtotal = Decimal(str(item.total_amount or 0)) + subtotal += line_subtotal + item_rate = Decimal(str(item.tax_rate if item.tax_rate is not None else (self.tax_rate or 0))) + tax_total += (line_subtotal * item_rate / 100).quantize(Decimal("0.01")) + + self.subtotal = subtotal + self.tax_amount = tax_total + self.total_amount = subtotal + tax_total + # Keep legacy amount in sync + self.amount = self.total_amount + + # ------------------------------------------------------------------ + # Serialisation + # ------------------------------------------------------------------ + + def to_dict(self, include_items=True): + d = { + "id": self.id, + "invoice_id": self.invoice_id, + "credit_number": self.credit_number, + "status": self.status, + "amount": float(self.amount or 0), + "subtotal": float(self.subtotal or 0), + "tax_amount": float(self.tax_amount or 0), + "total_amount": float(self.total_amount or 0), + "tax_rate": float(self.tax_rate or 0), + "vat_category": self.vat_category, + "currency_code": self.currency_code or "EUR", + "reason": self.reason, + "notes": self.notes, + "issue_date": self.issue_date.isoformat() if self.issue_date else None, + "created_by": self.created_by, + "created_at": self.created_at.isoformat() if self.created_at else None, + "updated_at": self.updated_at.isoformat() if self.updated_at else None, + } + if include_items: + line_items = self.items.all() if hasattr(self.items, "all") else list(self.items or []) + d["items"] = [i.to_dict() for i in sorted(line_items, key=lambda x: x.position)] + return d + + +class CreditNoteItem(db.Model): + """Line item on a credit note.""" + + __tablename__ = "credit_note_items" + + id = db.Column(db.Integer, primary_key=True) + credit_note_id = db.Column(db.Integer, db.ForeignKey("credit_notes.id"), nullable=False, index=True) + description = db.Column(db.String(500), nullable=False) + quantity = db.Column(db.Numeric(10, 2), nullable=False, default=1) + unit_price = db.Column(db.Numeric(10, 2), nullable=False, default=0) + total_amount = db.Column(db.Numeric(10, 2), nullable=False, default=0) + tax_rate = db.Column(db.Numeric(5, 2), nullable=True) + vat_category = db.Column(db.String(5), nullable=True) + discount_percent = db.Column(db.Numeric(5, 2), nullable=True, default=0) + discount_amount = db.Column(db.Numeric(10, 2), nullable=True, default=0) + position = db.Column(db.Integer, nullable=False, default=0) + invoice_item_id = db.Column(db.Integer, db.ForeignKey("invoice_items.id"), nullable=True) + created_at = db.Column(db.DateTime, default=datetime.utcnow, nullable=False) + + # Optional back-reference to source invoice item + source_invoice_item = db.relationship("InvoiceItem", foreign_keys=[invoice_item_id]) + + def __init__( + self, + credit_note_id, + description, + quantity, + unit_price, + tax_rate=None, + vat_category=None, + discount_percent=None, + discount_amount=None, + position=0, + invoice_item_id=None, + ): + self.credit_note_id = credit_note_id + self.description = description + self.quantity = Decimal(str(quantity)) + self.unit_price = Decimal(str(unit_price)) + self.tax_rate = Decimal(str(tax_rate)) if tax_rate is not None else None + self.vat_category = vat_category + self.discount_percent = Decimal(str(discount_percent)) if discount_percent is not None else Decimal("0") + self.discount_amount = Decimal(str(discount_amount)) if discount_amount is not None else Decimal("0") + self.position = int(position) if position is not None else 0 + self.invoice_item_id = invoice_item_id + self.total_amount = self.line_net + + @property + def line_discount_total(self) -> Decimal: + disc_amt = Decimal(str(self.discount_amount or 0)) + if disc_amt: + return disc_amt + disc_pct = Decimal(str(self.discount_percent or 0)) + if disc_pct: + gross = Decimal(str(self.quantity or 1)) * Decimal(str(self.unit_price or 0)) + return (gross * disc_pct / 100).quantize(Decimal("0.01")) + return Decimal("0") + + @property + def line_net(self) -> Decimal: + gross = Decimal(str(self.quantity or 1)) * Decimal(str(self.unit_price or 0)) + return max(Decimal("0"), gross - self.line_discount_total) + + def to_dict(self): + return { + "id": self.id, + "credit_note_id": self.credit_note_id, + "description": self.description, + "quantity": float(self.quantity), + "unit_price": float(self.unit_price), + "total_amount": float(self.total_amount), + "tax_rate": float(self.tax_rate) if self.tax_rate is not None else None, + "vat_category": self.vat_category, + "discount_percent": float(self.discount_percent or 0), + "discount_amount": float(self.discount_amount or 0), + "position": self.position, + "invoice_item_id": self.invoice_item_id, + } + class InvoiceReminderSchedule(db.Model): """Schedules to send invoice reminders before/after due dates.""" diff --git a/app/routes/credit_notes.py b/app/routes/credit_notes.py new file mode 100644 index 000000000..20266cc87 --- /dev/null +++ b/app/routes/credit_notes.py @@ -0,0 +1,247 @@ +"""Credit Notes blueprint — Phase 3 web UI + PDF + e-invoicing download routes.""" + +from __future__ import annotations + +import io +import logging + +from flask import ( + Blueprint, + Response, + abort, + current_app, + flash, + jsonify, + redirect, + render_template, + request, + send_file, + url_for, +) +from flask_babel import gettext as _ +from flask_login import current_user, login_required + +from app import db +from app.models import Invoice +from app.models.payments import CreditNote +from app.utils.module_helpers import module_enabled + +credit_notes_bp = Blueprint("credit_notes", __name__, url_prefix="/credit-notes") +logger = logging.getLogger(__name__) + + +# --------------------------------------------------------------------------- +# Helpers +# --------------------------------------------------------------------------- + +def _check_access(invoice): + """Raise 403 if the current user doesn't own or admin the invoice.""" + if not current_user.is_admin and invoice.created_by != current_user.id: + abort(403) + + +def _get_cn_or_404(cn_id): + return CreditNote.query.get_or_404(cn_id) + + +# --------------------------------------------------------------------------- +# List (optional simple view) +# --------------------------------------------------------------------------- + +@credit_notes_bp.route("/") +@login_required +@module_enabled("invoices") +def list_credit_notes(): + if current_user.is_admin: + cns = CreditNote.query.order_by(CreditNote.created_at.desc()).limit(200).all() + else: + cns = ( + CreditNote.query.join(Invoice, CreditNote.invoice_id == Invoice.id) + .filter(Invoice.created_by == current_user.id) + .order_by(CreditNote.created_at.desc()) + .limit(200) + .all() + ) + return render_template("credit_notes/list.html", credit_notes=cns) + + +# --------------------------------------------------------------------------- +# Create from invoice (POST) +# --------------------------------------------------------------------------- + +@credit_notes_bp.route("/create-from-invoice/", methods=["POST"]) +@login_required +@module_enabled("invoices") +def create_from_invoice(invoice_id): + invoice = Invoice.query.get_or_404(invoice_id) + _check_access(invoice) + + if invoice.status == "draft": + flash(_("Cannot create credit note for a draft invoice."), "error") + return redirect(url_for("invoices.view_invoice", invoice_id=invoice_id)) + + mode = request.form.get("mode", "full") # full | amount + reason = (request.form.get("reason") or "").strip() + + from app.services.credit_note_service import CreditNoteService + + try: + if mode == "full": + cn = CreditNoteService.create_full_credit(invoice, current_user.id, reason=reason) + else: + raw_amount = request.form.get("amount", "0") + try: + from decimal import Decimal + amount = Decimal(str(raw_amount)) + except Exception: + flash(_("Invalid amount."), "error") + return redirect(url_for("invoices.view_invoice", invoice_id=invoice_id)) + description = request.form.get("description") or reason or _("Credit") + cn = CreditNoteService.create_amount_credit( + invoice, current_user.id, amount, reason=reason, description=description + ) + + flash(_("Credit note %(cn)s created.", cn=cn.credit_number), "success") + return redirect(url_for("credit_notes.view_credit_note", cn_id=cn.id)) + except Exception as exc: + db.session.rollback() + logger.exception("Failed to create credit note for invoice %s", invoice_id) + flash(_("Could not create credit note: %(err)s", err=str(exc)), "error") + return redirect(url_for("invoices.view_invoice", invoice_id=invoice_id)) + + +# --------------------------------------------------------------------------- +# View +# --------------------------------------------------------------------------- + +@credit_notes_bp.route("/") +@login_required +@module_enabled("invoices") +def view_credit_note(cn_id): + cn = _get_cn_or_404(cn_id) + invoice = Invoice.query.get_or_404(cn.invoice_id) + _check_access(invoice) + items = cn.items.all() if hasattr(cn.items, "all") else list(cn.items or []) + items = sorted(items, key=lambda x: x.position) + return render_template("credit_notes/view.html", cn=cn, invoice=invoice, items=items) + + +# --------------------------------------------------------------------------- +# Issue (POST) +# --------------------------------------------------------------------------- + +@credit_notes_bp.route("//issue", methods=["POST"]) +@login_required +@module_enabled("invoices") +def issue_credit_note(cn_id): + cn = _get_cn_or_404(cn_id) + invoice = Invoice.query.get_or_404(cn.invoice_id) + _check_access(invoice) + + if cn.status not in ("draft",): + flash(_("Credit note is already issued."), "warning") + return redirect(url_for("credit_notes.view_credit_note", cn_id=cn_id)) + + from app.services.credit_note_service import CreditNoteService + + CreditNoteService.issue_credit_note(cn) + db.session.commit() + flash(_("Credit note %(cn)s issued.", cn=cn.credit_number), "success") + return redirect(url_for("credit_notes.view_credit_note", cn_id=cn_id)) + + +# --------------------------------------------------------------------------- +# PDF download +# --------------------------------------------------------------------------- + +@credit_notes_bp.route("//pdf") +@login_required +@module_enabled("invoices") +def download_pdf(cn_id): + cn = _get_cn_or_404(cn_id) + invoice = Invoice.query.get_or_404(cn.invoice_id) + _check_access(invoice) + + try: + from app.utils.credit_note_pdf import generate_credit_note_pdf + pdf_bytes = generate_credit_note_pdf(cn) + except Exception as exc: + logger.exception("Credit note PDF generation failed for cn=%s", cn_id) + abort(500, description=str(exc)) + + filename = f"credit-note-{cn.credit_number}.pdf" + return send_file( + io.BytesIO(pdf_bytes), + mimetype="application/pdf", + as_attachment=True, + download_name=filename, + ) + + +# --------------------------------------------------------------------------- +# E-invoicing XML download routes +# --------------------------------------------------------------------------- + +@credit_notes_bp.route("//ubl") +@login_required +@module_enabled("invoices") +def download_ubl(cn_id): + """Download Peppol UBL CreditNote XML (type 381).""" + cn = _get_cn_or_404(cn_id) + invoice = Invoice.query.get_or_404(cn.invoice_id) + _check_access(invoice) + + try: + from app.integrations.peppol import build_peppol_ubl_credit_note_xml, PeppolParty + from app.models import Settings + + settings = Settings.get_settings() + supplier = PeppolParty( + endpoint_id=getattr(settings, "peppol_sender_id", "") or "", + endpoint_scheme_id=getattr(settings, "peppol_sender_scheme", "0088") or "0088", + name=getattr(settings, "company_name", "Supplier") or "Supplier", + tax_id=getattr(settings, "company_tax_id", None), + ) + customer = PeppolParty( + endpoint_id=getattr(invoice, "buyer_reference", "") or "", + endpoint_scheme_id="0088", + name=invoice.client_name or "Customer", + ) + xml_str, _ = build_peppol_ubl_credit_note_xml(cn, invoice, supplier, customer) + except Exception as exc: + logger.exception("UBL credit note XML build failed for cn=%s", cn_id) + abort(500, description=str(exc)) + + filename = f"credit-note-{cn.credit_number}-ubl.xml" + return Response( + xml_str, + mimetype="application/xml", + headers={"Content-Disposition": f'attachment; filename="{filename}"'}, + ) + + +@credit_notes_bp.route("//fatturapa") +@login_required +@module_enabled("invoices") +def download_fatturapa(cn_id): + """Download FatturaPA XML (TD04 credit note).""" + cn = _get_cn_or_404(cn_id) + invoice = Invoice.query.get_or_404(cn.invoice_id) + _check_access(invoice) + + try: + from app.utils.fatturapa import build_fatturapa_credit_note_xml + from app.models import Settings, Client + + settings = Settings.get_settings() + client = Client.query.get(invoice.client_id) if invoice.client_id else None + xml_bytes, filename = build_fatturapa_credit_note_xml(cn, invoice, settings, client) + except Exception as exc: + logger.exception("FatturaPA credit note XML build failed for cn=%s", cn_id) + abort(500, description=str(exc)) + + return Response( + xml_bytes, + mimetype="application/xml", + headers={"Content-Disposition": f'attachment; filename="{filename}"'}, + ) diff --git a/app/services/credit_note_service.py b/app/services/credit_note_service.py new file mode 100644 index 000000000..12e64a0a6 --- /dev/null +++ b/app/services/credit_note_service.py @@ -0,0 +1,228 @@ +"""Credit Note Service — Phase 3. + +Provides high-level operations for creating, issuing, and querying credit notes. +""" + +from __future__ import annotations + +from datetime import date +from decimal import Decimal +from typing import Any, Dict, List, Optional + +from app import db + + +class CreditNoteService: + """Business logic for credit notes.""" + + # ------------------------------------------------------------------ + # Creation helpers + # ------------------------------------------------------------------ + + @staticmethod + def _make_credit_note(invoice: Any, user_id: int, reason: Optional[str] = None) -> Any: + """Create a bare (not-yet-committed) CreditNote linked to *invoice*.""" + from app.models.payments import CreditNote + from app.utils.invoice_numbering import allocate_next_credit_note_number + + credit_number = allocate_next_credit_note_number() + cn = CreditNote( + invoice_id=invoice.id, + credit_number=credit_number, + amount=Decimal("0"), + reason=reason or "", + created_by=user_id, + status="draft", + currency_code=getattr(invoice, "currency_code", "EUR") or "EUR", + tax_rate=getattr(invoice, "tax_rate", Decimal("0")) or Decimal("0"), + vat_category=getattr(invoice, "vat_category", None), + notes=reason, + ) + return cn + + @staticmethod + def _copy_invoice_items(cn: Any, invoice: Any, qty_multiplier: Decimal = Decimal("1")) -> None: + """Copy all line items from *invoice* to *cn*, scaling quantity by *qty_multiplier*.""" + from app.models.payments import CreditNoteItem + + line_items = invoice.items.all() if hasattr(invoice.items, "all") else list(invoice.items or []) + for pos, item in enumerate(sorted(line_items, key=lambda x: getattr(x, "position", 0))): + qty = Decimal(str(item.quantity or 1)) * qty_multiplier + cni = CreditNoteItem( + credit_note_id=cn.id, + description=item.description, + quantity=qty, + unit_price=Decimal(str(item.unit_price or 0)), + tax_rate=item.tax_rate, + vat_category=item.vat_category, + discount_percent=item.discount_percent, + discount_amount=item.discount_amount, + position=pos, + invoice_item_id=item.id, + ) + db.session.add(cni) + + # ------------------------------------------------------------------ + # Public API + # ------------------------------------------------------------------ + + @classmethod + def create_full_credit( + cls, invoice: Any, user_id: int, reason: Optional[str] = None, auto_issue: bool = True + ) -> Any: + """Create a full credit note for *invoice* covering all line items. + + When *auto_issue* is True (default) the credit note is immediately issued and + the invoice status is set to 'cancelled' because the credit covers the full amount. + """ + cn = cls._make_credit_note(invoice, user_id, reason) + db.session.add(cn) + db.session.flush() # get cn.id + + cls._copy_invoice_items(cn, invoice) + db.session.flush() + + cn.calculate_totals() + + if auto_issue: + cls.issue_credit_note(cn) + # Full credit → cancel the invoice + if hasattr(invoice, "status"): + invoice.status = "cancelled" + + db.session.commit() + cls._emit_created(cn) + return cn + + @classmethod + def create_partial_credit( + cls, + invoice: Any, + user_id: int, + item_specs: List[Dict[str, Any]], + reason: Optional[str] = None, + auto_issue: bool = False, + ) -> Any: + """Create a partial credit note for selected lines. + + *item_specs* is a list of dicts with keys: + - ``invoice_item_id`` (int): source line item id + - ``quantity`` (Decimal|float|str): quantity to credit (defaults to full line qty) + """ + from app.models.payments import CreditNoteItem + from app.models.invoice import InvoiceItem + + cn = cls._make_credit_note(invoice, user_id, reason) + db.session.add(cn) + db.session.flush() + + spec_map: Dict[int, Decimal] = {} + for spec in item_specs: + iid = int(spec["invoice_item_id"]) + qty = Decimal(str(spec.get("quantity", 0))) + spec_map[iid] = qty + + line_items = invoice.items.all() if hasattr(invoice.items, "all") else list(invoice.items or []) + for pos, item in enumerate(sorted(line_items, key=lambda x: getattr(x, "position", 0))): + if item.id not in spec_map: + continue + qty = spec_map[item.id] or Decimal(str(item.quantity or 1)) + cni = CreditNoteItem( + credit_note_id=cn.id, + description=item.description, + quantity=qty, + unit_price=Decimal(str(item.unit_price or 0)), + tax_rate=item.tax_rate, + vat_category=item.vat_category, + discount_percent=item.discount_percent, + discount_amount=item.discount_amount, + position=pos, + invoice_item_id=item.id, + ) + db.session.add(cni) + + db.session.flush() + cn.calculate_totals() + + if auto_issue: + cls.issue_credit_note(cn) + + db.session.commit() + cls._emit_created(cn) + return cn + + @classmethod + def create_amount_credit( + cls, + invoice: Any, + user_id: int, + amount: Any, + reason: Optional[str] = None, + description: Optional[str] = None, + auto_issue: bool = False, + ) -> Any: + """Create a free-form single-line credit note for a given *amount*.""" + from app.models.payments import CreditNoteItem + + cn = cls._make_credit_note(invoice, user_id, reason) + # Free-form amount is the total credit against outstanding (tax included / + # no extra VAT layer), so keep tax_rate at 0 for this mode. + cn.amount = Decimal(str(amount)) + cn.tax_rate = Decimal("0") + db.session.add(cn) + db.session.flush() + + cni = CreditNoteItem( + credit_note_id=cn.id, + description=description or reason or "Credit", + quantity=Decimal("1"), + unit_price=Decimal(str(amount)), + tax_rate=Decimal("0"), + vat_category=cn.vat_category, + position=0, + ) + db.session.add(cni) + db.session.flush() + + cn.calculate_totals() + + if auto_issue: + cls.issue_credit_note(cn) + + db.session.commit() + cls._emit_created(cn) + return cn + + @staticmethod + def _emit_created(cn: Any) -> None: + try: + from app.constants import WebhookEvent + from app.utils.invoice_events import emit_credit_note_event + + emit_credit_note_event(WebhookEvent.CREDIT_NOTE_CREATED.value, cn) + except Exception: + pass + + @staticmethod + def issue_credit_note(cn: Any) -> None: + """Mark a credit note as issued and set issue_date if not already set.""" + cn.status = "issued" + if not cn.issue_date: + cn.issue_date = date.today() + + @staticmethod + def recalculate_invoice_outstanding(invoice: Any) -> None: + """Recompute invoice outstanding_amount (triggers existing property; nothing to store).""" + # The outstanding_amount property on Invoice already sums credits dynamically. + # This is a no-op hook for callers that want explicit recalculation semantics. + _ = invoice.outstanding_amount + + @staticmethod + def get_credits_for_invoice(invoice_id: int) -> List[Any]: + from app.models.payments import CreditNote + + return ( + CreditNote.query.filter_by(invoice_id=invoice_id) + .order_by(CreditNote.created_at.desc()) + .all() + ) diff --git a/app/templates/credit_notes/list.html b/app/templates/credit_notes/list.html new file mode 100644 index 000000000..acd212857 --- /dev/null +++ b/app/templates/credit_notes/list.html @@ -0,0 +1,47 @@ +{% extends "base.html" %} +{% from 'components/ui.html' import page_header %} + +{% block content %} +{{ page_header('fas fa-file-invoice-dollar', _('Credit Notes'), breadcrumbs=[{'text': _('Credit Notes')}]) }} + +
+ {% if credit_notes %} +
+ + + + + + + + + + + + + {% for cn in credit_notes %} + + + + + + + + + {% endfor %} + +
{{ _('Number') }}{{ _('Invoice') }}{{ _('Amount') }}{{ _('Status') }}{{ _('Created') }}{{ _('Actions') }}
{{ cn.credit_number }} + {% if cn.invoice %} + {{ cn.invoice.invoice_number }} + {% else %} + #{{ cn.invoice_id }} + {% endif %} + {{ '%.2f'|format(cn.total_amount or cn.amount or 0) }} {{ cn.currency_code or '' }}{{ cn.status }}{{ cn.created_at|user_datetime if cn.created_at else '—' }} + {{ _('View') }} +
+
+ {% else %} +

{{ _('No credit notes yet.') }}

+ {% endif %} +
+{% endblock %} diff --git a/app/templates/credit_notes/view.html b/app/templates/credit_notes/view.html new file mode 100644 index 000000000..c75c23131 --- /dev/null +++ b/app/templates/credit_notes/view.html @@ -0,0 +1,75 @@ +{% extends "base.html" %} +{% from 'components/ui.html' import page_header %} + +{% block content %} +{% set actions %} +
+ {{ _('Back to Invoice') }} + {{ _('PDF') }} + {{ _('UBL 381') }} + {{ _('FatturaPA TD04') }} + {% if cn.status == 'draft' %} +
+ + +
+ {% endif %} +
+{% endset %} +{{ page_header('fas fa-file-invoice-dollar', _('Credit Note') ~ ' ' ~ cn.credit_number, actions_html=actions, breadcrumbs=[{'text': _('Invoices'), 'url': url_for('invoices.list_invoices')}, {'text': invoice.invoice_number, 'url': url_for('invoices.view_invoice', invoice_id=invoice.id)}, {'text': cn.credit_number}]) }} + +
+
+
+
+
{{ _('Status') }}
{{ cn.status }}
+
{{ _('Issue date') }}
{{ cn.issue_date or '—' }}
+
{{ _('Currency') }}
{{ cn.currency_code or invoice.currency_code }}
+
{{ _('Original invoice') }}
{{ invoice.invoice_number }}
+
{{ _('Reason') }}
{{ cn.reason or '—' }}
+
+
+ +
+

{{ _('Line items') }}

+ {% if items %} +
+ + + + + + + + + + + {% for item in items %} + + + + + + + {% endfor %} + +
{{ _('Description') }}{{ _('Qty') }}{{ _('Unit price') }}{{ _('Total') }}
{{ item.description }}{{ '%.2f'|format(item.quantity) }}{{ '%.2f'|format(item.unit_price) }}{{ '%.2f'|format(item.total_amount) }}
+
+ {% else %} +

{{ _('Amount-only credit (no line items).') }}

+ {% endif %} +
+
+ +
+
+

{{ _('Totals') }}

+
+
{{ _('Subtotal') }}
{{ '%.2f'|format(cn.subtotal or 0) }}
+
{{ _('Tax') }}
{{ '%.2f'|format(cn.tax_amount or 0) }}
+
{{ _('Total credit') }}
{{ '%.2f'|format(cn.total_amount or cn.amount or 0) }}
+
+
+
+
+{% endblock %} diff --git a/app/templates/invoices/view.html b/app/templates/invoices/view.html index 1e32743f6..493a855c7 100644 --- a/app/templates/invoices/view.html +++ b/app/templates/invoices/view.html @@ -4,7 +4,11 @@ {% block content %} {% set actions %}
+{% if invoice.status == 'draft' %} Edit +{% else %} +{{ _('Notes / Due date') }} +{% endif %}
+ + + + + +
+ + +
+ +
+
+ +{% endif %} + + +{% set reminder_schedules = invoice.reminder_schedules.all() %} +{% set reminder_emails = invoice.email_records | selectattr('status', 'ne', 'failed') | list %} +{% if reminder_schedules or reminder_emails %} +
+

+ {{ _('Reminder History') }} +

+ {% if reminder_schedules %} +

{{ _('Scheduled Reminders') }}

+
+ + + + + + + + + + + {% for rs in reminder_schedules | sort(attribute='days_offset') %} + + + + + + + {% endfor %} + +
{{ _('Days Offset') }}{{ _('Template') }}{{ _('Last Sent') }}{{ _('Status') }}
{{ rs.days_offset }}{{ rs.template_name or '—' }}{{ rs.last_sent_at.strftime('%Y-%m-%d %H:%M') if rs.last_sent_at else '—' }} + {% if rs.last_sent_at %} + {{ _('Sent') }} + {% elif rs.active %} + {{ _('Pending') }} + {% else %} + {{ _('Inactive') }} + {% endif %} +
+
+ {% endif %} + {% if reminder_emails %} +

{{ _('Reminder Emails Sent') }}

+
+ + + + + + + + + + + {% for em in reminder_emails | sort(attribute='sent_at', reverse=True) %} + + + + + + + {% endfor %} + +
{{ _('Recipient') }}{{ _('Subject') }}{{ _('Sent At') }}{{ _('Status') }}
{{ em.recipient_email }}{{ em.subject }}{{ em.sent_at.strftime('%Y-%m-%d %H:%M') if em.sent_at else '—' }}{{ em.status }}
+
+ {% endif %} +
+{% endif %} + - {% if invoice.payment_status != 'fully_paid' %}
+ {% if invoice.payment_status != 'fully_paid' %} {{ _('Pay Invoice') }} + {% endif %} + + + {{ _('Download PDF') }} + {{ _('Back to Invoices') }}
- {% endif %} {% if invoice.notes %}
diff --git a/app/templates/email/payment_receipt.html b/app/templates/email/payment_receipt.html new file mode 100644 index 000000000..7666f48e0 --- /dev/null +++ b/app/templates/email/payment_receipt.html @@ -0,0 +1,105 @@ + + + + + + + +
+

✓ Payment Received

+

Thank you — your payment has been recorded.

+
+ +
+

Dear {{ client_name or 'Valued Customer' }},

+

We have received your payment. Here is your receipt:

+ +
+
{{ currency }} {{ "%.2f"|format(amount) }}
+ +
+
+ Invoice Number + {{ invoice_number }} +
+
+ Payment Date + {{ payment_date }} +
+ {% if payment_method %} +
+ Payment Method + {{ payment_method }} +
+ {% endif %} + {% if reference %} +
+ Reference + {{ reference }} +
+ {% endif %} +
+ Status + Completed +
+
+
+ +

If you have any questions about this payment, please don't hesitate to contact us.

+

Thank you for your business!

+
+ + + + diff --git a/app/templates/payment_gateways/create.html b/app/templates/payment_gateways/create.html index cf46a4335..670d9ecfb 100644 --- a/app/templates/payment_gateways/create.html +++ b/app/templates/payment_gateways/create.html @@ -28,6 +28,7 @@

{{ _('Configure Payment Gateway') }}

+
@@ -64,6 +65,22 @@

{{ _('PayPal Configuration') }}

+
+ + +

{{ _('PayPal webhook ID for signature verification (from PayPal Developer Dashboard)') }}

+
+
+
+ + @@ -88,10 +105,13 @@

{{ _('PayPal Configuration') }}

document.getElementById('stripeFields').classList.add('hidden'); document.getElementById('paypalFields').classList.add('hidden'); + document.getElementById('mollieFields').classList.add('hidden'); if (provider === 'stripe') { document.getElementById('stripeFields').classList.remove('hidden'); } else if (provider === 'paypal') { document.getElementById('paypalFields').classList.remove('hidden'); + } else if (provider === 'mollie') { + document.getElementById('mollieFields').classList.remove('hidden'); } } diff --git a/app/templates/payment_gateways/pay.html b/app/templates/payment_gateways/pay.html index a54ecff12..604a0f4ff 100644 --- a/app/templates/payment_gateways/pay.html +++ b/app/templates/payment_gateways/pay.html @@ -22,13 +22,12 @@

{{ _('Pay Invoice') }}

- {% if gateway.provider == 'stripe' %}

- {{ _('You will be redirected to a secure payment page to complete your payment.') }} + {{ _('You will be redirected to a secure %(provider)s payment page to complete your payment.', provider=gateway.provider|title) }}

@@ -39,13 +38,5 @@

{{ _('Pay Invoice') }}

- {% else %} -
-

- - {{ _('Payment gateway not yet supported. Please contact support.') }} -

-
- {% endif %}
{% endblock %} diff --git a/app/templates/payments/view.html b/app/templates/payments/view.html index 6b240407d..da43de982 100644 --- a/app/templates/payments/view.html +++ b/app/templates/payments/view.html @@ -221,6 +221,16 @@

Actions< Edit Payment + {% if payment.status == 'completed' %} +
+ + + +
+ {% endif %} +