better-supabase 0.29.0 → 0.30.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 (143) hide show
  1. package/dist/ai-sdk/agents/index.d.ts +2 -2
  2. package/dist/{app-tables-DekyKNQ8.d.ts → app-tables-yyVncXEt.d.ts} +1 -1
  3. package/dist/{authorization-C7nuWMuB.d.ts → authorization-CDU9tYA_.d.ts} +14 -0
  4. package/dist/{bind-DmUGUsBd.d.ts → bind-p7asfI6H.d.ts} +1 -1
  5. package/dist/{block-env-DWtZsqhH.d.ts → block-env-B8wG3xeh.d.ts} +3 -3
  6. package/dist/blocks/ai-chat/index.d.ts +3 -3
  7. package/dist/blocks/announcements/index.d.ts +3 -3
  8. package/dist/blocks/api-keys/index.d.ts +1 -1
  9. package/dist/blocks/attachments/index.d.ts +1 -1
  10. package/dist/blocks/audit/index.d.ts +2 -2
  11. package/dist/blocks/automations/index.d.ts +1 -1
  12. package/dist/blocks/billing/index.d.ts +1 -1
  13. package/dist/blocks/bookings/index.d.ts +1 -1
  14. package/dist/blocks/calendar/index.d.ts +1 -1
  15. package/dist/blocks/calendar/index.js +1 -1
  16. package/dist/blocks/comments/index.d.ts +4 -4
  17. package/dist/blocks/entitlements/index.d.ts +2 -2
  18. package/dist/blocks/forms/index.d.ts +1 -1
  19. package/dist/blocks/inbox/index.d.ts +4 -4
  20. package/dist/blocks/index.d.ts +1 -1
  21. package/dist/blocks/messaging/index.d.ts +4 -4
  22. package/dist/blocks/mfa/index.d.ts +1 -1
  23. package/dist/blocks/notifications/index.d.ts +3 -3
  24. package/dist/blocks/onboarding/index.d.ts +1 -1
  25. package/dist/blocks/organizations/index.d.ts +2 -2
  26. package/dist/blocks/permissions/index.d.ts +1 -1
  27. package/dist/blocks/push/index.d.ts +1 -1
  28. package/dist/blocks/reactions/index.d.ts +3 -3
  29. package/dist/blocks/saved-views/index.d.ts +1 -1
  30. package/dist/blocks/search/index.d.ts +2 -2
  31. package/dist/blocks/sessions/index.d.ts +1 -1
  32. package/dist/blocks/settings/index.d.ts +1 -1
  33. package/dist/blocks/subjects/index.d.ts +1 -1
  34. package/dist/blocks/tags/index.d.ts +1 -1
  35. package/dist/blocks/undo/index.d.ts +1 -1
  36. package/dist/blocks/usage/index.d.ts +1 -1
  37. package/dist/blocks/workflow-editor/index.d.ts +3 -3
  38. package/dist/blocks/workflows/index.d.ts +3 -3
  39. package/dist/cli/add-BdhGOwkB.js +1 -0
  40. package/dist/cli/{add-CrQ3jS7t.js → add-D4w-Axib.js} +9 -9
  41. package/dist/cli/{add-BKkV99g9.js → add-Dggyehsy.js} +2 -2
  42. package/dist/cli/{app-table-files-PnPOpuB4.js → app-table-files-CiGuwLkO.js} +2 -2
  43. package/dist/cli/{backfill-DDDLhinm.js → backfill-DjVjXW_P.js} +1 -1
  44. package/dist/cli/bin.js +1 -1
  45. package/dist/cli/{blocks-BCVcjvbm.js → blocks-Bbmb6W_F.js} +1 -1
  46. package/dist/cli/{blocks-tRfYx_mh.js → blocks-jRL9K1R8.js} +1 -1
  47. package/dist/cli/{cache-DQZ09YOg.js → cache-BuoIFlUJ.js} +1 -1
  48. package/dist/cli/{codemod-HKuwQmi_.js → codemod-DRavXBCb.js} +1 -1
  49. package/dist/cli/{content-mapper-B0ehR7K-.js → content-mapper-BCtyfKXl.js} +2 -2
  50. package/dist/cli/{doctor-CXJOhwLB.js → doctor-Di2ZekfN.js} +49 -16
  51. package/dist/cli/{env-BM242BCV.js → env-B2CbnbzD.js} +1 -1
  52. package/dist/cli/env-CynGCICL.js +1 -0
  53. package/dist/cli/{gen-B7rw4j19.js → gen-STKC9vkK.js} +12 -12
  54. package/dist/cli/index.d.ts +1 -1
  55. package/dist/cli/index.js +6 -6
  56. package/dist/cli/{init-C1bXXB_P.js → init-DW6_nIwj.js} +8 -8
  57. package/dist/cli/{live-PpAh9pAc.js → live-0G4Plw3K.js} +2 -2
  58. package/dist/cli/{mcp-BRNAchdH.js → mcp-flKS8iU5.js} +2 -2
  59. package/dist/cli/{metadata-dAAKb_kR.js → metadata-VARUbXEe.js} +3 -3
  60. package/dist/cli/{migrate-BWYXFnaW.js → migrate-Bkq07XcT.js} +1 -1
  61. package/dist/cli/{migration-safety-DGQswWZy.js → migration-safety-BfVeza5j.js} +1 -1
  62. package/dist/cli/{migrations-Cqk-lJwu.js → migrations-BCq7Zs2E.js} +2 -2
  63. package/dist/cli/{module-migration-8-hMiZtW.js → module-migration-lbeUrsYv.js} +2 -2
  64. package/dist/cli/{powersync-BWQ-8T3G.js → powersync-B15CfH5Y.js} +3 -3
  65. package/dist/cli/powersync-DnBsDchT.js +1 -0
  66. package/dist/cli/{print-DSTnq5xz.js → print-DjxpBRnv.js} +2 -2
  67. package/dist/cli/{providers-Cjf5iOp5.js → providers-dyxcHQY3.js} +1 -1
  68. package/dist/cli/{remove-CwG8cPv1.js → remove-BLq5gbal.js} +5 -5
  69. package/dist/cli/{render-B18iAdsT.js → render-CizUf3RW.js} +3 -3
  70. package/dist/cli/{run-CvPl8iQd.js → run-ChEjR7yw.js} +2 -2
  71. package/dist/cli/{run-Wx_2Acgv.js → run-ChOY6s4o.js} +8 -8
  72. package/dist/cli/{run-C2Yg5MWt.js → run-MwM__teL.js} +24 -24
  73. package/dist/cli/{shared-BHbtUOvh.js → shared-DV5wIv-7.js} +1 -1
  74. package/dist/cli/{snapshot-CXgsUPGj.js → snapshot-B5LXkVMC.js} +2 -2
  75. package/dist/cli/{source-B6aMAoEK.js → source-BoLNG_2A.js} +1 -1
  76. package/dist/cli/{spec-EO0TP84d.js → spec-D6QeE2Zx.js} +1 -1
  77. package/dist/cli/{spec-BcYic005.js → spec-Dz-PGCaM.js} +2 -2
  78. package/dist/cli/{sql-layout-CkxDNVEH.js → sql-layout-zo02f3Dm.js} +2 -2
  79. package/dist/cli/{stack-env-6hS-WEmh.js → stack-env-3ziggrU3.js} +1 -1
  80. package/dist/cli/{sync-pq6gmlhG.js → sync-m-oZ_SyI.js} +4 -4
  81. package/dist/cli/{upgrade-Dp9p7A69.js → upgrade-C9sgVZ5z.js} +5 -5
  82. package/dist/cli/{upgrade-BoHb4h9P.js → upgrade-WwEJaX3i.js} +2 -2
  83. package/dist/cli/{version-CQHFm-ak.js → version-D2BQuqta.js} +1 -1
  84. package/dist/client/index.d.ts +5 -5
  85. package/dist/client/native/index.d.ts +4 -4
  86. package/dist/config/index.d.ts +2 -2
  87. package/dist/{context-B4TsE2gY.d.ts → context-nbYYjv7U.d.ts} +13 -1
  88. package/dist/{controller-CtwAsnVV.d.ts → controller-TRocodqG.d.ts} +1 -1
  89. package/dist/create/index.d.ts +3 -3
  90. package/dist/create/index.js +1 -1
  91. package/dist/create/lite/index.d.ts +3 -3
  92. package/dist/create/lite/index.js +1 -1
  93. package/dist/{entitlements-Bw3eYGKJ.d.ts → entitlements-B1i1-wfe.d.ts} +1 -1
  94. package/dist/{field-errors-DkzFduux.d.ts → field-errors-tJvehEFc.d.ts} +4 -4
  95. package/dist/{index-CBQT_nXf.d.ts → index-8US7qlvW.d.ts} +2 -2
  96. package/dist/{index-BNgpz_BV.d.ts → index-BKrxynq9.d.ts} +2 -2
  97. package/dist/{index-CB66nl14.d.ts → index-BkzXwuIN.d.ts} +1 -1
  98. package/dist/{index-BxckmAFc.d.ts → index-CWAQRWY8.d.ts} +2 -2
  99. package/dist/{index-Cw5gGSP8.d.ts → index-zsgNmE8m.d.ts} +6 -6
  100. package/dist/mapper/bin.js +5 -5
  101. package/dist/mcp/index.d.ts +1 -1
  102. package/dist/next/index.d.ts +86 -11
  103. package/dist/next/index.js +189 -49
  104. package/dist/{operations-CqmQrTKw.d.ts → operations-CB9atU2e.d.ts} +1 -1
  105. package/dist/{options-C4LuqmdG.js → options-BKBy5wM_.js} +2 -1
  106. package/dist/otel/index.js +4 -4
  107. package/dist/{ports-6LBgr1Aa.d.ts → ports-hpbyMySO.d.ts} +1 -1
  108. package/dist/powersync/index.d.ts +2 -2
  109. package/dist/preset/index.d.ts +3 -3
  110. package/dist/{project-C4NA_van.js → project-B32wb5J6.js} +1 -1
  111. package/dist/{push-token-BXsrJ7W9.d.ts → push-token-DQ1ycFPU.d.ts} +1 -1
  112. package/dist/react/index.d.ts +5 -5
  113. package/dist/react/native/index.d.ts +1 -1
  114. package/dist/react/server.d.ts +5 -5
  115. package/dist/realtime/index.d.ts +3 -3
  116. package/dist/records/index.d.ts +3 -3
  117. package/dist/server/index.d.ts +3 -3
  118. package/dist/server/index.js +1 -1
  119. package/dist/sign-in-BzihC_8k.d.ts +50 -0
  120. package/dist/{sign-in-NO7LWlw4.js → sign-in-Cyj3ZlFX.js} +120 -25
  121. package/dist/solid/index.d.ts +5 -5
  122. package/dist/sql/index.d.ts +4 -4
  123. package/dist/sql/index.js +2 -2
  124. package/dist/{sql-CoBySj2F.js → sql-CyeDg3Yh.js} +279 -171
  125. package/dist/ssr/index.d.ts +1 -1
  126. package/dist/svelte/index.d.ts +5 -5
  127. package/dist/{tenant-Ded341Qz.d.ts → tenant-C9YE_kqK.d.ts} +1 -1
  128. package/dist/testing/index.d.ts +3 -3
  129. package/dist/{topic-XDdKzlrn.d.ts → topic-breZqx_4.d.ts} +1 -1
  130. package/dist/{types-BFwB-E1j.d.ts → types-C3I7S51U.d.ts} +2 -2
  131. package/dist/vue/index.d.ts +5 -5
  132. package/dist/{watch-topic-DpN_GEoS.d.ts → watch-topic-ItO3dz8m.d.ts} +1 -1
  133. package/dist/workflow-sdk/world/index.js +1 -1
  134. package/dist/{workflow-sdk-CaEw822d.js → workflow-sdk-BWPsdzVK.js} +36 -8
  135. package/dist/yjs/index.d.ts +1 -1
  136. package/package.json +1 -1
  137. package/schemas/config-v1.json +2 -1
  138. package/schemas/doctor-report-v1.json +1 -0
  139. package/skills/better-supabase-auth/SKILL.md +8 -1
  140. package/dist/cli/add-CwhrRJz5.js +0 -1
  141. package/dist/cli/env-uqfUbUzk.js +0 -1
  142. package/dist/cli/powersync-CbYxLsjv.js +0 -1
  143. package/dist/sign-in-CfwJAJJL.d.ts +0 -24
@@ -12,7 +12,7 @@ import { t as isSqlType } from "./sql-type-iUSZpaUu.js";
12
12
  import { a as sqlString, i as sqlIdent } from "./template-Drgg3v2J.js";
13
13
  import { i as fillTemplate, l as templatePlaceholders } from "./access-sql-CTDNuxRv.js";
14
14
  import { t as MAX_BATCH } from "./batch-limit-DKVQDz4o.js";
15
- import { $ as ownRowPolicies, A as addForeignKey, B as ensureCheck, C as PARTITION_VARIABLES, D as activeMembership, E as accessDefinesDisabledHelpers, F as defaultPartition, G as jsonSchemaChecks, H as extraFieldsJson, I as defaultPartitionName, J as memberAddedRecord, K as jwtClaim, L as disabledHelpers, M as batchFunction, N as columnRef, O as addCheck, P as columnsObject, Q as organizationMissing, R as disabledHelpersNeedLaterTables, S as NOTHING, T as SERVICE_CALLER$1, U as fail$1, V as extraFieldsArg, W as insertExtraColumns, X as membershipSuspended, Y as membershipDisabledAt, Z as notNullCheckName, _ as roleScopeIs, _t as withExtraFields, at as renameSql, b as EQUIVALENT_TRIGGERS, c as OPTIONAL_MODULE_PERMISSIONS, ct as schemaPreamble, d as isOperationModule$1, dt as sha256Hex$1, et as pageSize, f as moduleOperations, ft as shortHash, g as roleNames, gt as userGrant, h as providerPlatformRoles, ht as updatedAt, it as registerPartitions, j as addNotNullCheck, k as addExtraColumns, l as accessModel, lt as serviceGrant, m as modulePermissionKey, mt as triggerGrant, n as WORKFLOW_SDK_WORLD, nt as raise$1, o as MODULE_PERMISSION_SCOPES, ot as replaceColumnCheck, p as modulePermission, pt as splitTable$1, q as lockTable, rt as recordTrigger, s as OPERATIONS, st as revokeTable, tt as quotedTable$1, u as hasPlatformRoles, ut as serviceOnly$1, v as rolesOf, vt as writeExtraColumns, w as SCHEMA$5, x as MONTHLY_PARTITIONS, y as tenantScope, z as dropExpiredPartitions } from "./workflow-sdk-CaEw822d.js";
15
+ import { $ as ownRowPolicies, A as addForeignKey, B as ensureCheck, C as PARTITION_VARIABLES, D as activeMembership, E as accessDefinesDisabledHelpers, F as defaultPartition, G as jsonSchemaChecks, H as extraFieldsJson, I as defaultPartitionName, J as memberAddedRecord, K as jwtClaim, L as disabledHelpers, M as batchFunction, N as columnRef, O as addCheck, P as columnsObject, Q as organizationMissing, R as disabledHelpersNeedLaterTables, S as NOTHING, T as SERVICE_CALLER$1, U as fail$1, V as extraFieldsArg, W as insertExtraColumns, X as membershipSuspended, Y as membershipDisabledAt, Z as notNullCheckName, _ as roleScopeIs, _t as withExtraFields, at as renameSql, b as EQUIVALENT_TRIGGERS, c as OPTIONAL_MODULE_PERMISSIONS, ct as schemaPreamble, d as isOperationModule$1, dt as sha256Hex$1, et as pageSize, f as moduleOperations, ft as shortHash, g as roleNames, gt as userGrant, h as providerPlatformRoles, ht as updatedAt, it as registerPartitions, j as addNotNullCheck, k as addExtraColumns, l as accessModel, lt as serviceGrant, m as modulePermissionKey, mt as triggerGrant, n as WORKFLOW_SDK_WORLD, nt as raise$1, o as MODULE_PERMISSION_SCOPES, ot as replaceColumnCheck, p as modulePermission, pt as splitTable$1, q as lockTable, rt as recordTrigger, s as OPERATIONS, st as revokeTable, tt as quotedTable$1, u as hasPlatformRoles, ut as serviceOnly$1, v as rolesOf, vt as writeExtraColumns, w as SCHEMA$5, x as MONTHLY_PARTITIONS, y as tenantScope, z as dropExpiredPartitions } from "./workflow-sdk-BWPsdzVK.js";
16
16
  import { n as blockOptions, r as option, t as NO_OPTIONS } from "./options-CfVPctAw.js";
17
17
  import { t as accessRequestsSqlOptions } from "./options-gUvfr3no.js";
18
18
  import { t as activitiesSqlOptions } from "./options-sU_zGkiV.js";
@@ -32,7 +32,7 @@ import { t as automationsSqlOptions } from "./options-DcHl59RC.js";
32
32
  import { t as billingSqlOptions } from "./options-DZHZYlpD.js";
33
33
  import { t as bookingsSqlOptions } from "./options-CZDmtsbV.js";
34
34
  import { t as bulkSqlOptions } from "./options-CTl8T88w.js";
35
- import { t as calendarSqlOptions } from "./options-C4LuqmdG.js";
35
+ import { t as calendarSqlOptions } from "./options-BKBy5wM_.js";
36
36
  import { t as catalogSqlOptions } from "./options-D0sj5abR.js";
37
37
  import { t as collectionsSqlOptions } from "./options-CyjL9lTf.js";
38
38
  import { t as commentsSqlOptions } from "./options-CoSPgWKy.js";
