@brainerce/mcp-server 3.4.0 → 3.5.1
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/dist/bin/http.js +1196 -150
- package/dist/bin/stdio.js +1196 -150
- package/dist/index.js +1196 -150
- package/dist/index.mjs +1196 -150
- package/package.json +53 -53
package/dist/index.mjs
CHANGED
|
@@ -87,7 +87,7 @@ npm install brainerce
|
|
|
87
87
|
import { BrainerceClient } from 'brainerce';
|
|
88
88
|
|
|
89
89
|
export const client = new BrainerceClient({
|
|
90
|
-
|
|
90
|
+
salesChannelId: '${connectionId}',
|
|
91
91
|
});
|
|
92
92
|
|
|
93
93
|
// Cart helpers \u2014 save cart ID to localStorage
|
|
@@ -189,7 +189,7 @@ async function startCheckout() {
|
|
|
189
189
|
### Full Checkout Flow (Multi-Provider)
|
|
190
190
|
|
|
191
191
|
1. Customer fills cart
|
|
192
|
-
2. Customer optionally applies coupon
|
|
192
|
+
2. Customer optionally applies coupon on cart page \u2192 \`applyCoupon(cartId, code)\`
|
|
193
193
|
3. Detect payment providers \u2192 \`getPaymentProviders()\`
|
|
194
194
|
4. Start checkout session (\`startGuestCheckout()\` or \`createCheckout()\`)
|
|
195
195
|
5. Set shipping address (includes required email) \u2192 \`setShippingAddress()\`
|
|
@@ -207,7 +207,7 @@ import { Elements, PaymentElement, useStripe, useElements } from '@stripe/react-
|
|
|
207
207
|
|
|
208
208
|
function CheckoutPage() {
|
|
209
209
|
const [paymentData, setPaymentData] = useState<{
|
|
210
|
-
clientSecret: string; provider: string; checkoutId: string;
|
|
210
|
+
clientSecret: string; provider: string; checkoutId: string; clientSdk?: { renderType: string };
|
|
211
211
|
} | null>(null);
|
|
212
212
|
const [stripePromise, setStripePromise] = useState<ReturnType<typeof loadStripe> | null>(null);
|
|
213
213
|
const [paypalClientId, setPaypalClientId] = useState<string | null>(null);
|
|
@@ -259,12 +259,17 @@ function CheckoutPage() {
|
|
|
259
259
|
}
|
|
260
260
|
|
|
261
261
|
// Step 4: Create payment intent \u2014 returns provider type!
|
|
262
|
+
// Pass saveCard: true when the customer ticked "save my card for next time" \u2014
|
|
263
|
+
// only honored for logged-in customers (not guests). The vaulted card then
|
|
264
|
+
// appears in client.listSavedPaymentMethods(storeId, customerId) and can be
|
|
265
|
+
// charged off-session via subscription / one-click checkout flows.
|
|
262
266
|
const paymentIntent = await client.createPaymentIntent(checkoutId, {
|
|
263
267
|
successUrl: \`\${window.location.origin}/order-confirmation?checkout_id=\${checkoutId}\`,
|
|
264
268
|
cancelUrl: \`\${window.location.origin}/checkout?error=payment_cancelled\`,
|
|
269
|
+
// saveCard: customerOptedIn, // optional opt-in
|
|
265
270
|
});
|
|
266
271
|
|
|
267
|
-
setPaymentData({ clientSecret: paymentIntent.clientSecret, provider: paymentIntent.provider, checkoutId });
|
|
272
|
+
setPaymentData({ clientSecret: paymentIntent.clientSecret, provider: paymentIntent.provider, checkoutId, clientSdk: paymentIntent.clientSdk });
|
|
268
273
|
|
|
269
274
|
// Step 5: Initialize the correct payment provider
|
|
270
275
|
if (paymentIntent.provider === 'stripe' && stripeProvider) {
|
|
@@ -382,8 +387,10 @@ function PaymentIframe({ clientSecret, checkoutId }: { clientSecret: string; che
|
|
|
382
387
|
}
|
|
383
388
|
if (data?.type === 'brainerce:redirect' && typeof data.url === 'string') {
|
|
384
389
|
// Top-level navigation (e.g. Bit). ALWAYS validate against an allowlist
|
|
385
|
-
// before navigating \u2014 never trust the URL blindly.
|
|
386
|
-
|
|
390
|
+
// before navigating \u2014 never trust the URL blindly. The SDK ships with
|
|
391
|
+
// a maintained list of payment-provider hosts; prefer it over a local
|
|
392
|
+
// copy so 'npm update brainerce' picks up new providers automatically.
|
|
393
|
+
if (isAllowedPaymentUrl(data.url)) { window.top!.location.href = data.url; }
|
|
387
394
|
}
|
|
388
395
|
if (data?.type === 'brainerce:payment-complete') {
|
|
389
396
|
// Payment done \u2014 redirect to confirmation page which verifies server-side
|
|
@@ -423,15 +430,10 @@ function PaymentIframe({ clientSecret, checkoutId }: { clientSecret: string; che
|
|
|
423
430
|
);
|
|
424
431
|
}
|
|
425
432
|
|
|
426
|
-
// Allowlist
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
if (u.protocol !== 'https:') return false;
|
|
431
|
-
// Add your provider hostnames here. Example: Cardcom for Bit express-pay.
|
|
432
|
-
return u.hostname === 'cardcom.solutions' || u.hostname.endsWith('.cardcom.solutions');
|
|
433
|
-
} catch { return false; }
|
|
434
|
-
}
|
|
433
|
+
// Allowlist check is provided by the SDK \u2014 covers Stripe, PayPal, Cardcom,
|
|
434
|
+
// Meshulam, Grow, CreditGuard, plus Brainerce-hosted embed shells. To extend
|
|
435
|
+
// for a self-hosted PSP, pass { extraHosts: ['my-psp.example.com'] }.
|
|
436
|
+
import { isAllowedPaymentUrl } from 'brainerce';
|
|
435
437
|
\`\`\`
|
|
436
438
|
|
|
437
439
|
### PayPal Payment Form
|
|
@@ -719,6 +721,80 @@ Provider-specific install notes:
|
|
|
719
721
|
- **Grow:** No SDK needed \u2014 JS SDK loaded via \`clientSdk.scriptUrl\`. Supports credit cards, Bit, Apple Pay, Google Pay.
|
|
720
722
|
- **Cardcom:** No SDK needed \u2014 rendering driven by \`renderType: 'iframe'\` + the inline/modal branch above. Supports credit cards, Bit (when terminal provisions it), installments, 3D Secure.`;
|
|
721
723
|
}
|
|
724
|
+
function getSavedPaymentMethodsSection() {
|
|
725
|
+
return `## Saved Payment Methods (vaulted cards)
|
|
726
|
+
|
|
727
|
+
When a logged-in customer ticks "save my card for next time", the platform vaults the
|
|
728
|
+
card with the underlying provider and stores a reference. Vaulted cards can later be
|
|
729
|
+
charged off-session \u2014 typically via subscription / one-click checkout features built
|
|
730
|
+
on top of this foundation.
|
|
731
|
+
|
|
732
|
+
### Opt-in at checkout
|
|
733
|
+
|
|
734
|
+
Pass \`saveCard: true\` to \`createPaymentIntent\` when the customer chose to save.
|
|
735
|
+
**Only honored for logged-in customers** \u2014 anonymous (guest) checkouts silently
|
|
736
|
+
skip vaulting because there's no Customer record to attach the resulting saved
|
|
737
|
+
method to.
|
|
738
|
+
|
|
739
|
+
\`\`\`typescript
|
|
740
|
+
const intent = await client.createPaymentIntent(checkoutId, {
|
|
741
|
+
successUrl,
|
|
742
|
+
cancelUrl,
|
|
743
|
+
saveCard: true, // optional \u2014 only when customer ticked the box AND is logged in
|
|
744
|
+
});
|
|
745
|
+
\`\`\`
|
|
746
|
+
|
|
747
|
+
After a successful charge, the saved card appears in the customer's profile.
|
|
748
|
+
|
|
749
|
+
### Listing saved cards (storefront / customer account page)
|
|
750
|
+
|
|
751
|
+
Show the customer their saved cards on a "Manage Payment Methods" page in their
|
|
752
|
+
account. The platform returns display-only metadata \u2014 last4, brand, expiry,
|
|
753
|
+
default flag, status. The underlying provider token is encrypted at rest and
|
|
754
|
+
NEVER returned through the SDK.
|
|
755
|
+
|
|
756
|
+
\`\`\`typescript
|
|
757
|
+
const methods = await client.listSavedPaymentMethods(storeId, customerId);
|
|
758
|
+
|
|
759
|
+
methods.forEach((m) => {
|
|
760
|
+
console.log(\`\${m.brand} ending in \${m.last4} (expires \${m.expMonth}/\${m.expYear})\`);
|
|
761
|
+
if (m.isDefault) console.log(' \u21B3 default');
|
|
762
|
+
if (m.status === 'expired') console.log(' \u21B3 expired \u2014 please add a new card');
|
|
763
|
+
});
|
|
764
|
+
\`\`\`
|
|
765
|
+
|
|
766
|
+
### Removing a saved card
|
|
767
|
+
|
|
768
|
+
\`\`\`typescript
|
|
769
|
+
await client.removeSavedPaymentMethod(storeId, customerId, methodId);
|
|
770
|
+
\`\`\`
|
|
771
|
+
|
|
772
|
+
Hard-deletes the row from the platform DB. The provider may still hold the
|
|
773
|
+
underlying token internally \u2014 we don't issue a delete-at-provider call because
|
|
774
|
+
not every provider supports it. From the platform's perspective the token is
|
|
775
|
+
gone; subsequent charges fail.
|
|
776
|
+
|
|
777
|
+
### Provider support matrix
|
|
778
|
+
|
|
779
|
+
| Provider | Save card on first charge | Charge saved card off-session |
|
|
780
|
+
|---|---|---|
|
|
781
|
+
| Cardcom | \u2705 (Operation: ChargeAndCreateToken) | \u2705 |
|
|
782
|
+
| PayPal | \u2705 (Vault API: store_in_vault) | \u2705 |
|
|
783
|
+
| Stripe | (separate workstream \u2014 Brainerce doesn't ship a Stripe payment app yet) | \u2014 |
|
|
784
|
+
| Grow | \u274C \u2014 returns 501 \`token_storage_unavailable\` | \u274C |
|
|
785
|
+
|
|
786
|
+
When a provider doesn't support tokenization, the platform surfaces a 409 with
|
|
787
|
+
\`code: 'token_storage_unavailable'\`. Storefronts should hide the "save card"
|
|
788
|
+
checkbox when the active provider doesn't support it.
|
|
789
|
+
|
|
790
|
+
### Charging off-session
|
|
791
|
+
|
|
792
|
+
Charging a saved card from the storefront is **not** part of this foundation \u2014
|
|
793
|
+
that's the job of the Subscription / one-click checkout features built on top.
|
|
794
|
+
For now, charges run through the standard \`createPaymentIntent\` flow. The
|
|
795
|
+
saved-method foundation makes those features possible without further platform
|
|
796
|
+
changes.`;
|
|
797
|
+
}
|
|
722
798
|
function getProductsSection(_currency) {
|
|
723
799
|
return `## Products & Variants
|
|
724
800
|
|
|
@@ -739,6 +815,18 @@ const filtered = await client.getProducts({
|
|
|
739
815
|
categories: ['cat_123'], minPrice: 10, maxPrice: 100,
|
|
740
816
|
sortBy: 'price', sortOrder: 'asc',
|
|
741
817
|
});
|
|
818
|
+
|
|
819
|
+
// Filter by custom fields (metafields). Only fields the merchant marked
|
|
820
|
+
// \`filterable: true\` are honored; supported types are SELECT, MULTI_SELECT,
|
|
821
|
+
// BOOLEAN. AND across keys, OR within a key.
|
|
822
|
+
const byCustom = await client.getProducts({
|
|
823
|
+
metafields: { color: ['red', 'blue'], in_stock: ['true'] },
|
|
824
|
+
});
|
|
825
|
+
|
|
826
|
+
// Discover which custom fields are filterable for the current store:
|
|
827
|
+
const { definitions } = await client.getPublicMetafieldDefinitions();
|
|
828
|
+
const facets = definitions.filter(d => d.filterable);
|
|
829
|
+
// Render a checkbox group per SELECT/MULTI_SELECT, a switch per BOOLEAN.
|
|
742
830
|
\`\`\`
|
|
743
831
|
|
|
744
832
|
### i18n \u2014 translated fields come back on every request
|
|
@@ -791,6 +879,10 @@ function ProductPage({ product, storeInfo }: { product: Product; storeInfo: Stor
|
|
|
791
879
|
? getVariantPrice(selectedVariant, product.basePrice).toString()
|
|
792
880
|
: product.salePrice || product.basePrice;
|
|
793
881
|
|
|
882
|
+
// \u2705 For catalog cards: use pre-computed priceMin/priceMax instead of iterating variants
|
|
883
|
+
// product.priceMin / product.priceMax are always set for VARIABLE products with explicit variant prices.
|
|
884
|
+
// product.priceVaries is true when the range should be shown as "\u20AA49 \u2013 \u20AA199".
|
|
885
|
+
|
|
794
886
|
// Build attribute buttons (size, color, etc.)
|
|
795
887
|
const allOptions = product.variants?.map(v => getVariantOptions(v)) || [];
|
|
796
888
|
const attrNames = [...new Set(allOptions.flatMap(opts => opts.map(o => o.name)))];
|
|
@@ -1005,6 +1097,7 @@ const total = cart.total;
|
|
|
1005
1097
|
|
|
1006
1098
|
### Coupons
|
|
1007
1099
|
|
|
1100
|
+
**On the cart page** (before checkout is created):
|
|
1008
1101
|
\`\`\`typescript
|
|
1009
1102
|
// Apply coupon \u2014 returns updated Cart with discountAmount
|
|
1010
1103
|
const updatedCart = await client.applyCoupon(cartId, 'SAVE20');
|
|
@@ -1012,13 +1105,24 @@ console.log(updatedCart.discountAmount); // "10.00"
|
|
|
1012
1105
|
console.log(updatedCart.couponCode); // "SAVE20"
|
|
1013
1106
|
|
|
1014
1107
|
// Remove coupon
|
|
1015
|
-
|
|
1108
|
+
await client.removeCoupon(cartId);
|
|
1016
1109
|
|
|
1017
1110
|
// Calculate totals including discount
|
|
1018
1111
|
const totals = getCartTotals(cart); // { subtotal, discount, shipping, total }
|
|
1019
1112
|
\`\`\`
|
|
1020
1113
|
|
|
1021
|
-
|
|
1114
|
+
**On the checkout page** (after checkout session exists \u2014 ALWAYS use this when checkoutId is available):
|
|
1115
|
+
\`\`\`typescript
|
|
1116
|
+
// Applies to cart AND updates checkout totals in one call
|
|
1117
|
+
const checkout = await client.applyCheckoutCoupon(checkoutId, 'SAVE20');
|
|
1118
|
+
console.log(checkout.discountAmount); // "10.00"
|
|
1119
|
+
console.log(checkout.total); // correctly updated total
|
|
1120
|
+
|
|
1121
|
+
// Remove coupon from checkout
|
|
1122
|
+
await client.removeCheckoutCoupon(checkoutId);
|
|
1123
|
+
\`\`\`
|
|
1124
|
+
|
|
1125
|
+
> \u26A0\uFE0F **Critical:** if a checkout session already exists, ALWAYS use \`applyCheckoutCoupon(checkoutId, code)\`. Using \`applyCoupon(cartId, code)\` after checkout creation does NOT update the checkout total \u2014 payment will charge the original amount. Show \`checkout.discountAmount\` and \`checkout.couponCode\` in the order summary.
|
|
1022
1126
|
|
|
1023
1127
|
### \u26A0\uFE0F Checkout Order Summary \u2014 Use checkout.lineItems, NOT cart.items!
|
|
1024
1128
|
|
|
@@ -1108,22 +1212,24 @@ const { upgrades } = await client.getCartUpgrades(cartId);
|
|
|
1108
1212
|
// Show inline banner per cart item if upgrade exists
|
|
1109
1213
|
\`\`\`
|
|
1110
1214
|
|
|
1111
|
-
**Bundle offers** (
|
|
1215
|
+
**Bundle offers** (N-product bundles configured by the store owner \u2014 productIds[0] triggers the offer, productIds[1..] are offered together at a discount):
|
|
1112
1216
|
\`\`\`typescript
|
|
1113
1217
|
import type { CartBundlesResponse } from 'brainerce';
|
|
1114
1218
|
const { bundles } = await client.getCartBundles(cartId);
|
|
1115
|
-
// bundles[].
|
|
1116
|
-
// bundles[].
|
|
1219
|
+
// bundles[].triggerProductId \u2014 already in cart, activates the offer
|
|
1220
|
+
// bundles[].productIds \u2014 full bundle composition (length >= 2)
|
|
1221
|
+
// bundles[].offeredProducts[] \u2014 products customer hasn't added yet
|
|
1222
|
+
// each with originalPrice + discountedPrice
|
|
1223
|
+
// bundles[].totalOriginalPrice / totalDiscountedPrice \u2014 sums across offeredProducts
|
|
1117
1224
|
// bundles[].discountType ('PERCENTAGE' | 'FIXED_AMOUNT') + discountValue
|
|
1118
|
-
// bundles[].requiresVariantSelection \u2014 true if customer must pick a variant
|
|
1119
|
-
// bundles[].lockedVariant \u2014 set if admin pre-selected a specific variant
|
|
1120
|
-
// bundles[].bundleProduct.variants \u2014 available variants (only when requiresVariantSelection)
|
|
1121
1225
|
|
|
1122
|
-
//
|
|
1226
|
+
// Accept a bundle (adds every offered product not yet in cart at the discount):
|
|
1123
1227
|
await client.addBundleToCart(cartId, bundleOfferId);
|
|
1124
|
-
//
|
|
1125
|
-
await client.addBundleToCart(cartId, bundleOfferId,
|
|
1126
|
-
|
|
1228
|
+
// If some offered products have variants, pass per-product variant selections:
|
|
1229
|
+
await client.addBundleToCart(cartId, bundleOfferId, {
|
|
1230
|
+
[variantProductId]: selectedVariantId,
|
|
1231
|
+
});
|
|
1232
|
+
// Remove an accepted bundle (removes every cart item linked to that bundle):
|
|
1127
1233
|
await client.removeBundleFromCart(cartId, bundleOfferId);
|
|
1128
1234
|
// Detect already-added bundles: check cart.items for metadata?.isBundleItem === true
|
|
1129
1235
|
\`\`\`
|
|
@@ -1179,11 +1285,12 @@ Always check the flag before rendering: \`if (storeInfo?.upsell?.featureName !==
|
|
|
1179
1285
|
| CartRecommendationSection | products/ | Cross-sell grid at bottom of cart page |
|
|
1180
1286
|
| FreeShippingBar | cart/ | Progress bar toward free shipping threshold |
|
|
1181
1287
|
| CartUpgradeBanner | cart/ | Inline "Upgrade to X for +$Y" per cart item |
|
|
1182
|
-
| CartBundleOfferCard | cart/ |
|
|
1288
|
+
| CartBundleOfferCard | cart/ | N-product bundle offer card in cart \u2014 lists every offered product with its discounted price and an "Add bundle" button |
|
|
1183
1289
|
| OrderBumpCard | checkout/ | Checkbox add-on card in checkout sidebar (with inline variant selector for variable products) |
|
|
1184
1290
|
|
|
1185
1291
|
ProductRecommendation: \`id\`, \`name\`, \`slug\`, \`basePrice\`, \`salePrice\`, \`images\`, \`type\`, \`inventory\`, \`relationType\`, \`variants?\` (when variant selection needed).
|
|
1186
|
-
OrderBump
|
|
1292
|
+
OrderBump: includes \`requiresVariantSelection\` (boolean) and \`lockedVariant?\` (\`{ id, name, attributes }\`).
|
|
1293
|
+
CartBundleOffer: \`productIds\` (length \\>= 2; index 0 = trigger), \`offeredProducts\` (per-product discounted prices), \`totalOriginalPrice\` / \`totalDiscountedPrice\`. Variant selection for offered products is passed per-call via \`variantSelections\` on \`addBundleToCart\`.`;
|
|
1187
1294
|
}
|
|
1188
1295
|
function getProductCustomizationFieldsSection() {
|
|
1189
1296
|
return `## Product Customization Fields (buyer input on product page)
|
|
@@ -1289,6 +1396,157 @@ When the order is created, each line's customization values are snapshotted onto
|
|
|
1289
1396
|
- Using a raw external URL (not from \`/customization-upload\`) for \`IMAGE\` / \`GALLERY\` \u2192 HTTP 400
|
|
1290
1397
|
- Assuming \`enumValues\` is present for all types \u2014 only \`SELECT\` / \`MULTI_SELECT\` require it`;
|
|
1291
1398
|
}
|
|
1399
|
+
function getModifierGroupsSection() {
|
|
1400
|
+
return `## Modifier Groups (toppings, sauce, build-your-own)
|
|
1401
|
+
|
|
1402
|
+
Modifier groups are merchant-defined option blocks attached to a product \u2014 the canonical example is "Toppings" on a pizza, where the customer picks 0\u20138 options with the first 3 free. They differ from \`customizationFields\` (which are arbitrary buyer input \u2014 text, photos, color picks): modifier groups are a **structured selection with priced options**, validated and priced server-side.
|
|
1403
|
+
|
|
1404
|
+
If \`product.modifierGroups\` is empty or missing, render the product page normally and skip everything below.
|
|
1405
|
+
|
|
1406
|
+
### Wire shape on \`GET /products/:id\`
|
|
1407
|
+
|
|
1408
|
+
\`\`\`typescript
|
|
1409
|
+
import type { Product, ModifierGroup, Modifier, ModifierSelection } from 'brainerce';
|
|
1410
|
+
|
|
1411
|
+
const product = await client.getProductBySlug(slug);
|
|
1412
|
+
const groups: ModifierGroup[] = product.modifierGroups ?? [];
|
|
1413
|
+
|
|
1414
|
+
// Each group looks like:
|
|
1415
|
+
// {
|
|
1416
|
+
// id: 'mg_toppings',
|
|
1417
|
+
// attachmentId: 'pmg_01', // ProductModifierGroup row \u2014 used for attach updates
|
|
1418
|
+
// name: 'Toppings', // customer-facing
|
|
1419
|
+
// internalName?: string, // ADMIN ONLY \u2014 never present in storefront responses
|
|
1420
|
+
// selectionType: 'SINGLE' | 'MULTIPLE',
|
|
1421
|
+
// min: number, // effective (overrides already applied)
|
|
1422
|
+
// max: number | null, // null = unlimited; **0 = group hidden for this variant**
|
|
1423
|
+
// freeQuantity: number, // first N picks at no extra cost
|
|
1424
|
+
// required: boolean,
|
|
1425
|
+
// freeAllocationPolicy: 'EXPENSIVE_FREE' | 'CHEAPEST_FREE' | 'SELECTION_ORDER',
|
|
1426
|
+
// defaultModifierIds: string[], // pre-checked on first render
|
|
1427
|
+
// modifiers: Array<{
|
|
1428
|
+
// id: 'm_olive',
|
|
1429
|
+
// name: 'Olives',
|
|
1430
|
+
// priceDelta: '5.00', // DECIMAL STRING \u2014 never JSON Number
|
|
1431
|
+
// position: 0,
|
|
1432
|
+
// isDefault: false, // pre-check this option even if not in defaultModifierIds
|
|
1433
|
+
// available: true, // false \u2192 "sold out", disabled in UI
|
|
1434
|
+
// referencedProductId?: string, // nested-combo target (depth \u2264 3)
|
|
1435
|
+
// }>,
|
|
1436
|
+
// }
|
|
1437
|
+
\`\`\`
|
|
1438
|
+
|
|
1439
|
+
**Money fields are strings.** \`priceDelta\` is \`"5.00"\` (or \`"-2.00"\` for downsell modifiers \u2014 see below). Use \`parseFloat()\` for display arithmetic; never compute the line total client-side \u2014 the server runs the free-allocation policy and returns the final \`unitPrice\` snapshot on the cart line.
|
|
1440
|
+
|
|
1441
|
+
### Render: SINGLE \u2192 radio, MULTIPLE \u2192 checkbox
|
|
1442
|
+
|
|
1443
|
+
Walk \`groups\` and pick the input type by \`selectionType\`. Sort modifiers by \`position\`.
|
|
1444
|
+
|
|
1445
|
+
\`\`\`typescript
|
|
1446
|
+
for (const group of groups) {
|
|
1447
|
+
if (group.max === 0) continue; // disabled-for-variant convention \u2014 skip entirely
|
|
1448
|
+
const inputType = group.selectionType === 'SINGLE' ? 'radio' : 'checkbox';
|
|
1449
|
+
const sorted = [...group.modifiers].sort((a, b) => a.position - b.position);
|
|
1450
|
+
// Render fieldset \u2192 legend with name + " *" if required \u2192 list of sorted options.
|
|
1451
|
+
// Each option: input(type=inputType, name=group.id, value=modifier.id),
|
|
1452
|
+
// disabled when modifier.available === false, with a "Sold out" badge.
|
|
1453
|
+
}
|
|
1454
|
+
\`\`\`
|
|
1455
|
+
|
|
1456
|
+
When \`group.freeQuantity > 0\`, show a running counter so the customer understands the rule:
|
|
1457
|
+
\`\`\`
|
|
1458
|
+
{Math.min(picks.length, group.freeQuantity)} of {group.freeQuantity} free
|
|
1459
|
+
\`\`\`
|
|
1460
|
+
|
|
1461
|
+
Note: individual modifiers may have \`excludeFromFree: true\` \u2014 these are "premium" options that always charge their \`priceDelta\` and are never consumed by a free slot. Render them with a label like "premium" so customers know they are not eligible for the free allocation.
|
|
1462
|
+
|
|
1463
|
+
### Initial state
|
|
1464
|
+
|
|
1465
|
+
Honor \`defaultModifierIds\` first (per-attach defaults set by the merchant for this product/variant), falling back to \`modifier.isDefault\` flags when the group has no per-attach defaults. Filter sold-out modifiers out of the initial picks. For SINGLE groups, cap to one.
|
|
1466
|
+
|
|
1467
|
+
### Pass selections on add-to-cart
|
|
1468
|
+
|
|
1469
|
+
\`\`\`typescript
|
|
1470
|
+
const selections: ModifierSelection[] = [
|
|
1471
|
+
{ modifierGroupId: 'mg_bread', modifierIds: ['m_thick'] },
|
|
1472
|
+
{ modifierGroupId: 'mg_toppings', modifierIds: ['m_olive', 'm_mushroom', 'm_bacon', 'm_egg'] },
|
|
1473
|
+
];
|
|
1474
|
+
|
|
1475
|
+
await client.smartAddToCart({
|
|
1476
|
+
productId: product.id,
|
|
1477
|
+
variantId: selectedVariant?.id,
|
|
1478
|
+
quantity: 1,
|
|
1479
|
+
selections,
|
|
1480
|
+
});
|
|
1481
|
+
\`\`\`
|
|
1482
|
+
|
|
1483
|
+
\`modifierIds\` is in **click-order** \u2014 the server uses this for the \`SELECTION_ORDER\` free-allocation policy. The cart response surfaces a per-line snapshot:
|
|
1484
|
+
|
|
1485
|
+
\`\`\`typescript
|
|
1486
|
+
// cart.items[i].modifiers \u2014 same shape as ModifierSelection but with snapshot data
|
|
1487
|
+
[
|
|
1488
|
+
{ modifierId: 'm_olive', name: 'Olives', priceDelta: '5.00', freeApplied: true },
|
|
1489
|
+
{ modifierId: 'm_mushroom', name: 'Mushrooms', priceDelta: '5.00', freeApplied: true },
|
|
1490
|
+
{ modifierId: 'm_bacon', name: 'Bacon', priceDelta: '7.00', freeApplied: true },
|
|
1491
|
+
{ modifierId: 'm_egg', name: 'Egg', priceDelta: '6.00', freeApplied: false },
|
|
1492
|
+
]
|
|
1493
|
+
// + cart.items[i].modifiersTotal \u2014 sum of paid (non-free) deltas as a decimal string
|
|
1494
|
+
\`\`\`
|
|
1495
|
+
|
|
1496
|
+
\`freeApplied: true\` means the modifier consumed a free slot \u2014 render with a "free" badge in the cart UI.
|
|
1497
|
+
|
|
1498
|
+
### Editing selections after add-to-cart (idempotent)
|
|
1499
|
+
|
|
1500
|
+
\`PATCH /cart/items/:id\` with a fresh \`selections\` array **replaces** the line's modifiers atomically \u2014 the server deletes old \`CartItemModifier\` rows and recreates them inside the same transaction. Omit \`selections\` from the body to leave them unchanged (e.g., quantity-only update).
|
|
1501
|
+
|
|
1502
|
+
\`\`\`typescript
|
|
1503
|
+
await client.updateCartItem(cart.id, itemId, {
|
|
1504
|
+
quantity: 1,
|
|
1505
|
+
selections: [{ modifierGroupId: 'mg_toppings', modifierIds: ['m_olive', 'm_mushroom'] }],
|
|
1506
|
+
});
|
|
1507
|
+
\`\`\`
|
|
1508
|
+
|
|
1509
|
+
### Validation envelope
|
|
1510
|
+
|
|
1511
|
+
When the payload is invalid the server returns HTTP 400 with a structured envelope. The SDK exposes it on \`BrainerceError.details\`:
|
|
1512
|
+
|
|
1513
|
+
\`\`\`typescript
|
|
1514
|
+
try {
|
|
1515
|
+
await client.smartAddToCart({ productId, quantity: 1, selections });
|
|
1516
|
+
} catch (err) {
|
|
1517
|
+
const e = err as { statusCode?: number; details?: { code?: string; errors?: Array<{ code: string; message: string; modifierGroupId?: string; modifierId?: string }> } };
|
|
1518
|
+
if (e.statusCode === 400 && e.details?.code === 'MODIFIER_VALIDATION_FAILED') {
|
|
1519
|
+
for (const issue of e.details.errors ?? []) {
|
|
1520
|
+
// issue.code is one of: REQUIRED_GROUP_MISSING | MIN_SELECTIONS_NOT_MET |
|
|
1521
|
+
// MAX_SELECTIONS_EXCEEDED | SINGLE_GROUP_MULTIPLE_PICKS | UNKNOWN_MODIFIER |
|
|
1522
|
+
// UNKNOWN_GROUP | MODIFIER_DISABLED_FOR_VARIANT | MODIFIER_NOT_AVAILABLE |
|
|
1523
|
+
// NESTED_DEPTH_EXCEEDED | NESTED_REQUIRES_PRODUCT_REF | INVALID_PRICE_DELTA |
|
|
1524
|
+
// MODIFIER_PRICE_FLOOR_VIOLATED
|
|
1525
|
+
console.error(issue.message);
|
|
1526
|
+
}
|
|
1527
|
+
}
|
|
1528
|
+
}
|
|
1529
|
+
\`\`\`
|
|
1530
|
+
|
|
1531
|
+
Special case: \`MODIFIER_PRICE_FLOOR_VIOLATED\` fires when downsell modifiers (negative \`priceDelta\`) would push \`unitPrice\` below \`0\`. The server reports a generic message \u2014 internals never leak \u2014 so show a friendly "Cannot apply more discounts on this item" and let the customer remove a downsell.
|
|
1532
|
+
|
|
1533
|
+
### Disable-for-variant convention (PRD \xA77.2.2)
|
|
1534
|
+
|
|
1535
|
+
The merchant can hide a group entirely for one variant by setting \`maxOverride: 0\` on a per-variant attachment. The product response then returns the group with \`max: 0\` for that variant. **Skip it entirely** \u2014 do not render, do not include in selections. The validator silently skips groups with \`effectiveMax === 0\` on the cart side.
|
|
1536
|
+
|
|
1537
|
+
### Common mistakes
|
|
1538
|
+
|
|
1539
|
+
- Treating \`priceDelta\` as a number \u2192 arithmetic precision bugs. Always strings; use \`parseFloat\` only at display time.
|
|
1540
|
+
- Computing the line total client-side \u2192 diverges from the server's free-allocation. Render the server's \`unitPrice\` / \`modifiers[]\` / \`modifiersTotal\` instead.
|
|
1541
|
+
- Rendering a group with \`max: 0\` \u2192 it's the variant-disable signal; treat as absent.
|
|
1542
|
+
- Showing \`internalName\` on a public storefront \u2192 it is **never** present in storefront responses; if your code is reading it, you're using an admin endpoint by accident.
|
|
1543
|
+
- Building \`selections\` keyed by \`modifier.name\` \u2192 must be \`modifierGroupId\` + \`modifierIds[]\` (the IDs, not names).
|
|
1544
|
+
- Sending \`modifiers\` instead of \`selections\` on add-to-cart \u2192 \`modifiers\` is the response field; the request key is \`selections\`.
|
|
1545
|
+
|
|
1546
|
+
### Restaurant features (advanced)
|
|
1547
|
+
|
|
1548
|
+
Allergens (informational chips), scheduled availability windows, nested combos (depth \u2264 3 via \`nestedByModifierId\`), and downsell modifiers (negative \`priceDelta\`) are all built on the same data model. See INTEGRATION-OPTIONAL.md "Restaurant / build-your-own products" for those flows.`;
|
|
1549
|
+
}
|
|
1292
1550
|
function getInventorySection() {
|
|
1293
1551
|
return `## Inventory, Stock Display & Reservation Countdown
|
|
1294
1552
|
|
|
@@ -1684,7 +1942,7 @@ subsequent SDK call sends the \`Accept-Language\` header automatically:
|
|
|
1684
1942
|
\`\`\`typescript
|
|
1685
1943
|
import { BrainerceClient } from 'brainerce';
|
|
1686
1944
|
|
|
1687
|
-
const client = new BrainerceClient({
|
|
1945
|
+
const client = new BrainerceClient({ salesChannelId: 'vc_...' });
|
|
1688
1946
|
client.setLocale('he'); // done \u2014 all calls are now in Hebrew
|
|
1689
1947
|
\`\`\`
|
|
1690
1948
|
|
|
@@ -1854,7 +2112,40 @@ const admin = new BrainerceClient({ apiKey: 'brainerce_...' });
|
|
|
1854
2112
|
// Email: getEmailTemplates(), createEmailTemplate()
|
|
1855
2113
|
// Conflicts: getSyncConflicts(), resolveSyncConflict()
|
|
1856
2114
|
// OAuth: getOAuthProviders(), configureOAuthProvider()
|
|
1857
|
-
|
|
2115
|
+
\`\`\`
|
|
2116
|
+
|
|
2117
|
+
### Per-Channel Publishing
|
|
2118
|
+
|
|
2119
|
+
Categories, tags, brands, and metafield definitions are gated to specific
|
|
2120
|
+
vibe-coded sites \u2014 same control already exposed for products and coupons.
|
|
2121
|
+
**Explicit opt-in:** an entity is visible to a vibe-coded site only if it
|
|
2122
|
+
has been explicitly published to that connection. Entities with no publish
|
|
2123
|
+
rows are invisible to every site (the merchant must publish them via the
|
|
2124
|
+
dashboard or the admin SDK).
|
|
2125
|
+
|
|
2126
|
+
\`\`\`typescript
|
|
2127
|
+
// Publish to a specific vibe-coded site (admin mode):
|
|
2128
|
+
await admin.publishCategoryToVibeCodedSite('cat_id', 'conn_id');
|
|
2129
|
+
await admin.publishTagToVibeCodedSite('tag_id', 'conn_id');
|
|
2130
|
+
await admin.publishBrandToVibeCodedSite('brand_id', 'conn_id');
|
|
2131
|
+
await admin.publishMetafieldDefinitionToVibeCodedSite('def_id', 'conn_id');
|
|
2132
|
+
|
|
2133
|
+
// Unpublish (entity stays visible to other sites unless they also have publishes):
|
|
2134
|
+
await admin.unpublishCategoryFromVibeCodedSite('cat_id', 'conn_id');
|
|
2135
|
+
// ...same for tag/brand/metafield definition.
|
|
2136
|
+
|
|
2137
|
+
// Read which sites an entity is published to via list/get responses:
|
|
2138
|
+
const cat = await admin.getCategory('cat_id');
|
|
2139
|
+
cat.vibeCodedPublishes; // [{ connection: { id, name, connectionId } }, ...]
|
|
2140
|
+
\`\`\`
|
|
2141
|
+
|
|
2142
|
+
Cross-account isolation is enforced server-side: a publish call only
|
|
2143
|
+
succeeds when entity and connection belong to the same account. Cross-account
|
|
2144
|
+
calls fail with \`404 Not Found\`.
|
|
2145
|
+
|
|
2146
|
+
The vibe-coded read endpoints (used by storefront SDK calls in \`connectionId\`
|
|
2147
|
+
mode) automatically filter by these junction tables, so storefronts never see
|
|
2148
|
+
entities that weren't published to their site.`;
|
|
1858
2149
|
}
|
|
1859
2150
|
function getContactInquiriesSection() {
|
|
1860
2151
|
return `## Contact Inquiries & Forms (optional)
|
|
@@ -1929,7 +2220,7 @@ const form = await brainerce.contactForms.get('main', 'en');
|
|
|
1929
2220
|
// \u2192 {
|
|
1930
2221
|
// id, key, name, description?, submitButton, successMessage,
|
|
1931
2222
|
// fields: [{ key, type, label, placeholder?, helpText?, isRequired,
|
|
1932
|
-
// enumValues?, validation?, defaultValue? }, ...]
|
|
2223
|
+
// enumValues?, validation?, defaultValue?, width? }, ...]
|
|
1933
2224
|
// }
|
|
1934
2225
|
|
|
1935
2226
|
// Submit a keyed payload. Unknown keys are stripped, required fields are
|
|
@@ -1955,6 +2246,20 @@ stripped server-side.
|
|
|
1955
2246
|
Render every field type the merchant can pick. Keep this as a \`<DynamicField>\`
|
|
1956
2247
|
component so the form is fully driven by \`schema.fields\`.
|
|
1957
2248
|
|
|
2249
|
+
**Layout.** Each field carries an optional \`width\` hint:
|
|
2250
|
+
|
|
2251
|
+
| \`field.width\` | Meaning | Grid style (6-column grid) |
|
|
2252
|
+
| ------------- | ------- | -------------------------- |
|
|
2253
|
+
| \`'FULL'\` (default) | Full row | \`grid-column: span 6\` |
|
|
2254
|
+
| \`'HALF'\` | Half row | \`grid-column: span 3\` |
|
|
2255
|
+
| \`'THIRD'\` | One-third row | \`grid-column: span 2\` |
|
|
2256
|
+
|
|
2257
|
+
Stack fields to full width on small screens (< ~640 px).
|
|
2258
|
+
|
|
2259
|
+
**Required fields.** Show a red asterisk on required labels, validate
|
|
2260
|
+
**client-side** before calling \`createInquiry()\`, and show inline error
|
|
2261
|
+
messages. Do NOT rely only on the server returning 400.
|
|
2262
|
+
|
|
1958
2263
|
\`\`\`tsx
|
|
1959
2264
|
import type { ContactFormPublic, ContactFormPublicField } from 'brainerce';
|
|
1960
2265
|
|
|
@@ -1972,13 +2277,24 @@ function isEmpty(v: FieldValue): boolean {
|
|
|
1972
2277
|
return v === false;
|
|
1973
2278
|
}
|
|
1974
2279
|
|
|
2280
|
+
// Map width \u2192 CSS grid column span (6-column grid)
|
|
2281
|
+
function widthClass(w?: string): string {
|
|
2282
|
+
switch (w) {
|
|
2283
|
+
case 'HALF': return 'grid-col-half'; // grid-column: span 3; on sm+, full on mobile
|
|
2284
|
+
case 'THIRD': return 'grid-col-third'; // grid-column: span 2; on sm+, full on mobile
|
|
2285
|
+
default: return 'grid-col-full'; // grid-column: span 6
|
|
2286
|
+
}
|
|
2287
|
+
}
|
|
2288
|
+
|
|
1975
2289
|
function DynamicField({
|
|
1976
2290
|
field,
|
|
1977
2291
|
value,
|
|
2292
|
+
error,
|
|
1978
2293
|
onChange,
|
|
1979
2294
|
}: {
|
|
1980
2295
|
field: ContactFormPublicField;
|
|
1981
2296
|
value: FieldValue;
|
|
2297
|
+
error?: string;
|
|
1982
2298
|
onChange: (v: FieldValue) => void;
|
|
1983
2299
|
}) {
|
|
1984
2300
|
const id = \`contact-\${field.key}\`;
|
|
@@ -1993,37 +2309,40 @@ function DynamicField({
|
|
|
1993
2309
|
</label>
|
|
1994
2310
|
);
|
|
1995
2311
|
const help = field.helpText ? <p className="mt-1 text-xs opacity-70">{field.helpText}</p> : null;
|
|
2312
|
+
const errorEl = error ? <p className="mt-1 text-xs text-red-500">{error}</p> : null;
|
|
1996
2313
|
|
|
2314
|
+
// Outer div uses widthClass to control grid-column span
|
|
1997
2315
|
switch (field.type) {
|
|
1998
2316
|
case 'TEXTAREA':
|
|
1999
|
-
return (<div>{label}<textarea id={id} required={field.isRequired} maxLength={maxLength} minLength={minLength} rows={6} placeholder={field.placeholder} value={strVal} onChange={(e) => onChange(e.target.value)} />{help}</div>);
|
|
2317
|
+
return (<div className={widthClass(field.width)}>{label}<textarea id={id} required={field.isRequired} maxLength={maxLength} minLength={minLength} rows={6} placeholder={field.placeholder} value={strVal} onChange={(e) => onChange(e.target.value)} />{help}{errorEl}</div>);
|
|
2000
2318
|
case 'EMAIL':
|
|
2001
|
-
return (<div>{label}<input id={id} type="email" required={field.isRequired} autoComplete="email" placeholder={field.placeholder} value={strVal} onChange={(e) => onChange(e.target.value)} />{help}</div>);
|
|
2319
|
+
return (<div className={widthClass(field.width)}>{label}<input id={id} type="email" required={field.isRequired} autoComplete="email" placeholder={field.placeholder} value={strVal} onChange={(e) => onChange(e.target.value)} />{help}{errorEl}</div>);
|
|
2002
2320
|
case 'PHONE':
|
|
2003
|
-
return (<div>{label}<input id={id} type="tel" required={field.isRequired} autoComplete="tel" placeholder={field.placeholder} value={strVal} onChange={(e) => onChange(e.target.value)} />{help}</div>);
|
|
2321
|
+
return (<div className={widthClass(field.width)}>{label}<input id={id} type="tel" required={field.isRequired} autoComplete="tel" placeholder={field.placeholder} value={strVal} onChange={(e) => onChange(e.target.value)} />{help}{errorEl}</div>);
|
|
2004
2322
|
case 'URL':
|
|
2005
|
-
return (<div>{label}<input id={id} type="url" required={field.isRequired} placeholder={field.placeholder} value={strVal} onChange={(e) => onChange(e.target.value)} />{help}</div>);
|
|
2323
|
+
return (<div className={widthClass(field.width)}>{label}<input id={id} type="url" required={field.isRequired} placeholder={field.placeholder} value={strVal} onChange={(e) => onChange(e.target.value)} />{help}{errorEl}</div>);
|
|
2006
2324
|
case 'NUMBER':
|
|
2007
|
-
return (<div>{label}<input id={id} type="number" required={field.isRequired} min={min} max={max} placeholder={field.placeholder} value={strVal} onChange={(e) => onChange(e.target.value)} />{help}</div>);
|
|
2325
|
+
return (<div className={widthClass(field.width)}>{label}<input id={id} type="number" required={field.isRequired} min={min} max={max} placeholder={field.placeholder} value={strVal} onChange={(e) => onChange(e.target.value)} />{help}{errorEl}</div>);
|
|
2008
2326
|
case 'DATE':
|
|
2009
|
-
return (<div>{label}<input id={id} type="date" required={field.isRequired} value={strVal} onChange={(e) => onChange(e.target.value)} />{help}</div>);
|
|
2327
|
+
return (<div className={widthClass(field.width)}>{label}<input id={id} type="date" required={field.isRequired} value={strVal} onChange={(e) => onChange(e.target.value)} />{help}{errorEl}</div>);
|
|
2010
2328
|
case 'SELECT':
|
|
2011
|
-
return (<div>{label}<select id={id} required={field.isRequired} value={strVal} onChange={(e) => onChange(e.target.value)}><option value="">\u2014</option>{field.enumValues?.map((o) => (<option key={o.value} value={o.value}>{o.label}</option>))}</select>{help}</div>);
|
|
2329
|
+
return (<div className={widthClass(field.width)}>{label}<select id={id} required={field.isRequired} value={strVal} onChange={(e) => onChange(e.target.value)}><option value="">\u2014</option>{field.enumValues?.map((o) => (<option key={o.value} value={o.value}>{o.label}</option>))}</select>{help}{errorEl}</div>);
|
|
2012
2330
|
case 'MULTI_SELECT': {
|
|
2013
2331
|
const arr = Array.isArray(value) ? value : [];
|
|
2014
|
-
return (<div>{label}<div>{field.enumValues?.map((o) => { const checked = arr.includes(o.value); return (<label key={o.value}><input type="checkbox" checked={checked} onChange={(e) => onChange(e.target.checked ? [...arr, o.value] : arr.filter((v) => v !== o.value))} /><span>{o.label}</span></label>); })}</div>{help}</div>);
|
|
2332
|
+
return (<div className={widthClass(field.width)}>{label}<div>{field.enumValues?.map((o) => { const checked = arr.includes(o.value); return (<label key={o.value}><input type="checkbox" checked={checked} onChange={(e) => onChange(e.target.checked ? [...arr, o.value] : arr.filter((v) => v !== o.value))} /><span>{o.label}</span></label>); })}</div>{help}{errorEl}</div>);
|
|
2015
2333
|
}
|
|
2016
2334
|
case 'CHECKBOX':
|
|
2017
|
-
return (<div><label htmlFor={id}><input id={id} type="checkbox" required={field.isRequired} checked={value === true} onChange={(e) => onChange(e.target.checked)} /><span>{field.label}</span></label>{help}</div>);
|
|
2335
|
+
return (<div className={widthClass(field.width)}><label htmlFor={id}><input id={id} type="checkbox" required={field.isRequired} checked={value === true} onChange={(e) => onChange(e.target.checked)} /><span>{field.label}</span></label>{help}{errorEl}</div>);
|
|
2018
2336
|
case 'TEXT':
|
|
2019
2337
|
default:
|
|
2020
|
-
return (<div>{label}<input id={id} type="text" required={field.isRequired} maxLength={maxLength} minLength={minLength} pattern={pattern} placeholder={field.placeholder} value={strVal} onChange={(e) => onChange(e.target.value)} />{help}</div>);
|
|
2338
|
+
return (<div className={widthClass(field.width)}>{label}<input id={id} type="text" required={field.isRequired} maxLength={maxLength} minLength={minLength} pattern={pattern} placeholder={field.placeholder} value={strVal} onChange={(e) => onChange(e.target.value)} />{help}{errorEl}</div>);
|
|
2021
2339
|
}
|
|
2022
2340
|
}
|
|
2023
2341
|
|
|
2024
2342
|
export function ContactPage() {
|
|
2025
2343
|
const [schema, setSchema] = useState<ContactFormPublic | null>(null);
|
|
2026
2344
|
const [values, setValues] = useState<Record<string, FieldValue>>({});
|
|
2345
|
+
const [errors, setErrors] = useState<Record<string, string>>({});
|
|
2027
2346
|
const [honeypot, setHoneypot] = useState('');
|
|
2028
2347
|
const [sent, setSent] = useState(false);
|
|
2029
2348
|
const [loading, setLoading] = useState(false);
|
|
@@ -2047,6 +2366,19 @@ export function ContactPage() {
|
|
|
2047
2366
|
if (loading) return;
|
|
2048
2367
|
if (honeypot.trim().length > 0) { setSent(true); return; } // bot \u2192 silent success
|
|
2049
2368
|
|
|
2369
|
+
// \u2500\u2500 Client-side required-field validation \u2500\u2500
|
|
2370
|
+
const newErrors: Record<string, string> = {};
|
|
2371
|
+
for (const f of schema.fields) {
|
|
2372
|
+
if (f.isRequired && isEmpty(values[f.key] ?? defaultValueFor(f))) {
|
|
2373
|
+
newErrors[f.key] = \`\${f.label} is required\`; // or pull from your i18n system
|
|
2374
|
+
}
|
|
2375
|
+
}
|
|
2376
|
+
if (Object.keys(newErrors).length > 0) {
|
|
2377
|
+
setErrors(newErrors);
|
|
2378
|
+
return; // block submission
|
|
2379
|
+
}
|
|
2380
|
+
setErrors({});
|
|
2381
|
+
|
|
2050
2382
|
setLoading(true);
|
|
2051
2383
|
try {
|
|
2052
2384
|
const payload: Record<string, unknown> = {};
|
|
@@ -2079,11 +2411,15 @@ export function ContactPage() {
|
|
|
2079
2411
|
value={honeypot} onChange={(e) => setHoneypot(e.target.value)} />
|
|
2080
2412
|
</div>
|
|
2081
2413
|
|
|
2082
|
-
{
|
|
2083
|
-
|
|
2084
|
-
|
|
2085
|
-
|
|
2086
|
-
|
|
2414
|
+
{/* CSS grid \u2014 6 columns on sm+, 1 column on mobile */}
|
|
2415
|
+
<div style={{ display: 'grid', gridTemplateColumns: 'repeat(6, 1fr)', gap: '1rem' }}>
|
|
2416
|
+
{schema.fields.map((field) => (
|
|
2417
|
+
<DynamicField key={field.key} field={field}
|
|
2418
|
+
value={values[field.key] ?? defaultValueFor(field)}
|
|
2419
|
+
error={errors[field.key]}
|
|
2420
|
+
onChange={(v) => setValues((p) => ({ ...p, [field.key]: v }))} />
|
|
2421
|
+
))}
|
|
2422
|
+
</div>
|
|
2087
2423
|
|
|
2088
2424
|
<button type="submit" disabled={loading}>
|
|
2089
2425
|
{loading ? '\u2026' : schema.submitButton}
|
|
@@ -2093,13 +2429,27 @@ export function ContactPage() {
|
|
|
2093
2429
|
}
|
|
2094
2430
|
\`\`\`
|
|
2095
2431
|
|
|
2432
|
+
CSS for the grid column helpers (or use the equivalent Tailwind / inline styles):
|
|
2433
|
+
|
|
2434
|
+
\`\`\`css
|
|
2435
|
+
.grid-col-full { grid-column: span 6; }
|
|
2436
|
+
.grid-col-half { grid-column: span 6; }
|
|
2437
|
+
.grid-col-third { grid-column: span 6; }
|
|
2438
|
+
|
|
2439
|
+
@media (min-width: 640px) {
|
|
2440
|
+
.grid-col-half { grid-column: span 3; }
|
|
2441
|
+
.grid-col-third { grid-column: span 2; }
|
|
2442
|
+
}
|
|
2443
|
+
\`\`\`
|
|
2444
|
+
|
|
2096
2445
|
### Rules
|
|
2097
2446
|
|
|
2098
2447
|
- **Rate limit:** 3 submissions / 60s per IP \u2014 show a friendly "try again later" message on HTTP 429.
|
|
2099
2448
|
- **Honeypot:** always render a hidden field named \`honeypot\` and **never send** it. Bots fill every input; the server rejects submissions carrying a non-empty \`honeypot\`.
|
|
2100
2449
|
- **Built-in keys:** \`name\`, \`email\`, \`phone\`, \`subject\`, \`message\` always exist on the default form; the legacy \`createInquiry\` shape keeps working forever.
|
|
2101
2450
|
- **Max values:** each field value is capped at 10 000 chars server-side. Validate client-side before submitting using \`field.validation.maxLength\`.
|
|
2102
|
-
- **Required fields:** respect \`field.isRequired\`. The server validates too, but
|
|
2451
|
+
- **Required fields:** respect \`field.isRequired\`. Show a red asterisk (\`*\`) next to the label. **Validate client-side before submission** \u2014 iterate over \`schema.fields\`, check \`isEmpty(values[f.key])\` for each required field, and block the submit with inline error messages. The server validates too, but the user should never see a raw 400 error.
|
|
2452
|
+
- **Width (layout):** respect \`field.width\`. Use a CSS grid with 6 columns: \`FULL\` = span 6 (default), \`HALF\` = span 3, \`THIRD\` = span 2. Stack to full width on small screens. If \`width\` is missing, treat as \`FULL\`.
|
|
2103
2453
|
- **Validation:** when \`field.validation.pattern\` is present, pass it as the input's \`pattern\` attribute; the server also enforces it. Likewise \`minLength\`/\`maxLength\`/\`min\`/\`max\`.
|
|
2104
2454
|
- **Enum values:** SELECT and MULTI_SELECT always return \`enumValues\` (non-empty array). Render from \`enumValues\`, never a hardcoded list.
|
|
2105
2455
|
- **Visibility:** the server strips fields with \`isVisible=false\`, so \`schema.fields\` only contains things to render.
|
|
@@ -2131,6 +2481,8 @@ function getSectionByTopic(topic, connectionId, currency) {
|
|
|
2131
2481
|
return getCheckoutCustomFieldsSection();
|
|
2132
2482
|
case "payment":
|
|
2133
2483
|
return getPaymentProvidersSection();
|
|
2484
|
+
case "saved-payment-methods":
|
|
2485
|
+
return getSavedPaymentMethodsSection();
|
|
2134
2486
|
case "auth":
|
|
2135
2487
|
return getCustomerAuthSection();
|
|
2136
2488
|
case "order-confirmation":
|
|
@@ -2143,6 +2495,8 @@ function getSectionByTopic(topic, connectionId, currency) {
|
|
|
2143
2495
|
return getRecommendationsSection();
|
|
2144
2496
|
case "product-customization-fields":
|
|
2145
2497
|
return getProductCustomizationFieldsSection();
|
|
2498
|
+
case "modifier-groups":
|
|
2499
|
+
return getModifierGroupsSection();
|
|
2146
2500
|
case "tax":
|
|
2147
2501
|
return getTaxDisplaySection(cur);
|
|
2148
2502
|
case "i18n":
|
|
@@ -2223,6 +2577,10 @@ function getSectionByTopic(topic, connectionId, currency) {
|
|
|
2223
2577
|
"",
|
|
2224
2578
|
"---",
|
|
2225
2579
|
"",
|
|
2580
|
+
getModifierGroupsSection(),
|
|
2581
|
+
"",
|
|
2582
|
+
"---",
|
|
2583
|
+
"",
|
|
2226
2584
|
getTaxDisplaySection(cur),
|
|
2227
2585
|
"",
|
|
2228
2586
|
"---",
|
|
@@ -2267,11 +2625,19 @@ var GET_SDK_DOCS_SCHEMA = {
|
|
|
2267
2625
|
"inquiries",
|
|
2268
2626
|
"all"
|
|
2269
2627
|
]).describe("The SDK documentation topic to retrieve"),
|
|
2270
|
-
|
|
2628
|
+
salesChannelId: z.string().optional().describe("Sales channel ID (starts with vc_). Used to personalize setup code."),
|
|
2629
|
+
/** @deprecated alias of salesChannelId */
|
|
2630
|
+
connectionId: z.string().optional().describe("Deprecated alias of salesChannelId \u2014 kept for backwards compat"),
|
|
2271
2631
|
currency: z.string().optional().describe("Store currency code (e.g., USD, ILS, EUR). Used in price formatting examples.")
|
|
2272
2632
|
};
|
|
2273
2633
|
async function handleGetSdkDocs(args) {
|
|
2274
|
-
const
|
|
2634
|
+
const id = args.salesChannelId ?? args.connectionId;
|
|
2635
|
+
if (!args.salesChannelId && args.connectionId) {
|
|
2636
|
+
console.warn(
|
|
2637
|
+
"get-sdk-docs: `connectionId` is deprecated \u2014 use `salesChannelId` instead"
|
|
2638
|
+
);
|
|
2639
|
+
}
|
|
2640
|
+
const content = getSectionByTopic(args.topic, id, args.currency);
|
|
2275
2641
|
return {
|
|
2276
2642
|
content: [{ type: "text", text: content }]
|
|
2277
2643
|
};
|
|
@@ -2293,6 +2659,9 @@ interface Product {
|
|
|
2293
2659
|
basePrice: string; // Use parseFloat() for calculations
|
|
2294
2660
|
salePrice?: string | null;
|
|
2295
2661
|
costPrice?: string | null;
|
|
2662
|
+
priceMin?: string | null; // Lowest variant price (VARIABLE products). Use for catalog/JSON-LD range display.
|
|
2663
|
+
priceMax?: string | null; // Highest variant price (VARIABLE products).
|
|
2664
|
+
priceVaries?: boolean; // true when variant prices differ \u2014 show "\u20AA49 \u2013 \u20AA199" range.
|
|
2296
2665
|
status: string;
|
|
2297
2666
|
type: 'SIMPLE' | 'VARIABLE';
|
|
2298
2667
|
isDownloadable?: boolean;
|
|
@@ -2310,7 +2679,7 @@ interface Product {
|
|
|
2310
2679
|
attributeId: string;
|
|
2311
2680
|
attributeOptionId: string;
|
|
2312
2681
|
platform: string;
|
|
2313
|
-
attribute: { id: string; name: string; displayType?: 'DEFAULT' | 'COLOR_SWATCH' | 'IMAGE_SWATCH' } | null;
|
|
2682
|
+
attribute: { id: string; name: string; displayType?: 'DEFAULT' | 'COLOR_SWATCH' | 'IMAGE_SWATCH' | 'MIXED_SWATCH' } | null;
|
|
2314
2683
|
attributeOption: { id: string; name: string; value?: string | null; swatchColor?: string | null; swatchColor2?: string | null; swatchImageUrl?: string | null } | null;
|
|
2315
2684
|
}>;
|
|
2316
2685
|
createdAt: string;
|
|
@@ -2319,6 +2688,8 @@ interface Product {
|
|
|
2319
2688
|
|
|
2320
2689
|
// Use getProductSwatches(product) to get grouped swatch data for storefront rendering.
|
|
2321
2690
|
// Returns Array<{ attributeName, displayType, options: Array<{ name, swatchColor?, swatchColor2?, swatchImageUrl? }> }>
|
|
2691
|
+
// displayType rendering: COLOR_SWATCH \u2192 color circle (swatchColor/swatchColor2); IMAGE_SWATCH \u2192 image thumbnail (swatchImageUrl);
|
|
2692
|
+
// MIXED_SWATCH \u2192 per-option: render swatchImageUrl if set, else swatchColor if set, else text only.
|
|
2322
2693
|
|
|
2323
2694
|
interface ProductImage {
|
|
2324
2695
|
url: string;
|
|
@@ -2399,6 +2770,10 @@ interface ProductQueryParams {
|
|
|
2399
2770
|
tags?: string | string[];
|
|
2400
2771
|
minPrice?: number;
|
|
2401
2772
|
maxPrice?: number;
|
|
2773
|
+
// Filter by custom-field (metafield) values. Keys = definition.key,
|
|
2774
|
+
// values = accepted values. Only definitions with filterable=true and
|
|
2775
|
+
// type SELECT/MULTI_SELECT/BOOLEAN are honored. AND across keys, OR within.
|
|
2776
|
+
metafields?: Record<string, string | string[]>;
|
|
2402
2777
|
sortBy?: 'name' | 'price' | 'createdAt';
|
|
2403
2778
|
sortOrder?: 'asc' | 'desc';
|
|
2404
2779
|
}
|
|
@@ -2816,6 +3191,36 @@ interface PaymentStatus {
|
|
|
2816
3191
|
error?: string;
|
|
2817
3192
|
}
|
|
2818
3193
|
|
|
3194
|
+
// ---- Saved Payment Methods (vaulted cards) ----
|
|
3195
|
+
// Display-only summary of a customer's vaulted payment method. The
|
|
3196
|
+
// underlying provider token is encrypted at rest in the platform DB
|
|
3197
|
+
// and NEVER returned through the SDK.
|
|
3198
|
+
//
|
|
3199
|
+
// To opt into vaulting at checkout, pass saveCard: true to
|
|
3200
|
+
// createPaymentIntent (only honored for logged-in customers).
|
|
3201
|
+
//
|
|
3202
|
+
// To list / remove saved methods, see:
|
|
3203
|
+
// client.listSavedPaymentMethods(storeId, customerId)
|
|
3204
|
+
// client.removeSavedPaymentMethod(storeId, customerId, methodId)
|
|
3205
|
+
|
|
3206
|
+
interface SavedPaymentMethodSummary {
|
|
3207
|
+
id: string;
|
|
3208
|
+
customerId: string;
|
|
3209
|
+
appInstallationId: string;
|
|
3210
|
+
paymentMethod: string; // 'credit_card' | 'paypal' | 'bank_account'
|
|
3211
|
+
brand: string | null;
|
|
3212
|
+
last4: string | null;
|
|
3213
|
+
expMonth: number | null;
|
|
3214
|
+
expYear: number | null;
|
|
3215
|
+
isDefault: boolean;
|
|
3216
|
+
status: string; // 'active' | 'expired' | 'invalid'
|
|
3217
|
+
failureReason: string | null;
|
|
3218
|
+
lastUsedAt: string | null;
|
|
3219
|
+
expiresAt: string | null;
|
|
3220
|
+
createdAt: string;
|
|
3221
|
+
updatedAt: string;
|
|
3222
|
+
}
|
|
3223
|
+
|
|
2819
3224
|
interface WaitForOrderResult {
|
|
2820
3225
|
success: boolean;
|
|
2821
3226
|
status: PaymentStatus; // Access: result.status.orderNumber
|
|
@@ -2827,9 +3232,9 @@ var HELPERS_TYPES = `// ---- Helper Functions (import from 'brainerce') ----
|
|
|
2827
3232
|
// Price helpers
|
|
2828
3233
|
function formatPrice(priceString: string | number | undefined | null, options?: { currency?: string; locale?: string; }): string;
|
|
2829
3234
|
function getProductPrice(product: Pick<Product, 'basePrice' | 'salePrice'>): number;
|
|
2830
|
-
function getProductPriceInfo(product: Pick<Product, 'basePrice' | 'salePrice'>): {
|
|
3235
|
+
function getProductPriceInfo(product: Pick<Product, 'basePrice' | 'salePrice' | 'discount' | 'priceMin' | 'priceVaries'>): {
|
|
2831
3236
|
price: number; originalPrice: number; isOnSale: boolean; discountAmount: number; discountPercent: number;
|
|
2832
|
-
};
|
|
3237
|
+
}; // Falls back to priceMin when basePrice=0 (VARIABLE products)
|
|
2833
3238
|
function getVariantPrice(variant: Pick<ProductVariant, 'price' | 'salePrice'>, productBasePrice: string): number;
|
|
2834
3239
|
|
|
2835
3240
|
// Cart helpers
|
|
@@ -2915,15 +3320,32 @@ interface CartUpgradeSuggestion {
|
|
|
2915
3320
|
priceDelta: string;
|
|
2916
3321
|
deltaPercent: number;
|
|
2917
3322
|
}
|
|
2918
|
-
interface
|
|
3323
|
+
interface CartBundleOfferOfferedProduct {
|
|
2919
3324
|
id: string;
|
|
2920
|
-
|
|
3325
|
+
name: string;
|
|
3326
|
+
slug: string | null;
|
|
3327
|
+
basePrice: string;
|
|
3328
|
+
salePrice: string | null;
|
|
3329
|
+
images: Array<{ url: string }>;
|
|
3330
|
+
type: string;
|
|
2921
3331
|
originalPrice: string;
|
|
2922
3332
|
discountedPrice: string;
|
|
3333
|
+
}
|
|
3334
|
+
interface CartBundleOffer {
|
|
3335
|
+
id: string;
|
|
3336
|
+
name: string;
|
|
3337
|
+
description: string | null;
|
|
3338
|
+
// productIds[0] = trigger product (must be in cart for the bundle to surface);
|
|
3339
|
+
// productIds[1..] = offered together at the bundle discount.
|
|
3340
|
+
triggerProductId: string;
|
|
3341
|
+
productIds: string[];
|
|
3342
|
+
// offeredProducts = productIds[1..] minus those already in cart, each with
|
|
3343
|
+
// its own original/discounted price applied.
|
|
3344
|
+
offeredProducts: CartBundleOfferOfferedProduct[];
|
|
2923
3345
|
discountType: 'PERCENTAGE' | 'FIXED_AMOUNT';
|
|
2924
|
-
discountValue:
|
|
2925
|
-
|
|
2926
|
-
|
|
3346
|
+
discountValue: string;
|
|
3347
|
+
totalOriginalPrice: string;
|
|
3348
|
+
totalDiscountedPrice: string;
|
|
2927
3349
|
}`;
|
|
2928
3350
|
var INQUIRIES_TYPES = `// ---- Contact Inquiries & Forms ----
|
|
2929
3351
|
|
|
@@ -2978,6 +3400,7 @@ interface ContactFormPublicField {
|
|
|
2978
3400
|
enumValues?: { value: string; label: string }[]; // present (non-empty) for SELECT / MULTI_SELECT
|
|
2979
3401
|
validation?: ContactFormFieldValidation;
|
|
2980
3402
|
defaultValue?: string;
|
|
3403
|
+
width?: 'FULL' | 'HALF' | 'THIRD'; // layout hint \u2014 FULL = full row, HALF = half row, THIRD = one-third row
|
|
2981
3404
|
}
|
|
2982
3405
|
|
|
2983
3406
|
interface ContactFormPublic {
|
|
@@ -3009,6 +3432,19 @@ interface ContactFormSummary {
|
|
|
3009
3432
|
// MULTI_SELECT \u2192 multiple <input type="checkbox">, value is string[]
|
|
3010
3433
|
// CHECKBOX \u2192 single <input type="checkbox">, value is boolean
|
|
3011
3434
|
// ------------------------------------------------------------------
|
|
3435
|
+
//
|
|
3436
|
+
// Layout: render fields inside a CSS grid container.
|
|
3437
|
+
// width='FULL' (default) \u2192 span entire row
|
|
3438
|
+
// width='HALF' \u2192 span half the row (two HALF fields sit side-by-side)
|
|
3439
|
+
// width='THIRD' \u2192 span one-third of the row (three THIRD fields sit side-by-side)
|
|
3440
|
+
// Use a 6-column grid for clean divisibility:
|
|
3441
|
+
// FULL \u2192 col-span-6 | HALF \u2192 col-span-3 | THIRD \u2192 col-span-2
|
|
3442
|
+
// Stack to full width on small screens (< sm breakpoint).
|
|
3443
|
+
//
|
|
3444
|
+
// Required fields: show a red asterisk (*) next to the label, validate
|
|
3445
|
+
// client-side before submission, and display inline error messages for
|
|
3446
|
+
// any empty required field. Do NOT rely only on the server returning 400.
|
|
3447
|
+
// ------------------------------------------------------------------
|
|
3012
3448
|
|
|
3013
3449
|
// SDK methods
|
|
3014
3450
|
// await brainerce.createInquiry(input) \u2192 POST /stores/{storeId}/inquiries
|
|
@@ -3021,6 +3457,130 @@ interface ContactFormSummary {
|
|
|
3021
3457
|
// - Always pass \`locale\` \u2014 inbox filters inquiries by language, and schema labels come back translated
|
|
3022
3458
|
// - Render \`schema.name\` / \`description\` / \`submitButton\` / \`successMessage\` directly \u2014 do NOT hardcode copy
|
|
3023
3459
|
// - Unknown field keys are stripped server-side \u2014 safe to send extras during dev`;
|
|
3460
|
+
var MODIFIER_GROUPS_TYPES = `// ---- Modifier Groups (Restaurant / Build-Your-Own) ----
|
|
3461
|
+
// Modifier groups are merchant-defined option blocks attached to a product
|
|
3462
|
+
// (toppings, sauce, bread type, \u2026). They differ from product.customizationFields:
|
|
3463
|
+
// modifier groups are STRUCTURED priced choices validated server-side, while
|
|
3464
|
+
// customizationFields are arbitrary buyer input (text/photo/color).
|
|
3465
|
+
//
|
|
3466
|
+
// Money fields are decimal STRINGS on the wire \u2014 "5.00", "-2.00" (downsell).
|
|
3467
|
+
// Never JSON Number. Use parseFloat() only at display time. Do not compute
|
|
3468
|
+
// the line total client-side; the server runs free-allocation and returns
|
|
3469
|
+
// cart.items[i].unitPrice + .modifiers[] + .modifiersTotal.
|
|
3470
|
+
|
|
3471
|
+
export type ModifierSelectionType = 'SINGLE' | 'MULTIPLE';
|
|
3472
|
+
|
|
3473
|
+
export type FreeAllocationPolicy = 'EXPENSIVE_FREE' | 'CHEAPEST_FREE' | 'SELECTION_ORDER';
|
|
3474
|
+
|
|
3475
|
+
export interface Modifier {
|
|
3476
|
+
id: string;
|
|
3477
|
+
name: string;
|
|
3478
|
+
description?: string;
|
|
3479
|
+
/** Decimal string. Negative values = downsell modifiers ("-2.00"). */
|
|
3480
|
+
priceDelta: string;
|
|
3481
|
+
sku?: string;
|
|
3482
|
+
image?: { url: string; thumbnailUrl?: string; alt?: string };
|
|
3483
|
+
position: number;
|
|
3484
|
+
/** Pre-checked on first render. */
|
|
3485
|
+
isDefault: boolean;
|
|
3486
|
+
/** false = sold out \u2014 disable in UI with a "Sold out" badge. */
|
|
3487
|
+
available: boolean;
|
|
3488
|
+
/** When true, never applied as a free selection \u2014 always charges priceDelta even when freeQuantity > 0 on the group. */
|
|
3489
|
+
excludeFromFree?: boolean;
|
|
3490
|
+
/** Nested combo: opens a sub-flow; depth \u2264 3 enforced server-side. */
|
|
3491
|
+
referencedProductId?: string;
|
|
3492
|
+
translations?: Record<string, { name?: string; description?: string }>;
|
|
3493
|
+
}
|
|
3494
|
+
|
|
3495
|
+
export interface ModifierGroup {
|
|
3496
|
+
id: string;
|
|
3497
|
+
/**
|
|
3498
|
+
* Set when fetched in a product context (the ProductModifierGroup row id).
|
|
3499
|
+
* Use this to update or detach the attachment without reattaching the group.
|
|
3500
|
+
*/
|
|
3501
|
+
attachmentId?: string;
|
|
3502
|
+
/** Customer-facing canonical name. */
|
|
3503
|
+
name: string;
|
|
3504
|
+
/**
|
|
3505
|
+
* Admin-only disambiguator \u2014 NEVER present in storefront responses.
|
|
3506
|
+
* If your client code reads this, you're hitting an admin endpoint by mistake.
|
|
3507
|
+
*/
|
|
3508
|
+
internalName?: string;
|
|
3509
|
+
description?: string;
|
|
3510
|
+
selectionType: ModifierSelectionType;
|
|
3511
|
+
/** Effective minimum after any per-attach / per-variant overrides. */
|
|
3512
|
+
min: number;
|
|
3513
|
+
/** Effective maximum; null = unlimited. **0 = group hidden for this variant** (PRD \xA77.2.2). */
|
|
3514
|
+
max?: number | null;
|
|
3515
|
+
freeQuantity: number;
|
|
3516
|
+
required: boolean;
|
|
3517
|
+
freeAllocationPolicy: FreeAllocationPolicy;
|
|
3518
|
+
modifiers: Modifier[];
|
|
3519
|
+
/** Effective default selections (after attachment-level overrides). */
|
|
3520
|
+
defaultModifierIds: string[];
|
|
3521
|
+
translations?: Record<string, { name?: string; description?: string }>;
|
|
3522
|
+
}
|
|
3523
|
+
|
|
3524
|
+
/** Customer-side selection payload \u2014 modifierIds in click-order. */
|
|
3525
|
+
export interface ModifierSelection {
|
|
3526
|
+
modifierGroupId: string;
|
|
3527
|
+
modifierIds: string[];
|
|
3528
|
+
}
|
|
3529
|
+
|
|
3530
|
+
/** Per-line modifier breakdown surfaced on cart.items[i] / order.items[i]. */
|
|
3531
|
+
export interface CartItemModifierLine {
|
|
3532
|
+
modifierId: string;
|
|
3533
|
+
/** Snapshot of the modifier's name at the time the line was added. */
|
|
3534
|
+
name: string;
|
|
3535
|
+
/** Decimal string snapshot of the priceDelta at the time the line was added. */
|
|
3536
|
+
priceDelta: string;
|
|
3537
|
+
/** True if this modifier consumed one of the group's free slots. */
|
|
3538
|
+
freeApplied: boolean;
|
|
3539
|
+
}
|
|
3540
|
+
|
|
3541
|
+
/**
|
|
3542
|
+
* Stable error codes returned in the structured 400 envelope when a cart
|
|
3543
|
+
* payload fails server-side validation. The SDK exposes the envelope on
|
|
3544
|
+
* BrainerceError.details \u2014 switch on details.code === 'MODIFIER_VALIDATION_FAILED'
|
|
3545
|
+
* first, then iterate details.errors[].
|
|
3546
|
+
*/
|
|
3547
|
+
export type ModifierValidationCode =
|
|
3548
|
+
| 'REQUIRED_GROUP_MISSING'
|
|
3549
|
+
| 'MIN_SELECTIONS_NOT_MET'
|
|
3550
|
+
| 'MAX_SELECTIONS_EXCEEDED'
|
|
3551
|
+
| 'SINGLE_GROUP_MULTIPLE_PICKS'
|
|
3552
|
+
| 'UNKNOWN_MODIFIER'
|
|
3553
|
+
| 'UNKNOWN_GROUP'
|
|
3554
|
+
| 'MODIFIER_DISABLED_FOR_VARIANT'
|
|
3555
|
+
| 'MODIFIER_NOT_AVAILABLE'
|
|
3556
|
+
| 'NESTED_DEPTH_EXCEEDED'
|
|
3557
|
+
| 'NESTED_REQUIRES_PRODUCT_REF'
|
|
3558
|
+
| 'INVALID_PRICE_DELTA'
|
|
3559
|
+
| 'MODIFIER_PRICE_FLOOR_VIOLATED';
|
|
3560
|
+
|
|
3561
|
+
export interface ModifierValidationError {
|
|
3562
|
+
code: ModifierValidationCode;
|
|
3563
|
+
message: string;
|
|
3564
|
+
modifierGroupId?: string;
|
|
3565
|
+
modifierId?: string;
|
|
3566
|
+
}
|
|
3567
|
+
|
|
3568
|
+
// Cart DTOs gain optional selections + nestedByModifierId \u2014 see CART_TYPES above.
|
|
3569
|
+
// Add to cart with selections:
|
|
3570
|
+
//
|
|
3571
|
+
// await client.smartAddToCart({
|
|
3572
|
+
// productId,
|
|
3573
|
+
// variantId,
|
|
3574
|
+
// quantity: 1,
|
|
3575
|
+
// selections: [
|
|
3576
|
+
// { modifierGroupId: 'mg_bread', modifierIds: ['m_thick'] },
|
|
3577
|
+
// { modifierGroupId: 'mg_toppings', modifierIds: ['m_olive', 'm_bacon'] },
|
|
3578
|
+
// ],
|
|
3579
|
+
// });
|
|
3580
|
+
//
|
|
3581
|
+
// The cart line then carries:
|
|
3582
|
+
// cart.items[i].modifiers \u2014 CartItemModifierLine[]
|
|
3583
|
+
// cart.items[i].modifiersTotal \u2014 decimal string of the paid (non-free) deltas`;
|
|
3024
3584
|
var TYPES_BY_DOMAIN = {
|
|
3025
3585
|
products: PRODUCTS_TYPES,
|
|
3026
3586
|
cart: CART_TYPES,
|
|
@@ -3029,7 +3589,8 @@ var TYPES_BY_DOMAIN = {
|
|
|
3029
3589
|
customers: CUSTOMERS_TYPES,
|
|
3030
3590
|
payments: PAYMENTS_TYPES,
|
|
3031
3591
|
helpers: HELPERS_TYPES,
|
|
3032
|
-
inquiries: INQUIRIES_TYPES
|
|
3592
|
+
inquiries: INQUIRIES_TYPES,
|
|
3593
|
+
"modifier-groups": MODIFIER_GROUPS_TYPES
|
|
3033
3594
|
};
|
|
3034
3595
|
function getTypesByDomain(domain) {
|
|
3035
3596
|
if (domain === "all") {
|
|
@@ -3095,7 +3656,12 @@ var GET_CODE_EXAMPLE_SCHEMA = {
|
|
|
3095
3656
|
"reservation-countdown",
|
|
3096
3657
|
"search-autocomplete-debounce",
|
|
3097
3658
|
"i18n-set-locale",
|
|
3098
|
-
"order-history-full"
|
|
3659
|
+
"order-history-full",
|
|
3660
|
+
"modifier-groups-render",
|
|
3661
|
+
"cart-add-with-selections",
|
|
3662
|
+
"modifier-validation-error-handling",
|
|
3663
|
+
"checkout-price-drift",
|
|
3664
|
+
"cart-item-modifier-display"
|
|
3099
3665
|
]).describe("The SDK operation to get a snippet for.")
|
|
3100
3666
|
};
|
|
3101
3667
|
var SNIPPETS = {
|
|
@@ -3103,7 +3669,10 @@ var SNIPPETS = {
|
|
|
3103
3669
|
import { BrainerceClient } from 'brainerce';
|
|
3104
3670
|
|
|
3105
3671
|
export const client = new BrainerceClient({
|
|
3106
|
-
|
|
3672
|
+
// Read either env var name (the new one is preferred; the old one is a soft
|
|
3673
|
+
// alias kept for backwards compatibility \u2014 both are accepted by the SDK).
|
|
3674
|
+
salesChannelId:
|
|
3675
|
+
process.env.BRAINERCE_SALES_CHANNEL_ID! ?? process.env.BRAINERCE_CONNECTION_ID!, // vc_*
|
|
3107
3676
|
});
|
|
3108
3677
|
|
|
3109
3678
|
// If the store has i18n enabled, set the locale at app start based on
|
|
@@ -3167,7 +3736,7 @@ function selectVariant(product: Product, selections: Record<string, string>) {
|
|
|
3167
3736
|
import { client } from './brainerce';
|
|
3168
3737
|
|
|
3169
3738
|
// 1. Submit the address + email. Email is REQUIRED on the DTO.
|
|
3170
|
-
const {
|
|
3739
|
+
const { checkout, rates } = await client.setShippingAddress(checkoutId, {
|
|
3171
3740
|
email,
|
|
3172
3741
|
firstName,
|
|
3173
3742
|
lastName,
|
|
@@ -3178,10 +3747,11 @@ const { shippingRates } = await client.setShippingAddress(checkoutId, {
|
|
|
3178
3747
|
postalCode,
|
|
3179
3748
|
country,
|
|
3180
3749
|
});
|
|
3750
|
+
// rates = available shipping rates; checkout = updated checkout object
|
|
3181
3751
|
|
|
3182
3752
|
// 2. Let the customer pick one of the returned rates.
|
|
3183
|
-
const chosen =
|
|
3184
|
-
await client.
|
|
3753
|
+
const chosen = rates[0]; // user selection
|
|
3754
|
+
await client.selectShippingMethod(checkoutId, chosen.id);
|
|
3185
3755
|
|
|
3186
3756
|
// 3. Re-fetch the checkout to get updated totals (tax may change after address).
|
|
3187
3757
|
const checkout = await client.getCheckout(checkoutId);
|
|
@@ -3235,21 +3805,21 @@ if (providers.length === 0) {
|
|
|
3235
3805
|
}
|
|
3236
3806
|
|
|
3237
3807
|
const active = providers[0];`,
|
|
3238
|
-
"checkout-stripe-confirm": `// Stripe confirm flow. Requires @stripe/stripe-js
|
|
3239
|
-
// (or the vanilla Stripe.js browser SDK).
|
|
3808
|
+
"checkout-stripe-confirm": `// Stripe confirm flow. Requires @stripe/stripe-js.
|
|
3240
3809
|
import { loadStripe } from '@stripe/stripe-js';
|
|
3241
3810
|
import { client } from './brainerce';
|
|
3242
3811
|
|
|
3243
3812
|
const stripe = await loadStripe(stripePublicKey);
|
|
3244
3813
|
if (!stripe) throw new Error('Stripe failed to load');
|
|
3245
3814
|
|
|
3246
|
-
//
|
|
3247
|
-
const
|
|
3248
|
-
|
|
3815
|
+
// Create a payment intent \u2014 returns clientSecret for Stripe Elements.
|
|
3816
|
+
const intent = await client.createPaymentIntent(checkoutId, {
|
|
3817
|
+
successUrl: \`\${window.location.origin}/order-confirmation?checkoutId=\${checkoutId}\`,
|
|
3818
|
+
cancelUrl: \`\${window.location.origin}/checkout?error=cancelled\`,
|
|
3249
3819
|
});
|
|
3250
3820
|
|
|
3251
|
-
// Use Stripe Elements to
|
|
3252
|
-
const result = await stripe.confirmCardPayment(clientSecret, {
|
|
3821
|
+
// Use Stripe Elements to confirm:
|
|
3822
|
+
const result = await stripe.confirmCardPayment(intent.clientSecret, {
|
|
3253
3823
|
payment_method: { card: cardElement },
|
|
3254
3824
|
});
|
|
3255
3825
|
|
|
@@ -3258,21 +3828,21 @@ if (result.error) {
|
|
|
3258
3828
|
return;
|
|
3259
3829
|
}
|
|
3260
3830
|
|
|
3261
|
-
// Success \u2014 redirect to
|
|
3831
|
+
// Success \u2014 redirect to confirmation page.
|
|
3262
3832
|
// The confirmation page runs handlePaymentSuccess + waitForOrder.
|
|
3263
3833
|
window.location.assign(\`/order-confirmation?checkoutId=\${checkoutId}\`);`,
|
|
3264
3834
|
"checkout-paypal-confirm": `// PayPal confirm flow. Use the PayPal JS SDK (render a PayPal button component).
|
|
3265
3835
|
import { client } from './brainerce';
|
|
3266
3836
|
|
|
3267
|
-
//
|
|
3268
|
-
|
|
3269
|
-
|
|
3270
|
-
|
|
3271
|
-
|
|
3272
|
-
});
|
|
3837
|
+
// Create a payment intent first \u2014 for PayPal this returns the PayPal order ID.
|
|
3838
|
+
const intent = await client.createPaymentIntent(checkoutId, {
|
|
3839
|
+
successUrl: \`\${window.location.origin}/order-confirmation?checkoutId=\${checkoutId}\`,
|
|
3840
|
+
cancelUrl: \`\${window.location.origin}/checkout?error=cancelled\`,
|
|
3841
|
+
});
|
|
3273
3842
|
|
|
3274
|
-
|
|
3275
|
-
|
|
3843
|
+
// Render a PayPal button using intent.clientSdk (provider SDK config).
|
|
3844
|
+
// When the PayPal button's onApprove fires, redirect to confirmation:
|
|
3845
|
+
function onPayPalApprove() {
|
|
3276
3846
|
window.location.assign(\`/order-confirmation?checkoutId=\${checkoutId}\`);
|
|
3277
3847
|
}`,
|
|
3278
3848
|
"checkout-sandbox-confirm": `// Sandbox payment \u2014 store has sandboxPaymentsEnabled=true. No real charge.
|
|
@@ -3315,7 +3885,7 @@ async function registerAndMaybeVerify(input: {
|
|
|
3315
3885
|
firstName: string;
|
|
3316
3886
|
lastName: string;
|
|
3317
3887
|
}) {
|
|
3318
|
-
const result = await client.
|
|
3888
|
+
const result = await client.registerCustomer(input);
|
|
3319
3889
|
if (result.requiresVerification) {
|
|
3320
3890
|
// Route the user to your verify-email UI. Do NOT treat them as logged in.
|
|
3321
3891
|
return { state: 'needs-verification' as const };
|
|
@@ -3336,7 +3906,7 @@ async function resendCode() {
|
|
|
3336
3906
|
import { client } from './brainerce';
|
|
3337
3907
|
|
|
3338
3908
|
async function login(email: string, password: string) {
|
|
3339
|
-
const result = await client.
|
|
3909
|
+
const result = await client.loginCustomer(email, password);
|
|
3340
3910
|
if (result.requiresVerification) {
|
|
3341
3911
|
return { state: 'needs-verification' as const };
|
|
3342
3912
|
}
|
|
@@ -3371,25 +3941,37 @@ async function submitReset(token: string, newPassword: string) {
|
|
|
3371
3941
|
"oauth-redirect-and-callback": `// OAuth sign-in. Redirect flow, NOT popup.
|
|
3372
3942
|
import { client } from './brainerce';
|
|
3373
3943
|
|
|
3374
|
-
//
|
|
3375
|
-
const providers = await client.getAvailableOAuthProviders();
|
|
3376
|
-
|
|
3377
|
-
|
|
3378
|
-
|
|
3944
|
+
// Step 1: Get available provider names (strings: 'GOOGLE', 'FACEBOOK', 'GITHUB')
|
|
3945
|
+
const { providers } = await client.getAvailableOAuthProviders();
|
|
3946
|
+
|
|
3947
|
+
// Step 2: For each provider, fetch the authorization URL, then redirect.
|
|
3948
|
+
// Call this when the user clicks a provider button:
|
|
3949
|
+
async function redirectToOAuth(provider: string) {
|
|
3950
|
+
const { authorizationUrl } = await client.getOAuthAuthorizeUrl(provider, {
|
|
3951
|
+
redirectUrl: \`\${window.location.origin}/auth/callback\`,
|
|
3952
|
+
});
|
|
3953
|
+
window.location.href = authorizationUrl; // full-page redirect, NOT a popup
|
|
3379
3954
|
}
|
|
3380
3955
|
|
|
3381
|
-
// On your
|
|
3382
|
-
|
|
3383
|
-
|
|
3384
|
-
|
|
3385
|
-
|
|
3386
|
-
|
|
3956
|
+
// Step 3: On your /auth/callback route, read token from URL params:
|
|
3957
|
+
const params = new URLSearchParams(window.location.search);
|
|
3958
|
+
const oauthError = params.get('oauth_error');
|
|
3959
|
+
const token = params.get('token');
|
|
3960
|
+
if (oauthError) {
|
|
3961
|
+
window.location.href = '/login?error=' + encodeURIComponent(oauthError);
|
|
3962
|
+
} else if (token) {
|
|
3963
|
+
client.setCustomerToken(token);
|
|
3964
|
+
window.location.href = '/account';
|
|
3965
|
+
}`,
|
|
3387
3966
|
"coupon-apply-and-remove": `// Coupon input. Build the UI even if no coupons exist today \u2014 it auto-hides.
|
|
3967
|
+
// IMPORTANT: use applyCheckoutCoupon when a checkoutId is available (checkout page).
|
|
3968
|
+
// Using applyCoupon after checkout creation does NOT update the checkout total.
|
|
3388
3969
|
import { client } from './brainerce';
|
|
3389
3970
|
|
|
3390
|
-
|
|
3971
|
+
// On cart page (no checkout session yet)
|
|
3972
|
+
async function applyCouponToCart(cartId: string, code: string) {
|
|
3391
3973
|
try {
|
|
3392
|
-
const cart = await client.applyCoupon(code);
|
|
3974
|
+
const cart = await client.applyCoupon(cartId, code);
|
|
3393
3975
|
return { ok: true, cart };
|
|
3394
3976
|
} catch (err) {
|
|
3395
3977
|
// Invalid / expired / minimum not met. Surface the specific error.
|
|
@@ -3397,17 +3979,30 @@ async function applyCoupon(code: string) {
|
|
|
3397
3979
|
}
|
|
3398
3980
|
}
|
|
3399
3981
|
|
|
3400
|
-
async function
|
|
3401
|
-
|
|
3402
|
-
|
|
3982
|
+
async function removeCouponFromCart(cartId: string) {
|
|
3983
|
+
return client.removeCoupon(cartId);
|
|
3984
|
+
}
|
|
3985
|
+
|
|
3986
|
+
// On checkout page (checkout session already exists \u2014 always prefer this)
|
|
3987
|
+
async function applyCouponToCheckout(checkoutId: string, code: string) {
|
|
3988
|
+
try {
|
|
3989
|
+
const checkout = await client.applyCheckoutCoupon(checkoutId, code);
|
|
3990
|
+
return { ok: true, checkout }; // checkout.total is already updated
|
|
3991
|
+
} catch (err) {
|
|
3992
|
+
return { ok: false, error: (err as Error).message };
|
|
3993
|
+
}
|
|
3994
|
+
}
|
|
3995
|
+
|
|
3996
|
+
async function removeCouponFromCheckout(checkoutId: string) {
|
|
3997
|
+
return client.removeCheckoutCoupon(checkoutId);
|
|
3403
3998
|
}`,
|
|
3404
3999
|
"reservation-countdown": `// Reservation countdown. Use the SDK's expiry timestamp \u2014 do NOT invent
|
|
3405
4000
|
// your own timer state.
|
|
3406
4001
|
import { client } from './brainerce';
|
|
3407
4002
|
|
|
3408
|
-
function getRemainingMs(cart: {
|
|
3409
|
-
if (!cart.
|
|
3410
|
-
const expiry = new Date(cart.
|
|
4003
|
+
function getRemainingMs(cart: { reservation?: { expiresAt?: string } }): number {
|
|
4004
|
+
if (!cart.reservation?.expiresAt) return 0;
|
|
4005
|
+
const expiry = new Date(cart.reservation.expiresAt).getTime();
|
|
3411
4006
|
return Math.max(0, expiry - Date.now());
|
|
3412
4007
|
}
|
|
3413
4008
|
|
|
@@ -3434,8 +4029,8 @@ function onSearchChange(query: string, onResults: (items: unknown[]) => void) {
|
|
|
3434
4029
|
return;
|
|
3435
4030
|
}
|
|
3436
4031
|
searchTimer = setTimeout(async () => {
|
|
3437
|
-
const
|
|
3438
|
-
onResults(
|
|
4032
|
+
const { products } = await client.getSearchSuggestions(query);
|
|
4033
|
+
onResults(products);
|
|
3439
4034
|
}, 300);
|
|
3440
4035
|
}`,
|
|
3441
4036
|
"i18n-set-locale": `// i18n \u2014 only if get-store-capabilities reports i18n.enabled.
|
|
@@ -3523,7 +4118,412 @@ for (const order of orders) {
|
|
|
3523
4118
|
|
|
3524
4119
|
// All sections above are conditional. Absent data = section not rendered \u2014
|
|
3525
4120
|
// never show empty placeholders. The create-brainerce-store template's
|
|
3526
|
-
// src/components/account/order-history.tsx is the reference implementation
|
|
4121
|
+
// src/components/account/order-history.tsx is the reference implementation.`,
|
|
4122
|
+
"modifier-groups-render": `// Render modifier groups on the product detail page (toppings / sauce /
|
|
4123
|
+
// build-your-own). The data lives on product.modifierGroups \u2014 only present
|
|
4124
|
+
// for restaurant / customizable products.
|
|
4125
|
+
import { useState } from 'react';
|
|
4126
|
+
import type { ModifierGroup, Product } from 'brainerce';
|
|
4127
|
+
|
|
4128
|
+
function ModifierGroups({ product }: { product: Product }) {
|
|
4129
|
+
const groups: ModifierGroup[] = product.modifierGroups ?? [];
|
|
4130
|
+
if (groups.length === 0) return null; // not a customizable product
|
|
4131
|
+
|
|
4132
|
+
// Local state: selected modifier IDs per group, in click-order.
|
|
4133
|
+
const [selections, setSelections] = useState<Record<string, string[]>>(() =>
|
|
4134
|
+
buildInitialSelections(groups)
|
|
4135
|
+
);
|
|
4136
|
+
|
|
4137
|
+
return (
|
|
4138
|
+
<>
|
|
4139
|
+
{groups.map((group) => {
|
|
4140
|
+
// PRD \xA77.2.2: max === 0 means "hidden for this variant" \u2014 skip entirely.
|
|
4141
|
+
if (group.max === 0) return null;
|
|
4142
|
+
|
|
4143
|
+
const isSingle = group.selectionType === 'SINGLE';
|
|
4144
|
+
const inputType = isSingle ? 'radio' : 'checkbox';
|
|
4145
|
+
const sorted = [...group.modifiers].sort((a, b) => a.position - b.position);
|
|
4146
|
+
const picks = selections[group.id] ?? [];
|
|
4147
|
+
const usedFree = Math.min(picks.length, group.freeQuantity);
|
|
4148
|
+
|
|
4149
|
+
const toggle = (modifierId: string, checked: boolean) => {
|
|
4150
|
+
setSelections((prev) => {
|
|
4151
|
+
const cur = prev[group.id] ?? [];
|
|
4152
|
+
if (isSingle) return { ...prev, [group.id]: checked ? [modifierId] : [] };
|
|
4153
|
+
if (checked) {
|
|
4154
|
+
if (group.max != null && cur.length >= group.max) return prev; // at cap
|
|
4155
|
+
return { ...prev, [group.id]: [...cur, modifierId] };
|
|
4156
|
+
}
|
|
4157
|
+
return { ...prev, [group.id]: cur.filter((id) => id !== modifierId) };
|
|
4158
|
+
});
|
|
4159
|
+
};
|
|
4160
|
+
|
|
4161
|
+
return (
|
|
4162
|
+
<fieldset key={group.id}>
|
|
4163
|
+
<legend>
|
|
4164
|
+
{group.name}{group.required && ' *'}
|
|
4165
|
+
</legend>
|
|
4166
|
+
{group.freeQuantity > 0 && (
|
|
4167
|
+
<p>{usedFree} of {group.freeQuantity} free</p>
|
|
4168
|
+
)}
|
|
4169
|
+
{sorted.map((m) => (
|
|
4170
|
+
<label key={m.id}>
|
|
4171
|
+
<input
|
|
4172
|
+
type={inputType}
|
|
4173
|
+
name={\`mg-\${group.id}\`}
|
|
4174
|
+
value={m.id}
|
|
4175
|
+
checked={picks.includes(m.id)}
|
|
4176
|
+
disabled={!m.available}
|
|
4177
|
+
onChange={(e) => toggle(m.id, e.target.checked)}
|
|
4178
|
+
/>
|
|
4179
|
+
{m.name}
|
|
4180
|
+
{parseFloat(m.priceDelta) !== 0 && (
|
|
4181
|
+
<span> {parseFloat(m.priceDelta) > 0 ? '+' : ''}{m.priceDelta}</span>
|
|
4182
|
+
)}
|
|
4183
|
+
{!m.available && <span> (Sold out)</span>}
|
|
4184
|
+
</label>
|
|
4185
|
+
))}
|
|
4186
|
+
</fieldset>
|
|
4187
|
+
);
|
|
4188
|
+
})}
|
|
4189
|
+
</>
|
|
4190
|
+
);
|
|
4191
|
+
}
|
|
4192
|
+
|
|
4193
|
+
// Initial state: prefer per-attach defaultModifierIds; fall back to
|
|
4194
|
+
// modifier.isDefault flags. Filter sold-out modifiers.
|
|
4195
|
+
function buildInitialSelections(groups: ModifierGroup[]): Record<string, string[]> {
|
|
4196
|
+
const out: Record<string, string[]> = {};
|
|
4197
|
+
for (const group of groups) {
|
|
4198
|
+
if (group.max === 0) continue;
|
|
4199
|
+
const fromAttach = group.defaultModifierIds ?? [];
|
|
4200
|
+
const fromIsDefault = group.modifiers
|
|
4201
|
+
.filter((m) => m.isDefault && m.available)
|
|
4202
|
+
.map((m) => m.id);
|
|
4203
|
+
const merged =
|
|
4204
|
+
fromAttach.length > 0
|
|
4205
|
+
? fromAttach.filter((id) => group.modifiers.some((m) => m.id === id && m.available))
|
|
4206
|
+
: fromIsDefault;
|
|
4207
|
+
const capped = group.selectionType === 'SINGLE' ? merged.slice(0, 1) : merged;
|
|
4208
|
+
if (capped.length > 0) out[group.id] = capped;
|
|
4209
|
+
}
|
|
4210
|
+
return out;
|
|
4211
|
+
}
|
|
4212
|
+
|
|
4213
|
+
// PRICE-DELTA RULES:
|
|
4214
|
+
// - "5.00" \u2192 +$5 added to unit price
|
|
4215
|
+
// - "-2.00" \u2192 downsell: subtracts $2; never consumes a free slot
|
|
4216
|
+
// - "0.00" \u2192 free option; render no price label
|
|
4217
|
+
// Server enforces unitPrice >= 0; rejects negative deltas combined with
|
|
4218
|
+
// referencedProductId. Do NOT compute the line total client-side \u2014 the
|
|
4219
|
+
// server runs free-allocation and returns cart.items[i].unitPrice.
|
|
4220
|
+
|
|
4221
|
+
`,
|
|
4222
|
+
"cart-add-with-selections": `// Pass modifier-group selections on add-to-cart. The server validates
|
|
4223
|
+
// against the effective rules and computes the final unitPrice (base +
|
|
4224
|
+
// paid modifiers, after the free-allocation policy runs).
|
|
4225
|
+
import { client } from './brainerce';
|
|
4226
|
+
import type { ModifierSelection } from 'brainerce';
|
|
4227
|
+
|
|
4228
|
+
async function addPizzaToCart(
|
|
4229
|
+
productId: string,
|
|
4230
|
+
variantId: string,
|
|
4231
|
+
selectionsByGroup: Record<string, string[]>
|
|
4232
|
+
) {
|
|
4233
|
+
// Adapter: shape used in component state \u2192 wire format the SDK accepts.
|
|
4234
|
+
const selections: ModifierSelection[] = Object.entries(selectionsByGroup)
|
|
4235
|
+
.filter(([, modifierIds]) => modifierIds.length > 0)
|
|
4236
|
+
.map(([modifierGroupId, modifierIds]) => ({ modifierGroupId, modifierIds }));
|
|
4237
|
+
|
|
4238
|
+
// modifierIds is in CLICK-ORDER \u2014 used by the SELECTION_ORDER free-allocation
|
|
4239
|
+
// policy. Don't sort it; preserve the order the customer clicked.
|
|
4240
|
+
|
|
4241
|
+
const cart = await client.smartAddToCart({
|
|
4242
|
+
productId,
|
|
4243
|
+
variantId,
|
|
4244
|
+
quantity: 1,
|
|
4245
|
+
selections,
|
|
4246
|
+
});
|
|
4247
|
+
|
|
4248
|
+
// Read the snapshot back off the new cart line.
|
|
4249
|
+
const line = cart.items[cart.items.length - 1];
|
|
4250
|
+
// line.modifiers \u2192 CartItemModifierLine[] with { modifierId, name, priceDelta, freeApplied }
|
|
4251
|
+
// line.modifiersTotal \u2192 decimal string of paid (non-free) deltas
|
|
4252
|
+
// line.unitPrice \u2192 final unit price including all paid modifiers
|
|
4253
|
+
console.log('Free applied:', line.modifiers?.filter((m) => m.freeApplied).map((m) => m.name));
|
|
4254
|
+
}
|
|
4255
|
+
|
|
4256
|
+
// EDITING SELECTIONS LATER (PRD \xA77.2.3 \u2014 idempotent replacement):
|
|
4257
|
+
// PATCH the cart item with a fresh selections array. The server deletes ALL
|
|
4258
|
+
// existing CartItemModifier rows and recreates them in the same transaction.
|
|
4259
|
+
// To leave selections untouched (e.g., quantity-only update), omit them.
|
|
4260
|
+
async function changeToppings(cartId: string, itemId: string, newToppingIds: string[]) {
|
|
4261
|
+
await client.updateCartItem(cartId, itemId, {
|
|
4262
|
+
quantity: 1,
|
|
4263
|
+
selections: [{ modifierGroupId: 'mg_toppings', modifierIds: newToppingIds }],
|
|
4264
|
+
});
|
|
4265
|
+
}
|
|
4266
|
+
|
|
4267
|
+
// NESTED COMBOS (depth \u2264 3): when a picked modifier carries
|
|
4268
|
+
// referencedProductId, fetch that product's own modifierGroups, collect the
|
|
4269
|
+
// nested selections, and pass them keyed by the PARENT modifier id.
|
|
4270
|
+
async function addCombo(productId: string, mainBurger: string) {
|
|
4271
|
+
await client.smartAddToCart({
|
|
4272
|
+
productId,
|
|
4273
|
+
quantity: 1,
|
|
4274
|
+
selections: [
|
|
4275
|
+
{ modifierGroupId: 'mg_main', modifierIds: [mainBurger] }, // the burger
|
|
4276
|
+
{ modifierGroupId: 'mg_drink', modifierIds: ['m_cola'] },
|
|
4277
|
+
],
|
|
4278
|
+
nestedByModifierId: {
|
|
4279
|
+
[mainBurger]: [
|
|
4280
|
+
{ modifierGroupId: 'mg_doneness', modifierIds: ['m_medium'] },
|
|
4281
|
+
{ modifierGroupId: 'mg_cheese', modifierIds: ['m_cheddar'] },
|
|
4282
|
+
],
|
|
4283
|
+
},
|
|
4284
|
+
});
|
|
4285
|
+
}`,
|
|
4286
|
+
"modifier-validation-error-handling": `// Surface MODIFIER_VALIDATION_FAILED to the user. The SDK throws
|
|
4287
|
+
// BrainerceError on HTTP 400; the structured envelope is on .details.
|
|
4288
|
+
import { client } from './brainerce';
|
|
4289
|
+
import type { ModifierSelection } from 'brainerce';
|
|
4290
|
+
|
|
4291
|
+
interface ModifierValidationError {
|
|
4292
|
+
code:
|
|
4293
|
+
| 'REQUIRED_GROUP_MISSING'
|
|
4294
|
+
| 'MIN_SELECTIONS_NOT_MET'
|
|
4295
|
+
| 'MAX_SELECTIONS_EXCEEDED'
|
|
4296
|
+
| 'SINGLE_GROUP_MULTIPLE_PICKS'
|
|
4297
|
+
| 'UNKNOWN_MODIFIER'
|
|
4298
|
+
| 'UNKNOWN_GROUP'
|
|
4299
|
+
| 'MODIFIER_DISABLED_FOR_VARIANT'
|
|
4300
|
+
| 'MODIFIER_NOT_AVAILABLE'
|
|
4301
|
+
| 'NESTED_DEPTH_EXCEEDED'
|
|
4302
|
+
| 'NESTED_REQUIRES_PRODUCT_REF'
|
|
4303
|
+
| 'INVALID_PRICE_DELTA'
|
|
4304
|
+
| 'MODIFIER_PRICE_FLOOR_VIOLATED';
|
|
4305
|
+
message: string;
|
|
4306
|
+
modifierGroupId?: string;
|
|
4307
|
+
modifierId?: string;
|
|
4308
|
+
}
|
|
4309
|
+
|
|
4310
|
+
async function tryAddToCart(productId: string, selections: ModifierSelection[]) {
|
|
4311
|
+
try {
|
|
4312
|
+
await client.smartAddToCart({ productId, quantity: 1, selections });
|
|
4313
|
+
return { ok: true as const };
|
|
4314
|
+
} catch (err) {
|
|
4315
|
+
const e = err as {
|
|
4316
|
+
statusCode?: number;
|
|
4317
|
+
details?: { code?: string; errors?: ModifierValidationError[] };
|
|
4318
|
+
};
|
|
4319
|
+
|
|
4320
|
+
if (e.statusCode === 400 && e.details?.code === 'MODIFIER_VALIDATION_FAILED') {
|
|
4321
|
+
// Surface each issue inline. groupId / modifierId let you highlight the
|
|
4322
|
+
// specific control the customer needs to fix.
|
|
4323
|
+
const issues = e.details.errors ?? [];
|
|
4324
|
+
const messages = issues.map((i) => formatIssue(i));
|
|
4325
|
+
return { ok: false as const, issues, messages };
|
|
4326
|
+
}
|
|
4327
|
+
|
|
4328
|
+
// Some other error (network, 500, etc.) \u2014 re-throw to a generic handler.
|
|
4329
|
+
throw err;
|
|
4330
|
+
}
|
|
4331
|
+
}
|
|
4332
|
+
|
|
4333
|
+
function formatIssue(issue: ModifierValidationError): string {
|
|
4334
|
+
switch (issue.code) {
|
|
4335
|
+
case 'REQUIRED_GROUP_MISSING':
|
|
4336
|
+
return 'Please pick at least one option from this group.';
|
|
4337
|
+
case 'MIN_SELECTIONS_NOT_MET':
|
|
4338
|
+
case 'MAX_SELECTIONS_EXCEEDED':
|
|
4339
|
+
case 'SINGLE_GROUP_MULTIPLE_PICKS':
|
|
4340
|
+
return issue.message; // server's message already says "Pick at least N" / "Pick at most N"
|
|
4341
|
+
case 'UNKNOWN_MODIFIER':
|
|
4342
|
+
case 'UNKNOWN_GROUP':
|
|
4343
|
+
case 'MODIFIER_DISABLED_FOR_VARIANT':
|
|
4344
|
+
case 'MODIFIER_NOT_AVAILABLE':
|
|
4345
|
+
// The catalog moved under us \u2014 refetch the product and ask the customer
|
|
4346
|
+
// to re-pick. These codes mean the option simply isn't valid anymore.
|
|
4347
|
+
return 'This option is no longer available \u2014 please refresh.';
|
|
4348
|
+
case 'NESTED_DEPTH_EXCEEDED':
|
|
4349
|
+
case 'NESTED_REQUIRES_PRODUCT_REF':
|
|
4350
|
+
return issue.message; // bug in your renderer \u2014 never go past 3 levels
|
|
4351
|
+
case 'INVALID_PRICE_DELTA':
|
|
4352
|
+
return issue.message; // shouldn't happen for SDK callers \u2014 server-validated on save
|
|
4353
|
+
case 'MODIFIER_PRICE_FLOOR_VIOLATED':
|
|
4354
|
+
// The server reports a generic message \u2014 internals never leak. Show a
|
|
4355
|
+
// friendly error and let the customer remove a downsell.
|
|
4356
|
+
return 'Cannot apply more discounts on this item.';
|
|
4357
|
+
}
|
|
4358
|
+
}
|
|
4359
|
+
|
|
4360
|
+
// CLIENT-SIDE PRE-FLIGHT (UX):
|
|
4361
|
+
// You can mirror these checks before calling addToCart to give faster
|
|
4362
|
+
// feedback, but the SERVER is authoritative. Always treat the 400 envelope
|
|
4363
|
+
// as the source of truth.
|
|
4364
|
+
function preflightSelections(
|
|
4365
|
+
groups: { id: string; name: string; min: number; max?: number | null; required: boolean; selectionType: 'SINGLE' | 'MULTIPLE'; }[],
|
|
4366
|
+
selections: Record<string, string[]>
|
|
4367
|
+
): string | null {
|
|
4368
|
+
for (const g of groups) {
|
|
4369
|
+
if (g.max === 0) continue; // disabled-for-variant
|
|
4370
|
+
const picks = selections[g.id] ?? [];
|
|
4371
|
+
if (g.required && picks.length === 0) return \`\${g.name} is required\`;
|
|
4372
|
+
if (picks.length < g.min) return \`Pick at least \${g.min} from \${g.name}\`;
|
|
4373
|
+
if (g.max != null && picks.length > g.max) return \`Pick at most \${g.max} from \${g.name}\`;
|
|
4374
|
+
if (g.selectionType === 'SINGLE' && picks.length > 1) return \`Only one option allowed in \${g.name}\`;
|
|
4375
|
+
}
|
|
4376
|
+
return null;
|
|
4377
|
+
}`,
|
|
4378
|
+
"checkout-price-drift": `// PRICE_DRIFT \u2014 a product's price changed between add-to-cart and checkout.
|
|
4379
|
+
// The server returns HTTP 400 with code "PRICE_DRIFT" when it detects that
|
|
4380
|
+
// the stored unitPrice no longer matches the live price.
|
|
4381
|
+
//
|
|
4382
|
+
// Strategy: catch the error \u2192 show "prices updated" dialog \u2192
|
|
4383
|
+
// call refreshCartSnapshots() to re-snapshot all live prices \u2192
|
|
4384
|
+
// retry createCheckout once.
|
|
4385
|
+
|
|
4386
|
+
import { client } from './brainerce-client';
|
|
4387
|
+
|
|
4388
|
+
interface CheckoutOptions {
|
|
4389
|
+
cartId: string;
|
|
4390
|
+
}
|
|
4391
|
+
|
|
4392
|
+
async function createCheckoutSafe(opts: CheckoutOptions) {
|
|
4393
|
+
try {
|
|
4394
|
+
// createCheckout only takes cartId (+ optional customerId, selectedItemIds).
|
|
4395
|
+
// Shipping address, shipping method, and payment are set via separate calls.
|
|
4396
|
+
return await client.createCheckout({ cartId: opts.cartId });
|
|
4397
|
+
} catch (err: unknown) {
|
|
4398
|
+
if (!isApiError(err, 'PRICE_DRIFT')) throw err;
|
|
4399
|
+
|
|
4400
|
+
// Prices changed \u2014 refresh snapshots then retry once.
|
|
4401
|
+
// refreshCartSnapshots updates every cart item's unitPrice to the current
|
|
4402
|
+
// live price (base price + any modifier deltas) so the next checkout call
|
|
4403
|
+
// will pass the drift guard.
|
|
4404
|
+
await client.refreshCartSnapshots(opts.cartId);
|
|
4405
|
+
|
|
4406
|
+
// After refreshing, re-fetch the cart so your UI shows the updated prices
|
|
4407
|
+
// before you retry, giving the customer a chance to review.
|
|
4408
|
+
const updatedCart = await client.getCart(opts.cartId);
|
|
4409
|
+
|
|
4410
|
+
// Signal to the UI layer that prices changed so it can show a dialog.
|
|
4411
|
+
throw Object.assign(new Error('PRICES_UPDATED'), {
|
|
4412
|
+
code: 'PRICES_UPDATED',
|
|
4413
|
+
updatedCart,
|
|
4414
|
+
});
|
|
4415
|
+
}
|
|
4416
|
+
}
|
|
4417
|
+
|
|
4418
|
+
function isApiError(err: unknown, code: string): boolean {
|
|
4419
|
+
return (
|
|
4420
|
+
typeof err === 'object' &&
|
|
4421
|
+
err !== null &&
|
|
4422
|
+
'code' in err &&
|
|
4423
|
+
(err as { code: string }).code === code
|
|
4424
|
+
);
|
|
4425
|
+
}
|
|
4426
|
+
|
|
4427
|
+
// --- UI integration example (framework-neutral) ---
|
|
4428
|
+
//
|
|
4429
|
+
// async function handlePlaceOrder() {
|
|
4430
|
+
// try {
|
|
4431
|
+
// const checkout = await createCheckoutSafe({ cartId, ... });
|
|
4432
|
+
// router.push(\`/order-confirmation?checkoutId=\${checkout.id}\`);
|
|
4433
|
+
// } catch (err: unknown) {
|
|
4434
|
+
// if (isApiError(err, 'PRICES_UPDATED')) {
|
|
4435
|
+
// const { updatedCart } = err as { updatedCart: Cart };
|
|
4436
|
+
// showPricesUpdatedDialog(updatedCart); // show diff, let user confirm
|
|
4437
|
+
// return;
|
|
4438
|
+
// }
|
|
4439
|
+
// showGenericError(err);
|
|
4440
|
+
// }
|
|
4441
|
+
// }
|
|
4442
|
+
//
|
|
4443
|
+
// The dialog should:
|
|
4444
|
+
// 1. Show which items changed price (compare old vs new unitPrice)
|
|
4445
|
+
// 2. Offer "Continue with new prices" (calls createCheckoutSafe again)
|
|
4446
|
+
// and "Go back to cart" (returns to cart page)
|
|
4447
|
+
// 3. NOT silently retry \u2014 the customer must acknowledge the price change.`,
|
|
4448
|
+
"cart-item-modifier-display": `// Rendering cart items that have modifier selections.
|
|
4449
|
+
// Each cart item has a \`modifiers\` array \u2014 each entry records the modifier
|
|
4450
|
+
// name, the price delta at time of add-to-cart, and whether it was free
|
|
4451
|
+
// (inside the group's freeQuantity allowance).
|
|
4452
|
+
//
|
|
4453
|
+
// Typical display:
|
|
4454
|
+
// Margherita \u20AA45.00
|
|
4455
|
+
// Extra cheese +\u20AA5.00
|
|
4456
|
+
// Mushrooms free
|
|
4457
|
+
// No onions \u2014
|
|
4458
|
+
// \u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500
|
|
4459
|
+
// Base \u20AA45.00 + Modifiers \u20AA5.00 = \u20AA50.00
|
|
4460
|
+
|
|
4461
|
+
import { formatPrice } from 'brainerce';
|
|
4462
|
+
|
|
4463
|
+
interface CartItemModifier {
|
|
4464
|
+
modifierId: string;
|
|
4465
|
+
name: string;
|
|
4466
|
+
priceDeltaAtTime: number; // in store currency units, e.g. 5.00
|
|
4467
|
+
freeApplied: boolean; // true when inside the group's freeQuantity
|
|
4468
|
+
}
|
|
4469
|
+
|
|
4470
|
+
interface CartItem {
|
|
4471
|
+
id: string;
|
|
4472
|
+
name: string;
|
|
4473
|
+
unitPrice: number; // base + all chargeable modifier deltas, as stored
|
|
4474
|
+
quantity: number;
|
|
4475
|
+
modifiers?: CartItemModifier[];
|
|
4476
|
+
currency: string; // e.g. 'ILS', 'USD'
|
|
4477
|
+
}
|
|
4478
|
+
|
|
4479
|
+
function renderCartItem(item: CartItem): string {
|
|
4480
|
+
const currency = item.currency;
|
|
4481
|
+
const lines: string[] = [];
|
|
4482
|
+
|
|
4483
|
+
lines.push(\`\${item.name} \${formatPrice(item.unitPrice, { currency })}\`);
|
|
4484
|
+
|
|
4485
|
+
const chargeableModifiers = (item.modifiers ?? []).filter(
|
|
4486
|
+
(m) => !m.freeApplied && m.priceDeltaAtTime !== 0
|
|
4487
|
+
);
|
|
4488
|
+
const freeModifiers = (item.modifiers ?? []).filter((m) => m.freeApplied);
|
|
4489
|
+
const zeroModifiers = (item.modifiers ?? []).filter(
|
|
4490
|
+
(m) => !m.freeApplied && m.priceDeltaAtTime === 0
|
|
4491
|
+
);
|
|
4492
|
+
|
|
4493
|
+
for (const m of chargeableModifiers) {
|
|
4494
|
+
const sign = m.priceDeltaAtTime > 0 ? '+' : '';
|
|
4495
|
+
lines.push(\` \${m.name} \${sign}\${formatPrice(m.priceDeltaAtTime, { currency })}\`);
|
|
4496
|
+
}
|
|
4497
|
+
for (const m of freeModifiers) {
|
|
4498
|
+
lines.push(\` \${m.name} free\`);
|
|
4499
|
+
}
|
|
4500
|
+
for (const m of zeroModifiers) {
|
|
4501
|
+
lines.push(\` \${m.name} \u2014\`);
|
|
4502
|
+
}
|
|
4503
|
+
|
|
4504
|
+
// Price breakdown: only show when there are chargeable modifiers
|
|
4505
|
+
const modifiersTotal = chargeableModifiers.reduce(
|
|
4506
|
+
(sum, m) => sum + m.priceDeltaAtTime,
|
|
4507
|
+
0
|
|
4508
|
+
);
|
|
4509
|
+
if (modifiersTotal !== 0) {
|
|
4510
|
+
// unitPrice already includes modifiers \u2014 derive base for display only
|
|
4511
|
+
const basePrice = item.unitPrice - modifiersTotal;
|
|
4512
|
+
const base = formatPrice(basePrice, { currency }) as string;
|
|
4513
|
+
const mods = formatPrice(modifiersTotal, { currency }) as string;
|
|
4514
|
+
const total = formatPrice(item.unitPrice, { currency }) as string;
|
|
4515
|
+
lines.push(\`Base \${base} + Modifiers \${mods} = \${total}\`);
|
|
4516
|
+
}
|
|
4517
|
+
|
|
4518
|
+
return lines.join('\\n');
|
|
4519
|
+
}
|
|
4520
|
+
|
|
4521
|
+
// IMPORTANT: unitPrice already includes all chargeable modifier deltas.
|
|
4522
|
+
// Do NOT add modifier prices on top of unitPrice when computing line totals \u2014
|
|
4523
|
+
// multiply unitPrice \xD7 quantity directly.
|
|
4524
|
+
function lineTotal(item: CartItem): number {
|
|
4525
|
+
return item.unitPrice * item.quantity;
|
|
4526
|
+
}`
|
|
3527
4527
|
};
|
|
3528
4528
|
async function handleGetCodeExample(args) {
|
|
3529
4529
|
const snippet = SNIPPETS[args.operation];
|
|
@@ -3639,13 +4639,27 @@ function getCandidateApiUrls() {
|
|
|
3639
4639
|
|
|
3640
4640
|
// src/tools/get-store-info.ts
|
|
3641
4641
|
var GET_STORE_INFO_NAME = "get-store-info";
|
|
3642
|
-
var GET_STORE_INFO_DESCRIPTION = "Fetch live store information from the Brainerce API using a
|
|
4642
|
+
var GET_STORE_INFO_DESCRIPTION = "Fetch live store information from the Brainerce API using a sales channel ID. Returns the channel display name (what the user sees in their dashboard), parent store name, currency, and language. Use this to personalize the store being built \u2014 prefer the channel name for user-facing text since a single Brainerce store can have multiple sales channels.";
|
|
3643
4643
|
var GET_STORE_INFO_SCHEMA = {
|
|
3644
|
-
|
|
4644
|
+
salesChannelId: z4.string().optional().describe("Sales channel ID (starts with vc_)"),
|
|
4645
|
+
/** @deprecated alias of salesChannelId */
|
|
4646
|
+
connectionId: z4.string().optional().describe("Deprecated alias of salesChannelId \u2014 kept for backwards compat")
|
|
3645
4647
|
};
|
|
3646
4648
|
async function handleGetStoreInfo(args) {
|
|
4649
|
+
const id = args.salesChannelId ?? args.connectionId;
|
|
4650
|
+
if (!id) {
|
|
4651
|
+
return {
|
|
4652
|
+
content: [{ type: "text", text: "Error: salesChannelId is required" }],
|
|
4653
|
+
isError: true
|
|
4654
|
+
};
|
|
4655
|
+
}
|
|
4656
|
+
if (!args.salesChannelId && args.connectionId) {
|
|
4657
|
+
console.warn(
|
|
4658
|
+
"get-store-info: `connectionId` is deprecated \u2014 use `salesChannelId` instead"
|
|
4659
|
+
);
|
|
4660
|
+
}
|
|
3647
4661
|
try {
|
|
3648
|
-
const resolved = await resolveStoreInfo(
|
|
4662
|
+
const resolved = await resolveStoreInfo(id, getCandidateApiUrls());
|
|
3649
4663
|
return {
|
|
3650
4664
|
content: [
|
|
3651
4665
|
{
|
|
@@ -3658,7 +4672,8 @@ async function handleGetStoreInfo(args) {
|
|
|
3658
4672
|
storeName: resolved.info.storeName,
|
|
3659
4673
|
currency: resolved.info.currency,
|
|
3660
4674
|
language: resolved.info.language,
|
|
3661
|
-
|
|
4675
|
+
salesChannelId: id,
|
|
4676
|
+
connectionId: id,
|
|
3662
4677
|
apiBaseUrl: resolved.apiBaseUrl
|
|
3663
4678
|
},
|
|
3664
4679
|
null,
|
|
@@ -3743,9 +4758,11 @@ async function resolveStoreCapabilities(connectionId, candidateUrls) {
|
|
|
3743
4758
|
|
|
3744
4759
|
// src/tools/get-store-capabilities.ts
|
|
3745
4760
|
var GET_STORE_CAPABILITIES_NAME = "get-store-capabilities";
|
|
3746
|
-
var GET_STORE_CAPABILITIES_DESCRIPTION = "Get live store capabilities and configured features for a
|
|
4761
|
+
var GET_STORE_CAPABILITIES_DESCRIPTION = "Get live store capabilities and configured features for a sales channel. Returns what payment providers, OAuth, shipping, discounts, and other features are set up. Use this to discover what your store supports and what pages/components to build.";
|
|
3747
4762
|
var GET_STORE_CAPABILITIES_SCHEMA = {
|
|
3748
|
-
|
|
4763
|
+
salesChannelId: z5.string().optional().describe("Sales channel ID (starts with vc_)"),
|
|
4764
|
+
/** @deprecated alias of salesChannelId */
|
|
4765
|
+
connectionId: z5.string().optional().describe("Deprecated alias of salesChannelId \u2014 kept for backwards compat")
|
|
3749
4766
|
};
|
|
3750
4767
|
function formatCapabilities(caps) {
|
|
3751
4768
|
const lines = [];
|
|
@@ -3858,15 +4875,27 @@ function formatCapabilities(caps) {
|
|
|
3858
4875
|
}
|
|
3859
4876
|
if (suggestions.length === 0) {
|
|
3860
4877
|
suggestions.push(
|
|
3861
|
-
"Start by building the required features. Use get-required-features with this
|
|
4878
|
+
"Start by building the required features. Use get-required-features with this salesChannelId for the checklist."
|
|
3862
4879
|
);
|
|
3863
4880
|
}
|
|
3864
4881
|
suggestions.forEach((s) => lines.push(`- ${s}`));
|
|
3865
4882
|
return lines.join("\n");
|
|
3866
4883
|
}
|
|
3867
4884
|
async function handleGetStoreCapabilities(args) {
|
|
4885
|
+
const id = args.salesChannelId ?? args.connectionId;
|
|
4886
|
+
if (!id) {
|
|
4887
|
+
return {
|
|
4888
|
+
content: [{ type: "text", text: "Error: salesChannelId is required" }],
|
|
4889
|
+
isError: true
|
|
4890
|
+
};
|
|
4891
|
+
}
|
|
4892
|
+
if (!args.salesChannelId && args.connectionId) {
|
|
4893
|
+
console.warn(
|
|
4894
|
+
"get-store-capabilities: `connectionId` is deprecated \u2014 use `salesChannelId` instead"
|
|
4895
|
+
);
|
|
4896
|
+
}
|
|
3868
4897
|
try {
|
|
3869
|
-
const resolved = await resolveStoreCapabilities(
|
|
4898
|
+
const resolved = await resolveStoreCapabilities(id, getCandidateApiUrls());
|
|
3870
4899
|
return {
|
|
3871
4900
|
content: [{ type: "text", text: formatCapabilities(resolved.capabilities) }]
|
|
3872
4901
|
};
|
|
@@ -3971,7 +5000,7 @@ var RULES = {
|
|
|
3971
5000
|
tokens: {
|
|
3972
5001
|
title: "Auth tokens & BFF pattern",
|
|
3973
5002
|
body: `- NEVER store customer auth tokens in \`localStorage\` directly from client code. Use a Backend-For-Frontend proxy: the server receives the token, sets an HttpOnly cookie, and the client reads session state from an endpoint like \`/api/auth/me\`.
|
|
3974
|
-
- NEVER put the admin API key (\`brainerce_*\`) in client code. It is a server-only secret. Client code uses \`connectionId\` or storefront endpoints.
|
|
5003
|
+
- NEVER put the admin API key (\`brainerce_*\`) in client code. It is a server-only secret. Client code uses \`salesChannelId\` (or the deprecated \`connectionId\` alias) or storefront endpoints.
|
|
3975
5004
|
- OAuth callbacks arrive with the token in URL params. Extract it SERVER-side and exchange it for a session cookie before redirecting to the app. Do not let the token land in browser history.
|
|
3976
5005
|
- On logout, clear the BFF session server-side. A client-only logout that forgets to tell the server leaves an active session on the server until it expires.`
|
|
3977
5006
|
},
|
|
@@ -4039,21 +5068,21 @@ var FLOWS = {
|
|
|
4039
5068
|
1. **Collect address + email.** Build a form that captures customer email, billing address, shipping address (with \`line1\`, \`line2\`, \`city\`, \`region\`, \`postalCode\`, \`country\`). \`email\` is REQUIRED on \`SetShippingAddressDto\`.
|
|
4040
5069
|
2. **Submit the address to get shipping rates.**
|
|
4041
5070
|
\`\`\`ts
|
|
4042
|
-
const {
|
|
5071
|
+
const { checkout, rates } = await client.setShippingAddress(checkoutId, {
|
|
4043
5072
|
email,
|
|
4044
5073
|
firstName,
|
|
4045
5074
|
lastName,
|
|
4046
5075
|
line1, line2, city, region, postalCode, country,
|
|
4047
5076
|
});
|
|
4048
5077
|
\`\`\`
|
|
4049
|
-
|
|
5078
|
+
\`rates\` = available shipping rates for that address + the store's zones. \`checkout\` = updated checkout object.
|
|
4050
5079
|
3. **Let the customer pick a rate**, then persist the selection:
|
|
4051
5080
|
\`\`\`ts
|
|
4052
|
-
await client.
|
|
5081
|
+
await client.selectShippingMethod(checkoutId, rateId);
|
|
4053
5082
|
\`\`\`
|
|
4054
|
-
4. **Fetch payment providers
|
|
5083
|
+
4. **Fetch payment providers:**
|
|
4055
5084
|
\`\`\`ts
|
|
4056
|
-
const providers = await client.getPaymentProviders(
|
|
5085
|
+
const providers = await client.getPaymentProviders();
|
|
4057
5086
|
\`\`\`
|
|
4058
5087
|
The response tells you which providers are configured (Stripe, Grow, PayPal, Sandbox) and how to render each. Each provider has a \`renderType\` telling you whether to show a Stripe Elements form, a redirect button, a PayPal button, or a sandbox "complete test order" button.
|
|
4059
5088
|
5. **Confirm payment using the provider's recommended flow.** For Stripe: Stripe Elements \u2192 \`stripe.confirmCardPayment\` using the clientSecret returned by the SDK. For sandbox payments: call \`completeGuestCheckout(checkoutId)\` directly. For PayPal/Grow: follow the redirect and handle the return on your confirmation page.
|
|
@@ -4069,28 +5098,28 @@ Never bypass these steps. Never call \`submitGuestOrder\` / \`createOrder\` \u20
|
|
|
4069
5098
|
"auth-register": {
|
|
4070
5099
|
title: "Registration",
|
|
4071
5100
|
body: `1. **Collect** email, password, first name, last name. Enforce strong passwords client-side: 8+ chars, upper, lower, number, special.
|
|
4072
|
-
2. **Call
|
|
5101
|
+
2. **Call registerCustomer:**
|
|
4073
5102
|
\`\`\`ts
|
|
4074
|
-
const result = await client.
|
|
5103
|
+
const result = await client.registerCustomer({ email, password, firstName, lastName });
|
|
4075
5104
|
\`\`\`
|
|
4076
5105
|
3. **Branch on \`result.requiresVerification\`:**
|
|
4077
|
-
- If \`true\`: route the user to your verify-email UI. Do NOT treat them as logged in yet.
|
|
4078
|
-
- If \`false\`:
|
|
5106
|
+
- If \`true\`: store the token temporarily (e.g. sessionStorage), route the user to your verify-email UI. Do NOT treat them as logged in yet.
|
|
5107
|
+
- If \`false\`: call \`client.setCustomerToken(result.token)\` and route to the account area.
|
|
4079
5108
|
4. **On the verify-email step:** collect a 6-digit code and call \`client.verifyEmail(code)\`. Offer a "resend code" button wired to \`client.resendVerificationEmail()\`.
|
|
4080
|
-
5. **After verifyEmail resolves:** the user is now logged in
|
|
5109
|
+
5. **After verifyEmail resolves:** call \`client.setCustomerToken(result.token)\` \u2014 the user is now logged in \u2014 then route to the account area.
|
|
4081
5110
|
|
|
4082
5111
|
Build the verify-email step EVEN IF the store currently has verification disabled. It auto-hides; store owners enable it later.`
|
|
4083
5112
|
},
|
|
4084
5113
|
"auth-login": {
|
|
4085
5114
|
title: "Login",
|
|
4086
5115
|
body: `1. **Collect** email + password.
|
|
4087
|
-
2. **Call
|
|
5116
|
+
2. **Call loginCustomer:**
|
|
4088
5117
|
\`\`\`ts
|
|
4089
|
-
const result = await client.
|
|
5118
|
+
const result = await client.loginCustomer(email, password);
|
|
4090
5119
|
\`\`\`
|
|
4091
5120
|
3. **Branch on \`result.requiresVerification\`:**
|
|
4092
5121
|
- If \`true\`: route to verify-email. The user must complete verification before accessing account features.
|
|
4093
|
-
- If \`false\`:
|
|
5122
|
+
- If \`false\`: call \`client.setCustomerToken(result.token)\` and route to the previous page (or account area).
|
|
4094
5123
|
4. **Offer OAuth buttons** from \`client.getAvailableOAuthProviders()\`. Render a placeholder region even when no providers are returned \u2014 the region auto-hides today and shows buttons the moment a provider is enabled in the dashboard.
|
|
4095
5124
|
5. **On error**, render the specific message (invalid credentials, rate limited, account disabled) \u2014 never swallow.`
|
|
4096
5125
|
},
|
|
@@ -4115,15 +5144,24 @@ Build both steps EVEN IF the store has no email provider configured today \u2014
|
|
|
4115
5144
|
},
|
|
4116
5145
|
oauth: {
|
|
4117
5146
|
title: "OAuth sign-in",
|
|
4118
|
-
body: `1. **
|
|
5147
|
+
body: `1. **Get available provider names:**
|
|
4119
5148
|
\`\`\`ts
|
|
4120
|
-
const providers = await client.getAvailableOAuthProviders();
|
|
5149
|
+
const { providers } = await client.getAvailableOAuthProviders();
|
|
5150
|
+
// providers = ['GOOGLE', 'FACEBOOK', 'GITHUB'] (strings, not objects with authorizationUrl)
|
|
4121
5151
|
\`\`\`
|
|
4122
|
-
|
|
4123
|
-
|
|
4124
|
-
|
|
4125
|
-
|
|
4126
|
-
|
|
5152
|
+
2. **For each provider, fetch the authorization URL:**
|
|
5153
|
+
\`\`\`ts
|
|
5154
|
+
const { authorizationUrl } = await client.getOAuthAuthorizeUrl(provider, {
|
|
5155
|
+
redirectUrl: \`\${window.location.origin}/auth/callback\`,
|
|
5156
|
+
});
|
|
5157
|
+
window.location.href = authorizationUrl; // full-page redirect, NOT a popup
|
|
5158
|
+
\`\`\`
|
|
5159
|
+
3. **On the callback page** the URL contains \`token\` + \`oauth_success\` (or \`oauth_error\`) query params. Extract and apply the token:
|
|
5160
|
+
\`\`\`ts
|
|
5161
|
+
const token = new URLSearchParams(location.search).get('token');
|
|
5162
|
+
if (token) client.setCustomerToken(token); // then redirect to account
|
|
5163
|
+
\`\`\`
|
|
5164
|
+
4. **On \`oauth_error\`:** redirect to login with an error message.
|
|
4127
5165
|
|
|
4128
5166
|
Build the OAuth button region AND the callback handler even when no providers are configured. They auto-hide.`
|
|
4129
5167
|
},
|
|
@@ -4145,7 +5183,7 @@ Build the OAuth button region AND the callback handler even when no providers ar
|
|
|
4145
5183
|
|
|
4146
5184
|
- **Cart ID persistence:** the SDK stores the cart ID across reloads. You do not need to write cart-to-localStorage code yourself.
|
|
4147
5185
|
- **Reads:** \`client.getCart()\` returns the current cart. Call it on mount in your cart UI and on any page that shows a cart count (header).
|
|
4148
|
-
- **Writes:** use \`client.addToCart\`, \`client.updateCartItem\`, \`client.removeCartItem\`, \`client.applyCoupon\`, \`client.removeCoupon\`. After each mutation the SDK returns the updated cart.
|
|
5186
|
+
- **Writes:** use \`client.addToCart\`, \`client.updateCartItem\`, \`client.removeCartItem\`, \`client.applyCoupon\`, \`client.removeCoupon\`. After each mutation the SDK returns the updated cart. On the **checkout page** use \`client.applyCheckoutCoupon(checkoutId, code)\` / \`client.removeCheckoutCoupon(checkoutId)\` \u2014 these update checkout totals atomically. Never use \`applyCoupon\` after a checkout session exists.
|
|
4149
5187
|
- **Totals:** call \`getCartTotals(cart)\` \u2014 do NOT read \`cart.total\`. The helper understands taxes, shipping, and discounts.
|
|
4150
5188
|
- **\`smartGetCart()\`** returns \`CartWithIncludes\` (extends \`Cart\`). All carts are server-side. Pass \`{ include: ['recommendations', 'upgrades', 'bundles'] }\` to fetch extras in one request.
|
|
4151
5189
|
- **NEVER mutate cart state outside SDK helpers.** Any hand-rolled cart update risks desync with the reservation timer and the checkout flow.`
|
|
@@ -4264,18 +5302,20 @@ ${flow.body}`
|
|
|
4264
5302
|
// src/tools/get-required-features.ts
|
|
4265
5303
|
import { z as z9 } from "zod";
|
|
4266
5304
|
var GET_REQUIRED_FEATURES_NAME = "get-required-features";
|
|
4267
|
-
var GET_REQUIRED_FEATURES_DESCRIPTION = "Get the functional coverage checklist for a Brainerce store. Returns user-capability-level features (what users must be able to do) rather than pages or file paths. Every feature marked mandatory must exist in the finished build, even when the underlying capability is currently disabled \u2014 those features auto-hide and store owners enable them later. Pass a
|
|
5305
|
+
var GET_REQUIRED_FEATURES_DESCRIPTION = "Get the functional coverage checklist for a Brainerce store. Returns user-capability-level features (what users must be able to do) rather than pages or file paths. Every feature marked mandatory must exist in the finished build, even when the underlying capability is currently disabled \u2014 those features auto-hide and store owners enable them later. Pass a salesChannelId to tune the checklist to the live store; without it, returns the generic complete-store checklist.";
|
|
4268
5306
|
var GET_REQUIRED_FEATURES_SCHEMA = {
|
|
4269
|
-
|
|
4270
|
-
"
|
|
4271
|
-
)
|
|
5307
|
+
salesChannelId: z9.string().optional().describe(
|
|
5308
|
+
"Sales channel ID (starts with vc_). Optional \u2014 without it, returns the generic checklist."
|
|
5309
|
+
),
|
|
5310
|
+
/** @deprecated alias of salesChannelId */
|
|
5311
|
+
connectionId: z9.string().optional().describe("Deprecated alias of salesChannelId \u2014 kept for backwards compat")
|
|
4272
5312
|
};
|
|
4273
5313
|
var FEATURES = [
|
|
4274
5314
|
{
|
|
4275
5315
|
id: "browse-products",
|
|
4276
5316
|
title: "Browse, filter, and search products",
|
|
4277
|
-
description: "Users can list products with pagination, apply category / price / attribute filters, sort by name / price / newest, and run a search with autocomplete. Must handle empty states and loading states.",
|
|
4278
|
-
sdk: "client.getProducts({ page, limit, filters, sort }), client.
|
|
5317
|
+
description: "Users can list products with pagination, apply category / price / attribute / custom-field filters, sort by name / price / newest, and run a search with autocomplete. Custom-field filters surface metafield definitions whose filterable=true (SELECT, MULTI_SELECT, BOOLEAN). Must handle empty states and loading states.",
|
|
5318
|
+
sdk: "client.getProducts({ page, limit, filters, sort, metafields }), client.getPublicMetafieldDefinitions(), client.getSearchSuggestions(query)",
|
|
4279
5319
|
mandatory: "mandatory"
|
|
4280
5320
|
},
|
|
4281
5321
|
{
|
|
@@ -4305,7 +5345,7 @@ var FEATURES = [
|
|
|
4305
5345
|
id: "cart-coupons",
|
|
4306
5346
|
title: "Apply and remove coupon codes",
|
|
4307
5347
|
description: "Users can enter a coupon code, see it applied to the cart, see the discount amount, and remove it. Build the UI even if no coupons are configured today \u2014 it auto-hides.",
|
|
4308
|
-
sdk: "client.applyCoupon(code), client.removeCoupon()",
|
|
5348
|
+
sdk: "client.applyCoupon(cartId, code), client.removeCoupon(cartId) \u2014 on cart page. client.applyCheckoutCoupon(checkoutId, code), client.removeCheckoutCoupon(checkoutId) \u2014 on checkout page (use when checkoutId exists)",
|
|
4309
5349
|
mandatory: "mandatory",
|
|
4310
5350
|
capabilityFlag: "hasCoupons",
|
|
4311
5351
|
whenDisabledNote: "Store has no coupons configured today. Build the UI anyway \u2014 it auto-hides until the store owner creates a coupon."
|
|
@@ -4322,7 +5362,7 @@ var FEATURES = [
|
|
|
4322
5362
|
id: "checkout",
|
|
4323
5363
|
title: "Complete a full checkout end-to-end",
|
|
4324
5364
|
description: "Users can enter their address, pick a shipping rate, pick a payment provider, pay, and land on a confirmation page showing the real order. Displays checkout.lineItems (not cart.items) on the summary.",
|
|
4325
|
-
sdk: "client.setShippingAddress, client.
|
|
5365
|
+
sdk: "client.setShippingAddress (returns { checkout, rates }), client.selectShippingMethod, client.getPaymentProviders(), provider-specific confirm, client.handlePaymentSuccess, client.waitForOrder",
|
|
4326
5366
|
flowRef: "checkout",
|
|
4327
5367
|
mandatory: "mandatory"
|
|
4328
5368
|
},
|
|
@@ -4338,7 +5378,7 @@ var FEATURES = [
|
|
|
4338
5378
|
id: "register",
|
|
4339
5379
|
title: "Register a new account with email verification",
|
|
4340
5380
|
description: 'Users can create an account (email, password, first + last name). Handles the requiresVerification branch by routing to an email-verification step. Verification step collects a 6-digit code and has a "resend code" action.',
|
|
4341
|
-
sdk: "client.
|
|
5381
|
+
sdk: "client.registerCustomer({email, password, firstName, lastName}), client.verifyEmail(code), client.resendVerificationEmail()",
|
|
4342
5382
|
flowRef: "auth-register",
|
|
4343
5383
|
mandatory: "mandatory",
|
|
4344
5384
|
capabilityFlag: "oauth",
|
|
@@ -4348,7 +5388,7 @@ var FEATURES = [
|
|
|
4348
5388
|
id: "login",
|
|
4349
5389
|
title: "Log in with email / password and handle verification branch",
|
|
4350
5390
|
description: "Users can log in. The login form handles the requiresVerification branch by routing to the verify-email step. Specific errors render (bad credentials, rate limited, disabled account).",
|
|
4351
|
-
sdk: "client.
|
|
5391
|
+
sdk: "client.loginCustomer(email, password)",
|
|
4352
5392
|
flowRef: "auth-login",
|
|
4353
5393
|
mandatory: "mandatory"
|
|
4354
5394
|
},
|
|
@@ -4381,14 +5421,14 @@ var FEATURES = [
|
|
|
4381
5421
|
id: "header",
|
|
4382
5422
|
title: "Global header with cart count and search",
|
|
4383
5423
|
description: "A header visible across the experience with the store logo, navigation, a cart icon with live item count, a search input with autocomplete (debounced ~300ms, 2-char minimum), and a login / account action. Below the header, discount banners render when active.",
|
|
4384
|
-
sdk: "client.getCart() for the count, client.
|
|
5424
|
+
sdk: "client.getCart() for the count, client.getSearchSuggestions(query) for autocomplete",
|
|
4385
5425
|
mandatory: "mandatory"
|
|
4386
5426
|
},
|
|
4387
5427
|
{
|
|
4388
5428
|
id: "discount-banners",
|
|
4389
5429
|
title: "Show active discount banners and badges",
|
|
4390
5430
|
description: "Active discount rules render as banners (below the header) and as badges on product cards / detail pages. Build the UI even if the store has no active discounts today \u2014 it auto-hides.",
|
|
4391
|
-
sdk: "client.getDiscountBanners(), getProductDiscountBadge(
|
|
5431
|
+
sdk: "client.getDiscountBanners(), client.getProductDiscountBadge(productId)",
|
|
4392
5432
|
mandatory: "mandatory",
|
|
4393
5433
|
capabilityFlag: "hasDiscountRules",
|
|
4394
5434
|
whenDisabledNote: "Store has no discount rules active. Build the banner and badge components anyway \u2014 they auto-hide."
|
|
@@ -4490,10 +5530,16 @@ function renderCapabilitiesSummary(caps) {
|
|
|
4490
5530
|
return lines.join("\n");
|
|
4491
5531
|
}
|
|
4492
5532
|
async function handleGetRequiredFeatures(args) {
|
|
5533
|
+
const id = args.salesChannelId ?? args.connectionId;
|
|
5534
|
+
if (!args.salesChannelId && args.connectionId) {
|
|
5535
|
+
console.warn(
|
|
5536
|
+
"get-required-features: `connectionId` is deprecated \u2014 use `salesChannelId` instead"
|
|
5537
|
+
);
|
|
5538
|
+
}
|
|
4493
5539
|
let caps = null;
|
|
4494
|
-
if (
|
|
5540
|
+
if (id) {
|
|
4495
5541
|
try {
|
|
4496
|
-
const resolved = await resolveStoreCapabilities(
|
|
5542
|
+
const resolved = await resolveStoreCapabilities(id, getCandidateApiUrls());
|
|
4497
5543
|
caps = resolved.capabilities;
|
|
4498
5544
|
} catch {
|
|
4499
5545
|
caps = null;
|
|
@@ -4505,11 +5551,11 @@ async function handleGetRequiredFeatures(args) {
|
|
|
4505
5551
|
);
|
|
4506
5552
|
if (caps) {
|
|
4507
5553
|
sections.push(renderCapabilitiesSummary(caps));
|
|
4508
|
-
} else if (
|
|
5554
|
+
} else if (id) {
|
|
4509
5555
|
sections.push(
|
|
4510
5556
|
`## Live store capabilities
|
|
4511
5557
|
|
|
4512
|
-
Could not fetch live capabilities for \`${
|
|
5558
|
+
Could not fetch live capabilities for \`${id}\`. Proceeding with the generic checklist. Call \`get-store-capabilities\` separately if you want a targeted checklist.`
|
|
4513
5559
|
);
|
|
4514
5560
|
}
|
|
4515
5561
|
sections.push("## Features");
|