@stacksjs/defaults 0.75.529 → 0.75.537

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 (248) hide show
  1. package/ai/skills/stacks-actions/SKILL.md +1 -1
  2. package/ai/skills/stacks-build/SKILL.md +1 -1
  3. package/ai/skills/stacks-dashboard/SKILL.md +2 -2
  4. package/ai/skills/stacks-database/SKILL.md +1 -1
  5. package/ai/skills/stacks-migrations/SKILL.md +2 -2
  6. package/ai/skills/stacks-native/CATALOG.md +6 -6
  7. package/app/Actions/Dashboard/Commerce/CommerceCouponsAction.ts +27 -15
  8. package/app/Actions/Dashboard/Commerce/CommerceCouponsExportAction.ts +45 -0
  9. package/app/Actions/Dashboard/Commerce/CommerceCustomersAction.ts +22 -12
  10. package/app/Actions/Dashboard/Commerce/CommerceCustomersExportAction.ts +44 -0
  11. package/app/Actions/Dashboard/Commerce/CommercePosCheckoutAction.ts +9 -29
  12. package/app/Actions/Dashboard/Commerce/CommercePrintDevicesAction.ts +7 -9
  13. package/app/Actions/Dashboard/Commerce/CommerceProductDetailAction.ts +9 -8
  14. package/app/Actions/Dashboard/Commerce/CommerceTaxesAction.ts +7 -9
  15. package/app/Actions/Dashboard/Commerce/ManufacturerIndexAction.ts +8 -20
  16. package/app/Actions/Dashboard/Commerce/commerce-coupon-list.test.ts +203 -0
  17. package/app/Actions/Dashboard/Commerce/commerce-coupon-list.ts +248 -0
  18. package/app/Actions/Dashboard/Commerce/commerce-customer-list.test.ts +183 -0
  19. package/app/Actions/Dashboard/Commerce/commerce-customer-list.ts +186 -0
  20. package/app/Actions/Dashboard/Commerce/commerce-customer-records.test.ts +1 -34
  21. package/app/Actions/Dashboard/Commerce/commerce-customer-records.ts +0 -11
  22. package/app/Actions/Dashboard/Commerce/commerce-manufacturer-list.test.ts +118 -0
  23. package/app/Actions/Dashboard/Commerce/commerce-manufacturer-list.ts +41 -0
  24. package/app/Actions/Dashboard/Commerce/commerce-pos-catalog.test.ts +17 -5
  25. package/app/Actions/Dashboard/Commerce/commerce-pos-catalog.ts +17 -3
  26. package/app/Actions/Dashboard/Commerce/commerce-print-device-list.test.ts +99 -0
  27. package/app/Actions/Dashboard/Commerce/commerce-print-device-list.ts +18 -0
  28. package/app/Actions/Dashboard/Commerce/commerce-product-list.ts +5 -5
  29. package/app/Actions/Dashboard/Commerce/commerce-product-options.test.ts +81 -0
  30. package/app/Actions/Dashboard/Commerce/commerce-tax-rate-list.test.ts +99 -0
  31. package/app/Actions/Dashboard/Commerce/commerce-tax-rate-list.ts +18 -0
  32. package/app/Actions/Dashboard/Commerce/coupon-records.test.ts +1 -16
  33. package/app/Actions/Dashboard/Commerce/coupon-records.ts +6 -10
  34. package/app/Actions/Dashboard/Commerce/manufacturer-records.test.ts +5 -17
  35. package/app/Actions/Dashboard/Commerce/manufacturer-records.ts +0 -29
  36. package/app/Actions/Dashboard/Email/captured-mail.test.ts +16 -0
  37. package/app/Actions/Dashboard/Email/captured-mail.ts +9 -1
  38. package/app/Actions/Dashboard/Models/model-write.ts +36 -3
  39. package/app/Actions/Dashboard/Notifications/NotificationDeliveryHistoryAction.ts +13 -58
  40. package/app/Actions/Dashboard/Notifications/notification-delivery-history.ts +74 -0
  41. package/app/Actions/SitemapAction.ts +3 -1
  42. package/app/Models/Notification.ts +3 -1
  43. package/app/Models/NotificationDelivery.ts +4 -0
  44. package/app/Models/User.ts +10 -1
  45. package/bootstrap.ts +10 -2
  46. package/functions/commerce/tax-types.ts +21 -0
  47. package/functions/dashboard-list.test.ts +16 -0
  48. package/functions/dashboard-list.ts +14 -6
  49. package/functions/dashboard-model-record.test.ts +139 -0
  50. package/functions/dashboard-model-record.ts +353 -0
  51. package/functions/monitoring/errors.ts +22 -103
  52. package/functions/notifications/deliveries.ts +7 -38
  53. package/functions/queries.ts +7 -10
  54. package/ide/vscode/package.json +1 -1
  55. package/package.json +5 -5
  56. package/resources/components/Dashboard/Analytics/AnalyticsHub.stx +2 -2
  57. package/resources/components/Dashboard/Analytics/CampaignAnalytics.stx +22 -28
  58. package/resources/components/Dashboard/Analytics/EventAnalytics.stx +26 -34
  59. package/resources/components/Dashboard/Analytics/SalesAnalytics.stx +29 -37
  60. package/resources/components/Dashboard/Analytics/WebAnalyticsBreakdown.stx +12 -16
  61. package/resources/components/Dashboard/Analytics/WebAnalyticsDashboard.stx +43 -53
  62. package/resources/components/Dashboard/App/RequestsOverview.stx +2 -1
  63. package/resources/components/Dashboard/App/SourceInventory.stx +2 -1
  64. package/resources/components/Dashboard/Auth/AccessTokens.stx +3 -5
  65. package/resources/components/Dashboard/Billing/BillingPaymentMethodsPanel.stx +9 -11
  66. package/resources/components/Dashboard/Billing/BillingSettings.stx +1 -1
  67. package/resources/components/Dashboard/Buddy/BuddyAssistant.stx +4 -6
  68. package/resources/components/Dashboard/Commerce/CommerceCategoriesDashboard.stx +2 -2
  69. package/resources/components/Dashboard/Commerce/CommerceCategoriesTable.stx +3 -3
  70. package/resources/components/Dashboard/Commerce/CommerceCategoryDialog.stx +2 -2
  71. package/resources/components/Dashboard/Commerce/CommerceCategoryHierarchy.stx +3 -5
  72. package/resources/components/Dashboard/Commerce/CommerceCouponBreakdown.stx +17 -13
  73. package/resources/components/Dashboard/Commerce/CommerceCouponDialog.stx +1 -1
  74. package/resources/components/Dashboard/Commerce/CommerceCouponsDashboard.stx +57 -85
  75. package/resources/components/Dashboard/Commerce/CommerceCouponsTable.stx +32 -9
  76. package/resources/components/Dashboard/Commerce/CommerceCustomerDialog.stx +1 -1
  77. package/resources/components/Dashboard/Commerce/CommerceCustomersDashboard.stx +49 -83
  78. package/resources/components/Dashboard/Commerce/CommerceCustomersTable.stx +32 -9
  79. package/resources/components/Dashboard/Commerce/CommerceGiftCardBreakdown.stx +9 -15
  80. package/resources/components/Dashboard/Commerce/CommerceGiftCardDialog.stx +1 -1
  81. package/resources/components/Dashboard/Commerce/CommerceGiftCardsDashboard.stx +35 -119
  82. package/resources/components/Dashboard/Commerce/CommerceGiftCardsTable.stx +3 -3
  83. package/resources/components/Dashboard/Commerce/CommerceManufacturerDialog.stx +1 -1
  84. package/resources/components/Dashboard/Commerce/CommerceManufacturersDashboard.stx +3 -5
  85. package/resources/components/Dashboard/Commerce/CommerceManufacturersTable.stx +2 -2
  86. package/resources/components/Dashboard/Commerce/CommerceOrderDialog.stx +4 -4
  87. package/resources/components/Dashboard/Commerce/CommerceOrdersDashboard.stx +42 -129
  88. package/resources/components/Dashboard/Commerce/CommerceOrdersTable.stx +3 -3
  89. package/resources/components/Dashboard/Commerce/CommerceOverviewDashboard.stx +1 -1
  90. package/resources/components/Dashboard/Commerce/CommerceOverviewOrdersTable.stx +9 -11
  91. package/resources/components/Dashboard/Commerce/CommerceOverviewProductsTable.stx +5 -7
  92. package/resources/components/Dashboard/Commerce/CommerceOverviewStats.stx +14 -16
  93. package/resources/components/Dashboard/Commerce/CommercePaymentsBreakdown.stx +12 -18
  94. package/resources/components/Dashboard/Commerce/CommercePaymentsDashboard.stx +41 -120
  95. package/resources/components/Dashboard/Commerce/CommercePaymentsTable.stx +1 -1
  96. package/resources/components/Dashboard/Commerce/CommercePosCart.stx +13 -15
  97. package/resources/components/Dashboard/Commerce/CommercePosCatalog.stx +17 -19
  98. package/resources/components/Dashboard/Commerce/CommercePosCheckoutDialog.stx +2 -2
  99. package/resources/components/Dashboard/Commerce/CommercePosDashboard.stx +1 -1
  100. package/resources/components/Dashboard/Commerce/CommercePosReceiptDialog.stx +1 -1
  101. package/resources/components/Dashboard/Commerce/CommerceProductDetailDashboard.stx +5 -5
  102. package/resources/components/Dashboard/Commerce/CommerceProductDialog.stx +3 -3
  103. package/resources/components/Dashboard/Commerce/CommerceProductsDashboard.stx +41 -122
  104. package/resources/components/Dashboard/Commerce/CommerceProductsTable.stx +3 -3
  105. package/resources/components/Dashboard/Commerce/CommerceReviewEditDialog.stx +1 -1
  106. package/resources/components/Dashboard/Commerce/CommerceReviewsDashboard.stx +38 -122
  107. package/resources/components/Dashboard/Commerce/CommerceReviewsTable.stx +2 -2
  108. package/resources/components/Dashboard/Commerce/CommerceTaxDialog.stx +3 -3
  109. package/resources/components/Dashboard/Commerce/CommerceTaxesDashboard.stx +5 -4
  110. package/resources/components/Dashboard/Commerce/CommerceTaxesTable.stx +4 -3
  111. package/resources/components/Dashboard/Commerce/CommerceUnitDialog.stx +3 -7
  112. package/resources/components/Dashboard/Commerce/CommerceUnitsDashboard.stx +3 -5
  113. package/resources/components/Dashboard/Commerce/CommerceUnitsTable.stx +2 -2
  114. package/resources/components/Dashboard/Commerce/CommerceVariantDialog.stx +3 -3
  115. package/resources/components/Dashboard/Commerce/CommerceVariantsDashboard.stx +4 -4
  116. package/resources/components/Dashboard/Commerce/CommerceVariantsTable.stx +3 -5
  117. package/resources/components/Dashboard/Commerce/Delivery/CourierDialog.stx +1 -1
  118. package/resources/components/Dashboard/Commerce/Delivery/CouriersDashboard.stx +1 -1
  119. package/resources/components/Dashboard/Commerce/Delivery/CouriersTable.stx +2 -2
  120. package/resources/components/Dashboard/Commerce/Delivery/DeliveryOverviewDashboard.stx +44 -52
  121. package/resources/components/Dashboard/Commerce/Delivery/DeliveryPagination.stx +2 -2
  122. package/resources/components/Dashboard/Commerce/Delivery/DeliveryRouteDialog.stx +1 -1
  123. package/resources/components/Dashboard/Commerce/Delivery/DeliveryRoutesDashboard.stx +1 -1
  124. package/resources/components/Dashboard/Commerce/Delivery/DeliveryRoutesTable.stx +2 -2
  125. package/resources/components/Dashboard/Commerce/Delivery/DigitalDeliveriesDashboard.stx +1 -1
  126. package/resources/components/Dashboard/Commerce/Delivery/DigitalDeliveryTable.stx +2 -2
  127. package/resources/components/Dashboard/Commerce/Delivery/LicenseKeyDialog.stx +3 -3
  128. package/resources/components/Dashboard/Commerce/Delivery/LicenseKeysDashboard.stx +1 -1
  129. package/resources/components/Dashboard/Commerce/Delivery/LicenseKeysTable.stx +2 -2
  130. package/resources/components/Dashboard/Commerce/Delivery/ShippingMethodsDashboard.stx +1 -1
  131. package/resources/components/Dashboard/Commerce/Delivery/ShippingMethodsTable.stx +2 -2
  132. package/resources/components/Dashboard/Commerce/Delivery/ShippingRateDialog.stx +2 -2
  133. package/resources/components/Dashboard/Commerce/Delivery/ShippingRatesDashboard.stx +1 -1
  134. package/resources/components/Dashboard/Commerce/Delivery/ShippingRatesTable.stx +2 -2
  135. package/resources/components/Dashboard/Commerce/Delivery/ShippingZoneDialog.stx +1 -1
  136. package/resources/components/Dashboard/Commerce/Delivery/ShippingZonesDashboard.stx +1 -1
  137. package/resources/components/Dashboard/Commerce/Delivery/ShippingZonesTable.stx +4 -8
  138. package/resources/components/Dashboard/Commerce/PaymentDetailsDialog.stx +1 -3
  139. package/resources/components/Dashboard/Commerce/PrintDeviceBreakdown.stx +9 -15
  140. package/resources/components/Dashboard/Commerce/PrintDeviceDialog.stx +1 -1
  141. package/resources/components/Dashboard/Commerce/PrintDevicesDashboard.stx +3 -3
  142. package/resources/components/Dashboard/Commerce/PrintDevicesTable.stx +3 -3
  143. package/resources/components/Dashboard/Commerce/PrintLogBreakdown.stx +3 -9
  144. package/resources/components/Dashboard/Commerce/PrintLogDetailsDialog.stx +1 -1
  145. package/resources/components/Dashboard/Commerce/PrintLogsDashboard.stx +4 -4
  146. package/resources/components/Dashboard/Commerce/PrintLogsTable.stx +8 -10
  147. package/resources/components/Dashboard/Commerce/ProductWaitlistDashboard.stx +37 -109
  148. package/resources/components/Dashboard/Commerce/ProductWaitlistEntryDialog.stx +3 -3
  149. package/resources/components/Dashboard/Commerce/ProductWaitlistTable.stx +2 -2
  150. package/resources/components/Dashboard/Commerce/RestaurantWaitlistDashboard.stx +38 -112
  151. package/resources/components/Dashboard/Commerce/RestaurantWaitlistEntryDialog.stx +2 -2
  152. package/resources/components/Dashboard/Commerce/RestaurantWaitlistTable.stx +2 -2
  153. package/resources/components/Dashboard/Content/AuthorsDashboard.stx +4 -4
  154. package/resources/components/Dashboard/Content/BlogDashboard.stx +4 -4
  155. package/resources/components/Dashboard/Content/CommentsDashboard.stx +36 -83
  156. package/resources/components/Dashboard/Content/ContentDashboard.stx +12 -14
  157. package/resources/components/Dashboard/Content/ContentTaxonomyDashboard.stx +2 -2
  158. package/resources/components/Dashboard/Content/FileManagerDashboard.stx +8 -12
  159. package/resources/components/Dashboard/Content/FileStoragePanel.stx +6 -10
  160. package/resources/components/Dashboard/Content/FileUploadDialog.stx +1 -3
  161. package/resources/components/Dashboard/Content/PagesDashboard.stx +39 -78
  162. package/resources/components/Dashboard/Content/PostEditorDialog.stx +4 -8
  163. package/resources/components/Dashboard/Content/PostsDashboard.stx +44 -85
  164. package/resources/components/Dashboard/Content/SeoDashboard.stx +5 -4
  165. package/resources/components/Dashboard/Data/DataRecords.stx +140 -12
  166. package/resources/components/Dashboard/Deployments/DeploymentList.stx +4 -4
  167. package/resources/components/Dashboard/Deployments/DeploymentTable.stx +3 -1
  168. package/resources/components/Dashboard/Elements/DropdownNavigation.stx +5 -7
  169. package/resources/components/Dashboard/Email/CapturedMailDashboard.stx +1 -3
  170. package/resources/components/Dashboard/Email/CapturedMailList.stx +18 -20
  171. package/resources/components/Dashboard/Email/EmailActivityDashboard.stx +24 -28
  172. package/resources/components/Dashboard/Email/EmailSettingsList.stx +6 -8
  173. package/resources/components/Dashboard/Email/EmailSettingsNavigation.stx +10 -12
  174. package/resources/components/Dashboard/Email/EmailSidebar.stx +33 -37
  175. package/resources/components/Dashboard/Email/InboxMessageDetail.stx +1 -1
  176. package/resources/components/Dashboard/Email/InboxMessageList.stx +16 -18
  177. package/resources/components/Dashboard/Email/InboxSettingsDashboard.stx +1 -1
  178. package/resources/components/Dashboard/Environment/EnvironmentDashboard.stx +2 -2
  179. package/resources/components/Dashboard/GlobalSearch.stx +19 -21
  180. package/resources/components/Dashboard/Home/DashboardHome.stx +8 -1
  181. package/resources/components/Dashboard/Infrastructure/CloudDashboard.stx +1 -1
  182. package/resources/components/Dashboard/Infrastructure/DnsDashboard.stx +27 -13
  183. package/resources/components/Dashboard/Infrastructure/LogsDashboard.stx +1 -1
  184. package/resources/components/Dashboard/Infrastructure/MailboxesDashboard.stx +46 -8
  185. package/resources/components/Dashboard/Infrastructure/ServerlessDashboard.stx +1 -1
  186. package/resources/components/Dashboard/Infrastructure/ServersDashboard.stx +1 -1
  187. package/resources/components/Dashboard/Jobs/JobDetail.stx +1 -1
  188. package/resources/components/Dashboard/Jobs/JobHistory.stx +44 -57
  189. package/resources/components/Dashboard/Jobs/JobTable.stx +23 -25
  190. package/resources/components/Dashboard/Kanban/KanbanCardDialog.stx +1 -1
  191. package/resources/components/Dashboard/Library/ComponentsDashboard.stx +1 -1
  192. package/resources/components/Dashboard/Management/AssignmentDrawer.stx +5 -7
  193. package/resources/components/Dashboard/Management/PermissionsDashboard.stx +35 -43
  194. package/resources/components/Dashboard/Marketing/AbandonedCartsDashboard.stx +11 -13
  195. package/resources/components/Dashboard/Marketing/CampaignDialog.stx +1 -3
  196. package/resources/components/Dashboard/Marketing/CampaignsDashboard.stx +2 -2
  197. package/resources/components/Dashboard/Marketing/CampaignsTable.stx +2 -2
  198. package/resources/components/Dashboard/Marketing/MarketingListsDashboard.stx +1 -1
  199. package/resources/components/Dashboard/Marketing/MarketingListsTable.stx +2 -2
  200. package/resources/components/Dashboard/Marketing/SocialPostDialog.stx +1 -3
  201. package/resources/components/Dashboard/Marketing/SocialPostsDashboard.stx +2 -2
  202. package/resources/components/Dashboard/Marketing/SocialPostsTable.stx +2 -2
  203. package/resources/components/Dashboard/Models/ModelRecordActions.stx +11 -2
  204. package/resources/components/Dashboard/Models/ModelRecordCreate.stx +193 -0
  205. package/resources/components/Dashboard/Models/ModelRecordDetail.stx +144 -0
  206. package/resources/components/Dashboard/Models/ModelRecordEdit.stx +176 -0
  207. package/resources/components/Dashboard/Models/ModelRecordsDashboard.stx +52 -186
  208. package/resources/components/Dashboard/Models/ModelsOverview.stx +2 -4
  209. package/resources/components/Dashboard/Monitoring/ErrorDashboard.stx +47 -81
  210. package/resources/components/Dashboard/Monitoring/ErrorTable.stx +4 -2
  211. package/resources/components/Dashboard/NotFoundDashboard.stx +4 -4
  212. package/resources/components/Dashboard/Notifications/NotificationDeliveryHistory.stx +43 -77
  213. package/resources/components/Dashboard/Notifications/NotificationDeliveryOverview.stx +15 -17
  214. package/resources/components/Dashboard/Notifications/NotificationDeliveryTable.stx +1 -1
  215. package/resources/components/Dashboard/Operations/AuditDashboard.stx +1 -1
  216. package/resources/components/Dashboard/Operations/ChangeDashboard.stx +1 -1
  217. package/resources/components/Dashboard/Operations/IncidentDashboard.stx +1 -1
  218. package/resources/components/Dashboard/Operations/MigrationDashboard.stx +2 -2
  219. package/resources/components/Dashboard/Operations/RecoveryDashboard.stx +1 -1
  220. package/resources/components/Dashboard/Operations/SchedulerDashboard.stx +1 -1
  221. package/resources/components/Dashboard/Queries/QueryDashboard.stx +60 -86
  222. package/resources/components/Dashboard/Queries/QueryDetail.stx +5 -9
  223. package/resources/components/Dashboard/Realtime/RealtimeDashboard.stx +6 -8
  224. package/resources/components/Dashboard/Remote/RemoteConsole.stx +14 -20
  225. package/resources/components/Dashboard/Settings/AppearanceSettingsDashboard.stx +48 -54
  226. package/resources/components/Dashboard/Settings/MailSettingsDashboard.stx +8 -8
  227. package/resources/components/Dashboard/Settings/SettingsDashboard.stx +43 -47
  228. package/resources/components/Dashboard/Teams/TeamInvitationDashboard.stx +2 -2
  229. package/resources/components/Dashboard/UI/ActivityTable.stx +2 -1
  230. package/resources/components/Dashboard/UI/Button.stx +15 -0
  231. package/resources/components/Dashboard/UI/MetricCards.stx +5 -7
  232. package/resources/components/Dashboard/UI/Pagination.stx +3 -5
  233. package/resources/components/Dashboard/UI/QuickLinks.stx +2 -2
  234. package/resources/components/Dashboard/UI/Select.stx +1 -0
  235. package/resources/components/Dashboard/UI/Table.stx +139 -96
  236. package/resources/components/Dashboard/UI/Tabs.stx +18 -20
  237. package/routes/dashboard-api.ts +2 -0
  238. package/routes/dashboard.ts +246 -253
  239. package/routes/storefront.ts +31 -0
  240. package/stx-components-plugin.ts +12 -1
  241. package/views/dashboard/content/categories/index.stx +1 -1
  242. package/views/dashboard/content/tags/index.stx +1 -1
  243. package/views/dashboard/layouts/default.stx +27 -12
  244. package/views/dashboard/models/[model]/[id]/edit.stx +8 -0
  245. package/views/dashboard/models/[model]/[id].stx +8 -0
  246. package/views/dashboard/models/[model]/create.stx +8 -0
  247. package/resources/components/Dashboard/CreateRecordModal.stx +0 -138
  248. package/resources/components/Dashboard/Models/EditRecordModal.stx +0 -81
