@teleporthq/teleport-plugin-next-workflows 0.44.4 → 0.44.6

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.
Files changed (29) hide show
  1. package/__tests__/account-delete-owned-rows.test.ts +488 -0
  2. package/__tests__/invoice-paid-status.test.ts +382 -0
  3. package/__tests__/invoice-tender.test.ts +5 -3
  4. package/dist/cjs/account-delete-route-generator.d.ts +9 -6
  5. package/dist/cjs/account-delete-route-generator.d.ts.map +1 -1
  6. package/dist/cjs/account-delete-route-generator.js +131 -1
  7. package/dist/cjs/account-delete-route-generator.js.map +1 -1
  8. package/dist/cjs/invoice/invoice-assembly-code.d.ts.map +1 -1
  9. package/dist/cjs/invoice/invoice-assembly-code.js +19 -2
  10. package/dist/cjs/invoice/invoice-assembly-code.js.map +1 -1
  11. package/dist/cjs/invoice/invoice-html-code.d.ts.map +1 -1
  12. package/dist/cjs/invoice/invoice-html-code.js +100 -71
  13. package/dist/cjs/invoice/invoice-html-code.js.map +1 -1
  14. package/dist/cjs/tsconfig.tsbuildinfo +1 -1
  15. package/dist/esm/account-delete-route-generator.d.ts +9 -6
  16. package/dist/esm/account-delete-route-generator.d.ts.map +1 -1
  17. package/dist/esm/account-delete-route-generator.js +131 -1
  18. package/dist/esm/account-delete-route-generator.js.map +1 -1
  19. package/dist/esm/invoice/invoice-assembly-code.d.ts.map +1 -1
  20. package/dist/esm/invoice/invoice-assembly-code.js +19 -2
  21. package/dist/esm/invoice/invoice-assembly-code.js.map +1 -1
  22. package/dist/esm/invoice/invoice-html-code.d.ts.map +1 -1
  23. package/dist/esm/invoice/invoice-html-code.js +100 -71
  24. package/dist/esm/invoice/invoice-html-code.js.map +1 -1
  25. package/dist/esm/tsconfig.tsbuildinfo +1 -1
  26. package/package.json +3 -3
  27. package/src/account-delete-route-generator.ts +140 -7
  28. package/src/invoice/invoice-assembly-code.ts +19 -2
  29. package/src/invoice/invoice-html-code.ts +100 -71
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@teleporthq/teleport-plugin-next-workflows",
3
- "version": "0.44.4",
3
+ "version": "0.44.6",
4
4
  "description": "A plugin for workflow code generation in Next.js projects.",
5
5
  "author": "teleportHQ",
6
6
  "license": "MIT",
@@ -66,8 +66,8 @@
66
66
  },
67
67
  "dependencies": {
68
68
  "@babel/types": "^7.5.5",
69
- "@teleporthq/teleport-shared": "^0.44.4",
69
+ "@teleporthq/teleport-shared": "^0.44.5",
70
70
  "@teleporthq/teleport-types": "^0.44.0"
71
71
  },
72
- "gitHead": "cacf0be69ff0d4b04635161e5d9e880bd5a2ec92"
72
+ "gitHead": "c763dc9d1d966d36811d04cd422e948a5cd7e841"
73
73
  }
@@ -6,17 +6,21 @@
6
6
  * 1. resolves the current user from the NextAuth session (never trusting a
7
7
  * client-supplied id),
8
8
  * 2. runs a single DB transaction that detaches + anonymises business/legal
9
- * records (orders, withdrawal requests) so tracking survives, deletes the
10
- * user's personal data (reviews, cart, favourites, chat history) and the
11
- * user row, and
9
+ * records (orders, withdrawal requests, bookings) so tracking survives,
10
+ * deletes the user's personal data (reviews, cart, favourites, chat
11
+ * history), deletes the rows the user owns in the project's own tables —
12
+ * the ones the AI made for the site, each through the one column the
13
+ * site's "My …" pages read it by (teleport-shared's resolveOwnerColumn,
14
+ * shipped into the route as text) — and then the user row, and
12
15
  * 3. best-effort sends the farewell email (a failed send never fails the
13
16
  * deletion).
14
17
  *
15
- * Every table statement is guarded by a runtime `information_schema` column
16
- * check, so the route is a no-op for feature tables a given project never
17
- * provisioned.
18
+ * Every platform-table statement is guarded by a runtime `information_schema`
19
+ * column check, so the route is a no-op for feature tables a given project
20
+ * never provisioned.
18
21
  */
