Functional Weave
Code in Python

charity.reclaim-batch

Gift Aid claim totals for a period from donation records: donor lines, aggregated small gifts, tax due.

1.0.1 · published 2026-10-03 by charlie · Anterra

Pinned by 12 tests, run in TypeScript, Python and Rust.

Not professional advice. This capability calculates tax figures from published rules. It is a software component for developers, not tax advice. Rules change and every rate here has an effective date. Check that the dates cover your case. Verify results against the official sources listed in its README, and have a charity tax specialist review how you use it, before anyone relies on the output. Provided “as is” under its licence, without warranty.

What it does

Turn a period's donation records into the figures of a Gift Aid repayment claim: the schedule lines, the total of eligible donations and the tax to reclaim, plus every donation left out and why.

For each donation, in input order:

For example

  • gift_aid_claim_batch(donations ×9, 2026-04-06, 2027-04-05, true) → lines ×3, eligible count 5, eligible total £150.01, claimable £37.50, excluded ×4 a mixed batch: donor lines, £20-or-less gifts aggregated, every exclusion named
  • gift_aid_claim_batch(donations ×9, 2026-04-06, 2027-04-05, false) → lines ×3, eligible count 5, eligible total £150.01, claimable £37.50, excluded ×4 the same batch without aggregation: every eligible gift on its donor's line
  • gift_aid_claim_batch(donations ×51, 2026-04-06, 2027-04-05, true) → lines ×2, eligible count 51, eligible total £1,020.00, claimable £255.00, excluded an aggregated line stops at £1,000: 51 gifts of £20 make a full line of 50 and a line of 1

The function

The same function in TypeScript, Python and Rust, pinned by the same tests. Pick your language; the choice follows you around the registry.

def gift_aid_claim_batch(donations: Sequence[GiftAidDonation], period_start: str, period_end: str, aggregate_small: bool) -> GiftAidClaimBatch
donationsGiftAidDonation[]donation records in any order; ids must be unique
period_startdatefirst day of the claim period, inclusive
period_enddatelast day of the claim period, inclusive
aggregate_smallboolput donations at or under the aggregation limit on aggregated lines instead of donor lines
returnsGiftAidClaimBatch

The types it declares, generated into your project

@dataclass(frozen=True)
class GiftAidDonation:
    """One donation as the charity recorded it."""

    id: str
    #: null for an anonymous gift
    donor_id: Optional[str]
    date: str
    #: GBP
    amount: Money
    #: a Gift Aid declaration from the donor covers it
    has_declaration: bool

ClaimLineKind = Literal["donor", "aggregated"]

@dataclass(frozen=True)
class ClaimLine:
    """One entry on the claim schedule."""

    kind: ClaimLineKind
    #: null on an aggregated line
    donor_id: Optional[str]
    #: date of the last donation on the line, as the schedule asks
    last_date: str
    count: int
    total: Money

@dataclass(frozen=True)
class ExcludedDonation:
    """A donation left out of the claim, and why."""

    id: str
    #: outside-period, not-positive, no-declaration or no-donor
    reason: str

@dataclass(frozen=True)
class GiftAidClaimBatch:
    """The claim: its lines, totals and what was left out."""

    #: donor lines by donorId, then aggregated lines by date
    lines: List[ClaimLine]
    eligible_count: int
    eligible_total: Money
    #: Gift Aid on eligibleTotal, worked out per tax year and rounded down once per year
    claimable: Money
    #: in input order
    excluded: List[ExcludedDonation]

Your code names it in one line, in the file that uses it

from fune.charity.reclaim_batch import gift_aid_claim_batch  # charity.reclaim-batch@^1
impl/python.py · 105 lines · open · raw

Imports name this capability’s declared dependencies, which fune builds next to it in your project; each one links to its page.

from typing import Dict, List, Optional, Sequence

from .charity_gift_aid import gift_aid  ← from charity.gift-aid ^1.0.0 · built alongside by fune
from .charity_reclaim_batch_data import AGGREGATION  ← this capability’s own data, compiled from data/aggregation.json into the same file by fune build
from .charity_reclaim_batch_types import ClaimLine, ExcludedDonation, GiftAidClaimBatch, GiftAidDonation
from .dates_uk_tax_year import uk_tax_year  ← from dates.uk-tax-year ^1.0.0 · built alongside by fune
from .money_amount import money  ← from money.amount ^1.0.0 · built alongside by fune


