better-supabase 0.34.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 (154) hide show
  1. package/dist/ai-sdk/agents/index.d.ts +2 -2
  2. package/dist/{app-tables-Don-aNOB.d.ts → app-tables-X3yzJljM.d.ts} +1 -1
  3. package/dist/{authorization-DpVtxuKM.d.ts → authorization-D1P3VBOd.d.ts} +37 -0
  4. package/dist/{automations-Bw5cX7oj.js → automations-D4QTP8nI.js} +2 -1
  5. package/dist/{bind-BA05aoY9.d.ts → bind-Bvv-Zrdh.d.ts} +1 -1
  6. package/dist/{block-env-UX42PHLP.d.ts → block-env-h_uPl2f_.d.ts} +3 -3
  7. package/dist/{block-tables-Bre1zjau.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/entitlements/index.d.ts +2 -2
  22. package/dist/blocks/forms/index.d.ts +1 -1
  23. package/dist/blocks/inbox/index.d.ts +4 -4
  24. package/dist/blocks/index.d.ts +1 -1
  25. package/dist/blocks/invoices/index.d.ts +4 -0
  26. package/dist/blocks/invoices/index.js +6 -3
  27. package/dist/blocks/messaging/index.d.ts +4 -4
  28. package/dist/blocks/mfa/index.d.ts +1 -1
  29. package/dist/blocks/notifications/index.d.ts +3 -3
  30. package/dist/blocks/onboarding/index.d.ts +1 -1
  31. package/dist/blocks/organizations/index.d.ts +2 -2
  32. package/dist/blocks/permissions/index.d.ts +1 -1
  33. package/dist/blocks/push/index.d.ts +1 -1
  34. package/dist/blocks/quotes/index.js +1 -1
  35. package/dist/blocks/reactions/index.d.ts +3 -3
  36. package/dist/blocks/saved-views/index.d.ts +1 -1
  37. package/dist/blocks/search/index.d.ts +2 -2
  38. package/dist/blocks/sessions/index.d.ts +1 -1
  39. package/dist/blocks/settings/index.d.ts +1 -1
  40. package/dist/blocks/subjects/index.d.ts +1 -1
  41. package/dist/blocks/tags/index.d.ts +1 -1
  42. package/dist/blocks/time-tracking/index.js +1 -1
  43. package/dist/blocks/undo/index.d.ts +1 -1
  44. package/dist/blocks/usage/index.d.ts +1 -1
  45. package/dist/blocks/workflow-editor/index.d.ts +3 -3
  46. package/dist/blocks/workflows/index.d.ts +3 -3
  47. package/dist/claims/index.d.ts +3 -3
  48. package/dist/cli/add-BaB3y1lv.js +1 -0
  49. package/dist/cli/{add-THXE7juv.js → add-CYreXA68.js} +9 -9
  50. package/dist/cli/{add-DoEtJhZG.js → add-DzgsOE8V.js} +2 -2
  51. package/dist/cli/{app-table-files-BqLd5TuX.js → app-table-files-BnISa3uY.js} +2 -2
  52. package/dist/cli/{backfill-D-2W0fNT.js → backfill-BLLTSDSa.js} +1 -1
  53. package/dist/cli/bin.js +1 -1
  54. package/dist/cli/{blocks-XwUHeyUH.js → blocks-CpRvI7x8.js} +1 -1
  55. package/dist/cli/{blocks-BVU_FoLo.js → blocks-uzh1g_0v.js} +1 -1
  56. package/dist/cli/{cache-D4nwCBXc.js → cache-BPWC7tGD.js} +1 -1
  57. package/dist/cli/{codemod-Dh4lf_k4.js → codemod-CbJVS_kG.js} +1 -1
  58. package/dist/cli/{content-mapper-CwFH_PEn.js → content-mapper-Cjkm2Sg3.js} +2 -2
  59. package/dist/cli/{doctor-CyAMbZ_s.js → doctor-D94FEJZs.js} +19 -19
  60. package/dist/cli/{gen-EAUNnUY7.js → gen-Cd0VNDjE.js} +11 -11
  61. package/dist/cli/index.d.ts +1 -1
  62. package/dist/cli/index.js +6 -6
  63. package/dist/cli/{init-BRmmmGHJ.js → init-Co1N9ZoA.js} +8 -8
  64. package/dist/cli/{live-CV9mn-xC.js → live-NFNeZsP7.js} +2 -2
  65. package/dist/cli/{mcp-CnaxcLWa.js → mcp-WZ8t7NMz.js} +2 -2
  66. package/dist/cli/{metadata-CFQGBR5E.js → metadata-BzMkmrZR.js} +3 -3
  67. package/dist/cli/{migrate-z5oHDGNs.js → migrate-C9gyDAV7.js} +1 -1
  68. package/dist/cli/{migration-safety-BtAPMEZa.js → migration-safety-BNi8PIiM.js} +1 -1
  69. package/dist/cli/{migrations-CNa62JSi.js → migrations-Ds0J_TmZ.js} +2 -2
  70. package/dist/cli/{module-migration-CKJ8kRm1.js → module-migration-hFrlzQZ5.js} +2 -2
  71. package/dist/cli/powersync-J2Kms2NT.js +1 -0
  72. package/dist/cli/{powersync-BgoAWeRT.js → powersync-oFiwgsBi.js} +3 -3
  73. package/dist/cli/{print-CoqKHoy0.js → print-BtreoJSm.js} +2 -2
  74. package/dist/cli/{providers-CfbFxUOQ.js → providers-Be2dgyuR.js} +1 -1
  75. package/dist/cli/{prune-workflows-BigCoXLw.js → prune-workflows-BPxgRrqY.js} +1 -1
  76. package/dist/cli/{remove-C9zwn-Kk.js → remove-B4ad996E.js} +5 -5
  77. package/dist/cli/{render-DQCU_kBW.js → render-C-Mfq-o3.js} +3 -3
  78. package/dist/cli/{run-DOD00FFl.js → run-D2nuyyPo.js} +47 -39
  79. package/dist/cli/{run-CVaBuT18.js → run-cLdnJHH0.js} +25 -25
  80. package/dist/cli/{shared-COtj7l3r.js → shared-DCHxLAEL.js} +1 -1
  81. package/dist/cli/{snapshot-BvlEmTB0.js → snapshot-CloKPNxv.js} +2 -2
  82. package/dist/cli/{source-BhZRCitG.js → source-Bwyp18Rj.js} +1 -1
  83. package/dist/cli/{spec-DsMWuJLv.js → spec-DAUF4ybu.js} +2 -2
  84. package/dist/cli/{spec-Bo2wIViH.js → spec-DsVq4_qV.js} +1 -1
  85. package/dist/cli/{sql-layout-CA7xgRjR.js → sql-layout-CHpEL0oq.js} +3 -3
  86. package/dist/cli/{sync-D9xSGdzO.js → sync-DZu1r34s.js} +4 -4
  87. package/dist/cli/{upgrade-XK_CQKVJ.js → upgrade-A-BALvp3.js} +2 -2
  88. package/dist/cli/{upgrade-Ykf0LLEB.js → upgrade-Bpvi70zm.js} +5 -5
  89. package/dist/cli/{version-Dfdz7KSh.js → version-B59mZJoy.js} +1 -1
  90. package/dist/client/index.d.ts +5 -5
  91. package/dist/client/native/index.d.ts +4 -4
  92. package/dist/config/index.d.ts +2 -2
  93. package/dist/config/index.js +4 -4
  94. package/dist/{config-Bu6pwqcO.js → config-BZWSFxkG.js} +3 -3
  95. package/dist/{config-MDRA2sre.js → config-DQP0IvDX.js} +1 -1
  96. package/dist/{context-BGC0J3t9.d.ts → context-CderJRZf.d.ts} +1 -1
  97. package/dist/contract/index.d.ts +3 -3
  98. package/dist/{controller-CQrkLoRX.d.ts → controller-DaWA9eWS.d.ts} +1 -1
  99. package/dist/create/index.d.ts +3 -3
  100. package/dist/create/index.js +3 -3
  101. package/dist/create/lite/index.d.ts +3 -3
  102. package/dist/create/lite/index.js +2 -2
  103. package/dist/{entitlements-BOWTZaRf.d.ts → entitlements-BefkpQIz.d.ts} +1 -1
  104. package/dist/{field-errors-DxPZYw2m.d.ts → field-errors-D1meOs_H.d.ts} +4 -4
  105. package/dist/{index-QTZIopQj.d.ts → index-BQlLxOj5.d.ts} +1 -1
  106. package/dist/{index-CJB50jzQ.d.ts → index-BbDiBiKt.d.ts} +4 -4
  107. package/dist/{index-Bz0WLuh_.d.ts → index-C13UgV67.d.ts} +2 -2
  108. package/dist/{index-Bhkag9ZE.d.ts → index-ChLuLxy-.d.ts} +6 -6
  109. package/dist/{index-CeUwyJ3Z.d.ts → index-D9aV0Fvx.d.ts} +2 -2
  110. package/dist/{index-BfU0KR0X.d.ts → index-DXUiRyEk.d.ts} +1 -1
  111. package/dist/{index-DNAkWDXc.d.ts → index-ZQZMQF4l.d.ts} +1 -1
  112. package/dist/{instances-D31jrmKh.js → instances-D9YrkoAy.js} +28 -1
  113. package/dist/mapper/bin.js +5 -5
  114. package/dist/mcp/index.d.ts +1 -1
  115. package/dist/next/index.d.ts +4 -4
  116. package/dist/{operations-BG6prEnh.d.ts → operations-t_hlXkS4.d.ts} +1 -1
  117. package/dist/{options-CgMiQGOF.js → options-C9bp3SEA.js} +2 -0
  118. package/dist/{options-Sq4bYbf5.js → options-CuaWhsQS.js} +2 -0
  119. package/dist/{options-DjFbIRgV.js → options-DjdxZgHi.js} +2 -1
  120. package/dist/{options-C-NFS6e3.js → options-DxgZ8tVc.js} +2 -1
  121. package/dist/otel/index.js +4 -4
  122. package/dist/{permissions-CoHsUtZS.d.ts → permissions-C8p6RlIZ.d.ts} +1 -1
  123. package/dist/{ports-XvgCe7ey.d.ts → ports-C-8uduFM.d.ts} +1 -1
  124. package/dist/powersync/index.d.ts +2 -2
  125. package/dist/preset/index.d.ts +3 -3
  126. package/dist/preset/index.js +3 -3
  127. package/dist/{preset-om2rbdYw.js → preset-B_sSI9vg.js} +2 -2
  128. package/dist/{project-B7nqCzn5.js → project-DVlXQGEp.js} +5 -5
  129. package/dist/{push-token-kcc04ZaS.d.ts → push-token-D41lOoE8.d.ts} +1 -1
  130. package/dist/react/index.d.ts +5 -5
  131. package/dist/react/native/index.d.ts +1 -1
  132. package/dist/react/server.d.ts +5 -5
  133. package/dist/realtime/index.d.ts +3 -3
  134. package/dist/records/index.d.ts +3 -3
  135. package/dist/{resolved-names-DYYyh35i.js → resolved-names-h-3UbKcw.js} +1 -1
  136. package/dist/server/index.d.ts +3 -3
  137. package/dist/solid/index.d.ts +5 -5
  138. package/dist/sql/index.d.ts +5 -5
  139. package/dist/sql/index.js +2 -2
  140. package/dist/{sql-DdtukoIm.js → sql-C9nO-Mat.js} +250 -88
  141. package/dist/ssr/index.d.ts +1 -1
  142. package/dist/svelte/index.d.ts +5 -5
  143. package/dist/{tenant-DkKbvK5T.d.ts → tenant-gezshhcs.d.ts} +1 -1
  144. package/dist/testing/index.d.ts +3 -3
  145. package/dist/testing/index.js +1 -1
  146. package/dist/{topic-B6zuexk7.d.ts → topic-BVq5RdsI.d.ts} +1 -1
  147. package/dist/{types-BvHw2cCS.d.ts → types-hTj5OuFo.d.ts} +2 -2
  148. package/dist/vue/index.d.ts +5 -5
  149. package/dist/{watch-topic-YYSVJGDY.d.ts → watch-topic-BOclyLFd.d.ts} +1 -1
  150. package/dist/yjs/index.d.ts +1 -1
  151. package/package.json +1 -1
  152. package/schemas/config-v1.json +36 -0
  153. package/dist/cli/add-C13ZqJ_N.js +0 -1
  154. package/dist/cli/powersync-DoCruiOt.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,7 +45,7 @@ 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";
@@ -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) => {
@@ -12478,12 +12478,12 @@ ${harness(ctx, names)}`;
12478
12478
  // src/sql/modules/usage-meters.ts
12479
12479
  const METER$1 = `'^[a-z][a-z0-9_.:-]{0,63}$'`;
12480
12480
  const METER_KEY$1 = /^[a-z][a-z0-9_.:-]{0,63}$/;
12481
- const IDENT$7 = /^[a-z_][a-z0-9_$]{0,62}$/;
12481
+ const IDENT$8 = /^[a-z_][a-z0-9_$]{0,62}$/;
12482
12482
  function meterTableOf(where, option) {
12483
12483
  const text = (name) => {
12484
12484
  const value = option[name];
12485
12485
  if (value === void 0) return;
12486
- 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`);
12487
12487
  return value;
