better-supabase 0.42.0 → 0.43.0

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 (149) hide show
  1. package/dist/ai-sdk/agents/index.d.ts +2 -2
  2. package/dist/{app-tables-DGgCgRwq.d.ts → app-tables-CVMn4c4b.d.ts} +1 -1
  3. package/dist/{authorization-CcvJbvr1.d.ts → authorization-hGBtxrnQ.d.ts} +27 -2
  4. package/dist/{automations-CJhRmPmq.js → automations-K0O3En6E.js} +4 -1
  5. package/dist/{bind-B71jMEGG.d.ts → bind-DWAIKYvJ.d.ts} +1 -1
  6. package/dist/{block-env-DzYTC9d1.d.ts → block-env-C6OEu9Xk.d.ts} +3 -3
  7. package/dist/{block-subjects-a_ECM9o0.js → block-subjects-B1zfhFWC.js} +1 -1
  8. package/dist/{block-tables-B92SBFqM.d.ts → block-tables-BIExrL2J.d.ts} +1 -1
  9. package/dist/blocks/ai-chat/index.d.ts +3 -3
  10. package/dist/blocks/announcements/index.d.ts +3 -3
  11. package/dist/blocks/api-keys/index.d.ts +1 -1
  12. package/dist/blocks/attachments/index.d.ts +1 -1
  13. package/dist/blocks/audit/index.d.ts +2 -2
  14. package/dist/blocks/automations/index.d.ts +1 -1
  15. package/dist/blocks/billing/index.d.ts +1 -1
  16. package/dist/blocks/bookings/index.d.ts +1 -1
  17. package/dist/blocks/calendar/index.d.ts +1 -1
  18. package/dist/blocks/comments/index.d.ts +4 -4
  19. package/dist/blocks/entitlements/index.d.ts +2 -2
  20. package/dist/blocks/forms/index.d.ts +1 -1
  21. package/dist/blocks/inbox/index.d.ts +4 -4
  22. package/dist/blocks/index.d.ts +1 -1
  23. package/dist/blocks/invoices/index.d.ts +15 -1
  24. package/dist/blocks/invoices/index.js +13 -4
  25. package/dist/blocks/messaging/index.d.ts +4 -4
  26. package/dist/blocks/mfa/index.d.ts +1 -1
  27. package/dist/blocks/notifications/index.d.ts +3 -3
  28. package/dist/blocks/onboarding/index.d.ts +1 -1
  29. package/dist/blocks/organizations/index.d.ts +2 -2
  30. package/dist/blocks/permissions/index.d.ts +1 -1
  31. package/dist/blocks/push/index.d.ts +1 -1
  32. package/dist/blocks/quotes/index.d.ts +9 -4
  33. package/dist/blocks/quotes/index.js +5 -2
  34. package/dist/blocks/reactions/index.d.ts +3 -3
  35. package/dist/blocks/saved-views/index.d.ts +1 -1
  36. package/dist/blocks/search/index.d.ts +2 -2
  37. package/dist/blocks/sessions/index.d.ts +1 -1
  38. package/dist/blocks/settings/index.d.ts +1 -1
  39. package/dist/blocks/subjects/index.d.ts +1 -1
  40. package/dist/blocks/tags/index.d.ts +1 -1
  41. package/dist/blocks/undo/index.d.ts +1 -1
  42. package/dist/blocks/usage/index.d.ts +1 -1
  43. package/dist/blocks/workflow-editor/index.d.ts +3 -3
  44. package/dist/blocks/workflows/index.d.ts +3 -3
  45. package/dist/claims/index.d.ts +3 -3
  46. package/dist/cli/add-CjSPssgL.js +1 -0
  47. package/dist/cli/{add-NosuEQn1.js → add-fdZAY8C_.js} +10 -10
  48. package/dist/cli/{add-U0pyhIyx.js → add-uwUI80aZ.js} +2 -2
  49. package/dist/cli/{app-table-files-DUi898lB.js → app-table-files-BR_7lT4u.js} +2 -2
  50. package/dist/cli/{app-tables-BINtREbx.js → app-tables-DoxrhJb1.js} +2 -2
  51. package/dist/cli/{backfill-VfqI5GqN.js → backfill-BTMgDL6X.js} +1 -1
  52. package/dist/cli/bin.js +1 -1
  53. package/dist/cli/{blocks-DsEaPf6J.js → blocks-BgPbXNhB.js} +1 -1
  54. package/dist/cli/{blocks-Bo2Lw2UO.js → blocks-Bj0LS3rF.js} +1 -1
  55. package/dist/cli/{cache-CNJD8OdR.js → cache-CEGpAmXJ.js} +1 -1
  56. package/dist/cli/{codemod-BWa3Bte6.js → codemod-CaXGpQ10.js} +1 -1
  57. package/dist/cli/{content-mapper-Dl50Ny6a.js → content-mapper-BJRfCnFX.js} +2 -2
  58. package/dist/cli/{doctor-B9GtOGSa.js → doctor-CHQDLcwL.js} +15 -15
  59. package/dist/cli/{gen-CIUD1sgB.js → gen-DSK152A3.js} +11 -11
  60. package/dist/cli/index.d.ts +1 -1
  61. package/dist/cli/index.js +6 -6
  62. package/dist/cli/{init-wl5jk5vX.js → init-CPC1ceqC.js} +8 -8
  63. package/dist/cli/{live-B0f_X3rI.js → live-BFXisTDf.js} +2 -2
  64. package/dist/cli/{mcp-CZWaBkXY.js → mcp-CrulrTBs.js} +2 -2
  65. package/dist/cli/{metadata-Bi5eQP4w.js → metadata-yePOltZY.js} +3 -3
  66. package/dist/cli/{migrate-DMITLPEu.js → migrate-kjYx7du-.js} +1 -1
  67. package/dist/cli/{migration-safety-2n8e8njJ.js → migration-safety-DnvCYRsw.js} +1 -1
  68. package/dist/cli/{migrations-C5k9hNOo.js → migrations-ZYHA0gks.js} +2 -2
  69. package/dist/cli/{module-migration-BFchEhAJ.js → module-migration-Du7UHsO9.js} +2 -2
  70. package/dist/cli/{powersync-DViexv6m.js → powersync-BOxy1_xW.js} +3 -3
  71. package/dist/cli/powersync-BurpZLJB.js +1 -0
  72. package/dist/cli/{print-ChX1vQhO.js → print-B4OqfSML.js} +2 -2
  73. package/dist/cli/{providers-lwK2lplZ.js → providers-KYOKi_jp.js} +1 -1
  74. package/dist/cli/{prune-workflows-DO3nRZFF.js → prune-workflows-7JISyAI7.js} +1 -1
  75. package/dist/cli/{remove-WB9dFyNn.js → remove-DvncDSRp.js} +5 -5
  76. package/dist/cli/{render-B0MMWWZE.js → render-C6dQ0C0Y.js} +3 -3
  77. package/dist/cli/{run-CmJbNG2-.js → run-BYiApqFR.js} +9 -9
  78. package/dist/cli/{run-CMvwtBX9.js → run-DWDRg4vp.js} +27 -27
  79. package/dist/cli/{shared-BL5kcRdz.js → shared-DC86fQYk.js} +1 -1
  80. package/dist/cli/{snapshot-CVB9Ri2a.js → snapshot-CwCG_YX2.js} +2 -2
  81. package/dist/cli/{source-COGgsYiV.js → source-DDxRHVzk.js} +1 -1
  82. package/dist/cli/{spec-CH6Qd2LE.js → spec-Cnxqc7kC.js} +2 -2
  83. package/dist/cli/{spec-002zD_9Z.js → spec-CvKJ6GpI.js} +1 -1
  84. package/dist/cli/{sql-layout-jZOzCj-S.js → sql-layout-BwbfVSR8.js} +2 -2
  85. package/dist/cli/{sync-I4x-1aVx.js → sync-lpbLqJly.js} +4 -4
  86. package/dist/cli/{upgrade-BRp5AxAY.js → upgrade-34ZODJZj.js} +2 -2
  87. package/dist/cli/{upgrade-C60BZggI.js → upgrade-Cq4EFBH7.js} +5 -5
  88. package/dist/cli/{version-CRCAxS2s.js → version-BGN5319Z.js} +1 -1
  89. package/dist/client/index.d.ts +5 -5
  90. package/dist/client/native/index.d.ts +4 -4
  91. package/dist/config/index.d.ts +2 -2
  92. package/dist/config/index.js +4 -4
  93. package/dist/{config-BND2PFGs.js → config-BN17nVp1.js} +1 -1
  94. package/dist/{config-2SwAe0Im.js → config-C-eXOuhp.js} +3 -3
  95. package/dist/{context-DXWyPNzr.d.ts → context-Dga2sgyx.d.ts} +1 -1
  96. package/dist/contract/index.d.ts +3 -3
  97. package/dist/{controller-D3MPVovD.d.ts → controller-BFOCK5AG.d.ts} +1 -1
  98. package/dist/create/index.d.ts +3 -3
  99. package/dist/create/index.js +3 -3
  100. package/dist/create/lite/index.d.ts +3 -3
  101. package/dist/create/lite/index.js +2 -2
  102. package/dist/{entitlements-CljrSoWD.d.ts → entitlements-C5k_9hHt.d.ts} +1 -1
  103. package/dist/{field-errors-C4NOUBpu.d.ts → field-errors-LVBXokQN.d.ts} +4 -4
  104. package/dist/{index-BrGOE0c2.d.ts → index-BA8sPQ49.d.ts} +2 -2
  105. package/dist/{index-DWVDKVYA.d.ts → index-BhmjjkMu.d.ts} +1 -1
  106. package/dist/{index-D5qW2cRD.d.ts → index-CjN6kzvL.d.ts} +2 -2
  107. package/dist/{index-DmSDAFkF.d.ts → index-D-SIdOiL.d.ts} +6 -6
  108. package/dist/{index-Bjj-GNhd.d.ts → index-DBbdaYAH.d.ts} +1 -1
  109. package/dist/{index-DhHtsi-q.d.ts → index-DUmsXPdh.d.ts} +1 -1
  110. package/dist/{index-CUxdZYSi.d.ts → index-DwP65vFk.d.ts} +2 -2
  111. package/dist/{instances-DwrdFwKq.js → instances-Bx94JGSW.js} +3 -0
  112. package/dist/mapper/bin.js +5 -5
  113. package/dist/mcp/index.d.ts +1 -1
  114. package/dist/next/index.d.ts +4 -4
  115. package/dist/{operations-DFmuxaxW.d.ts → operations-J0PkKTaF.d.ts} +1 -1
  116. package/dist/{options-C5cLEJEa.js → options-ByxOMSXu.js} +2 -1
  117. package/dist/otel/index.js +4 -4
  118. package/dist/{permissions-Bsd4mEEZ.d.ts → permissions-Cp2qvVJo.d.ts} +1 -1
  119. package/dist/{ports-BKdt_9Oe.d.ts → ports-C61eesjD.d.ts} +1 -1
  120. package/dist/powersync/index.d.ts +2 -2
  121. package/dist/preset/index.d.ts +3 -3
  122. package/dist/preset/index.js +3 -3
  123. package/dist/{preset-CenE7f1G.js → preset-yRJgGbn9.js} +2 -2
  124. package/dist/{project-Ceh2yTSv.js → project-ps9mOsLx.js} +5 -5
  125. package/dist/{push-token-DRcEl9Ce.d.ts → push-token-2LRdwl_8.d.ts} +1 -1
  126. package/dist/react/index.d.ts +5 -5
  127. package/dist/react/native/index.d.ts +1 -1
  128. package/dist/react/server.d.ts +5 -5
  129. package/dist/realtime/index.d.ts +3 -3
  130. package/dist/records/index.d.ts +3 -3
  131. package/dist/server/index.d.ts +3 -3
  132. package/dist/solid/index.d.ts +5 -5
  133. package/dist/sql/index.d.ts +5 -5
  134. package/dist/sql/index.js +2 -2
  135. package/dist/{sql-BIniB45X.js → sql-CWzlxS6f.js} +348 -130
  136. package/dist/ssr/index.d.ts +1 -1
  137. package/dist/svelte/index.d.ts +5 -5
  138. package/dist/{tenant--Hm8mlPy.d.ts → tenant-P7mo0ulH.d.ts} +1 -1
  139. package/dist/testing/index.d.ts +3 -3
  140. package/dist/testing/index.js +1 -1
  141. package/dist/{topic-BYF-GTW9.d.ts → topic-CjKlzHD-.d.ts} +1 -1
  142. package/dist/{types-B8h0reJ4.d.ts → types-VwM7DBvC.d.ts} +2 -2
  143. package/dist/vue/index.d.ts +5 -5
  144. package/dist/{watch-topic-tfTxgEGc.d.ts → watch-topic-jqBMNMs3.d.ts} +1 -1
  145. package/dist/yjs/index.d.ts +1 -1
  146. package/package.json +1 -1
  147. package/schemas/config-v1.json +17 -0
  148. package/dist/cli/add-BbhRYaFe.js +0 -1
  149. package/dist/cli/powersync-i7KJcTtM.js +0 -1
