Spend by Subaccount and by Card

Total spend over a date range for each subaccount and each card, per currency and never added across currencies, with settled and pending spend kept apart.

For: developers and finance teams

This recipe totals spend over a date range, for each subaccount and for each card in them. Totals are per currency and never added across currencies, and settled spend and pending spend are kept apart. Amounts are the card's billing amounts (cardholderBilling*, in cardholderBillingCurrency): what the cardholder's statement shows, whatever currency the merchant charged in.

Before you start

  • Scope: transactions:read.
  • The subaccounts to report on, and the first and last day of the range (both included).
  • Sandbox or production.

Which transactions count

Settled spend adds up each transaction's cardholderBillingSettledAmount. Astrada keeps that amount up to date as clearings, reversals and refunds arrive, so adding it up nets them: a refund counts against spend, and a reversed hold counts nothing. A refund either lowers its purchase's settled amount or, on accounts that keep refunds apart and once the purchase is no longer pending, arrives as its own transaction with a negative settled amount; either way the total nets it.

StatusWhat it adds
PENDINGIts settled amount so far, plus its cardholderBillingHoldAmount as pending spend. A pending refund holds a negative amount, so it lowers pending spend
SETTLEDIts settled amount. The status stays SETTLED, but a later message, such as a late authorization or clearing, can still change its amounts
VOIDEDIts settled amount, which is nothing while the hold is released. A clearing can still arrive and settle it, so run the report again later rather than treating a past one as closed
DECLINEDNothing
A status newer than your SDKIts settled amount, like any other status that is not declined

Dates and filters

The transaction list filters by subaccountId and cardId and sorts by createdAt, but has no date filter. So the code applies the date range itself, to transactionOccurrenceDate, the network's date of the transaction. It reads newest first and stops once transactions were created more than 31 days before the first day of the range. A transaction can be created before its occurrence date, for example an authorization that settles later, so keep that margin, or pass no limit to read every transaction.

For Mastercard the occurrence date is often the network's settlement date, which can be a day before or after the purchase's local date.

The code

Money is exact in each language. TypeScript has no decimal type, so each amount becomes whole minor units (cents for USD, none for JPY) and is added as an integer; Python adds Decimal values and Java adds BigDecimal values.

/** The spend of one group in one currency. */
export interface SpendTotals {
  /** Settled spend in minor units (cents for USD): exact. */
  settledMinor: number;
  /** Pending spend (holds of PENDING transactions) in minor units. */
  pendingMinor: number;
  /** The transactions counted. */
  transactions: number;
}

/** Totals by group id, then by currency. */
export type SpendByGroup = Record<string, Record<string, SpendTotals>>;

export interface SpendReport {
  bySubaccount: SpendByGroup;
  /** By card id; bank-sourced transactions with no card are under NO_CARD. */
  byCard: SpendByGroup;
}

export interface SpendOptions {
  /** First day, YYYY-MM-DD, included. */
  from: string;
  /** Last day, YYYY-MM-DD, included. */
  to: string;
  /** Only this card's transactions (the list's `cardId` filter). */
  cardId?: string;
  /** Stop reading once transactions were created this many days before `from`; null reads all. Default 31. */
  lookbackDays?: number | null;
}

export const NO_CARD = 'no-card';
@dataclass
class SpendTotals:
    """The spend of one group in one currency."""

    settled: Decimal = Decimal(0)
    # Pending spend: holds of PENDING transactions.
    pending: Decimal = Decimal(0)
    # The transactions counted.
    transactions: int = 0


SpendByGroup = Dict[str, Dict[str, SpendTotals]]
"""Totals by group id, then by currency."""


@dataclass
class SpendReport:
    by_subaccount: SpendByGroup = field(default_factory=dict)
    # By card id; bank-sourced transactions with no card are under NO_CARD.
    by_card: SpendByGroup = field(default_factory=dict)


NO_CARD = "no-card"
/** The spend of one group in one currency. */
public static final class SpendTotals {
    public BigDecimal settled = BigDecimal.ZERO;
    /** Pending spend: holds of PENDING transactions. */
    public BigDecimal pending = BigDecimal.ZERO;
    /** The transactions counted. */
    public int transactions;

    @Override
    public String toString() {
        return "settled " + settled.toPlainString() + " pending " + pending.toPlainString() + " (" + transactions + " transactions)";
    }
}

/** Group id, then currency. Bank-sourced transactions with no card are under NO_CARD in byCard. */
public static final class SpendReport {
    public final Map<String, Map<String, SpendTotals>> bySubaccount = new TreeMap<>();
    public final Map<String, Map<String, SpendTotals>> byCard = new TreeMap<>();
}

public static final String NO_CARD = "no-card";

Adding one transaction to its group's totals:

/** A missing amount counts as zero, so one incomplete transaction cannot stop the report. */
function orZero(amount: number | null | undefined): number {
  return amount ?? 0;
}

function add(group: Record<string, SpendTotals>, transaction: Transaction): void {
  const currency = transaction.cardholderBillingCurrency;
  const totals = (group[currency] ??= { settledMinor: 0, pendingMinor: 0, transactions: 0 });
  totals.settledMinor += toMinorUnits(orZero(transaction.cardholderBillingSettledAmount), currency);
  if (transaction.status === 'PENDING') {
    totals.pendingMinor += toMinorUnits(orZero(transaction.cardholderBillingHoldAmount), currency);
  }
  totals.transactions += 1;
}
def money(amount: Union[float, int]) -> Decimal:
    """An API amount as a Decimal, from its text (0.1 stays 0.1)."""
    return Decimal(str(amount))


