Skip to content

Open-source personal finance manager. Self-hosted, privacy-first.

7.7 KB
Raw Blame
"""What is still owed, as money the forecast can carry.

## Why invoices were kept out until now

Everything that projects in Securo does so **by being a transaction**: a
row counts as forecast when it is `pending`, or `posted` with a future
date, and a recurring schedule enters by being materialised into rows.
An invoice is a claim, not a movement, so it never qualified for free.

Projecting it before matching existed would have **double counted**. The
same R$5.000 is routinely an open invoice *and* a pending bank credit,
and until the two could be said to be the same money, adding both would
have inflated every forecast in the product. Saying they are the same
money is exactly what payment matching does, which is why this lands
with it and not before.

## What resolves the double count

Only the **unallocated** balance is projected. The moment a payment is
linked, the invoice's outstanding drops and the transaction carries the
forecast alone, so the total never moves twice for one payment. Nothing
has to be kept in sync: the subtraction is the mechanism.

## Three deliberate narrowings

**Only `status == 'open'`.** That is the stored decision, not the derived
reading. A draft is not owed by anybody yet, and `void` and
`uncollectible` are the two ways of saying the money is not coming.

**Only inside the window, by due date.** An invoice sixty days overdue is
still owed, and it is deliberately *not* projected: the only date we have
for it has passed, and moving it to today would be inventing a date
nobody promised. Overdue money is the aging table's subject, and a
forecast that quietly relocates it would make the aging table and the
forecast disagree about the same debt.

**Per currency, unconverted.** The caller decides. The dashboard keeps a
figure per currency, so a euro invoice belongs in the euro bucket; the
cash-flow report sums into one currency and converts on the way in.
Converting here would force the first caller to undo it.

## The module gate

There is no flag lookup. A workspace without invoicing has no rows in
`invoices`, so this costs one index probe and returns nothing, which is
cheaper than the query that would have asked whether to run it.
"""
from __future__ import annotations

import uuid
from dataclasses import dataclass
from datetime import date
from decimal import Decimal
from typing import Optional

from sqlalchemy import and_, func, or_, select
from sqlalchemy.ext.asyncio import AsyncSession

from app.models.invoice import Invoice, InvoiceAllocation, InvoiceDeduction, InvoiceInstallment

ZERO = Decimal("0")


@dataclass(frozen=True)
class Claim:
    """One promise of money, and when it was promised for."""

    due_date: date
    currency: str
    #: Always positive. `direction` says which way it points, because the
    #: two callers sign it differently: a balance walk adds or subtracts,
    #: a cash-flow report files it under income or expenses.
    amount: Decimal
    #: `receivable` (money owed to the workspace) or `payable`.
    direction: str

    @property
    def signed(self) -> Decimal:
        return self.amount if self.direction == "receivable" else -self.amount


async def claims_in_range(
    session: AsyncSession,
    workspace_id: uuid.UUID,
    range_start: date,
    range_end: date,
    *,
    directions: Optional[tuple[str, ...]] = None,
) -> list[Claim]:
    """Every open invoice falling due in `[range_start, range_end)`.

    Half-open on purpose, matching `_get_forecast_transactions`, so a
    caller walking month by month never counts the boundary day twice.
    """
    allocated = (
        select(
            InvoiceAllocation.invoice_id.label("invoice_id"),
            func.coalesce(func.sum(InvoiceAllocation.amount), 0).label("total"),
        )
        .group_by(InvoiceAllocation.invoice_id)
        .subquery()
    )
    deducted = (
        select(
            InvoiceDeduction.invoice_id.label("invoice_id"),
            func.coalesce(func.sum(InvoiceDeduction.amount), 0).label("total"),
        )
        .group_by(InvoiceDeduction.invoice_id)
        .subquery()
    )
    settled = func.coalesce(allocated.c.total, 0) + func.coalesce(deducted.c.total, 0)
    # An invoice whose money is expected in several dates enters the
    # window through any of them; the walk below decides which part.
    has_installment_in_range = (
        select(InvoiceInstallment.id)
        .where(
            InvoiceInstallment.invoice_id == Invoice.id,
            InvoiceInstallment.due_date >= range_start,
            InvoiceInstallment.due_date < range_end,
        )
        .exists()
    )

    query = (
        select(
            Invoice.id,
            Invoice.due_date,
            Invoice.currency,
            Invoice.direction,
            (Invoice.total - settled).label("outstanding"),
        )
        .outerjoin(allocated, allocated.c.invoice_id == Invoice.id)
        .outerjoin(deducted, deducted.c.invoice_id == Invoice.id)
        .where(
            Invoice.workspace_id == workspace_id,
            Invoice.status == "open",
            or_(
                and_(Invoice.due_date >= range_start, Invoice.due_date < range_end),
                has_installment_in_range,
            ),
            (Invoice.total - settled) > 0,
        )
    )

    if directions is not None:
        query = query.where(Invoice.direction.in_(directions))

    rows = (await session.execute(query)).all()
    ids = [row.id for row in rows]
    schedules: dict[uuid.UUID, list[InvoiceInstallment]] = {}
    if ids:
        for installment in (
            await session.execute(
                select(InvoiceInstallment)
                .where(InvoiceInstallment.invoice_id.in_(ids))
                .order_by(InvoiceInstallment.position)
            )
        ).scalars():
            schedules.setdefault(installment.invoice_id, []).append(installment)

    claims: list[Claim] = []
    for row in rows:
        currency = row.currency or "USD"
        outstanding = Decimal(str(row.outstanding))
        installments = schedules.get(row.id)
        if not installments:
            claims.append(Claim(row.due_date, currency, outstanding, row.direction))
            continue
        # Settled money covers the schedule first-to-last; what is left
        # of each installment is promised for that installment's date.
        covered = sum((i.amount for i in installments), Decimal("0")) - outstanding
        for installment in installments:
            share = min(installment.amount, max(covered, ZERO))
            covered -= share
            left = installment.amount - share
            if left > ZERO and range_start <= installment.due_date < range_end:
                claims.append(Claim(installment.due_date, currency, left, row.direction))

    # Periods of a recurring agreement that no invoice answers for yet.
    # Same money as the invoice the job will emit for them, and the two
    # never coexist: a period is projected only from the cursor on, and
    # the cursor moves the moment the invoice exists. Receivable only,
    # because that is the only side an agreement emits today.
    if directions is None or "receivable" in directions:
        # Imported lazily: the schedule service reads invoices and the
        # ledger, and this module is read by the dashboard and reports.
        # A top-level import would tie the two directions into a cycle.
        from app.services import invoice_schedule_service

        for period in await invoice_schedule_service.projected_periods(
            session, workspace_id, range_start, range_end
        ):
            claims.append(
                Claim(
                    due_date=period.due_date,
                    currency=period.currency,
                    amount=period.amount,
                    direction="receivable",
                )
            )
    return claims