better-supabase 0.41.0 → 0.42.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 (159) hide show
  1. package/dist/ai-sdk/agents/index.d.ts +2 -2
  2. package/dist/{app-tables-kHGNXFsd.d.ts → app-tables-DGgCgRwq.d.ts} +1 -1
  3. package/dist/{approvals-CTVaWq1O.d.ts → approvals-CYbTzQ7v.d.ts} +39 -1
  4. package/dist/{approvals-Qjn42OAZ.js → approvals-cyL5CmU7.js} +15 -3
  5. package/dist/{authorization-CS5Q1V7A.d.ts → authorization-CcvJbvr1.d.ts} +30 -2
  6. package/dist/{bind-XrFxNm5r.d.ts → bind-B71jMEGG.d.ts} +1 -1
  7. package/dist/{block-env-CHFHOjvz.d.ts → block-env-DzYTC9d1.d.ts} +3 -3
  8. package/dist/{block-subjects-Bz95_dqA.js → block-subjects-a_ECM9o0.js} +1 -1
  9. package/dist/{block-tables-EXcmuOJT.d.ts → block-tables-B92SBFqM.d.ts} +1 -1
  10. package/dist/blocks/ai-chat/index.d.ts +3 -3
  11. package/dist/blocks/announcements/index.d.ts +3 -3
  12. package/dist/blocks/api-keys/index.d.ts +1 -1
  13. package/dist/blocks/approvals/index.d.ts +2 -2
  14. package/dist/blocks/approvals/index.js +2 -2
  15. package/dist/blocks/attachments/index.d.ts +1 -1
  16. package/dist/blocks/audit/index.d.ts +2 -2
  17. package/dist/blocks/automations/index.d.ts +2 -2
  18. package/dist/blocks/billing/index.d.ts +1 -1
  19. package/dist/blocks/bookings/index.d.ts +1 -1
  20. package/dist/blocks/calendar/index.d.ts +1 -1
  21. package/dist/blocks/comments/index.d.ts +4 -4
  22. package/dist/blocks/drive/index.d.ts +1 -1
  23. package/dist/blocks/entitlements/index.d.ts +2 -2
  24. package/dist/blocks/expenses/index.js +1 -1
  25. package/dist/blocks/forms/index.d.ts +1 -1
  26. package/dist/blocks/inbox/index.d.ts +4 -4
  27. package/dist/blocks/index.d.ts +1 -1
  28. package/dist/blocks/invoices/index.d.ts +14 -5
  29. package/dist/blocks/invoices/index.js +16 -8
  30. package/dist/blocks/leave/index.js +1 -1
  31. package/dist/blocks/messaging/index.d.ts +4 -4
  32. package/dist/blocks/mfa/index.d.ts +1 -1
  33. package/dist/blocks/notifications/index.d.ts +3 -3
  34. package/dist/blocks/onboarding/index.d.ts +1 -1
  35. package/dist/blocks/organizations/index.d.ts +2 -2
  36. package/dist/blocks/permissions/index.d.ts +1 -1
  37. package/dist/blocks/push/index.d.ts +1 -1
  38. package/dist/blocks/reactions/index.d.ts +3 -3
  39. package/dist/blocks/saved-views/index.d.ts +1 -1
  40. package/dist/blocks/search/index.d.ts +2 -2
  41. package/dist/blocks/sessions/index.d.ts +1 -1
  42. package/dist/blocks/settings/index.d.ts +1 -1
  43. package/dist/blocks/subjects/index.d.ts +1 -1
  44. package/dist/blocks/tags/index.d.ts +1 -1
  45. package/dist/blocks/undo/index.d.ts +1 -1
  46. package/dist/blocks/usage/index.d.ts +1 -1
  47. package/dist/blocks/workflow-editor/index.d.ts +3 -3
  48. package/dist/blocks/workflows/index.d.ts +3 -3
  49. package/dist/claims/index.d.ts +3 -3
  50. package/dist/cli/add-BbhRYaFe.js +1 -0
  51. package/dist/cli/{add-BGErz-yb.js → add-NosuEQn1.js} +10 -10
  52. package/dist/cli/{add-DU5HAq6w.js → add-U0pyhIyx.js} +2 -2
  53. package/dist/cli/{app-table-files-Drzpekpt.js → app-table-files-DUi898lB.js} +2 -2
  54. package/dist/cli/{app-tables-dZpH63--.js → app-tables-BINtREbx.js} +2 -2
  55. package/dist/cli/{backfill-B-p-19g6.js → backfill-VfqI5GqN.js} +1 -1
  56. package/dist/cli/bin.js +1 -1
  57. package/dist/cli/{blocks-iUjNl5yJ.js → blocks-Bo2Lw2UO.js} +1 -1
  58. package/dist/cli/{blocks-Ews-FZZO.js → blocks-DsEaPf6J.js} +1 -1
  59. package/dist/cli/{cache-JT4JhdmX.js → cache-CNJD8OdR.js} +1 -1
  60. package/dist/cli/{codemod-KIxYiazj.js → codemod-BWa3Bte6.js} +1 -1
  61. package/dist/cli/{content-mapper-DkXzxt6f.js → content-mapper-Dl50Ny6a.js} +2 -2
  62. package/dist/cli/{doctor-VWanOD74.js → doctor-B9GtOGSa.js} +15 -15
  63. package/dist/cli/{gen-_lBdTgaR.js → gen-CIUD1sgB.js} +11 -11
  64. package/dist/cli/index.d.ts +1 -1
  65. package/dist/cli/index.js +6 -6
  66. package/dist/cli/{init-Cm6n4u_3.js → init-wl5jk5vX.js} +8 -8
  67. package/dist/cli/{live-D4iSuTmS.js → live-B0f_X3rI.js} +2 -2
  68. package/dist/cli/{mcp-CHYX7utI.js → mcp-CZWaBkXY.js} +2 -2
  69. package/dist/cli/{metadata-DLba0VjH.js → metadata-Bi5eQP4w.js} +3 -3
  70. package/dist/cli/{migrate-nQhh0nEJ.js → migrate-DMITLPEu.js} +1 -1
  71. package/dist/cli/{migration-safety-C2d3BSTf.js → migration-safety-2n8e8njJ.js} +1 -1
  72. package/dist/cli/{migrations-BOmMcme9.js → migrations-C5k9hNOo.js} +2 -2
  73. package/dist/cli/{module-migration-DSDB473C.js → module-migration-BFchEhAJ.js} +2 -2
  74. package/dist/cli/{powersync-CAHvPkkb.js → powersync-DViexv6m.js} +3 -3
  75. package/dist/cli/powersync-i7KJcTtM.js +1 -0
  76. package/dist/cli/{print-CahE8HYK.js → print-ChX1vQhO.js} +2 -2
  77. package/dist/cli/{providers-CL5Z5Uj4.js → providers-lwK2lplZ.js} +1 -1
  78. package/dist/cli/{prune-workflows-C9xO0fRU.js → prune-workflows-DO3nRZFF.js} +1 -1
  79. package/dist/cli/{remove-DIy7gthm.js → remove-WB9dFyNn.js} +5 -5
  80. package/dist/cli/{render-CoCZr3Ru.js → render-B0MMWWZE.js} +3 -3
  81. package/dist/cli/{run-BBj137Fn.js → run-CMvwtBX9.js} +27 -27
  82. package/dist/cli/{run-CVw8hmLk.js → run-CmJbNG2-.js} +9 -9
  83. package/dist/cli/{shared-BdKeo7xp.js → shared-BL5kcRdz.js} +1 -1
  84. package/dist/cli/{snapshot-P2ww2xCt.js → snapshot-CVB9Ri2a.js} +2 -2
  85. package/dist/cli/{source-BCs4oBl2.js → source-COGgsYiV.js} +1 -1
  86. package/dist/cli/{spec-oPbt9sbZ.js → spec-002zD_9Z.js} +1 -1
  87. package/dist/cli/{spec-uCpXPLoF.js → spec-CH6Qd2LE.js} +2 -2
  88. package/dist/cli/{sql-layout-Bsnge2oW.js → sql-layout-jZOzCj-S.js} +2 -2
  89. package/dist/cli/{sync-Cv7iBRhe.js → sync-I4x-1aVx.js} +4 -4
  90. package/dist/cli/{upgrade-C6jWNxkc.js → upgrade-BRp5AxAY.js} +2 -2
  91. package/dist/cli/{upgrade-DV7jTRdh.js → upgrade-C60BZggI.js} +5 -5
  92. package/dist/cli/{version-Hza4Q2PB.js → version-CRCAxS2s.js} +1 -1
  93. package/dist/client/index.d.ts +5 -5
  94. package/dist/client/native/index.d.ts +4 -4
  95. package/dist/config/index.d.ts +2 -2
  96. package/dist/config/index.js +4 -4
  97. package/dist/{config-DwXYtmwt.js → config-2SwAe0Im.js} +3 -3
  98. package/dist/{config-B7hnJFxh.js → config-BND2PFGs.js} +1 -1
  99. package/dist/{context-tFoygone.d.ts → context-DXWyPNzr.d.ts} +3 -1
  100. package/dist/contract/index.d.ts +3 -3
  101. package/dist/{controller-phhsPHSz.d.ts → controller-D3MPVovD.d.ts} +1 -1
  102. package/dist/create/index.d.ts +3 -3
  103. package/dist/create/index.js +3 -3
  104. package/dist/create/lite/index.d.ts +3 -3
  105. package/dist/create/lite/index.js +2 -2
  106. package/dist/{entitlements-LfW6S2RW.d.ts → entitlements-CljrSoWD.d.ts} +1 -1
  107. package/dist/eve/index.d.ts +1 -1
  108. package/dist/eve/index.js +1 -1
  109. package/dist/{field-errors-CMWRPBmF.d.ts → field-errors-C4NOUBpu.d.ts} +4 -4
  110. package/dist/{index-BXkPvYzd.d.ts → index-Bjj-GNhd.d.ts} +1 -1
  111. package/dist/{index-X5igfnIi.d.ts → index-BrGOE0c2.d.ts} +2 -2
  112. package/dist/{index-RZqQdq1G.d.ts → index-CUxdZYSi.d.ts} +2 -2
  113. package/dist/{index-B21Pim3I.d.ts → index-D5qW2cRD.d.ts} +2 -2
  114. package/dist/{index-fmrLdtVT.d.ts → index-DWVDKVYA.d.ts} +1 -1
  115. package/dist/{index-D-uiT4Qz.d.ts → index-DhHtsi-q.d.ts} +1 -1
  116. package/dist/{index-B-HuxATL.d.ts → index-DmSDAFkF.d.ts} +6 -6
  117. package/dist/{instances-DJOknCJ0.js → instances-DwrdFwKq.js} +2 -0
  118. package/dist/mapper/bin.js +5 -5
  119. package/dist/mcp/index.d.ts +1 -1
  120. package/dist/next/index.d.ts +4 -4
  121. package/dist/{operations-Cm4mSrAX.d.ts → operations-DFmuxaxW.d.ts} +1 -1
  122. package/dist/{options-zsLpIqBA.js → options-B1oSaIZ4.js} +2 -1
  123. package/dist/{options-CYZH9uxU.js → options-BXiUftgG.js} +3 -1
  124. package/dist/{options-CzxG2Phg.js → options-DLJTiX29.js} +3 -1
  125. package/dist/otel/index.js +4 -4
  126. package/dist/{permissions-r0Cxhxos.d.ts → permissions-Bsd4mEEZ.d.ts} +1 -1
  127. package/dist/{ports-BJJJmfWK.d.ts → ports-BKdt_9Oe.d.ts} +1 -1
  128. package/dist/powersync/index.d.ts +2 -2
  129. package/dist/preset/index.d.ts +3 -3
  130. package/dist/preset/index.js +3 -3
  131. package/dist/{preset-U47pzJMK.js → preset-CenE7f1G.js} +2 -2
  132. package/dist/{project-Dng8tO8S.js → project-Ceh2yTSv.js} +5 -5
  133. package/dist/{push-token-CA31xmQr.d.ts → push-token-DRcEl9Ce.d.ts} +1 -1
  134. package/dist/react/index.d.ts +5 -5
  135. package/dist/react/native/index.d.ts +1 -1
  136. package/dist/react/server.d.ts +5 -5
  137. package/dist/realtime/index.d.ts +3 -3
  138. package/dist/records/index.d.ts +3 -3
  139. package/dist/server/index.d.ts +3 -3
  140. package/dist/solid/index.d.ts +5 -5
  141. package/dist/sql/index.d.ts +5 -5
  142. package/dist/sql/index.js +3 -3
  143. package/dist/{sql-BudVz33a.js → sql-BIniB45X.js} +481 -163
  144. package/dist/ssr/index.d.ts +1 -1
  145. package/dist/svelte/index.d.ts +5 -5
  146. package/dist/{tenant-C2vnB0wX.d.ts → tenant--Hm8mlPy.d.ts} +1 -1
  147. package/dist/testing/index.d.ts +3 -3
  148. package/dist/testing/index.js +1 -1
  149. package/dist/{topic-CKN3kmoi.d.ts → topic-BYF-GTW9.d.ts} +1 -1
  150. package/dist/{types-D8Tltfdq.d.ts → types-B8h0reJ4.d.ts} +2 -2
  151. package/dist/vue/index.d.ts +5 -5
  152. package/dist/{watch-topic-0dXuJMuE.d.ts → watch-topic-tfTxgEGc.d.ts} +1 -1
  153. package/dist/workflow-sdk/world/index.js +1 -1
  154. package/dist/{workflow-sdk-vXuxBSrk.js → workflow-sdk-Bps7tpOv.js} +7 -1
  155. package/dist/yjs/index.d.ts +1 -1
  156. package/package.json +1 -1
  157. package/schemas/config-v1.json +20 -1
  158. package/dist/cli/add-CoP8iie6.js +0 -1
  159. package/dist/cli/powersync-nH-NLDjy.js +0 -1
@@ -3,16 +3,16 @@ import { d as temporalText } from "./temporal-DKTdGK9i.js";
3
3
  import { r as NEGATIVE, t as FILTER_OPERATORS } from "./filter-query-Ds7Z6lgZ.js";
4
4
  import { a as ok } from "./result-8xza7w5W.js";
5
5
  import { a as hasPlaceholder, l as splitPlaceholders, s as placeholderOf } from "./read-set-DEDoIHMM.js";
6
- import { c as resolveJsonSchema, i as installedBlockSubjects, l as CONFIG_DEFAULTS, o as blockColumnName, s as resolveNames } from "./block-subjects-Bz95_dqA.js";
6
+ import { c as resolveJsonSchema, i as installedBlockSubjects, l as CONFIG_DEFAULTS, o as blockColumnName, s as resolveNames } from "./block-subjects-a_ECM9o0.js";
7
7
  import { t as DEFAULT_CLAIMS } from "./claims-CqTr_N1n.js";