@@ -3,10 +3,10 @@ import { d as temporalText } from "./temporal-DKTdGK9i.js";
3
3
  import { r as NEGATIVE, t as FILTER_OPERATORS } from "./filter-query-Ds7Z6lgZ.js";
4
4
  import { a as ok } from "./result-8xza7w5W.js";
5
5
  import { a as hasPlaceholder, l as splitPlaceholders, s as placeholderOf } from "./read-set-DEDoIHMM.js";
6
- import { c as resolveJsonSchema, i as installedBlockSubjects, l as CONFIG_DEFAULTS, o as blockColumnName, s as resolveNames } from "./block-subjects-a_ECM9o0.js";
6
+ import { c as resolveJsonSchema, i as installedBlockSubjects, l as CONFIG_DEFAULTS, o as blockColumnName, s as resolveNames } from "./block-subjects-B1zfhFWC.js";
7
7
  import { t as DEFAULT_CLAIMS } from "./claims-CqTr_N1n.js";
8
8
  import { o as tenantNames, r as composeNames } from "./entity-naming-BES3pkQI.js";
9
- import { C as encryptedColumns, I as resolveBlock, L as tenantNameOf, N as BLOCK_SCOPES, S as columnsWithAccess, T as hiddenColumns, a as isRenamedInstance, g as appTableVersions, i as instancePrefix, l as APP_RANK_COLUMN, m as appTableEventKinds, s as APP_DELETED_AT_COLUMN, w as hasColumnAccess, x as hasComputed } from "./instances-DwrdFwKq.js";
9
+ import { C as encryptedColumns, I as resolveBlock, L as tenantNameOf, N as BLOCK_SCOPES, S as columnsWithAccess, T as hiddenColumns, a as isRenamedInstance, g as appTableVersions, i as instancePrefix, l as APP_RANK_COLUMN, m as appTableEventKinds, s as APP_DELETED_AT_COLUMN, w as hasColumnAccess, x as hasComputed } from "./instances-Bx94JGSW.js";
10
10
  import { a as RATING_BOUNDS, n as CUSTOM_FIELD_TYPES, r as FIELD_FORMATS, t as CUSTOM_FIELD_FORM_TYPES } from "./field-formats-Cap-V7UP.js";
11
11
  import { t as isSqlType } from "./sql-type-XWMeZRAl.js";
12
12
  import { a as sqlString, i as sqlIdent } from "./template-CNq9xcfx.js";
@@ -62,7 +62,7 @@ import { t as identitiesSqlOptions } from "./options-D5a9CHgP.js";
62
62
  import { r as inboxSqlOptions, t as CONVERSATION_TO_TASK } from "./automations-CCc5RUw-.js";
63
63
  import { t as incidentsSqlOptions } from "./options-BmFSI07A.js";
64
64
  import { t as inventorySqlOptions } from "./options-D4LuPM8a.js";
65
- import { t as invoicesSqlOptions } from "./options-C5cLEJEa.js";
65
+ import { t as invoicesSqlOptions } from "./options-ByxOMSXu.js";
66
66
  import { t as knowledgeSqlOptions } from "./options-CyYZvdSy.js";
67
67
  import { t as leadScoringSqlOptions } from "./options-COfEYic3.js";
68
68
  import { t as leasesSqlOptions } from "./options-CzIPn0fF.js";
@@ -88,7 +88,7 @@ import { t as profilesSqlOptions } from "./options-BxdqA2Ex.js";
88
88
  import { t as promotionsSqlOptions } from "./options-BvttpM1M.js";
89
89
  import { t as pushSqlOptions } from "./options-jg0FMHA5.js";
90
90
  import { n as rateLimitSqlOptions, r as webhookInboxSqlOptions, t as queueSqlOptions } from "./options-BTRH26MJ.js";
91
- import { n as QUOTE_TO_ORDER, r as quotesSqlOptions } from "./automations-CJhRmPmq.js";
91
+ import { n as QUOTE_TO_ORDER, r as quotesSqlOptions } from "./automations-K0O3En6E.js";
92
92
  import { t as reactionsSqlOptions } from "./options-BcBdiPSZ.js";
93
93
  import { t as relationsSqlOptions } from "./options-Lg76d-cV.js";
94
94
  import { t as remindersSqlOptions } from "./options-PTLBl6QT.js";
@@ -53304,11 +53304,12 @@ function totalColumnsSql(ctx, table) {
53304
53304
  * of them the plain line sums stay, so deals and invoices render as before.
53305
53305
  */
53306
53306
  function documentTotals(ctx, items) {
53307
+ const parentHas = items.parentHas ?? ((column) => declared(ctx, items.parent, column));
53307
53308
  return [
53308
53309
  "pricesIncludeTax",
53309
53310
  "discountBps",
53310
53311
  "discountAmount"
53311
- ].some((column) => declared(ctx, items.parent, column)) || declared(ctx, items.lines, "optional") || items.taxLines !== void 0 && ctx.hasTable(items.taxLines);
53312
+ ].some(parentHas) || declared(ctx, items.lines, "optional") || items.taxLines !== void 0 && ctx.hasTable(items.taxLines);
53312
53313
  }
