better-supabase 0.41.0 → 0.43.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 (163) hide show
  1. package/dist/ai-sdk/agents/index.d.ts +2 -2
  2. package/dist/{app-tables-kHGNXFsd.d.ts → app-tables-CVMn4c4b.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-hGBtxrnQ.d.ts} +57 -4
  6. package/dist/{automations-CJhRmPmq.js → automations-K0O3En6E.js} +4 -1
  7. package/dist/{bind-XrFxNm5r.d.ts → bind-DWAIKYvJ.d.ts} +1 -1
  8. package/dist/{block-env-CHFHOjvz.d.ts → block-env-C6OEu9Xk.d.ts} +3 -3
  9. package/dist/{block-subjects-Bz95_dqA.js → block-subjects-B1zfhFWC.js} +1 -1
  10. package/dist/{block-tables-EXcmuOJT.d.ts → block-tables-BIExrL2J.d.ts} +1 -1
  11. package/dist/blocks/ai-chat/index.d.ts +3 -3
  12. package/dist/blocks/announcements/index.d.ts +3 -3
  13. package/dist/blocks/api-keys/index.d.ts +1 -1
  14. package/dist/blocks/approvals/index.d.ts +2 -2
  15. package/dist/blocks/approvals/index.js +2 -2
  16. package/dist/blocks/attachments/index.d.ts +1 -1
  17. package/dist/blocks/audit/index.d.ts +2 -2
  18. package/dist/blocks/automations/index.d.ts +2 -2
  19. package/dist/blocks/billing/index.d.ts +1 -1
  20. package/dist/blocks/bookings/index.d.ts +1 -1
  21. package/dist/blocks/calendar/index.d.ts +1 -1
  22. package/dist/blocks/comments/index.d.ts +4 -4
  23. package/dist/blocks/drive/index.d.ts +1 -1
  24. package/dist/blocks/entitlements/index.d.ts +2 -2
  25. package/dist/blocks/expenses/index.js +1 -1
  26. package/dist/blocks/forms/index.d.ts +1 -1
  27. package/dist/blocks/inbox/index.d.ts +4 -4
  28. package/dist/blocks/index.d.ts +1 -1
  29. package/dist/blocks/invoices/index.d.ts +29 -6
  30. package/dist/blocks/invoices/index.js +29 -12
  31. package/dist/blocks/leave/index.js +1 -1
  32. package/dist/blocks/messaging/index.d.ts +4 -4
  33. package/dist/blocks/mfa/index.d.ts +1 -1
  34. package/dist/blocks/notifications/index.d.ts +3 -3
  35. package/dist/blocks/onboarding/index.d.ts +1 -1
  36. package/dist/blocks/organizations/index.d.ts +2 -2
  37. package/dist/blocks/permissions/index.d.ts +1 -1
  38. package/dist/blocks/push/index.d.ts +1 -1
  39. package/dist/blocks/quotes/index.d.ts +9 -4
  40. package/dist/blocks/quotes/index.js +5 -2
  41. package/dist/blocks/reactions/index.d.ts +3 -3
  42. package/dist/blocks/saved-views/index.d.ts +1 -1
  43. package/dist/blocks/search/index.d.ts +2 -2
  44. package/dist/blocks/sessions/index.d.ts +1 -1
  45. package/dist/blocks/settings/index.d.ts +1 -1
  46. package/dist/blocks/subjects/index.d.ts +1 -1
  47. package/dist/blocks/tags/index.d.ts +1 -1
  48. package/dist/blocks/undo/index.d.ts +1 -1
  49. package/dist/blocks/usage/index.d.ts +1 -1
  50. package/dist/blocks/workflow-editor/index.d.ts +3 -3
  51. package/dist/blocks/workflows/index.d.ts +3 -3
  52. package/dist/claims/index.d.ts +3 -3
  53. package/dist/cli/add-CjSPssgL.js +1 -0
  54. package/dist/cli/{add-BGErz-yb.js → add-fdZAY8C_.js} +10 -10
  55. package/dist/cli/{add-DU5HAq6w.js → add-uwUI80aZ.js} +2 -2
  56. package/dist/cli/{app-table-files-Drzpekpt.js → app-table-files-BR_7lT4u.js} +2 -2
  57. package/dist/cli/{app-tables-dZpH63--.js → app-tables-DoxrhJb1.js} +2 -2
  58. package/dist/cli/{backfill-B-p-19g6.js → backfill-BTMgDL6X.js} +1 -1
  59. package/dist/cli/bin.js +1 -1
  60. package/dist/cli/{blocks-Ews-FZZO.js → blocks-BgPbXNhB.js} +1 -1
  61. package/dist/cli/{blocks-iUjNl5yJ.js → blocks-Bj0LS3rF.js} +1 -1
  62. package/dist/cli/{cache-JT4JhdmX.js → cache-CEGpAmXJ.js} +1 -1
  63. package/dist/cli/{codemod-KIxYiazj.js → codemod-CaXGpQ10.js} +1 -1
  64. package/dist/cli/{content-mapper-DkXzxt6f.js → content-mapper-BJRfCnFX.js} +2 -2
  65. package/dist/cli/{doctor-VWanOD74.js → doctor-CHQDLcwL.js} +15 -15
  66. package/dist/cli/{gen-_lBdTgaR.js → gen-DSK152A3.js} +11 -11
  67. package/dist/cli/index.d.ts +1 -1
  68. package/dist/cli/index.js +6 -6
  69. package/dist/cli/{init-Cm6n4u_3.js → init-CPC1ceqC.js} +8 -8
  70. package/dist/cli/{live-D4iSuTmS.js → live-BFXisTDf.js} +2 -2
  71. package/dist/cli/{mcp-CHYX7utI.js → mcp-CrulrTBs.js} +2 -2
  72. package/dist/cli/{metadata-DLba0VjH.js → metadata-yePOltZY.js} +3 -3
  73. package/dist/cli/{migrate-nQhh0nEJ.js → migrate-kjYx7du-.js} +1 -1
  74. package/dist/cli/{migration-safety-C2d3BSTf.js → migration-safety-DnvCYRsw.js} +1 -1
  75. package/dist/cli/{migrations-BOmMcme9.js → migrations-ZYHA0gks.js} +2 -2
  76. package/dist/cli/{module-migration-DSDB473C.js → module-migration-Du7UHsO9.js} +2 -2
  77. package/dist/cli/{powersync-CAHvPkkb.js → powersync-BOxy1_xW.js} +3 -3
  78. package/dist/cli/powersync-BurpZLJB.js +1 -0
  79. package/dist/cli/{print-CahE8HYK.js → print-B4OqfSML.js} +2 -2
  80. package/dist/cli/{providers-CL5Z5Uj4.js → providers-KYOKi_jp.js} +1 -1
  81. package/dist/cli/{prune-workflows-C9xO0fRU.js → prune-workflows-7JISyAI7.js} +1 -1
  82. package/dist/cli/{remove-DIy7gthm.js → remove-DvncDSRp.js} +5 -5
  83. package/dist/cli/{render-CoCZr3Ru.js → render-C6dQ0C0Y.js} +3 -3
  84. package/dist/cli/{run-CVw8hmLk.js → run-BYiApqFR.js} +9 -9
  85. package/dist/cli/{run-BBj137Fn.js → run-DWDRg4vp.js} +27 -27
  86. package/dist/cli/{shared-BdKeo7xp.js → shared-DC86fQYk.js} +1 -1
  87. package/dist/cli/{snapshot-P2ww2xCt.js → snapshot-CwCG_YX2.js} +2 -2
  88. package/dist/cli/{source-BCs4oBl2.js → source-DDxRHVzk.js} +1 -1
  89. package/dist/cli/{spec-uCpXPLoF.js → spec-Cnxqc7kC.js} +2 -2
  90. package/dist/cli/{spec-oPbt9sbZ.js → spec-CvKJ6GpI.js} +1 -1
  91. package/dist/cli/{sql-layout-Bsnge2oW.js → sql-layout-BwbfVSR8.js} +2 -2
  92. package/dist/cli/{sync-Cv7iBRhe.js → sync-lpbLqJly.js} +4 -4
  93. package/dist/cli/{upgrade-C6jWNxkc.js → upgrade-34ZODJZj.js} +2 -2
  94. package/dist/cli/{upgrade-DV7jTRdh.js → upgrade-Cq4EFBH7.js} +5 -5
  95. package/dist/cli/{version-Hza4Q2PB.js → version-BGN5319Z.js} +1 -1
  96. package/dist/client/index.d.ts +5 -5
  97. package/dist/client/native/index.d.ts +4 -4
  98. package/dist/config/index.d.ts +2 -2
  99. package/dist/config/index.js +4 -4
  100. package/dist/{config-B7hnJFxh.js → config-BN17nVp1.js} +1 -1
  101. package/dist/{config-DwXYtmwt.js → config-C-eXOuhp.js} +3 -3
  102. package/dist/{context-tFoygone.d.ts → context-Dga2sgyx.d.ts} +3 -1
  103. package/dist/contract/index.d.ts +3 -3
  104. package/dist/{controller-phhsPHSz.d.ts → controller-BFOCK5AG.d.ts} +1 -1
  105. package/dist/create/index.d.ts +3 -3
  106. package/dist/create/index.js +3 -3
  107. package/dist/create/lite/index.d.ts +3 -3
  108. package/dist/create/lite/index.js +2 -2
  109. package/dist/{entitlements-LfW6S2RW.d.ts → entitlements-C5k_9hHt.d.ts} +1 -1
  110. package/dist/eve/index.d.ts +1 -1
  111. package/dist/eve/index.js +1 -1
  112. package/dist/{field-errors-CMWRPBmF.d.ts → field-errors-LVBXokQN.d.ts} +4 -4
  113. package/dist/{index-X5igfnIi.d.ts → index-BA8sPQ49.d.ts} +2 -2
  114. package/dist/{index-fmrLdtVT.d.ts → index-BhmjjkMu.d.ts} +1 -1
  115. package/dist/{index-B21Pim3I.d.ts → index-CjN6kzvL.d.ts} +2 -2
  116. package/dist/{index-B-HuxATL.d.ts → index-D-SIdOiL.d.ts} +6 -6
  117. package/dist/{index-BXkPvYzd.d.ts → index-DBbdaYAH.d.ts} +1 -1
  118. package/dist/{index-D-uiT4Qz.d.ts → index-DUmsXPdh.d.ts} +1 -1
  119. package/dist/{index-RZqQdq1G.d.ts → index-DwP65vFk.d.ts} +2 -2
  120. package/dist/{instances-DJOknCJ0.js → instances-Bx94JGSW.js} +5 -0
  121. package/dist/mapper/bin.js +5 -5
  122. package/dist/mcp/index.d.ts +1 -1
  123. package/dist/next/index.d.ts +4 -4
  124. package/dist/{operations-Cm4mSrAX.d.ts → operations-J0PkKTaF.d.ts} +1 -1
  125. package/dist/{options-zsLpIqBA.js → options-B1oSaIZ4.js} +2 -1
  126. package/dist/{options-CYZH9uxU.js → options-BXiUftgG.js} +3 -1
  127. package/dist/{options-C5cLEJEa.js → options-ByxOMSXu.js} +2 -1
  128. package/dist/{options-CzxG2Phg.js → options-DLJTiX29.js} +3 -1
  129. package/dist/otel/index.js +4 -4
  130. package/dist/{permissions-r0Cxhxos.d.ts → permissions-Cp2qvVJo.d.ts} +1 -1
  131. package/dist/{ports-BJJJmfWK.d.ts → ports-C61eesjD.d.ts} +1 -1
  132. package/dist/powersync/index.d.ts +2 -2
  133. package/dist/preset/index.d.ts +3 -3
  134. package/dist/preset/index.js +3 -3
  135. package/dist/{preset-U47pzJMK.js → preset-yRJgGbn9.js} +2 -2
  136. package/dist/{project-Dng8tO8S.js → project-ps9mOsLx.js} +5 -5
  137. package/dist/{push-token-CA31xmQr.d.ts → push-token-2LRdwl_8.d.ts} +1 -1
  138. package/dist/react/index.d.ts +5 -5
  139. package/dist/react/native/index.d.ts +1 -1
  140. package/dist/react/server.d.ts +5 -5
  141. package/dist/realtime/index.d.ts +3 -3
  142. package/dist/records/index.d.ts +3 -3
  143. package/dist/server/index.d.ts +3 -3
  144. package/dist/solid/index.d.ts +5 -5
  145. package/dist/sql/index.d.ts +5 -5
  146. package/dist/sql/index.js +3 -3
  147. package/dist/{sql-BudVz33a.js → sql-CWzlxS6f.js} +827 -291
  148. package/dist/ssr/index.d.ts +1 -1
  149. package/dist/svelte/index.d.ts +5 -5
  150. package/dist/{tenant-C2vnB0wX.d.ts → tenant-P7mo0ulH.d.ts} +1 -1
  151. package/dist/testing/index.d.ts +3 -3
  152. package/dist/testing/index.js +1 -1
  153. package/dist/{topic-CKN3kmoi.d.ts → topic-CjKlzHD-.d.ts} +1 -1
  154. package/dist/{types-D8Tltfdq.d.ts → types-VwM7DBvC.d.ts} +2 -2
  155. package/dist/vue/index.d.ts +5 -5
  156. package/dist/{watch-topic-0dXuJMuE.d.ts → watch-topic-jqBMNMs3.d.ts} +1 -1
  157. package/dist/workflow-sdk/world/index.js +1 -1
  158. package/dist/{workflow-sdk-vXuxBSrk.js → workflow-sdk-Bps7tpOv.js} +7 -1
  159. package/dist/yjs/index.d.ts +1 -1
  160. package/package.json +1 -1
  161. package/schemas/config-v1.json +37 -1
  162. package/dist/cli/add-CoP8iie6.js +0 -1
  163. 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-B1zfhFWC.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-Bx94JGSW.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";
@@ -62,11 +62,11 @@ import { t as identitiesSqlOptions } from "./options-D5a9CHgP.js";
62
62
  import { r as inboxSqlOptions, t as CONVERSATION_TO_TASK } from "./automations-CCc5RUw-.js";
63
63
  import { t as incidentsSqlOptions } from "./options-BmFSI07A.js";
64
64
  import { t as inventorySqlOptions } from "./options-D4LuPM8a.js";
65
- import { t as invoicesSqlOptions } from "./options-C5cLEJEa.js";
65
+ import { t as invoicesSqlOptions } from "./options-ByxOMSXu.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";
@@ -88,7 +88,7 @@ import { t as profilesSqlOptions } from "./options-BxdqA2Ex.js";
88
88
  import { t as promotionsSqlOptions } from "./options-BvttpM1M.js";
89
89
  import { t as pushSqlOptions } from "./options-jg0FMHA5.js";
90
90
  import { n as rateLimitSqlOptions, r as webhookInboxSqlOptions, t as queueSqlOptions } from "./options-BTRH26MJ.js";
91
- import { n as QUOTE_TO_ORDER, r as quotesSqlOptions } from "./automations-CJhRmPmq.js";
91
+ import { n as QUOTE_TO_ORDER, r as quotesSqlOptions } from "./automations-K0O3En6E.js";
92
92
  import { t as reactionsSqlOptions } from "./options-BcBdiPSZ.js";
93
93
  import { t as relationsSqlOptions } from "./options-Lg76d-cV.js";
94
94
  import { t as remindersSqlOptions } from "./options-PTLBl6QT.js";
