better-supabase 0.37.0 → 0.38.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 (155) hide show
  1. package/dist/ai-sdk/agents/index.d.ts +2 -2
  2. package/dist/{app-tables-BlhdqqHf.d.ts → app-tables-D2c0i05-.d.ts} +1 -1
  3. package/dist/{authorization-C7yjZttV.d.ts → authorization-D8CaAdqU.d.ts} +7 -5
  4. package/dist/{bind-BspFMDdW.d.ts → bind-5vOwNouG.d.ts} +1 -1
  5. package/dist/{block-env-CLco8YUl.d.ts → block-env-hco8BLjC.d.ts} +3 -3
  6. package/dist/block-subjects-CINiJW1R.js +253 -0
  7. package/dist/{block-tables-DfomofFv.d.ts → block-tables-BsgdB6VG.d.ts} +1 -1
  8. package/dist/blocks/ai-chat/index.d.ts +3 -3
  9. package/dist/blocks/announcements/index.d.ts +3 -3
  10. package/dist/blocks/api-keys/index.d.ts +1 -1
  11. package/dist/blocks/attachments/index.d.ts +1 -1
  12. package/dist/blocks/audit/index.d.ts +2 -2
  13. package/dist/blocks/automations/index.d.ts +1 -1
  14. package/dist/blocks/billing/index.d.ts +1 -1
  15. package/dist/blocks/bookings/index.d.ts +1 -1
  16. package/dist/blocks/calendar/index.d.ts +1 -1
  17. package/dist/blocks/catalog/index.d.ts +4 -0
  18. package/dist/blocks/catalog/index.js +10 -0
  19. package/dist/blocks/comments/index.d.ts +4 -4
  20. package/dist/blocks/entitlements/index.d.ts +2 -2
  21. package/dist/blocks/expenses/index.d.ts +2 -0
  22. package/dist/blocks/expenses/index.js +10 -3
  23. package/dist/blocks/forms/index.d.ts +1 -1
  24. package/dist/blocks/inbox/index.d.ts +4 -4
  25. package/dist/blocks/index.d.ts +1 -1
  26. package/dist/blocks/invoices/index.d.ts +15 -1
  27. package/dist/blocks/invoices/index.js +13 -0
  28. package/dist/blocks/leave/index.js +1 -1
  29. package/dist/blocks/messaging/index.d.ts +4 -4
  30. package/dist/blocks/mfa/index.d.ts +1 -1
  31. package/dist/blocks/notifications/index.d.ts +3 -3
  32. package/dist/blocks/onboarding/index.d.ts +1 -1
  33. package/dist/blocks/organizations/index.d.ts +2 -2
  34. package/dist/blocks/permissions/index.d.ts +1 -1
  35. package/dist/blocks/push/index.d.ts +1 -1
  36. package/dist/blocks/reactions/index.d.ts +3 -3
  37. package/dist/blocks/saved-views/index.d.ts +1 -1
  38. package/dist/blocks/search/index.d.ts +2 -2
  39. package/dist/blocks/sessions/index.d.ts +1 -1
  40. package/dist/blocks/settings/index.d.ts +1 -1
  41. package/dist/blocks/subjects/index.d.ts +1 -1
  42. package/dist/blocks/tags/index.d.ts +1 -1
  43. package/dist/blocks/undo/index.d.ts +1 -1
  44. package/dist/blocks/usage/index.d.ts +1 -1
  45. package/dist/blocks/workflow-editor/index.d.ts +3 -3
  46. package/dist/blocks/workflows/index.d.ts +3 -3
  47. package/dist/claims/index.d.ts +3 -3
  48. package/dist/cli/{add-DqfJVb1F.js → add-7nCSDmpt.js} +10 -10
  49. package/dist/cli/{add-Buuy7BSU.js → add-B4tQpnXP.js} +2 -2
  50. package/dist/cli/add-CdDneXMN.js +1 -0
  51. package/dist/cli/{app-table-files-Ku-4tPUu.js → app-table-files-CtO-zxpO.js} +2 -2
  52. package/dist/cli/{app-tables-Dg0sh4dH.js → app-tables-B7UzcJ_g.js} +2 -2
  53. package/dist/cli/{backfill-Dspz6kVJ.js → backfill-B2nFDXaS.js} +1 -1
  54. package/dist/cli/bin.js +1 -1
  55. package/dist/cli/{blocks-CqVBlc4L.js → blocks-BX_6HUQT.js} +1 -1
  56. package/dist/cli/{blocks-B8LAph-w.js → blocks-DU4iDrYS.js} +1 -1
  57. package/dist/cli/{cache-BbuuCIRU.js → cache-bS5bAoF-.js} +1 -1
  58. package/dist/cli/{codemod-DIAy8uXt.js → codemod-B1sSIE2p.js} +1 -1
  59. package/dist/cli/{content-mapper-NXfJ5VkP.js → content-mapper-CW6V6VRq.js} +2 -2
  60. package/dist/cli/{doctor-CUOyLE0c.js → doctor-Dw2pAf1b.js} +15 -15
  61. package/dist/cli/{gen-s9canfdC.js → gen-BtoSx3go.js} +11 -11
  62. package/dist/cli/index.d.ts +1 -1
  63. package/dist/cli/index.js +6 -6
  64. package/dist/cli/{init-Zs0Ca5on.js → init-DZXbrKuJ.js} +8 -8
  65. package/dist/cli/{live-BaLsNove.js → live-CDFfJcdR.js} +2 -2
  66. package/dist/cli/{mcp-ST7bVpJD.js → mcp-BukxvITV.js} +2 -2
  67. package/dist/cli/{metadata-aOvlCOOg.js → metadata-iZizGVuY.js} +3 -3
  68. package/dist/cli/{migrate-ClBx3Ggx.js → migrate-DPnnGLzw.js} +1 -1
  69. package/dist/cli/{migration-safety-mjm1pghO.js → migration-safety-COcnZbMO.js} +1 -1
  70. package/dist/cli/{migrations-tzItvwxT.js → migrations-BBt9fmiV.js} +2 -2
  71. package/dist/cli/{module-migration-D0Rjdvdx.js → module-migration-tCmPLhQp.js} +2 -2
  72. package/dist/cli/{powersync-DryX_DMG.js → powersync-BRmUJ-uR.js} +3 -3
  73. package/dist/cli/powersync-CYLPcJ9G.js +1 -0
  74. package/dist/cli/{print-fOUnKwA9.js → print-DdwQNG_e.js} +2 -2
  75. package/dist/cli/{providers-BR1d_5jA.js → providers-CaNg6Ayz.js} +1 -1
  76. package/dist/cli/{prune-workflows-CCjzNrxl.js → prune-workflows-BQQrI3tU.js} +1 -1
  77. package/dist/cli/{remove-B_0OIusa.js → remove-BEj9YEON.js} +5 -5
  78. package/dist/cli/{render-BCJKDX3c.js → render-UBqU9r44.js} +3 -3
  79. package/dist/cli/{run-4VUQTR-R.js → run-3E_IuJzS.js} +9 -9
  80. package/dist/cli/{run-BctvQX_g.js → run-BXlX9YdD.js} +27 -27
  81. package/dist/cli/{shared-oY7PGamd.js → shared-agrqD28l.js} +1 -1
  82. package/dist/cli/{snapshot-CWtER9-4.js → snapshot-DOXmozSq.js} +2 -2
  83. package/dist/cli/{source-D4uav_v9.js → source-BfJprU-6.js} +1 -1
  84. package/dist/cli/{spec-BPsyEzqH.js → spec-CgtIHFsl.js} +1 -1
  85. package/dist/cli/{spec-DTnBeaCD.js → spec-DRpSQGOW.js} +2 -2
  86. package/dist/cli/{sql-layout-DbhEQqq0.js → sql-layout-Cs3FMWcY.js} +2 -2
  87. package/dist/cli/{sync-CazH5FX4.js → sync-C_YGIDjk.js} +4 -4
  88. package/dist/cli/{upgrade-Cyx6ESpc.js → upgrade-ByQeJRGU.js} +5 -5
  89. package/dist/cli/{upgrade-Dyb4-f0Q.js → upgrade-OG9vaBeX.js} +2 -2
  90. package/dist/cli/{version-D1ZKUFng.js → version-CF6Yzah0.js} +1 -1
  91. package/dist/client/index.d.ts +5 -5
  92. package/dist/client/native/index.d.ts +4 -4
  93. package/dist/config/index.d.ts +2 -2
  94. package/dist/config/index.js +4 -4
  95. package/dist/{config-Dx3bEPlX.js → config-1-UmQczM.js} +1 -1
  96. package/dist/{config-uSliwPS6.js → config-AEB5iNEO.js} +4 -123
  97. package/dist/{context-D6OZQdcT.d.ts → context-CH5FYnVk.d.ts} +1 -1
  98. package/dist/contract/index.d.ts +3 -3
  99. package/dist/{controller-DhcSXkAC.d.ts → controller-CJ6rLnpS.d.ts} +1 -1
  100. package/dist/create/index.d.ts +3 -3
  101. package/dist/create/index.js +3 -3
  102. package/dist/create/lite/index.d.ts +3 -3
  103. package/dist/create/lite/index.js +2 -2
  104. package/dist/{entitlements-Bi4y8w8e.d.ts → entitlements-6gODwBSz.d.ts} +1 -1
  105. package/dist/{field-errors-CJ_i6HFg.d.ts → field-errors-CdSjV9Zo.d.ts} +4 -4
  106. package/dist/{index-C71uHfVj.d.ts → index-B5awu2SP.d.ts} +2 -2
  107. package/dist/{index-Cbwvf4yE.d.ts → index-BgRl484n.d.ts} +1 -1
  108. package/dist/{index-Bm1ftdBA.d.ts → index-CgKieWlO.d.ts} +2 -2
  109. package/dist/{index-ChvuVimY.d.ts → index-CrOeAgSh.d.ts} +2 -2
  110. package/dist/{index-Bc5t2QRU.d.ts → index-DnEJVKQ2.d.ts} +6 -6
  111. package/dist/{index-DrDCN45q.d.ts → index-DzLLMmUB.d.ts} +1 -1
  112. package/dist/{index-CRwpDGxd.d.ts → index-vkd2LTt2.d.ts} +1 -1
  113. package/dist/{instances-DKULdpWB.js → instances-Bycf_aus.js} +13 -1
  114. package/dist/mapper/bin.js +5 -5
  115. package/dist/mcp/index.d.ts +1 -1
  116. package/dist/next/index.d.ts +4 -4
  117. package/dist/{operations-BDjgCmT9.d.ts → operations-knMnfzgm.d.ts} +1 -1
  118. package/dist/{options-RYbyaVhv.js → options-CS1DA8q9.js} +1 -0
  119. package/dist/{options-ScQ6Hnxo.js → options-zsLpIqBA.js} +2 -1
  120. package/dist/otel/index.js +4 -4
  121. package/dist/{permissions-BGx22GP3.d.ts → permissions-Ed8WvLgQ.d.ts} +1 -1
  122. package/dist/{ports-D63bA3p4.d.ts → ports-Bnwy2mlR.d.ts} +1 -1
  123. package/dist/powersync/index.d.ts +2 -2
  124. package/dist/preset/index.d.ts +3 -3
  125. package/dist/preset/index.js +3 -3
  126. package/dist/{preset-oc_liUHz.js → preset-DkeXFh7e.js} +2 -2
  127. package/dist/{project-Cs0kz5OP.js → project-By0R8ioI.js} +5 -5
  128. package/dist/{push-token-BsyX0KlT.d.ts → push-token-CJbEvwjI.d.ts} +1 -1
  129. package/dist/react/index.d.ts +5 -5
  130. package/dist/react/native/index.d.ts +1 -1
  131. package/dist/react/server.d.ts +5 -5
  132. package/dist/realtime/index.d.ts +3 -3
  133. package/dist/records/index.d.ts +3 -3
  134. package/dist/server/index.d.ts +3 -3
  135. package/dist/solid/index.d.ts +5 -5
  136. package/dist/sql/index.d.ts +5 -5
  137. package/dist/sql/index.js +3 -3
  138. package/dist/{sql-CWYbu_6y.js → sql-B2cMvGnZ.js} +359 -47
  139. package/dist/ssr/index.d.ts +1 -1
  140. package/dist/svelte/index.d.ts +5 -5
  141. package/dist/{tenant-DqnE50Ju.d.ts → tenant-eZNRWTRJ.d.ts} +1 -1
  142. package/dist/testing/index.d.ts +3 -3
  143. package/dist/testing/index.js +1 -1
  144. package/dist/{topic-Dp7VGPd-.d.ts → topic-D7F2FBNp.d.ts} +1 -1
  145. package/dist/{types-DLXTmZtm.d.ts → types-bqvFoBhf.d.ts} +2 -2
  146. package/dist/vue/index.d.ts +5 -5
  147. package/dist/{watch-topic-CtJAkWT4.d.ts → watch-topic-BIEaSN0Y.d.ts} +1 -1
  148. package/dist/workflow-sdk/world/index.js +1 -1
  149. package/dist/{workflow-sdk-pB1jCLIL.js → workflow-sdk-6psRpDIo.js} +1 -69
  150. package/dist/yjs/index.d.ts +1 -1
  151. package/package.json +1 -1
  152. package/schemas/config-v1.json +10 -0
  153. package/dist/cli/add-8zKWiO0X.js +0 -1
  154. package/dist/cli/powersync-vvu2-72V.js +0 -1
  155. package/dist/resolved-names-sd6RuTju.js +0 -130