12488
12488
  };
12489
12489
  for (const name of Object.keys(option)) if (![
@@ -26250,6 +26250,28 @@ ${userGrant(`${fn("time_is_my_employee")}(${ctx.idType}, uuid)`)}
26250
26250
  ` : ""
26251
26251
  };
26252
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
+ }
26253
26275
  // src/sql/modules/billable-time.ts
26254
26276
  const GROUPINGS = [
26255
26277
  "subject",
@@ -33667,6 +33689,55 @@ const productExtras = (ctx) => ctx.extraColumns("products", [
33667
33689
  "status",
33668
33690
  "fields"
33669
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);
33670
33741
  function storefrontOption(ctx) {
33671
33742
  const value = ctx.text("storefront", "private");
33672
33743
  if (value !== "public" && value !== "private") throw new TypeError("blocks.catalog.options.storefront must be \"public\" or \"private\"");
@@ -33714,7 +33785,16 @@ function productFunctions(ctx, names) {
33714
33785
  const kind = ctx.has("products", "kind");
33715
33786
  const governed = machineGoverns$1(ctx);
33716
33787
  const extras = productExtras(ctx);
33717
- 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
+ `;
33718
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");
33719
33799
  const inventory = ctx.installed("inventory") ? ctx.of("inventory") : void 0;
33720
33800
  const historyCheck = (variantFilter, code) => inventory === void 0 ? "" : `
@@ -33722,9 +33802,10 @@ function productFunctions(ctx, names) {
33722
33802
  ${fail$1(code, "the stock ledger has movements for this record; archive it instead", "23503")}
33723
33803
  end if;`;
33724
33804
  return `
33725
- -- Creates a product (product null) or updates one. Returns its id, slug and status.
33726
- ${extraFieldsArg(extras).drop(fn("save_product"), saveArgs)}
33727
- 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})
33728
33809
  returns jsonb
33729
33810
  language plpgsql
33730
33811
  security definer
@@ -33762,7 +33843,7 @@ begin
33762
33843
  end if;
33763
33844
  exception when unique_violation then
33764
33845
  ${fail$1("CATALOG_SLUG_TAKEN", "another product has this slug", "23505")}
33765
- 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`)}
33766
33847
  if v_created then