53313
53314
  /**
53314
53315
  * The recount of a record whose totals follow its tax rates.
@@ -53327,7 +53328,7 @@ function documentRecountSql(ctx, items, options) {
53327
53328
  const c = (column) => ctx.col(items.lines, column);
53328
53329
  const pc = (column) => ctx.col(items.parent, column);
53329
53330
  const l = (column) => lineColumn(ctx, items.lines, "l", column);
53330
- const parentHas = (column) => declared(ctx, items.parent, column);
53331
+ const parentHas = items.parentHas ?? ((column) => declared(ctx, items.parent, column));
53331
53332
  const parent = `${options.setter}_recount.parent`;
53332
53333
  const amount = lineAmount(ctx, items.lines, "l");
53333
53334
  const discount = declared(ctx, items.lines, "discountBps") ? `round(${amount} * ${l("discountBps")} / 10000.0)` : "0";
@@ -62424,7 +62425,7 @@ function quoteKit(ctx, n) {
62424
62425
  if ${given} is not null then
62425
62426
  ${fail$1(`QUOTE_${thing}_UNSUPPORTED`, `this quotes table has no ${what}`, "22023")}
62426
62427
  end if;`;
62427
- const editable = (alias) => `(${n.service} or ${ctx.scope.can(`${alias}.${q("tenant")}`, n.write)})`;
62428
+ const editable = (alias, key = n.write) => `(${n.service} or ${ctx.scope.can(`${alias}.${q("tenant")}`, key)})`;
62428
62429
  const st = (value, labels, negate = false) => ctx.is("quotes", "status", value, labels, negate);
62429
62430
  const sv = (label) => ctx.value("quotes", "status", label);
62430
62431
  const viewed = ctx.appValues("quotes", "status", "viewed").length > 0;
@@ -62442,12 +62443,19 @@ function quoteKit(ctx, n) {
62442
62443
  end if;` : " null;";
62443
62444
  const workingCopy = workingCopyOn(ctx);
62444
62445
  const versionLines = versionLinesOn(ctx);
62445
- const open = (alias) => st(`${alias}.${q("status")}`, workingCopy ? [
62446
+ const declined = n.resend ? [
62447
+ "rejected",
62448
+ "withdrawn",
62449
+ "expired"
62450
+ ] : [];
62451
+ const openStatuses = workingCopy ? [
62446
62452
  "draft",
62447
62453
  "changes_requested",
62448
62454
  "sent",
62449
- "viewed"
62450
- ] : ["draft", "changes_requested"]);
62455
+ "viewed",
62456
+ ...declined
62457
+ ] : ["draft", "changes_requested"];
62458
+ const open = (alias) => st(`${alias}.${q("status")}`, openStatuses);
62451
62459
  const lineValue = (column) => lineColumn(ctx, "lines", "ql", column);
62452
62460
  const documentLine = [
62453
62461
  "section",
@@ -62522,6 +62530,8 @@ function quoteKit(ctx, n) {
62522
62530
  st,
62523
62531
  sv,
62524
62532
  open,
62533
+ openStatuses,
62534
+ declined,
62525
62535
  lines,
62526
62536
  taxLines,
62527
62537
  row,
@@ -62534,7 +62544,7 @@ function quoteKit(ctx, n) {
62534
62544
  checkParty,
62535
62545
  notifyOwner,
62536
62546
  markViewed,
62537
- depositDue: has("depositDue") && (has("depositBps") || has("depositAmount")) ? `${q("depositDue")} = case${has("depositAmount") ? ` when x.${q("depositAmount")} is not null then least(greatest(${total}, 0), x.${q("depositAmount")})` : ""}${has("depositBps") ? ` when x.${q("depositBps")} is not null then round(${total} * x.${q("depositBps")} / 10000.0)::bigint` : ""} else 0 end` : void 0
62547
+ depositDue: !n.appTotals && has("depositDue") && (has("depositBps") || has("depositAmount")) ? `${q("depositDue")} = case${has("depositAmount") ? ` when x.${q("depositAmount")} is not null then least(greatest(${total}, 0), x.${q("depositAmount")})` : ""}${has("depositBps") ? ` when x.${q("depositBps")} is not null then round(${total} * x.${q("depositBps")} / 10000.0)::bigint` : ""} else 0 end` : void 0
62538
62548
  };
62539
62549
  }
62540
62550
  // src/sql/modules/quotes-decisions.ts
@@ -62671,6 +62681,23 @@ function quoteDecisions(ctx, n, k) {
62671
62681
  if ${a.name}.decision = 'accepted' then
62672
62682
  ${ctx.hook("after_quote_accept", [["uuid", `v_row.${q("id")}`]])}
62673
62683
  end if;`;
62684
+ const viewer = (actor) => {
62685
+ const own = `begin
62686
+ v_ip := ${ip}::inet;
62687
+ exception when invalid_text_representation then
62688
+ v_ip := null;
62689
+ end;
62690
+ perform set_config('better_supabase.transition_actor', jsonb_strip_nulls(jsonb_build_object('email', auth.jwt() ->> 'email', 'ip', v_ip::text, 'userAgent', left(v_headers ->> 'user-agent', 512)))::text, true);`;
62691
+ return actor === void 0 ? `
62692
+ ${own}` : `
62693
+ if ${actor} is not null and not ${n.service} then
62694
+ ${fail$1("QUOTE_ACTOR_FORBIDDEN", "only the service role names who opened a quote", "42501")}
62695
+ end if;
62696
+ ${transitionActorSql(actor, "QUOTE_ACTOR_INVALID")}
62697
+ if ${actor} is null then
62698
+ ${own.replaceAll("\n", "\n ")}
62699
+ end if;`;
62700
+ };
62674
62701
  const answered = `jsonb_build_object('status', ${ctx.label("quotes", "status", `v_row.${q("status")}`)}, 'identifier', v_row.${q("identifier")}, 'revision', v_row.${q("revision")})`;
62675
62702
  const customerView = k.workingCopy ? `select v.${n.c("versions", "snapshot")} into v_snap from ${t("versions")} v where v.${n.c("versions", "id")} = ${k.latestVersion("v_row")};
62676
62703
  if v_snap is null then
@@ -62698,7 +62725,7 @@ declare
62698
62725
  v_row ${t("quotes")};
62699
62726
  v_claims text;${restoreVars}
62700
62727
  begin
62701
- select * into v_row from ${t("quotes")} x where x.${q("id")} = decide_quote.quote and ${editable("x")} for update;
62728
+ select * into v_row from ${t("quotes")} x where x.${q("id")} = decide_quote.quote and ${editable("x", n.decide)} for update;
62702
62729
  if v_row.${q("id")} is null then
62703
62730
  ${fail$1("QUOTE_NOT_FOUND", "no such quote you can edit", "P0002")}
62704
62731
  end if;${answer({
@@ -62723,12 +62750,12 @@ security definer
62723
62750
  set search_path = ''
62724
62751
  as $$
62725
62752
  declare
62726
- v_row ${t("quotes")};${restoreVars}
62753
+ v_row ${t("quotes")};${headers}${restoreVars}
62727
62754
  begin
62728
62755
  select * into v_row from ${t("quotes")} x where x.${q("tokenHash")} = ${sha256Hex$1("public_quote.token")};
62729
62756
  if v_row.${q("id")} is null then
62730
62757
  ${fail$1("QUOTE_LINK_INVALID", "this link is not valid", "P0002")}
62731
- end if;
62758
+ end if;${viewer()}
62732
62759
  ${k.markViewed()}
62733
62760
  ${customerView}
62734
62761
  end;
@@ -62770,16 +62797,18 @@ grant execute on function ${fn("respond_to_quote")}(text, text, text, text, json
62770
62797
  -- A quote shared with the signed-in guest, as the customer sees it: through
62771
62798
  -- a grant on the quote or as a guest of its company or contact. Opening a
62772
62799
  -- sent quote marks it viewed. No link token is needed. The service role
62773
- -- reads it too, for an app's own portal.
62774
- create or replace function ${fn("portal_quote")}(quote uuid)
62800
+ -- reads it too, for an app's own portal; actor is then the customer who
62801
+ -- opened it, for the state machine's history.
62802
+ drop function if exists ${fn("portal_quote")}(uuid);
62803
+ create or replace function ${fn("portal_quote")}(quote uuid, actor jsonb default null)
62775
62804
  returns jsonb
62776
62805
  language plpgsql
62777
62806
  security definer
62778
62807
  set search_path = ''
62779
62808
  as $$
62780
62809
  declare
62781
- v_row ${t("quotes")};${restoreVars}
62782
- begin
62810
+ v_row ${t("quotes")};${headers}${restoreVars}
62811
+ begin${viewer("portal_quote.actor")}
62783
62812
  select * into v_row from ${t("quotes")} x where x.${q("id")} = portal_quote.quote and (${guest} or (${n.service} and ${k.st(`x.${q("status")}`, ["draft"], true)}));
62784
62813
  if v_row.${q("id")} is null then
62785
62814
  ${fail$1("QUOTE_NOT_FOUND", "no such quote shared with you", "P0002")}
@@ -62788,7 +62817,7 @@ ${k.markViewed()}
62788
62817
  ${customerView}
62789
62818
  end;
62790
62819
  $$;
62791
- ${userGrant(`${fn("portal_quote")}(uuid)`)}
62820
+ ${userGrant(`${fn("portal_quote")}(uuid, jsonb)`)}
62792
62821
 
62793
62822
  -- The signed-in guest's answer to a quote shared with them, like
62794
62823
  -- respond_to_quote without a token. name defaults to their email; the
@@ -62913,6 +62942,7 @@ function quoteFunctions(ctx, n) {
62913
62942
  ${fail$1("QUOTE_ATTRS_INVALID", "a deposit is a share (depositBps) or an amount (depositAmount), not both", "22023")}
62914
62943
  end if;` : "";
62915
62944
  const actor = (name) => `\n ${transitionActorSql(`${name}.actor`, "QUOTE_ACTOR_INVALID")}`;
62945
+ const resent = k.declined.length === 0 ? "" : `${q("validUntil")} = case when ${st(`x.${q("status")}`, k.declined)} then greatest(x.${q("validUntil")}, current_date + ${String(n.validDays)}) else x.${q("validUntil")} end, ${has("viewedAt") && !k.workingCopy ? `${q("viewedAt")} = case when ${st(`x.${q("status")}`, k.declined)} then null else x.${q("viewedAt")} end, ` : ""}`;
62916
62946
  const publishedBy = `coalesce(auth.uid(), nullif(send_quote.actor ->> 'id', '')::uuid)`;
62917
62947
  const versionLinesCopy = (() => {
62918
62948
  if (!k.versionLines) return "";
@@ -62933,9 +62963,11 @@ function quoteFunctions(ctx, n) {
62933
62963
  "productId"
62934
62964
  ].filter((column) => declared(ctx, "versionLines", column) && declared(ctx, "lines", column));
62935
62965
  const value = (column) => column === "productType" ? ctx.cast("versionLines", column, `ql.${l(column)}::text`) : `ql.${l(column)}`;
62966
+ const lineExtraNames = new Set(n.lineExtras.map((extra) => extra.name));
62967
+ const extras = n.versionLineExtras.filter((extra) => lineExtraNames.has(extra.name)).map((extra) => extra.ident);
62936
62968
  return `
62937
- insert into ${t("versionLines")} (${vl("tenant")}, ${vl("version")}, ${copied.map(vl).join(", ")})
62938
- select v_row.${q("tenant")}, v_version, ${copied.map(value).join(", ")}
62969
+ insert into ${t("versionLines")} (${vl("tenant")}, ${vl("version")}, ${[...copied.map(vl), ...extras].join(", ")})
62970
+ select v_row.${q("tenant")}, v_version, ${[...copied.map(value), ...extras.map((ident) => `ql.${ident}`)].join(", ")}
62939
62971
  from ${t("lines")} ql where ql.${l("parent")} = v_row.${q("id")};`;
62940
62972
  })();
62941
62973
  const deals = ctx.installed("deals") ? ctx.of("deals") : void 0;
@@ -63099,8 +63131,8 @@ begin
63099
63131
  select * into v_row from ${t("quotes")} x where x.${q("id")} = v_row.${q("id")};`}
63100
63132
  exception when check_violation or invalid_text_representation or datetime_field_overflow or numeric_value_out_of_range then
63101
63133
  ${fail$1("QUOTE_ATTRS_INVALID", "a quote field has an invalid value", "22023")}
63102
- end;${oneDeposit}
63103
- perform ${fn("set_quote_lines_recount")}(v_row.${q("id")});
63134
+ end;${oneDeposit}${n.appTotals ? "" : `
63135
+ perform ${fn("set_quote_lines_recount")}(v_row.${q("id")});`}
63104
63136
  select * into v_row from ${t("quotes")} x where x.${q("id")} = v_row.${q("id")};
63105
63137
  ${record("quote.updated", "v_row")}
63106
63138
  return ${row("v_row")};
@@ -63113,6 +63145,7 @@ ${lineItemsSql(ctx, {
63113
63145
  frozen: `not (${open("p")})`,
63114
63146
  extras: n.lineExtras,
63115
63147
  taxLines: "taxLines",
63148
+ totals: !n.appTotals,
63116
63149
  ...k.depositDue === void 0 ? {} : { afterTotals: k.depositDue }
63117
63150
  }, {
63118
63151
  setter: "set_quote_lines",
@@ -63141,11 +63174,11 @@ declare
63141
63174
  v_token text := encode(extensions.gen_random_bytes(24), 'hex');
63142
63175
  v_version uuid;${k.workingCopy ? "\n v_linked boolean;" : ""}
63143
63176
  begin
63144
- select * into v_row from ${t("quotes")} x where x.${q("id")} = send_quote.quote and ${editable("x")} for update;
63177
+ select * into v_row from ${t("quotes")} x where x.${q("id")} = send_quote.quote and ${editable("x", n.send)} for update;
63145
63178
  if v_row.${q("id")} is null then
63146
63179
  ${fail$1("QUOTE_NOT_FOUND", "no such quote you can edit", "P0002")}
63147
63180
  end if;
63148
- if not (${open("v_row")}) then
63181
+ if not (${open("v_row")}${k.declined.length > 0 && !k.workingCopy ? ` or ${st(`v_row.${q("status")}`, k.declined)}` : ""}) then
63149
63182
  ${fail$1("QUOTE_NOT_EDITABLE", "the quote was already sent; revise it to send a new version", "55000")}
63150
63183
  end if;
63151
63184
  if not exists (select 1 from ${t("lines")} x where x.${l("parent")} = v_row.${q("id")}) then
@@ -63154,7 +63187,7 @@ begin
63154
63187
  ${ctx.hook("before_quote_send", [["uuid", `v_row.${q("id")}`]])}${k.workingCopy ? `\n v_linked := v_row.${q("tokenHash")} is not null;` : ""}
63155
63188
  update ${t("quotes")} x set ${q("status")} = ${sv("sent")}, ${q("sentAt")} = now(), ${q("tokenHash")} = ${k.workingCopy ? `coalesce(x.${q("tokenHash")}, ${sha256Hex$1("v_token")})` : sha256Hex$1("v_token")},
63156
63189
  ${q("revision")} = case when exists (select 1 from ${t("versions")} v where v.${v("quote")} = x.${q("id")} and v.${v("revision")} = x.${q("revision")}) then x.${q("revision")} + 1 else x.${q("revision")} end,
63157
- ${decisionReset}${k.workingCopy ? `${q("unpublishedChanges")} = false, ` : ""}${q("updatedAt")} = now()
63190
+ ${decisionReset}${resent}${k.workingCopy ? `${q("unpublishedChanges")} = false, ` : ""}${q("updatedAt")} = now()
63158
63191
  where x.${q("id")} = v_row.${q("id")}
63159
63192
  returning * into v_row;
63160
63193
  insert into ${t("versions")} (${v("tenant")}, ${v("quote")}, ${v("revision")}, ${v("snapshot")}, ${v("total")}, ${v("currency")}${ctx.has("versions", "publishedBy") ? `, ${v("publishedBy")}` : ""})
@@ -63204,8 +63237,8 @@ end;
63204
63237
  $$;
63205
63238
  ${userGrant(`${fn("revise_quote")}(uuid, jsonb)`)}
63206
63239
 
63207
- -- Takes back a sent quote the customer hasn't accepted: it can't be answered
63208
- -- any more until it is revised and sent again.
63240
+ -- Takes back a sent or expired quote the customer hasn't accepted: it can't
63241
+ -- be answered any more until it is revised and sent again.
63209
63242
  create or replace function ${fn("withdraw_quote")}(quote uuid, actor jsonb default null)
63210
63243
  returns jsonb
63211
63244
  language plpgsql
@@ -63215,14 +63248,15 @@ as $$
63215
63248
  declare
63216
63249
  v_row ${t("quotes")};
63217
63250
  begin
63218
- select * into v_row from ${t("quotes")} x where x.${q("id")} = withdraw_quote.quote and ${editable("x")} for update;
63251
+ select * into v_row from ${t("quotes")} x where x.${q("id")} = withdraw_quote.quote and ${editable("x", n.withdraw)} for update;
63219
63252
  if v_row.${q("id")} is null then
63220
63253
  ${fail$1("QUOTE_NOT_FOUND", "no such quote you can edit", "P0002")}
63221
63254
  end if;
63222
63255
  if ${st(`v_row.${q("status")}`, [
63223
63256
  "sent",
63224
63257
  "viewed",
63225
- "changes_requested"
63258
+ "changes_requested",
63259
+ "expired"
63226
63260
  ], true)} then
63227
63261
  ${fail$1("QUOTE_NOT_OPEN", "only a sent quote that wasn't answered is withdrawn", "55000")}
63228
63262
  end if;${actor("withdraw_quote")}
@@ -63246,6 +63280,7 @@ declare
63246
63280
  v_row ${t("quotes")};
63247
63281
  v_count integer := 0;
63248
63282
  begin
63283
+ perform set_config('better_supabase.transition_actor', '', true);
63249
63284
  for v_row in
63250
63285
  update ${t("quotes")} x set ${q("status")} = ${sv("expired")}, ${q("updatedAt")} = now()
63251
63286
  where ${st(`x.${q("status")}`, ["sent", "viewed"])} and x.${q("validUntil")} < current_date
@@ -63258,7 +63293,47 @@ begin
63258
63293
  end;
63259
63294
  $$;
63260
63295
  ${serviceGrant(`${fn("expire_quotes")}()`)}
63261
- ${fromDeal}`;
63296
+ ${appTotalsGuard(ctx, n, k)}${fromDeal}`;
63297
+ }
63298
+ /**
63299
+ * With `options.totals: "app"`, a trigger on the quotes table that refuses a
63300
+ * change to the totals once a quote is answered, expired or withdrawn, and
63301
+ * keeps the deposit due on the app's total.
63302
+ */
63303
+ function appTotalsGuard(ctx, n, k) {
63304
+ if (!n.appTotals) return "";
63305
+ const { q, has, st } = k;
63306
+ const trigger = ctx.trigger("quotes_app_totals");
63307
+ const fn = `better_supabase.${trigger.replaceAll("\"", "")}()`;
63308
+ const totals = Object.keys(TOTAL_COLUMNS).filter(has).map(q);
63309
+ const changeable = [.../* @__PURE__ */ new Set([
63310
+ ...k.openStatuses,
63311
+ "sent",
63312
+ "viewed"
63313
+ ])];
63314
+ const depositDue = has("depositDue") ? `
63315
+ new.${q("depositDue")} := case${has("depositAmount") ? ` when new.${q("depositAmount")} is not null then least(greatest(new.${q("total")}, 0), new.${q("depositAmount")})` : ""}${has("depositBps") ? ` when new.${q("depositBps")} is not null then round(new.${q("total")} * new.${q("depositBps")} / 10000.0)::bigint` : ""} else 0 end;` : "";
63316
+ return `
63317
+ -- The app keeps the quote's totals: once a quote is answered, expired or
63318
+ -- withdrawn they no longer change, and the deposit due follows the total.
63319
+ create or replace function ${fn}
63320
+ returns trigger
63321
+ language plpgsql
63322
+ set search_path = ''
63323
+ as $$
63324
+ begin
63325
+ if tg_op = 'UPDATE' and ${st(`old.${q("status")}`, changeable, true)}
63326
+ and (${totals.map((column) => `new.${column}`).join(", ")}) is distinct from (${totals.map((column) => `old.${column}`).join(", ")}) then
63327
+ ${fail$1("QUOTE_TOTALS_FROZEN", "the totals of an answered, expired or withdrawn quote don't change", "55000")}
63328
+ end if;${depositDue}
63329
+ return new;
63330
+ end;
63331
+ $$;
63332
+ ${triggerGrant(fn)}
63333
+ drop trigger if exists ${trigger} on ${n.t("quotes")};
63334
+ create trigger ${trigger} before insert or update on ${n.t("quotes")}
63335
+ for each row execute function ${fn};
63336
+ `;
63262
63337
  }
