interface Entry {
id: string;
sequence_number: number;
order_id: string | null;
order_link: 'order' | 'listing' | 'none' | 'unknown';
amount: { amount: string; currency: string } | null;
}
interface Page {
data: Entry[];
summary: { not_stored: { from: number; to: number; after: number } | null };
}
// Your copy of the ledger, by entry id: a later sync can rewrite an entry, so upsert.
const entries = new Map<string, Entry>();
let after = 0;
for (;;) {
const res = await fetch(`https://api.alura.io/v1/workspace/ledger?shop_id=22841907&after=${after}`, { headers: { Authorization: `Bearer ${process.env.ALURA_API_KEY}` } });
if (!res.ok) throw new Error(`${res.status}: ${await res.text()}`);
const page = (await res.json()) as Page;
for (const entry of page.data) entries.set(entry.id, entry);
const hole = page.summary.not_stored;
if (hole !== null) {
// Hold here and read again later from the same `after`.
console.log(`stopped before sequence numbers ${hole.from} to ${hole.to}`);
break;
}
if (page.data.length === 0) break;
after = page.data.at(-1)!.sequence_number;
}
// What each order earned after Etsy's fees and taxes, per currency, in minor units. An entry without an amount is never
// counted as 0: it leaves its order incomplete. An `unknown` entry may belong to any order, so while one remains, no
// total is complete.
const orders = new Map<string, { cents: Map<string, number>; missing: number }>();
let unknown = 0;
let noAmount = 0;
for (const entry of entries.values()) {
if (entry.order_link === 'unknown') unknown++;
if (entry.amount === null) noAmount++;
if (entry.order_link !== 'order' || entry.order_id === null) continue;
const order = orders.get(entry.order_id) ?? { cents: new Map<string, number>(), missing: 0 };
orders.set(entry.order_id, order);
if (entry.amount === null) {
order.missing++;
continue;
}
const { amount, currency } = entry.amount;
order.cents.set(currency, (order.cents.get(currency) ?? 0) + Math.round(Number(amount) * 100));
}
console.log(`${entries.size} entries, ${unknown} not tied to an order yet, ${noAmount} without an amount`);
for (const [id, order] of orders) {
const sums = [...order.cents].map(([currency, cents]) => `${(cents / 100).toFixed(2)} ${currency}`).join(' + ');
console.log(`order ${id}: ${sums}${order.missing > 0 ? ` (incomplete: ${order.missing} entries without an amount)` : ''}`);
}
if (unknown > 0) console.log(`totals incomplete: ${unknown} entries are not tied to an order yet; read them again later`);