diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 59fd02ce..9d988394 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -5,7 +5,7 @@ name: CI # Strategy: # - Path filtering skips irrelevant jobs (docs-only PRs finish in ~1 min) # - Lint, tests, frontend, docker, desktop/mobile run in parallel (no smoke gate) -# - Tests run once, sharded 4 ways against Postgres; coverage is combined +# - Tests run once, sharded 8 ways (duration-balanced) against Postgres; coverage is combined # - Docker image is built once (GHA cache) and reused for health check + e2e # - Migrations validation is a reusable workflow, only when models/migrations change # - Dependency CVE scans block only when requirements change (plus nightly workflow) @@ -248,18 +248,18 @@ jobs: if-no-files-found: warn # -------------------------------------------------------------------------- - # Tests (sharded once against Postgres) + # Tests (sharded once against Postgres; duration-balanced across 8 jobs) # -------------------------------------------------------------------------- tests: - name: Tests (${{ matrix.shard }}/4) + name: Tests (${{ matrix.shard }}/8) runs-on: ubuntu-latest needs: changes if: needs.changes.outputs.python == 'true' - timeout-minutes: 25 + timeout-minutes: 30 strategy: fail-fast: false matrix: - shard: [1, 2, 3, 4] + shard: [1, 2, 3, 4, 5, 6, 7, 8] services: postgres: image: postgres:16-alpine @@ -277,6 +277,21 @@ jobs: steps: - uses: actions/checkout@v7 - uses: ./.github/actions/setup-python-env + - name: Restore test durations cache + uses: actions/cache/restore@v6 + with: + path: .test_durations + key: test-durations-${{ runner.os }}-${{ github.sha }} + restore-keys: | + test-durations-${{ runner.os }}- + - name: Ensure durations file exists + run: | + if [ ! -f .test_durations ]; then + echo '{}' > .test_durations + echo "No cached durations; pytest-split will fall back to even splits." + else + echo "Restored .test_durations ($(wc -c < .test_durations) bytes)" + fi - name: Run test shard env: DATABASE_URL: postgresql+psycopg2://test_user:test_password@localhost:5432/test_db @@ -286,10 +301,12 @@ jobs: PYTHONPATH: ${{ github.workspace }} INSTALLATION_CONFIG_DIR: ${{ github.workspace }}/.test_installation_config run: | - pytest -v -n auto --durations=20 \ - --splits 4 --group ${{ matrix.shard }} \ + # Clear pytest.ini addopts (-v) so CI stays quiet; keep coverage data for the gate. + pytest -o addopts= -q -n auto --durations=20 \ + --splits 8 --group ${{ matrix.shard }} \ + --splitting-algorithm=least_duration \ + --store-durations --durations-path=.test_durations \ --cov=app --cov-report=xml:coverage-${{ matrix.shard }}.xml \ - --cov-report=term-missing \ --junitxml=junit-${{ matrix.shard }}.xml \ --maxfail=10 - name: Prepare coverage data artifact @@ -310,6 +327,77 @@ jobs: coverage-${{ matrix.shard }}.dat junit-${{ matrix.shard }}.xml if-no-files-found: warn + - name: Upload shard durations + if: always() + uses: actions/upload-artifact@v7 + with: + name: test-durations-shard-${{ matrix.shard }} + path: .test_durations + if-no-files-found: warn + + # Merge per-shard duration files and cache for the next CI run's least_duration split. + test-durations: + name: Cache test durations + runs-on: ubuntu-latest + needs: [changes, tests] + if: always() && needs.changes.outputs.python == 'true' + timeout-minutes: 5 + steps: + - name: Download shard durations + uses: actions/download-artifact@v8 + with: + pattern: test-durations-shard-* + merge-multiple: false + path: duration-shards + continue-on-error: true + - name: Merge durations and save cache + run: | + set -euo pipefail + python3 <<'PY' + import json + import pathlib + + # Cap absurd timings (e.g. freezegun poisoning absolute timestamps). + MAX_DURATION_S = 300.0 + root = pathlib.Path("duration-shards") + merged: dict[str, float] = {} + if root.exists(): + for path in sorted(root.rglob(".test_durations")): + try: + data = json.loads(path.read_text()) + except Exception as exc: + print(f"skip {path}: {exc}") + continue + if not isinstance(data, dict): + continue + for nodeid, duration in data.items(): + try: + value = float(duration) + except (TypeError, ValueError): + continue + if value < 0 or value > MAX_DURATION_S: + continue + # Keep the max observed legitimate duration per node. + prev = merged.get(nodeid) + if prev is None or value > prev: + merged[nodeid] = value + out = pathlib.Path(".test_durations") + out.write_text(json.dumps(merged, sort_keys=True, indent=4) + "\n") + print(f"Merged {len(merged)} test durations into {out}") + PY + - name: Save test durations cache + if: hashFiles('.test_durations') != '' + uses: actions/cache/save@v6 + with: + path: .test_durations + key: test-durations-${{ runner.os }}-${{ github.run_id }} + - name: Upload combined durations artifact + if: hashFiles('.test_durations') != '' + uses: actions/upload-artifact@v7 + with: + name: test-durations + path: .test_durations + if-no-files-found: warn coverage: name: Coverage gate diff --git a/app/blueprint_registry.py b/app/blueprint_registry.py index a749f618..07ce932d 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/constants.py b/app/constants.py index bffa1b09..233b5fda 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/integrations/peppol.py b/app/integrations/peppol.py index c831e312..152cc294 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/__init__.py b/app/models/__init__.py index 2600540b..0a14ed38 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 @@ -89,6 +89,7 @@ from .recurring_invoice import RecurringInvoice from .recurring_project_cost import RecurringProjectCost from .recurring_task import RecurringTask +from .reminder_policy import ReminderPolicy, ReminderPolicyLevel from .reporting import ReportEmailSchedule, SavedReportView from .salesman_email_mapping import SalesmanEmailMapping from .saved_filter import SavedFilter @@ -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/client.py b/app/models/client.py index eef6cbaa..d7a6a8b0 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/invoice.py b/app/models/invoice.py index fd0f4bc8..c37dd65d 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, server_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, server_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/models/payments.py b/app/models/payments.py index 3ec78127..a52cc238 100644 --- a/app/models/payments.py +++ b/app/models/payments.py @@ -1,3 +1,4 @@ +from datetime import date as _date from datetime import datetime from decimal import Decimal @@ -71,15 +72,174 @@ 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=True, default=0, server_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/models/reminder_policy.py b/app/models/reminder_policy.py new file mode 100644 index 00000000..73364605 --- /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/payments/base.py b/app/payments/base.py index 216afd74..7d23d365 100644 --- a/app/payments/base.py +++ b/app/payments/base.py @@ -51,3 +51,19 @@ def create_checkout_session( @abstractmethod def verify_webhook(self, payload: bytes, headers: Dict[str, str]) -> WebhookResult: raise NotImplementedError + + def refund( + self, + *, + gateway_transaction_id: str, + amount: Decimal, + currency: str, + reason: Optional[str] = None, + ) -> Dict[str, Any]: + """Issue a refund via the gateway. + + Returns a dict with at least ``success`` (bool) and ``message`` (str). + Default implementation returns a not-supported error so providers that + don't implement refunds fail gracefully. + """ + return {"success": False, "message": f"Refunds are not supported by provider '{self.provider_name}'"} diff --git a/app/payments/mollie_provider.py b/app/payments/mollie_provider.py index 4ac79f62..f6a99f2c 100644 --- a/app/payments/mollie_provider.py +++ b/app/payments/mollie_provider.py @@ -1,12 +1,15 @@ """Mollie payment provider (skeleton + live checkout when API key is configured).""" +import logging from decimal import Decimal -from typing import Dict, Optional +from typing import Any, Dict, Optional import requests from app.payments.base import CheckoutResult, PaymentProvider, WebhookResult +logger = logging.getLogger(__name__) + class MollieProvider(PaymentProvider): provider_name = "mollie" @@ -109,3 +112,39 @@ def verify_webhook(self, payload: bytes, headers: Dict[str, str]) -> WebhookResu currency=(amount_obj.get("currency") or "EUR").upper(), raw=data, ) + + def refund( + self, + *, + gateway_transaction_id: str, + amount: Decimal, + currency: str, + reason: Optional[str] = None, + ) -> Dict[str, Any]: + """Issue a refund for a Mollie payment.""" + headers = self._headers() + if not headers: + return {"success": False, "message": "Mollie API key not configured"} + payload: Dict[str, Any] = { + "amount": {"value": f"{amount:.2f}", "currency": currency.upper()}, + } + if reason: + payload["description"] = reason[:255] + try: + resp = requests.post( + f"{self._api_base()}/payments/{gateway_transaction_id}/refunds", + headers=headers, + json=payload, + timeout=30, + ) + if resp.status_code not in (200, 201): + logger.error("Mollie refund failed (%s): %s", resp.status_code, resp.text) + return { + "success": False, + "message": f"Mollie refund failed ({resp.status_code}): {resp.text[:200]}", + } + data = resp.json() + return {"success": True, "refund_id": data.get("id"), "raw": data} + except requests.RequestException as exc: + logger.error("Mollie refund request error: %s", exc) + return {"success": False, "message": str(exc)} diff --git a/app/payments/paypal_provider.py b/app/payments/paypal_provider.py index 5244fbf5..09b51934 100644 --- a/app/payments/paypal_provider.py +++ b/app/payments/paypal_provider.py @@ -1,10 +1,11 @@ """PayPal Orders v2 payment provider.""" import base64 +import hashlib import json import logging from decimal import Decimal -from typing import Dict, Optional +from typing import Any, Dict, Optional from urllib.parse import urlencode import requests @@ -122,6 +123,54 @@ def verify_webhook(self, payload: bytes, headers: Dict[str, str]) -> WebhookResu except (json.JSONDecodeError, UnicodeDecodeError): return WebhookResult(valid=False, message="Invalid PayPal webhook payload") + # --- PayPal webhook signature verification --- + webhook_id = self.config.get("webhook_id") + client_id = self.config.get("client_id") + client_secret = self.config.get("client_secret") + if not (webhook_id and client_id and client_secret): + # Credentials not configured — accept but log a warning so operators know + logger.warning( + "PayPal webhook_id/credentials not configured; accepting webhook without signature verification" + ) + else: + token = self._get_access_token() + if not token: + return WebhookResult(valid=False, message="PayPal credentials invalid; cannot verify webhook") + + # Build the verify-webhook-signature request + # PayPal requires specific header names (case-insensitive lookup): + def _h(name: str) -> str: + return headers.get(name) or headers.get(name.lower()) or "" + + verify_payload = { + "auth_algo": _h("PAYPAL-AUTH-ALGO"), + "cert_url": _h("PAYPAL-CERT-URL"), + "transmission_id": _h("PAYPAL-TRANSMISSION-ID"), + "transmission_sig": _h("PAYPAL-TRANSMISSION-SIG"), + "transmission_time": _h("PAYPAL-TRANSMISSION-TIME"), + "webhook_id": webhook_id, + "webhook_event": event, + } + try: + resp = requests.post( + f"{self._api_base()}/v1/notifications/verify-webhook-signature", + headers={ + "Authorization": f"Bearer {token}", + "Content-Type": "application/json", + }, + json=verify_payload, + timeout=30, + ) + if not resp.ok: + logger.error("PayPal webhook verify call failed: %s", resp.text) + return WebhookResult(valid=False, message=f"PayPal verify call failed ({resp.status_code})") + verification_status = resp.json().get("verification_status", "FAILURE") + if verification_status != "SUCCESS": + return WebhookResult(valid=False, message=f"PayPal signature invalid: {verification_status}") + except requests.RequestException as exc: + logger.error("PayPal webhook verify request error: %s", exc) + return WebhookResult(valid=False, message=f"PayPal verify request error: {exc}") + event_type = event.get("event_type") resource = event.get("resource") or {} @@ -159,3 +208,39 @@ def verify_webhook(self, payload: bytes, headers: Dict[str, str]) -> WebhookResu currency=currency, raw=event, ) + + def refund( + self, + *, + gateway_transaction_id: str, + amount: Decimal, + currency: str, + reason: Optional[str] = None, + ) -> Dict[str, Any]: + """Refund a PayPal capture via the Captures/Refund API.""" + token = self._get_access_token() + if not token: + return {"success": False, "message": "PayPal credentials not configured"} + payload: Dict[str, Any] = { + "amount": {"value": f"{amount:.2f}", "currency_code": currency.upper()}, + } + if reason: + payload["note_to_payer"] = reason[:255] + try: + resp = requests.post( + f"{self._api_base()}/v2/payments/captures/{gateway_transaction_id}/refund", + headers={ + "Authorization": f"Bearer {token}", + "Content-Type": "application/json", + }, + json=payload, + timeout=30, + ) + if not resp.ok: + logger.error("PayPal refund failed: %s", resp.text) + return {"success": False, "message": f"PayPal refund failed ({resp.status_code}): {resp.text[:200]}"} + data = resp.json() + return {"success": True, "refund_id": data.get("id"), "raw": data} + except requests.RequestException as exc: + logger.error("PayPal refund request error: %s", exc) + return {"success": False, "message": str(exc)} diff --git a/app/payments/stripe_provider.py b/app/payments/stripe_provider.py index 837f75cf..b8a8ee44 100644 --- a/app/payments/stripe_provider.py +++ b/app/payments/stripe_provider.py @@ -1,10 +1,13 @@ """Stripe payment provider.""" +import logging from decimal import Decimal -from typing import Dict, Optional +from typing import Any, Dict, Optional from app.payments.base import CheckoutResult, PaymentProvider, WebhookResult -from app.utils.stripe_integration import StripeIntegration, from_stripe_amount +from app.utils.stripe_integration import StripeIntegration, from_stripe_amount, to_stripe_amount + +logger = logging.getLogger(__name__) class StripeProvider(PaymentProvider): @@ -80,3 +83,34 @@ def verify_webhook(self, payload: bytes, headers: Dict[str, str]) -> WebhookResu currency=currency, raw=data_obj, ) + + def refund( + self, + *, + gateway_transaction_id: str, + amount: Decimal, + currency: str, + reason: Optional[str] = None, + ) -> Dict[str, Any]: + """Refund a Stripe payment intent via the Refunds API.""" + api_key = self.config.get("api_key") + if not api_key: + return {"success": False, "message": "Stripe API key not configured"} + try: + import stripe + + stripe.api_key = api_key + amount_int = to_stripe_amount(amount, currency) + params: Dict[str, Any] = { + "payment_intent": gateway_transaction_id, + "amount": amount_int, + } + if reason: + # Stripe accepts: duplicate, fraudulent, requested_by_customer + params["reason"] = "requested_by_customer" + params["metadata"] = {"reason": reason[:500]} + refund = stripe.Refund.create(**params) + return {"success": True, "refund_id": refund.get("id"), "raw": dict(refund)} + except Exception as exc: + logger.error("Stripe refund failed: %s", exc) + return {"success": False, "message": str(exc)} diff --git a/app/repositories/invoice_repository.py b/app/repositories/invoice_repository.py index f8853b74..75b06198 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.py b/app/routes/api_v1.py index fc09b307..e1e02b12 100644 --- a/app/routes/api_v1.py +++ b/app/routes/api_v1.py @@ -2886,17 +2886,16 @@ def create_credit_note(): amt = Decimal(str(data["amount"])) except Exception: return jsonify({"error": "Invalid amount"}), 400 - # Generate credit number (simple: CN--) - credit_number = f"CN-{inv.id}-{int(datetime.utcnow().timestamp())}" - cn = CreditNote( - invoice_id=inv.id, - credit_number=credit_number, - amount=amt, + from app.services.credit_note_service import CreditNoteService + + cn = CreditNoteService.create_amount_credit( + inv, + g.api_user.id, + amt, reason=data.get("reason"), - created_by=g.api_user.id, + description=data.get("reason") or "Credit", + auto_issue=False, ) - db.session.add(cn) - db.session.commit() return ( jsonify( { @@ -2951,6 +2950,61 @@ def delete_credit_note(cn_id): return jsonify({"message": "Credit note deleted successfully"}) +@api_v1_bp.route("/credit-notes//pdf", methods=["GET"]) +@require_api_token("read:invoices") +def download_credit_note_pdf_api(cn_id): + """Download credit note as PDF.""" + from app.utils.credit_note_pdf import generate_credit_note_pdf + + cn = CreditNote.query.get_or_404(cn_id) + try: + pdf_bytes = generate_credit_note_pdf(cn) + except Exception as e: + current_app.logger.error("Credit note PDF failed for cn=%s: %s", cn_id, e, exc_info=True) + return error_response("Failed to generate credit note PDF", status_code=500) + filename = f"credit-note-{cn.credit_number}.pdf" + return send_file( + io.BytesIO(pdf_bytes), + mimetype="application/pdf", + as_attachment=True, + download_name=filename, + ) + + +@api_v1_bp.route("/credit-notes//ubl", methods=["GET"]) +@require_api_token("read:invoices") +def download_credit_note_ubl_api(cn_id): + """Download credit note as Peppol UBL CreditNote XML.""" + from app.integrations.peppol import PeppolParty, build_peppol_ubl_credit_note_xml + from app.models import Settings + + cn = CreditNote.query.get_or_404(cn_id) + invoice = Invoice.query.get_or_404(cn.invoice_id) + try: + 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 e: + current_app.logger.error("Credit note UBL failed for cn=%s: %s", cn_id, e, exc_info=True) + return error_response("Failed to generate credit note UBL", status_code=500) + filename = f"credit-note-{cn.credit_number}-ubl.xml" + return Response( + xml_str, + mimetype="application/xml", + headers={"Content-Disposition": f'attachment; filename="{filename}"'}, + ) + + # ==================== Reports ==================== diff --git a/app/routes/api_v1_invoices.py b/app/routes/api_v1_invoices.py index 3552a363..946f6c24 100644 --- a/app/routes/api_v1_invoices.py +++ b/app/routes/api_v1_invoices.py @@ -5,7 +5,7 @@ import io -from flask import Blueprint, current_app, g, jsonify, request, send_file +from flask import Blueprint, Response, current_app, g, jsonify, request, send_file from app import db from app.routes.api_v1_common import _parse_date @@ -21,6 +21,19 @@ def _invoice_service(): return InvoiceService() +def _load_invoice_for_api(invoice_id): + """Load invoice with access check; return (invoice, error_response) tuple.""" + from app.models import Invoice + + invoice = Invoice.query.get(invoice_id) + if not invoice: + return None, error_response("Invoice not found", status_code=404) + svc = _invoice_service() + if not svc.user_can_access_invoice(invoice, g.api_user.id, g.api_user.is_admin): + return None, error_response("Permission denied", status_code=403) + return invoice, None + + @api_v1_invoices_bp.route("/invoices", methods=["GET"]) @require_api_token("read:invoices") def list_invoices(): @@ -163,6 +176,14 @@ def update_invoice(invoice_id): direct_dirty = True if direct_dirty: db.session.commit() + try: + from app.constants import WebhookEvent + from app.utils.invoice_events import emit_invoice_event + + # Service already emitted after its commit; re-emit once final fields are saved. + emit_invoice_event(WebhookEvent.INVOICE_UPDATED.value, result["invoice"]) + except Exception: + pass try: from app.utils.integration_sync_hooks import trigger_invoice_sync @@ -480,3 +501,134 @@ def send_invoice_sdi_api(invoice_id): return jsonify(payload) payload["message"] = "Failed to send via SDI" return jsonify(payload), 400 + + +@api_v1_invoices_bp.route("/invoices//send-email", methods=["POST"]) +@require_api_token("write:invoices") +def send_invoice_email_api(invoice_id): + """Send invoice via email. Body: optional recipient_email/recipient, subject, custom_message.""" + invoice, err = _load_invoice_for_api(invoice_id) + if err: + return err + + data = request.get_json(silent=True) or {} + recipient_email = (data.get("recipient_email") or data.get("recipient") or invoice.client_email or "").strip() + if not recipient_email: + return validation_error_response( + errors={"recipient_email": ["Recipient email is required"]}, + message="Recipient email address is required", + ) + + subject = (data.get("subject") or "").strip() or None + custom_message = (data.get("custom_message") or data.get("message") or "").strip() or None + email_template_id = data.get("email_template_id") + + try: + from app.utils.email import send_invoice_email + + success, invoice_email, message = send_invoice_email( + invoice=invoice, + recipient_email=recipient_email, + sender_user=g.api_user, + custom_message=custom_message, + email_template_id=email_template_id, + subject=subject, + ) + except Exception as e: + current_app.logger.error("API invoice email failed: %s: %s", type(e).__name__, e) + return error_response("Failed to send invoice email", status_code=500) + + if not success: + return error_response(message or "Failed to send invoice email", status_code=500) + + return jsonify( + { + "success": True, + "message": "Invoice email sent successfully", + "invoice_email_id": invoice_email.id if invoice_email else None, + } + ) + + +@api_v1_invoices_bp.route("/invoices//ubl", methods=["GET"]) +@require_api_token("read:invoices") +def export_invoice_ubl_api(invoice_id): + """Download invoice as PEPPOL UBL 2.1 XML.""" + invoice, err = _load_invoice_for_api(invoice_id) + if err: + return err + try: + from app.integrations.peppol import build_peppol_ubl_invoice_xml + from app.services.peppol_service import PeppolService + + svc = PeppolService() + sender = svc._get_sender_party() + recipient_party, _ign, _ign2 = svc._get_recipient_party(invoice) + ubl_xml, _ign3 = build_peppol_ubl_invoice_xml(invoice=invoice, supplier=sender, customer=recipient_party) + fn = f"{invoice.invoice_number}.xml" + return Response( + ubl_xml, + mimetype="application/xml", + headers={"Content-Disposition": f"attachment; filename={fn}"}, + ) + except ValueError as e: + return error_response(str(e) or "Cannot generate UBL", status_code=400) + except Exception as e: + current_app.logger.error("API UBL export failed for invoice %s: %s", invoice_id, e, exc_info=True) + return error_response("UBL export failed", status_code=500) + + +@api_v1_invoices_bp.route("/invoices//xrechnung", methods=["GET"]) +@require_api_token("read:invoices") +def export_invoice_xrechnung_api(invoice_id): + """Download invoice as XRechnung 3.0 UBL XML.""" + invoice, err = _load_invoice_for_api(invoice_id) + if err: + return err + from app.models import Settings + from app.utils.xrechnung import build_xrechnung_ubl_invoice_xml, validate_xrechnung_ready + + settings = Settings.get_settings() + client_obj = getattr(invoice, "client", None) + errors = validate_xrechnung_ready(invoice, settings, client_obj) + if errors: + return jsonify({"error": "xrechnung_not_ready", "messages": errors}), 400 + try: + xml, _sha = build_xrechnung_ubl_invoice_xml(invoice, settings, client_obj) + fn = f"{invoice.invoice_number}-xrechnung.xml" + return Response( + xml, + mimetype="application/xml", + headers={"Content-Disposition": f"attachment; filename={fn}"}, + ) + except Exception as e: + current_app.logger.error("API XRechnung export failed for invoice %s: %s", invoice_id, e, exc_info=True) + return error_response("XRechnung export failed", status_code=500) + + +@api_v1_invoices_bp.route("/invoices//fatturapa", methods=["GET"]) +@require_api_token("read:invoices") +def export_invoice_fatturapa_api(invoice_id): + """Download invoice as FatturaPA 1.2 XML.""" + invoice, err = _load_invoice_for_api(invoice_id) + if err: + return err + from app.models import Settings + from app.utils.fatturapa import build_fatturapa_xml, progressivo_from_id, validate_fatturapa_ready + + settings = Settings.get_settings() + client_obj = getattr(invoice, "client", None) + errors = validate_fatturapa_ready(invoice, settings, client_obj) + if errors: + return jsonify({"error": "fatturapa_not_ready", "messages": errors}), 400 + try: + progressivo = progressivo_from_id(invoice.id or 1) + xml, filename, _sha = build_fatturapa_xml(invoice, settings, client_obj, progressivo) + return Response( + xml, + mimetype="application/xml", + headers={"Content-Disposition": f"attachment; filename={filename}"}, + ) + except Exception as e: + current_app.logger.error("API FatturaPA export failed for invoice %s: %s", invoice_id, e, exc_info=True) + return error_response("FatturaPA export failed", status_code=500) diff --git a/app/routes/api_v1_payments.py b/app/routes/api_v1_payments.py index fede6bcc..54e7f242 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/client_portal.py b/app/routes/client_portal.py index bc6182b9..3780d685 100644 --- a/app/routes/client_portal.py +++ b/app/routes/client_portal.py @@ -1355,6 +1355,47 @@ def payment_success(): return redirect(url_for("client_portal.view_invoice", invoice_id=invoice_id)) +@client_portal_bp.route("/client-portal/invoices//pdf") +def invoice_pdf(invoice_id): + """Download PDF for an invoice via the client portal.""" + result = check_client_portal_access() + if not isinstance(result, Client): + return result + client = result + + invoice = Invoice.query.get_or_404(invoice_id) + if invoice.client_id != client.id: + flash(_("Invoice not found."), "error") + abort(404) + + import io + + from flask import current_app, send_file + + from app.models import Settings + + try: + from app.utils.pdf_generator import InvoicePDFGenerator + + settings = Settings.get_settings() + pdf_generator = InvoicePDFGenerator(invoice, settings=settings, page_size="A4") + pdf_bytes = pdf_generator.generate_pdf() + except Exception: + try: + from app.utils.pdf_generator_fallback import InvoicePDFGeneratorFallback + + settings = Settings.get_settings() + pdf_generator = InvoicePDFGeneratorFallback(invoice, settings=settings) + pdf_bytes = pdf_generator.generate_pdf() + except Exception as exc: + current_app.logger.error("Client portal PDF generation failed for invoice %s: %s", invoice_id, exc) + flash(_("PDF generation failed. Please try again later."), "error") + return redirect(url_for("client_portal.view_invoice", invoice_id=invoice_id)) + + filename = f"{invoice.invoice_number or invoice_id}.pdf" + return send_file(io.BytesIO(pdf_bytes), mimetype="application/pdf", as_attachment=True, download_name=filename) + + # ==================== Project Comments ==================== diff --git a/app/routes/clients.py b/app/routes/clients.py index d7a583c5..b1f416d7 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/credit_notes.py b/app/routes/credit_notes.py new file mode 100644 index 00000000..81f44883 --- /dev/null +++ b/app/routes/credit_notes.py @@ -0,0 +1,256 @@ +"""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 PeppolParty, build_peppol_ubl_credit_note_xml + 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.models import Client, Settings + from app.utils.fatturapa import build_fatturapa_credit_note_xml + + 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/routes/invoices.py b/app/routes/invoices.py index 9902e2b4..4843225f 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/routes/main.py b/app/routes/main.py index 3b4b05f8..b1b1d1b9 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/routes/payment_gateways.py b/app/routes/payment_gateways.py index b1cb5962..5111ac49 100644 --- a/app/routes/payment_gateways.py +++ b/app/routes/payment_gateways.py @@ -51,8 +51,13 @@ def create_gateway(): config = { "client_id": request.form.get("client_id", "").strip(), "client_secret": request.form.get("client_secret", "").strip(), + "webhook_id": request.form.get("webhook_id", "").strip(), "sandbox": is_test_mode, } + elif provider == "mollie": + config = { + "api_key": request.form.get("api_key", "").strip(), + } service = PaymentGatewayService() result = service.create_gateway(name=name, provider=provider, config=config, is_test_mode=is_test_mode) @@ -119,6 +124,20 @@ def paypal_webhook(): return jsonify({"status": "success"}), status +@payment_gateways_bp.route("/payment-gateways/mollie/webhook", methods=["POST"]) +def mollie_webhook(): + """Handle Mollie webhook""" + gateway = PaymentGatewayService().get_active_gateway(provider="mollie") + if not gateway: + return jsonify({"error": "Gateway not found"}), 404 + + result = CheckoutService().complete_webhook(gateway, request.data, dict(request.headers)) + status = result.get("status", 500 if not result.get("success") else 200) + if not result.get("success"): + return jsonify({"error": result.get("message")}), status + return jsonify({"status": "success"}), status + + @payment_gateways_bp.route("/payment-gateways/payment-success/") @login_required @module_enabled("payment_gateways") diff --git a/app/routes/payments.py b/app/routes/payments.py index 694967d5..061f8576 100644 --- a/app/routes/payments.py +++ b/app/routes/payments.py @@ -227,13 +227,23 @@ def create_payment(): db.session.add(payment) + # Warn (but allow) when payment exceeds outstanding balance + if status == "completed" and amount > invoice.outstanding_amount: + flash( + _( + "Payment exceeds the outstanding amount of %(outstanding)s. Invoice will be marked overpaid.", + outstanding=invoice.outstanding_amount, + ), + "warning", + ) + # Update invoice payment tracking if payment is completed if status == "completed": invoice.amount_paid = (invoice.amount_paid or Decimal("0")) + amount invoice.update_payment_status() - # Update invoice status if fully paid - if invoice.payment_status == "fully_paid": + # Update invoice status if fully paid or overpaid + if invoice.payment_status in ("fully_paid", "overpaid"): invoice.status = "paid" # Reduce stock when invoice is fully paid (if configured) @@ -739,6 +749,66 @@ def export_payments_excel(): ) +@payments_bp.route("/payments//refund", methods=["POST"]) +@login_required +@module_enabled("payments") +def refund_payment(payment_id): + """Refund a payment (gateway + local ledger)""" + payment = Payment.query.get_or_404(payment_id) + + if not current_user.is_admin and payment.invoice.created_by != current_user.id: + flash(_("You do not have permission to refund this payment"), "error") + return redirect(url_for("payments.list_payments")) + + if payment.status == "refunded": + flash(_("This payment has already been refunded"), "warning") + return redirect(url_for("payments.view_payment", payment_id=payment_id)) + + if payment.status != "completed": + flash(_("Only completed payments can be refunded"), "error") + return redirect(url_for("payments.view_payment", payment_id=payment_id)) + + reason = request.form.get("reason", "").strip() or None + + # Try gateway refund if we have a transaction id + if payment.gateway_transaction_id: + from app.payments.registry import get_provider + from app.services.payment_gateway_service import PaymentGatewayService + + gateway_service = PaymentGatewayService() + gateway = gateway_service.get_active_gateway(provider=payment.method) + if gateway: + try: + provider_impl = get_provider(gateway) + result = provider_impl.refund( + gateway_transaction_id=payment.gateway_transaction_id, + amount=payment.amount, + currency=payment.currency or "EUR", + reason=reason, + ) + if not result.get("success"): + flash( + _("Gateway refund failed: %(msg)s", msg=result.get("message", "unknown error")), + "error", + ) + return redirect(url_for("payments.view_payment", payment_id=payment_id)) + except Exception as exc: + current_app.logger.error("Gateway refund error for payment %s: %s", payment_id, exc, exc_info=True) + flash(_("Gateway refund error: %(msg)s", msg=str(exc)), "error") + return redirect(url_for("payments.view_payment", payment_id=payment_id)) + + # Mark payment as refunded via PaymentService to keep ledger correct + from app.services.payment_service import PaymentService + + update_result = PaymentService().update_payment(payment_id, current_user.id, status="refunded") + if not update_result.get("success"): + flash(_("Could not update payment status: %(msg)s", msg=update_result.get("message", "")), "error") + return redirect(url_for("payments.view_payment", payment_id=payment_id)) + + flash(_("Payment refunded successfully"), "success") + return redirect(url_for("payments.view_payment", payment_id=payment_id)) + + def get_user_invoices(): """Get invoices accessible by current user""" if current_user.is_admin: diff --git a/app/routes/reminder_policies.py b/app/routes/reminder_policies.py new file mode 100644 index 00000000..015cc0cd --- /dev/null +++ b/app/routes/reminder_policies.py @@ -0,0 +1,144 @@ +"""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/schemas/invoice_schema.py b/app/schemas/invoice_schema.py index 0be51ee6..f5daebec 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/checkout_service.py b/app/services/checkout_service.py index 357ddaf3..11a3c145 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/credit_note_service.py b/app/services/credit_note_service.py new file mode 100644 index 00000000..186108e9 --- /dev/null +++ b/app/services/credit_note_service.py @@ -0,0 +1,224 @@ +"""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.invoice import InvoiceItem + from app.models.payments import CreditNoteItem + + 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/services/invoice_reminder_service.py b/app/services/invoice_reminder_service.py new file mode 100644 index 00000000..34ee63db --- /dev/null +++ b/app/services/invoice_reminder_service.py @@ -0,0 +1,271 @@ +"""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 ROUND_HALF_UP, Decimal +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/services/invoice_service.py b/app/services/invoice_service.py index c48e9bdc..d15bffc9 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/services/payment_gateway_service.py b/app/services/payment_gateway_service.py index b55fb317..44040b12 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 f0e7da08..9320d2be 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/client_portal/invoice_detail.html b/app/templates/client_portal/invoice_detail.html index a46e1553..806f0836 100644 --- a/app/templates/client_portal/invoice_detail.html +++ b/app/templates/client_portal/invoice_detail.html @@ -102,21 +102,26 @@

