better-supabase 0.29.0 → 0.31.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 (208) hide show
  1. package/dist/{adapter-D4aNBxhm.js → adapter-BTbj5N9C.js} +2 -52
  2. package/dist/ai-sdk/agents/index.d.ts +2 -2
  3. package/dist/{app-tables-DekyKNQ8.d.ts → app-tables-B2mKMNRQ.d.ts} +1 -1
  4. package/dist/astro/index.js +2 -2
  5. package/dist/{authorization-C7nuWMuB.d.ts → authorization-DfEkyFt_.d.ts} +24 -3
  6. package/dist/{bind-DmUGUsBd.d.ts → bind-DAx0bMSi.d.ts} +2 -2
  7. package/dist/{block-env-DWtZsqhH.d.ts → block-env-Dz7Caxk0.d.ts} +3 -3
  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 +7 -3
  17. package/dist/blocks/calendar/index.js +5 -1
  18. package/dist/blocks/comments/index.d.ts +4 -4
  19. package/dist/blocks/employees/index.js +1 -4
  20. package/dist/blocks/entitlements/index.d.ts +2 -2
  21. package/dist/blocks/forms/index.d.ts +1 -1
  22. package/dist/blocks/inbox/index.d.ts +4 -4
  23. package/dist/blocks/index.d.ts +1 -1
  24. package/dist/blocks/messaging/index.d.ts +4 -4
  25. package/dist/blocks/mfa/index.d.ts +1 -1
  26. package/dist/blocks/notifications/index.d.ts +3 -3
  27. package/dist/blocks/notifications/index.js +5 -43
  28. package/dist/blocks/onboarding/index.d.ts +1 -1
  29. package/dist/blocks/organizations/index.d.ts +34 -21
  30. package/dist/blocks/organizations/index.js +5 -1
  31. package/dist/blocks/permissions/index.d.ts +32 -3
  32. package/dist/blocks/permissions/index.js +23 -2
  33. package/dist/blocks/push/index.d.ts +10 -2
  34. package/dist/blocks/push/index.js +23 -7
  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/tasks/index.js +1 -1
  43. package/dist/blocks/teams/index.d.ts +7 -1
  44. package/dist/blocks/teams/index.js +8 -7
  45. package/dist/blocks/undo/index.d.ts +1 -1
  46. package/dist/blocks/usage/index.d.ts +1 -1
  47. package/dist/blocks/workflow-editor/index.d.ts +3 -3
  48. package/dist/blocks/workflows/index.d.ts +3 -3
  49. package/dist/cli/{add-BKkV99g9.js → add-B9wP0YGU.js} +2 -2
  50. package/dist/cli/{add-CrQ3jS7t.js → add-DjZXKd7X.js} +10 -10
  51. package/dist/cli/add-ZcEOEK23.js +1 -0
  52. package/dist/cli/{app-table-files-PnPOpuB4.js → app-table-files-mtvjHa48.js} +2 -2
  53. package/dist/cli/{backfill-DDDLhinm.js → backfill-Coshdvh_.js} +2 -2
  54. package/dist/cli/bin.js +1 -1
  55. package/dist/cli/{blocks-tRfYx_mh.js → blocks-BWCuA0nq.js} +2 -2
  56. package/dist/cli/{blocks-BCVcjvbm.js → blocks-hiSazThw.js} +1 -1
  57. package/dist/cli/{cache-DQZ09YOg.js → cache-x2wWAy0h.js} +1 -1
  58. package/dist/cli/{codemod-HKuwQmi_.js → codemod-BnjV7BpC.js} +210 -11
  59. package/dist/cli/{command-DIPmo0wh.js → command-CCAwhiOh.js} +6 -0
  60. package/dist/cli/{completion-DxPxMtyP.js → completion-BJaB84Pe.js} +2 -2
  61. package/dist/cli/{completion-DyLMSjOD.js → completion-BkUhs1ms.js} +1 -1
  62. package/dist/cli/{completion-FUgqm2-N.js → completion-DmUVsUVQ.js} +2 -2
  63. package/dist/cli/{config-BfapErxs.js → config-zId1jkLx.js} +1 -1
  64. package/dist/cli/{content-mapper-B0ehR7K-.js → content-mapper-DvOSOdTE.js} +2 -2
  65. package/dist/cli/{db-CWvH1_46.js → db-DXKyVEDF.js} +1 -1
  66. package/dist/cli/{doctor-CXJOhwLB.js → doctor-Ywy8oJEU.js} +76 -18
  67. package/dist/cli/env-CNjT_uOV.js +1 -0
  68. package/dist/cli/{env-BM242BCV.js → env-XMiKvhtV.js} +2 -2
  69. package/dist/cli/{gen-B7rw4j19.js → gen-B-FbQmG1.js} +14 -14
  70. package/dist/cli/index.d.ts +1 -1
  71. package/dist/cli/index.js +7 -7
  72. package/dist/cli/{init-C1bXXB_P.js → init-fb9e1BKX.js} +9 -9
  73. package/dist/cli/{keys-V-HcO-21.js → keys-ORiPz1sM.js} +1 -1
  74. package/dist/cli/{live-PpAh9pAc.js → live-DIt7TP-N.js} +2 -2
  75. package/dist/cli/{mcp-BRNAchdH.js → mcp-CVWwraga.js} +3 -3
  76. package/dist/cli/{metadata-dAAKb_kR.js → metadata-CannIjel.js} +3 -3
  77. package/dist/cli/{migrate-BWYXFnaW.js → migrate-Ht2TzIQF.js} +2 -2
  78. package/dist/cli/{migration-safety-DGQswWZy.js → migration-safety-nNyB05I-.js} +1 -1
  79. package/dist/cli/{migrations-Cqk-lJwu.js → migrations-bAd7dpk1.js} +2 -2
  80. package/dist/cli/{module-migration-8-hMiZtW.js → module-migration-CkNux8dr.js} +2 -2
  81. package/dist/cli/{moved-DNOtp9LA.js → moved-C3WyRHkA.js} +1 -1
  82. package/dist/cli/{parse-BPf3kGnc.js → parse-DjHbTaFI.js} +1 -1
  83. package/dist/cli/{powersync-BWQ-8T3G.js → powersync-B2v0tDwp.js} +100 -7
  84. package/dist/cli/powersync-D3mAQ6QE.js +1 -0
  85. package/dist/cli/{print-DSTnq5xz.js → print-CxQ0rBKT.js} +2 -2
  86. package/dist/cli/{providers-Cjf5iOp5.js → providers-DtI90lSw.js} +1 -1
  87. package/dist/cli/{remove-CwG8cPv1.js → remove-DYtE4IZ4.js} +6 -6
  88. package/dist/cli/{render-B18iAdsT.js → render-QGWfEoiB.js} +3 -3
  89. package/dist/cli/{run-CvPl8iQd.js → run-B5aMwErM.js} +3 -3
  90. package/dist/cli/{run-C2Yg5MWt.js → run-BNoJKf5I.js} +40 -39
  91. package/dist/cli/{run-Wx_2Acgv.js → run-DiYX1XEa.js} +8 -8
  92. package/dist/cli/{seed-CDnL4Tnc.js → seed-C-Hu2n_E.js} +1 -1
  93. package/dist/cli/seed-Cm-c0BDd.js +1 -0
  94. package/dist/cli/{shared-BHbtUOvh.js → shared-D_CFi5di.js} +1 -1
  95. package/dist/cli/{skills-DM3oeIxY.js → skills-D98y0bSB.js} +1 -1
  96. package/dist/cli/{snapshot-CXgsUPGj.js → snapshot-BlQ4DDcJ.js} +9 -4
  97. package/dist/cli/{source-B6aMAoEK.js → source-CelMBQMj.js} +1 -1
  98. package/dist/cli/{spec-EO0TP84d.js → spec-BxcoGE0h.js} +1 -1
  99. package/dist/cli/{spec-BcYic005.js → spec-iBx1LcYO.js} +3 -3
  100. package/dist/cli/{sql-layout-CkxDNVEH.js → sql-layout-Dp4Rottt.js} +2 -2
  101. package/dist/cli/{stack-ClESAZYf.js → stack-B2slzrYH.js} +1 -1
  102. package/dist/cli/{stack-env-6hS-WEmh.js → stack-env-3ziggrU3.js} +1 -1
  103. package/dist/cli/{sync-pq6gmlhG.js → sync-BnORI43S.js} +4 -4
  104. package/dist/cli/{table-dyKddjwo.js → table-D6HUECKI.js} +1 -1
  105. package/dist/cli/{upgrade-Dp9p7A69.js → upgrade-CR6-WmIc.js} +5 -5
  106. package/dist/cli/{upgrade-BoHb4h9P.js → upgrade-fz92aCnh.js} +3 -3
  107. package/dist/cli/{version-CQHFm-ak.js → version-Dz8ZlOuh.js} +1 -1
  108. package/dist/client/index.d.ts +5 -5
  109. package/dist/client/native/index.d.ts +4 -4
  110. package/dist/{composite-CBRbvn5j.js → composite-B4qB6k31.js} +2 -2
  111. package/dist/config/index.d.ts +2 -2
  112. package/dist/config/index.js +4 -4
  113. package/dist/{config-r7njjNgh.js → config-B7g-HDis.js} +3 -3
  114. package/dist/{config-bqKaPjst.js → config-R0m0fBiD.js} +1 -1
  115. package/dist/{context-B4TsE2gY.d.ts → context-DWWoP1wK.d.ts} +13 -1
  116. package/dist/{controller-CtwAsnVV.d.ts → controller-Br9dGKGe.d.ts} +1 -1
  117. package/dist/{controller-qG-B1eDn.js → controller-W97g2WGG.js} +1 -1
  118. package/dist/create/index.d.ts +3 -3
  119. package/dist/create/index.js +3 -3
  120. package/dist/create/lite/index.d.ts +3 -3
  121. package/dist/create/lite/index.js +3 -3
  122. package/dist/delivery-events-DbL8IHIY.js +53 -0
  123. package/dist/edge/index.js +3 -3
  124. package/dist/{entitlements-Bw3eYGKJ.d.ts → entitlements-CBjm2lvD.d.ts} +1 -1
  125. package/dist/eve/index.js +1 -1
  126. package/dist/expo/index.js +3 -2
  127. package/dist/{field-errors-DkzFduux.d.ts → field-errors-CEjsMAgd.d.ts} +4 -4
  128. package/dist/{framework-DYEUraqt.js → framework-CqiZk89W.js} +1 -1
  129. package/dist/hono/index.js +2 -2
  130. package/dist/{index-CB66nl14.d.ts → index-Clyd2Goi.d.ts} +1 -1
  131. package/dist/{index-Cw5gGSP8.d.ts → index-D98bQs8a.d.ts} +7 -7
  132. package/dist/{index-BNgpz_BV.d.ts → index-DIdPoQtO.d.ts} +2 -2
  133. package/dist/{index-BxckmAFc.d.ts → index-I8YLxKq8.d.ts} +2 -2
  134. package/dist/{index-CBQT_nXf.d.ts → index-eRBuKtMt.d.ts} +2 -2
  135. package/dist/{index-BM6NmKSc.d.ts → index-uIU65iEn.d.ts} +6 -6
  136. package/dist/{instances-C7qUTjhJ.js → instances-DY_ORk5g.js} +2 -0
  137. package/dist/mapper/bin.js +5 -5
  138. package/dist/mcp/index.d.ts +1 -1
  139. package/dist/mcp/index.js +1 -1
  140. package/dist/mcp/sdk/index.js +1 -1
  141. package/dist/next/index.d.ts +155 -13
  142. package/dist/next/index.js +245 -52
  143. package/dist/{operations-CqmQrTKw.d.ts → operations-hm1Isvvs.d.ts} +1 -1
  144. package/dist/{options-C4LuqmdG.js → options-CF6EVF_G.js} +3 -1
  145. package/dist/{options-COo7_3MX.js → options-DSCW40_5.js} +3 -1
  146. package/dist/orpc/index.js +2 -1
  147. package/dist/otel/index.js +4 -4
  148. package/dist/{ports-6LBgr1Aa.d.ts → ports-DOrPTJzl.d.ts} +1 -1
  149. package/dist/powersync/index.d.ts +204 -4
  150. package/dist/powersync/index.js +361 -4
  151. package/dist/preset/index.d.ts +3 -3
  152. package/dist/preset/index.js +3 -3
  153. package/dist/{preset-DCdEnJj9.js → preset-CXhpPmPV.js} +2 -2
  154. package/dist/{project-C4NA_van.js → project-DJ9Uo0sT.js} +5 -5
  155. package/dist/{push-token-BXsrJ7W9.d.ts → push-token-B4vcIU4s.d.ts} +1 -1
  156. package/dist/query/index.d.ts +1 -1
  157. package/dist/query/index.js +1 -1
  158. package/dist/react/index.d.ts +5 -5
  159. package/dist/react/index.js +1 -1
  160. package/dist/react/native/index.d.ts +1 -1
  161. package/dist/react/server.d.ts +5 -5
  162. package/dist/react/server.js +1 -1
  163. package/dist/{react-CcrQQl0_.js → react-mdVjpewL.js} +2 -2
  164. package/dist/react-router/index.js +2 -2
  165. package/dist/realtime/index.d.ts +3 -3
  166. package/dist/{record-type-DRbnlj5q.js → record-type-BEUyEsFx.js} +2 -2
  167. package/dist/records/index.d.ts +5 -5
  168. package/dist/records/index.js +3 -3
  169. package/dist/{replicas-Dyoh3CEg.js → refresh-DLBgnxjL.js} +51 -1
  170. package/dist/{resolved-names-iLBOUaib.js → resolved-names-kMRjmSIy.js} +1 -1
  171. package/dist/{runtime-CoKxZibd.js → runtime-LRJM7UqY.js} +19 -20
  172. package/dist/server/index.d.ts +3 -3
  173. package/dist/server/index.js +4 -4
  174. package/dist/sign-in-BzihC_8k.d.ts +50 -0
  175. package/dist/{sign-in-NO7LWlw4.js → sign-in-CuZ1Ag7O.js} +136 -26
  176. package/dist/solid/index.d.ts +5 -5
  177. package/dist/solid-start/index.js +2 -2
  178. package/dist/spec/index.js +1 -1
  179. package/dist/sql/index.d.ts +4 -4
  180. package/dist/sql/index.js +3 -3
  181. package/dist/{sql-CoBySj2F.js → sql-DHp0L7zK.js} +680 -333
  182. package/dist/ssr/index.d.ts +1 -1
  183. package/dist/svelte/index.d.ts +5 -5
  184. package/dist/sveltekit/index.js +2 -2
  185. package/dist/tanstack-start/index.js +2 -2
  186. package/dist/{tenant-Ded341Qz.d.ts → tenant-FfgNhd5x.d.ts} +1 -1
  187. package/dist/testing/index.d.ts +13 -4
  188. package/dist/testing/index.js +17 -15
  189. package/dist/{timeline-DvXtXq5q.d.ts → timeline-DqEoD8bb.d.ts} +1 -1
  190. package/dist/{timeline--VU3A1e4.js → timeline-Dz3hO2I6.js} +1 -1
  191. package/dist/{topic-XDdKzlrn.d.ts → topic-BaUElNw2.d.ts} +1 -1
  192. package/dist/{types-BFwB-E1j.d.ts → types-CMN0h_Ix.d.ts} +2 -2
  193. package/dist/vue/index.d.ts +5 -5
  194. package/dist/{watch-topic-DpN_GEoS.d.ts → watch-topic-BabDTZ-L.d.ts} +1 -1
  195. package/dist/workflow-sdk/world/index.js +2 -2
  196. package/dist/{workflow-sdk-CaEw822d.js → workflow-sdk-DJJkP0dT.js} +47 -8
  197. package/dist/yjs/index.d.ts +1 -1
  198. package/package.json +1 -1
  199. package/schemas/config-v1.json +10 -1
  200. package/schemas/doctor-report-v1.json +2 -0
  201. package/skills/better-supabase/references/ui-recipes.md +524 -295
  202. package/skills/better-supabase-api/references/powersync.md +16 -0
  203. package/skills/better-supabase-auth/SKILL.md +11 -1
  204. package/dist/cli/add-CwhrRJz5.js +0 -1
  205. package/dist/cli/env-uqfUbUzk.js +0 -1
  206. package/dist/cli/powersync-CbYxLsjv.js +0 -1
  207. package/dist/cli/seed-BOun22-k.js +0 -1
  208. package/dist/sign-in-CfwJAJJL.d.ts +0 -24
@@ -3,16 +3,16 @@ import { d as temporalText } from "./temporal-Dbo0fLzc.js";
3
3
  import { r as NEGATIVE, t as FILTER_OPERATORS } from "./filter-query-CQ6d5GnQ.js";
4
4
  import { a as ok } from "./result-ntFBW2p2.js";
5
5
  import { a as hasPlaceholder, l as splitPlaceholders, s as placeholderOf } from "./read-set-B1sDib5O.js";
6
- import { n as resolveJsonSchema, r as CONFIG_DEFAULTS, t as resolveNames } from "./resolved-names-iLBOUaib.js";
6
+ import { n as resolveJsonSchema, r as CONFIG_DEFAULTS, t as resolveNames } from "./resolved-names-kMRjmSIy.js";
7
7
  import { t as DEFAULT_CLAIMS } from "./claims-Bp9My7XP.js";
8
8
  import { o as tenantNames, r as composeNames } from "./entity-naming-Dtyq5sKE.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-C7qUTjhJ.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-DY_ORk5g.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-C6QKA3UR.js";
11
11
  import { t as isSqlType } from "./sql-type-iUSZpaUu.js";
12
12
  import { a as sqlString, i as sqlIdent } from "./template-Drgg3v2J.js";
13
13
  import { i as fillTemplate, l as templatePlaceholders } from "./access-sql-CTDNuxRv.js";
14
14
  import { t as MAX_BATCH } from "./batch-limit-DKVQDz4o.js";
15
- import { $ as ownRowPolicies, A as addForeignKey, B as ensureCheck, C as PARTITION_VARIABLES, D as activeMembership, E as accessDefinesDisabledHelpers, F as defaultPartition, G as jsonSchemaChecks, H as extraFieldsJson, I as defaultPartitionName, J as memberAddedRecord, K as jwtClaim, L as disabledHelpers, M as batchFunction, N as columnRef, O as addCheck, P as columnsObject, Q as organizationMissing, R as disabledHelpersNeedLaterTables, S as NOTHING, T as SERVICE_CALLER$1, U as fail$1, V as extraFieldsArg, W as insertExtraColumns, X as membershipSuspended, Y as membershipDisabledAt, Z as notNullCheckName, _ as roleScopeIs, _t as withExtraFields, at as renameSql, b as EQUIVALENT_TRIGGERS, c as OPTIONAL_MODULE_PERMISSIONS, ct as schemaPreamble, d as isOperationModule$1, dt as sha256Hex$1, et as pageSize, f as moduleOperations, ft as shortHash, g as roleNames, gt as userGrant, h as providerPlatformRoles, ht as updatedAt, it as registerPartitions, j as addNotNullCheck, k as addExtraColumns, l as accessModel, lt as serviceGrant, m as modulePermissionKey, mt as triggerGrant, n as WORKFLOW_SDK_WORLD, nt as raise$1, o as MODULE_PERMISSION_SCOPES, ot as replaceColumnCheck, p as modulePermission, pt as splitTable$1, q as lockTable, rt as recordTrigger, s as OPERATIONS, st as revokeTable, tt as quotedTable$1, u as hasPlatformRoles, ut as serviceOnly$1, v as rolesOf, vt as writeExtraColumns, w as SCHEMA$5, x as MONTHLY_PARTITIONS, y as tenantScope, z as dropExpiredPartitions } from "./workflow-sdk-CaEw822d.js";
15
+ import { $ as ownRowPolicies, A as addForeignKey, B as ensureCheck, C as PARTITION_VARIABLES, D as activeMembership, E as accessDefinesDisabledHelpers, F as defaultPartition, G as jsonSchemaChecks, H as extraFieldsJson, I as defaultPartitionName, J as memberAddedRecord, K as jwtClaim, L as disabledHelpers, M as batchFunction, N as columnRef, O as addCheck, P as columnsObject, Q as organizationMissing, R as disabledHelpersNeedLaterTables, S as NOTHING, T as SERVICE_CALLER$1, U as fail$1, V as extraFieldsArg, W as insertExtraColumns, X as membershipSuspended, Y as membershipDisabledAt, Z as notNullCheckName, _ as roleScopeIs, _t as withExtraFields, at as renameSql, b as EQUIVALENT_TRIGGERS, c as OPTIONAL_MODULE_PERMISSIONS, ct as schemaPreamble, d as isOperationModule$1, dt as sha256Hex$1, et as pageSize, f as moduleOperations, ft as shortHash, g as roleNames, gt as userGrant, h as providerPlatformRoles, ht as updatedAt, it as registerPartitions, j as addNotNullCheck, k as addExtraColumns, l as accessModel, lt as serviceGrant, m as modulePermissionKey, mt as triggerGrant, n as WORKFLOW_SDK_WORLD, nt as raise$1, o as MODULE_PERMISSION_SCOPES, ot as replaceColumnCheck, p as modulePermission, pt as splitTable$1, q as lockTable, rt as recordTrigger, s as OPERATIONS, st as revokeTable, tt as quotedTable$1, u as hasPlatformRoles, ut as serviceOnly$1, v as rolesOf, vt as writeExtraColumns, w as SCHEMA$5, x as MONTHLY_PARTITIONS, y as tenantScope, z as dropExpiredPartitions } from "./workflow-sdk-DJJkP0dT.js";
16
16
  import { n as blockOptions, r as option, t as NO_OPTIONS } from "./options-CfVPctAw.js";
17
17
  import { t as accessRequestsSqlOptions } from "./options-gUvfr3no.js";
18
18
  import { t as activitiesSqlOptions } from "./options-sU_zGkiV.js";
@@ -32,7 +32,7 @@ import { t as automationsSqlOptions } from "./options-DcHl59RC.js";
32
32
  import { t as billingSqlOptions } from "./options-DZHZYlpD.js";
33
33
  import { t as bookingsSqlOptions } from "./options-CZDmtsbV.js";
34
34
  import { t as bulkSqlOptions } from "./options-CTl8T88w.js";
35
- import { t as calendarSqlOptions } from "./options-C4LuqmdG.js";
35
+ import { t as calendarSqlOptions } from "./options-CF6EVF_G.js";
36
36
  import { t as catalogSqlOptions } from "./options-D0sj5abR.js";
37
37
  import { t as collectionsSqlOptions } from "./options-CyjL9lTf.js";
38
38
  import { t as commentsSqlOptions } from "./options-CoSPgWKy.js";
@@ -110,7 +110,7 @@ import { t as slaSqlOptions } from "./options-Dz9Yo52Z.js";
110
110
  import { t as ssoSqlOptions } from "./options-3OYOU56e.js";
111
111
  import { t as stateMachineSqlOptions } from "./options-aT89JqlB.js";
112
112
  import { t as tagsSqlOptions } from "./options-BJtdsK7b.js";
113
- import { t as tasksSqlOptions } from "./options-COo7_3MX.js";
113
+ import { t as tasksSqlOptions } from "./options-DSCW40_5.js";
114
114
  import { t as teamsSqlOptions } from "./options-jsOCvLUz.js";
115
115
  import { t as templatesSqlOptions } from "./options-BKDxrPvE.js";
116
116
  import { t as timeTrackingSqlOptions } from "./options-eTepQ1rZ.js";