33767
33848
  ${ctx.record({
33768
33849
  type: "product.created",
@@ -33971,6 +34052,10 @@ function variantFunctions(ctx, names, historyCheck) {
33971
34052
  const p = (column) => ctx.col("products", column);
33972
34053
  const v = (column) => ctx.col("variants", column);
33973
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)");
33974
34059
  const tracking = optional("trackInventory") ? "" : `
33975
34060
  if save_variant.track_inventory is not null then
33976
34061
  ${fail$1("CATALOG_TRACK_INVENTORY_UNSUPPORTED", "this catalog tracks inventory per product, not per variant", "22023")}
@@ -34031,7 +34116,9 @@ function variantFunctions(ctx, names, historyCheck) {
34031
34116
  return `
34032
34117
  -- Creates a variant (variant null) or updates one. option_values holds one
34033
34118
  -- option value id per product option; no two variants share a combination.
34034
- 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})
34035
34122
  returns jsonb
34036
34123
  language plpgsql
34037
34124
  security definer
@@ -34061,8 +34148,8 @@ ${valueChecks.check}
34061
34148
  if v_created then
34062
34149
  select max(${rank.order(`x.${v("rank")}`)}) into v_last from ${variants} x where x.${v("product")} = save_variant.product;
34063
34150
  v_rank := ${rank.after("v_last")};
34064
- insert into ${variants} (${v("tenant")}, ${v("product")}, ${columns.map(([column]) => v(column)).join(", ")}, ${v("rank")})
34065
- 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})
34066
34153
  returning ${v("id")} into v_id;