@@ -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"`);
@@ -53172,11 +53304,12 @@ function totalColumnsSql(ctx, table) {
53172
53304
  * of them the plain line sums stay, so deals and invoices render as before.
53173
53305
  */
53174
53306
  function documentTotals(ctx, items) {
53307
+ const parentHas = items.parentHas ?? ((column) => declared(ctx, items.parent, column));
53175
53308
  return [
53176
53309
  "pricesIncludeTax",
53177
53310
  "discountBps",
53178
53311
  "discountAmount"
53179
- ].some((column) => declared(ctx, items.parent, column)) || declared(ctx, items.lines, "optional") || items.taxLines !== void 0 && ctx.hasTable(items.taxLines);
53312
+ ].some(parentHas) || declared(ctx, items.lines, "optional") || items.taxLines !== void 0 && ctx.hasTable(items.taxLines);
53180
53313
  }
53181
53314
  /**
53182
53315
  * The recount of a record whose totals follow its tax rates.
@@ -53195,7 +53328,7 @@ function documentRecountSql(ctx, items, options) {
53195
53328
  const c = (column) => ctx.col(items.lines, column);
53196
53329
  const pc = (column) => ctx.col(items.parent, column);
53197
53330
  const l = (column) => lineColumn(ctx, items.lines, "l", column);
53198
- const parentHas = (column) => declared(ctx, items.parent, column);
53331
+ const parentHas = items.parentHas ?? ((column) => declared(ctx, items.parent, column));
53199
53332
  const parent = `${options.setter}_recount.parent`;
53200
53333
  const amount = lineAmount(ctx, items.lines, "l");
53201
53334
  const discount = declared(ctx, items.lines, "discountBps") ? `round(${amount} * ${l("discountBps")} / 10000.0)` : "0";
@@ -62292,7 +62425,7 @@ function quoteKit(ctx, n) {
62292
62425
  if ${given} is not null then
62293
62426
  ${fail$1(`QUOTE_${thing}_UNSUPPORTED`, `this quotes table has no ${what}`, "22023")}
62294
62427
  end if;`;
62295
- const editable = (alias) => `(${n.service} or ${ctx.scope.can(`${alias}.${q("tenant")}`, n.write)})`;
62428
+ const editable = (alias, key = n.write) => `(${n.service} or ${ctx.scope.can(`${alias}.${q("tenant")}`, key)})`;
62296
62429
  const st = (value, labels, negate = false) => ctx.is("quotes", "status", value, labels, negate);
62297
62430
  const sv = (label) => ctx.value("quotes", "status", label);
62298
62431
  const viewed = ctx.appValues("quotes", "status", "viewed").length > 0;
@@ -62310,12 +62443,19 @@ function quoteKit(ctx, n) {
62310
62443
  end if;` : " null;";
62311
62444
  const workingCopy = workingCopyOn(ctx);
62312
62445
  const versionLines = versionLinesOn(ctx);
62313
- const open = (alias) => st(`${alias}.${q("status")}`, workingCopy ? [
62446
+ const declined = n.resend ? [
62447
+ "rejected",
62448
+ "withdrawn",
62449
+ "expired"
62450
+ ] : [];
62451
+ const openStatuses = workingCopy ? [
62314
62452
  "draft",
62315
62453
  "changes_requested",
62316
62454
  "sent",
62317
- "viewed"
62318
- ] : ["draft", "changes_requested"]);
62455
+ "viewed",
62456
+ ...declined
62457
+ ] : ["draft", "changes_requested"];
62458
+ const open = (alias) => st(`${alias}.${q("status")}`, openStatuses);
62319
62459
  const lineValue = (column) => lineColumn(ctx, "lines", "ql", column);
62320
62460
  const documentLine = [
62321
62461
  "section",
@@ -62390,6 +62530,8 @@ function quoteKit(ctx, n) {
62390
62530
  st,
62391
62531
  sv,
62392
62532
  open,
62533
+ openStatuses,
62534
+ declined,
62393
62535
  lines,
62394
62536
  taxLines,
62395
62537
  row,
@@ -62402,7 +62544,7 @@ function quoteKit(ctx, n) {
62402
62544
  checkParty,
62403
62545
  notifyOwner,
62404
62546
  markViewed,
62405
- depositDue: has("depositDue") && (has("depositBps") || has("depositAmount")) ? `${q("depositDue")} = case${has("depositAmount") ? ` when x.${q("depositAmount")} is not null then least(greatest(${total}, 0), x.${q("depositAmount")})` : ""}${has("depositBps") ? ` when x.${q("depositBps")} is not null then round(${total} * x.${q("depositBps")} / 10000.0)::bigint` : ""} else 0 end` : void 0
62547
+ depositDue: !n.appTotals && has("depositDue") && (has("depositBps") || has("depositAmount")) ? `${q("depositDue")} = case${has("depositAmount") ? ` when x.${q("depositAmount")} is not null then least(greatest(${total}, 0), x.${q("depositAmount")})` : ""}${has("depositBps") ? ` when x.${q("depositBps")} is not null then round(${total} * x.${q("depositBps")} / 10000.0)::bigint` : ""} else 0 end` : void 0
62406
62548
  };
62407
62549
  }
62408
62550
  // src/sql/modules/quotes-decisions.ts
@@ -62539,6 +62681,23 @@ function quoteDecisions(ctx, n, k) {
62539
62681
  if ${a.name}.decision = 'accepted' then
62540
62682
  ${ctx.hook("after_quote_accept", [["uuid", `v_row.${q("id")}`]])}
62541
62683
  end if;`;
62684
+ const viewer = (actor) => {
62685
+ const own = `begin
62686
+ v_ip := ${ip}::inet;
62687
+ exception when invalid_text_representation then
62688
+ v_ip := null;
62689
+ end;
62690
+ perform set_config('better_supabase.transition_actor', jsonb_strip_nulls(jsonb_build_object('email', auth.jwt() ->> 'email', 'ip', v_ip::text, 'userAgent', left(v_headers ->> 'user-agent', 512)))::text, true);`;
62691
+ return actor === void 0 ? `
62692
+ ${own}` : `
62693
+ if ${actor} is not null and not ${n.service} then
62694
+ ${fail$1("QUOTE_ACTOR_FORBIDDEN", "only the service role names who opened a quote", "42501")}
62695
+ end if;
62696
+ ${transitionActorSql(actor, "QUOTE_ACTOR_INVALID")}
62697
+ if ${actor} is null then
62698
+ ${own.replaceAll("\n", "\n ")}
62699
+ end if;`;
62700
+ };
62542
62701
  const answered = `jsonb_build_object('status', ${ctx.label("quotes", "status", `v_row.${q("status")}`)}, 'identifier', v_row.${q("identifier")}, 'revision', v_row.${q("revision")})`;
62543
62702
  const customerView = k.workingCopy ? `select v.${n.c("versions", "snapshot")} into v_snap from ${t("versions")} v where v.${n.c("versions", "id")} = ${k.latestVersion("v_row")};
62544
62703
  if v_snap is null then
@@ -62566,7 +62725,7 @@ declare
62566
62725
  v_row ${t("quotes")};
62567
62726
  v_claims text;${restoreVars}
62568
62727
  begin
62569
- select * into v_row from ${t("quotes")} x where x.${q("id")} = decide_quote.quote and ${editable("x")} for update;
62728
+ select * into v_row from ${t("quotes")} x where x.${q("id")} = decide_quote.quote and ${editable("x", n.decide)} for update;
62570
62729
  if v_row.${q("id")} is null then
62571
62730
  ${fail$1("QUOTE_NOT_FOUND", "no such quote you can edit", "P0002")}
62572
62731
  end if;${answer({
@@ -62591,12 +62750,12 @@ security definer
62591
62750
  set search_path = ''
62592
62751
  as $$
62593
62752
  declare
62594
- v_row ${t("quotes")};${restoreVars}
62753
+ v_row ${t("quotes")};${headers}${restoreVars}
62595
62754
  begin
62596
62755
  select * into v_row from ${t("quotes")} x where x.${q("tokenHash")} = ${sha256Hex$1("public_quote.token")};
62597
62756
  if v_row.${q("id")} is null then
62598
62757
  ${fail$1("QUOTE_LINK_INVALID", "this link is not valid", "P0002")}
62599
- end if;
62758
+ end if;${viewer()}
62600
62759
  ${k.markViewed()}
62601
62760
  ${customerView}
62602
62761
  end;
@@ -62638,16 +62797,18 @@ grant execute on function ${fn("respond_to_quote")}(text, text, text, text, json
62638
62797
  -- A quote shared with the signed-in guest, as the customer sees it: through
62639
62798
  -- a grant on the quote or as a guest of its company or contact. Opening a
62640
62799
  -- sent quote marks it viewed. No link token is needed. The service role
62641
- -- reads it too, for an app's own portal.
62642
- create or replace function ${fn("portal_quote")}(quote uuid)
62800
+ -- reads it too, for an app's own portal; actor is then the customer who
62801
+ -- opened it, for the state machine's history.
62802
+ drop function if exists ${fn("portal_quote")}(uuid);
62803
+ create or replace function ${fn("portal_quote")}(quote uuid, actor jsonb default null)
62643
62804
  returns jsonb
62644
62805
  language plpgsql
62645
62806
  security definer
62646
62807
  set search_path = ''
62647
62808
  as $$
62648
62809
  declare
62649
- v_row ${t("quotes")};${restoreVars}
62650
- begin
62810
+ v_row ${t("quotes")};${headers}${restoreVars}
62811
+ begin${viewer("portal_quote.actor")}
62651
62812
  select * into v_row from ${t("quotes")} x where x.${q("id")} = portal_quote.quote and (${guest} or (${n.service} and ${k.st(`x.${q("status")}`, ["draft"], true)}));
62652
62813
  if v_row.${q("id")} is null then
62653
62814
  ${fail$1("QUOTE_NOT_FOUND", "no such quote shared with you", "P0002")}
@@ -62656,7 +62817,7 @@ ${k.markViewed()}
62656
62817
  ${customerView}
62657
62818
  end;
62658
62819
  $$;
62659
- ${userGrant(`${fn("portal_quote")}(uuid)`)}
62820
+ ${userGrant(`${fn("portal_quote")}(uuid, jsonb)`)}
62660
62821
 
62661
62822
  -- The signed-in guest's answer to a quote shared with them, like
62662
62823
  -- respond_to_quote without a token. name defaults to their email; the
@@ -62781,6 +62942,7 @@ function quoteFunctions(ctx, n) {
62781
62942
  ${fail$1("QUOTE_ATTRS_INVALID", "a deposit is a share (depositBps) or an amount (depositAmount), not both", "22023")}
62782
62943
  end if;` : "";
62783
62944
  const actor = (name) => `\n ${transitionActorSql(`${name}.actor`, "QUOTE_ACTOR_INVALID")}`;
62945
+ const resent = k.declined.length === 0 ? "" : `${q("validUntil")} = case when ${st(`x.${q("status")}`, k.declined)} then greatest(x.${q("validUntil")}, current_date + ${String(n.validDays)}) else x.${q("validUntil")} end, ${has("viewedAt") && !k.workingCopy ? `${q("viewedAt")} = case when ${st(`x.${q("status")}`, k.declined)} then null else x.${q("viewedAt")} end, ` : ""}`;
62784
62946
  const publishedBy = `coalesce(auth.uid(), nullif(send_quote.actor ->> 'id', '')::uuid)`;
62785
62947
  const versionLinesCopy = (() => {
62786
62948
  if (!k.versionLines) return "";
@@ -62801,9 +62963,11 @@ function quoteFunctions(ctx, n) {
62801
62963
  "productId"
62802
62964
  ].filter((column) => declared(ctx, "versionLines", column) && declared(ctx, "lines", column));
62803
62965
  const value = (column) => column === "productType" ? ctx.cast("versionLines", column, `ql.${l(column)}::text`) : `ql.${l(column)}`;
62966
+ const lineExtraNames = new Set(n.lineExtras.map((extra) => extra.name));
62967
+ const extras = n.versionLineExtras.filter((extra) => lineExtraNames.has(extra.name)).map((extra) => extra.ident);
62804
62968
  return `
62805
- insert into ${t("versionLines")} (${vl("tenant")}, ${vl("version")}, ${copied.map(vl).join(", ")})
62806
- select v_row.${q("tenant")}, v_version, ${copied.map(value).join(", ")}
62969
+ insert into ${t("versionLines")} (${vl("tenant")}, ${vl("version")}, ${[...copied.map(vl), ...extras].join(", ")})
62970
+ select v_row.${q("tenant")}, v_version, ${[...copied.map(value), ...extras.map((ident) => `ql.${ident}`)].join(", ")}
62807
62971
  from ${t("lines")} ql where ql.${l("parent")} = v_row.${q("id")};`;
62808
62972
  })();
62809
62973
  const deals = ctx.installed("deals") ? ctx.of("deals") : void 0;
@@ -62967,8 +63131,8 @@ begin
62967
63131
  select * into v_row from ${t("quotes")} x where x.${q("id")} = v_row.${q("id")};`}
62968
63132
  exception when check_violation or invalid_text_representation or datetime_field_overflow or numeric_value_out_of_range then
62969
63133
  ${fail$1("QUOTE_ATTRS_INVALID", "a quote field has an invalid value", "22023")}
62970
- end;${oneDeposit}
62971
- perform ${fn("set_quote_lines_recount")}(v_row.${q("id")});
63134
+ end;${oneDeposit}${n.appTotals ? "" : `
63135
+ perform ${fn("set_quote_lines_recount")}(v_row.${q("id")});`}
62972
63136
  select * into v_row from ${t("quotes")} x where x.${q("id")} = v_row.${q("id")};
62973
63137
  ${record("quote.updated", "v_row")}
62974
63138
  return ${row("v_row")};
@@ -62981,6 +63145,7 @@ ${lineItemsSql(ctx, {
62981
63145
  frozen: `not (${open("p")})`,
62982
63146
  extras: n.lineExtras,
62983
63147
  taxLines: "taxLines",
63148
+ totals: !n.appTotals,
62984
63149
  ...k.depositDue === void 0 ? {} : { afterTotals: k.depositDue }
62985
63150
  }, {
62986
63151
  setter: "set_quote_lines",
@@ -63009,11 +63174,11 @@ declare
63009
63174
  v_token text := encode(extensions.gen_random_bytes(24), 'hex');
63010
63175
  v_version uuid;${k.workingCopy ? "\n v_linked boolean;" : ""}
63011
63176
  begin
63012
- select * into v_row from ${t("quotes")} x where x.${q("id")} = send_quote.quote and ${editable("x")} for update;
63177
+ select * into v_row from ${t("quotes")} x where x.${q("id")} = send_quote.quote and ${editable("x", n.send)} for update;
63013
63178
  if v_row.${q("id")} is null then
63014
63179
  ${fail$1("QUOTE_NOT_FOUND", "no such quote you can edit", "P0002")}
63015
63180
  end if;
63016
- if not (${open("v_row")}) then
63181
+ if not (${open("v_row")}${k.declined.length > 0 && !k.workingCopy ? ` or ${st(`v_row.${q("status")}`, k.declined)}` : ""}) then
63017
63182
  ${fail$1("QUOTE_NOT_EDITABLE", "the quote was already sent; revise it to send a new version", "55000")}
63018
63183
  end if;
63019
63184
  if not exists (select 1 from ${t("lines")} x where x.${l("parent")} = v_row.${q("id")}) then
@@ -63022,7 +63187,7 @@ begin
63022
63187
  ${ctx.hook("before_quote_send", [["uuid", `v_row.${q("id")}`]])}${k.workingCopy ? `\n v_linked := v_row.${q("tokenHash")} is not null;` : ""}
63023
63188
  update ${t("quotes")} x set ${q("status")} = ${sv("sent")}, ${q("sentAt")} = now(), ${q("tokenHash")} = ${k.workingCopy ? `coalesce(x.${q("tokenHash")}, ${sha256Hex$1("v_token")})` : sha256Hex$1("v_token")},
63024
63189
  ${q("revision")} = case when exists (select 1 from ${t("versions")} v where v.${v("quote")} = x.${q("id")} and v.${v("revision")} = x.${q("revision")}) then x.${q("revision")} + 1 else x.${q("revision")} end,
63025
- ${decisionReset}${k.workingCopy ? `${q("unpublishedChanges")} = false, ` : ""}${q("updatedAt")} = now()
63190
+ ${decisionReset}${resent}${k.workingCopy ? `${q("unpublishedChanges")} = false, ` : ""}${q("updatedAt")} = now()
63026
63191
  where x.${q("id")} = v_row.${q("id")}
63027
63192
  returning * into v_row;
63028
63193
  insert into ${t("versions")} (${v("tenant")}, ${v("quote")}, ${v("revision")}, ${v("snapshot")}, ${v("total")}, ${v("currency")}${ctx.has("versions", "publishedBy") ? `, ${v("publishedBy")}` : ""})
@@ -63072,8 +63237,8 @@ end;
63072
63237
  $$;
63073
63238
  ${userGrant(`${fn("revise_quote")}(uuid, jsonb)`)}
63074
63239
 
63075
- -- Takes back a sent quote the customer hasn't accepted: it can't be answered
63076
- -- any more until it is revised and sent again.
63240
+ -- Takes back a sent or expired quote the customer hasn't accepted: it can't
63241
+ -- be answered any more until it is revised and sent again.
63077
63242
  create or replace function ${fn("withdraw_quote")}(quote uuid, actor jsonb default null)
63078
63243
  returns jsonb
63079
63244
  language plpgsql
@@ -63083,14 +63248,15 @@ as $$
63083
63248
  declare
63084
63249
  v_row ${t("quotes")};
63085
63250
  begin
63086
- select * into v_row from ${t("quotes")} x where x.${q("id")} = withdraw_quote.quote and ${editable("x")} for update;
63251
+ select * into v_row from ${t("quotes")} x where x.${q("id")} = withdraw_quote.quote and ${editable("x", n.withdraw)} for update;
63087
63252
  if v_row.${q("id")} is null then
63088
63253
  ${fail$1("QUOTE_NOT_FOUND", "no such quote you can edit", "P0002")}
63089
63254
  end if;
63090
63255
  if ${st(`v_row.${q("status")}`, [
63091
63256
  "sent",
63092
63257
  "viewed",
63093
- "changes_requested"
63258
+ "changes_requested",
63259
+ "expired"
63094
63260
  ], true)} then
63095
63261
  ${fail$1("QUOTE_NOT_OPEN", "only a sent quote that wasn't answered is withdrawn", "55000")}
63096
63262
  end if;${actor("withdraw_quote")}
@@ -63114,6 +63280,7 @@ declare
63114
63280
  v_row ${t("quotes")};
63115
63281
  v_count integer := 0;
63116
63282
  begin
63283
+ perform set_config('better_supabase.transition_actor', '', true);
63117
63284
  for v_row in
63118
63285
  update ${t("quotes")} x set ${q("status")} = ${sv("expired")}, ${q("updatedAt")} = now()
63119
63286
  where ${st(`x.${q("status")}`, ["sent", "viewed"])} and x.${q("validUntil")} < current_date
@@ -63126,7 +63293,47 @@ begin
63126
63293
  end;
63127
63294
  $$;
63128
63295
  ${serviceGrant(`${fn("expire_quotes")}()`)}
63129
- ${fromDeal}`;
63296
+ ${appTotalsGuard(ctx, n, k)}${fromDeal}`;
63297
+ }
63298
+ /**
63299
+ * With `options.totals: "app"`, a trigger on the quotes table that refuses a
63300
+ * change to the totals once a quote is answered, expired or withdrawn, and
63301
+ * keeps the deposit due on the app's total.
63302
+ */
63303
+ function appTotalsGuard(ctx, n, k) {
63304
+ if (!n.appTotals) return "";
63305
+ const { q, has, st } = k;
63306
+ const trigger = ctx.trigger("quotes_app_totals");
63307
+ const fn = `better_supabase.${trigger.replaceAll("\"", "")}()`;
63308
+ const totals = Object.keys(TOTAL_COLUMNS).filter(has).map(q);
63309
+ const changeable = [.../* @__PURE__ */ new Set([
63310
+ ...k.openStatuses,
63311
+ "sent",
63312
+ "viewed"
63313
+ ])];
63314
+ const depositDue = has("depositDue") ? `
63315
+ new.${q("depositDue")} := case${has("depositAmount") ? ` when new.${q("depositAmount")} is not null then least(greatest(new.${q("total")}, 0), new.${q("depositAmount")})` : ""}${has("depositBps") ? ` when new.${q("depositBps")} is not null then round(new.${q("total")} * new.${q("depositBps")} / 10000.0)::bigint` : ""} else 0 end;` : "";
63316
+ return `
63317
+ -- The app keeps the quote's totals: once a quote is answered, expired or
63318
+ -- withdrawn they no longer change, and the deposit due follows the total.
63319
+ create or replace function ${fn}
63320
+ returns trigger
63321
+ language plpgsql
63322
+ set search_path = ''
63323
+ as $$
63324
+ begin
63325
+ if tg_op = 'UPDATE' and ${st(`old.${q("status")}`, changeable, true)}
63326
+ and (${totals.map((column) => `new.${column}`).join(", ")}) is distinct from (${totals.map((column) => `old.${column}`).join(", ")}) then
63327
+ ${fail$1("QUOTE_TOTALS_FROZEN", "the totals of an answered, expired or withdrawn quote don't change", "55000")}
63328
+ end if;${depositDue}
63329
+ return new;
63330
+ end;
63331
+ $$;
63332
+ ${triggerGrant(fn)}
63333
+ drop trigger if exists ${trigger} on ${n.t("quotes")};
63334
+ create trigger ${trigger} before insert or update on ${n.t("quotes")}
63335
+ for each row execute function ${fn};
63336
+ `;
63130
63337
  }
