@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.
- package/ai/skills/stacks-actions/SKILL.md +1 -1
- package/ai/skills/stacks-build/SKILL.md +1 -1
- package/ai/skills/stacks-dashboard/SKILL.md +2 -2
- package/ai/skills/stacks-database/SKILL.md +1 -1
- package/ai/skills/stacks-migrations/SKILL.md +2 -2
- package/ai/skills/stacks-native/CATALOG.md +6 -6
- package/app/Actions/Dashboard/Commerce/CommerceCouponsAction.ts +27 -15
- package/app/Actions/Dashboard/Commerce/CommerceCouponsExportAction.ts +45 -0
- package/app/Actions/Dashboard/Commerce/CommerceCustomersAction.ts +22 -12
- package/app/Actions/Dashboard/Commerce/CommerceCustomersExportAction.ts +44 -0
- package/app/Actions/Dashboard/Commerce/CommercePosCheckoutAction.ts +9 -29
- package/app/Actions/Dashboard/Commerce/CommercePrintDevicesAction.ts +7 -9
- package/app/Actions/Dashboard/Commerce/CommerceProductDetailAction.ts +9 -8
- package/app/Actions/Dashboard/Commerce/CommerceTaxesAction.ts +7 -9
- package/app/Actions/Dashboard/Commerce/ManufacturerIndexAction.ts +8 -20
- package/app/Actions/Dashboard/Commerce/commerce-coupon-list.test.ts +203 -0
- package/app/Actions/Dashboard/Commerce/commerce-coupon-list.ts +248 -0
- package/app/Actions/Dashboard/Commerce/commerce-customer-list.test.ts +183 -0
- package/app/Actions/Dashboard/Commerce/commerce-customer-list.ts +186 -0
- package/app/Actions/Dashboard/Commerce/commerce-customer-records.test.ts +1 -34
- package/app/Actions/Dashboard/Commerce/commerce-customer-records.ts +0 -11
- package/app/Actions/Dashboard/Commerce/commerce-manufacturer-list.test.ts +118 -0
- package/app/Actions/Dashboard/Commerce/commerce-manufacturer-list.ts +41 -0
- package/app/Actions/Dashboard/Commerce/commerce-pos-catalog.test.ts +17 -5
- package/app/Actions/Dashboard/Commerce/commerce-pos-catalog.ts +17 -3
- package/app/Actions/Dashboard/Commerce/commerce-print-device-list.test.ts +99 -0
- package/app/Actions/Dashboard/Commerce/commerce-print-device-list.ts +18 -0
- package/app/Actions/Dashboard/Commerce/commerce-product-list.ts +5 -5
- package/app/Actions/Dashboard/Commerce/commerce-product-options.test.ts +81 -0
- package/app/Actions/Dashboard/Commerce/commerce-tax-rate-list.test.ts +99 -0
- package/app/Actions/Dashboard/Commerce/commerce-tax-rate-list.ts +18 -0
- package/app/Actions/Dashboard/Commerce/coupon-records.test.ts +1 -16
- package/app/Actions/Dashboard/Commerce/coupon-records.ts +6 -10
- package/app/Actions/Dashboard/Commerce/manufacturer-records.test.ts +5 -17
- package/app/Actions/Dashboard/Commerce/manufacturer-records.ts +0 -29
- package/app/Actions/Dashboard/Email/captured-mail.test.ts +16 -0
- package/app/Actions/Dashboard/Email/captured-mail.ts +9 -1
- package/app/Actions/Dashboard/Models/model-write.ts +36 -3
- package/app/Actions/Dashboard/Notifications/NotificationDeliveryHistoryAction.ts +13 -58
- package/app/Actions/Dashboard/Notifications/notification-delivery-history.ts +74 -0
- package/app/Actions/SitemapAction.ts +3 -1
- package/app/Models/Notification.ts +3 -1
- package/app/Models/NotificationDelivery.ts +4 -0
- package/app/Models/User.ts +10 -1
- package/bootstrap.ts +10 -2
- package/functions/commerce/tax-types.ts +21 -0
- package/functions/dashboard-list.test.ts +16 -0
- package/functions/dashboard-list.ts +14 -6
- package/functions/dashboard-model-record.test.ts +139 -0
- package/functions/dashboard-model-record.ts +353 -0
- package/functions/monitoring/errors.ts +22 -103
- package/functions/notifications/deliveries.ts +7 -38
- package/functions/queries.ts +7 -10
- package/ide/vscode/package.json +1 -1
- package/package.json +5 -5
- package/resources/components/Dashboard/Analytics/AnalyticsHub.stx +2 -2
- package/resources/components/Dashboard/Analytics/CampaignAnalytics.stx +22 -28
- package/resources/components/Dashboard/Analytics/EventAnalytics.stx +26 -34
- package/resources/components/Dashboard/Analytics/SalesAnalytics.stx +29 -37
- package/resources/components/Dashboard/Analytics/WebAnalyticsBreakdown.stx +12 -16
- package/resources/components/Dashboard/Analytics/WebAnalyticsDashboard.stx +43 -53
- package/resources/components/Dashboard/App/RequestsOverview.stx +2 -1
- package/resources/components/Dashboard/App/SourceInventory.stx +2 -1
- package/resources/components/Dashboard/Auth/AccessTokens.stx +3 -5
- package/resources/components/Dashboard/Billing/BillingPaymentMethodsPanel.stx +9 -11
- package/resources/components/Dashboard/Billing/BillingSettings.stx +1 -1
- package/resources/components/Dashboard/Buddy/BuddyAssistant.stx +4 -6
- package/resources/components/Dashboard/Commerce/CommerceCategoriesDashboard.stx +2 -2
- package/resources/components/Dashboard/Commerce/CommerceCategoriesTable.stx +3 -3
- package/resources/components/Dashboard/Commerce/CommerceCategoryDialog.stx +2 -2
- package/resources/components/Dashboard/Commerce/CommerceCategoryHierarchy.stx +3 -5
- package/resources/components/Dashboard/Commerce/CommerceCouponBreakdown.stx +17 -13
- package/resources/components/Dashboard/Commerce/CommerceCouponDialog.stx +1 -1
- package/resources/components/Dashboard/Commerce/CommerceCouponsDashboard.stx +57 -85
- package/resources/components/Dashboard/Commerce/CommerceCouponsTable.stx +32 -9
- package/resources/components/Dashboard/Commerce/CommerceCustomerDialog.stx +1 -1
- package/resources/components/Dashboard/Commerce/CommerceCustomersDashboard.stx +49 -83
- package/resources/components/Dashboard/Commerce/CommerceCustomersTable.stx +32 -9
- package/resources/components/Dashboard/Commerce/CommerceGiftCardBreakdown.stx +9 -15
- package/resources/components/Dashboard/Commerce/CommerceGiftCardDialog.stx +1 -1
- package/resources/components/Dashboard/Commerce/CommerceGiftCardsDashboard.stx +35 -119
- package/resources/components/Dashboard/Commerce/CommerceGiftCardsTable.stx +3 -3
- package/resources/components/Dashboard/Commerce/CommerceManufacturerDialog.stx +1 -1
- package/resources/components/Dashboard/Commerce/CommerceManufacturersDashboard.stx +3 -5
- package/resources/components/Dashboard/Commerce/CommerceManufacturersTable.stx +2 -2
- package/resources/components/Dashboard/Commerce/CommerceOrderDialog.stx +4 -4
- package/resources/components/Dashboard/Commerce/CommerceOrdersDashboard.stx +42 -129
- package/resources/components/Dashboard/Commerce/CommerceOrdersTable.stx +3 -3
- package/resources/components/Dashboard/Commerce/CommerceOverviewDashboard.stx +1 -1
- package/resources/components/Dashboard/Commerce/CommerceOverviewOrdersTable.stx +9 -11
- package/resources/components/Dashboard/Commerce/CommerceOverviewProductsTable.stx +5 -7
- package/resources/components/Dashboard/Commerce/CommerceOverviewStats.stx +14 -16
- package/resources/components/Dashboard/Commerce/CommercePaymentsBreakdown.stx +12 -18
- package/resources/components/Dashboard/Commerce/CommercePaymentsDashboard.stx +41 -120
- package/resources/components/Dashboard/Commerce/CommercePaymentsTable.stx +1 -1
- package/resources/components/Dashboard/Commerce/CommercePosCart.stx +13 -15
- package/resources/components/Dashboard/Commerce/CommercePosCatalog.stx +17 -19
- package/resources/components/Dashboard/Commerce/CommercePosCheckoutDialog.stx +2 -2
- package/resources/components/Dashboard/Commerce/CommercePosDashboard.stx +1 -1
- package/resources/components/Dashboard/Commerce/CommercePosReceiptDialog.stx +1 -1
- package/resources/components/Dashboard/Commerce/CommerceProductDetailDashboard.stx +5 -5
- package/resources/components/Dashboard/Commerce/CommerceProductDialog.stx +3 -3
- package/resources/components/Dashboard/Commerce/CommerceProductsDashboard.stx +41 -122
- package/resources/components/Dashboard/Commerce/CommerceProductsTable.stx +3 -3
- package/resources/components/Dashboard/Commerce/CommerceReviewEditDialog.stx +1 -1
- package/resources/components/Dashboard/Commerce/CommerceReviewsDashboard.stx +38 -122
- package/resources/components/Dashboard/Commerce/CommerceReviewsTable.stx +2 -2
- package/resources/components/Dashboard/Commerce/CommerceTaxDialog.stx +3 -3
- package/resources/components/Dashboard/Commerce/CommerceTaxesDashboard.stx +5 -4
- package/resources/components/Dashboard/Commerce/CommerceTaxesTable.stx +4 -3
- package/resources/components/Dashboard/Commerce/CommerceUnitDialog.stx +3 -7
- package/resources/components/Dashboard/Commerce/CommerceUnitsDashboard.stx +3 -5
- package/resources/components/Dashboard/Commerce/CommerceUnitsTable.stx +2 -2
- package/resources/components/Dashboard/Commerce/CommerceVariantDialog.stx +3 -3
- package/resources/components/Dashboard/Commerce/CommerceVariantsDashboard.stx +4 -4
- package/resources/components/Dashboard/Commerce/CommerceVariantsTable.stx +3 -5
- package/resources/components/Dashboard/Commerce/Delivery/CourierDialog.stx +1 -1
- package/resources/components/Dashboard/Commerce/Delivery/CouriersDashboard.stx +1 -1
- package/resources/components/Dashboard/Commerce/Delivery/CouriersTable.stx +2 -2
- package/resources/components/Dashboard/Commerce/Delivery/DeliveryOverviewDashboard.stx +44 -52
- package/resources/components/Dashboard/Commerce/Delivery/DeliveryPagination.stx +2 -2
- package/resources/components/Dashboard/Commerce/Delivery/DeliveryRouteDialog.stx +1 -1
- package/resources/components/Dashboard/Commerce/Delivery/DeliveryRoutesDashboard.stx +1 -1
- package/resources/components/Dashboard/Commerce/Delivery/DeliveryRoutesTable.stx +2 -2
- package/resources/components/Dashboard/Commerce/Delivery/DigitalDeliveriesDashboard.stx +1 -1
- package/resources/components/Dashboard/Commerce/Delivery/DigitalDeliveryTable.stx +2 -2
- package/resources/components/Dashboard/Commerce/Delivery/LicenseKeyDialog.stx +3 -3
- package/resources/components/Dashboard/Commerce/Delivery/LicenseKeysDashboard.stx +1 -1
- package/resources/components/Dashboard/Commerce/Delivery/LicenseKeysTable.stx +2 -2
- package/resources/components/Dashboard/Commerce/Delivery/ShippingMethodsDashboard.stx +1 -1
- package/resources/components/Dashboard/Commerce/Delivery/ShippingMethodsTable.stx +2 -2
- package/resources/components/Dashboard/Commerce/Delivery/ShippingRateDialog.stx +2 -2
- package/resources/components/Dashboard/Commerce/Delivery/ShippingRatesDashboard.stx +1 -1
- package/resources/components/Dashboard/Commerce/Delivery/ShippingRatesTable.stx +2 -2
- package/resources/components/Dashboard/Commerce/Delivery/ShippingZoneDialog.stx +1 -1
- package/resources/components/Dashboard/Commerce/Delivery/ShippingZonesDashboard.stx +1 -1
- package/resources/components/Dashboard/Commerce/Delivery/ShippingZonesTable.stx +4 -8
- package/resources/components/Dashboard/Commerce/PaymentDetailsDialog.stx +1 -3
- package/resources/components/Dashboard/Commerce/PrintDeviceBreakdown.stx +9 -15
- package/resources/components/Dashboard/Commerce/PrintDeviceDialog.stx +1 -1
- package/resources/components/Dashboard/Commerce/PrintDevicesDashboard.stx +3 -3
- package/resources/components/Dashboard/Commerce/PrintDevicesTable.stx +3 -3
- package/resources/components/Dashboard/Commerce/PrintLogBreakdown.stx +3 -9
- package/resources/components/Dashboard/Commerce/PrintLogDetailsDialog.stx +1 -1
- package/resources/components/Dashboard/Commerce/PrintLogsDashboard.stx +4 -4
- package/resources/components/Dashboard/Commerce/PrintLogsTable.stx +8 -10
- package/resources/components/Dashboard/Commerce/ProductWaitlistDashboard.stx +37 -109
- package/resources/components/Dashboard/Commerce/ProductWaitlistEntryDialog.stx +3 -3
- package/resources/components/Dashboard/Commerce/ProductWaitlistTable.stx +2 -2
- package/resources/components/Dashboard/Commerce/RestaurantWaitlistDashboard.stx +38 -112
- package/resources/components/Dashboard/Commerce/RestaurantWaitlistEntryDialog.stx +2 -2
- package/resources/components/Dashboard/Commerce/RestaurantWaitlistTable.stx +2 -2
- package/resources/components/Dashboard/Content/AuthorsDashboard.stx +4 -4
- package/resources/components/Dashboard/Content/BlogDashboard.stx +4 -4
- package/resources/components/Dashboard/Content/CommentsDashboard.stx +36 -83
- package/resources/components/Dashboard/Content/ContentDashboard.stx +12 -14
- package/resources/components/Dashboard/Content/ContentTaxonomyDashboard.stx +2 -2
- package/resources/components/Dashboard/Content/FileManagerDashboard.stx +8 -12
- package/resources/components/Dashboard/Content/FileStoragePanel.stx +6 -10
- package/resources/components/Dashboard/Content/FileUploadDialog.stx +1 -3
- package/resources/components/Dashboard/Content/PagesDashboard.stx +39 -78
- package/resources/components/Dashboard/Content/PostEditorDialog.stx +4 -8
- package/resources/components/Dashboard/Content/PostsDashboard.stx +44 -85
- package/resources/components/Dashboard/Content/SeoDashboard.stx +5 -4
- package/resources/components/Dashboard/Data/DataRecords.stx +140 -12
- package/resources/components/Dashboard/Deployments/DeploymentList.stx +4 -4
- package/resources/components/Dashboard/Deployments/DeploymentTable.stx +3 -1
- package/resources/components/Dashboard/Elements/DropdownNavigation.stx +5 -7
- package/resources/components/Dashboard/Email/CapturedMailDashboard.stx +1 -3
- package/resources/components/Dashboard/Email/CapturedMailList.stx +18 -20
- package/resources/components/Dashboard/Email/EmailActivityDashboard.stx +24 -28
- package/resources/components/Dashboard/Email/EmailSettingsList.stx +6 -8
- package/resources/components/Dashboard/Email/EmailSettingsNavigation.stx +10 -12
- package/resources/components/Dashboard/Email/EmailSidebar.stx +33 -37
- package/resources/components/Dashboard/Email/InboxMessageDetail.stx +1 -1
- package/resources/components/Dashboard/Email/InboxMessageList.stx +16 -18
- package/resources/components/Dashboard/Email/InboxSettingsDashboard.stx +1 -1
- package/resources/components/Dashboard/Environment/EnvironmentDashboard.stx +2 -2
- package/resources/components/Dashboard/GlobalSearch.stx +19 -21
- package/resources/components/Dashboard/Home/DashboardHome.stx +8 -1
- package/resources/components/Dashboard/Infrastructure/CloudDashboard.stx +1 -1
- package/resources/components/Dashboard/Infrastructure/DnsDashboard.stx +27 -13
- package/resources/components/Dashboard/Infrastructure/LogsDashboard.stx +1 -1
- package/resources/components/Dashboard/Infrastructure/MailboxesDashboard.stx +46 -8
- package/resources/components/Dashboard/Infrastructure/ServerlessDashboard.stx +1 -1
- package/resources/components/Dashboard/Infrastructure/ServersDashboard.stx +1 -1
- package/resources/components/Dashboard/Jobs/JobDetail.stx +1 -1
- package/resources/components/Dashboard/Jobs/JobHistory.stx +44 -57
- package/resources/components/Dashboard/Jobs/JobTable.stx +23 -25
- package/resources/components/Dashboard/Kanban/KanbanCardDialog.stx +1 -1
- package/resources/components/Dashboard/Library/ComponentsDashboard.stx +1 -1
- package/resources/components/Dashboard/Management/AssignmentDrawer.stx +5 -7
- package/resources/components/Dashboard/Management/PermissionsDashboard.stx +35 -43
- package/resources/components/Dashboard/Marketing/AbandonedCartsDashboard.stx +11 -13
- package/resources/components/Dashboard/Marketing/CampaignDialog.stx +1 -3
- package/resources/components/Dashboard/Marketing/CampaignsDashboard.stx +2 -2
- package/resources/components/Dashboard/Marketing/CampaignsTable.stx +2 -2
- package/resources/components/Dashboard/Marketing/MarketingListsDashboard.stx +1 -1
- package/resources/components/Dashboard/Marketing/MarketingListsTable.stx +2 -2
- package/resources/components/Dashboard/Marketing/SocialPostDialog.stx +1 -3
- package/resources/components/Dashboard/Marketing/SocialPostsDashboard.stx +2 -2
- package/resources/components/Dashboard/Marketing/SocialPostsTable.stx +2 -2
- package/resources/components/Dashboard/Models/ModelRecordActions.stx +11 -2
- package/resources/components/Dashboard/Models/ModelRecordCreate.stx +193 -0
- package/resources/components/Dashboard/Models/ModelRecordDetail.stx +144 -0
- package/resources/components/Dashboard/Models/ModelRecordEdit.stx +176 -0
- package/resources/components/Dashboard/Models/ModelRecordsDashboard.stx +52 -186
- package/resources/components/Dashboard/Models/ModelsOverview.stx +2 -4
- package/resources/components/Dashboard/Monitoring/ErrorDashboard.stx +47 -81
- package/resources/components/Dashboard/Monitoring/ErrorTable.stx +4 -2
- package/resources/components/Dashboard/NotFoundDashboard.stx +4 -4
- package/resources/components/Dashboard/Notifications/NotificationDeliveryHistory.stx +43 -77
- package/resources/components/Dashboard/Notifications/NotificationDeliveryOverview.stx +15 -17
- package/resources/components/Dashboard/Notifications/NotificationDeliveryTable.stx +1 -1
- package/resources/components/Dashboard/Operations/AuditDashboard.stx +1 -1
- package/resources/components/Dashboard/Operations/ChangeDashboard.stx +1 -1
- package/resources/components/Dashboard/Operations/IncidentDashboard.stx +1 -1
- package/resources/components/Dashboard/Operations/MigrationDashboard.stx +2 -2
- package/resources/components/Dashboard/Operations/RecoveryDashboard.stx +1 -1
- package/resources/components/Dashboard/Operations/SchedulerDashboard.stx +1 -1
- package/resources/components/Dashboard/Queries/QueryDashboard.stx +60 -86
- package/resources/components/Dashboard/Queries/QueryDetail.stx +5 -9
- package/resources/components/Dashboard/Realtime/RealtimeDashboard.stx +6 -8
- package/resources/components/Dashboard/Remote/RemoteConsole.stx +14 -20
- package/resources/components/Dashboard/Settings/AppearanceSettingsDashboard.stx +48 -54
- package/resources/components/Dashboard/Settings/MailSettingsDashboard.stx +8 -8
- package/resources/components/Dashboard/Settings/SettingsDashboard.stx +43 -47
- package/resources/components/Dashboard/Teams/TeamInvitationDashboard.stx +2 -2
- package/resources/components/Dashboard/UI/ActivityTable.stx +2 -1
- package/resources/components/Dashboard/UI/Button.stx +15 -0
- package/resources/components/Dashboard/UI/MetricCards.stx +5 -7
- package/resources/components/Dashboard/UI/Pagination.stx +3 -5
- package/resources/components/Dashboard/UI/QuickLinks.stx +2 -2
- package/resources/components/Dashboard/UI/Select.stx +1 -0
- package/resources/components/Dashboard/UI/Table.stx +139 -96
- package/resources/components/Dashboard/UI/Tabs.stx +18 -20
- package/routes/dashboard-api.ts +2 -0
- package/routes/dashboard.ts +246 -253
- package/routes/storefront.ts +31 -0
- package/stx-components-plugin.ts +12 -1
- package/views/dashboard/content/categories/index.stx +1 -1
- package/views/dashboard/content/tags/index.stx +1 -1
- package/views/dashboard/layouts/default.stx +27 -12
- package/views/dashboard/models/[model]/[id]/edit.stx +8 -0
- package/views/dashboard/models/[model]/[id].stx +8 -0
- package/views/dashboard/models/[model]/create.stx +8 -0
- package/resources/components/Dashboard/CreateRecordModal.stx +0 -138
- package/resources/components/Dashboard/Models/EditRecordModal.stx +0 -81
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
import { Database } from 'bun:sqlite'
|
|
2
|
+
import { SQL } from 'bun'
|
|
3
|
+
import { describe, expect, test } from 'bun:test'
|
|
4
|
+
import { readProductOptions } from './commerce-product-list'
|
|
5
|
+
import type { CommerceSqlRunner } from './commerce-sql'
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* The category and manufacturer choices the Products page and each product's
|
|
9
|
+
* own page offer, against each dialect's real engine (stacksjs/stacks#3218).
|
|
10
|
+
* The product page used to read the first 500 of each by name; there are 520
|
|
11
|
+
* of each here, named so the last by id sorts first and case is ignored.
|
|
12
|
+
*/
|
|
13
|
+
type Dialect = 'sqlite' | 'postgres' | 'mysql'
|
|
14
|
+
type Run = (sql: string, values?: unknown[]) => Promise<unknown>
|
|
15
|
+
|
|
16
|
+
const ROWS = 520
|
|
17
|
+
|
|
18
|
+
/** Row n is named so that id order and name order run opposite ways, every other one in capitals. */
|
|
19
|
+
function nameOf(prefix: string, id: number): string {
|
|
20
|
+
const name = `${prefix} ${String(ROWS + 1 - id).padStart(3, '0')}`
|
|
21
|
+
return id % 2 === 0 ? name.toUpperCase() : name
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
async function setUp(run: Run, dialect: Dialect) {
|
|
25
|
+
const pk = dialect === 'postgres' ? 'BIGINT PRIMARY KEY' : 'INTEGER PRIMARY KEY'
|
|
26
|
+
const text = dialect === 'mysql' ? 'VARCHAR(255)' : 'TEXT'
|
|
27
|
+
const p = (index: number) => dialect === 'postgres' ? `$${index}` : '?'
|
|
28
|
+
const rows = Array.from({ length: ROWS }, (_, row) => `(${p(row * 2 + 1)}, ${p(row * 2 + 2)})`).join(', ')
|
|
29
|
+
await run(`CREATE TABLE categories (id ${pk}, name ${text})`)
|
|
30
|
+
await run(`CREATE TABLE manufacturers (id ${pk}, manufacturer ${text})`)
|
|
31
|
+
const ids = Array.from({ length: ROWS }, (_, index) => index + 1)
|
|
32
|
+
await run(`INSERT INTO categories (id, name) VALUES ${rows}`, ids.flatMap(id => [id, nameOf('Category', id)]))
|
|
33
|
+
await run(`INSERT INTO manufacturers (id, manufacturer) VALUES ${rows}`, ids.flatMap(id => [id, nameOf('Maker', id)]))
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
async function exercise(runner: CommerceSqlRunner) {
|
|
37
|
+
const { categories, manufacturers } = await readProductOptions(runner)
|
|
38
|
+
// All 520 of each, by name ignoring case: the newest id first.
|
|
39
|
+
const expected = Array.from({ length: ROWS }, (_, index) => String(ROWS - index))
|
|
40
|
+
expect(categories.map(option => option.id)).toEqual(expected)
|
|
41
|
+
expect(manufacturers.map(option => option.id)).toEqual(expected)
|
|
42
|
+
expect(categories[0]).toEqual({ id: '520', label: 'CATEGORY 001' })
|
|
43
|
+
expect(manufacturers.at(-1)).toEqual({ id: '1', label: 'Maker 520' })
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
describe('readProductOptions on SQLite', () => {
|
|
47
|
+
test('every category and manufacturer, by name', async () => {
|
|
48
|
+
const database = new Database(':memory:')
|
|
49
|
+
await setUp(async (sql, values = []) => database.query(sql).run(...(values as never[])), 'sqlite')
|
|
50
|
+
await exercise({ unsafe: (sql, values = []) => ({ execute: async () => database.query(sql).all(...(values as never[])) }) })
|
|
51
|
+
})
|
|
52
|
+
})
|
|
53
|
+
|
|
54
|
+
for (const dialect of ['postgres', 'mysql'] as const) {
|
|
55
|
+
const connection = dialect === 'postgres' ? process.env.STACKS_TEST_POSTGRES_URL : process.env.STACKS_TEST_MYSQL_URL
|
|
56
|
+
|
|
57
|
+
test.skipIf(!connection)(`readProductOptions on ${dialect}: every category and manufacturer, by name`, async () => {
|
|
58
|
+
const url = new URL(connection!)
|
|
59
|
+
if (!['127.0.0.1', 'localhost', '[::1]'].includes(url.hostname))
|
|
60
|
+
throw new Error('Product option tests require a local disposable database server')
|
|
61
|
+
|
|
62
|
+
const name = `stacks_product_options_${crypto.randomUUID().replaceAll('-', '')}`
|
|
63
|
+
const quoted = dialect === 'mysql' ? `\`${name}\`` : `"${name}"`
|
|
64
|
+
const admin = new SQL({ url: url.href, database: decodeURIComponent(url.pathname.slice(1)) || undefined })
|
|
65
|
+
await admin.unsafe(`CREATE DATABASE ${quoted}`)
|
|
66
|
+
const scoped = new URL(url.href)
|
|
67
|
+
scoped.pathname = `/${name}`
|
|
68
|
+
// Explicit database wins over inherited PGDATABASE / MYSQL_DATABASE in CI.
|
|
69
|
+
const database = new SQL({ url: scoped.href, database: name })
|
|
70
|
+
|
|
71
|
+
try {
|
|
72
|
+
await setUp(async (sql, values = []) => await database.unsafe(sql, values), dialect)
|
|
73
|
+
await exercise({ unsafe: (sql, values = []) => ({ execute: async () => await database.unsafe(sql, values) }) })
|
|
74
|
+
}
|
|
75
|
+
finally {
|
|
76
|
+
await database.close()
|
|
77
|
+
try { await admin.unsafe(`DROP DATABASE ${quoted}${dialect === 'postgres' ? ' WITH (FORCE)' : ''}`) }
|
|
78
|
+
finally { await admin.close() }
|
|
79
|
+
}
|
|
80
|
+
}, 60_000)
|
|
81
|
+
}
|
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
import { Database } from 'bun:sqlite'
|
|
2
|
+
import { SQL } from 'bun'
|
|
3
|
+
import { describe, expect, test } from 'bun:test'
|
|
4
|
+
import type { CommerceSqlRunner } from './commerce-sql'
|
|
5
|
+
import { readTaxRates } from './commerce-tax-rate-list'
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* The tax rates against each dialect's real engine (stacksjs/stacks#3218),
|
|
9
|
+
* over 520 of them: the page used to read the newest 500.
|
|
10
|
+
*/
|
|
11
|
+
type Dialect = 'sqlite' | 'postgres' | 'mysql'
|
|
12
|
+
|
|
13
|
+
const ROWS = 520
|
|
14
|
+
const REGIONS = ['North America', 'South America', 'Europe', 'Asia', 'Africa', 'Oceania', 'Antarctica'] as const
|
|
15
|
+
|
|
16
|
+
/** 26 countries; rates 1 and 520 are both defaults, a conflict the newest 500 could not see. */
|
|
17
|
+
const RATES = Array.from({ length: ROWS }, (_, index) => {
|
|
18
|
+
const id = index + 1
|
|
19
|
+
return {
|
|
20
|
+
id,
|
|
21
|
+
name: `Rate ${id}`,
|
|
22
|
+
rate: (id % 40) / 2,
|
|
23
|
+
type: id % 3 === 0 ? 'vat' : 'sales',
|
|
24
|
+
country: `C${String.fromCharCode(65 + (id % 26))}`,
|
|
25
|
+
region: REGIONS[id % REGIONS.length]!,
|
|
26
|
+
status: id % 4 === 0 ? 'inactive' : 'active',
|
|
27
|
+
isDefault: id === 1 || id === ROWS,
|
|
28
|
+
}
|
|
29
|
+
})
|
|
30
|
+
|
|
31
|
+
async function setUp(run: (sql: string, values?: unknown[]) => Promise<unknown>, dialect: Dialect) {
|
|
32
|
+
const pk = dialect === 'postgres' ? 'BIGINT PRIMARY KEY' : 'INTEGER PRIMARY KEY'
|
|
33
|
+
const text = dialect === 'mysql' ? 'VARCHAR(255)' : 'TEXT'
|
|
34
|
+
const bool = dialect === 'postgres' ? 'BOOLEAN' : dialect === 'mysql' ? 'TINYINT(1)' : 'INTEGER'
|
|
35
|
+
const time = dialect === 'sqlite' ? 'TEXT' : dialect === 'mysql' ? 'DATETIME(3)' : 'TIMESTAMP'
|
|
36
|
+
const p = (index: number) => dialect === 'postgres' ? `$${index}` : '?'
|
|
37
|
+
const columns = 9
|
|
38
|
+
await run(`CREATE TABLE tax_rates (id ${pk}, name ${text}, rate REAL, type ${text}, country ${text}, region ${text}, status ${text}, is_default ${bool}, created_at ${time})`)
|
|
39
|
+
await run(
|
|
40
|
+
`INSERT INTO tax_rates (id, name, rate, type, country, region, status, is_default, created_at) VALUES ${RATES.map((_, i) => `(${Array.from({ length: columns }, (_, c) => p(i * columns + c + 1)).join(', ')})`).join(', ')}`,
|
|
41
|
+
RATES.flatMap(rate => [
|
|
42
|
+
rate.id, rate.name, rate.rate, rate.type, rate.country, rate.region, rate.status,
|
|
43
|
+
dialect === 'postgres' ? rate.isDefault : (rate.isDefault ? 1 : 0), '2026-11-01 09:00:00',
|
|
44
|
+
]),
|
|
45
|
+
)
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
async function exercise(runner: CommerceSqlRunner) {
|
|
49
|
+
const { records, summary } = await readTaxRates(runner)
|
|
50
|
+
|
|
51
|
+
// Every rate, newest first, the oldest included.
|
|
52
|
+
expect(records.map(record => record.id)).toEqual(RATES.map(rate => String(rate.id)).reverse())
|
|
53
|
+
expect(records.at(-1)).toMatchObject({ id: '1', name: 'Rate 1', rate: 0.5, country: 'CB', region: 'South America', isDefault: true })
|
|
54
|
+
|
|
55
|
+
expect(summary).toEqual({
|
|
56
|
+
total: ROWS,
|
|
57
|
+
active: RATES.filter(rate => rate.status === 'active').length,
|
|
58
|
+
countries: 26,
|
|
59
|
+
averageRate: RATES.reduce((sum, rate) => sum + rate.rate, 0) / ROWS,
|
|
60
|
+
defaultConflicts: 1,
|
|
61
|
+
})
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
describe('readTaxRates on SQLite', () => {
|
|
65
|
+
test('every tax rate, newest first, with the summary of all of them', async () => {
|
|
66
|
+
const database = new Database(':memory:')
|
|
67
|
+
await setUp(async (sql, values = []) => database.query(sql).run(...(values as never[])), 'sqlite')
|
|
68
|
+
await exercise({ unsafe: (sql, values = []) => ({ execute: async () => database.query(sql).all(...(values as never[])) }) })
|
|
69
|
+
})
|
|
70
|
+
})
|
|
71
|
+
|
|
72
|
+
for (const dialect of ['postgres', 'mysql'] as const) {
|
|
73
|
+
const connection = dialect === 'postgres' ? process.env.STACKS_TEST_POSTGRES_URL : process.env.STACKS_TEST_MYSQL_URL
|
|
74
|
+
|
|
75
|
+
test.skipIf(!connection)(`readTaxRates on ${dialect}: every tax rate, newest first, with the summary of all of them`, async () => {
|
|
76
|
+
const url = new URL(connection!)
|
|
77
|
+
if (!['127.0.0.1', 'localhost', '[::1]'].includes(url.hostname))
|
|
78
|
+
throw new Error('Tax rate list tests require a local disposable database server')
|
|
79
|
+
|
|
80
|
+
const name = `stacks_tax_rates_${crypto.randomUUID().replaceAll('-', '')}`
|
|
81
|
+
const quoted = dialect === 'mysql' ? `\`${name}\`` : `"${name}"`
|
|
82
|
+
const admin = new SQL({ url: url.href, database: decodeURIComponent(url.pathname.slice(1)) || undefined })
|
|
83
|
+
await admin.unsafe(`CREATE DATABASE ${quoted}`)
|
|
84
|
+
const scoped = new URL(url.href)
|
|
85
|
+
scoped.pathname = `/${name}`
|
|
86
|
+
// Explicit database wins over inherited PGDATABASE / MYSQL_DATABASE in CI.
|
|
87
|
+
const database = new SQL({ url: scoped.href, database: name })
|
|
88
|
+
|
|
89
|
+
try {
|
|
90
|
+
await setUp(async (sql, values = []) => await database.unsafe(sql, values), dialect)
|
|
91
|
+
await exercise({ unsafe: (sql, values = []) => ({ execute: async () => await database.unsafe(sql, values) }) })
|
|
92
|
+
}
|
|
93
|
+
finally {
|
|
94
|
+
await database.close()
|
|
95
|
+
try { await admin.unsafe(`DROP DATABASE ${quoted}${dialect === 'postgres' ? ' WITH (FORCE)' : ''}`) }
|
|
96
|
+
finally { await admin.close() }
|
|
97
|
+
}
|
|
98
|
+
}, 60_000)
|
|
99
|
+
}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import type { CommerceSqlRunner } from './commerce-sql'
|
|
2
|
+
import { db } from '@stacksjs/database/runtime'
|
|
3
|
+
import { sqlRows } from './commerce-sql'
|
|
4
|
+
import type { TaxRateRecord, TaxRateSummary } from './tax-rate-records'
|
|
5
|
+
import { normalizeTaxRateRecord, summarizeTaxRates } from './tax-rate-records'
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* Every tax rate, newest first (stacksjs/stacks#3218).
|
|
9
|
+
*
|
|
10
|
+
* Tax rates are settings the page needs whole: it offers their countries and
|
|
11
|
+
* types as filters and counts default conflicts across them. It used to read
|
|
12
|
+
* the newest 500, so an older rate could not be found or edited, and the
|
|
13
|
+
* cards, the filters and the default-conflict warning saw only those 500.
|
|
14
|
+
*/
|
|
15
|
+
export async function readTaxRates(run: CommerceSqlRunner = db): Promise<{ records: TaxRateRecord[], summary: TaxRateSummary }> {
|
|
16
|
+
const records = sqlRows(await run.unsafe('SELECT * FROM tax_rates ORDER BY id DESC').execute()).map(normalizeTaxRateRecord)
|
|
17
|
+
return { records, summary: summarizeTaxRates(records) }
|
|
18
|
+
}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { describe, expect, test } from 'bun:test'
|
|
2
|
-
import { normalizeCouponRecord
|
|
2
|
+
import { normalizeCouponRecord } from './coupon-records'
|
|
3
3
|
|
|
4
4
|
function coupon(overrides: Record<string, unknown> = {}): Record<string, unknown> {
|
|
5
5
|
return {
|
|
@@ -73,19 +73,4 @@ describe('dashboard coupon records', () => {
|
|
|
73
73
|
start_date: '2026-02-30',
|
|
74
74
|
}))).toThrow('valid YYYY-MM-DD date')
|
|
75
75
|
})
|
|
76
|
-
|
|
77
|
-
test('summarizes persisted status and usage fields', () => {
|
|
78
|
-
const records = [
|
|
79
|
-
normalizeCouponRecord(coupon({ id: 1, status: 'Active', is_active: true, usage_count: 3 })),
|
|
80
|
-
normalizeCouponRecord(coupon({ id: 2, status: 'Scheduled', is_active: true, usage_count: 2 })),
|
|
81
|
-
normalizeCouponRecord(coupon({ id: 3, status: 'Expired', is_active: false, usage_count: 8 })),
|
|
82
|
-
]
|
|
83
|
-
expect(summarizeCoupons(records)).toEqual({
|
|
84
|
-
total: 3,
|
|
85
|
-
enabled: 2,
|
|
86
|
-
scheduled: 1,
|
|
87
|
-
expired: 1,
|
|
88
|
-
redemptions: 13,
|
|
89
|
-
})
|
|
90
|
-
})
|
|
91
76
|
})
|
|
@@ -34,12 +34,18 @@ export interface CouponRecord {
|
|
|
34
34
|
createdAt: string
|
|
35
35
|
}
|
|
36
36
|
|
|
37
|
+
/** The cards and breakdowns, over every coupon (commerce-coupon-list.ts). */
|
|
37
38
|
export interface CouponSummary {
|
|
38
39
|
total: number
|
|
39
40
|
enabled: number
|
|
41
|
+
active: number
|
|
40
42
|
scheduled: number
|
|
41
43
|
expired: number
|
|
44
|
+
percentage: number
|
|
45
|
+
fixedAmount: number
|
|
42
46
|
redemptions: number
|
|
47
|
+
/** The five most used, by code on a tie. */
|
|
48
|
+
mostUsed: Array<{ id: string, code: string, usageCount: number }>
|
|
43
49
|
}
|
|
44
50
|
|
|
45
51
|
export function normalizeCouponRecord(
|
|
@@ -129,13 +135,3 @@ export function normalizeCouponRecord(
|
|
|
129
135
|
createdAt: commerceTimestamp(commerceValue(record, 'created_at', 'createdAt'), source),
|
|
130
136
|
}
|
|
131
137
|
}
|
|
132
|
-
|
|
133
|
-
export function summarizeCoupons(records: CouponRecord[]): CouponSummary {
|
|
134
|
-
return {
|
|
135
|
-
total: records.length,
|
|
136
|
-
enabled: records.filter(record => record.isActive).length,
|
|
137
|
-
scheduled: records.filter(record => record.status === 'Scheduled').length,
|
|
138
|
-
expired: records.filter(record => record.status === 'Expired').length,
|
|
139
|
-
redemptions: records.reduce((sum, record) => sum + record.usageCount, 0),
|
|
140
|
-
}
|
|
141
|
-
}
|
|
@@ -1,18 +1,10 @@
|
|
|
1
1
|
import { describe, expect, test } from 'bun:test'
|
|
2
|
-
import {
|
|
3
|
-
manufacturerProductCounts,
|
|
4
|
-
normalizeManufacturerRecord,
|
|
5
|
-
summarizeManufacturers,
|
|
6
|
-
} from './manufacturer-records'
|
|
2
|
+
import { normalizeManufacturerRecord, summarizeManufacturers } from './manufacturer-records'
|
|
7
3
|
|
|
8
4
|
describe('dashboard manufacturer records', () => {
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
{ id: 2, manufacturerId: '4' },
|
|
13
|
-
{ id: 3, manufacturer_id: 8 },
|
|
14
|
-
{ id: 4, manufacturer_id: null },
|
|
15
|
-
], new Set(['4', '8']))
|
|
5
|
+
// The products are counted by the database (commerce-manufacturer-list.test.ts).
|
|
6
|
+
test('normalizes model columns with their product count', () => {
|
|
7
|
+
const counts = new Map([['4', 2], ['8', 1]])
|
|
16
8
|
const record = normalizeManufacturerRecord({
|
|
17
9
|
id: 4,
|
|
18
10
|
manufacturer: 'Native Systems',
|
|
@@ -33,7 +25,7 @@ describe('dashboard manufacturer records', () => {
|
|
|
33
25
|
})
|
|
34
26
|
})
|
|
35
27
|
|
|
36
|
-
test('rejects malformed fields
|
|
28
|
+
test('rejects malformed fields', () => {
|
|
37
29
|
expect(() => normalizeManufacturerRecord({
|
|
38
30
|
id: 4,
|
|
39
31
|
manufacturer: 'Native Systems',
|
|
@@ -42,10 +34,6 @@ describe('dashboard manufacturer records', () => {
|
|
|
42
34
|
featured: 'yes',
|
|
43
35
|
created_at: '2026-07-29 10:00:00',
|
|
44
36
|
})).toThrow('Manufacturer 4.featured must be a boolean')
|
|
45
|
-
|
|
46
|
-
expect(() => manufacturerProductCounts([
|
|
47
|
-
{ id: 9, manufacturer_id: 42 },
|
|
48
|
-
], new Set())).toThrow('Product 9.manufacturer_id references missing Manufacturer 42')
|
|
49
37
|
})
|
|
50
38
|
|
|
51
39
|
test('summarizes persisted manufacturers without invented fields', () => {
|
|
@@ -2,7 +2,6 @@ import {
|
|
|
2
2
|
commerceBoolean,
|
|
3
3
|
commerceIdentifier,
|
|
4
4
|
commerceNumber,
|
|
5
|
-
commerceOptionalIdentifier,
|
|
6
5
|
commerceOptionalString,
|
|
7
6
|
commerceRequiredString,
|
|
8
7
|
commerceTimestamp,
|
|
@@ -26,34 +25,6 @@ export interface ManufacturerSummary {
|
|
|
26
25
|
linkedProducts: number
|
|
27
26
|
}
|
|
28
27
|
|
|
29
|
-
export function manufacturerProductCounts(
|
|
30
|
-
products: any[],
|
|
31
|
-
manufacturerIds = new Set<string>(),
|
|
32
|
-
): Map<string, number> {
|
|
33
|
-
const counts = new Map<string, number>()
|
|
34
|
-
for (const product of products) {
|
|
35
|
-
const id = commerceIdentifier(commerceValue(product, 'id', 'uuid'), 'Product')
|
|
36
|
-
const source = `Product ${id}`
|
|
37
|
-
const manufacturerId = commerceOptionalIdentifier(
|
|
38
|
-
commerceValue(product, 'manufacturer_id', 'manufacturerId'),
|
|
39
|
-
source,
|
|
40
|
-
'manufacturer_id',
|
|
41
|
-
)
|
|
42
|
-
if (!manufacturerId)
|
|
43
|
-
continue
|
|
44
|
-
if (!manufacturerIds.has(manufacturerId))
|
|
45
|
-
throw new TypeError(`${source}.manufacturer_id references missing Manufacturer ${manufacturerId}.`)
|
|
46
|
-
counts.set(manufacturerId, (counts.get(manufacturerId) ?? 0) + 1)
|
|
47
|
-
}
|
|
48
|
-
return counts
|
|
49
|
-
}
|
|
50
|
-
|
|
51
|
-
export function manufacturerIdentifiers(records: any[]): Set<string> {
|
|
52
|
-
return new Set(records.map(record =>
|
|
53
|
-
commerceIdentifier(commerceValue(record, 'id', 'uuid'), 'Manufacturer'),
|
|
54
|
-
))
|
|
55
|
-
}
|
|
56
|
-
|
|
57
28
|
export function normalizeManufacturerRecord(
|
|
58
29
|
record: any,
|
|
59
30
|
productCounts = new Map<string, number>(),
|
|
@@ -63,6 +63,22 @@ describe('captured dashboard mail', () => {
|
|
|
63
63
|
expect(message?.text).toBe('')
|
|
64
64
|
})
|
|
65
65
|
|
|
66
|
+
it('previews character references as the characters they stand for', async () => {
|
|
67
|
+
const directory = await temporaryDirectory()
|
|
68
|
+
const filename = '2026-11-10T09-00-00-000Z-Your-order.html'
|
|
69
|
+
await writeFile(join(directory, filename), `<!--
|
|
70
|
+
Captured by @stacksjs/email log driver at 2026-11-10T09:00:00.000Z
|
|
71
|
+
From: Stacks <hello@example.com>
|
|
72
|
+
To: Ada <ada@example.test>
|
|
73
|
+
Subject: Your order
|
|
74
|
+
-->
|
|
75
|
+
<table><tr><td>Trail Runner × 3</td><td>€375</td></tr><tr><td>Use &lt;b&gt; for bold</td></tr></table>
|
|
76
|
+
`)
|
|
77
|
+
|
|
78
|
+
const { messages } = await listCapturedMail(directory)
|
|
79
|
+
expect(messages[0]?.preview).toBe(`Trail Runner ${String.fromCodePoint(0xD7)} 3 ${String.fromCodePoint(0x20AC)}375 Use <b> for bold`)
|
|
80
|
+
})
|
|
81
|
+
|
|
66
82
|
it('reports a malformed capture instead of fabricating metadata for it', async () => {
|
|
67
83
|
const directory = await temporaryDirectory()
|
|
68
84
|
await writeFile(join(directory, 'broken.html'), '<p>No capture header</p>')
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { readdir, readFile, stat } from 'node:fs/promises'
|
|
2
2
|
import { basename, join } from 'node:path'
|
|
3
3
|
import { log as logDriver } from '@stacksjs/email'
|
|
4
|
+
import { decodeHtmlEntities } from '@stacksjs/strings'
|
|
4
5
|
|
|
5
6
|
const { LogEmailDriver } = logDriver
|
|
6
7
|
|
|
@@ -59,11 +60,18 @@ function formatAddress(value: unknown): string {
|
|
|
59
60
|
return name ? `${name} <${address}>` : address
|
|
60
61
|
}
|
|
61
62
|
|
|
63
|
+
/**
|
|
64
|
+
* The first 140 characters a reader would see. Character references are
|
|
65
|
+
* decoded after the tags go, or an order email previewed as
|
|
66
|
+
* `Trail Runner × 3`; the list prints it as text, so a decoded `<` stays
|
|
67
|
+
* text.
|
|
68
|
+
*/
|
|
62
69
|
function previewFor(input: string): string {
|
|
63
|
-
|
|
70
|
+
const stripped = input
|
|
64
71
|
.replace(/<style[\s\S]*?<\/style>/gi, '')
|
|
65
72
|
.replace(/<script[\s\S]*?<\/script>/gi, '')
|
|
66
73
|
.replace(/<[^>]+>/g, ' ')
|
|
74
|
+
return decodeHtmlEntities(stripped)
|
|
67
75
|
.replace(/\s+/g, ' ')
|
|
68
76
|
.trim()
|
|
69
77
|
.slice(0, 140)
|
|
@@ -128,10 +128,35 @@ function isProtectedField(name: string): boolean {
|
|
|
128
128
|
return PROTECTED_COLUMNS.has(name) || PROTECTED_COLUMNS.has(column)
|
|
129
129
|
}
|
|
130
130
|
|
|
131
|
+
/**
|
|
132
|
+
* The attributes a new row must have that the create form cannot ask for:
|
|
133
|
+
* required, with no default, and withheld from the form because they are
|
|
134
|
+
* hidden or protected.
|
|
135
|
+
*
|
|
136
|
+
* `User.password` is the case that exists. The form leaves hidden fields out
|
|
137
|
+
* on purpose, the column is NOT NULL, and so every "Create user" ended in a
|
|
138
|
+
* 500 from the database after the visitor had filled the form in. A model in
|
|
139
|
+
* that position needs a flow of its own (registration, an invitation), not
|
|
140
|
+
* the generic form.
|
|
141
|
+
*/
|
|
142
|
+
export function uncollectableRequiredFields(Model: any): string[] {
|
|
143
|
+
const names: string[] = []
|
|
144
|
+
for (const [name, definition] of Object.entries((Model?.attributes ?? {}) as Record<string, any>)) {
|
|
145
|
+
if (!definition?.fillable || definition.default !== undefined)
|
|
146
|
+
continue
|
|
147
|
+
const required = definition.required === true || definition.validation?.rule?.isRequired === true
|
|
148
|
+
if (required && (definition.hidden || isProtectedField(name)))
|
|
149
|
+
names.push(name)
|
|
150
|
+
}
|
|
151
|
+
return names
|
|
152
|
+
}
|
|
153
|
+
|
|
131
154
|
export function modelWriteCapabilities(Model: any): ModelWriteCapabilities {
|
|
132
155
|
const routes = modelApiConfiguration(Model).routes
|
|
133
156
|
return {
|
|
134
|
-
|
|
157
|
+
// A store route is not enough: the form has to be able to supply every
|
|
158
|
+
// field a new row requires.
|
|
159
|
+
create: routes.includes('store') && uncollectableRequiredFields(Model).length === 0,
|
|
135
160
|
update: routes.includes('update'),
|
|
136
161
|
destroy: routes.includes('destroy'),
|
|
137
162
|
}
|
|
@@ -314,9 +339,17 @@ export async function resolveWritableModel(slug: string, operation?: ModelWriteO
|
|
|
314
339
|
if (!Model || typeof Model.find !== 'function')
|
|
315
340
|
return { error: `No ORM model named ${modelName}. Rows from tables without a model are read-only.`, status: 404 }
|
|
316
341
|
if (operation) {
|
|
317
|
-
|
|
318
|
-
if (!modelWriteCapabilities(Model)[capability])
|
|
342
|
+
if (!modelApiConfiguration(Model).routes.includes(operation))
|
|
319
343
|
return { error: `${modelName} does not declare the ${operation} route in its useApi trait.`, status: 405 }
|
|
344
|
+
if (operation === 'store') {
|
|
345
|
+
const missing = uncollectableRequiredFields(Model)
|
|
346
|
+
if (missing.length > 0) {
|
|
347
|
+
return {
|
|
348
|
+
error: `${modelName} records cannot be created from the dashboard: ${missing.map(humanize).join(', ')} ${missing.length === 1 ? 'is' : 'are'} required and the create form does not collect ${missing.length === 1 ? 'it' : 'them'}.`,
|
|
349
|
+
status: 405,
|
|
350
|
+
}
|
|
351
|
+
}
|
|
352
|
+
}
|
|
320
353
|
}
|
|
321
354
|
return { Model, modelName }
|
|
322
355
|
}
|
|
@@ -1,21 +1,15 @@
|
|
|
1
1
|
import type { RequestInstance } from '@stacksjs/types'
|
|
2
2
|
import { Action } from '@stacksjs/actions/runtime'
|
|
3
|
-
import { db } from '@stacksjs/database/runtime'
|
|
4
3
|
import { response } from '@stacksjs/router'
|
|
5
4
|
import { dashboardOperationalError } from '../dashboard-response'
|
|
6
5
|
import { dashboardRequestValue } from '../dashboard-request'
|
|
6
|
+
import { serializeNotificationDelivery } from './notification-delivery'
|
|
7
7
|
import {
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
const STATUSES = ['sent', 'delivered', 'failed', 'pending'] as const
|
|
14
|
-
const SORTS = ['sent_at', 'recipient', 'channel', 'status', 'id'] as const
|
|
15
|
-
|
|
16
|
-
type DeliveryChannel = typeof CHANNELS[number]
|
|
17
|
-
type DeliveryStatus = typeof STATUSES[number]
|
|
18
|
-
type DeliverySort = typeof SORTS[number]
|
|
8
|
+
DELIVERY_CHANNELS,
|
|
9
|
+
DELIVERY_SORTS,
|
|
10
|
+
DELIVERY_STATUSES,
|
|
11
|
+
readDeliveryHistory,
|
|
12
|
+
} from './notification-delivery-history'
|
|
19
13
|
|
|
20
14
|
function queryValue(request: RequestInstance, key: string): string {
|
|
21
15
|
return dashboardRequestValue(request, key)
|
|
@@ -33,56 +27,17 @@ export default new Action({
|
|
|
33
27
|
async handle(request: RequestInstance) {
|
|
34
28
|
const page = Math.min(1_000_000, Math.max(1, Number.parseInt(queryValue(request, 'page') || '1', 10) || 1))
|
|
35
29
|
const perPage = Math.min(100, Math.max(1, Number.parseInt(queryValue(request, 'per_page') || '20', 10) || 20))
|
|
36
|
-
const channel = allowedValue(queryValue(request, 'channel').toLowerCase(),
|
|
37
|
-
const status = allowedValue(queryValue(request, 'status').toLowerCase(),
|
|
38
|
-
const sort = allowedValue(queryValue(request, 'sort').toLowerCase(),
|
|
30
|
+
const channel = allowedValue(queryValue(request, 'channel').toLowerCase(), DELIVERY_CHANNELS)
|
|
31
|
+
const status = allowedValue(queryValue(request, 'status').toLowerCase(), DELIVERY_STATUSES)
|
|
32
|
+
const sort = allowedValue(queryValue(request, 'sort').toLowerCase(), DELIVERY_SORTS) || 'sent_at'
|
|
39
33
|
const direction = queryValue(request, 'direction').toLowerCase() === 'asc' ? 'asc' : 'desc'
|
|
40
34
|
const search = queryValue(request, 'search')
|
|
41
35
|
if (search.length > 200)
|
|
42
36
|
return response.json({ message: 'Notification delivery search must be 200 characters or fewer.' }, 422)
|
|
43
|
-
const searchPattern = `%${search}%`
|
|
44
|
-
|
|
45
|
-
const applyFilters = <T extends {
|
|
46
|
-
where: (...args: any[]) => T
|
|
47
|
-
}>(query: T): T => {
|
|
48
|
-
let filtered = query
|
|
49
|
-
if (channel)
|
|
50
|
-
filtered = filtered.where('channel', '=', channel)
|
|
51
|
-
if (status)
|
|
52
|
-
filtered = filtered.where('status', '=', status)
|
|
53
|
-
if (search) {
|
|
54
|
-
filtered = filtered.where((expression: any) => expression.or([
|
|
55
|
-
expression('recipient', 'like', searchPattern),
|
|
56
|
-
expression('subject', 'like', searchPattern),
|
|
57
|
-
expression('body', 'like', searchPattern),
|
|
58
|
-
expression('error', 'like', searchPattern),
|
|
59
|
-
]))
|
|
60
|
-
}
|
|
61
|
-
return filtered
|
|
62
|
-
}
|
|
63
37
|
|
|
64
38
|
try {
|
|
65
|
-
const
|
|
66
|
-
|
|
67
|
-
.selectFrom('notification_deliveries')
|
|
68
|
-
.select(db.fn.count('id').as('count')),
|
|
69
|
-
)
|
|
70
|
-
const rowsQuery = applyFilters(
|
|
71
|
-
db
|
|
72
|
-
.selectFrom('notification_deliveries')
|
|
73
|
-
.selectAll(),
|
|
74
|
-
)
|
|
75
|
-
|
|
76
|
-
const [countRow, rows] = await Promise.all([
|
|
77
|
-
countQuery.executeTakeFirst() as Promise<{ count: number | string } | undefined>,
|
|
78
|
-
rowsQuery
|
|
79
|
-
.orderBy(sort as DeliverySort, direction)
|
|
80
|
-
.limit(perPage)
|
|
81
|
-
.offset((page - 1) * perPage)
|
|
82
|
-
.execute() as unknown as Promise<NotificationDeliveryRow[]>,
|
|
83
|
-
])
|
|
84
|
-
|
|
85
|
-
const total = Number(countRow?.count || 0)
|
|
39
|
+
const { rows, total: counted } = await readDeliveryHistory({ page, perPage, channel, status, search, sort, direction })
|
|
40
|
+
const total = Number(counted || 0)
|
|
86
41
|
if (!Number.isSafeInteger(total) || total < 0)
|
|
87
42
|
throw new TypeError('Notification delivery count must be a non-negative integer.')
|
|
88
43
|
return response.json({
|
|
@@ -94,8 +49,8 @@ export default new Action({
|
|
|
94
49
|
total_pages: Math.max(1, Math.ceil(total / perPage)),
|
|
95
50
|
},
|
|
96
51
|
filters: {
|
|
97
|
-
channel
|
|
98
|
-
status
|
|
52
|
+
channel,
|
|
53
|
+
status,
|
|
99
54
|
search,
|
|
100
55
|
sort,
|
|
101
56
|
direction,
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
import { db } from '@stacksjs/database/runtime'
|
|
2
|
+
import type { NotificationDeliveryRow } from './notification-delivery'
|
|
3
|
+
|
|
4
|
+
export const DELIVERY_CHANNELS = ['email', 'sms', 'chat', 'database', 'push', 'broadcast'] as const
|
|
5
|
+
export const DELIVERY_STATUSES = ['sent', 'delivered', 'failed', 'pending'] as const
|
|
6
|
+
export const DELIVERY_SORTS = ['sent_at', 'recipient', 'channel', 'status', 'id'] as const
|
|
7
|
+
|
|
8
|
+
/** The columns the History search looks in. */
|
|
9
|
+
export const DELIVERY_SEARCH_COLUMNS = ['recipient', 'subject', 'body', 'error'] as const
|
|
10
|
+
|
|
11
|
+
export interface DeliveryHistoryQuery {
|
|
12
|
+
page: number
|
|
13
|
+
perPage: number
|
|
14
|
+
channel: typeof DELIVERY_CHANNELS[number] | null
|
|
15
|
+
status: typeof DELIVERY_STATUSES[number] | null
|
|
16
|
+
/** Matched anywhere in a searched column, ignoring case. Empty matches every row. */
|
|
17
|
+
search: string
|
|
18
|
+
sort: typeof DELIVERY_SORTS[number]
|
|
19
|
+
direction: 'asc' | 'desc'
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export interface DeliveryHistoryPage {
|
|
23
|
+
rows: NotificationDeliveryRow[]
|
|
24
|
+
/** How many rows match, across every page, as the database counted them. */
|
|
25
|
+
total: unknown
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* One page of `notification_deliveries`, filtered, searched, sorted and
|
|
30
|
+
* sliced by the database.
|
|
31
|
+
*
|
|
32
|
+
* The search used to hand `where` a Kysely-style expression callback, which
|
|
33
|
+
* bun-query-builder calls with a proxy rather than a function, so every
|
|
34
|
+
* search threw and the History page answered 503. It is a `whereGroup` of
|
|
35
|
+
* `whereILike` now, which binds the term and ignores case on every dialect
|
|
36
|
+
* (ILIKE on PostgreSQL, where a plain LIKE is case-sensitive, as in
|
|
37
|
+
* stacksjs/stacks#3202).
|
|
38
|
+
*
|
|
39
|
+
* The order ends on `id` in the same direction, so rows that tie on the sort
|
|
40
|
+
* column (every failed delivery, sorted by status) keep one order from page to
|
|
41
|
+
* page instead of whatever the database returns that time.
|
|
42
|
+
*/
|
|
43
|
+
export async function readDeliveryHistory(query: DeliveryHistoryQuery): Promise<DeliveryHistoryPage> {
|
|
44
|
+
const applyFilters = (chain: any): any => {
|
|
45
|
+
let filtered = chain
|
|
46
|
+
if (query.channel)
|
|
47
|
+
filtered = filtered.where('channel', '=', query.channel)
|
|
48
|
+
if (query.status)
|
|
49
|
+
filtered = filtered.where('status', '=', query.status)
|
|
50
|
+
if (query.search) {
|
|
51
|
+
const pattern = `%${query.search}%`
|
|
52
|
+
filtered = filtered.whereGroup((group: any) => {
|
|
53
|
+
for (const [index, column] of DELIVERY_SEARCH_COLUMNS.entries())
|
|
54
|
+
group = index === 0 ? group.whereILike(column, pattern) : group.orWhereILike(column, pattern)
|
|
55
|
+
return group
|
|
56
|
+
})
|
|
57
|
+
}
|
|
58
|
+
return filtered
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
let rowsQuery = applyFilters(db.selectFrom('notification_deliveries').selectAll())
|
|
62
|
+
.orderBy(query.sort, query.direction)
|
|
63
|
+
if (query.sort !== 'id')
|
|
64
|
+
rowsQuery = rowsQuery.orderBy('id', query.direction)
|
|
65
|
+
|
|
66
|
+
const [countRow, rows] = await Promise.all([
|
|
67
|
+
applyFilters(db.selectFrom('notification_deliveries').select(db.fn.count('id').as('count'))).executeTakeFirst() as Promise<{ count: number | string } | undefined>,
|
|
68
|
+
rowsQuery
|
|
69
|
+
.limit(query.perPage)
|
|
70
|
+
.offset((query.page - 1) * query.perPage)
|
|
71
|
+
.execute() as Promise<NotificationDeliveryRow[]>,
|
|
72
|
+
])
|
|
73
|
+
return { rows, total: countRow?.count ?? 0 }
|
|
74
|
+
}
|
|
@@ -256,7 +256,9 @@ export default new Action({
|
|
|
256
256
|
const siteUrl = (config as any).app?.url || 'http://localhost:3000'
|
|
257
257
|
const all: SitemapEntry[] = [
|
|
258
258
|
...(await staticEntries()),
|
|
259
|
-
|
|
259
|
+
// A table left behind by an uninstalled commerce bundle is not a
|
|
260
|
+
// catalogue: products are listed only while commerce is on.
|
|
261
|
+
...(feature('commerce') ? await discoverProducts() : []),
|
|
260
262
|
]
|
|
261
263
|
|
|
262
264
|
return response.xml(renderXml(siteUrl, all), 200, {
|
|
@@ -21,7 +21,9 @@ export default defineModel({
|
|
|
21
21
|
},
|
|
22
22
|
},
|
|
23
23
|
|
|
24
|
-
|
|
24
|
+
// Cascade, as the framework's own key repair has always made it
|
|
25
|
+
// (ensureNotificationForeignKeys): a user's notifications go with the user.
|
|
26
|
+
belongsTo: [{ model: 'User', onDelete: 'cascade' }],
|
|
25
27
|
|
|
26
28
|
attributes: {
|
|
27
29
|
type: {
|