---
title: "Sum usage with totals"
description: "Read per-resource totals, sum usage by unit and movement reason, and calculate the remaining value of a paid pack."
url: "https://agentpost.tools/docs/resourceshark/guides/usage-totals"
kind: guide
needs:
  - what: "The `api` helper"
    from: "https://agentpost.tools/docs/platform/quickstart.md"
  - what: "A `dev` secret key, `key`, for a project that adopted ResourceShark"
    from: "https://agentpost.tools/docs/platform/guides/keys.md"
  - what: "The prepaid resources and their activity, with `prepaidLoons`, `prepaidSignup`, and `prepaidPack`"
    from: "https://agentpost.tools/docs/resourceshark/guides/prepaid-credits.md"
  - what: "The app-side `orders` record"
    from: "https://agentpost.tools/docs/resourceshark/guides/prepaid-credits.md"
  - what: "The monthly limit resource, `recurringCap`, with its recorded usage"
    from: "https://agentpost.tools/docs/resourceshark/guides/recurring-supply.md"
---

# Sum usage with totals

Use [totals](/docs/resourceshark/concepts/totals.md) when your app needs usage over a period or balances across holders. ResourceShark answers with one row per resource. Your app chooses which [movement reasons](/docs/resourceshark/concepts/movements.md) count as usage and adds rows with matching units.

Run either code tab with the shared blocks. The SDK helpers are in `@agentpost-tools/resourceshark-sdk/helpers`.

## Before you start

-   The `api` helper, from [Platform quickstart](/docs/platform/quickstart.md).
-   A `dev` secret key, `key`, for a project that adopted ResourceShark, from [Create a project and issue a key](/docs/platform/guides/keys.md).
-   The prepaid resources and their activity, with `prepaidLoons`, `prepaidSignup`, and `prepaidPack`, from [Sell prepaid credits](/docs/resourceshark/guides/prepaid-credits.md).
-   The app-side `orders` record, from [Sell prepaid credits](/docs/resourceshark/guides/prepaid-credits.md).
-   The monthly limit resource, `recurringCap`, with its recorded usage, from [Post recurring supply](/docs/resourceshark/guides/recurring-supply.md).

This page's code continues the script of the pages above: run its blocks after theirs, in the same file. To run them as a script of their own, first copy each helper from the page that defines it, and set each other value, such as a key or an ID, to one you already have.

## 1\. Read the prepaid totals for a period

Use `key` for the project that adopted ResourceShark. Start with the credit and dollar activity from [Sell prepaid credits](/docs/resourceshark/guides/prepaid-credits.md) and the monthly limit usage from [Post recurring supply](/docs/resourceshark/guides/recurring-supply.md). Read the resources tagged `prepaid`, grouped by the `cohort` attribute on their supply. Use the first signup entry’s `createdAt` as the start of this 24-hour example. Movement sums include `from` and end just before `to`. Balances count expiries as of `asOf`.

```ts
const totalsDayMs = 86_400_000;
const totalsFrom = prepaidSignup.createdAt;
const totalsTo = new Date(Date.parse(totalsFrom) + totalsDayMs).toISOString();
const readResourceTotals = (selection: Record<string, string>) => {
  const query = new URLSearchParams({
    ...selection,
    from: totalsFrom,
    to: totalsTo,
  });
  return api('GET', `/v1/resources/reports/totals?${query}`, key);
};

const prepaidTotals = await readResourceTotals({
  tag: 'prepaid',
  groupBy: 'cohort',
});
console.log(prepaidTotals.resources.length); // 2
```

Use a secret key. The report answers [`forbidden`](/docs/resourceshark/errors.md#forbidden) for a holder’s user token. [Report requests](/docs/resourceshark/reference/reports.md) lists the selectors and their limits.

## 2\. Sum usage by unit

Count `use`, `commit`, and `settle` as net usage. Amounts are signed changes to what is on hand. A settlement that returns units reduces usage. Group rows by unit code and precision so loons and dollars stay in separate sums. With the SDK, pass the reasons to `sumTotals` and read their signed sum from `chosen`. Use `periodLength` to read elapsed time in milliseconds and 24-hour days.

```ts
const totalsReasons = ['use', 'commit', 'settle'] as const;
type TotalsUsageMovements = Partial<
  Record<(typeof totalsReasons)[number], number>
>;
const signedTotalsUsage = (movements: TotalsUsageMovements = {}) =>
  totalsReasons.reduce((sum, reason) => sum + (movements[reason] ?? 0), 0);
```

```ts tab="HTTP"
type UsageRow = {
  unit: { code: string; precision: number };
  movements?: TotalsUsageMovements;
};
const usageByUnit = new Map<string, number>();
for (const row of prepaidTotals.resources as UsageRow[]) {
  const unitKey = `${row.unit.code}:${row.unit.precision}`;
  const used = -signedTotalsUsage(row.movements);
  usageByUnit.set(unitKey, (usageByUnit.get(unitKey) ?? 0) + used);
}
const usageDays =
  (Date.parse(prepaidTotals.to) - Date.parse(prepaidTotals.from)) / totalsDayMs;
```

```ts tab="SDK"
import {
  periodLength,
  sumTotals,
} from '@agentpost-tools/resourceshark-sdk/helpers';

const usageSums = sumTotals(prepaidTotals, { reasons: [...totalsReasons] });
const usageByUnit = new Map(
  usageSums.map(
    ({ unit, chosen }) =>
      [`${unit.code}:${unit.precision}`, -(chosen ?? 0)] as const,
  ),
);
const usageDays = periodLength(prepaidTotals)?.days;
```

```ts
console.log(usageByUnit.get('loon:0'), usageByUnit.get('usd:4'), usageDays); // 191 23325 1
```

## 3\. Calculate the remaining value of a paid pack

Read the loons again, grouped by `source`, the attribute your app used for `pack` and `promo`. Read the remaining quantity from the pack’s supply entry and use its `evidence.ref` to look up the price in your app’s `orders` record. A group can cover purchases at different prices. This app values the 493 remaining loons at their share of the pack’s original 499-cent price, rounded down to cents. [Supply requests](/docs/resourceshark/reference/supply.md) lists the fields of a supply entry.

```ts
const loonsBySource = await readResourceTotals({
  resourceId: prepaidLoons.id,
  groupBy: 'source',
});
const paidGroup = loonsBySource.resources[0].groups.find(
  ({ value }: { value: string | null }) => value === 'pack',
);
const { supply: pricedPack } = await api(
  'GET',
  `/v1/resources/supply/${prepaidPack.id}`,
  key,
);
const packOrder = orders[pricedPack.evidence.ref];
if (!packOrder) throw new Error(`Missing order ${pricedPack.evidence.ref}`);
const remainingCents = Math.floor(
  (packOrder.priceInCents * pricedPack.remaining) / pricedPack.quantity,
);
console.log(paidGroup.balance.onHand, remainingCents); // 493 492
```

## Check it worked

Read the limit resource on its own and apply the same movement reasons. The builder used 20,000 limit units in the period.

```ts
const limitTotals = await readResourceTotals({ resourceId: recurringCap.id });
console.log(-signedTotalsUsage(limitTotals.resources[0].movements)); // 20000
```

[Movements](/docs/resourceshark/reference/movements.md) lists the individual changes behind a total.