8
8
  import { o as tenantNames, r as composeNames } from "./entity-naming-BES3pkQI.js";
9
- import { C as encryptedColumns, I as resolveBlock, L as tenantNameOf, N as BLOCK_SCOPES, S as columnsWithAccess, T as hiddenColumns, a as isRenamedInstance, g as appTableVersions, i as instancePrefix, l as APP_RANK_COLUMN, m as appTableEventKinds, s as APP_DELETED_AT_COLUMN, w as hasColumnAccess, x as hasComputed } from "./instances-DJOknCJ0.js";
9
+ import { C as encryptedColumns, I as resolveBlock, L as tenantNameOf, N as BLOCK_SCOPES, S as columnsWithAccess, T as hiddenColumns, a as isRenamedInstance, g as appTableVersions, i as instancePrefix, l as APP_RANK_COLUMN, m as appTableEventKinds, s as APP_DELETED_AT_COLUMN, w as hasColumnAccess, x as hasComputed } from "./instances-DwrdFwKq.js";
10
10
  import { a as RATING_BOUNDS, n as CUSTOM_FIELD_TYPES, r as FIELD_FORMATS, t as CUSTOM_FIELD_FORM_TYPES } from "./field-formats-Cap-V7UP.js";
11
11
  import { t as isSqlType } from "./sql-type-XWMeZRAl.js";
12
12
  import { a as sqlString, i as sqlIdent } from "./template-CNq9xcfx.js";
13
13
  import { i as fillTemplate, l as templatePlaceholders } from "./access-sql-Dao1C0fz.js";
14
14
  import { t as MAX_BATCH } from "./batch-limit-DqQ3d6op.js";
15
- import { $ as pageSize, A as addNotNullCheck, B as extraFieldsArg, C as SCHEMA$5, D as addCheck, E as activeMembership, F as defaultPartitionName, G as jwtClaim, H as fail$1, I as disabledHelpers, J as membershipDisabledAt, K as lockTable, L as disabledHelpersNeedLaterTables, M as columnRef, N as columnsObject, O as addExtraColumns, P as defaultPartition, Q as ownRowPolicies, R as dropExpiredPartitions, S as PARTITION_VARIABLES, T as accessDefinesDisabledHelpers, U as insertExtraColumns, V as extraFieldsJson, W as jsonSchemaChecks, X as notNullCheckName, Y as membershipSuspended, Z as organizationMissing, _ as rolesOf, _t as userGrant, at as replaceColumnCheck, b as MONTHLY_PARTITIONS, c as accessModel, ct as serviceGrant, d as moduleOperations, dt as shortHash, et as quotedTable$1, f as modulePermission, ft as splitTable$1, g as roleScopeIs, gt as updatedAt, h as roleNames, ht as updateExtraColumns, it as renameSql, j as batchFunction, k as addForeignKey, l as hasPlatformRoles, lt as serviceOnly$1, m as providerPlatformRoles, mt as triggerGrant, n as WORKFLOW_SDK_WORLD, nt as recordTrigger, o as MODULE_PERMISSION_SCOPES, ot as revokeTable, p as modulePermissionKey, pt as transitionActorSql, q as memberAddedRecord, rt as registerPartitions, s as OPERATIONS, st as schemaPreamble, tt as raise$1, u as isOperationModule$1, ut as sha256Hex$1, v as tenantScope, vt as withExtraFields, w as SERVICE_CALLER$1, x as NOTHING, y as EQUIVALENT_TRIGGERS, yt as writeExtraColumns, z as ensureCheck } from "./workflow-sdk-vXuxBSrk.js";
15
+ import { $ as pageSize, A as addNotNullCheck, B as extraFieldsArg, C as SCHEMA$5, D as addCheck, E as activeMembership, F as defaultPartitionName, G as jwtClaim, H as fail$1, I as disabledHelpers, J as membershipDisabledAt, K as lockTable, L as disabledHelpersNeedLaterTables, M as columnRef, N as columnsObject, O as addExtraColumns, P as defaultPartition, Q as ownRowPolicies, R as dropExpiredPartitions, S as PARTITION_VARIABLES, T as accessDefinesDisabledHelpers, U as insertExtraColumns, V as extraFieldsJson, W as jsonSchemaChecks, X as notNullCheckName, Y as membershipSuspended, Z as organizationMissing, _ as rolesOf, _t as updatedAt, at as replaceColumnCheck, b as MONTHLY_PARTITIONS, bt as writeExtraColumns, c as accessModel, ct as serviceGrant, d as moduleOperations, dt as shortHash, et as quotedTable$1, f as modulePermission, ft as splitTable$1, g as roleScopeIs, gt as updateExtraColumns, h as roleNames, ht as triggerGrant, it as renameSql, j as batchFunction, k as addForeignKey, l as hasPlatformRoles, lt as serviceOnly$1, m as providerPlatformRoles, mt as transitionReasonSql, n as WORKFLOW_SDK_WORLD, nt as recordTrigger, o as MODULE_PERMISSION_SCOPES, ot as revokeTable, p as modulePermissionKey, pt as transitionActorSql, q as memberAddedRecord, rt as registerPartitions, s as OPERATIONS, st as schemaPreamble, tt as raise$1, u as isOperationModule$1, ut as sha256Hex$1, v as tenantScope, vt as userGrant, w as SERVICE_CALLER$1, x as NOTHING, y as EQUIVALENT_TRIGGERS, yt as withExtraFields, z as ensureCheck } from "./workflow-sdk-Bps7tpOv.js";
16
16
  import { n as blockOptions, r as option, t as NO_OPTIONS } from "./options-Z-bd_H1E.js";
17
17
  import { t as accessRequestsSqlOptions } from "./options-BSTJmfX4.js";
18
18
  import { t as activitiesSqlOptions } from "./options-DFemc2im.js";
@@ -24,7 +24,7 @@ import { t as aiKeysSqlOptions } from "./options-DQkhhBLy.js";
24
24
  import { t as aiSchedulesSqlOptions } from "./options-BgCS5ODi.js";
25
25
  import { t as announcementsSqlOptions } from "./options-Bs2dC-at.js";
26
26
  import { t as apiKeysSqlOptions } from "./options-PM7IaIFP.js";
27
- import { t as approvalsSqlOptions } from "./options-CzxG2Phg.js";
27
+ import { t as approvalsSqlOptions } from "./options-DLJTiX29.js";
28
28
  import { t as assetsSqlOptions } from "./options-BLn1PFyu.js";
29
29
  import { t as attachmentsSqlOptions } from "./options-CJR59q8s.js";
30
30
  import { t as auditSqlOptions } from "./options-C2RjdunU.js";
@@ -53,7 +53,7 @@ import { t as donationsSqlOptions } from "./options-ompJjxkV.js";
53
53
  import { t as driveSqlOptions } from "./options-CjocPkX1.js";
54
54
  import { t as employeesSqlOptions } from "./options-XiD_Y3oK.js";
55
55
  import { t as enrollmentsSqlOptions } from "./options-eIEk0vqV.js";
56
- import { t as expensesSqlOptions } from "./options-CYZH9uxU.js";
56
+ import { t as expensesSqlOptions } from "./options-BXiUftgG.js";
57
57
  import { t as flagsSqlOptions } from "./options-BMO-FnOT.js";
58
58
  import { t as formsSqlOptions } from "./options-DpwRG4tO.js";
59
59
  import { t as goalsSqlOptions } from "./options-BNRvoEkj.js";
@@ -66,7 +66,7 @@ import { t as invoicesSqlOptions } from "./options-C5cLEJEa.js";
66
66
  import { t as knowledgeSqlOptions } from "./options-CyYZvdSy.js";
67
67
  import { t as leadScoringSqlOptions } from "./options-COfEYic3.js";
68
68
  import { t as leasesSqlOptions } from "./options-CzIPn0fF.js";
69
- import { t as leaveSqlOptions } from "./options-zsLpIqBA.js";
69
+ import { t as leaveSqlOptions } from "./options-B1oSaIZ4.js";
70
70
  import { t as mailSyncSqlOptions } from "./options-C1RIyAe1.js";
71
71
  import { t as membershipsSqlOptions } from "./options-z2Zhi97E.js";
72
72
  import { t as memorySqlOptions } from "./options-DTTz33na.js";
