better-supabase 0.40.0 → 0.41.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-kHGNXFsd.d.ts} +1 -1
- package/dist/{approvals-CXW3yFWZ.d.ts → approvals-CTVaWq1O.d.ts} +74 -13
- package/dist/{approvals-D8gR1R8R.js → approvals-Qjn42OAZ.js} +35 -17
- package/dist/{assistant-5heV2GeR.d.ts → assistant-B1p5mYaM.d.ts} +2 -2
- package/dist/{authorization-Ul_ApMYW.d.ts → authorization-CS5Q1V7A.d.ts} +33 -7
- package/dist/{automations-D4QTP8nI.js → automations-CJhRmPmq.js} +3 -1
- package/dist/{bind-B2GlypM6.d.ts → bind-XrFxNm5r.d.ts} +4 -4
- package/dist/{block-env-Bcr-jEA1.d.ts → block-env-CHFHOjvz.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-Bz95_dqA.js} +1 -1
- package/dist/{block-tables-nkIjJ1ly.d.ts → block-tables-EXcmuOJT.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 +4 -2
- 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 +7 -3
- package/dist/blocks/invoices/index.js +4 -2
- 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 +2 -1
- 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-BVs8Ym-K.js → add-BGErz-yb.js} +10 -10
- package/dist/cli/add-CoP8iie6.js +1 -0
- package/dist/cli/{add-DP1ct-7e.js → add-DU5HAq6w.js} +2 -2
- package/dist/cli/{app-table-files-gjMyFqH4.js → app-table-files-Drzpekpt.js} +2 -2
- package/dist/cli/{app-tables-B26PHK75.js → app-tables-dZpH63--.js} +2 -2
- package/dist/cli/{backfill-CP_LpTK2.js → backfill-B-p-19g6.js} +1 -1
- package/dist/cli/bin.js +1 -1
- package/dist/cli/{blocks-CpBLp57s.js → blocks-Ews-FZZO.js} +1 -1
- package/dist/cli/{blocks-Ewp49Kbm.js → blocks-iUjNl5yJ.js} +1 -1
- package/dist/cli/{cache-BxxtUXVN.js → cache-JT4JhdmX.js} +1 -1
- package/dist/cli/{codemod-CGCxMEyD.js → codemod-KIxYiazj.js} +1 -1
- package/dist/cli/{content-mapper-DngBJv4r.js → content-mapper-DkXzxt6f.js} +2 -2
- package/dist/cli/{doctor-3dcMraMn.js → doctor-VWanOD74.js} +15 -15
- package/dist/cli/{gen-DrXxFwUU.js → gen-_lBdTgaR.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-Cm6n4u_3.js} +8 -8
- package/dist/cli/{live-CHTbAqdS.js → live-D4iSuTmS.js} +2 -2
- package/dist/cli/{mcp-BbmhntrR.js → mcp-CHYX7utI.js} +2 -2
- package/dist/cli/{metadata-BS56R_eb.js → metadata-DLba0VjH.js} +3 -3
- package/dist/cli/{migrate-DV6a9-jI.js → migrate-nQhh0nEJ.js} +1 -1
- package/dist/cli/{migration-safety-Ce9IQwmJ.js → migration-safety-C2d3BSTf.js} +1 -1
- package/dist/cli/{migrations-CCCnMhmM.js → migrations-BOmMcme9.js} +2 -2
- package/dist/cli/{module-migration-C0cAzpNa.js → module-migration-DSDB473C.js} +2 -2
- package/dist/cli/{powersync-OIIpG-y_.js → powersync-CAHvPkkb.js} +3 -3
- package/dist/cli/powersync-nH-NLDjy.js +1 -0
- package/dist/cli/{print-BGF3d6O2.js → print-CahE8HYK.js} +2 -2
- package/dist/cli/{providers-fEzlYSLs.js → providers-CL5Z5Uj4.js} +1 -1
- package/dist/cli/{prune-workflows-Bx7J5T3a.js → prune-workflows-C9xO0fRU.js} +1 -1
- package/dist/cli/{remove-Ds4N6WvD.js → remove-DIy7gthm.js} +5 -5
- package/dist/cli/{render-BeZToAp-.js → render-CoCZr3Ru.js} +3 -3
- package/dist/cli/{run-iUmtksq5.js → run-BBj137Fn.js} +27 -27
- package/dist/cli/{run-DR0sTyNQ.js → run-CVw8hmLk.js} +9 -9
- package/dist/cli/{shared-BCWYvKeR.js → shared-BdKeo7xp.js} +1 -1
- package/dist/cli/{snapshot-CfgRxTQq.js → snapshot-P2ww2xCt.js} +2 -2
- package/dist/cli/{source-Ct3ZCy6p.js → source-BCs4oBl2.js} +1 -1
- package/dist/cli/{spec-1eEq2P4T.js → spec-oPbt9sbZ.js} +1 -1
- package/dist/cli/{spec-9vb-or-k.js → spec-uCpXPLoF.js} +2 -2
- package/dist/cli/{sql-layout-cYsnyjRf.js → sql-layout-Bsnge2oW.js} +2 -2
- package/dist/cli/{sync-XpcpINnx.js → sync-Cv7iBRhe.js} +4 -4
- package/dist/cli/{upgrade-A18FY5Iy.js → upgrade-C6jWNxkc.js} +2 -2
- package/dist/cli/{upgrade-DXhyb2jV.js → upgrade-DV7jTRdh.js} +5 -5
- package/dist/cli/{version-PcwPOm4G.js → version-Hza4Q2PB.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-BRGMUEE2.js → config-B7hnJFxh.js} +1 -1
- package/dist/{config-qqAfS_1_.js → config-DwXYtmwt.js} +3 -3
- package/dist/{connectors-DDsdz-cn.d.ts → connectors-OMJkoAP6.d.ts} +2 -2
- package/dist/{context-dHluCmud.d.ts → context-tFoygone.d.ts} +2 -2
- package/dist/contract/index.d.ts +4 -4
- package/dist/{controller-BQXgMwWN.d.ts → controller-phhsPHSz.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-LfW6S2RW.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-CMWRPBmF.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-BKz-E3Mv.d.ts → index-B-HuxATL.d.ts} +8 -8
- package/dist/{index-xmb6YGTg.d.ts → index-B21Pim3I.d.ts} +2 -2
- package/dist/{index-DhcLJAtX.d.ts → index-BXkPvYzd.d.ts} +1 -1
- package/dist/{index-IrJQqPeQ.d.ts → index-D-uiT4Qz.d.ts} +3 -3
- package/dist/{index-g_eFnFqo.d.ts → index-RZqQdq1G.d.ts} +2 -2
- package/dist/{index-y70eTezB.d.ts → index-X5igfnIi.d.ts} +2 -2
- package/dist/{index-CpZ4WDDJ.d.ts → index-fmrLdtVT.d.ts} +1 -1
- package/dist/{instances-DqEZrffE.js → instances-DJOknCJ0.js} +8 -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-Cm4mSrAX.d.ts} +1 -1
- package/dist/{options-Bgnm4pTD.js → options-CzxG2Phg.js} +3 -0
- 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-r0Cxhxos.d.ts} +1 -1
- package/dist/{ports-1M1E_r2n.d.ts → ports-BJJJmfWK.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-U47pzJMK.js} +2 -2
- package/dist/{project-Y2wW_nr_.js → project-Dng8tO8S.js} +5 -5
- package/dist/{push-token-DKImhAca.d.ts → push-token-CA31xmQr.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-BudVz33a.js} +1113 -375
- 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-C2vnB0wX.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-CKN3kmoi.d.ts} +1 -1
- package/dist/{types-DtiDatvu.d.ts → types-D--4dv5K.d.ts} +3 -3
- package/dist/{types-B42S7qfO.d.ts → types-D8Tltfdq.d.ts} +2 -2
- 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-0dXuJMuE.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-CUt0E4v6.d.ts → workflow-sdk-DzKQo265.d.ts} +2 -2
- package/dist/{workflow-sdk-6psRpDIo.js → workflow-sdk-vXuxBSrk.js} +20 -1
- 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 +22 -0
- 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-Bz95_dqA.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-DJOknCJ0.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 userGrant, at as replaceColumnCheck, b as MONTHLY_PARTITIONS, c as accessModel, ct as serviceGrant, d as moduleOperations, dt as shortHash, et as quotedTable$1, f as modulePermission, ft as splitTable$1, g as roleScopeIs, gt as updatedAt, h as roleNames, ht as updateExtraColumns, it as renameSql, j as batchFunction, k as addForeignKey, l as hasPlatformRoles, lt as serviceOnly$1, m as providerPlatformRoles, mt as triggerGrant, n as WORKFLOW_SDK_WORLD, nt as recordTrigger, o as MODULE_PERMISSION_SCOPES, ot as revokeTable, p as modulePermissionKey, pt as transitionActorSql, q as memberAddedRecord, rt as registerPartitions, s as OPERATIONS, st as schemaPreamble, tt as raise$1, u as isOperationModule$1, ut as sha256Hex$1, v as tenantScope, vt as withExtraFields, w as SERVICE_CALLER$1, x as NOTHING, y as EQUIVALENT_TRIGGERS, yt as writeExtraColumns, z as ensureCheck } from "./workflow-sdk-vXuxBSrk.js";
|
|
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-CzxG2Phg.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";
|
|
@@ -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,6 +3521,8 @@ 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 = "*";
|
|
3524
3526
|
const KEY$1 = /^[a-z][a-z0-9_-]*$/;
|
|
3525
3527
|
const UUID$7 = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
|
|
3526
3528
|
const DURATION = /^P(?=\d|T\d)(\d+Y)?(\d+M)?(\d+W)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?$/;
|
|
@@ -3555,20 +3557,44 @@ function stepOf(value, where) {
|
|
|
3555
3557
|
if (!isFields(value)) throw new TypeError(`${where} must be an object`);
|
|
3556
3558
|
const approvers = approversOf(value["approvers"], where);
|
|
3557
3559
|
const required = value["required"] ?? 1;
|
|
3560
|
+
const escalation = escalationOf(value, where);
|
|
3558
3561
|
if (required === "all") {
|
|
3559
|
-
|
|
3562
|
+
const only = Object.keys(approvers);
|
|
3563
|
+
if (only.length === 1 && approvers.permission !== void 0) return {
|
|
3564
|
+
approvers,
|
|
3565
|
+
required: "all",
|
|
3566
|
+
...escalation
|
|
3567
|
+
};
|
|
3568
|
+
if (only.length !== 1 || approvers.users === void 0) throw new TypeError(`${where}.required "all" needs approvers.users or approvers.permission and nothing else`);
|
|
3560
3569
|
return {
|
|
3561
3570
|
approvers,
|
|
3562
|
-
required: approvers.users.length
|
|
3571
|
+
required: approvers.users.length,
|
|
3572
|
+
...escalation
|
|
3563
3573
|
};
|
|
3564
3574
|
}
|
|
3565
3575
|
if (typeof required !== "number" || !Number.isInteger(required) || required < 1) throw new TypeError(`${where}.required must be a whole number or "all"`);
|
|
3566
3576
|
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
3577
|
return {
|
|
3568
3578
|
approvers,
|
|
3569
|
-
required
|
|
3579
|
+
required,
|
|
3580
|
+
...escalation
|
|
3581
|
+
};
|
|
3582
|
+
}
|
|
3583
|
+
function escalationOf(value, where) {
|
|
3584
|
+
const after = value["escalateAfter"];
|
|
3585
|
+
const to = value["escalateTo"];
|
|
3586
|
+
if (after === void 0 && to === void 0) return {};
|
|
3587
|
+
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`);
|
|
3588
|
+
return {
|
|
3589
|
+
escalateAfter: after,
|
|
3590
|
+
escalateTo: approversOf(to, `${where}.escalateTo`)
|
|
3570
3591
|
};
|
|
3571
3592
|
}
|
|
3593
|
+
function effectsOf(value, where) {
|
|
3594
|
+
if (value === void 0) return [];
|
|
3595
|
+
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`);
|
|
3596
|
+
return [...new Set(value.map(String))];
|
|
3597
|
+
}
|
|
3572
3598
|
function runOf(value, where) {
|
|
3573
3599
|
if (value === void 0) return;
|
|
3574
3600
|
if (isFields(value) && typeof value["transition"] === "string") return {
|
|
@@ -3586,7 +3612,7 @@ function runOf(value, where) {
|
|
|
3586
3612
|
* entry that tenant policies tighten) may have no steps.
|
|
3587
3613
|
*/
|
|
3588
3614
|
function policyOf(subjectType, action, value, where = `${WHERE$18}.${subjectType}.${action}`, floor = false) {
|
|
3589
|
-
if (!KEY$1.test(action)) throw new TypeError(`${where} has an invalid name`);
|
|
3615
|
+
if (!KEY$1.test(action) && action !== ANY_ACTION) throw new TypeError(`${where} has an invalid name`);
|
|
3590
3616
|
if (!isFields(value)) throw new TypeError(`${where} must be an object`);
|
|
3591
3617
|
const steps = value["steps"];
|
|
3592
3618
|
if (!Array.isArray(steps) || steps.length === 0 && !floor) throw new TypeError(`${where}.steps must be a non-empty list`);
|
|
@@ -3597,6 +3623,7 @@ function policyOf(subjectType, action, value, where = `${WHERE$18}.${subjectType
|
|
|
3597
3623
|
const selfApproval = value["selfApproval"] ?? false;
|
|
3598
3624
|
if (typeof selfApproval !== "boolean") throw new TypeError(`${where}.selfApproval must be a boolean`);
|
|
3599
3625
|
const run = runOf(value["run"], where);
|
|
3626
|
+
const effects = effectsOf(value["effects"], where);
|
|
3600
3627
|
return {
|
|
3601
3628
|
subjectType,
|
|
3602
3629
|
action,
|
|
@@ -3604,7 +3631,8 @@ function policyOf(subjectType, action, value, where = `${WHERE$18}.${subjectType
|
|
|
3604
3631
|
mode,
|
|
3605
3632
|
selfApproval,
|
|
3606
3633
|
...typeof expiresIn === "string" ? { expiresIn } : {},
|
|
3607
|
-
...run === void 0 ? {} : { run }
|
|
3634
|
+
...run === void 0 ? {} : { run },
|
|
3635
|
+
...effects.length === 0 ? {} : { effects }
|
|
3608
3636
|
};
|
|
3609
3637
|
}
|
|
3610
3638
|
/** `options.policies`: subject type, then action, then the policy. */
|
|
@@ -3628,16 +3656,34 @@ function policySnapshot(policy) {
|
|
|
3628
3656
|
selfApproval: policy.selfApproval,
|
|
3629
3657
|
expiresIn: policy.expiresIn ?? null,
|
|
3630
3658
|
run: policy.run ?? null,
|
|
3631
|
-
...policy.mode === "confirm" ? { mode: policy.mode } : {}
|
|
3659
|
+
...policy.mode === "confirm" ? { mode: policy.mode } : {},
|
|
3660
|
+
...policy.effects === void 0 ? {} : { effects: policy.effects }
|
|
3632
3661
|
});
|
|
3633
3662
|
}
|
|
3634
|
-
/**
|
|
3663
|
+
/**
|
|
3664
|
+
* The policy snapshot for the requested subject type and action, as SQL. A
|
|
3665
|
+
* floor for action `*` covers the subject type's other actions.
|
|
3666
|
+
*/
|
|
3635
3667
|
function policyCase(policies) {
|
|
3636
3668
|
if (policies.length === 0) return "null::jsonb";
|
|
3637
|
-
|
|
3638
|
-
${
|
|
3669
|
+
const cases = (key, items) => `case ${key}
|
|
3670
|
+
${items.map((policy) => ` when ${sqlString(`${policy.subjectType}:${policy.action}`)} then ${sqlString(policySnapshot(policy))}::jsonb`).join("\n")}
|
|
3639
3671
|
else null::jsonb
|
|
3640
3672
|
end`;
|
|
3673
|
+
const exact = cases("approval_policy.subject_type || ':' || approval_policy.action", policies);
|
|
3674
|
+
const any = policies.filter((policy) => policy.action === ANY_ACTION);
|
|
3675
|
+
return any.length === 0 ? exact : `coalesce(${exact}, ${cases("approval_policy.subject_type || ':*'", any)})`;
|
|
3676
|
+
}
|
|
3677
|
+
/**
|
|
3678
|
+
* The floors as a jsonb list of `{ subjectType, action, effects }`, for the
|
|
3679
|
+
* checks that a tenant or platform policy tightens one.
|
|
3680
|
+
*/
|
|
3681
|
+
function floorsJson(policies) {
|
|
3682
|
+
return `${sqlString(JSON.stringify(policies.map((policy) => ({
|
|
3683
|
+
subjectType: policy.subjectType,
|
|
3684
|
+
action: policy.action,
|
|
3685
|
+
effects: policy.effects ?? []
|
|
3686
|
+
}))))}::jsonb`;
|
|
3641
3687
|
}
|
|
3642
3688
|
/**
|
|
3643
3689
|
* Throws when a policy names the requester's manager without the employees
|
|
@@ -8277,6 +8323,113 @@ function subjectScope(ctx, provider, type, subject) {
|
|
|
8277
8323
|
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
8324
|
return scope;
|
|
8279
8325
|
}
|
|
8326
|
+
// src/sql/modules/approvals-conditions.ts
|
|
8327
|
+
/**
|
|
8328
|
+
* `"rules"` (default) matches conditions through the automations block's rule
|
|
8329
|
+
* fields; `"payload"` matches them against the request payload in this module.
|
|
8330
|
+
*/
|
|
8331
|
+
function approvalConditions(ctx) {
|
|
8332
|
+
const raw = ctx.option("conditions") ?? "rules";
|
|
8333
|
+
if (raw !== "rules" && raw !== "payload") throw new TypeError("blocks.approvals.options.conditions must be \"rules\" or \"payload\"");
|
|
8334
|
+
return raw;
|
|
8335
|
+
}
|
|
8336
|
+
/**
|
|
8337
|
+
* `approval_condition(node, payload)`: a filter tree matched against a request
|
|
8338
|
+
* payload, by path. It visits every node, so a call with an empty payload also
|
|
8339
|
+
* checks the tree, and it refuses an unknown node or operator.
|
|
8340
|
+
*/
|
|
8341
|
+
function approvalConditionSql(ctx) {
|
|
8342
|
+
const fn = ctx.fn("approval_condition");
|
|
8343
|
+
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");
|
|
8344
|
+
return `
|
|
8345
|
+
-- Matches a filter tree (groups of rules with a path, an operator and a value)
|
|
8346
|
+
-- against a request payload. A number compares as a number when the payload
|
|
8347
|
+
-- value is numeric, anything else as text.
|
|
8348
|
+
create or replace function ${fn}(node jsonb, payload jsonb)
|
|
8349
|
+
returns boolean
|
|
8350
|
+
language plpgsql
|
|
8351
|
+
immutable
|
|
8352
|
+
set search_path = ''
|
|
8353
|
+
as $$
|
|
8354
|
+
declare
|
|
8355
|
+
v_child jsonb;
|
|
8356
|
+
v_any boolean := false;
|
|
8357
|
+
v_all boolean := true;
|
|
8358
|
+
v_result boolean;
|
|
8359
|
+
v_op text;
|
|
8360
|
+
v_value jsonb;
|
|
8361
|
+
v_at jsonb;
|
|
8362
|
+
v_text text;
|
|
8363
|
+
v_other text;
|
|
8364
|
+
v_numeric boolean;
|
|
8365
|
+
v_empty boolean;
|
|
8366
|
+
begin
|
|
8367
|
+
if jsonb_typeof(node) is distinct from 'object' then
|
|
8368
|
+
${invalid}
|
|
8369
|
+
end if;
|
|
8370
|
+
if node ->> 'type' = 'group' then
|
|
8371
|
+
if jsonb_typeof(node -> 'rules') is distinct from 'array'
|
|
8372
|
+
or coalesce(node ->> 'combinator', 'and') not in ('and', 'or') then
|
|
8373
|
+
${invalid}
|
|
8374
|
+
end if;
|
|
8375
|
+
for v_child in select e.value from jsonb_array_elements(node -> 'rules') e loop
|
|
8376
|
+
v_result := ${fn}(v_child, payload);
|
|
8377
|
+
v_any := v_any or v_result;
|
|
8378
|
+
v_all := v_all and v_result;
|
|
8379
|
+
end loop;
|
|
8380
|
+
return case when coalesce(node ->> 'combinator', 'and') = 'or' then v_any else v_all end;
|
|
8381
|
+
end if;
|
|
8382
|
+
if node ->> 'type' is distinct from 'rule' or jsonb_typeof(node -> 'path') is distinct from 'array' then
|
|
8383
|
+
${invalid}
|
|
8384
|
+
end if;
|
|
8385
|
+
v_op := coalesce(node ->> 'operator', '');
|
|
8386
|
+
v_value := node -> 'value';
|
|
8387
|
+
v_at := coalesce(payload, '{}'::jsonb) #> array(select jsonb_array_elements_text(node -> 'path'));
|
|
8388
|
+
v_text := v_at #>> '{}';
|
|
8389
|
+
v_other := v_value #>> '{}';
|
|
8390
|
+
v_numeric := jsonb_typeof(v_value) = 'number' and v_text ~ '^-?[0-9]+(\\.[0-9]+)?$';
|
|
8391
|
+
v_empty := v_at is null or v_at = 'null'::jsonb or v_text = '' or v_at = '[]'::jsonb;
|
|
8392
|
+
v_result := case
|
|
8393
|
+
when v_op = '' then true
|
|
8394
|
+
when v_op = 'empty' then v_empty
|
|
8395
|
+
when v_op = 'not_empty' then not v_empty
|
|
8396
|
+
when v_op in ('is', 'eq') then case when v_numeric then v_text::numeric = v_other::numeric else v_text = v_other end
|
|
8397
|
+
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)
|
|
8398
|
+
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
|
|
8399
|
+
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
|
|
8400
|
+
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
|
|
8401
|
+
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
|
|
8402
|
+
when v_op in ('between', 'not_between') then
|
|
8403
|
+
jsonb_typeof(v_value) = 'array' and (
|
|
8404
|
+
case when jsonb_typeof(v_value -> 0) = 'number' and v_text ~ '^-?[0-9]+(\\.[0-9]+)?$'
|
|
8405
|
+
then v_text::numeric between (v_value ->> 0)::numeric and (v_value ->> 1)::numeric
|
|
8406
|
+
else v_text between v_value ->> 0 and v_value ->> 1 end
|
|
8407
|
+
) = (v_op = 'between')
|
|
8408
|
+
when v_op in ('is_any_of', 'is_none_of') then
|
|
8409
|
+
jsonb_typeof(v_value) = 'array'
|
|
8410
|
+
and exists (select 1 from jsonb_array_elements_text(v_value) e where e = v_text) = (v_op = 'is_any_of')
|
|
8411
|
+
when v_op in ('contains', 'not_contains') then
|
|
8412
|
+
(case when jsonb_typeof(v_at) = 'array' then v_at @> jsonb_build_array(v_value)
|
|
8413
|
+
else strpos(lower(v_text), lower(v_other)) > 0 end) = (v_op = 'contains')
|
|
8414
|
+
when v_op = 'starts_with' then left(lower(v_text), length(v_other)) = lower(v_other)
|
|
8415
|
+
when v_op = 'ends_with' then right(lower(v_text), length(v_other)) = lower(v_other)
|
|
8416
|
+
when v_op in ('has_any_of', 'has_none_of') then
|
|
8417
|
+
jsonb_typeof(v_at) = 'array' and jsonb_typeof(v_value) = 'array'
|
|
8418
|
+
and exists (select 1 from jsonb_array_elements(v_value) e where v_at @> jsonb_build_array(e.value)) = (v_op = 'has_any_of')
|
|
8419
|
+
when v_op = 'has_all_of' then
|
|
8420
|
+
jsonb_typeof(v_at) = 'array' and jsonb_typeof(v_value) = 'array' and v_at @> v_value
|
|
8421
|
+
end;
|
|
8422
|
+
if v_op not in ('', 'empty', 'not_empty', 'is', 'eq', 'is_not', 'neq', 'gt', 'is_after', 'gte', 'is_on_or_after', 'lt', 'is_before',
|
|
8423
|
+
'lte', 'is_on_or_before', 'between', 'not_between', 'is_any_of', 'is_none_of', 'contains', 'not_contains', 'starts_with',
|
|
8424
|
+
'ends_with', 'has_any_of', 'has_none_of', 'has_all_of') then
|
|
8425
|
+
${invalid}
|
|
8426
|
+
end if;
|
|
8427
|
+
v_result := coalesce(v_result, false);
|
|
8428
|
+
return case when coalesce((node ->> 'negated')::boolean, false) then not v_result else v_result end;
|
|
8429
|
+
end;
|
|
8430
|
+
$$;
|
|
8431
|
+
revoke execute on function ${fn}(jsonb, jsonb) from public, anon, authenticated;`;
|
|
8432
|
+
}
|
|
8280
8433
|
// src/sql/modules/over-app.ts
|
|
8281
8434
|
/** Postgres truncates longer identifiers, so two long index names could meet. */
|
|
8282
8435
|
const MAX_IDENTIFIER = 63;
|
|
@@ -8326,7 +8479,8 @@ const TENANT_POLICY_TABLES = { policies: {
|
|
|
8326
8479
|
"conditions",
|
|
8327
8480
|
"expiresIn",
|
|
8328
8481
|
"createdBy",
|
|
8329
|
-
"updatedAt"
|
|
8482
|
+
"updatedAt",
|
|
8483
|
+
"effect"
|
|
8330
8484
|
],
|
|
8331
8485
|
typed: ["mode"],
|
|
8332
8486
|
columns: {
|
|
@@ -8343,11 +8497,33 @@ const TENANT_POLICY_TABLES = { policies: {
|
|
|
8343
8497
|
enabled: "enabled",
|
|
8344
8498
|
createdBy: "created_by",
|
|
8345
8499
|
createdAt: "created_at",
|
|
8346
|
-
updatedAt: "updated_at"
|
|
8500
|
+
updatedAt: "updated_at",
|
|
8501
|
+
effect: "effect"
|
|
8347
8502
|
}
|
|
8348
8503
|
} };
|
|
8349
8504
|
/** Whether `blocks.approvals.options.tenantPolicies` is on. */
|
|
8350
8505
|
const tenantPoliciesOn = (ctx) => ctx.flag("tenantPolicies", false);
|
|
8506
|
+
/**
|
|
8507
|
+
* Whether `blocks.approvals.options.platformPolicies` is on: rows of the tenant
|
|
8508
|
+
* policies table without a tenant are platform policies, edited at runtime by
|
|
8509
|
+
* platform staff, that apply to every organization and can stand in for a
|
|
8510
|
+
* config floor.
|
|
8511
|
+
*/
|
|
8512
|
+
function platformPoliciesOn(ctx) {
|
|
8513
|
+
const on = ctx.flag("platformPolicies", false);
|
|
8514
|
+
if (on && !tenantPoliciesOn(ctx)) throw new TypeError("blocks.approvals.options.platformPolicies needs blocks.approvals.options.tenantPolicies");
|
|
8515
|
+
return on;
|
|
8516
|
+
}
|
|
8517
|
+
/**
|
|
8518
|
+
* `blocks.approvals.options.tenantless`: the subject types whose requests may
|
|
8519
|
+
* have no organization, for personal or platform actions.
|
|
8520
|
+
*/
|
|
8521
|
+
const tenantlessTypes = (ctx) => ctx.list("tenantless", []);
|
|
8522
|
+
/** SQL that is true when `type` may be filed without an organization. */
|
|
8523
|
+
function tenantlessType(ctx, type) {
|
|
8524
|
+
const types = tenantlessTypes(ctx);
|
|
8525
|
+
return types.length === 0 ? "false" : `${type} in (${types.map(sqlString).join(", ")})`;
|
|
8526
|
+
}
|
|
8351
8527
|
/** The employees module when it renders tables the approvals SQL can read. */
|
|
8352
8528
|
const employeesOf = (ctx) => ctx.installed("employees") && ctx.of("employees").mode !== "custom" ? ctx.of("employees") : void 0;
|
|
8353
8529
|
/**
|
|
@@ -8402,8 +8578,14 @@ $$;
|
|
|
8402
8578
|
revoke execute on function ${signature} from public, anon, authenticated;`;
|
|
8403
8579
|
const p = (column) => ctx.col("policies", column);
|
|
8404
8580
|
const has = (column) => ctx.has("policies", column);
|
|
8405
|
-
const
|
|
8406
|
-
const
|
|
8581
|
+
const platform = platformPoliciesOn(ctx);
|
|
8582
|
+
const payload = approvalConditions(ctx) === "payload";
|
|
8583
|
+
const rules = !payload && ctx.installed("automations") ? ctx.of("automations") : void 0;
|
|
8584
|
+
const conditions = has("conditions") ? payload ? `
|
|
8585
|
+
if v_row.${p("conditions")} is not null
|
|
8586
|
+
and not ${fn("approval_condition")}(v_row.${p("conditions")}, coalesce(approval_effective_policy.subject, '{}'::jsonb)) then
|
|
8587
|
+
continue;
|
|
8588
|
+
end if;` : rules === void 0 ? `
|
|
8407
8589
|
if v_row.${p("conditions")} is not null then
|
|
8408
8590
|
continue;
|
|
8409
8591
|
end if;` : `
|
|
@@ -8415,11 +8597,17 @@ revoke execute on function ${signature} from public, anon, authenticated;`;
|
|
|
8415
8597
|
continue;
|
|
8416
8598
|
end if;
|
|
8417
8599
|
end if;` : "";
|
|
8600
|
+
const missingFloor = platform ? `
|
|
8601
|
+
v_floor := '{"steps": [], "selfApproval": true, "expiresIn": null, "run": null}'::jsonb;
|
|
8602
|
+
v_matched := false;` : `
|
|
8603
|
+
return null;`;
|
|
8418
8604
|
return `
|
|
8419
8605
|
-- The policy a request snapshots: the options.policies floor, tightened by
|
|
8420
8606
|
-- every enabled tenant policy whose conditions match the request payload.
|
|
8421
|
-
--
|
|
8422
|
-
--
|
|
8607
|
+
-- A policy matches its subject type and action, \`*\` for any, and the
|
|
8608
|
+
-- floor's effects when it names one. Steps add up, the stricter mode wins,
|
|
8609
|
+
-- self-approval needs every policy to allow it and the shortest expiry
|
|
8610
|
+
-- applies.${platform ? "\n-- Platform policies (no tenant) come first and stand in for a missing floor." : ""}
|
|
8423
8611
|
create or replace function ${fn("approval_effective_policy")}(tenant ${ctx.idType}, subject_type text, action text, subject jsonb default '{}'::jsonb)
|
|
8424
8612
|
returns jsonb
|
|
8425
8613
|
language plpgsql
|
|
@@ -8437,33 +8625,45 @@ declare
|
|
|
8437
8625
|
v_expires interval;
|
|
8438
8626
|
v_ids jsonb := '[]'::jsonb;
|
|
8439
8627
|
v_fields jsonb;
|
|
8628
|
+
v_effects jsonb;
|
|
8629
|
+
v_matched boolean := true;
|
|
8440
8630
|
begin
|
|
8441
|
-
if v_floor is null then
|
|
8442
|
-
return null;
|
|
8631
|
+
if v_floor is null then${missingFloor}
|
|
8443
8632
|
end if;
|
|
8633
|
+
v_effects := coalesce(v_floor -> 'effects', '[]'::jsonb);
|
|
8444
8634
|
v_steps := coalesce(v_floor -> 'steps', '[]'::jsonb);
|
|
8445
8635
|
v_level := ${level("coalesce(v_floor ->> 'mode', 'authorize')", "v_steps")};
|
|
8446
8636
|
v_self := coalesce((v_floor ->> 'selfApproval')::boolean, false);
|
|
8447
8637
|
v_expires := (v_floor ->> 'expiresIn')::interval;
|
|
8448
8638
|
for v_row in
|
|
8449
8639
|
select * from ${ctx.table("policies")} x
|
|
8450
|
-
where x.${p("tenant")} = approval_effective_policy.tenant
|
|
8451
|
-
and x.${p("
|
|
8452
|
-
|
|
8453
|
-
|
|
8640
|
+
where (x.${p("tenant")} = approval_effective_policy.tenant${platform ? ` or x.${p("tenant")} is null` : ""})
|
|
8641
|
+
and (x.${p("subjectType")} = approval_effective_policy.subject_type or x.${p("subjectType")} = '*')
|
|
8642
|
+
and (x.${p("action")} = approval_effective_policy.action or x.${p("action")} = '*')${has("effect") ? `
|
|
8643
|
+
and (x.${p("effect")} is null or v_effects ? x.${p("effect")})` : ""}
|
|
8644
|
+
and x.${p("enabled")}
|
|
8645
|
+
order by ${platform ? `x.${p("tenant")} is null desc, ` : ""}x.${p("createdAt")}, x.${p("id")}
|
|
8646
|
+
loop${platform ? `
|
|
8647
|
+
if not v_matched and v_row.${p("tenant")} is not null then
|
|
8648
|
+
continue;
|
|
8649
|
+
end if;` : ""}${conditions}
|
|
8650
|
+
v_matched := true;
|
|
8454
8651
|
v_steps := v_steps || v_row.${p("steps")};
|
|
8455
8652
|
v_level := greatest(v_level, ${level(`v_row.${p("mode")}::text`, `v_row.${p("steps")}`)});
|
|
8456
8653
|
v_self := v_self and v_row.${p("selfApproval")};${has("expiresIn") ? `
|
|
8457
8654
|
v_expires := least(v_expires, v_row.${p("expiresIn")});` : ""}
|
|
8458
8655
|
v_ids := v_ids || to_jsonb(v_row.${p("id")});
|
|
8459
8656
|
end loop;
|
|
8657
|
+
if not v_matched then
|
|
8658
|
+
return null;
|
|
8659
|
+
end if;
|
|
8460
8660
|
return jsonb_build_object(
|
|
8461
8661
|
'steps', v_steps, 'selfApproval', v_self, 'expiresIn', v_expires::text, 'run', v_floor -> 'run',
|
|
8462
8662
|
'mode', case when v_level = 1 then 'confirm' else 'authorize' end, 'policies', v_ids
|
|
8463
|
-
);
|
|
8663
|
+
) || case when jsonb_array_length(v_effects) > 0 then jsonb_build_object('effects', v_effects) else '{}'::jsonb end;
|
|
8464
8664
|
end;
|
|
8465
8665
|
$$;
|
|
8466
|
-
revoke execute on function ${signature} from public, anon, authenticated
|
|
8666
|
+
revoke execute on function ${signature} from public, anon, authenticated;${payload ? approvalConditionSql(ctx) : ""}`;
|
|
8467
8667
|
}
|
|
8468
8668
|
function tenantPoliciesSql(ctx, helpers) {
|
|
8469
8669
|
const fn = (name) => ctx.fn(name);
|
|
@@ -8472,24 +8672,27 @@ function tenantPoliciesSql(ctx, helpers) {
|
|
|
8472
8672
|
const has = (column) => ctx.has("policies", column);
|
|
8473
8673
|
const or = (row, column) => has(column) ? `${row}.${p(column)}` : "null";
|
|
8474
8674
|
const { manage, read } = helpers.permissions;
|
|
8475
|
-
const
|
|
8675
|
+
const platform = platformPoliciesOn(ctx);
|
|
8676
|
+
const payload = approvalConditions(ctx) === "payload";
|
|
8677
|
+
const rules = !payload && ctx.installed("automations") ? ctx.of("automations") : void 0;
|
|
8476
8678
|
const manager = employeesOf(ctx) !== void 0;
|
|
8477
|
-
const
|
|
8679
|
+
const manages = (tenant) => platform ? `(case when ${tenant} is null then ${ctx.staff(manage)} else (${SERVICE_CALLER$1} or ${ctx.can("tenant", tenant, manage)}) end)` : `(${SERVICE_CALLER$1} or ${ctx.can("tenant", tenant, manage)})`;
|
|
8680
|
+
const json = (row) => `jsonb_build_object('id', ${row}.${p("id")}, 'organizationId', ${row}.${p("tenant")}, 'subjectType', ${row}.${p("subjectType")}, 'action', ${row}.${p("action")}, 'effect', ${or(row, "effect")}, 'name', ${row}.${p("name")}, 'conditions', ${or(row, "conditions")}, 'mode', ${row}.${p("mode")}, 'steps', ${row}.${p("steps")}, 'selfApproval', ${row}.${p("selfApproval")}, 'expiresIn', ${or(row, "expiresIn")}::text, 'enabled', ${row}.${p("enabled")}, 'createdAt', ${row}.${p("createdAt")}, 'updatedAt', ${or(row, "updatedAt")})`;
|
|
8478
8681
|
const column = (logical, definition) => has(logical) ? `\n ${definition(p(logical))},` : "";
|
|
8479
8682
|
const table = ctx.manages ? `
|
|
8480
8683
|
create table if not exists ${t} (
|
|
8481
8684
|
${p("id")} uuid primary key default gen_random_uuid(),
|
|
8482
|
-
${p("tenant")} ${ctx.idType} not null,
|
|
8685
|
+
${p("tenant")} ${ctx.idType}${platform ? "" : " not null"},
|
|
8483
8686
|
${p("subjectType")} text not null,
|
|
8484
8687
|
${p("action")} text not null,
|
|
8485
|
-
${p("name")} text not null check (length(${p("name")}) between 1 and 200),${column("conditions", (name) => `${name} jsonb`)}
|
|
8688
|
+
${p("name")} text not null check (length(${p("name")}) between 1 and 200),${column("conditions", (name) => `${name} jsonb`)}${column("effect", (name) => `${name} text`)}
|
|
8486
8689
|
${p("mode")} text not null default 'authorize' check (${p("mode")} in ('confirm', 'authorize')),
|
|
8487
8690
|
${p("steps")} jsonb not null default '[]'::jsonb check (jsonb_typeof(${p("steps")}) = 'array'),
|
|
8488
8691
|
${p("selfApproval")} boolean not null default false,${column("expiresIn", (name) => `${name} interval check (${name} is null or ${name} > interval '0')`)}
|
|
8489
8692
|
${p("enabled")} boolean not null default true,${column("createdBy", (name) => `${name} uuid`)}
|
|
8490
8693
|
${p("createdAt")} timestamptz not null default now()${has("updatedAt") ? `,\n ${p("updatedAt")} timestamptz not null default now()` : ""}
|
|
8491
8694
|
);
|
|
8492
|
-
create index if not exists ${sqlIdent(`${ctx.tableName("policies").name}_lookup_idx`)} on ${t} (${p("tenant")}, ${p("subjectType")}, ${p("action")});
|
|
8695
|
+
${has("effect") ? `alter table ${t} add column if not exists ${p("effect")} text;\n` : ""}${platform ? `alter table ${t} alter column ${p("tenant")} drop not null;\n` : ""}create index if not exists ${sqlIdent(`${ctx.tableName("policies").name}_lookup_idx`)} on ${t} (${p("tenant")}, ${p("subjectType")}, ${p("action")});
|
|
8493
8696
|
${lockModuleTable(ctx, "policies", { read: true })}
|
|
8494
8697
|
${renderPolicy(policy$1({
|
|
8495
8698
|
table: t,
|
|
@@ -8501,7 +8704,10 @@ ${renderPolicy(policy$1({
|
|
|
8501
8704
|
drop: true,
|
|
8502
8705
|
target: t
|
|
8503
8706
|
})}` : "";
|
|
8504
|
-
const conditionCheck = has("conditions") ?
|
|
8707
|
+
const conditionCheck = has("conditions") ? payload ? `
|
|
8708
|
+
if v_conditions is not null then
|
|
8709
|
+
perform ${fn("approval_condition")}(v_conditions, '{}'::jsonb);
|
|
8710
|
+
end if;` : rules ? `
|
|
8505
8711
|
if v_conditions is not null then
|
|
8506
8712
|
v_fields := ${rules.fn("rule_field_map")}(v_type);
|
|
8507
8713
|
if v_fields = '{}'::jsonb then
|
|
@@ -8510,12 +8716,23 @@ ${renderPolicy(policy$1({
|
|
|
8510
8716
|
perform ${rules.fn("rule_check")}(v_conditions, v_fields, 1);
|
|
8511
8717
|
end if;` : `
|
|
8512
8718
|
if v_conditions is not null then
|
|
8513
|
-
${fail$1("APPROVAL_CONDITIONS_UNSUPPORTED", "approval policy conditions need the automations module", "22023")}
|
|
8719
|
+
${fail$1("APPROVAL_CONDITIONS_UNSUPPORTED", "approval policy conditions need the automations module, or options.conditions: \"payload\"", "22023")}
|
|
8514
8720
|
end if;` : `
|
|
8515
8721
|
if v_conditions is not null then
|
|
8516
8722
|
${fail$1("APPROVAL_CONDITIONS_UNSUPPORTED", "this approval policies table has no conditions column", "22023")}
|
|
8517
8723
|
end if;`;
|
|
8518
|
-
const
|
|
8724
|
+
const floorExists = `(exists (
|
|
8725
|
+
select 1 from jsonb_array_elements(${floorsJson(approvalPolicies(ctx))}) f
|
|
8726
|
+
where (v_type = '*' or f.value ->> 'subjectType' = v_type)
|
|
8727
|
+
and (v_action = '*' or f.value ->> 'action' in (v_action, '*'))
|
|
8728
|
+
and (v_effect is null or f.value -> 'effects' ? v_effect)
|
|
8729
|
+
)${platform ? ` or (save_approval_policy.tenant is null) or exists (
|
|
8730
|
+
select 1 from ${t} f
|
|
8731
|
+
where f.${p("tenant")} is null and f.${p("enabled")}
|
|
8732
|
+
and (f.${p("subjectType")} in (v_type, '*'))
|
|
8733
|
+
and (f.${p("action")} in (v_action, '*'))${has("effect") ? `\n and (f.${p("effect")} is null or f.${p("effect")} = v_effect)` : ""}
|
|
8734
|
+
)` : ""})`;
|
|
8735
|
+
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
8736
|
return `${table}
|
|
8520
8737
|
|
|
8521
8738
|
-- Creates or changes a tenant policy. policy is { id?, subjectType, action,
|
|
@@ -8538,8 +8755,10 @@ declare
|
|
|
8538
8755
|
v_steps jsonb;
|
|
8539
8756
|
v_step jsonb;
|
|
8540
8757
|
v_fields jsonb;
|
|
8758
|
+
v_effect text;
|
|
8759
|
+
v_who jsonb;
|
|
8541
8760
|
begin
|
|
8542
|
-
if not
|
|
8761
|
+
if not ${manages("save_approval_policy.tenant")} then
|
|
8543
8762
|
${fail$1("APPROVAL_FORBIDDEN", "managing approval policies needs approvals.manage")}
|
|
8544
8763
|
end if;
|
|
8545
8764
|
if jsonb_typeof(save_approval_policy.policy) is distinct from 'object' then
|
|
@@ -8547,7 +8766,7 @@ begin
|
|
|
8547
8766
|
end if;
|
|
8548
8767
|
if save_approval_policy.policy ? 'id' then
|
|
8549
8768
|
select * into v_old from ${t} x
|
|
8550
|
-
where x.${p("id")} = (save_approval_policy.policy ->> 'id')::uuid and x.${p("tenant")}
|
|
8769
|
+
where x.${p("id")} = (save_approval_policy.policy ->> 'id')::uuid and x.${p("tenant")} is not distinct from save_approval_policy.tenant
|
|
8551
8770
|
for update;
|
|
8552
8771
|
if not found then
|
|
8553
8772
|
${fail$1("APPROVAL_POLICY_NOT_FOUND", "approval policy not found", "P0002")}
|
|
@@ -8555,8 +8774,12 @@ begin
|
|
|
8555
8774
|
end if;
|
|
8556
8775
|
v_type := coalesce(save_approval_policy.policy ->> 'subjectType', v_old.${p("subjectType")});
|
|
8557
8776
|
v_action := coalesce(save_approval_policy.policy ->> 'action', v_old.${p("action")});
|
|
8558
|
-
|
|
8559
|
-
|
|
8777
|
+
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") ? "" : `
|
|
8778
|
+
if nullif(save_approval_policy.policy ->> 'effect', '') is not null then
|
|
8779
|
+
${fail$1("APPROVAL_EFFECT_UNSUPPORTED", "this approval policies table has no effect column", "22023")}
|
|
8780
|
+
end if;`}
|
|
8781
|
+
if v_type is null or v_action is null or not ${floorExists} then
|
|
8782
|
+
${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
8783
|
end if;
|
|
8561
8784
|
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
8785
|
v_steps := coalesce(save_approval_policy.policy -> 'steps', v_old.${p("steps")}, '[]'::jsonb);
|
|
@@ -8564,14 +8787,24 @@ begin
|
|
|
8564
8787
|
${stepsInvalid}
|
|
8565
8788
|
end if;
|
|
8566
8789
|
for v_step in select * from jsonb_array_elements(v_steps) loop
|
|
8567
|
-
if jsonb_typeof(v_step) <> 'object'
|
|
8568
|
-
|
|
8569
|
-
|
|
8570
|
-
|
|
8571
|
-
|
|
8572
|
-
|
|
8573
|
-
|
|
8574
|
-
or (
|
|
8790
|
+
if jsonb_typeof(v_step) <> 'object' then
|
|
8791
|
+
${stepsInvalid}
|
|
8792
|
+
end if;
|
|
8793
|
+
for v_who in select a.w from (values (v_step -> 'approvers', true), (v_step -> 'escalateTo', v_step ? 'escalateTo')) a(w, checked) where a.checked loop
|
|
8794
|
+
if jsonb_typeof(v_who) is distinct from 'object'
|
|
8795
|
+
or not (v_who ?| array['permission', 'role', 'team', 'users', 'manager'])
|
|
8796
|
+
or (v_who ? 'manager' and ${manager ? "v_who -> 'manager' <> 'true'::jsonb" : "true"})
|
|
8797
|
+
or (v_who ? 'users' and (jsonb_typeof(v_who -> 'users') <> 'array'
|
|
8798
|
+
or exists (select 1 from jsonb_array_elements(v_who -> 'users') u
|
|
8799
|
+
where jsonb_typeof(u) <> 'string' or u #>> '{}' !~ '^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$'))) then
|
|
8800
|
+
${stepsInvalid}
|
|
8801
|
+
end if;
|
|
8802
|
+
end loop;
|
|
8803
|
+
if (v_step ? 'required' and v_step -> 'required' <> '"all"'::jsonb and (jsonb_typeof(v_step -> 'required') <> 'number' or (v_step ->> 'required')::numeric < 1
|
|
8804
|
+
or (v_step ->> 'required')::numeric <> trunc((v_step ->> 'required')::numeric)))
|
|
8805
|
+
or (v_step -> 'required' = '"all"'::jsonb and (v_step -> 'approvers') - 'permission' <> '{}'::jsonb)
|
|
8806
|
+
or ((v_step ? 'escalateAfter') <> (v_step ? 'escalateTo'))
|
|
8807
|
+
or (v_step ? 'escalateAfter' and (jsonb_typeof(v_step -> 'escalateAfter') <> 'string' or (v_step ->> 'escalateAfter')::interval <= interval '0')) then
|
|
8575
8808
|
${stepsInvalid}
|
|
8576
8809
|
end if;
|
|
8577
8810
|
end loop;
|
|
@@ -8579,8 +8812,8 @@ begin
|
|
|
8579
8812
|
${fail$1("APPROVAL_POLICY_INVALID", "mode must be confirm or authorize", "22023")}
|
|
8580
8813
|
end if;
|
|
8581
8814
|
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" : ""},
|
|
8815
|
+
insert into ${t} (${p("tenant")}, ${p("subjectType")}, ${p("action")}, ${p("name")}${has("conditions") ? `, ${p("conditions")}` : ""}${has("effect") ? `, ${p("effect")}` : ""}, ${p("mode")}, ${p("steps")}, ${p("selfApproval")}${has("expiresIn") ? `, ${p("expiresIn")}` : ""}, ${p("enabled")}${has("createdBy") ? `, ${p("createdBy")}` : ""})
|
|
8816
|
+
values (save_approval_policy.tenant, v_type, v_action, btrim(save_approval_policy.policy ->> 'name')${has("conditions") ? ", v_conditions" : ""}${has("effect") ? ", v_effect" : ""},
|
|
8584
8817
|
${ctx.cast("policies", "mode", "coalesce(save_approval_policy.policy ->> 'mode', 'authorize')")}, v_steps,
|
|
8585
8818
|
coalesce((save_approval_policy.policy ->> 'selfApproval')::boolean, false)${has("expiresIn") ? ", (save_approval_policy.policy ->> 'expiresIn')::interval" : ""},
|
|
8586
8819
|
coalesce((save_approval_policy.policy ->> 'enabled')::boolean, true)${has("createdBy") ? ", auth.uid()" : ""})
|
|
@@ -8589,7 +8822,7 @@ begin
|
|
|
8589
8822
|
update ${t} x set
|
|
8590
8823
|
${p("subjectType")} = v_type,
|
|
8591
8824
|
${p("action")} = v_action,
|
|
8592
|
-
${p("name")} = coalesce(btrim(save_approval_policy.policy ->> 'name'), x.${p("name")}),${has("conditions") ? `\n ${p("conditions")} = v_conditions,` : ""}
|
|
8825
|
+
${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
8826
|
${p("mode")} = coalesce(${ctx.cast("policies", "mode", "save_approval_policy.policy ->> 'mode'")}, x.${p("mode")}),
|
|
8594
8827
|
${p("steps")} = v_steps,
|
|
8595
8828
|
${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,` : ""}
|
|
@@ -8630,7 +8863,7 @@ begin
|
|
|
8630
8863
|
if not found then
|
|
8631
8864
|
return false;
|
|
8632
8865
|
end if;
|
|
8633
|
-
if not
|
|
8866
|
+
if not ${manages(`v_row.${p("tenant")}`)} then
|
|
8634
8867
|
${fail$1("APPROVAL_FORBIDDEN", "managing approval policies needs approvals.manage")}
|
|
8635
8868
|
end if;
|
|
8636
8869
|
delete from ${t} x where x.${p("id")} = v_row.${p("id")};
|
|
@@ -8659,14 +8892,14 @@ security definer
|
|
|
8659
8892
|
set search_path = ''
|
|
8660
8893
|
as $$
|
|
8661
8894
|
begin
|
|
8662
|
-
if not (${SERVICE_CALLER$1} or ${ctx.can("tenant", "list_approval_policies.tenant", read)}) then
|
|
8895
|
+
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
8896
|
${fail$1("APPROVAL_FORBIDDEN", "reading approval policies needs approvals.read")}
|
|
8664
8897
|
end if;
|
|
8665
8898
|
return coalesce((
|
|
8666
8899
|
select jsonb_agg(${json("x")} order by x.${p("subjectType")}, x.${p("action")}, x.${p("createdAt")}, x.${p("id")})
|
|
8667
8900
|
from (
|
|
8668
8901
|
select * from ${t} y
|
|
8669
|
-
where y.${p("tenant")} = list_approval_policies.tenant
|
|
8902
|
+
where (y.${p("tenant")} = list_approval_policies.tenant or (list_approval_policies.tenant is null and y.${p("tenant")} is null))
|
|
8670
8903
|
and (list_approval_policies.subject_type is null or y.${p("subjectType")} = list_approval_policies.subject_type)
|
|
8671
8904
|
order by y.${p("subjectType")}, y.${p("action")}, y.${p("createdAt")}, y.${p("id")}
|
|
8672
8905
|
limit ${pageSize("list_approval_policies.page_size", 100, 500)}
|
|
@@ -8686,6 +8919,11 @@ function requestSql(ctx, helpers) {
|
|
|
8686
8919
|
const args = requestArgs(ctx);
|
|
8687
8920
|
const fields = extraFieldsArg(extras);
|
|
8688
8921
|
const otherNew = extras.length === 0 ? `${args}, jsonb, text` : `${args}, text`;
|
|
8922
|
+
const tenantless = (name) => tenantlessTypes(ctx).length === 0 ? "" : ` or (${name}.tenant is null and ${tenantlessType(ctx, `${name}.subject_type`)} and auth.uid() is not null)`;
|
|
8923
|
+
const tenantRequired = (name) => tenantlessTypes(ctx).length === 0 ? "" : `
|
|
8924
|
+
if ${name}.tenant is null and not ${tenantlessType(ctx, `${name}.subject_type`)} then
|
|
8925
|
+
${fail$1("APPROVAL_TENANT_REQUIRED", "a request for this subject type needs an organization", "22023")}
|
|
8926
|
+
end if;`;
|
|
8689
8927
|
return `
|
|
8690
8928
|
-- What a request for the subject type and action would need right now, with
|
|
8691
8929
|
-- subject as the request payload the tenant policies' conditions read; null
|
|
@@ -8700,7 +8938,7 @@ as $$
|
|
|
8700
8938
|
declare
|
|
8701
8939
|
v_policy jsonb;
|
|
8702
8940
|
begin
|
|
8703
|
-
if not (${SERVICE_CALLER$1} or ${ctx.can("tenant", "approval_requirement.tenant", request)}) then
|
|
8941
|
+
if not (${SERVICE_CALLER$1} or ${ctx.can("tenant", "approval_requirement.tenant", request)}${tenantless("approval_requirement")}) then
|
|
8704
8942
|
${fail$1("APPROVAL_FORBIDDEN", "checking an approval requirement needs approvals.request")}
|
|
8705
8943
|
end if;
|
|
8706
8944
|
v_policy := ${fn("approval_effective_policy")}(approval_requirement.tenant, approval_requirement.subject_type, approval_requirement.action, approval_requirement.subject);
|
|
@@ -8730,8 +8968,8 @@ declare
|
|
|
8730
8968
|
begin
|
|
8731
8969
|
if v_policy is null then
|
|
8732
8970
|
${fail$1("APPROVAL_POLICY_UNKNOWN", "no approval policy for this subject type and action", "22023")}
|
|
8733
|
-
end if
|
|
8734
|
-
if not (${SERVICE_CALLER$1} or (${ctx.can("tenant", "request_approval.tenant", request)} and ${subjectWrite})) then
|
|
8971
|
+
end if;${tenantRequired("request_approval")}
|
|
8972
|
+
if not (${SERVICE_CALLER$1} or (${ctx.can("tenant", "request_approval.tenant", request)} and ${subjectWrite})${tenantless("request_approval")}) then
|
|
8735
8973
|
${fail$1("APPROVAL_FORBIDDEN", "not allowed to request approval for this record")}
|
|
8736
8974
|
end if;
|
|
8737
8975
|
if not ${required("v_policy")} then
|
|
@@ -8901,6 +9139,10 @@ const EVENTS$23 = {
|
|
|
8901
9139
|
subject: "approval-requests",
|
|
8902
9140
|
payload: PAYLOAD$4
|
|
8903
9141
|
},
|
|
9142
|
+
"approval.escalated": {
|
|
9143
|
+
subject: "approval-requests",
|
|
9144
|
+
payload: PAYLOAD$4
|
|
9145
|
+
},
|
|
8904
9146
|
"approval_policy.saved": {
|
|
8905
9147
|
subject: "approval-policies",
|
|
8906
9148
|
payload: POLICY_PAYLOAD
|
|
@@ -8939,6 +9181,9 @@ const APPROVALS_NAMES = {
|
|
|
8939
9181
|
options: [
|
|
8940
9182
|
"policies",
|
|
8941
9183
|
"tenantPolicies",
|
|
9184
|
+
"platformPolicies",
|
|
9185
|
+
"conditions",
|
|
9186
|
+
"tenantless",
|
|
8942
9187
|
"extraColumns"
|
|
8943
9188
|
],
|
|
8944
9189
|
tables: {
|
|
@@ -9032,7 +9277,8 @@ function approvalsContract(extra) {
|
|
|
9032
9277
|
args: [
|
|
9033
9278
|
"uuid",
|
|
9034
9279
|
"text",
|
|
9035
|
-
"text"
|
|
9280
|
+
"text",
|
|
9281
|
+
"uuid"
|
|
9036
9282
|
],
|
|
9037
9283
|
returns: "jsonb"
|
|
9038
9284
|
},
|
|
@@ -9061,6 +9307,167 @@ function approvalsContract(extra) {
|
|
|
9061
9307
|
}
|
|
9062
9308
|
];
|
|
9063
9309
|
}
|
|
9310
|
+
// src/sql/modules/approvals-steps.ts
|
|
9311
|
+
function allHoldersSql(k, holders) {
|
|
9312
|
+
const { has } = k;
|
|
9313
|
+
return has("policy") ? `
|
|
9314
|
+
if exists (select 1 from jsonb_array_elements(coalesce(v_policy -> 'steps', '[]'::jsonb)) e where e.value -> 'required' = '"all"'::jsonb) then${holders === void 0 ? `
|
|
9315
|
+
${fail$1("APPROVAL_ALL_UNSUPPORTED", "required all needs an access model that lists permission holders", "22023")}` : `
|
|
9316
|
+
v_policy := jsonb_set(v_policy, '{steps}', (
|
|
9317
|
+
select jsonb_agg(case when e.value -> 'required' = '"all"'::jsonb
|
|
9318
|
+
then e.value || jsonb_build_object('approvers', jsonb_build_object('users', h.users), 'required', jsonb_array_length(h.users), 'permission', e.value -> 'approvers' ->> 'permission')
|
|
9319
|
+
else e.value end order by e.ordinality)
|
|
9320
|
+
from jsonb_array_elements(v_policy -> 'steps') with ordinality e
|
|
9321
|
+
left join lateral (
|
|
9322
|
+
select coalesce(jsonb_agg(distinct to_jsonb(u.id::text)), '[]'::jsonb) as users
|
|
9323
|
+
from (${holders}) as u(id)
|
|
9324
|
+
where u.id is not null and (u.id is distinct from auth.uid() or coalesce((v_policy ->> 'selfApproval')::boolean, false))
|
|
9325
|
+
) h on e.value -> 'required' = '"all"'::jsonb
|
|
9326
|
+
));
|
|
9327
|
+
if exists (select 1 from jsonb_array_elements(v_policy -> 'steps') e where e.value -> 'required' = '0'::jsonb) then
|
|
9328
|
+
${fail$1("APPROVAL_APPROVERS_EMPTY", "nobody holds the permission a step asks every holder of", "22023")}
|
|
9329
|
+
end if;`}
|
|
9330
|
+
end if;` : "";
|
|
9331
|
+
}
|
|
9332
|
+
/** Decide_approval, with the service role deciding for a named user. */
|
|
9333
|
+
function decideSql(ctx, k) {
|
|
9334
|
+
const { requests, decisions, c, d, has, fn, policyOf, stepOf, record, json, also, alsoValue, decided, notFound, stepsRefusal, linkedReject, commentRefusal } = k;
|
|
9335
|
+
return `-- Approves or rejects the current step. Enough approvals move the request
|
|
9336
|
+
-- to the next step, and the last step runs the policy's action. The service
|
|
9337
|
+
-- role decides for the user in decided_by, who is recorded as the approver;
|
|
9338
|
+
-- it skips the approver check, never the requester's.
|
|
9339
|
+
drop function if exists ${fn("decide_approval")}(uuid, text, text);
|
|
9340
|
+
create or replace function ${fn("decide_approval")}(request_id uuid, decision text, comment text default null, decided_by uuid default null)
|
|
9341
|
+
returns jsonb
|
|
9342
|
+
language plpgsql
|
|
9343
|
+
security definer
|
|
9344
|
+
set search_path = ''
|
|
9345
|
+
as $$
|
|
9346
|
+
#variable_conflict use_column
|
|
9347
|
+
declare
|
|
9348
|
+
v_req ${requests}%rowtype;
|
|
9349
|
+
v_count integer;
|
|
9350
|
+
v_service boolean := ${SERVICE_CALLER$1};
|
|
9351
|
+
v_actor uuid := coalesce(decide_approval.decided_by, auth.uid());
|
|
9352
|
+
begin
|
|
9353
|
+
if decide_approval.decision not in ('approved', 'rejected') then
|
|
9354
|
+
${fail$1("APPROVAL_DECISION_INVALID", "decision must be approved or rejected", "22023")}
|
|
9355
|
+
end if;${commentRefusal("decide_approval.comment")}
|
|
9356
|
+
if decide_approval.decided_by is not null and not v_service and decide_approval.decided_by is distinct from auth.uid() then
|
|
9357
|
+
${fail$1("APPROVAL_FORBIDDEN", "only the service role decides for another user")}
|
|
9358
|
+
end if;
|
|
9359
|
+
select * into v_req from ${requests} r where r.${c("id")} = decide_approval.request_id for update;
|
|
9360
|
+
if not found then
|
|
9361
|
+
${notFound}
|
|
9362
|
+
end if;
|
|
9363
|
+
if v_req.${c("status")} <> 'pending' then
|
|
9364
|
+
${fail$1("APPROVAL_CLOSED", "this request is no longer pending", "22023")}
|
|
9365
|
+
end if;${has("expiresAt") ? `
|
|
9366
|
+
if v_req.${c("expiresAt")} is not null and v_req.${c("expiresAt")} <= now() then
|
|
9367
|
+
${fail$1("APPROVAL_EXPIRED", "this request has expired", "22023")}
|
|
9368
|
+
end if;` : ""}
|
|
9369
|
+
if v_service then
|
|
9370
|
+
if v_actor is not null and v_actor = v_req.${c("requestedBy")} and coalesce(${policyOf("v_req")} ->> 'mode', 'authorize') <> 'confirm'
|
|
9371
|
+
and not coalesce((${policyOf("v_req")} ->> 'selfApproval')::boolean, false) then
|
|
9372
|
+
${fail$1("APPROVAL_FORBIDDEN", "the requester can't decide their own request")}
|
|
9373
|
+
end if;
|
|
9374
|
+
if v_actor is not null and exists (
|
|
9375
|
+
select 1 from ${decisions} x
|
|
9376
|
+
where x.${d("request")} = v_req.${c("id")} and x.${d("step")} = ${stepOf("v_req")} and x.${d("approver")} = v_actor
|
|
9377
|
+
) then
|
|
9378
|
+
${fail$1("APPROVAL_FORBIDDEN", "this user already decided this step")}
|
|
9379
|
+
end if;
|
|
9380
|
+
elsif not ${fn("approval_eligible")}(v_req.${c("id")}) then
|
|
9381
|
+
${fail$1("APPROVAL_FORBIDDEN", "not an approver for this step")}
|
|
9382
|
+
end if;
|
|
9383
|
+
${ctx.hook("before_approval_decide", [["uuid", `v_req.${c("id")}`], ["text", "decide_approval.decision"]])}
|
|
9384
|
+
insert into ${decisions} (${d("request")}, ${d("tenant")}, ${d("step")}, ${d("approver")}, ${d("decision")}${also("decisions", "comment")})
|
|
9385
|
+
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")});
|
|
9386
|
+
if decide_approval.decision = 'rejected' then
|
|
9387
|
+
update ${requests} r set ${c("status")} = 'rejected'${decided}
|
|
9388
|
+
where r.${c("id")} = v_req.${c("id")} returning * into v_req;
|
|
9389
|
+
${record("approval.rejected", "v_req", true)}
|
|
9390
|
+
perform ${fn("approval_notify")}(v_req.${c("id")}, 'rejected');${linkedReject}
|
|
9391
|
+
else
|
|
9392
|
+
select count(*) into v_count from ${decisions} x
|
|
9393
|
+
where x.${d("request")} = v_req.${c("id")} and x.${d("step")} = ${stepOf("v_req")} and x.${d("decision")} = 'approved';
|
|
9394
|
+
if ${policyOf("v_req")} ->> 'mode' = 'confirm' and v_req.${c("requestedBy")} = v_actor then
|
|
9395
|
+
update ${requests} r set ${c("status")} = 'approved'${decided}
|
|
9396
|
+
where r.${c("id")} = v_req.${c("id")} returning * into v_req;
|
|
9397
|
+
perform ${fn("approval_finalize")}(v_req.${c("id")});
|
|
9398
|
+
elsif v_count >= coalesce((${policyOf("v_req")} -> 'steps' -> ${stepOf("v_req")} ->> 'required')::integer, 1) then
|
|
9399
|
+
if ${stepOf("v_req")} + 1 >= jsonb_array_length(${policyOf("v_req")} -> 'steps') then
|
|
9400
|
+
update ${requests} r set ${c("status")} = 'approved'${decided}
|
|
9401
|
+
where r.${c("id")} = v_req.${c("id")} returning * into v_req;
|
|
9402
|
+
perform ${fn("approval_finalize")}(v_req.${c("id")});
|
|
9403
|
+
else
|
|
9404
|
+
${has("step") ? `update ${requests} r set ${c("step")} = r.${c("step")} + 1${has("remindedAt") ? `, ${c("remindedAt")} = null` : ""}
|
|
9405
|
+
where r.${c("id")} = v_req.${c("id")} returning * into v_req;
|
|
9406
|
+
perform ${fn("approval_notify")}(v_req.${c("id")}, 'requested');` : stepsRefusal}
|
|
9407
|
+
end if;
|
|
9408
|
+
end if;
|
|
9409
|
+
end if;
|
|
9410
|
+
${ctx.hook("after_approval_decide", [["uuid", `v_req.${c("id")}`], ["text", `v_req.${c("status")}`]])}
|
|
9411
|
+
return ${json("v_req")};
|
|
9412
|
+
end;
|
|
9413
|
+
$$;
|
|
9414
|
+
${userGrant(`${fn("decide_approval")}(uuid, text, text, uuid)`)}`;
|
|
9415
|
+
}
|
|
9416
|
+
/** Escalate_approvals, which lets a waiting step's fallback approvers in. */
|
|
9417
|
+
function escalateSql(k) {
|
|
9418
|
+
const { requests, decisions, c, d, has, fn, stepOf, record } = k;
|
|
9419
|
+
return `-- Lets the fallback approvers (escalateTo) of a step decide it too once the
|
|
9420
|
+
-- step has waited its escalateAfter, and asks them. Run it from pg_cron like
|
|
9421
|
+
-- remind_approvals.
|
|
9422
|
+
create or replace function ${fn("escalate_approvals")}(max_requests integer default 200)
|
|
9423
|
+
returns integer
|
|
9424
|
+
language plpgsql
|
|
9425
|
+
security definer
|
|
9426
|
+
set search_path = ''
|
|
9427
|
+
as $$
|
|
9428
|
+
declare
|
|
9429
|
+
v_req ${requests}%rowtype;
|
|
9430
|
+
v_count integer := 0;
|
|
9431
|
+
begin${has("policy") ? `
|
|
9432
|
+
for v_req in
|
|
9433
|
+
select * from ${requests} r
|
|
9434
|
+
where r.${c("status")} = 'pending'${has("expiresAt") ? `\n and (r.${c("expiresAt")} is null or r.${c("expiresAt")} > now())` : ""}
|
|
9435
|
+
and r.${c("policy")} -> 'steps' -> ${stepOf("r")} ? 'escalateAfter'
|
|
9436
|
+
and not coalesce((r.${c("policy")} -> 'steps' -> ${stepOf("r")} ->> 'escalated')::boolean, false)
|
|
9437
|
+
and coalesce((
|
|
9438
|
+
select max(x.${d("createdAt")}) from ${decisions} x
|
|
9439
|
+
where x.${d("request")} = r.${c("id")} and x.${d("step")} = ${stepOf("r")} - 1
|
|
9440
|
+
), r.${c("createdAt")}) + (r.${c("policy")} -> 'steps' -> ${stepOf("r")} ->> 'escalateAfter')::interval <= now()
|
|
9441
|
+
order by r.${c("createdAt")}
|
|
9442
|
+
limit greatest(coalesce(escalate_approvals.max_requests, 200), 1)
|
|
9443
|
+
for update skip locked
|
|
9444
|
+
loop
|
|
9445
|
+
update ${requests} r set ${c("policy")} = jsonb_set(r.${c("policy")}, array['steps', (${stepOf("r")})::text, 'escalated'], 'true'::jsonb)
|
|
9446
|
+
where r.${c("id")} = v_req.${c("id")}
|
|
9447
|
+
returning * into v_req;
|
|
9448
|
+
${record("approval.escalated", "v_req", true)}
|
|
9449
|
+
perform ${fn("approval_notify")}(v_req.${c("id")}, 'escalated');
|
|
9450
|
+
v_count := v_count + 1;
|
|
9451
|
+
end loop;` : ""}
|
|
9452
|
+
return v_count;
|
|
9453
|
+
end;
|
|
9454
|
+
$$;
|
|
9455
|
+
${serviceGrant(`${fn("escalate_approvals")}(integer)`)}`;
|
|
9456
|
+
}
|
|
9457
|
+
/**
|
|
9458
|
+
* Throws when a step escalates or asks every holder without a policy column, or
|
|
9459
|
+
* asks every holder under an access model that can't list them.
|
|
9460
|
+
*/
|
|
9461
|
+
function validateSteps(policies, policyColumn, holders) {
|
|
9462
|
+
for (const policy of policies) {
|
|
9463
|
+
const where = `blocks.approvals.options.policies.${policy.subjectType}.${policy.action}`;
|
|
9464
|
+
if (policy.steps.some((step) => step.escalateAfter !== void 0) && !policyColumn) throw new TypeError(`${where}: escalateAfter needs a policy column on the approval requests table`);
|
|
9465
|
+
if (policy.steps.some((step) => step.required === "all")) {
|
|
9466
|
+
if (!policyColumn) throw new TypeError(`${where}: required "all" with a permission needs a policy column on the approval requests table`);
|
|
9467
|
+
if (!holders) throw new TypeError(`${where}: required "all" with a permission needs an access model that lists permission holders (holdersOf)`);
|
|
9468
|
+
}
|
|
9469
|
+
}
|
|
9470
|
+
}
|
|
9064
9471
|
// src/sql/modules/approver.ts
|
|
9065
9472
|
/** The `{kind}` of an AI tool call that waits for approval. */
|
|
9066
9473
|
const AI_TOOL_APPROVAL = "ai-tool";
|
|
@@ -10498,6 +10905,123 @@ function driveKit(ctx, own) {
|
|
|
10498
10905
|
siblings
|
|
10499
10906
|
};
|
|
10500
10907
|
}
|
|
10908
|
+
// src/sql/modules/notifications-audience.ts
|
|
10909
|
+
/**
|
|
10910
|
+
* Users who hold `notification.permission` in the tenant, added before
|
|
10911
|
+
* `exclude`. A provider without `holdersOf` refuses the audience. The roles and
|
|
10912
|
+
* catalog models ask `can_user` of each member, and the catalog model also
|
|
10913
|
+
* includes a platform-role holder. Never every member.
|
|
10914
|
+
*/
|
|
10915
|
+
function permissionAudience(ctx, layout) {
|
|
10916
|
+
const named = "nullif(notification ->> 'permission', '')";
|
|
10917
|
+
const unavailable = `
|
|
10918
|
+
if ${named} is not null then
|
|
10919
|
+
${fail$1("NOTIFICATION_PERMISSION_AUDIENCE_UNAVAILABLE", "This project has no permission audience", "0A000")}
|
|
10920
|
+
end if;`;
|
|
10921
|
+
const needsTenant = `
|
|
10922
|
+
if ${named} is not null and v_tenant is null then
|
|
10923
|
+
${fail$1("NOTIFICATION_PERMISSION_NEEDS_TENANT", "A permission audience needs a tenant", "22023")}
|
|
10924
|
+
end if;`;
|
|
10925
|
+
const model = accessModel(ctx);
|
|
10926
|
+
if (model === "provider") return providerAudience(layout, needsTenant, unavailable, named);
|
|
10927
|
+
if (model === "custom") return customAudience(ctx, needsTenant, unavailable, named);
|
|
10928
|
+
if (!ctx.installed("memberships")) return unavailable;
|
|
10929
|
+
return membershipAudience(ctx, model, needsTenant, named);
|
|
10930
|
+
}
|
|
10931
|
+
function providerAudience(layout, needsTenant, unavailable, named) {
|
|
10932
|
+
const provider = layout.accessProvider;
|
|
10933
|
+
if (provider === void 0) return unavailable;
|
|
10934
|
+
const template = provider.functions.holdersOf;
|
|
10935
|
+
if (template === void 0) return unavailable;
|
|
10936
|
+
return audienceAppend(needsTenant, named, fillTemplate("authorization.functions.holdersOf", template, {
|
|
10937
|
+
permission: "(notification ->> 'permission')",
|
|
10938
|
+
tenant: "v_tenant",
|
|
10939
|
+
scope: provider.scope
|
|
10940
|
+
}));
|
|
10941
|
+
}
|
|
10942
|
+
function customAudience(ctx, needsTenant, unavailable, named) {
|
|
10943
|
+
const template = ctx.modules.permissions?.functions?.holdersOf;
|
|
10944
|
+
if (template === void 0) return unavailable;
|
|
10945
|
+
return audienceAppend(needsTenant, named, fillTemplate("blocks.permissions.functions.holdersOf", template, {
|
|
10946
|
+
permission: "(notification ->> 'permission')",
|
|
10947
|
+
tenant: "v_tenant"
|
|
10948
|
+
}));
|
|
10949
|
+
}
|
|
10950
|
+
function membershipAudience(ctx, model, needsTenant, named) {
|
|
10951
|
+
const members = ctx.of("memberships");
|
|
10952
|
+
const user = members.col("memberships", "user");
|
|
10953
|
+
const tenant = members.col("memberships", "tenant");
|
|
10954
|
+
let platform = "";
|
|
10955
|
+
if (model === "catalog" && ctx.installed("permissions") && ctx.of("permissions").hasTable("platformAssignments")) {
|
|
10956
|
+
const access = ctx.of("permissions");
|
|
10957
|
+
const holder = access.col("platformAssignments", "user");
|
|
10958
|
+
platform = `
|
|
10959
|
+
union
|
|
10960
|
+
select a.${holder}
|
|
10961
|
+
from ${access.table("platformAssignments")} a
|
|
10962
|
+
where coalesce(better_supabase.platform_can(a.${holder}, notification ->> 'permission'), false)`;
|
|
10963
|
+
}
|
|
10964
|
+
return `${needsTenant}
|
|
10965
|
+
if ${named} is not null then
|
|
10966
|
+
v_recipients := v_recipients || coalesce(array(
|
|
10967
|
+
select m.${user}
|
|
10968
|
+
from ${members.table("memberships")} m
|
|
10969
|
+
where m.${tenant} = v_tenant
|
|
10970
|
+
and ${ctx.scope.canUser(`m.${user}`, "v_tenant", "notification ->> 'permission'")}
|
|
10971
|
+
${platform}
|
|
10972
|
+
), '{}');
|
|
10973
|
+
end if;`;
|
|
10974
|
+
}
|
|
10975
|
+
function audienceAppend(needsTenant, named, call) {
|
|
10976
|
+
return `${needsTenant}
|
|
10977
|
+
if ${named} is not null then
|
|
10978
|
+
v_recipients := v_recipients || coalesce(array(select u from ${call} as t(u)), '{}');
|
|
10979
|
+
end if;`;
|
|
10980
|
+
}
|
|
10981
|
+
const NAME$8 = /^[a-z][a-z0-9_]*$/;
|
|
10982
|
+
/**
|
|
10983
|
+
* A channel nobody chose is on for `in_app` and off for the rest, unless
|
|
10984
|
+
* `channelDefaults` says otherwise.
|
|
10985
|
+
*/
|
|
10986
|
+
function channelDefaults(ctx, channel) {
|
|
10987
|
+
const value = ctx.option("channelDefaults") ?? {};
|
|
10988
|
+
if (!isRecord$1(value)) throw new TypeError("blocks.notifications.options.channelDefaults must map channel names to booleans");
|
|
10989
|
+
return `case ${channel} ${[...Object.entries(value).map(([channel, enabled]) => {
|
|
10990
|
+
if (!NAME$8.test(channel) || typeof enabled !== "boolean") throw new TypeError(`blocks.notifications.options.channelDefaults.${channel} must be a boolean`);
|
|
10991
|
+
return `when ${sqlString(channel)} then ${String(enabled)}`;
|
|
10992
|
+
}), "when 'in_app' then true"].join(" ")} else false end`;
|
|
10993
|
+
}
|
|
10994
|
+
/**
|
|
10995
|
+
* A query of the user ids that hold `permission` in `tenant` (SQL expressions),
|
|
10996
|
+
* from the provider's or the custom model's `holdersOf`, or the members the
|
|
10997
|
+
* roles and catalog models allow; `undefined` when the access model can't list
|
|
10998
|
+
* holders.
|
|
10999
|
+
*/
|
|
11000
|
+
function permissionHolders(ctx, layout, permission, tenant) {
|
|
11001
|
+
const model = accessModel(ctx);
|
|
11002
|
+
if (model === "provider") {
|
|
11003
|
+
const provider = layout.accessProvider;
|
|
11004
|
+
const template = provider?.functions.holdersOf;
|
|
11005
|
+
return provider === void 0 || template === void 0 ? void 0 : `select h.u from ${fillTemplate("authorization.functions.holdersOf", template, {
|
|
11006
|
+
permission,
|
|
11007
|
+
tenant,
|
|
11008
|
+
scope: provider.scope
|
|
11009
|
+
})} as h(u)`;
|
|
11010
|
+
}
|
|
11011
|
+
if (model === "custom") {
|
|
11012
|
+
const template = ctx.modules.permissions?.functions?.holdersOf;
|
|
11013
|
+
return template === void 0 ? void 0 : `select h.u from ${fillTemplate("blocks.permissions.functions.holdersOf", template, {
|
|
11014
|
+
permission,
|
|
11015
|
+
tenant
|
|
11016
|
+
})} as h(u)`;
|
|
11017
|
+
}
|
|
11018
|
+
if (!ctx.installed("memberships")) return;
|
|
11019
|
+
const members = ctx.of("memberships");
|
|
11020
|
+
const user = members.col("memberships", "user");
|
|
11021
|
+
return `select m.${user} from ${members.table("memberships")} m
|
|
11022
|
+
where m.${members.col("memberships", "tenant")} = ${tenant}
|
|
11023
|
+
and ${ctx.scope.canUser(`m.${user}`, tenant, permission)}`;
|
|
11024
|
+
}
|
|
10501
11025
|
// src/sql/modules/subjects.ts
|
|
10502
11026
|
const NAMES$111 = { tables: {} };
|
|
10503
11027
|
/**
|
|
@@ -11037,6 +11561,10 @@ function build$112(ctx, layout) {
|
|
|
11037
11561
|
validateRuns(ctx, policies);
|
|
11038
11562
|
validateApprovers(ctx, policies, tenantPoliciesOn(ctx));
|
|
11039
11563
|
if (tenantPoliciesOn(ctx) && !has("policy")) throw new TypeError("blocks.approvals.options.tenantPolicies needs a policy column on the approval requests table");
|
|
11564
|
+
const tenantless = tenantlessTypes(ctx).length > 0;
|
|
11565
|
+
platformPoliciesOn(ctx);
|
|
11566
|
+
const holders = permissionHolders(ctx, layout, "(e.value -> 'approvers' ->> 'permission')", "open_approval.tenant");
|
|
11567
|
+
validateSteps(policies, has("policy"), holders !== void 0);
|
|
11040
11568
|
const provider = approverCheck(ctx, layout, {
|
|
11041
11569
|
kind: { sql: `v_req.${c("subjectType")} || '.' || v_req.${c("action")}` },
|
|
11042
11570
|
subject: `v_req.${c("subjectId")}::text`,
|
|
@@ -11100,6 +11628,18 @@ function build$112(ctx, layout) {
|
|
|
11100
11628
|
const managerMember = manager === void 0 ? "" : `
|
|
11101
11629
|
union
|
|
11102
11630
|
select ${manager} where coalesce((v_approvers ->> 'manager')::boolean, false)`;
|
|
11631
|
+
const approverMatch = `((coalesce(v_approvers -> 'users', '[]'::jsonb) ? v_me::text)
|
|
11632
|
+
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'")})
|
|
11633
|
+
or (v_approvers ->> 'role' is not null and exists (
|
|
11634
|
+
select 1 from ${members.table("memberships")} m
|
|
11635
|
+
where m.${mt} = v_req.${c("tenant")} and m.${mu} = v_me and m.${mr} = ${approverRole}
|
|
11636
|
+
))
|
|
11637
|
+
or (v_approvers ->> 'team' is not null and ${teamMatch("v_me")})${manager === void 0 ? "" : `
|
|
11638
|
+
or (coalesce((v_approvers ->> 'manager')::boolean, false) and ${managerMatch(ctx, {
|
|
11639
|
+
requester: `v_req.${c("requestedBy")}`,
|
|
11640
|
+
tenant: `v_req.${c("tenant")}`,
|
|
11641
|
+
user: "v_me"
|
|
11642
|
+
})})`})`;
|
|
11103
11643
|
const notFound = fail$1("APPROVAL_NOT_FOUND", "approval request not found", "P0002");
|
|
11104
11644
|
const queues = [...new Set(policies.flatMap((policy) => policy.run?.kind === "queue" ? [policy.run.queue] : []))];
|
|
11105
11645
|
const queueRun = queues.length === 0 ? "" : `
|
|
@@ -11134,16 +11674,36 @@ ${indent}end if;`;
|
|
|
11134
11674
|
subjectId: subjectId(""),
|
|
11135
11675
|
comment: lastComment
|
|
11136
11676
|
})};`, " ")]).join("");
|
|
11677
|
+
const kit = {
|
|
11678
|
+
requests,
|
|
11679
|
+
decisions,
|
|
11680
|
+
c,
|
|
11681
|
+
d,
|
|
11682
|
+
has,
|
|
11683
|
+
fn,
|
|
11684
|
+
policyOf,
|
|
11685
|
+
stepOf,
|
|
11686
|
+
record,
|
|
11687
|
+
json,
|
|
11688
|
+
also,
|
|
11689
|
+
alsoValue,
|
|
11690
|
+
decided,
|
|
11691
|
+
notFound,
|
|
11692
|
+
stepsRefusal,
|
|
11693
|
+
linkedReject,
|
|
11694
|
+
commentRefusal
|
|
11695
|
+
};
|
|
11696
|
+
const allHolders = allHoldersSql(kit, holders);
|
|
11137
11697
|
const notifyBody = ctx.installed("notifications") ? `
|
|
11138
11698
|
select * into v_req from ${requests} r where r.${c("id")} = approval_notify.request_id;
|
|
11139
|
-
if not found then
|
|
11699
|
+
if not found${tenantless ? ` or v_req.${c("tenant")} is null` : ""} then
|
|
11140
11700
|
return;
|
|
11141
11701
|
end if;
|
|
11142
11702
|
if approval_notify.kind in ('approved', 'rejected', 'expired') then
|
|
11143
11703
|
v_recipients := array[v_req.${c("requestedBy")}];
|
|
11144
11704
|
v_permission := null;
|
|
11145
11705
|
else
|
|
11146
|
-
v_approvers := ${policyOf("v_req")} -> 'steps' -> ${stepOf("v_req")} -> 'approvers';
|
|
11706
|
+
v_approvers := ${policyOf("v_req")} -> 'steps' -> ${stepOf("v_req")} -> case when approval_notify.kind = 'escalated' then 'escalateTo' else 'approvers' end;
|
|
11147
11707
|
v_permission := v_approvers ->> 'permission';
|
|
11148
11708
|
v_recipients := array(
|
|
11149
11709
|
select x::uuid from jsonb_array_elements_text(coalesce(v_approvers -> 'users', '[]'::jsonb)) x
|
|
@@ -11193,7 +11753,7 @@ ${indent}end if;`;
|
|
|
11193
11753
|
const column = (table, logical, definition) => ctx.has(table, logical) ? `\n ${definition(ctx.col(table, logical))},` : "";
|
|
11194
11754
|
const tables = ctx.manages ? `create table if not exists ${requests} (
|
|
11195
11755
|
${c("id")} uuid primary key default gen_random_uuid(),
|
|
11196
|
-
${c("tenant")} ${ctx.idType} not null,
|
|
11756
|
+
${c("tenant")} ${ctx.idType}${tenantless ? "" : " not null"},
|
|
11197
11757
|
${c("subjectType")} text not null,
|
|
11198
11758
|
${c("subjectId")} text not null,
|
|
11199
11759
|
${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 +11761,7 @@ ${indent}end if;`;
|
|
|
11201
11761
|
${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
11762
|
${c("createdAt")} timestamptz not null default now()
|
|
11203
11763
|
);${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';
|
|
11764
|
+
${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
11765
|
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
11766
|
${lockModuleTable(ctx, "requests", { read: true })}
|
|
11207
11767
|
${renderPolicy(policy$1({
|
|
@@ -11218,7 +11778,7 @@ ${renderPolicy(policy$1({
|
|
|
11218
11778
|
create table if not exists ${decisions} (
|
|
11219
11779
|
${d("id")} uuid primary key default gen_random_uuid(),
|
|
11220
11780
|
${d("request")} uuid not null references ${requests} (${c("id")}) on delete cascade,
|
|
11221
|
-
${d("tenant")} ${ctx.idType} not null,
|
|
11781
|
+
${d("tenant")} ${ctx.idType}${tenantless ? "" : " not null"},
|
|
11222
11782
|
${d("step")} integer not null,
|
|
11223
11783
|
${d("approver")} uuid,
|
|
11224
11784
|
${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 +11789,7 @@ create table if not exists ${decisions} (
|
|
|
11229
11789
|
"step",
|
|
11230
11790
|
"approver"
|
|
11231
11791
|
])}${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 })}
|
|
11792
|
+
${tenantless ? `alter table ${decisions} alter column ${d("tenant")} drop not null;\n` : ""}${lockModuleTable(ctx, "decisions", { read: true })}
|
|
11233
11793
|
${renderPolicy(policy$1({
|
|
11234
11794
|
table: decisions,
|
|
11235
11795
|
name: ctx.naming.rename("approval_decisions_read"),
|
|
@@ -11268,6 +11828,7 @@ set search_path = ''
|
|
|
11268
11828
|
as $$
|
|
11269
11829
|
declare
|
|
11270
11830
|
v_req ${requests}%rowtype;
|
|
11831
|
+
v_step jsonb;
|
|
11271
11832
|
v_approvers jsonb;
|
|
11272
11833
|
v_me uuid := auth.uid();
|
|
11273
11834
|
begin
|
|
@@ -11289,31 +11850,29 @@ begin
|
|
|
11289
11850
|
return false;
|
|
11290
11851
|
end if;
|
|
11291
11852
|
end if;${linkedEligible}
|
|
11292
|
-
|
|
11293
|
-
|
|
11294
|
-
|
|
11295
|
-
|
|
11296
|
-
|
|
11297
|
-
|
|
11298
|
-
|
|
11299
|
-
|
|
11300
|
-
|
|
11301
|
-
|
|
11302
|
-
|
|
11303
|
-
|
|
11304
|
-
})})`}${delegation ? `
|
|
11305
|
-
or exists (
|
|
11853
|
+
v_step := ${policyOf("v_req")} -> 'steps' -> ${stepOf("v_req")};
|
|
11854
|
+
v_approvers := v_step -> 'approvers';
|
|
11855
|
+
if ${approverMatch} then
|
|
11856
|
+
return true;
|
|
11857
|
+
end if;${has("policy") ? `
|
|
11858
|
+
if coalesce((v_step ->> 'escalated')::boolean, false) then
|
|
11859
|
+
v_approvers := v_step -> 'escalateTo';
|
|
11860
|
+
if ${approverMatch} then
|
|
11861
|
+
return true;
|
|
11862
|
+
end if;
|
|
11863
|
+
end if;` : ""}
|
|
11864
|
+
return ${[...delegation ? [`exists (
|
|
11306
11865
|
select 1 from ${decisions} x
|
|
11307
11866
|
where x.${d("request")} = v_req.${c("id")} and x.${d("step")} = ${stepOf("v_req")}
|
|
11308
11867
|
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))` : ""};
|
|
11868
|
+
)`] : [], ...provider ? [`(v_me is distinct from v_req.${c("requestedBy")} and coalesce((${provider.sql}), false))`] : []].join("\n or ") || "false"};
|
|
11311
11869
|
end;
|
|
11312
11870
|
$$;
|
|
11313
11871
|
${userGrant(`${fn("approval_eligible")}(uuid)`)}
|
|
11314
11872
|
|
|
11315
|
-
-- Notifies the current step's approvers (requested, reminder),
|
|
11316
|
-
-- (delegated) or the requester (approved,
|
|
11873
|
+
-- Notifies the current step's approvers (requested, reminder), its fallback
|
|
11874
|
+
-- approvers (escalated), a delegate (delegated) or the requester (approved,
|
|
11875
|
+
-- rejected, expired).
|
|
11317
11876
|
create or replace function ${fn("approval_notify")}(request_id uuid, kind text)
|
|
11318
11877
|
returns void
|
|
11319
11878
|
language plpgsql
|
|
@@ -11362,15 +11921,16 @@ as $$
|
|
|
11362
11921
|
#variable_conflict use_column
|
|
11363
11922
|
declare
|
|
11364
11923
|
v_req ${requests}%rowtype;
|
|
11924
|
+
v_policy jsonb := open_approval.policy;
|
|
11365
11925
|
begin
|
|
11366
11926
|
${ctx.hook("before_approval_request", [
|
|
11367
11927
|
[ctx.idType, "open_approval.tenant"],
|
|
11368
11928
|
["text", "open_approval.subject_type"],
|
|
11369
11929
|
["text", "open_approval.subject_id"],
|
|
11370
11930
|
["text", "open_approval.action"]
|
|
11371
|
-
])}${openRefusals}
|
|
11931
|
+
])}${openRefusals}${allHolders}
|
|
11372
11932
|
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", "
|
|
11933
|
+
values (open_approval.tenant, open_approval.subject_type, open_approval.subject_id, open_approval.action${alsoValue("requests", "policy", "v_policy")}, auth.uid()${alsoValue("requests", "reason", "open_approval.reason")}${alsoValue("requests", "payload", "coalesce(open_approval.payload, '{}'::jsonb)")}${has("expiresAt") ? `,\n case when open_approval.policy ->> 'expiresIn' is not null then now() + (open_approval.policy ->> 'expiresIn')::interval end` : ""})
|
|
11374
11934
|
on conflict (${c("subjectType")}, ${c("subjectId")}, ${c("action")}) where ${c("status")} = 'pending' do nothing
|
|
11375
11935
|
returning * into v_req;
|
|
11376
11936
|
if not found then
|
|
@@ -11438,67 +11998,7 @@ ${approvalsTenantSql(ctx, {
|
|
|
11438
11998
|
extras
|
|
11439
11999
|
})}
|
|
11440
12000
|
|
|
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)`)}
|
|
12001
|
+
${decideSql(ctx, kit)}
|
|
11502
12002
|
|
|
11503
12003
|
-- Hands the caller's place on the current step to another user.
|
|
11504
12004
|
create or replace function ${fn("delegate_approval")}(request_id uuid, to_user uuid, comment text default null)
|
|
@@ -11612,7 +12112,7 @@ begin
|
|
|
11612
12112
|
from (
|
|
11613
12113
|
select ${json("x")} as j, x.${c("createdAt")} as at, x.${c("id")} as id
|
|
11614
12114
|
from ${requests} x
|
|
11615
|
-
where x.${c("tenant")} = list_approvals.tenant
|
|
12115
|
+
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
12116
|
and (list_approvals.status is null or ${asText$2(ctx, "requests", `x.${c("status")}`)} = list_approvals.status)
|
|
11617
12117
|
and (list_approvals.subject_type is null or x.${c("subjectType")} = list_approvals.subject_type)
|
|
11618
12118
|
and (list_approvals.subject_id is null or x.${c("subjectId")} = list_approvals.subject_id)
|
|
@@ -11709,6 +12209,8 @@ begin${has("remindedAt") ? `
|
|
|
11709
12209
|
end;
|
|
11710
12210
|
$$;
|
|
11711
12211
|
${serviceGrant(`${fn("remind_approvals")}(interval, integer)`)}
|
|
12212
|
+
|
|
12213
|
+
${escalateSql(kit)}
|
|
11712
12214
|
${subjectCascades(ctx, subjects, `delete from ${requests} r where r.${c("subjectType")} = v_type and r.${c("subjectId")} = v_id;`)}
|
|
11713
12215
|
`;
|
|
11714
12216
|
}
|
|
@@ -39041,13 +39543,13 @@ const MESSAGING_NAMES = {
|
|
|
39041
39543
|
}
|
|
39042
39544
|
}
|
|
39043
39545
|
};
|
|
39044
|
-
const NAME$
|
|
39546
|
+
const NAME$7 = /^[a-z][a-z0-9_-]{0,30}$/;
|
|
39045
39547
|
const QUEUE$2 = /^[a-z][a-z0-9_]{0,40}$/;
|
|
39046
39548
|
function messagingSql(ctx, provider) {
|
|
39047
39549
|
const permissions = moduleOperations("messaging");
|
|
39048
39550
|
const key = (action) => ctx.permission(action, permissions[action]);
|
|
39049
39551
|
const topic = ctx.text("topic", "messages");
|
|
39050
|
-
if (!NAME$
|
|
39552
|
+
if (!NAME$7.test(topic)) throw new TypeError("blocks.messaging.options.topic must be a lowercase name of at most 31 characters");
|
|
39051
39553
|
const depth = ctx.option("threadDepth");
|
|
39052
39554
|
if (depth !== void 0 && depth !== 1 && depth !== "unlimited") throw new TypeError("blocks.messaging.options.threadDepth must be 1 or \"unlimited\"");
|
|
39053
39555
|
const maxBody = ctx.number("maxBodyLength", 4e4);
|
|
@@ -39194,7 +39696,7 @@ function channelsSql(ctx) {
|
|
|
39194
39696
|
};
|
|
39195
39697
|
}
|
|
39196
39698
|
// src/sql/modules/channels.ts
|
|
39197
|
-
const NAME$
|
|
39699
|
+
const NAME$6 = "'^[a-z0-9][a-z0-9_-]{0,79}$'";
|
|
39198
39700
|
/**
|
|
39199
39701
|
* `jsonb` for channel row `ch` with its conversation `c` and the caller's
|
|
39200
39702
|
* membership.
|
|
@@ -39241,7 +39743,7 @@ function channelsTable(q) {
|
|
|
39241
39743
|
create table if not exists ${t("channels")} (
|
|
39242
39744
|
${ch("id")} uuid primary key references ${conversations} (${cv("id")}) on delete cascade,
|
|
39243
39745
|
${ch("tenant")} ${ctx.idType} not null,
|
|
39244
|
-
${ch("name")} text not null check (${ch("name")} ~ ${NAME$
|
|
39746
|
+
${ch("name")} text not null check (${ch("name")} ~ ${NAME$6}),
|
|
39245
39747
|
${ch("visibility")} text not null default 'public' check (${ch("visibility")} in ('public', 'private')),
|
|
39246
39748
|
${ch("topic")} text check (${ch("topic")} is null or length(${ch("topic")}) <= 250),
|
|
39247
39749
|
${ch("purpose")} text check (${ch("purpose")} is null or length(${ch("purpose")}) <= 250),${optional("subjectType", "text")}${optional("subjectId", "text")}
|
|
@@ -39308,7 +39810,7 @@ begin
|
|
|
39308
39810
|
if not (${SERVICE_CALLER$1} or ${q.can("create_channel.tenant", "create")}) then
|
|
39309
39811
|
${fail$1("CHANNELS_FORBIDDEN", "not allowed to create channels here")}
|
|
39310
39812
|
end if;
|
|
39311
|
-
if v_name is null or v_name !~ ${NAME$
|
|
39813
|
+
if v_name is null or v_name !~ ${NAME$6} then
|
|
39312
39814
|
${fail$1("CHANNELS_NAME_INVALID", "a channel name is 1 to 80 lowercase letters, digits, - or _, starting with a letter or digit", "22023")}
|
|
39313
39815
|
end if;
|
|
39314
39816
|
if v_visibility not in ('public', 'private') then
|
|
@@ -39365,7 +39867,7 @@ begin
|
|
|
39365
39867
|
${fail$1("CHANNELS_FORBIDDEN", "not allowed to change this channel")}
|
|
39366
39868
|
end if;
|
|
39367
39869
|
v_name := coalesce(lower(trim(update_channel.attrs ->> 'name')), v_ch.${ch("name")});
|
|
39368
|
-
if v_name !~ ${NAME$
|
|
39870
|
+
if v_name !~ ${NAME$6} then
|
|
39369
39871
|
${fail$1("CHANNELS_NAME_INVALID", "a channel name is 1 to 80 lowercase letters, digits, - or _, starting with a letter or digit", "22023")}
|
|
39370
39872
|
end if;
|
|
39371
39873
|
v_visibility := coalesce(update_channel.attrs ->> 'visibility', v_ch.${ch("visibility")}::text);
|
|
@@ -52329,11 +52831,15 @@ const OPTIONAL_LINE_COLUMNS = [
|
|
|
52329
52831
|
"taxCode",
|
|
52330
52832
|
"createdAt"
|
|
52331
52833
|
];
|
|
52332
|
-
/**
|
|
52834
|
+
/**
|
|
52835
|
+
* The line columns of a document a customer answers: sections, options and the
|
|
52836
|
+
* number of periods a subscription line runs.
|
|
52837
|
+
*/
|
|
52333
52838
|
const DOCUMENT_LINE_COLUMNS = {
|
|
52334
52839
|
section: "section",
|
|
52335
52840
|
optional: "optional",
|
|
52336
|
-
selected: "selected"
|
|
52841
|
+
selected: "selected",
|
|
52842
|
+
periods: "periods"
|
|
52337
52843
|
};
|
|
52338
52844
|
/**
|
|
52339
52845
|
* A `NAMES.tables` entry for a line table called `name`. The app's own line
|
|
@@ -52375,6 +52881,14 @@ function countedLine(ctx, lines, alias) {
|
|
|
52375
52881
|
return declared(ctx, lines, "selected") ? `(not ${optional} or ${alias}.${ctx.col(lines, "selected")})` : `not ${optional}`;
|
|
52376
52882
|
}
|
|
52377
52883
|
/**
|
|
52884
|
+
* A line's amount before discounts: quantity times unit amount, times its
|
|
52885
|
+
* periods when the line table counts them, rounded once.
|
|
52886
|
+
*/
|
|
52887
|
+
function lineAmount(ctx, lines, alias) {
|
|
52888
|
+
const periods = declared(ctx, lines, "periods") ? ` * coalesce(${alias}.${ctx.col(lines, "periods")}, 1)` : "";
|
|
52889
|
+
return `round(${alias}.${ctx.col(lines, "quantity")}${periods} * ${alias}.${ctx.col(lines, "unitAmount")})`;
|
|
52890
|
+
}
|
|
52891
|
+
/**
|
|
52378
52892
|
* Line column `column` of row `alias` in line table `lines`, or what a read
|
|
52379
52893
|
* gives when the app's table lacks it.
|
|
52380
52894
|
*/
|
|
@@ -52437,7 +52951,7 @@ function lineItemsSql(ctx, items, options) {
|
|
|
52437
52951
|
const fn = ctx.fn(options.setter);
|
|
52438
52952
|
const recount = ctx.fn(`${options.setter}_recount`);
|
|
52439
52953
|
const trigger = `bsb_${ctx.tableName(items.lines).name}_totals`;
|
|
52440
|
-
const list =
|
|
52954
|
+
const list = lineAmount(ctx, items.lines, "l");
|
|
52441
52955
|
const discount = has("discountBps") ? `round(${list} * ${l("discountBps")} / 10000.0)` : "0";
|
|
52442
52956
|
const tax = has("taxRateBps") ? `round((${list} - ${discount}) * ${l("taxRateBps")} / 10000.0)` : "0";
|
|
52443
52957
|
const optional = (column, definition = () => "text") => has(column) ? `\n ${c(column)} ${definition(c(column))},` : "";
|
|
@@ -52458,6 +52972,7 @@ function lineItemsSql(ctx, items, options) {
|
|
|
52458
52972
|
["section", "nullif(trim(x.value ->> 'section'), '')"],
|
|
52459
52973
|
["optional", "coalesce((x.value ->> 'optional')::boolean, false)"],
|
|
52460
52974
|
["selected", "coalesce((x.value ->> 'selected')::boolean, not coalesce((x.value ->> 'optional')::boolean, false))"],
|
|
52975
|
+
["periods", "coalesce((x.value ->> 'periods')::integer, 1)"],
|
|
52461
52976
|
["position", "x.ordinality::integer"]
|
|
52462
52977
|
].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
52978
|
const extras = items.extras ?? [];
|
|
@@ -52468,10 +52983,10 @@ function lineItemsSql(ctx, items, options) {
|
|
|
52468
52983
|
${c("parent")} uuid not null references ${p} (${pc("id")}) on delete cascade,${optional("productType")}${optional("productId")}
|
|
52469
52984
|
${c("description")} text not null check (length(${c("description")}) between 1 and 2000),
|
|
52470
52985
|
${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")}
|
|
52986
|
+
${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
52987
|
${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
52988
|
);
|
|
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)}
|
|
52989
|
+
${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
52990
|
${lockTable(t, { read: true })}
|
|
52476
52991
|
drop policy if exists ${sqlIdent(`${name}_read`)} on ${t};
|
|
52477
52992
|
create policy ${sqlIdent(`${name}_read`)} on ${t} for select to authenticated
|
|
@@ -52519,7 +53034,7 @@ end;
|
|
|
52519
53034
|
$$;
|
|
52520
53035
|
revoke execute on function ${recount}(uuid) from public, anon, authenticated;
|
|
52521
53036
|
`;
|
|
52522
|
-
|
|
53037
|
+
const triggers = recounted ? `${recountSql}
|
|
52523
53038
|
-- Recounts each record a statement touched once, in id order so concurrent
|
|
52524
53039
|
-- statements lock the records in the same order. A transition table needs a
|
|
52525
53040
|
-- trigger per event, so there are three triggers on one function. The
|
|
@@ -52566,45 +53081,41 @@ drop trigger if exists ${trigger}_update on ${t};
|
|
|
52566
53081
|
drop trigger if exists ${trigger}_delete on ${t};
|
|
52567
53082
|
drop function if exists better_supabase.${trigger}();
|
|
52568
53083
|
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)
|
|
53084
|
+
`;
|
|
53085
|
+
const setterSql = (name, guard, frozen, grant) => `create or replace function ${ctx.fn(name)}(parent uuid, lines jsonb)
|
|
52575
53086
|
returns jsonb
|
|
52576
53087
|
language plpgsql
|
|
52577
53088
|
security definer
|
|
52578
53089
|
set search_path = ''
|
|
52579
53090
|
as $$
|
|
52580
53091
|
declare
|
|
52581
|
-
v_parent uuid := ${
|
|
53092
|
+
v_parent uuid := ${name}.parent;
|
|
52582
53093
|
v_tenant ${ctx.idType};
|
|
52583
53094
|
v_currency text;${extras.length === 0 ? "" : "\n v_line record;"}
|
|
52584
53095
|
begin
|
|
52585
|
-
select x.${pc("tenant")}, x.${pc("currency")} into v_tenant, v_currency from ${p} x where x.${pc("id")} = v_parent${
|
|
53096
|
+
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
53097
|
if v_tenant is null then
|
|
52587
53098
|
${fail$1("LINES_RECORD_INVALID", "no such record, or its lines are locked", "P0002")}
|
|
52588
53099
|
end if;
|
|
52589
|
-
${
|
|
52590
|
-
if jsonb_typeof(coalesce(${
|
|
53100
|
+
${guard}
|
|
53101
|
+
if jsonb_typeof(coalesce(${name}.lines, '[]')) <> 'array' then
|
|
52591
53102
|
${fail$1("LINES_INVALID", "lines must be a list", "22023")}
|
|
52592
53103
|
end if;
|
|
52593
|
-
if exists (select 1 from jsonb_array_elements(${
|
|
53104
|
+
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
53105
|
${fail$1("LINES_CURRENCY", "every line must be in the record's currency", "22023")}
|
|
52595
53106
|
end if;
|
|
52596
|
-
delete from ${t} l where l.${c("parent")} = v_parent${replaces ? "" : ` and l.${c("position")} > jsonb_array_length(coalesce(${
|
|
53107
|
+
delete from ${t} l where l.${c("parent")} = v_parent${replaces ? "" : ` and l.${c("position")} > jsonb_array_length(coalesce(${name}.lines, '[]'))`};
|
|
52597
53108
|
begin${replaces || positionKey ? "" : `
|
|
52598
53109
|
update ${t} l set ${written.filter(([column]) => ![
|
|
52599
53110
|
"tenant",
|
|
52600
53111
|
"parent",
|
|
52601
53112
|
"position"
|
|
52602
53113
|
].includes(column)).map(([column, value]) => `${c(column)} = ${value}`).join(", ")}
|
|
52603
|
-
from jsonb_array_elements(coalesce(${
|
|
53114
|
+
from jsonb_array_elements(coalesce(${name}.lines, '[]')) with ordinality x
|
|
52604
53115
|
where l.${c("parent")} = v_parent and l.${c("position")} = x.ordinality;`}
|
|
52605
53116
|
insert into ${t} (${written.map(([column]) => c(column)).join(", ")}${extrasInsert.columns})
|
|
52606
53117
|
select ${written.map(([, value]) => value).join(",\n ")}${extrasInsert.values}
|
|
52607
|
-
from jsonb_array_elements(coalesce(${
|
|
53118
|
+
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
53119
|
"tenant",
|
|
52609
53120
|
"parent",
|
|
52610
53121
|
"position"
|
|
@@ -52612,7 +53123,7 @@ begin
|
|
|
52612
53123
|
exception when check_violation or not_null_violation or invalid_text_representation or numeric_value_out_of_range then
|
|
52613
53124
|
${fail$1("LINES_INVALID", "every line needs a description, a positive quantity and a unit amount", "22023")}
|
|
52614
53125
|
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(${
|
|
53126
|
+
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
53127
|
end loop;`}
|
|
52617
53128
|
${recounted ? ` perform ${recount}(v_parent);\n` : ""} return (select jsonb_build_object(
|
|
52618
53129
|
${totalsJson},
|
|
@@ -52620,9 +53131,18 @@ ${recounted ? ` perform ${recount}(v_parent);\n` : ""} return (select jsonb_bu
|
|
|
52620
53131
|
from ${p} x where x.${pc("id")} = v_parent);
|
|
52621
53132
|
end;
|
|
52622
53133
|
$$;
|
|
52623
|
-
|
|
52624
|
-
grant execute on function ${fn}(uuid, jsonb) to authenticated, service_role;
|
|
53134
|
+
${grant}
|
|
52625
53135
|
`;
|
|
53136
|
+
return `${manages}${triggers}
|
|
53137
|
+
-- Replaces a record's lines with lines: a list of { description, quantity,
|
|
53138
|
+
-- unitAmount (minor units as text), currency, discountBps, taxRateBps,
|
|
53139
|
+
-- taxCode, product: { type, id } }. A line's currency must be the record's.
|
|
53140
|
+
-- Returns the record's totals as text, with its currency.${options.fallback ? "\n-- A line without unitAmount or description takes them from its product." : ""}
|
|
53141
|
+
${setterSql(options.setter, options.guard, items.frozen, `revoke execute on function ${fn}(uuid, jsonb) from public, anon;
|
|
53142
|
+
grant execute on function ${fn}(uuid, jsonb) to authenticated, service_role;`)}${options.restorer === void 0 ? "" : `
|
|
53143
|
+
-- Writes a record's lines like ${options.setter}, without its checks, for the
|
|
53144
|
+
-- module's own functions.
|
|
53145
|
+
${setterSql(options.restorer, "", void 0, `revoke execute on function ${ctx.fn(options.restorer)}(uuid, jsonb) from public, anon, authenticated;`)}`}`;
|
|
52626
53146
|
}
|
|
52627
53147
|
/**
|
|
52628
53148
|
* The `fallback` of a line that names a catalog variant (`product: { type:
|
|
@@ -52677,7 +53197,7 @@ function documentRecountSql(ctx, items, options) {
|
|
|
52677
53197
|
const l = (column) => lineColumn(ctx, items.lines, "l", column);
|
|
52678
53198
|
const parentHas = (column) => declared(ctx, items.parent, column);
|
|
52679
53199
|
const parent = `${options.setter}_recount.parent`;
|
|
52680
|
-
const amount =
|
|
53200
|
+
const amount = lineAmount(ctx, items.lines, "l");
|
|
52681
53201
|
const discount = declared(ctx, items.lines, "discountBps") ? `round(${amount} * ${l("discountBps")} / 10000.0)` : "0";
|
|
52682
53202
|
const rate = declared(ctx, items.lines, "taxRateBps") ? l("taxRateBps") : "0";
|
|
52683
53203
|
const code = declared(ctx, items.lines, "taxCode") ? `l.${c("taxCode")}` : "null::text";
|
|
@@ -53757,10 +54277,10 @@ const NAMES$80 = {
|
|
|
53757
54277
|
lines: lineTableSpec("deal_lines")
|
|
53758
54278
|
}
|
|
53759
54279
|
};
|
|
53760
|
-
const NAME$
|
|
54280
|
+
const NAME$5 = /^[a-z][a-z0-9_]{0,62}$/;
|
|
53761
54281
|
function names$7(ctx, option, fallback) {
|
|
53762
54282
|
const list = ctx.list(option, fallback);
|
|
53763
|
-
if (list.length === 0 || list.some((item) => !NAME$
|
|
54283
|
+
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
54284
|
return `${sqlString(`{${list.join(",")}}`)}::text[]`;
|
|
53765
54285
|
}
|
|
53766
54286
|
function tables$24(ctx, n) {
|
|
@@ -61728,6 +62248,23 @@ function quoteOrigin(ctx) {
|
|
|
61728
62248
|
return ctx.has("quotes", "originType") && ctx.has("quotes", "originId");
|
|
61729
62249
|
}
|
|
61730
62250
|
/**
|
|
62251
|
+
* `blocks.quotes.options.versionLines`: each published version keeps its lines
|
|
62252
|
+
* as rows with their own ids in `quote_version_lines`.
|
|
62253
|
+
*/
|
|
62254
|
+
function versionLinesOn(ctx) {
|
|
62255
|
+
return ctx.flag("versionLines", false) && ctx.hasTable("versionLines");
|
|
62256
|
+
}
|
|
62257
|
+
/**
|
|
62258
|
+
* `blocks.quotes.options.workingCopy`: staff edit a sent quote while the
|
|
62259
|
+
* customer keeps seeing its last published version, and sending publishes the
|
|
62260
|
+
* next one on the same link.
|
|
62261
|
+
*/
|
|
62262
|
+
function workingCopyOn(ctx) {
|
|
62263
|
+
const on = ctx.flag("workingCopy", false);
|
|
62264
|
+
if (on && !ctx.has("quotes", "unpublishedChanges")) throw new TypeError("blocks.quotes.options.workingCopy needs the quotes table's unpublishedChanges column");
|
|
62265
|
+
return on;
|
|
62266
|
+
}
|
|
62267
|
+
/**
|
|
61731
62268
|
* SQL over quote columns prefixed with `prefix` (`""` in a policy, `v_row.` in
|
|
61732
62269
|
* a function) that is true when the caller is a guest the quote is shared with:
|
|
61733
62270
|
* a grant on the quote, or a guest of its company or contact (ADR 0070). A
|
|
@@ -61771,12 +62308,20 @@ function quoteKit(ctx, n) {
|
|
|
61771
62308
|
returning * into v_row;
|
|
61772
62309
|
${record("quote.viewed", "v_row")}
|
|
61773
62310
|
end if;` : " null;";
|
|
61774
|
-
const
|
|
62311
|
+
const workingCopy = workingCopyOn(ctx);
|
|
62312
|
+
const versionLines = versionLinesOn(ctx);
|
|
62313
|
+
const open = (alias) => st(`${alias}.${q("status")}`, workingCopy ? [
|
|
62314
|
+
"draft",
|
|
62315
|
+
"changes_requested",
|
|
62316
|
+
"sent",
|
|
62317
|
+
"viewed"
|
|
62318
|
+
] : ["draft", "changes_requested"]);
|
|
61775
62319
|
const lineValue = (column) => lineColumn(ctx, "lines", "ql", column);
|
|
61776
62320
|
const documentLine = [
|
|
61777
62321
|
"section",
|
|
61778
62322
|
"optional",
|
|
61779
|
-
"selected"
|
|
62323
|
+
"selected",
|
|
62324
|
+
"periods"
|
|
61780
62325
|
].filter(lineHas).map((column) => `, ${sqlString(column)}, ql.${l(column)}`).join("");
|
|
61781
62326
|
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
62327
|
const tl = (column) => c("taxLines", column);
|
|
@@ -61791,14 +62336,23 @@ function quoteKit(ctx, n) {
|
|
|
61791
62336
|
const int8As = Object.fromEntries(int8Columns.map((logical) => [logical, (value) => `${value}::text`]));
|
|
61792
62337
|
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
62338
|
const text = (alias, logical, otherwise) => has(logical) ? `${alias}.${q(logical)}::text` : otherwise;
|
|
61794
|
-
const
|
|
62339
|
+
const v = (column) => c("versions", column);
|
|
62340
|
+
const vl = (column) => c("versionLines", column);
|
|
62341
|
+
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)`;
|
|
62342
|
+
const withVersionLineIds = (list, version) => versionLines ? `(select coalesce(jsonb_agg(e.value || jsonb_build_object('versionLineId', vx.${vl("id")}) order by e.ordinality), '[]'::jsonb)
|
|
62343
|
+
from jsonb_array_elements(${list}) with ordinality e
|
|
62344
|
+
left join ${t("versionLines")} vx on vx.${vl("version")} = ${version} and vx.${vl("position")} = (e.value ->> 'position')::integer)` : list;
|
|
62345
|
+
const publicJson = (alias, version) => `jsonb_build_object(
|
|
61795
62346
|
'identifier', ${alias}.${q("identifier")}, 'revision', ${alias}.${q("revision")}, 'title', ${alias}.${q("title")},
|
|
61796
62347
|
'status', ${ctx.label("quotes", "status", `${alias}.${q("status")}`)}, 'currency', ${alias}.${q("currency")}, 'validUntil', ${alias}.${q("validUntil")},
|
|
61797
62348
|
'terms', ${or(alias, "terms")}, 'pricesIncludeTax', ${has("pricesIncludeTax") ? `${alias}.${q("pricesIncludeTax")}` : "false"},
|
|
61798
62349
|
'discountBps', ${has("discountBps") ? `${alias}.${q("discountBps")}` : "0"}, 'discountAmount', ${text(alias, "discountAmount", "'0'")},
|
|
61799
|
-
'depositBps', ${or(alias, "depositBps")}, '
|
|
62350
|
+
'depositBps', ${or(alias, "depositBps")}, 'depositAmount', ${text(alias, "depositAmount", "null")}, 'depositRequired', ${has("depositRequired") ? `${alias}.${q("depositRequired")}` : "false"},
|
|
62351
|
+
'depositDue', ${text(alias, "depositDue", "'0'")},
|
|
61800
62352
|
'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,
|
|
62353
|
+
'taxTotal', ${alias}.${q("taxTotal")}::text, 'total', ${alias}.${q("total")}::text,
|
|
62354
|
+
'lines', ${version === void 0 ? withVersionLineIds(lines(alias), latestVersion(alias)) : withVersionLineIds(`coalesce(${version} -> 'lines', '[]'::jsonb)`, latestVersion(alias))},
|
|
62355
|
+
'taxLines', ${version === void 0 ? taxLines(alias) : `coalesce(${version} -> 'taxLines', '[]'::jsonb)`})`;
|
|
61802
62356
|
const checkParty = (kind, type, id, tenant) => (kind === "COMPANY" ? company : contact) ? `
|
|
61803
62357
|
if ${id} is not null and not ${subjectInTenant(ctx, type, id, tenant)} then
|
|
61804
62358
|
${fail$1(`QUOTE_${kind}_FORBIDDEN`, `the ${kind.toLowerCase()} is unknown or not readable in this organization`, "42501")}
|
|
@@ -61840,14 +62394,38 @@ function quoteKit(ctx, n) {
|
|
|
61840
62394
|
taxLines,
|
|
61841
62395
|
row,
|
|
61842
62396
|
publicJson,
|
|
62397
|
+
withVersionLineIds,
|
|
62398
|
+
latestVersion,
|
|
62399
|
+
versionLines,
|
|
62400
|
+
workingCopy,
|
|
61843
62401
|
record,
|
|
61844
62402
|
checkParty,
|
|
61845
62403
|
notifyOwner,
|
|
61846
62404
|
markViewed,
|
|
61847
|
-
depositDue: has("depositDue") && has("depositBps") ? `${q("depositDue")} = case when x.${q("
|
|
62405
|
+
depositDue: has("depositDue") && (has("depositBps") || has("depositAmount")) ? `${q("depositDue")} = case${has("depositAmount") ? ` when x.${q("depositAmount")} is not null then least(greatest(${total}, 0), x.${q("depositAmount")})` : ""}${has("depositBps") ? ` when x.${q("depositBps")} is not null then round(${total} * x.${q("depositBps")} / 10000.0)::bigint` : ""} else 0 end` : void 0
|
|
61848
62406
|
};
|
|
61849
62407
|
}
|
|
61850
62408
|
// src/sql/modules/quotes-decisions.ts
|
|
62409
|
+
/** The quote columns a customer sees of a published version. */
|
|
62410
|
+
const PUBLISHED = [
|
|
62411
|
+
"revision",
|
|
62412
|
+
"title",
|
|
62413
|
+
"currency",
|
|
62414
|
+
"validUntil",
|
|
62415
|
+
"terms",
|
|
62416
|
+
"pricesIncludeTax",
|
|
62417
|
+
"discountBps",
|
|
62418
|
+
"discountAmount",
|
|
62419
|
+
"depositBps",
|
|
62420
|
+
"depositAmount",
|
|
62421
|
+
"depositRequired",
|
|
62422
|
+
"depositDue",
|
|
62423
|
+
"listTotal",
|
|
62424
|
+
"subtotal",
|
|
62425
|
+
"discountTotal",
|
|
62426
|
+
"taxTotal",
|
|
62427
|
+
"total"
|
|
62428
|
+
];
|
|
61851
62429
|
/**
|
|
61852
62430
|
* The functions that take a customer's answer: recorded by staff, through the
|
|
61853
62431
|
* link, or by a signed-in guest the quote is shared with (ADR 0070), and the
|
|
@@ -61860,48 +62438,94 @@ function quoteDecisions(ctx, n, k) {
|
|
|
61860
62438
|
const guest = quoteGuest(ctx, n, "x.");
|
|
61861
62439
|
const noted = (note) => has("decisionNote") ? `v_row.${q("decisionNote")}` : `nullif(trim(${note}), '')`;
|
|
61862
62440
|
const selects = lineHas("optional") && lineHas("selected");
|
|
62441
|
+
const vl = (column) => n.c("versionLines", column);
|
|
62442
|
+
const position = (element) => k.versionLines ? `case when jsonb_typeof(${element}) = 'number' then (${element} #>> '{}')::numeric else (
|
|
62443
|
+
select vx.${vl("position")}::numeric from ${t("versionLines")} vx
|
|
62444
|
+
where vx.${vl("version")} = ${k.latestVersion("v_row")} and vx.${vl("id")}::text = ${element} #>> '{}'
|
|
62445
|
+
) end` : `(${element} #>> '{}')::numeric`;
|
|
61863
62446
|
const selection = (name) => selects ? `
|
|
61864
62447
|
if ${name}.selected is not null then
|
|
61865
62448
|
if jsonb_typeof(${name}.selected) <> 'array' or exists (
|
|
61866
62449
|
select 1 from jsonb_array_elements(${name}.selected) e
|
|
61867
|
-
where jsonb_typeof(e.value)
|
|
62450
|
+
where jsonb_typeof(e.value) not in ('number'${k.versionLines ? ", 'string'" : ""}) or not exists (
|
|
61868
62451
|
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
|
|
62452
|
+
where ql.${l("parent")} = v_row.${q("id")} and ql.${l("optional")} and ql.${l("position")} = ${position("e.value")}
|
|
61870
62453
|
)
|
|
61871
62454
|
) then
|
|
61872
|
-
${fail$1("QUOTE_SELECTION_INVALID",
|
|
62455
|
+
${fail$1("QUOTE_SELECTION_INVALID", `pick optional lines of this quote by position${k.versionLines ? " or version line id" : ""}`, "22023")}
|
|
61873
62456
|
end if;
|
|
61874
|
-
update ${t("lines")} ql set ${l("selected")} = ql.${l("position")} in (select (e.value
|
|
62457
|
+
update ${t("lines")} ql set ${l("selected")} = ql.${l("position")} in (select (${position("e.value")})::integer from jsonb_array_elements(${name}.selected) e)
|
|
61875
62458
|
where ql.${l("parent")} = v_row.${q("id")} and ql.${l("optional")};
|
|
61876
62459
|
end if;` : `
|
|
61877
62460
|
if ${name}.selected is not null and ${name}.selected <> '[]'::jsonb then
|
|
61878
62461
|
${fail$1("QUOTE_SELECTION_INVALID", "this quote has no optional lines", "22023")}
|
|
61879
62462
|
end if;`;
|
|
62463
|
+
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))`;
|
|
62464
|
+
const restored = [
|
|
62465
|
+
"title",
|
|
62466
|
+
"currency",
|
|
62467
|
+
"validUntil",
|
|
62468
|
+
"terms",
|
|
62469
|
+
"pricesIncludeTax",
|
|
62470
|
+
"discountBps",
|
|
62471
|
+
"discountAmount",
|
|
62472
|
+
"depositBps",
|
|
62473
|
+
"depositAmount",
|
|
62474
|
+
"depositRequired"
|
|
62475
|
+
].filter(has);
|
|
62476
|
+
const restore = k.workingCopy ? `
|
|
62477
|
+
if v_row.${q("unpublishedChanges")} then
|
|
62478
|
+
select v.${n.c("versions", "snapshot")} into v_snap from ${t("versions")} v where v.${n.c("versions", "id")} = ${k.latestVersion("v_row")};
|
|
62479
|
+
if v_snap is not null then
|
|
62480
|
+
v_pub := ${snapshotRecord([...restored, ...n.extras.map((extra) => extra.name)])};
|
|
62481
|
+
update ${t("quotes")} x set ${[...restored.map(q), ...n.extras.map((extra) => extra.ident)].map((column) => `${column} = v_pub.${column}`).join(", ")}
|
|
62482
|
+
where x.${q("id")} = v_row.${q("id")};
|
|
62483
|
+
perform ${fn("quote_lines_restore")}(v_row.${q("id")}, coalesce(v_snap -> 'lines', '[]'::jsonb));
|
|
62484
|
+
select * into v_row from ${t("quotes")} x where x.${q("id")} = v_row.${q("id")};
|
|
62485
|
+
end if;
|
|
62486
|
+
end if;` : "";
|
|
61880
62487
|
const client = (column, value) => has(column) ? `${q(column)} = ${value}, ` : "";
|
|
61881
62488
|
const headers = `
|
|
61882
|
-
v_headers jsonb := nullif(current_setting('request.headers', true), '')::jsonb
|
|
62489
|
+
v_headers jsonb := nullif(current_setting('request.headers', true), '')::jsonb;
|
|
62490
|
+
v_ip inet;`;
|
|
62491
|
+
const restoreVars = k.workingCopy ? `
|
|
62492
|
+
v_snap jsonb;
|
|
62493
|
+
v_pub ${t("quotes")};` : "";
|
|
61883
62494
|
const ip = "left(nullif(trim(reverse(split_part(reverse(v_headers ->> 'x-forwarded-for'), ',', 1))), ''), 64)";
|
|
62495
|
+
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)))`;
|
|
62496
|
+
const actorIp = (a) => a.actor === void 0 ? ip : `left(${a.actor} ->> 'ip', 64)`;
|
|
62497
|
+
const actorAgent = (a) => a.actor === void 0 ? "left(v_headers ->> 'user-agent', 512)" : `left(${a.actor} ->> 'userAgent', 512)`;
|
|
61884
62498
|
const answer = (a) => `
|
|
61885
62499
|
if ${a.name}.decision not in ('accepted', 'rejected', 'changes_requested') then
|
|
61886
62500
|
${fail$1("QUOTE_DECISION_INVALID", "answer accepted, rejected or changes_requested", "22023")}
|
|
61887
62501
|
end if;
|
|
61888
62502
|
if ${st(`v_row.${q("status")}`, ["sent", "viewed"], true)} then
|
|
61889
62503
|
${fail$1("QUOTE_NOT_OPEN", "this quote no longer takes an answer", "55000")}
|
|
61890
|
-
end if;${a.
|
|
61891
|
-
|
|
62504
|
+
end if;${a.actor === void 0 ? a.customer ? `
|
|
62505
|
+
begin
|
|
62506
|
+
v_ip := ${ip}::inet;
|
|
62507
|
+
exception when invalid_text_representation then
|
|
62508
|
+
v_ip := null;
|
|
62509
|
+
end;
|
|
62510
|
+
perform set_config('better_supabase.transition_actor', ${customerActor(a)}::text, true);` : "" : `
|
|
62511
|
+
${transitionActorSql(a.actor, "QUOTE_ACTOR_INVALID")}`}${a.expires === "false" ? "" : `
|
|
62512
|
+
if (${a.expires}) and v_row.${q("validUntil")} < current_date then
|
|
61892
62513
|
update ${t("quotes")} x set ${q("status")} = ${sv("expired")}, ${q("updatedAt")} = now() where x.${q("id")} = v_row.${q("id")}
|
|
61893
62514
|
returning * into v_row;
|
|
61894
62515
|
${record("quote.expired", "v_row")}
|
|
61895
62516
|
return jsonb_build_object('status', 'expired');
|
|
61896
|
-
end if;`
|
|
62517
|
+
end if;`}${a.customer ? `
|
|
61897
62518
|
if nullif(trim(${a.by}), '') is null then
|
|
61898
62519
|
${fail$1("QUOTE_NAME_REQUIRED", "say who answers", "23502")}
|
|
61899
62520
|
end if;` : ""}
|
|
61900
|
-
if ${a.name}.decision = 'accepted' then${
|
|
62521
|
+
if ${a.name}.decision = 'accepted' then${restore}${a.deposit && has("depositRequired") && has("depositDue") ? `
|
|
62522
|
+
if v_row.${q("depositRequired")} and v_row.${q("depositDue")} > 0 then
|
|
62523
|
+
${fail$1("QUOTE_DEPOSIT_REQUIRED", "pay the deposit before accepting; the app records the acceptance once it is paid", "55000")}
|
|
62524
|
+
end if;` : ""}${selection(a.name)}
|
|
61901
62525
|
${ctx.hook("before_quote_accept", [["uuid", `v_row.${q("id")}`]])}
|
|
61902
62526
|
end if;
|
|
61903
62527
|
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 ?
|
|
62528
|
+
${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
62529
|
where x.${q("id")} = v_row.${q("id")}
|
|
61906
62530
|
returning * into v_row;
|
|
61907
62531
|
case ${a.name}.decision
|
|
@@ -61916,13 +62540,23 @@ function quoteDecisions(ctx, n, k) {
|
|
|
61916
62540
|
${ctx.hook("after_quote_accept", [["uuid", `v_row.${q("id")}`]])}
|
|
61917
62541
|
end if;`;
|
|
61918
62542
|
const answered = `jsonb_build_object('status', ${ctx.label("quotes", "status", `v_row.${q("status")}`)}, 'identifier', v_row.${q("identifier")}, 'revision', v_row.${q("revision")})`;
|
|
62543
|
+
const customerView = k.workingCopy ? `select v.${n.c("versions", "snapshot")} into v_snap from ${t("versions")} v where v.${n.c("versions", "id")} = ${k.latestVersion("v_row")};
|
|
62544
|
+
if v_snap is null then
|
|
62545
|
+
return ${k.publicJson("v_row")};
|
|
62546
|
+
end if;
|
|
62547
|
+
v_pub := ${snapshotRecord(PUBLISHED.filter(has))};
|
|
62548
|
+
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
62549
|
const readable = (alias) => `(${n.service} or ${ctx.scope.can(`${alias}.${q("tenant")}`, n.read)})`;
|
|
61920
62550
|
return `
|
|
61921
62551
|
-- Records the customer's answer taken another way (by phone, by email):
|
|
61922
62552
|
-- decision is accepted, rejected or changes_requested; by is their name.
|
|
61923
|
-
-- selected lists the positions of the optional lines they took.
|
|
62553
|
+
-- selected lists the positions of the optional lines they took. actor is
|
|
62554
|
+
-- the customer when the app takes the answer in its own portal: id, name,
|
|
62555
|
+
-- email, ip and userAgent, kept with the answer and in the state machine's
|
|
62556
|
+
-- history; a quote past its valid date then expires instead.
|
|
61924
62557
|
drop function if exists ${fn("decide_quote")}(uuid, text, text, text);
|
|
61925
|
-
|
|
62558
|
+
drop function if exists ${fn("decide_quote")}(uuid, text, text, text, jsonb);
|
|
62559
|
+
create or replace function ${fn("decide_quote")}(quote uuid, decision text, note text, by text, selected jsonb default null, actor jsonb default null)
|
|
61926
62560
|
returns jsonb
|
|
61927
62561
|
language plpgsql
|
|
61928
62562
|
security definer
|
|
@@ -61930,21 +62564,23 @@ set search_path = ''
|
|
|
61930
62564
|
as $$
|
|
61931
62565
|
declare
|
|
61932
62566
|
v_row ${t("quotes")};
|
|
61933
|
-
v_claims text
|
|
62567
|
+
v_claims text;${restoreVars}
|
|
61934
62568
|
begin
|
|
61935
62569
|
select * into v_row from ${t("quotes")} x where x.${q("id")} = decide_quote.quote and ${editable("x")} for update;
|
|
61936
62570
|
if v_row.${q("id")} is null then
|
|
61937
62571
|
${fail$1("QUOTE_NOT_FOUND", "no such quote you can edit", "P0002")}
|
|
61938
62572
|
end if;${answer({
|
|
61939
62573
|
name: "decide_quote",
|
|
61940
|
-
by: "coalesce(nullif(trim(decide_quote.by), ''), auth.uid()::text)",
|
|
62574
|
+
by: "coalesce(nullif(trim(decide_quote.by), ''), nullif(trim(decide_quote.actor ->> 'name'), ''), decide_quote.actor ->> 'email', auth.uid()::text)",
|
|
61941
62575
|
customer: false,
|
|
61942
|
-
expires:
|
|
62576
|
+
expires: "decide_quote.actor is not null",
|
|
62577
|
+
actor: "decide_quote.actor",
|
|
62578
|
+
deposit: false
|
|
61943
62579
|
})}
|
|
61944
62580
|
return ${row("v_row")};
|
|
61945
62581
|
end;
|
|
61946
62582
|
$$;
|
|
61947
|
-
${userGrant(`${fn("decide_quote")}(uuid, text, text, text, jsonb)`)}
|
|
62583
|
+
${userGrant(`${fn("decide_quote")}(uuid, text, text, text, jsonb, jsonb)`)}
|
|
61948
62584
|
|
|
61949
62585
|
-- What the customer sees through the link: the quote without internal
|
|
61950
62586
|
-- notes. Opening a sent quote marks it viewed. Callable without signing in.
|
|
@@ -61955,14 +62591,14 @@ security definer
|
|
|
61955
62591
|
set search_path = ''
|
|
61956
62592
|
as $$
|
|
61957
62593
|
declare
|
|
61958
|
-
v_row ${t("quotes")}
|
|
62594
|
+
v_row ${t("quotes")};${restoreVars}
|
|
61959
62595
|
begin
|
|
61960
62596
|
select * into v_row from ${t("quotes")} x where x.${q("tokenHash")} = ${sha256Hex$1("public_quote.token")};
|
|
61961
62597
|
if v_row.${q("id")} is null then
|
|
61962
62598
|
${fail$1("QUOTE_LINK_INVALID", "this link is not valid", "P0002")}
|
|
61963
62599
|
end if;
|
|
61964
62600
|
${k.markViewed()}
|
|
61965
|
-
|
|
62601
|
+
${customerView}
|
|
61966
62602
|
end;
|
|
61967
62603
|
$$;
|
|
61968
62604
|
revoke all on function ${fn("public_quote")}(text) from public, anon, authenticated;
|
|
@@ -61981,7 +62617,7 @@ set search_path = ''
|
|
|
61981
62617
|
as $$
|
|
61982
62618
|
declare
|
|
61983
62619
|
v_row ${t("quotes")};${headers}
|
|
61984
|
-
v_claims text
|
|
62620
|
+
v_claims text;${restoreVars}
|
|
61985
62621
|
begin
|
|
61986
62622
|
select * into v_row from ${t("quotes")} x where x.${q("tokenHash")} = ${sha256Hex$1("respond_to_quote.token")} for update;
|
|
61987
62623
|
if v_row.${q("id")} is null then
|
|
@@ -61990,7 +62626,8 @@ begin
|
|
|
61990
62626
|
name: "respond_to_quote",
|
|
61991
62627
|
by: "respond_to_quote.name",
|
|
61992
62628
|
customer: true,
|
|
61993
|
-
expires: true
|
|
62629
|
+
expires: "true",
|
|
62630
|
+
deposit: true
|
|
61994
62631
|
})}
|
|
61995
62632
|
return ${answered};
|
|
61996
62633
|
end;
|
|
@@ -62000,7 +62637,8 @@ grant execute on function ${fn("respond_to_quote")}(text, text, text, text, json
|
|
|
62000
62637
|
|
|
62001
62638
|
-- A quote shared with the signed-in guest, as the customer sees it: through
|
|
62002
62639
|
-- 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.
|
|
62640
|
+
-- sent quote marks it viewed. No link token is needed. The service role
|
|
62641
|
+
-- reads it too, for an app's own portal.
|
|
62004
62642
|
create or replace function ${fn("portal_quote")}(quote uuid)
|
|
62005
62643
|
returns jsonb
|
|
62006
62644
|
language plpgsql
|
|
@@ -62008,14 +62646,14 @@ security definer
|
|
|
62008
62646
|
set search_path = ''
|
|
62009
62647
|
as $$
|
|
62010
62648
|
declare
|
|
62011
|
-
v_row ${t("quotes")}
|
|
62649
|
+
v_row ${t("quotes")};${restoreVars}
|
|
62012
62650
|
begin
|
|
62013
|
-
select * into v_row from ${t("quotes")} x where x.${q("id")} = portal_quote.quote and ${guest};
|
|
62651
|
+
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
62652
|
if v_row.${q("id")} is null then
|
|
62015
62653
|
${fail$1("QUOTE_NOT_FOUND", "no such quote shared with you", "P0002")}
|
|
62016
62654
|
end if;
|
|
62017
62655
|
${k.markViewed()}
|
|
62018
|
-
|
|
62656
|
+
${customerView}
|
|
62019
62657
|
end;
|
|
62020
62658
|
$$;
|
|
62021
62659
|
${userGrant(`${fn("portal_quote")}(uuid)`)}
|
|
@@ -62031,7 +62669,7 @@ set search_path = ''
|
|
|
62031
62669
|
as $$
|
|
62032
62670
|
declare
|
|
62033
62671
|
v_row ${t("quotes")};${headers}
|
|
62034
|
-
v_claims text
|
|
62672
|
+
v_claims text;${restoreVars}
|
|
62035
62673
|
begin
|
|
62036
62674
|
select * into v_row from ${t("quotes")} x where x.${q("id")} = respond_to_portal_quote.quote and ${guest} for update;
|
|
62037
62675
|
if v_row.${q("id")} is null then
|
|
@@ -62040,7 +62678,8 @@ begin
|
|
|
62040
62678
|
name: "respond_to_portal_quote",
|
|
62041
62679
|
by: "coalesce(nullif(trim(respond_to_portal_quote.name), ''), auth.jwt() ->> 'email')",
|
|
62042
62680
|
customer: true,
|
|
62043
|
-
expires: true
|
|
62681
|
+
expires: "true",
|
|
62682
|
+
deposit: true
|
|
62044
62683
|
})}
|
|
62045
62684
|
return ${answered};
|
|
62046
62685
|
end;
|
|
@@ -62088,7 +62727,8 @@ begin
|
|
|
62088
62727
|
if v_version.${v("id")} is null then
|
|
62089
62728
|
${fail$1("QUOTE_VERSION_NOT_FOUND", "this quote has no such version", "P0002")}
|
|
62090
62729
|
end if;
|
|
62091
|
-
return v_version.${v("snapshot")} || jsonb_build_object('revision', v_version.${v("revision")}, 'publishedAt', v_version.${v("publishedAt")}
|
|
62730
|
+
return v_version.${v("snapshot")} || jsonb_build_object('revision', v_version.${v("revision")}, 'publishedAt', v_version.${v("publishedAt")}${k.versionLines ? `,
|
|
62731
|
+
'lines', ${k.withVersionLineIds(`coalesce(v_version.${v("snapshot")} -> 'lines', '[]'::jsonb)`, `v_version.${v("id")}`)}` : ""});
|
|
62092
62732
|
end;
|
|
62093
62733
|
$$;
|
|
62094
62734
|
${userGrant(`${fn("quote_version")}(uuid, integer)`)}
|
|
@@ -62132,8 +62772,40 @@ function quoteFunctions(ctx, n) {
|
|
|
62132
62772
|
refuse(has("pricesIncludeTax"), `nullif(${attrs} ->> 'pricesIncludeTax', 'false')`, "PRICING", "prices_include_tax column"),
|
|
62133
62773
|
refuse(has("discountBps"), `nullif(${attrs} ->> 'discountBps', '0')`, "DISCOUNT", "discount column"),
|
|
62134
62774
|
refuse(has("discountAmount"), `nullif(${attrs} ->> 'discountAmount', '0')`, "DISCOUNT", "discount amount column"),
|
|
62135
|
-
refuse(has("depositBps"), `${attrs} ->> 'depositBps'`, "DEPOSIT", "deposit column")
|
|
62775
|
+
refuse(has("depositBps"), `${attrs} ->> 'depositBps'`, "DEPOSIT", "deposit column"),
|
|
62776
|
+
refuse(has("depositAmount"), `${attrs} ->> 'depositAmount'`, "DEPOSIT", "deposit amount column"),
|
|
62777
|
+
refuse(has("depositRequired"), `nullif(${attrs} ->> 'depositRequired', 'false')`, "DEPOSIT", "deposit required column")
|
|
62136
62778
|
].join("");
|
|
62779
|
+
const oneDeposit = has("depositBps") && has("depositAmount") ? `
|
|
62780
|
+
if v_row.${q("depositBps")} is not null and v_row.${q("depositAmount")} is not null then
|
|
62781
|
+
${fail$1("QUOTE_ATTRS_INVALID", "a deposit is a share (depositBps) or an amount (depositAmount), not both", "22023")}
|
|
62782
|
+
end if;` : "";
|
|
62783
|
+
const actor = (name) => `\n ${transitionActorSql(`${name}.actor`, "QUOTE_ACTOR_INVALID")}`;
|
|
62784
|
+
const publishedBy = `coalesce(auth.uid(), nullif(send_quote.actor ->> 'id', '')::uuid)`;
|
|
62785
|
+
const versionLinesCopy = (() => {
|
|
62786
|
+
if (!k.versionLines) return "";
|
|
62787
|
+
const vl = (column) => n.c("versionLines", column);
|
|
62788
|
+
const copied = [
|
|
62789
|
+
"position",
|
|
62790
|
+
"description",
|
|
62791
|
+
"quantity",
|
|
62792
|
+
"unitAmount",
|
|
62793
|
+
"periods",
|
|
62794
|
+
"discountBps",
|
|
62795
|
+
"taxRateBps",
|
|
62796
|
+
"taxCode",
|
|
62797
|
+
"section",
|
|
62798
|
+
"optional",
|
|
62799
|
+
"selected",
|
|
62800
|
+
"productType",
|
|
62801
|
+
"productId"
|
|
62802
|
+
].filter((column) => declared(ctx, "versionLines", column) && declared(ctx, "lines", column));
|
|
62803
|
+
const value = (column) => column === "productType" ? ctx.cast("versionLines", column, `ql.${l(column)}::text`) : `ql.${l(column)}`;
|
|
62804
|
+
return `
|
|
62805
|
+
insert into ${t("versionLines")} (${vl("tenant")}, ${vl("version")}, ${copied.map(vl).join(", ")})
|
|
62806
|
+
select v_row.${q("tenant")}, v_version, ${copied.map(value).join(", ")}
|
|
62807
|
+
from ${t("lines")} ql where ql.${l("parent")} = v_row.${q("id")};`;
|
|
62808
|
+
})();
|
|
62137
62809
|
const deals = ctx.installed("deals") ? ctx.of("deals") : void 0;
|
|
62138
62810
|
const fromDeal = deals === void 0 ? "" : (() => {
|
|
62139
62811
|
const d = (column) => deals.col("deals", column);
|
|
@@ -62191,8 +62863,9 @@ ${userGrant(`${fn("quote_from_deal")}(uuid)`)}
|
|
|
62191
62863
|
-- Creates a draft quote. attrs: title (required), currency, company and
|
|
62192
62864
|
-- contact ({ type, id }), ownerId, validUntil, terms, note, origin ({ type,
|
|
62193
62865
|
-- id }, the record it was made from), pricesIncludeTax, discountBps,
|
|
62194
|
-
-- discountAmount (minor units as text)
|
|
62195
|
-
--
|
|
62866
|
+
-- discountAmount (minor units as text), depositBps, or depositAmount (minor
|
|
62867
|
+
-- units as text) for a fixed deposit, and depositRequired, which makes the
|
|
62868
|
+
-- customer pay it before they accept. lines: see set_quote_lines.
|
|
62196
62869
|
create or replace function ${fn("create_quote")}(tenant ${ctx.idType}, attrs jsonb, lines jsonb)
|
|
62197
62870
|
returns jsonb
|
|
62198
62871
|
language plpgsql
|
|
@@ -62225,7 +62898,7 @@ begin
|
|
|
62225
62898
|
})}
|
|
62226
62899
|
begin
|
|
62227
62900
|
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})
|
|
62901
|
+
${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
62902
|
values (${valueLines(" ", [
|
|
62230
62903
|
"create_quote.tenant",
|
|
62231
62904
|
"v_seq",
|
|
@@ -62236,12 +62909,14 @@ begin
|
|
|
62236
62909
|
present("discountBps", "coalesce((create_quote.attrs ->> 'discountBps')::integer, 0)"),
|
|
62237
62910
|
present("discountAmount", "coalesce((create_quote.attrs ->> 'discountAmount')::bigint, 0)"),
|
|
62238
62911
|
present("depositBps", "(create_quote.attrs ->> 'depositBps')::integer"),
|
|
62912
|
+
present("depositAmount", "(create_quote.attrs ->> 'depositAmount')::bigint"),
|
|
62913
|
+
present("depositRequired", "coalesce((create_quote.attrs ->> 'depositRequired')::boolean, false)"),
|
|
62239
62914
|
present("createdBy", "auth.uid()")
|
|
62240
62915
|
])}${insertExtraColumns(t("quotes"), n.extras, "coalesce(create_quote.attrs -> 'fields', '{}'::jsonb)").values})
|
|
62241
62916
|
returning * into v_row;
|
|
62242
62917
|
exception when check_violation or invalid_text_representation or datetime_field_overflow or numeric_value_out_of_range then
|
|
62243
62918
|
${fail$1("QUOTE_ATTRS_INVALID", "a quote field has an invalid value", "22023")}
|
|
62244
|
-
end
|
|
62919
|
+
end;${oneDeposit}
|
|
62245
62920
|
if create_quote.lines is not null then
|
|
62246
62921
|
perform ${fn("set_quote_lines")}(v_row.${q("id")}, create_quote.lines);
|
|
62247
62922
|
end if;${origin ? `
|
|
@@ -62262,8 +62937,8 @@ ${userGrant(`${fn("create_quote")}(${ctx.idType}, jsonb, jsonb)`)}
|
|
|
62262
62937
|
|
|
62263
62938
|
-- Changes a draft quote, or one the customer asked changes on: title,
|
|
62264
62939
|
-- company, contact, currency, ownerId, validUntil, terms, note,
|
|
62265
|
-
-- pricesIncludeTax, discountBps, discountAmount
|
|
62266
|
-
-- follow the new pricing.
|
|
62940
|
+
-- pricesIncludeTax, discountBps, discountAmount, depositBps, depositAmount
|
|
62941
|
+
-- 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
62942
|
create or replace function ${fn("update_quote")}(quote uuid, attrs jsonb)
|
|
62268
62943
|
returns jsonb
|
|
62269
62944
|
language plpgsql
|
|
@@ -62285,14 +62960,14 @@ begin
|
|
|
62285
62960
|
${q("title")} = coalesce(nullif(trim(update_quote.attrs ->> 'title'), ''), x.${q("title")}),
|
|
62286
62961
|
${q("currency")} = coalesce(upper(update_quote.attrs ->> 'currency'), x.${q("currency")}),
|
|
62287
62962
|
${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`) : ""}
|
|
62963
|
+
${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
62964
|
${q("updatedAt")} = now()
|
|
62290
62965
|
where x.${q("id")} = v_row.${q("id")}
|
|
62291
62966
|
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
62967
|
select * into v_row from ${t("quotes")} x where x.${q("id")} = v_row.${q("id")};`}
|
|
62293
62968
|
exception when check_violation or invalid_text_representation or datetime_field_overflow or numeric_value_out_of_range then
|
|
62294
62969
|
${fail$1("QUOTE_ATTRS_INVALID", "a quote field has an invalid value", "22023")}
|
|
62295
|
-
end
|
|
62970
|
+
end;${oneDeposit}
|
|
62296
62971
|
perform ${fn("set_quote_lines_recount")}(v_row.${q("id")});
|
|
62297
62972
|
select * into v_row from ${t("quotes")} x where x.${q("id")} = v_row.${q("id")};
|
|
62298
62973
|
${record("quote.updated", "v_row")}
|
|
@@ -62311,15 +62986,19 @@ ${lineItemsSql(ctx, {
|
|
|
62311
62986
|
setter: "set_quote_lines",
|
|
62312
62987
|
guard: `if not exists (select 1 from ${t("quotes")} x where x.${q("id")} = v_parent and ${editable("x")}) then
|
|
62313
62988
|
${fail$1("QUOTE_NOT_FOUND", "no such quote you can edit", "P0002")}
|
|
62314
|
-
end if
|
|
62315
|
-
|
|
62989
|
+
end if;${k.workingCopy ? `
|
|
62990
|
+
update ${t("quotes")} x set ${q("unpublishedChanges")} = true where x.${q("id")} = v_parent;` : ""}`,
|
|
62991
|
+
...catalogPrice ? { fallback: catalogPrice } : {},
|
|
62992
|
+
...k.workingCopy ? { restorer: "quote_lines_restore" } : {}
|
|
62316
62993
|
})}
|
|
62317
62994
|
-- Sends a quote: it gets a public link the customer opens and a published
|
|
62318
62995
|
-- version, a snapshot that never changes. The quote can't change until it is
|
|
62319
62996
|
-- revised or the customer asks for changes; sending it again then publishes
|
|
62320
62997
|
-- the next revision. Returns the quote with the link's token, which is stored
|
|
62321
|
-
-- only as a hash and returned this once.
|
|
62322
|
-
|
|
62998
|
+
-- 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." : ""}
|
|
62999
|
+
-- actor: who sent it, for the state machine's history.
|
|
63000
|
+
drop function if exists ${fn("send_quote")}(uuid);
|
|
63001
|
+
create or replace function ${fn("send_quote")}(quote uuid, actor jsonb default null)
|
|
62323
63002
|
returns jsonb
|
|
62324
63003
|
language plpgsql
|
|
62325
63004
|
security definer
|
|
@@ -62328,6 +63007,7 @@ as $$
|
|
|
62328
63007
|
declare
|
|
62329
63008
|
v_row ${t("quotes")};
|
|
62330
63009
|
v_token text := encode(extensions.gen_random_bytes(24), 'hex');
|
|
63010
|
+
v_version uuid;${k.workingCopy ? "\n v_linked boolean;" : ""}
|
|
62331
63011
|
begin
|
|
62332
63012
|
select * into v_row from ${t("quotes")} x where x.${q("id")} = send_quote.quote and ${editable("x")} for update;
|
|
62333
63013
|
if v_row.${q("id")} is null then
|
|
@@ -62338,27 +63018,29 @@ begin
|
|
|
62338
63018
|
end if;
|
|
62339
63019
|
if not exists (select 1 from ${t("lines")} x where x.${l("parent")} = v_row.${q("id")}) then
|
|
62340
63020
|
${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")},
|
|
63021
|
+
end if;${actor("send_quote")}
|
|
63022
|
+
${ctx.hook("before_quote_send", [["uuid", `v_row.${q("id")}`]])}${k.workingCopy ? `\n v_linked := v_row.${q("tokenHash")} is not null;` : ""}
|
|
63023
|
+
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
63024
|
${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()
|
|
63025
|
+
${decisionReset}${k.workingCopy ? `${q("unpublishedChanges")} = false, ` : ""}${q("updatedAt")} = now()
|
|
62346
63026
|
where x.${q("id")} = v_row.${q("id")}
|
|
62347
63027
|
returning * into v_row;
|
|
62348
63028
|
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") ?
|
|
63029
|
+
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}` : ""})
|
|
63030
|
+
returning ${v("id")} into v_version;${versionLinesCopy}
|
|
62350
63031
|
${record("quote.sent", "v_row", `, 'revision', v_row.${q("revision")}`)}
|
|
62351
63032
|
${ctx.hook("after_quote_send", [["uuid", `v_row.${q("id")}`]])}
|
|
62352
|
-
return ${row("v_row")} || jsonb_build_object('token', v_token);
|
|
63033
|
+
return ${row("v_row")} || jsonb_build_object('token', ${k.workingCopy ? "case when v_linked then null else v_token end" : "v_token"});
|
|
62353
63034
|
end;
|
|
62354
63035
|
$$;
|
|
62355
|
-
${userGrant(`${fn("send_quote")}(uuid)`)}
|
|
63036
|
+
${userGrant(`${fn("send_quote")}(uuid, jsonb)`)}
|
|
62356
63037
|
|
|
62357
63038
|
-- Opens a sent or declined quote again as a draft of its next revision: the
|
|
62358
63039
|
-- same quote, number and lines, a fresh valid-until date, and its link ends.
|
|
62359
63040
|
-- 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
|
-
|
|
63041
|
+
-- 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." : ""}
|
|
63042
|
+
drop function if exists ${fn("revise_quote")}(uuid);
|
|
63043
|
+
create or replace function ${fn("revise_quote")}(quote uuid, actor jsonb default null)
|
|
62362
63044
|
returns jsonb
|
|
62363
63045
|
language plpgsql
|
|
62364
63046
|
security definer
|
|
@@ -62376,17 +63058,50 @@ begin
|
|
|
62376
63058
|
end if;
|
|
62377
63059
|
if ${st(`v_row.${q("status")}`, ["accepted"])} then
|
|
62378
63060
|
${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")} =
|
|
63061
|
+
end if;${actor("revise_quote")}
|
|
63062
|
+
${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,
|
|
63063
|
+
${q("validUntil")} = greatest(x.${q("validUntil")}, current_date + ${String(n.validDays)}),
|
|
63064
|
+
${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
63065
|
${q("validUntil")} = greatest(x.${q("validUntil")}, current_date + ${String(n.validDays)}),
|
|
62382
|
-
${decisionReset}${q("updatedAt")} = now()
|
|
63066
|
+
${decisionReset}${q("updatedAt")} = now()`}
|
|
62383
63067
|
where x.${q("id")} = v_row.${q("id")}
|
|
62384
63068
|
returning * into v_row;
|
|
62385
63069
|
${record("quote.revised", "v_row", `, 'revision', v_row.${q("revision")}`)}
|
|
62386
63070
|
return ${row("v_row")};
|
|
62387
63071
|
end;
|
|
62388
63072
|
$$;
|
|
62389
|
-
${userGrant(`${fn("revise_quote")}(uuid)`)}
|
|
63073
|
+
${userGrant(`${fn("revise_quote")}(uuid, jsonb)`)}
|
|
63074
|
+
|
|
63075
|
+
-- Takes back a sent quote the customer hasn't accepted: it can't be answered
|
|
63076
|
+
-- any more until it is revised and sent again.
|
|
63077
|
+
create or replace function ${fn("withdraw_quote")}(quote uuid, actor jsonb default null)
|
|
63078
|
+
returns jsonb
|
|
63079
|
+
language plpgsql
|
|
63080
|
+
security definer
|
|
63081
|
+
set search_path = ''
|
|
63082
|
+
as $$
|
|
63083
|
+
declare
|
|
63084
|
+
v_row ${t("quotes")};
|
|
63085
|
+
begin
|
|
63086
|
+
select * into v_row from ${t("quotes")} x where x.${q("id")} = withdraw_quote.quote and ${editable("x")} for update;
|
|
63087
|
+
if v_row.${q("id")} is null then
|
|
63088
|
+
${fail$1("QUOTE_NOT_FOUND", "no such quote you can edit", "P0002")}
|
|
63089
|
+
end if;
|
|
63090
|
+
if ${st(`v_row.${q("status")}`, [
|
|
63091
|
+
"sent",
|
|
63092
|
+
"viewed",
|
|
63093
|
+
"changes_requested"
|
|
63094
|
+
], true)} then
|
|
63095
|
+
${fail$1("QUOTE_NOT_OPEN", "only a sent quote that wasn't answered is withdrawn", "55000")}
|
|
63096
|
+
end if;${actor("withdraw_quote")}
|
|
63097
|
+
update ${t("quotes")} x set ${q("status")} = ${sv("withdrawn")}, ${q("updatedAt")} = now()
|
|
63098
|
+
where x.${q("id")} = v_row.${q("id")}
|
|
63099
|
+
returning * into v_row;
|
|
63100
|
+
${record("quote.withdrawn", "v_row", `, 'revision', v_row.${q("revision")}`)}
|
|
63101
|
+
return ${row("v_row")};
|
|
63102
|
+
end;
|
|
63103
|
+
$$;
|
|
63104
|
+
${userGrant(`${fn("withdraw_quote")}(uuid, jsonb)`)}
|
|
62390
63105
|
${quoteDecisions(ctx, n, k)}
|
|
62391
63106
|
-- Expires sent quotes past their valid date. Run it daily from a job.
|
|
62392
63107
|
create or replace function ${fn("expire_quotes")}()
|
|
@@ -65921,7 +66636,8 @@ function standaloneContract(ctx) {
|
|
|
65921
66636
|
args: [
|
|
65922
66637
|
"uuid",
|
|
65923
66638
|
"boolean",
|
|
65924
|
-
"text"
|
|
66639
|
+
"text",
|
|
66640
|
+
"uuid"
|
|
65925
66641
|
],
|
|
65926
66642
|
returns: "jsonb"
|
|
65927
66643
|
},
|
|
@@ -66221,7 +66937,9 @@ end;
|
|
|
66221
66937
|
$$;
|
|
66222
66938
|
${userGrant(`${fn("delete_expense")}(uuid)`)}
|
|
66223
66939
|
|
|
66224
|
-
|
|
66940
|
+
-- The service role names the user it decides for in decided_by.
|
|
66941
|
+
drop function if exists ${fn("decide_expense")}(uuid, boolean, text);
|
|
66942
|
+
create or replace function ${fn("decide_expense")}(expense_id uuid, approved boolean, note text default null, decided_by uuid default null)
|
|
66225
66943
|
returns jsonb
|
|
66226
66944
|
language plpgsql
|
|
66227
66945
|
security definer
|
|
@@ -66233,6 +66951,10 @@ begin${load("decide_expense.expense_id")}
|
|
|
66233
66951
|
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
66952
|
${forbidden("not allowed to decide this expense")}
|
|
66235
66953
|
end if;
|
|
66954
|
+
if decide_expense.decided_by is not null and (not ${SERVICE_CALLER$1} and decide_expense.decided_by is distinct from auth.uid()
|
|
66955
|
+
or decide_expense.decided_by = ${owner.requester("v_row")}) then
|
|
66956
|
+
${forbidden("only the service role decides for another user, never for the owner")}
|
|
66957
|
+
end if;
|
|
66236
66958
|
if ${status("v_row")} <> 'submitted' then
|
|
66237
66959
|
${fail$1("EXPENSE_LOCKED", "only a submitted expense is decided", "55000")}
|
|
66238
66960
|
end if;
|
|
@@ -66240,12 +66962,12 @@ begin${load("decide_expense.expense_id")}
|
|
|
66240
66962
|
${invalid("approved must be true or false")}
|
|
66241
66963
|
end if;${unsupported("decisionNote", "nullif(trim(decide_expense.note), '')")}
|
|
66242
66964
|
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), '')")}
|
|
66965
|
+
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
66966
|
where x.${e("id")} = v_row.${e("id")}
|
|
66245
66967
|
returning * into v_row;
|
|
66246
66968
|
${record("expense.approved", "approved an expense")}
|
|
66247
66969
|
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), '')")}
|
|
66970
|
+
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
66971
|
where x.${e("id")} = v_row.${e("id")}
|
|
66250
66972
|
returning * into v_row;
|
|
66251
66973
|
${record("expense.rejected", "rejected an expense")}
|
|
@@ -66253,7 +66975,7 @@ begin${load("decide_expense.expense_id")}
|
|
|
66253
66975
|
return ${json("v_row")};
|
|
66254
66976
|
end;
|
|
66255
66977
|
$$;
|
|
66256
|
-
${userGrant(`${fn("decide_expense")}(uuid, boolean, text)`)}
|
|
66978
|
+
${userGrant(`${fn("decide_expense")}(uuid, boolean, text, uuid)`)}
|
|
66257
66979
|
|
|
66258
66980
|
create or replace function ${fn("reimburse_expense")}(expense_id uuid, reference text default null)
|
|
66259
66981
|
returns jsonb
|
|
@@ -66402,8 +67124,9 @@ function expensesFunctions(ctx) {
|
|
|
66402
67124
|
-- Approves or rejects a submitted report without the approvals block: the
|
|
66403
67125
|
-- service role, or a member with the approve permission who doesn't own it.
|
|
66404
67126
|
-- Approval books it like a final approval; a rejected report can change and
|
|
66405
|
-
-- go in again.
|
|
66406
|
-
|
|
67127
|
+
-- go in again. The service role names the user it decides for in decided_by.
|
|
67128
|
+
drop function if exists ${fn("decide_expense_report")}(uuid, boolean, text);
|
|
67129
|
+
create or replace function ${fn("decide_expense_report")}(report_id uuid, approved boolean, note text default null, decided_by uuid default null)
|
|
66407
67130
|
returns jsonb
|
|
66408
67131
|
language plpgsql
|
|
66409
67132
|
security definer
|
|
@@ -66415,6 +67138,10 @@ begin${loadReport("decide_expense_report.report_id", true)}
|
|
|
66415
67138
|
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
67139
|
${forbidden("not allowed to decide this expense report")}
|
|
66417
67140
|
end if;
|
|
67141
|
+
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()
|
|
67142
|
+
or decide_expense_report.decided_by = v_row.${r("user")}) then
|
|
67143
|
+
${forbidden("only the service role decides for another user, never for the owner")}
|
|
67144
|
+
end if;
|
|
66418
67145
|
if ${status("v_row", "")} <> 'submitted' then
|
|
66419
67146
|
${fail$1("EXPENSE_REPORT_LOCKED", "only a submitted report is decided", "55000")}
|
|
66420
67147
|
end if;
|
|
@@ -66423,11 +67150,11 @@ begin${loadReport("decide_expense_report.report_id", true)}
|
|
|
66423
67150
|
end if;
|
|
66424
67151
|
if decide_expense_report.approved then
|
|
66425
67152
|
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), '')")}
|
|
67153
|
+
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
67154
|
where x.${r("id")} = v_row.${r("id")}
|
|
66428
67155
|
returning * into v_row;
|
|
66429
67156
|
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), '')")}
|
|
67157
|
+
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
67158
|
where x.${r("id")} = v_row.${r("id")}
|
|
66432
67159
|
returning * into v_row;
|
|
66433
67160
|
${reportRecord("expense_report.rejected", "rejected an expense report")}` : `
|
|
@@ -66436,7 +67163,7 @@ begin${loadReport("decide_expense_report.report_id", true)}
|
|
|
66436
67163
|
return ${reportJson("v_row", "")};
|
|
66437
67164
|
end;
|
|
66438
67165
|
$$;
|
|
66439
|
-
${userGrant(`${fn("decide_expense_report")}(uuid, boolean, text)`)}
|
|
67166
|
+
${userGrant(`${fn("decide_expense_report")}(uuid, boolean, text, uuid)`)}
|
|
66440
67167
|
`;
|
|
66441
67168
|
const total = (row) => `coalesce((select sum(y.${x("amount")}) from ${lines} y where y.${x("report")} = ${row}.${r("id")}), 0)`;
|
|
66442
67169
|
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)})`;
|
|
@@ -67360,7 +68087,8 @@ function contract$63(ctx) {
|
|
|
67360
68087
|
args: [
|
|
67361
68088
|
"uuid",
|
|
67362
68089
|
"boolean",
|
|
67363
|
-
"text"
|
|
68090
|
+
"text",
|
|
68091
|
+
"uuid"
|
|
67364
68092
|
],
|
|
67365
68093
|
returns: "jsonb"
|
|
67366
68094
|
}],
|
|
@@ -75167,7 +75895,7 @@ const INBOX_NAMES = {
|
|
|
75167
75895
|
was: "conversations"
|
|
75168
75896
|
}]
|
|
75169
75897
|
};
|
|
75170
|
-
const NAME$
|
|
75898
|
+
const NAME$4 = /^[a-z][a-z0-9_-]{0,30}$/;
|
|
75171
75899
|
/** What a row's JSON holds for an optional column the app's table lacks. */
|
|
75172
75900
|
const JSON_FALLBACKS = {
|
|
75173
75901
|
settings: "'{}'::jsonb",
|
|
@@ -75192,7 +75920,7 @@ function inboxSql(ctx, operations) {
|
|
|
75192
75920
|
return sqlString(operationPermission(operations, `${OPERATION_PREFIXES.inboxCommand}${name}`, fallback) ?? fallback);
|
|
75193
75921
|
};
|
|
75194
75922
|
const topic = ctx.text("topic", "inbox");
|
|
75195
|
-
if (!NAME$
|
|
75923
|
+
if (!NAME$4.test(topic)) throw new TypeError("blocks.inbox.options.topic must be a lowercase name of at most 31 characters");
|
|
75196
75924
|
const bucket = ctx.text("bucket", "inbox-files");
|
|
75197
75925
|
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
75926
|
const maxBody = ctx.number("maxBodyLength", 2e4);
|
|
@@ -85817,7 +86545,7 @@ ${userGrant(`${fn("delete_invoice")}(uuid)`)}
|
|
|
85817
86545
|
if v_row.${i("id")} is not null then
|
|
85818
86546
|
return ${row("v_row")};
|
|
85819
86547
|
end if;
|
|
85820
|
-
select coalesce(jsonb_agg(jsonb_build_object('description', x.${ql("description")}, 'quantity', x.${ql("quantity")}, 'unitAmount', x.${ql("unitAmount")}::text,
|
|
86548
|
+
select coalesce(jsonb_agg(jsonb_build_object('description', x.${ql("description")}, 'quantity', x.${ql("quantity")}${declared(quotes, "lines", "periods") ? ` * coalesce(x.${ql("periods")}, 1)` : ""}, 'unitAmount', x.${ql("unitAmount")}::text,
|
|
85821
86549
|
'discountBps', ${lineColumn(quotes, "lines", "x", "discountBps")}, 'taxRateBps', ${lineColumn(quotes, "lines", "x", "taxRateBps")}, 'taxCode', ${lineColumn(quotes, "lines", "x", "taxCode")},
|
|
85822
86550
|
'product', case when ${lineColumn(quotes, "lines", "x", "productType")} is null then null else jsonb_build_object('type', ${lineColumn(quotes, "lines", "x", "productType")}, 'id', ${lineColumn(quotes, "lines", "x", "productId")}) end
|
|
85823
86551
|
) order by x.${ql("position")}), '[]'::jsonb) into v_lines
|
|
@@ -86039,8 +86767,10 @@ ${updateInvoiceSql()}${lineItemsSql(ctx, {
|
|
|
86039
86767
|
-- Issues a draft: it gets the next number of its kind (gapless, so a
|
|
86040
86768
|
-- number is only taken when the invoice is final), its issue and due date,
|
|
86041
86769
|
-- and its lines freeze. A credit note reduces the balance of its original.
|
|
86770
|
+
-- actor: who issued it, for the state machine's history.
|
|
86042
86771
|
drop function if exists ${fn("issue_invoice")}(uuid, date);
|
|
86043
|
-
|
|
86772
|
+
drop function if exists ${fn("issue_invoice")}(uuid, date, date);
|
|
86773
|
+
create or replace function ${fn("issue_invoice")}(invoice uuid, issued_on date, due_on date default null, actor jsonb default null)
|
|
86044
86774
|
returns jsonb
|
|
86045
86775
|
language plpgsql
|
|
86046
86776
|
security definer
|
|
@@ -86066,6 +86796,7 @@ begin
|
|
|
86066
86796
|
if issue_invoice.due_on < v_issued_on then
|
|
86067
86797
|
${fail$1("INVOICE_DUE_INVALID", "an invoice falls due on or after its issue date", "22023")}
|
|
86068
86798
|
end if;
|
|
86799
|
+
${transitionActorSql("issue_invoice.actor", "INVOICE_ACTOR_INVALID")}
|
|
86069
86800
|
${ctx.hook("before_invoice_issue", [["uuid", `v_row.${i("id")}`]])}
|
|
86070
86801
|
if ${kd(`v_row.${i("kind")}`, ["credit_note"])} then
|
|
86071
86802
|
select * into v_original from ${t("invoices")} x where x.${i("id")} = v_row.${i("original")} for update;
|
|
@@ -86112,15 +86843,17 @@ begin
|
|
|
86112
86843
|
return ${row("v_row")};
|
|
86113
86844
|
end;
|
|
86114
86845
|
$$;
|
|
86115
|
-
${userGrant(`${fn("issue_invoice")}(uuid, date, date)`)}
|
|
86846
|
+
${userGrant(`${fn("issue_invoice")}(uuid, date, date, jsonb)`)}
|
|
86116
86847
|
|
|
86117
86848
|
-- Records a payment (a negative amount is a refund) in the invoice's
|
|
86118
86849
|
-- currency as a ledger transaction from the invoice's receivable account to
|
|
86119
86850
|
-- 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.
|
|
86851
|
+
-- organization, so recording the same payment twice adds it once. actor:
|
|
86852
|
+
-- who recorded it, for the state machine's history.
|
|
86121
86853
|
drop function if exists ${fn("record_invoice_payment")}(uuid, bigint, timestamptz, text, text);
|
|
86122
86854
|
drop function if exists ${fn("record_invoice_payment")}(uuid, bigint, text, timestamptz, text, text);
|
|
86123
|
-
|
|
86855
|
+
drop function if exists ${fn("record_invoice_payment")}(uuid, bigint, text, timestamptz, text, text, text);
|
|
86856
|
+
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
86857
|
returns jsonb
|
|
86125
86858
|
language plpgsql
|
|
86126
86859
|
security definer
|
|
@@ -86154,6 +86887,7 @@ begin
|
|
|
86154
86887
|
if upper(record_invoice_payment.currency) is distinct from v_row.${i("currency")} then
|
|
86155
86888
|
${fail$1("INVOICE_CURRENCY_MISMATCH", "a payment must be in the invoice's currency", "22023")}
|
|
86156
86889
|
end if;
|
|
86890
|
+
${transitionActorSql("record_invoice_payment.actor", "INVOICE_ACTOR_INVALID")}
|
|
86157
86891
|
-- A recorded reference is a replay that adds nothing, so it skips the check.
|
|
86158
86892
|
v_reference := nullif(trim(record_invoice_payment.reference), '');
|
|
86159
86893
|
if v_reference is not null and exists (
|
|
@@ -86176,7 +86910,7 @@ begin
|
|
|
86176
86910
|
return ${row("v_row")};
|
|
86177
86911
|
end;
|
|
86178
86912
|
$$;
|
|
86179
|
-
${userGrant(`${fn("record_invoice_payment")}(uuid, bigint, text, timestamptz, text, text, text)`)}
|
|
86913
|
+
${userGrant(`${fn("record_invoice_payment")}(uuid, bigint, text, timestamptz, text, text, text, jsonb)`)}
|
|
86180
86914
|
|
|
86181
86915
|
create or replace function ${fn("list_invoice_payments")}(invoice uuid)
|
|
86182
86916
|
returns jsonb
|
|
@@ -86769,7 +87503,8 @@ function contract$48(ctx) {
|
|
|
86769
87503
|
args: [
|
|
86770
87504
|
"uuid",
|
|
86771
87505
|
"date",
|
|
86772
|
-
"date"
|
|
87506
|
+
"date",
|
|
87507
|
+
"jsonb"
|
|
86773
87508
|
],
|
|
86774
87509
|
returns: "jsonb"
|
|
86775
87510
|
},
|
|
@@ -86782,7 +87517,8 @@ function contract$48(ctx) {
|
|
|
86782
87517
|
"timestamptz",
|
|
86783
87518
|
"text",
|
|
86784
87519
|
"text",
|
|
86785
|
-
"text"
|
|
87520
|
+
"text",
|
|
87521
|
+
"jsonb"
|
|
86786
87522
|
],
|
|
86787
87523
|
returns: "jsonb"
|
|
86788
87524
|
},
|
|
@@ -89546,7 +90282,8 @@ function leaveContract(ctx) {
|
|
|
89546
90282
|
args: [
|
|
89547
90283
|
"uuid",
|
|
89548
90284
|
"boolean",
|
|
89549
|
-
"text"
|
|
90285
|
+
"text",
|
|
90286
|
+
"uuid"
|
|
89550
90287
|
],
|
|
89551
90288
|
returns: "jsonb"
|
|
89552
90289
|
}] : [],
|
|
@@ -90240,10 +90977,10 @@ function build$51(ctx) {
|
|
|
90240
90977
|
const approve = ctx.permission("approve", permissions.approve);
|
|
90241
90978
|
const decision = (column, value) => ctx.has("requests", column) ? `, ${q(column)} = ${value}` : "";
|
|
90242
90979
|
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)
|
|
90980
|
+
-- Approves or rejects a pending request without the approvals block, as the
|
|
90981
|
+
-- service role or an approver who didn't ask; approval books the leave.
|
|
90982
|
+
drop function if exists ${fn("decide_leave_request")}(uuid, boolean, text);
|
|
90983
|
+
create or replace function ${fn("decide_leave_request")}(request_id uuid, approved boolean, note text default null, decided_by uuid default null)
|
|
90247
90984
|
returns jsonb
|
|
90248
90985
|
language plpgsql
|
|
90249
90986
|
security definer
|
|
@@ -90256,8 +90993,8 @@ begin
|
|
|
90256
90993
|
if not found then
|
|
90257
90994
|
${fail$1("LEAVE_REQUEST_NOT_FOUND", "leave request not found", "P0002")}
|
|
90258
90995
|
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")}
|
|
90996
|
+
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
|
|
90997
|
+
${forbidden("not allowed to decide this leave request; only the service role decides for another user, never for the requester")}
|
|
90261
90998
|
end if;
|
|
90262
90999
|
if not (${pendingIn("v_row", "")}) then
|
|
90263
91000
|
${fail$1("LEAVE_REQUEST_CLOSED", "this leave request was already decided or cancelled", "55000")}
|
|
@@ -90267,11 +91004,11 @@ begin
|
|
|
90267
91004
|
end if;
|
|
90268
91005
|
if decide_leave_request.approved then
|
|
90269
91006
|
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), '')")}
|
|
91007
|
+
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
91008
|
where x.${q("id")} = v_row.${q("id")}
|
|
90272
91009
|
returning * into v_row;
|
|
90273
91010
|
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), '')")}
|
|
91011
|
+
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
91012
|
where x.${q("id")} = v_row.${q("id")}
|
|
90276
91013
|
returning * into v_row;
|
|
90277
91014
|
${requestRecord("leave.rejected", "v_row", "rejected leave")}` : `
|
|
@@ -90280,7 +91017,7 @@ begin
|
|
|
90280
91017
|
return ${requestJson("v_row", "")};
|
|
90281
91018
|
end;
|
|
90282
91019
|
$$;
|
|
90283
|
-
${userGrant(`${fn("decide_leave_request")}(uuid, boolean, text)`)}
|
|
91020
|
+
${userGrant(`${fn("decide_leave_request")}(uuid, boolean, text, uuid)`)}
|
|
90284
91021
|
`;
|
|
90285
91022
|
const balanceCheck = allowNegative ? "" : `
|
|
90286
91023
|
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
|
|
@@ -96692,92 +97429,6 @@ function itemJson(n) {
|
|
|
96692
97429
|
if (n.extras.length > 0) pairs.push(["fields", columnsObject("ev", n.extras.map((extra) => extra.name))]);
|
|
96693
97430
|
return `jsonb_build_object(${pairs.map(([key, value]) => `'${key}', ${value}`).join(", ")})`;
|
|
96694
97431
|
}
|
|
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
97432
|
// src/sql/modules/notifications-suppressions.ts
|
|
96782
97433
|
/**
|
|
96783
97434
|
* Whether the module writes and honours suppressions. A module over the app's
|
|
@@ -112992,6 +113643,10 @@ const NAMES$35 = {
|
|
|
112992
113643
|
"quote.revised": {
|
|
112993
113644
|
subject: "quotes",
|
|
112994
113645
|
payload: [...QUOTE, "revision"]
|
|
113646
|
+
},
|
|
113647
|
+
"quote.withdrawn": {
|
|
113648
|
+
subject: "quotes",
|
|
113649
|
+
payload: [...QUOTE, "revision"]
|
|
112995
113650
|
}
|
|
112996
113651
|
},
|
|
112997
113652
|
hooks: [
|
|
@@ -113007,7 +113662,9 @@ const NAMES$35 = {
|
|
|
113007
113662
|
"validDays",
|
|
113008
113663
|
"extraColumns",
|
|
113009
113664
|
"lineExtraColumns",
|
|
113010
|
-
"lineRates"
|
|
113665
|
+
"lineRates",
|
|
113666
|
+
"workingCopy",
|
|
113667
|
+
"versionLines"
|
|
113011
113668
|
],
|
|
113012
113669
|
tables: {
|
|
113013
113670
|
quotes: {
|
|
@@ -113050,7 +113707,10 @@ const NAMES$35 = {
|
|
|
113050
113707
|
discountBps: "discount_bps",
|
|
113051
113708
|
discountAmount: "discount_amount",
|
|
113052
113709
|
depositBps: "deposit_bps",
|
|
113710
|
+
depositAmount: "deposit_amount",
|
|
113711
|
+
depositRequired: "deposit_required",
|
|
113053
113712
|
depositDue: "deposit_due",
|
|
113713
|
+
unpublishedChanges: "unpublished_changes",
|
|
113054
113714
|
createdBy: "created_by",
|
|
113055
113715
|
createdAt: "created_at",
|
|
113056
113716
|
updatedAt: "updated_at",
|
|
@@ -113074,7 +113734,10 @@ const NAMES$35 = {
|
|
|
113074
113734
|
"discountBps",
|
|
113075
113735
|
"discountAmount",
|
|
113076
113736
|
"depositBps",
|
|
113737
|
+
"depositAmount",
|
|
113738
|
+
"depositRequired",
|
|
113077
113739
|
"depositDue",
|
|
113740
|
+
"unpublishedChanges",
|
|
113078
113741
|
"createdBy"
|
|
113079
113742
|
],
|
|
113080
113743
|
typed: ["status"]
|
|
@@ -113100,6 +113763,45 @@ const NAMES$35 = {
|
|
|
113100
113763
|
},
|
|
113101
113764
|
optional: ["publishedBy"]
|
|
113102
113765
|
},
|
|
113766
|
+
versionLines: {
|
|
113767
|
+
name: "quote_version_lines",
|
|
113768
|
+
app: {},
|
|
113769
|
+
optionalTable: true,
|
|
113770
|
+
lifecycle: {
|
|
113771
|
+
tenant: "tenant",
|
|
113772
|
+
export: true
|
|
113773
|
+
},
|
|
113774
|
+
columns: {
|
|
113775
|
+
id: "id",
|
|
113776
|
+
tenant: "tenant_id",
|
|
113777
|
+
version: "version_id",
|
|
113778
|
+
position: "position",
|
|
113779
|
+
description: "description",
|
|
113780
|
+
quantity: "quantity",
|
|
113781
|
+
unitAmount: "unit_amount",
|
|
113782
|
+
periods: "periods",
|
|
113783
|
+
discountBps: "discount_bps",
|
|
113784
|
+
taxRateBps: "tax_rate_bps",
|
|
113785
|
+
taxCode: "tax_code",
|
|
113786
|
+
section: "section",
|
|
113787
|
+
optional: "optional",
|
|
113788
|
+
selected: "selected",
|
|
113789
|
+
productType: "product_type",
|
|
113790
|
+
productId: "product_id"
|
|
113791
|
+
},
|
|
113792
|
+
optional: [
|
|
113793
|
+
"periods",
|
|
113794
|
+
"discountBps",
|
|
113795
|
+
"taxRateBps",
|
|
113796
|
+
"taxCode",
|
|
113797
|
+
"section",
|
|
113798
|
+
"optional",
|
|
113799
|
+
"selected",
|
|
113800
|
+
"productType",
|
|
113801
|
+
"productId"
|
|
113802
|
+
],
|
|
113803
|
+
typed: ["productType"]
|
|
113804
|
+
},
|
|
113103
113805
|
taxLines: {
|
|
113104
113806
|
name: "quote_tax_lines",
|
|
113105
113807
|
app: {},
|
|
@@ -113130,6 +113832,11 @@ function tables$5(ctx, n) {
|
|
|
113130
113832
|
const company = quoteParty(ctx, "company");
|
|
113131
113833
|
const origin = quoteOrigin(ctx);
|
|
113132
113834
|
const column = (logical, definition) => ctx.has("quotes", logical) ? `\n ${q(logical)} ${typeof definition === "string" ? definition : definition(q(logical))},` : "";
|
|
113835
|
+
const added = [
|
|
113836
|
+
["depositAmount", (name) => `bigint check (${name} > 0)`],
|
|
113837
|
+
["depositRequired", () => "boolean not null default false"],
|
|
113838
|
+
["unpublishedChanges", () => "boolean not null default false"]
|
|
113839
|
+
].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
113840
|
const constraints = [
|
|
113134
113841
|
`unique (${q("tenant")}, ${q("number")}, ${q("revision")})`,
|
|
113135
113842
|
...company ? [`check ((${q("companyType")} is null) = (${q("companyId")} is null))`] : [],
|
|
@@ -113150,13 +113857,13 @@ create table if not exists ${t("quotes")} (
|
|
|
113150
113857
|
${q("tokenHash")} text unique,
|
|
113151
113858
|
${q("sentAt")} timestamptz,${column("viewedAt", "timestamptz")}
|
|
113152
113859
|
${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")}
|
|
113860
|
+
${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
113861
|
${q("createdAt")} timestamptz not null default now(),
|
|
113155
113862
|
${q("updatedAt")} timestamptz not null default now(),
|
|
113156
113863
|
${totalColumnsSql(ctx, "quotes")},
|
|
113157
113864
|
${constraints.join(",\n ")}
|
|
113158
113865
|
);
|
|
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")});` : ""}
|
|
113866
|
+
${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
113867
|
${addExtraColumns(t("quotes"), n.extras)}${appUniqueIndex(ctx, "quotes", ["tokenHash"])}
|
|
113161
113868
|
${lockModuleTable(ctx, "quotes", { read: true })}
|
|
113162
113869
|
${renderPolicy(policy$1({
|
|
@@ -113186,6 +113893,35 @@ function childTables(ctx, n) {
|
|
|
113186
113893
|
target: t(table)
|
|
113187
113894
|
});
|
|
113188
113895
|
const frozen = ctx.trigger("quote_versions_frozen");
|
|
113896
|
+
const frozenFn = `better_supabase.${frozen.replaceAll("\"", "")}()`;
|
|
113897
|
+
const vl = (column) => c("versionLines", column);
|
|
113898
|
+
const vlColumn = (logical, definition) => ctx.has("versionLines", logical) ? `\n ${vl(logical)} ${definition},` : "";
|
|
113899
|
+
const versionLines = versionLinesOn(ctx) ? `
|
|
113900
|
+
create table if not exists ${t("versionLines")} (
|
|
113901
|
+
${vl("id")} uuid primary key default gen_random_uuid(),
|
|
113902
|
+
${vl("tenant")} ${ctx.idType} not null,
|
|
113903
|
+
${vl("version")} uuid not null references ${t("versions")} (${v("id")}) on delete cascade,
|
|
113904
|
+
${vl("position")} integer not null,
|
|
113905
|
+
${vl("description")} text not null,
|
|
113906
|
+
${vl("quantity")} numeric(18, 4) not null,
|
|
113907
|
+
${vl("unitAmount")} bigint not null,${vlColumn("periods", "integer not null default 1")}${vlColumn("discountBps", "integer not null default 0")}${vlColumn("taxRateBps", "integer not null default 0")}${vlColumn("taxCode", "text")}${vlColumn("section", "text")}${vlColumn("optional", "boolean not null default false")}${vlColumn("selected", "boolean not null default true")}${vlColumn("productType", "text")}${vlColumn("productId", "text")}
|
|
113908
|
+
unique (${vl("version")}, ${vl("position")})
|
|
113909
|
+
);
|
|
113910
|
+
${lockModuleTable(ctx, "versionLines", { read: true })}
|
|
113911
|
+
${renderPolicy(policy$1({
|
|
113912
|
+
table: t("versionLines"),
|
|
113913
|
+
name: ctx.naming.rename(`${ctx.tableName("versionLines").name}_read`),
|
|
113914
|
+
command: "select",
|
|
113915
|
+
roles: ["authenticated"],
|
|
113916
|
+
using: `exists (select 1 from ${t("versions")} v where v.${v("id")} = ${vl("version")})`
|
|
113917
|
+
}), {
|
|
113918
|
+
drop: true,
|
|
113919
|
+
target: t("versionLines")
|
|
113920
|
+
})}
|
|
113921
|
+
drop trigger if exists ${frozen} on ${t("versionLines")};
|
|
113922
|
+
create trigger ${frozen} before update on ${t("versionLines")}
|
|
113923
|
+
for each row execute function ${frozenFn};
|
|
113924
|
+
` : "";
|
|
113189
113925
|
const taxLines = ctx.hasTable("taxLines") ? `
|
|
113190
113926
|
create table if not exists ${t("taxLines")} (
|
|
113191
113927
|
${x("id")} uuid primary key default gen_random_uuid(),
|
|
@@ -113227,7 +113963,7 @@ ${triggerGrant(`better_supabase.${frozen.replaceAll("\"", "")}()`)}
|
|
|
113227
113963
|
drop trigger if exists ${frozen} on ${t("versions")};
|
|
113228
113964
|
create trigger ${frozen} before update on ${t("versions")}
|
|
113229
113965
|
for each row execute function better_supabase.${frozen.replaceAll("\"", "")}();
|
|
113230
|
-
${taxLines}`;
|
|
113966
|
+
${versionLines}${taxLines}`;
|
|
113231
113967
|
}
|
|
113232
113968
|
function build$34(ctx) {
|
|
113233
113969
|
if (ctx.mode === "custom") return "";
|
|
@@ -113282,7 +114018,7 @@ function contract$32(ctx) {
|
|
|
113282
114018
|
},
|
|
113283
114019
|
{
|
|
113284
114020
|
name: "send_quote",
|
|
113285
|
-
args: ["uuid"],
|
|
114021
|
+
args: ["uuid", "jsonb"],
|
|
113286
114022
|
returns: "jsonb"
|
|
113287
114023
|
},
|
|
113288
114024
|
{
|
|
@@ -113292,13 +114028,19 @@ function contract$32(ctx) {
|
|
|
113292
114028
|
"text",
|
|
113293
114029
|
"text",
|
|
113294
114030
|
"text",
|
|
114031
|
+
"jsonb",
|
|
113295
114032
|
"jsonb"
|
|
113296
114033
|
],
|
|
113297
114034
|
returns: "jsonb"
|
|
113298
114035
|
},
|
|
113299
114036
|
{
|
|
113300
114037
|
name: "revise_quote",
|
|
113301
|
-
args: ["uuid"],
|
|
114038
|
+
args: ["uuid", "jsonb"],
|
|
114039
|
+
returns: "jsonb"
|
|
114040
|
+
},
|
|
114041
|
+
{
|
|
114042
|
+
name: "withdraw_quote",
|
|
114043
|
+
args: ["uuid", "jsonb"],
|
|
113302
114044
|
returns: "jsonb"
|
|
113303
114045
|
},
|
|
113304
114046
|
{
|
|
@@ -129531,6 +130273,11 @@ const CHANGED_SETTING = "better_supabase.lifecycle_changed";
|
|
|
129531
130273
|
/** The actor `transition()` passes to the trigger: name, email, ip, userAgent. */
|
|
129532
130274
|
const ACTOR_SETTING = "better_supabase.transition_actor";
|
|
129533
130275
|
const REASON = "nullif(current_setting('better_supabase.transition_reason', true), '')";
|
|
130276
|
+
/**
|
|
130277
|
+
* The acting user: the signed-in user, else the actor's `id`, which the service
|
|
130278
|
+
* role passes for the user it acts for.
|
|
130279
|
+
*/
|
|
130280
|
+
const ACTOR_ID = `coalesce(auth.uid(), nullif(nullif(current_setting('${ACTOR_SETTING}', true), '')::jsonb ->> 'id', '')::uuid)`;
|
|
129534
130281
|
/** One field of the actor `transition()` passed, as SQL. */
|
|
129535
130282
|
function actorField(field) {
|
|
129536
130283
|
const value = `nullif(nullif(current_setting('${ACTOR_SETTING}', true), '')::jsonb ->> ${sqlString(field)}, '')`;
|
|
@@ -129549,7 +130296,7 @@ function historyWrite(ctx, item) {
|
|
|
129549
130296
|
[hist.tenant, `new.${sqlIdent(item.tenantColumn)}`],
|
|
129550
130297
|
[hist.from, asColumnType(table, hist.from, from)],
|
|
129551
130298
|
[hist.to, asColumnType(table, hist.to, to)],
|
|
129552
|
-
[hist.actor,
|
|
130299
|
+
[hist.actor, ACTOR_ID],
|
|
129553
130300
|
[hist.reason, REASON],
|
|
129554
130301
|
...ACTOR_FIELDS.flatMap(([key, field]) => {
|
|
129555
130302
|
const column = hist[key];
|
|
@@ -129566,7 +130313,7 @@ function historyWrite(ctx, item) {
|
|
|
129566
130313
|
[h("subjectId"), `new.${sqlIdent(item.idColumn)}::text`],
|
|
129567
130314
|
[h("fromStatus"), ctx.cast("history", "fromStatus", from)],
|
|
129568
130315
|
[h("toStatus"), ctx.cast("history", "toStatus", to)],
|
|
129569
|
-
[h("actor"),
|
|
130316
|
+
[h("actor"), ACTOR_ID],
|
|
129570
130317
|
[h("reason"), REASON],
|
|
129571
130318
|
...ACTOR_FIELDS.flatMap(([key, field]) => ctx.has("history", key) ? [[h(key), actorField(field)]] : [])
|
|
129572
130319
|
];
|
|
@@ -130037,7 +130784,8 @@ drop function if exists ${ctx.fn("transition")}(text, text, text, text);
|
|
|
130037
130784
|
-- Sets the status as the caller, so the subject table's policies decide
|
|
130038
130785
|
-- whether they may update the record; the trigger checks the edge. actor
|
|
130039
130786
|
-- carries the name, email, ip and userAgent the history row keeps, e.g. for
|
|
130040
|
-
-- a portal visitor who isn't an auth user
|
|
130787
|
+
-- a portal visitor who isn't an auth user, and the id of the user the
|
|
130788
|
+
-- service role acts for.
|
|
130041
130789
|
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
130790
|
returns boolean
|
|
130043
130791
|
language plpgsql
|
|
@@ -130047,18 +130795,8 @@ as $$
|
|
|
130047
130795
|
declare
|
|
130048
130796
|
v_found boolean;
|
|
130049
130797
|
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
130798
|
perform set_config('better_supabase.transition_reason', coalesce(transition.reason, ''), true);
|
|
130061
|
-
|
|
130799
|
+
${transitionActorSql("transition.actor", "STATE_ACTOR_INVALID")}
|
|
130062
130800
|
${ctx.hook("before_status_transition", [
|
|
130063
130801
|
["text", "transition.subject_type"],
|
|
130064
130802
|
["text", "transition.subject_id"],
|