@sgflabs/storefront-core 0.1.9 → 0.1.11
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/README.md +4 -0
- package/package.json +9 -9
- package/src/components/organisms/AiChatWidget/AiChatWidget.tsx +256 -0
- package/src/components/organisms/ProductSidebar/CertificationFilter.tsx +105 -31
- package/src/components/organisms/ProductSidebar/ProductSidebar.tsx +8 -4
- package/src/components/sections/ProductListing/ProductListing.tsx +28 -11
- package/src/lib/ai-chat/ai-chat-api.ts +305 -0
- package/src/lib/ai-chat/use-ai-chat.ts +194 -0
- package/src/lib/data/products.ts +13 -0
- package/src/lib/runtime/public-storefront-runtime-env.ts +28 -0
- package/src/lib/storefront/industry-certifications.ts +32 -0
package/README.md
CHANGED
|
@@ -82,3 +82,7 @@ single callback, with no Google Console change.
|
|
|
82
82
|
- `NEXT_PUBLIC_BASE_URL` must be the exact public https origin of the app, and its proxy must send
|
|
83
83
|
`x-forwarded-proto: https`. In this mode the handoff redeems for that configured host, never the `Host` header, so it works only for the
|
|
84
84
|
exact host of `NEXT_PUBLIC_BASE_URL`: an alternate hostname that is also enabled as an SSO hub return origin will not work.
|
|
85
|
+
|
|
86
|
+
## AI assistant (`AiChatWidget`)
|
|
87
|
+
|
|
88
|
+
Mount `AiChatWidget` from `components/organisms/AiChatWidget/AiChatWidget` in the app's root layout. It renders nothing unless the ai-interface base URL is set: `AI_INTERFACE_URL` at container runtime (mirrored to the browser through the root layout's `window.__STOREFRONT_ENV__` snapshot, like the other runtime keys) or `NEXT_PUBLIC_AI_INTERFACE_URL` at build. Guests get an anonymous per-tab identity; the ai-interface must allow the storefront's origin (its `CORS_ORIGIN`, or the vendor-storefront host lookup). Pass `className` to move the launcher clear of an app's own fixed bottom bars. The empty panel carries the DPDP notice (messages go to an AI service) with a link to `/<locale>/legal/privacy`, so the storefront must serve that legal page.
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@sgflabs/storefront-core",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.11",
|
|
4
4
|
"description": "Shared storefront library consumed as raw TypeScript source by the brand apps.",
|
|
5
5
|
"license": "PolyForm-Shield-1.0.0",
|
|
6
6
|
"sideEffects": [
|
|
@@ -54,10 +54,10 @@
|
|
|
54
54
|
},
|
|
55
55
|
"devDependencies": {
|
|
56
56
|
"@sentry/nextjs": "^10.63.0",
|
|
57
|
-
"@sgflabs/artha-go-sdk": "^0.
|
|
58
|
-
"@sgflabs/gstin": "^0.1.
|
|
59
|
-
"@sgflabs/page-spec": "^0.1.
|
|
60
|
-
"@sgflabs/storefront-core-common": "^0.1.
|
|
57
|
+
"@sgflabs/artha-go-sdk": "^0.3.0",
|
|
58
|
+
"@sgflabs/gstin": "^0.1.11",
|
|
59
|
+
"@sgflabs/page-spec": "^0.1.11",
|
|
60
|
+
"@sgflabs/storefront-core-common": "^0.1.11",
|
|
61
61
|
"@testing-library/dom": "^10.4.1",
|
|
62
62
|
"@testing-library/jest-dom": "^7.0.0",
|
|
63
63
|
"@testing-library/react": "^16.3.2",
|
|
@@ -72,10 +72,10 @@
|
|
|
72
72
|
},
|
|
73
73
|
"peerDependencies": {
|
|
74
74
|
"@sentry/nextjs": "^10.63.0",
|
|
75
|
-
"@sgflabs/artha-go-sdk": "^0.
|
|
76
|
-
"@sgflabs/gstin": "^0.1.
|
|
77
|
-
"@sgflabs/page-spec": "^0.1.
|
|
78
|
-
"@sgflabs/storefront-core-common": "^0.1.
|
|
75
|
+
"@sgflabs/artha-go-sdk": "^0.3.0",
|
|
76
|
+
"@sgflabs/gstin": "^0.1.11",
|
|
77
|
+
"@sgflabs/page-spec": "^0.1.11",
|
|
78
|
+
"@sgflabs/storefront-core-common": "^0.1.11",
|
|
79
79
|
"next": "15.5.27",
|
|
80
80
|
"react": "^19.2.3",
|
|
81
81
|
"react-dom": "^19.2.3"
|
|
@@ -0,0 +1,256 @@
|
|
|
1
|
+
"use client"
|
|
2
|
+
|
|
3
|
+
import { Dialog, DialogPanel, DialogTitle } from "@headlessui/react"
|
|
4
|
+
import Link from "next/link"
|
|
5
|
+
import { usePathname } from "next/navigation"
|
|
6
|
+
import { useEffect, useRef, useState } from "react"
|
|
7
|
+
import ReactMarkdown, { type Components } from "react-markdown"
|
|
8
|
+
|
|
9
|
+
import { CloseIcon, MessageIcon } from "../../../icons"
|
|
10
|
+
import { CHAT_MESSAGE_MAX_LENGTH, resolveAiInterfaceUrl } from "../../../lib/ai-chat/ai-chat-api"
|
|
11
|
+
import { type ChatMessage, useAiChat } from "../../../lib/ai-chat/use-ai-chat"
|
|
12
|
+
import { cn } from "../../../lib/utils"
|
|
13
|
+
|
|
14
|
+
const SUGGESTIONS = [
|
|
15
|
+
"What products do you have?",
|
|
16
|
+
"Help me find a product for my application",
|
|
17
|
+
"What are your best sellers?",
|
|
18
|
+
]
|
|
19
|
+
|
|
20
|
+
// react-markdown already drops unsafe URL schemes (javascript:, data:) and
|
|
21
|
+
// never emits raw HTML; this only hardens how the allowed links open and
|
|
22
|
+
// keeps remote images out of the transcript.
|
|
23
|
+
const markdownComponents: Components = {
|
|
24
|
+
a: ({ href, children }) => (
|
|
25
|
+
<a href={href} target="_blank" rel="noopener noreferrer" className="underline">
|
|
26
|
+
{children}
|
|
27
|
+
</a>
|
|
28
|
+
),
|
|
29
|
+
img: () => null,
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
function MessageBubble({ message }: { message: ChatMessage }) {
|
|
33
|
+
if (message.role === "notice") {
|
|
34
|
+
return (
|
|
35
|
+
<p className="mx-auto max-w-[90%] rounded-sm border px-3 py-2 text-center text-xs text-secondary">
|
|
36
|
+
{message.content}
|
|
37
|
+
</p>
|
|
38
|
+
)
|
|
39
|
+
}
|
|
40
|
+
const isUser = message.role === "user"
|
|
41
|
+
return (
|
|
42
|
+
<div className={cn("flex", isUser ? "justify-end" : "justify-start")}>
|
|
43
|
+
<div
|
|
44
|
+
className={cn(
|
|
45
|
+
"max-w-[85%] rounded-sm px-3 py-2 text-sm leading-relaxed break-words",
|
|
46
|
+
isUser
|
|
47
|
+
? "bg-action text-action-on-primary whitespace-pre-wrap"
|
|
48
|
+
: "border bg-primary text-primary [&_ol]:list-decimal [&_ol]:pl-5 [&_p]:my-1 [&_ul]:list-disc [&_ul]:pl-5"
|
|
49
|
+
)}
|
|
50
|
+
data-testid={`ai-chat-message-${message.role}`}
|
|
51
|
+
>
|
|
52
|
+
{isUser ? (
|
|
53
|
+
message.content
|
|
54
|
+
) : (
|
|
55
|
+
<ReactMarkdown components={markdownComponents}>{message.content}</ReactMarkdown>
|
|
56
|
+
)}
|
|
57
|
+
</div>
|
|
58
|
+
</div>
|
|
59
|
+
)
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/**
|
|
63
|
+
* Headless UI's Dialog supplies the dialog basics (focus trap and initial
|
|
64
|
+
* focus, Escape and outside-click close, aria-modal, scroll lock, focus
|
|
65
|
+
* return to the launcher), same as the package's other modals.
|
|
66
|
+
*/
|
|
67
|
+
function ChatPanel({ baseUrl, onClose }: { baseUrl: string; onClose: () => void }) {
|
|
68
|
+
const { messages, isLoading, error, sendMessage, cancelMessage, startNewChat, clearError } =
|
|
69
|
+
useAiChat(baseUrl)
|
|
70
|
+
const [input, setInput] = useState("")
|
|
71
|
+
const listRef = useRef<HTMLDivElement>(null)
|
|
72
|
+
const pathname = usePathname()
|
|
73
|
+
const locale = pathname?.split("/").filter(Boolean)[0] ?? "in"
|
|
74
|
+
|
|
75
|
+
// biome-ignore lint/correctness/useExhaustiveDependencies: scroll to the newest line on every transcript change
|
|
76
|
+
useEffect(() => {
|
|
77
|
+
const list = listRef.current
|
|
78
|
+
if (list) {
|
|
79
|
+
list.scrollTop = list.scrollHeight
|
|
80
|
+
}
|
|
81
|
+
}, [messages, isLoading])
|
|
82
|
+
|
|
83
|
+
const handleSend = () => {
|
|
84
|
+
const text = input.trim()
|
|
85
|
+
if (!text || isLoading) {
|
|
86
|
+
return
|
|
87
|
+
}
|
|
88
|
+
setInput("")
|
|
89
|
+
clearError()
|
|
90
|
+
void sendMessage(text)
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
return (
|
|
94
|
+
<Dialog open onClose={onClose} className="relative z-[60]">
|
|
95
|
+
<DialogPanel
|
|
96
|
+
data-testid="ai-chat-panel"
|
|
97
|
+
className="fixed inset-0 flex flex-col bg-primary text-primary shadow-lg md:inset-auto md:bottom-6 md:right-6 md:h-[600px] md:max-h-[calc(100vh-3rem)] md:w-[400px] md:rounded-sm md:border"
|
|
98
|
+
>
|
|
99
|
+
<div className="flex items-center justify-between gap-2 border-b px-4 py-3">
|
|
100
|
+
<DialogTitle className="label-md uppercase">Assistant</DialogTitle>
|
|
101
|
+
<div className="flex items-center gap-3">
|
|
102
|
+
<button
|
|
103
|
+
type="button"
|
|
104
|
+
onClick={startNewChat}
|
|
105
|
+
className="text-xs text-secondary underline"
|
|
106
|
+
data-testid="ai-chat-new"
|
|
107
|
+
>
|
|
108
|
+
New chat
|
|
109
|
+
</button>
|
|
110
|
+
<button
|
|
111
|
+
type="button"
|
|
112
|
+
onClick={onClose}
|
|
113
|
+
aria-label="Close assistant"
|
|
114
|
+
data-testid="ai-chat-close"
|
|
115
|
+
>
|
|
116
|
+
<CloseIcon size={20} color="currentColor" />
|
|
117
|
+
</button>
|
|
118
|
+
</div>
|
|
119
|
+
</div>
|
|
120
|
+
|
|
121
|
+
<div
|
|
122
|
+
ref={listRef}
|
|
123
|
+
role="log"
|
|
124
|
+
aria-live="polite"
|
|
125
|
+
className="flex flex-1 flex-col gap-3 overflow-y-auto px-4 py-3"
|
|
126
|
+
>
|
|
127
|
+
{messages.length === 0 ? (
|
|
128
|
+
<div className="my-auto flex flex-col items-center gap-3 text-center">
|
|
129
|
+
<MessageIcon size={32} color="currentColor" />
|
|
130
|
+
<p className="text-sm text-secondary">
|
|
131
|
+
Ask about products, pricing, availability or anything in our catalogue.
|
|
132
|
+
</p>
|
|
133
|
+
<p className="text-xs text-secondary" data-testid="ai-chat-data-notice">
|
|
134
|
+
Messages are processed by an AI service. Please don't share personal details.{" "}
|
|
135
|
+
<Link href={`/${locale}/legal/privacy`} className="underline">
|
|
136
|
+
Privacy policy
|
|
137
|
+
</Link>
|
|
138
|
+
</p>
|
|
139
|
+
<div className="flex w-full flex-col gap-2">
|
|
140
|
+
{SUGGESTIONS.map((s) => (
|
|
141
|
+
<button
|
|
142
|
+
key={s}
|
|
143
|
+
type="button"
|
|
144
|
+
onClick={() => setInput(s)}
|
|
145
|
+
className="rounded-sm border px-3 py-2 text-left text-sm hover:bg-action-secondary-hover"
|
|
146
|
+
>
|
|
147
|
+
{s}
|
|
148
|
+
</button>
|
|
149
|
+
))}
|
|
150
|
+
</div>
|
|
151
|
+
</div>
|
|
152
|
+
) : (
|
|
153
|
+
messages.map((m) => <MessageBubble key={m.id} message={m} />)
|
|
154
|
+
)}
|
|
155
|
+
{isLoading && (
|
|
156
|
+
<p className="text-xs text-secondary" data-testid="ai-chat-typing">
|
|
157
|
+
Assistant is typing…
|
|
158
|
+
</p>
|
|
159
|
+
)}
|
|
160
|
+
</div>
|
|
161
|
+
|
|
162
|
+
{error && (
|
|
163
|
+
<div
|
|
164
|
+
role="alert"
|
|
165
|
+
className="mx-4 mb-2 flex items-start justify-between gap-2 rounded-sm border border-negative bg-negative-secondary px-3 py-2 text-xs text-negative"
|
|
166
|
+
>
|
|
167
|
+
<span>{error}</span>
|
|
168
|
+
<button type="button" onClick={clearError} aria-label="Dismiss error">
|
|
169
|
+
<CloseIcon size={14} color="currentColor" />
|
|
170
|
+
</button>
|
|
171
|
+
</div>
|
|
172
|
+
)}
|
|
173
|
+
|
|
174
|
+
<form
|
|
175
|
+
className="flex items-end gap-2 border-t px-3 py-3 pb-[calc(0.75rem+env(safe-area-inset-bottom,0px))]"
|
|
176
|
+
onSubmit={(e) => {
|
|
177
|
+
e.preventDefault()
|
|
178
|
+
handleSend()
|
|
179
|
+
}}
|
|
180
|
+
>
|
|
181
|
+
<textarea
|
|
182
|
+
autoFocus
|
|
183
|
+
value={input}
|
|
184
|
+
onChange={(e) => setInput(e.target.value)}
|
|
185
|
+
onKeyDown={(e) => {
|
|
186
|
+
if (e.key === "Enter" && !e.shiftKey) {
|
|
187
|
+
e.preventDefault()
|
|
188
|
+
handleSend()
|
|
189
|
+
}
|
|
190
|
+
}}
|
|
191
|
+
placeholder="Ask about products..."
|
|
192
|
+
aria-label="Message"
|
|
193
|
+
rows={1}
|
|
194
|
+
maxLength={CHAT_MESSAGE_MAX_LENGTH}
|
|
195
|
+
disabled={isLoading}
|
|
196
|
+
className="max-h-28 min-h-[40px] flex-1 resize-none rounded-sm border px-3 py-2 text-sm"
|
|
197
|
+
/>
|
|
198
|
+
{isLoading ? (
|
|
199
|
+
<button
|
|
200
|
+
type="button"
|
|
201
|
+
onClick={cancelMessage}
|
|
202
|
+
className="rounded-sm border px-3 py-2 text-sm"
|
|
203
|
+
data-testid="ai-chat-stop"
|
|
204
|
+
>
|
|
205
|
+
Stop
|
|
206
|
+
</button>
|
|
207
|
+
) : (
|
|
208
|
+
<button
|
|
209
|
+
type="submit"
|
|
210
|
+
disabled={!input.trim()}
|
|
211
|
+
className="rounded-sm bg-action px-3 py-2 text-sm text-action-on-primary disabled:bg-disabled disabled:text-disabled"
|
|
212
|
+
data-testid="ai-chat-send"
|
|
213
|
+
>
|
|
214
|
+
Send
|
|
215
|
+
</button>
|
|
216
|
+
)}
|
|
217
|
+
</form>
|
|
218
|
+
</DialogPanel>
|
|
219
|
+
</Dialog>
|
|
220
|
+
)
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
/**
|
|
224
|
+
* Floating AI assistant. Renders nothing unless AI_INTERFACE_URL (runtime) or
|
|
225
|
+
* NEXT_PUBLIC_AI_INTERFACE_URL (build) points at the artha-go ai-interface
|
|
226
|
+
* service; guests are allowed (anonymous per-tab identity).
|
|
227
|
+
*
|
|
228
|
+
* `className` positions the launcher: apps with their own fixed bottom bars
|
|
229
|
+
* (a sticky PDP action bar, a mini player) pass an offset for the pages that
|
|
230
|
+
* need it; the default sits in the bottom-right corner above page chrome.
|
|
231
|
+
*/
|
|
232
|
+
export function AiChatWidget({ className }: { className?: string }) {
|
|
233
|
+
const [open, setOpen] = useState(false)
|
|
234
|
+
const baseUrl = resolveAiInterfaceUrl()
|
|
235
|
+
if (!baseUrl) {
|
|
236
|
+
return null
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
return (
|
|
240
|
+
<>
|
|
241
|
+
{open && <ChatPanel baseUrl={baseUrl} onClose={() => setOpen(false)} />}
|
|
242
|
+
<button
|
|
243
|
+
type="button"
|
|
244
|
+
onClick={() => setOpen(true)}
|
|
245
|
+
aria-label="Open assistant"
|
|
246
|
+
data-testid="ai-chat-launcher"
|
|
247
|
+
className={cn(
|
|
248
|
+
"fixed right-4 bottom-[calc(1.5rem+env(safe-area-inset-bottom,0px))] z-[60] flex h-14 w-14 items-center justify-center rounded-full bg-action text-action-on-primary shadow-lg hover:bg-action-hover md:right-6",
|
|
249
|
+
className
|
|
250
|
+
)}
|
|
251
|
+
>
|
|
252
|
+
<MessageIcon size={24} color="currentColor" />
|
|
253
|
+
</button>
|
|
254
|
+
</>
|
|
255
|
+
)
|
|
256
|
+
}
|
|
@@ -1,47 +1,68 @@
|
|
|
1
1
|
"use client"
|
|
2
2
|
|
|
3
|
-
import { useEffect } from "react"
|
|
3
|
+
import { useEffect, useRef, useState } from "react"
|
|
4
4
|
|
|
5
5
|
import { FilterCheckboxOption, FilterSection } from "../../molecules"
|
|
6
6
|
import useFilters from "../../../hooks/useFilters"
|
|
7
|
+
import { CollapseIcon } from "../../../icons"
|
|
7
8
|
import { CERTIFICATION_TYPE_LABELS } from "../../../lib/helpers/certification-label"
|
|
8
9
|
import { registerFilterSection } from "../../../lib/helpers/filter-section-registry"
|
|
10
|
+
import type { CertificationType } from "../../../lib/helpers/parse-listing-controls"
|
|
11
|
+
import { cn } from "../../../lib/utils"
|
|
9
12
|
|
|
10
13
|
const CERTIFICATION_SECTION_ID = "certification"
|
|
11
14
|
|
|
15
|
+
// Beyond this many selections the trigger shows a count, not the labels, so a
|
|
16
|
+
// long selection cannot overflow the sidebar's width.
|
|
17
|
+
const MAX_LABELS_IN_TRIGGER = 2
|
|
18
|
+
|
|
12
19
|
/**
|
|
13
|
-
*
|
|
14
|
-
*
|
|
15
|
-
* (packages/modules/b2c-core/src/shared/certification/has-certification-filter.ts).
|
|
16
|
-
* The full ProductCertificationType has 10 values (also: iso, haccp, gmp,
|
|
17
|
-
* brc, other) -- deliberately not all shown here, matching the mockup.
|
|
20
|
+
* Multi-select certification dropdown. The options come from the caller (the
|
|
21
|
+
* storefront's industry decides them); an industry with none renders nothing.
|
|
18
22
|
*/
|
|
19
|
-
const SIDEBAR_CERTIFICATION_TYPES = ["fssai", "halal", "kosher", "organic", "vegan"] as const
|
|
20
|
-
|
|
21
|
-
type SidebarCertificationType = (typeof SIDEBAR_CERTIFICATION_TYPES)[number]
|
|
22
|
-
|
|
23
23
|
export function CertificationFilter({
|
|
24
|
+
certificationTypes,
|
|
24
25
|
certificationCounts,
|
|
25
26
|
searchTerm = "",
|
|
26
27
|
}: {
|
|
27
|
-
|
|
28
|
+
/** The industry's options -- see `getIndustryCertificationTypes`. */
|
|
29
|
+
certificationTypes: readonly CertificationType[]
|
|
30
|
+
certificationCounts?: Partial<Record<CertificationType, number>>
|
|
28
31
|
/** "Find a filter" substring match over certification labels, lifted from the sidebar. */
|
|
29
32
|
searchTerm?: string
|
|
30
33
|
}) {
|
|
31
34
|
const { isFilterActive, updateFilters } = useFilters("certification_type")
|
|
35
|
+
const [open, setOpen] = useState(false)
|
|
36
|
+
const containerRef = useRef<HTMLDivElement>(null)
|
|
37
|
+
const triggerRef = useRef<HTMLButtonElement>(null)
|
|
32
38
|
|
|
33
|
-
//
|
|
34
|
-
//
|
|
39
|
+
// Not an Accordion: an active chip's reveal opens the dropdown and scrolls
|
|
40
|
+
// the section into view.
|
|
35
41
|
useEffect(() => {
|
|
36
42
|
return registerFilterSection(CERTIFICATION_SECTION_ID, () => {
|
|
43
|
+
setOpen(true)
|
|
37
44
|
document
|
|
38
45
|
.getElementById(CERTIFICATION_SECTION_ID)
|
|
39
46
|
?.scrollIntoView({ behavior: "smooth", block: "center" })
|
|
40
47
|
})
|
|
41
48
|
}, [])
|
|
42
49
|
|
|
50
|
+
useEffect(() => {
|
|
51
|
+
if (!open) return
|
|
52
|
+
const closeOnOutsideClick = (event: MouseEvent) => {
|
|
53
|
+
if (!containerRef.current?.contains(event.target as Node)) {
|
|
54
|
+
setOpen(false)
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
document.addEventListener("mousedown", closeOnOutsideClick)
|
|
58
|
+
return () => document.removeEventListener("mousedown", closeOnOutsideClick)
|
|
59
|
+
}, [open])
|
|
60
|
+
|
|
43
61
|
const query = searchTerm.trim().toLowerCase()
|
|
44
|
-
|
|
62
|
+
// While the shopper is searching filters, show the matches rather than hide
|
|
63
|
+
// them inside a closed dropdown.
|
|
64
|
+
const isOpen = open || query !== ""
|
|
65
|
+
const visibleTypes = certificationTypes.filter(
|
|
45
66
|
(type) => !query || CERTIFICATION_TYPE_LABELS[type].toLowerCase().includes(query)
|
|
46
67
|
)
|
|
47
68
|
|
|
@@ -49,26 +70,79 @@ export function CertificationFilter({
|
|
|
49
70
|
return null
|
|
50
71
|
}
|
|
51
72
|
|
|
73
|
+
// Summarise only types this industry offers: a stale `?certification_type=`
|
|
74
|
+
// from another industry must not show as a selection the shopper cannot see.
|
|
75
|
+
const selectedLabels = certificationTypes
|
|
76
|
+
.filter((type) => isFilterActive(type))
|
|
77
|
+
.map((type) => CERTIFICATION_TYPE_LABELS[type])
|
|
78
|
+
const summary =
|
|
79
|
+
selectedLabels.length === 0
|
|
80
|
+
? "Select certifications"
|
|
81
|
+
: selectedLabels.length <= MAX_LABELS_IN_TRIGGER
|
|
82
|
+
? selectedLabels.join(", ")
|
|
83
|
+
: `${selectedLabels.length} selected`
|
|
84
|
+
|
|
52
85
|
return (
|
|
53
86
|
<FilterSection heading="Certification" id={CERTIFICATION_SECTION_ID}>
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
87
|
+
<div
|
|
88
|
+
ref={containerRef}
|
|
89
|
+
// On the container, not the panel: after opening by keyboard, focus is
|
|
90
|
+
// still on the trigger, and Escape must close from there too.
|
|
91
|
+
onKeyDown={(event) => {
|
|
92
|
+
if (event.key === "Escape" && open) {
|
|
93
|
+
setOpen(false)
|
|
94
|
+
triggerRef.current?.focus()
|
|
95
|
+
}
|
|
96
|
+
}}
|
|
97
|
+
>
|
|
98
|
+
<button
|
|
99
|
+
ref={triggerRef}
|
|
100
|
+
type="button"
|
|
101
|
+
onClick={() => setOpen((wasOpen) => !wasOpen)}
|
|
102
|
+
aria-expanded={isOpen}
|
|
103
|
+
aria-controls={isOpen ? "certification-options" : undefined}
|
|
104
|
+
className={cn(
|
|
105
|
+
"flex h-9 w-full items-center justify-between gap-2 rounded-[9px] border border-primary px-3 text-left text-[13px]",
|
|
106
|
+
"focus:border-brand-700 focus:outline-none",
|
|
107
|
+
selectedLabels.length > 0 ? "font-semibold text-primary" : "text-neutral-500"
|
|
108
|
+
)}
|
|
109
|
+
data-testid="filter-certification-trigger"
|
|
110
|
+
>
|
|
111
|
+
<span className="truncate">{summary}</span>
|
|
112
|
+
<CollapseIcon
|
|
113
|
+
size={16}
|
|
114
|
+
className={cn("shrink-0 transition-transform duration-200", isOpen && "rotate-180")}
|
|
69
115
|
/>
|
|
70
|
-
|
|
71
|
-
|
|
116
|
+
</button>
|
|
117
|
+
{isOpen && (
|
|
118
|
+
<div
|
|
119
|
+
id="certification-options"
|
|
120
|
+
role="group"
|
|
121
|
+
aria-label="Certification"
|
|
122
|
+
className="mt-1.5 flex max-h-56 flex-col gap-0.5 overflow-y-auto overscroll-contain rounded-[9px] border border-primary bg-primary px-2.5 py-1.5"
|
|
123
|
+
data-testid="filter-certification-panel"
|
|
124
|
+
>
|
|
125
|
+
{visibleTypes.map((type) => {
|
|
126
|
+
const checked = isFilterActive(type)
|
|
127
|
+
const amount = certificationCounts?.[type]
|
|
128
|
+
return (
|
|
129
|
+
<FilterCheckboxOption
|
|
130
|
+
key={type}
|
|
131
|
+
label={CERTIFICATION_TYPE_LABELS[type]}
|
|
132
|
+
checked={checked}
|
|
133
|
+
onCheck={() => updateFilters(type)}
|
|
134
|
+
amount={amount}
|
|
135
|
+
// A zero-count option leads to an empty result, so it is not
|
|
136
|
+
// selectable -- unless already selected (the buyer must be able
|
|
137
|
+
// to untick it). Unknown counts (facets not loaded) never disable.
|
|
138
|
+
disabled={amount === 0 && !checked}
|
|
139
|
+
data-testid={`filter-certification-${type}`}
|
|
140
|
+
/>
|
|
141
|
+
)
|
|
142
|
+
})}
|
|
143
|
+
</div>
|
|
144
|
+
)}
|
|
145
|
+
</div>
|
|
72
146
|
</FilterSection>
|
|
73
147
|
)
|
|
74
148
|
}
|
|
@@ -19,6 +19,7 @@ import { categoriesMirrorApplications } from '../../../lib/helpers/categories-mi
|
|
|
19
19
|
import { type FlatCategoryLike } from '../../../lib/helpers/category-tree';
|
|
20
20
|
import { registerFilterSection } from '../../../lib/helpers/filter-section-registry';
|
|
21
21
|
import { isCategoriesCollectionsBrowseMode } from '../../../lib/storefront/browse-nav-flags';
|
|
22
|
+
import { getIndustryCertificationTypes } from '../../../lib/storefront/industry-certifications';
|
|
22
23
|
import { cn } from '../../../lib/utils';
|
|
23
24
|
|
|
24
25
|
interface ProductSidebarProps {
|
|
@@ -64,11 +65,13 @@ export const ProductSidebar = ({
|
|
|
64
65
|
// Category filter is redundant with the Application filter — hide it.
|
|
65
66
|
// In categories-collections browse mode there is no Application filter, so
|
|
66
67
|
// never hide Category on that basis.
|
|
67
|
-
// Davison (categories-collections) is apparel: Size replaces Certification
|
|
68
|
-
// (
|
|
68
|
+
// Davison (categories-collections) is apparel: Size replaces Certification.
|
|
69
|
+
// Which certifications show (if any) is decided by the storefront's industry,
|
|
70
|
+
// not hardcoded -- FSSAI/Halal are food facets, ISO/GMP/BRC are polymer ones.
|
|
69
71
|
const hideApplicationFilter = isCategoriesCollectionsBrowseMode()
|
|
70
72
|
const showApparelSizeFilter = hideApplicationFilter
|
|
71
|
-
|
|
73
|
+
// categories-collections (apparel) never shows them, even if the industry env is unset.
|
|
74
|
+
const certificationTypes = hideApplicationFilter ? [] : getIndustryCertificationTypes()
|
|
72
75
|
const hideCategoryFilter =
|
|
73
76
|
!hideApplicationFilter &&
|
|
74
77
|
categoriesMirrorApplications(
|
|
@@ -191,8 +194,9 @@ export const ProductSidebar = ({
|
|
|
191
194
|
{showApparelSizeFilter && (
|
|
192
195
|
<SizeFilter searchTerm={findFilterTerm} />
|
|
193
196
|
)}
|
|
194
|
-
{
|
|
197
|
+
{certificationTypes.length > 0 && (
|
|
195
198
|
<CertificationFilter
|
|
199
|
+
certificationTypes={certificationTypes}
|
|
196
200
|
certificationCounts={facetCounts?.certification}
|
|
197
201
|
searchTerm={findFilterTerm}
|
|
198
202
|
/>
|
|
@@ -12,11 +12,11 @@ import { CATEGORY_PAGE_SIZE, PRODUCT_LIMIT } from "../../../const"
|
|
|
12
12
|
* Facets the sidebar renders counts for. Requested only on the two routes that
|
|
13
13
|
* can compute them; the core `/store/products` branch below cannot, so that
|
|
14
14
|
* listing renders the controls without counts rather than zeros it never
|
|
15
|
-
* measured.
|
|
16
|
-
*
|
|
15
|
+
* measured. An industry with no certifications (apparel, ...) omits
|
|
16
|
+
* `certification`, since the Certification sidebar section is hidden there.
|
|
17
17
|
*/
|
|
18
18
|
const LISTING_FACETS_DEFAULT = ["has_price", "has_sample", "certification"] as const
|
|
19
|
-
const
|
|
19
|
+
const LISTING_FACETS_NO_CERTIFICATION = ["has_price", "has_sample"] as const
|
|
20
20
|
import { listApplicationCategories, listApplications, listSellerApplications } from "../../../lib/data/applications"
|
|
21
21
|
import { getCategoryNamesByIds, listCategoryTreePage } from "../../../lib/data/categories"
|
|
22
22
|
import { getMusicCategoryIds } from "../../../lib/data/music-categories"
|
|
@@ -27,6 +27,7 @@ import {
|
|
|
27
27
|
} from "../../../lib/data/products"
|
|
28
28
|
import { CERTIFICATION_TYPE_LABELS } from "../../../lib/helpers/certification-label"
|
|
29
29
|
import { isCategoriesCollectionsBrowseMode } from "../../../lib/storefront/browse-nav-flags"
|
|
30
|
+
import { getIndustryCertificationTypes } from "../../../lib/storefront/industry-certifications"
|
|
30
31
|
import { isMusicOnlyCatalogEnabled } from "../../../lib/streaming/streaming-feature-flags"
|
|
31
32
|
import type { SortOptions } from "../../../types/product"
|
|
32
33
|
|
|
@@ -121,12 +122,19 @@ export const ProductListing = async ({
|
|
|
121
122
|
const priceMode =
|
|
122
123
|
sort === "price_asc" || sort === "price_desc" || minPrice != null || maxPrice != null
|
|
123
124
|
|
|
124
|
-
//
|
|
125
|
-
//
|
|
126
|
-
//
|
|
125
|
+
// Certification is industry-specific: only the types this storefront's
|
|
126
|
+
// industry offers may narrow the catalog, show a chip, or be counted. A
|
|
127
|
+
// stale or shared `?certification_type=halal` on a polymer store is dropped
|
|
128
|
+
// here, so the results, the chips and the dropdown always agree. Apparel
|
|
129
|
+
// (categories-collections) offers none.
|
|
127
130
|
const isApparelBrowse = isCategoriesCollectionsBrowseMode()
|
|
128
|
-
const
|
|
129
|
-
const
|
|
131
|
+
const industryCertificationTypes = isApparelBrowse ? [] : getIndustryCertificationTypes()
|
|
132
|
+
const effectiveCertificationTypes =
|
|
133
|
+
industryCertificationTypes.length === 0
|
|
134
|
+
? undefined
|
|
135
|
+
: certificationTypes?.filter((type) => (industryCertificationTypes as readonly string[]).includes(type))
|
|
136
|
+
const listingFacets =
|
|
137
|
+
industryCertificationTypes.length > 0 ? [...LISTING_FACETS_DEFAULT] : [...LISTING_FACETS_NO_CERTIFICATION]
|
|
130
138
|
const hasCertificationFilter = (effectiveCertificationTypes?.length ?? 0) > 0
|
|
131
139
|
const hasSizeFilter = (sizes?.length ?? 0) > 0
|
|
132
140
|
// A blank/whitespace-only term is "no search", not a filter for "" -- the
|
|
@@ -154,6 +162,7 @@ export const ProductListing = async ({
|
|
|
154
162
|
certificationTypes: effectiveCertificationTypes,
|
|
155
163
|
sizes,
|
|
156
164
|
listingFacets,
|
|
165
|
+
certificationFacetTypes: industryCertificationTypes,
|
|
157
166
|
})
|
|
158
167
|
: (hasApplicationFilter ||
|
|
159
168
|
hasSample ||
|
|
@@ -182,6 +191,7 @@ export const ProductListing = async ({
|
|
|
182
191
|
certificationTypes: effectiveCertificationTypes,
|
|
183
192
|
sizes,
|
|
184
193
|
listingFacets,
|
|
194
|
+
certificationFacetTypes: industryCertificationTypes,
|
|
185
195
|
})
|
|
186
196
|
: listProductsWithSort({
|
|
187
197
|
page: safePage,
|
|
@@ -296,9 +306,16 @@ export const ProductListing = async ({
|
|
|
296
306
|
: {}),
|
|
297
307
|
...(Object.keys(categoryNames).length > 0 ? { category_id: categoryNames } : {}),
|
|
298
308
|
// Static map, not resolved per-request: certification_type's URL values
|
|
299
|
-
// are enum slugs, not ids, so every label is already known up front.
|
|
300
|
-
//
|
|
301
|
-
|
|
309
|
+
// are enum slugs, not ids, so every label is already known up front. Only
|
|
310
|
+
// this industry's types get labels; a chip with no label is hidden, so an
|
|
311
|
+
// out-of-industry value in the URL never shows as a selection.
|
|
312
|
+
...(industryCertificationTypes.length > 0
|
|
313
|
+
? {
|
|
314
|
+
certification_type: Object.fromEntries(
|
|
315
|
+
industryCertificationTypes.map((type) => [type, CERTIFICATION_TYPE_LABELS[type]])
|
|
316
|
+
),
|
|
317
|
+
}
|
|
318
|
+
: {}),
|
|
302
319
|
}
|
|
303
320
|
|
|
304
321
|
return (
|
|
@@ -0,0 +1,305 @@
|
|
|
1
|
+
// Web port of apps/opticomm-mobile/lib/chat-api.ts. Transport is the SDK's
|
|
2
|
+
// `chat` namespace (artha-go `packages/artha-sdk/src/chat.ts`); this module
|
|
3
|
+
// owns only the client policy on top of it: retries, request timeout and the
|
|
4
|
+
// acknowledged poll loop.
|
|
5
|
+
|
|
6
|
+
import { AiInterfaceError, createChat } from "@sgflabs/artha-go-sdk"
|
|
7
|
+
|
|
8
|
+
import { readStorefrontRuntimePublic } from "../runtime/public-storefront-runtime-env"
|
|
9
|
+
|
|
10
|
+
/** Composer cap, the mobile app's convention; the service itself caps nothing shorter than the model context. */
|
|
11
|
+
export const CHAT_MESSAGE_MAX_LENGTH = 500
|
|
12
|
+
const REQUEST_TIMEOUT_MS = 15_000
|
|
13
|
+
const ENQUEUE_MAX_ATTEMPTS = 3
|
|
14
|
+
const ENQUEUE_BACKOFF_MS = 300
|
|
15
|
+
const DEFAULT_POLL_TIMEOUT_MS = 90_000
|
|
16
|
+
const DEFAULT_POLL_INTERVAL_MS = 1_000
|
|
17
|
+
const HTTP_FORBIDDEN = 403
|
|
18
|
+
const HTTP_REQUEST_TIMEOUT = 408
|
|
19
|
+
const HTTP_TOO_MANY_REQUESTS = 429
|
|
20
|
+
const HTTP_SERVER_ERROR_MIN = 500
|
|
21
|
+
|
|
22
|
+
export type { ChatReply } from "@sgflabs/artha-go-sdk"
|
|
23
|
+
|
|
24
|
+
import type { ChatReply } from "@sgflabs/artha-go-sdk"
|
|
25
|
+
|
|
26
|
+
export class ChatAbortedError extends Error {
|
|
27
|
+
constructor() {
|
|
28
|
+
super("Aborted")
|
|
29
|
+
this.name = "ChatAbortedError"
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* /api/chat/poll answered 403: the poll token is no longer known server-side.
|
|
35
|
+
* The message was already queued, and its tools (cart, order) may have run,
|
|
36
|
+
* so the turn is not resent: the buyer decides after checking.
|
|
37
|
+
*/
|
|
38
|
+
export class ChatPollTokenInvalidError extends Error {
|
|
39
|
+
constructor() {
|
|
40
|
+
super(
|
|
41
|
+
"Your session expired before the reply arrived. Anything you asked for may still have gone through, so please check your cart before sending again."
|
|
42
|
+
)
|
|
43
|
+
this.name = "ChatPollTokenInvalidError"
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/** Opaque 32-hex id. `randomUUID` exists only in secure contexts, so plain-http dev hosts take the second path. */
|
|
48
|
+
export function newMessageId() {
|
|
49
|
+
if (typeof crypto.randomUUID === "function") {
|
|
50
|
+
return crypto.randomUUID().replace(/-/g, "")
|
|
51
|
+
}
|
|
52
|
+
return Array.from(crypto.getRandomValues(new Uint8Array(16)), (b) =>
|
|
53
|
+
b.toString(16).padStart(2, "0")
|
|
54
|
+
).join("")
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* Base URL of the ai-interface service, or undefined when the widget must stay
|
|
59
|
+
* off. Fails closed on anything that is not an absolute http(s) URL so a
|
|
60
|
+
* mis-set variable cannot turn into a request to a relative path or a
|
|
61
|
+
* `javascript:` scheme.
|
|
62
|
+
*/
|
|
63
|
+
export function resolveAiInterfaceUrl() {
|
|
64
|
+
const raw = readStorefrontRuntimePublic("NEXT_PUBLIC_AI_INTERFACE_URL")
|
|
65
|
+
if (!raw) {
|
|
66
|
+
return undefined
|
|
67
|
+
}
|
|
68
|
+
try {
|
|
69
|
+
const url = new URL(raw)
|
|
70
|
+
if (url.protocol !== "https:" && url.protocol !== "http:") {
|
|
71
|
+
return undefined
|
|
72
|
+
}
|
|
73
|
+
return raw.replace(/\/+$/, "")
|
|
74
|
+
} catch {
|
|
75
|
+
return undefined
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
const chatClients = new Map<string, ReturnType<typeof createChat>>()
|
|
80
|
+
|
|
81
|
+
/** The SDK chat namespace for an ai-interface URL (runtime config, so not the shared `opticommSdk`). */
|
|
82
|
+
export function chatFor(aiInterfaceUrl: string) {
|
|
83
|
+
let chat = chatClients.get(aiInterfaceUrl)
|
|
84
|
+
if (!chat) {
|
|
85
|
+
chat = createChat(aiInterfaceUrl)
|
|
86
|
+
chatClients.set(aiInterfaceUrl, chat)
|
|
87
|
+
}
|
|
88
|
+
return chat
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
function isTransientStatus(status: number | undefined) {
|
|
92
|
+
return (
|
|
93
|
+
status === HTTP_REQUEST_TIMEOUT ||
|
|
94
|
+
status === HTTP_TOO_MANY_REQUESTS ||
|
|
95
|
+
(status !== undefined && status >= HTTP_SERVER_ERROR_MIN)
|
|
96
|
+
)
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/** Network failure (fetch rejects with a TypeError), our own timeout (an AbortError), or a transient status. */
|
|
100
|
+
function isTransientError(err: unknown) {
|
|
101
|
+
if (err instanceof AiInterfaceError) {
|
|
102
|
+
return isTransientStatus(err.status)
|
|
103
|
+
}
|
|
104
|
+
return err instanceof TypeError || (err instanceof DOMException && err.name === "AbortError")
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/** Waits `ms`, or less if `signal` aborts first. */
|
|
108
|
+
const sleep = (ms: number, signal?: AbortSignal) =>
|
|
109
|
+
new Promise<void>((resolve) => {
|
|
110
|
+
const timer = setTimeout(() => {
|
|
111
|
+
signal?.removeEventListener("abort", onAbort)
|
|
112
|
+
resolve()
|
|
113
|
+
}, ms)
|
|
114
|
+
function onAbort() {
|
|
115
|
+
clearTimeout(timer)
|
|
116
|
+
resolve()
|
|
117
|
+
}
|
|
118
|
+
signal?.addEventListener("abort", onAbort, { once: true })
|
|
119
|
+
})
|
|
120
|
+
|
|
121
|
+
/** Runs one SDK call with the request timeout, mapping the caller's abort to ChatAbortedError. */
|
|
122
|
+
async function withTimeout<T>(call: (signal: AbortSignal) => Promise<T>, signal?: AbortSignal) {
|
|
123
|
+
if (signal?.aborted) {
|
|
124
|
+
throw new ChatAbortedError()
|
|
125
|
+
}
|
|
126
|
+
const controller = new AbortController()
|
|
127
|
+
const timer = setTimeout(() => controller.abort(), REQUEST_TIMEOUT_MS)
|
|
128
|
+
const onAbort = () => controller.abort()
|
|
129
|
+
signal?.addEventListener("abort", onAbort)
|
|
130
|
+
try {
|
|
131
|
+
return await call(controller.signal)
|
|
132
|
+
} catch (err) {
|
|
133
|
+
if (signal?.aborted) {
|
|
134
|
+
throw new ChatAbortedError()
|
|
135
|
+
}
|
|
136
|
+
throw err
|
|
137
|
+
} finally {
|
|
138
|
+
clearTimeout(timer)
|
|
139
|
+
signal?.removeEventListener("abort", onAbort)
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
export async function enqueueChat(
|
|
144
|
+
baseUrl: string,
|
|
145
|
+
userId: string,
|
|
146
|
+
message: string,
|
|
147
|
+
messageId: string,
|
|
148
|
+
previousPollToken: string | undefined,
|
|
149
|
+
signal?: AbortSignal
|
|
150
|
+
) {
|
|
151
|
+
const body = {
|
|
152
|
+
user_id: userId,
|
|
153
|
+
message,
|
|
154
|
+
provider: "web" as const,
|
|
155
|
+
time: Date.now(),
|
|
156
|
+
// ai-interface round-trips `extra.messageId`, which lets the poll reject
|
|
157
|
+
// replies to earlier turns. (It strips any client-sent conversation sid.)
|
|
158
|
+
extra: { messageId },
|
|
159
|
+
// Proves this caller owns the active session for userId.
|
|
160
|
+
poll_token: previousPollToken,
|
|
161
|
+
}
|
|
162
|
+
const chat = chatFor(baseUrl)
|
|
163
|
+
let lastError: unknown
|
|
164
|
+
for (let attempt = 0; attempt < ENQUEUE_MAX_ATTEMPTS; attempt += 1) {
|
|
165
|
+
try {
|
|
166
|
+
const { poll_token } = await withTimeout((s) => chat.enqueue(body, { signal: s }), signal)
|
|
167
|
+
return { pollToken: poll_token }
|
|
168
|
+
} catch (err) {
|
|
169
|
+
if (!isTransientError(err)) {
|
|
170
|
+
throw err
|
|
171
|
+
}
|
|
172
|
+
lastError = err
|
|
173
|
+
// Back off so three attempts do not re-hit the enqueue throttle at once.
|
|
174
|
+
await sleep(ENQUEUE_BACKOFF_MS * 2 ** attempt, signal)
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
throw lastError
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
/**
|
|
181
|
+
* `lastMessageId` is the reply this caller already holds: the cursor that makes
|
|
182
|
+
* delivery acknowledged rather than destructive. Sending it keeps the reply in
|
|
183
|
+
* the server's inbox until it is named, so a response lost in flight is
|
|
184
|
+
* re-delivered on the next poll instead of dropped with the turn.
|
|
185
|
+
*/
|
|
186
|
+
export async function pollForReply(
|
|
187
|
+
baseUrl: string,
|
|
188
|
+
userId: string,
|
|
189
|
+
pollToken: string,
|
|
190
|
+
expectedMessageId: string,
|
|
191
|
+
{
|
|
192
|
+
timeoutMs = DEFAULT_POLL_TIMEOUT_MS,
|
|
193
|
+
intervalMs = DEFAULT_POLL_INTERVAL_MS,
|
|
194
|
+
signal,
|
|
195
|
+
lastMessageId = "",
|
|
196
|
+
}: {
|
|
197
|
+
timeoutMs?: number
|
|
198
|
+
intervalMs?: number
|
|
199
|
+
signal?: AbortSignal
|
|
200
|
+
lastMessageId?: string
|
|
201
|
+
} = {}
|
|
202
|
+
) {
|
|
203
|
+
const chat = chatFor(baseUrl)
|
|
204
|
+
const pollOnce = (cursor: string) =>
|
|
205
|
+
withTimeout(
|
|
206
|
+
(s) =>
|
|
207
|
+
chat.poll(
|
|
208
|
+
{ user_id: userId, poll_token: pollToken, last_message_id: cursor },
|
|
209
|
+
{ signal: s }
|
|
210
|
+
),
|
|
211
|
+
signal
|
|
212
|
+
)
|
|
213
|
+
let cursor = lastMessageId
|
|
214
|
+
// The cursor the most recent request actually carried; see the flush below.
|
|
215
|
+
let sentCursor = lastMessageId
|
|
216
|
+
const deadline = Date.now() + timeoutMs
|
|
217
|
+
while (Date.now() < deadline) {
|
|
218
|
+
if (signal?.aborted) {
|
|
219
|
+
throw new ChatAbortedError()
|
|
220
|
+
}
|
|
221
|
+
await sleep(intervalMs, signal)
|
|
222
|
+
if (signal?.aborted) {
|
|
223
|
+
throw new ChatAbortedError()
|
|
224
|
+
}
|
|
225
|
+
sentCursor = cursor
|
|
226
|
+
let body: ChatReply | null
|
|
227
|
+
try {
|
|
228
|
+
body = await pollOnce(cursor)
|
|
229
|
+
} catch (err) {
|
|
230
|
+
if (err instanceof AiInterfaceError && err.status === HTTP_FORBIDDEN) {
|
|
231
|
+
throw new ChatPollTokenInvalidError()
|
|
232
|
+
}
|
|
233
|
+
if (isTransientError(err)) {
|
|
234
|
+
continue
|
|
235
|
+
}
|
|
236
|
+
throw err
|
|
237
|
+
}
|
|
238
|
+
if (!body || body.message === undefined) {
|
|
239
|
+
continue
|
|
240
|
+
}
|
|
241
|
+
if (typeof body.message !== "string") {
|
|
242
|
+
throw new Error("Chat returned non-string message")
|
|
243
|
+
}
|
|
244
|
+
if (body.extra?.messageId !== expectedMessageId) {
|
|
245
|
+
// A reply to an earlier turn. Acknowledge it so it stops heading the
|
|
246
|
+
// inbox, otherwise every later poll returns it again.
|
|
247
|
+
if (typeof body.message_id === "string" && body.message_id !== "") {
|
|
248
|
+
cursor = body.message_id
|
|
249
|
+
}
|
|
250
|
+
continue
|
|
251
|
+
}
|
|
252
|
+
return body
|
|
253
|
+
}
|
|
254
|
+
// A stale reply learned on the last pass advanced the cursor with no request
|
|
255
|
+
// left to carry it. Flush it once, best effort, so it does not stall the
|
|
256
|
+
// next turn too.
|
|
257
|
+
if (cursor !== sentCursor && !signal?.aborted) {
|
|
258
|
+
try {
|
|
259
|
+
await pollOnce(cursor)
|
|
260
|
+
} catch {
|
|
261
|
+
// The next turn re-acknowledges what this missed.
|
|
262
|
+
}
|
|
263
|
+
}
|
|
264
|
+
throw new Error("Chat timed out — please try again")
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
/**
|
|
268
|
+
* `onEnqueued` fires with each poll token the service mints, before polling
|
|
269
|
+
* starts. Every enqueue rotates the token and the service accepts only the
|
|
270
|
+
* current or previous one, so a caller that persists the token only after the
|
|
271
|
+
* reply loses the session after two stopped turns in a row.
|
|
272
|
+
*/
|
|
273
|
+
export async function completeChatTurn(
|
|
274
|
+
baseUrl: string,
|
|
275
|
+
userId: string,
|
|
276
|
+
message: string,
|
|
277
|
+
messageId: string,
|
|
278
|
+
previousPollToken: string | undefined,
|
|
279
|
+
signal?: AbortSignal,
|
|
280
|
+
pollOptions?: {
|
|
281
|
+
timeoutMs?: number
|
|
282
|
+
intervalMs?: number
|
|
283
|
+
lastMessageId?: string
|
|
284
|
+
onEnqueued?: (pollToken: string) => void
|
|
285
|
+
}
|
|
286
|
+
) {
|
|
287
|
+
const { pollToken } = await enqueueChat(
|
|
288
|
+
baseUrl,
|
|
289
|
+
userId,
|
|
290
|
+
message,
|
|
291
|
+
messageId,
|
|
292
|
+
previousPollToken,
|
|
293
|
+
signal
|
|
294
|
+
)
|
|
295
|
+
pollOptions?.onEnqueued?.(pollToken)
|
|
296
|
+
// A poll 403 is not retried by re-enqueueing: the queued turn may already
|
|
297
|
+
// have run its tools, and the state that would let the service replay it
|
|
298
|
+
// (replay key, BullMQ job id) lives in the same store whose loss causes
|
|
299
|
+
// the 403. ChatPollTokenInvalidError tells the buyer to check first.
|
|
300
|
+
const reply = await pollForReply(baseUrl, userId, pollToken, messageId, {
|
|
301
|
+
...pollOptions,
|
|
302
|
+
signal,
|
|
303
|
+
})
|
|
304
|
+
return { pollToken, reply }
|
|
305
|
+
}
|
|
@@ -0,0 +1,194 @@
|
|
|
1
|
+
"use client"
|
|
2
|
+
|
|
3
|
+
// Web port of apps/opticomm-mobile/context/chat-context.tsx. One hook instead
|
|
4
|
+
// of a provider: the widget is mounted once per page. Identity lives in
|
|
5
|
+
// sessionStorage (per tab, gone when the tab closes), so a guest's
|
|
6
|
+
// conversation never outlives their visit and never follows another person
|
|
7
|
+
// using the same browser profile.
|
|
8
|
+
|
|
9
|
+
import { AiInterfaceError } from "@sgflabs/artha-go-sdk"
|
|
10
|
+
import { useCallback, useRef, useState } from "react"
|
|
11
|
+
|
|
12
|
+
import * as chatApi from "./ai-chat-api"
|
|
13
|
+
|
|
14
|
+
export type ChatMessage = {
|
|
15
|
+
// 'notice' is a client-side system line (the identity reset below), never a
|
|
16
|
+
// turn sent to or from the model.
|
|
17
|
+
role: "user" | "assistant" | "notice"
|
|
18
|
+
content: string
|
|
19
|
+
id: string
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* `lastReplyId` is the reply this tab already took delivery of: the cursor the
|
|
24
|
+
* poll acknowledges with. It belongs with the identity because it is scoped to
|
|
25
|
+
* `userId`'s inbox; a reset identity starts with an empty one.
|
|
26
|
+
*/
|
|
27
|
+
type ChatIdentity = {
|
|
28
|
+
userId: string
|
|
29
|
+
pollToken?: string
|
|
30
|
+
lastReplyId?: string
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export const CHAT_IDENTITY_KEY = "ai_chat_identity"
|
|
34
|
+
|
|
35
|
+
export const IDENTITY_RESET_NOTICE =
|
|
36
|
+
"Your session expired, so the conversation context was reset. Earlier messages are still shown, but the assistant no longer remembers them."
|
|
37
|
+
|
|
38
|
+
// sessionStorage can throw (private mode, blocked storage). Fall back to this
|
|
39
|
+
// tab's memory so the chat still works for the page's lifetime.
|
|
40
|
+
let memoryIdentity: ChatIdentity | undefined
|
|
41
|
+
|
|
42
|
+
function readIdentity(): ChatIdentity | undefined {
|
|
43
|
+
try {
|
|
44
|
+
const stored = window.sessionStorage.getItem(CHAT_IDENTITY_KEY)
|
|
45
|
+
if (!stored) {
|
|
46
|
+
return memoryIdentity
|
|
47
|
+
}
|
|
48
|
+
const parsed: unknown = JSON.parse(stored)
|
|
49
|
+
if (
|
|
50
|
+
parsed &&
|
|
51
|
+
typeof parsed === "object" &&
|
|
52
|
+
typeof (parsed as ChatIdentity).userId === "string"
|
|
53
|
+
) {
|
|
54
|
+
return parsed as ChatIdentity
|
|
55
|
+
}
|
|
56
|
+
} catch {
|
|
57
|
+
// Unreadable or unparsable: treat as absent.
|
|
58
|
+
}
|
|
59
|
+
return memoryIdentity
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
function writeIdentity(identity: ChatIdentity | undefined): void {
|
|
63
|
+
memoryIdentity = identity
|
|
64
|
+
try {
|
|
65
|
+
if (identity) {
|
|
66
|
+
window.sessionStorage.setItem(CHAT_IDENTITY_KEY, JSON.stringify(identity))
|
|
67
|
+
} else {
|
|
68
|
+
window.sessionStorage.removeItem(CHAT_IDENTITY_KEY)
|
|
69
|
+
}
|
|
70
|
+
} catch {
|
|
71
|
+
// Memory copy above is the fallback.
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
function getOrCreateIdentity(): ChatIdentity {
|
|
76
|
+
const existing = readIdentity()
|
|
77
|
+
if (existing) {
|
|
78
|
+
return existing
|
|
79
|
+
}
|
|
80
|
+
const identity = { userId: chatApi.newMessageId() }
|
|
81
|
+
writeIdentity(identity)
|
|
82
|
+
return identity
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
export function useAiChat(baseUrl: string) {
|
|
86
|
+
const [messages, setMessages] = useState<ChatMessage[]>([])
|
|
87
|
+
const [isLoading, setIsLoading] = useState(false)
|
|
88
|
+
const [error, setError] = useState<string | null>(null)
|
|
89
|
+
const sendAbortRef = useRef<AbortController | null>(null)
|
|
90
|
+
|
|
91
|
+
const sendMessage = useCallback(
|
|
92
|
+
async (content: string) => {
|
|
93
|
+
sendAbortRef.current?.abort()
|
|
94
|
+
const controller = new AbortController()
|
|
95
|
+
sendAbortRef.current = controller
|
|
96
|
+
const messageId = chatApi.newMessageId()
|
|
97
|
+
const dropOptimistic = () => setMessages((prev) => prev.filter((m) => m.id !== messageId))
|
|
98
|
+
|
|
99
|
+
try {
|
|
100
|
+
setIsLoading(true)
|
|
101
|
+
setError(null)
|
|
102
|
+
setMessages((prev) => [...prev, { role: "user", content, id: messageId }])
|
|
103
|
+
|
|
104
|
+
let identity = getOrCreateIdentity()
|
|
105
|
+
// Persist each minted token at once: see completeChatTurn's onEnqueued.
|
|
106
|
+
const keepToken = (pollToken: string) => {
|
|
107
|
+
// New chat mid-enqueue already dropped this identity; do not write it back.
|
|
108
|
+
if (controller.signal.aborted) {
|
|
109
|
+
return
|
|
110
|
+
}
|
|
111
|
+
identity = { ...identity, pollToken }
|
|
112
|
+
writeIdentity(identity)
|
|
113
|
+
}
|
|
114
|
+
let turn: Awaited<ReturnType<typeof chatApi.completeChatTurn>>
|
|
115
|
+
try {
|
|
116
|
+
turn = await chatApi.completeChatTurn(
|
|
117
|
+
baseUrl,
|
|
118
|
+
identity.userId,
|
|
119
|
+
content,
|
|
120
|
+
messageId,
|
|
121
|
+
identity.pollToken,
|
|
122
|
+
controller.signal,
|
|
123
|
+
{ lastMessageId: identity.lastReplyId ?? "", onEnqueued: keepToken }
|
|
124
|
+
)
|
|
125
|
+
} catch (err) {
|
|
126
|
+
if (!(err instanceof AiInterfaceError) || err.status !== 403) {
|
|
127
|
+
throw err
|
|
128
|
+
}
|
|
129
|
+
// Neither the current nor the previous poll token matches: the
|
|
130
|
+
// service no longer knows this identity. Re-enqueueing it would 403
|
|
131
|
+
// forever, so mint a fresh one and say so in the transcript.
|
|
132
|
+
writeIdentity(undefined)
|
|
133
|
+
identity = getOrCreateIdentity()
|
|
134
|
+
setMessages((prev) => [
|
|
135
|
+
...prev,
|
|
136
|
+
{ role: "notice", content: IDENTITY_RESET_NOTICE, id: `${messageId}:identity-reset` },
|
|
137
|
+
])
|
|
138
|
+
turn = await chatApi.completeChatTurn(
|
|
139
|
+
baseUrl,
|
|
140
|
+
identity.userId,
|
|
141
|
+
content,
|
|
142
|
+
messageId,
|
|
143
|
+
undefined,
|
|
144
|
+
controller.signal,
|
|
145
|
+
{ lastMessageId: "", onEnqueued: keepToken }
|
|
146
|
+
)
|
|
147
|
+
}
|
|
148
|
+
writeIdentity({
|
|
149
|
+
...identity,
|
|
150
|
+
pollToken: turn.pollToken,
|
|
151
|
+
lastReplyId: turn.reply.message_id,
|
|
152
|
+
})
|
|
153
|
+
if (controller.signal.aborted) {
|
|
154
|
+
return
|
|
155
|
+
}
|
|
156
|
+
setMessages((prev) => [
|
|
157
|
+
...prev,
|
|
158
|
+
{ role: "assistant", content: turn.reply.message, id: turn.reply.message_id },
|
|
159
|
+
])
|
|
160
|
+
} catch (err) {
|
|
161
|
+
dropOptimistic()
|
|
162
|
+
if (controller.signal.aborted) {
|
|
163
|
+
return
|
|
164
|
+
}
|
|
165
|
+
setError(err instanceof Error ? err.message : "Failed to send message")
|
|
166
|
+
} finally {
|
|
167
|
+
if (sendAbortRef.current === controller) {
|
|
168
|
+
sendAbortRef.current = null
|
|
169
|
+
setIsLoading(false)
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
},
|
|
173
|
+
[baseUrl]
|
|
174
|
+
)
|
|
175
|
+
|
|
176
|
+
const cancelMessage = useCallback(() => {
|
|
177
|
+
sendAbortRef.current?.abort()
|
|
178
|
+
}, [])
|
|
179
|
+
|
|
180
|
+
// Drops the persisted identity too, so the service starts a fresh thread
|
|
181
|
+
// instead of resuming the one tied to the old userId.
|
|
182
|
+
const startNewChat = useCallback(() => {
|
|
183
|
+
sendAbortRef.current?.abort()
|
|
184
|
+
sendAbortRef.current = null
|
|
185
|
+
writeIdentity(undefined)
|
|
186
|
+
setMessages([])
|
|
187
|
+
setError(null)
|
|
188
|
+
setIsLoading(false)
|
|
189
|
+
}, [])
|
|
190
|
+
|
|
191
|
+
const clearError = useCallback(() => setError(null), [])
|
|
192
|
+
|
|
193
|
+
return { messages, isLoading, error, sendMessage, cancelMessage, startNewChat, clearError }
|
|
194
|
+
}
|
package/src/lib/data/products.ts
CHANGED
|
@@ -651,6 +651,7 @@ export const listApplicationFilteredProducts = async ({
|
|
|
651
651
|
certificationTypes,
|
|
652
652
|
sizes,
|
|
653
653
|
listingFacets,
|
|
654
|
+
certificationFacetTypes,
|
|
654
655
|
sellerHandle,
|
|
655
656
|
withScopeEntities,
|
|
656
657
|
}: {
|
|
@@ -684,6 +685,12 @@ export const listApplicationFilteredProducts = async ({
|
|
|
684
685
|
* from paying for them.
|
|
685
686
|
*/
|
|
686
687
|
listingFacets?: string[];
|
|
688
|
+
/**
|
|
689
|
+
* Certification types the `certification` facet counts. Absent keeps the
|
|
690
|
+
* backend default (the food set); pass the storefront industry's own list so
|
|
691
|
+
* it does not pay for counts it never shows.
|
|
692
|
+
*/
|
|
693
|
+
certificationFacetTypes?: readonly string[];
|
|
687
694
|
/**
|
|
688
695
|
* Narrow to one seller. Served by the catalog route's own seller scope,
|
|
689
696
|
* which resolves from the seller↔product link rather than the price index —
|
|
@@ -749,6 +756,7 @@ export const listApplicationFilteredProducts = async ({
|
|
|
749
756
|
...(sizes?.length ? { size: sizes.join(',') } : {}),
|
|
750
757
|
...(sellerHandle ? { seller_handle: sellerHandle } : {}),
|
|
751
758
|
...(listingFacets?.length ? { facets: listingFacets.join(',') } : {}),
|
|
759
|
+
...(certificationFacetTypes?.length ? { certification_facet_types: certificationFacetTypes.join(',') } : {}),
|
|
752
760
|
...(region ? { region_id: region.id } : {}),
|
|
753
761
|
...(withScopeEntities ? { with_scope_entities: true } : {}),
|
|
754
762
|
limit,
|
|
@@ -821,6 +829,7 @@ export const listProductsSortedByPrice = async ({
|
|
|
821
829
|
sizes,
|
|
822
830
|
sellerHandle,
|
|
823
831
|
listingFacets,
|
|
832
|
+
certificationFacetTypes,
|
|
824
833
|
}: {
|
|
825
834
|
page?: number;
|
|
826
835
|
limit?: number;
|
|
@@ -850,6 +859,8 @@ export const listProductsSortedByPrice = async ({
|
|
|
850
859
|
sellerHandle?: string;
|
|
851
860
|
/** Facet counts to ask for; see listApplicationFilteredProducts. */
|
|
852
861
|
listingFacets?: string[];
|
|
862
|
+
/** Types the certification facet counts; see listApplicationFilteredProducts. */
|
|
863
|
+
certificationFacetTypes?: readonly string[];
|
|
853
864
|
}): Promise<{
|
|
854
865
|
response: {
|
|
855
866
|
products: HttpTypes.StoreProduct[];
|
|
@@ -894,6 +905,7 @@ export const listProductsSortedByPrice = async ({
|
|
|
894
905
|
...(sizes?.length ? { size: sizes.join(',') } : {}),
|
|
895
906
|
...(sellerHandle ? { seller_handle: sellerHandle } : {}),
|
|
896
907
|
...(listingFacets?.length ? { facets: listingFacets.join(',') } : {}),
|
|
908
|
+
...(certificationFacetTypes?.length ? { certification_facet_types: certificationFacetTypes.join(',') } : {}),
|
|
897
909
|
limit,
|
|
898
910
|
offset,
|
|
899
911
|
},
|
|
@@ -963,6 +975,7 @@ export const listProductsSortedByPrice = async ({
|
|
|
963
975
|
sortBy,
|
|
964
976
|
sellerHandle,
|
|
965
977
|
listingFacets,
|
|
978
|
+
certificationFacetTypes,
|
|
966
979
|
});
|
|
967
980
|
}
|
|
968
981
|
|
|
@@ -16,6 +16,10 @@ export type StorefrontPublicRuntimeSnapshot = {
|
|
|
16
16
|
NEXT_PUBLIC_ENABLE_COOKIE_CONSENT?: string
|
|
17
17
|
/** Browse panel vocabulary: `applications` (default) or `categories-collections` (Davison). */
|
|
18
18
|
NEXT_PUBLIC_BROWSE_NAV_MODE?: string
|
|
19
|
+
/** Industry sales-channel slug (e.g. `food_ingredients`); decides which certification filters show. */
|
|
20
|
+
NEXT_PUBLIC_STOREFRONT_INDUSTRY?: string
|
|
21
|
+
/** artha-go ai-interface base URL; the AI chat widget renders nothing when unset. */
|
|
22
|
+
NEXT_PUBLIC_AI_INTERFACE_URL?: string
|
|
19
23
|
}
|
|
20
24
|
|
|
21
25
|
declare global {
|
|
@@ -78,6 +82,18 @@ export function buildStorefrontRuntimeEnvSnapshot(): StorefrontPublicRuntimeSnap
|
|
|
78
82
|
if (browseNavMode !== undefined) {
|
|
79
83
|
snapshot.NEXT_PUBLIC_BROWSE_NAV_MODE = browseNavMode
|
|
80
84
|
}
|
|
85
|
+
const storefrontIndustry =
|
|
86
|
+
optionalTrim(process.env.STOREFRONT_INDUSTRY) ??
|
|
87
|
+
optionalTrim(process.env.NEXT_PUBLIC_STOREFRONT_INDUSTRY)
|
|
88
|
+
if (storefrontIndustry !== undefined) {
|
|
89
|
+
snapshot.NEXT_PUBLIC_STOREFRONT_INDUSTRY = storefrontIndustry
|
|
90
|
+
}
|
|
91
|
+
const aiInterfaceUrl =
|
|
92
|
+
optionalTrim(process.env.AI_INTERFACE_URL) ??
|
|
93
|
+
optionalTrim(process.env.NEXT_PUBLIC_AI_INTERFACE_URL)
|
|
94
|
+
if (aiInterfaceUrl !== undefined) {
|
|
95
|
+
snapshot.NEXT_PUBLIC_AI_INTERFACE_URL = aiInterfaceUrl
|
|
96
|
+
}
|
|
81
97
|
return snapshot
|
|
82
98
|
}
|
|
83
99
|
|
|
@@ -143,6 +159,18 @@ export function readStorefrontRuntimePublic(
|
|
|
143
159
|
optionalTrim(process.env.NEXT_PUBLIC_BROWSE_NAV_MODE)
|
|
144
160
|
)
|
|
145
161
|
}
|
|
162
|
+
if (publicKey === "NEXT_PUBLIC_STOREFRONT_INDUSTRY") {
|
|
163
|
+
return (
|
|
164
|
+
optionalTrim(process.env.STOREFRONT_INDUSTRY) ??
|
|
165
|
+
optionalTrim(process.env.NEXT_PUBLIC_STOREFRONT_INDUSTRY)
|
|
166
|
+
)
|
|
167
|
+
}
|
|
168
|
+
if (publicKey === "NEXT_PUBLIC_AI_INTERFACE_URL") {
|
|
169
|
+
return (
|
|
170
|
+
optionalTrim(process.env.AI_INTERFACE_URL) ??
|
|
171
|
+
optionalTrim(process.env.NEXT_PUBLIC_AI_INTERFACE_URL)
|
|
172
|
+
)
|
|
173
|
+
}
|
|
146
174
|
return optionalTrim(
|
|
147
175
|
process.env[publicKey as keyof NodeJS.ProcessEnv] as string | undefined
|
|
148
176
|
)
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import type { CertificationType } from "../helpers/parse-listing-controls"
|
|
2
|
+
import { readStorefrontRuntimePublic } from "../runtime/public-storefront-runtime-env"
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Industry slugs match the platform's sales-channel slugs
|
|
6
|
+
* (INDUSTRY_SLUG_BY_CHANNEL_NAME in @sgftech/framework, e.g. "Food Ingredients"
|
|
7
|
+
* -> "food_ingredients"). Restated rather than imported: storefront-core does
|
|
8
|
+
* not depend on the backend framework package.
|
|
9
|
+
*/
|
|
10
|
+
const DEFAULT_INDUSTRY = "food_ingredients"
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* Certifications that make sense for an industry's products. An industry not
|
|
14
|
+
* listed here (apparel, digital media, ...) has none, so the filter is hidden
|
|
15
|
+
* rather than showing food facets (FSSAI/Halal/...) on a store that cannot have
|
|
16
|
+
* them.
|
|
17
|
+
*/
|
|
18
|
+
const CERTIFICATION_TYPES_BY_INDUSTRY: Record<string, readonly CertificationType[]> = {
|
|
19
|
+
food_ingredients: ["fssai", "halal", "kosher", "organic", "vegan"],
|
|
20
|
+
polymer_specialities: ["iso", "gmp", "brc"],
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* The certification filter options for this storefront's industry, from
|
|
25
|
+
* `NEXT_PUBLIC_STOREFRONT_INDUSTRY` (an industry sales-channel slug). Unset
|
|
26
|
+
* keeps the original food behaviour; an unrecognised industry gets none.
|
|
27
|
+
*/
|
|
28
|
+
export function getIndustryCertificationTypes(): readonly CertificationType[] {
|
|
29
|
+
const raw = readStorefrontRuntimePublic("NEXT_PUBLIC_STOREFRONT_INDUSTRY")
|
|
30
|
+
const industry = raw ? raw.trim().toLowerCase() : DEFAULT_INDUSTRY
|
|
31
|
+
return CERTIFICATION_TYPES_BY_INDUSTRY[industry] ?? []
|
|
32
|
+
}
|