better-supabase 0.38.0 → 0.40.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 (156) hide show
  1. package/dist/ai-sdk/agents/index.d.ts +2 -2
  2. package/dist/{app-tables-D2c0i05-.d.ts → app-tables-jaQmdgAM.d.ts} +1 -1
  3. package/dist/{authorization-D8CaAdqU.d.ts → authorization-Ul_ApMYW.d.ts} +41 -2
  4. package/dist/{bind-5vOwNouG.d.ts → bind-B2GlypM6.d.ts} +1 -1
  5. package/dist/{block-env-hco8BLjC.d.ts → block-env-Bcr-jEA1.d.ts} +3 -3
  6. package/dist/{block-subjects-CINiJW1R.js → block-subjects-BumEsEYb.js} +17 -6
  7. package/dist/{block-tables-BsgdB6VG.d.ts → block-tables-nkIjJ1ly.d.ts} +1 -1
  8. package/dist/blocks/ai-chat/index.d.ts +3 -3
  9. package/dist/blocks/announcements/index.d.ts +3 -3
  10. package/dist/blocks/api-keys/index.d.ts +1 -1
  11. package/dist/blocks/attachments/index.d.ts +1 -1
  12. package/dist/blocks/audit/index.d.ts +2 -2
  13. package/dist/blocks/automations/index.d.ts +1 -1
  14. package/dist/blocks/billing/index.d.ts +1 -1
  15. package/dist/blocks/bookings/index.d.ts +1 -1
  16. package/dist/blocks/calendar/index.d.ts +1 -1
  17. package/dist/blocks/catalog/index.d.ts +25 -5
  18. package/dist/blocks/catalog/index.js +32 -9
  19. package/dist/blocks/comments/index.d.ts +4 -4
  20. package/dist/blocks/entitlements/index.d.ts +2 -2
  21. package/dist/blocks/expenses/index.js +1 -1
  22. package/dist/blocks/forms/index.d.ts +1 -1
  23. package/dist/blocks/inbox/index.d.ts +4 -4
  24. package/dist/blocks/index.d.ts +1 -1
  25. package/dist/blocks/invoices/index.d.ts +1 -0
  26. package/dist/blocks/invoices/index.js +18 -10
  27. package/dist/blocks/leave/index.d.ts +35 -1
  28. package/dist/blocks/leave/index.js +17 -2
  29. package/dist/blocks/ledger/index.d.ts +1 -0
  30. package/dist/blocks/ledger/index.js +2 -1
  31. package/dist/blocks/messaging/index.d.ts +4 -4
  32. package/dist/blocks/mfa/index.d.ts +1 -1
  33. package/dist/blocks/notifications/index.d.ts +3 -3
  34. package/dist/blocks/onboarding/index.d.ts +1 -1
  35. package/dist/blocks/organizations/index.d.ts +2 -2
  36. package/dist/blocks/permissions/index.d.ts +1 -1
  37. package/dist/blocks/push/index.d.ts +1 -1
  38. package/dist/blocks/reactions/index.d.ts +3 -3
  39. package/dist/blocks/saved-views/index.d.ts +1 -1
  40. package/dist/blocks/search/index.d.ts +2 -2
  41. package/dist/blocks/sessions/index.d.ts +1 -1
  42. package/dist/blocks/settings/index.d.ts +1 -1
  43. package/dist/blocks/subjects/index.d.ts +1 -1
  44. package/dist/blocks/tags/index.d.ts +1 -1
  45. package/dist/blocks/undo/index.d.ts +1 -1
  46. package/dist/blocks/usage/index.d.ts +1 -1
  47. package/dist/blocks/workflow-editor/index.d.ts +3 -3
  48. package/dist/blocks/workflows/index.d.ts +3 -3
  49. package/dist/claims/index.d.ts +3 -3
  50. package/dist/cli/{add-7nCSDmpt.js → add-BVs8Ym-K.js} +10 -10
  51. package/dist/cli/{add-B4tQpnXP.js → add-DP1ct-7e.js} +2 -2
  52. package/dist/cli/add-DrwQvDYD.js +1 -0
  53. package/dist/cli/{app-table-files-CtO-zxpO.js → app-table-files-gjMyFqH4.js} +2 -2
  54. package/dist/cli/{app-tables-B7UzcJ_g.js → app-tables-B26PHK75.js} +2 -2
  55. package/dist/cli/{backfill-B2nFDXaS.js → backfill-CP_LpTK2.js} +1 -1
  56. package/dist/cli/bin.js +1 -1
  57. package/dist/cli/{blocks-DU4iDrYS.js → blocks-CpBLp57s.js} +1 -1
  58. package/dist/cli/{blocks-BX_6HUQT.js → blocks-Ewp49Kbm.js} +1 -1
  59. package/dist/cli/{cache-bS5bAoF-.js → cache-BxxtUXVN.js} +1 -1
  60. package/dist/cli/{codemod-B1sSIE2p.js → codemod-CGCxMEyD.js} +1 -1
  61. package/dist/cli/{content-mapper-CW6V6VRq.js → content-mapper-DngBJv4r.js} +2 -2
  62. package/dist/cli/{doctor-Dw2pAf1b.js → doctor-3dcMraMn.js} +17 -17
  63. package/dist/cli/{gen-BtoSx3go.js → gen-DrXxFwUU.js} +11 -11
  64. package/dist/cli/index.d.ts +1 -1
  65. package/dist/cli/index.js +6 -6
  66. package/dist/cli/{init-DZXbrKuJ.js → init-bVKQ4Onb.js} +8 -8
  67. package/dist/cli/{live-CDFfJcdR.js → live-CHTbAqdS.js} +2 -2
  68. package/dist/cli/{mcp-BukxvITV.js → mcp-BbmhntrR.js} +2 -2
  69. package/dist/cli/{metadata-iZizGVuY.js → metadata-BS56R_eb.js} +3 -3
  70. package/dist/cli/{migrate-DPnnGLzw.js → migrate-DV6a9-jI.js} +1 -1
  71. package/dist/cli/{migration-safety-COcnZbMO.js → migration-safety-Ce9IQwmJ.js} +1 -1
  72. package/dist/cli/{migrations-BBt9fmiV.js → migrations-CCCnMhmM.js} +2 -2
  73. package/dist/cli/{module-migration-tCmPLhQp.js → module-migration-C0cAzpNa.js} +2 -2
  74. package/dist/cli/powersync-Cxd3a_v_.js +1 -0
  75. package/dist/cli/{powersync-BRmUJ-uR.js → powersync-OIIpG-y_.js} +3 -3
  76. package/dist/cli/{print-DdwQNG_e.js → print-BGF3d6O2.js} +2 -2
  77. package/dist/cli/{providers-CaNg6Ayz.js → providers-fEzlYSLs.js} +1 -1
  78. package/dist/cli/{prune-workflows-BQQrI3tU.js → prune-workflows-Bx7J5T3a.js} +1 -1
  79. package/dist/cli/{remove-BEj9YEON.js → remove-Ds4N6WvD.js} +5 -5
  80. package/dist/cli/{render-UBqU9r44.js → render-BeZToAp-.js} +3 -3
  81. package/dist/cli/{run-3E_IuJzS.js → run-DR0sTyNQ.js} +9 -9
  82. package/dist/cli/{run-BXlX9YdD.js → run-iUmtksq5.js} +27 -27
  83. package/dist/cli/{shared-agrqD28l.js → shared-BCWYvKeR.js} +1 -1
  84. package/dist/cli/{snapshot-DOXmozSq.js → snapshot-CfgRxTQq.js} +2 -2
  85. package/dist/cli/{source-BfJprU-6.js → source-Ct3ZCy6p.js} +1 -1
  86. package/dist/cli/{spec-CgtIHFsl.js → spec-1eEq2P4T.js} +1 -1
  87. package/dist/cli/{spec-DRpSQGOW.js → spec-9vb-or-k.js} +2 -2
  88. package/dist/cli/{sql-layout-Cs3FMWcY.js → sql-layout-cYsnyjRf.js} +2 -2
  89. package/dist/cli/{sync-C_YGIDjk.js → sync-XpcpINnx.js} +4 -4
  90. package/dist/cli/{upgrade-OG9vaBeX.js → upgrade-A18FY5Iy.js} +2 -2
  91. package/dist/cli/{upgrade-ByQeJRGU.js → upgrade-DXhyb2jV.js} +5 -5
  92. package/dist/cli/{version-CF6Yzah0.js → version-PcwPOm4G.js} +1 -1
  93. package/dist/client/index.d.ts +5 -5
  94. package/dist/client/native/index.d.ts +4 -4
  95. package/dist/config/index.d.ts +2 -2
  96. package/dist/config/index.js +4 -4
  97. package/dist/{config-1-UmQczM.js → config-BRGMUEE2.js} +1 -1
  98. package/dist/{config-AEB5iNEO.js → config-qqAfS_1_.js} +4 -4
  99. package/dist/{context-CH5FYnVk.d.ts → context-dHluCmud.d.ts} +1 -1
  100. package/dist/contract/index.d.ts +3 -3
  101. package/dist/{controller-CJ6rLnpS.d.ts → controller-BQXgMwWN.d.ts} +1 -1
  102. package/dist/create/index.d.ts +3 -3
  103. package/dist/create/index.js +3 -3
  104. package/dist/create/lite/index.d.ts +3 -3
  105. package/dist/create/lite/index.js +2 -2
  106. package/dist/{entitlements-6gODwBSz.d.ts → entitlements-Jh_w-PgX.d.ts} +1 -1
  107. package/dist/{field-errors-CdSjV9Zo.d.ts → field-errors-DIDkgzFA.d.ts} +4 -4
  108. package/dist/{index-DnEJVKQ2.d.ts → index-BKz-E3Mv.d.ts} +6 -6
  109. package/dist/{index-DzLLMmUB.d.ts → index-CpZ4WDDJ.d.ts} +1 -1
  110. package/dist/{index-vkd2LTt2.d.ts → index-DhcLJAtX.d.ts} +1 -1
  111. package/dist/{index-BgRl484n.d.ts → index-IrJQqPeQ.d.ts} +1 -1
  112. package/dist/{index-CrOeAgSh.d.ts → index-g_eFnFqo.d.ts} +2 -2
  113. package/dist/{index-CgKieWlO.d.ts → index-xmb6YGTg.d.ts} +2 -2
  114. package/dist/{index-B5awu2SP.d.ts → index-y70eTezB.d.ts} +2 -2
  115. package/dist/{instances-Bycf_aus.js → instances-DqEZrffE.js} +5 -1
  116. package/dist/mapper/bin.js +5 -5
  117. package/dist/mcp/index.d.ts +1 -1
  118. package/dist/next/index.d.ts +4 -4
  119. package/dist/{operations-knMnfzgm.d.ts → operations-Sza7UQKP.d.ts} +1 -1
  120. package/dist/{options-X61tvckX.js → options-C5cLEJEa.js} +4 -1
  121. package/dist/{options-CS1DA8q9.js → options-CYZH9uxU.js} +2 -1
  122. package/dist/{options-CEwoGUk_.js → options-DiEoDCtf.js} +4 -1
  123. package/dist/otel/index.js +4 -4
  124. package/dist/{permissions-Ed8WvLgQ.d.ts → permissions-COamTJYz.d.ts} +1 -1
  125. package/dist/{ports-Bnwy2mlR.d.ts → ports-1M1E_r2n.d.ts} +1 -1
  126. package/dist/powersync/index.d.ts +2 -2
  127. package/dist/preset/index.d.ts +3 -3
  128. package/dist/preset/index.js +3 -3
  129. package/dist/{preset-DkeXFh7e.js → preset-Byz43PrL.js} +2 -2
  130. package/dist/{project-By0R8ioI.js → project-Y2wW_nr_.js} +5 -5
  131. package/dist/{push-token-CJbEvwjI.d.ts → push-token-DKImhAca.d.ts} +1 -1
  132. package/dist/react/index.d.ts +5 -5
  133. package/dist/react/native/index.d.ts +1 -1
  134. package/dist/react/server.d.ts +5 -5
  135. package/dist/realtime/index.d.ts +3 -3
  136. package/dist/records/index.d.ts +3 -3
  137. package/dist/server/index.d.ts +3 -3
  138. package/dist/solid/index.d.ts +5 -5
  139. package/dist/sql/index.d.ts +5 -5
  140. package/dist/sql/index.js +2 -2
  141. package/dist/{sql-B2cMvGnZ.js → sql-B1FA8jTx.js} +265 -84
  142. package/dist/ssr/index.d.ts +1 -1
  143. package/dist/svelte/index.d.ts +5 -5
  144. package/dist/{tenant-eZNRWTRJ.d.ts → tenant-DflHpV32.d.ts} +1 -1
  145. package/dist/testing/index.d.ts +3 -3
  146. package/dist/testing/index.js +1 -1
  147. package/dist/{topic-D7F2FBNp.d.ts → topic-CekU96q7.d.ts} +1 -1
  148. package/dist/{types-bqvFoBhf.d.ts → types-B42S7qfO.d.ts} +2 -2
  149. package/dist/vue/index.d.ts +5 -5
  150. package/dist/{watch-topic-BIEaSN0Y.d.ts → watch-topic-DBw411Mq.d.ts} +1 -1
  151. package/dist/yjs/index.d.ts +1 -1
  152. package/package.json +1 -1
  153. package/schemas/config-v1.json +13 -0
  154. package/skills/better-supabase/SKILL.md +26 -8
  155. package/dist/cli/add-CdDneXMN.js +0 -1
  156. package/dist/cli/powersync-CYLPcJ9G.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 CONFIG_DEFAULTS, i as installedBlockSubjects, o as resolveNames, s as resolveJsonSchema } from "./block-subjects-CINiJW1R.js";