@@ -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 { n as resolveJsonSchema, r as CONFIG_DEFAULTS, t as resolveNames } from "./resolved-names-sd6RuTju.js";
6
+ import { c as CONFIG_DEFAULTS, i as installedBlockSubjects, o as resolveNames, s as resolveJsonSchema } from "./block-subjects-CINiJW1R.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-DKULdpWB.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-Bycf_aus.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 ownRowPolicies, A as addForeignKey, B as ensureCheck, C as PARTITION_VARIABLES, D as activeMembership, E as accessDefinesDisabledHelpers, F as defaultPartition, G as jsonSchemaChecks, H as extraFieldsJson, I as defaultPartitionName, J as memberAddedRecord, K as jwtClaim, L as disabledHelpers, M as batchFunction, N as columnRef, O as addCheck, P as columnsObject, Q as organizationMissing, R as disabledHelpersNeedLaterTables, S as NOTHING, T as SERVICE_CALLER$1, U as fail$1, V as extraFieldsArg, W as insertExtraColumns, X as membershipSuspended, Y as membershipDisabledAt, Z as notNullCheckName, _ as roleScopeIs, _t as userGrant, at as renameSql, b as EQUIVALENT_TRIGGERS, c as OPTIONAL_MODULE_PERMISSIONS, ct as schemaPreamble, d as isOperationModule$1, dt as sha256Hex$1, et as pageSize, f as moduleOperations, ft as shortHash, g as roleNames, gt as updatedAt, h as providerPlatformRoles, ht as updateExtraColumns, it as registerPartitions, j as addNotNullCheck, k as addExtraColumns, l as accessModel, lt as serviceGrant, m as modulePermissionKey, mt as triggerGrant, n as WORKFLOW_SDK_WORLD, nt as raise$1, o as MODULE_PERMISSION_SCOPES, ot as replaceColumnCheck, p as modulePermission, pt as splitTable$1, q as lockTable, rt as recordTrigger, s as OPERATIONS, st as revokeTable, tt as quotedTable$1, u as hasPlatformRoles, ut as serviceOnly$1, v as rolesOf, vt as withExtraFields, w as SCHEMA$5, x as MONTHLY_PARTITIONS, y as tenantScope, yt as writeExtraColumns, z as dropExpiredPartitions } from "./workflow-sdk-pB1jCLIL.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 withExtraFields, 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 userGrant, h as roleNames, ht as updatedAt, it as renameSql, j as batchFunction, k as addForeignKey, l as hasPlatformRoles, lt as serviceOnly$1, m as providerPlatformRoles, mt as updateExtraColumns, n as WORKFLOW_SDK_WORLD, nt as recordTrigger, o as MODULE_PERMISSION_SCOPES, ot as revokeTable, p as modulePermissionKey, pt as triggerGrant, 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 writeExtraColumns, w as SERVICE_CALLER$1, x as NOTHING, y as EQUIVALENT_TRIGGERS, z as ensureCheck } from "./workflow-sdk-6psRpDIo.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";
@@ -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-RYbyaVhv.js";
56
+ import { t as expensesSqlOptions } from "./options-CS1DA8q9.js";
57
57
  import { t as flagsSqlOptions } from "./options-BMO-FnOT.js";
58
58
  import { t as formsSqlOptions } from "./options-DpwRG4tO.js";
59
59
  import { t as goalsSqlOptions } from "./options-BNRvoEkj.js";