@@ -3523,7 +3523,11 @@ function migrationOptionUses(modules = {}) {
3523
3523
  // src/sql/modules/approvals-policies.ts
3524
3524
  /** The action of a floor that covers every action of its subject type. */
3525
3525
  const ANY_ACTION = "*";
3526
+ /** The subject type of a floor that covers every subject type. */
3527
+ const ANY_SUBJECT = "*";
3526
3528
  const KEY$1 = /^[a-z][a-z0-9_-]*$/;
3529
+ /** An action name, with dotted segments such as `quote.send`. */
3530
+ const ACTION$1 = /^[a-z][a-z0-9_-]*(?:\.[a-z][a-z0-9_-]*)*$/;
3527
3531
  const UUID$7 = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
3528
3532
  const DURATION = /^P(?=\d|T\d)(\d+Y)?(\d+M)?(\d+W)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?$/;
3529
3533
  const WHERE$18 = "blocks.approvals.options.policies";
@@ -3612,7 +3616,7 @@ function runOf(value, where) {
3612
3616
  * entry that tenant policies tighten) may have no steps.
3613
3617
  */
3614
3618
  function policyOf(subjectType, action, value, where = `${WHERE$18}.${subjectType}.${action}`, floor = false) {
3615
- if (!KEY$1.test(action) && action !== ANY_ACTION) throw new TypeError(`${where} has an invalid name`);
3619
+ if (!ACTION$1.test(action) && action !== ANY_ACTION) throw new TypeError(`${where} has an invalid name`);
3616
3620
  if (!isFields(value)) throw new TypeError(`${where} must be an object`);
3617
3621
  const steps = value["steps"];
3618
3622
  if (!Array.isArray(steps) || steps.length === 0 && !floor) throw new TypeError(`${where}.steps must be a non-empty list`);
@@ -3641,7 +3645,7 @@ function approvalPolicies(ctx) {
3641
3645
  if (raw === void 0) return [];
3642
3646
  if (!isFields(raw)) throw new TypeError(`${WHERE$18} must be an object`);
3643
3647
  return Object.entries(raw).flatMap(([subjectType, actions]) => {
3644
- if (!KEY$1.test(subjectType)) throw new TypeError(`${WHERE$18}.${subjectType} has an invalid name`);
3648
+ if (!KEY$1.test(subjectType) && subjectType !== ANY_SUBJECT) throw new TypeError(`${WHERE$18}.${subjectType} has an invalid name`);
3645
3649
  if (!isFields(actions)) throw new TypeError(`${WHERE$18}.${subjectType} must be an object of action to policy`);
3646
3650
  return Object.entries(actions).map(([action, value]) => policyOf(subjectType, action, value, `${WHERE$18}.${subjectType}.${action}`, true));
3647
3651
  });
@@ -3661,8 +3665,9 @@ function policySnapshot(policy) {
3661
3665
  });
3662
3666
  }
3663
3667
  /**
3664
- * The policy snapshot for the requested subject type and action, as SQL. A
3665
- * floor for action `*` covers the subject type's other actions.
3668
+ * The policy snapshot for the requested subject type and action, as SQL. The
3669
+ * most specific floor wins: the exact pair, then action `*` of the subject
3670
+ * type, then the action under subject type `*`, then `*` for both.
3666
3671
  */
3667
3672
  function policyCase(policies) {
3668
3673
  if (policies.length === 0) return "null::jsonb";
@@ -3670,9 +3675,16 @@ function policyCase(policies) {
3670
3675
  ${items.map((policy) => ` when ${sqlString(`${policy.subjectType}:${policy.action}`)} then ${sqlString(policySnapshot(policy))}::jsonb`).join("\n")}
3671
3676
  else null::jsonb
3672
3677
  end`;
3678
+ const anyAction = policies.filter((policy) => policy.action === ANY_ACTION);
3679
+ const anySubject = policies.filter((policy) => policy.subjectType === ANY_SUBJECT);
3680
+ const anyBoth = anySubject.filter((policy) => policy.action === ANY_ACTION);
3673
3681
  const exact = cases("approval_policy.subject_type || ':' || approval_policy.action", policies);
3674
- const any = policies.filter((policy) => policy.action === ANY_ACTION);
3675
- return any.length === 0 ? exact : `coalesce(${exact}, ${cases("approval_policy.subject_type || ':*'", any)})`;
3682
+ const fallbacks = [
3683
+ ...anyAction.length === 0 ? [] : [cases("approval_policy.subject_type || ':*'", anyAction)],
3684
+ ...anySubject.length === 0 ? [] : [cases("'*:' || approval_policy.action", anySubject)],
3685
+ ...anyBoth.length === 0 ? [] : [cases("'*:*'", anyBoth)]
3686
+ ];
3687
+ return fallbacks.length === 0 ? exact : `coalesce(${[exact, ...fallbacks].join(", ")})`;
3676
3688
  }
3677
3689
  /**
3678
3690
  * The floors as a jsonb list of `{ subjectType, action, effects }`, for the
@@ -8501,6 +8513,10 @@ const TENANT_POLICY_TABLES = { policies: {
8501
8513
  effect: "effect"
8502
8514
  }
8503
8515
  } };
8516
+ /** The keys the policy reads return next to the extra columns. */
8517
+ const POLICY_KEYS = ["fields"];
8518
+ /** `blocks.approvals.options.policyExtraColumns`, on the tenant policies table. */
8519
+ const policyExtras = (ctx) => tenantPoliciesOn(ctx) ? ctx.extraColumns("policies", POLICY_KEYS, "policyExtraColumns") : [];
8504
8520
  /** Whether `blocks.approvals.options.tenantPolicies` is on. */
8505
8521
  const tenantPoliciesOn = (ctx) => ctx.flag("tenantPolicies", false);
8506
8522
  /**
@@ -8528,23 +8544,25 @@ function tenantlessType(ctx, type) {
8528
8544
  const employeesOf = (ctx) => ctx.installed("employees") && ctx.of("employees").mode !== "custom" ? ctx.of("employees") : void 0;
8529
8545
  /**
8530
8546
  * The user id of the requester's manager in the request's tenant, as a SQL
8531
- * expression, or `undefined` without the employees module. An offboarded
8532
- * manager decides nothing.
8547
+ * expression, or `undefined` without the employees module. `employee`, a text
8548
+ * SQL expression, names the employee whose manager it is instead when it is not
8549
+ * null. An offboarded manager decides nothing.
8533
8550
  */
8534
- function managerOf(ctx, requester, tenant) {
8551
+ function managerOf(ctx, requester, tenant, employee) {
8535
8552
  const employees = employeesOf(ctx);
8536
8553
  if (employees === void 0) return;
8537
8554
  const e = (column) => employees.col("employees", column);
8538
8555
  const table = employees.table("employees");
8556
+ const who = employee === void 0 ? `me.${e("user")} = ${requester}` : `(case when ${employee} is not null then me.${e("id")}::text = ${employee} else me.${e("user")} = ${requester} end)`;
8539
8557
  return `(select mgr.${e("user")} from ${table} me
8540
8558
  join ${table} mgr on mgr.${e("id")} = me.${e("manager")}
8541
- where me.${e("tenant")} = ${tenant} and me.${e("user")} = ${requester}
8559
+ where me.${e("tenant")} = ${tenant} and ${who}
8542
8560
  and mgr.${e("user")} is not null and mgr.${e("status")}::text <> 'offboarded'
8543
8561
  limit 1)`;
8544
8562
  }
8545
8563
  /** Whether `user` is the requester's manager and still a member. */
8546
8564
  function managerMatch(ctx, args) {
8547
- const manager = managerOf(ctx, args.requester, args.tenant);
8565
+ const manager = managerOf(ctx, args.requester, args.tenant, args.employee);
8548
8566
  if (manager === void 0) return "false";
8549
8567
  const members = ctx.of("memberships");
8550
8568
  const m = (column) => members.col("memberships", column);
@@ -8665,6 +8683,33 @@ end;
8665
8683
  $$;
8666
8684
  revoke execute on function ${signature} from public, anon, authenticated;${payload ? approvalConditionSql(ctx) : ""}`;
8667
8685
  }
8686
+ /**
8687
+ * PL/pgSQL that raises `invalid` unless every step of `steps` (a jsonb array
8688
+ * expression) names approvers and a valid required count and escalation. It
8689
+ * reads and writes `v_step` and `v_who`.
8690
+ */
8691
+ const stepsCheck$1 = (steps, invalid, manager) => ` for v_step in select * from jsonb_array_elements(${steps}) loop
8692
+ if jsonb_typeof(v_step) <> 'object' then
8693
+ ${invalid}
8694
+ end if;
8695
+ for v_who in select a.w from (values (v_step -> 'approvers', true), (v_step -> 'escalateTo', v_step ? 'escalateTo')) a(w, checked) where a.checked loop
8696
+ if jsonb_typeof(v_who) is distinct from 'object'
8697
+ or not (v_who ?| array['permission', 'role', 'team', 'users', 'manager'])
8698
+ or (v_who ? 'manager' and ${manager ? "v_who -> 'manager' <> 'true'::jsonb" : "true"})
8699
+ or (v_who ? 'users' and (jsonb_typeof(v_who -> 'users') <> 'array'
8700
+ or exists (select 1 from jsonb_array_elements(v_who -> 'users') u
8701
+ where jsonb_typeof(u) <> 'string' or u #>> '{}' !~ '^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$'))) then
8702
+ ${invalid}
8703
+ end if;
8704
+ end loop;
8705
+ if (v_step ? 'required' and v_step -> 'required' <> '"all"'::jsonb and (jsonb_typeof(v_step -> 'required') <> 'number' or (v_step ->> 'required')::numeric < 1
8706
+ or (v_step ->> 'required')::numeric <> trunc((v_step ->> 'required')::numeric)))
8707
+ or (v_step -> 'required' = '"all"'::jsonb and (v_step -> 'approvers') - 'permission' <> '{}'::jsonb)
8708
+ or ((v_step ? 'escalateAfter') <> (v_step ? 'escalateTo'))
8709
+ or (v_step ? 'escalateAfter' and (jsonb_typeof(v_step -> 'escalateAfter') <> 'string' or (v_step ->> 'escalateAfter')::interval <= interval '0')) then
8710
+ ${invalid}
8711
+ end if;
8712
+ end loop;`;
8668
8713
  function tenantPoliciesSql(ctx, helpers) {
8669
8714
  const fn = (name) => ctx.fn(name);
8670
8715
  const t = ctx.table("policies");
@@ -8676,8 +8721,10 @@ function tenantPoliciesSql(ctx, helpers) {
8676
8721
  const payload = approvalConditions(ctx) === "payload";
8677
8722
  const rules = !payload && ctx.installed("automations") ? ctx.of("automations") : void 0;
8678
8723
  const manager = employeesOf(ctx) !== void 0;
8724
+ const extras = policyExtras(ctx);
8725
+ const inserted = insertExtraColumns(t, extras, "coalesce(save_approval_policy.policy -> 'fields', '{}'::jsonb)");
8679
8726
  const manages = (tenant) => platform ? `(case when ${tenant} is null then ${ctx.staff(manage)} else (${SERVICE_CALLER$1} or ${ctx.can("tenant", tenant, manage)}) end)` : `(${SERVICE_CALLER$1} or ${ctx.can("tenant", tenant, manage)})`;
8680
- const json = (row) => `jsonb_build_object('id', ${row}.${p("id")}, 'organizationId', ${row}.${p("tenant")}, 'subjectType', ${row}.${p("subjectType")}, 'action', ${row}.${p("action")}, 'effect', ${or(row, "effect")}, 'name', ${row}.${p("name")}, 'conditions', ${or(row, "conditions")}, 'mode', ${row}.${p("mode")}, 'steps', ${row}.${p("steps")}, 'selfApproval', ${row}.${p("selfApproval")}, 'expiresIn', ${or(row, "expiresIn")}::text, 'enabled', ${row}.${p("enabled")}, 'createdAt', ${row}.${p("createdAt")}, 'updatedAt', ${or(row, "updatedAt")})`;
8727
+ const json = (row) => `jsonb_build_object('id', ${row}.${p("id")}, 'organizationId', ${row}.${p("tenant")}, 'subjectType', ${row}.${p("subjectType")}, 'action', ${row}.${p("action")}, 'effect', ${or(row, "effect")}, 'name', ${row}.${p("name")}, 'conditions', ${or(row, "conditions")}, 'mode', ${row}.${p("mode")}, 'steps', ${row}.${p("steps")}, 'selfApproval', ${row}.${p("selfApproval")}, 'expiresIn', ${or(row, "expiresIn")}::text, 'enabled', ${row}.${p("enabled")}, 'createdAt', ${row}.${p("createdAt")}, 'updatedAt', ${or(row, "updatedAt")}${extraFieldsJson(row, extras)})`;
8681
8728
  const column = (logical, definition) => has(logical) ? `\n ${definition(p(logical))},` : "";
8682
8729
  const table = ctx.manages ? `
8683
8730
  create table if not exists ${t} (
@@ -8692,7 +8739,7 @@ create table if not exists ${t} (
8692
8739
  ${p("enabled")} boolean not null default true,${column("createdBy", (name) => `${name} uuid`)}
8693
8740
  ${p("createdAt")} timestamptz not null default now()${has("updatedAt") ? `,\n ${p("updatedAt")} timestamptz not null default now()` : ""}
8694
8741
  );
8695
- ${has("effect") ? `alter table ${t} add column if not exists ${p("effect")} text;\n` : ""}${platform ? `alter table ${t} alter column ${p("tenant")} drop not null;\n` : ""}create index if not exists ${sqlIdent(`${ctx.tableName("policies").name}_lookup_idx`)} on ${t} (${p("tenant")}, ${p("subjectType")}, ${p("action")});
8742
+ ${has("effect") ? `alter table ${t} add column if not exists ${p("effect")} text;\n` : ""}${platform ? `alter table ${t} alter column ${p("tenant")} drop not null;\n` : ""}create index if not exists ${sqlIdent(`${ctx.tableName("policies").name}_lookup_idx`)} on ${t} (${p("tenant")}, ${p("subjectType")}, ${p("action")});${addExtraColumns(t, extras)}
8696
8743
  ${lockModuleTable(ctx, "policies", { read: true })}
8697
8744
  ${renderPolicy(policy$1({
8698
8745
  table: t,
@@ -8721,9 +8768,10 @@ ${renderPolicy(policy$1({
8721
8768
  if v_conditions is not null then
8722
8769
  ${fail$1("APPROVAL_CONDITIONS_UNSUPPORTED", "this approval policies table has no conditions column", "22023")}
8723
8770
  end if;`;
8771
+ const floorPolicies = approvalPolicies(ctx);
8724
8772
  const floorExists = `(exists (
8725
- select 1 from jsonb_array_elements(${floorsJson(approvalPolicies(ctx))}) f
8726
- where (v_type = '*' or f.value ->> 'subjectType' = v_type)
8773
+ select 1 from jsonb_array_elements(${floorsJson(floorPolicies)}) f
8774
+ where (v_type = '*' or ${floorPolicies.some((each) => each.subjectType === "*") ? "f.value ->> 'subjectType' in (v_type, '*')" : "f.value ->> 'subjectType' = v_type"})
8727
8775
  and (v_action = '*' or f.value ->> 'action' in (v_action, '*'))
8728
8776
  and (v_effect is null or f.value -> 'effects' ? v_effect)
8729
8777
  )${platform ? ` or (save_approval_policy.tenant is null) or exists (
@@ -8786,37 +8834,16 @@ begin
8786
8834
  if jsonb_typeof(v_steps) <> 'array' or jsonb_array_length(v_steps) > 20 then
8787
8835
  ${stepsInvalid}
8788
8836
  end if;
8789
- for v_step in select * from jsonb_array_elements(v_steps) loop
8790
- if jsonb_typeof(v_step) <> 'object' then
8791
- ${stepsInvalid}
8792
- end if;
8793
- for v_who in select a.w from (values (v_step -> 'approvers', true), (v_step -> 'escalateTo', v_step ? 'escalateTo')) a(w, checked) where a.checked loop
8794
- if jsonb_typeof(v_who) is distinct from 'object'
8795
- or not (v_who ?| array['permission', 'role', 'team', 'users', 'manager'])
8796
- or (v_who ? 'manager' and ${manager ? "v_who -> 'manager' <> 'true'::jsonb" : "true"})
8797
- or (v_who ? 'users' and (jsonb_typeof(v_who -> 'users') <> 'array'
8798
- or exists (select 1 from jsonb_array_elements(v_who -> 'users') u
8799
- where jsonb_typeof(u) <> 'string' or u #>> '{}' !~ '^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$'))) then
8800
- ${stepsInvalid}
8801
- end if;
8802
- end loop;
8803
- if (v_step ? 'required' and v_step -> 'required' <> '"all"'::jsonb and (jsonb_typeof(v_step -> 'required') <> 'number' or (v_step ->> 'required')::numeric < 1
8804
- or (v_step ->> 'required')::numeric <> trunc((v_step ->> 'required')::numeric)))
8805
- or (v_step -> 'required' = '"all"'::jsonb and (v_step -> 'approvers') - 'permission' <> '{}'::jsonb)
8806
- or ((v_step ? 'escalateAfter') <> (v_step ? 'escalateTo'))
8807
- or (v_step ? 'escalateAfter' and (jsonb_typeof(v_step -> 'escalateAfter') <> 'string' or (v_step ->> 'escalateAfter')::interval <= interval '0')) then
8808
- ${stepsInvalid}
8809
- end if;
8810
- end loop;
8837
+ ${stepsCheck$1("v_steps", stepsInvalid, manager)}
8811
8838
  if coalesce(save_approval_policy.policy ->> 'mode', v_old.${p("mode")}::text, 'authorize') not in ('confirm', 'authorize') then
8812
8839
  ${fail$1("APPROVAL_POLICY_INVALID", "mode must be confirm or authorize", "22023")}
8813
8840
  end if;
8814
8841
  if v_old.${p("id")} is null then
8815
- insert into ${t} (${p("tenant")}, ${p("subjectType")}, ${p("action")}, ${p("name")}${has("conditions") ? `, ${p("conditions")}` : ""}${has("effect") ? `, ${p("effect")}` : ""}, ${p("mode")}, ${p("steps")}, ${p("selfApproval")}${has("expiresIn") ? `, ${p("expiresIn")}` : ""}, ${p("enabled")}${has("createdBy") ? `, ${p("createdBy")}` : ""})
8842
+ insert into ${t} (${p("tenant")}, ${p("subjectType")}, ${p("action")}, ${p("name")}${has("conditions") ? `, ${p("conditions")}` : ""}${has("effect") ? `, ${p("effect")}` : ""}, ${p("mode")}, ${p("steps")}, ${p("selfApproval")}${has("expiresIn") ? `, ${p("expiresIn")}` : ""}, ${p("enabled")}${has("createdBy") ? `, ${p("createdBy")}` : ""}${inserted.columns})
8816
8843
  values (save_approval_policy.tenant, v_type, v_action, btrim(save_approval_policy.policy ->> 'name')${has("conditions") ? ", v_conditions" : ""}${has("effect") ? ", v_effect" : ""},
8817
8844
  ${ctx.cast("policies", "mode", "coalesce(save_approval_policy.policy ->> 'mode', 'authorize')")}, v_steps,
8818
8845
  coalesce((save_approval_policy.policy ->> 'selfApproval')::boolean, false)${has("expiresIn") ? ", (save_approval_policy.policy ->> 'expiresIn')::interval" : ""},
8819
- coalesce((save_approval_policy.policy ->> 'enabled')::boolean, true)${has("createdBy") ? ", auth.uid()" : ""})
8846
+ coalesce((save_approval_policy.policy ->> 'enabled')::boolean, true)${has("createdBy") ? ", auth.uid()" : ""}${inserted.values})
8820
8847
  returning * into v_row;
8821
8848
  else
8822
8849
  update ${t} x set
@@ -8826,7 +8853,7 @@ begin
8826
8853
  ${p("mode")} = coalesce(${ctx.cast("policies", "mode", "save_approval_policy.policy ->> 'mode'")}, x.${p("mode")}),
8827
8854
  ${p("steps")} = v_steps,
8828
8855
  ${p("selfApproval")} = coalesce((save_approval_policy.policy ->> 'selfApproval')::boolean, x.${p("selfApproval")}),${has("expiresIn") ? `\n ${p("expiresIn")} = case when save_approval_policy.policy ? 'expiresIn' then (save_approval_policy.policy ->> 'expiresIn')::interval else x.${p("expiresIn")} end,` : ""}
8829
- ${p("enabled")} = coalesce((save_approval_policy.policy ->> 'enabled')::boolean, x.${p("enabled")})${has("updatedAt") ? `,\n ${p("updatedAt")} = now()` : ""}
8856
+ ${p("enabled")} = coalesce((save_approval_policy.policy ->> 'enabled')::boolean, x.${p("enabled")})${has("updatedAt") ? `,\n ${p("updatedAt")} = now()` : ""}${updateExtraColumns(t, extras, "(save_approval_policy.policy -> 'fields')")}
8830
8857
  where x.${p("id")} = v_old.${p("id")}
8831
8858
  returning * into v_row;
8832
8859
  end if;
@@ -8919,6 +8946,8 @@ function requestSql(ctx, helpers) {
8919
8946
  const args = requestArgs(ctx);
8920
8947
  const fields = extraFieldsArg(extras);
8921
8948
  const otherNew = extras.length === 0 ? `${args}, jsonb, text` : `${args}, text`;
8949
+ const manager = employeesOf(ctx) !== void 0;
8950
+ const ownInvalid = fail$1("APPROVAL_POLICY_INVALID", `policy must be { steps: [{ approvers: { permission, role, team, users${manager ? ", manager" : ""} }, required, escalateAfter, escalateTo }], mode, selfApproval, expiresIn${manager ? ", managerOf" : ""} }`, "22023");
8922
8951
  const tenantless = (name) => tenantlessTypes(ctx).length === 0 ? "" : ` or (${name}.tenant is null and ${tenantlessType(ctx, `${name}.subject_type`)} and auth.uid() is not null)`;
8923
8952
  const tenantRequired = (name) => tenantlessTypes(ctx).length === 0 ? "" : `
8924
8953
  if ${name}.tenant is null and not ${tenantlessType(ctx, `${name}.subject_type`)} then
@@ -8950,12 +8979,69 @@ end;
8950
8979
  $$;
8951
8980
  ${userGrant(`${fn("approval_requirement")}(${ctx.idType}, text, text, jsonb)`)}
8952
8981
 
8982
+ -- An app's own policy for one request, tightened by the policy the request
8983
+ -- would get anyway (base, null when there is none): steps add up, the stricter
8984
+ -- mode wins, self-approval needs both to allow it and the shorter expiry
8985
+ -- applies. It never loosens base.
8986
+ create or replace function ${fn("approval_policy_tighten")}(base jsonb, own jsonb)
8987
+ returns jsonb
8988
+ language plpgsql
8989
+ immutable
8990
+ set search_path = ''
8991
+ as $$
8992
+ declare
8993
+ v_step jsonb;
8994
+ v_who jsonb;
8995
+ v_mode text := coalesce(approval_policy_tighten.own ->> 'mode', 'authorize');
8996
+ v_steps jsonb := coalesce(approval_policy_tighten.own -> 'steps', '[]'::jsonb);
8997
+ v_level integer;
8998
+ v_expires interval;
8999
+ begin
9000
+ if jsonb_typeof(approval_policy_tighten.own) is distinct from 'object'
9001
+ or jsonb_typeof(v_steps) <> 'array' or jsonb_array_length(v_steps) > 20
9002
+ or v_mode not in ('confirm', 'authorize')
9003
+ or (approval_policy_tighten.own ? 'selfApproval' and jsonb_typeof(approval_policy_tighten.own -> 'selfApproval') <> 'boolean')
9004
+ or (approval_policy_tighten.own ? 'managerOf' and ${manager ? "jsonb_typeof(approval_policy_tighten.own -> 'managerOf') <> 'string'" : "true"})
9005
+ or (approval_policy_tighten.own ->> 'expiresIn' is not null and (approval_policy_tighten.own ->> 'expiresIn')::interval <= interval '0') then
9006
+ ${ownInvalid}
9007
+ end if;
9008
+ ${stepsCheck$1("v_steps", ownInvalid, manager)}
9009
+ v_expires := (approval_policy_tighten.own ->> 'expiresIn')::interval;
9010
+ if approval_policy_tighten.base is null then
9011
+ return jsonb_build_object(
9012
+ 'steps', v_steps,
9013
+ 'selfApproval', coalesce((approval_policy_tighten.own ->> 'selfApproval')::boolean, false),
9014
+ 'expiresIn', v_expires::text, 'run', null
9015
+ ) || case when v_mode = 'confirm' then '{"mode": "confirm"}'::jsonb else '{}'::jsonb end
9016
+ || case when approval_policy_tighten.own ? 'managerOf' then jsonb_build_object('managerOf', approval_policy_tighten.own -> 'managerOf') else '{}'::jsonb end;
9017
+ end if;
9018
+ v_level := greatest(
9019
+ ${level("coalesce(approval_policy_tighten.base ->> 'mode', 'authorize')", "coalesce(approval_policy_tighten.base -> 'steps', '[]'::jsonb)")},
9020
+ ${level("v_mode", "v_steps")}
9021
+ );
9022
+ return approval_policy_tighten.base || jsonb_build_object(
9023
+ 'steps', coalesce(approval_policy_tighten.base -> 'steps', '[]'::jsonb) || v_steps,
9024
+ 'selfApproval', coalesce((approval_policy_tighten.base ->> 'selfApproval')::boolean, false) and coalesce((approval_policy_tighten.own ->> 'selfApproval')::boolean, false),
9025
+ 'expiresIn', least((approval_policy_tighten.base ->> 'expiresIn')::interval, v_expires)::text,
9026
+ 'mode', case when v_level = 1 then 'confirm' else 'authorize' end
9027
+ ) || case when approval_policy_tighten.own ? 'managerOf' then jsonb_build_object('managerOf', approval_policy_tighten.own -> 'managerOf') else '{}'::jsonb end;
9028
+ exception
9029
+ when invalid_text_representation or invalid_datetime_format or datetime_field_overflow then
9030
+ ${ownInvalid}
9031
+ end;
9032
+ $$;
9033
+ revoke execute on function ${fn("approval_policy_tighten")}(jsonb, jsonb) from public, anon, authenticated;
9034
+
8953
9035
  drop function if exists ${fn("request_approval")}(${args});
8954
9036
  drop function if exists ${fn("request_approval")}(${args}, jsonb);
8955
9037
  drop function if exists ${fn("request_approval")}(${otherNew});
9038
+ drop function if exists ${fn("request_approval")}(${args}${fields.type}, text);
9039
+ drop function if exists ${fn("request_approval")}(${otherNew}, jsonb, uuid);
8956
9040
  -- fingerprint: the hex SHA-256 of the request's canonical form, which
8957
- -- consume_approval checks before the approved action runs.
8958
- create or replace function ${fn("request_approval")}(tenant ${ctx.idType}, subject_type text, subject_id text, action text, reason text default null, payload jsonb default '{}'::jsonb${fields.param}, fingerprint text default null)
9041
+ -- consume_approval checks before the approved action runs. The service role
9042
+ -- may pass its own policy, which only tightens the configured and stored ones,
9043
+ -- and requested_by, the user it files for, who can't approve it.
9044
+ create or replace function ${fn("request_approval")}(tenant ${ctx.idType}, subject_type text, subject_id text, action text, reason text default null, payload jsonb default '{}'::jsonb${fields.param}, fingerprint text default null, policy jsonb default null, requested_by uuid default null)
8959
9045
  returns jsonb
8960
9046
  language plpgsql
8961
9047
  security definer
@@ -8963,13 +9049,23 @@ set search_path = ''
8963
9049
  as $$
8964
9050
  declare
8965
9051
  v_policy jsonb := ${fn("approval_effective_policy")}(request_approval.tenant, request_approval.subject_type, request_approval.action, coalesce(request_approval.payload, '{}'::jsonb));
9052
+ v_service boolean := ${SERVICE_CALLER$1};
8966
9053
  v_result jsonb;
8967
9054
  v_req ${requests}%rowtype;
8968
9055
  begin
9056
+ if request_approval.policy is not null and not v_service then
9057
+ ${fail$1("APPROVAL_FORBIDDEN", "only the service role files a request under its own policy")}
9058
+ end if;
9059
+ if request_approval.requested_by is not null and not v_service and request_approval.requested_by is distinct from auth.uid() then
9060
+ ${fail$1("APPROVAL_FORBIDDEN", "only the service role files a request for another user")}
9061
+ end if;
9062
+ if request_approval.policy is not null then
9063
+ v_policy := ${fn("approval_policy_tighten")}(v_policy, request_approval.policy);
9064
+ end if;
8969
9065
  if v_policy is null then
8970
9066
  ${fail$1("APPROVAL_POLICY_UNKNOWN", "no approval policy for this subject type and action", "22023")}
8971
9067
  end if;${tenantRequired("request_approval")}
8972
- if not (${SERVICE_CALLER$1} or (${ctx.can("tenant", "request_approval.tenant", request)} and ${subjectWrite})${tenantless("request_approval")}) then
9068
+ if not (v_service or (${ctx.can("tenant", "request_approval.tenant", request)} and ${subjectWrite})${tenantless("request_approval")}) then
8973
9069
  ${fail$1("APPROVAL_FORBIDDEN", "not allowed to request approval for this record")}
8974
9070
  end if;
8975
9071
  if not ${required("v_policy")} then
@@ -8981,7 +9077,7 @@ begin
8981
9077
  if request_approval.fingerprint is not null then
8982
9078
  ${fail$1("APPROVAL_FINGERPRINT_UNSUPPORTED", "this approval requests table has no fingerprint column", "22023")}
8983
9079
  end if;`}
8984
- v_result := ${fn("open_approval")}(request_approval.tenant, request_approval.subject_type, request_approval.subject_id, request_approval.action, v_policy, request_approval.reason, request_approval.payload);${fingerprinted ? `
9080
+ v_result := ${fn("open_approval")}(request_approval.tenant, request_approval.subject_type, request_approval.subject_id, request_approval.action, v_policy, request_approval.reason, request_approval.payload, coalesce(request_approval.requested_by, auth.uid()));${fingerprinted ? `
8985
9081
  if request_approval.fingerprint is not null then
8986
9082
  update ${requests} x set ${c("fingerprint")} = request_approval.fingerprint
8987
9083
  where x.${c("id")} = (v_result ->> 'id')::uuid and x.${c("status")} = 'pending';
@@ -8994,7 +9090,7 @@ ${writeExtraColumns(requests, extras, "request_approval.fields", `x.${c("id")} =
8994
9090
  return v_result;
8995
9091
  end;
8996
9092
  $$;
8997
- ${userGrant(`${fn("request_approval")}(${args}${fields.type}, text)`)}`;
9093
+ ${userGrant(`${fn("request_approval")}(${args}${fields.type}, text, jsonb, uuid)`)}`;
8998
9094
  }
8999
9095
  function consumeSql(ctx, helpers) {
9000
9096
  const fn = (name) => ctx.fn(name);
@@ -9176,7 +9272,8 @@ const APPROVALS_NAMES = {
9176
9272
  "before_approval_request",
9177
9273
  "after_approval_request",
9178
9274
  "before_approval_decide",
9179
- "after_approval_decide"
9275
+ "after_approval_decide",
9276
+ "approval_notification"
9180
9277
  ],
9181
9278
  options: [
9182
9279
  "policies",
@@ -9184,7 +9281,9 @@ const APPROVALS_NAMES = {
9184
9281
  "platformPolicies",
9185
9282
  "conditions",
9186
9283
  "tenantless",
9187
- "extraColumns"
9284
+ "extraColumns",
9285
+ "notifications",
9286
+ "policyExtraColumns"
9188
9287
  ],
9189
9288
  tables: {
9190
9289
  requests: {
@@ -9268,7 +9367,9 @@ function approvalsContract(extra) {
9268
9367
  "text",
9269
9368
  "jsonb",
9270
9369
  ...extra,
9271
- "text"
9370
+ "text",
9371
+ "jsonb",
9372
+ "uuid"
9272
9373
  ],
9273
9374
  returns: "jsonb"
9274
9375
  },
@@ -9321,7 +9422,7 @@ function allHoldersSql(k, holders) {
9321
9422
  left join lateral (
9322
9423
  select coalesce(jsonb_agg(distinct to_jsonb(u.id::text)), '[]'::jsonb) as users
9323
9424
  from (${holders}) as u(id)
9324
- where u.id is not null and (u.id is distinct from auth.uid() or coalesce((v_policy ->> 'selfApproval')::boolean, false))
9425
+ where u.id is not null and (u.id is distinct from v_requester or coalesce((v_policy ->> 'selfApproval')::boolean, false))
9325
9426
  ) h on e.value -> 'required' = '"all"'::jsonb
9326
9427
  ));
9327
9428
  if exists (select 1 from jsonb_array_elements(v_policy -> 'steps') e where e.value -> 'required' = '0'::jsonb) then
@@ -9468,6 +9569,52 @@ function validateSteps(policies, policyColumn, holders) {
9468
9569
  }
9469
9570
  }
9470
9571
  }
9572
+ /**
9573
+ * Approval_settle, which closes the pending request of a subject its own module
9574
+ * decided.
9575
+ */
9576
+ function settleSql(ctx, k) {
9577
+ const { requests, decisions, c, d, fn, stepOf, record, also, alsoValue } = k;
9578
+ const { decided } = k;
9579
+ return `
9580
+ -- Closes the pending request for a subject that its own module decided
9581
+ -- (decide_ai_tool_approval, approve_support_request) without running the
9582
+ -- module again. A request that is no longer pending is left as it is.
9583
+ create or replace function ${fn("approval_settle")}(subject_type text, subject_id text, action text, decision text, approver uuid, comment text default null)
9584
+ returns void
9585
+ language plpgsql
9586
+ security definer
9587
+ set search_path = ''
9588
+ as $$
9589
+ #variable_conflict use_column
9590
+ declare
9591
+ v_req ${requests}%rowtype;
9592
+ begin
9593
+ select * into v_req from ${requests} r
9594
+ where r.${c("subjectType")} = approval_settle.subject_type and r.${c("subjectId")} = approval_settle.subject_id
9595
+ and r.${c("action")} = approval_settle.action and r.${c("status")} = 'pending'
9596
+ for update;
9597
+ if not found then
9598
+ return;
9599
+ end if;
9600
+ ${ctx.hook("before_approval_decide", [["uuid", `v_req.${c("id")}`], ["text", "approval_settle.decision"]])}
9601
+ insert into ${decisions} (${d("request")}, ${d("tenant")}, ${d("step")}, ${d("approver")}, ${d("decision")}${also("decisions", "comment")})
9602
+ values (v_req.${c("id")}, v_req.${c("tenant")}, ${stepOf("v_req")}, approval_settle.approver, ${ctx.cast("decisions", "decision", "approval_settle.decision")}${alsoValue("decisions", "comment", "approval_settle.comment")})
9603
+ on conflict do nothing;
9604
+ update ${requests} r set ${c("status")} = ${ctx.cast("requests", "status", "approval_settle.decision")}${decided}
9605
+ where r.${c("id")} = v_req.${c("id")} returning * into v_req;
9606
+ if approval_settle.decision = 'approved' then
9607
+ ${record("approval.approved", "v_req", true)}
9608
+ else
9609
+ ${record("approval.rejected", "v_req", true)}
9610
+ end if;
9611
+ perform ${fn("approval_notify")}(v_req.${c("id")}, approval_settle.decision);
9612
+ ${ctx.hook("after_approval_decide", [["uuid", `v_req.${c("id")}`], ["text", `v_req.${c("status")}`]])}
9613
+ end;
9614
+ $$;
9615
+ revoke execute on function ${fn("approval_settle")}(text, text, text, text, uuid, text) from public, anon, authenticated;
9616
+ `;
9617
+ }
9471
9618
  // src/sql/modules/approver.ts
9472
9619
  /** The `{kind}` of an AI tool call that waits for approval. */
9473
9620
  const AI_TOOL_APPROVAL = "ai-tool";
@@ -11560,6 +11707,7 @@ function build$112(ctx, layout) {
11560
11707
  const policies = approvalPolicies(ctx);
11561
11708
  validateRuns(ctx, policies);
11562
11709
  validateApprovers(ctx, policies, tenantPoliciesOn(ctx));
11710
+ if (ctx.option("policyExtraColumns") !== void 0 && !tenantPoliciesOn(ctx)) throw new TypeError("blocks.approvals.options.policyExtraColumns needs blocks.approvals.options.tenantPolicies");
11563
11711
  if (tenantPoliciesOn(ctx) && !has("policy")) throw new TypeError("blocks.approvals.options.tenantPolicies needs a policy column on the approval requests table");
11564
11712
  const tenantless = tenantlessTypes(ctx).length > 0;
11565
11713
  platformPoliciesOn(ctx);
@@ -11624,7 +11772,8 @@ function build$112(ctx, layout) {
11624
11772
  union
11625
11773
  select tm.${teams.col("members", "user")} from ${teams.table("members")} tm
11626
11774
  where tm.${teams.col("members", "team")}::text = v_approvers ->> 'team'`;
11627
- const manager = managerOf(ctx, `v_req.${c("requestedBy")}`, `v_req.${c("tenant")}`);
11775
+ const managerEmployee = has("policy") ? `(${policyOf("v_req")} ->> 'managerOf')` : void 0;
11776
+ const manager = managerOf(ctx, `v_req.${c("requestedBy")}`, `v_req.${c("tenant")}`, managerEmployee);
11628
11777
  const managerMember = manager === void 0 ? "" : `
11629
11778
  union
11630
11779
  select ${manager} where coalesce((v_approvers ->> 'manager')::boolean, false)`;
@@ -11638,7 +11787,8 @@ function build$112(ctx, layout) {
11638
11787
  or (coalesce((v_approvers ->> 'manager')::boolean, false) and ${managerMatch(ctx, {
11639
11788
  requester: `v_req.${c("requestedBy")}`,
11640
11789
  tenant: `v_req.${c("tenant")}`,
11641
- user: "v_me"
11790
+ user: "v_me",
11791
+ ...managerEmployee === void 0 ? {} : { employee: managerEmployee }
11642
11792
  })})`})`;
11643
11793
  const notFound = fail$1("APPROVAL_NOT_FOUND", "approval request not found", "P0002");
11644
11794
  const queues = [...new Set(policies.flatMap((policy) => policy.run?.kind === "queue" ? [policy.run.queue] : []))];
@@ -11662,17 +11812,21 @@ ${indent}if v_req.${c("subjectType")} = ${sqlString(subject)} then
11662
11812
  ${indent} ${body}
11663
11813
  ${indent}end if;`;
11664
11814
  const subjectId = (cast) => `v_req.${c("subjectId")}${cast}`;
11815
+ const lastApprover = `(select x.${d("approver")} from ${decisions} x where x.${d("request")} = v_req.${c("id")} and x.${d("decision")} = 'approved' order by x.${d("createdAt")} desc, x.${d("id")} desc limit 1)`;
11665
11816
  const contributedRun = contributed.map((each) => when(each.subject, each.approve({
11666
11817
  subjectId: subjectId(""),
11667
- comment: lastComment
11818
+ comment: lastComment,
11819
+ approver: lastApprover
11668
11820
  }), " ")).join("");
11669
- const linkedReject = linked.flatMap((each) => each.reject === void 0 ? [] : [when(each.subject, each.reject({
11821
+ const linkedReject = contributed.flatMap((each) => each.reject === void 0 ? [] : [when(each.subject, each.reject({
11670
11822
  subjectId: subjectId(""),
11671
- comment: "decide_approval.comment"
11823
+ comment: "decide_approval.comment",
11824
+ approver: "v_actor"
11672
11825
  }), " ")]).join("");
11673
11826
  const linkedEligible = linked.flatMap((each) => each.approvable === void 0 ? [] : [when(each.subject, `return ${each.approvable({
11674
11827
  subjectId: subjectId(""),
11675
- comment: lastComment
11828
+ comment: lastComment,
11829
+ approver: "v_me"
11676
11830
  })};`, " ")]).join("");
11677
11831
  const kit = {
11678
11832
  requests,
@@ -11694,7 +11848,18 @@ ${indent}end if;`;
11694
11848
  commentRefusal
11695
11849
  };
11696
11850
  const allHolders = allHoldersSql(kit, holders);
11697
- const notifyBody = ctx.installed("notifications") ? `
11851
+ const notificationHook = ctx.hookTarget("approval_notification");
11852
+ const enrich = `
11853
+ v_hook := to_regprocedure(${sqlString(`${notificationHook}(uuid, text, jsonb)`)});
11854
+ if v_hook is not null then
11855
+ execute format('select %s($1, $2, $3)', v_hook::oid::regproc) into v_extra
11856
+ using v_req.${c("id")}, approval_notify.kind, v_note;
11857
+ if v_extra is null then
11858
+ return;
11859
+ end if;
11860
+ v_note := v_note || (v_extra - 'data') || jsonb_build_object('data', coalesce(v_note -> 'data', '{}'::jsonb) || coalesce(v_extra -> 'data', '{}'::jsonb));
11861
+ end if;`;
11862
+ const notifyBody = ctx.installed("notifications") && ctx.flag("notifications", true) ? `
11698
11863
  select * into v_req from ${requests} r where r.${c("id")} = approval_notify.request_id;
11699
11864
  if not found${tenantless ? ` or v_req.${c("tenant")} is null` : ""} then
11700
11865
  return;
@@ -11735,7 +11900,7 @@ ${indent}end if;`;
11735
11900
  if cardinality(v_recipients) = 0 and v_permission is null then
11736
11901
  return;
11737
11902
  end if;
11738
- ${ctx.notify(`jsonb_build_object(
11903
+ v_note := jsonb_build_object(
11739
11904
  'type', 'approval.' || approval_notify.kind,
11740
11905
  'tenant', v_req.${c("tenant")},
11741
11906
  'actor', coalesce(auth.uid(), v_req.${c("requestedBy")}),
@@ -11748,7 +11913,8 @@ ${indent}end if;`;
11748
11913
  'include_actor', approval_notify.kind in ('approved', 'rejected', 'expired'),
11749
11914
  'key', 'approval.' || approval_notify.kind || ':' || v_req.${c("id")}::text || ':' || ${stepOf("v_req")}::text || ':' || extract(epoch from now())::bigint::text,
11750
11915
  'data', jsonb_build_object('requestId', v_req.${c("id")}, 'action', v_req.${c("action")}, 'step', ${stepOf("v_req")})
11751
- )`)}` : `
11916
+ );${enrich}
11917
+ ${ctx.notify("v_note")}` : `
11752
11918
  null;`;
11753
11919
  const column = (table, logical, definition) => ctx.has(table, logical) ? `\n ${definition(ctx.col(table, logical))},` : "";
11754
11920
  const tables = ctx.manages ? `create table if not exists ${requests} (
@@ -11884,7 +12050,7 @@ declare
11884
12050
  v_approvers jsonb;
11885
12051
  v_permission text;
11886
12052
  v_recipients uuid[] := '{}';
11887
- v_claims text;
12053
+ v_claims text;${notifyBody.includes("v_note") ? "\n v_note jsonb;\n v_hook regprocedure;\n v_extra jsonb;" : ""}
11888
12054
  begin${notifyBody}
11889
12055
  end;
11890
12056
  $$;
@@ -11911,8 +12077,10 @@ $$;
11911
12077
  revoke execute on function ${fn("approval_finalize")}(uuid) from public, anon, authenticated;
11912
12078
 
11913
12079
  -- Files a request under an explicit policy snapshot. request_approval and
11914
- -- the access-requests module call it after their own checks.
11915
- create or replace function ${fn("open_approval")}(tenant ${ctx.idType}, subject_type text, subject_id text, action text, policy jsonb, reason text, payload jsonb)
12080
+ -- the access-requests module call it after their own checks. requested_by
12081
+ -- defaults to the caller.
12082
+ drop function if exists ${fn("open_approval")}(${ctx.idType}, text, text, text, jsonb, text, jsonb);
12083
+ create or replace function ${fn("open_approval")}(tenant ${ctx.idType}, subject_type text, subject_id text, action text, policy jsonb, reason text, payload jsonb, requested_by uuid default null)
11916
12084
  returns jsonb
11917
12085
  language plpgsql
11918
12086
  security definer
@@ -11922,6 +12090,7 @@ as $$
11922
12090
  declare
11923
12091
  v_req ${requests}%rowtype;
11924
12092
  v_policy jsonb := open_approval.policy;
12093
+ v_requester uuid := coalesce(open_approval.requested_by, auth.uid());
11925
12094
  begin
11926
12095
  ${ctx.hook("before_approval_request", [
11927
12096
  [ctx.idType, "open_approval.tenant"],
@@ -11930,7 +12099,7 @@ begin
11930
12099
  ["text", "open_approval.action"]
11931
12100
  ])}${openRefusals}${allHolders}
11932
12101
  insert into ${requests} (${c("tenant")}, ${c("subjectType")}, ${c("subjectId")}, ${c("action")}${also("requests", "policy")}, ${c("requestedBy")}${also("requests", "reason")}${also("requests", "payload")}${also("requests", "expiresAt")})
11933
- values (open_approval.tenant, open_approval.subject_type, open_approval.subject_id, open_approval.action${alsoValue("requests", "policy", "v_policy")}, auth.uid()${alsoValue("requests", "reason", "open_approval.reason")}${alsoValue("requests", "payload", "coalesce(open_approval.payload, '{}'::jsonb)")}${has("expiresAt") ? `,\n case when open_approval.policy ->> 'expiresIn' is not null then now() + (open_approval.policy ->> 'expiresIn')::interval end` : ""})
12102
+ values (open_approval.tenant, open_approval.subject_type, open_approval.subject_id, open_approval.action${alsoValue("requests", "policy", "v_policy")}, v_requester${alsoValue("requests", "reason", "open_approval.reason")}${alsoValue("requests", "payload", "coalesce(open_approval.payload, '{}'::jsonb)")}${has("expiresAt") ? `,\n case when open_approval.policy ->> 'expiresIn' is not null then now() + (open_approval.policy ->> 'expiresIn')::interval end` : ""})
11934
12103
  on conflict (${c("subjectType")}, ${c("subjectId")}, ${c("action")}) where ${c("status")} = 'pending' do nothing
11935
12104
  returning * into v_req;
11936
12105
  if not found then
@@ -11942,45 +12111,8 @@ begin
11942
12111
  return ${json("v_req")};
11943
12112
  end;
11944
12113
  $$;
11945
- revoke execute on function ${fn("open_approval")}(${ctx.idType}, text, text, text, jsonb, text, jsonb) from public, anon, authenticated;
11946
- ${linked.length === 0 ? "" : `
11947
- -- Closes the pending request for a subject that its own module decided
11948
- -- (decide_ai_tool_approval, approve_support_request) without running the
11949
- -- module again. A request that is no longer pending is left as it is.
11950
- create or replace function ${fn("approval_settle")}(subject_type text, subject_id text, action text, decision text, approver uuid, comment text default null)
11951
- returns void
11952
- language plpgsql
11953
- security definer
11954
- set search_path = ''
11955
- as $$
11956
- #variable_conflict use_column
11957
- declare
11958
- v_req ${requests}%rowtype;
11959
- begin
11960
- select * into v_req from ${requests} r
11961
- where r.${c("subjectType")} = approval_settle.subject_type and r.${c("subjectId")} = approval_settle.subject_id
11962
- and r.${c("action")} = approval_settle.action and r.${c("status")} = 'pending'
11963
- for update;
11964
- if not found then
11965
- return;
11966
- end if;
11967
- ${ctx.hook("before_approval_decide", [["uuid", `v_req.${c("id")}`], ["text", "approval_settle.decision"]])}
11968
- insert into ${decisions} (${d("request")}, ${d("tenant")}, ${d("step")}, ${d("approver")}, ${d("decision")}${also("decisions", "comment")})
11969
- values (v_req.${c("id")}, v_req.${c("tenant")}, ${stepOf("v_req")}, approval_settle.approver, ${ctx.cast("decisions", "decision", "approval_settle.decision")}${alsoValue("decisions", "comment", "approval_settle.comment")})
11970
- on conflict do nothing;
11971
- update ${requests} r set ${c("status")} = ${ctx.cast("requests", "status", "approval_settle.decision")}${decided}
11972
- where r.${c("id")} = v_req.${c("id")} returning * into v_req;
11973
- if approval_settle.decision = 'approved' then
11974
- ${record("approval.approved", "v_req", true)}
11975
- else
11976
- ${record("approval.rejected", "v_req", true)}
11977
- end if;
11978
- perform ${fn("approval_notify")}(v_req.${c("id")}, approval_settle.decision);
11979
- ${ctx.hook("after_approval_decide", [["uuid", `v_req.${c("id")}`], ["text", `v_req.${c("status")}`]])}
11980
- end;
11981
- $$;
11982
- revoke execute on function ${fn("approval_settle")}(text, text, text, text, uuid, text) from public, anon, authenticated;
11983
- `}
12114
+ revoke execute on function ${fn("open_approval")}(${ctx.idType}, text, text, text, jsonb, text, jsonb, uuid) from public, anon, authenticated;
12115
+ ${linked.length === 0 ? "" : settleSql(ctx, kit)}
11984
12116
  ${approvalsTenantSql(ctx, {
11985
12117
  json,
11986
12118
  record,
@@ -27799,7 +27931,7 @@ function byEmployee(ctx) {
27799
27931
  function timeOwner(ctx, statusMode) {
27800
27932
  const fn = (name) => ctx.fn(name);
27801
27933
  const employeeMode = byEmployee(ctx);
27802
- if (employeeMode && !statusMode) throw new TypeError(`${WHERE$14}.owner "employee" keeps timesheets in a status column, so it needs ${WHERE$14}.approvals: false`);
27934
+ if (employeeMode && !statusMode) throw new TypeError(`${WHERE$14}.owner "employee" keeps timesheets in a status column`);
27803
27935
  if (employeeMode && !ctx.installed("employees")) throw new TypeError(`${WHERE$14}.owner "employee" needs the employees block`);
27804
27936
  if (employeeMode && (!ctx.has("entries", "employee") || !ctx.has("timesheets", "employee"))) throw new TypeError(`${WHERE$14}.owner "employee" keeps the employee on every row, so columns.entries.employee and columns.timesheets.employee can't be null`);
27805
27937
  if (!employeeMode && !ctx.has("timesheets", "user")) throw new TypeError(`blocks.time-tracking.columns.timesheets.user can be null only with ${WHERE$14}.owner "employee"`);
@@ -66552,6 +66684,23 @@ const EXPENSE_TABLE = {
66552
66684
  ],
66553
66685
  typed: ["status"]
66554
66686
  };
66687
+ /** The subject type of an expense the approvals block decides. */
66688
+ const EXPENSE_SUBJECT = "expense";
66689
+ /**
66690
+ * Whether each standalone expense goes through the approvals block:
66691
+ * `options.standaloneApprovals`, which needs `tables.reports: null`.
66692
+ */
66693
+ function standaloneApprovals(ctx) {
66694
+ const on = ctx.flag("standaloneApprovals", false);
66695
+ if (on && !expensesStandalone(ctx)) throw new TypeError("blocks.expenses.options.standaloneApprovals needs tables.reports: null; reports go through approvals already");
66696
+ return on;
66697
+ }
66698
+ /** `options.policy`, or one step for holders of the approve permission. */
66699
+ function standalonePolicy(ctx) {
66700
+ const policy = policyOf(EXPENSE_SUBJECT, "approve", ctx.option("policy") ?? { steps: [{ approvers: { permission: ctx.permissionKey("approve", OPERATIONS["expenses.approve"]) } }] }, "blocks.expenses.options.policy");
66701
+ if (policy.run !== void 0) throw new TypeError("blocks.expenses.options.policy.run is not allowed; the final approval approves the expense");
66702
+ return policySnapshot(policy);
66703
+ }
66555
66704
  function expensesStandalone(ctx) {
66556
66705
  const reports = ctx.config.tables["reports"] === null;
66557
66706
  if (reports !== (ctx.config.tables["lines"] === null)) throw new TypeError("blocks.expenses.tables.reports and lines map to null together: without reports, each expense is one row of tables.expenses");
@@ -66696,6 +66845,21 @@ function expenseStandaloneSql(ctx) {
66696
66845
  const extra = extraFieldsArg(extras);
66697
66846
  const statusColumn = has("status");
66698
66847
  const company = ctx.flag("companyExpenses", false);
66848
+ const linked = standaloneApprovals(ctx) ? ctx.of("approvals") : void 0;
66849
+ if (linked?.mode === "custom") throw new TypeError("blocks.expenses needs the approvals tables; approvals can't be in custom mode");
66850
+ const ar = linked?.table("requests") ?? "";
66851
+ const a = (column) => linked?.col("requests", column) ?? "";
66852
+ const pending = `exists (select 1 from ${ar} x where x.${a("subjectType")} = ${sqlString(EXPENSE_SUBJECT)} and x.${a("subjectId")} = v_row.${e("id")}::text and x.${a("status")} = 'pending')`;
66853
+ const openApproval = linked === void 0 ? "" : `
66854
+ perform ${linked.fn("open_approval")}(
66855
+ v_row.${e("tenant")}, ${sqlString(EXPENSE_SUBJECT)}, v_row.${e("id")}::text, 'approve',
66856
+ ${sqlString(standalonePolicy(ctx))}::jsonb${employee ? ` || jsonb_build_object('managerOf', v_row.${e("employee")}::text)` : ""}, null,
66857
+ jsonb_build_object('userId', ${owner.requester("v_row")}${employee ? `, 'employeeId', v_row.${e("employee")}` : ""}, 'amount', v_row.${e("amount")}::text, 'currency', v_row.${e("currency")}, 'spentOn', v_row.${e("spentOn")}),
66858
+ ${owner.requester("v_row")}
66859
+ );`;
66860
+ const cancelApproval = linked === void 0 ? "" : `
66861
+ update ${ar} x set ${a("status")} = 'cancelled'${linked.has("requests", "decidedAt") ? `, ${a("decidedAt")} = now()` : ""}
66862
+ where x.${a("subjectType")} = ${sqlString(EXPENSE_SUBJECT)} and x.${a("subjectId")} = v_row.${e("id")}::text and x.${a("status")} = 'pending';`;
66699
66863
  const inserted = insertExtraColumns(table, extras, "coalesce(create_expense.fields, '{}'::jsonb)");
66700
66864
  if (!statusColumn && !(has("approvedAt") && has("rejectedAt"))) throw new TypeError("blocks.expenses.columns.expenses needs a status column, or approvedAt and rejectedAt columns, to keep an expense's state");
66701
66865
  const forbidden = (message) => fail$1("EXPENSES_FORBIDDEN", message);
@@ -66884,7 +67048,7 @@ declare
66884
67048
  begin${load("submit_expense.expense_id")}${ownerOrManager(updateOthers)}${editable}
66885
67049
  update ${table} x set ${e("submittedAt")} = now()${setStatus("submitted")}${set("rejectedAt", "null")}${set("approvedAt", "null")}, ${e("updatedAt")} = now()
66886
67050
  where x.${e("id")} = v_row.${e("id")}
66887
- returning * into v_row;
67051
+ returning * into v_row;${openApproval}
66888
67052
  ${record("expense.submitted", "submitted an expense")}
66889
67053
  return ${json("v_row")};
66890
67054
  end;
@@ -66905,7 +67069,7 @@ begin${load("withdraw_expense.expense_id")}${ownerOrManager(withdrawApproved ? w
66905
67069
  end if;
66906
67070
  update ${table} x set ${e("submittedAt")} = null${setStatus("draft")}${withdrawApproved ? `${set("approvedAt", "null")}${set("decidedBy", "null")}${set("decidedAt", "null")}` : ""}, ${e("updatedAt")} = now()
66907
67071
  where x.${e("id")} = v_row.${e("id")}
66908
- returning * into v_row;
67072
+ returning * into v_row;${cancelApproval}
66909
67073
  ${record("expense.withdrawn", "withdrew an expense")}
66910
67074
  return ${json("v_row")};
66911
67075
  end;
@@ -66930,6 +67094,7 @@ begin${load("delete_expense.expense_id")}${deleteSubmitted === void 0 ? ownerOrM
66930
67094
  if ${status("v_row")} <> 'draft'${deleteSubmitted === void 0 ? "" : ` and ${status("v_row")} not in ('submitted', 'approved')`} then
66931
67095
  ${fail$1("EXPENSE_LOCKED", deleteSubmitted === void 0 ? "only a draft expense is deleted" : "only a draft, submitted or approved expense is deleted", "55000")}
66932
67096
  end if;
67097
+ ${cancelApproval}
66933
67098
  delete from ${table} x where x.${e("id")} = v_row.${e("id")};
66934
67099
  ${record("expense.deleted", "deleted an expense")}
66935
67100
  return true;
@@ -66957,7 +67122,10 @@ begin${load("decide_expense.expense_id")}
66957
67122
  end if;
66958
67123
  if ${status("v_row")} <> 'submitted' then
66959
67124
  ${fail$1("EXPENSE_LOCKED", "only a submitted expense is decided", "55000")}
66960
- end if;
67125
+ end if;${linked === void 0 ? "" : `
67126
+ if ${pending} then
67127
+ ${fail$1("EXPENSE_IN_APPROVAL", "this expense is decided through its approval request", "55000")}
67128
+ end if;`}
66961
67129
  if decide_expense.approved is null then
66962
67130
  ${invalid("approved must be true or false")}
66963
67131
  end if;${unsupported("decisionNote", "nullif(trim(decide_expense.note), '')")}
@@ -66976,7 +67144,37 @@ begin${load("decide_expense.expense_id")}
66976
67144
  end;
66977
67145
  $$;
66978
67146
  ${userGrant(`${fn("decide_expense")}(uuid, boolean, text, uuid)`)}
66979
-
67147
+ ${linked === void 0 ? "" : `
67148
+ -- Applies the final decision of an expense's approval request: approvals
67149
+ -- calls it, with the user who decided. It isn't granted to anyone.
67150
+ create or replace function ${fn("expense_approval_decided")}(expense_id uuid, approved boolean, note text, decided_by uuid)
67151
+ returns void
67152
+ language plpgsql
67153
+ security definer
67154
+ set search_path = ''
67155
+ as $$
67156
+ declare
67157
+ v_row ${table}%rowtype;
67158
+ begin
67159
+ select * into v_row from ${table} x where x.${e("id")} = expense_approval_decided.expense_id for update;
67160
+ if not found or ${status("v_row")} <> 'submitted' then
67161
+ return;
67162
+ end if;
67163
+ if expense_approval_decided.approved then
67164
+ update ${table} x set ${e("updatedAt")} = now()${setStatus("approved")}${set("approvedAt", "now()")}${set("decidedBy", "expense_approval_decided.decided_by")}${set("decidedAt", "now()")}${set("decisionNote", "nullif(trim(expense_approval_decided.note), '')")}
67165
+ where x.${e("id")} = v_row.${e("id")}
67166
+ returning * into v_row;
67167
+ ${record("expense.approved", "approved an expense")}
67168
+ else
67169
+ update ${table} x set ${e("updatedAt")} = now()${setStatus("rejected")}${set("rejectedAt", "now()")}${set("decidedBy", "expense_approval_decided.decided_by")}${set("decidedAt", "now()")}${set("decisionNote", "nullif(trim(expense_approval_decided.note), '')")}
67170
+ where x.${e("id")} = v_row.${e("id")}
67171
+ returning * into v_row;
67172
+ ${record("expense.rejected", "rejected an expense")}
67173
+ end if;
67174
+ end;
67175
+ $$;
67176
+ revoke execute on function ${fn("expense_approval_decided")}(uuid, boolean, text, uuid) from public, anon, authenticated;
67177
+ `}
66980
67178
  create or replace function ${fn("reimburse_expense")}(expense_id uuid, reference text default null)
66981
67179
  returns jsonb
66982
67180
  language plpgsql
@@ -67795,7 +67993,9 @@ const NAMES$72 = {
67795
67993
  "approvals",
67796
67994
  "owner",
67797
67995
  "companyExpenses",
67798
- "withdrawApproved"
67996
+ "withdrawApproved",
67997
+ "standaloneApprovals",
67998
+ "policy"
67799
67999
  ],
67800
68000
  tables: {
67801
68001
  categories: {
@@ -68110,7 +68310,12 @@ function contract$63(ctx) {
68110
68310
  }
68111
68311
  ];
68112
68312
  }
68113
- const CONTRIBUTES$10 = { approvals: (own) => expenseApprovals(own) ? [{
68313
+ const CONTRIBUTES$8 = { approvals: (own) => standaloneApprovals(own) ? [{
68314
+ subject: EXPENSE_SUBJECT,
68315
+ access: "declared",
68316
+ approve: ({ subjectId, comment, approver }) => `perform ${own.fn("expense_approval_decided")}(${subjectId}::uuid, true, ${comment}, ${approver});`,
68317
+ reject: ({ subjectId, comment, approver }) => `perform ${own.fn("expense_approval_decided")}(${subjectId}::uuid, false, ${comment}, ${approver});`
68318
+ }] : expenseApprovals(own) ? [{
68114
68319
  subject: EXPENSE_REPORT_SUBJECT,
68115
68320
  access: "declared",
68116
68321
  approve: ({ subjectId }) => `perform ${own.fn("approve_expense_report")}(${subjectId}::uuid);`
@@ -68122,7 +68327,7 @@ const REQUIRES$4 = [
68122
68327
  "ledger"
68123
68328
  ];
68124
68329
  const EXPENSES = {
68125
- contributes: CONTRIBUTES$10,
68330
+ contributes: CONTRIBUTES$8,
68126
68331
  name: "expenses",
68127
68332
  scopes: ["tenant"],
68128
68333
  title: "Expenses",
@@ -68130,7 +68335,11 @@ const EXPENSES = {
68130
68335
  requires: [...REQUIRES$4],
68131
68336
  dependencies: (layout) => {
68132
68337
  const expenses = layout.modules?.["expenses"];
68133
- if (expenses?.tables?.["reports"] === null) return ["memberships", "permissions"];
68338
+ if (expenses?.tables?.["reports"] === null) return expenses.options?.["standaloneApprovals"] === true ? [
68339
+ "memberships",
68340
+ "permissions",
68341
+ "approvals"
68342
+ ] : ["memberships", "permissions"];
68134
68343
  return expenses?.options?.["approvals"] === false ? REQUIRES$4.filter((name) => name !== "approvals") : [...REQUIRES$4];
68135
68344
  },
68136
68345
  integrates: [
@@ -86620,11 +86829,13 @@ ${userGrant(`${fn("invoice_from_quote")}(uuid, integer)`)}
86620
86829
  const writeOffReason = typeof ctx.config.columns["invoices"]?.["writeOffReason"] === "string" && ctx.has("invoices", "writeOffReason");
86621
86830
  const addCharge = charges ? `
86622
86831
  ${chargeFields.drop(fn("add_invoice_charge"), "uuid, bigint, text, text")}
86832
+ drop function if exists ${fn("add_invoice_charge")}(uuid, bigint, text, text${chargeFields.type});
86623
86833
  -- Adds a charge on top of an issued invoice's total, such as collection
86624
86834
  -- costs or a late fee, in the invoice's currency. It raises the balance, so
86625
86835
  -- a paid invoice is open again until the charge is paid too. fields: the
86626
- -- charge's extra columns (options.chargeExtraColumns).
86627
- create or replace function ${fn("add_invoice_charge")}(invoice uuid, amount bigint, currency text, description text${chargeFields.param})
86836
+ -- charge's extra columns (options.chargeExtraColumns). actor: who added it,
86837
+ -- for the state machine's history.
86838
+ create or replace function ${fn("add_invoice_charge")}(invoice uuid, amount bigint, currency text, description text${chargeFields.param}, actor jsonb default null)
86628
86839
  returns jsonb
86629
86840
  language plpgsql
86630
86841
  security definer
@@ -86651,6 +86862,7 @@ begin
86651
86862
  if upper(add_invoice_charge.currency) is distinct from v_row.${i("currency")} then
86652
86863
  ${fail$1("INVOICE_CURRENCY_MISMATCH", "a charge must be in the invoice's currency", "22023")}
86653
86864
  end if;
86865
+ ${transitionActorSql("add_invoice_charge.actor", "INVOICE_ACTOR_INVALID")}
86654
86866
  insert into ${t("charges")} (${chargeColumns.join(", ")}${chargeExtras.columns})
86655
86867
  values (${chargeValues.join(", ")}${chargeExtras.values})
86656
86868
  returning ${ch("id")} into v_charge;${settle("v_row")}
@@ -86658,9 +86870,10 @@ begin
86658
86870
  return ${row("v_row")};
86659
86871
  end;
86660
86872
  $$;
86661
- ${userGrant(`${fn("add_invoice_charge")}(uuid, bigint, text, text${chargeFields.type})`)}
86873
+ ${userGrant(`${fn("add_invoice_charge")}(uuid, bigint, text, text${chargeFields.type}, jsonb)`)}
86662
86874
 
86663
- create or replace function ${fn("remove_invoice_charge")}(charge uuid)
86875
+ drop function if exists ${fn("remove_invoice_charge")}(uuid);
86876
+ create or replace function ${fn("remove_invoice_charge")}(charge uuid, actor jsonb default null)
86664
86877
  returns jsonb
86665
86878
  language plpgsql
86666
86879
  security definer
@@ -86683,13 +86896,14 @@ begin
86683
86896
  ], true)} then
86684
86897
  ${fail$1("INVOICE_NOT_CHARGEABLE", "only an issued invoice changes its charges", "55000")}
86685
86898
  end if;
86899
+ ${transitionActorSql("remove_invoice_charge.actor", "INVOICE_ACTOR_INVALID")}
86686
86900
  delete from ${t("charges")} c where c.${ch("id")} = remove_invoice_charge.charge
86687
86901
  returning c.${ch("amount")} into v_amount;${settle("v_row")}
86688
86902
  ${record("invoice.charge_removed", "v_row", `, 'chargeId', remove_invoice_charge.charge, 'amount', v_amount::text, 'balance', ${balance("v_row")}::text`, true)}
86689
86903
  return ${row("v_row")};
86690
86904
  end;
86691
86905
  $$;
86692
- ${userGrant(`${fn("remove_invoice_charge")}(uuid)`)}
86906
+ ${userGrant(`${fn("remove_invoice_charge")}(uuid, jsonb)`)}
86693
86907
  ` : "";
86694
86908
  const kindTable = (kind) => `(select * from ${t("invoices")} k where ${kd(`k.${i("kind")}`, [kind])})`;
86695
86909
  return `
@@ -87002,8 +87216,10 @@ $$;
87002
87216
  ${userGrant(`${fn("credit_invoice")}(uuid, jsonb, text)`)}
87003
87217
 
87004
87218
  -- Voids an invoice without payments: a draft, or an issued one sent in
87005
- -- error. Its number stays taken. Needs invoices.manage.
87006
- create or replace function ${fn("void_invoice")}(invoice uuid, reason text)
87219
+ -- error. Its number stays taken. Needs invoices.manage. The reason and actor
87220
+ -- go to the state machine's history.
87221
+ drop function if exists ${fn("void_invoice")}(uuid, text);
87222
+ create or replace function ${fn("void_invoice")}(invoice uuid, reason text, actor jsonb default null)
87007
87223
  returns jsonb
87008
87224
  language plpgsql
87009
87225
  security definer
@@ -87019,18 +87235,23 @@ begin
87019
87235
  if ${st(`v_row.${i("status")}`, ["draft", "issued"], true)} or v_row.${i("paidTotal")} <> 0 or v_row.${i("creditedTotal")} <> 0 then
87020
87236
  ${fail$1("INVOICE_NOT_VOIDABLE", "an invoice with payments or credits is credited, not voided", "55000")}
87021
87237
  end if;
87238
+ ${transitionActorSql("void_invoice.actor", "INVOICE_ACTOR_INVALID")}
87239
+ ${transitionReasonSql("void_invoice.reason")}
87022
87240
  update ${t("invoices")} x set ${i("status")} = ${ctx.value("invoices", "status", "void")}, ${i("voidedAt")} = now(),
87023
87241
  ${has("voidReason") ? `${i("voidReason")} = nullif(trim(void_invoice.reason), ''), ` : ""}${i("updatedAt")} = now()
87024
87242
  where x.${i("id")} = v_row.${i("id")} returning * into v_row;
87243
+ ${transitionReasonSql()}
87025
87244
  ${record("invoice.voided", "v_row", `, 'reason', ${has("voidReason") ? `v_row.${i("voidReason")}` : "nullif(trim(void_invoice.reason), '')"}`, true)}
87026
87245
  return ${row("v_row")};
87027
87246
  end;
87028
87247
  $$;
87029
- ${userGrant(`${fn("void_invoice")}(uuid, text)`)}
87248
+ ${userGrant(`${fn("void_invoice")}(uuid, text, jsonb)`)}
87030
87249
 
87031
- -- Writes an open invoice off as uncollectible. Needs invoices.manage.
87250
+ -- Writes an open invoice off as uncollectible. Needs invoices.manage. The
87251
+ -- reason and actor go to the state machine's history.
87032
87252
  drop function if exists ${fn("write_off_invoice")}(uuid);
87033
- create or replace function ${fn("write_off_invoice")}(invoice uuid, reason text default null)
87253
+ drop function if exists ${fn("write_off_invoice")}(uuid, text);
87254
+ create or replace function ${fn("write_off_invoice")}(invoice uuid, reason text default null, actor jsonb default null)
87034
87255
  returns jsonb
87035
87256
  language plpgsql
87036
87257
  security definer
@@ -87039,19 +87260,25 @@ as $$
87039
87260
  declare
87040
87261
  v_row ${t("invoices")};
87041
87262
  begin
87263
+ ${transitionActorSql("write_off_invoice.actor", "INVOICE_ACTOR_INVALID")}
87264
+ ${transitionReasonSql("write_off_invoice.reason")}
87042
87265
  update ${t("invoices")} x set ${i("status")} = ${ctx.value("invoices", "status", "uncollectible")}, ${writeOffReason ? `${i("writeOffReason")} = nullif(trim(write_off_invoice.reason), ''), ` : ""}${i("updatedAt")} = now()
87043
87266
  where x.${i("id")} = write_off_invoice.invoice and ${can("x", n.writeOff)} and ${st(`x.${i("status")}`, ["issued", "partially_paid"])}
87044
87267
  returning * into v_row;
87045
87268
  if v_row.${i("id")} is null then
87046
87269
  ${fail$1("INVOICE_NOT_OPEN", "only an open invoice you can manage is written off", "55000")}
87047
87270
  end if;
87271
+ ${transitionReasonSql()}
87048
87272
  ${record("invoice.uncollected", "v_row", `, 'balance', ${balance("v_row")}::text, 'reason', nullif(trim(write_off_invoice.reason), '')`, true)}
87049
87273
  return ${row("v_row")};
87050
87274
  end;
87051
87275
  $$;
87052
- ${userGrant(`${fn("write_off_invoice")}(uuid, text)`)}
87276
+ ${userGrant(`${fn("write_off_invoice")}(uuid, text, jsonb)`)}
87053
87277
 
87054
- create or replace function ${fn("reverse_invoice_payment")}(payment uuid, reason text default null)
87278
+ -- Reverses a recorded payment. The reason and actor go to the state machine's
87279
+ -- history.
87280
+ drop function if exists ${fn("reverse_invoice_payment")}(uuid, text);
87281
+ create or replace function ${fn("reverse_invoice_payment")}(payment uuid, reason text default null, actor jsonb default null)
87055
87282
  returns jsonb
87056
87283
  language plpgsql
87057
87284
  security definer
@@ -87076,14 +87303,17 @@ begin
87076
87303
  or exists (select 1 from ${ledger.transactions} y where y.${ledger.tx("reverses")} = reverse_invoice_payment.payment) then
87077
87304
  ${fail$1("INVOICE_PAYMENT_REVERSED", "this payment is a reversal or is already reversed", "55000")}
87078
87305
  end if;
87306
+ ${transitionActorSql("reverse_invoice_payment.actor", "INVOICE_ACTOR_INVALID")}
87307
+ ${transitionReasonSql("reverse_invoice_payment.reason")}
87079
87308
  v_amount := ${ledger.paidTotal("v_row")};
87080
87309
  v_reversal := ${ledger.reverse("v_row", "reverse_invoice_payment.payment", "nullif(trim(reverse_invoice_payment.reason), '')")};
87081
87310
  v_amount := v_amount - ${ledger.paidTotal("v_row")};${settle("v_row")}
87311
+ ${transitionReasonSql()}
87082
87312
  ${record("invoice.payment_reversed", "v_row", `, 'paymentId', reverse_invoice_payment.payment, 'reversalId', v_reversal, 'amount', v_amount::text, 'balance', ${balance("v_row")}::text, 'reason', nullif(trim(reverse_invoice_payment.reason), '')`, true)}
87083
87313
  return ${row("v_row")};
87084
87314
  end;
87085
87315
  $$;
87086
- ${userGrant(`${fn("reverse_invoice_payment")}(uuid, text)`)}
87316
+ ${userGrant(`${fn("reverse_invoice_payment")}(uuid, text, jsonb)`)}
87087
87317
  ${addCharge}
87088
87318
  -- What a tenant is owed in one currency on as_of, by days past due:
87089
87319
  -- not yet due, 1 to 30, 31 to 60, 61 to 90 and over 90. Amounts are text.
@@ -87533,17 +87763,29 @@ function contract$48(ctx) {
87533
87763
  },
87534
87764
  {
87535
87765
  name: "void_invoice",
87536
- args: ["uuid", "text"],
87766
+ args: [
87767
+ "uuid",
87768
+ "text",
87769
+ "jsonb"
87770
+ ],
87537
87771
  returns: "jsonb"
87538
87772
  },
87539
87773
  {
87540
87774
  name: "write_off_invoice",
87541
- args: ["uuid", "text"],
87775
+ args: [
87776
+ "uuid",
87777
+ "text",
87778
+ "jsonb"
87779
+ ],
87542
87780
  returns: "jsonb"
87543
87781
  },
87544
87782
  {
87545
87783
  name: "reverse_invoice_payment",
87546
- args: ["uuid", "text"],
87784
+ args: [
87785
+ "uuid",
87786
+ "text",
87787
+ "jsonb"
87788
+ ],
87547
87789
  returns: "jsonb"
87548
87790
  },
87549
87791
  ...ctx.hasTable("charges") ? [{
@@ -87553,12 +87795,13 @@ function contract$48(ctx) {
87553
87795
  "bigint",
87554
87796
  "text",
87555
87797
  "text",
87556
- ...extraFieldsArg(chargeExtraColumns(ctx)).contract
87798
+ ...extraFieldsArg(chargeExtraColumns(ctx)).contract,
87799
+ "jsonb"
87557
87800
  ],
87558
87801
  returns: "jsonb"
87559
87802
  }, {
87560
87803
  name: "remove_invoice_charge",
87561
- args: ["uuid"],
87804
+ args: ["uuid", "jsonb"],
87562
87805
  returns: "jsonb"
87563
87806
  }] : [],
87564
87807
  {
@@ -90199,6 +90442,17 @@ function leavePolicy(ctx) {
90199
90442
  return policySnapshot(policy);
90200
90443
  }
90201
90444
  /**
90445
+ * `options.approvalOwner`: `"employee"` makes the request's employee the
90446
+ * approval's requester and points a manager step at their manager; the default
90447
+ * `"filer"` keeps the user who filed it. Needs `owner: "employee"`.
90448
+ */
90449
+ function leaveApprovalOwner(ctx, employee) {
90450
+ const value = ctx.text("approvalOwner", "filer");
90451
+ if (value !== "filer" && value !== "employee") throw new TypeError(`${WHERE$8}.approvalOwner must be "filer" or "employee"`);
90452
+ if (value === "employee" && !employee) throw new TypeError(`${WHERE$8}.approvalOwner "employee" needs ${WHERE$8}.owner "employee"`);
90453
+ return value;
90454
+ }
90455
+ /**
90202
90456
  * Whether requests keep their decision themselves instead of in the approvals
90203
90457
  * block: `options.approvals: false`, or no approval column.
90204
90458
  */
@@ -90294,6 +90548,15 @@ function leaveContract(ctx) {
90294
90548
  }] : []
90295
90549
  ];
90296
90550
  }
90551
+ /** The final approval of a leave request books it. */
90552
+ const LEAVE_CONTRIBUTES = {
90553
+ "share-links": (own) => [leaveFeedSubject(own), ...leaveTeamFeedSubject(own)],
90554
+ approvals: (own) => leaveStatusMode(own) ? [] : [{
90555
+ subject: LEAVE_REQUEST_SUBJECT,
90556
+ access: "declared",
90557
+ approve: ({ subjectId }) => `perform ${own.fn("approve_leave_request")}(${subjectId}::uuid);`
90558
+ }]
90559
+ };
90297
90560
  // src/sql/modules/leave-ledger.ts
90298
90561
  /** Leave amounts are numeric(8, 2); ledger amounts are hundredths. */
90299
90562
  const SCALE = 100;
@@ -90762,7 +91025,8 @@ const LEAVE_NAMES = {
90762
91025
  "feed",
90763
91026
  "approvals",
90764
91027
  "owner",
90765
- "reapprove"
91028
+ "reapprove",
91029
+ "approvalOwner"
90766
91030
  ],
90767
91031
  tables: {
90768
91032
  types: {
@@ -91164,13 +91428,14 @@ ${parts ? ` and ${existing.first} <= ${halfDays(starts, ends, "v_start", "v
91164
91428
  ` : ""} ) then
91165
91429
  ${fail$1("LEAVE_OVERLAP", "this overlaps another leave request", "23P01")}
91166
91430
  end if;`;
91431
+ const byEmployee = leaveApprovalOwner(ctx, owner.employee) === "employee";
91167
91432
  const openApproval = (tenant) => {
91168
91433
  if (approvals === void 0) return "";
91169
91434
  const open = `
91170
91435
  v_request := ${approvals.fn("open_approval")}(
91171
91436
  ${tenant}, ${sqlString(LEAVE_REQUEST_SUBJECT)}, v_row.${q("id")}::text, 'approve',
91172
- ${sqlString(policy)}::jsonb, ${or("requests", "v_row", "note")},
91173
- jsonb_build_object('userId', ${owner.employee ? "v_user, 'employeeId', v_owner" : "v_me"}, 'typeId', v_type.${ty("id")}, 'type', v_type.${ty("name")}, 'startsOn', v_row.${q("startsOn")}, 'endsOn', v_row.${q("endsOn")}, 'amount', v_amount::text, 'unit', v_type.${ty("unit")})
91437
+ ${sqlString(policy)}::jsonb${byEmployee ? " || jsonb_build_object('managerOf', v_owner::text)" : ""}, ${or("requests", "v_row", "note")},
91438
+ jsonb_build_object('userId', ${owner.employee ? "v_user, 'employeeId', v_owner" : "v_me"}, 'typeId', v_type.${ty("id")}, 'type', v_type.${ty("name")}, 'startsOn', v_row.${q("startsOn")}, 'endsOn', v_row.${q("endsOn")}, 'amount', v_amount::text, 'unit', v_type.${ty("unit")})${byEmployee ? ",\n v_user" : ""}
91174
91439
  );
91175
91440
  update ${requests} x set ${q("approval")} = (v_request ->> 'id')::uuid
91176
91441
  where x.${q("id")} = v_row.${q("id")}
@@ -91618,14 +91883,6 @@ ${userGrant(`${fn("list_leave_requests")}(${listBase}${owner.employee ? ", uuid"
91618
91883
 
91619
91884
  `;
91620
91885
  }
91621
- const CONTRIBUTES$7 = {
91622
- "share-links": (own) => [leaveFeedSubject(own), ...leaveTeamFeedSubject(own)],
91623
- approvals: (own) => leaveStatusMode(own) ? [] : [{
91624
- subject: LEAVE_REQUEST_SUBJECT,
91625
- access: "declared",
91626
- approve: ({ subjectId }) => `perform ${own.fn("approve_leave_request")}(${subjectId}::uuid);`
91627
- }]
91628
- };
91629
91886
  const REQUIRES$2 = [
91630
91887
  "memberships",
91631
91888
  "permissions",
@@ -91633,7 +91890,7 @@ const REQUIRES$2 = [
91633
91890
  "ledger"
91634
91891
  ];
91635
91892
  const LEAVE = {
91636
- contributes: CONTRIBUTES$7,
91893
+ contributes: LEAVE_CONTRIBUTES,
91637
91894
  internal: [
91638
91895
  "leave_available",
91639
91896
  "leave_post",
@@ -134672,6 +134929,8 @@ const TEMPLATES = {
134672
134929
  build: build$9
134673
134930
  };
134674
134931
  // src/sql/modules/time-tracking-approvals.ts
134932
+ /** Timesheets this block submits to approvals. */
134933
+ const TIMESHEET_SUBJECT = "timesheet";
134675
134934
  /**
134676
134935
  * The timesheet functions when weeks go through the approvals block: a
134677
134936
  * submitted week opens an approval request, and the final approval locks it.
@@ -134890,6 +135149,21 @@ $$;
134890
135149
  ${userGrant(`${fn("list_timesheets")}(${ctx.idType}, uuid, text, integer, date)`)}
134891
135150
  `;
134892
135151
  }
135152
+ /** Approvals decides weeks; per employee, the status column follows. */
135153
+ const TIME_TRACKING_CONTRIBUTES = { approvals: (own) => {
135154
+ if (!own.flag("approvals", true)) return [];
135155
+ if (byEmployee(own)) return [{
135156
+ subject: TIMESHEET_SUBJECT,
135157
+ access: "declared",
135158
+ approve: ({ subjectId, comment, approver }) => `perform ${own.fn("timesheet_approval_decided")}(${subjectId}::uuid, true, ${comment}, ${approver});`,
135159
+ reject: ({ subjectId, comment, approver }) => `perform ${own.fn("timesheet_approval_decided")}(${subjectId}::uuid, false, ${comment}, ${approver});`
135160
+ }];
135161
+ return [{
135162
+ subject: TIMESHEET_SUBJECT,
135163
+ access: "declared",
135164
+ approve: ({ subjectId }) => `perform ${own.fn("approve_timesheet")}(${subjectId}::uuid);`
135165
+ }];
135166
+ } };
134893
135167
  // src/sql/modules/time-tracking-rates.ts
134894
135168
  /**
134895
135169
  * The rate's currency is an uppercase three-letter code (the client checks it
@@ -135003,7 +135277,9 @@ function statusTimesheetFunctions(ctx, names) {
135003
135277
  const { entries, timesheets, e, t, read, track, manage, approve } = names;
135004
135278
  const { entryJson, timesheetRecord, forbidden, timesheetNotFound, week } = names;
135005
135279
  const { ended, running, owner } = names;
135280
+ const linked = names.approvals;
135006
135281
  const by = owner.employee;
135282
+ const pendingApproval = (row) => linked === void 0 ? "false" : `exists (select 1 from ${linked.requests} x where x.${linked.a("subjectType")} = ${sqlString(linked.subject)} and x.${linked.a("subjectId")} = ${row}.${t("id")}::text and x.${linked.a("status")} = 'pending')`;
135007
135283
  const ownerVar = by ? "v_owner" : "v_user";
135008
135284
  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)`;
135009
135285
  const ownerParam = by ? ", employee_id uuid default null" : "";
@@ -135046,7 +135322,10 @@ begin
135046
135322
  end if;
135047
135323
  if not ${is("v_sheet", ["submitted"])} then
135048
135324
  ${fail$1("TIMESHEET_NOT_SUBMITTED", "only a submitted week can be decided", "55000")}
135049
- end if;
135325
+ end if;${linked === void 0 ? "" : `
135326
+ if ${pendingApproval("v_sheet")} then
135327
+ ${fail$1("TIMESHEET_IN_APPROVAL", "this week is decided through its approval request", "55000")}
135328
+ end if;`}
135050
135329
  update ${timesheets} s set ${t("status")} = ${value(status)}${status === "approved" ? `, ${t("approvedAt")} = now()` : ""}${decide(name === "reject_timesheet" ? "reject_timesheet.note" : "null")}
135051
135330
  where s.${t("id")} = v_sheet.${t("id")}
135052
135331
  returning * into v_sheet;
@@ -135154,7 +135433,7 @@ ${by ? ` if v_owner is null then
135154
135433
  if ${is("v_sheet", ["approved"])} then
135155
135434
  ${fail$1("TIMESHEET_APPROVED", "this week is already approved", "55000")}
135156
135435
  end if;
135157
- if ${is("v_sheet", ["submitted"])} then
135436
+ if ${is("v_sheet", ["submitted"])}${linked === void 0 ? "" : ` and ${pendingApproval("v_sheet")}`} then
135158
135437
  ${fail$1("TIMESHEET_SUBMITTED", "this week is already waiting for a decision", "55000")}
135159
135438
  end if;
135160
135439
  ${ctx.hook("before_timesheet_submit", [
@@ -135165,7 +135444,13 @@ ${by ? ` if v_owner is null then
135165
135444
  update ${timesheets} s
135166
135445
  set ${t("status")} = ${value("submitted")}, ${t("note")} = submit_timesheet.note, ${t("submittedAt")} = now()${clearDecision}
135167
135446
  where s.${t("id")} = v_sheet.${t("id")}
135168
- returning * into v_sheet;
135447
+ returning * into v_sheet;${linked === void 0 ? "" : `
135448
+ perform ${linked.open}(
135449
+ submit_timesheet.tenant, ${sqlString(linked.subject)}, v_sheet.${t("id")}::text, 'approve',
135450
+ ${sqlString(linked.policy)}::jsonb || jsonb_build_object('managerOf', v_owner::text), submit_timesheet.note,
135451
+ jsonb_build_object('userId', ${owner.userOf("v_owner")}, 'employeeId', v_owner, 'week', v_week),
135452
+ ${owner.userOf("v_owner")}
135453
+ );`}
135169
135454
  ${timesheetRecord("timesheet.submitted", "v_sheet", "submitted a timesheet")}
135170
135455
  ${ctx.hook("after_timesheet_submit", [["uuid", `v_sheet.${t("id")}`]])}
135171
135456
  return ${json("v_sheet")};
@@ -135174,7 +135459,38 @@ $$;
135174
135459
  ${userGrant(`${fn("submit_timesheet")}(${ctx.idType}, date, text${ownerType})`)}
135175
135460
 
135176
135461
  drop function if exists ${fn("approve_timesheet")}(uuid);
135177
- ${decision("approve_timesheet", "approved", "timesheet.approved", "approved a timesheet")}${decision("reject_timesheet", "rejected", "timesheet.rejected", "rejected a timesheet")}
135462
+ ${decision("approve_timesheet", "approved", "timesheet.approved", "approved a timesheet")}${linked === void 0 ? "" : `
135463
+ -- Applies the final decision of a week's approval request: approvals calls it,
135464
+ -- with the user who decided. It isn't granted to anyone.
135465
+ create or replace function ${fn("timesheet_approval_decided")}(timesheet_id uuid, approved boolean, note text, decided_by uuid)
135466
+ returns void
135467
+ language plpgsql
135468
+ security definer
135469
+ set search_path = ''
135470
+ as $$
135471
+ declare
135472
+ v_sheet ${timesheets}%rowtype;
135473
+ begin
135474
+ update ${timesheets} s set ${t("status")} = case when timesheet_approval_decided.approved then ${value("approved")} else ${value("rejected")} end,
135475
+ ${t("approvedAt")} = case when timesheet_approval_decided.approved then now() end${[
135476
+ ...ctx.has("timesheets", "decidedBy") ? [`${t("decidedBy")} = timesheet_approval_decided.decided_by`] : [],
135477
+ ...ctx.has("timesheets", "decidedAt") ? [`${t("decidedAt")} = now()`] : [],
135478
+ ...ctx.has("timesheets", "decisionNote") ? [`${t("decisionNote")} = timesheet_approval_decided.note`] : []
135479
+ ].map((set) => `, ${set}`).join("")}
135480
+ where s.${t("id")} = timesheet_approval_decided.timesheet_id and ${is("s", ["submitted"])}
135481
+ returning * into v_sheet;
135482
+ if not found then
135483
+ return;
135484
+ end if;
135485
+ if timesheet_approval_decided.approved then
135486
+ ${timesheetRecord("timesheet.approved", "v_sheet", "approved a timesheet")}
135487
+ else
135488
+ ${timesheetRecord("timesheet.rejected", "v_sheet", "rejected a timesheet")}
135489
+ end if;
135490
+ end;
135491
+ $$;
135492
+ revoke execute on function ${fn("timesheet_approval_decided")}(uuid, boolean, text, uuid) from public, anon, authenticated;
135493
+ `}${decision("reject_timesheet", "rejected", "timesheet.rejected", "rejected a timesheet")}
135178
135494
  -- Unlocks an approved or rejected week so its entries can change and it can
135179
135495
  -- be sent again.
135180
135496
  create or replace function ${fn("reopen_timesheet")}(timesheet_id uuid)
@@ -135370,8 +135686,6 @@ ${userGrant(`${fn("resume_timer")}(uuid)`)}
135370
135686
  `;
135371
135687
  }
135372
135688
  // src/sql/modules/time-tracking.ts
135373
- /** Timesheets this block submits to approvals. */
135374
- const TIMESHEET_SUBJECT = "timesheet";
135375
135689
  const WHERE = "blocks.time-tracking.options";
135376
135690
  const ENTRY_PAYLOAD = [
135377
135691
  "organizationId",
@@ -135554,10 +135868,12 @@ function timesheetPolicy(ctx) {
135554
135868
  }
135555
135869
  function build$8(ctx) {
135556
135870
  if (ctx.mode === "custom") return "";
135557
- const statusMode = !ctx.flag("approvals", true);
135871
+ const employeeLinked = byEmployee(ctx) && ctx.flag("approvals", true);
135872
+ const statusMode = !ctx.flag("approvals", true) || employeeLinked;
135558
135873
  const approvals = statusMode ? void 0 : ctx.of("approvals");
135559
- if (approvals?.mode === "custom") throw new TypeError("blocks.time-tracking needs the approvals tables; approvals can't be in custom mode");
135560
- if (statusMode && !ctx.has("timesheets", "status")) throw new TypeError(`${WHERE}.approvals: false keeps the timesheet status in a column, so blocks.time-tracking.columns.timesheets.status can't be null`);
135874
+ const linked = employeeLinked ? ctx.of("approvals") : void 0;
135875
+ if ((approvals ?? linked)?.mode === "custom") throw new TypeError("blocks.time-tracking needs the approvals tables; approvals can't be in custom mode");
135876
+ if (statusMode && !ctx.has("timesheets", "status")) throw new TypeError(`${employeeLinked ? `${WHERE}.owner "employee"` : `${WHERE}.approvals: false`} keeps the timesheet status in a column, so blocks.time-tracking.columns.timesheets.status can't be null`);
135561
135877
  const entries = ctx.table("entries");
135562
135878
  const timesheets = ctx.table("timesheets");
135563
135879
  const e = (column) => ctx.col("entries", column);
@@ -135573,7 +135889,7 @@ function build$8(ctx) {
135573
135889
  const { bound, rowSubject, subjectColumns, setSubject, subjectInsert, subjectInsertValues } = entrySubjects(ctx, subjects);
135574
135890
  const zone = sqlString(weekTimeZone(ctx));
135575
135891
  const userZone = userTimeZoneOf(ctx);
135576
- const policy = statusMode ? "" : timesheetPolicy(ctx);
135892
+ const policy = statusMode && !employeeLinked ? "" : timesheetPolicy(ctx);
135577
135893
  const durationMode = durationEntries(ctx);
135578
135894
  const { allowOverlap, manyTimers } = timerOptions(ctx);
135579
135895
  if (durationMode && (ctx.owns("entries") || !ctx.has("entries", "seconds") || !ctx.has("entries", "runningSince"))) throw new TypeError("blocks.time-tracking.columns.entries.endedAt can be null only over your own entries table, with seconds (a writable duration column) and runningSince mapped");
@@ -136084,7 +136400,14 @@ ${statusMode ? statusTimesheetFunctions(ctx, {
136084
136400
  week: (at, user) => weekOf(at, user),
136085
136401
  ended,
136086
136402
  running,
136087
- owner: owner.status
136403
+ owner: owner.status,
136404
+ ...linked === void 0 ? {} : { approvals: {
136405
+ open: linked.fn("open_approval"),
136406
+ requests: linked.table("requests"),
136407
+ a: (column) => linked.col("requests", column),
136408
+ subject: TIMESHEET_SUBJECT,
136409
+ policy
136410
+ } }
136088
136411
  }) : approvalTimesheetFunctions(ctx, {
136089
136412
  entries,
136090
136413
  timesheets,
@@ -136182,18 +136505,13 @@ function contract$8(ctx) {
136182
136505
  }
136183
136506
  ];
136184
136507
  }
136185
- const CONTRIBUTES = { approvals: (own) => own.flag("approvals", true) ? [{
136186
- subject: TIMESHEET_SUBJECT,
136187
- access: "declared",
136188
- approve: ({ subjectId }) => `perform ${own.fn("approve_timesheet")}(${subjectId}::uuid);`
136189
- }] : [] };
136190
136508
  const REQUIRES = [
136191
136509
  "memberships",
136192
136510
  "permissions",
136193
136511
  "approvals"
136194
136512
  ];
136195
136513
  const TIME_TRACKING = {
136196
- contributes: CONTRIBUTES,
136514
+ contributes: TIME_TRACKING_CONTRIBUTES,
136197
136515
  name: "time-tracking",
136198
136516
  scopes: ["tenant"],
136199
136517
  title: "Time tracking",