6
+ import { c as resolveJsonSchema, i as installedBlockSubjects, l as CONFIG_DEFAULTS, o as blockColumnName, s as resolveNames } from "./block-subjects-BumEsEYb.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-Bycf_aus.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-DqEZrffE.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";
@@ -33,7 +33,7 @@ import { t as billingSqlOptions } from "./options-BzxR82Tu.js";
33
33
  import { t as bookingsSqlOptions } from "./options-DPQaafyc.js";
34
34
  import { t as bulkSqlOptions } from "./options-PheFo4JY.js";
35
35
  import { t as calendarSqlOptions } from "./options-BjEsSoFp.js";
36
- import { t as catalogSqlOptions } from "./options-CEwoGUk_.js";
36
+ import { t as catalogSqlOptions } from "./options-DiEoDCtf.js";
37
37
  import { t as collectionsSqlOptions } from "./options-DFSHZFLN.js";
38
38
  import { t as commentsSqlOptions } from "./options-C1kZ3qLd.js";
39
39
  import { t as complianceSqlOptions } from "./options-BDF60ouf.js";
@@ -53,7 +53,7 @@ import { t as donationsSqlOptions } from "./options-ompJjxkV.js";
53
53
  import { t as driveSqlOptions } from "./options-CjocPkX1.js";
54
54
  import { t as employeesSqlOptions } from "./options-XiD_Y3oK.js";
55
55
  import { t as enrollmentsSqlOptions } from "./options-eIEk0vqV.js";
56
- import { t as expensesSqlOptions } from "./options-CS1DA8q9.js";
56
+ import { t as expensesSqlOptions } from "./options-CYZH9uxU.js";
57
57
  import { t as flagsSqlOptions } from "./options-BMO-FnOT.js";
58
58
  import { t as formsSqlOptions } from "./options-DpwRG4tO.js";
59
59
  import { t as goalsSqlOptions } from "./options-BNRvoEkj.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-X61tvckX.js";
