@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,203 @@
|
|
|
1
|
+
import { Database } from 'bun:sqlite'
|
|
2
|
+
import { SQL } from 'bun'
|
|
3
|
+
import { describe, expect, test } from 'bun:test'
|
|
4
|
+
import type { CouponListQuery } from './commerce-coupon-list'
|
|
5
|
+
import { couponsCsv, parseCouponListQuery, readCouponPage, readCouponsForExport } from './commerce-coupon-list'
|
|
6
|
+
import type { CommerceSqlRunner } from './commerce-sql'
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* The coupons against each dialect's real engine (stacksjs/stacks#3218), over
|
|
10
|
+
* 520 coupons and 600 products: the page used to read the newest 500 coupons
|
|
11
|
+
* and check them against the first 500 products.
|
|
12
|
+
*/
|
|
13
|
+
type Dialect = 'sqlite' | 'postgres' | 'mysql'
|
|
14
|
+
type Run = (sql: string, values?: unknown[]) => Promise<unknown>
|
|
15
|
+
|
|
16
|
+
const ROWS = 520
|
|
17
|
+
const PRODUCTS = 600
|
|
18
|
+
const pad = (value: number, size = 3) => String(value).padStart(size, '0')
|
|
19
|
+
|
|
20
|
+
/** Codes run opposite to ids, every third in lower case; every tenth is for a product past the 500th. */
|
|
21
|
+
const COUPONS = Array.from({ length: ROWS }, (_, index) => {
|
|
22
|
+
const id = index + 1
|
|
23
|
+
const percentage = id % 2 === 1
|
|
24
|
+
return {
|
|
25
|
+
id,
|
|
26
|
+
code: id === 9 ? 'HALF_OFF' : `${id % 3 === 0 ? 'save' : 'SAVE'}${pad(ROWS + 1 - id)}`,
|
|
27
|
+
description: id === 11 ? 'Take 100% off' : id % 5 === 0 ? null : `Promo ${id}`,
|
|
28
|
+
status: (['Active', 'Scheduled', 'Expired'] as const)[id % 3]!,
|
|
29
|
+
active: id % 4 !== 0,
|
|
30
|
+
type: percentage ? 'percentage' : 'fixed_amount',
|
|
31
|
+
value: percentage ? (id % 90) + 1 : 100 + id,
|
|
32
|
+
limit: id % 6 === 0 ? null : 1000,
|
|
33
|
+
usage: (id * 13) % 50,
|
|
34
|
+
start: id % 7 === 0 ? null : `2026-01-${pad((id % 28) + 1, 2)}`,
|
|
35
|
+
end: id % 5 === 0 ? null : `2026-${pad((id % 12) + 1, 2)}-${pad((id % 28) + 1, 2)}`,
|
|
36
|
+
product: id % 10 === 0 ? 500 + (id % 100) + 1 : null,
|
|
37
|
+
freeProduct: id % 8 === 0 ? `FREE-${id}` : null,
|
|
38
|
+
}
|
|
39
|
+
})
|
|
40
|
+
type Coupon = typeof COUPONS[number]
|
|
41
|
+
|
|
42
|
+
function query(overrides: Partial<CouponListQuery> = {}): CouponListQuery {
|
|
43
|
+
return { search: '', status: '', enabled: '', type: '', sort: 'newest', direction: 'desc', page: 1, perPage: 25, ...overrides }
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** The order the database is asked for, in plain code. */
|
|
47
|
+
function ordered(rows: Coupon[], sort: CouponListQuery['sort'], direction: 'asc' | 'desc'): Coupon[] {
|
|
48
|
+
const sign = direction === 'asc' ? 1 : -1
|
|
49
|
+
const compare = (left: string | number, right: string | number) => left < right ? -1 : left > right ? 1 : 0
|
|
50
|
+
const key = (coupon: Coupon): string | number => {
|
|
51
|
+
switch (sort) {
|
|
52
|
+
case 'code': return coupon.code.toLowerCase()
|
|
53
|
+
case 'usage': return coupon.usage
|
|
54
|
+
case 'expiry': return coupon.end ?? ''
|
|
55
|
+
case 'start': return coupon.start ?? ''
|
|
56
|
+
case 'status': return coupon.status
|
|
57
|
+
case 'availability': return coupon.active ? 1 : 0
|
|
58
|
+
default: return coupon.id
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
const dated = (coupon: Coupon) => sort === 'expiry' ? coupon.end : sort === 'start' ? coupon.start : 'any'
|
|
62
|
+
return [...rows].sort((left, right) =>
|
|
63
|
+
(Number(!dated(left)) - Number(!dated(right)))
|
|
64
|
+
|| sign * compare(key(left), key(right))
|
|
65
|
+
|| (sort === 'code' || sort === 'newest' ? 0 : compare(left.code.toLowerCase(), right.code.toLowerCase()))
|
|
66
|
+
|| sign * (left.id - right.id))
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
const ids = (rows: Coupon[]) => rows.map(coupon => String(coupon.id))
|
|
70
|
+
|
|
71
|
+
async function setUp(run: Run, dialect: Dialect) {
|
|
72
|
+
const pk = dialect === 'postgres' ? 'BIGINT PRIMARY KEY' : 'INTEGER PRIMARY KEY'
|
|
73
|
+
const text = dialect === 'mysql' ? 'VARCHAR(255)' : 'TEXT'
|
|
74
|
+
const bool = dialect === 'postgres' ? 'BOOLEAN' : dialect === 'mysql' ? 'TINYINT(1)' : 'INTEGER'
|
|
75
|
+
const date = dialect === 'sqlite' ? 'TEXT' : 'DATE'
|
|
76
|
+
const time = dialect === 'sqlite' ? 'TEXT' : dialect === 'mysql' ? 'DATETIME(3)' : 'TIMESTAMP'
|
|
77
|
+
const p = (index: number) => dialect === 'postgres' ? `$${index}` : '?'
|
|
78
|
+
const rows = (count: number, columns: number) => Array.from({ length: count }, (_, i) => `(${Array.from({ length: columns }, (_, c) => p(i * columns + c + 1)).join(', ')})`).join(', ')
|
|
79
|
+
const flag = (value: boolean) => dialect === 'postgres' ? value : (value ? 1 : 0)
|
|
80
|
+
await run(`CREATE TABLE products (id ${pk}, name ${text})`)
|
|
81
|
+
await run(`CREATE TABLE coupons (id ${pk}, code ${text}, description ${text} NULL, status ${text}, is_active ${bool}, discount_type ${text}, discount_value INTEGER, min_order_amount INTEGER NULL, max_discount_amount INTEGER NULL, free_product_id ${text} NULL, product_id INTEGER NULL, usage_limit INTEGER NULL, usage_count INTEGER, start_date ${date} NULL, end_date ${date} NULL, created_at ${time})`)
|
|
82
|
+
await run(`INSERT INTO products (id, name) VALUES ${rows(PRODUCTS, 2)}`, Array.from({ length: PRODUCTS }, (_, i) => [i + 1, `Product ${i + 1}`]).flat())
|
|
83
|
+
await run(
|
|
84
|
+
`INSERT INTO coupons (id, code, description, status, is_active, discount_type, discount_value, free_product_id, product_id, usage_limit, usage_count, start_date, end_date, created_at) VALUES ${rows(ROWS, 14)}`,
|
|
85
|
+
COUPONS.flatMap(coupon => [
|
|
86
|
+
coupon.id, coupon.code, coupon.description, coupon.status, flag(coupon.active), coupon.type, coupon.value,
|
|
87
|
+
coupon.freeProduct, coupon.product, coupon.limit, coupon.usage, coupon.start, coupon.end, '2026-11-01 09:00:00',
|
|
88
|
+
]),
|
|
89
|
+
)
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
async function exercise(runner: CommerceSqlRunner, run: Run, dialect: Dialect) {
|
|
93
|
+
const page = (overrides: Partial<CouponListQuery> = {}) => readCouponPage(query(overrides), runner, dialect)
|
|
94
|
+
const idsOf = (result: { records: Array<{ id: string }> }) => result.records.map(record => record.id)
|
|
95
|
+
|
|
96
|
+
// Newest first, every one of them; coupons for products past the 500th read.
|
|
97
|
+
const first = await page()
|
|
98
|
+
expect(first.total).toBe(ROWS)
|
|
99
|
+
expect(idsOf(first)).toEqual(ids(ordered(COUPONS, 'newest', 'desc').slice(0, 25)))
|
|
100
|
+
expect(idsOf(await page({ page: 21 }))).toEqual(ids(ordered(COUPONS, 'newest', 'desc').slice(500)))
|
|
101
|
+
expect(first.records.find(record => record.id === '520')).toMatchObject({ productId: '521', endDate: '', startDate: '2026-01-17' })
|
|
102
|
+
|
|
103
|
+
// The cards and breakdowns are over every coupon.
|
|
104
|
+
const countWhere = (test: (coupon: Coupon) => boolean) => COUPONS.filter(test).length
|
|
105
|
+
expect(first.summary).toEqual({
|
|
106
|
+
total: ROWS,
|
|
107
|
+
enabled: countWhere(coupon => coupon.active),
|
|
108
|
+
active: countWhere(coupon => coupon.status === 'Active'),
|
|
109
|
+
scheduled: countWhere(coupon => coupon.status === 'Scheduled'),
|
|
110
|
+
expired: countWhere(coupon => coupon.status === 'Expired'),
|
|
111
|
+
percentage: countWhere(coupon => coupon.type === 'percentage'),
|
|
112
|
+
fixedAmount: countWhere(coupon => coupon.type === 'fixed_amount'),
|
|
113
|
+
redemptions: COUPONS.reduce((sum, coupon) => sum + coupon.usage, 0),
|
|
114
|
+
mostUsed: [...COUPONS]
|
|
115
|
+
.sort((left, right) => right.usage - left.usage || (left.code.toLowerCase() < right.code.toLowerCase() ? -1 : 1) || left.id - right.id)
|
|
116
|
+
.slice(0, 5)
|
|
117
|
+
.map(coupon => ({ id: String(coupon.id), code: coupon.code, usageCount: coupon.usage })),
|
|
118
|
+
})
|
|
119
|
+
|
|
120
|
+
// Every filter, together, and the search with % and _ taken literally.
|
|
121
|
+
const matching = COUPONS.filter(coupon => coupon.status === 'Scheduled' && coupon.active && coupon.type === 'fixed_amount')
|
|
122
|
+
expect(idsOf(await page({ status: 'Scheduled', enabled: 'enabled', type: 'fixed_amount', perPage: 100 }))).toEqual(ids(ordered(matching, 'newest', 'desc')))
|
|
123
|
+
expect((await page({ enabled: 'disabled' })).total).toBe(countWhere(coupon => !coupon.active))
|
|
124
|
+
expect(idsOf(await page({ search: '100%' }))).toEqual(['11'])
|
|
125
|
+
expect(idsOf(await page({ search: 'f_o' }))).toEqual(['9'])
|
|
126
|
+
expect(idsOf(await page({ search: 'free-16' }))).toEqual(['168', '160', '16'])
|
|
127
|
+
|
|
128
|
+
// Every sort, both ways; coupons without the date last either way.
|
|
129
|
+
for (const sort of ['code', 'usage', 'expiry', 'start', 'status', 'availability'] as const) {
|
|
130
|
+
for (const direction of ['asc', 'desc'] as const)
|
|
131
|
+
expect(idsOf(await page({ sort, direction, perPage: 100, page: 6 }))).toEqual(ids(ordered(COUPONS, sort, direction).slice(500)))
|
|
132
|
+
}
|
|
133
|
+
expect((await page({ sort: 'expiry', direction: 'desc', perPage: 10 })).records.every(record => record.endDate !== '')).toBe(true)
|
|
134
|
+
|
|
135
|
+
// The export: every matching coupon in the page's order, a batch at a time,
|
|
136
|
+
// a fixed amount in the store currency.
|
|
137
|
+
const fixed = COUPONS.filter(coupon => coupon.type === 'fixed_amount')
|
|
138
|
+
const exported = await readCouponsForExport({ search: '', status: '', enabled: '', type: 'fixed_amount', sort: 'usage', direction: 'desc' }, runner, dialect, 50)
|
|
139
|
+
expect(exported.map(record => record.id)).toEqual(ids(ordered(fixed, 'usage', 'desc')))
|
|
140
|
+
const top = ordered(fixed, 'usage', 'desc')[0]!
|
|
141
|
+
const csv = couponsCsv(exported.slice(0, 1), 'JPY', (amount, currency) => `${amount} ${currency}`)
|
|
142
|
+
expect(csv.charCodeAt(0)).toBe(0xFEFF)
|
|
143
|
+
expect(csv.slice(1).split('\n')[1]).toBe(
|
|
144
|
+
`"${top.code}","${top.description ?? ''}","${top.status}","${top.active ? 'Enabled' : 'Disabled'}","fixed_amount","${top.value} JPY","${top.usage}","${top.limit ?? ''}","${top.start ?? ''}","${top.end ?? ''}"`,
|
|
145
|
+
)
|
|
146
|
+
|
|
147
|
+
// A coupon for a product that does not exist still fails the page.
|
|
148
|
+
const p = (index: number) => dialect === 'postgres' ? `$${index}` : '?'
|
|
149
|
+
await run(`INSERT INTO coupons (id, code, status, is_active, discount_type, discount_value, product_id, usage_count, created_at) VALUES (${[1, 2, 3, 4, 5, 6, 7, 8, 9].map(p).join(', ')})`, [600, 'GONE', 'Active', dialect === 'postgres' ? true : 1, 'percentage', 5, 9999, 0, '2026-11-01 09:00:00'])
|
|
150
|
+
await expect(page()).rejects.toThrow('Coupon 600.product_id references missing Product 9999.')
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
describe('parseCouponListQuery', () => {
|
|
154
|
+
test('defaults and refusals', () => {
|
|
155
|
+
const read = (values: Record<string, string>) => parseCouponListQuery(key => values[key] ?? '')
|
|
156
|
+
expect(read({})).toEqual(query())
|
|
157
|
+
expect(read({ sort: 'code' })).toMatchObject({ sort: 'code', direction: 'asc' })
|
|
158
|
+
expect(read({ sort: 'usage' })).toMatchObject({ direction: 'desc' })
|
|
159
|
+
expect(read({ status: 'Paused' })).toEqual({ error: 'status must be one of Active, Scheduled, Expired.' })
|
|
160
|
+
expect(read({ type: 'free' })).toHaveProperty('error')
|
|
161
|
+
expect(read({ enabled: 'yes' })).toHaveProperty('error')
|
|
162
|
+
expect(read({ sort: 'discount' })).toHaveProperty('error')
|
|
163
|
+
})
|
|
164
|
+
})
|
|
165
|
+
|
|
166
|
+
describe('readCouponPage on SQLite', () => {
|
|
167
|
+
test('filters, search, sorts, pages, summary and export', async () => {
|
|
168
|
+
const database = new Database(':memory:')
|
|
169
|
+
const run: Run = async (sql, values = []) => database.query(sql).run(...(values as never[]))
|
|
170
|
+
await setUp(run, 'sqlite')
|
|
171
|
+
await exercise({ unsafe: (sql, values = []) => ({ execute: async () => database.query(sql).all(...(values as never[])) }) }, run, 'sqlite')
|
|
172
|
+
})
|
|
173
|
+
})
|
|
174
|
+
|
|
175
|
+
for (const dialect of ['postgres', 'mysql'] as const) {
|
|
176
|
+
const connection = dialect === 'postgres' ? process.env.STACKS_TEST_POSTGRES_URL : process.env.STACKS_TEST_MYSQL_URL
|
|
177
|
+
|
|
178
|
+
test.skipIf(!connection)(`readCouponPage on ${dialect}: filters, search, sorts, pages, summary and export`, async () => {
|
|
179
|
+
const url = new URL(connection!)
|
|
180
|
+
if (!['127.0.0.1', 'localhost', '[::1]'].includes(url.hostname))
|
|
181
|
+
throw new Error('Coupon list tests require a local disposable database server')
|
|
182
|
+
|
|
183
|
+
const name = `stacks_coupons_${crypto.randomUUID().replaceAll('-', '')}`
|
|
184
|
+
const quoted = dialect === 'mysql' ? `\`${name}\`` : `"${name}"`
|
|
185
|
+
const admin = new SQL({ url: url.href, database: decodeURIComponent(url.pathname.slice(1)) || undefined })
|
|
186
|
+
await admin.unsafe(`CREATE DATABASE ${quoted}`)
|
|
187
|
+
const scoped = new URL(url.href)
|
|
188
|
+
scoped.pathname = `/${name}`
|
|
189
|
+
// Explicit database wins over inherited PGDATABASE / MYSQL_DATABASE in CI.
|
|
190
|
+
const database = new SQL({ url: scoped.href, database: name })
|
|
191
|
+
|
|
192
|
+
try {
|
|
193
|
+
const run: Run = async (sql, values = []) => await database.unsafe(sql, values)
|
|
194
|
+
await setUp(run, dialect)
|
|
195
|
+
await exercise({ unsafe: (sql, values = []) => ({ execute: async () => await database.unsafe(sql, values) }) }, run, dialect)
|
|
196
|
+
}
|
|
197
|
+
finally {
|
|
198
|
+
await database.close()
|
|
199
|
+
try { await admin.unsafe(`DROP DATABASE ${quoted}${dialect === 'postgres' ? ' WITH (FORCE)' : ''}`) }
|
|
200
|
+
finally { await admin.close() }
|
|
201
|
+
}
|
|
202
|
+
}, 60_000)
|
|
203
|
+
}
|
|
@@ -0,0 +1,248 @@
|
|
|
1
|
+
import type { QueryBuilderDialect } from '@stacksjs/database/runtime'
|
|
2
|
+
import { db, getDatabaseDialect } from '@stacksjs/database/runtime'
|
|
3
|
+
import type { QueryReader } from '../Content/content-list'
|
|
4
|
+
import { containsPattern, countOf, LIST_PAGE_SIZES, pageWithin, queryText } from '../Content/content-list'
|
|
5
|
+
import { commerceIdentifier, commerceRequiredString, commerceValue, referencedIds } from './commerce-record'
|
|
6
|
+
import type { CommerceSqlRunner } from './commerce-sql'
|
|
7
|
+
import { asText, binder, idPlaceholders, isTrue, sqlRows } from './commerce-sql'
|
|
8
|
+
import type { CouponDiscountType, CouponRecord, CouponStatus, CouponSummary } from './coupon-records'
|
|
9
|
+
import { normalizeCouponRecord } from './coupon-records'
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* One page of coupons, searched, filtered, sorted and counted by the
|
|
13
|
+
* database, with the summary and breakdowns of every coupon
|
|
14
|
+
* (stacksjs/stacks#3218).
|
|
15
|
+
*
|
|
16
|
+
* The Coupons page used to read the newest 500 coupons and do all of that in
|
|
17
|
+
* the browser, so an older coupon could not be found, the cards, the status
|
|
18
|
+
* and type breakdowns and "Most redeemed" counted those 500, and "Export
|
|
19
|
+
* filtered" wrote only them. The record check read the first 500 products,
|
|
20
|
+
* so a coupon for any later product failed the whole page.
|
|
21
|
+
*/
|
|
22
|
+
export const COUPON_SORTS = ['newest', 'code', 'usage', 'expiry', 'start', 'status', 'availability'] as const
|
|
23
|
+
export type CouponSort = typeof COUPON_SORTS[number]
|
|
24
|
+
|
|
25
|
+
export const COUPON_STATUSES: readonly CouponStatus[] = ['Active', 'Scheduled', 'Expired']
|
|
26
|
+
export const COUPON_DISCOUNT_TYPES: readonly CouponDiscountType[] = ['percentage', 'fixed_amount']
|
|
27
|
+
|
|
28
|
+
export interface CouponListQuery {
|
|
29
|
+
search: string
|
|
30
|
+
/** '' for any. */
|
|
31
|
+
status: '' | CouponStatus
|
|
32
|
+
/** '' for any. */
|
|
33
|
+
enabled: '' | 'enabled' | 'disabled'
|
|
34
|
+
/** '' for any. */
|
|
35
|
+
type: '' | CouponDiscountType
|
|
36
|
+
sort: CouponSort
|
|
37
|
+
direction: 'asc' | 'desc'
|
|
38
|
+
page: number
|
|
39
|
+
perPage: number
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
const DESCENDING: readonly CouponSort[] = ['newest', 'usage']
|
|
43
|
+
|
|
44
|
+
export function parseCouponListQuery(read: QueryReader): CouponListQuery | { error: string } {
|
|
45
|
+
const pageText = queryText(read, 'page')
|
|
46
|
+
const page = pageText === '' ? 1 : Number(pageText)
|
|
47
|
+
if (!Number.isInteger(page) || page < 1)
|
|
48
|
+
return { error: 'page must be a whole number of 1 or more.' }
|
|
49
|
+
|
|
50
|
+
const sizeText = queryText(read, 'per_page')
|
|
51
|
+
const perPage = sizeText === '' ? 25 : Number(sizeText)
|
|
52
|
+
if (!(LIST_PAGE_SIZES as readonly number[]).includes(perPage))
|
|
53
|
+
return { error: `per_page must be one of ${LIST_PAGE_SIZES.join(', ')}.` }
|
|
54
|
+
|
|
55
|
+
const sort = queryText(read, 'sort') || 'newest'
|
|
56
|
+
if (!(COUPON_SORTS as readonly string[]).includes(sort))
|
|
57
|
+
return { error: `sort must be one of ${COUPON_SORTS.join(', ')}.` }
|
|
58
|
+
|
|
59
|
+
const directionText = queryText(read, 'direction').toLowerCase()
|
|
60
|
+
const direction = directionText === '' ? (DESCENDING.includes(sort as CouponSort) ? 'desc' : 'asc') : directionText
|
|
61
|
+
if (direction !== 'asc' && direction !== 'desc')
|
|
62
|
+
return { error: 'direction must be asc or desc.' }
|
|
63
|
+
|
|
64
|
+
const search = queryText(read, 'q')
|
|
65
|
+
if (search.length > 200)
|
|
66
|
+
return { error: 'q must be 200 characters or fewer.' }
|
|
67
|
+
|
|
68
|
+
const status = queryText(read, 'status')
|
|
69
|
+
if (status && !(COUPON_STATUSES as readonly string[]).includes(status))
|
|
70
|
+
return { error: `status must be one of ${COUPON_STATUSES.join(', ')}.` }
|
|
71
|
+
|
|
72
|
+
const enabled = queryText(read, 'enabled')
|
|
73
|
+
if (enabled && enabled !== 'enabled' && enabled !== 'disabled')
|
|
74
|
+
return { error: 'enabled must be enabled or disabled.' }
|
|
75
|
+
|
|
76
|
+
const type = queryText(read, 'type')
|
|
77
|
+
if (type && !(COUPON_DISCOUNT_TYPES as readonly string[]).includes(type))
|
|
78
|
+
return { error: `type must be one of ${COUPON_DISCOUNT_TYPES.join(', ')}.` }
|
|
79
|
+
|
|
80
|
+
return {
|
|
81
|
+
search,
|
|
82
|
+
status: status as CouponListQuery['status'],
|
|
83
|
+
enabled: enabled as CouponListQuery['enabled'],
|
|
84
|
+
type: type as CouponListQuery['type'],
|
|
85
|
+
sort: sort as CouponSort,
|
|
86
|
+
direction,
|
|
87
|
+
page,
|
|
88
|
+
perPage,
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
function sortExpression(sort: CouponSort, dialect: QueryBuilderDialect): string {
|
|
93
|
+
switch (sort) {
|
|
94
|
+
case 'code': return 'LOWER(code)'
|
|
95
|
+
case 'usage': return 'usage_count'
|
|
96
|
+
case 'expiry': return 'end_date'
|
|
97
|
+
case 'start': return 'start_date'
|
|
98
|
+
case 'status': return asText('status', dialect)
|
|
99
|
+
case 'availability': return `CASE WHEN ${isTrue('is_active', dialect)} THEN 1 ELSE 0 END`
|
|
100
|
+
default: return 'id'
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
export function couponFilter(query: Pick<CouponListQuery, 'search' | 'status' | 'enabled' | 'type'>, dialect: QueryBuilderDialect): { where: string, values: unknown[] } {
|
|
105
|
+
const { bind, values } = binder(dialect)
|
|
106
|
+
const clauses: string[] = []
|
|
107
|
+
// Text comparisons: PostgreSQL may keep these as enums.
|
|
108
|
+
if (query.status)
|
|
109
|
+
clauses.push(`${asText('status', dialect)} = ${bind(query.status)}`)
|
|
110
|
+
if (query.type)
|
|
111
|
+
clauses.push(`${asText('discount_type', dialect)} = ${bind(query.type)}`)
|
|
112
|
+
if (query.enabled === 'enabled')
|
|
113
|
+
clauses.push(isTrue('is_active', dialect))
|
|
114
|
+
if (query.enabled === 'disabled')
|
|
115
|
+
clauses.push(`NOT (${isTrue('is_active', dialect)})`)
|
|
116
|
+
if (query.search) {
|
|
117
|
+
const pattern = containsPattern(query.search)
|
|
118
|
+
const columns = ['code', `COALESCE(description, '')`, `COALESCE(free_product_id, '')`]
|
|
119
|
+
clauses.push(`(${columns.map(column => `LOWER(${column}) LIKE ${bind(pattern)} ESCAPE '!'`).join(' OR ')})`)
|
|
120
|
+
}
|
|
121
|
+
return { where: clauses.length > 0 ? ` WHERE ${clauses.join(' AND ')}` : '', values }
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
function orderBy(query: Pick<CouponListQuery, 'sort' | 'direction'>, dialect: QueryBuilderDialect): string {
|
|
125
|
+
const direction = query.direction === 'asc' ? 'ASC' : 'DESC'
|
|
126
|
+
if (query.sort === 'newest')
|
|
127
|
+
return ` ORDER BY id ${direction}`
|
|
128
|
+
// Coupons without the date come last either way: each dialect puts NULL at
|
|
129
|
+
// a different end of the order, and a coupon with no end never expires.
|
|
130
|
+
const column = query.sort === 'expiry' ? 'end_date' : query.sort === 'start' ? 'start_date' : ''
|
|
131
|
+
const undated = column ? `CASE WHEN ${column} IS NULL THEN 1 ELSE 0 END ASC, ` : ''
|
|
132
|
+
// Ties read by code, as the page sorted them; the id breaks every
|
|
133
|
+
// remaining tie, so pages never repeat or skip a coupon.
|
|
134
|
+
const byCode = query.sort === 'code' ? '' : ', LOWER(code) ASC'
|
|
135
|
+
return ` ORDER BY ${undated}${sortExpression(query.sort, dialect)} ${direction}${byCode}, id ${direction}`
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
/** Coupons turned into records, against exactly the products they reference. */
|
|
139
|
+
async function recordsFor(coupons: Array<Record<string, unknown>>, run: CommerceSqlRunner, dialect: QueryBuilderDialect): Promise<CouponRecord[]> {
|
|
140
|
+
if (coupons.length === 0)
|
|
141
|
+
return []
|
|
142
|
+
const productIds = referencedIds(coupons, 'product_id')
|
|
143
|
+
const products = productIds.length > 0
|
|
144
|
+
? await run.unsafe(`SELECT id FROM products WHERE id IN (${idPlaceholders(productIds, dialect)})`, productIds).execute()
|
|
145
|
+
: []
|
|
146
|
+
const known = new Set(sqlRows(products).map(row => commerceIdentifier(commerceValue(row, 'id'), 'Product')))
|
|
147
|
+
return coupons.map(coupon => normalizeCouponRecord(coupon, known))
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
/** The summary cards and breakdowns, over every coupon as before. */
|
|
151
|
+
async function summarize(run: CommerceSqlRunner, dialect: QueryBuilderDialect): Promise<CouponSummary> {
|
|
152
|
+
const status = asText('status', dialect)
|
|
153
|
+
const type = asText('discount_type', dialect)
|
|
154
|
+
const count = (condition: string) => `SUM(CASE WHEN ${condition} THEN 1 ELSE 0 END)`
|
|
155
|
+
const [totals, used] = await Promise.all([
|
|
156
|
+
run.unsafe(`SELECT COUNT(*) AS total_count, ${count(isTrue('is_active', dialect))} AS enabled_count, ${count(`${status} = 'Active'`)} AS active_count, ${count(`${status} = 'Scheduled'`)} AS scheduled_count, ${count(`${status} = 'Expired'`)} AS expired_count, ${count(`${type} = 'percentage'`)} AS percentage_count, ${count(`${type} = 'fixed_amount'`)} AS fixed_count, SUM(usage_count) AS usage_total FROM coupons`).execute(),
|
|
157
|
+
// "Most redeemed": the five most used, by code on a tie, as the page chose them.
|
|
158
|
+
run.unsafe('SELECT id, code, usage_count FROM coupons ORDER BY usage_count DESC, LOWER(code) ASC, id ASC LIMIT 5').execute(),
|
|
159
|
+
])
|
|
160
|
+
const row = sqlRows(totals)[0] ?? {}
|
|
161
|
+
return {
|
|
162
|
+
total: countOf(row.total_count),
|
|
163
|
+
enabled: countOf(row.enabled_count),
|
|
164
|
+
active: countOf(row.active_count),
|
|
165
|
+
scheduled: countOf(row.scheduled_count),
|
|
166
|
+
expired: countOf(row.expired_count),
|
|
167
|
+
percentage: countOf(row.percentage_count),
|
|
168
|
+
fixedAmount: countOf(row.fixed_count),
|
|
169
|
+
redemptions: countOf(row.usage_total),
|
|
170
|
+
mostUsed: sqlRows(used).map((entry) => {
|
|
171
|
+
const id = commerceIdentifier(commerceValue(entry, 'id'), 'Coupon')
|
|
172
|
+
return { id, code: commerceRequiredString(commerceValue(entry, 'code'), `Coupon ${id}`, 'code'), usageCount: countOf(entry.usage_count) }
|
|
173
|
+
}),
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
export interface CouponPage {
|
|
178
|
+
records: CouponRecord[]
|
|
179
|
+
total: number
|
|
180
|
+
page: number
|
|
181
|
+
summary: CouponSummary
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
export async function readCouponPage(
|
|
185
|
+
query: CouponListQuery,
|
|
186
|
+
run: CommerceSqlRunner = db,
|
|
187
|
+
dialect: QueryBuilderDialect = getDatabaseDialect(),
|
|
188
|
+
): Promise<CouponPage> {
|
|
189
|
+
const { where, values } = couponFilter(query, dialect)
|
|
190
|
+
const [counted, summary] = await Promise.all([
|
|
191
|
+
run.unsafe(`SELECT COUNT(*) AS total_count FROM coupons${where}`, values).execute(),
|
|
192
|
+
summarize(run, dialect),
|
|
193
|
+
])
|
|
194
|
+
const total = countOf(sqlRows(counted)[0]?.total_count)
|
|
195
|
+
const page = pageWithin(query.page, total, query.perPage)
|
|
196
|
+
const coupons = await run.unsafe(
|
|
197
|
+
`SELECT * FROM coupons${where}${orderBy(query, dialect)} LIMIT ${query.perPage} OFFSET ${(page - 1) * query.perPage}`,
|
|
198
|
+
values,
|
|
199
|
+
).execute()
|
|
200
|
+
return { records: await recordsFor(sqlRows(coupons), run, dialect), total, page, summary }
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
/** Every coupon matching the query, in its order, for the CSV export, a batch at a time. */
|
|
204
|
+
export async function readCouponsForExport(
|
|
205
|
+
query: Omit<CouponListQuery, 'page' | 'perPage'>,
|
|
206
|
+
run: CommerceSqlRunner = db,
|
|
207
|
+
dialect: QueryBuilderDialect = getDatabaseDialect(),
|
|
208
|
+
batchSize: number = 500,
|
|
209
|
+
): Promise<CouponRecord[]> {
|
|
210
|
+
const { where, values } = couponFilter(query, dialect)
|
|
211
|
+
const records: CouponRecord[] = []
|
|
212
|
+
for (let offset = 0; ; offset += batchSize) {
|
|
213
|
+
const batch = sqlRows(await run.unsafe(
|
|
214
|
+
`SELECT * FROM coupons${where}${orderBy(query, dialect)} LIMIT ${batchSize} OFFSET ${offset}`,
|
|
215
|
+
values,
|
|
216
|
+
).execute())
|
|
217
|
+
records.push(...await recordsFor(batch, run, dialect))
|
|
218
|
+
if (batch.length < batchSize)
|
|
219
|
+
return records
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
/** A byte order mark, so spreadsheet apps read the file as UTF-8. */
|
|
224
|
+
const BOM = String.fromCharCode(0xFEFF)
|
|
225
|
+
|
|
226
|
+
/**
|
|
227
|
+
* The CSV "Export filtered" downloads: the page's columns, for every matching
|
|
228
|
+
* coupon. A fixed amount is stored in minor units of the store currency, and
|
|
229
|
+
* the file carries it as a decimal of that currency; the page used to write
|
|
230
|
+
* it as US dollars whatever the store used.
|
|
231
|
+
*/
|
|
232
|
+
export function couponsCsv(records: CouponRecord[], currency: string, minor: (amount: number, currency: string) => string): string {
|
|
233
|
+
const escape = (value: string): string => `"${value.replaceAll('"', '""')}"`
|
|
234
|
+
const header = ['Code', 'Description', 'Status', 'Availability', 'Discount type', 'Discount value', 'Usage count', 'Usage limit', 'Start date', 'End date']
|
|
235
|
+
const lines = records.map(record => [
|
|
236
|
+
record.code,
|
|
237
|
+
record.description,
|
|
238
|
+
record.status,
|
|
239
|
+
record.isActive ? 'Enabled' : 'Disabled',
|
|
240
|
+
record.discountType,
|
|
241
|
+
record.discountType === 'fixed_amount' ? minor(record.discountValue, currency) : String(record.discountValue),
|
|
242
|
+
String(record.usageCount),
|
|
243
|
+
record.usageLimit === null ? '' : String(record.usageLimit),
|
|
244
|
+
record.startDate,
|
|
245
|
+
record.endDate,
|
|
246
|
+
])
|
|
247
|
+
return `${BOM}${[header, ...lines].map(row => row.map(escape).join(',')).join('\n')}`
|
|
248
|
+
}
|
|
@@ -0,0 +1,183 @@
|
|
|
1
|
+
import { Database } from 'bun:sqlite'
|
|
2
|
+
import { SQL } from 'bun'
|
|
3
|
+
import { describe, expect, test } from 'bun:test'
|
|
4
|
+
import type { CustomerListQuery } from './commerce-customer-list'
|
|
5
|
+
import { customersCsv, parseCustomerListQuery, readCustomerPage, readCustomersForExport } from './commerce-customer-list'
|
|
6
|
+
import type { CommerceSqlRunner } from './commerce-sql'
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* The customers against each dialect's real engine (stacksjs/stacks#3218),
|
|
10
|
+
* over 520 of them: the page used to read the first 500 by name.
|
|
11
|
+
*/
|
|
12
|
+
type Dialect = 'sqlite' | 'postgres' | 'mysql'
|
|
13
|
+
type Run = (sql: string, values?: unknown[]) => Promise<unknown>
|
|
14
|
+
|
|
15
|
+
const ROWS = 520
|
|
16
|
+
const pad = (value: number) => String(value).padStart(3, '0')
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* Names run opposite to ids, every third in lower case; every fifth has no
|
|
20
|
+
* phone; every fourth never ordered and every fourth after it has an empty
|
|
21
|
+
* last order; every third is Inactive; spend repeats, so ties are broken.
|
|
22
|
+
*/
|
|
23
|
+
const CUSTOMERS = Array.from({ length: ROWS }, (_, index) => {
|
|
24
|
+
const id = index + 1
|
|
25
|
+
const name = id === 7 ? 'Ann 100% Cotton' : `${id % 3 === 0 ? 'customer' : 'Customer'} ${pad(ROWS + 1 - id)}`
|
|
26
|
+
return {
|
|
27
|
+
id,
|
|
28
|
+
name,
|
|
29
|
+
email: `buyer${id}@shop.test`,
|
|
30
|
+
phone: id % 5 === 0 ? null : `+1 555 ${pad(id)}`,
|
|
31
|
+
spent: (id * 37) % 1000,
|
|
32
|
+
lastOrder: id % 4 === 0 ? null : id % 4 === 1 ? '' : `2026-10-${String((id % 28) + 1).padStart(2, '0')}`,
|
|
33
|
+
status: id % 3 === 0 ? 'Inactive' : 'Active',
|
|
34
|
+
}
|
|
35
|
+
})
|
|
36
|
+
type Customer = typeof CUSTOMERS[number]
|
|
37
|
+
|
|
38
|
+
function query(overrides: Partial<CustomerListQuery> = {}): CustomerListQuery {
|
|
39
|
+
return { search: '', status: '', sort: 'name', direction: 'asc', page: 1, perPage: 25, ...overrides }
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/** The order the database is asked for, in plain code. */
|
|
43
|
+
function ordered(rows: Customer[], sort: CustomerListQuery['sort'], direction: 'asc' | 'desc'): Customer[] {
|
|
44
|
+
const sign = direction === 'asc' ? 1 : -1
|
|
45
|
+
const compare = (left: string | number, right: string | number) => left < right ? -1 : left > right ? 1 : 0
|
|
46
|
+
const key = (customer: Customer): string | number => {
|
|
47
|
+
switch (sort) {
|
|
48
|
+
case 'spend': return customer.spent
|
|
49
|
+
case 'last-order': return customer.lastOrder ?? ''
|
|
50
|
+
case 'status': return customer.status
|
|
51
|
+
case 'newest': return customer.id
|
|
52
|
+
default: return customer.name.toLowerCase()
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
return [...rows].sort((left, right) => {
|
|
56
|
+
if (sort === 'last-order') {
|
|
57
|
+
const unordered = Number(!left.lastOrder) - Number(!right.lastOrder)
|
|
58
|
+
if (unordered !== 0)
|
|
59
|
+
return unordered
|
|
60
|
+
}
|
|
61
|
+
return sign * compare(key(left), key(right))
|
|
62
|
+
|| (sort === 'name' || sort === 'newest' ? 0 : compare(left.name.toLowerCase(), right.name.toLowerCase()))
|
|
63
|
+
|| sign * (left.id - right.id)
|
|
64
|
+
})
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
const ids = (rows: Customer[]) => rows.map(customer => String(customer.id))
|
|
68
|
+
|
|
69
|
+
async function setUp(run: Run, dialect: Dialect) {
|
|
70
|
+
const pk = dialect === 'postgres' ? 'BIGINT PRIMARY KEY' : 'INTEGER PRIMARY KEY'
|
|
71
|
+
const text = dialect === 'mysql' ? 'VARCHAR(255)' : 'TEXT'
|
|
72
|
+
const time = dialect === 'sqlite' ? 'TEXT' : dialect === 'mysql' ? 'DATETIME(3)' : 'TIMESTAMP'
|
|
73
|
+
const p = (index: number) => dialect === 'postgres' ? `$${index}` : '?'
|
|
74
|
+
const columns = 9
|
|
75
|
+
await run(`CREATE TABLE customers (id ${pk}, name ${text}, email ${text}, phone ${text} NULL, total_spent INTEGER, last_order ${text} NULL, status ${text}, avatar ${text}, created_at ${time})`)
|
|
76
|
+
await run(
|
|
77
|
+
`INSERT INTO customers (id, name, email, phone, total_spent, last_order, status, avatar, created_at) VALUES ${CUSTOMERS.map((_, i) => `(${Array.from({ length: columns }, (_, c) => p(i * columns + c + 1)).join(', ')})`).join(', ')}`,
|
|
78
|
+
CUSTOMERS.flatMap(customer => [
|
|
79
|
+
customer.id, customer.name, customer.email, customer.phone, customer.spent, customer.lastOrder, customer.status,
|
|
80
|
+
`https://example.test/${customer.id}.jpg`, '2026-11-01 09:00:00',
|
|
81
|
+
]),
|
|
82
|
+
)
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
async function exercise(runner: CommerceSqlRunner, dialect: Dialect) {
|
|
86
|
+
const page = (overrides: Partial<CustomerListQuery> = {}) => readCustomerPage(query(overrides), runner, dialect)
|
|
87
|
+
const idsOf = (result: { records: Array<{ id: string }> }) => result.records.map(record => record.id)
|
|
88
|
+
|
|
89
|
+
// By name, every one of them, the last page past the 500th.
|
|
90
|
+
const byName = ordered(CUSTOMERS, 'name', 'asc')
|
|
91
|
+
const first = await page()
|
|
92
|
+
expect(first.total).toBe(ROWS)
|
|
93
|
+
expect(idsOf(first)).toEqual(ids(byName.slice(0, 25)))
|
|
94
|
+
expect(idsOf(await page({ page: 21 }))).toEqual(ids(byName.slice(500)))
|
|
95
|
+
expect((await page({ page: 99 })).page).toBe(21)
|
|
96
|
+
|
|
97
|
+
// The summary is over every customer.
|
|
98
|
+
expect(first.summary).toEqual({
|
|
99
|
+
total: ROWS,
|
|
100
|
+
active: CUSTOMERS.filter(customer => customer.status === 'Active').length,
|
|
101
|
+
inactive: CUSTOMERS.filter(customer => customer.status === 'Inactive').length,
|
|
102
|
+
totalSpent: CUSTOMERS.reduce((sum, customer) => sum + customer.spent, 0),
|
|
103
|
+
averageSpent: CUSTOMERS.reduce((sum, customer) => sum + customer.spent, 0) / ROWS,
|
|
104
|
+
})
|
|
105
|
+
|
|
106
|
+
// The status filter and the search, over name, email and phone, % taken literally.
|
|
107
|
+
const inactive = CUSTOMERS.filter(customer => customer.status === 'Inactive')
|
|
108
|
+
expect((await page({ status: 'Inactive', perPage: 200 })).records.map(record => record.id)).toEqual(ids(ordered(inactive, 'name', 'asc')).slice(0, 200))
|
|
109
|
+
expect(idsOf(await page({ search: '100%' }))).toEqual(['7'])
|
|
110
|
+
expect(idsOf(await page({ search: 'BUYER519@' }))).toEqual(['519'])
|
|
111
|
+
expect(idsOf(await page({ search: '555 512' }))).toEqual(['512'])
|
|
112
|
+
expect((await page({ search: 'customer 00' })).total).toBe(9)
|
|
113
|
+
|
|
114
|
+
// Every sort, both ways, ties broken by name and then id.
|
|
115
|
+
for (const sort of ['spend', 'last-order', 'status', 'newest'] as const) {
|
|
116
|
+
for (const direction of ['asc', 'desc'] as const)
|
|
117
|
+
expect(idsOf(await page({ sort, direction, perPage: 100, page: 6 }))).toEqual(ids(ordered(CUSTOMERS, sort, direction).slice(500)))
|
|
118
|
+
}
|
|
119
|
+
// Customers who never ordered come last, whichever way.
|
|
120
|
+
const latest = await page({ sort: 'last-order', direction: 'desc', perPage: 10 })
|
|
121
|
+
expect(latest.records.every(record => record.lastOrder !== '')).toBe(true)
|
|
122
|
+
|
|
123
|
+
// The export: every matching customer in the page's order, a batch at a time.
|
|
124
|
+
const exported = await readCustomersForExport({ search: '', status: 'Inactive', sort: 'spend', direction: 'desc' }, runner, dialect, 50)
|
|
125
|
+
expect(exported.map(record => record.id)).toEqual(ids(ordered(inactive, 'spend', 'desc')))
|
|
126
|
+
const csv = customersCsv(exported.slice(0, 1), 'EUR', (amount, currency) => `${amount} ${currency}`)
|
|
127
|
+
const top = ordered(inactive, 'spend', 'desc')[0]!
|
|
128
|
+
expect(csv.charCodeAt(0)).toBe(0xFEFF)
|
|
129
|
+
expect(csv.slice(1).split('\n')).toEqual([
|
|
130
|
+
'"Name","Email","Phone","Status","Total spent (EUR)","Last order","Avatar URL"',
|
|
131
|
+
`"${top.name}","${top.email}","${top.phone ?? ''}","Inactive","${top.spent} EUR","${exported[0]!.lastOrder}","https://example.test/${top.id}.jpg"`,
|
|
132
|
+
])
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
describe('parseCustomerListQuery', () => {
|
|
136
|
+
test('defaults and refusals', () => {
|
|
137
|
+
const read = (values: Record<string, string>) => parseCustomerListQuery(key => values[key] ?? '')
|
|
138
|
+
expect(read({})).toEqual(query())
|
|
139
|
+
expect(read({ sort: 'spend' })).toMatchObject({ sort: 'spend', direction: 'desc' })
|
|
140
|
+
expect(read({ sort: 'last-order' })).toMatchObject({ direction: 'desc' })
|
|
141
|
+
expect(read({ status: 'Unknown' })).toEqual({ error: 'status must be one of Active, Inactive.' })
|
|
142
|
+
expect(read({ sort: 'phone' })).toHaveProperty('error')
|
|
143
|
+
expect(read({ per_page: '7' })).toHaveProperty('error')
|
|
144
|
+
expect(read({ page: '0' })).toHaveProperty('error')
|
|
145
|
+
})
|
|
146
|
+
})
|
|
147
|
+
|
|
148
|
+
describe('readCustomerPage on SQLite', () => {
|
|
149
|
+
test('search, filter, sorts, pages, summary and export', async () => {
|
|
150
|
+
const database = new Database(':memory:')
|
|
151
|
+
await setUp(async (sql, values = []) => database.query(sql).run(...(values as never[])), 'sqlite')
|
|
152
|
+
await exercise({ unsafe: (sql, values = []) => ({ execute: async () => database.query(sql).all(...(values as never[])) }) }, 'sqlite')
|
|
153
|
+
})
|
|
154
|
+
})
|
|
155
|
+
|
|
156
|
+
for (const dialect of ['postgres', 'mysql'] as const) {
|
|
157
|
+
const connection = dialect === 'postgres' ? process.env.STACKS_TEST_POSTGRES_URL : process.env.STACKS_TEST_MYSQL_URL
|
|
158
|
+
|
|
159
|
+
test.skipIf(!connection)(`readCustomerPage on ${dialect}: search, filter, sorts, pages, summary and export`, async () => {
|
|
160
|
+
const url = new URL(connection!)
|
|
161
|
+
if (!['127.0.0.1', 'localhost', '[::1]'].includes(url.hostname))
|
|
162
|
+
throw new Error('Customer list tests require a local disposable database server')
|
|
163
|
+
|
|
164
|
+
const name = `stacks_customers_${crypto.randomUUID().replaceAll('-', '')}`
|
|
165
|
+
const quoted = dialect === 'mysql' ? `\`${name}\`` : `"${name}"`
|
|
166
|
+
const admin = new SQL({ url: url.href, database: decodeURIComponent(url.pathname.slice(1)) || undefined })
|
|
167
|
+
await admin.unsafe(`CREATE DATABASE ${quoted}`)
|
|
168
|
+
const scoped = new URL(url.href)
|
|
169
|
+
scoped.pathname = `/${name}`
|
|
170
|
+
// Explicit database wins over inherited PGDATABASE / MYSQL_DATABASE in CI.
|
|
171
|
+
const database = new SQL({ url: scoped.href, database: name })
|
|
172
|
+
|
|
173
|
+
try {
|
|
174
|
+
await setUp(async (sql, values = []) => await database.unsafe(sql, values), dialect)
|
|
175
|
+
await exercise({ unsafe: (sql, values = []) => ({ execute: async () => await database.unsafe(sql, values) }) }, dialect)
|
|
176
|
+
}
|
|
177
|
+
finally {
|
|
178
|
+
await database.close()
|
|
179
|
+
try { await admin.unsafe(`DROP DATABASE ${quoted}${dialect === 'postgres' ? ' WITH (FORCE)' : ''}`) }
|
|
180
|
+
finally { await admin.close() }
|
|
181
|
+
}
|
|
182
|
+
}, 60_000)
|
|
183
|
+
}
|