From 8d79ff0c2e2568cb0de9d1c86fe9dd6c9797c0c2 Mon Sep 17 00:00:00 2001 From: Ashwin Date: Thu, 15 Oct 2026 18:45:23 +0530 Subject: [PATCH] feat: add account statement feature with PDF download - Implemented a new endpoint for generating account statements as PDFs. - Added API configuration for fetching account statements and their PDFs. - Created data models for account statements, including sections and entries. - Developed a provider for managing account statement data retrieval. - Introduced a new screen for displaying account statements with options to change the date range. - Enhanced the account detail screen to include a button for accessing statements. - Implemented unit tests for account statement functionality and provider behavior. - Updated invoice formatting to correctly display negative amounts for payments and credits. --- backend/invoices/api_urls.py | 11 + backend/invoices/api_views.py | 147 +++++-- backend/invoices/pdf.py | 108 ++++-- backend/invoices/serializer.py | 42 ++ backend/invoices/statements.py | 207 ++++++++++ .../templates/invoices/pdf/statement.html | 164 ++++++++ .../invoices/tests/test_account_statements.py | 314 +++++++++++++++ backend/pyproject.toml | 2 +- backend/uv.lock | 2 +- docs/api/endpoint-index.md | 2 + docs/api/invoices.md | 37 +- frontend/src/lib/server/v2/statements.js | 158 ++++++++ frontend/src/lib/server/v2/statements.test.js | 204 ++++++++++ .../routes/(app)/accounts/[id]/+page.svelte | 5 + .../accounts/[id]/statement/+page.server.js | 24 ++ .../accounts/[id]/statement/+page.svelte | 246 ++++++++++++ .../accounts/[id]/statement/pdf/+server.js | 11 + mobile/docs/PARITY.md | 1 + mobile/lib/config/api_config.dart | 27 ++ mobile/lib/data/models/account_statement.dart | 137 +++++++ .../providers/account_statement_provider.dart | 56 +++ mobile/lib/routes/app_router.dart | 9 + .../accounts/account_detail_screen.dart | 10 + .../accounts/account_statement_screen.dart | 359 ++++++++++++++++++ .../lib/screens/invoices/invoice_format.dart | 5 +- .../account_statement_screen_test.dart | 246 ++++++++++++ mobile/test/unit/account_statement_test.dart | 210 ++++++++++ 27 files changed, 2666 insertions(+), 78 deletions(-) create mode 100644 backend/invoices/statements.py create mode 100644 backend/invoices/templates/invoices/pdf/statement.html create mode 100644 backend/invoices/tests/test_account_statements.py create mode 100644 frontend/src/lib/server/v2/statements.js create mode 100644 frontend/src/lib/server/v2/statements.test.js create mode 100644 frontend/src/routes/(app)/accounts/[id]/statement/+page.server.js create mode 100644 frontend/src/routes/(app)/accounts/[id]/statement/+page.svelte create mode 100644 frontend/src/routes/(app)/accounts/[id]/statement/pdf/+server.js create mode 100644 mobile/lib/data/models/account_statement.dart create mode 100644 mobile/lib/providers/account_statement_provider.dart create mode 100644 mobile/lib/screens/accounts/account_statement_screen.dart create mode 100644 mobile/test/screens/account_statement_screen_test.dart create mode 100644 mobile/test/unit/account_statement_test.dart diff --git a/backend/invoices/api_urls.py b/backend/invoices/api_urls.py index 477f4fd5..a3ae4a0d 100644 --- a/backend/invoices/api_urls.py +++ b/backend/invoices/api_urls.py @@ -163,6 +163,17 @@ urlpatterns = [ api_views.AgingReportView.as_view(), name="reports_aging", ), + # Account statements (admin-only, like the reports) + path( + "statements//", + api_views.AccountStatementView.as_view(), + name="account_statement", + ), + path( + "statements//pdf/", + api_views.AccountStatementPDFView.as_view(), + name="account_statement_pdf", + ), # ========================================================================== # INVOICE FROM OPPORTUNITY # ========================================================================== diff --git a/backend/invoices/api_views.py b/backend/invoices/api_views.py index c325bfa6..f687eba4 100644 --- a/backend/invoices/api_views.py +++ b/backend/invoices/api_views.py @@ -20,6 +20,7 @@ from rest_framework.permissions import IsAuthenticated from rest_framework.response import Response from rest_framework.views import APIView +from accounts.models import Account from common.custom_fields import validate_payload as validate_custom_fields_payload from common.lookups import get_on_visible_record_or_404 from common.models import Attachments, Comment, CustomFieldDefinition @@ -48,6 +49,8 @@ from invoices.pdf import ( generate_estimate_pdf, generate_invoice_filename, generate_invoice_pdf, + generate_statement_filename, + generate_statement_pdf, ) from invoices.permissions import ( get_estimate_or_error, @@ -58,6 +61,7 @@ from invoices.permissions import ( visible_recurring_qs, ) from invoices.serializer import ( + AccountStatementSerializer, EstimateCreateSerializer, EstimateListSerializer, EstimateSerializer, @@ -80,6 +84,7 @@ from invoices.serializer import ( issued_lock_message, validate_document_account, ) +from invoices.statements import build_statement, statement_period from invoices.tasks import create_invoice_history, send_email, send_invoice_to_client logger = logging.getLogger(__name__) @@ -646,25 +651,35 @@ class InvoicePDFView(APIView): if error: return error - try: - pdf_content = generate_invoice_pdf(invoice) - filename = generate_invoice_filename(invoice) + return _pdf_response( + lambda: generate_invoice_pdf(invoice), generate_invoice_filename(invoice) + ) - response = HttpResponse(pdf_content, content_type="application/pdf") - response["Content-Disposition"] = f'attachment; filename="{filename}"' - return response - except ImportError: - logger.exception("PDF generation library not available") - return Response( - {"error": True, "message": "PDF generation unavailable"}, - status=status.HTTP_503_SERVICE_UNAVAILABLE, - ) - except Exception: - logger.exception("Failed to generate invoice PDF") - return Response( - {"error": True, "message": "Failed to generate PDF"}, - status=status.HTTP_500_INTERNAL_SERVER_ERROR, - ) + +def _pdf_response(render, filename): + """The PDF ``render()`` makes, as a download named ``filename``. + + 503 when WeasyPrint is not installed, 500 when the render fails; both are + logged. Shared by the invoice, estimate and account statement PDF views. + """ + try: + pdf_content = render() + except ImportError: + logger.exception("PDF generation library not available") + return Response( + {"error": True, "message": "PDF generation unavailable"}, + status=status.HTTP_503_SERVICE_UNAVAILABLE, + ) + except Exception: + logger.exception("Failed to generate %s", filename) + return Response( + {"error": True, "message": "Failed to generate PDF"}, + status=status.HTTP_500_INTERNAL_SERVER_ERROR, + ) + + response = HttpResponse(pdf_content, content_type="application/pdf") + response["Content-Disposition"] = f'attachment; filename="{filename}"' + return response # ============================================================================= @@ -1434,25 +1449,10 @@ class EstimatePDFView(APIView): if error: return error - try: - pdf_content = generate_estimate_pdf(estimate) - filename = generate_estimate_filename(estimate) - - response = HttpResponse(pdf_content, content_type="application/pdf") - response["Content-Disposition"] = f'attachment; filename="{filename}"' - return response - except ImportError: - logger.exception("PDF generation library not available") - return Response( - {"error": True, "message": "PDF generation unavailable"}, - status=status.HTTP_503_SERVICE_UNAVAILABLE, - ) - except Exception: - logger.exception("Failed to generate estimate PDF") - return Response( - {"error": True, "message": "Failed to generate PDF"}, - status=status.HTTP_500_INTERNAL_SERVER_ERROR, - ) + return _pdf_response( + lambda: generate_estimate_pdf(estimate), + generate_estimate_filename(estimate), + ) # ============================================================================= @@ -2036,7 +2036,7 @@ class InvoiceAttachmentDetailView(APIView): # ============================================================================= -def _forbid_non_admin_reports(request): +def _forbid_non_admin_reports(request, subject="invoice reports"): """Return a 403 Response for non-admins, or None to allow. The invoice reports are org-wide financial roll-ups -- total invoiced and @@ -2047,12 +2047,16 @@ def _forbid_non_admin_reports(request): leak those scopes exist to prevent. So the three report endpoints are admin-only (Django superusers included), the same bar as the org and team settings. + + Account statements are held to the same bar: one sums every invoice on an + account, including ones a member may not open, and one built from only the + invoices a member can see would show the customer a wrong balance. """ if not is_org_admin(request.profile): return Response( { "error": True, - "message": "Only an administrator can view invoice reports.", + "message": f"Only an administrator can view {subject}.", }, status=status.HTTP_403_FORBIDDEN, ) @@ -2389,6 +2393,70 @@ class AgingReportView(APIView): ) +# ============================================================================= +# ACCOUNT STATEMENTS +# ============================================================================= + + +def _statement_or_error(request, account_id): + """``(account, statement, None)``, or ``(None, None, response)`` to return. + + Admin-only before anything else, so a member learns nothing about which + accounts exist. Then the account, in the caller's org or a 404. A bad + period raises the ValidationError DRF answers with a 400. + """ + denied = _forbid_non_admin_reports(request, "account statements") + if denied: + return None, None, denied + account = Account.objects.filter(id=account_id, org=request.profile.org).first() + if account is None: + return ( + None, + None, + Response( + {"error": True, "message": "Account not found"}, + status=status.HTTP_404_NOT_FOUND, + ), + ) + start, end = statement_period(request.GET) + return account, build_statement(account, start, end), None + + +class AccountStatementView(APIView): + """An account's statement for a period: per currency, the opening balance, + the period's invoices, payments and cancellations with a running balance, + and the closing balance. See `invoices.statements`.""" + + permission_classes = (IsAuthenticated, HasOrgContext) + + @extend_schema( + tags=["Reports"], + operation_id="account_statement", + responses=AccountStatementSerializer, + ) + def get(self, request, account_id): + _, statement, error = _statement_or_error(request, account_id) + if error: + return error + return Response(AccountStatementSerializer(statement).data) + + +class AccountStatementPDFView(APIView): + """The same statement as a PDF.""" + + permission_classes = (IsAuthenticated, HasOrgContext) + + @extend_schema(tags=["Reports"], operation_id="account_statement_pdf") + def get(self, request, account_id): + account, statement, error = _statement_or_error(request, account_id) + if error: + return error + return _pdf_response( + lambda: generate_statement_pdf(account, statement), + generate_statement_filename(statement), + ) + + # ============================================================================= # INVOICE FROM OPPORTUNITY # ============================================================================= @@ -2583,7 +2651,6 @@ class InvoiceFromTimeEntriesView(APIView): permission_classes = (IsAuthenticated, HasOrgContext) def post(self, request, *args, **kwargs): - from accounts.models import Account from cases.models import TimeEntry from cases.services.billing import ( TimeEntryInvoicingError, diff --git a/backend/invoices/pdf.py b/backend/invoices/pdf.py index 57257281..afba822d 100644 --- a/backend/invoices/pdf.py +++ b/backend/invoices/pdf.py @@ -460,7 +460,10 @@ def format_currency(amount, currency="USD"): symbol = symbols.get(currency, currency + " ") if amount is None: amount = Decimal("0.00") - return f"{symbol}{amount:,.2f}" + # The sign leads ("-$40.00"): a statement's payments and credit balances + # are negative, and "$-40.00" reads as a typo. + sign = "-" if amount < 0 else "" + return f"{sign}{symbol}{abs(amount):,.2f}" def generate_invoice_pdf(invoice, include_payments=True): @@ -549,13 +552,29 @@ def generate_invoice_pdf(invoice, include_payments=True): else: css_content = get_default_css() - # Apply template colors if set + return _write_pdf(html_content, _with_template_colors(css_content, template)) + + +def _with_template_colors(css_content, template): + """``css_content`` in ``template``'s colors, when there is a template.""" if template: css_content = css_content.replace("#3B82F6", template.primary_color) if template.secondary_color: css_content = css_content.replace("#1E40AF", template.secondary_color) + return css_content - # Generate PDF + +def _default_css_for(org): + """The default stylesheet in the colors of ``org``'s default template.""" + from invoices.models import InvoiceTemplate + + template = InvoiceTemplate.objects.filter(org=org, is_default=True).first() + return _with_template_colors(get_default_css(), template) + + +def _write_pdf(html_content, css_content): + """Render HTML and CSS to PDF bytes, fetching only what + `SafePdfURLFetcher` allows.""" font_config = FontConfiguration() url_fetcher = SafePdfURLFetcher() html = HTML( @@ -589,11 +608,6 @@ def generate_estimate_pdf(estimate): """ check_weasyprint() - # Get the org's default template for styling - from invoices.models import InvoiceTemplate - - template = InvoiceTemplate.objects.filter(org=estimate.org, is_default=True).first() - # Pre-format line items with currency line_items = [] for item in estimate.line_items.all().order_by("order"): @@ -626,36 +640,58 @@ def generate_estimate_pdf(estimate): "total_amount": format_currency(estimate.total_amount, estimate.currency), } - # Use default template + # Use default template, in the org's default template's colors html_content = render_to_string("invoices/pdf/estimate.html", context) - css_content = get_default_css() + return _write_pdf(html_content, _default_css_for(estimate.org)) - # Apply template colors if set - if template: - css_content = css_content.replace("#3B82F6", template.primary_color) - if template.secondary_color: - css_content = css_content.replace("#1E40AF", template.secondary_color) - # Generate PDF - font_config = FontConfiguration() - url_fetcher = SafePdfURLFetcher() - html = HTML( - string=html_content, - base_url=settings.BASE_DIR, - url_fetcher=url_fetcher, - ) - css = CSS( - string=css_content, - base_url=settings.BASE_DIR, - url_fetcher=url_fetcher, - font_config=font_config, - ) +def generate_statement_pdf(account, statement): + """A PDF of ``statement`` (from `invoices.statements.build_statement`) + for ``account``, in the org's default template's colors. - pdf_buffer = io.BytesIO() - html.write_pdf(pdf_buffer, stylesheets=[css], font_config=font_config) - pdf_buffer.seek(0) + Built from the fixed template only, never an org's custom HTML, and through + Django's autoescape, since the account name and invoice titles are written + by members. + """ + check_weasyprint() - return pdf_buffer.getvalue() + sections = [] + for section in statement["currencies"]: + code = section["currency"] + + def fmt(amount, code=code): + return format_currency(amount, code) + + sections.append( + { + "currency": code, + "opening_balance": fmt(section["opening_balance"]), + "invoiced": fmt(section["invoiced"]), + "paid": fmt(-section["paid"]), + "cancelled": fmt(-section["cancelled"]), + "has_cancelled": section["cancelled"] > 0, + "closing_balance": fmt(section["closing_balance"]), + "in_credit": section["closing_balance"] < 0, + "entries": [ + { + **entry, + "amount": fmt(entry["amount"]), + "balance": fmt(entry["balance"]), + } + for entry in section["entries"] + ], + } + ) + + context = { + "org": account.org, + "account": account, + "start_date": statement["start_date"], + "end_date": statement["end_date"], + "sections": sections, + } + html_content = render_to_string("invoices/pdf/statement.html", context) + return _write_pdf(html_content, _default_css_for(account.org)) def render_invoice_template(template_html, context): @@ -725,3 +761,9 @@ def generate_invoice_filename(invoice): def generate_estimate_filename(estimate): """Generate a filename for the estimate PDF.""" return f"Estimate_{estimate.estimate_number}.pdf" + + +def generate_statement_filename(statement): + """Named for the period only. The account name is member-written text and + has no place in a Content-Disposition header.""" + return f"Statement_{statement['start_date']}_{statement['end_date']}.pdf" diff --git a/backend/invoices/serializer.py b/backend/invoices/serializer.py index 407b72e3..608751ab 100644 --- a/backend/invoices/serializer.py +++ b/backend/invoices/serializer.py @@ -1756,3 +1756,45 @@ class PublicEstimateSerializer(serializers.ModelSerializer): "terms", "line_items", ) + + +# ============================================================================= +# ACCOUNT STATEMENTS (read-only; built by `invoices.statements.build_statement`) +# ============================================================================= + + +def _statement_money(): + # No max_digits: a balance is a sum of many invoices and can outgrow one. + return serializers.DecimalField(max_digits=None, decimal_places=2) + + +class StatementEntrySerializer(serializers.Serializer): + date = serializers.DateField() + kind = serializers.ChoiceField(choices=("invoice", "payment", "cancellation")) + invoice_id = serializers.UUIDField() + invoice_number = serializers.CharField() + description = serializers.CharField() + amount = _statement_money() + balance = _statement_money() + + +class StatementCurrencySerializer(serializers.Serializer): + currency = serializers.CharField() + opening_balance = _statement_money() + invoiced = _statement_money() + paid = _statement_money() + cancelled = _statement_money() + closing_balance = _statement_money() + entries = StatementEntrySerializer(many=True) + + +class StatementAccountSerializer(serializers.Serializer): + id = serializers.UUIDField() + name = serializers.CharField() + + +class AccountStatementSerializer(serializers.Serializer): + account = StatementAccountSerializer() + start_date = serializers.DateField() + end_date = serializers.DateField() + currencies = StatementCurrencySerializer(many=True) diff --git a/backend/invoices/statements.py b/backend/invoices/statements.py new file mode 100644 index 00000000..ed963030 --- /dev/null +++ b/backend/invoices/statements.py @@ -0,0 +1,207 @@ +"""Account statements: what one account was billed and paid over a period. + +A statement is computed from the invoices and payments on record, never +stored, so it cannot disagree with them. There are no exchange rates, so it is +one section per currency, each with: + +* an opening balance: everything billed before the period, less everything + paid and cancelled before it; +* the period's entries in date order, each with the running balance: an + invoice on its issue date, a payment on its payment date, and a cancellation + on the day it happened; +* a closing balance: the opening balance plus the period's entries. + +Billed means the customer was asked to pay. Draft and Pending invoices were +not, so they are left off. A cancelled invoice stays on when it was sent or +paid toward: it is billed on its issue date and reversed on the day it was +cancelled, so a statement for an earlier month still closes on the balance it +showed then, and any payment it took leaves the account in credit. A cancelled +invoice nobody was sent or paid was never billed, and is left off. + +Admin-only (see `api_views._statement_or_error`): it sums every invoice on the +account, including ones a member may not open. +""" + +from decimal import Decimal + +from django.db.models import Exists, F, OuterRef, Q, Sum +from django.db.models.functions import Coalesce, TruncDate +from django.utils import timezone +from rest_framework.exceptions import ValidationError + +from common.money import group_by_currency +from common.validators import date_param +from invoices.models import Invoice, Payment + +# The longest period one statement covers, counting both ends: a year, +# leap year included. It bounds what one request may load and render. +MAX_STATEMENT_DAYS = 366 + +ZERO = Decimal("0") + +# Within a day: what was billed, then what was paid, then what was cancelled. +_KIND_ORDER = {"invoice": 0, "payment": 1, "cancellation": 2} + + +def statement_period(params): + """``(start, end)`` from a query string, or raise a ValidationError. + + Both dates are optional and default to this month so far, in the org's + day (`timezone.localdate()` is the org's inside a request). + """ + today = timezone.localdate() + start = date_param(params, "start_date") or today.replace(day=1) + end = date_param(params, "end_date") or today + if end < start: + raise ValidationError( + {"end_date": ["The end date must be on or after the start date."]} + ) + if (end - start).days + 1 > MAX_STATEMENT_DAYS: + raise ValidationError( + {"end_date": [f"A statement can cover at most {MAX_STATEMENT_DAYS} days."]} + ) + return start, end + + +def billed_invoices(account): + """The invoices on ``account`` its customer was asked to pay.""" + paid_toward = Exists(Payment.objects.filter(invoice=OuterRef("pk"))) + return ( + Invoice.objects.filter(org=account.org, account=account) + .exclude(status__in=("Draft", "Pending")) + .filter(~Q(status="Cancelled") | Q(sent_at__isnull=False) | Q(paid_toward)) + ) + + +def _payment_description(payment): + detail = payment.get_payment_method_display() + if payment.reference_number: + detail = f"{detail}, ref {payment.reference_number}" + return f"Payment ({detail})" + + +def build_statement(account, start, end): + """``account``'s statement from ``start`` to ``end``, both included. + + Amounts are signed: positive adds to what the account owes, negative takes + from it. A currency with no opening balance and nothing in the period is + left out. + """ + invoices = billed_invoices(account) + cancellations = invoices.filter(status="Cancelled").annotate( + cancelled_on=Coalesce(TruncDate("cancelled_at"), "issue_date") + ) + payments = Payment.objects.filter(org=account.org, invoice__in=invoices) + + before = {} + group_by_currency( + invoices.filter(issue_date__lt=start), before, invoiced=Sum("total_amount") + ) + group_by_currency( + cancellations.filter(cancelled_on__lt=start), + before, + cancelled=Sum("total_amount"), + ) + group_by_currency( + payments.filter(payment_date__lt=start), + before, + currency=F("invoice__currency"), + paid=Sum("amount"), + ) + + # (sort key, currency, invoice, entry) for everything dated in the period. + dated = [ + ( + (invoice.issue_date, _KIND_ORDER["invoice"], invoice.invoice_number), + invoice.currency, + invoice, + { + "date": invoice.issue_date, + "kind": "invoice", + "description": invoice.invoice_title, + "amount": invoice.total_amount, + }, + ) + for invoice in invoices.filter(issue_date__range=(start, end)) + ] + dated += [ + ( + (invoice.cancelled_on, _KIND_ORDER["cancellation"], invoice.invoice_number), + invoice.currency, + invoice, + { + "date": invoice.cancelled_on, + "kind": "cancellation", + "description": "Invoice cancelled", + "amount": -invoice.total_amount, + }, + ) + for invoice in cancellations.filter(cancelled_on__range=(start, end)) + ] + dated += [ + ( + ( + payment.payment_date, + _KIND_ORDER["payment"], + payment.invoice.invoice_number, + payment.created_at, + ), + payment.invoice.currency, + payment.invoice, + { + "date": payment.payment_date, + "kind": "payment", + "description": _payment_description(payment), + "amount": -payment.amount, + }, + ) + for payment in payments.filter(payment_date__range=(start, end)).select_related( + "invoice" + ) + ] + dated.sort(key=lambda row: row[0]) + + sections = [] + for code in sorted(set(before) | {row[1] for row in dated}): + prior = before.get(code, {}) + opening = ( + (prior.get("invoiced") or ZERO) + - (prior.get("paid") or ZERO) + - (prior.get("cancelled") or ZERO) + ) + entries = [] + totals = {"invoice": ZERO, "payment": ZERO, "cancellation": ZERO} + balance = opening + for _, currency, invoice, entry in dated: + if currency != code: + continue + balance += entry["amount"] + totals[entry["kind"]] += abs(entry["amount"]) + entries.append( + { + **entry, + "invoice_id": invoice.id, + "invoice_number": invoice.invoice_number, + "balance": balance, + } + ) + if not entries and not opening: + continue + sections.append( + { + "currency": code, + "opening_balance": opening, + "invoiced": totals["invoice"], + "paid": totals["payment"], + "cancelled": totals["cancellation"], + "closing_balance": balance, + "entries": entries, + } + ) + + return { + "account": {"id": account.id, "name": account.name}, + "start_date": start, + "end_date": end, + "currencies": sections, + } diff --git a/backend/invoices/templates/invoices/pdf/statement.html b/backend/invoices/templates/invoices/pdf/statement.html new file mode 100644 index 00000000..0f7de277 --- /dev/null +++ b/backend/invoices/templates/invoices/pdf/statement.html @@ -0,0 +1,164 @@ + + + + + Statement for {{ account.name }} + + + +
+
+
+