@@ -66,7 +66,7 @@ import { t as invoicesSqlOptions } from "./options-X61tvckX.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-ScQ6Hnxo.js";
69
+ import { t as leaveSqlOptions } from "./options-zsLpIqBA.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";
@@ -1863,7 +1863,7 @@ const CLIENT_FUNCTIONS = {
1863
1863
  bookings: "add_booking_exception available_slots cancel_booking confirm_booking delete_booking_exception expire_booking_holds hold_booking list_bookings save_booking_resource save_booking_service set_booking_availability",
1864
1864
  bulk: "bulk_apply bulk_run bulk_step start_bulk",
1865
1865
  calendar: "calendar_free_busy cancel_calendar_occurrence create_calendar delete_calendar delete_calendar_event import_calendar_events list_calendar_events list_calendar_working_hours list_calendars remove_calendar_attendee respond_calendar_event save_calendar_event set_calendar_attendee set_calendar_working_hours split_calendar_event",
1866
- catalog: "add_to_collection channel_price channel_products delete_catalog_channel delete_category delete_collection delete_price delete_price_list delete_product delete_product_option delete_variant move_category product_text publish_storefront rank_variant remove_from_collection reorder_product_options save_catalog_channel save_category save_collection save_price_list save_product save_product_option save_variant set_channel_listing set_price set_product_categories set_product_options set_product_status set_product_translation set_variant_translation variant_price",
1866
+ catalog: "add_to_collection channel_price channel_products delete_catalog_channel delete_category delete_collection delete_price delete_price_list delete_product delete_product_option delete_variant move_category product_text publish_storefront rank_variant remove_from_collection reorder_product_options save_catalog_channel save_category save_collection save_price_list save_product save_product_option save_variant set_channel_listing set_price set_product_categories set_product_options set_product_status set_product_translation set_variant_status set_variant_translation variant_price",
1867
1867
  channels: "archive_channel channels_for_record create_channel find_channel get_channel invite_to_channel join_channel leave_channel list_channels update_channel",
1868
1868
  "chat-sdk-state": "chat_install chat_installation chat_state_acquire_lock chat_state_append_to_list chat_state_delete chat_state_dequeue chat_state_enqueue chat_state_extend_lock chat_state_force_release_lock chat_state_get chat_state_get_list chat_state_is_subscribed chat_state_queue_depth chat_state_release_lock chat_state_set chat_state_set_if_not_exists chat_state_subscribe chat_state_unsubscribe chat_uninstall list_chat_installations purge_chat_state",
1869
1869
  collections: "add_collection_entries archive_collection collection_entries collection_subject_ids collections_of complete_saved_item create_collection list_collections list_saved_items rank_collection_entry rank_star remind_due_saved_items remove_collection_entries remove_saved_item rename_collection save_for_later star_subject starred_subjects unstar_subject",
@@ -1902,7 +1902,7 @@ const CLIENT_FUNCTIONS = {
1902
1902
  incidents: "delete_status_component get_incident get_status_page list_incidents list_status_components open_incident post_incident_update public_status_page publish_postmortem save_postmortem save_status_component save_status_page set_incident_impacts update_incident",
1903
1903
  inventory: "adjust_stock allocate_stock cancel_purchase_order cancel_transfer commit_reservation count_stock create_transfer delete_location expire_lots expire_reservations expiring_lots fulfill_allocation list_allocations place_purchase_order receive_purchase_order receive_transfer release_allocations release_reservation reserve_stock restore_allocation save_bin save_location save_lot save_purchase_order set_location_active set_reorder_point set_stock_item ship_transfer stock_detail stock_valuation",
1904
1904
  invitations: "accept_invitation accept_invitation_by_id decline_invitation decline_invitation_by_id invitation_preview invite_member my_invitations resend_invitation revoke_invitation update_invitation",
1905
- invoices: "add_invoice_charge create_invoice credit_invoice invoice_aging issue_invoice record_invoice_payment remove_invoice_charge reverse_invoice_payment set_invoice_lines void_invoice write_off_invoice",
1905
+ invoices: "add_invoice_charge create_invoice credit_invoice delete_invoice invoice_aging issue_invoice record_invoice_payment remove_invoice_charge reverse_invoice_payment set_invoice_lines update_invoice void_invoice write_off_invoice",
1906
1906
  knowledge: "create_knowledge_collection create_knowledge_document delete_knowledge_collection delete_knowledge_document fail_knowledge_document get_knowledge_document knowledge_search list_knowledge_collection_grants list_knowledge_collections list_knowledge_documents pending_knowledge_chunks pending_knowledge_documents reembed_knowledge set_knowledge_collection_grant set_knowledge_embeddings update_knowledge_collection write_knowledge_chunks",
1907
1907
  "lead-scoring": "lead_fields score_lead score_leads_due",
1908
1908
  leases: "activate_lease create_lease get_lease list_lease_charges list_leases post_due_rent record_rent_payment renew_lease terminate_lease",
@@ -3213,7 +3213,7 @@ function moduleContext(name, layout = {}, installed, instance) {
3213
3213
  return createModuleContext(name, (module) => registry$1().modules[module]?.names, {
3214
3214
  ...modules ? { modules } : {},
3215
3215
  ...layout.claims ? { claims: layout.claims } : {},
3216
- ...layout.subjects ? { subjects: layout.subjects } : {},
3216
+ ...layout.subjects ? { subjects: installed ? installedBlockSubjects(layout.subjects, installed, layout.modules ?? {}) : layout.subjects } : {},
3217
3217
  ...layout.appTables ? { appTables: Object.keys(layout.appTables) } : {},
3218
3218
  ...layout.ownTables ? { ownTables: layout.ownTables } : {},
3219
3219
  ...layout.ownViews ? { ownViews: layout.ownViews } : {},
@@ -3342,6 +3342,82 @@ function contributorsOf(block, layout, installed) {
3342
3342
  });
3343
3343
  });
3344
3344
  }
3345
+ // src/sql/optional-permissions.ts
3346
+ /** Actions a module checks only when `blocks.<module>.permissions` names a key. */
3347
+ const OPTIONAL_MODULE_PERMISSIONS = {
3348
+ organizations: {
3349
+ create: "platform",
3350
+ updatePlatform: "platform",
3351
+ deletePlatform: "platform",
3352
+ updateRolePlatform: "platform",
3353
+ removeMemberPlatform: "platform"
3354
+ },
3355
+ audit: { reveal: "tenant" },
3356
+ "data-lifecycle": { deletePlatform: "platform" },
3357
+ tags: {
3358
+ create: "tenant",
3359
+ update: "tenant",
3360
+ delete: "tenant"
3361
+ },
3362
+ tasks: {
3363
+ create: "tenant",
3364
+ delete: "tenant"
3365
+ },
3366
+ calendar: {
3367
+ create: "tenant",
3368
+ update: "tenant",
3369
+ delete: "tenant"
3370
+ },
3371
+ employees: {
3372
+ create: "tenant",
3373
+ contractsRead: "tenant",
3374
+ contractsWrite: "tenant",
3375
+ privateDetailsWrite: "tenant"
3376
+ },
3377
+ hiring: {
3378
+ create: "tenant",
3379
+ jobsCreate: "tenant",
3380
+ jobsUpdate: "tenant",
3381
+ score: "tenant"
3382
+ },
3383
+ teams: {
3384
+ create: "tenant",
3385
+ update: "tenant",
3386
+ delete: "tenant",
3387
+ members: "tenant"
3388
+ },
3389
+ catalog: {
3390
+ create: "tenant",
3391
+ update: "tenant",
3392
+ delete: "tenant",
3393
+ categoryCreate: "tenant",
3394
+ categoryUpdate: "tenant",
3395
+ categoryDelete: "tenant"
3396
+ },
3397
+ invoices: {
3398
+ create: "tenant",
3399
+ update: "tenant",
3400
+ issue: "tenant",
3401
+ payment: "tenant",
3402
+ credit: "tenant",
3403
+ charge: "tenant",
3404
+ void: "tenant",
3405
+ writeOff: "tenant",
3406
+ reverse: "tenant",
3407
+ delete: "tenant"
3408
+ },
3409
+ leave: {
3410
+ readConfidential: "tenant",
3411
+ reapprove: "tenant"
3412
+ },
3413
+ expenses: {
3414
+ create: "tenant",
3415
+ update: "tenant",
3416
+ delete: "tenant",
3417
+ reimburse: "tenant",
3418
+ categories: "tenant"
3419
+ }
3420
+ };
3345
3421
  // src/sql/block-renames.ts
3346
3422
  /**
3347
3423
  * The blocks 0.15 renamed to plain defaults (ADR 0093), from the 0.14 name to
@@ -37290,7 +37366,11 @@ declare
37290
37366
  v_last text;
37291
37367
  v_rank text;
37292
37368
  begin
37293
- ${guard$11(names, "save_category.tenant")}
37369
+ if v_id is null then
37370
+ ${guard$11(names, "save_category.tenant", names.categoryCreate)}
37371
+ else
37372
+ ${guard$11(names, "save_category.tenant", names.categoryUpdate)}
37373
+ end if;
37294
37374
  if v_slug is null or v_slug !~ ${SLUG$4} then
37295
37375
  ${fail$1("CATALOG_SLUG_INVALID", "the slug must be lower-case letters, digits and hyphens", "22023")}
37296
37376
  end if;
@@ -37341,7 +37421,7 @@ begin
37341
37421
  if v_tenant is null then
37342
37422
  ${fail$1("CATALOG_CATEGORY_NOT_FOUND", "category not found", "P0002")}
37343
37423
  end if;
37344
- ${guard$11(names, "v_tenant")}
37424
+ ${guard$11(names, "v_tenant", names.categoryUpdate)}
37345
37425
  if move_category.parent is not null and not exists (select 1 from ${categories} x where x.${k("id")} = move_category.parent and x.${k("tenant")} = v_tenant) then
37346
37426
  ${fail$1("CATALOG_CATEGORY_NOT_FOUND", "parent category not found", "P0002")}
37347
37427
  end if;
@@ -37367,7 +37447,7 @@ begin
37367
37447
  if v_tenant is null then
37368
37448
  return false;
37369
37449
  end if;
37370
- ${guard$11(names, "v_tenant")}
37450
+ ${guard$11(names, "v_tenant", names.categoryDelete)}
37371
37451
  begin
37372
37452
  delete from ${categories} x where x.${k("id")} = delete_category.category;
37373
37453
  exception when foreign_key_violation then
@@ -37606,6 +37686,95 @@ $$;
37606
37686
  ${userGrant(`${fn("publish_storefront")}(${ctx.idType}, boolean)`)}
37607
37687
  `;
37608
37688
  }
37689
+ // src/sql/modules/catalog-variant-status.ts
37690
+ function variantStatusFunction(ctx, names) {
37691
+ const hasValues = ctx.hasTable("variantValues") && ctx.hasTable("optionValues") && ctx.hasTable("options");
37692
+ const { fn } = names;
37693
+ if (typeof ctx.config.columns["variants"]?.["status"] !== "string" || !ctx.has("variants", "status")) return `
37694
+ -- Variants have no status column (columns.variants.status), so this refuses.
37695
+ create or replace function ${fn("set_variant_status")}(variant uuid, status text)
37696
+ returns jsonb
37697
+ language plpgsql
37698
+ security definer
37699
+ set search_path = ''
37700
+ as $$
37701
+ begin
37702
+ ${fail$1("CATALOG_VARIANT_STATUS_UNSUPPORTED", "this variants table has no status column", "22023")}
37703
+ end;
37704
+ $$;
37705
+ ${userGrant(`${fn("set_variant_status")}(uuid, text)`)}
37706
+ `;
37707
+ const variants = ctx.table("variants");
37708
+ const v = (column) => ctx.col("variants", column);
37709
+ const map = ctx.config.values?.["variants"];
37710
+ const labels = [.../* @__PURE__ */ new Set([
37711
+ "active",
37712
+ "archived",
37713
+ ...isRecord$1(map) && isRecord$1(map["status"]) ? Object.keys(map["status"]) : []
37714
+ ])];
37715
+ const live = ctx.is("variants", "status", `x.${v("status")}::text`, ["archived"], true);
37716
+ const liveChecks = hasValues ? (() => {
37717
+ const options = ctx.table("options");
37718
+ const variantValues = ctx.table("variantValues");
37719
+ const o = (column) => ctx.col("options", column);
37720
+ const vv = (column) => ctx.col("variantValues", column);
37721
+ const valueSet = (alias) => `coalesce((select array_agg(y.${vv("value")} order by y.${vv("value")}) from ${variantValues} y where y.${vv("variant")} = ${alias}), '{}'::uuid[])`;
37722
+ return `
37723
+ if exists (select 1 from ${variants} x where x.${v("id")} = set_variant_status.variant and ${live}) then
37724
+ if (select count(*) from ${options} o where o.${o("product")} = v_product) <> (select count(*) from ${variantValues} y where y.${vv("variant")} = set_variant_status.variant) then
37725
+ ${fail$1("CATALOG_VARIANT_OPTIONS", "a live variant needs one value of each product option; set them with save_variant", "22023")}
37726
+ end if;
37727
+ if exists (
37728
+ select 1 from ${variants} x
37729
+ where x.${v("product")} = v_product and x.${v("id")} <> set_variant_status.variant and ${live}
37730
+ and ${valueSet(`x.${v("id")}`)} = ${valueSet("set_variant_status.variant")}
37731
+ ) then
37732
+ ${fail$1("CATALOG_VARIANT_DUPLICATE", "another live variant has these option values", "23505")}
37733
+ end if;
37734
+ end if;`;
37735
+ })() : "";
37736
+ return `
37737
+ -- Moves a variant to another status: active, archived or a label
37738
+ -- values.variants.status maps. A variant that goes live again needs a free
37739
+ -- combination of option values.
37740
+ create or replace function ${fn("set_variant_status")}(variant uuid, status text)
37741
+ returns jsonb
37742
+ language plpgsql
37743
+ security definer
37744
+ set search_path = ''
37745
+ as $$
37746
+ declare
37747
+ v_tenant ${ctx.idType};
37748
+ v_product uuid;
37749
+ v_sku text;
37750
+ v_from text;
37751
+ v_to text;
37752
+ begin
37753
+ select x.${v("tenant")}, x.${v("product")}, x.${v("sku")}, ${ctx.label("variants", "status", `x.${v("status")}`)} into v_tenant, v_product, v_sku, v_from
37754
+ from ${variants} x where x.${v("id")} = set_variant_status.variant for update;
37755
+ if v_tenant is null then
37756
+ ${fail$1("CATALOG_VARIANT_NOT_FOUND", "variant not found", "P0002")}
37757
+ end if;
37758
+ ${guard$11(names, "v_tenant", names.update)}
37759
+ if set_variant_status.status is null or not (set_variant_status.status = any (${sqlString(`{${labels.join(",")}}`)}::text[])) then
37760
+ ${fail$1("CATALOG_STATUS_INVALID", `the status must be ${labels.join(", ")}`, "22023")}
37761
+ end if;
37762
+ update ${variants} x set ${v("status")} = ${ctx.cast("variants", "status", "set_variant_status.status")}, ${v("updatedAt")} = now()
37763
+ where x.${v("id")} = set_variant_status.variant
37764
+ returning ${ctx.label("variants", "status", `x.${v("status")}`)} into v_to;${liveChecks}
37765
+ ${ctx.record({
37766
+ type: "variant.updated",
37767
+ payload: `jsonb_build_object('organizationId', v_tenant, 'id', set_variant_status.variant, 'productId', v_product, 'sku', v_sku)`,
37768
+ subject: `'variants/' || set_variant_status.variant::text`,
37769
+ tenant: "v_tenant",
37770
+ audit: false
37771
+ })}
37772
+ return jsonb_build_object('id', set_variant_status.variant, 'status', v_to, 'from', v_from);
37773
+ end;
37774
+ $$;
37775
+ ${userGrant(`${fn("set_variant_status")}(uuid, text)`)}
37776
+ `;
37777
+ }
37609
37778
  // src/sql/modules/catalog.ts
