@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
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type {
|
|
1
|
+
import type { GateUser } from '@stacksjs/auth'
|
|
2
2
|
import { BasePolicy } from '@stacksjs/auth'
|
|
3
3
|
|
|
4
4
|
/**
|
|
@@ -33,7 +33,7 @@ export default class PostPolicy extends BasePolicy<Post> {
|
|
|
33
33
|
* Run before any other checks.
|
|
34
34
|
* Return true to allow, false to deny, null to continue.
|
|
35
35
|
*/
|
|
36
|
-
before(user:
|
|
36
|
+
before(user: GateUser | null, ability: string): boolean | null {
|
|
37
37
|
// Example: Admins can do anything with posts
|
|
38
38
|
// if (user?.role === 'admin') {
|
|
39
39
|
// return true
|
|
@@ -44,7 +44,7 @@ export default class PostPolicy extends BasePolicy<Post> {
|
|
|
44
44
|
/**
|
|
45
45
|
* Determine if the user can view any posts.
|
|
46
46
|
*/
|
|
47
|
-
viewAny(user:
|
|
47
|
+
viewAny(user: GateUser | null): boolean {
|
|
48
48
|
// Anyone can view the posts list
|
|
49
49
|
return true
|
|
50
50
|
}
|
|
@@ -52,7 +52,7 @@ export default class PostPolicy extends BasePolicy<Post> {
|
|
|
52
52
|
/**
|
|
53
53
|
* Determine if the user can view a specific post.
|
|
54
54
|
*/
|
|
55
|
-
view(user:
|
|
55
|
+
view(user: GateUser | null, post: Post): boolean {
|
|
56
56
|
// Published posts are visible to everyone
|
|
57
57
|
if (post.published) {
|
|
58
58
|
return true
|
|
@@ -65,7 +65,7 @@ export default class PostPolicy extends BasePolicy<Post> {
|
|
|
65
65
|
/**
|
|
66
66
|
* Determine if the user can create posts.
|
|
67
67
|
*/
|
|
68
|
-
create(user:
|
|
68
|
+
create(user: GateUser | null): boolean {
|
|
69
69
|
// Must be logged in to create posts
|
|
70
70
|
return user !== null
|
|
71
71
|
}
|
|
@@ -73,7 +73,7 @@ export default class PostPolicy extends BasePolicy<Post> {
|
|
|
73
73
|
/**
|
|
74
74
|
* Determine if the user can update the post.
|
|
75
75
|
*/
|
|
76
|
-
update(user:
|
|
76
|
+
update(user: GateUser | null, post: Post): boolean {
|
|
77
77
|
// Only the author can update their post
|
|
78
78
|
return user?.id === post.user_id
|
|
79
79
|
}
|
|
@@ -81,7 +81,7 @@ export default class PostPolicy extends BasePolicy<Post> {
|
|
|
81
81
|
/**
|
|
82
82
|
* Determine if the user can delete the post.
|
|
83
83
|
*/
|
|
84
|
-
delete(user:
|
|
84
|
+
delete(user: GateUser | null, post: Post): boolean {
|
|
85
85
|
// Only the author can delete their post
|
|
86
86
|
return user?.id === post.user_id
|
|
87
87
|
}
|
|
@@ -89,14 +89,14 @@ export default class PostPolicy extends BasePolicy<Post> {
|
|
|
89
89
|
/**
|
|
90
90
|
* Determine if the user can restore a soft-deleted post.
|
|
91
91
|
*/
|
|
92
|
-
restore(user:
|
|
92
|
+
restore(user: GateUser | null, post: Post): boolean {
|
|
93
93
|
return user?.id === post.user_id
|
|
94
94
|
}
|
|
95
95
|
|
|
96
96
|
/**
|
|
97
97
|
* Determine if the user can permanently delete the post.
|
|
98
98
|
*/
|
|
99
|
-
forceDelete(user:
|
|
99
|
+
forceDelete(user: GateUser | null, post: Post): boolean {
|
|
100
100
|
// Only allow force delete if you're the author
|
|
101
101
|
return user?.id === post.user_id
|
|
102
102
|
}
|
|
@@ -104,7 +104,7 @@ export default class PostPolicy extends BasePolicy<Post> {
|
|
|
104
104
|
/**
|
|
105
105
|
* Custom ability: Can the user publish the post?
|
|
106
106
|
*/
|
|
107
|
-
publish(user:
|
|
107
|
+
publish(user: GateUser | null, post: Post): boolean {
|
|
108
108
|
return user?.id === post.user_id
|
|
109
109
|
}
|
|
110
110
|
|
|
@@ -112,7 +112,7 @@ export default class PostPolicy extends BasePolicy<Post> {
|
|
|
112
112
|
* Custom ability: Can the user feature the post?
|
|
113
113
|
* Returns a detailed response.
|
|
114
114
|
*/
|
|
115
|
-
feature(user:
|
|
115
|
+
feature(user: GateUser | null, post: Post) {
|
|
116
116
|
if (!user) {
|
|
117
117
|
return this.deny('You must be logged in to feature posts.')
|
|
118
118
|
}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import type { RejectedCodeReason } from '@stacksjs/commerce/discounts/engine'
|
|
2
|
+
|
|
3
|
+
/** Why a discount code did nothing, in the shopper's words. */
|
|
4
|
+
export const DISCOUNT_CODE_MESSAGES: Record<RejectedCodeReason, string> = {
|
|
5
|
+
'not-found': 'That discount code does not exist.',
|
|
6
|
+
'inactive': 'That discount code is not active yet.',
|
|
7
|
+
'expired': 'That discount code has expired.',
|
|
8
|
+
'exhausted': 'That discount code has been used up.',
|
|
9
|
+
'requirements-not-met': 'Your cart does not meet that code\'s requirements yet.',
|
|
10
|
+
'no-eligible-items': 'That discount code does not apply to anything in your cart.',
|
|
11
|
+
'not-combinable': 'That discount code cannot be combined with the discount already applied.',
|
|
12
|
+
}
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import { timingSafeEqual } from 'node:crypto'
|
|
2
|
+
import { db } from '@stacksjs/database/runtime'
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* The order a confirmation link opens, when its `key` is right.
|
|
6
|
+
*
|
|
7
|
+
* A storefront order is opened by a shopper who is often not signed in, from
|
|
8
|
+
* a redirect or an emailed link, so the page and the actions it posts to
|
|
9
|
+
* authorise on possession of the order's unguessable `tracking_token`. Order
|
|
10
|
+
* ids are sequential: without the key, anyone could walk them and read names,
|
|
11
|
+
* emails and addresses, or add to someone else's order.
|
|
12
|
+
*/
|
|
13
|
+
export async function orderForKey(orderId: unknown, key: unknown): Promise<Record<string, any> | null> {
|
|
14
|
+
const id = Number(orderId)
|
|
15
|
+
const given = String(key ?? '')
|
|
16
|
+
if (!Number.isSafeInteger(id) || id <= 0 || given.length < 16)
|
|
17
|
+
return null
|
|
18
|
+
const order = await (db as any).selectFrom('orders').where('id', '=', id).selectAll().executeTakeFirst()
|
|
19
|
+
if (!order?.tracking_token)
|
|
20
|
+
return null
|
|
21
|
+
return keysMatch(String(order.tracking_token), given) ? order : null
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/** Compare a stored key with a given one in constant time. */
|
|
25
|
+
export function keysMatch(stored: string, given: string): boolean {
|
|
26
|
+
const a = Buffer.from(stored)
|
|
27
|
+
const b = Buffer.from(given)
|
|
28
|
+
return a.length === b.length && timingSafeEqual(a, b)
|
|
29
|
+
}
|
|
@@ -0,0 +1,211 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* What a storefront cart costs once the store's automatic discounts are
|
|
3
|
+
* applied: "buy 4, get 4 free", "5+ for 20% off", free shipping over a
|
|
4
|
+
* threshold.
|
|
5
|
+
*
|
|
6
|
+
* One function prices for every page and for the checkout, so the cart,
|
|
7
|
+
* each checkout step and the order PlaceOrderAction writes all agree. The
|
|
8
|
+
* pages read SQLite synchronously (see `StorefrontDatabase.ts`), and the
|
|
9
|
+
* action reads through the framework's database; both hand their rows to
|
|
10
|
+
* {@link priceStorefront}, which is pure.
|
|
11
|
+
*
|
|
12
|
+
* Amounts are integer minor units of the cart's currency.
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
import type { DiscountResult, DiscountRule } from '@stacksjs/commerce/discounts/engine'
|
|
16
|
+
import type { CouponRow, DiscountRow } from '@stacksjs/commerce/discounts/rules'
|
|
17
|
+
import type { Database } from 'bun:sqlite'
|
|
18
|
+
import { applyDiscounts } from '@stacksjs/commerce/discounts/engine'
|
|
19
|
+
import { ruleFromCoupon, ruleFromDiscount } from '@stacksjs/commerce/discounts/rules'
|
|
20
|
+
import { freeShippingThreshold, shippingFor } from '../Actions/Storefront/_shipping'
|
|
21
|
+
import { storefrontMoney } from './StorefrontMoney'
|
|
22
|
+
|
|
23
|
+
export interface StorefrontLine {
|
|
24
|
+
/** The cart item's id. */
|
|
25
|
+
id: number
|
|
26
|
+
productId: number
|
|
27
|
+
categoryId?: number | null
|
|
28
|
+
quantity: number
|
|
29
|
+
unitPrice: number
|
|
30
|
+
compareAtPrice?: number | null
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export interface StorefrontPrice {
|
|
34
|
+
result: DiscountResult
|
|
35
|
+
subtotal: number
|
|
36
|
+
discount: number
|
|
37
|
+
/** Shipping after any free-shipping discount. */
|
|
38
|
+
shipping: number
|
|
39
|
+
total: number
|
|
40
|
+
/** Minor units more needed for the flat free-shipping rule, or 0. */
|
|
41
|
+
remainingForFree: number
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* Price lines against rules. Shipping follows the storefront's rule on the
|
|
46
|
+
* subtotal after discounts, and a free-shipping discount can then waive it.
|
|
47
|
+
*/
|
|
48
|
+
export function priceStorefront(lines: readonly StorefrontLine[], rules: readonly DiscountRule[], currency: string, now: Date = new Date(), codes: readonly string[] = []): StorefrontPrice {
|
|
49
|
+
const first = applyDiscounts({ lines, rules, codes, now })
|
|
50
|
+
const baseShipping = shippingFor(first.discountedSubtotal, currency)
|
|
51
|
+
const result = applyDiscounts({ lines, rules, codes, shipping: baseShipping, now })
|
|
52
|
+
return {
|
|
53
|
+
result,
|
|
54
|
+
subtotal: result.subtotal,
|
|
55
|
+
discount: result.discount,
|
|
56
|
+
shipping: result.shippingAfterDiscount,
|
|
57
|
+
total: result.total,
|
|
58
|
+
remainingForFree: baseShipping > 0 && result.shippingAfterDiscount > 0
|
|
59
|
+
? Math.max(0, freeShippingThreshold(currency) - result.discountedSubtotal)
|
|
60
|
+
: 0,
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/**
|
|
65
|
+
* The store's automatic discounts, plus the discounts and coupons whose codes
|
|
66
|
+
* were entered, read from SQLite for a server-rendered page. A database
|
|
67
|
+
* without the `discounts` table (not migrated since it was added) has none,
|
|
68
|
+
* rather than an empty cart.
|
|
69
|
+
*/
|
|
70
|
+
export function readDiscountRules(db: Database, codes: readonly string[] = []): DiscountRule[] {
|
|
71
|
+
const wanted = new Set(codes.map(code => code.trim().toUpperCase()).filter(Boolean))
|
|
72
|
+
const rules: DiscountRule[] = []
|
|
73
|
+
const keep = (build: () => DiscountRule) => {
|
|
74
|
+
try {
|
|
75
|
+
rules.push(build())
|
|
76
|
+
}
|
|
77
|
+
catch {
|
|
78
|
+
// A row the engine cannot read is skipped, never the whole cart.
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
try {
|
|
83
|
+
for (const row of db.query<DiscountRow, []>(`SELECT * FROM discounts`).all()) {
|
|
84
|
+
if (!row.code || wanted.has(row.code.toUpperCase()))
|
|
85
|
+
keep(() => ruleFromDiscount(row))
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
catch {
|
|
89
|
+
// No discounts table yet.
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
if (wanted.size) {
|
|
93
|
+
try {
|
|
94
|
+
for (const row of db.query<CouponRow, []>(`SELECT * FROM coupons`).all()) {
|
|
95
|
+
if (row.code && wanted.has(row.code.toUpperCase()) && !rules.some(r => r.code?.toUpperCase() === row.code.toUpperCase()))
|
|
96
|
+
keep(() => ruleFromCoupon(row))
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
catch {
|
|
100
|
+
// No coupons table.
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
return rules
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/** The store's automatic discounts only. */
|
|
108
|
+
export function readAutomaticDiscounts(db: Database): DiscountRule[] {
|
|
109
|
+
return readDiscountRules(db)
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/** The code a cart carries, or none (also when the column is not migrated yet). */
|
|
113
|
+
export function readCartCode(db: Database, cartId: number): string[] {
|
|
114
|
+
try {
|
|
115
|
+
const row = db.query<{ discount_code: string | null }, [number]>(`SELECT discount_code FROM carts WHERE id = ?1`).get(cartId)
|
|
116
|
+
return row?.discount_code ? [row.discount_code] : []
|
|
117
|
+
}
|
|
118
|
+
catch {
|
|
119
|
+
return []
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
interface CartLineRow {
|
|
124
|
+
id: number
|
|
125
|
+
quantity: number | string
|
|
126
|
+
unit_price: number | string
|
|
127
|
+
product_id: number | null
|
|
128
|
+
category_id: number | null
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/** A cart's lines, joined to their products, for {@link priceStorefront}. */
|
|
132
|
+
export function readCartLines(db: Database, cartId: number): StorefrontLine[] {
|
|
133
|
+
const query = (category: string) => db.query<CartLineRow, [number]>(`
|
|
134
|
+
SELECT ci.id, ci.quantity, ci.unit_price, p.id AS product_id, ${category} AS category_id
|
|
135
|
+
FROM cart_items ci
|
|
136
|
+
LEFT JOIN products p ON p.slug = ci.product_sku
|
|
137
|
+
WHERE ci.cart_id = ?1
|
|
138
|
+
ORDER BY ci.id ASC
|
|
139
|
+
`).all(cartId)
|
|
140
|
+
|
|
141
|
+
let rows: CartLineRow[]
|
|
142
|
+
try {
|
|
143
|
+
rows = query('p.category_id')
|
|
144
|
+
}
|
|
145
|
+
catch {
|
|
146
|
+
// An older products table without categories still prices; category
|
|
147
|
+
// targeted discounts just do not match it.
|
|
148
|
+
rows = query('NULL')
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
return rows
|
|
152
|
+
.filter(row => row.product_id != null && Number(row.quantity) > 0)
|
|
153
|
+
.map(row => ({
|
|
154
|
+
id: Number(row.id),
|
|
155
|
+
productId: Number(row.product_id),
|
|
156
|
+
categoryId: row.category_id == null ? null : Number(row.category_id),
|
|
157
|
+
quantity: Number(row.quantity),
|
|
158
|
+
unitPrice: Math.round(Number(row.unit_price)),
|
|
159
|
+
}))
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
export interface StorefrontPricedSummary {
|
|
163
|
+
subtotal: number
|
|
164
|
+
discount: number
|
|
165
|
+
shipping: number
|
|
166
|
+
total: number
|
|
167
|
+
subtotalLabel: string
|
|
168
|
+
shippingLabel: string
|
|
169
|
+
totalLabel: string
|
|
170
|
+
freeShippingNote: string
|
|
171
|
+
/** "-$10.00", or empty when nothing was taken off. */
|
|
172
|
+
discountLabel: string
|
|
173
|
+
/** The discounts applied, joined: "BUY 4, GET 4 FREE". */
|
|
174
|
+
discountTitle: string
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
/**
|
|
178
|
+
* A cart's priced totals as the order summary shows them, or null when they
|
|
179
|
+
* cannot be worked out, so the page falls back to its undiscounted summary
|
|
180
|
+
* rather than to an empty cart.
|
|
181
|
+
*/
|
|
182
|
+
export function storefrontCartSummary(db: Database, cartId: number, currency: string): StorefrontPricedSummary | null {
|
|
183
|
+
try {
|
|
184
|
+
const codes = readCartCode(db, cartId)
|
|
185
|
+
const priced = priceStorefront(readCartLines(db, cartId), readDiscountRules(db, codes), currency, new Date(), codes)
|
|
186
|
+
return pricedSummary(priced, currency)
|
|
187
|
+
}
|
|
188
|
+
catch (error) {
|
|
189
|
+
console.warn(`[storefront] cart ${cartId} priced without discounts: ${error instanceof Error ? error.message : String(error)}`)
|
|
190
|
+
return null
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
/** Labels for a priced cart. */
|
|
195
|
+
export function pricedSummary(priced: StorefrontPrice, currency: string): StorefrontPricedSummary {
|
|
196
|
+
const merchandise = priced.result.applied.filter(a => a.class !== 'shipping')
|
|
197
|
+
return {
|
|
198
|
+
subtotal: priced.subtotal,
|
|
199
|
+
discount: priced.discount,
|
|
200
|
+
shipping: priced.shipping,
|
|
201
|
+
total: priced.total,
|
|
202
|
+
subtotalLabel: storefrontMoney(priced.subtotal, currency),
|
|
203
|
+
shippingLabel: priced.shipping === 0 ? 'Free' : storefrontMoney(priced.shipping, currency),
|
|
204
|
+
totalLabel: storefrontMoney(priced.total, currency),
|
|
205
|
+
freeShippingNote: priced.remainingForFree > 0
|
|
206
|
+
? `Add ${storefrontMoney(priced.remainingForFree, currency)} more for free shipping.`
|
|
207
|
+
: '',
|
|
208
|
+
discountLabel: priced.discount > 0 ? `-${storefrontMoney(priced.discount, currency)}` : '',
|
|
209
|
+
discountTitle: merchandise.map(a => a.title).join(', '),
|
|
210
|
+
}
|
|
211
|
+
}
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
import type { upsells } from '@stacksjs/commerce'
|
|
2
|
+
import { db } from '@stacksjs/database/runtime'
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* How the storefront takes the money for a post-purchase offer the shopper
|
|
6
|
+
* accepted. Override this file at `app/Storefront/UpsellCharge.ts` to charge
|
|
7
|
+
* your own way (a stored mandate, a provider of your own).
|
|
8
|
+
*
|
|
9
|
+
* The default follows how the order itself was paid:
|
|
10
|
+
*
|
|
11
|
+
* - The order has a payment a provider took (a `payments` row with a
|
|
12
|
+
* `transaction_id` and `payment_provider`): the addition is charged
|
|
13
|
+
* off-session to the customer's default saved payment method through that
|
|
14
|
+
* provider's driver, with no second checkout.
|
|
15
|
+
* - It has none, as with the default storefront's mock checkout: the addition
|
|
16
|
+
* is collected the same way the order will be, and no payment is recorded.
|
|
17
|
+
*/
|
|
18
|
+
export async function storefrontUpsellCharger(order: Record<string, any>): Promise<upsells.UpsellCharger> {
|
|
19
|
+
const payment = await (db as any)
|
|
20
|
+
.selectFrom('payments')
|
|
21
|
+
.where('order_id', '=', order.id)
|
|
22
|
+
.where('transaction_id', 'is not', null)
|
|
23
|
+
.where('payment_provider', 'is not', null)
|
|
24
|
+
.orderBy('id', 'asc')
|
|
25
|
+
.selectAll()
|
|
26
|
+
.executeTakeFirst()
|
|
27
|
+
|
|
28
|
+
if (!payment)
|
|
29
|
+
return 'collect-later'
|
|
30
|
+
|
|
31
|
+
const { paymentDriver } = await import('@stacksjs/payments')
|
|
32
|
+
const { upsells: { chargeDefaultMethod } } = await import('@stacksjs/commerce')
|
|
33
|
+
const customer = order.customer_id
|
|
34
|
+
? await (db as any).selectFrom('customers').where('id', '=', order.customer_id).selectAll().executeTakeFirst()
|
|
35
|
+
: null
|
|
36
|
+
const payer = {
|
|
37
|
+
id: customer?.user_id ?? customer?.id ?? order.customer_id,
|
|
38
|
+
email: customer?.email ?? null,
|
|
39
|
+
name: customer?.name ?? null,
|
|
40
|
+
stripe_id: customer?.stripe_id ?? null,
|
|
41
|
+
}
|
|
42
|
+
return chargeDefaultMethod(paymentDriver(String(payment.payment_provider)), payer)
|
|
43
|
+
}
|
package/ide/vscode/package.json
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
"publisher": "Stacks",
|
|
3
3
|
"name": "vscode-stacks",
|
|
4
4
|
"displayName": "Stacks",
|
|
5
|
-
"version": "0.75.
|
|
5
|
+
"version": "0.75.621",
|
|
6
6
|
"description": "Stacks, built into VS Code: stx templates, pickier linting and formatting, encrypted env files, the dev server preview and every buddy command. No other extensions required.",
|
|
7
7
|
"license": "MIT",
|
|
8
8
|
"funding": "https://github.com/sponsors/chrisbbreuer",
|
package/package.json
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
"name": "@stacksjs/defaults",
|
|
3
3
|
"type": "module",
|
|
4
4
|
"sideEffects": false,
|
|
5
|
-
"version": "0.75.
|
|
5
|
+
"version": "0.75.621",
|
|
6
6
|
"repository": {
|
|
7
7
|
"type": "git",
|
|
8
8
|
"url": "git+https://github.com/stacksjs/stacks.git",
|
|
@@ -45,14 +45,14 @@
|
|
|
45
45
|
"dependencies": {
|
|
46
46
|
"@iconify-json/f7": "^1.2.2",
|
|
47
47
|
"@iconify-json/hugeicons": "^1.2.35",
|
|
48
|
-
"@stacksjs/mobile": "0.75.
|
|
49
|
-
"@stacksjs/sanitizer": "^0.2.
|
|
50
|
-
"@stacksjs/stx": "^0.2.
|
|
51
|
-
"@stacksjs/strings": "0.75.
|
|
48
|
+
"@stacksjs/mobile": "0.75.621",
|
|
49
|
+
"@stacksjs/sanitizer": "^0.2.907",
|
|
50
|
+
"@stacksjs/stx": "^0.2.907",
|
|
51
|
+
"@stacksjs/strings": "0.75.621",
|
|
52
52
|
"@xterm/addon-fit": "^0.11.0",
|
|
53
53
|
"@xterm/xterm": "^6.0.0",
|
|
54
54
|
"ts-qr-codes": "^0.1.8",
|
|
55
|
-
"@stacksjs/support": "0.75.
|
|
56
|
-
"@stacksjs/browser": "0.75.
|
|
55
|
+
"@stacksjs/support": "0.75.621",
|
|
56
|
+
"@stacksjs/browser": "0.75.621"
|
|
57
57
|
}
|
|
58
58
|
}
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
<script client>
|
|
2
|
+
import type { DiscountSummary } from '../../../../app/Actions/Dashboard/Commerce/discount-records'
|
|
3
|
+
|
|
4
|
+
/** Counted by the server over every discount, against the current time. */
|
|
5
|
+
const summary = useReactiveProp<DiscountSummary>('summary', {
|
|
6
|
+
total: 0,
|
|
7
|
+
automatic: 0,
|
|
8
|
+
code: 0,
|
|
9
|
+
active: 0,
|
|
10
|
+
scheduled: 0,
|
|
11
|
+
expired: 0,
|
|
12
|
+
exhausted: 0,
|
|
13
|
+
disabled: 0,
|
|
14
|
+
redemptions: 0,
|
|
15
|
+
byType: { percentage: 0, fixed_amount: 0, buy_x_get_y: 0, volume: 0, free_shipping: 0 },
|
|
16
|
+
mostUsed: [],
|
|
17
|
+
})
|
|
18
|
+
|
|
19
|
+
function states(): Array<{ label: string, count: number, color: string }> {
|
|
20
|
+
return [
|
|
21
|
+
{ label: 'Active', count: summary().active, color: 'bg-emerald-500' },
|
|
22
|
+
{ label: 'Scheduled', count: summary().scheduled, color: 'bg-blue-500' },
|
|
23
|
+
{ label: 'Used up', count: summary().exhausted, color: 'bg-amber-500' },
|
|
24
|
+
{ label: 'Expired', count: summary().expired, color: 'bg-gray-400' },
|
|
25
|
+
{ label: 'Disabled', count: summary().disabled, color: 'bg-gray-300 dark:bg-neutral-600' },
|
|
26
|
+
]
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
function width(count: number): string {
|
|
30
|
+
return `${summary().total ? Math.round((count / summary().total) * 100) : 0}%`
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
function types(): Array<{ label: string, count: number }> {
|
|
34
|
+
const byType = summary().byType
|
|
35
|
+
return [
|
|
36
|
+
{ label: 'Percentage', count: byType.percentage },
|
|
37
|
+
{ label: 'Amount off', count: byType.fixed_amount },
|
|
38
|
+
{ label: 'Buy X get Y', count: byType.buy_x_get_y },
|
|
39
|
+
{ label: 'Volume tiers', count: byType.volume },
|
|
40
|
+
{ label: 'Free shipping', count: byType.free_shipping },
|
|
41
|
+
]
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
function mostUsed(): DiscountSummary['mostUsed'] {
|
|
45
|
+
return summary().mostUsed ?? []
|
|
46
|
+
}
|
|
47
|
+
</script>
|
|
48
|
+
|
|
49
|
+
<section aria-label="Discount breakdowns" class="grid gap-3 grid-cols-1 lg:grid-cols-3">
|
|
50
|
+
<article class="p-4 bg-white dark:bg-neutral-800 border border-gray-200 rounded-lg dark:border-neutral-700">
|
|
51
|
+
<h2 class="font-semibold text-gray-900 text-sm dark:text-white">Right now</h2>
|
|
52
|
+
<div class="mt-4 space-y-3">
|
|
53
|
+
<div :for="item in states()" :key="item.label">
|
|
54
|
+
<div class="flex justify-between text-xs"><span class="text-gray-500 dark:text-neutral-400">{{ item.label }}</span><span class="font-mono text-gray-700 dark:text-neutral-200">{{ item.count }}</span></div>
|
|
55
|
+
<div class="mt-1 h-1.5 bg-gray-100 dark:bg-neutral-700 rounded-full"><div :class="'h-full rounded-full ' + item.color" :style="'width: ' + width(item.count)"></div></div>
|
|
56
|
+
</div>
|
|
57
|
+
</div>
|
|
58
|
+
</article>
|
|
59
|
+
<article class="p-4 bg-white dark:bg-neutral-800 border border-gray-200 rounded-lg dark:border-neutral-700">
|
|
60
|
+
<h2 class="font-semibold text-gray-900 text-sm dark:text-white">Types</h2>
|
|
61
|
+
<dl class="mt-3 divide-gray-100 divide-y dark:divide-neutral-700">
|
|
62
|
+
<div :for="item in types()" :key="item.label" class="flex items-center justify-between py-2"><dt class="text-gray-500 text-sm dark:text-neutral-400">{{ item.label }}</dt><dd class="font-mono text-gray-900 text-sm dark:text-white">{{ item.count }}</dd></div>
|
|
63
|
+
</dl>
|
|
64
|
+
</article>
|
|
65
|
+
<article class="p-4 bg-white dark:bg-neutral-800 border border-gray-200 rounded-lg dark:border-neutral-700">
|
|
66
|
+
<h2 class="font-semibold text-gray-900 text-sm dark:text-white">Most used</h2>
|
|
67
|
+
<p :if="mostUsed().length === 0" class="mt-4 text-gray-500 text-sm dark:text-neutral-400">No discount has been used yet.</p>
|
|
68
|
+
<ol :else class="mt-3 divide-gray-100 divide-y dark:divide-neutral-700">
|
|
69
|
+
<li :for="entry in mostUsed()" :key="entry.id" class="flex items-center justify-between py-2"><span class="text-gray-600 text-sm truncate dark:text-neutral-300">{{ entry.title }}</span><span class="ml-3 font-mono text-gray-900 text-sm dark:text-white">{{ entry.usageCount.toLocaleString() }}</span></li>
|
|
70
|
+
</ol>
|
|
71
|
+
</article>
|
|
72
|
+
</section>
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
<script client>
|
|
2
|
+
import type { DiscountRecord } from '../../../../app/Actions/Dashboard/Commerce/discount-records'
|
|
3
|
+
|
|
4
|
+
const open = useReactiveProp('open', false)
|
|
5
|
+
const record = useReactiveProp('record', null as DiscountRecord | null)
|
|
6
|
+
const busy = useReactiveProp('busy', false)
|
|
7
|
+
const emit = defineEmits(['close', 'confirm'])
|
|
8
|
+
const description = derived(() => `Delete "${record()?.title || 'this discount'}" permanently? Placed orders keep the amount it took off. To pause it instead, edit it and switch it off.`)
|
|
9
|
+
</script>
|
|
10
|
+
|
|
11
|
+
<ConfirmDialog
|
|
12
|
+
:isOpen="open()"
|
|
13
|
+
title="Delete discount"
|
|
14
|
+
:description="description()"
|
|
15
|
+
confirmLabel="Delete discount"
|
|
16
|
+
:busy="busy()"
|
|
17
|
+
@close="emit('close')"
|
|
18
|
+
@confirm="emit('confirm')"
|
|
19
|
+
/>
|
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
<script client>
|
|
2
|
+
import type { DiscountRecord, DiscountTargetRecord } from '../../../../app/Actions/Dashboard/Commerce/discount-records'
|
|
3
|
+
import { formatCurrency } from '@stacksjs/commerce/money'
|
|
4
|
+
|
|
5
|
+
const open = useReactiveProp('open', false)
|
|
6
|
+
const record = useReactiveProp('record', null as DiscountRecord | null)
|
|
7
|
+
const currency = useReactiveProp('currency', 'USD')
|
|
8
|
+
const emit = defineEmits(['edit', 'close', 'delete'])
|
|
9
|
+
|
|
10
|
+
const STATE_LABELS: Record<string, string> = { active: 'Active', scheduled: 'Scheduled', expired: 'Expired', exhausted: 'Used up', disabled: 'Disabled' }
|
|
11
|
+
|
|
12
|
+
function money(value: number | null | undefined): string {
|
|
13
|
+
return value == null ? '' : formatCurrency(value, currency())
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
/** A target in words: product names, plus how many variants and categories it also names. */
|
|
17
|
+
function targetText(target: DiscountTargetRecord | undefined, empty: string): string {
|
|
18
|
+
const current = record()
|
|
19
|
+
if (!target || !current)
|
|
20
|
+
return empty
|
|
21
|
+
const parts: string[] = target.productIds.map(id => current.productLabels[id] ?? `Product #${id}`)
|
|
22
|
+
if (target.variantIds.length)
|
|
23
|
+
parts.push(`${target.variantIds.length} variant${target.variantIds.length === 1 ? '' : 's'}`)
|
|
24
|
+
if (target.categoryIds.length)
|
|
25
|
+
parts.push(`${target.categoryIds.length} categor${target.categoryIds.length === 1 ? 'y' : 'ies'}`)
|
|
26
|
+
return parts.length ? parts.join(', ') : empty
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/** What it does, in a sentence. */
|
|
30
|
+
function summaryText(): string {
|
|
31
|
+
const current = record()
|
|
32
|
+
if (!current)
|
|
33
|
+
return ''
|
|
34
|
+
switch (current.type) {
|
|
35
|
+
case 'percentage':
|
|
36
|
+
return current.appliesTo === 'product' ? `${current.value}% off ${targetText(current.target, 'the chosen products')}` : `${current.value}% off the whole order`
|
|
37
|
+
case 'fixed_amount':
|
|
38
|
+
return current.appliesTo === 'product'
|
|
39
|
+
? `${money(current.value)} off ${current.perItem ? 'each of ' : ''}${targetText(current.target, 'the chosen products')}`
|
|
40
|
+
: `${money(current.value)} off the order`
|
|
41
|
+
case 'buy_x_get_y':
|
|
42
|
+
return `Buy ${current.buyQuantity} of ${targetText(current.buyTarget, 'any product')}, get ${current.getQuantity} of ${targetText(current.getTarget, 'the same products')} ${current.getPercent === 100 ? 'free' : `${current.getPercent}% off`}${current.maxApplications ? `, up to ${current.maxApplications} times per order` : ''}`
|
|
43
|
+
case 'volume':
|
|
44
|
+
return `${current.tiers.map(t => `${t.minQuantity}+ for ${t.percent}% off`).join(', ')} on ${targetText(current.target, 'every product')}`
|
|
45
|
+
default:
|
|
46
|
+
return current.maxShipping != null ? `Free shipping on rates up to ${money(current.maxShipping)}` : 'Free shipping on any rate'
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
function combinations(): string {
|
|
51
|
+
const c = record()?.combinesWith
|
|
52
|
+
if (!c)
|
|
53
|
+
return 'Nothing'
|
|
54
|
+
const list = [c.product ? 'product' : '', c.order ? 'order' : '', c.shipping ? 'shipping' : ''].filter(Boolean)
|
|
55
|
+
return list.length ? `${list.join(', ')} discounts` : 'Nothing: the better discount wins'
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** When it runs, in words. */
|
|
59
|
+
function runs(): string {
|
|
60
|
+
const current = record()
|
|
61
|
+
if (!current?.startsAt && !current?.endsAt)
|
|
62
|
+
return 'Always'
|
|
63
|
+
if (current.startsAt && current.endsAt)
|
|
64
|
+
return `${current.startsAt} to ${current.endsAt}`
|
|
65
|
+
return current.startsAt ? `From ${current.startsAt}` : `Until ${current.endsAt}`
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
function editRecord(): void {
|
|
69
|
+
const current = record()
|
|
70
|
+
if (!current)
|
|
71
|
+
return
|
|
72
|
+
emit('edit', current)
|
|
73
|
+
emit('close')
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
function deleteRecord(): void {
|
|
77
|
+
const current = record()
|
|
78
|
+
if (!current)
|
|
79
|
+
return
|
|
80
|
+
emit('delete', current)
|
|
81
|
+
emit('close')
|
|
82
|
+
}
|
|
83
|
+
</script>
|
|
84
|
+
|
|
85
|
+
<Modal
|
|
86
|
+
:isOpen="open()"
|
|
87
|
+
:title="record()?.title || 'Discount'"
|
|
88
|
+
:description="summaryText()"
|
|
89
|
+
size="lg"
|
|
90
|
+
@close="emit('close')"
|
|
91
|
+
>
|
|
92
|
+
<template #header-trailing>
|
|
93
|
+
<span class="px-2 py-1 font-semibold text-gray-700 text-xs dark:text-neutral-200 bg-gray-100 dark:bg-neutral-700 rounded-full">{{ STATE_LABELS[record()?.state || ''] || 'Unknown' }}</span>
|
|
94
|
+
</template>
|
|
95
|
+
<div class="flex gap-2 items-center mb-5">
|
|
96
|
+
<span class="inline-flex gap-1.5 items-center px-2.5 py-1 font-semibold text-emerald-800 text-xs tracking-wide dark:text-emerald-300 bg-emerald-50 dark:bg-emerald-950/40 rounded-full"><span class="h-3.5 w-3.5 i-hugeicons-discount-tag-01"></span>{{ record()?.label }}</span>
|
|
97
|
+
<span class="text-gray-500 text-xs dark:text-neutral-400">{{ record()?.method === 'code' ? 'Code ' + record()?.code : 'Automatic' }}</span>
|
|
98
|
+
</div>
|
|
99
|
+
<dl class="grid gap-4 grid-cols-2">
|
|
100
|
+
<div><dt class="text-gray-500 text-xs dark:text-neutral-500">Used</dt><dd class="mt-1 font-mono text-gray-900 text-sm dark:text-white">{{ record()?.usageCount || 0 }} / {{ record()?.usageLimit || 'No limit' }}</dd></div>
|
|
101
|
+
<div><dt class="text-gray-500 text-xs dark:text-neutral-500">Combines with</dt><dd class="mt-1 text-gray-900 text-sm dark:text-white">{{ combinations() }}</dd></div>
|
|
102
|
+
<div><dt class="text-gray-500 text-xs dark:text-neutral-500">Minimum purchase</dt><dd class="mt-1 text-gray-900 text-sm dark:text-white">{{ record()?.minimumSubtotal ? money(record()?.minimumSubtotal) : 'None' }}</dd></div>
|
|
103
|
+
<div><dt class="text-gray-500 text-xs dark:text-neutral-500">Minimum items</dt><dd class="mt-1 text-gray-900 text-sm dark:text-white">{{ record()?.minimumQuantity || 'None' }}</dd></div>
|
|
104
|
+
<div><dt class="text-gray-500 text-xs dark:text-neutral-500">Most it takes off</dt><dd class="mt-1 text-gray-900 text-sm dark:text-white">{{ record()?.maxAmount ? money(record()?.maxAmount) : 'No cap' }}</dd></div>
|
|
105
|
+
<div><dt class="text-gray-500 text-xs dark:text-neutral-500">Runs</dt><dd class="mt-1 text-gray-900 text-sm dark:text-white">{{ runs() }}</dd></div>
|
|
106
|
+
</dl>
|
|
107
|
+
<template #footer>
|
|
108
|
+
<div class="flex gap-2 justify-between w-full"><Button variant="danger" @click="deleteRecord()">Delete</Button><div class="flex gap-2"><Button variant="secondary" @click="emit('close')">Close</Button><Button @click="editRecord()">Edit discount</Button></div></div>
|
|
109
|
+
</template>
|
|
110
|
+
</Modal>
|