def gift_aid_claim_batch(
    donations: Sequence[GiftAidDonation],
    period_start: str,
    period_end: str,
    aggregate_small: bool,
) -> GiftAidClaimBatch:
    """The totals of a Gift Aid repayment claim for a period. Every donation is
    either on the claim or listed as excluded with its reason, lines come out
    in a fixed order (donor lines by donorId, then aggregated lines by date),
    and the tax is worked out on each tax year's total.
    """
    uk_tax_year(period_start)
    uk_tax_year(period_end)
    if period_end < period_start:
        raise ValueError("periodEnd %s is before periodStart %s" % (period_end, period_start))
    rule = AGGREGATION[0]
    ids = set()
    excluded: List[ExcludedDonation] = []
    eligible: List[GiftAidDonation] = []
    for d in donations:
        if d.id in ids:
            raise ValueError('duplicate donation id "%s"' % (d.id,))
        ids.add(d.id)
        if d.amount.currency != "GBP":
            raise ValueError('donation "%s" must be in GBP, received %s' % (d.id, d.amount.currency))
        uk_tax_year(d.date)
        reason: Optional[str] = None
        if d.date < period_start or d.date > period_end:
            reason = "outside-period"
        elif d.amount.minor <= 0:
            reason = "not-positive"
        elif not d.has_declaration:
            reason = "no-declaration"
        elif d.donor_id is None:
            reason = "no-donor"
        if reason is None:
            eligible.append(d)
        else:
            excluded.append(ExcludedDonation(id=d.id, reason=reason))

    small = [d for d in eligible if d.amount.minor <= rule.max_donation] if aggregate_small else []
    named = [d for d in eligible if d.amount.minor > rule.max_donation] if aggregate_small else eligible

    by_donor: Dict[str, List[GiftAidDonation]] = {}
    for d in named:
        by_donor.setdefault(d.donor_id, []).append(d)
    lines: List[ClaimLine] = []
    for donor_id in sorted(by_donor.keys()):
        group = by_donor[donor_id]
        lines.append(
            ClaimLine(
                kind="donor",
                donor_id=donor_id,
                last_date=max(d.date for d in group),
                count=len(group),
                total=money(sum(d.amount.minor for d in group), "GBP"),
            )
        )

    # Aggregated lines fill in date order (ties by id) up to the line limit.
    current: List[GiftAidDonation] = []
    current_total = 0

    def flush() -> None:
        nonlocal current, current_total
        if not current:
            return
        lines.append(
            ClaimLine(kind="aggregated", donor_id=None, last_date=current[-1].date, count=len(current), total=money(current_total, "GBP"))
        )
        current = []
        current_total = 0

    for d in sorted(small, key=lambda x: (x.date, x.id)):
        if current_total + d.amount.minor > rule.max_line_total:
            flush()
        current.append(d)
        current_total += d.amount.minor
    flush()

    # One rounding per tax year, since each year has its own basic rate.
    by_year: Dict[str, int] = {}
    for d in eligible:
        start = uk_tax_year(d.date).start
        by_year[start] = by_year.get(start, 0) + d.amount.minor
    claimable = 0
    for start in sorted(by_year.keys()):
        claimable += gift_aid(money(by_year[start], "GBP"), start).tax_reclaimable.minor

    return GiftAidClaimBatch(
        lines=lines,
        eligible_count=len(eligible),
        eligible_total=money(sum(d.amount.minor for d in eligible), "GBP"),
        claimable=money(claimable, "GBP"),
        excluded=excluded,
    )

Install

fune build

With that line in your source, in a Python project (language python in fune.project), fune build resolves it and its 3 dependencies, pins them in fune.lock, downloads only the Python package of each, and builds the code above into your project’s .fune/build, one readable file per capability with a header linking back here. Or pin a range in fune.project and build in one step:

fune add charity.reclaim-batch
Download for Python charity.reclaim-batch-1.0.1-python.fune · 30,240 bytes sha256 89e01d9285a35c3b7f364d2e5e491e390035aa36dab0bec935b4fb95f506926a

The manifest, vectors and README with only the Python implementation. Install it without the registry with fune add ./charity.reclaim-batch-1.0.1-python.fune, or fetch it from a terminal with fune pull charity.reclaim-batch@1.0.1:python.

The whole function, every language, is one file too: charity.reclaim-batch-1.0.1.fune, 41,775 bytes, sha256 61c4ca7d06e99d0fef814257877c589ba302a746d61de27aaf668ef9615116ee. It installs into a project of any language.

Customise it in your app

The seams this capability offers. Put a marker directly above a function of your own and fune build wires it into the built code; the package on the registry is not changed, the built file’s header lists it under CUSTOMISED, and fune hooks lists every hook in the project. How hooks work.

before — your function gets the arguments and returns them, changed or not, or throws to refuse the call.

# fune: before charity.reclaim-batch

after — your function gets the result and the arguments, and returns the final result.

# fune: after charity.reclaim-batch

replace — inside this capability’s code only, calls to a dependency go to your function, with the same signature. Other capabilities that use it are unaffected; write in * to replace it everywhere.

# fune: replace charity.gift-aid in charity.reclaim-batch
# fune: replace dates.uk-tax-year in charity.reclaim-batch
# fune: replace money.amount in charity.reclaim-batch

step — your function runs at a numbered point inside the function’s body, receives the in-scope values it names as parameters, and may return replacements. List the points with fune show charity.reclaim-batch --steps.

# fune: step charity.reclaim-batch after <n|label>

Tests

A version published now needs at least 8 tests for every function, and one that expects the error for each function that throws; the registry refuses it otherwise. fune verify --all runs each case in TypeScript, Python and Rust, and a project runs them again with fune verify. This page lists the cases; it does not run them. The exact JSON is vectors.json.

