@stacksjs/defaults 0.75.617 → 0.75.621
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-auth/SKILL.md +12 -1
- package/ai/skills/stacks-auto-imports/SKILL.md +1 -1
- package/ai/skills/stacks-commerce/SKILL.md +78 -4
- 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 +10 -2
- package/ai/skills/stacks-mobile/SKILL.md +21 -2
- package/ai/skills/stacks-models/SKILL.md +2 -2
- package/ai/skills/stacks-native/CATALOG.md +11 -11
- package/ai/skills/stacks-orm/SKILL.md +2 -2
- package/app/Actions/Dashboard/Commerce/CommerceDiscountDestroyAction.ts +27 -0
- package/app/Actions/Dashboard/Commerce/CommerceDiscountStoreAction.ts +28 -0
- package/app/Actions/Dashboard/Commerce/CommerceDiscountUpdateAction.ts +30 -0
- package/app/Actions/Dashboard/Commerce/CommerceDiscountsAction.ts +42 -0
- package/app/Actions/Dashboard/Commerce/CommerceUpsellDestroyAction.ts +31 -0
- package/app/Actions/Dashboard/Commerce/CommerceUpsellDetailAction.ts +28 -0
- package/app/Actions/Dashboard/Commerce/CommerceUpsellStoreAction.ts +26 -0
- package/app/Actions/Dashboard/Commerce/CommerceUpsellUpdateAction.ts +29 -0
- package/app/Actions/Dashboard/Commerce/CommerceUpsellsAction.ts +40 -0
- package/app/Actions/Dashboard/Commerce/commerce-discount-list.ts +204 -0
- package/app/Actions/Dashboard/Commerce/commerce-discount-write.ts +53 -0
- package/app/Actions/Dashboard/Commerce/commerce-discounts-upsells.test.ts +228 -0
- package/app/Actions/Dashboard/Commerce/commerce-upsell-list.ts +289 -0
- package/app/Actions/Dashboard/Commerce/discount-records.ts +392 -0
- package/app/Actions/Dashboard/Commerce/upsell-offer-records.ts +307 -0
- package/app/Actions/Dashboard/Models/ModelSaveAction.ts +6 -1
- package/app/Actions/Dashboard/Models/model-relations.ts +17 -7
- package/app/Actions/Dashboard/Models/model-row-writes.ts +9 -8
- package/app/Actions/Dashboard/Models/model-write.ts +51 -2
- package/app/Actions/Dashboard/Remote/RemoteCommandRunAction.ts +1 -2
- package/app/Actions/Dashboard/Remote/RemoteTerminalCloseAction.ts +1 -2
- package/app/Actions/Dashboard/Remote/RemoteTerminalInputAction.ts +1 -2
- package/app/Actions/Dashboard/Remote/RemoteTerminalOpenAction.ts +1 -2
- package/app/Actions/Dashboard/Remote/RemoteTerminalResizeAction.ts +1 -2
- package/app/Actions/Dashboard/Remote/RemoteTerminalStreamAction.ts +1 -2
- package/app/Actions/Dashboard/Remote/remote-commands.test.ts +2 -2
- package/app/Actions/Dashboard/Remote/remote-commands.ts +4 -4
- package/app/Actions/Dashboard/Remote/remote-terminal.test.ts +45 -25
- package/app/Actions/Dashboard/Remote/remote-terminal.ts +9 -9
- package/app/Actions/Storefront/AcceptOrderOfferAction.ts +68 -0
- package/app/Actions/Storefront/ApplyDiscountCodeAction.ts +83 -0
- package/app/Actions/Storefront/DeclineOrderOfferAction.ts +25 -0
- package/app/Actions/Storefront/PlaceOrderAction.ts +135 -72
- package/app/Gates.ts +4 -4
- package/app/Mail/OrderConfirmation.ts +7 -1
- package/app/Models/commerce/Cart.ts +14 -0
- package/app/Models/commerce/Discount.ts +255 -0
- package/app/Models/commerce/PostPurchaseOffer.ts +175 -0
- package/app/Models/commerce/PostPurchaseOfferResponse.ts +145 -0
- package/app/Policies/PostPolicy.ts +11 -11
- package/app/Storefront/DiscountCodeMessages.ts +12 -0
- package/app/Storefront/OrderKey.ts +29 -0
- package/app/Storefront/StorefrontPricing.ts +211 -0
- package/app/Storefront/UpsellCharge.ts +43 -0
- package/ide/vscode/package.json +1 -1
- package/package.json +7 -7
- package/resources/components/Dashboard/Commerce/CommerceDiscountBreakdown.stx +72 -0
- package/resources/components/Dashboard/Commerce/CommerceDiscountDeleteDialog.stx +19 -0
- package/resources/components/Dashboard/Commerce/CommerceDiscountDetailsDialog.stx +110 -0
- package/resources/components/Dashboard/Commerce/CommerceDiscountDialog.stx +353 -0
- package/resources/components/Dashboard/Commerce/CommerceDiscountsDashboard.stx +211 -0
- package/resources/components/Dashboard/Commerce/CommerceDiscountsTable.stx +105 -0
- package/resources/components/Dashboard/Commerce/CommerceProductPicker.stx +115 -0
- package/resources/components/Dashboard/Commerce/CommerceUpsellDeleteDialog.stx +21 -0
- package/resources/components/Dashboard/Commerce/CommerceUpsellDetailsDialog.stx +153 -0
- package/resources/components/Dashboard/Commerce/CommerceUpsellDialog.stx +191 -0
- package/resources/components/Dashboard/Commerce/CommerceUpsellsDashboard.stx +214 -0
- package/resources/components/Dashboard/Commerce/CommerceUpsellsTable.stx +91 -0
- package/resources/components/Dashboard/Email/InboxSettingsDashboard.stx +4 -19
- package/resources/components/Dashboard/Settings/SettingsDashboard.stx +5 -3
- package/resources/components/Dashboard/UI/SearchFilter.stx +7 -4
- package/resources/components/Storefront/OrderSummary.stx +17 -0
- package/resources/functions/dashboard/sidebar.ts +4 -1
- package/resources/views/cart.stx +50 -16
- package/resources/views/checkout/contact.stx +11 -5
- package/resources/views/checkout/payment.stx +11 -5
- package/resources/views/checkout/shipping.stx +11 -5
- package/resources/views/orders/[id].stx +227 -50
- package/routes/dashboard-api.ts +12 -0
- package/routes/dashboard.ts +2 -0
- package/routes/storefront.ts +8 -0
- package/views/dashboard/commerce/discounts/index.stx +10 -0
- package/views/dashboard/commerce/upsells/index.stx +10 -0
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import type { RequestInstance } from '@stacksjs/types'
|
|
2
|
+
import { Action } from '@stacksjs/actions/runtime'
|
|
3
|
+
import { response } from '@stacksjs/router'
|
|
4
|
+
import { dashboardOperationalError } from '../dashboard-response'
|
|
5
|
+
import { deleteUpsellOffer } from './commerce-upsell-list'
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* `DELETE /api/dashboard/commerce/upsells/{id}` - remove an offer nobody has
|
|
9
|
+
* answered. One with responses is refused (409): switch it off instead.
|
|
10
|
+
*/
|
|
11
|
+
export default new Action({
|
|
12
|
+
name: 'CommerceUpsellDestroyAction',
|
|
13
|
+
description: 'Deletes an unanswered post-purchase offer from the dashboard.',
|
|
14
|
+
method: 'DELETE',
|
|
15
|
+
apiResponse: true,
|
|
16
|
+
|
|
17
|
+
async handle(request: RequestInstance) {
|
|
18
|
+
const id = Number(request.getParam('id'))
|
|
19
|
+
if (!Number.isSafeInteger(id) || id <= 0)
|
|
20
|
+
return response.json({ message: 'The offer id must be a positive whole number.' }, 422)
|
|
21
|
+
try {
|
|
22
|
+
const result = await deleteUpsellOffer(id)
|
|
23
|
+
if (!result.ok)
|
|
24
|
+
return response.json({ message: result.message }, result.status)
|
|
25
|
+
return response.json({ ok: true })
|
|
26
|
+
}
|
|
27
|
+
catch (error) {
|
|
28
|
+
return dashboardOperationalError(error, 'The offer could not be deleted.', 'CommerceUpsellDestroyAction')
|
|
29
|
+
}
|
|
30
|
+
},
|
|
31
|
+
})
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import type { RequestInstance } from '@stacksjs/types'
|
|
2
|
+
import { Action } from '@stacksjs/actions/runtime'
|
|
3
|
+
import { response } from '@stacksjs/router'
|
|
4
|
+
import { dashboardOperationalError } from '../dashboard-response'
|
|
5
|
+
import { readUpsellDetail } from './commerce-upsell-list'
|
|
6
|
+
|
|
7
|
+
/** `GET /api/dashboard/commerce/upsells/{id}` - one offer, its funnel and its latest responses. */
|
|
8
|
+
export default new Action({
|
|
9
|
+
name: 'CommerceUpsellDetailAction',
|
|
10
|
+
description: 'Returns one post-purchase offer with its recent responses.',
|
|
11
|
+
method: 'GET',
|
|
12
|
+
apiResponse: true,
|
|
13
|
+
|
|
14
|
+
async handle(request: RequestInstance) {
|
|
15
|
+
const id = Number(request.getParam('id'))
|
|
16
|
+
if (!Number.isSafeInteger(id) || id <= 0)
|
|
17
|
+
return response.json({ message: 'The offer id must be a positive whole number.' }, 422)
|
|
18
|
+
try {
|
|
19
|
+
const detail = await readUpsellDetail(id)
|
|
20
|
+
if (!detail)
|
|
21
|
+
return response.json({ message: `Offer ${id} does not exist.` }, 404)
|
|
22
|
+
return detail
|
|
23
|
+
}
|
|
24
|
+
catch (error) {
|
|
25
|
+
return dashboardOperationalError(error, 'The offer could not be read.', 'CommerceUpsellDetailAction')
|
|
26
|
+
}
|
|
27
|
+
},
|
|
28
|
+
})
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import type { RequestInstance } from '@stacksjs/types'
|
|
2
|
+
import { Action } from '@stacksjs/actions/runtime'
|
|
3
|
+
import { response } from '@stacksjs/router'
|
|
4
|
+
import { dashboardOperationalError } from '../dashboard-response'
|
|
5
|
+
import { asFieldErrors } from './commerce-discount-write'
|
|
6
|
+
import { saveUpsellOffer } from './commerce-upsell-list'
|
|
7
|
+
|
|
8
|
+
/** `POST /api/dashboard/commerce/upsells` - create a post-purchase offer. */
|
|
9
|
+
export default new Action({
|
|
10
|
+
name: 'CommerceUpsellStoreAction',
|
|
11
|
+
description: 'Creates a post-purchase offer from the dashboard.',
|
|
12
|
+
method: 'POST',
|
|
13
|
+
apiResponse: true,
|
|
14
|
+
|
|
15
|
+
async handle(request: RequestInstance) {
|
|
16
|
+
try {
|
|
17
|
+
const result = await saveUpsellOffer(null, request.all() as Record<string, unknown>)
|
|
18
|
+
if (!result.ok)
|
|
19
|
+
return response.json({ message: result.message, errors: asFieldErrors(result.errors) }, result.status)
|
|
20
|
+
return response.json(result.record, 201)
|
|
21
|
+
}
|
|
22
|
+
catch (error) {
|
|
23
|
+
return dashboardOperationalError(error, 'The offer could not be saved.', 'CommerceUpsellStoreAction')
|
|
24
|
+
}
|
|
25
|
+
},
|
|
26
|
+
})
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import type { RequestInstance } from '@stacksjs/types'
|
|
2
|
+
import { Action } from '@stacksjs/actions/runtime'
|
|
3
|
+
import { response } from '@stacksjs/router'
|
|
4
|
+
import { dashboardOperationalError } from '../dashboard-response'
|
|
5
|
+
import { asFieldErrors } from './commerce-discount-write'
|
|
6
|
+
import { saveUpsellOffer } from './commerce-upsell-list'
|
|
7
|
+
|
|
8
|
+
/** `PATCH /api/dashboard/commerce/upsells/{id}` - change a post-purchase offer. */
|
|
9
|
+
export default new Action({
|
|
10
|
+
name: 'CommerceUpsellUpdateAction',
|
|
11
|
+
description: 'Updates a post-purchase offer from the dashboard.',
|
|
12
|
+
method: 'PATCH',
|
|
13
|
+
apiResponse: true,
|
|
14
|
+
|
|
15
|
+
async handle(request: RequestInstance) {
|
|
16
|
+
const id = Number(request.getParam('id'))
|
|
17
|
+
if (!Number.isSafeInteger(id) || id <= 0)
|
|
18
|
+
return response.json({ message: 'The offer id must be a positive whole number.' }, 422)
|
|
19
|
+
try {
|
|
20
|
+
const result = await saveUpsellOffer(id, request.all() as Record<string, unknown>)
|
|
21
|
+
if (!result.ok)
|
|
22
|
+
return response.json({ message: result.message, errors: asFieldErrors(result.errors) }, result.status)
|
|
23
|
+
return response.json(result.record)
|
|
24
|
+
}
|
|
25
|
+
catch (error) {
|
|
26
|
+
return dashboardOperationalError(error, 'The offer could not be saved.', 'CommerceUpsellUpdateAction')
|
|
27
|
+
}
|
|
28
|
+
},
|
|
29
|
+
})
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import type { RequestInstance } from '@stacksjs/types'
|
|
2
|
+
import { Action } from '@stacksjs/actions/runtime'
|
|
3
|
+
import { config } from '@stacksjs/config'
|
|
4
|
+
import { response } from '@stacksjs/router'
|
|
5
|
+
import { dashboardOperationalError } from '../dashboard-response'
|
|
6
|
+
import { normalizeCommerceCurrency } from './commerce-product-records'
|
|
7
|
+
import { parseUpsellListQuery, readUpsellPage } from './commerce-upsell-list'
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* `GET /api/dashboard/commerce/upsells` - one page of post-purchase offers,
|
|
11
|
+
* each with its funnel (shown, taken, turned down, revenue), and the totals
|
|
12
|
+
* across every offer (commerce-upsell-list.ts).
|
|
13
|
+
*/
|
|
14
|
+
export default new Action({
|
|
15
|
+
name: 'CommerceUpsellsAction',
|
|
16
|
+
description: 'Returns one page of post-purchase offers with their conversion for dashboard management.',
|
|
17
|
+
method: 'GET',
|
|
18
|
+
apiResponse: true,
|
|
19
|
+
|
|
20
|
+
async handle(request: RequestInstance) {
|
|
21
|
+
const query = parseUpsellListQuery(key => request.get<unknown>(key, ''))
|
|
22
|
+
if ('error' in query)
|
|
23
|
+
return response.json({ message: query.error }, 422)
|
|
24
|
+
|
|
25
|
+
try {
|
|
26
|
+
const offers = await readUpsellPage(query)
|
|
27
|
+
return {
|
|
28
|
+
records: offers.records,
|
|
29
|
+
total: offers.total,
|
|
30
|
+
page: offers.page,
|
|
31
|
+
perPage: query.perPage,
|
|
32
|
+
summary: offers.summary,
|
|
33
|
+
currency: normalizeCommerceCurrency(config.commerce?.currency),
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
catch (error) {
|
|
37
|
+
return dashboardOperationalError(error, 'Post-purchase offers could not be read.', 'CommerceUpsellsAction')
|
|
38
|
+
}
|
|
39
|
+
},
|
|
40
|
+
})
|
|
@@ -0,0 +1,204 @@
|
|
|
1
|
+
import type { QueryBuilderDialect } from '@stacksjs/database/runtime'
|
|
2
|
+
import { db, getDatabaseDialect } from '@stacksjs/database/runtime'
|
|
3
|
+
import { formatDate } from '@stacksjs/orm'
|
|
4
|
+
import type { QueryReader } from '../Content/content-list'
|
|
5
|
+
import { containsPattern, countOf, LIST_PAGE_SIZES, pageWithin, queryText } from '../Content/content-list'
|
|
6
|
+
import { commerceIdentifier, commerceRequiredString, commerceValue } from './commerce-record'
|
|
7
|
+
import type { CommerceSqlRunner } from './commerce-sql'
|
|
8
|
+
import { asText, binder, idPlaceholders, isTrue, sqlRows } from './commerce-sql'
|
|
9
|
+
import type { DiscountMethod, DiscountRecord, DiscountState, DiscountSummary, DiscountType } from './discount-records'
|
|
10
|
+
import { DISCOUNT_STATES, DISCOUNT_TYPES, discountProductIds, emptyDiscountSummary, normalizeDiscountRecord } from './discount-records'
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* One page of discounts, searched, filtered, sorted and counted by the
|
|
14
|
+
* database, with the summary of every discount: the same shape as the coupon
|
|
15
|
+
* list (commerce-coupon-list.ts), over the Discount model.
|
|
16
|
+
*
|
|
17
|
+
* A discount's state (active, scheduled, expired, used up, switched off) is
|
|
18
|
+
* worked out in SQL against the current time, so the filter and the counts
|
|
19
|
+
* agree with what the checkout would do right now.
|
|
20
|
+
*/
|
|
21
|
+
export const DISCOUNT_SORTS = ['newest', 'title', 'usage', 'starts', 'ends', 'type'] as const
|
|
22
|
+
export type DiscountSort = typeof DISCOUNT_SORTS[number]
|
|
23
|
+
|
|
24
|
+
export interface DiscountListQuery {
|
|
25
|
+
search: string
|
|
26
|
+
/** '' for any. */
|
|
27
|
+
method: '' | DiscountMethod
|
|
28
|
+
/** '' for any. */
|
|
29
|
+
type: '' | DiscountType
|
|
30
|
+
/** '' for any. */
|
|
31
|
+
state: '' | DiscountState
|
|
32
|
+
sort: DiscountSort
|
|
33
|
+
direction: 'asc' | 'desc'
|
|
34
|
+
page: number
|
|
35
|
+
perPage: number
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
const DESCENDING: readonly DiscountSort[] = ['newest', 'usage']
|
|
39
|
+
|
|
40
|
+
export function parseDiscountListQuery(read: QueryReader): DiscountListQuery | { error: string } {
|
|
41
|
+
const pageText = queryText(read, 'page')
|
|
42
|
+
const page = pageText === '' ? 1 : Number(pageText)
|
|
43
|
+
if (!Number.isInteger(page) || page < 1)
|
|
44
|
+
return { error: 'page must be a whole number of 1 or more.' }
|
|
45
|
+
|
|
46
|
+
const sizeText = queryText(read, 'per_page')
|
|
47
|
+
const perPage = sizeText === '' ? 25 : Number(sizeText)
|
|
48
|
+
if (!(LIST_PAGE_SIZES as readonly number[]).includes(perPage))
|
|
49
|
+
return { error: `per_page must be one of ${LIST_PAGE_SIZES.join(', ')}.` }
|
|
50
|
+
|
|
51
|
+
const sort = queryText(read, 'sort') || 'newest'
|
|
52
|
+
if (!(DISCOUNT_SORTS as readonly string[]).includes(sort))
|
|
53
|
+
return { error: `sort must be one of ${DISCOUNT_SORTS.join(', ')}.` }
|
|
54
|
+
|
|
55
|
+
const directionText = queryText(read, 'direction').toLowerCase()
|
|
56
|
+
const direction = directionText === '' ? (DESCENDING.includes(sort as DiscountSort) ? 'desc' : 'asc') : directionText
|
|
57
|
+
if (direction !== 'asc' && direction !== 'desc')
|
|
58
|
+
return { error: 'direction must be asc or desc.' }
|
|
59
|
+
|
|
60
|
+
const search = queryText(read, 'q')
|
|
61
|
+
if (search.length > 200)
|
|
62
|
+
return { error: 'q must be 200 characters or fewer.' }
|
|
63
|
+
|
|
64
|
+
const method = queryText(read, 'method')
|
|
65
|
+
if (method && method !== 'automatic' && method !== 'code')
|
|
66
|
+
return { error: 'method must be automatic or code.' }
|
|
67
|
+
|
|
68
|
+
const type = queryText(read, 'type')
|
|
69
|
+
if (type && !(DISCOUNT_TYPES as readonly string[]).includes(type))
|
|
70
|
+
return { error: `type must be one of ${DISCOUNT_TYPES.join(', ')}.` }
|
|
71
|
+
|
|
72
|
+
const state = queryText(read, 'state')
|
|
73
|
+
if (state && !(DISCOUNT_STATES as readonly string[]).includes(state))
|
|
74
|
+
return { error: `state must be one of ${DISCOUNT_STATES.join(', ')}.` }
|
|
75
|
+
|
|
76
|
+
return {
|
|
77
|
+
search,
|
|
78
|
+
method: method as DiscountListQuery['method'],
|
|
79
|
+
type: type as DiscountListQuery['type'],
|
|
80
|
+
state: state as DiscountListQuery['state'],
|
|
81
|
+
sort: sort as DiscountSort,
|
|
82
|
+
direction,
|
|
83
|
+
page,
|
|
84
|
+
perPage,
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/**
|
|
89
|
+
* The SQL condition for each state, in the order the engine checks them. Each
|
|
90
|
+
* call binds `now` afresh: positional placeholders (`?`) cannot be reused, so
|
|
91
|
+
* a fragment is rendered where it is used, in the order it appears.
|
|
92
|
+
*/
|
|
93
|
+
function stateCondition(state: DiscountState, dialect: QueryBuilderDialect, bind: (value: unknown) => string, nowValue: string): string {
|
|
94
|
+
const enabled = `(is_active IS NULL OR ${isTrue('is_active', dialect)})`
|
|
95
|
+
const started = () => `(starts_at IS NULL OR starts_at <= ${bind(nowValue)})`
|
|
96
|
+
const notEnded = () => `(ends_at IS NULL OR ends_at >= ${bind(nowValue)})`
|
|
97
|
+
const left = '(usage_limit IS NULL OR COALESCE(usage_count, 0) < usage_limit)'
|
|
98
|
+
switch (state) {
|
|
99
|
+
case 'disabled': return `NOT ${enabled}`
|
|
100
|
+
case 'scheduled': return `${enabled} AND NOT ${started()}`
|
|
101
|
+
case 'expired': return `${enabled} AND ${started()} AND NOT ${notEnded()}`
|
|
102
|
+
case 'exhausted': return `${enabled} AND ${started()} AND ${notEnded()} AND NOT ${left}`
|
|
103
|
+
case 'active': return `${enabled} AND ${started()} AND ${notEnded()} AND ${left}`
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
export function discountFilter(query: Pick<DiscountListQuery, 'search' | 'method' | 'type' | 'state'>, dialect: QueryBuilderDialect, nowValue: string): { where: string, values: unknown[] } {
|
|
108
|
+
const { bind, values } = binder(dialect)
|
|
109
|
+
const clauses: string[] = []
|
|
110
|
+
if (query.method === 'automatic')
|
|
111
|
+
clauses.push(`(code IS NULL OR code = '')`)
|
|
112
|
+
if (query.method === 'code')
|
|
113
|
+
clauses.push(`(code IS NOT NULL AND code <> '')`)
|
|
114
|
+
if (query.type)
|
|
115
|
+
clauses.push(`${asText('type', dialect)} = ${bind(query.type)}`)
|
|
116
|
+
if (query.state)
|
|
117
|
+
clauses.push(`(${stateCondition(query.state, dialect, bind, nowValue)})`)
|
|
118
|
+
if (query.search) {
|
|
119
|
+
const pattern = containsPattern(query.search)
|
|
120
|
+
clauses.push(`(${['title', `COALESCE(code, '')`].map(column => `LOWER(${column}) LIKE ${bind(pattern)} ESCAPE '!'`).join(' OR ')})`)
|
|
121
|
+
}
|
|
122
|
+
return { where: clauses.length > 0 ? ` WHERE ${clauses.join(' AND ')}` : '', values }
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
function orderBy(query: Pick<DiscountListQuery, 'sort' | 'direction'>, dialect: QueryBuilderDialect): string {
|
|
126
|
+
const direction = query.direction === 'asc' ? 'ASC' : 'DESC'
|
|
127
|
+
switch (query.sort) {
|
|
128
|
+
case 'title': return ` ORDER BY LOWER(title) ${direction}, id ${direction}`
|
|
129
|
+
case 'usage': return ` ORDER BY COALESCE(usage_count, 0) ${direction}, LOWER(title) ASC, id ${direction}`
|
|
130
|
+
case 'type': return ` ORDER BY ${asText('type', dialect)} ${direction}, LOWER(title) ASC, id ${direction}`
|
|
131
|
+
// Undated discounts last either way: each dialect puts NULL at a
|
|
132
|
+
// different end, and a discount with no end never expires.
|
|
133
|
+
case 'starts': return ` ORDER BY CASE WHEN starts_at IS NULL THEN 1 ELSE 0 END ASC, starts_at ${direction}, id ${direction}`
|
|
134
|
+
case 'ends': return ` ORDER BY CASE WHEN ends_at IS NULL THEN 1 ELSE 0 END ASC, ends_at ${direction}, id ${direction}`
|
|
135
|
+
default: return ` ORDER BY id ${direction}`
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
async function summarize(run: CommerceSqlRunner, dialect: QueryBuilderDialect, nowValue: string): Promise<DiscountSummary> {
|
|
140
|
+
const { bind, values } = binder(dialect)
|
|
141
|
+
const count = (condition: string) => `SUM(CASE WHEN ${condition} THEN 1 ELSE 0 END)`
|
|
142
|
+
const type = asText('type', dialect)
|
|
143
|
+
const typeCounts = DISCOUNT_TYPES.map(t => `${count(`${type} = '${t}'`)} AS type_${t}`).join(', ')
|
|
144
|
+
const [totals, used] = await Promise.all([
|
|
145
|
+
run.unsafe(`SELECT COUNT(*) AS total_count, ${count(`(code IS NULL OR code = '')`)} AS automatic_count, ${DISCOUNT_STATES.map(state => `${count(stateCondition(state, dialect, bind, nowValue))} AS state_${state}`).join(', ')}, ${typeCounts}, SUM(COALESCE(usage_count, 0)) AS usage_total FROM discounts`, values).execute(),
|
|
146
|
+
run.unsafe('SELECT id, title, usage_count FROM discounts WHERE COALESCE(usage_count, 0) > 0 ORDER BY usage_count DESC, LOWER(title) ASC, id ASC LIMIT 5').execute(),
|
|
147
|
+
])
|
|
148
|
+
const row = sqlRows(totals)[0] ?? {}
|
|
149
|
+
const summary = emptyDiscountSummary()
|
|
150
|
+
summary.total = countOf(row.total_count)
|
|
151
|
+
summary.automatic = countOf(row.automatic_count)
|
|
152
|
+
summary.code = summary.total - summary.automatic
|
|
153
|
+
for (const state of DISCOUNT_STATES)
|
|
154
|
+
summary[state] = countOf(row[`state_${state}`])
|
|
155
|
+
for (const t of DISCOUNT_TYPES)
|
|
156
|
+
summary.byType[t] = countOf(row[`type_${t}`])
|
|
157
|
+
summary.redemptions = countOf(row.usage_total)
|
|
158
|
+
summary.mostUsed = sqlRows(used).map((entry) => {
|
|
159
|
+
const id = commerceIdentifier(commerceValue(entry, 'id'), 'Discount')
|
|
160
|
+
return { id, title: commerceRequiredString(commerceValue(entry, 'title'), `Discount ${id}`, 'title'), usageCount: countOf(entry.usage_count) }
|
|
161
|
+
})
|
|
162
|
+
return summary
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
export interface DiscountPage {
|
|
166
|
+
records: DiscountRecord[]
|
|
167
|
+
total: number
|
|
168
|
+
page: number
|
|
169
|
+
summary: DiscountSummary
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
export async function readDiscountPage(
|
|
173
|
+
query: DiscountListQuery,
|
|
174
|
+
currency = 'USD',
|
|
175
|
+
run: CommerceSqlRunner = db,
|
|
176
|
+
dialect: QueryBuilderDialect = getDatabaseDialect(),
|
|
177
|
+
now: Date = new Date(),
|
|
178
|
+
): Promise<DiscountPage> {
|
|
179
|
+
const nowValue = formatDate(now)
|
|
180
|
+
const { where, values } = discountFilter(query, dialect, nowValue)
|
|
181
|
+
const [counted, summary] = await Promise.all([
|
|
182
|
+
run.unsafe(`SELECT COUNT(*) AS total_count FROM discounts${where}`, values).execute(),
|
|
183
|
+
summarize(run, dialect, nowValue),
|
|
184
|
+
])
|
|
185
|
+
const total = countOf(sqlRows(counted)[0]?.total_count)
|
|
186
|
+
const page = pageWithin(query.page, total, query.perPage)
|
|
187
|
+
const rows = await run.unsafe(
|
|
188
|
+
`SELECT * FROM discounts${where}${orderBy(query, dialect)} LIMIT ${query.perPage} OFFSET ${(page - 1) * query.perPage}`,
|
|
189
|
+
values,
|
|
190
|
+
).execute()
|
|
191
|
+
return { records: await recordsFor(sqlRows(rows), nowValue, currency, run, dialect), total, page, summary }
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
/** Rows as records, with the names of exactly the products their targets name. */
|
|
195
|
+
export async function recordsFor(rows: Array<Record<string, unknown>>, nowValue: string, currency: string, run: CommerceSqlRunner, dialect: QueryBuilderDialect): Promise<DiscountRecord[]> {
|
|
196
|
+
const ids = [...new Set(rows.flatMap(discountProductIds))]
|
|
197
|
+
const names = new Map<number, string>()
|
|
198
|
+
if (ids.length > 0) {
|
|
199
|
+
const products = await run.unsafe(`SELECT id, name FROM products WHERE id IN (${idPlaceholders(ids, dialect)})`, ids).execute()
|
|
200
|
+
for (const product of sqlRows(products))
|
|
201
|
+
names.set(Number(product.id), String(product.name ?? `Product #${product.id}`))
|
|
202
|
+
}
|
|
203
|
+
return rows.map(row => normalizeDiscountRecord(row, nowValue, currency, names))
|
|
204
|
+
}
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
import { randomUUIDv7 } from 'bun'
|
|
2
|
+
import { db, mutationCount } from '@stacksjs/database/runtime'
|
|
3
|
+
import { formatDate, isUniqueViolation } from '@stacksjs/orm'
|
|
4
|
+
import type { DiscountRecord, DiscountWritePayload } from './discount-records'
|
|
5
|
+
import { discountWriteData, normalizeDiscountRecord } from './discount-records'
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* Creating, changing and removing discounts from the dashboard. Every write
|
|
9
|
+
* goes through `discountWriteData`, which prices the rule once with the
|
|
10
|
+
* engine, so what is saved is what a checkout can use.
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
export type DiscountSaveResult =
|
|
14
|
+
| { ok: true, record: DiscountRecord }
|
|
15
|
+
| { ok: false, status: 404 | 422, message: string, errors?: Record<string, string> }
|
|
16
|
+
|
|
17
|
+
export async function saveDiscount(id: number | null, payload: DiscountWritePayload, currency = 'USD', run: any = db): Promise<DiscountSaveResult> {
|
|
18
|
+
const checked = discountWriteData(payload)
|
|
19
|
+
if (!checked.ok)
|
|
20
|
+
return { ok: false, status: 422, message: 'The discount could not be saved.', errors: checked.errors }
|
|
21
|
+
|
|
22
|
+
const now = formatDate(new Date())
|
|
23
|
+
try {
|
|
24
|
+
if (id === null) {
|
|
25
|
+
const uuid = randomUUIDv7()
|
|
26
|
+
await run.insertInto('discounts').values({ ...checked.data, uuid, usage_count: 0, created_at: now, updated_at: now }).execute()
|
|
27
|
+
const row = await run.selectFrom('discounts').where('uuid', '=', uuid).selectAll().executeTakeFirst()
|
|
28
|
+
return { ok: true, record: normalizeDiscountRecord(row, now, currency) }
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
const result = await run.updateTable('discounts').set({ ...checked.data, updated_at: now }).where('id', '=', id).executeTakeFirst()
|
|
32
|
+
if (mutationCount(result) === 0)
|
|
33
|
+
return { ok: false, status: 404, message: `Discount ${id} does not exist.` }
|
|
34
|
+
const row = await run.selectFrom('discounts').where('id', '=', id).selectAll().executeTakeFirst()
|
|
35
|
+
return { ok: true, record: normalizeDiscountRecord(row, now, currency) }
|
|
36
|
+
}
|
|
37
|
+
catch (error) {
|
|
38
|
+
if (isUniqueViolation(error))
|
|
39
|
+
return { ok: false, status: 422, message: 'Another discount already uses that code.', errors: { code: 'is already used by another discount' } }
|
|
40
|
+
throw error
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** Remove a discount. Orders keep the amount it took off; nothing points at the row. */
|
|
45
|
+
export async function deleteDiscount(id: number, run: any = db): Promise<boolean> {
|
|
46
|
+
const result = await run.deleteFrom('discounts').where('id', '=', id).executeTakeFirst()
|
|
47
|
+
return mutationCount(result) > 0
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** Field errors in the `{ field: [message] }` shape the dashboard's API client reads. */
|
|
51
|
+
export function asFieldErrors(errors: Record<string, string> | undefined): Record<string, string[]> | undefined {
|
|
52
|
+
return errors ? Object.fromEntries(Object.entries(errors).map(([field, message]) => [field, [message]])) : undefined
|
|
53
|
+
}
|
|
@@ -0,0 +1,228 @@
|
|
|
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 type { DiscountListQuery } from './commerce-discount-list'
|
|
6
|
+
import type { UpsellListQuery } from './commerce-upsell-list'
|
|
7
|
+
import { parseDiscountListQuery, readDiscountPage } from './commerce-discount-list'
|
|
8
|
+
import { parseUpsellListQuery, readUpsellDetail, readUpsellPage } from './commerce-upsell-list'
|
|
9
|
+
import { discountWriteData } from './discount-records'
|
|
10
|
+
import { upsellWriteData } from './upsell-offer-records'
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* The Discounts and Upsells dashboard pages' server side, against each
|
|
14
|
+
* dialect's real engine: what a discount's state is right now, the funnel each
|
|
15
|
+
* offer's responses add up to, and the writes the dialogs send.
|
|
16
|
+
*/
|
|
17
|
+
type Dialect = 'sqlite' | 'postgres' | 'mysql'
|
|
18
|
+
type Run = (sql: string, values?: unknown[]) => Promise<unknown>
|
|
19
|
+
|
|
20
|
+
const NOW = new Date('2026-11-16T12:00:00Z')
|
|
21
|
+
|
|
22
|
+
function discountQuery(overrides: Partial<DiscountListQuery> = {}): DiscountListQuery {
|
|
23
|
+
return { search: '', method: '', type: '', state: '', sort: 'newest', direction: 'desc', page: 1, perPage: 25, ...overrides }
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
function upsellQuery(overrides: Partial<UpsellListQuery> = {}): UpsellListQuery {
|
|
27
|
+
return { search: '', state: '', sort: 'priority', direction: 'desc', page: 1, perPage: 25, ...overrides }
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
async function setUp(run: Run, dialect: Dialect) {
|
|
31
|
+
const pk = dialect === 'postgres' ? 'BIGINT PRIMARY KEY' : 'INTEGER PRIMARY KEY'
|
|
32
|
+
const text = dialect === 'mysql' ? 'VARCHAR(255)' : 'TEXT'
|
|
33
|
+
const bool = dialect === 'postgres' ? 'BOOLEAN' : dialect === 'mysql' ? 'TINYINT(1)' : 'INTEGER'
|
|
34
|
+
const p = (index: number) => dialect === 'postgres' ? `$${index}` : '?'
|
|
35
|
+
const insert = async (table: string, row: Record<string, unknown>) => {
|
|
36
|
+
const columns = Object.keys(row)
|
|
37
|
+
await run(`INSERT INTO ${table} (${columns.join(', ')}) VALUES (${columns.map((_, i) => p(i + 1)).join(', ')})`, Object.values(row))
|
|
38
|
+
}
|
|
39
|
+
const flag = (value: boolean) => dialect === 'postgres' ? value : (value ? 1 : 0)
|
|
40
|
+
|
|
41
|
+
await run(`CREATE TABLE products (id ${pk}, name ${text})`)
|
|
42
|
+
await run(`CREATE TABLE discounts (id ${pk}, title ${text}, code ${text} NULL, type ${text}, value INTEGER, scope ${text} NULL, per_item ${bool} NULL, target ${text} NULL, buy_quantity INTEGER NULL, buy_target ${text} NULL, get_quantity INTEGER NULL, get_target ${text} NULL, get_percent INTEGER NULL, max_applications INTEGER NULL, tiers ${text} NULL, max_shipping INTEGER NULL, minimum_subtotal INTEGER NULL, minimum_quantity INTEGER NULL, max_amount INTEGER NULL, combines_with_product ${bool} NULL, combines_with_order ${bool} NULL, combines_with_shipping ${bool} NULL, usage_limit INTEGER NULL, usage_count INTEGER NULL, is_active ${bool} NULL, starts_at ${text} NULL, ends_at ${text} NULL, created_at ${text})`)
|
|
43
|
+
await run(`CREATE TABLE post_purchase_offers (id ${pk}, name ${text}, headline ${text} NULL, message ${text} NULL, product_ids ${text}, discount_percent INTEGER, min_quantity INTEGER, default_quantity INTEGER, max_quantity INTEGER NULL, trigger_product_ids ${text} NULL, min_order_total INTEGER NULL, window_minutes INTEGER, priority INTEGER, is_active ${bool} NULL, starts_at ${text} NULL, ends_at ${text} NULL, created_at ${text})`)
|
|
44
|
+
await run(`CREATE TABLE post_purchase_offer_responses (id ${pk}, post_purchase_offer_id INTEGER, order_id INTEGER, status ${text}, product_id INTEGER, variant_id INTEGER NULL, quantity INTEGER NULL, unit_price INTEGER NULL, compare_at_price INTEGER NULL, amount INTEGER NULL, currency ${text} NULL, failure_reason ${text} NULL, responded_at ${text} NULL, created_at ${text})`)
|
|
45
|
+
|
|
46
|
+
for (const [id, name] of [[1, 'Toe Socks'], [2, 'Crew Socks'], [3, 'Ankle Socks']] as const)
|
|
47
|
+
await insert('products', { id, name })
|
|
48
|
+
|
|
49
|
+
const created = '2026-11-01 09:00:00'
|
|
50
|
+
// 1: automatic buy 4 get 4 free, running. 2: code, used up. 3: scheduled.
|
|
51
|
+
// 4: expired. 5: switched off. 6: volume tiers, running, most used.
|
|
52
|
+
await insert('discounts', { id: 1, title: 'BUY 4, GET 4 FREE | 50% OFF', code: null, type: 'buy_x_get_y', value: 0, buy_quantity: 4, get_quantity: 4, get_percent: 100, target: JSON.stringify({ productIds: [1] }), usage_count: 12, is_active: flag(true), created_at: created })
|
|
53
|
+
await insert('discounts', { id: 2, title: 'Welcome', code: 'WELCOME10', type: 'percentage', value: 10, usage_limit: 3, usage_count: 3, is_active: flag(true), created_at: created })
|
|
54
|
+
await insert('discounts', { id: 3, title: 'Black Friday', code: 'BF30', type: 'percentage', value: 30, usage_count: 0, is_active: flag(true), starts_at: '2026-11-27 00:00:00', created_at: created })
|
|
55
|
+
await insert('discounts', { id: 4, title: 'Summer', code: 'SUMMER', type: 'fixed_amount', value: 500, usage_count: 7, is_active: flag(true), ends_at: '2026-08-31 23:59:59', created_at: created })
|
|
56
|
+
await insert('discounts', { id: 5, title: 'Free shipping', code: null, type: 'free_shipping', value: 0, usage_count: 0, is_active: flag(false), created_at: created })
|
|
57
|
+
await insert('discounts', { id: 6, title: 'Stock up', code: null, type: 'volume', value: 0, tiers: JSON.stringify([{ minQuantity: 10, percent: 30 }, { minQuantity: 5, percent: 20 }]), usage_count: 40, is_active: flag(true), created_at: created })
|
|
58
|
+
|
|
59
|
+
await insert('post_purchase_offers', { id: 1, name: 'Sock bundle', headline: 'One-time offer', message: 'Grab 5+ pairs and get 60% off!', product_ids: JSON.stringify([2, 3, 99]), discount_percent: 60, min_quantity: 5, default_quantity: 5, trigger_product_ids: JSON.stringify([1]), window_minutes: 30, priority: 10, is_active: flag(true), created_at: created })
|
|
60
|
+
await insert('post_purchase_offers', { id: 2, name: 'Holiday', product_ids: JSON.stringify([3]), discount_percent: 20, min_quantity: 1, default_quantity: 1, window_minutes: 15, priority: 1, is_active: flag(true), starts_at: '2026-12-01 00:00:00', created_at: created })
|
|
61
|
+
await insert('post_purchase_offers', { id: 3, name: 'Retired', product_ids: JSON.stringify([2]), discount_percent: 10, min_quantity: 1, default_quantity: 1, window_minutes: 30, priority: 0, is_active: flag(false), created_at: created })
|
|
62
|
+
|
|
63
|
+
const responses: Array<[number, number, string, number, number | null, number | null]> = [
|
|
64
|
+
// offer, order, status, product, quantity, amount
|
|
65
|
+
[1, 100, 'accepted', 2, 5, 4800],
|
|
66
|
+
[1, 100, 'declined', 3, null, null],
|
|
67
|
+
[1, 101, 'accepted', 3, 5, 4200],
|
|
68
|
+
[1, 101, 'viewed', 2, null, null],
|
|
69
|
+
[1, 102, 'failed', 2, 5, 4800],
|
|
70
|
+
[3, 103, 'accepted', 2, 1, 2160],
|
|
71
|
+
]
|
|
72
|
+
for (const [index, [offer, order, status, product, quantity, amount]] of responses.entries())
|
|
73
|
+
await insert('post_purchase_offer_responses', { id: index + 1, post_purchase_offer_id: offer, order_id: order, status, product_id: product, quantity, amount, unit_price: amount && quantity ? amount / quantity : null, currency: 'USD', created_at: created })
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
async function exercise(runner: CommerceSqlRunner, dialect: Dialect) {
|
|
77
|
+
const discounts = (overrides: Partial<DiscountListQuery> = {}) => readDiscountPage(discountQuery(overrides), 'USD', runner, dialect, NOW)
|
|
78
|
+
const ids = (page: { records: Array<{ id: string }> }) => page.records.map(record => record.id)
|
|
79
|
+
|
|
80
|
+
const all = await discounts()
|
|
81
|
+
expect(all.total).toBe(6)
|
|
82
|
+
expect(ids(all)).toEqual(['6', '5', '4', '3', '2', '1'])
|
|
83
|
+
expect(all.summary).toMatchObject({ total: 6, automatic: 3, code: 3, active: 2, scheduled: 1, expired: 1, exhausted: 1, disabled: 1, redemptions: 62 })
|
|
84
|
+
expect(all.summary.byType).toEqual({ percentage: 2, fixed_amount: 1, buy_x_get_y: 1, volume: 1, free_shipping: 1 })
|
|
85
|
+
expect(all.summary.mostUsed.map(entry => entry.title)).toEqual(['Stock up', 'BUY 4, GET 4 FREE | 50% OFF', 'Summer', 'Welcome'])
|
|
86
|
+
|
|
87
|
+
const bxgy = all.records.find(record => record.id === '1')!
|
|
88
|
+
expect(bxgy).toMatchObject({ method: 'automatic', type: 'buy_x_get_y', state: 'active', label: 'BUY 4, GET 4 FREE', appliesTo: 'product', buyQuantity: 4, getQuantity: 4, getPercent: 100 })
|
|
89
|
+
expect(bxgy.target.productIds).toEqual(['1'])
|
|
90
|
+
expect(bxgy.productLabels).toEqual({ 1: 'Toe Socks' })
|
|
91
|
+
expect(all.records.find(record => record.id === '6')!.tiers).toEqual([{ minQuantity: 5, percent: 20 }, { minQuantity: 10, percent: 30 }])
|
|
92
|
+
expect(all.records.find(record => record.id === '4')).toMatchObject({ state: 'expired', label: '$5.00 OFF', endsAt: '2026-08-31', appliesTo: 'order' })
|
|
93
|
+
|
|
94
|
+
// Each state filter agrees with the state each record reports.
|
|
95
|
+
for (const state of ['active', 'scheduled', 'expired', 'exhausted', 'disabled'] as const) {
|
|
96
|
+
const page = await discounts({ state })
|
|
97
|
+
expect(page.records.every(record => record.state === state)).toBe(true)
|
|
98
|
+
expect(page.total).toBe(all.summary[state])
|
|
99
|
+
}
|
|
100
|
+
expect(ids(await discounts({ method: 'code', sort: 'title', direction: 'asc' }))).toEqual(['3', '4', '2'])
|
|
101
|
+
expect(ids(await discounts({ type: 'free_shipping' }))).toEqual(['5'])
|
|
102
|
+
expect(ids(await discounts({ search: 'welcome' }))).toEqual(['2'])
|
|
103
|
+
expect(ids(await discounts({ sort: 'usage' }))).toEqual(['6', '1', '4', '2', '3', '5'])
|
|
104
|
+
// Undated last either way.
|
|
105
|
+
expect(ids(await discounts({ sort: 'ends', direction: 'asc' }))[0]).toBe('4')
|
|
106
|
+
|
|
107
|
+
const offers = (overrides: Partial<UpsellListQuery> = {}) => readUpsellPage(upsellQuery(overrides), runner, dialect, NOW)
|
|
108
|
+
const page = await offers()
|
|
109
|
+
expect(ids(page)).toEqual(['1', '2', '3'])
|
|
110
|
+
const bundle = page.records[0]!
|
|
111
|
+
expect(bundle).toMatchObject({ name: 'Sock bundle', state: 'running', discountPercent: 60, minQuantity: 5 })
|
|
112
|
+
expect(bundle.products.map(p => [p.id, p.label, p.exists])).toEqual([['2', 'Crew Socks', true], ['3', 'Ankle Socks', true], ['99', 'Deleted product #99', false]])
|
|
113
|
+
expect(bundle.triggerProducts.map(p => p.label)).toEqual(['Toe Socks'])
|
|
114
|
+
expect(bundle.stats).toEqual({ views: 5, accepted: 2, declined: 1, pending: 0, failed: 1, conversionRate: 0.4, revenue: 9000, units: 10 })
|
|
115
|
+
expect(page.records[1]!.state).toBe('scheduled')
|
|
116
|
+
expect(page.records[2]!).toMatchObject({ state: 'disabled', stats: { accepted: 1, revenue: 2160 } })
|
|
117
|
+
|
|
118
|
+
expect(page.summary).toMatchObject({ total: 3, running: 1, views: 6, accepted: 3, declined: 1, revenue: 11160, units: 11 })
|
|
119
|
+
expect(page.summary.conversionRate).toBe(0.5)
|
|
120
|
+
expect(page.summary.top.map(entry => entry.name)).toEqual(['Sock bundle', 'Retired'])
|
|
121
|
+
|
|
122
|
+
expect(ids(await offers({ state: 'running' }))).toEqual(['1'])
|
|
123
|
+
expect(ids(await offers({ state: 'disabled' }))).toEqual(['3'])
|
|
124
|
+
expect(ids(await offers({ sort: 'revenue' }))).toEqual(['1', '3', '2'])
|
|
125
|
+
expect(ids(await offers({ search: '60%' }))).toEqual(['1'])
|
|
126
|
+
|
|
127
|
+
const detail = await readUpsellDetail(1, 25, runner, dialect, NOW)
|
|
128
|
+
expect(detail!.responses.map(r => [r.orderId, r.status, r.productLabel])).toEqual([
|
|
129
|
+
['102', 'failed', 'Crew Socks'],
|
|
130
|
+
['101', 'viewed', 'Crew Socks'],
|
|
131
|
+
['101', 'accepted', 'Ankle Socks'],
|
|
132
|
+
['100', 'declined', 'Ankle Socks'],
|
|
133
|
+
['100', 'accepted', 'Crew Socks'],
|
|
134
|
+
])
|
|
135
|
+
expect(await readUpsellDetail(404, 25, runner, dialect, NOW)).toBeNull()
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
describe('list queries', () => {
|
|
139
|
+
test('defaults and refusals', () => {
|
|
140
|
+
const discounts = (values: Record<string, string>) => parseDiscountListQuery(key => values[key] ?? '')
|
|
141
|
+
expect(discounts({})).toEqual(discountQuery())
|
|
142
|
+
expect(discounts({ sort: 'title' })).toMatchObject({ direction: 'asc' })
|
|
143
|
+
expect(discounts({ state: 'paused' })).toHaveProperty('error')
|
|
144
|
+
expect(discounts({ method: 'magic' })).toHaveProperty('error')
|
|
145
|
+
expect(discounts({ type: 'bogo' })).toHaveProperty('error')
|
|
146
|
+
|
|
147
|
+
const upsells = (values: Record<string, string>) => parseUpsellListQuery(key => values[key] ?? '')
|
|
148
|
+
expect(upsells({})).toEqual(upsellQuery())
|
|
149
|
+
expect(upsells({ sort: 'name' })).toMatchObject({ direction: 'asc' })
|
|
150
|
+
expect(upsells({ state: 'live' })).toHaveProperty('error')
|
|
151
|
+
})
|
|
152
|
+
})
|
|
153
|
+
|
|
154
|
+
describe('discount writes', () => {
|
|
155
|
+
test('a buy X get Y discount becomes the columns the engine reads', () => {
|
|
156
|
+
const result = discountWriteData({ title: 'BUY 4, GET 4 FREE', method: 'automatic', type: 'buy_x_get_y', buyQuantity: 4, getQuantity: '4', getPercent: 100, target: { productIds: ['7'] }, startsAt: '2026-11-20', endsAt: '2026-11-30', combinesWith: { shipping: true } })
|
|
157
|
+
expect(result).toMatchObject({ ok: true, data: { code: null, type: 'buy_x_get_y', buy_quantity: 4, get_quantity: 4, get_percent: 100, target: '{"productIds":[7],"variantIds":[],"categoryIds":[]}', starts_at: '2026-11-20 00:00:00', ends_at: '2026-11-30 23:59:59', combines_with_shipping: true, is_active: true } })
|
|
158
|
+
})
|
|
159
|
+
|
|
160
|
+
test('refuses by field what the engine would refuse at checkout', () => {
|
|
161
|
+
expect(discountWriteData({ title: '', type: 'percentage', value: 10 })).toEqual({ ok: false, errors: { title: 'is required' } })
|
|
162
|
+
expect(discountWriteData({ title: 'x', type: 'percentage', value: 120 })).toEqual({ ok: false, errors: { value: 'must be a whole number from 1 to 100' } })
|
|
163
|
+
expect(discountWriteData({ title: 'x', method: 'code', type: 'percentage', value: 10 })).toEqual({ ok: false, errors: { code: 'is required for a discount code' } })
|
|
164
|
+
expect(discountWriteData({ title: 'x', method: 'code', code: 'two words', type: 'percentage', value: 10 })).toMatchObject({ ok: false, errors: { code: expect.any(String) } })
|
|
165
|
+
expect(discountWriteData({ title: 'x', type: 'volume', tiers: [] })).toEqual({ ok: false, errors: { tiers: 'add at least one tier' } })
|
|
166
|
+
expect(discountWriteData({ title: 'x', type: 'volume', tiers: [{ minQuantity: 5, percent: 10 }, { minQuantity: 5, percent: 20 }] })).toMatchObject({ ok: false, errors: { tiers: expect.any(String) } })
|
|
167
|
+
expect(discountWriteData({ title: 'x', type: 'buy_x_get_y' })).toMatchObject({ ok: false, errors: { buyQuantity: 'is required', getQuantity: 'is required', getPercent: 'is required' } })
|
|
168
|
+
expect(discountWriteData({ title: 'x', type: 'percentage', value: 10, scope: 'product' })).toMatchObject({ ok: false, errors: { target: expect.any(String) } })
|
|
169
|
+
expect(discountWriteData({ title: 'x', type: 'percentage', value: 10, startsAt: '2026-12-01', endsAt: '2026-11-01' })).toMatchObject({ ok: false, errors: { endsAt: expect.any(String) } })
|
|
170
|
+
})
|
|
171
|
+
|
|
172
|
+
test('upper-cases a code and keeps it', () => {
|
|
173
|
+
expect(discountWriteData({ title: 'Welcome', method: 'code', code: 'welcome10', type: 'fixed_amount', value: 500, perItem: true })).toMatchObject({ ok: true, data: { code: 'WELCOME10', value: 500, per_item: true } })
|
|
174
|
+
})
|
|
175
|
+
})
|
|
176
|
+
|
|
177
|
+
describe('upsell writes', () => {
|
|
178
|
+
test('an offer becomes its columns, with the products to check', () => {
|
|
179
|
+
const result = upsellWriteData({ name: 'Sock bundle', message: 'Grab 5+ pairs', productIds: ['2', '3', '2'], triggerProductIds: [1], discountPercent: '60', minQuantity: 5, defaultQuantity: 5, windowMinutes: 30, priority: 10 })
|
|
180
|
+
expect(result).toMatchObject({ ok: true, productIds: [2, 3, 1], data: { product_ids: '[2,3]', trigger_product_ids: '[1]', discount_percent: 60, min_quantity: 5, default_quantity: 5, max_quantity: null, window_minutes: 30, priority: 10, is_active: true } })
|
|
181
|
+
})
|
|
182
|
+
|
|
183
|
+
test('refuses quantities that contradict each other and offers with nothing in them', () => {
|
|
184
|
+
expect(upsellWriteData({ name: 'x', productIds: [] })).toMatchObject({ ok: false, errors: { productIds: expect.any(String) } })
|
|
185
|
+
expect(upsellWriteData({ name: 'x', productIds: [1], minQuantity: 5, defaultQuantity: 2 })).toMatchObject({ ok: false, errors: { defaultQuantity: 'must be at least the minimum quantity' } })
|
|
186
|
+
expect(upsellWriteData({ name: 'x', productIds: [1], minQuantity: 5, maxQuantity: 3 })).toMatchObject({ ok: false, errors: { maxQuantity: 'must be at least the minimum quantity' } })
|
|
187
|
+
expect(upsellWriteData({ name: 'x', productIds: [1], discountPercent: 101 })).toMatchObject({ ok: false, errors: { discountPercent: expect.any(String) } })
|
|
188
|
+
expect(upsellWriteData({ name: 'x', productIds: [1], windowMinutes: 0 })).toMatchObject({ ok: false, errors: { windowMinutes: expect.any(String) } })
|
|
189
|
+
})
|
|
190
|
+
})
|
|
191
|
+
|
|
192
|
+
describe('Discounts and Upsells on SQLite', () => {
|
|
193
|
+
test('states, filters, sorts, summaries, funnels and detail', async () => {
|
|
194
|
+
const database = new Database(':memory:')
|
|
195
|
+
const run: Run = async (sql, values = []) => database.query(sql).run(...(values as never[]))
|
|
196
|
+
await setUp(run, 'sqlite')
|
|
197
|
+
await exercise({ unsafe: (sql, values = []) => ({ execute: async () => database.query(sql).all(...(values as never[])) }) }, 'sqlite')
|
|
198
|
+
})
|
|
199
|
+
})
|
|
200
|
+
|
|
201
|
+
for (const dialect of ['postgres', 'mysql'] as const) {
|
|
202
|
+
const connection = dialect === 'postgres' ? process.env.STACKS_TEST_POSTGRES_URL : process.env.STACKS_TEST_MYSQL_URL
|
|
203
|
+
|
|
204
|
+
test.skipIf(!connection)(`Discounts and Upsells on ${dialect}`, async () => {
|
|
205
|
+
const url = new URL(connection!)
|
|
206
|
+
if (!['127.0.0.1', 'localhost', '[::1]'].includes(url.hostname))
|
|
207
|
+
throw new Error('These tests require a local disposable database server')
|
|
208
|
+
|
|
209
|
+
const name = `stacks_discounts_${crypto.randomUUID().replaceAll('-', '')}`
|
|
210
|
+
const quoted = dialect === 'mysql' ? `\`${name}\`` : `"${name}"`
|
|
211
|
+
const admin = new SQL({ url: url.href, database: decodeURIComponent(url.pathname.slice(1)) || undefined })
|
|
212
|
+
await admin.unsafe(`CREATE DATABASE ${quoted}`)
|
|
213
|
+
const scoped = new URL(url.href)
|
|
214
|
+
scoped.pathname = `/${name}`
|
|
215
|
+
const database = new SQL({ url: scoped.href, database: name })
|
|
216
|
+
|
|
217
|
+
try {
|
|
218
|
+
const run: Run = async (sql, values = []) => await database.unsafe(sql, values)
|
|
219
|
+
await setUp(run, dialect)
|
|
220
|
+
await exercise({ unsafe: (sql, values = []) => ({ execute: async () => await database.unsafe(sql, values) }) }, dialect)
|
|
221
|
+
}
|
|
222
|
+
finally {
|
|
223
|
+
await database.close()
|
|
224
|
+
try { await admin.unsafe(`DROP DATABASE ${quoted}${dialect === 'postgres' ? ' WITH (FORCE)' : ''}`) }
|
|
225
|
+
finally { await admin.close() }
|
|
226
|
+
}
|
|
227
|
+
}, 60_000)
|
|
228
|
+
}
|