@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,302 @@
1
+ <script server>
2
+ // The project switcher at the top of the dashboard sidebar.
3
+ //
4
+ // Its button is drawn on the server with the project's name, so the sidebar
5
+ // does not shift when the page hydrates. The list is fetched in the browser,
6
+ // when the menu opens: which projects have a dashboard up changes from one
7
+ // minute to the next, and the layout this sits in is rendered once and kept.
8
+ const { name = '' } = defineProps<{ name?: string }>()
9
+
10
+ export const projectName = name
11
+ export const projectInitial = (name.trim()[0] || 'S').toUpperCase()
12
+ </script>
13
+
14
+ <script client>
15
+ import type { SwitcherProject } from '../../../functions/projects'
16
+ import { addProject, fetchProjects, filterProjects, goToProject, keepAlive, openProject, projectLocation } from '../../../functions/projects'
17
+
18
+ const isOpen = state(false)
19
+ const projects = state<SwitcherProject[]>([])
20
+ const query = state('')
21
+ const selectedIndex = state(0)
22
+ const isLoading = state(false)
23
+ // The id of the project being opened, while its dashboard starts.
24
+ const opening = state('')
25
+ const error = state('')
26
+ const isAdding = state(false)
27
+ const addPath = state('')
28
+ const isSaving = state(false)
29
+ const root = useRef<HTMLElement>('projectSwitcher')
30
+ const trigger = useRef<HTMLButtonElement>('projectSwitcherTrigger')
31
+ const searchInput = useRef<HTMLInputElement>('projectSwitcherSearch')
32
+ const addInput = useRef<HTMLInputElement>('projectSwitcherAddPath')
33
+ let stopKeepAlive = () => {}
34
+
35
+ function visibleProjects(): SwitcherProject[] {
36
+ return filterProjects(projects(), query())
37
+ }
38
+
39
+ async function load(): Promise<void> {
40
+ isLoading.set(true)
41
+ try {
42
+ const listing = await fetchProjects()
43
+ projects.set(listing.projects)
44
+ stopKeepAlive()
45
+ stopKeepAlive = keepAlive(listing.keepAliveMs)
46
+ }
47
+ catch (reason) {
48
+ error.set(reason instanceof Error ? reason.message : 'The project list could not be loaded.')
49
+ }
50
+ finally {
51
+ isLoading.set(false)
52
+ }
53
+ }
54
+
55
+ function open(): void {
56
+ isOpen.set(true)
57
+ query.set('')
58
+ error.set('')
59
+ selectedIndex.set(0)
60
+ isAdding.set(false)
61
+ void load()
62
+ void nextTick(() => searchInput.current?.focus())
63
+ }
64
+
65
+ function close(): void {
66
+ if (!isOpen()) return
67
+ isOpen.set(false)
68
+ // Opening a project that has to start can take a few seconds; closing the
69
+ // menu does not cancel it, it only stops showing it.
70
+ }
71
+
72
+ function toggle(): void {
73
+ isOpen() ? close() : open()
74
+ }
75
+
76
+ async function choose(project: SwitcherProject): Promise<void> {
77
+ if (opening()) return
78
+ if (project.current) {
79
+ close()
80
+ return
81
+ }
82
+
83
+ error.set('')
84
+ // Up already: go straight there. Otherwise ask for it to be started and
85
+ // wait until it answers.
86
+ if (project.running && project.url) {
87
+ goToProject(project.url)
88
+ return
89
+ }
90
+
91
+ opening.set(project.id)
92
+ try {
93
+ goToProject(await openProject(project.id))
94
+ }
95
+ catch (reason) {
96
+ opening.set('')
97
+ error.set(reason instanceof Error ? reason.message : `${project.name} could not be opened.`)
98
+ }
99
+ }
100
+
101
+ function startAdding(): void {
102
+ isAdding.set(true)
103
+ addPath.set('')
104
+ error.set('')
105
+ void nextTick(() => addInput.current?.focus())
106
+ }
107
+
108
+ async function submitAdd(): Promise<void> {
109
+ const path = addPath().trim()
110
+ if (!path || isSaving()) return
111
+
112
+ isSaving.set(true)
113
+ error.set('')
114
+ try {
115
+ const added = await addProject(path)
116
+ isAdding.set(false)
117
+ query.set('')
118
+ await load()
119
+ const index = visibleProjects().findIndex(project => project.id === added.id)
120
+ selectedIndex.set(index === -1 ? 0 : index)
121
+ void nextTick(() => searchInput.current?.focus())
122
+ }
123
+ catch (reason) {
124
+ error.set(reason instanceof Error ? reason.message : 'That project could not be added.')
125
+ }
126
+ finally {
127
+ isSaving.set(false)
128
+ }
129
+ }
130
+
131
+ function handleSearchKeydown(event: KeyboardEvent): void {
132
+ const items = visibleProjects()
133
+ if (event.key === 'ArrowDown') {
134
+ event.preventDefault()
135
+ if (items.length > 0)
136
+ selectedIndex.set(selectedIndex() >= items.length - 1 ? 0 : selectedIndex() + 1)
137
+ }
138
+ else if (event.key === 'ArrowUp') {
139
+ event.preventDefault()
140
+ if (items.length > 0)
141
+ selectedIndex.set(selectedIndex() <= 0 ? items.length - 1 : selectedIndex() - 1)
142
+ }
143
+ else if (event.key === 'Enter') {
144
+ event.preventDefault()
145
+ const project = items[selectedIndex()]
146
+ if (project) void choose(project)
147
+ }
148
+ }
149
+
150
+ function handleAddKeydown(event: KeyboardEvent): void {
151
+ if (event.key === 'Enter') {
152
+ event.preventDefault()
153
+ void submitAdd()
154
+ }
155
+ else if (event.key === 'Escape') {
156
+ // Back to the list, not out of the menu.
157
+ event.preventDefault()
158
+ event.stopPropagation()
159
+ isAdding.set(false)
160
+ void nextTick(() => searchInput.current?.focus())
161
+ }
162
+ }
163
+
164
+ function handleEscape(): void {
165
+ if (!isOpen()) return
166
+ close()
167
+ trigger.current?.focus()
168
+ }
169
+
170
+ // Complete class strings, because a `class` attribute is not reactive.
171
+ function rowClass(project: SwitcherProject, index: number): string {
172
+ const active = index === selectedIndex()
173
+ return `flex gap-2.5 items-center px-2 py-1.5 w-full text-left rounded-md ${active ? 'bg-black/8 dark:bg-white/12' : ''} ${opening() && opening() !== project.id ? 'opacity-50' : ''}`
174
+ }
175
+
176
+ useClickOutside(root, close)
177
+
178
+ onMount(() => {
179
+ // Learns whether the server wants to hear from this page, and has the list
180
+ // ready before the menu is first opened.
181
+ void load()
182
+ })
183
+
184
+ onDestroy(() => {
185
+ stopKeepAlive()
186
+ })
187
+ </script>
188
+
189
+ <div
190
+ ref="projectSwitcher"
191
+ data-project-switcher
192
+ :data-open="String(isOpen())"
193
+ class="relative pb-1.5 px-2 [-webkit-app-region:no-drag]"
194
+ @keydown.escape="handleEscape()"
195
+ >
196
+ <button
197
+ ref="projectSwitcherTrigger"
198
+ type="button"
199
+ aria-haspopup="dialog"
200
+ :aria-expanded="String(isOpen())"
201
+ aria-label="Switch project"
202
+ title="Switch project"
203
+ class="flex gap-2 items-center px-1.5 py-1.5 w-full text-left hover:bg-black/5 dark:hover:bg-white/10 rounded-lg focus-visible:outline-2 focus-visible:outline-blue-500 focus-visible:outline-offset-[-2px] transition-colors"
204
+ @click="toggle()"
205
+ >
206
+ <span aria-hidden="true" class="flex items-center justify-center shrink-0 h-6 w-6 font-semibold text-[11px] text-white dark:text-neutral-900 bg-neutral-800 dark:bg-neutral-100 rounded-md">{{ projectInitial }}</span>
207
+ <span class="flex-1 min-w-0 font-semibold text-[13px] truncate">{{ projectName }}</span>
208
+ <span aria-hidden="true" class="shrink-0 h-4 w-4 opacity-50 i-hugeicons-unfold-more"></span>
209
+ </button>
210
+
211
+ <div
212
+ :if="isOpen()"
213
+ role="dialog"
214
+ aria-label="Projects"
215
+ class="absolute left-2 overflow-hidden right-2 top-full z-50 text-neutral-800 dark:text-neutral-100 bg-white/95 dark:bg-neutral-800/95 border border-black/10 rounded-xl dark:border-white/10 shadow-black/15 shadow-xl dark:shadow-black/40 backdrop-blur-xl backdrop-saturate-150"
216
+ >
217
+ <div class="flex gap-2 items-center px-2.5 border-b border-black/10 dark:border-white/10">
218
+ <span aria-hidden="true" class="shrink-0 h-4 w-4 opacity-50 i-hugeicons-search-01"></span>
219
+ <input
220
+ ref="projectSwitcherSearch"
221
+ x-model="query"
222
+ type="text"
223
+ autocomplete="off"
224
+ spellcheck="false"
225
+ placeholder="Find a project"
226
+ aria-label="Find a project"
227
+ class="py-2 w-full text-[13px] placeholder:text-neutral-400 bg-transparent border-none focus:outline-none focus:ring-0"
228
+ @input="selectedIndex.set(0)"
229
+ @keydown="handleSearchKeydown"
230
+ />
231
+ <span :if="isLoading()" aria-hidden="true" class="shrink-0 h-4 w-4 opacity-60 animate-spin i-hugeicons-loading-03"></span>
232
+ </div>
233
+
234
+ <div role="listbox" aria-label="Projects on this machine" class="overflow-y-auto p-1 max-h-72">
235
+ <button
236
+ :for="(project, index) in visibleProjects()"
237
+ type="button"
238
+ role="option"
239
+ :aria-selected="String(index === selectedIndex())"
240
+ :data-project-id="project.id"
241
+ :title="project.path"
242
+ :disabled="Boolean(opening())"
243
+ :class="rowClass(project, index)"
244
+ @mouseenter="selectedIndex.set(index)"
245
+ @click="choose(project)"
246
+ >
247
+ <span aria-hidden="true" class="flex items-center justify-center shrink-0 h-6 w-6 font-semibold text-[11px] text-neutral-700 dark:text-neutral-200 bg-black/8 dark:bg-white/12 rounded-md">{{ (project.name[0] || '?').toUpperCase() }}</span>
248
+ <span class="flex-1 min-w-0">
249
+ <span class="block font-medium text-[13px] truncate">{{ project.name }}</span>
250
+ <span class="block text-[11px] truncate opacity-60">{{ projectLocation(project.path) }}</span>
251
+ </span>
252
+ <span :if="opening() === project.id" role="status" aria-label="Starting" class="shrink-0 h-4 w-4 animate-spin i-hugeicons-loading-03"></span>
253
+ <span :if="project.current && opening() !== project.id" aria-label="Current project" class="shrink-0 h-4 w-4 text-blue-500 i-hugeicons-tick-02"></span>
254
+ <span :if="project.running && !project.current && opening() !== project.id" title="Dashboard running" aria-label="Dashboard running" class="shrink-0 h-2 w-2 bg-green-500 rounded-full"></span>
255
+ </button>
256
+
257
+ <p :if="!isLoading() && projects().length > 0 && visibleProjects().length === 0" class="px-2 py-4 text-[12px] text-center opacity-60">
258
+ No project matches "{{ query() }}".
259
+ </p>
260
+ </div>
261
+
262
+ <p :if="opening()" role="status" class="px-3 py-2 text-[12px] border-black/10 border-t dark:border-white/10 opacity-70">
263
+ Starting its dashboard. This takes a few seconds the first time.
264
+ </p>
265
+ <p :if="error()" role="alert" class="px-3 py-2 break-words text-[12px] text-red-600 whitespace-pre-line dark:text-red-400 border-black/10 border-t dark:border-white/10">{{ error() }}</p>
266
+
267
+ <div class="p-1 border-black/10 border-t dark:border-white/10">
268
+ <button
269
+ :if="!isAdding()"
270
+ type="button"
271
+ data-project-add
272
+ class="flex gap-2.5 items-center px-2 py-1.5 w-full text-[13px] text-left hover:bg-black/5 dark:hover:bg-white/10 rounded-md"
273
+ @click="startAdding()"
274
+ >
275
+ <span aria-hidden="true" class="shrink-0 mx-1 h-4 w-4 opacity-70 i-hugeicons-folder-add"></span>
276
+ Add a project
277
+ </button>
278
+
279
+ <div :if="isAdding()" class="flex gap-1.5 items-center px-1 py-1">
280
+ <input
281
+ ref="projectSwitcherAddPath"
282
+ x-model="addPath"
283
+ type="text"
284
+ autocomplete="off"
285
+ spellcheck="false"
286
+ placeholder="~/Code/my-app"
287
+ aria-label="Path of the project to add"
288
+ class="flex-1 px-2 py-1 min-w-0 text-[12px] placeholder:text-neutral-400 bg-black/5 dark:bg-white/10 border-none rounded-md focus:outline-none focus:ring-1 focus:ring-blue-500"
289
+ @keydown="handleAddKeydown"
290
+ />
291
+ <Button
292
+ variant="primary"
293
+ size="xs"
294
+ :disabled="isSaving() || !addPath().trim()"
295
+ @click="submitAdd()"
296
+ >
297
+ Add
298
+ </Button>
299
+ </div>
300
+ </div>
301
+ </div>
302
+ </div>
@@ -43,14 +43,16 @@ const fields = state<ConfigField[]>([])
43
43
  const drafts = reactive<Record<string, string | number | boolean>>({})