@@ -2564,6 +2564,22 @@ function valueMethods(input) {
2564
2564
  return `${sqlString(name)}, ${readValue(mapOf(table, logical), `${alias}.${sqlIdent(name)}`)}`;
2565
2565
  }).join(", ")})`;
2566
2566
  },
2567
+ rowJson(table, alias, options = {}) {
2568
+ const pairs = Object.entries(tables[table]?.columns ?? {}).flatMap(([logical, name]) => {
2569
+ const app = input.mapped(table, logical);
2570
+ const own = input.own(name);
2571
+ const labelled = changes(table, logical);
2572
+ if (app === null || app === own && !labelled) return [];
2573
+ const value = `${alias}.${sqlIdent(app)}`;
2574
+ const as = options.as?.[logical];
2575
+ if (labelled) {
2576
+ const label = readValue(mapOf(table, logical), value);
2577
+ return [...app === own ? [] : [`${sqlString(app)}, ${label}`], `${sqlString(own)}, ${label}`];
2578
+ }
2579
+ return [`${sqlString(own)}, ${as === void 0 ? value : as(value)}`];
2580
+ });
2581
+ return pairs.length === 0 ? `to_jsonb(${alias})` : `(to_jsonb(${alias}) || jsonb_build_object(${pairs.join(", ")}))`;
2582
+ },
2567
2583
  mapsValues: changes
2568
2584
  };
2569
2585
  }
@@ -2906,7 +2922,9 @@ function createModuleContext(module, namesOf, source = {}) {
2906
2922
  tables: names.tables,
2907
2923
  maps: checkedValueMaps(where, config.values, names.tables),
2908
2924
  cast: owned.cast,
2909
- column: requiredColumn
2925
+ column: requiredColumn,
2926
+ mapped: (table, logical) => config.tables[table] === null ? null : column(table, logical),
2927
+ own: (name) => naming.rename(name)
2910
2928
  }),
2911
2929
  names,
2912
2930
  installedModules: [...installed],
@@ -4957,12 +4975,12 @@ function subjectPermissionKey(value) {
4957
4975
  //#endregion
4958
4976
  //#region src/sql/subject-registry.ts
4959
4977
  const TYPE$5 = SUBJECT_TYPE_PATTERN;
4960
- const COLUMN$9 = /^[a-z_][a-z0-9_]{0,62}$/;
4978
+ const COLUMN$10 = /^[a-z_][a-z0-9_]{0,62}$/;
4961
4979
  const ID_TYPE$2 = /^[a-z][a-z0-9_ ]{0,62}$/;
4962
4980
  const ACTION = /^[a-z][a-z0-9_.-]{0,62}$/;
4963
4981
  const PLACEHOLDER$1 = /\{([^}]*)\}/g;
4964
4982
  function column$2(where, value) {
4965
- if (typeof value !== "string" || !COLUMN$9.test(value)) throw new TypeError(`${where} must be a column name`);
4983
+ if (typeof value !== "string" || !COLUMN$10.test(value)) throw new TypeError(`${where} must be a column name`);
4966
4984
  return value;
4967
4985
  }
4968
4986
  const RESOURCE = /^[a-z][a-z0-9_]{0,62}$/;
@@ -8454,8 +8472,8 @@ const NAMES$114 = {
8454
8472
  }
8455
8473
  } }
8456
8474
  };
8457
- const COLUMN$8 = /^[a-z_][a-z0-9_]*$/;
8458
- const isColumn = (value) => typeof value === "string" && COLUMN$8.test(value);
8475
+ const COLUMN$9 = /^[a-z_][a-z0-9_]*$/;
8476
+ const isColumn = (value) => typeof value === "string" && COLUMN$9.test(value);
8459
8477
  const isColumnList$1 = (value) => Array.isArray(value) && value.every(isColumn);
8460
8478
  const isChildInput = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
8461
8479
  function childrenOf(value, where) {
@@ -23005,7 +23023,7 @@ ${userGrant(`${ctx.fn("revert_audit_entries")}(text[])`)}`;
23005
23023
  //#endregion
23006
23024
  //#region src/sql/modules/audit-subjects.ts
23007
23025
  const HEADER = /^[a-z0-9-]+$/;
23008
- const COLUMN$7 = /^[a-z_][a-z0-9_]*$/;
23026
+ const COLUMN$8 = /^[a-z_][a-z0-9_]*$/;
23009
23027
  const CLAIM = /^[a-z_][a-z0-9_]*(\.[a-z_][a-z0-9_]*)*$/i;
23010
23028
  const UUID$3 = "'^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$'";
23011
23029
  /**
@@ -23077,7 +23095,7 @@ function subjectColumns$1(ctx, taken) {
23077
23095
  if (raw === void 0) return [];
23078
23096
  if (!isRecord$1(raw)) throw new TypeError(`${where} must map column names to { type, from }`);
23079
23097
  return Object.entries(raw).map(([name, entry]) => {
23080
- if (!COLUMN$7.test(name) || name.length > 46) throw new TypeError(`${where}: "${name}" is not a valid column name`);
23098
+ if (!COLUMN$8.test(name) || name.length > 46) throw new TypeError(`${where}: "${name}" is not a valid column name`);
23081
23099
  if (taken.includes(name)) throw new TypeError(`${where}: "${name}" is already a column of the audit log`);
23082
23100
  const type = isRecord$1(entry) ? entry["type"] : void 0;
23083
23101
  const from = isRecord$1(entry) ? entry["from"] ?? name : void 0;
@@ -25752,12 +25770,12 @@ const RULES = {
25752
25770
  };
25753
25771
  //#endregion
25754
25772
  //#region src/sql/subject-columns.ts
25755
- const COLUMN$6 = /^[a-z_][a-z0-9_]{0,62}$/u;
25773
+ const COLUMN$7 = /^[a-z_][a-z0-9_]{0,62}$/u;
25756
25774
  function boundSubjects$1(subjects, where) {
25757
25775
  return subjects.flatMap(([type, subject]) => {
25758
25776
  const column = subject.extra["column"];
25759
25777
  if (column === void 0) return [];
25760
- if (typeof column !== "string" || !COLUMN$6.test(column)) throw new TypeError(`${where}.${type}.column must be a column name`);
25778
+ if (typeof column !== "string" || !COLUMN$7.test(column)) throw new TypeError(`${where}.${type}.column must be a column name`);
25761
25779
  return [{
25762
25780
  type,
25763
25781
  column,
@@ -29817,6 +29835,31 @@ function appFunction(value, key) {
29817
29835
  if (typeof value !== "string" || !QUALIFIED$1.test(value)) throw new TypeError(`blocks.calendar.options.accessFunctions.${key} must be a schema-qualified function name, such as public.can_read_calendar`);
29818
29836
  return value.split(".").map(sqlIdent).join(".");
29819
29837
  }
29838
+ const COLUMN$6 = /^[a-z_][a-z0-9_]{0,62}$/;
29839
+ function ruleDialect(ctx) {
29840
+ const raw = ctx.option("ruleDialect");
29841
+ const at = "blocks.calendar.options.ruleDialect";
29842
+ if (raw === void 0) return {
29843
+ lower: false,
29844
+ scalarMonthDay: false
29845
+ };
29846
+ if (!isRecord$1(raw) || ctx.owns("rules") || ctx.has("rules", "rrule")) throw new TypeError(`${at} takes { weekdays, monthDay, ordinal } and needs your own rules table with columns.rules.rrule mapped to null`);
29847
+ const { weekdays = "upper", monthDay = "list", ordinal } = raw;
29848
+ if (weekdays !== "upper" && weekdays !== "lower" || monthDay !== "list" && monthDay !== "scalar") throw new TypeError(`${at}: weekdays is "upper" or "lower", monthDay is "list" or "scalar"`);
29849
+ if (ordinal === void 0) return {
29850
+ lower: weekdays === "lower",
29851
+ scalarMonthDay: monthDay === "scalar"
29852
+ };
29853
+ if (!isRecord$1(ordinal) || typeof ordinal["weekday"] !== "string" || typeof ordinal["position"] !== "string" || !COLUMN$6.test(ordinal["weekday"]) || !COLUMN$6.test(ordinal["position"])) throw new TypeError(`${at}.ordinal takes { weekday, position }, two column names of the rules table`);
29854
+ return {
29855
+ lower: weekdays === "lower",
29856
+ scalarMonthDay: monthDay === "scalar",
29857
+ ordinal: {
29858
+ weekday: sqlIdent(ordinal["weekday"]),
29859
+ position: sqlIdent(ordinal["position"])
29860
+ }
29861
+ };
29862
+ }
29820
29863
  function calendarFeatures(ctx) {
29821
29864
  const access = ctx.flag("access", false);
29822
29865
  const functions = ctx.option("accessFunctions");
@@ -29826,6 +29869,7 @@ function calendarFeatures(ctx) {
29826
29869
  const attendeeKey = ctx.text("attendeeKey", "email");
29827
29870
  if (attendeeKey !== "email" && attendeeKey !== "any") throw new TypeError("blocks.calendar.options.attendeeKey must be \"email\" or \"any\"");
29828
29871
  const table = recurrence === "table";
29872
+ if (ctx.option("ruleDialect") !== void 0) ruleDialect(ctx);
29829
29873
  if (table && (!ctx.hasTable("rules") || !ctx.hasTable("recurrenceDates"))) throw new TypeError("blocks.calendar.options.recurrence \"table\" needs the rules and recurrenceDates tables");
29830
29874
  const readFn = isRecord$1(functions) ? appFunction(functions["read"], "read") : void 0;
29831
29875
  const writeFn = isRecord$1(functions) ? appFunction(functions["write"], "write") : void 0;
@@ -30084,13 +30128,18 @@ ${userGrant(`${ctx.fn("list_calendar_grants")}(uuid)`)}
30084
30128
  function ruleText(ctx) {
30085
30129
  const r = (column) => `r.${ctx.col("rules", column)}`;
30086
30130
  if (ctx.has("rules", "rrule")) return r("rrule");
30131
+ const dialect = ruleDialect(ctx);
30087
30132
  const list = (key, column) => ctx.has("rules", column) ? [`'${key}=' || nullif(translate(${r(column)}::text, '{}" ', ''), '')`] : [];
30133
+ const days = ctx.has("rules", "byDay") ? `nullif(translate(${dialect.lower ? `upper(${r("byDay")}::text)` : `${r("byDay")}::text`}, '{}" ', ''), '')` : void 0;
30134
+ const ordinal = dialect.ordinal === void 0 ? void 0 : `r.${dialect.ordinal.position}::text || upper(r.${dialect.ordinal.weekday}::text)`;
30135
+ const dayParts = [days, ordinal].filter((part) => part !== void 0);
30136
+ const byDay = dialect.lower || ordinal !== void 0 ? dayParts.length === 0 ? [] : [`'BYDAY=' || ${dayParts.length === 1 ? dayParts[0] : `coalesce(${dayParts.join(", ")})`}`] : list("BYDAY", "byDay");
30088
30137
  return `nullif(concat_ws(';', ${[
30089
30138
  `'FREQ=' || upper(${ctx.label("rules", "freq", r("freq"))})`,
30090
30139
  ...ctx.has("rules", "interval") ? [`'INTERVAL=' || ${r("interval")}`] : [],
30091
30140
  ...ctx.has("rules", "count") ? [`'COUNT=' || ${r("count")}`] : [],
30092
30141
  ...ctx.has("rules", "until") ? [`'UNTIL=' || to_char(${r("until")}::timestamptz at time zone 'UTC', 'YYYYMMDD"T"HH24MISS"Z"')`] : [],
30093
- ...list("BYDAY", "byDay"),
30142
+ ...byDay,
30094
30143
  ...list("BYMONTHDAY", "byMonthDay"),
30095
30144
  ...list("BYMONTH", "byMonth"),
30096
30145
  ...list("BYSETPOS", "bySetPos")
@@ -30154,12 +30203,16 @@ function insertRule(ctx, id, tenant, source) {
30154
30203
  add("interval", () => `(${part("INTERVAL", "[0-9]+")})::integer`);
30155
30204
  add("count", () => `(${part("COUNT", "[0-9]+")})::integer`);
30156
30205
  add("until", () => `case when ${part("UNTIL")} is null then null else to_timestamp(rpad(translate(${part("UNTIL")}, 'TZ', ''), 14, '0'), 'YYYYMMDDHH24MISS')::timestamp at time zone 'UTC' end`);
30157
- for (const [column, key] of [
30158
- ["byDay", "BYDAY"],
30159
- ["byMonthDay", "BYMONTHDAY"],
30160
- ["byMonth", "BYMONTH"],
30161
- ["bySetPos", "BYSETPOS"]
30162
- ]) add(column, () => ctx.cast("rules", column, `'{' || ${part(key)} || '}'`));
30206
+ const dialect = ruleDialect(ctx);
30207
+ const ordinalDay = `substring(upper(${source}) from '(?:^|;)BYDAY=([+-]?[0-9]+)[A-Z]{2}(?:;|$)')`;
30208
+ const weekdays = (value) => dialect.lower ? `lower(${value})` : value;
30209
+ add("byDay", () => ctx.cast("rules", "byDay", dialect.ordinal === void 0 ? `'{' || ${weekdays(part("BYDAY"))} || '}'` : `case when ${ordinalDay} is null then '{' || ${weekdays(part("BYDAY"))} || '}' end`));
30210
+ add("byMonthDay", () => ctx.cast("rules", "byMonthDay", dialect.scalarMonthDay ? part("BYMONTHDAY", "-?[0-9]+") : `'{' || ${part("BYMONTHDAY")} || '}'`));
30211
+ for (const [column, key] of [["byMonth", "BYMONTH"], ["bySetPos", "BYSETPOS"]]) add(column, () => ctx.cast("rules", column, `'{' || ${part(key)} || '}'`));
30212
+ if (dialect.ordinal !== void 0) {
30213
+ columns.push(dialect.ordinal.position, dialect.ordinal.weekday);
30214
+ values.push(`(${ordinalDay})::integer`, weekdays(`substring(upper(${source}) from '(?:^|;)BYDAY=[+-]?[0-9]+([A-Z]{2})(?:;|$)')`));
30215
+ }
30163
30216
  }
30164
30217
  return `insert into ${rules} (${columns.join(", ")}) values (${values.join(", ")});`;
30165
30218
  }
@@ -31527,7 +31580,8 @@ const CALENDAR_NAMES = {
31527
31580
  "recurrence",
31528
31581
  "rdates",
31529
31582
  "attendeeKey",
31530
- "calendarDetails"
31583
+ "calendarDetails",
31584
+ "ruleDialect"
31531
31585
  ],
31532
31586
  tables: {
31533
31587
  calendars: {
@@ -31690,6 +31744,7 @@ const CALENDAR_NAMES = {
31690
31744
  bySetPos: "by_set_pos"
31691
31745
  },
31692
31746
  optional: [
31747
+ "id",
31693
31748
  "tenant",
31694
31749
  "rrule",
31695
31750
  "freq",
@@ -32763,7 +32818,7 @@ begin
32763
32818
  if exists (select 1 from ${ledger.table("accounts")} x join ${ledger.table("entries")} y on y.${le("account")} = x.${la("id")}
32764
32819
  where x.${la("tenant")} = v_tenant and x.${la("managedBy")} = 'inventory' and x.${la("kind")} = 'stock'
32765
32820
  and x.${la("metadata")} ->> 'locationId' = delete_location.location::text)
32766
- or exists (select 1 from ${ctx.table("reservations")} x where x.${r("location")} = delete_location.location and x.${r("status")} = 'active') then
32821
+ or exists (select 1 from ${ctx.table("reservations")} x where x.${r("location")} = delete_location.location and ${ctx.is("reservations", "status", `x.${r("status")}`, ["active"])}) then
32767
32822
  ${fail$1("INVENTORY_LOCATION_IN_USE", "the location has stock history; deactivate it instead", "23503")}
32768
32823
  end if;
32769
32824
  delete from ${locations} x where x.${l("id")} = delete_location.location;
@@ -32961,9 +33016,9 @@ begin
32961
33016
  ])}
32962
33017
  ${lockLevel(ctx, "reserve_stock.variant", "reserve_stock.location")}
32963
33018
  with expired as (
32964
- update ${reservations} x set ${r("status")} = 'expired', ${r("updatedAt")} = now()
33019
+ update ${reservations} x set ${r("status")} = ${ctx.value("reservations", "status", "expired")}, ${r("updatedAt")} = now()
32965
33020
  where x.${r("variant")} = reserve_stock.variant and x.${r("location")} = reserve_stock.location
32966
- and x.${r("status")} = 'active' and x.${r("expiresAt")} <= now()
33021
+ and ${ctx.is("reservations", "status", `x.${r("status")}`, ["active"])} and x.${r("expiresAt")} <= now()
32967
33022
  returning x.${r("quantity")} as quantity
32968
33023
  )
32969
33024
  update ${levels} x set ${lv("reserved")} = greatest(x.${lv("reserved")} - (select coalesce(sum(e.quantity), 0)::integer from expired e), 0)
@@ -33012,7 +33067,7 @@ declare
33012
33067
  v_movement uuid;
33013
33068
  begin
33014
33069
  select x.${r("tenant")} as tenant, x.${r("variant")} as variant, x.${r("location")} as location,
33015
- x.${r("quantity")} as quantity, x.${r("status")} as status, x.${r("expiresAt")} as expires_at,
33070
+ x.${r("quantity")} as quantity, ${ctx.label("reservations", "status", `x.${r("status")}`)} as status, x.${r("expiresAt")} as expires_at,
33016
33071
  x.${r("referenceType")} as reference_type, x.${r("referenceId")} as reference_id
33017
33072
  into v_row from ${reservations} x where x.${r("id")} = commit_reservation.reservation for update;
33018
33073
  if not found then
@@ -33026,7 +33081,7 @@ begin
33026
33081
  ${fail$1("INVENTORY_RESERVATION_EXPIRED", "the reservation has expired", "55000")}
33027
33082
  end if;
33028
33083
  ${releaseLevel("v_row.variant", "v_row.location", "v_row.quantity")}
33029
- update ${reservations} x set ${r("status")} = 'committed', ${r("updatedAt")} = now()
33084
+ update ${reservations} x set ${r("status")} = ${ctx.value("reservations", "status", "committed")}, ${r("updatedAt")} = now()
33030
33085
  where x.${r("id")} = commit_reservation.reservation;
33031
33086
  v_movement := ${moveStock(ctx, {
33032
33087
  tenant: "v_row.tenant",
@@ -33060,7 +33115,7 @@ declare
33060
33115
  v_row record;
33061
33116
  begin
33062
33117
  select x.${r("id")} as id, x.${r("tenant")} as tenant, x.${r("variant")} as variant, x.${r("location")} as location,
33063
- x.${r("quantity")} as quantity, x.${r("status")} as status
33118
+ x.${r("quantity")} as quantity, ${ctx.label("reservations", "status", `x.${r("status")}`)} as status
33064
33119
  into v_row from ${reservations} x where x.${r("id")} = release_reservation.reservation for update;
33065
33120
  if not found then
33066
33121
  return false;
@@ -33070,7 +33125,7 @@ begin
33070
33125
  return false;
33071
33126
  end if;
33072
33127
  ${releaseLevel("v_row.variant", "v_row.location", "v_row.quantity")}
33073
- update ${reservations} x set ${r("status")} = 'released', ${r("updatedAt")} = now()
33128
+ update ${reservations} x set ${r("status")} = ${ctx.value("reservations", "status", "released")}, ${r("updatedAt")} = now()
33074
33129
  where x.${r("id")} = release_reservation.reservation;
33075
33130
  ${released("v_row.", "released")}
33076
33131
  return true;
@@ -33094,12 +33149,12 @@ begin
33094
33149
  select x.${r("id")} as id, x.${r("tenant")} as tenant, x.${r("variant")} as variant,
33095
33150
  x.${r("location")} as location, x.${r("quantity")} as quantity
33096
33151
  from ${reservations} x
33097
- where x.${r("status")} = 'active' and x.${r("expiresAt")} <= now()
33152
+ where ${ctx.is("reservations", "status", `x.${r("status")}`, ["active"])} and x.${r("expiresAt")} <= now()
33098
33153
  order by x.${r("expiresAt")}
33099
33154
  limit greatest(coalesce(expire_reservations.max_rows, 500), 1)
33100
33155
  for update skip locked
33101
33156
  loop
33102
- update ${reservations} x set ${r("status")} = 'expired', ${r("updatedAt")} = now() where x.${r("id")} = v_row.id;
33157
+ update ${reservations} x set ${r("status")} = ${ctx.value("reservations", "status", "expired")}, ${r("updatedAt")} = now() where x.${r("id")} = v_row.id;
33103
33158
  ${releaseLevel("v_row.variant", "v_row.location", "v_row.quantity")}
33104
33159
  ${released("v_row.", "expired")}
33105
33160
  v_count := v_count + 1;
@@ -33203,12 +33258,12 @@ begin
33203
33258
  begin
33204
33259
  if v_created then
33205
33260
  insert into ${products} (${p("tenant")}, ${p("title")}, ${p("slug")}${desc ? `, ${p("description")}` : ""}${kind ? `, ${p("kind")}` : ""})
33206
- values (save_product.tenant, save_product.title, v_slug${desc ? ", save_product.description" : ""}${kind ? ", coalesce(save_product.kind, 'physical')" : ""})
33207
- returning ${p("id")}, ${p("status")} into v_id, v_status;
33261
+ values (save_product.tenant, save_product.title, v_slug${desc ? ", save_product.description" : ""}${kind ? `, ${ctx.cast("products", "kind", "coalesce(save_product.kind, 'physical')")}` : ""})
33262
+ returning ${p("id")}, ${ctx.label("products", "status", p("status"))} into v_id, v_status;
33208
33263
  else
33209
- update ${products} x set ${p("title")} = save_product.title, ${p("slug")} = v_slug${desc ? `, ${p("description")} = save_product.description` : ""}${kind ? `, ${p("kind")} = coalesce(save_product.kind, x.${p("kind")})` : ""}, ${p("updatedAt")} = now()
33264
+ update ${products} x set ${p("title")} = save_product.title, ${p("slug")} = v_slug${desc ? `, ${p("description")} = save_product.description` : ""}${kind ? `, ${p("kind")} = coalesce(${ctx.cast("products", "kind", "save_product.kind")}, x.${p("kind")})` : ""}, ${p("updatedAt")} = now()
33210
33265
  where x.${p("id")} = save_product.product and x.${p("tenant")} = save_product.tenant
33211
- returning x.${p("status")} into v_status;
33266
+ returning ${ctx.label("products", "status", `x.${p("status")}`)} into v_status;
33212
33267
  if not found then
33213
33268
  ${fail$1("CATALOG_PRODUCT_NOT_FOUND", "product not found", "P0002")}
33214
33269
  end if;
@@ -33250,7 +33305,7 @@ declare
33250
33305
  v_tenant ${ctx.idType};
33251
33306
  v_from text;
33252
33307
  begin
33253
- select x.${p("tenant")}, x.${p("status")} into v_tenant, v_from from ${products} x where x.${p("id")} = set_product_status.product for update;
33308
+ select x.${p("tenant")}, ${ctx.label("products", "status", `x.${p("status")}`)} into v_tenant, v_from from ${products} x where x.${p("id")} = set_product_status.product for update;
33254
33309
  if v_tenant is null then
33255
33310
  ${fail$1("CATALOG_PRODUCT_NOT_FOUND", "product not found", "P0002")}
33256
33311
  end if;
@@ -33942,7 +33997,7 @@ as $$
33942
33997
  select jsonb_build_object(
33943
33998
  'id', p.${p("id")},
33944
33999
  'slug', p.${p("slug")},
33945
- 'status', p.${p("status")},
34000
+ 'status', ${ctx.label("products", "status", `p.${p("status")}`)},
33946
34001
  'kind', ${kind ? `p.${p("kind")}` : "null"},
33947
34002
  'locale', ${locale},
33948
34003
  'title', ${title},
@@ -34918,7 +34973,7 @@ security definer
34918
34973
  set search_path = ''
34919
34974
  as $$
34920
34975
  select x.${p("id")} from ${products} x
34921
- where x.${p("status")} = 'active'
34976
+ where ${ctx.is("products", "status", `x.${p("status")}`, ["active"])}
34922
34977
  and x.${p("tenant")} in (select y.${s("tenant")} from ${storefronts} y where y.${s("publishedAt")} is not null)
34923
34978
  $$;
34924
34979
  revoke execute on function ${fn("storefront_products")}() from public;
@@ -35113,7 +35168,7 @@ const NAMES$94 = {
35113
35168
  updatedAt: "updated_at"
35114
35169
  },
35115
35170
  optional: ["description", "kind"],
35116
- typed: ["status"]
35171
+ typed: ["status", "kind"]
35117
35172
  },
35118
35173
  options: {
35119
35174
  name: "product_options",
@@ -35542,7 +35597,7 @@ function storefrontPolicies(ctx, names) {
35542
35597
  const t = (name) => ctx.table(name);
35543
35598
  const c = (table, column) => ctx.col(table, column);
35544
35599
  const publicTables = [
35545
- ["products", `${c("products", "status")} = 'active' and ${c("products", "tenant")} in (select ${names.fn("storefront_tenants")}())`],
35600
+ ["products", `${ctx.is("products", "status", c("products", "status"), ["active"])} and ${c("products", "tenant")} in (select ${names.fn("storefront_tenants")}())`],
35546
35601
  ["options", `${c("options", "product")} in (select ${names.fn("storefront_products")}())`],
35547
35602
  ["optionValues", `${c("optionValues", "option")} in (select o.${c("options", "id")} from ${t("options")} o where o.${c("options", "product")} in (select ${names.fn("storefront_products")}()))`],
35548
35603
  ["variants", `${c("variants", "product")} in (select ${names.fn("storefront_products")}())`],
@@ -49495,6 +49550,7 @@ function lineItemsSql(ctx, items, options) {
49495
49550
  ["position", "x.ordinality::integer"]
49496
49551
  ].filter(([column]) => has(column)).map(([column, value]) => [column, column === "productType" ? ctx.cast(items.lines, column, value) : value]);
49497
49552
  const extras = items.extras ?? [];
49553
+ const extrasInsert = insertExtraColumns(t, extras, "(case when jsonb_typeof(x.value -> 'fields') = 'object' then x.value -> 'fields' end)");
49498
49554
  return `${ctx.manages ? `create table if not exists ${t} (
49499
49555
  ${c("id")} uuid primary key default gen_random_uuid(),
49500
49556
  ${c("tenant")} ${ctx.idType} not null,
@@ -49604,8 +49660,8 @@ begin
49604
49660
  end if;
49605
49661
  delete from ${t} l where l.${c("parent")} = v_parent${replaces ? "" : ` and l.${c("position")} > jsonb_array_length(coalesce(${options.setter}.lines, '[]'))`};
49606
49662
  begin
49607
- insert into ${t} (${written.map(([column]) => c(column)).join(", ")})
49608
- select ${written.map(([, value]) => value).join(",\n ")}
49663
+ insert into ${t} (${written.map(([column]) => c(column)).join(", ")}${extrasInsert.columns})
49664
+ select ${written.map(([, value]) => value).join(",\n ")}${extrasInsert.values}
49609
49665
  from jsonb_array_elements(coalesce(${options.setter}.lines, '[]')) with ordinality x${replaces ? "" : `\n on conflict (${c("parent")}, ${c("position")}) do update set ${written.filter(([column]) => ![
49610
49666
  "tenant",
49611
49667
  "parent",
@@ -49772,20 +49828,26 @@ function sequenceFormatOf(ctx, entity, tenant) {
49772
49828
  if (!ctx.installed("numbering")) return;
49773
49829
  const entry = sequenceEntry(ctx.of("numbering"), entity);
49774
49830
  if (entry === void 0 || typeof entry["format"] !== "string") return;
49775
- return isRecord$1(entry["formatFrom"]) ? `${ctx.of("numbering").fn("number_format")}(${tenant}, ${sqlString(entity)})` : sqlString(entry["format"]);
49831
+ return {
49832
+ format: isRecord$1(entry["formatFrom"]) ? `${ctx.of("numbering").fn("number_format")}(${tenant}, ${sqlString(entity)})` : sqlString(entry["format"]),
49833
+ assigns: typeof entry["table"] === "string"
49834
+ };
49776
49835
  }
49777
49836
  /**
49778
49837
  * PL/pgSQL that assigns the next number of `entity` in `tenant` to `target.seq`
49779
49838
  * (bigint) and `target.identifier` (text): from `numbering` when it numbers the
49780
49839
  * entity, otherwise one more than the tenant's highest in `fallback.table`
49781
- * under a transaction lock, with `prefix` in front (`DEAL-4821`).
49840
+ * under a transaction lock, with `prefix` in front (`DEAL-4821`). When the
49841
+ * entity has a table, the number is marked as issued for the transaction, so
49842
+ * its assign trigger accepts it on the block's insert instead of refusing it.
49782
49843
  */
