Files
yourprogrambuilder/store.js
T
martbost a8a1a8eec7 YourProgramBuilder, the Seed Bed (Marty 2026-11-17: "keep fleshing it out"): STAGING build
Plant a program free (referral link with {id}, link check green / yellow / red, daily recheck, reports), members save their
referral IDs in its packet, a sponsor-first link (member page / ?r= / the hub sponsor line, then the planter), the sprout meter
to REVIEW_SAVES (DEFAULT 25) -> Marty's review queue -> approved packets exported for the CTB builder / DownlineHydra wild heads
with every saved ID. Dormant old programs confirmed by their owner, old-link redirects (oldrefs), Spotlight on YPBShop (NOT
deployed; DEFAULT $10 / 1,000 views, 20/5/5/5/5, company 60), verified views with Spotlight delivery, trust pack (ledger,
contract, toasts, Telegram card, terms / disclaimer / privacy, TrustClickz only), network footer row, chatbot, promo kit,
Guides, PolHunter slot, LinkSpin tracked-link and zone hooks, AI writer through the hub. Seed-catalog look from the approved
mockup. Tests: qa/unit.test.cjs 33/33, qa/e2e.mjs 121/121 on a local anvil chain.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 09:30:59 -06:00

150 lines
9.3 KiB
JavaScript

