Merge pull request #839 from Django-CRM/dev

feat(invoices): account statements with PDF on web and mobile (#810)
This commit is contained in:
Ashwin Kumar 2026-10-15 18:46:12 +05:30 committed by GitHub
commit 0cd9afac22
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
27 changed files with 2666 additions and 78 deletions

View file

@ -163,6 +163,17 @@ urlpatterns = [
api_views.AgingReportView.as_view(),
name="reports_aging",
),
# Account statements (admin-only, like the reports)
path(
"statements/<uuid:account_id>/",
api_views.AccountStatementView.as_view(),
name="account_statement",
),
path(
"statements/<uuid:account_id>/pdf/",
api_views.AccountStatementPDFView.as_view(),
name="account_statement_pdf",
),
# ==========================================================================
# INVOICE FROM OPPORTUNITY
# ==========================================================================

View file

@ -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,

View file

@ -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"

View file

@ -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)

View file

@ -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,
}

View file

@ -0,0 +1,164 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Statement for {{ account.name }}</title>
<style>
.statement-currency { margin: 24px 0 8px; font-size: 15px; font-weight: 700; color: #222; }
/* A wrapped amount strands its minus sign on a line of its own. */
.statement-table td.date-col,
.statement-table td.price-col,
.statement-table td.total-col,
.totals-table .totals-label { white-space: nowrap; }
.statement-table .desc-col { width: 40%; }
.statement-table .opening td { color: #555; font-style: italic; }
.totals-table .credit .totals-value { color: #16a34a; }
</style>
</head>
<body>
<div class="invoice-container">
<header class="header">
<div class="company-details">
<h1>{{ org.company_name|default:org.name }}</h1>
{% if org.company_name and org.name and org.company_name != org.name %}
<p>{{ org.name }}</p>
{% endif %}
{% if org.address_line %}
<p>{{ org.address_line }}</p>
{% endif %}
{% if org.city or org.state or org.postcode %}
<p>
{% 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 %}
</p>
{% endif %}
{% if org.phone %}
<p>Tel: {{ org.phone }}</p>
{% endif %}
{% if org.email %}
<p>Email: {{ org.email }}</p>
{% endif %}
</div>
<div class="invoice-branding">
<div class="invoice-title">Statement</div>
{% if org.logo %}
<div class="logo-container">
<img src="{{ org.logo.url }}" alt="{{ org.name }}" class="logo">
</div>
{% else %}
<div class="logo-container">
<span class="logo-text">{{ org.company_name|default:org.name|slice:":4"|upper }}</span>
</div>
{% endif %}
</div>
</header>
<section class="info-section">
<div class="client-address">
<h3>{{ account.name }}</h3>
{% if account.address_line %}
<p>{{ account.address_line }}</p>
{% endif %}
{% if account.city or account.state or account.postcode %}
<p>
{% 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 %}
</p>
{% endif %}
{% if account.country %}
<p>{{ account.get_country_display }}</p>
{% endif %}
</div>
<div class="invoice-meta">
<div class="meta-row">
<span class="meta-label">From:</span>
<span class="meta-value">{{ start_date|date:"F d, Y" }}</span>
</div>
<div class="meta-row">
<span class="meta-label">To:</span>
<span class="meta-value">{{ end_date|date:"F d, Y" }}</span>
</div>
<div class="meta-row">
<span class="meta-label">Issued:</span>
<span class="meta-value">{% now "F d, Y" %}</span>
</div>
</div>
</section>
{% for section in sections %}
{% if sections|length > 1 %}
<div class="statement-currency">Amounts in {{ section.currency }}</div>
{% endif %}
<table class="line-items-table statement-table">
<thead>
<tr>
<th>Date</th>
<th>Invoice</th>
<th class="desc-col">Details</th>
<th class="price-col">Amount</th>
<th class="total-col">Balance</th>
</tr>
</thead>
<tbody>
<tr class="opening">
<td class="date-col">{{ start_date|date:"M d, Y" }}</td>
<td></td>
<td class="desc-col">Opening balance</td>
<td class="price-col"></td>
<td class="total-col">{{ section.opening_balance }}</td>
</tr>
{% for entry in section.entries %}
<tr>
<td class="date-col">{{ entry.date|date:"M d, Y" }}</td>
<td>{{ entry.invoice_number }}</td>
<td class="desc-col">{{ entry.description }}</td>
<td class="price-col">{{ entry.amount }}</td>
<td class="total-col">{{ entry.balance }}</td>
</tr>
{% endfor %}
</tbody>
</table>
<div class="totals-container">
<table class="totals-table">
<tbody>
<tr>
<td class="totals-label">Opening balance</td>
<td class="totals-value">{{ section.opening_balance }}</td>
</tr>
<tr>
<td class="totals-label">Invoiced</td>
<td class="totals-value">{{ section.invoiced }}</td>
</tr>
<tr>
<td class="totals-label">Payments</td>
<td class="totals-value paid">{{ section.paid }}</td>
</tr>
{% if section.has_cancelled %}
<tr>
<td class="totals-label">Cancelled</td>
<td class="totals-value">{{ section.cancelled }}</td>
</tr>
{% endif %}
<tr class="amount-due{% if section.in_credit %} credit{% endif %}">
<td class="totals-label">{% if section.in_credit %}In credit{% else %}Balance due{% endif %}</td>
<td class="totals-value">{{ section.closing_balance }}</td>
</tr>
</tbody>
</table>
</div>
{% empty %}
<p class="no-items">Nothing was billed or paid in this period, and nothing is owed.</p>
{% endfor %}
<div class="copyright">
{% if org.tax_id %}
<p>Tax ID: {{ org.tax_id }}</p>
{% endif %}
<p>{{ org.company_name|default:org.name }}</p>
</div>
</div>
</body>
</html>

View file

@ -0,0 +1,314 @@
"""Account statements: what one account was billed and paid over a period (#810).
`GET /api/invoices/statements/<account>/` 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="<b>Acme</b>", 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="<i>Build</i>"
)
_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 "&lt;b&gt;Acme&lt;/b&gt;" in rendered
assert "&lt;i&gt;Build&lt;/i&gt;" in rendered
assert "<b>Acme" not in rendered and "<i>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

View file

@ -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

View file

@ -681,7 +681,7 @@ wheels = [
[[package]]
name = "django-crm"
version = "1.14.12"
version = "1.15.0"
source = { editable = "." }
dependencies = [
{ name = "cairocffi" },

View file

@ -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 |

View file

@ -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_<start>_<end>.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`:

View file

@ -0,0 +1,158 @@
/**
* Account statements (#810): what one account was billed and paid over a
* period, from `GET /api/invoices/statements/<account>/` 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/<id>/statement/pdf?<period>`.
*
* 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"'
}
});
}

View file

@ -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<string, string>} */ 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');
});
});

View file

@ -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)}
<!-- Statements are admin-only on the API; a member would only be told so. -->
<a class="v2-btn" href={resolve(`/accounts/${account.id}/statement`)}>Statement</a>
{/if}
<a class="v2-btn" href={resolve(`/accounts/${account.id}/edit`)}>Edit</a>
{#if data.canDelete}
<!-- Offered only when the API's delete rule admits this caller; the

View file

@ -0,0 +1,24 @@
import { getStatement, previousMonth } from '$lib/server/v2/statements.js';
/**
* An account's statement for the period in the URL (`?start_date=&end_date=`),
* this month so far when there is none. See `$lib/server/v2/statements.js`.
*
* @type {import('./$types').PageServerLoad}
*/
export async function load({ cookies, params, url }) {
const result = await getStatement({ cookies }, params.id, url.searchParams);
// The form shows what was asked for, so a refused period can be corrected.
const period = result.statement
? { start_date: result.statement.start_date, end_date: result.statement.end_date }
: {
start_date: url.searchParams.get('start_date') ?? '',
end_date: url.searchParams.get('end_date') ?? ''
};
return {
...result,
accountId: params.id,
period,
previous: result.statement ? previousMonth(result.statement.start_date) : null
};
}

View file

@ -0,0 +1,246 @@
<script>
/**
* An account's statement (#810): per currency, the opening balance, the
* period's invoices, payments and cancellations with a running balance, and
* the closing balance.
*
* The API computes every figure, in the same order the PDF prints them; this
* page only lays them out. It is admin-only on the backend, and a member who
* reaches the URL gets a sentence saying so instead of numbers.
*
* On a phone each row is a card: the date leads, the amount sits in the
* corner, and the invoice, details and running balance wrap beneath.
*/
import { resolve } from '$app/paths';
import PageHeader from '$lib/v2/components/PageHeader.svelte';
import StatCard from '$lib/v2/components/StatCard.svelte';
import { money, shortDate, longDate } from '$lib/v2/format.js';
import { ChevronRight, Download } from '@lucide/svelte';
/** @type {{ data: any }} */
let { data } = $props();
let statement = $derived(data.statement);
/** The query string for a period, as the page and the PDF route read it. */
const query = (/** @type {{ start_date: string, end_date: string }} */ period) =>
`?start_date=${period.start_date}&end_date=${period.end_date}`;
</script>
<PageHeader title="Statement" record>
{#snippet crumb()}
<a href={resolve('/accounts')}>Accounts</a>
<ChevronRight size={12} />
<a href={resolve(`/accounts/${data.accountId}`)}>{statement?.account.name || 'Account'}</a>
{/snippet}
{#snippet sub()}
{#if statement}
{longDate(statement.start_date)} to {longDate(statement.end_date)}
{:else}
What the account was billed, paid and owes
{/if}
{/snippet}
{#snippet actions()}
{#if statement}
<a
class="v2-btn"
href={resolve(`/accounts/${data.accountId}/statement/pdf${query(statement)}`)}
target="_blank"
rel="noopener"
>
<Download size={14} /> Download PDF
</a>
{/if}
{/snippet}
</PageHeader>
<div class="v2-scroll">
<div class="v2-pad" style="padding-bottom:32px">
{#if !data.can_view}
<div class="v2-card stmt-note">
<strong>Statements are for administrators.</strong>
<p>
A statement adds up every invoice on the account, including ones you may not open, so it
is limited to admins. The invoices you can open are on
<a href={resolve(`/accounts/${data.accountId}`)}>the account's page</a>.
</p>
</div>
{:else}
<form method="GET" class="stmt-period">
<div class="v2-field">
<label for="s-start">From</label>
<input
id="s-start"
name="start_date"
type="date"
class="v2-input"
value={data.period.start_date}
required
/>
</div>
<div class="v2-field">
<label for="s-end">To</label>
<input
id="s-end"
name="end_date"
type="date"
class="v2-input"
value={data.period.end_date}
required
/>
</div>
<button class="v2-btn v2-btn-primary">Show</button>
</form>
<div class="stmt-presets">
{#if data.previous}
<a href={resolve(`/accounts/${data.accountId}/statement${query(data.previous)}`)}
>Previous month</a
>
{/if}
<a href={resolve(`/accounts/${data.accountId}/statement`)}>This month</a>
</div>
{#if data.error}
<p class="v2-error" role="alert">{data.error}</p>
{/if}
{#if statement}
{#each statement.currencies as section (section.currency)}
{@const inCredit = section.closing_balance < 0}
<section class="stmt-section">
{#if statement.currencies.length > 1}
<h2 class="v2-label">In {section.currency}</h2>
{/if}
<div class="v2-stats" style="margin-bottom:12px">
<StatCard
label="Opening balance"
value={money(section.opening_balance, section.currency)}
tone="slate"
/>
<StatCard label="Invoiced" value={money(section.invoiced, section.currency)} />
<StatCard
label="Paid"
value={money(section.paid, section.currency)}
tone="moss"
detail={section.cancelled
? `${money(section.cancelled, section.currency)} cancelled`
: undefined}
/>
<StatCard
label={inCredit ? 'In credit' : 'Balance due'}
value={money(Math.abs(section.closing_balance), section.currency)}
tone={section.closing_balance > 0 ? 'rust' : 'moss'}
/>
</div>
<div class="v2-table-wrap" style="margin:0">
<table class="v2-table">
<thead>
<tr>
<th>Date</th>
<th>Invoice</th>
<th>Details</th>
<th class="v2-r">Amount</th>
<th class="v2-r">Balance</th>
</tr>
</thead>
<tbody>
<tr>
<td>{shortDate(statement.start_date)}</td>
<td data-m="hide"></td>
<td data-m="meta" class="v2-muted">Opening balance</td>
<td data-m="hide"></td>
<td class="v2-r v2-num" data-m="tag"
>{money(section.opening_balance, section.currency)}</td
>
</tr>
{#each section.entries as entry, i (i)}
<tr>
<td>{shortDate(entry.date)}</td>
<td data-m="meta">
<a
class="v2-num stmt-invoice"
href={resolve(`/invoices/${entry.invoice_id}`)}>{entry.invoice_number}</a
>
</td>
<td data-m="meta">{entry.description}</td>
<td
class="v2-r v2-num"
data-m="tag"
style={entry.amount < 0 ? 'color:var(--v2-moss)' : ''}
>
{money(entry.amount, section.currency)}
</td>
<td class="v2-r v2-num" data-m="meta" data-l="Balance"
>{money(entry.balance, section.currency)}</td
>
</tr>
{/each}
</tbody>
</table>
</div>
</section>
{:else}
<p class="v2-sub stmt-empty">
Nothing was billed or paid in this period, and nothing is owed.
</p>
{/each}
{/if}
{/if}
</div>
</div>
<style>
.stmt-period {
display: flex;
flex-wrap: wrap;
align-items: flex-end;
gap: 10px;
margin-top: 10px;
}
.stmt-period .v2-field {
flex: 1 1 140px;
max-width: 200px;
margin-bottom: 0;
}
.stmt-presets {
display: flex;
gap: 16px;
margin: 10px 0 4px;
font-size: 12.5px;
}
.stmt-section {
margin-top: 18px;
}
.stmt-section h2 {
margin: 0 0 8px;
}
.stmt-empty {
margin-top: 18px;
}
.stmt-note {
padding: 16px 18px;
}
.stmt-note p {
margin: 6px 0 0;
font-size: 13px;
}
@media (max-width: 768px) {
.stmt-period .v2-field {
max-width: none;
}
.stmt-period .v2-input,
.stmt-period .v2-btn {
min-height: 44px;
}
.stmt-presets a {
padding: 12px 0;
}
/* The whole card opens the invoice: the number alone is a 17px target.
The row is `position: relative` at this width (`v2.css`). */
.stmt-invoice::after {
content: '';
position: absolute;
inset: 0;
}
}
</style>

View file

@ -0,0 +1,11 @@
import { forwardStatementPdf } from '$lib/server/v2/statements.js';
/**
* The statement as a PDF, for the period in the query string. The API decides
* who may have it; `forwardStatementPdf` has the why.
*
* @type {import('./$types').RequestHandler}
*/
export function GET(event) {
return forwardStatementPdf(event);
}

View file

@ -19,6 +19,7 @@ On 2026-09-26 the counts were 90 `+page.svelte` files under `frontend/src/routes
| ID | Gap | Missing on | Backend | Opened | Notes |
|---|---|---|---|---|---|
| B10 | Download an invoice's PDF | Mobile | `GET /api/invoices/{id}/pdf/` exists | 2026-10-15 | Found while building account statements (#810). The web's invoice page has Download PDF (`routes/(app)/invoices/[id]/pdf/+server.js`); the phone's invoice detail has no PDF action. The statement screen already saves its PDF through `downloadAttachment`, which is the pattern to reuse. |
## Web-only by design

View file

@ -639,6 +639,33 @@ class ApiConfig {
'$apiBaseUrl/invoices/reports/dashboard/';
static String get invoiceReportAging => '$apiBaseUrl/invoices/reports/aging/';
/// An account's statement for a period, as figures and as a PDF. Admin-only
/// like the reports. Blank dates are left out, so the server's default (this
/// month so far, in the org's day) applies.
static String accountStatement(
String accountId, {
String? start,
String? end,
}) => _withPeriod('$apiBaseUrl/invoices/statements/$accountId/', start, end);
static String accountStatementPdf(
String accountId, {
String? start,
String? end,
}) => _withPeriod(
'$apiBaseUrl/invoices/statements/$accountId/pdf/',
start,
end,
);
static String _withPeriod(String url, String? start, String? end) {
final query = {
if (start != null && start.isNotEmpty) 'start_date': start,
if (end != null && end.isNotEmpty) 'end_date': end,
};
return query.isEmpty
? url
: Uri.parse(url).replace(queryParameters: query).toString();
}
/// Kanban boards. The list returns only boards you own or belong to, so an
/// empty list is an answer and not a permission failure: creating one makes
/// you its owner.

View file

@ -0,0 +1,137 @@
/// An account's statement (#810), from `GET /api/invoices/statements/<id>/`.
///
/// Per currency the server 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, and the web page and the PDF
/// show the same figures; nothing here adds money up.
///
/// **Admin-only on the server**, like the invoice reports: a statement sums
/// every invoice on the account, including ones a member may not open.
class AccountStatement {
const AccountStatement({
required this.accountId,
required this.accountName,
required this.startDate,
required this.endDate,
required this.sections,
});
final String accountId;
final String accountName;
/// The period, `YYYY-MM-DD`, both days included.
final String startDate;
final String endDate;
/// One per currency, ordered by code. Empty when nothing was billed or paid
/// in the period and nothing is owed.
final List<StatementSection> sections;
factory AccountStatement.fromJson(Map<String, dynamic> json) {
final account = json['account'] is Map ? json['account'] as Map : const {};
return AccountStatement(
accountId: '${account['id'] ?? ''}',
accountName: '${account['name'] ?? ''}',
startDate: '${json['start_date'] ?? ''}',
endDate: '${json['end_date'] ?? ''}',
sections: [
for (final section in (json['currencies'] as List? ?? const []))
if (section is Map<String, dynamic>)
StatementSection.fromJson(section),
],
);
}
}
/// The statement in one currency. Never added to another: there are no
/// exchange rates.
class StatementSection {
const StatementSection({
required this.currency,
required this.openingBalance,
required this.invoiced,
required this.paid,
required this.cancelled,
required this.closingBalance,
required this.entries,
});
final String currency;
final double openingBalance;
final double invoiced;
final double paid;
final double cancelled;
/// Negative when the account is in credit.
final double closingBalance;
final List<StatementEntry> entries;
factory StatementSection.fromJson(Map<String, dynamic> json) =>
StatementSection(
currency: '${json['currency'] ?? ''}',
openingBalance: _num(json['opening_balance']),
invoiced: _num(json['invoiced']),
paid: _num(json['paid']),
cancelled: _num(json['cancelled']),
closingBalance: _num(json['closing_balance']),
entries: [
for (final entry in (json['entries'] as List? ?? const []))
if (entry is Map<String, dynamic>) StatementEntry.fromJson(entry),
],
);
}
/// One line: an invoice billed, a payment, or a cancellation.
class StatementEntry {
const StatementEntry({
required this.date,
required this.kind,
required this.invoiceId,
required this.invoiceNumber,
required this.description,
required this.amount,
required this.balance,
});
/// `YYYY-MM-DD`.
final String date;
/// `invoice`, `payment` or `cancellation`.
final String kind;
final String invoiceId;
final String invoiceNumber;
final String description;
/// Signed: positive adds to what the account owes, negative takes from it.
final double amount;
/// What the account owes after this line.
final double balance;
factory StatementEntry.fromJson(Map<String, dynamic> json) => StatementEntry(
date: '${json['date'] ?? ''}',
kind: '${json['kind'] ?? ''}',
invoiceId: '${json['invoice_id'] ?? ''}',
invoiceNumber: '${json['invoice_number'] ?? ''}',
description: '${json['description'] ?? ''}',
amount: _num(json['amount']),
balance: _num(json['balance']),
);
}
/// The whole calendar month before the one [iso] (`YYYY-MM-DD`) falls in.
/// Statements are read a month at a time, and stepping back by a tap beats
/// two date pickers.
({String start, String end}) previousMonth(String iso) {
final day = DateTime.parse(iso);
final first = DateTime(day.year, day.month - 1, 1);
// Day 0 of the following month is this month's last day.
final last = DateTime(first.year, first.month + 1, 0);
String ymd(DateTime d) =>
'${d.year}-${d.month.toString().padLeft(2, '0')}-'
'${d.day.toString().padLeft(2, '0')}';
return (start: ymd(first), end: ymd(last));
}
double _num(Object? value) =>
value is num ? value.toDouble() : double.tryParse('$value') ?? 0;

View file

@ -0,0 +1,56 @@
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../config/api_config.dart';
import '../data/models/account_statement.dart';
import '../services/api_service.dart';
/// The account, and the period to show, or nulls for the server's default
/// (this month so far, in the org's day).
typedef StatementRequest = ({String accountId, String? start, String? end});
/// The server refused: 403 to a member (statements are admin-only), 400 for a
/// period it will not cover, 404 for an account this org does not have.
/// [message] is the server's own sentence.
class StatementRefusal implements Exception {
const StatementRefusal(this.statusCode, this.message);
final int statusCode;
final String message;
/// Retrying cannot turn this into a statement, so the screen offers none.
bool get forbidden => statusCode == 403;
@override
String toString() => message;
}
/// A refusal is never retried: Riverpod's default would ask again up to ten
/// times for an answer that cannot change. Anything else (offline, a 500)
/// keeps the default backoff.
Duration? _retry(int count, Object error) => error is StatementRefusal
? null
: ProviderContainer.defaultRetry(count, error);
final accountStatementProvider = FutureProvider.autoDispose
.family<AccountStatement, StatementRequest>(retry: _retry, (
ref,
request,
) async {
final response = await ApiService().get(
ApiConfig.accountStatement(
request.accountId,
start: request.start,
end: request.end,
),
);
if (response.success && response.data != null) {
return AccountStatement.fromJson(response.data!);
}
if (const {400, 403, 404}.contains(response.statusCode)) {
throw StatementRefusal(
response.statusCode,
response.message ?? 'Could not load the statement',
);
}
throw Exception(response.message ?? 'Could not load the statement');
});

View file

@ -14,6 +14,7 @@ import '../screens/auth/magic_link_email_screen.dart';
import '../screens/auth/magic_link_code_screen.dart';
import '../screens/accounts/account_detail_screen.dart';
import '../screens/accounts/account_form_screen.dart';
import '../screens/accounts/account_statement_screen.dart';
import '../screens/accounts/accounts_list_screen.dart';
import '../screens/auth/org_create_screen.dart';
import '../screens/contacts/contact_detail_screen.dart';
@ -134,6 +135,7 @@ class AppRoutes {
static const String accountCreate = '/accounts/create';
static const String accountDetail = '/accounts/:id';
static const String accountEdit = '/accounts/:id/edit';
static const String accountStatement = '/accounts/:id/statement';
static const String contacts = '/contacts';
static const String contactCreate = '/contacts/create';
static const String contactDetail = '/contacts/:id';
@ -426,6 +428,13 @@ final appRouterProvider = Provider<GoRouter>((ref) {
builder: (context, state) =>
AccountFormScreen(accountId: state.pathParameters['id']!),
),
GoRoute(
path: AppRoutes.accountStatement,
name: 'accountStatement',
parentNavigatorKey: _rootNavigatorKey,
builder: (context, state) =>
AccountStatementScreen(accountId: state.pathParameters['id']!),
),
// Registered after `create` and `:id/edit` so those literal segments are
// not swallowed by the `:id` parameter.
GoRoute(

View file

@ -8,6 +8,7 @@ import '../../core/theme/theme.dart';
import '../../data/models/account.dart';
import '../../data/models/deal.dart' show Currency;
import '../../providers/accounts_provider.dart';
import '../../providers/auth_provider.dart';
import '../../providers/duplicates_provider.dart';
import '../../routes/app_router.dart';
import '../../widgets/duplicates/duplicates_panel.dart';
@ -123,6 +124,15 @@ class _AccountDetailScreenState extends ConsumerState<AccountDetailScreen> {
onPressed: () => context.pop(),
),
actions: [
// Statements are admin-only on the server; a member would only be
// told so.
if (account != null && ref.watch(isOrgAdminProvider))
IconButton(
icon: const Icon(LucideIcons.receiptText, size: 20),
tooltip: 'Statement',
onPressed: () =>
context.push('${AppRoutes.accounts}/${account.id}/statement'),
),
if (account != null)
IconButton(
icon: const Icon(LucideIcons.edit3, size: 20),

View file

@ -0,0 +1,359 @@
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import 'package:intl/intl.dart';
import 'package:lucide_icons_flutter/lucide_icons.dart';
import '../../config/api_config.dart';
import '../../core/theme/theme.dart';
import '../../data/models/account_statement.dart';
import '../../data/models/deal.dart' show Currency;
import '../../providers/account_statement_provider.dart';
import '../../routes/app_router.dart';
import '../../services/attachment_upload.dart';
import '../invoices/invoice_format.dart';
import '../invoices/invoice_shell.dart';
/// An account's statement (#810): per currency, the opening balance, the
/// period's invoices, payments and cancellations with a running balance, and
/// the closing balance. The web page `/accounts/<id>/statement` and the PDF
/// show the same figures, all computed by the server.
///
/// **Admin-only on the server.** The account screen offers this only to
/// admins, and a member who reaches it anyway is told so, with no Retry: a
/// 403 does not become a 200 by asking again.
class AccountStatementScreen extends ConsumerStatefulWidget {
const AccountStatementScreen({super.key, required this.accountId});
final String accountId;
@override
ConsumerState<AccountStatementScreen> createState() =>
_AccountStatementScreenState();
}
class _AccountStatementScreenState
extends ConsumerState<AccountStatementScreen> {
// Null asks for the server's default: this month so far, in the org's day.
String? _start;
String? _end;
bool _saving = false;
StatementRequest get _request =>
(accountId: widget.accountId, start: _start, end: _end);
void _show(String? start, String? end) => setState(() {
_start = start;
_end = end;
});
Future<void> _pickPeriod(AccountStatement? shown) async {
final now = DateTime.now();
final current = shown == null
? null
: DateTimeRange(
start: DateTime.parse(shown.startDate),
end: DateTime.parse(shown.endDate),
);
final picked = await showDateRangePicker(
context: context,
firstDate: DateTime(2000),
lastDate: DateTime(now.year + 5),
initialDateRange: current,
);
if (picked == null) return;
// The server caps a period at 366 days and says so if this is longer.
_show(_ymd(picked.start), _ymd(picked.end));
}
Future<void> _savePdf(AccountStatement statement) async {
setState(() => _saving = true);
final result = await downloadAttachment(
url: ApiConfig.accountStatementPdf(
widget.accountId,
start: statement.startDate,
end: statement.endDate,
),
fileName: 'Statement_${statement.startDate}_${statement.endDate}.pdf',
);
if (!mounted) return;
setState(() => _saving = false);
if (!result.success) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text(result.error ?? 'Could not save the statement'),
backgroundColor: AppColors.danger600,
),
);
}
}
@override
Widget build(BuildContext context) {
final async = ref.watch(accountStatementProvider(_request));
final statement = async.value;
return Scaffold(
backgroundColor: AppColors.surfaceDim,
appBar: AppBar(
title: const Text('Statement'),
backgroundColor: AppColors.surface,
elevation: 0,
scrolledUnderElevation: 1,
leading: IconButton(
icon: const Icon(LucideIcons.chevronLeft),
onPressed: () => context.pop(),
),
actions: [
if (statement != null && !async.hasError)
IconButton(
icon: const Icon(LucideIcons.download, size: 20),
tooltip: 'Save PDF',
onPressed: _saving ? null : () => _savePdf(statement),
),
],
),
body: async.when(
loading: () => const Center(child: CircularProgressIndicator()),
error: (error, _) {
if (error is StatementRefusal && error.forbidden) {
return InvoiceErrorState(
message: 'Statements are for administrators',
detail: error.message,
);
}
if (error is StatementRefusal && error.statusCode == 404) {
return const InvoiceErrorState(
message:
'This account does not exist, or you do not have access to it',
);
}
if (error is StatementRefusal) {
// A period the server will not cover: say why, keep the controls.
return ListView(
padding: const EdgeInsets.only(bottom: 32),
children: [
_periodCard(null),
Padding(
padding: const EdgeInsets.fromLTRB(16, 12, 16, 0),
child: Text(
error.message,
style: AppTypography.body.copyWith(
color: AppColors.danger600,
),
),
),
],
);
}
return InvoiceErrorState(
message: 'Could not load the statement',
onRetry: () => ref.invalidate(accountStatementProvider(_request)),
);
},
data: (statement) => RefreshIndicator(
onRefresh: () async =>
ref.invalidate(accountStatementProvider(_request)),
child: ListView(
padding: const EdgeInsets.only(bottom: 32),
children: [
_periodCard(statement),
if (statement.sections.isEmpty)
Padding(
padding: const EdgeInsets.fromLTRB(16, 20, 16, 0),
child: Text(
'Nothing was billed or paid in this period, and nothing '
'is owed.',
style: AppTypography.body.copyWith(
color: AppColors.textSecondary,
),
),
),
for (final section in statement.sections) ...[
_summary(section, labelled: statement.sections.length > 1),
_entries(section),
],
],
),
),
),
);
}
/// The account, the period shown and the ways to change it. With no
/// statement (a refused period) it shows the dates that were asked for.
Widget _periodCard(AccountStatement? statement) {
final start = statement?.startDate ?? _start;
final end = statement?.endDate ?? _end;
return Container(
color: AppColors.surface,
padding: const EdgeInsets.fromLTRB(16, 14, 16, 8),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
if (statement != null && statement.accountName.isNotEmpty)
Text(
statement.accountName,
style: AppTypography.body.copyWith(fontWeight: FontWeight.w600),
),
if (start != null && end != null)
Text(
'${_day(start)} to ${_day(end)}',
style: AppTypography.caption.copyWith(
color: AppColors.textSecondary,
),
),
const SizedBox(height: 6),
Wrap(
spacing: 4,
runSpacing: 0,
crossAxisAlignment: WrapCrossAlignment.center,
children: [
OutlinedButton.icon(
icon: const Icon(LucideIcons.calendarRange, size: 16),
label: const Text('Change period'),
onPressed: () => _pickPeriod(statement),
),
if (start != null)
TextButton(
onPressed: () {
final previous = previousMonth(start);
_show(previous.start, previous.end);
},
child: const Text('Previous month'),
),
TextButton(
onPressed: () => _show(null, null),
child: const Text('This month'),
),
],
),
],
),
);
}
Widget _summary(StatementSection section, {required bool labelled}) {
final symbol = Currency.symbolFor(section.currency);
final inCredit = section.closingBalance < 0;
return Container(
margin: const EdgeInsets.only(top: 8),
color: AppColors.surface,
padding: const EdgeInsets.fromLTRB(16, 14, 16, 14),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
if (labelled)
Padding(
padding: const EdgeInsets.only(bottom: 8),
child: Text(
'In ${section.currency}',
style: AppTypography.caption.copyWith(
color: AppColors.textSecondary,
fontWeight: FontWeight.w600,
),
),
),
InvoiceFactRow(
label: 'Opening balance',
value: money(section.openingBalance, symbol),
),
InvoiceFactRow(
label: 'Invoiced',
value: money(section.invoiced, symbol),
),
InvoiceFactRow(label: 'Paid', value: money(section.paid, symbol)),
if (section.cancelled > 0)
InvoiceFactRow(
label: 'Cancelled',
value: money(section.cancelled, symbol),
),
const Divider(height: 18),
InvoiceFactRow(
label: inCredit ? 'In credit' : 'Balance due',
value: money(section.closingBalance.abs(), symbol),
),
],
),
);
}
/// One row per entry; tapping it opens the invoice it belongs to.
Widget _entries(StatementSection section) {
final symbol = Currency.symbolFor(section.currency);
return Container(
color: AppColors.surface,
child: Column(
children: [
for (final entry in section.entries)
InkWell(
onTap: () =>
context.push('${AppRoutes.invoices}/${entry.invoiceId}'),
child: Container(
constraints: const BoxConstraints(minHeight: 56),
padding: const EdgeInsets.fromLTRB(16, 10, 16, 10),
decoration: BoxDecoration(
border: Border(top: BorderSide(color: Colors.grey.shade200)),
),
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
_day(entry.date),
style: AppTypography.caption.copyWith(
color: AppColors.textSecondary,
),
),
Text(entry.description, style: AppTypography.body),
Text(
entry.invoiceNumber,
style: AppTypography.caption.copyWith(
color: AppColors.textTertiary,
),
),
],
),
),
const SizedBox(width: 12),
Column(
crossAxisAlignment: CrossAxisAlignment.end,
children: [
Text(
money(entry.amount, symbol),
style: AppTypography.body.copyWith(
fontWeight: FontWeight.w600,
color: entry.amount < 0
? AppColors.success600
: AppColors.textPrimary,
),
),
Text(
'Balance ${money(entry.balance, symbol)}',
style: AppTypography.caption.copyWith(
color: AppColors.textSecondary,
),
),
],
),
],
),
),
),
],
),
);
}
}
String _ymd(DateTime d) =>
'${d.year}-${d.month.toString().padLeft(2, '0')}-'
'${d.day.toString().padLeft(2, '0')}';
String _day(String iso) {
final day = DateTime.tryParse(iso);
return day == null ? iso : DateFormat('d MMM yyyy').format(day);
}

View file

@ -12,7 +12,10 @@ final _money = NumberFormat('#,##0.00');
final _wholeMoney = NumberFormat('#,##0');
/// An exact amount, for anything a person might reconcile against a bank line.
String money(double value, String symbol) => '$symbol${_money.format(value)}';
/// The sign leads ("-$40.00"): a statement's payments and credit balances are
/// negative, and "$-40.00" reads as a typo.
String money(double value, String symbol) =>
'${value < 0 ? '-' : ''}$symbol${_money.format(value.abs())}';
/// A shortened amount for header figures, where the magnitude is the point and
/// the cents are noise. An empty [symbol] is a deliberate caller choice, used

View file

@ -0,0 +1,246 @@
import 'dart:async';
import 'package:bottle_crm/data/models/account.dart';
import 'package:bottle_crm/data/models/account_statement.dart';
import 'package:bottle_crm/providers/account_statement_provider.dart';
import 'package:bottle_crm/providers/accounts_provider.dart';
import 'package:bottle_crm/providers/auth_provider.dart';
import 'package:bottle_crm/providers/duplicates_provider.dart';
import 'package:bottle_crm/screens/accounts/account_detail_screen.dart';
import 'package:bottle_crm/screens/accounts/account_statement_screen.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_test/flutter_test.dart';
/// The account statement screen (#810) at a 390px phone, and the account
/// screen's way into it, which only admins are offered.
const _usd = StatementSection(
currency: 'USD',
openingBalance: 60,
invoiced: 250,
paid: 100,
cancelled: 0,
closingBalance: 210,
entries: [
StatementEntry(
date: '2026-10-05',
kind: 'invoice',
invoiceId: 'inv-1',
invoiceNumber: 'INV-20261005-0001',
description: 'Website rebuild, phase two of the migration',
amount: 250,
balance: 310,
),
StatementEntry(
date: '2026-10-20',
kind: 'payment',
invoiceId: 'inv-1',
invoiceNumber: 'INV-20261005-0001',
description: 'Payment (Bank Transfer, ref TX-4471-ACME-OCTOBER)',
amount: -100,
balance: 210,
),
],
);
const _eur = StatementSection(
currency: 'EUR',
openingBalance: 0,
invoiced: 0,
paid: 40,
cancelled: 0,
closingBalance: -40,
entries: [
StatementEntry(
date: '2026-10-08',
kind: 'payment',
invoiceId: 'inv-2',
invoiceNumber: 'INV-20260902-0004',
description: 'Payment (Cash)',
amount: -40,
balance: -40,
),
],
);
const _october = AccountStatement(
accountId: 'a1',
accountName: 'Northwind Traders and Distribution',
startDate: '2026-10-01',
endDate: '2026-10-31',
sections: [_eur, _usd],
);
void _usePhone(WidgetTester tester, double textScale) {
tester.view.devicePixelRatio = 3.0;
tester.view.physicalSize = const Size(390 * 3, 844 * 3);
tester.platformDispatcher.textScaleFactorTestValue = textScale;
addTearDown(tester.view.resetPhysicalSize);
addTearDown(tester.view.resetDevicePixelRatio);
addTearDown(tester.platformDispatcher.clearTextScaleFactorTestValue);
}
class _NoDuplicates extends DuplicatesApi {
@override
Future<RecordDuplicates> forRecord(DuplicateModule module, String id) async =>
const RecordDuplicates();
}
class _Accounts extends AccountsNotifier {
@override
Future<AccountsListData> build() async => const AccountsListData();
@override
Future<Account?> getAccount(String id, {void Function()? onNotFound}) async =>
Account.fromJson({'id': id, 'name': 'Northwind'}, canDelete: false);
}
void main() {
/// Every period the screen asked for, in order.
late List<StatementRequest> asked;
Future<void> pump(
WidgetTester tester,
FutureOr<AccountStatement> Function(StatementRequest) answer, {
double textScale = 1.0,
}) async {
asked = [];
_usePhone(tester, textScale);
await tester.pumpWidget(
ProviderScope(
overrides: [
accountStatementProvider.overrideWith((ref, request) async {
asked.add(request);
return answer(request);
}),
],
child: const MaterialApp(home: AccountStatementScreen(accountId: 'a1')),
),
);
await tester.pumpAndSettle();
}
for (final scale in [1.0, 1.3]) {
testWidgets('lays out each currency at a phone width, text scale $scale', (
tester,
) async {
await pump(tester, (_) => _october, textScale: scale);
expect(tester.takeException(), isNull);
// First load asks for the server's default period.
expect(asked.first, (accountId: 'a1', start: null, end: null));
expect(find.text('1 Oct 2026 to 31 Oct 2026'), findsOneWidget);
expect(find.byTooltip('Save PDF'), findsOneWidget);
expect(find.text('In EUR'), findsOneWidget);
// A credit balance is said in words, not as a negative amount due.
expect(find.text('In credit'), findsOneWidget);
expect(find.text('€40.00'), findsWidgets);
// The list builds what is on screen; scroll to the USD half.
Future<void> reach(Finder finder) => tester.scrollUntilVisible(
finder,
200,
scrollable: find.byType(Scrollable).first,
);
await reach(find.text('In USD'));
await reach(find.text('Balance due'));
// A payment takes money off: the sign goes before the symbol.
await reach(find.text('-\$100.00'));
expect(tester.takeException(), isNull);
});
}
testWidgets('a member is told it is for admins, with no retry', (
tester,
) async {
await pump(
tester,
(_) => throw const StatementRefusal(
403,
'Only an administrator can view account statements.',
),
);
expect(find.text('Statements are for administrators'), findsOneWidget);
expect(find.text('Retry'), findsNothing);
expect(find.byTooltip('Save PDF'), findsNothing);
});
testWidgets('a refused period says why and keeps the period controls', (
tester,
) async {
await pump(
tester,
(request) => request.start == null
? _october
: throw const StatementRefusal(
400,
'End date: A statement can cover at most 366 days.',
),
);
await tester.tap(find.text('Previous month'));
await tester.pumpAndSettle();
expect(find.textContaining('at most 366 days'), findsOneWidget);
expect(find.text('Change period'), findsOneWidget);
expect(find.text('This month'), findsOneWidget);
});
testWidgets('Previous month asks for the month before the one shown', (
tester,
) async {
await pump(tester, (_) => _october);
await tester.tap(find.text('Previous month'));
await tester.pumpAndSettle();
expect(asked.last, (
accountId: 'a1',
start: '2026-09-01',
end: '2026-09-30',
));
await tester.tap(find.text('This month'));
await tester.pumpAndSettle();
expect(asked.last, (accountId: 'a1', start: null, end: null));
});
testWidgets('an empty period says so', (tester) async {
await pump(
tester,
(_) => const AccountStatement(
accountId: 'a1',
accountName: 'Northwind',
startDate: '2026-10-01',
endDate: '2026-10-31',
sections: [],
),
);
expect(
find.text(
'Nothing was billed or paid in this period, and nothing is owed.',
),
findsOneWidget,
);
});
for (final admin in [true, false]) {
testWidgets('the account screen offers a statement: admin=$admin', (
tester,
) async {
_usePhone(tester, 1.3);
await tester.pumpWidget(
ProviderScope(
overrides: [
accountsProvider.overrideWith(_Accounts.new),
duplicatesApiProvider.overrideWithValue(_NoDuplicates()),
isOrgAdminProvider.overrideWithValue(admin),
],
child: const MaterialApp(home: AccountDetailScreen(accountId: 'a1')),
),
);
await tester.pumpAndSettle();
expect(tester.takeException(), isNull);
expect(
find.byTooltip('Statement'),
admin ? findsOneWidget : findsNothing,
);
});
}
}

View file

@ -0,0 +1,210 @@
import 'dart:convert';
import 'package:bottle_crm/data/models/account_statement.dart';
import 'package:bottle_crm/providers/account_statement_provider.dart';
import 'package:bottle_crm/screens/invoices/invoice_format.dart';
import 'package:bottle_crm/services/api_service.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:http/http.dart' as http;
import 'package:http/testing.dart';
/// Account statements (#810): what the phone reads from
/// `GET /api/invoices/statements/<account>/`, and how it asks for it.
const _account = '11111111-2222-3333-4444-555555555555';
Map<String, dynamic> statementJson() => {
'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': '100.00',
'cancelled': '0.00',
'closing_balance': '210.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-20',
'kind': 'payment',
'invoice_id': 'inv-1',
'invoice_number': 'INV-1',
'description': 'Payment (Bank Transfer)',
'amount': '-100.00',
'balance': '210.00',
},
],
},
],
};
/// A JWT that decodes but is not signed, so `ApiService` sends it as is.
String _token() {
String seg(Map<String, dynamic> m) =>
base64Url.encode(utf8.encode(jsonEncode(m))).replaceAll('=', '');
final exp = DateTime.now().add(const Duration(hours: 1));
return '${seg({'alg': 'HS256'})}.'
'${seg({'exp': exp.millisecondsSinceEpoch ~/ 1000})}.sig';
}
void main() {
group('AccountStatement.fromJson', () {
test('reads each currency, its balances and its entries in order', () {
final statement = AccountStatement.fromJson(statementJson());
expect(statement.accountName, 'Acme');
expect(
(statement.startDate, statement.endDate),
('2026-10-01', '2026-10-31'),
);
final usd = statement.sections.single;
expect(usd.currency, 'USD');
expect(
(usd.openingBalance, usd.invoiced, usd.paid, usd.closingBalance),
(60.0, 250.0, 100.0, 210.0),
);
expect(
[for (final e in usd.entries) (e.kind, e.amount, e.balance)],
[('invoice', 250.0, 310.0), ('payment', -100.0, 210.0)],
);
expect(usd.entries.first.invoiceId, 'inv-1');
expect(usd.entries.first.invoiceNumber, 'INV-1');
});
test('a period with nothing billed or owed has no sections', () {
final statement = AccountStatement.fromJson({
...statementJson(),
'currencies': <dynamic>[],
});
expect(statement.sections, isEmpty);
});
});
group('previousMonth', () {
test('is the whole calendar month before the one a date falls in', () {
expect(previousMonth('2026-10-15'), (
start: '2026-09-01',
end: '2026-09-30',
));
});
test('crosses a year and knows a leap February', () {
expect(previousMonth('2026-01-05'), (
start: '2025-12-01',
end: '2025-12-31',
));
expect(previousMonth('2024-03-31'), (
start: '2024-02-01',
end: '2024-02-29',
));
});
});
group('money', () {
test('puts the sign before the symbol', () {
expect(money(-100, '\$'), '-\$100.00');
expect(money(250.5, '\$'), '\$250.50');
});
});
group('accountStatementProvider', () {
late List<Uri> asked;
void answer(int status, Object body) {
asked = [];
ApiService().setAccessToken(_token());
ApiService().setClientForTesting(
MockClient((request) async {
asked.add(request.url);
return http.Response(jsonEncode(body), status);
}),
);
}
tearDown(() {
ApiService().clearAuth();
ApiService().setClientForTesting(http.Client());
});
Future<AccountStatement> read(StatementRequest request) {
final container = ProviderContainer();
addTearDown(container.dispose);
// Listened to, as a screen would: an auto-dispose provider nobody
// watches is disposed before a slow answer (a 403 retries) lands.
container.listen(accountStatementProvider(request), (_, _) {});
return container.read(accountStatementProvider(request).future);
}
test('asks for the account and the period', () async {
answer(200, statementJson());
final statement = await read((
accountId: _account,
start: '2026-10-01',
end: '2026-10-31',
));
expect(statement.sections.single.closingBalance, 210.0);
expect(asked.single.path, '/api/invoices/statements/$_account/');
expect(asked.single.queryParameters, {
'start_date': '2026-10-01',
'end_date': '2026-10-31',
});
});
test(
'sends no dates when none were picked, so the API default applies',
() async {
answer(200, statementJson());
await read((accountId: _account, start: null, end: null));
expect(asked.single.queryParameters, isEmpty);
},
);
test('a member is told it is for admins', () async {
answer(403, {
'error': true,
'message': 'Only an administrator can view account statements.',
});
await expectLater(
read((accountId: _account, start: null, end: null)),
throwsA(
isA<StatementRefusal>()
.having((e) => e.forbidden, 'forbidden', isTrue)
.having(
(e) => e.message,
'message',
'Only an administrator can view account statements.',
),
),
);
});
test("a refused period carries the API's sentence", () async {
answer(400, {
'end_date': ['A statement can cover at most 366 days.'],
});
await expectLater(
read((accountId: _account, start: '2026-01-01', end: '2027-06-01')),
throwsA(
isA<StatementRefusal>()
.having((e) => e.forbidden, 'forbidden', isFalse)
.having(
(e) => e.message,
'message',
contains('A statement can cover at most 366 days.'),
),
),
);
});
});
}