65
+ import { t as invoicesSqlOptions } from "./options-C5cLEJEa.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";
@@ -136,7 +136,7 @@ import { a as TRACKING_STATUSES, i as SHIPMENT_STATUSES, n as LINE_DIRECTIONS, r
136
136
  import { t as compileSql } from "./sql-C1K5JALb.js";
137
137
  // src/sql/policy.ts
138
138
  /** `name` as the policy is called: modules may pass it already quoted. */
139
- const bareName = (name) => name.length > 1 && name.startsWith("\"") && name.endsWith("\"") ? name.slice(1, -1).replaceAll("\"\"", "\"") : name;
139
+ const bareName$1 = (name) => name.length > 1 && name.startsWith("\"") && name.endsWith("\"") ? name.slice(1, -1).replaceAll("\"\"", "\"") : name;
140
140
  /**
141
141
  * A policy with the defaults Postgres uses: `for all to public`, permissive. A
142
142
  * `name` in double quotes is unquoted, so `sqlIdent(name)` works as a name.
@@ -144,7 +144,7 @@ const bareName = (name) => name.length > 1 && name.startsWith("\"") && name.ends
144
144
  function policy$1(input) {
145
145
  return {
146
146
  table: qualifiedName$1(input.table),
147
- name: bareName(input.name),
147
+ name: bareName$1(input.name),
148
148
  command: input.command ?? "all",
149
149
  roles: input.roles ?? ["public"],
150
150
  permissive: input.permissive ?? true,
@@ -1609,7 +1609,7 @@ function overAppViews(sql, views) {
1609
1609
  return `${lead}-- ${view} is the app's view: this block writes only the functions that read it.`;
1610
1610
  }).join("");
1611
1611
  }
1612
- const COLUMN_NAME$1 = /^("(?:[^"]|"")+"|[a-z_][\w$]*)/i;
1612
+ const COLUMN_NAME$2 = /^("(?:[^"]|"")+"|[a-z_][\w$]*)/i;
1613
1613
  const TABLE_CONSTRAINT$1 = /^(constraint|check|unique|primary|foreign|exclude|like)\b/i;
1614
1614
  function unquote$4(name) {
1615
1615
  return name.startsWith("\"") ? name.slice(1, -1).replaceAll("\"\"", "\"") : name;
@@ -1643,7 +1643,7 @@ function overAppTables(sql, appTables, appColumns = {}) {
1643
1643
  const has = new Set(appColumns[table]);
1644
1644
  const name = match[1].trim();
1645
1645
  const columns = splitTopLevel(masked.slice(open + 1, close)).map((part) => part.trim()).filter((part) => part !== "" && !TABLE_CONSTRAINT$1.test(part)).filter((part) => !part.startsWith(`"${UNMAPPED_COLUMN}`)).filter((part) => {
1646
- const column = COLUMN_NAME$1.exec(part)?.[0];
1646
+ const column = COLUMN_NAME$2.exec(part)?.[0];
1647
1647
  return column !== void 0 && !has.has(unquote$4(column));
1648
1648
  });
1649
1649
  const added = columns.length === 0 ? `-- ${table} is the app's table, and it has every column this block needs.` : [`-- ${table} is the app's table: this block adds only the columns it needs.`, ...columns.map((column) => `alter table ${name} add column if not exists ${addable(column)};`)].join("\n");
@@ -1902,7 +1902,7 @@ const CLIENT_FUNCTIONS = {
1902
1902
  incidents: "delete_status_component get_incident get_status_page list_incidents list_status_components open_incident post_incident_update public_status_page publish_postmortem save_postmortem save_status_component save_status_page set_incident_impacts update_incident",
1903
1903
  inventory: "adjust_stock allocate_stock cancel_purchase_order cancel_transfer commit_reservation count_stock create_transfer delete_location expire_lots expire_reservations expiring_lots fulfill_allocation list_allocations place_purchase_order receive_purchase_order receive_transfer release_allocations release_reservation reserve_stock restore_allocation save_bin save_location save_lot save_purchase_order set_location_active set_reorder_point set_stock_item ship_transfer stock_detail stock_valuation",
1904
1904
  invitations: "accept_invitation accept_invitation_by_id decline_invitation decline_invitation_by_id invitation_preview invite_member my_invitations resend_invitation revoke_invitation update_invitation",
1905
- invoices: "add_invoice_charge create_invoice credit_invoice delete_invoice invoice_aging issue_invoice record_invoice_payment remove_invoice_charge reverse_invoice_payment set_invoice_lines update_invoice void_invoice write_off_invoice",
1905
+ invoices: "add_invoice_charge create_invoice credit_invoice delete_invoice invoice_aging issue_invoice list_invoice_payments record_invoice_payment remove_invoice_charge reverse_invoice_payment set_invoice_lines update_invoice void_invoice write_off_invoice",
1906
1906
  knowledge: "create_knowledge_collection create_knowledge_document delete_knowledge_collection delete_knowledge_document fail_knowledge_document get_knowledge_document knowledge_search list_knowledge_collection_grants list_knowledge_collections list_knowledge_documents pending_knowledge_chunks pending_knowledge_documents reembed_knowledge set_knowledge_collection_grant set_knowledge_embeddings update_knowledge_collection write_knowledge_chunks",
1907
1907
  "lead-scoring": "lead_fields score_lead score_leads_due",
1908
1908
  leases: "activate_lease create_lease get_lease list_lease_charges list_leases post_due_rent record_rent_payment renew_lease terminate_lease",
@@ -2412,14 +2412,6 @@ function moduleScope(source) {
2412
2412
  default: throw new TypeError(`Unknown scope "${String(kind)}"`);
2413
2413
  }
2414
2414
  }
2415
- // src/sql/tenant-column.ts
2416
- const DEFAULT_TENANT_COLUMN = "tenant_id";
2417
- function blockColumnName(where, columns, name, tenantColumn, rename) {
2418
- if (name !== DEFAULT_TENANT_COLUMN || tenantColumn === void 0) return rename(name);
2419
- const clash = Object.entries(columns).find(([, other]) => rename(other) === tenantColumn);
2420
- if (clash !== void 0) throw new TypeError(`sql.tenantColumn: "${tenantColumn}" is the name of ${where.table}.${clash[0]} in the ${where.module} module. Choose another name, or map blocks.${where.module}.columns.${where.table}.tenant.`);
2421
- return tenantColumn;
2422
- }
2423
2415
  // src/sql/value-maps.ts
2424
2416
  const VALUE = /^[^\0]{1,200}$/u;
2425
2417
  /**
@@ -3415,7 +3407,9 @@ const OPTIONAL_MODULE_PERMISSIONS = {
3415
3407
  update: "tenant",
3416
3408
  delete: "tenant",
3417
3409
  reimburse: "tenant",
3418
- categories: "tenant"
3410
+ categories: "tenant",
3411
+ withdraw: "tenant",
3412
+ deleteSubmitted: "tenant"
3419
3413
  }
3420
3414
  };
3421
3415
  // src/sql/block-renames.ts
@@ -8028,7 +8022,7 @@ function onSettings(ctx) {
8028
8022
  return on;
8029
8023
  }
8030
8024
  const qualifiedTable$2 = (table) => quotedTable$1(table);
8031
- const COLUMN_NAME = /^[a-z_][a-z0-9_]*$/;
8025
+ const COLUMN_NAME$1 = /^[a-z_][a-z0-9_]*$/;
8032
8026
  /**
8033
8027
  * `on.<type>.<key>` as `{ table, <column>... }`. Undefined when the subject
8034
8028
  * doesn't set it (the module's polymorphic table is used). `columns` are
@@ -8046,7 +8040,7 @@ function subjectTableBinding(ctx, type, subject, key, spec) {
8046
8040
  } catch {
8047
8041
  throw new TypeError(`${where}.table must be "table" or "schema.table"`);
8048
8042
  }
8049
- if (!COLUMN_NAME.test(schema) || !COLUMN_NAME.test(table)) throw new TypeError(`${where}.table must be "table" or "schema.table"`);
8043
+ if (!COLUMN_NAME$1.test(schema) || !COLUMN_NAME$1.test(table)) throw new TypeError(`${where}.table must be "table" or "schema.table"`);
8050
8044
  const columns = {};
8051
8045
  const optional = new Set(spec.optional);
8052
8046
  const known = /* @__PURE__ */ new Set([
@@ -8057,13 +8051,13 @@ function subjectTableBinding(ctx, type, subject, key, spec) {
8057
8051
  for (const name of Object.keys(raw)) if (!known.has(name)) throw new TypeError(`${where}.${name} is not a column. Columns: ${[...spec.columns, ...optional].join(", ")}`);
8058
8052
  for (const name of spec.columns) {
8059
8053
  const value = raw[name];
8060
- if (typeof value !== "string" || !COLUMN_NAME.test(value)) throw new TypeError(`${where}.${name} must be a column name`);
8054
+ if (typeof value !== "string" || !COLUMN_NAME$1.test(value)) throw new TypeError(`${where}.${name} must be a column name`);
8061
8055
  columns[name] = value;
8062
8056
  }
8063
8057
  for (const name of optional) {
8064
8058
  const value = raw[name];
8065
8059
  if (value === void 0) continue;
8066
- if (typeof value !== "string" || !COLUMN_NAME.test(value)) throw new TypeError(`${where}.${name} must be a column name`);
8060
+ if (typeof value !== "string" || !COLUMN_NAME$1.test(value)) throw new TypeError(`${where}.${name} must be a column name`);
8067
8061
  columns[name] = value;
8068
8062
  }
8069
8063
  return {
@@ -32601,25 +32595,37 @@ const LEAVE_FEED_SUBJECT = "leave_feed";
32601
32595
  /** The share-links subject of one team's leave feed; its id is the team's. */
32602
32596
  const LEAVE_TEAM_FEED_SUBJECT = "leave_team_feed";
32603
32597
  const FEED_WHERE = "blocks.leave.options.feed";
32598
+ const COLUMN_NAME = /^[a-z_][a-z0-9_]*$/u;
32604
32599
  function leaveFeedExtras(ctx) {
32605
32600
  const raw = ctx.option("feed") ?? {};
32606
- const { names = false, hideTypes = [], typeKey, teams = false, fields = false } = isRecord$1(raw) ? raw : {};
32607
- if (typeKey !== void 0 && (typeof typeKey !== "string" || !/^[a-z_][a-z0-9_]*$/u.test(typeKey))) throw new TypeError(`${FEED_WHERE}.typeKey is a column name of the leave types table`);
32601
+ const { names = false, hideTypes = [], typeKey, teams = false, fields = false, teamColumn, teamName = false, organizationName, confidential = "hide" } = isRecord$1(raw) ? raw : {};
32602
+ if (typeKey !== void 0 && (typeof typeKey !== "string" || !COLUMN_NAME.test(typeKey))) throw new TypeError(`${FEED_WHERE}.typeKey is a column name of the leave types table`);
32608
32603
  for (const [key, value] of Object.entries({
32609
32604
  names,
32610
32605
  teams,
32611
- fields
32606
+ fields,
32607
+ teamName
32612
32608
  })) if (typeof value !== "boolean") throw new TypeError(`${FEED_WHERE}.${key} is a boolean`);
32613
32609
  if (!Array.isArray(hideTypes) || !hideTypes.every((key) => typeof key === "string")) throw new TypeError(`${FEED_WHERE}.hideTypes is a list of type keys`);
32614
32610
  if (names === true && !ctx.installed("employees")) throw new TypeError(`${FEED_WHERE}.names needs the employees block`);
32615
32611
  if (names === true && !splitName(ctx.of("employees")) && !ctx.of("employees").has("employees", "name")) throw new TypeError(`${FEED_WHERE}.names needs columns.employees.name or the employees block's split name`);
32616
32612
  if (teams === true && !ctx.installed("teams")) throw new TypeError(`${FEED_WHERE}.teams needs the teams block`);
32613
+ if (teamColumn !== void 0 && (typeof teamColumn !== "string" || !COLUMN_NAME.test(teamColumn))) throw new TypeError(`${FEED_WHERE}.teamColumn is a column name of the employees table`);
32614
+ if (teamColumn !== void 0 && (teams !== true || !ctx.installed("employees"))) throw new TypeError(`${FEED_WHERE}.teamColumn needs feed.teams and the employees block`);
32615
+ if (teamName === true && (teams !== true || !ctx.of("teams").has("teams", "name"))) throw new TypeError(`${FEED_WHERE}.teamName needs feed.teams and a teams name column`);
32616
+ if (organizationName !== void 0 && typeof organizationName !== "string") throw new TypeError(`${FEED_WHERE}.organizationName is "schema.table.column", matched on the table's id`);
32617
+ if (confidential !== "hide" && confidential !== "busy") throw new TypeError(`${FEED_WHERE}.confidential is "hide" or "busy"`);
32618
+ if (confidential === "busy" && !leaveConfidential(ctx)) throw new TypeError(`${FEED_WHERE}.confidential needs columns.types.confidential`);
32617
32619
  return {
32618
32620
  names: names === true,
32619
32621
  hideTypes,
32620
32622
  typeKey,
32621
32623
  teams: teams === true,
32622
- fields: fields === true
32624
+ fields: fields === true,
32625
+ teamColumn,
32626
+ teamName: teamName === true,
32627
+ organizationName: organizationName === void 0 ? void 0 : columnRef(`${FEED_WHERE}.organizationName`, organizationName),
32628
+ busy: confidential === "busy"
32623
32629
  };
32624
32630
  }
32625
32631
  /** The employee name of request row `row`. */
@@ -32673,8 +32679,37 @@ function leaveFeed(ctx) {
32673
32679
  const teams = extras.teams ? ctx.of("teams") : void 0;
32674
32680
  const subjects = [LEAVE_FEED_SUBJECT, ...teams === void 0 ? [] : [LEAVE_TEAM_FEED_SUBJECT]];
32675
32681
  const typeName = extras.hideTypes.length === 0 ? ty("name") : `case when ${extras.typeKey === void 0 ? leaveTypeKey(ctx, "t") : `t.${sqlIdent(extras.typeKey)}::text`} = any (${sqlString(`{${extras.hideTypes.join(",")}}`)}::text[]) then null else ${ty("name")} end`;
32682
+ const teamMember = () => {
32683
+ if (teams === void 0) return "";
32684
+ if (extras.teamColumn === void 0) return `${leaveRequestUser(ctx, "r")} in (select m.${teams.col("members", "user")} from ${teams.table("members")} m where m.${teams.col("members", "team")}::text = v_team)`;
32685
+ const staff = ctx.of("employees");
32686
+ const y = (column) => `y.${staff.col("employees", column)}`;
32687
+ return `exists (select 1 from ${staff.table("employees")} y where ${leaveByEmployee(ctx) ? `${y("id")} = ${q("employee")}` : `${y("tenant")} = ${q("tenant")} and ${y("user")} = ${q("user")}`} and y.${sqlIdent(extras.teamColumn)}::text = v_team)`;
32688
+ };
32676
32689
  const teamFilter = teams === void 0 ? "" : `
32677
- and (v_team is null or ${leaveRequestUser(ctx, "r")} in (select m.${teams.col("members", "user")} from ${teams.table("members")} m where m.${teams.col("members", "team")}::text = v_team))`;
32690
+ and (v_team is null or ${teamMember()})`;
32691
+ const confidentialType = () => `exists (select 1 from ${ctx.table("types")} lc where lc.${ctx.col("types", "id")}::text = (${q("type")})::text and lc.${ctx.col("types", "confidential")})`;
32692
+ const sees = ctx.scope.canUser("v_creator", "v_tenant", leaveConfidentialKey(ctx));
32693
+ const header = [
32694
+ ...extras.organizationName === void 0 ? [] : [`'organizationName', (select o.${extras.organizationName.column}::text from ${extras.organizationName.table} o where o.id = v_tenant)`],
32695
+ ...teams === void 0 ? [] : ["'teamId', v_team"],
32696
+ ...teams !== void 0 && extras.teamName ? [`'teamName', (select t.${teams.col("teams", "name")}::text from ${teams.table("teams")} t where t.${teams.col("teams", "id")}::text = v_team)`] : []
32697
+ ].map((entry) => `\n ${entry},`).join("");
32698
+ const busy = extras.busy ? `,
32699
+ 'busy', coalesce((
32700
+ select jsonb_agg(x.item order by x.starts_on, x.id)
32701
+ from (
32702
+ select jsonb_build_object('id', ${q("id")}, 'userId', ${leaveRequestUser(ctx, "r")}${leaveByEmployee(ctx) ? `, 'employeeId', ${q("employee")}` : ""}${extras.names ? `, 'name', ${employeeName(ctx, "r")}` : ""},
32703
+ 'startsOn', ${q("startsOn")}, 'endsOn', ${q("endsOn")}, 'partial', ${leavePartial(ctx, "r")}, 'startPart', ${leaveStartPart(ctx, "r")}, 'endPart', ${leaveEndPart(ctx, "r")}, 'updatedAt', ${q("updatedAt")}) as item,
32704
+ ${q("startsOn")} as starts_on, ${q("id")} as id
32705
+ from ${ctx.table("requests")} r
32706
+ where ${q("tenant")} = v_tenant and ${q("approvedAt")} is not null and ${q("cancelledAt")} is null
32707
+ and ${feedDateWindow(feed, q("startsOn"), q("endsOn"))}${teamFilter}
32708
+ and not (${sees}) and ${confidentialType()}
32709
+ order by ${q("startsOn")}, ${q("id")}
32710
+ limit ${String(feed.limit)}
32711
+ ) x
32712
+ ), '[]'::jsonb)` : "";
32678
32713
  return `
32679
32714
  -- The approved leave of the organization or team a share link points at,
32680
32715
  -- for an iCal feed: a year back and everything ahead. Open to anon: the
@@ -32708,7 +32743,7 @@ begin
32708
32743
  end if;
32709
32744
  ${touchShareLink(s, "v_link")}
32710
32745
  return jsonb_build_object(
32711
- 'organizationId', v_tenant,${teams === void 0 ? "" : "\n 'teamId', v_team,"}
32746
+ 'organizationId', v_tenant,${header}
32712
32747
  'requests', coalesce((
32713
32748
  select jsonb_agg(x.item order by x.starts_on, x.id)
32714
32749
  from (
@@ -32718,11 +32753,11 @@ begin
32718
32753
  from ${ctx.table("requests")} r
32719
32754
  join ${ctx.table("types")} t on ${ty("id")} = ${q("type")}
32720
32755
  where ${q("tenant")} = v_tenant and ${q("approvedAt")} is not null and ${q("cancelledAt")} is null
32721
- and ${feedDateWindow(feed, q("startsOn"), q("endsOn"))}${teamFilter}${leaveConfidentialFilter(ctx, q("type"), ctx.scope.canUser("v_creator", "v_tenant", leaveConfidentialKey(ctx)))}
32756
+ and ${feedDateWindow(feed, q("startsOn"), q("endsOn"))}${teamFilter}${leaveConfidentialFilter(ctx, q("type"), sees)}
32722
32757
  order by ${q("startsOn")}, ${q("id")}
32723
32758
  limit ${String(feed.limit)}
32724
32759
  ) x
32725
- ), '[]'::jsonb)
32760
+ ), '[]'::jsonb)${busy}
32726
32761
  );
32727
32762
  end;
32728
32763
  $$;
@@ -34735,6 +34770,59 @@ as $$
34735
34770
  $$;
34736
34771
  grant execute on function ${name}(text) to anon, authenticated, service_role;`;
34737
34772
  }
34773
+ // src/sql/column-defaults.ts
34774
+ const QUOTED_IDENT = /^"(.*)"$/s;
34775
+ const bareName = (ident) => QUOTED_IDENT.exec(ident)?.[1]?.replaceAll("\"\"", "\"") ?? ident;
34776
+ /**
34777
+ * PL/pgSQL that stores in `into` (a `jsonb` variable) the defaults of the
34778
+ * columns of `table` whose value is null, as `[column, value]` pairs of a
34779
+ * quoted identifier and SQL. An insert then writes `withColumnDefault(...)`
34780
+ * instead of an explicit null, so an app column such as `title text not null
34781
+ * default ''` keeps its default. Only the defaults of null values run.
34782
+ */
34783
+ function columnDefaults(table, columns, into) {
34784
+ if (columns.length === 0) return NOTHING;
34785
+ const wanted = columns.map(([column, value]) => `case when ${value} is null then ${sqlString(bareName(column))} end`).join(", ");
34786
+ return `execute coalesce((select 'select jsonb_build_object(' || string_agg(pg_catalog.quote_literal(a.attname) || ', ' || pg_catalog.pg_get_expr(d.adbin, d.adrelid), ', ') || ')'
34787
+ from pg_catalog.pg_attrdef d join pg_catalog.pg_attribute a on a.attrelid = d.adrelid and a.attnum = d.adnum
34788
+ where d.adrelid = ${sqlString(table)}::regclass and a.attname = any (array[${wanted}]::text[])), 'select ''{}''::jsonb') into ${into};`;
34789
+ }
34790
+ /**
34791
+ * `value`, or the default `columnDefaults` stored in `defaults` when it is
34792
+ * null.
34793
+ */
34794
+ const withColumnDefault = (table, column, value, defaults) => `coalesce(${value}, (jsonb_populate_record(null::${table}, ${defaults})).${column})`;
34795
+ /**
34796
+ * An `exception when unique_violation then` body: `then` (a `raise`) when the
34797
+ * violated index of `table` covers `column` (a quoted identifier), in its
34798
+ * columns or its expressions, and the original error otherwise, so an app's own
34799
+ * unique index keeps its constraint name.
34800
+ */
34801
+ function uniqueViolationOn(table, column, then) {
34802
+ const name = sqlString(bareName(column));
34803
+ return `declare
34804
+ v_constraint text;
34805
+ begin
34806
+ get stacked diagnostics v_constraint = constraint_name;
34807
+ if exists (
34808
+ select 1 from pg_catalog.pg_index i
34809
+ join pg_catalog.pg_class c on c.oid = i.indexrelid
34810
+ where i.indrelid = ${sqlString(table)}::regclass and c.relname = v_constraint
34811
+ and (exists (select 1 from pg_catalog.pg_attribute a where a.attrelid = i.indrelid and a.attnum = any (i.indkey) and a.attname = ${name})
34812
+ or coalesce(pg_catalog.pg_get_expr(i.indexprs, i.indrelid), '') ~ ('\\m' || ${name} || '\\M'))
34813
+ ) then
34814
+ ${then}
34815
+ end if;
34816
+ raise;
34817
+ end;`;
34818
+ }
34819
+ // src/sql/modules/catalog-names.ts
34820
+ /** `blocks.catalog.options.rankType`: rank keys or integer positions. */
34821
+ function catalogRank(ctx) {
34822
+ const type = ctx.text("rankType", "text");
34823
+ if (type !== "text" && type !== "integer") throw new TypeError("blocks.catalog.options.rankType must be \"text\" or \"integer\"");
34824
+ return rankSql(type);
34825
+ }
34738
34826
  // src/sql/modules/catalog-tracking.ts
34739
34827
  /**
34740
34828
  * SQL that is true when variant row `alias` of `catalog` tracks inventory: its
@@ -35417,12 +35505,6 @@ function variantInUse(ctx) {
35417
35505
  if (!QUALIFIED$1.test(value)) throw new TypeError("blocks.catalog.options.variantInUse must be a schema-qualified function name, such as public.variant_in_use");
35418
35506
  return value.split(".").map(sqlIdent).join(".");
35419
35507
  }
35420
- /** `blocks.catalog.options.rankType`: rank keys or integer positions. */
35421
- function catalogRank(ctx) {
35422
- const type = ctx.text("rankType", "text");
35423
- if (type !== "text" && type !== "integer") throw new TypeError("blocks.catalog.options.rankType must be \"text\" or \"integer\"");
35424
- return rankSql(type);
35425
- }
35426
35508
  function guard$11(names, tenant, key = names.manage) {
35427
35509
  return `if not (auth.role() = 'service_role' or ${names.scope.can(tenant, key)}) then
35428
35510
  ${fail$1("CATALOG_FORBIDDEN", "not allowed to manage the catalog")}
@@ -35491,7 +35573,7 @@ declare
35491
35573
  v_title text := save_product.title;
35492
35574
  v_slug text := nullif(save_product.slug, '');
35493
35575
  v_status text;
35494
- v_created boolean := save_product.product is null;
35576
+ v_created boolean := save_product.product is null;${desc ? "\n v_defaults jsonb;" : ""}
35495
35577
  begin
35496
35578
  if v_created then
35497
35579
  ${guard$11(names, "save_product.tenant", names.create)}
@@ -35518,9 +35600,9 @@ begin
35518
35600
  ["text", "save_product.kind"]
35519
35601
  ])}
35520
35602
  begin
35521
- if v_created then
35603
+ if v_created then${desc ? `\n ${columnDefaults(products, [[p("description"), "save_product.description"]], "v_defaults")}` : ""}
35522
35604
  insert into ${products} (${p("tenant")}, ${p("title")}, ${p("slug")}${desc ? `, ${p("description")}` : ""}${kind ? `, ${p("kind")}` : ""}${inserted.columns})
35523
- values (save_product.tenant, v_title, v_slug${desc ? ", save_product.description" : ""}${kind ? `, ${ctx.cast("products", "kind", "coalesce(save_product.kind, 'physical')")}` : ""}${inserted.values})
35605
+ values (save_product.tenant, v_title, v_slug${desc ? `, ${withColumnDefault(products, p("description"), "save_product.description", "v_defaults")}` : ""}${kind ? `, ${ctx.cast("products", "kind", "coalesce(save_product.kind, 'physical')")}` : ""}${inserted.values})
35524
35606
  returning ${p("id")}, ${ctx.label("products", "status", p("status"))} into v_id, v_status;
35525
35607
  else
35526
35608
  update ${products} x set ${p("title")} = v_title, ${p("slug")} = v_slug${desc ? `, ${p("description")} = case when ${clears("description")} then null else coalesce(save_product.description, x.${p("description")}) end` : ""}${kind ? `, ${p("kind")} = coalesce(${ctx.cast("products", "kind", "save_product.kind")}, x.${p("kind")})` : ""}, ${p("updatedAt")} = now()${settingSet}${updateExtraColumns(products, extras, "save_product.fields")}
@@ -35531,7 +35613,7 @@ begin
35531
35613
  end if;
35532
35614
  end if;
35533
35615
  exception when unique_violation then
35534
- ${fail$1("CATALOG_SLUG_TAKEN", "another product has this slug", "23505")}
35616
+ ${uniqueViolationOn(products, p("slug"), fail$1("CATALOG_SLUG_TAKEN", "another product has this slug", "23505"))}
35535
35617
  end;${settingWrite}
35536
35618
  if v_created then
35537
35619
  ${ctx.record({
@@ -36009,6 +36091,7 @@ function variantFunctions(ctx, names, historyCheck) {
36009
36091
  "save_variant.allow_backorder"
36010
36092
  ]
36011
36093
  ];
36094
+ const defaulted = columns.filter(([column]) => clearable.includes(column)).map(([column, value]) => [v(column), value]);
36012
36095
  const valueChecks = hasValues ? (() => {
36013
36096
  const options = ctx.table("options");
36014
36097
  const optionValues = ctx.table("optionValues");
@@ -36079,6 +36162,7 @@ declare
36079
36162
  v_last text;
36080
36163
  v_rank text;
36081
36164
  v_sku text := save_variant.sku;
36165
+ v_defaults jsonb;
36082
36166
  begin
36083
36167
  select x.${p("tenant")} into v_tenant from ${products} x where x.${p("id")} = save_variant.product for update;
36084
36168
  if v_tenant is null then
@@ -36103,9 +36187,10 @@ ${valueChecks.check}
36103
36187
  if v_created then
36104
36188
  select max(${rank.order(`x.${v("rank")}`)}) into v_last from ${variants} x where x.${v("product")} = save_variant.product;
36105
36189
  v_rank := ${rank.after("v_last")};
36106
- insert into ${variants} (${v("tenant")}, ${v("product")}, ${columns.map(([column]) => v(column)).join(", ")}, ${v("rank")}${inserted.columns})
36107
- values (v_tenant, save_variant.product, ${columns.map(([, value]) => value).join(", ")}, ${rank.write("v_rank")}${inserted.values})
36108
- returning ${v("id")} into v_id;
36190
+ ${columnDefaults(variants, defaulted, "v_defaults")}
36191
+ insert into ${variants} as x (${v("tenant")}, ${v("product")}, ${columns.map(([column]) => v(column)).join(", ")}, ${v("rank")}${inserted.columns})
36192
+ values (v_tenant, save_variant.product, ${columns.map(([column, value]) => clearable.includes(column) ? withColumnDefault(variants, v(column), value, "v_defaults") : value).join(", ")}, ${rank.write("v_rank")}${inserted.values})
36193
+ returning x.${v("id")}, x.${v("sku")} into v_id, v_sku;
36109
36194
  else
36110
36195
  update ${variants} x set ${columns.map(([column, , param]) => clearable.includes(column) ? `${v(column)} = case when ${sqlString(column)} = any (coalesce(save_variant.clear, '{}'::text[])) then null else coalesce(${param}, x.${v(column)}) end` : `${v(column)} = coalesce(${param}, x.${v(column)})`).join(", ")}, ${v("updatedAt")} = now()${updateExtraColumns(variants, extras, "save_variant.fields")}
36111
36196
  where x.${v("id")} = save_variant.variant and x.${v("product")} = save_variant.product
@@ -36115,7 +36200,7 @@ ${valueChecks.check}
36115
36200
  end if;
36116
36201
  end if;
36117
36202
  exception when unique_violation then
36118
- ${fail$1("CATALOG_SKU_TAKEN", "another variant has this SKU", "23505")}
36203
+ ${uniqueViolationOn(variants, v("sku"), fail$1("CATALOG_SKU_TAKEN", "another variant has this SKU", "23505"))}
36119
36204
  end;
36120
36205
  ${valueChecks.write}
36121
36206
  if v_created then
@@ -37365,6 +37450,7 @@ declare
37365
37450
  v_slug text := coalesce(nullif(save_category.slug, ''), trim(both '-' from regexp_replace(lower(save_category.name), '[^a-z0-9]+', '-', 'g')));
37366
37451
  v_last text;
37367
37452
  v_rank text;
37453
+ v_defaults jsonb;
37368
37454
  begin
37369
37455
  if v_id is null then
37370
37456
  ${guard$11(names, "save_category.tenant", names.categoryCreate)}
@@ -37383,8 +37469,9 @@ begin
37383
37469
  select max(${rank.order(`x.${k("rank")}`)}) into v_last from ${categories} x
37384
37470
  where x.${k("tenant")} = save_category.tenant and x.${k("parent")} is not distinct from save_category.parent;
37385
37471
  v_rank := ${rank.after("v_last")};
37472
+ ${columnDefaults(categories, [[k("description"), "save_category.description"]], "v_defaults")}
37386
37473
  insert into ${categories} (${k("tenant")}, ${k("parent")}, ${k("name")}, ${k("slug")}, ${k("description")}, ${k("rank")}${inserted.columns})
37387
- values (save_category.tenant, save_category.parent, save_category.name, v_slug, save_category.description, ${rank.write("v_rank")}${inserted.values})
37474
+ values (save_category.tenant, save_category.parent, save_category.name, v_slug, ${withColumnDefault(categories, k("description"), "save_category.description", "v_defaults")}, ${rank.write("v_rank")}${inserted.values})
37388
37475
  returning ${k("id")} into v_id;
37389
37476
  else
37390
37477
  update ${categories} x set ${k("parent")} = save_category.parent, ${k("name")} = save_category.name, ${k("slug")} = v_slug,
@@ -37396,7 +37483,7 @@ begin
37396
37483
  end if;
37397
37484
  end if;
37398
37485
  exception when unique_violation then
37399
- ${fail$1("CATALOG_SLUG_TAKEN", "another category has this slug", "23505")}
37486
+ ${uniqueViolationOn(categories, k("slug"), fail$1("CATALOG_SLUG_TAKEN", "another category has this slug", "23505"))}
37400
37487
  end;
37401
37488
  return jsonb_build_object('id', v_id, 'slug', v_slug, 'rank', v_rank)${extras.length === 0 ? "" : ` || (select jsonb_build_object('fields', ${columnsObject("x", extras.map((extra) => extra.name))}) from ${categories} x where x.${k("id")} = v_id)`};
37402
37489
  end;
@@ -51952,6 +52039,7 @@ begin
51952
52039
  and ${skipTables}
51953
52040
  order by (row_number() over ()) desc
51954
52041
  );
52042
+ perform set_config('better_supabase.purge_tenant', purge_organization.tenant::text, true);
51955
52043
  for v_pass in 1..10 loop
51956
52044
  exit when cardinality(v_pending) = 0;
51957
52045
  v_left := '{}';
@@ -51978,6 +52066,7 @@ begin
51978
52066
  end if;
51979
52067
  v_pending := v_left;
51980
52068
  end loop;
52069
+ perform set_config('better_supabase.purge_tenant', '', true);
51981
52070
  update ${d} x set ${cd("purgedAt")} = now() where x.${cd("tenant")} = v_row.${cd("tenant")} returning * into v_row;
51982
52071
  ${organizationRow}
51983
52072
  ${purgedEvent}
@@ -52354,6 +52443,7 @@ function lineItemsSql(ctx, items, options) {
52354
52443
  const optional = (column, definition = () => "text") => has(column) ? `\n ${c(column)} ${definition(c(column))},` : "";
52355
52444
  const name = ctx.tableName(items.lines).name;
52356
52445
  const replaces = ctx.owns(items.lines);
52446
+ const positionKey = items.positionKey ?? true;
52357
52447
  const written = [
52358
52448
  ["tenant", "v_tenant"],
52359
52449
  ["parent", "v_parent"],
@@ -52381,7 +52471,7 @@ function lineItemsSql(ctx, items, options) {
52381
52471
  ${c("unitAmount")} bigint not null,${optional("discountBps", (bps) => `integer not null default 0 check (${bps} >= 0 and ${bps} <= 10000)`)}${optional("taxRateBps", (bps) => `integer not null default 0 check (${bps} >= 0 and ${bps} <= 100000)`)}${optional("taxCode")}${optional("section", (section) => `text check (length(${section}) between 1 and 300)`)}${optional("optional", () => "boolean not null default false")}${optional("selected", () => "boolean not null default true")}
52382
52472
  ${c("position")} integer not null${has("createdAt") ? `,\n ${c("createdAt")} timestamptz not null default now()` : ""}${has("productType") && has("productId") ? `,\n check ((${c("productType")} is null) = (${c("productId")} is null))` : ""}
52383
52473
  );
52384
- create index if not exists ${sqlIdent(`${name}_parent_idx`)} on ${t} (${c("parent")}, ${c("position")});${ctx.owns(items.lines) ? "" : `\ncreate unique index if not exists ${sqlIdent(`bsb_${name}_position_key`)} on ${t} (${c("parent")}, ${c("position")});`}${addExtraColumns(t, extras)}
52474
+ create index if not exists ${sqlIdent(`${name}_parent_idx`)} on ${t} (${c("parent")}, ${c("position")});${ctx.owns(items.lines) || !positionKey ? "" : `\ncreate unique index if not exists ${sqlIdent(`bsb_${name}_position_key`)} on ${t} (${c("parent")}, ${c("position")});`}${addExtraColumns(t, extras)}
52385
52475
  ${lockTable(t, { read: true })}
52386
52476
  drop policy if exists ${sqlIdent(`${name}_read`)} on ${t};
52387
52477
  create policy ${sqlIdent(`${name}_read`)} on ${t} for select to authenticated
@@ -52504,14 +52594,21 @@ begin
52504
52594
  ${fail$1("LINES_CURRENCY", "every line must be in the record's currency", "22023")}
52505
52595
  end if;
52506
52596
  delete from ${t} l where l.${c("parent")} = v_parent${replaces ? "" : ` and l.${c("position")} > jsonb_array_length(coalesce(${options.setter}.lines, '[]'))`};
52507
- begin
52597
+ begin${replaces || positionKey ? "" : `
52598
+ update ${t} l set ${written.filter(([column]) => ![
52599
+ "tenant",
52600
+ "parent",
52601
+ "position"
52602
+ ].includes(column)).map(([column, value]) => `${c(column)} = ${value}`).join(", ")}
52603
+ from jsonb_array_elements(coalesce(${options.setter}.lines, '[]')) with ordinality x
52604
+ where l.${c("parent")} = v_parent and l.${c("position")} = x.ordinality;`}
52508
52605
  insert into ${t} (${written.map(([column]) => c(column)).join(", ")}${extrasInsert.columns})
52509
52606
  select ${written.map(([, value]) => value).join(",\n ")}${extrasInsert.values}
52510
- from jsonb_array_elements(coalesce(${options.setter}.lines, '[]')) with ordinality x${replaces ? "" : `\n on conflict (${c("parent")}, ${c("position")}) do update set ${written.filter(([column]) => ![
52607
+ from jsonb_array_elements(coalesce(${options.setter}.lines, '[]')) with ordinality x${replaces ? "" : positionKey ? `\n on conflict (${c("parent")}, ${c("position")}) do update set ${written.filter(([column]) => ![
52511
52608
  "tenant",
52512
52609
  "parent",
52513
52610
  "position"
52514
- ].includes(column)).map(([column]) => `${c(column)} = excluded.${c(column)}`).join(", ")}`};
52611
+ ].includes(column)).map(([column]) => `${c(column)} = excluded.${c(column)}`).join(", ")}` : `\n where not exists (select 1 from ${t} l where l.${c("parent")} = v_parent and l.${c("position")} = x.ordinality)`};
52515
52612
  exception when check_violation or not_null_violation or invalid_text_representation or numeric_value_out_of_range then
52516
52613
  ${fail$1("LINES_INVALID", "every line needs a description, a positive quantity and a unit amount", "22023")}
52517
52614
  end;${extras.length === 0 ? "" : `
@@ -65876,6 +65973,9 @@ function expenseStandaloneSql(ctx) {
65876
65973
  const updateOthers = expenseKey(ctx, "update");
65877
65974
  const deleteOthers = expenseKey(ctx, "delete");
65878
65975
  const reimburse = expenseKey(ctx, "reimburse");
65976
+ const withdrawApproved = ctx.flag("withdrawApproved", false);
65977
+ const withdrawOthers = sqlString(ctx.config.permissions["withdraw"] ?? ctx.config.permissions["update"] ?? ctx.permissionKey("manage", ops.manage));
65978
+ const deleteSubmitted = ctx.config.permissions["deleteSubmitted"];
65879
65979
  const extras = ctx.extraColumns("expenses", EXPENSE_RESERVED);
65880
65980
  const extra = extraFieldsArg(extras);
65881
65981
  const statusColumn = has("status");
@@ -66083,11 +66183,11 @@ set search_path = ''
66083
66183
  as $$
66084
66184
  declare
66085
66185
  v_row ${table}%rowtype;
66086
- begin${load("withdraw_expense.expense_id")}${ownerOrManager(updateOthers)}
66087
- if ${status("v_row")} <> 'submitted' then
66088
- ${fail$1("EXPENSE_LOCKED", "only a submitted expense is withdrawn", "55000")}
66186
+ begin${load("withdraw_expense.expense_id")}${ownerOrManager(withdrawApproved ? withdrawOthers : updateOthers)}
66187
+ if ${status("v_row")} not in (${withdrawApproved ? "'submitted', 'approved'" : "'submitted'"}) then
66188
+ ${fail$1("EXPENSE_LOCKED", withdrawApproved ? "only a submitted or approved expense is withdrawn" : "only a submitted expense is withdrawn", "55000")}
66089
66189
  end if;
66090
- update ${table} x set ${e("submittedAt")} = null${setStatus("draft")}, ${e("updatedAt")} = now()
66190
+ update ${table} x set ${e("submittedAt")} = null${setStatus("draft")}${withdrawApproved ? `${set("approvedAt", "null")}${set("decidedBy", "null")}${set("decidedAt", "null")}` : ""}, ${e("updatedAt")} = now()
66091
66191
  where x.${e("id")} = v_row.${e("id")}
66092
66192
  returning * into v_row;
66093
66193
  ${record("expense.withdrawn", "withdrew an expense")}
@@ -66104,9 +66204,15 @@ set search_path = ''
66104
66204
  as $$
66105
66205
  declare
66106
66206
  v_row ${table}%rowtype;
66107
- begin${load("delete_expense.expense_id")}${ownerOrManager(deleteOthers)}
66108
- if ${status("v_row")} <> 'draft' then
66109
- ${fail$1("EXPENSE_LOCKED", "only a draft expense is deleted", "55000")}
66207
+ begin${load("delete_expense.expense_id")}${deleteSubmitted === void 0 ? ownerOrManager(deleteOthers) : `
66208
+ if ${status("v_row")} in ('submitted', 'approved') then
66209
+ if not (${SERVICE_CALLER$1} or ${ctx.can("tenant", `v_row.${e("tenant")}`, sqlString(deleteSubmitted))}) then
66210
+ ${forbidden("not allowed to delete a submitted or approved expense")}
66211
+ end if;
66212
+ else${ownerOrManager(deleteOthers).replaceAll("\n", "\n ")}
66213
+ end if;`}
66214
+ if ${status("v_row")} <> 'draft'${deleteSubmitted === void 0 ? "" : ` and ${status("v_row")} not in ('submitted', 'approved')`} then
66215
+ ${fail$1("EXPENSE_LOCKED", deleteSubmitted === void 0 ? "only a draft expense is deleted" : "only a draft, submitted or approved expense is deleted", "55000")}
66110
66216
  end if;
66111
66217
  delete from ${table} x where x.${e("id")} = v_row.${e("id")};
66112
66218
  ${record("expense.deleted", "deleted an expense")}
@@ -66961,7 +67067,8 @@ const NAMES$72 = {
66961
67067
  "categoryExtraColumns",
66962
67068
  "approvals",
66963
67069
  "owner",
66964
- "companyExpenses"
67070
+ "companyExpenses",
67071
+ "withdrawApproved"
66965
67072
  ],
66966
67073
  tables: {
66967
67074
  categories: {
@@ -70995,7 +71102,7 @@ begin
70995
71102
  from (
70996
71103
  select jsonb_build_object('id', y.${e("id")}, 'accountId', y.${e("account")}, 'amount', y.${e("amount")}::text, 'unit', y.${e("unit")},
70997
71104
  'transactionId', r.${t("id")}, 'kind', r.${t("kind")}, 'referenceType', r.${t("referenceType")}, 'referenceId', r.${t("referenceId")},
70998
- 'memo', ${memo("r")}, 'reverses', r.${t("reverses")}, 'metadata', r.${t("metadata")}, 'effectiveAt', r.${t("effectiveAt")}, 'createdAt', y.${e("createdAt")}) as item,
71105
+ 'memo', ${memo("r")}, 'reverses', r.${t("reverses")}, 'metadata', r.${t("metadata")}, 'effectiveAt', r.${t("effectiveAt")}, 'actorId', r.${t("actor")}, 'createdAt', y.${e("createdAt")}) as item,
70999
71106
  y.${e("createdAt")} as created, y.${e("id")} as id
71000
71107
  from ${entries} y
71001
71108
  join ${transactions} r on r.${t("id")} = y.${e("transaction")}
@@ -71352,6 +71459,21 @@ from (
71352
71459
  ) s
71353
71460
  on conflict (${b("account")}) do update set ${b("balance")} = excluded.${b("balance")}, ${b("held")} = excluded.${b("held")}${ledgerTouch(ctx)};`;
71354
71461
  }
71462
+ function purgeBypass(ctx) {
71463
+ if (!ctx.installed("data-lifecycle")) return "";
71464
+ const lifecycle = ctx.of("data-lifecycle");
71465
+ const d = (column) => lifecycle.col("deletions", column);
71466
+ return `
71467
+ if tg_op = 'DELETE' and current_setting('better_supabase.purge_tenant', true) = to_jsonb(old) ->> tg_argv[0] then
71468
+ if ${SERVICE_CALLER$1} and exists (
71469
+ select 1 from ${lifecycle.table("deletions")} x
71470
+ where x.${d("tenant")}::text = to_jsonb(old) ->> tg_argv[0]
71471
+ and x.${d("cancelledAt")} is null and x.${d("purgedAt")} is null and x.${d("purgeAfter")} <= now()
71472
+ ) then
71473
+ return old;
71474
+ end if;
71475
+ end if;`;
71476
+ }
71355
71477
  function build$66(ctx) {
71356
71478
  if (ctx.mode === "custom") return "";
71357
71479
  const accounts = ctx.table("accounts");
@@ -71456,17 +71578,17 @@ returns trigger
71456
71578
  language plpgsql
71457
71579
  set search_path = ''
71458
71580
  as $$
71459
- begin
71581
+ begin${purgeBypass(ctx)}
71460
71582
  ${fail$1("LEDGER_APPEND_ONLY", "ledger entries and transactions can't be changed or deleted; post a reversal", "55000")}
71461
71583
  end;
71462
71584
  $$;
71463
71585
  revoke execute on function ${fn("ledger_append_only")}() from public, anon, authenticated;
71464
71586
  drop trigger if exists ${ctx.trigger("ledger_entries_append_only")} on ${entries};
71465
71587
  create trigger ${ctx.trigger("ledger_entries_append_only")} before update or delete on ${entries}
71466
- for each row execute function ${fn("ledger_append_only")}();
71588
+ for each row execute function ${fn("ledger_append_only")}(${sqlString(ctx.colName("entries", "tenant"))});
71467
71589
  drop trigger if exists ${ctx.trigger("ledger_transactions_append_only")} on ${transactions};
71468
71590
  create trigger ${ctx.trigger("ledger_transactions_append_only")} before update or delete on ${transactions}
71469
- for each row execute function ${fn("ledger_append_only")}();
71591
+ for each row execute function ${fn("ledger_append_only")}(${sqlString(ctx.colName("transactions", "tenant"))});
71470
71592
 
71471
71593
  -- Keeps the account's balance and refuses to take an account that doesn't
71472
71594
  -- allow it below zero (counting its holds).
@@ -71588,7 +71710,11 @@ const LEDGER = {
71588
71710
  title: "Ledger",
71589
71711
  description: "Double-entry accounts in a currency or a custom unit, balanced transactions, balances and holds. Credits, stock, leave balances and invoice payments post through it.",
71590
71712
  requires: ["memberships", "permissions"],
71591
- integrates: ["outbox", "audit"],
71713
+ integrates: [
71714
+ "outbox",
71715
+ "audit",
71716
+ "data-lifecycle"
71717
+ ],
71592
71718
  before: "inventory",
71593
71719
  target: "schema",
71594
71720
  modes: ["managed", "custom"],
@@ -85567,7 +85693,8 @@ function invoiceFunctions(ctx, n) {
85567
85693
  ${fail$1(`INVOICE_${kind}_FORBIDDEN`, `the ${party} is unknown or not readable in this organization`, "42501")}
85568
85694
  end if;`;
85569
85695
  };
85570
- const settle = (alias) => `
85696
+ const afterWriteOff = ctx.flag("paymentsAfterWriteOff", false);
85697
+ const settle = (alias, writtenOff = false) => `
85571
85698
  update ${t("invoices")} x set
85572
85699
  ${i("paidTotal")} = ${ledger.paidTotal("x")},
85573
85700
  ${i("updatedAt")} = now()
@@ -85575,11 +85702,16 @@ function invoiceFunctions(ctx, n) {
85575
85702
  returning * into ${alias};
85576
85703
  update ${t("invoices")} x set
85577
85704
  ${i("status")} = ${ctx.cast("invoices", "status", `case
85578
- when ${balance("x")} <= 0 then 'paid'
85705
+ when ${balance("x")} <= 0 then 'paid'${writtenOff ? `\n when ${st(`x.${i("status")}`, ["uncollectible"])} then 'uncollectible'` : ""}
85579
85706
  when x.${i("paidTotal")} > 0 or x.${i("creditedTotal")} > 0 then 'partially_paid'
85580
85707
  else 'issued' end`)},
85581
85708
  ${i("paidAt")} = case when ${balance("x")} <= 0 then coalesce(x.${i("paidAt")}, now()) end
85582
- where x.${i("id")} = ${alias}.${i("id")} and ${st(`x.${i("status")}`, [
85709
+ where x.${i("id")} = ${alias}.${i("id")} and ${st(`x.${i("status")}`, writtenOff ? [
85710
+ "issued",
85711
+ "partially_paid",
85712
+ "paid",
85713
+ "uncollectible"
85714
+ ] : [
85583
85715
  "issued",
85584
85716
  "partially_paid",
85585
85717
  "paid"
@@ -85896,7 +86028,8 @@ ${updateInvoiceSql()}${lineItemsSql(ctx, {
85896
86028
  parent: "invoices",
85897
86029
  frozen: st(`p.${i("status")}`, ["draft"], true),
85898
86030
  extras: n.lineExtras,
85899
- totals: !n.appTotals
86031
+ totals: !n.appTotals,
86032
+ positionKey: ctx.flag("linePositionKey", true)
85900
86033
  }, {
85901
86034
  setter: "set_invoice_lines",
85902
86035
  guard: `if not exists (select 1 from ${t("invoices")} x where x.${i("id")} = v_parent and ${can("x", n.update)}) then
@@ -86003,7 +86136,12 @@ begin
86003
86136
  if v_row.${i("id")} is null then
86004
86137
  ${fail$1("INVOICE_NOT_FOUND", "no such invoice you can edit", "P0002")}
86005
86138
  end if;
86006
- if ${kd(`v_row.${i("kind")}`, ["invoice"], true)} or ${st(`v_row.${i("status")}`, [
86139
+ if ${kd(`v_row.${i("kind")}`, ["invoice"], true)} or ${st(`v_row.${i("status")}`, afterWriteOff ? [
86140
+ "issued",
86141
+ "partially_paid",
86142
+ "paid",
86143
+ "uncollectible"
86144
+ ] : [
86007
86145
  "issued",
86008
86146
  "partially_paid",
86009
86147
  "paid"
@@ -86029,7 +86167,7 @@ begin
86029
86167
  end if;
86030
86168
  ${ctx.hook("before_invoice_payment", [["uuid", `v_row.${i("id")}`], ["bigint", "record_invoice_payment.amount"]])}
86031
86169
  v_was := v_row.${i("status")};
86032
- v_payment := ${ledger.post("v_row", "record_invoice_payment.amount", "coalesce(record_invoice_payment.paid_at, now())", "record_invoice_payment.method", "v_reference", "nullif(trim(record_invoice_payment.note), '')")};${settle("v_row")}
86170
+ v_payment := ${ledger.post("v_row", "record_invoice_payment.amount", "coalesce(record_invoice_payment.paid_at, now())", "record_invoice_payment.method", "v_reference", "nullif(trim(record_invoice_payment.note), '')")};${settle("v_row", afterWriteOff)}
86033
86171
  ${record("invoice.payment_recorded", "v_row", `, 'paymentId', v_payment, 'amount', record_invoice_payment.amount::text, 'balance', ${balance("v_row")}::text`)}
86034
86172
  if ${st(`v_row.${i("status")}`, ["paid"])} and ${st("v_was", ["paid"], true)} then
86035
86173
  ${record("invoice.paid", "v_row", `, 'total', v_row.${i("total")}::text`)}
@@ -86040,6 +86178,25 @@ end;
86040
86178
  $$;
86041
86179
  ${userGrant(`${fn("record_invoice_payment")}(uuid, bigint, text, timestamptz, text, text, text)`)}
86042
86180
 
86181
+ create or replace function ${fn("list_invoice_payments")}(invoice uuid)
86182
+ returns jsonb
86183
+ language plpgsql
86184
+ stable
86185
+ security definer
86186
+ set search_path = ''
86187
+ as $$
86188
+ declare
86189
+ v_row ${t("invoices")};
86190
+ begin
86191
+ select * into v_row from ${t("invoices")} x where x.${i("id")} = list_invoice_payments.invoice and ${can("x", n.read)};
86192
+ if v_row.${i("id")} is null then
86193
+ ${fail$1("INVOICE_NOT_FOUND", "no such invoice you can read", "P0002")}
86194
+ end if;
86195
+ return jsonb_build_object('currency', v_row.${i("currency")}, 'payments', ${ledger.payments("v_row")});
86196
+ end;
86197
+ $$;
86198
+ ${userGrant(`${fn("list_invoice_payments")}(uuid)`)}
86199
+
86043
86200
  -- A draft credit note against an issued invoice: its lines, or the given
86044
86201
  -- lines for a partial credit. Issue it to apply it.
86045
86202
  create or replace function ${fn("credit_invoice")}(invoice uuid, lines jsonb, note text)
@@ -86341,7 +86498,10 @@ const NAMES$56 = {
86341
86498
  "lineRates",
86342
86499
  "chargeExtraColumns",
86343
86500
  "totals",
86344
- "providerPaymentMethods"
86501
+ "providerPaymentMethods",
86502
+ "uniqueNumber",
86503
+ "linePositionKey",
86504
+ "paymentsAfterWriteOff"
86345
86505
  ],
86346
86506
  tables: {
86347
86507
  invoices: {
@@ -86437,6 +86597,7 @@ function tables$16(ctx, n) {
86437
86597
  const company = invoiceParty(ctx, "company");
86438
86598
  const contact = invoiceParty(ctx, "contact");
86439
86599
  const origin = invoiceParty(ctx, "origin");
86600
+ const uniqueNumber = invoiceUniqueNumber(ctx);
86440
86601
  const ch = (column) => c("charges", column);
86441
86602
  const chargeColumns = [
86442
86603
  `${ch("id")} uuid primary key default gen_random_uuid()`,
@@ -86488,15 +86649,14 @@ create table if not exists ${t("invoices")} (
86488
86649
  ${i("createdAt")} timestamptz not null default now(),
86489
86650
  ${i("updatedAt")} timestamptz not null default now(),
86490
86651
  ${totalColumnsSql(ctx, "invoices")},
86491
- unique (${i("tenant")}, ${i("kind")}, ${i("number")}),
86492
- check ((${i("kind")} = 'credit_note') = (${i("original")} is not null)),
86652
+ ${uniqueNumber === false ? "" : ` unique (${i("tenant")}, ${i("kind")}, ${i(uniqueNumber)}),\n`} check ((${i("kind")} = 'credit_note') = (${i("original")} is not null)),
86493
86653
  check (${i("status")} <> 'draft' or ${i("number")} is null),
86494
86654
  check (${i("status")} in ('draft', 'void') or ${i("number")} is not null)${company === "pair" ? `,\n check ((${i("companyType")} is null) = (${i("companyId")} is null))` : ""}
86495
86655
  );
86496
- 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)}${appUniqueIndex(ctx, "invoices", [
86656
+ 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", [
86497
86657
  "tenant",
86498
86658
  "kind",
86499
- "number"
86659
+ uniqueNumber
86500
86660
  ])}
86501
86661
  ${lockModuleTable(ctx, "invoices", { read: true })}
86502
86662
  ${renderPolicy(policy$1({
@@ -86516,6 +86676,15 @@ ${renderPolicy(policy$1({
86516
86676
  ${charges}
86517
86677
  `;
86518
86678
  }
86679
+ /**
86680
+ * `options.uniqueNumber`: the column that is unique per tenant and kind, or
86681
+ * `false` when the app keeps numbers unique itself.
86682
+ */
86683
+ function invoiceUniqueNumber(ctx) {
86684
+ const value = ctx.option("uniqueNumber") ?? "number";
86685
+ if (value !== "number" && value !== "identifier" && value !== false) throw new TypeError("blocks.invoices.options.uniqueNumber must be \"number\", \"identifier\" or false");
86686
+ return value;
86687
+ }
86519
86688
  /** `options.totals`: who keeps an invoice's totals. */
86520
86689
  function invoiceTotals(ctx) {
86521
86690
  const totals = ctx.text("totals", "block");
@@ -86665,6 +86834,11 @@ function contract$48(ctx) {
86665
86834
  ],
86666
86835
  returns: "jsonb"
86667
86836
  },
86837
+ {
86838
+ name: "list_invoice_payments",
86839
+ args: ["uuid"],
86840
+ returns: "jsonb"
86841
+ },
86668
86842
  ...ctx.installed("quotes") ? [{
86669
86843
  name: "invoice_from_quote",
86670
86844
  args: ["uuid", "integer"],
@@ -88959,6 +89133,10 @@ function leaveBalanceFunctions(ctx, parts) {
88959
89133
  const forbidden = (message) => fail$1("LEAVE_FORBIDDEN", message);
88960
89134
  const invalid = (message) => fail$1("LEAVE_INVALID", message, "22023");
88961
89135
  const ownerDrop = (name, types) => employee ? `drop function if exists ${fn(name)}(${types});\n` : "";
89136
+ const effectiveCheck = (arg) => has("effectiveOn") ? "" : `
89137
+ if ${arg} is not null then
89138
+ ${fail$1("LEAVE_EFFECTIVE_UNSUPPORTED", "this leave balances table has no effective date column", "22023")}
89139
+ end if;`;
88962
89140
  const effective = (row) => has("effectiveOn") ? `${row}.${b("effectiveOn")}` : "null::date";
88963
89141
  const expires = (row) => has("expiresOn") ? `${row}.${b("expiresOn")}` : "null::date";
88964
89142
  const kindText = (row) => `${row}.${b("kind")}::text`;
@@ -89119,7 +89297,8 @@ $$;
89119
89297
  ${userGrant(`${fn("leave_ledger_entries")}(${idType}, uuid, integer, uuid${employee ? ", uuid" : ""})`)}
89120
89298
 
89121
89299
  drop function if exists ${fn("adjust_leave_balance")}(${idType}, uuid, uuid, numeric, integer, text, text);
89122
- ${employee ? `drop function if exists ${fn("adjust_leave_balance")}(${idType}, uuid, uuid, numeric, integer, text, text, uuid);\n` : ""}create or replace function ${fn("adjust_leave_balance")}(tenant ${idType}, user_id uuid, type_id uuid, amount numeric, period integer default null, kind text default 'adjustment', note text default null${employee ? ", employee_id uuid default null" : ""}, expires_on date default null)
89300
+ ${employee ? `drop function if exists ${fn("adjust_leave_balance")}(${idType}, uuid, uuid, numeric, integer, text, text, uuid);\n` : ""}drop function if exists ${fn("adjust_leave_balance")}(${idType}, uuid, uuid, numeric, integer, text, text${employee ? ", uuid" : ""}, date);
89301
+ create or replace function ${fn("adjust_leave_balance")}(tenant ${idType}, user_id uuid, type_id uuid, amount numeric, period integer default null, kind text default 'adjustment', note text default null${employee ? ", employee_id uuid default null" : ""}, expires_on date default null, effective_on date default null)
89123
89302
  returns jsonb
89124
89303
  language plpgsql
89125
89304
  security definer
@@ -89127,7 +89306,7 @@ set search_path = ''
89127
89306
  as $$
89128
89307
  #variable_conflict use_column
89129
89308
  declare
89130
- v_period integer := coalesce(adjust_leave_balance.period, extract(year from current_date)::integer);
89309
+ v_period integer := coalesce(adjust_leave_balance.period, extract(year from coalesce(adjust_leave_balance.effective_on, current_date))::integer);
89131
89310
  v_entry uuid;
89132
89311
  v_row jsonb;${employee ? "\n v_owner uuid;\n v_user uuid;" : "\n v_user uuid := adjust_leave_balance.user_id;"}
89133
89312
  begin
@@ -89139,7 +89318,7 @@ begin
89139
89318
  end if;
89140
89319
  if adjust_leave_balance.amount is null or adjust_leave_balance.amount = 0 then
89141
89320
  ${invalid("amount must not be zero")}
89142
- end if;
89321
+ end if;${effectiveCheck("adjust_leave_balance.effective_on")}
89143
89322
  ${employee ? ` if adjust_leave_balance.user_id is null and adjust_leave_balance.employee_id is null then
89144
89323
  ${invalid("name user_id or employee_id")}
89145
89324
  end if;
@@ -89153,15 +89332,16 @@ ${employee ? ` if adjust_leave_balance.user_id is null and adjust_leave_balance
89153
89332
  ${fail$1("LEAVE_TYPE_NOT_FOUND", "leave type not found", "P0002")}
89154
89333
  end if;
89155
89334
  v_entry := ${fn("leave_post")}(adjust_leave_balance.tenant, ${key}, adjust_leave_balance.type_id,
89156
- coalesce(adjust_leave_balance.kind, 'adjustment'), adjust_leave_balance.amount, v_period, null, adjust_leave_balance.note, null, null, adjust_leave_balance.expires_on);
89335
+ coalesce(adjust_leave_balance.kind, 'adjustment'), adjust_leave_balance.amount, v_period, null, adjust_leave_balance.note, null, null, adjust_leave_balance.expires_on, adjust_leave_balance.effective_on);
89157
89336
  select ${entryJson("y")} into v_row from ${balances} y where y.${b("id")} = v_entry;
89158
89337
  ${adjusted}
89159
89338
  return v_row;
89160
89339
  end;
89161
89340
  $$;
89162
- ${userGrant(`${fn("adjust_leave_balance")}(${idType}, uuid, uuid, numeric, integer, text, text${employee ? ", uuid" : ""}, date)`)}
89341
+ ${userGrant(`${fn("adjust_leave_balance")}(${idType}, uuid, uuid, numeric, integer, text, text${employee ? ", uuid" : ""}, date, date)`)}
89163
89342
 
89164
- ${ownerDrop("accrue_leave", `${idType}, uuid, numeric, integer, uuid[], text, text`)}create or replace function ${fn("accrue_leave")}(tenant ${idType}, type_id uuid, amount numeric default null, period integer default null, user_ids uuid[] default null, idempotency_key text default null, note text default null${employee ? ", employee_ids uuid[] default null" : ""})
89343
+ ${ownerDrop("accrue_leave", `${idType}, uuid, numeric, integer, uuid[], text, text`)}drop function if exists ${fn("accrue_leave")}(${idType}, uuid, numeric, integer, uuid[], text, text${employee ? ", uuid[]" : ""});
89344
+ create or replace function ${fn("accrue_leave")}(tenant ${idType}, type_id uuid, amount numeric default null, period integer default null, user_ids uuid[] default null, idempotency_key text default null, note text default null${employee ? ", employee_ids uuid[] default null" : ""}, effective_on date default null)
89165
89345
  returns integer
89166
89346
  language plpgsql
89167
89347
  security definer
@@ -89184,20 +89364,21 @@ begin
89184
89364
  v_amount := ${ctx.has("types", "allowance") ? `coalesce(accrue_leave.amount, v_type.${ty("allowance")})` : "accrue_leave.amount"};
89185
89365
  if v_amount is null or v_amount <= 0 then
89186
89366
  ${invalid("name an amount, or give the type an allowance")}
89187
- end if;
89367
+ end if;${effectiveCheck("accrue_leave.effective_on")}
89188
89368
  for v_owner in
89189
89369
  ${accrueOwners}
89190
89370
  loop
89191
89371
  continue when accrue_leave.idempotency_key is not null
89192
89372
  and ${fn("leave_posted")}(accrue_leave.tenant, v_owner, v_type.${ty("id")}, accrue_leave.idempotency_key);
89193
89373
  perform ${fn("leave_post")}(accrue_leave.tenant, v_owner, v_type.${ty("id")}, 'accrual', v_amount,
89194
- coalesce(accrue_leave.period, extract(year from current_date)::integer), null, accrue_leave.note, accrue_leave.idempotency_key);
89374
+ coalesce(accrue_leave.period, extract(year from coalesce(accrue_leave.effective_on, current_date))::integer), null, accrue_leave.note, accrue_leave.idempotency_key,
89375
+ null, null, accrue_leave.effective_on);
89195
89376
  v_count := v_count + 1;
89196
89377
  end loop;
89197
89378
  return v_count;
89198
89379
  end;
89199
89380
  $$;
89200
- ${userGrant(`${fn("accrue_leave")}(${idType}, uuid, numeric, integer, uuid[], text, text${employee ? ", uuid[]" : ""})`)}
89381
+ ${userGrant(`${fn("accrue_leave")}(${idType}, uuid, numeric, integer, uuid[], text, text${employee ? ", uuid[]" : ""}, date)`)}
89201
89382
 
89202
89383
  create or replace function ${fn("close_leave_year")}(tenant ${idType}, period integer)
89203
89384
  returns integer