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:
martbost
2026-10-04 07:22:21 -05:00
parent ca7a579990
commit eb3cfebf1f
4 changed files with 210 additions and 118 deletions
+119 -111
View File
@@ -1,111 +1,119 @@
// Money moving in and out of the receiver wallets, which the chain index cannot tell us about // Money moving in and out of the receiver wallets, which the chain index cannot tell us about
// (Marty, 2026-09-23). The P&L derives revenue from AdminPaid events and holdings from // (Marty, 2026-09-23). The P&L derives revenue from AdminPaid events and holdings from
// eth_getBalance, so two real things were invisible: // eth_getBalance, so two real things were invisible:
// //
// OUT a draw. Marty funded RM Circle #139's Culmen->Apex upgrade from Receiver A. That is a // OUT a draw. Marty funded RM Circle #139's Culmen->Apex upgrade from Receiver A. That is a
// legitimate use of house profit, but nothing recorded it, so "earned" and "on hand" drift // legitimate use of house profit, but nothing recorded it, so "earned" and "on hand" drift
// apart for ever. ("Why would I ever keep a receiver wallet that I never take anything out // apart for ever. ("Why would I ever keep a receiver wallet that I never take anything out
// of? That's stupid, so I need to be able to account for it.") // of? That's stupid, so I need to be able to account for it.")
// IN outside income paid into the same wallet, e.g. a ClickBaitPays withdrawal. Real profit, // IN outside income paid into the same wallet, e.g. a ClickBaitPays withdrawal. Real profit,
// but it is not an AdminPaid event, so the revenue lines never see it. // but it is not an AdminPaid event, so the revenue lines never see it.
// //
// Both are hand-entered because only Marty knows what a transfer was for. Storage: // Both are hand-entered because only Marty knows what a transfer was for. Storage:
// DATA_DIR/ledger.json { entries: [{id, date, dir, asset, amount, usd, wallet, note, tx, ts}] } // DATA_DIR/ledger.json { entries: [{id, date, dir, asset, amount, usd, wallet, note, tx, ts}] }
const fs = require('fs'); const fs = require('fs');
const path = require('path'); const path = require('path');
let FILE = null; let FILE = null;
const DIRS = ['in', 'out']; const DIRS = ['in', 'out'];
const WALLETS = ['feeA', 'feeB', 'engine', 'hunt']; // 'outside': a wallet that is not one of ours above, e.g. Marty funding a game wallet from his own Tangem
// assets we can actually value; anything else is recorded but valued only by the usd field const WALLETS = ['feeA', 'feeB', 'engine', 'hunt', 'outside'];
const ASSETS = ['POL', 'USDC', 'USDT', 'DAI', 'other']; // assets we can actually value; anything else is recorded but valued only by the usd field
// WHY a kind and not just a direction (Marty, 2026-09-23): three different things move through const ASSETS = ['POL', 'USDC', 'USDT', 'DAI', 'other'];
// Receiver A and only one of them is profit. // WHY a kind and not just a direction (Marty, 2026-09-23): three different things move through
// revenue outside income earned by the business, e.g. a ClickBaitPays withdrawal in POL. // Receiver A and only one of them is profit.
// Counts toward profit AND toward the balance. // revenue outside income earned by the business, e.g. a ClickBaitPays withdrawal in POL.
// draw house profit spent on something, e.g. funding RM Circle #139's upgrade. Leaves the // Counts toward profit AND toward the balance.
// wallet, but it is not a cost of running InstantAdPay. // draw house profit spent on something, e.g. funding RM Circle #139's upgrade. Leaves the
// transfer Marty's own capital moved in or out for safekeeping, e.g. consolidating balances // wallet, but it is not a cost of running InstantAdPay.
// from other owned positions into the Tangem receiver. Touches the balance ONLY and // transfer Marty's own capital moved in or out for safekeeping, e.g. consolidating balances
// must never show up as revenue, or the P&L reports his savings as earnings. // from other owned positions into the Tangem receiver. Touches the balance ONLY and
const KINDS = ['revenue', 'draw', 'transfer']; // must never show up as revenue, or the P&L reports his savings as earnings.
// cost a real cost of running the network (2026-10-04, Marty: top up game wallets as needed and record each top-up so
function init(opts) { FILE = path.join(opts.dataDir, 'ledger.json'); } // the P&L balances; "show what I spent in advertising versus income" at tax time). Every cost has a category.
function load() { try { return JSON.parse(fs.readFileSync(FILE, 'utf8')); } catch (e) { return { entries: [] }; } } const KINDS = ['revenue', 'draw', 'transfer', 'cost'];
function save(d) { // tax-friendly cost categories: advertising + rewards are both "advertising and promotion" on the tax summary
const tmp = FILE + '.tmp'; const CATS = { advertising: 'Advertising (paid traffic, ad networks)', rewards: 'Player rewards (game and earning-site payouts)', software: 'Software and hosting', other: 'Other costs' };
fs.writeFileSync(tmp, JSON.stringify(d, null, 1));
fs.renameSync(tmp, FILE); // never leave a half-written ledger behind function init(opts) { FILE = path.join(opts.dataDir, 'ledger.json'); }
} function load() { try { return JSON.parse(fs.readFileSync(FILE, 'utf8')); } catch (e) { return { entries: [] }; } }
const newId = () => Date.now().toString(36) + Math.random().toString(36).slice(2, 6); function save(d) {
const num = v => { const n = Number(v); return Number.isFinite(n) && n >= 0 ? Math.round(n * 1e6) / 1e6 : 0; }; const tmp = FILE + '.tmp';
fs.writeFileSync(tmp, JSON.stringify(d, null, 1));
function entries() { fs.renameSync(tmp, FILE); // never leave a half-written ledger behind
return load().entries.slice().sort((a, b) => }
(b.date || '').localeCompare(a.date || '') || (b.ts || 0) - (a.ts || 0)); const newId = () => Date.now().toString(36) + Math.random().toString(36).slice(2, 6);
} const num = v => { const n = Number(v); return Number.isFinite(n) && n >= 0 ? Math.round(n * 1e6) / 1e6 : 0; };
function put(input) { function entries() {
const d = load(); return load().entries.slice().sort((a, b) =>
const dir = DIRS.includes(input.dir) ? input.dir : null; (b.date || '').localeCompare(a.date || '') || (b.ts || 0) - (a.ts || 0));
if (!dir) return { error: 'Say whether the money came in or went out.' }; }
const amount = num(input.amount);
const usd = num(input.usd); function put(input) {
if (!amount && !usd) return { error: 'Give an amount, in POL or in dollars.' }; const d = load();
const note = String(input.note || '').trim().slice(0, 200); const dir = DIRS.includes(input.dir) ? input.dir : null;
if (!note) return { error: 'Say what this was for. An unexplained line is the thing we are fixing.' }; if (!dir) return { error: 'Say whether the money came in or went out.' };
const date = /^\d{4}-\d{2}-\d{2}$/.test(String(input.date || '')) ? input.date const amount = num(input.amount);
: new Date().toLocaleDateString('en-CA', { timeZone: 'America/Chicago' }); // Central, like every other day key here const usd = num(input.usd);
const e = { if (!amount && !usd) return { error: 'Give an amount, in POL or in dollars.' };
id: input.id && d.entries.find(x => x.id === input.id) ? input.id : newId(), const note = String(input.note || '').trim().slice(0, 200);
date, dir, amount, usd, note, if (!note) return { error: 'Say what this was for. An unexplained line is the thing we are fixing.' };
asset: ASSETS.includes(input.asset) ? input.asset : 'POL', const date = /^\d{4}-\d{2}-\d{2}$/.test(String(input.date || '')) ? input.date
kind: KINDS.includes(input.kind) ? input.kind : (dir === 'in' ? 'revenue' : 'draw'), : new Date().toLocaleDateString('en-CA', { timeZone: 'America/Chicago' }); // Central, like every other day key here
wallet: WALLETS.includes(input.wallet) ? input.wallet : 'feeA', const e = {
tx: /^0x[0-9a-fA-F]{64}$/.test(String(input.tx || '')) ? String(input.tx).toLowerCase() : '', id: input.id && d.entries.find(x => x.id === input.id) ? input.id : newId(),
ts: Date.now(), date, dir, amount, usd, note,
}; asset: ASSETS.includes(input.asset) ? input.asset : 'POL',
const i = d.entries.findIndex(x => x.id === e.id); kind: KINDS.includes(input.kind) ? input.kind : (dir === 'in' ? 'revenue' : 'draw'),
if (i >= 0) d.entries[i] = e; else d.entries.push(e); wallet: WALLETS.includes(input.wallet) ? input.wallet : 'feeA',
save(d); tx: /^0x[0-9a-fA-F]{64}$/.test(String(input.tx || '')) ? String(input.tx).toLowerCase() : '',
return { ok: true, entry: e }; ts: Date.now(),
} };
if (e.kind === 'cost') e.category = CATS[input.category] ? input.category : 'other';
function remove(id) { if (e.tx && d.entries.some(x => x.tx === e.tx && x.id !== e.id)) return { error: 'That transaction is already recorded.', duplicate: true };
const d = load(); const i = d.entries.findIndex(x => x.id === e.id);
const i = d.entries.findIndex(x => x.id === id); if (i >= 0) d.entries[i] = e; else d.entries.push(e);
if (i < 0) return { error: 'No such entry.' }; save(d);
const [gone] = d.entries.splice(i, 1); return { ok: true, entry: e };
save(d); }
return { ok: true, entry: gone };
} function remove(id) {
const d = load();
// Totals per wallet, split by direction. POL is summed separately from dollar-denominated assets const i = d.entries.findIndex(x => x.id === id);
// because only POL can be reconciled against an on-chain balance. if (i < 0) return { error: 'No such entry.' };
function totals(wallet) { const [gone] = d.entries.splice(i, 1);
const rows = load().entries.filter(e => !wallet || e.wallet === wallet); save(d);
const t = { inPol: 0, outPol: 0, inUsd: 0, outUsd: 0, count: rows.length, return { ok: true, entry: gone };
// revenue and draws are the P&L numbers; transfers move the balance and nothing else }
revenuePol: 0, revenueUsd: 0, drawPol: 0, drawUsd: 0, transferPol: 0 };
for (const e of rows) { // Totals per wallet, split by direction. POL is summed separately from dollar-denominated assets
const pol = e.asset === 'POL' ? e.amount : 0; // because only POL can be reconciled against an on-chain balance.
if (e.dir === 'in') { t.inPol += pol; t.inUsd += e.usd; } else { t.outPol += pol; t.outUsd += e.usd; } function totals(wallet) {
if (e.kind === 'revenue') { t.revenuePol += pol; t.revenueUsd += e.usd; } const rows = load().entries.filter(e => !wallet || e.wallet === wallet);
else if (e.kind === 'draw') { t.drawPol += pol; t.drawUsd += e.usd; } const t = { inPol: 0, outPol: 0, inUsd: 0, outUsd: 0, count: rows.length,
else t.transferPol += (e.dir === 'in' ? pol : -pol); // revenue and draws are the P&L numbers; transfers move the balance and nothing else
} revenuePol: 0, revenueUsd: 0, drawPol: 0, drawUsd: 0, transferPol: 0, costPol: 0, costUsd: 0 };
for (const k of Object.keys(t)) if (k !== 'count') t[k] = Math.round(t[k] * 1e6) / 1e6; for (const e of rows) {
return t; const pol = e.asset === 'POL' ? e.amount : 0;
} if (e.dir === 'in') { t.inPol += pol; t.inUsd += e.usd; } else { t.outPol += pol; t.outUsd += e.usd; }
if (e.kind === 'revenue') { t.revenuePol += pol; t.revenueUsd += e.usd; }
// earned (AdminPaid) + POL in - POL out = what should be sitting there. Any drift is a transfer else if (e.kind === 'draw') { t.drawPol += pol; t.drawUsd += e.usd; }
// nobody has written down yet, and naming the number is the whole point of this file. else if (e.kind === 'cost') { t.costPol += (e.dir === 'out' ? pol : -pol); t.costUsd += (e.dir === 'out' ? e.usd : -e.usd); }
function reconcile(earnedPol, actualPol, wallet) { else t.transferPol += (e.dir === 'in' ? pol : -pol);
const t = totals(wallet || 'feeA'); }
const expected = Math.round((Number(earnedPol || 0) + t.inPol - t.outPol) * 1e6) / 1e6; for (const k of Object.keys(t)) if (k !== 'count') t[k] = Math.round(t[k] * 1e6) / 1e6;
const actual = Math.round(Number(actualPol || 0) * 1e6) / 1e6; return t;
return { earnedPol: Number(earnedPol || 0), expected, actual, }
drift: Math.round((actual - expected) * 1e6) / 1e6, totals: t };
} // earned (AdminPaid) + POL in - POL out = what should be sitting there. Any drift is a transfer
// nobody has written down yet, and naming the number is the whole point of this file.
module.exports = { init, entries, put, remove, totals, reconcile, DIRS, ASSETS, KINDS, WALLETS }; function reconcile(earnedPol, actualPol, wallet) {
const t = totals(wallet || 'feeA');
const expected = Math.round((Number(earnedPol || 0) + t.inPol - t.outPol) * 1e6) / 1e6;
const actual = Math.round(Number(actualPol || 0) * 1e6) / 1e6;
return { earnedPol: Number(earnedPol || 0), expected, actual,
drift: Math.round((actual - expected) * 1e6) / 1e6, totals: t };
}
module.exports = { init, entries, put, remove, totals, reconcile, DIRS, ASSETS, KINDS, WALLETS, CATS, entriesFor: year => load().entries.filter(e => String(e.date || '').startsWith(String(year))) };
+11 -3
View File
@@ -453,8 +453,9 @@
<div class="tablewrap"><table class="adm-table" id="pnlLedger"></table></div> <div class="tablewrap"><table class="adm-table" id="pnlLedger"></table></div>
<div class="grid" style="grid-template-columns:repeat(auto-fit,minmax(130px,1fr));gap:8px;margin-top:12px"> <div class="grid" style="grid-template-columns:repeat(auto-fit,minmax(130px,1fr));gap:8px;margin-top:12px">
<select id="ldDir"><option value="in">Money in</option><option value="out">Money out</option></select> <select id="ldDir"><option value="in">Money in</option><option value="out">Money out</option></select>
<select id="ldKind"><option value="revenue">Revenue</option><option value="draw">Draw</option><option value="transfer">Transfer</option></select> <select id="ldKind"><option value="revenue">Revenue</option><option value="cost">Cost</option><option value="draw">Draw</option><option value="transfer">Transfer</option></select>
<select id="ldWallet"><option value="feeA">Receiver A</option><option value="feeB">Receiver B</option><option value="engine">Engine</option><option value="hunt">PolHunter</option></select> <select id="ldCat" hidden><option value="advertising">Advertising</option><option value="rewards">Player rewards</option><option value="software">Software and hosting</option><option value="other">Other cost</option></select>
<select id="ldWallet"><option value="feeA">Receiver A</option><option value="feeB">Receiver B</option><option value="engine">Engine</option><option value="hunt">PolHunter</option><option value="outside">Outside wallet</option></select>
<input type="number" id="ldAmount" min="0" step="0.0001" placeholder="Amount in POL"> <input type="number" id="ldAmount" min="0" step="0.0001" placeholder="Amount in POL">
<input type="number" id="ldUsd" min="0" step="0.01" placeholder="USD (optional)"> <input type="number" id="ldUsd" min="0" step="0.01" placeholder="USD (optional)">
<input type="date" id="ldDate"> <input type="date" id="ldDate">
@@ -464,6 +465,13 @@
<button class="btn small" type="button" id="ldAdd">Add line</button> <button class="btn small" type="button" id="ldAdd">Add line</button>
</div> </div>
</div> </div>
<div class="card">
<div class="card-head"><h3>Tax summary</h3><span class="sub">income versus advertising and other costs, for one year</span></div>
<p class="small muted" style="margin:0 0 10px">Income is the platform's share of every package sale, valued at that sale's own dollar price, plus outside revenue. Sales to your own positions are left out. Costs are the ledger's Cost lines; game wallet top-ups are recorded there automatically as Player rewards. Draws and transfers are your money, not expenses, so they are listed apart.</p>
<p><select id="taxYear"></select> <button class="btn small" type="button" id="taxRun">Show</button> <button class="btn small sec" type="button" id="taxCsv" hidden>Copy CSV for your accountant</button></p>
<div id="taxOut" class="small"></div>
<textarea id="taxCsvText" hidden rows="6" style="width:100%;margin-top:8px" readonly></textarea>
</div>
<div class="card"> <div class="card">
<div class="card-head"><h3>Automatic credit burner</h3><span class="sub">settles pending campaign spend on-chain from the engine wallet</span></div> <div class="card-head"><h3>Automatic credit burner</h3><span class="sub">settles pending campaign spend on-chain from the engine wallet</span></div>
<p class="small" id="burnerLine">…</p> <p class="small" id="burnerLine">…</p>
@@ -512,6 +520,6 @@
</div> </div>
<script src="/assets/common.js?v=20261003fr2"></script><script src="/assets/welcome.js?v=20260923b"></script> <script src="/assets/common.js?v=20261003fr2"></script><script src="/assets/welcome.js?v=20260923b"></script>
<script src="/assets/admin.js?v=20261002sd"></script> <script src="/assets/admin.js?v=20261004tax"></script>
</body> </body>
</html> </html>
+35 -4
View File
@@ -753,15 +753,16 @@
// The ledger: hand-entered movements the chain index cannot see, plus the reconciliation that // The ledger: hand-entered movements the chain index cannot see, plus the reconciliation that
// makes "earned" and "on hand" agree. A drift that will not go to zero is a transfer nobody // makes "earned" and "on hand" agree. A drift that will not go to zero is a transfer nobody
// wrote down (Marty, 2026-09-23). // wrote down (Marty, 2026-09-23).
const LD_KIND = { revenue: 'Revenue', draw: 'Draw', transfer: 'Transfer' }; const LD_KIND = { revenue: 'Revenue', draw: 'Draw', transfer: 'Transfer', cost: 'Cost' };
const LD_WALLET = { feeA: 'Receiver A', feeB: 'Receiver B', engine: 'Engine', hunt: 'PolHunter' }; const LD_CAT = { advertising: 'Advertising', rewards: 'Player rewards', software: 'Software and hosting', other: 'Other cost' };
const LD_WALLET = { feeA: 'Receiver A', feeB: 'Receiver B', engine: 'Engine', hunt: 'PolHunter', outside: 'Outside wallet' };
const pol4 = n => Number(n || 0).toLocaleString(undefined, { maximumFractionDigits: 4 }); const pol4 = n => Number(n || 0).toLocaleString(undefined, { maximumFractionDigits: 4 });
function renderLedger(r) { function renderLedger(r) {
const L = (r && r.ledger) || {}, rows = L.entries || [], t = L.totals || {}, rec = L.reconcile || {}; const L = (r && r.ledger) || {}, rows = L.entries || [], t = L.totals || {}, rec = L.reconcile || {};
if ($('pnlLedger')) { if ($('pnlLedger')) {
$('pnlLedger').innerHTML = '<tr><th>Date</th><th>Wallet</th><th>Kind</th><th>POL</th><th>What for</th><th></th></tr>' $('pnlLedger').innerHTML = '<tr><th>Date</th><th>Wallet</th><th>Kind</th><th>POL</th><th>What for</th><th></th></tr>'
+ (rows.length ? rows.map(e => '<tr><td>' + e.date + '</td><td>' + (LD_WALLET[e.wallet] || e.wallet) + '</td>' + (rows.length ? rows.map(e => '<tr><td>' + e.date + '</td><td>' + (LD_WALLET[e.wallet] || e.wallet) + '</td>'
+ '<td>' + (LD_KIND[e.kind] || e.kind) + '</td>' + '<td>' + (LD_KIND[e.kind] || e.kind) + (e.kind === 'cost' ? ' <span class="muted">(' + (LD_CAT[e.category] || e.category || 'other') + ')</span>' : '') + '</td>'
+ '<td' + (e.dir === 'out' ? ' style="color:var(--bad)"' : '') + '>' + (e.dir === 'out' ? '-' : '+') + pol4(e.amount) + '<td' + (e.dir === 'out' ? ' style="color:var(--bad)"' : '') + '>' + (e.dir === 'out' ? '-' : '+') + pol4(e.amount)
+ (e.usd ? ' <span class="muted">($' + Number(e.usd).toFixed(2) + ')</span>' : '') + '</td>' + (e.usd ? ' <span class="muted">($' + Number(e.usd).toFixed(2) + ')</span>' : '') + '</td>'
+ '<td>' + esc(e.note || '') + '</td>' + '<td>' + esc(e.note || '') + '</td>'
@@ -788,7 +789,7 @@
} }
} }
if ($('ldAdd')) $('ldAdd').addEventListener('click', async () => { if ($('ldAdd')) $('ldAdd').addEventListener('click', async () => {
const body = { dir: $('ldDir').value, kind: $('ldKind').value, wallet: $('ldWallet').value, const body = { dir: $('ldDir').value, kind: $('ldKind').value, category: $('ldCat') ? $('ldCat').value : '', wallet: $('ldWallet').value,
amount: Number($('ldAmount').value) || 0, usd: Number($('ldUsd').value) || 0, amount: Number($('ldAmount').value) || 0, usd: Number($('ldUsd').value) || 0,
date: $('ldDate').value, note: $('ldNote').value }; date: $('ldDate').value, note: $('ldNote').value };
try { try {
@@ -1013,3 +1014,33 @@
render(); render();
})(); })();
// ---- tax summary (2026-10-04) + the cost category picker
(function () {
const $ = id => document.getElementById(id);
if ($('ldKind') && $('ldCat')) { const sync = () => { $('ldCat').hidden = $('ldKind').value !== 'cost'; }; $('ldKind').addEventListener('change', sync); sync(); }
if (!$('taxYear')) return;
const y = new Date().getFullYear(); for (let v = y; v >= 2025; v--) { const o = document.createElement('option'); o.value = v; o.textContent = v; $('taxYear').appendChild(o); }
const money = n => '$' + Number(n || 0).toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 });
$('taxRun').addEventListener('click', async () => {
$('taxOut').textContent = 'Working it out...';
try {
const r = await (await fetch('/api/admin/tax?year=' + $('taxYear').value, { credentials: 'same-origin' })).json();
if (r.error) throw new Error(r.error);
const cats = Object.entries(r.expenses.byCategory || {}).map(([k, v]) => '<tr><td>' + (r.expenses.labels[k] || k) + '</td><td class="num">' + money(v) + '</td></tr>').join('');
$('taxOut').innerHTML = '<table class="adm-table"><tr><th colspan="2">' + r.year + '</th></tr>'
+ '<tr><td><b>Income</b>: platform share of ' + r.income.sales + ' package sales</td><td class="num">' + money(r.income.platformUsd) + '</td></tr>'
+ (r.income.outsideUsd ? '<tr><td>Outside revenue</td><td class="num">' + money(r.income.outsideUsd) + '</td></tr>' : '')
+ '<tr><td><b>Total income</b></td><td class="num"><b>' + money(r.income.totalUsd) + '</b></td></tr>'
+ (cats || '<tr><td>No costs recorded yet</td><td></td></tr>')
+ '<tr><td><b>Advertising and promotion</b> (advertising + player rewards)</td><td class="num"><b>' + money(r.expenses.advertisingAndPromotionUsd) + '</b></td></tr>'
+ '<tr><td><b>Total costs</b></td><td class="num"><b>' + money(r.expenses.totalUsd) + '</b></td></tr>'
+ '<tr><td><b>Net</b></td><td class="num"><b>' + money(r.netUsd) + '</b></td></tr></table>'
+ '<p class="muted">Left out: ' + money(r.income.ownSalesExcludedUsd) + ' of sales to your own positions (' + r.ownMemberIds.join(', ') + '); ' + r.draws + ' draws and ' + r.transfers + ' transfers (your money, not expenses).</p>';
$('taxCsvText').value = r.csv; $('taxCsv').hidden = false;
} catch (e) { $('taxOut').textContent = 'Could not build the summary: ' + e.message; }
});
$('taxCsv').addEventListener('click', async () => {
try { await navigator.clipboard.writeText($('taxCsvText').value); IAP.status('CSV copied. Paste it into a spreadsheet.', 'good'); }
catch (e) { $('taxCsvText').hidden = false; $('taxCsvText').select(); IAP.status('Selected. Copy it with your keyboard.', 'good'); }
});
})();
+45
View File
@@ -4127,6 +4127,51 @@ const server = http.createServer(async (req, res) => {
ledger: { entries: ledger.entries(), totals: ledger.totals('feeA'), ledger: { entries: ledger.entries(), totals: ledger.totals('feeA'),
reconcile: ledger.reconcile(pol(sum(admin, e => e.amountWei)), pol(BigInt(balances.feeA || '0')), '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 (p === '/api/admin/ledger' && req.method === 'POST') {
if (!isAdmin(req)) return json(res, 401, { error: 'auth' }); if (!isAdmin(req)) return json(res, 401, { error: 'auth' });
const b = await readBody(req); const b = await readBody(req);