34067
34154
  else
34068
34155
  update ${variants} x set ${columns.map(([column, value]) => `${v(column)} = ${value}`).join(", ")}, ${v("updatedAt")} = now()
@@ -34070,7 +34157,7 @@ ${valueChecks.check}
34070
34157
  returning x.${v("rank")} into v_rank;
34071
34158
  if not found then
34072
34159
  ${fail$1("CATALOG_VARIANT_NOT_FOUND", "variant not found", "P0002")}
34073
- end if;
34160
+ end if;${writeExtraColumns(variants, extras, "save_variant.fields", `x.${v("id")} = v_id`).replaceAll("\n ", "\n ")}
34074
34161
  end if;
34075
34162
  exception when unique_violation then
34076
34163
  ${fail$1("CATALOG_SKU_TAKEN", "another variant has this SKU", "23505")}
@@ -34094,10 +34181,10 @@ ${valueChecks.write}
34094
34181
  })}
34095
34182
  end if;
34096
34183
  ${ctx.hook("after_variant_save", [["uuid", "v_id"], ["boolean", "v_created"]])}
34097
- 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)`};
34098
34185
  end;
34099
34186
  $$;
34100
- ${userGrant(`${fn("save_variant")}(uuid, uuid, text, uuid[], text, text, integer, boolean, boolean)`)}
34187
+ ${userGrant(`${fn("save_variant")}(${variantArgs}${extraArg.type})`)}
34101
34188
 
34102
34189
  -- Sets a variant's rank key among the product's variants.
34103
34190
  create or replace function ${fn("rank_variant")}(variant uuid, rank text)
@@ -35303,10 +35390,16 @@ ${userGrant(`${fn("set_product_categories")}(uuid, uuid[])`)}
35303
35390
  ) then
35304
35391
  ${fail$1("CATALOG_CATEGORY_CYCLE", "a category can't sit under itself", "22023")}
35305
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)");
35306
35397
  return `
35307
35398
  -- Creates a category (category null) or updates one, under parent (null
35308
- -- for the top level). A new category goes after its siblings.
35309
- 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})
35310
35403
  returns jsonb
35311
35404
  language plpgsql
35312
35405
  security definer
@@ -35331,8 +35424,8 @@ begin
35331
35424
  select max(${rank.order(`x.${k("rank")}`)}) into v_last from ${categories} x
35332
35425
  where x.${k("tenant")} = save_category.tenant and x.${k("parent")} is not distinct from save_category.parent;
35333
35426
  v_rank := ${rank.after("v_last")};
35334
- insert into ${categories} (${k("tenant")}, ${k("parent")}, ${k("name")}, ${k("slug")}, ${k("description")}, ${k("rank")})
35335
- 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})
35336
35429
  returning ${k("id")} into v_id;
35337
35430
  else
35338
35431
  update ${categories} x set ${k("parent")} = save_category.parent, ${k("name")} = save_category.name, ${k("slug")} = v_slug,
@@ -35341,15 +35434,15 @@ begin
35341
35434
  returning x.${k("rank")} into v_rank;
35342
35435
  if not found then
35343
35436
  ${fail$1("CATALOG_CATEGORY_NOT_FOUND", "category not found", "P0002")}
35344
- end if;
35437
+ end if;${writeExtraColumns(categories, extras, "save_category.fields", `x.${k("id")} = v_id`)}
35345
35438
  end if;
35346
35439
  exception when unique_violation then
35347
35440
  ${fail$1("CATALOG_SLUG_TAKEN", "another category has this slug", "23505")}
35348
35441
  end;
