@blamejs/blamejs-shop 0.3.71 → 0.3.72
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +2 -0
- package/README.md +1 -1
- package/lib/admin.js +254 -2
- package/lib/asset-manifest.json +1 -1
- package/lib/customer-segments.js +150 -0
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -8,6 +8,8 @@ upgrading across more than a few patches at a time.
|
|
|
8
8
|
|
|
9
9
|
## v0.3.x
|
|
10
10
|
|
|
11
|
+
- v0.3.72 (2026-06-05) — **Resend an order confirmation from the console, and export a segment's members as CSV.** Two operator actions land in the admin console. The order detail screen gains a Resend-confirmation action: buyer emails are stored only as one-way hashes, so the original address cannot be recovered — the operator types the recipient (from the customer's own request), and a fresh receipt rendered from the stored order is sent, rate-bounded to three per order per hour, with every send audited and the recipient kept out of the audit trail. The action appears only when a mailer is configured. Customer segments gain a members CSV export that streams id, display name, segment join date, and order count — deliberately no email column, since addresses are not stored in readable form; the file says so in a leading comment, cell values are quoted and spreadsheet-formula-neutralized, and the stream is written batch by batch so a large segment never buffers in memory. **Added:** *Resend order confirmation* — POST /admin/orders/:id/resend-confirmation sends a fresh receipt for the stored order to an operator-supplied address, since the buyer's email exists only as a hash and cannot be recovered — the recipient comes from the customer's own "I didn't get it" request. Rate-bounded to three sends per order per hour, audited without recording the recipient, gated on a configured mailer (the panel renders an honest disabled note otherwise), and validated for address shape. · *Segment members CSV export* — GET /admin/segments/:slug/members.csv streams a segment's members — customer id, display name, join date, order count — in keyset-paginated batches with RFC 4180 quoting and spreadsheet-formula-injection neutralization. There is no email column: addresses are stored hashed, and both the screen copy and a leading CSV comment state it. Unknown segments return 404 before any bytes stream; an archived segment yields a well-formed header-only file; each export is audited.
|
|
12
|
+
|
|
11
13
|
- v0.3.71 (2026-06-05) — **Vendored blamejs framework refreshed from v0.14.19 to v0.14.21.** The storefront runs on a vendored copy of the blamejs framework; this refreshes it across two upstream patch releases. The most operator-relevant upstream changes for this shop: the OAuth client — which Sign in with Google and Apple compose — gains RFC 9396 Rich Authorization Request validation and attestation-based client authentication primitives, and refuses token grants an identity provider broadened beyond what was requested; HEAD requests now conform by carrying no response body; the sealed-field store gains an unseal rate cap; and a framework-wide sweep ensures every accepted option is actually read, surfacing configuration typos that were previously silent. The remaining upstream changes are in framework areas the storefront does not expose (SCIM bulk operations, OID4VCI credential proofs, DMARC forensic-report parsing). The storefront's own behavior is unchanged, verified by the full test suite — including the regression guards that pin the CSRF origin posture, the referrer policy, and the payment-processor TLS agent against vendor drift — and the vendored-tree integrity manifest was re-stamped as part of the refresh. **Changed:** *Updated the vendored framework to blamejs v0.14.21* — The vendored framework moves from v0.14.19 to v0.14.21 (two upstream patch releases of fixes and additive, opt-in changes). Notable for this shop: hardened OAuth client validation behind federated sign-in, HTTP HEAD conformance, a sealed-field unseal rate cap, and boot-time validation of previously-unread options. The integrity manifest over the vendored tree was re-stamped as part of the refresh.
|
|
12
14
|
|
|
13
15
|
- v0.3.70 (2026-06-05) — **An Analytics screen in the admin console: funnel, search terms, and product views.** The admin console gains a read-only Analytics screen at /admin/analytics showing the pre-purchase signal the sales report cannot see: the browse-to-buy funnel (product views to cart adds to checkout starts to completed orders) with a conversion rate, top search terms, most-viewed products, top SKUs ranked by units sold, and a revenue-by-day sparkline. It complements rather than duplicates the existing Reports screen — revenue totals stay there, and the two screens link to each other. The same path answers a bearer-token request with JSON, and three JSON endpoints expose the funnel, search terms, and viewed products individually for tooling. Every aggregate is window-bounded (one year maximum, thirty-day default) and limit-bounded; the screen adds no write path anywhere. **Added:** *Read-only analytics dashboard* — The analytics primitive's aggregates are now wired into the console: a date-windowed view with the conversion funnel, top search terms, most-viewed products, units-ranked top SKUs, recent revenue trend, and cross-links with the Reports screen. The HTML view degrades a malformed date window to the default with a notice; the JSON surfaces reject it with a 400. Limits clamp to the primitive's own bounds, a refund-heavy window renders a signed negative total instead of failing, and every operator- or customer-derived string on the screen is escaped. The screen appears in the navigation only when the primitive is wired.
|
package/README.md
CHANGED
|
@@ -97,7 +97,7 @@ Every primitive is composed on the vendored blamejs surface — no npm runtime d
|
|
|
97
97
|
| **`lib/giftcards.js`** | Prepaid bearer gift cards. `issue({ amount_minor, currency })` generates a 16-char code (32-glyph alphabet, no ambiguous letters) via `b.crypto.generateBytes`, stores only its `namespaceHash` digest + a 4-char hint, and returns the plaintext code once. `balance(code)` / `lookup(code)` resolve a code to its live balance (constant-time hash compare); `redeem({ code, order_id, amount_minor })` decrements the balance with an atomic `balance >= amount` SQL guard so concurrent spends can't overdraw. Redeemed at checkout as a credit against the order grand total: the amount due drops by the applied balance (never below zero), the order still records the full total it owed, and the debit is recorded once per order — a card that fully covers the order is marked paid with no Stripe charge. Customers check a balance at `GET /gift-cards`; the page is not a code-existence oracle (unknown / malformed / expired all return the same generic not-found). |
|
|
98
98
|
| **`lib/gift-card-ledger.js`** | Append-only credit / debit / expire history per gift card, with a denormalized `balance_after_minor` snapshot for O(1) balance reads. `credit` / `debit` / `expire` write one row each; `history(id)` paginates a card's transactions; `transactionsForOrder(id)` lists a card's movements for one order. The audit trail behind the admin gift-card ledger console; overdraft is refused at the primitive layer. |
|
|
99
99
|
| **`lib/newsletter.js`** | Operator-collected email broadcast list — `signup({ email, source })` composes `b.guardEmail` for shape validation, `b.crypto.namespaceHash` for the dedup key, and `INSERT OR IGNORE` for idempotency. Storefront POST `/newsletter` route renders a designed thank-you card with separate copy for the `new` vs `dedup` branches. |
|
|
100
|
-
| **`lib/admin.js`** | Bearer-token-gated CRUD over catalog + orders + refunds + bulk CSV import + subscription plans + review moderation + return moderation. Token compared via `b.crypto.timingSafeEqual`. Errors as RFC 9457 problem documents via `b.problemDetails`. Audit emission on every mutation. Also serves a **browser admin console**: sign in at `/admin` by pasting the API key (sealed `shop_admin` session cookie, SameSite=Strict, /admin-scoped), with a persistent nav across every signed-in page. A guided **setup wizard** at `/admin/setup` writes shop identity to config; **Products** (`/admin/products`) browses the catalog and creates / archives / restores, and each product opens a management screen that edits its fields, adds / edits / removes variants, sets a variant's price and shows its price history, and attaches / uploads / removes images — the full path to a sellable product; **Inventory** (`/admin/inventory`) lists stock per SKU (on-hand / held / available) with a low-stock filter, restocks, sets per-SKU thresholds, and tracks new SKUs; **Orders** (`/admin/orders`) lists recent orders with status filters, opens an order's items, totals, and shipping address, and drives the lifecycle (mark paid → fulfil → ship → deliver, cancel — Refund goes through the payment provider) through the order FSM, and attaches a shipment (carrier + tracking number) with recorded shipment events that surface a public tracking link to the customer; **Customers** (`/admin/customers`) is a read-only roster, newest first — display name, short id, join date, sign-in method (passkey count + linked OAuth providers), and order count, with the count and sign-in methods resolved by bounded aggregate queries so a page of customers costs no per-row trips (email addresses aren't stored in the clear, so they're not shown); **Returns** (`/admin/returns`) is the RMA moderation queue — filter by status, open a request's items and reason, and approve (with refund amount) → mark received → refund, or reject with a reason, over the return FSM; **Reviews** (`/admin/reviews`) is the review moderation queue — filter by status and publish, reject (with a reason), or take down each submission inline; **Q&A** (`/admin/questions`) is the question moderation queue — filter by status, open a question to its full answer thread, approve / reject the question, post the seller answer, and approve / reject / pin individual answers; **Subscriptions** (`/admin/subscription-plans`) is the recurring-offer catalog — filter active / archived, create a plan (Stripe price id, interval, amount, trial), and archive one, with archiving terminal because the mirrored Stripe price can go stale; **Collections** (`/admin/collections`) manages manual + smart product collections — filter active / archived, create a collection (manual or smart with a starter rule), and per collection edit title / description / sort strategy, manage manual members (add by product id, remove, reorder) or edit a smart collection's rule set with a live preview of the products the rules currently match, and archive; **Gift cards** (`/admin/gift-cards`) is the gift-card ledger — list issued cards (masked code, original + remaining balance, status, issued date) filtered by lifecycle status, issue a new card (the bearer code shown once, right after creation), open a card to see its full credit / debit / expire ledger, and void an active card through a confirmation step; **Webhooks** (`/admin/webhooks`) registers outbound endpoints (https:// only) with a one-time signing-secret reveal, enables / disables / deletes them, and opens an endpoint's delivery feed to retry a failed delivery — the signing secret is shown once on create and never in the list, and order transitions fan out signed deliveries to subscribed endpoints. **Tax** (`/admin/tax-rates`), **Shipping** (`/admin/shipping`), and **Discounts** (`/admin/discounts`) configure tax rates per jurisdiction, shipping zones + rates, and automatic-discount rules — including code-unlocked rules a shopper redeems with a discount code on the cart page — + coupon-stacking policies — create / edit / archive each. **Audit** (`/admin/audit`) is a read-only activity log of every privileged action — filtered by outcome (success / failure / denied) and paginated — composed on the framework's tamper-evident `b.audit` chain; opening it is itself recorded as an `audit.read` event. **Errors** (`/admin/errors`) lists captured server-error detail — time, status, route, and a truncated message for scrubbed 500-class failures (checkout confirm, public API, admin actions) — newest-first, with the same path answering a bearer-token request with JSON so the log is one `curl` away. **Analytics** (`/admin/analytics`) is the pre-purchase view the sales report can't see — browse-to-buy funnel with conversion rate, top search terms, most-viewed products, units-ranked top SKUs, and a revenue-by-day sparkline — cross-linked with the Reports screen, read-only, every aggregate window- and limit-bounded. The Customers, Returns, Reviews, Q&A, Subscriptions, Collections, Gift cards, Webhooks, Tax, Shipping, Discounts, Delivery estimates, Analytics, and Errors links appear only when those primitives are wired. Each console path content-negotiates: a bearer-token client still gets the JSON API unchanged, a signed-in browser gets HTML. Reachable by the cookie or the bearer token. The console's styling is an external, integrity-pinned stylesheet (`themes/default/assets/css/admin.css`) with the same self-hosted typeface — no inline styles and no third-party font host, so it renders correctly under the strict `style-src 'self'` / `font-src 'self'` CSP that governs the route. |
|
|
100
|
+
| **`lib/admin.js`** | Bearer-token-gated CRUD over catalog + orders + refunds + bulk CSV import + subscription plans + review moderation + return moderation. Token compared via `b.crypto.timingSafeEqual`. Errors as RFC 9457 problem documents via `b.problemDetails`. Audit emission on every mutation. Also serves a **browser admin console**: sign in at `/admin` by pasting the API key (sealed `shop_admin` session cookie, SameSite=Strict, /admin-scoped), with a persistent nav across every signed-in page. A guided **setup wizard** at `/admin/setup` writes shop identity to config; **Products** (`/admin/products`) browses the catalog and creates / archives / restores, and each product opens a management screen that edits its fields, adds / edits / removes variants, sets a variant's price and shows its price history, and attaches / uploads / removes images — the full path to a sellable product; **Inventory** (`/admin/inventory`) lists stock per SKU (on-hand / held / available) with a low-stock filter, restocks, sets per-SKU thresholds, and tracks new SKUs; **Orders** (`/admin/orders`) lists recent orders with status filters, opens an order's items, totals, and shipping address, and drives the lifecycle (mark paid → fulfil → ship → deliver, cancel — Refund goes through the payment provider) through the order FSM, with a rate-bounded resend of the order confirmation to an operator-supplied address (the buyer's email is stored only as a hash, so the operator types the recipient), and attaches a shipment (carrier + tracking number) with recorded shipment events that surface a public tracking link to the customer; **Customers** (`/admin/customers`) is a read-only roster, newest first — display name, short id, join date, sign-in method (passkey count + linked OAuth providers), and order count, with the count and sign-in methods resolved by bounded aggregate queries so a page of customers costs no per-row trips (email addresses aren't stored in the clear, so they're not shown); customer segments export their members as a streamed CSV — id, display name, join date, order count, deliberately no email column; **Returns** (`/admin/returns`) is the RMA moderation queue — filter by status, open a request's items and reason, and approve (with refund amount) → mark received → refund, or reject with a reason, over the return FSM; **Reviews** (`/admin/reviews`) is the review moderation queue — filter by status and publish, reject (with a reason), or take down each submission inline; **Q&A** (`/admin/questions`) is the question moderation queue — filter by status, open a question to its full answer thread, approve / reject the question, post the seller answer, and approve / reject / pin individual answers; **Subscriptions** (`/admin/subscription-plans`) is the recurring-offer catalog — filter active / archived, create a plan (Stripe price id, interval, amount, trial), and archive one, with archiving terminal because the mirrored Stripe price can go stale; **Collections** (`/admin/collections`) manages manual + smart product collections — filter active / archived, create a collection (manual or smart with a starter rule), and per collection edit title / description / sort strategy, manage manual members (add by product id, remove, reorder) or edit a smart collection's rule set with a live preview of the products the rules currently match, and archive; **Gift cards** (`/admin/gift-cards`) is the gift-card ledger — list issued cards (masked code, original + remaining balance, status, issued date) filtered by lifecycle status, issue a new card (the bearer code shown once, right after creation), open a card to see its full credit / debit / expire ledger, and void an active card through a confirmation step; **Webhooks** (`/admin/webhooks`) registers outbound endpoints (https:// only) with a one-time signing-secret reveal, enables / disables / deletes them, and opens an endpoint's delivery feed to retry a failed delivery — the signing secret is shown once on create and never in the list, and order transitions fan out signed deliveries to subscribed endpoints. **Tax** (`/admin/tax-rates`), **Shipping** (`/admin/shipping`), and **Discounts** (`/admin/discounts`) configure tax rates per jurisdiction, shipping zones + rates, and automatic-discount rules — including code-unlocked rules a shopper redeems with a discount code on the cart page — + coupon-stacking policies — create / edit / archive each. **Audit** (`/admin/audit`) is a read-only activity log of every privileged action — filtered by outcome (success / failure / denied) and paginated — composed on the framework's tamper-evident `b.audit` chain; opening it is itself recorded as an `audit.read` event. **Errors** (`/admin/errors`) lists captured server-error detail — time, status, route, and a truncated message for scrubbed 500-class failures (checkout confirm, public API, admin actions) — newest-first, with the same path answering a bearer-token request with JSON so the log is one `curl` away. **Analytics** (`/admin/analytics`) is the pre-purchase view the sales report can't see — browse-to-buy funnel with conversion rate, top search terms, most-viewed products, units-ranked top SKUs, and a revenue-by-day sparkline — cross-linked with the Reports screen, read-only, every aggregate window- and limit-bounded. The Customers, Returns, Reviews, Q&A, Subscriptions, Collections, Gift cards, Webhooks, Tax, Shipping, Discounts, Delivery estimates, Analytics, and Errors links appear only when those primitives are wired. Each console path content-negotiates: a bearer-token client still gets the JSON API unchanged, a signed-in browser gets HTML. Reachable by the cookie or the bearer token. The console's styling is an external, integrity-pinned stylesheet (`themes/default/assets/css/admin.css`) with the same self-hosted typeface — no inline styles and no third-party font host, so it renders correctly under the strict `style-src 'self'` / `font-src 'self'` CSP that governs the route. |
|
|
101
101
|
| **`lib/catalog-import.js`** | Bulk CSV import — `POST /admin/catalog/import` accepts a `text/csv` body, parses via `b.csv`, content-safety-filters every cell through `b.guardCsv` (formula-injection / bidi / control / dangerous-function denylist), validates exact header order, de-dupes rows by `product_slug`, returns per-row errors without aborting. Default 1 MiB / 10000 rows caps. |
|
|
102
102
|
| **`lib/theme.js`** | File-backed templates with fallback chain. Operators register a named theme under `<themesDir>/<name>/*.html` and the storefront dispatches every renderer through it. `assetUrl(path)` resolves to `/assets/themes/<name>/<path>`. The shipped `default` theme is the fallback. |
|
|
103
103
|
|
package/lib/admin.js
CHANGED
|
@@ -524,6 +524,7 @@ function mount(router, deps) {
|
|
|
524
524
|
var catalog = deps.catalog;
|
|
525
525
|
var order = deps.order;
|
|
526
526
|
var payment = deps.payment || null; // refund endpoints disabled when absent
|
|
527
|
+
var mailer = deps.mailer || null; // transactional email factory (lib/email.js) — resend-confirmation disabled when absent
|
|
527
528
|
var _checkout = deps.checkout || null; // reserved — future webhook handler wiring
|
|
528
529
|
var r2 = deps.r2_bridge || null; // media-upload endpoint disabled when absent
|
|
529
530
|
var assetPrefix = typeof deps.asset_prefix === "string" ? deps.asset_prefix : "/assets/";
|
|
@@ -1781,6 +1782,14 @@ function mount(router, deps) {
|
|
|
1781
1782
|
// wired (its route is mounted only then).
|
|
1782
1783
|
can_receipt: !!printReceipts,
|
|
1783
1784
|
can_packing_slip: !!packingSlips,
|
|
1785
|
+
// Resend the order-confirmation email. The route mounts only when a
|
|
1786
|
+
// transactional mailer is wired; absent one the panel renders a
|
|
1787
|
+
// disabled note (mailer-gated, like the document links). The buyer's
|
|
1788
|
+
// plaintext address is never stored (the order keeps only the email
|
|
1789
|
+
// hash), so the form takes an operator-supplied recipient.
|
|
1790
|
+
can_resend_confirmation: !!mailer,
|
|
1791
|
+
resent: url && url.searchParams.get("resent"),
|
|
1792
|
+
resend_error: url && url.searchParams.get("resend_err"),
|
|
1784
1793
|
// Per-shipment carrier-label record form + split-shipment planner —
|
|
1785
1794
|
// each renders only when its primitive is wired (routes mount only
|
|
1786
1795
|
// then). Label carrier/package/broker enums drive the form selects.
|
|
@@ -2744,6 +2753,153 @@ function mount(router, deps) {
|
|
|
2744
2753
|
},
|
|
2745
2754
|
));
|
|
2746
2755
|
|
|
2756
|
+
// ---- resend order confirmation --------------------------------------
|
|
2757
|
+
//
|
|
2758
|
+
// Re-send the order-receipt email a customer asks for ("I never got my
|
|
2759
|
+
// confirmation"). The original receipt is sent by the payment provider
|
|
2760
|
+
// at confirm time (Stripe `receipt_email`) using the plaintext address
|
|
2761
|
+
// the buyer typed — that address is NEVER persisted: the order row keeps
|
|
2762
|
+
// only `customer_email_hash`, and the customers table keeps only
|
|
2763
|
+
// `email_hash`. A one-way hash can't be reversed into a deliverable
|
|
2764
|
+
// address, so this action can't recover the original recipient. It
|
|
2765
|
+
// therefore takes the recipient the OPERATOR supplies (they have it from
|
|
2766
|
+
// the support request) and sends a fresh receipt rendered from the stored
|
|
2767
|
+
// order totals. The email-hashing stance is unchanged — we never
|
|
2768
|
+
// reconstruct an address from a hash.
|
|
2769
|
+
//
|
|
2770
|
+
// Mounted only when a transactional mailer is wired (`deps.mailer`,
|
|
2771
|
+
// lib/email.js). Absent one the detail panel shows a disabled note.
|
|
2772
|
+
//
|
|
2773
|
+
// Rate-bound per order via the audit chain itself — no new column. Before
|
|
2774
|
+
// sending, we count this order's prior `order.receipt.resend` audit rows
|
|
2775
|
+
// inside the trailing hour; past the cap the send is refused. The audit
|
|
2776
|
+
// chain is append-only + tamper-evident, so the counter can't be quietly
|
|
2777
|
+
// reset.
|
|
2778
|
+
if (mailer && typeof mailer.orderReceipt === "function") {
|
|
2779
|
+
var RESEND_WINDOW_MS = b.constants.TIME.hours(1);
|
|
2780
|
+
var RESEND_MAX_PER_HR = 3;
|
|
2781
|
+
// Per-order sliding window of recent resend timestamps, scoped to this
|
|
2782
|
+
// admin mount. A plain in-memory map keyed by order id — the rate bound
|
|
2783
|
+
// is a soft abuse guard (stop an operator hammering "resend" at a
|
|
2784
|
+
// customer's inbox), not a security control, so an in-process window is
|
|
2785
|
+
// the right weight: no audit-chain read on the hot path, deterministic
|
|
2786
|
+
// under burst, and a process restart simply clears the soft window
|
|
2787
|
+
// (every resend is still durably recorded in the audit chain for
|
|
2788
|
+
// forensics). Stale order entries are pruned lazily on each check so the
|
|
2789
|
+
// map can't grow unbounded.
|
|
2790
|
+
var _resendWindow = Object.create(null);
|
|
2791
|
+
|
|
2792
|
+
function _recentResendCount(orderId, nowTs) {
|
|
2793
|
+
var cutoff = nowTs - RESEND_WINDOW_MS;
|
|
2794
|
+
var arr = _resendWindow[orderId];
|
|
2795
|
+
if (!arr) return 0;
|
|
2796
|
+
var kept = [];
|
|
2797
|
+
for (var i = 0; i < arr.length; i += 1) {
|
|
2798
|
+
if (arr[i] > cutoff) kept.push(arr[i]);
|
|
2799
|
+
}
|
|
2800
|
+
if (kept.length) _resendWindow[orderId] = kept;
|
|
2801
|
+
else delete _resendWindow[orderId];
|
|
2802
|
+
return kept.length;
|
|
2803
|
+
}
|
|
2804
|
+
|
|
2805
|
+
function _recordResendTimestamp(orderId, nowTs) {
|
|
2806
|
+
var arr = _resendWindow[orderId] || (_resendWindow[orderId] = []);
|
|
2807
|
+
arr.push(nowTs);
|
|
2808
|
+
}
|
|
2809
|
+
|
|
2810
|
+
// Resolve the display name for the receipt greeting. A linked customer
|
|
2811
|
+
// record carries a display_name; a guest order has none. The plaintext
|
|
2812
|
+
// email is operator-supplied (never stored), so only the name is read
|
|
2813
|
+
// from the order's customer link.
|
|
2814
|
+
async function _receiptName(o) {
|
|
2815
|
+
if (!o.customer_id || !customers) return "there";
|
|
2816
|
+
try {
|
|
2817
|
+
var c = await customers.get(o.customer_id);
|
|
2818
|
+
return (c && c.display_name) || "there";
|
|
2819
|
+
} catch (_e) { return "there"; }
|
|
2820
|
+
}
|
|
2821
|
+
|
|
2822
|
+
// Send the receipt for an order to an operator-supplied address. Throws
|
|
2823
|
+
// a TypeError on a bad address / rate-limit refusal so both the JSON and
|
|
2824
|
+
// browser paths can map it to a clean 4xx / err redirect; any genuine
|
|
2825
|
+
// mailer fault propagates.
|
|
2826
|
+
async function _resendReceipt(o, toRaw) {
|
|
2827
|
+
var to = typeof toRaw === "string" ? toRaw.trim() : "";
|
|
2828
|
+
if (!to || !/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(to) || to.length > 254) {
|
|
2829
|
+
var e = new TypeError("admin.order.resend: a valid recipient email is required");
|
|
2830
|
+
e.code = "RESEND_BAD_EMAIL";
|
|
2831
|
+
throw e;
|
|
2832
|
+
}
|
|
2833
|
+
var nowTs = Date.now();
|
|
2834
|
+
var recent = _recentResendCount(o.id, nowTs);
|
|
2835
|
+
if (recent >= RESEND_MAX_PER_HR) {
|
|
2836
|
+
var rl = new TypeError("admin.order.resend: resend limit reached for this order — try again later");
|
|
2837
|
+
rl.code = "RESEND_RATE_LIMITED";
|
|
2838
|
+
throw rl;
|
|
2839
|
+
}
|
|
2840
|
+
// Reserve the slot BEFORE awaiting the mailer: concurrent resend
|
|
2841
|
+
// POSTs for the same order would otherwise all read the same
|
|
2842
|
+
// pre-send count and pass the limit together while the first send
|
|
2843
|
+
// is still in flight. A mailer failure releases the reservation so
|
|
2844
|
+
// a failed send doesn't consume the operator's budget.
|
|
2845
|
+
_recordResendTimestamp(o.id, nowTs);
|
|
2846
|
+
try {
|
|
2847
|
+
var name = await _receiptName(o);
|
|
2848
|
+
await mailer.orderReceipt({ order: o, customer: { email: to, name: name } });
|
|
2849
|
+
} catch (sendErr) {
|
|
2850
|
+
var arr = _resendWindow[o.id];
|
|
2851
|
+
if (arr) {
|
|
2852
|
+
var idx = arr.indexOf(nowTs);
|
|
2853
|
+
if (idx !== -1) arr.splice(idx, 1);
|
|
2854
|
+
if (!arr.length) delete _resendWindow[o.id];
|
|
2855
|
+
}
|
|
2856
|
+
throw sendErr;
|
|
2857
|
+
}
|
|
2858
|
+
return { to: to };
|
|
2859
|
+
}
|
|
2860
|
+
|
|
2861
|
+
// The send is audited via the hot-path `safeEmit` (drop-silent, like
|
|
2862
|
+
// every other admin mutation) — the recipient is operator-supplied PII
|
|
2863
|
+
// and is deliberately kept OUT of the metadata; the row records only
|
|
2864
|
+
// that a resend happened for this order id.
|
|
2865
|
+
router.post("/admin/orders/:id/resend-confirmation", _pageOrApi(false,
|
|
2866
|
+
W("order.receipt.resend", async function (req, res) {
|
|
2867
|
+
var o = await order.get(req.params.id);
|
|
2868
|
+
if (!o) return _problem(res, 404, "order-not-found");
|
|
2869
|
+
var body = req.body || {};
|
|
2870
|
+
try { await _resendReceipt(o, body.email || body.to); }
|
|
2871
|
+
catch (e) {
|
|
2872
|
+
if (e instanceof TypeError) {
|
|
2873
|
+
var code = e.code === "RESEND_RATE_LIMITED" ? 429 : 400;
|
|
2874
|
+
return _problem(res, code, e.code === "RESEND_RATE_LIMITED" ? "resend-rate-limited" : "bad-request", e.message);
|
|
2875
|
+
}
|
|
2876
|
+
throw e;
|
|
2877
|
+
}
|
|
2878
|
+
_json(res, 200, { id: o.id, resent: true });
|
|
2879
|
+
return { id: o.id };
|
|
2880
|
+
}),
|
|
2881
|
+
async function (req, res) {
|
|
2882
|
+
var id = req.params.id;
|
|
2883
|
+
var enc = encodeURIComponent(id);
|
|
2884
|
+
var o;
|
|
2885
|
+
try { o = await order.get(id); }
|
|
2886
|
+
catch (e) { if (!(e instanceof TypeError)) throw e; o = null; }
|
|
2887
|
+
if (!o) return _sendHtml(res, 404, renderAdminOrders({
|
|
2888
|
+
shop_name: deps.shop_name, nav_available: navAvailable, orders: [], notice: "Order not found.",
|
|
2889
|
+
}));
|
|
2890
|
+
var body = req.body || {};
|
|
2891
|
+
try { await _resendReceipt(o, body.email || body.to); }
|
|
2892
|
+
catch (e) {
|
|
2893
|
+
if (!(e instanceof TypeError)) throw e;
|
|
2894
|
+
var reason = e.code === "RESEND_RATE_LIMITED" ? "rate" : "email";
|
|
2895
|
+
return _redirect(res, "/admin/orders/" + enc + "?resend_err=" + reason);
|
|
2896
|
+
}
|
|
2897
|
+
b.audit.safeEmit({ action: AUDIT_NAMESPACE + ".order.receipt.resend", outcome: "success", metadata: { id: id } });
|
|
2898
|
+
_redirect(res, "/admin/orders/" + enc + "?resent=1");
|
|
2899
|
+
},
|
|
2900
|
+
));
|
|
2901
|
+
}
|
|
2902
|
+
|
|
2747
2903
|
// ---- customers (read-only) ------------------------------------------
|
|
2748
2904
|
|
|
2749
2905
|
// Operator-facing customer roster, newest first. READ-ONLY — no create /
|
|
@@ -9748,6 +9904,62 @@ function mount(router, deps) {
|
|
|
9748
9904
|
_redirect(res, "/admin/segments?unarchived=1");
|
|
9749
9905
|
},
|
|
9750
9906
|
));
|
|
9907
|
+
|
|
9908
|
+
// Members CSV export — stream a segment's members for a marketing
|
|
9909
|
+
// handoff. The primitive yields a leading comment row + header, then
|
|
9910
|
+
// one chunk per membership batch (keyset-paginated, bounded memory);
|
|
9911
|
+
// the route writes each batch to the socket as it's produced, never
|
|
9912
|
+
// buffering the whole body — the download-route discipline. The CSV
|
|
9913
|
+
// carries NO email column (addresses are stored only as a one-way
|
|
9914
|
+
// hash and are never reconstructed). Audited as an export event.
|
|
9915
|
+
// Same response on the bearer + browser surfaces (a link, not a fetch).
|
|
9916
|
+
async function _streamSegmentMembers(res, slug) {
|
|
9917
|
+
var iter = customerSegments.membersCsvForSegment(slug);
|
|
9918
|
+
res.status(200);
|
|
9919
|
+
if (res.setHeader) {
|
|
9920
|
+
res.setHeader("content-type", "text/csv; charset=utf-8");
|
|
9921
|
+
var fname = ("segment-" + slug + "-members.csv").replace(/[^A-Za-z0-9._-]/g, "");
|
|
9922
|
+
res.setHeader("content-disposition", "attachment; filename=\"" + fname + "\"");
|
|
9923
|
+
res.setHeader("x-content-type-options", "nosniff");
|
|
9924
|
+
}
|
|
9925
|
+
// Write the header chunk first, then one chunk per batch. A response
|
|
9926
|
+
// without an incremental write() (a JSON test stub) buffers instead.
|
|
9927
|
+
if (typeof res.write === "function" && typeof res.end === "function") {
|
|
9928
|
+
for await (var chunk of iter) { if (chunk) res.write(chunk); }
|
|
9929
|
+
res.end();
|
|
9930
|
+
} else {
|
|
9931
|
+
var body = "";
|
|
9932
|
+
for await (var c2 of iter) body += c2;
|
|
9933
|
+
if (res.end) res.end(body); else res.send(body);
|
|
9934
|
+
}
|
|
9935
|
+
}
|
|
9936
|
+
|
|
9937
|
+
// Audit the export as a data-egress event before streaming. Hot-path
|
|
9938
|
+
// `safeEmit` (drop-silent) like every other admin mutation — a recording
|
|
9939
|
+
// hiccup must never block the operator's legitimate download.
|
|
9940
|
+
function _auditExport(slug) {
|
|
9941
|
+
b.audit.safeEmit({
|
|
9942
|
+
action: AUDIT_NAMESPACE + ".customer_segment.export",
|
|
9943
|
+
outcome: "success",
|
|
9944
|
+
metadata: { slug: slug },
|
|
9945
|
+
});
|
|
9946
|
+
}
|
|
9947
|
+
|
|
9948
|
+
router.get("/admin/segments/:slug/members.csv", _pageOrApi(true,
|
|
9949
|
+
R(async function (req, res) {
|
|
9950
|
+
var seg = await _segmentBySlug(req.params.slug);
|
|
9951
|
+
if (!seg) return _problem(res, 404, "customer-segment-not-found");
|
|
9952
|
+
_auditExport(seg.slug);
|
|
9953
|
+
return _streamSegmentMembers(res, seg.slug);
|
|
9954
|
+
}),
|
|
9955
|
+
async function (req, res) {
|
|
9956
|
+
var url = req.url ? new URL(req.url, "http://localhost") : null;
|
|
9957
|
+
var seg = await _segmentBySlug(req.params.slug);
|
|
9958
|
+
if (!seg) return _sendHtml(res, 404, await _renderSegments({ url: url, notice: "Segment not found." }));
|
|
9959
|
+
_auditExport(seg.slug);
|
|
9960
|
+
return _streamSegmentMembers(res, seg.slug);
|
|
9961
|
+
},
|
|
9962
|
+
));
|
|
9751
9963
|
}
|
|
9752
9964
|
|
|
9753
9965
|
// ---- quantity discounts ---------------------------------------------
|
|
@@ -11948,6 +12160,12 @@ function renderAdminOrder(opts) {
|
|
|
11948
12160
|
var shipOk = opts.ship_done ? "<div class=\"banner banner--ok\">Shipment updated.</div>" : "";
|
|
11949
12161
|
var labelOk = opts.label_done ? "<div class=\"banner banner--ok\">Shipping label updated.</div>" : "";
|
|
11950
12162
|
var splitOk = opts.split_done ? "<div class=\"banner banner--ok\">Split shipment updated.</div>" : "";
|
|
12163
|
+
var resentOk = opts.resent ? "<div class=\"banner banner--ok\">Confirmation email resent.</div>" : "";
|
|
12164
|
+
var resendErr = opts.resend_error === "rate"
|
|
12165
|
+
? "<div class=\"banner banner--err\">Resend limit reached for this order. Try again later.</div>"
|
|
12166
|
+
: (opts.resend_error === "email"
|
|
12167
|
+
? "<div class=\"banner banner--err\">Enter a valid recipient email address to resend.</div>"
|
|
12168
|
+
: "");
|
|
11951
12169
|
var notice = opts.notice ? "<div class=\"banner banner--err\">" + _htmlEscape(opts.notice) + "</div>" : "";
|
|
11952
12170
|
|
|
11953
12171
|
var lineRows = (o.lines || []).map(function (l) {
|
|
@@ -12019,6 +12237,28 @@ function renderAdminOrder(opts) {
|
|
|
12019
12237
|
"</div>"
|
|
12020
12238
|
: "";
|
|
12021
12239
|
|
|
12240
|
+
// Resend confirmation panel. The buyer's plaintext address is never
|
|
12241
|
+
// stored (the order keeps only the email hash), so the operator types
|
|
12242
|
+
// the recipient — typically the address from the customer's "I didn't
|
|
12243
|
+
// get my confirmation" request. Rendered only when a mailer is wired;
|
|
12244
|
+
// absent one it's a disabled note (mailer-gated, like the print links).
|
|
12245
|
+
var resendPanel;
|
|
12246
|
+
if (opts.can_resend_confirmation) {
|
|
12247
|
+
resendPanel =
|
|
12248
|
+
"<div class=\"panel mt\"><h3 class=\"subhead\">Resend confirmation</h3>" +
|
|
12249
|
+
"<p class=\"meta\">The original receipt was sent to the address the customer entered at checkout. That address isn't stored (only a one-way hash is), so enter where to send a fresh copy.</p>" +
|
|
12250
|
+
"<form method=\"post\" action=\"/admin/orders/" + _htmlEscape(o.id) + "/resend-confirmation\">" +
|
|
12251
|
+
_setupField("Recipient email", "email", "", "email", "Where to send the order receipt.", " maxlength=\"254\" required") +
|
|
12252
|
+
"<div class=\"actions-row\"><button class=\"btn\" type=\"submit\">Resend confirmation</button></div>" +
|
|
12253
|
+
"</form>" +
|
|
12254
|
+
"</div>";
|
|
12255
|
+
} else {
|
|
12256
|
+
resendPanel =
|
|
12257
|
+
"<div class=\"panel mt\"><h3 class=\"subhead\">Resend confirmation</h3>" +
|
|
12258
|
+
"<p class=\"empty\">Email isn't configured for this store, so confirmations can't be resent. Wire a transactional mailer to enable this.</p>" +
|
|
12259
|
+
"</div>";
|
|
12260
|
+
}
|
|
12261
|
+
|
|
12022
12262
|
// Shipment + tracking panel. Renders only when the tracking primitive is
|
|
12023
12263
|
// wired (`can_track`). For each existing shipment: the carrier, status,
|
|
12024
12264
|
// tracking number (linked to the carrier's public URL when known), and
|
|
@@ -12113,7 +12353,7 @@ function renderAdminOrder(opts) {
|
|
|
12113
12353
|
"<span class=\"status-pill " + _htmlEscape(o.status) + "\">" + _htmlEscape(o.status) + "</span></h2>" +
|
|
12114
12354
|
"<p class=\"meta\">Placed " + _htmlEscape(_fmtDate(o.created_at)) + " · last updated " + _htmlEscape(_fmtDate(o.updated_at)) +
|
|
12115
12355
|
(o.payment_intent_id ? " · payment <code class=\"order-id\">" + _htmlEscape(o.payment_intent_id) + "</code>" : "") + "</p>" +
|
|
12116
|
-
moved + shipOk + labelOk + splitOk + notice +
|
|
12356
|
+
moved + shipOk + labelOk + splitOk + resentOk + resendErr + notice +
|
|
12117
12357
|
"<div class=\"two-col\">" +
|
|
12118
12358
|
"<div class=\"panel\"><h3 class=\"subhead\">Items</h3>" + linesTable + "</div>" +
|
|
12119
12359
|
"<div class=\"panel\"><h3 class=\"subhead\">Ship to</h3>" +
|
|
@@ -12125,6 +12365,7 @@ function renderAdminOrder(opts) {
|
|
|
12125
12365
|
"<div class=\"order-actions\">" + actions + "</div>" +
|
|
12126
12366
|
"</div>" +
|
|
12127
12367
|
documentsPanel +
|
|
12368
|
+
resendPanel +
|
|
12128
12369
|
splitPanel +
|
|
12129
12370
|
trackingPanel +
|
|
12130
12371
|
"</section>";
|
|
@@ -15047,6 +15288,7 @@ function renderAdminSegments(opts) {
|
|
|
15047
15288
|
"<button class=\"btn btn--ghost\" type=\"submit\">Unarchive</button></form>"
|
|
15048
15289
|
: "<form method=\"post\" action=\"/admin/segments/" + _htmlEscape(enc) + "/recompute\" class=\"form-inline\">" +
|
|
15049
15290
|
"<button class=\"btn btn--ghost\" type=\"submit\">Recompute</button></form> " +
|
|
15291
|
+
"<a class=\"btn btn--ghost\" href=\"/admin/segments/" + _htmlEscape(enc) + "/members.csv\">Export CSV</a> " +
|
|
15050
15292
|
"<form method=\"post\" action=\"/admin/segments/" + _htmlEscape(enc) + "/archive\" class=\"form-inline\">" +
|
|
15051
15293
|
"<button class=\"btn btn--danger\" type=\"submit\">Archive</button></form>");
|
|
15052
15294
|
return "<tr>" +
|
|
@@ -15134,6 +15376,15 @@ function renderAdminSegment(opts) {
|
|
|
15134
15376
|
"<button class=\"btn\" type=\"submit\">Recompute membership</button>" +
|
|
15135
15377
|
"</form>";
|
|
15136
15378
|
|
|
15379
|
+
// Members CSV export — for a marketing handoff. Active segments only
|
|
15380
|
+
// (an archived segment's membership cache is cleared by contract). The
|
|
15381
|
+
// export carries no email addresses (stored as a one-way hash); the
|
|
15382
|
+
// note states this so the operator knows why.
|
|
15383
|
+
var exportLink = isArchived ? "" :
|
|
15384
|
+
"<a class=\"btn btn--ghost\" href=\"/admin/segments/" + _htmlEscape(enc) + "/members.csv\">Export members (CSV)</a>";
|
|
15385
|
+
var exportNote = isArchived ? "" :
|
|
15386
|
+
"<p class=\"meta\">The members CSV lists customer id, display name, join date, and order count — no email addresses (they're stored only as a one-way hash and aren't reconstructed). Recompute first if the membership looks stale.</p>";
|
|
15387
|
+
|
|
15137
15388
|
var editForm = isArchived
|
|
15138
15389
|
? "<p class=\"empty\">This segment is archived. Unarchive it to edit or recompute.</p>" +
|
|
15139
15390
|
"<form method=\"post\" action=\"/admin/segments/" + _htmlEscape(enc) + "/unarchive\" class=\"form-inline\">" +
|
|
@@ -15158,7 +15409,8 @@ function renderAdminSegment(opts) {
|
|
|
15158
15409
|
|
|
15159
15410
|
var body = "<section><h2>" + _htmlEscape(s.title) + "</h2>" + updated + recomputed + notice +
|
|
15160
15411
|
head + statCards +
|
|
15161
|
-
"<div class=\"actions-row mt\">" + recomputeForm + archiveForm + "</div>" +
|
|
15412
|
+
"<div class=\"actions-row mt\">" + recomputeForm + exportLink + archiveForm + "</div>" +
|
|
15413
|
+
exportNote +
|
|
15162
15414
|
editForm +
|
|
15163
15415
|
"<div class=\"actions-row mt\"><a class=\"btn btn--ghost\" href=\"/admin/segments\">Back to segments</a></div>" +
|
|
15164
15416
|
"</section>";
|
package/lib/asset-manifest.json
CHANGED
package/lib/customer-segments.js
CHANGED
|
@@ -113,6 +113,21 @@ var C = b.constants;
|
|
|
113
113
|
|
|
114
114
|
var DEFAULT_LIMIT = 100;
|
|
115
115
|
var MAX_LIMIT = 1000;
|
|
116
|
+
var EXPORT_BATCH_SIZE = 500;
|
|
117
|
+
|
|
118
|
+
// CSV column shape for a segment-members export. NO email column —
|
|
119
|
+
// customer email is stored only as a one-way hash, so a marketing
|
|
120
|
+
// export reconstructs no addresses; the operator gets a stable
|
|
121
|
+
// customer id, the display name, the join date (when the customer
|
|
122
|
+
// landed in the segment), and the lifetime order count. The screen
|
|
123
|
+
// copy + the leading comment row state this so the operator knows why
|
|
124
|
+
// the address is absent.
|
|
125
|
+
var MEMBER_EXPORT_COLUMNS = Object.freeze([
|
|
126
|
+
"customer_id",
|
|
127
|
+
"display_name",
|
|
128
|
+
"joined_segment_at",
|
|
129
|
+
"order_count",
|
|
130
|
+
]);
|
|
116
131
|
var SLUG_RE = /^[a-z0-9](?:[a-z0-9_-]{0,62}[a-z0-9])?$/;
|
|
117
132
|
var MAX_TITLE_LEN = 200;
|
|
118
133
|
var MAX_DESC_LEN = 1000;
|
|
@@ -314,6 +329,42 @@ function _limit(n, label) {
|
|
|
314
329
|
|
|
315
330
|
function _now() { return Date.now(); }
|
|
316
331
|
|
|
332
|
+
// ---- CSV helpers (members export) ---------------------------------------
|
|
333
|
+
//
|
|
334
|
+
// Same RFC-4180 quoting + spreadsheet-formula-injection neutralization
|
|
335
|
+
// the order-export primitive uses: every cell is quoted, embedded `"`
|
|
336
|
+
// doubled, and any cell beginning with `=` / `+` / `-` / `@` is prefixed
|
|
337
|
+
// with `'` so a spreadsheet treats it as text (a customer-controlled
|
|
338
|
+
// display_name is the injection vector). Signed numerics pass through.
|
|
339
|
+
|
|
340
|
+
function _coerceCell(value) {
|
|
341
|
+
if (value == null) return "";
|
|
342
|
+
if (typeof value === "string") return value;
|
|
343
|
+
if (typeof value === "number" || typeof value === "boolean") return String(value);
|
|
344
|
+
return JSON.stringify(value);
|
|
345
|
+
}
|
|
346
|
+
|
|
347
|
+
var _NUMERIC_SIGN_RE = /^[+-](?:\d+(?:\.\d+)?|\.\d+)$/;
|
|
348
|
+
|
|
349
|
+
function _neutralizeInjection(s) {
|
|
350
|
+
if (s.length === 0) return s;
|
|
351
|
+
var first = s.charAt(0);
|
|
352
|
+
if (first !== "=" && first !== "+" && first !== "-" && first !== "@") return s;
|
|
353
|
+
if ((first === "+" || first === "-") && _NUMERIC_SIGN_RE.test(s)) return s;
|
|
354
|
+
return "'" + s;
|
|
355
|
+
}
|
|
356
|
+
|
|
357
|
+
function _csvCell(value) {
|
|
358
|
+
var s = _neutralizeInjection(_coerceCell(value));
|
|
359
|
+
return '"' + s.replace(/"/g, '""') + '"';
|
|
360
|
+
}
|
|
361
|
+
|
|
362
|
+
function _csvRow(cells) {
|
|
363
|
+
var parts = [];
|
|
364
|
+
for (var i = 0; i < cells.length; i += 1) parts.push(_csvCell(cells[i]));
|
|
365
|
+
return parts.join(",") + "\r\n";
|
|
366
|
+
}
|
|
367
|
+
|
|
317
368
|
// ---- factory ------------------------------------------------------------
|
|
318
369
|
|
|
319
370
|
function create(opts) {
|
|
@@ -615,6 +666,100 @@ function create(opts) {
|
|
|
615
666
|
return { customer_ids: ids, next_cursor: nextCursor };
|
|
616
667
|
},
|
|
617
668
|
|
|
669
|
+
MEMBER_EXPORT_COLUMNS: MEMBER_EXPORT_COLUMNS.slice(),
|
|
670
|
+
|
|
671
|
+
// Streaming CSV of a segment's members for a marketing handoff.
|
|
672
|
+
// Async-iterable: yields a leading comment row + the header on the
|
|
673
|
+
// first iteration, then one chunk per membership batch. Keyset-
|
|
674
|
+
// paginated on customer_id ASC (the membership PK order) so the
|
|
675
|
+
// process holds at most one batch in memory regardless of segment
|
|
676
|
+
// size — mirrors the order-export streaming discipline.
|
|
677
|
+
//
|
|
678
|
+
// Columns: customer_id, display_name, joined_segment_at (the
|
|
679
|
+
// recompute timestamp that placed the customer in the segment),
|
|
680
|
+
// order_count (lifetime non-cancelled orders). There is NO email
|
|
681
|
+
// column — the address is stored only as a one-way hash and is never
|
|
682
|
+
// reconstructed; the leading comment row states this so the operator
|
|
683
|
+
// understands the omission.
|
|
684
|
+
//
|
|
685
|
+
// An unknown / archived slug yields an iterator whose first `next()`
|
|
686
|
+
// throws a TypeError, so the HTTP layer can map it to a clean 404
|
|
687
|
+
// without a partial stream.
|
|
688
|
+
membersCsvForSegment: function (slug, csvOpts) {
|
|
689
|
+
_slug(slug);
|
|
690
|
+
csvOpts = csvOpts || {};
|
|
691
|
+
var batch = EXPORT_BATCH_SIZE;
|
|
692
|
+
var cursorVal = null;
|
|
693
|
+
var done = false;
|
|
694
|
+
var preludeEmitted = false;
|
|
695
|
+
var seg = null;
|
|
696
|
+
|
|
697
|
+
async function _resolveSegment() {
|
|
698
|
+
if (seg) return seg;
|
|
699
|
+
var row = await _readSegment(slug);
|
|
700
|
+
if (!row) {
|
|
701
|
+
throw new TypeError("customer-segments.membersCsvForSegment: unknown slug " + JSON.stringify(slug));
|
|
702
|
+
}
|
|
703
|
+
seg = row;
|
|
704
|
+
return seg;
|
|
705
|
+
}
|
|
706
|
+
|
|
707
|
+
return {
|
|
708
|
+
[Symbol.asyncIterator]: function () { return this; },
|
|
709
|
+
next: async function () {
|
|
710
|
+
if (done) return { value: undefined, done: true };
|
|
711
|
+
var s = await _resolveSegment();
|
|
712
|
+
if (!preludeEmitted) {
|
|
713
|
+
preludeEmitted = true;
|
|
714
|
+
// Leading comment row — RFC-4180-quoted so spreadsheets keep it
|
|
715
|
+
// intact; states why no email column exists. Then the header.
|
|
716
|
+
var prelude =
|
|
717
|
+
_csvRow(["# Segment members export — email addresses are omitted (stored as a one-way hash, never reconstructed)."]) +
|
|
718
|
+
_csvRow(MEMBER_EXPORT_COLUMNS);
|
|
719
|
+
// An archived segment has an empty cache by contract — the
|
|
720
|
+
// header still emits so the consumer gets a well-formed
|
|
721
|
+
// (empty) file rather than a 404 mid-stream.
|
|
722
|
+
return { value: prelude, done: false };
|
|
723
|
+
}
|
|
724
|
+
var sql, params;
|
|
725
|
+
if (cursorVal != null) {
|
|
726
|
+
sql = "SELECT csm.customer_id AS customer_id, csm.evaluated_at AS joined_segment_at, " +
|
|
727
|
+
" c.display_name AS display_name, " +
|
|
728
|
+
" (SELECT COUNT(*) FROM orders o WHERE o.customer_id = csm.customer_id AND o.status != 'cancelled') AS order_count " +
|
|
729
|
+
"FROM customer_segment_membership csm " +
|
|
730
|
+
"LEFT JOIN customers c ON c.id = csm.customer_id " +
|
|
731
|
+
"WHERE csm.segment_id = ?1 AND csm.customer_id > ?2 " +
|
|
732
|
+
"ORDER BY csm.customer_id ASC LIMIT ?3";
|
|
733
|
+
params = [s.id, cursorVal, batch];
|
|
734
|
+
} else {
|
|
735
|
+
sql = "SELECT csm.customer_id AS customer_id, csm.evaluated_at AS joined_segment_at, " +
|
|
736
|
+
" c.display_name AS display_name, " +
|
|
737
|
+
" (SELECT COUNT(*) FROM orders o WHERE o.customer_id = csm.customer_id AND o.status != 'cancelled') AS order_count " +
|
|
738
|
+
"FROM customer_segment_membership csm " +
|
|
739
|
+
"LEFT JOIN customers c ON c.id = csm.customer_id " +
|
|
740
|
+
"WHERE csm.segment_id = ?1 " +
|
|
741
|
+
"ORDER BY csm.customer_id ASC LIMIT ?2";
|
|
742
|
+
params = [s.id, batch];
|
|
743
|
+
}
|
|
744
|
+
var rows = (await query(sql, params)).rows;
|
|
745
|
+
if (rows.length === 0) { done = true; return { value: undefined, done: true }; }
|
|
746
|
+
var out = "";
|
|
747
|
+
for (var i = 0; i < rows.length; i += 1) {
|
|
748
|
+
var r = rows[i];
|
|
749
|
+
out += _csvRow([
|
|
750
|
+
r.customer_id,
|
|
751
|
+
r.display_name == null ? "" : r.display_name,
|
|
752
|
+
r.joined_segment_at == null ? "" : r.joined_segment_at,
|
|
753
|
+
r.order_count == null ? 0 : r.order_count,
|
|
754
|
+
]);
|
|
755
|
+
}
|
|
756
|
+
cursorVal = rows[rows.length - 1].customer_id;
|
|
757
|
+
if (rows.length < batch) done = true;
|
|
758
|
+
return { value: out, done: false };
|
|
759
|
+
},
|
|
760
|
+
};
|
|
761
|
+
},
|
|
762
|
+
|
|
618
763
|
recompute: async function (recomputeOpts) {
|
|
619
764
|
recomputeOpts = recomputeOpts || {};
|
|
620
765
|
var slugFilter = null;
|
|
@@ -811,4 +956,9 @@ module.exports = {
|
|
|
811
956
|
ALLOWED_ORDER_STATUSES: ALLOWED_ORDER_STATUSES,
|
|
812
957
|
DEFAULT_LIMIT: DEFAULT_LIMIT,
|
|
813
958
|
MAX_LIMIT: MAX_LIMIT,
|
|
959
|
+
MEMBER_EXPORT_COLUMNS: MEMBER_EXPORT_COLUMNS,
|
|
960
|
+
// Exposed for the test suite to assert CSV cell semantics without a
|
|
961
|
+
// full DB round-trip.
|
|
962
|
+
_csvCell: _csvCell,
|
|
963
|
+
_neutralizeInjection: _neutralizeInjection,
|
|
814
964
|
};
|
package/package.json
CHANGED