// YourProgramBuilder data. One document (ypb.json) holds members, sessions, Spotlight purchases (the chain's Purchase events), the
// watcher position, the ref tags of buyers and daily counters. The growing collections are row tables when the app runs on MySQL
// (docstore splits): packets (planted programs), saved IDs, reports, verified visits, verified clicks and Spotlight views (the
// delivery audit trail: one row per view counted). Without DOCSTORE_URL (local prototype + tests only) everything stays in the one
// file, written atomically. Marty's rule (2026-11-13): MySQL is the standard; never launch on files.
'use strict';
const fs = require('fs');
const path = require('path');
const crypto = require('crypto');
const cfgMod = require('./config');
const docstore = require('./docstore');
const DOC = 'ypb.json';
const SPLITS = [
{ doc: DOC, field: 'packets', table: 'ypb_packets', key: 'id', ts: 'createdAt' },
{ doc: DOC, field: 'saves', table: 'ypb_saves', key: 'id', ts: 'at' },
{ doc: DOC, field: 'reports', table: 'ypb_reports', key: 'id', ts: 'at' },
{ doc: DOC, field: 'visits', table: 'ypb_visits', key: 'id', ts: 'at' },
{ doc: DOC, field: 'clicks', table: 'ypb_clicks', key: 'id', ts: 'at' },
{ doc: DOC, field: 'sviews', table: 'ypb_sviews', key: 'id', ts: 'at' }
];
const TABLE = Object.fromEntries(SPLITS.map(s => [s.field, s]));
let S = null, saveT = null, rowMode = false;
const packetById = new Map(), saveById = new Map(), savesByPacket = new Map(), savesByOwner = new Map();
const FILE = () => path.join(cfgMod.get().dataDir, DOC);
const lc = v => String(v || '').toLowerCase();
function index() {
packetById.clear(); saveById.clear(); savesByPacket.clear(); savesByOwner.clear();
for (const p of S.packets) packetById.set(p.id, p);
for (const s of S.saves) indexSave(s);
}
function indexSave(s) {
saveById.set(s.id, s);
let l = savesByPacket.get(s.packetId); if (!l) savesByPacket.set(s.packetId, l = []); if (!l.includes(s)) l.push(s);
let o = savesByOwner.get(s.owner); if (!o) savesByOwner.set(s.owner, o = []); if (!o.includes(s)) o.push(s);
}
function unindexSave(s) {
saveById.delete(s.id);
const l = savesByPacket.get(s.packetId); if (l) { const i = l.indexOf(s); if (i >= 0) l.splice(i, 1); }
const o = savesByOwner.get(s.owner); if (o) { const i = o.indexOf(s); if (i >= 0) o.splice(i, 1); }
}
function load() {
try { S = JSON.parse(fs.readFileSync(FILE(), 'utf8')); } catch (e) { S = null; }
S = Object.assign({ v: 1, seq: { packet: 0, report: 0, visit: 0, click: 0, sview: 0 }, daily: {}, totals: { visits: 0, views: 0, clicks: 0, vclicks: 0, sviews: 0 },
members: {}, sessions: {}, purchases: {}, shop: {}, orderRef: {}, packets: [], saves: [], reports: [], visits: [], clicks: [], sviews: [] }, S || {});
rowMode = docstore.isOn();
if (rowMode) for (const sp of SPLITS) S[sp.field] = (docstore.rows(sp.table) || []).slice();
index();
const now = Date.now();
for (const [k, s] of Object.entries(S.sessions)) if (s.expires < now) delete S.sessions[k];
}
function save(now) {
if (saveT && !now) return;
const run = () => {
saveT = null;
try {
const out = rowMode ? Object.assign({}, S, Object.fromEntries(SPLITS.map(sp => [sp.field, []]))) : S;
const tmp = FILE() + '.tmp'; fs.writeFileSync(tmp, JSON.stringify(out), { mode: 0o600 }); fs.renameSync(tmp, FILE());
} catch (e) { console.error('store save failed', e.message); }
};
if (now) { clearTimeout(saveT); run(); } else saveT = setTimeout(run, 800);
}
function flush() { save(true); }
const state = () => S;
function putRow(field, item) { if (rowMode) { const sp = TABLE[field]; docstore.rowPut(sp.table, item[sp.key], item[sp.ts], item); } save(); }
function dropRows(field, ids) {
if (!ids.length) return;
const set = new Set(ids); S[field] = S[field].filter(x => !set.has(x[TABLE[field].key]));
if (rowMode) docstore.rowDel(TABLE[field].table, ids);
save();
}
function nextId(kind) { S.seq[kind] = (S.seq[kind] || 0) + 1; return S.seq[kind]; }
// ---- Central time (Marty: everything on US Central) ----
const fmt = new Intl.DateTimeFormat('en-CA', { timeZone: 'America/Chicago', year: 'numeric', month: '2-digit', day: '2-digit', weekday: 'short' });
function ctDay(ts) { const p = Object.fromEntries(fmt.formatToParts(new Date(ts || Date.now())).map(x => [x.type, x.value])); return p.year + '-' + p.month + '-' + p.day; }
function ctWeek(ts) {
const p = Object.fromEntries(fmt.formatToParts(new Date(ts || Date.now())).map(x => [x.type, x.value]));
const back = { Mon: 0, Tue: 1, Wed: 2, Thu: 3, Fri: 4, Sat: 5, Sun: 6 }[p.weekday] || 0;
return new Date(Date.UTC(Number(p.year), Number(p.month) - 1, Number(p.day) - back)).toISOString().slice(0, 10);
}
function bump(k, n) { const day = ctDay(); const d = S.daily[day] || (S.daily[day] = {}); d[k] = (d[k] || 0) + (n || 1); save(); }
function today() { return S.daily[ctDay()] || {}; }
// ---- packets (planted programs) ----
function packet(id) { return packetById.get(Number(id)) || null; }
function packets() { return S.packets; }
function addPacket(p) { p.id = nextId('packet'); p.createdAt = p.createdAt || Date.now(); p.updatedAt = Date.now(); S.packets.push(p); packetById.set(p.id, p); putRow('packets', p); return p; }
function savePacket(p) { p.updatedAt = Date.now(); putRow('packets', p); }
function packetsOf(owner) { const o = lc(owner); return S.packets.filter(p => p.owner === o && p.status !== 'removed'); }
// ---- saved IDs: one per member per packet. id = <packetId>|<wallet> ----
const saveKey = (packetId, owner) => Number(packetId) + '|' + lc(owner);
function saveOf(packetId, owner) { return saveById.get(saveKey(packetId, owner)) || null; }
function savesOf(packetId) { return savesByPacket.get(Number(packetId)) || []; }
function savesBy(owner) { return savesByOwner.get(lc(owner)) || []; }
function putSave(packetId, owner, patch) {
const id = saveKey(packetId, owner); let s = saveById.get(id);
if (!s) { s = { id, packetId: Number(packetId), owner: lc(owner), at: Date.now() }; S.saves.push(s); indexSave(s); }
Object.assign(s, patch || {}); s.updatedAt = Date.now(); putRow('saves', s); return s;
}
function dropSave(packetId, owner) { const s = saveOf(packetId, owner); if (!s) return false; unindexSave(s); dropRows('saves', [s.id]); return true; }
function saves() { return S.saves; }
// ---- reports (the report button) ----
function addReport(r) { r.id = 'r' + nextId('report'); r.at = Date.now(); S.reports.push(r); putRow('reports', r); return r; }
function saveReport(r) { putRow('reports', r); }
function reports() { return S.reports; }
// ---- verified visits / clicks / Spotlight views ----
function addVisit(v) { v.id = 'v' + nextId('visit'); v.at = v.at || Date.now(); S.visits.push(v); putRow('visits', v); return v; }
function addClick(c) { c.id = 'k' + nextId('click'); c.at = c.at || Date.now(); S.clicks.push(c); putRow('clicks', c); return c; }
function addSview(b) { b.id = 's' + nextId('sview'); b.at = b.at || Date.now(); S.sviews.push(b); putRow('sviews', b); return b; }
const visits = () => S.visits, clicks = () => S.clicks, sviews = () => S.sviews;
// visits + clicks: 15 days (the 24-hour checks and the weekly numbers); Spotlight views: 120 days (the delivery audit trail)
function prune() {
const now = Date.now(); let n = 0;
for (const [f, days] of [['visits', 15], ['clicks', 15], ['sviews', 120]]) { const cut = now - days * 86400000; const old = S[f].filter(x => x.at < cut).map(x => x.id); dropRows(f, old); n += old.length; }
return n;
}
// ---- members (keyed by wallet: sign-in is by wallet or the network sign-in, which always carries the wallet) ----
function member(addr) { return S.members[lc(addr)] || null; }
function upsertMember(addr, patch) {
const a = lc(addr);
const m = S.members[a] || (S.members[a] = { address: a, username: null, joinedAt: Date.now(), via: null, netOk: false });
Object.assign(m, patch || {}); m.lastSeen = Date.now(); save(); return m;
}
function memberByName(name) {
const n = lc(name); if (!n) return null;
for (const m of Object.values(S.members)) if (m.username && m.username.toLowerCase() === n) return m;
return null;
}
function memberByHub(id) { if (!id) return null; for (const m of Object.values(S.members)) if (m.hubId === id) return m; return null; }
function members() { return Object.values(S.members); }
// ---- sessions ----
const SESSION_TTL = 7 * 24 * 3600000;
function mintSession(address) { const token = crypto.randomBytes(32).toString('hex'); S.sessions[token] = { address: lc(address), expires: Date.now() + SESSION_TTL }; save(); return token; }
function session(token) { const s = token && S.sessions[token]; return s && s.expires > Date.now() ? Object.assign({ token }, s) : null; }
function dropSession(token) { delete S.sessions[token]; save(); }
function endSessions(match, before) { let n = 0; for (const [k, x] of Object.entries(S.sessions)) if (x.expires - SESSION_TTL <= before && match(x)) { delete S.sessions[k]; n++; } if (n) save(); return n; }
module.exports = { SPLITS, load, flush, save, state, ctDay, ctWeek, bump, today,
packet, packets, addPacket, savePacket, packetsOf, saveOf, savesOf, savesBy, putSave, dropSave, saves, saveKey,
addReport, saveReport, reports, addVisit, addClick, addSview, visits, clicks, sviews, prune,
member, upsertMember, memberByName, memberByHub, members, mintSession, session, dropSession, endSessions, SESSION_TTL };