35349
- 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)`};
35350
35443
  end;
35351
35444
  $$;
35352
- ${userGrant(`${fn("save_category")}(${ctx.idType}, uuid, uuid, text, text, text)`)}
35445
+ ${userGrant(`${fn("save_category")}(${categoryArgs}${extraArg.type})`)}
35353
35446
 
35354
35447
  -- Moves a category under parent (null for the top level) at rank, a key
35355
35448
  -- from rankBetween over its new siblings' keys.
@@ -35766,6 +35859,8 @@ const NAMES$94 = {
35766
35859
  options: [
35767
35860
  "storefront",
35768
35861
  "extraColumns",
35862
+ "variantExtraColumns",
35863
+ "categoryExtraColumns",
35769
35864
  "locales",
35770
35865
  "rankType"
35771
35866
  ],
@@ -36122,7 +36217,7 @@ create table if not exists ${t("variants")} (
36122
36217
  ${c("variants", "updatedAt")} timestamptz not null default now(),
36123
36218
  unique (${c("variants", "tenant")}, ${c("variants", "sku")})
36124
36219
  );
36125
- 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))}
36126
36221
  ${lockTable(t("variants"), { read: true })}
36127
36222
  ${read("variants")}
36128
36223
 
@@ -36177,7 +36272,7 @@ create table if not exists ${t("categories")} (
36177
36272
  ${c("categories", "updatedAt")} timestamptz not null default now(),
36178
36273
  unique (${c("categories", "tenant")}, ${c("categories", "slug")})
36179
36274
  );
36180
- 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))}
36181
36276
  ${lockTable(t("categories"), { read: true })}
36182
36277
  ${read("categories")}
36183
36278
 
@@ -36301,6 +36396,7 @@ function contract$86(ctx) {
36301
36396
  "text",
36302
36397
  "text",
36303
36398
  "text",
36399
+ ...productSettingTypes(ctx),
36304
36400
  ...extraFieldsArg(productExtras(ctx)).contract
36305
36401
  ],
36306
36402
  returns: "jsonb"
@@ -36340,7 +36436,8 @@ function contract$86(ctx) {
36340
36436
  "text",
36341
36437
  "integer",
36342
36438
  "boolean",
36343
- "boolean"
36439
+ "boolean",
36440
+ ...extraFieldsArg(variantExtras(ctx)).contract
36344
36441
  ],
36345
36442
  returns: "jsonb"
36346
36443
  },
@@ -36405,7 +36502,8 @@ function contract$86(ctx) {
36405
36502
  "uuid",
36406
36503
  "text",
36407
36504
  "text",
36408
- "text"
36505
+ "text",
36506
+ ...extraFieldsArg(categoryExtras(ctx)).contract
36409
36507
  ],
36410
36508
  returns: "jsonb"
36411
36509
  },
@@ -50081,7 +50179,20 @@ function lineTableSpec(name) {
50081
50179
  * gives when the app's table lacks it.
50082
50180
  */
50083
50181
  function lineColumn(ctx, lines, alias, column) {
50084
- 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";
50085
50196
  }
50086
50197
  /** The columns a copy of lines writes, of the ones line table `lines` has. */
50087
50198
  function lineCopyColumns(ctx, lines) {
@@ -50143,7 +50254,7 @@ function lineItemsSql(ctx, items, options) {
50143
50254
  ["taxRateBps", "coalesce((x.value ->> 'taxRateBps')::integer, 0)"],
50144
50255
  ["taxCode", "x.value ->> 'taxCode'"],
50145
50256
  ["position", "x.ordinality::integer"]
50146
- ].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]);
50147
50258
  const extras = items.extras ?? [];
50148
50259
  const extrasInsert = insertExtraColumns(t, extras, "(case when jsonb_typeof(x.value -> 'fields') = 'object' then x.value -> 'fields' end)");
50149
50260
  const manages = ctx.manages ? `create table if not exists ${t} (
@@ -51227,7 +51338,8 @@ const NAMES$81 = {
51227
51338
  "prefix",
51228
51339
  "readAll",
51229
51340
  "extraColumns",
51230
- "lineExtraColumns"
51341
+ "lineExtraColumns",
51342
+ "lineRates"
51231
51343
  ],
51232
51344
  tables: {
51233
51345
  deals: {
@@ -57174,8 +57286,8 @@ ${subtree}
57174
57286
  $$;
57175
57287
  revoke execute on function ${fn("drive_subtree")}(uuid) from public, anon, authenticated;
57176
57288
 
57177
- -- Whether the node or anything under it is under a legal hold, which purge
57178
- -- 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.
57179
57291
  create or replace function ${fn("drive_node_held")}(node uuid)
57180
57292
  returns boolean
57181
57293
  language sql
@@ -57185,7 +57297,8 @@ set search_path = ''
57185
57297
  as $$
57186
57298
  select exists (
57187
57299
  select 1 from ${T} h
57188
- 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)))
57189
57302
  and ${held("h")}
57190
57303
  )
57191
57304
  $$;
@@ -57562,7 +57675,7 @@ revoke execute on function ${fn("drive_check_parent")}(${ctx.idType}, uuid, uuid
57562
57675
  drop function if exists ${fn("drive_insert_node")}(${ctx.idType}, uuid, uuid, text, text, text, jsonb);
57563
57676
  drop function if exists ${fn("drive_insert_node")}(${ctx.idType}, uuid, text, text, text, jsonb);
57564
57677
  -- Inserts a node after its siblings. Extra columns come from fields, or
57565
- -- 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}.` : ""}
57566
57679
  create or replace function ${fn("drive_insert_node")}(tenant ${ctx.idType}, drive uuid, parent uuid, kind text, name text, conflict text, fields jsonb)
57567
57680
  returns ${T}
57568
57681
  language plpgsql
@@ -57595,10 +57708,10 @@ begin
57595
57708
  insert into ${T} (${insertColumns.join(", ")})
57596
57709
  values (${insertValues.join(", ")})
57597
57710
  returning * into v_node;
57598
- 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
57599
57712
  ${directGrant("v_node", sqlString(roles.top), "auth.uid()")}
57600
57713
  end if;
57601
- ${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"))}
57602
57715
  ${ctx.hook("after_drive_node_create", [["uuid", `v_node.${n("id")}`]])}
57603
57716
  return v_node;
57604
57717
  end;
@@ -80451,6 +80564,8 @@ const INVITATIONS = {
80451
80564
  build: invitationsSql
80452
80565
  };
80453
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") : [];
80454
80569
  /**
80455
80570
  * How the invoices table holds a company, contact or origin: a type and an id
80456
80571
  * column (`pair`), only an id column of one fixed type, such as a foreign key
@@ -80515,7 +80630,7 @@ function invoiceFunctions(ctx, n) {
80515
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'"}`;
80516
80631
  const chargesJson = (alias) => charges ? `,
80517
80632
  'charged_total', ${charged(alias)}::text,
80518
- '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)` : "";
80519
80634
  const row = (alias) => `${ctx.rowJson("invoices", alias, { as: int8Text8 })} || ${int8Text(alias, int8)} || jsonb_build_object(
80520
80635
  'balance', ${balance(alias)}::text${missingKeys(alias)}${chargesJson(alias)},
80521
80636
  'overdue', ${st(`${alias}.${i("status")}`, ["issued", "partially_paid"])} and ${alias}.${i("dueOn")} < current_date,
@@ -80650,11 +80765,15 @@ ${userGrant(`${fn("invoice_from_quote")}(uuid, integer)`)}
80650
80765
  ...ctx.has("charges", "description") ? ["nullif(trim(add_invoice_charge.description), '')"] : [],
80651
80766
  ...ctx.has("charges", "createdBy") ? ["auth.uid()"] : []
80652
80767
  ];
80768
+ const chargeFields = extraFieldsArg(n.chargeExtras);
80769
+ const chargeExtras = insertExtraColumns(t("charges"), n.chargeExtras, "coalesce(add_invoice_charge.fields, '{}'::jsonb)");
80653
80770
  const addCharge = charges ? `