63263
63338
  // src/sql/modules/employees-functions.ts
63264
63339
  /**
@@ -86532,7 +86607,156 @@ const INVITATIONS = {
86532
86607
  }],
86533
86608
  build: invitationsSql
86534
86609
  };
86610
+ // src/sql/modules/invoices-from-quote.ts
86611
+ /**
86612
+ * `invoice_from_quote`: a deposit invoice for a share or an amount of an
86613
+ * accepted quote, or the final invoice less the deposits issued. Empty without
86614
+ * the quotes module.
86615
+ */
86616
+ function invoiceFromQuote(ctx, n, k) {
86617
+ const quotes = ctx.installed("quotes") ? ctx.of("quotes") : void 0;
86618
+ if (quotes === void 0) return "";
86619
+ const { fn, t } = n;
86620
+ const i = (column) => n.c("invoices", column);
86621
+ const { has, row, refuse, st, kd, origin, company, contact } = k;
86622
+ const q = (column) => quotes.col("quotes", column);
86623
+ const ql = (column) => quotes.col("lines", column);
86624
+ const kind = n.depositKind;
86625
+ const bpsDeposits = kind !== void 0 || has("depositBps");
86626
+ const amountDeposits = kind !== void 0 || has("depositAmount");
86627
+ const markers = ["depositBps", "depositAmount"].filter(has);
86628
+ const deposits = kind !== void 0 || markers.length > 0;
86629
+ const isDeposit = (alias) => kind === void 0 ? markers.map((column) => `${alias}.${i(column)} is not null`).join(" or ") : `${alias}.${i("kind")}::text = ${sqlString(kind)}`;
86630
+ const notDeposit = (alias) => kind === void 0 ? markers.map((column) => `${alias}.${i(column)} is null and `).join("") : `${alias}.${i("kind")}::text <> ${sqlString(kind)} and `;
86631
+ const originIs = (alias) => `${origin === "pair" ? `${alias}.${i("originType")} = 'quote' and ` : ""}${alias}.${i("originId")}::text = v_quote.${q("id")}::text`;
86632
+ const inclusive = has("pricesIncludeTax") && quotes.has("quotes", "pricesIncludeTax") ? `v_quote.${q("pricesIncludeTax")}` : "false";
86633
+ const base = (alias) => `case when ${inclusive} then ${alias}.${q("total")} else ${alias}.${q("subtotal")} end`;
86634
+ const blendedRate = `case when v_quote.${q("subtotal")} = 0 then 0 else round(v_quote.${q("taxTotal")} * 10000.0 / v_quote.${q("subtotal")})::integer end`;
86635
+ const taxLines = quotes.hasTable("taxLines") ? (column) => quotes.col("taxLines", column) : void 0;
86636
+ const invoiceLineExtras = new Set(n.lineExtras.map((extra) => extra.name));
86637
+ const lineFields = lineExtraColumns(quotes).filter((extra) => invoiceLineExtras.has(extra.name));
86638
+ const lineFieldsSql = lineFields.length === 0 ? "" : `, 'fields', jsonb_build_object(${lineFields.map((extra) => `${sqlString(extra.name)}, x.${extra.ident}`).join(", ")})`;
86639
+ const invoiceExtras = new Set(n.extras.map((extra) => extra.name));
86640
+ const headerFields = quotes.extraColumns("quotes", [
86641
+ "lines",
86642
+ "token",
86643
+ "fields"
86644
+ ]).filter((extra) => invoiceExtras.has(extra.name));
86645
+ const headerFieldsSql = headerFields.length === 0 ? "" : ` || jsonb_build_object(${headerFields.map((extra) => `${sqlString(extra.name)}, v_quote.${extra.ident}`).join(", ")})`;
86646
+ const discountLines = taxLines !== void 0 && quotes.has("taxLines", "discount") ? `
86647
+ select v_lines || coalesce(jsonb_agg(jsonb_build_object('description', 'Discount', 'quantity', 1, 'unitAmount', (-x.${taxLines("discount")})::text,
86648
+ 'taxRateBps', x.${taxLines("taxRateBps")}, 'taxCode', ${quotes.has("taxLines", "taxCode") ? `x.${taxLines("taxCode")}` : "null"}) order by x.${taxLines("taxRateBps")}), '[]'::jsonb)
86649
+ into v_lines
86650
+ from ${quotes.table("taxLines")} x where x.${taxLines("parent")} = v_quote.${q("id")} and x.${taxLines("discount")} <> 0;` : "";
86651
+ const quoteDiscounts = ["discountBps", "discountAmount"].filter((column) => quotes.has("quotes", column));
86652
+ const headerDiscount = quoteDiscounts.length > 0 && quoteDiscounts.every(has);
86653
+ const issuedDeposits = (alias) => `${originIs(alias)} and ${isDeposit(alias) === "" ? "false" : `(${isDeposit(alias)})`} and ${st(`${alias}.${i("status")}`, ["draft", "void"], true)}`;
86654
+ const discount = headerDiscount ? `
86655
+ if ${n.appTotals || !deposits ? "true" : `not exists (select 1 from ${t("invoices")} d where ${issuedDeposits("d")})`} then
86656
+ v_header := jsonb_build_object(${quoteDiscounts.map((column) => `${sqlString(column)}, v_quote.${q(column)}${column === "discountAmount" ? "::text" : ""}`).join(", ")});
86657
+ else${discountLines === "" ? "\n null;" : discountLines.replaceAll("\n", "\n ")}
86658
+ end if;` : discountLines;
86659
+ const party = (kind) => (kind === "company" ? company : contact) && quotes.has("quotes", `${kind}Type`) && quotes.has("quotes", `${kind}Id`) ? `case when v_quote.${q(`${kind}Id`)} is null then null else jsonb_build_object('type', v_quote.${q(`${kind}Type`)}, 'id', v_quote.${q(`${kind}Id`)}) end` : "null";
86660
+ const create = `${fn("create_invoice")}(v_quote.${q("tenant")}, jsonb_build_object(
86661
+ 'title', v_quote.${q("title")}, 'currency', v_quote.${q("currency")}, 'depositBps', ${has("depositBps") ? "invoice_from_quote.deposit_bps" : "null"},${has("depositAmount") ? " 'depositAmount', invoice_from_quote.deposit_amount::text," : ""}${has("pricesIncludeTax") ? ` 'pricesIncludeTax', ${inclusive},` : ""}
86662
+ 'company', ${party("company")},
86663
+ 'contact', ${party("contact")},
86664
+ 'origin', jsonb_build_object('type', 'quote', 'id', v_quote.${q("id")}::text))${headerDiscount ? " || v_header" : ""}${headerFieldsSql}, v_lines)`;
86665
+ const amountLine = amountDeposits ? `
86666
+ elsif invoice_from_quote.deposit_amount is not null then
86667
+ v_lines := jsonb_build_array(jsonb_build_object(
86668
+ 'description', 'Deposit of ' || v_quote.${q("identifier")},
86669
+ 'quantity', 1,
86670
+ 'unitAmount', (case when ${inclusive} or v_quote.${q("total")} = 0 then invoice_from_quote.deposit_amount
86671
+ else round(invoice_from_quote.deposit_amount::numeric * v_quote.${q("subtotal")} / v_quote.${q("total")})::bigint end)::text,
86672
+ 'taxRateBps', ${blendedRate}));` : "";
86673
+ const body = () => `
86674
+ if invoice_from_quote.deposit_bps is null${amountDeposits ? " and invoice_from_quote.deposit_amount is null" : ""} then
86675
+ select * into v_row from ${t("invoices")} x
86676
+ where ${originIs("x")}
86677
+ and ${notDeposit("x")}${st(`x.${i("status")}`, ["void"], true)} and ${kd(`x.${i("kind")}`, ["invoice"])}
86678
+ limit 1;
86679
+ if v_row.${i("id")} is not null then
86680
+ return ${row("v_row")};
86681
+ end if;
86682
+ select coalesce(jsonb_agg(jsonb_build_object('description', x.${ql("description")}, 'quantity', x.${ql("quantity")}${declared(quotes, "lines", "periods") ? ` * coalesce(x.${ql("periods")}, 1)` : ""}, 'unitAmount', x.${ql("unitAmount")}::text,
86683
+ 'discountBps', ${lineColumn(quotes, "lines", "x", "discountBps")}, 'taxRateBps', ${lineColumn(quotes, "lines", "x", "taxRateBps")}, 'taxCode', ${lineColumn(quotes, "lines", "x", "taxCode")},
86684
+ 'product', case when ${lineColumn(quotes, "lines", "x", "productType")} is null then null else jsonb_build_object('type', ${lineColumn(quotes, "lines", "x", "productType")}, 'id', ${lineColumn(quotes, "lines", "x", "productId")}) end${lineFieldsSql}
86685
+ ) order by x.${ql("position")}), '[]'::jsonb) into v_lines
86686
+ from ${quotes.table("lines")} x where x.${ql("parent")} = v_quote.${q("id")} and ${countedLine(quotes, "lines", "x")};${discount}${deposits ? `
86687
+ select v_lines || coalesce(jsonb_agg(jsonb_build_object('description', 'Deposit ' || d.${i("identifier")}, 'quantity', 1, 'unitAmount', (-(case when ${inclusive} then d.${i("total")} else d.${i("subtotal")} end))::text,
86688
+ 'taxRateBps', case when d.${i("subtotal")} = 0 then 0 else round(d.${i("taxTotal")} * 10000.0 / d.${i("subtotal")})::integer end)), '[]'::jsonb)
86689
+ into v_lines
86690
+ from ${t("invoices")} d
86691
+ where ${issuedDeposits("d")};` : ""}${amountLine}
86692
+ else
86693
+ v_lines := jsonb_build_array(jsonb_build_object(
86694
+ 'description', 'Deposit ' || (invoice_from_quote.deposit_bps / 100.0)::text || '% of ' || v_quote.${q("identifier")},
86695
+ 'quantity', 1,
86696
+ 'unitAmount', round(${base("v_quote")}::numeric * invoice_from_quote.deposit_bps / 10000)::bigint::text,
86697
+ 'taxRateBps', ${blendedRate}));
86698
+ end if;
86699
+ v_row := null;${kind === void 0 ? `
86700
+ return ${create};` : `
86701
+ v_made := ${create};
86702
+ if invoice_from_quote.deposit_bps is not null or invoice_from_quote.deposit_amount is not null then
86703
+ update ${t("invoices")} x set ${i("kind")} = ${ctx.cast("invoices", "kind", sqlString(kind))} where x.${i("id")} = (v_made ->> 'id')::uuid;
86704
+ return (select ${row("x")} from ${t("invoices")} x where x.${i("id")} = (v_made ->> 'id')::uuid);
86705
+ end if;
86706
+ return v_made;`}`;
86707
+ return `
86708
+ -- An invoice from an accepted quote. With deposit_bps (2000 for 20%) it is
86709
+ -- a deposit invoice for that share of the quote${amountDeposits ? ", and with deposit_amount\n-- one for that amount, tax included" : ""}; without, the full invoice,
86710
+ -- which subtracts the deposits already issued and is made once per quote.${headerDiscount ? "\n-- The quote's document discount stays on the invoice's header." : ""}
86711
+ drop function if exists ${fn("invoice_from_quote")}(uuid, integer);
86712
+ create or replace function ${fn("invoice_from_quote")}(quote uuid, deposit_bps integer, deposit_amount bigint default null)
86713
+ returns jsonb
86714
+ language plpgsql
86715
+ security definer
86716
+ set search_path = ''
86717
+ as $$
86718
+ declare
86719
+ v_quote ${quotes.table("quotes")};
86720
+ v_row ${t("invoices")};
86721
+ v_lines jsonb;${headerDiscount ? "\n v_header jsonb := '{}'::jsonb;" : ""}${kind === void 0 ? "" : "\n v_made jsonb;"}
86722
+ begin
86723
+ select * into v_quote from ${quotes.table("quotes")} x where x.${q("id")} = invoice_from_quote.quote;
86724
+ if v_quote.${q("id")} is null or not (${n.service} or ${ctx.scope.can(`v_quote.${q("tenant")}`, n.create)}) then
86725
+ ${fail$1("INVOICE_ORIGIN_NOT_FOUND", "no such quote you can invoice", "P0002")}
86726
+ end if;
86727
+ if ${quotes.is("quotes", "status", `v_quote.${q("status")}`, ["accepted"], true)} then
86728
+ ${fail$1("INVOICE_QUOTE_NOT_ACCEPTED", "only an accepted quote is invoiced", "55000")}
86729
+ end if;
86730
+ if invoice_from_quote.deposit_bps is not null and (invoice_from_quote.deposit_bps <= 0 or invoice_from_quote.deposit_bps >= 10000) then
86731
+ ${fail$1("INVOICE_DEPOSIT_INVALID", "a deposit is between 0 and 100 percent", "22023")}
86732
+ end if;
86733
+ if invoice_from_quote.deposit_bps is not null and invoice_from_quote.deposit_amount is not null then
86734
+ ${fail$1("INVOICE_DEPOSIT_INVALID", "a deposit is a share (deposit_bps) or an amount (deposit_amount), not both", "22023")}
86735
+ end if;
86736
+ if invoice_from_quote.deposit_amount is not null and (invoice_from_quote.deposit_amount <= 0 or invoice_from_quote.deposit_amount > v_quote.${q("total")}) then
86737
+ ${fail$1("INVOICE_DEPOSIT_INVALID", "a deposit amount is positive and at most the quote's total", "22023")}
86738
+ end if;${refuse(bpsDeposits, "invoice_from_quote.deposit_bps", "DEPOSIT", "deposit column")}${refuse(amountDeposits, "invoice_from_quote.deposit_amount", "DEPOSIT", "deposit amount column")}${origin === void 0 ? `
86739
+ ${fail$1("INVOICE_ORIGIN_UNSUPPORTED", "this invoices table has no origin columns, so a quote can't be invoiced once", "22023")}` : body()}
86740
+ end;
86741
+ $$;
86742
+ ${userGrant(`${fn("invoice_from_quote")}(uuid, integer, bigint)`)}
86743
+ `;
86744
+ }
86535
86745
  // src/sql/modules/invoices-functions.ts