{{ _('Invoice Items') }}

- {% 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/clients/edit.html b/app/templates/clients/edit.html index aef20592..f646073f 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/credit_notes/list.html b/app/templates/credit_notes/list.html new file mode 100644 index 00000000..acd21285 --- /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 00000000..c75c2313 --- /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/email/invoice_reminder.html b/app/templates/email/invoice_reminder.html new file mode 100644 index 00000000..426f00c8 --- /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/email/payment_receipt.html b/app/templates/email/payment_receipt.html new file mode 100644 index 00000000..7666f48e --- /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/invoices/_invoices_list.html b/app/templates/invoices/_invoices_list.html index 5dd5eef8..a365ab7f 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/app/templates/invoices/create.html b/app/templates/invoices/create.html index 186f32c6..cb14cbad 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 4fbdf568..d08db374 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 b7fbd44a..79be9c39 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/templates/invoices/view.html b/app/templates/invoices/view.html index 1e32743f..493a855c 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 %} + @@ -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 a54ecff1..604a0f4f 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 6b240407..da43de98 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 %} +
+

+ {% endfor %} +
+ + + +
+ + Cancel +
+ + + + +{% endblock %} diff --git a/app/templates/reminder_policies/list.html b/app/templates/reminder_policies/list.html new file mode 100644 index 00000000..78c0f174 --- /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/cii_invoice.py b/app/utils/cii_invoice.py index 221d3ed7..8eea7836 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,38 @@ 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/credit_note_pdf.py b/app/utils/credit_note_pdf.py new file mode 100644 index 00000000..bc288a95 --- /dev/null +++ b/app/utils/credit_note_pdf.py @@ -0,0 +1,79 @@ +"""Simple ReportLab PDF generator for credit notes.""" + +from __future__ import annotations + +import io +from decimal import Decimal + +from reportlab.lib import colors +from reportlab.lib.pagesizes import A4 +from reportlab.lib.styles import ParagraphStyle, getSampleStyleSheet +from reportlab.lib.units import mm +from reportlab.platypus import Paragraph, SimpleDocTemplate, Spacer, Table, TableStyle + + +def generate_credit_note_pdf(cn) -> bytes: + """Return PDF bytes for a credit note.""" + buffer = io.BytesIO() + doc = SimpleDocTemplate( + buffer, pagesize=A4, leftMargin=20 * mm, rightMargin=20 * mm, topMargin=20 * mm, bottomMargin=20 * mm + ) + styles = getSampleStyleSheet() + title_style = ParagraphStyle("CNTitle", parent=styles["Heading1"], fontSize=18, spaceAfter=12) + normal = styles["Normal"] + + story = [] + story.append(Paragraph("Credit Note", title_style)) + story.append(Paragraph(f"Number: {cn.credit_number}", normal)) + if cn.issue_date: + story.append(Paragraph(f"Issue date: {cn.issue_date.isoformat()}", normal)) + story.append(Paragraph(f"Status: {cn.status}", normal)) + if cn.invoice: + story.append(Paragraph(f"Original invoice: {cn.invoice.invoice_number}", normal)) + story.append(Paragraph(f"Client: {cn.invoice.client_name or ''}", normal)) + if cn.reason: + story.append(Spacer(1, 6)) + story.append(Paragraph(f"Reason: {cn.reason}", normal)) + story.append(Spacer(1, 12)) + + items = cn.items.all() if hasattr(cn.items, "all") else list(cn.items or []) + items = sorted(items, key=lambda x: getattr(x, "position", 0) or 0) + currency = cn.currency_code or (cn.invoice.currency_code if cn.invoice else "EUR") or "EUR" + + if items: + data = [["Description", "Qty", "Unit price", "Total"]] + for item in items: + data.append( + [ + str(item.description or "")[:80], + f"{Decimal(str(item.quantity or 0)):.2f}", + f"{Decimal(str(item.unit_price or 0)):.2f}", + f"{Decimal(str(item.total_amount or 0)):.2f}", + ] + ) + table = Table(data, colWidths=[90 * mm, 25 * mm, 30 * mm, 30 * mm]) + table.setStyle( + TableStyle( + [ + ("BACKGROUND", (0, 0), (-1, 0), colors.HexColor("#e5e7eb")), + ("GRID", (0, 0), (-1, -1), 0.5, colors.grey), + ("FONTNAME", (0, 0), (-1, 0), "Helvetica-Bold"), + ("ALIGN", (1, 1), (-1, -1), "RIGHT"), + ("VALIGN", (0, 0), (-1, -1), "MIDDLE"), + ("TOPPADDING", (0, 0), (-1, -1), 4), + ("BOTTOMPADDING", (0, 0), (-1, -1), 4), + ] + ) + ) + story.append(table) + story.append(Spacer(1, 12)) + + subtotal = Decimal(str(cn.subtotal if cn.subtotal is not None else 0)) + tax = Decimal(str(cn.tax_amount if cn.tax_amount is not None else 0)) + total = Decimal(str(cn.total_amount if cn.total_amount is not None else cn.amount or 0)) + story.append(Paragraph(f"Subtotal: {subtotal:.2f} {currency}", normal)) + story.append(Paragraph(f"Tax: {tax:.2f} {currency}", normal)) + story.append(Paragraph(f"Total credit: {total:.2f} {currency}", normal)) + + doc.build(story) + return buffer.getvalue() diff --git a/app/utils/email.py b/app/utils/email.py index 8cc550fb..766f8f8a 100644 --- a/app/utils/email.py +++ b/app/utils/email.py @@ -919,7 +919,9 @@ def send_invoice_template_test_email(template_id, recipient_email, invoice_id=No return False, "Failed to send test email" -def send_invoice_email(invoice, recipient_email, sender_user=None, custom_message=None, email_template_id=None): +def send_invoice_email( + invoice, recipient_email, sender_user=None, custom_message=None, email_template_id=None, subject=None +): """Send an invoice via email with PDF attachment Args: @@ -928,6 +930,7 @@ def send_invoice_email(invoice, recipient_email, sender_user=None, custom_messag sender_user: User object who is sending (for tracking) custom_message: Optional custom message to include in email email_template_id: Optional email template ID to use + subject: Optional subject override (defaults to built template subject) Returns: tuple: (success: bool, invoice_email: InvoiceEmail or None, message: str) @@ -938,9 +941,10 @@ def send_invoice_email(invoice, recipient_email, sender_user=None, custom_messag current_app.logger.info(f"[INVOICE EMAIL] Sending invoice {invoice.invoice_number} to {recipient_email}") try: - pdf_bytes, html_body, text_body, subject = _build_invoice_email_payload( + pdf_bytes, html_body, text_body, built_subject = _build_invoice_email_payload( invoice, email_template_id=email_template_id, custom_message=custom_message ) + subject = (subject or "").strip() or built_subject except ValueError: return False, None, "Failed to build invoice email" @@ -1020,6 +1024,17 @@ def send_invoice_email(invoice, recipient_email, sender_user=None, custom_messag queue_first_invoice_support_prompt(sender_id, first_send=sent_count == 1) except Exception: pass + try: + from app.constants import WebhookEvent + from app.utils.invoice_events import emit_invoice_event + + emit_invoice_event( + WebhookEvent.INVOICE_SENT.value, + invoice_row or invoice, + recipient_email=recipient_email, + ) + except Exception: + pass return True, invoice_email, f"Invoice email sent successfully to {recipient_email}" diff --git a/app/utils/fatturapa.py b/app/utils/fatturapa.py index 1fe6d017..8efe2114 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,91 @@ 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/invoice_events.py b/app/utils/invoice_events.py new file mode 100644 index 00000000..38798f32 --- /dev/null +++ b/app/utils/invoice_events.py @@ -0,0 +1,78 @@ +"""Helpers for emitting invoice-related webhook/domain events.""" + +from __future__ import annotations + +from typing import Any + +from app.utils.event_bus import emit_event + + +def emit_invoice_event(event_name: str, invoice: Any, **extra: Any) -> None: + """Emit a webhook/domain event for an invoice. + + Builds a standard payload from the invoice model and merges any extra fields. + Failures are swallowed so callers never break business flows on emit errors. + """ + try: + payload = { + "invoice_id": getattr(invoice, "id", None), + "invoice_number": getattr(invoice, "invoice_number", None), + "status": getattr(invoice, "status", None), + "payment_status": getattr(invoice, "payment_status", None), + "client_id": getattr(invoice, "client_id", None), + "project_id": getattr(invoice, "project_id", None), + } + payload.update(extra) + # Drop Nones for cleaner payloads + payload = {k: v for k, v in payload.items() if v is not None} + emit_event(event_name, payload) + except Exception: + try: + from flask import current_app + + current_app.logger.debug("emit_invoice_event failed for %s", event_name, exc_info=True) + except Exception: + pass + + +def emit_credit_note_event(event_name: str, credit_note: Any, **extra: Any) -> None: + """Emit a webhook/domain event for a credit note.""" + try: + payload = { + "credit_note_id": getattr(credit_note, "id", None), + "credit_number": getattr(credit_note, "credit_number", None), + "invoice_id": getattr(credit_note, "invoice_id", None), + "amount": float(credit_note.amount) if getattr(credit_note, "amount", None) is not None else None, + "status": getattr(credit_note, "status", None), + } + payload.update(extra) + payload = {k: v for k, v in payload.items() if v is not None} + emit_event(event_name, payload) + except Exception: + try: + from flask import current_app + + current_app.logger.debug("emit_credit_note_event failed for %s", event_name, exc_info=True) + except Exception: + pass + + +def emit_payment_event(event_name: str, payment: Any, **extra: Any) -> None: + """Emit a webhook/domain event for a payment.""" + try: + payload = { + "payment_id": getattr(payment, "id", None), + "invoice_id": getattr(payment, "invoice_id", None), + "amount": float(payment.amount) if getattr(payment, "amount", None) is not None else None, + "status": getattr(payment, "status", None), + } + payload.update(extra) + payload = {k: v for k, v in payload.items() if v is not None} + emit_event(event_name, payload) + except Exception: + try: + from flask import current_app + + current_app.logger.debug("emit_payment_event failed for %s", event_name, exc_info=True) + except Exception: + pass diff --git a/app/utils/invoice_numbering.py b/app/utils/invoice_numbering.py index 75ae1bb2..d9a9d80d 100644 --- a/app/utils/invoice_numbering.py +++ b/app/utils/invoice_numbering.py @@ -285,6 +285,45 @@ def generate_next_invoice_number_with_retry( raise RuntimeError("Invoice number allocation failed with no attempts") +def allocate_next_credit_note_number(credit_note_model=None, credit_note_query=None, settings=None, now=None): + """Allocate the next unique credit note number. + + Uses the same Settings-based locking mechanism as invoice numbering. + Format: CN-YYYY-##### (prefix configurable via Settings.credit_note_prefix if present, + otherwise defaults to 'CN'). + + Returns a string like ``CN-2026-00001``. + """ + if credit_note_model is None: + from app.models.payments import CreditNote + + credit_note_model = CreditNote + + locked_settings = _lock_settings_for_numbering() + if settings is None: + settings = locked_settings + + now = now or datetime.utcnow() + + # Allow settings override for prefix; fall back to 'CN' + raw_prefix = getattr(settings, "credit_note_prefix", None) or "CN" + prefix = sanitize_invoice_prefix(raw_prefix) + + # Fixed pattern CN-YYYY-##### + pattern = "{PREFIX}-{YYYY}-{SEQ}" + + return generate_next_document_number( + credit_note_model, + credit_note_model.credit_number, + prefix, + pattern, + 1, + document_query=credit_note_query, + now=now, + lock_settings=False, # already locked above + ) + + def generate_next_quote_number(quote_model, quote_query=None, settings=None, now=None): """Generate next quote number for the current pattern and settings. diff --git a/app/utils/scheduled_tasks.py b/app/utils/scheduled_tasks.py index 331ca660..c022526c 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/app/utils/webhook_service.py b/app/utils/webhook_service.py index 19f38a13..5de8a89e 100644 --- a/app/utils/webhook_service.py +++ b/app/utils/webhook_service.py @@ -379,6 +379,12 @@ def get_available_events() -> List[str]: "invoice.sent", "invoice.paid", "invoice.overdue", + # Credit note / payment events + "credit_note.created", + "payment.created", + "payment.processed", + "payment.failed", + "payment.refunded", # Client events "client.created", "client.updated", diff --git a/app/utils/xrechnung.py b/app/utils/xrechnung.py index 6af384eb..3778d232 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/docs/GAP_ROADMAP.md b/docs/GAP_ROADMAP.md index 6bf4edff..ebd6629c 100644 --- a/docs/GAP_ROADMAP.md +++ b/docs/GAP_ROADMAP.md @@ -172,3 +172,5 @@ Canonical workstream for finishing Phase 5 stubs and product polish. Stale plann | Architecture | Done | Payroll export extracted; `make check-route-sizes` CI guard | **Migrations:** `201` time_entries.custom_fields → `202` client.leitweg_id → `203` oauth_access_tokens → `204` user external identity → `205` scim_external_id → `206` bank_transactions. + +**Invoicing gaps closure:** Phases 1–6 shipped (credit notes service/routes, payment gateways, line tax, API send-email + e-invoice XML downloads, webhook events for invoice/credit-note/payment lifecycle). diff --git a/docs/api/API_TOKEN_SCOPES.md b/docs/api/API_TOKEN_SCOPES.md index ac700b14..50e1e7d8 100644 --- a/docs/api/API_TOKEN_SCOPES.md +++ b/docs/api/API_TOKEN_SCOPES.md @@ -245,6 +245,11 @@ curl -X POST https://your-domain.com/api/v1/clients \ **Endpoints** (non-exhaustive; see OpenAPI at `/api/docs` when enabled): - `GET /api/v1/invoices` — List invoices - `GET /api/v1/invoices/{id}` — Get invoice by id +- `GET /api/v1/invoices/{id}/pdf` — PDF download +- `GET /api/v1/invoices/{id}/ubl` — PEPPOL UBL XML +- `GET /api/v1/invoices/{id}/xrechnung` — XRechnung XML +- `GET /api/v1/invoices/{id}/fatturapa` — FatturaPA XML +- `GET /api/v1/credit-notes` / `{id}` / `{id}/pdf` / `{id}/ubl` — Credit notes and downloads **Use Cases**: - Billing dashboards and exports @@ -256,6 +261,9 @@ curl -X POST https://your-domain.com/api/v1/clients \ - `POST /api/v1/invoices` — Create invoice (JSON body) - `PUT` / `PATCH /api/v1/invoices/{id}` — Update invoice - `DELETE /api/v1/invoices/{id}` — Cancel invoice +- `POST /api/v1/invoices/{id}/send-email` — Email invoice (optional `recipient_email`, `subject`) +- `POST /api/v1/invoices/{id}/send-peppol` / `send-sdi` — E-invoicing send +- `POST` / `PATCH` / `DELETE /api/v1/credit-notes` — Credit note mutations - `POST /api/v1/clients/{client_id}/invoice-unbilled` — Create a **draft** invoice from all **unbilled** billable time for that client (line items grouped by project). Requires `write:invoices` when using an API token; the browser UI uses a logged-in session with **Create invoices** permission instead. Successful response JSON: `invoice_id`, `invoice_number`, `total`, `item_count`. Returns **400** when there is no unbilled time, or when any unbilled entry has no `project_id` (assign entries to a project first). **Use Cases**: diff --git a/docs/api/REST_API.md b/docs/api/REST_API.md index ae7504c3..41fcaaf5 100644 --- a/docs/api/REST_API.md +++ b/docs/api/REST_API.md @@ -1175,9 +1175,46 @@ The API implements rate limiting to ensure fair usage: When rate limited, you'll receive a `429 Too Many Requests` response. +## Invoices, credit notes, and payments + +Scopes: `read:invoices` / `write:invoices` (see [API_TOKEN_SCOPES.md](API_TOKEN_SCOPES.md)). + +### Invoices + +| Method | Path | Scope | Notes | +|--------|------|-------|-------| +| `GET` | `/invoices` | `read:invoices` | List (paginated; optional `status`) | +| `GET` | `/invoices/{id}` | `read:invoices` | Detail with line items and payments | +| `POST` | `/invoices` | `write:invoices` | Create draft | +| `PUT`/`PATCH` | `/invoices/{id}` | `write:invoices` | Update draft fields | +| `DELETE` | `/invoices/{id}` | `write:invoices` | Cancel (soft-delete) | +| `GET` | `/invoices/{id}/pdf` | `read:invoices` | PDF download | +| `GET` | `/invoices/{id}/ubl` | `read:invoices` | PEPPOL UBL 2.1 XML (`application/xml`) | +| `GET` | `/invoices/{id}/xrechnung` | `read:invoices` | XRechnung 3.0 XML | +| `GET` | `/invoices/{id}/fatturapa` | `read:invoices` | FatturaPA XML | +| `POST` | `/invoices/{id}/send-email` | `write:invoices` | Body: optional `recipient_email` / `recipient`, `subject`, `custom_message` | +| `POST` | `/invoices/{id}/send-peppol` | `write:invoices` | Send via Peppol access point | +| `POST` | `/invoices/{id}/send-sdi` | `write:invoices` | Send via SDI (FatturaPA) | + +### Credit notes + +| Method | Path | Scope | Notes | +|--------|------|-------|-------| +| `GET` | `/credit-notes` | `read:invoices` | List (optional `invoice_id`) | +| `GET` | `/credit-notes/{id}` | `read:invoices` | Detail | +| `POST` | `/credit-notes` | `write:invoices` | Body: `invoice_id`, `amount`, optional `reason` | +| `PUT`/`PATCH` | `/credit-notes/{id}` | `write:invoices` | Update amount/reason | +| `DELETE` | `/credit-notes/{id}` | `write:invoices` | Delete | +| `GET` | `/credit-notes/{id}/pdf` | `read:invoices` | PDF download | +| `GET` | `/credit-notes/{id}/ubl` | `read:invoices` | UBL CreditNote XML | + +### Payments + +Payment CRUD lives under `/api/v1/payments` (`read:invoices` / `write:invoices`). Recording a completed payment that fully settles an invoice emits `invoice.paid`; refunds emit `payment.refunded`. See [Webhooks](../features/webhooks.md). + ## Webhook Support -Webhooks are supported for real-time notifications. You can receive notifications when time entries are created/updated, projects change status, tasks are completed, and timer events occur. See [Webhooks](../features/webhooks.md) for setup and event types. +Webhooks are supported for real-time notifications. You can receive notifications when time entries are created/updated, projects change status, tasks are completed, timer events occur, and invoice/payment lifecycle events fire (`invoice.sent`, `invoice.paid`, `invoice.overdue`, `credit_note.created`, `payment.refunded`, and related). See [Webhooks](../features/webhooks.md) for setup and event types. ## Support diff --git a/docs/cicd/TESTING_WORKFLOW_STRATEGY.md b/docs/cicd/TESTING_WORKFLOW_STRATEGY.md index 08663a7f..d6266b07 100644 --- a/docs/cicd/TESTING_WORKFLOW_STRATEGY.md +++ b/docs/cicd/TESTING_WORKFLOW_STRATEGY.md @@ -21,7 +21,7 @@ TimeTracker uses a **single CI pipeline** ([`.github/workflows/ci.yml`](../../.g │ ┌────┴──────────────────────────────────────────────────────────┐ │ parallel (skipped when paths don't match) │ - │ lint │ security │ tests(×4 shards) │ frontend │ migrations │ + │ lint │ security │ tests(×8 shards) │ frontend │ migrations │ │ docker+e2e │ desktop │ mobile │ └────┬──────────────────────────────────────────────────────────┘ │ @@ -36,7 +36,7 @@ Docs-only PRs (`**/*.md`, `docs/**`) complete in about a minute: every heavy job ### Tests -- Run **once**, sharded 4 ways with `pytest-split` against Postgres. +- Run **once**, sharded **8** ways with `pytest-split` (`least_duration`) against Postgres. Durations are cached across runs so shards stay balanced. - Coverage shards are averaged; gate is **40%** (ratchet upward over time). - Integration no longer runs as a separate 15-minute job that timed out every release. diff --git a/docs/features/webhooks.md b/docs/features/webhooks.md index 9ab00157..24be1c7d 100644 --- a/docs/features/webhooks.md +++ b/docs/features/webhooks.md @@ -51,6 +51,13 @@ Webhooks allow you to: - `invoice.paid` - An invoice is paid - `invoice.overdue` - An invoice becomes overdue +### Credit Note & Payment Events +- `credit_note.created` - A credit note is created +- `payment.created` - A payment is recorded +- `payment.processed` - A gateway payment completes +- `payment.failed` - A gateway payment fails +- `payment.refunded` - A payment is refunded + ### Client Events - `client.created` - A client is created - `client.updated` - A client is updated 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 00000000..7fe3ce6b --- /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/migrations/versions/211_invoice_reminder_policies.py b/migrations/versions/211_invoice_reminder_policies.py new file mode 100644 index 00000000..b0fdb884 --- /dev/null +++ b/migrations/versions/211_invoice_reminder_policies.py @@ -0,0 +1,151 @@ +"""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 _has_index(inspector, table_name: str, index_name: str) -> bool: + try: + return any(idx["name"] == index_name for idx in inspector.get_indexes(table_name)) + except Exception: + return False + + +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 ─────────────────────────────────────────────── + inspector = inspect(bind) + 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"), + ) + op.create_index( + "ix_reminder_policy_levels_policy_id", + "reminder_policy_levels", + ["policy_id"], + unique=False, + ) + else: + if not _has_index(inspector, "reminder_policy_levels", "ix_reminder_policy_levels_policy_id"): + op.create_index( + "ix_reminder_policy_levels_policy_id", + "reminder_policy_levels", + ["policy_id"], + unique=False, + ) + + # SQLite cannot ALTER to add FK constraints; use batch copy-and-move. + inspector = inspect(bind) + if not _has_column(inspector, "clients", "reminder_policy_id"): + with op.batch_alter_table("clients", schema=None) as batch_op: + batch_op.add_column(sa.Column("reminder_policy_id", sa.Integer(), nullable=True)) + batch_op.create_foreign_key( + "clients_reminder_policy_id_fkey", + "reminder_policies", + ["reminder_policy_id"], + ["id"], + ) + + inspector = inspect(bind) + if not _has_column(inspector, "invoices", "reminder_policy_id"): + with op.batch_alter_table("invoices", schema=None) as batch_op: + batch_op.add_column(sa.Column("reminder_policy_id", sa.Integer(), nullable=True)) + batch_op.create_foreign_key( + "invoices_reminder_policy_id_fkey", + "reminder_policies", + ["reminder_policy_id"], + ["id"], + ) + + inspector = inspect(bind) + if not _has_column(inspector, "invoices", "late_fee_amount"): + op.add_column( + "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") + + inspector = inspect(bind) + if _has_column(inspector, "invoices", "reminder_policy_id"): + with op.batch_alter_table("invoices", schema=None) as batch_op: + batch_op.drop_constraint("invoices_reminder_policy_id_fkey", type_="foreignkey") + batch_op.drop_column("reminder_policy_id") + + inspector = inspect(bind) + if _has_column(inspector, "clients", "reminder_policy_id"): + with op.batch_alter_table("clients", schema=None) as batch_op: + batch_op.drop_constraint("clients_reminder_policy_id_fkey", type_="foreignkey") + batch_op.drop_column("reminder_policy_id") + + inspector = inspect(bind) + if _has_table(inspector, "reminder_policy_levels"): + if _has_index(inspector, "reminder_policy_levels", "ix_reminder_policy_levels_policy_id"): + op.drop_index("ix_reminder_policy_levels_policy_id", table_name="reminder_policy_levels") + op.drop_table("reminder_policy_levels") + + inspector = inspect(bind) + if _has_table(inspector, "reminder_policies"): + op.drop_table("reminder_policies") diff --git a/migrations/versions/212_credit_notes_extended.py b/migrations/versions/212_credit_notes_extended.py new file mode 100644 index 00000000..191e9b7a --- /dev/null +++ b/migrations/versions/212_credit_notes_extended.py @@ -0,0 +1,86 @@ +"""Extend credit_notes and add credit_note_items. + +Revision ID: 212_credit_notes_extended +Revises: 211_invoice_reminder_policies +""" + +import sqlalchemy as sa +from alembic import op +from sqlalchemy import inspect + +revision = "212_credit_notes_extended" +down_revision = "211_invoice_reminder_policies" +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) + + _add_column_if_missing(inspector, "credit_notes", sa.Column("status", sa.String(length=20), nullable=False, server_default="draft")) + _add_column_if_missing(inspector, "credit_notes", sa.Column("issue_date", sa.Date(), nullable=True)) + _add_column_if_missing(inspector, "credit_notes", sa.Column("currency_code", sa.String(length=3), nullable=True)) + _add_column_if_missing(inspector, "credit_notes", sa.Column("subtotal", sa.Numeric(10, 2), nullable=True)) + _add_column_if_missing(inspector, "credit_notes", sa.Column("tax_rate", sa.Numeric(5, 2), nullable=True)) + _add_column_if_missing(inspector, "credit_notes", sa.Column("tax_amount", sa.Numeric(10, 2), nullable=True)) + _add_column_if_missing(inspector, "credit_notes", sa.Column("total_amount", sa.Numeric(10, 2), nullable=True)) + _add_column_if_missing(inspector, "credit_notes", sa.Column("vat_category", sa.String(length=5), nullable=True)) + _add_column_if_missing(inspector, "credit_notes", sa.Column("notes", sa.Text(), nullable=True)) + + if not _has_table(inspector, "credit_note_items"): + op.create_table( + "credit_note_items", + sa.Column("id", sa.Integer(), primary_key=True), + sa.Column("credit_note_id", sa.Integer(), sa.ForeignKey("credit_notes.id"), nullable=False, index=True), + sa.Column("description", sa.String(length=500), nullable=False), + sa.Column("quantity", sa.Numeric(10, 2), nullable=False, server_default="1"), + sa.Column("unit_price", sa.Numeric(10, 2), nullable=False), + sa.Column("total_amount", sa.Numeric(10, 2), nullable=False), + sa.Column("tax_rate", sa.Numeric(5, 2), nullable=True), + sa.Column("vat_category", sa.String(length=5), nullable=True), + sa.Column("discount_percent", sa.Numeric(5, 2), nullable=True), + sa.Column("discount_amount", sa.Numeric(10, 2), nullable=True), + sa.Column("position", sa.Integer(), nullable=True, server_default="0"), + sa.Column("invoice_item_id", sa.Integer(), sa.ForeignKey("invoice_items.id"), nullable=True), + sa.Column("created_at", sa.DateTime(), nullable=True), + ) + + +def downgrade(): + bind = op.get_bind() + inspector = inspect(bind) + if _has_table(inspector, "credit_note_items"): + op.drop_table("credit_note_items") + for col in ( + "notes", + "vat_category", + "total_amount", + "tax_amount", + "tax_rate", + "subtotal", + "currency_code", + "issue_date", + "status", + ): + if _has_column(inspector, "credit_notes", col): + op.drop_column("credit_notes", col) diff --git a/tests/test_api_credit_notes_v1.py b/tests/test_api_credit_notes_v1.py index e9304184..32c05112 100644 --- a/tests/test_api_credit_notes_v1.py +++ b/tests/test_api_credit_notes_v1.py @@ -101,3 +101,36 @@ def test_credit_notes_crud(client, api_token, setup_invoice): # delete r = client.delete(f"/api/v1/credit-notes/{cn_id}", headers=_auth(api_token)) assert r.status_code == 200 + + +def test_credit_note_pdf_api(client, api_token, setup_invoice): + from unittest.mock import patch + + payload = {"invoice_id": setup_invoice.id, "amount": 5.0, "reason": "PDF test"} + r = client.post("/api/v1/credit-notes", headers=_auth(api_token), json=payload) + assert r.status_code == 201 + cn_id = r.get_json()["credit_note"]["id"] + + with patch("app.utils.credit_note_pdf.generate_credit_note_pdf", return_value=b"%PDF-1.4"): + r = client.get(f"/api/v1/credit-notes/{cn_id}/pdf", headers=_auth(api_token)) + assert r.status_code == 200 + assert r.content_type.startswith("application/pdf") + assert r.data.startswith(b"%PDF") + + +def test_credit_note_ubl_api(client, api_token, setup_invoice): + from unittest.mock import patch + + payload = {"invoice_id": setup_invoice.id, "amount": 5.0, "reason": "UBL test"} + r = client.post("/api/v1/credit-notes", headers=_auth(api_token), json=payload) + assert r.status_code == 201 + cn_id = r.get_json()["credit_note"]["id"] + + with patch( + "app.integrations.peppol.build_peppol_ubl_credit_note_xml", + return_value=("", "doc-id"), + ): + r = client.get(f"/api/v1/credit-notes/{cn_id}/ubl", headers=_auth(api_token)) + assert r.status_code == 200 + assert "xml" in (r.content_type or "") + assert b"/send-email --- + + +def test_send_invoice_email_api(client, api_token, project, client_model, user): + from unittest.mock import MagicMock, patch + + invoice_id = _create_draft_invoice(client, api_token, project, client_model) + mock_email = MagicMock() + mock_email.id = 42 + with patch( + "app.utils.email.send_invoice_email", + return_value=(True, mock_email, "ok"), + ) as mock_send: + r = client.post( + f"/api/v1/invoices/{invoice_id}/send-email", + headers=_auth_header(api_token), + json={"recipient_email": "billing@example.com", "subject": "Your invoice"}, + ) + assert r.status_code == 200, r.get_json() + body = r.get_json() + assert body["success"] is True + assert body["invoice_email_id"] == 42 + mock_send.assert_called_once() + kwargs = mock_send.call_args.kwargs + assert kwargs["recipient_email"] == "billing@example.com" + assert kwargs["subject"] == "Your invoice" + + +def test_send_invoice_email_requires_recipient(client, api_token, project, client_model, app): + invoice_id = _create_draft_invoice(client, api_token, project, client_model) + with app.app_context(): + inv = Invoice.query.get(invoice_id) + inv.client_email = None + db.session.commit() + r = client.post( + f"/api/v1/invoices/{invoice_id}/send-email", + headers=_auth_header(api_token), + json={}, + ) + assert r.status_code == 400 + + +# --- GET /invoices//ubl|xrechnung|fatturapa --- + + +def test_export_invoice_ubl_api(client, api_token, project, client_model): + from unittest.mock import MagicMock, patch + + invoice_id = _create_draft_invoice(client, api_token, project, client_model) + fake_party = MagicMock() + with ( + patch("app.services.peppol_service.PeppolService") as MockSvc, + patch( + "app.integrations.peppol.build_peppol_ubl_invoice_xml", + return_value=("", "doc-id"), + ), + ): + svc = MockSvc.return_value + svc._get_sender_party.return_value = fake_party + svc._get_recipient_party.return_value = (fake_party, None, None) + r = client.get(f"/api/v1/invoices/{invoice_id}/ubl", headers=_auth_header(api_token)) + assert r.status_code == 200 + assert "xml" in (r.content_type or "") + assert b"", "sha"), + ), + ): + r = client.get(f"/api/v1/invoices/{invoice_id}/xrechnung", headers=_auth_header(api_token)) + assert r.status_code == 200 + assert "xml" in (r.content_type or "") + + +def test_export_invoice_fatturapa_api(client, api_token, project, client_model): + from unittest.mock import patch + + invoice_id = _create_draft_invoice(client, api_token, project, client_model) + with ( + patch("app.utils.fatturapa.validate_fatturapa_ready", return_value=[]), + patch("app.utils.fatturapa.progressivo_from_id", return_value="00001"), + patch( + "app.utils.fatturapa.build_fatturapa_xml", + return_value=("", "IT123.xml", "sha"), + ), + ): + r = client.get(f"/api/v1/invoices/{invoice_id}/fatturapa", headers=_auth_header(api_token)) + assert r.status_code == 200 + assert "xml" in (r.content_type or "") diff --git a/tests/test_credit_notes.py b/tests/test_credit_notes.py new file mode 100644 index 00000000..467219ad --- /dev/null +++ b/tests/test_credit_notes.py @@ -0,0 +1,108 @@ +"""Phase 3 credit note tests.""" + +from datetime import date, timedelta +from decimal import Decimal + +import pytest +from factories import ClientFactory, InvoiceFactory, InvoiceItemFactory + + +@pytest.fixture +def sent_invoice(app, user, project): + from app import db + + client = ClientFactory(name="CN Client") + db.session.commit() + inv = InvoiceFactory( + project_id=project.id, + client_id=client.id, + client_name=client.name, + created_by=user.id, + due_date=date.today() + timedelta(days=14), + tax_rate=Decimal("20.00"), + ) + inv.status = "sent" + inv.tax_rate = Decimal("20.00") + db.session.commit() + InvoiceItemFactory( + invoice_id=inv.id, + description="Consulting", + quantity=Decimal("10.00"), + unit_price=Decimal("100.00"), + ) + db.session.commit() + inv.calculate_totals() + db.session.commit() + return inv + + +def test_full_credit_cancels_invoice_and_covers_outstanding(app, user, sent_invoice): + from app import db + from app.services.credit_note_service import CreditNoteService + + inv = sent_invoice + assert inv.outstanding_amount > 0 + cn = CreditNoteService.create_full_credit(inv, user.id, reason="Full cancel") + db.session.refresh(inv) + db.session.refresh(cn) + assert cn.status == "issued" + assert cn.total_amount == inv.total_amount or cn.amount == inv.total_amount + assert inv.status == "cancelled" + assert inv.outstanding_amount <= Decimal("0.01") + + +def test_amount_credit_reduces_outstanding(app, user, sent_invoice): + from app import db + from app.services.credit_note_service import CreditNoteService + + inv = sent_invoice + before = inv.outstanding_amount + cn = CreditNoteService.create_amount_credit( + inv, user.id, Decimal("50.00"), reason="Partial", description="Partial credit", auto_issue=True + ) + db.session.refresh(inv) + assert cn.status == "issued" + assert inv.outstanding_amount == before - Decimal("50.00") + assert inv.status != "cancelled" + + +def test_credit_note_pdf_endpoint(app, client, user, sent_invoice): + from app.services.credit_note_service import CreditNoteService + + cn = CreditNoteService.create_amount_credit( + sent_invoice, user.id, Decimal("25.00"), reason="PDF test", auto_issue=True + ) + with client.session_transaction() as sess: + sess["_user_id"] = str(user.id) + sess["_fresh"] = True + resp = client.get(f"/credit-notes/{cn.id}/pdf") + assert resp.status_code == 200 + assert resp.mimetype == "application/pdf" + assert resp.data[:4] == b"%PDF" + + +def test_ubl_credit_note_contains_381(app, user, sent_invoice): + from app.integrations.peppol import PeppolParty, build_peppol_ubl_credit_note_xml + from app.services.credit_note_service import CreditNoteService + + cn = CreditNoteService.create_full_credit(sent_invoice, user.id, reason="UBL", auto_issue=True) + supplier = PeppolParty(endpoint_id="123", endpoint_scheme_id="0088", name="Supplier") + customer = PeppolParty(endpoint_id="456", endpoint_scheme_id="0088", name="Customer") + xml, doc_id = build_peppol_ubl_credit_note_xml(cn, sent_invoice, supplier, customer) + assert "381" in xml + assert "CreditNote" in xml + assert sent_invoice.invoice_number in xml + assert doc_id == cn.credit_number + + +def test_fatturapa_credit_note_td04(app, user, sent_invoice): + from app.models import Settings + from app.services.credit_note_service import CreditNoteService + from app.utils.fatturapa import build_fatturapa_credit_note_xml + + cn = CreditNoteService.create_amount_credit(sent_invoice, user.id, Decimal("10.00"), reason="TD04", auto_issue=True) + settings = Settings.get_settings() + xml_bytes, filename = build_fatturapa_credit_note_xml(cn, sent_invoice, settings, client=None) + xml = xml_bytes.decode("utf-8") if isinstance(xml_bytes, (bytes, bytearray)) else xml_bytes + assert "TD04" in xml + assert "DatiFattureCollegate" in xml or sent_invoice.invoice_number in xml diff --git a/tests/test_invoice_events.py b/tests/test_invoice_events.py new file mode 100644 index 00000000..a8a80964 --- /dev/null +++ b/tests/test_invoice_events.py @@ -0,0 +1,88 @@ +"""Unit tests for invoice webhook event emission helpers.""" + +from types import SimpleNamespace +from unittest.mock import patch + +import pytest + +from app.constants import WebhookEvent +from app.utils.invoice_events import emit_credit_note_event, emit_invoice_event, emit_payment_event + +pytestmark = [pytest.mark.unit] + + +def test_emit_invoice_event_builds_payload(): + invoice = SimpleNamespace( + id=7, + invoice_number="INV-001", + status="sent", + payment_status="unpaid", + client_id=3, + project_id=9, + ) + with patch("app.utils.invoice_events.emit_event") as mock_emit: + emit_invoice_event(WebhookEvent.INVOICE_SENT.value, invoice, recipient_email="a@b.c") + mock_emit.assert_called_once() + event_name, payload = mock_emit.call_args[0] + assert event_name == "invoice.sent" + assert payload["invoice_id"] == 7 + assert payload["invoice_number"] == "INV-001" + assert payload["recipient_email"] == "a@b.c" + + +def test_emit_invoice_paid_via_payment_service_path(): + """Smoke: PaymentService emits invoice.paid when fully paid (mocked commit).""" + from decimal import Decimal + from unittest.mock import MagicMock, patch + + from app.services.payment_service import PaymentService + + invoice = MagicMock() + invoice.id = 1 + invoice.currency_code = "EUR" + invoice.outstanding_amount = Decimal("100") + invoice.payment_status = "fully_paid" + invoice.client_id = None + invoice.client_email = None + + payment = MagicMock() + payment.id = 11 + payment.amount = Decimal("100") + + svc = PaymentService() + svc.invoice_repo = MagicMock() + svc.invoice_repo.get_by_id.return_value = invoice + svc.payment_repo = MagicMock() + svc.payment_repo.create.return_value = payment + svc.payment_repo.get_total_for_invoice.return_value = Decimal("100") + + with ( + patch("app.services.payment_service.safe_commit", return_value=True), + patch("app.services.payment_service.db.session.flush"), + patch("app.services.payment_service.emit_event"), + patch("app.utils.workflow_bridge.fire_invoice_paid_workflow"), + patch("app.utils.invoice_events.emit_event") as mock_emit, + ): + from datetime import date + + result = svc.create_payment( + invoice_id=1, + amount=Decimal("100"), + payment_date=date.today(), + received_by=1, + status="completed", + ) + assert result["success"] is True + paid_calls = [c for c in mock_emit.call_args_list if c[0][0] == WebhookEvent.INVOICE_PAID.value] + assert paid_calls, "expected invoice.paid emit" + + +def test_emit_credit_note_and_payment_helpers(): + cn = SimpleNamespace(id=2, credit_number="CN-1", invoice_id=1, amount=10, status="draft") + payment = SimpleNamespace(id=5, invoice_id=1, amount=20, status="refunded") + with patch("app.utils.invoice_events.emit_event") as mock_emit: + emit_credit_note_event(WebhookEvent.CREDIT_NOTE_CREATED.value, cn) + emit_payment_event(WebhookEvent.PAYMENT_REFUNDED.value, payment) + assert mock_emit.call_count == 2 + assert mock_emit.call_args_list[0][0][0] == "credit_note.created" + assert mock_emit.call_args_list[1][0][0] == "payment.refunded" diff --git a/tests/test_invoice_line_tax_discounts.py b/tests/test_invoice_line_tax_discounts.py new file mode 100644 index 00000000..c95149cd --- /dev/null +++ b/tests/test_invoice_line_tax_discounts.py @@ -0,0 +1,455 @@ +"""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 factories import ClientFactory, ProjectFactory, UserFactory + +from app import db +from app.models import Client, Invoice, InvoiceItem, Project, Settings, User + +# --------------------------------------------------------------------------- +# 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 diff --git a/tests/test_invoice_reminders.py b/tests/test_invoice_reminders.py new file mode 100644 index 00000000..266600b6 --- /dev/null +++ b/tests/test_invoice_reminders.py @@ -0,0 +1,335 @@ +"""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 + +from datetime import date, datetime +from decimal import Decimal + +import pytest + +# --------------------------------------------------------------------------- +# 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.models import Invoice + from app.services.invoice_reminder_service import process_due_reminders + + 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.models import Invoice + from app.services.invoice_reminder_service import process_due_reminders + + 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") diff --git a/tests/test_invoices.py b/tests/test_invoices.py index f592c73e..20548067 100644 --- a/tests/test_invoices.py +++ b/tests/test_invoices.py @@ -2423,3 +2423,70 @@ 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_phase5_features.py b/tests/test_phase5_features.py new file mode 100644 index 00000000..81d10c23 --- /dev/null +++ b/tests/test_phase5_features.py @@ -0,0 +1,446 @@ +"""Phase 5 tests: Mollie, PayPal signature, refunds, portal PDF, pay.html, receipt email.""" + +import io +import json +from decimal import Decimal +from types import SimpleNamespace +from unittest.mock import MagicMock, patch + +import pytest + +# --------------------------------------------------------------------------- +# 1. Registry / Mollie +# --------------------------------------------------------------------------- + + +def test_provider_registry_includes_mollie(): + from app.payments.registry import PROVIDERS + + assert "mollie" in PROVIDERS + + +def test_mollie_checkout_requires_api_key(): + from app.payments.mollie_provider import MollieProvider + + provider = MollieProvider({}, is_test_mode=True) + result = provider.create_checkout_session( + invoice_id=1, + amount=Decimal("50.00"), + currency="EUR", + success_url="https://example.com/success", + cancel_url="https://example.com/cancel", + ) + assert result.success is False + assert "API key" in (result.message or "") + + +def test_mollie_webhook_returns_valid_on_paid_status(): + """verify_webhook fetches payment from Mollie and returns its status as event_type.""" + from app.payments.mollie_provider import MollieProvider + + payment_data = { + "id": "tr_test_1", + "status": "paid", + "metadata": {"invoice_id": "42"}, + "amount": {"value": "75.00", "currency": "EUR"}, + } + mock_resp = MagicMock() + mock_resp.status_code = 200 + mock_resp.json.return_value = payment_data + + provider = MollieProvider({"api_key": "test_key"}, is_test_mode=True) + with patch("requests.get", return_value=mock_resp): + result = provider.verify_webhook(b"id=tr_test_1", {}) + + assert result.valid is True + assert result.event_type == "paid" + assert result.transaction_id == "tr_test_1" + assert result.invoice_id == 42 + assert result.amount == Decimal("75.00") + + +def test_mollie_webhook_whitelist_accepted_in_checkout_service(): + """'paid' event_type from Mollie should be processed (not ignored) by CheckoutService.""" + from app.payments.base import WebhookResult + + wh = WebhookResult( + valid=True, + event_type="paid", + transaction_id="tr_mollie_1", + invoice_id=None, # no invoice_id — will be ignored gracefully + amount=Decimal("0"), + currency="EUR", + ) + # event_type is accepted (not ignored), so it reaches the invoice_id check + # With invoice_id=None it returns ignored but NOT status 400 + from app.services.checkout_service import CheckoutService + + class _FakeProvider: + def verify_webhook(self, payload, headers): + return wh + + gw = SimpleNamespace(id=1, provider="mollie", is_test_mode=True, config="{}") + with patch("app.payments.registry.get_provider", return_value=_FakeProvider()): + result = CheckoutService().complete_webhook(gw, b"id=tr_mollie_1", {}) + + assert result["success"] is True # not 400 + assert result.get("status") == 200 + + +# --------------------------------------------------------------------------- +# 2. PayPal webhook signature verification +# --------------------------------------------------------------------------- + + +def test_paypal_webhook_no_credentials_logs_warning_and_accepts(): + """When webhook_id/credentials are absent, webhook is accepted with a warning.""" + from app.payments.paypal_provider import PayPalProvider + + event = { + "event_type": "PAYMENT.CAPTURE.COMPLETED", + "resource": { + "id": "cap_1", + "custom_id": "7", + "amount": {"value": "30.00", "currency_code": "USD"}, + }, + } + provider = PayPalProvider({}, is_test_mode=True) + result = provider.verify_webhook(json.dumps(event).encode(), {}) + assert result.valid is True + assert result.event_type == "PAYMENT.CAPTURE.COMPLETED" + + +def test_paypal_webhook_with_credentials_calls_verify_api(): + """When credentials present, the verify-webhook-signature API is called.""" + from app.payments.paypal_provider import PayPalProvider + + event = { + "event_type": "PAYMENT.CAPTURE.COMPLETED", + "resource": { + "id": "cap_2", + "custom_id": "8", + "amount": {"value": "50.00", "currency_code": "EUR"}, + }, + } + headers = { + "PAYPAL-AUTH-ALGO": "SHA256withRSA", + "PAYPAL-CERT-URL": "https://api.paypal.com/cert", + "PAYPAL-TRANSMISSION-ID": "tx_id", + "PAYPAL-TRANSMISSION-SIG": "sig", + "PAYPAL-TRANSMISSION-TIME": "2024-01-01T00:00:00Z", + } + + config = { + "client_id": "client_id_x", + "client_secret": "client_secret_x", + "webhook_id": "WH-123", + "sandbox": True, + } + provider = PayPalProvider(config, is_test_mode=True) + + # Mock token fetch and verification call + token_resp = MagicMock() + token_resp.ok = True + token_resp.json.return_value = {"access_token": "test_token"} + + verify_resp = MagicMock() + verify_resp.ok = True + verify_resp.json.return_value = {"verification_status": "SUCCESS"} + + with patch("requests.post", side_effect=[token_resp, verify_resp]) as mock_post: + result = provider.verify_webhook(json.dumps(event).encode(), headers) + + assert result.valid is True + # Second call should be the verify-webhook-signature endpoint + verify_call_url = mock_post.call_args_list[1].args[0] + assert "verify-webhook-signature" in verify_call_url + + +def test_paypal_webhook_invalid_signature_returns_invalid(): + """FAILURE status from PayPal verify API should make webhook invalid.""" + from app.payments.paypal_provider import PayPalProvider + + event = {"event_type": "PAYMENT.CAPTURE.COMPLETED", "resource": {}} + config = { + "client_id": "cid", + "client_secret": "csecret", + "webhook_id": "WH-456", + "sandbox": True, + } + provider = PayPalProvider(config, is_test_mode=True) + + token_resp = MagicMock() + token_resp.ok = True + token_resp.json.return_value = {"access_token": "tok"} + + verify_resp = MagicMock() + verify_resp.ok = True + verify_resp.json.return_value = {"verification_status": "FAILURE"} + + with patch("requests.post", side_effect=[token_resp, verify_resp]): + result = provider.verify_webhook(json.dumps(event).encode(), {}) + + assert result.valid is False + assert "FAILURE" in (result.message or "") + + +# --------------------------------------------------------------------------- +# 3. Refunds +# --------------------------------------------------------------------------- + + +def test_base_refund_default_not_supported(): + """Default PaymentProvider.refund() returns not-supported.""" + from app.payments.base import PaymentProvider + + class _Concrete(PaymentProvider): + provider_name = "dummy" + + def create_checkout_session(self, **kw): + pass + + def verify_webhook(self, payload, headers): + pass + + p = _Concrete({}) + res = p.refund(gateway_transaction_id="tx", amount=Decimal("10"), currency="EUR") + assert res["success"] is False + assert "not supported" in res["message"] + + +def test_stripe_refund_calls_stripe_api(): + from app.payments.stripe_provider import StripeProvider + + provider = StripeProvider({"api_key": "sk_test"}, is_test_mode=True) + mock_refund = {"id": "re_1", "status": "succeeded"} + + with patch("stripe.Refund.create", return_value=mock_refund) as mock_create: + result = provider.refund( + gateway_transaction_id="pi_test_1", + amount=Decimal("20.00"), + currency="EUR", + reason="requested_by_customer", + ) + + assert result["success"] is True + assert result["refund_id"] == "re_1" + assert mock_create.call_args.kwargs["payment_intent"] == "pi_test_1" + + +def test_mollie_refund_calls_mollie_api(): + from app.payments.mollie_provider import MollieProvider + + provider = MollieProvider({"api_key": "test_key"}, is_test_mode=True) + mock_resp = MagicMock() + mock_resp.status_code = 201 + mock_resp.json.return_value = {"id": "re_mol_1", "status": "pending"} + + with patch("requests.post", return_value=mock_resp): + result = provider.refund( + gateway_transaction_id="tr_test_1", + amount=Decimal("15.00"), + currency="EUR", + ) + + assert result["success"] is True + assert result["refund_id"] == "re_mol_1" + + +def test_paypal_refund_calls_paypal_api(): + from app.payments.paypal_provider import PayPalProvider + + provider = PayPalProvider({"client_id": "cid", "client_secret": "cs", "sandbox": True}, is_test_mode=True) + token_resp = MagicMock() + token_resp.ok = True + token_resp.json.return_value = {"access_token": "tok"} + + refund_resp = MagicMock() + refund_resp.ok = True + refund_resp.json.return_value = {"id": "refund_pp_1", "status": "COMPLETED"} + + with patch("requests.post", side_effect=[token_resp, refund_resp]): + result = provider.refund( + gateway_transaction_id="cap_1", + amount=Decimal("25.00"), + currency="USD", + ) + + assert result["success"] is True + assert result["refund_id"] == "refund_pp_1" + + +def test_refund_route_local_only(app, invoice): + """Refund route marks payment refunded when no gateway_transaction_id present.""" + from app.models import Payment + + with app.app_context(): + from datetime import date + + from app import db + + # Create a completed payment with no gateway id + payment = Payment( + invoice_id=invoice.id, + amount=Decimal("10.00"), + currency="EUR", + payment_date=date.today(), + status="completed", + method="bank_transfer", + received_by=1, + ) + db.session.add(payment) + db.session.commit() + payment_id = payment.id + + with app.test_client() as client: + # Login as admin + with client.session_transaction() as sess: + sess["_user_id"] = "1" + sess["_fresh"] = True + + resp = client.post( + f"/payments/{payment_id}/refund", + data={"csrf_token": "test", "reason": "test refund"}, + follow_redirects=False, + ) + # Should redirect (302) rather than error + assert resp.status_code in (302, 200, 400) + + +# --------------------------------------------------------------------------- +# 4. pay.html provider-neutral +# --------------------------------------------------------------------------- + + +def test_pay_html_no_unsupported_message_for_paypal(app): + """pay.html should not contain the 'not yet supported' string.""" + import os + + template_path = os.path.join( + os.path.dirname(__file__), + "../app/templates/payment_gateways/pay.html", + ) + with open(template_path) as f: + content = f.read() + assert "not yet supported" not in content + assert "Continue to Payment" in content + + +def test_pay_html_uses_provider_title(app): + """pay.html should reference the provider dynamically (not hardcode stripe check).""" + import os + + template_path = os.path.join( + os.path.dirname(__file__), + "../app/templates/payment_gateways/pay.html", + ) + with open(template_path) as f: + content = f.read() + # No provider-specific conditional branch left + assert "gateway.provider == 'stripe'" not in content + + +# --------------------------------------------------------------------------- +# 5. Receipt email +# --------------------------------------------------------------------------- + + +def test_receipt_email_sent_on_completed_payment(app, invoice): + """PaymentService.create_payment sends receipt email when client_email present.""" + from datetime import date + from decimal import Decimal + + with app.app_context(): + from app.models import Invoice + + inv = Invoice.query.get(invoice.id) + inv.client_email = "client@example.com" + from app import db + + db.session.commit() + + with app.app_context(): + from app.services.payment_service import PaymentService + + with patch("app.services.payment_service.PaymentService._send_receipt_email") as mock_send: + PaymentService().create_payment( + invoice_id=invoice.id, + amount=Decimal("10.00"), + payment_date=date.today(), + received_by=1, + currency="EUR", + status="completed", + ) + assert mock_send.called + + +def test_receipt_email_not_sent_for_pending(app, invoice): + """No receipt email for pending payments.""" + from datetime import date + from decimal import Decimal + + with app.app_context(): + from app.services.payment_service import PaymentService + + with patch("app.services.payment_service.PaymentService._send_receipt_email") as mock_send: + PaymentService().create_payment( + invoice_id=invoice.id, + amount=Decimal("5.00"), + payment_date=date.today(), + received_by=1, + currency="EUR", + status="pending", + ) + assert not mock_send.called + + +# --------------------------------------------------------------------------- +# 6. Client portal PDF route +# --------------------------------------------------------------------------- + + +def test_portal_pdf_requires_auth(app): + """PDF route returns 302 redirect (to login) when not authenticated.""" + with app.test_client() as client: + resp = client.get("/client-portal/invoices/999/pdf") + assert resp.status_code in (302, 401) + + +def test_portal_pdf_rejects_wrong_client(app, invoice): + """PDF route returns 404/403 when invoice belongs to different client.""" + with app.app_context(): + from app import db + from app.models import Client + + # Create a different client + other_client = Client(name="Other Client", email="other@example.com") + db.session.add(other_client) + db.session.commit() + other_client_id = other_client.id + + with app.test_client() as client: + with client.session_transaction() as sess: + sess["client_portal_client_id"] = other_client_id + sess["client_portal_logged_in"] = True + + resp = client.get(f"/client-portal/invoices/{invoice.id}/pdf") + assert resp.status_code in (302, 404, 403) + + +# --------------------------------------------------------------------------- +# 7. create.html includes Mollie option +# --------------------------------------------------------------------------- + + +def test_create_html_has_mollie_option(): + """create.html should include Mollie as a provider option.""" + import os + + template_path = os.path.join( + os.path.dirname(__file__), + "../app/templates/payment_gateways/create.html", + ) + with open(template_path) as f: + content = f.read() + assert 'value="mollie"' in content + assert "mollieFields" in content diff --git a/tests/test_scheduled_invoice_reports.py b/tests/test_scheduled_invoice_reports.py index 8ecb0301..ff3bafd7 100644 --- a/tests/test_scheduled_invoice_reports.py +++ b/tests/test_scheduled_invoice_reports.py @@ -44,3 +44,80 @@ 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 factories import ClientFactory, InvoiceFactory + + from app import db + from app.models import Invoice + from app.utils.scheduled_tasks import check_overdue_invoices + + 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 32fdeba9..d9a838a6 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"