@stacksjs/defaults 0.75.618 → 0.75.622

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (94) hide show
  1. package/ai/skills/stacks-actions/SKILL.md +1 -1
  2. package/ai/skills/stacks-auth/SKILL.md +12 -1
  3. package/ai/skills/stacks-auto-imports/SKILL.md +1 -1
  4. package/ai/skills/stacks-buddy/SKILL.md +70 -7
  5. package/ai/skills/stacks-commerce/SKILL.md +78 -4
  6. package/ai/skills/stacks-dashboard/SKILL.md +32 -2
  7. package/ai/skills/stacks-database/SKILL.md +1 -1
  8. package/ai/skills/stacks-development/SKILL.md +3 -0
  9. package/ai/skills/stacks-migrations/SKILL.md +10 -2
  10. package/ai/skills/stacks-mobile/SKILL.md +21 -2
  11. package/ai/skills/stacks-models/SKILL.md +2 -2
  12. package/ai/skills/stacks-native/CATALOG.md +21 -21
  13. package/ai/skills/stacks-orm/SKILL.md +2 -2
  14. package/ai/skills/stacks-utils/SKILL.md +8 -3
  15. package/app/Actions/Dashboard/Commerce/CommerceDiscountDestroyAction.ts +27 -0
  16. package/app/Actions/Dashboard/Commerce/CommerceDiscountStoreAction.ts +28 -0
  17. package/app/Actions/Dashboard/Commerce/CommerceDiscountUpdateAction.ts +30 -0
  18. package/app/Actions/Dashboard/Commerce/CommerceDiscountsAction.ts +42 -0
  19. package/app/Actions/Dashboard/Commerce/CommerceUpsellDestroyAction.ts +31 -0
  20. package/app/Actions/Dashboard/Commerce/CommerceUpsellDetailAction.ts +28 -0
  21. package/app/Actions/Dashboard/Commerce/CommerceUpsellStoreAction.ts +26 -0
  22. package/app/Actions/Dashboard/Commerce/CommerceUpsellUpdateAction.ts +29 -0
  23. package/app/Actions/Dashboard/Commerce/CommerceUpsellsAction.ts +40 -0
  24. package/app/Actions/Dashboard/Commerce/commerce-discount-list.ts +204 -0
  25. package/app/Actions/Dashboard/Commerce/commerce-discount-write.ts +53 -0
  26. package/app/Actions/Dashboard/Commerce/commerce-discounts-upsells.test.ts +228 -0
  27. package/app/Actions/Dashboard/Commerce/commerce-upsell-list.ts +289 -0
  28. package/app/Actions/Dashboard/Commerce/discount-records.ts +392 -0
  29. package/app/Actions/Dashboard/Commerce/upsell-offer-records.ts +307 -0
  30. package/app/Actions/Dashboard/Models/ModelSaveAction.ts +6 -1
  31. package/app/Actions/Dashboard/Models/model-relations.ts +17 -7
  32. package/app/Actions/Dashboard/Models/model-row-writes.ts +9 -8
  33. package/app/Actions/Dashboard/Models/model-write.ts +51 -2
  34. package/app/Actions/Dashboard/Remote/RemoteCommandRunAction.ts +1 -2
  35. package/app/Actions/Dashboard/Remote/RemoteTerminalCloseAction.ts +1 -2
  36. package/app/Actions/Dashboard/Remote/RemoteTerminalInputAction.ts +1 -2
  37. package/app/Actions/Dashboard/Remote/RemoteTerminalOpenAction.ts +1 -2
  38. package/app/Actions/Dashboard/Remote/RemoteTerminalResizeAction.ts +1 -2
  39. package/app/Actions/Dashboard/Remote/RemoteTerminalStreamAction.ts +1 -2
  40. package/app/Actions/Dashboard/Remote/remote-commands.test.ts +2 -2
  41. package/app/Actions/Dashboard/Remote/remote-commands.ts +4 -4
  42. package/app/Actions/Dashboard/Remote/remote-terminal.test.ts +45 -25
  43. package/app/Actions/Dashboard/Remote/remote-terminal.ts +9 -9
  44. package/app/Actions/Storefront/AcceptOrderOfferAction.ts +68 -0
  45. package/app/Actions/Storefront/ApplyDiscountCodeAction.ts +83 -0
  46. package/app/Actions/Storefront/DeclineOrderOfferAction.ts +25 -0
  47. package/app/Actions/Storefront/PlaceOrderAction.ts +135 -72
  48. package/app/Gates.ts +4 -4
  49. package/app/Mail/OrderConfirmation.ts +7 -1
  50. package/app/Models/commerce/Cart.ts +14 -0
  51. package/app/Models/commerce/Discount.ts +255 -0
  52. package/app/Models/commerce/PostPurchaseOffer.ts +175 -0
  53. package/app/Models/commerce/PostPurchaseOfferResponse.ts +145 -0
  54. package/app/Policies/PostPolicy.ts +11 -11
  55. package/app/Storefront/DiscountCodeMessages.ts +12 -0
  56. package/app/Storefront/OrderKey.ts +29 -0
  57. package/app/Storefront/StorefrontPricing.ts +211 -0
  58. package/app/Storefront/UpsellCharge.ts +43 -0
  59. package/functions/projects.test.ts +38 -0
  60. package/functions/projects.ts +99 -0
  61. package/ide/vscode/package.json +1 -1
  62. package/package.json +7 -7
  63. package/resources/components/Dashboard/Commerce/CommerceDiscountBreakdown.stx +72 -0
  64. package/resources/components/Dashboard/Commerce/CommerceDiscountDeleteDialog.stx +19 -0
  65. package/resources/components/Dashboard/Commerce/CommerceDiscountDetailsDialog.stx +110 -0
  66. package/resources/components/Dashboard/Commerce/CommerceDiscountDialog.stx +353 -0
  67. package/resources/components/Dashboard/Commerce/CommerceDiscountsDashboard.stx +211 -0
  68. package/resources/components/Dashboard/Commerce/CommerceDiscountsTable.stx +105 -0
  69. package/resources/components/Dashboard/Commerce/CommerceProductPicker.stx +115 -0
  70. package/resources/components/Dashboard/Commerce/CommerceUpsellDeleteDialog.stx +21 -0
  71. package/resources/components/Dashboard/Commerce/CommerceUpsellDetailsDialog.stx +153 -0
  72. package/resources/components/Dashboard/Commerce/CommerceUpsellDialog.stx +191 -0
  73. package/resources/components/Dashboard/Commerce/CommerceUpsellsDashboard.stx +214 -0
  74. package/resources/components/Dashboard/Commerce/CommerceUpsellsTable.stx +91 -0
  75. package/resources/components/Dashboard/Email/InboxSettingsDashboard.stx +4 -19
  76. package/resources/components/Dashboard/ProjectSwitcher.stx +302 -0
  77. package/resources/components/Dashboard/Settings/SettingsDashboard.stx +5 -3
  78. package/resources/components/Dashboard/UI/SearchFilter.stx +7 -4
  79. package/resources/components/Storefront/OrderSummary.stx +17 -0
  80. package/resources/functions/dashboard/project-switcher.test.ts +14 -0
  81. package/resources/functions/dashboard/project-switcher.ts +28 -0
  82. package/resources/functions/dashboard/sidebar.ts +4 -1
  83. package/resources/plugins/preloader.ts +33 -2
  84. package/resources/views/cart.stx +50 -16
  85. package/resources/views/checkout/contact.stx +11 -5
  86. package/resources/views/checkout/payment.stx +11 -5
  87. package/resources/views/checkout/shipping.stx +11 -5
  88. package/resources/views/orders/[id].stx +227 -50
  89. package/routes/dashboard-api.ts +12 -0
  90. package/routes/dashboard.ts +2 -0
  91. package/routes/storefront.ts +8 -0
  92. package/views/dashboard/commerce/discounts/index.stx +10 -0
  93. package/views/dashboard/commerce/upsells/index.stx +10 -0
  94. package/views/dashboard/layouts/default.stx +17 -0