80771
+ ${chargeFields.drop(fn("add_invoice_charge"), "uuid, bigint, text, text")}
80654
80772
  -- Adds a charge on top of an issued invoice's total, such as collection
80655
80773
  -- costs or a late fee, in the invoice's currency. It raises the balance, so
80656
- -- a paid invoice is open again until the charge is paid too.
80657
- 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})
80658
80777
  returns jsonb
80659
80778
  language plpgsql
80660
80779
  security definer
@@ -80681,14 +80800,14 @@ begin
80681
80800
  if upper(add_invoice_charge.currency) is distinct from v_row.${i("currency")} then
80682
80801
  ${fail$1("INVOICE_CURRENCY_MISMATCH", "a charge must be in the invoice's currency", "22023")}
80683
80802
  end if;
80684
- insert into ${t("charges")} (${chargeColumns.join(", ")})
80685
- values (${chargeValues.join(", ")})
80803
+ insert into ${t("charges")} (${chargeColumns.join(", ")}${chargeExtras.columns})
80804
+ values (${chargeValues.join(", ")}${chargeExtras.values})
80686
80805
  returning ${ch("id")} into v_charge;${settle("v_row")}
80687
80806
  ${record("invoice.charged", "v_row", `, 'chargeId', v_charge, 'amount', add_invoice_charge.amount::text, 'balance', ${balance("v_row")}::text`, true)}
80688
80807
  return ${row("v_row")};
80689
80808
  end;
80690
80809
  $$;
80691
- ${userGrant(`${fn("add_invoice_charge")}(uuid, bigint, text, text)`)}
80810
+ ${userGrant(`${fn("add_invoice_charge")}(uuid, bigint, text, text${chargeFields.type})`)}
80692
80811
  ` : "";
80693
80812
  const kindTable = (kind) => `(select * from ${t("invoices")} k where ${kd(`k.${i("kind")}`, [kind])})`;
80694
80813
  return `
@@ -81125,6 +81244,8 @@ const NAMES$57 = {
81125
81244
  "termsDays",
81126
81245
  "extraColumns",
81127
81246
  "lineExtraColumns",
81247
+ "lineRates",
81248
+ "chargeExtraColumns",
81128
81249
  "totals"
81129
81250
  ],
81130
81251
  tables: {
@@ -81232,7 +81353,7 @@ function tables$16(ctx, n) {
81232
81353
  create table if not exists ${t("charges")} (
81233
81354
  ${chargeColumns.join(",\n ")}
81234
81355
  );
81235
- 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))}
81236
81357
  ${lockModuleTable(ctx, "charges", { read: true })}
