better-supabase 0.55.0 → 0.57.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (400) hide show
  1. package/dist/{agents-CBXJce8J.d.ts → agents-BXjBzFlb.d.ts} +2 -2
  2. package/dist/{ai-schedules-CtwkMJDZ.d.ts → ai-schedules-F9MS-bie.d.ts} +1 -1
  3. package/dist/ai-sdk/agents/index.d.ts +1 -1
  4. package/dist/ai-sdk/workflow/index.d.ts +1 -1
  5. package/dist/{app-tables-BsDmauWB.d.ts → app-tables-DypEnAID.d.ts} +1 -1
  6. package/dist/{authorization-DK7YSiFV.d.ts → authorization-CRKL2OFQ.d.ts} +1 -1
  7. package/dist/{bind-DiGmjHzz.d.ts → bind-DEPqZLwv.d.ts} +3 -3
  8. package/dist/{block-env-BTKZBCL4.d.ts → block-env-CAdE4Q5v.d.ts} +4 -4
  9. package/dist/{block-subjects-BoJrJAgR.js → block-subjects-B9hb1LLk.js} +2 -2
  10. package/dist/{block-tables-B6Jt0mWg.d.ts → block-tables-BATer_QF.d.ts} +1 -1
  11. package/dist/blocks/access-requests/index.d.ts +1 -1
  12. package/dist/blocks/accounting/index.d.ts +1 -1
  13. package/dist/blocks/acknowledgements/index.d.ts +1 -1
  14. package/dist/blocks/activities/index.d.ts +2 -2
  15. package/dist/blocks/advisories/index.d.ts +1 -1
  16. package/dist/blocks/agent-checkout/index.d.ts +1 -1
  17. package/dist/blocks/agents/index.d.ts +1 -1
  18. package/dist/blocks/ai-cache/index.d.ts +1 -1
  19. package/dist/blocks/ai-chat/index.d.ts +1 -1
  20. package/dist/blocks/ai-evals/index.d.ts +1 -1
  21. package/dist/blocks/ai-files/index.d.ts +1 -1
  22. package/dist/blocks/ai-guardrails/index.d.ts +1 -1
  23. package/dist/blocks/ai-keys/index.d.ts +1 -1
  24. package/dist/blocks/ai-schedules/index.d.ts +2 -2
  25. package/dist/blocks/announcements/index.d.ts +4 -4
  26. package/dist/blocks/api-keys/index.d.ts +1 -1
  27. package/dist/blocks/appraisals/index.d.ts +1 -1
  28. package/dist/blocks/approvals/index.d.ts +1 -1
  29. package/dist/blocks/assets/index.d.ts +2 -2
  30. package/dist/blocks/assignment/index.d.ts +1 -1
  31. package/dist/blocks/attachments/index.d.ts +5 -5
  32. package/dist/blocks/audit/index.d.ts +2 -2
  33. package/dist/blocks/automations/index.d.ts +3 -3
  34. package/dist/blocks/banking/index.d.ts +1 -1
  35. package/dist/blocks/billable-time/index.d.ts +1 -1
  36. package/dist/blocks/billing/index.d.ts +2 -2
  37. package/dist/blocks/bookings/index.d.ts +2 -2
  38. package/dist/blocks/bulk/index.d.ts +1 -1
  39. package/dist/blocks/calendar/index.d.ts +3 -3
  40. package/dist/blocks/care/index.d.ts +27 -27
  41. package/dist/blocks/care-plans/index.d.ts +3 -3
  42. package/dist/blocks/cases/index.d.ts +3 -3
  43. package/dist/blocks/catalog/index.d.ts +2 -2
  44. package/dist/blocks/channels/index.d.ts +1 -1
  45. package/dist/blocks/clinical-decision-support/index.d.ts +1 -1
  46. package/dist/blocks/cms/index.d.ts +5 -5
  47. package/dist/blocks/collaboration/index.d.ts +6 -6
  48. package/dist/blocks/collections/index.d.ts +1 -1
  49. package/dist/blocks/comments/index.d.ts +2 -2
  50. package/dist/blocks/commerce/index.d.ts +5 -5
  51. package/dist/blocks/commissions/index.d.ts +1 -1
  52. package/dist/blocks/compliance/index.d.ts +1 -1
  53. package/dist/blocks/connectors/index.d.ts +1 -1
  54. package/dist/blocks/consents/index.d.ts +2 -2
  55. package/dist/blocks/contacts/index.d.ts +2 -2
  56. package/dist/blocks/content/index.d.ts +2 -2
  57. package/dist/blocks/contracts/index.d.ts +1 -1
  58. package/dist/blocks/courses/index.d.ts +3 -3
  59. package/dist/blocks/created-by/index.d.ts +2 -2
  60. package/dist/blocks/crm/index.d.ts +16 -16
  61. package/dist/blocks/custom-fields/index.d.ts +1 -1
  62. package/dist/blocks/dam/index.d.ts +2 -2
  63. package/dist/blocks/data-lifecycle/index.d.ts +2 -2
  64. package/dist/blocks/deadlines/index.d.ts +249 -43
  65. package/dist/blocks/deadlines/index.js +862 -20
  66. package/dist/blocks/deals/index.d.ts +1 -1
  67. package/dist/blocks/dispatch/index.d.ts +2 -2
  68. package/dist/blocks/document-templates/index.d.ts +2 -2
  69. package/dist/blocks/documents/index.d.ts +1 -1
  70. package/dist/blocks/domains/index.d.ts +1 -1
  71. package/dist/blocks/donations/index.d.ts +1 -1
  72. package/dist/blocks/drive/index.d.ts +5 -5
  73. package/dist/blocks/e-prescribing/index.d.ts +1 -1
  74. package/dist/blocks/employees/index.d.ts +1 -1
  75. package/dist/blocks/enrichment/index.d.ts +1 -1
  76. package/dist/blocks/enrollments/index.d.ts +2 -2
  77. package/dist/blocks/entitlements/index.d.ts +3 -3
  78. package/dist/blocks/events/index.d.ts +3 -3
  79. package/dist/blocks/expenses/index.d.ts +1 -1
  80. package/dist/blocks/field-history/index.d.ts +1 -1
  81. package/dist/blocks/filespace/index.d.ts +8 -8
  82. package/dist/blocks/finance/index.d.ts +5 -5
  83. package/dist/blocks/flags/index.d.ts +1 -1
  84. package/dist/blocks/forecasts/index.d.ts +1 -1
  85. package/dist/blocks/forms/index.d.ts +3 -3
  86. package/dist/blocks/funding/index.d.ts +2 -2
  87. package/dist/blocks/goals/index.d.ts +1 -1
  88. package/dist/blocks/governance/index.d.ts +4 -4
  89. package/dist/blocks/guests/index.d.ts +1 -1
  90. package/dist/blocks/hiring/index.d.ts +1 -1
  91. package/dist/blocks/identities/index.d.ts +1 -1
  92. package/dist/blocks/imports/index.d.ts +2 -2
  93. package/dist/blocks/inbox/index.d.ts +6 -6
  94. package/dist/blocks/incidents/index.d.ts +1 -1
  95. package/dist/blocks/index.d.ts +3 -3
  96. package/dist/blocks/inspections/index.d.ts +2 -2
  97. package/dist/blocks/inventory/index.d.ts +1 -1
  98. package/dist/blocks/invoices/index.d.ts +1 -1
  99. package/dist/blocks/knowledge/index.d.ts +1 -1
  100. package/dist/blocks/lead-scoring/index.d.ts +2 -2
  101. package/dist/blocks/learning/index.d.ts +3 -3
  102. package/dist/blocks/leases/index.d.ts +1 -1
  103. package/dist/blocks/leave/index.d.ts +1 -1
  104. package/dist/blocks/ledger/index.d.ts +1 -1
  105. package/dist/blocks/legal-entities/index.d.ts +2 -2
  106. package/dist/blocks/lims/index.d.ts +2 -2
  107. package/dist/blocks/mail-sync/index.d.ts +3 -3
  108. package/dist/blocks/maintenance/index.d.ts +2 -2
  109. package/dist/blocks/manufacturing/index.d.ts +2 -2
  110. package/dist/blocks/medications/index.d.ts +1 -1
  111. package/dist/blocks/meetings/index.d.ts +3 -3
  112. package/dist/blocks/memberships/index.d.ts +2 -2
  113. package/dist/blocks/memory/index.d.ts +1 -1
  114. package/dist/blocks/messaging/index.d.ts +5 -5
  115. package/dist/blocks/metrics/index.d.ts +1 -1
  116. package/dist/blocks/mfa/index.d.ts +2 -2
  117. package/dist/blocks/moderation/index.d.ts +2 -2
  118. package/dist/blocks/notifications/index.d.ts +5 -5
  119. package/dist/blocks/numbering/index.d.ts +1 -1
  120. package/dist/blocks/oauth-server/index.d.ts +1 -1
  121. package/dist/blocks/observations/index.d.ts +2 -2
  122. package/dist/blocks/onboarding/index.d.ts +2 -2
  123. package/dist/blocks/option-sets/index.d.ts +2 -2
  124. package/dist/blocks/orders/index.d.ts +1 -1
  125. package/dist/blocks/organizations/index.d.ts +2 -2
  126. package/dist/blocks/outbox/index.d.ts +1 -1
  127. package/dist/blocks/passes/index.d.ts +2 -2
  128. package/dist/blocks/payroll-export/index.d.ts +2 -2
  129. package/dist/blocks/people/index.d.ts +7 -7
  130. package/dist/blocks/periods/index.d.ts +1 -1
  131. package/dist/blocks/permissions/index.d.ts +3 -3
  132. package/dist/blocks/pipelines/index.d.ts +1 -1
  133. package/dist/blocks/posts/index.d.ts +2 -2
  134. package/dist/blocks/procurement/index.d.ts +5 -5
  135. package/dist/blocks/profiles/index.d.ts +1 -1
  136. package/dist/blocks/projects/index.d.ts +7 -7
  137. package/dist/blocks/promotions/index.d.ts +1 -1
  138. package/dist/blocks/prompts/index.d.ts +1 -1
  139. package/dist/blocks/push/index.d.ts +2 -2
  140. package/dist/blocks/qualifications/index.d.ts +2 -2
  141. package/dist/blocks/queue/index.d.ts +2 -2
  142. package/dist/blocks/quotes/index.d.ts +1 -1
  143. package/dist/blocks/rank/index.d.ts +1 -1
  144. package/dist/blocks/reactions/index.d.ts +4 -4
  145. package/dist/blocks/recruiting/index.d.ts +4 -4
  146. package/dist/blocks/referrals/index.d.ts +1 -1
  147. package/dist/blocks/relations/index.d.ts +1 -1
  148. package/dist/blocks/reminders/index.d.ts +1 -1
  149. package/dist/blocks/reviews/index.d.ts +1 -1
  150. package/dist/blocks/rfqs/index.d.ts +2 -2
  151. package/dist/blocks/risks/index.d.ts +2 -2
  152. package/dist/blocks/saas/index.d.ts +12 -12
  153. package/dist/blocks/sales/index.d.ts +1 -1
  154. package/dist/blocks/saved-views/index.d.ts +2 -2
  155. package/dist/blocks/scheduling/index.d.ts +4 -4
  156. package/dist/blocks/scores/index.d.ts +2 -2
  157. package/dist/blocks/search/index.d.ts +3 -3
  158. package/dist/blocks/security-events/index.d.ts +1 -1
  159. package/dist/blocks/segments/index.d.ts +2 -2
  160. package/dist/blocks/sequences/index.d.ts +3 -3
  161. package/dist/blocks/service/index.d.ts +7 -7
  162. package/dist/blocks/service-accounts/index.d.ts +1 -1
  163. package/dist/blocks/sessions/index.d.ts +2 -2
  164. package/dist/blocks/settings/index.d.ts +2 -2
  165. package/dist/blocks/share-links/index.d.ts +1 -1
  166. package/dist/blocks/shifts/index.d.ts +2 -2
  167. package/dist/blocks/shipments/index.d.ts +2 -2
  168. package/dist/blocks/signatures/index.d.ts +2 -2
  169. package/dist/blocks/signing-keys/index.d.ts +1 -1
  170. package/dist/blocks/sla/index.d.ts +1 -1
  171. package/dist/blocks/sso/index.d.ts +1 -1
  172. package/dist/blocks/state-machine/index.d.ts +1 -1
  173. package/dist/blocks/subjects/index.d.ts +2 -2
  174. package/dist/blocks/support/index.d.ts +5 -5
  175. package/dist/blocks/tags/index.d.ts +2 -2
  176. package/dist/blocks/tasks/index.d.ts +2 -2
  177. package/dist/blocks/tax/index.d.ts +2 -2
  178. package/dist/blocks/teams/index.d.ts +1 -1
  179. package/dist/blocks/templates/index.d.ts +1 -1
  180. package/dist/blocks/tills/index.d.ts +1 -1
  181. package/dist/blocks/time-tracking/index.d.ts +2 -2
  182. package/dist/blocks/timeline/index.d.ts +1 -1
  183. package/dist/blocks/trash/index.d.ts +1 -1
  184. package/dist/blocks/undo/index.d.ts +2 -2
  185. package/dist/blocks/updated-at/index.d.ts +2 -2
  186. package/dist/blocks/usage/index.d.ts +2 -2
  187. package/dist/blocks/vercel-marketplace/index.d.ts +1 -1
  188. package/dist/blocks/versions/index.d.ts +1 -1
  189. package/dist/blocks/waitlist/index.d.ts +1 -1
  190. package/dist/blocks/warehouse/index.d.ts +1 -1
  191. package/dist/blocks/webhooks/index.d.ts +1 -1
  192. package/dist/blocks/workflow-editor/index.d.ts +4 -4
  193. package/dist/blocks/workflows/index.d.ts +4 -4
  194. package/dist/{blocks-2HFgUcqG.d.ts → blocks-Cf2U_jmO.d.ts} +4 -4
  195. package/dist/claims/index.d.ts +3 -3
  196. package/dist/cli/{add-LvxZ-JNB.js → add-CB2nU8nW.js} +2 -2
  197. package/dist/cli/{add-BnYh-Kpy.js → add-DQXg3MLt.js} +10 -10
  198. package/dist/cli/add-DWUCeKIl.js +1 -0
  199. package/dist/cli/{app-table-files-7M0I9LaE.js → app-table-files-Ch3GTFjg.js} +2 -2
  200. package/dist/cli/{app-tables-BfWPWiOJ.js → app-tables-CwSpV4yV.js} +2 -2
  201. package/dist/cli/{backfill-i0Tx24Sa.js → backfill-Cngd3Ax2.js} +1 -1
  202. package/dist/cli/bin.js +1 -1
  203. package/dist/cli/{blocks-C_7ioBdJ.js → blocks--hf8elE7.js} +1 -1
  204. package/dist/cli/{blocks-X_eD_t_f.js → blocks-BGHYZGoh.js} +1 -1
  205. package/dist/cli/{cache-D98rjB1C.js → cache-DMqncCOE.js} +1 -1
  206. package/dist/cli/{codemod-j1nCkgA5.js → codemod-BrNMM9qN.js} +1 -1
  207. package/dist/cli/{content-mapper-UsLt4y0J.js → content-mapper-CBBnca0p.js} +2 -2
  208. package/dist/cli/{doctor-BYJM72wi.js → doctor-BHsw2SGl.js} +15 -15
  209. package/dist/cli/{gen-D47t5jj3.js → gen-BbLeZxhv.js} +11 -11
  210. package/dist/cli/index.d.ts +1 -1
  211. package/dist/cli/index.js +6 -6
  212. package/dist/cli/{init-CAWeLXCs.js → init-DH0LI0hx.js} +9 -9
  213. package/dist/cli/{live-DNd8MMNk.js → live-DFlCT5Uk.js} +2 -2
  214. package/dist/cli/{mcp-BUs7M6fq.js → mcp-B9ZwlZrA.js} +2 -2
  215. package/dist/cli/{metadata-UwEYCntC.js → metadata-DmXQDGq9.js} +3 -3
  216. package/dist/cli/{migrate-D-GzXR4D.js → migrate-DG4_cemN.js} +1 -1
  217. package/dist/cli/{migration-safety-Cg9jf2s-.js → migration-safety-CMvBM2Vi.js} +1 -1
  218. package/dist/cli/{migrations-Bhcf7MHM.js → migrations-B88uNBtB.js} +2 -2
  219. package/dist/cli/{module-migration-BJaOdOWy.js → module-migration-CrVdvTsm.js} +2 -2
  220. package/dist/cli/{powersync-DQKdjG_K.js → powersync-CiWMuRwt.js} +3 -3
  221. package/dist/cli/powersync-TFSmK9XH.js +1 -0
  222. package/dist/cli/{print-B1onZWRG.js → print-DJtwCt5U.js} +2 -2
  223. package/dist/cli/{providers-M7s8btf1.js → providers-CN8w11Yf.js} +1 -1
  224. package/dist/cli/{prune-workflows-BiRF1YBZ.js → prune-workflows-Bwzd1_z4.js} +1 -1
  225. package/dist/cli/{remove-BHyzqWNm.js → remove-D4fXl2zz.js} +6 -6
  226. package/dist/cli/{render-DDCy_0V_.js → render-Fafpgh5a.js} +3 -3
  227. package/dist/cli/{run-DDUBMkbN.js → run-BM4C0L-r.js} +9 -9
  228. package/dist/cli/{run-Csm1-Uto.js → run-du7PclzJ.js} +31 -31
  229. package/dist/cli/{shared-Cv22MEAO.js → shared-l0oG47Rc.js} +1 -1
  230. package/dist/cli/{snapshot-9xnSt525.js → snapshot-DAVFBIVQ.js} +2 -2
  231. package/dist/cli/{source-B_miugrh.js → source-CfPOobxZ.js} +1 -1
  232. package/dist/cli/{spec-dYLJbr9J.js → spec-DCSih_mA.js} +2 -2
  233. package/dist/cli/{spec-BeAgQ-of.js → spec-Dlbmh0EH.js} +1 -1
  234. package/dist/cli/{sql-layout-3YU4941N.js → sql-layout-DpCFWUnX.js} +2 -2
  235. package/dist/cli/{sync-Bfwk4Ldc.js → sync-3LMoCI1x.js} +4 -4
  236. package/dist/cli/{upgrade-BMrkzAcD.js → upgrade-4A6oQN-6.js} +5 -5
  237. package/dist/cli/{upgrade-DRvMFW2T.js → upgrade-DyE_4LAn.js} +2 -2
  238. package/dist/cli/{version-BXjNETWS.js → version-DaV4RlVP.js} +1 -1
  239. package/dist/client/index.d.ts +5 -5
  240. package/dist/client/native/index.d.ts +4 -4
  241. package/dist/config/index.d.ts +4 -4
  242. package/dist/config/index.js +4 -4
  243. package/dist/{config-CsX2THwJ.js → config-Bx3UYp8b.js} +3 -3
  244. package/dist/{config-Dgl6AxKE.js → config-CAjlOSQY.js} +1 -1
  245. package/dist/{context-DSJpfeVv.d.ts → context-C3-QkbC2.d.ts} +3 -3
  246. package/dist/contract/index.d.ts +3 -3
  247. package/dist/{controller-BVee4yX8.d.ts → controller-6_Uo4WEe.d.ts} +1 -1
  248. package/dist/{conversion-BPkWkVoa.d.ts → conversion-kJKGDyKY.d.ts} +1 -1
  249. package/dist/create/index.d.ts +4 -4
  250. package/dist/create/index.js +3 -3
  251. package/dist/create/lite/index.d.ts +3 -3
  252. package/dist/create/lite/index.js +2 -2
  253. package/dist/deadlines-values-vmaCCdGl.js +92 -0
  254. package/dist/{define-block-Cu67KCN1.d.ts → define-block-Dle1hNrI.d.ts} +1 -1
  255. package/dist/{drive-D008IDpI.d.ts → drive-C2EYvBxH.d.ts} +1 -1
  256. package/dist/{entitlements-CRBZg5y2.d.ts → entitlements-Bb-dOARS.d.ts} +1 -1
  257. package/dist/{extract-BU5w3k5s.d.ts → extract-BwhGjyWJ.d.ts} +1 -1
  258. package/dist/{field-errors-CjEgbjO9.d.ts → field-errors-CjEfOrH1.d.ts} +5 -5
  259. package/dist/{index-voglIa16.d.ts → index-2gyZE8Rf.d.ts} +3 -3
  260. package/dist/{index-CDEzb5bl.d.ts → index-B5Qh7kMt.d.ts} +1 -1
  261. package/dist/{index-DhS8Qkgj.d.ts → index-BE4JTKF9.d.ts} +2 -2
  262. package/dist/{index-DYzQ_PPW.d.ts → index-BEmlle8t.d.ts} +1 -1
  263. package/dist/{index-BDn4Mqq0.d.ts → index-BEtCBklB.d.ts} +1 -1
  264. package/dist/{index-AmPcMT_X.d.ts → index-BY1YQVSU.d.ts} +1 -1
  265. package/dist/{index-Dyq6B4gZ.d.ts → index-BYV1G4-b.d.ts} +2 -2
  266. package/dist/{index-DZRsTCds.d.ts → index-BjIGMnQ0.d.ts} +1 -1
  267. package/dist/{index-CKdNndE3.d.ts → index-BqD3Iu_J.d.ts} +2 -2
  268. package/dist/{index-BTl5A8Aj.d.ts → index-BqJum_h9.d.ts} +1 -1
  269. package/dist/{index-DtMdKIJU.d.ts → index-Buxrux0m.d.ts} +2 -2
  270. package/dist/{index-DR4P3Lf9.d.ts → index-BzrihVGI.d.ts} +2 -2
  271. package/dist/{index-BeU2DRAI.d.ts → index-C8S7_Q8r.d.ts} +1 -1
  272. package/dist/{index-r3QZBY7z.d.ts → index-CC34bHDQ.d.ts} +1 -1
  273. package/dist/{index-_RnZChF8.d.ts → index-CN3C6JkR.d.ts} +1 -1
  274. package/dist/{index-CaW37FHZ.d.ts → index-CNuolr9n.d.ts} +1 -1
  275. package/dist/{index-DJ1Uk4ff.d.ts → index-COIhSgY7.d.ts} +4 -4
  276. package/dist/{index-BOZ6AsMs.d.ts → index-Cg7SR_qX.d.ts} +1 -1
  277. package/dist/{index-BvPirjfD.d.ts → index-Cm8MeW9i.d.ts} +4 -4
  278. package/dist/{index-ChaJiMkI.d.ts → index-CwPttFTz.d.ts} +2 -2
  279. package/dist/{index-u8EXkOzJ.d.ts → index-D1O-RJWe.d.ts} +1 -1
  280. package/dist/{index-BleHtlJ6.d.ts → index-D9nVD78s.d.ts} +1 -1
  281. package/dist/{index-dMGEJLxl.d.ts → index-DBFr7a8o.d.ts} +1 -1
  282. package/dist/{index-BVJsz3pS.d.ts → index-DOfmW2AH.d.ts} +2 -2
  283. package/dist/{index-D5nY5k-2.d.ts → index-DSAikYZQ.d.ts} +7 -7
  284. package/dist/{index-D-3fZP5z.d.ts → index-DbCYIGAY.d.ts} +1 -1
  285. package/dist/{index--7HXH_H_.d.ts → index-DdMcDiIK.d.ts} +2 -2
  286. package/dist/{index-DsA7MQwZ.d.ts → index-Ddo11etS.d.ts} +1 -1
  287. package/dist/{index-BR8ZkijS.d.ts → index-DugPUkCG.d.ts} +2 -2
  288. package/dist/{index-BoCyVsCr.d.ts → index-DwDtMCDt.d.ts} +1 -1
  289. package/dist/{index-_wr8wCe9.d.ts → index-Dx6jNpfl.d.ts} +1 -1
  290. package/dist/{index-D7zwaGAP.d.ts → index-Dxza7aew.d.ts} +1 -1
  291. package/dist/{index-ilxdL8pz.d.ts → index-NzTBsdNG.d.ts} +1 -1
  292. package/dist/{index-DDDHYXtr.d.ts → index-U2_mkKvZ.d.ts} +8 -8
  293. package/dist/{index-JzAR_Y7n.d.ts → index-bTW0dRZY.d.ts} +3 -3
  294. package/dist/{index-E_Q5L9PV.d.ts → index-hctpn1Mt.d.ts} +1 -1
  295. package/dist/{index-slG4UpF_.d.ts → index-yL19hBMN.d.ts} +2 -2
  296. package/dist/{instances-BMjIO6Xu.js → instances-z6DJn2Gr.js} +20 -1
  297. package/dist/{manifest-CbKgs5qA.d.ts → manifest-2z4m-cwI.d.ts} +1 -1
  298. package/dist/{manifest-CoFpa0dN.d.ts → manifest-64Zd4QzL.d.ts} +1 -1
  299. package/dist/{manifest-DhpmWh55.d.ts → manifest-9tZFwb_N.d.ts} +1 -1
  300. package/dist/{manifest-BZL2TAB1.d.ts → manifest-B0-5rKJ_.d.ts} +1 -1
  301. package/dist/{manifest-CELTce26.d.ts → manifest-B0ByrOJ2.d.ts} +1 -1
  302. package/dist/{manifest-CGZQ9lU3.d.ts → manifest-B4yf2Fir.d.ts} +1 -1
  303. package/dist/{manifest-D2Z_2z9-.d.ts → manifest-BBETqrI-.d.ts} +1 -1
  304. package/dist/{manifest-CMnLDDS3.d.ts → manifest-BEFiuvqo.d.ts} +1 -1
  305. package/dist/{manifest-BE7UwezO.d.ts → manifest-BG6K9qvU.d.ts} +1 -1
  306. package/dist/{manifest-6PhMgCFi.d.ts → manifest-BOkGzZcG.d.ts} +1 -1
  307. package/dist/{manifest-BzsuqiQx.d.ts → manifest-BReV7Ehb.d.ts} +1 -1
  308. package/dist/{manifest-CdD44xlg.d.ts → manifest-BSmnJW4X.d.ts} +1 -1
  309. package/dist/{manifest-DYPVnKW_.d.ts → manifest-BV8_wZab.d.ts} +1 -1
  310. package/dist/{manifest-xikzppm9.d.ts → manifest-BXvY6i0C.d.ts} +1 -1
  311. package/dist/{manifest-lzwWCAYV.d.ts → manifest-BbUa_z3D.d.ts} +1 -1
  312. package/dist/{manifest-Eazz96as.d.ts → manifest-BcurR7jz.d.ts} +1 -1
  313. package/dist/{manifest-BknZ4yQ-.d.ts → manifest-BfWK-zw_.d.ts} +1 -1
  314. package/dist/{manifest-Dk_7prKx.d.ts → manifest-Bl4kFo6c.d.ts} +1 -1
  315. package/dist/{manifest-CSHNTEJZ.d.ts → manifest-Bsr9SSG5.d.ts} +1 -1
  316. package/dist/{manifest-DxPLHyKY.d.ts → manifest-BtI5HhXk.d.ts} +1 -1
  317. package/dist/{manifest-BMNwdO5D.d.ts → manifest-BxY9kn1w.d.ts} +1 -1
  318. package/dist/{manifest-BSvxbZH5.d.ts → manifest-C2QmAn2x.d.ts} +1 -1
  319. package/dist/{manifest-DhXoSaUC.d.ts → manifest-C5CZYXC2.d.ts} +1 -1
  320. package/dist/{manifest-Bz0EjE76.d.ts → manifest-C9PoeugH.d.ts} +1 -1
  321. package/dist/{manifest-DwCorUVJ.d.ts → manifest-C9x5lxeF.d.ts} +1 -1
  322. package/dist/{manifest-CaA-2HPK.d.ts → manifest-CKAtEVtk.d.ts} +1 -1
  323. package/dist/{manifest-C_dVunWg.d.ts → manifest-CVQ3q-JJ.d.ts} +1 -1
  324. package/dist/{manifest-BYbt4y_O.d.ts → manifest-CWKtnWcS.d.ts} +1 -1
  325. package/dist/{manifest-Dl_bw4IU.d.ts → manifest-CchgUbRg.d.ts} +1 -1
  326. package/dist/{manifest-auanzyjB.d.ts → manifest-Cjt5fW9U.d.ts} +1 -1
  327. package/dist/{manifest-Bp0oZ3-W.d.ts → manifest-CuuE9u0c.d.ts} +1 -1
  328. package/dist/{manifest-D7mliM-d.d.ts → manifest-D23v7_Fg.d.ts} +1 -1
  329. package/dist/{manifest-CGcGylmw.d.ts → manifest-D9fWfK2i.d.ts} +1 -1
  330. package/dist/{manifest-DMvx2rWH.d.ts → manifest-DGHeP3gy.d.ts} +1 -1
  331. package/dist/{manifest-DGiswyG5.d.ts → manifest-DGePKO35.d.ts} +1 -1
  332. package/dist/{manifest-gGFtQDJz.d.ts → manifest-DHAShiq8.d.ts} +1 -1
  333. package/dist/{manifest-DPqKZgWn.d.ts → manifest-DPSgN4LB.d.ts} +1 -1
  334. package/dist/{manifest-D2d1wS7g.d.ts → manifest-DPeSW0P5.d.ts} +1 -1
  335. package/dist/{manifest-CBwrN4Nf.d.ts → manifest-DT4l91L_.d.ts} +1 -1
  336. package/dist/{manifest-Pl5us_yz.d.ts → manifest-DUA64Tnn.d.ts} +1 -1
  337. package/dist/{manifest-DUlZ8qck.d.ts → manifest-DVBfzRly.d.ts} +1 -1
  338. package/dist/{manifest-uIIb_YLI.d.ts → manifest-DXuOYu6Q.d.ts} +1 -1
  339. package/dist/{manifest-Df1QDhiQ.d.ts → manifest-D_AT0kqo.d.ts} +1 -1
  340. package/dist/{manifest-B4CEdcH_.d.ts → manifest-D_aJ09Il.d.ts} +1 -1
  341. package/dist/{manifest-D_VmA0aC.d.ts → manifest-D_kxP0yH.d.ts} +1 -1
  342. package/dist/{manifest-X4analSK.d.ts → manifest-DgtO2rew.d.ts} +1 -1
  343. package/dist/{manifest-DG0oDOmq.d.ts → manifest-DiKKpytg.d.ts} +1 -1
  344. package/dist/{manifest-BVjhJ3Mj.d.ts → manifest-DlWg4mC8.d.ts} +1 -1
  345. package/dist/{manifest-DAXz8rxB.d.ts → manifest-DlyGRc_x.d.ts} +1 -1
  346. package/dist/{manifest-BB3GjGa3.d.ts → manifest-DreoW4xj.d.ts} +1 -1
  347. package/dist/{manifest-Dc8pNExY.d.ts → manifest-Gwsis09w.d.ts} +1 -1
  348. package/dist/{manifest-CWj5SFuw.d.ts → manifest-K1yCH7Ai.d.ts} +1 -1
  349. package/dist/{manifest-DtEcJBdE.d.ts → manifest-TSUBAvih.d.ts} +1 -1
  350. package/dist/{manifest-DsuoLp-Y.d.ts → manifest-WuPrNtWh.d.ts} +1 -1
  351. package/dist/{manifest-yKx0faak.d.ts → manifest-b1ei2NBj.d.ts} +1 -1
  352. package/dist/{manifest-BXxSqnLS.d.ts → manifest-byZwzlAG.d.ts} +1 -1
  353. package/dist/{manifest-D9P9Yhe3.d.ts → manifest-fUQWT0ft.d.ts} +1 -1
  354. package/dist/{manifest-DGLrMEdB.d.ts → manifest-hrX9Hsgd.d.ts} +1 -1
  355. package/dist/{manifest-D0FjVeay.d.ts → manifest-iRyMyb7t.d.ts} +1 -1
  356. package/dist/{manifest-B17Sra5h.d.ts → manifest-r5iVaZrT.d.ts} +1 -1
  357. package/dist/{manifest-DIZ6chpf.d.ts → manifest-xVl_34TT.d.ts} +1 -1
  358. package/dist/{manifest-CMNPpmWS.d.ts → manifest-yUJGXgsd.d.ts} +2 -2
  359. package/dist/mapper/bin.js +5 -5
  360. package/dist/mcp/index.d.ts +1 -1
  361. package/dist/next/index.d.ts +7 -7
  362. package/dist/{operations-DKfYeS5z.d.ts → operations-DvIB3N20.d.ts} +1 -1
  363. package/dist/otel/index.js +4 -4
  364. package/dist/{permissions-C5h1cU25.d.ts → permissions-CtS73Ot8.d.ts} +1 -1
  365. package/dist/{ports-DvaVv_3b.d.ts → ports-D_z0B0OU.d.ts} +1 -1
  366. package/dist/powersync/index.d.ts +2 -2
  367. package/dist/preset/index.d.ts +4 -4
  368. package/dist/preset/index.js +3 -3
  369. package/dist/{preset-Cl3Q5ASC.js → preset-CPUA9haY.js} +3 -3
  370. package/dist/{preview-Bwg7r1Lf.d.ts → preview-B0MvbKqQ.d.ts} +2 -2
  371. package/dist/{project-At5wBJSS.js → project-CMRUh_6Z.js} +5 -5
  372. package/dist/{push-token-C6ZGE1g0.d.ts → push-token--jdbVbWv.d.ts} +1 -1
  373. package/dist/query/index.d.ts +1 -1
  374. package/dist/react/index.d.ts +5 -5
  375. package/dist/react/native/index.d.ts +1 -1
  376. package/dist/react/server.d.ts +5 -5
  377. package/dist/realtime/index.d.ts +3 -3
  378. package/dist/{record-form-DTncyqVH.d.ts → record-form-Bb3mf114.d.ts} +1 -1
  379. package/dist/records/index.d.ts +7 -7
  380. package/dist/server/index.d.ts +3 -3
  381. package/dist/solid/index.d.ts +5 -5
  382. package/dist/sql/index.d.ts +5 -5
  383. package/dist/sql/index.js +2 -2
  384. package/dist/{sql-CdZdPqjA.js → sql-DXME28Gr.js} +1560 -264
  385. package/dist/ssr/index.d.ts +1 -1
  386. package/dist/svelte/index.d.ts +5 -5
  387. package/dist/{tenant-BTnwa5oZ.d.ts → tenant-sm9d_APF.d.ts} +1 -1
  388. package/dist/testing/index.d.ts +6 -6
  389. package/dist/testing/index.js +1 -1
  390. package/dist/{timeline-B7kBQ1gh.d.ts → timeline-BR-oKhI4.d.ts} +2 -2
  391. package/dist/{topic-hu0RP7CG.d.ts → topic-CBTgUy6t.d.ts} +1 -1
  392. package/dist/{types-DvglaQ_D.d.ts → types-DRNzKqdm.d.ts} +2 -2
  393. package/dist/vue/index.d.ts +5 -5
  394. package/dist/{watch-topic-C_rGHxIA.d.ts → watch-topic-DYDnWH_a.d.ts} +1 -1
  395. package/dist/webmcp/index.d.ts +1 -1
  396. package/dist/yjs/index.d.ts +1 -1
  397. package/package.json +1 -1
  398. package/dist/cli/add-D0TUMxXn.js +0 -1
  399. package/dist/cli/powersync-Bn-u0TGP.js +0 -1
  400. package/dist/deadlines-values-B7ArpVJU.js +0 -127