@@ -0,0 +1,289 @@
1
+ import type { QueryBuilderDialect } from '@stacksjs/database/runtime'
2
+ import { randomUUIDv7 } from 'bun'
3
+ import { db, getDatabaseDialect, mutationCount } from '@stacksjs/database/runtime'
4
+ import { formatDate } from '@stacksjs/orm'
5
+ import type { QueryReader } from '../Content/content-list'
6
+ import { containsPattern, countOf, LIST_PAGE_SIZES, pageWithin, queryText } from '../Content/content-list'
7
+ import { commerceIdentifier, commerceValue } from './commerce-record'
8
+ import type { CommerceSqlRunner } from './commerce-sql'
9
+ import { asText, binder, idPlaceholders, isTrue, sqlRows } from './commerce-sql'
10
+ import type { UpsellOfferRecord, UpsellResponseRecord, UpsellState, UpsellStats, UpsellSummary, UpsellWritePayload } from './upsell-offer-records'
11
+ import { emptyUpsellStats, emptyUpsellSummary, normalizeUpsellOfferRecord, parseIdList, statsFrom, UPSELL_STATES, upsellWriteData } from './upsell-offer-records'
12
+
13
+ /**
14
+ * The Upsells page: post-purchase offers, one page at a time, each with the
15
+ * funnel its responses add up to, and the totals across every offer. Reads
16
+ * are plain SQL, like the other commerce lists, so they run the same on
17
+ * SQLite, PostgreSQL and MySQL.
18
+ */
19
+ export const UPSELL_SORTS = ['newest', 'name', 'priority', 'revenue'] as const
20
+ export type UpsellSort = typeof UPSELL_SORTS[number]
21
+
22
+ export interface UpsellListQuery {
23
+ search: string
24
+ /** '' for any. */
25
+ state: '' | UpsellState
26
+ sort: UpsellSort
27
+ direction: 'asc' | 'desc'
28
+ page: number
29
+ perPage: number
30
+ }
31
+
32
+ export function parseUpsellListQuery(read: QueryReader): UpsellListQuery | { error: string } {
33
+ const pageText = queryText(read, 'page')
34
+ const page = pageText === '' ? 1 : Number(pageText)
35
+ if (!Number.isInteger(page) || page < 1)
36
+ return { error: 'page must be a whole number of 1 or more.' }
37
+
38
+ const sizeText = queryText(read, 'per_page')
39
+ const perPage = sizeText === '' ? 25 : Number(sizeText)
40
+ if (!(LIST_PAGE_SIZES as readonly number[]).includes(perPage))
41
+ return { error: `per_page must be one of ${LIST_PAGE_SIZES.join(', ')}.` }
42
+
43
+ const sort = queryText(read, 'sort') || 'priority'
44
+ if (!(UPSELL_SORTS as readonly string[]).includes(sort))
45
+ return { error: `sort must be one of ${UPSELL_SORTS.join(', ')}.` }
46
+
47
+ const directionText = queryText(read, 'direction').toLowerCase()
48
+ const direction = directionText === '' ? (sort === 'name' ? 'asc' : 'desc') : directionText
49
+ if (direction !== 'asc' && direction !== 'desc')
50
+ return { error: 'direction must be asc or desc.' }
51
+
52
+ const search = queryText(read, 'q')
53
+ if (search.length > 200)
54
+ return { error: 'q must be 200 characters or fewer.' }
55
+
56
+ const state = queryText(read, 'state')
57
+ if (state && !(UPSELL_STATES as readonly string[]).includes(state))
58
+ return { error: `state must be one of ${UPSELL_STATES.join(', ')}.` }
59
+
60
+ return { search, state: state as UpsellListQuery['state'], sort: sort as UpsellSort, direction, page, perPage }
61
+ }
62
+
63
+ function filter(query: Pick<UpsellListQuery, 'search' | 'state'>, dialect: QueryBuilderDialect, nowValue: string): { where: string, values: unknown[] } {
64
+ const { bind, values } = binder(dialect)
65
+ const clauses: string[] = []
66
+ const enabled = `(o.is_active IS NULL OR ${isTrue('o.is_active', dialect)})`
67
+ if (query.state === 'disabled')
68
+ clauses.push(`NOT ${enabled}`)
69
+ if (query.state === 'scheduled')
70
+ clauses.push(`${enabled} AND o.starts_at IS NOT NULL AND o.starts_at > ${bind(nowValue)}`)
71
+ if (query.state === 'ended')
72
+ clauses.push(`${enabled} AND (o.starts_at IS NULL OR o.starts_at <= ${bind(nowValue)}) AND o.ends_at IS NOT NULL AND o.ends_at < ${bind(nowValue)}`)
73
+ if (query.state === 'running')
74
+ clauses.push(`${enabled} AND (o.starts_at IS NULL OR o.starts_at <= ${bind(nowValue)}) AND (o.ends_at IS NULL OR o.ends_at >= ${bind(nowValue)})`)
75
+ if (query.search) {
76
+ const pattern = containsPattern(query.search)
77
+ clauses.push(`(${['o.name', `COALESCE(o.headline, '')`, `COALESCE(o.message, '')`].map(column => `LOWER(${column}) LIKE ${bind(pattern)} ESCAPE '!'`).join(' OR ')})`)
78
+ }
79
+ return { where: clauses.length ? ` WHERE ${clauses.map(c => `(${c})`).join(' AND ')}` : '', values }
80
+ }
81
+
82
+ /**
83
+ * Revenue per offer, for sorting by it in SQL. The status is compared as text:
84
+ * PostgreSQL may keep it as an enum.
85
+ */
86
+ function revenueSql(dialect: QueryBuilderDialect): string {
87
+ return `(SELECT COALESCE(SUM(r.amount), 0) FROM post_purchase_offer_responses r WHERE r.post_purchase_offer_id = o.id AND ${asText('r.status', dialect)} = 'accepted')`
88
+ }
89
+
90
+ function orderBy(query: Pick<UpsellListQuery, 'sort' | 'direction'>, dialect: QueryBuilderDialect): string {
91
+ const direction = query.direction === 'asc' ? 'ASC' : 'DESC'
92
+ switch (query.sort) {
93
+ case 'name': return ` ORDER BY LOWER(o.name) ${direction}, o.id ${direction}`
94
+ case 'revenue': return ` ORDER BY ${revenueSql(dialect)} ${direction}, LOWER(o.name) ASC, o.id ${direction}`
95
+ // Ties by age, oldest first: the offer that would show first does.
96
+ case 'priority': return ` ORDER BY COALESCE(o.priority, 0) ${direction}, o.id ASC`
97
+ default: return ` ORDER BY o.id ${direction}`
98
+ }
99
+ }
100
+
101
+ /** Product names by id, for the offers' products and triggers. */
102
+ async function productNames(ids: number[], run: CommerceSqlRunner, dialect: QueryBuilderDialect): Promise<Map<number, string>> {
103
+ if (ids.length === 0)
104
+ return new Map()
105
+ const rows = await run.unsafe(`SELECT id, name FROM products WHERE id IN (${idPlaceholders(ids, dialect)})`, ids).execute()
106
+ return new Map(sqlRows(rows).map(row => [Number(row.id), String(row.name ?? `Product ${row.id}`)]))
107
+ }
108
+
109
+ /** The funnel of each offer, from its responses grouped by status. */
110
+ async function statsByOffer(offerIds: number[], run: CommerceSqlRunner, dialect: QueryBuilderDialect): Promise<Map<number, UpsellStats>> {
111
+ const out = new Map<number, UpsellStats>()
112
+ if (offerIds.length === 0)
113
+ return out
114
+ const rows = await run.unsafe(
115
+ `SELECT post_purchase_offer_id AS offer_id, ${asText('status', dialect)} AS status, COUNT(*) AS row_count, SUM(COALESCE(amount, 0)) AS amount_total, SUM(COALESCE(quantity, 0)) AS unit_total
116
+ FROM post_purchase_offer_responses WHERE post_purchase_offer_id IN (${idPlaceholders(offerIds, dialect)})
117
+ GROUP BY post_purchase_offer_id, ${asText('status', dialect)}`,
118
+ offerIds,
119
+ ).execute()
120
+ const groups = new Map<number, Array<{ status: string, rows: number, amount: number, units: number }>>()
121
+ for (const row of sqlRows(rows)) {
122
+ const id = Number(row.offer_id)
123
+ const list = groups.get(id) ?? []
124
+ list.push({ status: String(row.status), rows: countOf(row.row_count), amount: countOf(row.amount_total), units: countOf(row.unit_total) })
125
+ groups.set(id, list)
126
+ }
127
+ for (const id of offerIds)
128
+ out.set(id, statsFrom(groups.get(id) ?? []))
129
+ return out
130
+ }
131
+
132
+ async function recordsFor(rows: Array<Record<string, unknown>>, nowValue: string, run: CommerceSqlRunner, dialect: QueryBuilderDialect): Promise<UpsellOfferRecord[]> {
133
+ if (rows.length === 0)
134
+ return []
135
+ const ids = rows.map(row => Number(row.id))
136
+ const productIds = [...new Set(rows.flatMap(row => [...parseIdList(row.product_ids), ...parseIdList(row.trigger_product_ids)]))]
137
+ const [names, stats] = await Promise.all([productNames(productIds, run, dialect), statsByOffer(ids, run, dialect)])
138
+ return rows.map(row => normalizeUpsellOfferRecord(row, nowValue, names, stats.get(Number(row.id)) ?? emptyUpsellStats()))
139
+ }
140
+
141
+ async function summarize(run: CommerceSqlRunner, dialect: QueryBuilderDialect, nowValue: string): Promise<UpsellSummary> {
142
+ const status = asText('status', dialect)
143
+ const { bind, values } = binder(dialect)
144
+ const enabled = `(is_active IS NULL OR ${isTrue('is_active', dialect)})`
145
+ const running = `${enabled} AND (starts_at IS NULL OR starts_at <= ${bind(nowValue)}) AND (ends_at IS NULL OR ends_at >= ${bind(nowValue)})`
146
+ const [offers, funnel, top] = await Promise.all([
147
+ run.unsafe(`SELECT COUNT(*) AS total_count, SUM(CASE WHEN ${running} THEN 1 ELSE 0 END) AS running_count FROM post_purchase_offers`, values).execute(),
148
+ run.unsafe(`SELECT COUNT(*) AS view_count, SUM(CASE WHEN ${status} = 'accepted' THEN 1 ELSE 0 END) AS accepted_count, SUM(CASE WHEN ${status} = 'declined' THEN 1 ELSE 0 END) AS declined_count, SUM(CASE WHEN ${status} = 'accepted' THEN COALESCE(amount, 0) ELSE 0 END) AS revenue_total, SUM(CASE WHEN ${status} = 'accepted' THEN COALESCE(quantity, 0) ELSE 0 END) AS unit_total FROM post_purchase_offer_responses`).execute(),
149
+ run.unsafe(`SELECT o.id, o.name, ${revenueSql(dialect)} AS revenue_total, (SELECT COUNT(*) FROM post_purchase_offer_responses r WHERE r.post_purchase_offer_id = o.id) AS view_count, (SELECT COUNT(*) FROM post_purchase_offer_responses r WHERE r.post_purchase_offer_id = o.id AND ${asText('r.status', dialect)} = 'accepted') AS accepted_count FROM post_purchase_offers o ORDER BY revenue_total DESC, LOWER(o.name) ASC, o.id ASC LIMIT 5`).execute(),
150
+ ])
151
+ const o = sqlRows(offers)[0] ?? {}
152
+ const f = sqlRows(funnel)[0] ?? {}
153
+ const summary = emptyUpsellSummary()
154
+ summary.total = countOf(o.total_count)
155
+ summary.running = countOf(o.running_count)
156
+ summary.views = countOf(f.view_count)
157
+ summary.accepted = countOf(f.accepted_count)
158
+ summary.declined = countOf(f.declined_count)
159
+ summary.revenue = countOf(f.revenue_total)
160
+ summary.units = countOf(f.unit_total)
161
+ summary.conversionRate = summary.views ? summary.accepted / summary.views : 0
162
+ summary.top = sqlRows(top)
163
+ .filter(row => countOf(row.revenue_total) > 0)
164
+ .map((row) => {
165
+ const views = countOf(row.view_count)
166
+ return {
167
+ id: commerceIdentifier(commerceValue(row, 'id'), 'PostPurchaseOffer'),
168
+ name: String(row.name ?? ''),
169
+ revenue: countOf(row.revenue_total),
170
+ conversionRate: views ? countOf(row.accepted_count) / views : 0,
171
+ }
172
+ })
173
+ return summary
174
+ }
175
+
176
+ export interface UpsellPage {
177
+ records: UpsellOfferRecord[]
178
+ total: number
179
+ page: number
180
+ summary: UpsellSummary
181
+ }
182
+
183
+ export async function readUpsellPage(
184
+ query: UpsellListQuery,
185
+ run: CommerceSqlRunner = db,
186
+ dialect: QueryBuilderDialect = getDatabaseDialect(),
187
+ now: Date = new Date(),
188
+ ): Promise<UpsellPage> {
189
+ const nowValue = formatDate(now)
190
+ const { where, values } = filter(query, dialect, nowValue)
191
+ const [counted, summary] = await Promise.all([
192
+ run.unsafe(`SELECT COUNT(*) AS total_count FROM post_purchase_offers o${where}`, values).execute(),
193
+ summarize(run, dialect, nowValue),
194
+ ])
195
+ const total = countOf(sqlRows(counted)[0]?.total_count)
196
+ const page = pageWithin(query.page, total, query.perPage)
197
+ const rows = await run.unsafe(
198
+ `SELECT o.* FROM post_purchase_offers o${where}${orderBy(query, dialect)} LIMIT ${query.perPage} OFFSET ${(page - 1) * query.perPage}`,
199
+ values,
200
+ ).execute()
201
+ return { records: await recordsFor(sqlRows(rows), nowValue, run, dialect), total, page, summary }
202
+ }
203
+
204
+ /** One offer with its funnel and its most recent responses, newest first. */
205
+ export async function readUpsellDetail(
206
+ id: number,
207
+ limit = 25,
208
+ run: CommerceSqlRunner = db,
209
+ dialect: QueryBuilderDialect = getDatabaseDialect(),
210
+ now: Date = new Date(),
211
+ ): Promise<{ record: UpsellOfferRecord, responses: UpsellResponseRecord[] } | null> {
212
+ const nowValue = formatDate(now)
213
+ const offerParam = idPlaceholders([id], dialect)
214
+ const rows = sqlRows(await run.unsafe(`SELECT * FROM post_purchase_offers WHERE id = ${offerParam}`, [id]).execute())
215
+ if (rows.length === 0)
216
+ return null
217
+ const [record] = await recordsFor(rows, nowValue, run, dialect)
218
+ const responses = sqlRows(await run.unsafe(
219
+ `SELECT r.*, p.name AS product_name FROM post_purchase_offer_responses r LEFT JOIN products p ON p.id = r.product_id WHERE r.post_purchase_offer_id = ${offerParam} ORDER BY r.id DESC LIMIT ${Math.max(1, Math.min(100, limit))}`,
220
+ [id],
221
+ ).execute())
222
+ return {
223
+ record: record!,
224
+ responses: responses.map(row => ({
225
+ id: String(row.id),
226
+ orderId: String(row.order_id ?? ''),
227
+ status: String(row.status) as UpsellResponseRecord['status'],
228
+ productId: String(row.product_id ?? ''),
229
+ productLabel: row.product_name ? String(row.product_name) : `Deleted product #${row.product_id}`,
230
+ variantId: row.variant_id == null ? '' : String(row.variant_id),
231
+ quantity: row.quantity == null ? null : Number(row.quantity),
232
+ unitPrice: row.unit_price == null ? null : Number(row.unit_price),
233
+ compareAtPrice: row.compare_at_price == null ? null : Number(row.compare_at_price),
234
+ amount: row.amount == null ? null : Number(row.amount),
235
+ currency: String(row.currency ?? ''),
236
+ failureReason: String(row.failure_reason ?? ''),
237
+ respondedAt: String(row.responded_at ?? ''),
238
+ createdAt: String(row.created_at ?? ''),
239
+ })),
240
+ }
241
+ }
242
+
243
+ export type UpsellSaveResult =
244
+ | { ok: true, record: UpsellOfferRecord }
245
+ | { ok: false, status: 404 | 409 | 422, message: string, errors?: Record<string, string> }
246
+
247
+ /** Create (id null) or change an offer, checking every product it names exists. */
248
+ export async function saveUpsellOffer(id: number | null, payload: UpsellWritePayload, run: any = db, dialect: QueryBuilderDialect = getDatabaseDialect()): Promise<UpsellSaveResult> {
249
+ const checked = upsellWriteData(payload)
250
+ if (!checked.ok)
251
+ return { ok: false, status: 422, message: 'The offer could not be saved.', errors: checked.errors }
252
+
253
+ const names = await productNames(checked.productIds, run, dialect)
254
+ const missing = checked.productIds.filter(productId => !names.has(productId))
255
+ if (missing.length > 0)
256
+ return { ok: false, status: 422, message: 'The offer names products that do not exist.', errors: { productIds: `no product with id ${missing.join(', ')}` } }
257
+
258
+ const now = formatDate(new Date())
259
+ let offerId = id
260
+ if (id === null) {
261
+ const uuid = randomUUIDv7()
262
+ await run.insertInto('post_purchase_offers').values({ ...checked.data, uuid, created_at: now, updated_at: now }).execute()
263
+ const row = await run.selectFrom('post_purchase_offers').where('uuid', '=', uuid).select(['id']).executeTakeFirst()
264
+ offerId = Number(row?.id)
265
+ }
266
+ else {
267
+ const result = await run.updateTable('post_purchase_offers').set({ ...checked.data, updated_at: now }).where('id', '=', id).executeTakeFirst()
268
+ if (mutationCount(result) === 0)
269
+ return { ok: false, status: 404, message: `Offer ${id} does not exist.` }
270
+ }
271
+
272
+ const detail = await readUpsellDetail(Number(offerId), 1, run, dialect)
273
+ if (!detail)
274
+ return { ok: false, status: 404, message: `Offer ${offerId} does not exist.` }
275
+ return { ok: true, record: detail.record }
276
+ }
277
+
278
+ /**
279
+ * Delete an offer nobody has answered yet. Once orders have responded, its
280
+ * responses are the record of what was added to them, so the offer is
281
+ * switched off instead and the refusal says so.
282
+ */
283
+ export async function deleteUpsellOffer(id: number, run: any = db): Promise<{ ok: true } | { ok: false, status: 404 | 409, message: string }> {
284
+ const answered = await run.selectFrom('post_purchase_offer_responses').where('post_purchase_offer_id', '=', id).select(['id']).limit(1).executeTakeFirst()
285
+ if (answered)
286
+ return { ok: false, status: 409, message: 'Orders have already responded to this offer, and those records are kept. Switch it off instead.' }
287
+ const result = await run.deleteFrom('post_purchase_offers').where('id', '=', id).executeTakeFirst()
288
+ return mutationCount(result) > 0 ? { ok: true } : { ok: false, status: 404, message: `Offer ${id} does not exist.` }
289
+ }
@@ -0,0 +1,392 @@
1
+ import type { DiscountRow } from '@stacksjs/commerce/discounts/rules'
2
+ import { applyDiscounts, discountLabel } from '@stacksjs/commerce/discounts/engine'
3
+ import { ruleFromDiscount } from '@stacksjs/commerce/discounts/rules'
4
+ import { formatCurrency } from '@stacksjs/commerce/money'
5
+ import { commerceIdentifier, commerceTimestamp, commerceValue } from './commerce-record'
6
+
7
+ /**
8
+ * Discounts as the dashboard shows and writes them (the Discount model,
9
+ * `commerce.discounts`). A record is what the engine reads, plus the labels a
10
+ * table needs; a write is checked through the engine itself, so the dashboard
11
+ * cannot save a discount that would fail at a shopper's checkout.
12
+ */
13
+
14
+ export const DISCOUNT_TYPES = ['percentage', 'fixed_amount', 'buy_x_get_y', 'volume', 'free_shipping'] as const
15
+ export type DiscountType = typeof DISCOUNT_TYPES[number]
16
+ export type DiscountMethod = 'automatic' | 'code'
17
+ /** Where a discount stands now: the order the engine checks them in. */
18
+ export const DISCOUNT_STATES = ['active', 'scheduled', 'expired', 'exhausted', 'disabled'] as const
19
+ export type DiscountState = typeof DISCOUNT_STATES[number]
20
+
21
+ export interface DiscountTargetRecord {
22
+ productIds: string[]
23
+ variantIds: string[]
24
+ categoryIds: string[]
25
+ }
26
+
27
+ export interface DiscountRecord {
28
+ id: string
29
+ title: string
30
+ code: string
31
+ method: DiscountMethod
32
+ type: DiscountType
33
+ /** Whole percent for `percentage`, minor units for `fixed_amount`, 0 otherwise. */
34
+ value: number
35
+ scope: '' | 'product' | 'order'
36
+ perItem: boolean
37
+ target: DiscountTargetRecord
38
+ buyQuantity: number | null
39
+ buyTarget: DiscountTargetRecord
40
+ getQuantity: number | null
41
+ getTarget: DiscountTargetRecord
42
+ getPercent: number | null
43
+ maxApplications: number | null
44
+ tiers: Array<{ minQuantity: number, percent: number }>
45
+ maxShipping: number | null
46
+ minimumSubtotal: number | null
47
+ minimumQuantity: number | null
48
+ maxAmount: number | null
49
+ combinesWith: { product: boolean, order: boolean, shipping: boolean }
50
+ usageLimit: number | null
51
+ usageCount: number
52
+ isActive: boolean
53
+ /** `YYYY-MM-DD`, the day it starts, or ''. */
54
+ startsAt: string
55
+ /** `YYYY-MM-DD`, the last day it runs, or ''. */
56
+ endsAt: string
57
+ state: DiscountState
58
+ /** The badge a storefront shows: `BUY 4, GET 4 FREE`, `20% OFF`. */
59
+ label: string
60
+ /** product, order or shipping: what it takes money off. */
61
+ appliesTo: 'product' | 'order' | 'shipping'
62
+ /** Names of the products its targets name, by id, for showing them. */
63
+ productLabels: Record<string, string>
64
+ createdAt: string
65
+ }
66
+
67
+ export interface DiscountSummary {
68
+ total: number
69
+ automatic: number
70
+ code: number
71
+ active: number
72
+ scheduled: number
73
+ expired: number
74
+ exhausted: number
75
+ disabled: number
76
+ /** Uses counted over every discount. */
77
+ redemptions: number
78
+ byType: Record<DiscountType, number>
79
+ /** The five most used, by title on a tie. */
80
+ mostUsed: Array<{ id: string, title: string, usageCount: number }>
81
+ }
82
+
83
+ export function emptyDiscountSummary(): DiscountSummary {
84
+ return {
85
+ total: 0,
86
+ automatic: 0,
87
+ code: 0,
88
+ active: 0,
89
+ scheduled: 0,
90
+ expired: 0,
91
+ exhausted: 0,
92
+ disabled: 0,
93
+ redemptions: 0,
94
+ byType: { percentage: 0, fixed_amount: 0, buy_x_get_y: 0, volume: 0, free_shipping: 0 },
95
+ mostUsed: [],
96
+ }
97
+ }
98
+
99
+ /** `YYYY-MM-DD HH:MM:SS` (or a date) as the calendar day it names, or ''. */
100
+ function day(value: unknown): string {
101
+ const text = value == null ? '' : String(value).trim()
102
+ return /^\d{4}-\d{2}-\d{2}/.test(text) ? text.slice(0, 10) : ''
103
+ }
104
+
105
+ function ids(list: readonly number[] | null | undefined): string[] {
106
+ return (list ?? []).map(String)
107
+ }
108
+
109
+ function targetRecord(target: { productIds?: readonly number[] | null, variantIds?: readonly number[] | null, categoryIds?: readonly number[] | null } | null | undefined): DiscountTargetRecord {
110
+ return { productIds: ids(target?.productIds), variantIds: ids(target?.variantIds), categoryIds: ids(target?.categoryIds) }
111
+ }
112
+
113
+ /** Where a discount stands at `now`, the order the engine checks in. */
114
+ export function discountState(row: Pick<DiscountRow, 'is_active' | 'starts_at' | 'ends_at' | 'usage_limit' | 'usage_count'>, now: string): DiscountState {
115
+ const active = row.is_active == null || row.is_active === true || row.is_active === 1 || String(row.is_active) === '1' || String(row.is_active) === 'true'
116
+ if (!active)
117
+ return 'disabled'
118
+ if (row.starts_at && String(row.starts_at) > now)
119
+ return 'scheduled'
120
+ if (row.ends_at && String(row.ends_at) < now)
121
+ return 'expired'
122
+ if (row.usage_limit != null && Number(row.usage_count ?? 0) >= Number(row.usage_limit))
123
+ return 'exhausted'
124
+ return 'active'
125
+ }
126
+
127
+ /**
128
+ * One `discounts` row as a dashboard record. `now` is `YYYY-MM-DD HH:MM:SS` in
129
+ * UTC, the way the rows store their dates. A row the engine cannot read throws
130
+ * a TypeError naming it, like every commerce record normalizer.
131
+ */
132
+ export function normalizeDiscountRecord(row: Record<string, unknown>, now: string, currency = 'USD', productNames: ReadonlyMap<number, string> = new Map()): DiscountRecord {
133
+ const id = commerceIdentifier(commerceValue(row, 'id'), 'Discount')
134
+ let rule
135
+ try {
136
+ rule = ruleFromDiscount(row as unknown as DiscountRow)
137
+ applyDiscounts({ lines: [], rules: [rule] })
138
+ }
139
+ catch (error) {
140
+ throw new TypeError(`Discount ${id} cannot be priced: ${error instanceof Error ? error.message : String(error)}`)
141
+ }
142
+ const effect = rule.effect
143
+ const appliesTo = effect.type === 'free_shipping'
144
+ ? 'shipping'
145
+ : effect.type === 'buy_x_get_y' || effect.type === 'volume'
146
+ ? 'product'
147
+ : rule.scope ?? ((rule.target?.productIds?.length || rule.target?.variantIds?.length || rule.target?.categoryIds?.length) ? 'product' : 'order')
148
+
149
+ const target = targetRecord(rule.target)
150
+ const buyTarget = targetRecord(effect.type === 'buy_x_get_y' ? effect.buyTarget : null)
151
+ const getTarget = targetRecord(effect.type === 'buy_x_get_y' ? effect.getTarget : null)
152
+ const productLabels: Record<string, string> = {}
153
+ for (const productId of [...target.productIds, ...buyTarget.productIds, ...getTarget.productIds])
154
+ productLabels[productId] = productNames.get(Number(productId)) ?? `Product #${productId}`
155
+
156
+ return {
157
+ id,
158
+ title: rule.title,
159
+ code: rule.code ?? '',
160
+ method: rule.code ? 'code' : 'automatic',
161
+ type: effect.type,
162
+ value: effect.type === 'percentage' ? effect.percent : effect.type === 'fixed_amount' ? effect.amount : 0,
163
+ scope: rule.scope ?? '',
164
+ perItem: effect.type === 'fixed_amount' && Boolean(effect.perItem),
165
+ target,
166
+ buyQuantity: effect.type === 'buy_x_get_y' ? effect.buyQuantity : null,
167
+ buyTarget,
168
+ getQuantity: effect.type === 'buy_x_get_y' ? effect.getQuantity : null,
169
+ getTarget,
170
+ getPercent: effect.type === 'buy_x_get_y' ? effect.getPercent : null,
171
+ maxApplications: effect.type === 'buy_x_get_y' ? effect.maxApplications ?? null : null,
172
+ tiers: effect.type === 'volume' ? [...effect.tiers].sort((a, b) => a.minQuantity - b.minQuantity) : [],
173
+ maxShipping: effect.type === 'free_shipping' ? effect.maxShipping ?? null : null,
174
+ minimumSubtotal: rule.minimumSubtotal ?? null,
175
+ minimumQuantity: rule.minimumQuantity ?? null,
176
+ maxAmount: rule.maxAmount ?? null,
177
+ combinesWith: {
178
+ product: Boolean(rule.combinesWith?.product),
179
+ order: Boolean(rule.combinesWith?.order),
180
+ shipping: Boolean(rule.combinesWith?.shipping),
181
+ },
182
+ usageLimit: rule.usageLimit ?? null,
183
+ usageCount: Number(rule.usageCount ?? 0),
184
+ isActive: rule.isActive !== false,
185
+ startsAt: day(row.starts_at),
186
+ endsAt: day(row.ends_at),
187
+ state: discountState(row as unknown as DiscountRow, now),
188
+ label: discountLabel(rule, minor => formatCurrency(minor, currency)),
189
+ appliesTo,
190
+ productLabels,
191
+ createdAt: commerceTimestamp(commerceValue(row, 'created_at', 'createdAt'), `Discount ${id}`),
192
+ }
193
+ }
194
+
195
+ /** What the dashboard's dialog sends. */
196
+ export interface DiscountWritePayload {
197
+ title?: unknown
198
+ method?: unknown
199
+ code?: unknown
200
+ type?: unknown
201
+ value?: unknown
202
+ scope?: unknown
203
+ perItem?: unknown
204
+ target?: unknown
205
+ buyQuantity?: unknown
206
+ buyTarget?: unknown
207
+ getQuantity?: unknown
208
+ getTarget?: unknown
209
+ getPercent?: unknown
210
+ maxApplications?: unknown
211
+ tiers?: unknown
212
+ maxShipping?: unknown
213
+ minimumSubtotal?: unknown
214
+ minimumQuantity?: unknown
215
+ maxAmount?: unknown
216
+ combinesWith?: unknown
217
+ usageLimit?: unknown
218
+ isActive?: unknown
219
+ startsAt?: unknown
220
+ endsAt?: unknown
221
+ }
222
+
223
+ export type DiscountWriteResult =
224
+ | { ok: true, data: Record<string, unknown> }
225
+ | { ok: false, errors: Record<string, string> }
226
+
227
+ function optionalWhole(value: unknown, field: string, errors: Record<string, string>, min = 0, max = Number.MAX_SAFE_INTEGER): number | null {
228
+ if (value === undefined || value === null || value === '')
229
+ return null
230
+ const n = Number(value)
231
+ if (!Number.isSafeInteger(n) || n < min || n > max) {
232
+ errors[field] = max === Number.MAX_SAFE_INTEGER ? `must be a whole number of at least ${min}` : `must be a whole number from ${min} to ${max}`
233
+ return null
234
+ }
235
+ return n
236
+ }
237
+
238
+ function idList(value: unknown): number[] {
239
+ if (!Array.isArray(value))
240
+ return []
241
+ return [...new Set(value.map(Number).filter(n => Number.isSafeInteger(n) && n > 0))]
242
+ }
243
+
244
+ function targetJson(value: unknown): string | null {
245
+ const target = (value && typeof value === 'object' ? value : {}) as Record<string, unknown>
246
+ const out = { productIds: idList(target.productIds), variantIds: idList(target.variantIds), categoryIds: idList(target.categoryIds) }
247
+ return out.productIds.length || out.variantIds.length || out.categoryIds.length ? JSON.stringify(out) : null
248
+ }
249
+
250
+ function dateColumn(value: unknown, field: string, endOfDay: boolean, errors: Record<string, string>): string | null {
251
+ const text = value == null ? '' : String(value).trim()
252
+ if (!text)
253
+ return null
254
+ if (!/^\d{4}-\d{2}-\d{2}$/.test(text) || Number.isNaN(Date.parse(text))) {
255
+ errors[field] = 'must be a date'
256
+ return null
257
+ }
258
+ // Stored like every timestamp here (UTC, `formatDate`): from the first
259
+ // second of the start day through the last second of the end day.
260
+ return `${text} ${endOfDay ? '23:59:59' : '00:00:00'}`
261
+ }
262
+
263
+ /**
264
+ * A dialog payload as the columns to write, or the field errors. The rule is
265
+ * then priced once through the engine, so anything it would refuse at
266
+ * checkout (a 120% discount, a tier of 0 units) is refused here, by field.
267
+ */
268
+ export function discountWriteData(payload: DiscountWritePayload): DiscountWriteResult {
269
+ const errors: Record<string, string> = {}
270
+ const title = String(payload.title ?? '').trim()
271
+ if (!title)
272
+ errors.title = 'is required'
273
+ else if (title.length > 255)
274
+ errors.title = 'must be 255 characters or fewer'
275
+
276
+ const method = payload.method === 'code' ? 'code' : 'automatic'
277
+ const code = method === 'code' ? String(payload.code ?? '').trim().toUpperCase() : ''
278
+ if (method === 'code' && !code)
279
+ errors.code = 'is required for a discount code'
280
+ else if (code.length > 64)
281
+ errors.code = 'must be 64 characters or fewer'
282
+ else if (code && !/^[A-Z0-9_-]+$/.test(code))
283
+ errors.code = 'may use letters, digits, - and _ only'
284
+
285
+ const type = String(payload.type ?? '') as DiscountType
286
+ if (!(DISCOUNT_TYPES as readonly string[]).includes(type))
287
+ errors.type = `must be one of ${DISCOUNT_TYPES.join(', ')}`
288
+
289
+ let value = 0
290
+ if (type === 'percentage' || type === 'fixed_amount') {
291
+ const given = optionalWhole(payload.value, 'value', errors, 1, type === 'percentage' ? 100 : Number.MAX_SAFE_INTEGER)
292
+ if (given === null && !errors.value)
293
+ errors.value = 'is required'
294
+ value = given ?? 0
295
+ }
296
+
297
+ const scope = payload.scope === 'product' || payload.scope === 'order' ? payload.scope : null
298
+ const target = targetJson(payload.target)
299
+ if (scope === 'product' && !target && (type === 'percentage' || type === 'fixed_amount'))
300
+ errors.target = 'choose the products it applies to'
301
+
302
+ let tiers: string | null = null
303
+ if (type === 'volume') {
304
+ const list = Array.isArray(payload.tiers) ? payload.tiers : []
305
+ const parsed = list.map(t => ({ minQuantity: Number((t as any)?.minQuantity), percent: Number((t as any)?.percent) }))
306
+ if (parsed.length === 0)
307
+ errors.tiers = 'add at least one tier'
308
+ else if (parsed.some(t => !Number.isSafeInteger(t.minQuantity) || t.minQuantity < 1 || !Number.isSafeInteger(t.percent) || t.percent < 1 || t.percent > 100))
309
+ errors.tiers = 'each tier needs a quantity of at least 1 and a whole percent from 1 to 100'
310
+ else if (new Set(parsed.map(t => t.minQuantity)).size !== parsed.length)
311
+ errors.tiers = 'two tiers cannot start at the same quantity'
312
+ else
313
+ tiers = JSON.stringify(parsed.sort((a, b) => a.minQuantity - b.minQuantity))
314
+ }
315
+
316
+ const buyQuantity = type === 'buy_x_get_y' ? optionalWhole(payload.buyQuantity, 'buyQuantity', errors, 1) : null
317
+ const getQuantity = type === 'buy_x_get_y' ? optionalWhole(payload.getQuantity, 'getQuantity', errors, 1) : null
318
+ const getPercent = type === 'buy_x_get_y' ? optionalWhole(payload.getPercent, 'getPercent', errors, 1, 100) : null
319
+ if (type === 'buy_x_get_y') {
320
+ if (buyQuantity === null && !errors.buyQuantity)
321
+ errors.buyQuantity = 'is required'
322
+ if (getQuantity === null && !errors.getQuantity)
323
+ errors.getQuantity = 'is required'
324
+ if (getPercent === null && !errors.getPercent)
325
+ errors.getPercent = 'is required'
326
+ }
327
+
328
+ const combines = (payload.combinesWith && typeof payload.combinesWith === 'object' ? payload.combinesWith : {}) as Record<string, unknown>
329
+ const startsAt = dateColumn(payload.startsAt, 'startsAt', false, errors)
330
+ const endsAt = dateColumn(payload.endsAt, 'endsAt', true, errors)
331
+ if (startsAt && endsAt && endsAt < startsAt)
332
+ errors.endsAt = 'must be on or after the start date'
333
+
334
+ const data: Record<string, unknown> = {
335
+ title,
336
+ code: code || null,
337
+ type,
338
+ value,
339
+ scope: type === 'percentage' || type === 'fixed_amount' ? scope : null,
340
+ per_item: type === 'fixed_amount' && payload.perItem === true,
341
+ target: type === 'free_shipping' ? null : target,
342
+ buy_quantity: buyQuantity,
343
+ buy_target: type === 'buy_x_get_y' ? targetJson(payload.buyTarget) : null,
344
+ get_quantity: getQuantity,
345
+ get_target: type === 'buy_x_get_y' ? targetJson(payload.getTarget) : null,
346
+ get_percent: getPercent,
347
+ max_applications: type === 'buy_x_get_y' ? optionalWhole(payload.maxApplications, 'maxApplications', errors, 1) : null,
348
+ tiers,
349
+ max_shipping: type === 'free_shipping' ? optionalWhole(payload.maxShipping, 'maxShipping', errors, 0) : null,
350
+ minimum_subtotal: optionalWhole(payload.minimumSubtotal, 'minimumSubtotal', errors, 0),
351
+ minimum_quantity: optionalWhole(payload.minimumQuantity, 'minimumQuantity', errors, 0),
352
+ max_amount: type === 'free_shipping' ? null : optionalWhole(payload.maxAmount, 'maxAmount', errors, 1),
353
+ combines_with_product: combines.product === true,
354
+ combines_with_order: combines.order === true,
355
+ combines_with_shipping: combines.shipping === true,
356
+ usage_limit: optionalWhole(payload.usageLimit, 'usageLimit', errors, 1),
357
+ is_active: payload.isActive !== false,
358
+ starts_at: startsAt,
359
+ ends_at: endsAt,
360
+ }
361
+
362
+ if (Object.keys(errors).length > 0)
363
+ return { ok: false, errors }
364
+
365
+ try {
366
+ applyDiscounts({ lines: [], rules: [ruleFromDiscount({ id: 0, ...data } as unknown as DiscountRow)] })
367
+ }
368
+ catch (error) {
369
+ return { ok: false, errors: { type: error instanceof Error ? error.message : String(error) } }
370
+ }
371
+
372
+ return { ok: true, data }
373
+ }
374
+
375
+ /** Every product id a `discounts` row's targets name, for looking their names up. */
376
+ export function discountProductIds(row: Record<string, unknown>): number[] {
377
+ const ids: number[] = []
378
+ for (const column of ['target', 'buy_target', 'get_target']) {
379
+ const raw = row[column]
380
+ if (typeof raw !== 'string' || !raw)
381
+ continue
382
+ try {
383
+ const parsed = JSON.parse(raw) as { productIds?: unknown }
384
+ if (Array.isArray(parsed.productIds))
385
+ ids.push(...parsed.productIds.map(Number).filter(n => Number.isSafeInteger(n) && n > 0))
386
+ }
387
+ catch {
388
+ // An unreadable target is the normalizer's to report.
389
+ }
390
+ }
391
+ return [...new Set(ids)]
392
+ }