{{ org.company_name|default:org.name }}

+ {% if org.company_name and org.name and org.company_name != org.name %} +

{{ org.name }}

+ {% endif %} + {% if org.address_line %} +

{{ org.address_line }}

+ {% endif %} + {% if org.city or org.state or org.postcode %} +

+ {% if org.city %}{{ org.city }}{% endif %}{% if org.city and org.state %}, {% endif %}{% if org.state %}{{ org.state }}{% endif %} + {% if org.postcode %} {{ org.postcode }}{% endif %} +

+ {% endif %} + {% if org.phone %} +

Tel: {{ org.phone }}

+ {% endif %} + {% if org.email %} +

Email: {{ org.email }}

+ {% endif %} +
+ +
+
Statement
+ {% if org.logo %} +
+ +
+ {% else %} +
+ {{ org.company_name|default:org.name|slice:":4"|upper }} +
+ {% endif %} +
+
+ +
+
+

{{ account.name }}

+ {% if account.address_line %} +

{{ account.address_line }}

+ {% endif %} + {% if account.city or account.state or account.postcode %} +

+ {% if account.city %}{{ account.city }}{% endif %}{% if account.city and account.state %}, {% endif %}{% if account.state %}{{ account.state }}{% endif %} + {% if account.postcode %} {{ account.postcode }}{% endif %} +