@@ -6,10 +6,10 @@ import { a as hasPlaceholder, l as splitPlaceholders, r as containsPlaceholder,
6
6
  import { r as isFunctionSpec } from "./spec-BSc8n34a.js";
7
7
  import { a as OPERATION_RENAMES, c as PROGRAM_EVENT_MOVES, f as configuredAction, g as isOldPermissionKey, i as EVENT_TYPE_SPLITS, m as currentPermissionKeys, o as PERMISSION_KEY_RENAMES, p as currentEventTypes, r as EVENT_TYPE_RENAMES, s as PERMISSION_KEY_SPLITS, t as ENTITY_KEY_RENAMES, u as SUBJECT_TYPE_RENAMES } from "./renames-PnqMkqit.js";
8
8
  import { t as SPEC_PINS } from "./spec-pins-Dlz8OVqi.js";
9
- import { _ as resolveJsonSchema, a as blockFormerSubjectTypes, d as freesTableName, f as tableBase, g as clientFunctions, h as resolveNames, l as blockColumnName, m as entityType, p as tableMoves, s as installedBlockSubjects, u as columnRenamer, v as CONFIG_DEFAULTS } from "./block-subjects-BoJrJAgR.js";
9
+ import { _ as resolveJsonSchema, a as blockFormerSubjectTypes, d as freesTableName, f as tableBase, g as clientFunctions, h as resolveNames, l as blockColumnName, m as entityType, p as tableMoves, s as installedBlockSubjects, u as columnRenamer, v as CONFIG_DEFAULTS } from "./block-subjects-B9hb1LLk.js";
10
10
  import { t as DEFAULT_CLAIMS } from "./claims-CqTr_N1n.js";
11
11
  import { o as tenantNames, r as composeNames } from "./entity-naming-BES3pkQI.js";
12
- import { B as resolveBlock, C as columnsWithAccess, E as hiddenColumns, I as PRESET_CATALOG, L as BLOCK_SCOPES, N as createdFromLink, P as link, S as hasComputed, T as hasColumnAccess, V as tenantNameOf, 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-BMjIO6Xu.js";
12
+ import { B as resolveBlock, C as columnsWithAccess, E as hiddenColumns, I as PRESET_CATALOG, L as BLOCK_SCOPES, N as createdFromLink, P as link, S as hasComputed, T as hasColumnAccess, V as tenantNameOf, 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-z6DJn2Gr.js";
13
13
  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";
14
14
  import { t as isSqlType } from "./sql-type-XWMeZRAl.js";
15
15
  import { a as sqlString, i as sqlIdent$1 } from "./template-1e2akYYK.js";
@@ -167,7 +167,7 @@ import { t as ISO_4217_MINOR_UNITS } from "./iso4217-oKsif_hW.js";
167
167
  import { a as moveStock, c as stockHistory, d as variantTracked, i as locationsOf, l as strict, n as guard$13, o as reservationFunctions, r as locationFunctions, s as stockFunctions, t as columns$1, u as threshold } from "./inventory-stock-DadU4mb2.js";
168
168
  import { a as CARE_BUILT_IN_SOURCE, i as CARE_ALERT_STATUSES, n as CARE_ALERT_KINDS, o as CARE_RULE_KINDS, r as CARE_ALERT_SEVERITIES, t as CARE_ALERT_DECISIONS } from "./clinical-decision-support-values-Bk1AzL7L.js";
169
169
  import { t as DAM_RENDITION_STATUSES } from "./dam-values-C1SGxSoe.js";
170
- import { a as OFFSET_UNITS, i as OFFSET_LIMIT, n as DEADLINE_RESULTS, o as RULE_VERSION_STATUSES, r as DEADLINE_STATES, t as DEADLINE_ADJUSTMENTS } from "./deadlines-values-B7ArpVJU.js";
170
+ import { a as EXCEPTION_RESULTS, c as LAST_FURNISHING_FACT, d as OBSERVED_FALLS_ON, f as OBSERVED_MOVES, g as ROLL_DAYS, h as PART_STATUSES, i as DEADLINE_STATES, l as META_LIMIT, m as OFFSET_UNITS, o as FIRST_FURNISHING_FACT, p as OFFSET_LIMIT, r as DEADLINE_RESULTS, t as DEADLINE_ADJUSTMENTS, u as NOTE_LIMIT, v as RULE_VERSION_STATUSES, y as WEEKDAYS } from "./deadlines-values-vmaCCdGl.js";
171
171
  import { i as FORM_SCHEMA_DIALECT, o as UNSCORED_FIELD_TYPES, r as FORM_MAX_LENGTH, t as FORM_DEFINITION_SCHEMA } from "./form-definition-DbyY2DKZ.js";
172
172
  import { r as operationPermission, t as OPERATION_PREFIXES } from "./operations-BNFbWv1t.js";
173
173
  import { i as MAINTENANCE_PRIORITIES, n as MAINTENANCE_PLAN_KINDS, r as MAINTENANCE_PLAN_STATUSES, t as MAINTENANCE_CALIBRATION_RESULTS } from "./maintenance-values-DlqhkGvQ.js";
@@ -15555,7 +15555,7 @@ const NAMES$149 = {
15555
15555
  }
15556
15556
  }
15557
15557
  };
15558
- const list$37 = (values) => values.map((value) => sqlString(value)).join(", ");
15558
+ const list$38 = (values) => values.map((value) => sqlString(value)).join(", ");
15559
15559
  /** A block context of another module, when it is installed and not custom. */
15560
15560
  function linked$7(ctx, module) {
15561
15561
  return ctx.installed(module) && ctx.of(module).mode !== "custom" ? ctx.of(module) : void 0;
@@ -15639,8 +15639,8 @@ create table if not exists ${sessions} (
15639
15639
  ${s("id")} uuid primary key default gen_random_uuid(),
15640
15640
  ${s("tenant")} ${id} not null,
15641
15641
  ${s("cart")} uuid not null,
15642
- ${s("protocol")} text not null check (${s("protocol")} in (${list$37(CHECKOUT_PROTOCOLS)})),
15643
- ${s("status")} text not null default 'open' check (${s("status")} in (${list$37(CHECKOUT_SESSION_STATUSES)})),
15642
+ ${s("protocol")} text not null check (${s("protocol")} in (${list$38(CHECKOUT_PROTOCOLS)})),
15643
+ ${s("status")} text not null default 'open' check (${s("status")} in (${list$38(CHECKOUT_SESSION_STATUSES)})),
15644
15644
  ${s("idempotencyKey")} text not null check (length(${s("idempotencyKey")}) between 1 and 255),
15645
15645
  ${s("requestHash")} text not null check (length(${s("requestHash")}) between 1 and 128),
15646
15646
  ${s("buyer")} jsonb,
@@ -15663,8 +15663,8 @@ create table if not exists ${mandates} (
15663
15663
  ${m("id")} uuid primary key default gen_random_uuid(),
15664
15664
  ${m("tenant")} ${id} not null,
15665
15665
  ${m("session")} uuid${ctx.owns("sessions") ? ` references ${sessions} (${s("id")}) on delete set null` : ""},
15666
- ${m("vct")} text not null check (${m("vct")} in (${list$37(AGENT_MANDATE_TYPES)})),
15667
- ${m("status")} text not null default 'active' check (${m("status")} in (${list$37(AGENT_MANDATE_STATUSES)})),
15666
+ ${m("vct")} text not null check (${m("vct")} in (${list$38(AGENT_MANDATE_TYPES)})),
15667
+ ${m("status")} text not null default 'active' check (${m("status")} in (${list$38(AGENT_MANDATE_STATUSES)})),
15668
15668
  ${m("credential")} text not null check (length(${m("credential")}) between 1 and 16384),
15669
15669
  ${m("credentialHash")} text not null check (length(${m("credentialHash")}) between 1 and 128),
15670
15670
  ${m("issuerKid")} text,
@@ -15696,7 +15696,7 @@ begin
15696
15696
  if not ${allowed("create_checkout_session.tenant", write)} then
15697
15697
  ${fail("CHECKOUT_FORBIDDEN", "not allowed to start checkout sessions")}
15698
15698
  end if;
15699
- if create_checkout_session.protocol is null or create_checkout_session.protocol not in (${list$37(CHECKOUT_PROTOCOLS)}) then
15699
+ if create_checkout_session.protocol is null or create_checkout_session.protocol not in (${list$38(CHECKOUT_PROTOCOLS)}) then
15700
15700
  ${invalid("the protocol is acp or ucp")}
15701
15701
  end if;
15702
15702
  if coalesce(create_checkout_session.idempotency_key, '') = '' or coalesce(create_checkout_session.request_hash, '') = '' then
@@ -15889,7 +15889,7 @@ begin
15889
15889
  if not ${allowed("store_agent_mandate.tenant", write)} then
15890
15890
  ${fail("AGENT_MANDATE_FORBIDDEN", "not allowed to store mandates")}
15891
15891
  end if;
15892
- if coalesce(v_input ->> 'vct', '') not in (${list$37(AGENT_MANDATE_TYPES)}) then
15892
+ if coalesce(v_input ->> 'vct', '') not in (${list$38(AGENT_MANDATE_TYPES)}) then
15893
15893
  ${fail("AGENT_MANDATE_INVALID", "vct is mandate.checkout.open.1 or mandate.checkout.1", "22023")}
15894
15894
  end if;
15895
15895
  if coalesce(v_input ->> 'credential', '') = '' or coalesce(v_input ->> 'credentialHash', '') = '' or coalesce(v_input ->> 'expiresAt', '') = '' then
@@ -21043,7 +21043,7 @@ function permissionHolders(ctx, layout, permission, tenant) {
21043
21043
  // src/sql/modules/contacts-representatives.ts
21044
21044
  /** The relation kind a representative's link has. */
21045
21045
  const REPRESENTS = "represents";
21046
- const list$36 = (values) => values.map((value) => sqlString(value)).join(", ");
21046
+ const list$37 = (values) => values.map((value) => sqlString(value)).join(", ");
21047
21047
  /** Whether `key` of `data` (a jsonb expression) is missing or a date string. */
21048
21048
  const dateOrMissing = (data, key) => `(${data} -> '${key}' is null or (jsonb_typeof(${data} -> '${key}') = 'string' and pg_input_is_valid(${data} ->> '${key}', 'date')))`;
21049
21049
  /**
@@ -21054,8 +21054,8 @@ function representationData(data) {
21054
21054
  const from = `${data} ->> 'valid_from'`;
21055
21055
  const until = `${data} ->> 'valid_until'`;
21056
21056
  return `(jsonb_typeof(${data}) = 'object'
21057
- and (${data} ->> 'role') in (${list$36(REPRESENTATIVE_ROLES)})
21058
- and (${data} ->> 'authority') in (${list$36(REPRESENTATIVE_AUTHORITIES)})
21057
+ and (${data} ->> 'role') in (${list$37(REPRESENTATIVE_ROLES)})
21058
+ and (${data} ->> 'authority') in (${list$37(REPRESENTATIVE_AUTHORITIES)})
21059
21059
  and ${dateOrMissing(data, "valid_from")}
21060
21060
  and ${dateOrMissing(data, "valid_until")}
21061
21061
  and case when pg_input_is_valid(${from}, 'date') and pg_input_is_valid(${until}, 'date')
@@ -34791,7 +34791,7 @@ const NAMES$132 = {
34791
34791
  }
34792
34792
  }
34793
34793
  };
34794
- const list$35 = (values) => values.map((value) => `'${value}'`).join(", ");
34794
+ const list$36 = (values) => values.map((value) => `'${value}'`).join(", ");
34795
34795
  function tables$57(ctx) {
34796
34796
  const q = appraisalsSql(ctx);
34797
34797
  const { y, a, r, c, g, k, t, cycles, appraisals, reviews, calibrations, goals, competencies, ratings } = q;
@@ -34817,10 +34817,10 @@ create table if not exists ${cycles} (
34817
34817
  ${y("endsOn")} date not null,
34818
34818
  -- The key of the enrollment program the cycle's appraisals follow, when set.
34819
34819
  ${y("program")} text,
34820
- ${y("status")} text not null default 'draft' check (${y("status")} in (${list$35(APPRAISAL_CYCLE_STATUSES)})),
34820
+ ${y("status")} text not null default 'draft' check (${y("status")} in (${list$36(APPRAISAL_CYCLE_STATUSES)})),
34821
34821
  -- Who learns which peer wrote a review: everyone who sees it (none), anyone
34822
34822
  -- but the appraised person (subject), or only the reviewer (all).
34823
- ${y("anonymity")} text not null default 'subject' check (${y("anonymity")} in (${list$35(APPRAISAL_ANONYMITY)})),
34823
+ ${y("anonymity")} text not null default 'subject' check (${y("anonymity")} in (${list$36(APPRAISAL_ANONYMITY)})),
34824
34824
  -- Whether the appraised person reads the manager and peer reviews once the
34825
34825
  -- appraisal is signed off.
34826
34826
  ${y("shareFeedback")} boolean not null default false,
@@ -34841,7 +34841,7 @@ create table if not exists ${appraisals} (
34841
34841
  ${a("cycle")} uuid not null,
34842
34842
  ${a("subjectUser")} uuid not null,
34843
34843
  ${a("manager")} uuid,
34844
- ${a("status")} text not null default 'pending' check (${a("status")} in (${list$35(APPRAISAL_STATUSES)})),
34844
+ ${a("status")} text not null default 'pending' check (${a("status")} in (${list$36(APPRAISAL_STATUSES)})),
34845
34845
  -- The average of the submitted reviews.
34846
34846
  ${a("rating")} numeric(3, 2) check (${a("rating")} is null or ${a("rating")} between 1 and 5),
34847
34847
  -- The rating a calibration session set, when it moved.
@@ -34870,7 +34870,7 @@ create table if not exists ${reviews} (
34870
34870
  ${r("tenant")} ${ctx.idType} not null,
34871
34871
  ${r("appraisal")} uuid not null,
34872
34872
  ${r("reviewer")} uuid not null,
34873
- ${r("kind")} text not null check (${r("kind")} in (${list$35(APPRAISAL_REVIEW_KINDS)})),
34873
+ ${r("kind")} text not null check (${r("kind")} in (${list$36(APPRAISAL_REVIEW_KINDS)})),
34874
34874
  ${r("rating")} smallint check (${r("rating")} is null or ${r("rating")} between 1 and 5),
34875
34875
  ${r("comments")} text check (${r("comments")} is null or length(${r("comments")}) <= 10000),
34876
34876
  -- The forms submission with the longer answers, when the review uses a form.
@@ -45487,7 +45487,7 @@ function bankingAccountingSources(ctx) {
45487
45487
  }];
45488
45488
  }
45489
45489
  // src/sql/modules/banking-functions.ts
45490
- const list$34 = (values) => values.map((value) => `'${value}'`).join(", ");
45490
+ const list$35 = (values) => values.map((value) => `'${value}'`).join(", ");
45491
45491
  /**
45492
45492
  * The reference helpers: `bank_mod97` (ISO 7064 MOD 97-10 over letters and
45493
45493
  * digits) and `bank_reference`, the payload of an ISO 11649 RF creditor
@@ -45745,7 +45745,7 @@ begin${loadAccount("import_bank_statement.account_id", q.import, true)}
45745
45745
  ${q.statementInvalid("a statement is an object with a transactions array")}
45746
45746
  end if;
45747
45747
  v_format := coalesce(import_bank_statement.statement ->> 'format', 'feed');
45748
- if v_format not in (${list$34(STATEMENT_FORMATS)}) then
45748
+ if v_format not in (${list$35(STATEMENT_FORMATS)}) then
45749
45749
  ${q.statementInvalid("a statement's format is camt053, mt940, csv or feed")}
45750
45750
  end if;
45751
45751
  if coalesce(import_bank_statement.statement ->> 'openingBalance', '0') !~ '^-?[0-9]{1,18}$'
@@ -46415,7 +46415,7 @@ ${userGrant(`${fn("apply_bank_rules")}(uuid)`)}
46415
46415
  `;
46416
46416
  }
46417
46417
  // src/sql/modules/banking-tables.ts
46418
- const list$33 = (values) => values.map((value) => `'${value}'`).join(", ");
46418
+ const list$34 = (values) => values.map((value) => `'${value}'`).join(", ");
46419
46419
  /** The banking tables: accounts, rules, statements, transactions, matches. */
46420
46420
  function bankingTables(ctx) {
46421
46421
  const q = bankingSql(ctx);
@@ -46493,7 +46493,7 @@ create table if not exists ${q.statements} (
46493
46493
  -- Minor units of the account's currency.
46494
46494
  ${s("openingBalance")} bigint,
46495
46495
  ${s("closingBalance")} bigint,
46496
- ${s("format")} text not null check (${s("format")} in (${list$33(STATEMENT_FORMATS)})),
46496
+ ${s("format")} text not null check (${s("format")} in (${list$34(STATEMENT_FORMATS)})),
46497
46497
  -- The file it was read from.
46498
46498
  ${s("attachment")} uuid${ref(attachments, "attachments", "set null")},
46499
46499
  ${s("importedBy")} uuid,
@@ -46528,7 +46528,7 @@ create table if not exists ${q.transactions} (
46528
46528
  ${t("endToEndId")} text check (${t("endToEndId")} is null or length(${t("endToEndId")}) <= 100),
46529
46529
  -- The bank's id of the entry; importing it again adds nothing.
46530
46530
  ${t("externalId")} text not null check (length(${t("externalId")}) between 1 and 200),
46531
- ${t("status")} text not null default 'unmatched' check (${t("status")} in (${list$33(TRANSACTION_STATUSES)})),
46531
+ ${t("status")} text not null default 'unmatched' check (${t("status")} in (${list$34(TRANSACTION_STATUSES)})),
46532
46532
  -- The bank rule that matched or ignored it.
46533
46533
  ${t("rule")} uuid,
46534
46534
  ${t("matchedAt")} timestamptz,
@@ -46553,7 +46553,7 @@ create table if not exists ${q.matches} (
46553
46553
  ${m("id")} uuid primary key default gen_random_uuid(),
46554
46554
  ${m("tenant")} ${ctx.idType} not null,
46555
46555
  ${m("transaction")} uuid not null,
46556
- ${m("targetType")} text not null check (${m("targetType")} in (${list$33(MATCH_TARGETS)})),
46556
+ ${m("targetType")} text not null check (${m("targetType")} in (${list$34(MATCH_TARGETS)})),
46557
46557
  ${m("targetId")} uuid not null,
46558
46558
  -- Minor units with the transaction's sign; a transaction's matches add up to
46559
46559
  -- its amount.
@@ -54008,7 +54008,7 @@ const ALARM_ACTIONS = [
54008
54008
  ];
54009
54009
  /** A year either way, the bound `reminders` puts on its offsets too. */
54010
54010
  const TRIGGER_BOUND = 525600;
54011
- const list$32 = (values) => `(${values.map((value) => `'${value}'`).join(", ")})`;
54011
+ const list$33 = (values) => `(${values.map((value) => `'${value}'`).join(", ")})`;
54012
54012
  /**
54013
54013
  * The `calendar_event_alarms` table: one row per `VALARM` of an event, with an
54014
54014
  * offset in minutes before the start or end (`offset_minutes`, the reminders
@@ -54042,7 +54042,7 @@ function alarmsTable(ctx) {
54042
54042
  ...ctx.has("alarms", "method") ? [addCheck({
54043
54043
  table: alarms,
54044
54044
  name: `${name}_method_check`,
54045
- expression: `${l("method")} in ${list$32(ALARM_ACTIONS)}`
54045
+ expression: `${l("method")} in ${list$33(ALARM_ACTIONS)}`
54046
54046
  })] : [],
54047
54047
  addCheck({
54048
54048
  table: alarms,
@@ -54130,7 +54130,7 @@ function alarmWrites(ctx) {
54130
54130
  if exists (
54131
54131
  select 1 from jsonb_array_elements(v_item -> 'alarms') x
54132
54132
  where jsonb_typeof(x) <> 'object'
54133
- or coalesce(x ->> 'method', 'display') not in ${list$32(ALARM_ACTIONS)}
54133
+ or coalesce(x ->> 'method', 'display') not in ${list$33(ALARM_ACTIONS)}
54134
54134
  or coalesce(x ->> 'related', 'start') not in ('start', 'end')
54135
54135
  or (x ->> 'offsetMinutes' is null) = (x ->> 'at' is null)
54136
54136
  or abs(coalesce((x ->> 'offsetMinutes')::integer, 0)) > ${TRIGGER_BOUND}
@@ -58326,7 +58326,7 @@ const NAMES$119 = {
58326
58326
  }
58327
58327
  }
58328
58328
  };
58329
- const list$31 = (values) => values.map((value) => `'${value}'`).join(", ");
58329
+ const list$32 = (values) => values.map((value) => `'${value}'`).join(", ");
58330
58330
  function tables$52(ctx) {
58331
58331
  const q = carePlansSql(ctx);
58332
58332
  const { p, pr, g, a, e, plans, problems, goals, actions, evaluations } = q;
@@ -58358,7 +58358,7 @@ create table if not exists ${plans} (
58358
58358
  ${p("subjectType")} text not null check (length(${p("subjectType")}) between 1 and 63),
58359
58359
  ${p("subjectId")} text not null check (length(${p("subjectId")}) between 1 and 200),
58360
58360
  ${p("title")} text not null check (length(${p("title")}) between 1 and 300),
58361
- ${p("status")} text not null default 'draft' check (${p("status")} in (${list$31(CARE_PLAN_STATUSES)})),
58361
+ ${p("status")} text not null default 'draft' check (${p("status")} in (${list$32(CARE_PLAN_STATUSES)})),
58362
58362
  -- 1 for a subject's first plan, one more for each plan after it.
58363
58363
  ${p("version")} integer not null default 1 check (${p("version")} >= 1),
58364
58364
  ${p("startsOn")} date,
@@ -58394,7 +58394,7 @@ create table if not exists ${problems} (
58394
58394
  ${text(pr("code"), 100)},
58395
58395
  ${pr("title")} text not null check (length(${pr("title")}) between 1 and 300),
58396
58396
  ${text(pr("description"), 1e4)},
58397
- ${pr("status")} text not null default 'active' check (${pr("status")} in (${list$31(CARE_PLAN_PROBLEM_STATUSES)})),
58397
+ ${pr("status")} text not null default 'active' check (${pr("status")} in (${list$32(CARE_PLAN_PROBLEM_STATUSES)})),
58398
58398
  ${rank(pr("rank"))},
58399
58399
  ${pr("createdAt")} timestamptz not null default now(),
58400
58400
  ${pr("updatedAt")} timestamptz not null default now(),
@@ -58412,7 +58412,7 @@ create table if not exists ${goals} (
58412
58412
  ${g("problem")} uuid not null,
58413
58413
  ${g("title")} text not null check (length(${g("title")}) between 1 and 300),
58414
58414
  ${g("targetOn")} date,
58415
- ${g("status")} text not null default 'planned' check (${g("status")} in (${list$31(CARE_PLAN_GOAL_STATUSES)})),
58415
+ ${g("status")} text not null default 'planned' check (${g("status")} in (${list$32(CARE_PLAN_GOAL_STATUSES)})),
58416
58416
  -- How progress is measured, such as { "kind": "score", "target": 3 }.
58417
58417
  ${g("measure")} jsonb check (${g("measure")} is null or jsonb_typeof(${g("measure")}) = 'object'),
58418
58418
  ${rank(g("rank"))},
@@ -58430,7 +58430,7 @@ create table if not exists ${actions} (
58430
58430
  ${a("tenant")} ${ctx.idType} not null,
58431
58431
  ${a("plan")} uuid not null,
58432
58432
  ${a("goal")} uuid not null,
58433
- ${a("kind")} text not null default 'intervention' check (${a("kind")} in (${list$31(CARE_PLAN_ACTION_KINDS)})),
58433
+ ${a("kind")} text not null default 'intervention' check (${a("kind")} in (${list$32(CARE_PLAN_ACTION_KINDS)})),
58434
58434
  ${a("title")} text not null check (length(${a("title")}) between 1 and 300),
58435
58435
  ${text(a("instructions"), 1e4)},
58436
58436
  -- How often, such as { "every": "P1D", "times": ["08:00", "20:00"] }.
@@ -58452,7 +58452,7 @@ create table if not exists ${actions} (
58452
58452
  ${a("reviewNotifiedAt")} timestamptz,
58453
58453
  ${a("startsOn")} date,
58454
58454
  ${a("endsOn")} date,
58455
- ${a("status")} text not null default 'planned' check (${a("status")} in (${list$31(CARE_PLAN_ACTION_STATUSES)})),
58455
+ ${a("status")} text not null default 'planned' check (${a("status")} in (${list$32(CARE_PLAN_ACTION_STATUSES)})),
58456
58456
  ${a("startedAt")} timestamptz,
58457
58457
  ${a("endedAt")} timestamptz,
58458
58458
  ${text(a("endReason"), 2e3)},
@@ -58477,7 +58477,7 @@ create table if not exists ${evaluations} (
58477
58477
  ${e("goal")} uuid not null,
58478
58478
  ${e("evaluatedAt")} timestamptz not null default now(),
58479
58479
  -- The goal's status the evaluation found.
58480
- ${e("status")} text not null check (${e("status")} in (${list$31(CARE_PLAN_GOAL_STATUSES)})),
58480
+ ${e("status")} text not null check (${e("status")} in (${list$32(CARE_PLAN_GOAL_STATUSES)})),
58481
58481
  ${text(e("outcome"), 1e4)},
58482
58482
  -- The forms submission that recorded the evaluation, if one did.
58483
58483
  ${e("submission")} uuid,
@@ -61409,7 +61409,7 @@ const NAMES$118 = {
61409
61409
  }
61410
61410
  }
61411
61411
  };
61412
- const list$30 = (values) => values.map((value) => `'${value}'`).join(", ");
61412
+ const list$31 = (values) => values.map((value) => `'${value}'`).join(", ");
61413
61413
  function tables$51(ctx) {
61414
61414
  const q = casesSql(ctx);
61415
61415
  const { k, c, a, kinds, cases, actions } = q;
@@ -61473,7 +61473,7 @@ create table if not exists ${cases} (
61473
61473
  ${c("stage")} uuid,
61474
61474
  ${c("stageEnteredAt")} timestamptz,
61475
61475
  -- Follows the stage's outcome: open, closed (success) or canceled (failure).
61476
- ${c("status")} text not null default 'open' check (${c("status")} in (${list$30(CASE_STATUSES)})),
61476
+ ${c("status")} text not null default 'open' check (${c("status")} in (${list$31(CASE_STATUSES)})),
61477
61477
  ${text(c("rootCause"), 1e4)},
61478
61478
  ${c("rootCauseSubmission")} uuid,
61479
61479
  ${c("effective")} boolean,
@@ -61508,7 +61508,7 @@ create table if not exists ${actions} (
61508
61508
  -- A work item of the tasks block.
61509
61509
  -- No foreign key: the work items table renders after this one.
61510
61510
  ${a("task")} uuid not null,
61511
- ${a("type")} text not null check (${a("type")} in (${list$30(CASE_ACTION_TYPES)})),
61511
+ ${a("type")} text not null check (${a("type")} in (${list$31(CASE_ACTION_TYPES)})),
61512
61512
  ${a("required")} boolean not null default true,
61513
61513
  ${a("createdAt")} timestamptz not null default now(),
61514
61514
  unique (${a("case")}, ${a("task")}),
@@ -62575,7 +62575,7 @@ const MAPPING_FIELDS = [
62575
62575
  "keywords"
62576
62576
  ];
62577
62577
  const NO_PARTY = "'00000000-0000-0000-0000-000000000000'::uuid";
62578
- const list$29 = (values) => values.map((value) => `'${value}'`).join(", ");
62578
+ const list$30 = (values) => values.map((value) => `'${value}'`).join(", ");
62579
62579
  /**
62580
62580
  * Whether a table added in version 5 exists: always when managed, and when the
62581
62581
  * app maps it on an adopted catalog.
@@ -62624,7 +62624,7 @@ create table if not exists ${t("identifiers")} (
62624
62624
  ${c("identifiers", "id")} uuid primary key default gen_random_uuid(),
62625
62625
  ${c("identifiers", "tenant")} ${ctx.idType} not null,
62626
62626
  ${c("identifiers", "variant")} uuid not null references ${t("variants")} (${c("variants", "id")}) on delete cascade,
62627
- ${c("identifiers", "type")} text not null check (${c("identifiers", "type")} in (${list$29(IDENTIFIER_TYPES)})),
62627
+ ${c("identifiers", "type")} text not null check (${c("identifiers", "type")} in (${list$30(IDENTIFIER_TYPES)})),
62628
62628
  ${c("identifiers", "value")} text not null check (length(${c("identifiers", "value")}) between 1 and 100),
62629
62629
  -- The supplier or manufacturer the code belongs to; a soft reference, so the
62630
62630
  -- contacts block stays optional.
@@ -62643,7 +62643,7 @@ create table if not exists ${t("relations")} (
62643
62643
  ${c("relations", "tenant")} ${ctx.idType} not null,
62644
62644
  ${c("relations", "from")} uuid not null references ${t("variants")} (${c("variants", "id")}) on delete cascade,
62645
62645
  ${c("relations", "to")} uuid not null references ${t("variants")} (${c("variants", "id")}) on delete cascade,
62646
- ${c("relations", "kind")} text not null check (${c("relations", "kind")} in (${list$29(RELATION_KINDS)})),
62646
+ ${c("relations", "kind")} text not null check (${c("relations", "kind")} in (${list$30(RELATION_KINDS)})),
62647
62647
  ${c("relations", "createdAt")} timestamptz not null default now(),
62648
62648
  primary key (${c("relations", "from")}, ${c("relations", "to")}, ${c("relations", "kind")}),
62649
62649
  check (${c("relations", "from")} <> ${c("relations", "to")})
@@ -62692,7 +62692,7 @@ ${readPolicy$2(ctx, names, "supplierItemMappings")}`);
62692
62692
  return parts.join("\n");
62693
62693
  }
62694
62694
  /** The type and value validation shared by the function and the import. */
62695
- const checks = (value, type) => `if ${type} is null or ${type} not in (${list$29(IDENTIFIER_TYPES)}) then
62695
+ const checks = (value, type) => `if ${type} is null or ${type} not in (${list$30(IDENTIFIER_TYPES)}) then
62696
62696
  ${fail("CATALOG_IDENTIFIER_TYPE_INVALID", `the type must be one of ${IDENTIFIER_TYPES.join(", ")}`, "22023")}
62697
62697
  end if;
62698
62698
  if ${value} is null or length(${value}) not between 1 and 100 then
@@ -62819,7 +62819,7 @@ declare
62819
62819
  v_created boolean;
62820
62820
  begin
62821
62821
  ${guard$11(names, "save_product_relation.tenant")}
62822
- if save_product_relation.kind is null or save_product_relation.kind not in (${list$29(RELATION_KINDS)}) then
62822
+ if save_product_relation.kind is null or save_product_relation.kind not in (${list$30(RELATION_KINDS)}) then
62823
62823
  ${fail("CATALOG_RELATION_KIND_INVALID", `the kind must be one of ${RELATION_KINDS.join(", ")}`, "22023")}
62824
62824
  end if;
62825
62825
  if save_product_relation.from_variant = save_product_relation.to_variant then
@@ -62934,7 +62934,7 @@ begin
62934
62934
  ${fail("CATALOG_SUPPLIER_MAPPING_INVALID", "columns and defaults must be objects", "22023")}
62935
62935
  end if;
62936
62936
  for v_key, v_value in select e.key, e.value from jsonb_each(set_supplier_item_mapping.columns) e loop
62937
- if v_key <> all (array[${list$29(MAPPING_FIELDS)}]) then
62937
+ if v_key <> all (array[${list$30(MAPPING_FIELDS)}]) then
62938
62938
  ${fail("CATALOG_SUPPLIER_MAPPING_INVALID", `a mapping fills only ${MAPPING_FIELDS.join(", ")}`, "22023")}
62939
62939
  end if;
62940
62940
  if not (jsonb_typeof(v_value) = 'string' or (v_key = 'keywords' and jsonb_typeof(v_value) = 'array' and not exists (select 1 from jsonb_array_elements(v_value) a where jsonb_typeof(a.value) <> 'string'))) then
@@ -68304,7 +68304,7 @@ ${userGrant(`${fn("list_care_alerts")}(${idType}, jsonb)`)}
68304
68304
  `;
68305
68305
  }
68306
68306
  // src/sql/modules/clinical-decision-support-functions.ts
68307
- const list$28 = (values) => values.map((value) => `'${value}'`).join(", ");
68307
+ const list$29 = (values) => values.map((value) => `'${value}'`).join(", ");
68308
68308
  /** The rule functions and the decision on an alert. */
68309
68309
  function decisionSupportFunctions(ctx) {
68310
68310
  const sql = decisionSupportSql(ctx);
@@ -68355,10 +68355,10 @@ begin
68355
68355
  v_kind := v_attrs ->> 'kind';
68356
68356
  v_severity := coalesce(nullif(v_attrs ->> 'severity', ''), 'warning');
68357
68357
  v_message := nullif(trim(v_attrs ->> 'message'), '');
68358
- if v_kind is null or v_kind not in (${list$28(CARE_RULE_KINDS)}) then
68358
+ if v_kind is null or v_kind not in (${list$29(CARE_RULE_KINDS)}) then
68359
68359
  ${sql.invalid("kind is dose_range, duplicate_therapy or interaction")}
68360
68360
  end if;
68361
- if v_severity not in (${list$28(CARE_ALERT_SEVERITIES)}) then
68361
+ if v_severity not in (${list$29(CARE_ALERT_SEVERITIES)}) then
68362
68362
  ${sql.invalid("severity is info, warning or critical")}
68363
68363
  end if;
68364
68364
  if v_message is not null and length(v_message) > 1000 then
@@ -68479,7 +68479,7 @@ begin
68479
68479
  if not ${sql.allowed(`v_row.${a("tenant")}`, sql.write)} then
68480
68480
  ${sql.forbidden("not allowed to decide on care alerts")}
68481
68481
  end if;
68482
- if decide_care_alert.decision is null or decide_care_alert.decision not in (${list$28(CARE_ALERT_DECISIONS)}) then
68482
+ if decide_care_alert.decision is null or decide_care_alert.decision not in (${list$29(CARE_ALERT_DECISIONS)}) then
68483
68483
  ${sql.invalid("decision is acknowledged or overridden")}
68484
68484
  end if;
68485
68485
  if v_row.${a("status")} = 'resolved' or (v_row.${a("status")} = 'overridden') or (v_row.${a("status")} = 'acknowledged' and decide_care_alert.decision = 'acknowledged') then
@@ -71268,7 +71268,7 @@ drop function if exists ${fn("comments_after_write")}();`;
71268
71268
  build: build$115
71269
71269
  };
71270
71270
  // src/sql/modules/commissions-tables.ts
71271
- const list$27 = (values) => values.map((value) => `'${value}'`).join(", ");
71271
+ const list$28 = (values) => values.map((value) => `'${value}'`).join(", ");
71272
71272
  /** The JSON a plan, an assignment, an entry or a statement reads as. */
71273
71273
  function commissionJson(k) {
71274
71274
  const { p, a, c, s } = k;
@@ -71300,7 +71300,7 @@ create table if not exists ${plans} (
71300
71300
  ${p("id")} uuid primary key default gen_random_uuid(),
71301
71301
  ${p("tenant")} ${idType} not null,
71302
71302
  ${p("name")} text not null check (length(${p("name")}) between 1 and 200),
71303
- ${p("kind")} text not null check (${p("kind")} in (${list$27(COMMISSION_PLAN_KINDS)})),
71303
+ ${p("kind")} text not null check (${p("kind")} in (${list$28(COMMISSION_PLAN_KINDS)})),
71304
71304
  -- A flat plan's rate in basis points (100 is 1%).
71305
71305
  ${p("rateBps")} integer check (${p("rateBps")} between 0 and 10000),
71306
71306
  -- A tiered plan's marginal tiers: [{ "upTo": 100000, "bps": 500 }, { "upTo": null, "bps": 800 }].
@@ -71343,7 +71343,7 @@ create table if not exists ${statements} (
71343
71343
  ${s("currency")} text not null check (${s("currency")} ~ '^[A-Z]{3}$'),
71344
71344
  ${s("startsOn")} date not null,
71345
71345
  ${s("endsOn")} date not null,
71346
- ${s("status")} text not null default 'open' check (${s("status")} in (${list$27(COMMISSION_STATEMENT_STATUSES)})),
71346
+ ${s("status")} text not null default 'open' check (${s("status")} in (${list$28(COMMISSION_STATEMENT_STATUSES)})),
71347
71347
  ${s("total")} bigint not null default 0,
71348
71348
  -- The ledger transaction that paid the statement out.
71349
71349
  ${s("ledgerTransaction")} uuid,
@@ -71372,7 +71372,7 @@ create table if not exists ${entries} (
71372
71372
  ${c("amount")} bigint not null check (${c("amount")} > 0),
71373
71373
  ${c("currency")} text not null check (${c("currency")} ~ '^[A-Z]{3}$'),
71374
71374
  ${c("occurredOn")} date not null,
71375
- ${c("status")} text not null default 'accrued' check (${c("status")} in (${list$27(COMMISSION_STATUSES)})),
71375
+ ${c("status")} text not null default 'accrued' check (${c("status")} in (${list$28(COMMISSION_STATUSES)})),
71376
71376
  ${c("statement")} uuid,
71377
71377
  ${c("ledgerTransaction")} uuid,
71378
71378
  ${c("reversedAt")} timestamptz,
@@ -74977,7 +74977,7 @@ function consentsSql(ctx) {
74977
74977
  };
74978
74978
  }
74979
74979
  // src/sql/modules/consents-functions.ts
74980
- const list$26 = (values) => values.map((value) => `'${value}'`).join(", ");
74980
+ const list$27 = (values) => values.map((value) => `'${value}'`).join(", ");
74981
74981
  function purposeFunctions(ctx, q) {
74982
74982
  const { fn, p, has, purposes, invalid, purposeJson } = q;
74983
74983
  const description = has("purposes", "description") ? `\n ${p("description")} = v_description,` : "";
@@ -75031,7 +75031,7 @@ begin
75031
75031
  if length(v_description) > 4000 then
75032
75032
  ${invalid("a purpose description is at most 4000 characters")}
75033
75033
  end if;
75034
- if v_basis not in (${list$26(LEGAL_BASES)}) then
75034
+ if v_basis not in (${list$27(LEGAL_BASES)}) then
75035
75035
  ${invalid("legal_basis is one of consent, contract, legal_obligation, vital_interest, public_task and legitimate_interest")}
75036
75036
  end if;
75037
75037
  if save_consent_purpose.valid_months is not null and save_consent_purpose.valid_months not between 1 and 1200 then
@@ -83998,7 +83998,7 @@ function damSql(ctx) {
83998
83998
  };
83999
83999
  }
84000
84000
  // src/sql/modules/dam-functions.ts
84001
- const list$25 = (values) => values.map((value) => `'${value}'`).join(", ");
84001
+ const list$26 = (values) => values.map((value) => `'${value}'`).join(", ");
84002
84002
  function renditionFunctions(ctx, q) {
84003
84003
  const { fn, n, renditions } = q;
84004
84004
  const idType = ctx.idType;
@@ -84028,7 +84028,7 @@ begin
84028
84028
  if record_rendition.kind is null or record_rendition.kind !~ '^[a-z][a-z0-9_]{0,40}$' then
84029
84029
  ${q.invalid("a rendition kind is lowercase letters, digits and underscores, up to 41 characters")}
84030
84030
  end if;
84031
- if v_status not in (${list$25(DAM_RENDITION_STATUSES)}) then
84031
+ if v_status not in (${list$26(DAM_RENDITION_STATUSES)}) then
84032
84032
  ${q.invalid("the status is pending, ready or failed")}
84033
84033
  end if;
84034
84034
  begin
@@ -84380,7 +84380,7 @@ const NAMES$102 = {
84380
84380
  }
84381
84381
  }
84382
84382
  };
84383
- const list$24 = (values) => values.map((value) => `'${value}'`).join(", ");
84383
+ const list$25 = (values) => values.map((value) => `'${value}'`).join(", ");
84384
84384
  function tables$42(ctx) {
84385
84385
  const q = damSql(ctx);
84386
84386
  const { n, u, renditions, rights } = q;
@@ -84404,7 +84404,7 @@ create table if not exists ${renditions} (
84404
84404
  ${n("tenant")} ${ctx.idType} not null,
84405
84405
  ${n("node")} uuid not null,
84406
84406
  ${n("kind")} text not null check (${n("kind")} ~ '^[a-z][a-z0-9_]{0,40}$'),
84407
- ${n("status")} text not null default 'ready' check (${n("status")} in (${list$24(DAM_RENDITION_STATUSES)})),
84407
+ ${n("status")} text not null default 'ready' check (${n("status")} in (${list$25(DAM_RENDITION_STATUSES)})),
84408
84408
  ${n("format")} text check (${n("format")} is null or length(${n("format")}) <= 20),
84409
84409
  ${n("width")} integer check (${n("width")} is null or ${n("width")} > 0),
84410
84410
  ${n("height")} integer check (${n("height")} is null or ${n("height")} > 0),
@@ -87194,152 +87194,1136 @@ const DATA_LIFECYCLE = {
87194
87194
  data: data$1
87195
87195
  };
87196
87196
  // src/sql/modules/deadlines-evaluator.ts
87197
- const list$23 = (values) => values.map((value) => `'${value}'`).join(", ");
87197
+ const list$24 = (values) => values.map((value) => `'${value}'`).join(", ");
87198
87198
  /**
87199
- * The pure SQL functions of the deadlines module: the rule evaluator and the
87200
- * rule validator. They mirror `evaluateDeadlineRule` and
87201
- * `validateDeadlineRules` in `deadlines-values.ts`.
87202
- */
87203
- function evaluatorSql(fn, grant) {
87204
- return `
87205
- -- Evaluates one rule against facts: { status: 'due', dueOn } or
87206
- -- { status: 'unknown', missing: [fact names] }. The anchor fact is a date
87207
- -- (YYYY-MM-DD). Weekends are Saturday and Sunday; holidays are not modeled.
87208
- create or replace function ${fn("evaluate_deadline_rule")}(rule jsonb, facts jsonb)
87199
+ * The SQL evaluator of the deadlines module, `evaluate_deadlines`, and its
87200
+ * helpers. Each mirrors the function of the same concept in
87201
+ * `deadlines-evaluate.ts` (`evaluateVersion`, `deadlineIsHoliday`,
87202
+ * `deadlineAdd`); the golden fixtures run both. The helpers are not callable
87203
+ * through the API.
87204
+ */
87205
+ function evaluatorSql(fn, grant, helperGrant) {
87206
+ const date = fn("deadline_date");
87207
+ const holidaysOf = fn("deadline_holidays_of");
87208
+ const isHoliday = fn("deadline_is_holiday");
87209
+ const businessDay = fn("deadline_business_day");
87210
+ const add = fn("deadline_add");
87211
+ const roll = fn("deadline_roll");
87212
+ const candidate = fn("deadline_candidate");
87213
+ const outcome = fn("deadline_outcome");
87214
+ const periods = fn("deadline_periods");
87215
+ const judge = fn("deadline_judge");
87216
+ const select = fn("deadline_select_rule");
87217
+ const group = fn("deadline_group");
87218
+ const cascade = fn("deadline_cascade");
87219
+ const sortedText = fn("deadline_sorted");
87220
+ const whole = fn("deadline_whole");
87221
+ return `
87222
+ -- An ISO date (YYYY-MM-DD) held in a jsonb string, or null.
87223
+ create or replace function ${date}(value jsonb)
87224
+ returns date
87225
+ language plpgsql
87226
+ immutable
87227
+ set search_path = ''
87228
+ as $$
87229
+ declare
87230
+ v_text text := value #>> '{}';
87231
+ begin
87232
+ if jsonb_typeof(value) is distinct from 'string' or v_text !~ '^[0-9]{4}-[0-9]{2}-[0-9]{2}$' then
87233
+ return null;
87234
+ end if;
87235
+ return make_date(substr(v_text, 1, 4)::integer, substr(v_text, 6, 2)::integer, substr(v_text, 9, 2)::integer);
87236
+ exception when others then
87237
+ return null;
87238
+ end;
87239
+ $$;
87240
+ ${helperGrant(`${date}(jsonb)`)}
87241
+
87242
+ -- Distinct text values in byte order, as a jsonb array.
87243
+ create or replace function ${sortedText}(names text[])
87209
87244
  returns jsonb
87245
+ language sql
87246
+ immutable
87247
+ set search_path = ''
87248
+ as $$
87249
+ select coalesce(jsonb_agg(s.x order by s.x collate "C"), '[]'::jsonb)
87250
+ from (select distinct u.x from unnest(names) u(x) where u.x is not null) s
87251
+ $$;
87252
+ ${helperGrant(`${sortedText}(text[])`)}
87253
+
87254
+ -- A whole number from min to max held in jsonb.
87255
+ create or replace function ${whole}(value jsonb, min_value integer, max_value integer)
87256
+ returns boolean
87257
+ language sql
87258
+ immutable
87259
+ set search_path = ''
87260
+ as $$
87261
+ select jsonb_typeof(value) is not distinct from 'number'
87262
+ and (value #>> '{}')::numeric % 1 = 0
87263
+ and (value #>> '{}')::numeric between min_value and max_value
87264
+ $$;
87265
+ ${helperGrant(`${whole}(jsonb, integer, integer)`)}
87266
+
87267
+ -- The days a counting block's holidays fall on for the dates listed in a year.
87268
+ create or replace function ${holidaysOf}(holidays jsonb, year integer)
87269
+ returns date[]
87210
87270
  language plpgsql
87211
87271
  immutable
87212
87272
  set search_path = ''
87213
87273
  as $$
87214
87274
  declare
87215
- v_facts jsonb := coalesce(evaluate_deadline_rule.facts, '{}'::jsonb);
87216
- v_name text;
87217
- v_missing text[] := '{}';
87218
- v_anchor date;
87219
- v_due date;
87220
- v_amount integer := (evaluate_deadline_rule.rule #>> '{offset,amount}')::integer;
87221
- v_unit text := evaluate_deadline_rule.rule #>> '{offset,unit}';
87222
- v_adjust text := coalesce(evaluate_deadline_rule.rule ->> 'adjust', 'none');
87275
+ v_holiday jsonb;
87276
+ v_observed jsonb;
87277
+ v_month integer;
87278
+ v_first date;
87279
+ v_last integer;
87280
+ v_listed date;
87281
+ v_wanted integer;
87282
+ v_dow integer;
87283
+ v_target integer;
87284
+ v_moved date[];
87285
+ v_replaces boolean;
87286
+ v_days date[] := '{}';
87287
+ begin
87288
+ for v_holiday in select e.value from jsonb_array_elements(coalesce(holidays, '[]'::jsonb)) e(value) loop
87289
+ v_month := (v_holiday #>> '{date,month}')::integer;
87290
+ v_first := make_date(year, v_month, 1);
87291
+ v_last := (v_first + interval '1 month')::date - v_first;
87292
+ if v_holiday -> 'date' ? 'day' then
87293
+ if (v_holiday #>> '{date,day}')::integer > v_last then
87294
+ continue;
87295
+ end if;
87296
+ v_listed := make_date(year, v_month, (v_holiday #>> '{date,day}')::integer);
87297
+ else
87298
+ v_wanted := array_position(array[${list$24(WEEKDAYS)}], v_holiday #>> '{date,weekday}');
87299
+ if v_holiday #>> '{date,nth}' = 'last' then
87300
+ v_listed := v_first + (v_last - 1);
87301
+ v_listed := v_listed - ((extract(isodow from v_listed)::integer - v_wanted + 7) % 7);
87302
+ else
87303
+ v_listed := v_first + ((v_wanted - extract(isodow from v_first)::integer + 7) % 7) + ((v_holiday #>> '{date,nth}')::integer - 1) * 7;
87304
+ if v_listed - v_first >= v_last then
87305
+ continue;
87306
+ end if;
87307
+ end if;
87308
+ end if;
87309
+ v_moved := '{}';
87310
+ v_replaces := false;
87311
+ v_dow := extract(isodow from v_listed)::integer;
87312
+ for v_observed in select e.value from jsonb_array_elements(coalesce(v_holiday -> 'observed', '[]'::jsonb)) e(value) loop
87313
+ if (v_observed ->> 'falls_on' = 'saturday' and v_dow = 6)
87314
+ or (v_observed ->> 'falls_on' = 'sunday' and v_dow = 7)
87315
+ or (v_observed ->> 'falls_on' = 'other_than_sunday' and v_dow <> 7) then
87316
+ v_target := case v_observed ->> 'observe' when 'preceding_friday' then 5 when 'following_monday' then 1 else 7 end;
87317
+ if v_observed ->> 'observe' in ('preceding_friday', 'preceding_sunday') then
87318
+ v_moved := v_moved || (v_listed - (((v_dow - v_target + 6) % 7) + 1));
87319
+ else
87320
+ v_moved := v_moved || (v_listed + (((v_target - v_dow + 6) % 7) + 1));
87321
+ end if;
87322
+ if v_observed -> 'replaces' = 'true'::jsonb then
87323
+ v_replaces := true;
87324
+ end if;
87325
+ end if;
87326
+ end loop;
87327
+ v_days := v_days || case when v_replaces then v_moved else array[v_listed] || v_moved end;
87328
+ end loop;
87329
+ return v_days;
87330
+ end;
87331
+ $$;
87332
+ ${helperGrant(`${holidaysOf}(jsonb, integer)`)}
87333
+
87334
+ -- Whether a day is a holiday of a counting block: listed in its year, or
87335
+ -- observed from a date listed in the year before or after.
87336
+ create or replace function ${isHoliday}(counting jsonb, day date)
87337
+ returns boolean
87338
+ language plpgsql
87339
+ immutable
87340
+ set search_path = ''
87341
+ as $$
87342
+ declare
87343
+ v_holidays jsonb := case when jsonb_typeof(counting) = 'object' then counting -> 'holidays' end;
87344
+ v_year integer := extract(year from day)::integer;
87345
+ begin
87346
+ if jsonb_typeof(v_holidays) is distinct from 'array' or jsonb_array_length(v_holidays) = 0 then
87347
+ return false;
87348
+ end if;
87349
+ return day = any (${holidaysOf}(v_holidays, v_year - 1) || ${holidaysOf}(v_holidays, v_year) || ${holidaysOf}(v_holidays, v_year + 1));
87350
+ end;
87351
+ $$;
87352
+ ${helperGrant(`${isHoliday}(jsonb, date)`)}
87353
+
87354
+ -- Not a weekend, and not a holiday of an approved counting block.
87355
+ create or replace function ${businessDay}(counting jsonb, day date)
87356
+ returns boolean
87357
+ language sql
87358
+ immutable
87359
+ set search_path = ''
87360
+ as $$
87361
+ select extract(isodow from day) < 6
87362
+ and not (jsonb_typeof(counting) is not distinct from 'object'
87363
+ and coalesce(counting ->> 'status', 'approved') = 'approved'
87364
+ and ${isHoliday}(counting, day))
87365
+ $$;
87366
+ ${helperGrant(`${businessDay}(jsonb, date)`)}
87367
+
87368
+ -- The date a count yields from an anchor date, before any roll.
87369
+ create or replace function ${add}(anchor date, count jsonb, counting jsonb default null)
87370
+ returns date
87371
+ language plpgsql
87372
+ immutable
87373
+ set search_path = ''
87374
+ as $$
87375
+ declare
87376
+ v_n integer := coalesce((count ->> 'n')::integer, 0) * case when count ->> 'before' is null then 1 else -1 end;
87377
+ v_day date := anchor;
87378
+ v_first date;
87223
87379
  v_step integer;
87224
87380
  v_left integer;
87225
87381
  begin
87226
- for v_name in
87227
- select d.x from (
87228
- select min(s.o) as o, s.x from (
87229
- select 0 as o, evaluate_deadline_rule.rule ->> 'anchor' as x
87230
- union all
87231
- select e.ord::integer, e.v
87232
- from jsonb_array_elements_text(coalesce(evaluate_deadline_rule.rule -> 'requires', '[]'::jsonb)) with ordinality as e(v, ord)
87233
- ) s group by s.x
87234
- ) d order by d.o
87382
+ if anchor is null then
87383
+ return null;
87384
+ end if;
87385
+ if count ->> 'unit' = 'months' then
87386
+ if count ->> 'day_of_month' is null then
87387
+ return (anchor + make_interval(months => v_n))::date;
87388
+ end if;
87389
+ v_first := (date_trunc('month', anchor)::date + make_interval(months => v_n))::date;
87390
+ return make_date(extract(year from v_first)::integer, extract(month from v_first)::integer,
87391
+ least((count ->> 'day_of_month')::integer, (v_first + interval '1 month')::date - v_first));
87392
+ end if;
87393
+ if count ->> 'unit' = 'business_days' then
87394
+ v_step := case when v_n < 0 then -1 else 1 end;
87395
+ v_left := abs(v_n);
87396
+ if v_left > ${String(OFFSET_LIMIT)} then
87397
+ raise exception 'n is a whole number from 0 to ${String(OFFSET_LIMIT)}' using errcode = '22023', hint = 'DEADLINE_INVALID';
87398
+ end if;
87399
+ while v_left > 0 loop
87400
+ v_day := v_day + v_step;
87401
+ if ${businessDay}(counting, v_day) then
87402
+ v_left := v_left - 1;
87403
+ end if;
87404
+ end loop;
87405
+ return v_day;
87406
+ end if;
87407
+ return anchor + v_n;
87408
+ end;
87409
+ $$;
87410
+ ${helperGrant(`${add}(date, jsonb, jsonb)`)}
87411
+
87412
+ -- A last day rolled past the days an approved counting block names (when the
87413
+ -- deadline rolls), then moved off a non-business day by the rule's adjust.
87414
+ create or replace function ${roll}(counting jsonb, day date, rolls boolean, adjust text)
87415
+ returns date
87416
+ language plpgsql
87417
+ immutable
87418
+ set search_path = ''
87419
+ as $$
87420
+ declare
87421
+ v_day date := day;
87422
+ v_when jsonb := counting -> 'roll_when';
87423
+ v_step integer;
87424
+ begin
87425
+ if rolls and jsonb_typeof(counting) is not distinct from 'object' and coalesce(counting ->> 'status', 'approved') = 'approved' then
87426
+ while (v_when ? 'saturday' and extract(isodow from v_day) = 6)
87427
+ or (v_when ? 'sunday' and extract(isodow from v_day) = 7)
87428
+ or (v_when ? 'holiday' and ${isHoliday}(counting, v_day)) loop
87429
+ v_day := v_day + 1;
87430
+ end loop;
87431
+ end if;
87432
+ if coalesce(adjust, 'none') <> 'none' then
87433
+ v_step := case when adjust = 'next_business_day' then 1 else -1 end;
87434
+ while not ${businessDay}(counting, v_day) loop
87435
+ v_day := v_day + v_step;
87436
+ end loop;
87437
+ end if;
87438
+ return v_day;
87439
+ end;
87440
+ $$;
87441
+ ${helperGrant(`${roll}(jsonb, date, boolean, text)`)}
87442
+
87443
+ -- One count against the facts: { state: dated, due, fact, anchor } when its
87444
+ -- fact holds a date, { state: skipped } when the fact is null, and
87445
+ -- { state: unanswered, asks } otherwise.
87446
+ create or replace function ${candidate}(count jsonb, facts jsonb, counting jsonb)
87447
+ returns jsonb
87448
+ language plpgsql
87449
+ immutable
87450
+ set search_path = ''
87451
+ as $$
87452
+ declare
87453
+ v_fact text := coalesce(count ->> 'from', count ->> 'before', '');
87454
+ v_anchor date;
87455
+ begin
87456
+ if not facts ? v_fact then
87457
+ return jsonb_build_object('state', 'unanswered', 'asks', jsonb_build_array(v_fact));
87458
+ end if;
87459
+ if facts -> v_fact = 'null'::jsonb then
87460
+ return jsonb_build_object('state', 'skipped');
87461
+ end if;
87462
+ v_anchor := ${date}(facts -> v_fact);
87463
+ if v_anchor is null then
87464
+ return jsonb_build_object('state', 'unanswered', 'asks', jsonb_build_array(v_fact));
87465
+ end if;
87466
+ return jsonb_build_object('state', 'dated', 'due', ${add}(v_anchor, count, counting), 'fact', v_fact, 'anchor', v_anchor);
87467
+ end;
87468
+ $$;
87469
+ ${helperGrant(`${candidate}(jsonb, jsonb, jsonb)`)}
87470
+
87471
+ -- A rule's deadline against the facts, before any roll: { result: due |
87472
+ -- unknown | pending | undated, due, asks, basis }.
87473
+ create or replace function ${outcome}(deadline jsonb, facts jsonb, counting jsonb)
87474
+ returns jsonb
87475
+ language plpgsql
87476
+ immutable
87477
+ set search_path = ''
87478
+ as $$
87479
+ declare
87480
+ v_kind text;
87481
+ v_counts jsonb;
87482
+ v_candidates jsonb[] := '{}';
87483
+ v_count jsonb;
87484
+ v_candidate jsonb;
87485
+ v_asks text[] := '{}';
87486
+ v_before text[] := '{}';
87487
+ v_without text[] := '{}';
87488
+ v_dated date[] := '{}';
87489
+ v_taken jsonb;
87490
+ v_undated jsonb;
87491
+ begin
87492
+ if deadline is null or jsonb_typeof(deadline) = 'null' or deadline = '"none"'::jsonb then
87493
+ return jsonb_build_object('result', 'undated', 'due', null, 'asks', '[]'::jsonb, 'basis', null);
87494
+ end if;
87495
+ v_kind := case when deadline ? 'first_of' then 'first_of' when deadline ? 'earlier_of' then 'earlier_of' when deadline ? 'later_of' then 'later_of' else 'count' end;
87496
+ v_counts := case when v_kind = 'count' then jsonb_build_array(deadline) else deadline -> v_kind end;
87497
+ for v_count in select e.value from jsonb_array_elements(v_counts) e(value) loop
87498
+ v_candidate := ${candidate}(v_count, facts, counting);
87499
+ v_candidates := v_candidates || v_candidate;
87500
+ if v_candidate ->> 'state' = 'unanswered' then
87501
+ v_asks := v_asks || array(select jsonb_array_elements_text(v_candidate -> 'asks'));
87502
+ if v_taken is null then
87503
+ v_before := v_before || array(select jsonb_array_elements_text(v_candidate -> 'asks'));
87504
+ end if;
87505
+ elsif v_candidate ->> 'state' = 'skipped' then
87506
+ if v_count ->> 'from' is not null then
87507
+ v_without := v_without || (v_count ->> 'from');
87508
+ end if;
87509
+ else
87510
+ v_dated := v_dated || (v_candidate ->> 'due')::date;
87511
+ if v_taken is null then
87512
+ v_taken := v_candidate;
87513
+ end if;
87514
+ end if;
87515
+ end loop;
87516
+ v_undated := jsonb_build_object('result', case when cardinality(v_asks) > 0 then 'unknown' else 'pending' end,
87517
+ 'due', null, 'asks', to_jsonb(v_asks), 'basis', null);
87518
+ if v_kind = 'first_of' then
87519
+ if v_taken is null then
87520
+ return v_undated;
87521
+ end if;
87522
+ return jsonb_build_object('result', 'due', 'due', v_taken -> 'due', 'asks', to_jsonb(v_before),
87523
+ 'basis', jsonb_build_object('anchor', jsonb_build_object('fact', v_taken -> 'fact', 'date', v_taken -> 'anchor'), 'without', to_jsonb(v_without)));
87524
+ end if;
87525
+ if v_kind = 'earlier_of' then
87526
+ if cardinality(v_dated) = 0 then
87527
+ return v_undated;
87528
+ end if;
87529
+ return jsonb_build_object('result', 'due', 'due', (select min(x) from unnest(v_dated) x), 'asks', to_jsonb(v_asks),
87530
+ 'basis', jsonb_build_object('anchor', null, 'without', to_jsonb(v_without)));
87531
+ end if;
87532
+ if v_kind = 'later_of' then
87533
+ if cardinality(v_dated) = 0 or cardinality(v_asks) > 0 then
87534
+ return v_undated;
87535
+ end if;
87536
+ return jsonb_build_object('result', 'due', 'due', (select max(x) from unnest(v_dated) x), 'asks', '[]'::jsonb,
87537
+ 'basis', jsonb_build_object('anchor', null, 'without', '[]'::jsonb));
87538
+ end if;
87539
+ if v_taken is null then
87540
+ return v_undated;
87541
+ end if;
87542
+ return jsonb_build_object('result', 'due', 'due', v_taken -> 'due', 'asks', '[]'::jsonb,
87543
+ 'basis', jsonb_build_object('anchor', jsonb_build_object('fact', v_taken -> 'fact', 'date', v_taken -> 'anchor'), 'without', '[]'::jsonb));
87544
+ end;
87545
+ $$;
87546
+ ${helperGrant(`${outcome}(jsonb, jsonb, jsonb)`)}
87547
+
87548
+ -- A monthly count's months as their first days, or what it waits for: from
87549
+ -- the first furnishing month through the last, or while furnishing goes on
87550
+ -- through the month of as_of and one ahead.
87551
+ create or replace function ${periods}(facts jsonb, as_of date)
87552
+ returns jsonb
87553
+ language plpgsql
87554
+ immutable
87555
+ set search_path = ''
87556
+ as $$
87557
+ declare
87558
+ v_first date;
87559
+ v_last date;
87560
+ v_ongoing boolean;
87561
+ v_end date;
87562
+ v_month date;
87563
+ v_months date[] := '{}';
87564
+ begin
87565
+ if facts -> '${FIRST_FURNISHING_FACT}' = 'null'::jsonb then
87566
+ return jsonb_build_object('months', '[]'::jsonb, 'asks', '[]'::jsonb);
87567
+ end if;
87568
+ v_first := ${date}(facts -> '${FIRST_FURNISHING_FACT}');
87569
+ if v_first is null then
87570
+ return jsonb_build_object('months', '[]'::jsonb, 'asks', jsonb_build_array('${FIRST_FURNISHING_FACT}'));
87571
+ end if;
87572
+ v_last := ${date}(facts -> '${LAST_FURNISHING_FACT}');
87573
+ v_ongoing := v_last is null or v_last > as_of;
87574
+ v_end := date_trunc('month', case when v_ongoing then as_of else v_last end)::date;
87575
+ v_month := date_trunc('month', v_first)::date;
87235
87576
  loop
87236
- if nullif(btrim(v_facts ->> v_name), '') is null then
87237
- v_missing := v_missing || v_name;
87238
- elsif v_name = evaluate_deadline_rule.rule ->> 'anchor' then
87239
- begin
87240
- if v_facts ->> v_name !~ '^\\s*\\d{4}-\\d{2}-\\d{2}\\s*$' then
87241
- raise invalid_datetime_format;
87577
+ v_months := v_months || v_month;
87578
+ v_month := (v_month + interval '1 month')::date;
87579
+ exit when v_month > v_end;
87580
+ end loop;
87581
+ if v_ongoing then
87582
+ v_months := v_months || v_month;
87583
+ end if;
87584
+ return jsonb_build_object('months', to_jsonb(v_months), 'asks', '[]'::jsonb);
87585
+ end;
87586
+ $$;
87587
+ ${helperGrant(`${periods}(jsonb, date)`)}
87588
+
87589
+ -- A three-valued AND of a condition's entries: { verdict: true | false |
87590
+ -- unknown, asks }. A missing fact is unknown; null is absent for present and
87591
+ -- absent, and unknown otherwise.
87592
+ create or replace function ${judge}(condition jsonb, facts jsonb)
87593
+ returns jsonb
87594
+ language plpgsql
87595
+ immutable
87596
+ set search_path = ''
87597
+ as $$
87598
+ declare
87599
+ v_fact text;
87600
+ v_expected jsonb;
87601
+ v_value jsonb;
87602
+ v_code text;
87603
+ v_verdict text;
87604
+ v_asks text[] := '{}';
87605
+ begin
87606
+ for v_fact, v_expected in select e.key, e.value from jsonb_each(coalesce(condition, '{}'::jsonb)) e loop
87607
+ if not facts ? v_fact then
87608
+ v_verdict := 'unknown';
87609
+ else
87610
+ v_value := facts -> v_fact;
87611
+ if v_expected in ('"present"'::jsonb, '"absent"'::jsonb) then
87612
+ v_verdict := case when (jsonb_typeof(v_value) <> 'null') = (v_expected = '"present"'::jsonb) then 'true' else 'false' end;
87613
+ elsif jsonb_typeof(v_value) = 'null' then
87614
+ v_verdict := 'unknown';
87615
+ elsif jsonb_typeof(v_expected) = 'boolean' then
87616
+ v_verdict := case when v_value = v_expected then 'true' else 'false' end;
87617
+ else
87618
+ v_code := case when jsonb_typeof(v_value) in ('string', 'number') then v_value #>> '{}' end;
87619
+ if jsonb_typeof(v_expected) = 'string' then
87620
+ v_verdict := case when v_code is not null and v_code = v_expected #>> '{}' then 'true' else 'false' end;
87621
+ else
87622
+ v_verdict := case when v_code is not null and v_code = any (array(select jsonb_array_elements_text(v_expected))) then 'true' else 'false' end;
87242
87623
  end if;
87243
- v_anchor := btrim(v_facts ->> v_name)::date;
87244
- exception when others then
87245
- v_missing := v_missing || v_name;
87246
- end;
87624
+ end if;
87625
+ end if;
87626
+ if v_verdict = 'false' then
87627
+ return jsonb_build_object('verdict', 'false', 'asks', '[]'::jsonb);
87628
+ end if;
87629
+ if v_verdict = 'unknown' then
87630
+ v_asks := v_asks || v_fact;
87247
87631
  end if;
87248
87632
  end loop;
87249
- if cardinality(v_missing) > 0 or v_anchor is null then
87250
- return jsonb_build_object('status', 'unknown', 'missing', to_jsonb(v_missing));
87251
- end if;
87252
- v_due := v_anchor;
87253
- if v_unit = 'days' then
87254
- v_due := v_anchor + v_amount;
87255
- elsif v_unit = 'months' then
87256
- v_due := (v_anchor + make_interval(months => v_amount))::date;
87257
- else
87258
- v_step := case when v_amount < 0 then -1 else 1 end;
87259
- v_left := abs(v_amount);
87260
- while v_left > 0 loop
87261
- v_due := v_due + v_step;
87262
- while extract(isodow from v_due) in (6, 7) loop
87263
- v_due := v_due + v_step;
87264
- end loop;
87265
- v_left := v_left - 1;
87633
+ return jsonb_build_object('verdict', case when cardinality(v_asks) > 0 then 'unknown' else 'true' end, 'asks', to_jsonb(v_asks));
87634
+ end;
87635
+ $$;
87636
+ ${helperGrant(`${judge}(jsonb, jsonb)`)}
87637
+
87638
+ -- The first rule of a group that applies, unless an earlier one is open:
87639
+ -- { kind: rule, rule, regime }, { kind: asks, asks } or { kind: not_covered }.
87640
+ -- A date regime whose date is unknown applies and names the fact.
87641
+ create or replace function ${select}(rules jsonb, facts jsonb)
87642
+ returns jsonb
87643
+ language plpgsql
87644
+ immutable
87645
+ set search_path = ''
87646
+ as $$
87647
+ declare
87648
+ v_rule jsonb;
87649
+ v_membership jsonb;
87650
+ v_fact text;
87651
+ v_range jsonb;
87652
+ v_judged jsonb;
87653
+ v_verdict text;
87654
+ v_regime jsonb;
87655
+ v_date date;
87656
+ v_asks text[] := '{}';
87657
+ begin
87658
+ for v_rule in select e.value from jsonb_array_elements(rules) e(value) loop
87659
+ select coalesce(jsonb_object_agg(a.key, a.value) filter (where jsonb_typeof(a.value) <> 'object'), '{}'::jsonb),
87660
+ min(a.key) filter (where jsonb_typeof(a.value) = 'object')
87661
+ into v_membership, v_fact
87662
+ from jsonb_each(coalesce(v_rule -> 'applies', '{}'::jsonb)) a;
87663
+ v_judged := ${judge}(v_membership, facts);
87664
+ v_verdict := v_judged ->> 'verdict';
87665
+ v_regime := null;
87666
+ if v_verdict = 'true' and v_fact is not null then
87667
+ v_range := v_rule -> 'applies' -> v_fact;
87668
+ v_date := ${date}(facts -> v_fact);
87669
+ if v_date is null then
87670
+ v_regime := jsonb_build_object('fact', v_fact, 'from', v_range -> 'from');
87671
+ elsif not ((v_range ->> 'from' is null or v_date >= (v_range ->> 'from')::date)
87672
+ and (v_range ->> 'before' is null or v_date < (v_range ->> 'before')::date)) then
87673
+ v_verdict := 'false';
87674
+ end if;
87675
+ end if;
87676
+ if v_verdict = 'true' and cardinality(v_asks) = 0 then
87677
+ return jsonb_build_object('kind', 'rule', 'rule', v_rule, 'regime', v_regime);
87678
+ end if;
87679
+ if v_verdict = 'unknown' then
87680
+ v_asks := v_asks || array(select jsonb_array_elements_text(v_judged -> 'asks'));
87681
+ end if;
87682
+ end loop;
87683
+ if cardinality(v_asks) > 0 then
87684
+ return jsonb_build_object('kind', 'asks', 'asks', to_jsonb(v_asks));
87685
+ end if;
87686
+ return jsonb_build_object('kind', 'not_covered');
87687
+ end;
87688
+ $$;
87689
+ ${helperGrant(`${select}(jsonb, jsonb)`)}
87690
+
87691
+ -- One group of a version for the facts: one result, or one per month for a
87692
+ -- periodic rule.
87693
+ create or replace function ${group}(content jsonb, deadline_group jsonb, facts jsonb, as_of date)
87694
+ returns jsonb
87695
+ language plpgsql
87696
+ immutable
87697
+ set search_path = ''
87698
+ as $$
87699
+ declare
87700
+ v_counting jsonb := case when jsonb_typeof(content -> 'counting') = 'object' then content -> 'counting' end;
87701
+ v_selection jsonb;
87702
+ v_rule jsonb;
87703
+ v_base jsonb;
87704
+ v_regime_marks jsonb := '[]'::jsonb;
87705
+ v_rule_marks jsonb := '[]'::jsonb;
87706
+ v_counting_marks jsonb := '[]'::jsonb;
87707
+ v_unsettled jsonb := '[]'::jsonb;
87708
+ v_regime_asks text[] := '{}';
87709
+ v_open text[] := '{}';
87710
+ v_exception jsonb;
87711
+ v_when jsonb;
87712
+ v_unless jsonb;
87713
+ v_status text;
87714
+ v_deadline jsonb;
87715
+ v_rolls boolean;
87716
+ v_months jsonb;
87717
+ v_outcome jsonb;
87718
+ v_missing jsonb;
87719
+ v_result text;
87720
+ v_month date;
87721
+ v_results jsonb := '[]'::jsonb;
87722
+ begin
87723
+ v_base := jsonb_build_object('group', deadline_group -> 'key', 'ruleKey', null, 'period', null, 'result', 'not_covered',
87724
+ 'dueOn', null, 'provisional', false, 'missing', '[]'::jsonb, 'exception', null, 'review', '[]'::jsonb,
87725
+ 'basis', null, 'deadline', null, 'citation', deadline_group -> 'citation');
87726
+ v_selection := ${select}(coalesce((select jsonb_agg(e.value order by e.ord) from jsonb_array_elements(content -> 'rules') with ordinality e(value, ord)
87727
+ where e.value -> 'group' = deadline_group -> 'key'), '[]'::jsonb), facts);
87728
+ if v_selection ->> 'kind' = 'asks' then
87729
+ return jsonb_build_array(v_base || jsonb_build_object('result', 'unknown',
87730
+ 'missing', ${sortedText}(array(select jsonb_array_elements_text(v_selection -> 'asks')))));
87731
+ end if;
87732
+ if v_selection ->> 'kind' = 'not_covered' then
87733
+ return jsonb_build_array(v_base);
87734
+ end if;
87735
+ v_rule := v_selection -> 'rule';
87736
+ if jsonb_typeof(v_selection -> 'regime') = 'object' then
87737
+ v_regime_marks := jsonb_build_array(jsonb_build_object('kind', 'regime') || (v_selection -> 'regime'));
87738
+ v_regime_asks := array[v_selection #>> '{regime,fact}'];
87739
+ end if;
87740
+ v_status := coalesce(v_rule ->> 'status', 'approved');
87741
+ if v_status <> 'approved' then
87742
+ v_rule_marks := jsonb_build_array(jsonb_build_object('kind', 'rule', 'status', v_status));
87743
+ end if;
87744
+ v_deadline := v_rule -> 'deadline';
87745
+ v_base := v_base || jsonb_build_object('ruleKey', v_rule -> 'key', 'deadline', coalesce(v_deadline, 'null'::jsonb), 'citation', v_rule -> 'citation');
87746
+ if v_rule -> 'required' = 'false'::jsonb then
87747
+ v_missing := ${sortedText}(v_regime_asks);
87748
+ return jsonb_build_array(v_base || jsonb_build_object('result', 'not_required', 'citation', deadline_group -> 'citation',
87749
+ 'missing', v_missing, 'provisional', jsonb_array_length(v_missing) > 0, 'review', v_regime_marks || v_rule_marks));
87750
+ end if;
87751
+ for v_exception in select e.value from jsonb_array_elements(coalesce(v_rule -> 'exceptions', '[]'::jsonb)) e(value) loop
87752
+ v_when := ${judge}(v_exception -> 'when', facts);
87753
+ v_unless := case when v_exception ? 'unless' then ${judge}(v_exception -> 'unless', facts) else jsonb_build_object('verdict', 'false', 'asks', '[]'::jsonb) end;
87754
+ if v_when ->> 'verdict' = 'false' or v_unless ->> 'verdict' = 'true' then
87755
+ continue;
87756
+ end if;
87757
+ if v_when ->> 'verdict' = 'true' and v_unless ->> 'verdict' = 'false' then
87758
+ if v_exception ->> 'result' <> 'review_required' and coalesce(v_exception ->> 'status', 'approved') <> 'review_required' then
87759
+ v_missing := ${sortedText}(v_regime_asks || v_open);
87760
+ return jsonb_build_array(v_base || jsonb_build_object('result', v_exception ->> 'result',
87761
+ 'exception', jsonb_build_object('name', v_exception -> 'name', 'citation', v_exception -> 'citation')
87762
+ || case when v_exception ? 'remedy' then jsonb_build_object('remedy', v_exception -> 'remedy') else '{}'::jsonb end
87763
+ || case when v_exception ? 'note' then jsonb_build_object('note', v_exception -> 'note') else '{}'::jsonb end,
87764
+ 'missing', v_missing, 'provisional', jsonb_array_length(v_missing) > 0, 'review', v_regime_marks || v_rule_marks));
87765
+ end if;
87766
+ v_unsettled := v_unsettled || jsonb_build_array(jsonb_build_object('kind', 'exception', 'name', v_exception -> 'name', 'citation', v_exception -> 'citation')
87767
+ || case when v_exception ? 'note' then jsonb_build_object('note', v_exception -> 'note') else '{}'::jsonb end);
87768
+ continue;
87769
+ end if;
87770
+ v_open := v_open || array(select jsonb_array_elements_text(v_when -> 'asks')) || array(select jsonb_array_elements_text(v_unless -> 'asks'));
87771
+ end loop;
87772
+ if v_counting is not null and coalesce(v_counting ->> 'status', 'approved') <> 'approved' then
87773
+ v_counting_marks := jsonb_build_array(jsonb_build_object('kind', 'counting', 'status', v_counting ->> 'status'));
87774
+ end if;
87775
+ v_rolls := v_deadline is not null and jsonb_typeof(v_deadline) <> 'null' and not exists (
87776
+ select 1 from jsonb_array_elements(case
87777
+ when jsonb_typeof(v_deadline) <> 'object' then '[]'::jsonb
87778
+ when v_deadline ? 'first_of' then v_deadline -> 'first_of'
87779
+ when v_deadline ? 'earlier_of' then v_deadline -> 'earlier_of'
87780
+ when v_deadline ? 'later_of' then v_deadline -> 'later_of'
87781
+ else jsonb_build_array(v_deadline) end) c(value)
87782
+ where c.value ? 'before');
87783
+ if jsonb_typeof(v_deadline) = 'object' and v_deadline ->> 'each' = 'furnishing_month' then
87784
+ v_months := ${periods}(facts, as_of);
87785
+ if jsonb_array_length(v_months -> 'months') = 0 then
87786
+ v_missing := ${sortedText}(v_regime_asks || v_open || array(select jsonb_array_elements_text(v_months -> 'asks')));
87787
+ v_result := case when jsonb_array_length(v_months -> 'asks') > 0 then 'unknown' else 'pending' end;
87788
+ return jsonb_build_array(v_base || jsonb_build_object('result', v_result, 'missing', v_missing,
87789
+ 'provisional', v_result <> 'unknown' and jsonb_array_length(v_missing) > 0,
87790
+ 'review', v_regime_marks || v_unsettled || v_rule_marks));
87791
+ end if;
87792
+ v_missing := ${sortedText}(v_regime_asks || v_open);
87793
+ for v_month in select (e.value #>> '{}')::date from jsonb_array_elements(v_months -> 'months') e(value) loop
87794
+ v_results := v_results || jsonb_build_array(v_base || jsonb_build_object('result', 'due',
87795
+ 'period', to_char(v_month, 'YYYY-MM'),
87796
+ 'dueOn', to_char(${roll}(v_counting, ${add}(v_month, v_deadline, v_counting), v_rolls, v_rule ->> 'adjust'), 'YYYY-MM-DD'),
87797
+ 'basis', jsonb_build_object('anchor', jsonb_build_object('fact', coalesce(v_deadline ->> 'from', ''), 'date', to_char(v_month, 'YYYY-MM-DD')), 'without', '[]'::jsonb),
87798
+ 'missing', v_missing, 'provisional', jsonb_array_length(v_missing) > 0,
87799
+ 'review', v_regime_marks || v_unsettled || v_counting_marks || v_rule_marks));
87266
87800
  end loop;
87801
+ return v_results;
87267
87802
  end if;
87268
- if v_adjust <> 'none' then
87269
- v_step := case when v_adjust = 'next_business_day' then 1 else -1 end;
87270
- while extract(isodow from v_due) in (6, 7) loop
87271
- v_due := v_due + v_step;
87803
+ v_outcome := ${outcome}(v_deadline, facts, v_counting);
87804
+ v_result := v_outcome ->> 'result';
87805
+ v_missing := ${sortedText}(v_regime_asks || v_open || array(select jsonb_array_elements_text(v_outcome -> 'asks')));
87806
+ return jsonb_build_array(v_base || jsonb_build_object('result', v_result,
87807
+ 'dueOn', case when v_result = 'due' then to_char(${roll}(v_counting, (v_outcome ->> 'due')::date, v_rolls, v_rule ->> 'adjust'), 'YYYY-MM-DD') end,
87808
+ 'basis', v_outcome -> 'basis',
87809
+ 'missing', v_missing, 'provisional', v_result <> 'unknown' and jsonb_array_length(v_missing) > 0,
87810
+ 'review', v_regime_marks || v_unsettled || case when v_result = 'due' then v_counting_marks else '[]'::jsonb end || v_rule_marks));
87811
+ end;
87812
+ $$;
87813
+ ${helperGrant(`${group}(jsonb, jsonb, jsonb, date)`)}
87814
+
87815
+ -- Bars a group that requires a barred group, to a fixed point. results is an
87816
+ -- object of group key to its results; only a group without a refusal of its
87817
+ -- own falls.
87818
+ create or replace function ${cascade}(results jsonb, groups jsonb)
87819
+ returns jsonb
87820
+ language plpgsql
87821
+ immutable
87822
+ set search_path = ''
87823
+ as $$
87824
+ declare
87825
+ v_results jsonb := results;
87826
+ v_group jsonb;
87827
+ v_first jsonb;
87828
+ v_barring jsonb;
87829
+ v_changed boolean := true;
87830
+ begin
87831
+ while v_changed loop
87832
+ v_changed := false;
87833
+ for v_group in select e.value from jsonb_array_elements(groups) e(value) loop
87834
+ v_first := v_results -> (v_group ->> 'key') -> 0;
87835
+ if v_first is null or not (v_first ->> 'result' in ('due', 'unknown', 'pending', 'undated')) then
87836
+ continue;
87837
+ end if;
87838
+ select v_results -> r.key -> 0 into v_barring
87839
+ from jsonb_array_elements_text(coalesce(v_group -> 'requires', '[]'::jsonb)) with ordinality r(key, ord)
87840
+ where v_results -> r.key -> 0 ->> 'result' = 'barred'
87841
+ order by r.ord limit 1;
87842
+ if v_barring is null or jsonb_typeof(v_barring -> 'exception') is distinct from 'object' then
87843
+ continue;
87844
+ end if;
87845
+ v_results := jsonb_set(v_results, array[v_group ->> 'key'], jsonb_build_array(v_first || jsonb_build_object(
87846
+ 'period', null, 'result', 'barred', 'dueOn', null, 'provisional', false, 'missing', '[]'::jsonb, 'basis', null,
87847
+ 'review', coalesce((select jsonb_agg(m.value order by m.ord) from jsonb_array_elements(v_first -> 'review') with ordinality m(value, ord)
87848
+ where m.value ->> 'kind' not in ('exception', 'counting')), '[]'::jsonb),
87849
+ 'exception', jsonb_build_object('name', v_barring #> '{exception,name}', 'citation', v_barring #> '{exception,citation}',
87850
+ 'note', 'falls with ' || (v_barring ->> 'group')))));
87851
+ v_changed := true;
87272
87852
  end loop;
87853
+ end loop;
87854
+ return v_results;
87855
+ end;
87856
+ $$;
87857
+ ${helperGrant(`${cascade}(jsonb, jsonb)`)}
87858
+
87859
+ -- Evaluates a rule set version for a subject's facts: an array of results,
87860
+ -- one per group in the version's order (one per month for a periodic rule),
87861
+ -- or only group_key's. as_of ends a periodic rule's months while furnishing
87862
+ -- goes on.
87863
+ create or replace function ${fn("evaluate_deadlines")}(content jsonb, facts jsonb, as_of date default current_date, group_key text default null)
87864
+ returns jsonb
87865
+ language plpgsql
87866
+ immutable
87867
+ security definer
87868
+ set search_path = ''
87869
+ as $$
87870
+ declare
87871
+ v_groups jsonb;
87872
+ v_results jsonb := '{}'::jsonb;
87873
+ v_group jsonb;
87874
+ v_facts jsonb := coalesce(facts, '{}'::jsonb);
87875
+ begin
87876
+ if as_of is null then
87877
+ raise exception 'as_of is required' using errcode = '22023', hint = 'DEADLINE_INVALID';
87878
+ end if;
87879
+ with recursive wanted(key) as (
87880
+ select group_key where group_key is not null
87881
+ union
87882
+ select r.key from wanted w
87883
+ join jsonb_array_elements(content -> 'groups') g(value) on g.value ->> 'key' = w.key
87884
+ cross join jsonb_array_elements_text(coalesce(g.value -> 'requires', '[]'::jsonb)) r(key)
87885
+ )
87886
+ select coalesce(jsonb_agg(g.value order by g.ord), '[]'::jsonb) into v_groups
87887
+ from jsonb_array_elements(content -> 'groups') with ordinality g(value, ord)
87888
+ where group_key is null or g.value ->> 'key' in (select w.key from wanted w);
87889
+ for v_group in select e.value from jsonb_array_elements(v_groups) e(value) loop
87890
+ v_results := v_results || jsonb_build_object(v_group ->> 'key', ${group}(content, v_group, v_facts, as_of));
87891
+ end loop;
87892
+ v_results := ${cascade}(v_results, v_groups);
87893
+ return coalesce((
87894
+ select jsonb_agg(r.value order by g.ord, r.ord)
87895
+ from jsonb_array_elements(v_groups) with ordinality g(value, ord)
87896
+ cross join jsonb_array_elements(v_results -> (g.value ->> 'key')) with ordinality r(value, ord)
87897
+ where group_key is null or g.value ->> 'key' = group_key
87898
+ ), '[]'::jsonb);
87899
+ end;
87900
+ $$;
87901
+ ${grant(`${fn("evaluate_deadlines")}(jsonb, jsonb, date, text)`)}
87902
+ `;
87903
+ }
87904
+ // src/sql/modules/deadlines-validator.ts
87905
+ const list$23 = (values) => values.map((value) => `'${value}'`).join(", ");
87906
+ const words$1 = (values) => values.join(", ");
87907
+ /**
87908
+ * The SQL rule version validator, `validate_deadline_rules`, and its helpers.
87909
+ * It finds the problems `validateRuleVersion` in `deadlines-validate.ts` finds,
87910
+ * in the same order. It calls `deadline_date` and `deadline_whole` from
87911
+ * `evaluatorSql`.
87912
+ */
87913
+ function validatorSql(fn, grant, helperGrant) {
87914
+ const date = fn("deadline_date");
87915
+ const whole = fn("deadline_whole");
87916
+ const citationBad = fn("deadline_citation_bad");
87917
+ const metaBad = fn("deadline_meta_bad");
87918
+ const codes = fn("deadline_codes");
87919
+ const conditionBad = fn("deadline_condition_bad");
87920
+ const countIssues = fn("deadline_count_issues");
87921
+ return `
87922
+ -- Validation helpers: a citation without a reference, a meta that is not an
87923
+ -- object of at most ${META_LIMIT} bytes, a list of distinct codes, a condition.
87924
+ create or replace function ${citationBad}(value jsonb)
87925
+ returns boolean
87926
+ language sql
87927
+ immutable
87928
+ set search_path = ''
87929
+ as $$
87930
+ select jsonb_typeof(value) is distinct from 'object'
87931
+ or jsonb_typeof(value -> 'reference') is distinct from 'string'
87932
+ or (value ->> 'reference') !~ '[^[:space:]]'
87933
+ $$;
87934
+ ${helperGrant(`${citationBad}(jsonb)`)}
87935
+
87936
+ create or replace function ${metaBad}(value jsonb)
87937
+ returns boolean
87938
+ language sql
87939
+ immutable
87940
+ set search_path = ''
87941
+ as $$
87942
+ select jsonb_typeof(value) is distinct from 'object' or octet_length(value::text) > ${String(META_LIMIT)}
87943
+ $$;
87944
+ ${helperGrant(`${metaBad}(jsonb)`)}
87945
+
87946
+ create or replace function ${codes}(value jsonb)
87947
+ returns boolean
87948
+ language sql
87949
+ immutable
87950
+ set search_path = ''
87951
+ as $$
87952
+ select jsonb_typeof(value) is not distinct from 'array'
87953
+ and jsonb_array_length(value) > 0
87954
+ and not exists (select 1 from jsonb_array_elements(value) e where jsonb_typeof(e) <> 'string' or e = '""'::jsonb)
87955
+ and (select count(distinct e) from jsonb_array_elements(value) e) = jsonb_array_length(value)
87956
+ $$;
87957
+ ${helperGrant(`${codes}(jsonb)`)}
87958
+
87959
+ create or replace function ${conditionBad}(value jsonb, non_empty boolean)
87960
+ returns boolean
87961
+ language sql
87962
+ immutable
87963
+ set search_path = ''
87964
+ as $$
87965
+ select jsonb_typeof(value) is distinct from 'object'
87966
+ or (non_empty and value = '{}'::jsonb)
87967
+ or exists (
87968
+ select 1 from jsonb_each(value) e
87969
+ where e.key !~ '^[a-z][a-z0-9_]{0,62}$'
87970
+ or not (jsonb_typeof(e.value) = 'boolean'
87971
+ or (jsonb_typeof(e.value) = 'string' and e.value <> '""'::jsonb)
87972
+ or ${codes}(e.value))
87973
+ )
87974
+ $$;
87975
+ ${helperGrant(`${conditionBad}(jsonb, boolean)`)}
87976
+
87977
+ create or replace function ${countIssues}(count jsonb, at text, inside boolean)
87978
+ returns text[]
87979
+ language plpgsql
87980
+ immutable
87981
+ set search_path = ''
87982
+ as $$
87983
+ declare
87984
+ v_issues text[] := '{}';
87985
+ v_name constant text := '^[a-z][a-z0-9_]{0,62}$';
87986
+ begin
87987
+ if jsonb_typeof(count) is distinct from 'object' then
87988
+ return array[at || ' must be a count'];
87989
+ end if;
87990
+ if (count ? 'from') = (count ? 'before')
87991
+ or (count ? 'from' and (jsonb_typeof(count -> 'from') <> 'string' or (count ->> 'from') !~ v_name))
87992
+ or (count ? 'before' and (jsonb_typeof(count -> 'before') <> 'string' or (count ->> 'before') !~ v_name)) then
87993
+ v_issues := v_issues || (at || ' counts from or before one fact');
87994
+ end if;
87995
+ if count ? 'n' and not ${whole}(count -> 'n', 0, ${String(OFFSET_LIMIT)}) then
87996
+ v_issues := v_issues || (at || ' n is a whole number from 0 to ${String(OFFSET_LIMIT)}');
87997
+ end if;
87998
+ if count ? 'unit' and not (jsonb_typeof(count -> 'unit') = 'string' and (count ->> 'unit') in (${list$23(OFFSET_UNITS)})) then
87999
+ v_issues := v_issues || (at || ' unit is ${words$1(OFFSET_UNITS)}');
88000
+ end if;
88001
+ if count ? 'n' and not count ? 'unit' then
88002
+ v_issues := v_issues || (at || ' n needs a unit');
88003
+ end if;
88004
+ if count ? 'from' and not count ? 'n' then
88005
+ v_issues := v_issues || (at || ' from needs n');
88006
+ end if;
88007
+ if count ? 'day_of_month' and (not ${whole}(count -> 'day_of_month', 1, 28) or count -> 'unit' is distinct from '"months"'::jsonb) then
88008
+ v_issues := v_issues || (at || ' day_of_month is 1 to 28 with unit months');
88009
+ end if;
88010
+ if count ? 'each' then
88011
+ if inside then
88012
+ v_issues := v_issues || (at || ' each is not allowed inside a combinator');
88013
+ elsif count -> 'each' is distinct from '"furnishing_month"'::jsonb or not count ? 'from' or not count ? 'n' then
88014
+ v_issues := v_issues || (at || ' each is furnishing_month on a count from a fact');
88015
+ end if;
87273
88016
  end if;
87274
- return jsonb_build_object('status', 'due', 'dueOn', to_char(v_due, 'YYYY-MM-DD'));
88017
+ return v_issues;
87275
88018
  end;
87276
88019
  $$;
87277
- ${grant(`${fn("evaluate_deadline_rule")}(jsonb, jsonb)`)}
88020
+ ${helperGrant(`${countIssues}(jsonb, text, boolean)`)}
87278
88021
 
87279
- -- The problems of a rule list, as text, empty when it is valid.
87280
- create or replace function ${fn("validate_deadline_rules")}(rules jsonb)
88022
+ -- The problems of a rule set version's content, as text, empty when it can be
88023
+ -- saved. validateRuleVersion finds the same ones in the same order.
88024
+ create or replace function ${fn("validate_deadline_rules")}(content jsonb)
87281
88025
  returns text[]
87282
88026
  language plpgsql
87283
88027
  immutable
88028
+ security definer
87284
88029
  set search_path = ''
87285
88030
  as $$
87286
88031
  declare
87287
88032
  v_issues text[] := '{}';
87288
- v_rule jsonb;
88033
+ v_name constant text := '^[a-z][a-z0-9_]{0,62}$';
88034
+ v_rule_key constant text := '^[a-z][a-z0-9_]{0,127}$';
88035
+ v_rules jsonb;
88036
+ v_groups jsonb;
88037
+ v_item jsonb;
87289
88038
  v_ord integer;
88039
+ v_at text;
88040
+ v_here text;
87290
88041
  v_key text;
87291
88042
  v_keys text[] := '{}';
87292
- v_at text;
87293
- v_name constant text := '^[a-z][a-z0-9_]{0,62}$';
87294
- v_amount integer;
87295
- begin
87296
- if validate_deadline_rules.rules is null or jsonb_typeof(validate_deadline_rules.rules) <> 'array' or jsonb_array_length(validate_deadline_rules.rules) = 0 then
87297
- return array['a rule set version needs a non-empty list of rules'];
88043
+ v_all_keys text[];
88044
+ v_requires jsonb := '{}'::jsonb;
88045
+ v_next text;
88046
+ v_fact text;
88047
+ v_value jsonb;
88048
+ v_regimes integer;
88049
+ v_combinator text;
88050
+ v_sub jsonb;
88051
+ v_sub_ord integer;
88052
+ v_names text[];
88053
+ v_counting jsonb;
88054
+ v_date jsonb;
88055
+ v_date_keys text;
88056
+ begin
88057
+ if jsonb_typeof(content) is distinct from 'object' then
88058
+ return array['a rule set version is an object with rules and groups'];
88059
+ end if;
88060
+ v_rules := content -> 'rules';
88061
+ v_groups := content -> 'groups';
88062
+ if jsonb_typeof(v_rules) is distinct from 'array' or jsonb_array_length(v_rules) = 0 then
88063
+ v_issues := v_issues || 'a rule set version needs a non-empty list of rules'::text;
88064
+ end if;
88065
+ if jsonb_typeof(v_groups) is distinct from 'array' or jsonb_array_length(v_groups) = 0 then
88066
+ v_issues := v_issues || 'a rule set version needs a non-empty list of groups'::text;
87298
88067
  end if;
87299
- for v_rule, v_ord in
87300
- select e.v, e.ord::integer from jsonb_array_elements(validate_deadline_rules.rules) with ordinality as e(v, ord)
87301
- loop
87302
- v_at := 'rule ' || v_ord;
87303
- if jsonb_typeof(v_rule) <> 'object' then
88068
+ if cardinality(v_issues) > 0 then
88069
+ return v_issues;
88070
+ end if;
88071
+
88072
+ for v_item, v_ord in select e.value, e.ord::integer from jsonb_array_elements(v_groups) with ordinality e(value, ord) loop
88073
+ v_at := 'group ' || v_ord;
88074
+ if jsonb_typeof(v_item) <> 'object' then
87304
88075
  v_issues := v_issues || (v_at || ' must be an object');
87305
88076
  continue;
87306
88077
  end if;
87307
- v_key := v_rule ->> 'key';
87308
- if jsonb_typeof(v_rule -> 'key') is distinct from 'string' or v_key !~ v_name then
88078
+ v_key := v_item ->> 'key';
88079
+ if jsonb_typeof(v_item -> 'key') is distinct from 'string' or v_key !~ v_name then
87309
88080
  v_issues := v_issues || (v_at || ' needs a key in lower case letters, digits and _');
87310
88081
  elsif v_key = any (v_keys) then
87311
88082
  v_issues := v_issues || (v_at || ' repeats the key ' || v_key);
87312
88083
  else
87313
88084
  v_keys := v_keys || v_key;
87314
88085
  end if;
87315
- if jsonb_typeof(v_rule -> 'anchor') is distinct from 'string' or (v_rule ->> 'anchor') !~ v_name then
87316
- v_issues := v_issues || (v_at || ' needs an anchor fact name');
88086
+ if v_item ? 'title' and (jsonb_typeof(v_item -> 'title') <> 'string' or char_length(v_item ->> 'title') > 200) then
88087
+ v_issues := v_issues || (v_at || ' title is text of at most 200 characters');
87317
88088
  end if;
87318
- v_amount := case when (v_rule #>> '{offset,amount}') ~ '^-?\\d{1,4}$' then (v_rule #>> '{offset,amount}')::integer end;
87319
- if jsonb_typeof(v_rule -> 'offset') is distinct from 'object'
87320
- or jsonb_typeof(v_rule #> '{offset,amount}') is distinct from 'number'
87321
- or v_amount is null or abs(v_amount) > ${String(OFFSET_LIMIT)}
87322
- or (v_rule #>> '{offset,unit}') is null or not (v_rule #>> '{offset,unit}') in (${list$23(OFFSET_UNITS)}) then
87323
- v_issues := v_issues || (v_at || ' needs an offset of a whole amount up to ${String(OFFSET_LIMIT)} in ${OFFSET_UNITS.join(", ")}');
88089
+ if ${citationBad}(v_item -> 'citation') then
88090
+ v_issues := v_issues || (v_at || ' needs a citation with a reference');
87324
88091
  end if;
87325
- if v_rule ? 'adjust' and (jsonb_typeof(v_rule -> 'adjust') is distinct from 'string' or not (v_rule ->> 'adjust') in (${list$23(DEADLINE_ADJUSTMENTS)})) then
87326
- v_issues := v_issues || (v_at || ' adjust is ${DEADLINE_ADJUSTMENTS.join(", ")}');
88092
+ if v_item ? 'meta' and ${metaBad}(v_item -> 'meta') then
88093
+ v_issues := v_issues || (v_at || ' meta must be an object of at most ${String(META_LIMIT)} bytes');
87327
88094
  end if;
87328
- if v_rule ? 'requires' and (
87329
- jsonb_typeof(v_rule -> 'requires') is distinct from 'array'
87330
- or exists (
87331
- select 1 from jsonb_array_elements(v_rule -> 'requires') r
87332
- where jsonb_typeof(r) <> 'string' or (r #>> '{}') !~ v_name
87333
- )
88095
+ end loop;
88096
+ for v_item, v_ord in select e.value, e.ord::integer from jsonb_array_elements(v_groups) with ordinality e(value, ord) loop
88097
+ if jsonb_typeof(v_item) <> 'object' or not v_item ? 'requires' then
88098
+ continue;
88099
+ end if;
88100
+ if jsonb_typeof(v_item -> 'requires') = 'array' and not exists (
88101
+ select 1 from jsonb_array_elements(v_item -> 'requires') r
88102
+ where jsonb_typeof(r) <> 'string' or not ((r #>> '{}') = any (v_keys)) or r = v_item -> 'key'
87334
88103
  ) then
87335
- v_issues := v_issues || (v_at || ' requires is a list of fact names');
88104
+ if jsonb_typeof(v_item -> 'key') = 'string' then
88105
+ v_requires := v_requires || jsonb_build_object(v_item ->> 'key', v_item -> 'requires');
88106
+ end if;
88107
+ else
88108
+ v_issues := v_issues || ('group ' || v_ord || ' requires is a list of other group keys');
88109
+ end if;
88110
+ end loop;
88111
+ for v_item, v_ord in select e.value, e.ord::integer from jsonb_array_elements(v_groups) with ordinality e(value, ord) loop
88112
+ if jsonb_typeof(v_item) <> 'object' or jsonb_typeof(v_item -> 'key') is distinct from 'string' then
88113
+ continue;
88114
+ end if;
88115
+ v_key := v_item ->> 'key';
88116
+ for v_next in select r.key from jsonb_array_elements_text(coalesce(v_requires -> v_key, '[]'::jsonb)) with ordinality r(key, ord) order by r.ord loop
88117
+ if exists (
88118
+ with recursive walk(key) as (
88119
+ select v_next
88120
+ union
88121
+ select n.key from walk w cross join jsonb_array_elements_text(coalesce(v_requires -> w.key, '[]'::jsonb)) n(key)
88122
+ ) select 1 from walk where walk.key = v_key
88123
+ ) then
88124
+ v_issues := v_issues || ('group ' || v_ord || ' requires itself through ' || v_next);
88125
+ exit;
88126
+ end if;
88127
+ end loop;
88128
+ end loop;
88129
+
88130
+ v_all_keys := array(select g ->> 'key' from jsonb_array_elements(v_groups) g where jsonb_typeof(g -> 'key') = 'string');
88131
+ v_keys := '{}';
88132
+ for v_item, v_ord in select e.value, e.ord::integer from jsonb_array_elements(v_rules) with ordinality e(value, ord) loop
88133
+ v_at := 'rule ' || v_ord;
88134
+ if jsonb_typeof(v_item) <> 'object' then
88135
+ v_issues := v_issues || (v_at || ' must be an object');
88136
+ continue;
88137
+ end if;
88138
+ v_key := v_item ->> 'key';
88139
+ if jsonb_typeof(v_item -> 'key') is distinct from 'string' or v_key !~ v_rule_key then
88140
+ v_issues := v_issues || (v_at || ' needs a key in lower case letters, digits and _');
88141
+ elsif v_key = any (v_keys) then
88142
+ v_issues := v_issues || (v_at || ' repeats the key ' || v_key);
88143
+ else
88144
+ v_keys := v_keys || v_key;
88145
+ end if;
88146
+ if jsonb_typeof(v_item -> 'group') is distinct from 'string' or not ((v_item ->> 'group') = any (v_all_keys)) then
88147
+ v_issues := v_issues || (v_at || ' needs a group that the version lists');
87336
88148
  end if;
87337
- if jsonb_typeof(v_rule -> 'citation') is distinct from 'object'
87338
- or jsonb_typeof(v_rule #> '{citation,reference}') is distinct from 'string'
87339
- or btrim(v_rule #>> '{citation,reference}') = '' then
88149
+ if v_item ? 'title' and (jsonb_typeof(v_item -> 'title') <> 'string' or char_length(v_item ->> 'title') > 200) then
88150
+ v_issues := v_issues || (v_at || ' title is text of at most 200 characters');
88151
+ end if;
88152
+ if v_item ? 'status' and not (jsonb_typeof(v_item -> 'status') = 'string' and (v_item ->> 'status') in (${list$23(PART_STATUSES)})) then
88153
+ v_issues := v_issues || (v_at || ' status is ${words$1(PART_STATUSES)}');
88154
+ end if;
88155
+ if v_item ? 'adjust' and not (jsonb_typeof(v_item -> 'adjust') = 'string' and (v_item ->> 'adjust') in (${list$23(DEADLINE_ADJUSTMENTS)})) then
88156
+ v_issues := v_issues || (v_at || ' adjust is ${words$1(DEADLINE_ADJUSTMENTS)}');
88157
+ end if;
88158
+ if v_item ->> 'adjust' = 'next_business_day' and jsonb_path_exists(v_item -> 'deadline', 'strict $.**.before') then
88159
+ v_issues := v_issues || (v_at || ' adjust next_business_day never follows a before count');
88160
+ end if;
88161
+ if v_item ? 'required' and jsonb_typeof(v_item -> 'required') <> 'boolean' then
88162
+ v_issues := v_issues || (v_at || ' required is true or false');
88163
+ end if;
88164
+ if ${citationBad}(v_item -> 'citation') then
87340
88165
  v_issues := v_issues || (v_at || ' needs a citation with a reference');
87341
88166
  end if;
88167
+
88168
+ if v_item ? 'applies' then
88169
+ if jsonb_typeof(v_item -> 'applies') <> 'object' then
88170
+ v_issues := v_issues || (v_at || ' applies must be an object');
88171
+ else
88172
+ v_regimes := 0;
88173
+ for v_fact, v_value in select a.key, a.value from jsonb_each(v_item -> 'applies') a order by a.key collate "C" loop
88174
+ if v_fact !~ v_name then
88175
+ v_issues := v_issues || (v_at || ' applies ' || v_fact || ' is not a fact name');
88176
+ elsif jsonb_typeof(v_value) = 'object' then
88177
+ v_regimes := v_regimes + 1;
88178
+ if exists (select 1 from jsonb_object_keys(v_value) k where k not in ('from', 'before'))
88179
+ or not (v_value ? 'from' or v_value ? 'before')
88180
+ or (v_value ? 'from' and ${date}(v_value -> 'from') is null)
88181
+ or (v_value ? 'before' and ${date}(v_value -> 'before') is null)
88182
+ or (${date}(v_value -> 'from') >= ${date}(v_value -> 'before')) then
88183
+ v_issues := v_issues || (v_at || ' applies ' || v_fact || ' is a date range from before before');
88184
+ end if;
88185
+ elsif not (v_value in ('"present"'::jsonb, '"absent"'::jsonb) or ${codes}(v_value)) then
88186
+ v_issues := v_issues || (v_at || ' applies ' || v_fact || ' is a list of codes, present or absent');
88187
+ end if;
88188
+ end loop;
88189
+ if v_regimes > 1 then
88190
+ v_issues := v_issues || (v_at || ' selects by one date at most');
88191
+ end if;
88192
+ end if;
88193
+ end if;
88194
+
88195
+ if v_item ? 'deadline' and v_item -> 'deadline' <> '"none"'::jsonb then
88196
+ v_value := v_item -> 'deadline';
88197
+ if jsonb_typeof(v_value) <> 'object' then
88198
+ v_issues := v_issues || (v_at || ' deadline is none, a count, or first_of, earlier_of, later_of with at least two counts');
88199
+ else
88200
+ v_combinator := case when v_value ? 'first_of' then 'first_of' when v_value ? 'earlier_of' then 'earlier_of' when v_value ? 'later_of' then 'later_of' end;
88201
+ if v_combinator is null then
88202
+ v_issues := v_issues || ${countIssues}(v_value, v_at || ' deadline', false);
88203
+ elsif (select count(*) from jsonb_object_keys(v_value)) <> 1
88204
+ or jsonb_typeof(v_value -> v_combinator) <> 'array' or jsonb_array_length(v_value -> v_combinator) < 2 then
88205
+ v_issues := v_issues || (v_at || ' deadline is none, a count, or first_of, earlier_of, later_of with at least two counts');
88206
+ else
88207
+ for v_sub, v_sub_ord in select c.value, c.ord::integer from jsonb_array_elements(v_value -> v_combinator) with ordinality c(value, ord) loop
88208
+ v_issues := v_issues || ${countIssues}(v_sub, v_at || ' deadline ' || v_combinator || ' ' || v_sub_ord, true);
88209
+ end loop;
88210
+ end if;
88211
+ end if;
88212
+ end if;
88213
+
88214
+ if v_item ? 'exceptions' then
88215
+ if jsonb_typeof(v_item -> 'exceptions') <> 'array' then
88216
+ v_issues := v_issues || (v_at || ' exceptions must be a list');
88217
+ else
88218
+ v_names := '{}';
88219
+ for v_sub, v_sub_ord in select x.value, x.ord::integer from jsonb_array_elements(v_item -> 'exceptions') with ordinality x(value, ord) loop
88220
+ v_here := v_at || ' exception ' || v_sub_ord;
88221
+ if jsonb_typeof(v_sub) <> 'object' then
88222
+ v_issues := v_issues || (v_here || ' must be an object');
88223
+ continue;
88224
+ end if;
88225
+ if jsonb_typeof(v_sub -> 'name') is distinct from 'string' or (v_sub ->> 'name') !~ v_name then
88226
+ v_issues := v_issues || (v_here || ' needs a name in lower case letters, digits and _');
88227
+ elsif (v_sub ->> 'name') = any (v_names) then
88228
+ v_issues := v_issues || (v_here || ' repeats the name ' || (v_sub ->> 'name'));
88229
+ else
88230
+ v_names := v_names || (v_sub ->> 'name');
88231
+ end if;
88232
+ if ${conditionBad}(v_sub -> 'when', true) then
88233
+ v_issues := v_issues || (v_here || ' when is a non-empty condition');
88234
+ end if;
88235
+ if v_sub ? 'unless' and ${conditionBad}(v_sub -> 'unless', false) then
88236
+ v_issues := v_issues || (v_here || ' unless is a condition');
88237
+ end if;
88238
+ if not (jsonb_typeof(v_sub -> 'result') is not distinct from 'string' and (v_sub ->> 'result') in (${list$23(EXCEPTION_RESULTS)})) then
88239
+ v_issues := v_issues || (v_here || ' result is ${words$1(EXCEPTION_RESULTS)}');
88240
+ end if;
88241
+ if v_sub ? 'remedy' and (jsonb_typeof(v_sub -> 'remedy') <> 'string' or char_length(v_sub ->> 'remedy') > 500) then
88242
+ v_issues := v_issues || (v_here || ' remedy is text of at most 500 characters');
88243
+ end if;
88244
+ if v_sub ? 'note' and (jsonb_typeof(v_sub -> 'note') <> 'string' or char_length(v_sub ->> 'note') > ${String(NOTE_LIMIT)}) then
88245
+ v_issues := v_issues || (v_here || ' note is text of at most ${String(NOTE_LIMIT)} characters');
88246
+ end if;
88247
+ if v_sub ? 'status' and not (jsonb_typeof(v_sub -> 'status') = 'string' and (v_sub ->> 'status') in (${list$23(PART_STATUSES)})) then
88248
+ v_issues := v_issues || (v_here || ' status is ${words$1(PART_STATUSES)}');
88249
+ end if;
88250
+ if ${citationBad}(v_sub -> 'citation') then
88251
+ v_issues := v_issues || (v_here || ' needs a citation with a reference');
88252
+ end if;
88253
+ end loop;
88254
+ end if;
88255
+ end if;
88256
+
88257
+ if v_item ? 'meta' and ${metaBad}(v_item -> 'meta') then
88258
+ v_issues := v_issues || (v_at || ' meta must be an object of at most ${String(META_LIMIT)} bytes');
88259
+ end if;
87342
88260
  end loop;
88261
+
88262
+ v_counting := content -> 'counting';
88263
+ if jsonb_typeof(v_counting) = 'object' then
88264
+ if v_counting -> 'roll_to' is distinct from '"next_business_day"'::jsonb then
88265
+ v_issues := v_issues || 'counting roll_to is next_business_day'::text;
88266
+ end if;
88267
+ if jsonb_typeof(v_counting -> 'roll_when') is distinct from 'array'
88268
+ or jsonb_array_length(v_counting -> 'roll_when') = 0
88269
+ or exists (select 1 from jsonb_array_elements(v_counting -> 'roll_when') w where jsonb_typeof(w) <> 'string' or not ((w #>> '{}') in (${list$23(ROLL_DAYS)})))
88270
+ or (select count(distinct w) from jsonb_array_elements(v_counting -> 'roll_when') w) <> jsonb_array_length(v_counting -> 'roll_when') then
88271
+ v_issues := v_issues || 'counting roll_when is a non-empty list of ${words$1(ROLL_DAYS)}'::text;
88272
+ end if;
88273
+ if jsonb_typeof(v_counting -> 'holidays') = 'array' then
88274
+ for v_sub, v_sub_ord in select h.value, h.ord::integer from jsonb_array_elements(v_counting -> 'holidays') with ordinality h(value, ord) loop
88275
+ v_here := 'counting holiday ' || v_sub_ord;
88276
+ if jsonb_typeof(v_sub) <> 'object' then
88277
+ v_issues := v_issues || (v_here || ' must be an object');
88278
+ continue;
88279
+ end if;
88280
+ if jsonb_typeof(v_sub -> 'name') is distinct from 'string' or (v_sub ->> 'name') = '' or char_length(v_sub ->> 'name') > 200 then
88281
+ v_issues := v_issues || (v_here || ' needs a name of at most 200 characters');
88282
+ end if;
88283
+ v_date := v_sub -> 'date';
88284
+ v_date_keys := case when jsonb_typeof(v_date) = 'object' then (select string_agg(k, ',' order by k collate "C") from jsonb_object_keys(v_date) k) end;
88285
+ if not coalesce(
88286
+ (v_date_keys = 'day,month' and ${whole}(v_date -> 'month', 1, 12) and ${whole}(v_date -> 'day', 1, 31))
88287
+ or (v_date_keys = 'month,nth,weekday' and ${whole}(v_date -> 'month', 1, 12)
88288
+ and jsonb_typeof(v_date -> 'weekday') = 'string' and (v_date ->> 'weekday') in (${list$23(WEEKDAYS)})
88289
+ and (v_date -> 'nth' = '"last"'::jsonb or ${whole}(v_date -> 'nth', 1, 5))), false) then
88290
+ v_issues := v_issues || (v_here || ' date is a month and day, or a month, weekday and nth');
88291
+ end if;
88292
+ if ${citationBad}(v_sub -> 'citation') then
88293
+ v_issues := v_issues || (v_here || ' needs a citation with a reference');
88294
+ end if;
88295
+ if v_sub ? 'observed' then
88296
+ if jsonb_typeof(v_sub -> 'observed') <> 'array' then
88297
+ v_issues := v_issues || (v_here || ' observed must be a list');
88298
+ else
88299
+ v_issues := v_issues || array(
88300
+ select v_here || ' observed ' || o.ord || ' needs falls_on, observe and a citation'
88301
+ from jsonb_array_elements(v_sub -> 'observed') with ordinality o(value, ord)
88302
+ where jsonb_typeof(o.value) <> 'object'
88303
+ or not coalesce((o.value ->> 'falls_on') in (${list$23(OBSERVED_FALLS_ON)}) and jsonb_typeof(o.value -> 'falls_on') = 'string', false)
88304
+ or not coalesce((o.value ->> 'observe') in (${list$23(OBSERVED_MOVES)}) and jsonb_typeof(o.value -> 'observe') = 'string', false)
88305
+ or (o.value ? 'replaces' and jsonb_typeof(o.value -> 'replaces') <> 'boolean')
88306
+ or ${citationBad}(o.value -> 'citation')
88307
+ order by o.ord);
88308
+ end if;
88309
+ end if;
88310
+ end loop;
88311
+ elsif v_counting ? 'holidays' then
88312
+ v_issues := v_issues || 'counting holidays must be a list'::text;
88313
+ end if;
88314
+ if v_counting ? 'citation' and ${citationBad}(v_counting -> 'citation') then
88315
+ v_issues := v_issues || 'counting citation needs a reference'::text;
88316
+ end if;
88317
+ if v_counting ? 'status' and not (jsonb_typeof(v_counting -> 'status') = 'string' and (v_counting ->> 'status') in (${list$23(PART_STATUSES)})) then
88318
+ v_issues := v_issues || 'counting status is ${words$1(PART_STATUSES)}'::text;
88319
+ end if;
88320
+ elsif v_counting is not null and jsonb_typeof(v_counting) <> 'null' then
88321
+ v_issues := v_issues || 'counting must be an object'::text;
88322
+ end if;
88323
+
88324
+ if content ? 'meta' and jsonb_typeof(content -> 'meta') <> 'null' and ${metaBad}(content -> 'meta') then
88325
+ v_issues := v_issues || 'meta must be an object of at most ${String(META_LIMIT)} bytes'::text;
88326
+ end if;
87343
88327
  return v_issues;
87344
88328
  end;
87345
88329
  $$;
@@ -87354,9 +88338,12 @@ const deadline = {
87354
88338
  "id",
87355
88339
  "subjectType",
87356
88340
  "subjectId",
88341
+ "groupKey",
87357
88342
  "ruleKey",
88343
+ "period",
87358
88344
  "result",
87359
- "dueOn"
88345
+ "dueOn",
88346
+ "provisional"
87360
88347
  ]]
87361
88348
  };
87362
88349
  const NAMES$100 = {
@@ -87392,6 +88379,9 @@ const NAMES$100 = {
87392
88379
  version: "version",
87393
88380
  status: "status",
87394
88381
  rules: "rules",
88382
+ groups: "groups",
88383
+ counting: "counting",
88384
+ meta: "meta",
87395
88385
  contentHash: "content_hash",
87396
88386
  effectiveFrom: "effective_from",
87397
88387
  approvedBy: "approved_by",
@@ -87415,13 +88405,21 @@ const NAMES$100 = {
87415
88405
  subjectId: "subject_id",
87416
88406
  jurisdiction: "jurisdiction",
87417
88407
  kind: "kind",
88408
+ groupKey: "group_key",
87418
88409
  ruleKey: "rule_key",
88410
+ period: "period",
87419
88411
  ruleVersion: "rule_version_id",
87420
88412
  facts: "facts",
87421
88413
  result: "result",
87422
88414
  dueOn: "due_on",
88415
+ provisional: "provisional",
87423
88416
  missing: "missing",
88417
+ exception: "exception",
88418
+ review: "review",
88419
+ basis: "basis",
88420
+ deadline: "deadline",
87424
88421
  citation: "citation",
88422
+ asOf: "as_of",
87425
88423
  state: "state",
87426
88424
  satisfiedAt: "satisfied_at",
87427
88425
  satisfiedBy: "satisfied_by",
@@ -87433,6 +88431,158 @@ const NAMES$100 = {
87433
88431
  }
87434
88432
  };
87435
88433
  const quoted$3 = (values) => values.map((value) => `'${value}'`).join(", ");
88434
+ /** The SHA-256 of a version's content, shared by approval and the upgrade. */
88435
+ function contentHashSql(ctx) {
88436
+ return `-- The SHA-256 content hash of a rule set version: its rules, groups,
88437
+ -- counting block and meta.
88438
+ create or replace function ${ctx.fn("version_content_hash")}(rules jsonb, groups jsonb, counting jsonb, meta jsonb)
88439
+ returns text
88440
+ language sql
88441
+ immutable
88442
+ set search_path = ''
88443
+ as $$
88444
+ select ${sha256HexSql("convert_to(jsonb_build_object('rules', rules, 'groups', groups, 'counting', counting, 'meta', meta)::text, 'UTF8')")}
88445
+ $$;
88446
+ ${triggerGrant(`${ctx.fn("version_content_hash")}(jsonb, jsonb, jsonb, jsonb)`)}`;
88447
+ }
88448
+ /**
88449
+ * Converts a rule of the version 1 shape (anchor and offset) to a rule and its
88450
+ * group.
88451
+ */
88452
+ function fromV1Sql(ctx) {
88453
+ return `-- A rule of the version 1 shape (anchor, offset, requires) as a rule of
88454
+ -- its own group: the offset counts from the anchor, or before it when it is
88455
+ -- negative, and each required fact must be present.
88456
+ create or replace function ${ctx.fn("deadline_rule_from_v1")}(rule jsonb)
88457
+ returns jsonb
88458
+ language sql
88459
+ immutable
88460
+ set search_path = ''
88461
+ as $$
88462
+ select jsonb_build_object(
88463
+ 'key', rule -> 'key',
88464
+ 'group', rule -> 'key',
88465
+ 'deadline', jsonb_build_object(
88466
+ 'n', abs((rule #>> '{offset,amount}')::integer),
88467
+ 'unit', rule #> '{offset,unit}',
88468
+ case when (rule #>> '{offset,amount}')::integer < 0 then 'before' else 'from' end, rule -> 'anchor'),
88469
+ 'citation', rule -> 'citation')
88470
+ || case when rule ? 'title' then jsonb_build_object('title', rule -> 'title') else '{}'::jsonb end
88471
+ || case when rule ? 'adjust' then jsonb_build_object('adjust', rule -> 'adjust') else '{}'::jsonb end
88472
+ || coalesce((
88473
+ select jsonb_build_object('applies', jsonb_object_agg(r.name, 'present'))
88474
+ from jsonb_array_elements_text(case when jsonb_typeof(rule -> 'requires') = 'array' then rule -> 'requires' else '[]'::jsonb end) r(name)
88475
+ having count(*) > 0
88476
+ ), '{}'::jsonb)
88477
+ $$;
88478
+ ${triggerGrant(`${ctx.fn("deadline_rule_from_v1")}(jsonb)`)}`;
88479
+ }
88480
+ const TO_GROUPS = {
88481
+ from: 1,
88482
+ description: "Rule set versions take groups, a counting block and meta, and rules move to the v2 grammar: each version 1 rule (anchor, offset) becomes a rule of its own group, and an approved version keeps its old hash in meta.previous_content_hash. Deadlines gain group_key (backfilled from rule_key), period, provisional, exception, review, basis, deadline and as_of; save_rule_version takes the content, and the per-rule unique constraint gives way to a unique index per group and period.",
88483
+ sql: (ctx) => {
88484
+ if (ctx.mode === "custom") return "";
88485
+ const v = (column) => ctx.col("ruleVersions", column);
88486
+ const d = (column) => ctx.col("deadlines", column);
88487
+ const versions = ctx.table("ruleVersions");
88488
+ const deadlines = ctx.table("deadlines");
88489
+ const name = ctx.tableName("deadlines").name;
88490
+ return `${contentHashSql(ctx)}
88491
+
88492
+ ${fromV1Sql(ctx)}
88493
+
88494
+ do $$
88495
+ begin
88496
+ if to_regclass(${sqlString(versions)}) is null then
88497
+ return;
88498
+ end if;
88499
+ alter table ${versions} add column if not exists ${v("groups")} jsonb not null default '[]'::jsonb;
88500
+ alter table ${versions} add column if not exists ${v("counting")} jsonb;
88501
+ alter table ${versions} add column if not exists ${v("meta")} jsonb;
88502
+ alter table ${deadlines} add column if not exists ${d("groupKey")} text;
88503
+ alter table ${deadlines} add column if not exists ${d("period")} text check (${d("period")} ~ '^[0-9]{4}-[0-9]{2}$');
88504
+ alter table ${deadlines} add column if not exists ${d("provisional")} boolean not null default false;
88505
+ alter table ${deadlines} add column if not exists ${d("exception")} jsonb;
88506
+ alter table ${deadlines} add column if not exists ${d("review")} jsonb not null default '[]'::jsonb;
88507
+ alter table ${deadlines} add column if not exists ${d("basis")} jsonb;
88508
+ alter table ${deadlines} add column if not exists ${d("deadline")} jsonb;
88509
+ alter table ${deadlines} add column if not exists ${d("asOf")} date not null default current_date;
88510
+ update ${deadlines} set ${d("groupKey")} = ${d("ruleKey")} where ${d("groupKey")} is null;
88511
+ alter table ${deadlines} alter column ${d("groupKey")} set not null;
88512
+ alter table ${deadlines} alter column ${d("ruleKey")} drop not null;
88513
+ alter table ${deadlines} drop constraint if exists ${sqlIdent$1(`${name}_result_check`)};
88514
+ alter table ${deadlines} add constraint ${sqlIdent$1(`${name}_result_check`)} check (${d("result")} in (${quoted$3(DEADLINE_RESULTS)}));
88515
+ alter table ${deadlines} drop constraint if exists ${sqlIdent$1(`${name}_period_due_check`)};
88516
+ alter table ${deadlines} add constraint ${sqlIdent$1(`${name}_period_due_check`)} check (${d("period")} is null or ${d("result")} = 'due');
88517
+ alter table ${deadlines} drop constraint if exists ${sqlIdent$1(`${name}_subject_rule_key`)};
88518
+
88519
+ alter table ${versions} disable trigger bsb_deadlines_version_frozen;
88520
+ with converted as (
88521
+ select x.${v("id")} as id,
88522
+ (select jsonb_agg(${ctx.fn("deadline_rule_from_v1")}(r.value) order by r.ord) from jsonb_array_elements(x.${v("rules")}) with ordinality r(value, ord)) as rules,
88523
+ (select jsonb_agg(jsonb_build_object('key', r.value -> 'key', 'citation', r.value -> 'citation') order by r.ord) from jsonb_array_elements(x.${v("rules")}) with ordinality r(value, ord)) as groups,
88524
+ case when x.${v("status")} = 'approved'
88525
+ then coalesce(x.${v("meta")}, '{}'::jsonb) || jsonb_build_object('previous_content_hash', x.${v("contentHash")})
88526
+ else x.${v("meta")} end as meta
88527
+ from ${versions} x
88528
+ where exists (select 1 from jsonb_array_elements(x.${v("rules")}) r(value) where r.value ? 'anchor')
88529
+ )
88530
+ update ${versions} x set ${v("rules")} = c.rules, ${v("groups")} = c.groups, ${v("meta")} = c.meta,
88531
+ ${v("contentHash")} = case when x.${v("status")} = 'approved'
88532
+ then ${ctx.fn("version_content_hash")}(c.rules, c.groups, x.${v("counting")}, c.meta) else x.${v("contentHash")} end
88533
+ from converted c where x.${v("id")} = c.id;
88534
+ alter table ${versions} enable trigger bsb_deadlines_version_frozen;
88535
+ end;
88536
+ $$;
88537
+
88538
+ drop function if exists ${ctx.fn("save_rule_version")}(text, text, jsonb, date, text);
88539
+ drop function if exists ${ctx.fn("validate_deadline_rules")}(jsonb);`;
88540
+ }
88541
+ };
88542
+ const DEPRECATED = [{
88543
+ kind: "function",
88544
+ symbol: "better_supabase.evaluate_deadline_rule",
88545
+ use: "better_supabase.evaluate_deadlines(content, facts, as_of, group_key); removed in 0.58",
88546
+ since: "0.56.0",
88547
+ wrapper: (ctx) => `create or replace function ${ctx.fn("evaluate_deadline_rule")}(rule jsonb, facts jsonb)
88548
+ returns jsonb
88549
+ language plpgsql
88550
+ immutable
88551
+ security definer
88552
+ set search_path = ''
88553
+ as $$
88554
+ declare
88555
+ v_rule jsonb := case when rule ? 'anchor' then ${ctx.fn("deadline_rule_from_v1")}(rule) else rule end;
88556
+ v_result jsonb;
88557
+ begin
88558
+ v_result := ${ctx.fn("evaluate_deadlines")}(
88559
+ jsonb_build_object('rules', jsonb_build_array(v_rule),
88560
+ 'groups', jsonb_build_array(jsonb_build_object('key', v_rule -> 'group', 'citation', v_rule -> 'citation'))),
88561
+ coalesce(facts, '{}'::jsonb), current_date) -> 0;
88562
+ if v_result ->> 'result' = 'due' then
88563
+ return jsonb_build_object('status', 'due', 'dueOn', v_result -> 'dueOn');
88564
+ end if;
88565
+ return jsonb_build_object('status', 'unknown', 'missing', v_result -> 'missing');
88566
+ end;
88567
+ $$;
88568
+ comment on function ${ctx.fn("evaluate_deadline_rule")}(jsonb, jsonb) is 'deprecated: use evaluate_deadlines';
88569
+ ${userGrant(`${ctx.fn("evaluate_deadline_rule")}(jsonb, jsonb)`)}`
88570
+ }, {
88571
+ kind: "function",
88572
+ symbol: "better_supabase.compute_deadline",
88573
+ use: "better_supabase.compute_deadlines(..., group_key); removed in 0.58",
88574
+ since: "0.56.0",
88575
+ wrapper: (ctx) => `create or replace function ${ctx.fn("compute_deadline")}(tenant ${ctx.idType}, subject_type text, subject_id text, jurisdiction text, kind text, rule_key text, facts jsonb default '{}', as_of date default current_date)
88576
+ returns jsonb
88577
+ language sql
88578
+ security definer
88579
+ set search_path = ''
88580
+ as $$
88581
+ select ${ctx.fn("compute_deadlines")}(tenant, subject_type, subject_id, jurisdiction, kind, facts, as_of, rule_key) -> 0
88582
+ $$;
88583
+ comment on function ${ctx.fn("compute_deadline")}(${ctx.idType}, text, text, text, text, text, jsonb, date) is 'deprecated: use compute_deadlines';
88584
+ ${userGrant(`${ctx.fn("compute_deadline")}(${ctx.idType}, text, text, text, text, text, jsonb, date)`)}`
88585
+ }];
87436
88586
  function build$102(ctx) {
87437
88587
  if (ctx.mode === "custom") return "";
87438
88588
  const idType = ctx.idType;
@@ -87443,26 +88593,31 @@ function build$102(ctx) {
87443
88593
  const sets = ctx.table("ruleSets");
87444
88594
  const versions = ctx.table("ruleVersions");
87445
88595
  const deadlines = ctx.table("deadlines");
88596
+ const deadlinesName = ctx.tableName("deadlines").name;
87446
88597
  const read = ctx.permission("read", OPERATIONS["deadlines.read"]);
87447
88598
  const write = ctx.permission("write", OPERATIONS["deadlines.write"]);
87448
88599
  const approvals = ctx.installed("approvals") ? ctx.of("approvals") : void 0;
87449
88600
  const allowed = (tenant, permission) => `(${SERVICE_CALLER$1} or (${tenant} is not null and ${ctx.can("tenant", tenant, permission)}))`;
88601
+ const subjects = subjectsOption(ctx);
88602
+ const visible = (type, id, tenant) => `(${SERVICE_CALLER$1} or ${fn("deadline_subject_readable")}(${type}, ${id}, ${tenant}))`;
87450
88603
  const serviceOnly = (what) => `if not ${SERVICE_CALLER$1} then
87451
88604
  ${fail("DEADLINE_FORBIDDEN", `only the service role may ${what}`)}
87452
88605
  end if;`;
87453
88606
  const missing = fail("DEADLINE_NOT_FOUND", "no such deadline", "P0002");
87454
- const versionJson = (row, sets_ = sets) => `jsonb_build_object('id', ${row}.${v("id")}, 'jurisdiction', (select z.${s("jurisdiction")} from ${sets_} z where z.${s("id")} = ${row}.${v("ruleSet")}), 'kind', (select z.${s("kind")} from ${sets_} z where z.${s("id")} = ${row}.${v("ruleSet")}), 'version', ${row}.${v("version")}, 'status', ${row}.${v("status")}, 'rules', ${row}.${v("rules")}, 'contentHash', ${row}.${v("contentHash")}, 'effectiveFrom', ${row}.${v("effectiveFrom")}, 'approvedBy', ${row}.${v("approvedBy")}, 'approvedAt', ${row}.${v("approvedAt")}, 'createdAt', ${row}.${v("createdAt")})`;
87455
- const json = (row) => `jsonb_build_object('id', ${row}.${d("id")}, 'organizationId', ${row}.${d("tenant")}, 'subjectType', ${row}.${d("subjectType")}, 'subjectId', ${row}.${d("subjectId")}, 'jurisdiction', ${row}.${d("jurisdiction")}, 'kind', ${row}.${d("kind")}, 'ruleKey', ${row}.${d("ruleKey")}, 'ruleVersionId', ${row}.${d("ruleVersion")}, 'ruleVersion', (select x.${v("version")} from ${versions} x where x.${v("id")} = ${row}.${d("ruleVersion")}), 'facts', ${row}.${d("facts")}, 'result', ${row}.${d("result")}, 'dueOn', ${row}.${d("dueOn")}, 'missing', to_jsonb(${row}.${d("missing")}), 'citation', ${row}.${d("citation")}, 'state', ${row}.${d("state")}, 'satisfiedAt', ${row}.${d("satisfiedAt")}, 'satisfiedBy', ${row}.${d("satisfiedBy")}, 'satisfiedAction', ${row}.${d("satisfiedAction")}, 'computedAt', ${row}.${d("computedAt")}, 'createdAt', ${row}.${d("createdAt")})`;
88607
+ const content = (row) => `jsonb_build_object('rules', ${row}.${v("rules")}, 'groups', ${row}.${v("groups")}) || case when ${row}.${v("counting")} is null then '{}'::jsonb else jsonb_build_object('counting', ${row}.${v("counting")}) end || case when ${row}.${v("meta")} is null then '{}'::jsonb else jsonb_build_object('meta', ${row}.${v("meta")}) end`;
88608
+ const versionJson = (row) => `jsonb_build_object('id', ${row}.${v("id")}, 'jurisdiction', (select z.${s("jurisdiction")} from ${sets} z where z.${s("id")} = ${row}.${v("ruleSet")}), 'kind', (select z.${s("kind")} from ${sets} z where z.${s("id")} = ${row}.${v("ruleSet")}), 'version', ${row}.${v("version")}, 'status', ${row}.${v("status")}, 'rules', ${row}.${v("rules")}, 'groups', ${row}.${v("groups")}, 'counting', ${row}.${v("counting")}, 'meta', ${row}.${v("meta")}, 'contentHash', ${row}.${v("contentHash")}, 'effectiveFrom', ${row}.${v("effectiveFrom")}, 'approvedBy', ${row}.${v("approvedBy")}, 'approvedAt', ${row}.${v("approvedAt")}, 'createdAt', ${row}.${v("createdAt")})`;
88609
+ const json = (row) => `jsonb_build_object('id', ${row}.${d("id")}, 'organizationId', ${row}.${d("tenant")}, 'subjectType', ${row}.${d("subjectType")}, 'subjectId', ${row}.${d("subjectId")}, 'jurisdiction', ${row}.${d("jurisdiction")}, 'kind', ${row}.${d("kind")}, 'groupKey', ${row}.${d("groupKey")}, 'ruleKey', ${row}.${d("ruleKey")}, 'period', ${row}.${d("period")}, 'ruleVersionId', ${row}.${d("ruleVersion")}, 'ruleVersion', (select x.${v("version")} from ${versions} x where x.${v("id")} = ${row}.${d("ruleVersion")}), 'facts', ${row}.${d("facts")}, 'result', ${row}.${d("result")}, 'dueOn', ${row}.${d("dueOn")}, 'provisional', ${row}.${d("provisional")}, 'missing', to_jsonb(${row}.${d("missing")}), 'exception', ${row}.${d("exception")}, 'review', ${row}.${d("review")}, 'basis', ${row}.${d("basis")}, 'deadline', ${row}.${d("deadline")}, 'citation', ${row}.${d("citation")}, 'asOf', ${row}.${d("asOf")}, 'state', ${row}.${d("state")}, 'satisfiedAt', ${row}.${d("satisfiedAt")}, 'satisfiedBy', ${row}.${d("satisfiedBy")}, 'satisfiedAction', ${row}.${d("satisfiedAction")}, 'computedAt', ${row}.${d("computedAt")}, 'createdAt', ${row}.${d("createdAt")})`;
88610
+ const payload = (row) => `jsonb_build_object('organizationId', ${row}.${d("tenant")}, 'id', ${row}.${d("id")}, 'subjectType', ${row}.${d("subjectType")}, 'subjectId', ${row}.${d("subjectId")}, 'groupKey', ${row}.${d("groupKey")}, 'ruleKey', ${row}.${d("ruleKey")}, 'period', ${row}.${d("period")}, 'result', ${row}.${d("result")}, 'dueOn', ${row}.${d("dueOn")}, 'provisional', ${row}.${d("provisional")})`;
87456
88611
  const record = (type, row) => ctx.record({
87457
88612
  type,
87458
- payload: `jsonb_build_object('organizationId', ${row}.${d("tenant")}, 'id', ${row}.${d("id")}, 'subjectType', ${row}.${d("subjectType")}, 'subjectId', ${row}.${d("subjectId")}, 'ruleKey', ${row}.${d("ruleKey")}, 'result', ${row}.${d("result")}, 'dueOn', ${row}.${d("dueOn")})`,
88613
+ payload: payload(row),
87459
88614
  subject: `'deadlines/' || ${row}.${d("id")}::text`,
87460
88615
  tenant: `${row}.${d("tenant")}`,
87461
88616
  audit: {
87462
88617
  category: "data",
87463
88618
  targetType: "deadline",
87464
88619
  recordId: `${row}.${d("id")}::text`,
87465
- targetLabel: `${row}.${d("ruleKey")} || ' ' || ${row}.${d("subjectType")} || '/' || ${row}.${d("subjectId")}`,
88620
+ targetLabel: `${row}.${d("groupKey")} || coalesce(' ' || ${row}.${d("period")}, '') || ' ' || ${row}.${d("subjectType")} || '/' || ${row}.${d("subjectId")}`,
87466
88621
  summary: sqlString(type.replace("deadline.", "deadline "))
87467
88622
  }
87468
88623
  });
@@ -87488,27 +88643,24 @@ function build$102(ctx) {
87488
88643
  });
87489
88644
  const readPolicy = renderPolicy(policy$1({
87490
88645
  table: deadlines,
87491
- name: sqlIdent$1(`${ctx.tableName("deadlines").name}_read`),
88646
+ name: sqlIdent$1(`${deadlinesName}_read`),
87492
88647
  command: "select",
87493
88648
  roles: ["authenticated"],
87494
- using: ctx.scope.check(d("tenant"), read)
88649
+ using: `${ctx.scope.check(d("tenant"), read)} and ${fn("deadline_subject_readable")}(${d("subjectType")}, ${d("subjectId")}, ${d("tenant")})`
87495
88650
  }), {
87496
88651
  drop: true,
87497
88652
  target: deadlines
87498
88653
  });
87499
- const appKey = ctx.owns("deadlines") ? "" : `\ncreate unique index if not exists ${sqlIdent$1(`bsb_${ctx.tableName("deadlines").name}_tenant_id_key`)} on ${deadlines} (${d("tenant")}, ${d("id")});`;
87500
- const recomputeRow = `
87501
- select x.* into v_version from ${versions} x where x.${v("id")} = v_row.${d("ruleVersion")};
87502
- select e.value into v_rule from jsonb_array_elements(v_version.${v("rules")}) e(value)
87503
- where e.value ->> 'key' = v_row.${d("ruleKey")};
87504
- v_facts := v_row.${d("facts")} || coalesce(p_facts, '{}'::jsonb);
87505
- v_result := ${fn("evaluate_deadline_rule")}(v_rule, v_facts);`;
88654
+ const appKey = ctx.owns("deadlines") ? "" : `\ncreate unique index if not exists ${sqlIdent$1(`bsb_${deadlinesName}_tenant_id_key`)} on ${deadlines} (${d("tenant")}, ${d("id")});`;
88655
+ const periodKey = `(${d("tenant")}, ${d("subjectType")}, ${d("subjectId")}, ${d("groupKey")}, (coalesce(${d("period")}, '')))`;
87506
88656
  return `${schemaPreamble(ctx)}
87507
88657
  -- Deadlines: rule sets owned by the platform (no tenant), versioned and approved
87508
- -- once, and the deadlines computed from a subject's facts. A rule is data: an
87509
- -- anchor fact, an offset, a weekend adjustment, the facts it requires and a
87510
- -- citation. A deadline is either due on a date or unknown, naming the facts it
87511
- -- still waits for.
88658
+ -- once, and the deadlines computed from a subject's facts. A version is data:
88659
+ -- ordered groups, ordered rules with conditions, exceptions and a deadline
88660
+ -- grammar, a counting block with holidays, and opaque meta. Each group yields
88661
+ -- one deadline per subject (one per month for a periodic rule): due on a
88662
+ -- date, unknown with the facts it waits for, pending, undated, or refused as
88663
+ -- not covered, not applicable, not required or barred.
87512
88664
  create table if not exists ${sets} (
87513
88665
  ${s("id")} uuid primary key default gen_random_uuid(),
87514
88666
  ${s("jurisdiction")} text not null check (${s("jurisdiction")} ~ '^[a-z][a-z0-9_-]{0,62}$'),
@@ -87526,6 +88678,9 @@ create table if not exists ${versions} (
87526
88678
  ${v("version")} integer not null check (${v("version")} >= 1),
87527
88679
  ${v("status")} text not null default 'draft' check (${v("status")} in (${quoted$3(RULE_VERSION_STATUSES)})),
87528
88680
  ${v("rules")} jsonb not null,
88681
+ ${v("groups")} jsonb not null default '[]'::jsonb,
88682
+ ${v("counting")} jsonb,
88683
+ ${v("meta")} jsonb,
87529
88684
  ${v("contentHash")} text,
87530
88685
  ${v("effectiveFrom")} date,
87531
88686
  ${v("approvedBy")} uuid,
@@ -87568,31 +88723,69 @@ create table if not exists ${deadlines} (
87568
88723
  ${d("subjectId")} text not null check (length(${d("subjectId")}) between 1 and 200),
87569
88724
  ${d("jurisdiction")} text not null,
87570
88725
  ${d("kind")} text not null,
87571
- ${d("ruleKey")} text not null,
88726
+ ${d("groupKey")} text not null,
88727
+ ${d("ruleKey")} text,
88728
+ ${d("period")} text check (${d("period")} ~ '^[0-9]{4}-[0-9]{2}$'),
87572
88729
  ${d("ruleVersion")} uuid not null references ${versions} (${v("id")}) on delete restrict,
87573
88730
  ${d("facts")} jsonb not null default '{}'::jsonb,
87574
- ${d("result")} text not null check (${d("result")} in (${quoted$3(DEADLINE_RESULTS)})),
88731
+ ${d("result")} text not null,
87575
88732
  ${d("dueOn")} date,
88733
+ ${d("provisional")} boolean not null default false,
87576
88734
  ${d("missing")} text[] not null default '{}',
88735
+ ${d("exception")} jsonb,
88736
+ ${d("review")} jsonb not null default '[]'::jsonb,
88737
+ ${d("basis")} jsonb,
88738
+ ${d("deadline")} jsonb,
87577
88739
  ${d("citation")} jsonb not null,
88740
+ ${d("asOf")} date not null default current_date,
87578
88741
  ${d("state")} text not null default 'pending' check (${d("state")} in (${quoted$3(DEADLINE_STATES)})),
87579
88742
  ${d("satisfiedAt")} timestamptz,
87580
88743
  ${d("satisfiedBy")} uuid,
87581
88744
  ${d("satisfiedAction")} text check (${d("satisfiedAction")} is null or length(${d("satisfiedAction")}) <= 200),
87582
88745
  ${d("computedAt")} timestamptz not null default now(),
87583
88746
  ${d("createdAt")} timestamptz not null default now(),
88747
+ constraint ${sqlIdent$1(`${deadlinesName}_result_check`)} check (${d("result")} in (${quoted$3(DEADLINE_RESULTS)})),
87584
88748
  check ((${d("result")} = 'due') = (${d("dueOn")} is not null)),
87585
- constraint ${sqlIdent$1(`${ctx.tableName("deadlines").name}_subject_rule_key`)} unique (${d("tenant")}, ${d("subjectType")}, ${d("subjectId")}, ${d("ruleKey")})
88749
+ constraint ${sqlIdent$1(`${deadlinesName}_period_due_check`)} check (${d("period")} is null or ${d("result")} = 'due')
87586
88750
  );${appKey}
87587
- create index if not exists ${sqlIdent$1(`${ctx.tableName("deadlines").name}_version_idx`)} on ${deadlines} (${d("ruleVersion")});
87588
- create index if not exists ${sqlIdent$1(`${ctx.tableName("deadlines").name}_due_idx`)} on ${deadlines} (${d("tenant")}, ${d("dueOn")}) where ${d("state")} = 'pending';
88751
+ create unique index if not exists ${sqlIdent$1(`bsb_${deadlinesName}_subject_group_period_key`)} on ${deadlines} ${periodKey};
88752
+ create index if not exists ${sqlIdent$1(`${deadlinesName}_version_idx`)} on ${deadlines} (${d("ruleVersion")});
88753
+ create index if not exists ${sqlIdent$1(`${deadlinesName}_due_idx`)} on ${deadlines} (${d("tenant")}, ${d("dueOn")}) where ${d("state")} = 'pending';
87589
88754
  ${lockTable(deadlines, { read: true })}
88755
+
88756
+ -- Whether the caller may read the subject a deadline belongs to: its row is
88757
+ -- visible to them (the subject table's own policies apply) and they hold its
88758
+ -- read permission, as blocks.deadlines.on or config.subjects declares it.
88759
+ -- Without subjects every subject passes; with them an unlisted type fails.
88760
+ -- plpgsql, so a subject table a later module creates binds late.
88761
+ create or replace function ${fn("deadline_subject_readable")}(subject_type text, subject_id text, tenant ${idType})
88762
+ returns boolean
88763
+ language plpgsql
88764
+ stable
88765
+ security invoker
88766
+ set search_path = ''
88767
+ as $$
88768
+ begin
88769
+ return ${subjects.length === 0 ? "true" : `coalesce(${subjectReadable(ctx, subjects, {
88770
+ type: "deadline_subject_readable.subject_type",
88771
+ id: "deadline_subject_readable.subject_id",
88772
+ tenant: "deadline_subject_readable.tenant"
88773
+ })}, false)`};
88774
+ end;
88775
+ $$;
88776
+ revoke execute on function ${fn("deadline_subject_readable")}(text, text, ${idType}) from public, anon;
88777
+ grant execute on function ${fn("deadline_subject_readable")}(text, text, ${idType}) to authenticated, service_role;
87590
88778
  ${readPolicy}
87591
- ${evaluatorSql(fn, userGrant)}
87592
- -- Saves the rules of a rule set as a new draft version, creating the rule set
87593
- -- on first use. A draft is replaced by the next save until it is approved.
87594
- -- Service role only.
87595
- create or replace function ${fn("save_rule_version")}(jurisdiction text, kind text, rules jsonb, effective_from date default null, title text default null)
88779
+ ${evaluatorSql(fn, userGrant, triggerGrant)}
88780
+ ${validatorSql(fn, userGrant, triggerGrant)}
88781
+ ${contentHashSql(ctx)}
88782
+
88783
+ ${fromV1Sql(ctx)}
88784
+
88785
+ -- Saves a rule set version's content ({ rules, groups, counting?, meta? }) as
88786
+ -- a new draft version, creating the rule set on first use. A draft is replaced
88787
+ -- by the next save until it is approved. Service role only.
88788
+ create or replace function ${fn("save_rule_version")}(jurisdiction text, kind text, content jsonb, effective_from date default null, title text default null)
87596
88789
  returns jsonb
87597
88790
  language plpgsql
87598
88791
  security definer
@@ -87603,13 +88796,15 @@ declare
87603
88796
  v_set ${sets};
87604
88797
  v_row ${versions};
87605
88798
  v_issues text[];
88799
+ v_counting jsonb := case when jsonb_typeof(save_rule_version.content -> 'counting') = 'object' then save_rule_version.content -> 'counting' end;
88800
+ v_meta jsonb := case when jsonb_typeof(save_rule_version.content -> 'meta') = 'object' then save_rule_version.content -> 'meta' end;
87606
88801
  begin
87607
88802
  ${serviceOnly("save rule set versions")}
87608
88803
  if save_rule_version.jurisdiction is null or save_rule_version.jurisdiction !~ '^[a-z][a-z0-9_-]{0,62}$'
87609
88804
  or save_rule_version.kind is null or save_rule_version.kind !~ '^[a-z][a-z0-9_]{0,62}$' then
87610
88805
  ${fail("DEADLINE_RULES_INVALID", "a rule set has a lower case jurisdiction and kind", "22023")}
87611
88806
  end if;
87612
- v_issues := ${fn("validate_deadline_rules")}(save_rule_version.rules);
88807
+ v_issues := ${fn("validate_deadline_rules")}(save_rule_version.content);
87613
88808
  if cardinality(v_issues) > 0 then
87614
88809
  raise exception 'invalid rules: %', array_to_string(v_issues, '; ') using errcode = '22023', hint = 'DEADLINE_RULES_INVALID', detail = jsonb_build_object('issues', to_jsonb(v_issues))::text;
87615
88810
  end if;
@@ -87621,11 +88816,13 @@ begin
87621
88816
  where x.${v("ruleSet")} = v_set.${s("id")} and x.${v("status")} = 'draft'
87622
88817
  order by x.${v("version")} desc limit 1 for update;
87623
88818
  if found then
87624
- update ${versions} x set ${v("rules")} = save_rule_version.rules, ${v("effectiveFrom")} = save_rule_version.effective_from
88819
+ update ${versions} x set ${v("rules")} = save_rule_version.content -> 'rules', ${v("groups")} = save_rule_version.content -> 'groups',
88820
+ ${v("counting")} = v_counting, ${v("meta")} = v_meta, ${v("effectiveFrom")} = save_rule_version.effective_from
87625
88821
  where x.${v("id")} = v_row.${v("id")} returning * into v_row;
87626
88822
  else
87627
- insert into ${versions} (${v("ruleSet")}, ${v("version")}, ${v("rules")}, ${v("effectiveFrom")})
87628
- values (v_set.${s("id")}, coalesce((select max(y.${v("version")}) from ${versions} y where y.${v("ruleSet")} = v_set.${s("id")}), 0) + 1, save_rule_version.rules, save_rule_version.effective_from)
88823
+ insert into ${versions} (${v("ruleSet")}, ${v("version")}, ${v("rules")}, ${v("groups")}, ${v("counting")}, ${v("meta")}, ${v("effectiveFrom")})
88824
+ values (v_set.${s("id")}, coalesce((select max(y.${v("version")}) from ${versions} y where y.${v("ruleSet")} = v_set.${s("id")}), 0) + 1,
88825
+ save_rule_version.content -> 'rules', save_rule_version.content -> 'groups', v_counting, v_meta, save_rule_version.effective_from)
87629
88826
  returning * into v_row;
87630
88827
  end if;
87631
88828
  return ${versionJson("v_row")};
@@ -87633,7 +88830,7 @@ end;
87633
88830
  $$;
87634
88831
  ${serviceGrant(`${fn("save_rule_version")}(text, text, jsonb, date, text)`)}
87635
88832
 
87636
- -- Approves a draft version: freezes its rules with a SHA-256 content hash and
88833
+ -- Approves a draft version: freezes its content with a SHA-256 content hash and
87637
88834
  -- records who approved it and from which date it applies. ${approvals === void 0 ? "" : "The approval request (subject type deadline_rule_version, subject id the version id) must be approved. "}Service role only.
87638
88835
  create or replace function ${fn("approve_rule_version")}(version_id uuid, approval_id uuid default null, effective_from date default null)
87639
88836
  returns jsonb
@@ -87663,7 +88860,7 @@ begin
87663
88860
  update ${versions} x set
87664
88861
  ${v("status")} = 'approved',
87665
88862
  ${v("effectiveFrom")} = v_from,
87666
- ${v("contentHash")} = ${sha256HexSql(`convert_to(v_row.${v("rules")}::text, 'UTF8')`)},
88863
+ ${v("contentHash")} = ${fn("version_content_hash")}(v_row.${v("rules")}, v_row.${v("groups")}, v_row.${v("counting")}, v_row.${v("meta")}),
87667
88864
  ${v("approvedBy")} = auth.uid(),
87668
88865
  ${v("approvedAt")} = now(),
87669
88866
  ${v("approvalId")} = approve_rule_version.approval_id
@@ -87699,69 +88896,137 @@ end;
87699
88896
  $$;
87700
88897
  ${userGrant(`${fn("rule_version_at")}(text, text, date)`)}
87701
88898
 
87702
- -- Computes the deadline of one rule for a subject from its facts, with the rule
87703
- -- set version that applies on as_of (today by default), and stores it. The
87704
- -- result is due on a date or unknown with the facts it waits for. A satisfied
87705
- -- deadline is returned unchanged. Needs deadlines.write.
87706
- create or replace function ${fn("compute_deadline")}(tenant ${idType}, subject_type text, subject_id text, jurisdiction text, kind text, rule_key text, facts jsonb default '{}', as_of date default current_date)
88899
+ -- Stores evaluated results for a subject: one row per group and period,
88900
+ -- upserted on the unique index. A satisfied row stays as it is; a pending row
88901
+ -- of the groups whose results these are and that has no result any more is
88902
+ -- deleted. Records deadline.computed for every row it inserts or changes, and
88903
+ -- returns { rows, changed }. The callers check permissions.
88904
+ create or replace function ${fn("deadline_store")}(p_tenant ${idType}, p_subject_type text, p_subject_id text, p_jurisdiction text, p_kind text, p_version_id uuid, p_facts jsonb, p_as_of date, p_results jsonb, p_group_keys text[])
87707
88905
  returns jsonb
87708
88906
  language plpgsql
87709
88907
  security definer
87710
88908
  set search_path = ''
87711
88909
  as $$
87712
- #variable_conflict use_variable
87713
88910
  declare
87714
- v_version jsonb;
87715
- v_rule jsonb;
87716
88911
  v_result jsonb;
87717
88912
  v_row ${deadlines};
88913
+ v_rows jsonb := '[]'::jsonb;
88914
+ v_changed integer := 0;
88915
+ v_missing text[];
88916
+ v_deleted integer;
88917
+ begin
88918
+ for v_result in select e.value from jsonb_array_elements(p_results) e(value) loop
88919
+ v_missing := array(select jsonb_array_elements_text(v_result -> 'missing'));
88920
+ select * into v_row from ${deadlines} x
88921
+ where x.${d("tenant")} = p_tenant and x.${d("subjectType")} = p_subject_type
88922
+ and x.${d("subjectId")} = p_subject_id and x.${d("groupKey")} = v_result ->> 'group'
88923
+ and coalesce(x.${d("period")}, '') = coalesce(v_result ->> 'period', '')
88924
+ for update;
88925
+ if found and (v_row.${d("state")} = 'satisfied' or (
88926
+ v_row.${d("ruleVersion")} = p_version_id and v_row.${d("facts")} = p_facts
88927
+ and v_row.${d("ruleKey")} is not distinct from v_result ->> 'ruleKey' and v_row.${d("result")} = v_result ->> 'result'
88928
+ and v_row.${d("dueOn")} is not distinct from (v_result ->> 'dueOn')::date and v_row.${d("provisional")} = (v_result -> 'provisional')::boolean
88929
+ and v_row.${d("missing")} = v_missing and v_row.${d("exception")} is not distinct from nullif(v_result -> 'exception', 'null'::jsonb)
88930
+ and v_row.${d("review")} = v_result -> 'review' and v_row.${d("basis")} is not distinct from nullif(v_result -> 'basis', 'null'::jsonb)
88931
+ and v_row.${d("deadline")} is not distinct from nullif(v_result -> 'deadline', 'null'::jsonb) and v_row.${d("citation")} = v_result -> 'citation')) then
88932
+ v_rows := v_rows || ${json("v_row")};
88933
+ continue;
88934
+ end if;
88935
+ insert into ${deadlines} (${d("tenant")}, ${d("subjectType")}, ${d("subjectId")}, ${d("jurisdiction")}, ${d("kind")}, ${d("groupKey")}, ${d("ruleKey")}, ${d("period")},
88936
+ ${d("ruleVersion")}, ${d("facts")}, ${d("result")}, ${d("dueOn")}, ${d("provisional")}, ${d("missing")}, ${d("exception")}, ${d("review")}, ${d("basis")}, ${d("deadline")}, ${d("citation")}, ${d("asOf")})
88937
+ values (p_tenant, p_subject_type, p_subject_id, p_jurisdiction, p_kind,
88938
+ v_result ->> 'group', v_result ->> 'ruleKey', v_result ->> 'period', p_version_id, p_facts,
88939
+ v_result ->> 'result', (v_result ->> 'dueOn')::date, (v_result -> 'provisional')::boolean, v_missing,
88940
+ nullif(v_result -> 'exception', 'null'::jsonb), v_result -> 'review', nullif(v_result -> 'basis', 'null'::jsonb),
88941
+ nullif(v_result -> 'deadline', 'null'::jsonb), v_result -> 'citation', p_as_of)
88942
+ on conflict ${periodKey} do update set
88943
+ ${d("jurisdiction")} = excluded.${d("jurisdiction")}, ${d("kind")} = excluded.${d("kind")}, ${d("ruleKey")} = excluded.${d("ruleKey")},
88944
+ ${d("ruleVersion")} = excluded.${d("ruleVersion")}, ${d("facts")} = excluded.${d("facts")}, ${d("result")} = excluded.${d("result")},
88945
+ ${d("dueOn")} = excluded.${d("dueOn")}, ${d("provisional")} = excluded.${d("provisional")}, ${d("missing")} = excluded.${d("missing")},
88946
+ ${d("exception")} = excluded.${d("exception")}, ${d("review")} = excluded.${d("review")}, ${d("basis")} = excluded.${d("basis")},
88947
+ ${d("deadline")} = excluded.${d("deadline")}, ${d("citation")} = excluded.${d("citation")}, ${d("asOf")} = excluded.${d("asOf")},
88948
+ ${d("computedAt")} = now()
88949
+ returning * into v_row;
88950
+ ${record("deadline.computed", "v_row")}
88951
+ v_rows := v_rows || ${json("v_row")};
88952
+ v_changed := v_changed + 1;
88953
+ end loop;
88954
+ delete from ${deadlines} x
88955
+ where x.${d("tenant")} = p_tenant and x.${d("subjectType")} = p_subject_type
88956
+ and x.${d("subjectId")} = p_subject_id and x.${d("state")} = 'pending'
88957
+ and x.${d("groupKey")} = any (p_group_keys)
88958
+ and not exists (
88959
+ select 1 from jsonb_array_elements(p_results) r(value)
88960
+ where r.value ->> 'group' = x.${d("groupKey")} and coalesce(r.value ->> 'period', '') = coalesce(x.${d("period")}, '')
88961
+ );
88962
+ get diagnostics v_deleted = row_count;
88963
+ return jsonb_build_object('rows', v_rows, 'changed', v_changed + v_deleted);
88964
+ end;
88965
+ $$;
88966
+ ${triggerGrant(`${fn("deadline_store")}(${idType}, text, text, text, text, uuid, jsonb, date, jsonb, text[])`)}
88967
+
88968
+ -- Computes a subject's deadlines from its facts with the rule set version that
88969
+ -- applies on as_of (today by default): every group of the version, or only
88970
+ -- group_key, and stores one row per group (one per month for a periodic
88971
+ -- rule). Returns the rows. A satisfied row is returned unchanged and kept as
88972
+ -- history. Without group_key, a pending row of this jurisdiction and kind
88973
+ -- that the evaluation no longer yields (its group was dropped or yields no
88974
+ -- row) is deleted. Needs deadlines.write and read access to the subject.
88975
+ create or replace function ${fn("compute_deadlines")}(tenant ${idType}, subject_type text, subject_id text, jurisdiction text, kind text, facts jsonb default '{}', as_of date default current_date, group_key text default null)
88976
+ returns jsonb
88977
+ language plpgsql
88978
+ security definer
88979
+ set search_path = ''
88980
+ as $$
88981
+ #variable_conflict use_variable
88982
+ declare
88983
+ v_version jsonb;
88984
+ v_results jsonb;
87718
88985
  begin
87719
- if not ${allowed("compute_deadline.tenant", write)} then
88986
+ if not ${allowed("compute_deadlines.tenant", write)} then
87720
88987
  ${fail("DEADLINE_FORBIDDEN", "not allowed to compute deadlines")}
87721
88988
  end if;
87722
- if compute_deadline.subject_type is null or compute_deadline.subject_type !~ '^[a-z][a-z0-9_]{0,62}$'
87723
- or compute_deadline.subject_id is null or length(compute_deadline.subject_id) not between 1 and 200
87724
- or compute_deadline.facts is null or jsonb_typeof(compute_deadline.facts) <> 'object' then
87725
- ${fail("DEADLINE_INVALID", "a deadline needs a subject type, a subject id and facts as an object", "22023")}
88989
+ if compute_deadlines.subject_type is null or compute_deadlines.subject_type !~ '^[a-z][a-z0-9_]{0,62}$'
88990
+ or compute_deadlines.subject_id is null or length(compute_deadlines.subject_id) not between 1 and 200
88991
+ or compute_deadlines.facts is null or jsonb_typeof(compute_deadlines.facts) <> 'object'
88992
+ or compute_deadlines.as_of is null then
88993
+ ${fail("DEADLINE_INVALID", "a deadline needs a subject type, a subject id, facts as an object and a date", "22023")}
87726
88994
  end if;
87727
- v_version := ${fn("rule_version_at")}(compute_deadline.jurisdiction, compute_deadline.kind, compute_deadline.as_of);
88995
+ if not ${visible("compute_deadlines.subject_type", "compute_deadlines.subject_id", "compute_deadlines.tenant")} then
88996
+ ${fail("DEADLINE_FORBIDDEN", "not allowed to compute deadlines for this subject")}
88997
+ end if;
88998
+ v_version := ${fn("rule_version_at")}(compute_deadlines.jurisdiction, compute_deadlines.kind, compute_deadlines.as_of);
87728
88999
  if v_version is null then
87729
89000
  ${fail("DEADLINE_RULES_NOT_FOUND", "no approved rule set version applies", "P0002")}
87730
89001
  end if;
87731
- select e.value into v_rule from jsonb_array_elements(v_version -> 'rules') e(value)
87732
- where e.value ->> 'key' = compute_deadline.rule_key;
87733
- if v_rule is null then
87734
- ${fail("DEADLINE_RULE_NOT_FOUND", "the rule set has no rule with this key", "P0002")}
87735
- end if;
87736
- select * into v_row from ${deadlines} x
87737
- where x.${d("tenant")} = compute_deadline.tenant and x.${d("subjectType")} = compute_deadline.subject_type
87738
- and x.${d("subjectId")} = compute_deadline.subject_id and x.${d("ruleKey")} = compute_deadline.rule_key
87739
- for update;
87740
- if found and v_row.${d("state")} = 'satisfied' then
87741
- return ${json("v_row")};
87742
- end if;
87743
- v_result := ${fn("evaluate_deadline_rule")}(v_rule, compute_deadline.facts);
87744
- insert into ${deadlines} (${d("tenant")}, ${d("subjectType")}, ${d("subjectId")}, ${d("jurisdiction")}, ${d("kind")}, ${d("ruleKey")}, ${d("ruleVersion")}, ${d("facts")}, ${d("result")}, ${d("dueOn")}, ${d("missing")}, ${d("citation")})
87745
- values (compute_deadline.tenant, compute_deadline.subject_type, compute_deadline.subject_id, compute_deadline.jurisdiction, compute_deadline.kind, compute_deadline.rule_key,
87746
- (v_version ->> 'id')::uuid, compute_deadline.facts, case v_result ->> 'status' when 'due' then 'due' else 'unknown' end,
87747
- nullif(v_result ->> 'dueOn', '')::date,
87748
- coalesce(array(select jsonb_array_elements_text(coalesce(v_result -> 'missing', '[]'::jsonb))), '{}'),
87749
- v_rule -> 'citation')
87750
- on conflict on constraint ${sqlIdent$1(`${ctx.tableName("deadlines").name}_subject_rule_key`)} do update set
87751
- ${d("ruleVersion")} = excluded.${d("ruleVersion")}, ${d("facts")} = excluded.${d("facts")}, ${d("result")} = excluded.${d("result")},
87752
- ${d("dueOn")} = excluded.${d("dueOn")}, ${d("missing")} = excluded.${d("missing")}, ${d("citation")} = excluded.${d("citation")},
87753
- ${d("computedAt")} = now()
87754
- returning * into v_row;
87755
- ${record("deadline.computed", "v_row")}
87756
- return ${json("v_row")};
89002
+ if compute_deadlines.group_key is not null and not exists (
89003
+ select 1 from jsonb_array_elements(v_version -> 'groups') g(value) where g.value ->> 'key' = compute_deadlines.group_key
89004
+ ) then
89005
+ ${fail("DEADLINE_RULE_NOT_FOUND", "the rule set has no group with this key", "P0002")}
89006
+ end if;
89007
+ v_results := ${fn("evaluate_deadlines")}(
89008
+ jsonb_build_object('rules', v_version -> 'rules', 'groups', v_version -> 'groups', 'counting', v_version -> 'counting'),
89009
+ compute_deadlines.facts, compute_deadlines.as_of, compute_deadlines.group_key);
89010
+ return ${fn("deadline_store")}(compute_deadlines.tenant, compute_deadlines.subject_type, compute_deadlines.subject_id,
89011
+ compute_deadlines.jurisdiction, compute_deadlines.kind, (v_version ->> 'id')::uuid, compute_deadlines.facts, compute_deadlines.as_of,
89012
+ v_results, case when compute_deadlines.group_key is null
89013
+ then array(
89014
+ select g.value ->> 'key' from jsonb_array_elements(v_version -> 'groups') g(value)
89015
+ union
89016
+ select x.${d("groupKey")} from ${deadlines} x
89017
+ where x.${d("tenant")} = compute_deadlines.tenant and x.${d("subjectType")} = compute_deadlines.subject_type
89018
+ and x.${d("subjectId")} = compute_deadlines.subject_id and x.${d("jurisdiction")} = compute_deadlines.jurisdiction
89019
+ and x.${d("kind")} = compute_deadlines.kind)
89020
+ else array[compute_deadlines.group_key] end) -> 'rows';
87757
89021
  end;
87758
89022
  $$;
87759
- ${userGrant(`${fn("compute_deadline")}(${idType}, text, text, text, text, text, jsonb, date)`)}
89023
+ ${userGrant(`${fn("compute_deadlines")}(${idType}, text, text, text, text, jsonb, date, text)`)}
87760
89024
 
87761
89025
  -- Re-evaluates the pending deadlines of a subject after new facts arrived,
87762
- -- against the rule set version each one was computed with, and returns how many
87763
- -- changed. Runs without a permission check; the facts trigger and
87764
- -- recompute_deadlines call it.
89026
+ -- against the rule set version they were computed with (never a newer one),
89027
+ -- for the groups the subject has rows of, and returns how many rows changed.
89028
+ -- The facts are the latest stored ones merged with p_facts. Runs without a
89029
+ -- permission check; the facts trigger and recompute_deadlines call it.
87765
89030
  create or replace function ${fn("deadline_recompute")}(tenant text, subject_type text, subject_id text, p_facts jsonb)
87766
89031
  returns integer
87767
89032
  language plpgsql
@@ -87770,31 +89035,37 @@ set search_path = ''
87770
89035
  as $$
87771
89036
  #variable_conflict use_variable
87772
89037
  declare
87773
- v_row ${deadlines};
89038
+ v_set record;
87774
89039
  v_version ${versions};
87775
- v_rule jsonb;
87776
89040
  v_facts jsonb;
87777
- v_result jsonb;
89041
+ v_groups text[];
89042
+ v_results jsonb;
87778
89043
  v_changed integer := 0;
87779
- v_due date;
87780
- v_missing text[];
87781
89044
  begin
87782
- for v_row in
87783
- select * from ${deadlines} x
89045
+ for v_set in
89046
+ select x.${d("tenant")} as tenant, x.${d("jurisdiction")} as jurisdiction, x.${d("kind")} as kind, x.${d("ruleVersion")} as version_id
89047
+ from ${deadlines} x
87784
89048
  where x.${d("tenant")}::text = deadline_recompute.tenant and x.${d("subjectType")} = deadline_recompute.subject_type
87785
89049
  and x.${d("subjectId")} = deadline_recompute.subject_id and x.${d("state")} = 'pending'
87786
- for update
87787
- loop${recomputeRow}
87788
- v_due := nullif(v_result ->> 'dueOn', '')::date;
87789
- v_missing := coalesce(array(select jsonb_array_elements_text(coalesce(v_result -> 'missing', '[]'::jsonb))), '{}');
87790
- if v_facts is distinct from v_row.${d("facts")} or v_due is distinct from v_row.${d("dueOn")} or v_missing is distinct from v_row.${d("missing")} then
87791
- update ${deadlines} x set ${d("facts")} = v_facts,
87792
- ${d("result")} = case v_result ->> 'status' when 'due' then 'due' else 'unknown' end,
87793
- ${d("dueOn")} = v_due, ${d("missing")} = v_missing, ${d("computedAt")} = now()
87794
- where x.${d("id")} = v_row.${d("id")} returning * into v_row;
87795
- ${record("deadline.computed", "v_row")}
87796
- v_changed := v_changed + 1;
87797
- end if;
89050
+ group by 1, 2, 3, 4
89051
+ loop
89052
+ select * into v_version from ${versions} x where x.${v("id")} = v_set.version_id;
89053
+ select y.${d("facts")} || coalesce(deadline_recompute.p_facts, '{}'::jsonb) into v_facts from ${deadlines} y
89054
+ where y.${d("tenant")} = v_set.tenant and y.${d("subjectType")} = deadline_recompute.subject_type
89055
+ and y.${d("subjectId")} = deadline_recompute.subject_id and y.${d("ruleVersion")} = v_set.version_id
89056
+ order by y.${d("computedAt")} desc, y.${d("id")} limit 1;
89057
+ v_groups := array(
89058
+ select distinct y.${d("groupKey")} from ${deadlines} y
89059
+ where y.${d("tenant")} = v_set.tenant and y.${d("subjectType")} = deadline_recompute.subject_type
89060
+ and y.${d("subjectId")} = deadline_recompute.subject_id and y.${d("ruleVersion")} = v_set.version_id
89061
+ );
89062
+ v_results := coalesce((
89063
+ select jsonb_agg(r.value order by r.ord)
89064
+ from jsonb_array_elements(${fn("evaluate_deadlines")}(${content("v_version")}, v_facts, current_date)) with ordinality r(value, ord)
89065
+ where r.value ->> 'group' = any (v_groups)
89066
+ ), '[]'::jsonb);
89067
+ v_changed := v_changed + (${fn("deadline_store")}(v_set.tenant, deadline_recompute.subject_type, deadline_recompute.subject_id,
89068
+ v_set.jurisdiction, v_set.kind, v_set.version_id, v_facts, current_date, v_results, v_groups) ->> 'changed')::integer;
87798
89069
  end loop;
87799
89070
  return v_changed;
87800
89071
  end;
@@ -87802,7 +89073,7 @@ $$;
87802
89073
  ${triggerGrant(`${fn("deadline_recompute")}(text, text, text, jsonb)`)}
87803
89074
 
87804
89075
  -- Re-evaluates a subject's pending deadlines with extra facts. Needs
87805
- -- deadlines.write.
89076
+ -- deadlines.write and read access to the subject.
87806
89077
  create or replace function ${fn("recompute_deadlines")}(tenant ${idType}, subject_type text, subject_id text, facts jsonb default '{}')
87807
89078
  returns integer
87808
89079
  language plpgsql
@@ -87814,6 +89085,9 @@ begin
87814
89085
  if not ${allowed("recompute_deadlines.tenant", write)} then
87815
89086
  ${fail("DEADLINE_FORBIDDEN", "not allowed to compute deadlines")}
87816
89087
  end if;
89088
+ if not ${visible("recompute_deadlines.subject_type", "recompute_deadlines.subject_id", "recompute_deadlines.tenant")} then
89089
+ ${fail("DEADLINE_FORBIDDEN", "not allowed to compute deadlines for this subject")}
89090
+ end if;
87817
89091
  return ${fn("deadline_recompute")}(recompute_deadlines.tenant::text, recompute_deadlines.subject_type, recompute_deadlines.subject_id, recompute_deadlines.facts);
87818
89092
  end;
87819
89093
  $$;
@@ -87822,7 +89096,9 @@ ${userGrant(`${fn("recompute_deadlines")}(${idType}, text, text, jsonb)`)}
87822
89096
  -- A trigger function for the table that holds a subject's facts, one row per
87823
89097
  -- fact. Attach it with an after insert row trigger and pass the subject type,
87824
89098
  -- then the column names for the organization, subject id, fact name and value.
87825
- -- A new row recomputes the pending deadlines of its subject.
89099
+ -- A new row recomputes the pending deadlines of its subject. The value arrives
89100
+ -- as text, so a condition on a boolean fact needs recompute_deadlines with
89101
+ -- typed facts instead.
87826
89102
  create or replace function ${fn("deadline_fact_trigger")}()
87827
89103
  returns trigger
87828
89104
  language plpgsql
@@ -87841,7 +89117,8 @@ end;
87841
89117
  $$;
87842
89118
  ${triggerGrant(`${fn("deadline_fact_trigger")}()`)}
87843
89119
 
87844
- -- Records the action that satisfied a deadline. Needs deadlines.write.
89120
+ -- Records the action that satisfied a deadline (one period of a periodic rule
89121
+ -- on its own). Needs deadlines.write and read access to the subject.
87845
89122
  create or replace function ${fn("satisfy_deadline")}(deadline_id uuid, action text default null)
87846
89123
  returns jsonb
87847
89124
  language plpgsql
@@ -87853,7 +89130,8 @@ declare
87853
89130
  v_row ${deadlines};
87854
89131
  begin
87855
89132
  select * into v_row from ${deadlines} x where x.${d("id")} = satisfy_deadline.deadline_id for update;
87856
- if not found or not ${allowed(`v_row.${d("tenant")}`, read)} then
89133
+ if not found or not ${allowed(`v_row.${d("tenant")}`, read)}
89134
+ or not ${visible(`v_row.${d("subjectType")}`, `v_row.${d("subjectId")}`, `v_row.${d("tenant")}`)} then
87857
89135
  ${missing}
87858
89136
  end if;
87859
89137
  if not ${allowed(`v_row.${d("tenant")}`, write)} then
@@ -87871,13 +89149,15 @@ end;
87871
89149
  $$;
87872
89150
  ${userGrant(`${fn("satisfy_deadline")}(uuid, text)`)}
87873
89151
 
87874
- -- An organization's deadlines, soonest first. filters is { subjectType,
87875
- -- subjectId, state, result, dueBefore, limit }.
89152
+ -- An organization's deadlines on the subjects the caller may read, soonest
89153
+ -- first. Security invoker, so the read policy and the subject tables' own
89154
+ -- policies decide which rows it returns. filters is { subjectType,
89155
+ -- subjectId, groupKey, period, state, result, provisional, dueBefore, limit }.
87876
89156
  create or replace function ${fn("list_deadlines")}(tenant ${idType}, filters jsonb default '{}')
87877
89157
  returns jsonb
87878
89158
  language plpgsql
87879
89159
  stable
87880
- security definer
89160
+ security invoker
87881
89161
  set search_path = ''
87882
89162
  as $$
87883
89163
  #variable_conflict use_variable
@@ -87894,8 +89174,11 @@ begin
87894
89174
  where z.${d("tenant")} = list_deadlines.tenant
87895
89175
  and (not v_filters ? 'subjectType' or z.${d("subjectType")} = v_filters ->> 'subjectType')
87896
89176
  and (not v_filters ? 'subjectId' or z.${d("subjectId")} = v_filters ->> 'subjectId')
89177
+ and (not v_filters ? 'groupKey' or z.${d("groupKey")} = v_filters ->> 'groupKey')
89178
+ and (not v_filters ? 'period' or z.${d("period")} = v_filters ->> 'period')
87897
89179
  and (not v_filters ? 'state' or z.${d("state")} = v_filters ->> 'state')
87898
89180
  and (not v_filters ? 'result' or z.${d("result")} = v_filters ->> 'result')
89181
+ and (not v_filters ? 'provisional' or z.${d("provisional")} = (v_filters ->> 'provisional')::boolean)
87899
89182
  and (not v_filters ? 'dueBefore' or z.${d("dueOn")} < (v_filters ->> 'dueBefore')::date)
87900
89183
  order by z.${d("dueOn")} nulls last, z.${d("createdAt")}
87901
89184
  limit least(greatest(coalesce((v_filters ->> 'limit')::integer, 100), 1), 500)
@@ -87909,8 +89192,13 @@ ${userGrant(`${fn("list_deadlines")}(${idType}, jsonb)`)}
87909
89192
  function contract$90() {
87910
89193
  return [
87911
89194
  {
87912
- name: "evaluate_deadline_rule",
87913
- args: ["jsonb", "jsonb"],
89195
+ name: "evaluate_deadlines",
89196
+ args: [
89197
+ "jsonb",
89198
+ "jsonb",
89199
+ "date",
89200
+ "text"
89201
+ ],
87914
89202
  returns: "jsonb"
87915
89203
  },
87916
89204
  {
@@ -87948,16 +89236,16 @@ function contract$90() {
87948
89236
  returns: "jsonb"
87949
89237
  },
87950
89238
  {
87951
- name: "compute_deadline",
89239
+ name: "compute_deadlines",
87952
89240
  args: [
87953
89241
  "{id}",
87954
89242
  "text",
87955
89243
  "text",
87956
89244
  "text",
87957
89245
  "text",
87958
- "text",
87959
89246
  "jsonb",
87960
- "date"
89247
+ "date",
89248
+ "text"
87961
89249
  ],
87962
89250
  returns: "jsonb"
87963
89251
  },
@@ -87987,7 +89275,7 @@ const DEADLINES = {
87987
89275
  name: "deadlines",
87988
89276
  scopes: ["tenant"],
87989
89277
  title: "Deadlines",
87990
- description: "Platform-owned rule sets per jurisdiction and kind, versioned and approved once with a content hash and a citation per rule, and the deadlines computed from a subject's facts: due on a date or unknown with the facts still missing, recomputed when facts arrive and satisfied by a recorded action.",
89278
+ description: "Platform-owned rule sets per jurisdiction and kind, versioned and approved once with a content hash: ordered groups of rules with conditions, exceptions, a deadline grammar, a counting block with holidays and opaque meta. Each group yields a subject's deadline from its facts: due on a date (one per month for a periodic rule), unknown with the facts still missing, pending, undated, or not covered, not applicable, not required or barred; recomputed when facts arrive and satisfied by a recorded action.",
87991
89279
  requires: ["memberships", "permissions"],
87992
89280
  integrates: [
87993
89281
  "outbox",
@@ -87996,6 +89284,14 @@ const DEADLINES = {
87996
89284
  ],
87997
89285
  target: "schema",
87998
89286
  modes: ["managed", "custom"],
89287
+ version: 2,
89288
+ upgrades: [TO_GROUPS],
89289
+ deprecated: DEPRECATED,
89290
+ internal: [
89291
+ "evaluate_deadline_rule",
89292
+ "compute_deadline",
89293
+ "deadline_subject_readable"
89294
+ ],
87999
89295
  names: NAMES$100,
88000
89296
  contract: contract$90,
88001
89297
  build: build$102