better-supabase 0.42.0 → 0.45.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/{access-sql-Dao1C0fz.js → access-sql-BHat-brX.js} +1 -0
- package/dist/{adapter-ddQ9Hzka.js → adapter-C0C4jIwI.js} +153 -4
- package/dist/{agents-BAiLeoR-.d.ts → agents-DxhGxwDS.d.ts} +4 -4
- package/dist/{ai-cache-B94R1da7.d.ts → ai-cache-OkvpE7L-.d.ts} +4 -4
- package/dist/{ai-chat-rQ7Ftq9W.d.ts → ai-chat-LHWztFya.d.ts} +4 -4
- package/dist/{ai-schedules-DIiPmFgn.d.ts → ai-schedules-BP0PBKhY.d.ts} +5 -5
- 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 +3 -3
- package/dist/ai-sdk/memory/index.d.ts +3 -3
- package/dist/ai-sdk/memory/index.js +1 -1
- package/dist/ai-sdk/workflow/index.d.ts +3 -3
- package/dist/{api-CbY2qdzT.d.ts → api-CgO8Gin7.d.ts} +6 -6
- package/dist/{api-wwix_K5c.js → api-DXCaMM2S.js} +1 -1
- package/dist/{api-keys-U3JQ8IlM.d.ts → api-keys-DINjcAaY.d.ts} +4 -4
- package/dist/{app-tables-DGgCgRwq.d.ts → app-tables-Dg9lERHb.d.ts} +1 -1
- package/dist/{approvals-CYbTzQ7v.d.ts → approvals-CoBe9E2b.d.ts} +6 -6
- package/dist/{assistant-B1p5mYaM.d.ts → assistant-DMaZZFps.d.ts} +2 -2
- package/dist/astro/index.d.ts +7 -7
- package/dist/astro/index.js +4 -5
- package/dist/{authorization-CcvJbvr1.d.ts → authorization-CcWVJSsN.d.ts} +109 -24
- package/dist/{authorization-hooks-CR8TVvqo.d.ts → authorization-hooks-u2Z18CAM.d.ts} +2 -2
- package/dist/authz-refresh-C_zK-BdX.js +115 -0
- package/dist/authz-refresh-DIqPTJZe.d.ts +79 -0
- package/dist/{auth-link-BmJsQG4a.js → authz-refresh-DQ0Q_1_V.js} +87 -1
- package/dist/authz-refresh-Nc-38Xeh.d.ts +38 -0
- package/dist/authz-topic-C7n3kIm_.d.ts +21 -0
- package/dist/{automations-CJhRmPmq.js → automations-Bk-_P7Zp.js} +5 -1
- package/dist/better-result/index.d.ts +3 -3
- package/dist/{bind-B71jMEGG.d.ts → bind-BieIoT6r.d.ts} +7 -7
- package/dist/{block-env-DzYTC9d1.d.ts → block-env-YzSHv579.d.ts} +4 -4
- package/dist/{block-helpers-Sj-efEhC.d.ts → block-helpers-DzIR3Ob8.d.ts} +1 -1
- package/dist/{block-hooks-VW4knarE.d.ts → block-hooks-D9NKzUqW.d.ts} +2 -2
- package/dist/{block-subjects-a_ECM9o0.js → block-subjects-CTIsFATg.js} +1 -1
- package/dist/{block-subjects-Bkieh2Xk.d.ts → block-subjects-hcIVjfyD.d.ts} +1 -1
- package/dist/{block-tables-B92SBFqM.d.ts → block-tables-D-UjSTXa.d.ts} +1 -1
- package/dist/{block-transport-CDmOUuLZ.d.ts → block-transport-Do7J4MsA.d.ts} +2 -2
- package/dist/blocks/access-requests/index.d.ts +5 -5
- package/dist/blocks/activities/index.d.ts +10 -10
- package/dist/blocks/activities/index.js +1 -1
- package/dist/blocks/agents/index.d.ts +4 -4
- package/dist/blocks/ai-cache/index.d.ts +3 -3
- package/dist/blocks/ai-chat/index.d.ts +8 -8
- package/dist/blocks/ai-files/index.d.ts +3 -3
- package/dist/blocks/ai-keys/index.d.ts +4 -4
- package/dist/blocks/ai-schedules/index.d.ts +3 -3
- package/dist/blocks/announcements/index.d.ts +8 -8
- package/dist/blocks/api-keys/index.d.ts +3 -3
- package/dist/blocks/approvals/index.d.ts +4 -4
- package/dist/blocks/assets/index.d.ts +6 -6
- package/dist/blocks/assignment/index.d.ts +7 -7
- package/dist/blocks/attachments/index.d.ts +4 -4
- package/dist/blocks/audit/index.d.ts +13 -13
- package/dist/blocks/audit/index.js +1 -1
- package/dist/blocks/automations/index.d.ts +12 -12
- package/dist/blocks/billable-time/index.d.ts +6 -6
- package/dist/blocks/billing/index.d.ts +9 -9
- package/dist/blocks/bookings/index.d.ts +4 -4
- package/dist/blocks/bulk/index.d.ts +4 -4
- package/dist/blocks/calendar/index.d.ts +5 -5
- package/dist/blocks/catalog/index.d.ts +6 -6
- package/dist/blocks/channels/index.d.ts +7 -7
- package/dist/blocks/collections/index.d.ts +6 -6
- package/dist/blocks/comments/index.d.ts +10 -10
- package/dist/blocks/compliance/index.d.ts +26 -10
- package/dist/blocks/compliance/index.js +38 -4
- package/dist/blocks/connectors/index.d.ts +4 -4
- package/dist/blocks/contacts/index.d.ts +52 -9
- package/dist/blocks/contacts/index.js +48 -5
- package/dist/blocks/content/index.d.ts +5 -5
- package/dist/blocks/contracts/index.d.ts +6 -6
- package/dist/blocks/courses/index.d.ts +22 -7
- package/dist/blocks/courses/index.js +11 -0
- package/dist/blocks/created-by/index.d.ts +2 -2
- package/dist/blocks/custom-fields/index.d.ts +7 -7
- package/dist/blocks/custom-fields/index.js +1 -1
- package/dist/blocks/data-lifecycle/index.d.ts +8 -8
- package/dist/blocks/deals/index.d.ts +6 -6
- package/dist/blocks/dispatch/index.d.ts +6 -6
- package/dist/blocks/documents/index.d.ts +4 -4
- package/dist/blocks/domains/index.d.ts +6 -6
- package/dist/blocks/donations/index.d.ts +6 -6
- package/dist/blocks/drive/index.d.ts +6 -6
- package/dist/blocks/employees/index.d.ts +8 -8
- package/dist/blocks/enrichment/index.d.ts +6 -6
- package/dist/blocks/enrollments/index.d.ts +6 -6
- package/dist/blocks/entitlements/index.d.ts +6 -6
- package/dist/blocks/expenses/index.d.ts +5 -5
- package/dist/blocks/field-history/index.d.ts +4 -4
- package/dist/blocks/flags/index.d.ts +5 -5
- package/dist/blocks/forecasts/index.d.ts +6 -6
- package/dist/blocks/forms/index.d.ts +6 -6
- package/dist/blocks/goals/index.d.ts +5 -5
- package/dist/blocks/goals/index.js +1 -1
- package/dist/blocks/guests/index.d.ts +6 -6
- package/dist/blocks/guests/index.js +2 -2
- package/dist/blocks/hiring/index.d.ts +6 -6
- package/dist/blocks/identities/index.d.ts +5 -5
- package/dist/blocks/imports/index.d.ts +5 -5
- package/dist/blocks/inbox/index.d.ts +10 -10
- package/dist/blocks/incidents/index.d.ts +5 -5
- package/dist/blocks/index.d.ts +9 -9
- package/dist/blocks/inventory/index.d.ts +6 -6
- package/dist/blocks/invoices/index.d.ts +28 -9
- package/dist/blocks/invoices/index.js +15 -5
- package/dist/blocks/knowledge/index.d.ts +3 -3
- package/dist/blocks/lead-scoring/index.d.ts +7 -7
- package/dist/blocks/leases/index.d.ts +6 -6
- package/dist/blocks/leave/index.d.ts +5 -5
- package/dist/blocks/ledger/index.d.ts +6 -6
- package/dist/blocks/mail-sync/index.d.ts +5 -5
- package/dist/blocks/memberships/index.d.ts +2 -2
- package/dist/blocks/memory/index.d.ts +4 -4
- package/dist/blocks/messaging/index.d.ts +11 -11
- package/dist/blocks/metrics/index.d.ts +6 -6
- package/dist/blocks/mfa/index.d.ts +2 -2
- package/dist/blocks/moderation/index.d.ts +6 -6
- package/dist/blocks/notifications/index.d.ts +11 -11
- package/dist/blocks/numbering/index.d.ts +4 -4
- package/dist/blocks/oauth-server/index.d.ts +64 -38
- package/dist/blocks/oauth-server/index.js +6 -3
- package/dist/blocks/onboarding/index.d.ts +5 -5
- package/dist/blocks/orders/index.d.ts +7 -7
- package/dist/blocks/organizations/index.d.ts +8 -8
- package/dist/blocks/outbox/index.d.ts +4 -4
- package/dist/blocks/passes/index.d.ts +8 -8
- package/dist/blocks/permissions/index.d.ts +7 -7
- package/dist/blocks/pipelines/index.d.ts +6 -6
- package/dist/blocks/posts/index.d.ts +5 -5
- package/dist/blocks/profiles/index.d.ts +4 -4
- package/dist/blocks/promotions/index.d.ts +5 -5
- package/dist/blocks/push/index.d.ts +7 -7
- package/dist/blocks/queue/index.d.ts +7 -7
- package/dist/blocks/queue/index.js +4 -4
- package/dist/blocks/quotes/index.d.ts +28 -16
- package/dist/blocks/quotes/index.js +7 -3
- package/dist/blocks/rank/index.d.ts +4 -4
- package/dist/blocks/reactions/index.d.ts +9 -9
- package/dist/blocks/relations/index.d.ts +7 -7
- package/dist/blocks/reminders/index.d.ts +8 -8
- package/dist/blocks/reviews/index.d.ts +5 -5
- package/dist/blocks/saved-views/index.d.ts +6 -6
- package/dist/blocks/scores/index.d.ts +5 -5
- package/dist/blocks/search/index.d.ts +7 -7
- package/dist/blocks/security-events/index.d.ts +7 -7
- package/dist/blocks/segments/index.d.ts +7 -7
- package/dist/blocks/sequences/index.d.ts +6 -6
- package/dist/blocks/service-accounts/index.d.ts +5 -5
- package/dist/blocks/service-accounts/index.js +1 -1
- package/dist/blocks/sessions/index.d.ts +2 -2
- package/dist/blocks/settings/index.d.ts +6 -6
- package/dist/blocks/share-links/index.d.ts +5 -5
- package/dist/blocks/shipments/index.d.ts +6 -6
- package/dist/blocks/signatures/index.d.ts +14 -6
- package/dist/blocks/signatures/index.js +3 -1
- package/dist/blocks/signing-keys/index.d.ts +4 -4
- package/dist/blocks/sla/index.d.ts +7 -7
- package/dist/blocks/sso/index.d.ts +6 -6
- package/dist/blocks/state-machine/index.d.ts +5 -5
- package/dist/blocks/subjects/index.d.ts +6 -6
- package/dist/blocks/tags/index.d.ts +6 -6
- package/dist/blocks/tasks/index.d.ts +9 -9
- package/dist/blocks/teams/index.d.ts +4 -4
- package/dist/blocks/templates/index.d.ts +8 -8
- package/dist/blocks/time-tracking/index.d.ts +7 -7
- package/dist/blocks/timeline/index.d.ts +9 -9
- package/dist/blocks/timeline/index.js +1 -1
- package/dist/blocks/trash/index.d.ts +6 -6
- package/dist/blocks/undo/index.d.ts +4 -4
- package/dist/blocks/updated-at/index.d.ts +2 -2
- package/dist/blocks/usage/index.d.ts +4 -4
- package/dist/blocks/vercel-marketplace/index.d.ts +5 -5
- package/dist/blocks/versions/index.d.ts +6 -6
- package/dist/blocks/waitlist/index.d.ts +5 -5
- package/dist/blocks/webhooks/index.d.ts +13 -13
- package/dist/blocks/workflow-editor/index.d.ts +9 -9
- package/dist/blocks/workflows/index.d.ts +7 -7
- package/dist/{bookings-CHUzFwOI.d.ts → bookings-Du1lvUg1.d.ts} +3 -3
- package/dist/{bucket-CrsJNHzi.d.ts → bucket-CjIhrluq.d.ts} +1 -1
- package/dist/cache-tags-C5Oivuxo.js +27 -0
- package/dist/{sign-in-D5Bg7R47.d.ts → cache-tags-DrywUP3I.d.ts} +16 -2
- package/dist/chat-sdk/index.d.ts +6 -6
- package/dist/claims/index.d.ts +6 -6
- package/dist/claims/index.js +1 -1
- package/dist/cli/{add-NosuEQn1.js → add-B5Gq34wX.js} +12 -12
- package/dist/cli/add-D_JV6V6k.js +1 -0
- package/dist/cli/{add-U0pyhIyx.js → add-DcLNy2oN.js} +2 -2
- package/dist/cli/{app-table-files-DUi898lB.js → app-table-files-CcGWy0qX.js} +14 -6
- package/dist/cli/{app-tables-BINtREbx.js → app-tables-RbPMD2M3.js} +2 -2
- package/dist/cli/{backfill-VfqI5GqN.js → backfill-BJterqcQ.js} +3 -3
- package/dist/cli/bin.js +1 -1
- package/dist/cli/{blocks-Bo2Lw2UO.js → blocks-BBALfFv-.js} +1 -1
- package/dist/cli/{blocks-DsEaPf6J.js → blocks-DsAwI_4v.js} +1 -1
- package/dist/cli/{cache-CNJD8OdR.js → cache-DRb1xVPh.js} +1 -1
- package/dist/cli/{codemod-BWa3Bte6.js → codemod-Cpd4DnrL.js} +1 -1
- package/dist/cli/{config-CrwCec-B.js → config-CGVmcEZa.js} +1 -1
- package/dist/cli/{config-DrrkMihk.js → config-Dy-BAGel.js} +34 -5
- package/dist/cli/{content-mapper-Dl50Ny6a.js → content-mapper-D0riSMnP.js} +2 -2
- package/dist/cli/{db-bK5eCLaE.js → db-BCVXzXDA.js} +2 -2
- package/dist/cli/{doctor-B9GtOGSa.js → doctor-CHmX2gau.js} +273 -230
- package/dist/cli/{gen-CIUD1sgB.js → gen-DB0svRc8.js} +14 -14
- package/dist/cli/index.d.ts +1 -1
- package/dist/cli/index.js +7 -7
- package/dist/cli/{init-wl5jk5vX.js → init-B4fQNe4C.js} +9 -9
- package/dist/cli/{live-B0f_X3rI.js → live-Bft5EE70.js} +2 -2
- package/dist/cli/{mcp-CZWaBkXY.js → mcp-BKcS-LZw.js} +2 -2
- package/dist/cli/{metadata-Bi5eQP4w.js → metadata-CgKNmMsc.js} +3 -3
- package/dist/cli/{migrate-DMITLPEu.js → migrate-ehxT23Gg.js} +1 -1
- package/dist/cli/{migration-safety-2n8e8njJ.js → migration-safety-D2gG-dDs.js} +2 -2
- package/dist/cli/{migrations-C5k9hNOo.js → migrations-CQ1Sgz_X.js} +2 -2
- package/dist/cli/{module-migration-BFchEhAJ.js → module-migration-BOPJUkIX.js} +2 -2
- package/dist/cli/powersync-B8GWjT_L.js +1 -0
- package/dist/cli/{powersync-DViexv6m.js → powersync-BTari5WF.js} +20 -4
- package/dist/cli/{print-ChX1vQhO.js → print-BMJnlJ8k.js} +2 -2
- package/dist/cli/{providers-lwK2lplZ.js → providers-BNZ-OqMI.js} +1 -1
- package/dist/cli/{prune-workflows-DO3nRZFF.js → prune-workflows-BG55npqs.js} +3 -3
- package/dist/cli/{remove-WB9dFyNn.js → remove-BIqGDE0A.js} +5 -5
- package/dist/cli/{render-B0MMWWZE.js → render-BIC4Wctz.js} +4 -4
- package/dist/cli/{run-CmJbNG2-.js → run-BJ4_rmHy.js} +9 -9
- package/dist/cli/{run-CMvwtBX9.js → run-C_slJx8m.js} +32 -32
- package/dist/cli/{seed-DSC6f0oh.js → seed-0r_0aD8_.js} +2 -2
- package/dist/cli/seed-DX1NTTOK.js +1 -0
- package/dist/cli/{shared-BL5kcRdz.js → shared-DhpBDjRa.js} +1 -1
- package/dist/cli/{snapshot-CVB9Ri2a.js → snapshot-CMJksw-t.js} +3 -3
- package/dist/cli/{source-COGgsYiV.js → source-CJilfcq-.js} +1 -1
- package/dist/cli/{source-args-Bz5QQne2.js → source-args-CgCX8KUJ.js} +1 -1
- package/dist/cli/{spec-CH6Qd2LE.js → spec-Br9cWMbU.js} +2 -2
- package/dist/cli/{spec-002zD_9Z.js → spec-CnjHA0br.js} +1 -1
- package/dist/cli/{sql-layout-jZOzCj-S.js → sql-layout-BCiEl_G5.js} +32 -13
- package/dist/cli/{sync-I4x-1aVx.js → sync-Bulv1zyy.js} +4 -4
- package/dist/cli/{table-BIQA9Hdt.js → table-BAR0cLmU.js} +1 -1
- package/dist/cli/{upgrade-BRp5AxAY.js → upgrade-C8fiTE3r.js} +2 -2
- package/dist/cli/{upgrade-C60BZggI.js → upgrade-DTBvTAAV.js} +5 -5
- package/dist/cli/{version-CRCAxS2s.js → version-hhuwVLKj.js} +1 -1
- package/dist/client/index.d.ts +6 -6
- package/dist/client/native/index.d.ts +7 -31
- package/dist/client/native/index.js +2 -2
- package/dist/{cloud-event-BjgxkfJJ.d.ts → cloud-event-LTUGgt6D.d.ts} +1 -1
- package/dist/{compiler-BOW4yPcW.d.ts → compiler-CJorTlU7.d.ts} +2 -2
- package/dist/{composite-DPN4SFud.d.ts → composite-BCUNxZCd.d.ts} +7 -7
- package/dist/{composite-BidYZWZY.js → composite-C3lLpMys.js} +2 -2
- package/dist/config/index.d.ts +5 -5
- package/dist/config/index.js +5 -5
- package/dist/{config-2SwAe0Im.js → config-DA_R9O_y.js} +3 -3
- package/dist/{config-BND2PFGs.js → config-HOXkrND2.js} +1 -1
- package/dist/{connectors-OMJkoAP6.d.ts → connectors-DTxDzUzD.d.ts} +4 -4
- package/dist/{context-DXWyPNzr.d.ts → context-BJK9_ppk.d.ts} +38 -4
- package/dist/contract/index.d.ts +11 -10
- package/dist/{controller-D3MPVovD.d.ts → controller-TplPQG5m.d.ts} +1 -1
- package/dist/{conversion-BShzA-u-.d.ts → conversion-DwDBNeWT.d.ts} +1 -1
- package/dist/create/index.d.ts +3 -3
- package/dist/create/index.js +18 -3
- package/dist/create/lite/index.d.ts +4 -4
- package/dist/create/lite/index.js +3 -3
- package/dist/credentials/index.d.ts +4 -4
- package/dist/{data-engine-CX1oYDZl.d.ts → data-engine-ZcGeVz1i.d.ts} +7 -1
- package/dist/{define-C_He1bQO.d.ts → define-DXQHQ2Qy.d.ts} +5 -5
- package/dist/{define-block-DBD7yhQg.d.ts → define-block-tFQZ8936.d.ts} +12 -12
- package/dist/{documents-CNVPrE_0.d.ts → documents-Ciijx56T.d.ts} +3 -3
- package/dist/edge/index.d.ts +9 -9
- package/dist/edge/index.js +6 -7
- package/dist/elysia/index.d.ts +1 -1
- package/dist/elysia/index.js +1 -1
- package/dist/{embeddings-C2PBJ2Lx.d.ts → embeddings-LhxY3bUD.d.ts} +1 -1
- package/dist/{ended-BwpmNC5k.d.ts → ended-CpyW7_0h.d.ts} +2 -2
- package/dist/{entitlements-CljrSoWD.d.ts → entitlements-SqfT4gk_.d.ts} +2 -2
- package/dist/eve/index.d.ts +9 -9
- package/dist/eve/index.js +1 -1
- package/dist/{eve-CtQd4iaO.d.ts → eve-DmbLji3M.d.ts} +2 -2
- package/dist/events/index.d.ts +3 -3
- package/dist/{events-DddDlibJ.d.ts → events-BrgD2StJ.d.ts} +3 -1
- package/dist/{executor-CxMHiDp_.d.ts → executor-DlAtlYxY.d.ts} +4 -4
- package/dist/{executor-DL7cZ-3T.d.ts → executor-kfUaLlQr.d.ts} +1 -1
- package/dist/{executor-DoSNec_H.d.ts → executor-rs231gO_.d.ts} +1 -1
- package/dist/expo/index.d.ts +51 -8
- package/dist/expo/index.js +89 -4
- package/dist/{field-errors-C4NOUBpu.d.ts → field-errors-DyWpuH1q.d.ts} +10 -10
- package/dist/{field-formats-DVukMbRa.d.ts → field-formats-BJeg-rv8.d.ts} +13 -3
- package/dist/{field-formats-Cap-V7UP.js → field-formats-sLYMh1ZK.js} +52 -4
- package/dist/{fields-CP46SPNE.d.ts → fields-OVgN0HOy.d.ts} +1 -1
- package/dist/{filter-evaluate-Bkbb0nuQ.d.ts → filter-evaluate-BzyMp2LO.d.ts} +1 -1
- package/dist/{filter-query-Xj40B5KT.d.ts → filter-query-BcheQ5zK.d.ts} +1 -1
- package/dist/{flags-BrXfCmGB.d.ts → flags-D71LTDHR.d.ts} +2 -2
- package/dist/flags-sdk/index.d.ts +2 -2
- package/dist/{framework-B6JAPr1i.d.ts → framework-C8HFM1bX.d.ts} +8 -8
- package/dist/{framework-z3KTPRjk.js → framework-DydnLrMk.js} +1 -1
- package/dist/{gateway-DJX-XUWl.d.ts → gateway-DQirTFOg.d.ts} +3 -3
- package/dist/guest-actions-Du1ph4dE.js +11 -0
- package/dist/h3/index.d.ts +1 -1
- package/dist/h3/index.js +1 -1
- package/dist/h3/v1/index.d.ts +1 -1
- package/dist/h3/v1/index.js +1 -1
- package/dist/hono/index.d.ts +9 -9
- package/dist/hono/index.js +5 -6
- package/dist/{inbox-DiQ8KhG8.d.ts → inbox-nk8pqL8V.d.ts} +5 -5
- package/dist/{index-1_-lg9Gc.d.ts → index-0erPlzHd.d.ts} +5 -5
- package/dist/{index-1uV69AZq.d.ts → index-BKDvrKDl.d.ts} +1 -1
- package/dist/{index-D5qW2cRD.d.ts → index-BjN_IQQd.d.ts} +5 -5
- package/dist/{index-DjJUamhw.d.ts → index-Brzh6XAW.d.ts} +5 -4
- package/dist/{index-CvLTqmdq.d.ts → index-CwDdMCdH.d.ts} +1 -1
- package/dist/{index-BrGOE0c2.d.ts → index-DCyNdhEC.d.ts} +5 -5
- package/dist/{index-Bjj-GNhd.d.ts → index-DcmDWojr.d.ts} +1 -1
- package/dist/{index-DhHtsi-q.d.ts → index-Ddjcn6i7.d.ts} +5 -5
- package/dist/{index-CUxdZYSi.d.ts → index-DkmorC1b.d.ts} +5 -5
- package/dist/{index-DmSDAFkF.d.ts → index-vGZZjCW7.d.ts} +14 -14
- package/dist/{index-DWVDKVYA.d.ts → index-x2YRPbXr.d.ts} +6 -6
- package/dist/index.d.ts +7 -7
- package/dist/index.js +1 -1
- package/dist/{instances-DwrdFwKq.js → instances-DGtu3S0m.js} +114 -15
- package/dist/{kit-lHFpu2_1.d.ts → kit-C1GVbhtg.d.ts} +4 -4
- package/dist/{kit-D5rRAKWJ.js → kit-CB3AfM9W.js} +106 -4
- package/dist/{knowledge-DtECa_QW.d.ts → knowledge-CCOSNGJp.d.ts} +5 -5
- package/dist/lint/index.d.ts +1 -1
- package/dist/list/index.d.ts +3 -3
- package/dist/{list-query-BkbLV-Yc.d.ts → list-query-CF-5EUVX.d.ts} +3 -3
- package/dist/mapper/bin.js +7 -6
- package/dist/mcp/index.d.ts +3 -3
- package/dist/mcp/index.js +4 -5
- package/dist/mcp/sdk/index.d.ts +6 -6
- package/dist/mcp/sdk/index.js +2 -2
- package/dist/{messaging-CpQIhkFi.d.ts → messaging-2-SIPAp-.d.ts} +4 -4
- package/dist/nestjs/index.d.ts +2 -2
- package/dist/nestjs/index.js +1 -1
- package/dist/next/client/index.d.ts +1 -1
- package/dist/next/index.d.ts +29 -76
- package/dist/next/index.js +29 -117
- package/dist/node/index.d.ts +2 -2
- package/dist/node/index.js +1 -1
- package/dist/{operations-DFmuxaxW.d.ts → operations-CkgwsViz.d.ts} +1 -1
- package/dist/{options-C5cLEJEa.js → options-ByxOMSXu.js} +2 -1
- package/dist/options-Cdr6Ac4-.d.ts +12 -0
- package/dist/{options-DUNUGuhM.js → options-CpSqyI8k.js} +4 -1
- package/dist/orpc/index.d.ts +8 -8
- package/dist/orpc/index.js +3 -4
- package/dist/otel/index.d.ts +3 -3
- package/dist/otel/index.js +5 -5
- package/dist/{outbox-Cpxpzcue.d.ts → outbox-DL2737I0.d.ts} +4 -4
- package/dist/{permissions-Bsd4mEEZ.d.ts → permissions-vbtGrV26.d.ts} +1 -1
- package/dist/{pool-BJAjQcrJ.d.ts → pool-DfDolmmm.d.ts} +3 -3
- package/dist/{ports-BKdt_9Oe.d.ts → ports-ClyPs0q6.d.ts} +1 -1
- package/dist/postgres/index.d.ts +4 -4
- package/dist/{postgrest-Bjain6nf.d.ts → postgrest-CF0ekbC-.d.ts} +1 -1
- package/dist/powersync/index.d.ts +44 -10
- package/dist/powersync/index.js +52 -5
- package/dist/preset/index.d.ts +3 -3
- package/dist/preset/index.js +3 -3
- package/dist/{preset-CenE7f1G.js → preset-His18bto.js} +3 -3
- package/dist/{project-Ceh2yTSv.js → project-D81NwLP6.js} +13 -7
- package/dist/{provider-CVlXXbda.d.ts → provider-DxJWo8yD.d.ts} +1 -1
- package/dist/{push-token-DRcEl9Ce.d.ts → push-token-DMOeO8cU.d.ts} +1 -1
- package/dist/query/index.d.ts +1 -1
- package/dist/react/index.d.ts +9 -10
- package/dist/react/index.js +3 -3
- package/dist/react/native/index.d.ts +38 -1
- package/dist/react/native/index.js +47 -3
- package/dist/react/server.d.ts +9 -10
- package/dist/react/server.js +2 -2
- package/dist/react/session.d.ts +64 -2
- package/dist/react/session.js +1 -1
- package/dist/{react-DZ7AW2yf.js → react-DkGGh9FE.js} +2 -2
- package/dist/react-router/index.d.ts +6 -6
- package/dist/react-router/index.js +4 -5
- package/dist/realtime/index.d.ts +6 -6
- package/dist/realtime/index.js +1 -1
- package/dist/{record-form-C-1TPtMG.d.ts → record-form-BRtDkhLZ.d.ts} +1 -1
- package/dist/{recordings-BVuri85k.d.ts → recordings-fWDldPuP.d.ts} +1 -1
- package/dist/records/index.d.ts +9 -9
- package/dist/records/index.js +1 -1
- package/dist/{refusal-rnbr6RZD.js → refusal-B9w5Bapa.js} +1 -2
- package/dist/{refusal-CjUUBfhY.d.ts → refusal-DjCQCcCj.d.ts} +3 -3
- package/dist/representatives-DRNDAf0i.js +22 -0
- package/dist/{resolve-XlMQRUeG.d.ts → resolve-CKJMUYRc.d.ts} +8 -1
- package/dist/{resolve-CZV31iCm.js → resolve-nj0eZ44A.js} +38 -1
- package/dist/{resource-CaYpB07K.d.ts → resource-C_rLLwNU.d.ts} +1 -1
- package/dist/{resource-COaS9_i8.js → resource-CrmhNagD.js} +1 -1
- package/dist/{resource-execute-B7-QaS6R.d.ts → resource-execute-DZeWkyIU.d.ts} +2 -2
- package/dist/{resource-types-CF3Uc6OW.d.ts → resource-types-D3gmBOeY.d.ts} +4 -4
- package/dist/{resources-DhiK3yLO.js → resources-B2i_nIgJ.js} +1 -1
- package/dist/{resources-DnHSmJIM.d.ts → resources-CSjwmcFs.d.ts} +2 -2
- package/dist/{respond-D7kUatjc.d.ts → respond-DxS_8bzC.d.ts} +1 -1
- package/dist/{sales-lines-wQHuL-pa.d.ts → sales-lines-DFQ9oIO-.d.ts} +1 -1
- package/dist/{sandboxes-DKgJZYUZ.d.ts → sandboxes-Xh_uNXU4.d.ts} +1 -1
- package/dist/{scores-BXuSVczw.d.ts → scores-DaGD79BY.d.ts} +5 -5
- package/dist/server/index.d.ts +29 -38
- package/dist/server/index.js +9 -9
- package/dist/{server-types-DpI82uNq.d.ts → server-types-DCC-dWKF.d.ts} +91 -17
- package/dist/{session-s-mUZ8RQ.d.ts → session-Ca4clB30.d.ts} +6 -6
- package/dist/{session-BjPYE4dT.js → session-CaoAgv8e.js} +58 -51
- package/dist/{session-status-CJjTuFtA.d.ts → session-status-CYtwZBi5.d.ts} +2 -2
- package/dist/{sign-in-k2lXELeC.js → sign-in-BUiy6unD.js} +1 -1
- package/dist/{sign-in-djgvab1X.js → sign-in-Dhd16x_j.js} +1 -1
- package/dist/{signers-UANxMfH-.d.ts → signers-CtrTcr3i.d.ts} +4 -4
- package/dist/{signing-keys-DhBSWFy_.d.ts → signing-keys-BAyNlJE4.d.ts} +2 -2
- package/dist/solid/index.d.ts +10 -10
- package/dist/solid-start/index.d.ts +6 -6
- package/dist/solid-start/index.js +4 -5
- package/dist/spec/index.d.ts +3 -3
- package/dist/spec/index.js +2 -2
- package/dist/{spec-pins-CuQ2anBw.d.ts → spec-pins-CRJEZYBW.d.ts} +5 -0
- package/dist/{spec-pins-FKUzgF6K.js → spec-pins-Dd1Qj3Sj.js} +1 -0
- package/dist/sql/index.d.ts +5 -5
- package/dist/sql/index.js +3 -3
- package/dist/{sql-BIniB45X.js → sql-D3ihagTr.js} +1390 -429
- package/dist/sqlite/index.d.ts +3 -3
- package/dist/{sso-Frh3sbJ1.d.ts → sso-BVYSNVmk.d.ts} +3 -3
- package/dist/ssr/index.d.ts +4 -4
- package/dist/ssr/index.js +1 -1
- package/dist/storage/index.d.ts +3 -3
- package/dist/storage/index.js +1 -1
- package/dist/streams/index.d.ts +1 -1
- package/dist/{subject-readers-D1Km_Q42.d.ts → subject-readers-nnYmRpv8.d.ts} +2 -2
- package/dist/{subjects-DNFE2rMl.d.ts → subjects-DgP5x73R.d.ts} +3 -3
- package/dist/{support-Dj5V2WTs.d.ts → support-BzXcdRLG.d.ts} +4 -4
- package/dist/{support-view-DKZkZeM5.d.ts → support-view-DNZh8-wA.d.ts} +1 -1
- package/dist/svelte/index.d.ts +9 -9
- package/dist/sveltekit/index.d.ts +7 -7
- package/dist/sveltekit/index.js +4 -5
- package/dist/{tags-BihwKkTT.d.ts → tags-CpFIpRw8.d.ts} +1 -1
- package/dist/tanstack-db/index.d.ts +3 -3
- package/dist/tanstack-start/index.d.ts +6 -6
- package/dist/tanstack-start/index.js +4 -5
- package/dist/{tenant--Hm8mlPy.d.ts → tenant-DyZZDYmm.d.ts} +1 -1
- package/dist/testing/index.d.ts +56 -30
- package/dist/testing/index.js +58 -7
- package/dist/{timeline-BB9fKT_r.d.ts → timeline-Df8GMPkZ.d.ts} +5 -5
- package/dist/{topic-BYF-GTW9.d.ts → topic-B4fSui6P.d.ts} +5 -5
- package/dist/{topic-k17VvXRj.js → topic-BtoL1fKf.js} +1 -1
- package/dist/{types-B8h0reJ4.d.ts → types-BeXhugiI.d.ts} +2 -2
- package/dist/{types-DU_nNO7U.d.ts → types-BgvKQUuy.d.ts} +3 -3
- package/dist/{types-LLCyr-xs.d.ts → types-ByApBdXv.d.ts} +5 -5
- package/dist/{types-BzIYSSWK.d.ts → types-CF5j7kOm.d.ts} +4 -2
- package/dist/{types-kq8S5HVE.d.ts → types-CeV22tnf.d.ts} +1 -1
- package/dist/{types-DCzgSAlU.d.ts → types-D6GlpLD9.d.ts} +4 -4
- package/dist/{types-z31g0-5T.d.ts → types-DJfGy-40.d.ts} +5 -5
- package/dist/{types-D--4dv5K.d.ts → types-mYxPduXR.d.ts} +7 -7
- package/dist/{undo-BCQMqIQN.d.ts → undo-CbLZkEny.d.ts} +2 -2
- package/dist/{usage-CJDj5j15.d.ts → usage-BcD0X7qJ.d.ts} +4 -4
- package/dist/{vault-CbhvnoVC.d.ts → vault-nYFV6WUD.d.ts} +2 -2
- package/dist/vercel-connect/index.d.ts +1 -1
- package/dist/vercel-sandbox/index.d.ts +2 -2
- package/dist/{verify-Cpc1upDA.d.ts → verify-DxTccsBh.d.ts} +2 -2
- package/dist/{view-eHgOOyRS.d.ts → view-DwXy8N6Y.d.ts} +27 -3
- package/dist/vue/index.d.ts +10 -10
- package/dist/{watch-topic-tfTxgEGc.d.ts → watch-topic-DShzD8ul.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.d.ts +1 -1
- package/dist/{workflow-sdk-DzKQo265.d.ts → workflow-sdk-ClwzLwNe.d.ts} +3 -3
- package/dist/{workflows-D7HvWeNu.d.ts → workflows-ZGDa9twb.d.ts} +3 -3
- package/dist/yjs/index.d.ts +2 -2
- package/dist/yjs/index.js +1 -1
- package/package.json +1 -1
- package/schemas/config-v1.json +41 -1
- package/schemas/design-v1.json +7 -1
- package/schemas/doctor-report-v1.json +1 -0
- package/skills/better-supabase/SKILL.md +1 -0
- package/skills/better-supabase/references/ui-recipes.md +13 -15
- package/skills/better-supabase-auth/SKILL.md +26 -2
- package/skills/better-supabase-auth/references/native.md +115 -0
- package/dist/cli/add-BbhRYaFe.js +0 -1
- package/dist/cli/powersync-i7KJcTtM.js +0 -1
- package/dist/cli/seed-CLlvrV8I.js +0 -1
- package/dist/guest-actions-CEwttioE.js +0 -8
- package/dist/impersonation-BOCJcsmS.d.ts +0 -26
- package/dist/options-B7Pl708M.js +0 -8
- package/dist/options-B9w_Y08G.d.ts +0 -6
- package/dist/respond-8A3EOo61.js +0 -106
- package/dist/session-JV1z0kxa.d.ts +0 -77
|
@@ -3,14 +3,14 @@ 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-CTIsFATg.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
|
|
10
|
-
import {
|
|
9
|
+
import { C as columnsWithAccess, E as hiddenColumns, L as resolveBlock, P as BLOCK_SCOPES, R as tenantNameOf, S as hasComputed, T as hasColumnAccess, 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 encryptedColumns, y as lookupColumn } from "./instances-DGtu3S0m.js";
|
|
10
|
+
import { i as FIELD_FORMATS, n as CUSTOM_FIELD_FORM_TYPES, o as FIELD_FORMAT_VALIDATORS, r as CUSTOM_FIELD_TYPES, s as RATING_BOUNDS, t as CUSTOM_FIELD_CHECKED_FORMATS } from "./field-formats-sLYMh1ZK.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
|
-
import { i as fillTemplate, l as templatePlaceholders } from "./access-sql-
|
|
13
|
+
import { i as fillTemplate, l as templatePlaceholders } from "./access-sql-BHat-brX.js";
|
|
14
14
|
import { t as MAX_BATCH } from "./batch-limit-DqQ3d6op.js";
|
|
15
15
|
import { $ as pageSize, A as addNotNullCheck, B as extraFieldsArg, C as SCHEMA$5, D as addCheck, E as activeMembership, F as defaultPartitionName, G as jwtClaim, H as fail$1, I as disabledHelpers, J as membershipDisabledAt, K as lockTable, L as disabledHelpersNeedLaterTables, M as columnRef, N as columnsObject, O as addExtraColumns, P as defaultPartition, Q as ownRowPolicies, R as dropExpiredPartitions, S as PARTITION_VARIABLES, T as accessDefinesDisabledHelpers, U as insertExtraColumns, V as extraFieldsJson, W as jsonSchemaChecks, X as notNullCheckName, Y as membershipSuspended, Z as organizationMissing, _ as rolesOf, _t as updatedAt, at as replaceColumnCheck, b as MONTHLY_PARTITIONS, bt as writeExtraColumns, c as accessModel, ct as serviceGrant, d as moduleOperations, dt as shortHash, et as quotedTable$1, f as modulePermission, ft as splitTable$1, g as roleScopeIs, gt as updateExtraColumns, h as roleNames, ht as triggerGrant, it as renameSql, j as batchFunction, k as addForeignKey, l as hasPlatformRoles, lt as serviceOnly$1, m as providerPlatformRoles, mt as transitionReasonSql, n as WORKFLOW_SDK_WORLD, nt as recordTrigger, o as MODULE_PERMISSION_SCOPES, ot as revokeTable, p as modulePermissionKey, pt as transitionActorSql, q as memberAddedRecord, rt as registerPartitions, s as OPERATIONS, st as schemaPreamble, tt as raise$1, u as isOperationModule$1, ut as sha256Hex$1, v as tenantScope, vt as userGrant, w as SERVICE_CALLER$1, x as NOTHING, y as EQUIVALENT_TRIGGERS, yt as withExtraFields, z as ensureCheck } from "./workflow-sdk-Bps7tpOv.js";
|
|
16
16
|
import { n as blockOptions, r as option, t as NO_OPTIONS } from "./options-Z-bd_H1E.js";
|
|
@@ -38,7 +38,7 @@ import { t as collectionsSqlOptions } from "./options-DFSHZFLN.js";
|
|
|
38
38
|
import { t as commentsSqlOptions } from "./options-C1kZ3qLd.js";
|
|
39
39
|
import { t as complianceSqlOptions } from "./options-BDF60ouf.js";
|
|
40
40
|
import { t as connectorsSqlOptions } from "./options-DvgKdZ2K.js";
|
|
41
|
-
import {
|
|
41
|
+
import { n as REPRESENTATIVE_ROLES, r as contactsSqlOptions, t as REPRESENTATIVE_AUTHORITIES } from "./representatives-DRNDAf0i.js";
|
|
42
42
|
import { t as contentSqlOptions } from "./options-mypVYaqR.js";
|
|
43
43
|
import { t as contractsSqlOptions } from "./options-Bn3NjXfn.js";
|
|
44
44
|
import { t as coursesSqlOptions } from "./options--rohtkkC.js";
|
|
@@ -57,12 +57,13 @@ import { t as expensesSqlOptions } from "./options-BXiUftgG.js";
|
|
|
57
57
|
import { t as flagsSqlOptions } from "./options-BMO-FnOT.js";
|
|
58
58
|
import { t as formsSqlOptions } from "./options-DpwRG4tO.js";
|
|
59
59
|
import { t as goalsSqlOptions } from "./options-BNRvoEkj.js";
|
|
60
|
+
import { n as guestsSqlOptions, t as GUEST_ACTIONS } from "./guest-actions-Du1ph4dE.js";
|
|
60
61
|
import { r as hiringSqlOptions, t as APPLICATION_TO_EMPLOYEE } from "./automations-BfH8GJqv.js";
|
|
61
62
|
import { t as identitiesSqlOptions } from "./options-D5a9CHgP.js";
|
|
62
63
|
import { r as inboxSqlOptions, t as CONVERSATION_TO_TASK } from "./automations-CCc5RUw-.js";
|
|
63
64
|
import { t as incidentsSqlOptions } from "./options-BmFSI07A.js";
|
|
64
65
|
import { t as inventorySqlOptions } from "./options-D4LuPM8a.js";
|
|
65
|
-
import { t as invoicesSqlOptions } from "./options-
|
|
66
|
+
import { t as invoicesSqlOptions } from "./options-ByxOMSXu.js";
|
|
66
67
|
import { t as knowledgeSqlOptions } from "./options-CyYZvdSy.js";
|
|
67
68
|
import { t as leadScoringSqlOptions } from "./options-COfEYic3.js";
|
|
68
69
|
import { t as leasesSqlOptions } from "./options-CzIPn0fF.js";
|
|
@@ -88,7 +89,7 @@ import { t as profilesSqlOptions } from "./options-BxdqA2Ex.js";
|
|
|
88
89
|
import { t as promotionsSqlOptions } from "./options-BvttpM1M.js";
|
|
89
90
|
import { t as pushSqlOptions } from "./options-jg0FMHA5.js";
|
|
90
91
|
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-
|
|
92
|
+
import { n as QUOTE_TO_ORDER, r as quotesSqlOptions } from "./automations-Bk-_P7Zp.js";
|
|
92
93
|
import { t as reactionsSqlOptions } from "./options-BcBdiPSZ.js";
|
|
93
94
|
import { t as relationsSqlOptions } from "./options-Lg76d-cV.js";
|
|
94
95
|
import { t as remindersSqlOptions } from "./options-PTLBl6QT.js";
|
|
@@ -104,7 +105,7 @@ import { t as sessionsSqlOptions } from "./options-D-jiqb0l.js";
|
|
|
104
105
|
import { t as settingsSqlOptions } from "./options-DWgpi5ns.js";
|
|
105
106
|
import { t as shareLinksSqlOptions } from "./options-CsLUAt04.js";
|
|
106
107
|
import { t as shipmentsSqlOptions } from "./options-Bkx8vwip.js";
|
|
107
|
-
import { t as signaturesSqlOptions } from "./options-
|
|
108
|
+
import { t as signaturesSqlOptions } from "./options-CpSqyI8k.js";
|
|
108
109
|
import { t as signingKeysSqlOptions } from "./options-DToWdVqW.js";
|
|
109
110
|
import { t as slaSqlOptions } from "./options-BmwDdKwE.js";
|
|
110
111
|
import { t as ssoSqlOptions } from "./options-CzWjw2HY.js";
|
|
@@ -122,7 +123,6 @@ import { t as versionsSqlOptions } from "./options-C5MfwOAO.js";
|
|
|
122
123
|
import { t as waitlistSqlOptions } from "./options-DFgHHwzD.js";
|
|
123
124
|
import { n as webhooksOutSqlOptions, t as webhooksInSqlOptions } from "./options-BfY4pyQE.js";
|
|
124
125
|
import { t as workflowEditorSqlOptions } from "./options-SlC_jZ7y.js";
|
|
125
|
-
import { t as GUEST_ACTIONS } from "./guest-actions-CEwttioE.js";
|
|
126
126
|
import { n as SUBJECT_TYPE_SQL_PATTERN, r as subjectTypeIdent, t as SUBJECT_TYPE_PATTERN } from "./subject-type-BarjdHZV.js";
|
|
127
127
|
import { t as AI_MESSAGE_PART_TYPES } from "./ai-message-cnroprVB.js";
|
|
128
128
|
import { t as FINAL_RUN_STATES$1 } from "./run-state-DGiyDQxH.js";
|
|
@@ -1044,7 +1044,7 @@ const DROP_POLICY$1 = /* @__PURE__ */ new RegExp(String.raw`\bdrop\s+policy\s+(?
|
|
|
1044
1044
|
const TABLE_NAME$4 = String.raw`${NAME$9}(?:\s*\.\s*${NAME$9})?`;
|
|
1045
1045
|
const DROP_TABLE = /* @__PURE__ */ new RegExp(String.raw`\bdrop\s+table\s+(?:if\s+exists\s+)?(${TABLE_NAME$4}(?:\s*,\s*${TABLE_NAME$4})*)`, "gi");
|
|
1046
1046
|
function droppedTables(list) {
|
|
1047
|
-
return (list.match(new RegExp(TABLE_NAME$4, "g")) ?? []).map(qualified$
|
|
1047
|
+
return (list.match(new RegExp(TABLE_NAME$4, "g")) ?? []).map(qualified$9);
|
|
1048
1048
|
}
|
|
1049
1049
|
function inOrder(statements) {
|
|
1050
1050
|
for (const statement of statements.flat().toSorted((a, b) => a.index - b.index)) statement.apply();
|
|
@@ -1056,7 +1056,7 @@ const COMMANDS$2 = [
|
|
|
1056
1056
|
"delete"
|
|
1057
1057
|
];
|
|
1058
1058
|
const unquote$5 = (name) => name.startsWith("\"") ? name.slice(1, -1).replaceAll("\"\"", "\"") : name.toLowerCase();
|
|
1059
|
-
function qualified$
|
|
1059
|
+
function qualified$9(target) {
|
|
1060
1060
|
const parts = (target.match(new RegExp(NAME$9, "g")) ?? []).map(unquote$5);
|
|
1061
1061
|
return parts.length === 1 ? `public.${parts[0]}` : parts.join(".");
|
|
1062
1062
|
}
|
|
@@ -1076,7 +1076,7 @@ function declaredTables(files, schemas) {
|
|
|
1076
1076
|
inOrder([[...text.matchAll(TABLE$2)].map((match) => ({
|
|
1077
1077
|
index: match.index,
|
|
1078
1078
|
apply: () => {
|
|
1079
|
-
const table = qualified$
|
|
1079
|
+
const table = qualified$9(match[1]);
|
|
1080
1080
|
if (schemas.includes(table.slice(0, table.indexOf(".")))) found.add(table);
|
|
1081
1081
|
}
|
|
1082
1082
|
})), [...text.matchAll(DROP_TABLE)].map((match) => ({
|
|
@@ -1150,11 +1150,11 @@ function declaredViews(files, schemas) {
|
|
|
1150
1150
|
const insteadOf = /* @__PURE__ */ new Set();
|
|
1151
1151
|
for (const file of files) {
|
|
1152
1152
|
const text = withoutComments(file.text);
|
|
1153
|
-
for (const match of text.matchAll(INSTEAD_OF_TRIGGER)) insteadOf.add(qualified$
|
|
1153
|
+
for (const match of text.matchAll(INSTEAD_OF_TRIGGER)) insteadOf.add(qualified$9(match[1]));
|
|
1154
1154
|
inOrder([[...text.matchAll(VIEW)].map((match) => ({
|
|
1155
1155
|
index: match.index,
|
|
1156
1156
|
apply: () => {
|
|
1157
|
-
const view = qualified$
|
|
1157
|
+
const view = qualified$9(match[2]);
|
|
1158
1158
|
if (!schemas.includes(view.slice(0, view.indexOf(".")))) return;
|
|
1159
1159
|
let at = match.index + match[0].length;
|
|
1160
1160
|
let listed;
|
|
@@ -1203,7 +1203,7 @@ function rlsTables(files, schemas) {
|
|
|
1203
1203
|
inOrder([[...text.matchAll(RLS_TOGGLE)].map((match) => ({
|
|
1204
1204
|
index: match.index,
|
|
1205
1205
|
apply: () => {
|
|
1206
|
-
const table = qualified$
|
|
1206
|
+
const table = qualified$9(match[1]);
|
|
1207
1207
|
if (!schemas.includes(table.slice(0, table.indexOf(".")))) return;
|
|
1208
1208
|
if (match[2].toLowerCase() === "enable") found.add(table);
|
|
1209
1209
|
else found.delete(table);
|
|
@@ -1238,7 +1238,7 @@ function declaredColumnTypes(files, schemas) {
|
|
|
1238
1238
|
for (const file of files) {
|
|
1239
1239
|
const text = withoutComments(file.text);
|
|
1240
1240
|
for (const match of text.matchAll(TABLE$2)) {
|
|
1241
|
-
const table = qualified$
|
|
1241
|
+
const table = qualified$9(match[1]);
|
|
1242
1242
|
if (!schemas.includes(table.slice(0, table.indexOf(".")))) continue;
|
|
1243
1243
|
const open = match.index + match[0].length - 1;
|
|
1244
1244
|
const close = closingParen(text, open);
|
|
@@ -1263,7 +1263,7 @@ function typeName(text) {
|
|
|
1263
1263
|
const ENUM = /* @__PURE__ */ new RegExp(String.raw`\bcreate\s+type\s+(${NAME$9}(?:\s*\.\s*${NAME$9})?)\s+as\s+enum\b`, "gi");
|
|
1264
1264
|
/** The enum types `files` create (`create type ... as enum`), as `schema.type`. */
|
|
1265
1265
|
function declaredEnums(files) {
|
|
1266
|
-
return new Set(files.flatMap((file) => [...withoutComments(file.text).matchAll(ENUM)].map((match) => qualified$
|
|
1266
|
+
return new Set(files.flatMap((file) => [...withoutComments(file.text).matchAll(ENUM)].map((match) => qualified$9(match[1]))));
|
|
1267
1267
|
}
|
|
1268
1268
|
function closingParen(text, open) {
|
|
1269
1269
|
let depth = 0;
|
|
@@ -1316,7 +1316,7 @@ function policyGrants(files, schemas) {
|
|
|
1316
1316
|
[...text.matchAll(POLICY$1)].map((match) => ({
|
|
1317
1317
|
index: match.index,
|
|
1318
1318
|
apply: () => {
|
|
1319
|
-
const table = qualified$
|
|
1319
|
+
const table = qualified$9(match[2]);
|
|
1320
1320
|
if (!schemas.includes(table.slice(0, table.indexOf(".")))) return;
|
|
1321
1321
|
const clauses = match[3];
|
|
1322
1322
|
if (/\bas\s+restrictive\b/i.test(clauses)) return;
|
|
@@ -1334,7 +1334,7 @@ function policyGrants(files, schemas) {
|
|
|
1334
1334
|
[...text.matchAll(DROP_POLICY$1)].map((match) => ({
|
|
1335
1335
|
index: match.index,
|
|
1336
1336
|
apply: () => {
|
|
1337
|
-
policies.get(qualified$
|
|
1337
|
+
policies.get(qualified$9(match[2]))?.delete(unquote$5(match[1]));
|
|
1338
1338
|
}
|
|
1339
1339
|
})),
|
|
1340
1340
|
[...text.matchAll(DROP_TABLE)].map((match) => ({
|
|
@@ -1387,12 +1387,12 @@ const SETS_UPDATED_AT$1 = /\bnew\s*\.\s*"?updated_at"?\s*:?=/i;
|
|
|
1387
1387
|
function declaredUpdatedAtTriggers(files, schemas) {
|
|
1388
1388
|
const texts = files.map((file) => withoutComments(file.text));
|
|
1389
1389
|
const setters = /* @__PURE__ */ new Set();
|
|
1390
|
-
for (const text of texts) for (const match of text.matchAll(FUNCTION_DEF)) if (SETS_UPDATED_AT$1.test(match[3])) setters.add(qualified$
|
|
1390
|
+
for (const text of texts) for (const match of text.matchAll(FUNCTION_DEF)) if (SETS_UPDATED_AT$1.test(match[3])) setters.add(qualified$9(match[1]));
|
|
1391
1391
|
const found = {};
|
|
1392
1392
|
for (const text of texts) for (const match of text.matchAll(TRIGGER_DEF)) {
|
|
1393
1393
|
const name = unquote$5(match[1]);
|
|
1394
|
-
const table = qualified$
|
|
1395
|
-
const fn = qualified$
|
|
1394
|
+
const table = qualified$9(match[2]);
|
|
1395
|
+
const fn = qualified$9(match[3]);
|
|
1396
1396
|
if (!name.startsWith("bsb_") && schemas.includes(table.slice(0, table.indexOf("."))) && (UPDATED_AT_FUNCTION.test(fn.slice(fn.indexOf(".") + 1)) || setters.has(fn))) found[table] ??= name;
|
|
1397
1397
|
}
|
|
1398
1398
|
return found;
|
|
@@ -1425,7 +1425,7 @@ function indexStatements(text) {
|
|
|
1425
1425
|
const rest = text.slice(close + 1, end === -1 ? text.length : end);
|
|
1426
1426
|
return [{
|
|
1427
1427
|
name: match[2] === void 0 ? void 0 : unquote$5(match[2]),
|
|
1428
|
-
table: qualified$
|
|
1428
|
+
table: qualified$9(match[3]),
|
|
1429
1429
|
unique: match[1] !== void 0,
|
|
1430
1430
|
method: (match[4] ?? "btree").toLowerCase(),
|
|
1431
1431
|
partial: /\bwhere\b/i.test(rest),
|
|
@@ -1453,7 +1453,7 @@ function declaredIndexes(files, schemas) {
|
|
|
1453
1453
|
const text = withoutComments(file.text);
|
|
1454
1454
|
for (const index of indexStatements(text)) if (!index.partial && index.method === "btree") add(index.table, index.columns, index.name);
|
|
1455
1455
|
for (const match of text.matchAll(TABLE$2)) {
|
|
1456
|
-
const table = qualified$
|
|
1456
|
+
const table = qualified$9(match[1]);
|
|
1457
1457
|
const open = match.index + match[0].length - 1;
|
|
1458
1458
|
const close = closingParen(text, open);
|
|
1459
1459
|
if (close === -1) continue;
|
|
@@ -1570,7 +1570,7 @@ const ENSURE_CHECK = /^do \$\$\nbegin\n {2}if coalesce\(obj_description\(\(\n\s+
|
|
|
1570
1570
|
*/
|
|
1571
1571
|
function withoutAppTableEdits(sql, appTables) {
|
|
1572
1572
|
if (appTables.size === 0) return sql;
|
|
1573
|
-
const drop = (statement, table) => appTables.has(qualified$
|
|
1573
|
+
const drop = (statement, table) => appTables.has(qualified$9(table)) ? "" : statement;
|
|
1574
1574
|
return sql.replaceAll(ALTER_CONSTRAINT, drop).replaceAll(REVOKE, drop).replaceAll(ENSURE_CHECK, drop);
|
|
1575
1575
|
}
|
|
1576
1576
|
/**
|
|
@@ -1601,7 +1601,7 @@ function overAppViews(sql, views) {
|
|
|
1601
1601
|
const statement = sql.slice(from, to);
|
|
1602
1602
|
const masked = maskComments(statement);
|
|
1603
1603
|
const target = DDL_TARGETS.map((pattern) => pattern.exec(masked)?.[1]).find((match) => match !== void 0);
|
|
1604
|
-
const view = target === void 0 ? void 0 : qualified$
|
|
1604
|
+
const view = target === void 0 ? void 0 : qualified$9(target);
|
|
1605
1605
|
if (view === void 0 || !views.has(view)) return statement;
|
|
1606
1606
|
const lead = /^\s*/.exec(statement)[0];
|
|
1607
1607
|
if (said.has(view)) return "";
|
|
@@ -1634,7 +1634,7 @@ function overAppTables(sql, appTables, appColumns = {}) {
|
|
|
1634
1634
|
let out = "";
|
|
1635
1635
|
let at = 0;
|
|
1636
1636
|
for (const match of masked.matchAll(TABLE$2)) {
|
|
1637
|
-
const table = qualified$
|
|
1637
|
+
const table = qualified$9(match[1]);
|
|
1638
1638
|
if (!appTables.has(table) || match.index < at) continue;
|
|
1639
1639
|
const open = match.index + match[0].length - 1;
|
|
1640
1640
|
const close = closingParen(masked, open);
|
|
@@ -1780,7 +1780,7 @@ function policiesOn(statements, appTables) {
|
|
|
1780
1780
|
for (const { masked } of statements) {
|
|
1781
1781
|
const match = CREATE_POLICY.exec(masked);
|
|
1782
1782
|
if (match === null || isBlockName(match[2])) continue;
|
|
1783
|
-
const table = qualified$
|
|
1783
|
+
const table = qualified$9(match[4]);
|
|
1784
1784
|
if (!appTables.has(table)) continue;
|
|
1785
1785
|
const command = COMMAND.exec(masked)?.[1]?.toLowerCase() ?? "all";
|
|
1786
1786
|
const list = found.get(table) ?? [];
|
|
@@ -1810,27 +1810,27 @@ function blockNamesOnAppTables(sql, appTables, updatedAtTriggers = {}) {
|
|
|
1810
1810
|
return statements.map(({ text, masked: statement }) => {
|
|
1811
1811
|
const create = CREATE_POLICY.exec(statement);
|
|
1812
1812
|
if (create !== null) {
|
|
1813
|
-
const name = policies.get(qualified$
|
|
1813
|
+
const name = policies.get(qualified$9(create[4]))?.get(unquote$5(create[2]));
|
|
1814
1814
|
return name === void 0 || isBlockName(create[2]) ? text : renamed(text, create, 2, name);
|
|
1815
1815
|
}
|
|
1816
1816
|
const policy = POLICY_REFERENCE.exec(statement);
|
|
1817
1817
|
if (policy !== null && !isBlockName(policy[2])) {
|
|
1818
|
-
const table = qualified$
|
|
1818
|
+
const table = qualified$9(policy[4]);
|
|
1819
1819
|
if (!appTables.has(table)) return text;
|
|
1820
1820
|
const name = policies.get(table)?.get(unquote$5(policy[2]));
|
|
1821
1821
|
return name === void 0 ? leading(text, policy) : renamed(text, policy, 2, name);
|
|
1822
1822
|
}
|
|
1823
1823
|
const trigger = CREATE_TRIGGER.exec(statement);
|
|
1824
|
-
if (trigger !== null && appTables.has(qualified$
|
|
1825
|
-
const kept = updatedAtTriggers[qualified$
|
|
1824
|
+
if (trigger !== null && appTables.has(qualified$9(trigger[4]))) {
|
|
1825
|
+
const kept = updatedAtTriggers[qualified$9(trigger[4])];
|
|
1826
1826
|
if (kept !== void 0 && SETS_UPDATED_AT.test(statement)) return `${leading(text, trigger)}
|
|
1827
|
-
-- ${qualified$
|
|
1827
|
+
-- ${qualified$9(trigger[4])} keeps updated_at current with its own trigger ${kept}.`;
|
|
1828
1828
|
return isBlockName(trigger[2]) ? text : renamed(text, trigger, 2, blockTriggerName(unquote$5(trigger[2])));
|
|
1829
1829
|
}
|
|
1830
1830
|
const reference = TRIGGER_REFERENCE.exec(statement);
|
|
1831
|
-
if (reference !== null && appTables.has(qualified$
|
|
1831
|
+
if (reference !== null && appTables.has(qualified$9(reference[4])) && !isBlockName(reference[2])) return renamed(text, reference, 2, blockTriggerName(unquote$5(reference[2])));
|
|
1832
1832
|
const toggle = TABLE_TRIGGER.exec(statement);
|
|
1833
|
-
if (toggle !== null && appTables.has(qualified$
|
|
1833
|
+
if (toggle !== null && appTables.has(qualified$9(toggle[2])) && !isBlockName(toggle[4])) return renamed(text, toggle, 4, blockTriggerName(unquote$5(toggle[4])));
|
|
1834
1834
|
return text;
|
|
1835
1835
|
}).join("");
|
|
1836
1836
|
}
|
|
@@ -2194,7 +2194,7 @@ const BLOCK_OPTION_SCHEMAS = {
|
|
|
2194
2194
|
forecasts: NO_OPTIONS,
|
|
2195
2195
|
forms: formsSqlOptions,
|
|
2196
2196
|
goals: goalsSqlOptions,
|
|
2197
|
-
guests:
|
|
2197
|
+
guests: guestsSqlOptions,
|
|
2198
2198
|
hiring: hiringSqlOptions,
|
|
2199
2199
|
idempotency: NO_OPTIONS,
|
|
2200
2200
|
impersonation: impersonationSqlOptions,
|
|
@@ -8557,7 +8557,7 @@ function managerOf(ctx, requester, tenant, employee) {
|
|
|
8557
8557
|
return `(select mgr.${e("user")} from ${table} me
|
|
8558
8558
|
join ${table} mgr on mgr.${e("id")} = me.${e("manager")}
|
|
8559
8559
|
where me.${e("tenant")} = ${tenant} and ${who}
|
|
8560
|
-
and mgr.${e("user")} is not null and mgr.${e("status")}
|
|
8560
|
+
and mgr.${e("user")} is not null and ${employees.is("employees", "status", `mgr.${e("status")}`, ["offboarded"], true)}
|
|
8561
8561
|
limit 1)`;
|
|
8562
8562
|
}
|
|
8563
8563
|
/** Whether `user` is the requester's manager and still a member. */
|
|
@@ -8684,6 +8684,13 @@ $$;
|
|
|
8684
8684
|
revoke execute on function ${signature} from public, anon, authenticated;${payload ? approvalConditionSql(ctx) : ""}`;
|
|
8685
8685
|
}
|
|
8686
8686
|
/**
|
|
8687
|
+
* `steps` with `required: "all"` on a step that only lists users replaced by
|
|
8688
|
+
* their count, as the config parser does.
|
|
8689
|
+
*/
|
|
8690
|
+
const allUsersCounted = (steps) => `(select coalesce(jsonb_agg(case when s -> 'required' = '"all"'::jsonb and (s -> 'approvers') ? 'users'
|
|
8691
|
+
then jsonb_set(s, '{required}', to_jsonb(jsonb_array_length(s -> 'approvers' -> 'users'))) else s end order by o), '[]'::jsonb)
|
|
8692
|
+
from jsonb_array_elements(${steps}) with ordinality e(s, o))`;
|
|
8693
|
+
/**
|
|
8687
8694
|
* PL/pgSQL that raises `invalid` unless every step of `steps` (a jsonb array
|
|
8688
8695
|
* expression) names approvers and a valid required count and escalation. It
|
|
8689
8696
|
* reads and writes `v_step` and `v_who`.
|
|
@@ -8704,7 +8711,10 @@ const stepsCheck$1 = (steps, invalid, manager) => ` for v_step in select * from
|
|
|
8704
8711
|
end loop;
|
|
8705
8712
|
if (v_step ? 'required' and v_step -> 'required' <> '"all"'::jsonb and (jsonb_typeof(v_step -> 'required') <> 'number' or (v_step ->> 'required')::numeric < 1
|
|
8706
8713
|
or (v_step ->> 'required')::numeric <> trunc((v_step ->> 'required')::numeric)))
|
|
8707
|
-
or (v_step -> 'required' = '"all"'::jsonb and (v_step -> 'approvers') - 'permission' <> '{}'::jsonb
|
|
8714
|
+
or (v_step -> 'required' = '"all"'::jsonb and (v_step -> 'approvers') - 'permission' <> '{}'::jsonb
|
|
8715
|
+
and ((v_step -> 'approvers') - 'users' <> '{}'::jsonb or jsonb_array_length(v_step -> 'approvers' -> 'users') = 0))
|
|
8716
|
+
or (jsonb_typeof(v_step -> 'required') = 'number' and (v_step -> 'approvers') - 'users' = '{}'::jsonb
|
|
8717
|
+
and (v_step ->> 'required')::numeric > jsonb_array_length(v_step -> 'approvers' -> 'users'))
|
|
8708
8718
|
or ((v_step ? 'escalateAfter') <> (v_step ? 'escalateTo'))
|
|
8709
8719
|
or (v_step ? 'escalateAfter' and (jsonb_typeof(v_step -> 'escalateAfter') <> 'string' or (v_step ->> 'escalateAfter')::interval <= interval '0')) then
|
|
8710
8720
|
${invalid}
|
|
@@ -8835,6 +8845,7 @@ begin
|
|
|
8835
8845
|
${stepsInvalid}
|
|
8836
8846
|
end if;
|
|
8837
8847
|
${stepsCheck$1("v_steps", stepsInvalid, manager)}
|
|
8848
|
+
v_steps := ${allUsersCounted("v_steps")};
|
|
8838
8849
|
if coalesce(save_approval_policy.policy ->> 'mode', v_old.${p("mode")}::text, 'authorize') not in ('confirm', 'authorize') then
|
|
8839
8850
|
${fail$1("APPROVAL_POLICY_INVALID", "mode must be confirm or authorize", "22023")}
|
|
8840
8851
|
end if;
|
|
@@ -9006,6 +9017,7 @@ begin
|
|
|
9006
9017
|
${ownInvalid}
|
|
9007
9018
|
end if;
|
|
9008
9019
|
${stepsCheck$1("v_steps", ownInvalid, manager)}
|
|
9020
|
+
v_steps := ${allUsersCounted("v_steps")};
|
|
9009
9021
|
v_expires := (approval_policy_tighten.own ->> 'expiresIn')::interval;
|
|
9010
9022
|
if approval_policy_tighten.base is null then
|
|
9011
9023
|
return jsonb_build_object(
|
|
@@ -9638,6 +9650,7 @@ function approverCheck(ctx, layout, request) {
|
|
|
9638
9650
|
subject: request.subject,
|
|
9639
9651
|
tenant: request.tenant,
|
|
9640
9652
|
requester: request.requester,
|
|
9653
|
+
approvers: request.approvers ?? "null::jsonb",
|
|
9641
9654
|
scope: provider.scope
|
|
9642
9655
|
}),
|
|
9643
9656
|
template: "isApprover",
|
|
@@ -10377,7 +10390,7 @@ const TRASH = {
|
|
|
10377
10390
|
build: build$114
|
|
10378
10391
|
};
|
|
10379
10392
|
// src/sql/modules/drive-kit.ts
|
|
10380
|
-
const SUBJECT_TYPE$
|
|
10393
|
+
const SUBJECT_TYPE$2 = /^[a-z][a-z0-9_]{0,62}$/;
|
|
10381
10394
|
const ROLE$1 = /^[a-z][a-z0-9_]{0,30}$/;
|
|
10382
10395
|
const SOURCE = /^[a-z][a-z0-9-]{0,30}$/;
|
|
10383
10396
|
const CONFLICTS = [
|
|
@@ -10745,7 +10758,7 @@ function driveSubjectGuard(ctx) {
|
|
|
10745
10758
|
/** `options.subjectType`: the subject type of a node, `drive_node` by default. */
|
|
10746
10759
|
function driveSubjectType(ctx) {
|
|
10747
10760
|
const type = ctx.text("subjectType", "drive_node");
|
|
10748
|
-
if (!SUBJECT_TYPE$
|
|
10761
|
+
if (!SUBJECT_TYPE$2.test(type)) throw new TypeError("blocks.drive.options.subjectType must be lowercase letters, digits and underscores");
|
|
10749
10762
|
return type;
|
|
10750
10763
|
}
|
|
10751
10764
|
function conflictDefault(ctx) {
|
|
@@ -11717,7 +11730,8 @@ function build$112(ctx, layout) {
|
|
|
11717
11730
|
kind: { sql: `v_req.${c("subjectType")} || '.' || v_req.${c("action")}` },
|
|
11718
11731
|
subject: `v_req.${c("subjectId")}::text`,
|
|
11719
11732
|
tenant: `v_req.${c("tenant")}`,
|
|
11720
|
-
requester: `v_req.${c("requestedBy")}
|
|
11733
|
+
requester: `v_req.${c("requestedBy")}`,
|
|
11734
|
+
approvers: "(coalesce(v_approvers, '{}'::jsonb) || jsonb_build_object('required', coalesce(v_step -> 'required', '1'::jsonb)))"
|
|
11721
11735
|
});
|
|
11722
11736
|
const subjects = subjectsOption(ctx);
|
|
11723
11737
|
const fn = (name) => ctx.fn(name);
|
|
@@ -26172,7 +26186,7 @@ ${forgetDropped(ctx)}`,
|
|
|
26172
26186
|
tests: (ctx, layout) => auditTests(ctx, layout.auditedTables ?? [], restrictedOn(ctx))
|
|
26173
26187
|
};
|
|
26174
26188
|
// src/sql/modules/automations-tables.ts
|
|
26175
|
-
const SUBJECT_TYPE = SUBJECT_TYPE_SQL_PATTERN;
|
|
26189
|
+
const SUBJECT_TYPE$1 = SUBJECT_TYPE_SQL_PATTERN;
|
|
26176
26190
|
const TRIGGER$1 = "^[a-z][a-z0-9_]*([.:][a-z0-9_]+)*$";
|
|
26177
26191
|
const ACTION_KIND = "^[a-z][a-z0-9_]*([.][a-z0-9_]+)*$";
|
|
26178
26192
|
const FIELD_ID = "^[A-Za-z_][A-Za-z0-9_]*([.][A-Za-z_][A-Za-z0-9_]*)*$";
|
|
@@ -26213,7 +26227,7 @@ create unique index if not exists ${ctx.naming.rename("rules_default_key_idx")}
|
|
|
26213
26227
|
${createTable(ctx, "rules", [
|
|
26214
26228
|
["id", "uuid primary key default gen_random_uuid()"],
|
|
26215
26229
|
["tenant", `${id} not null`],
|
|
26216
|
-
["subjectType", `text not null check (${r("subjectType")} ~ ${sqlString(SUBJECT_TYPE)})`],
|
|
26230
|
+
["subjectType", `text not null check (${r("subjectType")} ~ ${sqlString(SUBJECT_TYPE$1)})`],
|
|
26217
26231
|
["trigger", `text not null check (length(${r("trigger")}) <= 128 and ${r("trigger")} ~ ${sqlString(TRIGGER$1)})`],
|
|
26218
26232
|
["name", `text not null check (length(${r("name")}) between 1 and 200)`],
|
|
26219
26233
|
["description", `text check (length(${r("description")}) <= 2000)`],
|
|
@@ -26237,7 +26251,7 @@ ${lockTable(t)}
|
|
|
26237
26251
|
${createTable(ctx, "defaults", [
|
|
26238
26252
|
["key", `text primary key check (length(${rd("key")}) <= 128 and ${rd("key")} ~ ${sqlString(ACTION_KIND)})`],
|
|
26239
26253
|
["block", "text not null"],
|
|
26240
|
-
["subjectType", `text not null check (${rd("subjectType")} ~ ${sqlString(SUBJECT_TYPE)})`],
|
|
26254
|
+
["subjectType", `text not null check (${rd("subjectType")} ~ ${sqlString(SUBJECT_TYPE$1)})`],
|
|
26241
26255
|
["trigger", `text not null check (length(${rd("trigger")}) <= 128 and ${rd("trigger")} ~ ${sqlString(TRIGGER$1)})`],
|
|
26242
26256
|
["name", `text not null check (length(${rd("name")}) between 1 and 200)`],
|
|
26243
26257
|
["description", `text check (length(${rd("description")}) <= 2000)`],
|
|
@@ -26286,7 +26300,7 @@ ${lockTable(e)}
|
|
|
26286
26300
|
-- The fields rules may test, per subject type. The app declares them in code
|
|
26287
26301
|
-- (defineRuleFields) and syncs them with the service role.
|
|
26288
26302
|
${createTable(ctx, "fields", [
|
|
26289
|
-
["subjectType", `text not null check (${rf("subjectType")} ~ ${sqlString(SUBJECT_TYPE)})`],
|
|
26303
|
+
["subjectType", `text not null check (${rf("subjectType")} ~ ${sqlString(SUBJECT_TYPE$1)})`],
|
|
26290
26304
|
["id", `text not null check (length(${rf("id")}) <= 128 and ${rf("id")} ~ ${sqlString(FIELD_ID)})`],
|
|
26291
26305
|
["label", "text not null"],
|
|
26292
26306
|
["description", "text"],
|
|
@@ -27329,7 +27343,7 @@ begin
|
|
|
27329
27343
|
if not ${canKey("save_rule.tenant", `(v_enabled or coalesce(v_old.${r("enabled")}, false))`)} then
|
|
27330
27344
|
${raise$1("You need % to save this rule", "42501", "RULE_FORBIDDEN", keyFor(`(v_enabled or coalesce(v_old.${r("enabled")}, false))`))}
|
|
27331
27345
|
end if;
|
|
27332
|
-
if v_subject_type is null or v_subject_type !~ ${sqlString(SUBJECT_TYPE)} then
|
|
27346
|
+
if v_subject_type is null or v_subject_type !~ ${sqlString(SUBJECT_TYPE$1)} then
|
|
27333
27347
|
${fail$1("RULE_INVALID", "A rule needs a subject type", "22023")}
|
|
27334
27348
|
end if;
|
|
27335
27349
|
if v_trigger is null or length(v_trigger) > 128 or v_trigger !~ ${sqlString(TRIGGER$1)} then
|
|
@@ -29049,9 +29063,9 @@ function plansOf(ctx) {
|
|
|
29049
29063
|
...variant === void 0 ? {} : { variant }
|
|
29050
29064
|
};
|
|
29051
29065
|
}
|
|
29052
|
-
const qualified$
|
|
29066
|
+
const qualified$8 = (table) => quotedTable$1(table);
|
|
29053
29067
|
const platformPlans = (plans) => plans && {
|
|
29054
|
-
table: qualified$
|
|
29068
|
+
table: qualified$8(plans.table),
|
|
29055
29069
|
key: plans.key,
|
|
29056
29070
|
price: plans.price
|
|
29057
29071
|
};
|
|
@@ -29069,7 +29083,7 @@ stable
|
|
|
29069
29083
|
security definer
|
|
29070
29084
|
set search_path = ''
|
|
29071
29085
|
as $$
|
|
29072
|
-
${plans ? `select p.${sqlIdent(plans.price)}::text from ${qualified$
|
|
29086
|
+
${plans ? `select p.${sqlIdent(plans.price)}::text from ${qualified$8(plans.table)} p
|
|
29073
29087
|
where p.${sqlIdent(plans.key)}::text = billing_plan_price.plan${plans.interval ? `
|
|
29074
29088
|
and (billing_plan_price.billing_interval is null or p.${sqlIdent(plans.interval)}::text = billing_plan_price.billing_interval)` : ""}${plans.variant ? `
|
|
29075
29089
|
and (billing_plan_price.variant is null or p.${sqlIdent(plans.variant)}::text = billing_plan_price.variant)` : ""}${plans.active ? `
|
|
@@ -32446,7 +32460,7 @@ const ALARM_ACTIONS = [
|
|
|
32446
32460
|
const TRIGGER_BOUND = 525600;
|
|
32447
32461
|
/** At most this many alarms per event. */
|
|
32448
32462
|
const ALARM_LIMIT = 20;
|
|
32449
|
-
const list$
|
|
32463
|
+
const list$10 = (values) => `(${values.map((value) => `'${value}'`).join(", ")})`;
|
|
32450
32464
|
/**
|
|
32451
32465
|
* The `calendar_event_alarms` table: one row per `VALARM` of an event, with an
|
|
32452
32466
|
* offset in minutes before the start or end (`offset_minutes`, the reminders
|
|
@@ -32480,7 +32494,7 @@ function alarmsTable(ctx) {
|
|
|
32480
32494
|
...ctx.has("alarms", "method") ? [addCheck({
|
|
32481
32495
|
table: alarms,
|
|
32482
32496
|
name: `${name}_method_check`,
|
|
32483
|
-
expression: `${l("method")} in ${list$
|
|
32497
|
+
expression: `${l("method")} in ${list$10(ALARM_ACTIONS)}`
|
|
32484
32498
|
})] : [],
|
|
32485
32499
|
addCheck({
|
|
32486
32500
|
table: alarms,
|
|
@@ -32568,7 +32582,7 @@ function alarmWrites(ctx) {
|
|
|
32568
32582
|
if exists (
|
|
32569
32583
|
select 1 from jsonb_array_elements(v_item -> 'alarms') x
|
|
32570
32584
|
where jsonb_typeof(x) <> 'object'
|
|
32571
|
-
or coalesce(x ->> 'method', 'display') not in ${list$
|
|
32585
|
+
or coalesce(x ->> 'method', 'display') not in ${list$10(ALARM_ACTIONS)}
|
|
32572
32586
|
or coalesce(x ->> 'related', 'start') not in ('start', 'end')
|
|
32573
32587
|
or (x ->> 'offsetMinutes' is null) = (x ->> 'at' is null)
|
|
32574
32588
|
or abs(coalesce((x ->> 'offsetMinutes')::integer, 0)) > ${TRIGGER_BOUND}
|
|
@@ -43513,6 +43527,13 @@ drop function if exists ${fn("comments_after_write")}();`;
|
|
|
43513
43527
|
// src/sql/modules/compliance-shared.ts
|
|
43514
43528
|
/** The keys the control reads return next to the extra columns. */
|
|
43515
43529
|
const CONTROL_RESERVED = ["fields", "status"];
|
|
43530
|
+
/** What a framework is: a standard, a law, the organization's own or a contract. */
|
|
43531
|
+
const FRAMEWORK_KINDS = [
|
|
43532
|
+
"standard",
|
|
43533
|
+
"legal",
|
|
43534
|
+
"internal",
|
|
43535
|
+
"contract"
|
|
43536
|
+
];
|
|
43516
43537
|
/** The attachments module, when its table is there to reference. */
|
|
43517
43538
|
function evidenceAttachments(ctx) {
|
|
43518
43539
|
return ctx.installed("attachments") && ctx.of("attachments").manages ? ctx.of("attachments") : void 0;
|
|
@@ -43520,8 +43541,10 @@ function evidenceAttachments(ctx) {
|
|
|
43520
43541
|
/** `row.column`, or null when the app's table lacks the optional column. */
|
|
43521
43542
|
const optionalField$1 = (ctx, table, row, column) => ctx.has(table, column) ? `${row}.${ctx.col(table, column)}` : "null";
|
|
43522
43543
|
// src/sql/modules/compliance-functions.ts
|
|
43544
|
+
/** The arguments of save_control before it took a source and a jurisdiction. */
|
|
43545
|
+
const PREVIOUS_CONTROL_ARGS = "uuid, text, text, text, uuid, boolean, uuid";
|
|
43523
43546
|
/** The framework, control, evidence and evidence task functions. */
|
|
43524
|
-
function
|
|
43547
|
+
function complianceFunctions(ctx) {
|
|
43525
43548
|
const frameworks = ctx.table("frameworks");
|
|
43526
43549
|
const controls = ctx.table("controls");
|
|
43527
43550
|
const evidence = ctx.table("evidence");
|
|
@@ -43545,9 +43568,12 @@ function controlsFunctions(ctx) {
|
|
|
43545
43568
|
const insertCol = (table, column) => has(table, column) ? `, ${ctx.col(table, column)}` : "";
|
|
43546
43569
|
const insertVal = (table, column, value) => has(table, column) ? `, ${value}` : "";
|
|
43547
43570
|
const touch = (table) => has(table, "updatedAt") ? `, ${ctx.col(table, "updatedAt")} = now()` : "";
|
|
43571
|
+
const labels = ["source", "jurisdiction"].filter((column) => has("controls", column));
|
|
43572
|
+
const labelSets = (row) => labels.map((column) => `, ${k(column)} = ${row}.${k(column)}`).join("");
|
|
43573
|
+
const labelUpdates = labels.map((column) => `${k(column)} = nullif(trim(save_control.${column}), ''), `).join("");
|
|
43548
43574
|
const assignee = has("tasks", "assignee");
|
|
43549
43575
|
const owner = has("controls", "owner");
|
|
43550
|
-
const frameworkSets = [`${f("name")} = excluded.${f("name")}${has("frameworks", "version") ? `, ${f("version")} = excluded.${f("version")}` : ""}`, [has("frameworks", "description") ? `${f("description")} = excluded.${f("description")}` : "", has("frameworks", "updatedAt") ? `${f("updatedAt")} = now()` : ""].filter((set) => set !== "").join(", ")].filter((line) => line !== "").join(",\n ");
|
|
43576
|
+
const frameworkSets = [`${f("name")} = excluded.${f("name")}${has("frameworks", "kind") ? `, ${f("kind")} = excluded.${f("kind")}` : ""}${has("frameworks", "version") ? `, ${f("version")} = excluded.${f("version")}` : ""}`, [has("frameworks", "description") ? `${f("description")} = excluded.${f("description")}` : "", has("frameworks", "updatedAt") ? `${f("updatedAt")} = now()` : ""].filter((set) => set !== "").join(", ")].filter((line) => line !== "").join(",\n ");
|
|
43551
43577
|
const allowed = (tenant, permission) => `(${SERVICE_CALLER$1} or ${ctx.can("tenant", tenant, permission)})`;
|
|
43552
43578
|
const forbidden = (message) => fail$1("CONTROLS_FORBIDDEN", message);
|
|
43553
43579
|
const invalid = (message) => fail$1("CONTROLS_INVALID", message, "22023");
|
|
@@ -43562,8 +43588,8 @@ function controlsFunctions(ctx) {
|
|
|
43562
43588
|
when exists (select 1 from ${evidence} se where se.${e("control")} = ${row}.${k("id")}) then 'failing'
|
|
43563
43589
|
else 'not_started'
|
|
43564
43590
|
end`;
|
|
43565
|
-
const controlJson = (row) => `jsonb_build_object('id', ${row}.${k("id")}, 'organizationId', ${row}.${k("tenant")}, 'frameworkId', ${row}.${k("framework")}, 'code', ${row}.${k("code")}, 'title', ${row}.${k("title")}, 'description', ${field("controls", row, "description")}, 'ownerId', ${field("controls", row, "owner")}, 'applicable', ${row}.${k("applicable")}, 'status', ${status(row)}, 'createdAt', ${field("controls", row, "createdAt")}, 'updatedAt', ${field("controls", row, "updatedAt")}${extraFieldsJson(row, extras)})`;
|
|
43566
|
-
const frameworkJson = (row) => `jsonb_build_object('id', ${row}.${f("id")}, 'organizationId', ${row}.${f("tenant")}, 'key', ${row}.${f("key")}, 'name', ${row}.${f("name")}, 'version', ${field("frameworks", row, "version")}, 'description', ${field("frameworks", row, "description")}, 'createdAt', ${field("frameworks", row, "createdAt")}, 'updatedAt', ${field("frameworks", row, "updatedAt")})`;
|
|
43591
|
+
const controlJson = (row) => `jsonb_build_object('id', ${row}.${k("id")}, 'organizationId', ${row}.${k("tenant")}, 'frameworkId', ${row}.${k("framework")}, 'code', ${row}.${k("code")}, 'title', ${row}.${k("title")}, 'description', ${field("controls", row, "description")}, 'ownerId', ${field("controls", row, "owner")}, 'applicable', ${row}.${k("applicable")}, 'source', ${field("controls", row, "source")}, 'jurisdiction', ${field("controls", row, "jurisdiction")}, 'status', ${status(row)}, 'createdAt', ${field("controls", row, "createdAt")}, 'updatedAt', ${field("controls", row, "updatedAt")}${extraFieldsJson(row, extras)})`;
|
|
43592
|
+
const frameworkJson = (row) => `jsonb_build_object('id', ${row}.${f("id")}, 'organizationId', ${row}.${f("tenant")}, 'key', ${row}.${f("key")}, 'name', ${row}.${f("name")}, 'kind', ${has("frameworks", "kind") ? `${row}.${f("kind")}` : "'standard'"}, 'version', ${field("frameworks", row, "version")}, 'description', ${field("frameworks", row, "description")}, 'createdAt', ${field("frameworks", row, "createdAt")}, 'updatedAt', ${field("frameworks", row, "updatedAt")})`;
|
|
43567
43593
|
const evidenceJson = (row) => `jsonb_build_object('id', ${row}.${e("id")}, 'organizationId', ${row}.${e("tenant")}, 'controlId', ${row}.${e("control")}, 'evidenceTaskId', ${row}.${e("task")}, 'attachmentId', ${row}.${e("attachment")}, 'note', ${field("evidence", row, "note")}, 'collectedBy', ${row}.${e("collectedBy")}, 'collectedAt', ${row}.${e("collectedAt")}, 'validUntil', ${row}.${e("validUntil")}, 'valid', ${valid(row)})`;
|
|
43568
43594
|
const taskJson = (row) => `jsonb_build_object('id', ${row}.${t("id")}, 'organizationId', ${row}.${t("tenant")}, 'controlId', ${row}.${t("control")}, 'title', ${row}.${t("title")}, 'assigneeId', ${field("tasks", row, "assignee")}, 'intervalDays', ${row}.${t("intervalDays")}, 'dueOn', ${row}.${t("dueOn")}, 'lastCollectedAt', ${field("tasks", row, "lastCollectedAt")}, 'active', ${row}.${t("active")}, 'overdue', ${overdue(row)}, 'createdAt', ${field("tasks", row, "createdAt")}, 'updatedAt', ${field("tasks", row, "updatedAt")})`;
|
|
43569
43595
|
const attachmentCheck = attachments === void 0 ? `if add_control_evidence.attachment_id is not null then
|
|
@@ -43591,7 +43617,10 @@ function controlsFunctions(ctx) {
|
|
|
43591
43617
|
end if;` : "";
|
|
43592
43618
|
return `
|
|
43593
43619
|
-- Creates or updates a framework (SOC 2, ISO 27001, an internal one) by key.
|
|
43594
|
-
|
|
43620
|
+
-- kind is standard, legal (a register of legal obligations), internal or
|
|
43621
|
+
-- contract.
|
|
43622
|
+
drop function if exists ${fn("save_control_framework")}(${idType}, text, text, text, text);
|
|
43623
|
+
create or replace function ${fn("save_control_framework")}(tenant ${idType}, key text, name text, version text default null, description text default null, kind text default 'standard')
|
|
43595
43624
|
returns jsonb
|
|
43596
43625
|
language plpgsql
|
|
43597
43626
|
security definer
|
|
@@ -43604,15 +43633,18 @@ begin
|
|
|
43604
43633
|
if not ${allowed("save_control_framework.tenant", manage)} then
|
|
43605
43634
|
${forbidden("not allowed to manage controls")}
|
|
43606
43635
|
end if;
|
|
43607
|
-
|
|
43608
|
-
|
|
43636
|
+
if save_control_framework.kind is null or save_control_framework.kind not in (${FRAMEWORK_KINDS.map((item) => `'${item}'`).join(", ")}) then
|
|
43637
|
+
${invalid(`kind must be one of ${FRAMEWORK_KINDS.join(", ")}`)}
|
|
43638
|
+
end if;
|
|
43639
|
+
insert into ${frameworks} (${f("tenant")}, ${f("key")}, ${f("name")}${insertCol("frameworks", "kind")}${insertCol("frameworks", "version")}${insertCol("frameworks", "description")})
|
|
43640
|
+
values (save_control_framework.tenant, save_control_framework.key, trim(save_control_framework.name)${insertVal("frameworks", "kind", "save_control_framework.kind")}${insertVal("frameworks", "version", "nullif(trim(save_control_framework.version), '')")}${insertVal("frameworks", "description", "nullif(trim(save_control_framework.description), '')")})
|
|
43609
43641
|
on conflict (${f("tenant")}, ${f("key")}) do update
|
|
43610
43642
|
set ${frameworkSets}
|
|
43611
43643
|
returning * into v_row;
|
|
43612
43644
|
return ${frameworkJson("v_row")};
|
|
43613
43645
|
end;
|
|
43614
43646
|
$$;
|
|
43615
|
-
${userGrant(`${fn("save_control_framework")}(${idType}, text, text, text, text)`)}
|
|
43647
|
+
${userGrant(`${fn("save_control_framework")}(${idType}, text, text, text, text, text)`)}
|
|
43616
43648
|
|
|
43617
43649
|
create or replace function ${fn("list_control_frameworks")}(tenant ${idType})
|
|
43618
43650
|
returns jsonb
|
|
@@ -43629,8 +43661,12 @@ ${userGrant(`${fn("list_control_frameworks")}(${idType})`)}
|
|
|
43629
43661
|
|
|
43630
43662
|
-- Creates a control in a framework, or changes one (control_id). Without
|
|
43631
43663
|
-- control_id, a control with the same code in the framework is updated.
|
|
43632
|
-
|
|
43633
|
-
|
|
43664
|
+
-- source names where an obligation comes from (a law or a clause) and
|
|
43665
|
+
-- jurisdiction where it applies.
|
|
43666
|
+
drop function if exists ${fn("save_control")}(${PREVIOUS_CONTROL_ARGS});
|
|
43667
|
+
drop function if exists ${fn("save_control")}(${PREVIOUS_CONTROL_ARGS}, jsonb);
|
|
43668
|
+
${extra.drop(fn("save_control"), `${PREVIOUS_CONTROL_ARGS}, text, text`)}
|
|
43669
|
+
create or replace function ${fn("save_control")}(framework_id uuid, code text, title text, description text default null, owner_id uuid default null, applicable boolean default true, control_id uuid default null, source text default null, jurisdiction text default null${extra.param})
|
|
43634
43670
|
returns jsonb
|
|
43635
43671
|
language plpgsql
|
|
43636
43672
|
security definer
|
|
@@ -43656,15 +43692,15 @@ ${owner ? ` if save_control.owner_id is not null and not ${isMember(`v_framewor
|
|
|
43656
43692
|
${invalid("the owner must be a member of the organization")}
|
|
43657
43693
|
end if;
|
|
43658
43694
|
` : ""} if save_control.control_id is null then
|
|
43659
|
-
insert into ${controls} (${k("tenant")}, ${k("framework")}, ${k("code")}, ${k("title")}${insertCol("controls", "description")}${insertCol("controls", "owner")}, ${k("applicable")})
|
|
43660
|
-
values (v_framework.${f("tenant")}, v_framework.${f("id")}, trim(save_control.code), trim(save_control.title)${insertVal("controls", "description", "nullif(trim(save_control.description), '')")}${insertVal("controls", "owner", "save_control.owner_id")}, coalesce(save_control.applicable, true))
|
|
43695
|
+
insert into ${controls} (${k("tenant")}, ${k("framework")}, ${k("code")}, ${k("title")}${insertCol("controls", "description")}${insertCol("controls", "owner")}${insertCol("controls", "source")}${insertCol("controls", "jurisdiction")}, ${k("applicable")})
|
|
43696
|
+
values (v_framework.${f("tenant")}, v_framework.${f("id")}, trim(save_control.code), trim(save_control.title)${insertVal("controls", "description", "nullif(trim(save_control.description), '')")}${insertVal("controls", "owner", "save_control.owner_id")}${insertVal("controls", "source", "nullif(trim(save_control.source), '')")}${insertVal("controls", "jurisdiction", "nullif(trim(save_control.jurisdiction), '')")}, coalesce(save_control.applicable, true))
|
|
43661
43697
|
on conflict (${k("framework")}, ${k("code")}) do update
|
|
43662
|
-
set ${k("title")} = excluded.${k("title")}${has("controls", "description") ? `, ${k("description")} = excluded.${k("description")}` : ""},
|
|
43698
|
+
set ${k("title")} = excluded.${k("title")}${has("controls", "description") ? `, ${k("description")} = excluded.${k("description")}` : ""}${labelSets("excluded")},
|
|
43663
43699
|
${owner ? `${k("owner")} = excluded.${k("owner")}, ` : ""}${k("applicable")} = excluded.${k("applicable")}${touch("controls")}
|
|
43664
43700
|
returning * into v_row;
|
|
43665
43701
|
else
|
|
43666
43702
|
update ${controls} x set ${k("code")} = trim(save_control.code), ${k("title")} = trim(save_control.title),
|
|
43667
|
-
${has("controls", "description") ? `${k("description")} = nullif(trim(save_control.description), ''), ` : ""}${owner ? `${k("owner")} = save_control.owner_id,\n ` : ""}${k("applicable")} = coalesce(save_control.applicable, true)${touch("controls")}
|
|
43703
|
+
${has("controls", "description") ? `${k("description")} = nullif(trim(save_control.description), ''), ` : ""}${labelUpdates}${owner ? `${k("owner")} = save_control.owner_id,\n ` : ""}${k("applicable")} = coalesce(save_control.applicable, true)${touch("controls")}
|
|
43668
43704
|
where x.${k("id")} = save_control.control_id and x.${k("framework")} = v_framework.${f("id")}
|
|
43669
43705
|
returning * into v_row;
|
|
43670
43706
|
if not found then
|
|
@@ -43686,7 +43722,7 @@ ${owner ? ` if save_control.owner_id is not null and not ${isMember(`v_framewor
|
|
|
43686
43722
|
return ${controlJson("v_row")};
|
|
43687
43723
|
end;
|
|
43688
43724
|
$$;
|
|
43689
|
-
${userGrant(`${fn("save_control")}(
|
|
43725
|
+
${userGrant(`${fn("save_control")}(${PREVIOUS_CONTROL_ARGS}, text, text${extra.type})`)}
|
|
43690
43726
|
|
|
43691
43727
|
-- A control with its evidence (the newest first) and its evidence tasks.
|
|
43692
43728
|
create or replace function ${fn("get_control")}(control_id uuid)
|
|
@@ -43962,7 +43998,7 @@ ${serviceGrant(`${fn("notify_overdue_evidence_tasks")}()`)}
|
|
|
43962
43998
|
`;
|
|
43963
43999
|
}
|
|
43964
44000
|
// src/sql/modules/compliance-policies.ts
|
|
43965
|
-
/** The policy and acknowledgement functions of the `
|
|
44001
|
+
/** The policy and acknowledgement functions of the `compliance` module. */
|
|
43966
44002
|
function policyFunctions(ctx) {
|
|
43967
44003
|
const policies = ctx.table("policies");
|
|
43968
44004
|
const acks = ctx.table("acknowledgements");
|
|
@@ -44301,12 +44337,14 @@ const NAMES$89 = {
|
|
|
44301
44337
|
tenant: "tenant_id",
|
|
44302
44338
|
key: "key",
|
|
44303
44339
|
name: "name",
|
|
44340
|
+
kind: "kind",
|
|
44304
44341
|
version: "version",
|
|
44305
44342
|
description: "description",
|
|
44306
44343
|
createdAt: "created_at",
|
|
44307
44344
|
updatedAt: "updated_at"
|
|
44308
44345
|
},
|
|
44309
44346
|
optional: [
|
|
44347
|
+
"kind",
|
|
44310
44348
|
"version",
|
|
44311
44349
|
"description",
|
|
44312
44350
|
"createdAt",
|
|
@@ -44329,12 +44367,16 @@ const NAMES$89 = {
|
|
|
44329
44367
|
description: "description",
|
|
44330
44368
|
owner: "owner_id",
|
|
44331
44369
|
applicable: "applicable",
|
|
44370
|
+
source: "source",
|
|
44371
|
+
jurisdiction: "jurisdiction",
|
|
44332
44372
|
createdAt: "created_at",
|
|
44333
44373
|
updatedAt: "updated_at"
|
|
44334
44374
|
},
|
|
44335
44375
|
optional: [
|
|
44336
44376
|
"description",
|
|
44337
44377
|
"owner",
|
|
44378
|
+
"source",
|
|
44379
|
+
"jurisdiction",
|
|
44338
44380
|
"createdAt",
|
|
44339
44381
|
"updatedAt"
|
|
44340
44382
|
]
|
|
@@ -44455,6 +44497,9 @@ function tables$28(ctx) {
|
|
|
44455
44497
|
const extras = ctx.extraColumns("controls", CONTROL_RESERVED);
|
|
44456
44498
|
const name = (logical, suffix) => sqlIdent(`${ctx.tableName(logical).name}_${suffix}`);
|
|
44457
44499
|
const opt = (logical, column, line) => ctx.has(logical, column) ? `\n ${line()},` : "";
|
|
44500
|
+
const added = (logical, column, line) => ctx.has(logical, column) ? `\nalter table ${ctx.table(logical)} add column if not exists ${line()};` : "";
|
|
44501
|
+
const kind = () => `${f("kind")} text not null default 'standard' check (${f("kind")} in (${FRAMEWORK_KINDS.map((item) => `'${item}'`).join(", ")}))`;
|
|
44502
|
+
const label = (column) => () => `${k(column)} text check (${k(column)} is null or length(${k(column)}) between 1 and 200)`;
|
|
44458
44503
|
const readPolicy = (logical, using) => {
|
|
44459
44504
|
const policy = ctx.owns(logical) ? name(logical, "read") : sqlIdent(`bsb_${ctx.tableName(logical).name}_read`);
|
|
44460
44505
|
return renderPolicy(policy$1({
|
|
@@ -44475,10 +44520,10 @@ create table if not exists ${frameworks} (
|
|
|
44475
44520
|
${f("id")} uuid primary key default gen_random_uuid(),
|
|
44476
44521
|
${f("tenant")} ${ctx.idType} not null,
|
|
44477
44522
|
${f("key")} text not null check (${f("key")} ~ '^[a-z0-9][a-z0-9_.-]{0,62}$'),
|
|
44478
|
-
${f("name")} text not null check (length(${f("name")}) between 1 and 200),${opt("frameworks", "version", () => `${f("version")} text check (${f("version")} is null or length(${f("version")}) <= 50)`)}${opt("frameworks", "description", () => `${f("description")} text check (${f("description")} is null or length(${f("description")}) <= 4000)`)}${opt("frameworks", "createdAt", () => `${f("createdAt")} timestamptz not null default now()`)}${opt("frameworks", "updatedAt", () => `${f("updatedAt")} timestamptz not null default now()`)}
|
|
44523
|
+
${f("name")} text not null check (length(${f("name")}) between 1 and 200),${opt("frameworks", "kind", kind)}${opt("frameworks", "version", () => `${f("version")} text check (${f("version")} is null or length(${f("version")}) <= 50)`)}${opt("frameworks", "description", () => `${f("description")} text check (${f("description")} is null or length(${f("description")}) <= 4000)`)}${opt("frameworks", "createdAt", () => `${f("createdAt")} timestamptz not null default now()`)}${opt("frameworks", "updatedAt", () => `${f("updatedAt")} timestamptz not null default now()`)}
|
|
44479
44524
|
unique (${f("tenant")}, ${f("key")}),
|
|
44480
44525
|
unique (${f("tenant")}, ${f("id")})
|
|
44481
|
-
);${appKey("frameworks", "tenant_key", `${f("tenant")}, ${f("key")}`)}${appKey("frameworks", "tenant_id", `${f("tenant")}, ${f("id")}`)}
|
|
44526
|
+
);${added("frameworks", "kind", kind)}${appKey("frameworks", "tenant_key", `${f("tenant")}, ${f("key")}`)}${appKey("frameworks", "tenant_id", `${f("tenant")}, ${f("id")}`)}
|
|
44482
44527
|
${lockTable(frameworks, { read: true })}
|
|
44483
44528
|
${readPolicy("frameworks", ctx.scope.check(f("tenant"), read))}
|
|
44484
44529
|
|
|
@@ -44489,11 +44534,11 @@ create table if not exists ${controls} (
|
|
|
44489
44534
|
${k("code")} text not null check (length(${k("code")}) between 1 and 50),
|
|
44490
44535
|
${k("title")} text not null check (length(${k("title")}) between 1 and 200),${opt("controls", "description", () => `${k("description")} text check (${k("description")} is null or length(${k("description")}) <= 10000)`)}${opt("controls", "owner", () => `${k("owner")} uuid`)}
|
|
44491
44536
|
-- A control out of scope (excluded in the statement of applicability).
|
|
44492
|
-
${k("applicable")} boolean not null default true,${opt("controls", "createdAt", () => `${k("createdAt")} timestamptz not null default now()`)}${opt("controls", "updatedAt", () => `${k("updatedAt")} timestamptz not null default now()`)}
|
|
44537
|
+
${k("applicable")} boolean not null default true,${opt("controls", "source", label("source"))}${opt("controls", "jurisdiction", label("jurisdiction"))}${opt("controls", "createdAt", () => `${k("createdAt")} timestamptz not null default now()`)}${opt("controls", "updatedAt", () => `${k("updatedAt")} timestamptz not null default now()`)}
|
|
44493
44538
|
unique (${k("framework")}, ${k("code")}),
|
|
44494
44539
|
unique (${k("tenant")}, ${k("id")}),
|
|
44495
44540
|
foreign key (${k("tenant")}, ${k("framework")}) references ${frameworks} (${f("tenant")}, ${f("id")}) on delete cascade
|
|
44496
|
-
);${addExtraColumns(controls, extras)}${appKey("controls", "framework_code", `${k("framework")}, ${k("code")}`)}${appKey("controls", "tenant_id", `${k("tenant")}, ${k("id")}`)}
|
|
44541
|
+
);${added("controls", "source", label("source"))}${added("controls", "jurisdiction", label("jurisdiction"))}${addExtraColumns(controls, extras)}${appKey("controls", "framework_code", `${k("framework")}, ${k("code")}`)}${appKey("controls", "tenant_id", `${k("tenant")}, ${k("id")}`)}
|
|
44497
44542
|
create index if not exists ${name("controls", "tenant_idx")} on ${controls} (${k("tenant")}, ${k("framework")});${ctx.has("controls", "owner") ? `
|
|
44498
44543
|
create index if not exists ${name("controls", "owner_idx")} on ${controls} (${k("tenant")}, ${k("owner")}) where ${k("owner")} is not null;` : ""}
|
|
44499
44544
|
${lockTable(controls, { read: true })}
|
|
@@ -44578,7 +44623,7 @@ function build$89(ctx) {
|
|
|
44578
44623
|
return `${schemaPreamble(ctx)}
|
|
44579
44624
|
-- Compliance controls: frameworks of controls, evidence linked to them,
|
|
44580
44625
|
-- recurring evidence tasks, and versioned policies members acknowledge.
|
|
44581
|
-
${tables$28(ctx)}${
|
|
44626
|
+
${tables$28(ctx)}${complianceFunctions(ctx)}${policyFunctions(ctx)}`;
|
|
44582
44627
|
}
|
|
44583
44628
|
function contract$80(ctx) {
|
|
44584
44629
|
return [
|
|
@@ -44589,6 +44634,7 @@ function contract$80(ctx) {
|
|
|
44589
44634
|
"text",
|
|
44590
44635
|
"text",
|
|
44591
44636
|
"text",
|
|
44637
|
+
"text",
|
|
44592
44638
|
"text"
|
|
44593
44639
|
],
|
|
44594
44640
|
returns: "jsonb"
|
|
@@ -44608,6 +44654,8 @@ function contract$80(ctx) {
|
|
|
44608
44654
|
"uuid",
|
|
44609
44655
|
"boolean",
|
|
44610
44656
|
"uuid",
|
|
44657
|
+
"text",
|
|
44658
|
+
"text",
|
|
44611
44659
|
...extraFieldsArg(ctx.extraColumns("controls", CONTROL_RESERVED)).contract
|
|
44612
44660
|
],
|
|
44613
44661
|
returns: "jsonb"
|
|
@@ -44724,7 +44772,7 @@ function contract$80(ctx) {
|
|
|
44724
44772
|
}
|
|
44725
44773
|
];
|
|
44726
44774
|
}
|
|
44727
|
-
const
|
|
44775
|
+
const COMPLIANCE = {
|
|
44728
44776
|
name: "compliance",
|
|
44729
44777
|
scopes: ["tenant"],
|
|
44730
44778
|
title: "Compliance controls",
|
|
@@ -46015,6 +46063,117 @@ $$;
|
|
|
46015
46063
|
${userGrant(`${fn("person_for_inbox_contact")}(uuid, boolean)`)}
|
|
46016
46064
|
`;
|
|
46017
46065
|
}
|
|
46066
|
+
// src/sql/modules/contacts-representatives.ts
|
|
46067
|
+
/** The relation kind a representative's link has. */
|
|
46068
|
+
const REPRESENTS = "represents";
|
|
46069
|
+
const list$9 = (values) => values.map((value) => sqlString(value)).join(", ");
|
|
46070
|
+
/** Whether `key` of `data` (a jsonb expression) is missing or a date string. */
|
|
46071
|
+
const dateOrMissing = (data, key) => `(${data} -> '${key}' is null or (jsonb_typeof(${data} -> '${key}') = 'string' and pg_input_is_valid(${data} ->> '${key}', 'date')))`;
|
|
46072
|
+
/**
|
|
46073
|
+
* The check `link` runs on a `represents` link's data: a role, an authority,
|
|
46074
|
+
* and `valid_from` and `valid_until` dates in order when set.
|
|
46075
|
+
*/
|
|
46076
|
+
function representationData(data) {
|
|
46077
|
+
const from = `${data} ->> 'valid_from'`;
|
|
46078
|
+
const until = `${data} ->> 'valid_until'`;
|
|
46079
|
+
return `(jsonb_typeof(${data}) = 'object'
|
|
46080
|
+
and (${data} ->> 'role') in (${list$9(REPRESENTATIVE_ROLES)})
|
|
46081
|
+
and (${data} ->> 'authority') in (${list$9(REPRESENTATIVE_AUTHORITIES)})
|
|
46082
|
+
and ${dateOrMissing(data, "valid_from")}
|
|
46083
|
+
and ${dateOrMissing(data, "valid_until")}
|
|
46084
|
+
and case when pg_input_is_valid(${from}, 'date') and pg_input_is_valid(${until}, 'date')
|
|
46085
|
+
then (${from})::date <= (${until})::date else true end)`;
|
|
46086
|
+
}
|
|
46087
|
+
/**
|
|
46088
|
+
* Whether a `represents` link with `data` holds today: `valid_from` is past or
|
|
46089
|
+
* unset and `valid_until` is today or later or unset. A date Postgres can't
|
|
46090
|
+
* read ends the link, so an app kind without the check never throws here.
|
|
46091
|
+
*/
|
|
46092
|
+
function representationActive(data) {
|
|
46093
|
+
const bound = (key, compare) => `case when ${data} ->> '${key}' is null then true
|
|
46094
|
+
when pg_input_is_valid(${data} ->> '${key}', 'date') then (${data} ->> '${key}')::date ${compare} current_date
|
|
46095
|
+
else false end`;
|
|
46096
|
+
return `(${bound("valid_from", "<=")}) and (${bound("valid_until", ">=")})`;
|
|
46097
|
+
}
|
|
46098
|
+
/**
|
|
46099
|
+
* The `represents` kind contacts adds to relations: a person represents a
|
|
46100
|
+
* record.
|
|
46101
|
+
*/
|
|
46102
|
+
function representsKind(own) {
|
|
46103
|
+
return {
|
|
46104
|
+
kind: REPRESENTS,
|
|
46105
|
+
inverse: "represented_by",
|
|
46106
|
+
types: { source: [own.naming.rename("person")] },
|
|
46107
|
+
data: representationData
|
|
46108
|
+
};
|
|
46109
|
+
}
|
|
46110
|
+
/**
|
|
46111
|
+
* `list_representatives` and `represented_by_me` over the relations block's
|
|
46112
|
+
* links, with a leading newline. Empty without relations.
|
|
46113
|
+
*/
|
|
46114
|
+
function representativeFunctions(ctx, names) {
|
|
46115
|
+
if (!ctx.installed("relations")) return "";
|
|
46116
|
+
const relations = ctx.of("relations");
|
|
46117
|
+
const links = relations.table("relations");
|
|
46118
|
+
const r = (column) => `r.${relations.col("relations", column)}`;
|
|
46119
|
+
const p = (column) => `p.${names.c("people", column)}`;
|
|
46120
|
+
const person = sqlString(ctx.naming.rename("person"));
|
|
46121
|
+
const active = representationActive(r("data"));
|
|
46122
|
+
const kind = sqlString(REPRESENTS);
|
|
46123
|
+
const terms = `'role', ${r("data")} ->> 'role', 'authority', ${r("data")} ->> 'authority',
|
|
46124
|
+
'validFrom', ${r("data")} ->> 'valid_from', 'validUntil', ${r("data")} ->> 'valid_until'`;
|
|
46125
|
+
return `
|
|
46126
|
+
-- The people who represent a record (a client's guardian, a legal
|
|
46127
|
+
-- representative), with their role and authority. Runs as the caller, so the
|
|
46128
|
+
-- relations and people policies decide what they see. Ended links come last.
|
|
46129
|
+
create or replace function ${names.fn("list_representatives")}(subject_type text, subject_id text)
|
|
46130
|
+
returns jsonb
|
|
46131
|
+
language sql
|
|
46132
|
+
stable
|
|
46133
|
+
security invoker
|
|
46134
|
+
set search_path = ''
|
|
46135
|
+
as $$
|
|
46136
|
+
select coalesce(jsonb_agg(jsonb_build_object(
|
|
46137
|
+
'id', ${r("id")}, 'organizationId', ${r("tenant")}::text,
|
|
46138
|
+
'personId', ${p("id")}, 'name', ${p("name")}, 'email', ${p("email")}, 'phone', ${p("phone")},
|
|
46139
|
+
${terms},
|
|
46140
|
+
'active', ${active}, 'createdAt', ${r("createdAt")}
|
|
46141
|
+
) order by ${active} desc, ${p("name")}, ${r("id")}), '[]'::jsonb)
|
|
46142
|
+
from ${links} r
|
|
46143
|
+
join ${names.t("people")} p on ${p("id")}::text = ${r("sourceId")} and ${p("tenant")} = ${r("tenant")}
|
|
46144
|
+
where ${r("kind")} = ${kind} and ${r("sourceType")} = ${person}
|
|
46145
|
+
and ${r("targetType")} = list_representatives.subject_type
|
|
46146
|
+
and ${r("targetId")} = list_representatives.subject_id
|
|
46147
|
+
$$;
|
|
46148
|
+
${userGrant(`${names.fn("list_representatives")}(text, text)`)}
|
|
46149
|
+
|
|
46150
|
+
-- The records the caller represents in tenant, as a guest whose party is the
|
|
46151
|
+
-- representative, while the link holds.
|
|
46152
|
+
create or replace function ${names.fn("represented_by_me")}(tenant ${ctx.idType})
|
|
46153
|
+
returns jsonb
|
|
46154
|
+
language plpgsql
|
|
46155
|
+
stable
|
|
46156
|
+
security definer
|
|
46157
|
+
set search_path = ''
|
|
46158
|
+
as $$
|
|
46159
|
+
begin
|
|
46160
|
+
return (
|
|
46161
|
+
select coalesce(jsonb_agg(jsonb_build_object(
|
|
46162
|
+
'id', ${r("id")}, 'organizationId', ${r("tenant")}::text, 'personId', ${r("sourceId")},
|
|
46163
|
+
'subjectType', ${r("targetType")}, 'subjectId', ${r("targetId")},
|
|
46164
|
+
${terms}
|
|
46165
|
+
) order by ${r("createdAt")}, ${r("id")}), '[]'::jsonb)
|
|
46166
|
+
from ${links} r
|
|
46167
|
+
where ${r("tenant")} = represented_by_me.tenant
|
|
46168
|
+
and ${r("kind")} = ${kind} and ${r("sourceType")} = ${person}
|
|
46169
|
+
and ${active}
|
|
46170
|
+
and ${names.scope.guestParty("represented_by_me.tenant", person, r("sourceId"))}
|
|
46171
|
+
);
|
|
46172
|
+
end;
|
|
46173
|
+
$$;
|
|
46174
|
+
${userGrant(`${names.fn("represented_by_me")}(${ctx.idType})`)}
|
|
46175
|
+
`;
|
|
46176
|
+
}
|
|
46018
46177
|
// src/sql/modules/contacts.ts
|
|
46019
46178
|
/** The lifecycle stages `options.companyLifecycles` falls back to. */
|
|
46020
46179
|
const COMPANY_LIFECYCLES = [
|
|
@@ -46326,8 +46485,9 @@ function build$87(ctx) {
|
|
|
46326
46485
|
};
|
|
46327
46486
|
return `${schemaPreamble(ctx)}
|
|
46328
46487
|
-- Companies and people an organization works with, and who works where.
|
|
46329
|
-
${tables$27(ctx, names)}${partyFunctions(ctx, names)}${partiesInboxSql(ctx, names)}`;
|
|
46488
|
+
${tables$27(ctx, names)}${partyFunctions(ctx, names)}${partiesInboxSql(ctx, names)}${representativeFunctions(ctx, names)}`;
|
|
46330
46489
|
}
|
|
46490
|
+
const CONTRIBUTES$12 = { relations: (own) => [representsKind(own)] };
|
|
46331
46491
|
function contract$79(ctx) {
|
|
46332
46492
|
return [
|
|
46333
46493
|
{
|
|
@@ -46430,10 +46590,20 @@ function contract$79(ctx) {
|
|
|
46430
46590
|
args: ["uuid", "boolean"],
|
|
46431
46591
|
returns: "jsonb"
|
|
46432
46592
|
}
|
|
46433
|
-
] : []
|
|
46593
|
+
] : [],
|
|
46594
|
+
...ctx.installed("relations") ? [{
|
|
46595
|
+
name: "list_representatives",
|
|
46596
|
+
args: ["text", "text"],
|
|
46597
|
+
returns: "jsonb"
|
|
46598
|
+
}, {
|
|
46599
|
+
name: "represented_by_me",
|
|
46600
|
+
args: ["{id}"],
|
|
46601
|
+
returns: "jsonb"
|
|
46602
|
+
}] : []
|
|
46434
46603
|
];
|
|
46435
46604
|
}
|
|
46436
46605
|
const PARTIES = {
|
|
46606
|
+
contributes: CONTRIBUTES$12,
|
|
46437
46607
|
name: "contacts",
|
|
46438
46608
|
scopes: ["tenant"],
|
|
46439
46609
|
title: "Parties",
|
|
@@ -46443,7 +46613,8 @@ const PARTIES = {
|
|
|
46443
46613
|
"outbox",
|
|
46444
46614
|
"audit",
|
|
46445
46615
|
"notifications",
|
|
46446
|
-
"inbox"
|
|
46616
|
+
"inbox",
|
|
46617
|
+
"relations"
|
|
46447
46618
|
],
|
|
46448
46619
|
target: "schema",
|
|
46449
46620
|
modes: ["managed", "custom"],
|
|
@@ -48478,6 +48649,7 @@ const COURSE_KEYS = [
|
|
|
48478
48649
|
"summary",
|
|
48479
48650
|
"status",
|
|
48480
48651
|
"certificate",
|
|
48652
|
+
"validForMonths",
|
|
48481
48653
|
"createdBy",
|
|
48482
48654
|
"createdAt",
|
|
48483
48655
|
"updatedAt",
|
|
@@ -48523,7 +48695,7 @@ function courseSql(ctx) {
|
|
|
48523
48695
|
forbidden: (message) => fail$1("COURSE_FORBIDDEN", message),
|
|
48524
48696
|
courseMissing: fail$1("COURSE_NOT_FOUND", "course not found", "P0002"),
|
|
48525
48697
|
lessonMissing: fail$1("COURSE_LESSON_NOT_FOUND", "course lesson not found", "P0002"),
|
|
48526
|
-
courseJson: (row) => withExtraFields(`jsonb_build_object('id', ${row}.${c("id")}, 'organizationId', ${row}.${c("tenant")}, 'key', ${row}.${c("key")}, 'title', ${row}.${c("title")}, 'summary', ${field("courses", row, "summary")}, 'status', ${row}.${c("status")}, 'certificate', ${field("courses", row, "certificate", "true")}, 'createdBy', ${field("courses", row, "createdBy")}, 'createdAt', ${field("courses", row, "createdAt")}, 'updatedAt', ${field("courses", row, "updatedAt")})`, row, extras),
|
|
48698
|
+
courseJson: (row) => withExtraFields(`jsonb_build_object('id', ${row}.${c("id")}, 'organizationId', ${row}.${c("tenant")}, 'key', ${row}.${c("key")}, 'title', ${row}.${c("title")}, 'summary', ${field("courses", row, "summary")}, 'status', ${row}.${c("status")}, 'certificate', ${field("courses", row, "certificate", "true")}, 'validForMonths', ${field("courses", row, "validForMonths")}, 'createdBy', ${field("courses", row, "createdBy")}, 'createdAt', ${field("courses", row, "createdAt")}, 'updatedAt', ${field("courses", row, "updatedAt")})`, row, extras),
|
|
48527
48699
|
program: (course) => `('course:' || ${course}::text)`,
|
|
48528
48700
|
learnerRecord: (type, summary) => ctx.record({
|
|
48529
48701
|
type,
|
|
@@ -48568,9 +48740,9 @@ function courseAuthoringFunctions(ctx) {
|
|
|
48568
48740
|
summary: `'${summary}'`
|
|
48569
48741
|
}
|
|
48570
48742
|
});
|
|
48571
|
-
const certificateRecord = (type, row, summary) => ctx.record({
|
|
48743
|
+
const certificateRecord = (type, row, summary, extra = "") => ctx.record({
|
|
48572
48744
|
type,
|
|
48573
|
-
payload: `jsonb_build_object('organizationId', ${row}.${q.k("tenant")}, 'id', ${row}.${q.k("id")}, 'courseId', ${row}.${q.k("course")}, 'userId', ${row}.${q.k("user")}, 'enrollmentId', ${row}.${q.k("enrollment")})`,
|
|
48745
|
+
payload: `jsonb_build_object('organizationId', ${row}.${q.k("tenant")}, 'id', ${row}.${q.k("id")}, 'courseId', ${row}.${q.k("course")}, 'userId', ${row}.${q.k("user")}, 'enrollmentId', ${row}.${q.k("enrollment")}${extra})`,
|
|
48574
48746
|
subject: `'course-certificates/' || ${row}.${q.k("id")}::text`,
|
|
48575
48747
|
tenant: `${row}.${q.k("tenant")}`,
|
|
48576
48748
|
audit: {
|
|
@@ -48585,6 +48757,7 @@ function courseAuthoringFunctions(ctx) {
|
|
|
48585
48757
|
const lessonJson = (row) => `jsonb_build_object('id', ${row}.${l("id")}, 'courseId', ${row}.${l("course")}, 'moduleId', ${row}.${l("module")}, 'title', ${row}.${l("title")}, 'kind', ${row}.${l("kind")}, 'body', ${field("lessons", row, "body")}, 'mediaUrl', ${field("lessons", row, "mediaUrl")}, 'formId', ${row}.${l("form")}, 'required', ${row}.${l("required")}, 'minutes', ${field("lessons", row, "minutes")}, 'rank', ${row}.${l("rank")}, 'createdAt', ${field("lessons", row, "createdAt")}, 'updatedAt', ${field("lessons", row, "updatedAt")})`;
|
|
48586
48758
|
/** `, <column> = now()` when `table` has its updatedAt column. */
|
|
48587
48759
|
const touched = (table) => ctx.has(table, "updatedAt") ? `, ${ctx.col(table, "updatedAt")} = now()` : "";
|
|
48760
|
+
const expires = ctx.has("certificates", "expiresAt");
|
|
48588
48761
|
const touchCourse = ctx.has("courses", "updatedAt") ? `\n update ${q.courses} x set ${c("updatedAt")} = now() where x.${c("id")} = v_course.${c("id")};` : "";
|
|
48589
48762
|
const courseInsert = [
|
|
48590
48763
|
["tenant", "save_course.tenant"],
|
|
@@ -48593,6 +48766,7 @@ function courseAuthoringFunctions(ctx) {
|
|
|
48593
48766
|
["summary", "v_summary"],
|
|
48594
48767
|
["status", ctx.cast("courses", "status", "v_status")],
|
|
48595
48768
|
["certificate", "v_certificate"],
|
|
48769
|
+
["validForMonths", "v_valid_for"],
|
|
48596
48770
|
["createdBy", "auth.uid()"]
|
|
48597
48771
|
].filter(([column]) => ctx.has("courses", column));
|
|
48598
48772
|
const lessonWrite = [
|
|
@@ -48652,7 +48826,7 @@ declare
|
|
|
48652
48826
|
v_enrollment record;
|
|
48653
48827
|
v_certificate ${q.certificates};
|
|
48654
48828
|
begin
|
|
48655
|
-
select x.${e("id")} as id, x.${e("tenant")} as tenant, x.${e("status")} as status, x.${e("user")} as learner, y.${c("id")} as course, ${field("courses", "y", "certificate", "true")} as certifies
|
|
48829
|
+
select x.${e("id")} as id, x.${e("tenant")} as tenant, x.${e("status")} as status, x.${e("user")} as learner, y.${c("id")} as course, ${field("courses", "y", "certificate", "true")} as certifies, ${field("courses", "y", "validForMonths")}::integer as valid_for
|
|
48656
48830
|
into v_enrollment
|
|
48657
48831
|
from ${q.enrollments} x join ${q.courses} y on ${q.program(`y.${c("id")}`)} = x.${e("program")}
|
|
48658
48832
|
where x.${e("id")} = course_finish.enrollment_id;
|
|
@@ -48663,12 +48837,12 @@ begin
|
|
|
48663
48837
|
${q.learnerRecord("course.completed", "completed a course")}
|
|
48664
48838
|
end if;
|
|
48665
48839
|
if v_enrollment.certifies then
|
|
48666
|
-
insert into ${q.certificates} (${q.k("tenant")}, ${q.k("course")}, ${q.k("enrollment")}, ${q.k("user")}, ${q.k("code")})
|
|
48667
|
-
values (v_enrollment.tenant, v_enrollment.course, v_enrollment.id, v_enrollment.learner, encode(extensions.gen_random_bytes(16), 'hex'))
|
|
48840
|
+
insert into ${q.certificates} (${q.k("tenant")}, ${q.k("course")}, ${q.k("enrollment")}, ${q.k("user")}, ${q.k("code")}${expires ? `, ${q.k("expiresAt")}` : ""})
|
|
48841
|
+
values (v_enrollment.tenant, v_enrollment.course, v_enrollment.id, v_enrollment.learner, encode(extensions.gen_random_bytes(16), 'hex')${expires ? ", now() + make_interval(months => v_enrollment.valid_for)" : ""})
|
|
48668
48842
|
on conflict ${q.certificateTarget} do nothing
|
|
48669
48843
|
returning * into v_certificate;
|
|
48670
48844
|
if v_certificate.${q.k("id")} is not null then
|
|
48671
|
-
${certificateRecord("course_certificate.issued", "v_certificate", "issued a course certificate")}
|
|
48845
|
+
${certificateRecord("course_certificate.issued", "v_certificate", "issued a course certificate", `, 'expiresAt', ${field("certificates", "v_certificate", "expiresAt")}`)}
|
|
48672
48846
|
end if;
|
|
48673
48847
|
end if;
|
|
48674
48848
|
end;
|
|
@@ -48707,7 +48881,8 @@ $$;
|
|
|
48707
48881
|
revoke execute on function ${fn("course_sync")}(uuid) from public, anon, authenticated;
|
|
48708
48882
|
|
|
48709
48883
|
-- Creates or changes a course. course is { id?, key, title, summary, status,
|
|
48710
|
-
-- certificate, fields }; keys left out keep their value.
|
|
48884
|
+
-- certificate, validForMonths, fields }; keys left out keep their value.
|
|
48885
|
+
-- validForMonths is how long a certificate stays valid; null never expires.
|
|
48711
48886
|
create or replace function ${fn("save_course")}(tenant ${idType}, course jsonb)
|
|
48712
48887
|
returns jsonb
|
|
48713
48888
|
language plpgsql
|
|
@@ -48724,6 +48899,7 @@ declare
|
|
|
48724
48899
|
v_summary text;
|
|
48725
48900
|
v_status text;
|
|
48726
48901
|
v_certificate boolean;
|
|
48902
|
+
v_valid_for integer;
|
|
48727
48903
|
begin
|
|
48728
48904
|
if not ${q.allowed("save_course.tenant", q.manage)} then
|
|
48729
48905
|
${q.forbidden("not allowed to manage courses")}
|
|
@@ -48743,6 +48919,18 @@ begin
|
|
|
48743
48919
|
v_summary := case when save_course.course ? 'summary' then nullif(trim(save_course.course ->> 'summary'), '') else ${field("courses", "v_old", "summary")} end;
|
|
48744
48920
|
v_status := coalesce(save_course.course ->> 'status', v_old.${c("status")}, 'draft');
|
|
48745
48921
|
v_certificate := case when save_course.course ? 'certificate' then (save_course.course ->> 'certificate')::boolean else coalesce(${field("courses", "v_old", "certificate")}, true) end;
|
|
48922
|
+
v_valid_for := ${field("courses", "v_old", "validForMonths")};
|
|
48923
|
+
if save_course.course ? 'validForMonths' then
|
|
48924
|
+
if jsonb_typeof(save_course.course -> 'validForMonths') = 'null' then
|
|
48925
|
+
v_valid_for := null;
|
|
48926
|
+
elsif jsonb_typeof(save_course.course -> 'validForMonths') <> 'number'
|
|
48927
|
+
or (save_course.course ->> 'validForMonths')::numeric % 1 <> 0
|
|
48928
|
+
or (save_course.course ->> 'validForMonths')::numeric not between 1 and 240 then
|
|
48929
|
+
${q.invalid("validForMonths must be a whole number of months from 1 to 240, or null")}
|
|
48930
|
+
else
|
|
48931
|
+
v_valid_for := (save_course.course ->> 'validForMonths')::integer;
|
|
48932
|
+
end if;
|
|
48933
|
+
end if;
|
|
48746
48934
|
if v_key is null or v_key !~ '^[a-z][a-z0-9-]{0,62}$' then
|
|
48747
48935
|
${q.invalid("key: use lowercase letters, digits or \"-\", starting with a letter")}
|
|
48748
48936
|
end if;
|
|
@@ -48766,7 +48954,7 @@ begin
|
|
|
48766
48954
|
else
|
|
48767
48955
|
begin
|
|
48768
48956
|
update ${q.courses} x
|
|
48769
|
-
set ${c("key")} = v_key, ${c("title")} = v_title,${ctx.has("courses", "summary") ? ` ${c("summary")} = v_summary,` : ""} ${c("status")} = ${ctx.cast("courses", "status", "v_status")}${ctx.has("courses", "certificate") ? `,\n ${c("certificate")} = v_certificate` : ""}${touched("courses")}
|
|
48957
|
+
set ${c("key")} = v_key, ${c("title")} = v_title,${ctx.has("courses", "summary") ? ` ${c("summary")} = v_summary,` : ""} ${c("status")} = ${ctx.cast("courses", "status", "v_status")}${ctx.has("courses", "certificate") ? `,\n ${c("certificate")} = v_certificate` : ""}${ctx.has("courses", "validForMonths") ? `,\n ${c("validForMonths")} = v_valid_for` : ""}${touched("courses")}
|
|
48770
48958
|
where x.${c("id")} = v_old.${c("id")}
|
|
48771
48959
|
returning * into v_row;
|
|
48772
48960
|
exception when unique_violation then
|
|
@@ -49156,7 +49344,9 @@ function courseLearningFunctions(ctx) {
|
|
|
49156
49344
|
or exists (select 1 from ${q.enrollments} y where y.${e("tenant")} = ${course}.${c("tenant")} and y.${e("program")} = ${q.program(`${course}.${c("id")}`)}
|
|
49157
49345
|
and y.${e("subjectType")} = 'user' and y.${e("subjectId")} = auth.uid()::text and y.${e("status")} <> 'cancelled'))`;
|
|
49158
49346
|
const entryJson = (row) => `jsonb_build_object('lessonId', ${row}.${p("lesson")}, 'startedAt', ${field("progress", row, "startedAt")}, 'completedAt', ${row}.${p("completedAt")}, 'attempts', ${row}.${p("attempts")}, 'submissionId', ${field("progress", row, "submission")}, 'score', ${field("progress", row, "score")}, 'maxScore', ${field("progress", row, "maxScore")}, 'passed', ${field("progress", row, "passed")})`;
|
|
49159
|
-
const certificateJson = (row) => `jsonb_build_object('id', ${row}.${k("id")}, 'courseId', ${row}.${k("course")}, 'userId', ${row}.${k("user")}, 'code', ${row}.${k("code")}, 'issuedAt', ${field("certificates", row, "issuedAt")}, 'revokedAt', ${row}.${k("revokedAt")})`;
|
|
49347
|
+
const certificateJson = (row) => `jsonb_build_object('id', ${row}.${k("id")}, 'courseId', ${row}.${k("course")}, 'userId', ${row}.${k("user")}, 'code', ${row}.${k("code")}, 'issuedAt', ${field("certificates", row, "issuedAt")}, 'expiresAt', ${field("certificates", row, "expiresAt")}, 'revokedAt', ${row}.${k("revokedAt")})`;
|
|
49348
|
+
const expiresAt = field("certificates", "z", "expiresAt");
|
|
49349
|
+
const expired = ctx.has("certificates", "expiresAt") ? `coalesce(${expiresAt} <= now(), false)` : "false";
|
|
49160
49350
|
const enrollmentOf = (course, user) => `select * into v_row from ${q.enrollments} x
|
|
49161
49351
|
where x.${e("tenant")} = ${course}.${c("tenant")} and x.${e("program")} = ${q.program(`${course}.${c("id")}`)}
|
|
49162
49352
|
and x.${e("subjectType")} = 'user' and x.${e("subjectId")} = ${user}::text`;
|
|
@@ -49537,8 +49727,8 @@ $$;
|
|
|
49537
49727
|
${userGrant(`${fn("list_course_learners")}(uuid, text, integer, timestamptz)`)}
|
|
49538
49728
|
|
|
49539
49729
|
-- Checks a certificate by the code its link carries. Anyone with the code
|
|
49540
|
-
-- learns the course, when it was issued and whether it was
|
|
49541
|
-
-- an unknown code.
|
|
49730
|
+
-- learns the course, when it was issued, when it expires and whether it was
|
|
49731
|
+
-- revoked; null for an unknown code. An expired certificate is not valid.
|
|
49542
49732
|
create or replace function ${fn("verify_course_certificate")}(code text)
|
|
49543
49733
|
returns jsonb
|
|
49544
49734
|
language sql
|
|
@@ -49547,7 +49737,8 @@ security definer
|
|
|
49547
49737
|
set search_path = ''
|
|
49548
49738
|
as $$
|
|
49549
49739
|
select jsonb_build_object('id', z.${k("id")}, 'courseId', z.${k("course")}, 'courseTitle', y.${c("title")}, 'organizationId', z.${k("tenant")},
|
|
49550
|
-
'issuedAt', ${field("certificates", "z", "issuedAt")}, '
|
|
49740
|
+
'issuedAt', ${field("certificates", "z", "issuedAt")}, 'expiresAt', ${expiresAt}, 'revokedAt', z.${k("revokedAt")},
|
|
49741
|
+
'expired', ${expired}, 'valid', z.${k("revokedAt")} is null and not ${expired})
|
|
49551
49742
|
from ${q.certificates} z join ${q.courses} y on y.${c("id")} = z.${k("course")}
|
|
49552
49743
|
where z.${k("code")} = lower(verify_course_certificate.code)
|
|
49553
49744
|
$$;
|
|
@@ -49633,7 +49824,7 @@ const NAMES$84 = {
|
|
|
49633
49824
|
},
|
|
49634
49825
|
"course_certificate.issued": {
|
|
49635
49826
|
subject: "course-certificates",
|
|
49636
|
-
payload: COURSE_ITEM_PAYLOAD
|
|
49827
|
+
payload: [...COURSE_ITEM_PAYLOAD, "expiresAt"]
|
|
49637
49828
|
},
|
|
49638
49829
|
"course_certificate.revoked": {
|
|
49639
49830
|
subject: "course-certificates",
|
|
@@ -49653,6 +49844,7 @@ const NAMES$84 = {
|
|
|
49653
49844
|
optional: [
|
|
49654
49845
|
"summary",
|
|
49655
49846
|
"certificate",
|
|
49847
|
+
"validForMonths",
|
|
49656
49848
|
"createdBy",
|
|
49657
49849
|
"createdAt",
|
|
49658
49850
|
"updatedAt"
|
|
@@ -49666,6 +49858,7 @@ const NAMES$84 = {
|
|
|
49666
49858
|
summary: "summary",
|
|
49667
49859
|
status: "status",
|
|
49668
49860
|
certificate: "issues_certificate",
|
|
49861
|
+
validForMonths: "valid_for_months",
|
|
49669
49862
|
createdBy: "created_by",
|
|
49670
49863
|
createdAt: "created_at",
|
|
49671
49864
|
updatedAt: "updated_at"
|
|
@@ -49761,7 +49954,7 @@ const NAMES$84 = {
|
|
|
49761
49954
|
user: "user",
|
|
49762
49955
|
export: true
|
|
49763
49956
|
},
|
|
49764
|
-
optional: ["issuedAt"],
|
|
49957
|
+
optional: ["issuedAt", "expiresAt"],
|
|
49765
49958
|
columns: {
|
|
49766
49959
|
id: "id",
|
|
49767
49960
|
tenant: "tenant_id",
|
|
@@ -49770,6 +49963,7 @@ const NAMES$84 = {
|
|
|
49770
49963
|
user: "user_id",
|
|
49771
49964
|
code: "code",
|
|
49772
49965
|
issuedAt: "issued_at",
|
|
49966
|
+
expiresAt: "expires_at",
|
|
49773
49967
|
revokedAt: "revoked_at"
|
|
49774
49968
|
}
|
|
49775
49969
|
}
|
|
@@ -49796,6 +49990,9 @@ function courseTables(ctx) {
|
|
|
49796
49990
|
const extras = ctx.extraColumns("courses", COURSE_KEYS);
|
|
49797
49991
|
const name = (logical, suffix) => sqlIdent(`${ctx.tableName(logical).name}_${suffix}`);
|
|
49798
49992
|
const optional = (table, column, definition) => ctx.has(table, column) ? `\n ${definition(ctx.col(table, column))},` : "";
|
|
49993
|
+
const added = (table, column, definition) => ctx.has(table, column) ? `\nalter table ${ctx.table(table)} add column if not exists ${definition(ctx.col(table, column))};` : "";
|
|
49994
|
+
const validFor = (x) => `${x} integer check (${x} is null or ${x} between 1 and 240)`;
|
|
49995
|
+
const expires = (x) => `${x} timestamptz`;
|
|
49799
49996
|
const stamps = (table) => ["createdAt", "updatedAt"].filter((column) => ctx.has(table, column)).map((column) => `,\n ${ctx.col(table, column)} timestamptz not null default now()`).join("");
|
|
49800
49997
|
const key = (logical, suffix, columns) => ctx.owns(logical) ? "" : `\ncreate unique index if not exists ${sqlIdent(`bsb_${ctx.tableName(logical).name}_${suffix}`)} on ${ctx.table(logical)} (${columns});`;
|
|
49801
49998
|
return `create table if not exists ${courses} (
|
|
@@ -49803,9 +50000,9 @@ function courseTables(ctx) {
|
|
|
49803
50000
|
${c("tenant")} ${ctx.idType} not null,
|
|
49804
50001
|
${c("key")} text not null check (${c("key")} ~ '^[a-z][a-z0-9-]{0,62}$'),
|
|
49805
50002
|
${c("title")} text not null check (length(${c("title")}) between 1 and 200),${optional("courses", "summary", (x) => `${x} text check (${x} is null or length(${x}) <= 2000)`)}
|
|
49806
|
-
${c("status")} text not null default 'draft' check (${c("status")} in ('draft', 'published', 'archived')),${optional("courses", "certificate", (x) => `${x} boolean not null default true`)}${optional("courses", "createdBy", (x) => `${x} uuid`)}${optional("courses", "createdAt", (x) => `${x} timestamptz not null default now()`)}${optional("courses", "updatedAt", (x) => `${x} timestamptz not null default now()`)}
|
|
50003
|
+
${c("status")} text not null default 'draft' check (${c("status")} in ('draft', 'published', 'archived')),${optional("courses", "certificate", (x) => `${x} boolean not null default true`)}${optional("courses", "validForMonths", validFor)}${optional("courses", "createdBy", (x) => `${x} uuid`)}${optional("courses", "createdAt", (x) => `${x} timestamptz not null default now()`)}${optional("courses", "updatedAt", (x) => `${x} timestamptz not null default now()`)}
|
|
49807
50004
|
unique (${c("tenant")}, ${c("key")})
|
|
49808
|
-
);${key("courses", "key_key", `${c("tenant")}, ${c("key")}`)}${addExtraColumns(courses, extras)}
|
|
50005
|
+
);${key("courses", "key_key", `${c("tenant")}, ${c("key")}`)}${added("courses", "validForMonths", validFor)}${addExtraColumns(courses, extras)}
|
|
49809
50006
|
|
|
49810
50007
|
create table if not exists ${modules} (
|
|
49811
50008
|
${m("id")} uuid primary key default gen_random_uuid(),
|
|
@@ -49863,10 +50060,10 @@ create table if not exists ${certificates} (
|
|
|
49863
50060
|
${k("course")} uuid not null references ${courses} (${c("id")}) on delete cascade,
|
|
49864
50061
|
${k("enrollment")} uuid not null references ${enrollments} (${enrollmentId}) on delete cascade,
|
|
49865
50062
|
${k("user")} uuid not null references auth.users (id) on delete cascade,
|
|
49866
|
-
${k("code")} text not null unique check (${k("code")} ~ '^[0-9a-f]{32}$'),${optional("certificates", "issuedAt", (x) => `${x} timestamptz not null default now()`)}
|
|
50063
|
+
${k("code")} text not null unique check (${k("code")} ~ '^[0-9a-f]{32}$'),${optional("certificates", "issuedAt", (x) => `${x} timestamptz not null default now()`)}${optional("certificates", "expiresAt", expires)}
|
|
49867
50064
|
${k("revokedAt")} timestamptz,
|
|
49868
50065
|
constraint ${name("certificates", "enrollment_key")} unique (${k("enrollment")})
|
|
49869
|
-
);${key("certificates", "enrollment_key", k("enrollment"))}
|
|
50066
|
+
);${key("certificates", "enrollment_key", k("enrollment"))}${added("certificates", "expiresAt", expires)}
|
|
49870
50067
|
create index if not exists ${name("certificates", "parent_idx")} on ${certificates} (${k("course")});
|
|
49871
50068
|
create index if not exists ${name("certificates", "user_idx")} on ${certificates} (${k("user")});
|
|
49872
50069
|
|
|
@@ -50114,6 +50311,79 @@ $$;
|
|
|
50114
50311
|
revoke execute on function better_supabase.token_scope_allows(text) from public;
|
|
50115
50312
|
grant execute on function better_supabase.token_scope_allows(text) to anon, authenticated, service_role;`
|
|
50116
50313
|
};
|
|
50314
|
+
// src/sql/format-checks.ts
|
|
50315
|
+
/** `<schema>.bsb_valid_<name>`, quoted. */
|
|
50316
|
+
function validatorFunction(schema, validator) {
|
|
50317
|
+
return `${sqlIdent(schema)}.${sqlIdent(`bsb_valid_${validator}`)}`;
|
|
50318
|
+
}
|
|
50319
|
+
/** The validators the formats in `formats` need, in a fixed order. */
|
|
50320
|
+
function validatorsOf(formats) {
|
|
50321
|
+
const used = /* @__PURE__ */ new Set();
|
|
50322
|
+
for (const format of formats) {
|
|
50323
|
+
const validator = format === void 0 ? void 0 : FIELD_FORMATS[format].validator;
|
|
50324
|
+
if (validator !== void 0) used.add(validator);
|
|
50325
|
+
}
|
|
50326
|
+
return FIELD_FORMAT_VALIDATORS.filter((validator) => used.has(validator));
|
|
50327
|
+
}
|
|
50328
|
+
/**
|
|
50329
|
+
* The SQL conditions a `format` puts on the text expression `ident`: its
|
|
50330
|
+
* pattern and its validator in `schema`. Bounds are the caller's.
|
|
50331
|
+
*/
|
|
50332
|
+
function formatConditions(format, ident, schema) {
|
|
50333
|
+
const spec = FIELD_FORMATS[format];
|
|
50334
|
+
return [...spec.pattern === void 0 ? [] : [`${ident} ~* ${sqlString(spec.pattern)}`], ...spec.validator === void 0 ? [] : [`${validatorFunction(schema, spec.validator)}(${ident})`]];
|
|
50335
|
+
}
|
|
50336
|
+
/**
|
|
50337
|
+
* Whether the text `value` passes the format the custom field type `type`
|
|
50338
|
+
* checks (`CUSTOM_FIELD_CHECKED_FORMATS`); `true` for the other types, and not
|
|
50339
|
+
* false for a `null` value.
|
|
50340
|
+
*/
|
|
50341
|
+
function customFieldValueCheck(type, value, schema) {
|
|
50342
|
+
return `case ${type} ${Object.entries(CUSTOM_FIELD_CHECKED_FORMATS).map(([field, format]) => `when ${sqlString(field)} then ${formatConditions(format, value, schema).join(" and ")}`).join(" ")} else true end`;
|
|
50343
|
+
}
|
|
50344
|
+
/** The validators the checked custom field types call. */
|
|
50345
|
+
const CUSTOM_FIELD_VALIDATORS = validatorsOf(Object.values(CUSTOM_FIELD_CHECKED_FORMATS));
|
|
50346
|
+
function bodyOf(validator) {
|
|
50347
|
+
switch (validator) {
|
|
50348
|
+
case "bsn": return ` select case
|
|
50349
|
+
when value !~ '^[0-9]{9}$' or value = '000000000' then false
|
|
50350
|
+
else (
|
|
50351
|
+
select sum(substr(value, i, 1)::integer * case when i = 9 then -1 else 10 - i end)
|
|
50352
|
+
from generate_series(1, 9) as i
|
|
50353
|
+
) % 11 = 0
|
|
50354
|
+
end`;
|
|
50355
|
+
case "iban": return ` select case
|
|
50356
|
+
when value !~ '^[A-Z]{2}[0-9]{2}[A-Z0-9]{11,30}$' then false
|
|
50357
|
+
else (
|
|
50358
|
+
select string_agg(case when ascii(c.ch) between 65 and 90 then (ascii(c.ch) - 55)::text else c.ch end, '' order by c.n)
|
|
50359
|
+
from regexp_split_to_table(substr(value, 5) || substr(value, 1, 4), '') with ordinality as c(ch, n)
|
|
50360
|
+
)::numeric % 97 = 1
|
|
50361
|
+
end`;
|
|
50362
|
+
default: throw new TypeError(`Unknown format validator "${String(validator)}"`);
|
|
50363
|
+
}
|
|
50364
|
+
}
|
|
50365
|
+
/**
|
|
50366
|
+
* The `bsb_valid_<name>(value text)` functions of `validators` in `schema`:
|
|
50367
|
+
* immutable, `null` for `null`, callable by signed-in users and the service
|
|
50368
|
+
* role so a check constraint that calls one runs for them.
|
|
50369
|
+
*/
|
|
50370
|
+
function formatValidatorSql(schema, validators) {
|
|
50371
|
+
return validators.map((validator) => {
|
|
50372
|
+
const fn = validatorFunction(schema, validator);
|
|
50373
|
+
return `create or replace function ${fn}(value text)
|
|
50374
|
+
returns boolean
|
|
50375
|
+
language sql
|
|
50376
|
+
immutable
|
|
50377
|
+
strict
|
|
50378
|
+
parallel safe
|
|
50379
|
+
set search_path = ''
|
|
50380
|
+
as $$
|
|
50381
|
+
${bodyOf(validator)}
|
|
50382
|
+
$$;
|
|
50383
|
+
revoke execute on function ${fn}(text) from public, anon;
|
|
50384
|
+
grant execute on function ${fn}(text) to authenticated, service_role;`;
|
|
50385
|
+
}).join("\n");
|
|
50386
|
+
}
|
|
50117
50387
|
// src/sql/modules/custom-fields-keyed.ts
|
|
50118
50388
|
/** The value column each field type is stored in, when the table maps it. */
|
|
50119
50389
|
const VALUE_COLUMNS = {
|
|
@@ -50328,6 +50598,9 @@ begin
|
|
|
50328
50598
|
if coalesce(trim(${s("key")}), '') = '' or coalesce(trim(${s("label")}), '') = '' or v_type is null or v_type not in (${CUSTOM_FIELD_TYPES.map((type) => sqlString(type)).join(", ")}) then
|
|
50329
50599
|
${fail$1("FIELD_INVALID", "a field needs a key, a label and a known type", "22023")}
|
|
50330
50600
|
end if;
|
|
50601
|
+
if not (${customFieldValueCheck("v_type", `${s("value")} #>> '{}'`, ctx.schemaName)}) then
|
|
50602
|
+
${fail$1("FIELD_VALUE_INVALID", "the value doesn't match the field's format", "22023")}
|
|
50603
|
+
end if;
|
|
50331
50604
|
if not (${check(s("subject_type"), s("subject_id"), s("tenant"))}) then
|
|
50332
50605
|
${fail$1("FIELD_SUBJECT_FORBIDDEN", "not allowed to set fields on this record")}
|
|
50333
50606
|
end if;
|
|
@@ -50459,6 +50732,8 @@ const NAMES$83 = {
|
|
|
50459
50732
|
const FIELD_CIPHER_PREFIX = "bsf1:";
|
|
50460
50733
|
/** The Vault secret name prefix of a data key; the owner follows it. */
|
|
50461
50734
|
const FIELD_KEY_PREFIX = "bs:field-key:";
|
|
50735
|
+
/** The Vault secret name prefix of a lookup key; the owner follows it. */
|
|
50736
|
+
const FIELD_LOOKUP_KEY_PREFIX = "bs:field-lookup-key:";
|
|
50462
50737
|
/** The pgcrypto options: AES-256, and one S2K pass since the key is random. */
|
|
50463
50738
|
const CIPHER_OPTIONS = "cipher-algo=aes256, s2k-mode=1";
|
|
50464
50739
|
/** SQL that revokes a function from every API role, the service role too. */
|
|
@@ -50474,15 +50749,10 @@ function fieldKeyOwner(kind, column) {
|
|
|
50474
50749
|
}
|
|
50475
50750
|
function build$83(ctx) {
|
|
50476
50751
|
const fn = (name) => ctx.fn(name);
|
|
50477
|
-
const secret = (owner) => `'${
|
|
50478
|
-
|
|
50479
|
-
|
|
50480
|
-
|
|
50481
|
-
-- Field data keys live only in Vault, one per owner (tenant:<id>, user:<id>
|
|
50482
|
-
-- or app), as bs:field-key:<owner>. No API role calls field_key, field_seal
|
|
50483
|
-
-- or field_open; security definer functions of app tables and custom fields
|
|
50484
|
-
-- do, after they check the caller's scope.
|
|
50485
|
-
create or replace function ${fn("field_key")}(owner text, make boolean default true)
|
|
50752
|
+
const secret = (owner, prefix = FIELD_KEY_PREFIX) => `'${prefix}' || ${owner}`;
|
|
50753
|
+
const keyFunction = (name, prefix, label) => {
|
|
50754
|
+
const owner = `${name}.owner`;
|
|
50755
|
+
return `create or replace function ${fn(name)}(owner text, make boolean default true)
|
|
50486
50756
|
returns text
|
|
50487
50757
|
language plpgsql
|
|
50488
50758
|
security definer
|
|
@@ -50491,25 +50761,37 @@ as $$
|
|
|
50491
50761
|
declare
|
|
50492
50762
|
v_key text;
|
|
50493
50763
|
begin
|
|
50494
|
-
if
|
|
50764
|
+
if ${owner} is null or length(${owner}) = 0 then
|
|
50495
50765
|
${fail$1("FIELD_KEY_OWNER", "a field key needs an owner", "22023")}
|
|
50496
50766
|
end if;
|
|
50497
50767
|
select ds.decrypted_secret into v_key from vault.decrypted_secrets ds
|
|
50498
|
-
where ds.name = ${secret(
|
|
50499
|
-
if v_key is not null or not
|
|
50768
|
+
where ds.name = ${secret(owner, prefix)};
|
|
50769
|
+
if v_key is not null or not ${name}.make then
|
|
50500
50770
|
return v_key;
|
|
50501
50771
|
end if;
|
|
50502
|
-
perform pg_advisory_xact_lock(hashtextextended(${secret(
|
|
50772
|
+
perform pg_advisory_xact_lock(hashtextextended(${secret(owner, prefix)}, 0));
|
|
50503
50773
|
select ds.decrypted_secret into v_key from vault.decrypted_secrets ds
|
|
50504
|
-
where ds.name = ${secret(
|
|
50774
|
+
where ds.name = ${secret(owner, prefix)};
|
|
50505
50775
|
if v_key is null then
|
|
50506
50776
|
v_key := encode(extensions.gen_random_bytes(32), 'base64');
|
|
50507
|
-
perform vault.create_secret(v_key, ${secret(
|
|
50777
|
+
perform vault.create_secret(v_key, ${secret(owner, prefix)}, '${label}');
|
|
50508
50778
|
end if;
|
|
50509
50779
|
return v_key;
|
|
50510
50780
|
end;
|
|
50511
50781
|
$$;
|
|
50512
|
-
${privateGrant(`${fn(
|
|
50782
|
+
${privateGrant(`${fn(name)}(text, boolean)`)}`;
|
|
50783
|
+
};
|
|
50784
|
+
return `${schemaPreamble(ctx)}
|
|
50785
|
+
create extension if not exists pgcrypto with schema extensions;
|
|
50786
|
+
|
|
50787
|
+
-- Field data keys live only in Vault, one per owner (tenant:<id>, user:<id>
|
|
50788
|
+
-- or app), as bs:field-key:<owner>, and the lookup keys next to them as
|
|
50789
|
+
-- bs:field-lookup-key:<owner>. No API role calls field_key, field_lookup_key,
|
|
50790
|
+
-- field_seal, field_open or field_hash; security definer functions of app
|
|
50791
|
+
-- tables and custom fields do, after they check the caller's scope.
|
|
50792
|
+
${keyFunction("field_key", FIELD_KEY_PREFIX, "better-supabase field encryption key")}
|
|
50793
|
+
|
|
50794
|
+
${keyFunction("field_lookup_key", FIELD_LOOKUP_KEY_PREFIX, "better-supabase field lookup key")}
|
|
50513
50795
|
|
|
50514
50796
|
-- Encrypts a value with a data key: ${FIELD_CIPHER_PREFIX} then base64 of an OpenPGP message.
|
|
50515
50797
|
create or replace function ${fn("field_seal")}(key text, value text)
|
|
@@ -50541,6 +50823,20 @@ as $$
|
|
|
50541
50823
|
$$;
|
|
50542
50824
|
${privateGrant(`${fn("field_open")}(text, text)`)}
|
|
50543
50825
|
|
|
50826
|
+
-- The lookup hash of a value: HMAC-SHA256 of the value, lowercased and
|
|
50827
|
+
-- without whitespace, under a lookup key. null without a key or a value.
|
|
50828
|
+
create or replace function ${fn("field_hash")}(key text, value text)
|
|
50829
|
+
returns bytea
|
|
50830
|
+
language sql
|
|
50831
|
+
immutable
|
|
50832
|
+
set search_path = ''
|
|
50833
|
+
as $$
|
|
50834
|
+
select case when field_hash.key is null or field_hash.value is null then null
|
|
50835
|
+
else extensions.hmac(convert_to(lower(regexp_replace(field_hash.value, '\\s', '', 'g')), 'UTF8'), decode(field_hash.key, 'base64'), 'sha256')
|
|
50836
|
+
end
|
|
50837
|
+
$$;
|
|
50838
|
+
${privateGrant(`${fn("field_hash")}(text, text)`)}
|
|
50839
|
+
|
|
50544
50840
|
-- Encrypts a value with the owner's key, creating the key on first use.
|
|
50545
50841
|
create or replace function ${fn("field_encrypt")}(owner text, value text)
|
|
50546
50842
|
returns text
|
|
@@ -50573,8 +50869,27 @@ end;
|
|
|
50573
50869
|
$$;
|
|
50574
50870
|
${serviceGrant(`${fn("field_decrypt")}(text, text)`)}
|
|
50575
50871
|
|
|
50576
|
-
--
|
|
50577
|
-
--
|
|
50872
|
+
-- The lookup hash of a value under the owner's lookup key, to compare with a
|
|
50873
|
+
-- <column>_lookup column; null when the owner has no lookup key.
|
|
50874
|
+
create or replace function ${fn("field_lookup")}(owner text, value text)
|
|
50875
|
+
returns bytea
|
|
50876
|
+
language plpgsql
|
|
50877
|
+
stable
|
|
50878
|
+
security definer
|
|
50879
|
+
set search_path = ''
|
|
50880
|
+
as $$
|
|
50881
|
+
begin
|
|
50882
|
+
if field_lookup.value is null then
|
|
50883
|
+
return null;
|
|
50884
|
+
end if;
|
|
50885
|
+
return ${fn("field_hash")}(${fn("field_lookup_key")}(field_lookup.owner, false), field_lookup.value);
|
|
50886
|
+
end;
|
|
50887
|
+
$$;
|
|
50888
|
+
${serviceGrant(`${fn("field_lookup")}(text, text)`)}
|
|
50889
|
+
|
|
50890
|
+
-- Deletes an owner's data key and lookup key, so every value encrypted with
|
|
50891
|
+
-- them reads as null and no lookup finds it (crypto-shredding, for example
|
|
50892
|
+
-- after a tenant is erased).
|
|
50578
50893
|
create or replace function ${fn("drop_field_key")}(owner text)
|
|
50579
50894
|
returns boolean
|
|
50580
50895
|
language plpgsql
|
|
@@ -50585,7 +50900,7 @@ begin
|
|
|
50585
50900
|
if not (${SERVICE_CALLER$1}) then
|
|
50586
50901
|
${fail$1("FIELD_KEY_FORBIDDEN", "only the service role drops field keys")}
|
|
50587
50902
|
end if;
|
|
50588
|
-
delete from vault.secrets s where s.name
|
|
50903
|
+
delete from vault.secrets s where s.name in (${secret("drop_field_key.owner")}, ${secret("drop_field_key.owner", FIELD_LOOKUP_KEY_PREFIX)});
|
|
50589
50904
|
if not found then
|
|
50590
50905
|
return false;
|
|
50591
50906
|
end if;
|
|
@@ -50616,6 +50931,11 @@ function contract$75() {
|
|
|
50616
50931
|
args: ["text", "text"],
|
|
50617
50932
|
returns: "text"
|
|
50618
50933
|
},
|
|
50934
|
+
{
|
|
50935
|
+
name: "field_lookup",
|
|
50936
|
+
args: ["text", "text"],
|
|
50937
|
+
returns: "bytea"
|
|
50938
|
+
},
|
|
50619
50939
|
{
|
|
50620
50940
|
name: "drop_field_key",
|
|
50621
50941
|
args: ["text"],
|
|
@@ -50626,7 +50946,7 @@ function contract$75() {
|
|
|
50626
50946
|
const FIELD_ENCRYPTION = {
|
|
50627
50947
|
name: "field-encryption",
|
|
50628
50948
|
title: "Field encryption",
|
|
50629
|
-
description: "Encrypts app table columns and custom field values at rest with a data key per tenant, user or app, kept in Supabase Vault as bs:field-key:<owner>. Only security definer read paths that check the caller's scope decrypt; drop_field_key deletes
|
|
50949
|
+
description: "Encrypts app table columns and custom field values at rest with a data key per tenant, user or app, kept in Supabase Vault as bs:field-key:<owner>. Only security definer read paths that check the caller's scope decrypt; a lookup column keeps an HMAC of the value under the owner's lookup key for equality searches; drop_field_key deletes both keys so the values can no longer be read or found.",
|
|
50630
50950
|
requires: [],
|
|
50631
50951
|
target: "schema",
|
|
50632
50952
|
modes: ["managed"],
|
|
@@ -50640,7 +50960,10 @@ const FIELD_ENCRYPTION = {
|
|
|
50640
50960
|
const ENCRYPTABLE_TYPES = [
|
|
50641
50961
|
"text",
|
|
50642
50962
|
"email",
|
|
50643
|
-
"url"
|
|
50963
|
+
"url",
|
|
50964
|
+
"bsn",
|
|
50965
|
+
"iban",
|
|
50966
|
+
"phone_e164"
|
|
50644
50967
|
];
|
|
50645
50968
|
const NAMES$82 = {
|
|
50646
50969
|
entities: { field: {
|
|
@@ -50787,6 +51110,7 @@ function build$82(ctx) {
|
|
|
50787
51110
|
const manageKey = ctx.permission("manage", OPERATIONS["custom-fields.manage"]);
|
|
50788
51111
|
const { rankType, readAccess } = keyedOptions(ctx);
|
|
50789
51112
|
if (layout === "keyed") return `${schemaPreamble(ctx)}
|
|
51113
|
+
${formatValidatorSql(ctx.schemaName, CUSTOM_FIELD_VALIDATORS)}
|
|
50790
51114
|
${keyedFields(ctx, {
|
|
50791
51115
|
manage: manageKey,
|
|
50792
51116
|
read: ctx.permission("read", OPERATIONS["custom-fields.read"])
|
|
@@ -50846,7 +51170,7 @@ ${inline || !ctx.has("values", "definition") ? "" : `create index if not exists
|
|
|
50846
51170
|
const visible = inline ? "true" : `not coalesce(d.${ctx.col("definitions", "sensitive")}, false)
|
|
50847
51171
|
or ${ctx.scope.can(`v.${ctx.col("values", "tenant")}`, `coalesce(d.${ctx.col("definitions", "permission")}, ${sensitive})`)}`;
|
|
50848
51172
|
return `${schemaPreamble(ctx)}
|
|
50849
|
-
-- A sensitive value is returned only when the caller holds the field's
|
|
51173
|
+
${inline ? "" : `${formatValidatorSql(ctx.schemaName, CUSTOM_FIELD_VALIDATORS)}\n`}-- A sensitive value is returned only when the caller holds the field's
|
|
50850
51174
|
-- permission, or custom_fields.sensitive.read when the field names none.
|
|
50851
51175
|
${tables}
|
|
50852
51176
|
create or replace function ${ctx.fn("save_field_definition")}(tenant ${ctx.idType}, entity text, key text, label text, type text, sensitive boolean)
|
|
@@ -50937,6 +51261,9 @@ begin
|
|
|
50937
51261
|
end if;${subjectWrite === void 0 ? "" : `
|
|
50938
51262
|
if not ${subjectWrite} then
|
|
50939
51263
|
${fail$1("FIELD_SUBJECT_FORBIDDEN", "not allowed to set fields on this record")}
|
|
51264
|
+
end if;`}${inline ? "" : `
|
|
51265
|
+
if exists (select 1 from ${definitions} d where d.${ctx.col("definitions", "id")} = set_field_value.definition and not (${customFieldValueCheck(`d.${ctx.col("definitions", "type")}`, "set_field_value.value", ctx.schemaName)})) then
|
|
51266
|
+
${fail$1("FIELD_VALUE_INVALID", "the value doesn't match the field's format", "22023")}
|
|
50940
51267
|
end if;`}
|
|
50941
51268
|
insert into ${values} (${ctx.col("values", "tenant")}, ${ctx.has("values", "definition") && !inline ? `${ctx.col("values", "definition")}, ` : ""}${ctx.col("values", "subjectType")}, ${ctx.col("values", "subjectId")}, ${ctx.col("values", "valueText")})
|
|
50942
51269
|
values (set_field_value.tenant, ${ctx.has("values", "definition") && !inline ? "set_field_value.definition, " : ""}set_field_value.subject_type, set_field_value.subject_id, ${encrypted === "" ? "set_field_value.value" : `case when exists (select 1 from ${definitions} d where d.${ctx.col("definitions", "id")} = set_field_value.definition and d.${ctx.col("definitions", "encrypted")}) then ${encryption?.fn("field_encrypt")}('tenant:' || set_field_value.tenant::text, set_field_value.value) else set_field_value.value end`})
|
|
@@ -53106,7 +53433,7 @@ function lineItemsSql(ctx, items, options) {
|
|
|
53106
53433
|
["selected", "coalesce((x.value ->> 'selected')::boolean, not coalesce((x.value ->> 'optional')::boolean, false))"],
|
|
53107
53434
|
["periods", "coalesce((x.value ->> 'periods')::integer, 1)"],
|
|
53108
53435
|
["position", "x.ordinality::integer"]
|
|
53109
|
-
].filter(([column]) => has(column)).map(([column, value]) => [column, column === "productType" ? ctx.cast(items.lines, column, value) : RATE_COLUMNS.has(column) && percentRates(ctx, items.lines) ? `(${value} / 100.0)` : value]);
|
|
53436
|
+
].filter(([column]) => has(column)).map(([column, value]) => [column, column === "productType" ? ctx.cast(items.lines, column, value) : column === "productId" && !replaces ? asColumnType(t, ctx.colName(items.lines, column), value) : RATE_COLUMNS.has(column) && percentRates(ctx, items.lines) ? `(${value} / 100.0)` : value]);
|
|
53110
53437
|
const extras = items.extras ?? [];
|
|
53111
53438
|
const extrasInsert = insertExtraColumns(t, extras, "(case when jsonb_typeof(x.value -> 'fields') = 'object' then x.value -> 'fields' end)");
|
|
53112
53439
|
const manages = ctx.manages ? `create table if not exists ${t} (
|
|
@@ -53304,11 +53631,12 @@ function totalColumnsSql(ctx, table) {
|
|
|
53304
53631
|
* of them the plain line sums stay, so deals and invoices render as before.
|
|
53305
53632
|
*/
|
|
53306
53633
|
function documentTotals(ctx, items) {
|
|
53634
|
+
const parentHas = items.parentHas ?? ((column) => declared(ctx, items.parent, column));
|
|
53307
53635
|
return [
|
|
53308
53636
|
"pricesIncludeTax",
|
|
53309
53637
|
"discountBps",
|
|
53310
53638
|
"discountAmount"
|
|
53311
|
-
].some(
|
|
53639
|
+
].some(parentHas) || declared(ctx, items.lines, "optional") || items.taxLines !== void 0 && ctx.hasTable(items.taxLines);
|
|
53312
53640
|
}
|
|
53313
53641
|
/**
|
|
53314
53642
|
* The recount of a record whose totals follow its tax rates.
|
|
@@ -53327,7 +53655,7 @@ function documentRecountSql(ctx, items, options) {
|
|
|
53327
53655
|
const c = (column) => ctx.col(items.lines, column);
|
|
53328
53656
|
const pc = (column) => ctx.col(items.parent, column);
|
|
53329
53657
|
const l = (column) => lineColumn(ctx, items.lines, "l", column);
|
|
53330
|
-
const parentHas = (column) => declared(ctx, items.parent, column);
|
|
53658
|
+
const parentHas = items.parentHas ?? ((column) => declared(ctx, items.parent, column));
|
|
53331
53659
|
const parent = `${options.setter}_recount.parent`;
|
|
53332
53660
|
const amount = lineAmount(ctx, items.lines, "l");
|
|
53333
53661
|
const discount = declared(ctx, items.lines, "discountBps") ? `round(${amount} * ${l("discountBps")} / 10000.0)` : "0";
|
|
@@ -62371,9 +62699,22 @@ function hiringCandidate(hiring, row) {
|
|
|
62371
62699
|
};
|
|
62372
62700
|
}
|
|
62373
62701
|
// src/sql/modules/quotes-kit.ts
|
|
62374
|
-
/**
|
|
62702
|
+
/**
|
|
62703
|
+
* How the quotes table holds a company or contact: a type and an id column
|
|
62704
|
+
* (`pair`), only an id column of the fixed type `options.company` or `contact`,
|
|
62705
|
+
* such as a foreign key to the app's customers (`fixed`), or not at all.
|
|
62706
|
+
*/
|
|
62375
62707
|
function quoteParty(ctx, party) {
|
|
62376
|
-
|
|
62708
|
+
if (!ctx.has("quotes", `${party}Id`)) return;
|
|
62709
|
+
return ctx.has("quotes", `${party}Type`) ? "pair" : "fixed";
|
|
62710
|
+
}
|
|
62711
|
+
/**
|
|
62712
|
+
* SQL for the type of a quote's company or contact under `prefix`: its type
|
|
62713
|
+
* column, or the fixed type when the id is set.
|
|
62714
|
+
*/
|
|
62715
|
+
function quotePartyType(ctx, party, prefix) {
|
|
62716
|
+
const at = (logical) => `${prefix}${ctx.col("quotes", logical)}`;
|
|
62717
|
+
return quoteParty(ctx, party) === "pair" ? at(`${party}Type`) : `(case when ${at(`${party}Id`)} is null then null else ${sqlString(ctx.text(party, party === "company" ? "company" : "person"))} end)`;
|
|
62377
62718
|
}
|
|
62378
62719
|
/** Whether the quotes table has both columns of the record it was made from. */
|
|
62379
62720
|
function quoteOrigin(ctx) {
|
|
@@ -62404,7 +62745,7 @@ function workingCopyOn(ctx) {
|
|
|
62404
62745
|
*/
|
|
62405
62746
|
function quoteGuest(ctx, n, prefix) {
|
|
62406
62747
|
const q = (column) => `${prefix}${n.c("quotes", column)}`;
|
|
62407
|
-
const checks = [ctx.scope.guest(q("tenant"), "'quote'", `${q("id")}::text`, "read"), ...["company", "contact"].filter((party) => quoteParty(ctx, party)).map((party) => ctx.scope.guestParty(q("tenant"),
|
|
62748
|
+
const checks = [ctx.scope.guest(q("tenant"), "'quote'", `${q("id")}::text`, "read"), ...["company", "contact"].filter((party) => quoteParty(ctx, party) !== void 0).map((party) => ctx.scope.guestParty(q("tenant"), quotePartyType(ctx, party, prefix), q(`${party}Id`)))].filter((check) => check !== "false");
|
|
62408
62749
|
return checks.length === 0 ? "false" : `(${ctx.is("quotes", "status", q("status"), ["draft"], true)} and (${checks.join(" or ")}))`;
|
|
62409
62750
|
}
|
|
62410
62751
|
function quoteKit(ctx, n) {
|
|
@@ -62424,7 +62765,7 @@ function quoteKit(ctx, n) {
|
|
|
62424
62765
|
if ${given} is not null then
|
|
62425
62766
|
${fail$1(`QUOTE_${thing}_UNSUPPORTED`, `this quotes table has no ${what}`, "22023")}
|
|
62426
62767
|
end if;`;
|
|
62427
|
-
const editable = (alias) => `(${n.service} or ${ctx.scope.can(`${alias}.${q("tenant")}`,
|
|
62768
|
+
const editable = (alias, key = n.write) => `(${n.service} or ${ctx.scope.can(`${alias}.${q("tenant")}`, key)})`;
|
|
62428
62769
|
const st = (value, labels, negate = false) => ctx.is("quotes", "status", value, labels, negate);
|
|
62429
62770
|
const sv = (label) => ctx.value("quotes", "status", label);
|
|
62430
62771
|
const viewed = ctx.appValues("quotes", "status", "viewed").length > 0;
|
|
@@ -62442,12 +62783,19 @@ function quoteKit(ctx, n) {
|
|
|
62442
62783
|
end if;` : " null;";
|
|
62443
62784
|
const workingCopy = workingCopyOn(ctx);
|
|
62444
62785
|
const versionLines = versionLinesOn(ctx);
|
|
62445
|
-
const
|
|
62786
|
+
const declined = n.resend ? [
|
|
62787
|
+
"rejected",
|
|
62788
|
+
"withdrawn",
|
|
62789
|
+
"expired"
|
|
62790
|
+
] : [];
|
|
62791
|
+
const openStatuses = workingCopy ? [
|
|
62446
62792
|
"draft",
|
|
62447
62793
|
"changes_requested",
|
|
62448
62794
|
"sent",
|
|
62449
|
-
"viewed"
|
|
62450
|
-
|
|
62795
|
+
"viewed",
|
|
62796
|
+
...declined
|
|
62797
|
+
] : ["draft", "changes_requested"];
|
|
62798
|
+
const open = (alias) => st(`${alias}.${q("status")}`, openStatuses);
|
|
62451
62799
|
const lineValue = (column) => lineColumn(ctx, "lines", "ql", column);
|
|
62452
62800
|
const documentLine = [
|
|
62453
62801
|
"section",
|
|
@@ -62455,7 +62803,8 @@ function quoteKit(ctx, n) {
|
|
|
62455
62803
|
"selected",
|
|
62456
62804
|
"periods"
|
|
62457
62805
|
].filter(lineHas).map((column) => `, ${sqlString(column)}, ql.${l(column)}`).join("");
|
|
62458
|
-
const
|
|
62806
|
+
const product = !lineHas("productType") && lineHas("productId") ? `case when ql.${l("productId")} is null then null else jsonb_build_object('type', null, 'id', ql.${l("productId")}) end` : `case when ${lineValue("productType")} is null then null else jsonb_build_object('type', ${lineValue("productType")}, 'id', ${lineValue("productId")}) end`;
|
|
62807
|
+
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', ${product}${lineFieldsJson("ql", n.lineExtras)}) order by ql.${l("position")}) from ${t("lines")} ql where ql.${l("parent")} = ${alias}.${q("id")}), '[]'::jsonb)`;
|
|
62459
62808
|
const tl = (column) => c("taxLines", column);
|
|
62460
62809
|
const taxLines = (alias) => ctx.hasTable("taxLines") ? `coalesce((select jsonb_agg(jsonb_build_object('taxRateBps', tl.${tl("taxRateBps")}, 'taxCode', ${ctx.has("taxLines", "taxCode") ? `tl.${tl("taxCode")}` : "null"}, 'net', tl.${tl("net")}::text, 'tax', tl.${tl("tax")}::text, 'gross', tl.${tl("gross")}::text, 'discount', ${ctx.has("taxLines", "discount") ? `tl.${tl("discount")}::text` : "'0'"}) order by tl.${tl("taxRateBps")}, ${ctx.has("taxLines", "taxCode") ? `tl.${tl("taxCode")}` : "1"} nulls first) from ${t("taxLines")} tl where tl.${tl("parent")} = ${alias}.${q("id")}), '[]'::jsonb)` : "'[]'::jsonb";
|
|
62461
62810
|
const int8Columns = [
|
|
@@ -62466,7 +62815,8 @@ function quoteKit(ctx, n) {
|
|
|
62466
62815
|
].filter(has);
|
|
62467
62816
|
const int8 = int8Columns.map(q);
|
|
62468
62817
|
const int8As = Object.fromEntries(int8Columns.map((logical) => [logical, (value) => `${value}::text`]));
|
|
62469
|
-
const
|
|
62818
|
+
const missingKeys = (alias) => `${["company", "contact"].filter((party) => quoteParty(ctx, party) === "fixed").map((party) => `, ${sqlString(`${party}_type`)}, ${quotePartyType(ctx, party, `${alias}.`)}`).join("")}${has("listTotal") ? "" : `, 'list_total', ${alias}.${q("subtotal")}::text`}${has("discountTotal") ? "" : ", 'discount_total', '0'"}`;
|
|
62819
|
+
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)}${missingKeys(alias)}${n.extras.length === 0 ? "" : `, 'fields', ${columnsObject(alias, n.extras.map((extra) => extra.name))}`})`;
|
|
62470
62820
|
const text = (alias, logical, otherwise) => has(logical) ? `${alias}.${q(logical)}::text` : otherwise;
|
|
62471
62821
|
const v = (column) => c("versions", column);
|
|
62472
62822
|
const vl = (column) => c("versionLines", column);
|
|
@@ -62485,17 +62835,37 @@ function quoteKit(ctx, n) {
|
|
|
62485
62835
|
'taxTotal', ${alias}.${q("taxTotal")}::text, 'total', ${alias}.${q("total")}::text,
|
|
62486
62836
|
'lines', ${version === void 0 ? withVersionLineIds(lines(alias), latestVersion(alias)) : withVersionLineIds(`coalesce(${version} -> 'lines', '[]'::jsonb)`, latestVersion(alias))},
|
|
62487
62837
|
'taxLines', ${version === void 0 ? taxLines(alias) : `coalesce(${version} -> 'taxLines', '[]'::jsonb)`})`;
|
|
62488
|
-
const checkParty = (kind, type, id, tenant) =>
|
|
62838
|
+
const checkParty = (kind, type, id, tenant) => {
|
|
62839
|
+
const party = kind === "COMPANY" ? "company" : "contact";
|
|
62840
|
+
const mode = kind === "COMPANY" ? company : contact;
|
|
62841
|
+
const fixed = party === "company" ? n.company : n.contact;
|
|
62842
|
+
if (mode === void 0) return refuse(false, id, kind, `${party} columns`);
|
|
62843
|
+
return `${mode === "fixed" ? `
|
|
62844
|
+
if ${id} is not null and ${type} is distinct from ${sqlString(fixed)} then
|
|
62845
|
+
${fail$1(`QUOTE_${kind}_UNSUPPORTED`, `this quotes table takes only a ${fixed} as the ${party}`, "22023")}
|
|
62846
|
+
end if;` : ""}
|
|
62489
62847
|
if ${id} is not null and not ${subjectInTenant(ctx, type, id, tenant)} then
|
|
62490
|
-
${fail$1(`QUOTE_${kind}_FORBIDDEN`, `the ${
|
|
62491
|
-
end if
|
|
62492
|
-
|
|
62848
|
+
${fail$1(`QUOTE_${kind}_FORBIDDEN`, `the ${party} is unknown or not readable in this organization`, "42501")}
|
|
62849
|
+
end if;`;
|
|
62850
|
+
};
|
|
62851
|
+
const partyFields = (party) => {
|
|
62852
|
+
const mode = quoteParty(ctx, party);
|
|
62853
|
+
if (mode === void 0) return [];
|
|
62854
|
+
return mode === "pair" ? [`${party}Type`, `${party}Id`] : [`${party}Id`];
|
|
62855
|
+
};
|
|
62856
|
+
const partyValues = (party, type, id) => {
|
|
62857
|
+
const mode = quoteParty(ctx, party);
|
|
62858
|
+
if (mode === "pair") return [`case when ${id} is null then null else ${type} end`, id];
|
|
62859
|
+
return mode === "fixed" ? [asColumnType(t("quotes"), ctx.colName("quotes", `${party}Id`), id)] : [];
|
|
62860
|
+
};
|
|
62861
|
+
const notifyOwner = (event) => ctx.installed("notifications") && ctx.flag("notifications", true) ? `
|
|
62493
62862
|
if v_row.${q("owner")} is not null then
|
|
62494
62863
|
${ctx.notify(`jsonb_build_object(
|
|
62495
62864
|
'type', ${sqlString(event)},
|
|
62496
62865
|
'tenant', v_row.${q("tenant")},
|
|
62497
62866
|
'subject_type', 'quote',
|
|
62498
62867
|
'subject_id', v_row.${q("id")}::text,
|
|
62868
|
+
'subject_label', v_row.${q("identifier")} || ' ' || v_row.${q("title")},
|
|
62499
62869
|
'summary', v_row.${q("identifier")} || ' ' || v_row.${q("title")},
|
|
62500
62870
|
'recipients', jsonb_build_array(v_row.${q("owner")}),
|
|
62501
62871
|
'key', ${sqlString(`${event}:`)} || v_row.${q("id")}::text,
|
|
@@ -62522,6 +62892,8 @@ function quoteKit(ctx, n) {
|
|
|
62522
62892
|
st,
|
|
62523
62893
|
sv,
|
|
62524
62894
|
open,
|
|
62895
|
+
openStatuses,
|
|
62896
|
+
declined,
|
|
62525
62897
|
lines,
|
|
62526
62898
|
taxLines,
|
|
62527
62899
|
row,
|
|
@@ -62532,9 +62904,11 @@ function quoteKit(ctx, n) {
|
|
|
62532
62904
|
workingCopy,
|
|
62533
62905
|
record,
|
|
62534
62906
|
checkParty,
|
|
62907
|
+
partyFields,
|
|
62908
|
+
partyValues,
|
|
62535
62909
|
notifyOwner,
|
|
62536
62910
|
markViewed,
|
|
62537
|
-
depositDue: has("depositDue") && (has("depositBps") || has("depositAmount")) ? `${q("depositDue")} = case${has("depositAmount") ? ` when x.${q("depositAmount")} is not null then least(greatest(${total}, 0), x.${q("depositAmount")})` : ""}${has("depositBps") ? ` when x.${q("depositBps")} is not null then round(${total} * x.${q("depositBps")} / 10000.0)::bigint` : ""} else 0 end` : void 0
|
|
62911
|
+
depositDue: !n.appTotals && has("depositDue") && (has("depositBps") || has("depositAmount")) ? `${q("depositDue")} = case${has("depositAmount") ? ` when x.${q("depositAmount")} is not null then least(greatest(${total}, 0), x.${q("depositAmount")})` : ""}${has("depositBps") ? ` when x.${q("depositBps")} is not null then round(${total} * x.${q("depositBps")} / 10000.0)::bigint` : ""} else 0 end` : void 0
|
|
62538
62912
|
};
|
|
62539
62913
|
}
|
|
62540
62914
|
// src/sql/modules/quotes-decisions.ts
|
|
@@ -62656,10 +63030,10 @@ function quoteDecisions(ctx, n, k) {
|
|
|
62656
63030
|
end if;` : ""}${selection(a.name)}
|
|
62657
63031
|
${ctx.hook("before_quote_accept", [["uuid", `v_row.${q("id")}`]])}
|
|
62658
63032
|
end if;
|
|
62659
|
-
update ${t("quotes")} x set ${q("status")} = ${ctx.cast("quotes", "status", `${a.name}.decision`)}, ${q("decidedAt")} = now(), ${q("decidedBy")} = nullif(trim(${a.by}), ''),
|
|
63033
|
+
${a.customer ? "" : `${transitionReasonSql(`${a.name}.note`)}\n `}update ${t("quotes")} x set ${q("status")} = ${ctx.cast("quotes", "status", `${a.name}.decision`)}, ${q("decidedAt")} = now(), ${q("decidedBy")} = nullif(trim(${a.by}), ''),
|
|
62660
63034
|
${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()
|
|
62661
63035
|
where x.${q("id")} = v_row.${q("id")}
|
|
62662
|
-
returning * into v_row
|
|
63036
|
+
returning * into v_row;${a.customer ? "" : `\n ${transitionReasonSql()}`}
|
|
62663
63037
|
case ${a.name}.decision
|
|
62664
63038
|
when 'accepted' then
|
|
62665
63039
|
${record("quote.accepted", "v_row", `, 'total', v_row.${q("total")}::text, 'currency', v_row.${q("currency")}, 'byName', v_row.${q("decidedBy")}, 'revision', v_row.${q("revision")}, 'depositDue', ${has("depositDue") ? `v_row.${q("depositDue")}::text` : "'0'"}`)}
|
|
@@ -62671,6 +63045,23 @@ function quoteDecisions(ctx, n, k) {
|
|
|
62671
63045
|
if ${a.name}.decision = 'accepted' then
|
|
62672
63046
|
${ctx.hook("after_quote_accept", [["uuid", `v_row.${q("id")}`]])}
|
|
62673
63047
|
end if;`;
|
|
63048
|
+
const viewer = (actor) => {
|
|
63049
|
+
const own = `begin
|
|
63050
|
+
v_ip := ${ip}::inet;
|
|
63051
|
+
exception when invalid_text_representation then
|
|
63052
|
+
v_ip := null;
|
|
63053
|
+
end;
|
|
63054
|
+
perform set_config('better_supabase.transition_actor', jsonb_strip_nulls(jsonb_build_object('email', auth.jwt() ->> 'email', 'ip', v_ip::text, 'userAgent', left(v_headers ->> 'user-agent', 512)))::text, true);`;
|
|
63055
|
+
return actor === void 0 ? `
|
|
63056
|
+
${own}` : `
|
|
63057
|
+
if ${actor} is not null and not ${n.service} then
|
|
63058
|
+
${fail$1("QUOTE_ACTOR_FORBIDDEN", "only the service role names who opened a quote", "42501")}
|
|
63059
|
+
end if;
|
|
63060
|
+
${transitionActorSql(actor, "QUOTE_ACTOR_INVALID")}
|
|
63061
|
+
if ${actor} is null then
|
|
63062
|
+
${own.replaceAll("\n", "\n ")}
|
|
63063
|
+
end if;`;
|
|
63064
|
+
};
|
|
62674
63065
|
const answered = `jsonb_build_object('status', ${ctx.label("quotes", "status", `v_row.${q("status")}`)}, 'identifier', v_row.${q("identifier")}, 'revision', v_row.${q("revision")})`;
|
|
62675
63066
|
const customerView = k.workingCopy ? `select v.${n.c("versions", "snapshot")} into v_snap from ${t("versions")} v where v.${n.c("versions", "id")} = ${k.latestVersion("v_row")};
|
|
62676
63067
|
if v_snap is null then
|
|
@@ -62681,7 +63072,9 @@ function quoteDecisions(ctx, n, k) {
|
|
|
62681
63072
|
const readable = (alias) => `(${n.service} or ${ctx.scope.can(`${alias}.${q("tenant")}`, n.read)})`;
|
|
62682
63073
|
return `
|
|
62683
63074
|
-- Records the customer's answer taken another way (by phone, by email):
|
|
62684
|
-
-- decision is accepted, rejected or changes_requested; by is their name
|
|
63075
|
+
-- decision is accepted, rejected or changes_requested; by is their name,
|
|
63076
|
+
-- and without it or an actor the answer names no one. The note is also the
|
|
63077
|
+
-- reason in the state machine's history.
|
|
62685
63078
|
-- selected lists the positions of the optional lines they took. actor is
|
|
62686
63079
|
-- the customer when the app takes the answer in its own portal: id, name,
|
|
62687
63080
|
-- email, ip and userAgent, kept with the answer and in the state machine's
|
|
@@ -62698,12 +63091,12 @@ declare
|
|
|
62698
63091
|
v_row ${t("quotes")};
|
|
62699
63092
|
v_claims text;${restoreVars}
|
|
62700
63093
|
begin
|
|
62701
|
-
select * into v_row from ${t("quotes")} x where x.${q("id")} = decide_quote.quote and ${editable("x")} for update;
|
|
63094
|
+
select * into v_row from ${t("quotes")} x where x.${q("id")} = decide_quote.quote and ${editable("x", n.decide)} for update;
|
|
62702
63095
|
if v_row.${q("id")} is null then
|
|
62703
63096
|
${fail$1("QUOTE_NOT_FOUND", "no such quote you can edit", "P0002")}
|
|
62704
63097
|
end if;${answer({
|
|
62705
63098
|
name: "decide_quote",
|
|
62706
|
-
by: "coalesce(nullif(trim(decide_quote.by), ''), nullif(trim(decide_quote.actor ->> 'name'), ''), decide_quote.actor ->> 'email'
|
|
63099
|
+
by: "coalesce(nullif(trim(decide_quote.by), ''), nullif(trim(decide_quote.actor ->> 'name'), ''), decide_quote.actor ->> 'email')",
|
|
62707
63100
|
customer: false,
|
|
62708
63101
|
expires: "decide_quote.actor is not null",
|
|
62709
63102
|
actor: "decide_quote.actor",
|
|
@@ -62723,12 +63116,12 @@ security definer
|
|
|
62723
63116
|
set search_path = ''
|
|
62724
63117
|
as $$
|
|
62725
63118
|
declare
|
|
62726
|
-
v_row ${t("quotes")};${restoreVars}
|
|
63119
|
+
v_row ${t("quotes")};${headers}${restoreVars}
|
|
62727
63120
|
begin
|
|
62728
63121
|
select * into v_row from ${t("quotes")} x where x.${q("tokenHash")} = ${sha256Hex$1("public_quote.token")};
|
|
62729
63122
|
if v_row.${q("id")} is null then
|
|
62730
63123
|
${fail$1("QUOTE_LINK_INVALID", "this link is not valid", "P0002")}
|
|
62731
|
-
end if
|
|
63124
|
+
end if;${viewer()}
|
|
62732
63125
|
${k.markViewed()}
|
|
62733
63126
|
${customerView}
|
|
62734
63127
|
end;
|
|
@@ -62770,16 +63163,18 @@ grant execute on function ${fn("respond_to_quote")}(text, text, text, text, json
|
|
|
62770
63163
|
-- A quote shared with the signed-in guest, as the customer sees it: through
|
|
62771
63164
|
-- a grant on the quote or as a guest of its company or contact. Opening a
|
|
62772
63165
|
-- sent quote marks it viewed. No link token is needed. The service role
|
|
62773
|
-
-- reads it too, for an app's own portal
|
|
62774
|
-
|
|
63166
|
+
-- reads it too, for an app's own portal; actor is then the customer who
|
|
63167
|
+
-- opened it, for the state machine's history.
|
|
63168
|
+
drop function if exists ${fn("portal_quote")}(uuid);
|
|
63169
|
+
create or replace function ${fn("portal_quote")}(quote uuid, actor jsonb default null)
|
|
62775
63170
|
returns jsonb
|
|
62776
63171
|
language plpgsql
|
|
62777
63172
|
security definer
|
|
62778
63173
|
set search_path = ''
|
|
62779
63174
|
as $$
|
|
62780
63175
|
declare
|
|
62781
|
-
v_row ${t("quotes")};${restoreVars}
|
|
62782
|
-
begin
|
|
63176
|
+
v_row ${t("quotes")};${headers}${restoreVars}
|
|
63177
|
+
begin${viewer("portal_quote.actor")}
|
|
62783
63178
|
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)}));
|
|
62784
63179
|
if v_row.${q("id")} is null then
|
|
62785
63180
|
${fail$1("QUOTE_NOT_FOUND", "no such quote shared with you", "P0002")}
|
|
@@ -62788,7 +63183,7 @@ ${k.markViewed()}
|
|
|
62788
63183
|
${customerView}
|
|
62789
63184
|
end;
|
|
62790
63185
|
$$;
|
|
62791
|
-
${userGrant(`${fn("portal_quote")}(uuid)`)}
|
|
63186
|
+
${userGrant(`${fn("portal_quote")}(uuid, jsonb)`)}
|
|
62792
63187
|
|
|
62793
63188
|
-- The signed-in guest's answer to a quote shared with them, like
|
|
62794
63189
|
-- respond_to_quote without a token. name defaults to their email; the
|
|
@@ -62912,7 +63307,15 @@ function quoteFunctions(ctx, n) {
|
|
|
62912
63307
|
if v_row.${q("depositBps")} is not null and v_row.${q("depositAmount")} is not null then
|
|
62913
63308
|
${fail$1("QUOTE_ATTRS_INVALID", "a deposit is a share (depositBps) or an amount (depositAmount), not both", "22023")}
|
|
62914
63309
|
end if;` : "";
|
|
63310
|
+
const partyAssign = (party) => {
|
|
63311
|
+
const given = `update_quote.attrs ? ${sqlString(party)}`;
|
|
63312
|
+
const id = `update_quote.attrs -> ${sqlString(party)} ->> 'id'`;
|
|
63313
|
+
const type = `coalesce(update_quote.attrs -> ${sqlString(party)} ->> 'type', ${sqlString(party === "company" ? n.company : n.contact)})`;
|
|
63314
|
+
const values = k.partyValues(party, type, id);
|
|
63315
|
+
return k.partyFields(party).map((field, index) => assign(field, (col) => `case when ${given} then ${values[index] ?? "null"} else x.${col} end`)).join("");
|
|
63316
|
+
};
|
|
62915
63317
|
const actor = (name) => `\n ${transitionActorSql(`${name}.actor`, "QUOTE_ACTOR_INVALID")}`;
|
|
63318
|
+
const resent = k.declined.length === 0 ? "" : `${q("validUntil")} = case when ${st(`x.${q("status")}`, k.declined)} then greatest(x.${q("validUntil")}, current_date + ${String(n.validDays)}) else x.${q("validUntil")} end, ${has("viewedAt") && !k.workingCopy ? `${q("viewedAt")} = case when ${st(`x.${q("status")}`, k.declined)} then null else x.${q("viewedAt")} end, ` : ""}`;
|
|
62916
63319
|
const publishedBy = `coalesce(auth.uid(), nullif(send_quote.actor ->> 'id', '')::uuid)`;
|
|
62917
63320
|
const versionLinesCopy = (() => {
|
|
62918
63321
|
if (!k.versionLines) return "";
|
|
@@ -62933,9 +63336,11 @@ function quoteFunctions(ctx, n) {
|
|
|
62933
63336
|
"productId"
|
|
62934
63337
|
].filter((column) => declared(ctx, "versionLines", column) && declared(ctx, "lines", column));
|
|
62935
63338
|
const value = (column) => column === "productType" ? ctx.cast("versionLines", column, `ql.${l(column)}::text`) : `ql.${l(column)}`;
|
|
63339
|
+
const lineExtraNames = new Set(n.lineExtras.map((extra) => extra.name));
|
|
63340
|
+
const extras = n.versionLineExtras.filter((extra) => lineExtraNames.has(extra.name)).map((extra) => extra.ident);
|
|
62936
63341
|
return `
|
|
62937
|
-
insert into ${t("versionLines")} (${vl("tenant")}, ${vl("version")}, ${copied.map(vl).join(", ")})
|
|
62938
|
-
select v_row.${q("tenant")}, v_version, ${copied.map(value).join(", ")}
|
|
63342
|
+
insert into ${t("versionLines")} (${vl("tenant")}, ${vl("version")}, ${[...copied.map(vl), ...extras].join(", ")})
|
|
63343
|
+
select v_row.${q("tenant")}, v_version, ${[...copied.map(value), ...extras.map((ident) => `ql.${ident}`)].join(", ")}
|
|
62939
63344
|
from ${t("lines")} ql where ql.${l("parent")} = v_row.${q("id")};`;
|
|
62940
63345
|
})();
|
|
62941
63346
|
const deals = ctx.installed("deals") ? ctx.of("deals") : void 0;
|
|
@@ -63029,14 +63434,14 @@ begin
|
|
|
63029
63434
|
prefix: n.prefix
|
|
63030
63435
|
})}
|
|
63031
63436
|
begin
|
|
63032
|
-
insert into ${t("quotes")} (${q("tenant")}, ${q("number")}, ${q("identifier")}, ${q("title")}${
|
|
63437
|
+
insert into ${t("quotes")} (${q("tenant")}, ${q("number")}, ${q("identifier")}, ${q("title")}${[...k.partyFields("company"), ...k.partyFields("contact")].map((field) => `, ${q(field)}`).join("")},
|
|
63033
63438
|
${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})
|
|
63034
63439
|
values (${valueLines(" ", [
|
|
63035
63440
|
"create_quote.tenant",
|
|
63036
63441
|
"v_seq",
|
|
63037
63442
|
"v_identifier",
|
|
63038
63443
|
"trim(create_quote.attrs ->> 'title')"
|
|
63039
|
-
], company
|
|
63444
|
+
], k.partyValues("company", "v_company_type", "v_company_id"), k.partyValues("contact", "v_contact_type", "v_contact_id"), ["coalesce((create_quote.attrs ->> 'ownerId')::uuid, auth.uid())", "upper(coalesce(create_quote.attrs ->> 'currency', 'EUR'))"], [`coalesce((create_quote.attrs ->> 'validUntil')::date, current_date + ${String(n.validDays)})`], [present("terms", "create_quote.attrs ->> 'terms'"), present("note", "create_quote.attrs ->> 'note'")], [present("originType", "create_quote.attrs -> 'origin' ->> 'type'"), present("originId", "create_quote.attrs -> 'origin' ->> 'id'")], [
|
|
63040
63445
|
present("pricesIncludeTax", "coalesce((create_quote.attrs ->> 'pricesIncludeTax')::boolean, false)"),
|
|
63041
63446
|
present("discountBps", "coalesce((create_quote.attrs ->> 'discountBps')::integer, 0)"),
|
|
63042
63447
|
present("discountAmount", "coalesce((create_quote.attrs ->> 'discountAmount')::bigint, 0)"),
|
|
@@ -63092,15 +63497,15 @@ begin
|
|
|
63092
63497
|
${q("title")} = coalesce(nullif(trim(update_quote.attrs ->> 'title'), ''), x.${q("title")}),
|
|
63093
63498
|
${q("currency")} = coalesce(upper(update_quote.attrs ->> 'currency'), x.${q("currency")}),
|
|
63094
63499
|
${q("owner")} = case when update_quote.attrs ? 'ownerId' then (update_quote.attrs ->> 'ownerId')::uuid else x.${q("owner")} end,
|
|
63095
|
-
${q("validUntil")} = case when update_quote.attrs ? 'validUntil' then (update_quote.attrs ->> 'validUntil')::date else x.${q("validUntil")} end,${assign("terms", (col) => `case when update_quote.attrs ? 'terms' then update_quote.attrs ->> 'terms' else x.${col} end`)}${assign("note", (col) => `case when update_quote.attrs ? 'note' then update_quote.attrs ->> 'note' else x.${col} end`)}${assign("pricesIncludeTax", (col) => `case when update_quote.attrs ? 'pricesIncludeTax' then coalesce((update_quote.attrs ->> 'pricesIncludeTax')::boolean, false) else x.${col} end`)}${assign("discountBps", (col) => `case when update_quote.attrs ? 'discountBps' then coalesce((update_quote.attrs ->> 'discountBps')::integer, 0) else x.${col} end`)}${assign("discountAmount", (col) => `case when update_quote.attrs ? 'discountAmount' then coalesce((update_quote.attrs ->> 'discountAmount')::bigint, 0) else x.${col} end`)}${assign("depositBps", (col) => `case when update_quote.attrs ? 'depositBps' then (update_quote.attrs ->> 'depositBps')::integer else x.${col} end`)}${assign("depositAmount", (col) => `case when update_quote.attrs ? 'depositAmount' then (update_quote.attrs ->> 'depositAmount')::bigint else x.${col} end`)}${assign("depositRequired", (col) => `case when update_quote.attrs ? 'depositRequired' then coalesce((update_quote.attrs ->> 'depositRequired')::boolean, false) else x.${col} end`)}${k.workingCopy ? assign("unpublishedChanges", () => "true") : ""}${
|
|
63500
|
+
${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") : ""}${partyAssign("company")}${partyAssign("contact")}
|
|
63096
63501
|
${q("updatedAt")} = now()
|
|
63097
63502
|
where x.${q("id")} = v_row.${q("id")}
|
|
63098
63503
|
returning * into v_row;${n.extras.length === 0 ? "" : `${writeExtraColumns(t("quotes"), n.extras, "(update_quote.attrs -> 'fields')", `x.${q("id")} = v_row.${q("id")}`)}
|
|
63099
63504
|
select * into v_row from ${t("quotes")} x where x.${q("id")} = v_row.${q("id")};`}
|
|
63100
63505
|
exception when check_violation or invalid_text_representation or datetime_field_overflow or numeric_value_out_of_range then
|
|
63101
63506
|
${fail$1("QUOTE_ATTRS_INVALID", "a quote field has an invalid value", "22023")}
|
|
63102
|
-
end;${oneDeposit}
|
|
63103
|
-
perform ${fn("set_quote_lines_recount")}(v_row.${q("id")})
|
|
63507
|
+
end;${oneDeposit}${n.appTotals ? "" : `
|
|
63508
|
+
perform ${fn("set_quote_lines_recount")}(v_row.${q("id")});`}
|
|
63104
63509
|
select * into v_row from ${t("quotes")} x where x.${q("id")} = v_row.${q("id")};
|
|
63105
63510
|
${record("quote.updated", "v_row")}
|
|
63106
63511
|
return ${row("v_row")};
|
|
@@ -63113,6 +63518,7 @@ ${lineItemsSql(ctx, {
|
|
|
63113
63518
|
frozen: `not (${open("p")})`,
|
|
63114
63519
|
extras: n.lineExtras,
|
|
63115
63520
|
taxLines: "taxLines",
|
|
63521
|
+
totals: !n.appTotals,
|
|
63116
63522
|
...k.depositDue === void 0 ? {} : { afterTotals: k.depositDue }
|
|
63117
63523
|
}, {
|
|
63118
63524
|
setter: "set_quote_lines",
|
|
@@ -63141,11 +63547,11 @@ declare
|
|
|
63141
63547
|
v_token text := encode(extensions.gen_random_bytes(24), 'hex');
|
|
63142
63548
|
v_version uuid;${k.workingCopy ? "\n v_linked boolean;" : ""}
|
|
63143
63549
|
begin
|
|
63144
|
-
select * into v_row from ${t("quotes")} x where x.${q("id")} = send_quote.quote and ${editable("x")} for update;
|
|
63550
|
+
select * into v_row from ${t("quotes")} x where x.${q("id")} = send_quote.quote and ${editable("x", n.send)} for update;
|
|
63145
63551
|
if v_row.${q("id")} is null then
|
|
63146
63552
|
${fail$1("QUOTE_NOT_FOUND", "no such quote you can edit", "P0002")}
|
|
63147
63553
|
end if;
|
|
63148
|
-
if not (${open("v_row")}) then
|
|
63554
|
+
if not (${open("v_row")}${k.declined.length > 0 && !k.workingCopy ? ` or ${st(`v_row.${q("status")}`, k.declined)}` : ""}) then
|
|
63149
63555
|
${fail$1("QUOTE_NOT_EDITABLE", "the quote was already sent; revise it to send a new version", "55000")}
|
|
63150
63556
|
end if;
|
|
63151
63557
|
if not exists (select 1 from ${t("lines")} x where x.${l("parent")} = v_row.${q("id")}) then
|
|
@@ -63154,7 +63560,7 @@ begin
|
|
|
63154
63560
|
${ctx.hook("before_quote_send", [["uuid", `v_row.${q("id")}`]])}${k.workingCopy ? `\n v_linked := v_row.${q("tokenHash")} is not null;` : ""}
|
|
63155
63561
|
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")},
|
|
63156
63562
|
${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,
|
|
63157
|
-
${decisionReset}${k.workingCopy ? `${q("unpublishedChanges")} = false, ` : ""}${q("updatedAt")} = now()
|
|
63563
|
+
${decisionReset}${resent}${k.workingCopy ? `${q("unpublishedChanges")} = false, ` : ""}${q("updatedAt")} = now()
|
|
63158
63564
|
where x.${q("id")} = v_row.${q("id")}
|
|
63159
63565
|
returning * into v_row;
|
|
63160
63566
|
insert into ${t("versions")} (${v("tenant")}, ${v("quote")}, ${v("revision")}, ${v("snapshot")}, ${v("total")}, ${v("currency")}${ctx.has("versions", "publishedBy") ? `, ${v("publishedBy")}` : ""})
|
|
@@ -63204,9 +63610,11 @@ end;
|
|
|
63204
63610
|
$$;
|
|
63205
63611
|
${userGrant(`${fn("revise_quote")}(uuid, jsonb)`)}
|
|
63206
63612
|
|
|
63207
|
-
-- Takes back a sent quote the customer hasn't accepted: it can't
|
|
63208
|
-
-- any more until it is revised and sent again.
|
|
63209
|
-
|
|
63613
|
+
-- Takes back a sent or expired quote the customer hasn't accepted: it can't
|
|
63614
|
+
-- be answered any more until it is revised and sent again. The actor and
|
|
63615
|
+
-- reason go to the state machine's history.
|
|
63616
|
+
drop function if exists ${fn("withdraw_quote")}(uuid, jsonb);
|
|
63617
|
+
create or replace function ${fn("withdraw_quote")}(quote uuid, actor jsonb default null, reason text default null)
|
|
63210
63618
|
returns jsonb
|
|
63211
63619
|
language plpgsql
|
|
63212
63620
|
security definer
|
|
@@ -63215,25 +63623,28 @@ as $$
|
|
|
63215
63623
|
declare
|
|
63216
63624
|
v_row ${t("quotes")};
|
|
63217
63625
|
begin
|
|
63218
|
-
select * into v_row from ${t("quotes")} x where x.${q("id")} = withdraw_quote.quote and ${editable("x")} for update;
|
|
63626
|
+
select * into v_row from ${t("quotes")} x where x.${q("id")} = withdraw_quote.quote and ${editable("x", n.withdraw)} for update;
|
|
63219
63627
|
if v_row.${q("id")} is null then
|
|
63220
63628
|
${fail$1("QUOTE_NOT_FOUND", "no such quote you can edit", "P0002")}
|
|
63221
63629
|
end if;
|
|
63222
63630
|
if ${st(`v_row.${q("status")}`, [
|
|
63223
63631
|
"sent",
|
|
63224
63632
|
"viewed",
|
|
63225
|
-
"changes_requested"
|
|
63633
|
+
"changes_requested",
|
|
63634
|
+
"expired"
|
|
63226
63635
|
], true)} then
|
|
63227
63636
|
${fail$1("QUOTE_NOT_OPEN", "only a sent quote that wasn't answered is withdrawn", "55000")}
|
|
63228
63637
|
end if;${actor("withdraw_quote")}
|
|
63638
|
+
${transitionReasonSql("withdraw_quote.reason")}
|
|
63229
63639
|
update ${t("quotes")} x set ${q("status")} = ${sv("withdrawn")}, ${q("updatedAt")} = now()
|
|
63230
63640
|
where x.${q("id")} = v_row.${q("id")}
|
|
63231
63641
|
returning * into v_row;
|
|
63642
|
+
${transitionReasonSql()}
|
|
63232
63643
|
${record("quote.withdrawn", "v_row", `, 'revision', v_row.${q("revision")}`)}
|
|
63233
63644
|
return ${row("v_row")};
|
|
63234
63645
|
end;
|
|
63235
63646
|
$$;
|
|
63236
|
-
${userGrant(`${fn("withdraw_quote")}(uuid, jsonb)`)}
|
|
63647
|
+
${userGrant(`${fn("withdraw_quote")}(uuid, jsonb, text)`)}
|
|
63237
63648
|
${quoteDecisions(ctx, n, k)}
|
|
63238
63649
|
-- Expires sent quotes past their valid date. Run it daily from a job.
|
|
63239
63650
|
create or replace function ${fn("expire_quotes")}()
|
|
@@ -63246,6 +63657,7 @@ declare
|
|
|
63246
63657
|
v_row ${t("quotes")};
|
|
63247
63658
|
v_count integer := 0;
|
|
63248
63659
|
begin
|
|
63660
|
+
perform set_config('better_supabase.transition_actor', '', true);
|
|
63249
63661
|
for v_row in
|
|
63250
63662
|
update ${t("quotes")} x set ${q("status")} = ${sv("expired")}, ${q("updatedAt")} = now()
|
|
63251
63663
|
where ${st(`x.${q("status")}`, ["sent", "viewed"])} and x.${q("validUntil")} < current_date
|
|
@@ -63258,7 +63670,47 @@ begin
|
|
|
63258
63670
|
end;
|
|
63259
63671
|
$$;
|
|
63260
63672
|
${serviceGrant(`${fn("expire_quotes")}()`)}
|
|
63261
|
-
${fromDeal}`;
|
|
63673
|
+
${appTotalsGuard(ctx, n, k)}${fromDeal}`;
|
|
63674
|
+
}
|
|
63675
|
+
/**
|
|
63676
|
+
* With `options.totals: "app"`, a trigger on the quotes table that refuses a
|
|
63677
|
+
* change to the totals once a quote is answered, expired or withdrawn, and
|
|
63678
|
+
* keeps the deposit due on the app's total.
|
|
63679
|
+
*/
|
|
63680
|
+
function appTotalsGuard(ctx, n, k) {
|
|
63681
|
+
if (!n.appTotals) return "";
|
|
63682
|
+
const { q, has, st } = k;
|
|
63683
|
+
const trigger = ctx.trigger("quotes_app_totals");
|
|
63684
|
+
const fn = `better_supabase.${trigger.replaceAll("\"", "")}()`;
|
|
63685
|
+
const totals = Object.keys(TOTAL_COLUMNS).filter(has).map(q);
|
|
63686
|
+
const changeable = [.../* @__PURE__ */ new Set([
|
|
63687
|
+
...k.openStatuses,
|
|
63688
|
+
"sent",
|
|
63689
|
+
"viewed"
|
|
63690
|
+
])];
|
|
63691
|
+
const depositDue = has("depositDue") ? `
|
|
63692
|
+
new.${q("depositDue")} := case${has("depositAmount") ? ` when new.${q("depositAmount")} is not null then least(greatest(new.${q("total")}, 0), new.${q("depositAmount")})` : ""}${has("depositBps") ? ` when new.${q("depositBps")} is not null then round(new.${q("total")} * new.${q("depositBps")} / 10000.0)::bigint` : ""} else 0 end;` : "";
|
|
63693
|
+
return `
|
|
63694
|
+
-- The app keeps the quote's totals: once a quote is answered, expired or
|
|
63695
|
+
-- withdrawn they no longer change, and the deposit due follows the total.
|
|
63696
|
+
create or replace function ${fn}
|
|
63697
|
+
returns trigger
|
|
63698
|
+
language plpgsql
|
|
63699
|
+
set search_path = ''
|
|
63700
|
+
as $$
|
|
63701
|
+
begin
|
|
63702
|
+
if tg_op = 'UPDATE' and ${st(`old.${q("status")}`, changeable, true)}
|
|
63703
|
+
and (${totals.map((column) => `new.${column}`).join(", ")}) is distinct from (${totals.map((column) => `old.${column}`).join(", ")}) then
|
|
63704
|
+
${fail$1("QUOTE_TOTALS_FROZEN", "the totals of an answered, expired or withdrawn quote don't change", "55000")}
|
|
63705
|
+
end if;${depositDue}
|
|
63706
|
+
return new;
|
|
63707
|
+
end;
|
|
63708
|
+
$$;
|
|
63709
|
+
${triggerGrant(fn)}
|
|
63710
|
+
drop trigger if exists ${trigger} on ${n.t("quotes")};
|
|
63711
|
+
create trigger ${trigger} before insert or update on ${n.t("quotes")}
|
|
63712
|
+
for each row execute function ${fn};
|
|
63713
|
+
`;
|
|
63262
63714
|
}
|
|
63263
63715
|
// src/sql/modules/employees-functions.ts
|
|
63264
63716
|
/**
|
|
@@ -63341,7 +63793,7 @@ function employeeFunctions(ctx, n) {
|
|
|
63341
63793
|
select u.${e("id")}, u.${e("manager")} from ${table} u join up on u.${e("id")} = up.manager
|
|
63342
63794
|
)
|
|
63343
63795
|
select 1 from up join ${table} me on me.${e("id")} = up.id where me.${e("user")} = auth.uid())`;
|
|
63344
|
-
const payload = (alias, extra) => `jsonb_build_object('organizationId', ${alias}.${e("tenant")}, 'employeeId', ${alias}.${e("id")}, 'subjectType', 'employee', 'subjectId', ${alias}.${e("id")}::text, 'name', ${n.name(alias)}${extra})`;
|
|
63796
|
+
const payload = (alias, extra) => `jsonb_build_object('organizationId', ${alias}.${e("tenant")}, 'employeeId', ${alias}.${e("id")}, 'subjectType', 'employee', 'subjectId', ${alias}.${e("id")}::text, 'name', ${n.name(alias)}, 'userId', ${alias}.${e("user")}${extra})`;
|
|
63345
63797
|
const record = (type, alias, extra = "") => ctx.record({
|
|
63346
63798
|
type,
|
|
63347
63799
|
payload: payload(alias, extra),
|
|
@@ -63467,7 +63919,7 @@ begin
|
|
|
63467
63919
|
when check_violation or not_null_violation or invalid_text_representation or invalid_datetime_format or datetime_field_overflow then
|
|
63468
63920
|
${fail$1("EMPLOYEE_ATTRS_INVALID", "an employee field has an invalid value", "22023")}
|
|
63469
63921
|
end;${typeCheck("v_row")}${member(`v_row.${e("tenant")}`, `v_row.${e("user")}`)}${link}
|
|
63470
|
-
${record("employee.created", "v_row", `, '
|
|
63922
|
+
${record("employee.created", "v_row", `, 'managerId', v_row.${e("manager")}, 'status', v_row.${e("status")}`)}
|
|
63471
63923
|
${ctx.hook("after_employee_create", [["uuid", `v_row.${e("id")}`]])}
|
|
63472
63924
|
return ${n.json("v_row")};
|
|
63473
63925
|
end;
|
|
@@ -63943,7 +64395,7 @@ function contractsSql(ctx, n, reader, load) {
|
|
|
63943
64395
|
end if;` : insertWith(void 0);
|
|
63944
64396
|
const updated = ctx.record({
|
|
63945
64397
|
type: "employee.updated",
|
|
63946
|
-
payload: `jsonb_build_object('organizationId', v_employee.${e("tenant")}, 'employeeId', v_employee.${e("id")}, 'subjectType', 'employee', 'subjectId', v_employee.${e("id")}::text, 'name', ${n.name("v_employee")}, 'fields', jsonb_build_array('contract'))`,
|
|
64398
|
+
payload: `jsonb_build_object('organizationId', v_employee.${e("tenant")}, 'employeeId', v_employee.${e("id")}, 'subjectType', 'employee', 'subjectId', v_employee.${e("id")}::text, 'name', ${n.name("v_employee")}, 'userId', v_employee.${e("user")}, 'fields', jsonb_build_array('contract'))`,
|
|
63947
64399
|
subject: `'employees/' || v_employee.${e("id")}::text`,
|
|
63948
64400
|
tenant: `v_employee.${e("tenant")}::text`,
|
|
63949
64401
|
audit: false
|
|
@@ -64095,14 +64547,14 @@ const EMPLOYEE = [
|
|
|
64095
64547
|
"employeeId",
|
|
64096
64548
|
"subjectType",
|
|
64097
64549
|
"subjectId",
|
|
64098
|
-
"name"
|
|
64550
|
+
"name",
|
|
64551
|
+
"userId"
|
|
64099
64552
|
];
|
|
64100
64553
|
const EVENTS$12 = {
|
|
64101
64554
|
"employee.created": {
|
|
64102
64555
|
subject: "employees",
|
|
64103
64556
|
payload: [
|
|
64104
64557
|
...EMPLOYEE,
|
|
64105
|
-
"userId",
|
|
64106
64558
|
"managerId",
|
|
64107
64559
|
"status"
|
|
64108
64560
|
]
|
|
@@ -66532,7 +66984,7 @@ ${layout.entitlementsProvider ? providerEntitlementChecks(claims, layout.entitle
|
|
|
66532
66984
|
revoke execute on function better_supabase.feature_claims(uuid) from public, anon, authenticated;
|
|
66533
66985
|
grant execute on function better_supabase.feature_claims(uuid) to service_role, supabase_auth_admin;`;
|
|
66534
66986
|
};
|
|
66535
|
-
const qualified$
|
|
66987
|
+
const qualified$7 = (table) => quotedTable$1(table);
|
|
66536
66988
|
/**
|
|
66537
66989
|
* `tenant_entitlements` over a plan catalog: the active subscription's plan
|
|
66538
66990
|
* features.
|
|
@@ -66554,8 +67006,8 @@ security definer
|
|
|
66554
67006
|
set search_path = ''
|
|
66555
67007
|
as $$
|
|
66556
67008
|
select coalesce(array_agg(distinct f.${sqlIdent(features.feature)}::text order by f.${sqlIdent(features.feature)}::text), '{}')
|
|
66557
|
-
from ${qualified$
|
|
66558
|
-
join ${qualified$
|
|
67009
|
+
from ${qualified$7(subs.table)} s
|
|
67010
|
+
join ${qualified$7(features.table)} f on f.${sqlIdent(features.plan)}::text = s.${sqlIdent(subs.plan)}::text
|
|
66559
67011
|
where s.${sqlIdent(subs.tenant)} = tenant_entitlements.tenant${status}${included}
|
|
66560
67012
|
and f.${sqlIdent(features.feature)} is not null
|
|
66561
67013
|
$$;
|
|
@@ -66574,7 +67026,7 @@ security definer
|
|
|
66574
67026
|
set search_path = ''
|
|
66575
67027
|
as $$
|
|
66576
67028
|
select coalesce(array_agg(distinct s.${sqlIdent(subs.plan)}::text order by s.${sqlIdent(subs.plan)}::text), '{}')
|
|
66577
|
-
from ${qualified$
|
|
67029
|
+
from ${qualified$7(subs.table)} s
|
|
66578
67030
|
where s.${sqlIdent(subs.tenant)} = tenant_plans.tenant${status}
|
|
66579
67031
|
and s.${sqlIdent(subs.plan)} is not null
|
|
66580
67032
|
$$;
|
|
@@ -66603,8 +67055,8 @@ security definer
|
|
|
66603
67055
|
set search_path = ''
|
|
66604
67056
|
as $$
|
|
66605
67057
|
select coalesce(${value}, 'true'::jsonb)
|
|
66606
|
-
from ${qualified$
|
|
66607
|
-
join ${qualified$
|
|
67058
|
+
from ${qualified$7(subs.table)} s
|
|
67059
|
+
join ${qualified$7(features.table)} f on f.${sqlIdent(features.plan)}::text = s.${sqlIdent(subs.plan)}::text
|
|
66608
67060
|
where s.${sqlIdent(subs.tenant)} = tenant_entitlement_value.tenant${status}${included}
|
|
66609
67061
|
and f.${sqlIdent(features.feature)}::text = tenant_entitlement_value.key
|
|
66610
67062
|
order by case when jsonb_typeof(${value}) = 'number' then (${value} #>> '{}')::numeric end desc nulls last,
|
|
@@ -73138,6 +73590,7 @@ const NAMES$65 = {
|
|
|
73138
73590
|
payload: ACCESS_PAYLOAD
|
|
73139
73591
|
}
|
|
73140
73592
|
},
|
|
73593
|
+
options: ["representation"],
|
|
73141
73594
|
tables: {
|
|
73142
73595
|
guests: {
|
|
73143
73596
|
name: "guests",
|
|
@@ -73221,6 +73674,44 @@ function grantSubjectTenant(ctx, type, id) {
|
|
|
73221
73674
|
const registered = subjectTenant(ctx, type, id);
|
|
73222
73675
|
return owned.length === 0 ? registered : `(case ${type}\n ${owned.join("\n ")}\n else ${registered}\n end)`;
|
|
73223
73676
|
}
|
|
73677
|
+
const SUBJECT_TYPE = /^[a-z][a-z0-9_-]{0,62}$/;
|
|
73678
|
+
/** `options.representation.subjects`, checked; undefined without the option. */
|
|
73679
|
+
function representedTypes(ctx) {
|
|
73680
|
+
const where = "blocks.guests.options.representation";
|
|
73681
|
+
const raw = ctx.option("representation");
|
|
73682
|
+
if (raw === void 0) return;
|
|
73683
|
+
const subjects = typeof raw === "object" && raw !== null && !Array.isArray(raw) ? new Map(Object.entries(raw)).get("subjects") : void 0;
|
|
73684
|
+
const list = Array.isArray(subjects) ? subjects : [];
|
|
73685
|
+
const types = list.filter((type) => typeof type === "string" && SUBJECT_TYPE.test(type));
|
|
73686
|
+
if (types.length === 0 || types.length !== list.length) throw new TypeError(`${where} must be { subjects: [...] }, a non-empty list of subject types`);
|
|
73687
|
+
if (!ctx.installed("relations") || !ctx.installed("contacts")) throw new TypeError(`${where} needs the relations and contacts blocks`);
|
|
73688
|
+
if (!(ctx.has("guests", "partyType") && ctx.has("guests", "partyId"))) throw new TypeError(`${where} needs the guests table's party_type and party_id columns`);
|
|
73689
|
+
return types;
|
|
73690
|
+
}
|
|
73691
|
+
/**
|
|
73692
|
+
* The records a guest reaches as a representative: their party is a contacts
|
|
73693
|
+
* person with a `represents` link to a record of a listed type that holds
|
|
73694
|
+
* today. `read` always, `comment` and `upload` with `authority: "act"`. Read
|
|
73695
|
+
* live from the links, so ending or dating a link takes effect at once.
|
|
73696
|
+
*/
|
|
73697
|
+
function representation(ctx, live) {
|
|
73698
|
+
const types = representedTypes(ctx);
|
|
73699
|
+
if (types === void 0) return {};
|
|
73700
|
+
const relations = ctx.of("relations");
|
|
73701
|
+
const r = (column) => `r.${relations.col("relations", column)}`;
|
|
73702
|
+
const g = (column) => `x.${ctx.col("guests", column)}`;
|
|
73703
|
+
const person = sqlString(ctx.of("contacts").naming.rename("person"));
|
|
73704
|
+
return { subjects: `select ${g("tenant")}::text, ${r("targetType")}, ${r("targetId")}
|
|
73705
|
+
from ${relations.table("relations")} r
|
|
73706
|
+
join ${ctx.table("guests")} x on ${g("tenant")} = ${r("tenant")}
|
|
73707
|
+
and ${g("partyType")} = ${person} and ${g("partyId")} = ${r("sourceId")}
|
|
73708
|
+
where ${live("x")}
|
|
73709
|
+
and ${r("kind")} = ${sqlString(REPRESENTS)} and ${r("sourceType")} = ${person}
|
|
73710
|
+
and ${r("targetType")} in (${types.map((type) => sqlString(type)).join(", ")})
|
|
73711
|
+
and ${representationActive(r("data"))}
|
|
73712
|
+
and (portal_subjects.action = 'read'
|
|
73713
|
+
or (${r("data")} ->> 'authority' = 'act' and portal_subjects.action in ('comment', 'upload')))` };
|
|
73714
|
+
}
|
|
73224
73715
|
function tables$19(ctx) {
|
|
73225
73716
|
if (!ctx.manages) return "";
|
|
73226
73717
|
const guests = ctx.table("guests");
|
|
@@ -73403,7 +73894,11 @@ function functions$7(ctx, layout) {
|
|
|
73403
73894
|
end if;`;
|
|
73404
73895
|
const token = "encode(extensions.gen_random_bytes(32), 'hex')";
|
|
73405
73896
|
const hash = (value) => sha256Hex$1(`convert_to(${value}, 'utf8')`);
|
|
73406
|
-
return `${guestFunctions([
|
|
73897
|
+
return `${guestFunctions([
|
|
73898
|
+
own,
|
|
73899
|
+
representation(ctx, live),
|
|
73900
|
+
providerGuestSource(layout)
|
|
73901
|
+
])}
|
|
73407
73902
|
-- Whether the caller reaches subject_type/subject_id as a guest for action.
|
|
73408
73903
|
create or replace function ${fn("guest_can")}(subject_type text, subject_id text, action text default 'read')
|
|
73409
73904
|
returns boolean
|
|
@@ -73793,7 +74288,8 @@ const GUESTS = {
|
|
|
73793
74288
|
"audit",
|
|
73794
74289
|
"invoices",
|
|
73795
74290
|
"bookings",
|
|
73796
|
-
"contacts"
|
|
74291
|
+
"contacts",
|
|
74292
|
+
"relations"
|
|
73797
74293
|
],
|
|
73798
74294
|
before: "comments",
|
|
73799
74295
|
target: "schema",
|
|
@@ -86532,7 +87028,156 @@ const INVITATIONS = {
|
|
|
86532
87028
|
}],
|
|
86533
87029
|
build: invitationsSql
|
|
86534
87030
|
};
|
|
87031
|
+
// src/sql/modules/invoices-from-quote.ts
|
|
87032
|
+
/**
|
|
87033
|
+
* `invoice_from_quote`: a deposit invoice for a share or an amount of an
|
|
87034
|
+
* accepted quote, or the final invoice less the deposits issued. Empty without
|
|
87035
|
+
* the quotes module.
|
|
87036
|
+
*/
|
|
87037
|
+
function invoiceFromQuote(ctx, n, k) {
|
|
87038
|
+
const quotes = ctx.installed("quotes") ? ctx.of("quotes") : void 0;
|
|
87039
|
+
if (quotes === void 0) return "";
|
|
87040
|
+
const { fn, t } = n;
|
|
87041
|
+
const i = (column) => n.c("invoices", column);
|
|
87042
|
+
const { has, row, refuse, st, kd, origin, company, contact } = k;
|
|
87043
|
+
const q = (column) => quotes.col("quotes", column);
|
|
87044
|
+
const ql = (column) => quotes.col("lines", column);
|
|
87045
|
+
const kind = n.depositKind;
|
|
87046
|
+
const bpsDeposits = kind !== void 0 || has("depositBps");
|
|
87047
|
+
const amountDeposits = kind !== void 0 || has("depositAmount");
|
|
87048
|
+
const markers = ["depositBps", "depositAmount"].filter(has);
|
|
87049
|
+
const deposits = kind !== void 0 || markers.length > 0;
|
|
87050
|
+
const isDeposit = (alias) => kind === void 0 ? markers.map((column) => `${alias}.${i(column)} is not null`).join(" or ") : `${alias}.${i("kind")}::text = ${sqlString(kind)}`;
|
|
87051
|
+
const notDeposit = (alias) => kind === void 0 ? markers.map((column) => `${alias}.${i(column)} is null and `).join("") : `${alias}.${i("kind")}::text <> ${sqlString(kind)} and `;
|
|
87052
|
+
const originIs = (alias) => `${origin === "pair" ? `${alias}.${i("originType")} = 'quote' and ` : ""}${alias}.${i("originId")}::text = v_quote.${q("id")}::text`;
|
|
87053
|
+
const inclusive = has("pricesIncludeTax") && quotes.has("quotes", "pricesIncludeTax") ? `v_quote.${q("pricesIncludeTax")}` : "false";
|
|
87054
|
+
const base = (alias) => `case when ${inclusive} then ${alias}.${q("total")} else ${alias}.${q("subtotal")} end`;
|
|
87055
|
+
const blendedRate = `case when v_quote.${q("subtotal")} = 0 then 0 else round(v_quote.${q("taxTotal")} * 10000.0 / v_quote.${q("subtotal")})::integer end`;
|
|
87056
|
+
const taxLines = quotes.hasTable("taxLines") ? (column) => quotes.col("taxLines", column) : void 0;
|
|
87057
|
+
const invoiceLineExtras = new Set(n.lineExtras.map((extra) => extra.name));
|
|
87058
|
+
const lineFields = lineExtraColumns(quotes).filter((extra) => invoiceLineExtras.has(extra.name));
|
|
87059
|
+
const lineFieldsSql = lineFields.length === 0 ? "" : `, 'fields', jsonb_build_object(${lineFields.map((extra) => `${sqlString(extra.name)}, x.${extra.ident}`).join(", ")})`;
|
|
87060
|
+
const invoiceExtras = new Set(n.extras.map((extra) => extra.name));
|
|
87061
|
+
const headerFields = quotes.extraColumns("quotes", [
|
|
87062
|
+
"lines",
|
|
87063
|
+
"token",
|
|
87064
|
+
"fields"
|
|
87065
|
+
]).filter((extra) => invoiceExtras.has(extra.name));
|
|
87066
|
+
const headerFieldsSql = headerFields.length === 0 ? "" : ` || jsonb_build_object(${headerFields.map((extra) => `${sqlString(extra.name)}, v_quote.${extra.ident}`).join(", ")})`;
|
|
87067
|
+
const discountLines = taxLines !== void 0 && quotes.has("taxLines", "discount") ? `
|
|
87068
|
+
select v_lines || coalesce(jsonb_agg(jsonb_build_object('description', 'Discount', 'quantity', 1, 'unitAmount', (-x.${taxLines("discount")})::text,
|
|
87069
|
+
'taxRateBps', x.${taxLines("taxRateBps")}, 'taxCode', ${quotes.has("taxLines", "taxCode") ? `x.${taxLines("taxCode")}` : "null"}) order by x.${taxLines("taxRateBps")}), '[]'::jsonb)
|
|
87070
|
+
into v_lines
|
|
87071
|
+
from ${quotes.table("taxLines")} x where x.${taxLines("parent")} = v_quote.${q("id")} and x.${taxLines("discount")} <> 0;` : "";
|
|
87072
|
+
const quoteDiscounts = ["discountBps", "discountAmount"].filter((column) => quotes.has("quotes", column));
|
|
87073
|
+
const headerDiscount = quoteDiscounts.length > 0 && quoteDiscounts.every(has);
|
|
87074
|
+
const issuedDeposits = (alias) => `${originIs(alias)} and ${isDeposit(alias) === "" ? "false" : `(${isDeposit(alias)})`} and ${st(`${alias}.${i("status")}`, ["draft", "void"], true)}`;
|
|
87075
|
+
const discount = headerDiscount ? `
|
|
87076
|
+
if ${n.appTotals || !deposits ? "true" : `not exists (select 1 from ${t("invoices")} d where ${issuedDeposits("d")})`} then
|
|
87077
|
+
v_header := jsonb_build_object(${quoteDiscounts.map((column) => `${sqlString(column)}, v_quote.${q(column)}${column === "discountAmount" ? "::text" : ""}`).join(", ")});
|
|
87078
|
+
else${discountLines === "" ? "\n null;" : discountLines.replaceAll("\n", "\n ")}
|
|
87079
|
+
end if;` : discountLines;
|
|
87080
|
+
const party = (kind) => (kind === "company" ? company : contact) && quoteParty(quotes, kind) !== void 0 ? `case when v_quote.${q(`${kind}Id`)} is null then null else jsonb_build_object('type', ${quotePartyType(quotes, kind, "v_quote.")}, 'id', v_quote.${q(`${kind}Id`)}) end` : "null";
|
|
87081
|
+
const create = `${fn("create_invoice")}(v_quote.${q("tenant")}, jsonb_build_object(
|
|
87082
|
+
'title', v_quote.${q("title")}, 'currency', v_quote.${q("currency")}, 'depositBps', ${has("depositBps") ? "invoice_from_quote.deposit_bps" : "null"},${has("depositAmount") ? " 'depositAmount', invoice_from_quote.deposit_amount::text," : ""}${has("pricesIncludeTax") ? ` 'pricesIncludeTax', ${inclusive},` : ""}
|
|
87083
|
+
'company', ${party("company")},
|
|
87084
|
+
'contact', ${party("contact")},
|
|
87085
|
+
'origin', jsonb_build_object('type', 'quote', 'id', v_quote.${q("id")}::text))${headerDiscount ? " || v_header" : ""}${headerFieldsSql}, v_lines)`;
|
|
87086
|
+
const amountLine = amountDeposits ? `
|
|
87087
|
+
elsif invoice_from_quote.deposit_amount is not null then
|
|
87088
|
+
v_lines := jsonb_build_array(jsonb_build_object(
|
|
87089
|
+
'description', 'Deposit of ' || v_quote.${q("identifier")},
|
|
87090
|
+
'quantity', 1,
|
|
87091
|
+
'unitAmount', (case when ${inclusive} or v_quote.${q("total")} = 0 then invoice_from_quote.deposit_amount
|
|
87092
|
+
else round(invoice_from_quote.deposit_amount::numeric * v_quote.${q("subtotal")} / v_quote.${q("total")})::bigint end)::text,
|
|
87093
|
+
'taxRateBps', ${blendedRate}));` : "";
|
|
87094
|
+
const body = () => `
|
|
87095
|
+
if invoice_from_quote.deposit_bps is null${amountDeposits ? " and invoice_from_quote.deposit_amount is null" : ""} then
|
|
87096
|
+
select * into v_row from ${t("invoices")} x
|
|
87097
|
+
where ${originIs("x")}
|
|
87098
|
+
and ${notDeposit("x")}${st(`x.${i("status")}`, ["void"], true)} and ${kd(`x.${i("kind")}`, ["invoice"])}
|
|
87099
|
+
limit 1;
|
|
87100
|
+
if v_row.${i("id")} is not null then
|
|
87101
|
+
return ${row("v_row")};
|
|
87102
|
+
end if;
|
|
87103
|
+
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,
|
|
87104
|
+
'discountBps', ${lineColumn(quotes, "lines", "x", "discountBps")}, 'taxRateBps', ${lineColumn(quotes, "lines", "x", "taxRateBps")}, 'taxCode', ${lineColumn(quotes, "lines", "x", "taxCode")},
|
|
87105
|
+
'product', case when ${lineColumn(quotes, "lines", "x", "productType")} is null then null else jsonb_build_object('type', ${lineColumn(quotes, "lines", "x", "productType")}, 'id', ${lineColumn(quotes, "lines", "x", "productId")}) end${lineFieldsSql}
|
|
87106
|
+
) order by x.${ql("position")}), '[]'::jsonb) into v_lines
|
|
87107
|
+
from ${quotes.table("lines")} x where x.${ql("parent")} = v_quote.${q("id")} and ${countedLine(quotes, "lines", "x")};${discount}${deposits ? `
|
|
87108
|
+
select v_lines || coalesce(jsonb_agg(jsonb_build_object('description', 'Deposit ' || d.${i("identifier")}, 'quantity', 1, 'unitAmount', (-(case when ${inclusive} then d.${i("total")} else d.${i("subtotal")} end))::text,
|
|
87109
|
+
'taxRateBps', case when d.${i("subtotal")} = 0 then 0 else round(d.${i("taxTotal")} * 10000.0 / d.${i("subtotal")})::integer end)), '[]'::jsonb)
|
|
87110
|
+
into v_lines
|
|
87111
|
+
from ${t("invoices")} d
|
|
87112
|
+
where ${issuedDeposits("d")};` : ""}${amountLine}
|
|
87113
|
+
else
|
|
87114
|
+
v_lines := jsonb_build_array(jsonb_build_object(
|
|
87115
|
+
'description', 'Deposit ' || (invoice_from_quote.deposit_bps / 100.0)::text || '% of ' || v_quote.${q("identifier")},
|
|
87116
|
+
'quantity', 1,
|
|
87117
|
+
'unitAmount', round(${base("v_quote")}::numeric * invoice_from_quote.deposit_bps / 10000)::bigint::text,
|
|
87118
|
+
'taxRateBps', ${blendedRate}));
|
|
87119
|
+
end if;
|
|
87120
|
+
v_row := null;${kind === void 0 ? `
|
|
87121
|
+
return ${create};` : `
|
|
87122
|
+
v_made := ${create};
|
|
87123
|
+
if invoice_from_quote.deposit_bps is not null or invoice_from_quote.deposit_amount is not null then
|
|
87124
|
+
update ${t("invoices")} x set ${i("kind")} = ${ctx.cast("invoices", "kind", sqlString(kind))} where x.${i("id")} = (v_made ->> 'id')::uuid;
|
|
87125
|
+
return (select ${row("x")} from ${t("invoices")} x where x.${i("id")} = (v_made ->> 'id')::uuid);
|
|
87126
|
+
end if;
|
|
87127
|
+
return v_made;`}`;
|
|
87128
|
+
return `
|
|
87129
|
+
-- An invoice from an accepted quote. With deposit_bps (2000 for 20%) it is
|
|
87130
|
+
-- a deposit invoice for that share of the quote${amountDeposits ? ", and with deposit_amount\n-- one for that amount, tax included" : ""}; without, the full invoice,
|
|
87131
|
+
-- which subtracts the deposits already issued and is made once per quote.${headerDiscount ? "\n-- The quote's document discount stays on the invoice's header." : ""}
|
|
87132
|
+
drop function if exists ${fn("invoice_from_quote")}(uuid, integer);
|
|
87133
|
+
create or replace function ${fn("invoice_from_quote")}(quote uuid, deposit_bps integer, deposit_amount bigint default null)
|
|
87134
|
+
returns jsonb
|
|
87135
|
+
language plpgsql
|
|
87136
|
+
security definer
|
|
87137
|
+
set search_path = ''
|
|
87138
|
+
as $$
|
|
87139
|
+
declare
|
|
87140
|
+
v_quote ${quotes.table("quotes")};
|
|
87141
|
+
v_row ${t("invoices")};
|
|
87142
|
+
v_lines jsonb;${headerDiscount ? "\n v_header jsonb := '{}'::jsonb;" : ""}${kind === void 0 ? "" : "\n v_made jsonb;"}
|
|
87143
|
+
begin
|
|
87144
|
+
select * into v_quote from ${quotes.table("quotes")} x where x.${q("id")} = invoice_from_quote.quote;
|
|
87145
|
+
if v_quote.${q("id")} is null or not (${n.service} or ${ctx.scope.can(`v_quote.${q("tenant")}`, n.create)}) then
|
|
87146
|
+
${fail$1("INVOICE_ORIGIN_NOT_FOUND", "no such quote you can invoice", "P0002")}
|
|
87147
|
+
end if;
|
|
87148
|
+
if ${quotes.is("quotes", "status", `v_quote.${q("status")}`, ["accepted"], true)} then
|
|
87149
|
+
${fail$1("INVOICE_QUOTE_NOT_ACCEPTED", "only an accepted quote is invoiced", "55000")}
|
|
87150
|
+
end if;
|
|
87151
|
+
if invoice_from_quote.deposit_bps is not null and (invoice_from_quote.deposit_bps <= 0 or invoice_from_quote.deposit_bps >= 10000) then
|
|
87152
|
+
${fail$1("INVOICE_DEPOSIT_INVALID", "a deposit is between 0 and 100 percent", "22023")}
|
|
87153
|
+
end if;
|
|
87154
|
+
if invoice_from_quote.deposit_bps is not null and invoice_from_quote.deposit_amount is not null then
|
|
87155
|
+
${fail$1("INVOICE_DEPOSIT_INVALID", "a deposit is a share (deposit_bps) or an amount (deposit_amount), not both", "22023")}
|
|
87156
|
+
end if;
|
|
87157
|
+
if invoice_from_quote.deposit_amount is not null and (invoice_from_quote.deposit_amount <= 0 or invoice_from_quote.deposit_amount > v_quote.${q("total")}) then
|
|
87158
|
+
${fail$1("INVOICE_DEPOSIT_INVALID", "a deposit amount is positive and at most the quote's total", "22023")}
|
|
87159
|
+
end if;${refuse(bpsDeposits, "invoice_from_quote.deposit_bps", "DEPOSIT", "deposit column")}${refuse(amountDeposits, "invoice_from_quote.deposit_amount", "DEPOSIT", "deposit amount column")}${origin === void 0 ? `
|
|
87160
|
+
${fail$1("INVOICE_ORIGIN_UNSUPPORTED", "this invoices table has no origin columns, so a quote can't be invoiced once", "22023")}` : body()}
|
|
87161
|
+
end;
|
|
87162
|
+
$$;
|
|
87163
|
+
${userGrant(`${fn("invoice_from_quote")}(uuid, integer, bigint)`)}
|
|
87164
|
+
`;
|
|
87165
|
+
}
|
|
86535
87166
|
// src/sql/modules/invoices-functions.ts
|
|
87167
|
+
/**
|
|
87168
|
+
* Invoice columns a config opts into by naming them in
|
|
87169
|
+
* `blocks.invoices.columns.invoices`, so app tables made before them keep
|
|
87170
|
+
* working: a fixed deposit and a header discount.
|
|
87171
|
+
*/
|
|
87172
|
+
const OPT_IN = [
|
|
87173
|
+
"depositAmount",
|
|
87174
|
+
"discountBps",
|
|
87175
|
+
"discountAmount"
|
|
87176
|
+
];
|
|
87177
|
+
/** Whether the invoices table has the opt-in column `logical`. */
|
|
87178
|
+
function invoiceOptIn(ctx, logical) {
|
|
87179
|
+
return typeof ctx.config.columns["invoices"]?.[logical] === "string" && ctx.has("invoices", logical);
|
|
87180
|
+
}
|
|
86536
87181
|
/** `options.chargeExtraColumns`: app columns of the charges table. */
|
|
86537
87182
|
const chargeExtraColumns = (ctx) => ctx.hasTable("charges") ? ctx.extraColumns("charges", ["fields"], "chargeExtraColumns") : [];
|
|
86538
87183
|
/**
|
|
@@ -86565,7 +87210,7 @@ function invoiceFunctions(ctx, n) {
|
|
|
86565
87210
|
const company = invoiceParty(ctx, "company");
|
|
86566
87211
|
const contact = invoiceParty(ctx, "contact");
|
|
86567
87212
|
const origin = invoiceParty(ctx, "origin");
|
|
86568
|
-
const has = (logical) => ctx.has("invoices", logical);
|
|
87213
|
+
const has = (logical) => OPT_IN.includes(logical) ? invoiceOptIn(ctx, logical) : ctx.has("invoices", logical);
|
|
86569
87214
|
const charges = ctx.hasTable("charges");
|
|
86570
87215
|
const ch = (column) => c("charges", column);
|
|
86571
87216
|
const physical = (logical) => ctx.colName("invoices", logical);
|
|
@@ -86588,7 +87233,9 @@ function invoiceFunctions(ctx, n) {
|
|
|
86588
87233
|
"number",
|
|
86589
87234
|
"paidTotal",
|
|
86590
87235
|
"creditedTotal",
|
|
86591
|
-
...Object.keys(TOTAL_COLUMNS)
|
|
87236
|
+
...Object.keys(TOTAL_COLUMNS),
|
|
87237
|
+
"depositAmount",
|
|
87238
|
+
"discountAmount"
|
|
86592
87239
|
].filter(has);
|
|
86593
87240
|
const int8 = amounts.map(i);
|
|
86594
87241
|
const int8Text8 = Object.fromEntries(amounts.map((logical) => [logical, (value) => `${value}::text`]));
|
|
@@ -86656,10 +87303,21 @@ function invoiceFunctions(ctx, n) {
|
|
|
86656
87303
|
returning * into ${alias};`;
|
|
86657
87304
|
const keep = (logical, value, key) => has(logical) ? `,\n ${i(logical)} = case when update_invoice.attrs ? ${sqlString(key)} then ${value} else x.${i(logical)} end` : "";
|
|
86658
87305
|
const relations = ctx.installed("relations") ? ctx.of("relations") : void 0;
|
|
87306
|
+
const discounts = has("discountBps") || has("discountAmount");
|
|
87307
|
+
const recountKeys = [
|
|
87308
|
+
"pricesIncludeTax",
|
|
87309
|
+
"discountBps",
|
|
87310
|
+
"discountAmount"
|
|
87311
|
+
].filter(has);
|
|
87312
|
+
const headerRefusals = (attrs) => [
|
|
87313
|
+
refuse(has("depositAmount"), `${attrs} ->> 'depositAmount'`, "DEPOSIT", "deposit amount column"),
|
|
87314
|
+
refuse(has("discountBps"), `nullif(${attrs} ->> 'discountBps', '0')`, "DISCOUNT", "discount column"),
|
|
87315
|
+
refuse(has("discountAmount"), `nullif(${attrs} ->> 'discountAmount', '0')`, "DISCOUNT", "discount amount column")
|
|
87316
|
+
].join("");
|
|
86659
87317
|
const updateInvoiceSql = () => `
|
|
86660
87318
|
-- Changes a draft's header. attrs: title, company and contact ({ type, id },
|
|
86661
87319
|
-- null clears), termsDays, note, depositBps, pricesIncludeTax and the extra
|
|
86662
|
-
-- columns by name. A key left out keeps its value.
|
|
87320
|
+
-- columns by name${discounts ? ", and the header discount (discountBps, discountAmount)" : ""}. A key left out keeps its value.
|
|
86663
87321
|
create or replace function ${fn("update_invoice")}(invoice uuid, attrs jsonb)
|
|
86664
87322
|
returns jsonb
|
|
86665
87323
|
language plpgsql
|
|
@@ -86683,17 +87341,17 @@ begin
|
|
|
86683
87341
|
if jsonb_typeof(update_invoice.attrs) is distinct from 'object'
|
|
86684
87342
|
or (update_invoice.attrs ? 'title' and nullif(trim(update_invoice.attrs ->> 'title'), '') is null) then
|
|
86685
87343
|
${fail$1("INVOICE_ATTRS_INVALID", "attrs is an object, and a title isn't empty", "22023")}
|
|
86686
|
-
end if;${checkParty("COMPANY", "v_company_type", "v_company_id", `v_row.${i("tenant")}`)}${checkParty("CONTACT", "v_contact_type", "v_contact_id", `v_row.${i("tenant")}`)}${refuse(has("note"), "update_invoice.attrs ->> 'note'", "NOTE", "note column")}${refuse(has("depositBps"), "update_invoice.attrs ->> 'depositBps'", "DEPOSIT", "deposit column")}${refuse(has("pricesIncludeTax"), "nullif(update_invoice.attrs ->> 'pricesIncludeTax', 'false')", "PRICING", "prices_include_tax column")}
|
|
87344
|
+
end if;${checkParty("COMPANY", "v_company_type", "v_company_id", `v_row.${i("tenant")}`)}${checkParty("CONTACT", "v_contact_type", "v_contact_id", `v_row.${i("tenant")}`)}${refuse(has("note"), "update_invoice.attrs ->> 'note'", "NOTE", "note column")}${refuse(has("depositBps"), "update_invoice.attrs ->> 'depositBps'", "DEPOSIT", "deposit column")}${refuse(has("pricesIncludeTax"), "nullif(update_invoice.attrs ->> 'pricesIncludeTax', 'false')", "PRICING", "prices_include_tax column")}${headerRefusals("update_invoice.attrs")}
|
|
86687
87345
|
begin
|
|
86688
87346
|
update ${t("invoices")} x set
|
|
86689
|
-
${i("title")} = case when update_invoice.attrs ? 'title' then trim(update_invoice.attrs ->> 'title') else x.${i("title")} end${keep("companyType", "case when v_company_id is null then null else v_company_type end", "company")}${company === void 0 ? "" : keep("companyId", partyId("company", "v_company_id"), "company")}${keep("contactType", "case when v_contact_id is null then null else v_contact_type end", "contact")}${contact === void 0 ? "" : keep("contactId", partyId("contact", "v_contact_id"), "contact")}${keep("termsDays", "(update_invoice.attrs ->> 'termsDays')::integer", "termsDays")}${keep("note", "update_invoice.attrs ->> 'note'", "note")}${keep("depositBps", "(update_invoice.attrs ->> 'depositBps')::integer", "depositBps")}${keep("pricesIncludeTax", "coalesce((update_invoice.attrs ->> 'pricesIncludeTax')::boolean, false)", "pricesIncludeTax")},
|
|
87347
|
+
${i("title")} = case when update_invoice.attrs ? 'title' then trim(update_invoice.attrs ->> 'title') else x.${i("title")} end${keep("companyType", "case when v_company_id is null then null else v_company_type end", "company")}${company === void 0 ? "" : keep("companyId", partyId("company", "v_company_id"), "company")}${keep("contactType", "case when v_contact_id is null then null else v_contact_type end", "contact")}${contact === void 0 ? "" : keep("contactId", partyId("contact", "v_contact_id"), "contact")}${keep("termsDays", "(update_invoice.attrs ->> 'termsDays')::integer", "termsDays")}${keep("note", "update_invoice.attrs ->> 'note'", "note")}${keep("depositBps", "(update_invoice.attrs ->> 'depositBps')::integer", "depositBps")}${keep("pricesIncludeTax", "coalesce((update_invoice.attrs ->> 'pricesIncludeTax')::boolean, false)", "pricesIncludeTax")}${keep("depositAmount", "(update_invoice.attrs ->> 'depositAmount')::bigint", "depositAmount")}${keep("discountBps", "coalesce((update_invoice.attrs ->> 'discountBps')::integer, 0)", "discountBps")}${keep("discountAmount", "coalesce((update_invoice.attrs ->> 'discountAmount')::bigint, 0)", "discountAmount")},
|
|
86690
87348
|
${i("updatedAt")} = now()${updateExtraColumns(t("invoices"), n.extras, "update_invoice.attrs")}
|
|
86691
87349
|
where x.${i("id")} = v_row.${i("id")}
|
|
86692
87350
|
returning * into v_row;
|
|
86693
|
-
exception when check_violation or invalid_text_representation or not_null_violation then
|
|
87351
|
+
exception when check_violation or invalid_text_representation or not_null_violation${discounts || has("depositAmount") ? " or numeric_value_out_of_range" : ""} then
|
|
86694
87352
|
${fail$1("INVOICE_ATTRS_INVALID", "an invoice field has an invalid value", "22023")}
|
|
86695
|
-
end;${n.appTotals ||
|
|
86696
|
-
if update_invoice.attrs ?
|
|
87353
|
+
end;${n.appTotals || recountKeys.length === 0 ? "" : `
|
|
87354
|
+
if ${recountKeys.map((key) => `update_invoice.attrs ? ${sqlString(key)}`).join(" or ")} then
|
|
86697
87355
|
perform ${fn("set_invoice_lines_recount")}(v_row.${i("id")});
|
|
86698
87356
|
end if;`}
|
|
86699
87357
|
${record("invoice.updated", "v_row")}
|
|
@@ -86730,84 +87388,16 @@ end;
|
|
|
86730
87388
|
$$;
|
|
86731
87389
|
${userGrant(`${fn("delete_invoice")}(uuid)`)}
|
|
86732
87390
|
`;
|
|
86733
|
-
const
|
|
86734
|
-
|
|
86735
|
-
|
|
86736
|
-
|
|
86737
|
-
|
|
86738
|
-
|
|
86739
|
-
|
|
86740
|
-
|
|
86741
|
-
|
|
86742
|
-
|
|
86743
|
-
'taxRateBps', x.${taxLines("taxRateBps")}, 'taxCode', ${quotes.has("taxLines", "taxCode") ? `x.${taxLines("taxCode")}` : "null"}) order by x.${taxLines("taxRateBps")}), '[]'::jsonb)
|
|
86744
|
-
into v_lines
|
|
86745
|
-
from ${quotes.table("taxLines")} x where x.${taxLines("parent")} = v_quote.${q("id")} and x.${taxLines("discount")} <> 0;` : "";
|
|
86746
|
-
const party = (kind) => (kind === "company" ? company : contact) && quotes.has("quotes", `${kind}Type`) && quotes.has("quotes", `${kind}Id`) ? `case when v_quote.${q(`${kind}Id`)} is null then null else jsonb_build_object('type', v_quote.${q(`${kind}Type`)}, 'id', v_quote.${q(`${kind}Id`)}) end` : "null";
|
|
86747
|
-
const originIs = (alias) => `${origin === "pair" ? `${alias}.${i("originType")} = 'quote' and ` : ""}${alias}.${i("originId")}::text = v_quote.${q("id")}::text`;
|
|
86748
|
-
const body = () => `
|
|
86749
|
-
if invoice_from_quote.deposit_bps is null then
|
|
86750
|
-
select * into v_row from ${t("invoices")} x
|
|
86751
|
-
where ${originIs("x")}
|
|
86752
|
-
and ${deposits ? `x.${i("depositBps")} is null and ` : ""}${st(`x.${i("status")}`, ["void"], true)} and ${kd(`x.${i("kind")}`, ["invoice"])}
|
|
86753
|
-
limit 1;
|
|
86754
|
-
if v_row.${i("id")} is not null then
|
|
86755
|
-
return ${row("v_row")};
|
|
86756
|
-
end if;
|
|
86757
|
-
select coalesce(jsonb_agg(jsonb_build_object('description', x.${ql("description")}, 'quantity', x.${ql("quantity")}${declared(quotes, "lines", "periods") ? ` * coalesce(x.${ql("periods")}, 1)` : ""}, 'unitAmount', x.${ql("unitAmount")}::text,
|
|
86758
|
-
'discountBps', ${lineColumn(quotes, "lines", "x", "discountBps")}, 'taxRateBps', ${lineColumn(quotes, "lines", "x", "taxRateBps")}, 'taxCode', ${lineColumn(quotes, "lines", "x", "taxCode")},
|
|
86759
|
-
'product', case when ${lineColumn(quotes, "lines", "x", "productType")} is null then null else jsonb_build_object('type', ${lineColumn(quotes, "lines", "x", "productType")}, 'id', ${lineColumn(quotes, "lines", "x", "productId")}) end
|
|
86760
|
-
) order by x.${ql("position")}), '[]'::jsonb) into v_lines
|
|
86761
|
-
from ${quotes.table("lines")} x where x.${ql("parent")} = v_quote.${q("id")} and ${countedLine(quotes, "lines", "x")};${discountLines}${deposits ? `
|
|
86762
|
-
select v_lines || coalesce(jsonb_agg(jsonb_build_object('description', 'Deposit ' || d.${i("identifier")}, 'quantity', 1, 'unitAmount', (-(case when ${inclusive} then d.${i("total")} else d.${i("subtotal")} end))::text,
|
|
86763
|
-
'taxRateBps', case when d.${i("subtotal")} = 0 then 0 else round(d.${i("taxTotal")} * 10000.0 / d.${i("subtotal")})::integer end)), '[]'::jsonb)
|
|
86764
|
-
into v_lines
|
|
86765
|
-
from ${t("invoices")} d
|
|
86766
|
-
where ${originIs("d")} and d.${i("depositBps")} is not null and ${st(`d.${i("status")}`, ["draft", "void"], true)};` : ""}
|
|
86767
|
-
else
|
|
86768
|
-
v_lines := jsonb_build_array(jsonb_build_object(
|
|
86769
|
-
'description', 'Deposit ' || (invoice_from_quote.deposit_bps / 100.0)::text || '% of ' || v_quote.${q("identifier")},
|
|
86770
|
-
'quantity', 1,
|
|
86771
|
-
'unitAmount', round(${base("v_quote")}::numeric * invoice_from_quote.deposit_bps / 10000)::bigint::text,
|
|
86772
|
-
'taxRateBps', case when v_quote.${q("subtotal")} = 0 then 0 else round(v_quote.${q("taxTotal")} * 10000.0 / v_quote.${q("subtotal")})::integer end));
|
|
86773
|
-
end if;
|
|
86774
|
-
v_row := null;
|
|
86775
|
-
return ${fn("create_invoice")}(v_quote.${q("tenant")}, jsonb_build_object(
|
|
86776
|
-
'title', v_quote.${q("title")}, 'currency', v_quote.${q("currency")}, 'depositBps', invoice_from_quote.deposit_bps,${has("pricesIncludeTax") ? ` 'pricesIncludeTax', ${inclusive},` : ""}
|
|
86777
|
-
'company', ${party("company")},
|
|
86778
|
-
'contact', ${party("contact")},
|
|
86779
|
-
'origin', jsonb_build_object('type', 'quote', 'id', v_quote.${q("id")}::text)), v_lines);`;
|
|
86780
|
-
return `
|
|
86781
|
-
-- An invoice from an accepted quote. With deposit_bps (2000 for 20%) it is
|
|
86782
|
-
-- a deposit invoice for that share of the quote; without, the full invoice,
|
|
86783
|
-
-- which subtracts the deposits already issued and is made once per quote.
|
|
86784
|
-
create or replace function ${fn("invoice_from_quote")}(quote uuid, deposit_bps integer)
|
|
86785
|
-
returns jsonb
|
|
86786
|
-
language plpgsql
|
|
86787
|
-
security definer
|
|
86788
|
-
set search_path = ''
|
|
86789
|
-
as $$
|
|
86790
|
-
declare
|
|
86791
|
-
v_quote ${quotes.table("quotes")};
|
|
86792
|
-
v_row ${t("invoices")};
|
|
86793
|
-
v_lines jsonb;
|
|
86794
|
-
begin
|
|
86795
|
-
select * into v_quote from ${quotes.table("quotes")} x where x.${q("id")} = invoice_from_quote.quote;
|
|
86796
|
-
if v_quote.${q("id")} is null or not (${n.service} or ${ctx.scope.can(`v_quote.${q("tenant")}`, n.create)}) then
|
|
86797
|
-
${fail$1("INVOICE_ORIGIN_NOT_FOUND", "no such quote you can invoice", "P0002")}
|
|
86798
|
-
end if;
|
|
86799
|
-
if ${quotes.is("quotes", "status", `v_quote.${q("status")}`, ["accepted"], true)} then
|
|
86800
|
-
${fail$1("INVOICE_QUOTE_NOT_ACCEPTED", "only an accepted quote is invoiced", "55000")}
|
|
86801
|
-
end if;
|
|
86802
|
-
if invoice_from_quote.deposit_bps is not null and (invoice_from_quote.deposit_bps <= 0 or invoice_from_quote.deposit_bps >= 10000) then
|
|
86803
|
-
${fail$1("INVOICE_DEPOSIT_INVALID", "a deposit is between 0 and 100 percent", "22023")}
|
|
86804
|
-
end if;${refuse(deposits, "invoice_from_quote.deposit_bps", "DEPOSIT", "deposit column")}${origin === void 0 ? `
|
|
86805
|
-
${fail$1("INVOICE_ORIGIN_UNSUPPORTED", "this invoices table has no origin columns, so a quote can't be invoiced once", "22023")}` : body()}
|
|
86806
|
-
end;
|
|
86807
|
-
$$;
|
|
86808
|
-
${userGrant(`${fn("invoice_from_quote")}(uuid, integer)`)}
|
|
86809
|
-
`;
|
|
86810
|
-
})();
|
|
87391
|
+
const fromQuote = invoiceFromQuote(ctx, n, {
|
|
87392
|
+
has,
|
|
87393
|
+
row,
|
|
87394
|
+
refuse,
|
|
87395
|
+
st,
|
|
87396
|
+
kd,
|
|
87397
|
+
origin,
|
|
87398
|
+
company: company !== void 0,
|
|
87399
|
+
contact: contact !== void 0
|
|
87400
|
+
});
|
|
86811
87401
|
const chargeColumns = [
|
|
86812
87402
|
ch("tenant"),
|
|
86813
87403
|
ch("invoice"),
|
|
@@ -86909,7 +87499,7 @@ ${userGrant(`${fn("remove_invoice_charge")}(uuid, jsonb)`)}
|
|
|
86909
87499
|
return `
|
|
86910
87500
|
-- Creates a draft invoice. attrs: title (required), currency, company and
|
|
86911
87501
|
-- contact ({ type, id }), termsDays, note, origin ({ type, id }) and the
|
|
86912
|
-
-- extra columns by name.
|
|
87502
|
+
-- extra columns by name${discounts || has("depositAmount") ? ", with depositAmount and the header discount (discountBps,\n-- discountAmount) when the table has them" : ""}.
|
|
86913
87503
|
create or replace function ${fn("create_invoice")}(tenant ${ctx.idType}, attrs jsonb, lines jsonb)
|
|
86914
87504
|
returns jsonb
|
|
86915
87505
|
language plpgsql
|
|
@@ -86931,21 +87521,24 @@ begin
|
|
|
86931
87521
|
end if;${checkParty("COMPANY", "v_company_type", "v_company_id", "create_invoice.tenant")}${checkParty("CONTACT", "v_contact_type", "v_contact_id", "create_invoice.tenant")}${refuse(has("note"), "create_invoice.attrs ->> 'note'", "NOTE", "note column")}${refuse(origin !== void 0, "(create_invoice.attrs -> 'origin' ->> 'id')", "ORIGIN", "origin columns")}${origin === "fixed" ? `
|
|
86932
87522
|
if create_invoice.attrs -> 'origin' ->> 'id' is not null and (create_invoice.attrs -> 'origin' ->> 'type') is distinct from 'quote' then
|
|
86933
87523
|
${fail$1("INVOICE_ORIGIN_UNSUPPORTED", "this invoices table takes only a quote as the origin", "22023")}
|
|
86934
|
-
end if;` : ""}${refuse(has("depositBps"), "create_invoice.attrs ->> 'depositBps'", "DEPOSIT", "deposit column")}${refuse(has("pricesIncludeTax"), "nullif(create_invoice.attrs ->> 'pricesIncludeTax', 'false')", "PRICING", "prices_include_tax column")}
|
|
87524
|
+
end if;` : ""}${refuse(has("depositBps"), "create_invoice.attrs ->> 'depositBps'", "DEPOSIT", "deposit column")}${refuse(has("pricesIncludeTax"), "nullif(create_invoice.attrs ->> 'pricesIncludeTax', 'false')", "PRICING", "prices_include_tax column")}${headerRefusals("create_invoice.attrs")}
|
|
86935
87525
|
begin
|
|
86936
87526
|
insert into ${t("invoices")} (${i("tenant")}, ${i("title")}${also("companyType")}${also("companyId")}${also("contactType")}${also("contactId")}, ${i("currency")},
|
|
86937
|
-
${i("termsDays")}${also("note")}${also("originType")}${also("originId")}${also("depositBps")}${also("pricesIncludeTax")}${also("createdBy")}${insertExtraColumns(t("invoices"), n.extras, "create_invoice.attrs").columns})
|
|
87527
|
+
${i("termsDays")}${also("note")}${also("originType")}${also("originId")}${also("depositBps")}${also("depositAmount")}${also("discountBps")}${also("discountAmount")}${also("pricesIncludeTax")}${also("createdBy")}${insertExtraColumns(t("invoices"), n.extras, "create_invoice.attrs").columns})
|
|
86938
87528
|
values (${valueLines(" ", ["create_invoice.tenant", "trim(create_invoice.attrs ->> 'title')"], [present("companyType", "case when v_company_id is null then null else v_company_type end"), company === void 0 ? void 0 : partyId("company", "v_company_id")], [present("contactType", "case when v_contact_id is null then null else v_contact_type end"), contact === void 0 ? void 0 : partyId("contact", "v_contact_id")], ["upper(coalesce(create_invoice.attrs ->> 'currency', 'EUR'))", `case when create_invoice.attrs ? 'termsDays' then (create_invoice.attrs ->> 'termsDays')::integer else ${String(n.termsDays)} end`], [
|
|
86939
87529
|
present("note", "create_invoice.attrs ->> 'note'"),
|
|
86940
87530
|
present("originType", "create_invoice.attrs -> 'origin' ->> 'type'"),
|
|
86941
87531
|
present("originId", partyId("origin", "create_invoice.attrs -> 'origin' ->> 'id'"))
|
|
86942
87532
|
], [
|
|
86943
87533
|
present("depositBps", "(create_invoice.attrs ->> 'depositBps')::integer"),
|
|
87534
|
+
present("depositAmount", "(create_invoice.attrs ->> 'depositAmount')::bigint"),
|
|
87535
|
+
present("discountBps", "coalesce((create_invoice.attrs ->> 'discountBps')::integer, 0)"),
|
|
87536
|
+
present("discountAmount", "coalesce((create_invoice.attrs ->> 'discountAmount')::bigint, 0)"),
|
|
86944
87537
|
present("pricesIncludeTax", "coalesce((create_invoice.attrs ->> 'pricesIncludeTax')::boolean, false)"),
|
|
86945
87538
|
present("createdBy", "auth.uid()")
|
|
86946
87539
|
])}${insertExtraColumns(t("invoices"), n.extras, "create_invoice.attrs").values})
|
|
86947
87540
|
returning * into v_row;
|
|
86948
|
-
exception when check_violation or invalid_text_representation then
|
|
87541
|
+
exception when check_violation or invalid_text_representation${discounts || has("depositAmount") ? " or numeric_value_out_of_range" : ""} then
|
|
86949
87542
|
${fail$1("INVOICE_ATTRS_INVALID", "an invoice field has an invalid value", "22023")}
|
|
86950
87543
|
end;
|
|
86951
87544
|
if create_invoice.lines is not null then
|
|
@@ -86971,6 +87564,7 @@ ${updateInvoiceSql()}${lineItemsSql(ctx, {
|
|
|
86971
87564
|
frozen: st(`p.${i("status")}`, ["draft"], true),
|
|
86972
87565
|
extras: n.lineExtras,
|
|
86973
87566
|
totals: !n.appTotals,
|
|
87567
|
+
parentHas: has,
|
|
86974
87568
|
positionKey: ctx.flag("linePositionKey", true)
|
|
86975
87569
|
}, {
|
|
86976
87570
|
setter: "set_invoice_lines",
|
|
@@ -87063,11 +87657,13 @@ ${userGrant(`${fn("issue_invoice")}(uuid, date, date, jsonb)`)}
|
|
|
87063
87657
|
-- currency as a ledger transaction from the invoice's receivable account to
|
|
87064
87658
|
-- cash. A reference, such as a bank or payment provider id, is unique per
|
|
87065
87659
|
-- organization, so recording the same payment twice adds it once. actor:
|
|
87066
|
-
-- who recorded it, for the state
|
|
87660
|
+
-- who recorded it, and reason: why the status changes, for the state
|
|
87661
|
+
-- machine's history.
|
|
87067
87662
|
drop function if exists ${fn("record_invoice_payment")}(uuid, bigint, timestamptz, text, text);
|
|
87068
87663
|
drop function if exists ${fn("record_invoice_payment")}(uuid, bigint, text, timestamptz, text, text);
|
|
87069
87664
|
drop function if exists ${fn("record_invoice_payment")}(uuid, bigint, text, timestamptz, text, text, text);
|
|
87070
|
-
|
|
87665
|
+
drop function if exists ${fn("record_invoice_payment")}(uuid, bigint, text, timestamptz, text, text, text, jsonb);
|
|
87666
|
+
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, reason text default null)
|
|
87071
87667
|
returns jsonb
|
|
87072
87668
|
language plpgsql
|
|
87073
87669
|
security definer
|
|
@@ -87115,7 +87711,9 @@ begin
|
|
|
87115
87711
|
end if;
|
|
87116
87712
|
${ctx.hook("before_invoice_payment", [["uuid", `v_row.${i("id")}`], ["bigint", "record_invoice_payment.amount"]])}
|
|
87117
87713
|
v_was := v_row.${i("status")};
|
|
87714
|
+
${transitionReasonSql("record_invoice_payment.reason")}
|
|
87118
87715
|
v_payment := ${ledger.post("v_row", "record_invoice_payment.amount", "coalesce(record_invoice_payment.paid_at, now())", "record_invoice_payment.method", "v_reference", "nullif(trim(record_invoice_payment.note), '')")};${settle("v_row", afterWriteOff)}
|
|
87716
|
+
${transitionReasonSql()}
|
|
87119
87717
|
${record("invoice.payment_recorded", "v_row", `, 'paymentId', v_payment, 'amount', record_invoice_payment.amount::text, 'balance', ${balance("v_row")}::text`)}
|
|
87120
87718
|
if ${st(`v_row.${i("status")}`, ["paid"])} and ${st("v_was", ["paid"], true)} then
|
|
87121
87719
|
${record("invoice.paid", "v_row", `, 'total', v_row.${i("total")}::text`)}
|
|
@@ -87124,7 +87722,7 @@ begin
|
|
|
87124
87722
|
return ${row("v_row")};
|
|
87125
87723
|
end;
|
|
87126
87724
|
$$;
|
|
87127
|
-
${userGrant(`${fn("record_invoice_payment")}(uuid, bigint, text, timestamptz, text, text, text, jsonb)`)}
|
|
87725
|
+
${userGrant(`${fn("record_invoice_payment")}(uuid, bigint, text, timestamptz, text, text, text, jsonb, text)`)}
|
|
87128
87726
|
|
|
87129
87727
|
create or replace function ${fn("list_invoice_payments")}(invoice uuid)
|
|
87130
87728
|
returns jsonb
|
|
@@ -87465,12 +88063,13 @@ const NAMES$56 = {
|
|
|
87465
88063
|
"providerPaymentMethods",
|
|
87466
88064
|
"uniqueNumber",
|
|
87467
88065
|
"linePositionKey",
|
|
87468
|
-
"paymentsAfterWriteOff"
|
|
88066
|
+
"paymentsAfterWriteOff",
|
|
88067
|
+
"depositKind"
|
|
87469
88068
|
],
|
|
87470
88069
|
tables: {
|
|
87471
88070
|
invoices: {
|
|
87472
88071
|
name: "invoices",
|
|
87473
|
-
app: { unused: (ctx) => typeof ctx.config.columns["invoices"]?.[
|
|
88072
|
+
app: { unused: (ctx) => ["writeOffReason", ...OPT_IN].filter((column) => typeof ctx.config.columns["invoices"]?.[column] !== "string") },
|
|
87474
88073
|
lifecycle: {
|
|
87475
88074
|
tenant: "tenant",
|
|
87476
88075
|
export: true
|
|
@@ -87502,6 +88101,9 @@ const NAMES$56 = {
|
|
|
87502
88101
|
originType: "origin_type",
|
|
87503
88102
|
originId: "origin_id",
|
|
87504
88103
|
depositBps: "deposit_bps",
|
|
88104
|
+
depositAmount: "deposit_amount",
|
|
88105
|
+
discountBps: "discount_bps",
|
|
88106
|
+
discountAmount: "discount_amount",
|
|
87505
88107
|
pricesIncludeTax: "prices_include_tax",
|
|
87506
88108
|
createdBy: "created_by",
|
|
87507
88109
|
createdAt: "created_at",
|
|
@@ -87519,6 +88121,9 @@ const NAMES$56 = {
|
|
|
87519
88121
|
"originType",
|
|
87520
88122
|
"originId",
|
|
87521
88123
|
"depositBps",
|
|
88124
|
+
"depositAmount",
|
|
88125
|
+
"discountBps",
|
|
88126
|
+
"discountAmount",
|
|
87522
88127
|
"pricesIncludeTax",
|
|
87523
88128
|
"createdBy",
|
|
87524
88129
|
"listTotal",
|
|
@@ -87591,6 +88196,12 @@ ${renderPolicy(policy$1({
|
|
|
87591
88196
|
})}
|
|
87592
88197
|
` : "";
|
|
87593
88198
|
const column = (logical, definition) => ctx.has("invoices", logical) ? `\n ${i(logical)} ${definition},` : "";
|
|
88199
|
+
const optIn = {
|
|
88200
|
+
depositAmount: (name) => `bigint check (${name} > 0)`,
|
|
88201
|
+
discountBps: (name) => `integer not null default 0 check (${name} >= 0 and ${name} <= 10000)`,
|
|
88202
|
+
discountAmount: (name) => `bigint not null default 0 check (${name} >= 0)`
|
|
88203
|
+
};
|
|
88204
|
+
const added = OPT_IN.filter((logical) => invoiceOptIn(ctx, logical)).map((logical) => `\nalter table ${t("invoices")} add column if not exists ${i(logical)} ${optIn[logical](i(logical))};`).join("");
|
|
87594
88205
|
const index = (name, columns) => `\ncreate index if not exists ${ctx.naming.rename(name)} on ${t("invoices")} (${columns.map(i).join(", ")});`;
|
|
87595
88206
|
return `
|
|
87596
88207
|
create table if not exists ${t("invoices")} (
|
|
@@ -87617,7 +88228,7 @@ ${uniqueNumber === false ? "" : ` unique (${i("tenant")}, ${i("kind")}, ${i(uni
|
|
|
87617
88228
|
check (${i("status")} <> 'draft' or ${i("number")} is null),
|
|
87618
88229
|
check (${i("status")} in ('draft', 'void') or ${i("number")} is not null)${company === "pair" ? `,\n check ((${i("companyType")} is null) = (${i("companyId")} is null))` : ""}
|
|
87619
88230
|
);
|
|
87620
|
-
create index if not exists ${ctx.naming.rename("invoices_tenant_status_idx")} on ${t("invoices")} (${i("tenant")}, ${i("status")}, ${i("dueOn")});${origin === void 0 ? "" : index("invoices_origin_idx", origin === "pair" ? ["originType", "originId"] : ["originId"])}${index("invoices_original_idx", ["original"])}${company === void 0 ? "" : index("invoices_company_idx", company === "pair" ? ["companyType", "companyId"] : ["companyId"])}${addExtraColumns(t("invoices"), n.extras)}${uniqueNumber === false ? "" : appUniqueIndex(ctx, "invoices", [
|
|
88231
|
+
${added === "" ? "" : `${added.slice(1)}\n`}create index if not exists ${ctx.naming.rename("invoices_tenant_status_idx")} on ${t("invoices")} (${i("tenant")}, ${i("status")}, ${i("dueOn")});${origin === void 0 ? "" : index("invoices_origin_idx", origin === "pair" ? ["originType", "originId"] : ["originId"])}${index("invoices_original_idx", ["original"])}${company === void 0 ? "" : index("invoices_company_idx", company === "pair" ? ["companyType", "companyId"] : ["companyId"])}${addExtraColumns(t("invoices"), n.extras)}${uniqueNumber === false ? "" : appUniqueIndex(ctx, "invoices", [
|
|
87621
88232
|
"tenant",
|
|
87622
88233
|
"kind",
|
|
87623
88234
|
uniqueNumber
|
|
@@ -87655,6 +88266,17 @@ function invoiceTotals(ctx) {
|
|
|
87655
88266
|
if (totals !== "block" && totals !== "app") throw new TypeError("blocks.invoices.options.totals must be \"block\" or \"app\"");
|
|
87656
88267
|
return totals;
|
|
87657
88268
|
}
|
|
88269
|
+
/**
|
|
88270
|
+
* `options.depositKind`: the app value of the kind column that marks a deposit
|
|
88271
|
+
* invoice. It must be one the `invoice` label maps to, so the block treats a
|
|
88272
|
+
* deposit invoice as an invoice everywhere else.
|
|
88273
|
+
*/
|
|
88274
|
+
function depositKind(ctx) {
|
|
88275
|
+
const kind = ctx.option("depositKind");
|
|
88276
|
+
if (kind === void 0) return;
|
|
88277
|
+
if (typeof kind !== "string" || !ctx.appValues("invoices", "kind", "invoice").includes(kind)) throw new TypeError("blocks.invoices.options.depositKind must be one of the values blocks.invoices.values.invoices.kind.invoice maps to");
|
|
88278
|
+
return kind;
|
|
88279
|
+
}
|
|
87658
88280
|
function build$55(ctx) {
|
|
87659
88281
|
if (ctx.mode === "custom") return "";
|
|
87660
88282
|
const keys = moduleOperations("invoices");
|
|
@@ -87695,7 +88317,8 @@ function build$55(ctx) {
|
|
|
87695
88317
|
]),
|
|
87696
88318
|
lineExtras: lineExtraColumns(ctx),
|
|
87697
88319
|
chargeExtras: chargeExtraColumns(ctx),
|
|
87698
|
-
appTotals: invoiceTotals(ctx) === "app"
|
|
88320
|
+
appTotals: invoiceTotals(ctx) === "app",
|
|
88321
|
+
depositKind: depositKind(ctx)
|
|
87699
88322
|
};
|
|
87700
88323
|
return `${schemaPreamble(ctx)}
|
|
87701
88324
|
-- Invoices an organization sends its own customers: drafts with lines, a
|
|
@@ -87748,7 +88371,8 @@ function contract$48(ctx) {
|
|
|
87748
88371
|
"text",
|
|
87749
88372
|
"text",
|
|
87750
88373
|
"text",
|
|
87751
|
-
"jsonb"
|
|
88374
|
+
"jsonb",
|
|
88375
|
+
"text"
|
|
87752
88376
|
],
|
|
87753
88377
|
returns: "jsonb"
|
|
87754
88378
|
},
|
|
@@ -87820,7 +88444,11 @@ function contract$48(ctx) {
|
|
|
87820
88444
|
},
|
|
87821
88445
|
...ctx.installed("quotes") ? [{
|
|
87822
88446
|
name: "invoice_from_quote",
|
|
87823
|
-
args: [
|
|
88447
|
+
args: [
|
|
88448
|
+
"uuid",
|
|
88449
|
+
"integer",
|
|
88450
|
+
"bigint"
|
|
88451
|
+
],
|
|
87824
88452
|
returns: "jsonb"
|
|
87825
88453
|
}] : []
|
|
87826
88454
|
];
|
|
@@ -96194,7 +96822,7 @@ function windowOf(ctx) {
|
|
|
96194
96822
|
if (!WINDOW.test(window)) throw new TypeError("blocks.metrics.options.window must be an interval such as \"3 days\" or \"12 hours\"");
|
|
96195
96823
|
return window;
|
|
96196
96824
|
}
|
|
96197
|
-
const qualified$
|
|
96825
|
+
const qualified$6 = (table) => table.includes(".") ? table : `public.${table}`;
|
|
96198
96826
|
/**
|
|
96199
96827
|
* The metrics declared in `options.metrics`. A metric over a subject table with
|
|
96200
96828
|
* `deletedAt` skips soft-deleted rows unless `where` names that column or the
|
|
@@ -96203,7 +96831,7 @@ const qualified$5 = (table) => table.includes(".") ? table : `public.${table}`;
|
|
|
96203
96831
|
function declaredMetrics(ctx) {
|
|
96204
96832
|
return metricsOf(ctx.option("metrics")).map((metric) => {
|
|
96205
96833
|
if (metric.includeDeleted === true) return metric;
|
|
96206
|
-
const column = Object.values(ctx.subjects).find((entry) => entry.deletedAt !== void 0 && qualified$
|
|
96834
|
+
const column = Object.values(ctx.subjects).find((entry) => entry.deletedAt !== void 0 && qualified$6(entry.table) === qualified$6(metric.table))?.deletedAt;
|
|
96207
96835
|
if (column === void 0 || Object.hasOwn(metric.where ?? {}, column)) return metric;
|
|
96208
96836
|
return {
|
|
96209
96837
|
...metric,
|
|
@@ -101834,7 +102462,7 @@ function contract$40() {
|
|
|
101834
102462
|
const OAUTH_SERVER = {
|
|
101835
102463
|
name: "oauth-server",
|
|
101836
102464
|
title: "OAuth server",
|
|
101837
|
-
description: "Storage for an OAuth 2.1 authorization server: registered clients (RFC 7591) with hashed secrets, a grant per user and client, single-use authorization codes bound to a PKCE S256 challenge, device codes (RFC 8628) and a revocation list of access token jtis. It issues no tokens.
|
|
102465
|
+
description: "Storage for an OAuth 2.1 authorization server: registered clients (RFC 7591) with hashed secrets, a grant per user and client, single-use authorization codes bound to a PKCE S256 challenge, device codes (RFC 8628) and a revocation list of access token jtis. It issues no tokens. createOauthServer() in better-supabase/blocks/oauth-server hashes secrets and checks PKCE, and its isRevoked plugs into accessTokenResolver.",
|
|
101838
102466
|
requires: [],
|
|
101839
102467
|
integrates: ["outbox", "audit"],
|
|
101840
102468
|
target: "schema",
|
|
@@ -102701,7 +103329,7 @@ begin
|
|
|
102701
103329
|
end if;
|
|
102702
103330
|
return ${fn("order_from_document")}(v_quote.${q("tenant")}, v_attrs || jsonb_build_object(
|
|
102703
103331
|
'currency', v_quote.${q("currency")}, 'taxInclusive', ${inclusive},
|
|
102704
|
-
'subtotal', v_quote.${q("listTotal")}::text, 'discountTotal', v_quote.${q("discountTotal")}::text, 'shippingTotal', '0',
|
|
103332
|
+
'subtotal', v_quote.${q(quotes.has("quotes", "listTotal") ? "listTotal" : "subtotal")}::text, 'discountTotal', ${quotes.has("quotes", "discountTotal") ? `v_quote.${q("discountTotal")}::text` : "'0'"}, 'shippingTotal', '0',
|
|
102705
103333
|
'taxTotal', v_quote.${q("taxTotal")}::text, 'total', v_quote.${q("total")}::text,
|
|
102706
103334
|
'origin', jsonb_build_object('type', 'quote', 'id', v_quote.${q("id")}::text)),
|
|
102707
103335
|
v_lines, nullif(v_attrs ->> 'locationId', '')::uuid);
|
|
@@ -111158,7 +111786,7 @@ function guard$5(names, tenant) {
|
|
|
111158
111786
|
/** `options.extraColumns`, added to the promotions table. */
|
|
111159
111787
|
const promotionExtras = (ctx) => ctx.extraColumns("promotions");
|
|
111160
111788
|
/** Normalizes a shopper-typed code: trimmed and upper case. */
|
|
111161
|
-
const normalized = (code) => `upper(btrim(${code}))`;
|
|
111789
|
+
const normalized$1 = (code) => `upper(btrim(${code}))`;
|
|
111162
111790
|
function promotionFunctions(ctx, names) {
|
|
111163
111791
|
const { fn } = names;
|
|
111164
111792
|
const extras = promotionExtras(ctx);
|
|
@@ -111364,7 +111992,7 @@ declare
|
|
|
111364
111992
|
v_code text;
|
|
111365
111993
|
v_id uuid;
|
|
111366
111994
|
v_out jsonb := '[]';
|
|
111367
|
-
v_prefix text := coalesce(${normalized("create_promotion_codes.prefix")}, '');
|
|
111995
|
+
v_prefix text := coalesce(${normalized$1("create_promotion_codes.prefix")}, '');
|
|
111368
111996
|
v_bytes bytea;
|
|
111369
111997
|
v_attempts integer := 0;
|
|
111370
111998
|
begin
|
|
@@ -111387,7 +112015,7 @@ begin
|
|
|
111387
112015
|
end if;
|
|
111388
112016
|
if create_promotion_codes.codes is not null then
|
|
111389
112017
|
foreach v_code in array create_promotion_codes.codes loop
|
|
111390
|
-
v_code := ${normalized("v_code")};
|
|
112018
|
+
v_code := ${normalized$1("v_code")};
|
|
111391
112019
|
if v_code is null or v_code !~ '^[A-Z0-9_-]{3,40}$' then
|
|
111392
112020
|
${fail$1("PROMOTIONS_CODE_FORMAT", "a code has 3 to 40 letters, digits, dashes or underscores", "22023")}
|
|
111393
112021
|
end if;
|
|
@@ -111476,7 +112104,7 @@ begin
|
|
|
111476
112104
|
x.${p("usageLimit")} as usage_limit, x.${p("redemptions")} as used
|
|
111477
112105
|
into v_code
|
|
111478
112106
|
from ${codes} k join ${ctx.table("promotions")} x on x.${p("id")} = k.${k("promotion")}
|
|
111479
|
-
where k.${k("tenant")} = v_cart.tenant and k.${k("code")} = ${normalized("apply_promotion_code.code")}
|
|
112107
|
+
where k.${k("tenant")} = v_cart.tenant and k.${k("code")} = ${normalized$1("apply_promotion_code.code")}
|
|
111480
112108
|
and x.${p("active")} and (x.${p("startsAt")} is null or x.${p("startsAt")} <= now())
|
|
111481
112109
|
and (x.${p("endsAt")} is null or x.${p("endsAt")} > now());
|
|
111482
112110
|
if not found then
|
|
@@ -111516,7 +112144,7 @@ begin
|
|
|
111516
112144
|
end if;
|
|
111517
112145
|
delete from ${ctx.table("cartCodes")} x
|
|
111518
112146
|
where x.${cc("cart")} = remove_promotion_code.cart
|
|
111519
|
-
and x.${cc("code")} in (select k.${k("id")} from ${codes} k where k.${k("code")} = ${normalized("remove_promotion_code.code")});
|
|
112147
|
+
and x.${cc("code")} in (select k.${k("id")} from ${codes} k where k.${k("code")} = ${normalized$1("remove_promotion_code.code")});
|
|
111520
112148
|
return found;
|
|
111521
112149
|
end;
|
|
111522
112150
|
$$;
|
|
@@ -113921,7 +114549,11 @@ const NAMES$35 = {
|
|
|
113921
114549
|
"lineExtraColumns",
|
|
113922
114550
|
"lineRates",
|
|
113923
114551
|
"workingCopy",
|
|
113924
|
-
"versionLines"
|
|
114552
|
+
"versionLines",
|
|
114553
|
+
"versionLineExtraColumns",
|
|
114554
|
+
"totals",
|
|
114555
|
+
"resend",
|
|
114556
|
+
"notifications"
|
|
113925
114557
|
],
|
|
113926
114558
|
tables: {
|
|
113927
114559
|
quotes: {
|
|
@@ -113995,7 +114627,9 @@ const NAMES$35 = {
|
|
|
113995
114627
|
"depositRequired",
|
|
113996
114628
|
"depositDue",
|
|
113997
114629
|
"unpublishedChanges",
|
|
113998
|
-
"createdBy"
|
|
114630
|
+
"createdBy",
|
|
114631
|
+
"listTotal",
|
|
114632
|
+
"discountTotal"
|
|
113999
114633
|
],
|
|
114000
114634
|
typed: ["status"]
|
|
114001
114635
|
},
|
|
@@ -114096,7 +114730,7 @@ function tables$5(ctx, n) {
|
|
|
114096
114730
|
].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("");
|
|
114097
114731
|
const constraints = [
|
|
114098
114732
|
`unique (${q("tenant")}, ${q("number")}, ${q("revision")})`,
|
|
114099
|
-
...company ? [`check ((${q("companyType")} is null) = (${q("companyId")} is null))`] : [],
|
|
114733
|
+
...company === "pair" ? [`check ((${q("companyType")} is null) = (${q("companyId")} is null))`] : [],
|
|
114100
114734
|
...origin ? [`check ((${q("originType")} is null) = (${q("originId")} is null))`] : []
|
|
114101
114735
|
];
|
|
114102
114736
|
return `
|
|
@@ -114163,7 +114797,7 @@ create table if not exists ${t("versionLines")} (
|
|
|
114163
114797
|
${vl("quantity")} numeric(18, 4) not null,
|
|
114164
114798
|
${vl("unitAmount")} bigint not null,${vlColumn("periods", "integer not null default 1")}${vlColumn("discountBps", "integer not null default 0")}${vlColumn("taxRateBps", "integer not null default 0")}${vlColumn("taxCode", "text")}${vlColumn("section", "text")}${vlColumn("optional", "boolean not null default false")}${vlColumn("selected", "boolean not null default true")}${vlColumn("productType", "text")}${vlColumn("productId", "text")}
|
|
114165
114799
|
unique (${vl("version")}, ${vl("position")})
|
|
114166
|
-
)
|
|
114800
|
+
);${addExtraColumns(t("versionLines"), n.versionLineExtras)}
|
|
114167
114801
|
${lockModuleTable(ctx, "versionLines", { read: true })}
|
|
114168
114802
|
${renderPolicy(policy$1({
|
|
114169
114803
|
table: t("versionLines"),
|
|
@@ -114222,9 +114856,16 @@ create trigger ${frozen} before update on ${t("versions")}
|
|
|
114222
114856
|
for each row execute function better_supabase.${frozen.replaceAll("\"", "")}();
|
|
114223
114857
|
${versionLines}${taxLines}`;
|
|
114224
114858
|
}
|
|
114859
|
+
/** `options.totals`: who keeps a quote's totals. */
|
|
114860
|
+
function quoteTotals(ctx) {
|
|
114861
|
+
const totals = ctx.text("totals", "block");
|
|
114862
|
+
if (totals !== "block" && totals !== "app") throw new TypeError("blocks.quotes.options.totals must be \"block\" or \"app\"");
|
|
114863
|
+
return totals;
|
|
114864
|
+
}
|
|
114225
114865
|
function build$34(ctx) {
|
|
114226
114866
|
if (ctx.mode === "custom") return "";
|
|
114227
114867
|
const keys = moduleOperations("quotes");
|
|
114868
|
+
const finer = (action) => sqlString(ctx.config.permissions[action] ?? ctx.permissionKey("write", keys.write));
|
|
114228
114869
|
const validDays = ctx.number("validDays", 30);
|
|
114229
114870
|
if (!Number.isInteger(validDays) || validDays < 1) throw new TypeError("blocks.quotes.options.validDays must be a positive integer");
|
|
114230
114871
|
const n = {
|
|
@@ -114234,6 +114875,9 @@ function build$34(ctx) {
|
|
|
114234
114875
|
read: ctx.permission("read", keys.read),
|
|
114235
114876
|
write: ctx.permission("write", keys.write),
|
|
114236
114877
|
manage: ctx.permission("manage", keys.manage),
|
|
114878
|
+
send: finer("send"),
|
|
114879
|
+
decide: finer("decide"),
|
|
114880
|
+
withdraw: finer("withdraw"),
|
|
114237
114881
|
company: ctx.text("company", "company"),
|
|
114238
114882
|
contact: ctx.text("contact", "person"),
|
|
114239
114883
|
prefix: ctx.text("prefix", "Q-"),
|
|
@@ -114244,7 +114888,10 @@ function build$34(ctx) {
|
|
|
114244
114888
|
"token",
|
|
114245
114889
|
"fields"
|
|
114246
114890
|
]),
|
|
114247
|
-
lineExtras: lineExtraColumns(ctx)
|
|
114891
|
+
lineExtras: lineExtraColumns(ctx),
|
|
114892
|
+
versionLineExtras: versionLinesOn(ctx) ? ctx.extraColumns("versionLines", [], "versionLineExtraColumns") : [],
|
|
114893
|
+
appTotals: quoteTotals(ctx) === "app",
|
|
114894
|
+
resend: ctx.flag("resend", false)
|
|
114248
114895
|
};
|
|
114249
114896
|
return `${schemaPreamble(ctx)}
|
|
114250
114897
|
-- Quotes: line items, sections, optional lines, discounts and tax per rate,
|
|
@@ -114297,7 +114944,11 @@ function contract$32(ctx) {
|
|
|
114297
114944
|
},
|
|
114298
114945
|
{
|
|
114299
114946
|
name: "withdraw_quote",
|
|
114300
|
-
args: [
|
|
114947
|
+
args: [
|
|
114948
|
+
"uuid",
|
|
114949
|
+
"jsonb",
|
|
114950
|
+
"text"
|
|
114951
|
+
],
|
|
114301
114952
|
returns: "jsonb"
|
|
114302
114953
|
},
|
|
114303
114954
|
{
|
|
@@ -114312,7 +114963,7 @@ function contract$32(ctx) {
|
|
|
114312
114963
|
},
|
|
114313
114964
|
{
|
|
114314
114965
|
name: "portal_quote",
|
|
114315
|
-
args: ["uuid"],
|
|
114966
|
+
args: ["uuid", "jsonb"],
|
|
114316
114967
|
returns: "jsonb"
|
|
114317
114968
|
},
|
|
114318
114969
|
{
|
|
@@ -116232,14 +116883,48 @@ const NAMES$31 = {
|
|
|
116232
116883
|
}
|
|
116233
116884
|
} }
|
|
116234
116885
|
};
|
|
116886
|
+
const KIND_OPTIONS = [
|
|
116887
|
+
"inverse",
|
|
116888
|
+
"acyclic",
|
|
116889
|
+
"cardinality",
|
|
116890
|
+
"symmetric",
|
|
116891
|
+
"types"
|
|
116892
|
+
];
|
|
116893
|
+
/** `types.source` or `types.target` of a kind, checked. */
|
|
116894
|
+
function typeList(where, value) {
|
|
116895
|
+
if (value === void 0) return;
|
|
116896
|
+
const list = Array.isArray(value) ? value : [];
|
|
116897
|
+
const types = list.filter((type) => typeof type === "string" && NAME$1.test(type));
|
|
116898
|
+
if (types.length === 0 || types.length !== list.length) throw new TypeError(`${where} must be a non-empty list of subject types (lowercase letters, digits and underscores)`);
|
|
116899
|
+
return types;
|
|
116900
|
+
}
|
|
116901
|
+
/** `types` of a kind, checked. */
|
|
116902
|
+
function kindTypes(where, value) {
|
|
116903
|
+
if (value === void 0) return {
|
|
116904
|
+
sourceTypes: void 0,
|
|
116905
|
+
targetTypes: void 0
|
|
116906
|
+
};
|
|
116907
|
+
if (typeof value !== "object" || value === null || Array.isArray(value)) throw new TypeError(`${where} must be an object with source and target`);
|
|
116908
|
+
const entry = new Map(Object.entries(value));
|
|
116909
|
+
for (const key of entry.keys()) if (key !== "source" && key !== "target") throw new TypeError(`${where}.${key} is not an option. Options: source, target`);
|
|
116910
|
+
return {
|
|
116911
|
+
sourceTypes: typeList(`${where}.source`, entry.get("source")),
|
|
116912
|
+
targetTypes: typeList(`${where}.target`, entry.get("target"))
|
|
116913
|
+
};
|
|
116914
|
+
}
|
|
116235
116915
|
/**
|
|
116236
|
-
* `options.kinds
|
|
116237
|
-
*
|
|
116916
|
+
* `options.kinds` (or the defaults), then the kinds other blocks contribute
|
|
116917
|
+
* that the app doesn't name, checked: names, inverses that clash, and symmetric
|
|
116918
|
+
* kinds without direction.
|
|
116238
116919
|
*/
|
|
116239
116920
|
function relationKinds(ctx) {
|
|
116240
116921
|
const where = "blocks.relations.options.kinds";
|
|
116241
116922
|
const raw = ctx.option("kinds") ?? DEFAULT_RELATION_KINDS;
|
|
116242
116923
|
if (typeof raw !== "object" || raw === null || Array.isArray(raw)) throw new TypeError(`${where} must be an object of kind name to options`);
|
|
116924
|
+
const own = new Map(Object.entries(raw));
|
|
116925
|
+
const contributions = uniqueContributions("relations", ctx.contributions("relations"), (contribution) => contribution.kind).filter((contribution) => !own.has(contribution.kind));
|
|
116926
|
+
const contributed = contributions.map(({ kind, data: _data, ...entry }) => [kind, entry]);
|
|
116927
|
+
const checks = new Map(contributions.map((contribution) => [contribution.kind, contribution.data]));
|
|
116243
116928
|
const kinds = [];
|
|
116244
116929
|
const names = /* @__PURE__ */ new Set();
|
|
116245
116930
|
const claim = (name) => {
|
|
@@ -116247,16 +116932,11 @@ function relationKinds(ctx) {
|
|
|
116247
116932
|
if (names.has(name)) throw new TypeError(`${where}: "${name}" is named twice`);
|
|
116248
116933
|
names.add(name);
|
|
116249
116934
|
};
|
|
116250
|
-
for (const [name, value] of
|
|
116935
|
+
for (const [name, value] of [...own, ...contributed]) {
|
|
116251
116936
|
claim(name);
|
|
116252
116937
|
if (typeof value !== "object" || value === null || Array.isArray(value)) throw new TypeError(`${where}.${name} must be an object`);
|
|
116253
116938
|
const entry = new Map(Object.entries(value));
|
|
116254
|
-
for (const key of entry.keys()) if (!
|
|
116255
|
-
"inverse",
|
|
116256
|
-
"acyclic",
|
|
116257
|
-
"cardinality",
|
|
116258
|
-
"symmetric"
|
|
116259
|
-
].includes(key)) throw new TypeError(`${where}.${name}.${key} is not an option. Options: inverse, acyclic, cardinality, symmetric`);
|
|
116939
|
+
for (const key of entry.keys()) if (!KIND_OPTIONS.includes(key)) throw new TypeError(`${where}.${name}.${key} is not an option. Options: ${KIND_OPTIONS.join(", ")}`);
|
|
116260
116940
|
const inverse = entry.get("inverse");
|
|
116261
116941
|
if (inverse !== void 0 && typeof inverse !== "string") throw new TypeError(`${where}.${name}.inverse must be a string`);
|
|
116262
116942
|
const cardinality = entry.get("cardinality") ?? "many";
|
|
@@ -116269,11 +116949,36 @@ function relationKinds(ctx) {
|
|
|
116269
116949
|
inverse,
|
|
116270
116950
|
acyclic: entry.get("acyclic") === true,
|
|
116271
116951
|
single: cardinality === "one",
|
|
116272
|
-
symmetric
|
|
116952
|
+
symmetric,
|
|
116953
|
+
...kindTypes(`${where}.${name}.types`, entry.get("types")),
|
|
116954
|
+
data: checks.get(name)
|
|
116273
116955
|
});
|
|
116274
116956
|
}
|
|
116275
116957
|
return kinds;
|
|
116276
116958
|
}
|
|
116959
|
+
/**
|
|
116960
|
+
* The checks `link` runs on the stored ends of each kind that names its subject
|
|
116961
|
+
* types. A symmetric kind accepts either order.
|
|
116962
|
+
*/
|
|
116963
|
+
function typeChecks(kinds) {
|
|
116964
|
+
const within = (column, types) => types === void 0 ? void 0 : `${column} in (${types.map((type) => sqlString(type)).join(", ")})`;
|
|
116965
|
+
const both = (source, target, kind) => [within(source, kind.sourceTypes), within(target, kind.targetTypes)].filter((part) => part !== void 0).join(" and ");
|
|
116966
|
+
return kinds.filter((kind) => kind.sourceTypes !== void 0 || kind.targetTypes !== void 0).map((kind) => {
|
|
116967
|
+
const forward = both("v_source_type", "v_target_type", kind);
|
|
116968
|
+
const allowed = kind.symmetric ? `(${forward}) or (${both("v_target_type", "v_source_type", kind)})` : forward;
|
|
116969
|
+
return `
|
|
116970
|
+
if v_kind = ${sqlString(kind.name)} and not (${allowed}) then
|
|
116971
|
+
${fail$1("RELATION_TYPE_NOT_ALLOWED", `this kind of link doesn't accept these record types`, "22023")}
|
|
116972
|
+
end if;`;
|
|
116973
|
+
}).join("");
|
|
116974
|
+
}
|
|
116975
|
+
/** The checks `link` runs on the data it stores, for kinds that check it. */
|
|
116976
|
+
function dataChecks(kinds, data) {
|
|
116977
|
+
return kinds.flatMap((kind) => kind.data === void 0 ? [] : [`
|
|
116978
|
+
if v_kind = ${sqlString(kind.name)} and not coalesce(${kind.data(data)}, false) then
|
|
116979
|
+
${fail$1("RELATION_DATA_INVALID", "this kind of link doesn't accept this data", "22023")}
|
|
116980
|
+
end if;`]).join("");
|
|
116981
|
+
}
|
|
116277
116982
|
/** A `values` list of every name a caller may pass, with the kind it stands for. */
|
|
116278
116983
|
function kindTable(kinds) {
|
|
116279
116984
|
return `(values ${kinds.flatMap((kind) => {
|
|
@@ -116450,7 +117155,7 @@ begin
|
|
|
116450
117155
|
if link.source_type = link.target_type and link.source_id = link.target_id then
|
|
116451
117156
|
${fail$1("RELATION_SELF", "a record can't link to itself", "22023")}
|
|
116452
117157
|
end if;
|
|
116453
|
-
${canonical("link")}
|
|
117158
|
+
${canonical("link")}${typeChecks(kinds)}
|
|
116454
117159
|
if not (${readable("link", "link.source_type", "link.source_id")})
|
|
116455
117160
|
or not (${readable("link", "link.target_type", "link.target_id")}) then
|
|
116456
117161
|
${fail$1("RELATION_SUBJECT_FORBIDDEN", "not allowed to link these records")}
|
|
@@ -116470,7 +117175,7 @@ ${canonical("link")}
|
|
|
116470
117175
|
where ${tenant} = link.tenant and ${kind} = v_kind
|
|
116471
117176
|
and ${sourceType} = v_source_type and ${sourceId} = v_source_id
|
|
116472
117177
|
and ${targetType} = v_target_type and ${targetId} = v_target_id;
|
|
116473
|
-
if v_id is null then
|
|
117178
|
+
if v_id is null then${dataChecks(kinds, "coalesce(link.data, '{}'::jsonb)")}
|
|
116474
117179
|
if v_acyclic and exists (
|
|
116475
117180
|
with recursive reach(t, i, depth) as (
|
|
116476
117181
|
select v_target_type, v_target_id, 0
|
|
@@ -116505,7 +117210,7 @@ ${canonical("link")}
|
|
|
116505
117210
|
returning ${id} into v_id;
|
|
116506
117211
|
v_created := true;
|
|
116507
117212
|
${event("subject.linked", "v_id", "link.tenant")}
|
|
116508
|
-
elsif link.data is not null then
|
|
117213
|
+
elsif link.data is not null then${dataChecks(kinds, "link.data")}
|
|
116509
117214
|
update ${relations} set ${data} = link.data where ${id} = v_id;
|
|
116510
117215
|
end if;${writeExtraColumns(relations, extras, "link.fields", `x.${id} = v_id`)}
|
|
116511
117216
|
${ctx.hook("after_relation_link", [["uuid", "v_id"]])}
|
|
@@ -123280,19 +123985,30 @@ function bootstrapFunctions(ctx) {
|
|
|
123280
123985
|
});
|
|
123281
123986
|
}
|
|
123282
123987
|
/**
|
|
123988
|
+
* Whether the database keeps a live authorization version: the module's own
|
|
123989
|
+
* table (`authzVersions`) or the provider's (`authorization.versions`).
|
|
123990
|
+
*/
|
|
123991
|
+
function hasVersionSource(ctx, layout) {
|
|
123992
|
+
return layout.authzVersionsProvider !== void 0 || ctx.flag("authzVersions", false);
|
|
123993
|
+
}
|
|
123994
|
+
/**
|
|
123283
123995
|
* One wrapper per `bootstrap` entry: the session check, the authorization
|
|
123284
123996
|
* version and the app function's data in one jsonb, so a page's first query
|
|
123285
123997
|
* carries all three. It runs as the caller, so the app function's policies
|
|
123286
|
-
* apply.
|
|
123998
|
+
* apply. `authz_version` is the live version when the database keeps one, so a
|
|
123999
|
+
* seeded version cache never hides a role change the token predates;
|
|
124000
|
+
* `token_authz_version` is the token's.
|
|
123287
124001
|
*/
|
|
123288
|
-
function bootstrapWrappers(ctx) {
|
|
124002
|
+
function bootstrapWrappers(ctx, layout) {
|
|
123289
124003
|
const functions = bootstrapFunctions(ctx);
|
|
123290
124004
|
if (functions.length === 0) return "";
|
|
124005
|
+
const live = hasVersionSource(ctx, layout) ? "to_jsonb(better_supabase.caller_authz_version())" : "auth.jwt() -> 'authz_ver'";
|
|
123291
124006
|
return `
|
|
123292
124007
|
|
|
123293
124008
|
-- blocks['sessions'].options.bootstrap: bsb.bootstrap({ rpc }) calls these.
|
|
123294
124009
|
-- Each checks the session and returns the caller's authorization version
|
|
123295
|
-
--
|
|
124010
|
+
-- (the live one when the database keeps it, and the token's) with the app
|
|
124011
|
+
-- function's data, so a cache miss is one query.
|
|
123296
124012
|
${functions.map(([name, fn]) => {
|
|
123297
124013
|
const wrapper = `better_supabase.bootstrap_${name}`;
|
|
123298
124014
|
return `create or replace function ${wrapper}(args jsonb default '{}'::jsonb)
|
|
@@ -123306,13 +124022,15 @@ begin
|
|
|
123306
124022
|
return jsonb_build_object(
|
|
123307
124023
|
'session_active', false,
|
|
123308
124024
|
'authz_version', auth.jwt() -> 'authz_ver',
|
|
124025
|
+
'token_authz_version', auth.jwt() -> 'authz_ver',
|
|
123309
124026
|
'tenant', args ->> 'tenant',
|
|
123310
124027
|
'data', null
|
|
123311
124028
|
);
|
|
123312
124029
|
end if;
|
|
123313
124030
|
return jsonb_build_object(
|
|
123314
124031
|
'session_active', true,
|
|
123315
|
-
'authz_version',
|
|
124032
|
+
'authz_version', ${live},
|
|
124033
|
+
'token_authz_version', auth.jwt() -> 'authz_ver',
|
|
123316
124034
|
'tenant', args ->> 'tenant',
|
|
123317
124035
|
'data', to_jsonb(${fn}(args))
|
|
123318
124036
|
);
|
|
@@ -123324,12 +124042,46 @@ grant execute on function ${wrapper}(jsonb) to authenticated;`;
|
|
|
123324
124042
|
}).join("\n\n")}`;
|
|
123325
124043
|
}
|
|
123326
124044
|
/**
|
|
124045
|
+
* `better_supabase.caller_authz_version()`: the caller's own live version, for
|
|
124046
|
+
* the bootstrap wrappers and for clients that catch up after a missed
|
|
124047
|
+
* broadcast. Reads the provider's function when it keeps the versions.
|
|
124048
|
+
*/
|
|
124049
|
+
function callerAuthzVersion(ctx, layout) {
|
|
124050
|
+
if (!hasVersionSource(ctx, layout)) return "";
|
|
124051
|
+
const provider = layout.authzVersionsProvider;
|
|
124052
|
+
const source = provider ? `${provider.function}(auth.uid())` : "better_supabase.authz_version(auth.uid())";
|
|
124053
|
+
return `
|
|
124054
|
+
|
|
124055
|
+
-- The caller's own authorization version, null without a signed-in user.
|
|
124056
|
+
-- Clients compare it with the token's authz_ver to catch up on a broadcast
|
|
124057
|
+
-- they missed.${provider ? `\n-- ${provider.name} keeps the versions in ${provider.function}.` : ""}
|
|
124058
|
+
create or replace function better_supabase.caller_authz_version()
|
|
124059
|
+
returns bigint
|
|
124060
|
+
language plpgsql
|
|
124061
|
+
stable
|
|
124062
|
+
security definer
|
|
124063
|
+
set search_path = ''
|
|
124064
|
+
as $$
|
|
124065
|
+
begin
|
|
124066
|
+
if auth.uid() is null then
|
|
124067
|
+
return null;
|
|
124068
|
+
end if;
|
|
124069
|
+
return ${source};
|
|
124070
|
+
end;
|
|
124071
|
+
$$;
|
|
124072
|
+
|
|
124073
|
+
revoke execute on function better_supabase.caller_authz_version() from public, anon;
|
|
124074
|
+
grant execute on function better_supabase.caller_authz_version() to authenticated;`;
|
|
124075
|
+
}
|
|
124076
|
+
/**
|
|
123327
124077
|
* `blocks['sessions'].options.authzVersions`: a version per user that a trigger
|
|
123328
124078
|
* bumps, the access token hook copies into `authz_ver`, and Realtime broadcasts
|
|
123329
|
-
* on the shared server topic and on the user's own `authz:<uid>`.
|
|
124079
|
+
* on the shared server topic and on the user's own `authz:<uid>`. A provider
|
|
124080
|
+
* that keeps the versions (`authorization.versions`) owns all of that, so the
|
|
124081
|
+
* module writes none of it.
|
|
123330
124082
|
*/
|
|
123331
|
-
function authzVersions(ctx) {
|
|
123332
|
-
if (!ctx.flag("authzVersions", false)) return "";
|
|
124083
|
+
function authzVersions(ctx, layout) {
|
|
124084
|
+
if (!ctx.flag("authzVersions", false) || layout.authzVersionsProvider !== void 0) return "";
|
|
123333
124085
|
const payload = "jsonb_build_object('user_id', new.user_id, 'version', new.version)";
|
|
123334
124086
|
return `
|
|
123335
124087
|
|
|
@@ -123578,7 +124330,7 @@ grant execute on function better_supabase.end_my_session(uuid) to authenticated;
|
|
|
123578
124330
|
-- create policy session_required on public.invoices as restrictive
|
|
123579
124331
|
-- for all to authenticated
|
|
123580
124332
|
-- using ((select better_supabase.session_active()))
|
|
123581
|
-
-- with check ((select better_supabase.session_active()));${sessionPolicies(ctx, layout)}${
|
|
124333
|
+
-- with check ((select better_supabase.session_active()));${sessionPolicies(ctx, layout)}${authzVersions(ctx, layout)}${callerAuthzVersion(ctx, layout)}${bootstrapWrappers(ctx, layout)}`
|
|
123582
124334
|
};
|
|
123583
124335
|
// src/sql/modules/settings.ts
|
|
123584
124336
|
const EVENTS$4 = {
|
|
@@ -124007,6 +124759,20 @@ as $$
|
|
|
124007
124759
|
select exists (select 1 from removed)
|
|
124008
124760
|
$$;
|
|
124009
124761
|
|
|
124762
|
+
-- One organization setting for other modules' security definer functions,
|
|
124763
|
+
-- which decide who may see it. Returns null when the key is not set.
|
|
124764
|
+
create or replace function ${fn("organization_setting")}(tenant ${id}, key text)
|
|
124765
|
+
returns jsonb
|
|
124766
|
+
language sql
|
|
124767
|
+
stable
|
|
124768
|
+
security definer
|
|
124769
|
+
set search_path = ''
|
|
124770
|
+
as $$
|
|
124771
|
+
select s.${oc("value")}
|
|
124772
|
+
from ${o} s
|
|
124773
|
+
where s.${oc("tenant")} = organization_setting.tenant and s.${oc("key")} = organization_setting.key
|
|
124774
|
+
$$;
|
|
124775
|
+
|
|
124010
124776
|
create or replace function ${fn("get_platform_settings")}()
|
|
124011
124777
|
returns jsonb
|
|
124012
124778
|
language sql
|
|
@@ -124062,6 +124828,7 @@ grant execute on function ${fn("reset_user_setting")}(text) to authenticated, se
|
|
|
124062
124828
|
grant execute on function ${fn("get_organization_settings")}(${id}) to authenticated, service_role;
|
|
124063
124829
|
grant execute on function ${fn("set_organization_setting")}(${id}, text, jsonb) to authenticated, service_role;
|
|
124064
124830
|
grant execute on function ${fn("reset_organization_setting")}(${id}, text) to authenticated, service_role;
|
|
124831
|
+
${serviceGrant(`${fn("organization_setting")}(${id}, text)`)}
|
|
124065
124832
|
|
|
124066
124833
|
-- Records organization and platform setting changes; user settings are not
|
|
124067
124834
|
-- recorded.
|
|
@@ -124115,6 +124882,11 @@ function contract$19() {
|
|
|
124115
124882
|
args: ["{id}", "text"],
|
|
124116
124883
|
returns: "boolean"
|
|
124117
124884
|
},
|
|
124885
|
+
{
|
|
124886
|
+
name: "organization_setting",
|
|
124887
|
+
args: ["{id}", "text"],
|
|
124888
|
+
returns: "jsonb"
|
|
124889
|
+
},
|
|
124118
124890
|
{
|
|
124119
124891
|
name: "get_platform_settings",
|
|
124120
124892
|
args: [],
|
|
@@ -125375,7 +126147,8 @@ const NAMES$18 = {
|
|
|
125375
126147
|
payload: [
|
|
125376
126148
|
...SUBJECT_PAYLOAD$1,
|
|
125377
126149
|
"id",
|
|
125378
|
-
"versionId"
|
|
126150
|
+
"versionId",
|
|
126151
|
+
"meaning"
|
|
125379
126152
|
]
|
|
125380
126153
|
},
|
|
125381
126154
|
"signature.declined": {
|
|
@@ -125397,7 +126170,7 @@ const NAMES$18 = {
|
|
|
125397
126170
|
"before_signature_sign",
|
|
125398
126171
|
"after_signature_sign"
|
|
125399
126172
|
],
|
|
125400
|
-
options: ["extraColumns"],
|
|
126173
|
+
options: ["extraColumns", "meanings"],
|
|
125401
126174
|
tables: {
|
|
125402
126175
|
requests: {
|
|
125403
126176
|
name: "signature_requests",
|
|
@@ -125407,6 +126180,7 @@ const NAMES$18 = {
|
|
|
125407
126180
|
user: "requestedBy",
|
|
125408
126181
|
export: true
|
|
125409
126182
|
},
|
|
126183
|
+
optional: ["meaning"],
|
|
125410
126184
|
columns: {
|
|
125411
126185
|
id: "id",
|
|
125412
126186
|
tenant: "tenant_id",
|
|
@@ -125419,6 +126193,7 @@ const NAMES$18 = {
|
|
|
125419
126193
|
status: "status",
|
|
125420
126194
|
approval: "approval_request_id",
|
|
125421
126195
|
message: "message",
|
|
126196
|
+
meaning: "meaning",
|
|
125422
126197
|
requestedBy: "requested_by",
|
|
125423
126198
|
createdAt: "created_at",
|
|
125424
126199
|
completedAt: "completed_at"
|
|
@@ -125450,6 +126225,23 @@ const NAMES$18 = {
|
|
|
125450
126225
|
};
|
|
125451
126226
|
/** How many people one request can ask to sign. */
|
|
125452
126227
|
const MAX_SIGNERS = 20;
|
|
126228
|
+
/** What a signature can mean when `options.meanings` is unset. */
|
|
126229
|
+
const SIGNATURE_MEANINGS = [
|
|
126230
|
+
"authored",
|
|
126231
|
+
"reviewed",
|
|
126232
|
+
"approved",
|
|
126233
|
+
"released",
|
|
126234
|
+
"acknowledged"
|
|
126235
|
+
];
|
|
126236
|
+
const MEANING = /^[a-z][a-z0-9_]{0,62}$/;
|
|
126237
|
+
/** `blocks.signatures.options.meanings`: what a signature can mean. */
|
|
126238
|
+
function meaningsOf(ctx) {
|
|
126239
|
+
const meanings = ctx.list("meanings", SIGNATURE_MEANINGS);
|
|
126240
|
+
if (meanings.length === 0 || meanings.some((item) => !MEANING.test(item))) throw new TypeError("blocks.signatures.options.meanings must be a non-empty list of lowercase names such as approved");
|
|
126241
|
+
return meanings;
|
|
126242
|
+
}
|
|
126243
|
+
/** The arguments of create_signature_request before it took a meaning. */
|
|
126244
|
+
const PREVIOUS_REQUEST_ARGS = "text, text, uuid[], uuid, text, uuid, text";
|
|
125453
126245
|
/** The hash `versions` stores for a version's content. */
|
|
125454
126246
|
const versionHash = (content, storagePath) => sha256Hex$1(`coalesce(${content}::text, '') || coalesce(${storagePath}, '')`);
|
|
125455
126247
|
/**
|
|
@@ -125479,8 +126271,11 @@ function build$18(ctx) {
|
|
|
125479
126271
|
const forbidden = (message) => fail$1("SIGNATURE_FORBIDDEN", message);
|
|
125480
126272
|
const extras = ctx.extraColumns("requests", ["fields"]);
|
|
125481
126273
|
const extra = extraFieldsArg(extras);
|
|
125482
|
-
const requestJson = (row) => `jsonb_build_object('id', ${row}.${r("id")}, 'organizationId', ${row}.${r("tenant")}, 'subjectType', ${row}.${r("subjectType")}, 'subjectId', ${row}.${r("subjectId")}, 'versionId', ${row}.${r("version")}, 'contentHash', ${row}.${r("contentHash")}, 'signers', to_jsonb(${row}.${r("signers")}), 'order', ${row}.${r("order")}, 'status', ${row}.${r("status")}, 'approvalRequestId', ${row}.${r("approval")}, 'message', ${row}.${r("message")}, 'requestedBy', ${row}.${r("requestedBy")}, 'createdAt', ${row}.${r("createdAt")}, 'completedAt', ${row}.${r("completedAt")}${extraFieldsJson(row, extras)})`;
|
|
126274
|
+
const requestJson = (row) => `jsonb_build_object('id', ${row}.${r("id")}, 'organizationId', ${row}.${r("tenant")}, 'subjectType', ${row}.${r("subjectType")}, 'subjectId', ${row}.${r("subjectId")}, 'versionId', ${row}.${r("version")}, 'contentHash', ${row}.${r("contentHash")}, 'signers', to_jsonb(${row}.${r("signers")}), 'order', ${row}.${r("order")}, 'status', ${row}.${r("status")}, 'approvalRequestId', ${row}.${r("approval")}, 'message', ${row}.${r("message")}, 'meaning', ${meaning(row)}, 'requestedBy', ${row}.${r("requestedBy")}, 'createdAt', ${row}.${r("createdAt")}, 'completedAt', ${row}.${r("completedAt")}${extraFieldsJson(row, extras)})`;
|
|
125483
126275
|
const signatureJson = (row) => `jsonb_build_object('id', ${row}.${s("id")}, 'requestId', ${row}.${s("request")}, 'signer', ${row}.${s("signer")}, 'method', ${row}.${s("method")}, 'typedName', ${row}.${s("typedName")}, 'imageAttachmentId', ${row}.${s("image")}, 'signedHash', ${row}.${s("signedHash")}, 'ip', ${row}.${s("ip")}, 'userAgent', ${row}.${s("userAgent")}, 'signedAt', ${row}.${s("signedAt")})`;
|
|
126276
|
+
const hasMeaning = ctx.has("requests", "meaning");
|
|
126277
|
+
const meanings = meaningsOf(ctx);
|
|
126278
|
+
const meaning = (row) => hasMeaning ? `${row}.${r("meaning")}` : "null::text";
|
|
125484
126279
|
const requestRecord = (type, row, extra, audit) => ctx.record({
|
|
125485
126280
|
type,
|
|
125486
126281
|
payload: `jsonb_build_object('organizationId', ${row}.${r("tenant")}, 'subjectType', ${row}.${r("subjectType")}, 'subjectId', ${row}.${r("subjectId")}, 'id', ${row}.${r("id")}${extra})`,
|
|
@@ -125535,10 +126330,13 @@ function build$18(ctx) {
|
|
|
125535
126330
|
${r("status")} text not null default 'pending' check (${r("status")} in ('pending', 'completed', 'declined', 'cancelled')),
|
|
125536
126331
|
${r("approval")} uuid,
|
|
125537
126332
|
${r("message")} text check (${r("message")} is null or length(${r("message")}) <= 2000),
|
|
126333
|
+
${r("meaning")} text,
|
|
125538
126334
|
${r("requestedBy")} uuid,
|
|
125539
126335
|
${r("createdAt")} timestamptz not null default now(),
|
|
125540
126336
|
${r("completedAt")} timestamptz
|
|
125541
|
-
)
|
|
126337
|
+
);
|
|
126338
|
+
-- What signing means (blocks.signatures.options.meanings), such as approved.
|
|
126339
|
+
alter table ${requests} add column if not exists ${r("meaning")} text;${addExtraColumns(requests, extras)}
|
|
125542
126340
|
create index if not exists ${sqlIdent(`${ctx.tableName("requests").name}_subject_idx`)} on ${requests} (${r("tenant")}, ${r("subjectType")}, ${r("subjectId")});
|
|
125543
126341
|
create index if not exists ${sqlIdent(`${ctx.tableName("requests").name}_version_idx`)} on ${requests} (${r("version")});
|
|
125544
126342
|
create index if not exists ${sqlIdent(`${ctx.tableName("requests").name}_signers_idx`)} on ${requests} using gin (${r("signers")});
|
|
@@ -125595,10 +126393,13 @@ ${renderPolicy(policy$1({
|
|
|
125595
126393
|
${tables}
|
|
125596
126394
|
-- Asks members to sign one version of a record. The version is frozen, so
|
|
125597
126395
|
-- retention and delete_version keep it; without one, the record's columns
|
|
125598
|
-
-- are snapshotted first.
|
|
126396
|
+
-- are snapshotted first. meaning says what signing means, one of
|
|
126397
|
+
-- blocks.signatures.options.meanings. fields: the extra columns
|
|
125599
126398
|
-- (blocks.signatures.options.extraColumns) to set.
|
|
125600
|
-
${
|
|
125601
|
-
|
|
126399
|
+
drop function if exists ${fn("create_signature_request")}(${ctx.idType}, ${PREVIOUS_REQUEST_ARGS});
|
|
126400
|
+
drop function if exists ${fn("create_signature_request")}(${ctx.idType}, ${PREVIOUS_REQUEST_ARGS}, jsonb);
|
|
126401
|
+
${extra.drop(fn("create_signature_request"), `${ctx.idType}, ${PREVIOUS_REQUEST_ARGS}, text`)}
|
|
126402
|
+
create or replace function ${fn("create_signature_request")}(tenant ${ctx.idType}, subject_type text, subject_id text, signers uuid[], version_id uuid default null, sign_order text default 'parallel', approval_request_id uuid default null, message text default null, meaning text default null${extra.param})
|
|
125602
126403
|
returns jsonb
|
|
125603
126404
|
language plpgsql
|
|
125604
126405
|
security definer
|
|
@@ -125617,6 +126418,9 @@ begin
|
|
|
125617
126418
|
})})) then
|
|
125618
126419
|
${forbidden("not allowed to request signatures on this record")}
|
|
125619
126420
|
end if;
|
|
126421
|
+
if create_signature_request.meaning is not null and create_signature_request.meaning not in (${meanings.map((item) => `'${item}'`).join(", ")}) then
|
|
126422
|
+
${fail$1("SIGNATURE_REQUEST_MEANING_UNKNOWN", `meaning must be one of ${meanings.join(", ")}`, "22023")}
|
|
126423
|
+
end if;
|
|
125620
126424
|
if create_signature_request.sign_order not in ('parallel', 'sequential') then
|
|
125621
126425
|
${fail$1("SIGNATURE_ORDER_INVALID", "sign_order must be parallel or sequential", "22023")}
|
|
125622
126426
|
end if;
|
|
@@ -125654,15 +126458,15 @@ begin
|
|
|
125654
126458
|
["uuid", "v_version"]
|
|
125655
126459
|
])}
|
|
125656
126460
|
update ${vt} x set ${v("frozen")} = true where x.${v("id")} = v_version and not x.${v("frozen")};
|
|
125657
|
-
insert into ${requests} (${r("tenant")}, ${r("subjectType")}, ${r("subjectId")}, ${r("version")}, ${r("contentHash")}, ${r("signers")}, ${r("order")}, ${r("approval")}, ${r("message")}, ${r("requestedBy")})
|
|
125658
|
-
values (create_signature_request.tenant, create_signature_request.subject_type, create_signature_request.subject_id, v_version, v_hash, create_signature_request.signers, create_signature_request.sign_order, create_signature_request.approval_request_id, nullif(trim(create_signature_request.message), ''), auth.uid())
|
|
126461
|
+
insert into ${requests} (${r("tenant")}, ${r("subjectType")}, ${r("subjectId")}, ${r("version")}, ${r("contentHash")}, ${r("signers")}, ${r("order")}, ${r("approval")}, ${r("message")}${hasMeaning ? `, ${r("meaning")}` : ""}, ${r("requestedBy")})
|
|
126462
|
+
values (create_signature_request.tenant, create_signature_request.subject_type, create_signature_request.subject_id, v_version, v_hash, create_signature_request.signers, create_signature_request.sign_order, create_signature_request.approval_request_id, nullif(trim(create_signature_request.message), '')${hasMeaning ? ", create_signature_request.meaning" : ""}, auth.uid())
|
|
125659
126463
|
returning * into v_row;${writeExtraColumns(requests, extras, "create_signature_request.fields", `x.${r("id")} = v_row.${r("id")}`, "v_row")}
|
|
125660
126464
|
${requestRecord("signature.requested", "v_row", `, 'versionId', v_row.${r("version")}`, `'requested signatures on ' || v_row.${r("subjectType")} || ' ' || v_row.${r("subjectId")}`)}
|
|
125661
126465
|
${ctx.hook("after_signature_request", [["uuid", `v_row.${r("id")}`]])}
|
|
125662
126466
|
return ${requestJson("v_row")};
|
|
125663
126467
|
end;
|
|
125664
126468
|
$$;
|
|
125665
|
-
${userGrant(`${fn("create_signature_request")}(${ctx.idType}, text, text, uuid[], uuid, text, uuid, text${extra.type})`)}
|
|
126469
|
+
${userGrant(`${fn("create_signature_request")}(${ctx.idType}, text, text, uuid[], uuid, text, uuid, text, text${extra.type})`)}
|
|
125666
126470
|
|
|
125667
126471
|
-- Recomputes the signed version's hash from its content and each signature's
|
|
125668
126472
|
-- hash, and reports whether the record has a newer version since.
|
|
@@ -125786,7 +126590,7 @@ begin
|
|
|
125786
126590
|
update ${requests} x set ${r("status")} = 'completed', ${r("completedAt")} = v_at
|
|
125787
126591
|
where x.${r("id")} = v_req.${r("id")}
|
|
125788
126592
|
returning * into v_req;
|
|
125789
|
-
${requestRecord("signature.completed", "v_req", `, 'versionId', v_req.${r("version")}`, false)}
|
|
126593
|
+
${requestRecord("signature.completed", "v_req", `, 'versionId', v_req.${r("version")}, 'meaning', ${meaning("v_req")}`, false)}
|
|
125790
126594
|
end if;
|
|
125791
126595
|
${ctx.hook("after_signature_sign", [["uuid", `v_row.${s("id")}`], ["text", `v_req.${r("status")}`]])}
|
|
125792
126596
|
return ${signatureJson("v_row")} || jsonb_build_object('requestStatus', v_req.${r("status")});
|
|
@@ -125924,6 +126728,7 @@ function contract$17(ctx) {
|
|
|
125924
126728
|
"text",
|
|
125925
126729
|
"uuid",
|
|
125926
126730
|
"text",
|
|
126731
|
+
"text",
|
|
125927
126732
|
...extraFieldsArg(ctx.extraColumns("requests", ["fields"])).contract
|
|
125928
126733
|
],
|
|
125929
126734
|
returns: "jsonb"
|
|
@@ -130535,10 +131340,13 @@ const REASON = "nullif(current_setting('better_supabase.transition_reason', true
|
|
|
130535
131340
|
* role passes for the user it acts for.
|
|
130536
131341
|
*/
|
|
130537
131342
|
const ACTOR_ID = `coalesce(auth.uid(), nullif(nullif(current_setting('${ACTOR_SETTING}', true), '')::jsonb ->> 'id', '')::uuid)`;
|
|
130538
|
-
/** One field of the actor `transition()` passed, as SQL. */
|
|
131343
|
+
/** One field of the actor `transition()` passed, as text SQL. */
|
|
131344
|
+
function actorText(field) {
|
|
131345
|
+
return `nullif(nullif(current_setting('${ACTOR_SETTING}', true), '')::jsonb ->> ${sqlString(field)}, '')`;
|
|
131346
|
+
}
|
|
131347
|
+
/** One field of the actor `transition()` passed, as SQL of its column type. */
|
|
130539
131348
|
function actorField(field) {
|
|
130540
|
-
|
|
130541
|
-
return field === "ip" ? `${value}::inet` : value;
|
|
131349
|
+
return field === "ip" ? `${actorText(field)}::inet` : actorText(field);
|
|
130542
131350
|
}
|
|
130543
131351
|
/** The history columns and values a transition writes. */
|
|
130544
131352
|
function historyWrite(ctx, item) {
|
|
@@ -130557,7 +131365,7 @@ function historyWrite(ctx, item) {
|
|
|
130557
131365
|
[hist.reason, REASON],
|
|
130558
131366
|
...ACTOR_FIELDS.flatMap(([key, field]) => {
|
|
130559
131367
|
const column = hist[key];
|
|
130560
|
-
return column === void 0 ? [] : [[column, asColumnType(table, column,
|
|
131368
|
+
return column === void 0 ? [] : [[column, asColumnType(table, column, actorText(field))]];
|
|
130561
131369
|
})
|
|
130562
131370
|
];
|
|
130563
131371
|
return `insert into ${table} (${columns.map(([column]) => sqlIdent(column)).join(", ")})
|
|
@@ -136540,6 +137348,10 @@ const TIME_TRACKING = {
|
|
|
136540
137348
|
build: build$8
|
|
136541
137349
|
};
|
|
136542
137350
|
// src/sql/modules/timeline-reads.ts
|
|
137351
|
+
const NO_BRANCH = {
|
|
137352
|
+
sql: "",
|
|
137353
|
+
covers: ""
|
|
137354
|
+
};
|
|
136543
137355
|
const DELIVERIES_SIGNATURE = (ctx) => `${ctx.fn("activity_subject_deliveries")}(${ctx.idType}, text, text, timestamptz, integer)`;
|
|
136544
137356
|
/**
|
|
136545
137357
|
* How the activity feed reads through the `subjects` registry and the audit
|
|
@@ -136558,6 +137370,7 @@ function activityReads(ctx) {
|
|
|
136558
137370
|
auditSetup: "",
|
|
136559
137371
|
auditBranch: "",
|
|
136560
137372
|
sourceBranches: "",
|
|
137373
|
+
eventDedupe: "",
|
|
136561
137374
|
helpers: `\ndrop function if exists ${DELIVERIES_SIGNATURE(ctx)};`,
|
|
136562
137375
|
sources: ["event"]
|
|
136563
137376
|
};
|
|
@@ -136572,6 +137385,8 @@ function activityReads(ctx) {
|
|
|
136572
137385
|
const runs = runBranch(ctx, types);
|
|
136573
137386
|
const transitions = transitionBranch(ctx, types);
|
|
136574
137387
|
const messages = messageBranch(ctx, types);
|
|
137388
|
+
const type = `y.${ctx.col("activity", "type")}`;
|
|
137389
|
+
const covered = [...transitions.covers === "" ? [] : [`(${type} = 'status.changed' and ${transitions.covers})`], ...messages.covers === "" ? [] : [`(${type} in ('message.sent', 'comment.posted') and ${messages.covers})`]];
|
|
136575
137390
|
const deliveries = deliveryHelper(ctx, types);
|
|
136576
137391
|
return {
|
|
136577
137392
|
readable: `-- Whether the caller can read a registered subject (can_subject).
|
|
@@ -136606,20 +137421,22 @@ ${registry.map((subject) => ` when ${sqlString(subject.type)} then ${sqlStr
|
|
|
136606
137421
|
end;
|
|
136607
137422
|
end if;` : "",
|
|
136608
137423
|
auditBranch: auditOn ? auditBranch(ctx, audit) : "",
|
|
136609
|
-
sourceBranches: `${runs}${transitions}${messages}${deliveries === void 0 ? "" : `
|
|
137424
|
+
sourceBranches: `${runs}${transitions.sql}${messages.sql}${deliveries === void 0 ? "" : `
|
|
136610
137425
|
union all
|
|
136611
137426
|
(select d.entry, d.at, d.id
|
|
136612
137427
|
from ${ctx.fn("activity_subject_deliveries")}(list_activity.tenant, list_activity.subject_type, list_activity.subject_id, list_activity.before, v_limit) d
|
|
136613
137428
|
where list_activity.subject_id is not null
|
|
136614
137429
|
and (list_activity.sources is null or 'delivery' = any (list_activity.sources)))`}`,
|
|
137430
|
+
eventDedupe: covered.length === 0 ? "" : `
|
|
137431
|
+
and not (${covered.join("\n or ")})`,
|
|
136615
137432
|
helpers: deliveries ?? `\ndrop function if exists ${DELIVERIES_SIGNATURE(ctx)};`,
|
|
136616
137433
|
sources: [
|
|
136617
137434
|
"event",
|
|
136618
137435
|
...auditOn ? ["audit"] : [],
|
|
136619
137436
|
...deliveries === void 0 ? [] : ["delivery"],
|
|
136620
137437
|
...runs === "" ? [] : ["run"],
|
|
136621
|
-
...transitions === "" ? [] : ["transition"],
|
|
136622
|
-
...messages === "" ? [] : ["message"]
|
|
137438
|
+
...transitions.sql === "" ? [] : ["transition"],
|
|
137439
|
+
...messages.sql === "" ? [] : ["message"]
|
|
136623
137440
|
]
|
|
136624
137441
|
};
|
|
136625
137442
|
}
|
|
@@ -136688,20 +137505,18 @@ function runBranch(ctx, types) {
|
|
|
136688
137505
|
* skipped). As the caller, so the history's read policy applies.
|
|
136689
137506
|
*/
|
|
136690
137507
|
function transitionBranch(ctx, types) {
|
|
136691
|
-
if (ctx.scope.kind !== "tenant" || !ctx.installed("state-machine")) return
|
|
137508
|
+
if (ctx.scope.kind !== "tenant" || !ctx.installed("state-machine")) return NO_BRANCH;
|
|
136692
137509
|
const sm = ctx.of("state-machine");
|
|
136693
|
-
if (sm.mode === "custom") return
|
|
137510
|
+
if (sm.mode === "custom") return NO_BRANCH;
|
|
136694
137511
|
const names = machines(sm).filter((item) => item.history === void 0).map((item) => item.name);
|
|
136695
|
-
if (names.length === 0) return
|
|
137512
|
+
if (names.length === 0) return NO_BRANCH;
|
|
136696
137513
|
const h = (logical) => `h.${sm.col("history", logical)}`;
|
|
136697
137514
|
const data = [
|
|
136698
137515
|
`'from', ${h("fromStatus")}::text`,
|
|
136699
137516
|
`'to', ${h("toStatus")}::text`,
|
|
136700
137517
|
`'reason', ${h("reason")}`
|
|
136701
137518
|
];
|
|
136702
|
-
|
|
136703
|
-
union all
|
|
136704
|
-
(select jsonb_build_object(${entry$1(ctx, {
|
|
137519
|
+
const values = {
|
|
136705
137520
|
id: `${h("id")}::text`,
|
|
136706
137521
|
tenant: h("tenant"),
|
|
136707
137522
|
event: "null::text",
|
|
@@ -136712,28 +137527,35 @@ function transitionBranch(ctx, types) {
|
|
|
136712
137527
|
summary: "null::text",
|
|
136713
137528
|
data: `jsonb_strip_nulls(jsonb_build_object(${data.join(", ")}))`,
|
|
136714
137529
|
occurredAt: h("createdAt")
|
|
136715
|
-
}
|
|
136716
|
-
|
|
136717
|
-
from ${sm.table("history")} h
|
|
136718
|
-
where list_activity.subject_id is not null
|
|
137530
|
+
};
|
|
137531
|
+
const covers = `list_activity.subject_id is not null
|
|
136719
137532
|
and list_activity.subject_type = any (${types})
|
|
136720
137533
|
and list_activity.subject_type = any (${sqlString(`{${names.join(",")}}`)}::text[])
|
|
136721
|
-
and (list_activity.sources is null or 'transition' = any (list_activity.sources))
|
|
137534
|
+
and (list_activity.sources is null or 'transition' = any (list_activity.sources))`;
|
|
137535
|
+
return {
|
|
137536
|
+
sql: `
|
|
137537
|
+
union all
|
|
137538
|
+
(select jsonb_build_object(${entry$1(ctx, values, "transition")}) as entry,
|
|
137539
|
+
${h("createdAt")} as at, ${h("id")}::text as id
|
|
137540
|
+
from ${sm.table("history")} h
|
|
137541
|
+
where ${covers}
|
|
136722
137542
|
and ${h("tenant")} = list_activity.tenant
|
|
136723
137543
|
and ${h("subjectType")} = list_activity.subject_type
|
|
136724
137544
|
and ${h("subjectId")} = list_activity.subject_id
|
|
136725
137545
|
and (list_activity.before is null or ${h("createdAt")} < list_activity.before)
|
|
136726
137546
|
order by ${h("createdAt")} desc, ${h("id")} desc
|
|
136727
|
-
limit v_limit)
|
|
137547
|
+
limit v_limit)`,
|
|
137548
|
+
covers
|
|
137549
|
+
};
|
|
136728
137550
|
}
|
|
136729
137551
|
/**
|
|
136730
137552
|
* The sent messages of the subject's conversation in messaging. As the caller,
|
|
136731
137553
|
* so the conversation's access decides which the caller sees.
|
|
136732
137554
|
*/
|
|
136733
137555
|
function messageBranch(ctx, types) {
|
|
136734
|
-
if (ctx.scope.kind !== "tenant" || !ctx.installed("messaging")) return
|
|
137556
|
+
if (ctx.scope.kind !== "tenant" || !ctx.installed("messaging")) return NO_BRANCH;
|
|
136735
137557
|
const ms = ctx.of("messaging");
|
|
136736
|
-
if (!(ms.mode !== "custom" && ms.has("conversations", "subjectType") && ms.has("conversations", "subjectId"))) return
|
|
137558
|
+
if (!(ms.mode !== "custom" && ms.has("conversations", "subjectType") && ms.has("conversations", "subjectId"))) return NO_BRANCH;
|
|
136737
137559
|
const m = (logical) => `m.${ms.col("messages", logical)}`;
|
|
136738
137560
|
const c = (logical) => `c.${ms.col("conversations", logical)}`;
|
|
136739
137561
|
const data = [
|
|
@@ -136742,26 +137564,29 @@ function messageBranch(ctx, types) {
|
|
|
136742
137564
|
`'threadId', ${m("thread")}`,
|
|
136743
137565
|
`'kind', ${m("kind")}::text`
|
|
136744
137566
|
];
|
|
136745
|
-
|
|
136746
|
-
union all
|
|
136747
|
-
(select jsonb_build_object(${entry$1(ctx, {
|
|
137567
|
+
const values = {
|
|
136748
137568
|
id: `${m("id")}::text`,
|
|
136749
137569
|
tenant: m("tenant"),
|
|
136750
137570
|
event: "null::text",
|
|
136751
|
-
type: "'message.sent'
|
|
137571
|
+
type: `case when ${c("kind")} = 'subject' then 'comment.posted' else 'message.sent' end`,
|
|
136752
137572
|
actor: m("author"),
|
|
136753
137573
|
subjectType: "list_activity.subject_type",
|
|
136754
137574
|
subjectId: "list_activity.subject_id",
|
|
136755
137575
|
summary: `left(${m("body")}, 280)`,
|
|
136756
137576
|
data: `jsonb_strip_nulls(jsonb_build_object(${data.join(", ")}))`,
|
|
136757
137577
|
occurredAt: m("sentAt")
|
|
136758
|
-
}
|
|
137578
|
+
};
|
|
137579
|
+
const covers = `list_activity.subject_id is not null
|
|
137580
|
+
and list_activity.subject_type = any (${types})
|
|
137581
|
+
and (list_activity.sources is null or 'message' = any (list_activity.sources))`;
|
|
137582
|
+
return {
|
|
137583
|
+
sql: `
|
|
137584
|
+
union all
|
|
137585
|
+
(select jsonb_build_object(${entry$1(ctx, values, "message")}) as entry,
|
|
136759
137586
|
${m("sentAt")} as at, ${m("id")}::text as id
|
|
136760
137587
|
from ${ms.table("messages")} m
|
|
136761
137588
|
join ${ms.table("conversations")} c on ${c("id")} = ${m("conversation")}
|
|
136762
|
-
where
|
|
136763
|
-
and list_activity.subject_type = any (${types})
|
|
136764
|
-
and (list_activity.sources is null or 'message' = any (list_activity.sources))
|
|
137589
|
+
where ${covers}
|
|
136765
137590
|
and ${c("tenant")} = list_activity.tenant
|
|
136766
137591
|
and ${c("subjectType")} = list_activity.subject_type
|
|
136767
137592
|
and ${c("subjectId")} = list_activity.subject_id
|
|
@@ -136769,7 +137594,9 @@ function messageBranch(ctx, types) {
|
|
|
136769
137594
|
and ${m("deletedAt")} is null
|
|
136770
137595
|
and (list_activity.before is null or ${m("sentAt")} < list_activity.before)
|
|
136771
137596
|
order by ${m("sentAt")} desc, ${m("id")} desc
|
|
136772
|
-
limit v_limit)
|
|
137597
|
+
limit v_limit)`,
|
|
137598
|
+
covers
|
|
137599
|
+
};
|
|
136773
137600
|
}
|
|
136774
137601
|
/**
|
|
136775
137602
|
* Activity_subject_deliveries: the deliveries of the notifications about a
|
|
@@ -137056,7 +137883,7 @@ begin${reads.gate}${reads.auditSetup}
|
|
|
137056
137883
|
and (list_activity.sources is null or 'event' = any (list_activity.sources))
|
|
137057
137884
|
and (list_activity.subject_type is null or y.${a("subjectType")} = list_activity.subject_type)
|
|
137058
137885
|
and (list_activity.subject_id is null or y.${a("subjectId")} = list_activity.subject_id)
|
|
137059
|
-
and (list_activity.before is null or y.${a("occurredAt")} < list_activity.before)
|
|
137886
|
+
and (list_activity.before is null or y.${a("occurredAt")} < list_activity.before)${reads.eventDedupe}
|
|
137060
137887
|
order by y.${a("occurredAt")} desc, y.${a("id")} desc
|
|
137061
137888
|
limit v_limit)${reads.auditBranch}${reads.sourceBranches}
|
|
137062
137889
|
) u
|
|
@@ -147248,7 +148075,7 @@ const SQL_MODULES = Object.fromEntries([
|
|
|
147248
148075
|
built(DISPATCH),
|
|
147249
148076
|
built(SHIPMENTS),
|
|
147250
148077
|
built(CONTRACTS),
|
|
147251
|
-
built(
|
|
148078
|
+
built(COMPLIANCE),
|
|
147252
148079
|
built(INCIDENTS),
|
|
147253
148080
|
built(COURSES),
|
|
147254
148081
|
built(MESSAGING),
|
|
@@ -147701,6 +148528,14 @@ function columnAccessRefusals(table) {
|
|
|
147701
148528
|
return [...hidden.map((column) => `select extensions.throws_ok($$select ${sqlIdent(column)} from ${target}$$, '42501', null, ${sqlString(`a signed-in user cannot read ${SCHEMA$4}.${table.name}.${column}`)});`), ...restricted.map((column) => `select extensions.throws_ok($$update ${target} set ${sqlIdent(column)} = null where false$$, '42501', null, ${sqlString(`a signed-in user cannot write ${SCHEMA$4}.${table.name}.${column}`)});`)];
|
|
147702
148529
|
}
|
|
147703
148530
|
// src/sql/modules/app-table-checks.ts
|
|
148531
|
+
/** A value of each checked text format that passes its check. */
|
|
148532
|
+
const TEXT_SAMPLES = {
|
|
148533
|
+
email: "'test@example.com'",
|
|
148534
|
+
url: "'https://example.com'",
|
|
148535
|
+
phone_e164: "'+31201234567'",
|
|
148536
|
+
bsn: "'111222333'",
|
|
148537
|
+
iban: "'NL91ABNA0417164300'"
|
|
148538
|
+
};
|
|
147704
148539
|
/**
|
|
147705
148540
|
* The conditions of a column's check on the `ident` expression: its format,
|
|
147706
148541
|
* options and bounds.
|
|
@@ -147708,7 +148543,7 @@ function columnAccessRefusals(table) {
|
|
|
147708
148543
|
function constraintChecks(column, ident) {
|
|
147709
148544
|
const conditions = [];
|
|
147710
148545
|
const format = column.format === void 0 || column.domain !== void 0 ? void 0 : FIELD_FORMATS[column.format];
|
|
147711
|
-
if (format
|
|
148546
|
+
if (format !== void 0 && column.format !== void 0) conditions.push(...formatConditions(column.format, ident, "public"));
|
|
147712
148547
|
if (column.options !== void 0) {
|
|
147713
148548
|
const list = column.options.map((option) => sqlString(option)).join(", ");
|
|
147714
148549
|
conditions.push(column.type === "text[]" ? `${ident} <@ array[${list}]::text[]` : `${ident} in (${list})`);
|
|
@@ -147734,10 +148569,11 @@ function sampleValue(column) {
|
|
|
147734
148569
|
const format = column.format === void 0 ? void 0 : FIELD_FORMATS[column.format];
|
|
147735
148570
|
const low = column.min ?? format?.bounds?.[0];
|
|
147736
148571
|
switch (column.type) {
|
|
147737
|
-
case "text":
|
|
147738
|
-
|
|
147739
|
-
if (
|
|
148572
|
+
case "text": {
|
|
148573
|
+
const sample = column.format === void 0 ? void 0 : TEXT_SAMPLES[column.format];
|
|
148574
|
+
if (sample !== void 0) return sample;
|
|
147740
148575
|
return `repeat('x', ${String(Math.max(low ?? 1, 1))})`;
|
|
148576
|
+
}
|
|
147741
148577
|
case "integer":
|
|
147742
148578
|
case "bigint":
|
|
147743
148579
|
case "numeric": return String(low ?? 0);
|
|
@@ -147767,7 +148603,7 @@ const scopePolicyName = (table, command) => `${table.enrich ? "bsb_" : ""}${tabl
|
|
|
147767
148603
|
function grantsPrelude(target, enriched) {
|
|
147768
148604
|
return enriched ? `-- ${target} keeps the app's own grants; these add what the scope needs.` : revokeTable(target);
|
|
147769
148605
|
}
|
|
147770
|
-
const qualified$
|
|
148606
|
+
const qualified$5 = (table) => `${sqlIdent(SCHEMA$3)}.${sqlIdent(table)}`;
|
|
147771
148607
|
/**
|
|
147772
148608
|
* Each implicit column the app's table lacks, added with `add column if not
|
|
147773
148609
|
* exists`, nullable unless it has a default. The id is unique instead of the
|
|
@@ -147776,7 +148612,7 @@ const qualified$4 = (table) => `${sqlIdent(SCHEMA$3)}.${sqlIdent(table)}`;
|
|
|
147776
148612
|
* complete.
|
|
147777
148613
|
*/
|
|
147778
148614
|
function enrichSql(table) {
|
|
147779
|
-
const target = qualified$
|
|
148615
|
+
const target = qualified$5(table.name);
|
|
147780
148616
|
const columns = [
|
|
147781
148617
|
...table.existing.has("id") ? [] : [table.config.id === "bigint" ? "id bigint generated by default as identity unique" : "id uuid not null default gen_random_uuid() unique"],
|
|
147782
148618
|
...table.scope && !table.existing.has(table.scope.name) ? [`${sqlIdent(table.scope.name)} ${table.scope.addable}`] : [],
|
|
@@ -147798,10 +148634,10 @@ function enrichSql(table) {
|
|
|
147798
148634
|
function enrichChecks(table, policies) {
|
|
147799
148635
|
const name = sqlString(table.name);
|
|
147800
148636
|
const label = `${SCHEMA$3}.${table.name}`;
|
|
147801
|
-
const regclass = `${sqlString(qualified$
|
|
148637
|
+
const regclass = `${sqlString(qualified$5(table.name))}::regclass`;
|
|
147802
148638
|
const checks = [`select extensions.ok(array[${policies.map((policy) => sqlString(policy)).join(", ")}]::name[] <@ array(select p.policyname from pg_catalog.pg_policies p where p.schemaname = '${SCHEMA$3}' and p.tablename = ${name}), ${sqlString(`${label} has the policies for its scope`)});`];
|
|
147803
148639
|
if (table.scope) {
|
|
147804
|
-
const constraint = notNullCheckName(qualified$
|
|
148640
|
+
const constraint = notNullCheckName(qualified$5(table.name), sqlIdent(table.scope.name));
|
|
147805
148641
|
checks.push(`select extensions.has_column('${SCHEMA$3}', ${name}, ${sqlString(table.scope.name)}, ${sqlString(`${label} has the scope column ${table.scope.name}`)});`, `select extensions.ok(exists (select 1 from pg_catalog.pg_constraint k where k.conrelid = ${regclass} and k.conname = ${sqlString(constraint)} and k.contype = 'c'), ${sqlString(`new rows of ${label} must fill ${table.scope.name}`)});`);
|
|
147806
148642
|
}
|
|
147807
148643
|
return checks;
|
|
@@ -147830,9 +148666,19 @@ function privilegeChecks(table) {
|
|
|
147830
148666
|
const SCHEMA$2 = "public";
|
|
147831
148667
|
/** The most ids one `<table>_reveal` call decrypts. */
|
|
147832
148668
|
const APP_REVEAL_LIMIT = 500;
|
|
147833
|
-
const qualified$
|
|
148669
|
+
const qualified$4 = (table) => `${sqlIdent(SCHEMA$2)}.${sqlIdent(table)}`;
|
|
147834
148670
|
/** The reveal function of `table`, quoted. */
|
|
147835
|
-
const revealFunction = (table) => qualified$
|
|
148671
|
+
const revealFunction = (table) => qualified$4(`${table}_reveal`);
|
|
148672
|
+
/** The find function of `table`, quoted. */
|
|
148673
|
+
const findFunction = (table) => qualified$4(`${table}_find`);
|
|
148674
|
+
/** The encrypted columns of `config` that keep a lookup hash. */
|
|
148675
|
+
function lookupColumns(config) {
|
|
148676
|
+
return encryptedColumns(config).filter((name) => config.columns?.[name]?.lookup === true);
|
|
148677
|
+
}
|
|
148678
|
+
/** The plaintext `value` as the column type prints it, as the trigger hashes it. */
|
|
148679
|
+
function normalized(column, value) {
|
|
148680
|
+
return column.type === "text" ? value : `((${value})::${column.type})::text`;
|
|
148681
|
+
}
|
|
147836
148682
|
/** The SQL type of the table's id. */
|
|
147837
148683
|
const idType = (config) => config.id === "bigint" ? "bigint" : "uuid";
|
|
147838
148684
|
/** The SQL that names the data key a row of `table` is encrypted with. */
|
|
@@ -147870,27 +148716,48 @@ function sealSql(table, checks) {
|
|
|
147870
148716
|
const open = encryption.fn("field_open");
|
|
147871
148717
|
const fn = ctx.fn(`${table.name}_seal`);
|
|
147872
148718
|
const trigger = ctx.trigger("seal_fields");
|
|
147873
|
-
const target = qualified$
|
|
148719
|
+
const target = qualified$4(table.name);
|
|
147874
148720
|
const prefix = sqlString(FIELD_CIPHER_PREFIX);
|
|
147875
148721
|
const width = String(5);
|
|
148722
|
+
const lookupKey = encryption.fn("field_lookup_key");
|
|
148723
|
+
const hash = encryption.fn("field_hash");
|
|
148724
|
+
const lookups = new Set(lookupColumns(table.config));
|
|
147876
148725
|
const branch = (name) => {
|
|
147877
148726
|
const column = table.config.columns?.[name] ?? { type: "text" };
|
|
147878
148727
|
const value = `new.${sqlIdent(name)}`;
|
|
147879
148728
|
const conditions = plainChecks(column, checks, value);
|
|
148729
|
+
const lookup = lookups.has(name) ? sqlIdent(lookupColumn(name)) : void 0;
|
|
147880
148730
|
const normalize = column.type === "text" ? "" : `\n ${value} := ((${value})::${column.type})::text;`;
|
|
147881
148731
|
const check = conditions.length === 0 ? "" : `\n if not (${conditions.join(" and ")}) then
|
|
147882
148732
|
raise exception 'new row for relation "%" violates check constraint "%"', ${sqlString(table.name)}, ${sqlString(`${table.name}_${name}_check`)}
|
|
147883
148733
|
using errcode = '23514';
|
|
147884
148734
|
end if;`;
|
|
147885
|
-
|
|
148735
|
+
const fresh = `case when tg_op = 'INSERT' then true else ${value} is distinct from old.${sqlIdent(name)} end`;
|
|
148736
|
+
const hashed = (plain) => `\n v_lookup_key := coalesce(v_lookup_key, ${lookupKey}(v_owner, true));\n new.${lookup ?? ""} := ${hash}(v_lookup_key, ${plain});`;
|
|
148737
|
+
if (lookup === void 0) return ` if ${value} is not null and (${fresh} or left(${value}, ${width}) <> ${prefix}) then${normalize}${check}
|
|
147886
148738
|
v_key := coalesce(v_key, ${key}(v_owner, true));
|
|
147887
148739
|
${value} := ${seal}(v_key, ${value});
|
|
147888
148740
|
elsif ${value} is not null and v_moved then
|
|
147889
148741
|
v_key := coalesce(v_key, ${key}(v_owner, true));
|
|
147890
148742
|
${value} := ${seal}(v_key, ${open}(${key}(v_old_owner, false), ${value}));
|
|
148743
|
+
end if;`;
|
|
148744
|
+
return ` if ${value} is not null and (${fresh} or left(${value}, ${width}) <> ${prefix}) then${normalize}${check}${hashed(value)}
|
|
148745
|
+
v_key := coalesce(v_key, ${key}(v_owner, true));
|
|
148746
|
+
${value} := ${seal}(v_key, ${value});
|
|
148747
|
+
elsif ${value} is not null and v_moved then
|
|
148748
|
+
v_plain := ${open}(${key}(v_old_owner, false), ${value});${hashed("v_plain")}
|
|
148749
|
+
v_key := coalesce(v_key, ${key}(v_owner, true));
|
|
148750
|
+
${value} := ${seal}(v_key, v_plain);
|
|
148751
|
+
elsif ${value} is null then
|
|
148752
|
+
new.${lookup} := null;
|
|
148753
|
+
elsif new.${lookup} is null or (tg_op = 'UPDATE' and new.${lookup} is distinct from old.${lookup}) then${hashed(`${open}(${key}(v_owner, false), ${value})`)}
|
|
147891
148754
|
end if;`;
|
|
147892
148755
|
};
|
|
147893
|
-
const watched = [
|
|
148756
|
+
const watched = [
|
|
148757
|
+
...table.scope ? [table.scope.name] : [],
|
|
148758
|
+
...columns,
|
|
148759
|
+
...[...lookups].map((name) => lookupColumn(name))
|
|
148760
|
+
].map((column) => sqlIdent(column));
|
|
147894
148761
|
return `-- Encrypts ${columns.join(", ")} with the row's data key before the row is written.
|
|
147895
148762
|
create or replace function ${fn}()
|
|
147896
148763
|
returns trigger
|
|
@@ -147902,7 +148769,7 @@ declare
|
|
|
147902
148769
|
v_owner text := ${ownerOf(table, "new")};
|
|
147903
148770
|
v_old_owner text;
|
|
147904
148771
|
v_moved boolean := false;
|
|
147905
|
-
v_key text;
|
|
148772
|
+
v_key text;${lookups.size === 0 ? "" : "\n v_lookup_key text;\n v_plain text;"}
|
|
147906
148773
|
begin
|
|
147907
148774
|
if tg_op = 'UPDATE' then
|
|
147908
148775
|
v_old_owner := ${ownerOf(table, "old")};
|
|
@@ -147934,7 +148801,7 @@ function revealSql(table) {
|
|
|
147934
148801
|
const fn = ctx.fn(`${table.name}_reveal`);
|
|
147935
148802
|
const wrapper = revealFunction(table.name);
|
|
147936
148803
|
const id = idType(table.config);
|
|
147937
|
-
const target = qualified$
|
|
148804
|
+
const target = qualified$4(table.name);
|
|
147938
148805
|
const ids = `${ctx.fnName(`${table.name}_reveal`)}.ids`;
|
|
147939
148806
|
const filter = `t.id = any (${ids}) and (v_service or (${[table.own, ...table.sessionPolicy ? ["(select better_supabase.session_active())"] : []].join(" and ")}))`;
|
|
147940
148807
|
const outputs = columns.map((name) => {
|
|
@@ -147991,6 +148858,86 @@ $$;
|
|
|
147991
148858
|
revoke execute on function ${wrapper}(${id}[]) from public, anon;
|
|
147992
148859
|
grant execute on function ${wrapper}(${id}[]) to authenticated, service_role;`;
|
|
147993
148860
|
}
|
|
148861
|
+
/**
|
|
148862
|
+
* `public.<table>_find(lookup_column, value)`: the ids of the rows the caller
|
|
148863
|
+
* reaches whose lookup column holds the hash of `value`. It hashes `value` once
|
|
148864
|
+
* per owner the caller can reach: the tenants they are a member of, or
|
|
148865
|
+
* themselves, and for the service role every owner in the table. Like
|
|
148866
|
+
* `<table>_reveal`, a `security invoker` wrapper in `public` calls the definer
|
|
148867
|
+
* function in `better_supabase`.
|
|
148868
|
+
*/
|
|
148869
|
+
function findSql(table) {
|
|
148870
|
+
const columns = lookupColumns(table.config);
|
|
148871
|
+
if (columns.length === 0) return "";
|
|
148872
|
+
const { ctx } = table;
|
|
148873
|
+
const encryption = ctx.of("field-encryption");
|
|
148874
|
+
const fn = ctx.fn(`${table.name}_find`);
|
|
148875
|
+
const name = ctx.fnName(`${table.name}_find`);
|
|
148876
|
+
const wrapper = findFunction(table.name);
|
|
148877
|
+
const id = idType(table.config);
|
|
148878
|
+
const target = qualified$4(table.name);
|
|
148879
|
+
const scope = table.scope;
|
|
148880
|
+
const reach = [table.own, ...table.sessionPolicy ? ["(select better_supabase.session_active())"] : []].join(" and ");
|
|
148881
|
+
const kind = ctx.scope.kind === "user" ? "user" : "tenant";
|
|
148882
|
+
const owners = scope === void 0 ? `select ${fieldKeyOwner("none", "")} as bsb_owner` : `select distinct ${fieldKeyOwner(kind, "o.id")} as bsb_owner
|
|
148883
|
+
from (
|
|
148884
|
+
select t.${sqlIdent(scope.name)} as id from ${target} t where v_service
|
|
148885
|
+
union all
|
|
148886
|
+
select m.id from ${ctx.scope.members()} as m(id) where not v_service
|
|
148887
|
+
) o
|
|
148888
|
+
where o.id is not null`;
|
|
148889
|
+
const branches = columns.map((column, index) => {
|
|
148890
|
+
const config = table.config.columns?.[column] ?? { type: "text" };
|
|
148891
|
+
return ` ${index === 0 ? "if" : "elsif"} ${name}.lookup_column = ${sqlString(column)} then
|
|
148892
|
+
return query
|
|
148893
|
+
with k as materialized (
|
|
148894
|
+
select w.bsb_owner, ${encryption.fn("field_hash")}(${encryption.fn("field_lookup_key")}(w.bsb_owner, false), ${normalized(config, `${name}.value`)}) as bsb_hash
|
|
148895
|
+
from (${owners}) w
|
|
148896
|
+
)
|
|
148897
|
+
select t.id
|
|
148898
|
+
from ${target} t
|
|
148899
|
+
join k on k.bsb_hash = t.${sqlIdent(lookupColumn(column))} and k.bsb_owner = ${ownerOf(table, "t")}
|
|
148900
|
+
where v_service or (${reach});`;
|
|
148901
|
+
});
|
|
148902
|
+
return `-- Finds the rows whose ${columns.join(", ")} equal a value, by their lookup hash, as the table's policies allow.
|
|
148903
|
+
create or replace function ${fn}(lookup_column text, value text)
|
|
148904
|
+
returns table (id ${id})
|
|
148905
|
+
language plpgsql
|
|
148906
|
+
stable
|
|
148907
|
+
security definer
|
|
148908
|
+
set search_path = ''
|
|
148909
|
+
as $$
|
|
148910
|
+
#variable_conflict use_column
|
|
148911
|
+
declare
|
|
148912
|
+
v_service boolean := ${SERVICE_CALLER$1};
|
|
148913
|
+
begin
|
|
148914
|
+
if (select auth.uid()) is null and not v_service then
|
|
148915
|
+
${fail$1("APP_FIND_FORBIDDEN", `only signed-in users and the service role find ${table.name}`)}
|
|
148916
|
+
end if;
|
|
148917
|
+
if ${name}.value is null then
|
|
148918
|
+
return;
|
|
148919
|
+
end if;
|
|
148920
|
+
${branches.join("\n")}
|
|
148921
|
+
else
|
|
148922
|
+
${fail$1("APP_FIND_COLUMN", `${table.name} keeps a lookup for ${columns.join(", ")} only`, "22023")}
|
|
148923
|
+
end if;
|
|
148924
|
+
end;
|
|
148925
|
+
$$;
|
|
148926
|
+
revoke execute on function ${fn}(text, text) from public, anon;
|
|
148927
|
+
grant execute on function ${fn}(text, text) to authenticated, service_role;
|
|
148928
|
+
-- The API entry point for ${fn}; the definer function stays out of the exposed schemas.
|
|
148929
|
+
create or replace function ${wrapper}(lookup_column text, value text)
|
|
148930
|
+
returns table (id ${id})
|
|
148931
|
+
language sql
|
|
148932
|
+
stable
|
|
148933
|
+
security invoker
|
|
148934
|
+
set search_path = ''
|
|
148935
|
+
as $$
|
|
148936
|
+
select * from ${fn}(lookup_column, value);
|
|
148937
|
+
$$;
|
|
148938
|
+
revoke execute on function ${wrapper}(text, text) from public, anon;
|
|
148939
|
+
grant execute on function ${wrapper}(text, text) to authenticated, service_role;`;
|
|
148940
|
+
}
|
|
147994
148941
|
/** The audit entries of one reveal call: one per tenant, naming its rows. */
|
|
147995
148942
|
function auditSql(table, columns, filter) {
|
|
147996
148943
|
if (table.config.auditReads !== true) return "";
|
|
@@ -148012,7 +148959,7 @@ function auditSql(table, columns, filter) {
|
|
|
148012
148959
|
return `
|
|
148013
148960
|
for v_read in
|
|
148014
148961
|
select ${tenant} as tenant, jsonb_agg(t.id order by t.id) as ids
|
|
148015
|
-
from ${qualified$
|
|
148962
|
+
from ${qualified$4(table.name)} t
|
|
148016
148963
|
where ${filter}
|
|
148017
148964
|
group by 1
|
|
148018
148965
|
loop
|
|
@@ -148067,10 +149014,10 @@ function sealChecks(table, seeded, sample) {
|
|
|
148067
149014
|
return {
|
|
148068
149015
|
static: statics,
|
|
148069
149016
|
seeded: [
|
|
148070
|
-
`update ${qualified$
|
|
148071
|
-
`select set_config(${sqlString(REVEAL_IDS)}, (select array_agg(id)::text from ${qualified$
|
|
149017
|
+
`update ${qualified$4(table.name)} set ${columns.map((column) => `${sqlIdent(column)} = (${plain(column)})::text`).join(", ")};`,
|
|
149018
|
+
`select set_config(${sqlString(REVEAL_IDS)}, (select array_agg(id)::text from ${qualified$4(table.name)}), true);`,
|
|
148072
149019
|
`select set_config('request.jwt.claims', json_build_object('role', 'service_role')::text, true);`,
|
|
148073
|
-
...columns.flatMap((column) => [`select extensions.ok((select bool_and(left(${sqlIdent(column)}, ${String(5)}) = ${sqlString(FIELD_CIPHER_PREFIX)} and ${sqlIdent(column)} <> (${plain(column)})::text) from ${qualified$
|
|
149020
|
+
...columns.flatMap((column) => [`select extensions.ok((select bool_and(left(${sqlIdent(column)}, ${String(5)}) = ${sqlString(FIELD_CIPHER_PREFIX)} and ${sqlIdent(column)} <> (${plain(column)})::text) from ${qualified$4(table.name)}), ${sqlString(`${label}.${column} is ciphertext at rest`)});`, `select extensions.is((select r.${sqlIdent(column)}::text from ${reveal} r limit 1), (${plain(column)})::text, ${sqlString(`the service role reveals ${label}.${column}`)});`])
|
|
148074
149021
|
],
|
|
148075
149022
|
behaviour: [`select extensions.is((select count(*)::integer from ${reveal}), 0, ${sqlString(`a signed-in user does not reveal a row of ${label} outside their scope`)});`]
|
|
148076
149023
|
};
|
|
@@ -148139,6 +149086,49 @@ end;
|
|
|
148139
149086
|
$$;
|
|
148140
149087
|
${userGrant(`${fn}(${idType}, text, text, jsonb)`)}`;
|
|
148141
149088
|
}
|
|
149089
|
+
// src/sql/modules/app-table-tenant-keys.ts
|
|
149090
|
+
const qualified$3 = (table) => `${sqlIdent("public")}.${sqlIdent(table)}`;
|
|
149091
|
+
/**
|
|
149092
|
+
* The references of a tenant-scoped table to another tenant-scoped app table
|
|
149093
|
+
* (itself included), which `tenantKeysSql` checks per tenant.
|
|
149094
|
+
*/
|
|
149095
|
+
function tenantReferencesOf(table, tenantScoped) {
|
|
149096
|
+
const references = /* @__PURE__ */ new Map();
|
|
149097
|
+
if (table.ctx.scope.kind !== "tenant" || !table.scope) return references;
|
|
149098
|
+
for (const [column, config] of Object.entries(table.config.columns ?? {})) {
|
|
149099
|
+
const reference = config.references;
|
|
149100
|
+
if (reference !== void 0 && !("block" in reference) && tenantScoped.has(reference.table)) references.set(column, {
|
|
149101
|
+
column,
|
|
149102
|
+
target: reference.table,
|
|
149103
|
+
tenant: table.scope.name,
|
|
149104
|
+
onDelete: reference.onDelete
|
|
149105
|
+
});
|
|
149106
|
+
}
|
|
149107
|
+
return references;
|
|
149108
|
+
}
|
|
149109
|
+
/**
|
|
149110
|
+
* The unique `(tenant, id)` index on every target of a tenant reference, then
|
|
149111
|
+
* each reference as a foreign key on `(tenant, column)`. The key is dropped and
|
|
149112
|
+
* added again so a re-run replaces the single-column key an earlier version
|
|
149113
|
+
* wrote under the same name. `set null` names the column (Postgres 15), so the
|
|
149114
|
+
* tenant column keeps its value.
|
|
149115
|
+
*/
|
|
149116
|
+
function tenantKeysSql(tables) {
|
|
149117
|
+
const references = tables.flatMap((table) => [...table.tenantReferences.values()].map((reference) => ({
|
|
149118
|
+
table: table.name,
|
|
149119
|
+
reference
|
|
149120
|
+
})));
|
|
149121
|
+
const indexes = [...new Map(references.map(({ reference }) => [reference.target, reference.tenant]))].map(([target, tenant]) => `create unique index if not exists ${sqlIdent(`${target}_${tenant}_id_key`)} on ${qualified$3(target)} (${sqlIdent(tenant)}, id);`);
|
|
149122
|
+
const keys = references.map(({ table, reference }) => {
|
|
149123
|
+
const name = sqlIdent(`${table}_${reference.column}_fkey`);
|
|
149124
|
+
const tenant = sqlIdent(reference.tenant);
|
|
149125
|
+
const column = sqlIdent(reference.column);
|
|
149126
|
+
const onDelete = reference.onDelete === void 0 ? "" : reference.onDelete === "set null" ? ` on delete set null (${column})` : ` on delete ${reference.onDelete}`;
|
|
149127
|
+
return `alter table ${qualified$3(table)} drop constraint if exists ${name};
|
|
149128
|
+
alter table ${qualified$3(table)} add constraint ${name} foreign key (${tenant}, ${column}) references ${qualified$3(reference.target)} (${tenant}, id)${onDelete};`;
|
|
149129
|
+
});
|
|
149130
|
+
return [...indexes, ...keys].join("\n");
|
|
149131
|
+
}
|
|
148142
149132
|
// src/sql/modules/app-views.ts
|
|
148143
149133
|
const SCHEMA$1 = "public";
|
|
148144
149134
|
const qualified$2 = (table) => `${sqlIdent(SCHEMA$1)}.${sqlIdent(table)}`;
|
|
@@ -148302,47 +149292,6 @@ function columnSql(table, name, column) {
|
|
|
148302
149292
|
column.references === void 0 || table.tenantReferences.has(name) ? "" : referenceSql(`tables.${table.name}.columns.${name}`, column.references, table.ctx)
|
|
148303
149293
|
].join("");
|
|
148304
149294
|
}
|
|
148305
|
-
/**
|
|
148306
|
-
* The references of a tenant-scoped table to another tenant-scoped app table
|
|
148307
|
-
* (itself included), which `tenantKeysSql` checks per tenant.
|
|
148308
|
-
*/
|
|
148309
|
-
function tenantReferencesOf(table, tenantScoped) {
|
|
148310
|
-
const references = /* @__PURE__ */ new Map();
|
|
148311
|
-
if (table.ctx.scope.kind !== "tenant" || !table.scope) return references;
|
|
148312
|
-
for (const [column, config] of Object.entries(table.config.columns ?? {})) {
|
|
148313
|
-
const reference = config.references;
|
|
148314
|
-
if (reference !== void 0 && !("block" in reference) && tenantScoped.has(reference.table)) references.set(column, {
|
|
148315
|
-
column,
|
|
148316
|
-
target: reference.table,
|
|
148317
|
-
tenant: table.scope.name,
|
|
148318
|
-
onDelete: reference.onDelete
|
|
148319
|
-
});
|
|
148320
|
-
}
|
|
148321
|
-
return references;
|
|
148322
|
-
}
|
|
148323
|
-
/**
|
|
148324
|
-
* The unique `(tenant, id)` index on every target of a tenant reference, then
|
|
148325
|
-
* each reference as a foreign key on `(tenant, column)`. The key is dropped and
|
|
148326
|
-
* added again so a re-run replaces the single-column key an earlier version
|
|
148327
|
-
* wrote under the same name. `set null` names the column (Postgres 15), so the
|
|
148328
|
-
* tenant column keeps its value.
|
|
148329
|
-
*/
|
|
148330
|
-
function tenantKeysSql(tables) {
|
|
148331
|
-
const references = tables.flatMap((table) => [...table.tenantReferences.values()].map((reference) => ({
|
|
148332
|
-
table: table.name,
|
|
148333
|
-
reference
|
|
148334
|
-
})));
|
|
148335
|
-
const indexes = [...new Map(references.map(({ reference }) => [reference.target, reference.tenant]))].map(([target, tenant]) => `create unique index if not exists ${sqlIdent(`${target}_${tenant}_id_key`)} on ${qualified$1(target)} (${sqlIdent(tenant)}, id);`);
|
|
148336
|
-
const keys = references.map(({ table, reference }) => {
|
|
148337
|
-
const name = sqlIdent(`${table}_${reference.column}_fkey`);
|
|
148338
|
-
const tenant = sqlIdent(reference.tenant);
|
|
148339
|
-
const column = sqlIdent(reference.column);
|
|
148340
|
-
const onDelete = reference.onDelete === void 0 ? "" : reference.onDelete === "set null" ? ` on delete set null (${column})` : ` on delete ${reference.onDelete}`;
|
|
148341
|
-
return `alter table ${qualified$1(table)} drop constraint if exists ${name};
|
|
148342
|
-
alter table ${qualified$1(table)} add constraint ${name} foreign key (${tenant}, ${column}) references ${qualified$1(reference.target)} (${tenant}, id)${onDelete};`;
|
|
148343
|
-
});
|
|
148344
|
-
return [...indexes, ...keys].join("\n");
|
|
148345
|
-
}
|
|
148346
149295
|
function createSql(table) {
|
|
148347
149296
|
if (table.enrich) return enrichSql(table.enrich);
|
|
148348
149297
|
const timestamps = table.config.timestamps !== false;
|
|
@@ -148361,7 +149310,11 @@ function subjectColumnsSql(table) {
|
|
|
148361
149310
|
return [...subject?.rank === void 0 ? [] : [`${sqlIdent(APP_RANK_COLUMN)} text collate "C" not null default 'V'`], ...subject?.softDelete === true ? [`${sqlIdent(APP_DELETED_AT_COLUMN)} timestamptz`] : []];
|
|
148362
149311
|
}
|
|
148363
149312
|
function columnsSql(table) {
|
|
148364
|
-
return [
|
|
149313
|
+
return [
|
|
149314
|
+
...Object.entries(table.config.columns ?? {}).filter(([name]) => !table.enrich?.existing.has(name)).map(([name, column]) => columnSql(table, name, column)),
|
|
149315
|
+
...subjectColumnsSql(table),
|
|
149316
|
+
...lookupColumns(table.config).map((name) => `${sqlIdent(lookupColumn(name))} bytea`)
|
|
149317
|
+
].map((column) => `alter table ${qualified$1(table.name)} add column if not exists ${column};`).join("\n");
|
|
148365
149318
|
}
|
|
148366
149319
|
/** The rank key's index, within its group when the subject sets one. */
|
|
148367
149320
|
function rankIndex(table) {
|
|
@@ -148373,7 +149326,8 @@ function indexesSql(table) {
|
|
|
148373
149326
|
return [
|
|
148374
149327
|
...[...table.scope ? [table.scope.name] : [], ...Object.entries(table.config.columns ?? {}).filter(([, column]) => column.references !== void 0 && column.unique !== true).map(([name]) => name)].map((column) => [column]),
|
|
148375
149328
|
...rankIndex(table),
|
|
148376
|
-
...table.config.indexes ?? []
|
|
149329
|
+
...table.config.indexes ?? [],
|
|
149330
|
+
...lookupColumns(table.config).map((name) => [lookupColumn(name)])
|
|
148377
149331
|
].map((columns) => `create index if not exists ${sqlIdent(`${table.name}_${columns.join("_")}_idx`)} on ${qualified$1(table.name)} (${columns.map((column) => sqlIdent(column)).join(", ")});`).join("\n");
|
|
148378
149332
|
}
|
|
148379
149333
|
/** Every column of the table, implicit ones first. */
|
|
@@ -148646,7 +149600,8 @@ function tableSql(table) {
|
|
|
148646
149600
|
triggerSql(table),
|
|
148647
149601
|
eventsSql(table),
|
|
148648
149602
|
sealSql(sealTable(table), constraintChecks),
|
|
148649
|
-
revealSql(sealTable(table))
|
|
149603
|
+
revealSql(sealTable(table)),
|
|
149604
|
+
findSql(sealTable(table))
|
|
148650
149605
|
].filter((part) => part !== "").join("\n");
|
|
148651
149606
|
}
|
|
148652
149607
|
/**
|
|
@@ -148822,6 +149777,7 @@ function appTablesFiles(layout, installed) {
|
|
|
148822
149777
|
...managed
|
|
148823
149778
|
].join("\n");
|
|
148824
149779
|
const body = [
|
|
149780
|
+
formatValidatorSql(SCHEMA, validatorsOf(tables.flatMap((table) => Object.values(table.config.columns ?? {}).map((column) => column.format)))),
|
|
148825
149781
|
tables.map((table) => createSql(table)).join("\n\n"),
|
|
148826
149782
|
tables.map((table) => columnsSql(table)).filter((part) => part !== "").join("\n\n"),
|
|
148827
149783
|
...tables.map((table) => tableSql(table)),
|
|
@@ -149079,7 +150035,7 @@ function withoutBlockPolicies(sql, skip, restrictive = false) {
|
|
|
149079
150035
|
});
|
|
149080
150036
|
return statements.map(({ masked: statement }, index) => {
|
|
149081
150037
|
const edit = POLICY_EDIT.exec(statement);
|
|
149082
|
-
return edit !== null && skipped.has(`${qualified$
|
|
150038
|
+
return edit !== null && skipped.has(`${qualified$9(edit[2])}\u0000${unquote$5(edit[1])}`) ? "" : kept[index];
|
|
149083
150039
|
}).join("");
|
|
149084
150040
|
}
|
|
149085
150041
|
/**
|
|
@@ -149137,7 +150093,7 @@ function declaredPolicies(sources, schemas) {
|
|
|
149137
150093
|
continue;
|
|
149138
150094
|
}
|
|
149139
150095
|
const drop = DROP_POLICY.exec(statement);
|
|
149140
|
-
if (drop !== null) found.get(qualified$
|
|
150096
|
+
if (drop !== null) found.get(qualified$9(drop[2]))?.delete(unquote$5(drop[1]));
|
|
149141
150097
|
}
|
|
149142
150098
|
}
|
|
149143
150099
|
return Object.fromEntries([...found].map(([table, named]) => [table, [...named.values()]]));
|
|
@@ -149726,6 +150682,10 @@ function moduleLayout(config, testsDir = config.sql.testsDir, readSets = [], ent
|
|
|
149726
150682
|
...entitlementsProvider ? { entitlementsProvider } : {},
|
|
149727
150683
|
...accessProvider ? { accessProvider } : {},
|
|
149728
150684
|
...permissionCatalog ? { permissionCatalog } : {},
|
|
150685
|
+
...config.authorization?.versions ? { authzVersionsProvider: {
|
|
150686
|
+
name: config.authorization.name,
|
|
150687
|
+
function: config.authorization.versions.function
|
|
150688
|
+
} } : {},
|
|
149729
150689
|
...config.authorization?.delegation?.scopes ? { delegationScopes: config.authorization.delegation.scopes } : {},
|
|
149730
150690
|
dir: config.sql.dir,
|
|
149731
150691
|
prefix: config.sql.prefix,
|
|
@@ -149955,7 +150915,7 @@ function computedWrites(sql) {
|
|
|
149955
150915
|
const text = withoutComments(sql);
|
|
149956
150916
|
const found = /* @__PURE__ */ new Map();
|
|
149957
150917
|
for (const match of text.matchAll(INSERT)) {
|
|
149958
|
-
const table = qualified$
|
|
150918
|
+
const table = qualified$9(match[1]);
|
|
149959
150919
|
const open = match.index + match[0].length - 1;
|
|
149960
150920
|
const close = closingParen(text, open);
|
|
149961
150921
|
if (close === -1) continue;
|
|
@@ -149974,7 +150934,7 @@ function computedWrites(sql) {
|
|
|
149974
150934
|
}
|
|
149975
150935
|
}
|
|
149976
150936
|
for (const match of text.matchAll(UPDATE)) {
|
|
149977
|
-
const table = qualified$
|
|
150937
|
+
const table = qualified$9(match[1]);
|
|
149978
150938
|
const start = match.index + match[0].length;
|
|
149979
150939
|
assignments(found, table, text.slice(start, partEnd(text, start, SET_END)));
|
|
149980
150940
|
}
|
|
@@ -150125,8 +151085,8 @@ function enumColumnProblems(modules, files, schemas, ownTables, context) {
|
|
|
150125
151085
|
return table.textColumns.flatMap((logical) => {
|
|
150126
151086
|
const column = table.columns[logical];
|
|
150127
151087
|
const type = column === void 0 ? void 0 : declared.get(column);
|
|
150128
|
-
if (column === void 0 || type === void 0 || type.endsWith("]") || !enums.has(qualified$
|
|
150129
|
-
return [enumColumnProblem(table, logical, column, qualified$
|
|
151088
|
+
if (column === void 0 || type === void 0 || type.endsWith("]") || !enums.has(qualified$9(type))) return [];
|
|
151089
|
+
return [enumColumnProblem(table, logical, column, qualified$9(type))];
|
|
150130
151090
|
});
|
|
150131
151091
|
});
|
|
150132
151092
|
}
|
|
@@ -150172,7 +151132,7 @@ function constraintOf(table, text) {
|
|
|
150172
151132
|
return {
|
|
150173
151133
|
table,
|
|
150174
151134
|
columns: names(match[1]),
|
|
150175
|
-
references: qualified$
|
|
151135
|
+
references: qualified$9(match[2]),
|
|
150176
151136
|
referencedColumns: names(match[3])
|
|
150177
151137
|
};
|
|
150178
151138
|
}
|
|
@@ -150189,7 +151149,7 @@ function declaredForeignKeys(files, schemas) {
|
|
|
150189
151149
|
const text = withoutComments(file.text);
|
|
150190
151150
|
const found = [];
|
|
150191
151151
|
for (const match of text.matchAll(TABLE$2)) {
|
|
150192
|
-
const table = qualified$
|
|
151152
|
+
const table = qualified$9(match[1]);
|
|
150193
151153
|
const open = match.index + match[0].length - 1;
|
|
150194
151154
|
const close = closingParen(text, open);
|
|
150195
151155
|
if (close === -1) continue;
|
|
@@ -150216,14 +151176,14 @@ function declaredForeignKeys(files, schemas) {
|
|
|
150216
151176
|
key: {
|
|
150217
151177
|
table,
|
|
150218
151178
|
columns: [unquote$5(column)],
|
|
150219
|
-
references: qualified$
|
|
151179
|
+
references: qualified$9(inline[1]),
|
|
150220
151180
|
referencedColumns: names(inline[2])
|
|
150221
151181
|
}
|
|
150222
151182
|
});
|
|
150223
151183
|
}
|
|
150224
151184
|
}
|
|
150225
151185
|
for (const match of text.matchAll(ALTER)) {
|
|
150226
|
-
const key = constraintOf(qualified$
|
|
151186
|
+
const key = constraintOf(qualified$9(match[1]), match[2]);
|
|
150227
151187
|
if (key !== void 0) found.push({
|
|
150228
151188
|
index: match.index,
|
|
150229
151189
|
key
|
|
@@ -150793,6 +151753,7 @@ const TABLE_FEATURES = [
|
|
|
150793
151753
|
"json",
|
|
150794
151754
|
"expose",
|
|
150795
151755
|
"encrypted",
|
|
151756
|
+
"lookup",
|
|
150796
151757
|
"server",
|
|
150797
151758
|
"events",
|
|
150798
151759
|
"vector-search"
|