better-supabase 0.33.0 → 0.35.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-IrglDJCs.d.ts → app-tables-X3yzJljM.d.ts} +1 -1
  3. package/dist/{authorization-BlmDNI2b.d.ts → authorization-D1P3VBOd.d.ts} +53 -1
  4. package/dist/{automations-Bw5cX7oj.js → automations-D4QTP8nI.js} +2 -1
  5. package/dist/{bind-DP-KLgYI.d.ts → bind-Bvv-Zrdh.d.ts} +1 -1
  6. package/dist/{block-env-CJ38ZSTP.d.ts → block-env-h_uPl2f_.d.ts} +3 -3
  7. package/dist/{block-tables-CQTU71zn.d.ts → block-tables-pj3eHfoP.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 +15 -0
  18. package/dist/blocks/catalog/index.js +23 -8
  19. package/dist/blocks/comments/index.d.ts +4 -4
  20. package/dist/blocks/deals/index.js +1 -1
  21. package/dist/blocks/drive/index.js +1 -1
  22. package/dist/blocks/entitlements/index.d.ts +2 -2
  23. package/dist/blocks/forms/index.d.ts +1 -1
  24. package/dist/blocks/inbox/index.d.ts +4 -4
  25. package/dist/blocks/index.d.ts +1 -1
  26. package/dist/blocks/invoices/index.d.ts +4 -0
  27. package/dist/blocks/invoices/index.js +6 -3
  28. package/dist/blocks/messaging/index.d.ts +4 -4
  29. package/dist/blocks/mfa/index.d.ts +1 -1
  30. package/dist/blocks/notifications/index.d.ts +3 -3
  31. package/dist/blocks/onboarding/index.d.ts +1 -1
  32. package/dist/blocks/organizations/index.d.ts +2 -2
  33. package/dist/blocks/permissions/index.d.ts +1 -1
  34. package/dist/blocks/push/index.d.ts +1 -1
  35. package/dist/blocks/quotes/index.js +1 -1
  36. package/dist/blocks/reactions/index.d.ts +3 -3
  37. package/dist/blocks/saved-views/index.d.ts +1 -1
  38. package/dist/blocks/search/index.d.ts +2 -2
  39. package/dist/blocks/sessions/index.d.ts +1 -1
  40. package/dist/blocks/settings/index.d.ts +1 -1
  41. package/dist/blocks/subjects/index.d.ts +1 -1
  42. package/dist/blocks/tags/index.d.ts +1 -1
  43. package/dist/blocks/time-tracking/index.js +1 -1
  44. package/dist/blocks/undo/index.d.ts +1 -1
  45. package/dist/blocks/usage/index.d.ts +1 -1
  46. package/dist/blocks/workflow-editor/index.d.ts +3 -3
  47. package/dist/blocks/workflows/index.d.ts +3 -3
  48. package/dist/claims/index.d.ts +3 -3
  49. package/dist/cli/add-BaB3y1lv.js +1 -0
  50. package/dist/cli/{add-D2pKTbPw.js → add-CYreXA68.js} +9 -9
  51. package/dist/cli/{add-BDLLVLI8.js → add-DzgsOE8V.js} +2 -2
  52. package/dist/cli/{app-table-files-CimWi_eh.js → app-table-files-BnISa3uY.js} +2 -2
  53. package/dist/cli/{backfill-B1xAsdL4.js → backfill-BLLTSDSa.js} +1 -1
  54. package/dist/cli/bin.js +1 -1
  55. package/dist/cli/{blocks-DtZtn-R4.js → blocks-CpRvI7x8.js} +1 -1
  56. package/dist/cli/{blocks-rBeis04I.js → blocks-uzh1g_0v.js} +1 -1
  57. package/dist/cli/{cache-CvBRwv02.js → cache-BPWC7tGD.js} +1 -1
  58. package/dist/cli/{codemod-DYbVbJ-e.js → codemod-CbJVS_kG.js} +1 -1
  59. package/dist/cli/{content-mapper-DrhtDsAm.js → content-mapper-Cjkm2Sg3.js} +2 -2
  60. package/dist/cli/{doctor-Dn4TzGmw.js → doctor-D94FEJZs.js} +19 -19
  61. package/dist/cli/{gen-BbeS0KgF.js → gen-Cd0VNDjE.js} +11 -11
  62. package/dist/cli/index.d.ts +1 -1
  63. package/dist/cli/index.js +6 -6
  64. package/dist/cli/{init-C30xdMSs.js → init-Co1N9ZoA.js} +8 -8
  65. package/dist/cli/{live-Ctc8Qh9Y.js → live-NFNeZsP7.js} +2 -2
  66. package/dist/cli/{mcp-5J0kUOtD.js → mcp-WZ8t7NMz.js} +2 -2
  67. package/dist/cli/{metadata-DxhUNctA.js → metadata-BzMkmrZR.js} +3 -3
  68. package/dist/cli/{migrate-ockrh3UX.js → migrate-C9gyDAV7.js} +1 -1
  69. package/dist/cli/{migration-safety-CLrqC0D-.js → migration-safety-BNi8PIiM.js} +1 -1
  70. package/dist/cli/{migrations-CZTg2UJM.js → migrations-Ds0J_TmZ.js} +2 -2
  71. package/dist/cli/{module-migration-BptQzmj2.js → module-migration-hFrlzQZ5.js} +2 -2
  72. package/dist/cli/powersync-J2Kms2NT.js +1 -0
  73. package/dist/cli/{powersync-DIvsipKr.js → powersync-oFiwgsBi.js} +3 -3
  74. package/dist/cli/{print-DdHt8xCc.js → print-BtreoJSm.js} +2 -2
  75. package/dist/cli/{providers-k-1cEna6.js → providers-Be2dgyuR.js} +1 -1
  76. package/dist/cli/{prune-workflows-Ddv-GfkO.js → prune-workflows-BPxgRrqY.js} +1 -1
  77. package/dist/cli/{remove-DEEQDoc7.js → remove-B4ad996E.js} +5 -5
  78. package/dist/cli/{render-SjSVz8yK.js → render-C-Mfq-o3.js} +3 -3
  79. package/dist/cli/{run-DdhIK7-K.js → run-D2nuyyPo.js} +47 -39
  80. package/dist/cli/{run-Ixt9mEb6.js → run-cLdnJHH0.js} +25 -25
  81. package/dist/cli/{shared-p6sxli_5.js → shared-DCHxLAEL.js} +1 -1
  82. package/dist/cli/{snapshot-Dd_8B9g-.js → snapshot-CloKPNxv.js} +2 -2
  83. package/dist/cli/{source-BYvVe_Es.js → source-Bwyp18Rj.js} +1 -1
  84. package/dist/cli/{spec-BxQgllJY.js → spec-DAUF4ybu.js} +2 -2
  85. package/dist/cli/{spec-liRzcZTa.js → spec-DsVq4_qV.js} +1 -1
  86. package/dist/cli/{sql-layout-DHwiUOaD.js → sql-layout-CHpEL0oq.js} +3 -3
  87. package/dist/cli/{sync-CreQWj53.js → sync-DZu1r34s.js} +4 -4
  88. package/dist/cli/{upgrade-U7IKj45h.js → upgrade-A-BALvp3.js} +2 -2
  89. package/dist/cli/{upgrade-3NQOUO1_.js → upgrade-Bpvi70zm.js} +5 -5
  90. package/dist/cli/{version-mBwP-aMG.js → version-B59mZJoy.js} +1 -1
  91. package/dist/client/index.d.ts +5 -5
  92. package/dist/client/native/index.d.ts +4 -4
  93. package/dist/config/index.d.ts +2 -2
  94. package/dist/config/index.js +4 -4
  95. package/dist/{config-Bu6pwqcO.js → config-BZWSFxkG.js} +3 -3
  96. package/dist/{config-MDRA2sre.js → config-DQP0IvDX.js} +1 -1
  97. package/dist/{context-D7jICqdN.d.ts → context-CderJRZf.d.ts} +1 -1
  98. package/dist/contract/index.d.ts +3 -3
  99. package/dist/{controller-DxtxeYdf.d.ts → controller-DaWA9eWS.d.ts} +1 -1
  100. package/dist/create/index.d.ts +3 -3
  101. package/dist/create/index.js +3 -3
  102. package/dist/create/lite/index.d.ts +3 -3
  103. package/dist/create/lite/index.js +2 -2
  104. package/dist/{entitlements-w04ivvAy.d.ts → entitlements-BefkpQIz.d.ts} +1 -1
  105. package/dist/{field-errors-DKCaSlZw.d.ts → field-errors-D1meOs_H.d.ts} +4 -4
  106. package/dist/{index-BvcMQYL-.d.ts → index-BQlLxOj5.d.ts} +1 -1
  107. package/dist/{index-DU0UwWvL.d.ts → index-BbDiBiKt.d.ts} +4 -4
  108. package/dist/{index-BZCmy767.d.ts → index-C13UgV67.d.ts} +2 -2
  109. package/dist/{index-BgkHbf9C.d.ts → index-ChLuLxy-.d.ts} +6 -6
  110. package/dist/{index-BdC2IqkU.d.ts → index-D9aV0Fvx.d.ts} +2 -2
  111. package/dist/{index-CbUXFzQV.d.ts → index-DXUiRyEk.d.ts} +1 -1
  112. package/dist/{index-CiE37wKX.d.ts → index-ZQZMQF4l.d.ts} +1 -1
  113. package/dist/{instances-D31jrmKh.js → instances-D9YrkoAy.js} +28 -1
  114. package/dist/mapper/bin.js +5 -5
  115. package/dist/mcp/index.d.ts +1 -1
  116. package/dist/next/index.d.ts +4 -4
  117. package/dist/{operations-CsCwruKT.d.ts → operations-t_hlXkS4.d.ts} +1 -1
  118. package/dist/{options-CgMiQGOF.js → options-C9bp3SEA.js} +2 -0
  119. package/dist/{options-B56njigZ.js → options-CjocPkX1.js} +2 -0
  120. package/dist/{options-Sq4bYbf5.js → options-CuaWhsQS.js} +2 -0
  121. package/dist/{options-DjFbIRgV.js → options-DjdxZgHi.js} +2 -1
  122. package/dist/{options-C-NFS6e3.js → options-DxgZ8tVc.js} +2 -1
  123. package/dist/otel/index.js +4 -4
  124. package/dist/{permissions-BP593xxk.d.ts → permissions-C8p6RlIZ.d.ts} +1 -1
  125. package/dist/{ports-BVLhLUvR.d.ts → ports-C-8uduFM.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-om2rbdYw.js → preset-B_sSI9vg.js} +2 -2
  130. package/dist/{project-D4ArwcS5.js → project-DVlXQGEp.js} +5 -5
  131. package/dist/{push-token-B0j171on.d.ts → push-token-D41lOoE8.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/{resolved-names-DYYyh35i.js → resolved-names-h-3UbKcw.js} +1 -1
  138. package/dist/server/index.d.ts +3 -3
  139. package/dist/solid/index.d.ts +5 -5
  140. package/dist/sql/index.d.ts +5 -5
  141. package/dist/sql/index.js +2 -2
  142. package/dist/{sql-DiUP7fKX.js → sql-C9nO-Mat.js} +493 -198
  143. package/dist/ssr/index.d.ts +1 -1
  144. package/dist/svelte/index.d.ts +5 -5
  145. package/dist/{tenant-B3IIq8Eq.d.ts → tenant-gezshhcs.d.ts} +1 -1
  146. package/dist/testing/index.d.ts +3 -3
  147. package/dist/testing/index.js +1 -1
  148. package/dist/{topic-D2MyBeaI.d.ts → topic-BVq5RdsI.d.ts} +1 -1
  149. package/dist/{types-BFEKRmEK.d.ts → types-hTj5OuFo.d.ts} +2 -2
  150. package/dist/vue/index.d.ts +5 -5
  151. package/dist/{watch-topic-q6krNw0T.d.ts → watch-topic-BOclyLFd.d.ts} +1 -1
  152. package/dist/yjs/index.d.ts +1 -1
  153. package/package.json +1 -1
  154. package/schemas/config-v1.json +41 -0
  155. package/dist/cli/add-BaOCKKt6.js +0 -1
  156. package/dist/cli/powersync-CmsXOuui.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 { n as resolveJsonSchema, r as CONFIG_DEFAULTS, t as resolveNames } from "./resolved-names-DYYyh35i.js";
6
+ import { n as resolveJsonSchema, r as CONFIG_DEFAULTS, t as resolveNames } from "./resolved-names-h-3UbKcw.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-D31jrmKh.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-D9YrkoAy.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-CgMiQGOF.js";
36
+ import { t as catalogSqlOptions } from "./options-C9bp3SEA.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";
@@ -45,12 +45,12 @@ import { t as coursesSqlOptions } from "./options--rohtkkC.js";
45
45
  import { t as createdBySqlOptions } from "./options-CcW7h8mv.js";
46
46
  import { t as customFieldsSqlOptions } from "./options-Bi96Lzuf.js";
47
47
  import { t as dataLifecycleSqlOptions } from "./options-BqK4xV67.js";
48
- import { t as dealsSqlOptions } from "./options-C-NFS6e3.js";
48
+ import { t as dealsSqlOptions } from "./options-DxgZ8tVc.js";
49
49
  import { n as WORK_ORDER_STATUSES, r as dispatchSqlOptions, t as WORK_ORDER_PRIORITIES } from "./statuses-Bv-0XoYC.js";
50
50
  import { t as documentsSqlOptions } from "./options-C4kpi6HE.js";
51
51
  import { t as domainsSqlOptions } from "./options-eLIedotm.js";
52
52
  import { t as donationsSqlOptions } from "./options-ompJjxkV.js";
53
- import { t as driveSqlOptions } from "./options-B56njigZ.js";
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
56
  import { t as expensesSqlOptions } from "./options-CuPWezcV.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-Sq4bYbf5.js";
65
+ import { t as invoicesSqlOptions } from "./options-CuaWhsQS.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-Bw5cX7oj.js";
91
+ import { n as QUOTE_TO_ORDER, r as quotesSqlOptions } from "./automations-D4QTP8nI.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";
@@ -113,7 +113,7 @@ import { t as tagsSqlOptions } from "./options-CyDOOWlk.js";
113
113
  import { t as tasksSqlOptions } from "./options-B7YrdiUc.js";
114
114
  import { t as teamsSqlOptions } from "./options-B8c2_hIB.js";
115
115
  import { t as templatesSqlOptions } from "./options-yRwYr4up.js";
116
- import { t as timeTrackingSqlOptions } from "./options-DjFbIRgV.js";
116
+ import { t as timeTrackingSqlOptions } from "./options-DjdxZgHi.js";
117
117
  import { t as trashSqlOptions } from "./options-B3xH2JvJ.js";
118
118
  import { t as updatedAtSqlOptions } from "./options-1iHDmlZ5.js";
119
119
  import { t as usageSqlOptions } from "./options-DiIlMZpc.js";
@@ -966,9 +966,9 @@ function registration(args) {
966
966
  };
967
967
  }
968
968
  const CALL$1 = /\bbetter_supabase\s*\.\s*(un)?audit\s*\(/gi;
969
- const IDENT$11 = String.raw`(?:"(?:[^"]|"")+"|[A-Za-z_][\w$]*)`;
970
- const TRIGGER$2 = /* @__PURE__ */ new RegExp(String.raw`\bcreate\s+(?:or\s+replace\s+)?trigger\s+"?bsb?_audit"?\s+after\s+[\s\S]*?\bon\s+(${IDENT$11}(?:\s*\.\s*${IDENT$11})?)\s+for\s+each\s+row\s+execute\s+(?:function|procedure)\s+better_supabase\s*\.\s*audit_row_change\s*\(`, "gi");
971
- const TABLE_NAME$5 = String.raw`${IDENT$11}(?:\s*\.\s*${IDENT$11})?`;
969
+ const IDENT$12 = String.raw`(?:"(?:[^"]|"")+"|[A-Za-z_][\w$]*)`;
970
+ const TRIGGER$2 = /* @__PURE__ */ new RegExp(String.raw`\bcreate\s+(?:or\s+replace\s+)?trigger\s+"?bsb?_audit"?\s+after\s+[\s\S]*?\bon\s+(${IDENT$12}(?:\s*\.\s*${IDENT$12})?)\s+for\s+each\s+row\s+execute\s+(?:function|procedure)\s+better_supabase\s*\.\s*audit_row_change\s*\(`, "gi");
971
+ const TABLE_NAME$5 = String.raw`${IDENT$12}(?:\s*\.\s*${IDENT$12})?`;
972
972
  const DROP = /* @__PURE__ */ new RegExp(String.raw`\bdrop\s+table\s+(?:if\s+exists\s+)?(${TABLE_NAME$5}(?:\s*,\s*${TABLE_NAME$5})*)`, "gi");
973
973
  const names$9 = (value) => Array.isArray(value) ? value.filter((item) => typeof item === "string") : [];
974
974
  function triggerRegistration(target, args) {
@@ -2057,9 +2057,9 @@ function rendersOwnInstance(block, layout) {
2057
2057
  function renamedInstances(block, layout) {
2058
2058
  return Object.values(layout.instances ?? {}).filter((instance) => instance.block === block && isRenamedInstance(instance));
2059
2059
  }
2060
- const IDENT$10 = String.raw`(?:"[^"]+"|[A-Za-z_][\w$]*)`;
2061
- const CREATED = new RegExp(String.raw`\bcreate\s+(?:or\s+replace\s+)?(?:unique\s+)?(?:function|procedure|index|type|sequence|view|materialized\s+view|table|trigger|event\s+trigger|aggregate|domain)\s+(?:concurrently\s+)?(?:if\s+not\s+exists\s+)?(?:${IDENT$10}\.)?(${IDENT$10})`, "gi");
2062
- const CONSTRAINT$1 = new RegExp(String.raw`\bconstraint\s+(${IDENT$10})`, "gi");
2060
+ const IDENT$11 = String.raw`(?:"[^"]+"|[A-Za-z_][\w$]*)`;
2061
+ const CREATED = new RegExp(String.raw`\bcreate\s+(?:or\s+replace\s+)?(?:unique\s+)?(?:function|procedure|index|type|sequence|view|materialized\s+view|table|trigger|event\s+trigger|aggregate|domain)\s+(?:concurrently\s+)?(?:if\s+not\s+exists\s+)?(?:${IDENT$11}\.)?(${IDENT$11})`, "gi");
2062
+ const CONSTRAINT$1 = new RegExp(String.raw`\bconstraint\s+(${IDENT$11})`, "gi");
2063
2063
  const unquote$3 = (name) => name.startsWith("\"") ? name.slice(1, -1) : name;
2064
2064
  /**
2065
2065
  * The functions, indexes, types, sequences, views, tables, triggers and
@@ -2617,7 +2617,7 @@ const FIXED_FUNCTIONS = { memberships: /* @__PURE__ */ new Set([
2617
2617
  "organization_member_role",
2618
2618
  "organization_member_roles"
2619
2619
  ]) };
2620
- const IDENT$9 = /^[A-Za-z_][A-Za-z0-9_$]*$/;
2620
+ const IDENT$10 = /^[A-Za-z_][A-Za-z0-9_$]*$/;
2621
2621
  function splitTable(value, schema) {
2622
2622
  const dot = value.indexOf(".");
2623
2623
  return dot === -1 ? {
@@ -2629,7 +2629,7 @@ function splitTable(value, schema) {
2629
2629
  };
2630
2630
  }
2631
2631
  function checkIdent(where, value) {
2632
- if (!IDENT$9.test(value) || value.length > 63) throw new TypeError(`${where}: "${value}" is not a valid identifier`);
2632
+ if (!IDENT$10.test(value) || value.length > 63) throw new TypeError(`${where}: "${value}" is not a valid identifier`);
2633
2633
  return value;
2634
2634
  }
2635
2635
  /**
@@ -3748,7 +3748,7 @@ grant execute on function ${fn}(${id}, uuid) to service_role;
3748
3748
  `;
3749
3749
  }
3750
3750
  // src/sql/modules/tenant-same.ts
3751
- const IDENT$8 = /^[a-z_][a-z0-9_$]{0,62}$/;
3751
+ const IDENT$9 = /^[a-z_][a-z0-9_$]{0,62}$/;
3752
3752
  const WHERE$13 = "blocks.memberships.options.sameTenant";
3753
3753
  /**
3754
3754
  * One entry per declared foreign key from a table with the tenant column to
@@ -3791,7 +3791,7 @@ function entriesOf(ctx, layout) {
3791
3791
  function parseEntries(value, fallback, where) {
3792
3792
  const ident = (at, name, otherwise) => {
3793
3793
  const resolved = name ?? otherwise;
3794
- if (typeof resolved !== "string" || !IDENT$8.test(resolved)) throw new TypeError(`${at} must be a lowercase column name`);
3794
+ if (typeof resolved !== "string" || !IDENT$9.test(resolved)) throw new TypeError(`${at} must be a lowercase column name`);
3795
3795
  return resolved;
3796
3796
  };
3797
3797
  return value.map((entry, index) => {
@@ -8376,6 +8376,69 @@ function rankSql(type) {
8376
8376
  pattern: RANK_KEY_PATTERN
8377
8377
  };
8378
8378
  }
8379
+ // src/sql/provider-rows.ts
8380
+ const RESOURCE = /^[a-z_][a-z0-9_]{0,62}$/;
8381
+ const isResourceName = (rows) => typeof rows === "string" && RESOURCE.test(rows);
8382
+ function providerRowCheck(ctx, where, rows, key) {
8383
+ const rowsWith = ctx.providerRowsWith;
8384
+ if (rowsWith === void 0) throw new TypeError(`${where}.rows needs blocks.permissions.model "provider" and an authorization provider with functions.rowsWith`);
8385
+ const forUser = ctx.providerRowsWithFor;
8386
+ const permission = sqlString(key);
8387
+ return (id, user) => {
8388
+ const ids = `array[${id}::text]`;
8389
+ const member = (set) => `${id}::text in (select r.id::text from ${set} as r(id))`;
8390
+ const own = member(fillTemplate("authorization.functions.rowsWith", rowsWith, {
8391
+ resource: rows,
8392
+ permission,
8393
+ ids
8394
+ }));
8395
+ if (forUser === void 0) return `(${user} = auth.uid() and ${own})`;
8396
+ return `(case when ${user} = auth.uid() then ${own} when ${user} is not null then ${member(fillTemplate("authorization.functions.rowsWithFor", forUser, {
8397
+ user,
8398
+ resource: rows,
8399
+ permission,
8400
+ ids
8401
+ }))} else false end)`;
8402
+ };
8403
+ }
8404
+ // src/sql/modules/drive-roles.ts
8405
+ const QUALIFIED$2 = /^[A-Za-z_][\w$]*\.[A-Za-z_][\w$]*$/;
8406
+ function providerRoles(ctx, all, at, rows, map) {
8407
+ if (!isResourceName(rows) || !isRecord$1(map) || Object.keys(map).length === 0 || !Object.entries(map).every(([role, key]) => all.includes(role) && typeof key === "string" && key !== "")) throw new TypeError(`${at} takes { rows, roles }: the provider's resource name and a permission key for each of options.roles it grants`);
8408
+ const checks = all.filter((role) => map[role] !== void 0).toReversed().map((role) => ({
8409
+ role,
8410
+ check: providerRowCheck(ctx, at, rows, String(map[role]))
8411
+ }));
8412
+ return {
8413
+ label: `the authorization provider's grants on ${rows}`,
8414
+ role: (id, user) => `case ${checks.map(({ role, check }) => `when ${check(id, user)} then ${sqlString(role)}`).join(" ")} end`
8415
+ };
8416
+ }
8417
+ /** `options.roleFunctions`: app functions that return the caller's role. */
8418
+ function driveRoleFunctions(ctx, all) {
8419
+ const where = "blocks.drive.options.roleFunctions";
8420
+ const raw = ctx.option("roleFunctions");
8421
+ if (raw === void 0) return {
8422
+ node: void 0,
8423
+ drive: void 0
8424
+ };
8425
+ if (!isRecord$1(raw)) throw new TypeError(`${where} takes { node, drive } function names or { rows, roles }`);
8426
+ const parse = (key) => {
8427
+ const value = raw[key];
8428
+ if (value === void 0) return;
8429
+ if (isRecord$1(value)) return providerRoles(ctx, all, `${where}.${key}`, value["rows"], value["roles"]);
8430
+ if (typeof value !== "string" || !QUALIFIED$2.test(value)) throw new TypeError(`${where}.${key} must be a schema-qualified function name, such as public.file_node_role, or { rows, roles }`);
8431
+ const fn = value.split(".").map(sqlIdent).join(".");
8432
+ return {
8433
+ label: fn,
8434
+ role: (id, user) => `${fn}(${id}, ${user})`
8435
+ };
8436
+ };
8437
+ return {
8438
+ node: parse("node"),
8439
+ drive: parse("drive")
8440
+ };
8441
+ }
8379
8442
  // src/sql/subject-write.ts
8380
8443
  /**
8381
8444
  * Whether the caller holds the `write` key a registered subject type names
@@ -9122,6 +9185,8 @@ const NAMES$113 = {
9122
9185
  "drives",
9123
9186
  "driveKinds",
9124
9187
  "sources",
9188
+ "roleFunctions",
9189
+ "readPolicy",
9125
9190
  "extraColumns"
9126
9191
  ],
9127
9192
  tables: {
@@ -9225,7 +9290,7 @@ const NAMES$113 = {
9225
9290
  },
9226
9291
  driveGrants: {
9227
9292
  name: "drive_drive_grants",
9228
- app: {},
9293
+ app: { unused: (ctx) => ctx.has("driveGrants", "principalType") ? ["user", "team"] : ["principalType", "principalId"] },
9229
9294
  optionalTable: true,
9230
9295
  lifecycle: {
9231
9296
  tenant: "tenant",
@@ -9237,12 +9302,21 @@ const NAMES$113 = {
9237
9302
  drive: "drive_id",
9238
9303
  principalType: "principal_type",
9239
9304
  principalId: "principal_id",
9305
+ user: "user_id",
9306
+ team: "team_id",
9240
9307
  role: "role",
9241
9308
  expiresAt: "expires_at",
9242
9309
  createdBy: "created_by",
9243
9310
  createdAt: "created_at"
9244
9311
  },
9245
- optional: ["expiresAt", "createdBy"]
9312
+ optional: [
9313
+ "principalType",
9314
+ "principalId",
9315
+ "user",
9316
+ "team",
9317
+ "expiresAt",
9318
+ "createdBy"
9319
+ ]
9246
9320
  },
9247
9321
  connections: {
9248
9322
  name: "drive_connections",
@@ -9373,12 +9447,20 @@ function driveKit(ctx, own) {
9373
9447
  const teamColumn = !typed && ctx.has("grants", "team");
9374
9448
  const expiring = ctx.has("grants", "expiresAt");
9375
9449
  const drives = ctx.flag("drives", false);
9376
- const driveColumn = has("drive");
9450
+ const driveColumn = has("drive") && (!ctx.owns("nodes") || drives);
9377
9451
  const sourceColumn = has("source");
9378
9452
  const externalColumn = has("externalId");
9379
9453
  const metadataColumn = has("externalMetadata");
9380
9454
  const holdColumn = has("legalHoldUntil");
9381
9455
  if (drives && !driveColumn) throw new TypeError("blocks.drive.options.drives needs blocks.drive.columns.nodes.drive");
9456
+ const driveTyped = drives && ctx.has("driveGrants", "principalType") && ctx.has("driveGrants", "principalId");
9457
+ const driveUserColumn = drives && ctx.has("driveGrants", "user");
9458
+ const driveTeamColumn = !driveTyped && driveUserColumn && ctx.has("driveGrants", "team");
9459
+ if (drives && !driveTyped && !driveUserColumn) throw new TypeError("blocks.drive.columns.driveGrants needs principalType and principalId, or user (and team)");
9460
+ const drivePrincipalTypes = driveTyped ? "('user', 'team', 'role')" : driveTeamColumn ? "('user', 'team')" : "('user')";
9461
+ const roleFunctions = driveRoleFunctions(ctx, driveRoles(ctx).all);
9462
+ if (roleFunctions.drive !== void 0 && !drives) throw new TypeError("blocks.drive.options.roleFunctions.drive needs blocks.drive.options.drives");
9463
+ const readPolicy = ctx.flag("readPolicy", true);
9382
9464
  if (externalColumn && !sourceColumn) throw new TypeError("blocks.drive.columns.nodes.externalId needs blocks.drive.columns.nodes.source");
9383
9465
  if (drives && (!ctx.hasTable("drives") || !ctx.hasTable("driveGrants") || !ctx.hasTable("connections") || !ctx.has("drives", "kind") || !ctx.has("drives", "owner") || !ctx.has("drives", "connection"))) throw new TypeError("blocks.drive.options.drives needs the drives, driveGrants and connections tables with kind, owner and connection columns");
9384
9466
  const driveKinds = ctx.list("driveKinds", ["shared"]);
@@ -9471,27 +9553,35 @@ function driveKit(ctx, own) {
9471
9553
  targetLabel: `${row}.${c("name")}`,
9472
9554
  summary: sqlString(summary)
9473
9555
  });
9556
+ const teamMember = (team, uid) => teams === void 0 ? "false" : `exists (select 1 from ${teams.table("members")} tm where tm.${teams.col("members", "team")}::text = ${team}::text and tm.${teams.col("members", "user")} = ${uid})`;
9474
9557
  const principalMatch = (grant, uid, tenantId) => {
9475
- const teamMember = (team) => teams === void 0 ? "false" : `exists (select 1 from ${teams.table("members")} tm where tm.${teams.col("members", "team")}::text = ${team}::text and tm.${teams.col("members", "user")} = ${uid})`;
9476
- if (!typed) return `(${grant}.${g("user")} = ${uid}${teamColumn ? ` or (${grant}.${g("team")} is not null and ${teamMember(`${grant}.${g("team")}`)})` : ""})`;
9558
+ if (!typed) return `(${grant}.${g("user")} = ${uid}${teamColumn ? ` or (${grant}.${g("team")} is not null and ${teamMember(`${grant}.${g("team")}`, uid)})` : ""})`;
9477
9559
  return `((${grant}.${g("principalType")} = 'user' and ${grant}.${g("principalId")} = ${uid}::text)
9478
- or (${grant}.${g("principalType")} = 'team' and ${teamMember(`${grant}.${g("principalId")}`)})
9560
+ or (${grant}.${g("principalType")} = 'team' and ${teamMember(`${grant}.${g("principalId")}`, uid)})
9479
9561
  or (${grant}.${g("principalType")} = 'role' and exists (select 1 from ${tenant.table("memberships")} mr where mr.${m("tenant")} = ${tenantId} and mr.${m("user")} = ${uid} and mr.${m("role")}::text = ${grant}.${g("principalId")}${activeMembership(ctx, "mr")})))`;
9480
9562
  };
9563
+ const drivePrincipalMatch = (grant, uid, tenantId) => {
9564
+ if (!driveTyped) return `(${grant}.${dg("user")} = ${uid}${driveTeamColumn ? ` or (${grant}.${dg("team")} is not null and ${teamMember(`${grant}.${dg("team")}`, uid)})` : ""})`;
9565
+ return `((${grant}.${dg("principalType")} = 'user' and ${grant}.${dg("principalId")} = ${uid}::text)
9566
+ or (${grant}.${dg("principalType")} = 'team' and ${teamMember(`${grant}.${dg("principalId")}`, uid)})
9567
+ or (${grant}.${dg("principalType")} = 'role' and exists (select 1 from ${tenant.table("memberships")} mr where mr.${m("tenant")} = ${tenantId} and mr.${m("user")} = ${uid} and mr.${m("role")}::text = ${grant}.${dg("principalId")}${activeMembership(ctx, "mr")})))`;
9568
+ };
9569
+ const drivePrincipalType = (grant) => driveTyped ? `${grant}.${dg("principalType")}` : driveTeamColumn ? `case when ${grant}.${dg("user")} is not null then 'user' else 'team' end` : "'user'";
9570
+ const drivePrincipalId = (grant) => driveTyped ? `${grant}.${dg("principalId")}` : driveTeamColumn ? `coalesce(${grant}.${dg("user")}::text, ${grant}.${dg("team")}::text)` : `${grant}.${dg("user")}::text`;
9481
9571
  const grantLive = (grant) => expiring ? ` and (${grant}.${g("expiresAt")} is null or ${grant}.${g("expiresAt")} > now())` : "";
9482
9572
  const driveExpiring = drives && ctx.has("driveGrants", "expiresAt");
9483
9573
  const driveGrantLive = (grant) => driveExpiring ? ` and (${grant}.${dg("expiresAt")} is null or ${grant}.${dg("expiresAt")} > now())` : "";
9484
9574
  const principalType = (grant) => typed ? `${grant}.${g("principalType")}` : teamColumn ? `case when ${grant}.${g("user")} is not null then 'user' else 'team' end` : "'user'";
9485
9575
  const principalId = (grant) => typed ? `${grant}.${g("principalId")}` : teamColumn ? `coalesce(${grant}.${g("user")}::text, ${grant}.${g("team")}::text)` : `${grant}.${g("user")}::text`;
9486
9576
  const fileJson = A === void 0 ? "" : `, 'attachmentId', ($1).${n("attachment")}, 'file', (select jsonb_build_object('mimeType', fa.${a("mimeType")}, 'size', fa.${a("size")}, 'status', fa.${a("status")}, 'uploadedAt', fa.${a("uploadedAt")}) from ${A} fa where fa.${a("id")} = ($1).${n("attachment")})`;
9487
- const nodeJson = (file) => `jsonb_build_object('id', ($1).${n("id")}, 'organizationId', ($1).${n("tenant")}, 'driveId', ${drives ? `($1).${n("drive")}` : "null"}, 'parentId', ($1).${n("parent")}, 'kind', ($1).${n("kind")}, 'name', ($1).${n("name")}, 'rank', ${ranked ? `($1).${n("rank")}` : "null"}, 'source', ${sourceColumn ? `($1).${n("source")}` : "null"}, 'externalId', ${externalColumn ? `($1).${n("externalId")}` : "null"}, 'externalMetadata', ${metadataColumn ? `($1).${n("externalMetadata")}` : "null"}, 'legalHoldUntil', ${holdColumn ? `($1).${n("legalHoldUntil")}` : "null"}, 'createdBy', ${has("createdBy") ? `($1).${n("createdBy")}` : "null"}, 'createdAt', ($1).${n("createdAt")}, 'updatedAt', ${has("updatedAt") ? `($1).${n("updatedAt")}` : "null"}, 'deletedAt', ${binColumn ? `($1).${n("deletedAt")}` : "null"}${file}${extras.length === 0 ? "" : `, 'fields', ${columnsObject("($1)", extras.map((column) => column.name))}`})`;
9577
+ const nodeJson = (file) => `jsonb_build_object('id', ($1).${n("id")}, 'organizationId', ($1).${n("tenant")}, 'driveId', ${driveColumn ? `($1).${n("drive")}` : "null"}, 'parentId', ($1).${n("parent")}, 'kind', ($1).${n("kind")}, 'name', ($1).${n("name")}, 'rank', ${ranked ? `($1).${n("rank")}` : "null"}, 'source', ${sourceColumn ? `($1).${n("source")}` : "null"}, 'externalId', ${externalColumn ? `($1).${n("externalId")}` : "null"}, 'externalMetadata', ${metadataColumn ? `($1).${n("externalMetadata")}` : "null"}, 'legalHoldUntil', ${holdColumn ? `($1).${n("legalHoldUntil")}` : "null"}, 'createdBy', ${has("createdBy") ? `($1).${n("createdBy")}` : "null"}, 'createdAt', ($1).${n("createdAt")}, 'updatedAt', ${has("updatedAt") ? `($1).${n("updatedAt")}` : "null"}, 'deletedAt', ${binColumn ? `($1).${n("deletedAt")}` : "null"}${file}${extras.length === 0 ? "" : `, 'fields', ${columnsObject("($1)", extras.map((column) => column.name))}`})`;
9488
9578
  const json = (row) => `${fn("drive_node_json")}(${row})`;
9489
9579
  const withRole = (row) => `(${json(row)} || jsonb_build_object('role', ${fn("drive_role")}((${row}).${n("id")}), 'readOnly', ${readOnly(`(${row})`)}, 'held', ${fn("drive_node_held")}((${row}).${n("id")})))`;
9490
9580
  const orderBy = (alias) => `(${alias}.${n("kind")} = 'folder') desc${ranked ? `, ${alias}.${n("rank")}` : ""}, lower(${alias}.${n("name")}), ${alias}.${n("id")}`;
9491
9581
  const touch = has("updatedAt") ? `, ${n("updatedAt")} = now()` : "";
9492
9582
  const insertColumns = [
9493
9583
  n("tenant"),
9494
- ...drives ? [n("drive")] : [],
9584
+ ...driveColumn ? [n("drive")] : [],
9495
9585
  n("parent"),
9496
9586
  n("kind"),
9497
9587
  n("name"),
@@ -9502,7 +9592,7 @@ function driveKit(ctx, own) {
9502
9592
  ];
9503
9593
  const insertValues = [
9504
9594
  "drive_insert_node.tenant",
9505
- ...drives ? [`coalesce(drive_insert_node.drive, v_parent.${n("drive")})`] : [],
9595
+ ...driveColumn ? ["v_drive"] : [],
9506
9596
  "drive_insert_node.parent",
9507
9597
  "drive_insert_node.kind",
9508
9598
  "v_name",
@@ -9517,8 +9607,8 @@ function driveKit(ctx, own) {
9517
9607
  insert into ${G} (${g("tenant")}, ${g("node")}, ${g("user")}, ${g("role")})
9518
9608
  values (${node}.${n("tenant")}, ${node}.${n("id")}, ${uid}, ${role});`;
9519
9609
  const siblings = (alias, tenantId, parent, drive) => {
9520
- if (drives && drive === void 0) throw new Error("a drive-wide name check needs the drive");
9521
- return `${alias}.${n("tenant")} = ${tenantId} and ${alias}.${n("parent")} is not distinct from ${parent}${drives ? ` and ${alias}.${n("drive")} = ${drive}` : ""}${live(alias)}`;
9610
+ if (driveColumn && drive === void 0) throw new Error("a drive-wide name check needs the drive");
9611
+ return `${alias}.${n("tenant")} = ${tenantId} and ${alias}.${n("parent")} is not distinct from ${parent}${driveColumn ? ` and ${alias}.${n("drive")} = ${drive}` : ""}${live(alias)}`;
9522
9612
  };
9523
9613
  return {
9524
9614
  ctx,
@@ -9555,6 +9645,16 @@ function driveKit(ctx, own) {
9555
9645
  dg,
9556
9646
  c,
9557
9647
  driveColumn,
9648
+ driveTyped,
9649
+ driveTeamColumn,
9650
+ driveUserColumn,
9651
+ drivePrincipalTypes,
9652
+ drivePrincipalMatch,
9653
+ drivePrincipalType,
9654
+ drivePrincipalId,
9655
+ nodeRole: roleFunctions.node,
9656
+ driveRole: roleFunctions.drive,
9657
+ readPolicy,
9558
9658
  sourceColumn,
9559
9659
  externalColumn,
9560
9660
  metadataColumn,
@@ -12378,12 +12478,12 @@ ${harness(ctx, names)}`;
12378
12478
  // src/sql/modules/usage-meters.ts
12379
12479
  const METER$1 = `'^[a-z][a-z0-9_.:-]{0,63}$'`;
12380
12480
  const METER_KEY$1 = /^[a-z][a-z0-9_.:-]{0,63}$/;
12381
- const IDENT$7 = /^[a-z_][a-z0-9_$]{0,62}$/;
12481
+ const IDENT$8 = /^[a-z_][a-z0-9_$]{0,62}$/;
12382
12482
  function meterTableOf(where, option) {
12383
12483
  const text = (name) => {
12384
12484
  const value = option[name];
12385
12485
  if (value === void 0) return;
12386
- if (typeof value !== "string" || !value.split(".").every((part) => IDENT$7.test(part))) throw new TypeError(`${where}.${name} must be a lowercase identifier`);
12486
+ if (typeof value !== "string" || !value.split(".").every((part) => IDENT$8.test(part))) throw new TypeError(`${where}.${name} must be a lowercase identifier`);
12387
12487
  return value;
12388
12488
  };
12389
12489
  for (const name of Object.keys(option)) if (![
@@ -26150,6 +26250,28 @@ ${userGrant(`${fn("time_is_my_employee")}(${ctx.idType}, uuid)`)}
26150
26250
  ` : ""
26151
26251
  };
26152
26252
  }
26253
+ const IDENT$7 = /^[a-z_][a-z0-9_$]*$/u;
26254
+ /**
26255
+ * `options.lockedColumns`: the entry columns a submitted or approved week
26256
+ * refuses to change, as logical names or the table's own column names. By
26257
+ * default the ones that change logged time: start, end or duration, subject,
26258
+ * owner and rate.
26259
+ */
26260
+ function lockedColumns(ctx, subjectColumns, employeeMode, logical) {
26261
+ const raw = ctx.option("lockedColumns");
26262
+ const e = (column) => ctx.col("entries", column);
26263
+ if (raw === void 0) return [.../* @__PURE__ */ new Set([
26264
+ e("startedAt"),
26265
+ ...durationEntries(ctx) ? [e("seconds"), e("runningSince")] : [e("endedAt")],
26266
+ ...subjectColumns,
26267
+ e("user"),
26268
+ ...employeeMode ? [e("employee")] : [],
26269
+ e("rate"),
26270
+ e("rateCurrency")
26271
+ ])];
26272
+ if (!Array.isArray(raw) || !raw.every((column) => typeof column === "string" && (logical.includes(column) && ctx.has("entries", column) || IDENT$7.test(column)))) throw new TypeError(`${WHERE$11}.lockedColumns takes entry columns: logical names such as startedAt, or the table's own column names`);
26273
+ return [...new Set(raw.map((column) => logical.includes(column) ? e(column) : sqlIdent(column)))];
26274
+ }
26153
26275
  // src/sql/modules/billable-time.ts
26154
26276
  const GROUPINGS = [
26155
26277
  "subject",
@@ -30069,35 +30191,19 @@ const BULK = {
30069
30191
  };
30070
30192
  // src/sql/modules/calendar-features.ts
30071
30193
  const QUALIFIED$1 = /^[A-Za-z_][\w$]*\.[A-Za-z_][\w$]*$/;
30072
- const RESOURCE = /^[a-z_][a-z0-9_]{0,62}$/;
30073
30194
  /**
30074
30195
  * `accessFunctions.read` or `write`: an app function `(calendar_id, user_id)`,
30075
30196
  * or `{ rows, key }`, the authorization provider's per-row grants of `key` on
30076
- * resource `rows`, through `rowsWithFor` (or `rowsWith` for the caller only).
30197
+ * resource `rows`, through `rowsWith` for the caller and `rowsWithFor` for
30198
+ * anyone else.
30077
30199
  */
30078
30200
  function appFunction(ctx, value, key) {
30079
30201
  const where = `blocks.calendar.options.accessFunctions.${key}`;
30080
30202
  if (value === void 0) return;
30081
30203
  if (isRecord$1(value)) {
30082
30204
  const { rows, key: permission } = value;
30083
- if (typeof rows !== "string" || !RESOURCE.test(rows) || typeof permission !== "string" || permission === "") throw new TypeError(`${where} takes { rows, key }: the provider's resource name and the permission key`);
30084
- if (ctx.providerRowsWith === void 0) throw new TypeError(`${where}.rows needs blocks.permissions.model "provider" and an authorization provider with functions.rowsWith`);
30085
- const forUser = ctx.providerRowsWithFor;
30086
- const rowsWith = ctx.providerRowsWith;
30087
- return (calendar, user) => {
30088
- const ids = `array[${calendar}::text]`;
30089
- const member = `${calendar}::text in (select r.id::text from ${forUser === void 0 ? fillTemplate(`authorization.functions.rowsWith`, rowsWith, {
30090
- resource: rows,
30091
- permission: sqlString(permission),
30092
- ids
30093
- }) : fillTemplate(`authorization.functions.rowsWithFor`, forUser, {
30094
- user,
30095
- resource: rows,
30096
- permission: sqlString(permission),
30097
- ids
30098
- })} as r(id))`;
30099
- return forUser === void 0 ? `(${user} = auth.uid() and ${member})` : `(${member})`;
30100
- };
30205
+ if (!isResourceName(rows) || typeof permission !== "string" || permission === "") throw new TypeError(`${where} takes { rows, key }: the provider's resource name and the permission key`);
30206
+ return providerRowCheck(ctx, where, rows, permission);
30101
30207
  }
30102
30208
  if (typeof value !== "string" || !QUALIFIED$1.test(value)) throw new TypeError(`${where} must be a schema-qualified function name, such as public.can_read_calendar, or { rows, key }`);
30103
30209
  const fn = value.split(".").map(sqlIdent).join(".");
@@ -30196,7 +30302,25 @@ function eventOwner(ctx) {
30196
30302
  return ctx.has("events", "createdBy") ? ctx.col("events", "createdBy") : void 0;
30197
30303
  }
30198
30304
  const accessCall = (ctx, calendar, action, user = "auth.uid()") => `${ctx.fn("calendar_access")}(${calendar}, ${user}, '${action}')`;
30305
+ const accessForCall = (ctx, calendar, user) => `${ctx.fn("calendar_access_for")}(${calendar}, ${user}, 'read')`;
30306
+ const eventAccessForCall = (ctx, event, user) => `${ctx.fn("calendar_event_access_for")}(${event}, ${user}, 'read')`;
30199
30307
  const eventAccessCall = (ctx, event, action, user = "auth.uid()") => `${ctx.fn("calendar_event_access")}(${event}, ${user}, '${action}')`;
30308
+ const internalGrant = (signature) => `revoke execute on function ${signature} from public, anon, authenticated;`;
30309
+ const callerOnly = (ctx, name, id) => `
30310
+ -- ${name}_for for the caller; another user's access is not theirs to see.
30311
+ create or replace function ${ctx.fn(name)}(${id} uuid, user_id uuid, action text)
30312
+ returns boolean
30313
+ language sql
30314
+ stable
30315
+ security definer
30316
+ set search_path = ''
30317
+ as $$
30318
+ select case
30319
+ when ${name}.user_id is distinct from auth.uid() and auth.role() is distinct from 'service_role' then false
30320
+ else ${ctx.fn(`${name}_for`)}(${name}.${id}, ${name}.user_id, ${name}.action)
30321
+ end
30322
+ $$;
30323
+ ${userGrant(`${ctx.fn(name)}(uuid, uuid, text)`)}`;
30200
30324
  function accessFunctions(ctx) {
30201
30325
  const features = calendarFeatures(ctx);
30202
30326
  if (!features.access) return "";
@@ -30208,25 +30332,27 @@ function accessFunctions(ctx) {
30208
30332
  const events = ctx.table("events");
30209
30333
  const k = (column) => `k.${ctx.col("calendars", column)}`;
30210
30334
  const e = (column) => `e.${ctx.col("events", column)}`;
30211
- const user = "calendar_access.user_id";
30335
+ const user = "calendar_access_for.user_id";
30212
30336
  const can = (key) => ctx.scope.canUser(user, "v_tenant", key);
30213
30337
  const grant = features.grants ? `
30214
30338
  select case when bool_or(${ctx.is("grants", "role", `g.${ctx.col("grants", "role")}`, ["editor"])}) then 'editor' else 'viewer' end
30215
30339
  into v_grant
30216
30340
  from ${ctx.table("grants")} g
30217
- where g.${ctx.col("grants", "calendar")} = calendar_access.calendar_id
30341
+ where g.${ctx.col("grants", "calendar")} = calendar_access_for.calendar_id
30218
30342
  and g.${ctx.col("grants", "user")} = ${user}
30219
30343
  having count(*) > 0;` : "";
30220
30344
  const custom = (fn, actions) => fn === void 0 ? "" : `
30221
- if calendar_access.action in (${actions}) then
30222
- return coalesce(${fn("calendar_access.calendar_id", user)}, false);
30345
+ if calendar_access_for.action in (${actions}) then
30346
+ return coalesce(${fn("calendar_access_for.calendar_id", user)}, false);
30223
30347
  end if;`;
30224
30348
  const owner = eventOwner(ctx);
30225
30349
  return `
30226
30350
  -- Whether user_id may read, write or manage a calendar, or see its private
30227
30351
  -- events: its owner may do all of it; an editor grant writes and sees private
30228
- -- events; on a shared calendar the tenant's keys decide.
30229
- create or replace function ${ctx.fn("calendar_access")}(calendar_id uuid, user_id uuid, action text)
30352
+ -- events; on a shared calendar the tenant's keys decide. It answers for any
30353
+ -- user, so only the block's own functions call it; calendar_access answers
30354
+ -- for the caller.
30355
+ create or replace function ${ctx.fn("calendar_access_for")}(calendar_id uuid, user_id uuid, action text)
30230
30356
  returns boolean
30231
30357
  language plpgsql
30232
30358
  stable
@@ -30246,14 +30372,14 @@ begin
30246
30372
  select ${k("tenant")}, ${ownedBy(ctx, "k.", user)}, ${privateCalendar(ctx, "k.")}
30247
30373
  into v_tenant, v_owner, v_private
30248
30374
  from ${calendars} k
30249
- where ${k("id")} = calendar_access.calendar_id;
30375
+ where ${k("id")} = calendar_access_for.calendar_id;
30250
30376
  if not found or not ${can(read)} then
30251
30377
  return false;
30252
30378
  end if;${custom(features.readFn, "'read'")}${custom(features.writeFn, "'write', 'manage', 'private'")}${custom(features.shareFn ?? features.writeFn, "'share'")}
30253
30379
  if v_owner then
30254
30380
  return true;
30255
30381
  end if;${grant}
30256
- return case calendar_access.action
30382
+ return case calendar_access_for.action
30257
30383
  when 'read' then not v_private or v_grant is not null
30258
30384
  when 'write' then coalesce(v_grant = 'editor', false) or (not v_private and ${can(write)})
30259
30385
  when 'manage' then not v_private and ${can(manage)}
@@ -30263,11 +30389,12 @@ begin
30263
30389
  end;
30264
30390
  end;
30265
30391
  $$;
30266
- ${userGrant(`${ctx.fn("calendar_access")}(uuid, uuid, text)`)}
30392
+ ${internalGrant(`${ctx.fn("calendar_access_for")}(uuid, uuid, text)`)}
30393
+ ${callerOnly(ctx, "calendar_access", "calendar_id")}
30267
30394
 
30268
30395
  -- Whether user_id may read or write one event: the calendar's access, and for
30269
30396
  -- a private event its owner or someone who sees the calendar's private events.
30270
- create or replace function ${ctx.fn("calendar_event_access")}(event_id uuid, user_id uuid, action text)
30397
+ create or replace function ${ctx.fn("calendar_event_access_for")}(event_id uuid, user_id uuid, action text)
30271
30398
  returns boolean
30272
30399
  language plpgsql
30273
30400
  stable
@@ -30280,20 +30407,21 @@ declare
30280
30407
  v_private boolean;
30281
30408
  v_mine boolean;
30282
30409
  begin
30283
- if calendar_event_access.user_id is null then
30410
+ if calendar_event_access_for.user_id is null then
30284
30411
  return auth.role() = 'service_role';
30285
30412
  end if;
30286
- select ${e("calendar")}, ${privateEvent(ctx, "e.")}, ${owner === void 0 ? "false" : `coalesce(e.${owner} = calendar_event_access.user_id, false)`}
30413
+ select ${e("calendar")}, ${privateEvent(ctx, "e.")}, ${owner === void 0 ? "false" : `coalesce(e.${owner} = calendar_event_access_for.user_id, false)`}
30287
30414
  into v_calendar, v_private, v_mine
30288
30415
  from ${events} e
30289
- where ${e("id")} = calendar_event_access.event_id;
30290
- if not found or not ${ctx.fn("calendar_access")}(v_calendar, calendar_event_access.user_id, case when calendar_event_access.action = 'write' then 'write' else 'read' end) then
30416
+ where ${e("id")} = calendar_event_access_for.event_id;
30417
+ if not found or not ${ctx.fn("calendar_access_for")}(v_calendar, calendar_event_access_for.user_id, case when calendar_event_access_for.action = 'write' then 'write' else 'read' end) then
30291
30418
  return false;
30292
30419
  end if;
30293
- return not v_private or v_mine or ${ctx.fn("calendar_access")}(v_calendar, calendar_event_access.user_id, 'private');
30420
+ return not v_private or v_mine or ${ctx.fn("calendar_access_for")}(v_calendar, calendar_event_access_for.user_id, 'private');
30294
30421
  end;
30295
30422
  $$;
30296
- ${userGrant(`${ctx.fn("calendar_event_access")}(uuid, uuid, text)`)}
30423
+ ${internalGrant(`${ctx.fn("calendar_event_access_for")}(uuid, uuid, text)`)}
30424
+ ${callerOnly(ctx, "calendar_event_access", "event_id")}
30297
30425
  `;
30298
30426
  }
30299
30427
  function grantsTable(ctx) {
@@ -31731,7 +31859,7 @@ function feedEvents(ctx, events, calendars, attendees, where, creator) {
31731
31859
  const e = (column) => `e.${ctx.col("events", column)}`;
31732
31860
  const k = (column) => `k.${ctx.col("calendars", column)}`;
31733
31861
  const owner = eventOwner(ctx);
31734
- const visible = feed.visibility === "public" ? `(not ${privateEvent(ctx, "e.")}${owner === void 0 ? "" : ` or e.${owner} = ${creator}`})` : features.access ? eventAccessCall(ctx, e("id"), "read", creator) : "true";
31862
+ const visible = feed.visibility === "public" ? `(not ${privateEvent(ctx, "e.")}${owner === void 0 ? "" : ` or e.${owner} = ${creator}`})` : features.access ? eventAccessForCall(ctx, e("id"), creator) : "true";
31735
31863
  const reminders = ctx.installed("reminders") && ctx.of("reminders").hasTable("reminders") ? (() => {
31736
31864
  const r = ctx.of("reminders");
31737
31865
  const c = (column) => `r.${r.col("reminders", column)}`;
@@ -31790,7 +31918,7 @@ begin
31790
31918
  return null;
31791
31919
  end if;
31792
31920
  v_calendar := v_subject::uuid;
31793
- if v_creator is null or not ${ctx.scope.canUser("v_creator", "v_tenant", read)}${features.access ? ` or not ${accessCall(ctx, "v_calendar", "read", "v_creator")}` : ""} then
31921
+ if v_creator is null or not ${ctx.scope.canUser("v_creator", "v_tenant", read)}${features.access ? ` or not ${accessForCall(ctx, "v_calendar", "v_creator")}` : ""} then
31794
31922
  return null;
31795
31923
  end if;
31796
31924
  ${touchShareLink(s, "v_link")}
@@ -31815,7 +31943,7 @@ function userFeed(ctx, events, calendars, attendees) {
31815
31943
  const l = (column) => `l.${s.col("links", column)}`;
31816
31944
  const k = (column) => `k.${ctx.col("calendars", column)}`;
31817
31945
  const read = ctx.permission("read", moduleOperations("calendar").read);
31818
- const readable = features.access ? accessCall(ctx, k("id"), "read", "v_user") : ctx.scope.canUser("v_user", k("tenant"), read);
31946
+ const readable = features.access ? accessForCall(ctx, k("id"), "v_user") : ctx.scope.canUser("v_user", k("tenant"), read);
31819
31947
  return `
31820
31948
  -- Every calendar the user a share link names can read, with their events, as
31821
31949
  -- one iCal feed. Open to anon: the token is the credential, and each fetch
@@ -33561,6 +33689,55 @@ const productExtras = (ctx) => ctx.extraColumns("products", [
33561
33689
  "status",
33562
33690
  "fields"
33563
33691
  ]);
33692
+ /** `options.variantExtraColumns`, which `save_variant` writes from `fields`. */
33693
+ const variantExtras = (ctx) => ctx.extraColumns("variants", [
33694
+ "id",
33695
+ "sku",
33696
+ "rank",
33697
+ "fields"
33698
+ ], "variantExtraColumns");
33699
+ /** `options.categoryExtraColumns`, which `save_category` writes from `fields`. */
33700
+ const categoryExtras = (ctx) => ctx.hasTable("categories") ? ctx.extraColumns("categories", [
33701
+ "id",
33702
+ "slug",
33703
+ "rank",
33704
+ "fields"
33705
+ ], "categoryExtraColumns") : [];
33706
+ /**
33707
+ * The product columns `save_product` sets: without a prices table, the
33708
+ * product's price in minor units and its currency, and whether inventory counts
33709
+ * stock when variants don't say. Each is a parameter with a null default that
33710
+ * leaves the column as it is.
33711
+ */
33712
+ function productSettings(ctx) {
33713
+ const onVariant = !ctx.hasTable("prices");
33714
+ return [
33715
+ [
33716
+ "price",
33717
+ "price",
33718
+ "bigint",
33719
+ onVariant
33720
+ ],
33721
+ [
33722
+ "currency",
33723
+ "currency",
33724
+ "text",
33725
+ onVariant
33726
+ ],
33727
+ [
33728
+ "trackInventory",
33729
+ "track_inventory",
33730
+ "boolean",
33731
+ !ctx.has("variants", "trackInventory")
33732
+ ]
33733
+ ].filter(([logical, , , used]) => used && ctx.has("products", logical)).map(([logical, param, type]) => [
33734
+ logical,
33735
+ param,
33736
+ type
33737
+ ]);
33738
+ }
33739
+ /** `save_product`'s argument types after `kind`, without the extra fields. */
33740
+ const productSettingTypes = (ctx) => productSettings(ctx).map(([, , type]) => type);
33564
33741
  function storefrontOption(ctx) {
33565
33742
  const value = ctx.text("storefront", "private");
33566
33743
  if (value !== "public" && value !== "private") throw new TypeError("blocks.catalog.options.storefront must be \"public\" or \"private\"");
@@ -33608,7 +33785,16 @@ function productFunctions(ctx, names) {
33608
33785
  const kind = ctx.has("products", "kind");
33609
33786
  const governed = machineGoverns$1(ctx);
33610
33787
  const extras = productExtras(ctx);
33611
- const saveArgs = `${ctx.idType}, uuid, text, text, text, text`;
33788
+ const settings = productSettings(ctx);
33789
+ const baseArgs = `${ctx.idType}, uuid, text, text, text, text`;
33790
+ const saveArgs = [baseArgs, ...productSettingTypes(ctx)].join(", ");
33791
+ const settingParams = settings.map(([, param, type]) => `, ${param} ${type} default null`).join("");
33792
+ const settingWrite = settings.length === 0 ? "" : `
33793
+ update ${products} x set ${settings.map(([logical, param]) => `${p(logical)} = coalesce(${logical === "currency" ? `upper(save_product.${param})` : `save_product.${param}`}, x.${p(logical)})`).join(", ")}
33794
+ where x.${p("id")} = v_id;`;
33795
+ const staleDrops = settings.length === 0 ? "" : `drop function if exists ${fn("save_product")}(${baseArgs});
33796
+ drop function if exists ${fn("save_product")}(${baseArgs}, jsonb);
33797
+ `;
33612
33798
  const edges = Object.entries(STATUS_EDGES).map(([from, to]) => ` when ${sqlString(from)} then set_product_status.status = any (${sqlString(`{${to.join(",")}}`)}::text[])`).join("\n");
33613
33799
  const inventory = ctx.installed("inventory") ? ctx.of("inventory") : void 0;
33614
33800
  const historyCheck = (variantFilter, code) => inventory === void 0 ? "" : `
@@ -33616,9 +33802,10 @@ function productFunctions(ctx, names) {
33616
33802
  ${fail$1(code, "the stock ledger has movements for this record; archive it instead", "23503")}
33617
33803
  end if;`;
33618
33804
  return `
33619
- -- Creates a product (product null) or updates one. Returns its id, slug and status.
33620
- ${extraFieldsArg(extras).drop(fn("save_product"), saveArgs)}
33621
- create or replace function ${fn("save_product")}(tenant ${ctx.idType}, product uuid, title text, slug text, description text, kind text${extraFieldsArg(extras).param})
33805
+ -- Creates a product (product null) or updates one. Returns its id, slug and
33806
+ -- status.${settings.length === 0 ? "" : " A null price, currency or track_inventory keeps the column."}
33807
+ ${staleDrops}${extraFieldsArg(extras).drop(fn("save_product"), saveArgs)}
33808
+ create or replace function ${fn("save_product")}(tenant ${ctx.idType}, product uuid, title text, slug text, description text, kind text${settingParams}${extraFieldsArg(extras).param})
33622
33809
  returns jsonb
33623
33810
  language plpgsql
33624
33811
  security definer
@@ -33656,7 +33843,7 @@ begin
33656
33843
  end if;
33657
33844
  exception when unique_violation then
33658
33845
  ${fail$1("CATALOG_SLUG_TAKEN", "another product has this slug", "23505")}
33659
- end;${writeExtraColumns(products, extras, "save_product.fields", `x.${p("id")} = v_id`)}
33846
+ end;${settingWrite}${writeExtraColumns(products, extras, "save_product.fields", `x.${p("id")} = v_id`)}
33660
33847
  if v_created then
33661
33848
  ${ctx.record({
33662
33849
  type: "product.created",
@@ -33865,6 +34052,10 @@ function variantFunctions(ctx, names, historyCheck) {
33865
34052
  const p = (column) => ctx.col("products", column);
33866
34053
  const v = (column) => ctx.col("variants", column);
33867
34054
  const optional = (column) => ctx.has("variants", column);
34055
+ const extras = variantExtras(ctx);
34056
+ const extraArg = extraFieldsArg(extras);
34057
+ const variantArgs = "uuid, uuid, text, uuid[], text, text, integer, boolean, boolean";
34058
+ const inserted = insertExtraColumns(variants, extras, "coalesce(save_variant.fields, '{}'::jsonb)");
33868
34059
  const tracking = optional("trackInventory") ? "" : `
33869
34060
  if save_variant.track_inventory is not null then
33870
34061
  ${fail$1("CATALOG_TRACK_INVENTORY_UNSUPPORTED", "this catalog tracks inventory per product, not per variant", "22023")}
@@ -33925,7 +34116,9 @@ function variantFunctions(ctx, names, historyCheck) {
33925
34116
  return `
33926
34117
  -- Creates a variant (variant null) or updates one. option_values holds one
33927
34118
  -- option value id per product option; no two variants share a combination.
33928
- create or replace function ${fn("save_variant")}(product uuid, variant uuid, sku text, option_values uuid[], title text, barcode text, weight_grams integer, track_inventory boolean, allow_backorder boolean)
34119
+ -- fields: the extra columns (options.variantExtraColumns) to set.
34120
+ ${extraArg.drop(fn("save_variant"), variantArgs)}
34121
+ create or replace function ${fn("save_variant")}(product uuid, variant uuid, sku text, option_values uuid[], title text, barcode text, weight_grams integer, track_inventory boolean, allow_backorder boolean${extraArg.param})
33929
34122
  returns jsonb
33930
34123
  language plpgsql
33931
34124
  security definer
@@ -33955,8 +34148,8 @@ ${valueChecks.check}
33955
34148
  if v_created then
33956
34149
  select max(${rank.order(`x.${v("rank")}`)}) into v_last from ${variants} x where x.${v("product")} = save_variant.product;
33957
34150
  v_rank := ${rank.after("v_last")};
33958
- insert into ${variants} (${v("tenant")}, ${v("product")}, ${columns.map(([column]) => v(column)).join(", ")}, ${v("rank")})
33959
- values (v_tenant, save_variant.product, ${columns.map(([, value]) => value).join(", ")}, ${rank.write("v_rank")})
34151
+ insert into ${variants} (${v("tenant")}, ${v("product")}, ${columns.map(([column]) => v(column)).join(", ")}, ${v("rank")}${inserted.columns})
34152
+ values (v_tenant, save_variant.product, ${columns.map(([, value]) => value).join(", ")}, ${rank.write("v_rank")}${inserted.values})
33960
34153
  returning ${v("id")} into v_id;
33961
34154
  else
33962
34155
  update ${variants} x set ${columns.map(([column, value]) => `${v(column)} = ${value}`).join(", ")}, ${v("updatedAt")} = now()
@@ -33964,7 +34157,7 @@ ${valueChecks.check}
33964
34157
  returning x.${v("rank")} into v_rank;
33965
34158
  if not found then
33966
34159
  ${fail$1("CATALOG_VARIANT_NOT_FOUND", "variant not found", "P0002")}
33967
- end if;
34160
+ end if;${writeExtraColumns(variants, extras, "save_variant.fields", `x.${v("id")} = v_id`).replaceAll("\n ", "\n ")}
33968
34161
  end if;
33969
34162
  exception when unique_violation then
33970
34163
  ${fail$1("CATALOG_SKU_TAKEN", "another variant has this SKU", "23505")}
@@ -33988,10 +34181,10 @@ ${valueChecks.write}
33988
34181
  })}
33989
34182
  end if;
33990
34183
  ${ctx.hook("after_variant_save", [["uuid", "v_id"], ["boolean", "v_created"]])}
33991
- return jsonb_build_object('id', v_id, 'sku', save_variant.sku, 'rank', v_rank);
34184
+ return jsonb_build_object('id', v_id, 'sku', save_variant.sku, 'rank', v_rank)${extras.length === 0 ? "" : ` || (select jsonb_build_object('fields', ${columnsObject("x", extras.map((extra) => extra.name))}) from ${variants} x where x.${v("id")} = v_id)`};
33992
34185
  end;
33993
34186
  $$;
33994
- ${userGrant(`${fn("save_variant")}(uuid, uuid, text, uuid[], text, text, integer, boolean, boolean)`)}
34187
+ ${userGrant(`${fn("save_variant")}(${variantArgs}${extraArg.type})`)}
33995
34188
 
33996
34189
  -- Sets a variant's rank key among the product's variants.
33997
34190
  create or replace function ${fn("rank_variant")}(variant uuid, rank text)
@@ -35197,10 +35390,16 @@ ${userGrant(`${fn("set_product_categories")}(uuid, uuid[])`)}
35197
35390
  ) then
35198
35391
  ${fail$1("CATALOG_CATEGORY_CYCLE", "a category can't sit under itself", "22023")}
35199
35392
  end if;`;
35393
+ const extras = categoryExtras(ctx);
35394
+ const extraArg = extraFieldsArg(extras);
35395
+ const categoryArgs = `${ctx.idType}, uuid, uuid, text, text, text`;
35396
+ const inserted = insertExtraColumns(categories, extras, "coalesce(save_category.fields, '{}'::jsonb)");
35200
35397
  return `
35201
35398
  -- Creates a category (category null) or updates one, under parent (null
35202
- -- for the top level). A new category goes after its siblings.
35203
- create or replace function ${fn("save_category")}(tenant ${ctx.idType}, category uuid, parent uuid, name text, slug text, description text)
35399
+ -- for the top level). A new category goes after its siblings. fields: the
35400
+ -- extra columns (options.categoryExtraColumns) to set.
35401
+ ${extraArg.drop(fn("save_category"), categoryArgs)}
35402
+ create or replace function ${fn("save_category")}(tenant ${ctx.idType}, category uuid, parent uuid, name text, slug text, description text${extraArg.param})
35204
35403
  returns jsonb
35205
35404
  language plpgsql
35206
35405
  security definer
@@ -35225,8 +35424,8 @@ begin
35225
35424
  select max(${rank.order(`x.${k("rank")}`)}) into v_last from ${categories} x
35226
35425
  where x.${k("tenant")} = save_category.tenant and x.${k("parent")} is not distinct from save_category.parent;
35227
35426
  v_rank := ${rank.after("v_last")};
35228
- insert into ${categories} (${k("tenant")}, ${k("parent")}, ${k("name")}, ${k("slug")}, ${k("description")}, ${k("rank")})
35229
- values (save_category.tenant, save_category.parent, save_category.name, v_slug, save_category.description, ${rank.write("v_rank")})
35427
+ insert into ${categories} (${k("tenant")}, ${k("parent")}, ${k("name")}, ${k("slug")}, ${k("description")}, ${k("rank")}${inserted.columns})
35428
+ values (save_category.tenant, save_category.parent, save_category.name, v_slug, save_category.description, ${rank.write("v_rank")}${inserted.values})
35230
35429
  returning ${k("id")} into v_id;
35231
35430
  else
35232
35431
  update ${categories} x set ${k("parent")} = save_category.parent, ${k("name")} = save_category.name, ${k("slug")} = v_slug,
@@ -35235,15 +35434,15 @@ begin
35235
35434
  returning x.${k("rank")} into v_rank;
35236
35435
  if not found then
35237
35436
  ${fail$1("CATALOG_CATEGORY_NOT_FOUND", "category not found", "P0002")}
35238
- end if;
35437
+ end if;${writeExtraColumns(categories, extras, "save_category.fields", `x.${k("id")} = v_id`)}
35239
35438
  end if;
35240
35439
  exception when unique_violation then
35241
35440
  ${fail$1("CATALOG_SLUG_TAKEN", "another category has this slug", "23505")}
35242
35441
  end;
35243
- return jsonb_build_object('id', v_id, 'slug', v_slug, 'rank', v_rank);
35442
+ 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)`};
35244
35443
  end;
35245
35444
  $$;
35246
- ${userGrant(`${fn("save_category")}(${ctx.idType}, uuid, uuid, text, text, text)`)}
35445
+ ${userGrant(`${fn("save_category")}(${categoryArgs}${extraArg.type})`)}
35247
35446
 
35248
35447
  -- Moves a category under parent (null for the top level) at rank, a key
35249
35448
  -- from rankBetween over its new siblings' keys.
@@ -35660,6 +35859,8 @@ const NAMES$94 = {
35660
35859
  options: [
35661
35860
  "storefront",
35662
35861
  "extraColumns",
35862
+ "variantExtraColumns",
35863
+ "categoryExtraColumns",
35663
35864
  "locales",
35664
35865
  "rankType"
35665
35866
  ],
@@ -36016,7 +36217,7 @@ create table if not exists ${t("variants")} (
36016
36217
  ${c("variants", "updatedAt")} timestamptz not null default now(),
36017
36218
  unique (${c("variants", "tenant")}, ${c("variants", "sku")})
36018
36219
  );
36019
- create index if not exists ${ctx.naming.rename("product_variants_product_idx")} on ${t("variants")} (${c("variants", "product")});
36220
+ create index if not exists ${ctx.naming.rename("product_variants_product_idx")} on ${t("variants")} (${c("variants", "product")});${addExtraColumns(t("variants"), variantExtras(ctx))}
36020
36221
  ${lockTable(t("variants"), { read: true })}
36021
36222
  ${read("variants")}
36022
36223
 
@@ -36071,7 +36272,7 @@ create table if not exists ${t("categories")} (
36071
36272
  ${c("categories", "updatedAt")} timestamptz not null default now(),
36072
36273
  unique (${c("categories", "tenant")}, ${c("categories", "slug")})
36073
36274
  );
36074
- create index if not exists ${ctx.naming.rename("categories_parent_idx")} on ${t("categories")} (${c("categories", "parent")});
36275
+ create index if not exists ${ctx.naming.rename("categories_parent_idx")} on ${t("categories")} (${c("categories", "parent")});${addExtraColumns(t("categories"), categoryExtras(ctx))}
36075
36276
  ${lockTable(t("categories"), { read: true })}
36076
36277
  ${read("categories")}
36077
36278
 
@@ -36195,6 +36396,7 @@ function contract$86(ctx) {
36195
36396
  "text",
36196
36397
  "text",
36197
36398
  "text",
36399
+ ...productSettingTypes(ctx),
36198
36400
  ...extraFieldsArg(productExtras(ctx)).contract
36199
36401
  ],
36200
36402
  returns: "jsonb"
@@ -36234,7 +36436,8 @@ function contract$86(ctx) {
36234
36436
  "text",
36235
36437
  "integer",
36236
36438
  "boolean",
36237
- "boolean"
36439
+ "boolean",
36440
+ ...extraFieldsArg(variantExtras(ctx)).contract
36238
36441
  ],
36239
36442
  returns: "jsonb"
36240
36443
  },
@@ -36299,7 +36502,8 @@ function contract$86(ctx) {
36299
36502
  "uuid",
36300
36503
  "text",
36301
36504
  "text",
36302
- "text"
36505
+ "text",
36506
+ ...extraFieldsArg(categoryExtras(ctx)).contract
36303
36507
  ],
36304
36508
  returns: "jsonb"
36305
36509
  },
@@ -49975,7 +50179,20 @@ function lineTableSpec(name) {
49975
50179
  * gives when the app's table lacks it.
49976
50180
  */
49977
50181
  function lineColumn(ctx, lines, alias, column) {
49978
- return ctx.has(lines, column) ? `${alias}.${ctx.col(lines, column)}` : LINE_DEFAULTS[column] ?? "null";
50182
+ if (!ctx.has(lines, column)) return LINE_DEFAULTS[column] ?? "null";
50183
+ return RATE_COLUMNS.has(column) && percentRates(ctx, lines) ? `round(${alias}.${ctx.col(lines, column)} * 100)::integer` : `${alias}.${ctx.col(lines, column)}`;
50184
+ }
50185
+ const RATE_COLUMNS = /* @__PURE__ */ new Set(["discountBps", "taxRateBps"]);
50186
+ /**
50187
+ * `options.lineRates: "percent"`: the app's line table keeps discount and tax
50188
+ * rates as percentages, such as `numeric(5, 2)`, which the block reads and
50189
+ * writes as basis points.
50190
+ */
50191
+ function percentRates(ctx, lines) {
50192
+ const raw = ctx.option("lineRates") ?? "bps";
50193
+ if (raw !== "bps" && raw !== "percent") throw new TypeError(`blocks.${ctx.module}.options.lineRates must be "bps" or "percent"`);
50194
+ if (raw === "percent" && ctx.owns(lines)) throw new TypeError(`blocks.${ctx.module}.options.lineRates: "percent" needs your own line table, mapped in tables.${lines}`);
50195
+ return raw === "percent";
49979
50196
  }
49980
50197
  /** The columns a copy of lines writes, of the ones line table `lines` has. */
49981
50198
  function lineCopyColumns(ctx, lines) {
@@ -50037,7 +50254,7 @@ function lineItemsSql(ctx, items, options) {
50037
50254
  ["taxRateBps", "coalesce((x.value ->> 'taxRateBps')::integer, 0)"],
50038
50255
  ["taxCode", "x.value ->> 'taxCode'"],
50039
50256
  ["position", "x.ordinality::integer"]
50040
- ].filter(([column]) => has(column)).map(([column, value]) => [column, column === "productType" ? ctx.cast(items.lines, column, value) : value]);
50257
+ ].filter(([column]) => has(column)).map(([column, value]) => [column, column === "productType" ? ctx.cast(items.lines, column, value) : RATE_COLUMNS.has(column) && percentRates(ctx, items.lines) ? `(${value} / 100.0)` : value]);
50041
50258
  const extras = items.extras ?? [];
50042
50259
  const extrasInsert = insertExtraColumns(t, extras, "(case when jsonb_typeof(x.value -> 'fields') = 'object' then x.value -> 'fields' end)");
50043
50260
  const manages = ctx.manages ? `create table if not exists ${t} (
@@ -51121,7 +51338,8 @@ const NAMES$81 = {
51121
51338
  "prefix",
51122
51339
  "readAll",
51123
51340
  "extraColumns",
51124
- "lineExtraColumns"
51341
+ "lineExtraColumns",
51342
+ "lineRates"
51125
51343
  ],
51126
51344
  tables: {
51127
51345
  deals: {
@@ -56102,9 +56320,12 @@ const DONATIONS = {
56102
56320
  // src/sql/modules/drive-drives.ts
56103
56321
  /** The drives, their sharing and their external connections. */
56104
56322
  function driveDrivesSql(kit) {
56105
- const { ctx, T, n, fn, read, create, manage, roles, typed, teamColumn, drives, driveKinds, driveKindsArray, sources, sourcesArray, D, DG, C, d, dg, c, has, binColumn, sourceColumn, externalColumn, metadataColumn, driveHeld, connectionJson, withDriveRole, driveExpiring, driveGrantLive, driveAudit, connectionAudit, recordDrive, recordConnection, teams, tenant, m, rank, forbidden, touch } = kit;
56106
- const principalTypes = typed ? "('user', 'team', 'role')" : teamColumn ? "('user', 'team')" : "('user')";
56107
- const teamExistsDrive = teams === void 0 ? "false" : `exists (select 1 from ${teams.table("teams")} t where t.${teams.col("teams", "id")}::text = drive_share_drive.principal_id and t.${teams.col("teams", "tenant")} = v_drive.${d("tenant")})`;
56323
+ const { ctx, T, n, fn, read, create, manage, roles, driveTyped, driveTeamColumn, drivePrincipalTypes, drivePrincipalType, drivePrincipalId, drives, driveKinds, driveKindsArray, sources, sourcesArray, D, DG, C, d, dg, c, has, binColumn, sourceColumn, externalColumn, metadataColumn, driveHeld, connectionJson, withDriveRole, driveExpiring, driveGrantLive, driveAudit, connectionAudit, recordDrive, recordConnection, teams, tenant, m, rank, forbidden, touch } = kit;
56324
+ const teamExistsDrive = !drives || teams === void 0 ? "false" : `exists (select 1 from ${teams.table("teams")} t where t.${teams.col("teams", "id")}::text = drive_share_drive.principal_id and t.${teams.col("teams", "tenant")} = v_drive.${d("tenant")})`;
56325
+ const driveTeamValue = drives && driveTeamColumn ? teams === void 0 ? "null" : `case when v_type = 'team' then (select t.${teams.col("teams", "id")} from ${teams.table("teams")} t where t.${teams.col("teams", "id")}::text = drive_share_drive.principal_id and t.${teams.col("teams", "tenant")} = v_drive.${d("tenant")}) end` : void 0;
56326
+ const driveGrantColumns = drives ? driveTyped ? `${dg("tenant")}, ${dg("drive")}, ${dg("principalType")}, ${dg("principalId")}, ${dg("role")}${driveExpiring ? `, ${dg("expiresAt")}` : ""}${ctx.has("driveGrants", "createdBy") ? `, ${dg("createdBy")}` : ""}` : `${dg("tenant")}, ${dg("drive")}, ${dg("user")}${driveTeamColumn ? `, ${dg("team")}` : ""}, ${dg("role")}${driveExpiring ? `, ${dg("expiresAt")}` : ""}${ctx.has("driveGrants", "createdBy") ? `, ${dg("createdBy")}` : ""}` : "";
56327
+ const driveGrantValues = drives ? driveTyped ? `v_drive.${d("tenant")}, v_drive.${d("id")}, v_type, drive_share_drive.principal_id, drive_share_drive.role${driveExpiring ? ", drive_share_drive.expires_at" : ""}${ctx.has("driveGrants", "createdBy") ? ", auth.uid()" : ""}` : `v_drive.${d("tenant")}, v_drive.${d("id")}, case when v_type = 'user' then drive_share_drive.principal_id::uuid end${driveTeamColumn ? `, ${driveTeamValue}` : ""}, drive_share_drive.role${driveExpiring ? ", drive_share_drive.expires_at" : ""}${ctx.has("driveGrants", "createdBy") ? ", auth.uid()" : ""}` : "";
56328
+ const principalError = drives ? driveTyped ? "principal_type must be user, team or role" : driveTeamColumn ? "principal_type must be user or team" : "principal_type must be user" : "";
56108
56329
  return drives ? `
56109
56330
  -- The drives of an organization, with the caller's role on each.
56110
56331
  create or replace function ${fn("drive_create_drive")}(tenant ${ctx.idType}, name text, kind text default null, owner uuid default null, connection uuid default null)
@@ -56303,8 +56524,8 @@ begin
56303
56524
  if ${rank("drive_share_drive.role")} = 0 then
56304
56525
  ${fail$1("DRIVE_ROLE_UNKNOWN", `role must be one of ${roles.all.join(", ")}`, "22023")}
56305
56526
  end if;
56306
- if v_type not in ${principalTypes} or drive_share_drive.principal_id is null then
56307
- ${fail$1("DRIVE_PRINCIPAL_INVALID", "principal_type must be user, team or role", "22023")}
56527
+ if v_type not in ${drivePrincipalTypes} or drive_share_drive.principal_id is null then
56528
+ ${fail$1("DRIVE_PRINCIPAL_INVALID", principalError, "22023")}
56308
56529
  end if;
56309
56530
  if (v_type = 'user' and (drive_share_drive.principal_id !~ ${UUID_TEXT$1} or not exists (
56310
56531
  select 1 from ${tenant.table("memberships")} mu
@@ -56314,9 +56535,9 @@ begin
56314
56535
  ${fail$1("DRIVE_PRINCIPAL_NOT_FOUND", "no member or team of this organization has that id", "P0002")}
56315
56536
  end if;
56316
56537
  delete from ${DG} dg where dg.${dg("drive")} = v_drive.${d("id")}
56317
- and dg.${dg("principalType")} = v_type and dg.${dg("principalId")} = drive_share_drive.principal_id;
56318
- insert into ${DG} (${dg("tenant")}, ${dg("drive")}, ${dg("principalType")}, ${dg("principalId")}, ${dg("role")}${driveExpiring ? `, ${dg("expiresAt")}` : ""}${ctx.has("driveGrants", "createdBy") ? `, ${dg("createdBy")}` : ""})
56319
- values (v_drive.${d("tenant")}, v_drive.${d("id")}, v_type, drive_share_drive.principal_id, drive_share_drive.role${driveExpiring ? ", drive_share_drive.expires_at" : ""}${ctx.has("driveGrants", "createdBy") ? ", auth.uid()" : ""})
56538
+ and ${drivePrincipalType("dg")} = v_type and ${drivePrincipalId("dg")} = drive_share_drive.principal_id;
56539
+ insert into ${DG} (${driveGrantColumns})
56540
+ values (${driveGrantValues})
56320
56541
  returning ${dg("id")} into v_id;
56321
56542
  ${recordDrive("drive.shared", "v_drive", ", 'principalType', v_type, 'principalId', drive_share_drive.principal_id, 'role', drive_share_drive.role", driveAudit("v_drive", "shared"))}
56322
56543
  return jsonb_build_object('id', v_id, 'driveId', v_drive.${d("id")}, 'principalType', v_type, 'principalId', drive_share_drive.principal_id, 'role', drive_share_drive.role, 'expiresAt', drive_share_drive.expires_at);
@@ -56344,7 +56565,7 @@ begin
56344
56565
  end if;
56345
56566
  ${READ_ONLY_GUARD}
56346
56567
  delete from ${DG} dg where dg.${dg("drive")} = v_drive.${d("id")}
56347
- and dg.${dg("principalType")} = v_type and dg.${dg("principalId")} = drive_unshare_drive.principal_id;
56568
+ and ${drivePrincipalType("dg")} = v_type and ${drivePrincipalId("dg")} = drive_unshare_drive.principal_id;
56348
56569
  if not found then
56349
56570
  return false;
56350
56571
  end if;
@@ -56367,7 +56588,7 @@ begin
56367
56588
  ${fail$1("DRIVE_NOT_FOUND", "drive not found", "P0002")}
56368
56589
  end if;
56369
56590
  return (
56370
- select coalesce(jsonb_agg(jsonb_build_object('id', dg.${dg("id")}, 'driveId', dg.${dg("drive")}, 'principalType', dg.${dg("principalType")}, 'principalId', dg.${dg("principalId")}, 'role', dg.${dg("role")}, 'expiresAt', ${driveExpiring ? `dg.${dg("expiresAt")}` : "null"}) order by ${rank(`dg.${dg("role")}`)} desc, dg.${dg("id")}), '[]'::jsonb)
56591
+ select coalesce(jsonb_agg(jsonb_build_object('id', dg.${dg("id")}, 'driveId', dg.${dg("drive")}, 'principalType', ${drivePrincipalType("dg")}, 'principalId', ${drivePrincipalId("dg")}, 'role', dg.${dg("role")}, 'expiresAt', ${driveExpiring ? `dg.${dg("expiresAt")}` : "null"}) order by ${rank(`dg.${dg("role")}`)} desc, dg.${dg("id")}), '[]'::jsonb)
56371
56592
  from ${DG} dg
56372
56593
  where dg.${dg("drive")} = drive_grants_for_drive.drive${driveGrantLive("dg")}
56373
56594
  );
@@ -56775,8 +56996,8 @@ ${userGrant(`${fn("drive_release_hold")}(uuid)`)}
56775
56996
  // src/sql/modules/drive-tables.ts
56776
56997
  /** The drive tables and the triggers that keep paths and drives in step. */
56777
56998
  function driveTablesSql(kit) {
56778
- const { ctx, T, G, n, g, read, driveKinds, driveKindsArray, sourcesArray, drives, D, DG, C, d, dg, c, extras, sourceColumn, externalColumn, metadataColumn, holdColumn, binColumn, rolesArray } = kit;
56779
- return `${drives && ctx.owns("connections") && C !== void 0 ? `create table if not exists ${C} (
56999
+ const { ctx, T, G, n, g, read, driveKinds, driveKindsArray, sourcesArray, drives, D, DG, C, d, dg, c, extras, sourceColumn, externalColumn, metadataColumn, holdColumn, binColumn, rolesArray, typed, teamColumn, driveColumn, driveTyped, driveTeamColumn } = kit;
57000
+ const connectionTable = drives && ctx.owns("connections") && C !== void 0 ? `create table if not exists ${C} (
56780
57001
  ${c("id")} uuid primary key default gen_random_uuid(),
56781
57002
  ${c("tenant")} ${ctx.idType} not null,
56782
57003
  ${c("user")} uuid not null,
@@ -56805,7 +57026,8 @@ ${renderPolicy(policy$1({
56805
57026
  drop: true,
56806
57027
  target: C
56807
57028
  })}
56808
- ` : ""}${drives && ctx.owns("drives") && D !== void 0 ? `create table if not exists ${D} (
57029
+ ` : "";
57030
+ const driveTable = drives && ctx.owns("drives") && D !== void 0 ? `create table if not exists ${D} (
56809
57031
  ${d("id")} uuid primary key default gen_random_uuid(),
56810
57032
  ${d("tenant")} ${ctx.idType} not null,
56811
57033
  ${d("name")} text not null check (length(btrim(${d("name")})) between 1 and 255),
@@ -56822,26 +57044,36 @@ create index if not exists ${sqlIdent(`${ctx.tableName("drives").name}_kind_idx`
56822
57044
  create index if not exists ${sqlIdent(`${ctx.tableName("drives").name}_owner_idx`)} on ${D} (${d("owner")}) where ${d("owner")} is not null;
56823
57045
  create index if not exists ${sqlIdent(`${ctx.tableName("drives").name}_connection_idx`)} on ${D} (${d("connection")}) where ${d("connection")} is not null;
56824
57046
  ${lockTable(D, { read: true })}
56825
- ` : ""}${drives && ctx.owns("driveGrants") && DG !== void 0 && D !== void 0 ? `create table if not exists ${DG} (
57047
+ ` : "";
57048
+ const driveGrantIdentity = drives && DG !== void 0 ? driveTyped ? ` ${dg("principalType")} text not null check (${dg("principalType")} in ('user', 'team', 'role')),
57049
+ ${dg("principalId")} text not null,` : ` ${dg("user")} uuid${driveTeamColumn ? "" : " not null"},${driveTeamColumn ? `
57050
+ ${dg("team")} uuid,
57051
+ check ((${dg("user")} is not null)::int + (${dg("team")} is not null)::int = 1),` : ""}` : "";
57052
+ const driveGrantUnique = drives && DG !== void 0 && driveTyped ? ` unique (${dg("drive")}, ${dg("principalType")}, ${dg("principalId")}),
57053
+ ` : "";
57054
+ const driveGrantIndexes = drives && DG !== void 0 ? driveTyped ? `create index if not exists ${sqlIdent(`${ctx.tableName("driveGrants").name}_principal_idx`)} on ${DG} (${dg("principalType")}, ${dg("principalId")});` : `create unique index if not exists ${sqlIdent(`${ctx.tableName("driveGrants").name}_user_idx`)} on ${DG} (${dg("drive")}, ${dg("user")}) where ${dg("user")} is not null;
57055
+ create index if not exists ${sqlIdent(`${ctx.tableName("driveGrants").name}_user_principal_idx`)} on ${DG} (${dg("user")}) where ${dg("user")} is not null;${driveTeamColumn ? `
57056
+ create unique index if not exists ${sqlIdent(`${ctx.tableName("driveGrants").name}_team_idx`)} on ${DG} (${dg("drive")}, ${dg("team")}) where ${dg("team")} is not null;
57057
+ create index if not exists ${sqlIdent(`${ctx.tableName("driveGrants").name}_team_principal_idx`)} on ${DG} (${dg("team")}) where ${dg("team")} is not null;` : ""}` : "";
57058
+ const driveGrantTable = drives && ctx.owns("driveGrants") && DG !== void 0 && D !== void 0 ? `create table if not exists ${DG} (
56826
57059
  ${dg("id")} uuid primary key default gen_random_uuid(),
56827
57060
  ${dg("tenant")} ${ctx.idType} not null,
56828
57061
  ${dg("drive")} uuid not null,
56829
- ${dg("principalType")} text not null check (${dg("principalType")} in ('user', 'team', 'role')),
56830
- ${dg("principalId")} text not null,
57062
+ ${driveGrantIdentity}
56831
57063
  ${dg("role")} text not null,
56832
57064
  ${dg("expiresAt")} timestamptz,
56833
57065
  ${dg("createdBy")} uuid default auth.uid(),
56834
57066
  ${dg("createdAt")} timestamptz not null default now(),
56835
- unique (${dg("drive")}, ${dg("principalType")}, ${dg("principalId")}),
56836
- foreign key (${dg("drive")}, ${dg("tenant")}) references ${D} (${d("id")}, ${d("tenant")}) on delete cascade
57067
+ ${driveGrantUnique} foreign key (${dg("drive")}, ${dg("tenant")}) references ${D} (${d("id")}, ${d("tenant")}) on delete cascade
56837
57068
  );
56838
- create index if not exists ${sqlIdent(`${ctx.tableName("driveGrants").name}_principal_idx`)} on ${DG} (${dg("principalType")}, ${dg("principalId")});
57069
+ ${driveGrantIndexes}
56839
57070
  ${ensureCheck(DG, "bsb_drive_drive_grants_role", `${dg("role")} = any (${rolesArray})`)}
56840
57071
  ${lockTable(DG, { read: true })}
56841
- ` : ""}${ctx.owns("nodes") ? `create table if not exists ${T} (
57072
+ ` : "";
57073
+ const nodeTable = ctx.owns("nodes") ? `create table if not exists ${T} (
56842
57074
  ${n("id")} uuid primary key default gen_random_uuid(),
56843
57075
  ${n("tenant")} ${ctx.idType} not null,
56844
- ${drives ? `${n("drive")} uuid not null,` : ""}
57076
+ ${driveColumn ? `${n("drive")} uuid not null,` : ""}
56845
57077
  ${n("parent")} uuid references ${T} (${n("id")}) on delete cascade,
56846
57078
  ${n("kind")} text not null check (${n("kind")} in ('folder', 'file')),
56847
57079
  ${n("name")} text not null check (length(btrim(${n("name")})) between 1 and 255 and ${n("name")} !~ '[/[:cntrl:]]'),
@@ -56859,27 +57091,35 @@ ${lockTable(DG, { read: true })}
56859
57091
  foreign key (${n("drive")}, ${n("tenant")}) references ${D} (${d("id")}, ${d("tenant")}) on delete cascade` : ""}${externalColumn && sourceColumn ? `,
56860
57092
  check (${n("externalId")} is null or ${n("source")} <> 'internal')` : ""}
56861
57093
  );${addExtraColumns(T, extras)}
56862
- create unique index if not exists ${sqlIdent(`${ctx.tableName("nodes").name}_sibling_name_idx`)} on ${T} (${n("tenant")}${drives ? `, ${n("drive")}` : ""}, coalesce(${n("parent")}, '00000000-0000-0000-0000-000000000000'::uuid), lower(${n("name")})) where ${n("deletedAt")} is null${sourceColumn ? ` and ${n("source")} = 'internal'` : ""};
56863
- create index if not exists ${sqlIdent(`${ctx.tableName("nodes").name}_parent_idx`)} on ${T} (${n("tenant")}${drives ? `, ${n("drive")}` : ""}, ${n("parent")}, ${n("rank")});
57094
+ create unique index if not exists ${sqlIdent(`${ctx.tableName("nodes").name}_sibling_name_idx`)} on ${T} (${n("tenant")}${driveColumn ? `, ${n("drive")}` : ""}, coalesce(${n("parent")}, '00000000-0000-0000-0000-000000000000'::uuid), lower(${n("name")})) where ${n("deletedAt")} is null${sourceColumn ? ` and ${n("source")} = 'internal'` : ""};
57095
+ create index if not exists ${sqlIdent(`${ctx.tableName("nodes").name}_parent_idx`)} on ${T} (${n("tenant")}${driveColumn ? `, ${n("drive")}` : ""}, ${n("parent")}, ${n("rank")});
56864
57096
  create index if not exists ${sqlIdent(`${ctx.tableName("nodes").name}_parent_fk_idx`)} on ${T} (${n("parent")}) where ${n("parent")} is not null;
56865
57097
  create index if not exists ${sqlIdent(`${ctx.tableName("nodes").name}_path_idx`)} on ${T} (${n("path")} text_pattern_ops);
56866
- create index if not exists ${sqlIdent(`${ctx.tableName("nodes").name}_attachment_idx`)} on ${T} (${n("attachment")});${drives ? `
57098
+ create index if not exists ${sqlIdent(`${ctx.tableName("nodes").name}_attachment_idx`)} on ${T} (${n("attachment")});${driveColumn ? `
56867
57099
  create index if not exists ${sqlIdent(`${ctx.tableName("nodes").name}_drive_idx`)} on ${T} (${n("tenant")}, ${n("drive")}, ${n("parent")}, ${n("rank")});` : ""}${externalColumn ? `
56868
- create unique index if not exists ${sqlIdent(`${ctx.tableName("nodes").name}_external_idx`)} on ${T} (${drives ? `${n("drive")}, ` : `${n("tenant")}, `}${n("source")}, ${n("externalId")}) where ${n("externalId")} is not null${binColumn ? ` and ${n("deletedAt")} is null` : ""};` : ""}
57100
+ create unique index if not exists ${sqlIdent(`${ctx.tableName("nodes").name}_external_idx`)} on ${T} (${driveColumn ? `${n("drive")}, ` : `${n("tenant")}, `}${n("source")}, ${n("externalId")}) where ${n("externalId")} is not null${binColumn ? ` and ${n("deletedAt")} is null` : ""};` : ""}
56869
57101
  ${lockTable(T, { read: true })}
56870
- ` : ""}${ctx.owns("grants") ? `create table if not exists ${G} (
57102
+ ` : "";
57103
+ const grantIdentity = ctx.owns("grants") ? typed ? ` ${g("principalType")} text not null check (${g("principalType")} in ('user', 'team', 'role')),
57104
+ ${g("principalId")} text not null,` : ` ${g("user")} uuid${teamColumn ? "" : " not null"},${teamColumn ? `
57105
+ ${g("team")} uuid,
57106
+ check ((${g("user")} is not null)::int + (${g("team")} is not null)::int = 1),` : ""}` : "";
57107
+ const grantUnique = ctx.owns("grants") && typed ? ` unique (${g("node")}, ${g("principalType")}, ${g("principalId")})` : "";
57108
+ const grantIndexes = ctx.owns("grants") ? typed ? `create index if not exists ${sqlIdent(`${ctx.tableName("grants").name}_principal_idx`)} on ${G} (${g("principalType")}, ${g("principalId")});` : `create unique index if not exists ${sqlIdent(`${ctx.tableName("grants").name}_user_idx`)} on ${G} (${g("node")}, ${g("user")}) where ${g("user")} is not null;
57109
+ create index if not exists ${sqlIdent(`${ctx.tableName("grants").name}_user_principal_idx`)} on ${G} (${g("user")}) where ${g("user")} is not null;${teamColumn ? `
57110
+ create unique index if not exists ${sqlIdent(`${ctx.tableName("grants").name}_team_idx`)} on ${G} (${g("node")}, ${g("team")}) where ${g("team")} is not null;
57111
+ create index if not exists ${sqlIdent(`${ctx.tableName("grants").name}_team_principal_idx`)} on ${G} (${g("team")}) where ${g("team")} is not null;` : ""}` : "";
57112
+ return `${connectionTable}${driveTable}${driveGrantTable}${nodeTable}${ctx.owns("grants") ? `create table if not exists ${G} (
56871
57113
  ${g("id")} uuid primary key default gen_random_uuid(),
56872
57114
  ${g("tenant")} ${ctx.idType} not null,
56873
57115
  ${g("node")} uuid not null references ${T} (${n("id")}) on delete cascade,
56874
- ${g("principalType")} text not null check (${g("principalType")} in ('user', 'team', 'role')),
56875
- ${g("principalId")} text not null,
57116
+ ${grantIdentity}
56876
57117
  ${g("role")} text not null,
56877
57118
  ${g("expiresAt")} timestamptz,
56878
57119
  ${g("createdBy")} uuid default auth.uid(),
56879
- ${g("createdAt")} timestamptz not null default now(),
56880
- unique (${g("node")}, ${g("principalType")}, ${g("principalId")})
56881
- );
56882
- create index if not exists ${sqlIdent(`${ctx.tableName("grants").name}_principal_idx`)} on ${G} (${g("principalType")}, ${g("principalId")});
57120
+ ${g("createdAt")} timestamptz not null default now()${grantUnique ? "," : ""}
57121
+ ${grantUnique ? `${grantUnique}\n` : ""});
57122
+ ${grantIndexes}
56883
57123
  ${ensureCheck(G, "bsb_drive_grants_role", `${g("role")} = any (${rolesArray})`)}
56884
57124
  ${lockTable(G, { read: false })}
56885
57125
  ` : ""}`;
@@ -57004,7 +57244,7 @@ create trigger ${ctx.trigger("drive_node_drive_cascade")}
57004
57244
  // src/sql/modules/drive-core.ts
57005
57245
  /** The tree, grants and sharing: the drive module. */
57006
57246
  function driveCoreSql(kit) {
57007
- const { ctx, T, G, n, g, fn, read, create, manage, roles, conflict, pathMode, ranked, drives, D, DG, d, dg, readOnly, held, driveGrantLive, rolesArray, rank, live, canRead, canWrite, canShare, notFound, forbidden, record, dataAudit, principalMatch, grantLive, nodeJson, withRole, orderBy, touch, insertColumns, insertValues, directGrant, siblings } = kit;
57247
+ const { ctx, T, G, n, g, fn, read, create, manage, roles, conflict, pathMode, ranked, drives, D, DG, d, dg, readOnly, held, driveGrantLive, rolesArray, rank, live, canRead, canWrite, canShare, notFound, forbidden, record, dataAudit, principalMatch, drivePrincipalMatch, grantLive, nodeJson, withRole, orderBy, touch, insertColumns, insertValues, directGrant, siblings, nodeRole, driveRole, readPolicy, driveColumn } = kit;
57008
57248
  const tables = driveTablesSql(kit);
57009
57249
  const ancestors = pathMode ? ` select string_to_array(btrim(x.${n("path")}, '/'), '/')::uuid[] from ${T} x where x.${n("id")} = drive_ancestors.node` : ` with recursive up (id, parent, depth) as (
57010
57250
  select x.${n("id")}, x.${n("parent")}, 0 from ${T} x where x.${n("id")} = drive_ancestors.node
@@ -57046,8 +57286,8 @@ ${subtree}
57046
57286
  $$;
57047
57287
  revoke execute on function ${fn("drive_subtree")}(uuid) from public, anon, authenticated;
57048
57288
 
57049
- -- Whether the node or anything under it is under a legal hold, which purge
57050
- -- has to respect.
57289
+ -- Whether the node, a folder above it or anything under it is under a legal
57290
+ -- hold, which purge has to respect.
57051
57291
  create or replace function ${fn("drive_node_held")}(node uuid)
57052
57292
  returns boolean
57053
57293
  language sql
@@ -57057,15 +57297,14 @@ set search_path = ''
57057
57297
  as $$
57058
57298
  select exists (
57059
57299
  select 1 from ${T} h
57060
- where h.${n("id")} in (select s.node_id from ${fn("drive_subtree")}(drive_node_held.node) s)
57300
+ where (h.${n("id")} in (select s.node_id from ${fn("drive_subtree")}(drive_node_held.node) s)
57301
+ or h.${n("id")} = any (${fn("drive_ancestors")}(drive_node_held.node)))
57061
57302
  and ${held("h")}
57062
57303
  )
57063
57304
  $$;
57064
57305
  ${userGrant(`${fn("drive_node_held")}(uuid)`)}
57065
57306
  ${drives ? `
57066
- -- The caller's role on a drive: ${OPERATIONS["drive.manage"]} is ${roles.top},
57067
- -- the owner holds ${roles.top} too${roles.member === void 0 ? "" : `, options.memberRole (${roles.member}) covers every member with ${OPERATIONS["drive.read"]}`}, and a grant that names them or one of their teams
57068
- -- adds its role. ${OPERATIONS["drive.read"]} in the drive's organization is required.
57307
+ -- The caller's role on a drive: ${driveRole === void 0 ? `${OPERATIONS["drive.manage"]} is ${roles.top}, the owner holds ${roles.top} too${roles.member === void 0 ? "" : `, options.memberRole (${roles.member}) covers every member with ${OPERATIONS["drive.read"]}`}, and a grant that names them or one of their teams adds its role` : `options.roleFunctions.drive (${driveRole.label}) decides it`}. ${OPERATIONS["drive.read"]} in the drive's organization is required.
57069
57308
  create or replace function ${fn("drive_drive_role")}(drive uuid)
57070
57309
  returns text
57071
57310
  language plpgsql
@@ -57086,13 +57325,13 @@ begin
57086
57325
  select d.${d("tenant")}, d.${d("owner")} into v_tenant, v_owner from ${D} d where d.${d("id")} = drive_drive_role.drive;
57087
57326
  if v_tenant is null or v_uid is null or not ${ctx.can("tenant", "v_tenant", read)} then
57088
57327
  return null;
57089
- end if;
57328
+ end if;${driveRole === void 0 ? "" : `\n return (select r from (select ${driveRole.role("drive_drive_role.drive", "v_uid")}) x(r) where r = any (${rolesArray}));`}
57090
57329
  if ${ctx.can("tenant", "v_tenant", manage)} or v_owner = v_uid then
57091
57330
  return ${sqlString(roles.top)};
57092
57331
  end if;
57093
57332
  select max(${rank(`dg.${dg("role")}`)}) into v_rank from ${DG} dg
57094
57333
  where dg.${dg("drive")} = drive_drive_role.drive${driveGrantLive("dg")}
57095
- and ${principalMatch("dg", "v_uid", "v_tenant")};
57334
+ and ${drivePrincipalMatch("dg", "v_uid", "v_tenant")};
57096
57335
  ${roles.member === void 0 ? "" : `v_rank := greatest(coalesce(v_rank, 0), ${rank(sqlString(roles.member))});`}
57097
57336
  if coalesce(v_rank, 0) = 0 then
57098
57337
  return null;
@@ -57122,7 +57361,7 @@ stable
57122
57361
  security definer
57123
57362
  set search_path = ''
57124
57363
  as $$
57125
- select d.${d("id")} from ${D} d
57364
+ ${driveRole === void 0 ? ` select d.${d("id")} from ${D} d
57126
57365
  where ${SERVICE_CALLER$1}
57127
57366
  or (auth.uid() is not null
57128
57367
  and d.${d("tenant")} in (select ${ctx.scope.ids(read)})
@@ -57134,13 +57373,16 @@ as $$
57134
57373
  and ${rank(`dg.${dg("role")}`)} >= ${rank(sqlString(roles.read))}
57135
57374
  and ${rank(sqlString(roles.read))} > 0
57136
57375
  and d.${d("tenant")} in (select ${ctx.scope.ids(read)})
57137
- and ${principalMatch("dg", "auth.uid()", `d.${d("tenant")}`)}
57376
+ and ${drivePrincipalMatch("dg", "auth.uid()", `d.${d("tenant")}`)}` : ` select d.${d("id")} from ${D} d
57377
+ where ${SERVICE_CALLER$1}
57378
+ or (auth.uid() is not null
57379
+ and d.${d("tenant")} in (select ${ctx.scope.ids(read)})
57380
+ and (${driveRole.role(`d.${d("id")}`, "auth.uid()")}) = any (${rolesArray}))`}
57138
57381
  $$;
57139
57382
  ${userGrant(`${fn("drive_drive_readable_ids")}()`)}
57140
57383
  ` : ""}
57141
57384
 
57142
- -- The caller's role on a node: the highest of the grants on it and its
57143
- -- ancestors that name them, one of their teams or their organization role${roles.member === void 0 ? "" : `, and options.memberRole (${roles.member}) for every member with ${OPERATIONS["drive.read"]}`}. ${OPERATIONS["drive.manage"]} is ${roles.top} everywhere. Grants
57385
+ -- The caller's role on a node: ${nodeRole === void 0 ? `the highest of the grants on it and its ancestors that name them, one of their teams or their organization role${roles.member === void 0 ? "" : `, and options.memberRole (${roles.member}) for every member with ${OPERATIONS["drive.read"]}`}. ${OPERATIONS["drive.manage"]} is ${roles.top} everywhere` : `options.roleFunctions.node (${nodeRole.label}) decides it`}. Grants
57144
57386
  -- need ${OPERATIONS["drive.read"]} in the node's organization too.
57145
57387
  create or replace function ${fn("drive_role")}(node uuid)
57146
57388
  returns text
@@ -57162,7 +57404,7 @@ begin
57162
57404
  select x.${n("tenant")}${drives ? `, x.${n("drive")}` : ""} into v_tenant${drives ? ", v_drive" : ""} from ${T} x where x.${n("id")} = drive_role.node;
57163
57405
  if v_tenant is null or v_uid is null or not ${ctx.can("tenant", "v_tenant", read)} then
57164
57406
  return null;
57165
- end if;
57407
+ end if;${nodeRole === void 0 ? "" : `\n return (select r from (select ${nodeRole.role("drive_role.node", "v_uid")}) x(r) where r = any (${rolesArray}));`}
57166
57408
  if ${ctx.can("tenant", "v_tenant", manage)} then
57167
57409
  return ${sqlString(roles.top)};
57168
57410
  end if;
@@ -57216,7 +57458,7 @@ stable
57216
57458
  security definer
57217
57459
  set search_path = ''
57218
57460
  as $$
57219
- select x.${n("id")} from ${T} x
57461
+ ${nodeRole === void 0 ? ` select x.${n("id")} from ${T} x
57220
57462
  where ${SERVICE_CALLER$1}
57221
57463
  or (auth.uid() is not null
57222
57464
  and x.${n("tenant")} in (select ${ctx.scope.ids(read)})
@@ -57243,7 +57485,11 @@ as $$
57243
57485
  and ${rank(`dg.${dg("role")}`)} >= ${rank(sqlString(roles.read))}
57244
57486
  and ${rank(sqlString(roles.read))} > 0
57245
57487
  and x.${n("tenant")} in (select ${ctx.scope.ids(read)})
57246
- and ${principalMatch("dg", "auth.uid()", `x.${n("tenant")}`)}` : ""}
57488
+ and ${drivePrincipalMatch("dg", "auth.uid()", `x.${n("tenant")}`)}` : ""}` : ` select x.${n("id")} from ${T} x
57489
+ where ${SERVICE_CALLER$1}
57490
+ or (auth.uid() is not null
57491
+ and x.${n("tenant")} in (select ${ctx.scope.ids(read)})
57492
+ and (${nodeRole.role(`x.${n("id")}`, "auth.uid()")}) = any (${rolesArray}))`}
57247
57493
  $$;
57248
57494
  ${userGrant(`${fn("drive_readable_ids")}()`)}
57249
57495
 
@@ -57257,7 +57503,7 @@ as $$
57257
57503
  select ${nodeJson("")}
57258
57504
  $$;
57259
57505
  revoke execute on function ${fn("drive_node_json")}(${T}) from public, anon, authenticated;
57260
- ${ctx.manages ? `
57506
+ ${ctx.manages && readPolicy ? `
57261
57507
  ${renderPolicy(policy$1({
57262
57508
  table: T,
57263
57509
  name: ctx.naming.rename("drive_nodes_read"),
@@ -57268,7 +57514,7 @@ ${renderPolicy(policy$1({
57268
57514
  drop: true,
57269
57515
  target: T
57270
57516
  })}
57271
- ` : ""}${drives && D !== void 0 && ctx.owns("drives") ? `
57517
+ ` : ""}${readPolicy && drives && D !== void 0 && ctx.owns("drives") ? `
57272
57518
  ${renderPolicy(policy$1({
57273
57519
  table: D,
57274
57520
  name: ctx.naming.rename("drive_drives_read"),
@@ -57279,7 +57525,7 @@ ${renderPolicy(policy$1({
57279
57525
  drop: true,
57280
57526
  target: D
57281
57527
  })}
57282
- ` : ""}${drives && DG !== void 0 && ctx.owns("driveGrants") ? `
57528
+ ` : ""}${readPolicy && drives && DG !== void 0 && ctx.owns("driveGrants") ? `
57283
57529
  ${renderPolicy(policy$1({
57284
57530
  table: DG,
57285
57531
  name: ctx.naming.rename("drive_drive_grants_read"),
@@ -57429,7 +57675,7 @@ revoke execute on function ${fn("drive_check_parent")}(${ctx.idType}, uuid, uuid
57429
57675
  drop function if exists ${fn("drive_insert_node")}(${ctx.idType}, uuid, uuid, text, text, text, jsonb);
57430
57676
  drop function if exists ${fn("drive_insert_node")}(${ctx.idType}, uuid, text, text, text, jsonb);
57431
57677
  -- Inserts a node after its siblings. Extra columns come from fields, or
57432
- -- from the parent. At the root, the creator gets ${roles.top}.
57678
+ -- from the parent.${nodeRole === void 0 ? ` At the root, the creator gets ${roles.top}.` : ""}
57433
57679
  create or replace function ${fn("drive_insert_node")}(tenant ${ctx.idType}, drive uuid, parent uuid, kind text, name text, conflict text, fields jsonb)
57434
57680
  returns ${T}
57435
57681
  language plpgsql
@@ -57445,7 +57691,7 @@ declare
57445
57691
  v_name text;
57446
57692
  v_last text;
57447
57693
  begin
57448
- select * into v_parent from ${T} x where x.${n("id")} = drive_insert_node.parent;${drives ? `
57694
+ select * into v_parent from ${T} x where x.${n("id")} = drive_insert_node.parent;${driveColumn ? `
57449
57695
  if drive_insert_node.parent is not null then
57450
57696
  v_drive := v_parent.${n("drive")};
57451
57697
  end if;` : ""}
@@ -57462,10 +57708,10 @@ begin
57462
57708
  insert into ${T} (${insertColumns.join(", ")})
57463
57709
  values (${insertValues.join(", ")})
57464
57710
  returning * into v_node;
57465
- if drive_insert_node.parent is null and auth.uid() is not null then
57711
+ ${nodeRole === void 0 ? ` if drive_insert_node.parent is null and auth.uid() is not null then
57466
57712
  ${directGrant("v_node", sqlString(roles.top), "auth.uid()")}
57467
57713
  end if;
57468
- ${record("drive.node_created", "v_node", `, 'kind', v_node.${n("kind")}, 'name', v_node.${n("name")}, 'parentId', v_node.${n("parent")}`, dataAudit("v_node", "created"))}
57714
+ ` : ""} ${record("drive.node_created", "v_node", `, 'kind', v_node.${n("kind")}, 'name', v_node.${n("name")}, 'parentId', v_node.${n("parent")}`, dataAudit("v_node", "created"))}
57469
57715
  ${ctx.hook("after_drive_node_create", [["uuid", `v_node.${n("id")}`]])}
57470
57716
  return v_node;
57471
57717
  end;
@@ -57630,7 +57876,7 @@ begin
57630
57876
  if v_name = v_node.${n("name")} then
57631
57877
  return ${withRole("v_node")};
57632
57878
  end if;
57633
- v_name := ${fn("drive_free_name")}(v_node.${n("tenant")}, ${drives ? `v_node.${n("drive")}` : "null"}, v_node.${n("parent")}, v_name, v_node.${n("id")},
57879
+ v_name := ${fn("drive_free_name")}(v_node.${n("tenant")}, ${driveColumn ? `v_node.${n("drive")}` : "null"}, v_node.${n("parent")}, v_name, v_node.${n("id")},
57634
57880
  case when ${fn("drive_conflict")}(drive_rename.conflict) = 'rename' then 'rename' else 'fail' end);
57635
57881
  ${ctx.hook("before_drive_node_rename", [["uuid", `v_node.${n("id")}`], ["text", "v_name"]])}
57636
57882
  v_previous := v_node.${n("name")};
@@ -57676,8 +57922,8 @@ begin
57676
57922
  ${fail$1("DRIVE_RANK_INVALID", "rank must be a key from rankBetween", "22023")}
57677
57923
  end if;` : ""}
57678
57924
  v_previous := v_node.${n("parent")};
57679
- if drive_move.parent is null then${drives ? `
57680
- v_target := coalesce(drive_move.drive, v_node.${n("drive")});
57925
+ if drive_move.parent is null then${driveColumn ? `
57926
+ v_target := coalesce(drive_move.drive, v_node.${n("drive")});` : ""}${drives ? `
57681
57927
  if v_target is null then
57682
57928
  ${fail$1("DRIVE_REQUIRED", "a top-level item needs a drive", "22023")}
57683
57929
  end if;
@@ -57701,14 +57947,14 @@ begin
57701
57947
  perform ${fn("drive_check_parent")}(v_node.${n("tenant")}, drive_move.parent, drive_move.drive);
57702
57948
  if v_node.${n("id")} = any (${fn("drive_ancestors")}(drive_move.parent)) then
57703
57949
  ${fail$1("DRIVE_MOVE_CYCLE", "a folder can't move into itself or its own subfolder", "22023")}
57704
- end if;${drives ? `
57705
- select x.${n("drive")} into v_target from ${T} x where x.${n("id")} = drive_move.parent;
57950
+ end if;${driveColumn ? `
57951
+ select x.${n("drive")} into v_target from ${T} x where x.${n("id")} = drive_move.parent;` : ""}${drives ? `
57706
57952
  if v_target is distinct from v_node.${n("drive")} and not (${SERVICE_CALLER$1} or ${canShare(`v_node.${n("id")}`)}) then
57707
57953
  ${forbidden("move this item to another drive")}
57708
57954
  end if;` : ""}
57709
57955
  end if;
57710
57956
  ${ctx.hook("before_drive_node_move", [["uuid", `v_node.${n("id")}`], ["uuid", "drive_move.parent"]])}
57711
- if v_previous is distinct from drive_move.parent${drives ? ` or v_target is distinct from v_node.${n("drive")}` : ""} then
57957
+ if v_previous is distinct from drive_move.parent${driveColumn ? ` or v_target is distinct from v_node.${n("drive")}` : ""} then
57712
57958
  v_name := ${fn("drive_free_name")}(v_node.${n("tenant")}, v_target, drive_move.parent, v_node.${n("name")}, v_node.${n("id")},
57713
57959
  case when ${fn("drive_conflict")}(drive_move.conflict) = 'rename' then 'rename' else 'fail' end);
57714
57960
  if drive_move.parent is null and auth.uid() is not null then
@@ -57719,7 +57965,7 @@ begin
57719
57965
  select max(x.${n("rank")}) into v_last from ${T} x
57720
57966
  where ${siblings("x", `v_node.${n("tenant")}`, "drive_move.parent", "v_target")};
57721
57967
  end if;` : ""}
57722
- update ${T} x set ${n("parent")} = drive_move.parent, ${n("name")} = v_name${drives ? `, ${n("drive")} = v_target` : ""}${ranked ? `, ${n("rank")} = coalesce(drive_move.rank, ${rankAfter("v_last")})` : ""}${touch}
57968
+ update ${T} x set ${n("parent")} = drive_move.parent, ${n("name")} = v_name${driveColumn ? `, ${n("drive")} = v_target` : ""}${ranked ? `, ${n("rank")} = coalesce(drive_move.rank, ${rankAfter("v_last")})` : ""}${touch}
57723
57969
  where x.${n("id")} = v_node.${n("id")}
57724
57970
  returning * into v_node;
57725
57971
  ${record("drive.node_moved", "v_node", `, 'parentId', v_node.${n("parent")}, 'previousParentId', v_previous`, dataAudit("v_node", "moved"))}
@@ -57777,7 +58023,7 @@ ${driveDrivesSql(kit)}
57777
58023
  const APPROVE = "'approve'";
57778
58024
  /** Files, revisions, the bin, stars and links: the drive-files module. */
57779
58025
  function driveFilesSql(kit) {
57780
- const { ctx, own, T, G, n, g, fn, read, drives, readOnly, typeLit, attachments, A, a, versions, v, trash, ti, shareLinks, state, st, live, canRead, canWrite, canShare, notFound, forbidden, record, dataAudit, fileJson, nodeJson, json, withRole, orderBy, touch, siblings } = kit;
58026
+ const { ctx, own, T, G, n, g, fn, read, driveColumn, readOnly, typeLit, attachments, A, a, versions, v, trash, ti, shareLinks, state, st, live, canRead, canWrite, canShare, notFound, forbidden, record, dataAudit, fileJson, nodeJson, json, withRole, orderBy, touch, siblings } = kit;
57781
58027
  const tags = labelTags(own);
57782
58028
  const approvals = A !== void 0 && own.installed("approvals") && own.of("approvals").mode !== "custom" ? own.of("approvals") : void 0;
57783
58029
  const tg = (column) => tags === void 0 ? column : tags.col("taggings", column);
@@ -57818,7 +58064,7 @@ declare
57818
58064
  v_node ${T}%rowtype;
57819
58065
  begin
57820
58066
  ${READ_ONLY_GUARD}
57821
- perform ${fn("drive_check_parent")}(drive_create_file.tenant, drive_create_file.parent, drive_create_file.drive);${drives ? `
58067
+ perform ${fn("drive_check_parent")}(drive_create_file.tenant, drive_create_file.parent, drive_create_file.drive);${driveColumn ? `
57822
58068
  if drive_create_file.parent is not null then
57823
58069
  select x.${n("drive")} into v_drive from ${T} x where x.${n("id")} = drive_create_file.parent;
57824
58070
  end if;` : ""}
@@ -58216,7 +58462,7 @@ begin
58216
58462
  ) then
58217
58463
  ${fail$1("DRIVE_PARENT_TRASHED", "restore the folder this item was in first", "22023")}
58218
58464
  end if;
58219
- v_name := ${fn("drive_free_name")}(v_node.${n("tenant")}, ${drives ? `v_node.${n("drive")}` : "null"}, v_node.${n("parent")}, v_node.${n("name")}, v_node.${n("id")}, ${fn("drive_conflict")}(drive_restore.conflict));
58465
+ v_name := ${fn("drive_free_name")}(v_node.${n("tenant")}, ${driveColumn ? `v_node.${n("drive")}` : "null"}, v_node.${n("parent")}, v_node.${n("name")}, v_node.${n("id")}, ${fn("drive_conflict")}(drive_restore.conflict));
58220
58466
  if v_name <> v_node.${n("name")} then
58221
58467
  update ${T} x set ${n("name")} = v_name where x.${n("id")} = v_node.${n("id")};
58222
58468
  end if;
@@ -80318,6 +80564,8 @@ const INVITATIONS = {
80318
80564
  build: invitationsSql
80319
80565
  };
80320
80566
  // src/sql/modules/invoices-functions.ts
80567
+ /** `options.chargeExtraColumns`: app columns of the charges table. */
80568
+ const chargeExtraColumns = (ctx) => ctx.hasTable("charges") ? ctx.extraColumns("charges", ["fields"], "chargeExtraColumns") : [];
80321
80569
  /**
80322
80570
  * How the invoices table holds a company, contact or origin: a type and an id
80323
80571
  * column (`pair`), only an id column of one fixed type, such as a foreign key
@@ -80382,7 +80630,7 @@ function invoiceFunctions(ctx, n) {
80382
80630
  ].filter((party) => invoiceParty(ctx, party) === "fixed").map((party) => `, ${sqlString(`${party}_type`)}, ${partyTypeSql(ctx, n, party, alias)}`).join("")}${has("listTotal") ? "" : `, 'list_total', ${alias}.${i("subtotal")}::text`}${has("discountTotal") ? "" : ", 'discount_total', '0'"}`;
80383
80631
  const chargesJson = (alias) => charges ? `,
80384
80632
  'charged_total', ${charged(alias)}::text,
80385
- 'charges', coalesce((select jsonb_agg(jsonb_build_object('id', y.${ch("id")}, 'amount', y.${ch("amount")}::text, 'description', ${ctx.has("charges", "description") ? `y.${ch("description")}` : "null"}${ctx.has("charges", "createdAt") ? `, 'createdAt', y.${ch("createdAt")}` : ""})${ctx.has("charges", "createdAt") ? ` order by y.${ch("createdAt")}` : ""}) from ${t("charges")} y where y.${ch("invoice")} = ${alias}.${i("id")}), '[]'::jsonb)` : "";
80633
+ 'charges', coalesce((select jsonb_agg(jsonb_build_object('id', y.${ch("id")}, 'amount', y.${ch("amount")}::text, 'description', ${ctx.has("charges", "description") ? `y.${ch("description")}` : "null"}${ctx.has("charges", "createdAt") ? `, 'createdAt', y.${ch("createdAt")}` : ""}${extraFieldsJson("y", n.chargeExtras)})${ctx.has("charges", "createdAt") ? ` order by y.${ch("createdAt")}` : ""}) from ${t("charges")} y where y.${ch("invoice")} = ${alias}.${i("id")}), '[]'::jsonb)` : "";
80386
80634
  const row = (alias) => `${ctx.rowJson("invoices", alias, { as: int8Text8 })} || ${int8Text(alias, int8)} || jsonb_build_object(
80387
80635
  'balance', ${balance(alias)}::text${missingKeys(alias)}${chargesJson(alias)},
80388
80636
  'overdue', ${st(`${alias}.${i("status")}`, ["issued", "partially_paid"])} and ${alias}.${i("dueOn")} < current_date,
@@ -80517,11 +80765,15 @@ ${userGrant(`${fn("invoice_from_quote")}(uuid, integer)`)}
80517
80765
  ...ctx.has("charges", "description") ? ["nullif(trim(add_invoice_charge.description), '')"] : [],
80518
80766
  ...ctx.has("charges", "createdBy") ? ["auth.uid()"] : []
80519
80767
  ];
80768
+ const chargeFields = extraFieldsArg(n.chargeExtras);
80769
+ const chargeExtras = insertExtraColumns(t("charges"), n.chargeExtras, "coalesce(add_invoice_charge.fields, '{}'::jsonb)");
80520
80770
  const addCharge = charges ? `
80771
+ ${chargeFields.drop(fn("add_invoice_charge"), "uuid, bigint, text, text")}
80521
80772
  -- Adds a charge on top of an issued invoice's total, such as collection
80522
80773
  -- costs or a late fee, in the invoice's currency. It raises the balance, so
80523
- -- a paid invoice is open again until the charge is paid too.
80524
- create or replace function ${fn("add_invoice_charge")}(invoice uuid, amount bigint, currency text, description text)
80774
+ -- a paid invoice is open again until the charge is paid too. fields: the
80775
+ -- charge's extra columns (options.chargeExtraColumns).
80776
+ create or replace function ${fn("add_invoice_charge")}(invoice uuid, amount bigint, currency text, description text${chargeFields.param})
80525
80777
  returns jsonb
80526
80778
  language plpgsql
80527
80779
  security definer
@@ -80548,14 +80800,14 @@ begin
80548
80800
  if upper(add_invoice_charge.currency) is distinct from v_row.${i("currency")} then
80549
80801
  ${fail$1("INVOICE_CURRENCY_MISMATCH", "a charge must be in the invoice's currency", "22023")}
80550
80802
  end if;
80551
- insert into ${t("charges")} (${chargeColumns.join(", ")})
80552
- values (${chargeValues.join(", ")})
80803
+ insert into ${t("charges")} (${chargeColumns.join(", ")}${chargeExtras.columns})
80804
+ values (${chargeValues.join(", ")}${chargeExtras.values})
80553
80805
  returning ${ch("id")} into v_charge;${settle("v_row")}
80554
80806
  ${record("invoice.charged", "v_row", `, 'chargeId', v_charge, 'amount', add_invoice_charge.amount::text, 'balance', ${balance("v_row")}::text`, true)}
80555
80807
  return ${row("v_row")};
80556
80808
  end;
80557
80809
  $$;
80558
- ${userGrant(`${fn("add_invoice_charge")}(uuid, bigint, text, text)`)}
80810
+ ${userGrant(`${fn("add_invoice_charge")}(uuid, bigint, text, text${chargeFields.type})`)}
80559
80811
  ` : "";
80560
80812
  const kindTable = (kind) => `(select * from ${t("invoices")} k where ${kd(`k.${i("kind")}`, [kind])})`;
80561
80813
  return `
@@ -80992,6 +81244,8 @@ const NAMES$57 = {
80992
81244
  "termsDays",
80993
81245
  "extraColumns",
80994
81246
  "lineExtraColumns",
81247
+ "lineRates",
81248
+ "chargeExtraColumns",
80995
81249
  "totals"
80996
81250
  ],
80997
81251
  tables: {
@@ -81099,7 +81353,7 @@ function tables$16(ctx, n) {
81099
81353
  create table if not exists ${t("charges")} (
81100
81354
  ${chargeColumns.join(",\n ")}
81101
81355
  );
81102
- create index if not exists ${ctx.naming.rename("invoice_charges_invoice_idx")} on ${t("charges")} (${ch("invoice")});
81356
+ create index if not exists ${ctx.naming.rename("invoice_charges_invoice_idx")} on ${t("charges")} (${ch("invoice")});${addExtraColumns(t("charges"), chargeExtraColumns(ctx))}
81103
81357
  ${lockModuleTable(ctx, "charges", { read: true })}
81104
81358
  ${renderPolicy(policy$1({
81105
81359
  table: t("charges"),
@@ -81196,6 +81450,7 @@ function build$55(ctx) {
81196
81450
  "charged_total"
81197
81451
  ]),
81198
81452
  lineExtras: lineExtraColumns(ctx),
81453
+ chargeExtras: chargeExtraColumns(ctx),
81199
81454
  appTotals: invoiceTotals(ctx) === "app"
81200
81455
  };
81201
81456
  return `${schemaPreamble(ctx)}
@@ -81261,7 +81516,8 @@ function contract$49(ctx) {
81261
81516
  "uuid",
81262
81517
  "bigint",
81263
81518
  "text",
81264
- "text"
81519
+ "text",
81520
+ ...extraFieldsArg(chargeExtraColumns(ctx)).contract
81265
81521
  ],
81266
81522
  returns: "jsonb"
81267
81523
  }] : [],
@@ -83217,6 +83473,16 @@ const LEASES = {
83217
83473
  build: build$52
83218
83474
  };
83219
83475
  // src/sql/modules/leave-feed.ts
83476
+ /** A type row's key: its key column, or its id without one. */
83477
+ const leaveTypeKey = (ctx, row) => ctx.has("types", "key") ? `${row}.${ctx.col("types", "key")}` : `${row}.${ctx.col("types", "id")}::text`;
83478
+ /**
83479
+ * A request row's part of the day: its partial column, or without one `hours`
83480
+ * for an hours type and `full` otherwise.
83481
+ */
83482
+ function leavePartial(ctx, row) {
83483
+ if (ctx.has("requests", "partial")) return `${row}.${ctx.col("requests", "partial")}`;
83484
+ return `(select case when ${ctx.label("types", "unit", `p.${ctx.col("types", "unit")}`)} = 'hours' then 'hours' else 'full' end from ${ctx.table("types")} p where p.${ctx.col("types", "id")} = ${row}.${ctx.col("requests", "type")})`;
83485
+ }
83220
83486
  /** The share-links subject of an organization's leave feed. */
83221
83487
  const LEAVE_FEED_SUBJECT = "leave_feed";
83222
83488
  const read = (ctx) => ctx.permission("read", moduleOperations("leave").read);
@@ -83279,7 +83545,7 @@ begin
83279
83545
  select jsonb_agg(x.item order by x.starts_on, x.id)
83280
83546
  from (
83281
83547
  select jsonb_build_object('id', ${q("id")}, 'userId', ${q("user")}, 'typeId', ${q("type")}, 'type', ${ty("name")}, 'unit', ${ty("unit")},
83282
- 'startsOn', ${q("startsOn")}, 'endsOn', ${q("endsOn")}, 'partial', ${q("partial")}, 'amount', ${q("amount")}::text, 'approvedAt', ${q("approvedAt")}, 'updatedAt', ${q("updatedAt")}) as item,
83548
+ 'startsOn', ${q("startsOn")}, 'endsOn', ${q("endsOn")}, 'partial', ${leavePartial(ctx, "r")}, 'amount', ${q("amount")}::text, 'approvedAt', ${q("approvedAt")}, 'updatedAt', ${q("updatedAt")}) as item,
83283
83549
  ${q("startsOn")} as starts_on, ${q("id")} as id
83284
83550
  from ${ctx.table("requests")} r
83285
83551
  join ${ctx.table("types")} t on ${ty("id")} = ${q("type")}
@@ -83447,7 +83713,7 @@ begin
83447
83713
  ${invalid("name user_id")}
83448
83714
  end if;
83449
83715
  select coalesce(jsonb_agg(jsonb_build_object(
83450
- 'typeId', t.${ty("id")}, 'key', t.${ty("key")}, 'name', t.${ty("name")}, 'unit', t.${ty("unit")},
83716
+ 'typeId', t.${ty("id")}, 'key', ${leaveTypeKey(ctx, "t")}, 'name', t.${ty("name")}, 'unit', t.${ty("unit")},
83451
83717
  'userId', v_user, 'period', v_period,
83452
83718
  'granted', ${decimalText("coalesce(b.granted, 0)")},
83453
83719
  'taken', ${decimalText("coalesce(b.taken, 0)")},
@@ -83765,6 +84031,7 @@ const NAMES$53 = {
83765
84031
  updatedAt: "updated_at"
83766
84032
  },
83767
84033
  optional: [
84034
+ "key",
83768
84035
  "allowance",
83769
84036
  "carryoverMax",
83770
84037
  "color"
@@ -83800,6 +84067,7 @@ const NAMES$53 = {
83800
84067
  decisionNote: "decision_note"
83801
84068
  },
83802
84069
  optional: [
84070
+ "partial",
83803
84071
  "note",
83804
84072
  "cancelledBy",
83805
84073
  "approval",
@@ -83897,9 +84165,30 @@ function build$51(ctx) {
83897
84165
  ["color", "save_leave_type.color"]
83898
84166
  ].filter(([logical]) => ctx.has("types", logical));
83899
84167
  const settingsLine = typeSettings.filter(([logical]) => logical !== "allowance").map(([logical]) => `${ty(logical)} = excluded.${ty(logical)}`).join(", ");
84168
+ const unitArg = ctx.cast("types", "unit", "coalesce(save_leave_type.unit, 'days')");
84169
+ const typeUpsert = ctx.has("types", "key") ? ` insert into ${types} (${ty("tenant")}, ${ty("key")}, ${ty("name")}, ${ty("unit")}, ${ty("paid")}, ${ty("tracked")}${typeSettings.map(([logical]) => `, ${ty(logical)}`).join("")})
84170
+ values (save_leave_type.tenant, save_leave_type.key, save_leave_type.name, ${unitArg}, coalesce(save_leave_type.paid, true), coalesce(save_leave_type.tracked, true)${typeSettings.map(([, arg]) => `, ${arg}`).join("")})
84171
+ on conflict (${ty("tenant")}, ${ty("key")}) do update
84172
+ set ${ty("name")} = excluded.${ty("name")}, ${ty("unit")} = excluded.${ty("unit")}, ${ty("paid")} = excluded.${ty("paid")},
84173
+ ${ty("tracked")} = excluded.${ty("tracked")}${ctx.has("types", "allowance") ? `, ${ty("allowance")} = excluded.${ty("allowance")}` : ""},
84174
+ ${settingsLine === "" ? "" : `${settingsLine},\n `}${ty("archivedAt")} = null, ${ty("updatedAt")} = now()
84175
+ returning * into v_row;` : ` select * into v_row from ${types} x
84176
+ where x.${ty("tenant")} = save_leave_type.tenant and x.${ty("id")}::text = save_leave_type.key
84177
+ for update;
84178
+ if found then
84179
+ update ${types} x
84180
+ set ${ty("name")} = save_leave_type.name, ${ty("unit")} = ${unitArg}, ${ty("paid")} = coalesce(save_leave_type.paid, true),
84181
+ ${ty("tracked")} = coalesce(save_leave_type.tracked, true)${typeSettings.map(([logical, arg]) => `, ${ty(logical)} = ${arg}`).join("")}, ${ty("archivedAt")} = null, ${ty("updatedAt")} = now()
84182
+ where x.${ty("id")} = v_row.${ty("id")}
84183
+ returning * into v_row;
84184
+ else
84185
+ insert into ${types} (${ty("tenant")}, ${ty("name")}, ${ty("unit")}, ${ty("paid")}, ${ty("tracked")}${typeSettings.map(([logical]) => `, ${ty(logical)}`).join("")})
84186
+ values (save_leave_type.tenant, save_leave_type.name, ${unitArg}, coalesce(save_leave_type.paid, true), coalesce(save_leave_type.tracked, true)${typeSettings.map(([, arg]) => `, ${arg}`).join("")})
84187
+ returning * into v_row;
84188
+ end if;`;
83900
84189
  const status = (row, approval) => approvals === void 0 ? `case when ${row}.${q("cancelledAt")} is not null then 'cancelled' when ${row}.${q("approvedAt")} is not null then 'approved'${rejections ? ` when ${row}.${q("rejectedAt")} is not null then 'rejected'` : ""} else 'pending' end` : `case when ${row}.${q("cancelledAt")} is not null then 'cancelled' when ${row}.${q("approvedAt")} is not null then 'approved' when ${approval}.${a("status")} in ('rejected', 'expired') then 'rejected' when ${approval}.${a("status")} = 'cancelled' then 'cancelled' else 'pending' end`;
83901
- const typeJson = (row) => `jsonb_build_object('id', ${row}.${ty("id")}, 'organizationId', ${row}.${ty("tenant")}, 'key', ${row}.${ty("key")}, 'name', ${row}.${ty("name")}, 'unit', ${row}.${ty("unit")}, 'paid', ${row}.${ty("paid")}, 'tracked', ${row}.${ty("tracked")}, 'allowance', ${or("types", row, "allowance")}::text, 'carryoverMax', ${or("types", row, "carryoverMax")}::text, 'color', ${or("types", row, "color")}, 'archivedAt', ${row}.${ty("archivedAt")}, 'createdAt', ${row}.${ty("createdAt")}, 'updatedAt', ${row}.${ty("updatedAt")})`;
83902
- const requestJson = (row, approval) => `jsonb_build_object('id', ${row}.${q("id")}, 'organizationId', ${row}.${q("tenant")}, 'userId', ${row}.${q("user")}, 'typeId', ${row}.${q("type")}, 'startsOn', ${row}.${q("startsOn")}, 'endsOn', ${row}.${q("endsOn")}, 'partial', ${row}.${q("partial")}, 'amount', ${row}.${q("amount")}::text, 'note', ${or("requests", row, "note")}, 'status', ${status(row, approval)}, 'approvalId', ${or("requests", row, "approval")}, 'approvedAt', ${row}.${q("approvedAt")}, 'cancelledAt', ${row}.${q("cancelledAt")}, 'createdAt', ${row}.${q("createdAt")}, 'updatedAt', ${row}.${q("updatedAt")}${extraFieldsJson(row, extras)})`;
84190
+ const typeJson = (row) => `jsonb_build_object('id', ${row}.${ty("id")}, 'organizationId', ${row}.${ty("tenant")}, 'key', ${leaveTypeKey(ctx, row)}, 'name', ${row}.${ty("name")}, 'unit', ${row}.${ty("unit")}, 'paid', ${row}.${ty("paid")}, 'tracked', ${row}.${ty("tracked")}, 'allowance', ${or("types", row, "allowance")}::text, 'carryoverMax', ${or("types", row, "carryoverMax")}::text, 'color', ${or("types", row, "color")}, 'archivedAt', ${row}.${ty("archivedAt")}, 'createdAt', ${row}.${ty("createdAt")}, 'updatedAt', ${row}.${ty("updatedAt")})`;
84191
+ const requestJson = (row, approval) => `jsonb_build_object('id', ${row}.${q("id")}, 'organizationId', ${row}.${q("tenant")}, 'userId', ${row}.${q("user")}, 'typeId', ${row}.${q("type")}, 'startsOn', ${row}.${q("startsOn")}, 'endsOn', ${row}.${q("endsOn")}, 'partial', ${leavePartial(ctx, row)}, 'amount', ${row}.${q("amount")}::text, 'note', ${or("requests", row, "note")}, 'status', ${status(row, approval)}, 'approvalId', ${or("requests", row, "approval")}, 'approvedAt', ${row}.${q("approvedAt")}, 'cancelledAt', ${row}.${q("cancelledAt")}, 'createdAt', ${row}.${q("createdAt")}, 'updatedAt', ${row}.${q("updatedAt")}${extraFieldsJson(row, extras)})`;
83903
84192
  const requestRecord = (type, row, summary) => ctx.record({
83904
84193
  type,
83905
84194
  payload: `jsonb_build_object('organizationId', ${row}.${q("tenant")}, 'id', ${row}.${q("id")}, 'userId', ${row}.${q("user")}, 'typeId', ${row}.${q("type")}, 'startsOn', ${row}.${q("startsOn")}, 'endsOn', ${row}.${q("endsOn")}, 'amount', ${row}.${q("amount")}::text, 'approvalId', ${or("requests", row, "approval")})`,
@@ -83967,7 +84256,7 @@ ${userGrant(`${fn("decide_leave_request")}(uuid, boolean, text)`)}
83967
84256
  const tables = ctx.manages ? `create table if not exists ${types} (
83968
84257
  ${ty("id")} uuid primary key default gen_random_uuid(),
83969
84258
  ${ty("tenant")} ${idType} not null,
83970
- ${ty("key")} text not null check (${ty("key")} ~ '^[a-z][a-z0-9_-]{0,62}$'),
84259
+ ${column("types", "key", (name) => `${name} text not null check (${name} ~ '^[a-z][a-z0-9_-]{0,62}$')`).slice(1)}
83971
84260
  ${ty("name")} text not null check (length(${ty("name")}) between 1 and 100),
83972
84261
  ${ty("unit")} text not null default 'days' check (${ty("unit")} in ('days', 'hours')),
83973
84262
  ${ty("paid")} boolean not null default true,
@@ -83976,9 +84265,9 @@ ${userGrant(`${fn("decide_leave_request")}(uuid, boolean, text)`)}
83976
84265
  ${ty("archivedAt")} timestamptz,
83977
84266
  ${ty("createdAt")} timestamptz not null default now(),
83978
84267
  ${ty("updatedAt")} timestamptz not null default now(),
83979
- unique (${ty("tenant")}, ${ty("key")}),
83980
- unique (${ty("tenant")}, ${ty("id")})
83981
- );${appUniqueIndex(ctx, "types", ["tenant", "key"])}${appUniqueIndex(ctx, "types", ["tenant", "id"])}
84268
+ ${ctx.has("types", "key") ? ` unique (${ty("tenant")}, ${ty("key")}),
84269
+ ` : ""} unique (${ty("tenant")}, ${ty("id")})
84270
+ );${ctx.has("types", "key") ? appUniqueIndex(ctx, "types", ["tenant", "key"]) : ""}${appUniqueIndex(ctx, "types", ["tenant", "id"])}
83982
84271
  ${lockModuleTable(ctx, "types", { read: true })}
83983
84272
  ${renderPolicy(policy$1({
83984
84273
  table: types,
@@ -83998,7 +84287,7 @@ create table if not exists ${requests} (
83998
84287
  ${q("type")} uuid not null,
83999
84288
  ${q("startsOn")} date not null,
84000
84289
  ${q("endsOn")} date not null,
84001
- ${q("partial")} text not null default 'full' check (${q("partial")} in ('full', 'morning', 'afternoon', 'hours')),
84290
+ ${column("requests", "partial", (name) => `${name} text not null default 'full' check (${name} in ('full', 'morning', 'afternoon', 'hours'))`).slice(1)}
84002
84291
  -- Working days, or hours for an hours type, that the request books.
84003
84292
  ${q("amount")} numeric(8, 2) not null check (${q("amount")} > 0),${column("requests", "note", (name) => `${name} text check (${name} is null or length(${name}) <= 2000)`)}
84004
84293
  ${approvals === void 0 ? "" : ` ${q("approval")} uuid references ${ar} (${a("id")}) on delete set null,\n`} ${q("approvedAt")} timestamptz,${statusMode ? `${column("requests", "rejectedAt", (name) => `${name} timestamptz`)}${column("requests", "decidedBy", (name) => `${name} uuid`)}${column("requests", "decisionNote", (name) => `${name} text check (${name} is null or length(${name}) <= 2000)`)}` : ""}
@@ -84050,7 +84339,8 @@ as $$
84050
84339
  $$;
84051
84340
  ${userGrant(`${fn("leave_working_days")}(date, date)`)}
84052
84341
 
84053
- -- Creates or updates a leave type by key.
84342
+ -- Creates or updates a leave type by key. Without a key column, key is the
84343
+ -- id of the type to update, and any other key creates one.
84054
84344
  create or replace function ${fn("save_leave_type")}(tenant ${idType}, key text, name text, unit text default 'days', paid boolean default true, tracked boolean default true, allowance numeric default null, carryover_max numeric default null, color text default null)
84055
84345
  returns jsonb
84056
84346
  language plpgsql
@@ -84064,13 +84354,7 @@ begin
84064
84354
  if not (${SERVICE_CALLER$1} or ${ctx.can("tenant", "save_leave_type.tenant", manage)}) then
84065
84355
  ${forbidden("not allowed to manage leave types")}
84066
84356
  end if;${typeUnsupported("allowance", "save_leave_type.allowance", "allowance")}${typeUnsupported("carryoverMax", "save_leave_type.carryover_max", "carryover")}${typeUnsupported("color", "save_leave_type.color", "color")}
84067
- insert into ${types} (${ty("tenant")}, ${ty("key")}, ${ty("name")}, ${ty("unit")}, ${ty("paid")}, ${ty("tracked")}${typeSettings.map(([logical]) => `, ${ty(logical)}`).join("")})
84068
- values (save_leave_type.tenant, save_leave_type.key, save_leave_type.name, ${ctx.cast("types", "unit", "coalesce(save_leave_type.unit, 'days')")}, coalesce(save_leave_type.paid, true), coalesce(save_leave_type.tracked, true)${typeSettings.map(([, arg]) => `, ${arg}`).join("")})
84069
- on conflict (${ty("tenant")}, ${ty("key")}) do update
84070
- set ${ty("name")} = excluded.${ty("name")}, ${ty("unit")} = excluded.${ty("unit")}, ${ty("paid")} = excluded.${ty("paid")},
84071
- ${ty("tracked")} = excluded.${ty("tracked")}${ctx.has("types", "allowance") ? `, ${ty("allowance")} = excluded.${ty("allowance")}` : ""},
84072
- ${settingsLine === "" ? "" : `${settingsLine},\n `}${ty("archivedAt")} = null, ${ty("updatedAt")} = now()
84073
- returning * into v_row;
84357
+ ${typeUpsert}
84074
84358
  return ${typeJson("v_row")};
84075
84359
  end;
84076
84360
  $$;
@@ -84163,7 +84447,10 @@ begin
84163
84447
  end if;
84164
84448
  if v_partial in ('morning', 'afternoon') and request_leave.starts_on <> request_leave.ends_on then
84165
84449
  ${invalid("a half day starts and ends on the same date")}
84166
- end if;
84450
+ end if;${ctx.has("requests", "partial") ? "" : `
84451
+ if v_partial <> 'full' then
84452
+ ${fail$1("LEAVE_PARTIAL_UNSUPPORTED", "this leave requests table has no partial column, so a request takes whole days", "22023")}
84453
+ end if;`}
84167
84454
  v_amount := ${fn("leave_working_days")}(request_leave.starts_on, request_leave.ends_on)
84168
84455
  * case when v_partial = 'full' then 1 else 0.5 end;
84169
84456
  end if;
@@ -84179,9 +84466,9 @@ begin
84179
84466
  where r.${q("tenant")} = request_leave.tenant and r.${q("user")} = v_me
84180
84467
  and r.${q("cancelledAt")} is null and (r.${q("approvedAt")} is not null or ${approvals === void 0 ? `(${pendingIn("r", "p")})` : `p.${a("status")} = 'pending'`})
84181
84468
  and daterange(r.${q("startsOn")}, r.${q("endsOn")}, '[]') && daterange(request_leave.starts_on, request_leave.ends_on, '[]')
84182
- and not (r.${q("partial")} = 'morning' and v_partial = 'afternoon')
84469
+ ${ctx.has("requests", "partial") ? ` and not (r.${q("partial")} = 'morning' and v_partial = 'afternoon')
84183
84470
  and not (r.${q("partial")} = 'afternoon' and v_partial = 'morning')
84184
- ) then
84471
+ ` : ""} ) then
84185
84472
  ${fail$1("LEAVE_OVERLAP", "this overlaps another leave request", "23P01")}
84186
84473
  end if;${balanceCheck}
84187
84474
  ${ctx.hook("before_leave_request", [
@@ -84191,8 +84478,8 @@ begin
84191
84478
  ["date", "request_leave.ends_on"],
84192
84479
  ["numeric", "v_amount"]
84193
84480
  ])}
84194
- insert into ${requests} (${q("tenant")}, ${q("user")}, ${q("type")}, ${q("startsOn")}, ${q("endsOn")}, ${q("partial")}, ${q("amount")}${also("requests", "note")})
84195
- values (request_leave.tenant, v_me, v_type.${ty("id")}, request_leave.starts_on, request_leave.ends_on, ${ctx.cast("requests", "partial", "v_partial")}, v_amount${alsoValue("requests", "note", "nullif(trim(request_leave.note), '')")})
84481
+ insert into ${requests} (${q("tenant")}, ${q("user")}, ${q("type")}, ${q("startsOn")}, ${q("endsOn")}${also("requests", "partial")}, ${q("amount")}${also("requests", "note")})
84482
+ values (request_leave.tenant, v_me, v_type.${ty("id")}, request_leave.starts_on, request_leave.ends_on${ctx.has("requests", "partial") ? `, ${ctx.cast("requests", "partial", "v_partial")}` : ""}, v_amount${alsoValue("requests", "note", "nullif(trim(request_leave.note), '')")})
84196
84483
  returning * into v_row;${writeExtraColumns(requests, extras, "request_leave.fields", `x.${q("id")} = v_row.${q("id")}`, "v_row")}${approvals === void 0 ? "" : `
84197
84484
  v_request := ${approvals.fn("open_approval")}(
84198
84485
  request_leave.tenant, ${sqlString(LEAVE_REQUEST_SUBJECT)}, v_row.${q("id")}::text, 'approve',
@@ -105922,7 +106209,8 @@ const NAMES$35 = {
105922
106209
  "prefix",
105923
106210
  "validDays",
105924
106211
  "extraColumns",
105925
- "lineExtraColumns"
106212
+ "lineExtraColumns",
106213
+ "lineRates"
105926
106214
  ],
105927
106215
  tables: {
105928
106216
  quotes: {
@@ -125984,7 +126272,8 @@ const NAMES$8 = {
125984
126272
  "userTimeZone",
125985
126273
  "owner",
125986
126274
  "overlap",
125987
- "timers"
126275
+ "timers",
126276
+ "lockedColumns"
125988
126277
  ],
125989
126278
  tables: {
125990
126279
  entries: {
@@ -126106,6 +126395,7 @@ function build$8(ctx) {
126106
126395
  const owner = timeOwner(ctx, statusMode);
126107
126396
  const { employeeMode, staff, eOwner, tOwner, ownerVar, sheetUser, myEmployee, employeeOf, employeeOfUser, ownedByMe, sheetUserJson } = owner;
126108
126397
  const ended = (alias) => entryEnded(ctx, alias);
126398
+ const locked = lockedColumns(ctx, subjectColumns, employeeMode, Object.keys(NAMES$8.tables["entries"]?.columns ?? {}));
126109
126399
  const running = (alias) => durationMode ? `${alias}.${ctx.col("entries", "runningSince")} is not null` : `${alias}.${ctx.col("entries", "endedAt")} is null`;
126110
126400
  const stop = (alias, at) => durationMode ? `${ctx.col("entries", "seconds")} = coalesce(${alias}.${ctx.col("entries", "seconds")}, 0) + greatest(extract(epoch from ${at} - ${alias}.${ctx.col("entries", "runningSince")})::bigint, 0), ${ctx.col("entries", "runningSince")} = null` : `${ctx.col("entries", "endedAt")} = ${at}`;
126111
126401
  const endColumn = durationMode ? ctx.col("entries", "seconds") : ctx.col("entries", "endedAt");
@@ -126292,11 +126582,11 @@ security definer
126292
126582
  set search_path = ''
126293
126583
  as $$
126294
126584
  begin
126295
- ${employeeMode ? "" : ` -- employees keeps employee_id current, also on a locked week.
126296
- if tg_op = 'UPDATE' and (to_jsonb(new) - 'employee_id') = (to_jsonb(old) - 'employee_id') then
126585
+ -- Only a change to logged time (options.lockedColumns) touches the week.
126586
+ if tg_op = 'UPDATE' and ${locked.length === 0 ? "true" : `(${locked.map((column) => `new.${column}`).join(", ")}) is not distinct from (${locked.map((column) => `old.${column}`).join(", ")})`} then
126297
126587
  return new;
126298
126588
  end if;
126299
- `} if tg_op in ('UPDATE', 'DELETE') and ${fn("time_week_locked")}(old.${e("tenant")}, old.${eOwner}, old.${e("startedAt")}) then
126589
+ if tg_op in ('UPDATE', 'DELETE') and ${fn("time_week_locked")}(old.${e("tenant")}, old.${eOwner}, old.${e("startedAt")}) then
126300
126590
  ${fail$1("TIME_PERIOD_LOCKED", "this week's timesheet is submitted or approved", "55000")}
126301
126591
  end if;
126302
126592
  if tg_op in ('INSERT', 'UPDATE') and ${fn("time_week_locked")}(new.${e("tenant")}, new.${eOwner}, new.${e("startedAt")}) then
@@ -139893,7 +140183,9 @@ function unusedColumns(name, ctx) {
139893
140183
  */
139894
140184
  function contextOf(name, layout) {
139895
140185
  try {
139896
- return moduleContext(name, layout, Object.keys(layout.modules));
140186
+ const ctx = moduleContext(name, layout, Object.keys(layout.modules));
140187
+ unusedColumns(name, ctx);
140188
+ return ctx;
139897
140189
  } catch {
139898
140190
  return;
139899
140191
  }
@@ -139960,9 +140252,12 @@ function adoptedTables(modules, ownTables, views = {}) {
139960
140252
  * write as text. `upgrade` refuses those configs. A column missing from a
139961
140253
  * block's own logical table isn't one: the block adds it.
139962
140254
  */
139963
- function adoptedColumnProblems(modules, files, schemas, ownTables, subjects) {
140255
+ function adoptedColumnProblems(modules, files, schemas, ownTables, subjects, accessProvider) {
139964
140256
  const declared = declaredTableColumns(files, schemas);
139965
- const context = subjects === void 0 ? {} : { subjects };
140257
+ const context = {
140258
+ ...subjects === void 0 ? {} : { subjects },
140259
+ ...accessProvider === void 0 ? {} : { accessProvider }
140260
+ };
139966
140261
  return [...adoptedTables(modules, ownTables, context).flatMap((table) => {
139967
140262
  const columns = declared.get(`${table.schema}.${table.table}`);
139968
140263
  if (columns === void 0 || SQL_MODULES[table.module]?.names?.tables[table.logical] !== void 0) return [];