def add(group: Dict[str, SpendTotals], transaction: astrada.Transaction) -> None:
    totals = group.setdefault(transaction.cardholder_billing_currency, SpendTotals())
    totals.settled += money(transaction.cardholder_billing_settled_amount)
    if transaction.status == "PENDING":
        totals.pending += money(transaction.cardholder_billing_hold_amount)
    totals.transactions += 1
static BigDecimal orZero(BigDecimal amount) {
    return Objects.requireNonNullElse(amount, BigDecimal.ZERO);
}

static void add(Map<String, SpendTotals> group, Transaction transaction) {
    SpendTotals totals = group.computeIfAbsent(transaction.getCardholderBillingCurrency(), c -> new SpendTotals());
    // A missing amount counts as zero, so one incomplete transaction cannot stop the report.
    totals.settled = totals.settled.add(orZero(transaction.getCardholderBillingSettledAmount()));
    if ("PENDING".equals(transaction.getStatusRawValue())) {
        totals.pending = totals.pending.add(orZero(transaction.getCardholderBillingHoldAmount()));
    }
    totals.transactions++;
}

The report itself, which reads each subaccount's transactions in the date range:

/** Spend of each subaccount, and of each card in them, over the date range. */
export async function spendReport(astrada: Astrada, subaccountIds: string[], options: SpendOptions): Promise<SpendReport> {
  const lookbackDays = options.lookbackDays === undefined ? 31 : options.lookbackDays;
  const stopBefore = lookbackDays === null ? undefined : Date.parse(`${options.from}T00:00:00Z`) - lookbackDays * 86_400_000;
  const report: SpendReport = { bySubaccount: {}, byCard: {} };
  for (const subaccountId of subaccountIds) {
    const bySubaccount = (report.bySubaccount[subaccountId] ??= {});
    for await (const transaction of astrada.transactions.listAll({
      subaccountId,
      cardId: options.cardId,
      order: 'desc',
      limit: 100,
    })) {
      if (stopBefore !== undefined && Date.parse(transaction.createdAt) < stopBefore) break; // stops reading pages
      const day = transaction.transactionOccurrenceDate ?? transaction.createdAt.slice(0, 10);
      if (day < options.from || day > options.to) continue;
      if (transaction.status === 'DECLINED') continue;
      add(bySubaccount, transaction);
      add((report.byCard[transaction.cardId ?? NO_CARD] ??= {}), transaction);
    }
  }
  return report;
}
def spend_report(
    client: astrada.Astrada,
    subaccount_ids: List[str],
    start: date,
    end: date,
    card_id: Optional[str] = None,
    lookback_days: Optional[int] = 31,
) -> SpendReport:
    """Spend of each subaccount, and of each card in them, from `start` to `end` (both included).
    `card_id` keeps one card's transactions (the list's `cardId` filter)."""
    stop_before = (None if lookback_days is None else
                   datetime.combine(start, time(0), timezone.utc) - timedelta(days=lookback_days))
    report = SpendReport()
    for subaccount_id in subaccount_ids:
        by_subaccount = report.by_subaccount.setdefault(subaccount_id, {})
        for transaction in client.transactions.list_all(
                subaccount_id=subaccount_id, card_id=card_id, order="desc", limit=100):
            if stop_before is not None and transaction.created_at < stop_before:
                break  # stops reading pages
            day = transaction.transaction_occurrence_date or transaction.created_at.date()
            if day < start or day > end:
                continue
            if transaction.status == "DECLINED":
                continue
            add(by_subaccount, transaction)
            card = str(transaction.card_id) if transaction.card_id else NO_CARD
            add(report.by_card.setdefault(card, {}), transaction)
    return report
/**
 * Spend of each subaccount, and of each card in them, from {@code from} to {@code to} (both
 * included). {@code cardId} (or null) keeps one card's transactions (the list's cardId filter).
 */
public static SpendReport spendReport(ApiClient client, List<UUID> subaccountIds, LocalDate from, LocalDate to,
        UUID cardId, Integer lookbackDays) {
    OffsetDateTime stopBefore = lookbackDays == null ? null : from.atStartOfDay().atOffset(ZoneOffset.UTC).minusDays(lookbackDays);
    SpendReport report = new SpendReport();
    for (UUID subaccountId : subaccountIds) {
        Map<String, SpendTotals> bySubaccount = report.bySubaccount.computeIfAbsent(subaccountId.toString(), id -> new TreeMap<>());
        ListTransactionsRequest.Builder request = ListTransactionsRequest.builder()
                .subaccountId(subaccountId).order("desc").limit(100);
        if (cardId != null) {
            request.cardId(cardId);
        }
        for (Transaction transaction : client.transactions().listAll(request.build())) {
            if (stopBefore != null && transaction.getCreatedAt().isBefore(stopBefore)) {
                break; // stops reading pages
            }
            LocalDate day = transaction.getTransactionOccurrenceDate() != null ? transaction.getTransactionOccurrenceDate()
                    : transaction.getCreatedAt().toLocalDate();
            if (day.isBefore(from) || day.isAfter(to)) {
                continue;
            }
            if ("DECLINED".equals(transaction.getStatusRawValue())) {
                continue;
            }
            add(bySubaccount, transaction);
            String card = transaction.getCardId() == null ? NO_CARD : transaction.getCardId().toString();
            add(report.byCard.computeIfAbsent(card, id -> new TreeMap<>()), transaction);
        }
    }
    return report;
}

Whole example files: TypeScript, Python, Java.

What to expect

For each subaccount, and for each card, you get one line per currency with settled spend, pending spend and the number of transactions counted. Transactions from a bank account with no card are grouped under no-card in the per-card totals.

Read more


Did this page help you?