better-supabase 0.40.0 → 0.42.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{agents-BwUHtvD6.d.ts → agents-BAiLeoR-.d.ts} +3 -3
- package/dist/{ai-cache-CPOP2PYz.d.ts → ai-cache-B94R1da7.d.ts} +3 -3
- package/dist/{ai-chat-BZhfCHHr.d.ts → ai-chat-rQ7Ftq9W.d.ts} +3 -3
- package/dist/{ai-schedules-ChJkI2jo.d.ts → ai-schedules-DIiPmFgn.d.ts} +4 -4
- package/dist/ai-sdk/agents/index.d.ts +6 -6
- package/dist/ai-sdk/batches/index.d.ts +3 -3
- package/dist/ai-sdk/cache/index.d.ts +1 -1
- package/dist/ai-sdk/chat/index.d.ts +2 -2
- package/dist/ai-sdk/embeddings/index.d.ts +2 -2
- package/dist/ai-sdk/files/index.d.ts +1 -1
- package/dist/ai-sdk/index.d.ts +5 -5
- package/dist/ai-sdk/mcp/index.d.ts +1 -1
- package/dist/ai-sdk/memory/index.d.ts +3 -3
- package/dist/ai-sdk/workflow/index.d.ts +3 -3
- package/dist/{api-keys-BncNDlWG.d.ts → api-keys-U3JQ8IlM.d.ts} +2 -2
- package/dist/{app-tables-jaQmdgAM.d.ts → app-tables-DGgCgRwq.d.ts} +1 -1
- package/dist/{approvals-CXW3yFWZ.d.ts → approvals-CYbTzQ7v.d.ts} +112 -13
- package/dist/{approvals-D8gR1R8R.js → approvals-cyL5CmU7.js} +49 -19
- package/dist/{assistant-5heV2GeR.d.ts → assistant-B1p5mYaM.d.ts} +2 -2
- package/dist/{authorization-Ul_ApMYW.d.ts → authorization-CcvJbvr1.d.ts} +62 -8
- package/dist/{automations-D4QTP8nI.js → automations-CJhRmPmq.js} +3 -1
- package/dist/{bind-B2GlypM6.d.ts → bind-B71jMEGG.d.ts} +4 -4
- package/dist/{block-env-Bcr-jEA1.d.ts → block-env-DzYTC9d1.d.ts} +4 -4
- package/dist/{block-helpers-BNtM1tqy.d.ts → block-helpers-Sj-efEhC.d.ts} +15 -1
- package/dist/{block-hooks-CtMsgLQr.d.ts → block-hooks-VW4knarE.d.ts} +1 -1
- package/dist/{block-subjects-BumEsEYb.js → block-subjects-a_ECM9o0.js} +1 -1
- package/dist/{block-tables-nkIjJ1ly.d.ts → block-tables-B92SBFqM.d.ts} +1 -1
- package/dist/blocks/access-requests/index.d.ts +3 -3
- package/dist/blocks/activities/index.d.ts +6 -6
- package/dist/blocks/agents/index.d.ts +2 -2
- package/dist/blocks/ai-cache/index.d.ts +2 -2
- package/dist/blocks/ai-chat/index.d.ts +6 -6
- package/dist/blocks/ai-files/index.d.ts +2 -2
- package/dist/blocks/ai-keys/index.d.ts +2 -2
- package/dist/blocks/ai-schedules/index.d.ts +2 -2
- package/dist/blocks/announcements/index.d.ts +6 -6
- package/dist/blocks/api-keys/index.d.ts +2 -2
- package/dist/blocks/approvals/index.d.ts +4 -3
- package/dist/blocks/approvals/index.js +3 -2
- package/dist/blocks/assets/index.d.ts +3 -3
- package/dist/blocks/assignment/index.d.ts +3 -3
- package/dist/blocks/attachments/index.d.ts +2 -2
- package/dist/blocks/audit/index.d.ts +6 -6
- package/dist/blocks/automations/index.d.ts +6 -6
- package/dist/blocks/billable-time/index.d.ts +3 -3
- package/dist/blocks/billing/index.d.ts +4 -4
- package/dist/blocks/bookings/index.d.ts +3 -3
- package/dist/blocks/bulk/index.d.ts +2 -2
- package/dist/blocks/calendar/index.d.ts +3 -3
- package/dist/blocks/catalog/index.d.ts +3 -3
- package/dist/blocks/channels/index.d.ts +3 -3
- package/dist/blocks/collections/index.d.ts +3 -3
- package/dist/blocks/comments/index.d.ts +8 -8
- package/dist/blocks/compliance/index.d.ts +3 -3
- package/dist/blocks/connectors/index.d.ts +2 -2
- package/dist/blocks/contacts/index.d.ts +3 -3
- package/dist/blocks/content/index.d.ts +3 -3
- package/dist/blocks/contracts/index.d.ts +3 -3
- package/dist/blocks/courses/index.d.ts +3 -3
- package/dist/blocks/created-by/index.d.ts +1 -1
- package/dist/blocks/custom-fields/index.d.ts +3 -3
- package/dist/blocks/data-lifecycle/index.d.ts +4 -4
- package/dist/blocks/deals/index.d.ts +3 -3
- package/dist/blocks/dispatch/index.d.ts +3 -3
- package/dist/blocks/documents/index.d.ts +2 -2
- package/dist/blocks/domains/index.d.ts +4 -4
- package/dist/blocks/donations/index.d.ts +3 -3
- package/dist/blocks/drive/index.d.ts +4 -4
- package/dist/blocks/employees/index.d.ts +4 -4
- package/dist/blocks/enrichment/index.d.ts +3 -3
- package/dist/blocks/enrollments/index.d.ts +3 -3
- package/dist/blocks/entitlements/index.d.ts +4 -4
- package/dist/blocks/expenses/index.d.ts +7 -3
- package/dist/blocks/expenses/index.js +5 -3
- package/dist/blocks/field-history/index.d.ts +3 -3
- package/dist/blocks/flags/index.d.ts +3 -3
- package/dist/blocks/forecasts/index.d.ts +3 -3
- package/dist/blocks/forms/index.d.ts +4 -4
- package/dist/blocks/goals/index.d.ts +3 -3
- package/dist/blocks/guests/index.d.ts +3 -3
- package/dist/blocks/hiring/index.d.ts +3 -3
- package/dist/blocks/identities/index.d.ts +3 -3
- package/dist/blocks/imports/index.d.ts +2 -2
- package/dist/blocks/inbox/index.d.ts +8 -8
- package/dist/blocks/incidents/index.d.ts +3 -3
- package/dist/blocks/index.d.ts +4 -4
- package/dist/blocks/inventory/index.d.ts +4 -4
- package/dist/blocks/invoices/index.d.ts +21 -8
- package/dist/blocks/invoices/index.js +20 -10
- package/dist/blocks/knowledge/index.d.ts +2 -2
- package/dist/blocks/lead-scoring/index.d.ts +4 -4
- package/dist/blocks/leases/index.d.ts +3 -3
- package/dist/blocks/leave/index.d.ts +5 -3
- package/dist/blocks/leave/index.js +3 -2
- package/dist/blocks/ledger/index.d.ts +3 -3
- package/dist/blocks/mail-sync/index.d.ts +2 -2
- package/dist/blocks/memberships/index.d.ts +1 -1
- package/dist/blocks/memory/index.d.ts +3 -3
- package/dist/blocks/messaging/index.d.ts +7 -7
- package/dist/blocks/metrics/index.d.ts +4 -4
- package/dist/blocks/mfa/index.d.ts +2 -2
- package/dist/blocks/moderation/index.d.ts +3 -3
- package/dist/blocks/notifications/index.d.ts +6 -6
- package/dist/blocks/numbering/index.d.ts +2 -2
- package/dist/blocks/oauth-server/index.d.ts +3 -3
- package/dist/blocks/onboarding/index.d.ts +4 -4
- package/dist/blocks/orders/index.d.ts +5 -5
- package/dist/blocks/organizations/index.d.ts +5 -5
- package/dist/blocks/outbox/index.d.ts +2 -2
- package/dist/blocks/passes/index.d.ts +5 -5
- package/dist/blocks/permissions/index.d.ts +5 -5
- package/dist/blocks/pipelines/index.d.ts +3 -3
- package/dist/blocks/posts/index.d.ts +3 -3
- package/dist/blocks/profiles/index.d.ts +3 -3
- package/dist/blocks/promotions/index.d.ts +3 -3
- package/dist/blocks/push/index.d.ts +4 -4
- package/dist/blocks/queue/index.d.ts +4 -4
- package/dist/blocks/quotes/index.d.ts +57 -12
- package/dist/blocks/quotes/index.js +35 -7
- package/dist/blocks/rank/index.d.ts +4 -4
- package/dist/blocks/reactions/index.d.ts +6 -6
- package/dist/blocks/relations/index.d.ts +4 -4
- package/dist/blocks/reminders/index.d.ts +4 -4
- package/dist/blocks/reviews/index.d.ts +3 -3
- package/dist/blocks/saved-views/index.d.ts +3 -3
- package/dist/blocks/scores/index.d.ts +3 -3
- package/dist/blocks/search/index.d.ts +5 -5
- package/dist/blocks/security-events/index.d.ts +4 -4
- package/dist/blocks/segments/index.d.ts +3 -3
- package/dist/blocks/sequences/index.d.ts +3 -3
- package/dist/blocks/service-accounts/index.d.ts +3 -3
- package/dist/blocks/sessions/index.d.ts +2 -2
- package/dist/blocks/settings/index.d.ts +4 -4
- package/dist/blocks/share-links/index.d.ts +3 -3
- package/dist/blocks/shipments/index.d.ts +3 -3
- package/dist/blocks/signatures/index.d.ts +3 -3
- package/dist/blocks/signing-keys/index.d.ts +2 -2
- package/dist/blocks/sla/index.d.ts +3 -3
- package/dist/blocks/sso/index.d.ts +4 -4
- package/dist/blocks/state-machine/index.d.ts +3 -14
- package/dist/blocks/subjects/index.d.ts +3 -3
- package/dist/blocks/tags/index.d.ts +4 -4
- package/dist/blocks/tasks/index.d.ts +5 -5
- package/dist/blocks/teams/index.d.ts +3 -3
- package/dist/blocks/templates/index.d.ts +6 -6
- package/dist/blocks/time-tracking/index.d.ts +3 -3
- package/dist/blocks/timeline/index.d.ts +3 -3
- package/dist/blocks/trash/index.d.ts +3 -3
- package/dist/blocks/undo/index.d.ts +3 -3
- package/dist/blocks/updated-at/index.d.ts +1 -1
- package/dist/blocks/usage/index.d.ts +3 -3
- package/dist/blocks/vercel-marketplace/index.d.ts +3 -3
- package/dist/blocks/versions/index.d.ts +3 -3
- package/dist/blocks/waitlist/index.d.ts +3 -3
- package/dist/blocks/webhooks/index.d.ts +5 -5
- package/dist/blocks/workflow-editor/index.d.ts +7 -7
- package/dist/blocks/workflows/index.d.ts +5 -5
- package/dist/{bookings-Dj5cvXKv.d.ts → bookings-CHUzFwOI.d.ts} +3 -3
- package/dist/chat-sdk/index.d.ts +3 -3
- package/dist/claims/index.d.ts +4 -4
- package/dist/cli/add-BbhRYaFe.js +1 -0
- package/dist/cli/{add-BVs8Ym-K.js → add-NosuEQn1.js} +10 -10
- package/dist/cli/{add-DP1ct-7e.js → add-U0pyhIyx.js} +2 -2
- package/dist/cli/{app-table-files-gjMyFqH4.js → app-table-files-DUi898lB.js} +2 -2
- package/dist/cli/{app-tables-B26PHK75.js → app-tables-BINtREbx.js} +2 -2
- package/dist/cli/{backfill-CP_LpTK2.js → backfill-VfqI5GqN.js} +1 -1
- package/dist/cli/bin.js +1 -1
- package/dist/cli/{blocks-Ewp49Kbm.js → blocks-Bo2Lw2UO.js} +1 -1
- package/dist/cli/{blocks-CpBLp57s.js → blocks-DsEaPf6J.js} +1 -1
- package/dist/cli/{cache-BxxtUXVN.js → cache-CNJD8OdR.js} +1 -1
- package/dist/cli/{codemod-CGCxMEyD.js → codemod-BWa3Bte6.js} +1 -1
- package/dist/cli/{content-mapper-DngBJv4r.js → content-mapper-Dl50Ny6a.js} +2 -2
- package/dist/cli/{doctor-3dcMraMn.js → doctor-B9GtOGSa.js} +15 -15
- package/dist/cli/{gen-DrXxFwUU.js → gen-CIUD1sgB.js} +11 -11
- package/dist/cli/index.d.ts +1 -1
- package/dist/cli/index.js +6 -6
- package/dist/cli/{init-bVKQ4Onb.js → init-wl5jk5vX.js} +8 -8
- package/dist/cli/{live-CHTbAqdS.js → live-B0f_X3rI.js} +2 -2
- package/dist/cli/{mcp-BbmhntrR.js → mcp-CZWaBkXY.js} +2 -2
- package/dist/cli/{metadata-BS56R_eb.js → metadata-Bi5eQP4w.js} +3 -3
- package/dist/cli/{migrate-DV6a9-jI.js → migrate-DMITLPEu.js} +1 -1
- package/dist/cli/{migration-safety-Ce9IQwmJ.js → migration-safety-2n8e8njJ.js} +1 -1
- package/dist/cli/{migrations-CCCnMhmM.js → migrations-C5k9hNOo.js} +2 -2
- package/dist/cli/{module-migration-C0cAzpNa.js → module-migration-BFchEhAJ.js} +2 -2
- package/dist/cli/{powersync-OIIpG-y_.js → powersync-DViexv6m.js} +3 -3
- package/dist/cli/powersync-i7KJcTtM.js +1 -0
- package/dist/cli/{print-BGF3d6O2.js → print-ChX1vQhO.js} +2 -2
- package/dist/cli/{providers-fEzlYSLs.js → providers-lwK2lplZ.js} +1 -1
- package/dist/cli/{prune-workflows-Bx7J5T3a.js → prune-workflows-DO3nRZFF.js} +1 -1
- package/dist/cli/{remove-Ds4N6WvD.js → remove-WB9dFyNn.js} +5 -5
- package/dist/cli/{render-BeZToAp-.js → render-B0MMWWZE.js} +3 -3
- package/dist/cli/{run-iUmtksq5.js → run-CMvwtBX9.js} +27 -27
- package/dist/cli/{run-DR0sTyNQ.js → run-CmJbNG2-.js} +9 -9
- package/dist/cli/{shared-BCWYvKeR.js → shared-BL5kcRdz.js} +1 -1
- package/dist/cli/{snapshot-CfgRxTQq.js → snapshot-CVB9Ri2a.js} +2 -2
- package/dist/cli/{source-Ct3ZCy6p.js → source-COGgsYiV.js} +1 -1
- package/dist/cli/{spec-1eEq2P4T.js → spec-002zD_9Z.js} +1 -1
- package/dist/cli/{spec-9vb-or-k.js → spec-CH6Qd2LE.js} +2 -2
- package/dist/cli/{sql-layout-cYsnyjRf.js → sql-layout-jZOzCj-S.js} +2 -2
- package/dist/cli/{sync-XpcpINnx.js → sync-I4x-1aVx.js} +4 -4
- package/dist/cli/{upgrade-A18FY5Iy.js → upgrade-BRp5AxAY.js} +2 -2
- package/dist/cli/{upgrade-DXhyb2jV.js → upgrade-C60BZggI.js} +5 -5
- package/dist/cli/{version-PcwPOm4G.js → version-CRCAxS2s.js} +1 -1
- package/dist/client/index.d.ts +5 -5
- package/dist/client/native/index.d.ts +4 -4
- package/dist/config/index.d.ts +2 -2
- package/dist/config/index.js +4 -4
- package/dist/{config-qqAfS_1_.js → config-2SwAe0Im.js} +3 -3
- package/dist/{config-BRGMUEE2.js → config-BND2PFGs.js} +1 -1
- package/dist/{connectors-DDsdz-cn.d.ts → connectors-OMJkoAP6.d.ts} +2 -2
- package/dist/{context-dHluCmud.d.ts → context-DXWyPNzr.d.ts} +4 -2
- package/dist/contract/index.d.ts +4 -4
- package/dist/{controller-BQXgMwWN.d.ts → controller-D3MPVovD.d.ts} +1 -1
- package/dist/{conversion-CLBBITW5.d.ts → conversion-BShzA-u-.d.ts} +1 -1
- package/dist/create/index.d.ts +3 -3
- package/dist/create/index.js +3 -3
- package/dist/create/lite/index.d.ts +3 -3
- package/dist/create/lite/index.js +2 -2
- package/dist/{define-block-CDw9YGVh.d.ts → define-block-DBD7yhQg.d.ts} +5 -5
- package/dist/{documents-Btk0MhC0.d.ts → documents-CNVPrE_0.d.ts} +2 -2
- package/dist/{embeddings-CI6P_mtD.d.ts → embeddings-C2PBJ2Lx.d.ts} +1 -1
- package/dist/{entitlements-Jh_w-PgX.d.ts → entitlements-CljrSoWD.d.ts} +1 -1
- package/dist/eve/index.d.ts +5 -5
- package/dist/eve/index.js +1 -1
- package/dist/{eve-DleYrhwj.d.ts → eve-CtQd4iaO.d.ts} +2 -2
- package/dist/{executor-uNDJBzT8.d.ts → executor-DL7cZ-3T.d.ts} +1 -1
- package/dist/{field-errors-DIDkgzFA.d.ts → field-errors-C4NOUBpu.d.ts} +6 -6
- package/dist/{flags-Cuew4tGx.d.ts → flags-BrXfCmGB.d.ts} +1 -1
- package/dist/flags-sdk/index.d.ts +1 -1
- package/dist/{gateway-B9k89AC4.d.ts → gateway-DJX-XUWl.d.ts} +3 -3
- package/dist/{inbox-yGfUVQr2.d.ts → inbox-DiQ8KhG8.d.ts} +4 -4
- package/dist/{index-DAS_5OfK.d.ts → index-1_-lg9Gc.d.ts} +1 -1
- package/dist/{index-DhcLJAtX.d.ts → index-Bjj-GNhd.d.ts} +1 -1
- package/dist/{index-y70eTezB.d.ts → index-BrGOE0c2.d.ts} +2 -2
- package/dist/{index-g_eFnFqo.d.ts → index-CUxdZYSi.d.ts} +2 -2
- package/dist/{index-xmb6YGTg.d.ts → index-D5qW2cRD.d.ts} +2 -2
- package/dist/{index-CpZ4WDDJ.d.ts → index-DWVDKVYA.d.ts} +1 -1
- package/dist/{index-IrJQqPeQ.d.ts → index-DhHtsi-q.d.ts} +3 -3
- package/dist/{index-BKz-E3Mv.d.ts → index-DmSDAFkF.d.ts} +8 -8
- package/dist/{instances-DqEZrffE.js → instances-DwrdFwKq.js} +10 -1
- package/dist/{knowledge-DWXAxvkN.d.ts → knowledge-DtECa_QW.d.ts} +4 -4
- package/dist/mapper/bin.js +5 -5
- package/dist/mcp/index.d.ts +1 -1
- package/dist/{messaging-Bfe4p9Pm.d.ts → messaging-CpQIhkFi.d.ts} +2 -2
- package/dist/next/index.d.ts +7 -7
- package/dist/{operations-Sza7UQKP.d.ts → operations-DFmuxaxW.d.ts} +1 -1
- package/dist/{options-zsLpIqBA.js → options-B1oSaIZ4.js} +2 -1
- package/dist/{options-CYZH9uxU.js → options-BXiUftgG.js} +3 -1
- package/dist/{options-Bgnm4pTD.js → options-DLJTiX29.js} +6 -1
- package/dist/otel/index.js +4 -4
- package/dist/{outbox-DikdzUKf.d.ts → outbox-Cpxpzcue.d.ts} +2 -2
- package/dist/{permissions-COamTJYz.d.ts → permissions-Bsd4mEEZ.d.ts} +1 -1
- package/dist/{ports-1M1E_r2n.d.ts → ports-BKdt_9Oe.d.ts} +1 -1
- package/dist/powersync/index.d.ts +2 -2
- package/dist/preset/index.d.ts +3 -3
- package/dist/preset/index.js +3 -3
- package/dist/{preset-Byz43PrL.js → preset-CenE7f1G.js} +2 -2
- package/dist/{project-Y2wW_nr_.js → project-Ceh2yTSv.js} +5 -5
- package/dist/{push-token-DKImhAca.d.ts → push-token-DRcEl9Ce.d.ts} +1 -1
- package/dist/query/index.d.ts +1 -1
- package/dist/react/index.d.ts +5 -5
- package/dist/react/native/index.d.ts +1 -1
- package/dist/react/server.d.ts +5 -5
- package/dist/realtime/index.d.ts +3 -3
- package/dist/{record-form-C-gIxGXe.d.ts → record-form-C-1TPtMG.d.ts} +1 -1
- package/dist/{recordings-Bw5LoocX.d.ts → recordings-BVuri85k.d.ts} +1 -1
- package/dist/records/index.d.ts +8 -8
- package/dist/{sandboxes-BF9RxxCU.d.ts → sandboxes-DKgJZYUZ.d.ts} +1 -1
- package/dist/{scores-Ce8MxQX9.d.ts → scores-BXuSVczw.d.ts} +2 -2
- package/dist/server/index.d.ts +4 -4
- package/dist/{signers-Dw9DBZjJ.d.ts → signers-UANxMfH-.d.ts} +2 -2
- package/dist/{signing-keys-FglIQ6iL.d.ts → signing-keys-DhBSWFy_.d.ts} +2 -2
- package/dist/solid/index.d.ts +5 -5
- package/dist/sql/index.d.ts +5 -5
- package/dist/sql/index.js +3 -3
- package/dist/{sql-B1FA8jTx.js → sql-BIniB45X.js} +1558 -502
- package/dist/{sso-B7w7h8RJ.d.ts → sso-Frh3sbJ1.d.ts} +2 -2
- package/dist/ssr/index.d.ts +1 -1
- package/dist/{subjects-CVjAE7nz.d.ts → subjects-DNFE2rMl.d.ts} +2 -2
- package/dist/svelte/index.d.ts +5 -5
- package/dist/{tenant-DflHpV32.d.ts → tenant--Hm8mlPy.d.ts} +1 -1
- package/dist/testing/index.d.ts +13 -13
- package/dist/testing/index.js +1 -1
- package/dist/{timeline-c6I3uxya.d.ts → timeline-BB9fKT_r.d.ts} +2 -2
- package/dist/{topic-CekU96q7.d.ts → topic-BYF-GTW9.d.ts} +1 -1
- package/dist/{types-B42S7qfO.d.ts → types-B8h0reJ4.d.ts} +2 -2
- package/dist/{types-DtiDatvu.d.ts → types-D--4dv5K.d.ts} +3 -3
- package/dist/{types-BXLiM6VM.d.ts → types-DCzgSAlU.d.ts} +2 -2
- package/dist/{types-6PMaLIyw.d.ts → types-DU_nNO7U.d.ts} +2 -2
- package/dist/{types-BdhE7I8Z.d.ts → types-LLCyr-xs.d.ts} +2 -2
- package/dist/{types-D5uf0l4_.d.ts → types-kq8S5HVE.d.ts} +1 -1
- package/dist/{types-C7K8mu9B.d.ts → types-z31g0-5T.d.ts} +3 -3
- package/dist/{undo-CdKp5_2X.d.ts → undo-BCQMqIQN.d.ts} +1 -1
- package/dist/{usage-DZ8j5Tm_.d.ts → usage-CJDj5j15.d.ts} +3 -3
- package/dist/vercel-sandbox/index.d.ts +1 -1
- package/dist/vue/index.d.ts +5 -5
- package/dist/{watch-topic-DBw411Mq.d.ts → watch-topic-tfTxgEGc.d.ts} +1 -1
- package/dist/workflow-sdk/builder/index.d.ts +3 -3
- package/dist/workflow-sdk/index.d.ts +1 -1
- package/dist/workflow-sdk/world/index.js +1 -1
- package/dist/{workflow-sdk-6psRpDIo.js → workflow-sdk-Bps7tpOv.js} +26 -1
- package/dist/{workflow-sdk-CUt0E4v6.d.ts → workflow-sdk-DzKQo265.d.ts} +2 -2
- package/dist/{workflows-BI4yKqFh.d.ts → workflows-D7HvWeNu.d.ts} +2 -2
- package/dist/yjs/index.d.ts +2 -2
- package/package.json +1 -1
- package/schemas/config-v1.json +42 -1
- package/dist/cli/add-DrwQvDYD.js +0 -1
- package/dist/cli/powersync-Cxd3a_v_.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-
|
|
6
|
+
import { c as resolveJsonSchema, i as installedBlockSubjects, l as CONFIG_DEFAULTS, o as blockColumnName, s as resolveNames } from "./block-subjects-a_ECM9o0.js";
|
|
7
7
|
import { t as DEFAULT_CLAIMS } from "./claims-CqTr_N1n.js";
|
|
8
8
|
import { o as tenantNames, r as composeNames } from "./entity-naming-BES3pkQI.js";
|
|
9
|
-
import { C as encryptedColumns, I as resolveBlock, L as tenantNameOf, N as BLOCK_SCOPES, S as columnsWithAccess, T as hiddenColumns, a as isRenamedInstance, g as appTableVersions, i as instancePrefix, l as APP_RANK_COLUMN, m as appTableEventKinds, s as APP_DELETED_AT_COLUMN, w as hasColumnAccess, x as hasComputed } from "./instances-
|
|
9
|
+
import { C as encryptedColumns, I as resolveBlock, L as tenantNameOf, N as BLOCK_SCOPES, S as columnsWithAccess, T as hiddenColumns, a as isRenamedInstance, g as appTableVersions, i as instancePrefix, l as APP_RANK_COLUMN, m as appTableEventKinds, s as APP_DELETED_AT_COLUMN, w as hasColumnAccess, x as hasComputed } from "./instances-DwrdFwKq.js";
|
|
10
10
|
import { a as RATING_BOUNDS, n as CUSTOM_FIELD_TYPES, r as FIELD_FORMATS, t as CUSTOM_FIELD_FORM_TYPES } from "./field-formats-Cap-V7UP.js";
|
|
11
11
|
import { t as isSqlType } from "./sql-type-XWMeZRAl.js";
|
|
12
12
|
import { a as sqlString, i as sqlIdent } from "./template-CNq9xcfx.js";
|
|
13
13
|
import { i as fillTemplate, l as templatePlaceholders } from "./access-sql-Dao1C0fz.js";
|
|
14
14
|
import { t as MAX_BATCH } from "./batch-limit-DqQ3d6op.js";
|
|
15
|
-
import { $ as pageSize, A as addNotNullCheck, B as extraFieldsArg, C as SCHEMA$5, D as addCheck, E as activeMembership, F as defaultPartitionName, G as jwtClaim, H as fail$1, I as disabledHelpers, J as membershipDisabledAt, K as lockTable, L as disabledHelpersNeedLaterTables, M as columnRef, N as columnsObject, O as addExtraColumns, P as defaultPartition, Q as ownRowPolicies, R as dropExpiredPartitions, S as PARTITION_VARIABLES, T as accessDefinesDisabledHelpers, U as insertExtraColumns, V as extraFieldsJson, W as jsonSchemaChecks, X as notNullCheckName, Y as membershipSuspended, Z as organizationMissing, _ as rolesOf, _t as
|
|
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-
|
|
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-
|
|
56
|
+
import { t as expensesSqlOptions } from "./options-BXiUftgG.js";
|
|
57
57
|
import { t as flagsSqlOptions } from "./options-BMO-FnOT.js";
|
|
58
58
|
import { t as formsSqlOptions } from "./options-DpwRG4tO.js";
|
|
59
59
|
import { t as goalsSqlOptions } from "./options-BNRvoEkj.js";
|
|
@@ -66,7 +66,7 @@ import { t as invoicesSqlOptions } from "./options-C5cLEJEa.js";
|
|
|
66
66
|
import { t as knowledgeSqlOptions } from "./options-CyYZvdSy.js";
|
|
67
67
|
import { t as leadScoringSqlOptions } from "./options-COfEYic3.js";
|
|
68
68
|
import { t as leasesSqlOptions } from "./options-CzIPn0fF.js";
|
|
69
|
-
import { t as leaveSqlOptions } from "./options-
|
|
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-
|
|
91
|
+
import { n as QUOTE_TO_ORDER, r as quotesSqlOptions } from "./automations-CJhRmPmq.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";
|
|
@@ -1928,7 +1928,7 @@ const CLIENT_FUNCTIONS = {
|
|
|
1928
1928
|
promotions: "apply_promotion_code create_promotion_codes delete_promotion delete_promotion_code remove_promotion_code save_promotion set_promotion_active",
|
|
1929
1929
|
push: "prune_push_tokens push_tokens_for register_push_device unregister_push_device",
|
|
1930
1930
|
queue: "advance_schedule claim_due_schedules claim_jobs complete_job enqueue_job enqueue_job_once extend_job_lease fail_job job_queue_stats list_dead_jobs list_schedules purge_job_archive replay_dead_job retry_dead_jobs schedule_job unschedule_job unschedule_tenant",
|
|
1931
|
-
quotes: "create_quote decide_quote expire_quotes portal_quote public_quote quote_version quote_versions respond_to_portal_quote respond_to_quote revise_quote send_quote set_quote_lines update_quote",
|
|
1931
|
+
quotes: "create_quote decide_quote expire_quotes portal_quote public_quote quote_version quote_versions respond_to_portal_quote respond_to_quote revise_quote send_quote set_quote_lines update_quote withdraw_quote",
|
|
1932
1932
|
rank: "move rebalance_ranks",
|
|
1933
1933
|
"rate-limit": "check_rate_limit check_rate_limits purge_rate_limits",
|
|
1934
1934
|
reactions: "delete_custom_emoji list_custom_emoji react reaction_summary save_custom_emoji vote vote_summary",
|
|
@@ -3521,7 +3521,13 @@ function migrationOptionUses(modules = {}) {
|
|
|
3521
3521
|
});
|
|
3522
3522
|
}
|
|
3523
3523
|
// src/sql/modules/approvals-policies.ts
|
|
3524
|
+
/** The action of a floor that covers every action of its subject type. */
|
|
3525
|
+
const ANY_ACTION = "*";
|
|
3526
|
+
/** The subject type of a floor that covers every subject type. */
|
|
3527
|
+
const ANY_SUBJECT = "*";
|
|
3524
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_-]*)*$/;
|
|
3525
3531
|
const UUID$7 = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
|
|
3526
3532
|
const DURATION = /^P(?=\d|T\d)(\d+Y)?(\d+M)?(\d+W)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?$/;
|
|
3527
3533
|
const WHERE$18 = "blocks.approvals.options.policies";
|
|
@@ -3555,20 +3561,44 @@ function stepOf(value, where) {
|
|
|
3555
3561
|
if (!isFields(value)) throw new TypeError(`${where} must be an object`);
|
|
3556
3562
|
const approvers = approversOf(value["approvers"], where);
|
|
3557
3563
|
const required = value["required"] ?? 1;
|
|
3564
|
+
const escalation = escalationOf(value, where);
|
|
3558
3565
|
if (required === "all") {
|
|
3559
|
-
|
|
3566
|
+
const only = Object.keys(approvers);
|
|
3567
|
+
if (only.length === 1 && approvers.permission !== void 0) return {
|
|
3568
|
+
approvers,
|
|
3569
|
+
required: "all",
|
|
3570
|
+
...escalation
|
|
3571
|
+
};
|
|
3572
|
+
if (only.length !== 1 || approvers.users === void 0) throw new TypeError(`${where}.required "all" needs approvers.users or approvers.permission and nothing else`);
|
|
3560
3573
|
return {
|
|
3561
3574
|
approvers,
|
|
3562
|
-
required: approvers.users.length
|
|
3575
|
+
required: approvers.users.length,
|
|
3576
|
+
...escalation
|
|
3563
3577
|
};
|
|
3564
3578
|
}
|
|
3565
3579
|
if (typeof required !== "number" || !Number.isInteger(required) || required < 1) throw new TypeError(`${where}.required must be a whole number or "all"`);
|
|
3566
3580
|
if (approvers.users !== void 0 && Object.keys(approvers).length === 1 && required > approvers.users.length) throw new TypeError(`${where}.required is more than approvers.users`);
|
|
3567
3581
|
return {
|
|
3568
3582
|
approvers,
|
|
3569
|
-
required
|
|
3583
|
+
required,
|
|
3584
|
+
...escalation
|
|
3585
|
+
};
|
|
3586
|
+
}
|
|
3587
|
+
function escalationOf(value, where) {
|
|
3588
|
+
const after = value["escalateAfter"];
|
|
3589
|
+
const to = value["escalateTo"];
|
|
3590
|
+
if (after === void 0 && to === void 0) return {};
|
|
3591
|
+
if (typeof after !== "string" || !DURATION.test(after) || to === void 0) throw new TypeError(`${where} needs escalateAfter (an ISO 8601 duration such as PT4H) and escalateTo together`);
|
|
3592
|
+
return {
|
|
3593
|
+
escalateAfter: after,
|
|
3594
|
+
escalateTo: approversOf(to, `${where}.escalateTo`)
|
|
3570
3595
|
};
|
|
3571
3596
|
}
|
|
3597
|
+
function effectsOf(value, where) {
|
|
3598
|
+
if (value === void 0) return [];
|
|
3599
|
+
if (!Array.isArray(value) || !value.every((item) => typeof item === "string" && KEY$1.test(item))) throw new TypeError(`${where}.effects must be a list of names`);
|
|
3600
|
+
return [...new Set(value.map(String))];
|
|
3601
|
+
}
|
|
3572
3602
|
function runOf(value, where) {
|
|
3573
3603
|
if (value === void 0) return;
|
|
3574
3604
|
if (isFields(value) && typeof value["transition"] === "string") return {
|
|
@@ -3586,7 +3616,7 @@ function runOf(value, where) {
|
|
|
3586
3616
|
* entry that tenant policies tighten) may have no steps.
|
|
3587
3617
|
*/
|
|
3588
3618
|
function policyOf(subjectType, action, value, where = `${WHERE$18}.${subjectType}.${action}`, floor = false) {
|
|
3589
|
-
if (!
|
|
3619
|
+
if (!ACTION$1.test(action) && action !== ANY_ACTION) throw new TypeError(`${where} has an invalid name`);
|
|
3590
3620
|
if (!isFields(value)) throw new TypeError(`${where} must be an object`);
|
|
3591
3621
|
const steps = value["steps"];
|
|
3592
3622
|
if (!Array.isArray(steps) || steps.length === 0 && !floor) throw new TypeError(`${where}.steps must be a non-empty list`);
|
|
@@ -3597,6 +3627,7 @@ function policyOf(subjectType, action, value, where = `${WHERE$18}.${subjectType
|
|
|
3597
3627
|
const selfApproval = value["selfApproval"] ?? false;
|
|
3598
3628
|
if (typeof selfApproval !== "boolean") throw new TypeError(`${where}.selfApproval must be a boolean`);
|
|
3599
3629
|
const run = runOf(value["run"], where);
|
|
3630
|
+
const effects = effectsOf(value["effects"], where);
|
|
3600
3631
|
return {
|
|
3601
3632
|
subjectType,
|
|
3602
3633
|
action,
|
|
@@ -3604,7 +3635,8 @@ function policyOf(subjectType, action, value, where = `${WHERE$18}.${subjectType
|
|
|
3604
3635
|
mode,
|
|
3605
3636
|
selfApproval,
|
|
3606
3637
|
...typeof expiresIn === "string" ? { expiresIn } : {},
|
|
3607
|
-
...run === void 0 ? {} : { run }
|
|
3638
|
+
...run === void 0 ? {} : { run },
|
|
3639
|
+
...effects.length === 0 ? {} : { effects }
|
|
3608
3640
|
};
|
|
3609
3641
|
}
|
|
3610
3642
|
/** `options.policies`: subject type, then action, then the policy. */
|
|
@@ -3613,7 +3645,7 @@ function approvalPolicies(ctx) {
|
|
|
3613
3645
|
if (raw === void 0) return [];
|
|
3614
3646
|
if (!isFields(raw)) throw new TypeError(`${WHERE$18} must be an object`);
|
|
3615
3647
|
return Object.entries(raw).flatMap(([subjectType, actions]) => {
|
|
3616
|
-
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`);
|
|
3617
3649
|
if (!isFields(actions)) throw new TypeError(`${WHERE$18}.${subjectType} must be an object of action to policy`);
|
|
3618
3650
|
return Object.entries(actions).map(([action, value]) => policyOf(subjectType, action, value, `${WHERE$18}.${subjectType}.${action}`, true));
|
|
3619
3651
|
});
|
|
@@ -3628,16 +3660,42 @@ function policySnapshot(policy) {
|
|
|
3628
3660
|
selfApproval: policy.selfApproval,
|
|
3629
3661
|
expiresIn: policy.expiresIn ?? null,
|
|
3630
3662
|
run: policy.run ?? null,
|
|
3631
|
-
...policy.mode === "confirm" ? { mode: policy.mode } : {}
|
|
3663
|
+
...policy.mode === "confirm" ? { mode: policy.mode } : {},
|
|
3664
|
+
...policy.effects === void 0 ? {} : { effects: policy.effects }
|
|
3632
3665
|
});
|
|
3633
3666
|
}
|
|
3634
|
-
/**
|
|
3667
|
+
/**
|
|
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.
|
|
3671
|
+
*/
|
|
3635
3672
|
function policyCase(policies) {
|
|
3636
3673
|
if (policies.length === 0) return "null::jsonb";
|
|
3637
|
-
|
|
3638
|
-
${
|
|
3674
|
+
const cases = (key, items) => `case ${key}
|
|
3675
|
+
${items.map((policy) => ` when ${sqlString(`${policy.subjectType}:${policy.action}`)} then ${sqlString(policySnapshot(policy))}::jsonb`).join("\n")}
|
|
3639
3676
|
else null::jsonb
|
|
3640
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);
|
|
3681
|
+
const exact = cases("approval_policy.subject_type || ':' || approval_policy.action", policies);
|
|
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(", ")})`;
|
|
3688
|
+
}
|
|
3689
|
+
/**
|
|
3690
|
+
* The floors as a jsonb list of `{ subjectType, action, effects }`, for the
|
|
3691
|
+
* checks that a tenant or platform policy tightens one.
|
|
3692
|
+
*/
|
|
3693
|
+
function floorsJson(policies) {
|
|
3694
|
+
return `${sqlString(JSON.stringify(policies.map((policy) => ({
|
|
3695
|
+
subjectType: policy.subjectType,
|
|
3696
|
+
action: policy.action,
|
|
3697
|
+
effects: policy.effects ?? []
|
|
3698
|
+
}))))}::jsonb`;
|
|
3641
3699
|
}
|
|
3642
3700
|
/**
|
|
3643
3701
|
* Throws when a policy names the requester's manager without the employees
|
|
@@ -8277,6 +8335,113 @@ function subjectScope(ctx, provider, type, subject) {
|
|
|
8277
8335
|
if (scope === provider.scope || !(provider.scopes ?? []).includes(scope)) throw new TypeError(`${where}: "${scope}" is not a scope ${provider.name} declares below its tenant scope "${provider.scope}". Scopes: ${(provider.scopes ?? []).filter((name) => name !== provider.scope).join(", ") || "none"}`);
|
|
8278
8336
|
return scope;
|
|
8279
8337
|
}
|
|
8338
|
+
// src/sql/modules/approvals-conditions.ts
|
|
8339
|
+
/**
|
|
8340
|
+
* `"rules"` (default) matches conditions through the automations block's rule
|
|
8341
|
+
* fields; `"payload"` matches them against the request payload in this module.
|
|
8342
|
+
*/
|
|
8343
|
+
function approvalConditions(ctx) {
|
|
8344
|
+
const raw = ctx.option("conditions") ?? "rules";
|
|
8345
|
+
if (raw !== "rules" && raw !== "payload") throw new TypeError("blocks.approvals.options.conditions must be \"rules\" or \"payload\"");
|
|
8346
|
+
return raw;
|
|
8347
|
+
}
|
|
8348
|
+
/**
|
|
8349
|
+
* `approval_condition(node, payload)`: a filter tree matched against a request
|
|
8350
|
+
* payload, by path. It visits every node, so a call with an empty payload also
|
|
8351
|
+
* checks the tree, and it refuses an unknown node or operator.
|
|
8352
|
+
*/
|
|
8353
|
+
function approvalConditionSql(ctx) {
|
|
8354
|
+
const fn = ctx.fn("approval_condition");
|
|
8355
|
+
const invalid = fail$1("APPROVAL_CONDITIONS_INVALID", "conditions must be a filter tree of groups and rules with a path and a known operator", "22023");
|
|
8356
|
+
return `
|
|
8357
|
+
-- Matches a filter tree (groups of rules with a path, an operator and a value)
|
|
8358
|
+
-- against a request payload. A number compares as a number when the payload
|
|
8359
|
+
-- value is numeric, anything else as text.
|
|
8360
|
+
create or replace function ${fn}(node jsonb, payload jsonb)
|
|
8361
|
+
returns boolean
|
|
8362
|
+
language plpgsql
|
|
8363
|
+
immutable
|
|
8364
|
+
set search_path = ''
|
|
8365
|
+
as $$
|
|
8366
|
+
declare
|
|
8367
|
+
v_child jsonb;
|
|
8368
|
+
v_any boolean := false;
|
|
8369
|
+
v_all boolean := true;
|
|
8370
|
+
v_result boolean;
|
|
8371
|
+
v_op text;
|
|
8372
|
+
v_value jsonb;
|
|
8373
|
+
v_at jsonb;
|
|
8374
|
+
v_text text;
|
|
8375
|
+
v_other text;
|
|
8376
|
+
v_numeric boolean;
|
|
8377
|
+
v_empty boolean;
|
|
8378
|
+
begin
|
|
8379
|
+
if jsonb_typeof(node) is distinct from 'object' then
|
|
8380
|
+
${invalid}
|
|
8381
|
+
end if;
|
|
8382
|
+
if node ->> 'type' = 'group' then
|
|
8383
|
+
if jsonb_typeof(node -> 'rules') is distinct from 'array'
|
|
8384
|
+
or coalesce(node ->> 'combinator', 'and') not in ('and', 'or') then
|
|
8385
|
+
${invalid}
|
|
8386
|
+
end if;
|
|
8387
|
+
for v_child in select e.value from jsonb_array_elements(node -> 'rules') e loop
|
|
8388
|
+
v_result := ${fn}(v_child, payload);
|
|
8389
|
+
v_any := v_any or v_result;
|
|
8390
|
+
v_all := v_all and v_result;
|
|
8391
|
+
end loop;
|
|
8392
|
+
return case when coalesce(node ->> 'combinator', 'and') = 'or' then v_any else v_all end;
|
|
8393
|
+
end if;
|
|
8394
|
+
if node ->> 'type' is distinct from 'rule' or jsonb_typeof(node -> 'path') is distinct from 'array' then
|
|
8395
|
+
${invalid}
|
|
8396
|
+
end if;
|
|
8397
|
+
v_op := coalesce(node ->> 'operator', '');
|
|
8398
|
+
v_value := node -> 'value';
|
|
8399
|
+
v_at := coalesce(payload, '{}'::jsonb) #> array(select jsonb_array_elements_text(node -> 'path'));
|
|
8400
|
+
v_text := v_at #>> '{}';
|
|
8401
|
+
v_other := v_value #>> '{}';
|
|
8402
|
+
v_numeric := jsonb_typeof(v_value) = 'number' and v_text ~ '^-?[0-9]+(\\.[0-9]+)?$';
|
|
8403
|
+
v_empty := v_at is null or v_at = 'null'::jsonb or v_text = '' or v_at = '[]'::jsonb;
|
|
8404
|
+
v_result := case
|
|
8405
|
+
when v_op = '' then true
|
|
8406
|
+
when v_op = 'empty' then v_empty
|
|
8407
|
+
when v_op = 'not_empty' then not v_empty
|
|
8408
|
+
when v_op in ('is', 'eq') then case when v_numeric then v_text::numeric = v_other::numeric else v_text = v_other end
|
|
8409
|
+
when v_op in ('is_not', 'neq') then not coalesce(case when v_numeric then v_text::numeric = v_other::numeric else v_text = v_other end, false)
|
|
8410
|
+
when v_op in ('gt', 'is_after') then case when v_numeric then v_text::numeric > v_other::numeric else v_text > v_other end
|
|
8411
|
+
when v_op in ('gte', 'is_on_or_after') then case when v_numeric then v_text::numeric >= v_other::numeric else v_text >= v_other end
|
|
8412
|
+
when v_op in ('lt', 'is_before') then case when v_numeric then v_text::numeric < v_other::numeric else v_text < v_other end
|
|
8413
|
+
when v_op in ('lte', 'is_on_or_before') then case when v_numeric then v_text::numeric <= v_other::numeric else v_text <= v_other end
|
|
8414
|
+
when v_op in ('between', 'not_between') then
|
|
8415
|
+
jsonb_typeof(v_value) = 'array' and (
|
|
8416
|
+
case when jsonb_typeof(v_value -> 0) = 'number' and v_text ~ '^-?[0-9]+(\\.[0-9]+)?$'
|
|
8417
|
+
then v_text::numeric between (v_value ->> 0)::numeric and (v_value ->> 1)::numeric
|
|
8418
|
+
else v_text between v_value ->> 0 and v_value ->> 1 end
|
|
8419
|
+
) = (v_op = 'between')
|
|
8420
|
+
when v_op in ('is_any_of', 'is_none_of') then
|
|
8421
|
+
jsonb_typeof(v_value) = 'array'
|
|
8422
|
+
and exists (select 1 from jsonb_array_elements_text(v_value) e where e = v_text) = (v_op = 'is_any_of')
|
|
8423
|
+
when v_op in ('contains', 'not_contains') then
|
|
8424
|
+
(case when jsonb_typeof(v_at) = 'array' then v_at @> jsonb_build_array(v_value)
|
|
8425
|
+
else strpos(lower(v_text), lower(v_other)) > 0 end) = (v_op = 'contains')
|
|
8426
|
+
when v_op = 'starts_with' then left(lower(v_text), length(v_other)) = lower(v_other)
|
|
8427
|
+
when v_op = 'ends_with' then right(lower(v_text), length(v_other)) = lower(v_other)
|
|
8428
|
+
when v_op in ('has_any_of', 'has_none_of') then
|
|
8429
|
+
jsonb_typeof(v_at) = 'array' and jsonb_typeof(v_value) = 'array'
|
|
8430
|
+
and exists (select 1 from jsonb_array_elements(v_value) e where v_at @> jsonb_build_array(e.value)) = (v_op = 'has_any_of')
|
|
8431
|
+
when v_op = 'has_all_of' then
|
|
8432
|
+
jsonb_typeof(v_at) = 'array' and jsonb_typeof(v_value) = 'array' and v_at @> v_value
|
|
8433
|
+
end;
|
|
8434
|
+
if v_op not in ('', 'empty', 'not_empty', 'is', 'eq', 'is_not', 'neq', 'gt', 'is_after', 'gte', 'is_on_or_after', 'lt', 'is_before',
|
|
8435
|
+
'lte', 'is_on_or_before', 'between', 'not_between', 'is_any_of', 'is_none_of', 'contains', 'not_contains', 'starts_with',
|
|
8436
|
+
'ends_with', 'has_any_of', 'has_none_of', 'has_all_of') then
|
|
8437
|
+
${invalid}
|
|
8438
|
+
end if;
|
|
8439
|
+
v_result := coalesce(v_result, false);
|
|
8440
|
+
return case when coalesce((node ->> 'negated')::boolean, false) then not v_result else v_result end;
|
|
8441
|
+
end;
|
|
8442
|
+
$$;
|
|
8443
|
+
revoke execute on function ${fn}(jsonb, jsonb) from public, anon, authenticated;`;
|
|
8444
|
+
}
|
|
8280
8445
|
// src/sql/modules/over-app.ts
|
|
8281
8446
|
/** Postgres truncates longer identifiers, so two long index names could meet. */
|
|
8282
8447
|
const MAX_IDENTIFIER = 63;
|
|
@@ -8326,7 +8491,8 @@ const TENANT_POLICY_TABLES = { policies: {
|
|
|
8326
8491
|
"conditions",
|
|
8327
8492
|
"expiresIn",
|
|
8328
8493
|
"createdBy",
|
|
8329
|
-
"updatedAt"
|
|
8494
|
+
"updatedAt",
|
|
8495
|
+
"effect"
|
|
8330
8496
|
],
|
|
8331
8497
|
typed: ["mode"],
|
|
8332
8498
|
columns: {
|
|
@@ -8343,32 +8509,60 @@ const TENANT_POLICY_TABLES = { policies: {
|
|
|
8343
8509
|
enabled: "enabled",
|
|
8344
8510
|
createdBy: "created_by",
|
|
8345
8511
|
createdAt: "created_at",
|
|
8346
|
-
updatedAt: "updated_at"
|
|
8512
|
+
updatedAt: "updated_at",
|
|
8513
|
+
effect: "effect"
|
|
8347
8514
|
}
|
|
8348
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") : [];
|
|
8349
8520
|
/** Whether `blocks.approvals.options.tenantPolicies` is on. */
|
|
8350
8521
|
const tenantPoliciesOn = (ctx) => ctx.flag("tenantPolicies", false);
|
|
8522
|
+
/**
|
|
8523
|
+
* Whether `blocks.approvals.options.platformPolicies` is on: rows of the tenant
|
|
8524
|
+
* policies table without a tenant are platform policies, edited at runtime by
|
|
8525
|
+
* platform staff, that apply to every organization and can stand in for a
|
|
8526
|
+
* config floor.
|
|
8527
|
+
*/
|
|
8528
|
+
function platformPoliciesOn(ctx) {
|
|
8529
|
+
const on = ctx.flag("platformPolicies", false);
|
|
8530
|
+
if (on && !tenantPoliciesOn(ctx)) throw new TypeError("blocks.approvals.options.platformPolicies needs blocks.approvals.options.tenantPolicies");
|
|
8531
|
+
return on;
|
|
8532
|
+
}
|
|
8533
|
+
/**
|
|
8534
|
+
* `blocks.approvals.options.tenantless`: the subject types whose requests may
|
|
8535
|
+
* have no organization, for personal or platform actions.
|
|
8536
|
+
*/
|
|
8537
|
+
const tenantlessTypes = (ctx) => ctx.list("tenantless", []);
|
|
8538
|
+
/** SQL that is true when `type` may be filed without an organization. */
|
|
8539
|
+
function tenantlessType(ctx, type) {
|
|
8540
|
+
const types = tenantlessTypes(ctx);
|
|
8541
|
+
return types.length === 0 ? "false" : `${type} in (${types.map(sqlString).join(", ")})`;
|
|
8542
|
+
}
|
|
8351
8543
|
/** The employees module when it renders tables the approvals SQL can read. */
|
|
8352
8544
|
const employeesOf = (ctx) => ctx.installed("employees") && ctx.of("employees").mode !== "custom" ? ctx.of("employees") : void 0;
|
|
8353
8545
|
/**
|
|
8354
8546
|
* The user id of the requester's manager in the request's tenant, as a SQL
|
|
8355
|
-
* expression, or `undefined` without the employees module.
|
|
8356
|
-
* manager
|
|
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.
|
|
8357
8550
|
*/
|
|
8358
|
-
function managerOf(ctx, requester, tenant) {
|
|
8551
|
+
function managerOf(ctx, requester, tenant, employee) {
|
|
8359
8552
|
const employees = employeesOf(ctx);
|
|
8360
8553
|
if (employees === void 0) return;
|
|
8361
8554
|
const e = (column) => employees.col("employees", column);
|
|
8362
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)`;
|
|
8363
8557
|
return `(select mgr.${e("user")} from ${table} me
|
|
8364
8558
|
join ${table} mgr on mgr.${e("id")} = me.${e("manager")}
|
|
8365
|
-
where me.${e("tenant")} = ${tenant} and
|
|
8559
|
+
where me.${e("tenant")} = ${tenant} and ${who}
|
|
8366
8560
|
and mgr.${e("user")} is not null and mgr.${e("status")}::text <> 'offboarded'
|
|
8367
8561
|
limit 1)`;
|
|
8368
8562
|
}
|
|
8369
8563
|
/** Whether `user` is the requester's manager and still a member. */
|
|
8370
8564
|
function managerMatch(ctx, args) {
|
|
8371
|
-
const manager = managerOf(ctx, args.requester, args.tenant);
|
|
8565
|
+
const manager = managerOf(ctx, args.requester, args.tenant, args.employee);
|
|
8372
8566
|
if (manager === void 0) return "false";
|
|
8373
8567
|
const members = ctx.of("memberships");
|
|
8374
8568
|
const m = (column) => members.col("memberships", column);
|
|
@@ -8402,8 +8596,14 @@ $$;
|
|
|
8402
8596
|
revoke execute on function ${signature} from public, anon, authenticated;`;
|
|
8403
8597
|
const p = (column) => ctx.col("policies", column);
|
|
8404
8598
|
const has = (column) => ctx.has("policies", column);
|
|
8405
|
-
const
|
|
8406
|
-
const
|
|
8599
|
+
const platform = platformPoliciesOn(ctx);
|
|
8600
|
+
const payload = approvalConditions(ctx) === "payload";
|
|
8601
|
+
const rules = !payload && ctx.installed("automations") ? ctx.of("automations") : void 0;
|
|
8602
|
+
const conditions = has("conditions") ? payload ? `
|
|
8603
|
+
if v_row.${p("conditions")} is not null
|
|
8604
|
+
and not ${fn("approval_condition")}(v_row.${p("conditions")}, coalesce(approval_effective_policy.subject, '{}'::jsonb)) then
|
|
8605
|
+
continue;
|
|
8606
|
+
end if;` : rules === void 0 ? `
|
|
8407
8607
|
if v_row.${p("conditions")} is not null then
|
|
8408
8608
|
continue;
|
|
8409
8609
|
end if;` : `
|
|
@@ -8415,11 +8615,17 @@ revoke execute on function ${signature} from public, anon, authenticated;`;
|
|
|
8415
8615
|
continue;
|
|
8416
8616
|
end if;
|
|
8417
8617
|
end if;` : "";
|
|
8618
|
+
const missingFloor = platform ? `
|
|
8619
|
+
v_floor := '{"steps": [], "selfApproval": true, "expiresIn": null, "run": null}'::jsonb;
|
|
8620
|
+
v_matched := false;` : `
|
|
8621
|
+
return null;`;
|
|
8418
8622
|
return `
|
|
8419
8623
|
-- The policy a request snapshots: the options.policies floor, tightened by
|
|
8420
8624
|
-- every enabled tenant policy whose conditions match the request payload.
|
|
8421
|
-
--
|
|
8422
|
-
--
|
|
8625
|
+
-- A policy matches its subject type and action, \`*\` for any, and the
|
|
8626
|
+
-- floor's effects when it names one. Steps add up, the stricter mode wins,
|
|
8627
|
+
-- self-approval needs every policy to allow it and the shortest expiry
|
|
8628
|
+
-- applies.${platform ? "\n-- Platform policies (no tenant) come first and stand in for a missing floor." : ""}
|
|
8423
8629
|
create or replace function ${fn("approval_effective_policy")}(tenant ${ctx.idType}, subject_type text, action text, subject jsonb default '{}'::jsonb)
|
|
8424
8630
|
returns jsonb
|
|
8425
8631
|
language plpgsql
|
|
@@ -8437,34 +8643,73 @@ declare
|
|
|
8437
8643
|
v_expires interval;
|
|
8438
8644
|
v_ids jsonb := '[]'::jsonb;
|
|
8439
8645
|
v_fields jsonb;
|
|
8646
|
+
v_effects jsonb;
|
|
8647
|
+
v_matched boolean := true;
|
|
8440
8648
|
begin
|
|
8441
|
-
if v_floor is null then
|
|
8442
|
-
return null;
|
|
8649
|
+
if v_floor is null then${missingFloor}
|
|
8443
8650
|
end if;
|
|
8651
|
+
v_effects := coalesce(v_floor -> 'effects', '[]'::jsonb);
|
|
8444
8652
|
v_steps := coalesce(v_floor -> 'steps', '[]'::jsonb);
|
|
8445
8653
|
v_level := ${level("coalesce(v_floor ->> 'mode', 'authorize')", "v_steps")};
|
|
8446
8654
|
v_self := coalesce((v_floor ->> 'selfApproval')::boolean, false);
|
|
8447
8655
|
v_expires := (v_floor ->> 'expiresIn')::interval;
|
|
8448
8656
|
for v_row in
|
|
8449
8657
|
select * from ${ctx.table("policies")} x
|
|
8450
|
-
where x.${p("tenant")} = approval_effective_policy.tenant
|
|
8451
|
-
and x.${p("
|
|
8452
|
-
|
|
8453
|
-
|
|
8658
|
+
where (x.${p("tenant")} = approval_effective_policy.tenant${platform ? ` or x.${p("tenant")} is null` : ""})
|
|
8659
|
+
and (x.${p("subjectType")} = approval_effective_policy.subject_type or x.${p("subjectType")} = '*')
|
|
8660
|
+
and (x.${p("action")} = approval_effective_policy.action or x.${p("action")} = '*')${has("effect") ? `
|
|
8661
|
+
and (x.${p("effect")} is null or v_effects ? x.${p("effect")})` : ""}
|
|
8662
|
+
and x.${p("enabled")}
|
|
8663
|
+
order by ${platform ? `x.${p("tenant")} is null desc, ` : ""}x.${p("createdAt")}, x.${p("id")}
|
|
8664
|
+
loop${platform ? `
|
|
8665
|
+
if not v_matched and v_row.${p("tenant")} is not null then
|
|
8666
|
+
continue;
|
|
8667
|
+
end if;` : ""}${conditions}
|
|
8668
|
+
v_matched := true;
|
|
8454
8669
|
v_steps := v_steps || v_row.${p("steps")};
|
|
8455
8670
|
v_level := greatest(v_level, ${level(`v_row.${p("mode")}::text`, `v_row.${p("steps")}`)});
|
|
8456
8671
|
v_self := v_self and v_row.${p("selfApproval")};${has("expiresIn") ? `
|
|
8457
8672
|
v_expires := least(v_expires, v_row.${p("expiresIn")});` : ""}
|
|
8458
8673
|
v_ids := v_ids || to_jsonb(v_row.${p("id")});
|
|
8459
8674
|
end loop;
|
|
8675
|
+
if not v_matched then
|
|
8676
|
+
return null;
|
|
8677
|
+
end if;
|
|
8460
8678
|
return jsonb_build_object(
|
|
8461
8679
|
'steps', v_steps, 'selfApproval', v_self, 'expiresIn', v_expires::text, 'run', v_floor -> 'run',
|
|
8462
8680
|
'mode', case when v_level = 1 then 'confirm' else 'authorize' end, 'policies', v_ids
|
|
8463
|
-
);
|
|
8681
|
+
) || case when jsonb_array_length(v_effects) > 0 then jsonb_build_object('effects', v_effects) else '{}'::jsonb end;
|
|
8464
8682
|
end;
|
|
8465
8683
|
$$;
|
|
8466
|
-
revoke execute on function ${signature} from public, anon, authenticated
|
|
8684
|
+
revoke execute on function ${signature} from public, anon, authenticated;${payload ? approvalConditionSql(ctx) : ""}`;
|
|
8467
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;`;
|
|
8468
8713
|
function tenantPoliciesSql(ctx, helpers) {
|
|
8469
8714
|
const fn = (name) => ctx.fn(name);
|
|
8470
8715
|
const t = ctx.table("policies");
|
|
@@ -8472,24 +8717,29 @@ function tenantPoliciesSql(ctx, helpers) {
|
|
|
8472
8717
|
const has = (column) => ctx.has("policies", column);
|
|
8473
8718
|
const or = (row, column) => has(column) ? `${row}.${p(column)}` : "null";
|
|
8474
8719
|
const { manage, read } = helpers.permissions;
|
|
8475
|
-
const
|
|
8720
|
+
const platform = platformPoliciesOn(ctx);
|
|
8721
|
+
const payload = approvalConditions(ctx) === "payload";
|
|
8722
|
+
const rules = !payload && ctx.installed("automations") ? ctx.of("automations") : void 0;
|
|
8476
8723
|
const manager = employeesOf(ctx) !== void 0;
|
|
8477
|
-
const
|
|
8724
|
+
const extras = policyExtras(ctx);
|
|
8725
|
+
const inserted = insertExtraColumns(t, extras, "coalesce(save_approval_policy.policy -> 'fields', '{}'::jsonb)");
|
|
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)})`;
|
|
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)})`;
|
|
8478
8728
|
const column = (logical, definition) => has(logical) ? `\n ${definition(p(logical))},` : "";
|
|
8479
8729
|
const table = ctx.manages ? `
|
|
8480
8730
|
create table if not exists ${t} (
|
|
8481
8731
|
${p("id")} uuid primary key default gen_random_uuid(),
|
|
8482
|
-
${p("tenant")} ${ctx.idType} not null,
|
|
8732
|
+
${p("tenant")} ${ctx.idType}${platform ? "" : " not null"},
|
|
8483
8733
|
${p("subjectType")} text not null,
|
|
8484
8734
|
${p("action")} text not null,
|
|
8485
|
-
${p("name")} text not null check (length(${p("name")}) between 1 and 200),${column("conditions", (name) => `${name} jsonb`)}
|
|
8735
|
+
${p("name")} text not null check (length(${p("name")}) between 1 and 200),${column("conditions", (name) => `${name} jsonb`)}${column("effect", (name) => `${name} text`)}
|
|
8486
8736
|
${p("mode")} text not null default 'authorize' check (${p("mode")} in ('confirm', 'authorize')),
|
|
8487
8737
|
${p("steps")} jsonb not null default '[]'::jsonb check (jsonb_typeof(${p("steps")}) = 'array'),
|
|
8488
8738
|
${p("selfApproval")} boolean not null default false,${column("expiresIn", (name) => `${name} interval check (${name} is null or ${name} > interval '0')`)}
|
|
8489
8739
|
${p("enabled")} boolean not null default true,${column("createdBy", (name) => `${name} uuid`)}
|
|
8490
8740
|
${p("createdAt")} timestamptz not null default now()${has("updatedAt") ? `,\n ${p("updatedAt")} timestamptz not null default now()` : ""}
|
|
8491
8741
|
);
|
|
8492
|
-
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)}
|
|
8493
8743
|
${lockModuleTable(ctx, "policies", { read: true })}
|
|
8494
8744
|
${renderPolicy(policy$1({
|
|
8495
8745
|
table: t,
|
|
@@ -8501,7 +8751,10 @@ ${renderPolicy(policy$1({
|
|
|
8501
8751
|
drop: true,
|
|
8502
8752
|
target: t
|
|
8503
8753
|
})}` : "";
|
|
8504
|
-
const conditionCheck = has("conditions") ?
|
|
8754
|
+
const conditionCheck = has("conditions") ? payload ? `
|
|
8755
|
+
if v_conditions is not null then
|
|
8756
|
+
perform ${fn("approval_condition")}(v_conditions, '{}'::jsonb);
|
|
8757
|
+
end if;` : rules ? `
|
|
8505
8758
|
if v_conditions is not null then
|
|
8506
8759
|
v_fields := ${rules.fn("rule_field_map")}(v_type);
|
|
8507
8760
|
if v_fields = '{}'::jsonb then
|
|
@@ -8510,12 +8763,24 @@ ${renderPolicy(policy$1({
|
|
|
8510
8763
|
perform ${rules.fn("rule_check")}(v_conditions, v_fields, 1);
|
|
8511
8764
|
end if;` : `
|
|
8512
8765
|
if v_conditions is not null then
|
|
8513
|
-
${fail$1("APPROVAL_CONDITIONS_UNSUPPORTED", "approval policy conditions need the automations module", "22023")}
|
|
8766
|
+
${fail$1("APPROVAL_CONDITIONS_UNSUPPORTED", "approval policy conditions need the automations module, or options.conditions: \"payload\"", "22023")}
|
|
8514
8767
|
end if;` : `
|
|
8515
8768
|
if v_conditions is not null then
|
|
8516
8769
|
${fail$1("APPROVAL_CONDITIONS_UNSUPPORTED", "this approval policies table has no conditions column", "22023")}
|
|
8517
8770
|
end if;`;
|
|
8518
|
-
const
|
|
8771
|
+
const floorPolicies = approvalPolicies(ctx);
|
|
8772
|
+
const floorExists = `(exists (
|
|
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"})
|
|
8775
|
+
and (v_action = '*' or f.value ->> 'action' in (v_action, '*'))
|
|
8776
|
+
and (v_effect is null or f.value -> 'effects' ? v_effect)
|
|
8777
|
+
)${platform ? ` or (save_approval_policy.tenant is null) or exists (
|
|
8778
|
+
select 1 from ${t} f
|
|
8779
|
+
where f.${p("tenant")} is null and f.${p("enabled")}
|
|
8780
|
+
and (f.${p("subjectType")} in (v_type, '*'))
|
|
8781
|
+
and (f.${p("action")} in (v_action, '*'))${has("effect") ? `\n and (f.${p("effect")} is null or f.${p("effect")} = v_effect)` : ""}
|
|
8782
|
+
)` : ""})`;
|
|
8783
|
+
const stepsInvalid = fail$1("APPROVAL_POLICY_INVALID", `steps must be a list of { approvers: { permission, role, team, users${manager ? ", manager" : ""} }, required, escalateAfter, escalateTo } objects`, "22023");
|
|
8519
8784
|
return `${table}
|
|
8520
8785
|
|
|
8521
8786
|
-- Creates or changes a tenant policy. policy is { id?, subjectType, action,
|
|
@@ -8538,8 +8803,10 @@ declare
|
|
|
8538
8803
|
v_steps jsonb;
|
|
8539
8804
|
v_step jsonb;
|
|
8540
8805
|
v_fields jsonb;
|
|
8806
|
+
v_effect text;
|
|
8807
|
+
v_who jsonb;
|
|
8541
8808
|
begin
|
|
8542
|
-
if not
|
|
8809
|
+
if not ${manages("save_approval_policy.tenant")} then
|
|
8543
8810
|
${fail$1("APPROVAL_FORBIDDEN", "managing approval policies needs approvals.manage")}
|
|
8544
8811
|
end if;
|
|
8545
8812
|
if jsonb_typeof(save_approval_policy.policy) is distinct from 'object' then
|
|
@@ -8547,7 +8814,7 @@ begin
|
|
|
8547
8814
|
end if;
|
|
8548
8815
|
if save_approval_policy.policy ? 'id' then
|
|
8549
8816
|
select * into v_old from ${t} x
|
|
8550
|
-
where x.${p("id")} = (save_approval_policy.policy ->> 'id')::uuid and x.${p("tenant")}
|
|
8817
|
+
where x.${p("id")} = (save_approval_policy.policy ->> 'id')::uuid and x.${p("tenant")} is not distinct from save_approval_policy.tenant
|
|
8551
8818
|
for update;
|
|
8552
8819
|
if not found then
|
|
8553
8820
|
${fail$1("APPROVAL_POLICY_NOT_FOUND", "approval policy not found", "P0002")}
|
|
@@ -8555,45 +8822,38 @@ begin
|
|
|
8555
8822
|
end if;
|
|
8556
8823
|
v_type := coalesce(save_approval_policy.policy ->> 'subjectType', v_old.${p("subjectType")});
|
|
8557
8824
|
v_action := coalesce(save_approval_policy.policy ->> 'action', v_old.${p("action")});
|
|
8558
|
-
|
|
8559
|
-
|
|
8825
|
+
v_effect := ${has("effect") ? `case when save_approval_policy.policy ? 'effect' then nullif(save_approval_policy.policy ->> 'effect', '') else v_old.${p("effect")} end` : "null"};${has("effect") ? "" : `
|
|
8826
|
+
if nullif(save_approval_policy.policy ->> 'effect', '') is not null then
|
|
8827
|
+
${fail$1("APPROVAL_EFFECT_UNSUPPORTED", "this approval policies table has no effect column", "22023")}
|
|
8828
|
+
end if;`}
|
|
8829
|
+
if v_type is null or v_action is null or not ${floorExists} then
|
|
8830
|
+
${fail$1("APPROVAL_POLICY_UNKNOWN", "a tenant policy tightens an options.policies entry, and there is none for this subject type, action and effect", "22023")}
|
|
8560
8831
|
end if;
|
|
8561
8832
|
v_conditions := case when save_approval_policy.policy ? 'conditions' then nullif(save_approval_policy.policy -> 'conditions', 'null'::jsonb) else ${or("v_old", "conditions")} end;${conditionCheck}
|
|
8562
8833
|
v_steps := coalesce(save_approval_policy.policy -> 'steps', v_old.${p("steps")}, '[]'::jsonb);
|
|
8563
8834
|
if jsonb_typeof(v_steps) <> 'array' or jsonb_array_length(v_steps) > 20 then
|
|
8564
8835
|
${stepsInvalid}
|
|
8565
8836
|
end if;
|
|
8566
|
-
|
|
8567
|
-
if jsonb_typeof(v_step) <> 'object' or jsonb_typeof(v_step -> 'approvers') is distinct from 'object'
|
|
8568
|
-
or not (v_step -> 'approvers' ?| array['permission', 'role', 'team', 'users', 'manager'])
|
|
8569
|
-
or (v_step -> 'approvers' ? 'manager' and ${manager ? "v_step -> 'approvers' -> 'manager' <> 'true'::jsonb" : "true"})
|
|
8570
|
-
or (v_step -> 'approvers' ? 'users' and (jsonb_typeof(v_step -> 'approvers' -> 'users') <> 'array'
|
|
8571
|
-
or exists (select 1 from jsonb_array_elements(v_step -> 'approvers' -> 'users') u
|
|
8572
|
-
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}$')))
|
|
8573
|
-
or (v_step ? 'required' and (jsonb_typeof(v_step -> 'required') <> 'number' or (v_step ->> 'required')::numeric < 1
|
|
8574
|
-
or (v_step ->> 'required')::numeric <> trunc((v_step ->> 'required')::numeric))) then
|
|
8575
|
-
${stepsInvalid}
|
|
8576
|
-
end if;
|
|
8577
|
-
end loop;
|
|
8837
|
+
${stepsCheck$1("v_steps", stepsInvalid, manager)}
|
|
8578
8838
|
if coalesce(save_approval_policy.policy ->> 'mode', v_old.${p("mode")}::text, 'authorize') not in ('confirm', 'authorize') then
|
|
8579
8839
|
${fail$1("APPROVAL_POLICY_INVALID", "mode must be confirm or authorize", "22023")}
|
|
8580
8840
|
end if;
|
|
8581
8841
|
if v_old.${p("id")} is null then
|
|
8582
|
-
insert into ${t} (${p("tenant")}, ${p("subjectType")}, ${p("action")}, ${p("name")}${has("conditions") ? `, ${p("conditions")}` : ""}, ${p("mode")}, ${p("steps")}, ${p("selfApproval")}${has("expiresIn") ? `, ${p("expiresIn")}` : ""}, ${p("enabled")}${has("createdBy") ? `, ${p("createdBy")}` : ""})
|
|
8583
|
-
values (save_approval_policy.tenant, v_type, v_action, btrim(save_approval_policy.policy ->> 'name')${has("conditions") ? ", v_conditions" : ""},
|
|
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})
|
|
8843
|
+
values (save_approval_policy.tenant, v_type, v_action, btrim(save_approval_policy.policy ->> 'name')${has("conditions") ? ", v_conditions" : ""}${has("effect") ? ", v_effect" : ""},
|
|
8584
8844
|
${ctx.cast("policies", "mode", "coalesce(save_approval_policy.policy ->> 'mode', 'authorize')")}, v_steps,
|
|
8585
8845
|
coalesce((save_approval_policy.policy ->> 'selfApproval')::boolean, false)${has("expiresIn") ? ", (save_approval_policy.policy ->> 'expiresIn')::interval" : ""},
|
|
8586
|
-
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})
|
|
8587
8847
|
returning * into v_row;
|
|
8588
8848
|
else
|
|
8589
8849
|
update ${t} x set
|
|
8590
8850
|
${p("subjectType")} = v_type,
|
|
8591
8851
|
${p("action")} = v_action,
|
|
8592
|
-
${p("name")} = coalesce(btrim(save_approval_policy.policy ->> 'name'), x.${p("name")}),${has("conditions") ? `\n ${p("conditions")} = v_conditions,` : ""}
|
|
8852
|
+
${p("name")} = coalesce(btrim(save_approval_policy.policy ->> 'name'), x.${p("name")}),${has("conditions") ? `\n ${p("conditions")} = v_conditions,` : ""}${has("effect") ? `\n ${p("effect")} = v_effect,` : ""}
|
|
8593
8853
|
${p("mode")} = coalesce(${ctx.cast("policies", "mode", "save_approval_policy.policy ->> 'mode'")}, x.${p("mode")}),
|
|
8594
8854
|
${p("steps")} = v_steps,
|
|
8595
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,` : ""}
|
|
8596
|
-
${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')")}
|
|
8597
8857
|
where x.${p("id")} = v_old.${p("id")}
|
|
8598
8858
|
returning * into v_row;
|
|
8599
8859
|
end if;
|
|
@@ -8630,7 +8890,7 @@ begin
|
|
|
8630
8890
|
if not found then
|
|
8631
8891
|
return false;
|
|
8632
8892
|
end if;
|
|
8633
|
-
if not
|
|
8893
|
+
if not ${manages(`v_row.${p("tenant")}`)} then
|
|
8634
8894
|
${fail$1("APPROVAL_FORBIDDEN", "managing approval policies needs approvals.manage")}
|
|
8635
8895
|
end if;
|
|
8636
8896
|
delete from ${t} x where x.${p("id")} = v_row.${p("id")};
|
|
@@ -8659,14 +8919,14 @@ security definer
|
|
|
8659
8919
|
set search_path = ''
|
|
8660
8920
|
as $$
|
|
8661
8921
|
begin
|
|
8662
|
-
if not (${SERVICE_CALLER$1} or ${ctx.can("tenant", "list_approval_policies.tenant", read)}) then
|
|
8922
|
+
if not ${platform ? `(case when list_approval_policies.tenant is null then ${ctx.staff(read)} else (${SERVICE_CALLER$1} or ${ctx.can("tenant", "list_approval_policies.tenant", read)}) end)` : `(${SERVICE_CALLER$1} or ${ctx.can("tenant", "list_approval_policies.tenant", read)})`} then
|
|
8663
8923
|
${fail$1("APPROVAL_FORBIDDEN", "reading approval policies needs approvals.read")}
|
|
8664
8924
|
end if;
|
|
8665
8925
|
return coalesce((
|
|
8666
8926
|
select jsonb_agg(${json("x")} order by x.${p("subjectType")}, x.${p("action")}, x.${p("createdAt")}, x.${p("id")})
|
|
8667
8927
|
from (
|
|
8668
8928
|
select * from ${t} y
|
|
8669
|
-
where y.${p("tenant")} = list_approval_policies.tenant
|
|
8929
|
+
where (y.${p("tenant")} = list_approval_policies.tenant or (list_approval_policies.tenant is null and y.${p("tenant")} is null))
|
|
8670
8930
|
and (list_approval_policies.subject_type is null or y.${p("subjectType")} = list_approval_policies.subject_type)
|
|
8671
8931
|
order by y.${p("subjectType")}, y.${p("action")}, y.${p("createdAt")}, y.${p("id")}
|
|
8672
8932
|
limit ${pageSize("list_approval_policies.page_size", 100, 500)}
|
|
@@ -8686,6 +8946,13 @@ function requestSql(ctx, helpers) {
|
|
|
8686
8946
|
const args = requestArgs(ctx);
|
|
8687
8947
|
const fields = extraFieldsArg(extras);
|
|
8688
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");
|
|
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)`;
|
|
8952
|
+
const tenantRequired = (name) => tenantlessTypes(ctx).length === 0 ? "" : `
|
|
8953
|
+
if ${name}.tenant is null and not ${tenantlessType(ctx, `${name}.subject_type`)} then
|
|
8954
|
+
${fail$1("APPROVAL_TENANT_REQUIRED", "a request for this subject type needs an organization", "22023")}
|
|
8955
|
+
end if;`;
|
|
8689
8956
|
return `
|
|
8690
8957
|
-- What a request for the subject type and action would need right now, with
|
|
8691
8958
|
-- subject as the request payload the tenant policies' conditions read; null
|
|
@@ -8700,7 +8967,7 @@ as $$
|
|
|
8700
8967
|
declare
|
|
8701
8968
|
v_policy jsonb;
|
|
8702
8969
|
begin
|
|
8703
|
-
if not (${SERVICE_CALLER$1} or ${ctx.can("tenant", "approval_requirement.tenant", request)}) then
|
|
8970
|
+
if not (${SERVICE_CALLER$1} or ${ctx.can("tenant", "approval_requirement.tenant", request)}${tenantless("approval_requirement")}) then
|
|
8704
8971
|
${fail$1("APPROVAL_FORBIDDEN", "checking an approval requirement needs approvals.request")}
|
|
8705
8972
|
end if;
|
|
8706
8973
|
v_policy := ${fn("approval_effective_policy")}(approval_requirement.tenant, approval_requirement.subject_type, approval_requirement.action, approval_requirement.subject);
|
|
@@ -8712,12 +8979,69 @@ end;
|
|
|
8712
8979
|
$$;
|
|
8713
8980
|
${userGrant(`${fn("approval_requirement")}(${ctx.idType}, text, text, jsonb)`)}
|
|
8714
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
|
+
|
|
8715
9035
|
drop function if exists ${fn("request_approval")}(${args});
|
|
8716
9036
|
drop function if exists ${fn("request_approval")}(${args}, jsonb);
|
|
8717
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);
|
|
8718
9040
|
-- fingerprint: the hex SHA-256 of the request's canonical form, which
|
|
8719
|
-
-- consume_approval checks before the approved action runs.
|
|
8720
|
-
|
|
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)
|
|
8721
9045
|
returns jsonb
|
|
8722
9046
|
language plpgsql
|
|
8723
9047
|
security definer
|
|
@@ -8725,13 +9049,23 @@ set search_path = ''
|
|
|
8725
9049
|
as $$
|
|
8726
9050
|
declare
|
|
8727
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};
|
|
8728
9053
|
v_result jsonb;
|
|
8729
9054
|
v_req ${requests}%rowtype;
|
|
8730
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;
|
|
8731
9065
|
if v_policy is null then
|
|
8732
9066
|
${fail$1("APPROVAL_POLICY_UNKNOWN", "no approval policy for this subject type and action", "22023")}
|
|
8733
|
-
end if
|
|
8734
|
-
if not (
|
|
9067
|
+
end if;${tenantRequired("request_approval")}
|
|
9068
|
+
if not (v_service or (${ctx.can("tenant", "request_approval.tenant", request)} and ${subjectWrite})${tenantless("request_approval")}) then
|
|
8735
9069
|
${fail$1("APPROVAL_FORBIDDEN", "not allowed to request approval for this record")}
|
|
8736
9070
|
end if;
|
|
8737
9071
|
if not ${required("v_policy")} then
|
|
@@ -8743,7 +9077,7 @@ begin
|
|
|
8743
9077
|
if request_approval.fingerprint is not null then
|
|
8744
9078
|
${fail$1("APPROVAL_FINGERPRINT_UNSUPPORTED", "this approval requests table has no fingerprint column", "22023")}
|
|
8745
9079
|
end if;`}
|
|
8746
|
-
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 ? `
|
|
8747
9081
|
if request_approval.fingerprint is not null then
|
|
8748
9082
|
update ${requests} x set ${c("fingerprint")} = request_approval.fingerprint
|
|
8749
9083
|
where x.${c("id")} = (v_result ->> 'id')::uuid and x.${c("status")} = 'pending';
|
|
@@ -8756,7 +9090,7 @@ ${writeExtraColumns(requests, extras, "request_approval.fields", `x.${c("id")} =
|
|
|
8756
9090
|
return v_result;
|
|
8757
9091
|
end;
|
|
8758
9092
|
$$;
|
|
8759
|
-
${userGrant(`${fn("request_approval")}(${args}${fields.type}, text)`)}`;
|
|
9093
|
+
${userGrant(`${fn("request_approval")}(${args}${fields.type}, text, jsonb, uuid)`)}`;
|
|
8760
9094
|
}
|
|
8761
9095
|
function consumeSql(ctx, helpers) {
|
|
8762
9096
|
const fn = (name) => ctx.fn(name);
|
|
@@ -8901,6 +9235,10 @@ const EVENTS$23 = {
|
|
|
8901
9235
|
subject: "approval-requests",
|
|
8902
9236
|
payload: PAYLOAD$4
|
|
8903
9237
|
},
|
|
9238
|
+
"approval.escalated": {
|
|
9239
|
+
subject: "approval-requests",
|
|
9240
|
+
payload: PAYLOAD$4
|
|
9241
|
+
},
|
|
8904
9242
|
"approval_policy.saved": {
|
|
8905
9243
|
subject: "approval-policies",
|
|
8906
9244
|
payload: POLICY_PAYLOAD
|
|
@@ -8934,12 +9272,18 @@ const APPROVALS_NAMES = {
|
|
|
8934
9272
|
"before_approval_request",
|
|
8935
9273
|
"after_approval_request",
|
|
8936
9274
|
"before_approval_decide",
|
|
8937
|
-
"after_approval_decide"
|
|
9275
|
+
"after_approval_decide",
|
|
9276
|
+
"approval_notification"
|
|
8938
9277
|
],
|
|
8939
9278
|
options: [
|
|
8940
9279
|
"policies",
|
|
8941
9280
|
"tenantPolicies",
|
|
8942
|
-
"
|
|
9281
|
+
"platformPolicies",
|
|
9282
|
+
"conditions",
|
|
9283
|
+
"tenantless",
|
|
9284
|
+
"extraColumns",
|
|
9285
|
+
"notifications",
|
|
9286
|
+
"policyExtraColumns"
|
|
8943
9287
|
],
|
|
8944
9288
|
tables: {
|
|
8945
9289
|
requests: {
|
|
@@ -9023,7 +9367,9 @@ function approvalsContract(extra) {
|
|
|
9023
9367
|
"text",
|
|
9024
9368
|
"jsonb",
|
|
9025
9369
|
...extra,
|
|
9026
|
-
"text"
|
|
9370
|
+
"text",
|
|
9371
|
+
"jsonb",
|
|
9372
|
+
"uuid"
|
|
9027
9373
|
],
|
|
9028
9374
|
returns: "jsonb"
|
|
9029
9375
|
},
|
|
@@ -9032,7 +9378,8 @@ function approvalsContract(extra) {
|
|
|
9032
9378
|
args: [
|
|
9033
9379
|
"uuid",
|
|
9034
9380
|
"text",
|
|
9035
|
-
"text"
|
|
9381
|
+
"text",
|
|
9382
|
+
"uuid"
|
|
9036
9383
|
],
|
|
9037
9384
|
returns: "jsonb"
|
|
9038
9385
|
},
|
|
@@ -9061,6 +9408,213 @@ function approvalsContract(extra) {
|
|
|
9061
9408
|
}
|
|
9062
9409
|
];
|
|
9063
9410
|
}
|
|
9411
|
+
// src/sql/modules/approvals-steps.ts
|
|
9412
|
+
function allHoldersSql(k, holders) {
|
|
9413
|
+
const { has } = k;
|
|
9414
|
+
return has("policy") ? `
|
|
9415
|
+
if exists (select 1 from jsonb_array_elements(coalesce(v_policy -> 'steps', '[]'::jsonb)) e where e.value -> 'required' = '"all"'::jsonb) then${holders === void 0 ? `
|
|
9416
|
+
${fail$1("APPROVAL_ALL_UNSUPPORTED", "required all needs an access model that lists permission holders", "22023")}` : `
|
|
9417
|
+
v_policy := jsonb_set(v_policy, '{steps}', (
|
|
9418
|
+
select jsonb_agg(case when e.value -> 'required' = '"all"'::jsonb
|
|
9419
|
+
then e.value || jsonb_build_object('approvers', jsonb_build_object('users', h.users), 'required', jsonb_array_length(h.users), 'permission', e.value -> 'approvers' ->> 'permission')
|
|
9420
|
+
else e.value end order by e.ordinality)
|
|
9421
|
+
from jsonb_array_elements(v_policy -> 'steps') with ordinality e
|
|
9422
|
+
left join lateral (
|
|
9423
|
+
select coalesce(jsonb_agg(distinct to_jsonb(u.id::text)), '[]'::jsonb) as users
|
|
9424
|
+
from (${holders}) as u(id)
|
|
9425
|
+
where u.id is not null and (u.id is distinct from v_requester or coalesce((v_policy ->> 'selfApproval')::boolean, false))
|
|
9426
|
+
) h on e.value -> 'required' = '"all"'::jsonb
|
|
9427
|
+
));
|
|
9428
|
+
if exists (select 1 from jsonb_array_elements(v_policy -> 'steps') e where e.value -> 'required' = '0'::jsonb) then
|
|
9429
|
+
${fail$1("APPROVAL_APPROVERS_EMPTY", "nobody holds the permission a step asks every holder of", "22023")}
|
|
9430
|
+
end if;`}
|
|
9431
|
+
end if;` : "";
|
|
9432
|
+
}
|
|
9433
|
+
/** Decide_approval, with the service role deciding for a named user. */
|
|
9434
|
+
function decideSql(ctx, k) {
|
|
9435
|
+
const { requests, decisions, c, d, has, fn, policyOf, stepOf, record, json, also, alsoValue, decided, notFound, stepsRefusal, linkedReject, commentRefusal } = k;
|
|
9436
|
+
return `-- Approves or rejects the current step. Enough approvals move the request
|
|
9437
|
+
-- to the next step, and the last step runs the policy's action. The service
|
|
9438
|
+
-- role decides for the user in decided_by, who is recorded as the approver;
|
|
9439
|
+
-- it skips the approver check, never the requester's.
|
|
9440
|
+
drop function if exists ${fn("decide_approval")}(uuid, text, text);
|
|
9441
|
+
create or replace function ${fn("decide_approval")}(request_id uuid, decision text, comment text default null, decided_by uuid default null)
|
|
9442
|
+
returns jsonb
|
|
9443
|
+
language plpgsql
|
|
9444
|
+
security definer
|
|
9445
|
+
set search_path = ''
|
|
9446
|
+
as $$
|
|
9447
|
+
#variable_conflict use_column
|
|
9448
|
+
declare
|
|
9449
|
+
v_req ${requests}%rowtype;
|
|
9450
|
+
v_count integer;
|
|
9451
|
+
v_service boolean := ${SERVICE_CALLER$1};
|
|
9452
|
+
v_actor uuid := coalesce(decide_approval.decided_by, auth.uid());
|
|
9453
|
+
begin
|
|
9454
|
+
if decide_approval.decision not in ('approved', 'rejected') then
|
|
9455
|
+
${fail$1("APPROVAL_DECISION_INVALID", "decision must be approved or rejected", "22023")}
|
|
9456
|
+
end if;${commentRefusal("decide_approval.comment")}
|
|
9457
|
+
if decide_approval.decided_by is not null and not v_service and decide_approval.decided_by is distinct from auth.uid() then
|
|
9458
|
+
${fail$1("APPROVAL_FORBIDDEN", "only the service role decides for another user")}
|
|
9459
|
+
end if;
|
|
9460
|
+
select * into v_req from ${requests} r where r.${c("id")} = decide_approval.request_id for update;
|
|
9461
|
+
if not found then
|
|
9462
|
+
${notFound}
|
|
9463
|
+
end if;
|
|
9464
|
+
if v_req.${c("status")} <> 'pending' then
|
|
9465
|
+
${fail$1("APPROVAL_CLOSED", "this request is no longer pending", "22023")}
|
|
9466
|
+
end if;${has("expiresAt") ? `
|
|
9467
|
+
if v_req.${c("expiresAt")} is not null and v_req.${c("expiresAt")} <= now() then
|
|
9468
|
+
${fail$1("APPROVAL_EXPIRED", "this request has expired", "22023")}
|
|
9469
|
+
end if;` : ""}
|
|
9470
|
+
if v_service then
|
|
9471
|
+
if v_actor is not null and v_actor = v_req.${c("requestedBy")} and coalesce(${policyOf("v_req")} ->> 'mode', 'authorize') <> 'confirm'
|
|
9472
|
+
and not coalesce((${policyOf("v_req")} ->> 'selfApproval')::boolean, false) then
|
|
9473
|
+
${fail$1("APPROVAL_FORBIDDEN", "the requester can't decide their own request")}
|
|
9474
|
+
end if;
|
|
9475
|
+
if v_actor is not null and exists (
|
|
9476
|
+
select 1 from ${decisions} x
|
|
9477
|
+
where x.${d("request")} = v_req.${c("id")} and x.${d("step")} = ${stepOf("v_req")} and x.${d("approver")} = v_actor
|
|
9478
|
+
) then
|
|
9479
|
+
${fail$1("APPROVAL_FORBIDDEN", "this user already decided this step")}
|
|
9480
|
+
end if;
|
|
9481
|
+
elsif not ${fn("approval_eligible")}(v_req.${c("id")}) then
|
|
9482
|
+
${fail$1("APPROVAL_FORBIDDEN", "not an approver for this step")}
|
|
9483
|
+
end if;
|
|
9484
|
+
${ctx.hook("before_approval_decide", [["uuid", `v_req.${c("id")}`], ["text", "decide_approval.decision"]])}
|
|
9485
|
+
insert into ${decisions} (${d("request")}, ${d("tenant")}, ${d("step")}, ${d("approver")}, ${d("decision")}${also("decisions", "comment")})
|
|
9486
|
+
values (v_req.${c("id")}, v_req.${c("tenant")}, ${stepOf("v_req")}, v_actor, ${ctx.cast("decisions", "decision", "decide_approval.decision")}${alsoValue("decisions", "comment", "decide_approval.comment")});
|
|
9487
|
+
if decide_approval.decision = 'rejected' then
|
|
9488
|
+
update ${requests} r set ${c("status")} = 'rejected'${decided}
|
|
9489
|
+
where r.${c("id")} = v_req.${c("id")} returning * into v_req;
|
|
9490
|
+
${record("approval.rejected", "v_req", true)}
|
|
9491
|
+
perform ${fn("approval_notify")}(v_req.${c("id")}, 'rejected');${linkedReject}
|
|
9492
|
+
else
|
|
9493
|
+
select count(*) into v_count from ${decisions} x
|
|
9494
|
+
where x.${d("request")} = v_req.${c("id")} and x.${d("step")} = ${stepOf("v_req")} and x.${d("decision")} = 'approved';
|
|
9495
|
+
if ${policyOf("v_req")} ->> 'mode' = 'confirm' and v_req.${c("requestedBy")} = v_actor then
|
|
9496
|
+
update ${requests} r set ${c("status")} = 'approved'${decided}
|
|
9497
|
+
where r.${c("id")} = v_req.${c("id")} returning * into v_req;
|
|
9498
|
+
perform ${fn("approval_finalize")}(v_req.${c("id")});
|
|
9499
|
+
elsif v_count >= coalesce((${policyOf("v_req")} -> 'steps' -> ${stepOf("v_req")} ->> 'required')::integer, 1) then
|
|
9500
|
+
if ${stepOf("v_req")} + 1 >= jsonb_array_length(${policyOf("v_req")} -> 'steps') then
|
|
9501
|
+
update ${requests} r set ${c("status")} = 'approved'${decided}
|
|
9502
|
+
where r.${c("id")} = v_req.${c("id")} returning * into v_req;
|
|
9503
|
+
perform ${fn("approval_finalize")}(v_req.${c("id")});
|
|
9504
|
+
else
|
|
9505
|
+
${has("step") ? `update ${requests} r set ${c("step")} = r.${c("step")} + 1${has("remindedAt") ? `, ${c("remindedAt")} = null` : ""}
|
|
9506
|
+
where r.${c("id")} = v_req.${c("id")} returning * into v_req;
|
|
9507
|
+
perform ${fn("approval_notify")}(v_req.${c("id")}, 'requested');` : stepsRefusal}
|
|
9508
|
+
end if;
|
|
9509
|
+
end if;
|
|
9510
|
+
end if;
|
|
9511
|
+
${ctx.hook("after_approval_decide", [["uuid", `v_req.${c("id")}`], ["text", `v_req.${c("status")}`]])}
|
|
9512
|
+
return ${json("v_req")};
|
|
9513
|
+
end;
|
|
9514
|
+
$$;
|
|
9515
|
+
${userGrant(`${fn("decide_approval")}(uuid, text, text, uuid)`)}`;
|
|
9516
|
+
}
|
|
9517
|
+
/** Escalate_approvals, which lets a waiting step's fallback approvers in. */
|
|
9518
|
+
function escalateSql(k) {
|
|
9519
|
+
const { requests, decisions, c, d, has, fn, stepOf, record } = k;
|
|
9520
|
+
return `-- Lets the fallback approvers (escalateTo) of a step decide it too once the
|
|
9521
|
+
-- step has waited its escalateAfter, and asks them. Run it from pg_cron like
|
|
9522
|
+
-- remind_approvals.
|
|
9523
|
+
create or replace function ${fn("escalate_approvals")}(max_requests integer default 200)
|
|
9524
|
+
returns integer
|
|
9525
|
+
language plpgsql
|
|
9526
|
+
security definer
|
|
9527
|
+
set search_path = ''
|
|
9528
|
+
as $$
|
|
9529
|
+
declare
|
|
9530
|
+
v_req ${requests}%rowtype;
|
|
9531
|
+
v_count integer := 0;
|
|
9532
|
+
begin${has("policy") ? `
|
|
9533
|
+
for v_req in
|
|
9534
|
+
select * from ${requests} r
|
|
9535
|
+
where r.${c("status")} = 'pending'${has("expiresAt") ? `\n and (r.${c("expiresAt")} is null or r.${c("expiresAt")} > now())` : ""}
|
|
9536
|
+
and r.${c("policy")} -> 'steps' -> ${stepOf("r")} ? 'escalateAfter'
|
|
9537
|
+
and not coalesce((r.${c("policy")} -> 'steps' -> ${stepOf("r")} ->> 'escalated')::boolean, false)
|
|
9538
|
+
and coalesce((
|
|
9539
|
+
select max(x.${d("createdAt")}) from ${decisions} x
|
|
9540
|
+
where x.${d("request")} = r.${c("id")} and x.${d("step")} = ${stepOf("r")} - 1
|
|
9541
|
+
), r.${c("createdAt")}) + (r.${c("policy")} -> 'steps' -> ${stepOf("r")} ->> 'escalateAfter')::interval <= now()
|
|
9542
|
+
order by r.${c("createdAt")}
|
|
9543
|
+
limit greatest(coalesce(escalate_approvals.max_requests, 200), 1)
|
|
9544
|
+
for update skip locked
|
|
9545
|
+
loop
|
|
9546
|
+
update ${requests} r set ${c("policy")} = jsonb_set(r.${c("policy")}, array['steps', (${stepOf("r")})::text, 'escalated'], 'true'::jsonb)
|
|
9547
|
+
where r.${c("id")} = v_req.${c("id")}
|
|
9548
|
+
returning * into v_req;
|
|
9549
|
+
${record("approval.escalated", "v_req", true)}
|
|
9550
|
+
perform ${fn("approval_notify")}(v_req.${c("id")}, 'escalated');
|
|
9551
|
+
v_count := v_count + 1;
|
|
9552
|
+
end loop;` : ""}
|
|
9553
|
+
return v_count;
|
|
9554
|
+
end;
|
|
9555
|
+
$$;
|
|
9556
|
+
${serviceGrant(`${fn("escalate_approvals")}(integer)`)}`;
|
|
9557
|
+
}
|
|
9558
|
+
/**
|
|
9559
|
+
* Throws when a step escalates or asks every holder without a policy column, or
|
|
9560
|
+
* asks every holder under an access model that can't list them.
|
|
9561
|
+
*/
|
|
9562
|
+
function validateSteps(policies, policyColumn, holders) {
|
|
9563
|
+
for (const policy of policies) {
|
|
9564
|
+
const where = `blocks.approvals.options.policies.${policy.subjectType}.${policy.action}`;
|
|
9565
|
+
if (policy.steps.some((step) => step.escalateAfter !== void 0) && !policyColumn) throw new TypeError(`${where}: escalateAfter needs a policy column on the approval requests table`);
|
|
9566
|
+
if (policy.steps.some((step) => step.required === "all")) {
|
|
9567
|
+
if (!policyColumn) throw new TypeError(`${where}: required "all" with a permission needs a policy column on the approval requests table`);
|
|
9568
|
+
if (!holders) throw new TypeError(`${where}: required "all" with a permission needs an access model that lists permission holders (holdersOf)`);
|
|
9569
|
+
}
|
|
9570
|
+
}
|
|
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
|
+
}
|
|
9064
9618
|
// src/sql/modules/approver.ts
|
|
9065
9619
|
/** The `{kind}` of an AI tool call that waits for approval. */
|
|
9066
9620
|
const AI_TOOL_APPROVAL = "ai-tool";
|
|
@@ -10498,6 +11052,123 @@ function driveKit(ctx, own) {
|
|
|
10498
11052
|
siblings
|
|
10499
11053
|
};
|
|
10500
11054
|
}
|
|
11055
|
+
// src/sql/modules/notifications-audience.ts
|
|
11056
|
+
/**
|
|
11057
|
+
* Users who hold `notification.permission` in the tenant, added before
|
|
11058
|
+
* `exclude`. A provider without `holdersOf` refuses the audience. The roles and
|
|
11059
|
+
* catalog models ask `can_user` of each member, and the catalog model also
|
|
11060
|
+
* includes a platform-role holder. Never every member.
|
|
11061
|
+
*/
|
|
11062
|
+
function permissionAudience(ctx, layout) {
|
|
11063
|
+
const named = "nullif(notification ->> 'permission', '')";
|
|
11064
|
+
const unavailable = `
|
|
11065
|
+
if ${named} is not null then
|
|
11066
|
+
${fail$1("NOTIFICATION_PERMISSION_AUDIENCE_UNAVAILABLE", "This project has no permission audience", "0A000")}
|
|
11067
|
+
end if;`;
|
|
11068
|
+
const needsTenant = `
|
|
11069
|
+
if ${named} is not null and v_tenant is null then
|
|
11070
|
+
${fail$1("NOTIFICATION_PERMISSION_NEEDS_TENANT", "A permission audience needs a tenant", "22023")}
|
|
11071
|
+
end if;`;
|
|
11072
|
+
const model = accessModel(ctx);
|
|
11073
|
+
if (model === "provider") return providerAudience(layout, needsTenant, unavailable, named);
|
|
11074
|
+
if (model === "custom") return customAudience(ctx, needsTenant, unavailable, named);
|
|
11075
|
+
if (!ctx.installed("memberships")) return unavailable;
|
|
11076
|
+
return membershipAudience(ctx, model, needsTenant, named);
|
|
11077
|
+
}
|
|
11078
|
+
function providerAudience(layout, needsTenant, unavailable, named) {
|
|
11079
|
+
const provider = layout.accessProvider;
|
|
11080
|
+
if (provider === void 0) return unavailable;
|
|
11081
|
+
const template = provider.functions.holdersOf;
|
|
11082
|
+
if (template === void 0) return unavailable;
|
|
11083
|
+
return audienceAppend(needsTenant, named, fillTemplate("authorization.functions.holdersOf", template, {
|
|
11084
|
+
permission: "(notification ->> 'permission')",
|
|
11085
|
+
tenant: "v_tenant",
|
|
11086
|
+
scope: provider.scope
|
|
11087
|
+
}));
|
|
11088
|
+
}
|
|
11089
|
+
function customAudience(ctx, needsTenant, unavailable, named) {
|
|
11090
|
+
const template = ctx.modules.permissions?.functions?.holdersOf;
|
|
11091
|
+
if (template === void 0) return unavailable;
|
|
11092
|
+
return audienceAppend(needsTenant, named, fillTemplate("blocks.permissions.functions.holdersOf", template, {
|
|
11093
|
+
permission: "(notification ->> 'permission')",
|
|
11094
|
+
tenant: "v_tenant"
|
|
11095
|
+
}));
|
|
11096
|
+
}
|
|
11097
|
+
function membershipAudience(ctx, model, needsTenant, named) {
|
|
11098
|
+
const members = ctx.of("memberships");
|
|
11099
|
+
const user = members.col("memberships", "user");
|
|
11100
|
+
const tenant = members.col("memberships", "tenant");
|
|
11101
|
+
let platform = "";
|
|
11102
|
+
if (model === "catalog" && ctx.installed("permissions") && ctx.of("permissions").hasTable("platformAssignments")) {
|
|
11103
|
+
const access = ctx.of("permissions");
|
|
11104
|
+
const holder = access.col("platformAssignments", "user");
|
|
11105
|
+
platform = `
|
|
11106
|
+
union
|
|
11107
|
+
select a.${holder}
|
|
11108
|
+
from ${access.table("platformAssignments")} a
|
|
11109
|
+
where coalesce(better_supabase.platform_can(a.${holder}, notification ->> 'permission'), false)`;
|
|
11110
|
+
}
|
|
11111
|
+
return `${needsTenant}
|
|
11112
|
+
if ${named} is not null then
|
|
11113
|
+
v_recipients := v_recipients || coalesce(array(
|
|
11114
|
+
select m.${user}
|
|
11115
|
+
from ${members.table("memberships")} m
|
|
11116
|
+
where m.${tenant} = v_tenant
|
|
11117
|
+
and ${ctx.scope.canUser(`m.${user}`, "v_tenant", "notification ->> 'permission'")}
|
|
11118
|
+
${platform}
|
|
11119
|
+
), '{}');
|
|
11120
|
+
end if;`;
|
|
11121
|
+
}
|
|
11122
|
+
function audienceAppend(needsTenant, named, call) {
|
|
11123
|
+
return `${needsTenant}
|
|
11124
|
+
if ${named} is not null then
|
|
11125
|
+
v_recipients := v_recipients || coalesce(array(select u from ${call} as t(u)), '{}');
|
|
11126
|
+
end if;`;
|
|
11127
|
+
}
|
|
11128
|
+
const NAME$8 = /^[a-z][a-z0-9_]*$/;
|
|
11129
|
+
/**
|
|
11130
|
+
* A channel nobody chose is on for `in_app` and off for the rest, unless
|
|
11131
|
+
* `channelDefaults` says otherwise.
|
|
11132
|
+
*/
|
|
11133
|
+
function channelDefaults(ctx, channel) {
|
|
11134
|
+
const value = ctx.option("channelDefaults") ?? {};
|
|
11135
|
+
if (!isRecord$1(value)) throw new TypeError("blocks.notifications.options.channelDefaults must map channel names to booleans");
|
|
11136
|
+
return `case ${channel} ${[...Object.entries(value).map(([channel, enabled]) => {
|
|
11137
|
+
if (!NAME$8.test(channel) || typeof enabled !== "boolean") throw new TypeError(`blocks.notifications.options.channelDefaults.${channel} must be a boolean`);
|
|
11138
|
+
return `when ${sqlString(channel)} then ${String(enabled)}`;
|
|
11139
|
+
}), "when 'in_app' then true"].join(" ")} else false end`;
|
|
11140
|
+
}
|
|
11141
|
+
/**
|
|
11142
|
+
* A query of the user ids that hold `permission` in `tenant` (SQL expressions),
|
|
11143
|
+
* from the provider's or the custom model's `holdersOf`, or the members the
|
|
11144
|
+
* roles and catalog models allow; `undefined` when the access model can't list
|
|
11145
|
+
* holders.
|
|
11146
|
+
*/
|
|
11147
|
+
function permissionHolders(ctx, layout, permission, tenant) {
|
|
11148
|
+
const model = accessModel(ctx);
|
|
11149
|
+
if (model === "provider") {
|
|
11150
|
+
const provider = layout.accessProvider;
|
|
11151
|
+
const template = provider?.functions.holdersOf;
|
|
11152
|
+
return provider === void 0 || template === void 0 ? void 0 : `select h.u from ${fillTemplate("authorization.functions.holdersOf", template, {
|
|
11153
|
+
permission,
|
|
11154
|
+
tenant,
|
|
11155
|
+
scope: provider.scope
|
|
11156
|
+
})} as h(u)`;
|
|
11157
|
+
}
|
|
11158
|
+
if (model === "custom") {
|
|
11159
|
+
const template = ctx.modules.permissions?.functions?.holdersOf;
|
|
11160
|
+
return template === void 0 ? void 0 : `select h.u from ${fillTemplate("blocks.permissions.functions.holdersOf", template, {
|
|
11161
|
+
permission,
|
|
11162
|
+
tenant
|
|
11163
|
+
})} as h(u)`;
|
|
11164
|
+
}
|
|
11165
|
+
if (!ctx.installed("memberships")) return;
|
|
11166
|
+
const members = ctx.of("memberships");
|
|
11167
|
+
const user = members.col("memberships", "user");
|
|
11168
|
+
return `select m.${user} from ${members.table("memberships")} m
|
|
11169
|
+
where m.${members.col("memberships", "tenant")} = ${tenant}
|
|
11170
|
+
and ${ctx.scope.canUser(`m.${user}`, tenant, permission)}`;
|
|
11171
|
+
}
|
|
10501
11172
|
// src/sql/modules/subjects.ts
|
|
10502
11173
|
const NAMES$111 = { tables: {} };
|
|
10503
11174
|
/**
|
|
@@ -11036,7 +11707,12 @@ function build$112(ctx, layout) {
|
|
|
11036
11707
|
const policies = approvalPolicies(ctx);
|
|
11037
11708
|
validateRuns(ctx, policies);
|
|
11038
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");
|
|
11039
11711
|
if (tenantPoliciesOn(ctx) && !has("policy")) throw new TypeError("blocks.approvals.options.tenantPolicies needs a policy column on the approval requests table");
|
|
11712
|
+
const tenantless = tenantlessTypes(ctx).length > 0;
|
|
11713
|
+
platformPoliciesOn(ctx);
|
|
11714
|
+
const holders = permissionHolders(ctx, layout, "(e.value -> 'approvers' ->> 'permission')", "open_approval.tenant");
|
|
11715
|
+
validateSteps(policies, has("policy"), holders !== void 0);
|
|
11040
11716
|
const provider = approverCheck(ctx, layout, {
|
|
11041
11717
|
kind: { sql: `v_req.${c("subjectType")} || '.' || v_req.${c("action")}` },
|
|
11042
11718
|
subject: `v_req.${c("subjectId")}::text`,
|
|
@@ -11096,10 +11772,24 @@ function build$112(ctx, layout) {
|
|
|
11096
11772
|
union
|
|
11097
11773
|
select tm.${teams.col("members", "user")} from ${teams.table("members")} tm
|
|
11098
11774
|
where tm.${teams.col("members", "team")}::text = v_approvers ->> 'team'`;
|
|
11099
|
-
const
|
|
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);
|
|
11100
11777
|
const managerMember = manager === void 0 ? "" : `
|
|
11101
11778
|
union
|
|
11102
11779
|
select ${manager} where coalesce((v_approvers ->> 'manager')::boolean, false)`;
|
|
11780
|
+
const approverMatch = `((coalesce(v_approvers -> 'users', '[]'::jsonb) ? v_me::text)
|
|
11781
|
+
or (v_approvers ->> 'permission' is not null and ${tenantless ? `case when v_req.${c("tenant")} is null then ${ctx.staff("v_approvers ->> 'permission'")} else ${ctx.can("tenant", `v_req.${c("tenant")}`, "v_approvers ->> 'permission'")} end` : ctx.can("tenant", `v_req.${c("tenant")}`, "v_approvers ->> 'permission'")})
|
|
11782
|
+
or (v_approvers ->> 'role' is not null and exists (
|
|
11783
|
+
select 1 from ${members.table("memberships")} m
|
|
11784
|
+
where m.${mt} = v_req.${c("tenant")} and m.${mu} = v_me and m.${mr} = ${approverRole}
|
|
11785
|
+
))
|
|
11786
|
+
or (v_approvers ->> 'team' is not null and ${teamMatch("v_me")})${manager === void 0 ? "" : `
|
|
11787
|
+
or (coalesce((v_approvers ->> 'manager')::boolean, false) and ${managerMatch(ctx, {
|
|
11788
|
+
requester: `v_req.${c("requestedBy")}`,
|
|
11789
|
+
tenant: `v_req.${c("tenant")}`,
|
|
11790
|
+
user: "v_me",
|
|
11791
|
+
...managerEmployee === void 0 ? {} : { employee: managerEmployee }
|
|
11792
|
+
})})`})`;
|
|
11103
11793
|
const notFound = fail$1("APPROVAL_NOT_FOUND", "approval request not found", "P0002");
|
|
11104
11794
|
const queues = [...new Set(policies.flatMap((policy) => policy.run?.kind === "queue" ? [policy.run.queue] : []))];
|
|
11105
11795
|
const queueRun = queues.length === 0 ? "" : `
|
|
@@ -11122,28 +11812,63 @@ ${indent}if v_req.${c("subjectType")} = ${sqlString(subject)} then
|
|
|
11122
11812
|
${indent} ${body}
|
|
11123
11813
|
${indent}end if;`;
|
|
11124
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)`;
|
|
11125
11816
|
const contributedRun = contributed.map((each) => when(each.subject, each.approve({
|
|
11126
11817
|
subjectId: subjectId(""),
|
|
11127
|
-
comment: lastComment
|
|
11818
|
+
comment: lastComment,
|
|
11819
|
+
approver: lastApprover
|
|
11128
11820
|
}), " ")).join("");
|
|
11129
|
-
const linkedReject =
|
|
11821
|
+
const linkedReject = contributed.flatMap((each) => each.reject === void 0 ? [] : [when(each.subject, each.reject({
|
|
11130
11822
|
subjectId: subjectId(""),
|
|
11131
|
-
comment: "decide_approval.comment"
|
|
11823
|
+
comment: "decide_approval.comment",
|
|
11824
|
+
approver: "v_actor"
|
|
11132
11825
|
}), " ")]).join("");
|
|
11133
11826
|
const linkedEligible = linked.flatMap((each) => each.approvable === void 0 ? [] : [when(each.subject, `return ${each.approvable({
|
|
11134
11827
|
subjectId: subjectId(""),
|
|
11135
|
-
comment: lastComment
|
|
11828
|
+
comment: lastComment,
|
|
11829
|
+
approver: "v_me"
|
|
11136
11830
|
})};`, " ")]).join("");
|
|
11137
|
-
const
|
|
11831
|
+
const kit = {
|
|
11832
|
+
requests,
|
|
11833
|
+
decisions,
|
|
11834
|
+
c,
|
|
11835
|
+
d,
|
|
11836
|
+
has,
|
|
11837
|
+
fn,
|
|
11838
|
+
policyOf,
|
|
11839
|
+
stepOf,
|
|
11840
|
+
record,
|
|
11841
|
+
json,
|
|
11842
|
+
also,
|
|
11843
|
+
alsoValue,
|
|
11844
|
+
decided,
|
|
11845
|
+
notFound,
|
|
11846
|
+
stepsRefusal,
|
|
11847
|
+
linkedReject,
|
|
11848
|
+
commentRefusal
|
|
11849
|
+
};
|
|
11850
|
+
const allHolders = allHoldersSql(kit, holders);
|
|
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) ? `
|
|
11138
11863
|
select * into v_req from ${requests} r where r.${c("id")} = approval_notify.request_id;
|
|
11139
|
-
if not found then
|
|
11864
|
+
if not found${tenantless ? ` or v_req.${c("tenant")} is null` : ""} then
|
|
11140
11865
|
return;
|
|
11141
11866
|
end if;
|
|
11142
11867
|
if approval_notify.kind in ('approved', 'rejected', 'expired') then
|
|
11143
11868
|
v_recipients := array[v_req.${c("requestedBy")}];
|
|
11144
11869
|
v_permission := null;
|
|
11145
11870
|
else
|
|
11146
|
-
v_approvers := ${policyOf("v_req")} -> 'steps' -> ${stepOf("v_req")} -> 'approvers';
|
|
11871
|
+
v_approvers := ${policyOf("v_req")} -> 'steps' -> ${stepOf("v_req")} -> case when approval_notify.kind = 'escalated' then 'escalateTo' else 'approvers' end;
|
|
11147
11872
|
v_permission := v_approvers ->> 'permission';
|
|
11148
11873
|
v_recipients := array(
|
|
11149
11874
|
select x::uuid from jsonb_array_elements_text(coalesce(v_approvers -> 'users', '[]'::jsonb)) x
|
|
@@ -11175,7 +11900,7 @@ ${indent}end if;`;
|
|
|
11175
11900
|
if cardinality(v_recipients) = 0 and v_permission is null then
|
|
11176
11901
|
return;
|
|
11177
11902
|
end if;
|
|
11178
|
-
|
|
11903
|
+
v_note := jsonb_build_object(
|
|
11179
11904
|
'type', 'approval.' || approval_notify.kind,
|
|
11180
11905
|
'tenant', v_req.${c("tenant")},
|
|
11181
11906
|
'actor', coalesce(auth.uid(), v_req.${c("requestedBy")}),
|
|
@@ -11188,12 +11913,13 @@ ${indent}end if;`;
|
|
|
11188
11913
|
'include_actor', approval_notify.kind in ('approved', 'rejected', 'expired'),
|
|
11189
11914
|
'key', 'approval.' || approval_notify.kind || ':' || v_req.${c("id")}::text || ':' || ${stepOf("v_req")}::text || ':' || extract(epoch from now())::bigint::text,
|
|
11190
11915
|
'data', jsonb_build_object('requestId', v_req.${c("id")}, 'action', v_req.${c("action")}, 'step', ${stepOf("v_req")})
|
|
11191
|
-
)
|
|
11916
|
+
);${enrich}
|
|
11917
|
+
${ctx.notify("v_note")}` : `
|
|
11192
11918
|
null;`;
|
|
11193
11919
|
const column = (table, logical, definition) => ctx.has(table, logical) ? `\n ${definition(ctx.col(table, logical))},` : "";
|
|
11194
11920
|
const tables = ctx.manages ? `create table if not exists ${requests} (
|
|
11195
11921
|
${c("id")} uuid primary key default gen_random_uuid(),
|
|
11196
|
-
${c("tenant")} ${ctx.idType} not null,
|
|
11922
|
+
${c("tenant")} ${ctx.idType}${tenantless ? "" : " not null"},
|
|
11197
11923
|
${c("subjectType")} text not null,
|
|
11198
11924
|
${c("subjectId")} text not null,
|
|
11199
11925
|
${c("action")} text not null,${column("requests", "policy", (name) => `${name} jsonb not null`)}${column("requests", "step", (name) => `${name} integer not null default 0 check (${name} >= 0)`)}
|
|
@@ -11201,7 +11927,7 @@ ${indent}end if;`;
|
|
|
11201
11927
|
${c("requestedBy")} uuid,${column("requests", "reason", (name) => `${name} text check (${name} is null or length(${name}) <= 2000)`)}${column("requests", "payload", (name) => `${name} jsonb not null default '{}'::jsonb`)}${column("requests", "expiresAt", (name) => `${name} timestamptz`)}${column("requests", "remindedAt", (name) => `${name} timestamptz`)}${column("requests", "decidedAt", (name) => `${name} timestamptz`)}${column("requests", "fingerprint", (name) => `${name} text check (${name} is null or ${name} ~ '^[0-9a-f]{64}$')`)}${column("requests", "consumedAt", (name) => `${name} timestamptz`)}
|
|
11202
11928
|
${c("createdAt")} timestamptz not null default now()
|
|
11203
11929
|
);${has("fingerprint") ? `\nalter table ${requests} add column if not exists ${c("fingerprint")} text check (${c("fingerprint")} is null or ${c("fingerprint")} ~ '^[0-9a-f]{64}$');` : ""}${has("consumedAt") ? `\nalter table ${requests} add column if not exists ${c("consumedAt")} timestamptz;` : ""}
|
|
11204
|
-
create unique index if not exists ${sqlIdent(`${ctx.tableName("requests").name}_pending_idx`)} on ${requests} (${c("subjectType")}, ${c("subjectId")}, ${c("action")}) where ${c("status")} = 'pending';
|
|
11930
|
+
${tenantless ? `alter table ${requests} alter column ${c("tenant")} drop not null;\n` : ""}create unique index if not exists ${sqlIdent(`${ctx.tableName("requests").name}_pending_idx`)} on ${requests} (${c("subjectType")}, ${c("subjectId")}, ${c("action")}) where ${c("status")} = 'pending';
|
|
11205
11931
|
create index if not exists ${sqlIdent(`${ctx.tableName("requests").name}_tenant_idx`)} on ${requests} (${c("tenant")}, ${c("status")}, ${c("createdAt")} desc);${addExtraColumns(requests, extras)}
|
|
11206
11932
|
${lockModuleTable(ctx, "requests", { read: true })}
|
|
11207
11933
|
${renderPolicy(policy$1({
|
|
@@ -11218,7 +11944,7 @@ ${renderPolicy(policy$1({
|
|
|
11218
11944
|
create table if not exists ${decisions} (
|
|
11219
11945
|
${d("id")} uuid primary key default gen_random_uuid(),
|
|
11220
11946
|
${d("request")} uuid not null references ${requests} (${c("id")}) on delete cascade,
|
|
11221
|
-
${d("tenant")} ${ctx.idType} not null,
|
|
11947
|
+
${d("tenant")} ${ctx.idType}${tenantless ? "" : " not null"},
|
|
11222
11948
|
${d("step")} integer not null,
|
|
11223
11949
|
${d("approver")} uuid,
|
|
11224
11950
|
${d("decision")} text not null check (${d("decision")} in ('approved', 'rejected', 'delegated')),${column("decisions", "delegateTo", (name) => `${name} uuid`)}${column("decisions", "comment", (name) => `${name} text check (${name} is null or length(${name}) <= 2000)`)}
|
|
@@ -11229,7 +11955,7 @@ create table if not exists ${decisions} (
|
|
|
11229
11955
|
"step",
|
|
11230
11956
|
"approver"
|
|
11231
11957
|
])}${delegation ? `\ncreate index if not exists ${sqlIdent(`${ctx.tableName("decisions").name}_delegate_idx`)} on ${decisions} (${d("delegateTo")}) where ${d("delegateTo")} is not null;` : ""}
|
|
11232
|
-
${lockModuleTable(ctx, "decisions", { read: true })}
|
|
11958
|
+
${tenantless ? `alter table ${decisions} alter column ${d("tenant")} drop not null;\n` : ""}${lockModuleTable(ctx, "decisions", { read: true })}
|
|
11233
11959
|
${renderPolicy(policy$1({
|
|
11234
11960
|
table: decisions,
|
|
11235
11961
|
name: ctx.naming.rename("approval_decisions_read"),
|
|
@@ -11268,6 +11994,7 @@ set search_path = ''
|
|
|
11268
11994
|
as $$
|
|
11269
11995
|
declare
|
|
11270
11996
|
v_req ${requests}%rowtype;
|
|
11997
|
+
v_step jsonb;
|
|
11271
11998
|
v_approvers jsonb;
|
|
11272
11999
|
v_me uuid := auth.uid();
|
|
11273
12000
|
begin
|
|
@@ -11289,31 +12016,29 @@ begin
|
|
|
11289
12016
|
return false;
|
|
11290
12017
|
end if;
|
|
11291
12018
|
end if;${linkedEligible}
|
|
11292
|
-
|
|
11293
|
-
|
|
11294
|
-
|
|
11295
|
-
|
|
11296
|
-
|
|
11297
|
-
|
|
11298
|
-
|
|
11299
|
-
|
|
11300
|
-
|
|
11301
|
-
|
|
11302
|
-
|
|
11303
|
-
|
|
11304
|
-
})})`}${delegation ? `
|
|
11305
|
-
or exists (
|
|
12019
|
+
v_step := ${policyOf("v_req")} -> 'steps' -> ${stepOf("v_req")};
|
|
12020
|
+
v_approvers := v_step -> 'approvers';
|
|
12021
|
+
if ${approverMatch} then
|
|
12022
|
+
return true;
|
|
12023
|
+
end if;${has("policy") ? `
|
|
12024
|
+
if coalesce((v_step ->> 'escalated')::boolean, false) then
|
|
12025
|
+
v_approvers := v_step -> 'escalateTo';
|
|
12026
|
+
if ${approverMatch} then
|
|
12027
|
+
return true;
|
|
12028
|
+
end if;
|
|
12029
|
+
end if;` : ""}
|
|
12030
|
+
return ${[...delegation ? [`exists (
|
|
11306
12031
|
select 1 from ${decisions} x
|
|
11307
12032
|
where x.${d("request")} = v_req.${c("id")} and x.${d("step")} = ${stepOf("v_req")}
|
|
11308
12033
|
and x.${d("decision")} = 'delegated' and x.${d("delegateTo")} = v_me
|
|
11309
|
-
)` : ""}${provider
|
|
11310
|
-
or (v_me is distinct from v_req.${c("requestedBy")} and coalesce((${provider.sql}), false))` : ""};
|
|
12034
|
+
)`] : [], ...provider ? [`(v_me is distinct from v_req.${c("requestedBy")} and coalesce((${provider.sql}), false))`] : []].join("\n or ") || "false"};
|
|
11311
12035
|
end;
|
|
11312
12036
|
$$;
|
|
11313
12037
|
${userGrant(`${fn("approval_eligible")}(uuid)`)}
|
|
11314
12038
|
|
|
11315
|
-
-- Notifies the current step's approvers (requested, reminder),
|
|
11316
|
-
-- (delegated) or the requester (approved,
|
|
12039
|
+
-- Notifies the current step's approvers (requested, reminder), its fallback
|
|
12040
|
+
-- approvers (escalated), a delegate (delegated) or the requester (approved,
|
|
12041
|
+
-- rejected, expired).
|
|
11317
12042
|
create or replace function ${fn("approval_notify")}(request_id uuid, kind text)
|
|
11318
12043
|
returns void
|
|
11319
12044
|
language plpgsql
|
|
@@ -11325,7 +12050,7 @@ declare
|
|
|
11325
12050
|
v_approvers jsonb;
|
|
11326
12051
|
v_permission text;
|
|
11327
12052
|
v_recipients uuid[] := '{}';
|
|
11328
|
-
v_claims text;
|
|
12053
|
+
v_claims text;${notifyBody.includes("v_note") ? "\n v_note jsonb;\n v_hook regprocedure;\n v_extra jsonb;" : ""}
|
|
11329
12054
|
begin${notifyBody}
|
|
11330
12055
|
end;
|
|
11331
12056
|
$$;
|
|
@@ -11352,8 +12077,10 @@ $$;
|
|
|
11352
12077
|
revoke execute on function ${fn("approval_finalize")}(uuid) from public, anon, authenticated;
|
|
11353
12078
|
|
|
11354
12079
|
-- Files a request under an explicit policy snapshot. request_approval and
|
|
11355
|
-
-- the access-requests module call it after their own checks.
|
|
11356
|
-
|
|
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)
|
|
11357
12084
|
returns jsonb
|
|
11358
12085
|
language plpgsql
|
|
11359
12086
|
security definer
|
|
@@ -11362,15 +12089,17 @@ as $$
|
|
|
11362
12089
|
#variable_conflict use_column
|
|
11363
12090
|
declare
|
|
11364
12091
|
v_req ${requests}%rowtype;
|
|
12092
|
+
v_policy jsonb := open_approval.policy;
|
|
12093
|
+
v_requester uuid := coalesce(open_approval.requested_by, auth.uid());
|
|
11365
12094
|
begin
|
|
11366
12095
|
${ctx.hook("before_approval_request", [
|
|
11367
12096
|
[ctx.idType, "open_approval.tenant"],
|
|
11368
12097
|
["text", "open_approval.subject_type"],
|
|
11369
12098
|
["text", "open_approval.subject_id"],
|
|
11370
12099
|
["text", "open_approval.action"]
|
|
11371
|
-
])}${openRefusals}
|
|
12100
|
+
])}${openRefusals}${allHolders}
|
|
11372
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")})
|
|
11373
|
-
values (open_approval.tenant, open_approval.subject_type, open_approval.subject_id, open_approval.action${alsoValue("requests", "policy", "
|
|
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` : ""})
|
|
11374
12103
|
on conflict (${c("subjectType")}, ${c("subjectId")}, ${c("action")}) where ${c("status")} = 'pending' do nothing
|
|
11375
12104
|
returning * into v_req;
|
|
11376
12105
|
if not found then
|
|
@@ -11382,45 +12111,8 @@ begin
|
|
|
11382
12111
|
return ${json("v_req")};
|
|
11383
12112
|
end;
|
|
11384
12113
|
$$;
|
|
11385
|
-
revoke execute on function ${fn("open_approval")}(${ctx.idType}, text, text, text, jsonb, text, jsonb) from public, anon, authenticated;
|
|
11386
|
-
${linked.length === 0 ? "" :
|
|
11387
|
-
-- Closes the pending request for a subject that its own module decided
|
|
11388
|
-
-- (decide_ai_tool_approval, approve_support_request) without running the
|
|
11389
|
-
-- module again. A request that is no longer pending is left as it is.
|
|
11390
|
-
create or replace function ${fn("approval_settle")}(subject_type text, subject_id text, action text, decision text, approver uuid, comment text default null)
|
|
11391
|
-
returns void
|
|
11392
|
-
language plpgsql
|
|
11393
|
-
security definer
|
|
11394
|
-
set search_path = ''
|
|
11395
|
-
as $$
|
|
11396
|
-
#variable_conflict use_column
|
|
11397
|
-
declare
|
|
11398
|
-
v_req ${requests}%rowtype;
|
|
11399
|
-
begin
|
|
11400
|
-
select * into v_req from ${requests} r
|
|
11401
|
-
where r.${c("subjectType")} = approval_settle.subject_type and r.${c("subjectId")} = approval_settle.subject_id
|
|
11402
|
-
and r.${c("action")} = approval_settle.action and r.${c("status")} = 'pending'
|
|
11403
|
-
for update;
|
|
11404
|
-
if not found then
|
|
11405
|
-
return;
|
|
11406
|
-
end if;
|
|
11407
|
-
${ctx.hook("before_approval_decide", [["uuid", `v_req.${c("id")}`], ["text", "approval_settle.decision"]])}
|
|
11408
|
-
insert into ${decisions} (${d("request")}, ${d("tenant")}, ${d("step")}, ${d("approver")}, ${d("decision")}${also("decisions", "comment")})
|
|
11409
|
-
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")})
|
|
11410
|
-
on conflict do nothing;
|
|
11411
|
-
update ${requests} r set ${c("status")} = ${ctx.cast("requests", "status", "approval_settle.decision")}${decided}
|
|
11412
|
-
where r.${c("id")} = v_req.${c("id")} returning * into v_req;
|
|
11413
|
-
if approval_settle.decision = 'approved' then
|
|
11414
|
-
${record("approval.approved", "v_req", true)}
|
|
11415
|
-
else
|
|
11416
|
-
${record("approval.rejected", "v_req", true)}
|
|
11417
|
-
end if;
|
|
11418
|
-
perform ${fn("approval_notify")}(v_req.${c("id")}, approval_settle.decision);
|
|
11419
|
-
${ctx.hook("after_approval_decide", [["uuid", `v_req.${c("id")}`], ["text", `v_req.${c("status")}`]])}
|
|
11420
|
-
end;
|
|
11421
|
-
$$;
|
|
11422
|
-
revoke execute on function ${fn("approval_settle")}(text, text, text, text, uuid, text) from public, anon, authenticated;
|
|
11423
|
-
`}
|
|
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)}
|
|
11424
12116
|
${approvalsTenantSql(ctx, {
|
|
11425
12117
|
json,
|
|
11426
12118
|
record,
|
|
@@ -11438,67 +12130,7 @@ ${approvalsTenantSql(ctx, {
|
|
|
11438
12130
|
extras
|
|
11439
12131
|
})}
|
|
11440
12132
|
|
|
11441
|
-
|
|
11442
|
-
-- to the next step, and the last step runs the policy's action.
|
|
11443
|
-
create or replace function ${fn("decide_approval")}(request_id uuid, decision text, comment text default null)
|
|
11444
|
-
returns jsonb
|
|
11445
|
-
language plpgsql
|
|
11446
|
-
security definer
|
|
11447
|
-
set search_path = ''
|
|
11448
|
-
as $$
|
|
11449
|
-
#variable_conflict use_column
|
|
11450
|
-
declare
|
|
11451
|
-
v_req ${requests}%rowtype;
|
|
11452
|
-
v_count integer;
|
|
11453
|
-
begin
|
|
11454
|
-
if decide_approval.decision not in ('approved', 'rejected') then
|
|
11455
|
-
${fail$1("APPROVAL_DECISION_INVALID", "decision must be approved or rejected", "22023")}
|
|
11456
|
-
end if;${commentRefusal("decide_approval.comment")}
|
|
11457
|
-
select * into v_req from ${requests} r where r.${c("id")} = decide_approval.request_id for update;
|
|
11458
|
-
if not found then
|
|
11459
|
-
${notFound}
|
|
11460
|
-
end if;
|
|
11461
|
-
if v_req.${c("status")} <> 'pending' then
|
|
11462
|
-
${fail$1("APPROVAL_CLOSED", "this request is no longer pending", "22023")}
|
|
11463
|
-
end if;${has("expiresAt") ? `
|
|
11464
|
-
if v_req.${c("expiresAt")} is not null and v_req.${c("expiresAt")} <= now() then
|
|
11465
|
-
${fail$1("APPROVAL_EXPIRED", "this request has expired", "22023")}
|
|
11466
|
-
end if;` : ""}
|
|
11467
|
-
if not ${fn("approval_eligible")}(v_req.${c("id")}) then
|
|
11468
|
-
${fail$1("APPROVAL_FORBIDDEN", "not an approver for this step")}
|
|
11469
|
-
end if;
|
|
11470
|
-
${ctx.hook("before_approval_decide", [["uuid", `v_req.${c("id")}`], ["text", "decide_approval.decision"]])}
|
|
11471
|
-
insert into ${decisions} (${d("request")}, ${d("tenant")}, ${d("step")}, ${d("approver")}, ${d("decision")}${also("decisions", "comment")})
|
|
11472
|
-
values (v_req.${c("id")}, v_req.${c("tenant")}, ${stepOf("v_req")}, auth.uid(), ${ctx.cast("decisions", "decision", "decide_approval.decision")}${alsoValue("decisions", "comment", "decide_approval.comment")});
|
|
11473
|
-
if decide_approval.decision = 'rejected' then
|
|
11474
|
-
update ${requests} r set ${c("status")} = 'rejected'${decided}
|
|
11475
|
-
where r.${c("id")} = v_req.${c("id")} returning * into v_req;
|
|
11476
|
-
${record("approval.rejected", "v_req", true)}
|
|
11477
|
-
perform ${fn("approval_notify")}(v_req.${c("id")}, 'rejected');${linkedReject}
|
|
11478
|
-
else
|
|
11479
|
-
select count(*) into v_count from ${decisions} x
|
|
11480
|
-
where x.${d("request")} = v_req.${c("id")} and x.${d("step")} = ${stepOf("v_req")} and x.${d("decision")} = 'approved';
|
|
11481
|
-
if ${policyOf("v_req")} ->> 'mode' = 'confirm' and v_req.${c("requestedBy")} = auth.uid() then
|
|
11482
|
-
update ${requests} r set ${c("status")} = 'approved'${decided}
|
|
11483
|
-
where r.${c("id")} = v_req.${c("id")} returning * into v_req;
|
|
11484
|
-
perform ${fn("approval_finalize")}(v_req.${c("id")});
|
|
11485
|
-
elsif v_count >= coalesce((${policyOf("v_req")} -> 'steps' -> ${stepOf("v_req")} ->> 'required')::integer, 1) then
|
|
11486
|
-
if ${stepOf("v_req")} + 1 >= jsonb_array_length(${policyOf("v_req")} -> 'steps') then
|
|
11487
|
-
update ${requests} r set ${c("status")} = 'approved'${decided}
|
|
11488
|
-
where r.${c("id")} = v_req.${c("id")} returning * into v_req;
|
|
11489
|
-
perform ${fn("approval_finalize")}(v_req.${c("id")});
|
|
11490
|
-
else
|
|
11491
|
-
${has("step") ? `update ${requests} r set ${c("step")} = r.${c("step")} + 1${has("remindedAt") ? `, ${c("remindedAt")} = null` : ""}
|
|
11492
|
-
where r.${c("id")} = v_req.${c("id")} returning * into v_req;
|
|
11493
|
-
perform ${fn("approval_notify")}(v_req.${c("id")}, 'requested');` : stepsRefusal}
|
|
11494
|
-
end if;
|
|
11495
|
-
end if;
|
|
11496
|
-
end if;
|
|
11497
|
-
${ctx.hook("after_approval_decide", [["uuid", `v_req.${c("id")}`], ["text", `v_req.${c("status")}`]])}
|
|
11498
|
-
return ${json("v_req")};
|
|
11499
|
-
end;
|
|
11500
|
-
$$;
|
|
11501
|
-
${userGrant(`${fn("decide_approval")}(uuid, text, text)`)}
|
|
12133
|
+
${decideSql(ctx, kit)}
|
|
11502
12134
|
|
|
11503
12135
|
-- Hands the caller's place on the current step to another user.
|
|
11504
12136
|
create or replace function ${fn("delegate_approval")}(request_id uuid, to_user uuid, comment text default null)
|
|
@@ -11612,7 +12244,7 @@ begin
|
|
|
11612
12244
|
from (
|
|
11613
12245
|
select ${json("x")} as j, x.${c("createdAt")} as at, x.${c("id")} as id
|
|
11614
12246
|
from ${requests} x
|
|
11615
|
-
where x.${c("tenant")} = list_approvals.tenant
|
|
12247
|
+
where ${tenantless ? `(x.${c("tenant")} = list_approvals.tenant or (list_approvals.tenant is null and x.${c("tenant")} is null))` : `x.${c("tenant")} = list_approvals.tenant`}
|
|
11616
12248
|
and (list_approvals.status is null or ${asText$2(ctx, "requests", `x.${c("status")}`)} = list_approvals.status)
|
|
11617
12249
|
and (list_approvals.subject_type is null or x.${c("subjectType")} = list_approvals.subject_type)
|
|
11618
12250
|
and (list_approvals.subject_id is null or x.${c("subjectId")} = list_approvals.subject_id)
|
|
@@ -11709,6 +12341,8 @@ begin${has("remindedAt") ? `
|
|
|
11709
12341
|
end;
|
|
11710
12342
|
$$;
|
|
11711
12343
|
${serviceGrant(`${fn("remind_approvals")}(interval, integer)`)}
|
|
12344
|
+
|
|
12345
|
+
${escalateSql(kit)}
|
|
11712
12346
|
${subjectCascades(ctx, subjects, `delete from ${requests} r where r.${c("subjectType")} = v_type and r.${c("subjectId")} = v_id;`)}
|
|
11713
12347
|
`;
|
|
11714
12348
|
}
|
|
@@ -27297,7 +27931,7 @@ function byEmployee(ctx) {
|
|
|
27297
27931
|
function timeOwner(ctx, statusMode) {
|
|
27298
27932
|
const fn = (name) => ctx.fn(name);
|
|
27299
27933
|
const employeeMode = byEmployee(ctx);
|
|
27300
|
-
if (employeeMode && !statusMode) throw new TypeError(`${WHERE$14}.owner "employee" keeps timesheets in a status column
|
|
27934
|
+
if (employeeMode && !statusMode) throw new TypeError(`${WHERE$14}.owner "employee" keeps timesheets in a status column`);
|
|
27301
27935
|
if (employeeMode && !ctx.installed("employees")) throw new TypeError(`${WHERE$14}.owner "employee" needs the employees block`);
|
|
27302
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`);
|
|
27303
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"`);
|
|
@@ -39041,13 +39675,13 @@ const MESSAGING_NAMES = {
|
|
|
39041
39675
|
}
|
|
39042
39676
|
}
|
|
39043
39677
|
};
|
|
39044
|
-
const NAME$
|
|
39678
|
+
const NAME$7 = /^[a-z][a-z0-9_-]{0,30}$/;
|
|
39045
39679
|
const QUEUE$2 = /^[a-z][a-z0-9_]{0,40}$/;
|
|
39046
39680
|
function messagingSql(ctx, provider) {
|
|
39047
39681
|
const permissions = moduleOperations("messaging");
|
|
39048
39682
|
const key = (action) => ctx.permission(action, permissions[action]);
|
|
39049
39683
|
const topic = ctx.text("topic", "messages");
|
|
39050
|
-
if (!NAME$
|
|
39684
|
+
if (!NAME$7.test(topic)) throw new TypeError("blocks.messaging.options.topic must be a lowercase name of at most 31 characters");
|
|
39051
39685
|
const depth = ctx.option("threadDepth");
|
|
39052
39686
|
if (depth !== void 0 && depth !== 1 && depth !== "unlimited") throw new TypeError("blocks.messaging.options.threadDepth must be 1 or \"unlimited\"");
|
|
39053
39687
|
const maxBody = ctx.number("maxBodyLength", 4e4);
|
|
@@ -39194,7 +39828,7 @@ function channelsSql(ctx) {
|
|
|
39194
39828
|
};
|
|
39195
39829
|
}
|
|
39196
39830
|
// src/sql/modules/channels.ts
|
|
39197
|
-
const NAME$
|
|
39831
|
+
const NAME$6 = "'^[a-z0-9][a-z0-9_-]{0,79}$'";
|
|
39198
39832
|
/**
|
|
39199
39833
|
* `jsonb` for channel row `ch` with its conversation `c` and the caller's
|
|
39200
39834
|
* membership.
|
|
@@ -39241,7 +39875,7 @@ function channelsTable(q) {
|
|
|
39241
39875
|
create table if not exists ${t("channels")} (
|
|
39242
39876
|
${ch("id")} uuid primary key references ${conversations} (${cv("id")}) on delete cascade,
|
|
39243
39877
|
${ch("tenant")} ${ctx.idType} not null,
|
|
39244
|
-
${ch("name")} text not null check (${ch("name")} ~ ${NAME$
|
|
39878
|
+
${ch("name")} text not null check (${ch("name")} ~ ${NAME$6}),
|
|
39245
39879
|
${ch("visibility")} text not null default 'public' check (${ch("visibility")} in ('public', 'private')),
|
|
39246
39880
|
${ch("topic")} text check (${ch("topic")} is null or length(${ch("topic")}) <= 250),
|
|
39247
39881
|
${ch("purpose")} text check (${ch("purpose")} is null or length(${ch("purpose")}) <= 250),${optional("subjectType", "text")}${optional("subjectId", "text")}
|
|
@@ -39308,7 +39942,7 @@ begin
|
|
|
39308
39942
|
if not (${SERVICE_CALLER$1} or ${q.can("create_channel.tenant", "create")}) then
|
|
39309
39943
|
${fail$1("CHANNELS_FORBIDDEN", "not allowed to create channels here")}
|
|
39310
39944
|
end if;
|
|
39311
|
-
if v_name is null or v_name !~ ${NAME$
|
|
39945
|
+
if v_name is null or v_name !~ ${NAME$6} then
|
|
39312
39946
|
${fail$1("CHANNELS_NAME_INVALID", "a channel name is 1 to 80 lowercase letters, digits, - or _, starting with a letter or digit", "22023")}
|
|
39313
39947
|
end if;
|
|
39314
39948
|
if v_visibility not in ('public', 'private') then
|
|
@@ -39365,7 +39999,7 @@ begin
|
|
|
39365
39999
|
${fail$1("CHANNELS_FORBIDDEN", "not allowed to change this channel")}
|
|
39366
40000
|
end if;
|
|
39367
40001
|
v_name := coalesce(lower(trim(update_channel.attrs ->> 'name')), v_ch.${ch("name")});
|
|
39368
|
-
if v_name !~ ${NAME$
|
|
40002
|
+
if v_name !~ ${NAME$6} then
|
|
39369
40003
|
${fail$1("CHANNELS_NAME_INVALID", "a channel name is 1 to 80 lowercase letters, digits, - or _, starting with a letter or digit", "22023")}
|
|
39370
40004
|
end if;
|
|
39371
40005
|
v_visibility := coalesce(update_channel.attrs ->> 'visibility', v_ch.${ch("visibility")}::text);
|
|
@@ -52329,11 +52963,15 @@ const OPTIONAL_LINE_COLUMNS = [
|
|
|
52329
52963
|
"taxCode",
|
|
52330
52964
|
"createdAt"
|
|
52331
52965
|
];
|
|
52332
|
-
/**
|
|
52966
|
+
/**
|
|
52967
|
+
* The line columns of a document a customer answers: sections, options and the
|
|
52968
|
+
* number of periods a subscription line runs.
|
|
52969
|
+
*/
|
|
52333
52970
|
const DOCUMENT_LINE_COLUMNS = {
|
|
52334
52971
|
section: "section",
|
|
52335
52972
|
optional: "optional",
|
|
52336
|
-
selected: "selected"
|
|
52973
|
+
selected: "selected",
|
|
52974
|
+
periods: "periods"
|
|
52337
52975
|
};
|
|
52338
52976
|
/**
|
|
52339
52977
|
* A `NAMES.tables` entry for a line table called `name`. The app's own line
|
|
@@ -52375,6 +53013,14 @@ function countedLine(ctx, lines, alias) {
|
|
|
52375
53013
|
return declared(ctx, lines, "selected") ? `(not ${optional} or ${alias}.${ctx.col(lines, "selected")})` : `not ${optional}`;
|
|
52376
53014
|
}
|
|
52377
53015
|
/**
|
|
53016
|
+
* A line's amount before discounts: quantity times unit amount, times its
|
|
53017
|
+
* periods when the line table counts them, rounded once.
|
|
53018
|
+
*/
|
|
53019
|
+
function lineAmount(ctx, lines, alias) {
|
|
53020
|
+
const periods = declared(ctx, lines, "periods") ? ` * coalesce(${alias}.${ctx.col(lines, "periods")}, 1)` : "";
|
|
53021
|
+
return `round(${alias}.${ctx.col(lines, "quantity")}${periods} * ${alias}.${ctx.col(lines, "unitAmount")})`;
|
|
53022
|
+
}
|
|
53023
|
+
/**
|
|
52378
53024
|
* Line column `column` of row `alias` in line table `lines`, or what a read
|
|
52379
53025
|
* gives when the app's table lacks it.
|
|
52380
53026
|
*/
|
|
@@ -52437,7 +53083,7 @@ function lineItemsSql(ctx, items, options) {
|
|
|
52437
53083
|
const fn = ctx.fn(options.setter);
|
|
52438
53084
|
const recount = ctx.fn(`${options.setter}_recount`);
|
|
52439
53085
|
const trigger = `bsb_${ctx.tableName(items.lines).name}_totals`;
|
|
52440
|
-
const list =
|
|
53086
|
+
const list = lineAmount(ctx, items.lines, "l");
|
|
52441
53087
|
const discount = has("discountBps") ? `round(${list} * ${l("discountBps")} / 10000.0)` : "0";
|
|
52442
53088
|
const tax = has("taxRateBps") ? `round((${list} - ${discount}) * ${l("taxRateBps")} / 10000.0)` : "0";
|
|
52443
53089
|
const optional = (column, definition = () => "text") => has(column) ? `\n ${c(column)} ${definition(c(column))},` : "";
|
|
@@ -52458,6 +53104,7 @@ function lineItemsSql(ctx, items, options) {
|
|
|
52458
53104
|
["section", "nullif(trim(x.value ->> 'section'), '')"],
|
|
52459
53105
|
["optional", "coalesce((x.value ->> 'optional')::boolean, false)"],
|
|
52460
53106
|
["selected", "coalesce((x.value ->> 'selected')::boolean, not coalesce((x.value ->> 'optional')::boolean, false))"],
|
|
53107
|
+
["periods", "coalesce((x.value ->> 'periods')::integer, 1)"],
|
|
52461
53108
|
["position", "x.ordinality::integer"]
|
|
52462
53109
|
].filter(([column]) => has(column)).map(([column, value]) => [column, column === "productType" ? ctx.cast(items.lines, column, value) : RATE_COLUMNS.has(column) && percentRates(ctx, items.lines) ? `(${value} / 100.0)` : value]);
|
|
52463
53110
|
const extras = items.extras ?? [];
|
|
@@ -52468,10 +53115,10 @@ function lineItemsSql(ctx, items, options) {
|
|
|
52468
53115
|
${c("parent")} uuid not null references ${p} (${pc("id")}) on delete cascade,${optional("productType")}${optional("productId")}
|
|
52469
53116
|
${c("description")} text not null check (length(${c("description")}) between 1 and 2000),
|
|
52470
53117
|
${c("quantity")} numeric(18, 4) not null check (${c("quantity")} > 0),
|
|
52471
|
-
${c("unitAmount")} bigint not null,${optional("discountBps", (bps) => `integer not null default 0 check (${bps} >= 0 and ${bps} <= 10000)`)}${optional("taxRateBps", (bps) => `integer not null default 0 check (${bps} >= 0 and ${bps} <= 100000)`)}${optional("taxCode")}${optional("section", (section) => `text check (length(${section}) between 1 and 300)`)}${optional("optional", () => "boolean not null default false")}${optional("selected", () => "boolean not null default true")}
|
|
53118
|
+
${c("unitAmount")} bigint not null,${optional("discountBps", (bps) => `integer not null default 0 check (${bps} >= 0 and ${bps} <= 10000)`)}${optional("taxRateBps", (bps) => `integer not null default 0 check (${bps} >= 0 and ${bps} <= 100000)`)}${optional("taxCode")}${optional("section", (section) => `text check (length(${section}) between 1 and 300)`)}${optional("optional", () => "boolean not null default false")}${optional("selected", () => "boolean not null default true")}${optional("periods", (periods) => `integer not null default 1 check (${periods} > 0)`)}
|
|
52472
53119
|
${c("position")} integer not null${has("createdAt") ? `,\n ${c("createdAt")} timestamptz not null default now()` : ""}${has("productType") && has("productId") ? `,\n check ((${c("productType")} is null) = (${c("productId")} is null))` : ""}
|
|
52473
53120
|
);
|
|
52474
|
-
create index if not exists ${sqlIdent(`${name}_parent_idx`)} on ${t} (${c("parent")}, ${c("position")});${ctx.owns(items.lines) || !positionKey ? "" : `\ncreate unique index if not exists ${sqlIdent(`bsb_${name}_position_key`)} on ${t} (${c("parent")}, ${c("position")});`}${addExtraColumns(t, extras)}
|
|
53121
|
+
${has("periods") ? `alter table ${t} add column if not exists ${c("periods")} integer not null default 1 check (${c("periods")} > 0);\n` : ""}create index if not exists ${sqlIdent(`${name}_parent_idx`)} on ${t} (${c("parent")}, ${c("position")});${ctx.owns(items.lines) || !positionKey ? "" : `\ncreate unique index if not exists ${sqlIdent(`bsb_${name}_position_key`)} on ${t} (${c("parent")}, ${c("position")});`}${addExtraColumns(t, extras)}
|
|
52475
53122
|
${lockTable(t, { read: true })}
|
|
52476
53123
|
drop policy if exists ${sqlIdent(`${name}_read`)} on ${t};
|
|
52477
53124
|
create policy ${sqlIdent(`${name}_read`)} on ${t} for select to authenticated
|
|
@@ -52519,7 +53166,7 @@ end;
|
|
|
52519
53166
|
$$;
|
|
52520
53167
|
revoke execute on function ${recount}(uuid) from public, anon, authenticated;
|
|
52521
53168
|
`;
|
|
52522
|
-
|
|
53169
|
+
const triggers = recounted ? `${recountSql}
|
|
52523
53170
|
-- Recounts each record a statement touched once, in id order so concurrent
|
|
52524
53171
|
-- statements lock the records in the same order. A transition table needs a
|
|
52525
53172
|
-- trigger per event, so there are three triggers on one function. The
|
|
@@ -52566,45 +53213,41 @@ drop trigger if exists ${trigger}_update on ${t};
|
|
|
52566
53213
|
drop trigger if exists ${trigger}_delete on ${t};
|
|
52567
53214
|
drop function if exists better_supabase.${trigger}();
|
|
52568
53215
|
drop function if exists ${recount}(uuid);
|
|
52569
|
-
|
|
52570
|
-
|
|
52571
|
-
-- unitAmount (minor units as text), currency, discountBps, taxRateBps,
|
|
52572
|
-
-- taxCode, product: { type, id } }. A line's currency must be the record's.
|
|
52573
|
-
-- Returns the record's totals as text, with its currency.${options.fallback ? "\n-- A line without unitAmount or description takes them from its product." : ""}
|
|
52574
|
-
create or replace function ${fn}(parent uuid, lines jsonb)
|
|
53216
|
+
`;
|
|
53217
|
+
const setterSql = (name, guard, frozen, grant) => `create or replace function ${ctx.fn(name)}(parent uuid, lines jsonb)
|
|
52575
53218
|
returns jsonb
|
|
52576
53219
|
language plpgsql
|
|
52577
53220
|
security definer
|
|
52578
53221
|
set search_path = ''
|
|
52579
53222
|
as $$
|
|
52580
53223
|
declare
|
|
52581
|
-
v_parent uuid := ${
|
|
53224
|
+
v_parent uuid := ${name}.parent;
|
|
52582
53225
|
v_tenant ${ctx.idType};
|
|
52583
53226
|
v_currency text;${extras.length === 0 ? "" : "\n v_line record;"}
|
|
52584
53227
|
begin
|
|
52585
|
-
select x.${pc("tenant")}, x.${pc("currency")} into v_tenant, v_currency from ${p} x where x.${pc("id")} = v_parent${
|
|
53228
|
+
select x.${pc("tenant")}, x.${pc("currency")} into v_tenant, v_currency from ${p} x where x.${pc("id")} = v_parent${frozen === void 0 ? "" : ` and not (${frozen.replaceAll("p.", "x.")})`};
|
|
52586
53229
|
if v_tenant is null then
|
|
52587
53230
|
${fail$1("LINES_RECORD_INVALID", "no such record, or its lines are locked", "P0002")}
|
|
52588
53231
|
end if;
|
|
52589
|
-
${
|
|
52590
|
-
if jsonb_typeof(coalesce(${
|
|
53232
|
+
${guard}
|
|
53233
|
+
if jsonb_typeof(coalesce(${name}.lines, '[]')) <> 'array' then
|
|
52591
53234
|
${fail$1("LINES_INVALID", "lines must be a list", "22023")}
|
|
52592
53235
|
end if;
|
|
52593
|
-
if exists (select 1 from jsonb_array_elements(${
|
|
53236
|
+
if exists (select 1 from jsonb_array_elements(${name}.lines) x where x.value ? 'currency' and x.value ->> 'currency' is distinct from v_currency) then
|
|
52594
53237
|
${fail$1("LINES_CURRENCY", "every line must be in the record's currency", "22023")}
|
|
52595
53238
|
end if;
|
|
52596
|
-
delete from ${t} l where l.${c("parent")} = v_parent${replaces ? "" : ` and l.${c("position")} > jsonb_array_length(coalesce(${
|
|
53239
|
+
delete from ${t} l where l.${c("parent")} = v_parent${replaces ? "" : ` and l.${c("position")} > jsonb_array_length(coalesce(${name}.lines, '[]'))`};
|
|
52597
53240
|
begin${replaces || positionKey ? "" : `
|
|
52598
53241
|
update ${t} l set ${written.filter(([column]) => ![
|
|
52599
53242
|
"tenant",
|
|
52600
53243
|
"parent",
|
|
52601
53244
|
"position"
|
|
52602
53245
|
].includes(column)).map(([column, value]) => `${c(column)} = ${value}`).join(", ")}
|
|
52603
|
-
from jsonb_array_elements(coalesce(${
|
|
53246
|
+
from jsonb_array_elements(coalesce(${name}.lines, '[]')) with ordinality x
|
|
52604
53247
|
where l.${c("parent")} = v_parent and l.${c("position")} = x.ordinality;`}
|
|
52605
53248
|
insert into ${t} (${written.map(([column]) => c(column)).join(", ")}${extrasInsert.columns})
|
|
52606
53249
|
select ${written.map(([, value]) => value).join(",\n ")}${extrasInsert.values}
|
|
52607
|
-
from jsonb_array_elements(coalesce(${
|
|
53250
|
+
from jsonb_array_elements(coalesce(${name}.lines, '[]')) with ordinality x${replaces ? "" : positionKey ? `\n on conflict (${c("parent")}, ${c("position")}) do update set ${written.filter(([column]) => ![
|
|
52608
53251
|
"tenant",
|
|
52609
53252
|
"parent",
|
|
52610
53253
|
"position"
|
|
@@ -52612,7 +53255,7 @@ begin
|
|
|
52612
53255
|
exception when check_violation or not_null_violation or invalid_text_representation or numeric_value_out_of_range then
|
|
52613
53256
|
${fail$1("LINES_INVALID", "every line needs a description, a positive quantity and a unit amount", "22023")}
|
|
52614
53257
|
end;${extras.length === 0 ? "" : `
|
|
52615
|
-
for v_line in select x.value -> 'fields' as fields, x.ordinality::integer as position from jsonb_array_elements(coalesce(${
|
|
53258
|
+
for v_line in select x.value -> 'fields' as fields, x.ordinality::integer as position from jsonb_array_elements(coalesce(${name}.lines, '[]')) with ordinality x where jsonb_typeof(x.value -> 'fields') = 'object' loop${writeExtraColumns(t, extras, "v_line.fields", `x.${c("parent")} = v_parent and x.${c("position")} = v_line.position`).replaceAll("\n", "\n ")}
|
|
52616
53259
|
end loop;`}
|
|
52617
53260
|
${recounted ? ` perform ${recount}(v_parent);\n` : ""} return (select jsonb_build_object(
|
|
52618
53261
|
${totalsJson},
|
|
@@ -52620,9 +53263,18 @@ ${recounted ? ` perform ${recount}(v_parent);\n` : ""} return (select jsonb_bu
|
|
|
52620
53263
|
from ${p} x where x.${pc("id")} = v_parent);
|
|
52621
53264
|
end;
|
|
52622
53265
|
$$;
|
|
52623
|
-
|
|
52624
|
-
grant execute on function ${fn}(uuid, jsonb) to authenticated, service_role;
|
|
53266
|
+
${grant}
|
|
52625
53267
|
`;
|
|
53268
|
+
return `${manages}${triggers}
|
|
53269
|
+
-- Replaces a record's lines with lines: a list of { description, quantity,
|
|
53270
|
+
-- unitAmount (minor units as text), currency, discountBps, taxRateBps,
|
|
53271
|
+
-- taxCode, product: { type, id } }. A line's currency must be the record's.
|
|
53272
|
+
-- Returns the record's totals as text, with its currency.${options.fallback ? "\n-- A line without unitAmount or description takes them from its product." : ""}
|
|
53273
|
+
${setterSql(options.setter, options.guard, items.frozen, `revoke execute on function ${fn}(uuid, jsonb) from public, anon;
|
|
53274
|
+
grant execute on function ${fn}(uuid, jsonb) to authenticated, service_role;`)}${options.restorer === void 0 ? "" : `
|
|
53275
|
+
-- Writes a record's lines like ${options.setter}, without its checks, for the
|
|
53276
|
+
-- module's own functions.
|
|
53277
|
+
${setterSql(options.restorer, "", void 0, `revoke execute on function ${ctx.fn(options.restorer)}(uuid, jsonb) from public, anon, authenticated;`)}`}`;
|
|
52626
53278
|
}
|
|
52627
53279
|
/**
|
|
52628
53280
|
* The `fallback` of a line that names a catalog variant (`product: { type:
|
|
@@ -52677,7 +53329,7 @@ function documentRecountSql(ctx, items, options) {
|
|
|
52677
53329
|
const l = (column) => lineColumn(ctx, items.lines, "l", column);
|
|
52678
53330
|
const parentHas = (column) => declared(ctx, items.parent, column);
|
|
52679
53331
|
const parent = `${options.setter}_recount.parent`;
|
|
52680
|
-
const amount =
|
|
53332
|
+
const amount = lineAmount(ctx, items.lines, "l");
|
|
52681
53333
|
const discount = declared(ctx, items.lines, "discountBps") ? `round(${amount} * ${l("discountBps")} / 10000.0)` : "0";
|
|
52682
53334
|
const rate = declared(ctx, items.lines, "taxRateBps") ? l("taxRateBps") : "0";
|
|
52683
53335
|
const code = declared(ctx, items.lines, "taxCode") ? `l.${c("taxCode")}` : "null::text";
|
|
@@ -53757,10 +54409,10 @@ const NAMES$80 = {
|
|
|
53757
54409
|
lines: lineTableSpec("deal_lines")
|
|
53758
54410
|
}
|
|
53759
54411
|
};
|
|
53760
|
-
const NAME$
|
|
54412
|
+
const NAME$5 = /^[a-z][a-z0-9_]{0,62}$/;
|
|
53761
54413
|
function names$7(ctx, option, fallback) {
|
|
53762
54414
|
const list = ctx.list(option, fallback);
|
|
53763
|
-
if (list.length === 0 || list.some((item) => !NAME$
|
|
54415
|
+
if (list.length === 0 || list.some((item) => !NAME$5.test(item))) throw new TypeError(`blocks.deals.options.${option} must be a non-empty list of lowercase names`);
|
|
53764
54416
|
return `${sqlString(`{${list.join(",")}}`)}::text[]`;
|
|
53765
54417
|
}
|
|
53766
54418
|
function tables$24(ctx, n) {
|
|
@@ -61728,6 +62380,23 @@ function quoteOrigin(ctx) {
|
|
|
61728
62380
|
return ctx.has("quotes", "originType") && ctx.has("quotes", "originId");
|
|
61729
62381
|
}
|
|
61730
62382
|
/**
|
|
62383
|
+
* `blocks.quotes.options.versionLines`: each published version keeps its lines
|
|
62384
|
+
* as rows with their own ids in `quote_version_lines`.
|
|
62385
|
+
*/
|
|
62386
|
+
function versionLinesOn(ctx) {
|
|
62387
|
+
return ctx.flag("versionLines", false) && ctx.hasTable("versionLines");
|
|
62388
|
+
}
|
|
62389
|
+
/**
|
|
62390
|
+
* `blocks.quotes.options.workingCopy`: staff edit a sent quote while the
|
|
62391
|
+
* customer keeps seeing its last published version, and sending publishes the
|
|
62392
|
+
* next one on the same link.
|
|
62393
|
+
*/
|
|
62394
|
+
function workingCopyOn(ctx) {
|
|
62395
|
+
const on = ctx.flag("workingCopy", false);
|
|
62396
|
+
if (on && !ctx.has("quotes", "unpublishedChanges")) throw new TypeError("blocks.quotes.options.workingCopy needs the quotes table's unpublishedChanges column");
|
|
62397
|
+
return on;
|
|
62398
|
+
}
|
|
62399
|
+
/**
|
|
61731
62400
|
* SQL over quote columns prefixed with `prefix` (`""` in a policy, `v_row.` in
|
|
61732
62401
|
* a function) that is true when the caller is a guest the quote is shared with:
|
|
61733
62402
|
* a grant on the quote, or a guest of its company or contact (ADR 0070). A
|
|
@@ -61771,12 +62440,20 @@ function quoteKit(ctx, n) {
|
|
|
61771
62440
|
returning * into v_row;
|
|
61772
62441
|
${record("quote.viewed", "v_row")}
|
|
61773
62442
|
end if;` : " null;";
|
|
61774
|
-
const
|
|
62443
|
+
const workingCopy = workingCopyOn(ctx);
|
|
62444
|
+
const versionLines = versionLinesOn(ctx);
|
|
62445
|
+
const open = (alias) => st(`${alias}.${q("status")}`, workingCopy ? [
|
|
62446
|
+
"draft",
|
|
62447
|
+
"changes_requested",
|
|
62448
|
+
"sent",
|
|
62449
|
+
"viewed"
|
|
62450
|
+
] : ["draft", "changes_requested"]);
|
|
61775
62451
|
const lineValue = (column) => lineColumn(ctx, "lines", "ql", column);
|
|
61776
62452
|
const documentLine = [
|
|
61777
62453
|
"section",
|
|
61778
62454
|
"optional",
|
|
61779
|
-
"selected"
|
|
62455
|
+
"selected",
|
|
62456
|
+
"periods"
|
|
61780
62457
|
].filter(lineHas).map((column) => `, ${sqlString(column)}, ql.${l(column)}`).join("");
|
|
61781
62458
|
const lines = (alias) => `coalesce((select jsonb_agg(jsonb_build_object('position', ql.${l("position")}, 'description', ql.${l("description")}, 'quantity', ql.${l("quantity")}, 'unitAmount', ql.${l("unitAmount")}::text, 'discountBps', ${lineValue("discountBps")}, 'taxRateBps', ${lineValue("taxRateBps")}, 'taxCode', ${lineValue("taxCode")}${documentLine}, 'product', case when ${lineValue("productType")} is null then null else jsonb_build_object('type', ${lineValue("productType")}, 'id', ${lineValue("productId")}) end${lineFieldsJson("ql", n.lineExtras)}) order by ql.${l("position")}) from ${t("lines")} ql where ql.${l("parent")} = ${alias}.${q("id")}), '[]'::jsonb)`;
|
|
61782
62459
|
const tl = (column) => c("taxLines", column);
|
|
@@ -61791,14 +62468,23 @@ function quoteKit(ctx, n) {
|
|
|
61791
62468
|
const int8As = Object.fromEntries(int8Columns.map((logical) => [logical, (value) => `${value}::text`]));
|
|
61792
62469
|
const row = (alias) => `(${ctx.rowJson("quotes", alias, { as: int8As })} - ${sqlString(q("tokenHash").replaceAll("\"", ""))}${q("tokenHash") === "\"token_hash\"" ? "" : " - 'token_hash'"}) || ${int8Text(alias, int8)} || jsonb_build_object('lines', ${lines(alias)}, 'taxLines', ${taxLines(alias)}${n.extras.length === 0 ? "" : `, 'fields', ${columnsObject(alias, n.extras.map((extra) => extra.name))}`})`;
|
|
61793
62470
|
const text = (alias, logical, otherwise) => has(logical) ? `${alias}.${q(logical)}::text` : otherwise;
|
|
61794
|
-
const
|
|
62471
|
+
const v = (column) => c("versions", column);
|
|
62472
|
+
const vl = (column) => c("versionLines", column);
|
|
62473
|
+
const latestVersion = (alias) => `(select lv.${v("id")} from ${t("versions")} lv where lv.${v("quote")} = ${alias}.${q("id")} order by lv.${v("revision")} desc limit 1)`;
|
|
62474
|
+
const withVersionLineIds = (list, version) => versionLines ? `(select coalesce(jsonb_agg(e.value || jsonb_build_object('versionLineId', vx.${vl("id")}) order by e.ordinality), '[]'::jsonb)
|
|
62475
|
+
from jsonb_array_elements(${list}) with ordinality e
|
|
62476
|
+
left join ${t("versionLines")} vx on vx.${vl("version")} = ${version} and vx.${vl("position")} = (e.value ->> 'position')::integer)` : list;
|
|
62477
|
+
const publicJson = (alias, version) => `jsonb_build_object(
|
|
61795
62478
|
'identifier', ${alias}.${q("identifier")}, 'revision', ${alias}.${q("revision")}, 'title', ${alias}.${q("title")},
|
|
61796
62479
|
'status', ${ctx.label("quotes", "status", `${alias}.${q("status")}`)}, 'currency', ${alias}.${q("currency")}, 'validUntil', ${alias}.${q("validUntil")},
|
|
61797
62480
|
'terms', ${or(alias, "terms")}, 'pricesIncludeTax', ${has("pricesIncludeTax") ? `${alias}.${q("pricesIncludeTax")}` : "false"},
|
|
61798
62481
|
'discountBps', ${has("discountBps") ? `${alias}.${q("discountBps")}` : "0"}, 'discountAmount', ${text(alias, "discountAmount", "'0'")},
|
|
61799
|
-
'depositBps', ${or(alias, "depositBps")}, '
|
|
62482
|
+
'depositBps', ${or(alias, "depositBps")}, 'depositAmount', ${text(alias, "depositAmount", "null")}, 'depositRequired', ${has("depositRequired") ? `${alias}.${q("depositRequired")}` : "false"},
|
|
62483
|
+
'depositDue', ${text(alias, "depositDue", "'0'")},
|
|
61800
62484
|
'listTotal', ${text(alias, "listTotal", `${alias}.${q("subtotal")}::text`)}, 'subtotal', ${alias}.${q("subtotal")}::text, 'discountTotal', ${text(alias, "discountTotal", "'0'")},
|
|
61801
|
-
'taxTotal', ${alias}.${q("taxTotal")}::text, 'total', ${alias}.${q("total")}::text,
|
|
62485
|
+
'taxTotal', ${alias}.${q("taxTotal")}::text, 'total', ${alias}.${q("total")}::text,
|
|
62486
|
+
'lines', ${version === void 0 ? withVersionLineIds(lines(alias), latestVersion(alias)) : withVersionLineIds(`coalesce(${version} -> 'lines', '[]'::jsonb)`, latestVersion(alias))},
|
|
62487
|
+
'taxLines', ${version === void 0 ? taxLines(alias) : `coalesce(${version} -> 'taxLines', '[]'::jsonb)`})`;
|
|
61802
62488
|
const checkParty = (kind, type, id, tenant) => (kind === "COMPANY" ? company : contact) ? `
|
|
61803
62489
|
if ${id} is not null and not ${subjectInTenant(ctx, type, id, tenant)} then
|
|
61804
62490
|
${fail$1(`QUOTE_${kind}_FORBIDDEN`, `the ${kind.toLowerCase()} is unknown or not readable in this organization`, "42501")}
|
|
@@ -61840,14 +62526,38 @@ function quoteKit(ctx, n) {
|
|
|
61840
62526
|
taxLines,
|
|
61841
62527
|
row,
|
|
61842
62528
|
publicJson,
|
|
62529
|
+
withVersionLineIds,
|
|
62530
|
+
latestVersion,
|
|
62531
|
+
versionLines,
|
|
62532
|
+
workingCopy,
|
|
61843
62533
|
record,
|
|
61844
62534
|
checkParty,
|
|
61845
62535
|
notifyOwner,
|
|
61846
62536
|
markViewed,
|
|
61847
|
-
depositDue: has("depositDue") && has("depositBps") ? `${q("depositDue")} = case when x.${q("
|
|
62537
|
+
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
|
|
61848
62538
|
};
|
|
61849
62539
|
}
|
|
61850
62540
|
// src/sql/modules/quotes-decisions.ts
|
|
62541
|
+
/** The quote columns a customer sees of a published version. */
|
|
62542
|
+
const PUBLISHED = [
|
|
62543
|
+
"revision",
|
|
62544
|
+
"title",
|
|
62545
|
+
"currency",
|
|
62546
|
+
"validUntil",
|
|
62547
|
+
"terms",
|
|
62548
|
+
"pricesIncludeTax",
|
|
62549
|
+
"discountBps",
|
|
62550
|
+
"discountAmount",
|
|
62551
|
+
"depositBps",
|
|
62552
|
+
"depositAmount",
|
|
62553
|
+
"depositRequired",
|
|
62554
|
+
"depositDue",
|
|
62555
|
+
"listTotal",
|
|
62556
|
+
"subtotal",
|
|
62557
|
+
"discountTotal",
|
|
62558
|
+
"taxTotal",
|
|
62559
|
+
"total"
|
|
62560
|
+
];
|
|
61851
62561
|
/**
|
|
61852
62562
|
* The functions that take a customer's answer: recorded by staff, through the
|
|
61853
62563
|
* link, or by a signed-in guest the quote is shared with (ADR 0070), and the
|
|
@@ -61860,48 +62570,94 @@ function quoteDecisions(ctx, n, k) {
|
|
|
61860
62570
|
const guest = quoteGuest(ctx, n, "x.");
|
|
61861
62571
|
const noted = (note) => has("decisionNote") ? `v_row.${q("decisionNote")}` : `nullif(trim(${note}), '')`;
|
|
61862
62572
|
const selects = lineHas("optional") && lineHas("selected");
|
|
62573
|
+
const vl = (column) => n.c("versionLines", column);
|
|
62574
|
+
const position = (element) => k.versionLines ? `case when jsonb_typeof(${element}) = 'number' then (${element} #>> '{}')::numeric else (
|
|
62575
|
+
select vx.${vl("position")}::numeric from ${t("versionLines")} vx
|
|
62576
|
+
where vx.${vl("version")} = ${k.latestVersion("v_row")} and vx.${vl("id")}::text = ${element} #>> '{}'
|
|
62577
|
+
) end` : `(${element} #>> '{}')::numeric`;
|
|
61863
62578
|
const selection = (name) => selects ? `
|
|
61864
62579
|
if ${name}.selected is not null then
|
|
61865
62580
|
if jsonb_typeof(${name}.selected) <> 'array' or exists (
|
|
61866
62581
|
select 1 from jsonb_array_elements(${name}.selected) e
|
|
61867
|
-
where jsonb_typeof(e.value)
|
|
62582
|
+
where jsonb_typeof(e.value) not in ('number'${k.versionLines ? ", 'string'" : ""}) or not exists (
|
|
61868
62583
|
select 1 from ${t("lines")} ql
|
|
61869
|
-
where ql.${l("parent")} = v_row.${q("id")} and ql.${l("optional")} and ql.${l("position")} = (e.value
|
|
62584
|
+
where ql.${l("parent")} = v_row.${q("id")} and ql.${l("optional")} and ql.${l("position")} = ${position("e.value")}
|
|
61870
62585
|
)
|
|
61871
62586
|
) then
|
|
61872
|
-
${fail$1("QUOTE_SELECTION_INVALID",
|
|
62587
|
+
${fail$1("QUOTE_SELECTION_INVALID", `pick optional lines of this quote by position${k.versionLines ? " or version line id" : ""}`, "22023")}
|
|
61873
62588
|
end if;
|
|
61874
|
-
update ${t("lines")} ql set ${l("selected")} = ql.${l("position")} in (select (e.value
|
|
62589
|
+
update ${t("lines")} ql set ${l("selected")} = ql.${l("position")} in (select (${position("e.value")})::integer from jsonb_array_elements(${name}.selected) e)
|
|
61875
62590
|
where ql.${l("parent")} = v_row.${q("id")} and ql.${l("optional")};
|
|
61876
62591
|
end if;` : `
|
|
61877
62592
|
if ${name}.selected is not null and ${name}.selected <> '[]'::jsonb then
|
|
61878
62593
|
${fail$1("QUOTE_SELECTION_INVALID", "this quote has no optional lines", "22023")}
|
|
61879
62594
|
end if;`;
|
|
62595
|
+
const snapshotRecord = (columns) => `jsonb_populate_record(v_row, coalesce((select jsonb_object_agg(e.key, e.value) from jsonb_each(v_snap) e where e.key in (${columns.map((column) => sqlString(Object.hasOwn(ctx.names.tables["quotes"]?.columns ?? {}, column) ? ctx.colName("quotes", column) : column)).join(", ")})), '{}'::jsonb))`;
|
|
62596
|
+
const restored = [
|
|
62597
|
+
"title",
|
|
62598
|
+
"currency",
|
|
62599
|
+
"validUntil",
|
|
62600
|
+
"terms",
|
|
62601
|
+
"pricesIncludeTax",
|
|
62602
|
+
"discountBps",
|
|
62603
|
+
"discountAmount",
|
|
62604
|
+
"depositBps",
|
|
62605
|
+
"depositAmount",
|
|
62606
|
+
"depositRequired"
|
|
62607
|
+
].filter(has);
|
|
62608
|
+
const restore = k.workingCopy ? `
|
|
62609
|
+
if v_row.${q("unpublishedChanges")} then
|
|
62610
|
+
select v.${n.c("versions", "snapshot")} into v_snap from ${t("versions")} v where v.${n.c("versions", "id")} = ${k.latestVersion("v_row")};
|
|
62611
|
+
if v_snap is not null then
|
|
62612
|
+
v_pub := ${snapshotRecord([...restored, ...n.extras.map((extra) => extra.name)])};
|
|
62613
|
+
update ${t("quotes")} x set ${[...restored.map(q), ...n.extras.map((extra) => extra.ident)].map((column) => `${column} = v_pub.${column}`).join(", ")}
|
|
62614
|
+
where x.${q("id")} = v_row.${q("id")};
|
|
62615
|
+
perform ${fn("quote_lines_restore")}(v_row.${q("id")}, coalesce(v_snap -> 'lines', '[]'::jsonb));
|
|
62616
|
+
select * into v_row from ${t("quotes")} x where x.${q("id")} = v_row.${q("id")};
|
|
62617
|
+
end if;
|
|
62618
|
+
end if;` : "";
|
|
61880
62619
|
const client = (column, value) => has(column) ? `${q(column)} = ${value}, ` : "";
|
|
61881
62620
|
const headers = `
|
|
61882
|
-
v_headers jsonb := nullif(current_setting('request.headers', true), '')::jsonb
|
|
62621
|
+
v_headers jsonb := nullif(current_setting('request.headers', true), '')::jsonb;
|
|
62622
|
+
v_ip inet;`;
|
|
62623
|
+
const restoreVars = k.workingCopy ? `
|
|
62624
|
+
v_snap jsonb;
|
|
62625
|
+
v_pub ${t("quotes")};` : "";
|
|
61883
62626
|
const ip = "left(nullif(trim(reverse(split_part(reverse(v_headers ->> 'x-forwarded-for'), ',', 1))), ''), 64)";
|
|
62627
|
+
const customerActor = (a) => `jsonb_strip_nulls(jsonb_build_object('name', nullif(trim(${a.by}), ''), 'email', auth.jwt() ->> 'email', 'ip', v_ip::text, 'userAgent', left(v_headers ->> 'user-agent', 512)))`;
|
|
62628
|
+
const actorIp = (a) => a.actor === void 0 ? ip : `left(${a.actor} ->> 'ip', 64)`;
|
|
62629
|
+
const actorAgent = (a) => a.actor === void 0 ? "left(v_headers ->> 'user-agent', 512)" : `left(${a.actor} ->> 'userAgent', 512)`;
|
|
61884
62630
|
const answer = (a) => `
|
|
61885
62631
|
if ${a.name}.decision not in ('accepted', 'rejected', 'changes_requested') then
|
|
61886
62632
|
${fail$1("QUOTE_DECISION_INVALID", "answer accepted, rejected or changes_requested", "22023")}
|
|
61887
62633
|
end if;
|
|
61888
62634
|
if ${st(`v_row.${q("status")}`, ["sent", "viewed"], true)} then
|
|
61889
62635
|
${fail$1("QUOTE_NOT_OPEN", "this quote no longer takes an answer", "55000")}
|
|
61890
|
-
end if;${a.
|
|
61891
|
-
|
|
62636
|
+
end if;${a.actor === void 0 ? a.customer ? `
|
|
62637
|
+
begin
|
|
62638
|
+
v_ip := ${ip}::inet;
|
|
62639
|
+
exception when invalid_text_representation then
|
|
62640
|
+
v_ip := null;
|
|
62641
|
+
end;
|
|
62642
|
+
perform set_config('better_supabase.transition_actor', ${customerActor(a)}::text, true);` : "" : `
|
|
62643
|
+
${transitionActorSql(a.actor, "QUOTE_ACTOR_INVALID")}`}${a.expires === "false" ? "" : `
|
|
62644
|
+
if (${a.expires}) and v_row.${q("validUntil")} < current_date then
|
|
61892
62645
|
update ${t("quotes")} x set ${q("status")} = ${sv("expired")}, ${q("updatedAt")} = now() where x.${q("id")} = v_row.${q("id")}
|
|
61893
62646
|
returning * into v_row;
|
|
61894
62647
|
${record("quote.expired", "v_row")}
|
|
61895
62648
|
return jsonb_build_object('status', 'expired');
|
|
61896
|
-
end if;`
|
|
62649
|
+
end if;`}${a.customer ? `
|
|
61897
62650
|
if nullif(trim(${a.by}), '') is null then
|
|
61898
62651
|
${fail$1("QUOTE_NAME_REQUIRED", "say who answers", "23502")}
|
|
61899
62652
|
end if;` : ""}
|
|
61900
|
-
if ${a.name}.decision = 'accepted' then${
|
|
62653
|
+
if ${a.name}.decision = 'accepted' then${restore}${a.deposit && has("depositRequired") && has("depositDue") ? `
|
|
62654
|
+
if v_row.${q("depositRequired")} and v_row.${q("depositDue")} > 0 then
|
|
62655
|
+
${fail$1("QUOTE_DEPOSIT_REQUIRED", "pay the deposit before accepting; the app records the acceptance once it is paid", "55000")}
|
|
62656
|
+
end if;` : ""}${selection(a.name)}
|
|
61901
62657
|
${ctx.hook("before_quote_accept", [["uuid", `v_row.${q("id")}`]])}
|
|
61902
62658
|
end if;
|
|
61903
62659
|
update ${t("quotes")} x set ${q("status")} = ${ctx.cast("quotes", "status", `${a.name}.decision`)}, ${q("decidedAt")} = now(), ${q("decidedBy")} = nullif(trim(${a.by}), ''),
|
|
61904
|
-
${has("decisionNote") ? `${q("decisionNote")} = nullif(trim(${a.name}.note), ''), ` : ""}${client("decidedUser", "auth.uid()")}${client("decidedIp", a.customer ?
|
|
62660
|
+
${has("decisionNote") ? `${q("decisionNote")} = nullif(trim(${a.name}.note), ''), ` : ""}${client("decidedUser", a.actor === void 0 ? "auth.uid()" : `coalesce(nullif(${a.actor} ->> 'id', '')::uuid, auth.uid())`)}${client("decidedIp", a.customer || a.actor !== void 0 ? actorIp(a) : "null")}${client("decidedUserAgent", a.customer || a.actor !== void 0 ? actorAgent(a) : "null")}${k.workingCopy ? `${q("unpublishedChanges")} = case when ${a.name}.decision = 'accepted' then false else x.${q("unpublishedChanges")} end, ` : ""}${q("updatedAt")} = now()
|
|
61905
62661
|
where x.${q("id")} = v_row.${q("id")}
|
|
61906
62662
|
returning * into v_row;
|
|
61907
62663
|
case ${a.name}.decision
|
|
@@ -61916,13 +62672,23 @@ function quoteDecisions(ctx, n, k) {
|
|
|
61916
62672
|
${ctx.hook("after_quote_accept", [["uuid", `v_row.${q("id")}`]])}
|
|
61917
62673
|
end if;`;
|
|
61918
62674
|
const answered = `jsonb_build_object('status', ${ctx.label("quotes", "status", `v_row.${q("status")}`)}, 'identifier', v_row.${q("identifier")}, 'revision', v_row.${q("revision")})`;
|
|
62675
|
+
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")};
|
|
62676
|
+
if v_snap is null then
|
|
62677
|
+
return ${k.publicJson("v_row")};
|
|
62678
|
+
end if;
|
|
62679
|
+
v_pub := ${snapshotRecord(PUBLISHED.filter(has))};
|
|
62680
|
+
return ${k.publicJson("v_pub", "v_snap")} || jsonb_build_object('status', ${ctx.label("quotes", "status", `v_row.${q("status")}`)});` : `return ${k.publicJson("v_row")};`;
|
|
61919
62681
|
const readable = (alias) => `(${n.service} or ${ctx.scope.can(`${alias}.${q("tenant")}`, n.read)})`;
|
|
61920
62682
|
return `
|
|
61921
62683
|
-- Records the customer's answer taken another way (by phone, by email):
|
|
61922
62684
|
-- decision is accepted, rejected or changes_requested; by is their name.
|
|
61923
|
-
-- selected lists the positions of the optional lines they took.
|
|
62685
|
+
-- selected lists the positions of the optional lines they took. actor is
|
|
62686
|
+
-- the customer when the app takes the answer in its own portal: id, name,
|
|
62687
|
+
-- email, ip and userAgent, kept with the answer and in the state machine's
|
|
62688
|
+
-- history; a quote past its valid date then expires instead.
|
|
61924
62689
|
drop function if exists ${fn("decide_quote")}(uuid, text, text, text);
|
|
61925
|
-
|
|
62690
|
+
drop function if exists ${fn("decide_quote")}(uuid, text, text, text, jsonb);
|
|
62691
|
+
create or replace function ${fn("decide_quote")}(quote uuid, decision text, note text, by text, selected jsonb default null, actor jsonb default null)
|
|
61926
62692
|
returns jsonb
|
|
61927
62693
|
language plpgsql
|
|
61928
62694
|
security definer
|
|
@@ -61930,21 +62696,23 @@ set search_path = ''
|
|
|
61930
62696
|
as $$
|
|
61931
62697
|
declare
|
|
61932
62698
|
v_row ${t("quotes")};
|
|
61933
|
-
v_claims text
|
|
62699
|
+
v_claims text;${restoreVars}
|
|
61934
62700
|
begin
|
|
61935
62701
|
select * into v_row from ${t("quotes")} x where x.${q("id")} = decide_quote.quote and ${editable("x")} for update;
|
|
61936
62702
|
if v_row.${q("id")} is null then
|
|
61937
62703
|
${fail$1("QUOTE_NOT_FOUND", "no such quote you can edit", "P0002")}
|
|
61938
62704
|
end if;${answer({
|
|
61939
62705
|
name: "decide_quote",
|
|
61940
|
-
by: "coalesce(nullif(trim(decide_quote.by), ''), auth.uid()::text)",
|
|
62706
|
+
by: "coalesce(nullif(trim(decide_quote.by), ''), nullif(trim(decide_quote.actor ->> 'name'), ''), decide_quote.actor ->> 'email', auth.uid()::text)",
|
|
61941
62707
|
customer: false,
|
|
61942
|
-
expires:
|
|
62708
|
+
expires: "decide_quote.actor is not null",
|
|
62709
|
+
actor: "decide_quote.actor",
|
|
62710
|
+
deposit: false
|
|
61943
62711
|
})}
|
|
61944
62712
|
return ${row("v_row")};
|
|
61945
62713
|
end;
|
|
61946
62714
|
$$;
|
|
61947
|
-
${userGrant(`${fn("decide_quote")}(uuid, text, text, text, jsonb)`)}
|
|
62715
|
+
${userGrant(`${fn("decide_quote")}(uuid, text, text, text, jsonb, jsonb)`)}
|
|
61948
62716
|
|
|
61949
62717
|
-- What the customer sees through the link: the quote without internal
|
|
61950
62718
|
-- notes. Opening a sent quote marks it viewed. Callable without signing in.
|
|
@@ -61955,14 +62723,14 @@ security definer
|
|
|
61955
62723
|
set search_path = ''
|
|
61956
62724
|
as $$
|
|
61957
62725
|
declare
|
|
61958
|
-
v_row ${t("quotes")}
|
|
62726
|
+
v_row ${t("quotes")};${restoreVars}
|
|
61959
62727
|
begin
|
|
61960
62728
|
select * into v_row from ${t("quotes")} x where x.${q("tokenHash")} = ${sha256Hex$1("public_quote.token")};
|
|
61961
62729
|
if v_row.${q("id")} is null then
|
|
61962
62730
|
${fail$1("QUOTE_LINK_INVALID", "this link is not valid", "P0002")}
|
|
61963
62731
|
end if;
|
|
61964
62732
|
${k.markViewed()}
|
|
61965
|
-
|
|
62733
|
+
${customerView}
|
|
61966
62734
|
end;
|
|
61967
62735
|
$$;
|
|
61968
62736
|
revoke all on function ${fn("public_quote")}(text) from public, anon, authenticated;
|
|
@@ -61981,7 +62749,7 @@ set search_path = ''
|
|
|
61981
62749
|
as $$
|
|
61982
62750
|
declare
|
|
61983
62751
|
v_row ${t("quotes")};${headers}
|
|
61984
|
-
v_claims text
|
|
62752
|
+
v_claims text;${restoreVars}
|
|
61985
62753
|
begin
|
|
61986
62754
|
select * into v_row from ${t("quotes")} x where x.${q("tokenHash")} = ${sha256Hex$1("respond_to_quote.token")} for update;
|
|
61987
62755
|
if v_row.${q("id")} is null then
|
|
@@ -61990,7 +62758,8 @@ begin
|
|
|
61990
62758
|
name: "respond_to_quote",
|
|
61991
62759
|
by: "respond_to_quote.name",
|
|
61992
62760
|
customer: true,
|
|
61993
|
-
expires: true
|
|
62761
|
+
expires: "true",
|
|
62762
|
+
deposit: true
|
|
61994
62763
|
})}
|
|
61995
62764
|
return ${answered};
|
|
61996
62765
|
end;
|
|
@@ -62000,7 +62769,8 @@ grant execute on function ${fn("respond_to_quote")}(text, text, text, text, json
|
|
|
62000
62769
|
|
|
62001
62770
|
-- A quote shared with the signed-in guest, as the customer sees it: through
|
|
62002
62771
|
-- a grant on the quote or as a guest of its company or contact. Opening a
|
|
62003
|
-
-- sent quote marks it viewed. No link token is needed.
|
|
62772
|
+
-- sent quote marks it viewed. No link token is needed. The service role
|
|
62773
|
+
-- reads it too, for an app's own portal.
|
|
62004
62774
|
create or replace function ${fn("portal_quote")}(quote uuid)
|
|
62005
62775
|
returns jsonb
|
|
62006
62776
|
language plpgsql
|
|
@@ -62008,14 +62778,14 @@ security definer
|
|
|
62008
62778
|
set search_path = ''
|
|
62009
62779
|
as $$
|
|
62010
62780
|
declare
|
|
62011
|
-
v_row ${t("quotes")}
|
|
62781
|
+
v_row ${t("quotes")};${restoreVars}
|
|
62012
62782
|
begin
|
|
62013
|
-
select * into v_row from ${t("quotes")} x where x.${q("id")} = portal_quote.quote and ${guest};
|
|
62783
|
+
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)}));
|
|
62014
62784
|
if v_row.${q("id")} is null then
|
|
62015
62785
|
${fail$1("QUOTE_NOT_FOUND", "no such quote shared with you", "P0002")}
|
|
62016
62786
|
end if;
|
|
62017
62787
|
${k.markViewed()}
|
|
62018
|
-
|
|
62788
|
+
${customerView}
|
|
62019
62789
|
end;
|
|
62020
62790
|
$$;
|
|
62021
62791
|
${userGrant(`${fn("portal_quote")}(uuid)`)}
|
|
@@ -62031,7 +62801,7 @@ set search_path = ''
|
|
|
62031
62801
|
as $$
|
|
62032
62802
|
declare
|
|
62033
62803
|
v_row ${t("quotes")};${headers}
|
|
62034
|
-
v_claims text
|
|
62804
|
+
v_claims text;${restoreVars}
|
|
62035
62805
|
begin
|
|
62036
62806
|
select * into v_row from ${t("quotes")} x where x.${q("id")} = respond_to_portal_quote.quote and ${guest} for update;
|
|
62037
62807
|
if v_row.${q("id")} is null then
|
|
@@ -62040,7 +62810,8 @@ begin
|
|
|
62040
62810
|
name: "respond_to_portal_quote",
|
|
62041
62811
|
by: "coalesce(nullif(trim(respond_to_portal_quote.name), ''), auth.jwt() ->> 'email')",
|
|
62042
62812
|
customer: true,
|
|
62043
|
-
expires: true
|
|
62813
|
+
expires: "true",
|
|
62814
|
+
deposit: true
|
|
62044
62815
|
})}
|
|
62045
62816
|
return ${answered};
|
|
62046
62817
|
end;
|
|
@@ -62088,7 +62859,8 @@ begin
|
|
|
62088
62859
|
if v_version.${v("id")} is null then
|
|
62089
62860
|
${fail$1("QUOTE_VERSION_NOT_FOUND", "this quote has no such version", "P0002")}
|
|
62090
62861
|
end if;
|
|
62091
|
-
return v_version.${v("snapshot")} || jsonb_build_object('revision', v_version.${v("revision")}, 'publishedAt', v_version.${v("publishedAt")}
|
|
62862
|
+
return v_version.${v("snapshot")} || jsonb_build_object('revision', v_version.${v("revision")}, 'publishedAt', v_version.${v("publishedAt")}${k.versionLines ? `,
|
|
62863
|
+
'lines', ${k.withVersionLineIds(`coalesce(v_version.${v("snapshot")} -> 'lines', '[]'::jsonb)`, `v_version.${v("id")}`)}` : ""});
|
|
62092
62864
|
end;
|
|
62093
62865
|
$$;
|
|
62094
62866
|
${userGrant(`${fn("quote_version")}(uuid, integer)`)}
|
|
@@ -62132,8 +62904,40 @@ function quoteFunctions(ctx, n) {
|
|
|
62132
62904
|
refuse(has("pricesIncludeTax"), `nullif(${attrs} ->> 'pricesIncludeTax', 'false')`, "PRICING", "prices_include_tax column"),
|
|
62133
62905
|
refuse(has("discountBps"), `nullif(${attrs} ->> 'discountBps', '0')`, "DISCOUNT", "discount column"),
|
|
62134
62906
|
refuse(has("discountAmount"), `nullif(${attrs} ->> 'discountAmount', '0')`, "DISCOUNT", "discount amount column"),
|
|
62135
|
-
refuse(has("depositBps"), `${attrs} ->> 'depositBps'`, "DEPOSIT", "deposit column")
|
|
62907
|
+
refuse(has("depositBps"), `${attrs} ->> 'depositBps'`, "DEPOSIT", "deposit column"),
|
|
62908
|
+
refuse(has("depositAmount"), `${attrs} ->> 'depositAmount'`, "DEPOSIT", "deposit amount column"),
|
|
62909
|
+
refuse(has("depositRequired"), `nullif(${attrs} ->> 'depositRequired', 'false')`, "DEPOSIT", "deposit required column")
|
|
62136
62910
|
].join("");
|
|
62911
|
+
const oneDeposit = has("depositBps") && has("depositAmount") ? `
|
|
62912
|
+
if v_row.${q("depositBps")} is not null and v_row.${q("depositAmount")} is not null then
|
|
62913
|
+
${fail$1("QUOTE_ATTRS_INVALID", "a deposit is a share (depositBps) or an amount (depositAmount), not both", "22023")}
|
|
62914
|
+
end if;` : "";
|
|
62915
|
+
const actor = (name) => `\n ${transitionActorSql(`${name}.actor`, "QUOTE_ACTOR_INVALID")}`;
|
|
62916
|
+
const publishedBy = `coalesce(auth.uid(), nullif(send_quote.actor ->> 'id', '')::uuid)`;
|
|
62917
|
+
const versionLinesCopy = (() => {
|
|
62918
|
+
if (!k.versionLines) return "";
|
|
62919
|
+
const vl = (column) => n.c("versionLines", column);
|
|
62920
|
+
const copied = [
|
|
62921
|
+
"position",
|
|
62922
|
+
"description",
|
|
62923
|
+
"quantity",
|
|
62924
|
+
"unitAmount",
|
|
62925
|
+
"periods",
|
|
62926
|
+
"discountBps",
|
|
62927
|
+
"taxRateBps",
|
|
62928
|
+
"taxCode",
|
|
62929
|
+
"section",
|
|
62930
|
+
"optional",
|
|
62931
|
+
"selected",
|
|
62932
|
+
"productType",
|
|
62933
|
+
"productId"
|
|
62934
|
+
].filter((column) => declared(ctx, "versionLines", column) && declared(ctx, "lines", column));
|
|
62935
|
+
const value = (column) => column === "productType" ? ctx.cast("versionLines", column, `ql.${l(column)}::text`) : `ql.${l(column)}`;
|
|
62936
|
+
return `
|
|
62937
|
+
insert into ${t("versionLines")} (${vl("tenant")}, ${vl("version")}, ${copied.map(vl).join(", ")})
|
|
62938
|
+
select v_row.${q("tenant")}, v_version, ${copied.map(value).join(", ")}
|
|
62939
|
+
from ${t("lines")} ql where ql.${l("parent")} = v_row.${q("id")};`;
|
|
62940
|
+
})();
|
|
62137
62941
|
const deals = ctx.installed("deals") ? ctx.of("deals") : void 0;
|
|
62138
62942
|
const fromDeal = deals === void 0 ? "" : (() => {
|
|
62139
62943
|
const d = (column) => deals.col("deals", column);
|
|
@@ -62191,8 +62995,9 @@ ${userGrant(`${fn("quote_from_deal")}(uuid)`)}
|
|
|
62191
62995
|
-- Creates a draft quote. attrs: title (required), currency, company and
|
|
62192
62996
|
-- contact ({ type, id }), ownerId, validUntil, terms, note, origin ({ type,
|
|
62193
62997
|
-- id }, the record it was made from), pricesIncludeTax, discountBps,
|
|
62194
|
-
-- discountAmount (minor units as text)
|
|
62195
|
-
--
|
|
62998
|
+
-- discountAmount (minor units as text), depositBps, or depositAmount (minor
|
|
62999
|
+
-- units as text) for a fixed deposit, and depositRequired, which makes the
|
|
63000
|
+
-- customer pay it before they accept. lines: see set_quote_lines.
|
|
62196
63001
|
create or replace function ${fn("create_quote")}(tenant ${ctx.idType}, attrs jsonb, lines jsonb)
|
|
62197
63002
|
returns jsonb
|
|
62198
63003
|
language plpgsql
|
|
@@ -62225,7 +63030,7 @@ begin
|
|
|
62225
63030
|
})}
|
|
62226
63031
|
begin
|
|
62227
63032
|
insert into ${t("quotes")} (${q("tenant")}, ${q("number")}, ${q("identifier")}, ${q("title")}${also("companyType")}${also("companyId")}${also("contactType")}${also("contactId")},
|
|
62228
|
-
${q("owner")}, ${q("currency")}, ${q("validUntil")}${also("terms")}${also("note")}${also("originType")}${also("originId")}${also("pricesIncludeTax")}${also("discountBps")}${also("discountAmount")}${also("depositBps")}${also("createdBy")}${insertExtraColumns(t("quotes"), n.extras, "coalesce(create_quote.attrs -> 'fields', '{}'::jsonb)").columns})
|
|
63033
|
+
${q("owner")}, ${q("currency")}, ${q("validUntil")}${also("terms")}${also("note")}${also("originType")}${also("originId")}${also("pricesIncludeTax")}${also("discountBps")}${also("discountAmount")}${also("depositBps")}${also("depositAmount")}${also("depositRequired")}${also("createdBy")}${insertExtraColumns(t("quotes"), n.extras, "coalesce(create_quote.attrs -> 'fields', '{}'::jsonb)").columns})
|
|
62229
63034
|
values (${valueLines(" ", [
|
|
62230
63035
|
"create_quote.tenant",
|
|
62231
63036
|
"v_seq",
|
|
@@ -62236,12 +63041,14 @@ begin
|
|
|
62236
63041
|
present("discountBps", "coalesce((create_quote.attrs ->> 'discountBps')::integer, 0)"),
|
|
62237
63042
|
present("discountAmount", "coalesce((create_quote.attrs ->> 'discountAmount')::bigint, 0)"),
|
|
62238
63043
|
present("depositBps", "(create_quote.attrs ->> 'depositBps')::integer"),
|
|
63044
|
+
present("depositAmount", "(create_quote.attrs ->> 'depositAmount')::bigint"),
|
|
63045
|
+
present("depositRequired", "coalesce((create_quote.attrs ->> 'depositRequired')::boolean, false)"),
|
|
62239
63046
|
present("createdBy", "auth.uid()")
|
|
62240
63047
|
])}${insertExtraColumns(t("quotes"), n.extras, "coalesce(create_quote.attrs -> 'fields', '{}'::jsonb)").values})
|
|
62241
63048
|
returning * into v_row;
|
|
62242
63049
|
exception when check_violation or invalid_text_representation or datetime_field_overflow or numeric_value_out_of_range then
|
|
62243
63050
|
${fail$1("QUOTE_ATTRS_INVALID", "a quote field has an invalid value", "22023")}
|
|
62244
|
-
end
|
|
63051
|
+
end;${oneDeposit}
|
|
62245
63052
|
if create_quote.lines is not null then
|
|
62246
63053
|
perform ${fn("set_quote_lines")}(v_row.${q("id")}, create_quote.lines);
|
|
62247
63054
|
end if;${origin ? `
|
|
@@ -62262,8 +63069,8 @@ ${userGrant(`${fn("create_quote")}(${ctx.idType}, jsonb, jsonb)`)}
|
|
|
62262
63069
|
|
|
62263
63070
|
-- Changes a draft quote, or one the customer asked changes on: title,
|
|
62264
63071
|
-- company, contact, currency, ownerId, validUntil, terms, note,
|
|
62265
|
-
-- pricesIncludeTax, discountBps, discountAmount
|
|
62266
|
-
-- follow the new pricing.
|
|
63072
|
+
-- pricesIncludeTax, discountBps, discountAmount, depositBps, depositAmount
|
|
63073
|
+
-- and depositRequired. The totals follow the new pricing.${k.workingCopy ? "\n-- A sent quote changes too; the customer sees it once it is sent again." : ""}
|
|
62267
63074
|
create or replace function ${fn("update_quote")}(quote uuid, attrs jsonb)
|
|
62268
63075
|
returns jsonb
|
|
62269
63076
|
language plpgsql
|
|
@@ -62285,14 +63092,14 @@ begin
|
|
|
62285
63092
|
${q("title")} = coalesce(nullif(trim(update_quote.attrs ->> 'title'), ''), x.${q("title")}),
|
|
62286
63093
|
${q("currency")} = coalesce(upper(update_quote.attrs ->> 'currency'), x.${q("currency")}),
|
|
62287
63094
|
${q("owner")} = case when update_quote.attrs ? 'ownerId' then (update_quote.attrs ->> 'ownerId')::uuid else x.${q("owner")} end,
|
|
62288
|
-
${q("validUntil")} = case when update_quote.attrs ? 'validUntil' then (update_quote.attrs ->> 'validUntil')::date else x.${q("validUntil")} end,${assign("terms", (col) => `case when update_quote.attrs ? 'terms' then update_quote.attrs ->> 'terms' else x.${col} end`)}${assign("note", (col) => `case when update_quote.attrs ? 'note' then update_quote.attrs ->> 'note' else x.${col} end`)}${assign("pricesIncludeTax", (col) => `case when update_quote.attrs ? 'pricesIncludeTax' then coalesce((update_quote.attrs ->> 'pricesIncludeTax')::boolean, false) else x.${col} end`)}${assign("discountBps", (col) => `case when update_quote.attrs ? 'discountBps' then coalesce((update_quote.attrs ->> 'discountBps')::integer, 0) else x.${col} end`)}${assign("discountAmount", (col) => `case when update_quote.attrs ? 'discountAmount' then coalesce((update_quote.attrs ->> 'discountAmount')::bigint, 0) else x.${col} end`)}${assign("depositBps", (col) => `case when update_quote.attrs ? 'depositBps' then (update_quote.attrs ->> 'depositBps')::integer else x.${col} end`)}${company ? assign("companyType", (col) => `case when update_quote.attrs ? 'company' then case when update_quote.attrs -> 'company' ->> 'id' is null then null else coalesce(update_quote.attrs -> 'company' ->> 'type', ${sqlString(n.company)}) end else x.${col} end`) + assign("companyId", (col) => `case when update_quote.attrs ? 'company' then update_quote.attrs -> 'company' ->> 'id' else x.${col} end`) : ""}${contact ? assign("contactType", (col) => `case when update_quote.attrs ? 'contact' then case when update_quote.attrs -> 'contact' ->> 'id' is null then null else coalesce(update_quote.attrs -> 'contact' ->> 'type', ${sqlString(n.contact)}) end else x.${col} end`) + assign("contactId", (col) => `case when update_quote.attrs ? 'contact' then update_quote.attrs -> 'contact' ->> 'id' else x.${col} end`) : ""}
|
|
63095
|
+
${q("validUntil")} = case when update_quote.attrs ? 'validUntil' then (update_quote.attrs ->> 'validUntil')::date else x.${q("validUntil")} end,${assign("terms", (col) => `case when update_quote.attrs ? 'terms' then update_quote.attrs ->> 'terms' else x.${col} end`)}${assign("note", (col) => `case when update_quote.attrs ? 'note' then update_quote.attrs ->> 'note' else x.${col} end`)}${assign("pricesIncludeTax", (col) => `case when update_quote.attrs ? 'pricesIncludeTax' then coalesce((update_quote.attrs ->> 'pricesIncludeTax')::boolean, false) else x.${col} end`)}${assign("discountBps", (col) => `case when update_quote.attrs ? 'discountBps' then coalesce((update_quote.attrs ->> 'discountBps')::integer, 0) else x.${col} end`)}${assign("discountAmount", (col) => `case when update_quote.attrs ? 'discountAmount' then coalesce((update_quote.attrs ->> 'discountAmount')::bigint, 0) else x.${col} end`)}${assign("depositBps", (col) => `case when update_quote.attrs ? 'depositBps' then (update_quote.attrs ->> 'depositBps')::integer else x.${col} end`)}${assign("depositAmount", (col) => `case when update_quote.attrs ? 'depositAmount' then (update_quote.attrs ->> 'depositAmount')::bigint else x.${col} end`)}${assign("depositRequired", (col) => `case when update_quote.attrs ? 'depositRequired' then coalesce((update_quote.attrs ->> 'depositRequired')::boolean, false) else x.${col} end`)}${k.workingCopy ? assign("unpublishedChanges", () => "true") : ""}${company ? assign("companyType", (col) => `case when update_quote.attrs ? 'company' then case when update_quote.attrs -> 'company' ->> 'id' is null then null else coalesce(update_quote.attrs -> 'company' ->> 'type', ${sqlString(n.company)}) end else x.${col} end`) + assign("companyId", (col) => `case when update_quote.attrs ? 'company' then update_quote.attrs -> 'company' ->> 'id' else x.${col} end`) : ""}${contact ? assign("contactType", (col) => `case when update_quote.attrs ? 'contact' then case when update_quote.attrs -> 'contact' ->> 'id' is null then null else coalesce(update_quote.attrs -> 'contact' ->> 'type', ${sqlString(n.contact)}) end else x.${col} end`) + assign("contactId", (col) => `case when update_quote.attrs ? 'contact' then update_quote.attrs -> 'contact' ->> 'id' else x.${col} end`) : ""}
|
|
62289
63096
|
${q("updatedAt")} = now()
|
|
62290
63097
|
where x.${q("id")} = v_row.${q("id")}
|
|
62291
63098
|
returning * into v_row;${n.extras.length === 0 ? "" : `${writeExtraColumns(t("quotes"), n.extras, "(update_quote.attrs -> 'fields')", `x.${q("id")} = v_row.${q("id")}`)}
|
|
62292
63099
|
select * into v_row from ${t("quotes")} x where x.${q("id")} = v_row.${q("id")};`}
|
|
62293
63100
|
exception when check_violation or invalid_text_representation or datetime_field_overflow or numeric_value_out_of_range then
|
|
62294
63101
|
${fail$1("QUOTE_ATTRS_INVALID", "a quote field has an invalid value", "22023")}
|
|
62295
|
-
end
|
|
63102
|
+
end;${oneDeposit}
|
|
62296
63103
|
perform ${fn("set_quote_lines_recount")}(v_row.${q("id")});
|
|
62297
63104
|
select * into v_row from ${t("quotes")} x where x.${q("id")} = v_row.${q("id")};
|
|
62298
63105
|
${record("quote.updated", "v_row")}
|
|
@@ -62311,15 +63118,19 @@ ${lineItemsSql(ctx, {
|
|
|
62311
63118
|
setter: "set_quote_lines",
|
|
62312
63119
|
guard: `if not exists (select 1 from ${t("quotes")} x where x.${q("id")} = v_parent and ${editable("x")}) then
|
|
62313
63120
|
${fail$1("QUOTE_NOT_FOUND", "no such quote you can edit", "P0002")}
|
|
62314
|
-
end if
|
|
62315
|
-
|
|
63121
|
+
end if;${k.workingCopy ? `
|
|
63122
|
+
update ${t("quotes")} x set ${q("unpublishedChanges")} = true where x.${q("id")} = v_parent;` : ""}`,
|
|
63123
|
+
...catalogPrice ? { fallback: catalogPrice } : {},
|
|
63124
|
+
...k.workingCopy ? { restorer: "quote_lines_restore" } : {}
|
|
62316
63125
|
})}
|
|
62317
63126
|
-- Sends a quote: it gets a public link the customer opens and a published
|
|
62318
63127
|
-- version, a snapshot that never changes. The quote can't change until it is
|
|
62319
63128
|
-- revised or the customer asks for changes; sending it again then publishes
|
|
62320
63129
|
-- the next revision. Returns the quote with the link's token, which is stored
|
|
62321
|
-
-- only as a hash and returned this once.
|
|
62322
|
-
|
|
63130
|
+
-- only as a hash and returned this once.${k.workingCopy ? "\n-- A sent quote keeps its link: sending it again publishes the working copy\n-- as the next revision on the same link, without a new token." : ""}
|
|
63131
|
+
-- actor: who sent it, for the state machine's history.
|
|
63132
|
+
drop function if exists ${fn("send_quote")}(uuid);
|
|
63133
|
+
create or replace function ${fn("send_quote")}(quote uuid, actor jsonb default null)
|
|
62323
63134
|
returns jsonb
|
|
62324
63135
|
language plpgsql
|
|
62325
63136
|
security definer
|
|
@@ -62328,6 +63139,7 @@ as $$
|
|
|
62328
63139
|
declare
|
|
62329
63140
|
v_row ${t("quotes")};
|
|
62330
63141
|
v_token text := encode(extensions.gen_random_bytes(24), 'hex');
|
|
63142
|
+
v_version uuid;${k.workingCopy ? "\n v_linked boolean;" : ""}
|
|
62331
63143
|
begin
|
|
62332
63144
|
select * into v_row from ${t("quotes")} x where x.${q("id")} = send_quote.quote and ${editable("x")} for update;
|
|
62333
63145
|
if v_row.${q("id")} is null then
|
|
@@ -62338,27 +63150,29 @@ begin
|
|
|
62338
63150
|
end if;
|
|
62339
63151
|
if not exists (select 1 from ${t("lines")} x where x.${l("parent")} = v_row.${q("id")}) then
|
|
62340
63152
|
${fail$1("QUOTE_EMPTY", "a quote needs a line before it is sent", "23514")}
|
|
62341
|
-
end if
|
|
62342
|
-
${ctx.hook("before_quote_send", [["uuid", `v_row.${q("id")}`]])}
|
|
62343
|
-
update ${t("quotes")} x set ${q("status")} = ${sv("sent")}, ${q("sentAt")} = now(), ${q("tokenHash")} = ${sha256Hex$1("v_token")},
|
|
63153
|
+
end if;${actor("send_quote")}
|
|
63154
|
+
${ctx.hook("before_quote_send", [["uuid", `v_row.${q("id")}`]])}${k.workingCopy ? `\n v_linked := v_row.${q("tokenHash")} is not null;` : ""}
|
|
63155
|
+
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")},
|
|
62344
63156
|
${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,
|
|
62345
|
-
${decisionReset}${q("updatedAt")} = now()
|
|
63157
|
+
${decisionReset}${k.workingCopy ? `${q("unpublishedChanges")} = false, ` : ""}${q("updatedAt")} = now()
|
|
62346
63158
|
where x.${q("id")} = v_row.${q("id")}
|
|
62347
63159
|
returning * into v_row;
|
|
62348
63160
|
insert into ${t("versions")} (${v("tenant")}, ${v("quote")}, ${v("revision")}, ${v("snapshot")}, ${v("total")}, ${v("currency")}${ctx.has("versions", "publishedBy") ? `, ${v("publishedBy")}` : ""})
|
|
62349
|
-
values (v_row.${q("tenant")}, v_row.${q("id")}, v_row.${q("revision")}, ${row("v_row")}, v_row.${q("total")}, v_row.${q("currency")}${ctx.has("versions", "publishedBy") ?
|
|
63161
|
+
values (v_row.${q("tenant")}, v_row.${q("id")}, v_row.${q("revision")}, ${row("v_row")}, v_row.${q("total")}, v_row.${q("currency")}${ctx.has("versions", "publishedBy") ? `, ${publishedBy}` : ""})
|
|
63162
|
+
returning ${v("id")} into v_version;${versionLinesCopy}
|
|
62350
63163
|
${record("quote.sent", "v_row", `, 'revision', v_row.${q("revision")}`)}
|
|
62351
63164
|
${ctx.hook("after_quote_send", [["uuid", `v_row.${q("id")}`]])}
|
|
62352
|
-
return ${row("v_row")} || jsonb_build_object('token', v_token);
|
|
63165
|
+
return ${row("v_row")} || jsonb_build_object('token', ${k.workingCopy ? "case when v_linked then null else v_token end" : "v_token"});
|
|
62353
63166
|
end;
|
|
62354
63167
|
$$;
|
|
62355
|
-
${userGrant(`${fn("send_quote")}(uuid)`)}
|
|
63168
|
+
${userGrant(`${fn("send_quote")}(uuid, jsonb)`)}
|
|
62356
63169
|
|
|
62357
63170
|
-- Opens a sent or declined quote again as a draft of its next revision: the
|
|
62358
63171
|
-- same quote, number and lines, a fresh valid-until date, and its link ends.
|
|
62359
63172
|
-- The versions already published stay as they were. An accepted quote is
|
|
62360
|
-
-- kept as the customer accepted it; start a new quote instead.
|
|
62361
|
-
|
|
63173
|
+
-- kept as the customer accepted it; start a new quote instead.${k.workingCopy ? "\n-- With a working copy the link stays and so does a sent quote's status; a\n-- declined quote goes back to draft until it is sent again." : ""}
|
|
63174
|
+
drop function if exists ${fn("revise_quote")}(uuid);
|
|
63175
|
+
create or replace function ${fn("revise_quote")}(quote uuid, actor jsonb default null)
|
|
62362
63176
|
returns jsonb
|
|
62363
63177
|
language plpgsql
|
|
62364
63178
|
security definer
|
|
@@ -62376,17 +63190,50 @@ begin
|
|
|
62376
63190
|
end if;
|
|
62377
63191
|
if ${st(`v_row.${q("status")}`, ["accepted"])} then
|
|
62378
63192
|
${fail$1("QUOTE_ACCEPTED", "an accepted quote stays as accepted; start a new quote", "55000")}
|
|
62379
|
-
end if
|
|
62380
|
-
update ${t("quotes")} x set ${q("status")} =
|
|
63193
|
+
end if;${actor("revise_quote")}
|
|
63194
|
+
${k.workingCopy ? `update ${t("quotes")} x set ${q("status")} = case when ${st(`x.${q("status")}`, ["sent", "viewed"])} then x.${q("status")} else ${sv("draft")} end,
|
|
63195
|
+
${q("validUntil")} = greatest(x.${q("validUntil")}, current_date + ${String(n.validDays)}),
|
|
63196
|
+
${decisionReset}${q("updatedAt")} = now()` : `update ${t("quotes")} x set ${q("status")} = ${sv("draft")}, ${q("revision")} = x.${q("revision")} + 1, ${q("tokenHash")} = null, ${q("sentAt")} = null,${has("viewedAt") ? ` ${q("viewedAt")} = null,` : ""}
|
|
62381
63197
|
${q("validUntil")} = greatest(x.${q("validUntil")}, current_date + ${String(n.validDays)}),
|
|
62382
|
-
${decisionReset}${q("updatedAt")} = now()
|
|
63198
|
+
${decisionReset}${q("updatedAt")} = now()`}
|
|
62383
63199
|
where x.${q("id")} = v_row.${q("id")}
|
|
62384
63200
|
returning * into v_row;
|
|
62385
63201
|
${record("quote.revised", "v_row", `, 'revision', v_row.${q("revision")}`)}
|
|
62386
63202
|
return ${row("v_row")};
|
|
62387
63203
|
end;
|
|
62388
63204
|
$$;
|
|
62389
|
-
${userGrant(`${fn("revise_quote")}(uuid)`)}
|
|
63205
|
+
${userGrant(`${fn("revise_quote")}(uuid, jsonb)`)}
|
|
63206
|
+
|
|
63207
|
+
-- Takes back a sent quote the customer hasn't accepted: it can't be answered
|
|
63208
|
+
-- any more until it is revised and sent again.
|
|
63209
|
+
create or replace function ${fn("withdraw_quote")}(quote uuid, actor jsonb default null)
|
|
63210
|
+
returns jsonb
|
|
63211
|
+
language plpgsql
|
|
63212
|
+
security definer
|
|
63213
|
+
set search_path = ''
|
|
63214
|
+
as $$
|
|
63215
|
+
declare
|
|
63216
|
+
v_row ${t("quotes")};
|
|
63217
|
+
begin
|
|
63218
|
+
select * into v_row from ${t("quotes")} x where x.${q("id")} = withdraw_quote.quote and ${editable("x")} for update;
|
|
63219
|
+
if v_row.${q("id")} is null then
|
|
63220
|
+
${fail$1("QUOTE_NOT_FOUND", "no such quote you can edit", "P0002")}
|
|
63221
|
+
end if;
|
|
63222
|
+
if ${st(`v_row.${q("status")}`, [
|
|
63223
|
+
"sent",
|
|
63224
|
+
"viewed",
|
|
63225
|
+
"changes_requested"
|
|
63226
|
+
], true)} then
|
|
63227
|
+
${fail$1("QUOTE_NOT_OPEN", "only a sent quote that wasn't answered is withdrawn", "55000")}
|
|
63228
|
+
end if;${actor("withdraw_quote")}
|
|
63229
|
+
update ${t("quotes")} x set ${q("status")} = ${sv("withdrawn")}, ${q("updatedAt")} = now()
|
|
63230
|
+
where x.${q("id")} = v_row.${q("id")}
|
|
63231
|
+
returning * into v_row;
|
|
63232
|
+
${record("quote.withdrawn", "v_row", `, 'revision', v_row.${q("revision")}`)}
|
|
63233
|
+
return ${row("v_row")};
|
|
63234
|
+
end;
|
|
63235
|
+
$$;
|
|
63236
|
+
${userGrant(`${fn("withdraw_quote")}(uuid, jsonb)`)}
|
|
62390
63237
|
${quoteDecisions(ctx, n, k)}
|
|
62391
63238
|
-- Expires sent quotes past their valid date. Run it daily from a job.
|
|
62392
63239
|
create or replace function ${fn("expire_quotes")}()
|
|
@@ -65837,6 +66684,23 @@ const EXPENSE_TABLE = {
|
|
|
65837
66684
|
],
|
|
65838
66685
|
typed: ["status"]
|
|
65839
66686
|
};
|
|
66687
|
+
/** The subject type of an expense the approvals block decides. */
|
|
66688
|
+
const EXPENSE_SUBJECT = "expense";
|
|
66689
|
+
/**
|
|
66690
|
+
* Whether each standalone expense goes through the approvals block:
|
|
66691
|
+
* `options.standaloneApprovals`, which needs `tables.reports: null`.
|
|
66692
|
+
*/
|
|
66693
|
+
function standaloneApprovals(ctx) {
|
|
66694
|
+
const on = ctx.flag("standaloneApprovals", false);
|
|
66695
|
+
if (on && !expensesStandalone(ctx)) throw new TypeError("blocks.expenses.options.standaloneApprovals needs tables.reports: null; reports go through approvals already");
|
|
66696
|
+
return on;
|
|
66697
|
+
}
|
|
66698
|
+
/** `options.policy`, or one step for holders of the approve permission. */
|
|
66699
|
+
function standalonePolicy(ctx) {
|
|
66700
|
+
const policy = policyOf(EXPENSE_SUBJECT, "approve", ctx.option("policy") ?? { steps: [{ approvers: { permission: ctx.permissionKey("approve", OPERATIONS["expenses.approve"]) } }] }, "blocks.expenses.options.policy");
|
|
66701
|
+
if (policy.run !== void 0) throw new TypeError("blocks.expenses.options.policy.run is not allowed; the final approval approves the expense");
|
|
66702
|
+
return policySnapshot(policy);
|
|
66703
|
+
}
|
|
65840
66704
|
function expensesStandalone(ctx) {
|
|
65841
66705
|
const reports = ctx.config.tables["reports"] === null;
|
|
65842
66706
|
if (reports !== (ctx.config.tables["lines"] === null)) throw new TypeError("blocks.expenses.tables.reports and lines map to null together: without reports, each expense is one row of tables.expenses");
|
|
@@ -65921,7 +66785,8 @@ function standaloneContract(ctx) {
|
|
|
65921
66785
|
args: [
|
|
65922
66786
|
"uuid",
|
|
65923
66787
|
"boolean",
|
|
65924
|
-
"text"
|
|
66788
|
+
"text",
|
|
66789
|
+
"uuid"
|
|
65925
66790
|
],
|
|
65926
66791
|
returns: "jsonb"
|
|
65927
66792
|
},
|
|
@@ -65980,6 +66845,21 @@ function expenseStandaloneSql(ctx) {
|
|
|
65980
66845
|
const extra = extraFieldsArg(extras);
|
|
65981
66846
|
const statusColumn = has("status");
|
|
65982
66847
|
const company = ctx.flag("companyExpenses", false);
|
|
66848
|
+
const linked = standaloneApprovals(ctx) ? ctx.of("approvals") : void 0;
|
|
66849
|
+
if (linked?.mode === "custom") throw new TypeError("blocks.expenses needs the approvals tables; approvals can't be in custom mode");
|
|
66850
|
+
const ar = linked?.table("requests") ?? "";
|
|
66851
|
+
const a = (column) => linked?.col("requests", column) ?? "";
|
|
66852
|
+
const pending = `exists (select 1 from ${ar} x where x.${a("subjectType")} = ${sqlString(EXPENSE_SUBJECT)} and x.${a("subjectId")} = v_row.${e("id")}::text and x.${a("status")} = 'pending')`;
|
|
66853
|
+
const openApproval = linked === void 0 ? "" : `
|
|
66854
|
+
perform ${linked.fn("open_approval")}(
|
|
66855
|
+
v_row.${e("tenant")}, ${sqlString(EXPENSE_SUBJECT)}, v_row.${e("id")}::text, 'approve',
|
|
66856
|
+
${sqlString(standalonePolicy(ctx))}::jsonb${employee ? ` || jsonb_build_object('managerOf', v_row.${e("employee")}::text)` : ""}, null,
|
|
66857
|
+
jsonb_build_object('userId', ${owner.requester("v_row")}${employee ? `, 'employeeId', v_row.${e("employee")}` : ""}, 'amount', v_row.${e("amount")}::text, 'currency', v_row.${e("currency")}, 'spentOn', v_row.${e("spentOn")}),
|
|
66858
|
+
${owner.requester("v_row")}
|
|
66859
|
+
);`;
|
|
66860
|
+
const cancelApproval = linked === void 0 ? "" : `
|
|
66861
|
+
update ${ar} x set ${a("status")} = 'cancelled'${linked.has("requests", "decidedAt") ? `, ${a("decidedAt")} = now()` : ""}
|
|
66862
|
+
where x.${a("subjectType")} = ${sqlString(EXPENSE_SUBJECT)} and x.${a("subjectId")} = v_row.${e("id")}::text and x.${a("status")} = 'pending';`;
|
|
65983
66863
|
const inserted = insertExtraColumns(table, extras, "coalesce(create_expense.fields, '{}'::jsonb)");
|
|
65984
66864
|
if (!statusColumn && !(has("approvedAt") && has("rejectedAt"))) throw new TypeError("blocks.expenses.columns.expenses needs a status column, or approvedAt and rejectedAt columns, to keep an expense's state");
|
|
65985
66865
|
const forbidden = (message) => fail$1("EXPENSES_FORBIDDEN", message);
|
|
@@ -66168,7 +67048,7 @@ declare
|
|
|
66168
67048
|
begin${load("submit_expense.expense_id")}${ownerOrManager(updateOthers)}${editable}
|
|
66169
67049
|
update ${table} x set ${e("submittedAt")} = now()${setStatus("submitted")}${set("rejectedAt", "null")}${set("approvedAt", "null")}, ${e("updatedAt")} = now()
|
|
66170
67050
|
where x.${e("id")} = v_row.${e("id")}
|
|
66171
|
-
returning * into v_row
|
|
67051
|
+
returning * into v_row;${openApproval}
|
|
66172
67052
|
${record("expense.submitted", "submitted an expense")}
|
|
66173
67053
|
return ${json("v_row")};
|
|
66174
67054
|
end;
|
|
@@ -66189,7 +67069,7 @@ begin${load("withdraw_expense.expense_id")}${ownerOrManager(withdrawApproved ? w
|
|
|
66189
67069
|
end if;
|
|
66190
67070
|
update ${table} x set ${e("submittedAt")} = null${setStatus("draft")}${withdrawApproved ? `${set("approvedAt", "null")}${set("decidedBy", "null")}${set("decidedAt", "null")}` : ""}, ${e("updatedAt")} = now()
|
|
66191
67071
|
where x.${e("id")} = v_row.${e("id")}
|
|
66192
|
-
returning * into v_row
|
|
67072
|
+
returning * into v_row;${cancelApproval}
|
|
66193
67073
|
${record("expense.withdrawn", "withdrew an expense")}
|
|
66194
67074
|
return ${json("v_row")};
|
|
66195
67075
|
end;
|
|
@@ -66214,6 +67094,7 @@ begin${load("delete_expense.expense_id")}${deleteSubmitted === void 0 ? ownerOrM
|
|
|
66214
67094
|
if ${status("v_row")} <> 'draft'${deleteSubmitted === void 0 ? "" : ` and ${status("v_row")} not in ('submitted', 'approved')`} then
|
|
66215
67095
|
${fail$1("EXPENSE_LOCKED", deleteSubmitted === void 0 ? "only a draft expense is deleted" : "only a draft, submitted or approved expense is deleted", "55000")}
|
|
66216
67096
|
end if;
|
|
67097
|
+
${cancelApproval}
|
|
66217
67098
|
delete from ${table} x where x.${e("id")} = v_row.${e("id")};
|
|
66218
67099
|
${record("expense.deleted", "deleted an expense")}
|
|
66219
67100
|
return true;
|
|
@@ -66221,7 +67102,9 @@ end;
|
|
|
66221
67102
|
$$;
|
|
66222
67103
|
${userGrant(`${fn("delete_expense")}(uuid)`)}
|
|
66223
67104
|
|
|
66224
|
-
|
|
67105
|
+
-- The service role names the user it decides for in decided_by.
|
|
67106
|
+
drop function if exists ${fn("decide_expense")}(uuid, boolean, text);
|
|
67107
|
+
create or replace function ${fn("decide_expense")}(expense_id uuid, approved boolean, note text default null, decided_by uuid default null)
|
|
66225
67108
|
returns jsonb
|
|
66226
67109
|
language plpgsql
|
|
66227
67110
|
security definer
|
|
@@ -66233,19 +67116,26 @@ begin${load("decide_expense.expense_id")}
|
|
|
66233
67116
|
if not (${SERVICE_CALLER$1} or (${ctx.can("tenant", `v_row.${e("tenant")}`, approve)} and ${owner.requester("v_row")} is distinct from auth.uid())) then
|
|
66234
67117
|
${forbidden("not allowed to decide this expense")}
|
|
66235
67118
|
end if;
|
|
67119
|
+
if decide_expense.decided_by is not null and (not ${SERVICE_CALLER$1} and decide_expense.decided_by is distinct from auth.uid()
|
|
67120
|
+
or decide_expense.decided_by = ${owner.requester("v_row")}) then
|
|
67121
|
+
${forbidden("only the service role decides for another user, never for the owner")}
|
|
67122
|
+
end if;
|
|
66236
67123
|
if ${status("v_row")} <> 'submitted' then
|
|
66237
67124
|
${fail$1("EXPENSE_LOCKED", "only a submitted expense is decided", "55000")}
|
|
66238
|
-
end if
|
|
67125
|
+
end if;${linked === void 0 ? "" : `
|
|
67126
|
+
if ${pending} then
|
|
67127
|
+
${fail$1("EXPENSE_IN_APPROVAL", "this expense is decided through its approval request", "55000")}
|
|
67128
|
+
end if;`}
|
|
66239
67129
|
if decide_expense.approved is null then
|
|
66240
67130
|
${invalid("approved must be true or false")}
|
|
66241
67131
|
end if;${unsupported("decisionNote", "nullif(trim(decide_expense.note), '')")}
|
|
66242
67132
|
if decide_expense.approved then
|
|
66243
|
-
update ${table} x set ${e("updatedAt")} = now()${setStatus("approved")}${set("approvedAt", "now()")}${set("decidedBy", "auth.uid()")}${set("decidedAt", "now()")}${set("decisionNote", "nullif(trim(decide_expense.note), '')")}
|
|
67133
|
+
update ${table} x set ${e("updatedAt")} = now()${setStatus("approved")}${set("approvedAt", "now()")}${set("decidedBy", "coalesce(decide_expense.decided_by, auth.uid())")}${set("decidedAt", "now()")}${set("decisionNote", "nullif(trim(decide_expense.note), '')")}
|
|
66244
67134
|
where x.${e("id")} = v_row.${e("id")}
|
|
66245
67135
|
returning * into v_row;
|
|
66246
67136
|
${record("expense.approved", "approved an expense")}
|
|
66247
67137
|
else
|
|
66248
|
-
update ${table} x set ${e("updatedAt")} = now()${setStatus("rejected")}${set("rejectedAt", "now()")}${set("decidedBy", "auth.uid()")}${set("decidedAt", "now()")}${set("decisionNote", "nullif(trim(decide_expense.note), '')")}
|
|
67138
|
+
update ${table} x set ${e("updatedAt")} = now()${setStatus("rejected")}${set("rejectedAt", "now()")}${set("decidedBy", "coalesce(decide_expense.decided_by, auth.uid())")}${set("decidedAt", "now()")}${set("decisionNote", "nullif(trim(decide_expense.note), '')")}
|
|
66249
67139
|
where x.${e("id")} = v_row.${e("id")}
|
|
66250
67140
|
returning * into v_row;
|
|
66251
67141
|
${record("expense.rejected", "rejected an expense")}
|
|
@@ -66253,8 +67143,38 @@ begin${load("decide_expense.expense_id")}
|
|
|
66253
67143
|
return ${json("v_row")};
|
|
66254
67144
|
end;
|
|
66255
67145
|
$$;
|
|
66256
|
-
${userGrant(`${fn("decide_expense")}(uuid, boolean, text)`)}
|
|
66257
|
-
|
|
67146
|
+
${userGrant(`${fn("decide_expense")}(uuid, boolean, text, uuid)`)}
|
|
67147
|
+
${linked === void 0 ? "" : `
|
|
67148
|
+
-- Applies the final decision of an expense's approval request: approvals
|
|
67149
|
+
-- calls it, with the user who decided. It isn't granted to anyone.
|
|
67150
|
+
create or replace function ${fn("expense_approval_decided")}(expense_id uuid, approved boolean, note text, decided_by uuid)
|
|
67151
|
+
returns void
|
|
67152
|
+
language plpgsql
|
|
67153
|
+
security definer
|
|
67154
|
+
set search_path = ''
|
|
67155
|
+
as $$
|
|
67156
|
+
declare
|
|
67157
|
+
v_row ${table}%rowtype;
|
|
67158
|
+
begin
|
|
67159
|
+
select * into v_row from ${table} x where x.${e("id")} = expense_approval_decided.expense_id for update;
|
|
67160
|
+
if not found or ${status("v_row")} <> 'submitted' then
|
|
67161
|
+
return;
|
|
67162
|
+
end if;
|
|
67163
|
+
if expense_approval_decided.approved then
|
|
67164
|
+
update ${table} x set ${e("updatedAt")} = now()${setStatus("approved")}${set("approvedAt", "now()")}${set("decidedBy", "expense_approval_decided.decided_by")}${set("decidedAt", "now()")}${set("decisionNote", "nullif(trim(expense_approval_decided.note), '')")}
|
|
67165
|
+
where x.${e("id")} = v_row.${e("id")}
|
|
67166
|
+
returning * into v_row;
|
|
67167
|
+
${record("expense.approved", "approved an expense")}
|
|
67168
|
+
else
|
|
67169
|
+
update ${table} x set ${e("updatedAt")} = now()${setStatus("rejected")}${set("rejectedAt", "now()")}${set("decidedBy", "expense_approval_decided.decided_by")}${set("decidedAt", "now()")}${set("decisionNote", "nullif(trim(expense_approval_decided.note), '')")}
|
|
67170
|
+
where x.${e("id")} = v_row.${e("id")}
|
|
67171
|
+
returning * into v_row;
|
|
67172
|
+
${record("expense.rejected", "rejected an expense")}
|
|
67173
|
+
end if;
|
|
67174
|
+
end;
|
|
67175
|
+
$$;
|
|
67176
|
+
revoke execute on function ${fn("expense_approval_decided")}(uuid, boolean, text, uuid) from public, anon, authenticated;
|
|
67177
|
+
`}
|
|
66258
67178
|
create or replace function ${fn("reimburse_expense")}(expense_id uuid, reference text default null)
|
|
66259
67179
|
returns jsonb
|
|
66260
67180
|
language plpgsql
|
|
@@ -66402,8 +67322,9 @@ function expensesFunctions(ctx) {
|
|
|
66402
67322
|
-- Approves or rejects a submitted report without the approvals block: the
|
|
66403
67323
|
-- service role, or a member with the approve permission who doesn't own it.
|
|
66404
67324
|
-- Approval books it like a final approval; a rejected report can change and
|
|
66405
|
-
-- go in again.
|
|
66406
|
-
|
|
67325
|
+
-- go in again. The service role names the user it decides for in decided_by.
|
|
67326
|
+
drop function if exists ${fn("decide_expense_report")}(uuid, boolean, text);
|
|
67327
|
+
create or replace function ${fn("decide_expense_report")}(report_id uuid, approved boolean, note text default null, decided_by uuid default null)
|
|
66407
67328
|
returns jsonb
|
|
66408
67329
|
language plpgsql
|
|
66409
67330
|
security definer
|
|
@@ -66415,6 +67336,10 @@ begin${loadReport("decide_expense_report.report_id", true)}
|
|
|
66415
67336
|
if not (${SERVICE_CALLER$1} or (${ctx.can("tenant", `v_row.${r("tenant")}`, approve)} and v_row.${r("user")} is distinct from auth.uid())) then
|
|
66416
67337
|
${forbidden("not allowed to decide this expense report")}
|
|
66417
67338
|
end if;
|
|
67339
|
+
if decide_expense_report.decided_by is not null and (not ${SERVICE_CALLER$1} and decide_expense_report.decided_by is distinct from auth.uid()
|
|
67340
|
+
or decide_expense_report.decided_by = v_row.${r("user")}) then
|
|
67341
|
+
${forbidden("only the service role decides for another user, never for the owner")}
|
|
67342
|
+
end if;
|
|
66418
67343
|
if ${status("v_row", "")} <> 'submitted' then
|
|
66419
67344
|
${fail$1("EXPENSE_REPORT_LOCKED", "only a submitted report is decided", "55000")}
|
|
66420
67345
|
end if;
|
|
@@ -66423,11 +67348,11 @@ begin${loadReport("decide_expense_report.report_id", true)}
|
|
|
66423
67348
|
end if;
|
|
66424
67349
|
if decide_expense_report.approved then
|
|
66425
67350
|
perform ${fn("approve_expense_report")}(v_row.${r("id")});
|
|
66426
|
-
update ${reports} x set ${r("updatedAt")} = now()${alsoSet("reports", "decidedBy", "auth.uid()")}${alsoSet("reports", "decisionNote", "nullif(trim(decide_expense_report.note), '')")}
|
|
67351
|
+
update ${reports} x set ${r("updatedAt")} = now()${alsoSet("reports", "decidedBy", "coalesce(decide_expense_report.decided_by, auth.uid())")}${alsoSet("reports", "decisionNote", "nullif(trim(decide_expense_report.note), '')")}
|
|
66427
67352
|
where x.${r("id")} = v_row.${r("id")}
|
|
66428
67353
|
returning * into v_row;
|
|
66429
67354
|
else${rejections ? `
|
|
66430
|
-
update ${reports} x set ${r("rejectedAt")} = now(), ${r("updatedAt")} = now()${alsoSet("reports", "decidedBy", "auth.uid()")}${alsoSet("reports", "decisionNote", "nullif(trim(decide_expense_report.note), '')")}
|
|
67355
|
+
update ${reports} x set ${r("rejectedAt")} = now(), ${r("updatedAt")} = now()${alsoSet("reports", "decidedBy", "coalesce(decide_expense_report.decided_by, auth.uid())")}${alsoSet("reports", "decisionNote", "nullif(trim(decide_expense_report.note), '')")}
|
|
66431
67356
|
where x.${r("id")} = v_row.${r("id")}
|
|
66432
67357
|
returning * into v_row;
|
|
66433
67358
|
${reportRecord("expense_report.rejected", "rejected an expense report")}` : `
|
|
@@ -66436,7 +67361,7 @@ begin${loadReport("decide_expense_report.report_id", true)}
|
|
|
66436
67361
|
return ${reportJson("v_row", "")};
|
|
66437
67362
|
end;
|
|
66438
67363
|
$$;
|
|
66439
|
-
${userGrant(`${fn("decide_expense_report")}(uuid, boolean, text)`)}
|
|
67364
|
+
${userGrant(`${fn("decide_expense_report")}(uuid, boolean, text, uuid)`)}
|
|
66440
67365
|
`;
|
|
66441
67366
|
const total = (row) => `coalesce((select sum(y.${x("amount")}) from ${lines} y where y.${x("report")} = ${row}.${r("id")}), 0)`;
|
|
66442
67367
|
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)})`;
|
|
@@ -67068,7 +67993,9 @@ const NAMES$72 = {
|
|
|
67068
67993
|
"approvals",
|
|
67069
67994
|
"owner",
|
|
67070
67995
|
"companyExpenses",
|
|
67071
|
-
"withdrawApproved"
|
|
67996
|
+
"withdrawApproved",
|
|
67997
|
+
"standaloneApprovals",
|
|
67998
|
+
"policy"
|
|
67072
67999
|
],
|
|
67073
68000
|
tables: {
|
|
67074
68001
|
categories: {
|
|
@@ -67360,7 +68287,8 @@ function contract$63(ctx) {
|
|
|
67360
68287
|
args: [
|
|
67361
68288
|
"uuid",
|
|
67362
68289
|
"boolean",
|
|
67363
|
-
"text"
|
|
68290
|
+
"text",
|
|
68291
|
+
"uuid"
|
|
67364
68292
|
],
|
|
67365
68293
|
returns: "jsonb"
|
|
67366
68294
|
}],
|
|
@@ -67382,7 +68310,12 @@ function contract$63(ctx) {
|
|
|
67382
68310
|
}
|
|
67383
68311
|
];
|
|
67384
68312
|
}
|
|
67385
|
-
const CONTRIBUTES$
|
|
68313
|
+
const CONTRIBUTES$8 = { approvals: (own) => standaloneApprovals(own) ? [{
|
|
68314
|
+
subject: EXPENSE_SUBJECT,
|
|
68315
|
+
access: "declared",
|
|
68316
|
+
approve: ({ subjectId, comment, approver }) => `perform ${own.fn("expense_approval_decided")}(${subjectId}::uuid, true, ${comment}, ${approver});`,
|
|
68317
|
+
reject: ({ subjectId, comment, approver }) => `perform ${own.fn("expense_approval_decided")}(${subjectId}::uuid, false, ${comment}, ${approver});`
|
|
68318
|
+
}] : expenseApprovals(own) ? [{
|
|
67386
68319
|
subject: EXPENSE_REPORT_SUBJECT,
|
|
67387
68320
|
access: "declared",
|
|
67388
68321
|
approve: ({ subjectId }) => `perform ${own.fn("approve_expense_report")}(${subjectId}::uuid);`
|
|
@@ -67394,7 +68327,7 @@ const REQUIRES$4 = [
|
|
|
67394
68327
|
"ledger"
|
|
67395
68328
|
];
|
|
67396
68329
|
const EXPENSES = {
|
|
67397
|
-
contributes: CONTRIBUTES$
|
|
68330
|
+
contributes: CONTRIBUTES$8,
|
|
67398
68331
|
name: "expenses",
|
|
67399
68332
|
scopes: ["tenant"],
|
|
67400
68333
|
title: "Expenses",
|
|
@@ -67402,7 +68335,11 @@ const EXPENSES = {
|
|
|
67402
68335
|
requires: [...REQUIRES$4],
|
|
67403
68336
|
dependencies: (layout) => {
|
|
67404
68337
|
const expenses = layout.modules?.["expenses"];
|
|
67405
|
-
if (expenses?.tables?.["reports"] === null) return ["
|
|
68338
|
+
if (expenses?.tables?.["reports"] === null) return expenses.options?.["standaloneApprovals"] === true ? [
|
|
68339
|
+
"memberships",
|
|
68340
|
+
"permissions",
|
|
68341
|
+
"approvals"
|
|
68342
|
+
] : ["memberships", "permissions"];
|
|
67406
68343
|
return expenses?.options?.["approvals"] === false ? REQUIRES$4.filter((name) => name !== "approvals") : [...REQUIRES$4];
|
|
67407
68344
|
},
|
|
67408
68345
|
integrates: [
|
|
@@ -75167,7 +76104,7 @@ const INBOX_NAMES = {
|
|
|
75167
76104
|
was: "conversations"
|
|
75168
76105
|
}]
|
|
75169
76106
|
};
|
|
75170
|
-
const NAME$
|
|
76107
|
+
const NAME$4 = /^[a-z][a-z0-9_-]{0,30}$/;
|
|
75171
76108
|
/** What a row's JSON holds for an optional column the app's table lacks. */
|
|
75172
76109
|
const JSON_FALLBACKS = {
|
|
75173
76110
|
settings: "'{}'::jsonb",
|
|
@@ -75192,7 +76129,7 @@ function inboxSql(ctx, operations) {
|
|
|
75192
76129
|
return sqlString(operationPermission(operations, `${OPERATION_PREFIXES.inboxCommand}${name}`, fallback) ?? fallback);
|
|
75193
76130
|
};
|
|
75194
76131
|
const topic = ctx.text("topic", "inbox");
|
|
75195
|
-
if (!NAME$
|
|
76132
|
+
if (!NAME$4.test(topic)) throw new TypeError("blocks.inbox.options.topic must be a lowercase name of at most 31 characters");
|
|
75196
76133
|
const bucket = ctx.text("bucket", "inbox-files");
|
|
75197
76134
|
if (!/^[a-z0-9][a-z0-9_-]{0,62}$/.test(bucket)) throw new TypeError("blocks.inbox.options.bucket must be a lowercase bucket id");
|
|
75198
76135
|
const maxBody = ctx.number("maxBodyLength", 2e4);
|
|
@@ -85817,7 +86754,7 @@ ${userGrant(`${fn("delete_invoice")}(uuid)`)}
|
|
|
85817
86754
|
if v_row.${i("id")} is not null then
|
|
85818
86755
|
return ${row("v_row")};
|
|
85819
86756
|
end if;
|
|
85820
|
-
select coalesce(jsonb_agg(jsonb_build_object('description', x.${ql("description")}, 'quantity', x.${ql("quantity")}, 'unitAmount', x.${ql("unitAmount")}::text,
|
|
86757
|
+
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,
|
|
85821
86758
|
'discountBps', ${lineColumn(quotes, "lines", "x", "discountBps")}, 'taxRateBps', ${lineColumn(quotes, "lines", "x", "taxRateBps")}, 'taxCode', ${lineColumn(quotes, "lines", "x", "taxCode")},
|
|
85822
86759
|
'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
|
|
85823
86760
|
) order by x.${ql("position")}), '[]'::jsonb) into v_lines
|
|
@@ -85892,11 +86829,13 @@ ${userGrant(`${fn("invoice_from_quote")}(uuid, integer)`)}
|
|
|
85892
86829
|
const writeOffReason = typeof ctx.config.columns["invoices"]?.["writeOffReason"] === "string" && ctx.has("invoices", "writeOffReason");
|
|
85893
86830
|
const addCharge = charges ? `
|
|
85894
86831
|
${chargeFields.drop(fn("add_invoice_charge"), "uuid, bigint, text, text")}
|
|
86832
|
+
drop function if exists ${fn("add_invoice_charge")}(uuid, bigint, text, text${chargeFields.type});
|
|
85895
86833
|
-- Adds a charge on top of an issued invoice's total, such as collection
|
|
85896
86834
|
-- costs or a late fee, in the invoice's currency. It raises the balance, so
|
|
85897
86835
|
-- a paid invoice is open again until the charge is paid too. fields: the
|
|
85898
|
-
-- charge's extra columns (options.chargeExtraColumns).
|
|
85899
|
-
|
|
86836
|
+
-- charge's extra columns (options.chargeExtraColumns). actor: who added it,
|
|
86837
|
+
-- for the state machine's history.
|
|
86838
|
+
create or replace function ${fn("add_invoice_charge")}(invoice uuid, amount bigint, currency text, description text${chargeFields.param}, actor jsonb default null)
|
|
85900
86839
|
returns jsonb
|
|
85901
86840
|
language plpgsql
|
|
85902
86841
|
security definer
|
|
@@ -85923,6 +86862,7 @@ begin
|
|
|
85923
86862
|
if upper(add_invoice_charge.currency) is distinct from v_row.${i("currency")} then
|
|
85924
86863
|
${fail$1("INVOICE_CURRENCY_MISMATCH", "a charge must be in the invoice's currency", "22023")}
|
|
85925
86864
|
end if;
|
|
86865
|
+
${transitionActorSql("add_invoice_charge.actor", "INVOICE_ACTOR_INVALID")}
|
|
85926
86866
|
insert into ${t("charges")} (${chargeColumns.join(", ")}${chargeExtras.columns})
|
|
85927
86867
|
values (${chargeValues.join(", ")}${chargeExtras.values})
|
|
85928
86868
|
returning ${ch("id")} into v_charge;${settle("v_row")}
|
|
@@ -85930,9 +86870,10 @@ begin
|
|
|
85930
86870
|
return ${row("v_row")};
|
|
85931
86871
|
end;
|
|
85932
86872
|
$$;
|
|
85933
|
-
${userGrant(`${fn("add_invoice_charge")}(uuid, bigint, text, text${chargeFields.type})`)}
|
|
86873
|
+
${userGrant(`${fn("add_invoice_charge")}(uuid, bigint, text, text${chargeFields.type}, jsonb)`)}
|
|
85934
86874
|
|
|
85935
|
-
|
|
86875
|
+
drop function if exists ${fn("remove_invoice_charge")}(uuid);
|
|
86876
|
+
create or replace function ${fn("remove_invoice_charge")}(charge uuid, actor jsonb default null)
|
|
85936
86877
|
returns jsonb
|
|
85937
86878
|
language plpgsql
|
|
85938
86879
|
security definer
|
|
@@ -85955,13 +86896,14 @@ begin
|
|
|
85955
86896
|
], true)} then
|
|
85956
86897
|
${fail$1("INVOICE_NOT_CHARGEABLE", "only an issued invoice changes its charges", "55000")}
|
|
85957
86898
|
end if;
|
|
86899
|
+
${transitionActorSql("remove_invoice_charge.actor", "INVOICE_ACTOR_INVALID")}
|
|
85958
86900
|
delete from ${t("charges")} c where c.${ch("id")} = remove_invoice_charge.charge
|
|
85959
86901
|
returning c.${ch("amount")} into v_amount;${settle("v_row")}
|
|
85960
86902
|
${record("invoice.charge_removed", "v_row", `, 'chargeId', remove_invoice_charge.charge, 'amount', v_amount::text, 'balance', ${balance("v_row")}::text`, true)}
|
|
85961
86903
|
return ${row("v_row")};
|
|
85962
86904
|
end;
|
|
85963
86905
|
$$;
|
|
85964
|
-
${userGrant(`${fn("remove_invoice_charge")}(uuid)`)}
|
|
86906
|
+
${userGrant(`${fn("remove_invoice_charge")}(uuid, jsonb)`)}
|
|
85965
86907
|
` : "";
|
|
85966
86908
|
const kindTable = (kind) => `(select * from ${t("invoices")} k where ${kd(`k.${i("kind")}`, [kind])})`;
|
|
85967
86909
|
return `
|
|
@@ -86039,8 +86981,10 @@ ${updateInvoiceSql()}${lineItemsSql(ctx, {
|
|
|
86039
86981
|
-- Issues a draft: it gets the next number of its kind (gapless, so a
|
|
86040
86982
|
-- number is only taken when the invoice is final), its issue and due date,
|
|
86041
86983
|
-- and its lines freeze. A credit note reduces the balance of its original.
|
|
86984
|
+
-- actor: who issued it, for the state machine's history.
|
|
86042
86985
|
drop function if exists ${fn("issue_invoice")}(uuid, date);
|
|
86043
|
-
|
|
86986
|
+
drop function if exists ${fn("issue_invoice")}(uuid, date, date);
|
|
86987
|
+
create or replace function ${fn("issue_invoice")}(invoice uuid, issued_on date, due_on date default null, actor jsonb default null)
|
|
86044
86988
|
returns jsonb
|
|
86045
86989
|
language plpgsql
|
|
86046
86990
|
security definer
|
|
@@ -86066,6 +87010,7 @@ begin
|
|
|
86066
87010
|
if issue_invoice.due_on < v_issued_on then
|
|
86067
87011
|
${fail$1("INVOICE_DUE_INVALID", "an invoice falls due on or after its issue date", "22023")}
|
|
86068
87012
|
end if;
|
|
87013
|
+
${transitionActorSql("issue_invoice.actor", "INVOICE_ACTOR_INVALID")}
|
|
86069
87014
|
${ctx.hook("before_invoice_issue", [["uuid", `v_row.${i("id")}`]])}
|
|
86070
87015
|
if ${kd(`v_row.${i("kind")}`, ["credit_note"])} then
|
|
86071
87016
|
select * into v_original from ${t("invoices")} x where x.${i("id")} = v_row.${i("original")} for update;
|
|
@@ -86112,15 +87057,17 @@ begin
|
|
|
86112
87057
|
return ${row("v_row")};
|
|
86113
87058
|
end;
|
|
86114
87059
|
$$;
|
|
86115
|
-
${userGrant(`${fn("issue_invoice")}(uuid, date, date)`)}
|
|
87060
|
+
${userGrant(`${fn("issue_invoice")}(uuid, date, date, jsonb)`)}
|
|
86116
87061
|
|
|
86117
87062
|
-- Records a payment (a negative amount is a refund) in the invoice's
|
|
86118
87063
|
-- currency as a ledger transaction from the invoice's receivable account to
|
|
86119
87064
|
-- cash. A reference, such as a bank or payment provider id, is unique per
|
|
86120
|
-
-- organization, so recording the same payment twice adds it once.
|
|
87065
|
+
-- organization, so recording the same payment twice adds it once. actor:
|
|
87066
|
+
-- who recorded it, for the state machine's history.
|
|
86121
87067
|
drop function if exists ${fn("record_invoice_payment")}(uuid, bigint, timestamptz, text, text);
|
|
86122
87068
|
drop function if exists ${fn("record_invoice_payment")}(uuid, bigint, text, timestamptz, text, text);
|
|
86123
|
-
|
|
87069
|
+
drop function if exists ${fn("record_invoice_payment")}(uuid, bigint, text, timestamptz, text, text, text);
|
|
87070
|
+
create or replace function ${fn("record_invoice_payment")}(invoice uuid, amount bigint, currency text, paid_at timestamptz, method text, reference text, note text default null, actor jsonb default null)
|
|
86124
87071
|
returns jsonb
|
|
86125
87072
|
language plpgsql
|
|
86126
87073
|
security definer
|
|
@@ -86154,6 +87101,7 @@ begin
|
|
|
86154
87101
|
if upper(record_invoice_payment.currency) is distinct from v_row.${i("currency")} then
|
|
86155
87102
|
${fail$1("INVOICE_CURRENCY_MISMATCH", "a payment must be in the invoice's currency", "22023")}
|
|
86156
87103
|
end if;
|
|
87104
|
+
${transitionActorSql("record_invoice_payment.actor", "INVOICE_ACTOR_INVALID")}
|
|
86157
87105
|
-- A recorded reference is a replay that adds nothing, so it skips the check.
|
|
86158
87106
|
v_reference := nullif(trim(record_invoice_payment.reference), '');
|
|
86159
87107
|
if v_reference is not null and exists (
|
|
@@ -86176,7 +87124,7 @@ begin
|
|
|
86176
87124
|
return ${row("v_row")};
|
|
86177
87125
|
end;
|
|
86178
87126
|
$$;
|
|
86179
|
-
${userGrant(`${fn("record_invoice_payment")}(uuid, bigint, text, timestamptz, text, text, text)`)}
|
|
87127
|
+
${userGrant(`${fn("record_invoice_payment")}(uuid, bigint, text, timestamptz, text, text, text, jsonb)`)}
|
|
86180
87128
|
|
|
86181
87129
|
create or replace function ${fn("list_invoice_payments")}(invoice uuid)
|
|
86182
87130
|
returns jsonb
|
|
@@ -86268,8 +87216,10 @@ $$;
|
|
|
86268
87216
|
${userGrant(`${fn("credit_invoice")}(uuid, jsonb, text)`)}
|
|
86269
87217
|
|
|
86270
87218
|
-- Voids an invoice without payments: a draft, or an issued one sent in
|
|
86271
|
-
-- error. Its number stays taken. Needs invoices.manage.
|
|
86272
|
-
|
|
87219
|
+
-- error. Its number stays taken. Needs invoices.manage. The reason and actor
|
|
87220
|
+
-- go to the state machine's history.
|
|
87221
|
+
drop function if exists ${fn("void_invoice")}(uuid, text);
|
|
87222
|
+
create or replace function ${fn("void_invoice")}(invoice uuid, reason text, actor jsonb default null)
|
|
86273
87223
|
returns jsonb
|
|
86274
87224
|
language plpgsql
|
|
86275
87225
|
security definer
|
|
@@ -86285,18 +87235,23 @@ begin
|
|
|
86285
87235
|
if ${st(`v_row.${i("status")}`, ["draft", "issued"], true)} or v_row.${i("paidTotal")} <> 0 or v_row.${i("creditedTotal")} <> 0 then
|
|
86286
87236
|
${fail$1("INVOICE_NOT_VOIDABLE", "an invoice with payments or credits is credited, not voided", "55000")}
|
|
86287
87237
|
end if;
|
|
87238
|
+
${transitionActorSql("void_invoice.actor", "INVOICE_ACTOR_INVALID")}
|
|
87239
|
+
${transitionReasonSql("void_invoice.reason")}
|
|
86288
87240
|
update ${t("invoices")} x set ${i("status")} = ${ctx.value("invoices", "status", "void")}, ${i("voidedAt")} = now(),
|
|
86289
87241
|
${has("voidReason") ? `${i("voidReason")} = nullif(trim(void_invoice.reason), ''), ` : ""}${i("updatedAt")} = now()
|
|
86290
87242
|
where x.${i("id")} = v_row.${i("id")} returning * into v_row;
|
|
87243
|
+
${transitionReasonSql()}
|
|
86291
87244
|
${record("invoice.voided", "v_row", `, 'reason', ${has("voidReason") ? `v_row.${i("voidReason")}` : "nullif(trim(void_invoice.reason), '')"}`, true)}
|
|
86292
87245
|
return ${row("v_row")};
|
|
86293
87246
|
end;
|
|
86294
87247
|
$$;
|
|
86295
|
-
${userGrant(`${fn("void_invoice")}(uuid, text)`)}
|
|
87248
|
+
${userGrant(`${fn("void_invoice")}(uuid, text, jsonb)`)}
|
|
86296
87249
|
|
|
86297
|
-
-- Writes an open invoice off as uncollectible. Needs invoices.manage.
|
|
87250
|
+
-- Writes an open invoice off as uncollectible. Needs invoices.manage. The
|
|
87251
|
+
-- reason and actor go to the state machine's history.
|
|
86298
87252
|
drop function if exists ${fn("write_off_invoice")}(uuid);
|
|
86299
|
-
|
|
87253
|
+
drop function if exists ${fn("write_off_invoice")}(uuid, text);
|
|
87254
|
+
create or replace function ${fn("write_off_invoice")}(invoice uuid, reason text default null, actor jsonb default null)
|
|
86300
87255
|
returns jsonb
|
|
86301
87256
|
language plpgsql
|
|
86302
87257
|
security definer
|
|
@@ -86305,19 +87260,25 @@ as $$
|
|
|
86305
87260
|
declare
|
|
86306
87261
|
v_row ${t("invoices")};
|
|
86307
87262
|
begin
|
|
87263
|
+
${transitionActorSql("write_off_invoice.actor", "INVOICE_ACTOR_INVALID")}
|
|
87264
|
+
${transitionReasonSql("write_off_invoice.reason")}
|
|
86308
87265
|
update ${t("invoices")} x set ${i("status")} = ${ctx.value("invoices", "status", "uncollectible")}, ${writeOffReason ? `${i("writeOffReason")} = nullif(trim(write_off_invoice.reason), ''), ` : ""}${i("updatedAt")} = now()
|
|
86309
87266
|
where x.${i("id")} = write_off_invoice.invoice and ${can("x", n.writeOff)} and ${st(`x.${i("status")}`, ["issued", "partially_paid"])}
|
|
86310
87267
|
returning * into v_row;
|
|
86311
87268
|
if v_row.${i("id")} is null then
|
|
86312
87269
|
${fail$1("INVOICE_NOT_OPEN", "only an open invoice you can manage is written off", "55000")}
|
|
86313
87270
|
end if;
|
|
87271
|
+
${transitionReasonSql()}
|
|
86314
87272
|
${record("invoice.uncollected", "v_row", `, 'balance', ${balance("v_row")}::text, 'reason', nullif(trim(write_off_invoice.reason), '')`, true)}
|
|
86315
87273
|
return ${row("v_row")};
|
|
86316
87274
|
end;
|
|
86317
87275
|
$$;
|
|
86318
|
-
${userGrant(`${fn("write_off_invoice")}(uuid, text)`)}
|
|
87276
|
+
${userGrant(`${fn("write_off_invoice")}(uuid, text, jsonb)`)}
|
|
86319
87277
|
|
|
86320
|
-
|
|
87278
|
+
-- Reverses a recorded payment. The reason and actor go to the state machine's
|
|
87279
|
+
-- history.
|
|
87280
|
+
drop function if exists ${fn("reverse_invoice_payment")}(uuid, text);
|
|
87281
|
+
create or replace function ${fn("reverse_invoice_payment")}(payment uuid, reason text default null, actor jsonb default null)
|
|
86321
87282
|
returns jsonb
|
|
86322
87283
|
language plpgsql
|
|
86323
87284
|
security definer
|
|
@@ -86342,14 +87303,17 @@ begin
|
|
|
86342
87303
|
or exists (select 1 from ${ledger.transactions} y where y.${ledger.tx("reverses")} = reverse_invoice_payment.payment) then
|
|
86343
87304
|
${fail$1("INVOICE_PAYMENT_REVERSED", "this payment is a reversal or is already reversed", "55000")}
|
|
86344
87305
|
end if;
|
|
87306
|
+
${transitionActorSql("reverse_invoice_payment.actor", "INVOICE_ACTOR_INVALID")}
|
|
87307
|
+
${transitionReasonSql("reverse_invoice_payment.reason")}
|
|
86345
87308
|
v_amount := ${ledger.paidTotal("v_row")};
|
|
86346
87309
|
v_reversal := ${ledger.reverse("v_row", "reverse_invoice_payment.payment", "nullif(trim(reverse_invoice_payment.reason), '')")};
|
|
86347
87310
|
v_amount := v_amount - ${ledger.paidTotal("v_row")};${settle("v_row")}
|
|
87311
|
+
${transitionReasonSql()}
|
|
86348
87312
|
${record("invoice.payment_reversed", "v_row", `, 'paymentId', reverse_invoice_payment.payment, 'reversalId', v_reversal, 'amount', v_amount::text, 'balance', ${balance("v_row")}::text, 'reason', nullif(trim(reverse_invoice_payment.reason), '')`, true)}
|
|
86349
87313
|
return ${row("v_row")};
|
|
86350
87314
|
end;
|
|
86351
87315
|
$$;
|
|
86352
|
-
${userGrant(`${fn("reverse_invoice_payment")}(uuid, text)`)}
|
|
87316
|
+
${userGrant(`${fn("reverse_invoice_payment")}(uuid, text, jsonb)`)}
|
|
86353
87317
|
${addCharge}
|
|
86354
87318
|
-- What a tenant is owed in one currency on as_of, by days past due:
|
|
86355
87319
|
-- not yet due, 1 to 30, 31 to 60, 61 to 90 and over 90. Amounts are text.
|
|
@@ -86769,7 +87733,8 @@ function contract$48(ctx) {
|
|
|
86769
87733
|
args: [
|
|
86770
87734
|
"uuid",
|
|
86771
87735
|
"date",
|
|
86772
|
-
"date"
|
|
87736
|
+
"date",
|
|
87737
|
+
"jsonb"
|
|
86773
87738
|
],
|
|
86774
87739
|
returns: "jsonb"
|
|
86775
87740
|
},
|
|
@@ -86782,7 +87747,8 @@ function contract$48(ctx) {
|
|
|
86782
87747
|
"timestamptz",
|
|
86783
87748
|
"text",
|
|
86784
87749
|
"text",
|
|
86785
|
-
"text"
|
|
87750
|
+
"text",
|
|
87751
|
+
"jsonb"
|
|
86786
87752
|
],
|
|
86787
87753
|
returns: "jsonb"
|
|
86788
87754
|
},
|
|
@@ -86797,17 +87763,29 @@ function contract$48(ctx) {
|
|
|
86797
87763
|
},
|
|
86798
87764
|
{
|
|
86799
87765
|
name: "void_invoice",
|
|
86800
|
-
args: [
|
|
87766
|
+
args: [
|
|
87767
|
+
"uuid",
|
|
87768
|
+
"text",
|
|
87769
|
+
"jsonb"
|
|
87770
|
+
],
|
|
86801
87771
|
returns: "jsonb"
|
|
86802
87772
|
},
|
|
86803
87773
|
{
|
|
86804
87774
|
name: "write_off_invoice",
|
|
86805
|
-
args: [
|
|
87775
|
+
args: [
|
|
87776
|
+
"uuid",
|
|
87777
|
+
"text",
|
|
87778
|
+
"jsonb"
|
|
87779
|
+
],
|
|
86806
87780
|
returns: "jsonb"
|
|
86807
87781
|
},
|
|
86808
87782
|
{
|
|
86809
87783
|
name: "reverse_invoice_payment",
|
|
86810
|
-
args: [
|
|
87784
|
+
args: [
|
|
87785
|
+
"uuid",
|
|
87786
|
+
"text",
|
|
87787
|
+
"jsonb"
|
|
87788
|
+
],
|
|
86811
87789
|
returns: "jsonb"
|
|
86812
87790
|
},
|
|
86813
87791
|
...ctx.hasTable("charges") ? [{
|
|
@@ -86817,12 +87795,13 @@ function contract$48(ctx) {
|
|
|
86817
87795
|
"bigint",
|
|
86818
87796
|
"text",
|
|
86819
87797
|
"text",
|
|
86820
|
-
...extraFieldsArg(chargeExtraColumns(ctx)).contract
|
|
87798
|
+
...extraFieldsArg(chargeExtraColumns(ctx)).contract,
|
|
87799
|
+
"jsonb"
|
|
86821
87800
|
],
|
|
86822
87801
|
returns: "jsonb"
|
|
86823
87802
|
}, {
|
|
86824
87803
|
name: "remove_invoice_charge",
|
|
86825
|
-
args: ["uuid"],
|
|
87804
|
+
args: ["uuid", "jsonb"],
|
|
86826
87805
|
returns: "jsonb"
|
|
86827
87806
|
}] : [],
|
|
86828
87807
|
{
|
|
@@ -89463,6 +90442,17 @@ function leavePolicy(ctx) {
|
|
|
89463
90442
|
return policySnapshot(policy);
|
|
89464
90443
|
}
|
|
89465
90444
|
/**
|
|
90445
|
+
* `options.approvalOwner`: `"employee"` makes the request's employee the
|
|
90446
|
+
* approval's requester and points a manager step at their manager; the default
|
|
90447
|
+
* `"filer"` keeps the user who filed it. Needs `owner: "employee"`.
|
|
90448
|
+
*/
|
|
90449
|
+
function leaveApprovalOwner(ctx, employee) {
|
|
90450
|
+
const value = ctx.text("approvalOwner", "filer");
|
|
90451
|
+
if (value !== "filer" && value !== "employee") throw new TypeError(`${WHERE$8}.approvalOwner must be "filer" or "employee"`);
|
|
90452
|
+
if (value === "employee" && !employee) throw new TypeError(`${WHERE$8}.approvalOwner "employee" needs ${WHERE$8}.owner "employee"`);
|
|
90453
|
+
return value;
|
|
90454
|
+
}
|
|
90455
|
+
/**
|
|
89466
90456
|
* Whether requests keep their decision themselves instead of in the approvals
|
|
89467
90457
|
* block: `options.approvals: false`, or no approval column.
|
|
89468
90458
|
*/
|
|
@@ -89546,7 +90536,8 @@ function leaveContract(ctx) {
|
|
|
89546
90536
|
args: [
|
|
89547
90537
|
"uuid",
|
|
89548
90538
|
"boolean",
|
|
89549
|
-
"text"
|
|
90539
|
+
"text",
|
|
90540
|
+
"uuid"
|
|
89550
90541
|
],
|
|
89551
90542
|
returns: "jsonb"
|
|
89552
90543
|
}] : [],
|
|
@@ -89557,6 +90548,15 @@ function leaveContract(ctx) {
|
|
|
89557
90548
|
}] : []
|
|
89558
90549
|
];
|
|
89559
90550
|
}
|
|
90551
|
+
/** The final approval of a leave request books it. */
|
|
90552
|
+
const LEAVE_CONTRIBUTES = {
|
|
90553
|
+
"share-links": (own) => [leaveFeedSubject(own), ...leaveTeamFeedSubject(own)],
|
|
90554
|
+
approvals: (own) => leaveStatusMode(own) ? [] : [{
|
|
90555
|
+
subject: LEAVE_REQUEST_SUBJECT,
|
|
90556
|
+
access: "declared",
|
|
90557
|
+
approve: ({ subjectId }) => `perform ${own.fn("approve_leave_request")}(${subjectId}::uuid);`
|
|
90558
|
+
}]
|
|
90559
|
+
};
|
|
89560
90560
|
// src/sql/modules/leave-ledger.ts
|
|
89561
90561
|
/** Leave amounts are numeric(8, 2); ledger amounts are hundredths. */
|
|
89562
90562
|
const SCALE = 100;
|
|
@@ -90025,7 +91025,8 @@ const LEAVE_NAMES = {
|
|
|
90025
91025
|
"feed",
|
|
90026
91026
|
"approvals",
|
|
90027
91027
|
"owner",
|
|
90028
|
-
"reapprove"
|
|
91028
|
+
"reapprove",
|
|
91029
|
+
"approvalOwner"
|
|
90029
91030
|
],
|
|
90030
91031
|
tables: {
|
|
90031
91032
|
types: {
|
|
@@ -90240,10 +91241,10 @@ function build$51(ctx) {
|
|
|
90240
91241
|
const approve = ctx.permission("approve", permissions.approve);
|
|
90241
91242
|
const decision = (column, value) => ctx.has("requests", column) ? `, ${q(column)} = ${value}` : "";
|
|
90242
91243
|
const decide = `
|
|
90243
|
-
-- Approves or rejects a pending request without the approvals block
|
|
90244
|
-
-- service role
|
|
90245
|
-
|
|
90246
|
-
create or replace function ${fn("decide_leave_request")}(request_id uuid, approved boolean, note text default null)
|
|
91244
|
+
-- Approves or rejects a pending request without the approvals block, as the
|
|
91245
|
+
-- service role or an approver who didn't ask; approval books the leave.
|
|
91246
|
+
drop function if exists ${fn("decide_leave_request")}(uuid, boolean, text);
|
|
91247
|
+
create or replace function ${fn("decide_leave_request")}(request_id uuid, approved boolean, note text default null, decided_by uuid default null)
|
|
90247
91248
|
returns jsonb
|
|
90248
91249
|
language plpgsql
|
|
90249
91250
|
security definer
|
|
@@ -90256,8 +91257,8 @@ begin
|
|
|
90256
91257
|
if not found then
|
|
90257
91258
|
${fail$1("LEAVE_REQUEST_NOT_FOUND", "leave request not found", "P0002")}
|
|
90258
91259
|
end if;
|
|
90259
|
-
if not (${SERVICE_CALLER$1} or (${ctx.can("tenant", `v_row.${q("tenant")}`, approve)} and ${owner.requester("v_row")} is distinct from auth.uid())) then
|
|
90260
|
-
${forbidden("not allowed to decide this leave request")}
|
|
91260
|
+
if not (${SERVICE_CALLER$1} or (${ctx.can("tenant", `v_row.${q("tenant")}`, approve)} and ${owner.requester("v_row")} is distinct from auth.uid())) or (decide_leave_request.decided_by is not null and (not ${SERVICE_CALLER$1} and decide_leave_request.decided_by is distinct from auth.uid() or decide_leave_request.decided_by = ${owner.requester("v_row")})) then
|
|
91261
|
+
${forbidden("not allowed to decide this leave request; only the service role decides for another user, never for the requester")}
|
|
90261
91262
|
end if;
|
|
90262
91263
|
if not (${pendingIn("v_row", "")}) then
|
|
90263
91264
|
${fail$1("LEAVE_REQUEST_CLOSED", "this leave request was already decided or cancelled", "55000")}
|
|
@@ -90267,11 +91268,11 @@ begin
|
|
|
90267
91268
|
end if;
|
|
90268
91269
|
if decide_leave_request.approved then
|
|
90269
91270
|
perform ${fn("approve_leave_request")}(v_row.${q("id")});
|
|
90270
|
-
update ${requests} x set ${q("updatedAt")} = now()${decision("decidedBy", "auth.uid()")}${decision("decisionNote", "nullif(trim(decide_leave_request.note), '')")}
|
|
91271
|
+
update ${requests} x set ${q("updatedAt")} = now()${decision("decidedBy", "coalesce(decide_leave_request.decided_by, auth.uid())")}${decision("decisionNote", "nullif(trim(decide_leave_request.note), '')")}
|
|
90271
91272
|
where x.${q("id")} = v_row.${q("id")}
|
|
90272
91273
|
returning * into v_row;
|
|
90273
91274
|
else${rejections ? `
|
|
90274
|
-
update ${requests} x set ${q("rejectedAt")} = now(), ${q("updatedAt")} = now()${decision("decidedBy", "auth.uid()")}${decision("decisionNote", "nullif(trim(decide_leave_request.note), '')")}
|
|
91275
|
+
update ${requests} x set ${q("rejectedAt")} = now(), ${q("updatedAt")} = now()${decision("decidedBy", "coalesce(decide_leave_request.decided_by, auth.uid())")}${decision("decisionNote", "nullif(trim(decide_leave_request.note), '')")}
|
|
90275
91276
|
where x.${q("id")} = v_row.${q("id")}
|
|
90276
91277
|
returning * into v_row;
|
|
90277
91278
|
${requestRecord("leave.rejected", "v_row", "rejected leave")}` : `
|
|
@@ -90280,7 +91281,7 @@ begin
|
|
|
90280
91281
|
return ${requestJson("v_row", "")};
|
|
90281
91282
|
end;
|
|
90282
91283
|
$$;
|
|
90283
|
-
${userGrant(`${fn("decide_leave_request")}(uuid, boolean, text)`)}
|
|
91284
|
+
${userGrant(`${fn("decide_leave_request")}(uuid, boolean, text, uuid)`)}
|
|
90284
91285
|
`;
|
|
90285
91286
|
const balanceCheck = allowNegative ? "" : `
|
|
90286
91287
|
if v_type.${ty("tracked")} and ${fn("leave_available")}(request_leave.tenant, ${me}, v_type.${ty("id")}, ${appBalances ? "request_leave.starts_on" : "extract(year from request_leave.starts_on)::integer"}) < v_amount then
|
|
@@ -90427,13 +91428,14 @@ ${parts ? ` and ${existing.first} <= ${halfDays(starts, ends, "v_start", "v
|
|
|
90427
91428
|
` : ""} ) then
|
|
90428
91429
|
${fail$1("LEAVE_OVERLAP", "this overlaps another leave request", "23P01")}
|
|
90429
91430
|
end if;`;
|
|
91431
|
+
const byEmployee = leaveApprovalOwner(ctx, owner.employee) === "employee";
|
|
90430
91432
|
const openApproval = (tenant) => {
|
|
90431
91433
|
if (approvals === void 0) return "";
|
|
90432
91434
|
const open = `
|
|
90433
91435
|
v_request := ${approvals.fn("open_approval")}(
|
|
90434
91436
|
${tenant}, ${sqlString(LEAVE_REQUEST_SUBJECT)}, v_row.${q("id")}::text, 'approve',
|
|
90435
|
-
${sqlString(policy)}::jsonb, ${or("requests", "v_row", "note")},
|
|
90436
|
-
jsonb_build_object('userId', ${owner.employee ? "v_user, 'employeeId', v_owner" : "v_me"}, 'typeId', v_type.${ty("id")}, 'type', v_type.${ty("name")}, 'startsOn', v_row.${q("startsOn")}, 'endsOn', v_row.${q("endsOn")}, 'amount', v_amount::text, 'unit', v_type.${ty("unit")})
|
|
91437
|
+
${sqlString(policy)}::jsonb${byEmployee ? " || jsonb_build_object('managerOf', v_owner::text)" : ""}, ${or("requests", "v_row", "note")},
|
|
91438
|
+
jsonb_build_object('userId', ${owner.employee ? "v_user, 'employeeId', v_owner" : "v_me"}, 'typeId', v_type.${ty("id")}, 'type', v_type.${ty("name")}, 'startsOn', v_row.${q("startsOn")}, 'endsOn', v_row.${q("endsOn")}, 'amount', v_amount::text, 'unit', v_type.${ty("unit")})${byEmployee ? ",\n v_user" : ""}
|
|
90437
91439
|
);
|
|
90438
91440
|
update ${requests} x set ${q("approval")} = (v_request ->> 'id')::uuid
|
|
90439
91441
|
where x.${q("id")} = v_row.${q("id")}
|
|
@@ -90881,14 +91883,6 @@ ${userGrant(`${fn("list_leave_requests")}(${listBase}${owner.employee ? ", uuid"
|
|
|
90881
91883
|
|
|
90882
91884
|
`;
|
|
90883
91885
|
}
|
|
90884
|
-
const CONTRIBUTES$7 = {
|
|
90885
|
-
"share-links": (own) => [leaveFeedSubject(own), ...leaveTeamFeedSubject(own)],
|
|
90886
|
-
approvals: (own) => leaveStatusMode(own) ? [] : [{
|
|
90887
|
-
subject: LEAVE_REQUEST_SUBJECT,
|
|
90888
|
-
access: "declared",
|
|
90889
|
-
approve: ({ subjectId }) => `perform ${own.fn("approve_leave_request")}(${subjectId}::uuid);`
|
|
90890
|
-
}]
|
|
90891
|
-
};
|
|
90892
91886
|
const REQUIRES$2 = [
|
|
90893
91887
|
"memberships",
|
|
90894
91888
|
"permissions",
|
|
@@ -90896,7 +91890,7 @@ const REQUIRES$2 = [
|
|
|
90896
91890
|
"ledger"
|
|
90897
91891
|
];
|
|
90898
91892
|
const LEAVE = {
|
|
90899
|
-
contributes:
|
|
91893
|
+
contributes: LEAVE_CONTRIBUTES,
|
|
90900
91894
|
internal: [
|
|
90901
91895
|
"leave_available",
|
|
90902
91896
|
"leave_post",
|
|
@@ -96692,92 +97686,6 @@ function itemJson(n) {
|
|
|
96692
97686
|
if (n.extras.length > 0) pairs.push(["fields", columnsObject("ev", n.extras.map((extra) => extra.name))]);
|
|
96693
97687
|
return `jsonb_build_object(${pairs.map(([key, value]) => `'${key}', ${value}`).join(", ")})`;
|
|
96694
97688
|
}
|
|
96695
|
-
// src/sql/modules/notifications-audience.ts
|
|
96696
|
-
/**
|
|
96697
|
-
* Users who hold `notification.permission` in the tenant, added before
|
|
96698
|
-
* `exclude`. A provider without `holdersOf` refuses the audience. The roles and
|
|
96699
|
-
* catalog models ask `can_user` of each member, and the catalog model also
|
|
96700
|
-
* includes a platform-role holder. Never every member.
|
|
96701
|
-
*/
|
|
96702
|
-
function permissionAudience(ctx, layout) {
|
|
96703
|
-
const named = "nullif(notification ->> 'permission', '')";
|
|
96704
|
-
const unavailable = `
|
|
96705
|
-
if ${named} is not null then
|
|
96706
|
-
${fail$1("NOTIFICATION_PERMISSION_AUDIENCE_UNAVAILABLE", "This project has no permission audience", "0A000")}
|
|
96707
|
-
end if;`;
|
|
96708
|
-
const needsTenant = `
|
|
96709
|
-
if ${named} is not null and v_tenant is null then
|
|
96710
|
-
${fail$1("NOTIFICATION_PERMISSION_NEEDS_TENANT", "A permission audience needs a tenant", "22023")}
|
|
96711
|
-
end if;`;
|
|
96712
|
-
const model = accessModel(ctx);
|
|
96713
|
-
if (model === "provider") return providerAudience(layout, needsTenant, unavailable, named);
|
|
96714
|
-
if (model === "custom") return customAudience(ctx, needsTenant, unavailable, named);
|
|
96715
|
-
if (!ctx.installed("memberships")) return unavailable;
|
|
96716
|
-
return membershipAudience(ctx, model, needsTenant, named);
|
|
96717
|
-
}
|
|
96718
|
-
function providerAudience(layout, needsTenant, unavailable, named) {
|
|
96719
|
-
const provider = layout.accessProvider;
|
|
96720
|
-
if (provider === void 0) return unavailable;
|
|
96721
|
-
const template = provider.functions.holdersOf;
|
|
96722
|
-
if (template === void 0) return unavailable;
|
|
96723
|
-
return audienceAppend(needsTenant, named, fillTemplate("authorization.functions.holdersOf", template, {
|
|
96724
|
-
permission: "(notification ->> 'permission')",
|
|
96725
|
-
tenant: "v_tenant",
|
|
96726
|
-
scope: provider.scope
|
|
96727
|
-
}));
|
|
96728
|
-
}
|
|
96729
|
-
function customAudience(ctx, needsTenant, unavailable, named) {
|
|
96730
|
-
const template = ctx.modules.permissions?.functions?.holdersOf;
|
|
96731
|
-
if (template === void 0) return unavailable;
|
|
96732
|
-
return audienceAppend(needsTenant, named, fillTemplate("blocks.permissions.functions.holdersOf", template, {
|
|
96733
|
-
permission: "(notification ->> 'permission')",
|
|
96734
|
-
tenant: "v_tenant"
|
|
96735
|
-
}));
|
|
96736
|
-
}
|
|
96737
|
-
function membershipAudience(ctx, model, needsTenant, named) {
|
|
96738
|
-
const members = ctx.of("memberships");
|
|
96739
|
-
const user = members.col("memberships", "user");
|
|
96740
|
-
const tenant = members.col("memberships", "tenant");
|
|
96741
|
-
let platform = "";
|
|
96742
|
-
if (model === "catalog" && ctx.installed("permissions") && ctx.of("permissions").hasTable("platformAssignments")) {
|
|
96743
|
-
const access = ctx.of("permissions");
|
|
96744
|
-
const holder = access.col("platformAssignments", "user");
|
|
96745
|
-
platform = `
|
|
96746
|
-
union
|
|
96747
|
-
select a.${holder}
|
|
96748
|
-
from ${access.table("platformAssignments")} a
|
|
96749
|
-
where coalesce(better_supabase.platform_can(a.${holder}, notification ->> 'permission'), false)`;
|
|
96750
|
-
}
|
|
96751
|
-
return `${needsTenant}
|
|
96752
|
-
if ${named} is not null then
|
|
96753
|
-
v_recipients := v_recipients || coalesce(array(
|
|
96754
|
-
select m.${user}
|
|
96755
|
-
from ${members.table("memberships")} m
|
|
96756
|
-
where m.${tenant} = v_tenant
|
|
96757
|
-
and ${ctx.scope.canUser(`m.${user}`, "v_tenant", "notification ->> 'permission'")}
|
|
96758
|
-
${platform}
|
|
96759
|
-
), '{}');
|
|
96760
|
-
end if;`;
|
|
96761
|
-
}
|
|
96762
|
-
function audienceAppend(needsTenant, named, call) {
|
|
96763
|
-
return `${needsTenant}
|
|
96764
|
-
if ${named} is not null then
|
|
96765
|
-
v_recipients := v_recipients || coalesce(array(select u from ${call} as t(u)), '{}');
|
|
96766
|
-
end if;`;
|
|
96767
|
-
}
|
|
96768
|
-
const NAME$4 = /^[a-z][a-z0-9_]*$/;
|
|
96769
|
-
/**
|
|
96770
|
-
* A channel nobody chose is on for `in_app` and off for the rest, unless
|
|
96771
|
-
* `channelDefaults` says otherwise.
|
|
96772
|
-
*/
|
|
96773
|
-
function channelDefaults(ctx, channel) {
|
|
96774
|
-
const value = ctx.option("channelDefaults") ?? {};
|
|
96775
|
-
if (!isRecord$1(value)) throw new TypeError("blocks.notifications.options.channelDefaults must map channel names to booleans");
|
|
96776
|
-
return `case ${channel} ${[...Object.entries(value).map(([channel, enabled]) => {
|
|
96777
|
-
if (!NAME$4.test(channel) || typeof enabled !== "boolean") throw new TypeError(`blocks.notifications.options.channelDefaults.${channel} must be a boolean`);
|
|
96778
|
-
return `when ${sqlString(channel)} then ${String(enabled)}`;
|
|
96779
|
-
}), "when 'in_app' then true"].join(" ")} else false end`;
|
|
96780
|
-
}
|
|
96781
97689
|
// src/sql/modules/notifications-suppressions.ts
|
|
96782
97690
|
/**
|
|
96783
97691
|
* Whether the module writes and honours suppressions. A module over the app's
|
|
@@ -112992,6 +113900,10 @@ const NAMES$35 = {
|
|
|
112992
113900
|
"quote.revised": {
|
|
112993
113901
|
subject: "quotes",
|
|
112994
113902
|
payload: [...QUOTE, "revision"]
|
|
113903
|
+
},
|
|
113904
|
+
"quote.withdrawn": {
|
|
113905
|
+
subject: "quotes",
|
|
113906
|
+
payload: [...QUOTE, "revision"]
|
|
112995
113907
|
}
|
|
112996
113908
|
},
|
|
112997
113909
|
hooks: [
|
|
@@ -113007,7 +113919,9 @@ const NAMES$35 = {
|
|
|
113007
113919
|
"validDays",
|
|
113008
113920
|
"extraColumns",
|
|
113009
113921
|
"lineExtraColumns",
|
|
113010
|
-
"lineRates"
|
|
113922
|
+
"lineRates",
|
|
113923
|
+
"workingCopy",
|
|
113924
|
+
"versionLines"
|
|
113011
113925
|
],
|
|
113012
113926
|
tables: {
|
|
113013
113927
|
quotes: {
|
|
@@ -113050,7 +113964,10 @@ const NAMES$35 = {
|
|
|
113050
113964
|
discountBps: "discount_bps",
|
|
113051
113965
|
discountAmount: "discount_amount",
|
|
113052
113966
|
depositBps: "deposit_bps",
|
|
113967
|
+
depositAmount: "deposit_amount",
|
|
113968
|
+
depositRequired: "deposit_required",
|
|
113053
113969
|
depositDue: "deposit_due",
|
|
113970
|
+
unpublishedChanges: "unpublished_changes",
|
|
113054
113971
|
createdBy: "created_by",
|
|
113055
113972
|
createdAt: "created_at",
|
|
113056
113973
|
updatedAt: "updated_at",
|
|
@@ -113074,7 +113991,10 @@ const NAMES$35 = {
|
|
|
113074
113991
|
"discountBps",
|
|
113075
113992
|
"discountAmount",
|
|
113076
113993
|
"depositBps",
|
|
113994
|
+
"depositAmount",
|
|
113995
|
+
"depositRequired",
|
|
113077
113996
|
"depositDue",
|
|
113997
|
+
"unpublishedChanges",
|
|
113078
113998
|
"createdBy"
|
|
113079
113999
|
],
|
|
113080
114000
|
typed: ["status"]
|
|
@@ -113100,6 +114020,45 @@ const NAMES$35 = {
|
|
|
113100
114020
|
},
|
|
113101
114021
|
optional: ["publishedBy"]
|
|
113102
114022
|
},
|
|
114023
|
+
versionLines: {
|
|
114024
|
+
name: "quote_version_lines",
|
|
114025
|
+
app: {},
|
|
114026
|
+
optionalTable: true,
|
|
114027
|
+
lifecycle: {
|
|
114028
|
+
tenant: "tenant",
|
|
114029
|
+
export: true
|
|
114030
|
+
},
|
|
114031
|
+
columns: {
|
|
114032
|
+
id: "id",
|
|
114033
|
+
tenant: "tenant_id",
|
|
114034
|
+
version: "version_id",
|
|
114035
|
+
position: "position",
|
|
114036
|
+
description: "description",
|
|
114037
|
+
quantity: "quantity",
|
|
114038
|
+
unitAmount: "unit_amount",
|
|
114039
|
+
periods: "periods",
|
|
114040
|
+
discountBps: "discount_bps",
|
|
114041
|
+
taxRateBps: "tax_rate_bps",
|
|
114042
|
+
taxCode: "tax_code",
|
|
114043
|
+
section: "section",
|
|
114044
|
+
optional: "optional",
|
|
114045
|
+
selected: "selected",
|
|
114046
|
+
productType: "product_type",
|
|
114047
|
+
productId: "product_id"
|
|
114048
|
+
},
|
|
114049
|
+
optional: [
|
|
114050
|
+
"periods",
|
|
114051
|
+
"discountBps",
|
|
114052
|
+
"taxRateBps",
|
|
114053
|
+
"taxCode",
|
|
114054
|
+
"section",
|
|
114055
|
+
"optional",
|
|
114056
|
+
"selected",
|
|
114057
|
+
"productType",
|
|
114058
|
+
"productId"
|
|
114059
|
+
],
|
|
114060
|
+
typed: ["productType"]
|
|
114061
|
+
},
|
|
113103
114062
|
taxLines: {
|
|
113104
114063
|
name: "quote_tax_lines",
|
|
113105
114064
|
app: {},
|
|
@@ -113130,6 +114089,11 @@ function tables$5(ctx, n) {
|
|
|
113130
114089
|
const company = quoteParty(ctx, "company");
|
|
113131
114090
|
const origin = quoteOrigin(ctx);
|
|
113132
114091
|
const column = (logical, definition) => ctx.has("quotes", logical) ? `\n ${q(logical)} ${typeof definition === "string" ? definition : definition(q(logical))},` : "";
|
|
114092
|
+
const added = [
|
|
114093
|
+
["depositAmount", (name) => `bigint check (${name} > 0)`],
|
|
114094
|
+
["depositRequired", () => "boolean not null default false"],
|
|
114095
|
+
["unpublishedChanges", () => "boolean not null default false"]
|
|
114096
|
+
].filter(([logical]) => ctx.has("quotes", logical)).map(([logical, type]) => `alter table ${t("quotes")} add column if not exists ${q(logical)} ${type(q(logical))};\n`).join("");
|
|
113133
114097
|
const constraints = [
|
|
113134
114098
|
`unique (${q("tenant")}, ${q("number")}, ${q("revision")})`,
|
|
113135
114099
|
...company ? [`check ((${q("companyType")} is null) = (${q("companyId")} is null))`] : [],
|
|
@@ -113150,13 +114114,13 @@ create table if not exists ${t("quotes")} (
|
|
|
113150
114114
|
${q("tokenHash")} text unique,
|
|
113151
114115
|
${q("sentAt")} timestamptz,${column("viewedAt", "timestamptz")}
|
|
113152
114116
|
${q("decidedAt")} timestamptz,
|
|
113153
|
-
${q("decidedBy")} text,${column("decisionNote", "text")}${column("decidedUser", "uuid")}${column("decidedIp", "text")}${column("decidedUserAgent", "text")}${column("pricesIncludeTax", "boolean not null default false")}${column("discountBps", (bps) => `integer not null default 0 check (${bps} >= 0 and ${bps} <= 10000)`)}${column("discountAmount", (amount) => `bigint not null default 0 check (${amount} >= 0)`)}${column("depositBps", (bps) => `integer check (${bps} > 0 and ${bps} < 10000)`)}${column("depositDue", "bigint not null default 0")}${column("createdBy", "uuid")}
|
|
114117
|
+
${q("decidedBy")} text,${column("decisionNote", "text")}${column("decidedUser", "uuid")}${column("decidedIp", "text")}${column("decidedUserAgent", "text")}${column("pricesIncludeTax", "boolean not null default false")}${column("discountBps", (bps) => `integer not null default 0 check (${bps} >= 0 and ${bps} <= 10000)`)}${column("discountAmount", (amount) => `bigint not null default 0 check (${amount} >= 0)`)}${column("depositBps", (bps) => `integer check (${bps} > 0 and ${bps} < 10000)`)}${column("depositAmount", (amount) => `bigint check (${amount} > 0)`)}${column("depositRequired", "boolean not null default false")}${column("depositDue", "bigint not null default 0")}${column("unpublishedChanges", "boolean not null default false")}${column("createdBy", "uuid")}
|
|
113154
114118
|
${q("createdAt")} timestamptz not null default now(),
|
|
113155
114119
|
${q("updatedAt")} timestamptz not null default now(),
|
|
113156
114120
|
${totalColumnsSql(ctx, "quotes")},
|
|
113157
114121
|
${constraints.join(",\n ")}
|
|
113158
114122
|
);
|
|
113159
|
-
create index if not exists ${ctx.naming.rename("quotes_tenant_status_idx")} on ${t("quotes")} (${q("tenant")}, ${q("status")}, ${q("createdAt")} desc);${origin ? `\ncreate index if not exists ${ctx.naming.rename("quotes_origin_idx")} on ${t("quotes")} (${q("originType")}, ${q("originId")});` : ""}
|
|
114123
|
+
${added}create index if not exists ${ctx.naming.rename("quotes_tenant_status_idx")} on ${t("quotes")} (${q("tenant")}, ${q("status")}, ${q("createdAt")} desc);${origin ? `\ncreate index if not exists ${ctx.naming.rename("quotes_origin_idx")} on ${t("quotes")} (${q("originType")}, ${q("originId")});` : ""}
|
|
113160
114124
|
${addExtraColumns(t("quotes"), n.extras)}${appUniqueIndex(ctx, "quotes", ["tokenHash"])}
|
|
113161
114125
|
${lockModuleTable(ctx, "quotes", { read: true })}
|
|
113162
114126
|
${renderPolicy(policy$1({
|
|
@@ -113186,6 +114150,35 @@ function childTables(ctx, n) {
|
|
|
113186
114150
|
target: t(table)
|
|
113187
114151
|
});
|
|
113188
114152
|
const frozen = ctx.trigger("quote_versions_frozen");
|
|
114153
|
+
const frozenFn = `better_supabase.${frozen.replaceAll("\"", "")}()`;
|
|
114154
|
+
const vl = (column) => c("versionLines", column);
|
|
114155
|
+
const vlColumn = (logical, definition) => ctx.has("versionLines", logical) ? `\n ${vl(logical)} ${definition},` : "";
|
|
114156
|
+
const versionLines = versionLinesOn(ctx) ? `
|
|
114157
|
+
create table if not exists ${t("versionLines")} (
|
|
114158
|
+
${vl("id")} uuid primary key default gen_random_uuid(),
|
|
114159
|
+
${vl("tenant")} ${ctx.idType} not null,
|
|
114160
|
+
${vl("version")} uuid not null references ${t("versions")} (${v("id")}) on delete cascade,
|
|
114161
|
+
${vl("position")} integer not null,
|
|
114162
|
+
${vl("description")} text not null,
|
|
114163
|
+
${vl("quantity")} numeric(18, 4) not null,
|
|
114164
|
+
${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")}
|
|
114165
|
+
unique (${vl("version")}, ${vl("position")})
|
|
114166
|
+
);
|
|
114167
|
+
${lockModuleTable(ctx, "versionLines", { read: true })}
|
|
114168
|
+
${renderPolicy(policy$1({
|
|
114169
|
+
table: t("versionLines"),
|
|
114170
|
+
name: ctx.naming.rename(`${ctx.tableName("versionLines").name}_read`),
|
|
114171
|
+
command: "select",
|
|
114172
|
+
roles: ["authenticated"],
|
|
114173
|
+
using: `exists (select 1 from ${t("versions")} v where v.${v("id")} = ${vl("version")})`
|
|
114174
|
+
}), {
|
|
114175
|
+
drop: true,
|
|
114176
|
+
target: t("versionLines")
|
|
114177
|
+
})}
|
|
114178
|
+
drop trigger if exists ${frozen} on ${t("versionLines")};
|
|
114179
|
+
create trigger ${frozen} before update on ${t("versionLines")}
|
|
114180
|
+
for each row execute function ${frozenFn};
|
|
114181
|
+
` : "";
|
|
113189
114182
|
const taxLines = ctx.hasTable("taxLines") ? `
|
|
113190
114183
|
create table if not exists ${t("taxLines")} (
|
|
113191
114184
|
${x("id")} uuid primary key default gen_random_uuid(),
|
|
@@ -113227,7 +114220,7 @@ ${triggerGrant(`better_supabase.${frozen.replaceAll("\"", "")}()`)}
|
|
|
113227
114220
|
drop trigger if exists ${frozen} on ${t("versions")};
|
|
113228
114221
|
create trigger ${frozen} before update on ${t("versions")}
|
|
113229
114222
|
for each row execute function better_supabase.${frozen.replaceAll("\"", "")}();
|
|
113230
|
-
${taxLines}`;
|
|
114223
|
+
${versionLines}${taxLines}`;
|
|
113231
114224
|
}
|
|
113232
114225
|
function build$34(ctx) {
|
|
113233
114226
|
if (ctx.mode === "custom") return "";
|
|
@@ -113282,7 +114275,7 @@ function contract$32(ctx) {
|
|
|
113282
114275
|
},
|
|
113283
114276
|
{
|
|
113284
114277
|
name: "send_quote",
|
|
113285
|
-
args: ["uuid"],
|
|
114278
|
+
args: ["uuid", "jsonb"],
|
|
113286
114279
|
returns: "jsonb"
|
|
113287
114280
|
},
|
|
113288
114281
|
{
|
|
@@ -113292,13 +114285,19 @@ function contract$32(ctx) {
|
|
|
113292
114285
|
"text",
|
|
113293
114286
|
"text",
|
|
113294
114287
|
"text",
|
|
114288
|
+
"jsonb",
|
|
113295
114289
|
"jsonb"
|
|
113296
114290
|
],
|
|
113297
114291
|
returns: "jsonb"
|
|
113298
114292
|
},
|
|
113299
114293
|
{
|
|
113300
114294
|
name: "revise_quote",
|
|
113301
|
-
args: ["uuid"],
|
|
114295
|
+
args: ["uuid", "jsonb"],
|
|
114296
|
+
returns: "jsonb"
|
|
114297
|
+
},
|
|
114298
|
+
{
|
|
114299
|
+
name: "withdraw_quote",
|
|
114300
|
+
args: ["uuid", "jsonb"],
|
|
113302
114301
|
returns: "jsonb"
|
|
113303
114302
|
},
|
|
113304
114303
|
{
|
|
@@ -129531,6 +130530,11 @@ const CHANGED_SETTING = "better_supabase.lifecycle_changed";
|
|
|
129531
130530
|
/** The actor `transition()` passes to the trigger: name, email, ip, userAgent. */
|
|
129532
130531
|
const ACTOR_SETTING = "better_supabase.transition_actor";
|
|
129533
130532
|
const REASON = "nullif(current_setting('better_supabase.transition_reason', true), '')";
|
|
130533
|
+
/**
|
|
130534
|
+
* The acting user: the signed-in user, else the actor's `id`, which the service
|
|
130535
|
+
* role passes for the user it acts for.
|
|
130536
|
+
*/
|
|
130537
|
+
const ACTOR_ID = `coalesce(auth.uid(), nullif(nullif(current_setting('${ACTOR_SETTING}', true), '')::jsonb ->> 'id', '')::uuid)`;
|
|
129534
130538
|
/** One field of the actor `transition()` passed, as SQL. */
|
|
129535
130539
|
function actorField(field) {
|
|
129536
130540
|
const value = `nullif(nullif(current_setting('${ACTOR_SETTING}', true), '')::jsonb ->> ${sqlString(field)}, '')`;
|
|
@@ -129549,7 +130553,7 @@ function historyWrite(ctx, item) {
|
|
|
129549
130553
|
[hist.tenant, `new.${sqlIdent(item.tenantColumn)}`],
|
|
129550
130554
|
[hist.from, asColumnType(table, hist.from, from)],
|
|
129551
130555
|
[hist.to, asColumnType(table, hist.to, to)],
|
|
129552
|
-
[hist.actor,
|
|
130556
|
+
[hist.actor, ACTOR_ID],
|
|
129553
130557
|
[hist.reason, REASON],
|
|
129554
130558
|
...ACTOR_FIELDS.flatMap(([key, field]) => {
|
|
129555
130559
|
const column = hist[key];
|
|
@@ -129566,7 +130570,7 @@ function historyWrite(ctx, item) {
|
|
|
129566
130570
|
[h("subjectId"), `new.${sqlIdent(item.idColumn)}::text`],
|
|
129567
130571
|
[h("fromStatus"), ctx.cast("history", "fromStatus", from)],
|
|
129568
130572
|
[h("toStatus"), ctx.cast("history", "toStatus", to)],
|
|
129569
|
-
[h("actor"),
|
|
130573
|
+
[h("actor"), ACTOR_ID],
|
|
129570
130574
|
[h("reason"), REASON],
|
|
129571
130575
|
...ACTOR_FIELDS.flatMap(([key, field]) => ctx.has("history", key) ? [[h(key), actorField(field)]] : [])
|
|
129572
130576
|
];
|
|
@@ -130037,7 +131041,8 @@ drop function if exists ${ctx.fn("transition")}(text, text, text, text);
|
|
|
130037
131041
|
-- Sets the status as the caller, so the subject table's policies decide
|
|
130038
131042
|
-- whether they may update the record; the trigger checks the edge. actor
|
|
130039
131043
|
-- carries the name, email, ip and userAgent the history row keeps, e.g. for
|
|
130040
|
-
-- a portal visitor who isn't an auth user
|
|
131044
|
+
-- a portal visitor who isn't an auth user, and the id of the user the
|
|
131045
|
+
-- service role acts for.
|
|
130041
131046
|
create or replace function ${ctx.fn("transition")}(subject_type text, subject_id text, to_status text, reason text default null, actor jsonb default null)
|
|
130042
131047
|
returns boolean
|
|
130043
131048
|
language plpgsql
|
|
@@ -130047,18 +131052,8 @@ as $$
|
|
|
130047
131052
|
declare
|
|
130048
131053
|
v_found boolean;
|
|
130049
131054
|
begin
|
|
130050
|
-
if transition.actor is not null then
|
|
130051
|
-
if jsonb_typeof(transition.actor) <> 'object' then
|
|
130052
|
-
${fail$1("STATE_ACTOR_INVALID", "actor must be an object of name, email, ip and userAgent", "22023")}
|
|
130053
|
-
end if;
|
|
130054
|
-
begin
|
|
130055
|
-
perform nullif(transition.actor ->> 'ip', '')::inet;
|
|
130056
|
-
exception when invalid_text_representation then
|
|
130057
|
-
${fail$1("STATE_ACTOR_INVALID", "actor.ip must be an IP address", "22023")}
|
|
130058
|
-
end;
|
|
130059
|
-
end if;
|
|
130060
131055
|
perform set_config('better_supabase.transition_reason', coalesce(transition.reason, ''), true);
|
|
130061
|
-
|
|
131056
|
+
${transitionActorSql("transition.actor", "STATE_ACTOR_INVALID")}
|
|
130062
131057
|
${ctx.hook("before_status_transition", [
|
|
130063
131058
|
["text", "transition.subject_type"],
|
|
130064
131059
|
["text", "transition.subject_id"],
|
|
@@ -133934,6 +134929,8 @@ const TEMPLATES = {
|
|
|
133934
134929
|
build: build$9
|
|
133935
134930
|
};
|
|
133936
134931
|
// src/sql/modules/time-tracking-approvals.ts
|
|
134932
|
+
/** Timesheets this block submits to approvals. */
|
|
134933
|
+
const TIMESHEET_SUBJECT = "timesheet";
|
|
133937
134934
|
/**
|
|
133938
134935
|
* The timesheet functions when weeks go through the approvals block: a
|
|
133939
134936
|
* submitted week opens an approval request, and the final approval locks it.
|
|
@@ -134152,6 +135149,21 @@ $$;
|
|
|
134152
135149
|
${userGrant(`${fn("list_timesheets")}(${ctx.idType}, uuid, text, integer, date)`)}
|
|
134153
135150
|
`;
|
|
134154
135151
|
}
|
|
135152
|
+
/** Approvals decides weeks; per employee, the status column follows. */
|
|
135153
|
+
const TIME_TRACKING_CONTRIBUTES = { approvals: (own) => {
|
|
135154
|
+
if (!own.flag("approvals", true)) return [];
|
|
135155
|
+
if (byEmployee(own)) return [{
|
|
135156
|
+
subject: TIMESHEET_SUBJECT,
|
|
135157
|
+
access: "declared",
|
|
135158
|
+
approve: ({ subjectId, comment, approver }) => `perform ${own.fn("timesheet_approval_decided")}(${subjectId}::uuid, true, ${comment}, ${approver});`,
|
|
135159
|
+
reject: ({ subjectId, comment, approver }) => `perform ${own.fn("timesheet_approval_decided")}(${subjectId}::uuid, false, ${comment}, ${approver});`
|
|
135160
|
+
}];
|
|
135161
|
+
return [{
|
|
135162
|
+
subject: TIMESHEET_SUBJECT,
|
|
135163
|
+
access: "declared",
|
|
135164
|
+
approve: ({ subjectId }) => `perform ${own.fn("approve_timesheet")}(${subjectId}::uuid);`
|
|
135165
|
+
}];
|
|
135166
|
+
} };
|
|
134155
135167
|
// src/sql/modules/time-tracking-rates.ts
|
|
134156
135168
|
/**
|
|
134157
135169
|
* The rate's currency is an uppercase three-letter code (the client checks it
|
|
@@ -134265,7 +135277,9 @@ function statusTimesheetFunctions(ctx, names) {
|
|
|
134265
135277
|
const { entries, timesheets, e, t, read, track, manage, approve } = names;
|
|
134266
135278
|
const { entryJson, timesheetRecord, forbidden, timesheetNotFound, week } = names;
|
|
134267
135279
|
const { ended, running, owner } = names;
|
|
135280
|
+
const linked = names.approvals;
|
|
134268
135281
|
const by = owner.employee;
|
|
135282
|
+
const pendingApproval = (row) => linked === void 0 ? "false" : `exists (select 1 from ${linked.requests} x where x.${linked.a("subjectType")} = ${sqlString(linked.subject)} and x.${linked.a("subjectId")} = ${row}.${t("id")}::text and x.${linked.a("status")} = 'pending')`;
|
|
134269
135283
|
const ownerVar = by ? "v_owner" : "v_user";
|
|
134270
135284
|
const sheetMine = (row) => by ? `(${owner.sheetUser ? `coalesce(${row}.${t("user")} = auth.uid(), false) or ` : ""}${row}.${owner.timesheets} = ${owner.mine(`${row}.${t("tenant")}`)})` : `coalesce(${row}.${t("user")} = auth.uid(), false)`;
|
|
134271
135285
|
const ownerParam = by ? ", employee_id uuid default null" : "";
|
|
@@ -134308,7 +135322,10 @@ begin
|
|
|
134308
135322
|
end if;
|
|
134309
135323
|
if not ${is("v_sheet", ["submitted"])} then
|
|
134310
135324
|
${fail$1("TIMESHEET_NOT_SUBMITTED", "only a submitted week can be decided", "55000")}
|
|
134311
|
-
end if
|
|
135325
|
+
end if;${linked === void 0 ? "" : `
|
|
135326
|
+
if ${pendingApproval("v_sheet")} then
|
|
135327
|
+
${fail$1("TIMESHEET_IN_APPROVAL", "this week is decided through its approval request", "55000")}
|
|
135328
|
+
end if;`}
|
|
134312
135329
|
update ${timesheets} s set ${t("status")} = ${value(status)}${status === "approved" ? `, ${t("approvedAt")} = now()` : ""}${decide(name === "reject_timesheet" ? "reject_timesheet.note" : "null")}
|
|
134313
135330
|
where s.${t("id")} = v_sheet.${t("id")}
|
|
134314
135331
|
returning * into v_sheet;
|
|
@@ -134416,7 +135433,7 @@ ${by ? ` if v_owner is null then
|
|
|
134416
135433
|
if ${is("v_sheet", ["approved"])} then
|
|
134417
135434
|
${fail$1("TIMESHEET_APPROVED", "this week is already approved", "55000")}
|
|
134418
135435
|
end if;
|
|
134419
|
-
if ${is("v_sheet", ["submitted"])} then
|
|
135436
|
+
if ${is("v_sheet", ["submitted"])}${linked === void 0 ? "" : ` and ${pendingApproval("v_sheet")}`} then
|
|
134420
135437
|
${fail$1("TIMESHEET_SUBMITTED", "this week is already waiting for a decision", "55000")}
|
|
134421
135438
|
end if;
|
|
134422
135439
|
${ctx.hook("before_timesheet_submit", [
|
|
@@ -134427,7 +135444,13 @@ ${by ? ` if v_owner is null then
|
|
|
134427
135444
|
update ${timesheets} s
|
|
134428
135445
|
set ${t("status")} = ${value("submitted")}, ${t("note")} = submit_timesheet.note, ${t("submittedAt")} = now()${clearDecision}
|
|
134429
135446
|
where s.${t("id")} = v_sheet.${t("id")}
|
|
134430
|
-
returning * into v_sheet
|
|
135447
|
+
returning * into v_sheet;${linked === void 0 ? "" : `
|
|
135448
|
+
perform ${linked.open}(
|
|
135449
|
+
submit_timesheet.tenant, ${sqlString(linked.subject)}, v_sheet.${t("id")}::text, 'approve',
|
|
135450
|
+
${sqlString(linked.policy)}::jsonb || jsonb_build_object('managerOf', v_owner::text), submit_timesheet.note,
|
|
135451
|
+
jsonb_build_object('userId', ${owner.userOf("v_owner")}, 'employeeId', v_owner, 'week', v_week),
|
|
135452
|
+
${owner.userOf("v_owner")}
|
|
135453
|
+
);`}
|
|
134431
135454
|
${timesheetRecord("timesheet.submitted", "v_sheet", "submitted a timesheet")}
|
|
134432
135455
|
${ctx.hook("after_timesheet_submit", [["uuid", `v_sheet.${t("id")}`]])}
|
|
134433
135456
|
return ${json("v_sheet")};
|
|
@@ -134436,7 +135459,38 @@ $$;
|
|
|
134436
135459
|
${userGrant(`${fn("submit_timesheet")}(${ctx.idType}, date, text${ownerType})`)}
|
|
134437
135460
|
|
|
134438
135461
|
drop function if exists ${fn("approve_timesheet")}(uuid);
|
|
134439
|
-
${decision("approve_timesheet", "approved", "timesheet.approved", "approved a timesheet")}${
|
|
135462
|
+
${decision("approve_timesheet", "approved", "timesheet.approved", "approved a timesheet")}${linked === void 0 ? "" : `
|
|
135463
|
+
-- Applies the final decision of a week's approval request: approvals calls it,
|
|
135464
|
+
-- with the user who decided. It isn't granted to anyone.
|
|
135465
|
+
create or replace function ${fn("timesheet_approval_decided")}(timesheet_id uuid, approved boolean, note text, decided_by uuid)
|
|
135466
|
+
returns void
|
|
135467
|
+
language plpgsql
|
|
135468
|
+
security definer
|
|
135469
|
+
set search_path = ''
|
|
135470
|
+
as $$
|
|
135471
|
+
declare
|
|
135472
|
+
v_sheet ${timesheets}%rowtype;
|
|
135473
|
+
begin
|
|
135474
|
+
update ${timesheets} s set ${t("status")} = case when timesheet_approval_decided.approved then ${value("approved")} else ${value("rejected")} end,
|
|
135475
|
+
${t("approvedAt")} = case when timesheet_approval_decided.approved then now() end${[
|
|
135476
|
+
...ctx.has("timesheets", "decidedBy") ? [`${t("decidedBy")} = timesheet_approval_decided.decided_by`] : [],
|
|
135477
|
+
...ctx.has("timesheets", "decidedAt") ? [`${t("decidedAt")} = now()`] : [],
|
|
135478
|
+
...ctx.has("timesheets", "decisionNote") ? [`${t("decisionNote")} = timesheet_approval_decided.note`] : []
|
|
135479
|
+
].map((set) => `, ${set}`).join("")}
|
|
135480
|
+
where s.${t("id")} = timesheet_approval_decided.timesheet_id and ${is("s", ["submitted"])}
|
|
135481
|
+
returning * into v_sheet;
|
|
135482
|
+
if not found then
|
|
135483
|
+
return;
|
|
135484
|
+
end if;
|
|
135485
|
+
if timesheet_approval_decided.approved then
|
|
135486
|
+
${timesheetRecord("timesheet.approved", "v_sheet", "approved a timesheet")}
|
|
135487
|
+
else
|
|
135488
|
+
${timesheetRecord("timesheet.rejected", "v_sheet", "rejected a timesheet")}
|
|
135489
|
+
end if;
|
|
135490
|
+
end;
|
|
135491
|
+
$$;
|
|
135492
|
+
revoke execute on function ${fn("timesheet_approval_decided")}(uuid, boolean, text, uuid) from public, anon, authenticated;
|
|
135493
|
+
`}${decision("reject_timesheet", "rejected", "timesheet.rejected", "rejected a timesheet")}
|
|
134440
135494
|
-- Unlocks an approved or rejected week so its entries can change and it can
|
|
134441
135495
|
-- be sent again.
|
|
134442
135496
|
create or replace function ${fn("reopen_timesheet")}(timesheet_id uuid)
|
|
@@ -134632,8 +135686,6 @@ ${userGrant(`${fn("resume_timer")}(uuid)`)}
|
|
|
134632
135686
|
`;
|
|
134633
135687
|
}
|
|
134634
135688
|
// src/sql/modules/time-tracking.ts
|
|
134635
|
-
/** Timesheets this block submits to approvals. */
|
|
134636
|
-
const TIMESHEET_SUBJECT = "timesheet";
|
|
134637
135689
|
const WHERE = "blocks.time-tracking.options";
|
|
134638
135690
|
const ENTRY_PAYLOAD = [
|
|
134639
135691
|
"organizationId",
|
|
@@ -134816,10 +135868,12 @@ function timesheetPolicy(ctx) {
|
|
|
134816
135868
|
}
|
|
134817
135869
|
function build$8(ctx) {
|
|
134818
135870
|
if (ctx.mode === "custom") return "";
|
|
134819
|
-
const
|
|
135871
|
+
const employeeLinked = byEmployee(ctx) && ctx.flag("approvals", true);
|
|
135872
|
+
const statusMode = !ctx.flag("approvals", true) || employeeLinked;
|
|
134820
135873
|
const approvals = statusMode ? void 0 : ctx.of("approvals");
|
|
134821
|
-
|
|
134822
|
-
if (
|
|
135874
|
+
const linked = employeeLinked ? ctx.of("approvals") : void 0;
|
|
135875
|
+
if ((approvals ?? linked)?.mode === "custom") throw new TypeError("blocks.time-tracking needs the approvals tables; approvals can't be in custom mode");
|
|
135876
|
+
if (statusMode && !ctx.has("timesheets", "status")) throw new TypeError(`${employeeLinked ? `${WHERE}.owner "employee"` : `${WHERE}.approvals: false`} keeps the timesheet status in a column, so blocks.time-tracking.columns.timesheets.status can't be null`);
|
|
134823
135877
|
const entries = ctx.table("entries");
|
|
134824
135878
|
const timesheets = ctx.table("timesheets");
|
|
134825
135879
|
const e = (column) => ctx.col("entries", column);
|
|
@@ -134835,7 +135889,7 @@ function build$8(ctx) {
|
|
|
134835
135889
|
const { bound, rowSubject, subjectColumns, setSubject, subjectInsert, subjectInsertValues } = entrySubjects(ctx, subjects);
|
|
134836
135890
|
const zone = sqlString(weekTimeZone(ctx));
|
|
134837
135891
|
const userZone = userTimeZoneOf(ctx);
|
|
134838
|
-
const policy = statusMode ? "" : timesheetPolicy(ctx);
|
|
135892
|
+
const policy = statusMode && !employeeLinked ? "" : timesheetPolicy(ctx);
|
|
134839
135893
|
const durationMode = durationEntries(ctx);
|
|
134840
135894
|
const { allowOverlap, manyTimers } = timerOptions(ctx);
|
|
134841
135895
|
if (durationMode && (ctx.owns("entries") || !ctx.has("entries", "seconds") || !ctx.has("entries", "runningSince"))) throw new TypeError("blocks.time-tracking.columns.entries.endedAt can be null only over your own entries table, with seconds (a writable duration column) and runningSince mapped");
|
|
@@ -135346,7 +136400,14 @@ ${statusMode ? statusTimesheetFunctions(ctx, {
|
|
|
135346
136400
|
week: (at, user) => weekOf(at, user),
|
|
135347
136401
|
ended,
|
|
135348
136402
|
running,
|
|
135349
|
-
owner: owner.status
|
|
136403
|
+
owner: owner.status,
|
|
136404
|
+
...linked === void 0 ? {} : { approvals: {
|
|
136405
|
+
open: linked.fn("open_approval"),
|
|
136406
|
+
requests: linked.table("requests"),
|
|
136407
|
+
a: (column) => linked.col("requests", column),
|
|
136408
|
+
subject: TIMESHEET_SUBJECT,
|
|
136409
|
+
policy
|
|
136410
|
+
} }
|
|
135350
136411
|
}) : approvalTimesheetFunctions(ctx, {
|
|
135351
136412
|
entries,
|
|
135352
136413
|
timesheets,
|
|
@@ -135444,18 +136505,13 @@ function contract$8(ctx) {
|
|
|
135444
136505
|
}
|
|
135445
136506
|
];
|
|
135446
136507
|
}
|
|
135447
|
-
const CONTRIBUTES = { approvals: (own) => own.flag("approvals", true) ? [{
|
|
135448
|
-
subject: TIMESHEET_SUBJECT,
|
|
135449
|
-
access: "declared",
|
|
135450
|
-
approve: ({ subjectId }) => `perform ${own.fn("approve_timesheet")}(${subjectId}::uuid);`
|
|
135451
|
-
}] : [] };
|
|
135452
136508
|
const REQUIRES = [
|
|
135453
136509
|
"memberships",
|
|
135454
136510
|
"permissions",
|
|
135455
136511
|
"approvals"
|
|
135456
136512
|
];
|
|
135457
136513
|
const TIME_TRACKING = {
|
|
135458
|
-
contributes:
|
|
136514
|
+
contributes: TIME_TRACKING_CONTRIBUTES,
|
|
135459
136515
|
name: "time-tracking",
|
|
135460
136516
|
scopes: ["tenant"],
|
|
135461
136517
|
title: "Time tracking",
|