49783
49844
  function assignNumberSql(ctx, entity, tenant, target, fallback) {
49784
- const format = sequenceFormatOf(ctx, entity, tenant);
49785
- if (format !== void 0) {
49845
+ const sequence = sequenceFormatOf(ctx, entity, tenant);
49846
+ if (sequence !== void 0) {
49786
49847
  const next = ctx.of("numbering").fn("next_number");
49787
49848
  return `${target.seq} := ${next}(${tenant}, ${sqlString(entity)}, now());
49788
- ${target.identifier} := better_supabase.format_assigned_number(${format}, ${target.seq}, now());`;
49849
+ ${target.identifier} := better_supabase.format_assigned_number(${sequence.format}, ${target.seq}, now());${sequence.assigns ? `
49850
+ perform set_config('better_supabase.issued_number', ${sqlString(entity)} || chr(31) || ${target.seq}::text || chr(31) || ${target.identifier}, true);` : ""}`;
49789
49851
  }
49790
49852
  return `perform pg_catalog.pg_advisory_xact_lock(pg_catalog.hashtextextended(${tenant}::text || ${sqlString(`:${entity}`)}, 0));
49791
49853
  select coalesce(max(x.${fallback.seq}), 0) + 1 into ${target.seq} from ${fallback.table} x where x.${fallback.tenant} = ${tenant};
@@ -54861,8 +54923,9 @@ function trigger$1(ctx, item) {
54861
54923
  const sequence = item.sequenceColumn === void 0 ? void 0 : sqlIdent(item.sequenceColumn);
54862
54924
  const fn = sqlIdent(`bsb_assign_number_${item.name}`);
54863
54925
  const manual = fail$1("NUMBER_MANUAL", "a number is assigned by the sequence, not set by hand", "42501");
54926
+ const issued = `coalesce(v_issued[1] = ${sqlString(item.name)} and new.${col}::text in (v_issued[2], v_issued[3])${sequence === void 0 ? "" : ` and new.${sequence}::text = v_issued[2]`}, false)`;
54864
54927
  const manualSequence = sequence === void 0 ? "" : `
54865
- if not (${SERVICE_CALLER$1}) then
54928
+ if not (${SERVICE_CALLER$1} or ${issued}) then
54866
54929
  if tg_op = 'INSERT' then
54867
54930
  if new.${sequence} is not null then
54868
54931
  ${manual}
@@ -54881,6 +54944,7 @@ as $$
54881
54944
  declare
54882
54945
  v_n bigint;
54883
54946
  v_at timestamptz;
54947
+ v_issued text[] := string_to_array(coalesce(current_setting('better_supabase.issued_number', true), ''), chr(31));
54884
54948
  begin
54885
54949
  if not (better_supabase.actor_may_write()) then
54886
54950
  ${fail$1("ACTOR_READ_ONLY", "This session is read-only")}
@@ -54893,7 +54957,9 @@ begin
54893
54957
  end if;
54894
54958
  -- A number is assigned here or by the service role, never sent by a client.${manualSequence}
54895
54959
  if new.${col} is not null then
54896
- if not (${SERVICE_CALLER$1}) then
54960
+ if ${issued} then
54961
+ perform set_config('better_supabase.issued_number', '', true);
54962
+ elsif not (${SERVICE_CALLER$1}) then
54897
54963
  ${manual}
54898
54964
  end if;
54899
54965
  return new;
@@ -57555,10 +57621,19 @@ function quoteFunctions(ctx, n) {
57555
57621
  ${fail$1(`QUOTE_${thing}_UNSUPPORTED`, `this quotes table has no ${what}`, "22023")}
57556
57622
  end if;`;
57557
57623
  const editable = (alias) => `(${n.service} or ${ctx.scope.can(`${alias}.${q("tenant")}`, n.write)})`;
57558
- const open = (alias) => `${alias}.${q("status")} in ('draft', 'changes_requested')`;
57624
+ const st = (value, labels, negate = false) => ctx.is("quotes", "status", value, labels, negate);
57625
+ const sv = (label) => ctx.value("quotes", "status", label);
57626
+ const viewed = ctx.appValues("quotes", "status", "viewed").length > 0;
57627
+ const markViewed = () => viewed || has("viewedAt") ? ` if ${st(`v_row.${q("status")}`, ["sent"])}${viewed ? "" : ` and v_row.${q("viewedAt")} is null`} then
57628
+ update ${t("quotes")} x set ${viewed ? `${q("status")} = ${sv("viewed")}${has("viewedAt") ? ", " : ""}` : ""}${has("viewedAt") ? `${q("viewedAt")} = now()` : ""} where x.${q("id")} = v_row.${q("id")}
57629
+ returning * into v_row;
57630
+ ${record("quote.viewed", "v_row")}
57631
+ end if;` : " null;";
57632
+ const open = (alias) => st(`${alias}.${q("status")}`, ["draft", "changes_requested"]);
57559
57633
  const lines = (alias) => `coalesce((select jsonb_agg(jsonb_build_object('description', ql.${l("description")}, 'quantity', ql.${l("quantity")}, 'unitAmount', ql.${l("unitAmount")}::text, 'discountBps', ${lineColumn(ctx, "lines", "ql", "discountBps")}, 'taxRateBps', ${lineColumn(ctx, "lines", "ql", "taxRateBps")}, 'taxCode', ${lineColumn(ctx, "lines", "ql", "taxCode")}, 'product', case when ${lineColumn(ctx, "lines", "ql", "productType")} is null then null else jsonb_build_object('type', ${lineColumn(ctx, "lines", "ql", "productType")}, 'id', ${lineColumn(ctx, "lines", "ql", "productId")}) end${lineFieldsJson("ql", n.lineExtras)}) order by ql.${l("position")}) from ${t("lines")} ql where ql.${l("parent")} = ${alias}.${q("id")}), '[]'::jsonb)`;
57560
57634
  const int8 = ["number", ...Object.keys(TOTAL_COLUMNS)].map(q);
57561
- const row = (alias) => `(to_jsonb(${alias}) - ${sqlString(q("tokenHash").replaceAll("\"", ""))}) || ${int8Text(alias, int8)} || jsonb_build_object('lines', ${lines(alias)}${n.extras.length === 0 ? "" : `, 'fields', ${columnsObject(alias, n.extras.map((extra) => extra.name))}`})`;
57635
+ const int8As = Object.fromEntries(["number", ...Object.keys(TOTAL_COLUMNS)].map((logical) => [logical, (value) => `${value}::text`]));
57636
+ const row = (alias) => `(${ctx.rowJson("quotes", alias, { as: int8As })} - ${sqlString(q("tokenHash").replaceAll("\"", ""))}${q("tokenHash") === "\"token_hash\"" ? "" : " - 'token_hash'"}) || ${int8Text(alias, int8)} || jsonb_build_object('lines', ${lines(alias)}${n.extras.length === 0 ? "" : `, 'fields', ${columnsObject(alias, n.extras.map((extra) => extra.name))}`})`;
57562
57637
  const record = (type, alias, extra = "") => ctx.record({
57563
57638
  type,
57564
57639
  payload: `jsonb_build_object('organizationId', ${alias}.${q("tenant")}, 'quoteId', ${alias}.${q("id")}, 'subjectType', 'quote', 'subjectId', ${alias}.${q("id")}::text, 'identifier', ${alias}.${q("identifier")}${extra})`,
@@ -57793,7 +57868,7 @@ begin
57793
57868
  ${fail$1("QUOTE_EMPTY", "a quote needs a line before it is sent", "23514")}
57794
57869
  end if;
57795
57870
  ${ctx.hook("before_quote_send", [["uuid", `v_row.${q("id")}`]])}
57796
- update ${t("quotes")} x set ${q("status")} = 'sent', ${q("sentAt")} = now(), ${q("tokenHash")} = ${sha256Hex$1("v_token")},
57871
+ update ${t("quotes")} x set ${q("status")} = ${sv("sent")}, ${q("sentAt")} = now(), ${q("tokenHash")} = ${sha256Hex$1("v_token")},
57797
57872
  ${q("decidedAt")} = null, ${q("decidedBy")} = null, ${has("decisionNote") ? `${q("decisionNote")} = null, ` : ""}${q("updatedAt")} = now()
57798
57873
  where x.${q("id")} = v_row.${q("id")}
57799
57874
  returning * into v_row;
@@ -57823,7 +57898,7 @@ begin
57823
57898
  if decide_quote.decision not in ('accepted', 'rejected', 'changes_requested') then
57824
57899
  ${fail$1("QUOTE_DECISION_INVALID", "decide accepted, rejected or changes_requested", "22023")}
57825
57900
  end if;
57826
- if v_row.${q("status")} not in ('sent', 'viewed') then
57901
+ if ${st(`v_row.${q("status")}`, ["sent", "viewed"], true)} then
57827
57902
  ${fail$1("QUOTE_NOT_OPEN", "only a sent quote takes a decision", "55000")}
57828
57903
  end if;
57829
57904
  if decide_quote.decision = 'accepted' then
@@ -57853,7 +57928,7 @@ begin
57853
57928
  if v_old.${q("id")} is null then
57854
57929
  ${fail$1("QUOTE_NOT_FOUND", "no such quote you can edit", "P0002")}
57855
57930
  end if;
57856
- if v_old.${q("status")} = 'draft' then
57931
+ if ${st(`v_old.${q("status")}`, ["draft"])} then
57857
57932
  ${fail$1("QUOTE_NOT_SENT", "a draft is edited, not revised", "55000")}
57858
57933
  end if;
57859
57934
  if exists (select 1 from ${t("quotes")} x where x.${q("supersedes")} = v_old.${q("id")}) then
@@ -57909,8 +57984,8 @@ begin
57909
57984
  insert into ${t("lines")} (${lineCopyColumns(ctx, "lines").map(l).join(", ")})
57910
57985
  select ${lineCopyColumns(ctx, "lines").map((column) => column === "parent" ? `v_row.${q("id")}` : `x.${l(column)}`).join(", ")}
57911
57986
  from ${t("lines")} x where x.${l("parent")} = v_old.${q("id")};
57912
- if v_old.${q("status")} <> 'accepted' then
57913
- update ${t("quotes")} x set ${q("status")} = 'withdrawn', ${q("tokenHash")} = null, ${q("updatedAt")} = now() where x.${q("id")} = v_old.${q("id")};
57987
+ if ${st(`v_old.${q("status")}`, ["accepted"], true)} then
57988
+ update ${t("quotes")} x set ${q("status")} = ${sv("withdrawn")}, ${q("tokenHash")} = null, ${q("updatedAt")} = now() where x.${q("id")} = v_old.${q("id")};
57914
57989
  end if;
57915
57990
  ${record("quote.revised", "v_old", `, 'revisionId', v_row.${q("id")}`)}
57916
57991
  return (select ${row("x")} from ${t("quotes")} x where x.${q("id")} = v_row.${q("id")});
@@ -57933,14 +58008,10 @@ begin
57933
58008
  if v_row.${q("id")} is null then
57934
58009
  ${fail$1("QUOTE_LINK_INVALID", "this link is not valid", "P0002")}
57935
58010
  end if;
57936
- if v_row.${q("status")} = 'sent' then
57937
- update ${t("quotes")} x set ${q("status")} = 'viewed'${has("viewedAt") ? `, ${q("viewedAt")} = now()` : ""} where x.${q("id")} = v_row.${q("id")}
57938
- returning * into v_row;
57939
- ${record("quote.viewed", "v_row")}
57940
- end if;
58011
+ ${markViewed()}
57941
58012
  return jsonb_build_object(
57942
58013
  'identifier', v_row.${q("identifier")}, 'revision', v_row.${q("revision")}, 'title', v_row.${q("title")},
57943
- 'status', v_row.${q("status")}, 'currency', v_row.${q("currency")}, 'validUntil', v_row.${q("validUntil")},
58014
+ 'status', ${ctx.label("quotes", "status", `v_row.${q("status")}`)}, 'currency', v_row.${q("currency")}, 'validUntil', v_row.${q("validUntil")},
57944
58015
  'terms', ${or("v_row", "terms")}, 'subtotal', v_row.${q("subtotal")}::text, 'discountTotal', v_row.${q("discountTotal")}::text,
57945
58016
  'taxTotal', v_row.${q("taxTotal")}::text, 'total', v_row.${q("total")}::text, 'lines', ${lines("v_row")});
57946
58017
  end;
@@ -57968,11 +58039,11 @@ begin
57968
58039
  if respond_to_quote.decision not in ('accepted', 'rejected', 'changes_requested') then
57969
58040
  ${fail$1("QUOTE_DECISION_INVALID", "answer accepted, rejected or changes_requested", "22023")}
57970
58041
  end if;
57971
- if v_row.${q("status")} not in ('sent', 'viewed') then
58042
+ if ${st(`v_row.${q("status")}`, ["sent", "viewed"], true)} then
57972
58043
  ${fail$1("QUOTE_NOT_OPEN", "this quote no longer takes an answer", "55000")}
57973
58044
  end if;
57974
58045
  if v_row.${q("validUntil")} < current_date then
57975
- update ${t("quotes")} x set ${q("status")} = 'expired', ${q("updatedAt")} = now() where x.${q("id")} = v_row.${q("id")}
58046
+ update ${t("quotes")} x set ${q("status")} = ${sv("expired")}, ${q("updatedAt")} = now() where x.${q("id")} = v_row.${q("id")}
57976
58047
  returning * into v_row;
57977
58048
  ${record("quote.expired", "v_row")}
57978
58049
  return jsonb_build_object('status', 'expired');
@@ -57986,7 +58057,7 @@ begin
57986
58057
  if respond_to_quote.decision = 'accepted' then
57987
58058
  ${ctx.hook("after_quote_accept", [["uuid", `v_row.${q("id")}`]])}
57988
58059
  end if;
57989
- return jsonb_build_object('status', v_row.${q("status")}, 'identifier', v_row.${q("identifier")});
58060
+ return jsonb_build_object('status', ${ctx.label("quotes", "status", `v_row.${q("status")}`)}, 'identifier', v_row.${q("identifier")});
57990
58061
  end;
57991
58062
  $$;
57992
58063
  revoke all on function ${fn("respond_to_quote")}(text, text, text, text) from public, anon, authenticated;
@@ -58004,8 +58075,8 @@ declare
58004
58075
  v_count integer := 0;
58005
58076
  begin
58006
58077
  for v_row in
58007
- update ${t("quotes")} x set ${q("status")} = 'expired', ${q("updatedAt")} = now()
58008
- where x.${q("status")} in ('sent', 'viewed') and x.${q("validUntil")} < current_date
58078
+ update ${t("quotes")} x set ${q("status")} = ${sv("expired")}, ${q("updatedAt")} = now()
58079
+ where ${st(`x.${q("status")}`, ["sent", "viewed"])} and x.${q("validUntil")} < current_date
58009
58080
  returning *
58010
58081
  loop
58011
58082
  ${record("quote.expired", "v_row")}
@@ -58577,7 +58648,7 @@ function privateSql(ctx, n, reader, load) {
58577
58648
  const address = pairs(ADDRESS_KEYS, alias);
58578
58649
  const contact = pairs(CONTACT_KEYS, alias);
58579
58650
  const parts = [...address === "" || has("address") ? [] : [`'address', nullif(jsonb_strip_nulls(jsonb_build_object(${address})), '{}'::jsonb)`], ...contact === "" || has("emergencyContacts") ? [] : [`'emergency_contacts', case when ${flat.includes("emergencyName") ? `${alias}.${p("emergencyName")} is null` : "true"} then '[]'::jsonb else jsonb_build_array(jsonb_strip_nulls(jsonb_build_object(${contact}))) end`]];
58580
- return parts.length === 0 ? `to_jsonb(${alias})` : `(to_jsonb(${alias}) || jsonb_build_object(${parts.join(", ")}))`;
58651
+ return parts.length === 0 ? ctx.rowJson("privateDetails", alias) : `(${ctx.rowJson("privateDetails", alias)} || jsonb_build_object(${parts.join(", ")}))`;
58581
58652
  };
58582
58653
  const sets = [
58583
58654
  ...DETAILS.filter((detail) => has(detail.column)).map((detail) => {
@@ -58661,7 +58732,9 @@ function contractsSql(ctx, n, reader, load) {
58661
58732
  const currency = has("currency");
58662
58733
  const major = majorSalary(ctx);
58663
58734
  const exponent = (code) => currency ? minorUnits(code) : "2";
58664
- const row = (alias) => salary ? major ? `to_jsonb(${alias}) || jsonb_build_object(${sqlString(k("salary").replaceAll("\"", ""))}, (${alias}.${k("salary")} * power(10, ${exponent(currency ? `${alias}.${k("currency")}` : "null")}))::bigint::text)` : `to_jsonb(${alias}) || ${int8Text(alias, [k("salary")])}` : `to_jsonb(${alias})`;
58735
+ const minorText = (alias, value) => major ? `(${value} * power(10, ${exponent(currency ? `${alias}.${k("currency")}` : "null")}))::bigint::text` : `${value}::text`;
58736
+ const json = (alias) => ctx.rowJson("contracts", alias, { as: { salary: (value) => minorText(alias, value) } });
58737
+ const row = (alias) => salary ? major ? `${json(alias)} || jsonb_build_object(${sqlString(k("salary").replaceAll("\"", ""))}, ${minorText(alias, `${alias}.${k("salary")}`)})` : `${json(alias)} || ${int8Text(alias, [k("salary")])}` : json(alias);
58665
58738
  const salaryValue = (minor, code) => major ? `(${minor})::numeric / power(10, ${exponent(code)})` : `(${minor})::bigint`;
58666
58739
  const arg = (key) => `add_employee_contract.attrs ->> ${sqlString(key)}`;
58667
58740
  const extras = ctx.extraColumns("contracts", [], "contractExtraColumns");
@@ -58691,6 +58764,14 @@ function contractsSql(ctx, n, reader, load) {
58691
58764
  ...has("note") ? [`nullif(trim(${arg("note")}), '')`] : [],
58692
58765
  ...has("createdBy") ? ["auth.uid()"] : []
58693
58766
  ];
58767
+ const insertWith = (skip) => `insert into ${table} (${columns.filter((column) => column !== skip).join(", ")}${required.columns})
58768
+ values (${values.filter((_, index) => columns[index] !== skip).join(", ")}${required.values})
58769
+ returning * into v_row;`;
58770
+ const insert = currency && !ctx.owns("contracts") ? `if add_employee_contract.attrs ? 'currency' then
58771
+ ${insertWith(void 0).replaceAll("\n ", "\n ")}
58772
+ else
58773
+ ${insertWith(k("currency")).replaceAll("\n ", "\n ")}
58774
+ end if;` : insertWith(void 0);
58694
58775
  const updated = ctx.record({
58695
58776
  type: "employee.updated",
58696
58777
  payload: `jsonb_build_object('organizationId', v_employee.${e("tenant")}, 'employeeId', v_employee.${e("id")}, 'subjectType', 'employee', 'subjectId', v_employee.${e("id")}::text, 'name', ${n.name("v_employee")}, 'fields', jsonb_build_array('contract'))`,
@@ -58742,9 +58823,7 @@ begin${load("add_employee_contract", "employee", contractWriter(ctx, n, "v_emplo
58742
58823
  end if;
58743
58824
  update ${table} x set ${k("endsOn")} = v_starts - 1
58744
58825
  where x.${k("employee")} = v_employee.${e("id")} and (x.${k("endsOn")} is null or x.${k("endsOn")} >= v_starts);`}
58745
- insert into ${table} (${columns.join(", ")}${required.columns})
58746
- values (${values.join(", ")}${required.values})
58747
- returning * into v_row;${writeExtraColumns(table, extras, fields, `x.${k("id")} = v_row.${k("id")}`, "v_row").replaceAll("\n ", "\n ")}
58826
+ ${insert}${writeExtraColumns(table, extras, fields, `x.${k("id")} = v_row.${k("id")}`, "v_row").replaceAll("\n ", "\n ")}
58748
58827
  exception when check_violation or not_null_violation or invalid_text_representation or invalid_datetime_format or datetime_field_overflow or numeric_value_out_of_range then
58749
58828
  ${fail$1("EMPLOYEE_CONTRACT_INVALID", "a contract field has an invalid value", "22023")}
58750
58829
  end;
@@ -59280,7 +59359,7 @@ function build$74(ctx) {
59280
59359
  service: "(auth.role() = 'service_role')",
59281
59360
  extras: ctx.extraColumns("employees", RESERVED$7),
59282
59361
  name: fullName,
59283
- json: (alias) => ctx.has("employees", "name") ? `to_jsonb(${alias})` : `(to_jsonb(${alias}) || jsonb_build_object('name', ${fullName(alias)}))`
59362
+ json: (alias) => ctx.has("employees", "name") ? ctx.rowJson("employees", alias) : `(${ctx.rowJson("employees", alias)} || jsonb_build_object('name', ${fullName(alias)}))`
59284
59363
  };
59285
59364
  return `${schemaPreamble(ctx)}
59286
59365
  -- Employees: the people an organization employs, with or without an
@@ -67583,14 +67662,14 @@ function build$63(ctx) {
67583
67662
  const candidateType = (row) => hiringCandidate(ctx, row).type;
67584
67663
  const candidateId = (row) => hiringCandidate(ctx, row).id;
67585
67664
  const candidateValue = (value) => fixedCandidate ? asColumnType(t("applications"), ctx.colName("applications", "candidateId"), value) : value;
67586
- const applicationJson = (alias) => fixedCandidate ? `(to_jsonb(${alias}) || jsonb_build_object('candidate_type', ${sqlString(candidate)}, ${sqlString(ctx.colName("applications", "candidateId"))}, ${alias}.${a("candidateId")}::text))` : `to_jsonb(${alias})`;
67665
+ const applicationJson = (alias) => fixedCandidate ? `(${ctx.rowJson("applications", alias, { as: { candidateId: (value) => `${value}::text` } })} || jsonb_build_object('candidate_type', ${sqlString(candidate)}, ${sqlString(ctx.colName("applications", "candidateId"))}, ${alias}.${a("candidateId")}::text))` : ctx.rowJson("applications", alias);
67587
67666
  const interviewerOf = (row, user) => {
67588
67667
  const checks = [...ctx.has("interviews", "interviewers") ? [`${user} = any (${row}.${v("interviewers")})`] : [], ...interviewerRows ? [`exists (select 1 from ${t("interviewers")} z where z.${iv("interview")} = ${row}.${v("id")} and z.${iv("user")} = ${user})`] : []];
67589
67668
  if (checks.length <= 1) return checks[0];
67590
67669
  return `(${checks.join(" or ")})`;
67591
67670
  };
67592
- const interviewJson = (alias) => interviewerRows ? `(to_jsonb(${alias}) || jsonb_build_object('interviewer_user_ids', (select coalesce(jsonb_agg(z.${iv("user")} order by z.${iv("user")}), '[]'::jsonb) from ${t("interviewers")} z where z.${iv("interview")} = ${alias}.${v("id")})))` : `to_jsonb(${alias})`;
67593
- const scorecardJson = (alias) => scoreRows ? `(to_jsonb(${alias}) || jsonb_build_object('scores', (select coalesce(jsonb_agg(jsonb_build_object('criterion', y.${sc("criterion")}, 'score', y.${sc("score")}, 'notes', ${ctx.has("scorecardScores", "notes") ? `y.${sc("notes")}` : "null"}) order by y.${sc("criterion")}), '[]'::jsonb) from ${t("scorecardScores")} y where y.${sc("scorecard")} = ${alias}.${s("id")})))` : `to_jsonb(${alias})`;
67671
+ const interviewJson = (alias) => interviewerRows ? `(${ctx.rowJson("interviews", alias)} || jsonb_build_object('interviewer_user_ids', (select coalesce(jsonb_agg(z.${iv("user")} order by z.${iv("user")}), '[]'::jsonb) from ${t("interviewers")} z where z.${iv("interview")} = ${alias}.${v("id")})))` : ctx.rowJson("interviews", alias);
67672
+ const scorecardJson = (alias) => scoreRows ? `(${ctx.rowJson("scorecards", alias)} || jsonb_build_object('scores', (select coalesce(jsonb_agg(jsonb_build_object('criterion', y.${sc("criterion")}, 'score', y.${sc("score")}, 'notes', ${ctx.has("scorecardScores", "notes") ? `y.${sc("notes")}` : "null"}) order by y.${sc("criterion")}), '[]'::jsonb) from ${t("scorecardScores")} y where y.${sc("scorecard")} = ${alias}.${s("id")})))` : ctx.rowJson("scorecards", alias);
67594
67673
  const managerValue = managerEmployee && ctx.has("jobs", "hiringManager") ? asColumnType(t("jobs"), ctx.colName("jobs", "hiringManager"), "save_job.attrs ->> 'hiringManagerId'") : "(save_job.attrs ->> 'hiringManagerId')::uuid";
67595
67674
  const column = (table, logical, type) => ctx.has(table, logical) ? `\n ${ctx.col(table, logical)} ${type},` : "";
67596
67675
  const or = (table, row, logical) => ctx.has(table, logical) ? `${row}.${ctx.col(table, logical)}` : "null";
@@ -67818,7 +67897,7 @@ begin
67818
67897
  ${jobRecord("job.closed")}
67819
67898
  end if;
67820
67899
  end if;
67821
- return ${withExtraFields("to_jsonb(v_job)", "v_job", extras)};
67900
+ return ${withExtraFields(ctx.rowJson("jobs", "v_job"), "v_job", extras)};
67822
67901
  end;
67823
67902
  $$;
67824
67903
  ${userGrant(`${fn("save_job")}(${ctx.idType}, uuid, jsonb)`)}
@@ -73666,7 +73745,7 @@ function transferFunctions(ctx, names) {
73666
73745
  const t = columns$1(ctx, "transfers");
73667
73746
  const tl = columns$1(ctx, "transferLines");
73668
73747
  const l = locationsOf(ctx).col;
73669
- const load = (name) => `select x.${t("tenant")} as tenant, x.${t("from")} as from_location, x.${t("to")} as to_location, x.${t("status")} as status
73748
+ const load = (name) => `select x.${t("tenant")} as tenant, x.${t("from")} as from_location, x.${t("to")} as to_location, ${ctx.label("transfers", "status", `x.${t("status")}`)} as status
73670
73749
  into v_row from ${transfers} x where x.${t("id")} = ${name}.transfer for update;
73671
73750
  if not found then
73672
73751
  ${fail$1("INVENTORY_TRANSFER_NOT_FOUND", "transfer not found", "P0002")}
@@ -73737,7 +73816,7 @@ begin
73737
73816
  ${statusError}
73738
73817
  end if;
73739
73818
  ${move("ship_transfer", "v_row.from_location", "-", "transfer_out")}
73740
- update ${transfers} x set ${t("status")} = 'in_transit', ${t("shippedAt")} = now() where x.${t("id")} = ship_transfer.transfer;
73819
+ update ${transfers} x set ${t("status")} = ${ctx.value("transfers", "status", "in_transit")}, ${t("shippedAt")} = now() where x.${t("id")} = ship_transfer.transfer;
73741
73820
  ${event("transfer.shipped", "ship_transfer", "'in_transit'")}
73742
73821
  return true;
73743
73822
  end;
@@ -73759,7 +73838,7 @@ begin
73759
73838
  ${statusError}
73760
73839
  end if;
73761
73840
  ${move("receive_transfer", "v_row.to_location", "", "transfer_in")}
73762
- update ${transfers} x set ${t("status")} = 'received', ${t("receivedAt")} = now() where x.${t("id")} = receive_transfer.transfer;
73841
+ update ${transfers} x set ${t("status")} = ${ctx.value("transfers", "status", "received")}, ${t("receivedAt")} = now() where x.${t("id")} = receive_transfer.transfer;
73763
73842
  ${event("transfer.received", "receive_transfer", "'received'")}
73764
73843
  return true;
73765
73844
  end;
@@ -73783,7 +73862,7 @@ begin
73783
73862
  if v_row.status = 'in_transit' then
73784
73863
  ${move("cancel_transfer", "v_row.from_location", "", "transfer_in")}
73785
73864
  end if;
73786
- update ${transfers} x set ${t("status")} = 'cancelled' where x.${t("id")} = cancel_transfer.transfer;
73865
+ update ${transfers} x set ${t("status")} = ${ctx.value("transfers", "status", "cancelled")} where x.${t("id")} = cancel_transfer.transfer;
73787
73866
  ${event("transfer.cancelled", "cancel_transfer", "'cancelled'")}
73788
73867
  return true;
73789
73868
  end;
@@ -73803,7 +73882,7 @@ function purchaseOrderFunctions(ctx, names) {
73803
73882
  const lv = columns$1(ctx, "levels");
73804
73883
  const l = locationsOf(ctx).col;
73805
73884
  const currencyUnits = ctx.of("catalog").fn("currency_minor_units");
73806
- const load = (name) => `select x.${po("tenant")} as tenant, x.${po("location")} as location, x.${po("status")} as status,
73885
+ const load = (name) => `select x.${po("tenant")} as tenant, x.${po("location")} as location, ${ctx.label("purchaseOrders", "status", `x.${po("status")}`)} as status,
73807
73886
  x.${po("supplierType")} as supplier_type, x.${po("supplierId")} as supplier_id
73808
73887
  into v_row from ${orders} x where x.${po("id")} = ${name}.purchase_order for update;
73809
73888
  if not found then
@@ -73856,7 +73935,7 @@ begin
73856
73935
  update ${orders} x set ${po("location")} = save_purchase_order.location, ${po("supplierType")} = save_purchase_order.supplier_type,
73857
73936
  ${po("supplierId")} = save_purchase_order.supplier_id, ${po("currency")} = save_purchase_order.currency,
73858
73937
  ${po("expectedAt")} = save_purchase_order.expected_at, ${po("note")} = save_purchase_order.note, ${po("updatedAt")} = now()
73859
- where x.${po("id")} = v_id and x.${po("status")} = 'draft';
73938
+ where x.${po("id")} = v_id and ${ctx.is("purchaseOrders", "status", `x.${po("status")}`, ["draft"])};
73860
73939
  if not found then
73861
73940
  ${fail$1("INVENTORY_PURCHASE_ORDER_LOCKED", "only a draft purchase order can change", "55000")}
73862
73941
  end if;
@@ -73889,7 +73968,7 @@ begin
73889
73968
  from ${lines} y where y.${pl("order")} = place_purchase_order.purchase_order
73890
73969
  on conflict (${lv("variant")}, ${lv("location")}) do update
73891
73970
  set ${lv("incoming")} = x.${lv("incoming")} + excluded.${lv("incoming")}, ${lv("updatedAt")} = now();
73892
- update ${orders} x set ${po("status")} = 'ordered', ${po("placedAt")} = now(), ${po("updatedAt")} = now()
73971
+ update ${orders} x set ${po("status")} = ${ctx.value("purchaseOrders", "status", "ordered")}, ${po("placedAt")} = now(), ${po("updatedAt")} = now()
73893
73972
  where x.${po("id")} = place_purchase_order.purchase_order;
73894
73973
  ${event("purchase_order.placed", "place_purchase_order", "'ordered'")}
73895
73974
  return true;
@@ -73975,7 +74054,7 @@ begin
73975
74054
  where y.${pl("order")} = cancel_purchase_order.purchase_order
73976
74055
  and x.${lv("variant")} = y.${pl("variant")} and x.${lv("location")} = v_row.location;
73977
74056
  end if;
73978
- update ${orders} x set ${po("status")} = 'cancelled', ${po("updatedAt")} = now()
74057
+ update ${orders} x set ${po("status")} = ${ctx.value("purchaseOrders", "status", "cancelled")}, ${po("updatedAt")} = now()
73979
74058
  where x.${po("id")} = cancel_purchase_order.purchase_order;
73980
74059
  ${event("purchase_order.cancelled", "cancel_purchase_order", "'cancelled'")}
73981
74060
  return true;
@@ -74137,7 +74216,8 @@ const NAMES$60 = {
74137
74216
  expiresAt: "expires_at",
74138
74217
  createdAt: "created_at",
74139
74218
  updatedAt: "updated_at"
74140
- }
74219
+ },
74220
+ typed: ["status"]
74141
74221
  },
74142
74222
  transfers: {
74143
74223
  name: "stock_transfers",
@@ -74154,7 +74234,8 @@ const NAMES$60 = {
74154
74234
  createdAt: "created_at",
74155
74235
  shippedAt: "shipped_at",
74156
74236
  receivedAt: "received_at"
74157
- }
74237
+ },
74238
+ typed: ["status"]
74158
74239
  },
74159
74240
  transferLines: {
74160
74241
  name: "stock_transfer_lines",
@@ -78079,6 +78160,8 @@ function invoiceFunctions(ctx, n) {
78079
78160
  ${fail$1(`INVOICE_${thing}_UNSUPPORTED`, `this invoices table has no ${what}`, "22023")}
78080
78161
  end if;`;
78081
78162
  const can = (alias, permission) => `(${n.service} or ${ctx.scope.can(`${alias}.${i("tenant")}`, permission)})`;
78163
+ const st = (value, labels, negate = false) => ctx.is("invoices", "status", value, labels, negate);
78164
+ const kd = (value, labels, negate = false) => ctx.is("invoices", "kind", value, labels, negate);
78082
78165
  const balance = (alias) => `(${alias}.${i("total")} - ${alias}.${i("creditedTotal")} - ${alias}.${i("paidTotal")})`;
78083
78166
  const int8 = [
78084
78167
  "number",
@@ -78086,9 +78169,15 @@ function invoiceFunctions(ctx, n) {
78086
78169
  "creditedTotal",
78087
78170
  ...Object.keys(TOTAL_COLUMNS)
78088
78171
  ].map(i);
78089
- const row = (alias) => `to_jsonb(${alias}) || ${int8Text(alias, int8)} || jsonb_build_object(
78172
+ const int8Text8 = Object.fromEntries([
78173
+ "number",
78174
+ "paidTotal",
78175
+ "creditedTotal",
78176
+ ...Object.keys(TOTAL_COLUMNS)
78177
+ ].map((logical) => [logical, (value) => `${value}::text`]));
78178
+ const row = (alias) => `${ctx.rowJson("invoices", alias, { as: int8Text8 })} || ${int8Text(alias, int8)} || jsonb_build_object(
78090
78179
  'balance', ${balance(alias)}::text,
78091
- 'overdue', ${alias}.${i("status")} in ('issued', 'partially_paid') and ${alias}.${i("dueOn")} < current_date,
78180
+ 'overdue', ${st(`${alias}.${i("status")}`, ["issued", "partially_paid"])} and ${alias}.${i("dueOn")} < current_date,
78092
78181
  'lines', coalesce((select jsonb_agg(jsonb_build_object('description', il.${l("description")}, 'quantity', il.${l("quantity")}, 'unitAmount', il.${l("unitAmount")}::text, 'discountBps', ${lineColumn(ctx, "lines", "il", "discountBps")}, 'taxRateBps', ${lineColumn(ctx, "lines", "il", "taxRateBps")}, 'taxCode', ${lineColumn(ctx, "lines", "il", "taxCode")}${lineFieldsJson("il", n.lineExtras)}) order by il.${l("position")}) from ${t("lines")} il where il.${l("parent")} = ${alias}.${i("id")}), '[]'::jsonb),
78093
78182
  'payments', ${ledger.payments(alias)})`;
78094
78183
  const record = (type, alias, extra = "", audit = false) => ctx.record({
@@ -78120,7 +78209,11 @@ function invoiceFunctions(ctx, n) {
78120
78209
  when x.${i("paidTotal")} > 0 or x.${i("creditedTotal")} > 0 then 'partially_paid'
78121
78210
  else 'issued' end`)},
78122
78211
  ${i("paidAt")} = case when ${balance("x")} <= 0 then coalesce(x.${i("paidAt")}, now()) end
78123
- where x.${i("id")} = ${alias}.${i("id")} and x.${i("status")} in ('issued', 'partially_paid', 'paid')
78212
+ where x.${i("id")} = ${alias}.${i("id")} and ${st(`x.${i("status")}`, [
78213
+ "issued",
78214
+ "partially_paid",
78215
+ "paid"
78216
+ ])}
78124
78217
  returning * into ${alias};`;
78125
78218
  const quotes = ctx.installed("quotes") ? ctx.of("quotes") : void 0;
78126
78219
  const fromQuote = quotes === void 0 ? "" : (() => {
@@ -78132,7 +78225,7 @@ function invoiceFunctions(ctx, n) {
78132
78225
  if invoice_from_quote.deposit_bps is null then
78133
78226
  select * into v_row from ${t("invoices")} x
78134
78227
  where x.${i("originType")} = 'quote' and x.${i("originId")} = v_quote.${q("id")}::text
78135
- and ${deposits ? `x.${i("depositBps")} is null and ` : ""}x.${i("status")} <> 'void' and x.${i("kind")} = 'invoice'
78228
+ and ${deposits ? `x.${i("depositBps")} is null and ` : ""}${st(`x.${i("status")}`, ["void"], true)} and ${kd(`x.${i("kind")}`, ["invoice"])}
78136
78229
  limit 1;
78137
78230
  if v_row.${i("id")} is not null then
78138
78231
  return ${row("v_row")};
@@ -78146,7 +78239,7 @@ function invoiceFunctions(ctx, n) {
78146
78239
  'taxRateBps', case when d.${i("subtotal")} = 0 then 0 else round(d.${i("taxTotal")} * 10000.0 / d.${i("subtotal")})::integer end)), '[]'::jsonb)
78147
78240
  into v_lines
78148
78241
  from ${t("invoices")} d
78149
- where d.${i("originType")} = 'quote' and d.${i("originId")} = v_quote.${q("id")}::text and d.${i("depositBps")} is not null and d.${i("status")} not in ('draft', 'void');` : ""}
78242
+ where d.${i("originType")} = 'quote' and d.${i("originId")} = v_quote.${q("id")}::text and d.${i("depositBps")} is not null and ${st(`d.${i("status")}`, ["draft", "void"], true)};` : ""}
78150
78243
  else
78151
78244
  v_lines := jsonb_build_array(jsonb_build_object(
78152
78245
  'description', 'Deposit ' || (invoice_from_quote.deposit_bps / 100.0)::text || '% of ' || v_quote.${q("identifier")},
@@ -78179,7 +78272,7 @@ begin
78179
78272
  if v_quote.${q("id")} is null or not (${n.service} or ${ctx.scope.can(`v_quote.${q("tenant")}`, n.write)}) then
78180
78273
  ${fail$1("INVOICE_ORIGIN_NOT_FOUND", "no such quote you can invoice", "P0002")}
78181
78274
  end if;
78182
- if v_quote.${q("status")} <> 'accepted' then
78275
+ if ${quotes.is("quotes", "status", `v_quote.${q("status")}`, ["accepted"], true)} then
78183
78276
  ${fail$1("INVOICE_QUOTE_NOT_ACCEPTED", "only an accepted quote is invoiced", "55000")}
78184
78277
  end if;
78185
78278
  if invoice_from_quote.deposit_bps is not null and (invoice_from_quote.deposit_bps <= 0 or invoice_from_quote.deposit_bps >= 10000) then
@@ -78191,7 +78284,7 @@ $$;
78191
78284
  ${userGrant(`${fn("invoice_from_quote")}(uuid, integer)`)}
78192
78285
  `;
78193
78286
  })();
78194
- const kindTable = (kind) => `(select * from ${t("invoices")} k where k.${i("kind")} = ${kind})`;
78287
+ const kindTable = (kind) => `(select * from ${t("invoices")} k where ${kd(`k.${i("kind")}`, [kind])})`;
78195
78288
  return `
78196
78289
  -- Creates a draft invoice. attrs: title (required), currency, company and
78197
78290
  -- contact ({ type, id }), termsDays, note, origin ({ type, id }) and the
@@ -78247,7 +78340,7 @@ ${userGrant(`${fn("create_invoice")}(${ctx.idType}, jsonb, jsonb)`)}
78247
78340
  ${lineItemsSql(ctx, {
78248
78341
  lines: "lines",
78249
78342
  parent: "invoices",
78250
- frozen: `p.${i("status")} <> 'draft'`,
78343
+ frozen: st(`p.${i("status")}`, ["draft"], true),
78251
78344
  extras: n.lineExtras
78252
78345
  }, {
78253
78346
  setter: "set_invoice_lines",
@@ -78274,14 +78367,14 @@ begin
78274
78367
  if v_row.${i("id")} is null then
78275
78368
  ${fail$1("INVOICE_NOT_FOUND", "no such invoice you can edit", "P0002")}
78276
78369
  end if;
78277
- if v_row.${i("status")} <> 'draft' then
78370
+ if ${st(`v_row.${i("status")}`, ["draft"], true)} then
78278
78371
  ${fail$1("INVOICE_NOT_DRAFT", "the invoice was already issued", "55000")}
78279
78372
  end if;
78280
78373
  if not exists (select 1 from ${t("lines")} x where x.${l("parent")} = v_row.${i("id")}) then
78281
78374
  ${fail$1("INVOICE_EMPTY", "an invoice needs a line before it is issued", "23514")}
78282
78375
  end if;
78283
78376
  ${ctx.hook("before_invoice_issue", [["uuid", `v_row.${i("id")}`]])}
78284
- if v_row.${i("kind")} = 'credit_note' then
78377
+ if ${kd(`v_row.${i("kind")}`, ["credit_note"])} then
78285
78378
  select * into v_original from ${t("invoices")} x where x.${i("id")} = v_row.${i("original")} for update;
78286
78379
  if v_row.${i("total")} > ${balance("v_original")} then
78287
78380
  ${fail$1("INVOICE_CREDIT_TOO_LARGE", "a credit note can't exceed what is still owed", "23514")}
@@ -78290,7 +78383,7 @@ begin
78290
78383
  seq: "v_seq",
78291
78384
  identifier: "v_identifier"
78292
78385
  }, {
78293
- table: kindTable("'credit_note'"),
78386
+ table: kindTable("credit_note"),
78294
78387
  seq: i("number"),
78295
78388
  tenant: i("tenant"),
78296
78389
  prefix: n.creditPrefix
@@ -78300,25 +78393,25 @@ begin
78300
78393
  seq: "v_seq",
78301
78394
  identifier: "v_identifier"
78302
78395
  }, {
78303
- table: kindTable("'invoice'"),
78396
+ table: kindTable("invoice"),
78304
78397
  seq: i("number"),
78305
78398
  tenant: i("tenant"),
78306
78399
  prefix: n.prefix
78307
78400
  })}
78308
78401
  end if;
78309
- update ${t("invoices")} x set ${i("status")} = 'issued', ${i("number")} = v_seq, ${i("identifier")} = v_identifier,
78402
+ update ${t("invoices")} x set ${i("status")} = ${ctx.value("invoices", "status", "issued")}, ${i("number")} = v_seq, ${i("identifier")} = v_identifier,
78310
78403
  ${i("issuedOn")} = coalesce(issue_invoice.issued_on, current_date),
78311
78404
  ${i("dueOn")} = coalesce(issue_invoice.issued_on, current_date) + x.${i("termsDays")},
78312
78405
  ${i("updatedAt")} = now()
78313
78406
  where x.${i("id")} = v_row.${i("id")}
78314
78407
  returning * into v_row;
78315
78408
  ${record("invoice.issued", "v_row", `, 'total', v_row.${i("total")}::text, 'currency', v_row.${i("currency")}, 'dueOn', v_row.${i("dueOn")}`)}
78316
- if v_row.${i("kind")} = 'credit_note' then
78409
+ if ${kd(`v_row.${i("kind")}`, ["credit_note"])} then
78317
78410
  update ${t("invoices")} x set ${i("creditedTotal")} = x.${i("creditedTotal")} + v_row.${i("total")}, ${i("updatedAt")} = now()
78318
78411
  where x.${i("id")} = v_original.${i("id")}
78319
78412
  returning * into v_original;${settle("v_original")}
78320
78413
  ${record("invoice.credited", "v_original", `, 'creditNoteId', v_row.${i("id")}, 'amount', v_row.${i("total")}::text`)}
78321
- if v_original.${i("status")} = 'paid' then
78414
+ if ${st(`v_original.${i("status")}`, ["paid"])} then
78322
78415
  ${record("invoice.paid", "v_original", `, 'total', v_original.${i("total")}::text`)}
78323
78416
  end if;
78324
78417
  end if;
@@ -78349,7 +78442,11 @@ begin
78349
78442
  if v_row.${i("id")} is null then
78350
78443
  ${fail$1("INVOICE_NOT_FOUND", "no such invoice you can edit", "P0002")}
78351
78444
  end if;
78352
- if v_row.${i("kind")} <> 'invoice' or v_row.${i("status")} not in ('issued', 'partially_paid', 'paid') then
78445
+ if ${kd(`v_row.${i("kind")}`, ["invoice"], true)} or ${st(`v_row.${i("status")}`, [
78446
+ "issued",
78447
+ "partially_paid",
78448
+ "paid"
78449
+ ], true)} then
78353
78450
  ${fail$1("INVOICE_NOT_PAYABLE", "only an issued invoice takes payments", "55000")}
78354
78451
  end if;
78355
78452
  if coalesce(record_invoice_payment.amount, 0) = 0 then
@@ -78373,7 +78470,7 @@ begin
78373
78470
  v_was := v_row.${i("status")};
78374
78471
  v_payment := ${ledger.post("v_row", "record_invoice_payment.amount", "coalesce(record_invoice_payment.paid_at, now())", "record_invoice_payment.method", "v_reference")};${settle("v_row")}
78375
78472
  ${record("invoice.payment_recorded", "v_row", `, 'paymentId', v_payment, 'amount', record_invoice_payment.amount::text, 'balance', ${balance("v_row")}::text`)}
78376
- if v_row.${i("status")} = 'paid' and v_was <> 'paid' then
78473
+ if ${st(`v_row.${i("status")}`, ["paid"])} and ${st("v_was", ["paid"], true)} then
78377
78474
  ${record("invoice.paid", "v_row", `, 'total', v_row.${i("total")}::text`)}
78378
78475
  end if;
78379
78476
  ${ctx.hook("after_invoice_payment", [["uuid", `v_row.${i("id")}`], ["uuid", "v_payment"]])}
@@ -78398,7 +78495,11 @@ begin
78398
78495
  if v_original.${i("id")} is null then
78399
78496
  ${fail$1("INVOICE_NOT_FOUND", "no such invoice you can edit", "P0002")}
78400
78497
  end if;
78401
- if v_original.${i("kind")} <> 'invoice' or v_original.${i("status")} not in ('issued', 'partially_paid', 'paid') then
78498
+ if ${kd(`v_original.${i("kind")}`, ["invoice"], true)} or ${st(`v_original.${i("status")}`, [
78499
+ "issued",
78500
+ "partially_paid",
78501
+ "paid"
78502
+ ], true)} then
78402
78503
  ${fail$1("INVOICE_NOT_CREDITABLE", "only an issued invoice is credited", "55000")}
78403
78504
  end if;
78404
78505
  insert into ${t("invoices")} (${valueLines(" ", [
@@ -78418,7 +78519,7 @@ begin
78418
78519
  ])})
78419
78520
  values (${valueLines(" ", [
78420
78521
  `v_original.${i("tenant")}`,
78421
- "'credit_note'",
78522
+ ctx.value("invoices", "kind", "credit_note"),
78422
78523
  `v_original.${i("id")}`,
78423
78524
  `'Credit for ' || coalesce(v_original.${i("identifier")}, v_original.${i("title")})`
78424
78525
  ], [
@@ -78461,10 +78562,10 @@ begin
78461
78562
  if v_row.${i("id")} is null then
78462
78563
  ${fail$1("INVOICE_NOT_FOUND", "no such invoice you can manage", "P0002")}
78463
78564
  end if;
78464
- if v_row.${i("status")} not in ('draft', 'issued') or v_row.${i("paidTotal")} <> 0 or v_row.${i("creditedTotal")} <> 0 then
78565
+ if ${st(`v_row.${i("status")}`, ["draft", "issued"], true)} or v_row.${i("paidTotal")} <> 0 or v_row.${i("creditedTotal")} <> 0 then
78465
78566
  ${fail$1("INVOICE_NOT_VOIDABLE", "an invoice with payments or credits is credited, not voided", "55000")}
78466
78567
  end if;
78467
- update ${t("invoices")} x set ${i("status")} = 'void', ${i("voidedAt")} = now(),
78568
+ update ${t("invoices")} x set ${i("status")} = ${ctx.value("invoices", "status", "void")}, ${i("voidedAt")} = now(),
78468
78569
  ${has("voidReason") ? `${i("voidReason")} = nullif(trim(void_invoice.reason), ''), ` : ""}${i("updatedAt")} = now()
78469
78570
  where x.${i("id")} = v_row.${i("id")} returning * into v_row;
78470
78571
  ${record("invoice.voided", "v_row", `, 'reason', ${has("voidReason") ? `v_row.${i("voidReason")}` : "nullif(trim(void_invoice.reason), '')"}`, true)}
@@ -78483,8 +78584,8 @@ as $$
78483
78584
  declare
78484
78585
  v_row ${t("invoices")};
78485
78586
  begin
78486
- update ${t("invoices")} x set ${i("status")} = 'uncollectible', ${i("updatedAt")} = now()
78487
- where x.${i("id")} = write_off_invoice.invoice and ${can("x", n.manage)} and x.${i("status")} in ('issued', 'partially_paid')
78587
+ update ${t("invoices")} x set ${i("status")} = ${ctx.value("invoices", "status", "uncollectible")}, ${i("updatedAt")} = now()
78588
+ where x.${i("id")} = write_off_invoice.invoice and ${can("x", n.manage)} and ${st(`x.${i("status")}`, ["issued", "partially_paid"])}
78488
78589
  returning * into v_row;
78489
78590
  if v_row.${i("id")} is null then
78490
78591
  ${fail$1("INVOICE_NOT_OPEN", "only an open invoice you can manage is written off", "55000")}
@@ -78508,7 +78609,7 @@ as $$
78508
78609
  select ${balance("x")} as balance, coalesce(invoice_aging.as_of, current_date) - x.${i("dueOn")} as late
78509
78610
  from ${t("invoices")} x
78510
78611
  where x.${i("tenant")} = invoice_aging.tenant and x.${i("currency")} = upper(invoice_aging.currency)
78511
- and x.${i("kind")} = 'invoice' and x.${i("status")} in ('issued', 'partially_paid')
78612
+ and ${kd(`x.${i("kind")}`, ["invoice"])} and ${st(`x.${i("status")}`, ["issued", "partially_paid"])}
78512
78613
  )
78513
78614
  select jsonb_build_object(
78514
78615
  'currency', upper(invoice_aging.currency),
@@ -92114,7 +92215,7 @@ as $$
92114
92215
  declare
92115
92216
  v_from text;
92116
92217
  begin
92117
- select x.${o("status")} into v_from from ${ctx.table("orders")} x where x.${o("id")} = p_order for update;
92218
+ select ${ctx.label("orders", "status", `x.${o("status")}`)} into v_from from ${ctx.table("orders")} x where x.${o("id")} = p_order for update;
92118
92219
  if v_from = p_to then
92119
92220
  return v_from;
92120
92221
  end if;${governed ? "" : `
@@ -92165,7 +92266,7 @@ function orderFields(ctx, alias) {
92165
92266
  ["tax_inclusive", "taxInclusive"],
92166
92267
  ["invoice_number", "invoiceNumber"],
92167
92268
  ["placed_at", "placedAt"]
92168
- ].map(([as, column]) => `${alias}.${o(column ?? "")} as ${as}`).join(", ");
92269
+ ].map(([as, column]) => column === "status" ? `${ctx.label("orders", "status", `${alias}.${o(column)}`)} as ${as}` : `${alias}.${o(column ?? "")} as ${as}`).join(", ");
92169
92270
  }
92170
92271
  //#endregion
92171
92272
  //#region src/sql/modules/orders-after-sale.ts
@@ -92237,13 +92338,13 @@ function afterSaleFunctions(ctx, names) {
92237
92338
  tenant: "v_order.tenant",
92238
92339
  audit: false
92239
92340
  });
92240
- const loadFulfillment = (id) => `select x.${f("id")} as id, x.${f("order")} as order_id, x.${f("status")} as status into v_fulfillment
92341
+ const loadFulfillment = (id) => `select x.${f("id")} as id, x.${f("order")} as order_id, ${ctx.label("fulfillments", "status", `x.${f("status")}`)} as status into v_fulfillment
92241
92342
  from ${fulfillments} x where x.${f("id")} = ${id} for update;
92242
92343
  if not found then
92243
92344
  ${fail$1("ORDERS_FULFILLMENT_NOT_FOUND", "fulfillment not found", "P0002")}
92244
92345
  end if;
92245
92346
  ${load("v_fulfillment.order_id")}`;
92246
- const loadReturn = (id) => `select x.${r("id")} as id, x.${r("order")} as order_id, x.${r("status")} as status into v_return
92347
+ const loadReturn = (id) => `select x.${r("id")} as id, x.${r("order")} as order_id, ${ctx.label("returns", "status", `x.${r("status")}`)} as status into v_return
92247
92348
  from ${returns} x where x.${r("id")} = ${id} for update;
92248
92349
  if not found then
92249
92350
  ${fail$1("ORDERS_RETURN_NOT_FOUND", "return not found", "P0002")}
@@ -92323,7 +92424,7 @@ begin
92323
92424
  if v_fulfillment.status <> 'pending' then
92324
92425
  ${fail$1("ORDERS_TRANSITION_INVALID", "only a pending fulfillment can ship", "55000")}
92325
92426
  end if;${unsupported(trackingUrl, "ship_fulfillment.tracking_url", "ORDERS_TRACKING_URL_UNSUPPORTED", "this fulfillment table has no tracking URL column")}
92326
- update ${fulfillments} x set ${f("status")} = 'shipped', ${f("shippedAt")} = now(),
92427
+ update ${fulfillments} x set ${f("status")} = ${ctx.value("fulfillments", "status", "shipped")}, ${f("shippedAt")} = now(),
92327
92428
  ${f("carrier")} = coalesce(ship_fulfillment.carrier, x.${f("carrier")}),
92328
92429
  ${f("trackingNumber")} = coalesce(ship_fulfillment.tracking_number, x.${f("trackingNumber")})${trackingUrl ? `,
92329
92430
  ${f("trackingUrl")} = coalesce(ship_fulfillment.tracking_url, x.${f("trackingUrl")})` : ""}
@@ -92331,7 +92432,7 @@ begin
92331
92432
  ${partEvent("fulfillment.shipped", "v_fulfillment.id", [["carrier", `(select x.${f("carrier")} from ${fulfillments} x where x.${f("id")} = v_fulfillment.id)`], ["trackingNumber", `(select x.${f("trackingNumber")} from ${fulfillments} x where x.${f("id")} = v_fulfillment.id)`]])}
92332
92433
  if v_order.status = 'paid'
92333
92434
  and not exists (select 1 from ${lines} l where l.${ol("order")} = v_order.id and l.${ol("fulfilled")} < l.${ol("quantity")})
92334
- and not exists (select 1 from ${fulfillments} x where x.${f("order")} = v_order.id and x.${f("status")} = 'pending') then
92435
+ and not exists (select 1 from ${fulfillments} x where x.${f("order")} = v_order.id and ${ctx.is("fulfillments", "status", `x.${f("status")}`, ["pending"])}) then
92335
92436
  perform ${fn("order_transition")}(v_order.id, 'fulfilled');
92336
92437
  ${event("order.fulfilled", [])}
92337
92438
  end if;
@@ -92360,10 +92461,10 @@ begin
92360
92461
  if v_fulfillment.status <> 'shipped' then
92361
92462
  ${fail$1("ORDERS_TRANSITION_INVALID", "only a shipped fulfillment can be delivered", "55000")}
92362
92463
  end if;
92363
- update ${fulfillments} x set ${f("status")} = 'delivered', ${f("deliveredAt")} = now() where x.${f("id")} = v_fulfillment.id;
92464
+ update ${fulfillments} x set ${f("status")} = ${ctx.value("fulfillments", "status", "delivered")}, ${f("deliveredAt")} = now() where x.${f("id")} = v_fulfillment.id;
92364
92465
  ${partEvent("fulfillment.delivered", "v_fulfillment.id", [])}
92365
92466
  if v_order.status = 'fulfilled'
92366
- and not exists (select 1 from ${fulfillments} x where x.${f("order")} = v_order.id and x.${f("status")} in ('pending', 'shipped')) then
92467
+ and not exists (select 1 from ${fulfillments} x where x.${f("order")} = v_order.id and ${ctx.is("fulfillments", "status", `x.${f("status")}`, ["pending", "shipped"])}) then
92367
92468
  perform ${fn("order_transition")}(v_order.id, 'completed');
92368
92469
  ${event("order.completed", [])}
92369
92470
  end if;
@@ -92394,7 +92495,7 @@ begin
92394
92495
  update ${lines} x set ${ol("fulfilled")} = x.${ol("fulfilled")} - y.${fl("quantity")}
92395
92496
  from ${fulfillmentLines} y
92396
92497
  where y.${fl("fulfillment")} = v_fulfillment.id and x.${ol("id")} = y.${fl("line")};
92397
- update ${fulfillments} x set ${f("status")} = 'cancelled' where x.${f("id")} = v_fulfillment.id;
92498
+ update ${fulfillments} x set ${f("status")} = ${ctx.value("fulfillments", "status", "cancelled")} where x.${f("id")} = v_fulfillment.id;
92398
92499
  return true;
92399
92500
  end;
92400
92501
  $$;
@@ -92436,7 +92537,7 @@ begin
92436
92537
  end if;
92437
92538
  select coalesce(sum(y.${rl("quantity")}), 0) into v_open
92438
92539
  from ${returnLines} y join ${returns} z on z.${r("id")} = y.${rl("return")}
92439
- where y.${rl("line")} = v_item.line and z.${r("status")} = 'requested';
92540
+ where y.${rl("line")} = v_item.line and ${ctx.is("returns", "status", `z.${r("status")}`, ["requested"])};
92440
92541
  if not exists (select 1 from ${lines} l where l.${ol("id")} = v_item.line and l.${ol("order")} = v_order.id
92441
92542
  and l.${ol("fulfilled")} - l.${ol("returned")} - v_open >= v_item.quantity) then
92442
92543
  ${fail$1("ORDERS_RETURN_INVALID", "a line isn't on this order or has fewer fulfilled units left to return", "22023")}
@@ -92482,7 +92583,7 @@ begin
92482
92583
  update ${lines} x set ${ol("returned")} = x.${ol("returned")} + v_line.quantity where x.${ol("id")} = v_line.line;${restock(ctx)}
92483
92584
  v_units := v_units + v_line.quantity;
92484
92585
  end loop;
92485
- update ${returns} x set ${r("status")} = 'received', ${r("receivedAt")} = now() where x.${r("id")} = v_return.id;
92586
+ update ${returns} x set ${r("status")} = ${ctx.value("returns", "status", "received")}, ${r("receivedAt")} = now() where x.${r("id")} = v_return.id;
92486
92587
  ${partEvent("return.received", "v_return.id", [["quantity", "v_units::text"]])}
92487
92588
  return true;
92488
92589
  end;
@@ -92504,7 +92605,7 @@ begin
92504
92605
  if v_return.status <> 'requested' then
92505
92606
  ${fail$1("ORDERS_TRANSITION_INVALID", "only a requested return can be rejected", "55000")}
92506
92607
  end if;
92507
- update ${returns} x set ${r("status")} = 'rejected' where x.${r("id")} = v_return.id;
92608
+ update ${returns} x set ${r("status")} = ${ctx.value("returns", "status", "rejected")} where x.${r("id")} = v_return.id;
92508
92609
  return true;
92509
92610
  end;
92510
92611
  $$;
@@ -92535,7 +92636,7 @@ begin
92535
92636
  ${fail$1("ORDERS_RETURN_NOT_FOUND", "return not found on this order", "P0002")}
92536
92637
  end if;
92537
92638
  select coalesce(sum(x.${rf("amount")}), 0) into v_pending from ${refunds} x
92538
- where x.${rf("order")} = v_order.id and x.${rf("status")} = 'pending';
92639
+ where x.${rf("order")} = v_order.id and ${ctx.is("refunds", "status", `x.${rf("status")}`, ["pending"])};
92539
92640
  v_left := v_order.paid_total - v_order.refunded_total - v_pending;
92540
92641
  v_amount := coalesce(create_refund.amount, v_left);
92541
92642
  if v_amount <= 0 or v_amount > v_left then
@@ -92543,9 +92644,9 @@ begin
92543
92644
  end if;
92544
92645
  select y.${p("id")} as id, y.${p("provider")} as provider, y.${p("reference")} as reference into v_payment
92545
92646
  from ${payments} y
92546
- where y.${p("order")} = v_order.id and y.${p("status")} = 'succeeded'
92647
+ where y.${p("order")} = v_order.id and ${ctx.is("payments", "status", `y.${p("status")}`, ["succeeded"])}
92547
92648
  and y.${p("captured")} - y.${p("refunded")} - coalesce((select sum(z.${rf("amount")}) from ${refunds} z
92548
- where z.${rf("payment")} = y.${p("id")} and z.${rf("status")} = 'pending'), 0) >= v_amount
92649
+ where z.${rf("payment")} = y.${p("id")} and ${ctx.is("refunds", "status", `z.${rf("status")}`, ["pending"])}), 0) >= v_amount
92549
92650
  order by y.${p("createdAt")} desc
92550
92651
  limit 1;
92551
92652
  if not found then
@@ -92582,7 +92683,7 @@ begin
92582
92683
  ${fail$1("ORDERS_REFUND_STATUS_INVALID", "status is pending, succeeded or failed", "22023")}
92583
92684
  end if;
92584
92685
  select x.${rf("id")} as id, x.${rf("order")} as order_id, x.${rf("payment")} as payment, x.${rf("amount")} as amount,
92585
- x.${rf("status")} as status
92686
+ ${ctx.label("refunds", "status", `x.${rf("status")}`)} as status
92586
92687
  into v_refund from ${refunds} x
92587
92688
  where (complete_refund.refund is not null and x.${rf("id")} = complete_refund.refund)
92588
92689
  or (complete_refund.refund is null and x.${rf("providerReference")} = complete_refund.provider_reference)
@@ -92611,12 +92712,12 @@ begin
92611
92712
  ["currency", "v_order.currency"],
92612
92713
  ["amount", "v_refund.amount::text"],
92613
92714
  ["refundedTotal", "v_total::text"],
92614
- ["status", `(select x.${o("status")} from ${orders} x where x.${o("id")} = v_order.id)`]
92715
+ ["status", `(select ${ctx.label("orders", "status", `x.${o("status")}`)} from ${orders} x where x.${o("id")} = v_order.id)`]
92615
92716
  ], "'order.refunded:' || v_refund.id::text")}
92616
92717
  end if;
92617
92718
  end if;
92618
- return (select jsonb_build_object('id', x.${rf("id")}, 'orderId', x.${rf("order")}, 'status', x.${rf("status")},
92619
- 'amount', x.${rf("amount")}::text, 'orderStatus', y.${o("status")}, 'refundedTotal', y.${o("refundedTotal")}::text)
92719
+ return (select jsonb_build_object('id', x.${rf("id")}, 'orderId', x.${rf("order")}, 'status', ${ctx.label("refunds", "status", `x.${rf("status")}`)},
92720
+ 'amount', x.${rf("amount")}::text, 'orderStatus', ${ctx.label("orders", "status", `y.${o("status")}`)}, 'refundedTotal', y.${o("refundedTotal")}::text)
92620
92721
  from ${refunds} x join ${orders} y on y.${o("id")} = x.${rf("order")} where x.${rf("id")} = v_refund.id);
92621
92722
  end;
92622
92723
  $$;
@@ -92643,7 +92744,7 @@ function addressCheck(address) {
92643
92744
  function ownCart(ctx, id, options = {}) {
92644
92745
  const c = columns(ctx, "carts");
92645
92746
  const readers = options.readers === void 0 ? "" : ` or ${ctx.scope.can("v_cart.tenant", options.readers)}`;
92646
- return `select x.${c("tenant")} as tenant, x.${c("user")} as owner, x.${c("status")} as status,
92747
+ return `select x.${c("tenant")} as tenant, x.${c("user")} as owner, ${ctx.label("carts", "status", `x.${c("status")}`)} as status,
92647
92748
  x.${c("currency")} as currency, x.${c("priceList")} as price_list, x.${c("shippingAddress")} as shipping_address
92648
92749
  into v_cart from ${ctx.table("carts")} x where x.${c("id")} = ${id}${options.lock ? " for update" : ""};
92649
92750
  if not found or not (auth.role() = 'service_role' or v_cart.owner = auth.uid()${readers}) then
@@ -92662,7 +92763,7 @@ function sellable(ctx, variant) {
92662
92763
  const p = columns(catalog, "products");
92663
92764
  return `if not exists (
92664
92765
  select 1 from ${catalog.table("variants")} cv join ${catalog.table("products")} cp on cp.${p("id")} = cv.${v("product")}
92665
- where cv.${v("id")} = ${variant} and cv.${v("tenant")} = v_cart.tenant and cp.${p("status")} = 'active'
92766
+ where cv.${v("id")} = ${variant} and cv.${v("tenant")} = v_cart.tenant and ${catalog.is("products", "status", `cp.${p("status")}`, ["active"])}
92666
92767
  ) then
92667
92768
  ${fail$1("ORDERS_VARIANT_UNAVAILABLE", "this variant is not for sale", "P0002")}
92668
92769
  end if;`;
@@ -92805,11 +92906,11 @@ declare
92805
92906
  begin
92806
92907
  select x.${c("tenant")} as tenant, x.${c("currency")} as currency, x.${c("priceList")} as price_list,
92807
92908
  x.${c("shippingAddress")} as shipping_address, x.${c("shippingRate")} as shipping_rate,
92808
- x.${c("user")} as owner, x.${c("status")} as status, ${or("carts", "x", "email", "text")} as email, ${or("carts", "x", "billingAddress", "jsonb")} as billing_address
92909
+ x.${c("user")} as owner, ${ctx.label("carts", "status", `x.${c("status")}`)} as status, ${or("carts", "x", "email", "text")} as email, ${or("carts", "x", "billingAddress", "jsonb")} as billing_address
92809
92910
  into v_cart from ${ctx.table("carts")} x where x.${c("id")} = p_cart;
92810
92911
  for v_line in
92811
92912
  select l.${cl("id")} as id, l.${cl("variant")} as variant, l.${cl("quantity")} as quantity, l.${cl("unitAmount")} as unit_amount,
92812
- cv.${v("sku")} as sku, ${title} as title, cp.${p("id")} as product, cp.${p("status")} as status,
92913
+ cv.${v("sku")} as sku, ${title} as title, cp.${p("id")} as product, ${catalog.label("products", "status", `cp.${p("status")}`)} as status,
92813
92914
  ${kind} as kind, ${weight} as weight
92814
92915
  from ${ctx.table("cartLines")} l
92815
92916
  join ${catalog.table("variants")} cv on cv.${v("id")} = l.${cl("variant")}
@@ -92844,7 +92945,7 @@ begin
92844
92945
  from jsonb_array_elements(v_lines) with ordinality as e(l, n);
92845
92946
  v_country := v_cart.shipping_address ->> 'country';
92846
92947
  if v_ships and v_cart.shipping_rate is not null then
92847
- select x.${s("id")} as id, x.${s("name")} as name, x.${s("countries")} as countries, x.${s("kind")} as kind,
92948
+ select x.${s("id")} as id, x.${s("name")} as name, x.${s("countries")} as countries, ${ctx.label("shippingRates", "kind", `x.${s("kind")}`)} as kind,
92848
92949
  x.${s("amount")} as amount, x.${s("perKg")} as per_kg, ${or("shippingRates", "x", "freeOver", "bigint")} as free_over
92849
92950
  into v_rate from ${ctx.table("shippingRates")} x
92850
92951
  where x.${s("id")} = v_cart.shipping_rate and x.${s("active")} and x.${s("currency")} = v_cart.currency;
@@ -92923,7 +93024,7 @@ begin
92923
93024
  end if;`}
92924
93025
  insert into ${carts} as x (${c("tenant")}, ${c("user")}, ${c("currency")}, ${c("priceList")}${email ? `, ${c("email")}` : ""})
92925
93026
  values (create_cart.tenant, auth.uid(), create_cart.currency, create_cart.price_list${email ? ", create_cart.email" : ""})
92926
- on conflict (${c("tenant")}, ${c("user")}, ${c("currency")}) where ${c("status")} = 'open' do update
93027
+ on conflict (${c("tenant")}, ${c("user")}, ${c("currency")}) where ${ctx.is("carts", "status", c("status"), ["open"])} do update
92927
93028
  set ${c("priceList")} = coalesce(excluded.${c("priceList")}, x.${c("priceList")}),${email ? `
92928
93029
  ${c("email")} = coalesce(excluded.${c("email")}, x.${c("email")}),` : ""} ${c("updatedAt")} = now()
92929
93030
  returning x.${c("id")} into v_id;
@@ -93077,10 +93178,10 @@ begin
93077
93178
  v_weight := (v_totals ->> 'weightGrams')::bigint;
93078
93179
  return coalesce((
93079
93180
  select jsonb_agg(jsonb_build_object(
93080
- 'id', x.${s("id")}, 'name', x.${s("name")}, 'kind', x.${s("kind")}, 'currency', x.${s("currency")},
93181
+ 'id', x.${s("id")}, 'name', x.${s("name")}, 'kind', ${ctx.label("shippingRates", "kind", `x.${s("kind")}`)}, 'currency', x.${s("currency")},
93081
93182
  'amount', (case
93082
93183
  ${ctx.has("shippingRates", "freeOver") ? ` when x.${s("freeOver")} is not null and v_after_discount >= x.${s("freeOver")} then 0
93083
- ` : ""} else x.${s("amount")} + case when x.${s("kind")} = 'weight' then (x.${s("perKg")} * v_weight + 999) / 1000 else 0 end
93184
+ ` : ""} else x.${s("amount")} + case when ${ctx.is("shippingRates", "kind", `x.${s("kind")}`, ["weight"])} then (x.${s("perKg")} * v_weight + 999) / 1000 else 0 end
93084
93185
  end)::text) order by x.${s("amount")}, x.${s("name")})
93085
93186
  from ${ctx.table("shippingRates")} x
93086
93187
  where x.${s("tenant")} = v_cart.tenant and x.${s("active")} and x.${s("currency")} = v_cart.currency
@@ -93129,12 +93230,12 @@ begin
93129
93230
  end if;
93130
93231
  for v_from in
93131
93232
  select x.${c("id")} as id, x.${c("tenant")} as tenant, x.${c("currency")} as currency
93132
- from ${carts} x where x.${c("user")} = merge_carts.from_user and x.${c("status")} = 'open'
93233
+ from ${carts} x where x.${c("user")} = merge_carts.from_user and ${ctx.is("carts", "status", `x.${c("status")}`, ["open"])}
93133
93234
  for update
93134
93235
  loop
93135
93236
  select x.${c("id")} into v_to from ${carts} x
93136
93237
  where x.${c("user")} = merge_carts.to_user and x.${c("tenant")} = v_from.tenant
93137
- and x.${c("currency")} = v_from.currency and x.${c("status")} = 'open'
93238
+ and x.${c("currency")} = v_from.currency and ${ctx.is("carts", "status", `x.${c("status")}`, ["open"])}
93138
93239
  for update;
93139
93240
  if v_to is null then
93140
93241
  update ${carts} x set ${c("user")} = merge_carts.to_user, ${c("updatedAt")} = now() where x.${c("id")} = v_from.id;
@@ -93144,7 +93245,7 @@ begin
93144
93245
  from ${lines} l where l.${cl("cart")} = v_from.id
93145
93246
  on conflict (${cl("cart")}, ${cl("variant")}) do update
93146
93247
  set ${cl("quantity")} = least(x.${cl("quantity")} + excluded.${cl("quantity")}, ${MAX_QUANTITY}), ${cl("updatedAt")} = now();${moveCodes}
93147
- update ${carts} x set ${c("status")} = 'abandoned', ${c("updatedAt")} = now() where x.${c("id")} = v_from.id;
93248
+ update ${carts} x set ${c("status")} = ${ctx.value("carts", "status", "abandoned")}, ${c("updatedAt")} = now() where x.${c("id")} = v_from.id;
93148
93249
  end if;
93149
93250
  v_to := null;
93150
93251
  v_count := v_count + 1;
@@ -93194,7 +93295,11 @@ function orderInvoice(ctx) {
93194
93295
  }
93195
93296
  const PAYMENT_STATUSES = "('requires_action', 'processing', 'authorized', 'succeeded', 'failed', 'canceled')";
93196
93297
  /** Payment statuses a late webhook can't move a payment back from. */
93197
- const SETTLED = "('succeeded', 'failed', 'canceled')";
93298
+ const SETTLED = [
93299
+ "succeeded",
93300
+ "failed",
93301
+ "canceled"
93302
+ ];
93198
93303
  /**
93199
93304
  * `order_json(order)`: the order with its lines, payments, fulfillments,
93200
93305
  * returns and refunds.
@@ -93222,7 +93327,7 @@ set search_path = ''
93222
93327
  as $$
93223
93328
  select jsonb_build_object(
93224
93329
  'id', x.${o("id")}, 'organizationId', x.${o("tenant")}, 'number', x.${o("number")}, 'cartId', x.${o("cart")},
93225
- 'customerId', x.${o("customer")}, 'email', ${or("orders", "x", "email")}, 'status', x.${o("status")}, 'currency', x.${o("currency")},
93330
+ 'customerId', x.${o("customer")}, 'email', ${or("orders", "x", "email")}, 'status', ${ctx.label("orders", "status", `x.${o("status")}`)}, 'currency', x.${o("currency")},
93226
93331
  'subtotal', ${text("x", o("subtotal"))}, 'discountTotal', ${text("x", o("discountTotal"))},
93227
93332
  'shippingTotal', ${text("x", o("shippingTotal"))}, 'taxTotal', ${text("x", o("taxTotal"))}, 'total', ${text("x", o("total"))},
93228
93333
  'paidTotal', ${text("x", o("paidTotal"))}, 'refundedTotal', ${text("x", o("refundedTotal"))}, 'taxInclusive', x.${o("taxInclusive")},
@@ -93240,26 +93345,26 @@ as $$
93240
93345
  'backordered', l.${ol("backordered")}) order by l.${ol("position")})
93241
93346
  from ${ctx.table("orderLines")} l where l.${ol("order")} = x.${o("id")}), '[]'::jsonb),
93242
93347
  'payments', coalesce((select jsonb_agg(jsonb_build_object(
93243
- 'id', y.${p("id")}, 'provider', y.${p("provider")}, 'reference', y.${p("reference")}, 'status', y.${p("status")},
93348
+ 'id', y.${p("id")}, 'provider', y.${p("provider")}, 'reference', y.${p("reference")}, 'status', ${ctx.label("payments", "status", `y.${p("status")}`)},
93244
93349
  'amount', ${text("y", p("amount"))}, 'captured', ${text("y", p("captured"))}, 'refunded', ${text("y", p("refunded"))},
93245
93350
  'createdAt', y.${p("createdAt")}) order by y.${p("createdAt")})
93246
93351
  from ${ctx.table("payments")} y where y.${p("order")} = x.${o("id")}), '[]'::jsonb),
93247
93352
  'fulfillments', coalesce((select jsonb_agg(jsonb_build_object(
93248
- 'id', y.${f("id")}, 'status', y.${f("status")}, 'locationId', y.${f("location")}, 'carrier', y.${f("carrier")},
93353
+ 'id', y.${f("id")}, 'status', ${ctx.label("fulfillments", "status", `y.${f("status")}`)}, 'locationId', y.${f("location")}, 'carrier', y.${f("carrier")},
93249
93354
  'trackingNumber', y.${f("trackingNumber")}, 'trackingUrl', ${or("fulfillments", "y", "trackingUrl")}, 'createdAt', y.${f("createdAt")},
93250
93355
  'shippedAt', y.${f("shippedAt")}, 'deliveredAt', y.${f("deliveredAt")},
93251
93356
  'lines', coalesce((select jsonb_agg(jsonb_build_object('lineId', z.${fl("line")}, 'quantity', z.${fl("quantity")}))
93252
93357
  from ${ctx.table("fulfillmentLines")} z where z.${fl("fulfillment")} = y.${f("id")}), '[]'::jsonb)) order by y.${f("createdAt")})
93253
93358
  from ${ctx.table("fulfillments")} y where y.${f("order")} = x.${o("id")}), '[]'::jsonb),
93254
93359
  'returns', coalesce((select jsonb_agg(jsonb_build_object(
93255
- 'id', y.${r("id")}, 'status', y.${r("status")}, 'reason', ${or("returns", "y", "reason")}, 'createdAt', y.${r("createdAt")},
93360
+ 'id', y.${r("id")}, 'status', ${ctx.label("returns", "status", `y.${r("status")}`)}, 'reason', ${or("returns", "y", "reason")}, 'createdAt', y.${r("createdAt")},
93256
93361
  'receivedAt', y.${r("receivedAt")},
93257
93362
  'lines', coalesce((select jsonb_agg(jsonb_build_object('lineId', z.${rl("line")}, 'quantity', z.${rl("quantity")}))
93258
93363
  from ${ctx.table("returnLines")} z where z.${rl("return")} = y.${r("id")}), '[]'::jsonb)) order by y.${r("createdAt")})
93259
93364
  from ${ctx.table("returns")} y where y.${r("order")} = x.${o("id")}), '[]'::jsonb),
93260
93365
  'refunds', coalesce((select jsonb_agg(jsonb_build_object(
93261
93366
  'id', y.${rf("id")}, 'paymentId', y.${rf("payment")}, 'returnId', y.${rf("return")}, 'amount', ${text("y", rf("amount"))},
93262
- 'status', y.${rf("status")}, 'reason', ${or("refunds", "y", "reason")}, 'providerReference', y.${rf("providerReference")},
93367
+ 'status', ${ctx.label("refunds", "status", `y.${rf("status")}`)}, 'reason', ${or("refunds", "y", "reason")}, 'providerReference', y.${rf("providerReference")},
93263
93368
  'createdAt', y.${rf("createdAt")}, 'completedAt', y.${rf("completedAt")}) order by y.${rf("createdAt")})
93264
93369
  from ${ctx.table("refunds")} y where y.${rf("order")} = x.${o("id")}), '[]'::jsonb)${extraFieldsJson("x", names.extras)})
93265
93370
  from ${ctx.table("orders")} x where x.${o("id")} = p_order
@@ -93357,6 +93462,7 @@ function releaseLines(ctx) {
93357
93462
  function checkoutFunctions(ctx, names) {
93358
93463
  const { fn } = names;
93359
93464
  const minutes = paymentWindow(ctx);
93465
+ const settled = (value, negate = false) => ctx.is("payments", "status", value, SETTLED, negate);
93360
93466
  const carts = ctx.table("carts");
93361
93467
  const orders = ctx.table("orders");
93362
93468
  const payments = ctx.table("payments");
@@ -93416,7 +93522,7 @@ declare
93416
93522
  v_claims text;
93417
93523
  begin
93418
93524
  ${serviceOnlyGuard()}
93419
- select x.${c("tenant")} as tenant, x.${c("user")} as owner, x.${c("status")} as status, x.${c("currency")} as currency,
93525
+ select x.${c("tenant")} as tenant, x.${c("user")} as owner, ${ctx.label("carts", "status", `x.${c("status")}`)} as status, x.${c("currency")} as currency,
93420
93526
  ${cartOr("email", "text")} as email, x.${c("shippingAddress")} as shipping_address, ${cartOr("billingAddress", "jsonb")} as billing_address
93421
93527
  into v_cart from ${carts} x where x.${c("id")} = place_order.cart for update;
93422
93528
  if not found then
@@ -93479,7 +93585,7 @@ begin
93479
93585
  from jsonb_array_elements(v_priced -> 'lines') with ordinality as e(l, n);
93480
93586
  ${load("v_id", false)}${reserveLines(ctx, minutes)}${promotions === void 0 ? "" : `
93481
93587
  perform ${promotions.fn("redeem_promotions")}(v_order.id, v_priced -> 'promotions');`}
93482
- update ${carts} x set ${c("status")} = 'converted', ${c("convertedAt")} = now(), ${c("updatedAt")} = now()
93588
+ update ${carts} x set ${c("status")} = ${ctx.value("carts", "status", "converted")}, ${c("convertedAt")} = now(), ${c("updatedAt")} = now()
93483
93589
  where x.${c("id")} = place_order.cart;
93484
93590
  ${ctx.record({
93485
93591
  type: "order.placed",
@@ -93551,7 +93657,7 @@ begin
93551
93657
  values (v_order.tenant, v_order.id, record_payment.provider, record_payment.reference, ${ctx.cast("payments", "status", "record_payment.status")}, record_payment.currency,
93552
93658
  record_payment.amount, coalesce(record_payment.captured, 0), coalesce(record_payment.refunded, 0))
93553
93659
  on conflict (${p("provider")}, ${p("reference")}) do update set
93554
- ${p("status")} = case when x.${p("status")} in ${SETTLED} and excluded.${p("status")} not in ${SETTLED} then x.${p("status")} else excluded.${p("status")} end,
93660
+ ${p("status")} = case when ${settled(`x.${p("status")}`)} and ${settled(`excluded.${p("status")}`, true)} then x.${p("status")} else excluded.${p("status")} end,
93555
93661
  ${p("amount")} = excluded.${p("amount")},
93556
93662
  ${p("captured")} = greatest(x.${p("captured")}, excluded.${p("captured")}),
93557
93663
  ${p("refunded")} = greatest(x.${p("refunded")}, excluded.${p("refunded")}),
@@ -93561,7 +93667,7 @@ begin
93561
93667
  ${fail$1("ORDERS_PAYMENT_CONFLICT", "this payment reference belongs to another order", "23505")}
93562
93668
  end if;
93563
93669
  select coalesce(sum(x.${p("captured")}), 0) into v_paid from ${payments} x
93564
- where x.${p("order")} = v_order.id and x.${p("status")} = 'succeeded';
93670
+ where x.${p("order")} = v_order.id and ${ctx.is("payments", "status", `x.${p("status")}`, ["succeeded"])};
93565
93671
  update ${orders} x set ${o("paidTotal")} = v_paid, ${o("updatedAt")} = now() where x.${o("id")} = v_order.id;
93566
93672
  if v_order.status = 'pending_payment' and v_paid >= v_order.total then
93567
93673
  perform ${fn("order_transition")}(v_order.id, 'paid');${commitLines(ctx)}
@@ -93588,7 +93694,7 @@ begin
93588
93694
  })}
93589
93695
  v_newly := true;
93590
93696
  end if;
93591
- return jsonb_build_object('orderId', v_order.id, 'status', (select x.${o("status")} from ${orders} x where x.${o("id")} = v_order.id),
93697
+ return jsonb_build_object('orderId', v_order.id, 'status', (select ${ctx.label("orders", "status", `x.${o("status")}`)} from ${orders} x where x.${o("id")} = v_order.id),
93592
93698
  'paidTotal', v_paid::text, 'newlyPaid', v_newly,
93593
93699
  'invoiceNumber', coalesce(v_number, v_order.invoice_number)${invoice ? `, 'invoiceId', v_invoice ->> ${sqlString(invoice.id)}` : ""});
93594
93700
  end;
@@ -93679,7 +93785,7 @@ begin
93679
93785
  ${serviceOnlyGuard()}
93680
93786
  for v_id in
93681
93787
  select x.${o("id")} from ${orders} x
93682
- where x.${o("status")} = 'pending_payment' and x.${o("placedAt")} < now() - interval '${String(minutes)} minutes'
93788
+ where ${ctx.is("orders", "status", `x.${o("status")}`, ["pending_payment"])} and x.${o("placedAt")} < now() - interval '${String(minutes)} minutes'
93683
93789
  order by x.${o("placedAt")}
93684
93790
  limit greatest(coalesce(expire_orders.max_rows, 100), 1)
93685
93791
  for update skip locked
@@ -94184,7 +94290,7 @@ as $$
94184
94290
  'orderId', o.${o("id")},
94185
94291
  'number', o.${o("number")},
94186
94292
  'customerId', o.${o("customer")},
94187
- 'status', o.${o("status")},
94293
+ 'status', ${ctx.label("orders", "status", `o.${o("status")}`)},
94188
94294
  'state', (${STATES})[min(${rank(stateOf("p"))})],
94189
94295
  'sentAt', min(p.${lp("queuedAt")}),
94190
94296
  'readyAt', case when bool_and(p.${lp("readyAt")} is not null) then max(p.${lp("readyAt")}) end,
@@ -94682,7 +94788,7 @@ create table if not exists ${t("carts")} (
94682
94788
  ${c("updatedAt")} timestamptz not null default now(),
94683
94789
  ${c("convertedAt")} timestamptz
94684
94790
  );
94685
- create unique index if not exists ${ctx.naming.rename("carts_open_idx")} on ${t("carts")} (${c("tenant")}, ${c("user")}, ${c("currency")}) where ${c("status")} = 'open';
94791
+ create unique index if not exists ${ctx.naming.rename("carts_open_idx")} on ${t("carts")} (${c("tenant")}, ${c("user")}, ${c("currency")}) where ${ctx.is("carts", "status", c("status"), ["open"])};
94686
94792
  create index if not exists ${ctx.naming.rename("carts_user_idx")} on ${t("carts")} (${c("user")});
94687
94793
  create index if not exists ${ctx.naming.rename("carts_rate_idx")} on ${t("carts")} (${c("shippingRate")});
94688
94794
  ${c("priceList") && priceList ? `create index if not exists ${ctx.naming.rename("carts_price_list_idx")} on ${t("carts")} (${c("priceList")});\n` : ""}${lockModuleTable(ctx, "carts", { read: true })}
@@ -99490,8 +99596,8 @@ ${renderPolicy(policy$1({
99490
99596
  * the ones the app lacks.
99491
99597
  */
99492
99598
  function rowJson(ctx, table, alias) {
99493
- if (ctx.owns(table)) return `to_jsonb(${alias})`;
99494
- return `jsonb_build_object(${Object.entries(NAMES$40.tables[table]?.columns ?? {}).map(([logical, name]) => `${sqlString(name)}, ${ctx.has(table, logical) ? `${alias}.${ctx.col(table, logical)}` : "null"}`).join(", ")})`;
99599
+ if (ctx.owns(table)) return ctx.rowJson(table, alias);
99600
+ return `jsonb_build_object(${Object.entries(NAMES$40.tables[table]?.columns ?? {}).map(([logical, name]) => `${sqlString(name)}, ${ctx.has(table, logical) ? ctx.label(table, logical, `${alias}.${ctx.col(table, logical)}`) : "null"}`).join(", ")})`;
99495
99601
  }
99496
99602
  /**
99497
99603
  * `options.extraColumns`, added to the pipelines table. `stages` is reserved:
@@ -113369,8 +113475,9 @@ function functions$1(ctx, extras) {
113369
113475
  const fields = extraFieldsArg(extras);
113370
113476
  const linked = ctx.has("shipments", "subjectType") && ctx.has("shipments", "subjectId");
113371
113477
  const location = ctx.has("shipments", "fromLocation");
113372
- const shipStatus = (row) => asText$2(ctx, "shipments", `${row}.${h("status")}`);
113373
- const eventStatus = (row) => asText$2(ctx, "trackingEvents", `${row}.${e("status")}`);
113478
+ const shipStatus = (row) => ctx.mapsValues("shipments", "status") ? ctx.label("shipments", "status", `${row}.${h("status")}`) : asText$2(ctx, "shipments", `${row}.${h("status")}`);
113479
+ const eventStatus = (row) => ctx.mapsValues("trackingEvents", "status") ? ctx.label("trackingEvents", "status", `${row}.${e("status")}`) : asText$2(ctx, "trackingEvents", `${row}.${e("status")}`);
113480
+ const st = (row, labels, negate = false) => ctx.is("shipments", "status", `${row}.${h("status")}`, labels, negate);
113374
113481
  const or = (table, row, logical) => ctx.has(table, logical) ? `${row}.${ctx.col(table, logical)}` : "null";
113375
113482
  const also = (table, logical) => ctx.has(table, logical) ? `, ${ctx.col(table, logical)}` : "";
113376
113483
  const alsoValue = (table, logical, value) => ctx.has(table, logical) ? `, ${value}` : "";
@@ -113378,8 +113485,8 @@ function functions$1(ctx, extras) {
113378
113485
  const lines = (...groups) => groups.map((group) => group.filter((value) => value !== void 0).join(", ")).filter((line) => line !== "").join(",\n ");
113379
113486
  const allowed = (tenant, permission) => `(${SERVICE_CALLER$1} or ${ctx.can("tenant", tenant, permission)})`;
113380
113487
  const packagesJson = (row) => `(select coalesce(jsonb_agg(jsonb_build_object('id', pk.${p("id")}, 'position', pk.${p("position")}, 'weightGrams', pk.${p("weight")}, 'lengthMm', ${or("packages", "pk", "length")}, 'widthMm', ${or("packages", "pk", "width")}, 'heightMm', ${or("packages", "pk", "height")}, 'reference', ${or("packages", "pk", "reference")}) order by pk.${p("position")}), '[]'::jsonb) from ${packages} pk where pk.${p("shipment")} = ${row}.${h("id")})`;
113381
- const shipmentJson = (row) => withExtraFields(`jsonb_build_object('id', ${row}.${h("id")}, 'organizationId', ${row}.${h("tenant")}::text, 'reference', ${row}.${h("reference")}, 'status', ${row}.${h("status")}, 'from', ${row}.${h("fromAddress")}, 'to', ${row}.${h("toAddress")}, 'fromLocationId', ${or("shipments", row, "fromLocation")}, 'subjectType', ${or("shipments", row, "subjectType")}, 'subjectId', ${or("shipments", row, "subjectId")}, 'carrier', ${row}.${h("carrier")}, 'service', ${row}.${h("service")}, 'trackingNumber', ${row}.${h("trackingNumber")}, 'trackingUrl', ${or("shipments", row, "trackingUrl")}, 'labelId', ${row}.${h("labelId")}, 'labelUrl', ${or("shipments", row, "labelUrl")}, 'labelFormat', ${row}.${h("labelFormat")}, 'labelCost', ${row}.${h("labelCost")}::text, 'currency', ${row}.${h("currency")}, 'labeledAt', ${row}.${h("labeledAt")}, 'deliveredAt', ${row}.${h("deliveredAt")}, 'cancelledAt', ${row}.${h("cancelledAt")}, 'createdBy', ${or("shipments", row, "createdBy")}, 'createdAt', ${row}.${h("createdAt")}, 'updatedAt', ${row}.${h("updatedAt")}, 'packages', ${packagesJson(row)})`, row, extras);
113382
- const eventJson = (row) => `jsonb_build_object('id', ${row}.${e("id")}, 'externalId', ${row}.${e("externalId")}, 'status', ${row}.${e("status")}, 'occurredAt', ${row}.${e("occurredAt")}, 'description', ${or("trackingEvents", row, "description")}, 'location', ${or("trackingEvents", row, "location")}, 'source', ${row}.${e("source")}, 'createdAt', ${row}.${e("createdAt")})`;
113488
+ const shipmentJson = (row) => withExtraFields(`jsonb_build_object('id', ${row}.${h("id")}, 'organizationId', ${row}.${h("tenant")}::text, 'reference', ${row}.${h("reference")}, 'status', ${ctx.label("shipments", "status", `${row}.${h("status")}`)}, 'from', ${row}.${h("fromAddress")}, 'to', ${row}.${h("toAddress")}, 'fromLocationId', ${or("shipments", row, "fromLocation")}, 'subjectType', ${or("shipments", row, "subjectType")}, 'subjectId', ${or("shipments", row, "subjectId")}, 'carrier', ${row}.${h("carrier")}, 'service', ${row}.${h("service")}, 'trackingNumber', ${row}.${h("trackingNumber")}, 'trackingUrl', ${or("shipments", row, "trackingUrl")}, 'labelId', ${row}.${h("labelId")}, 'labelUrl', ${or("shipments", row, "labelUrl")}, 'labelFormat', ${row}.${h("labelFormat")}, 'labelCost', ${row}.${h("labelCost")}::text, 'currency', ${row}.${h("currency")}, 'labeledAt', ${row}.${h("labeledAt")}, 'deliveredAt', ${row}.${h("deliveredAt")}, 'cancelledAt', ${row}.${h("cancelledAt")}, 'createdBy', ${or("shipments", row, "createdBy")}, 'createdAt', ${row}.${h("createdAt")}, 'updatedAt', ${row}.${h("updatedAt")}, 'packages', ${packagesJson(row)})`, row, extras);
113489
+ const eventJson = (row) => `jsonb_build_object('id', ${row}.${e("id")}, 'externalId', ${row}.${e("externalId")}, 'status', ${ctx.label("trackingEvents", "status", `${row}.${e("status")}`)}, 'occurredAt', ${row}.${e("occurredAt")}, 'description', ${or("trackingEvents", row, "description")}, 'location', ${or("trackingEvents", row, "location")}, 'source', ${row}.${e("source")}, 'createdAt', ${row}.${e("createdAt")})`;
113383
113490
  const subject = (row) => `'shipments/' || ${row}.${h("id")}::text`;
113384
113491
  const base = (row) => `'organizationId', ${row}.${h("tenant")}::text, 'id', ${row}.${h("id")}`;
113385
113492
  const audited = (row, summary) => ({
@@ -113406,7 +113513,7 @@ function functions$1(ctx, extras) {
113406
113513
  end;`;
113407
113514
  const statusRecord = ctx.record({
113408
113515
  type: "shipment.status_changed",
113409
- payload: `jsonb_build_object(${base("v_ship")}, 'from', v_from, 'to', v_ship.${h("status")}, 'trackingNumber', v_ship.${h("trackingNumber")})`,
113516
+ payload: `jsonb_build_object(${base("v_ship")}, 'from', v_from, 'to', ${ctx.label("shipments", "status", `v_ship.${h("status")}`)}, 'trackingNumber', v_ship.${h("trackingNumber")})`,
113410
113517
  subject: subject("v_ship"),
113411
113518
  tenant: `v_ship.${h("tenant")}`,
113412
113519
  audit: false
@@ -113416,8 +113523,8 @@ function functions$1(ctx, extras) {
113416
113523
  where t.${e("shipment")} = v_ship.${h("id")}
113417
113524
  order by t.${e("occurredAt")} desc, array_position(array[${list(TRACKING_STATUSES)}]::text[], ${eventStatus("t")}) desc
113418
113525
  limit 1;
113419
- if v_status is not null and v_ship.${h("status")} <> 'cancelled' and v_status <> ${shipStatus("v_ship")} then
113420
- v_from := v_ship.${h("status")};
113526
+ if v_status is not null and ${st("v_ship", ["cancelled"], true)} and v_status <> ${shipStatus("v_ship")} then
113527
+ v_from := ${ctx.label("shipments", "status", `v_ship.${h("status")}`)};
113421
113528
  update ${shipments} x set
113422
113529
  ${h("status")} = ${ctx.cast("shipments", "status", "v_status")},
113423
113530
  ${h("deliveredAt")} = case when v_status = 'delivered' then v_at end,
@@ -113589,7 +113696,7 @@ declare
113589
113696
  v_ship ${shipments}%rowtype;${syncDeclare}
113590
113697
  begin
113591
113698
  ${findForWrite("set_shipment_label.shipment_id")}
113592
- if v_ship.${h("status")} <> 'draft' then
113699
+ if ${st("v_ship", ["draft"], true)} then
113593
113700
  ${fail$1("SHIPMENT_NOT_DRAFT", "only a draft shipment gets a label", "55000")}
113594
113701
  end if;
113595
113702
  begin
@@ -113615,7 +113722,7 @@ ${findForWrite("set_shipment_label.shipment_id")}
113615
113722
  ${fail$1("SHIPMENT_LABEL_INVALID", "a label needs a carrier, service, tracking number, label id, a cost of zero or more and a currency", "22023")}
113616
113723
  end if;
113617
113724
  insert into ${events} (${e("tenant")}, ${e("shipment")}, ${e("externalId")}, ${e("status")}, ${e("occurredAt")}${also("trackingEvents", "description")}, ${e("source")})
113618
- values (v_ship.${h("tenant")}, v_ship.${h("id")}, 'label:' || v_ship.${h("labelId")}, 'label_created', now()${alsoValue("trackingEvents", "description", "'Label created'")}, 'carrier')
113725
+ values (v_ship.${h("tenant")}, v_ship.${h("id")}, 'label:' || v_ship.${h("labelId")}, ${ctx.value("trackingEvents", "status", "label_created")}, now()${alsoValue("trackingEvents", "description", "'Label created'")}, 'carrier')
113619
113726
  on conflict (${e("shipment")}, ${e("externalId")}) do nothing;
113620
113727
  ${ctx.record({
113621
113728
  type: "shipment.labeled",
@@ -113679,7 +113786,7 @@ begin
113679
113786
  end if;
113680
113787
  ${insertEvents("ingest_tracking_events.events", "'webhook'")}
113681
113788
  ${syncStatus}
113682
- return jsonb_build_object('id', v_ship.${h("id")}, 'organizationId', v_ship.${h("tenant")}::text, 'status', v_ship.${h("status")}, 'recorded', v_count);
113789
+ return jsonb_build_object('id', v_ship.${h("id")}, 'organizationId', v_ship.${h("tenant")}::text, 'status', ${ctx.label("shipments", "status", `v_ship.${h("status")}`)}, 'recorded', v_count);
113683
113790
  end;
113684
113791
  $$;
113685
113792
  ${serviceGrant(`${fn("ingest_tracking_events")}(text, text, jsonb)`)}
@@ -113697,11 +113804,11 @@ declare
113697
113804
  v_ship ${shipments}%rowtype;
113698
113805
  begin
113699
113806
  ${findForWrite("cancel_shipment.shipment_id")}
113700
- if v_ship.${h("status")} not in ('draft', 'label_created') then
113807
+ if ${st("v_ship", ["draft", "label_created"], true)} then
113701
113808
  ${fail$1("SHIPMENT_SHIPPED", "only a draft or a shipment that hasn't left gets cancelled", "55000")}
113702
113809
  end if;
113703
113810
  update ${shipments} x set
113704
- ${h("status")} = 'cancelled',
113811
+ ${h("status")} = ${ctx.value("shipments", "status", "cancelled")},
113705
113812
  ${h("cancelledAt")} = now(),
113706
113813
  ${h("updatedAt")} = now()
113707
113814
  where x.${h("id")} = v_ship.${h("id")}
@@ -115337,8 +115444,9 @@ function workItemFunctions(ctx, n) {
115337
115444
  if ${attrs} ->> ${sqlString(key)} is not null then
115338
115445
  ${fail$1("WORK_ITEM_FIELD_UNSUPPORTED", `this ${ctx.tableName(table).name} table has no ${logical} column`, "22023")}
115339
115446
  end if;`).join("");
115447
+ const extrasInsert = insertExtraColumns(t("items"), n.extras, "(create_work_item.attrs -> 'fields')");
115340
115448
  const editable = (alias) => `(${n.service} or ${ctx.scope.can(`${alias}.${w("tenant")}`, n.write)})`;
115341
- const row = (alias) => `to_jsonb(${alias})${ctx.labelsJson("items", alias)} || ${int8Text(alias, [w("number")])} || jsonb_build_object('assignees', coalesce((select jsonb_agg(ra.${a("user")} order by ${ctx.has("assignees", "createdAt") ? `ra.${a("createdAt")}, ` : ""}ra.${a("user")}) from ${t("assignees")} ra where ra.${a("item")} = ${alias}.${w("id")}), '[]'::jsonb)) || ${itemExtrasJson(ctx, n, alias)}`;
115449
+ const row = (alias) => `${ctx.rowJson("items", alias, { as: { number: (v) => `${v}::text` } })} || ${int8Text(alias, [w("number")])} || jsonb_build_object('assignees', coalesce((select jsonb_agg(ra.${a("user")} order by ${ctx.has("assignees", "createdAt") ? `ra.${a("createdAt")}, ` : ""}ra.${a("user")}) from ${t("assignees")} ra where ra.${a("item")} = ${alias}.${w("id")}), '[]'::jsonb)) || ${itemExtrasJson(ctx, n, alias)}`;
115342
115450
  const record = (type, alias, extra = "") => ctx.record({
115343
115451
  type,
115344
115452
  payload: `jsonb_build_object('organizationId', ${alias}.${w("tenant")}, 'workItemId', ${alias}.${w("id")}, 'subjectType', ${item}, 'subjectId', ${alias}.${w("id")}::text, 'title', ${alias}.${w("title")}${extra})`,
@@ -115434,7 +115542,7 @@ ${["startOn", "targetOn"].flatMap((key) => ctx.has("projects", key) ? [`
115434
115542
  when check_violation or not_null_violation then
115435
115543
  ${fail$1("WORK_ITEM_PROJECT_INVALID", "a project needs a key of capitals and a name, and ends after it starts", "22023")}
115436
115544
  end;
115437
- return (select to_jsonb(x) || jsonb_build_object('progress', ${has("project") ? `(
115545
+ return (select ${ctx.rowJson("projects", "x")} || jsonb_build_object('progress', ${has("project") ? `(
115438
115546
  select case when count(*) = 0 then null else round(100.0 * count(*) filter (where ${state(`y.${w("state")}`, ["completed"])}) / count(*) filter (where ${state(`y.${w("state")}`, ["canceled"], true)})) end
115439
115547
  from ${t("items")} y where y.${w("project")} = x.${p("id")} and y.${w("archivedAt")} is null
115440
115548
  )` : "null"}) from ${t("projects")} x where x.${p("id")} = v_id);
@@ -115474,7 +115582,7 @@ begin
115474
115582
  exception when check_violation or not_null_violation then
115475
115583
  ${fail$1("WORK_ITEM_ITERATION_INVALID", "an iteration needs a name and ends on or after it starts", "22023")}
115476
115584
  end;
115477
- return (select to_jsonb(x) from ${t("iterations")} x where x.${i("id")} = v_id);
115585
+ return (select ${ctx.rowJson("iterations", "x")} from ${t("iterations")} x where x.${i("id")} = v_id);
115478
115586
  end;
115479
115587
  $$;
115480
115588
  ${userGrant(`${fn("save_iteration")}(${ctx.idType}, uuid, jsonb)`)}
@@ -115542,7 +115650,7 @@ begin
115542
115650
  w("pipeline"),
115543
115651
  w("stage"),
115544
115652
  column("createdBy")
115545
- ])})
115653
+ ])}${extrasInsert.columns})
115546
115654
  values (${lines(" ", [
115547
115655
  "create_work_item.tenant",
115548
115656
  "v_seq",
@@ -115561,7 +115669,7 @@ begin
115561
115669
  "(create_work_item.attrs ->> 'pipelineId')::uuid",
115562
115670
  "(create_work_item.attrs ->> 'stageId')::uuid",
115563
115671
  present("items", "createdBy", "auth.uid()")
115564
- ])})
115672
+ ])}${extrasInsert.values})
115565
115673
  returning ${w("id")} into v_id;
115566
115674
  exception when check_violation or invalid_text_representation or datetime_field_overflow or numeric_value_out_of_range or foreign_key_violation then
115567
115675
  ${fail$1("WORK_ITEM_ATTRS_INVALID", "a work item field has an invalid value", "22023")}