P&L: Cost lines with tax categories (advertising, player rewards, software, other), outside-wallet source, duplicate-tx guard; Tax summary (income vs advertising/promotion, own sales excluded, CSV)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -4127,6 +4127,51 @@ const server = http.createServer(async (req, res) => {
|
||||
ledger: { entries: ledger.entries(), totals: ledger.totals('feeA'),
|
||||
reconcile: ledger.reconcile(pol(sum(admin, e => e.amountWei)), pol(BigInt(balances.feeA || '0')), 'feeA') } });
|
||||
}
|
||||
// tax summary (2026-10-04, Marty: "show what I spent in advertising versus income" at tax time). Income = the platform's cut
|
||||
// of every package sale (AdminPaid), valued in dollars at that sale's own price (Purchase.priceCents / paidWei in the same
|
||||
// transaction), minus sales to Marty's own positions (site config ownMemberIds, default "1": his own money moving around is
|
||||
// not income), plus outside revenue lines. Costs = ledger 'cost' lines by category. Draws and transfers are listed apart:
|
||||
// they are owner money, not expenses. Dates come from block numbers (Polygon ~2 s blocks), so a sale within a few hours
|
||||
// of New Year can land in the neighbouring year; the CSV says so.
|
||||
if (p === '/api/admin/tax' && req.method === 'GET') {
|
||||
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
|
||||
const year = String(Number(u.searchParams.get('year')) || new Date().getFullYear());
|
||||
const own = new Set(String(siteConfig().ownMemberIds || '1').split(',').map(x => Number(x.trim())).filter(Boolean));
|
||||
let latest = 0, latestTs = Date.now(); try { const b = await chain.rpc('eth_getBlockByNumber', ['latest', false]); latest = parseInt(b.number, 16); latestTs = parseInt(b.timestamp, 16) * 1000; } catch (e) {}
|
||||
const dayOf = blk => new Date(latestTs - (latest - blk) * 2000).toLocaleDateString('en-CA', { timeZone: 'America/Chicago' });
|
||||
const evs = chain.recentEvents(1e9);
|
||||
const buys = new Map(); for (const e of evs) if (e.type === 'Purchase') buys.set(e.tx, e);
|
||||
const months = {}; let incomeUsd = 0, incomePol = 0, ownUsd = 0, sales = 0;
|
||||
for (const e of evs) {
|
||||
if (e.type !== 'AdminPaid') continue; const day = dayOf(e.block); if (!day.startsWith(year)) continue;
|
||||
const b = buys.get(e.tx); const pol = Number(BigInt(e.amountWei) / 10n ** 12n) / 1e6;
|
||||
const usd = b && Number(b.paidWei) > 0 ? (Number(BigInt(e.amountWei) * 1000000n / BigInt(b.paidWei)) / 1e6) * (b.priceCents / 100) : 0;
|
||||
if (own.has(Number(e.buyerId))) { ownUsd += usd; continue; }
|
||||
incomeUsd += usd; incomePol += pol; sales++; const m = day.slice(0, 7); months[m] = months[m] || { incomeUsd: 0, costUsd: {} }; months[m].incomeUsd += usd;
|
||||
}
|
||||
const lines = ledger.entriesFor(year); let outsideUsd = 0; const costs = {}; const draws = []; const transfers = [];
|
||||
for (const l of lines) {
|
||||
const m = l.date.slice(0, 7); months[m] = months[m] || { incomeUsd: 0, costUsd: {} };
|
||||
if (l.kind === 'revenue') { outsideUsd += l.usd; months[m].incomeUsd += l.usd; }
|
||||
else if (l.kind === 'cost') { const c = l.category || 'other', v = l.dir === 'out' ? l.usd : -l.usd; costs[c] = (costs[c] || 0) + v; months[m].costUsd[c] = (months[m].costUsd[c] || 0) + v; }
|
||||
else if (l.kind === 'draw') draws.push(l); else transfers.push(l);
|
||||
}
|
||||
const r2 = n => Math.round(n * 100) / 100, adPromo = (costs.advertising || 0) + (costs.rewards || 0), allCosts = Object.values(costs).reduce((n, v) => n + v, 0);
|
||||
const csv = [['Section', 'Date', 'Category', 'Description', 'POL', 'USD', 'Transaction'].join(',')];
|
||||
const q = v => '"' + String(v == null ? '' : v).replace(/"/g, '""') + '"';
|
||||
for (const e of evs) { if (e.type !== 'AdminPaid' || own.has(Number(e.buyerId))) continue; const day = dayOf(e.block); if (!day.startsWith(year)) continue; const b = buys.get(e.tx);
|
||||
const usd = b && Number(b.paidWei) > 0 ? (Number(BigInt(e.amountWei) * 1000000n / BigInt(b.paidWei)) / 1e6) * (b.priceCents / 100) : 0;
|
||||
csv.push(['Income', day, 'Platform share of package sale', 'Member #' + e.buyerId + (b ? ' bought the $' + Math.round(b.priceCents / 100) + ' package' : ''), (Number(BigInt(e.amountWei) / 10n ** 12n) / 1e6).toFixed(6), usd.toFixed(2), e.tx].map(q).join(',')); }
|
||||
for (const l of lines) { const sec = l.kind === 'revenue' ? 'Income' : l.kind === 'cost' ? 'Expense' : l.kind === 'draw' ? 'Owner draw (not an expense)' : 'Transfer (not income or expense)';
|
||||
csv.push([sec, l.date, l.kind === 'cost' ? (ledger.CATS[l.category] || l.category) : l.kind, l.note, (l.dir === 'out' ? -1 : 1) * l.amount, (l.kind === 'cost' && l.dir === 'out' ? -1 : 1) * l.usd, l.tx].map(q).join(',')); }
|
||||
csv.push(''); csv.push(q('Dates for on-chain sales come from block numbers; check any sale within a few hours of January 1. Sales to your own positions (' + Array.from(own).join(', ') + ') are left out.'));
|
||||
return json(res, 200, { year, ownMemberIds: Array.from(own),
|
||||
income: { platformUsd: r2(incomeUsd), platformPol: Math.round(incomePol * 1e4) / 1e4, sales, outsideUsd: r2(outsideUsd), totalUsd: r2(incomeUsd + outsideUsd), ownSalesExcludedUsd: r2(ownUsd) },
|
||||
expenses: { byCategory: Object.fromEntries(Object.entries(costs).map(([k, v]) => [k, r2(v)])), labels: ledger.CATS, advertisingAndPromotionUsd: r2(adPromo), totalUsd: r2(allCosts) },
|
||||
netUsd: r2(incomeUsd + outsideUsd - allCosts), draws: draws.length, transfers: transfers.length,
|
||||
months: Object.fromEntries(Object.keys(months).sort().map(k => [k, { incomeUsd: r2(months[k].incomeUsd), costUsd: r2(Object.values(months[k].costUsd).reduce((n, v) => n + v, 0)) }])),
|
||||
csv: csv.join('\n') });
|
||||
}
|
||||
if (p === '/api/admin/ledger' && req.method === 'POST') {
|
||||
if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
|
||||
const b = await readBody(req);
|
||||
|
||||
Reference in New Issue
Block a user