19
22
  import { UIDLLocalizedEmailTemplates } from '@teleporthq/teleport-types'
23
+ import { OwnerColumns } from '@teleporthq/teleport-shared'
20
24
  import { generatePgClientCode } from './pg-client-code'
21
25
  import { generateCommonJsSessionTokenResolverCode } from './session-cookie-resolver'
22
26
  import {
@@ -84,11 +88,22 @@ const DELETE_TABLES = [
84
88
  'teleport_cart',
85
89
  'teleport_ai_chat_messages',
86
90
  'teleport_ai_chat_conversations',
91
+ // A push subscription is the capability to notify the user's device.
92
+ 'teleport_push_subscriptions',
87
93
  ];
88
94
  // Business / legal records that must survive: the user link is nulled and any
89
95
  // stored personal email is replaced with a synthetic, self-describing address.
90
- const ANONYMIZE_TABLES = ['teleport_orders', 'teleport_withdrawal_requests'];
96
+ const ANONYMIZE_TABLES = [
97
+ 'teleport_orders',
98
+ 'teleport_withdrawal_requests',
99
+ 'teleport_bookings',
100
+ 'teleport_subscriptions',
101
+ 'teleport_abandoned_carts',
102
+ 'teleport_voucher_redemptions',
103
+ ];
91
104
  const EMAIL_COLUMNS = ['billing_email', 'shipping_email', 'customer_email', 'email'];
105
+ // A booking also names the customer and carries their phone; both are cleared.
106
+ const CLEARED_COLUMNS = { teleport_bookings: ['customer_name', 'customer_phone'] };
92
107
 
93
108
  async function tableColumns(client, table) {
94
109
  var r = await client.query(
@@ -111,6 +126,10 @@ async function anonymizeUserRows(client, table, userId, syntheticEmail) {
111
126
  sets.push(EMAIL_COLUMNS[i] + ' = $' + params.length);
112
127
  }
113
128
  }
129
+ var cleared = CLEARED_COLUMNS[table] || [];
130
+ for (var c = 0; c < cleared.length; c++) {
131
+ if (cols.indexOf(cleared[c]) !== -1) { sets.push(cleared[c] + ' = NULL'); }
132
+ }
114
133
  await client.query('UPDATE ' + table + ' SET ' + sets.join(', ') + ' WHERE user_id = $1', params);
115
134
  }
116
135
 
@@ -127,6 +146,119 @@ async function deleteRowsByEmail(client, table, column, email) {
127
146
  await client.query('DELETE FROM ' + table + ' WHERE ' + column + ' = $1', [email]);
128
147
  }
129
148
 
149
+ // Rows the user owns in the project's OWN tables — the ones the AI made for
150
+ // this site (saved items, requests, reviews …). Their link to the user is
151
+ // ON DELETE SET NULL, so they outlived the account with a blank owner, and the
152
+ // "My …" pages read "owner = me OR owner IS NULL": every other signed-in
153
+ // visitor saw them. Platform tables keep the explicit handling above —
154
+ // deleted, anonymised, or kept as the business's records.
155
+ //
156
+ // Each table is attributed through exactly ONE column, the one its "My …"
157
+ // pages read it by: resolveOwnerColumn below is the AI pipeline's own
158
+ // decision, shipped here as text, so the two sides cannot disagree. Rows go
159
+ // only through an "owner" column (whose the row is: author, submitter,
160
+ // sender); an "actor" column (who approved, reviewed, was assigned or
161
+ // addressed) names somebody else's row and leaves the table alone.
162
+ ${OwnerColumns.generateOwnerColumnResolverCode()}
163
+
164
+ const PLATFORM_TABLE_PREFIX = 'teleport_';
165
+ const PLATFORM_TABLES = [AUTH_USERS_TABLE, 'password_reset_tokens'];
166
+
167
+ function isPlatformTable(table) {
168
+ return PLATFORM_TABLES.indexOf(table) !== -1 || table.indexOf(PLATFORM_TABLE_PREFIX) === 0;
169
+ }
170
+
171
+ function quoteIdentifier(name) {
172
+ return '"' + String(name).split('"').join('""') + '"';
173
+ }
174
+
175
+ // The (table, column) pairs through which the project's own tables name their
176
+ // owner: the resolved owner column when it references the users table — or
177
+ // references nothing, in older projects whose link was dropped. One that
178
+ // references another table (account_id -> accounts) is a domain link and the
179
+ // table is left alone. Links are read from pg_constraint rather than
180
+ // information_schema: constraint names are only unique per table, so a join
181
+ // by name can pair the wrong tables.
182
+ async function ownedRowLinks(client) {
183
+ var columns = await client.query(
184
+ "SELECT c.table_name, c.column_name, c.ordinal_position FROM information_schema.columns c" +
185
+ " JOIN information_schema.tables t ON t.table_schema = c.table_schema AND t.table_name = c.table_name" +
186
+ " WHERE c.table_schema = 'public' AND t.table_type = 'BASE TABLE'" +
187
+ " ORDER BY c.table_name, c.ordinal_position"
188
+ );
189
+ var links = await client.query(
190
+ "SELECT cl.relname AS table_name, a.attname AS column_name," +
191
+ " rcl.relname AS referenced_table, ra.attname AS referenced_column" +
192
+ " FROM pg_constraint k" +
193
+ " JOIN pg_class cl ON cl.oid = k.conrelid" +
194
+ " JOIN pg_namespace n ON n.oid = cl.relnamespace" +
195
+ " JOIN pg_attribute a ON a.attrelid = k.conrelid AND a.attnum = k.conkey[1]" +
196
+ " JOIN pg_class rcl ON rcl.oid = k.confrelid" +
197
+ " JOIN pg_attribute ra ON ra.attrelid = k.confrelid AND ra.attnum = k.confkey[1]" +
198
+ " WHERE k.contype = 'f' AND n.nspname = 'public' AND array_length(k.conkey, 1) = 1"
199
+ );
200
+ var referenced = {};
201
+ for (var i = 0; i < links.rows.length; i++) {
202
+ var link = links.rows[i];
203
+ referenced[link.table_name + '.' + link.column_name] = link.referenced_table + '.' + link.referenced_column;
204
+ }
205
+ var tables = [];
206
+ var columnsOf = {};
207
+ for (var j = 0; j < columns.rows.length; j++) {
208
+ var row = columns.rows[j];
209
+ if (!columnsOf[row.table_name]) {
210
+ columnsOf[row.table_name] = [];
211
+ tables.push(row.table_name);
212
+ }
213
+ columnsOf[row.table_name].push({ name: row.column_name, ordinalPosition: Number(row.ordinal_position) });
214
+ }
215
+ var owned = [];
216
+ for (var t = 0; t < tables.length; t++) {
217
+ var table = tables[t];
218
+ if (isPlatformTable(table)) { continue; }
219
+ var resolved = resolveOwnerColumn(columnsOf[table]);
220
+ if (!resolved || resolved.kind !== 'owner') { continue; }
221
+ var target = referenced[table + '.' + resolved.column];
222
+ if (target && target !== AUTH_USERS_TABLE + '.id') { continue; }
223
+ owned.push({ table: table, column: resolved.column });
224
+ }
225
+ return owned;
226
+ }
227
+
228
+ // Each table is deleted from under its own savepoint, so one that refuses
229
+ // (another user's row still points at this user's, through a link without
230
+ // ON DELETE CASCADE) stops neither the other tables nor the account from being
231
+ // deleted. A refused table is retried once the rest are done — the blocker may
232
+ // have been this user's own row in another table; what is still refused stays
233
+ // as it always did, and the log names it.
234
+ async function deleteOwnedRows(client, userId) {
235
+ var pending = await ownedRowLinks(client);
236
+ while (pending.length > 0) {
237
+ var refused = [];
238
+ for (var i = 0; i < pending.length; i++) {
239
+ var link = pending[i];
240
+ await client.query('SAVEPOINT owned_rows');
241
+ try {
242
+ await client.query(
243
+ 'DELETE FROM ' + quoteIdentifier(link.table) + ' WHERE ' + quoteIdentifier(link.column) + ' = $1',
244
+ [userId]
245
+ );
246
+ await client.query('RELEASE SAVEPOINT owned_rows');
247
+ } catch (err) {
248
+ await client.query('ROLLBACK TO SAVEPOINT owned_rows');
249
+ await client.query('RELEASE SAVEPOINT owned_rows');
250
+ link.error = err && err.message ? err.message : String(err);
251
+ refused.push(link);
252
+ }
253
+ }
254
+ if (refused.length === pending.length) { break; }
255
+ pending = refused;
256
+ }
257
+ for (var k = 0; k < pending.length; k++) {
258
+ console.error('[account-delete] rows kept in ' + pending[k].table + ' (' + pending[k].column + '): ' + pending[k].error);
259
+ }
260
+ }
261
+
130
262
  // Invoices are a financial/tax record that must survive, but they store the
131
263
  // customer's PII denormalised and link to the user only through order_id (no
132
264
  // user_id). Scrub the PII in place, matching invoices whose order belongs to the
@@ -246,6 +378,7 @@ module.exports = async function handler(req, res) {
246
378
  for (var d = 0; d < DELETE_TABLES.length; d++) {
247
379
  await deleteUserRows(client, DELETE_TABLES[d], userId);
248
380
  }
381
+ await deleteOwnedRows(client, userId);
249
382
  // password_reset_tokens has no user_id — it is keyed by the email string.
250
383
  await deleteRowsByEmail(client, 'password_reset_tokens', 'email', userEmail);
251
384
  await client.query('DELETE FROM ' + AUTH_USERS_TABLE + ' WHERE id = $1', [userId]);
@@ -93,6 +93,16 @@ var CURRENCY_SYMBOLS = {
93
93
  'CLP': 'CLP$', 'PEN': 'S/.', 'VND': '\\u20AB', 'UAH': '\\u20B4',
94
94
  };
95
95
 
96
+ // \`teleport_orders.payment_status\` values that mean the order's money was
97
+ // collected — the editor's PAID_PAYMENT_STATUS_VALUES (teleport-gui
98
+ // e-commerce/constants/order-statuses.ts), provider spellings included.
99
+ var PAID_ORDER_PAYMENT_STATUSES = ['paid', 'partially_refunded', 'succeeded', 'success', 'completed', 'captured'];
100
+
101
+ function isPaidOrder(order) {
102
+ var paymentStatus = String((order && order.payment_status) || '').trim().toLowerCase();
103
+ return PAID_ORDER_PAYMENT_STATUSES.indexOf(paymentStatus) !== -1;
104
+ }
105
+
96
106
  function isLoopbackHost(host) {
97
107
  var name = String(host || '').replace(/:[0-9]+$/, '').toLowerCase();
98
108
  return name === 'localhost' || name === '127.0.0.1' || name === '[::1]';
@@ -473,15 +483,22 @@ function assembleInvoiceData(body, hydratedOrder, hydratedItems) {
473
483
  var fallbackPaymentIntentId = orderRow.payment_intent_id || '';
474
484
  var fallbackNotes = orderRow.notes || '';
475
485
 
486
+ // Paid or not, when the caller does not say: the order's money state. The
487
+ // payment webhook marks an order paid and then asks for its invoice with just
488
+ // the order id; a cash-on-delivery order is invoiced unpaid when it is placed.
489
+ // The orders table keeps no payment time of its own — the mark-paid write
490
+ // stamps \`updated_at\`, just before the webhook asks.
491
+ var paidByOrder = !body.status && isPaidOrder(orderRow);
492
+
476
493
  var invoiceData = {
477
494
  id: body.id || require('crypto').randomUUID(),
478
495
  // Numbered by the route: an invoice issued at payment takes the next
479
496
  // number, a regenerated one keeps its own.
480
497
  invoiceNumber: '',
481
- status: body.status || 'issued',
498
+ status: body.status || (paidByOrder ? 'paid' : 'issued'),
482
499
  issueDate: issueDate,
483
500
  dueDate: dueDate,
484
- paidAt: body.paidAt || null,
501
+ paidAt: body.paidAt || (paidByOrder ? orderRow.updated_at || new Date().toISOString() : null),
485
502
  customerName: body.customerName || fallbackCustomerName || '',
486
503
  customerEmail: body.customerEmail || fallbackCustomerEmail || '',
487
504
  customerAddress: body.customerAddress || fallbackCustomerAddress || '',
@@ -12,12 +12,12 @@ import { UIDLInvoiceSettings } from '@teleporthq/teleport-types'
12
12
  //
13
13
  // The UIDL tree has several features that need runtime handling:
14
14
  //
15
- // 1. `<context>` elements carry default invoice data on their attributes
16
- // (Company, Invoice, Customer, Products, Payment). Children reference
17
- // that data through expressions like `invoiceData?.Company?.name`. We
18
- // build a per-render scope from the attrs merged with real DB data
19
- // (real wins unless empty) so every expression resolves against the
20
- // buyer's actual order.
15
+ // 1. `<context>` elements carry the design canvas's sample invoice on
16
+ // their attributes (Company, Invoice, Customer, Products, Payment).
17
+ // Children reference that data through expressions like
18
+ // `invoiceData?.Company?.name`. Every render builds the scope from the
19
+ // real invoice alone, so every expression resolves against the buyer's
20
+ // actual order and an empty field prints nothing — never the sample.
21
21
  //
22
22
  // 2. `cms-list-repeater` iterates `invoiceData.Products` with a
23
23
  // per-iteration variable (the `renderPropIdentifier`). Each line item
@@ -153,11 +153,12 @@ var COMPONENT_DEFINITIONS = ${componentDefinitionsJson};
153
153
  var MAX_COMPONENT_DEPTH = 12;
154
154
 
155
155
  // ---------------------------------------------------------------------------
156
- // Scope construction — merges real DB data with defaults the user set on
157
- // the <context> element in the editor. Per-field fallback: if the real
158
- // field is empty/null, the UIDL default wins. Covers the common dev case
159
- // where COMPANY_DETAILS from invoiceSettings isn't filled in but the user
160
- // dropped "Acme Corporation" into the template preview.
156
+ // Scope construction — the real invoice, the store's company details and the
157
+ // buyer, never the sample on the template's <context>: an empty notes field,
158
+ // VAT number or paid date printed the design canvas's "Payment is due within
159
+ // 30 days", "US123456789" or "Jan 20, 2025" on a real invoice. The one value
160
+ // read from the context is the company logo URL, which the editor writes there
161
+ // from the store's own logo (the sample's is empty).
161
162
  // ---------------------------------------------------------------------------
162
163
 
163
164
  function extractStaticAttrsFromContext(uidl) {
@@ -194,23 +195,9 @@ function findFirstContextNode(node) {
194
195
  return null;
195
196
  }
196
197
 
197
- function nonEmpty(v) {
198
- if (v == null) return false;
199
- if (typeof v === 'string') return v.length > 0;
200
- if (typeof v === 'number') return !isNaN(v);
201
- return true;
202
- }
203
-
204
- function mergeWithDefaults(primary, defaults) {
205
- var out = Object.assign({}, defaults || {});
206
- if (primary) {
207
- Object.keys(primary).forEach(function (k) {
208
- if (nonEmpty(primary[k])) out[k] = primary[k];
209
- });
210
- }
211
- return out;
212
- }
213
-
198
+ // Money on the invoice, in the PDF and the email alike. A symbol that ends in
199
+ // a letter is a word ("lei", "CHF", "kr") and stands apart from the number
200
+ // ("lei 119.00"); a sign sits against it ("$119.00", "\u20AC119.00").
214
201
  function formatCurrencyValue(amount, sym, decimals) {
215
202
  var num = Number(amount);
216
203
  if (!isFinite(num)) num = 0;
@@ -218,7 +205,17 @@ function formatCurrencyValue(amount, sym, decimals) {
218
205
  var fixed = num.toFixed(dec);
219
206
  var parts = fixed.split('.');
220
207
  parts[0] = parts[0].replace(/\\B(?=(\\d{3})+(?!\\d))/g, ',');
221
- return (sym || '') + parts.join('.');
208
+ var symbol = String(sym == null ? '' : sym).trim();
209
+ var separator = /\\p{L}$/u.test(symbol) ? ' ' : '';
210
+ return symbol + separator + parts.join('.');
211
+ }
212
+
213
+ // Invoice statuses of money that was collected: a refund later moves a paid
214
+ // invoice to one of the last two, and it was paid all the same.
215
+ var SETTLED_INVOICE_STATUSES = ['paid', 'partially_refunded', 'refunded'];
216
+
217
+ function isSettledInvoice(status) {
218
+ return SETTLED_INVOICE_STATUSES.indexOf(String(status || '').toLowerCase()) !== -1;
222
219
  }
223
220
 
224
221
  // Per-line VAT formulas. These MIRROR the GUI helpers in
@@ -269,7 +266,7 @@ function formatDateValue(raw) {
269
266
  }
270
267
 
271
268
  function buildInvoiceDataScope(invoiceData) {
272
- var defaults = extractStaticAttrsFromContext(TEMPLATE_COMPONENT_UIDL);
269
+ var contextCompany = extractStaticAttrsFromContext(TEMPLATE_COMPONENT_UIDL).Company || {};
273
270
  var sym = invoiceData.currencySymbol || '$';
274
271
 
275
272
  var realCompany = {
@@ -283,7 +280,7 @@ function buildInvoiceDataScope(invoiceData) {
283
280
  registrationNumber: COMPANY_DETAILS.companyRegNumber,
284
281
  email: COMPANY_DETAILS.companyEmail,
285
282
  phone: COMPANY_DETAILS.companyPhone,
286
- logoUrl: invoiceData.companyLogoUrl || '',
283
+ logoUrl: invoiceData.companyLogoUrl || contextCompany.logoUrl || '',
287
284
  website: COMPANY_DETAILS.companyWebsite,
288
285
  };
289
286
 
@@ -319,12 +316,20 @@ function buildInvoiceDataScope(invoiceData) {
319
316
  amountDueNumber = Math.max(0, totalNumber - giftCardAmountNumber);
320
317
  }
321
318
 
319
+ // A paid invoice asks for nothing: where the due date would print, it says
320
+ // when it was paid. The order keeps no payment method finer than its
321
+ // provider, so the line names none.
322
+ var paid = isSettledInvoice(invoiceData.status);
323
+ var paidDate = formatDateValue(invoiceData.paidAt || (paid ? invoiceData.issueDate : ''));
324
+ var paidLine = paid ? 'Paid' + (paidDate ? ' on ' + paidDate : '') : '';
325
+
322
326
  var realInvoice = {
323
327
  invoiceNumber: invoiceData.invoiceNumber ? '#' + invoiceData.invoiceNumber : '',
324
328
  status: invoiceData.status || '',
325
329
  issueDate: formatDateValue(invoiceData.issueDate),
326
- dueDate: formatDateValue(invoiceData.dueDate),
327
- paidDate: formatDateValue(invoiceData.paidAt),
330
+ dueDate: paidLine || formatDateValue(invoiceData.dueDate),
331
+ paidDate: paidDate,
332
+ paidLine: paidLine,
328
333
  subtotal: formatCurrencyValue(invoiceData.subtotal, sym),
329
334
  taxRate: invoiceData.taxRate != null ? String(invoiceData.taxRate) : '',
330
335
  taxAmount: formatCurrencyValue(invoiceData.taxAmount, sym),
@@ -351,13 +356,6 @@ function buildInvoiceDataScope(invoiceData) {
351
356
  notes: invoiceData.notes || '',
352
357
  pdfUrl: invoiceData.pdfUrl || '',
353
358
  };
354
- // The merge below lets an EMPTY real value fall back to the template's
355
- // sample — right for a company address, wrong for a code or a card tail: an
356
- // order without a voucher must not print the designer's "SAVE20".
357
- var realInvoiceNeverSampled = { voucherCode: voucherCode, giftCardLast4: giftCardLast4 };
358
- // The buyer and their payment are never sampled either: an order with no
359
- // city (a booking, a pickup, a download) must not print the designer's
360
- // sample customer's, nor a card it was not paid with.
361
359
 
362
360
  var realCustomer = {
363
361
  name: invoiceData.customerName || '',
@@ -470,11 +468,11 @@ function buildInvoiceDataScope(invoiceData) {
470
468
 
471
469
  return {
472
470
  invoiceData: {
473
- Company: mergeWithDefaults(realCompany, defaults.Company),
474
- Invoice: Object.assign(mergeWithDefaults(realInvoice, defaults.Invoice), realInvoiceNeverSampled),
471
+ Company: realCompany,
472
+ Invoice: realInvoice,
475
473
  Customer: realCustomer,
476
474
  Payment: realPayment,
477
- Products: realProducts.length > 0 ? realProducts : (defaults.Products || []),
475
+ Products: realProducts,
478
476
  },
479
477
  };
480
478
  }
@@ -975,7 +973,12 @@ function buildFallbackInvoiceHtml(scope) {
975
973
  var parts = [];
976
974
  parts.push('<div style="padding:32px;font-family:Helvetica,Arial,sans-serif;color:#333;font-size:10pt;">');
977
975
  parts.push('<h1 style="text-align:right;font-size:24pt;margin:0 0 4px;">INVOICE</h1>');
978
- parts.push('<p style="text-align:right;color:#666;margin:0 0 24px;">' + escapeHtml(inv.invoiceNumber || '') + '</p>');
976
+ if (inv.paidLine) {
977
+ parts.push('<p style="text-align:right;color:#666;margin:0 0 4px;">' + escapeHtml(inv.invoiceNumber || '') + '</p>');
978
+ parts.push('<p style="text-align:right;color:#666;margin:0 0 24px;">' + escapeHtml(inv.paidLine) + '</p>');
979
+ } else {
980
+ parts.push('<p style="text-align:right;color:#666;margin:0 0 24px;">' + escapeHtml(inv.invoiceNumber || '') + '</p>');
981
+ }
979
982
  parts.push('<div style="display:flex;gap:40px;margin-bottom:24px;">');
980
983
  parts.push('<div style="flex:1;"><strong>' + escapeHtml(comp.name || '') + '</strong><br/>' +
981
984
  escapeHtml(comp.address || '') + '<br/>' +
@@ -1074,25 +1077,47 @@ function resolveTextSpans(spans, scope) {
1074
1077
  }).join('');
1075
1078
  }
1076
1079
 
1077
- // Amount tokens whose line means nothing at zero: "Delivery $0.00" on a
1078
- // pickup order, "Discount −$0.00" without a voucher. The table row (or list
1079
- // item / paragraph) that carries such a token is dropped before the tokens are
1080
- // filled, so the merchant's summary only lists the figures that applied.
1081
- // Matched innermost — a row inside a row keeps its parent.
1082
- var OPTIONAL_AMOUNT_TOKENS = ['shippingAmount', 'discountAmount', 'giftCardAmount'];
1083
-
1084
- function stripZeroAmountLines(template, inv) {
1085
- var out = template;
1086
- for (var i = 0; i < OPTIONAL_AMOUNT_TOKENS.length; i++) {
1087
- var key = OPTIONAL_AMOUNT_TOKENS[i];
1088
- if (Number(inv[key] || 0) > 0) continue;
1089
- var line = new RegExp(
1090
- '<(tr|li|p)\\\\b(?:(?!<\\\\/?\\\\1\\\\b)[\\\\s\\\\S])*?\\\\{\\\\{' + key + '\\\\}\\\\}(?:(?!<\\\\/?\\\\1\\\\b)[\\\\s\\\\S])*?<\\\\/\\\\1\\\\s*>',
1091
- 'g'
1092
- );
1093
- out = out.replace(line, '');
1094
- }
1095
- return out;
1080
+ // The summary lines the email leaves out. An amount whose line means nothing at
1081
+ // zero: "Delivery $0.00" on a pickup order, "Discount −$0.00" without a
1082
+ // voucher, "Tax $0.00" in an untaxed store. And what a paid invoice no longer
1083
+ // asks for: its due date and the amount due. As on the PDF, the amount due is
1084
+ // printed only beside a gift card; without one it is the total again.
1085
+ var OPTIONAL_AMOUNT_TOKENS = ['shippingAmount', 'discountAmount', 'taxAmount', 'giftCardAmount'];
1086
+
1087
+ function omittedLineTokens(inv) {
1088
+ var tokens = OPTIONAL_AMOUNT_TOKENS.filter(function (key) {
1089
+ return !(Number(inv[key] || 0) > 0);
1090
+ });
1091
+ var paid = isSettledInvoice(inv.status);
1092
+ if (paid) tokens.push('dueDate');
1093
+ if (paid || !(Number(inv.giftCardAmount || 0) > 0)) tokens.push('amountDue');
1094
+ return tokens;
1095
+ }
1096
+
1097
+ // A line is the table row, list item or paragraph carrying the token, matched
1098
+ // innermost — a row inside a row keeps its parent. The editor's designs publish
1099
+ // each line as a <div> of <span>s instead, so a token outside those drops the
1100
+ // innermost <div> holding it, and only when that <div> is the line alone: one
1101
+ // that also holds a block or another token is the merchant's own, and stays.
1102
+ var NO_BLOCK_OR_TOKEN = '(?!<\\\\/?(?:div|p|tr|li|table|ul|ol|h[1-6])\\\\b|\\\\{\\\\{)';
1103
+
1104
+ function stripLinesHolding(template, key) {
1105
+ var token = '\\\\{\\\\{' + key + '\\\\}\\\\}';
1106
+ var row = new RegExp(
1107
+ '<(tr|li|p)\\\\b(?:(?!<\\\\/?\\\\1\\\\b)[\\\\s\\\\S])*?' + token + '(?:(?!<\\\\/?\\\\1\\\\b)[\\\\s\\\\S])*?<\\\\/\\\\1\\\\s*>',
1108
+ 'g'
1109
+ );
1110
+ var lineDiv = new RegExp(
1111
+ '<div\\\\b(?:' + NO_BLOCK_OR_TOKEN + '[\\\\s\\\\S])*?' + token + '(?:' + NO_BLOCK_OR_TOKEN + '[\\\\s\\\\S])*?<\\\\/div\\\\s*>',
1112
+ 'g'
1113
+ );
1114
+ return template.replace(row, '').replace(lineDiv, '');
1115
+ }
1116
+
1117
+ function stripOmittedLines(template, inv) {
1118
+ return omittedLineTokens(inv).reduce(function (out, key) {
1119
+ return stripLinesHolding(out, key);
1120
+ }, template);
1096
1121
  }
1097
1122
 
1098
1123
  function replacePlaceholders(template, data) {
@@ -1100,7 +1125,8 @@ function replacePlaceholders(template, data) {
1100
1125
  var inv = data.invoice || {};
1101
1126
  var cust = data.customer || {};
1102
1127
  var comp = data.company || {};
1103
- return stripZeroAmountLines(template, inv).replace(/\\{\\{(\\w+)\\}\\}/g, function (match, key) {
1128
+ var sym = inv.currencySymbol;
1129
+ return stripOmittedLines(template, inv).replace(/\\{\\{(\\w+)\\}\\}/g, function (match, key) {
1104
1130
  var map = {
1105
1131
  invoiceNumber: inv.number || '',
1106
1132
  customerName: cust.name || '',
@@ -1111,14 +1137,14 @@ function replacePlaceholders(template, data) {
1111
1137
  // so the mail and its attachment agree.
1112
1138
  invoiceDate: formatDateValue(inv.issueDate),
1113
1139
  dueDate: formatDateValue(inv.dueDate),
1114
- totalAmount: (inv.currencySymbol || '') + Number(inv.total || 0).toFixed(2),
1115
- subtotal: (inv.currencySymbol || '') + Number(inv.subtotal || 0).toFixed(2),
1116
- taxAmount: (inv.currencySymbol || '') + Number(inv.taxAmount || 0).toFixed(2),
1117
- shippingAmount: (inv.currencySymbol || '') + Number(inv.shippingAmount || 0).toFixed(2),
1118
- discountAmount: (inv.currencySymbol || '') + Number(inv.discountAmount || 0).toFixed(2),
1119
- giftCardAmount: (inv.currencySymbol || '') + Number(inv.giftCardAmount || 0).toFixed(2),
1140
+ totalAmount: formatCurrencyValue(inv.total, sym),
1141
+ subtotal: formatCurrencyValue(inv.subtotal, sym),
1142
+ taxAmount: formatCurrencyValue(inv.taxAmount, sym),
1143
+ shippingAmount: formatCurrencyValue(inv.shippingAmount, sym),
1144
+ discountAmount: formatCurrencyValue(inv.discountAmount, sym),
1145
+ giftCardAmount: formatCurrencyValue(inv.giftCardAmount, sym),
1120
1146
  // What is left after a gift card; the whole total when none was used.
1121
- amountDue: (inv.currencySymbol || '') + Number(inv.amountDue != null ? inv.amountDue : (inv.total || 0)).toFixed(2),
1147
+ amountDue: formatCurrencyValue(inv.amountDue != null ? inv.amountDue : inv.total, sym),
1122
1148
  companyName: comp.name || '',
1123
1149
  companyEmail: comp.email || '',
1124
1150
  invoiceUrl: inv.pdfUrl || '',
@@ -1136,6 +1162,9 @@ function buildDataContext(invoiceData) {
1136
1162
  return {
1137
1163
  invoice: {
1138
1164
  number: invoiceData.invoiceNumber || '',
1165
+ // Paid or not decides which lines the email keeps (see omittedLineTokens).
1166
+ status: invoiceData.status || '',
1167
+ paidAt: invoiceData.paidAt || null,
1139
1168
  issueDate: invoiceData.issueDate || '',
1140
1169
  dueDate: invoiceData.dueDate || '',
1141
1170
  subtotal: invoiceData.subtotal || 0,