81237
81358
  ${renderPolicy(policy$1({
81238
81359
  table: t("charges"),
@@ -81329,6 +81450,7 @@ function build$55(ctx) {
81329
81450
  "charged_total"
81330
81451
  ]),
81331
81452
  lineExtras: lineExtraColumns(ctx),
81453
+ chargeExtras: chargeExtraColumns(ctx),
81332
81454
  appTotals: invoiceTotals(ctx) === "app"
81333
81455
  };
81334
81456
  return `${schemaPreamble(ctx)}
@@ -81394,7 +81516,8 @@ function contract$49(ctx) {
81394
81516
  "uuid",
81395
81517
  "bigint",
81396
81518
  "text",
81397
- "text"
81519
+ "text",
81520
+ ...extraFieldsArg(chargeExtraColumns(ctx)).contract
81398
81521
  ],
81399
81522
  returns: "jsonb"
81400
81523
  }] : [],
@@ -83350,6 +83473,16 @@ const LEASES = {
83350
83473
  build: build$52
83351
83474
  };
83352
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
+ }
83353
83486
  /** The share-links subject of an organization's leave feed. */
83354
83487
  const LEAVE_FEED_SUBJECT = "leave_feed";
83355
83488
  const read = (ctx) => ctx.permission("read", moduleOperations("leave").read);
@@ -83412,7 +83545,7 @@ begin
83412
83545
  select jsonb_agg(x.item order by x.starts_on, x.id)
83413
83546
  from (
83414
83547
  select jsonb_build_object('id', ${q("id")}, 'userId', ${q("user")}, 'typeId', ${q("type")}, 'type', ${ty("name")}, 'unit', ${ty("unit")},
83415
- '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,
83416
83549
  ${q("startsOn")} as starts_on, ${q("id")} as id
83417
83550
  from ${ctx.table("requests")} r
83418
83551
  join ${ctx.table("types")} t on ${ty("id")} = ${q("type")}
@@ -83580,7 +83713,7 @@ begin
83580
83713
  ${invalid("name user_id")}
83581
83714
  end if;
83582
83715
  select coalesce(jsonb_agg(jsonb_build_object(
83583
- '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")},
83584
83717
  'userId', v_user, 'period', v_period,
83585
83718
  'granted', ${decimalText("coalesce(b.granted, 0)")},
83586
83719
  'taken', ${decimalText("coalesce(b.taken, 0)")},
@@ -83898,6 +84031,7 @@ const NAMES$53 = {
83898
84031
  updatedAt: "updated_at"
83899
84032
  },
83900
84033
  optional: [
84034
+ "key",
83901
84035
  "allowance",
83902
84036
  "carryoverMax",
83903
84037
  "color"
@@ -83933,6 +84067,7 @@ const NAMES$53 = {
83933
84067
  decisionNote: "decision_note"
83934
84068
  },
83935
84069
  optional: [
84070
+ "partial",
83936
84071
  "note",
83937
84072
  "cancelledBy",
83938
84073
  "approval",
@@ -84030,9 +84165,30 @@ function build$51(ctx) {
84030
84165
  ["color", "save_leave_type.color"]
84031
84166
  ].filter(([logical]) => ctx.has("types", logical));
84032
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;`;
84033
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`;
84034
- 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")})`;
84035
- 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)})`;
84036
84192
  const requestRecord = (type, row, summary) => ctx.record({
84037
84193
  type,
84038
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")})`,
@@ -84100,7 +84256,7 @@ ${userGrant(`${fn("decide_leave_request")}(uuid, boolean, text)`)}
84100
84256
  const tables = ctx.manages ? `create table if not exists ${types} (
84101
84257
  ${ty("id")} uuid primary key default gen_random_uuid(),
84102
84258
  ${ty("tenant")} ${idType} not null,
84103
- ${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)}
84104
84260
  ${ty("name")} text not null check (length(${ty("name")}) between 1 and 100),
84105
84261
  ${ty("unit")} text not null default 'days' check (${ty("unit")} in ('days', 'hours')),
84106
84262
  ${ty("paid")} boolean not null default true,
@@ -84109,9 +84265,9 @@ ${userGrant(`${fn("decide_leave_request")}(uuid, boolean, text)`)}
84109
84265
  ${ty("archivedAt")} timestamptz,
84110
84266
  ${ty("createdAt")} timestamptz not null default now(),
84111
84267
  ${ty("updatedAt")} timestamptz not null default now(),
84112
- unique (${ty("tenant")}, ${ty("key")}),
84113
- unique (${ty("tenant")}, ${ty("id")})
84114
- );${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"])}
84115
84271
  ${lockModuleTable(ctx, "types", { read: true })}
84116
84272
  ${renderPolicy(policy$1({
84117
84273
  table: types,
@@ -84131,7 +84287,7 @@ create table if not exists ${requests} (
84131
84287
  ${q("type")} uuid not null,
84132
84288
  ${q("startsOn")} date not null,
84133
84289
  ${q("endsOn")} date not null,
84134
- ${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)}
84135
84291
  -- Working days, or hours for an hours type, that the request books.
84136
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)`)}
84137
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)`)}` : ""}
@@ -84183,7 +84339,8 @@ as $$
84183
84339
  $$;
84184
84340
  ${userGrant(`${fn("leave_working_days")}(date, date)`)}
84185
84341
 
84186
- -- 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.
84187
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)
84188
84345
  returns jsonb
84189
84346
  language plpgsql
@@ -84197,13 +84354,7 @@ begin
84197
84354
  if not (${SERVICE_CALLER$1} or ${ctx.can("tenant", "save_leave_type.tenant", manage)}) then
84198
84355
  ${forbidden("not allowed to manage leave types")}
84199
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")}
84200
- insert into ${types} (${ty("tenant")}, ${ty("key")}, ${ty("name")}, ${ty("unit")}, ${ty("paid")}, ${ty("tracked")}${typeSettings.map(([logical]) => `, ${ty(logical)}`).join("")})
84201
- 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("")})
84202
- on conflict (${ty("tenant")}, ${ty("key")}) do update
84203
- set ${ty("name")} = excluded.${ty("name")}, ${ty("unit")} = excluded.${ty("unit")}, ${ty("paid")} = excluded.${ty("paid")},
84204
- ${ty("tracked")} = excluded.${ty("tracked")}${ctx.has("types", "allowance") ? `, ${ty("allowance")} = excluded.${ty("allowance")}` : ""},
84205
- ${settingsLine === "" ? "" : `${settingsLine},\n `}${ty("archivedAt")} = null, ${ty("updatedAt")} = now()
84206
- returning * into v_row;
84357
+ ${typeUpsert}
84207
84358
  return ${typeJson("v_row")};
84208
84359
  end;
84209
84360
  $$;
@@ -84296,7 +84447,10 @@ begin
84296
84447
  end if;
84297
84448
  if v_partial in ('morning', 'afternoon') and request_leave.starts_on <> request_leave.ends_on then
84298
84449
  ${invalid("a half day starts and ends on the same date")}