86746
+ /**
86747
+ * Invoice columns a config opts into by naming them in
86748
+ * `blocks.invoices.columns.invoices`, so app tables made before them keep
86749
+ * working: a fixed deposit and a header discount.
86750
+ */
86751
+ const OPT_IN = [
86752
+ "depositAmount",
86753
+ "discountBps",
86754
+ "discountAmount"
86755
+ ];
86756
+ /** Whether the invoices table has the opt-in column `logical`. */
86757
+ function invoiceOptIn(ctx, logical) {
86758
+ return typeof ctx.config.columns["invoices"]?.[logical] === "string" && ctx.has("invoices", logical);
86759
+ }
86536
86760
  /** `options.chargeExtraColumns`: app columns of the charges table. */
86537
86761
  const chargeExtraColumns = (ctx) => ctx.hasTable("charges") ? ctx.extraColumns("charges", ["fields"], "chargeExtraColumns") : [];
86538
86762
  /**
@@ -86565,7 +86789,7 @@ function invoiceFunctions(ctx, n) {
86565
86789
  const company = invoiceParty(ctx, "company");
86566
86790
  const contact = invoiceParty(ctx, "contact");
86567
86791
  const origin = invoiceParty(ctx, "origin");
86568
- const has = (logical) => ctx.has("invoices", logical);
86792
+ const has = (logical) => OPT_IN.includes(logical) ? invoiceOptIn(ctx, logical) : ctx.has("invoices", logical);
86569
86793
  const charges = ctx.hasTable("charges");
86570
86794
  const ch = (column) => c("charges", column);
86571
86795
  const physical = (logical) => ctx.colName("invoices", logical);
@@ -86588,7 +86812,9 @@ function invoiceFunctions(ctx, n) {
86588
86812
  "number",
86589
86813
  "paidTotal",
86590
86814
  "creditedTotal",
86591
- ...Object.keys(TOTAL_COLUMNS)
86815
+ ...Object.keys(TOTAL_COLUMNS),
86816
+ "depositAmount",
86817
+ "discountAmount"
86592
86818
  ].filter(has);
86593
86819
  const int8 = amounts.map(i);
86594
86820
  const int8Text8 = Object.fromEntries(amounts.map((logical) => [logical, (value) => `${value}::text`]));
@@ -86656,10 +86882,21 @@ function invoiceFunctions(ctx, n) {
86656
86882
  returning * into ${alias};`;
86657
86883
  const keep = (logical, value, key) => has(logical) ? `,\n ${i(logical)} = case when update_invoice.attrs ? ${sqlString(key)} then ${value} else x.${i(logical)} end` : "";
86658
86884
  const relations = ctx.installed("relations") ? ctx.of("relations") : void 0;
86885
+ const discounts = has("discountBps") || has("discountAmount");
86886
+ const recountKeys = [
86887
+ "pricesIncludeTax",
86888
+ "discountBps",
86889
+ "discountAmount"
86890
+ ].filter(has);
86891
+ const headerRefusals = (attrs) => [
86892
+ refuse(has("depositAmount"), `${attrs} ->> 'depositAmount'`, "DEPOSIT", "deposit amount column"),
86893
+ refuse(has("discountBps"), `nullif(${attrs} ->> 'discountBps', '0')`, "DISCOUNT", "discount column"),
86894
+ refuse(has("discountAmount"), `nullif(${attrs} ->> 'discountAmount', '0')`, "DISCOUNT", "discount amount column")
86895
+ ].join("");
86659
86896
  const updateInvoiceSql = () => `
86660
86897
  -- Changes a draft's header. attrs: title, company and contact ({ type, id },
86661
86898
  -- null clears), termsDays, note, depositBps, pricesIncludeTax and the extra
86662
- -- columns by name. A key left out keeps its value.
86899
+ -- columns by name${discounts ? ", and the header discount (discountBps, discountAmount)" : ""}. A key left out keeps its value.
86663
86900
  create or replace function ${fn("update_invoice")}(invoice uuid, attrs jsonb)
86664
86901
  returns jsonb
86665
86902
  language plpgsql
@@ -86683,17 +86920,17 @@ begin
86683
86920
  if jsonb_typeof(update_invoice.attrs) is distinct from 'object'
86684
86921
  or (update_invoice.attrs ? 'title' and nullif(trim(update_invoice.attrs ->> 'title'), '') is null) then
86685
86922
  ${fail$1("INVOICE_ATTRS_INVALID", "attrs is an object, and a title isn't empty", "22023")}
86686
- end if;${checkParty("COMPANY", "v_company_type", "v_company_id", `v_row.${i("tenant")}`)}${checkParty("CONTACT", "v_contact_type", "v_contact_id", `v_row.${i("tenant")}`)}${refuse(has("note"), "update_invoice.attrs ->> 'note'", "NOTE", "note column")}${refuse(has("depositBps"), "update_invoice.attrs ->> 'depositBps'", "DEPOSIT", "deposit column")}${refuse(has("pricesIncludeTax"), "nullif(update_invoice.attrs ->> 'pricesIncludeTax', 'false')", "PRICING", "prices_include_tax column")}
86923
+ end if;${checkParty("COMPANY", "v_company_type", "v_company_id", `v_row.${i("tenant")}`)}${checkParty("CONTACT", "v_contact_type", "v_contact_id", `v_row.${i("tenant")}`)}${refuse(has("note"), "update_invoice.attrs ->> 'note'", "NOTE", "note column")}${refuse(has("depositBps"), "update_invoice.attrs ->> 'depositBps'", "DEPOSIT", "deposit column")}${refuse(has("pricesIncludeTax"), "nullif(update_invoice.attrs ->> 'pricesIncludeTax', 'false')", "PRICING", "prices_include_tax column")}${headerRefusals("update_invoice.attrs")}
86687
86924
  begin
86688
86925
  update ${t("invoices")} x set
86689
- ${i("title")} = case when update_invoice.attrs ? 'title' then trim(update_invoice.attrs ->> 'title') else x.${i("title")} end${keep("companyType", "case when v_company_id is null then null else v_company_type end", "company")}${company === void 0 ? "" : keep("companyId", partyId("company", "v_company_id"), "company")}${keep("contactType", "case when v_contact_id is null then null else v_contact_type end", "contact")}${contact === void 0 ? "" : keep("contactId", partyId("contact", "v_contact_id"), "contact")}${keep("termsDays", "(update_invoice.attrs ->> 'termsDays')::integer", "termsDays")}${keep("note", "update_invoice.attrs ->> 'note'", "note")}${keep("depositBps", "(update_invoice.attrs ->> 'depositBps')::integer", "depositBps")}${keep("pricesIncludeTax", "coalesce((update_invoice.attrs ->> 'pricesIncludeTax')::boolean, false)", "pricesIncludeTax")},
86926
+ ${i("title")} = case when update_invoice.attrs ? 'title' then trim(update_invoice.attrs ->> 'title') else x.${i("title")} end${keep("companyType", "case when v_company_id is null then null else v_company_type end", "company")}${company === void 0 ? "" : keep("companyId", partyId("company", "v_company_id"), "company")}${keep("contactType", "case when v_contact_id is null then null else v_contact_type end", "contact")}${contact === void 0 ? "" : keep("contactId", partyId("contact", "v_contact_id"), "contact")}${keep("termsDays", "(update_invoice.attrs ->> 'termsDays')::integer", "termsDays")}${keep("note", "update_invoice.attrs ->> 'note'", "note")}${keep("depositBps", "(update_invoice.attrs ->> 'depositBps')::integer", "depositBps")}${keep("pricesIncludeTax", "coalesce((update_invoice.attrs ->> 'pricesIncludeTax')::boolean, false)", "pricesIncludeTax")}${keep("depositAmount", "(update_invoice.attrs ->> 'depositAmount')::bigint", "depositAmount")}${keep("discountBps", "coalesce((update_invoice.attrs ->> 'discountBps')::integer, 0)", "discountBps")}${keep("discountAmount", "coalesce((update_invoice.attrs ->> 'discountAmount')::bigint, 0)", "discountAmount")},
86690
86927
  ${i("updatedAt")} = now()${updateExtraColumns(t("invoices"), n.extras, "update_invoice.attrs")}
86691
86928
  where x.${i("id")} = v_row.${i("id")}
86692
86929
  returning * into v_row;
86693
- exception when check_violation or invalid_text_representation or not_null_violation then
86930
+ exception when check_violation or invalid_text_representation or not_null_violation${discounts || has("depositAmount") ? " or numeric_value_out_of_range" : ""} then
86694
86931
  ${fail$1("INVOICE_ATTRS_INVALID", "an invoice field has an invalid value", "22023")}
86695
- end;${n.appTotals || !has("pricesIncludeTax") ? "" : `
86696
- if update_invoice.attrs ? 'pricesIncludeTax' then
86932
+ end;${n.appTotals || recountKeys.length === 0 ? "" : `
86933
+ if ${recountKeys.map((key) => `update_invoice.attrs ? ${sqlString(key)}`).join(" or ")} then
86697
86934
  perform ${fn("set_invoice_lines_recount")}(v_row.${i("id")});
86698
86935
  end if;`}
86699
86936
  ${record("invoice.updated", "v_row")}
@@ -86730,84 +86967,16 @@ end;
86730
86967
  $$;
86731
86968
  ${userGrant(`${fn("delete_invoice")}(uuid)`)}
86732
86969
  `;
86733
- const quotes = ctx.installed("quotes") ? ctx.of("quotes") : void 0;
86734
- const fromQuote = quotes === void 0 ? "" : (() => {
86735
- const q = (column) => quotes.col("quotes", column);
86736
- const ql = (column) => quotes.col("lines", column);
86737
- const deposits = has("depositBps");
86738
- const inclusive = has("pricesIncludeTax") && quotes.has("quotes", "pricesIncludeTax") ? `v_quote.${q("pricesIncludeTax")}` : "false";
86739
- const base = (alias) => `case when ${inclusive} then ${alias}.${q("total")} else ${alias}.${q("subtotal")} end`;
86740
- const taxLines = quotes.hasTable("taxLines") ? (column) => quotes.col("taxLines", column) : void 0;
86741
- const discountLines = taxLines !== void 0 && quotes.has("taxLines", "discount") ? `
86742
- select v_lines || coalesce(jsonb_agg(jsonb_build_object('description', 'Discount', 'quantity', 1, 'unitAmount', (-x.${taxLines("discount")})::text,
86743
- 'taxRateBps', x.${taxLines("taxRateBps")}, 'taxCode', ${quotes.has("taxLines", "taxCode") ? `x.${taxLines("taxCode")}` : "null"}) order by x.${taxLines("taxRateBps")}), '[]'::jsonb)
86744
- into v_lines
86745
- from ${quotes.table("taxLines")} x where x.${taxLines("parent")} = v_quote.${q("id")} and x.${taxLines("discount")} <> 0;` : "";
86746
- const party = (kind) => (kind === "company" ? company : contact) && quotes.has("quotes", `${kind}Type`) && quotes.has("quotes", `${kind}Id`) ? `case when v_quote.${q(`${kind}Id`)} is null then null else jsonb_build_object('type', v_quote.${q(`${kind}Type`)}, 'id', v_quote.${q(`${kind}Id`)}) end` : "null";
86747
- const originIs = (alias) => `${origin === "pair" ? `${alias}.${i("originType")} = 'quote' and ` : ""}${alias}.${i("originId")}::text = v_quote.${q("id")}::text`;
86748
- const body = () => `
86749
- if invoice_from_quote.deposit_bps is null then
86750
- select * into v_row from ${t("invoices")} x
86751
- where ${originIs("x")}
86752
- and ${deposits ? `x.${i("depositBps")} is null and ` : ""}${st(`x.${i("status")}`, ["void"], true)} and ${kd(`x.${i("kind")}`, ["invoice"])}
86753
- limit 1;
86754
- if v_row.${i("id")} is not null then
86755
- return ${row("v_row")};
86756
- end if;
86757
- select coalesce(jsonb_agg(jsonb_build_object('description', x.${ql("description")}, 'quantity', x.${ql("quantity")}${declared(quotes, "lines", "periods") ? ` * coalesce(x.${ql("periods")}, 1)` : ""}, 'unitAmount', x.${ql("unitAmount")}::text,
86758
- 'discountBps', ${lineColumn(quotes, "lines", "x", "discountBps")}, 'taxRateBps', ${lineColumn(quotes, "lines", "x", "taxRateBps")}, 'taxCode', ${lineColumn(quotes, "lines", "x", "taxCode")},
86759
- 'product', case when ${lineColumn(quotes, "lines", "x", "productType")} is null then null else jsonb_build_object('type', ${lineColumn(quotes, "lines", "x", "productType")}, 'id', ${lineColumn(quotes, "lines", "x", "productId")}) end
86760
- ) order by x.${ql("position")}), '[]'::jsonb) into v_lines
86761
- from ${quotes.table("lines")} x where x.${ql("parent")} = v_quote.${q("id")} and ${countedLine(quotes, "lines", "x")};${discountLines}${deposits ? `
86762
- select v_lines || coalesce(jsonb_agg(jsonb_build_object('description', 'Deposit ' || d.${i("identifier")}, 'quantity', 1, 'unitAmount', (-(case when ${inclusive} then d.${i("total")} else d.${i("subtotal")} end))::text,
86763
- 'taxRateBps', case when d.${i("subtotal")} = 0 then 0 else round(d.${i("taxTotal")} * 10000.0 / d.${i("subtotal")})::integer end)), '[]'::jsonb)
86764
- into v_lines
86765
- from ${t("invoices")} d
86766
- where ${originIs("d")} and d.${i("depositBps")} is not null and ${st(`d.${i("status")}`, ["draft", "void"], true)};` : ""}
86767
- else
86768
- v_lines := jsonb_build_array(jsonb_build_object(
86769
- 'description', 'Deposit ' || (invoice_from_quote.deposit_bps / 100.0)::text || '% of ' || v_quote.${q("identifier")},
86770
- 'quantity', 1,
86771
- 'unitAmount', round(${base("v_quote")}::numeric * invoice_from_quote.deposit_bps / 10000)::bigint::text,
86772
- 'taxRateBps', case when v_quote.${q("subtotal")} = 0 then 0 else round(v_quote.${q("taxTotal")} * 10000.0 / v_quote.${q("subtotal")})::integer end));
86773
- end if;
86774
- v_row := null;
86775
- return ${fn("create_invoice")}(v_quote.${q("tenant")}, jsonb_build_object(
86776
- 'title', v_quote.${q("title")}, 'currency', v_quote.${q("currency")}, 'depositBps', invoice_from_quote.deposit_bps,${has("pricesIncludeTax") ? ` 'pricesIncludeTax', ${inclusive},` : ""}
86777
- 'company', ${party("company")},
86778
- 'contact', ${party("contact")},
86779
- 'origin', jsonb_build_object('type', 'quote', 'id', v_quote.${q("id")}::text)), v_lines);`;
86780
- return `
86781
- -- An invoice from an accepted quote. With deposit_bps (2000 for 20%) it is
86782
- -- a deposit invoice for that share of the quote; without, the full invoice,
86783
- -- which subtracts the deposits already issued and is made once per quote.
86784
- create or replace function ${fn("invoice_from_quote")}(quote uuid, deposit_bps integer)
86785
- returns jsonb
86786
- language plpgsql
86787
- security definer
86788
- set search_path = ''
86789
- as $$
86790
- declare
86791
- v_quote ${quotes.table("quotes")};
86792
- v_row ${t("invoices")};
86793
- v_lines jsonb;
86794
- begin
86795
- select * into v_quote from ${quotes.table("quotes")} x where x.${q("id")} = invoice_from_quote.quote;
86796
- if v_quote.${q("id")} is null or not (${n.service} or ${ctx.scope.can(`v_quote.${q("tenant")}`, n.create)}) then
86797
- ${fail$1("INVOICE_ORIGIN_NOT_FOUND", "no such quote you can invoice", "P0002")}
86798
- end if;
86799
- if ${quotes.is("quotes", "status", `v_quote.${q("status")}`, ["accepted"], true)} then
86800
- ${fail$1("INVOICE_QUOTE_NOT_ACCEPTED", "only an accepted quote is invoiced", "55000")}
86801
- end if;
86802
- if invoice_from_quote.deposit_bps is not null and (invoice_from_quote.deposit_bps <= 0 or invoice_from_quote.deposit_bps >= 10000) then
86803
- ${fail$1("INVOICE_DEPOSIT_INVALID", "a deposit is between 0 and 100 percent", "22023")}
86804
- end if;${refuse(deposits, "invoice_from_quote.deposit_bps", "DEPOSIT", "deposit column")}${origin === void 0 ? `
86805
- ${fail$1("INVOICE_ORIGIN_UNSUPPORTED", "this invoices table has no origin columns, so a quote can't be invoiced once", "22023")}` : body()}
86806
- end;
86807
- $$;
86808
- ${userGrant(`${fn("invoice_from_quote")}(uuid, integer)`)}
86809
- `;
86810
- })();
86970
+ const fromQuote = invoiceFromQuote(ctx, n, {
86971
+ has,
86972
+ row,
86973
+ refuse,
86974
+ st,
86975
+ kd,
86976
+ origin,
86977
+ company: company !== void 0,
86978
+ contact: contact !== void 0
86979
+ });
86811
86980
  const chargeColumns = [
86812
86981
  ch("tenant"),
86813
86982
  ch("invoice"),
@@ -86909,7 +87078,7 @@ ${userGrant(`${fn("remove_invoice_charge")}(uuid, jsonb)`)}
86909
87078
  return `
86910
87079
  -- Creates a draft invoice. attrs: title (required), currency, company and
86911
87080
  -- contact ({ type, id }), termsDays, note, origin ({ type, id }) and the
86912
- -- extra columns by name.
87081
+ -- extra columns by name${discounts || has("depositAmount") ? ", with depositAmount and the header discount (discountBps,\n-- discountAmount) when the table has them" : ""}.
86913
87082
  create or replace function ${fn("create_invoice")}(tenant ${ctx.idType}, attrs jsonb, lines jsonb)
86914
87083
  returns jsonb
86915
87084
  language plpgsql
@@ -86931,21 +87100,24 @@ begin
86931
87100
  end if;${checkParty("COMPANY", "v_company_type", "v_company_id", "create_invoice.tenant")}${checkParty("CONTACT", "v_contact_type", "v_contact_id", "create_invoice.tenant")}${refuse(has("note"), "create_invoice.attrs ->> 'note'", "NOTE", "note column")}${refuse(origin !== void 0, "(create_invoice.attrs -> 'origin' ->> 'id')", "ORIGIN", "origin columns")}${origin === "fixed" ? `
86932
87101
  if create_invoice.attrs -> 'origin' ->> 'id' is not null and (create_invoice.attrs -> 'origin' ->> 'type') is distinct from 'quote' then
86933
87102
  ${fail$1("INVOICE_ORIGIN_UNSUPPORTED", "this invoices table takes only a quote as the origin", "22023")}
86934
- end if;` : ""}${refuse(has("depositBps"), "create_invoice.attrs ->> 'depositBps'", "DEPOSIT", "deposit column")}${refuse(has("pricesIncludeTax"), "nullif(create_invoice.attrs ->> 'pricesIncludeTax', 'false')", "PRICING", "prices_include_tax column")}
87103
+ end if;` : ""}${refuse(has("depositBps"), "create_invoice.attrs ->> 'depositBps'", "DEPOSIT", "deposit column")}${refuse(has("pricesIncludeTax"), "nullif(create_invoice.attrs ->> 'pricesIncludeTax', 'false')", "PRICING", "prices_include_tax column")}${headerRefusals("create_invoice.attrs")}
86935
87104
  begin
86936
87105
  insert into ${t("invoices")} (${i("tenant")}, ${i("title")}${also("companyType")}${also("companyId")}${also("contactType")}${also("contactId")}, ${i("currency")},
86937
- ${i("termsDays")}${also("note")}${also("originType")}${also("originId")}${also("depositBps")}${also("pricesIncludeTax")}${also("createdBy")}${insertExtraColumns(t("invoices"), n.extras, "create_invoice.attrs").columns})
87106
+ ${i("termsDays")}${also("note")}${also("originType")}${also("originId")}${also("depositBps")}${also("depositAmount")}${also("discountBps")}${also("discountAmount")}${also("pricesIncludeTax")}${also("createdBy")}${insertExtraColumns(t("invoices"), n.extras, "create_invoice.attrs").columns})
86938
87107
  values (${valueLines(" ", ["create_invoice.tenant", "trim(create_invoice.attrs ->> 'title')"], [present("companyType", "case when v_company_id is null then null else v_company_type end"), company === void 0 ? void 0 : partyId("company", "v_company_id")], [present("contactType", "case when v_contact_id is null then null else v_contact_type end"), contact === void 0 ? void 0 : partyId("contact", "v_contact_id")], ["upper(coalesce(create_invoice.attrs ->> 'currency', 'EUR'))", `case when create_invoice.attrs ? 'termsDays' then (create_invoice.attrs ->> 'termsDays')::integer else ${String(n.termsDays)} end`], [
86939
87108
  present("note", "create_invoice.attrs ->> 'note'"),
86940
87109
  present("originType", "create_invoice.attrs -> 'origin' ->> 'type'"),
86941
87110
  present("originId", partyId("origin", "create_invoice.attrs -> 'origin' ->> 'id'"))
86942
87111
  ], [
86943
87112
  present("depositBps", "(create_invoice.attrs ->> 'depositBps')::integer"),
87113
+ present("depositAmount", "(create_invoice.attrs ->> 'depositAmount')::bigint"),
87114
+ present("discountBps", "coalesce((create_invoice.attrs ->> 'discountBps')::integer, 0)"),
87115
+ present("discountAmount", "coalesce((create_invoice.attrs ->> 'discountAmount')::bigint, 0)"),
86944
87116
  present("pricesIncludeTax", "coalesce((create_invoice.attrs ->> 'pricesIncludeTax')::boolean, false)"),
86945
87117
  present("createdBy", "auth.uid()")
86946
87118
  ])}${insertExtraColumns(t("invoices"), n.extras, "create_invoice.attrs").values})
86947
87119
  returning * into v_row;
86948
- exception when check_violation or invalid_text_representation then
87120
+ exception when check_violation or invalid_text_representation${discounts || has("depositAmount") ? " or numeric_value_out_of_range" : ""} then
86949
87121
  ${fail$1("INVOICE_ATTRS_INVALID", "an invoice field has an invalid value", "22023")}
86950
87122
  end;
86951
87123
  if create_invoice.lines is not null then
@@ -86971,6 +87143,7 @@ ${updateInvoiceSql()}${lineItemsSql(ctx, {
86971
87143
  frozen: st(`p.${i("status")}`, ["draft"], true),
86972
87144
  extras: n.lineExtras,
86973
87145
  totals: !n.appTotals,
87146
+ parentHas: has,
86974
87147
  positionKey: ctx.flag("linePositionKey", true)
86975
87148
  }, {
86976
87149
  setter: "set_invoice_lines",
@@ -87465,12 +87638,13 @@ const NAMES$56 = {
87465
87638
  "providerPaymentMethods",
87466
87639
  "uniqueNumber",
87467
87640
  "linePositionKey",
87468
- "paymentsAfterWriteOff"
87641
+ "paymentsAfterWriteOff",
87642
+ "depositKind"
87469
87643
  ],
87470
87644
  tables: {
87471
87645
  invoices: {
87472
87646
  name: "invoices",
87473
- app: { unused: (ctx) => typeof ctx.config.columns["invoices"]?.["writeOffReason"] === "string" ? [] : ["writeOffReason"] },
87647
+ app: { unused: (ctx) => ["writeOffReason", ...OPT_IN].filter((column) => typeof ctx.config.columns["invoices"]?.[column] !== "string") },
87474
87648
  lifecycle: {
87475
87649
  tenant: "tenant",
87476
87650
  export: true
@@ -87502,6 +87676,9 @@ const NAMES$56 = {
87502
87676
  originType: "origin_type",
87503
87677
  originId: "origin_id",
87504
87678
  depositBps: "deposit_bps",
87679
+ depositAmount: "deposit_amount",
87680
+ discountBps: "discount_bps",
87681
+ discountAmount: "discount_amount",
87505
87682
  pricesIncludeTax: "prices_include_tax",
87506
87683
  createdBy: "created_by",
87507
87684
  createdAt: "created_at",
@@ -87519,6 +87696,9 @@ const NAMES$56 = {
87519
87696
  "originType",
87520
87697
  "originId",
87521
87698
  "depositBps",
87699
+ "depositAmount",
87700
+ "discountBps",
87701
+ "discountAmount",
87522
87702
  "pricesIncludeTax",
87523
87703
  "createdBy",
87524
87704
  "listTotal",
@@ -87591,6 +87771,12 @@ ${renderPolicy(policy$1({
87591
87771
  })}
87592
87772
  ` : "";
87593
87773
  const column = (logical, definition) => ctx.has("invoices", logical) ? `\n ${i(logical)} ${definition},` : "";
87774
+ const optIn = {
87775
+ depositAmount: (name) => `bigint check (${name} > 0)`,
87776
+ discountBps: (name) => `integer not null default 0 check (${name} >= 0 and ${name} <= 10000)`,
87777
+ discountAmount: (name) => `bigint not null default 0 check (${name} >= 0)`
87778
+ };
87779
+ const added = OPT_IN.filter((logical) => invoiceOptIn(ctx, logical)).map((logical) => `\nalter table ${t("invoices")} add column if not exists ${i(logical)} ${optIn[logical](i(logical))};`).join("");
87594
87780
  const index = (name, columns) => `\ncreate index if not exists ${ctx.naming.rename(name)} on ${t("invoices")} (${columns.map(i).join(", ")});`;
87595
87781
  return `
87596
87782
  create table if not exists ${t("invoices")} (
@@ -87617,7 +87803,7 @@ ${uniqueNumber === false ? "" : ` unique (${i("tenant")}, ${i("kind")}, ${i(uni
87617
87803
  check (${i("status")} <> 'draft' or ${i("number")} is null),
87618
87804
  check (${i("status")} in ('draft', 'void') or ${i("number")} is not null)${company === "pair" ? `,\n check ((${i("companyType")} is null) = (${i("companyId")} is null))` : ""}
87619
87805
  );
87620
- create index if not exists ${ctx.naming.rename("invoices_tenant_status_idx")} on ${t("invoices")} (${i("tenant")}, ${i("status")}, ${i("dueOn")});${origin === void 0 ? "" : index("invoices_origin_idx", origin === "pair" ? ["originType", "originId"] : ["originId"])}${index("invoices_original_idx", ["original"])}${company === void 0 ? "" : index("invoices_company_idx", company === "pair" ? ["companyType", "companyId"] : ["companyId"])}${addExtraColumns(t("invoices"), n.extras)}${uniqueNumber === false ? "" : appUniqueIndex(ctx, "invoices", [
87806
+ ${added === "" ? "" : `${added.slice(1)}\n`}create index if not exists ${ctx.naming.rename("invoices_tenant_status_idx")} on ${t("invoices")} (${i("tenant")}, ${i("status")}, ${i("dueOn")});${origin === void 0 ? "" : index("invoices_origin_idx", origin === "pair" ? ["originType", "originId"] : ["originId"])}${index("invoices_original_idx", ["original"])}${company === void 0 ? "" : index("invoices_company_idx", company === "pair" ? ["companyType", "companyId"] : ["companyId"])}${addExtraColumns(t("invoices"), n.extras)}${uniqueNumber === false ? "" : appUniqueIndex(ctx, "invoices", [
87621
87807
  "tenant",
87622
87808
  "kind",
87623
87809
  uniqueNumber
@@ -87655,6 +87841,17 @@ function invoiceTotals(ctx) {
87655
87841
  if (totals !== "block" && totals !== "app") throw new TypeError("blocks.invoices.options.totals must be \"block\" or \"app\"");
87656
87842
  return totals;
87657
87843
  }
87844
+ /**
87845
+ * `options.depositKind`: the app value of the kind column that marks a deposit
87846
+ * invoice. It must be one the `invoice` label maps to, so the block treats a
87847
+ * deposit invoice as an invoice everywhere else.
87848
+ */
87849
+ function depositKind(ctx) {
87850
+ const kind = ctx.option("depositKind");
87851
+ if (kind === void 0) return;
87852
+ if (typeof kind !== "string" || !ctx.appValues("invoices", "kind", "invoice").includes(kind)) throw new TypeError("blocks.invoices.options.depositKind must be one of the values blocks.invoices.values.invoices.kind.invoice maps to");
87853
+ return kind;
87854
+ }
87658
87855
  function build$55(ctx) {
87659
87856
  if (ctx.mode === "custom") return "";
87660
87857
  const keys = moduleOperations("invoices");
@@ -87695,7 +87892,8 @@ function build$55(ctx) {
87695
87892
  ]),
