@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.
- 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-buddy/SKILL.md +70 -7
- package/ai/skills/stacks-commerce/SKILL.md +78 -4
- package/ai/skills/stacks-dashboard/SKILL.md +32 -2
- package/ai/skills/stacks-database/SKILL.md +1 -1
- package/ai/skills/stacks-development/SKILL.md +3 -0
- 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 +21 -21
- package/ai/skills/stacks-orm/SKILL.md +2 -2
- package/ai/skills/stacks-utils/SKILL.md +8 -3
- 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/functions/projects.test.ts +38 -0
- package/functions/projects.ts +99 -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/ProjectSwitcher.stx +302 -0
- 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/project-switcher.test.ts +14 -0
- package/resources/functions/dashboard/project-switcher.ts +28 -0
- package/resources/functions/dashboard/sidebar.ts +4 -1
- package/resources/plugins/preloader.ts +33 -2
- 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
- package/views/dashboard/layouts/default.stx +17 -0
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type {
|
|
1
|
+
import type { GateUser } from '@stacksjs/auth'
|
|
2
2
|
import type { RemoteHost } from './remote-commands'
|
|
3
3
|
import type { TerminalAuditSink, TerminalEvent, TerminalProcess, TerminalSessionOptions } from './remote-terminal'
|
|
4
4
|
import { describe, expect, it, jest } from 'bun:test'
|
|
@@ -16,8 +16,8 @@ import { encodeTerminalEvent, terminalEventStream, terminalSessions } from './te
|
|
|
16
16
|
* local shell standing in for ssh.
|
|
17
17
|
*/
|
|
18
18
|
|
|
19
|
-
const alice = { id: 1, email: 'alice@example.com' } as unknown as
|
|
20
|
-
const bob = { id: 2, email: 'bob@example.com' } as unknown as
|
|
19
|
+
const alice = { id: 1, email: 'alice@example.com' } as unknown as GateUser
|
|
20
|
+
const bob = { id: 2, email: 'bob@example.com' } as unknown as GateUser
|
|
21
21
|
|
|
22
22
|
const shellHost: RemoteHost = { key: 'app', host: 'app.example.com', user: 'deploy', knownHosts: 'app.example.com ssh-ed25519 AAAA', terminal: true }
|
|
23
23
|
const commandOnlyHost: RemoteHost = { key: 'db', host: 'db.example.com', user: 'deploy', knownHosts: 'db.example.com ssh-ed25519 AAAA' }
|
|
@@ -396,28 +396,48 @@ describe.if(Boolean(SSHD))('a terminal session over real SSH', () => {
|
|
|
396
396
|
for (const name of ['host_key', 'client_key'])
|
|
397
397
|
Bun.spawnSync(['ssh-keygen', '-q', '-t', 'ed25519', '-N', '', '-f', join(dir, name)])
|
|
398
398
|
writeFileSync(join(dir, 'authorized_keys'), readFileSync(join(dir, 'client_key.pub')), { mode: 0o600 })
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
399
|
+
// A port the OS says is free, rather than a random one: sshd exits when its
|
|
400
|
+
// port is taken, and a random pick in a busy CI job sometimes is. Retried
|
|
401
|
+
// if sshd exits anyway, and a daemon that never listens fails here with its
|
|
402
|
+
// own log, not later as a misleading "Connection refused".
|
|
403
|
+
let port = 0
|
|
404
|
+
let daemon: ReturnType<typeof Bun.spawn> | undefined
|
|
405
|
+
for (let attempt = 0; attempt < 3 && !daemon; attempt++) {
|
|
406
|
+
const probe = Bun.listen({ hostname: '127.0.0.1', port: 0, socket: { data() {} } })
|
|
407
|
+
port = probe.port
|
|
408
|
+
probe.stop(true)
|
|
409
|
+
writeFileSync(join(dir, 'sshd_config'), [
|
|
410
|
+
`Port ${port}`,
|
|
411
|
+
'ListenAddress 127.0.0.1',
|
|
412
|
+
`HostKey ${join(dir, 'host_key')}`,
|
|
413
|
+
`AuthorizedKeysFile ${join(dir, 'authorized_keys')}`,
|
|
414
|
+
`PidFile ${join(dir, 'sshd.pid')}`,
|
|
415
|
+
'UsePAM no',
|
|
416
|
+
'StrictModes no',
|
|
417
|
+
'PasswordAuthentication no',
|
|
418
|
+
'KbdInteractiveAuthentication no',
|
|
419
|
+
'LogLevel ERROR',
|
|
420
|
+
// The same shell whoever runs this, rather than their login shell -
|
|
421
|
+
// some report 0 for `exit 7`, which would make the exit status untestable.
|
|
422
|
+
'ForceCommand /bin/sh -i',
|
|
423
|
+
].join('\n'))
|
|
424
|
+
const started = Bun.spawn([SSHD!, '-D', '-f', join(dir, 'sshd_config'), '-E', join(dir, 'sshd.log')])
|
|
425
|
+
for (let i = 0; i < 50 && started.exitCode === null; i++) {
|
|
426
|
+
if (Bun.spawnSync(['nc', '-z', '127.0.0.1', String(port)]).exitCode === 0) {
|
|
427
|
+
daemon = started
|
|
428
|
+
break
|
|
429
|
+
}
|
|
430
|
+
await Bun.sleep(100)
|
|
431
|
+
}
|
|
432
|
+
if (!daemon)
|
|
433
|
+
started.kill()
|
|
434
|
+
}
|
|
435
|
+
if (!daemon) {
|
|
436
|
+
const log = existsSync(join(dir, 'sshd.log')) ? readFileSync(join(dir, 'sshd.log'), 'utf8') : 'no sshd log'
|
|
437
|
+
rmSync(dir, { force: true, recursive: true })
|
|
438
|
+
throw new Error(`the test sshd never listened on 127.0.0.1:${port}: ${log}`)
|
|
420
439
|
}
|
|
440
|
+
const running = daemon
|
|
421
441
|
const hostKey = readFileSync(join(dir, 'host_key.pub'), 'utf8').split(' ').slice(0, 2).join(' ')
|
|
422
442
|
const host: RemoteHost = {
|
|
423
443
|
key: 'local',
|
|
@@ -431,7 +451,7 @@ describe.if(Boolean(SSHD))('a terminal session over real SSH', () => {
|
|
|
431
451
|
return {
|
|
432
452
|
host,
|
|
433
453
|
stop: () => {
|
|
434
|
-
|
|
454
|
+
running.kill()
|
|
435
455
|
rmSync(dir, { force: true, recursive: true })
|
|
436
456
|
},
|
|
437
457
|
}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type {
|
|
1
|
+
import type { GateUser } from '@stacksjs/auth'
|
|
2
2
|
import type { RemoteHost } from './remote-commands'
|
|
3
3
|
import { randomBytes } from 'node:crypto'
|
|
4
4
|
import { RemoteCommandError, resolveHost } from './remote-commands'
|
|
@@ -68,7 +68,7 @@ export interface TerminalAuditSink {
|
|
|
68
68
|
}
|
|
69
69
|
|
|
70
70
|
/** Whether `user` may open a terminal on the host with this key. */
|
|
71
|
-
export type TerminalAuthorizer = (user:
|
|
71
|
+
export type TerminalAuthorizer = (user: GateUser | null, hostKey: string) => Promise<boolean> | boolean
|
|
72
72
|
|
|
73
73
|
/** What a viewer receives: output in order, then the end. */
|
|
74
74
|
export type TerminalEvent =
|
|
@@ -124,7 +124,7 @@ interface Session {
|
|
|
124
124
|
detachTimer?: ReturnType<typeof setTimeout>
|
|
125
125
|
}
|
|
126
126
|
|
|
127
|
-
function ownerOf(user:
|
|
127
|
+
function ownerOf(user: GateUser | null): string {
|
|
128
128
|
if (!user)
|
|
129
129
|
throw new RemoteCommandError('Authentication is required.', 401)
|
|
130
130
|
const id = (user as { id?: unknown }).id
|
|
@@ -160,7 +160,7 @@ export class TerminalSessions {
|
|
|
160
160
|
* process starts, so a session that hangs on connect is still on record.
|
|
161
161
|
*/
|
|
162
162
|
async open(input: {
|
|
163
|
-
user:
|
|
163
|
+
user: GateUser | null
|
|
164
164
|
hosts: readonly RemoteHost[]
|
|
165
165
|
hostKey: unknown
|
|
166
166
|
authorizer?: TerminalAuthorizer
|
|
@@ -237,7 +237,7 @@ export class TerminalSessions {
|
|
|
237
237
|
}
|
|
238
238
|
|
|
239
239
|
/** Type into the session. */
|
|
240
|
-
async input(id: string, user:
|
|
240
|
+
async input(id: string, user: GateUser | null, data: unknown): Promise<void> {
|
|
241
241
|
const session = this.find(id, user)
|
|
242
242
|
if (typeof data !== 'string' || data.length === 0)
|
|
243
243
|
throw new RemoteCommandError('Input is a non-empty string.', 422)
|
|
@@ -251,13 +251,13 @@ export class TerminalSessions {
|
|
|
251
251
|
await this.recordInput(session, data)
|
|
252
252
|
}
|
|
253
253
|
|
|
254
|
-
resize(id: string, user:
|
|
254
|
+
resize(id: string, user: GateUser | null, cols: unknown, rows: unknown): void {
|
|
255
255
|
const session = this.find(id, user)
|
|
256
256
|
const size = normalizeSize(cols, rows)
|
|
257
257
|
session.process.resize(size.cols, size.rows)
|
|
258
258
|
}
|
|
259
259
|
|
|
260
|
-
async close(id: string, user:
|
|
260
|
+
async close(id: string, user: GateUser | null): Promise<void> {
|
|
261
261
|
await this.end(this.find(id, user), 'closed')
|
|
262
262
|
}
|
|
263
263
|
|
|
@@ -277,7 +277,7 @@ export class TerminalSessions {
|
|
|
277
277
|
* viewer stops reading. A viewer that reconnects passes the last sequence it
|
|
278
278
|
* saw and misses nothing still in the replay buffer.
|
|
279
279
|
*/
|
|
280
|
-
watch(id: string, user:
|
|
280
|
+
watch(id: string, user: GateUser | null, afterSeq = 0): AsyncIterable<TerminalEvent> {
|
|
281
281
|
const session = this.find(id, user)
|
|
282
282
|
const queue: TerminalEvent[] = session.backlog
|
|
283
283
|
.filter(chunk => chunk.seq > afterSeq)
|
|
@@ -327,7 +327,7 @@ export class TerminalSessions {
|
|
|
327
327
|
}
|
|
328
328
|
|
|
329
329
|
/** The session with this id, if this user owns it. Anyone else gets the 404 a missing id gets. */
|
|
330
|
-
private find(id: unknown, user:
|
|
330
|
+
private find(id: unknown, user: GateUser | null): Session {
|
|
331
331
|
const owner = ownerOf(user)
|
|
332
332
|
const session = typeof id === 'string' ? this.sessions.get(id) : undefined
|
|
333
333
|
if (!session || session.owner !== owner || session.ended)
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
import { Action } from '@stacksjs/actions/runtime'
|
|
2
|
+
import { upsells } from '@stacksjs/commerce'
|
|
3
|
+
import { refuse } from '@stacksjs/router'
|
|
4
|
+
import { orderForKey } from '../../Storefront/OrderKey'
|
|
5
|
+
import { storefrontUpsellCharger } from '../../Storefront/UpsellCharge'
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* "Add to order" on the confirmation page: take a post-purchase offer.
|
|
9
|
+
*
|
|
10
|
+
* Authorised by the order's key, like the page itself. The price comes from
|
|
11
|
+
* the catalog and the offer, never from the form; `commerce.upsells` claims
|
|
12
|
+
* the offer once per order and product, reserves the stock, charges (see
|
|
13
|
+
* `app/Storefront/UpsellCharge.ts`) and adds the line to the order in one
|
|
14
|
+
* transaction. A browser form goes back to the order with a notice; a script
|
|
15
|
+
* gets the result.
|
|
16
|
+
*/
|
|
17
|
+
export default new Action({
|
|
18
|
+
name: 'AcceptOrderOfferAction',
|
|
19
|
+
description: 'Add a discounted post-purchase offer to an order just placed.',
|
|
20
|
+
method: 'POST',
|
|
21
|
+
notice: (result: { status: string }) => result.status === 'requires_action'
|
|
22
|
+
? 'Your bank needs you to confirm this payment. We have reserved the items for you.'
|
|
23
|
+
: result.status === 'pending'
|
|
24
|
+
? 'Added to your order. We will confirm the payment shortly.'
|
|
25
|
+
: 'Added to your order.',
|
|
26
|
+
next: (result: { order_id: number, key: string }) => `/orders/${result.order_id}?key=${encodeURIComponent(result.key)}`,
|
|
27
|
+
|
|
28
|
+
async handle(request: any) {
|
|
29
|
+
const key = String(request.get('key') ?? '')
|
|
30
|
+
const order = await orderForKey(request.get('order_id'), key)
|
|
31
|
+
if (!order)
|
|
32
|
+
return refuse('We could not find that order.', { status: 404 })
|
|
33
|
+
|
|
34
|
+
const variant = request.get('variant_id')
|
|
35
|
+
const result = await upsells.acceptOffer({
|
|
36
|
+
orderId: Number(order.id),
|
|
37
|
+
offerId: Number(request.get('offer_id')),
|
|
38
|
+
productId: Number(request.get('product_id')),
|
|
39
|
+
variantId: variant == null || variant === '' ? null : Number(variant),
|
|
40
|
+
quantity: Number(request.get('quantity')),
|
|
41
|
+
charge: await storefrontUpsellCharger(order),
|
|
42
|
+
})
|
|
43
|
+
|
|
44
|
+
if (result.ok)
|
|
45
|
+
return { ok: true, status: result.status, order_id: Number(order.id), key, response_id: result.response.id }
|
|
46
|
+
|
|
47
|
+
if (result.reason === 'payment-requires-action') {
|
|
48
|
+
// The bank wants the shopper to confirm. A page with the provider's SDK
|
|
49
|
+
// finishes it from `client_confirmation`, and the payment webhook then
|
|
50
|
+
// adds the line. The items stay reserved meanwhile.
|
|
51
|
+
return {
|
|
52
|
+
ok: false,
|
|
53
|
+
status: 'requires_action',
|
|
54
|
+
order_id: Number(order.id),
|
|
55
|
+
key,
|
|
56
|
+
response_id: result.response.id,
|
|
57
|
+
client_confirmation: result.clientConfirmation ?? null,
|
|
58
|
+
redirect_url: result.redirectUrl ?? null,
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
const status = result.reason === 'already-responded' || result.reason === 'out-of-stock' ? 409
|
|
63
|
+
: result.reason === 'payment-failed' ? 402
|
|
64
|
+
: result.reason === 'offer-expired' || result.reason === 'order-closed' ? 410
|
|
65
|
+
: 422
|
|
66
|
+
return refuse(result.message, { status })
|
|
67
|
+
},
|
|
68
|
+
})
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
import type { DiscountRule } from '@stacksjs/commerce/discounts/engine'
|
|
2
|
+
import type { StorefrontLine } from '../../Storefront/StorefrontPricing'
|
|
3
|
+
import { Action } from '@stacksjs/actions/runtime'
|
|
4
|
+
import { discounts } from '@stacksjs/commerce'
|
|
5
|
+
import { db } from '@stacksjs/database/runtime'
|
|
6
|
+
import { refuse } from '@stacksjs/router'
|
|
7
|
+
import { readCartCookie } from '../../Storefront/CartCookie'
|
|
8
|
+
import { DISCOUNT_CODE_MESSAGES } from '../../Storefront/DiscountCodeMessages'
|
|
9
|
+
import { storefrontCurrency } from '../../Storefront/StorefrontMoney'
|
|
10
|
+
import { priceStorefront } from '../../Storefront/StorefrontPricing'
|
|
11
|
+
|
|
12
|
+
const CART_COOKIE = 'stacks_cart'
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* The cart's discount code field: apply a code, or take it off (`remove`).
|
|
16
|
+
*
|
|
17
|
+
* A code is priced against the cart before it is kept, so the shopper hears
|
|
18
|
+
* straight away that it has expired or does not reach anything in the cart,
|
|
19
|
+
* in the engine's terms (`rejectedCodes`). It is checked again when the order
|
|
20
|
+
* is placed. One code per cart; applying another replaces it.
|
|
21
|
+
*/
|
|
22
|
+
export default new Action({
|
|
23
|
+
name: 'ApplyDiscountCodeAction',
|
|
24
|
+
description: 'Apply or remove the discount code on the caller\'s cart.',
|
|
25
|
+
method: 'POST',
|
|
26
|
+
notice: (result: { code: string | null }) => result.code ? `Discount code ${result.code} applied.` : 'Discount code removed.',
|
|
27
|
+
|
|
28
|
+
async handle(request: any) {
|
|
29
|
+
const token = readCartCookie(request, CART_COOKIE)
|
|
30
|
+
const cart = token
|
|
31
|
+
? await (db as any).selectFrom('carts').where('session_token', '=', token).where('status', '=', 'active').selectAll().executeTakeFirst()
|
|
32
|
+
: null
|
|
33
|
+
if (!cart)
|
|
34
|
+
return refuse('Your cart is empty.', { status: 400 })
|
|
35
|
+
|
|
36
|
+
const remove = String(request.get('remove') ?? '') !== ''
|
|
37
|
+
const code = String(request.get('code') ?? '').trim()
|
|
38
|
+
|
|
39
|
+
if (remove || code === '') {
|
|
40
|
+
await (db as any).updateTable('carts').set({ discount_code: null }).where('id', '=', cart.id).execute()
|
|
41
|
+
return { ok: true, code: null }
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
if (code.length > 64)
|
|
45
|
+
return refuse(DISCOUNT_CODE_MESSAGES['not-found'], { field: 'code' })
|
|
46
|
+
|
|
47
|
+
const items = await (db as any).selectFrom('cart_items').where('cart_id', '=', cart.id).selectAll().execute()
|
|
48
|
+
const lines: StorefrontLine[] = []
|
|
49
|
+
for (const item of items) {
|
|
50
|
+
const product = await (db as any).selectFrom('products').where('slug', '=', item.product_sku).selectAll().executeTakeFirst()
|
|
51
|
+
if (!product)
|
|
52
|
+
continue
|
|
53
|
+
lines.push({
|
|
54
|
+
id: Number(item.id),
|
|
55
|
+
productId: Number(product.id),
|
|
56
|
+
categoryId: product.category_id == null ? null : Number(product.category_id),
|
|
57
|
+
quantity: Number(item.quantity),
|
|
58
|
+
unitPrice: Math.round(Number(item.unit_price)),
|
|
59
|
+
})
|
|
60
|
+
}
|
|
61
|
+
if (lines.length === 0)
|
|
62
|
+
return refuse('Your cart is empty.', { status: 400 })
|
|
63
|
+
|
|
64
|
+
let rules: DiscountRule[] = []
|
|
65
|
+
try {
|
|
66
|
+
rules = await discounts.fetchRules({ codes: [code] })
|
|
67
|
+
}
|
|
68
|
+
catch {
|
|
69
|
+
return refuse('Discount codes are not available right now.', { field: 'code' })
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
const priced = priceStorefront(lines, rules, storefrontCurrency(cart.currency), new Date(), [code])
|
|
73
|
+
const rejected = priced.result.rejectedCodes.find(r => r.code.toUpperCase() === code.toUpperCase())
|
|
74
|
+
if (rejected)
|
|
75
|
+
return refuse(DISCOUNT_CODE_MESSAGES[rejected.reason], { field: 'code' })
|
|
76
|
+
|
|
77
|
+
// Kept as the store spells it, so the cart shows the code it knows.
|
|
78
|
+
const applied = priced.result.applied.find(a => a.code?.toUpperCase() === code.toUpperCase())
|
|
79
|
+
const stored = applied?.code ?? code
|
|
80
|
+
await (db as any).updateTable('carts').set({ discount_code: stored }).where('id', '=', cart.id).execute()
|
|
81
|
+
return { ok: true, code: stored, discount: priced.discount, total: priced.total }
|
|
82
|
+
},
|
|
83
|
+
})
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import { Action } from '@stacksjs/actions/runtime'
|
|
2
|
+
import { upsells } from '@stacksjs/commerce'
|
|
3
|
+
import { refuse } from '@stacksjs/router'
|
|
4
|
+
import { orderForKey } from '../../Storefront/OrderKey'
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* "No thanks" on a post-purchase offer: it is not shown to this order again.
|
|
8
|
+
* Authorised by the order's key.
|
|
9
|
+
*/
|
|
10
|
+
export default new Action({
|
|
11
|
+
name: 'DeclineOrderOfferAction',
|
|
12
|
+
description: 'Turn down a post-purchase offer for an order.',
|
|
13
|
+
method: 'POST',
|
|
14
|
+
next: (result: { order_id: number, key: string }) => `/orders/${result.order_id}?key=${encodeURIComponent(result.key)}`,
|
|
15
|
+
|
|
16
|
+
async handle(request: any) {
|
|
17
|
+
const key = String(request.get('key') ?? '')
|
|
18
|
+
const order = await orderForKey(request.get('order_id'), key)
|
|
19
|
+
if (!order)
|
|
20
|
+
return refuse('We could not find that order.', { status: 404 })
|
|
21
|
+
|
|
22
|
+
const declined = await upsells.declineOffer(Number(order.id), Number(request.get('offer_id')))
|
|
23
|
+
return { ok: true, order_id: Number(order.id), key, declined }
|
|
24
|
+
},
|
|
25
|
+
})
|
|
@@ -1,13 +1,17 @@
|
|
|
1
|
+
import type { DiscountRule } from '@stacksjs/commerce/discounts/engine'
|
|
2
|
+
import type { StorefrontLine } from '../../Storefront/StorefrontPricing'
|
|
3
|
+
import { randomBytes } from 'node:crypto'
|
|
1
4
|
import { randomUUIDv7 } from 'bun'
|
|
2
5
|
import { Action } from '@stacksjs/actions/runtime'
|
|
3
|
-
import { customers } from '@stacksjs/commerce'
|
|
6
|
+
import { customers, discounts, orders } from '@stacksjs/commerce'
|
|
4
7
|
import { config } from '@stacksjs/config'
|
|
5
8
|
import { db } from '@stacksjs/database/runtime'
|
|
6
9
|
import { refuse } from '@stacksjs/router'
|
|
7
10
|
import { sendOrderConfirmation } from '../../Mail/OrderConfirmation'
|
|
8
11
|
import { readCartCookie } from '../../Storefront/CartCookie'
|
|
12
|
+
import { DISCOUNT_CODE_MESSAGES } from '../../Storefront/DiscountCodeMessages'
|
|
9
13
|
import { storefrontCurrency } from '../../Storefront/StorefrontMoney'
|
|
10
|
-
import {
|
|
14
|
+
import { priceStorefront } from '../../Storefront/StorefrontPricing'
|
|
11
15
|
|
|
12
16
|
const CART_COOKIE = 'stacks_cart'
|
|
13
17
|
|
|
@@ -16,20 +20,27 @@ const CART_COOKIE = 'stacks_cart'
|
|
|
16
20
|
*
|
|
17
21
|
* Pulls everything we collected in earlier steps off the cart row
|
|
18
22
|
* (email + shipping_*), creates a Customer if we don't have one for
|
|
19
|
-
* this email yet,
|
|
20
|
-
*
|
|
21
|
-
*
|
|
23
|
+
* this email yet, prices the cart with the store's automatic discounts
|
|
24
|
+
* (the same `priceStorefront` the cart and checkout pages show), and
|
|
25
|
+
* writes the order, its lines and the stock it takes in ONE transaction
|
|
26
|
+
* through `commerce.orders.placeOrder`: a line that cannot be stocked
|
|
27
|
+
* refuses the order instead of overselling, and a double-submitted form
|
|
28
|
+
* returns the order the first submit placed.
|
|
22
29
|
*
|
|
23
|
-
*
|
|
24
|
-
*
|
|
25
|
-
*
|
|
30
|
+
* The confirmation page is opened with the order's unguessable
|
|
31
|
+
* `tracking_token` as `?key=`, so a sequential order id alone shows
|
|
32
|
+
* nobody's name, email or address.
|
|
33
|
+
*
|
|
34
|
+
* No real card is charged — a payment call would slot in between the
|
|
35
|
+
* pricing and the placement. The mock card form on the payment view
|
|
36
|
+
* doesn't actually submit any sensitive data.
|
|
26
37
|
*/
|
|
27
38
|
export default new Action({
|
|
28
39
|
name: 'PlaceOrderAction',
|
|
29
40
|
description: 'Convert the active cart into an Order + OrderItems.',
|
|
30
41
|
method: 'POST',
|
|
31
42
|
// A browser form goes to the order it placed; a script gets its id and totals.
|
|
32
|
-
next: (result: { order_id: number }) => `/orders/${result.order_id}`,
|
|
43
|
+
next: (result: { order_id: number, key: string }) => `/orders/${result.order_id}?key=${encodeURIComponent(result.key)}`,
|
|
33
44
|
|
|
34
45
|
async handle(request: any) {
|
|
35
46
|
const token = readCartCookie(request, CART_COOKIE)
|
|
@@ -39,13 +50,21 @@ export default new Action({
|
|
|
39
50
|
const cart = await (db as any)
|
|
40
51
|
.selectFrom('carts')
|
|
41
52
|
.where('session_token', '=', token)
|
|
42
|
-
.where('status', '=', 'active')
|
|
43
53
|
.selectAll()
|
|
44
54
|
.executeTakeFirst()
|
|
45
55
|
|
|
46
|
-
if (!cart)
|
|
56
|
+
if (!cart || (cart.status !== 'active' && cart.status !== 'converted'))
|
|
47
57
|
return refuse('Your cart is empty.', { status: 400 })
|
|
48
58
|
|
|
59
|
+
// A second submit of a cart that already became an order (a double click,
|
|
60
|
+
// a resubmitted form after a slow response) lands on that order.
|
|
61
|
+
if (cart.status === 'converted') {
|
|
62
|
+
const placed = await orders.findOrderByIdempotencyKey(`storefront-cart-${cart.id}`)
|
|
63
|
+
if (placed?.tracking_token)
|
|
64
|
+
return { ok: true, order_id: Number(placed.id), key: String(placed.tracking_token), total: Number(placed.total_amount) }
|
|
65
|
+
return refuse('Your cart is empty.', { status: 400 })
|
|
66
|
+
}
|
|
67
|
+
|
|
49
68
|
const items = await (db as any)
|
|
50
69
|
.selectFrom('cart_items')
|
|
51
70
|
.where('cart_id', '=', cart.id)
|
|
@@ -58,6 +77,19 @@ export default new Action({
|
|
|
58
77
|
if (!cart.email || !cart.shipping_name || !cart.shipping_address)
|
|
59
78
|
return refuse('Checkout details are incomplete. Go back and fill in your email and shipping address.')
|
|
60
79
|
|
|
80
|
+
// Every cart line has to still be a product we sell.
|
|
81
|
+
const products = new Map<string, any>()
|
|
82
|
+
for (const item of items) {
|
|
83
|
+
const product = await (db as any)
|
|
84
|
+
.selectFrom('products')
|
|
85
|
+
.where('slug', '=', item.product_sku)
|
|
86
|
+
.selectAll()
|
|
87
|
+
.executeTakeFirst()
|
|
88
|
+
if (!product || product.is_available === 0 || product.is_available === false)
|
|
89
|
+
return refuse(`${item.product_name || 'An item in your cart'} is no longer available. Remove it to continue.`)
|
|
90
|
+
products.set(item.product_sku, product)
|
|
91
|
+
}
|
|
92
|
+
|
|
61
93
|
// One customer per email — repeat shoppers reuse the same row so
|
|
62
94
|
// the dashboard's customer total isn't inflated by checkouts.
|
|
63
95
|
let customer = await (db as any)
|
|
@@ -73,75 +105,94 @@ export default new Action({
|
|
|
73
105
|
|
|
74
106
|
// Integer minor units of the cart's currency, like every amount here.
|
|
75
107
|
const currency = storefrontCurrency(cart.currency)
|
|
76
|
-
const
|
|
77
|
-
|
|
108
|
+
const lines: StorefrontLine[] = items.map((item: any) => {
|
|
109
|
+
const product = products.get(item.product_sku)
|
|
110
|
+
return {
|
|
111
|
+
id: Number(item.id),
|
|
112
|
+
productId: Number(product.id),
|
|
113
|
+
categoryId: product.category_id == null ? null : Number(product.category_id),
|
|
114
|
+
quantity: Number(item.quantity),
|
|
115
|
+
unitPrice: Math.round(Number(item.unit_price)),
|
|
116
|
+
}
|
|
117
|
+
})
|
|
118
|
+
|
|
119
|
+
const codes: string[] = cart.discount_code ? [String(cart.discount_code)] : []
|
|
120
|
+
let rules: DiscountRule[] = []
|
|
121
|
+
try {
|
|
122
|
+
rules = await discounts.fetchRules({ codes })
|
|
123
|
+
}
|
|
124
|
+
catch (error) {
|
|
125
|
+
// An app that has not migrated the discounts table yet sells at full price.
|
|
126
|
+
console.warn(`[PlaceOrderAction] automatic discounts unavailable: ${error instanceof Error ? error.message : String(error)}`)
|
|
127
|
+
}
|
|
128
|
+
const priced = priceStorefront(lines, rules, currency, new Date(), codes)
|
|
129
|
+
|
|
130
|
+
// The code was good when it was applied; it can have expired or run out
|
|
131
|
+
// since. Say so and take it off, rather than charge a price the shopper
|
|
132
|
+
// was not shown.
|
|
133
|
+
const rejected = priced.result.rejectedCodes[0]
|
|
134
|
+
if (rejected) {
|
|
135
|
+
await (db as any).updateTable('carts').set({ discount_code: null }).where('id', '=', cart.id).execute()
|
|
136
|
+
return refuse(`${DISCOUNT_CODE_MESSAGES[rejected.reason]} We took it off your cart; check the new total and place your order again.`, { status: 409 })
|
|
137
|
+
}
|
|
138
|
+
const discountTitle = priced.result.applied.filter(a => a.class !== 'shipping').map(a => a.title).join(', ')
|
|
78
139
|
|
|
79
140
|
const fullAddress = [
|
|
80
141
|
cart.shipping_address,
|
|
81
142
|
[cart.shipping_city, cart.shipping_state, cart.shipping_zip].filter(Boolean).join(', '),
|
|
82
143
|
].filter(Boolean).join('\n')
|
|
83
144
|
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
145
|
+
const trackingToken = randomBytes(24).toString('base64url')
|
|
146
|
+
|
|
147
|
+
// Stock is taken only where it is tracked; NULL means "not counted".
|
|
148
|
+
const inventory = items
|
|
149
|
+
.map((item: any) => ({ product: products.get(item.product_sku), quantity: Number(item.quantity) }))
|
|
150
|
+
.filter(({ product }: { product: any }) => product.inventory_count != null)
|
|
151
|
+
.map(({ product, quantity }: { product: any, quantity: number }) => ({ id: Number(product.id), delta: -quantity }))
|
|
152
|
+
|
|
153
|
+
const placed = await orders.placeOrder({
|
|
154
|
+
order: {
|
|
87
155
|
customer_id: customer.id,
|
|
88
|
-
status: '
|
|
156
|
+
status: 'PROCESSING',
|
|
89
157
|
order_type: 'shipping',
|
|
90
|
-
total_amount: total,
|
|
158
|
+
total_amount: priced.total,
|
|
159
|
+
discount_amount: priced.discount,
|
|
91
160
|
currency,
|
|
92
|
-
delivery_fee: shipping,
|
|
161
|
+
delivery_fee: priced.shipping,
|
|
93
162
|
delivery_address: fullAddress,
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
.
|
|
103
|
-
|
|
104
|
-
.executeTakeFirst()
|
|
105
|
-
|
|
106
|
-
// Map cart_items → order_items, resolving product_id by SKU.
|
|
107
|
-
for (const item of items) {
|
|
108
|
-
const product = await (db as any)
|
|
109
|
-
.selectFrom('products')
|
|
110
|
-
.where('slug', '=', item.product_sku)
|
|
111
|
-
.selectAll()
|
|
112
|
-
.executeTakeFirst()
|
|
163
|
+
tracking_token: trackingToken,
|
|
164
|
+
} as never,
|
|
165
|
+
items: items.map((item: any) => ({
|
|
166
|
+
productId: Number(products.get(item.product_sku).id),
|
|
167
|
+
quantity: Number(item.quantity),
|
|
168
|
+
price: Math.round(Number(item.unit_price)),
|
|
169
|
+
})),
|
|
170
|
+
inventory: mergeInventory(inventory),
|
|
171
|
+
idempotencyKey: `storefront-cart-${cart.id}`,
|
|
172
|
+
})
|
|
113
173
|
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
.
|
|
117
|
-
|
|
118
|
-
product_id: product?.id ?? null,
|
|
119
|
-
quantity: Number(item.quantity),
|
|
120
|
-
price: Number(item.unit_price),
|
|
121
|
-
})
|
|
122
|
-
.execute()
|
|
174
|
+
if (!placed.ok) {
|
|
175
|
+
if (placed.reason === 'out-of-stock')
|
|
176
|
+
return refuse('Sorry, part of your order just sold out. Check your cart and try again.', { status: 409 })
|
|
177
|
+
throw placed.error instanceof Error ? placed.error : new Error(`Order placement failed: ${placed.reason}`)
|
|
123
178
|
}
|
|
124
179
|
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
180
|
+
const order = placed.order as Record<string, any>
|
|
181
|
+
const key = String(order.tracking_token || trackingToken)
|
|
182
|
+
|
|
183
|
+
// Count each discount's use. The order stands either way: the shopper was
|
|
184
|
+
// shown and charged this price, so a limit reached by a concurrent
|
|
185
|
+
// checkout is logged for the merchant rather than taken back.
|
|
186
|
+
if (priced.result.applied.length > 0) {
|
|
129
187
|
try {
|
|
130
|
-
const
|
|
131
|
-
.
|
|
132
|
-
|
|
133
|
-
.selectAll()
|
|
134
|
-
.executeTakeFirst()
|
|
135
|
-
if (product) {
|
|
136
|
-
const next = Math.max(0, Number(product.inventory_count || 0) - Number(item.quantity))
|
|
137
|
-
await (db as any)
|
|
138
|
-
.updateTable('products')
|
|
139
|
-
.set({ inventory_count: next })
|
|
140
|
-
.where('id', '=', product.id)
|
|
141
|
-
.execute()
|
|
188
|
+
for (const outcome of await discounts.redeemApplied(priced.result.applied)) {
|
|
189
|
+
if (!outcome.ok && outcome.reason !== 'not-stored')
|
|
190
|
+
console.warn(`[PlaceOrderAction] order #${order.id} used discount ${String(outcome.ruleId)} past its limit (${outcome.reason}).`)
|
|
142
191
|
}
|
|
143
192
|
}
|
|
144
|
-
catch {
|
|
193
|
+
catch (error) {
|
|
194
|
+
console.warn(`[PlaceOrderAction] could not count discount uses for order #${order.id}: ${error instanceof Error ? error.message : String(error)}`)
|
|
195
|
+
}
|
|
145
196
|
}
|
|
146
197
|
|
|
147
198
|
await (db as any)
|
|
@@ -171,11 +222,13 @@ export default new Action({
|
|
|
171
222
|
lineTotal: Number(row.total_price || 0),
|
|
172
223
|
})),
|
|
173
224
|
currency,
|
|
174
|
-
subtotal,
|
|
175
|
-
|
|
176
|
-
|
|
225
|
+
subtotal: priced.subtotal,
|
|
226
|
+
discount: priced.discount,
|
|
227
|
+
discountTitle,
|
|
228
|
+
shipping: priced.shipping,
|
|
229
|
+
total: priced.total,
|
|
177
230
|
shippingAddress: fullAddress,
|
|
178
|
-
orderUrl: `${baseUrl}/orders/${order.id}`,
|
|
231
|
+
orderUrl: `${baseUrl}/orders/${order.id}?key=${encodeURIComponent(key)}`,
|
|
179
232
|
}).catch((err: unknown) => {
|
|
180
233
|
const message = err instanceof Error ? err.message : String(err)
|
|
181
234
|
console.error(`[PlaceOrderAction] order receipt email failed for order #${order.id}:`, message)
|
|
@@ -183,10 +236,20 @@ export default new Action({
|
|
|
183
236
|
|
|
184
237
|
return {
|
|
185
238
|
ok: true,
|
|
186
|
-
order_id: order.id,
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
239
|
+
order_id: Number(order.id),
|
|
240
|
+
key,
|
|
241
|
+
total: priced.total,
|
|
242
|
+
subtotal: priced.subtotal,
|
|
243
|
+
discount: priced.discount,
|
|
244
|
+
shipping: priced.shipping,
|
|
190
245
|
}
|
|
191
246
|
},
|
|
192
247
|
})
|
|
248
|
+
|
|
249
|
+
/** One stock movement per product, so two lines of one product are checked together. */
|
|
250
|
+
function mergeInventory(moves: Array<{ id: number, delta: number }>): Array<{ id: number, delta: number }> {
|
|
251
|
+
const merged = new Map<number, number>()
|
|
252
|
+
for (const { id, delta } of moves)
|
|
253
|
+
merged.set(id, (merged.get(id) ?? 0) + delta)
|
|
254
|
+
return [...merged].map(([id, delta]) => ({ id, delta }))
|
|
255
|
+
}
|