+ {% endif %} + {% if account.country %} +

{{ account.get_country_display }}

+ {% endif %} +
+ +
+
+ From: + {{ start_date|date:"F d, Y" }} +
+
+ To: + {{ end_date|date:"F d, Y" }} +
+
+ Issued: + {% now "F d, Y" %} +
+
+
+ + {% for section in sections %} + {% if sections|length > 1 %} +
Amounts in {{ section.currency }}
+ {% endif %} + + + + + + + + + + + + + + + + + + + {% for entry in section.entries %} + + + + + + + + {% endfor %} + +
DateInvoiceDetailsAmountBalance
{{ start_date|date:"M d, Y" }}Opening balance{{ section.opening_balance }}
{{ entry.date|date:"M d, Y" }}{{ entry.invoice_number }}{{ entry.description }}{{ entry.amount }}{{ entry.balance }}
+ +
+ + + + + + + + + + + + + + + {% if section.has_cancelled %} + + + + + {% endif %} + + + + + +
Opening balance{{ section.opening_balance }}
Invoiced{{ section.invoiced }}
Payments
Cancelled{{ section.cancelled }}
{% if section.in_credit %}In credit{% else %}Balance due{% endif %}{{ section.closing_balance }}
+
+ {% empty %} +

Nothing was billed or paid in this period, and nothing is owed.

