Functional Weave
Code in TypeScript

charity.reclaim-batch

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

1.0.0 (not the latest) · 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

  • giftAidClaimBatch(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
  • giftAidClaimBatch(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
  • giftAidClaimBatch(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.

export function giftAidClaimBatch(donations: readonly GiftAidDonation[], periodStart: string, periodEnd: string, aggregateSmall: boolean): GiftAidClaimBatch
donationsGiftAidDonation[]donation records in any order; ids must be unique
periodStartdatefirst day of the claim period, inclusive
periodEnddatelast day of the claim period, inclusive
aggregateSmallboolput donations at or under the aggregation limit on aggregated lines instead of donor lines
returnsGiftAidClaimBatch

The types it declares, generated into your project

/** One donation as the charity recorded it. */
export interface GiftAidDonation {
  readonly id: string;
  /** null for an anonymous gift */
  readonly donorId: string | null;
  readonly date: string;
  /** GBP */
  readonly amount: Money;
  /** a Gift Aid declaration from the donor covers it */
  readonly hasDeclaration: boolean;
}

export type ClaimLineKind = "donor" | "aggregated";

/** One entry on the claim schedule. */
export interface ClaimLine {
  readonly kind: ClaimLineKind;
  /** null on an aggregated line */
  readonly donorId: string | null;
  /** date of the last donation on the line, as the schedule asks */
  readonly lastDate: string;
  readonly count: number;
  readonly total: Money;
}

/** A donation left out of the claim, and why. */
export interface ExcludedDonation {
  readonly id: string;
  /** outside-period, not-positive, no-declaration or no-donor */
  readonly reason: string;
}

/** The claim: its lines, totals and what was left out. */
export interface GiftAidClaimBatch {
  /** donor lines by donorId, then aggregated lines by date */
  readonly lines: readonly ClaimLine[];
  readonly eligibleCount: number;
  readonly eligibleTotal: Money;
  /** Gift Aid on eligibleTotal, worked out per tax year and rounded down once per year */
  readonly claimable: Money;
  /** in input order */
  readonly excluded: readonly ExcludedDonation[];
}

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

import { giftAidClaimBatch } from "#fune/charity.reclaim-batch@^1";
impl/typescript.ts · 108 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.

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

function compare(a: string, b: string): number {
  return a < b ? -1 : a > b ? 1 : 0;
}

/**
 * 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, so the same records always
 * give the same claim.
 */
export function giftAidClaimBatch(
  donations: readonly GiftAidDonation[],
  periodStart: string,
  periodEnd: string,
  aggregateSmall: boolean
): GiftAidClaimBatch {
  ukTaxYear(periodStart);
  ukTaxYear(periodEnd);
  if (periodEnd < periodStart) throw new RangeError(`periodEnd ${periodEnd} is before periodStart ${periodStart}`);
  const rule = AGGREGATION[0];
  const ids = new Set<string>();
  const excluded: ExcludedDonation[] = [];
  const eligible: GiftAidDonation[] = [];
  for (const d of donations) {
    if (ids.has(d.id)) throw new RangeError(`duplicate donation id "${d.id}"`);
    ids.add(d.id);
    if (d.amount.currency !== "GBP") throw new RangeError(`donation "${d.id}" must be in GBP, received ${d.amount.currency}`);
    ukTaxYear(d.date);
    let reason: string | null = null;
    if (d.date < periodStart || d.date > periodEnd) reason = "outside-period";
    else if (d.amount.minor <= 0) reason = "not-positive";
    else if (!d.hasDeclaration) reason = "no-declaration";
    else if (d.donorId === null) reason = "no-donor";
    if (reason === null) eligible.push(d);
    else excluded.push({ id: d.id, reason });
  }

  const small = aggregateSmall ? eligible.filter((d) => d.amount.minor <= rule.maxDonation) : [];
  const named = aggregateSmall ? eligible.filter((d) => d.amount.minor > rule.maxDonation) : eligible;

  const byDonor = new Map<string, GiftAidDonation[]>();
  for (const d of named) {
    const key = d.donorId as string;
    const list = byDonor.get(key);
    if (list === undefined) byDonor.set(key, [d]);
    else list.push(d);
  }
  const lines: ClaimLine[] = [];
  for (const donorId of [...byDonor.keys()].sort(compare)) {
    const list = byDonor.get(donorId) as GiftAidDonation[];
    lines.push({
      kind: "donor",
      donorId,
      lastDate: list.map((d) => d.date).reduce((a, b) => (b > a ? b : a)),
      count: list.length,
      total: money(list.reduce((s, d) => s + d.amount.minor, 0), "GBP"),
    });
  }

  // Aggregated lines fill in date order (ties by id) up to the line limit.
  const sortedSmall = [...small].sort((a, b) => compare(a.date, b.date) || compare(a.id, b.id));
  let current: GiftAidDonation[] = [];
  let currentTotal = 0;
  const flush = (): void => {
    if (current.length === 0) return;
    lines.push({
      kind: "aggregated",
      donorId: null,
      lastDate: current[current.length - 1].date,
      count: current.length,
      total: money(currentTotal, "GBP"),
    });
    current = [];
    currentTotal = 0;
  };
  for (const d of sortedSmall) {
    if (currentTotal + d.amount.minor > rule.maxLineTotal) flush();
    current.push(d);
    currentTotal += d.amount.minor;
  }
  flush();

  // One rounding per tax year, since each year has its own basic rate.
  const byYear = new Map<string, number>();
  for (const d of eligible) {
    const start = ukTaxYear(d.date).start;
    byYear.set(start, (byYear.get(start) ?? 0) + d.amount.minor);
  }
  let claimable = 0;
  for (const start of [...byYear.keys()].sort(compare)) {
    claimable += giftAid(money(byYear.get(start) as number, "GBP"), start).taxReclaimable.minor;
  }

  return {
    lines,
    eligibleCount: eligible.length,
    eligibleTotal: money(eligible.reduce((s, d) => s + d.amount.minor, 0), "GBP"),
    claimable: money(claimable, "GBP"),
    excluded,
  };
}

Install

fune build

With that line in your source, in a TypeScript project (language typescript in fune.project), fune build resolves it and its 3 dependencies, pins them in fune.lock, downloads only the TypeScript 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 TypeScript charity.reclaim-batch-1.0.0-typescript.fune · 29,960 bytes sha256 1ca0a9aae809ce8de1178870acf2257c2353ca43d2d2107b90f959e3a2cd4180

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

The whole function, every language, is one file too: charity.reclaim-batch-1.0.0.fune, 41,304 bytes, sha256 995d5fa2b05115145fab470ba75db554f74130aa8d83f1415827ffedf9dbd537. 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.

Files

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