63131
63338
  // src/sql/modules/employees-functions.ts
63132
63339
  /**
@@ -66552,6 +66759,23 @@ const EXPENSE_TABLE = {
66552
66759
  ],
66553
66760
  typed: ["status"]
66554
66761
  };
66762
+ /** The subject type of an expense the approvals block decides. */
66763
+ const EXPENSE_SUBJECT = "expense";
66764
+ /**
66765
+ * Whether each standalone expense goes through the approvals block:
66766
+ * `options.standaloneApprovals`, which needs `tables.reports: null`.
66767
+ */
66768
+ function standaloneApprovals(ctx) {
66769
+ const on = ctx.flag("standaloneApprovals", false);
66770
+ if (on && !expensesStandalone(ctx)) throw new TypeError("blocks.expenses.options.standaloneApprovals needs tables.reports: null; reports go through approvals already");
66771
+ return on;
66772
+ }
66773
+ /** `options.policy`, or one step for holders of the approve permission. */
66774
+ function standalonePolicy(ctx) {
66775
+ const policy = policyOf(EXPENSE_SUBJECT, "approve", ctx.option("policy") ?? { steps: [{ approvers: { permission: ctx.permissionKey("approve", OPERATIONS["expenses.approve"]) } }] }, "blocks.expenses.options.policy");
66776
+ if (policy.run !== void 0) throw new TypeError("blocks.expenses.options.policy.run is not allowed; the final approval approves the expense");
66777
+ return policySnapshot(policy);
66778
+ }
66555
66779
  function expensesStandalone(ctx) {
66556
66780
  const reports = ctx.config.tables["reports"] === null;
66557
66781
  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 +66920,21 @@ function expenseStandaloneSql(ctx) {
66696
66920
  const extra = extraFieldsArg(extras);
66697
66921
  const statusColumn = has("status");
66698
66922
  const company = ctx.flag("companyExpenses", false);
66923
+ const linked = standaloneApprovals(ctx) ? ctx.of("approvals") : void 0;
66924
+ if (linked?.mode === "custom") throw new TypeError("blocks.expenses needs the approvals tables; approvals can't be in custom mode");
66925
+ const ar = linked?.table("requests") ?? "";
66926
+ const a = (column) => linked?.col("requests", column) ?? "";
66927
+ 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')`;
66928
+ const openApproval = linked === void 0 ? "" : `
66929
+ perform ${linked.fn("open_approval")}(
66930
+ v_row.${e("tenant")}, ${sqlString(EXPENSE_SUBJECT)}, v_row.${e("id")}::text, 'approve',
66931
+ ${sqlString(standalonePolicy(ctx))}::jsonb${employee ? ` || jsonb_build_object('managerOf', v_row.${e("employee")}::text)` : ""}, null,
66932
+ 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")}),
66933
+ ${owner.requester("v_row")}
66934
+ );`;
66935
+ const cancelApproval = linked === void 0 ? "" : `
66936
+ update ${ar} x set ${a("status")} = 'cancelled'${linked.has("requests", "decidedAt") ? `, ${a("decidedAt")} = now()` : ""}
66937
+ where x.${a("subjectType")} = ${sqlString(EXPENSE_SUBJECT)} and x.${a("subjectId")} = v_row.${e("id")}::text and x.${a("status")} = 'pending';`;
66699
66938
  const inserted = insertExtraColumns(table, extras, "coalesce(create_expense.fields, '{}'::jsonb)");
66700
66939
  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
66940
  const forbidden = (message) => fail$1("EXPENSES_FORBIDDEN", message);
@@ -66884,7 +67123,7 @@ declare
66884
67123
  begin${load("submit_expense.expense_id")}${ownerOrManager(updateOthers)}${editable}
66885
67124
  update ${table} x set ${e("submittedAt")} = now()${setStatus("submitted")}${set("rejectedAt", "null")}${set("approvedAt", "null")}, ${e("updatedAt")} = now()
66886
67125
  where x.${e("id")} = v_row.${e("id")}
66887
- returning * into v_row;
67126
+ returning * into v_row;${openApproval}
66888
67127
  ${record("expense.submitted", "submitted an expense")}
66889
67128
  return ${json("v_row")};
66890
67129
  end;
@@ -66905,7 +67144,7 @@ begin${load("withdraw_expense.expense_id")}${ownerOrManager(withdrawApproved ? w
66905
67144
  end if;
66906
67145
  update ${table} x set ${e("submittedAt")} = null${setStatus("draft")}${withdrawApproved ? `${set("approvedAt", "null")}${set("decidedBy", "null")}${set("decidedAt", "null")}` : ""}, ${e("updatedAt")} = now()
66907
67146
  where x.${e("id")} = v_row.${e("id")}
66908
- returning * into v_row;
67147
+ returning * into v_row;${cancelApproval}
66909
67148
  ${record("expense.withdrawn", "withdrew an expense")}
66910
67149
  return ${json("v_row")};
66911
67150
  end;
@@ -66930,6 +67169,7 @@ begin${load("delete_expense.expense_id")}${deleteSubmitted === void 0 ? ownerOrM
66930
67169
  if ${status("v_row")} <> 'draft'${deleteSubmitted === void 0 ? "" : ` and ${status("v_row")} not in ('submitted', 'approved')`} then
66931
67170
  ${fail$1("EXPENSE_LOCKED", deleteSubmitted === void 0 ? "only a draft expense is deleted" : "only a draft, submitted or approved expense is deleted", "55000")}
66932
67171
  end if;
67172
+ ${cancelApproval}
66933
67173
  delete from ${table} x where x.${e("id")} = v_row.${e("id")};
66934
67174
  ${record("expense.deleted", "deleted an expense")}
66935
67175
  return true;
@@ -66957,7 +67197,10 @@ begin${load("decide_expense.expense_id")}
66957
67197
  end if;
66958
67198
  if ${status("v_row")} <> 'submitted' then
66959
67199
  ${fail$1("EXPENSE_LOCKED", "only a submitted expense is decided", "55000")}
66960
- end if;
67200
+ end if;${linked === void 0 ? "" : `
67201
+ if ${pending} then
67202
+ ${fail$1("EXPENSE_IN_APPROVAL", "this expense is decided through its approval request", "55000")}
67203
+ end if;`}
66961
67204
  if decide_expense.approved is null then
66962
67205
  ${invalid("approved must be true or false")}
66963
67206
  end if;${unsupported("decisionNote", "nullif(trim(decide_expense.note), '')")}
@@ -66976,7 +67219,37 @@ begin${load("decide_expense.expense_id")}
66976
67219
  end;
66977
67220
  $$;
66978
67221
  ${userGrant(`${fn("decide_expense")}(uuid, boolean, text, uuid)`)}
66979
-
67222
+ ${linked === void 0 ? "" : `
67223
+ -- Applies the final decision of an expense's approval request: approvals
67224
+ -- calls it, with the user who decided. It isn't granted to anyone.
67225
+ create or replace function ${fn("expense_approval_decided")}(expense_id uuid, approved boolean, note text, decided_by uuid)
67226
+ returns void
67227
+ language plpgsql
67228
+ security definer
67229
+ set search_path = ''
67230
+ as $$
67231
+ declare
67232
+ v_row ${table}%rowtype;
67233
+ begin
67234
+ select * into v_row from ${table} x where x.${e("id")} = expense_approval_decided.expense_id for update;
67235
+ if not found or ${status("v_row")} <> 'submitted' then
67236
+ return;
67237
+ end if;
67238
+ if expense_approval_decided.approved then
67239
+ 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), '')")}
67240
+ where x.${e("id")} = v_row.${e("id")}
67241
+ returning * into v_row;
67242
+ ${record("expense.approved", "approved an expense")}
67243
+ else
67244
+ 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), '')")}
67245
+ where x.${e("id")} = v_row.${e("id")}
67246
+ returning * into v_row;
67247
+ ${record("expense.rejected", "rejected an expense")}
67248
+ end if;
67249
+ end;
67250
+ $$;
67251
+ revoke execute on function ${fn("expense_approval_decided")}(uuid, boolean, text, uuid) from public, anon, authenticated;
67252
+ `}
66980
67253
  create or replace function ${fn("reimburse_expense")}(expense_id uuid, reference text default null)
66981
67254
  returns jsonb
66982
67255
  language plpgsql
@@ -67795,7 +68068,9 @@ const NAMES$72 = {
67795
68068
  "approvals",
67796
68069
  "owner",
67797
68070
  "companyExpenses",
67798
- "withdrawApproved"
68071
+ "withdrawApproved",
68072
+ "standaloneApprovals",
68073
+ "policy"
67799
68074
  ],
67800
68075
  tables: {
67801
68076
  categories: {
@@ -68110,7 +68385,12 @@ function contract$63(ctx) {
68110
68385
  }
68111
68386
  ];
68112
68387
  }
68113
- const CONTRIBUTES$10 = { approvals: (own) => expenseApprovals(own) ? [{
68388
+ const CONTRIBUTES$8 = { approvals: (own) => standaloneApprovals(own) ? [{
68389
+ subject: EXPENSE_SUBJECT,
68390
+ access: "declared",
68391
+ approve: ({ subjectId, comment, approver }) => `perform ${own.fn("expense_approval_decided")}(${subjectId}::uuid, true, ${comment}, ${approver});`,
68392
+ reject: ({ subjectId, comment, approver }) => `perform ${own.fn("expense_approval_decided")}(${subjectId}::uuid, false, ${comment}, ${approver});`
68393
+ }] : expenseApprovals(own) ? [{
68114
68394
  subject: EXPENSE_REPORT_SUBJECT,
68115
68395
  access: "declared",
68116
68396
  approve: ({ subjectId }) => `perform ${own.fn("approve_expense_report")}(${subjectId}::uuid);`
@@ -68122,7 +68402,7 @@ const REQUIRES$4 = [
68122
68402
  "ledger"
68123
68403
  ];
68124
68404
  const EXPENSES = {
68125
- contributes: CONTRIBUTES$10,
68405
+ contributes: CONTRIBUTES$8,
68126
68406
  name: "expenses",
68127
68407
  scopes: ["tenant"],
68128
68408
  title: "Expenses",
@@ -68130,7 +68410,11 @@ const EXPENSES = {
68130
68410
  requires: [...REQUIRES$4],
68131
68411
  dependencies: (layout) => {
68132
68412
  const expenses = layout.modules?.["expenses"];
68133
- if (expenses?.tables?.["reports"] === null) return ["memberships", "permissions"];
68413
+ if (expenses?.tables?.["reports"] === null) return expenses.options?.["standaloneApprovals"] === true ? [
68414
+ "memberships",
68415
+ "permissions",
68416
+ "approvals"
68417
+ ] : ["memberships", "permissions"];
68134
68418
  return expenses?.options?.["approvals"] === false ? REQUIRES$4.filter((name) => name !== "approvals") : [...REQUIRES$4];
68135
68419
  },
68136
68420
  integrates: [
@@ -86323,7 +86607,156 @@ const INVITATIONS = {
86323
86607
  }],
86324
86608
  build: invitationsSql
86325
86609
  };
86610
+ // src/sql/modules/invoices-from-quote.ts
86611
+ /**
86612
+ * `invoice_from_quote`: a deposit invoice for a share or an amount of an
86613
+ * accepted quote, or the final invoice less the deposits issued. Empty without
86614
+ * the quotes module.
86615
+ */
86616
+ function invoiceFromQuote(ctx, n, k) {
86617
+ const quotes = ctx.installed("quotes") ? ctx.of("quotes") : void 0;
86618
+ if (quotes === void 0) return "";
86619
+ const { fn, t } = n;
86620
+ const i = (column) => n.c("invoices", column);
86621
+ const { has, row, refuse, st, kd, origin, company, contact } = k;
86622
+ const q = (column) => quotes.col("quotes", column);
86623
+ const ql = (column) => quotes.col("lines", column);
86624
+ const kind = n.depositKind;
86625
+ const bpsDeposits = kind !== void 0 || has("depositBps");
86626
+ const amountDeposits = kind !== void 0 || has("depositAmount");
86627
+ const markers = ["depositBps", "depositAmount"].filter(has);
86628
+ const deposits = kind !== void 0 || markers.length > 0;
86629
+ const isDeposit = (alias) => kind === void 0 ? markers.map((column) => `${alias}.${i(column)} is not null`).join(" or ") : `${alias}.${i("kind")}::text = ${sqlString(kind)}`;
86630
+ const notDeposit = (alias) => kind === void 0 ? markers.map((column) => `${alias}.${i(column)} is null and `).join("") : `${alias}.${i("kind")}::text <> ${sqlString(kind)} and `;
86631
+ const originIs = (alias) => `${origin === "pair" ? `${alias}.${i("originType")} = 'quote' and ` : ""}${alias}.${i("originId")}::text = v_quote.${q("id")}::text`;
86632
+ const inclusive = has("pricesIncludeTax") && quotes.has("quotes", "pricesIncludeTax") ? `v_quote.${q("pricesIncludeTax")}` : "false";
86633
+ const base = (alias) => `case when ${inclusive} then ${alias}.${q("total")} else ${alias}.${q("subtotal")} end`;
86634
+ const blendedRate = `case when v_quote.${q("subtotal")} = 0 then 0 else round(v_quote.${q("taxTotal")} * 10000.0 / v_quote.${q("subtotal")})::integer end`;
86635
+ const taxLines = quotes.hasTable("taxLines") ? (column) => quotes.col("taxLines", column) : void 0;
86636
+ const invoiceLineExtras = new Set(n.lineExtras.map((extra) => extra.name));
86637
+ const lineFields = lineExtraColumns(quotes).filter((extra) => invoiceLineExtras.has(extra.name));
86638
+ const lineFieldsSql = lineFields.length === 0 ? "" : `, 'fields', jsonb_build_object(${lineFields.map((extra) => `${sqlString(extra.name)}, x.${extra.ident}`).join(", ")})`;
86639
+ const invoiceExtras = new Set(n.extras.map((extra) => extra.name));
86640
+ const headerFields = quotes.extraColumns("quotes", [
86641
+ "lines",
86642
+ "token",
86643
+ "fields"
86644
+ ]).filter((extra) => invoiceExtras.has(extra.name));
86645
+ const headerFieldsSql = headerFields.length === 0 ? "" : ` || jsonb_build_object(${headerFields.map((extra) => `${sqlString(extra.name)}, v_quote.${extra.ident}`).join(", ")})`;
86646
+ const discountLines = taxLines !== void 0 && quotes.has("taxLines", "discount") ? `
86647
+ select v_lines || coalesce(jsonb_agg(jsonb_build_object('description', 'Discount', 'quantity', 1, 'unitAmount', (-x.${taxLines("discount")})::text,
86648
+ 'taxRateBps', x.${taxLines("taxRateBps")}, 'taxCode', ${quotes.has("taxLines", "taxCode") ? `x.${taxLines("taxCode")}` : "null"}) order by x.${taxLines("taxRateBps")}), '[]'::jsonb)
86649
+ into v_lines
86650
+ from ${quotes.table("taxLines")} x where x.${taxLines("parent")} = v_quote.${q("id")} and x.${taxLines("discount")} <> 0;` : "";
86651
+ const quoteDiscounts = ["discountBps", "discountAmount"].filter((column) => quotes.has("quotes", column));
86652
+ const headerDiscount = quoteDiscounts.length > 0 && quoteDiscounts.every(has);
86653
+ const issuedDeposits = (alias) => `${originIs(alias)} and ${isDeposit(alias) === "" ? "false" : `(${isDeposit(alias)})`} and ${st(`${alias}.${i("status")}`, ["draft", "void"], true)}`;
86654
+ const discount = headerDiscount ? `
86655
+ if ${n.appTotals || !deposits ? "true" : `not exists (select 1 from ${t("invoices")} d where ${issuedDeposits("d")})`} then
86656
+ v_header := jsonb_build_object(${quoteDiscounts.map((column) => `${sqlString(column)}, v_quote.${q(column)}${column === "discountAmount" ? "::text" : ""}`).join(", ")});
86657
+ else${discountLines === "" ? "\n null;" : discountLines.replaceAll("\n", "\n ")}
86658
+ end if;` : discountLines;
86659
+ const party = (kind) => (kind === "company" ? company : contact) && quotes.has("quotes", `${kind}Type`) && quotes.has("quotes", `${kind}Id`) ? `case when v_quote.${q(`${kind}Id`)} is null then null else jsonb_build_object('type', v_quote.${q(`${kind}Type`)}, 'id', v_quote.${q(`${kind}Id`)}) end` : "null";
86660
+ const create = `${fn("create_invoice")}(v_quote.${q("tenant")}, jsonb_build_object(
86661
+ 'title', v_quote.${q("title")}, 'currency', v_quote.${q("currency")}, 'depositBps', ${has("depositBps") ? "invoice_from_quote.deposit_bps" : "null"},${has("depositAmount") ? " 'depositAmount', invoice_from_quote.deposit_amount::text," : ""}${has("pricesIncludeTax") ? ` 'pricesIncludeTax', ${inclusive},` : ""}
86662
+ 'company', ${party("company")},
86663
+ 'contact', ${party("contact")},
86664
+ 'origin', jsonb_build_object('type', 'quote', 'id', v_quote.${q("id")}::text))${headerDiscount ? " || v_header" : ""}${headerFieldsSql}, v_lines)`;
86665
+ const amountLine = amountDeposits ? `
86666
+ elsif invoice_from_quote.deposit_amount is not null then
86667
+ v_lines := jsonb_build_array(jsonb_build_object(
86668
+ 'description', 'Deposit of ' || v_quote.${q("identifier")},
86669
+ 'quantity', 1,
86670
+ 'unitAmount', (case when ${inclusive} or v_quote.${q("total")} = 0 then invoice_from_quote.deposit_amount
86671
+ else round(invoice_from_quote.deposit_amount::numeric * v_quote.${q("subtotal")} / v_quote.${q("total")})::bigint end)::text,
86672
+ 'taxRateBps', ${blendedRate}));` : "";
86673
+ const body = () => `
86674
+ if invoice_from_quote.deposit_bps is null${amountDeposits ? " and invoice_from_quote.deposit_amount is null" : ""} then
86675
+ select * into v_row from ${t("invoices")} x
86676
+ where ${originIs("x")}
86677
+ and ${notDeposit("x")}${st(`x.${i("status")}`, ["void"], true)} and ${kd(`x.${i("kind")}`, ["invoice"])}
86678
+ limit 1;
86679
+ if v_row.${i("id")} is not null then
86680
+ return ${row("v_row")};
86681
+ end if;
86682
+ select coalesce(jsonb_agg(jsonb_build_object('description', x.${ql("description")}, 'quantity', x.${ql("quantity")}${declared(quotes, "lines", "periods") ? ` * coalesce(x.${ql("periods")}, 1)` : ""}, 'unitAmount', x.${ql("unitAmount")}::text,
86683
+ 'discountBps', ${lineColumn(quotes, "lines", "x", "discountBps")}, 'taxRateBps', ${lineColumn(quotes, "lines", "x", "taxRateBps")}, 'taxCode', ${lineColumn(quotes, "lines", "x", "taxCode")},
86684
+ 'product', case when ${lineColumn(quotes, "lines", "x", "productType")} is null then null else jsonb_build_object('type', ${lineColumn(quotes, "lines", "x", "productType")}, 'id', ${lineColumn(quotes, "lines", "x", "productId")}) end${lineFieldsSql}
86685
+ ) order by x.${ql("position")}), '[]'::jsonb) into v_lines
86686
+ from ${quotes.table("lines")} x where x.${ql("parent")} = v_quote.${q("id")} and ${countedLine(quotes, "lines", "x")};${discount}${deposits ? `
86687
+ select v_lines || coalesce(jsonb_agg(jsonb_build_object('description', 'Deposit ' || d.${i("identifier")}, 'quantity', 1, 'unitAmount', (-(case when ${inclusive} then d.${i("total")} else d.${i("subtotal")} end))::text,
86688
+ 'taxRateBps', case when d.${i("subtotal")} = 0 then 0 else round(d.${i("taxTotal")} * 10000.0 / d.${i("subtotal")})::integer end)), '[]'::jsonb)
86689
+ into v_lines
86690
+ from ${t("invoices")} d
86691
+ where ${issuedDeposits("d")};` : ""}${amountLine}
86692
+ else
86693
+ v_lines := jsonb_build_array(jsonb_build_object(
86694
+ 'description', 'Deposit ' || (invoice_from_quote.deposit_bps / 100.0)::text || '% of ' || v_quote.${q("identifier")},
86695
+ 'quantity', 1,
86696
+ 'unitAmount', round(${base("v_quote")}::numeric * invoice_from_quote.deposit_bps / 10000)::bigint::text,
86697
+ 'taxRateBps', ${blendedRate}));
86698
+ end if;
86699
+ v_row := null;${kind === void 0 ? `
86700
+ return ${create};` : `
86701
+ v_made := ${create};
86702
+ if invoice_from_quote.deposit_bps is not null or invoice_from_quote.deposit_amount is not null then
86703
+ update ${t("invoices")} x set ${i("kind")} = ${ctx.cast("invoices", "kind", sqlString(kind))} where x.${i("id")} = (v_made ->> 'id')::uuid;
86704
+ return (select ${row("x")} from ${t("invoices")} x where x.${i("id")} = (v_made ->> 'id')::uuid);
86705
+ end if;
86706
+ return v_made;`}`;
86707
+ return `
86708
+ -- An invoice from an accepted quote. With deposit_bps (2000 for 20%) it is
86709
+ -- a deposit invoice for that share of the quote${amountDeposits ? ", and with deposit_amount\n-- one for that amount, tax included" : ""}; without, the full invoice,
86710
+ -- which subtracts the deposits already issued and is made once per quote.${headerDiscount ? "\n-- The quote's document discount stays on the invoice's header." : ""}
86711
+ drop function if exists ${fn("invoice_from_quote")}(uuid, integer);
86712
+ create or replace function ${fn("invoice_from_quote")}(quote uuid, deposit_bps integer, deposit_amount bigint default null)
86713
+ returns jsonb
86714
+ language plpgsql
86715
+ security definer
86716
+ set search_path = ''
86717
+ as $$
86718
+ declare
86719
+ v_quote ${quotes.table("quotes")};
86720
+ v_row ${t("invoices")};
86721
+ v_lines jsonb;${headerDiscount ? "\n v_header jsonb := '{}'::jsonb;" : ""}${kind === void 0 ? "" : "\n v_made jsonb;"}
86722
+ begin
86723
+ select * into v_quote from ${quotes.table("quotes")} x where x.${q("id")} = invoice_from_quote.quote;
86724
+ if v_quote.${q("id")} is null or not (${n.service} or ${ctx.scope.can(`v_quote.${q("tenant")}`, n.create)}) then
86725
+ ${fail$1("INVOICE_ORIGIN_NOT_FOUND", "no such quote you can invoice", "P0002")}
86726
+ end if;
86727
+ if ${quotes.is("quotes", "status", `v_quote.${q("status")}`, ["accepted"], true)} then
86728
+ ${fail$1("INVOICE_QUOTE_NOT_ACCEPTED", "only an accepted quote is invoiced", "55000")}
86729
+ end if;
86730
+ if invoice_from_quote.deposit_bps is not null and (invoice_from_quote.deposit_bps <= 0 or invoice_from_quote.deposit_bps >= 10000) then
86731
+ ${fail$1("INVOICE_DEPOSIT_INVALID", "a deposit is between 0 and 100 percent", "22023")}
86732
+ end if;
86733
+ if invoice_from_quote.deposit_bps is not null and invoice_from_quote.deposit_amount is not null then
86734
+ ${fail$1("INVOICE_DEPOSIT_INVALID", "a deposit is a share (deposit_bps) or an amount (deposit_amount), not both", "22023")}
86735
+ end if;
86736
+ if invoice_from_quote.deposit_amount is not null and (invoice_from_quote.deposit_amount <= 0 or invoice_from_quote.deposit_amount > v_quote.${q("total")}) then
86737
+ ${fail$1("INVOICE_DEPOSIT_INVALID", "a deposit amount is positive and at most the quote's total", "22023")}
86738
+ end if;${refuse(bpsDeposits, "invoice_from_quote.deposit_bps", "DEPOSIT", "deposit column")}${refuse(amountDeposits, "invoice_from_quote.deposit_amount", "DEPOSIT", "deposit amount column")}${origin === void 0 ? `
86739
+ ${fail$1("INVOICE_ORIGIN_UNSUPPORTED", "this invoices table has no origin columns, so a quote can't be invoiced once", "22023")}` : body()}
86740
+ end;
86741
+ $$;
86742
+ ${userGrant(`${fn("invoice_from_quote")}(uuid, integer, bigint)`)}
86743
+ `;
86744
+ }
86326
86745
  // src/sql/modules/invoices-functions.ts
86746
+ /**
86747
+ * Invoice columns a config opts into by naming them in
86748
+ * `blocks.invoices.columns.invoices`, so app tables made before them keep
86749
+ * working: a fixed deposit and a header discount.
86750
+ */
86751
+ const OPT_IN = [
86752
+ "depositAmount",
86753
+ "discountBps",
86754
+ "discountAmount"
86755
+ ];
86756
+ /** Whether the invoices table has the opt-in column `logical`. */
86757
+ function invoiceOptIn(ctx, logical) {
86758
+ return typeof ctx.config.columns["invoices"]?.[logical] === "string" && ctx.has("invoices", logical);
86759
+ }
86327
86760
  /** `options.chargeExtraColumns`: app columns of the charges table. */
86328
86761
  const chargeExtraColumns = (ctx) => ctx.hasTable("charges") ? ctx.extraColumns("charges", ["fields"], "chargeExtraColumns") : [];
86329
86762
  /**
@@ -86356,7 +86789,7 @@ function invoiceFunctions(ctx, n) {
86356
86789
  const company = invoiceParty(ctx, "company");
86357
86790
  const contact = invoiceParty(ctx, "contact");
86358
86791
  const origin = invoiceParty(ctx, "origin");
86359
- const has = (logical) => ctx.has("invoices", logical);
86792
+ const has = (logical) => OPT_IN.includes(logical) ? invoiceOptIn(ctx, logical) : ctx.has("invoices", logical);
86360
86793
  const charges = ctx.hasTable("charges");
86361
86794
  const ch = (column) => c("charges", column);
86362
86795
  const physical = (logical) => ctx.colName("invoices", logical);
@@ -86379,7 +86812,9 @@ function invoiceFunctions(ctx, n) {
86379
86812
  "number",
86380
86813
  "paidTotal",
86381
86814
  "creditedTotal",
86382
- ...Object.keys(TOTAL_COLUMNS)
86815
+ ...Object.keys(TOTAL_COLUMNS),
86816
+ "depositAmount",
86817
+ "discountAmount"
86383
86818
  ].filter(has);
86384
86819
  const int8 = amounts.map(i);
86385
86820
  const int8Text8 = Object.fromEntries(amounts.map((logical) => [logical, (value) => `${value}::text`]));
@@ -86447,10 +86882,21 @@ function invoiceFunctions(ctx, n) {
86447
86882
  returning * into ${alias};`;
86448
86883
  const keep = (logical, value, key) => has(logical) ? `,\n ${i(logical)} = case when update_invoice.attrs ? ${sqlString(key)} then ${value} else x.${i(logical)} end` : "";
86449
86884
  const relations = ctx.installed("relations") ? ctx.of("relations") : void 0;
86885
+ const discounts = has("discountBps") || has("discountAmount");
86886
+ const recountKeys = [
86887
+ "pricesIncludeTax",
86888
+ "discountBps",
86889
+ "discountAmount"
86890
+ ].filter(has);
86891
+ const headerRefusals = (attrs) => [
86892
+ refuse(has("depositAmount"), `${attrs} ->> 'depositAmount'`, "DEPOSIT", "deposit amount column"),
86893
+ refuse(has("discountBps"), `nullif(${attrs} ->> 'discountBps', '0')`, "DISCOUNT", "discount column"),
86894
+ refuse(has("discountAmount"), `nullif(${attrs} ->> 'discountAmount', '0')`, "DISCOUNT", "discount amount column")
86895
+ ].join("");
86450
86896
  const updateInvoiceSql = () => `
86451
86897
  -- Changes a draft's header. attrs: title, company and contact ({ type, id },
86452
86898
  -- null clears), termsDays, note, depositBps, pricesIncludeTax and the extra
86453
- -- columns by name. A key left out keeps its value.
86899
+ -- columns by name${discounts ? ", and the header discount (discountBps, discountAmount)" : ""}. A key left out keeps its value.
86454
86900
  create or replace function ${fn("update_invoice")}(invoice uuid, attrs jsonb)
86455
86901
  returns jsonb
86456
86902
  language plpgsql
@@ -86474,17 +86920,17 @@ begin
86474
86920
  if jsonb_typeof(update_invoice.attrs) is distinct from 'object'
86475
86921
  or (update_invoice.attrs ? 'title' and nullif(trim(update_invoice.attrs ->> 'title'), '') is null) then
86476
86922
  ${fail$1("INVOICE_ATTRS_INVALID", "attrs is an object, and a title isn't empty", "22023")}
86477
- end if;${checkParty("COMPANY", "v_company_type", "v_company_id", `v_row.${i("tenant")}`)}${checkParty("CONTACT", "v_contact_type", "v_contact_id", `v_row.${i("tenant")}`)}${refuse(has("note"), "update_invoice.attrs ->> 'note'", "NOTE", "note column")}${refuse(has("depositBps"), "update_invoice.attrs ->> 'depositBps'", "DEPOSIT", "deposit column")}${refuse(has("pricesIncludeTax"), "nullif(update_invoice.attrs ->> 'pricesIncludeTax', 'false')", "PRICING", "prices_include_tax column")}
86923
+ end if;${checkParty("COMPANY", "v_company_type", "v_company_id", `v_row.${i("tenant")}`)}${checkParty("CONTACT", "v_contact_type", "v_contact_id", `v_row.${i("tenant")}`)}${refuse(has("note"), "update_invoice.attrs ->> 'note'", "NOTE", "note column")}${refuse(has("depositBps"), "update_invoice.attrs ->> 'depositBps'", "DEPOSIT", "deposit column")}${refuse(has("pricesIncludeTax"), "nullif(update_invoice.attrs ->> 'pricesIncludeTax', 'false')", "PRICING", "prices_include_tax column")}${headerRefusals("update_invoice.attrs")}
86478
86924
  begin
86479
86925
  update ${t("invoices")} x set
86480
- ${i("title")} = case when update_invoice.attrs ? 'title' then trim(update_invoice.attrs ->> 'title') else x.${i("title")} end${keep("companyType", "case when v_company_id is null then null else v_company_type end", "company")}${company === void 0 ? "" : keep("companyId", partyId("company", "v_company_id"), "company")}${keep("contactType", "case when v_contact_id is null then null else v_contact_type end", "contact")}${contact === void 0 ? "" : keep("contactId", partyId("contact", "v_contact_id"), "contact")}${keep("termsDays", "(update_invoice.attrs ->> 'termsDays')::integer", "termsDays")}${keep("note", "update_invoice.attrs ->> 'note'", "note")}${keep("depositBps", "(update_invoice.attrs ->> 'depositBps')::integer", "depositBps")}${keep("pricesIncludeTax", "coalesce((update_invoice.attrs ->> 'pricesIncludeTax')::boolean, false)", "pricesIncludeTax")},
86926
+ ${i("title")} = case when update_invoice.attrs ? 'title' then trim(update_invoice.attrs ->> 'title') else x.${i("title")} end${keep("companyType", "case when v_company_id is null then null else v_company_type end", "company")}${company === void 0 ? "" : keep("companyId", partyId("company", "v_company_id"), "company")}${keep("contactType", "case when v_contact_id is null then null else v_contact_type end", "contact")}${contact === void 0 ? "" : keep("contactId", partyId("contact", "v_contact_id"), "contact")}${keep("termsDays", "(update_invoice.attrs ->> 'termsDays')::integer", "termsDays")}${keep("note", "update_invoice.attrs ->> 'note'", "note")}${keep("depositBps", "(update_invoice.attrs ->> 'depositBps')::integer", "depositBps")}${keep("pricesIncludeTax", "coalesce((update_invoice.attrs ->> 'pricesIncludeTax')::boolean, false)", "pricesIncludeTax")}${keep("depositAmount", "(update_invoice.attrs ->> 'depositAmount')::bigint", "depositAmount")}${keep("discountBps", "coalesce((update_invoice.attrs ->> 'discountBps')::integer, 0)", "discountBps")}${keep("discountAmount", "coalesce((update_invoice.attrs ->> 'discountAmount')::bigint, 0)", "discountAmount")},
86481
86927
  ${i("updatedAt")} = now()${updateExtraColumns(t("invoices"), n.extras, "update_invoice.attrs")}
86482
86928
  where x.${i("id")} = v_row.${i("id")}
86483
86929
  returning * into v_row;
86484
- exception when check_violation or invalid_text_representation or not_null_violation then
86930
+ exception when check_violation or invalid_text_representation or not_null_violation${discounts || has("depositAmount") ? " or numeric_value_out_of_range" : ""} then
86485
86931
  ${fail$1("INVOICE_ATTRS_INVALID", "an invoice field has an invalid value", "22023")}
86486
- end;${n.appTotals || !has("pricesIncludeTax") ? "" : `
86487
- if update_invoice.attrs ? 'pricesIncludeTax' then
86932
+ end;${n.appTotals || recountKeys.length === 0 ? "" : `
86933
+ if ${recountKeys.map((key) => `update_invoice.attrs ? ${sqlString(key)}`).join(" or ")} then
86488
86934
  perform ${fn("set_invoice_lines_recount")}(v_row.${i("id")});
86489
86935
  end if;`}
86490
86936
  ${record("invoice.updated", "v_row")}
@@ -86521,84 +86967,16 @@ end;
86521
86967
  $$;
86522
86968
  ${userGrant(`${fn("delete_invoice")}(uuid)`)}
86523
86969
  `;
86524
- const quotes = ctx.installed("quotes") ? ctx.of("quotes") : void 0;
86525
- const fromQuote = quotes === void 0 ? "" : (() => {
86526
- const q = (column) => quotes.col("quotes", column);
86527
- const ql = (column) => quotes.col("lines", column);
86528
- const deposits = has("depositBps");
86529
- const inclusive = has("pricesIncludeTax") && quotes.has("quotes", "pricesIncludeTax") ? `v_quote.${q("pricesIncludeTax")}` : "false";
86530
- const base = (alias) => `case when ${inclusive} then ${alias}.${q("total")} else ${alias}.${q("subtotal")} end`;
86531
- const taxLines = quotes.hasTable("taxLines") ? (column) => quotes.col("taxLines", column) : void 0;
86532
- const discountLines = taxLines !== void 0 && quotes.has("taxLines", "discount") ? `
86533
- select v_lines || coalesce(jsonb_agg(jsonb_build_object('description', 'Discount', 'quantity', 1, 'unitAmount', (-x.${taxLines("discount")})::text,
86534
- 'taxRateBps', x.${taxLines("taxRateBps")}, 'taxCode', ${quotes.has("taxLines", "taxCode") ? `x.${taxLines("taxCode")}` : "null"}) order by x.${taxLines("taxRateBps")}), '[]'::jsonb)
86535
- into v_lines
86536
- from ${quotes.table("taxLines")} x where x.${taxLines("parent")} = v_quote.${q("id")} and x.${taxLines("discount")} <> 0;` : "";
86537
- const party = (kind) => (kind === "company" ? company : contact) && quotes.has("quotes", `${kind}Type`) && quotes.has("quotes", `${kind}Id`) ? `case when v_quote.${q(`${kind}Id`)} is null then null else jsonb_build_object('type', v_quote.${q(`${kind}Type`)}, 'id', v_quote.${q(`${kind}Id`)}) end` : "null";
86538
- const originIs = (alias) => `${origin === "pair" ? `${alias}.${i("originType")} = 'quote' and ` : ""}${alias}.${i("originId")}::text = v_quote.${q("id")}::text`;
86539
- const body = () => `
86540
- if invoice_from_quote.deposit_bps is null then
86541
- select * into v_row from ${t("invoices")} x
86542
- where ${originIs("x")}
86543
- and ${deposits ? `x.${i("depositBps")} is null and ` : ""}${st(`x.${i("status")}`, ["void"], true)} and ${kd(`x.${i("kind")}`, ["invoice"])}
86544
- limit 1;
86545
- if v_row.${i("id")} is not null then
86546
- return ${row("v_row")};
86547
- end if;
86548
- select coalesce(jsonb_agg(jsonb_build_object('description', x.${ql("description")}, 'quantity', x.${ql("quantity")}${declared(quotes, "lines", "periods") ? ` * coalesce(x.${ql("periods")}, 1)` : ""}, 'unitAmount', x.${ql("unitAmount")}::text,
86549
- 'discountBps', ${lineColumn(quotes, "lines", "x", "discountBps")}, 'taxRateBps', ${lineColumn(quotes, "lines", "x", "taxRateBps")}, 'taxCode', ${lineColumn(quotes, "lines", "x", "taxCode")},
86550
- 'product', case when ${lineColumn(quotes, "lines", "x", "productType")} is null then null else jsonb_build_object('type', ${lineColumn(quotes, "lines", "x", "productType")}, 'id', ${lineColumn(quotes, "lines", "x", "productId")}) end
86551
- ) order by x.${ql("position")}), '[]'::jsonb) into v_lines
86552
- from ${quotes.table("lines")} x where x.${ql("parent")} = v_quote.${q("id")} and ${countedLine(quotes, "lines", "x")};${discountLines}${deposits ? `
86553
- select v_lines || coalesce(jsonb_agg(jsonb_build_object('description', 'Deposit ' || d.${i("identifier")}, 'quantity', 1, 'unitAmount', (-(case when ${inclusive} then d.${i("total")} else d.${i("subtotal")} end))::text,
86554
- 'taxRateBps', case when d.${i("subtotal")} = 0 then 0 else round(d.${i("taxTotal")} * 10000.0 / d.${i("subtotal")})::integer end)), '[]'::jsonb)
86555
- into v_lines
86556
- from ${t("invoices")} d
86557
- where ${originIs("d")} and d.${i("depositBps")} is not null and ${st(`d.${i("status")}`, ["draft", "void"], true)};` : ""}
86558
- else
86559
- v_lines := jsonb_build_array(jsonb_build_object(
86560
- 'description', 'Deposit ' || (invoice_from_quote.deposit_bps / 100.0)::text || '% of ' || v_quote.${q("identifier")},
86561
- 'quantity', 1,
86562
- 'unitAmount', round(${base("v_quote")}::numeric * invoice_from_quote.deposit_bps / 10000)::bigint::text,
86563
- 'taxRateBps', case when v_quote.${q("subtotal")} = 0 then 0 else round(v_quote.${q("taxTotal")} * 10000.0 / v_quote.${q("subtotal")})::integer end));
86564
- end if;
86565
- v_row := null;
86566
- return ${fn("create_invoice")}(v_quote.${q("tenant")}, jsonb_build_object(
86567
- 'title', v_quote.${q("title")}, 'currency', v_quote.${q("currency")}, 'depositBps', invoice_from_quote.deposit_bps,${has("pricesIncludeTax") ? ` 'pricesIncludeTax', ${inclusive},` : ""}
86568
- 'company', ${party("company")},
86569
- 'contact', ${party("contact")},
86570
- 'origin', jsonb_build_object('type', 'quote', 'id', v_quote.${q("id")}::text)), v_lines);`;
86571
- return `
86572
- -- An invoice from an accepted quote. With deposit_bps (2000 for 20%) it is
86573
- -- a deposit invoice for that share of the quote; without, the full invoice,
86574
- -- which subtracts the deposits already issued and is made once per quote.
86575
- create or replace function ${fn("invoice_from_quote")}(quote uuid, deposit_bps integer)
86576
- returns jsonb
86577
- language plpgsql
86578
- security definer
86579
- set search_path = ''
86580
- as $$
86581
- declare
86582
- v_quote ${quotes.table("quotes")};
86583
- v_row ${t("invoices")};
86584
- v_lines jsonb;
86585
- begin
86586
- select * into v_quote from ${quotes.table("quotes")} x where x.${q("id")} = invoice_from_quote.quote;
86587
- if v_quote.${q("id")} is null or not (${n.service} or ${ctx.scope.can(`v_quote.${q("tenant")}`, n.create)}) then
86588
- ${fail$1("INVOICE_ORIGIN_NOT_FOUND", "no such quote you can invoice", "P0002")}
86589
- end if;
86590
- if ${quotes.is("quotes", "status", `v_quote.${q("status")}`, ["accepted"], true)} then
86591
- ${fail$1("INVOICE_QUOTE_NOT_ACCEPTED", "only an accepted quote is invoiced", "55000")}
86592
- end if;
86593
- if invoice_from_quote.deposit_bps is not null and (invoice_from_quote.deposit_bps <= 0 or invoice_from_quote.deposit_bps >= 10000) then
86594
- ${fail$1("INVOICE_DEPOSIT_INVALID", "a deposit is between 0 and 100 percent", "22023")}
86595
- end if;${refuse(deposits, "invoice_from_quote.deposit_bps", "DEPOSIT", "deposit column")}${origin === void 0 ? `
86596
- ${fail$1("INVOICE_ORIGIN_UNSUPPORTED", "this invoices table has no origin columns, so a quote can't be invoiced once", "22023")}` : body()}
86597
- end;
86598
- $$;
86599
- ${userGrant(`${fn("invoice_from_quote")}(uuid, integer)`)}
86600
- `;
86601
- })();
86970
+ const fromQuote = invoiceFromQuote(ctx, n, {
86971
+ has,
86972
+ row,
86973
+ refuse,
86974
+ st,
86975
+ kd,
86976
+ origin,
86977
+ company: company !== void 0,
86978
+ contact: contact !== void 0
86979
+ });
86602
86980
  const chargeColumns = [
86603
86981
  ch("tenant"),
86604
86982
  ch("invoice"),
@@ -86620,11 +86998,13 @@ ${userGrant(`${fn("invoice_from_quote")}(uuid, integer)`)}
86620
86998
  const writeOffReason = typeof ctx.config.columns["invoices"]?.["writeOffReason"] === "string" && ctx.has("invoices", "writeOffReason");
86621
86999
  const addCharge = charges ? `
86622
87000
  ${chargeFields.drop(fn("add_invoice_charge"), "uuid, bigint, text, text")}
87001
+ drop function if exists ${fn("add_invoice_charge")}(uuid, bigint, text, text${chargeFields.type});
86623
87002
  -- Adds a charge on top of an issued invoice's total, such as collection
86624
87003
  -- costs or a late fee, in the invoice's currency. It raises the balance, so
86625
87004
  -- 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})
87005
+ -- charge's extra columns (options.chargeExtraColumns). actor: who added it,
87006
+ -- for the state machine's history.
87007
+ create or replace function ${fn("add_invoice_charge")}(invoice uuid, amount bigint, currency text, description text${chargeFields.param}, actor jsonb default null)
86628
87008
  returns jsonb
86629
87009
  language plpgsql
86630
87010
  security definer
@@ -86651,6 +87031,7 @@ begin
86651
87031
  if upper(add_invoice_charge.currency) is distinct from v_row.${i("currency")} then
86652
87032
  ${fail$1("INVOICE_CURRENCY_MISMATCH", "a charge must be in the invoice's currency", "22023")}
86653
87033
  end if;
87034
+ ${transitionActorSql("add_invoice_charge.actor", "INVOICE_ACTOR_INVALID")}
86654
87035
  insert into ${t("charges")} (${chargeColumns.join(", ")}${chargeExtras.columns})
86655
87036
  values (${chargeValues.join(", ")}${chargeExtras.values})
86656
87037
  returning ${ch("id")} into v_charge;${settle("v_row")}
@@ -86658,9 +87039,10 @@ begin
86658
87039
  return ${row("v_row")};
86659
87040
  end;
86660
87041
  $$;
86661
- ${userGrant(`${fn("add_invoice_charge")}(uuid, bigint, text, text${chargeFields.type})`)}
87042
+ ${userGrant(`${fn("add_invoice_charge")}(uuid, bigint, text, text${chargeFields.type}, jsonb)`)}
86662
87043
 
86663
- create or replace function ${fn("remove_invoice_charge")}(charge uuid)
87044
+ drop function if exists ${fn("remove_invoice_charge")}(uuid);
87045
+ create or replace function ${fn("remove_invoice_charge")}(charge uuid, actor jsonb default null)
86664
87046
  returns jsonb
86665
87047
  language plpgsql
86666
87048
  security definer
@@ -86683,19 +87065,20 @@ begin
86683
87065
  ], true)} then
86684
87066
  ${fail$1("INVOICE_NOT_CHARGEABLE", "only an issued invoice changes its charges", "55000")}
86685
87067
  end if;
87068
+ ${transitionActorSql("remove_invoice_charge.actor", "INVOICE_ACTOR_INVALID")}
86686
87069
  delete from ${t("charges")} c where c.${ch("id")} = remove_invoice_charge.charge
86687
87070
  returning c.${ch("amount")} into v_amount;${settle("v_row")}
86688
87071
  ${record("invoice.charge_removed", "v_row", `, 'chargeId', remove_invoice_charge.charge, 'amount', v_amount::text, 'balance', ${balance("v_row")}::text`, true)}
86689
87072
  return ${row("v_row")};
86690
87073
  end;
86691
87074
  $$;
86692
- ${userGrant(`${fn("remove_invoice_charge")}(uuid)`)}
87075
+ ${userGrant(`${fn("remove_invoice_charge")}(uuid, jsonb)`)}
86693
87076
  ` : "";
86694
87077
  const kindTable = (kind) => `(select * from ${t("invoices")} k where ${kd(`k.${i("kind")}`, [kind])})`;
86695
87078
  return `
86696
87079
  -- Creates a draft invoice. attrs: title (required), currency, company and
86697
87080
  -- contact ({ type, id }), termsDays, note, origin ({ type, id }) and the
86698
- -- extra columns by name.
87081
+ -- extra columns by name${discounts || has("depositAmount") ? ", with depositAmount and the header discount (discountBps,\n-- discountAmount) when the table has them" : ""}.
86699
87082
  create or replace function ${fn("create_invoice")}(tenant ${ctx.idType}, attrs jsonb, lines jsonb)
86700
87083
  returns jsonb
86701
87084
  language plpgsql
@@ -86717,21 +87100,24 @@ begin
86717
87100
  end if;${checkParty("COMPANY", "v_company_type", "v_company_id", "create_invoice.tenant")}${checkParty("CONTACT", "v_contact_type", "v_contact_id", "create_invoice.tenant")}${refuse(has("note"), "create_invoice.attrs ->> 'note'", "NOTE", "note column")}${refuse(origin !== void 0, "(create_invoice.attrs -> 'origin' ->> 'id')", "ORIGIN", "origin columns")}${origin === "fixed" ? `
86718
87101
  if create_invoice.attrs -> 'origin' ->> 'id' is not null and (create_invoice.attrs -> 'origin' ->> 'type') is distinct from 'quote' then
86719
87102
  ${fail$1("INVOICE_ORIGIN_UNSUPPORTED", "this invoices table takes only a quote as the origin", "22023")}
86720
- end if;` : ""}${refuse(has("depositBps"), "create_invoice.attrs ->> 'depositBps'", "DEPOSIT", "deposit column")}${refuse(has("pricesIncludeTax"), "nullif(create_invoice.attrs ->> 'pricesIncludeTax', 'false')", "PRICING", "prices_include_tax column")}
87103
+ end if;` : ""}${refuse(has("depositBps"), "create_invoice.attrs ->> 'depositBps'", "DEPOSIT", "deposit column")}${refuse(has("pricesIncludeTax"), "nullif(create_invoice.attrs ->> 'pricesIncludeTax', 'false')", "PRICING", "prices_include_tax column")}${headerRefusals("create_invoice.attrs")}
86721
87104
  begin
86722
87105
  insert into ${t("invoices")} (${i("tenant")}, ${i("title")}${also("companyType")}${also("companyId")}${also("contactType")}${also("contactId")}, ${i("currency")},
86723
- ${i("termsDays")}${also("note")}${also("originType")}${also("originId")}${also("depositBps")}${also("pricesIncludeTax")}${also("createdBy")}${insertExtraColumns(t("invoices"), n.extras, "create_invoice.attrs").columns})
87106
+ ${i("termsDays")}${also("note")}${also("originType")}${also("originId")}${also("depositBps")}${also("depositAmount")}${also("discountBps")}${also("discountAmount")}${also("pricesIncludeTax")}${also("createdBy")}${insertExtraColumns(t("invoices"), n.extras, "create_invoice.attrs").columns})
86724
87107
  values (${valueLines(" ", ["create_invoice.tenant", "trim(create_invoice.attrs ->> 'title')"], [present("companyType", "case when v_company_id is null then null else v_company_type end"), company === void 0 ? void 0 : partyId("company", "v_company_id")], [present("contactType", "case when v_contact_id is null then null else v_contact_type end"), contact === void 0 ? void 0 : partyId("contact", "v_contact_id")], ["upper(coalesce(create_invoice.attrs ->> 'currency', 'EUR'))", `case when create_invoice.attrs ? 'termsDays' then (create_invoice.attrs ->> 'termsDays')::integer else ${String(n.termsDays)} end`], [
86725
87108
  present("note", "create_invoice.attrs ->> 'note'"),
86726
87109
  present("originType", "create_invoice.attrs -> 'origin' ->> 'type'"),
86727
87110
  present("originId", partyId("origin", "create_invoice.attrs -> 'origin' ->> 'id'"))
86728
87111
  ], [
86729
87112
  present("depositBps", "(create_invoice.attrs ->> 'depositBps')::integer"),
87113
+ present("depositAmount", "(create_invoice.attrs ->> 'depositAmount')::bigint"),
87114
+ present("discountBps", "coalesce((create_invoice.attrs ->> 'discountBps')::integer, 0)"),
87115
+ present("discountAmount", "coalesce((create_invoice.attrs ->> 'discountAmount')::bigint, 0)"),
86730
87116
  present("pricesIncludeTax", "coalesce((create_invoice.attrs ->> 'pricesIncludeTax')::boolean, false)"),
86731
87117
  present("createdBy", "auth.uid()")
86732
87118
  ])}${insertExtraColumns(t("invoices"), n.extras, "create_invoice.attrs").values})
86733
87119
  returning * into v_row;
86734
- exception when check_violation or invalid_text_representation then
87120
+ exception when check_violation or invalid_text_representation${discounts || has("depositAmount") ? " or numeric_value_out_of_range" : ""} then
86735
87121
  ${fail$1("INVOICE_ATTRS_INVALID", "an invoice field has an invalid value", "22023")}
86736
87122
  end;
86737
87123
  if create_invoice.lines is not null then
@@ -86757,6 +87143,7 @@ ${updateInvoiceSql()}${lineItemsSql(ctx, {
86757
87143
  frozen: st(`p.${i("status")}`, ["draft"], true),
86758
87144
  extras: n.lineExtras,
86759
87145
  totals: !n.appTotals,
87146
+ parentHas: has,
86760
87147
  positionKey: ctx.flag("linePositionKey", true)
86761
87148
  }, {
86762
87149
  setter: "set_invoice_lines",
@@ -87002,8 +87389,10 @@ $$;
87002
87389
  ${userGrant(`${fn("credit_invoice")}(uuid, jsonb, text)`)}
87003
87390
 
87004
87391
  -- 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)
87392
+ -- error. Its number stays taken. Needs invoices.manage. The reason and actor
87393
+ -- go to the state machine's history.
87394
+ drop function if exists ${fn("void_invoice")}(uuid, text);
87395
+ create or replace function ${fn("void_invoice")}(invoice uuid, reason text, actor jsonb default null)
87007
87396
  returns jsonb
87008
87397
  language plpgsql
87009
87398
  security definer
@@ -87019,18 +87408,23 @@ begin
87019
87408
  if ${st(`v_row.${i("status")}`, ["draft", "issued"], true)} or v_row.${i("paidTotal")} <> 0 or v_row.${i("creditedTotal")} <> 0 then
87020
87409
  ${fail$1("INVOICE_NOT_VOIDABLE", "an invoice with payments or credits is credited, not voided", "55000")}
87021
87410
  end if;
87411
+ ${transitionActorSql("void_invoice.actor", "INVOICE_ACTOR_INVALID")}
87412
+ ${transitionReasonSql("void_invoice.reason")}
87022
87413
  update ${t("invoices")} x set ${i("status")} = ${ctx.value("invoices", "status", "void")}, ${i("voidedAt")} = now(),
87023
87414
  ${has("voidReason") ? `${i("voidReason")} = nullif(trim(void_invoice.reason), ''), ` : ""}${i("updatedAt")} = now()
87024
87415
  where x.${i("id")} = v_row.${i("id")} returning * into v_row;
87416
+ ${transitionReasonSql()}
87025
87417
  ${record("invoice.voided", "v_row", `, 'reason', ${has("voidReason") ? `v_row.${i("voidReason")}` : "nullif(trim(void_invoice.reason), '')"}`, true)}
87026
87418
  return ${row("v_row")};
87027
87419
  end;
87028
87420
  $$;
87029
- ${userGrant(`${fn("void_invoice")}(uuid, text)`)}
87421
+ ${userGrant(`${fn("void_invoice")}(uuid, text, jsonb)`)}
87030
87422
 
87031
- -- Writes an open invoice off as uncollectible. Needs invoices.manage.
87423
+ -- Writes an open invoice off as uncollectible. Needs invoices.manage. The
87424
+ -- reason and actor go to the state machine's history.
87032
87425
  drop function if exists ${fn("write_off_invoice")}(uuid);
87033
- create or replace function ${fn("write_off_invoice")}(invoice uuid, reason text default null)
87426
+ drop function if exists ${fn("write_off_invoice")}(uuid, text);
87427
+ create or replace function ${fn("write_off_invoice")}(invoice uuid, reason text default null, actor jsonb default null)
87034
87428
  returns jsonb
87035
87429
  language plpgsql
87036
87430
  security definer
@@ -87039,19 +87433,25 @@ as $$
87039
87433
  declare
87040
87434
  v_row ${t("invoices")};
87041
87435
  begin
87436
+ ${transitionActorSql("write_off_invoice.actor", "INVOICE_ACTOR_INVALID")}
87437
+ ${transitionReasonSql("write_off_invoice.reason")}
87042
87438
  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
87439
  where x.${i("id")} = write_off_invoice.invoice and ${can("x", n.writeOff)} and ${st(`x.${i("status")}`, ["issued", "partially_paid"])}
87044
87440
  returning * into v_row;
87045
87441
  if v_row.${i("id")} is null then
87046
87442
  ${fail$1("INVOICE_NOT_OPEN", "only an open invoice you can manage is written off", "55000")}
87047
87443
  end if;
87444
+ ${transitionReasonSql()}
87048
87445
  ${record("invoice.uncollected", "v_row", `, 'balance', ${balance("v_row")}::text, 'reason', nullif(trim(write_off_invoice.reason), '')`, true)}
87049
87446
  return ${row("v_row")};
87050
87447
  end;
87051
87448
  $$;
87052
- ${userGrant(`${fn("write_off_invoice")}(uuid, text)`)}
87449
+ ${userGrant(`${fn("write_off_invoice")}(uuid, text, jsonb)`)}
87053
87450
 
87054
- create or replace function ${fn("reverse_invoice_payment")}(payment uuid, reason text default null)
87451
+ -- Reverses a recorded payment. The reason and actor go to the state machine's
87452
+ -- history.
87453
+ drop function if exists ${fn("reverse_invoice_payment")}(uuid, text);
87454
+ create or replace function ${fn("reverse_invoice_payment")}(payment uuid, reason text default null, actor jsonb default null)
87055
87455
  returns jsonb
87056
87456
  language plpgsql
87057
87457
  security definer
@@ -87076,14 +87476,17 @@ begin
87076
87476
  or exists (select 1 from ${ledger.transactions} y where y.${ledger.tx("reverses")} = reverse_invoice_payment.payment) then
87077
87477
  ${fail$1("INVOICE_PAYMENT_REVERSED", "this payment is a reversal or is already reversed", "55000")}
87078
87478
  end if;
87479
+ ${transitionActorSql("reverse_invoice_payment.actor", "INVOICE_ACTOR_INVALID")}
87480
+ ${transitionReasonSql("reverse_invoice_payment.reason")}
87079
87481
  v_amount := ${ledger.paidTotal("v_row")};
87080
87482
  v_reversal := ${ledger.reverse("v_row", "reverse_invoice_payment.payment", "nullif(trim(reverse_invoice_payment.reason), '')")};
87081
87483
  v_amount := v_amount - ${ledger.paidTotal("v_row")};${settle("v_row")}
87484
+ ${transitionReasonSql()}
87082
87485
  ${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
87486
  return ${row("v_row")};
87084
87487
  end;
87085
87488
  $$;
87086
- ${userGrant(`${fn("reverse_invoice_payment")}(uuid, text)`)}
87489
+ ${userGrant(`${fn("reverse_invoice_payment")}(uuid, text, jsonb)`)}
87087
87490
  ${addCharge}
87088
87491
  -- What a tenant is owed in one currency on as_of, by days past due:
87089
87492
  -- not yet due, 1 to 30, 31 to 60, 61 to 90 and over 90. Amounts are text.
@@ -87235,12 +87638,13 @@ const NAMES$56 = {
87235
87638
  "providerPaymentMethods",
87236
87639
  "uniqueNumber",
87237
87640
  "linePositionKey",
87238
- "paymentsAfterWriteOff"
87641
+ "paymentsAfterWriteOff",
87642
+ "depositKind"
87239
87643
  ],
87240
87644
  tables: {
87241
87645
  invoices: {
87242
87646
  name: "invoices",
87243
- app: { unused: (ctx) => typeof ctx.config.columns["invoices"]?.["writeOffReason"] === "string" ? [] : ["writeOffReason"] },
87647
+ app: { unused: (ctx) => ["writeOffReason", ...OPT_IN].filter((column) => typeof ctx.config.columns["invoices"]?.[column] !== "string") },
87244
87648
  lifecycle: {
87245
87649
  tenant: "tenant",
87246
87650
  export: true
@@ -87272,6 +87676,9 @@ const NAMES$56 = {
87272
87676
  originType: "origin_type",
87273
87677
  originId: "origin_id",
87274
87678
  depositBps: "deposit_bps",
87679
+ depositAmount: "deposit_amount",
87680
+ discountBps: "discount_bps",
87681
+ discountAmount: "discount_amount",
87275
87682
  pricesIncludeTax: "prices_include_tax",
87276
87683
  createdBy: "created_by",
87277
87684
  createdAt: "created_at",
@@ -87289,6 +87696,9 @@ const NAMES$56 = {
87289
87696
  "originType",
87290
87697
  "originId",
87291
87698
  "depositBps",
87699
+ "depositAmount",
87700
+ "discountBps",
87701
+ "discountAmount",
87292
87702
  "pricesIncludeTax",
87293
87703
  "createdBy",
87294
87704
  "listTotal",
@@ -87361,6 +87771,12 @@ ${renderPolicy(policy$1({
87361
87771
  })}
87362
87772
  ` : "";
87363
87773
  const column = (logical, definition) => ctx.has("invoices", logical) ? `\n ${i(logical)} ${definition},` : "";
87774
+ const optIn = {
87775
+ depositAmount: (name) => `bigint check (${name} > 0)`,
87776
+ discountBps: (name) => `integer not null default 0 check (${name} >= 0 and ${name} <= 10000)`,
87777
+ discountAmount: (name) => `bigint not null default 0 check (${name} >= 0)`
87778
+ };
87779
+ const added = OPT_IN.filter((logical) => invoiceOptIn(ctx, logical)).map((logical) => `\nalter table ${t("invoices")} add column if not exists ${i(logical)} ${optIn[logical](i(logical))};`).join("");
87364
87780
  const index = (name, columns) => `\ncreate index if not exists ${ctx.naming.rename(name)} on ${t("invoices")} (${columns.map(i).join(", ")});`;
87365
87781
  return `
87366
87782
  create table if not exists ${t("invoices")} (
@@ -87387,7 +87803,7 @@ ${uniqueNumber === false ? "" : ` unique (${i("tenant")}, ${i("kind")}, ${i(uni
87387
87803
  check (${i("status")} <> 'draft' or ${i("number")} is null),
87388
87804
  check (${i("status")} in ('draft', 'void') or ${i("number")} is not null)${company === "pair" ? `,\n check ((${i("companyType")} is null) = (${i("companyId")} is null))` : ""}
87389
87805
  );
87390
- create index if not exists ${ctx.naming.rename("invoices_tenant_status_idx")} on ${t("invoices")} (${i("tenant")}, ${i("status")}, ${i("dueOn")});${origin === void 0 ? "" : index("invoices_origin_idx", origin === "pair" ? ["originType", "originId"] : ["originId"])}${index("invoices_original_idx", ["original"])}${company === void 0 ? "" : index("invoices_company_idx", company === "pair" ? ["companyType", "companyId"] : ["companyId"])}${addExtraColumns(t("invoices"), n.extras)}${uniqueNumber === false ? "" : appUniqueIndex(ctx, "invoices", [
87806
+ ${added === "" ? "" : `${added.slice(1)}\n`}create index if not exists ${ctx.naming.rename("invoices_tenant_status_idx")} on ${t("invoices")} (${i("tenant")}, ${i("status")}, ${i("dueOn")});${origin === void 0 ? "" : index("invoices_origin_idx", origin === "pair" ? ["originType", "originId"] : ["originId"])}${index("invoices_original_idx", ["original"])}${company === void 0 ? "" : index("invoices_company_idx", company === "pair" ? ["companyType", "companyId"] : ["companyId"])}${addExtraColumns(t("invoices"), n.extras)}${uniqueNumber === false ? "" : appUniqueIndex(ctx, "invoices", [
87391
87807
  "tenant",
87392
87808
  "kind",
87393
87809
  uniqueNumber
@@ -87425,6 +87841,17 @@ function invoiceTotals(ctx) {
87425
87841
  if (totals !== "block" && totals !== "app") throw new TypeError("blocks.invoices.options.totals must be \"block\" or \"app\"");
87426
87842
  return totals;
87427
87843
  }
87844
+ /**
87845
+ * `options.depositKind`: the app value of the kind column that marks a deposit
87846
+ * invoice. It must be one the `invoice` label maps to, so the block treats a
87847
+ * deposit invoice as an invoice everywhere else.
87848
+ */
87849
+ function depositKind(ctx) {
87850
+ const kind = ctx.option("depositKind");
87851
+ if (kind === void 0) return;
87852
+ if (typeof kind !== "string" || !ctx.appValues("invoices", "kind", "invoice").includes(kind)) throw new TypeError("blocks.invoices.options.depositKind must be one of the values blocks.invoices.values.invoices.kind.invoice maps to");
87853
+ return kind;
87854
+ }
87428
87855
  function build$55(ctx) {
87429
87856
  if (ctx.mode === "custom") return "";
87430
87857
  const keys = moduleOperations("invoices");
@@ -87465,7 +87892,8 @@ function build$55(ctx) {
87465
87892
  ]),
87466
87893
  lineExtras: lineExtraColumns(ctx),
87467
87894
  chargeExtras: chargeExtraColumns(ctx),
87468
- appTotals: invoiceTotals(ctx) === "app"
87895
+ appTotals: invoiceTotals(ctx) === "app",
87896
+ depositKind: depositKind(ctx)
87469
87897
  };
87470
87898
  return `${schemaPreamble(ctx)}
87471
87899
  -- Invoices an organization sends its own customers: drafts with lines, a
@@ -87533,17 +87961,29 @@ function contract$48(ctx) {
87533
87961
  },
87534
87962
  {
87535
87963
  name: "void_invoice",
87536
- args: ["uuid", "text"],
87964
+ args: [
87965
+ "uuid",
87966
+ "text",
87967
+ "jsonb"
87968
+ ],
87537
87969
  returns: "jsonb"
87538
87970
  },
87539
87971
  {
87540
87972
  name: "write_off_invoice",
87541
- args: ["uuid", "text"],
87973
+ args: [
87974
+ "uuid",
87975
+ "text",
87976
+ "jsonb"
87977
+ ],
87542
87978
  returns: "jsonb"
87543
87979
  },
87544
87980
  {
87545
87981
  name: "reverse_invoice_payment",
87546
- args: ["uuid", "text"],
87982
+ args: [
87983
+ "uuid",
87984
+ "text",
87985
+ "jsonb"
87986
+ ],
87547
87987
  returns: "jsonb"
87548
87988
  },
87549
87989
  ...ctx.hasTable("charges") ? [{
@@ -87553,12 +87993,13 @@ function contract$48(ctx) {
87553
87993
  "bigint",
87554
87994
  "text",
87555
87995
  "text",
87556
- ...extraFieldsArg(chargeExtraColumns(ctx)).contract
87996
+ ...extraFieldsArg(chargeExtraColumns(ctx)).contract,
87997
+ "jsonb"
87557
87998
  ],
87558
87999
  returns: "jsonb"
87559
88000
  }, {
87560
88001
  name: "remove_invoice_charge",
87561
- args: ["uuid"],
88002
+ args: ["uuid", "jsonb"],
87562
88003
  returns: "jsonb"
87563
88004
  }] : [],
87564
88005
  {
@@ -87577,7 +88018,11 @@ function contract$48(ctx) {
87577
88018
  },
87578
88019
  ...ctx.installed("quotes") ? [{
87579
88020
  name: "invoice_from_quote",
87580
- args: ["uuid", "integer"],
88021
+ args: [
88022
+ "uuid",
88023
+ "integer",
88024
+ "bigint"
88025
+ ],
87581
88026
  returns: "jsonb"
87582
88027
  }] : []
87583
88028
  ];
@@ -90199,6 +90644,17 @@ function leavePolicy(ctx) {
90199
90644
  return policySnapshot(policy);
90200
90645
  }
90201
90646
  /**
90647
+ * `options.approvalOwner`: `"employee"` makes the request's employee the
90648
+ * approval's requester and points a manager step at their manager; the default
90649
+ * `"filer"` keeps the user who filed it. Needs `owner: "employee"`.
90650
+ */
90651
+ function leaveApprovalOwner(ctx, employee) {
90652
+ const value = ctx.text("approvalOwner", "filer");
90653
+ if (value !== "filer" && value !== "employee") throw new TypeError(`${WHERE$8}.approvalOwner must be "filer" or "employee"`);
90654
+ if (value === "employee" && !employee) throw new TypeError(`${WHERE$8}.approvalOwner "employee" needs ${WHERE$8}.owner "employee"`);
90655
+ return value;
90656
+ }
90657
+ /**
90202
90658
  * Whether requests keep their decision themselves instead of in the approvals
90203
90659
  * block: `options.approvals: false`, or no approval column.
90204
90660
  */
@@ -90294,6 +90750,15 @@ function leaveContract(ctx) {
90294
90750
  }] : []
90295
90751
  ];
90296
90752
  }
90753
+ /** The final approval of a leave request books it. */
90754
+ const LEAVE_CONTRIBUTES = {
90755
+ "share-links": (own) => [leaveFeedSubject(own), ...leaveTeamFeedSubject(own)],
90756
+ approvals: (own) => leaveStatusMode(own) ? [] : [{
90757
+ subject: LEAVE_REQUEST_SUBJECT,
90758
+ access: "declared",
90759
+ approve: ({ subjectId }) => `perform ${own.fn("approve_leave_request")}(${subjectId}::uuid);`
90760
+ }]
90761
+ };
90297
90762
  // src/sql/modules/leave-ledger.ts
90298
90763
  /** Leave amounts are numeric(8, 2); ledger amounts are hundredths. */
90299
90764
  const SCALE = 100;
@@ -90762,7 +91227,8 @@ const LEAVE_NAMES = {
90762
91227
  "feed",
90763
91228
  "approvals",
90764
91229
  "owner",
90765
- "reapprove"
91230
+ "reapprove",
91231
+ "approvalOwner"
90766
91232
  ],
90767
91233
  tables: {
90768
91234
  types: {
@@ -91164,13 +91630,14 @@ ${parts ? ` and ${existing.first} <= ${halfDays(starts, ends, "v_start", "v
91164
91630
  ` : ""} ) then
91165
91631
  ${fail$1("LEAVE_OVERLAP", "this overlaps another leave request", "23P01")}
91166
91632
  end if;`;
91633
+ const byEmployee = leaveApprovalOwner(ctx, owner.employee) === "employee";
91167
91634
  const openApproval = (tenant) => {
91168
91635
  if (approvals === void 0) return "";
91169
91636
  const open = `
91170
91637
  v_request := ${approvals.fn("open_approval")}(
91171
91638
  ${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")})
91639
+ ${sqlString(policy)}::jsonb${byEmployee ? " || jsonb_build_object('managerOf', v_owner::text)" : ""}, ${or("requests", "v_row", "note")},
91640
+ 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
91641
  );
91175
91642
  update ${requests} x set ${q("approval")} = (v_request ->> 'id')::uuid
91176
91643
  where x.${q("id")} = v_row.${q("id")}
@@ -91618,14 +92085,6 @@ ${userGrant(`${fn("list_leave_requests")}(${listBase}${owner.employee ? ", uuid"
91618
92085
 
91619
92086
  `;
91620
92087
  }
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
92088
  const REQUIRES$2 = [
91630
92089
  "memberships",
91631
92090
  "permissions",
@@ -91633,7 +92092,7 @@ const REQUIRES$2 = [
91633
92092
  "ledger"
91634
92093
  ];
91635
92094
  const LEAVE = {
91636
- contributes: CONTRIBUTES$7,
92095
+ contributes: LEAVE_CONTRIBUTES,
91637
92096
  internal: [
91638
92097
  "leave_available",
91639
92098
  "leave_post",
@@ -113664,7 +114123,10 @@ const NAMES$35 = {
113664
114123
  "lineExtraColumns",
113665
114124
  "lineRates",
113666
114125
  "workingCopy",
113667
- "versionLines"
114126
+ "versionLines",
114127
+ "versionLineExtraColumns",
114128
+ "totals",
114129
+ "resend"
113668
114130
  ],
113669
114131
  tables: {
113670
114132
  quotes: {
@@ -113906,7 +114368,7 @@ create table if not exists ${t("versionLines")} (
113906
114368
  ${vl("quantity")} numeric(18, 4) not null,
113907
114369
  ${vl("unitAmount")} bigint not null,${vlColumn("periods", "integer not null default 1")}${vlColumn("discountBps", "integer not null default 0")}${vlColumn("taxRateBps", "integer not null default 0")}${vlColumn("taxCode", "text")}${vlColumn("section", "text")}${vlColumn("optional", "boolean not null default false")}${vlColumn("selected", "boolean not null default true")}${vlColumn("productType", "text")}${vlColumn("productId", "text")}
113908
114370
  unique (${vl("version")}, ${vl("position")})
113909
- );
114371
+ );${addExtraColumns(t("versionLines"), n.versionLineExtras)}
113910
114372
  ${lockModuleTable(ctx, "versionLines", { read: true })}
113911
114373
  ${renderPolicy(policy$1({
113912
114374
  table: t("versionLines"),
@@ -113965,9 +114427,16 @@ create trigger ${frozen} before update on ${t("versions")}
113965
114427
  for each row execute function better_supabase.${frozen.replaceAll("\"", "")}();
113966
114428
  ${versionLines}${taxLines}`;
113967
114429
  }
114430
+ /** `options.totals`: who keeps a quote's totals. */
114431
+ function quoteTotals(ctx) {
114432
+ const totals = ctx.text("totals", "block");
114433
+ if (totals !== "block" && totals !== "app") throw new TypeError("blocks.quotes.options.totals must be \"block\" or \"app\"");
114434
+ return totals;
114435
+ }
113968
114436
  function build$34(ctx) {
113969
114437
  if (ctx.mode === "custom") return "";
113970
114438
  const keys = moduleOperations("quotes");
114439
+ const finer = (action) => sqlString(ctx.config.permissions[action] ?? ctx.permissionKey("write", keys.write));
113971
114440
  const validDays = ctx.number("validDays", 30);
113972
114441
  if (!Number.isInteger(validDays) || validDays < 1) throw new TypeError("blocks.quotes.options.validDays must be a positive integer");
113973
114442
  const n = {
@@ -113977,6 +114446,9 @@ function build$34(ctx) {
113977
114446
  read: ctx.permission("read", keys.read),
113978
114447
  write: ctx.permission("write", keys.write),
113979
114448
  manage: ctx.permission("manage", keys.manage),
114449
+ send: finer("send"),
114450
+ decide: finer("decide"),
114451
+ withdraw: finer("withdraw"),
113980
114452
  company: ctx.text("company", "company"),
113981
114453
  contact: ctx.text("contact", "person"),
113982
114454
  prefix: ctx.text("prefix", "Q-"),
@@ -113987,7 +114459,10 @@ function build$34(ctx) {
113987
114459
  "token",
113988
114460
  "fields"
113989
114461
  ]),
113990
- lineExtras: lineExtraColumns(ctx)
114462
+ lineExtras: lineExtraColumns(ctx),
114463
+ versionLineExtras: versionLinesOn(ctx) ? ctx.extraColumns("versionLines", [], "versionLineExtraColumns") : [],
114464
+ appTotals: quoteTotals(ctx) === "app",
114465
+ resend: ctx.flag("resend", false)
113991
114466
  };
113992
114467
  return `${schemaPreamble(ctx)}
113993
114468
  -- Quotes: line items, sections, optional lines, discounts and tax per rate,
@@ -114055,7 +114530,7 @@ function contract$32(ctx) {
114055
114530
  },
114056
114531
  {
114057
114532
  name: "portal_quote",
114058
- args: ["uuid"],
114533
+ args: ["uuid", "jsonb"],
114059
114534
  returns: "jsonb"
114060
114535
  },
114061
114536
  {
@@ -134672,6 +135147,8 @@ const TEMPLATES = {
134672
135147
  build: build$9
134673
135148
  };
134674
135149
  // src/sql/modules/time-tracking-approvals.ts
135150
+ /** Timesheets this block submits to approvals. */
135151
+ const TIMESHEET_SUBJECT = "timesheet";
134675
135152
  /**
134676
135153
  * The timesheet functions when weeks go through the approvals block: a
134677
135154
  * submitted week opens an approval request, and the final approval locks it.
@@ -134890,6 +135367,21 @@ $$;
134890
135367
  ${userGrant(`${fn("list_timesheets")}(${ctx.idType}, uuid, text, integer, date)`)}
134891
135368
  `;
134892
135369
  }
135370
+ /** Approvals decides weeks; per employee, the status column follows. */
135371
+ const TIME_TRACKING_CONTRIBUTES = { approvals: (own) => {
135372
+ if (!own.flag("approvals", true)) return [];
135373
+ if (byEmployee(own)) return [{
135374
+ subject: TIMESHEET_SUBJECT,
135375
+ access: "declared",
135376
+ approve: ({ subjectId, comment, approver }) => `perform ${own.fn("timesheet_approval_decided")}(${subjectId}::uuid, true, ${comment}, ${approver});`,
135377
+ reject: ({ subjectId, comment, approver }) => `perform ${own.fn("timesheet_approval_decided")}(${subjectId}::uuid, false, ${comment}, ${approver});`
135378
+ }];
135379
+ return [{
135380
+ subject: TIMESHEET_SUBJECT,
135381
+ access: "declared",
135382
+ approve: ({ subjectId }) => `perform ${own.fn("approve_timesheet")}(${subjectId}::uuid);`
135383
+ }];
135384
+ } };
134893
135385
  // src/sql/modules/time-tracking-rates.ts
134894
135386
  /**
134895
135387
  * The rate's currency is an uppercase three-letter code (the client checks it
@@ -135003,7 +135495,9 @@ function statusTimesheetFunctions(ctx, names) {
135003
135495
  const { entries, timesheets, e, t, read, track, manage, approve } = names;
135004
135496
  const { entryJson, timesheetRecord, forbidden, timesheetNotFound, week } = names;
135005
135497
  const { ended, running, owner } = names;
135498
+ const linked = names.approvals;
135006
135499
  const by = owner.employee;
135500
+ 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
135501
  const ownerVar = by ? "v_owner" : "v_user";
135008
135502
  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
135503
  const ownerParam = by ? ", employee_id uuid default null" : "";
@@ -135046,7 +135540,10 @@ begin
135046
135540
  end if;
135047
135541
  if not ${is("v_sheet", ["submitted"])} then
135048
135542
  ${fail$1("TIMESHEET_NOT_SUBMITTED", "only a submitted week can be decided", "55000")}
135049
- end if;
135543
+ end if;${linked === void 0 ? "" : `
135544
+ if ${pendingApproval("v_sheet")} then
135545
+ ${fail$1("TIMESHEET_IN_APPROVAL", "this week is decided through its approval request", "55000")}
135546
+ end if;`}
135050
135547
  update ${timesheets} s set ${t("status")} = ${value(status)}${status === "approved" ? `, ${t("approvedAt")} = now()` : ""}${decide(name === "reject_timesheet" ? "reject_timesheet.note" : "null")}
135051
135548
  where s.${t("id")} = v_sheet.${t("id")}
135052
135549
  returning * into v_sheet;
@@ -135154,7 +135651,7 @@ ${by ? ` if v_owner is null then
135154
135651
  if ${is("v_sheet", ["approved"])} then
135155
135652
  ${fail$1("TIMESHEET_APPROVED", "this week is already approved", "55000")}
135156
135653
  end if;
135157
- if ${is("v_sheet", ["submitted"])} then
135654
+ if ${is("v_sheet", ["submitted"])}${linked === void 0 ? "" : ` and ${pendingApproval("v_sheet")}`} then
135158
135655
  ${fail$1("TIMESHEET_SUBMITTED", "this week is already waiting for a decision", "55000")}
135159
135656
  end if;
135160
135657
  ${ctx.hook("before_timesheet_submit", [
@@ -135165,7 +135662,13 @@ ${by ? ` if v_owner is null then
135165
135662
  update ${timesheets} s
135166
135663
  set ${t("status")} = ${value("submitted")}, ${t("note")} = submit_timesheet.note, ${t("submittedAt")} = now()${clearDecision}
135167
135664
  where s.${t("id")} = v_sheet.${t("id")}
135168
- returning * into v_sheet;
135665
+ returning * into v_sheet;${linked === void 0 ? "" : `
135666
+ perform ${linked.open}(
135667
+ submit_timesheet.tenant, ${sqlString(linked.subject)}, v_sheet.${t("id")}::text, 'approve',
135668
+ ${sqlString(linked.policy)}::jsonb || jsonb_build_object('managerOf', v_owner::text), submit_timesheet.note,
135669
+ jsonb_build_object('userId', ${owner.userOf("v_owner")}, 'employeeId', v_owner, 'week', v_week),
135670
+ ${owner.userOf("v_owner")}
135671
+ );`}
135169
135672
  ${timesheetRecord("timesheet.submitted", "v_sheet", "submitted a timesheet")}
135170
135673
  ${ctx.hook("after_timesheet_submit", [["uuid", `v_sheet.${t("id")}`]])}
135171
135674
  return ${json("v_sheet")};
@@ -135174,7 +135677,38 @@ $$;
135174
135677
  ${userGrant(`${fn("submit_timesheet")}(${ctx.idType}, date, text${ownerType})`)}
135175
135678
 
135176
135679
  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")}
135680
+ ${decision("approve_timesheet", "approved", "timesheet.approved", "approved a timesheet")}${linked === void 0 ? "" : `
135681
+ -- Applies the final decision of a week's approval request: approvals calls it,
135682
+ -- with the user who decided. It isn't granted to anyone.
135683
+ create or replace function ${fn("timesheet_approval_decided")}(timesheet_id uuid, approved boolean, note text, decided_by uuid)
135684
+ returns void
135685
+ language plpgsql
135686
+ security definer
135687
+ set search_path = ''
135688
+ as $$
135689
+ declare
135690
+ v_sheet ${timesheets}%rowtype;
135691
+ begin
135692
+ update ${timesheets} s set ${t("status")} = case when timesheet_approval_decided.approved then ${value("approved")} else ${value("rejected")} end,
135693
+ ${t("approvedAt")} = case when timesheet_approval_decided.approved then now() end${[
135694
+ ...ctx.has("timesheets", "decidedBy") ? [`${t("decidedBy")} = timesheet_approval_decided.decided_by`] : [],
135695
+ ...ctx.has("timesheets", "decidedAt") ? [`${t("decidedAt")} = now()`] : [],
135696
+ ...ctx.has("timesheets", "decisionNote") ? [`${t("decisionNote")} = timesheet_approval_decided.note`] : []
135697
+ ].map((set) => `, ${set}`).join("")}
135698
+ where s.${t("id")} = timesheet_approval_decided.timesheet_id and ${is("s", ["submitted"])}
135699
+ returning * into v_sheet;
135700
+ if not found then
135701
+ return;
135702
+ end if;
135703
+ if timesheet_approval_decided.approved then
135704
+ ${timesheetRecord("timesheet.approved", "v_sheet", "approved a timesheet")}
135705
+ else
135706
+ ${timesheetRecord("timesheet.rejected", "v_sheet", "rejected a timesheet")}
135707
+ end if;
135708
+ end;
135709
+ $$;
135710
+ revoke execute on function ${fn("timesheet_approval_decided")}(uuid, boolean, text, uuid) from public, anon, authenticated;
135711
+ `}${decision("reject_timesheet", "rejected", "timesheet.rejected", "rejected a timesheet")}
135178
135712
  -- Unlocks an approved or rejected week so its entries can change and it can
135179
135713
  -- be sent again.
135180
135714
  create or replace function ${fn("reopen_timesheet")}(timesheet_id uuid)
@@ -135370,8 +135904,6 @@ ${userGrant(`${fn("resume_timer")}(uuid)`)}
135370
135904
  `;
135371
135905
  }
135372
135906
  // src/sql/modules/time-tracking.ts
135373
- /** Timesheets this block submits to approvals. */
135374
- const TIMESHEET_SUBJECT = "timesheet";
135375
135907
  const WHERE = "blocks.time-tracking.options";
135376
135908
  const ENTRY_PAYLOAD = [
135377
135909
  "organizationId",
@@ -135554,10 +136086,12 @@ function timesheetPolicy(ctx) {
135554
136086
  }
135555
136087
  function build$8(ctx) {
135556
136088
  if (ctx.mode === "custom") return "";
135557
- const statusMode = !ctx.flag("approvals", true);
136089
+ const employeeLinked = byEmployee(ctx) && ctx.flag("approvals", true);
136090
+ const statusMode = !ctx.flag("approvals", true) || employeeLinked;
135558
136091
  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`);
136092
+ const linked = employeeLinked ? ctx.of("approvals") : void 0;
136093
+ if ((approvals ?? linked)?.mode === "custom") throw new TypeError("blocks.time-tracking needs the approvals tables; approvals can't be in custom mode");
136094
+ 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
136095
  const entries = ctx.table("entries");
135562
136096
  const timesheets = ctx.table("timesheets");
135563
136097
  const e = (column) => ctx.col("entries", column);
@@ -135573,7 +136107,7 @@ function build$8(ctx) {
135573
136107
  const { bound, rowSubject, subjectColumns, setSubject, subjectInsert, subjectInsertValues } = entrySubjects(ctx, subjects);
135574
136108
  const zone = sqlString(weekTimeZone(ctx));
135575
136109
  const userZone = userTimeZoneOf(ctx);
135576
- const policy = statusMode ? "" : timesheetPolicy(ctx);
136110
+ const policy = statusMode && !employeeLinked ? "" : timesheetPolicy(ctx);
135577
136111
  const durationMode = durationEntries(ctx);
135578
136112
  const { allowOverlap, manyTimers } = timerOptions(ctx);
135579
136113
  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 +136618,14 @@ ${statusMode ? statusTimesheetFunctions(ctx, {
136084
136618
  week: (at, user) => weekOf(at, user),
136085
136619
  ended,
136086
136620
  running,
136087
- owner: owner.status
136621
+ owner: owner.status,
136622
+ ...linked === void 0 ? {} : { approvals: {
136623
+ open: linked.fn("open_approval"),
136624
+ requests: linked.table("requests"),
136625
+ a: (column) => linked.col("requests", column),
136626
+ subject: TIMESHEET_SUBJECT,
136627
+ policy
136628
+ } }
136088
136629
  }) : approvalTimesheetFunctions(ctx, {
136089
136630
  entries,
136090
136631
  timesheets,
@@ -136182,18 +136723,13 @@ function contract$8(ctx) {
136182
136723
  }
136183
136724
  ];
136184
136725
  }
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
136726
  const REQUIRES = [
136191
136727
  "memberships",
136192
136728
  "permissions",
136193
136729
  "approvals"
136194
136730
  ];
136195
136731
  const TIME_TRACKING = {
136196
- contributes: CONTRIBUTES,
136732
+ contributes: TIME_TRACKING_CONTRIBUTES,
136197
136733
  name: "time-tracking",
136198
136734
  scopes: ["tenant"],
136199
136735
  title: "Time tracking",