@@ -23,6 +23,10 @@ export default defineModel({
23
23
  },
24
24
  },
25
25
 
26
+ // Cascade, as the framework's own key repair has always made it
27
+ // (ensureNotificationForeignKeys): a user's delivery log goes with the user.
28
+ belongsTo: [{ model: 'User', onDelete: 'cascade' }],
29
+
26
30
  attributes: {
27
31
  userId: {
28
32
  required: false,
@@ -100,7 +100,16 @@ export default defineModel({
100
100
  },
101
101
  },
102
102
 
103
- factory: faker => faker.internet.email(),
103
+ // Built from the name seeded above it, so a demo user reads as one
104
+ // person: "Alex Castillo" was seeded as kimberly.lee@..., and every row
105
+ // of the dashboard's Users page looked like a data error. Titles and
106
+ // suffixes ("Dr.", "Jr.") are not part of anyone's address.
107
+ factory: (faker, { name }) => {
108
+ const words = String(name ?? '').split(/\s+/).filter(word => word && !word.endsWith('.') && !/^(?:jr|sr|ii|iii|iv|md|phd|dds)$/i.test(word))
109
+ if (words.length === 0)
110
+ return faker.internet.email()
111
+ return faker.internet.email({ firstName: words[0], lastName: words.at(-1) }).toLowerCase()
112
+ },
104
113
  },
105
114
  password: {
106
115
  personal: { export: false },
package/bootstrap.ts CHANGED
@@ -96,8 +96,9 @@ async function registerDefaultBundles(): Promise<void> {
96
96
  if (mounts('auth'))
97
97
  await route.register(frameworkPath('defaults/routes/auth.ts'))
98
98
 
99
- // The rest of dashboard.ts: email subscribe, storefront cart/checkout,
100
- // reviews, sitemap, AI, voice, and the admin dashboard's REST surface. Still
99
+ // The rest of dashboard.ts: email subscribe, sitemap, AI, voice, and the
100
+ // admin dashboard's REST surface (its CMS and commerce groups follow their
101
+ // features). The storefront moved to its own bundle below. Still
101
102
  // one file and still one gate — splitting auth out was the case with a
102
103
  // reporter behind it; marketing.ts / commerce.ts / monitoring.ts remain the
103
104
  // obvious next cuts.
@@ -164,6 +165,13 @@ async function registerDefaultBundles(): Promise<void> {
164
165
  await route.register(frameworkPath('defaults/routes/delivery.ts'))
165
166
  }
166
167
 
168
+ // The storefront: cart, checkout and buyer reviews, behind the default
169
+ // `cart`, `checkout` and `orders` pages. Gated with the commerce surface, so
170
+ // an app without commerce neither mounts these routes nor serves the pages.
171
+ if (mounts('storefront')) {
172
+ await route.register(frameworkPath('defaults/routes/storefront.ts'))
173
+ }
174
+
167
175
  // The payment provider's webhook, which applies payments and refunds to
168
176
  // orders. Gated with the commerce surface; it answers 401 until the driver's
169
177
  // webhook secret is configured.
@@ -0,0 +1,21 @@
1
+ /**
2
+ * Tax types as a reader meets them in the dashboard.
3
+ *
4
+ * A tax rate's `type` is free text the store owner chooses, and the common
5
+ * ones are acronyms: "GST" and "VAT" mean nothing to someone who has never
6
+ * run a shop in a country that charges them. A known type reads with its
7
+ * meaning beside it; anything else reads exactly as written.
8
+ */
9
+ const MEANINGS: Record<string, string> = {
10
+ GST: 'goods and services tax',
11
+ HST: 'harmonized sales tax',
12
+ PST: 'provincial sales tax',
13
+ QST: 'Quebec sales tax',
14
+ VAT: 'value-added tax',
15
+ }
16
+
17
+ /** `GST` reads as "GST (goods and services tax)"; an unknown type is unchanged. */
18
+ export function taxTypeLabel(type: string): string {
19
+ const meaning = MEANINGS[type.trim().toUpperCase()]
20
+ return meaning ? `${type} (${meaning})` : type
21
+ }
@@ -278,6 +278,22 @@ describe('useServerList', () => {
278
278
  expect(api.asked[1]!.has('status')).toBe(false)
279
279
  })
280
280
 
281
+ it('sends no sort for a list with no order to choose', async () => {
282
+ const api = server()
283
+ const list = useServerList<string>({ fetch: api.fetch })
284
+ void list.load()
285
+ expect(api.asked[0]!.toString()).toBe('page=1&per_page=25')
286
+ })
287
+
288
+ it('sends the search under the name the endpoint reads', async () => {
289
+ const api = server()
290
+ const list = useServerList<string>({ fetch: api.fetch, defaultSort: { sort: 'id', direction: 'asc' }, searchDelay: 5, searchParam: 'search' })
291
+ list.search.set('hello')
292
+ await sleep(20)
293
+ expect(api.asked[0]!.get('search')).toBe('hello')
294
+ expect(api.asked[0]!.has('q')).toBe(false)
295
+ })
296
+
281
297
  it('sends the search once typing pauses', async () => {
282
298
  const api = server()
283
299
  const list = useServerList<string>({ fetch: api.fetch, defaultSort: { sort: 'id', direction: 'asc' }, searchDelay: 20 })
@@ -265,16 +265,17 @@ export interface ServerListPage<T> {
265
265
 
266
266
  export interface ServerListOptions<T> {
267
267
  /**
268
- * Ask for one page. `params` carries `sort`, `direction`, `q`, the filters,
268
+ * Ask for one page. `params` carries `sort`, `direction`, the search, the filters,
269
269
  * `page` and `per_page`, as the commerce list endpoints read them.
270
270
  */
271
271
  fetch: (params: URLSearchParams) => Promise<ServerListPage<T>>
272
272
  /**
273
273
  * The order before any column header is clicked. An accessor when the page
274
274
  * has a sort select: changing it hands the order back from a header sort
275
- * and asks for page 1.
275
+ * and asks for page 1. Left out for a list with no order to choose, which
276
+ * then sends no sort at all.
276
277
  */
277
- defaultSort: { sort: string, direction: 'asc' | 'desc' } | (() => { sort: string, direction: 'asc' | 'desc' })
278
+ defaultSort?: { sort: string, direction: 'asc' | 'desc' } | (() => { sort: string, direction: 'asc' | 'desc' })
278
279
  /** The table's sortable column keys, as the server's sort names. A column not listed returns to `defaultSort`. */
279
280
  columnSorts?: Record<string, string>
280
281
  /** The filter values, read reactively: a change asks for page 1. `''` or `'all'` leaves a filter out. */
@@ -283,6 +284,11 @@ export interface ServerListOptions<T> {
283
284
  perPage?: number
284
285
  /** How long typing pauses before the search is sent. Default 250ms. */
285
286
  searchDelay?: number
287
+ /**
288
+ * The query parameter the search is sent as. Default `q`, as the commerce
289
+ * lists read it; the content lists read `search`.
290
+ */
291
+ searchParam?: string
286
292
  /** Called with whatever a load threw, after `loadError` is set. */
287
293
  onError?: (error: unknown) => void
288
294
  /** Called with each answer that lands, for anything else it carries (a summary, choices). */
@@ -341,10 +347,12 @@ export function useServerList<T>(options: ServerListOptions<T>): ServerList<T> {
341
347
  const params = (): URLSearchParams => {
342
348
  const query = new URLSearchParams()
343
349
  const order = headerSort() ?? defaultOrder()
344
- query.set('sort', order.sort)
345
- query.set('direction', order.direction)
350
+ if (order) {
351
+ query.set('sort', order.sort)
352
+ query.set('direction', order.direction)
353
+ }
346
354
  if (appliedSearch())
347
- query.set('q', appliedSearch())
355
+ query.set(options.searchParam ?? 'q', appliedSearch())
348
356
  for (const [name, value] of Object.entries(options.filters?.() ?? {})) {
349
357
  if (value !== '' && value !== 'all')
350
358
  query.set(name, value)
@@ -0,0 +1,139 @@
1
+ import { describe, expect, it } from 'bun:test'
2
+ import { DashboardApiError } from './dashboard-api'
3
+ import { changedModelFields, modelCreateFailure, modelRecordBackHref, modelRecordCreateHref, modelRecordEditHref, modelRecordFields, modelRecordHref, modelRecordListLabel, modelRecordSections, modelRecordTitle } from './dashboard-model-record'
4
+ import type { ModelRecord } from './dashboard-model-record'
5
+
6
+ const record: ModelRecord = {
7
+ modelName: 'Team',
8
+ row: { id: 4, name: 'PrimeSoft Ltd', description: null, status: 'active', created_at: '2026-08-08' },
9
+ columns: [
10
+ { name: 'id', label: 'Id', type: 'number' },
11
+ { name: 'name', label: 'Name', type: 'text' },
12
+ { name: 'description', label: 'Description', type: 'text' },
13
+ { name: 'status', label: 'Status', type: 'text' },
14
+ { name: 'created_at', label: 'Created At', type: 'date' },
15
+ ],
16
+ updateColumns: ['name', 'description', 'status'],
17
+ writeCapabilities: { create: true, update: true, destroy: true },
18
+ }
19
+
20
+ describe('a model record in the dashboard dialog', () => {
21
+ it('lets the pencil change only the writable columns', () => {
22
+ const fields = modelRecordFields(record)
23
+ expect(fields.map(field => field.name)).toEqual(['id', 'name', 'description', 'status', 'created_at'])
24
+ expect(fields.filter(field => !field.readonly).map(field => field.name)).toEqual(['name', 'description', 'status'])
25
+ expect(fields.find(field => field.name === 'description')?.value).toBe('')
26
+ })
27
+
28
+ it('sends only what an edit changed, an emptied field as null', () => {
29
+ expect(changedModelFields(record.row, { name: 'PrimeSoft Ltd', description: '', status: 'inactive' })).toEqual({ status: 'inactive' })
30
+ expect(changedModelFields(record.row, { name: '', description: 'Cloud', status: 'active' })).toEqual({ name: null, description: 'Cloud' })
31
+ expect(changedModelFields(record.row, { name: 'PrimeSoft Ltd' })).toEqual({})
32
+ })
33
+ })
34
+
35
+ describe('a model record on its own page', () => {
36
+ const user: ModelRecord = {
37
+ modelName: 'User',
38
+ tableName: 'users',
39
+ row: { id: 13, uuid: null, name: 'Ava', email: 'ava@example.com', avatar: null, status: 'active', two_factor_enabled: 0, login_count: 4, team_id: 2, meta: { plan: 'pro' }, created_at: '2026-11-05T23:01:51.038Z', updated_at: null, email_verified_at: null },
40
+ columns: [
41
+ { name: 'id', label: 'ID', type: 'number' },
42
+ { name: 'uuid', label: 'Uuid', type: 'text' },
43
+ { name: 'name', label: 'Name', type: 'text' },
44
+ { name: 'email', label: 'Email', type: 'text' },
45
+ { name: 'avatar', label: 'Avatar', type: 'text' },
46
+ { name: 'status', label: 'Status', type: 'text' },
47
+ { name: 'two_factor_enabled', label: 'Two Factor Enabled', type: 'boolean' },
48
+ { name: 'login_count', label: 'Login Count', type: 'number' },
49
+ { name: 'team_id', label: 'Team ID', type: 'number' },
50
+ { name: 'meta', label: 'Meta', type: 'json' },
51
+ { name: 'created_at', label: 'Created At', type: 'date' },
52
+ { name: 'updated_at', label: 'Updated At', type: 'date' },
53
+ { name: 'email_verified_at', label: 'Email Verified At', type: 'text' },
54
+ ],
55
+ updateColumns: [],
56
+ writeCapabilities: { create: true, update: false, destroy: false },
57
+ }
58
+
59
+ it('groups the fields into the cards of the page', () => {
60
+ const sections = modelRecordSections(user)
61
+ expect(sections.map(section => [section.id, section.title, section.columns])).toEqual([
62
+ ['information', 'User Information', 1],
63
+ ['details', 'User Details', 2],
64
+ ['identifiers', 'Identifiers', 2],
65
+ ['timestamps', 'Timestamps', 2],
66
+ ])
67
+ const names = Object.fromEntries(sections.map(section => [section.id, section.details.map(detail => detail.name)]))
68
+ expect(names.information).toEqual(['name', 'email', 'avatar', 'meta'])
69
+ expect(names.details).toEqual(['status', 'two_factor_enabled', 'login_count'])
70
+ expect(names.identifiers).toEqual(['id', 'uuid', 'team_id'])
71
+ expect(names.timestamps).toEqual(['created_at', 'updated_at', 'email_verified_at'])
72
+ })
73
+
74
+ it('reads each value as a person would, and says what is missing', () => {
75
+ const by = Object.fromEntries(modelRecordSections(user).flatMap(section => section.details).map(detail => [detail.name, detail]))
76
+ expect(by.avatar).toMatchObject({ value: 'No avatar', empty: true })
77
+ expect(by.uuid).toMatchObject({ label: 'UUID', value: 'No UUID', empty: true })
78
+ expect(by.status).toMatchObject({ value: 'Active', kind: 'badge' })
79
+ expect(by.two_factor_enabled).toMatchObject({ value: 'No', kind: 'boolean', yes: false, empty: false })
80
+ expect(by.meta).toMatchObject({ kind: 'json', wide: true })
81
+ expect(by.meta!.value).toContain('"plan": "pro"')
82
+ // A date reads as a date, and its label drops the "At".
83
+ expect(by.created_at!.label).toBe('Created')
84
+ expect(by.created_at!.value).not.toContain('T23:01')
85
+ expect(by.created_at!.value).toContain('2026')
86
+ expect(by.updated_at).toMatchObject({ label: 'Last Updated', value: 'Not yet', empty: true })
87
+ expect(by.email_verified_at).toMatchObject({ label: 'Email Verified', value: 'Not yet', empty: true })
88
+ })
89
+
90
+ it('leaves out a card with nothing in it', () => {
91
+ const sections = modelRecordSections({ ...user, columns: user.columns.filter(column => column.name === 'name') })
92
+ expect(sections.map(section => section.id)).toEqual(['information'])
93
+ })
94
+
95
+ it('names the list in the breadcrumb', () => {
96
+ expect(modelRecordListLabel(user, '/data/users')).toBe('Users')
97
+ expect(modelRecordListLabel({ ...user, tableName: 'product_categories' }, '/models/product-category')).toBe('Product Categories')
98
+ expect(modelRecordListLabel(null, '/models/user')).toBe('Records')
99
+ })
100
+
101
+ it('names the record by what it is called, else by its id', () => {
102
+ expect(modelRecordTitle(record)).toBe('PrimeSoft Ltd')
103
+ expect(modelRecordTitle({ ...record, row: { id: 9, email: 'ava@example.com' } })).toBe('ava@example.com')
104
+ expect(modelRecordTitle({ ...record, row: { id: 9 } })).toBe('Team 9')
105
+ })
106
+
107
+ it('links to the page and back to the list it came from', () => {
108
+ expect(modelRecordHref('user', 13)).toBe('/models/user/13')
109
+ expect(modelRecordHref('user', 13, '/data/users')).toBe('/models/user/13?from=%2Fdata%2Fusers')
110
+ expect(modelRecordBackHref('user', '/data/users')).toBe('/data/users')
111
+ expect(modelRecordBackHref('user', null)).toBe('/models/user')
112
+ })
113
+
114
+ it('links to the edit page, remembering where the visitor came from', () => {
115
+ expect(modelRecordEditHref('team', 1)).toBe('/models/team/1/edit')
116
+ expect(modelRecordEditHref('team', 1, { from: '/data/teams' })).toBe('/models/team/1/edit?from=%2Fdata%2Fteams')
117
+ expect(modelRecordEditHref('team', 1, { from: '/data/teams', via: 'view' })).toBe('/models/team/1/edit?from=%2Fdata%2Fteams&via=view')
118
+ expect(modelRecordEditHref('team', 1, { via: 'view' })).toBe('/models/team/1/edit?via=view')
119
+ })
120
+
121
+ it('never goes back to an address outside the dashboard', () => {
122
+ for (const from of ['//evil.example', 'https://evil.example', 'javascript:alert(1)', '/data/users?x=<script>'])
123
+ expect(modelRecordBackHref('user', from)).toBe('/models/user')
124
+ })
125
+ })
126
+
127
+ describe('creating a model record', () => {
128
+ it('links to the create page, remembering the list to return to', () => {
129
+ expect(modelRecordCreateHref('team')).toBe('/models/team/create')
130
+ expect(modelRecordCreateHref('team', '/data/teams')).toBe('/models/team/create?from=%2Fdata%2Fteams')
131
+ })
132
+
133
+ it('reports a refusal in one shape, with each field\'s message under its field', () => {
134
+ expect(modelCreateFailure(new DashboardApiError('The name is required.', 422, { name: 'The name is required.' })))
135
+ .toEqual({ ok: false, error: 'The name is required.', errors: { name: ['The name is required.'] } })
136
+ expect(modelCreateFailure(new DashboardApiError('Server error', 500))).toEqual({ ok: false, error: 'Server error', errors: {} })
137
+ expect(modelCreateFailure(new Error('offline'))).toEqual({ ok: false, error: 'offline', errors: {} })
138
+ })
139
+ })
@@ -0,0 +1,353 @@
1
+ /**
2
+ * One model record, read and written through the dashboard's generic model
3
+ * API (`/api/dashboard/models/{slug}`): the record's own page
4
+ * (`/models/{slug}/{id}`, where the eye leads), its edit page
5
+ * (`/models/{slug}/{id}/edit`, where the pencil leads), the page that creates
6
+ * one (`/models/{slug}/create`), and the trash on a page that lists records
7
+ * of its own - Users, Teams and Subscribers.
8
+ *
9
+ * What a page may do comes from the model, not the page: `writeCapabilities`
10
+ * follows the model's `useApi` routes, so a model that does not expose
11
+ * `update` or `destroy` (User, on purpose: its rows are personal data) offers
12
+ * the eye and nothing else.
13
+ */
14
+ import { DashboardApiError, dashboardApi } from './dashboard-api'
15
+
16
+ export interface ModelWriteCapabilities {
17
+ create: boolean
18
+ update: boolean
19
+ destroy: boolean
20
+ }
21
+
22
+ export interface ModelColumn {
23
+ name: string
24
+ label: string
25
+ type?: 'number' | 'boolean' | 'date' | 'json' | 'text'
26
+ }
27
+
28
+ export interface ModelRecord {
29
+ modelName: string
30
+ /** The model's table, e.g. `product_categories`. Names the list in the breadcrumb. */
31
+ tableName?: string
32
+ row: Record<string, unknown>
33
+ columns: ModelColumn[]
34
+ /** The columns an edit may change: fillable attributes and declared keys. */
35
+ updateColumns: string[]
36
+ writeCapabilities: ModelWriteCapabilities
37
+ }
38
+
39
+ export interface ModelRecordField {
40
+ name: string
41
+ label: string
42
+ value: string
43
+ readonly: boolean
44
+ }
45
+
46
+ interface ModelShowResponse {
47
+ modelName?: string
48
+ tableName?: string
49
+ createFields?: ModelCreateField[]
50
+ rows?: Array<Record<string, unknown>>
51
+ columnMeta?: ModelColumn[]
52
+ updateColumns?: string[]
53
+ writeCapabilities?: ModelWriteCapabilities
54
+ error?: string | null
55
+ }
56
+
57
+ /** A field of the create form, from the model's fillable attributes. */
58
+ export interface ModelCreateField {
59
+ name: string
60
+ label: string
61
+ type: 'boolean' | 'date' | 'datetime' | 'email' | 'enum' | 'number' | 'text'
62
+ required: boolean
63
+ defaultValue: unknown
64
+ options: string[]
65
+ }
66
+
67
+ export interface ModelCreateForm {
68
+ modelName: string
69
+ tableName?: string
70
+ fields: ModelCreateField[]
71
+ /** Whether the model's API has a store route at all. */
72
+ canCreate: boolean
73
+ }
74
+
75
+ const NO_WRITES: ModelWriteCapabilities = { create: false, update: false, destroy: false }
76
+
77
+ function modelPath(slug: string): string {
78
+ return `/api/dashboard/models/${encodeURIComponent(slug)}`
79
+ }
80
+
81
+ /** What the model lets the dashboard do, without loading any rows of note. */
82
+ export async function fetchModelCapabilities(slug: string): Promise<ModelWriteCapabilities> {
83
+ const data = await dashboardApi<ModelShowResponse>(`${modelPath(slug)}?perPage=1`)
84
+ return data.writeCapabilities ?? NO_WRITES
85
+ }
86
+
87
+ /** What the create page needs: the model's name and the fields a new record takes. */
88
+ export async function fetchModelCreateForm(slug: string): Promise<ModelCreateForm> {
89
+ const data = await dashboardApi<ModelShowResponse>(`${modelPath(slug)}?perPage=1`)
90
+ if (data.error)
91
+ throw new Error(data.error)
92
+ return {
93
+ modelName: data.modelName || 'Record',
94
+ tableName: data.tableName,
95
+ fields: data.createFields ?? [],
96
+ canCreate: Boolean(data.writeCapabilities?.create),
97
+ }
98
+ }
99
+
100
+ /** Every stored column of one record, with what an edit may change. */
101
+ export async function fetchModelRecord(slug: string, id: string | number): Promise<ModelRecord> {
102
+ const filters = encodeURIComponent(JSON.stringify({ id: String(id) }))
103
+ const data = await dashboardApi<ModelShowResponse>(`${modelPath(slug)}?perPage=1&filters=${filters}`)
104
+ if (data.error)
105
+ throw new Error(data.error)
106
+ const row = data.rows?.find(candidate => String(candidate.id) === String(id))
107
+ if (!row)
108
+ throw new Error(`${data.modelName || 'Record'} ${id} was not found.`)
109
+ return {
110
+ modelName: data.modelName || 'Record',
111
+ tableName: data.tableName,
112
+ row,
113
+ columns: data.columnMeta ?? [],
114
+ updateColumns: data.updateColumns ?? [],
115
+ writeCapabilities: data.writeCapabilities ?? NO_WRITES,
116
+ }
117
+ }
118
+
119
+ function text(value: unknown): string {
120
+ return value === null || value === undefined ? '' : String(value)
121
+ }
122
+
123
+ /**
124
+ * The edit dialog's fields for a record: the writable columns can change, and
125
+ * the rest stay visible, read-only, as context.
126
+ */
127
+ export function modelRecordFields(record: ModelRecord): ModelRecordField[] {
128
+ return record.columns.map(column => ({
129
+ name: column.name,
130
+ label: column.label,
131
+ value: text(record.row[column.name]),
132
+ readonly: !record.updateColumns.includes(column.name),
133
+ }))
134
+ }
135
+
136
+ export interface ModelRecordDetail {
137
+ name: string
138
+ label: string
139
+ /** As a person reads it: a date in their locale, Yes or No, formatted JSON. */
140
+ value: string
141
+ /** Nothing is stored in this column; `value` then says so ("No email"). */
142
+ empty: boolean
143
+ /**
144
+ * How the value is drawn: plain text, an outlined badge for a status-like
145
+ * word, a check or cross for a boolean, a preformatted block for JSON.
146
+ */
147
+ kind: 'text' | 'badge' | 'boolean' | 'json'
148
+ /** A boolean's answer, for the icon. */
149
+ yes: boolean
150
+ /** Takes the card's full width: long text and JSON. */
151
+ wide: boolean
152
+ }
153
+
154
+ export interface ModelRecordSection {
155
+ id: 'information' | 'details' | 'identifiers' | 'timestamps'
156
+ title: string
157
+ /** One field per row, or two side by side. */
158
+ columns: 1 | 2
159
+ details: ModelRecordDetail[]
160
+ }
161
+
162
+ /** Columns whose value is one word out of a few: drawn as a badge. */
163
+ const BADGE_COLUMNS = new Set(['status', 'state', 'type', 'role', 'source', 'plan', 'category', 'kind', 'channel', 'driver', 'priority', 'visibility', 'guard_name', 'provider', 'locale', 'currency'])
164
+
165
+ function isIdentifier(name: string): boolean {
166
+ return name === 'id' || name === 'uuid' || name.endsWith('_id') || name.endsWith('_uuid')
167
+ }
168
+
169
+ function isDate(column: ModelColumn): boolean {
170
+ return column.type === 'date' || /_(?:at|on)$/.test(column.name)
171
+ }
172
+
173
+ /** "Created At" reads as "Created", and the update time as "Last Updated". */
174
+ function detailLabel(column: ModelColumn): string {
175
+ if (column.name === 'updated_at')
176
+ return 'Last Updated'
177
+ if (column.name === 'uuid')
178
+ return 'UUID'
179
+ return isDate(column) ? column.label.replace(/\s+(?:At|On)$/i, '') : column.label
180
+ }
181
+
182
+ /** "No email", "No stripe ID": lower case, except a word that is an acronym. */
183
+ function emptyText(column: ModelColumn, label: string): string {
184
+ if (isDate(column))
185
+ return 'Not yet'
186
+ return `No ${label.split(' ').map(word => word === word.toUpperCase() ? word : word.toLowerCase()).join(' ')}`
187
+ }
188
+
189
+ function titleCase(words: string): string {
190
+ return words.replace(/[_-]+/g, ' ').replace(/\b[a-z]/g, letter => letter.toUpperCase())
191
+ }
192
+
193
+ function detail(record: ModelRecord, column: ModelColumn): ModelRecordDetail {
194
+ const stored = record.row[column.name]
195
+ const label = detailLabel(column)
196
+ const base = { name: column.name, label, yes: false, wide: false }
197
+ if (column.type === 'boolean') {
198
+ const yes = stored === true || stored === 1 || stored === '1'
199
+ return { ...base, value: yes ? 'Yes' : 'No', empty: false, kind: 'boolean', yes }
200
+ }
201
+ if (stored === null || stored === undefined || stored === '')
202
+ return { ...base, value: emptyText(column, label), empty: true, kind: 'text' }
203
+ if (isDate(column)) {
204
+ const date = new Date(stored as string | number)
205
+ const value = Number.isNaN(date.getTime()) ? String(stored) : new Intl.DateTimeFormat(undefined, { dateStyle: 'medium', timeStyle: 'short' }).format(date)
206
+ return { ...base, value, empty: false, kind: 'text' }
207
+ }
208
+ if (typeof stored === 'object') {
209
+ let value = String(stored)
210
+ try {
211
+ value = JSON.stringify(stored, null, 2)
212
+ }
213
+ catch {}
214
+ return { ...base, value, empty: false, kind: 'json', wide: true }
215
+ }
216
+ const value = String(stored)
217
+ if (BADGE_COLUMNS.has(column.name) && value.length <= 32)
218
+ return { ...base, value: titleCase(value), empty: false, kind: 'badge' }
219
+ return { ...base, value, empty: false, kind: 'text', wide: value.length > 80 }
220
+ }
221
+
222
+ /**
223
+ * A record's fields as the cards of its page: what it is, its settings, the
224
+ * ids that tie it to other records, and when things happened to it. A card
225
+ * with nothing in it is left out.
226
+ */
227
+ export function modelRecordSections(record: ModelRecord): ModelRecordSection[] {
228
+ const groups: Record<ModelRecordSection['id'], ModelRecordDetail[]> = { information: [], details: [], identifiers: [], timestamps: [] }
229
+ for (const column of record.columns) {
230
+ const entry = detail(record, column)
231
+ if (isIdentifier(column.name))
232
+ groups.identifiers.push(entry)
233
+ else if (isDate(column))
234
+ groups.timestamps.push(entry)
235
+ else if (column.type === 'boolean' || column.type === 'number' || BADGE_COLUMNS.has(column.name))
236
+ groups.details.push(entry)
237
+ else
238
+ groups.information.push(entry)
239
+ }
240
+ const sections: ModelRecordSection[] = [
241
+ { id: 'information', title: `${record.modelName} Information`, columns: 1, details: groups.information },
242
+ { id: 'details', title: `${record.modelName} Details`, columns: 2, details: groups.details },
243
+ { id: 'identifiers', title: 'Identifiers', columns: 2, details: groups.identifiers },
244
+ { id: 'timestamps', title: 'Timestamps', columns: 2, details: groups.timestamps },
245
+ ]
246
+ return sections.filter(section => section.details.length > 0)
247
+ }
248
+
249
+ /** The list a record belongs to, as the breadcrumb names it: "Users", "Product Categories". */
250
+ export function modelRecordListLabel(record: { tableName?: string } | null, backHref: string): string {
251
+ const last = backHref.split('/').filter(Boolean).pop() || ''
252
+ if (backHref.startsWith('/data/') && last)
253
+ return titleCase(last)
254
+ return record?.tableName ? titleCase(record.tableName) : 'Records'
255
+ }
256
+
257
+ /** What to call a record in a heading: its name, title or email, else its id. */
258
+ export function modelRecordTitle(record: ModelRecord): string {
259
+ for (const key of ['name', 'title', 'email', 'subject']) {
260
+ const value = record.row[key]
261
+ if (typeof value === 'string' && value.trim())
262
+ return value
263
+ }
264
+ return `${record.modelName} ${text(record.row.id)}`
265
+ }
266
+
267
+ /** The record's own page. `from` is the list to go back to, when it is not the model's own. */
268
+ export function modelRecordHref(slug: string, id: string | number, from?: string): string {
269
+ const path = `/models/${encodeURIComponent(slug)}/${encodeURIComponent(String(id))}`
270
+ return from ? `${path}?from=${encodeURIComponent(from)}` : path
271
+ }
272
+
273
+ /** The page that creates a record. `from` is the list to return to. */
274
+ export function modelRecordCreateHref(slug: string, from?: string): string {
275
+ const path = `/models/${encodeURIComponent(slug)}/create`
276
+ return from ? `${path}?from=${encodeURIComponent(from)}` : path
277
+ }
278
+
279
+ /**
280
+ * The record's edit page, where the pencil leads. `from` is the list the
281
+ * visitor came from. `via: 'view'` means they came from the record's own
282
+ * page, so saving or cancelling returns there instead of to the list.
283
+ */
284
+ export function modelRecordEditHref(slug: string, id: string | number, options: { from?: string, via?: 'view' } = {}): string {
285
+ const path = `/models/${encodeURIComponent(slug)}/${encodeURIComponent(String(id))}/edit`
286
+ const query = [
287
+ options.from ? `from=${encodeURIComponent(options.from)}` : '',
288
+ options.via ? `via=${options.via}` : '',
289
+ ].filter(Boolean).join('&')
290
+ return query ? `${path}?${query}` : path
291
+ }
292
+
293
+ /**
294
+ * Where "back" goes: the list the visitor came from when it is a path inside
295
+ * the dashboard, else the model's records. Never an outside address.
296
+ */
297
+ export function modelRecordBackHref(slug: string, from: string | null | undefined): string {
298
+ return from && /^\/(?!\/)[\w\-/]*$/.test(from) ? from : `/models/${encodeURIComponent(slug)}`
299
+ }
300
+
301
+ /**
302
+ * The fields an edit actually changed, as the model API takes them: a value
303
+ * the editor merely displayed is never sent, and an emptied field is null.
304
+ */
305
+ export function changedModelFields(row: Record<string, unknown>, values: Record<string, string>): Record<string, unknown> {
306
+ const fields: Record<string, unknown> = {}
307
+ for (const [column, value] of Object.entries(values)) {
308
+ if (value !== text(row[column]))
309
+ fields[column] = value === '' ? null : value
310
+ }
311
+ return fields
312
+ }
313
+
314
+ export async function updateModelRecord(slug: string, id: string | number, fields: Record<string, unknown>): Promise<void> {
315
+ const result = await dashboardApi<{ ok: boolean, error?: string }>(`${modelPath(slug)}/${encodeURIComponent(String(id))}`, { method: 'PATCH', body: { fields } })
316
+ if (!result?.ok)
317
+ throw new Error(result?.error || 'The update was rejected.')
318
+ }
319
+
320
+ export type ModelCreateResult
321
+ = | { ok: true, id: string | number | null }
322
+ | { ok: false, error: string, errors: Record<string, string[]> }
323
+
324
+ /**
325
+ * Why a create was refused, in one shape: the message for the top of the form
326
+ * and the messages under each field. The API answers a refusal two ways, as a
327
+ * body with `ok: false` or as an error status carrying `fields`.
328
+ */
329
+ export function modelCreateFailure(reason: unknown): { ok: false, error: string, errors: Record<string, string[]> } {
330
+ if (reason instanceof DashboardApiError) {
331
+ const errors = Object.fromEntries(Object.entries(reason.fields ?? {}).map(([field, message]) => [field, [message]]))
332
+ return { ok: false, error: reason.message, errors }
333
+ }
334
+ return { ok: false, error: reason instanceof Error ? reason.message : String(reason), errors: {} }
335
+ }
336
+
337
+ export async function createModelRecord(slug: string, fields: Record<string, unknown>): Promise<ModelCreateResult> {
338
+ try {
339
+ const result = await dashboardApi<{ ok: boolean, id?: number | string | null, error?: string, errors?: Record<string, string[]> }>(modelPath(slug), { method: 'POST', body: { fields } })
340
+ if (!result?.ok)
341
+ return { ok: false, error: result?.error || 'The record was rejected.', errors: result?.errors ?? {} }
342
+ return { ok: true, id: result.id ?? null }
343
+ }
344
+ catch (reason) {
345
+ return modelCreateFailure(reason)
346
+ }
347
+ }
348
+
349
+ export async function deleteModelRecord(slug: string, id: string | number): Promise<void> {
350
+ const result = await dashboardApi<{ ok: boolean, error?: string }>(`${modelPath(slug)}/${encodeURIComponent(String(id))}`, { method: 'DELETE' })
351
+ if (!result?.ok)
352
+ throw new Error(result?.error || 'The delete was rejected.')
353
+ }