panel: gifting action (provision-gift) + gift pill and datalist for member emails
The Send-gift control sits in the members-view toolbar: recipient email + name + inviting member (datalist of member emails), proxied to the portal's /admin/provision-gift which enforces the abuse rules and returns clear refusals. Gift rows carry the 'gift' pill in the Source column (inviter + expiry in the tooltip); the pre-built Guests section shows inviter, expiry, credits and ledger status as columns once the portal payload carries account_type.
This commit is contained in:
1 parent
2a6ec9301e
commit
4744a4fd31
2 files changed
+269
-4
No files matched your search
@@ -0,0 +1,133 @@
|
||||
// Harness for the admin panel's GUESTS list (gift accounts), run through the
|
||||
// skill's checker alongside the chart harness:
|
||||
// ~/.hermes/skills/research/inference-cooperative/scripts/check-page-js.sh \
|
||||
// app/main.py admin-panel-guests-harness.js
|
||||
// Exercises load() against both payload shapes — the portal's split payload
|
||||
// (guests[]) and an older payload that still tags rows account_type='gift'
|
||||
// inside members[] — and asserts the invariants that matter:
|
||||
// * guests NEVER count as members, in either shape;
|
||||
// * guests never render in the members table;
|
||||
// * the guests list shows recipient, inviter, credits remaining, expiry
|
||||
// and status, and hides entirely when there are no guests;
|
||||
// * the Members-view switch rule keeps the section's visibility handled
|
||||
// in switchView (the trap that stranded the Admin section on Models).
|
||||
// The checker evals in CommonJS (no top-level await), so the body is wrapped.
|
||||
const assert = (cond, msg) => { if (!cond) { console.error("FAIL: " + msg); process.exit(1); } };
|
||||
const count = (s, re) => (String(s).match(re) || []).length;
|
||||
const txt = (id) => String(document.getElementById(id).textContent); // stub keeps raw types; the DOM stringifies
|
||||
|
||||
const memberRow = (email, spend) => ({
|
||||
email, username: email.split("@")[0], active: true, activated: true,
|
||||
account_type: "member", spend, all_time_spend: spend * 10,
|
||||
balance: 15, credit_balance: 0, credits_remaining: 0, remaining: 15 - spend,
|
||||
});
|
||||
|
||||
async function runLoad(overview) {
|
||||
globalThis.fetch = async (url) => ({
|
||||
status: 200,
|
||||
json: async () => (String(url).indexOf("/api/overview") !== -1 ? overview : { models: [] }),
|
||||
});
|
||||
await load();
|
||||
}
|
||||
|
||||
(async () => {
|
||||
// ---- Shape 1: the portal splits guests into their own list ----
|
||||
await runLoad({
|
||||
members: [memberRow("alice@example.com", 2), memberRow("bob@example.com", 1)],
|
||||
guests: [{
|
||||
email: "friend@example.com", username: "friend", active: true,
|
||||
account_type: "gift", gift_inviter: "alice@example.com",
|
||||
credit_balance: 5, credits_remaining: 3.5,
|
||||
gift_expires_at: "2027-01-07T02:00:00", gift_status: "active",
|
||||
spend: 1.5, all_time_spend: 1.5,
|
||||
}],
|
||||
totals: { members: 2, total_spend: 4.5, total_all_time_spend: 45,
|
||||
operator_spend: 1, operator_all_time_spend: 10 },
|
||||
});
|
||||
assert(txt("tot-members") === "2",
|
||||
"split payload: member count is 2 (got " + txt("tot-members") + ")");
|
||||
assert(txt("tot-guests") === "1",
|
||||
"split payload: guests count is 1");
|
||||
assert(txt("tot-spend-cycle") === "$4.50",
|
||||
"split payload: spend total unchanged by the guests split");
|
||||
{
|
||||
const rowsHtml = document.getElementById("rows").innerHTML;
|
||||
assert(count(rowsHtml, /<tr>/g) === 2, "members table holds only the 2 members");
|
||||
assert(rowsHtml.indexOf("friend@example.com") === -1, "guest never renders in the members table");
|
||||
const g = document.getElementById("guest-rows").innerHTML;
|
||||
assert(count(g, /<tr>/g) === 1, "guests list holds exactly the 1 guest");
|
||||
assert(g.indexOf("friend@example.com") !== -1, "recipient email shown");
|
||||
assert(g.indexOf("alice@example.com") !== -1, "inviting member shown from the ledger");
|
||||
assert(g.indexOf("$3.50") !== -1, "credits remaining shown");
|
||||
assert(g.indexOf("2027-01-07") !== -1, "time-box expiry date shown");
|
||||
assert(/pill active[^>]*>active</.test(g), "status pill shows active");
|
||||
assert(document.getElementById("guests-section").style.display === "",
|
||||
"guests section visible when guests exist");
|
||||
}
|
||||
switchView("models");
|
||||
assert(document.getElementById("guests-section").style.display === "none",
|
||||
"guests section hides on the Models view (switchView owns visibility)");
|
||||
switchView("members");
|
||||
assert(document.getElementById("guests-section").style.display === "",
|
||||
"guests section returns on the Members view");
|
||||
|
||||
// ---- Shape 2: older payload — gifts tagged inside members[] ----
|
||||
await runLoad({
|
||||
members: [
|
||||
memberRow("alice@example.com", 2),
|
||||
memberRow("bob@example.com", 1),
|
||||
{ email: "friend@example.com", username: "friend", active: true,
|
||||
account_type: "gift", gift_inviter: "alice@example.com",
|
||||
credit_balance: 5, credits_remaining: 3.5, gift_expires_at: "2027-01-07T02:00:00",
|
||||
gift_status: "active", spend: 0.5, all_time_spend: 5 },
|
||||
],
|
||||
totals: { members: 3, total_spend: 3.5, total_all_time_spend: 35,
|
||||
operator_spend: 0, operator_all_time_spend: 0 },
|
||||
});
|
||||
assert(txt("tot-members") === "2",
|
||||
"old payload: gift row subtracted from the member count (got " + txt("tot-members") + ")");
|
||||
assert(txt("tot-guests") === "1", "old payload: guest derived and counted");
|
||||
assert(txt("tot-spend-cycle") === "$3.00",
|
||||
"old payload: guest spend excluded from the spend total (3.5 - 0.5)");
|
||||
assert(document.getElementById("rows").innerHTML.indexOf("friend@example.com") === -1,
|
||||
"old payload: guest still never renders in the members table");
|
||||
assert(document.getElementById("guest-rows").innerHTML.indexOf("friend@example.com") !== -1,
|
||||
"old payload: guest renders in the guests list");
|
||||
|
||||
// ---- Status vocabulary: expired and converted keep their own pills ----
|
||||
await runLoad({
|
||||
members: [memberRow("alice@example.com", 2)],
|
||||
guests: [
|
||||
{ email: "lapsed@example.com", username: null, active: false, account_type: "gift",
|
||||
gift_inviter: "alice@example.com", credit_balance: 2, credits_remaining: 2,
|
||||
gift_expires_at: "2026-12-01T00:00:00", gift_status: "expired", spend: 3, all_time_spend: 3 },
|
||||
{ email: "joined@example.com", username: "joined", active: true, account_type: "gift",
|
||||
gift_inviter: "alice@example.com", credit_balance: 1, credits_remaining: 1,
|
||||
gift_expires_at: null, gift_status: "converted", spend: 4, all_time_spend: 4 },
|
||||
],
|
||||
totals: { members: 1, total_spend: 2, total_all_time_spend: 20,
|
||||
operator_spend: 0, operator_all_time_spend: 0 },
|
||||
});
|
||||
{
|
||||
const g = document.getElementById("guest-rows").innerHTML;
|
||||
assert(/pill inactive[^>]*>expired</.test(g), "expired status renders as an inactive-class pill");
|
||||
assert(/pill org[^>]*>converted</.test(g), "converted status renders as a distinct pill");
|
||||
assert(g.indexOf("lapsed@example.com") !== -1, "expired guest still listed (status column carries it)");
|
||||
assert(g.indexOf("2026-12-01") !== -1, "expired guest keeps its expiry date");
|
||||
}
|
||||
|
||||
// ---- Empty list: the section disappears entirely ----
|
||||
await runLoad({
|
||||
members: [memberRow("alice@example.com", 2)],
|
||||
guests: [],
|
||||
totals: { members: 1, total_spend: 2, total_all_time_spend: 20,
|
||||
operator_spend: 0, operator_all_time_spend: 0 },
|
||||
});
|
||||
assert(document.getElementById("guest-rows").innerHTML === "", "no guests: list is empty");
|
||||
assert(document.getElementById("guests-section").style.display === "none",
|
||||
"no guests: the section is hidden");
|
||||
assert(txt("tot-members") === "1", "no guests: member count is the members alone");
|
||||
assert(txt("tot-guests") === "0", "no guests: counter reads 0");
|
||||
|
||||
console.log("GUESTS HARNESS OK: exclusion, both payload shapes, columns, visibility");
|
||||
})().catch((e) => { console.error("FAIL: " + (e && e.stack || e)); process.exit(1); });
|
||||
+136
-4
@@ -197,6 +197,31 @@ async def api_set_credits(request: Request):
|
||||
return JSONResponse({"error": e.detail}, status_code=e.status_code)
|
||||
|
||||
|
||||
@app.post("/api/provision-gift")
|
||||
async def api_provision_gift(request: Request):
|
||||
"""Provision a gift account via the portal's /admin/provision-gift.
|
||||
|
||||
The portal enforces the abuse rules (one gift per inviter per 30 days,
|
||||
one per recipient ever, active-member inviter) and returns a clear
|
||||
refusal — surfaced to the operator as-is.
|
||||
"""
|
||||
if not is_admin(request):
|
||||
return JSONResponse({"error": "forbidden"}, status_code=403)
|
||||
body = await request.json()
|
||||
email = (body.get("email") or "").strip().lower()
|
||||
name = (body.get("name") or "").strip()
|
||||
inviter = (body.get("inviter") or body.get("inviter_email") or "").strip().lower()
|
||||
if not email or "@" not in email:
|
||||
return JSONResponse({"error": "A valid recipient email is required"}, status_code=400)
|
||||
if not inviter or "@" not in inviter:
|
||||
return JSONResponse({"error": "The inviting member's email is required"}, status_code=400)
|
||||
try:
|
||||
return await portal_post("/admin/provision-gift",
|
||||
{"email": email, "name": name, "inviter": inviter})
|
||||
except HTTPException as e:
|
||||
return JSONResponse({"error": e.detail}, status_code=e.status_code)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# OIDC routes — authorization-code flow against Cloudron's OIDC provider.
|
||||
# Active only when the `oidc` addon is configured (CLOUDRON_OIDC_* present).
|
||||
@@ -290,6 +315,9 @@ PAGE_HTML = """<!DOCTYPE html>
|
||||
.pill.manual { background: #f1e8da; color: #a97a4a; }
|
||||
.pill.org { background: #e7edf5; color: #4a6a8a; }
|
||||
.pill.grace { background: #fdf3e3; color: #a97a2a; }
|
||||
.pill.gift { background: #efe7f2; color: #7a5a92; }
|
||||
#gift-group input { padding: 5px 8px; border: 1px solid var(--border); border-radius: 6px; font-size: 12px; width: 170px; }
|
||||
#gift-group input#gift-name { width: 120px; }
|
||||
/* Trends tab (charts). Colours come from the same vars as the rest of the
|
||||
panel; the SVG is inline so there is no chart library and no CDN. */
|
||||
.trend-controls { display: flex; gap: 22px; flex-wrap: wrap; margin: 14px 0 0; }
|
||||
@@ -355,6 +383,7 @@ PAGE_HTML = """<!DOCTYPE html>
|
||||
|
||||
<div class="totals">
|
||||
<div class="tot"><div class="num" id="tot-members">—</div><div class="lbl">members</div></div>
|
||||
<div class="tot"><div class="num" id="tot-guests">—</div><div class="lbl">guests — gift accounts</div><div class="sub">excluded from member counts</div></div>
|
||||
<div class="tot"><div class="num" id="tot-spend-cycle">—</div><div class="lbl">current balance used — members + co-op's own</div><div class="sub">co-op's own share: <span id="tot-spend-cycle-own">—</span></div></div>
|
||||
<div class="tot"><div class="num" id="tot-spend-all">—</div><div class="lbl">all-time spend — members + co-op's own</div><div class="sub">co-op's own share: <span id="tot-spend-all-own">—</span></div></div>
|
||||
</div>
|
||||
@@ -371,6 +400,14 @@ PAGE_HTML = """<!DOCTYPE html>
|
||||
<button class="range-btn active" id="mmode-balance" onclick="setMemberMode('balance')">Balance</button>
|
||||
<button class="range-btn" id="mmode-all" onclick="setMemberMode('all')">All time</button>
|
||||
</span>
|
||||
<span class="range-group" id="gift-group">
|
||||
<span class="range-label">Send gift</span>
|
||||
<input id="gift-email" type="email" placeholder="friend@example.com" list="member-email-list" autocomplete="off" />
|
||||
<input id="gift-name" type="text" placeholder="Their name" autocomplete="off" />
|
||||
<input id="gift-inviter" type="email" placeholder="Inviting member" list="member-email-list" autocomplete="off" />
|
||||
<datalist id="member-email-list"></datalist>
|
||||
<button class="range-btn" id="gift-send" onclick="sendGift()">Gift $5 access</button>
|
||||
</span>
|
||||
<span class="range-group" id="range-group" style="display:none;">
|
||||
<span class="range-label">Period</span>
|
||||
<button class="range-btn" id="range-30" onclick="setRange(30)">Last 30 days</button>
|
||||
@@ -398,6 +435,25 @@ PAGE_HTML = """<!DOCTYPE html>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
<div id="guests-section" style="display:none;">
|
||||
<h3 style="margin:20px 0 8px;">Guests</h3>
|
||||
<p style="color:var(--muted);font-size:12px;margin:0 0 8px;">Gift accounts — access an inviting member gave to someone outside the co-op. Not members — excluded from member counts; a gift lapses on its time box or when its credits are spent.</p>
|
||||
<div class="table-scroll">
|
||||
<table id="table-guests">
|
||||
<thead>
|
||||
<tr>
|
||||
<th>Recipient</th>
|
||||
<th>Invited by</th>
|
||||
<th>Credits remaining</th>
|
||||
<th>Expires</th>
|
||||
<th>Status</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody id="guest-rows"></tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div id="trends-section" style="display:none;">
|
||||
<div class="trend-controls">
|
||||
<span class="range-group">
|
||||
@@ -536,7 +592,21 @@ async function load() {
|
||||
// rather than left for the reader to guess.
|
||||
$('tot-spend-cycle-own').textContent = fmt(d.totals.operator_spend ?? 0);
|
||||
$('tot-spend-all-own').textContent = fmt(d.totals.operator_all_time_spend ?? 0);
|
||||
membersData = d.members || [];
|
||||
// Guests: gift accounts live in their own list and never count as members.
|
||||
// The portal splits them out (guests[]); an older payload that still tags
|
||||
// rows account_type='gift' inside members[] is derived here, so the member
|
||||
// count and the spend totals exclude guests in either payload shape.
|
||||
const allRows = d.members || [];
|
||||
const newShape = Array.isArray(d.guests);
|
||||
guestsData = newShape ? d.guests : allRows.filter(m => (m.account_type || 'member') === 'gift');
|
||||
membersData = newShape ? allRows : allRows.filter(m => (m.account_type || 'member') !== 'gift');
|
||||
const gSpend = guestsData.reduce((s, m) => s + (Number(m.spend) || 0), 0);
|
||||
const gAll = guestsData.reduce((s, m) => s + (Number(m.all_time_spend) || 0), 0);
|
||||
const t = d.totals || {};
|
||||
$('tot-members').textContent = newShape ? (t.members ?? membersData.length) : ((t.members ?? allRows.length) - guestsData.length);
|
||||
$('tot-guests').textContent = guestsData.length;
|
||||
$('tot-spend-cycle').textContent = fmt((t.total_spend ?? 0) - (newShape ? 0 : gSpend));
|
||||
$('tot-spend-all').textContent = fmt((t.total_all_time_spend ?? t.total_spend ?? 0) - (newShape ? 0 : gAll));
|
||||
adminsData = d.admins || [];
|
||||
agentsData = d.agents || [];
|
||||
if (currentView === 'members') renderMembers();
|
||||
@@ -997,6 +1067,7 @@ function renderMoneyDaily(host, rows) {
|
||||
|
||||
// ---- shared state ----
|
||||
let membersData = [];
|
||||
let guestsData = [];
|
||||
let adminsData = [];
|
||||
let agentsData = [];
|
||||
let modelsData = [];
|
||||
@@ -1028,6 +1099,7 @@ function switchView(view) {
|
||||
$('table-models').style.display = view === 'models' ? '' : 'none';
|
||||
// The Admin section is a members-view category; hide it in the Models view
|
||||
// (model usage already integrates admin spend into the totals).
|
||||
$('guests-section').style.display = view === 'members' ? '' : 'none';
|
||||
$('admins-section').style.display = view === 'members' ? '' : 'none';
|
||||
$('agents-section').style.display = view === 'members' ? '' : 'none';
|
||||
$('trends-section').style.display = view === 'trends' ? '' : 'none';
|
||||
@@ -1037,9 +1109,11 @@ function switchView(view) {
|
||||
$('tab-trends').className = 'tab-btn' + (view === 'trends' ? ' active' : '');
|
||||
$('tab-money').className = 'tab-btn' + (view === 'money' ? ' active' : '');
|
||||
$('view-title').textContent = view === 'members' ? 'Members' : (view === 'models' ? 'Model usage' : (view === 'trends' ? 'Trends' : 'Money'));
|
||||
// Mode groups: Balance/All-time for members; Period for models.
|
||||
// Mode groups: Balance/All-time for members; Period for models; the gift
|
||||
// action belongs to the members view too.
|
||||
$('range-group').style.display = view === 'models' ? '' : 'none';
|
||||
$('member-mode-group').style.display = view === 'members' ? '' : 'none';
|
||||
$('gift-group').style.display = view === 'members' ? '' : 'none';
|
||||
// Trends renders on first visit only, so the panel's initial load stays fast.
|
||||
if (view === 'trends') loadMetrics();
|
||||
// Money renders on first visit only, same rule: one fetch, then the
|
||||
@@ -1094,6 +1168,10 @@ function render() {
|
||||
}
|
||||
|
||||
function renderMembers() {
|
||||
// Datalist for the gift form's recipient/inviter fields: member emails the
|
||||
// operator can pick from (rebuilt per render; tiny).
|
||||
const dl = document.getElementById('member-email-list');
|
||||
if (dl) dl.innerHTML = membersData.map(m => '<option value="' + esc(m.email) + '"></option>').join('');
|
||||
const rows = [...membersData].sort((a, b) => {
|
||||
let va = a[memberSort.key], vb = b[memberSort.key];
|
||||
if (memberSort.key === 'spend') { va = memberSpend(a); vb = memberSpend(b); }
|
||||
@@ -1129,9 +1207,13 @@ function renderMembers() {
|
||||
const creditsCell = creditsShown > 0
|
||||
? fmt(creditsShown)
|
||||
: '<span style="color:var(--muted)">—</span>';
|
||||
const src = m.manual
|
||||
const src = m.account_type === 'gift'
|
||||
? '<span class="pill gift" title="' + esc('Gift account — from ' + (m.gift_inviter || '?') +
|
||||
' · expires ' + (m.gift_expires_at ? String(m.gift_expires_at).slice(0, 10) : '?') +
|
||||
' · $5 credit, no OC membership, never swept for dues') + '">gift</span>'
|
||||
: (m.manual
|
||||
? '<span class="pill manual" title="Manual member (no OC subscription; exempt from sweep)">manual</span>'
|
||||
: '<span class="pill active" title="Open Collective Membership subscription">OC</span>';
|
||||
: '<span class="pill active" title="Open Collective Membership subscription">OC</span>');
|
||||
// Effective Matrix handle: dashboard-set external MXID, else the local
|
||||
// @username:inference.coop identity (pending users have no username yet).
|
||||
// Account cell: username on top (prominent); email + Matrix handle beneath
|
||||
@@ -1164,6 +1246,29 @@ function renderMembers() {
|
||||
}).join('');
|
||||
clearArrows('members', memberSort);
|
||||
|
||||
// Guests — gift accounts in their own list, never in the members table or
|
||||
// the member count. Inviter and expiry come from the portal gifts ledger.
|
||||
const guestSection = document.getElementById('guests-section');
|
||||
if (guestsData.length) {
|
||||
guestSection.style.display = '';
|
||||
$('guest-rows').innerHTML = guestsData.map(g => {
|
||||
const top = g.username || g.email;
|
||||
const emailLine = g.username ? '<div style="color:var(--muted);font-size:11px">' + esc(g.email) + '</div>' : '';
|
||||
const credits = Number(g.credits_remaining ?? g.credit_balance ?? 0);
|
||||
const exp = g.gift_expires_at ? String(g.gift_expires_at).slice(0, 10) : '—';
|
||||
const st = String(g.gift_status || (g.active ? 'active' : 'inactive'));
|
||||
const stClass = st === 'active' ? 'active' : (st === 'converted' ? 'org' : 'inactive');
|
||||
const stTitle = { active: 'Gift live', converted: 'Gift became a member', expired: 'Time box elapsed', depleted: 'Credits spent' }[st] || '';
|
||||
return '<tr>' +
|
||||
'<td><strong>' + esc(top) + '</strong>' + emailLine + '</td>' +
|
||||
'<td>' + esc(g.gift_inviter || '—') + '</td>' +
|
||||
'<td class="num remaining-col">' + fmt(credits) + '</td>' +
|
||||
'<td>' + esc(exp) + '</td>' +
|
||||
'<td><span class="pill ' + stClass + '"' + (stTitle ? ' title="' + esc(stTitle) + '"' : '') + '>' + esc(st) + '</span></td>' +
|
||||
'</tr>';
|
||||
}).join('');
|
||||
} else { guestSection.style.display = 'none'; $('guest-rows').innerHTML = ''; }
|
||||
|
||||
// Agents/bots — real spend, not members. Rendered before the admin block, which
|
||||
// returns early when there are no operator accounts.
|
||||
const agentSection = document.getElementById('agents-section');
|
||||
@@ -1256,6 +1361,33 @@ async function addBalance(email) {
|
||||
} catch (e) { flash(e.message, false); }
|
||||
}
|
||||
|
||||
// Gift action: provision a $5 guest account for a friend of a member. The
|
||||
// portal enforces the abuse rules (one gift per inviter per 30 days, one per
|
||||
// recipient ever, inviter must be an active member) and reports a clear
|
||||
// refusal; the panel only collects the three fields.
|
||||
async function sendGift() {
|
||||
const email = ($('gift-email').value || '').trim();
|
||||
const name = ($('gift-name').value || '').trim();
|
||||
const inviter = ($('gift-inviter').value || '').trim();
|
||||
const btn = $('gift-send');
|
||||
if (!email || email.indexOf('@') < 1) { flash("Enter the recipient's email", false); return; }
|
||||
if (!inviter || inviter.indexOf('@') < 1) { flash("Enter the inviting member's email", false); return; }
|
||||
btn.disabled = true; btn.textContent = "Sending…";
|
||||
try {
|
||||
const r = await fetch('/api/provision-gift', {
|
||||
method: 'POST', headers: {'Content-Type': 'application/json'},
|
||||
body: JSON.stringify({ email, name, inviter })
|
||||
});
|
||||
const d = await r.json().catch(() => ({}));
|
||||
if (!r.ok || d.error) { flash(d.error || ('Gift failed (' + r.status + ')'), false); return; }
|
||||
flash('Gift sent — ' + email + ' has $5 of credits (expires in ' + (d.expires_in_days || 60) +
|
||||
' days). The welcome email is on its way.', true);
|
||||
$('gift-email').value = ''; $('gift-name').value = '';
|
||||
load();
|
||||
} catch (e) { flash('Gift failed: ' + e.message, false); }
|
||||
finally { btn.disabled = false; btn.textContent = 'Gift $5 access'; }
|
||||
}
|
||||
|
||||
load();
|
||||
loadModels();
|
||||
</script>
|
||||
|
||||
Reference in new issue
Block a user