37610
37779
  const EVENTS$18 = {
37611
37780
  "product.created": {
@@ -38253,7 +38422,10 @@ function build$94(ctx) {
38253
38422
  read: ctx.permission("read", keys.read),
38254
38423
  create: actionKey(ctx, "create", keys.manage),
38255
38424
  update: actionKey(ctx, "update", keys.manage),
38256
- remove: actionKey(ctx, "delete", keys.manage)
38425
+ remove: actionKey(ctx, "delete", keys.manage),
38426
+ categoryCreate: actionKey(ctx, "categoryCreate", keys.manage),
38427
+ categoryUpdate: actionKey(ctx, "categoryUpdate", keys.manage),
38428
+ categoryDelete: actionKey(ctx, "categoryDelete", keys.manage)
38257
38429
  };
38258
38430
  storefrontOption(ctx);
38259
38431
  catalogLocales(ctx);
@@ -38262,7 +38434,7 @@ function build$94(ctx) {
38262
38434
  -- categories, collections, price lists, sales channels, translations,
38263
38435
  -- product media and an optional public storefront.
38264
38436
  ${currencyMinorUnitsFunction(names.fn("currency_minor_units"))}
38265
- ${tables$30(ctx, names)}${productFunctions(ctx, names)}${optionFunctions(ctx, names)}${priceFunctions(ctx, names)}${categoryFunctions(ctx, names)}${collectionFunctions$1(ctx, names)}${storefrontFunctions(ctx, names)}${channelModuleFunctions(ctx, names)}
38437
+ ${tables$30(ctx, names)}${productFunctions(ctx, names)}${variantStatusFunction(ctx, names)}${optionFunctions(ctx, names)}${priceFunctions(ctx, names)}${categoryFunctions(ctx, names)}${collectionFunctions$1(ctx, names)}${storefrontFunctions(ctx, names)}${channelModuleFunctions(ctx, names)}
38266
38438
  ${ctx.hasTable("storefronts") ? storefrontPolicies(ctx, names) : ""}
38267
38439
  `;
38268
38440
  }
@@ -38295,6 +38467,11 @@ function contract$85(ctx) {
38295
38467
  args: ["uuid", "text"],
38296
38468
  returns: "jsonb"
38297
38469
  },
38470
+ {
38471
+ name: "set_variant_status",
38472
+ args: ["uuid", "text"],
38473
+ returns: "jsonb"
38474
+ },
38298
38475
  {
38299
38476
  name: "delete_product",
38300
38477
  args: ["uuid"],
@@ -66059,6 +66236,7 @@ ${userGrant(`${fn("list_expenses")}(${listTypes}${employee ? ", uuid" : ""})`)}
66059
66236
  const EXPENSE_REPORT_SUBJECT = "expense_report";
66060
66237
  /** The keys the report reads return next to the extra columns. */
66061
66238
  const EXPENSE_REPORT_RESERVED = ["fields"];
66239
+ const expenseCategoryExtras = (ctx) => ctx.extraColumns("categories", ["fields"], "categoryExtraColumns");
66062
66240
  /** One approver step: anyone with the approve permission. */
66063
66241
  function expensePolicy(ctx) {
66064
66242
  return policySnapshot(policyOf(EXPENSE_REPORT_SUBJECT, "approve", { steps: [{ approvers: { permission: ctx.permissionKey("approve", OPERATIONS["expenses.approve"]) } }] }, "blocks.expenses"));
@@ -66080,6 +66258,9 @@ function expensesFunctions(ctx) {
66080
66258
  const reports = standalone ? "" : ctx.table("reports");
66081
66259
  const lines = standalone ? "" : ctx.table("lines");
66082
66260
  const k = (column) => ctx.col("categories", column);
66261
+ const keyed = ctx.has("categories", "key");
66262
+ const categoryKey = (row) => keyed ? `${row}.${k("key")}` : `${row}.${k("id")}::text`;
66263
+ const categoryExtras = expenseCategoryExtras(ctx);
66083
66264
  const r = (column) => ctx.col("reports", column);
66084
66265
  const x = (column) => ctx.col("lines", column);
66085
66266
  const ar = approvals?.table("requests") ?? "";
@@ -66152,7 +66333,7 @@ $$;
66152
66333
  ${userGrant(`${fn("decide_expense_report")}(uuid, boolean, text)`)}
66153
66334
  `;
66154
66335
  const total = (row) => `coalesce((select sum(y.${x("amount")}) from ${lines} y where y.${x("report")} = ${row}.${r("id")}), 0)`;
66155
- const categoryJson = (row) => `jsonb_build_object('id', ${row}.${k("id")}, 'organizationId', ${row}.${k("tenant")}, 'key', ${row}.${k("key")}, 'name', ${row}.${k("name")}, 'currency', ${row}.${k("currency")}, 'limitAmount', ${or("categories", row, "limitAmount")}::text, 'receiptOver', ${or("categories", row, "receiptOver")}::text, 'archivedAt', ${row}.${k("archivedAt")}, 'createdAt', ${row}.${k("createdAt")}, 'updatedAt', ${row}.${k("updatedAt")})`;
66336
+ const categoryJson = (row) => `jsonb_build_object('id', ${row}.${k("id")}, 'organizationId', ${row}.${k("tenant")}, 'key', ${categoryKey(row)}, 'name', ${row}.${k("name")}, 'currency', ${or("categories", row, "currency")}, 'limitAmount', ${or("categories", row, "limitAmount")}::text, 'receiptOver', ${or("categories", row, "receiptOver")}::text, 'archivedAt', ${row}.${k("archivedAt")}, 'createdAt', ${row}.${k("createdAt")}, 'updatedAt', ${row}.${k("updatedAt")}${extraFieldsJson(row, categoryExtras)})`;
66156
66337
  const receipts = (line) => attachments === void 0 ? "0" : `(select count(*) from ${attachments.table("attachments")} t where t.${attachments.col("attachments", "subjectType")} = ${sqlString(lineType)} and t.${attachments.col("attachments", "subjectId")} = ${line}.${x("id")}::text and t.${attachments.col("attachments", "uploadedAt")} is not null and t.${attachments.col("attachments", "status")} <> 'infected')`;
66157
66338
  const findings = [...limits ? [`select 1 as ord, min(l.${x("createdAt")}) as at, jsonb_build_object('kind', 'limit', 'categoryId', c.${k("id")}, 'category', c.${k("name")},
66158
66339
  'limit', c.${k("limitAmount")}::text, 'total', sum(l.${x("amount")})::text, 'currency', c.${k("currency")}) as v
@@ -66183,7 +66364,7 @@ ${userGrant(`${fn("decide_expense_report")}(uuid, boolean, text)`)}
66183
66364
  const account = (tenant, kind, code, name, currency, holder, owner) => `${ledger?.fn("ledger_account_for") ?? ""}(${tenant}, ${kind}, ${code}, ${name}, ${currency}::text, 0::smallint, ${holder}, ${owner}, true, ${read}, 'expenses', null)`;
66184
66365
  const payableAccount = (row) => account(`${row}.${r("tenant")}`, "'expense_payable'", `'expenses:payable:' || ${row}.${r("user")}::text || ':' || ${row}.${r("currency")}`, `'Expenses owed ' || ${row}.${r("currency")}`, `${row}.${r("currency")}`, `'users', ${row}.${r("user")}::text`, `${row}.${r("user")}`);
66185
66366
  const cashAccount = (row) => account(`${row}.${r("tenant")}`, "'expense_cash'", `'expenses:cash:' || ${row}.${r("currency")}`, `'Expenses paid ' || ${row}.${r("currency")}`, `${row}.${r("currency")}`, "null, null", "null");
66186
- const categoryAccount = (row, category) => account(`${row}.${r("tenant")}`, "'expense'", `'expenses:category:' || ${category}.${k("key")} || ':' || ${row}.${r("currency")}`, `'Expenses: ' || ${category}.${k("name")}`, `${row}.${r("currency")}`, "null, null", "null");
66367
+ const categoryAccount = (row, category) => account(`${row}.${r("tenant")}`, "'expense'", `'expenses:category:' || ${categoryKey(category)} || ':' || ${row}.${r("currency")}`, `'Expenses: ' || ${category}.${k("name")}`, `${row}.${r("currency")}`, "null, null", "null");
66187
66368
  const loadReport = (id, lock = false) => `
66188
66369
  select * into v_row from ${reports} x where x.${r("id")} = ${id}${lock ? " for update" : ""};
66189
66370
  if not found then
@@ -66200,19 +66381,44 @@ ${userGrant(`${fn("decide_expense_report")}(uuid, boolean, text)`)}
66200
66381
  const reader = `
66201
66382
  if not (coalesce(v_row.${r("user")} = auth.uid(), false) or ${can(`v_row.${r("tenant")}`, read)}) then
66202
66383
  ${fail$1("EXPENSE_REPORT_NOT_FOUND", "no such expense report", "P0002")}
66384
+ end if;`;
66385
+ const categoryArg = extraFieldsArg(categoryExtras);
66386
+ const categoryArgs = `${idType}, text, text, text, bigint, bigint`;
66387
+ const categoryInsert = insertExtraColumns(categories, categoryExtras, "coalesce(save_expense_category.fields, '{}'::jsonb)");
66388
+ const policySets = [
66389
+ ...ctx.has("categories", "currency") ? [[k("currency"), "save_expense_category.currency"]] : [],
66390
+ ...limits ? [[k("limitAmount"), "save_expense_category.limit_amount"]] : [],
66391
+ ...thresholds ? [[k("receiptOver"), "save_expense_category.receipt_over"]] : []
66392
+ ];
66393
+ const insertColumns = `${k("tenant")}${keyed ? `, ${k("key")}` : ""}, ${k("name")}${policySets.map(([column]) => `, ${column}`).join("")}${categoryInsert.columns}`;
66394
+ const insertValues = `save_expense_category.tenant${keyed ? ", save_expense_category.key" : ""}, trim(save_expense_category.name)${policySets.map(([, value]) => `, ${value}`).join("")}${categoryInsert.values}`;
66395
+ const categorySets = `${k("name")} = trim(save_expense_category.name)${policySets.map(([column, value]) => `, ${column} = ${value}`).join("")}, ${k("archivedAt")} = null, ${k("updatedAt")} = now()${updateExtraColumns(categories, categoryExtras, "save_expense_category.fields")}`;
66396
+ const categoryWrite = keyed ? ` insert into ${categories} as x (${insertColumns})
66397
+ values (${insertValues})
66398
+ on conflict (${k("tenant")}, ${k("key")}) do update set
66399
+ ${categorySets}
66400
+ returning * into v_row;` : ` update ${categories} x set ${categorySets}
66401
+ where x.${k("tenant")} = save_expense_category.tenant and x.${k("id")}::text = save_expense_category.key
66402
+ returning * into v_row;
66403
+ if not found then
66404
+ insert into ${categories} (${insertColumns})
66405
+ values (${insertValues})
66406
+ returning * into v_row;
66203
66407
  end if;`;
66204
66408
  const categoryCheck = (category, tenant) => `
66205
66409
  select * into v_category from ${categories} c
66206
66410
  where c.${k("id")} = ${category} and c.${k("tenant")} = ${tenant} and c.${k("archivedAt")} is null;
66207
66411
  if not found then
66208
66412
  ${invalid("EXPENSE_CATEGORY_INVALID", "the category is unknown, archived or not in this organization")}
66209
- end if;
66413
+ end if;${ctx.has("categories", "currency") ? `
66210
66414
  if v_category.${k("currency")} is not null and v_category.${k("currency")} <> v_row.${r("currency")} then
66211
66415
  ${invalid("EXPENSE_CURRENCY_MISMATCH", "the category's policy is in another currency than the report")}
66212
- end if;`;
66416
+ end if;` : ""}`;
66213
66417
  return `
66214
- -- Creates or updates the category with this key and its spend policy.
66215
- create or replace function ${fn("save_expense_category")}(tenant ${idType}, key text, name text, currency text default null, limit_amount bigint default null, receipt_over bigint default null)
66418
+ -- Creates or updates the category with this key and its spend policy.${keyed ? "" : "\n-- Without a key column, key is the id of the category to update, and any\n-- other key creates one."} fields:
66419
+ -- the extra columns (options.categoryExtraColumns) to set.
66420
+ ${categoryArg.drop(fn("save_expense_category"), categoryArgs)}
66421
+ create or replace function ${fn("save_expense_category")}(tenant ${idType}, key text, name text, currency text default null, limit_amount bigint default null, receipt_over bigint default null${categoryArg.param})
66216
66422
  returns jsonb
66217
66423
  language plpgsql
66218
66424
  security definer
@@ -66224,10 +66430,10 @@ declare
66224
66430
  begin
66225
66431
  if not ${can("save_expense_category.tenant", expenseKey(ctx, "categories"))} then
66226
66432
  ${forbidden("not allowed to manage expense categories")}
66227
- end if;
66433
+ end if;${keyed ? `
66228
66434
  if save_expense_category.key is null or save_expense_category.key !~ '^[a-z][a-z0-9_]{0,62}$' then
66229
66435
  ${invalid("EXPENSE_CATEGORY_INVALID", "a key is lowercase letters, digits and underscores")}
66230
- end if;
66436
+ end if;` : ""}
66231
66437
  if nullif(trim(save_expense_category.name), '') is null then
66232
66438
  ${invalid("EXPENSE_CATEGORY_INVALID", "a category needs a name")}
66233
66439
  end if;
@@ -66240,20 +66446,15 @@ begin
66240
66446
  end if;
66241
66447
  if save_expense_category.receipt_over is not null and save_expense_category.receipt_over < 0 then
66242
66448
  ${invalid("EXPENSE_CATEGORY_INVALID", "a receipt threshold is zero or more minor units")}
66243
- end if;${unsupported("categories", "limitAmount", "save_expense_category.limit_amount", "EXPENSE_LIMIT_UNSUPPORTED", "this expense categories table has no limit column")}${unsupported("categories", "receiptOver", "save_expense_category.receipt_over", "EXPENSE_RECEIPT_THRESHOLD_UNSUPPORTED", "this expense categories table has no receipt threshold column")}${attachments === void 0 ? `
66449
+ end if;${unsupported("categories", "currency", "save_expense_category.currency", "EXPENSE_CURRENCY_UNSUPPORTED", "this expense categories table has no currency column")}${unsupported("categories", "limitAmount", "save_expense_category.limit_amount", "EXPENSE_LIMIT_UNSUPPORTED", "this expense categories table has no limit column")}${unsupported("categories", "receiptOver", "save_expense_category.receipt_over", "EXPENSE_RECEIPT_THRESHOLD_UNSUPPORTED", "this expense categories table has no receipt threshold column")}${attachments === void 0 ? `
66244
66450
  if save_expense_category.receipt_over is not null then
66245
66451
  ${invalid("EXPENSE_CATEGORY_INVALID", "a receipt threshold needs the attachments block")}
66246
66452
  end if;` : ""}
66247
- insert into ${categories} (${k("tenant")}, ${k("key")}, ${k("name")}, ${k("currency")}${also("categories", "limitAmount")}${also("categories", "receiptOver")})
66248
- values (save_expense_category.tenant, save_expense_category.key, trim(save_expense_category.name), save_expense_category.currency${limits || thresholds ? ",\n " : ""}${[...limits ? ["save_expense_category.limit_amount"] : [], ...thresholds ? ["save_expense_category.receipt_over"] : []].join(", ")})
66249
- on conflict (${k("tenant")}, ${k("key")}) do update set
66250
- ${k("name")} = excluded.${k("name")}, ${k("currency")} = excluded.${k("currency")}${limits ? `, ${k("limitAmount")} = excluded.${k("limitAmount")}` : ""},
66251
- ${thresholds ? `${k("receiptOver")} = excluded.${k("receiptOver")}, ` : ""}${k("archivedAt")} = null, ${k("updatedAt")} = now()
66252
- returning * into v_row;
66453
+ ${categoryWrite}
66253
66454
  return ${categoryJson("v_row")};
66254
66455
  end;
66255
66456
  $$;
66256
- ${userGrant(`${fn("save_expense_category")}(${idType}, text, text, text, bigint, bigint)`)}
66457
+ ${userGrant(`${fn("save_expense_category")}(${categoryArgs}${categoryArg.type})`)}
66257
66458
 
66258
66459
  create or replace function ${fn("archive_expense_category")}(category_id uuid)
66259
66460
  returns jsonb
@@ -66517,7 +66718,7 @@ begin
66517
66718
  if not found then
66518
66719
  return;
66519
66720
  end if;
66520
- select jsonb_agg(jsonb_build_object('account', ${categoryAccount("v_row", "c")}, 'amount', q.total) order by c.${k("key")})
66721
+ select jsonb_agg(jsonb_build_object('account', ${categoryAccount("v_row", "c")}, 'amount', q.total) order by ${categoryKey("c")})
66521
66722
  into v_lines
66522
66723
  from (
66523
66724
  select l.${x("category")} as category, sum(l.${x("amount")}) as total
@@ -66757,6 +66958,7 @@ const NAMES$72 = {
66757
66958
  },
66758
66959
  options: [
66759
66960
  "extraColumns",
66961
+ "categoryExtraColumns",
66760
66962
  "approvals",
66761
66963
  "owner",
66762
66964
  "companyExpenses"
@@ -66781,7 +66983,12 @@ const NAMES$72 = {
66781
66983
  createdAt: "created_at",
66782
66984
  updatedAt: "updated_at"
66783
66985
  },
66784
- optional: ["limitAmount", "receiptOver"]
66986
+ optional: [
66987
+ "key",
66988
+ "currency",
66989
+ "limitAmount",
66990
+ "receiptOver"
66991
+ ]
66785
66992
  },
66786
66993
  reports: {
66787
66994
  name: "expense_reports",
@@ -66870,15 +67077,13 @@ function tables$21(ctx) {
66870
67077
  create table if not exists ${categories} (
66871
67078
  ${k("id")} uuid primary key default gen_random_uuid(),
66872
67079
  ${k("tenant")} ${ctx.idType} not null,
66873
- ${k("key")} text not null check (${k("key")} ~ '^[a-z][a-z0-9_]{0,62}$'),
66874
- ${k("name")} text not null check (length(${k("name")}) between 1 and 200),
66875
- ${k("currency")} char(3) check (${k("currency")} is null or ${k("currency")} ~ '^[A-Z]{3}$'),${column("categories", "limitAmount", (name) => `${name} bigint check (${name} is null or ${name} > 0)`)}${column("categories", "receiptOver", (name) => `${name} bigint check (${name} is null or ${name} >= 0)`)}
67080
+ ${column("categories", "key", (name) => `${name} text not null check (${name} ~ '^[a-z][a-z0-9_]{0,62}$')`).slice(1)}
67081
+ ${k("name")} text not null check (length(${k("name")}) between 1 and 200),${column("categories", "currency", (name) => `${name} char(3) check (${name} is null or ${name} ~ '^[A-Z]{3}$')`)}${column("categories", "limitAmount", (name) => `${name} bigint check (${name} is null or ${name} > 0)`)}${column("categories", "receiptOver", (name) => `${name} bigint check (${name} is null or ${name} >= 0)`)}
66876
67082
  ${k("archivedAt")} timestamptz,
66877
67083
  ${k("createdAt")} timestamptz not null default now(),
66878
67084
  ${k("updatedAt")} timestamptz not null default now(),
66879
- unique (${k("tenant")}, ${k("key")}),
66880
- unique (${k("tenant")}, ${k("id")})${policyCheck}
66881
- );${appUniqueIndex(ctx, "categories", ["tenant", "key"])}${appUniqueIndex(ctx, "categories", ["tenant", "id"])}
67085
+ ${ctx.has("categories", "key") ? ` unique (${k("tenant")}, ${k("key")}),\n` : ""} unique (${k("tenant")}, ${k("id")})${policyCheck}
67086
+ );${addExtraColumns(categories, expenseCategoryExtras(ctx))}${ctx.has("categories", "key") ? appUniqueIndex(ctx, "categories", ["tenant", "key"]) : ""}${appUniqueIndex(ctx, "categories", ["tenant", "id"])}
66882
67087
  ${lockModuleTable(ctx, "categories", { read: true })}
66883
67088
  drop policy if exists ${index("categories", "read")} on ${categories};
66884
67089
  ${renderPolicy(policy$1({
@@ -66946,6 +67151,7 @@ function build$71(ctx) {
66946
67151
  if (ctx.mode === "custom") return "";
66947
67152
  const approvals = expenseApprovals(ctx);
66948
67153
  const standalone = expensesStandalone(ctx);
67154
+ if (!ctx.has("categories", "currency") && (ctx.has("categories", "limitAmount") || ctx.has("categories", "receiptOver"))) throw new TypeError("blocks.expenses: a category limit or receipt threshold needs the currency column; map limitAmount and receiptOver to null too");
66949
67155
  for (const needed of standalone ? [] : approvals ? ["approvals", "ledger"] : ["ledger"]) if (ctx.of(needed).mode === "custom") throw new TypeError(`blocks.expenses needs the ${needed} tables; ${needed} can't be in custom mode`);
66950
67156
  return `${schemaPreamble(ctx)}
66951
67157
  -- Expenses: reports of lines in categories, spend policies checked on
@@ -85379,6 +85585,82 @@ function invoiceFunctions(ctx, n) {
85379
85585
  "paid"
85380
85586
  ])}
85381
85587
  returning * into ${alias};`;
85588
+ const keep = (logical, value, key) => has(logical) ? `,\n ${i(logical)} = case when update_invoice.attrs ? ${sqlString(key)} then ${value} else x.${i(logical)} end` : "";
85589
+ const relations = ctx.installed("relations") ? ctx.of("relations") : void 0;
85590
+ const updateInvoiceSql = () => `
85591
+ -- Changes a draft's header. attrs: title, company and contact ({ type, id },
85592
+ -- null clears), termsDays, note, depositBps, pricesIncludeTax and the extra
85593
+ -- columns by name. A key left out keeps its value.
85594
+ create or replace function ${fn("update_invoice")}(invoice uuid, attrs jsonb)
85595
+ returns jsonb
85596
+ language plpgsql
85597
+ security definer
85598
+ set search_path = ''
85599
+ as $$
85600
+ declare
85601
+ v_row ${t("invoices")};
85602
+ v_company_type text := coalesce(update_invoice.attrs -> 'company' ->> 'type', ${sqlString(n.company)});
85603
+ v_company_id text := update_invoice.attrs -> 'company' ->> 'id';
85604
+ v_contact_type text := coalesce(update_invoice.attrs -> 'contact' ->> 'type', ${sqlString(n.contact)});
85605
+ v_contact_id text := update_invoice.attrs -> 'contact' ->> 'id';
85606
+ begin
85607
+ select * into v_row from ${t("invoices")} x where x.${i("id")} = update_invoice.invoice and ${can("x", n.update)} for update;
85608
+ if v_row.${i("id")} is null then
85609
+ ${fail$1("INVOICE_NOT_FOUND", "no such invoice you can edit", "P0002")}
85610
+ end if;
85611
+ if ${st(`v_row.${i("status")}`, ["draft"], true)} then
85612
+ ${fail$1("INVOICE_NOT_DRAFT", "only a draft changes", "55000")}
85613
+ end if;
85614
+ if jsonb_typeof(update_invoice.attrs) is distinct from 'object'
85615
+ or (update_invoice.attrs ? 'title' and nullif(trim(update_invoice.attrs ->> 'title'), '') is null) then
85616
+ ${fail$1("INVOICE_ATTRS_INVALID", "attrs is an object, and a title isn't empty", "22023")}
85617
+ 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")}
85618
+ begin
85619
+ update ${t("invoices")} x set
85620
+ ${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")},
85621
+ ${i("updatedAt")} = now()${updateExtraColumns(t("invoices"), n.extras, "update_invoice.attrs")}
85622
+ where x.${i("id")} = v_row.${i("id")}
85623
+ returning * into v_row;
85624
+ exception when check_violation or invalid_text_representation or not_null_violation then
85625
+ ${fail$1("INVOICE_ATTRS_INVALID", "an invoice field has an invalid value", "22023")}
85626
+ end;${n.appTotals || !has("pricesIncludeTax") ? "" : `
85627
+ if update_invoice.attrs ? 'pricesIncludeTax' then
85628
+ perform ${fn("set_invoice_lines_recount")}(v_row.${i("id")});
85629
+ end if;`}
85630
+ ${record("invoice.updated", "v_row")}
85631
+ return (select ${row("x")} from ${t("invoices")} x where x.${i("id")} = v_row.${i("id")});
85632
+ end;
85633
+ $$;
85634
+ ${userGrant(`${fn("update_invoice")}(uuid, jsonb)`)}
85635
+
85636
+ -- Deletes a draft with its lines${charges ? " and charges" : ""}. An issued invoice is voided instead.
85637
+ create or replace function ${fn("delete_invoice")}(invoice uuid)
85638
+ returns boolean
85639
+ language plpgsql
85640
+ security definer
85641
+ set search_path = ''
85642
+ as $$
85643
+ declare
85644
+ v_row ${t("invoices")};
85645
+ begin
85646
+ select * into v_row from ${t("invoices")} x where x.${i("id")} = delete_invoice.invoice and ${can("x", n.remove)} for update;
85647
+ if v_row.${i("id")} is null then
85648
+ ${fail$1("INVOICE_NOT_FOUND", "no such invoice you can delete", "P0002")}
85649
+ end if;
85650
+ if ${st(`v_row.${i("status")}`, ["draft"], true)} then
85651
+ ${fail$1("INVOICE_NOT_DRAFT", "only a draft is deleted; void an issued invoice", "55000")}
85652
+ end if;${charges ? `
85653
+ delete from ${t("charges")} y where y.${ch("invoice")} = v_row.${i("id")};` : ""}
85654
+ delete from ${t("lines")} y where y.${l("parent")} = v_row.${i("id")};${relations === void 0 ? "" : `
85655
+ delete from ${relations.table("relations")} y
85656
+ where y.${relations.col("relations", "kind")} = 'created_from' and y.${relations.col("relations", "sourceType")} = 'invoice' and y.${relations.col("relations", "sourceId")} = v_row.${i("id")}::text;`}
85657
+ delete from ${t("invoices")} x where x.${i("id")} = v_row.${i("id")};
85658
+ ${record("invoice.deleted", "v_row")}
85659
+ return true;
85660
+ end;
85661
+ $$;
85662
+ ${userGrant(`${fn("delete_invoice")}(uuid)`)}
85663
+ `;
85382
85664
  const quotes = ctx.installed("quotes") ? ctx.of("quotes") : void 0;
85383
85665
  const fromQuote = quotes === void 0 ? "" : (() => {
85384
85666
  const q = (column) => quotes.col("quotes", column);
@@ -85609,7 +85891,7 @@ begin
85609
85891
  end;
85610
85892
  $$;
85611
85893
  ${userGrant(`${fn("create_invoice")}(${ctx.idType}, jsonb, jsonb)`)}
85612
- ${lineItemsSql(ctx, {
85894
+ ${updateInvoiceSql()}${lineItemsSql(ctx, {
85613
85895
  lines: "lines",
85614
85896
  parent: "invoices",
85615
85897
  frozen: st(`p.${i("status")}`, ["draft"], true),
@@ -85968,6 +86250,14 @@ const NAMES$56 = {
85968
86250
  subject: "invoices",
85969
86251
  payload: [...INVOICE]
85970
86252
  },
86253
+ "invoice.updated": {
86254
+ subject: "invoices",
86255
+ payload: [...INVOICE]
86256
+ },
86257
+ "invoice.deleted": {
86258
+ subject: "invoices",
86259
+ payload: [...INVOICE]
86260
+ },
85971
86261
  "invoice.issued": {
85972
86262
  subject: "invoices",
85973
86263
  payload: [
@@ -86254,6 +86544,7 @@ function build$55(ctx) {
86254
86544
  void: finer("void", "manage"),
86255
86545
  writeOff: finer("writeOff", "manage"),
86256
86546
  reverse: finer("reverse", "manage"),
86547
+ remove: sqlString(ctx.config.permissions["delete"] ?? ctx.config.permissions["update"] ?? ctx.permissionKey("write", keys.write)),
86257
86548
  company: ctx.text("company", "company"),
86258
86549
  contact: ctx.text("contact", "person"),
86259
86550
  prefix: ctx.text("prefix", "INV-"),
@@ -86289,6 +86580,16 @@ function contract$48(ctx) {
86289
86580
  ],
86290
86581
  returns: "jsonb"
86291
86582
  },
86583
+ {
86584
+ name: "update_invoice",
86585
+ args: ["uuid", "jsonb"],
86586
+ returns: "jsonb"
86587
+ },
86588
+ {
86589
+ name: "delete_invoice",
86590
+ args: ["uuid"],
86591
+ returns: "boolean"
86592
+ },
86292
86593
  {
86293
86594
  name: "set_invoice_lines",
86294
86595
  args: ["uuid", "jsonb"],
@@ -89542,7 +89843,8 @@ const LEAVE_NAMES = {
89542
89843
  "extraColumns",
89543
89844
  "feed",
89544
89845
  "approvals",
89545
- "owner"
89846
+ "owner",
89847
+ "reapprove"
89546
89848
  ],
89547
89849
  tables: {
89548
89850
  types: {
@@ -89973,6 +90275,10 @@ ${parts ? ` and ${existing.first} <= ${halfDays(starts, ends, "v_start", "v
89973
90275
  v_owner := v_row.${q("employee")};
89974
90276
  v_user := ${owner.userOf(`v_row.${q("employee")}`)};` : `
89975
90277
  v_me := v_row.${q("user")};`;
90278
+ const reapproveOwn = ctx.flag("reapprove", false);
90279
+ const reapproveKey = ctx.config.permissions["reapprove"];
90280
+ const reapproves = reapproveOwn || reapproveKey !== void 0;
90281
+ const reapproveHolder = reapproveKey === void 0 ? "false" : ctx.can("tenant", `v_row.${q("tenant")}`, sqlString(reapproveKey));
89976
90282
  const updateBase = `uuid, date, date, text, numeric, text${parts ? ", text, text" : ""}`;
89977
90283
  const keepParts = (part) => `coalesce(update_leave_request.${part}_part, case when update_leave_request.partial is null then ${part === "start" ? leaveStartPart(ctx, "v_old") : leaveEndPart(ctx, "v_old")} end)`;
89978
90284
  const editFunctions = `
@@ -89996,7 +90302,7 @@ declare
89996
90302
  v_type ${types}%rowtype;
89997
90303
  v_partial text;${parts ? "\n v_start text;\n v_end text;" : ""}
89998
90304
  v_amount numeric;
89999
- v_manager boolean;
90305
+ v_manager boolean;${reapproves ? "\n v_holder boolean;\n v_reapprove boolean;" : ""}
90000
90306
  v_status text;
90001
90307
  v_starts date;
90002
90308
  v_ends date;${approvalVar}${approvals === void 0 ? "" : "\n v_request jsonb;"}
@@ -90007,16 +90313,20 @@ begin
90007
90313
  end if;${loadApproval}
90008
90314
  v_old := v_row;
90009
90315
  v_manager := ${SERVICE_CALLER$1} or ${ctx.can("tenant", `v_row.${q("tenant")}`, manage)}${owner.employee ? ` or ${owner.manages(`v_row.${q("tenant")}`, `v_row.${q("employee")}`)}` : ""};
90010
- if not (v_manager or coalesce(${owner.requester("v_row")} = auth.uid(), false)) then
90316
+ ${reapproves ? ` v_holder := ${reapproveHolder};\n` : ""} if not (v_manager${reapproves ? " or v_holder" : ""} or coalesce(${owner.requester("v_row")} = auth.uid(), false)) then
90011
90317
  ${forbidden("not allowed to change this leave request")}
90012
90318
  end if;
90013
90319
  v_status := ${status("v_row", approvals === void 0 ? "v_row" : "v_approval")};
90014
90320
  if v_status not in ('pending', 'approved') then
90015
90321
  ${fail$1("LEAVE_REQUEST_CLOSED", "only a pending or approved leave request changes", "55000")}
90016
- end if;
90322
+ end if;${reapproves ? `
90323
+ v_reapprove := v_status = 'approved' and not v_manager;
90324
+ if v_reapprove and not (v_holder${reapproveOwn ? ` or coalesce(${owner.requester("v_row")} = auth.uid(), false)` : ""}) then
90325
+ ${forbidden("approved leave is changed by a manager")}
90326
+ end if;` : `
90017
90327
  if v_status = 'approved' and not v_manager then
90018
90328
  ${forbidden("approved leave is changed by a manager")}
90019
- end if;
90329
+ end if;`}
90020
90330
  select * into v_type from ${types} x where x.${ty("id")} = v_row.${q("type")};${ownerFromRow}
90021
90331
  v_starts := coalesce(update_leave_request.starts_on, v_row.${q("startsOn")});
90022
90332
  v_ends := coalesce(update_leave_request.ends_on, v_row.${q("endsOn")});
@@ -90045,12 +90355,14 @@ ${overlapCheck(`v_row.${q("tenant")}`, "v_starts", "v_ends", `v_row.${q("id")}`)
90045
90355
  end if;`}
90046
90356
  if v_status = 'approved' then${taken("v_old", 1, "changed")}
90047
90357
  end if;
90048
- update ${requests} x set ${q("startsOn")} = v_starts, ${q("endsOn")} = v_ends${ctx.has("requests", "partial") ? `, ${q("partial")} = ${ctx.cast("requests", "partial", "v_partial")}` : ""}${parts ? `, ${q("startPart")} = ${ctx.cast("requests", "startPart", "v_start")}, ${q("endPart")} = ${ctx.cast("requests", "endPart", "v_end")}` : ""}, ${q("amount")} = v_amount${ctx.has("requests", "note") ? `, ${q("note")} = case when update_leave_request.note is null then x.${q("note")} else nullif(trim(update_leave_request.note), '') end` : ""}, ${q("updatedAt")} = now()${updateExtraColumns(requests, extras, "update_leave_request.fields")}
90358
+ update ${requests} x set ${q("startsOn")} = v_starts, ${q("endsOn")} = v_ends${ctx.has("requests", "partial") ? `, ${q("partial")} = ${ctx.cast("requests", "partial", "v_partial")}` : ""}${parts ? `, ${q("startPart")} = ${ctx.cast("requests", "startPart", "v_start")}, ${q("endPart")} = ${ctx.cast("requests", "endPart", "v_end")}` : ""}, ${q("amount")} = v_amount${ctx.has("requests", "note") ? `, ${q("note")} = case when update_leave_request.note is null then x.${q("note")} else nullif(trim(update_leave_request.note), '') end` : ""}, ${q("updatedAt")} = now()${reapproves ? `, ${q("approvedAt")} = case when v_reapprove then null else x.${q("approvedAt")} end${statusMode ? `${decision("decidedBy", `case when v_reapprove then null else x.${q("decidedBy")} end`)}${decision("decisionNote", `case when v_reapprove then null else x.${q("decisionNote")} end`)}` : ""}` : ""}${updateExtraColumns(requests, extras, "update_leave_request.fields")}
90049
90359
  where x.${q("id")} = v_row.${q("id")}
90050
90360
  returning * into v_row;
90051
- if v_status = 'approved' then${taken("v_row", -1)}
90052
- end if;${approvals === void 0 ? "" : `
90053
- if v_status = 'pending' then
90361
+ if v_status = 'approved'${reapproves ? " and not v_reapprove" : ""} then${taken("v_row", -1)}
90362
+ end if;${approvals === void 0 ? reapproves && autoApproved !== "" ? `
90363
+ if v_reapprove then${autoApproved.replaceAll("\n ", "\n ")}
90364
+ end if;` : "" : `
90365
+ if v_status = 'pending'${reapproves ? " or v_reapprove" : ""} then
90054
90366
  update ${ar} p set ${a("status")} = 'cancelled', ${a("decidedAt")} = now()
90055
90367
  where p.${a("id")} = v_row.${q("approval")} and p.${a("status")} = 'pending';${openApproval(`v_row.${q("tenant")}`).replaceAll("\n ", "\n ")}${autoApproved.replaceAll("\n ", "\n ")}
90056
90368
  end if;`}