CaseArgumentsExpected
a mixed batch: donor lines, £20-or-less gifts aggregated, every exclusion named donations ×9, 2026-04-06, 2027-04-05, true → lines ×3, eligible count 5, eligible total £150.01, claimable £37.50, excluded ×4
the same batch without aggregation: every eligible gift on its donor's line donations ×9, 2026-04-06, 2027-04-05, false → lines ×3, eligible count 5, eligible total £150.01, claimable £37.50, excluded ×4
an aggregated line stops at £1,000: 51 gifts of £20 make a full line of 50 and a line of 1 donations ×51, 2026-04-06, 2027-04-05, true → lines ×2, eligible count 51, eligible total £1,020.00, claimable £255.00, excluded
a claim across 5 April 2008 uses 22% before it and 20% after donations ×2, 2008-01-01, 2008-12-31, false → lines ×1, eligible count 2, eligible total £178.00, claimable £47.00, excluded
the tax is worked out on the year's total: £10.01 and £10.03 give 501p, not 250p + 250p donations ×2, 2026-04-06, 2027-04-05, false → lines ×2, eligible count 2, eligible total £20.04, claimable £5.01, excluded
donor lines are ordered by donor id, not by input order donations ×2, 2026-04-06, 2027-04-05, true → lines ×2, eligible count 2, eligible total £100.00, claimable £25.00, excluded
the period bounds are inclusive donations ×3, 2026-04-06, 2027-04-05, false → lines ×1, eligible count 2, eligible total £100.00, claimable £25.00, excluded ×1
an empty batch claims nothing , 2026-04-06, 2027-04-05, true → lines , eligible count 0, eligible total £0.00, claimable £0.00, excluded
a duplicate donation id is an error donations ×2, 2026-04-06, 2027-04-05, true → error: duplicate donation id "a"
a period that ends before it starts is an error , 2027-04-05, 2026-04-06, true → error: periodEnd 2026-04-06 is before periodStart 2027-04-05
Show the other 2 tests
CaseArgumentsExpected
a euro donation is an error donations ×1, 2026-04-06, 2027-04-05, true → error: donation "a" must be in GBP, received EUR
a malformed donation date is an error donations ×1, 2026-04-06, 2027-04-05, true → error: is not an ISO date

More from the author

- outside `periodStart`..`periodEnd` (inclusive): excluded, `outside-period`; - zero or negative (a refund, a reversal): excluded, `not-positive`; - no Gift Aid declaration: excluded, `no-declaration`; - no donor (anonymous): excluded, `no-donor`; - otherwise it is on the claim.

Eligible donations become **donor lines**, one per donor with the donor's total, count and last donation date (the schedule asks for the date of the last donation in a series), ordered by donor id. With `aggregateSmall`, donations of **£20 or less** go instead onto **aggregated lines** of up to **£1,000** each, filled in date order (ties by donation id), as Charities Online allows; each line's date is its last donation's. A donor's larger gifts stay on their donor line.

The tax is Gift Aid (charity.gift-aid) on the eligible total of **each tax year** in the period, rounded down once per year: a claim that crosses 5 April 2008 uses 22% before and 20% after, and pennies are not lost by rounding every gift. Ordering is fixed throughout, so the same records always give the same claim.

## Decisions and limits

- The aggregation limits are one row of data (`maxDonation` 2000p, `maxLineTotal` 100000p) with **no effective dates**: they are HMRC's administrative rule for Charities Online rather than law, and HMRC has not published the date they took effect, so there is nothing honest to put in a `validFrom`. It is kept as data so a change is a data release. Note that GOV.UK's schedule spreadsheet page also describes aggregated donations in passing as "multiple donations under £30", while its own detailed section and the Charities Online page both say "£20 or less"; this follows the detailed rule. - Donor ids sort by plain string order (ordinal, not locale): use ASCII ids. - It does not check benefits (charity.gift-aid-eligibility), the sponsored-event rule (sponsorship under £500 per sponsor listed under the participant), the four-year time limit, or visitor-attraction admissions, which may not be aggregated.

## Sources

- GOV.UK, "Claim tax back on donations using Charities Online" ("add together small donations of £20 or less, up to a total of £1,000 per entry"), https://www.gov.uk/guidance/claim-tax-back-on-donations-using-charities-online - GOV.UK, "Schedule spreadsheet to claim back tax on Gift Aid donations" ("donations of £20 or less from different donors ... cannot be higher than £1,000"; date of the last donation), https://www.gov.uk/guidance/schedule-spreadsheet-to-claim-back-tax-on-gift-aid-donations - Basic rates: see charity.gift-aid.

## Notices

Contains public sector information licensed under the Open Government Licence v3.0 (https://www.nationalarchives.gov.uk/doc/open-government-licence/version/3/).

1.0.1 adds its attribution notices (NOTICE). The code and the tests are unchanged.

Files

PathBytes
NOTICE184
README.md3,117
data/aggregation.json214
impl/python.py3,944
impl/rust.rs6,976
impl/typescript.ts4,122
vectors.json15,098