87696
87893
  lineExtras: lineExtraColumns(ctx),
87697
87894
  chargeExtras: chargeExtraColumns(ctx),
87698
- appTotals: invoiceTotals(ctx) === "app"
87895
+ appTotals: invoiceTotals(ctx) === "app",
87896
+ depositKind: depositKind(ctx)
87699
87897
  };
87700
87898
  return `${schemaPreamble(ctx)}
87701
87899
  -- Invoices an organization sends its own customers: drafts with lines, a
@@ -87820,7 +88018,11 @@ function contract$48(ctx) {
87820
88018
  },
87821
88019
  ...ctx.installed("quotes") ? [{
87822
88020
  name: "invoice_from_quote",
87823
- args: ["uuid", "integer"],
88021
+ args: [
88022
+ "uuid",
88023
+ "integer",
88024
+ "bigint"
88025
+ ],
87824
88026
  returns: "jsonb"
87825
88027
  }] : []
87826
88028
  ];
@@ -113921,7 +114123,10 @@ const NAMES$35 = {
113921
114123
  "lineExtraColumns",
113922
114124
  "lineRates",
113923
114125
  "workingCopy",
113924
- "versionLines"
114126
+ "versionLines",
114127
+ "versionLineExtraColumns",
114128
+ "totals",
114129
+ "resend"
113925
114130
  ],
113926
114131
  tables: {
113927
114132
  quotes: {
@@ -114163,7 +114368,7 @@ create table if not exists ${t("versionLines")} (
114163
114368
  ${vl("quantity")} numeric(18, 4) not null,
114164
114369
  ${vl("unitAmount")} bigint not null,${vlColumn("periods", "integer not null default 1")}${vlColumn("discountBps", "integer not null default 0")}${vlColumn("taxRateBps", "integer not null default 0")}${vlColumn("taxCode", "text")}${vlColumn("section", "text")}${vlColumn("optional", "boolean not null default false")}${vlColumn("selected", "boolean not null default true")}${vlColumn("productType", "text")}${vlColumn("productId", "text")}
114165
114370
  unique (${vl("version")}, ${vl("position")})
114166
- );
114371
+ );${addExtraColumns(t("versionLines"), n.versionLineExtras)}
114167
114372
  ${lockModuleTable(ctx, "versionLines", { read: true })}
114168
114373
  ${renderPolicy(policy$1({
114169
114374
  table: t("versionLines"),
@@ -114222,9 +114427,16 @@ create trigger ${frozen} before update on ${t("versions")}
114222
114427
  for each row execute function better_supabase.${frozen.replaceAll("\"", "")}();
114223
114428
  ${versionLines}${taxLines}`;