44
44
  const selected = state('')
45
45
  const pendingSelection = state('')
46
- const query = state('')
46
+ // Not `query`: the render context has one of its own (the request's query
47
+ // string), and a component binding resolved to it.
48
+ const configQuery = state('')
47
49
  const loading = state(true)
48
50
  const saving = state(false)
49
51
  const message = state('')
50
52
  const error = state('')
51
53
 
52
54
  const filteredFiles = derived(() => {
53
- const needle = query().trim().toLowerCase()
55
+ const needle = configQuery().trim().toLowerCase()
54
56
  if (!needle)
55
57
  return files()
56
58
 
@@ -198,7 +200,7 @@ void loadFiles()
198
200
  <div class="grid gap-6 lg:grid-cols-[17rem_minmax(0,1fr)]">
199
201
  <Card variant="default" padding="none">
200
202
  <div class="p-4 border-b border-neutral-200/60 dark:border-white/5">
201
- <SearchFilter v-model:searchValue="query" placeholder="Search config" ariaLabel="Search configuration" />
203
+ <SearchFilter v-model:searchValue="configQuery" placeholder="Search config" ariaLabel="Search configuration" />
202
204
  </div>
203
205
 
204
206
  <nav class="overflow-y-auto p-2 max-h-[68vh]" aria-label="Configuration files">
@@ -18,7 +18,10 @@ const placeholder = useReactiveProp('placeholder', 'Search...')
18
18
  // bar names the list it searches ("Search coupons").
19
19
  const ariaLabel = useReactiveProp('ariaLabel', '')
20
20
  const requested = useReactiveProp('searchValue', '')
21
- const query = state(requested())
21
+ // Not `query`: a render's context has a `query` of its own (the request's
22
+ // query-string object), and the binding below resolved to that, filling
23
+ // every dashboard search box with "[object Object]".
24
+ const term = state(requested())
22
25
  const emit = defineEmits(['update:searchValue', 'search'])
23
26
  // What the box last showed that the parent already knows: the value it was
24
27
  // seeded with, or the last search reported. Only a change the person makes is
@@ -29,11 +32,11 @@ let known = requested()
29
32
  effect(() => {
30
33
  const next = requested()
31
34
  known = next
32
- query.set(next)
35
+ term.set(next)
33
36
  })
34
37
 
35
38
  effect(() => {
36
- const value = query()
39
+ const value = term()
37
40
  if (value === known)
38
41
  return
39
42
  known = value
@@ -48,7 +51,7 @@ effect(() => {
48
51
  The box is the root, so a caller's `class` (a width) sizes the whole field.
49
52
  -->
50
53
  <div>
51
- <Input v-model:value="query" type="search" name="search" :placeholder="placeholder()" :ariaLabel="ariaLabel() || placeholder()" autocomplete="off" :spellcheck="false">
54
+ <Input v-model:value="term" type="search" name="search" :placeholder="placeholder()" :ariaLabel="ariaLabel() || placeholder()" autocomplete="off" :spellcheck="false">
52
55
  <template #iconLeft>
53
56
  <span aria-hidden="true" class="h-4 w-4 i-hugeicons-search-01"></span>
54
57
  </template>
@@ -21,6 +21,10 @@ interface OrderSummaryProps {
21
21
  /** Optional, pre-formatted "Add $X.XX more for free shipping." nudge.
22
22
  * When empty/omitted the nudge is hidden — let the caller decide. */
23
23
  freeShippingNote?: string
24
+ /** Optional, pre-formatted discount ("-$10.00"); the row is hidden when empty. */
25
+ discountLabel?: string
26
+ /** What the discount is, shown under the row: "BUY 4, GET 4 FREE". */
27
+ discountTitle?: string
24
28
  showItems?: boolean
25
29
  ctaHref?: string
26
30
  ctaLabel?: string
@@ -38,6 +42,8 @@ const {
38
42
  shippingLabel,
39
43
  totalLabel,
40
44
  freeShippingNote = '',
45
+ discountLabel = '',
46
+ discountTitle = '',
41
47
  showItems = false,
42
48
  ctaHref = '',
43
49
  ctaLabel = '',
@@ -64,6 +70,17 @@ const {
64
70
 
65
71
  <dl class="space-y-3 text-sm {{ showItems ? '' : 'mt-4' }}">
66
72
  <div class="flex justify-between"><dt class="text-stone-600">Subtotal</dt><dd class="font-semibold text-stone-900">{{ subtotalLabel }}</dd></div>
73
+ @if (discountLabel)
74
+ <div class="flex gap-3 justify-between">
75
+ <dt class="text-stone-600">
76
+ Discount
77
+ @if (discountTitle)
78
+ <span class="block font-medium text-emerald-700 text-xs tracking-wide uppercase">{{ discountTitle }}</span>
79
+ @endif
80
+ </dt>
81
+ <dd class="font-semibold text-emerald-700">{{ discountLabel }}</dd>
82
+ </div>
83
+ @endif
67
84
  <div class="flex justify-between"><dt class="text-stone-600">Shipping</dt><dd class="font-semibold text-stone-900">{{ shippingLabel }}</dd></div>
68
85
  @if (taxLabel)
69
86
  <div class="flex justify-between"><dt class="text-stone-600">Tax</dt><dd class="font-semibold text-stone-900">{{ taxLabel }}</dd></div>
@@ -0,0 +1,14 @@
1
+ import { describe, expect, it } from 'bun:test'
2
+ import { dashboardProjectIdentity } from './project-switcher'
3
+
4
+ describe('the project a dashboard names in its sidebar', () => {
5
+ it('is the directory it serves, with a switcher on the developer\'s machine', () => {
6
+ expect(dashboardProjectIdentity('/Users/dev/Code/shop', { STACKS_DASHBOARD_PROJECTS: '1' })).toEqual({ enabled: true, name: 'shop' })
7
+ })
8
+
9
+ it('has no switcher where the dev dashboard server did not ask for one', () => {
10
+ // A deployed dashboard: one project, and a release directory for a name.
11
+ expect(dashboardProjectIdentity('/var/www/shop/releases/42', {}).enabled).toBe(false)
12
+ expect(dashboardProjectIdentity('/var/www/shop', { STACKS_DASHBOARD_PROJECTS: '0' }).enabled).toBe(false)
13
+ })
14
+ })
@@ -0,0 +1,28 @@
1
+ import { basename } from 'node:path'
2
+ import process from 'node:process'
3
+
4
+ /**
5
+ * What the dashboard layout needs to draw the project switcher on the first
6
+ * paint: the name of the project being served, and whether there is a
7
+ * switcher at all.
8
+ *
9
+ * There is one only on the developer's machine, where `buddy` knows the other
10
+ * projects and can start their dashboards; the dev dashboard server says so
11
+ * by setting `STACKS_DASHBOARD_PROJECTS`. A deployed dashboard serves the one
12
+ * project it was deployed with, and draws nothing here.
13
+ *
14
+ * Node built-ins only: this runs in the layout's server script.
15
+ */
16
+ export interface DashboardProjectIdentity {
17
+ enabled: boolean
18
+ name: string
19
+ }
20
+
21
+ export function dashboardProjectIdentity(root: string = process.cwd(), env: Record<string, string | undefined> = process.env): DashboardProjectIdentity {
22
+ return {
23
+ enabled: env.STACKS_DASHBOARD_PROJECTS === '1',
24
+ // The directory name is what a developer calls the project, and it is the
25
+ // name `buddy projects` and `--project` use for it.
26
+ name: basename(root),
27
+ }
28
+ }
@@ -482,6 +482,8 @@ export function buildNavSections(
482
482
  { to: '/commerce/variants', icon: 'puzzle', text: 'Variants' },
483
483
  { to: '/commerce/reviews', icon: 'star', text: 'Reviews' },
484
484
  { to: '/commerce/coupons', icon: 'coupon', text: 'Coupons' },
485
+ { to: '/commerce/discounts', icon: 'sale-tag', text: 'Discounts' },
486
+ { to: '/commerce/upsells', icon: 'zap', text: 'Upsells' },
485
487
  { to: '/commerce/gift-cards', icon: 'gift', text: 'Gift Cards' },
486
488
  { to: '/commerce/payments', icon: 'invoice', text: 'Payments' },
487
489
  { to: '/commerce/taxes', icon: 'percent', text: 'Taxes' },
@@ -491,7 +493,8 @@ export function buildNavSections(
491
493
  { to: '/commerce/waitlist/restaurant', icon: 'clock', text: 'Restaurant Waitlist' },
492
494
  ...categoryNavItems(discoveredModels, 'commerce', new Set([
493
495
  'customer', 'order', 'product', 'product-variant', 'product-unit',
494
- 'manufacturer', 'review', 'coupon', 'gift-card', 'payment', 'category',
496
+ 'manufacturer', 'review', 'coupon', 'discount', 'post-purchase-offer', 'post-purchase-offer-response',
497
+ 'gift-card', 'payment', 'category',
495
498
  'cart', 'cart-item', 'order-item', 'tax-rate',
496
499
  'shipping-method', 'shipping-rate', 'shipping-zone',
497
500
  'delivery-route', 'courier', 'license-key', 'digital-delivery',
@@ -96,7 +96,38 @@ const entrypoint = (process.argv[1] ?? '').replaceAll('\\', '/')
96
96
  const repositoryAction = '(?:release|bump|generate/lib-entries)\\.[jt]s'
97
97
  const isRepositoryAction = new RegExp(`(?:^|/)storage/framework/core/actions/src/${repositoryAction}$`).test(entrypoint)
98
98
  || new RegExp(`(?:^|/)(?:node_modules|pantry)/@stacksjs/actions/(?:src|dist(?:/src)?)/${repositoryAction}$`).test(entrypoint)
99
- const skipPreloader = isRepl || isPostinstall || isRepositoryAction || (args.length > 0 && fastCommands.some(cmd => args[0] === cmd || args[0].startsWith(`${cmd}:`)))
99
+
100
+ /**
101
+ * A `buddy` installed once for the whole machine, started in this project.
102
+ *
103
+ * It is only passing through: it finds the project and replaces itself with
104
+ * the project's own `buddy`, which runs this file again, for real. Everything
105
+ * below (the env files, the auto-import graph) would be loaded here, thrown
106
+ * away a moment later, and loaded again: about half a second on every command
107
+ * typed at a project root.
108
+ *
109
+ * Not when this process was itself handed the project (`STACKS_BUDDY_ROOT`):
110
+ * that one is the last, and does the work.
111
+ */
112
+ async function isVisitingBuddy(): Promise<boolean> {
113
+ if (isPostinstall || !/(?:^|\/)buddy\/(?:src\/cli\.ts|dist\/cli\.js)$/.test(entrypoint))
114
+ return false
115
+ if (process.env.STACKS_BUDDY_ROOT)
116
+ return false
117
+
118
+ try {
119
+ const pathPackage = '@stacksjs/' + 'path'
120
+ const { isVisitingCli } = await import('../../../core/path/src/index.ts').catch(() => import(pathPackage))
121
+ // An installed @stacksjs/path that predates the helper: carry on as before.
122
+ return typeof isVisitingCli === 'function' && isVisitingCli(process.cwd(), entrypoint)
123
+ }
124
+ catch {
125
+ return false
126
+ }
127
+ }
128
+
129
+ const isPassingThrough = await isVisitingBuddy()
130
+ const skipPreloader = isRepl || isPostinstall || isRepositoryAction || isPassingThrough || (args.length > 0 && fastCommands.some(cmd => args[0] === cmd || args[0].startsWith(`${cmd}:`)))
100
131
 
101
132
  if (!skipPreloader) {
102
133
  // Detect production/deployment commands and set environment accordingly BEFORE loading env files
@@ -137,7 +168,7 @@ if (!skipPreloader) {
137
168
  // importing it there can fail (see the isPostinstall note above). The REPL keeps
138
169
  // its original skip. The heavy auto-import graph below stays gated separately via
139
170
  // `skipAutoImports`.
140
- if (!isRepl && !isPostinstall) {
171
+ if (!isRepl && !isPostinstall && !isPassingThrough) {
141
172
  // Resolve the vendored source first; the package fallback covers non-standard
142
173
  // layouts where defaults is consumed outside the framework layout.
143
174
  const envPackage = '@stacksjs/' + 'env'
@@ -19,6 +19,7 @@ interface CartItemRow {
19
19
  interface CartRow {
20
20
  id: number
21
21
  currency: string | null
22
+ discount_code?: string | null
22
23
  }
23
24
 
24
25
  interface StorefrontLineItem { lineTotal: number }
@@ -26,16 +27,17 @@ interface StorefrontLineItem { lineTotal: number }
26
27
  const { verifyCartCookie } = require('../../app/Storefront/CartCookie')
27
28
  const { readStorefront } = require('../../app/Storefront/StorefrontDatabase')
28
29
  const { storefrontCurrency, storefrontMoney, storefrontSummary } = require('../../app/Storefront/StorefrontMoney')
30
+ const { storefrontCartSummary } = require('../../app/Storefront/StorefrontPricing')
29
31
 
30
32
  // Signed by the storefront actions as the token, a dot and its HMAC. An
31
33
  // unsigned or tampered cookie is no cart, and is never looked up.
32
34
  const token = verifyCartCookie(requestContext.cookie('stacks_cart'))
33
35
 
34
36
  const found = token
35
- ? readStorefront('views/cart.stx', { cart: null, items: [] }, (db: import('bun:sqlite').Database) => {
37
+ ? readStorefront('views/cart.stx', { cart: null, items: [], summary: null }, (db: import('bun:sqlite').Database) => {
36
38
  const row = db.query<CartRow, [string]>(`SELECT * FROM carts WHERE session_token = ?1 AND status = 'active' LIMIT 1`).get(token)
37
39
  if (!row)
38
- return { cart: null, items: [] }
40
+ return { cart: null, items: [], summary: null }
39
41
 
40
42
  // Every amount below is integer minor units of the cart's currency.
41
43
  const currency = storefrontCurrency(row.currency)
@@ -63,9 +65,10 @@ const found = token
63
65
  }
64
66
  })
65
67
 
66
- return { cart: row, items: lines }
68
+ // Priced with the store's automatic discounts, exactly as PlaceOrderAction charges.
69
+ return { cart: row, items: lines, summary: storefrontCartSummary(db, row.id, currency) }
67
70
  })
68
- : { cart: null, items: [] }
71
+ : { cart: null, items: [], summary: null }
69
72
 
70
73
  const cart = found.cart
71
74
  const items = found.items
@@ -78,7 +81,9 @@ const subtotal = items.reduce((sum: number, i: StorefrontLineItem) => sum + i.li
78
81
  // Pre-format every amount so the OrderSummary component template doesn't
79
82
  // have to format a defineProps local — STX's SSR pass doesn't reliably
80
83
  // expose those locals, so callers do the formatting.
81
- const summary = storefrontSummary(subtotal, storefrontCurrency(cart?.currency))
84
+ const summary = found.summary ?? { ...storefrontSummary(subtotal, storefrontCurrency(cart?.currency)), discountLabel: '', discountTitle: '' }
85
+ const discountLabel = summary.discountLabel
86
+ const discountTitle = summary.discountTitle
82
87
  const subtotalLabel = summary.subtotalLabel
83
88
  const shippingLabel = summary.shippingLabel
84
89
  const totalLabel = summary.totalLabel
@@ -89,6 +94,10 @@ const cartNotice = requestContext.notice()
89
94
  // Why the form this page posted was refused, when it was not about one field
90
95
  // ("Your cart is empty."). Shown once (stacksjs/stacks#3311).
91
96
  const formError = requestContext.formError()
97
+ // The discount code field: what is applied, or what was typed and refused.
98
+ const discountCode = String(cart?.discount_code ?? '')
99
+ const codeError = requestContext.error('code')
100
+ const codeValue = requestContext.old('code', '')
92
101
  </script>
93
102
 
94
103
  @section('content')
@@ -165,17 +174,42 @@ const formError = requestContext.formError()
165
174
  @endforeach
166
175
  </div>
167
176
 
168
- <OrderSummary
169
- subtotalLabel="{{ subtotalLabel }}"
170
- shippingLabel="{{ shippingLabel }}"
171
- totalLabel="{{ totalLabel }}"
172
- freeShippingNote="{{ freeShippingNote }}"
173
- ctaHref="/checkout/contact"
174
- ctaLabel="Checkout"
175
- secondaryHref="/products"
176
- secondaryLabel="Keep shopping"
177
- :sticky="true"
178
- />
177
+ <div class="space-y-4 lg:sticky lg:top-28">
178
+ <OrderSummary
179
+ subtotalLabel="{{ subtotalLabel }}"
180
+ shippingLabel="{{ shippingLabel }}"
181
+ totalLabel="{{ totalLabel }}"
182
+ freeShippingNote="{{ freeShippingNote }}"
183
+ discountLabel="{{ discountLabel }}"
184
+ discountTitle="{{ discountTitle }}"
185
+ ctaHref="/checkout/contact"
186
+ ctaLabel="Checkout"
187
+ secondaryHref="/products"
188
+ secondaryLabel="Keep shopping"
189
+ />
190
+
191
+ <form action="/api/cart/discount" method="POST" class="p-4 border border-stone-200 rounded-2xl">
192
+ @if (discountCode)
193
+ <p class="font-semibold text-stone-500 text-xs tracking-wider uppercase">Discount code</p>
194
+ <div class="flex gap-3 items-center justify-between mt-2">
195
+ <span class="inline-flex gap-2 items-center px-3 py-1.5 font-semibold text-emerald-800 text-sm bg-emerald-50 rounded-full">
196
+ <span class="i-hugeicons-discount-tag-01 h-4 w-4" aria-hidden="true"></span>
197
+ {{ discountCode }}
198
+ </span>
199
+ <button type="submit" name="remove" value="1" class="font-medium text-stone-500 text-xs underline-offset-4 hover:text-stone-900 hover:underline focus-visible:outline-none focus-visible:underline">Remove</button>
200
+ </div>
201
+ @else
202
+ <label for="discount-code" class="font-semibold text-stone-500 text-xs tracking-wider uppercase">Discount code</label>
203
+ <div class="flex gap-2 mt-2">
204
+ <input id="discount-code" name="code" type="text" autocomplete="off" autocapitalize="characters" maxlength="64" value="{{ codeValue }}" placeholder="Enter code" class="flex-1 min-w-0 px-3 py-2 text-sm text-stone-900 border border-stone-300 rounded-xl focus:border-stone-900 focus:outline-none" aria-describedby="discount-code-error">
205
+ <button type="submit" class="px-4 py-2 font-semibold text-sm text-stone-900 border border-stone-300 hover:border-stone-900 rounded-xl focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-stone-900 transition-colors">Apply</button>
206
+ </div>
207
+ @if (codeError)
208
+ <p id="discount-code-error" role="alert" class="mt-2 text-red-700 text-xs">{{ codeError }}</p>
209
+ @endif
210
+ @endif
211
+ </form>
212
+ </div>
179
213
 
180
214
  </div>
181
215
  @endif