84299
- 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;`}
84300
84454
  v_amount := ${fn("leave_working_days")}(request_leave.starts_on, request_leave.ends_on)
84301
84455
  * case when v_partial = 'full' then 1 else 0.5 end;
84302
84456
  end if;
@@ -84312,9 +84466,9 @@ begin
84312
84466
  where r.${q("tenant")} = request_leave.tenant and r.${q("user")} = v_me
84313
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'`})
84314
84468
  and daterange(r.${q("startsOn")}, r.${q("endsOn")}, '[]') && daterange(request_leave.starts_on, request_leave.ends_on, '[]')
84315
- 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')
84316
84470
  and not (r.${q("partial")} = 'afternoon' and v_partial = 'morning')
84317
- ) then
84471
+ ` : ""} ) then
84318
84472
  ${fail$1("LEAVE_OVERLAP", "this overlaps another leave request", "23P01")}
84319
84473
  end if;${balanceCheck}
84320
84474
  ${ctx.hook("before_leave_request", [
@@ -84324,8 +84478,8 @@ begin
84324
84478
  ["date", "request_leave.ends_on"],
84325
84479
  ["numeric", "v_amount"]
84326
84480
  ])}
84327
- insert into ${requests} (${q("tenant")}, ${q("user")}, ${q("type")}, ${q("startsOn")}, ${q("endsOn")}, ${q("partial")}, ${q("amount")}${also("requests", "note")})
84328
- 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), '')")})
84329
84483
  returning * into v_row;${writeExtraColumns(requests, extras, "request_leave.fields", `x.${q("id")} = v_row.${q("id")}`, "v_row")}${approvals === void 0 ? "" : `
84330
84484
  v_request := ${approvals.fn("open_approval")}(
84331
84485
  request_leave.tenant, ${sqlString(LEAVE_REQUEST_SUBJECT)}, v_row.${q("id")}::text, 'approve',
@@ -106055,7 +106209,8 @@ const NAMES$35 = {
106055
106209
  "prefix",
106056
106210
  "validDays",
106057
106211
  "extraColumns",
106058
- "lineExtraColumns"
106212
+ "lineExtraColumns",
106213
+ "lineRates"
106059
106214
  ],
106060
106215
  tables: {
106061
106216
  quotes: {
@@ -126117,7 +126272,8 @@ const NAMES$8 = {
126117
126272
  "userTimeZone",
126118
126273
  "owner",
126119
126274
  "overlap",
126120
- "timers"
126275
+ "timers",
126276
+ "lockedColumns"
126121
126277
  ],
126122
126278
  tables: {
126123
126279
  entries: {
@@ -126239,6 +126395,7 @@ function build$8(ctx) {
126239
126395
  const owner = timeOwner(ctx, statusMode);
126240
126396
  const { employeeMode, staff, eOwner, tOwner, ownerVar, sheetUser, myEmployee, employeeOf, employeeOfUser, ownedByMe, sheetUserJson } = owner;
126241
126397
  const ended = (alias) => entryEnded(ctx, alias);
126398
+ const locked = lockedColumns(ctx, subjectColumns, employeeMode, Object.keys(NAMES$8.tables["entries"]?.columns ?? {}));
126242
126399
  const running = (alias) => durationMode ? `${alias}.${ctx.col("entries", "runningSince")} is not null` : `${alias}.${ctx.col("entries", "endedAt")} is null`;
126243
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}`;
126244
126401
  const endColumn = durationMode ? ctx.col("entries", "seconds") : ctx.col("entries", "endedAt");
@@ -126425,11 +126582,11 @@ security definer
126425
126582
  set search_path = ''
126426
126583
  as $$
126427
126584
  begin
126428
- ${employeeMode ? "" : ` -- employees keeps employee_id current, also on a locked week.
126429
- 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
126430
126587
  return new;
126431
126588
  end if;
126432
- `} 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
126433
126590
  ${fail$1("TIME_PERIOD_LOCKED", "this week's timesheet is submitted or approved", "55000")}
126434
126591
  end if;
126435
126592
  if tg_op in ('INSERT', 'UPDATE') and ${fn("time_week_locked")}(new.${e("tenant")}, new.${eOwner}, new.${e("startedAt")}) then
@@ -140026,7 +140183,9 @@ function unusedColumns(name, ctx) {
140026
140183
  */
140027
140184
  function contextOf(name, layout) {
140028
140185
  try {
140029
- 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;
140030
140189
  } catch {
140031
140190
  return;
140032
140191
  }
@@ -140093,9 +140252,12 @@ function adoptedTables(modules, ownTables, views = {}) {
140093
140252
  * write as text. `upgrade` refuses those configs. A column missing from a
140094
140253
  * block's own logical table isn't one: the block adds it.
140095
140254
  */
140096
- function adoptedColumnProblems(modules, files, schemas, ownTables, subjects) {
140255
+ function adoptedColumnProblems(modules, files, schemas, ownTables, subjects, accessProvider) {
140097
140256
  const declared = declaredTableColumns(files, schemas);
140098
- const context = subjects === void 0 ? {} : { subjects };
140257
+ const context = {
140258
+ ...subjects === void 0 ? {} : { subjects },
140259
+ ...accessProvider === void 0 ? {} : { accessProvider }
140260
+ };
140099
140261
  return [...adoptedTables(modules, ownTables, context).flatMap((table) => {
140100
140262
  const columns = declared.get(`${table.schema}.${table.table}`);
140101
140263
  if (columns === void 0 || SQL_MODULES[table.module]?.names?.tables[table.logical] !== void 0) return [];