+ {% endfor %} + + +
+ + diff --git a/backend/invoices/tests/test_account_statements.py b/backend/invoices/tests/test_account_statements.py new file mode 100644 index 00000000..c1d4319e --- /dev/null +++ b/backend/invoices/tests/test_account_statements.py @@ -0,0 +1,314 @@ +"""Account statements: what one account was billed and paid over a period (#810). + +`GET /api/invoices/statements//` and its `pdf/` twin. Per currency, a +statement has an opening balance, the period's invoices, payments and +cancellations in date order with a running balance, and a closing balance. + +Admin-only, like the invoice reports: it sums every invoice on the account, +including ones a member may not open, and a statement built from only the +invoices a member can see would show the customer a wrong balance. +""" + +import datetime +import uuid +from decimal import Decimal +from unittest.mock import patch + +import pytest +from django.utils import timezone + +from accounts.models import Account +from invoices.models import Invoice, Payment + +pytestmark = pytest.mark.django_db + +OCTOBER = "start_date=2026-10-01&end_date=2026-10-31" +SEPTEMBER = "start_date=2026-09-01&end_date=2026-09-30" + + +def _url(account_id, query=OCTOBER, pdf=False): + return f"/api/invoices/statements/{account_id}/{'pdf/' if pdf else ''}?{query}" + + +def _invoice(account, total, issued, status="Sent", currency="USD", **fields): + """An invoice for ``total``, stored as the lifecycle endpoints leave one.""" + invoice = Invoice.objects.create( + invoice_title=fields.pop("title", "Work"), + account=account, + currency=currency, + issue_date=issued, + org=account.org, + ) + Invoice.objects.filter(pk=invoice.pk).update( + status=status, + total_amount=Decimal(total), + amount_due=Decimal(total), + **fields, + ) + invoice.refresh_from_db() + return invoice + + +def _pay(invoice, amount, on): + return Payment.objects.create( + invoice=invoice, + amount=Decimal(amount), + payment_date=on, + payment_method="BANK_TRANSFER", + org=invoice.org, + ) + + +def _noon(day): + return datetime.datetime.combine(day, datetime.time(12), tzinfo=datetime.UTC) + + +def _sections(response): + assert response.status_code == 200, response.content + return {s["currency"]: s for s in response.json()["currencies"]} + + +def _rows(section): + return [ + (e["date"], e["kind"], e["amount"], e["balance"]) for e in section["entries"] + ] + + +@pytest.fixture +def account(org_a): + return Account.objects.create(name="Acme", org=org_a) + + +class TestWhoMayRead: + @pytest.mark.parametrize("pdf", [False, True], ids=["json", "pdf"]) + def test_a_member_is_refused(self, user_client, account, pdf): + _invoice(account, "100.00", datetime.date(2026, 10, 2)) + response = user_client.get(_url(account.id, pdf=pdf)) + assert response.status_code == 403 + assert "currencies" not in response.json() + + def test_a_member_learns_nothing_about_which_accounts_exist(self, user_client): + response = user_client.get(_url(uuid.uuid4())) + assert response.status_code == 403 + + def test_an_admin_may_read_it(self, admin_client, account): + assert admin_client.get(_url(account.id)).status_code == 200 + + def test_another_orgs_account_is_not_found(self, admin_client, org_b): + theirs = Account.objects.create(name="Theirs", org=org_b) + for pdf in (False, True): + assert admin_client.get(_url(theirs.id, pdf=pdf)).status_code == 404 + + def test_an_unknown_account_is_not_found(self, admin_client): + assert admin_client.get(_url(uuid.uuid4())).status_code == 404 + + def test_signed_out_is_refused(self, unauthenticated_client, account): + response = unauthenticated_client.get(_url(account.id)) + assert response.status_code in (401, 403) + assert "currencies" not in response.json() + + +class TestBalances: + def test_opening_balance_entries_and_closing_balance(self, admin_client, account): + earlier = _invoice(account, "100.00", datetime.date(2026, 9, 10)) + _pay(earlier, "40.00", datetime.date(2026, 9, 20)) + october = _invoice(account, "250.00", datetime.date(2026, 10, 5), title="Build") + _pay(earlier, "60.00", datetime.date(2026, 10, 12)) + _pay(october, "100.00", datetime.date(2026, 10, 20)) + _invoice(account, "30.00", datetime.date(2026, 11, 2)) # after the period + + response = admin_client.get(_url(account.id)) + usd = _sections(response)["USD"] + + body = response.json() + assert body["account"] == {"id": str(account.id), "name": "Acme"} + assert (body["start_date"], body["end_date"]) == ("2026-10-01", "2026-10-31") + assert usd["opening_balance"] == "60.00" + assert _rows(usd) == [ + ("2026-10-05", "invoice", "250.00", "310.00"), + ("2026-10-12", "payment", "-60.00", "250.00"), + ("2026-10-20", "payment", "-100.00", "150.00"), + ] + assert (usd["invoiced"], usd["paid"], usd["cancelled"]) == ( + "250.00", + "160.00", + "0.00", + ) + assert usd["closing_balance"] == "150.00" + + def test_entries_say_what_they_are(self, admin_client, account): + invoice = _invoice(account, "250.00", datetime.date(2026, 10, 5), title="Build") + payment = _pay(invoice, "100.00", datetime.date(2026, 10, 20)) + Payment.objects.filter(pk=payment.pk).update(reference_number="TX-9") + + entries = _sections(admin_client.get(_url(account.id)))["USD"]["entries"] + + assert [(e["invoice_id"], e["invoice_number"]) for e in entries] == [ + (str(invoice.id), invoice.invoice_number) + ] * 2 + assert [e["description"] for e in entries] == [ + "Build", + "Payment (Bank Transfer, ref TX-9)", + ] + + def test_drafts_and_pending_invoices_were_never_billed(self, admin_client, account): + _invoice(account, "500.00", datetime.date(2026, 10, 7), status="Draft") + _invoice(account, "70.00", datetime.date(2026, 9, 7), status="Pending") + assert _sections(admin_client.get(_url(account.id))) == {} + + def test_other_accounts_are_left_off(self, admin_client, account, org_a): + other = Account.objects.create(name="Other", org=org_a) + _invoice(other, "90.00", datetime.date(2026, 10, 3)) + assert _sections(admin_client.get(_url(account.id))) == {} + + def test_currencies_are_never_added_together(self, admin_client, account): + _invoice(account, "100.00", datetime.date(2026, 10, 3)) + _invoice(account, "80.00", datetime.date(2026, 10, 4), currency="EUR") + sections = _sections(admin_client.get(_url(account.id))) + assert sorted(sections) == ["EUR", "USD"] + assert sections["USD"]["closing_balance"] == "100.00" + assert sections["EUR"]["closing_balance"] == "80.00" + + def test_a_currency_is_shown_while_it_has_a_balance(self, admin_client, account): + settled = _invoice(account, "80.00", datetime.date(2026, 9, 4), currency="EUR") + _pay(settled, "80.00", datetime.date(2026, 9, 9)) + _invoice(account, "50.00", datetime.date(2026, 9, 6), currency="GBP") + + sections = _sections(admin_client.get(_url(account.id))) + + # EUR was settled before October and nothing happened in it since. + assert sorted(sections) == ["GBP"] + gbp = sections["GBP"] + assert (gbp["opening_balance"], gbp["closing_balance"]) == ("50.00", "50.00") + assert gbp["entries"] == [] + + +class TestCancelledInvoices: + def test_a_sent_invoice_is_reversed_on_the_day_it_was_cancelled( + self, admin_client, account + ): + _invoice( + account, + "100.00", + datetime.date(2026, 9, 15), + status="Cancelled", + sent_at=_noon(datetime.date(2026, 9, 15)), + cancelled_at=_noon(datetime.date(2026, 10, 10)), + ) + + september = _sections(admin_client.get(_url(account.id, SEPTEMBER)))["USD"] + october = _sections(admin_client.get(_url(account.id)))["USD"] + + # September still closes on what it showed the customer at the time. + assert _rows(september) == [("2026-09-15", "invoice", "100.00", "100.00")] + assert october["opening_balance"] == september["closing_balance"] + assert _rows(october) == [("2026-10-10", "cancellation", "-100.00", "0.00")] + assert october["entries"][0]["description"] == "Invoice cancelled" + assert october["cancelled"] == "100.00" + + def test_cancelling_after_a_part_payment_leaves_the_account_in_credit( + self, admin_client, account + ): + invoice = _invoice(account, "100.00", datetime.date(2026, 10, 2)) + _pay(invoice, "40.00", datetime.date(2026, 10, 4)) + Invoice.objects.filter(pk=invoice.pk).update( + status="Cancelled", cancelled_at=_noon(datetime.date(2026, 10, 8)) + ) + + usd = _sections(admin_client.get(_url(account.id)))["USD"] + + assert _rows(usd) == [ + ("2026-10-02", "invoice", "100.00", "100.00"), + ("2026-10-04", "payment", "-40.00", "60.00"), + ("2026-10-08", "cancellation", "-100.00", "-40.00"), + ] + assert usd["closing_balance"] == "-40.00" + + def test_one_cancelled_before_anyone_saw_it_was_never_billed( + self, admin_client, account + ): + _invoice( + account, + "100.00", + datetime.date(2026, 10, 2), + status="Cancelled", + cancelled_at=_noon(datetime.date(2026, 10, 3)), + ) + assert _sections(admin_client.get(_url(account.id))) == {} + + +class TestPeriod: + def test_defaults_to_this_month_so_far(self, admin_client, account): + today = timezone.localdate() + body = admin_client.get(f"/api/invoices/statements/{account.id}/").json() + assert body["start_date"] == today.replace(day=1).isoformat() + assert body["end_date"] == today.isoformat() + + @pytest.mark.parametrize("pdf", [False, True], ids=["json", "pdf"]) + def test_a_malformed_date_is_refused(self, admin_client, account, pdf): + response = admin_client.get( + _url(account.id, "start_date=10/01/2026&end_date=2026-10-31", pdf=pdf) + ) + assert response.status_code == 400 + assert list(response.json()) == ["start_date"] + + def test_an_end_before_the_start_is_refused(self, admin_client, account): + response = admin_client.get( + _url(account.id, "start_date=2026-10-31&end_date=2026-10-01") + ) + assert response.status_code == 400 + assert list(response.json()) == ["end_date"] + + def test_a_period_of_366_days_is_allowed(self, admin_client, account): + response = admin_client.get( + _url(account.id, "start_date=2026-01-01&end_date=2027-01-01") + ) + assert response.status_code == 200, response.content + + def test_a_longer_period_is_refused(self, admin_client, account): + response = admin_client.get( + _url(account.id, "start_date=2026-01-01&end_date=2027-01-02") + ) + assert response.status_code == 400 + assert response.json()["end_date"] == [ + "A statement can cover at most 366 days." + ] + + +class TestPDF: + def test_renders_a_pdf_named_for_the_period(self, admin_client, account): + _invoice(account, "250.00", datetime.date(2026, 10, 5)) + + response = admin_client.get(_url(account.id, pdf=True)) + + assert response.status_code == 200 + assert response["Content-Type"] == "application/pdf" + assert response["Content-Disposition"] == ( + 'attachment; filename="Statement_2026-10-01_2026-10-31.pdf"' + ) + assert response.content.startswith(b"%PDF") + + def test_the_pdf_shows_the_balances_and_escapes_what_members_wrote( + self, admin_client, org_a + ): + account = Account.objects.create(name="Acme", org=org_a) + earlier = _invoice(account, "100.00", datetime.date(2026, 9, 10)) + _pay(earlier, "40.00", datetime.date(2026, 9, 20)) + october = _invoice( + account, "250.00", datetime.date(2026, 10, 5), title="Build" + ) + _pay(october, "100.00", datetime.date(2026, 10, 20)) + + with patch("invoices.pdf.HTML") as html: + response = admin_client.get(_url(account.id, pdf=True)) + + assert response.status_code == 200 + rendered = html.call_args.kwargs["string"] + assert "<b>Acme</b>" in rendered + assert "<i>Build</i>" in rendered + assert "Acme" not in rendered and "Build" not in rendered + assert "$60.00" in rendered # opening balance + assert "$210.00" in rendered # closing balance + # A payment takes money off: the sign goes before the symbol. + assert "-$100.00" in rendered + assert "$-" not in rendered diff --git a/backend/pyproject.toml b/backend/pyproject.toml index eb7dfb66..d1325f1a 100644 --- a/backend/pyproject.toml +++ b/backend/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "hatchling.build" [project] name = "django-crm" -version = "1.14.12" +version = "1.15.0" # The one-line summary PyPI shows under the project title and in search results, # so it carries the terms people actually search for ("open source CRM", # "self-hosted CRM", "Django CRM") and names the modules rather than the diff --git a/backend/uv.lock b/backend/uv.lock index f275e8de..d175c127 100644 --- a/backend/uv.lock +++ b/backend/uv.lock @@ -681,7 +681,7 @@ wheels = [ [[package]] name = "django-crm" -version = "1.14.12" +version = "1.15.0" source = { editable = "." } dependencies = [ { name = "cairocffi" }, diff --git a/docs/api/endpoint-index.md b/docs/api/endpoint-index.md index 8265ef52..8565ee17 100644 --- a/docs/api/endpoint-index.md +++ b/docs/api/endpoint-index.md @@ -143,6 +143,8 @@ Interactive versions of the same schema are served by a running backend at | `/api/invoices/reports/aging/` | GET | | `/api/invoices/reports/dashboard/` | GET | | `/api/invoices/reports/revenue/` | GET | +| `/api/invoices/statements/{account_id}/` | GET | +| `/api/invoices/statements/{account_id}/pdf/` | GET | | `/api/invoices/templates/` | GET, POST | | `/api/invoices/templates/{id}/` | DELETE, GET, PUT | | `/api/invoices/templates/{id}/editor/` | GET | diff --git a/docs/api/invoices.md b/docs/api/invoices.md index 10ae1135..feca92a8 100644 --- a/docs/api/invoices.md +++ b/docs/api/invoices.md @@ -9,8 +9,8 @@ is centralized in `backend/invoices/permissions.py`. See [Conventions](conventio filtering and response-shape rules assumed rather than repeated here, and [Errors](errors.md) for the 404-vs-403 principle this page's own module docstring states almost verbatim. -This page covers invoices, estimates, line items and the public portal, the endpoints this -documentation task scopes. Payments, products, templates, recurring invoices, dashboards/reports, and +This page covers invoices, estimates, line items, account statements and the public portal, the +endpoints this documentation task scopes. Payments, products, templates, recurring invoices, dashboards/reports, and invoice-from-opportunity/from-time-entries are also part of this module (`api_urls.py`) but are out of scope for this page. @@ -229,6 +229,39 @@ parent-serializer-level check `InvoiceCreateSerializer` has. The same RLS caveat correctly-configured (non-superuser) database role, and a real cross-tenant read under the default, superuser one. +## Account statements + +| Method | Path | Notes | +| --- | --- | --- | +| GET | `/api/invoices/statements/{account_id}/` | The statement as JSON | +| GET | `/api/invoices/statements/{account_id}/pdf/` | The same statement as a PDF, `Statement__.pdf` | + +What one account was billed and paid over a period (issue #810). Computed on every request from the +invoices and payments on record (`backend/invoices/statements.py`), never stored, so it cannot +disagree with them. + +**Admin-only.** A member gets `403` before the account is looked up, so the answer says nothing about +which accounts exist. The rule is the invoice reports' (`_forbid_non_admin_reports`): a statement sums +every invoice on the account, including ones a member may not open, and one built from only the +invoices a member can see would show the customer a wrong balance. An account in another org is `404`. + +**Period.** `start_date` and `end_date` (`YYYY-MM-DD`, both included) default to this month so far, in +the org's day. A period longer than 366 days, or one that ends before it starts, is a `400` with the +DRF field shape (`{"end_date": ["..."]}`). + +**Shape.** One entry in `currencies` per currency, ordered by code, since nothing converts between +them: `opening_balance`, the period's `invoiced`, `paid` and `cancelled` totals, `closing_balance`, +and `entries` in date order. Each entry has `date`, `kind` (`invoice`, `payment` or `cancellation`), +`invoice_id`, `invoice_number`, `description`, a signed `amount` (positive adds to what the account +owes) and the running `balance`. A negative balance means the account is in credit. A currency with no +opening balance and nothing in the period is left out. + +**What counts.** An invoice is on the statement once its customer was asked to pay: Draft and Pending +are left off. A cancelled invoice stays on if it was sent or paid toward, billed on its issue date and +reversed on the day it was cancelled, so an earlier month's statement still closes on the balance it +showed then, and a payment it took leaves the account in credit. A cancelled invoice nobody was sent +or paid was never billed, and is left off. + ## Public portal endpoints **Mounted at `/api/public/...`, not under `/api/invoices/...`**: `backend/crm/urls.py:23`: diff --git a/frontend/src/lib/server/v2/statements.js b/frontend/src/lib/server/v2/statements.js new file mode 100644 index 00000000..927bf913 --- /dev/null +++ b/frontend/src/lib/server/v2/statements.js @@ -0,0 +1,158 @@ +/** + * Account statements (#810): what one account was billed and paid over a + * period, from `GET /api/invoices/statements//` and its `pdf/` twin. + * + * Per currency the API sends an opening balance, the period's invoices, + * payments and cancellations in date order with a running balance, and a + * closing balance. It does all the arithmetic; nothing here adds money up. + * + * Admin-only on the backend, like the invoice reports: a statement sums every + * invoice on the account, including ones a member may not open. A member's 403 + * comes back as `can_view: false` so the page can say so. The account page + * only offers the link to admins, but that is courtesy, not the control. + */ +import { error } from '@sveltejs/kit'; +import { env } from '$env/dynamic/public'; +import { apiRequest } from '$lib/api-helpers.js'; +import { readableError } from '$lib/server/v2/form-errors.js'; + +const num = (/** @type {any} */ value) => { + const n = Number(value); + return Number.isFinite(n) ? n : 0; +}; + +/** + * The API query for the period in the page's own URL: `start_date` and + * `end_date`, blanks left out so the API's default (this month so far) applies. + * + * @param {URLSearchParams} searchParams + */ +export function statementQuery(searchParams) { + const query = new URLSearchParams(); + for (const name of ['start_date', 'end_date']) { + const value = searchParams.get(name)?.trim(); + if (value) query.set(name, value); + } + const qs = query.toString(); + return qs ? `?${qs}` : ''; +} + +/** + * The whole calendar month before the one `iso` falls in, as the period the + * page links to. Statements are read a month at a time, and stepping back by + * a link beats two date pickers on a phone. + * + * @param {string} iso YYYY-MM-DD + */ +export function previousMonth(iso) { + const [y, m] = iso.split('-').map(Number); + const year = m === 1 ? y - 1 : y; + const month = m === 1 ? 12 : m - 1; + // Day 0 of the next month is this month's last day; `month` is 1-based, + // which is the next month to `Date.UTC`'s 0-based count. + const last = new Date(Date.UTC(year, month, 0)).getUTCDate(); + const mm = String(month).padStart(2, '0'); + return { start_date: `${year}-${mm}-01`, end_date: `${year}-${mm}-${last}` }; +} + +/** @param {any} section */ +function toSection(section) { + return { + currency: section.currency, + opening_balance: num(section.opening_balance), + invoiced: num(section.invoiced), + paid: num(section.paid), + cancelled: num(section.cancelled), + closing_balance: num(section.closing_balance), + entries: (section.entries ?? []).map((/** @type {any} */ entry) => ({ + date: entry.date, + kind: entry.kind, + invoice_id: entry.invoice_id, + invoice_number: entry.invoice_number ?? '', + description: entry.description ?? '', + amount: num(entry.amount), + balance: num(entry.balance) + })) + }; +} + +/** + * `{ can_view, statement, error }`. `statement` is null when the caller is not + * an admin (`can_view: false`) or the period was refused (`error` says why). + * + * @param {{ cookies: import('@sveltejs/kit').Cookies }} event + * @param {string} accountId + * @param {URLSearchParams} searchParams the page's own query string + */ +export async function getStatement({ cookies }, accountId, searchParams) { + let body; + try { + body = await apiRequest( + `/invoices/statements/${accountId}/${statementQuery(searchParams)}`, + {}, + { cookies } + ); + } catch (/** @type {any} */ err) { + if (err?.status === 403) return { can_view: false, statement: null, error: null }; + if (err?.status === 404) { + error(404, 'That account does not exist, or you do not have access to it.'); + } + if (err?.status === 400) { + // `{"end_date": ["..."]}`: the sentence alone, the field is on the form. + const said = Object.values(err.body ?? {}) + .flat() + .find((m) => typeof m === 'string'); + return { + can_view: true, + statement: null, + error: said ?? readableError(err, 'Those dates do not make a period.') + }; + } + throw err; + } + + return { + can_view: true, + error: null, + statement: { + account: { id: body.account?.id ?? accountId, name: body.account?.name ?? '' }, + start_date: body.start_date, + end_date: body.end_date, + currencies: (body.currencies ?? []).map(toSection) + } + }; +} + +/** + * Stream the statement PDF for `/accounts//statement/pdf?`. + * + * The access token is an httpOnly cookie that a plain link cannot attach, so + * this carries it. It never gates: the API decides, and a refusal is passed on + * as a refusal rather than as a file. + * + * @param {{ cookies: import('@sveltejs/kit').Cookies, params: { id: string }, url: URL, request: Request }} event + */ +export async function forwardStatementPdf({ cookies, params, url, request }) { + const accessToken = cookies.get('jwt_access'); + if (!accessToken) return new Response('Unauthorized', { status: 401 }); + + const upstream = await fetch( + `${env.PUBLIC_DJANGO_API_URL}/api/invoices/statements/${params.id}/pdf/${statementQuery(url.searchParams)}`, + { headers: { Authorization: `Bearer ${accessToken}` }, signal: request.signal } + ); + + if (!upstream.ok || !upstream.body) { + return new Response(`Upstream error: ${upstream.status}`, { + status: upstream.status || 502 + }); + } + + return new Response(upstream.body, { + status: 200, + headers: { + 'Content-Type': 'application/pdf', + 'Content-Disposition': + upstream.headers.get('Content-Disposition') ?? 'attachment; filename="statement.pdf"' + } + }); +} diff --git a/frontend/src/lib/server/v2/statements.test.js b/frontend/src/lib/server/v2/statements.test.js new file mode 100644 index 00000000..6cf0cb3c --- /dev/null +++ b/frontend/src/lib/server/v2/statements.test.js @@ -0,0 +1,204 @@ +/** + * Account statements (#810): the page asks for the period in its own URL, a + * member's 403 becomes the "admins only" state, a refused period shows the + * API's sentence, and the PDF streams through with the caller's own token. + */ +import { describe, it, expect, vi, beforeEach } from 'vitest'; + +vi.mock('$env/dynamic/public', () => ({ + env: { PUBLIC_DJANGO_API_URL: 'http://api.test' } +})); +const apiRequest = vi.fn(); +vi.mock('$lib/api-helpers.js', () => ({ apiRequest: (...a) => apiRequest(...a) })); + +const { statementQuery, previousMonth, getStatement, forwardStatementPdf } = + await import('./statements.js'); + +const ACCOUNT = '11111111-2222-3333-4444-555555555555'; +const OCTOBER = 'start_date=2026-10-01&end_date=2026-10-31'; +const cookies = /** @type {any} */ ({ get: () => 'tok' }); + +/** What `apiRequest` throws: the status and the parsed body travel with it. */ +const refusal = (/** @type {number} */ status, /** @type {any} */ body = {}) => + Object.assign(new Error(`HTTP ${status}`), { status, body }); + +describe('statementQuery', () => { + it('keeps the two dates and nothing else', () => { + const params = new URLSearchParams(`${OCTOBER}&limit=5&org=x`); + expect(statementQuery(params)).toBe(`?${OCTOBER}`); + }); + + it('leaves blank dates out, so the API default applies', () => { + expect(statementQuery(new URLSearchParams('start_date=&end_date=2026-10-31'))).toBe( + '?end_date=2026-10-31' + ); + expect(statementQuery(new URLSearchParams())).toBe(''); + }); +}); + +describe('previousMonth', () => { + it('is the whole calendar month before the one a date falls in', () => { + expect(previousMonth('2026-10-15')).toEqual({ + start_date: '2026-09-01', + end_date: '2026-09-30' + }); + }); + + it('crosses a year and knows a leap February', () => { + expect(previousMonth('2026-01-05')).toEqual({ + start_date: '2025-12-01', + end_date: '2025-12-31' + }); + expect(previousMonth('2024-03-31')).toEqual({ + start_date: '2024-02-01', + end_date: '2024-02-29' + }); + }); +}); + +describe('getStatement', () => { + beforeEach(() => { + apiRequest.mockReset(); + }); + + it('asks for the account and period, and reads money as numbers', async () => { + apiRequest.mockResolvedValue({ + account: { id: ACCOUNT, name: 'Acme' }, + start_date: '2026-10-01', + end_date: '2026-10-31', + currencies: [ + { + currency: 'USD', + opening_balance: '60.00', + invoiced: '250.00', + paid: '160.00', + cancelled: '0.00', + closing_balance: '150.00', + entries: [ + { + date: '2026-10-05', + kind: 'invoice', + invoice_id: 'inv-1', + invoice_number: 'INV-1', + description: 'Build', + amount: '250.00', + balance: '310.00' + }, + { + date: '2026-10-12', + kind: 'payment', + invoice_id: 'inv-1', + invoice_number: 'INV-1', + description: 'Payment (Bank Transfer)', + amount: '-100.00', + balance: '210.00' + } + ] + } + ] + }); + + const result = await getStatement({ cookies }, ACCOUNT, new URLSearchParams(OCTOBER)); + + expect(apiRequest.mock.calls[0][0]).toBe(`/invoices/statements/${ACCOUNT}/?${OCTOBER}`); + expect(result.can_view).toBe(true); + expect(result.error).toBeNull(); + const usd = result.statement.currencies[0]; + expect(usd).toMatchObject({ + currency: 'USD', + opening_balance: 60, + invoiced: 250, + paid: 160, + cancelled: 0, + closing_balance: 150 + }); + expect(usd.entries.map((/** @type {any} */ e) => [e.kind, e.amount, e.balance])).toEqual([ + ['invoice', 250, 310], + ['payment', -100, 210] + ]); + }); + + it('tells a member it is for admins rather than failing', async () => { + apiRequest.mockRejectedValue(refusal(403, { error: true, message: 'Only an administrator' })); + const result = await getStatement({ cookies }, ACCOUNT, new URLSearchParams()); + expect(result).toEqual({ can_view: false, statement: null, error: null }); + }); + + it("shows the API's reason for refusing a period", async () => { + apiRequest.mockRejectedValue( + refusal(400, { end_date: ['A statement can cover at most 366 days.'] }) + ); + const result = await getStatement({ cookies }, ACCOUNT, new URLSearchParams(OCTOBER)); + expect(result).toEqual({ + can_view: true, + statement: null, + error: 'A statement can cover at most 366 days.' + }); + }); + + it('answers a missing account with a 404', async () => { + apiRequest.mockRejectedValue(refusal(404, { error: true, message: 'Account not found' })); + await expect(getStatement({ cookies }, ACCOUNT, new URLSearchParams())).rejects.toMatchObject({ + status: 404 + }); + }); + + it('lets any other failure through', async () => { + const boom = refusal(500); + apiRequest.mockRejectedValue(boom); + await expect(getStatement({ cookies }, ACCOUNT, new URLSearchParams())).rejects.toBe(boom); + }); +}); + +describe('forwardStatementPdf', () => { + /** @type {import('vitest').Mock} */ + let fetchMock; + + beforeEach(() => { + fetchMock = vi.fn( + async () => + new Response('%PDF-1.7', { + status: 200, + headers: { + 'Content-Type': 'application/pdf', + 'Content-Disposition': 'attachment; filename="Statement_2026-10-01_2026-10-31.pdf"' + } + }) + ); + vi.stubGlobal('fetch', fetchMock); + }); + + const event = (/** @type {Record} */ jar) => + /** @type {any} */ ({ + cookies: { get: (/** @type {string} */ k) => jar[k] }, + params: { id: ACCOUNT }, + url: new URL(`http://app.test/accounts/${ACCOUNT}/statement/pdf?${OCTOBER}&limit=9`), + request: new Request('http://app.test/') + }); + + it('refuses without a session and never calls the API', async () => { + const res = await forwardStatementPdf(event({})); + expect(res.status).toBe(401); + expect(fetchMock).not.toHaveBeenCalled(); + }); + + it("sends the caller's token and the period, and passes the PDF through", async () => { + const res = await forwardStatementPdf(event({ jwt_access: 'tok' })); + const [url, init] = fetchMock.mock.calls[0]; + expect(url).toBe(`http://api.test/api/invoices/statements/${ACCOUNT}/pdf/?${OCTOBER}`); + expect(init.headers).toEqual({ Authorization: 'Bearer tok' }); + expect(res.status).toBe(200); + expect(res.headers.get('Content-Type')).toBe('application/pdf'); + expect(res.headers.get('Content-Disposition')).toBe( + 'attachment; filename="Statement_2026-10-01_2026-10-31.pdf"' + ); + expect(await res.text()).toBe('%PDF-1.7'); + }); + + it('passes a refusal through as a refusal, never as a PDF', async () => { + fetchMock.mockResolvedValueOnce(new Response('{}', { status: 403 })); + const res = await forwardStatementPdf(event({ jwt_access: 'tok' })); + expect(res.status).toBe(403); + expect(res.headers.get('Content-Type')).not.toBe('application/pdf'); + }); +}); diff --git a/frontend/src/routes/(app)/accounts/[id]/+page.svelte b/frontend/src/routes/(app)/accounts/[id]/+page.svelte index 49dea2a6..c78f59ff 100644 --- a/frontend/src/routes/(app)/accounts/[id]/+page.svelte +++ b/frontend/src/routes/(app)/accounts/[id]/+page.svelte @@ -19,6 +19,7 @@ import DuplicatesPanel from '$lib/v2/components/DuplicatesPanel.svelte'; import ConfirmAction from '$lib/v2/components/ConfirmAction.svelte'; import { money, moneyEach, shortDate, longDate } from '$lib/v2/format.js'; + import { isOrgAdmin } from '$lib/admin.js'; import { CLOSED_KINDS, PRIORITY_TONE, @@ -75,6 +76,10 @@ .join(' · ')} {/snippet} {#snippet actions()} + {#if isOrgAdmin(data)} + + Statement + {/if} Edit {#if data.canDelete}