Sum usage with totals
Use totals 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 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
apihelper, from Platform quickstart. - A
devsecret key,key, for a project that adopted ResourceShark, from Create a project and issue a key. - The prepaid resources and their activity, with
prepaidLoons,prepaidSignup, andprepaidPack, from Sell prepaid credits. - The app-side
ordersrecord, from Sell prepaid credits. - The monthly limit resource,
recurringCap, with its recorded usage, from Post recurring supply.
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 and the monthly limit usage from Post recurring supply. 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.
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 for a holder’s user token. Report requests 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.
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);
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;
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;
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 lists the fields of a supply entry.
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.
const limitTotals = await readResourceTotals({ resourceId: recurringCap.id });
console.log(-signedTotalsUsage(limitTotals.resources[0].movements)); // 20000
Movements lists the individual changes behind a total.