@@ -1929,7 +1929,7 @@ const CLIENT_FUNCTIONS = {
1929
1929
  organizations: "create_organization delete_organization leave_organization list_members list_my_organizations mark_used organization_slug_problem remove_member resume_member suspend_member switch_organization transfer_ownership update_member_role update_organization",
1930
1930
  outbox: "emit_event outbox_ack outbox_claim outbox_dead_letters outbox_fail outbox_history outbox_register outbox_unregister purge_outbox",
1931
1931
  passes: "check_in_pass get_pass issue_pass list_pass_check_ins list_passes my_passes revoke_pass",
1932
- permissions: "can my_permissions",
1932
+ permissions: "can list_roles my_permissions set_permission_override",
1933
1933
  pipelines: "archive_pipeline archive_pipeline_stage list_pipelines pipeline_board pipeline_health pipeline_stats rank_pipeline_stage save_pipeline save_pipeline_stage set_pipeline_transitions",
1934
1934
  posts: "create_post delete_post get_post list_post_boards list_posts merge_posts save_post_board set_post_state update_post vote_on_post",
1935
1935
  profiles: "my_profile update_my_profile",
@@ -2564,6 +2564,22 @@ function valueMethods(input) {
2564
2564
  return `${sqlString(name)}, ${readValue(mapOf(table, logical), `${alias}.${sqlIdent(name)}`)}`;
2565
2565
  }).join(", ")})`;
2566
2566
  },
2567
+ rowJson(table, alias, options = {}) {
2568
+ const pairs = Object.entries(tables[table]?.columns ?? {}).flatMap(([logical, name]) => {
2569
+ const app = input.mapped(table, logical);
2570
+ const own = input.own(name);
2571
+ const labelled = changes(table, logical);
2572
+ if (app === null || app === own && !labelled) return [];
2573
+ const value = `${alias}.${sqlIdent(app)}`;
2574
+ const as = options.as?.[logical];
2575
+ if (labelled) {
2576
+ const label = readValue(mapOf(table, logical), value);
2577
+ return [...app === own ? [] : [`${sqlString(app)}, ${label}`], `${sqlString(own)}, ${label}`];
2578
+ }
2579
+ return [`${sqlString(own)}, ${as === void 0 ? value : as(value)}`];
2580
+ });
2581
+ return pairs.length === 0 ? `to_jsonb(${alias})` : `(to_jsonb(${alias}) || jsonb_build_object(${pairs.join(", ")}))`;
2582
+ },
2567
2583
  mapsValues: changes
2568
2584
  };
2569
2585
  }
@@ -2906,7 +2922,9 @@ function createModuleContext(module, namesOf, source = {}) {
2906
2922
  tables: names.tables,
2907
2923
  maps: checkedValueMaps(where, config.values, names.tables),
2908
2924
  cast: owned.cast,
2909
- column: requiredColumn
2925
+ column: requiredColumn,
2926
+ mapped: (table, logical) => config.tables[table] === null ? null : column(table, logical),
2927
+ own: (name) => naming.rename(name)
2910
2928
  }),
2911
2929
  names,
2912
2930
  installedModules: [...installed],
@@ -4799,7 +4817,7 @@ begin
4799
4817
  if not found then
4800
4818
  ${fail$1("ACCESS_REQUEST_NOT_FOUND", "access request not found", "P0002")}
4801
4819
  end if;
4802
- if not (${SERVICE_CALLER$1} or v_row.${c("user")} = auth.uid() or ${ctx.can("tenant", `v_row.${c("tenant")}`, manage)}) then
4820
+ if not (${SERVICE_CALLER$1} or coalesce(v_row.${c("user")} = auth.uid(), false) or ${ctx.can("tenant", `v_row.${c("tenant")}`, manage)}) then
4803
4821
  ${fail$1("ACCESS_REQUEST_FORBIDDEN", "not allowed to end this access")}
4804
4822
  end if;
4805
4823
  if v_row.${c("grantedAt")} is null or v_row.${c("endedAt")} is not null then
@@ -4852,7 +4870,7 @@ declare
4852
4870
  v_approval ${ar}%rowtype;
4853
4871
  begin
4854
4872
  select * into v_row from ${requests} r where r.${c("id")} = get_access_request.request_id;
4855
- if not found or not (${SERVICE_CALLER$1} or v_row.${c("user")} = auth.uid() or ${ctx.can("tenant", `v_row.${c("tenant")}`, read)}) then
4873
+ if not found or not (${SERVICE_CALLER$1} or coalesce(v_row.${c("user")} = auth.uid(), false) or ${ctx.can("tenant", `v_row.${c("tenant")}`, read)}) then
4856
4874
  ${fail$1("ACCESS_REQUEST_NOT_FOUND", "access request not found", "P0002")}
4857
4875
  end if;
4858
4876
  select * into v_approval from ${ar} x where x.${a("id")} = v_row.${c("approval")};
@@ -4957,12 +4975,12 @@ function subjectPermissionKey(value) {
4957
4975
  //#endregion
4958
4976
  //#region src/sql/subject-registry.ts
4959
4977
  const TYPE$5 = SUBJECT_TYPE_PATTERN;
4960
- const COLUMN$9 = /^[a-z_][a-z0-9_]{0,62}$/;
4978
+ const COLUMN$10 = /^[a-z_][a-z0-9_]{0,62}$/;
4961
4979
  const ID_TYPE$2 = /^[a-z][a-z0-9_ ]{0,62}$/;
4962
4980
  const ACTION = /^[a-z][a-z0-9_.-]{0,62}$/;
4963
4981
  const PLACEHOLDER$1 = /\{([^}]*)\}/g;
4964
4982
  function column$2(where, value) {
4965
- if (typeof value !== "string" || !COLUMN$9.test(value)) throw new TypeError(`${where} must be a column name`);
4983
+ if (typeof value !== "string" || !COLUMN$10.test(value)) throw new TypeError(`${where} must be a column name`);
4966
4984
  return value;
4967
4985
  }
4968
4986
  const RESOURCE = /^[a-z][a-z0-9_]{0,62}$/;
@@ -5027,7 +5045,7 @@ function checkPermission(where, action, value) {
5027
5045
  * (`organization_id`, or `workspace_id` for
5028
5046
  * `blocks.memberships.names.organization: workspace`).
5029
5047
  */
5030
- function registeredSubjects(subjects, naming = tenantNames()) {
5048
+ function registeredSubjects$1(subjects, naming = tenantNames()) {
5031
5049
  const idents = /* @__PURE__ */ new Map();
5032
5050
  for (const type of Object.keys(subjects)) {
5033
5051
  const other = idents.get(subjectTypeIdent(type));
@@ -5144,7 +5162,7 @@ function urlExpression(template, alias = "s") {
5144
5162
  * module must require `subjects`.
5145
5163
  */
5146
5164
  function subjectInTenant(ctx, type, id, tenant) {
5147
- const subjects = registeredSubjects(ctx.subjects, ctx.naming).filter((subject) => subject.tenant !== void 0);
5165
+ const subjects = registeredSubjects$1(ctx.subjects, ctx.naming).filter((subject) => subject.tenant !== void 0);
5148
5166
  if (subjects.length === 0) return "false";
5149
5167
  const canSubject = ctx.of("subjects").fn("can_subject");
5150
5168
  return `(case ${type}
@@ -5158,7 +5176,7 @@ ${subjects.map((subject) => ` when ${sqlString(subject.type)} then exists (
5158
5176
  * security definer code after checking the caller.
5159
5177
  */
5160
5178
  function subjectTenant(ctx, type, id) {
5161
- const subjects = registeredSubjects(ctx.subjects, ctx.naming).filter((subject) => subject.tenant !== void 0);
5179
+ const subjects = registeredSubjects$1(ctx.subjects, ctx.naming).filter((subject) => subject.tenant !== void 0);
5162
5180
  if (subjects.length === 0) return "null::text";
5163
5181
  return `(case ${type}
5164
5182
  ${subjects.map((subject) => ` when ${sqlString(subject.type)} then (select s.${subject.tenant ?? ""}::text from ${subject.qualified} s where ${registeredIdMatches(subject, id)})`).join("\n")}
@@ -5171,7 +5189,7 @@ ${subjects.map((subject) => ` when ${sqlString(subject.type)} then (select
5171
5189
  * one. Reads the table directly, so check the caller first.
5172
5190
  */
5173
5191
  function subjectTitle(ctx, type, id) {
5174
- const subjects = registeredSubjects(ctx.subjects, ctx.naming).filter((subject) => subject.config.title !== void 0);
5192
+ const subjects = registeredSubjects$1(ctx.subjects, ctx.naming).filter((subject) => subject.config.title !== void 0);
5175
5193
  if (subjects.length === 0) return "null::text";
5176
5194
  return `(case ${type}
5177
5195
  ${subjects.map((subject) => ` when ${sqlString(subject.type)} then (select s.${sqlIdent(subject.config.title ?? "")}::text from ${subject.qualified} s where ${registeredIdMatches(subject, id)})`).join("\n")}
@@ -6700,7 +6718,7 @@ function build$116(ctx) {
6700
6718
  returning * into v_row;` : "";
6701
6719
  const installCount = (change, indent) => agent("installCount") ? `\n${indent}update ${ctx.table("agents")} x set ${a.installCount} = ${change} where x.${a.id} = install_agent.agent_id;` : "";
6702
6720
  const readable = (row) => `(${row}.${a.owner} = (select auth.uid()) or (${row}.${a.publishedAt} is not null and (${row}.${a.visibility} = 'public' or (${row}.${a.visibility} = 'organization' and ${ctx.scope.check(`${row}.${a.tenant}`, read)}))) or ${ctx.scope.check(`${row}.${a.tenant}`, moderate)})`;
6703
- const canChange = (row) => `(${SERVICE_CALLER$1} or ${row}.${a.owner} = auth.uid() or ${ctx.scope.can(`${row}.${a.tenant}`, moderate)})`;
6721
+ const canChange = (row) => `(${SERVICE_CALLER$1} or coalesce(${row}.${a.owner} = auth.uid(), false) or ${ctx.scope.can(`${row}.${a.tenant}`, moderate)})`;
6704
6722
  const notFound = (agent) => raise$1("agent % not found", "P0002", "AGENT_NOT_FOUND", agent);
6705
6723
  const agentEvent = (type, row, extra = "") => ctx.record({
6706
6724
  type,
@@ -6888,7 +6906,7 @@ begin
6888
6906
  ${notFound("publish_agent.id")}
6889
6907
  end if;
6890
6908
  if publish_agent.visibility <> 'private' and not (${SERVICE_CALLER$1} or ${ctx.scope.can(`v_row.${a.tenant}`, moderate)}
6891
- or (v_row.${a.owner} = auth.uid() and ${ctx.scope.can(`v_row.${a.tenant}`, publish)})) then
6909
+ or (coalesce(v_row.${a.owner} = auth.uid(), false) and ${ctx.scope.can(`v_row.${a.tenant}`, publish)})) then
6892
6910
  ${raise$1("you may not publish agents here", "42501", "AGENT_FORBIDDEN")}
6893
6911
  end if;
6894
6912
  update ${agents} x set
@@ -8454,8 +8472,8 @@ const NAMES$114 = {
8454
8472
  }
8455
8473
  } }
8456
8474
  };
8457
- const COLUMN$8 = /^[a-z_][a-z0-9_]*$/;
8458
- const isColumn = (value) => typeof value === "string" && COLUMN$8.test(value);
8475
+ const COLUMN$9 = /^[a-z_][a-z0-9_]*$/;
8476
+ const isColumn = (value) => typeof value === "string" && COLUMN$9.test(value);
8459
8477
  const isColumnList$1 = (value) => Array.isArray(value) && value.every(isColumn);
8460
8478
  const isChildInput = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
8461
8479
  function childrenOf(value, where) {
@@ -9557,7 +9575,7 @@ ${userGrant(`${fn("my_work")}(${ctx.idType}, integer)`)}
9557
9575
  }
9558
9576
  function build$113(ctx, layout) {
9559
9577
  if (ctx.mode === "custom") return "";
9560
- const subjects = registeredSubjects(ctx.subjects, ctx.naming);
9578
+ const subjects = registeredSubjects$1(ctx.subjects, ctx.naming);
9561
9579
  const provider = accessModel(ctx) === "provider" ? layout.accessProvider : void 0;
9562
9580
  const fn = (name) => ctx.fn(name);
9563
9581
  return `${schemaPreamble(ctx)}
@@ -9963,6 +9981,7 @@ function build$112(ctx, layout) {
9963
9981
  const mu = members.col("memberships", "user");
9964
9982
  const mt = members.col("memberships", "tenant");
9965
9983
  const mr = members.col("memberships", "role");
9984
+ const approverRole = roleValue(ctx, "v_approvers ->> 'role'", `v_req.${c("tenant")}`);
9966
9985
  const memberIdsFor = providerMembers(ctx, layout).idsFor;
9967
9986
  const delegateMember = memberIdsFor === void 0 ? `exists (
9968
9987
  select 1 from ${members.table("memberships")} m
@@ -10025,7 +10044,7 @@ ${indent}end if;`;
10025
10044
  select x::uuid from jsonb_array_elements_text(coalesce(v_approvers -> 'users', '[]'::jsonb)) x
10026
10045
  union
10027
10046
  select m.${mu} from ${members.table("memberships")} m
10028
- where m.${mt} = v_req.${c("tenant")} and m.${mr} = v_approvers ->> 'role'${teamMembers}${delegation ? `
10047
+ where m.${mt} = v_req.${c("tenant")} and m.${mr} = ${approverRole}${teamMembers}${delegation ? `
10029
10048
  union
10030
10049
  select x.${d("delegateTo")} from ${decisions} x
10031
10050
  where x.${d("request")} = v_req.${c("id")} and x.${d("step")} = ${stepOf("v_req")} and x.${d("decision")} = 'delegated'
@@ -10165,7 +10184,7 @@ begin
10165
10184
  or (v_approvers ->> 'permission' is not null and ${ctx.can("tenant", `v_req.${c("tenant")}`, "v_approvers ->> 'permission'")})
10166
10185
  or (v_approvers ->> 'role' is not null and exists (
10167
10186
  select 1 from ${members.table("memberships")} m
10168
- where m.${mt} = v_req.${c("tenant")} and m.${mu} = v_me and m.${mr} = v_approvers ->> 'role'
10187
+ where m.${mt} = v_req.${c("tenant")} and m.${mu} = v_me and m.${mr} = ${approverRole}
10169
10188
  ))
10170
10189
  or (v_approvers ->> 'team' is not null and ${teamMatch("v_me")})${delegation ? `
10171
10190
  or exists (
@@ -10427,7 +10446,7 @@ begin
10427
10446
  if not found then
10428
10447
  ${notFound}
10429
10448
  end if;
10430
- if not (${SERVICE_CALLER$1} or v_req.${c("requestedBy")} = auth.uid() or ${ctx.can("tenant", `v_req.${c("tenant")}`, manage)}) then
10449
+ if not (${SERVICE_CALLER$1} or coalesce(v_req.${c("requestedBy")} = auth.uid(), false) or ${ctx.can("tenant", `v_req.${c("tenant")}`, manage)}) then
10431
10450
  ${fail$1("APPROVAL_FORBIDDEN", "only the requester or a manager can cancel this request")}
10432
10451
  end if;
10433
10452
  if v_req.${c("status")} <> 'pending' then
@@ -10455,7 +10474,7 @@ begin
10455
10474
  if not found then
10456
10475
  ${notFound}
10457
10476
  end if;
10458
- if not (${SERVICE_CALLER$1} or v_req.${c("requestedBy")} = auth.uid() or ${fn("approval_eligible")}(v_req.${c("id")})
10477
+ if not (${SERVICE_CALLER$1} or coalesce(v_req.${c("requestedBy")} = auth.uid(), false) or ${fn("approval_eligible")}(v_req.${c("id")})
10459
10478
  or (${ctx.can("tenant", `v_req.${c("tenant")}`, read)} and ${readable("v_req")})) then
10460
10479
  ${notFound}
10461
10480
  end if;
@@ -11004,7 +11023,7 @@ declare
11004
11023
  v_row ${t.inputs};
11005
11024
  begin
11006
11025
  select * into v_row from ${t.inputs} x where x.${i.id} = answer_ai_pending_input.id for update;
11007
- if not found or not (${SERVICE_CALLER$1} or v_row.${i.owner} = (select auth.uid())) then
11026
+ if not found or not (${SERVICE_CALLER$1} or coalesce(v_row.${i.owner} = (select auth.uid()), false)) then
11008
11027
  ${raise$1("No question %", "P0002", "AI_INPUT_NOT_FOUND", "answer_ai_pending_input.id")}
11009
11028
  end if;
11010
11029
  if v_row.${i.answeredAt} is not null then
@@ -12274,7 +12293,7 @@ function aiChatMessages(ctx, names) {
12274
12293
  const st = (column) => streams.col("streams", column);
12275
12294
  const ownChat = (name) => `
12276
12295
  select * into v_chat from ${t.chats} x where x.${ch.id} = ${name}.chat for update;
12277
- if not found or not (${SERVICE_CALLER$1} or v_chat.${ch.owner} = (select auth.uid())) then
12296
+ if not found or not (${SERVICE_CALLER$1} or coalesce(v_chat.${ch.owner} = (select auth.uid()), false)) then
12278
12297
  ${raise$1("No chat %", "P0002", "AI_CHAT_NOT_FOUND", `${name}.chat`)}
12279
12298
  end if;`;
12280
12299
  const metering = runMetering(ctx, names);
@@ -12923,7 +12942,7 @@ declare
12923
12942
  v_project uuid := (v_fields ->> 'project_id')::uuid;
12924
12943
  begin
12925
12944
  select * into v_row from ${t.chats} x where x.${ch.id} = update_ai_chat.chat for update;
12926
- if not found or not (${SERVICE_CALLER$1} or v_row.${ch.owner} = (select auth.uid())) then
12945
+ if not found or not (${SERVICE_CALLER$1} or coalesce(v_row.${ch.owner} = (select auth.uid()), false)) then
12927
12946
  ${notFound.replace("%CHAT%", "update_ai_chat.chat")}
12928
12947
  end if;
12929
12948
  if v_project is not null and not ${ownProject("v_project", `v_row.${ch.owner}`, `v_row.${ch.tenant}`)} then
@@ -12963,7 +12982,7 @@ begin
12963
12982
  if not found then
12964
12983
  return false;
12965
12984
  end if;
12966
- if not (${SERVICE_CALLER$1} or v_row.${ch.owner} = (select auth.uid()) or ${can(`v_row.${ch.tenant}`, perm.admin)}) then
12985
+ if not (${SERVICE_CALLER$1} or coalesce(v_row.${ch.owner} = (select auth.uid()), false) or ${can(`v_row.${ch.tenant}`, perm.admin)}) then
12967
12986
  ${notFound.replace("%CHAT%", "delete_ai_chat.chat")}
12968
12987
  end if;
12969
12988
  delete from ${t.chats} x where x.${ch.id} = delete_ai_chat.chat;
@@ -13192,7 +13211,8 @@ const NAMES$111 = {
13192
13211
  lifecycle: {
13193
13212
  tenant: "tenant",
13194
13213
  user: "createdBy",
13195
- export: true
13214
+ export: true,
13215
+ omit: ["tokenHash"]
13196
13216
  },
13197
13217
  columns: {
13198
13218
  id: "id",
@@ -13298,10 +13318,34 @@ function blockSubjects(ctx) {
13298
13318
  * (`config.subjects` or `on`) check the row's tenant and the subject's read
13299
13319
  * permission. Any other type fails.
13300
13320
  */
13321
+ function allowedTypes(ctx) {
13322
+ const on = ctx.on;
13323
+ if (on === void 0) return;
13324
+ return Array.isArray(on) ? on.map(String) : Object.keys(on);
13325
+ }
13326
+ function allowedCheck(ctx) {
13327
+ const allowed = allowedTypes(ctx);
13328
+ return allowed === void 0 ? "" : `
13329
+ if create_share_link.subject_type is null or create_share_link.subject_type <> all (array[${allowed.map(sqlString).join(", ")}]::text[]) then
13330
+ ${fail$1("SHARE_SUBJECT_UNKNOWN", "this subject type can't be shared", "22023")}
13331
+ end if;`;
13332
+ }
13333
+ function registeredSubjects(ctx) {
13334
+ const owned = new Set(blockSubjects(ctx).map(([type]) => type));
13335
+ const on = ctx.on;
13336
+ if (on === void 0) return subjectsOption(ctx);
13337
+ const listed = Array.isArray(on) ? on.filter((type) => !owned.has(String(type))) : Object.fromEntries(Object.entries(on).filter(([type]) => !owned.has(type)));
13338
+ return Object.keys(listed).length === 0 ? [] : subjectsOption({
13339
+ ...ctx,
13340
+ on: listed
13341
+ });
13342
+ }
13301
13343
  function subjectCheck(ctx) {
13302
- const blocks = blockSubjects(ctx);
13303
- const owned = new Set(blocks.map(([type]) => type));
13304
- const registered = subjectsOption(ctx).filter(([type]) => !owned.has(type));
13344
+ const allowed = allowedTypes(ctx);
13345
+ const every = blockSubjects(ctx);
13346
+ const owned = new Set(every.map(([type]) => type));
13347
+ const blocks = every.filter(([type]) => allowed === void 0 || allowed.includes(type));
13348
+ const registered = registeredSubjects(ctx).filter(([type]) => !owned.has(type));
13305
13349
  const sharable = subjectActionCheck(ctx, registered, SUBJECT_ARGS, ["share"]);
13306
13350
  const readable = registered.length === 0 ? "null" : subjectReadable(ctx, registered, SUBJECT_ARGS).replace(/else false\s+end$/, "else null\n end");
13307
13351
  const others = sharable === void 0 || readable === "null" ? readable : `case when ${readable} then ${sharable} else ${readable} end`;
@@ -13379,7 +13423,7 @@ function build$111(ctx) {
13379
13423
  const linkId = ctx.col("links", "id");
13380
13424
  const hashed = ctx.flag("tokenHash", false);
13381
13425
  const full = ctx.flag("fullRows", false);
13382
- const subjects = subjectsOption(ctx);
13426
+ const subjects = registeredSubjects(ctx);
13383
13427
  const l = (column) => `l.${ctx.col("links", column)}`;
13384
13428
  const shareOn = (type, id) => subjectActionCheck(ctx, subjects, {
13385
13429
  type,
@@ -13467,6 +13511,7 @@ begin
13467
13511
  if create_share_link.token_hash is not null and create_share_link.token_hash !~ '^[0-9a-f]{64}$' then
13468
13512
  ${fail$1("SHARE_TOKEN_HASH_INVALID", "token_hash must be 64 lowercase hex characters", "22023")}
13469
13513
  end if;` : ""}
13514
+ ${allowedCheck(ctx)}
13470
13515
  ${subjectCheck(ctx)}
13471
13516
  ${versionCheck(ctx)}
13472
13517
  insert into ${links} (${ctx.col("links", "tenant")}, ${ctx.col("links", "subjectType")}, ${ctx.col("links", "subjectId")}, ${ctx.col("links", "tokenHash")}, ${ctx.col("links", "role")}, ${ctx.col("links", "expiresAt")}, ${ctx.col("links", "maxUses")}, ${ctx.col("links", "createdBy")}${pinned ? `, ${ctx.col("links", "versionId")}` : ""})
@@ -13503,7 +13548,7 @@ begin
13503
13548
  for update;
13504
13549
  if not found or not (
13505
13550
  auth.role() = 'service_role'
13506
- or (v_creator is not null and v_creator = auth.uid())
13551
+ or (v_creator is not null and coalesce(v_creator = auth.uid(), false))
13507
13552
  or ${revokeShare === void 0 ? ctx.scope.can("v_tenant", create) : `(${ctx.scope.can("v_tenant", create)} and ${revokeShare})`}
13508
13553
  ) then
13509
13554
  ${fail$1("SHARE_NOT_FOUND", "share link not found", "P0002")}
@@ -14989,8 +15034,8 @@ function build$109(ctx) {
14989
15034
  const versionJson = (row) => `jsonb_build_object('document_id', ${row}.${v.document}, 'version', ${row}.${v.version}, 'content', ${row}.${v.content}, 'storage_path', ${or("versions", row, "storagePath", "null")}, 'created_by_message_id', ${or("versions", row, "message", "null")}, 'created_by', ${or("versions", row, "createdBy", "null")}, 'created_at', ${or("versions", row, "createdAt", "null")})`;
14990
15035
  const suggestionJson = (row) => `jsonb_build_object('id', ${row}.${sg.id}, 'document_id', ${row}.${sg.document}, 'version', ${row}.${sg.version}, 'original_text', ${row}.${sg.original}, 'suggested_text', ${row}.${sg.suggested}, 'description', ${or("suggestions", row, "description", "null")}, 'created_by', ${or("suggestions", row, "createdBy", "null")}, 'created_at', ${or("suggestions", row, "createdAt", "null")}, 'resolved_at', ${row}.${sg.resolvedAt}, 'accepted', ${row}.${sg.accepted})`;
14991
15036
  const readable = (prefix, owner, tenant, chat) => `(${prefix}${owner} = (select auth.uid()) or ${prefix === "" ? ctx.scope.check(tenant, manage) : ctx.scope.can(`${prefix}${tenant}`, manage)} or ${chatReadable(`${prefix}${chat}`)})`;
14992
- const ownFile = (row) => `(${SERVICE_CALLER$1} or ${row}.${f.owner} = auth.uid() or ${ctx.scope.can(`${row}.${f.tenant}`, manage)})`;
14993
- const ownDocument = (row) => `(${SERVICE_CALLER$1} or ${row}.${d.owner} = auth.uid() or ${ctx.scope.can(`${row}.${d.tenant}`, manage)})`;
15037
+ const ownFile = (row) => `(${SERVICE_CALLER$1} or coalesce(${row}.${f.owner} = auth.uid(), false) or ${ctx.scope.can(`${row}.${f.tenant}`, manage)})`;
15038
+ const ownDocument = (row) => `(${SERVICE_CALLER$1} or coalesce(${row}.${d.owner} = auth.uid(), false) or ${ctx.scope.can(`${row}.${d.tenant}`, manage)})`;
14994
15039
  const reserveInsert = [
14995
15040
  ["tenant", "reserve_ai_file.tenant"],
14996
15041
  ["owner", "auth.uid()"],
@@ -15272,7 +15317,7 @@ declare
15272
15317
  v_size bigint;
15273
15318
  begin
15274
15319
  select * into v_row from ${files} x where x.${f.id} = confirm_ai_file.file_id for update;
15275
- if not found or not (${SERVICE_CALLER$1} or v_row.${f.owner} = auth.uid()) then
15320
+ if not found or not (${SERVICE_CALLER$1} or coalesce(v_row.${f.owner} = auth.uid(), false)) then
15276
15321
  ${raise$1("file % not found", "P0002", "AI_FILE_NOT_FOUND", "file_id")}
15277
15322
  end if;
15278
15323
  if v_row.${f.status} <> 'pending' then
@@ -16782,7 +16827,7 @@ function build$106(ctx) {
16782
16827
  const line = (present, definition) => present ? `\n ${definition},` : "";
16783
16828
  const enqueue = (run) => ctx.installed("queue") ? `
16784
16829
  ${ctx.enqueue(queue, `jsonb_build_object('run_id', ${run})`, `'ai-task:' || ${run}::text`)}` : "";
16785
- const mayEdit = (row) => `(${SERVICE_CALLER$1} or ${row}.${t.user} = auth.uid() or ${ctx.scope.can(`${row}.${t.tenant}`, manage)})`;
16830
+ const mayEdit = (row) => `(${SERVICE_CALLER$1} or coalesce(${row}.${t.user} = auth.uid(), false) or ${ctx.scope.can(`${row}.${t.tenant}`, manage)})`;
16786
16831
  const notFound = raise$1("task % not found", "P0002", "AI_TASK_NOT_FOUND", "v_id");
16787
16832
  return `${schemaPreamble(ctx)}
16788
16833
  -- Prompts a user schedules to run on a cron. next_run_at is computed by the
@@ -18152,7 +18197,7 @@ function assetsFunctions(ctx) {
18152
18197
  const workItems = ctx.installed("tasks") && ctx.of("tasks").manages ? ctx.of("tasks") : void 0;
18153
18198
  const allowed = (tenant, permission) => `(${SERVICE_CALLER$1} or ${ctx.can("tenant", tenant, permission)})`;
18154
18199
  const readsLocation = (row) => allowed(`${row}.${l("tenant")}`, read);
18155
- const readsAsset = (row) => `(${allowed(`${row}.${s("tenant")}`, read)} or (${row}.${s("assigneeType")} = 'member' and ${row}.${s("assigneeId")} = auth.uid()::text))`;
18200
+ const readsAsset = (row) => `(${allowed(`${row}.${s("tenant")}`, read)} or (${row}.${s("assigneeType")} = 'member' and coalesce(${row}.${s("assigneeId")} = auth.uid()::text, false)))`;
18156
18201
  const forbidden = (message) => fail$1("ASSETS_FORBIDDEN", message);
18157
18202
  const invalid = (code, message) => fail$1(code, message, "22023");
18158
18203
  const locationMissing = fail$1("ASSETS_LOCATION_NOT_FOUND", "location not found", "P0002");
@@ -20907,7 +20952,7 @@ end;`;
20907
20952
  id,
20908
20953
  tenantless: tenantless.length > 0,
20909
20954
  json,
20910
- mayVersion: `(v_row.${c("uploadedBy")} = auth.uid() and ${inTenant("v_row", "upload")}) or ${canManage("v_row")} or (${SERVICE_CALLER$1})`
20955
+ mayVersion: `(coalesce(v_row.${c("uploadedBy")} = auth.uid(), false) and ${inTenant("v_row", "upload")}) or ${canManage("v_row")} or (${SERVICE_CALLER$1})`
20911
20956
  });
20912
20957
  const policy = (name) => sqlIdent(`bsb_attachments_${name}`);
20913
20958
  const offlineSql = offline ? attachmentsOfflineSql(ctx, {
@@ -23005,7 +23050,7 @@ ${userGrant(`${ctx.fn("revert_audit_entries")}(text[])`)}`;
23005
23050
  //#endregion
23006
23051
  //#region src/sql/modules/audit-subjects.ts
23007
23052
  const HEADER = /^[a-z0-9-]+$/;
23008
- const COLUMN$7 = /^[a-z_][a-z0-9_]*$/;
23053
+ const COLUMN$8 = /^[a-z_][a-z0-9_]*$/;
23009
23054
  const CLAIM = /^[a-z_][a-z0-9_]*(\.[a-z_][a-z0-9_]*)*$/i;
23010
23055
  const UUID$3 = "'^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$'";
23011
23056
  /**
@@ -23077,7 +23122,7 @@ function subjectColumns$1(ctx, taken) {
23077
23122
  if (raw === void 0) return [];
23078
23123
  if (!isRecord$1(raw)) throw new TypeError(`${where} must map column names to { type, from }`);
23079
23124
  return Object.entries(raw).map(([name, entry]) => {
23080
- if (!COLUMN$7.test(name) || name.length > 46) throw new TypeError(`${where}: "${name}" is not a valid column name`);
23125
+ if (!COLUMN$8.test(name) || name.length > 46) throw new TypeError(`${where}: "${name}" is not a valid column name`);
23081
23126
  if (taken.includes(name)) throw new TypeError(`${where}: "${name}" is already a column of the audit log`);
23082
23127
  const type = isRecord$1(entry) ? entry["type"] : void 0;
23083
23128
  const from = isRecord$1(entry) ? entry["from"] ?? name : void 0;
@@ -25752,12 +25797,12 @@ const RULES = {
25752
25797
  };
25753
25798
  //#endregion
25754
25799
  //#region src/sql/subject-columns.ts
25755
- const COLUMN$6 = /^[a-z_][a-z0-9_]{0,62}$/u;
25800
+ const COLUMN$7 = /^[a-z_][a-z0-9_]{0,62}$/u;
25756
25801
  function boundSubjects$1(subjects, where) {
25757
25802
  return subjects.flatMap(([type, subject]) => {
25758
25803
  const column = subject.extra["column"];
25759
25804
  if (column === void 0) return [];
25760
- if (typeof column !== "string" || !COLUMN$6.test(column)) throw new TypeError(`${where}.${type}.column must be a column name`);
25805
+ if (typeof column !== "string" || !COLUMN$7.test(column)) throw new TypeError(`${where}.${type}.column must be a column name`);
25761
25806
  return [{
25762
25807
  type,
25763
25808
  column,
@@ -25843,7 +25888,7 @@ function timeOwner(ctx, statusMode) {
25843
25888
  const myEmployee = (tenant) => staff === void 0 ? "null::uuid" : `(select y.${staff.col("employees", "id")} from ${staff.table("employees")} y where y.${staff.col("employees", "tenant")} = ${tenant} and y.${staff.col("employees", "user")} = auth.uid())`;
25844
25889
  const employeeOf = (tenant, employee) => staff === void 0 ? "" : `select y.${staff.col("employees", "id")}, y.${staff.col("employees", "user")} into v_owner, v_user from ${staff.table("employees")} y where y.${staff.col("employees", "id")} = ${employee} and y.${staff.col("employees", "tenant")} = ${tenant};`;
25845
25890
  const employeeOfUser = (tenant, user) => staff === void 0 ? "" : `select y.${staff.col("employees", "id")}, y.${staff.col("employees", "user")} into v_owner, v_user from ${staff.table("employees")} y where y.${staff.col("employees", "tenant")} = ${tenant} and y.${staff.col("employees", "user")} = ${user};`;
25846
- const ownedByMe = (row) => employeeMode ? `(${row}.${ctx.col("entries", "user")} = auth.uid() or ${row}.${ctx.col("entries", "employee")} = ${myEmployee(`${row}.${ctx.col("entries", "tenant")}`)})` : `${row}.${ctx.col("entries", "user")} = auth.uid()`;
25891
+ const ownedByMe = (row) => employeeMode ? `(coalesce(${row}.${ctx.col("entries", "user")} = auth.uid(), false) or ${row}.${ctx.col("entries", "employee")} = ${myEmployee(`${row}.${ctx.col("entries", "tenant")}`)})` : `coalesce(${row}.${ctx.col("entries", "user")} = auth.uid(), false)`;
25847
25892
  const sheetUserJson = (row) => `'userId', ${sheetUser ? `${row}.${ctx.col("timesheets", "user")}` : "null::uuid"}${employeeMode ? `, 'employeeId', ${row}.${ctx.col("timesheets", "employee")}` : ""}`;
25848
25893
  return {
25849
25894
  employeeMode,
@@ -26413,7 +26458,7 @@ ${userGrant(`${fn("list_invoiced_time")}(uuid, integer)`)}
26413
26458
  }
26414
26459
  /** Moves the rates on a merged registered subject to the record it merged into. */
26415
26460
  function rateMerges(ctx) {
26416
- return subjectMergeHandler(ctx, registeredSubjects(ctx.subjects, ctx.naming).map((subject) => [subject.type, {
26461
+ return subjectMergeHandler(ctx, registeredSubjects$1(ctx.subjects, ctx.naming).map((subject) => [subject.type, {
26417
26462
  table: `${subject.schema}.${subject.table}`,
26418
26463
  extra: {}
26419
26464
  }]), moveSubjectRows({
@@ -27964,7 +28009,7 @@ function seriesFunctions(p) {
27964
28009
  const series = ctx.table("series");
27965
28010
  const e = (column) => ctx.col("series", column);
27966
28011
  const seriesJsonOf = (alias) => `jsonb_build_object('id', ${alias}.${e("id")}, 'organizationId', ${alias}.${e("tenant")}::text, 'serviceId', ${alias}.${e("service")}, 'resourceId', ${alias}.${e("resource")}, 'rule', ${alias}.${e("rule")}, 'startsAt', ${alias}.${e("startsAt")}, 'tz', ${alias}.${e("tz")}, 'customerName', ${alias}.${e("customerName")}, 'customerEmail', ${alias}.${e("customerEmail")}, 'customerUserId', ${alias}.${e("customerUser")}, 'status', ${alias}.${e("status")}, 'endsAt', ${alias}.${e("endsAt")}, 'createdAt', ${alias}.${e("createdAt")})`;
27967
- const mayChange = (tenant, customer) => `(${allowed(p.scope, tenant, p.manage)} or (${customer} = auth.uid() and ${allowed(p.scope, tenant, p.create)}))`;
28012
+ const mayChange = (tenant, customer) => `(${allowed(p.scope, tenant, p.manage)} or (coalesce(${customer} = auth.uid(), false) and ${allowed(p.scope, tenant, p.create)}))`;
27968
28013
  return `
27969
28014
  -- The starts of a rule's occurrences from first_start: { freq: daily or
27970
28015
  -- weekly, interval, weekdays (1 is Monday, weekly only), count or until }.
@@ -29197,7 +29242,7 @@ begin
29197
29242
  if not (
29198
29243
  ${allowed(p.scope, `v_booking.${b("tenant")}`, p.manage)}
29199
29244
  or (change_booking.access_token is not null and v_booking.${b("accessHash")} = ${sha256Hex$1("convert_to(change_booking.access_token, 'utf8')")})
29200
- or (change_booking.access_token is null and v_booking.${b("customerUser")} = auth.uid() and ${allowed(p.scope, `v_booking.${b("tenant")}`, p.create)})
29245
+ or (change_booking.access_token is null and coalesce(v_booking.${b("customerUser")} = auth.uid(), false) and ${allowed(p.scope, `v_booking.${b("tenant")}`, p.create)})
29201
29246
  ) then
29202
29247
  ${fail$1("BOOKING_FORBIDDEN", "not allowed to change this booking")}
29203
29248
  end if;
@@ -29817,6 +29862,31 @@ function appFunction(value, key) {
29817
29862
  if (typeof value !== "string" || !QUALIFIED$1.test(value)) throw new TypeError(`blocks.calendar.options.accessFunctions.${key} must be a schema-qualified function name, such as public.can_read_calendar`);
29818
29863
  return value.split(".").map(sqlIdent).join(".");
29819
29864
  }
29865
+ const COLUMN$6 = /^[a-z_][a-z0-9_]{0,62}$/;
29866
+ function ruleDialect(ctx) {
29867
+ const raw = ctx.option("ruleDialect");
29868
+ const at = "blocks.calendar.options.ruleDialect";
29869
+ if (raw === void 0) return {
29870
+ lower: false,
29871
+ scalarMonthDay: false
29872
+ };
29873
+ if (!isRecord$1(raw) || ctx.owns("rules") || ctx.has("rules", "rrule")) throw new TypeError(`${at} takes { weekdays, monthDay, ordinal } and needs your own rules table with columns.rules.rrule mapped to null`);
29874
+ const { weekdays = "upper", monthDay = "list", ordinal } = raw;
29875
+ if (weekdays !== "upper" && weekdays !== "lower" || monthDay !== "list" && monthDay !== "scalar") throw new TypeError(`${at}: weekdays is "upper" or "lower", monthDay is "list" or "scalar"`);
29876
+ if (ordinal === void 0) return {
29877
+ lower: weekdays === "lower",
29878
+ scalarMonthDay: monthDay === "scalar"
29879
+ };
29880
+ if (!isRecord$1(ordinal) || typeof ordinal["weekday"] !== "string" || typeof ordinal["position"] !== "string" || !COLUMN$6.test(ordinal["weekday"]) || !COLUMN$6.test(ordinal["position"])) throw new TypeError(`${at}.ordinal takes { weekday, position }, two column names of the rules table`);
29881
+ return {
29882
+ lower: weekdays === "lower",
29883
+ scalarMonthDay: monthDay === "scalar",
29884
+ ordinal: {
29885
+ weekday: sqlIdent(ordinal["weekday"]),
29886
+ position: sqlIdent(ordinal["position"])
29887
+ }
29888
+ };
29889
+ }
29820
29890
  function calendarFeatures(ctx) {
29821
29891
  const access = ctx.flag("access", false);
29822
29892
  const functions = ctx.option("accessFunctions");
@@ -29826,6 +29896,7 @@ function calendarFeatures(ctx) {
29826
29896
  const attendeeKey = ctx.text("attendeeKey", "email");
29827
29897
  if (attendeeKey !== "email" && attendeeKey !== "any") throw new TypeError("blocks.calendar.options.attendeeKey must be \"email\" or \"any\"");
29828
29898
  const table = recurrence === "table";
29899
+ if (ctx.option("ruleDialect") !== void 0) ruleDialect(ctx);
29829
29900
  if (table && (!ctx.hasTable("rules") || !ctx.hasTable("recurrenceDates"))) throw new TypeError("blocks.calendar.options.recurrence \"table\" needs the rules and recurrenceDates tables");
29830
29901
  const readFn = isRecord$1(functions) ? appFunction(functions["read"], "read") : void 0;
29831
29902
  const writeFn = isRecord$1(functions) ? appFunction(functions["write"], "write") : void 0;
@@ -30084,13 +30155,18 @@ ${userGrant(`${ctx.fn("list_calendar_grants")}(uuid)`)}
30084
30155
  function ruleText(ctx) {
30085
30156
  const r = (column) => `r.${ctx.col("rules", column)}`;
30086
30157
  if (ctx.has("rules", "rrule")) return r("rrule");
30158
+ const dialect = ruleDialect(ctx);
30087
30159
  const list = (key, column) => ctx.has("rules", column) ? [`'${key}=' || nullif(translate(${r(column)}::text, '{}" ', ''), '')`] : [];
30160
+ const days = ctx.has("rules", "byDay") ? `nullif(translate(${dialect.lower ? `upper(${r("byDay")}::text)` : `${r("byDay")}::text`}, '{}" ', ''), '')` : void 0;
30161
+ const ordinal = dialect.ordinal === void 0 ? void 0 : `r.${dialect.ordinal.position}::text || upper(r.${dialect.ordinal.weekday}::text)`;
30162
+ const dayParts = [days, ordinal].filter((part) => part !== void 0);
30163
+ const byDay = dialect.lower || ordinal !== void 0 ? dayParts.length === 0 ? [] : [`'BYDAY=' || ${dayParts.length === 1 ? dayParts[0] : `coalesce(${dayParts.join(", ")})`}`] : list("BYDAY", "byDay");
30088
30164
  return `nullif(concat_ws(';', ${[
30089
30165
  `'FREQ=' || upper(${ctx.label("rules", "freq", r("freq"))})`,
30090
30166
  ...ctx.has("rules", "interval") ? [`'INTERVAL=' || ${r("interval")}`] : [],
30091
30167
  ...ctx.has("rules", "count") ? [`'COUNT=' || ${r("count")}`] : [],
30092
30168
  ...ctx.has("rules", "until") ? [`'UNTIL=' || to_char(${r("until")}::timestamptz at time zone 'UTC', 'YYYYMMDD"T"HH24MISS"Z"')`] : [],
30093
- ...list("BYDAY", "byDay"),
30169
+ ...byDay,
30094
30170
  ...list("BYMONTHDAY", "byMonthDay"),
30095
30171
  ...list("BYMONTH", "byMonth"),
30096
30172
  ...list("BYSETPOS", "bySetPos")
@@ -30154,12 +30230,16 @@ function insertRule(ctx, id, tenant, source) {
30154
30230
  add("interval", () => `(${part("INTERVAL", "[0-9]+")})::integer`);
30155
30231
  add("count", () => `(${part("COUNT", "[0-9]+")})::integer`);
30156
30232
  add("until", () => `case when ${part("UNTIL")} is null then null else to_timestamp(rpad(translate(${part("UNTIL")}, 'TZ', ''), 14, '0'), 'YYYYMMDDHH24MISS')::timestamp at time zone 'UTC' end`);
30157
- for (const [column, key] of [
30158
- ["byDay", "BYDAY"],
30159
- ["byMonthDay", "BYMONTHDAY"],
30160
- ["byMonth", "BYMONTH"],
30161
- ["bySetPos", "BYSETPOS"]
30162
- ]) add(column, () => ctx.cast("rules", column, `'{' || ${part(key)} || '}'`));
30233
+ const dialect = ruleDialect(ctx);
30234
+ const ordinalDay = `substring(upper(${source}) from '(?:^|;)BYDAY=([+-]?[0-9]+)[A-Z]{2}(?:;|$)')`;
30235
+ const weekdays = (value) => dialect.lower ? `lower(${value})` : value;
30236
+ add("byDay", () => ctx.cast("rules", "byDay", dialect.ordinal === void 0 ? `'{' || ${weekdays(part("BYDAY"))} || '}'` : `case when ${ordinalDay} is null then '{' || ${weekdays(part("BYDAY"))} || '}' end`));
30237
+ add("byMonthDay", () => ctx.cast("rules", "byMonthDay", dialect.scalarMonthDay ? part("BYMONTHDAY", "-?[0-9]+") : `'{' || ${part("BYMONTHDAY")} || '}'`));
30238
+ for (const [column, key] of [["byMonth", "BYMONTH"], ["bySetPos", "BYSETPOS"]]) add(column, () => ctx.cast("rules", column, `'{' || ${part(key)} || '}'`));
30239
+ if (dialect.ordinal !== void 0) {
30240
+ columns.push(dialect.ordinal.position, dialect.ordinal.weekday);
30241
+ values.push(`(${ordinalDay})::integer`, weekdays(`substring(upper(${source}) from '(?:^|;)BYDAY=[+-]?[0-9]+([A-Z]{2})(?:;|$)')`));
30242
+ }
30163
30243
  }
30164
30244
  return `insert into ${rules} (${columns.join(", ")}) values (${values.join(", ")});`;
30165
30245
  }
@@ -30220,6 +30300,36 @@ ${lockTable(dates, { read: true })}
30220
30300
  ${readPolicy(dates, datesName, calendarFeatures(ctx).access ? d("event") : d("tenant"))}
30221
30301
  `;
30222
30302
  }
30303
+ function readOnlyRule(ctx) {
30304
+ const raw = ctx.option("readOnly");
30305
+ if (raw === void 0) return;
30306
+ const rule = typeof raw === "object" && raw !== null ? Object.fromEntries(Object.entries(raw)) : {};
30307
+ const column = rule["column"];
30308
+ const given = Array.isArray(rule["values"]) ? rule["values"] : [];
30309
+ const values = given.filter((value) => typeof value === "string");
30310
+ if (typeof column !== "string" || column === "" || values.length === 0 || values.length !== given.length) throw new TypeError("blocks.calendar.options.readOnly must be { column, values } with a column of the events table and at least one value");
30311
+ return {
30312
+ column,
30313
+ values
30314
+ };
30315
+ }
30316
+ function eventGuards(ctx, allowed) {
30317
+ const readOnly = readOnlyRule(ctx);
30318
+ const e = (column) => ctx.col("events", column);
30319
+ return {
30320
+ actionCheck: (action, tenant) => {
30321
+ const key = ctx.config.permissions[action];
30322
+ return key === void 0 ? "" : `
30323
+ if not ${allowed(tenant, sqlString(key))} then
30324
+ ${fail$1("CALENDAR_FORBIDDEN", `not allowed to ${action} calendar events`)}
30325
+ end if;`;
30326
+ },
30327
+ readOnlyCheck: (id) => readOnly === void 0 ? "" : `
30328
+ if auth.role() is distinct from 'service_role' and exists (select 1 from ${ctx.table("events")} x where x.${e("id")} = ${id} and x.${sqlIdent(readOnly.column)}::text = any (array[${readOnly.values.map(sqlString).join(", ")}]::text[])) then
30329
+ ${fail$1("CALENDAR_EVENT_READ_ONLY", "this event is read-only", "42501")}
30330
+ end if;`
30331
+ };
30332
+ }
30223
30333
  //#endregion
30224
30334
  //#region src/sql/modules/calendar-rows.ts
30225
30335
  const STATUSES$1 = "('confirmed', 'tentative', 'cancelled')";
@@ -31043,7 +31153,7 @@ begin
31043
31153
  end if;
31044
31154
  if not (
31045
31155
  ${allowed("set_calendar_working_hours.tenant", manage)}
31046
- or (v_user = auth.uid() and ${ctx.scope.can("set_calendar_working_hours.tenant", read)})
31156
+ or (coalesce(v_user = auth.uid(), false) and ${ctx.scope.can("set_calendar_working_hours.tenant", read)})
31047
31157
  ) then
31048
31158
  ${fail$1("CALENDAR_FORBIDDEN", "not allowed to set these working hours")}
31049
31159
  end if;
@@ -31527,7 +31637,9 @@ const CALENDAR_NAMES = {
31527
31637
  "recurrence",
31528
31638
  "rdates",
31529
31639
  "attendeeKey",
31530
- "calendarDetails"
31640
+ "calendarDetails",
31641
+ "ruleDialect",
31642
+ "readOnly"
31531
31643
  ],
31532
31644
  tables: {
31533
31645
  calendars: {
@@ -31618,8 +31730,12 @@ const CALENDAR_NAMES = {
31618
31730
  "owner",
31619
31731
  "rdates"
31620
31732
  ],
31621
- typed: ["status", "visibility"],
31622
- mappable: ["kind", "transparency"]
31733
+ typed: [
31734
+ "status",
31735
+ "visibility",
31736
+ "kind",
31737
+ "transparency"
31738
+ ]
31623
31739
  },
31624
31740
  attendees: {
31625
31741
  name: "calendar_attendees",
@@ -31653,7 +31769,7 @@ const CALENDAR_NAMES = {
31653
31769
  "organizer",
31654
31770
  "optional"
31655
31771
  ],
31656
- mappable: ["role", "response"]
31772
+ typed: ["role", "response"]
31657
31773
  },
31658
31774
  workingHours: WORKING_HOURS_TABLE,
31659
31775
  grants: {
@@ -31690,6 +31806,7 @@ const CALENDAR_NAMES = {
31690
31806
  bySetPos: "by_set_pos"
31691
31807
  },
31692
31808
  optional: [
31809
+ "id",
31693
31810
  "tenant",
31694
31811
  "rrule",
31695
31812
  "freq",
@@ -31759,6 +31876,9 @@ function build$95(ctx) {
31759
31876
  const features = calendarFeatures(ctx);
31760
31877
  const writesCalendar = (calendar, tenant) => features.access ? accessCall(ctx, calendar, "write") : allowed(tenant, write);
31761
31878
  const writesEvent = (event, tenant) => features.access ? eventAccessCall(ctx, event, "write") : allowed(tenant, write);
31879
+ const { actionCheck, readOnlyCheck } = eventGuards(ctx, allowed);
31880
+ const saveChecks = `${actionCheck("create", "v_tenant")}${readOnlyCheck("v_master")}`;
31881
+ const changeChecks = `${actionCheck("update", "v_tenant")}${readOnlyCheck("v_id")}`;
31762
31882
  const recurrence = recurrenceSql(ctx);
31763
31883
  const me = "(select auth.uid())";
31764
31884
  const calendarColumns = `${features.access && ctx.has("calendars", "visibility") ? `
@@ -32093,6 +32213,10 @@ begin
32093
32213
  if v_id is not null and not ${eventAccessCall(ctx, "v_id", "write")} then
32094
32214
  ${fail$1("CALENDAR_FORBIDDEN", "not allowed to change this event")}
32095
32215
  end if;${visibilityCheck("visibility", "('public', 'private')", "CALENDAR_EVENT_INVALID")}` : ""}
32216
+ ${saveChecks === "" && changeChecks === "" ? "" : `
32217
+ if v_id is null then${saveChecks || "\n null;"}
32218
+ else${changeChecks || "\n null;"}
32219
+ end if;`}
32096
32220
  if v_item ? 'status' and v_item ->> 'status' not in ${STATUSES$1} then
32097
32221
  ${fail$1("CALENDAR_EVENT_INVALID", "status must be confirmed, tentative or cancelled", "22023")}
32098
32222
  end if;
@@ -32172,7 +32296,7 @@ begin
32172
32296
  end if;
32173
32297
  if not ${writesEvent("v_id", "v_tenant")} then
32174
32298
  ${fail$1("CALENDAR_FORBIDDEN", "not allowed to change this calendar")}
32175
- end if;
32299
+ end if;${actionCheck("delete", "v_tenant")}${readOnlyCheck("v_id")}
32176
32300
  delete from ${events} where ${e("id")} = v_id;
32177
32301
  ${reminderRule(ctx, "delete")}
32178
32302
  ${record("calendar_event.deleted", "v_id", "v_calendar", "v_tenant")}
@@ -32201,7 +32325,7 @@ begin
32201
32325
  end if;
32202
32326
  if not ${writesEvent("v_id", "v_tenant")} then
32203
32327
  ${fail$1("CALENDAR_FORBIDDEN", "not allowed to change this calendar")}
32204
- end if;
32328
+ end if;${actionCheck("delete", "v_tenant")}${readOnlyCheck("v_id")}
32205
32329
  ${features.table ? `if not (cancel_calendar_occurrence.original_start = any (${recurrence.exdatesOf("v_id")})) then
32206
32330
  ${addDate(ctx, "v_id", "v_tenant", "exdate", "cancel_calendar_occurrence.original_start")}
32207
32331
  end if;
@@ -32246,7 +32370,7 @@ begin
32246
32370
  end if;
32247
32371
  if not ${writesEvent("v_id", "v_tenant")} then
32248
32372
  ${fail$1("CALENDAR_FORBIDDEN", "not allowed to change this calendar")}
32249
- end if;
32373
+ end if;${changeChecks}${actionCheck("create", "v_tenant")}
32250
32374
  if split_calendar_event.split_at <= v_starts or nullif(split_calendar_event.before_rrule, '') is null then
32251
32375
  ${fail$1("CALENDAR_SPLIT_INVALID", "split at a later occurrence, with the rule that ends the series before it", "22023")}
32252
32376
  end if;
@@ -32763,7 +32887,7 @@ begin
32763
32887
  if exists (select 1 from ${ledger.table("accounts")} x join ${ledger.table("entries")} y on y.${le("account")} = x.${la("id")}
32764
32888
  where x.${la("tenant")} = v_tenant and x.${la("managedBy")} = 'inventory' and x.${la("kind")} = 'stock'
32765
32889
  and x.${la("metadata")} ->> 'locationId' = delete_location.location::text)
32766
- or exists (select 1 from ${ctx.table("reservations")} x where x.${r("location")} = delete_location.location and x.${r("status")} = 'active') then
32890
+ or exists (select 1 from ${ctx.table("reservations")} x where x.${r("location")} = delete_location.location and ${ctx.is("reservations", "status", `x.${r("status")}`, ["active"])}) then
32767
32891
  ${fail$1("INVENTORY_LOCATION_IN_USE", "the location has stock history; deactivate it instead", "23503")}
32768
32892
  end if;
32769
32893
  delete from ${locations} x where x.${l("id")} = delete_location.location;
@@ -32961,9 +33085,9 @@ begin
32961
33085
  ])}
32962
33086
  ${lockLevel(ctx, "reserve_stock.variant", "reserve_stock.location")}
32963
33087
  with expired as (
32964
- update ${reservations} x set ${r("status")} = 'expired', ${r("updatedAt")} = now()
33088
+ update ${reservations} x set ${r("status")} = ${ctx.value("reservations", "status", "expired")}, ${r("updatedAt")} = now()
32965
33089
  where x.${r("variant")} = reserve_stock.variant and x.${r("location")} = reserve_stock.location
32966
- and x.${r("status")} = 'active' and x.${r("expiresAt")} <= now()
33090
+ and ${ctx.is("reservations", "status", `x.${r("status")}`, ["active"])} and x.${r("expiresAt")} <= now()
32967
33091
  returning x.${r("quantity")} as quantity
32968
33092
  )
32969
33093
  update ${levels} x set ${lv("reserved")} = greatest(x.${lv("reserved")} - (select coalesce(sum(e.quantity), 0)::integer from expired e), 0)
@@ -33012,7 +33136,7 @@ declare
33012
33136
  v_movement uuid;
33013
33137
  begin
33014
33138
  select x.${r("tenant")} as tenant, x.${r("variant")} as variant, x.${r("location")} as location,
33015
- x.${r("quantity")} as quantity, x.${r("status")} as status, x.${r("expiresAt")} as expires_at,
33139
+ x.${r("quantity")} as quantity, ${ctx.label("reservations", "status", `x.${r("status")}`)} as status, x.${r("expiresAt")} as expires_at,
33016
33140
  x.${r("referenceType")} as reference_type, x.${r("referenceId")} as reference_id
33017
33141
  into v_row from ${reservations} x where x.${r("id")} = commit_reservation.reservation for update;
33018
33142
  if not found then
@@ -33026,7 +33150,7 @@ begin
33026
33150
  ${fail$1("INVENTORY_RESERVATION_EXPIRED", "the reservation has expired", "55000")}
33027
33151
  end if;
33028
33152
  ${releaseLevel("v_row.variant", "v_row.location", "v_row.quantity")}
33029
- update ${reservations} x set ${r("status")} = 'committed', ${r("updatedAt")} = now()
33153
+ update ${reservations} x set ${r("status")} = ${ctx.value("reservations", "status", "committed")}, ${r("updatedAt")} = now()
33030
33154
  where x.${r("id")} = commit_reservation.reservation;
33031
33155
  v_movement := ${moveStock(ctx, {
33032
33156
  tenant: "v_row.tenant",
@@ -33060,7 +33184,7 @@ declare
33060
33184
  v_row record;
33061
33185
  begin
33062
33186
  select x.${r("id")} as id, x.${r("tenant")} as tenant, x.${r("variant")} as variant, x.${r("location")} as location,
33063
- x.${r("quantity")} as quantity, x.${r("status")} as status
33187
+ x.${r("quantity")} as quantity, ${ctx.label("reservations", "status", `x.${r("status")}`)} as status
33064
33188
  into v_row from ${reservations} x where x.${r("id")} = release_reservation.reservation for update;
33065
33189
  if not found then
33066
33190
  return false;
@@ -33070,7 +33194,7 @@ begin
33070
33194
  return false;
33071
33195
  end if;
33072
33196
  ${releaseLevel("v_row.variant", "v_row.location", "v_row.quantity")}
33073
- update ${reservations} x set ${r("status")} = 'released', ${r("updatedAt")} = now()
33197
+ update ${reservations} x set ${r("status")} = ${ctx.value("reservations", "status", "released")}, ${r("updatedAt")} = now()
33074
33198
  where x.${r("id")} = release_reservation.reservation;
33075
33199
  ${released("v_row.", "released")}
33076
33200
  return true;
@@ -33094,12 +33218,12 @@ begin
33094
33218
  select x.${r("id")} as id, x.${r("tenant")} as tenant, x.${r("variant")} as variant,
33095
33219
  x.${r("location")} as location, x.${r("quantity")} as quantity
33096
33220
  from ${reservations} x
33097
- where x.${r("status")} = 'active' and x.${r("expiresAt")} <= now()
33221
+ where ${ctx.is("reservations", "status", `x.${r("status")}`, ["active"])} and x.${r("expiresAt")} <= now()
33098
33222
  order by x.${r("expiresAt")}
33099
33223
  limit greatest(coalesce(expire_reservations.max_rows, 500), 1)
33100
33224
  for update skip locked
33101
33225
  loop
33102
- update ${reservations} x set ${r("status")} = 'expired', ${r("updatedAt")} = now() where x.${r("id")} = v_row.id;
33226
+ update ${reservations} x set ${r("status")} = ${ctx.value("reservations", "status", "expired")}, ${r("updatedAt")} = now() where x.${r("id")} = v_row.id;
33103
33227
  ${releaseLevel("v_row.variant", "v_row.location", "v_row.quantity")}
33104
33228
  ${released("v_row.", "expired")}
33105
33229
  v_count := v_count + 1;
@@ -33203,12 +33327,12 @@ begin
33203
33327
  begin
33204
33328
  if v_created then
33205
33329
  insert into ${products} (${p("tenant")}, ${p("title")}, ${p("slug")}${desc ? `, ${p("description")}` : ""}${kind ? `, ${p("kind")}` : ""})
33206
- values (save_product.tenant, save_product.title, v_slug${desc ? ", save_product.description" : ""}${kind ? ", coalesce(save_product.kind, 'physical')" : ""})
33207
- returning ${p("id")}, ${p("status")} into v_id, v_status;
33330
+ values (save_product.tenant, save_product.title, v_slug${desc ? ", save_product.description" : ""}${kind ? `, ${ctx.cast("products", "kind", "coalesce(save_product.kind, 'physical')")}` : ""})
33331
+ returning ${p("id")}, ${ctx.label("products", "status", p("status"))} into v_id, v_status;
33208
33332
  else
33209
- update ${products} x set ${p("title")} = save_product.title, ${p("slug")} = v_slug${desc ? `, ${p("description")} = save_product.description` : ""}${kind ? `, ${p("kind")} = coalesce(save_product.kind, x.${p("kind")})` : ""}, ${p("updatedAt")} = now()
33333
+ update ${products} x set ${p("title")} = save_product.title, ${p("slug")} = v_slug${desc ? `, ${p("description")} = save_product.description` : ""}${kind ? `, ${p("kind")} = coalesce(${ctx.cast("products", "kind", "save_product.kind")}, x.${p("kind")})` : ""}, ${p("updatedAt")} = now()
33210
33334
  where x.${p("id")} = save_product.product and x.${p("tenant")} = save_product.tenant
33211
- returning x.${p("status")} into v_status;
33335
+ returning ${ctx.label("products", "status", `x.${p("status")}`)} into v_status;
33212
33336
  if not found then
33213
33337
  ${fail$1("CATALOG_PRODUCT_NOT_FOUND", "product not found", "P0002")}
33214
33338
  end if;
@@ -33250,7 +33374,7 @@ declare
33250
33374
  v_tenant ${ctx.idType};
33251
33375
  v_from text;
33252
33376
  begin
33253
- select x.${p("tenant")}, x.${p("status")} into v_tenant, v_from from ${products} x where x.${p("id")} = set_product_status.product for update;
33377
+ select x.${p("tenant")}, ${ctx.label("products", "status", `x.${p("status")}`)} into v_tenant, v_from from ${products} x where x.${p("id")} = set_product_status.product for update;
33254
33378
  if v_tenant is null then
33255
33379
  ${fail$1("CATALOG_PRODUCT_NOT_FOUND", "product not found", "P0002")}
33256
33380
  end if;
@@ -33942,7 +34066,7 @@ as $$
33942
34066
  select jsonb_build_object(
33943
34067
  'id', p.${p("id")},
33944
34068
  'slug', p.${p("slug")},
33945
- 'status', p.${p("status")},
34069
+ 'status', ${ctx.label("products", "status", `p.${p("status")}`)},
33946
34070
  'kind', ${kind ? `p.${p("kind")}` : "null"},
33947
34071
  'locale', ${locale},
33948
34072
  'title', ${title},
@@ -34918,7 +35042,7 @@ security definer
34918
35042
  set search_path = ''
34919
35043
  as $$
34920
35044
  select x.${p("id")} from ${products} x
34921
- where x.${p("status")} = 'active'
35045
+ where ${ctx.is("products", "status", `x.${p("status")}`, ["active"])}
34922
35046
  and x.${p("tenant")} in (select y.${s("tenant")} from ${storefronts} y where y.${s("publishedAt")} is not null)
34923
35047
  $$;
34924
35048
  revoke execute on function ${fn("storefront_products")}() from public;
@@ -35113,7 +35237,7 @@ const NAMES$94 = {
35113
35237
  updatedAt: "updated_at"
35114
35238
  },
35115
35239
  optional: ["description", "kind"],
35116
- typed: ["status"]
35240
+ typed: ["status", "kind"]
35117
35241
  },
35118
35242
  options: {
35119
35243
  name: "product_options",
@@ -35542,7 +35666,7 @@ function storefrontPolicies(ctx, names) {
35542
35666
  const t = (name) => ctx.table(name);
35543
35667
  const c = (table, column) => ctx.col(table, column);
35544
35668
  const publicTables = [
35545
- ["products", `${c("products", "status")} = 'active' and ${c("products", "tenant")} in (select ${names.fn("storefront_tenants")}())`],
35669
+ ["products", `${ctx.is("products", "status", c("products", "status"), ["active"])} and ${c("products", "tenant")} in (select ${names.fn("storefront_tenants")}())`],
35546
35670
  ["options", `${c("options", "product")} in (select ${names.fn("storefront_products")}())`],
35547
35671
  ["optionValues", `${c("optionValues", "option")} in (select o.${c("options", "id")} from ${t("options")} o where o.${c("options", "product")} in (select ${names.fn("storefront_products")}()))`],
35548
35672
  ["variants", `${c("variants", "product")} in (select ${names.fn("storefront_products")}())`],
@@ -36095,7 +36219,7 @@ function messagingSql(ctx, provider) {
36095
36219
  if (!Number.isInteger(editWindow) || editWindow < 0) throw new TypeError("blocks.messaging.options.editWindow must be 0 (always) or a number of seconds");
36096
36220
  const scheduleQueue = ctx.text("scheduleQueue", "messaging");
36097
36221
  if (!QUEUE$2.test(scheduleQueue)) throw new TypeError("blocks.messaging.options.scheduleQueue must be a lowercase queue name");
36098
- const scoped = registeredSubjects(ctx.subjects, ctx.naming).flatMap((subject) => subject.config.scope === void 0 ? [] : [{
36222
+ const scoped = registeredSubjects$1(ctx.subjects, ctx.naming).flatMap((subject) => subject.config.scope === void 0 ? [] : [{
36099
36223
  type: subject.type,
36100
36224
  scope: subject.config.scope
36101
36225
  }]);
@@ -37432,11 +37556,11 @@ function collectionFunctions(ctx, names) {
37432
37556
  const setExtras = (source, id) => writeExtraColumns(t("collections"), extras, source, `x.${co("id")} = ${id}`);
37433
37557
  const en = (column) => names.c("entries", column);
37434
37558
  const maySee = (alias) => `(${SERVICE$1} or (${ctx.scope.can(`${alias}.${co("tenant")}`, names.read)} and (
37435
- (${alias}.${co("scope")} = 'user' and ${alias}.${co("owner")} = auth.uid())
37559
+ (${alias}.${co("scope")} = 'user' and coalesce(${alias}.${co("owner")} = auth.uid(), false))
37436
37560
  or (${alias}.${co("scope")} = 'team' and ${names.inTeam(`${alias}.${co("team")}`)})
37437
37561
  or ${alias}.${co("scope")} = 'tenant')))`;
37438
37562
  const mayManage = (alias) => `(${SERVICE$1}
37439
- or (${alias}.${co("scope")} = 'user' and ${alias}.${co("owner")} = auth.uid() and ${ctx.scope.can(`${alias}.${co("tenant")}`, names.write)})
37563
+ or (${alias}.${co("scope")} = 'user' and coalesce(${alias}.${co("owner")} = auth.uid(), false) and ${ctx.scope.can(`${alias}.${co("tenant")}`, names.write)})
37440
37564
  or (${alias}.${co("scope")} <> 'user' and ${ctx.scope.can(`${alias}.${co("tenant")}`, names.share)}))`;
37441
37565
  const mayFill = (alias) => `(${SERVICE$1} or (${maySee(alias)} and ${ctx.scope.can(`${alias}.${co("tenant")}`, names.write)}))`;
37442
37566
  const json = (alias) => `jsonb_build_object(
@@ -38373,7 +38497,7 @@ ${renderPolicy(policy$1({
38373
38497
  }
38374
38498
  /** The registry types whose `cascade: true` deletes their entries and stars. */
38375
38499
  function cascading(ctx) {
38376
- return registeredSubjects(ctx.subjects, ctx.naming).filter((subject) => subject.config.cascade === true).map((subject) => [subject.type, {
38500
+ return registeredSubjects$1(ctx.subjects, ctx.naming).filter((subject) => subject.config.cascade === true).map((subject) => [subject.type, {
38377
38501
  table: subject.config.table,
38378
38502
  ...subject.config.id === void 0 ? {} : { id: subject.config.id },
38379
38503
  cascade: true,
@@ -38384,7 +38508,7 @@ function build$91(ctx, layout) {
38384
38508
  if (ctx.mode === "custom") return "";
38385
38509
  const keys = moduleOperations("collections");
38386
38510
  const teams = callerTeamIdsSql(ctx, layout);
38387
- const subjectTypes = registeredSubjects(ctx.subjects, ctx.naming).filter((subject) => subject.tenant !== void 0).map((subject) => subject.type);
38511
+ const subjectTypes = registeredSubjects$1(ctx.subjects, ctx.naming).filter((subject) => subject.tenant !== void 0).map((subject) => subject.type);
38388
38512
  const read = ctx.permission("read", keys.read);
38389
38513
  const names = {
38390
38514
  scope: ctx.scope,
@@ -40180,7 +40304,7 @@ begin
40180
40304
  ${fail$1("EVIDENCE_TASK_NOT_FOUND", "the evidence task isn't a task of this control", "P0002")}
40181
40305
  end if;
40182
40306
  end if;
40183
- if not (${allowed(`v_control.${k("tenant")}`, collect)}${assignee ? ` or (v_task.${t("assignee")} is not null and v_task.${t("assignee")} = auth.uid())` : ""}) then
40307
+ if not (${allowed(`v_control.${k("tenant")}`, collect)}${assignee ? ` or (v_task.${t("assignee")} is not null and coalesce(v_task.${t("assignee")} = auth.uid(), false))` : ""}) then
40184
40308
  ${forbidden("not allowed to collect evidence")}
40185
40309
  end if;
40186
40310
  ${has("evidence", "note") ? `if add_control_evidence.attachment_id is null and nullif(trim(add_control_evidence.note), '') is null then
@@ -44451,7 +44575,7 @@ begin
44451
44575
  if not found then
44452
44576
  ${fail$1("OBLIGATION_NOT_FOUND", "obligation not found", "P0002")}
44453
44577
  end if;
44454
- if not (${allowed(`v_row.${o("tenant")}`, write)} or v_row.${o("owner")} = auth.uid()) then
44578
+ if not (${allowed(`v_row.${o("tenant")}`, write)} or coalesce(v_row.${o("owner")} = auth.uid(), false)) then
44455
44579
  ${forbidden("not allowed to change this obligation")}
44456
44580
  end if;
44457
44581
  if set_obligation_status.status is null or set_obligation_status.status not in ('open', 'done', 'waived') then
@@ -44751,7 +44875,7 @@ ${renderPolicy(policy$1({
44751
44875
  /** Moves the contracts of a merged counterparty to the record it merged into. */
44752
44876
  function counterpartyMerges(ctx) {
44753
44877
  if (!keepsContract(ctx, "counterpartyType")) return "";
44754
- return subjectMergeHandler(ctx, registeredSubjects(ctx.subjects, ctx.naming).map((subject) => [subject.type, {
44878
+ return subjectMergeHandler(ctx, registeredSubjects$1(ctx.subjects, ctx.naming).map((subject) => [subject.type, {
44755
44879
  table: `${subject.schema}.${subject.table}`,
44756
44880
  extra: {}
44757
44881
  }]), moveSubjectRows({
@@ -45752,7 +45876,7 @@ begin
45752
45876
  if v_user is distinct from auth.uid() and not ${q.allowed(`v_course.${c("tenant")}`, q.enroll)} then
45753
45877
  ${q.forbidden("not allowed to enroll others in courses")}
45754
45878
  end if;
45755
- if v_user = auth.uid() and not (${q.allowed(`v_course.${c("tenant")}`, q.read)} or ${q.allowed(`v_course.${c("tenant")}`, q.enroll)}) then
45879
+ if coalesce(v_user = auth.uid(), false) and not (${q.allowed(`v_course.${c("tenant")}`, q.read)} or ${q.allowed(`v_course.${c("tenant")}`, q.enroll)}) then
45756
45880
  ${q.forbidden("not allowed to enroll in courses")}
45757
45881
  end if;
45758
45882
  if v_course.${c("status")} <> 'published' then
@@ -46723,7 +46847,7 @@ function keyedFields(ctx, keys, options) {
46723
46847
  s("label"),
46724
46848
  ctx.cast("values", "type", "v_type"),
46725
46849
  ...assignments.map(([, expression]) => expression),
46726
- ...ctx.has("values", "rank") ? [rankValue(s("rank"))] : []
46850
+ ...ctx.has("values", "rank") ? [integerRank ? `coalesce(${rankValue(s("rank"))}, (select coalesce(max(v.${c("rank")}), 0) + 1 from ${values} v where v.${c("tenant")} = ${s("tenant")} and ${subjectMatch(ctx, "v", s("subject_type"), s("subject_id"))}))` : rankValue(s("rank"))] : []
46727
46851
  ];
46728
46852
  const updates = [
46729
46853
  `${c("label")} = ${s("label")}`,
@@ -49038,7 +49162,7 @@ begin
49038
49162
  if v_row.${cd("tenant")} is null then
49039
49163
  return null;
49040
49164
  end if;
49041
- if not (${SERVICE_CALLER$1} or ${requested("requestedBy") ? `v_row.${cd("requestedBy")} = auth.uid() or ` : ""}${allowed})${platform} then
49165
+ if not (${SERVICE_CALLER$1} or ${requested("requestedBy") ? `coalesce(v_row.${cd("requestedBy")} = auth.uid(), false) or ` : ""}${allowed})${platform} then
49042
49166
  ${fail$1("ORGANIZATION_DELETION_FORBIDDEN", "You may not cancel this deletion")}
49043
49167
  end if;
49044
49168
  update ${d} x set ${cd("cancelledAt")} = now()
@@ -49495,6 +49619,7 @@ function lineItemsSql(ctx, items, options) {
49495
49619
  ["position", "x.ordinality::integer"]
49496
49620
  ].filter(([column]) => has(column)).map(([column, value]) => [column, column === "productType" ? ctx.cast(items.lines, column, value) : value]);
49497
49621
  const extras = items.extras ?? [];
49622
+ const extrasInsert = insertExtraColumns(t, extras, "(case when jsonb_typeof(x.value -> 'fields') = 'object' then x.value -> 'fields' end)");
49498
49623
  return `${ctx.manages ? `create table if not exists ${t} (
49499
49624
  ${c("id")} uuid primary key default gen_random_uuid(),
49500
49625
  ${c("tenant")} ${ctx.idType} not null,
@@ -49604,8 +49729,8 @@ begin
49604
49729
  end if;
49605
49730
  delete from ${t} l where l.${c("parent")} = v_parent${replaces ? "" : ` and l.${c("position")} > jsonb_array_length(coalesce(${options.setter}.lines, '[]'))`};
49606
49731
  begin
49607
- insert into ${t} (${written.map(([column]) => c(column)).join(", ")})
49608
- select ${written.map(([, value]) => value).join(",\n ")}
49732
+ insert into ${t} (${written.map(([column]) => c(column)).join(", ")}${extrasInsert.columns})
49733
+ select ${written.map(([, value]) => value).join(",\n ")}${extrasInsert.values}
49609
49734
  from jsonb_array_elements(coalesce(${options.setter}.lines, '[]')) with ordinality x${replaces ? "" : `\n on conflict (${c("parent")}, ${c("position")}) do update set ${written.filter(([column]) => ![
49610
49735
  "tenant",
49611
49736
  "parent",
@@ -49772,20 +49897,26 @@ function sequenceFormatOf(ctx, entity, tenant) {
49772
49897
  if (!ctx.installed("numbering")) return;
49773
49898
  const entry = sequenceEntry(ctx.of("numbering"), entity);
49774
49899
  if (entry === void 0 || typeof entry["format"] !== "string") return;
49775
- return isRecord$1(entry["formatFrom"]) ? `${ctx.of("numbering").fn("number_format")}(${tenant}, ${sqlString(entity)})` : sqlString(entry["format"]);
49900
+ return {
49901
+ format: isRecord$1(entry["formatFrom"]) ? `${ctx.of("numbering").fn("number_format")}(${tenant}, ${sqlString(entity)})` : sqlString(entry["format"]),
49902
+ assigns: typeof entry["table"] === "string"
49903
+ };
49776
49904
  }
49777
49905
  /**
49778
49906
  * PL/pgSQL that assigns the next number of `entity` in `tenant` to `target.seq`
49779
49907
  * (bigint) and `target.identifier` (text): from `numbering` when it numbers the
49780
49908
  * entity, otherwise one more than the tenant's highest in `fallback.table`
49781
- * under a transaction lock, with `prefix` in front (`DEAL-4821`).
49909
+ * under a transaction lock, with `prefix` in front (`DEAL-4821`). When the
49910
+ * entity has a table, the number is marked as issued for the transaction, so
49911
+ * its assign trigger accepts it on the block's insert instead of refusing it.
49782
49912
  */
49783
49913
  function assignNumberSql(ctx, entity, tenant, target, fallback) {
49784
- const format = sequenceFormatOf(ctx, entity, tenant);
49785
- if (format !== void 0) {
49914
+ const sequence = sequenceFormatOf(ctx, entity, tenant);
49915
+ if (sequence !== void 0) {
49786
49916
  const next = ctx.of("numbering").fn("next_number");
49787
49917
  return `${target.seq} := ${next}(${tenant}, ${sqlString(entity)}, now());
49788
- ${target.identifier} := better_supabase.format_assigned_number(${format}, ${target.seq}, now());`;
49918
+ ${target.identifier} := better_supabase.format_assigned_number(${sequence.format}, ${target.seq}, now());${sequence.assigns ? `
49919
+ perform set_config('better_supabase.issued_number', ${sqlString(entity)} || chr(31) || ${target.seq}::text || chr(31) || ${target.identifier}, true);` : ""}`;
49789
49920
  }
49790
49921
  return `perform pg_catalog.pg_advisory_xact_lock(pg_catalog.hashtextextended(${tenant}::text || ${sqlString(`:${entity}`)}, 0));
49791
49922
  select coalesce(max(x.${fallback.seq}), 0) + 1 into ${target.seq} from ${fallback.table} x where x.${fallback.tenant} = ${tenant};
@@ -49996,7 +50127,7 @@ function dealFunctions(ctx, n) {
49996
50127
  const stages = pipelines.table("stages");
49997
50128
  const s = (column) => pipelines.col("stages", column);
49998
50129
  const rotting = pipelines.has("stages", "rottingAfterDays") ? `st.${s("rottingAfterDays")} is not null and now() - coalesce(x.${d("stageEnteredAt")}, x.${d("createdAt")}) > make_interval(days => st.${s("rottingAfterDays")})` : "false";
49999
- const editable = (alias) => `(${n.service} or (${ctx.scope.can(`${alias}.${d("tenant")}`, n.write)} and (${n.readAll ? "true" : "false"} or ${alias}.${d("owner")} = auth.uid()
50130
+ const editable = (alias) => `(${n.service} or (${ctx.scope.can(`${alias}.${d("tenant")}`, n.write)} and (${n.readAll ? "true" : "false"} or coalesce(${alias}.${d("owner")} = auth.uid(), false)
50000
50131
  or ${ctx.scope.can(`${alias}.${d("tenant")}`, n.manage)}
50001
50132
  or exists (select 1 from ${t("members")} mm where mm.${m("deal")} = ${alias}.${d("id")} and mm.${m("user")} = auth.uid()))))`;
50002
50133
  const has = (column) => n.has("deals", column);
@@ -51612,7 +51743,7 @@ function functions$10(ctx, extras) {
51612
51743
  const { assets, bookings, catalog, inventory } = linked(ctx);
51613
51744
  const fields = extraFieldsArg(extras);
51614
51745
  const allowed = (tenant, permission) => `(${SERVICE_CALLER$1} or ${ctx.can("tenant", tenant, permission)})`;
51615
- const worker = (row) => `(${allowed(`${row}.${w("tenant")}`, manage)} or (${row}.${w("technician")} = auth.uid() and ${ctx.can("tenant", `${row}.${w("tenant")}`, work)}))`;
51746
+ const worker = (row) => `(${allowed(`${row}.${w("tenant")}`, manage)} or (coalesce(${row}.${w("technician")} = auth.uid(), false) and ${ctx.can("tenant", `${row}.${w("tenant")}`, work)}))`;
51616
51747
  const busy = list$6(BUSY);
51617
51748
  const orderJson = (row) => withExtraFields(`jsonb_build_object('id', ${row}.${w("id")}, 'organizationId', ${row}.${w("tenant")}::text, 'title', ${row}.${w("title")}, 'description', ${or("workOrders", row, "description")}, 'priority', ${row}.${w("priority")}, 'status', ${row}.${w("status")}, 'technicianId', ${row}.${w("technician")}, 'startsAt', ${row}.${w("startsAt")}, 'endsAt', ${row}.${w("endsAt")}, 'day', (${row}.${w("startsAt")} at time zone ${zone})::date, 'locationId', ${row}.${w("location")}, 'assetId', ${row}.${w("asset")}, 'bookingId', ${or("workOrders", row, "booking")}, 'subjectType', ${row}.${w("subjectType")}, 'subjectId', ${row}.${w("subjectId")}, 'address', ${or("workOrders", row, "address")}, 'enRouteAt', ${or("workOrders", row, "enRouteAt")}, 'arrivedAt', ${or("workOrders", row, "arrivedAt")}, 'completedAt', ${row}.${w("completedAt")}, 'cancelledAt', ${row}.${w("cancelledAt")}, 'cancelReason', ${or("workOrders", row, "cancelReason")}, 'completionNote', ${or("workOrders", row, "completionNote")}, 'createdBy', ${row}.${w("createdBy")}, 'createdAt', ${row}.${w("createdAt")}, 'updatedAt', ${row}.${w("updatedAt")})`, row, extras);
51618
51749
  const partJson = (row) => `jsonb_build_object('id', ${row}.${q("id")}, 'organizationId', ${row}.${q("tenant")}::text, 'workOrderId', ${row}.${q("workOrder")}, 'name', ${row}.${q("name")}, 'quantity', ${row}.${q("quantity")}::text, 'unit', ${or("parts", row, "unit")}, 'assetId', ${row}.${q("asset")}, 'variantId', ${row}.${q("variant")}, 'locationId', ${row}.${q("location")}, 'recordedBy', ${row}.${q("recordedBy")}, 'createdAt', ${row}.${q("createdAt")})`;
@@ -52068,7 +52199,7 @@ declare
52068
52199
  begin
52069
52200
  if v_technician is null or not (
52070
52201
  ${allowed("technician_day.tenant", read)}
52071
- or (v_technician = auth.uid() and ${ctx.can("tenant", "technician_day.tenant", work)})
52202
+ or (coalesce(v_technician = auth.uid(), false) and ${ctx.can("tenant", "technician_day.tenant", work)})
52072
52203
  ) then
52073
52204
  ${fail$1("DISPATCH_FORBIDDEN", "not allowed to read this technician's day")}
52074
52205
  end if;
@@ -52116,7 +52247,7 @@ declare
52116
52247
  begin
52117
52248
  if plan_dispatch_route.technician is null or not (
52118
52249
  ${allowed("plan_dispatch_route.tenant", manage)}
52119
- or (plan_dispatch_route.technician = auth.uid() and ${ctx.can("tenant", "plan_dispatch_route.tenant", work)})
52250
+ or (coalesce(plan_dispatch_route.technician = auth.uid(), false) and ${ctx.can("tenant", "plan_dispatch_route.tenant", work)})
52120
52251
  ) then
52121
52252
  ${fail$1("DISPATCH_FORBIDDEN", "not allowed to plan this technician's route")}
52122
52253
  end if;
@@ -52236,7 +52367,7 @@ begin
52236
52367
  select * into v_row from ${parts} y where y.${q("id")} = remove_work_order_part.part_id for update;
52237
52368
  if not found or not (
52238
52369
  ${allowed(`v_row.${q("tenant")}`, manage)}
52239
- or (v_row.${q("recordedBy")} = auth.uid() and ${ctx.can("tenant", `v_row.${q("tenant")}`, work)})
52370
+ or (coalesce(v_row.${q("recordedBy")} = auth.uid(), false) and ${ctx.can("tenant", `v_row.${q("tenant")}`, work)})
52240
52371
  ) then
52241
52372
  return false;
52242
52373
  end if;
@@ -52252,7 +52383,7 @@ ${userGrant(`${fn("remove_work_order_part")}(uuid)`)}
52252
52383
  * into.
52253
52384
  */
52254
52385
  function workOrderMerges(ctx) {
52255
- return subjectMergeHandler(ctx, registeredSubjects(ctx.subjects, ctx.naming).map((subject) => [subject.type, {
52386
+ return subjectMergeHandler(ctx, registeredSubjects$1(ctx.subjects, ctx.naming).map((subject) => [subject.type, {
52256
52387
  table: `${subject.schema}.${subject.table}`,
52257
52388
  extra: {}
52258
52389
  }]), moveSubjectRows({
@@ -52929,14 +53060,14 @@ begin
52929
53060
  if found then
52930
53061
  select * into v_doc from ${documents} d where d.${c("id")} = v_suggestion.${g("document")};
52931
53062
  end if;
52932
- if v_suggestion.${g("id")} is null or not (${SERVICE_CALLER$1} or ${canRead("v_doc")} or v_suggestion.${g("createdBy")} = auth.uid()) then
53063
+ if v_suggestion.${g("id")} is null or not (${SERVICE_CALLER$1} or ${canRead("v_doc")} or coalesce(v_suggestion.${g("createdBy")} = auth.uid(), false)) then
52933
53064
  ${fail$1("DOCUMENT_SUGGESTION_NOT_FOUND", "suggestion not found", "P0002")}
52934
53065
  end if;
52935
53066
  if decide_document_suggestion.decision is null or decide_document_suggestion.decision not in ('accepted', 'rejected', 'withdrawn') then
52936
53067
  ${fail$1("DOCUMENT_SUGGESTION_INVALID", "decide with accepted, rejected or withdrawn", "22023")}
52937
53068
  end if;
52938
53069
  if decide_document_suggestion.decision = 'withdrawn' then
52939
- if not (${SERVICE_CALLER$1} or v_suggestion.${g("createdBy")} = auth.uid()) then
53070
+ if not (${SERVICE_CALLER$1} or coalesce(v_suggestion.${g("createdBy")} = auth.uid(), false)) then
52940
53071
  ${fail$1("DOCUMENT_FORBIDDEN", "only the author can withdraw a suggestion")}
52941
53072
  end if;
52942
53073
  elsif not (${SERVICE_CALLER$1} or ${canWrite("v_doc")}) then
@@ -54861,8 +54992,9 @@ function trigger$1(ctx, item) {
54861
54992
  const sequence = item.sequenceColumn === void 0 ? void 0 : sqlIdent(item.sequenceColumn);
54862
54993
  const fn = sqlIdent(`bsb_assign_number_${item.name}`);
54863
54994
  const manual = fail$1("NUMBER_MANUAL", "a number is assigned by the sequence, not set by hand", "42501");
54995
+ const issued = `coalesce(v_issued[1] = ${sqlString(item.name)} and new.${col}::text in (v_issued[2], v_issued[3])${sequence === void 0 ? "" : ` and new.${sequence}::text = v_issued[2]`}, false)`;
54864
54996
  const manualSequence = sequence === void 0 ? "" : `
54865
- if not (${SERVICE_CALLER$1}) then
54997
+ if not (${SERVICE_CALLER$1} or ${issued}) then
54866
54998
  if tg_op = 'INSERT' then
54867
54999
  if new.${sequence} is not null then
54868
55000
  ${manual}
@@ -54881,6 +55013,7 @@ as $$
54881
55013
  declare
54882
55014
  v_n bigint;
54883
55015
  v_at timestamptz;
55016
+ v_issued text[] := string_to_array(coalesce(current_setting('better_supabase.issued_number', true), ''), chr(31));
54884
55017
  begin
54885
55018
  if not (better_supabase.actor_may_write()) then
54886
55019
  ${fail$1("ACTOR_READ_ONLY", "This session is read-only")}
@@ -54893,7 +55026,9 @@ begin
54893
55026
  end if;
54894
55027
  -- A number is assigned here or by the service role, never sent by a client.${manualSequence}
54895
55028
  if new.${col} is not null then
54896
- if not (${SERVICE_CALLER$1}) then
55029
+ if ${issued} then
55030
+ perform set_config('better_supabase.issued_number', '', true);
55031
+ elsif not (${SERVICE_CALLER$1}) then
54897
55032
  ${manual}
54898
55033
  end if;
54899
55034
  return new;
@@ -55289,7 +55424,7 @@ ${ctx.has("donations", "refundTransaction") ? `create index if not exists ${inde
55289
55424
  }
55290
55425
  /** Moves a merged donor's gifts, pledges and receipts to the record kept. */
55291
55426
  function donorMerges(ctx) {
55292
- const subjects = registeredSubjects(ctx.subjects, ctx.naming).map((subject) => [subject.type, {
55427
+ const subjects = registeredSubjects$1(ctx.subjects, ctx.naming).map((subject) => [subject.type, {
55293
55428
  table: `${subject.schema}.${subject.table}`,
55294
55429
  extra: {}
55295
55430
  }]);
@@ -57413,7 +57548,7 @@ function choice(ctx, name, values) {
57413
57548
  return value;
57414
57549
  }
57415
57550
  function candidateSubjectIdType(ctx, candidate) {
57416
- return registeredSubjects(ctx.subjects, ctx.naming).find((item) => item.type === candidate)?.config.idType ?? "text";
57551
+ return registeredSubjects$1(ctx.subjects, ctx.naming).find((item) => item.type === candidate)?.config.idType ?? "text";
57417
57552
  }
57418
57553
  function reviewable(check, editable, from) {
57419
57554
  return check === void 0 ? `(${editable})` : `(${editable} or exists (
@@ -57555,10 +57690,19 @@ function quoteFunctions(ctx, n) {
57555
57690
  ${fail$1(`QUOTE_${thing}_UNSUPPORTED`, `this quotes table has no ${what}`, "22023")}
57556
57691
  end if;`;
57557
57692
  const editable = (alias) => `(${n.service} or ${ctx.scope.can(`${alias}.${q("tenant")}`, n.write)})`;
57558
- const open = (alias) => `${alias}.${q("status")} in ('draft', 'changes_requested')`;
57693
+ const st = (value, labels, negate = false) => ctx.is("quotes", "status", value, labels, negate);
57694
+ const sv = (label) => ctx.value("quotes", "status", label);
57695
+ const viewed = ctx.appValues("quotes", "status", "viewed").length > 0;
57696
+ const markViewed = () => viewed || has("viewedAt") ? ` if ${st(`v_row.${q("status")}`, ["sent"])}${viewed ? "" : ` and v_row.${q("viewedAt")} is null`} then
57697
+ update ${t("quotes")} x set ${viewed ? `${q("status")} = ${sv("viewed")}${has("viewedAt") ? ", " : ""}` : ""}${has("viewedAt") ? `${q("viewedAt")} = now()` : ""} where x.${q("id")} = v_row.${q("id")}
57698
+ returning * into v_row;
57699
+ ${record("quote.viewed", "v_row")}
57700
+ end if;` : " null;";
57701
+ const open = (alias) => st(`${alias}.${q("status")}`, ["draft", "changes_requested"]);
57559
57702
  const lines = (alias) => `coalesce((select jsonb_agg(jsonb_build_object('description', ql.${l("description")}, 'quantity', ql.${l("quantity")}, 'unitAmount', ql.${l("unitAmount")}::text, 'discountBps', ${lineColumn(ctx, "lines", "ql", "discountBps")}, 'taxRateBps', ${lineColumn(ctx, "lines", "ql", "taxRateBps")}, 'taxCode', ${lineColumn(ctx, "lines", "ql", "taxCode")}, 'product', case when ${lineColumn(ctx, "lines", "ql", "productType")} is null then null else jsonb_build_object('type', ${lineColumn(ctx, "lines", "ql", "productType")}, 'id', ${lineColumn(ctx, "lines", "ql", "productId")}) end${lineFieldsJson("ql", n.lineExtras)}) order by ql.${l("position")}) from ${t("lines")} ql where ql.${l("parent")} = ${alias}.${q("id")}), '[]'::jsonb)`;
57560
57703
  const int8 = ["number", ...Object.keys(TOTAL_COLUMNS)].map(q);
57561
- const row = (alias) => `(to_jsonb(${alias}) - ${sqlString(q("tokenHash").replaceAll("\"", ""))}) || ${int8Text(alias, int8)} || jsonb_build_object('lines', ${lines(alias)}${n.extras.length === 0 ? "" : `, 'fields', ${columnsObject(alias, n.extras.map((extra) => extra.name))}`})`;
57704
+ const int8As = Object.fromEntries(["number", ...Object.keys(TOTAL_COLUMNS)].map((logical) => [logical, (value) => `${value}::text`]));
57705
+ const row = (alias) => `(${ctx.rowJson("quotes", alias, { as: int8As })} - ${sqlString(q("tokenHash").replaceAll("\"", ""))}${q("tokenHash") === "\"token_hash\"" ? "" : " - 'token_hash'"}) || ${int8Text(alias, int8)} || jsonb_build_object('lines', ${lines(alias)}${n.extras.length === 0 ? "" : `, 'fields', ${columnsObject(alias, n.extras.map((extra) => extra.name))}`})`;
57562
57706
  const record = (type, alias, extra = "") => ctx.record({
57563
57707
  type,
57564
57708
  payload: `jsonb_build_object('organizationId', ${alias}.${q("tenant")}, 'quoteId', ${alias}.${q("id")}, 'subjectType', 'quote', 'subjectId', ${alias}.${q("id")}::text, 'identifier', ${alias}.${q("identifier")}${extra})`,
@@ -57793,7 +57937,7 @@ begin
57793
57937
  ${fail$1("QUOTE_EMPTY", "a quote needs a line before it is sent", "23514")}
57794
57938
  end if;
57795
57939
  ${ctx.hook("before_quote_send", [["uuid", `v_row.${q("id")}`]])}
57796
- update ${t("quotes")} x set ${q("status")} = 'sent', ${q("sentAt")} = now(), ${q("tokenHash")} = ${sha256Hex$1("v_token")},
57940
+ update ${t("quotes")} x set ${q("status")} = ${sv("sent")}, ${q("sentAt")} = now(), ${q("tokenHash")} = ${sha256Hex$1("v_token")},
57797
57941
  ${q("decidedAt")} = null, ${q("decidedBy")} = null, ${has("decisionNote") ? `${q("decisionNote")} = null, ` : ""}${q("updatedAt")} = now()
57798
57942
  where x.${q("id")} = v_row.${q("id")}
57799
57943
  returning * into v_row;
@@ -57823,7 +57967,7 @@ begin
57823
57967
  if decide_quote.decision not in ('accepted', 'rejected', 'changes_requested') then
57824
57968
  ${fail$1("QUOTE_DECISION_INVALID", "decide accepted, rejected or changes_requested", "22023")}
57825
57969
  end if;
57826
- if v_row.${q("status")} not in ('sent', 'viewed') then
57970
+ if ${st(`v_row.${q("status")}`, ["sent", "viewed"], true)} then
57827
57971
  ${fail$1("QUOTE_NOT_OPEN", "only a sent quote takes a decision", "55000")}
57828
57972
  end if;
57829
57973
  if decide_quote.decision = 'accepted' then
@@ -57853,7 +57997,7 @@ begin
57853
57997
  if v_old.${q("id")} is null then
57854
57998
  ${fail$1("QUOTE_NOT_FOUND", "no such quote you can edit", "P0002")}
57855
57999
  end if;
57856
- if v_old.${q("status")} = 'draft' then
58000
+ if ${st(`v_old.${q("status")}`, ["draft"])} then
57857
58001
  ${fail$1("QUOTE_NOT_SENT", "a draft is edited, not revised", "55000")}
57858
58002
  end if;
57859
58003
  if exists (select 1 from ${t("quotes")} x where x.${q("supersedes")} = v_old.${q("id")}) then
@@ -57909,8 +58053,8 @@ begin
57909
58053
  insert into ${t("lines")} (${lineCopyColumns(ctx, "lines").map(l).join(", ")})
57910
58054
  select ${lineCopyColumns(ctx, "lines").map((column) => column === "parent" ? `v_row.${q("id")}` : `x.${l(column)}`).join(", ")}
57911
58055
  from ${t("lines")} x where x.${l("parent")} = v_old.${q("id")};
57912
- if v_old.${q("status")} <> 'accepted' then
57913
- update ${t("quotes")} x set ${q("status")} = 'withdrawn', ${q("tokenHash")} = null, ${q("updatedAt")} = now() where x.${q("id")} = v_old.${q("id")};
58056
+ if ${st(`v_old.${q("status")}`, ["accepted"], true)} then
58057
+ update ${t("quotes")} x set ${q("status")} = ${sv("withdrawn")}, ${q("tokenHash")} = null, ${q("updatedAt")} = now() where x.${q("id")} = v_old.${q("id")};
57914
58058
  end if;
57915
58059
  ${record("quote.revised", "v_old", `, 'revisionId', v_row.${q("id")}`)}
57916
58060
  return (select ${row("x")} from ${t("quotes")} x where x.${q("id")} = v_row.${q("id")});
@@ -57933,14 +58077,10 @@ begin
57933
58077
  if v_row.${q("id")} is null then
57934
58078
  ${fail$1("QUOTE_LINK_INVALID", "this link is not valid", "P0002")}
57935
58079
  end if;
57936
- if v_row.${q("status")} = 'sent' then
57937
- update ${t("quotes")} x set ${q("status")} = 'viewed'${has("viewedAt") ? `, ${q("viewedAt")} = now()` : ""} where x.${q("id")} = v_row.${q("id")}
57938
- returning * into v_row;
57939
- ${record("quote.viewed", "v_row")}
57940
- end if;
58080
+ ${markViewed()}
57941
58081
  return jsonb_build_object(
57942
58082
  'identifier', v_row.${q("identifier")}, 'revision', v_row.${q("revision")}, 'title', v_row.${q("title")},
57943
- 'status', v_row.${q("status")}, 'currency', v_row.${q("currency")}, 'validUntil', v_row.${q("validUntil")},
58083
+ 'status', ${ctx.label("quotes", "status", `v_row.${q("status")}`)}, 'currency', v_row.${q("currency")}, 'validUntil', v_row.${q("validUntil")},
57944
58084
  'terms', ${or("v_row", "terms")}, 'subtotal', v_row.${q("subtotal")}::text, 'discountTotal', v_row.${q("discountTotal")}::text,
57945
58085
  'taxTotal', v_row.${q("taxTotal")}::text, 'total', v_row.${q("total")}::text, 'lines', ${lines("v_row")});
57946
58086
  end;
@@ -57968,11 +58108,11 @@ begin
57968
58108
  if respond_to_quote.decision not in ('accepted', 'rejected', 'changes_requested') then
57969
58109
  ${fail$1("QUOTE_DECISION_INVALID", "answer accepted, rejected or changes_requested", "22023")}
57970
58110
  end if;
57971
- if v_row.${q("status")} not in ('sent', 'viewed') then
58111
+ if ${st(`v_row.${q("status")}`, ["sent", "viewed"], true)} then
57972
58112
  ${fail$1("QUOTE_NOT_OPEN", "this quote no longer takes an answer", "55000")}
57973
58113
  end if;
57974
58114
  if v_row.${q("validUntil")} < current_date then
57975
- update ${t("quotes")} x set ${q("status")} = 'expired', ${q("updatedAt")} = now() where x.${q("id")} = v_row.${q("id")}
58115
+ update ${t("quotes")} x set ${q("status")} = ${sv("expired")}, ${q("updatedAt")} = now() where x.${q("id")} = v_row.${q("id")}
57976
58116
  returning * into v_row;
57977
58117
  ${record("quote.expired", "v_row")}
57978
58118
  return jsonb_build_object('status', 'expired');
@@ -57986,7 +58126,7 @@ begin
57986
58126
  if respond_to_quote.decision = 'accepted' then
57987
58127
  ${ctx.hook("after_quote_accept", [["uuid", `v_row.${q("id")}`]])}
57988
58128
  end if;
57989
- return jsonb_build_object('status', v_row.${q("status")}, 'identifier', v_row.${q("identifier")});
58129
+ return jsonb_build_object('status', ${ctx.label("quotes", "status", `v_row.${q("status")}`)}, 'identifier', v_row.${q("identifier")});
57990
58130
  end;
57991
58131
  $$;
57992
58132
  revoke all on function ${fn("respond_to_quote")}(text, text, text, text) from public, anon, authenticated;
@@ -58004,8 +58144,8 @@ declare
58004
58144
  v_count integer := 0;
58005
58145
  begin
58006
58146
  for v_row in
58007
- update ${t("quotes")} x set ${q("status")} = 'expired', ${q("updatedAt")} = now()
58008
- where x.${q("status")} in ('sent', 'viewed') and x.${q("validUntil")} < current_date
58147
+ update ${t("quotes")} x set ${q("status")} = ${sv("expired")}, ${q("updatedAt")} = now()
58148
+ where ${st(`x.${q("status")}`, ["sent", "viewed"])} and x.${q("validUntil")} < current_date
58009
58149
  returning *
58010
58150
  loop
58011
58151
  ${record("quote.expired", "v_row")}
@@ -58147,17 +58287,16 @@ function employeeFunctions(ctx, n) {
58147
58287
  ...list.map((field) => e(field.column)),
58148
58288
  e("status"),
58149
58289
  ...origin ? [e("originType"), e("originId")] : [],
58150
- ...has("createdBy") ? [e("createdBy")] : [],
58151
- ...n.extras.map((extra) => extra.ident)
58290
+ ...has("createdBy") ? [e("createdBy")] : []
58152
58291
  ];
58153
58292
  const insertValues = [
58154
58293
  "create_employee.tenant",
58155
58294
  ...list.map((field) => field.column === "employmentType" ? ctx.cast("employees", "employmentType", `coalesce(${typeText(`create_employee.attrs -> 'employmentType'`)}, (${n.types})[1])`) : attr(field)),
58156
58295
  ctx.cast("employees", "status", "v_status"),
58157
58296
  ...origin ? ["create_employee.attrs -> 'origin' ->> 'type'", "create_employee.attrs -> 'origin' ->> 'id'"] : [],
58158
- ...has("createdBy") ? ["auth.uid()"] : [],
58159
- ...n.extras.map((extra) => extraValue("create_employee.attrs", extra.ident))
58297
+ ...has("createdBy") ? ["auth.uid()"] : []
58160
58298
  ];
58299
+ const extrasInsert = insertExtraColumns(table, n.extras, "create_employee.attrs");
58161
58300
  const existing = origin ? `
58162
58301
  if create_employee.attrs -> 'origin' ->> 'id' is not null then
58163
58302
  select * into v_row from ${table} x
@@ -58217,8 +58356,8 @@ begin
58217
58356
  if v_status = 'offboarded' then
58218
58357
  ${fail$1("EMPLOYEE_STATUS_INVALID", "create the employee, then offboard them", "22023")}
58219
58358
  end if;
58220
- insert into ${table} (${insertColumns.join(", ")})
58221
- values (${insertValues.join(", ")})
58359
+ insert into ${table} (${insertColumns.join(", ")}${extrasInsert.columns})
58360
+ values (${insertValues.join(", ")}${extrasInsert.values})
58222
58361
  returning * into v_row;
58223
58362
  exception
58224
58363
  when unique_violation then
@@ -58556,13 +58695,13 @@ const CONTACT_KEYS = {
58556
58695
  function sensitiveFunctions(ctx, n) {
58557
58696
  const e = (column) => n.c("employees", column);
58558
58697
  const employees = n.t("employees");
58559
- const reader = (alias) => `(${n.service} or ${ctx.scope.can(`${alias}.${e("tenant")}`, n.sensitive)} or ${alias}.${e("user")} = auth.uid())`;
58698
+ const reader = (alias) => `(${n.service} or ${ctx.scope.can(`${alias}.${e("tenant")}`, n.sensitive)} or coalesce(${alias}.${e("user")} = auth.uid(), false))`;
58560
58699
  const load = (fnName, arg, allowed) => `
58561
58700
  select * into v_employee from ${employees} x where x.${e("id")} = ${fnName}.${arg};
58562
58701
  if v_employee.${e("id")} is null or not ${allowed} then
58563
58702
  ${fail$1("EMPLOYEE_NOT_FOUND", "no such employee whose details you can see", "P0002")}
58564
58703
  end if;`;
58565
- const contractReader = (alias) => `(${n.service} or ${ctx.scope.can(`${alias}.${e("tenant")}`, n.contractsRead)} or ${alias}.${e("user")} = auth.uid())`;
58704
+ const contractReader = (alias) => `(${n.service} or ${ctx.scope.can(`${alias}.${e("tenant")}`, n.contractsRead)} or coalesce(${alias}.${e("user")} = auth.uid(), false))`;
58566
58705
  return `${privateSql(ctx, n, reader, load)}${contractsSql(ctx, n, contractReader, load)}`;
58567
58706
  }
58568
58707
  function privateSql(ctx, n, reader, load) {
@@ -58577,7 +58716,7 @@ function privateSql(ctx, n, reader, load) {
58577
58716
  const address = pairs(ADDRESS_KEYS, alias);
58578
58717
  const contact = pairs(CONTACT_KEYS, alias);
58579
58718
  const parts = [...address === "" || has("address") ? [] : [`'address', nullif(jsonb_strip_nulls(jsonb_build_object(${address})), '{}'::jsonb)`], ...contact === "" || has("emergencyContacts") ? [] : [`'emergency_contacts', case when ${flat.includes("emergencyName") ? `${alias}.${p("emergencyName")} is null` : "true"} then '[]'::jsonb else jsonb_build_array(jsonb_strip_nulls(jsonb_build_object(${contact}))) end`]];
58580
- return parts.length === 0 ? `to_jsonb(${alias})` : `(to_jsonb(${alias}) || jsonb_build_object(${parts.join(", ")}))`;
58719
+ return parts.length === 0 ? ctx.rowJson("privateDetails", alias) : `(${ctx.rowJson("privateDetails", alias)} || jsonb_build_object(${parts.join(", ")}))`;
58581
58720
  };
58582
58721
  const sets = [
58583
58722
  ...DETAILS.filter((detail) => has(detail.column)).map((detail) => {
@@ -58631,7 +58770,7 @@ as $$
58631
58770
  declare
58632
58771
  v_employee ${n.t("employees")};
58633
58772
  v_row ${table};
58634
- begin${load("save_employee_private_details", "employee", n.privateDetailsWrite === void 0 ? reader("v_employee") : `(${n.service} or (${ctx.scope.can(`v_employee.${e("tenant")}`, n.sensitive)} and ${ctx.scope.can(`v_employee.${e("tenant")}`, n.privateDetailsWrite)}) or v_employee.${e("user")} = auth.uid())`)}
58773
+ begin${load("save_employee_private_details", "employee", n.privateDetailsWrite === void 0 ? reader("v_employee") : `(${n.service} or (${ctx.scope.can(`v_employee.${e("tenant")}`, n.sensitive)} and ${ctx.scope.can(`v_employee.${e("tenant")}`, n.privateDetailsWrite)}) or coalesce(v_employee.${e("user")} = auth.uid(), false))`)}
58635
58774
  if jsonb_typeof(coalesce(save_employee_private_details.attrs, '{}')) <> 'object' then
58636
58775
  ${fail$1("EMPLOYEE_PRIVATE_INVALID", "attrs must be an object", "22023")}
58637
58776
  end if;
@@ -58661,7 +58800,9 @@ function contractsSql(ctx, n, reader, load) {
58661
58800
  const currency = has("currency");
58662
58801
  const major = majorSalary(ctx);
58663
58802
  const exponent = (code) => currency ? minorUnits(code) : "2";
58664
- const row = (alias) => salary ? major ? `to_jsonb(${alias}) || jsonb_build_object(${sqlString(k("salary").replaceAll("\"", ""))}, (${alias}.${k("salary")} * power(10, ${exponent(currency ? `${alias}.${k("currency")}` : "null")}))::bigint::text)` : `to_jsonb(${alias}) || ${int8Text(alias, [k("salary")])}` : `to_jsonb(${alias})`;
58803
+ const minorText = (alias, value) => major ? `(${value} * power(10, ${exponent(currency ? `${alias}.${k("currency")}` : "null")}))::bigint::text` : `${value}::text`;
58804
+ const json = (alias) => ctx.rowJson("contracts", alias, { as: { salary: (value) => minorText(alias, value) } });
58805
+ const row = (alias) => salary ? major ? `${json(alias)} || jsonb_build_object(${sqlString(k("salary").replaceAll("\"", ""))}, ${minorText(alias, `${alias}.${k("salary")}`)})` : `${json(alias)} || ${int8Text(alias, [k("salary")])}` : json(alias);
58665
58806
  const salaryValue = (minor, code) => major ? `(${minor})::numeric / power(10, ${exponent(code)})` : `(${minor})::bigint`;
58666
58807
  const arg = (key) => `add_employee_contract.attrs ->> ${sqlString(key)}`;
58667
58808
  const extras = ctx.extraColumns("contracts", [], "contractExtraColumns");
@@ -58691,6 +58832,14 @@ function contractsSql(ctx, n, reader, load) {
58691
58832
  ...has("note") ? [`nullif(trim(${arg("note")}), '')`] : [],
58692
58833
  ...has("createdBy") ? ["auth.uid()"] : []
58693
58834
  ];
58835
+ const insertWith = (skip) => `insert into ${table} (${columns.filter((column) => column !== skip).join(", ")}${required.columns})
58836
+ values (${values.filter((_, index) => columns[index] !== skip).join(", ")}${required.values})
58837
+ returning * into v_row;`;
58838
+ const insert = currency && !ctx.owns("contracts") ? `if add_employee_contract.attrs ? 'currency' then
58839
+ ${insertWith(void 0).replaceAll("\n ", "\n ")}
58840
+ else
58841
+ ${insertWith(k("currency")).replaceAll("\n ", "\n ")}
58842
+ end if;` : insertWith(void 0);
58694
58843
  const updated = ctx.record({
58695
58844
  type: "employee.updated",
58696
58845
  payload: `jsonb_build_object('organizationId', v_employee.${e("tenant")}, 'employeeId', v_employee.${e("id")}, 'subjectType', 'employee', 'subjectId', v_employee.${e("id")}::text, 'name', ${n.name("v_employee")}, 'fields', jsonb_build_array('contract'))`,
@@ -58742,9 +58891,7 @@ begin${load("add_employee_contract", "employee", contractWriter(ctx, n, "v_emplo
58742
58891
  end if;
58743
58892
  update ${table} x set ${k("endsOn")} = v_starts - 1
58744
58893
  where x.${k("employee")} = v_employee.${e("id")} and (x.${k("endsOn")} is null or x.${k("endsOn")} >= v_starts);`}
58745
- insert into ${table} (${columns.join(", ")}${required.columns})
58746
- values (${values.join(", ")}${required.values})
58747
- returning * into v_row;${writeExtraColumns(table, extras, fields, `x.${k("id")} = v_row.${k("id")}`, "v_row").replaceAll("\n ", "\n ")}
58894
+ ${insert}${writeExtraColumns(table, extras, fields, `x.${k("id")} = v_row.${k("id")}`, "v_row").replaceAll("\n ", "\n ")}
58748
58895
  exception when check_violation or not_null_violation or invalid_text_representation or invalid_datetime_format or datetime_field_overflow or numeric_value_out_of_range then
58749
58896
  ${fail$1("EMPLOYEE_CONTRACT_INVALID", "a contract field has an invalid value", "22023")}
58750
58897
  end;
@@ -58778,7 +58925,7 @@ function editContractsSql(ctx, n, names) {
58778
58925
  patch("endsOn", "endsOn", `(${text("endsOn")})::date`),
58779
58926
  patch("hoursPerWeek", "hoursPerWeek", `(${text("hoursPerWeek")})::numeric`),
58780
58927
  ...has("salary") ? [patch("salary", "salary", salaryValue(text("salary"), has("currency") ? `coalesce(upper(${text("currency")}), x.${k("currency")})` : "null"))] : [],
58781
- ...has("currency") ? [`${k("currency")} = case when ${attrs} ? 'salary' or ${attrs} ? 'currency' then upper(${text("currency")}) else x.${k("currency")} end`] : [],
58928
+ ...has("currency") ? [`${k("currency")} = case when ${attrs} ? 'currency' then upper(${text("currency")})${ctx.owns("contracts") ? ` when ${attrs} ? 'salary' and ${text("salary")} is null then null` : ""} else x.${k("currency")} end`] : [],
58782
58929
  ...has("salaryPeriod") ? [patch("salaryPeriod", "salaryPeriod", ctx.cast("contracts", "salaryPeriod", text("salaryPeriod")))] : [],
58783
58930
  ...has("note") ? [patch("note", "note", `nullif(trim(${text("note")}), '')`)] : []
58784
58931
  ];
@@ -59280,7 +59427,7 @@ function build$74(ctx) {
59280
59427
  service: "(auth.role() = 'service_role')",
59281
59428
  extras: ctx.extraColumns("employees", RESERVED$7),
59282
59429
  name: fullName,
59283
- json: (alias) => ctx.has("employees", "name") ? `to_jsonb(${alias})` : `(to_jsonb(${alias}) || jsonb_build_object('name', ${fullName(alias)}))`
59430
+ json: (alias) => ctx.has("employees", "name") ? ctx.rowJson("employees", alias) : `(${ctx.rowJson("employees", alias)} || jsonb_build_object('name', ${fullName(alias)}))`
59284
59431
  };
59285
59432
  return `${schemaPreamble(ctx)}
59286
59433
  -- Employees: the people an organization employs, with or without an
@@ -59837,7 +59984,7 @@ function enrollmentsFunctions(ctx) {
59837
59984
  ["steps", "enrollment_ensure.steps"],
59838
59985
  ["enrolledBy", "enrollment_ensure.actor"]
59839
59986
  ].filter(([column]) => ctx.has("enrollments", column));
59840
- const self = (row) => `(${row}.${e("user")} is not null and ${row}.${e("user")} = auth.uid())`;
59987
+ const self = (row) => `(${row}.${e("user")} is not null and coalesce(${row}.${e("user")} = auth.uid(), false))`;
59841
59988
  const programJson = (row) => `jsonb_build_object('id', ${row}.${p("id")}, 'organizationId', ${row}.${p("tenant")}, 'key', ${row}.${p("key")}, 'name', ${row}.${p("name")}, 'description', ${field("programs", row, "description")}, 'subjectTypes', to_jsonb(${row}.${p("subjectTypes")}), 'steps', ${row}.${p("steps")}, 'enabled', ${row}.${p("enabled")}, 'version', ${row}.${p("version")}, 'createdBy', ${field("programs", row, "createdBy")}, 'createdAt', ${field("programs", row, "createdAt")}, 'updatedAt', ${field("programs", row, "updatedAt")})`;
59842
59989
  const programRecord = (type, row, summary) => ctx.record({
59843
59990
  type,
@@ -60215,7 +60362,7 @@ as $$
60215
60362
  declare
60216
60363
  v_id uuid;
60217
60364
  begin
60218
- if not (${allowed("enrollment.tenant", read)} or (enrollment.subject_type = 'user' and enrollment.subject_id = auth.uid()::text)) then
60365
+ if not (${allowed("enrollment.tenant", read)} or (enrollment.subject_type = 'user' and coalesce(enrollment.subject_id = auth.uid()::text, false))) then
60219
60366
  ${forbidden("not allowed to read enrollments")}
60220
60367
  end if;
60221
60368
  select x.${e("id")} into v_id from ${enrollments} x
@@ -61184,7 +61331,7 @@ function expensesFunctions(ctx) {
61184
61331
  end if;
61185
61332
  select * into v_approval from ${ar} p where p.${a("id")} = v_row.${r("approval")};`;
61186
61333
  const ownerOnly = `
61187
- if not (v_row.${r("user")} = auth.uid() and ${ctx.can("tenant", `v_row.${r("tenant")}`, submit)}) then
61334
+ if not (coalesce(v_row.${r("user")} = auth.uid(), false) and ${ctx.can("tenant", `v_row.${r("tenant")}`, submit)}) then
61188
61335
  ${forbidden("only the member who owns the report can change it")}
61189
61336
  end if;`;
61190
61337
  const editable = `
@@ -61192,7 +61339,7 @@ function expensesFunctions(ctx) {
61192
61339
  ${fail$1("EXPENSE_REPORT_LOCKED", "only a draft or rejected report can change", "55000")}
61193
61340
  end if;`;
61194
61341
  const reader = `
61195
- if not (v_row.${r("user")} = auth.uid() or ${can(`v_row.${r("tenant")}`, read)}) then
61342
+ if not (coalesce(v_row.${r("user")} = auth.uid(), false) or ${can(`v_row.${r("tenant")}`, read)}) then
61196
61343
  ${fail$1("EXPENSE_REPORT_NOT_FOUND", "no such expense report", "P0002")}
61197
61344
  end if;`;
61198
61345
  const categoryCheck = (category, tenant) => `
@@ -61583,7 +61730,7 @@ declare
61583
61730
  v_row ${reports}%rowtype;
61584
61731
  v_approval ${ar}%rowtype;
61585
61732
  begin${loadReport("cancel_expense_report.report_id", true)}
61586
- if not (v_row.${r("user")} = auth.uid() or ${can(`v_row.${r("tenant")}`, manage)}) then
61733
+ if not (coalesce(v_row.${r("user")} = auth.uid(), false) or ${can(`v_row.${r("tenant")}`, manage)}) then
61587
61734
  ${forbidden("not allowed to cancel this expense report")}
61588
61735
  end if;
61589
61736
  if ${status("v_row", "v_approval")} not in ('draft', 'submitted', 'rejected') then
@@ -61633,7 +61780,7 @@ begin
61633
61780
  if not (v_reader or ${ctx.can("tenant", "list_expense_reports.tenant", submit)}) then
61634
61781
  ${forbidden("not allowed to list expense reports")}
61635
61782
  end if;
61636
- if not v_reader and (coalesce(list_expense_reports.everyone, false) or (list_expense_reports.user_id is not null and list_expense_reports.user_id <> auth.uid())) then
61783
+ if not v_reader and (coalesce(list_expense_reports.everyone, false) or (list_expense_reports.user_id is not null and list_expense_reports.user_id is distinct from auth.uid())) then
61637
61784
  ${forbidden("not allowed to read another member's expenses")}
61638
61785
  end if;
61639
61786
  return (
@@ -62065,7 +62212,7 @@ const COLUMN$5 = /^[a-z_][a-z0-9_]{0,62}$/u;
62065
62212
  * `config.subjects`.
62066
62213
  */
62067
62214
  function historyBindings(ctx) {
62068
- const registry = registeredSubjects(ctx.subjects, ctx.naming);
62215
+ const registry = registeredSubjects$1(ctx.subjects, ctx.naming);
62069
62216
  return Object.entries(onSettings(ctx)).map(([type, settings]) => {
62070
62217
  const where = `blocks.field-history.on.${type}`;
62071
62218
  const subject = registry.find((item) => item.type === type);
@@ -64570,7 +64717,7 @@ begin
64570
64717
  if not found then
64571
64718
  ${submissionNotFound}
64572
64719
  end if;
64573
- if not (${SERVICE_CALLER$1} or v_row.${s("respondent")} = auth.uid() or ${ctx.can("tenant", `v_row.${s("tenant")}`, review)}) then
64720
+ if not (${SERVICE_CALLER$1} or coalesce(v_row.${s("respondent")} = auth.uid(), false) or ${ctx.can("tenant", `v_row.${s("tenant")}`, review)}) then
64574
64721
  ${submissionNotFound}
64575
64722
  end if;
64576
64723
  return ${submissionJson("v_row")};
@@ -64663,7 +64810,7 @@ begin
64663
64810
  ${submissionNotFound}
64664
64811
  end if;
64665
64812
  if not (${SERVICE_CALLER$1} or ${ctx.can("tenant", `v_row.${s("tenant")}`, review)}
64666
- or (v_row.${s("respondent")} = auth.uid() and v_row.${s("status")} = 'draft')) then
64813
+ or (coalesce(v_row.${s("respondent")} = auth.uid(), false) and v_row.${s("status")} = 'draft')) then
64667
64814
  ${fail$1("FORM_FORBIDDEN", "not allowed to delete this submission")}
64668
64815
  end if;
64669
64816
  delete from ${submissions} x where x.${s("id")} = delete_form_submission.submission_id;
@@ -64779,7 +64926,7 @@ function ledgerFunctions(ctx) {
64779
64926
  const hasMemo = ctx.has("transactions", "memo");
64780
64927
  const memo = (row) => hasMemo ? `${row}.${t("memo")}` : "null::text";
64781
64928
  const allowed = (tenant, permission) => `(${SERVICE_CALLER$1} or ${ctx.can("tenant", tenant, permission)})`;
64782
- const visible = (row) => `(${SERVICE_CALLER$1} or ${ctx.can("tenant", `${row}.${a("tenant")}`, read)} or ${row}.${a("owner")} = auth.uid() or (${row}.${a("readPermission")} is not null and ${ctx.can("tenant", `${row}.${a("tenant")}`, `${row}.${a("readPermission")}`)}))`;
64929
+ const visible = (row) => `(${SERVICE_CALLER$1} or ${ctx.can("tenant", `${row}.${a("tenant")}`, read)} or coalesce(${row}.${a("owner")} = auth.uid(), false) or (${row}.${a("readPermission")} is not null and ${ctx.can("tenant", `${row}.${a("tenant")}`, `${row}.${a("readPermission")}`)}))`;
64783
64930
  const forbidden = (message) => fail$1("LEDGER_FORBIDDEN", message);
64784
64931
  const invalid = (code, message) => fail$1(code, message, "22023");
64785
64932
  const accountJson = (row, balance) => `jsonb_build_object('id', ${row}.${a("id")}, 'organizationId', ${row}.${a("tenant")}, 'kind', ${row}.${a("kind")}, 'code', ${row}.${a("code")}, 'name', ${row}.${a("name")}, 'unit', ${row}.${a("unit")}, 'scale', ${row}.${a("scale")}, 'holderType', ${row}.${a("holderType")}, 'holderId', ${row}.${a("holderId")}, 'ownerId', ${row}.${a("owner")}, 'allowNegative', ${row}.${a("allowNegative")}, 'readPermission', ${row}.${a("readPermission")}, 'managedBy', ${row}.${a("managedBy")}, 'metadata', ${row}.${a("metadata")}, 'closedAt', ${row}.${a("closedAt")}, 'createdAt', ${row}.${a("createdAt")}, 'balance', coalesce(${balance}.${b("balance")}, 0)::text, 'held', coalesce(${balance}.${b("held")}, 0)::text, 'available', coalesce(${balance}.${b("balance")} - ${balance}.${b("held")}, 0)::text)`;
@@ -67005,7 +67152,7 @@ ${tables$19(ctx)}${functions$7(ctx, layout)}${grantMerges(ctx)}`;
67005
67152
  }
67006
67153
  /** Moves the grants on a merged registered subject to the record it merged into. */
67007
67154
  function grantMerges(ctx) {
67008
- return subjectMergeHandler(ctx, registeredSubjects(ctx.subjects, ctx.naming).map((subject) => [subject.type, {
67155
+ return subjectMergeHandler(ctx, registeredSubjects$1(ctx.subjects, ctx.naming).map((subject) => [subject.type, {
67009
67156
  table: `${subject.schema}.${subject.table}`,
67010
67157
  extra: {}
67011
67158
  }]), moveSubjectRows({
@@ -67583,14 +67730,14 @@ function build$63(ctx) {
67583
67730
  const candidateType = (row) => hiringCandidate(ctx, row).type;
67584
67731
  const candidateId = (row) => hiringCandidate(ctx, row).id;
67585
67732
  const candidateValue = (value) => fixedCandidate ? asColumnType(t("applications"), ctx.colName("applications", "candidateId"), value) : value;
67586
- const applicationJson = (alias) => fixedCandidate ? `(to_jsonb(${alias}) || jsonb_build_object('candidate_type', ${sqlString(candidate)}, ${sqlString(ctx.colName("applications", "candidateId"))}, ${alias}.${a("candidateId")}::text))` : `to_jsonb(${alias})`;
67733
+ const applicationJson = (alias) => fixedCandidate ? `(${ctx.rowJson("applications", alias, { as: { candidateId: (value) => `${value}::text` } })} || jsonb_build_object('candidate_type', ${sqlString(candidate)}, ${sqlString(ctx.colName("applications", "candidateId"))}, ${alias}.${a("candidateId")}::text))` : ctx.rowJson("applications", alias);
67587
67734
  const interviewerOf = (row, user) => {
67588
67735
  const checks = [...ctx.has("interviews", "interviewers") ? [`${user} = any (${row}.${v("interviewers")})`] : [], ...interviewerRows ? [`exists (select 1 from ${t("interviewers")} z where z.${iv("interview")} = ${row}.${v("id")} and z.${iv("user")} = ${user})`] : []];
67589
67736
  if (checks.length <= 1) return checks[0];
67590
67737
  return `(${checks.join(" or ")})`;
67591
67738
  };
67592
- const interviewJson = (alias) => interviewerRows ? `(to_jsonb(${alias}) || jsonb_build_object('interviewer_user_ids', (select coalesce(jsonb_agg(z.${iv("user")} order by z.${iv("user")}), '[]'::jsonb) from ${t("interviewers")} z where z.${iv("interview")} = ${alias}.${v("id")})))` : `to_jsonb(${alias})`;
67593
- const scorecardJson = (alias) => scoreRows ? `(to_jsonb(${alias}) || jsonb_build_object('scores', (select coalesce(jsonb_agg(jsonb_build_object('criterion', y.${sc("criterion")}, 'score', y.${sc("score")}, 'notes', ${ctx.has("scorecardScores", "notes") ? `y.${sc("notes")}` : "null"}) order by y.${sc("criterion")}), '[]'::jsonb) from ${t("scorecardScores")} y where y.${sc("scorecard")} = ${alias}.${s("id")})))` : `to_jsonb(${alias})`;
67739
+ const interviewJson = (alias) => interviewerRows ? `(${ctx.rowJson("interviews", alias)} || jsonb_build_object('interviewer_user_ids', (select coalesce(jsonb_agg(z.${iv("user")} order by z.${iv("user")}), '[]'::jsonb) from ${t("interviewers")} z where z.${iv("interview")} = ${alias}.${v("id")})))` : ctx.rowJson("interviews", alias);
67740
+ const scorecardJson = (alias) => scoreRows ? `(${ctx.rowJson("scorecards", alias)} || jsonb_build_object('scores', (select coalesce(jsonb_agg(jsonb_build_object('criterion', y.${sc("criterion")}, 'score', y.${sc("score")}, 'notes', ${ctx.has("scorecardScores", "notes") ? `y.${sc("notes")}` : "null"}) order by y.${sc("criterion")}), '[]'::jsonb) from ${t("scorecardScores")} y where y.${sc("scorecard")} = ${alias}.${s("id")})))` : ctx.rowJson("scorecards", alias);
67594
67741
  const managerValue = managerEmployee && ctx.has("jobs", "hiringManager") ? asColumnType(t("jobs"), ctx.colName("jobs", "hiringManager"), "save_job.attrs ->> 'hiringManagerId'") : "(save_job.attrs ->> 'hiringManagerId')::uuid";
67595
67742
  const column = (table, logical, type) => ctx.has(table, logical) ? `\n ${ctx.col(table, logical)} ${type},` : "";
67596
67743
  const or = (table, row, logical) => ctx.has(table, logical) ? `${row}.${ctx.col(table, logical)}` : "null";
@@ -67818,7 +67965,7 @@ begin
67818
67965
  ${jobRecord("job.closed")}
67819
67966
  end if;
67820
67967
  end if;
67821
- return ${withExtraFields("to_jsonb(v_job)", "v_job", extras)};
67968
+ return ${withExtraFields(ctx.rowJson("jobs", "v_job"), "v_job", extras)};
67822
67969
  end;
67823
67970
  $$;
67824
67971
  ${userGrant(`${fn("save_job")}(${ctx.idType}, uuid, jsonb)`)}
@@ -70532,7 +70679,7 @@ declare
70532
70679
  v_before uuid;${notifyDeclare}
70533
70680
  begin
70534
70681
  ${loadConversation("assign_conversation.conversation")}
70535
- if not (${service} or ${command("assign", "assign")} or (assignee = (select auth.uid()) and ${staffCan("reply")})) then
70682
+ if not (${service} or ${command("assign", "assign")} or (coalesce(assignee = (select auth.uid()), false) and ${staffCan("reply")})) then
70536
70683
  ${forbidden("not allowed to assign this conversation")}
70537
70684
  end if;
70538
70685
  if assignee is not null and not ${ctx.scope.canUser("assignee", `v_conv.${cv("tenant")}`, q.key("read"))} then
@@ -70697,7 +70844,7 @@ begin
70697
70844
  if not found then
70698
70845
  ${missing("message", "MESSAGE_NOT_FOUND")}
70699
70846
  end if;
70700
- if not (${service} or (v_msg.${cm("author")} is not null and v_msg.${cm("author")} = (select auth.uid()))) then
70847
+ if not (${service} or (v_msg.${cm("author")} is not null and coalesce(v_msg.${cm("author")} = (select auth.uid()), false))) then
70701
70848
  ${forbidden("only the author edits a message")}
70702
70849
  end if;
70703
70850
  if v_msg.${cm("deletedAt")} is not null then
@@ -73666,7 +73813,7 @@ function transferFunctions(ctx, names) {
73666
73813
  const t = columns$1(ctx, "transfers");
73667
73814
  const tl = columns$1(ctx, "transferLines");
73668
73815
  const l = locationsOf(ctx).col;
73669
- const load = (name) => `select x.${t("tenant")} as tenant, x.${t("from")} as from_location, x.${t("to")} as to_location, x.${t("status")} as status
73816
+ const load = (name) => `select x.${t("tenant")} as tenant, x.${t("from")} as from_location, x.${t("to")} as to_location, ${ctx.label("transfers", "status", `x.${t("status")}`)} as status
73670
73817
  into v_row from ${transfers} x where x.${t("id")} = ${name}.transfer for update;
73671
73818
  if not found then
73672
73819
  ${fail$1("INVENTORY_TRANSFER_NOT_FOUND", "transfer not found", "P0002")}
@@ -73737,7 +73884,7 @@ begin
73737
73884
  ${statusError}
73738
73885
  end if;
73739
73886
  ${move("ship_transfer", "v_row.from_location", "-", "transfer_out")}
73740
- update ${transfers} x set ${t("status")} = 'in_transit', ${t("shippedAt")} = now() where x.${t("id")} = ship_transfer.transfer;
73887
+ update ${transfers} x set ${t("status")} = ${ctx.value("transfers", "status", "in_transit")}, ${t("shippedAt")} = now() where x.${t("id")} = ship_transfer.transfer;
73741
73888
  ${event("transfer.shipped", "ship_transfer", "'in_transit'")}
73742
73889
  return true;
73743
73890
  end;
@@ -73759,7 +73906,7 @@ begin
73759
73906
  ${statusError}
73760
73907
  end if;
73761
73908
  ${move("receive_transfer", "v_row.to_location", "", "transfer_in")}
73762
- update ${transfers} x set ${t("status")} = 'received', ${t("receivedAt")} = now() where x.${t("id")} = receive_transfer.transfer;
73909
+ update ${transfers} x set ${t("status")} = ${ctx.value("transfers", "status", "received")}, ${t("receivedAt")} = now() where x.${t("id")} = receive_transfer.transfer;
73763
73910
  ${event("transfer.received", "receive_transfer", "'received'")}
73764
73911
  return true;
73765
73912
  end;
@@ -73783,7 +73930,7 @@ begin
73783
73930
  if v_row.status = 'in_transit' then
73784
73931
  ${move("cancel_transfer", "v_row.from_location", "", "transfer_in")}
73785
73932
  end if;
73786
- update ${transfers} x set ${t("status")} = 'cancelled' where x.${t("id")} = cancel_transfer.transfer;
73933
+ update ${transfers} x set ${t("status")} = ${ctx.value("transfers", "status", "cancelled")} where x.${t("id")} = cancel_transfer.transfer;
73787
73934
  ${event("transfer.cancelled", "cancel_transfer", "'cancelled'")}
73788
73935
  return true;
73789
73936
  end;
@@ -73803,7 +73950,7 @@ function purchaseOrderFunctions(ctx, names) {
73803
73950
  const lv = columns$1(ctx, "levels");
73804
73951
  const l = locationsOf(ctx).col;
73805
73952
  const currencyUnits = ctx.of("catalog").fn("currency_minor_units");
73806
- const load = (name) => `select x.${po("tenant")} as tenant, x.${po("location")} as location, x.${po("status")} as status,
73953
+ const load = (name) => `select x.${po("tenant")} as tenant, x.${po("location")} as location, ${ctx.label("purchaseOrders", "status", `x.${po("status")}`)} as status,
73807
73954
  x.${po("supplierType")} as supplier_type, x.${po("supplierId")} as supplier_id
73808
73955
  into v_row from ${orders} x where x.${po("id")} = ${name}.purchase_order for update;
73809
73956
  if not found then
@@ -73856,7 +74003,7 @@ begin
73856
74003
  update ${orders} x set ${po("location")} = save_purchase_order.location, ${po("supplierType")} = save_purchase_order.supplier_type,
73857
74004
  ${po("supplierId")} = save_purchase_order.supplier_id, ${po("currency")} = save_purchase_order.currency,
73858
74005
  ${po("expectedAt")} = save_purchase_order.expected_at, ${po("note")} = save_purchase_order.note, ${po("updatedAt")} = now()
73859
- where x.${po("id")} = v_id and x.${po("status")} = 'draft';
74006
+ where x.${po("id")} = v_id and ${ctx.is("purchaseOrders", "status", `x.${po("status")}`, ["draft"])};
73860
74007
  if not found then
73861
74008
  ${fail$1("INVENTORY_PURCHASE_ORDER_LOCKED", "only a draft purchase order can change", "55000")}
73862
74009
  end if;
@@ -73889,7 +74036,7 @@ begin
73889
74036
  from ${lines} y where y.${pl("order")} = place_purchase_order.purchase_order
73890
74037
  on conflict (${lv("variant")}, ${lv("location")}) do update
73891
74038
  set ${lv("incoming")} = x.${lv("incoming")} + excluded.${lv("incoming")}, ${lv("updatedAt")} = now();
73892
- update ${orders} x set ${po("status")} = 'ordered', ${po("placedAt")} = now(), ${po("updatedAt")} = now()
74039
+ update ${orders} x set ${po("status")} = ${ctx.value("purchaseOrders", "status", "ordered")}, ${po("placedAt")} = now(), ${po("updatedAt")} = now()
73893
74040
  where x.${po("id")} = place_purchase_order.purchase_order;
73894
74041
  ${event("purchase_order.placed", "place_purchase_order", "'ordered'")}
73895
74042
  return true;
@@ -73975,7 +74122,7 @@ begin
73975
74122
  where y.${pl("order")} = cancel_purchase_order.purchase_order
73976
74123
  and x.${lv("variant")} = y.${pl("variant")} and x.${lv("location")} = v_row.location;
73977
74124
  end if;
73978
- update ${orders} x set ${po("status")} = 'cancelled', ${po("updatedAt")} = now()
74125
+ update ${orders} x set ${po("status")} = ${ctx.value("purchaseOrders", "status", "cancelled")}, ${po("updatedAt")} = now()
73979
74126
  where x.${po("id")} = cancel_purchase_order.purchase_order;
73980
74127
  ${event("purchase_order.cancelled", "cancel_purchase_order", "'cancelled'")}
73981
74128
  return true;
@@ -74137,7 +74284,8 @@ const NAMES$60 = {
74137
74284
  expiresAt: "expires_at",
74138
74285
  createdAt: "created_at",
74139
74286
  updatedAt: "updated_at"
74140
- }
74287
+ },
74288
+ typed: ["status"]
74141
74289
  },
74142
74290
  transfers: {
74143
74291
  name: "stock_transfers",
@@ -74154,7 +74302,8 @@ const NAMES$60 = {
74154
74302
  createdAt: "created_at",
74155
74303
  shippedAt: "shipped_at",
74156
74304
  receivedAt: "received_at"
74157
- }
74305
+ },
74306
+ typed: ["status"]
74158
74307
  },
74159
74308
  transferLines: {
74160
74309
  name: "stock_transfer_lines",
@@ -74933,7 +75082,7 @@ function build$56(ctx, layout) {
74933
75082
  const restoring = ctx.flag("restore", false);
74934
75083
  const derivedSlug = "trim(both '-' from regexp_replace(lower(create_team.name), '[^a-z0-9]+', '-', 'g'))";
74935
75084
  const drops = (fn, head, tails) => tails.map((tail) => `drop function if exists ${fn}(${head}${tail});`).join("\n");
74936
- const teamJson = (alias) => `jsonb_build_object('id', ${alias}.${id}, 'slug', ${alias}.${slug}${extraFieldsJson(alias, extras)})`;
75085
+ const teamJson = (alias) => `jsonb_build_object('id', ${alias}.${id}, 'name', ${alias}.${name}, 'slug', ${alias}.${slug}, 'description', ${alias}.${description}, 'status', ${alias}.${status}${extraFieldsJson(alias, extras)})`;
74937
75086
  const idDefault = idType === "uuid" ? " default gen_random_uuid()" : " generated always as identity";
74938
75087
  const tables = ctx.manages ? `create table if not exists ${teams} (
74939
75088
  ${id} ${idType} primary key${idDefault},
@@ -75012,7 +75161,8 @@ ${patching ? drops(fn("create_team"), `${ctx.idType}, text, text`, [
75012
75161
  "",
75013
75162
  ", jsonb",
75014
75163
  extras.length === 0 ? ", text, jsonb" : ", text"
75015
- ]) : extra.drop(fn("create_team"), `${ctx.idType}, text, text`)}
75164
+ ]) : `${extra.drop(fn("create_team"), `${ctx.idType}, text, text`)}
75165
+ ${drops(fn("create_team"), `${ctx.idType}, text, text`, [", text", ", text, jsonb"])}`}
75016
75166
  create or replace function ${fn("create_team")}(tenant ${ctx.idType}, name text, description text${patching ? ", slug text default null" : ""}${extra.param})
75017
75167
  returns jsonb
75018
75168
  language plpgsql
@@ -75078,7 +75228,7 @@ ${patching ? ` if update_team.patch is not null and (jsonb_typeof(update_team.p
75078
75228
  ${updatedAt} = now()`}
75079
75229
  where t.${id} = update_team.team;${writeExtraColumns(teams, extras, "update_team.fields", `x.${id} = update_team.team`)}
75080
75230
  ${record$1(ctx, "team.updated", "update_team.team", "v_tenant", "update_team.name")}
75081
- return ${extras.length === 0 ? "jsonb_build_object('id', update_team.team)" : `(select ${teamJson("x")} from ${teams} x where x.${id} = update_team.team)`};
75231
+ return (select ${teamJson("x")} from ${teams} x where x.${id} = update_team.team);
75082
75232
  end;
75083
75233
  $$;
75084
75234
  ${userGrant(`${fn("update_team")}(${idType}, text, text${patching ? ", jsonb" : ""}${extra.type})`)}
@@ -75213,8 +75363,14 @@ as $$
75213
75363
  'id', t.${id},
75214
75364
  'name', t.${name},
75215
75365
  'slug', t.${slug},
75216
- 'status', t.${status}${extraFieldsJson("t", extras)}
75217
- )), '[]'::jsonb)
75366
+ 'description', t.${description},
75367
+ 'status', t.${status},
75368
+ 'member_ids', coalesce((
75369
+ select jsonb_agg(m.${memberUser} order by m.${memberCreated})
75370
+ from ${members} m
75371
+ where m.${memberTeam} = t.${id}
75372
+ ), '[]'::jsonb)${extraFieldsJson("t", extras)}
75373
+ ) order by t.${name}), '[]'::jsonb)
75218
75374
  from ${teams} t
75219
75375
  where t.${tenant} = list_teams.tenant
75220
75376
  and (
@@ -75235,7 +75391,8 @@ function membershipFk(ctx, members, tenant, user) {
75235
75391
  alter table ${members}
75236
75392
  add constraint ${ctx.naming.rename("team_members_membership_fkey")}
75237
75393
  foreign key (${tenant}, ${user})
75238
- references ${memberships.table("memberships")} (${memberships.col("memberships", "tenant")}, ${memberships.col("memberships", "user")});`;
75394
+ references ${memberships.table("memberships")} (${memberships.col("memberships", "tenant")}, ${memberships.col("memberships", "user")})
75395
+ on delete cascade;`;
75239
75396
  }
75240
75397
  function membershipCheck(ctx, tenant, user) {
75241
75398
  if (!ctx.installed("memberships")) return "";
@@ -76153,6 +76310,147 @@ as $$
76153
76310
  $$;`;
76154
76311
  }
76155
76312
  //#endregion
76313
+ //#region src/sql/modules/permissions-roles.ts
76314
+ /**
76315
+ * `list_roles` and `set_permission_override`: the catalog's tenant roles with
76316
+ * their keys in one tenant, and the per-tenant grant or deny of one key. Only
76317
+ * the catalog model with the overrides table renders them.
76318
+ */
76319
+ const rendersRoleFunctions = (ctx) => accessModel(ctx) === "catalog" && ctx.hasTable("overrides");
76320
+ function catalogRoleFunctions(ctx) {
76321
+ const id = ctx.idType;
76322
+ if (!rendersRoleFunctions(ctx)) return `
76323
+ drop function if exists ${ctx.fn("list_roles")}(${id});
76324
+ drop function if exists ${ctx.fn("set_permission_override")}(${id}, text, text, boolean);`;
76325
+ const members = ctx.of("memberships");
76326
+ const m = members.table("memberships");
76327
+ const mTenant = members.col("memberships", "tenant");
76328
+ const mUser = members.col("memberships", "user");
76329
+ const mRole = members.col("memberships", "role");
76330
+ const roles = ctx.table("roles");
76331
+ const rId = ctx.col("roles", "id");
76332
+ const rKey = ctx.col("roles", "key");
76333
+ const perms = ctx.table("permissions");
76334
+ const pId = ctx.col("permissions", "id");
76335
+ const pKey = ctx.col("permissions", "key");
76336
+ const rp = ctx.table("rolePermissions");
76337
+ const rpRole = ctx.col("rolePermissions", "role");
76338
+ const rpPermission = ctx.col("rolePermissions", "permission");
76339
+ const o = ctx.table("overrides");
76340
+ const oTenant = ctx.col("overrides", "tenant");
76341
+ const oRole = ctx.col("overrides", "role");
76342
+ const oPermission = ctx.col("overrides", "permission");
76343
+ const oGranted = ctx.col("overrides", "granted");
76344
+ const listKey = ctx.permission("listRoles", OPERATIONS["permissions.listRoles"]);
76345
+ const manageKey = ctx.permission("setOverride", OPERATIONS["permissions.setOverride"]);
76346
+ const tenantRole = roleScopeIs(ctx, "r", "tenant");
76347
+ const scoped = tenantRole ? ` and ${tenantRole}` : "";
76348
+ const memberCan = (tenant, key) => `coalesce(better_supabase.member_can(auth.uid(), ${tenant}, ${key}), false)`;
76349
+ const roleJson = (tenant) => `jsonb_build_object(
76350
+ 'id', r.${rId},
76351
+ 'key', r.${rKey},
76352
+ 'members', (select count(*) from ${m} mm where mm.${mTenant} = ${tenant} and mm.${mRole} = r.${rId}),
76353
+ 'default_permissions', coalesce((
76354
+ select jsonb_agg(p.${pKey} order by p.${pKey})
76355
+ from ${rp} x join ${perms} p on p.${pId} = x.${rpPermission}
76356
+ where x.${rpRole} = r.${rId}
76357
+ ), '[]'::jsonb),
76358
+ 'permissions', coalesce((
76359
+ select jsonb_agg(p.${pKey} order by p.${pKey})
76360
+ from ${perms} p
76361
+ where coalesce(
76362
+ (select bool_and(ov.${oGranted}) from ${o} ov
76363
+ where ov.${oTenant} = ${tenant} and ov.${oRole} = r.${rId} and ov.${oPermission} = p.${pId}),
76364
+ exists (select 1 from ${rp} x where x.${rpRole} = r.${rId} and x.${rpPermission} = p.${pId})
76365
+ )
76366
+ ), '[]'::jsonb),
76367
+ 'overrides', coalesce((
76368
+ select jsonb_agg(jsonb_build_object('permission', p.${pKey}, 'granted', ov.${oGranted}) order by p.${pKey})
76369
+ from ${o} ov join ${perms} p on p.${pId} = ov.${oPermission}
76370
+ where ov.${oTenant} = ${tenant} and ov.${oRole} = r.${rId}
76371
+ ), '[]'::jsonb)
76372
+ )`;
76373
+ return `
76374
+ -- The tenant roles of the catalog with their keys in one tenant: the role's
76375
+ -- defaults, the keys after this tenant's overrides, the overrides and how many
76376
+ -- members hold the role.
76377
+ create or replace function ${ctx.fn("list_roles")}(tenant ${id})
76378
+ returns jsonb
76379
+ language plpgsql
76380
+ stable
76381
+ security definer
76382
+ set search_path = ''
76383
+ as $$
76384
+ begin
76385
+ if not (${SERVICE_CALLER$1} or ${memberCan("list_roles.tenant", listKey)}) then
76386
+ ${fail$1("PERMISSIONS_FORBIDDEN", "Not allowed to read roles")}
76387
+ end if;
76388
+ return coalesce((
76389
+ select jsonb_agg(${roleJson("list_roles.tenant")} order by r.${rKey})
76390
+ from ${roles} r
76391
+ where true${scoped}
76392
+ ), '[]'::jsonb);
76393
+ end;
76394
+ $$;
76395
+ ${userGrant(`${ctx.fn("list_roles")}(${id})`)}
76396
+
76397
+ -- Grants (true) or denies (false) one key to a role in one tenant; null
76398
+ -- clears the override, so the role's default applies again. Members change
76399
+ -- only roles they could assign, and only keys they hold themselves.
76400
+ -- Errors carry a code in the hint: PERMISSIONS_FORBIDDEN, PERMISSIONS_ROLE_UNKNOWN,
76401
+ -- PERMISSIONS_KEY_UNKNOWN, PERMISSIONS_ROLE_CEILING, PERMISSIONS_KEY_CEILING,
76402
+ -- PERMISSIONS_SELF_LOCKOUT.
76403
+ create or replace function ${ctx.fn("set_permission_override")}(tenant ${id}, role text, permission text, granted boolean)
76404
+ returns jsonb
76405
+ language plpgsql
76406
+ security definer
76407
+ set search_path = ''
76408
+ as $$
76409
+ #variable_conflict use_variable
76410
+ declare
76411
+ v_role uuid;
76412
+ v_permission uuid;
76413
+ v_service boolean := ${SERVICE_CALLER$1};
76414
+ begin
76415
+ if not (v_service or ${memberCan("tenant", manageKey)}) then
76416
+ ${fail$1("PERMISSIONS_FORBIDDEN", "Not allowed to change role permissions")}
76417
+ end if;
76418
+ select r.${rId} into v_role from ${roles} r
76419
+ where (r.${rId}::text = role or r.${rKey} = role)${scoped};
76420
+ if v_role is null then
76421
+ ${fail$1("PERMISSIONS_ROLE_UNKNOWN", "Unknown role", "P0002")}
76422
+ end if;
76423
+ select p.${pId} into v_permission from ${perms} p where p.${pKey} = permission;
76424
+ if v_permission is null then
76425
+ ${fail$1("PERMISSIONS_KEY_UNKNOWN", "Unknown permission", "P0002")}
76426
+ end if;
76427
+ if not v_service then
76428
+ if not better_supabase.can_assign(tenant, v_role::text) then
76429
+ ${fail$1("PERMISSIONS_ROLE_CEILING", "That role is above your own")}
76430
+ end if;
76431
+ if not ${memberCan("tenant", "permission")} then
76432
+ ${fail$1("PERMISSIONS_KEY_CEILING", "You can only change keys you hold")}
76433
+ end if;
76434
+ if granted is distinct from true and permission = ${manageKey} and exists (
76435
+ select 1 from ${m} mm where mm.${mTenant} = tenant and mm.${mUser} = auth.uid() and mm.${mRole} = v_role
76436
+ ) then
76437
+ ${fail$1("PERMISSIONS_SELF_LOCKOUT", "You cannot take this key from your own role")}
76438
+ end if;
76439
+ end if;
76440
+ if granted is null then
76441
+ delete from ${o} ov
76442
+ where ov.${oTenant} = tenant and ov.${oRole} = v_role and ov.${oPermission} = v_permission;
76443
+ else
76444
+ insert into ${o} (${oTenant}, ${oRole}, ${oPermission}, ${oGranted})
76445
+ values (tenant, v_role, v_permission, granted)
76446
+ on conflict (${oTenant}, ${oRole}, ${oPermission}) do update set ${oGranted} = excluded.${oGranted};
76447
+ end if;
76448
+ return (select ${roleJson("set_permission_override.tenant")} from ${roles} r where r.${rId} = v_role);
76449
+ end;
76450
+ $$;
76451
+ ${userGrant(`${ctx.fn("set_permission_override")}(${id}, text, text, boolean)`)}`;
76452
+ }
76453
+ //#endregion
76156
76454
  //#region src/sql/modules/permissions.ts
76157
76455
  const SERVICE = `coalesce(auth.jwt() ->> 'role', '') = 'service_role'`;
76158
76456
  const NOT_ACTING = `(platform_can.member is distinct from auth.uid() or auth.jwt() -> 'act' is null)`;
@@ -76918,7 +77216,7 @@ as $$
76918
77216
  select coalesce(better_supabase.platform_can(auth.uid(), is_platform.permission), false)
76919
77217
  $$;
76920
77218
 
76921
- ${myPermissionsSql(id)}${providerGuestFunctions(ctx.installedModules, layout)}
77219
+ ${myPermissionsSql(id)}${providerGuestFunctions(ctx.installedModules, layout)}${catalogRoleFunctions(ctx)}
76922
77220
 
76923
77221
  ${[
76924
77222
  "permission_matches(text, text)",
@@ -77079,6 +77377,7 @@ const ACCESS = {
77079
77377
  returns: "jsonb"
77080
77378
  }
77081
77379
  ],
77380
+ unusedPermissions: (ctx) => rendersRoleFunctions(ctx) ? [] : ["listRoles", "setOverride"],
77082
77381
  build: accessSql
77083
77382
  };
77084
77383
  //#endregion
@@ -78079,6 +78378,8 @@ function invoiceFunctions(ctx, n) {
78079
78378
  ${fail$1(`INVOICE_${thing}_UNSUPPORTED`, `this invoices table has no ${what}`, "22023")}
78080
78379
  end if;`;
78081
78380
  const can = (alias, permission) => `(${n.service} or ${ctx.scope.can(`${alias}.${i("tenant")}`, permission)})`;
78381
+ const st = (value, labels, negate = false) => ctx.is("invoices", "status", value, labels, negate);
78382
+ const kd = (value, labels, negate = false) => ctx.is("invoices", "kind", value, labels, negate);
78082
78383
  const balance = (alias) => `(${alias}.${i("total")} - ${alias}.${i("creditedTotal")} - ${alias}.${i("paidTotal")})`;
78083
78384
  const int8 = [
78084
78385
  "number",
@@ -78086,9 +78387,15 @@ function invoiceFunctions(ctx, n) {
78086
78387
  "creditedTotal",
78087
78388
  ...Object.keys(TOTAL_COLUMNS)
78088
78389
  ].map(i);
78089
- const row = (alias) => `to_jsonb(${alias}) || ${int8Text(alias, int8)} || jsonb_build_object(
78390
+ const int8Text8 = Object.fromEntries([
78391
+ "number",
78392
+ "paidTotal",
78393
+ "creditedTotal",
78394
+ ...Object.keys(TOTAL_COLUMNS)
78395
+ ].map((logical) => [logical, (value) => `${value}::text`]));
78396
+ const row = (alias) => `${ctx.rowJson("invoices", alias, { as: int8Text8 })} || ${int8Text(alias, int8)} || jsonb_build_object(
78090
78397
  'balance', ${balance(alias)}::text,
78091
- 'overdue', ${alias}.${i("status")} in ('issued', 'partially_paid') and ${alias}.${i("dueOn")} < current_date,
78398
+ 'overdue', ${st(`${alias}.${i("status")}`, ["issued", "partially_paid"])} and ${alias}.${i("dueOn")} < current_date,
78092
78399
  'lines', coalesce((select jsonb_agg(jsonb_build_object('description', il.${l("description")}, 'quantity', il.${l("quantity")}, 'unitAmount', il.${l("unitAmount")}::text, 'discountBps', ${lineColumn(ctx, "lines", "il", "discountBps")}, 'taxRateBps', ${lineColumn(ctx, "lines", "il", "taxRateBps")}, 'taxCode', ${lineColumn(ctx, "lines", "il", "taxCode")}${lineFieldsJson("il", n.lineExtras)}) order by il.${l("position")}) from ${t("lines")} il where il.${l("parent")} = ${alias}.${i("id")}), '[]'::jsonb),
78093
78400
  'payments', ${ledger.payments(alias)})`;
78094
78401
  const record = (type, alias, extra = "", audit = false) => ctx.record({
@@ -78120,7 +78427,11 @@ function invoiceFunctions(ctx, n) {
78120
78427
  when x.${i("paidTotal")} > 0 or x.${i("creditedTotal")} > 0 then 'partially_paid'
78121
78428
  else 'issued' end`)},
78122
78429
  ${i("paidAt")} = case when ${balance("x")} <= 0 then coalesce(x.${i("paidAt")}, now()) end
78123
- where x.${i("id")} = ${alias}.${i("id")} and x.${i("status")} in ('issued', 'partially_paid', 'paid')
78430
+ where x.${i("id")} = ${alias}.${i("id")} and ${st(`x.${i("status")}`, [
78431
+ "issued",
78432
+ "partially_paid",
78433
+ "paid"
78434
+ ])}
78124
78435
  returning * into ${alias};`;
78125
78436
  const quotes = ctx.installed("quotes") ? ctx.of("quotes") : void 0;
78126
78437
  const fromQuote = quotes === void 0 ? "" : (() => {
@@ -78132,7 +78443,7 @@ function invoiceFunctions(ctx, n) {
78132
78443
  if invoice_from_quote.deposit_bps is null then
78133
78444
  select * into v_row from ${t("invoices")} x
78134
78445
  where x.${i("originType")} = 'quote' and x.${i("originId")} = v_quote.${q("id")}::text
78135
- and ${deposits ? `x.${i("depositBps")} is null and ` : ""}x.${i("status")} <> 'void' and x.${i("kind")} = 'invoice'
78446
+ and ${deposits ? `x.${i("depositBps")} is null and ` : ""}${st(`x.${i("status")}`, ["void"], true)} and ${kd(`x.${i("kind")}`, ["invoice"])}
78136
78447
  limit 1;
78137
78448
  if v_row.${i("id")} is not null then
78138
78449
  return ${row("v_row")};
@@ -78146,7 +78457,7 @@ function invoiceFunctions(ctx, n) {
78146
78457
  'taxRateBps', case when d.${i("subtotal")} = 0 then 0 else round(d.${i("taxTotal")} * 10000.0 / d.${i("subtotal")})::integer end)), '[]'::jsonb)
78147
78458
  into v_lines
78148
78459
  from ${t("invoices")} d
78149
- where d.${i("originType")} = 'quote' and d.${i("originId")} = v_quote.${q("id")}::text and d.${i("depositBps")} is not null and d.${i("status")} not in ('draft', 'void');` : ""}
78460
+ where d.${i("originType")} = 'quote' and d.${i("originId")} = v_quote.${q("id")}::text and d.${i("depositBps")} is not null and ${st(`d.${i("status")}`, ["draft", "void"], true)};` : ""}
78150
78461
  else
78151
78462
  v_lines := jsonb_build_array(jsonb_build_object(
78152
78463
  'description', 'Deposit ' || (invoice_from_quote.deposit_bps / 100.0)::text || '% of ' || v_quote.${q("identifier")},
@@ -78179,7 +78490,7 @@ begin
78179
78490
  if v_quote.${q("id")} is null or not (${n.service} or ${ctx.scope.can(`v_quote.${q("tenant")}`, n.write)}) then
78180
78491
  ${fail$1("INVOICE_ORIGIN_NOT_FOUND", "no such quote you can invoice", "P0002")}
78181
78492
  end if;
78182
- if v_quote.${q("status")} <> 'accepted' then
78493
+ if ${quotes.is("quotes", "status", `v_quote.${q("status")}`, ["accepted"], true)} then
78183
78494
  ${fail$1("INVOICE_QUOTE_NOT_ACCEPTED", "only an accepted quote is invoiced", "55000")}
78184
78495
  end if;
78185
78496
  if invoice_from_quote.deposit_bps is not null and (invoice_from_quote.deposit_bps <= 0 or invoice_from_quote.deposit_bps >= 10000) then
@@ -78191,7 +78502,7 @@ $$;
78191
78502
  ${userGrant(`${fn("invoice_from_quote")}(uuid, integer)`)}
78192
78503
  `;
78193
78504
  })();
78194
- const kindTable = (kind) => `(select * from ${t("invoices")} k where k.${i("kind")} = ${kind})`;
78505
+ const kindTable = (kind) => `(select * from ${t("invoices")} k where ${kd(`k.${i("kind")}`, [kind])})`;
78195
78506
  return `
78196
78507
  -- Creates a draft invoice. attrs: title (required), currency, company and
78197
78508
  -- contact ({ type, id }), termsDays, note, origin ({ type, id }) and the
@@ -78247,7 +78558,7 @@ ${userGrant(`${fn("create_invoice")}(${ctx.idType}, jsonb, jsonb)`)}
78247
78558
  ${lineItemsSql(ctx, {
78248
78559
  lines: "lines",
78249
78560
  parent: "invoices",
78250
- frozen: `p.${i("status")} <> 'draft'`,
78561
+ frozen: st(`p.${i("status")}`, ["draft"], true),
78251
78562
  extras: n.lineExtras
78252
78563
  }, {
78253
78564
  setter: "set_invoice_lines",
@@ -78274,14 +78585,14 @@ begin
78274
78585
  if v_row.${i("id")} is null then
78275
78586
  ${fail$1("INVOICE_NOT_FOUND", "no such invoice you can edit", "P0002")}
78276
78587
  end if;
78277
- if v_row.${i("status")} <> 'draft' then
78588
+ if ${st(`v_row.${i("status")}`, ["draft"], true)} then
78278
78589
  ${fail$1("INVOICE_NOT_DRAFT", "the invoice was already issued", "55000")}
78279
78590
  end if;
78280
78591
  if not exists (select 1 from ${t("lines")} x where x.${l("parent")} = v_row.${i("id")}) then
78281
78592
  ${fail$1("INVOICE_EMPTY", "an invoice needs a line before it is issued", "23514")}
78282
78593
  end if;
78283
78594
  ${ctx.hook("before_invoice_issue", [["uuid", `v_row.${i("id")}`]])}
78284
- if v_row.${i("kind")} = 'credit_note' then
78595
+ if ${kd(`v_row.${i("kind")}`, ["credit_note"])} then
78285
78596
  select * into v_original from ${t("invoices")} x where x.${i("id")} = v_row.${i("original")} for update;
78286
78597
  if v_row.${i("total")} > ${balance("v_original")} then
78287
78598
  ${fail$1("INVOICE_CREDIT_TOO_LARGE", "a credit note can't exceed what is still owed", "23514")}
@@ -78290,7 +78601,7 @@ begin
78290
78601
  seq: "v_seq",
78291
78602
  identifier: "v_identifier"
78292
78603
  }, {
78293
- table: kindTable("'credit_note'"),
78604
+ table: kindTable("credit_note"),
78294
78605
  seq: i("number"),
78295
78606
  tenant: i("tenant"),
78296
78607
  prefix: n.creditPrefix
@@ -78300,25 +78611,25 @@ begin
78300
78611
  seq: "v_seq",
78301
78612
  identifier: "v_identifier"
78302
78613
  }, {
78303
- table: kindTable("'invoice'"),
78614
+ table: kindTable("invoice"),
78304
78615
  seq: i("number"),
78305
78616
  tenant: i("tenant"),
78306
78617
  prefix: n.prefix
78307
78618
  })}
78308
78619
  end if;
78309
- update ${t("invoices")} x set ${i("status")} = 'issued', ${i("number")} = v_seq, ${i("identifier")} = v_identifier,
78620
+ update ${t("invoices")} x set ${i("status")} = ${ctx.value("invoices", "status", "issued")}, ${i("number")} = v_seq, ${i("identifier")} = v_identifier,
78310
78621
  ${i("issuedOn")} = coalesce(issue_invoice.issued_on, current_date),
78311
78622
  ${i("dueOn")} = coalesce(issue_invoice.issued_on, current_date) + x.${i("termsDays")},
78312
78623
  ${i("updatedAt")} = now()
78313
78624
  where x.${i("id")} = v_row.${i("id")}
78314
78625
  returning * into v_row;
78315
78626
  ${record("invoice.issued", "v_row", `, 'total', v_row.${i("total")}::text, 'currency', v_row.${i("currency")}, 'dueOn', v_row.${i("dueOn")}`)}
78316
- if v_row.${i("kind")} = 'credit_note' then
78627
+ if ${kd(`v_row.${i("kind")}`, ["credit_note"])} then
78317
78628
  update ${t("invoices")} x set ${i("creditedTotal")} = x.${i("creditedTotal")} + v_row.${i("total")}, ${i("updatedAt")} = now()
78318
78629
  where x.${i("id")} = v_original.${i("id")}
78319
78630
  returning * into v_original;${settle("v_original")}
78320
78631
  ${record("invoice.credited", "v_original", `, 'creditNoteId', v_row.${i("id")}, 'amount', v_row.${i("total")}::text`)}
78321
- if v_original.${i("status")} = 'paid' then
78632
+ if ${st(`v_original.${i("status")}`, ["paid"])} then
78322
78633
  ${record("invoice.paid", "v_original", `, 'total', v_original.${i("total")}::text`)}
78323
78634
  end if;
78324
78635
  end if;
@@ -78349,7 +78660,11 @@ begin
78349
78660
  if v_row.${i("id")} is null then
78350
78661
  ${fail$1("INVOICE_NOT_FOUND", "no such invoice you can edit", "P0002")}
78351
78662
  end if;
78352
- if v_row.${i("kind")} <> 'invoice' or v_row.${i("status")} not in ('issued', 'partially_paid', 'paid') then
78663
+ if ${kd(`v_row.${i("kind")}`, ["invoice"], true)} or ${st(`v_row.${i("status")}`, [
78664
+ "issued",
78665
+ "partially_paid",
78666
+ "paid"
78667
+ ], true)} then
78353
78668
  ${fail$1("INVOICE_NOT_PAYABLE", "only an issued invoice takes payments", "55000")}
78354
78669
  end if;
78355
78670
  if coalesce(record_invoice_payment.amount, 0) = 0 then
@@ -78373,7 +78688,7 @@ begin
78373
78688
  v_was := v_row.${i("status")};
78374
78689
  v_payment := ${ledger.post("v_row", "record_invoice_payment.amount", "coalesce(record_invoice_payment.paid_at, now())", "record_invoice_payment.method", "v_reference")};${settle("v_row")}
78375
78690
  ${record("invoice.payment_recorded", "v_row", `, 'paymentId', v_payment, 'amount', record_invoice_payment.amount::text, 'balance', ${balance("v_row")}::text`)}
78376
- if v_row.${i("status")} = 'paid' and v_was <> 'paid' then
78691
+ if ${st(`v_row.${i("status")}`, ["paid"])} and ${st("v_was", ["paid"], true)} then
78377
78692
  ${record("invoice.paid", "v_row", `, 'total', v_row.${i("total")}::text`)}
78378
78693
  end if;
78379
78694
  ${ctx.hook("after_invoice_payment", [["uuid", `v_row.${i("id")}`], ["uuid", "v_payment"]])}
@@ -78398,7 +78713,11 @@ begin
78398
78713
  if v_original.${i("id")} is null then
78399
78714
  ${fail$1("INVOICE_NOT_FOUND", "no such invoice you can edit", "P0002")}
78400
78715
  end if;
78401
- if v_original.${i("kind")} <> 'invoice' or v_original.${i("status")} not in ('issued', 'partially_paid', 'paid') then
78716
+ if ${kd(`v_original.${i("kind")}`, ["invoice"], true)} or ${st(`v_original.${i("status")}`, [
78717
+ "issued",
78718
+ "partially_paid",
78719
+ "paid"
78720
+ ], true)} then
78402
78721
  ${fail$1("INVOICE_NOT_CREDITABLE", "only an issued invoice is credited", "55000")}
78403
78722
  end if;
78404
78723
  insert into ${t("invoices")} (${valueLines(" ", [
@@ -78418,7 +78737,7 @@ begin
78418
78737
  ])})
78419
78738
  values (${valueLines(" ", [
78420
78739
  `v_original.${i("tenant")}`,
78421
- "'credit_note'",
78740
+ ctx.value("invoices", "kind", "credit_note"),
78422
78741
  `v_original.${i("id")}`,
78423
78742
  `'Credit for ' || coalesce(v_original.${i("identifier")}, v_original.${i("title")})`
78424
78743
  ], [
@@ -78461,10 +78780,10 @@ begin
78461
78780
  if v_row.${i("id")} is null then
78462
78781
  ${fail$1("INVOICE_NOT_FOUND", "no such invoice you can manage", "P0002")}
78463
78782
  end if;
78464
- if v_row.${i("status")} not in ('draft', 'issued') or v_row.${i("paidTotal")} <> 0 or v_row.${i("creditedTotal")} <> 0 then
78783
+ if ${st(`v_row.${i("status")}`, ["draft", "issued"], true)} or v_row.${i("paidTotal")} <> 0 or v_row.${i("creditedTotal")} <> 0 then
78465
78784
  ${fail$1("INVOICE_NOT_VOIDABLE", "an invoice with payments or credits is credited, not voided", "55000")}
78466
78785
  end if;
78467
- update ${t("invoices")} x set ${i("status")} = 'void', ${i("voidedAt")} = now(),
78786
+ update ${t("invoices")} x set ${i("status")} = ${ctx.value("invoices", "status", "void")}, ${i("voidedAt")} = now(),
78468
78787
  ${has("voidReason") ? `${i("voidReason")} = nullif(trim(void_invoice.reason), ''), ` : ""}${i("updatedAt")} = now()
78469
78788
  where x.${i("id")} = v_row.${i("id")} returning * into v_row;
78470
78789
  ${record("invoice.voided", "v_row", `, 'reason', ${has("voidReason") ? `v_row.${i("voidReason")}` : "nullif(trim(void_invoice.reason), '')"}`, true)}
@@ -78483,8 +78802,8 @@ as $$
78483
78802
  declare
78484
78803
  v_row ${t("invoices")};
78485
78804
  begin
78486
- update ${t("invoices")} x set ${i("status")} = 'uncollectible', ${i("updatedAt")} = now()
78487
- where x.${i("id")} = write_off_invoice.invoice and ${can("x", n.manage)} and x.${i("status")} in ('issued', 'partially_paid')
78805
+ update ${t("invoices")} x set ${i("status")} = ${ctx.value("invoices", "status", "uncollectible")}, ${i("updatedAt")} = now()
78806
+ where x.${i("id")} = write_off_invoice.invoice and ${can("x", n.manage)} and ${st(`x.${i("status")}`, ["issued", "partially_paid"])}
78488
78807
  returning * into v_row;
78489
78808
  if v_row.${i("id")} is null then
78490
78809
  ${fail$1("INVOICE_NOT_OPEN", "only an open invoice you can manage is written off", "55000")}
@@ -78508,7 +78827,7 @@ as $$
78508
78827
  select ${balance("x")} as balance, coalesce(invoice_aging.as_of, current_date) - x.${i("dueOn")} as late
78509
78828
  from ${t("invoices")} x
78510
78829
  where x.${i("tenant")} = invoice_aging.tenant and x.${i("currency")} = upper(invoice_aging.currency)
78511
- and x.${i("kind")} = 'invoice' and x.${i("status")} in ('issued', 'partially_paid')
78830
+ and ${kd(`x.${i("kind")}`, ["invoice"])} and ${st(`x.${i("status")}`, ["issued", "partially_paid"])}
78512
78831
  )
78513
78832
  select jsonb_build_object(
78514
78833
  'currency', upper(invoice_aging.currency),
@@ -79106,7 +79425,7 @@ function build$54(ctx, layout) {
79106
79425
  ];
79107
79426
  const unique = (table, what, columns) => ctx.owns(table) ? "" : `\ncreate unique index if not exists ${sqlIdent(`bsb_${ctx.tableName(table).name}_${what}_key`)} on ${ctx.table(table)} (${columns});`;
79108
79427
  const readable = `(${d.owner} = (select auth.uid()) or (${d.scope} in ('organization', 'agent') and ${ctx.scope.check(d.tenant, read)}) or ${ctx.scope.check(d.tenant, manage)} or (${d.scope} = 'chat' and ${chatReadable(d.scopeId)}))`;
79109
- const ownDocument = (row) => `(${SERVICE_CALLER$1} or ${row}.${d.owner} = auth.uid() or ${ctx.scope.can(`${row}.${d.tenant}`, manage)})`;
79428
+ const ownDocument = (row) => `(${SERVICE_CALLER$1} or coalesce(${row}.${d.owner} = auth.uid(), false) or ${ctx.scope.can(`${row}.${d.tenant}`, manage)})`;
79110
79429
  const notFound = raise$1("document % not found", "P0002", "KNOWLEDGE_NOT_FOUND", "document_id");
79111
79430
  return `${schemaPreamble(ctx)}
79112
79431
  -- Documents for retrieval: uploaded files, pasted text and synced rows, split
@@ -80618,7 +80937,7 @@ ${renderPolicy(policy$1({
80618
80937
  }
80619
80938
  /** Moves the leases of a merged party to the record it merged into. */
80620
80939
  function partyMerges(ctx) {
80621
- return subjectMergeHandler(ctx, registeredSubjects(ctx.subjects, ctx.naming).map((subject) => [subject.type, {
80940
+ return subjectMergeHandler(ctx, registeredSubjects$1(ctx.subjects, ctx.naming).map((subject) => [subject.type, {
80622
80941
  table: `${subject.schema}.${subject.table}`,
80623
80942
  extra: {}
80624
80943
  }]), moveSubjectRows({
@@ -80905,7 +81224,7 @@ declare
80905
81224
  v_rows jsonb;
80906
81225
  begin
80907
81226
  if not (${SERVICE_CALLER$1} or ${ctx.can("tenant", "leave_balances.tenant", read)}
80908
- or (v_user = auth.uid() and ${ctx.can("tenant", "leave_balances.tenant", request)})) then
81227
+ or (coalesce(v_user = auth.uid(), false) and ${ctx.can("tenant", "leave_balances.tenant", request)})) then
80909
81228
  ${forbidden("not allowed to read this member's leave balance")}
80910
81229
  end if;
80911
81230
  if v_user is null then
@@ -80950,7 +81269,7 @@ declare
80950
81269
  v_rows jsonb;
80951
81270
  begin
80952
81271
  if not (${SERVICE_CALLER$1} or ${ctx.can("tenant", "leave_ledger_entries.tenant", read)}
80953
- or (v_user = auth.uid() and ${ctx.can("tenant", "leave_ledger_entries.tenant", request)})) then
81272
+ or (coalesce(v_user = auth.uid(), false) and ${ctx.can("tenant", "leave_ledger_entries.tenant", request)})) then
80954
81273
  ${forbidden("not allowed to read this member's leave balance")}
80955
81274
  end if;
80956
81275
  select coalesce(jsonb_agg(${entryJson} order by y.${le("createdAt")} desc, y.${le("id")} desc), '[]'::jsonb) into v_rows
@@ -81651,7 +81970,7 @@ begin
81651
81970
  ${fail$1("LEAVE_REQUEST_NOT_FOUND", "leave request not found", "P0002")}
81652
81971
  end if;
81653
81972
  v_manager := ${SERVICE_CALLER$1} or ${ctx.can("tenant", `v_row.${q("tenant")}`, manage)};
81654
- if not (v_manager or v_row.${q("user")} = auth.uid()) then
81973
+ if not (v_manager or coalesce(v_row.${q("user")} = auth.uid(), false)) then
81655
81974
  ${forbidden("not allowed to cancel this leave request")}
81656
81975
  end if;
81657
81976
  if v_row.${q("cancelledAt")} is not null then
@@ -81693,7 +82012,7 @@ begin
81693
82012
  if not (v_reader or ${ctx.can("tenant", "list_leave_requests.tenant", request)}) then
81694
82013
  ${forbidden("not allowed to list leave requests")}
81695
82014
  end if;
81696
- if not v_reader and (coalesce(list_leave_requests.everyone, false) or (list_leave_requests.user_id is not null and list_leave_requests.user_id <> auth.uid())) then
82015
+ if not v_reader and (coalesce(list_leave_requests.everyone, false) or (list_leave_requests.user_id is not null and list_leave_requests.user_id is distinct from auth.uid())) then
81697
82016
  ${forbidden("not allowed to read another member's leave")}
81698
82017
  end if;
81699
82018
  select coalesce(jsonb_agg(z.item order by z.starts, z.created), '[]'::jsonb) into v_rows
@@ -83776,7 +84095,7 @@ declare
83776
84095
  v_row ${memories}%rowtype;
83777
84096
  begin
83778
84097
  select * into v_row from ${memories} x where x.${m.id} = memory_forget.memory_id;
83779
- if not found or not (${SERVICE_CALLER$1} or v_row.${m.owner} = auth.uid() or (v_row.${m.scope} = 'organization' and ${ctx.scope.can(`v_row.${m.tenant}`, manage)})) then
84098
+ if not found or not (${SERVICE_CALLER$1} or coalesce(v_row.${m.owner} = auth.uid(), false) or (v_row.${m.scope} = 'organization' and ${ctx.scope.can(`v_row.${m.tenant}`, manage)})) then
83780
84099
  return false;
83781
84100
  end if;
83782
84101
  if memory_forget.superseded_by is null then
@@ -84313,8 +84632,8 @@ begin
84313
84632
  end if;
84314
84633
  if not (${q.service}
84315
84634
  or ${fn("can_conversation")}(v_conv.${cv("id")}, 'moderate')
84316
- or (${fn("can_conversation")}(v_conv.${cv("id")}, 'send') and (v_conv.${cv("access")} = 'members' or add_conversation_members.users <@ array[auth.uid()]))
84317
- or (v_conv.${cv("access")} = 'tenant' and v_conv.${cv("archivedAt")} is null and add_conversation_members.users <@ array[auth.uid()])) then
84635
+ or (${fn("can_conversation")}(v_conv.${cv("id")}, 'send') and (v_conv.${cv("access")} = 'members' or coalesce(add_conversation_members.users <@ array[auth.uid()], false)))
84636
+ or (v_conv.${cv("access")} = 'tenant' and v_conv.${cv("archivedAt")} is null and coalesce(add_conversation_members.users <@ array[auth.uid()], false))) then
84318
84637
  ${fail$1("MESSAGING_FORBIDDEN", "not allowed to add members here")}
84319
84638
  end if;
84320
84639
  for v_user in select distinct x from unnest(add_conversation_members.users) x where x is not null loop
@@ -84353,7 +84672,7 @@ begin
84353
84672
  ${fail$1("MESSAGING_MEMBERS_FIXED", "this conversation's members can't change", "22023")}
84354
84673
  end if;
84355
84674
  if not (${q.service}
84356
- or remove_conversation_member.member = auth.uid()
84675
+ or coalesce(remove_conversation_member.member = auth.uid(), false)
84357
84676
  or ${fn("can_conversation")}(v_conv.${cv("id")}, 'moderate')
84358
84677
  or exists (select 1 from ${t("members")} k where k.${mb("conversation")} = v_conv.${cv("id")} and k.${mb("user")} = auth.uid() and k.${mb("role")} = 'owner')) then
84359
84678
  ${fail$1("MESSAGING_FORBIDDEN", "not allowed to remove this member")}
@@ -84385,7 +84704,7 @@ begin
84385
84704
  end if;
84386
84705
  if not (${q.service}
84387
84706
  or ${fn("can_conversation")}(v_conv.${cv("id")}, 'moderate')
84388
- or v_conv.${cv("createdBy")} = auth.uid()
84707
+ or coalesce(v_conv.${cv("createdBy")} = auth.uid(), false)
84389
84708
  or exists (select 1 from ${t("members")} k where k.${mb("conversation")} = v_conv.${cv("id")} and k.${mb("user")} = auth.uid() and k.${mb("role")} = 'owner')) then
84390
84709
  ${fail$1("MESSAGING_FORBIDDEN", "not allowed to archive this conversation")}
84391
84710
  end if;
@@ -84792,7 +85111,7 @@ function sentEffects(q) {
84792
85111
  'summary', left(v_msg.${ms("body")}, 140),
84793
85112
  'data', jsonb_build_object(${messageId}, v_msg.${ms("id")}, ${sqlString(q.e("conversationId"))}, v_msg.${ms("conversation")})${extra}
84794
85113
  )`, { indent: " " });
84795
- const keyed = registeredSubjects(ctx.subjects, ctx.naming).filter((subject) => subject.config.permissions?.["read"] !== void 0).map((subject) => subject.type);
85114
+ const keyed = registeredSubjects$1(ctx.subjects, ctx.naming).filter((subject) => subject.config.permissions?.["read"] !== void 0).map((subject) => subject.type);
84796
85115
  const readsRecord = (user) => keyed.length === 0 ? "" : `
84797
85116
  and (v_conv.${cv("access")} <> 'subject' or case v_conv.${cv("subjectType")} ${keyed.map((type) => `when ${sqlString(type)} then coalesce(${ctx.of("subjects").fn("can_subject_for")}(${user}, v_conv.${cv("subjectType")}, v_conv.${cv("subjectId")}, 'read'), false)`).join(" ")} else true end)`;
84798
85117
  const canRead = (user) => `${ctx.scope.canUser(user, `v_msg.${ms("tenant")}`, q.key("read"))}
@@ -85283,7 +85602,7 @@ begin
85283
85602
  if not found then
85284
85603
  return false;
85285
85604
  end if;
85286
- if not (${q.service} or v_msg.${ms("author")} = auth.uid() or ${fn("can_conversation")}(v_msg.${ms("conversation")}, 'moderate')) then
85605
+ if not (${q.service} or coalesce(v_msg.${ms("author")} = auth.uid(), false) or ${fn("can_conversation")}(v_msg.${ms("conversation")}, 'moderate')) then
85287
85606
  ${fail$1("MESSAGING_FORBIDDEN", "not allowed to delete this message")}
85288
85607
  end if;
85289
85608
  update ${t("messages")} m set ${ms("body")} = '', ${ms("document")} = null, ${ms("mentions")} = '{}', ${ms("mentionScope")} = null,
@@ -92114,7 +92433,7 @@ as $$
92114
92433
  declare
92115
92434
  v_from text;
92116
92435
  begin
92117
- select x.${o("status")} into v_from from ${ctx.table("orders")} x where x.${o("id")} = p_order for update;
92436
+ select ${ctx.label("orders", "status", `x.${o("status")}`)} into v_from from ${ctx.table("orders")} x where x.${o("id")} = p_order for update;
92118
92437
  if v_from = p_to then
92119
92438
  return v_from;
92120
92439
  end if;${governed ? "" : `
@@ -92165,7 +92484,7 @@ function orderFields(ctx, alias) {
92165
92484
  ["tax_inclusive", "taxInclusive"],
92166
92485
  ["invoice_number", "invoiceNumber"],
92167
92486
  ["placed_at", "placedAt"]
92168
- ].map(([as, column]) => `${alias}.${o(column ?? "")} as ${as}`).join(", ");
92487
+ ].map(([as, column]) => column === "status" ? `${ctx.label("orders", "status", `${alias}.${o(column)}`)} as ${as}` : `${alias}.${o(column ?? "")} as ${as}`).join(", ");
92169
92488
  }
92170
92489
  //#endregion
92171
92490
  //#region src/sql/modules/orders-after-sale.ts
@@ -92237,13 +92556,13 @@ function afterSaleFunctions(ctx, names) {
92237
92556
  tenant: "v_order.tenant",
92238
92557
  audit: false
92239
92558
  });
92240
- const loadFulfillment = (id) => `select x.${f("id")} as id, x.${f("order")} as order_id, x.${f("status")} as status into v_fulfillment
92559
+ const loadFulfillment = (id) => `select x.${f("id")} as id, x.${f("order")} as order_id, ${ctx.label("fulfillments", "status", `x.${f("status")}`)} as status into v_fulfillment
92241
92560
  from ${fulfillments} x where x.${f("id")} = ${id} for update;
92242
92561
  if not found then
92243
92562
  ${fail$1("ORDERS_FULFILLMENT_NOT_FOUND", "fulfillment not found", "P0002")}
92244
92563
  end if;
92245
92564
  ${load("v_fulfillment.order_id")}`;
92246
- const loadReturn = (id) => `select x.${r("id")} as id, x.${r("order")} as order_id, x.${r("status")} as status into v_return
92565
+ const loadReturn = (id) => `select x.${r("id")} as id, x.${r("order")} as order_id, ${ctx.label("returns", "status", `x.${r("status")}`)} as status into v_return
92247
92566
  from ${returns} x where x.${r("id")} = ${id} for update;
92248
92567
  if not found then
92249
92568
  ${fail$1("ORDERS_RETURN_NOT_FOUND", "return not found", "P0002")}
@@ -92323,7 +92642,7 @@ begin
92323
92642
  if v_fulfillment.status <> 'pending' then
92324
92643
  ${fail$1("ORDERS_TRANSITION_INVALID", "only a pending fulfillment can ship", "55000")}
92325
92644
  end if;${unsupported(trackingUrl, "ship_fulfillment.tracking_url", "ORDERS_TRACKING_URL_UNSUPPORTED", "this fulfillment table has no tracking URL column")}
92326
- update ${fulfillments} x set ${f("status")} = 'shipped', ${f("shippedAt")} = now(),
92645
+ update ${fulfillments} x set ${f("status")} = ${ctx.value("fulfillments", "status", "shipped")}, ${f("shippedAt")} = now(),
92327
92646
  ${f("carrier")} = coalesce(ship_fulfillment.carrier, x.${f("carrier")}),
92328
92647
  ${f("trackingNumber")} = coalesce(ship_fulfillment.tracking_number, x.${f("trackingNumber")})${trackingUrl ? `,
92329
92648
  ${f("trackingUrl")} = coalesce(ship_fulfillment.tracking_url, x.${f("trackingUrl")})` : ""}
@@ -92331,7 +92650,7 @@ begin
92331
92650
  ${partEvent("fulfillment.shipped", "v_fulfillment.id", [["carrier", `(select x.${f("carrier")} from ${fulfillments} x where x.${f("id")} = v_fulfillment.id)`], ["trackingNumber", `(select x.${f("trackingNumber")} from ${fulfillments} x where x.${f("id")} = v_fulfillment.id)`]])}
92332
92651
  if v_order.status = 'paid'
92333
92652
  and not exists (select 1 from ${lines} l where l.${ol("order")} = v_order.id and l.${ol("fulfilled")} < l.${ol("quantity")})
92334
- and not exists (select 1 from ${fulfillments} x where x.${f("order")} = v_order.id and x.${f("status")} = 'pending') then
92653
+ and not exists (select 1 from ${fulfillments} x where x.${f("order")} = v_order.id and ${ctx.is("fulfillments", "status", `x.${f("status")}`, ["pending"])}) then
92335
92654
  perform ${fn("order_transition")}(v_order.id, 'fulfilled');
92336
92655
  ${event("order.fulfilled", [])}
92337
92656
  end if;
@@ -92360,10 +92679,10 @@ begin
92360
92679
  if v_fulfillment.status <> 'shipped' then
92361
92680
  ${fail$1("ORDERS_TRANSITION_INVALID", "only a shipped fulfillment can be delivered", "55000")}
92362
92681
  end if;
92363
- update ${fulfillments} x set ${f("status")} = 'delivered', ${f("deliveredAt")} = now() where x.${f("id")} = v_fulfillment.id;
92682
+ update ${fulfillments} x set ${f("status")} = ${ctx.value("fulfillments", "status", "delivered")}, ${f("deliveredAt")} = now() where x.${f("id")} = v_fulfillment.id;
92364
92683
  ${partEvent("fulfillment.delivered", "v_fulfillment.id", [])}
92365
92684
  if v_order.status = 'fulfilled'
92366
- and not exists (select 1 from ${fulfillments} x where x.${f("order")} = v_order.id and x.${f("status")} in ('pending', 'shipped')) then
92685
+ and not exists (select 1 from ${fulfillments} x where x.${f("order")} = v_order.id and ${ctx.is("fulfillments", "status", `x.${f("status")}`, ["pending", "shipped"])}) then
92367
92686
  perform ${fn("order_transition")}(v_order.id, 'completed');
92368
92687
  ${event("order.completed", [])}
92369
92688
  end if;
@@ -92394,7 +92713,7 @@ begin
92394
92713
  update ${lines} x set ${ol("fulfilled")} = x.${ol("fulfilled")} - y.${fl("quantity")}
92395
92714
  from ${fulfillmentLines} y
92396
92715
  where y.${fl("fulfillment")} = v_fulfillment.id and x.${ol("id")} = y.${fl("line")};
92397
- update ${fulfillments} x set ${f("status")} = 'cancelled' where x.${f("id")} = v_fulfillment.id;
92716
+ update ${fulfillments} x set ${f("status")} = ${ctx.value("fulfillments", "status", "cancelled")} where x.${f("id")} = v_fulfillment.id;
92398
92717
  return true;
92399
92718
  end;
92400
92719
  $$;
@@ -92416,7 +92735,7 @@ declare
92416
92735
  v_units integer := 0;
92417
92736
  begin
92418
92737
  ${load("request_return.order_id")}
92419
- if not (auth.role() = 'service_role' or v_order.customer = auth.uid() or ${ctx.scope.can("v_order.tenant", names.manage)}) then
92738
+ if not (auth.role() = 'service_role' or coalesce(v_order.customer = auth.uid(), false) or ${ctx.scope.can("v_order.tenant", names.manage)}) then
92420
92739
  ${fail$1("ORDERS_FORBIDDEN", "not allowed to return this order")}
92421
92740
  end if;
92422
92741
  if v_order.status not in ('paid', 'fulfilled', 'completed') then
@@ -92436,7 +92755,7 @@ begin
92436
92755
  end if;
92437
92756
  select coalesce(sum(y.${rl("quantity")}), 0) into v_open
92438
92757
  from ${returnLines} y join ${returns} z on z.${r("id")} = y.${rl("return")}
92439
- where y.${rl("line")} = v_item.line and z.${r("status")} = 'requested';
92758
+ where y.${rl("line")} = v_item.line and ${ctx.is("returns", "status", `z.${r("status")}`, ["requested"])};
92440
92759
  if not exists (select 1 from ${lines} l where l.${ol("id")} = v_item.line and l.${ol("order")} = v_order.id
92441
92760
  and l.${ol("fulfilled")} - l.${ol("returned")} - v_open >= v_item.quantity) then
92442
92761
  ${fail$1("ORDERS_RETURN_INVALID", "a line isn't on this order or has fewer fulfilled units left to return", "22023")}
@@ -92482,7 +92801,7 @@ begin
92482
92801
  update ${lines} x set ${ol("returned")} = x.${ol("returned")} + v_line.quantity where x.${ol("id")} = v_line.line;${restock(ctx)}
92483
92802
  v_units := v_units + v_line.quantity;
92484
92803
  end loop;
92485
- update ${returns} x set ${r("status")} = 'received', ${r("receivedAt")} = now() where x.${r("id")} = v_return.id;
92804
+ update ${returns} x set ${r("status")} = ${ctx.value("returns", "status", "received")}, ${r("receivedAt")} = now() where x.${r("id")} = v_return.id;
92486
92805
  ${partEvent("return.received", "v_return.id", [["quantity", "v_units::text"]])}
92487
92806
  return true;
92488
92807
  end;
@@ -92504,7 +92823,7 @@ begin
92504
92823
  if v_return.status <> 'requested' then
92505
92824
  ${fail$1("ORDERS_TRANSITION_INVALID", "only a requested return can be rejected", "55000")}
92506
92825
  end if;
92507
- update ${returns} x set ${r("status")} = 'rejected' where x.${r("id")} = v_return.id;
92826
+ update ${returns} x set ${r("status")} = ${ctx.value("returns", "status", "rejected")} where x.${r("id")} = v_return.id;
92508
92827
  return true;
92509
92828
  end;
92510
92829
  $$;
@@ -92535,7 +92854,7 @@ begin
92535
92854
  ${fail$1("ORDERS_RETURN_NOT_FOUND", "return not found on this order", "P0002")}
92536
92855
  end if;
92537
92856
  select coalesce(sum(x.${rf("amount")}), 0) into v_pending from ${refunds} x
92538
- where x.${rf("order")} = v_order.id and x.${rf("status")} = 'pending';
92857
+ where x.${rf("order")} = v_order.id and ${ctx.is("refunds", "status", `x.${rf("status")}`, ["pending"])};
92539
92858
  v_left := v_order.paid_total - v_order.refunded_total - v_pending;
92540
92859
  v_amount := coalesce(create_refund.amount, v_left);
92541
92860
  if v_amount <= 0 or v_amount > v_left then
@@ -92543,9 +92862,9 @@ begin
92543
92862
  end if;
92544
92863
  select y.${p("id")} as id, y.${p("provider")} as provider, y.${p("reference")} as reference into v_payment
92545
92864
  from ${payments} y
92546
- where y.${p("order")} = v_order.id and y.${p("status")} = 'succeeded'
92865
+ where y.${p("order")} = v_order.id and ${ctx.is("payments", "status", `y.${p("status")}`, ["succeeded"])}
92547
92866
  and y.${p("captured")} - y.${p("refunded")} - coalesce((select sum(z.${rf("amount")}) from ${refunds} z
92548
- where z.${rf("payment")} = y.${p("id")} and z.${rf("status")} = 'pending'), 0) >= v_amount
92867
+ where z.${rf("payment")} = y.${p("id")} and ${ctx.is("refunds", "status", `z.${rf("status")}`, ["pending"])}), 0) >= v_amount
92549
92868
  order by y.${p("createdAt")} desc
92550
92869
  limit 1;
92551
92870
  if not found then
@@ -92582,7 +92901,7 @@ begin
92582
92901
  ${fail$1("ORDERS_REFUND_STATUS_INVALID", "status is pending, succeeded or failed", "22023")}
92583
92902
  end if;
92584
92903
  select x.${rf("id")} as id, x.${rf("order")} as order_id, x.${rf("payment")} as payment, x.${rf("amount")} as amount,
92585
- x.${rf("status")} as status
92904
+ ${ctx.label("refunds", "status", `x.${rf("status")}`)} as status
92586
92905
  into v_refund from ${refunds} x
92587
92906
  where (complete_refund.refund is not null and x.${rf("id")} = complete_refund.refund)
92588
92907
  or (complete_refund.refund is null and x.${rf("providerReference")} = complete_refund.provider_reference)
@@ -92611,12 +92930,12 @@ begin
92611
92930
  ["currency", "v_order.currency"],
92612
92931
  ["amount", "v_refund.amount::text"],
92613
92932
  ["refundedTotal", "v_total::text"],
92614
- ["status", `(select x.${o("status")} from ${orders} x where x.${o("id")} = v_order.id)`]
92933
+ ["status", `(select ${ctx.label("orders", "status", `x.${o("status")}`)} from ${orders} x where x.${o("id")} = v_order.id)`]
92615
92934
  ], "'order.refunded:' || v_refund.id::text")}
92616
92935
  end if;
92617
92936
  end if;
92618
- return (select jsonb_build_object('id', x.${rf("id")}, 'orderId', x.${rf("order")}, 'status', x.${rf("status")},
92619
- 'amount', x.${rf("amount")}::text, 'orderStatus', y.${o("status")}, 'refundedTotal', y.${o("refundedTotal")}::text)
92937
+ return (select jsonb_build_object('id', x.${rf("id")}, 'orderId', x.${rf("order")}, 'status', ${ctx.label("refunds", "status", `x.${rf("status")}`)},
92938
+ 'amount', x.${rf("amount")}::text, 'orderStatus', ${ctx.label("orders", "status", `y.${o("status")}`)}, 'refundedTotal', y.${o("refundedTotal")}::text)
92620
92939
  from ${refunds} x join ${orders} y on y.${o("id")} = x.${rf("order")} where x.${rf("id")} = v_refund.id);
92621
92940
  end;
92622
92941
  $$;
@@ -92643,10 +92962,10 @@ function addressCheck(address) {
92643
92962
  function ownCart(ctx, id, options = {}) {
92644
92963
  const c = columns(ctx, "carts");
92645
92964
  const readers = options.readers === void 0 ? "" : ` or ${ctx.scope.can("v_cart.tenant", options.readers)}`;
92646
- return `select x.${c("tenant")} as tenant, x.${c("user")} as owner, x.${c("status")} as status,
92965
+ return `select x.${c("tenant")} as tenant, x.${c("user")} as owner, ${ctx.label("carts", "status", `x.${c("status")}`)} as status,
92647
92966
  x.${c("currency")} as currency, x.${c("priceList")} as price_list, x.${c("shippingAddress")} as shipping_address
92648
92967
  into v_cart from ${ctx.table("carts")} x where x.${c("id")} = ${id}${options.lock ? " for update" : ""};
92649
- if not found or not (auth.role() = 'service_role' or v_cart.owner = auth.uid()${readers}) then
92968
+ if not found or not (auth.role() = 'service_role' or coalesce(v_cart.owner = auth.uid(), false)${readers}) then
92650
92969
  ${fail$1("ORDERS_CART_NOT_FOUND", "cart not found", "P0002")}
92651
92970
  end if;`;
92652
92971
  }
@@ -92662,7 +92981,7 @@ function sellable(ctx, variant) {
92662
92981
  const p = columns(catalog, "products");
92663
92982
  return `if not exists (
92664
92983
  select 1 from ${catalog.table("variants")} cv join ${catalog.table("products")} cp on cp.${p("id")} = cv.${v("product")}
92665
- where cv.${v("id")} = ${variant} and cv.${v("tenant")} = v_cart.tenant and cp.${p("status")} = 'active'
92984
+ where cv.${v("id")} = ${variant} and cv.${v("tenant")} = v_cart.tenant and ${catalog.is("products", "status", `cp.${p("status")}`, ["active"])}
92666
92985
  ) then
92667
92986
  ${fail$1("ORDERS_VARIANT_UNAVAILABLE", "this variant is not for sale", "P0002")}
92668
92987
  end if;`;
@@ -92805,11 +93124,11 @@ declare
92805
93124
  begin
92806
93125
  select x.${c("tenant")} as tenant, x.${c("currency")} as currency, x.${c("priceList")} as price_list,
92807
93126
  x.${c("shippingAddress")} as shipping_address, x.${c("shippingRate")} as shipping_rate,
92808
- x.${c("user")} as owner, x.${c("status")} as status, ${or("carts", "x", "email", "text")} as email, ${or("carts", "x", "billingAddress", "jsonb")} as billing_address
93127
+ x.${c("user")} as owner, ${ctx.label("carts", "status", `x.${c("status")}`)} as status, ${or("carts", "x", "email", "text")} as email, ${or("carts", "x", "billingAddress", "jsonb")} as billing_address
92809
93128
  into v_cart from ${ctx.table("carts")} x where x.${c("id")} = p_cart;
92810
93129
  for v_line in
92811
93130
  select l.${cl("id")} as id, l.${cl("variant")} as variant, l.${cl("quantity")} as quantity, l.${cl("unitAmount")} as unit_amount,
92812
- cv.${v("sku")} as sku, ${title} as title, cp.${p("id")} as product, cp.${p("status")} as status,
93131
+ cv.${v("sku")} as sku, ${title} as title, cp.${p("id")} as product, ${catalog.label("products", "status", `cp.${p("status")}`)} as status,
92813
93132
  ${kind} as kind, ${weight} as weight
92814
93133
  from ${ctx.table("cartLines")} l
92815
93134
  join ${catalog.table("variants")} cv on cv.${v("id")} = l.${cl("variant")}
@@ -92844,7 +93163,7 @@ begin
92844
93163
  from jsonb_array_elements(v_lines) with ordinality as e(l, n);
92845
93164
  v_country := v_cart.shipping_address ->> 'country';
92846
93165
  if v_ships and v_cart.shipping_rate is not null then
92847
- select x.${s("id")} as id, x.${s("name")} as name, x.${s("countries")} as countries, x.${s("kind")} as kind,
93166
+ select x.${s("id")} as id, x.${s("name")} as name, x.${s("countries")} as countries, ${ctx.label("shippingRates", "kind", `x.${s("kind")}`)} as kind,
92848
93167
  x.${s("amount")} as amount, x.${s("perKg")} as per_kg, ${or("shippingRates", "x", "freeOver", "bigint")} as free_over
92849
93168
  into v_rate from ${ctx.table("shippingRates")} x
92850
93169
  where x.${s("id")} = v_cart.shipping_rate and x.${s("active")} and x.${s("currency")} = v_cart.currency;
@@ -92923,7 +93242,7 @@ begin
92923
93242
  end if;`}
92924
93243
  insert into ${carts} as x (${c("tenant")}, ${c("user")}, ${c("currency")}, ${c("priceList")}${email ? `, ${c("email")}` : ""})
92925
93244
  values (create_cart.tenant, auth.uid(), create_cart.currency, create_cart.price_list${email ? ", create_cart.email" : ""})
92926
- on conflict (${c("tenant")}, ${c("user")}, ${c("currency")}) where ${c("status")} = 'open' do update
93245
+ on conflict (${c("tenant")}, ${c("user")}, ${c("currency")}) where ${ctx.is("carts", "status", c("status"), ["open"])} do update
92927
93246
  set ${c("priceList")} = coalesce(excluded.${c("priceList")}, x.${c("priceList")}),${email ? `
92928
93247
  ${c("email")} = coalesce(excluded.${c("email")}, x.${c("email")}),` : ""} ${c("updatedAt")} = now()
92929
93248
  returning x.${c("id")} into v_id;
@@ -93077,10 +93396,10 @@ begin
93077
93396
  v_weight := (v_totals ->> 'weightGrams')::bigint;
93078
93397
  return coalesce((
93079
93398
  select jsonb_agg(jsonb_build_object(
93080
- 'id', x.${s("id")}, 'name', x.${s("name")}, 'kind', x.${s("kind")}, 'currency', x.${s("currency")},
93399
+ 'id', x.${s("id")}, 'name', x.${s("name")}, 'kind', ${ctx.label("shippingRates", "kind", `x.${s("kind")}`)}, 'currency', x.${s("currency")},
93081
93400
  'amount', (case
93082
93401
  ${ctx.has("shippingRates", "freeOver") ? ` when x.${s("freeOver")} is not null and v_after_discount >= x.${s("freeOver")} then 0
93083
- ` : ""} else x.${s("amount")} + case when x.${s("kind")} = 'weight' then (x.${s("perKg")} * v_weight + 999) / 1000 else 0 end
93402
+ ` : ""} else x.${s("amount")} + case when ${ctx.is("shippingRates", "kind", `x.${s("kind")}`, ["weight"])} then (x.${s("perKg")} * v_weight + 999) / 1000 else 0 end
93084
93403
  end)::text) order by x.${s("amount")}, x.${s("name")})
93085
93404
  from ${ctx.table("shippingRates")} x
93086
93405
  where x.${s("tenant")} = v_cart.tenant and x.${s("active")} and x.${s("currency")} = v_cart.currency
@@ -93129,12 +93448,12 @@ begin
93129
93448
  end if;
93130
93449
  for v_from in
93131
93450
  select x.${c("id")} as id, x.${c("tenant")} as tenant, x.${c("currency")} as currency
93132
- from ${carts} x where x.${c("user")} = merge_carts.from_user and x.${c("status")} = 'open'
93451
+ from ${carts} x where x.${c("user")} = merge_carts.from_user and ${ctx.is("carts", "status", `x.${c("status")}`, ["open"])}
93133
93452
  for update
93134
93453
  loop
93135
93454
  select x.${c("id")} into v_to from ${carts} x
93136
93455
  where x.${c("user")} = merge_carts.to_user and x.${c("tenant")} = v_from.tenant
93137
- and x.${c("currency")} = v_from.currency and x.${c("status")} = 'open'
93456
+ and x.${c("currency")} = v_from.currency and ${ctx.is("carts", "status", `x.${c("status")}`, ["open"])}
93138
93457
  for update;
93139
93458
  if v_to is null then
93140
93459
  update ${carts} x set ${c("user")} = merge_carts.to_user, ${c("updatedAt")} = now() where x.${c("id")} = v_from.id;
@@ -93144,7 +93463,7 @@ begin
93144
93463
  from ${lines} l where l.${cl("cart")} = v_from.id
93145
93464
  on conflict (${cl("cart")}, ${cl("variant")}) do update
93146
93465
  set ${cl("quantity")} = least(x.${cl("quantity")} + excluded.${cl("quantity")}, ${MAX_QUANTITY}), ${cl("updatedAt")} = now();${moveCodes}
93147
- update ${carts} x set ${c("status")} = 'abandoned', ${c("updatedAt")} = now() where x.${c("id")} = v_from.id;
93466
+ update ${carts} x set ${c("status")} = ${ctx.value("carts", "status", "abandoned")}, ${c("updatedAt")} = now() where x.${c("id")} = v_from.id;
93148
93467
  end if;
93149
93468
  v_to := null;
93150
93469
  v_count := v_count + 1;
@@ -93194,7 +93513,11 @@ function orderInvoice(ctx) {
93194
93513
  }
93195
93514
  const PAYMENT_STATUSES = "('requires_action', 'processing', 'authorized', 'succeeded', 'failed', 'canceled')";
93196
93515
  /** Payment statuses a late webhook can't move a payment back from. */
93197
- const SETTLED = "('succeeded', 'failed', 'canceled')";
93516
+ const SETTLED = [
93517
+ "succeeded",
93518
+ "failed",
93519
+ "canceled"
93520
+ ];
93198
93521
  /**
93199
93522
  * `order_json(order)`: the order with its lines, payments, fulfillments,
93200
93523
  * returns and refunds.
@@ -93222,7 +93545,7 @@ set search_path = ''
93222
93545
  as $$
93223
93546
  select jsonb_build_object(
93224
93547
  'id', x.${o("id")}, 'organizationId', x.${o("tenant")}, 'number', x.${o("number")}, 'cartId', x.${o("cart")},
93225
- 'customerId', x.${o("customer")}, 'email', ${or("orders", "x", "email")}, 'status', x.${o("status")}, 'currency', x.${o("currency")},
93548
+ 'customerId', x.${o("customer")}, 'email', ${or("orders", "x", "email")}, 'status', ${ctx.label("orders", "status", `x.${o("status")}`)}, 'currency', x.${o("currency")},
93226
93549
  'subtotal', ${text("x", o("subtotal"))}, 'discountTotal', ${text("x", o("discountTotal"))},
93227
93550
  'shippingTotal', ${text("x", o("shippingTotal"))}, 'taxTotal', ${text("x", o("taxTotal"))}, 'total', ${text("x", o("total"))},
93228
93551
  'paidTotal', ${text("x", o("paidTotal"))}, 'refundedTotal', ${text("x", o("refundedTotal"))}, 'taxInclusive', x.${o("taxInclusive")},
@@ -93240,26 +93563,26 @@ as $$
93240
93563
  'backordered', l.${ol("backordered")}) order by l.${ol("position")})
93241
93564
  from ${ctx.table("orderLines")} l where l.${ol("order")} = x.${o("id")}), '[]'::jsonb),
93242
93565
  'payments', coalesce((select jsonb_agg(jsonb_build_object(
93243
- 'id', y.${p("id")}, 'provider', y.${p("provider")}, 'reference', y.${p("reference")}, 'status', y.${p("status")},
93566
+ 'id', y.${p("id")}, 'provider', y.${p("provider")}, 'reference', y.${p("reference")}, 'status', ${ctx.label("payments", "status", `y.${p("status")}`)},
93244
93567
  'amount', ${text("y", p("amount"))}, 'captured', ${text("y", p("captured"))}, 'refunded', ${text("y", p("refunded"))},
93245
93568
  'createdAt', y.${p("createdAt")}) order by y.${p("createdAt")})
93246
93569
  from ${ctx.table("payments")} y where y.${p("order")} = x.${o("id")}), '[]'::jsonb),
93247
93570
  'fulfillments', coalesce((select jsonb_agg(jsonb_build_object(
93248
- 'id', y.${f("id")}, 'status', y.${f("status")}, 'locationId', y.${f("location")}, 'carrier', y.${f("carrier")},
93571
+ 'id', y.${f("id")}, 'status', ${ctx.label("fulfillments", "status", `y.${f("status")}`)}, 'locationId', y.${f("location")}, 'carrier', y.${f("carrier")},
93249
93572
  'trackingNumber', y.${f("trackingNumber")}, 'trackingUrl', ${or("fulfillments", "y", "trackingUrl")}, 'createdAt', y.${f("createdAt")},
93250
93573
  'shippedAt', y.${f("shippedAt")}, 'deliveredAt', y.${f("deliveredAt")},
93251
93574
  'lines', coalesce((select jsonb_agg(jsonb_build_object('lineId', z.${fl("line")}, 'quantity', z.${fl("quantity")}))
93252
93575
  from ${ctx.table("fulfillmentLines")} z where z.${fl("fulfillment")} = y.${f("id")}), '[]'::jsonb)) order by y.${f("createdAt")})
93253
93576
  from ${ctx.table("fulfillments")} y where y.${f("order")} = x.${o("id")}), '[]'::jsonb),
93254
93577
  'returns', coalesce((select jsonb_agg(jsonb_build_object(
93255
- 'id', y.${r("id")}, 'status', y.${r("status")}, 'reason', ${or("returns", "y", "reason")}, 'createdAt', y.${r("createdAt")},
93578
+ 'id', y.${r("id")}, 'status', ${ctx.label("returns", "status", `y.${r("status")}`)}, 'reason', ${or("returns", "y", "reason")}, 'createdAt', y.${r("createdAt")},
93256
93579
  'receivedAt', y.${r("receivedAt")},
93257
93580
  'lines', coalesce((select jsonb_agg(jsonb_build_object('lineId', z.${rl("line")}, 'quantity', z.${rl("quantity")}))
93258
93581
  from ${ctx.table("returnLines")} z where z.${rl("return")} = y.${r("id")}), '[]'::jsonb)) order by y.${r("createdAt")})
93259
93582
  from ${ctx.table("returns")} y where y.${r("order")} = x.${o("id")}), '[]'::jsonb),
93260
93583
  'refunds', coalesce((select jsonb_agg(jsonb_build_object(
93261
93584
  'id', y.${rf("id")}, 'paymentId', y.${rf("payment")}, 'returnId', y.${rf("return")}, 'amount', ${text("y", rf("amount"))},
93262
- 'status', y.${rf("status")}, 'reason', ${or("refunds", "y", "reason")}, 'providerReference', y.${rf("providerReference")},
93585
+ 'status', ${ctx.label("refunds", "status", `y.${rf("status")}`)}, 'reason', ${or("refunds", "y", "reason")}, 'providerReference', y.${rf("providerReference")},
93263
93586
  'createdAt', y.${rf("createdAt")}, 'completedAt', y.${rf("completedAt")}) order by y.${rf("createdAt")})
93264
93587
  from ${ctx.table("refunds")} y where y.${rf("order")} = x.${o("id")}), '[]'::jsonb)${extraFieldsJson("x", names.extras)})
93265
93588
  from ${ctx.table("orders")} x where x.${o("id")} = p_order
@@ -93357,6 +93680,7 @@ function releaseLines(ctx) {
93357
93680
  function checkoutFunctions(ctx, names) {
93358
93681
  const { fn } = names;
93359
93682
  const minutes = paymentWindow(ctx);
93683
+ const settled = (value, negate = false) => ctx.is("payments", "status", value, SETTLED, negate);
93360
93684
  const carts = ctx.table("carts");
93361
93685
  const orders = ctx.table("orders");
93362
93686
  const payments = ctx.table("payments");
@@ -93416,7 +93740,7 @@ declare
93416
93740
  v_claims text;
93417
93741
  begin
93418
93742
  ${serviceOnlyGuard()}
93419
- select x.${c("tenant")} as tenant, x.${c("user")} as owner, x.${c("status")} as status, x.${c("currency")} as currency,
93743
+ select x.${c("tenant")} as tenant, x.${c("user")} as owner, ${ctx.label("carts", "status", `x.${c("status")}`)} as status, x.${c("currency")} as currency,
93420
93744
  ${cartOr("email", "text")} as email, x.${c("shippingAddress")} as shipping_address, ${cartOr("billingAddress", "jsonb")} as billing_address
93421
93745
  into v_cart from ${carts} x where x.${c("id")} = place_order.cart for update;
93422
93746
  if not found then
@@ -93479,7 +93803,7 @@ begin
93479
93803
  from jsonb_array_elements(v_priced -> 'lines') with ordinality as e(l, n);
93480
93804
  ${load("v_id", false)}${reserveLines(ctx, minutes)}${promotions === void 0 ? "" : `
93481
93805
  perform ${promotions.fn("redeem_promotions")}(v_order.id, v_priced -> 'promotions');`}
93482
- update ${carts} x set ${c("status")} = 'converted', ${c("convertedAt")} = now(), ${c("updatedAt")} = now()
93806
+ update ${carts} x set ${c("status")} = ${ctx.value("carts", "status", "converted")}, ${c("convertedAt")} = now(), ${c("updatedAt")} = now()
93483
93807
  where x.${c("id")} = place_order.cart;
93484
93808
  ${ctx.record({
93485
93809
  type: "order.placed",
@@ -93551,7 +93875,7 @@ begin
93551
93875
  values (v_order.tenant, v_order.id, record_payment.provider, record_payment.reference, ${ctx.cast("payments", "status", "record_payment.status")}, record_payment.currency,
93552
93876
  record_payment.amount, coalesce(record_payment.captured, 0), coalesce(record_payment.refunded, 0))
93553
93877
  on conflict (${p("provider")}, ${p("reference")}) do update set
93554
- ${p("status")} = case when x.${p("status")} in ${SETTLED} and excluded.${p("status")} not in ${SETTLED} then x.${p("status")} else excluded.${p("status")} end,
93878
+ ${p("status")} = case when ${settled(`x.${p("status")}`)} and ${settled(`excluded.${p("status")}`, true)} then x.${p("status")} else excluded.${p("status")} end,
93555
93879
  ${p("amount")} = excluded.${p("amount")},
93556
93880
  ${p("captured")} = greatest(x.${p("captured")}, excluded.${p("captured")}),
93557
93881
  ${p("refunded")} = greatest(x.${p("refunded")}, excluded.${p("refunded")}),
@@ -93561,7 +93885,7 @@ begin
93561
93885
  ${fail$1("ORDERS_PAYMENT_CONFLICT", "this payment reference belongs to another order", "23505")}
93562
93886
  end if;
93563
93887
  select coalesce(sum(x.${p("captured")}), 0) into v_paid from ${payments} x
93564
- where x.${p("order")} = v_order.id and x.${p("status")} = 'succeeded';
93888
+ where x.${p("order")} = v_order.id and ${ctx.is("payments", "status", `x.${p("status")}`, ["succeeded"])};
93565
93889
  update ${orders} x set ${o("paidTotal")} = v_paid, ${o("updatedAt")} = now() where x.${o("id")} = v_order.id;
93566
93890
  if v_order.status = 'pending_payment' and v_paid >= v_order.total then
93567
93891
  perform ${fn("order_transition")}(v_order.id, 'paid');${commitLines(ctx)}
@@ -93588,7 +93912,7 @@ begin
93588
93912
  })}
93589
93913
  v_newly := true;
93590
93914
  end if;
93591
- return jsonb_build_object('orderId', v_order.id, 'status', (select x.${o("status")} from ${orders} x where x.${o("id")} = v_order.id),
93915
+ return jsonb_build_object('orderId', v_order.id, 'status', (select ${ctx.label("orders", "status", `x.${o("status")}`)} from ${orders} x where x.${o("id")} = v_order.id),
93592
93916
  'paidTotal', v_paid::text, 'newlyPaid', v_newly,
93593
93917
  'invoiceNumber', coalesce(v_number, v_order.invoice_number)${invoice ? `, 'invoiceId', v_invoice ->> ${sqlString(invoice.id)}` : ""});
93594
93918
  end;
@@ -93646,10 +93970,10 @@ declare
93646
93970
  v_order record;
93647
93971
  begin
93648
93972
  ${load("cancel_order.order_id", true)}
93649
- if not found or not (auth.role() = 'service_role' or v_order.customer = auth.uid() or ${ctx.scope.can("v_order.tenant", names.read)}) then
93973
+ if not found or not (auth.role() = 'service_role' or coalesce(v_order.customer = auth.uid(), false) or ${ctx.scope.can("v_order.tenant", names.read)}) then
93650
93974
  ${fail$1("ORDERS_ORDER_NOT_FOUND", "order not found", "P0002")}
93651
93975
  end if;
93652
- if not (auth.role() = 'service_role' or v_order.customer = auth.uid() or ${ctx.scope.can("v_order.tenant", names.manage)}) then
93976
+ if not (auth.role() = 'service_role' or coalesce(v_order.customer = auth.uid(), false) or ${ctx.scope.can("v_order.tenant", names.manage)}) then
93653
93977
  ${fail$1("ORDERS_FORBIDDEN", "not allowed to cancel this order")}
93654
93978
  end if;
93655
93979
  if v_order.status = 'cancelled' then
@@ -93679,7 +94003,7 @@ begin
93679
94003
  ${serviceOnlyGuard()}
93680
94004
  for v_id in
93681
94005
  select x.${o("id")} from ${orders} x
93682
- where x.${o("status")} = 'pending_payment' and x.${o("placedAt")} < now() - interval '${String(minutes)} minutes'
94006
+ where ${ctx.is("orders", "status", `x.${o("status")}`, ["pending_payment"])} and x.${o("placedAt")} < now() - interval '${String(minutes)} minutes'
93683
94007
  order by x.${o("placedAt")}
93684
94008
  limit greatest(coalesce(expire_orders.max_rows, 100), 1)
93685
94009
  for update skip locked
@@ -93705,7 +94029,7 @@ declare
93705
94029
  v_order record;
93706
94030
  begin
93707
94031
  ${load("get_order.order_id", false)}
93708
- if not found or not (auth.role() = 'service_role' or v_order.customer = auth.uid() or ${ctx.scope.can("v_order.tenant", names.read)}) then
94032
+ if not found or not (auth.role() = 'service_role' or coalesce(v_order.customer = auth.uid(), false) or ${ctx.scope.can("v_order.tenant", names.read)}) then
93709
94033
  ${fail$1("ORDERS_ORDER_NOT_FOUND", "order not found", "P0002")}
93710
94034
  end if;
93711
94035
  return ${fn("order_json")}(v_order.id);
@@ -94184,7 +94508,7 @@ as $$
94184
94508
  'orderId', o.${o("id")},
94185
94509
  'number', o.${o("number")},
94186
94510
  'customerId', o.${o("customer")},
94187
- 'status', o.${o("status")},
94511
+ 'status', ${ctx.label("orders", "status", `o.${o("status")}`)},
94188
94512
  'state', (${STATES})[min(${rank(stateOf("p"))})],
94189
94513
  'sentAt', min(p.${lp("queuedAt")}),
94190
94514
  'readyAt', case when bool_and(p.${lp("readyAt")} is not null) then max(p.${lp("readyAt")}) end,
@@ -94682,7 +95006,7 @@ create table if not exists ${t("carts")} (
94682
95006
  ${c("updatedAt")} timestamptz not null default now(),
94683
95007
  ${c("convertedAt")} timestamptz
94684
95008
  );
94685
- create unique index if not exists ${ctx.naming.rename("carts_open_idx")} on ${t("carts")} (${c("tenant")}, ${c("user")}, ${c("currency")}) where ${c("status")} = 'open';
95009
+ create unique index if not exists ${ctx.naming.rename("carts_open_idx")} on ${t("carts")} (${c("tenant")}, ${c("user")}, ${c("currency")}) where ${ctx.is("carts", "status", c("status"), ["open"])};
94686
95010
  create index if not exists ${ctx.naming.rename("carts_user_idx")} on ${t("carts")} (${c("user")});
94687
95011
  create index if not exists ${ctx.naming.rename("carts_rate_idx")} on ${t("carts")} (${c("shippingRate")});
94688
95012
  ${c("priceList") && priceList ? `create index if not exists ${ctx.naming.rename("carts_price_list_idx")} on ${t("carts")} (${c("priceList")});\n` : ""}${lockModuleTable(ctx, "carts", { read: true })}
@@ -95931,7 +96255,7 @@ begin
95931
96255
  if not exists (select 1 from ${n.m} m where m.${n.tenant} = organization and m.${n.user} = member) then
95932
96256
  ${fail$1("ORGANIZATION_NOT_MEMBER", "Not a member", "P0002")}
95933
96257
  end if;
95934
- if not (${SERVICE_CALLER$1}) and member = auth.uid() then
96258
+ if not (${SERVICE_CALLER$1}) and coalesce(member = auth.uid(), false) then
95935
96259
  ${fail$1("ORGANIZATION_SELF_ROLE", "You cannot change your own role")}
95936
96260
  end if;
95937
96261
  if not better_supabase.can_assign(organization, role) then
@@ -95972,7 +96296,7 @@ begin
95972
96296
  if not exists (select 1 from ${mr} r where r.${n.tenant} = organization and r.${n.user} = member and r."role" = role) then
95973
96297
  return false;
95974
96298
  end if;
95975
- if not (${SERVICE_CALLER$1}) and member = auth.uid() then
96299
+ if not (${SERVICE_CALLER$1}) and coalesce(member = auth.uid(), false) then
95976
96300
  ${fail$1("ORGANIZATION_SELF_ROLE", "You cannot change your own role")}
95977
96301
  end if;
95978
96302
  if not better_supabase.can_assign(organization, role) then
@@ -96031,7 +96355,7 @@ begin
96031
96355
  end if;
96032
96356
  -- Checked here whatever blocks.organizations.options.assignmentGuard
96033
96357
  -- says: a guard that checks only client writes never sees this function's.
96034
- if not (${SERVICE_CALLER$1}) and member = auth.uid() then
96358
+ if not (${SERVICE_CALLER$1}) and coalesce(member = auth.uid(), false) then
96035
96359
  ${fail$1("ORGANIZATION_SELF_ROLE", "You cannot change your own role")}
96036
96360
  end if;
96037
96361
  if not better_supabase.can_assign(organization, previous_assignable)
@@ -97171,7 +97495,7 @@ declare
97171
97495
  v_entry uuid;
97172
97496
  begin
97173
97497
  select * into v_pass from ${passes} x where x.${p("id")} = book_with_credit.pass_id for update;
97174
- if not found or not (v_pass.${p("holderUser")} = auth.uid() or ${allowed(`v_pass.${p("tenant")}`, manage)}) then
97498
+ if not found or not (coalesce(v_pass.${p("holderUser")} = auth.uid(), false) or ${allowed(`v_pass.${p("tenant")}`, manage)}) then
97175
97499
  ${fail$1("PASS_NOT_FOUND", "pass not found", "P0002")}
97176
97500
  end if;
97177
97501
  if v_pass.${p("status")} <> 'active' then
@@ -97258,7 +97582,7 @@ declare
97258
97582
  v_pass ${passes}%rowtype;
97259
97583
  begin
97260
97584
  select * into v_pass from ${passes} x where x.${p("id")} = list_pass_credits.pass_id;
97261
- if not found or not (v_pass.${p("holderUser")} = auth.uid() or ${allowed(`v_pass.${p("tenant")}`, read)}) then
97585
+ if not found or not (coalesce(v_pass.${p("holderUser")} = auth.uid(), false) or ${allowed(`v_pass.${p("tenant")}`, read)}) then
97262
97586
  ${fail$1("PASS_NOT_FOUND", "pass not found", "P0002")}
97263
97587
  end if;
97264
97588
  return coalesce((
@@ -97813,7 +98137,7 @@ declare
97813
98137
  v_row ${passes}%rowtype;
97814
98138
  begin
97815
98139
  select * into v_row from ${passes} x where x.${p("id")} = get_pass.pass_id;
97816
- if not found or not (v_row.${p("holderUser")} = auth.uid() or ${allowed(`v_row.${p("tenant")}`, manage)}) then
98140
+ if not found or not (coalesce(v_row.${p("holderUser")} = auth.uid(), false) or ${allowed(`v_row.${p("tenant")}`, manage)}) then
97817
98141
  return null;
97818
98142
  end if;
97819
98143
  return ${withNonce("v_row")};
@@ -97933,7 +98257,7 @@ declare
97933
98257
  v_pass ${passes}%rowtype;
97934
98258
  begin
97935
98259
  select * into v_pass from ${passes} x where x.${p("id")} = list_pass_check_ins.pass_id;
97936
- if not found or not (v_pass.${p("holderUser")} = auth.uid() or ${allowed(`v_pass.${p("tenant")}`, read)}) then
98260
+ if not found or not (coalesce(v_pass.${p("holderUser")} = auth.uid(), false) or ${allowed(`v_pass.${p("tenant")}`, read)}) then
97937
98261
  return '[]'::jsonb;
97938
98262
  end if;
97939
98263
  return (
@@ -97955,7 +98279,7 @@ ${occupancy}`;
97955
98279
  /** Moves the passes on a merged registered subject to the record it merged into. */
97956
98280
  function passMerges(ctx) {
97957
98281
  if (!keepsSubject(ctx)) return "";
97958
- return subjectMergeHandler(ctx, registeredSubjects(ctx.subjects, ctx.naming).map((subject) => [subject.type, {
98282
+ return subjectMergeHandler(ctx, registeredSubjects$1(ctx.subjects, ctx.naming).map((subject) => [subject.type, {
97959
98283
  table: `${subject.schema}.${subject.table}`,
97960
98284
  extra: {}
97961
98285
  }]), moveSubjectRows({
@@ -98377,7 +98701,7 @@ function pipelineBindings(ctx) {
98377
98701
  };
98378
98702
  }
98379
98703
  for (const [type, entry] of Object.entries(configured)) if (!(type in raw)) raw[type] = entry;
98380
- const registry = registeredSubjects({
98704
+ const registry = registeredSubjects$1({
98381
98705
  ...builtInSubjects,
98382
98706
  ...ctx.subjects
98383
98707
  }, ctx.naming);
@@ -99490,8 +99814,8 @@ ${renderPolicy(policy$1({
99490
99814
  * the ones the app lacks.
99491
99815
  */
99492
99816
  function rowJson(ctx, table, alias) {
99493
- if (ctx.owns(table)) return `to_jsonb(${alias})`;
99494
- return `jsonb_build_object(${Object.entries(NAMES$40.tables[table]?.columns ?? {}).map(([logical, name]) => `${sqlString(name)}, ${ctx.has(table, logical) ? `${alias}.${ctx.col(table, logical)}` : "null"}`).join(", ")})`;
99817
+ if (ctx.owns(table)) return ctx.rowJson(table, alias);
99818
+ return `jsonb_build_object(${Object.entries(NAMES$40.tables[table]?.columns ?? {}).map(([logical, name]) => `${sqlString(name)}, ${ctx.has(table, logical) ? ctx.label(table, logical, `${alias}.${ctx.col(table, logical)}`) : "null"}`).join(", ")})`;
99495
99819
  }
99496
99820
  /**
99497
99821
  * `options.extraColumns`, added to the pipelines table. `stages` is reserved:
@@ -100899,7 +101223,7 @@ declare
100899
101223
  begin
100900
101224
  select x.${c("tenant")} as tenant, x.${c("user")} as owner, x.${c("status")} as status
100901
101225
  into v_cart from ${orders.table("carts")} x where x.${c("id")} = apply_promotion_code.cart for update;
100902
- if not found or not (auth.role() = 'service_role' or v_cart.owner = auth.uid()) then
101226
+ if not found or not (auth.role() = 'service_role' or coalesce(v_cart.owner = auth.uid(), false)) then
100903
101227
  ${fail$1("ORDERS_CART_NOT_FOUND", "cart not found", "P0002")}
100904
101228
  end if;
100905
101229
  if v_cart.status <> 'open' then
@@ -100942,7 +101266,7 @@ declare
100942
101266
  begin
100943
101267
  select x.${c("user")} as owner, x.${c("status")} as status
100944
101268
  into v_cart from ${orders.table("carts")} x where x.${c("id")} = remove_promotion_code.cart;
100945
- if not found or not (auth.role() = 'service_role' or v_cart.owner = auth.uid()) then
101269
+ if not found or not (auth.role() = 'service_role' or coalesce(v_cart.owner = auth.uid(), false)) then
100946
101270
  ${fail$1("ORDERS_CART_NOT_FOUND", "cart not found", "P0002")}
100947
101271
  end if;
100948
101272
  if v_cart.status <> 'open' then
@@ -101589,22 +101913,27 @@ function pushTickets(ctx) {
101589
101913
  const events = recordsEvents(ctx) ? `
101590
101914
  -- The delivery's provider message id is Expo's first ticket id, so every
101591
101915
  -- receipt of the delivery records its event on that message, once per
101592
- -- ticket.
101593
- perform ${notifications.fn("record_delivery_event")}(
101594
- 'expo',
101595
- d.${d("providerMessageId")},
101596
- case when r ->> 'status' = 'ok' then 'delivered' else 'bounced' end,
101597
- 'expo-receipt:' || (r ->> 'id'),
101598
- now(),
101599
- jsonb_strip_nulls(jsonb_build_object('token', x.${c("token")}, 'error', r ->> 'error', 'message', r ->> 'message')),
101600
- false
101601
- )
101602
- from ${t} x
101603
- join ${notifications.table("deliveries")} d on d.${d("id")} = x.${c("delivery")}
101604
- cross join jsonb_array_elements(complete_push_receipts.receipts) r
101605
- where x.${c("ticket")} = r ->> 'id'
101606
- and x.${c("checkedAt")} is null
101607
- and d.${d("providerMessageId")} is not null;` : "";
101916
+ -- ticket. The events stored now come back for the client to emit.
101917
+ select coalesce(jsonb_agg(e.recorded || jsonb_build_object('provider_event_id', e.event_id)), '[]'::jsonb)
101918
+ into v_events
101919
+ from (
101920
+ select ${notifications.fn("record_delivery_event")}(
101921
+ 'expo',
101922
+ d.${d("providerMessageId")},
101923
+ case when r ->> 'status' = 'ok' then 'delivered' else 'bounced' end,
101924
+ 'expo-receipt:' || (r ->> 'id'),
101925
+ now(),
101926
+ jsonb_strip_nulls(jsonb_build_object('token', x.${c("token")}, 'error', r ->> 'error', 'message', r ->> 'message')),
101927
+ false
101928
+ ) as recorded, 'expo-receipt:' || (r ->> 'id') as event_id
101929
+ from ${t} x
101930
+ join ${notifications.table("deliveries")} d on d.${d("id")} = x.${c("delivery")}
101931
+ cross join jsonb_array_elements(complete_push_receipts.receipts) r
101932
+ where x.${c("ticket")} = r ->> 'id'
101933
+ and x.${c("checkedAt")} is null
101934
+ and d.${d("providerMessageId")} is not null
101935
+ ) e
101936
+ where coalesce((e.recorded ->> 'recorded')::boolean, false);` : "";
101608
101937
  return `
101609
101938
  -- One row per delivery and device: the Expo ticket id, or the error Expo
101610
101939
  -- answered. A retried delivery skips the devices that already have a ticket.
@@ -101708,15 +102037,20 @@ $$;
101708
102037
  -- Stores what Expo answered for each ticket, [{ id, status: ok | error,
101709
102038
  -- error, message }], and records notification.delivered or bounced on the
101710
102039
  -- delivery when the notifications block tracks provider events. A ticket
101711
- -- Expo has no receipt for yet stays unchecked. Returns how many it stored.
102040
+ -- Expo has no receipt for yet stays unchecked. Returns { updated, events }:
102041
+ -- how many tickets it stored and the provider events it recorded for the
102042
+ -- first time, as record_delivery_event returns them. Postgres can't change
102043
+ -- a return type in place, so the integer version is dropped first.
102044
+ drop function if exists ${fn("complete_push_receipts")}(jsonb);
101712
102045
  create or replace function ${fn("complete_push_receipts")}(receipts jsonb)
101713
- returns integer
102046
+ returns jsonb
101714
102047
  language plpgsql
101715
102048
  security definer
101716
102049
  set search_path = ''
101717
102050
  as $$
101718
102051
  declare
101719
102052
  v_count integer;
102053
+ v_events jsonb := '[]'::jsonb;
101720
102054
  begin${serviceOnly}
101721
102055
  if jsonb_typeof(complete_push_receipts.receipts) <> 'array' or jsonb_array_length(complete_push_receipts.receipts) > 1000 then
101722
102056
  ${fail$1("PUSH_TOO_MANY", "pass at most 1000 receipts", "22023")}
@@ -101728,7 +102062,7 @@ begin${serviceOnly}
101728
102062
  where x.${c("ticket")} = r ->> 'id'
101729
102063
  and x.${c("checkedAt")} is null;
101730
102064
  get diagnostics v_count = row_count;
101731
- return v_count;
102065
+ return jsonb_build_object('updated', v_count, 'events', v_events);
101732
102066
  end;
101733
102067
  $$;
101734
102068
  ${TICKET_FUNCTIONS.map(([name, args]) => `revoke execute on function ${fn(name)}(${args}) from public, anon, authenticated;
@@ -101755,7 +102089,7 @@ function ticketsContract(ctx) {
101755
102089
  {
101756
102090
  name: "complete_push_receipts",
101757
102091
  args: ["jsonb"],
101758
- returns: "integer"
102092
+ returns: "jsonb"
101759
102093
  }
101760
102094
  ];
101761
102095
  }
@@ -102088,11 +102422,15 @@ const PUSH = {
102088
102422
  integrates: ["notifications"],
102089
102423
  target: "schema",
102090
102424
  modes: ["managed", "custom"],
102091
- version: 2,
102425
+ version: 3,
102092
102426
  upgrades: [{
102093
102427
  from: 1,
102094
102428
  description: "With the notifications block installed, push_tickets stores Expo's tickets per delivery; record_push_tickets, push_tickets_for, unchecked_push_tickets and complete_push_receipts are new, for retries that skip devices already sent to and the receipt check.",
102095
102429
  sql: () => ""
102430
+ }, {
102431
+ from: 2,
102432
+ description: "complete_push_receipts returns { updated, events }: the ticket count and the provider events it recorded for the first time, so the client emits notification.delivered and notification.bounced like recordDeliveryEvent does.",
102433
+ sql: () => ""
102096
102434
  }],
102097
102435
  names: NAMES$37,
102098
102436
  contract: contract$33,
@@ -103588,7 +103926,7 @@ const RANK_REBALANCE_LENGTH = 24;
103588
103926
  /** The rebalance job's queue. */
103589
103927
  const ALPHABET = sqlString(RANK_ALPHABET);
103590
103928
  function ranked(ctx) {
103591
- return registeredSubjects(ctx.subjects, ctx.naming).filter((subject) => subject.config.rank !== void 0);
103929
+ return registeredSubjects$1(ctx.subjects, ctx.naming).filter((subject) => subject.config.rank !== void 0);
103592
103930
  }
103593
103931
  function cases(selector, subjects, branch, otherwise) {
103594
103932
  if (subjects.length === 0) return otherwise;
@@ -107615,11 +107953,11 @@ ${lockTable(views, { read: true })}
107615
107953
  or ${scope} = 'tenant'
107616
107954
  )`;
107617
107955
  const mayEdit = (alias) => `(auth.role() = 'service_role'
107618
- or (${alias}.${scope} = 'user' and ${alias}.${owner} = auth.uid())
107956
+ or (${alias}.${scope} = 'user' and coalesce(${alias}.${owner} = auth.uid(), false))
107619
107957
  or (${alias}.${scope} <> 'user' and ${ctx.scope.can(`${alias}.${tenant}`, share)}))`;
107620
107958
  const maySee = (alias) => `(auth.role() = 'service_role'
107621
107959
  or (${ctx.scope.can(`${alias}.${tenant}`, read)} and (
107622
- (${alias}.${scope} = 'user' and ${alias}.${owner} = auth.uid())
107960
+ (${alias}.${scope} = 'user' and coalesce(${alias}.${owner} = auth.uid(), false))
107623
107961
  or (${alias}.${scope} = 'team' and ${inTeam(`${alias}.${team}`)})
107624
107962
  or ${alias}.${scope} = 'tenant')))`;
107625
107963
  const collection = ctx.installed("collections") ? collectionCheck(ctx.of("collections")) : "";
@@ -108834,7 +109172,7 @@ function dimensionsOf(ctx) {
108834
109172
  }
108835
109173
  /** The registered subjects with a `search` entry and a tenant column. */
108836
109174
  function searchedSubjects(ctx) {
108837
- return registeredSubjects(ctx.subjects, ctx.naming).filter((subject) => subject.config.search !== void 0 && subject.tenant !== void 0 && (subject.config.search.title ?? subject.config.title) !== void 0);
109175
+ return registeredSubjects$1(ctx.subjects, ctx.naming).filter((subject) => subject.config.search !== void 0 && subject.tenant !== void 0 && (subject.config.search.title ?? subject.config.title) !== void 0);
108838
109176
  }
108839
109177
  /** Whether any searched subject returns a description with its hits. */
108840
109178
  const describes = (subjects) => subjects.some((subject) => subject.config.search?.description !== void 0);
@@ -110288,7 +110626,7 @@ function names$1(ctx) {
110288
110626
  read: ctx.permission("read", keys.read),
110289
110627
  edit: ctx.permission("edit", keys.edit),
110290
110628
  maxMembers,
110291
- subjects: registeredSubjects(ctx.subjects, ctx.naming).filter((subject) => subject.tenant !== void 0)
110629
+ subjects: registeredSubjects$1(ctx.subjects, ctx.naming).filter((subject) => subject.tenant !== void 0)
110292
110630
  };
110293
110631
  }
110294
110632
  function tables$4(ctx, n) {
@@ -113369,8 +113707,9 @@ function functions$1(ctx, extras) {
113369
113707
  const fields = extraFieldsArg(extras);
113370
113708
  const linked = ctx.has("shipments", "subjectType") && ctx.has("shipments", "subjectId");
113371
113709
  const location = ctx.has("shipments", "fromLocation");
113372
- const shipStatus = (row) => asText$2(ctx, "shipments", `${row}.${h("status")}`);
113373
- const eventStatus = (row) => asText$2(ctx, "trackingEvents", `${row}.${e("status")}`);
113710
+ const shipStatus = (row) => ctx.mapsValues("shipments", "status") ? ctx.label("shipments", "status", `${row}.${h("status")}`) : asText$2(ctx, "shipments", `${row}.${h("status")}`);
113711
+ const eventStatus = (row) => ctx.mapsValues("trackingEvents", "status") ? ctx.label("trackingEvents", "status", `${row}.${e("status")}`) : asText$2(ctx, "trackingEvents", `${row}.${e("status")}`);
113712
+ const st = (row, labels, negate = false) => ctx.is("shipments", "status", `${row}.${h("status")}`, labels, negate);
113374
113713
  const or = (table, row, logical) => ctx.has(table, logical) ? `${row}.${ctx.col(table, logical)}` : "null";
113375
113714
  const also = (table, logical) => ctx.has(table, logical) ? `, ${ctx.col(table, logical)}` : "";
113376
113715
  const alsoValue = (table, logical, value) => ctx.has(table, logical) ? `, ${value}` : "";
@@ -113378,8 +113717,8 @@ function functions$1(ctx, extras) {
113378
113717
  const lines = (...groups) => groups.map((group) => group.filter((value) => value !== void 0).join(", ")).filter((line) => line !== "").join(",\n ");
113379
113718
  const allowed = (tenant, permission) => `(${SERVICE_CALLER$1} or ${ctx.can("tenant", tenant, permission)})`;
113380
113719
  const packagesJson = (row) => `(select coalesce(jsonb_agg(jsonb_build_object('id', pk.${p("id")}, 'position', pk.${p("position")}, 'weightGrams', pk.${p("weight")}, 'lengthMm', ${or("packages", "pk", "length")}, 'widthMm', ${or("packages", "pk", "width")}, 'heightMm', ${or("packages", "pk", "height")}, 'reference', ${or("packages", "pk", "reference")}) order by pk.${p("position")}), '[]'::jsonb) from ${packages} pk where pk.${p("shipment")} = ${row}.${h("id")})`;
113381
- const shipmentJson = (row) => withExtraFields(`jsonb_build_object('id', ${row}.${h("id")}, 'organizationId', ${row}.${h("tenant")}::text, 'reference', ${row}.${h("reference")}, 'status', ${row}.${h("status")}, 'from', ${row}.${h("fromAddress")}, 'to', ${row}.${h("toAddress")}, 'fromLocationId', ${or("shipments", row, "fromLocation")}, 'subjectType', ${or("shipments", row, "subjectType")}, 'subjectId', ${or("shipments", row, "subjectId")}, 'carrier', ${row}.${h("carrier")}, 'service', ${row}.${h("service")}, 'trackingNumber', ${row}.${h("trackingNumber")}, 'trackingUrl', ${or("shipments", row, "trackingUrl")}, 'labelId', ${row}.${h("labelId")}, 'labelUrl', ${or("shipments", row, "labelUrl")}, 'labelFormat', ${row}.${h("labelFormat")}, 'labelCost', ${row}.${h("labelCost")}::text, 'currency', ${row}.${h("currency")}, 'labeledAt', ${row}.${h("labeledAt")}, 'deliveredAt', ${row}.${h("deliveredAt")}, 'cancelledAt', ${row}.${h("cancelledAt")}, 'createdBy', ${or("shipments", row, "createdBy")}, 'createdAt', ${row}.${h("createdAt")}, 'updatedAt', ${row}.${h("updatedAt")}, 'packages', ${packagesJson(row)})`, row, extras);
113382
- const eventJson = (row) => `jsonb_build_object('id', ${row}.${e("id")}, 'externalId', ${row}.${e("externalId")}, 'status', ${row}.${e("status")}, 'occurredAt', ${row}.${e("occurredAt")}, 'description', ${or("trackingEvents", row, "description")}, 'location', ${or("trackingEvents", row, "location")}, 'source', ${row}.${e("source")}, 'createdAt', ${row}.${e("createdAt")})`;
113720
+ const shipmentJson = (row) => withExtraFields(`jsonb_build_object('id', ${row}.${h("id")}, 'organizationId', ${row}.${h("tenant")}::text, 'reference', ${row}.${h("reference")}, 'status', ${ctx.label("shipments", "status", `${row}.${h("status")}`)}, 'from', ${row}.${h("fromAddress")}, 'to', ${row}.${h("toAddress")}, 'fromLocationId', ${or("shipments", row, "fromLocation")}, 'subjectType', ${or("shipments", row, "subjectType")}, 'subjectId', ${or("shipments", row, "subjectId")}, 'carrier', ${row}.${h("carrier")}, 'service', ${row}.${h("service")}, 'trackingNumber', ${row}.${h("trackingNumber")}, 'trackingUrl', ${or("shipments", row, "trackingUrl")}, 'labelId', ${row}.${h("labelId")}, 'labelUrl', ${or("shipments", row, "labelUrl")}, 'labelFormat', ${row}.${h("labelFormat")}, 'labelCost', ${row}.${h("labelCost")}::text, 'currency', ${row}.${h("currency")}, 'labeledAt', ${row}.${h("labeledAt")}, 'deliveredAt', ${row}.${h("deliveredAt")}, 'cancelledAt', ${row}.${h("cancelledAt")}, 'createdBy', ${or("shipments", row, "createdBy")}, 'createdAt', ${row}.${h("createdAt")}, 'updatedAt', ${row}.${h("updatedAt")}, 'packages', ${packagesJson(row)})`, row, extras);
113721
+ const eventJson = (row) => `jsonb_build_object('id', ${row}.${e("id")}, 'externalId', ${row}.${e("externalId")}, 'status', ${ctx.label("trackingEvents", "status", `${row}.${e("status")}`)}, 'occurredAt', ${row}.${e("occurredAt")}, 'description', ${or("trackingEvents", row, "description")}, 'location', ${or("trackingEvents", row, "location")}, 'source', ${row}.${e("source")}, 'createdAt', ${row}.${e("createdAt")})`;
113383
113722
  const subject = (row) => `'shipments/' || ${row}.${h("id")}::text`;
113384
113723
  const base = (row) => `'organizationId', ${row}.${h("tenant")}::text, 'id', ${row}.${h("id")}`;
113385
113724
  const audited = (row, summary) => ({
@@ -113406,7 +113745,7 @@ function functions$1(ctx, extras) {
113406
113745
  end;`;
113407
113746
  const statusRecord = ctx.record({
113408
113747
  type: "shipment.status_changed",
113409
- payload: `jsonb_build_object(${base("v_ship")}, 'from', v_from, 'to', v_ship.${h("status")}, 'trackingNumber', v_ship.${h("trackingNumber")})`,
113748
+ payload: `jsonb_build_object(${base("v_ship")}, 'from', v_from, 'to', ${ctx.label("shipments", "status", `v_ship.${h("status")}`)}, 'trackingNumber', v_ship.${h("trackingNumber")})`,
113410
113749
  subject: subject("v_ship"),
113411
113750
  tenant: `v_ship.${h("tenant")}`,
113412
113751
  audit: false
@@ -113416,8 +113755,8 @@ function functions$1(ctx, extras) {
113416
113755
  where t.${e("shipment")} = v_ship.${h("id")}
113417
113756
  order by t.${e("occurredAt")} desc, array_position(array[${list(TRACKING_STATUSES)}]::text[], ${eventStatus("t")}) desc
113418
113757
  limit 1;
113419
- if v_status is not null and v_ship.${h("status")} <> 'cancelled' and v_status <> ${shipStatus("v_ship")} then
113420
- v_from := v_ship.${h("status")};
113758
+ if v_status is not null and ${st("v_ship", ["cancelled"], true)} and v_status <> ${shipStatus("v_ship")} then
113759
+ v_from := ${ctx.label("shipments", "status", `v_ship.${h("status")}`)};
113421
113760
  update ${shipments} x set
113422
113761
  ${h("status")} = ${ctx.cast("shipments", "status", "v_status")},
113423
113762
  ${h("deliveredAt")} = case when v_status = 'delivered' then v_at end,
@@ -113589,7 +113928,7 @@ declare
113589
113928
  v_ship ${shipments}%rowtype;${syncDeclare}
113590
113929
  begin
113591
113930
  ${findForWrite("set_shipment_label.shipment_id")}
113592
- if v_ship.${h("status")} <> 'draft' then
113931
+ if ${st("v_ship", ["draft"], true)} then
113593
113932
  ${fail$1("SHIPMENT_NOT_DRAFT", "only a draft shipment gets a label", "55000")}
113594
113933
  end if;
113595
113934
  begin
@@ -113615,7 +113954,7 @@ ${findForWrite("set_shipment_label.shipment_id")}
113615
113954
  ${fail$1("SHIPMENT_LABEL_INVALID", "a label needs a carrier, service, tracking number, label id, a cost of zero or more and a currency", "22023")}
113616
113955
  end if;
113617
113956
  insert into ${events} (${e("tenant")}, ${e("shipment")}, ${e("externalId")}, ${e("status")}, ${e("occurredAt")}${also("trackingEvents", "description")}, ${e("source")})
113618
- values (v_ship.${h("tenant")}, v_ship.${h("id")}, 'label:' || v_ship.${h("labelId")}, 'label_created', now()${alsoValue("trackingEvents", "description", "'Label created'")}, 'carrier')
113957
+ values (v_ship.${h("tenant")}, v_ship.${h("id")}, 'label:' || v_ship.${h("labelId")}, ${ctx.value("trackingEvents", "status", "label_created")}, now()${alsoValue("trackingEvents", "description", "'Label created'")}, 'carrier')
113619
113958
  on conflict (${e("shipment")}, ${e("externalId")}) do nothing;
113620
113959
  ${ctx.record({
113621
113960
  type: "shipment.labeled",
@@ -113679,7 +114018,7 @@ begin
113679
114018
  end if;
113680
114019
  ${insertEvents("ingest_tracking_events.events", "'webhook'")}
113681
114020
  ${syncStatus}
113682
- return jsonb_build_object('id', v_ship.${h("id")}, 'organizationId', v_ship.${h("tenant")}::text, 'status', v_ship.${h("status")}, 'recorded', v_count);
114021
+ return jsonb_build_object('id', v_ship.${h("id")}, 'organizationId', v_ship.${h("tenant")}::text, 'status', ${ctx.label("shipments", "status", `v_ship.${h("status")}`)}, 'recorded', v_count);
113683
114022
  end;
113684
114023
  $$;
113685
114024
  ${serviceGrant(`${fn("ingest_tracking_events")}(text, text, jsonb)`)}
@@ -113697,11 +114036,11 @@ declare
113697
114036
  v_ship ${shipments}%rowtype;
113698
114037
  begin
113699
114038
  ${findForWrite("cancel_shipment.shipment_id")}
113700
- if v_ship.${h("status")} not in ('draft', 'label_created') then
114039
+ if ${st("v_ship", ["draft", "label_created"], true)} then
113701
114040
  ${fail$1("SHIPMENT_SHIPPED", "only a draft or a shipment that hasn't left gets cancelled", "55000")}
113702
114041
  end if;
113703
114042
  update ${shipments} x set
113704
- ${h("status")} = 'cancelled',
114043
+ ${h("status")} = ${ctx.value("shipments", "status", "cancelled")},
113705
114044
  ${h("cancelledAt")} = now(),
113706
114045
  ${h("updatedAt")} = now()
113707
114046
  where x.${h("id")} = v_ship.${h("id")}
@@ -113750,7 +114089,7 @@ ${userGrant(`${fn("list_tracking_events")}(uuid)`)}
113750
114089
  */
113751
114090
  function shipmentMerges(ctx) {
113752
114091
  if (!ctx.has("shipments", "subjectType") || !ctx.has("shipments", "subjectId")) return "";
113753
- return subjectMergeHandler(ctx, registeredSubjects(ctx.subjects, ctx.naming).map((subject) => [subject.type, {
114092
+ return subjectMergeHandler(ctx, registeredSubjects$1(ctx.subjects, ctx.naming).map((subject) => [subject.type, {
113754
114093
  table: `${subject.schema}.${subject.table}`,
113755
114094
  extra: {}
113756
114095
  }]), moveSubjectRows({
@@ -114371,7 +114710,7 @@ begin
114371
114710
  if not found then
114372
114711
  ${notFound}
114373
114712
  end if;
114374
- if not (${SERVICE_CALLER$1} or v_req.${r("requestedBy")} = auth.uid() or ${ctx.can("tenant", `v_req.${r("tenant")}`, manage)}) then
114713
+ if not (${SERVICE_CALLER$1} or coalesce(v_req.${r("requestedBy")} = auth.uid(), false) or ${ctx.can("tenant", `v_req.${r("tenant")}`, manage)}) then
114375
114714
  ${forbidden("not allowed to cancel this request")}
114376
114715
  end if;
114377
114716
  if v_req.${r("status")} <> 'pending' then
@@ -114401,7 +114740,7 @@ begin
114401
114740
  if not found then
114402
114741
  ${notFound}
114403
114742
  end if;
114404
- if not (${SERVICE_CALLER$1} or auth.uid() = any (v_req.${r("signers")}) or ${readableRequest("v_req")}) then
114743
+ if not (${SERVICE_CALLER$1} or coalesce(auth.uid() = any (v_req.${r("signers")}), false) or ${readableRequest("v_req")}) then
114405
114744
  ${forbidden("not allowed to read this request")}
114406
114745
  end if;
114407
114746
  select coalesce(jsonb_agg(${signatureJson("g")} order by g.${s("signedAt")}), '[]'::jsonb) into v_items
@@ -115337,8 +115676,9 @@ function workItemFunctions(ctx, n) {
115337
115676
  if ${attrs} ->> ${sqlString(key)} is not null then
115338
115677
  ${fail$1("WORK_ITEM_FIELD_UNSUPPORTED", `this ${ctx.tableName(table).name} table has no ${logical} column`, "22023")}
115339
115678
  end if;`).join("");
115679
+ const extrasInsert = insertExtraColumns(t("items"), n.extras, "(create_work_item.attrs -> 'fields')");
115340
115680
  const editable = (alias) => `(${n.service} or ${ctx.scope.can(`${alias}.${w("tenant")}`, n.write)})`;
115341
- const row = (alias) => `to_jsonb(${alias})${ctx.labelsJson("items", alias)} || ${int8Text(alias, [w("number")])} || jsonb_build_object('assignees', coalesce((select jsonb_agg(ra.${a("user")} order by ${ctx.has("assignees", "createdAt") ? `ra.${a("createdAt")}, ` : ""}ra.${a("user")}) from ${t("assignees")} ra where ra.${a("item")} = ${alias}.${w("id")}), '[]'::jsonb)) || ${itemExtrasJson(ctx, n, alias)}`;
115681
+ const row = (alias) => `${ctx.rowJson("items", alias, { as: { number: (v) => `${v}::text` } })} || ${int8Text(alias, [w("number")])} || jsonb_build_object('assignees', coalesce((select jsonb_agg(ra.${a("user")} order by ${ctx.has("assignees", "createdAt") ? `ra.${a("createdAt")}, ` : ""}ra.${a("user")}) from ${t("assignees")} ra where ra.${a("item")} = ${alias}.${w("id")}), '[]'::jsonb)) || ${itemExtrasJson(ctx, n, alias)}`;
115342
115682
  const record = (type, alias, extra = "") => ctx.record({
115343
115683
  type,
115344
115684
  payload: `jsonb_build_object('organizationId', ${alias}.${w("tenant")}, 'workItemId', ${alias}.${w("id")}, 'subjectType', ${item}, 'subjectId', ${alias}.${w("id")}::text, 'title', ${alias}.${w("title")}${extra})`,
@@ -115362,7 +115702,8 @@ function workItemFunctions(ctx, n) {
115362
115702
  subjectType: item,
115363
115703
  subjectId: `v_row.${w("id")}::text`
115364
115704
  });
115365
- const notify = ctx.installed("notifications") ? `
115705
+ const actionPath = n.actionPath === "" ? "null" : `replace(replace(${sqlString(n.actionPath)}, '{id}', v_row.${w("id")}::text), '{identifier}', ${ctx.has("items", "identifier") ? `coalesce(v_row.${w("identifier")}, '')` : "''"})`;
115706
+ const notify = ctx.installed("notifications") && n.notify ? `
115366
115707
  if cardinality(v_new) > 0 then
115367
115708
  ${ctx.notify(`jsonb_build_object(
115368
115709
  'type', ${sqlString(e("work_item.assigned"))},
@@ -115370,7 +115711,9 @@ function workItemFunctions(ctx, n) {
115370
115711
  'actor', auth.uid(),
115371
115712
  'subject_type', ${item},
115372
115713
  'subject_id', v_row.${w("id")}::text,
115714
+ 'subject_label', v_row.${w("title")},
115373
115715
  'summary', v_row.${w("title")},
115716
+ 'action_path', ${actionPath},
115374
115717
  'recipients', to_jsonb(v_new),
115375
115718
  'watchers', false,
115376
115719
  'key', ${sqlString(e("work_item.assigned:"))} || v_row.${w("id")}::text || ':' || md5(array_to_string(v_new, ',')),
@@ -115434,7 +115777,7 @@ ${["startOn", "targetOn"].flatMap((key) => ctx.has("projects", key) ? [`
115434
115777
  when check_violation or not_null_violation then
115435
115778
  ${fail$1("WORK_ITEM_PROJECT_INVALID", "a project needs a key of capitals and a name, and ends after it starts", "22023")}
115436
115779
  end;
115437
- return (select to_jsonb(x) || jsonb_build_object('progress', ${has("project") ? `(
115780
+ return (select ${ctx.rowJson("projects", "x")} || jsonb_build_object('progress', ${has("project") ? `(
115438
115781
  select case when count(*) = 0 then null else round(100.0 * count(*) filter (where ${state(`y.${w("state")}`, ["completed"])}) / count(*) filter (where ${state(`y.${w("state")}`, ["canceled"], true)})) end
115439
115782
  from ${t("items")} y where y.${w("project")} = x.${p("id")} and y.${w("archivedAt")} is null
115440
115783
  )` : "null"}) from ${t("projects")} x where x.${p("id")} = v_id);
@@ -115474,7 +115817,7 @@ begin
115474
115817
  exception when check_violation or not_null_violation then
115475
115818
  ${fail$1("WORK_ITEM_ITERATION_INVALID", "an iteration needs a name and ends on or after it starts", "22023")}
115476
115819
  end;
115477
- return (select to_jsonb(x) from ${t("iterations")} x where x.${i("id")} = v_id);
115820
+ return (select ${ctx.rowJson("iterations", "x")} from ${t("iterations")} x where x.${i("id")} = v_id);
115478
115821
  end;
115479
115822
  $$;
115480
115823
  ${userGrant(`${fn("save_iteration")}(${ctx.idType}, uuid, jsonb)`)}
@@ -115542,7 +115885,7 @@ begin
115542
115885
  w("pipeline"),
115543
115886
  w("stage"),
115544
115887
  column("createdBy")
115545
- ])})
115888
+ ])}${extrasInsert.columns})
115546
115889
  values (${lines(" ", [
115547
115890
  "create_work_item.tenant",
115548
115891
  "v_seq",
@@ -115561,7 +115904,7 @@ begin
115561
115904
  "(create_work_item.attrs ->> 'pipelineId')::uuid",
115562
115905
  "(create_work_item.attrs ->> 'stageId')::uuid",
115563
115906
  present("items", "createdBy", "auth.uid()")
115564
- ])})
115907
+ ])}${extrasInsert.values})
115565
115908
  returning ${w("id")} into v_id;
115566
115909
  exception when check_violation or invalid_text_representation or datetime_field_overflow or numeric_value_out_of_range or foreign_key_violation then
115567
115910
  ${fail$1("WORK_ITEM_ATTRS_INVALID", "a work item field has an invalid value", "22023")}
@@ -115870,7 +116213,9 @@ const NAMES$16 = {
115870
116213
  "prefix",
115871
116214
  "maxAssignees",
115872
116215
  "extraColumns",
115873
- "authorCanDelete"
116216
+ "authorCanDelete",
116217
+ "notify",
116218
+ "actionPath"
115874
116219
  ],
115875
116220
  tables: {
115876
116221
  items: {
@@ -116214,6 +116559,8 @@ function build$16(ctx) {
116214
116559
  create: sqlString(ctx.config.permissions["create"] ?? ctx.permissionKey("write", keys.write)),
116215
116560
  remove: sqlString(ctx.config.permissions["delete"] ?? ctx.permissionKey("manage", keys.manage)),
116216
116561
  authorCanDelete: ctx.flag("authorCanDelete", true),
116562
+ notify: ctx.flag("notify", true),
116563
+ actionPath: ctx.text("actionPath", ""),
116217
116564
  prefix: ctx.text("prefix", "TASK-"),
116218
116565
  maxAssignees,
116219
116566
  service: "(auth.role() = 'service_role')",
@@ -116532,7 +116879,7 @@ function businessHours(ctx) {
116532
116879
  };
116533
116880
  }
116534
116881
  function bindings(ctx) {
116535
- const registry = registeredSubjects(ctx.subjects, ctx.naming);
116882
+ const registry = registeredSubjects$1(ctx.subjects, ctx.naming);
116536
116883
  return Object.entries(onSettings(ctx)).map(([type, entry]) => {
116537
116884
  const where = `blocks.${ctx.instance}.on.${type}`;
116538
116885
  const subject = registry.find((item) => item.type === type);
@@ -122677,7 +123024,7 @@ declare
122677
123024
  v_entries jsonb;
122678
123025
  v_totals jsonb;
122679
123026
  begin
122680
- if not (${SERVICE_CALLER$1} or (v_user = auth.uid() and ${ctx.can("tenant", "get_timesheet.tenant", track)}) or ${ctx.can("tenant", "get_timesheet.tenant", read)}) then
123027
+ if not (${SERVICE_CALLER$1} or (coalesce(v_user = auth.uid(), false) and ${ctx.can("tenant", "get_timesheet.tenant", track)}) or ${ctx.can("tenant", "get_timesheet.tenant", read)}) then
122681
123028
  ${forbidden("not allowed to read this timesheet")}
122682
123029
  end if;
122683
123030
  select * into v_sheet from ${timesheets} s
@@ -122847,7 +123194,7 @@ begin
122847
123194
  if not (v_reader or ${ctx.can("tenant", "list_timesheets.tenant", track)}) then
122848
123195
  ${forbidden("not allowed to list timesheets")}
122849
123196
  end if;
122850
- if not v_reader and list_timesheets.user_id is not null and list_timesheets.user_id <> auth.uid() then
123197
+ if not v_reader and list_timesheets.user_id is not null and list_timesheets.user_id is distinct from auth.uid() then
122851
123198
  ${forbidden("not allowed to read another member's timesheets")}
122852
123199
  end if;
122853
123200
  select coalesce(jsonb_agg(q.item order by q.week desc, q.created desc), '[]'::jsonb) into v_rows
@@ -122983,7 +123330,7 @@ function statusTimesheetFunctions(ctx, names) {
122983
123330
  const { ended, running, owner } = names;
122984
123331
  const by = owner.employee;
122985
123332
  const ownerVar = by ? "v_owner" : "v_user";
122986
- const sheetMine = (row) => by ? `(${owner.sheetUser ? `${row}.${t("user")} = auth.uid() or ` : ""}${row}.${owner.timesheets} = ${owner.mine(`${row}.${t("tenant")}`)})` : `${row}.${t("user")} = auth.uid()`;
123333
+ const sheetMine = (row) => by ? `(${owner.sheetUser ? `coalesce(${row}.${t("user")} = auth.uid(), false) or ` : ""}${row}.${owner.timesheets} = ${owner.mine(`${row}.${t("tenant")}`)})` : `coalesce(${row}.${t("user")} = auth.uid(), false)`;
122987
123334
  const ownerParam = by ? ", employee_id uuid default null" : "";
122988
123335
  const ownerType = by ? ", uuid" : "";
122989
123336
  const fn = (name) => ctx.fn(name);
@@ -123198,7 +123545,7 @@ begin
123198
123545
  if not (v_reader or ${ctx.can("tenant", "list_timesheets.tenant", track)}) then
123199
123546
  ${forbidden("not allowed to list timesheets")}
123200
123547
  end if;
123201
- if not v_reader and list_timesheets.user_id is not null and list_timesheets.user_id <> auth.uid() then
123548
+ if not v_reader and list_timesheets.user_id is not null and list_timesheets.user_id is distinct from auth.uid() then
123202
123549
  ${forbidden("not allowed to read another member's timesheets")}
123203
123550
  end if;${by ? `
123204
123551
  if not v_reader and list_timesheets.employee_id is not null and list_timesheets.employee_id is distinct from ${owner.mine("list_timesheets.tenant")} then
@@ -123919,7 +124266,7 @@ begin
123919
124266
  if not (${SERVICE_CALLER$1} or ((v_owner = ${myEmployee("list_time_entries.tenant")} and not list_time_entries.everyone) and ${ctx.can("tenant", "list_time_entries.tenant", track)}) or ${ctx.can("tenant", "list_time_entries.tenant", read)}) then` : ` v_user uuid := coalesce(list_time_entries.user_id, auth.uid());
123920
124267
  v_rows jsonb;
123921
124268
  begin
123922
- if not (${SERVICE_CALLER$1} or ((v_user = auth.uid() and not list_time_entries.everyone) and ${ctx.can("tenant", "list_time_entries.tenant", track)}) or ${ctx.can("tenant", "list_time_entries.tenant", read)}) then`}
124269
+ if not (${SERVICE_CALLER$1} or ((coalesce(v_user = auth.uid(), false) and not list_time_entries.everyone) and ${ctx.can("tenant", "list_time_entries.tenant", track)}) or ${ctx.can("tenant", "list_time_entries.tenant", read)}) then`}
123923
124270
  ${forbidden("not allowed to read these entries")}
123924
124271
  end if;
123925
124272
  select coalesce(jsonb_agg(${entryJson("q")} order by q.${e("startedAt")} desc), '[]'::jsonb) into v_rows
@@ -124106,7 +124453,7 @@ function activityReads(ctx) {
124106
124453
  sources: ["event"]
124107
124454
  };
124108
124455
  if (!ctx.installed("subjects")) return none;
124109
- const registry = registeredSubjects(ctx.subjects, ctx.naming);
124456
+ const registry = registeredSubjects$1(ctx.subjects, ctx.naming);
124110
124457
  if (registry.length === 0) return none;
124111
124458
  const a = (logical) => ctx.col("activity", logical);
124112
124459
  const readable = ctx.fn("activity_subject_readable");