114224
114429
  }
114430
+ /** `options.totals`: who keeps a quote's totals. */
114431
+ function quoteTotals(ctx) {
114432
+ const totals = ctx.text("totals", "block");
114433
+ if (totals !== "block" && totals !== "app") throw new TypeError("blocks.quotes.options.totals must be \"block\" or \"app\"");
114434
+ return totals;
114435
+ }
114225
114436
  function build$34(ctx) {
114226
114437
  if (ctx.mode === "custom") return "";
114227
114438
  const keys = moduleOperations("quotes");
114439
+ const finer = (action) => sqlString(ctx.config.permissions[action] ?? ctx.permissionKey("write", keys.write));
114228
114440
  const validDays = ctx.number("validDays", 30);
114229
114441
  if (!Number.isInteger(validDays) || validDays < 1) throw new TypeError("blocks.quotes.options.validDays must be a positive integer");
114230
114442
  const n = {
@@ -114234,6 +114446,9 @@ function build$34(ctx) {
114234
114446
  read: ctx.permission("read", keys.read),
114235
114447
  write: ctx.permission("write", keys.write),
114236
114448
  manage: ctx.permission("manage", keys.manage),
114449
+ send: finer("send"),
114450
+ decide: finer("decide"),
114451
+ withdraw: finer("withdraw"),
114237
114452
  company: ctx.text("company", "company"),
114238
114453
  contact: ctx.text("contact", "person"),
114239
114454
  prefix: ctx.text("prefix", "Q-"),
@@ -114244,7 +114459,10 @@ function build$34(ctx) {
114244
114459
  "token",
114245
114460
  "fields"
114246
114461
  ]),
114247
- lineExtras: lineExtraColumns(ctx)
114462
+ lineExtras: lineExtraColumns(ctx),
114463
+ versionLineExtras: versionLinesOn(ctx) ? ctx.extraColumns("versionLines", [], "versionLineExtraColumns") : [],
114464
+ appTotals: quoteTotals(ctx) === "app",
114465
+ resend: ctx.flag("resend", false)
114248
114466
  };
114249
114467
  return `${schemaPreamble(ctx)}
114250
114468
  -- Quotes: line items, sections, optional lines, discounts and tax per rate,
@@ -114312,7 +114530,7 @@ function contract$32(ctx) {
114312
114530
  },
114313
114531
  {
114314
114532
  name: "portal_quote",
114315
- args: ["uuid"],
114533
+ args: ["uuid", "jsonb"],
114316
114534
  returns: "jsonb"
114317
114535
  },
114318
114536
  {