create-nextblock 0.15.8 → 0.15.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (71) hide show
  1. package/package.json +1 -1
  2. package/templates/nextblock-template/app/ToasterProvider.tsx +26 -17
  3. package/templates/nextblock-template/app/actions/contactSellerActions.test.ts +280 -0
  4. package/templates/nextblock-template/app/actions/contactSellerActions.ts +222 -0
  5. package/templates/nextblock-template/app/actions/email-retry.test.ts +62 -0
  6. package/templates/nextblock-template/app/actions/email.ts +241 -110
  7. package/templates/nextblock-template/app/actions/formActions.ts +245 -116
  8. package/templates/nextblock-template/app/actions/interactions.ts +489 -396
  9. package/templates/nextblock-template/app/actions/threadActions.ts +166 -0
  10. package/templates/nextblock-template/app/api/checkout/route.ts +162 -146
  11. package/templates/nextblock-template/app/api/cron/reset-sandbox/sandboxResetSql.ts +664 -1
  12. package/templates/nextblock-template/app/checkout/page.tsx +57 -52
  13. package/templates/nextblock-template/app/cms/CmsClientLayout.tsx +552 -529
  14. package/templates/nextblock-template/app/cms/blocks/editors/FormBlockEditor.tsx +304 -181
  15. package/templates/nextblock-template/app/cms/components/ContactReminderBanner.tsx +75 -0
  16. package/templates/nextblock-template/app/cms/components/PaymentsReminderBanner.tsx +58 -0
  17. package/templates/nextblock-template/app/cms/components/VisibilityControl.tsx +542 -528
  18. package/templates/nextblock-template/app/cms/inquiries/actions.ts +66 -0
  19. package/templates/nextblock-template/app/cms/inquiries/page.tsx +12 -0
  20. package/templates/nextblock-template/app/cms/interactions/page.tsx +12 -51
  21. package/templates/nextblock-template/app/cms/layout.tsx +101 -73
  22. package/templates/nextblock-template/app/cms/messages/MessagesClient.tsx +661 -0
  23. package/templates/nextblock-template/app/cms/messages/actions.ts +404 -0
  24. package/templates/nextblock-template/app/cms/messages/loadInbox.ts +333 -0
  25. package/templates/nextblock-template/app/cms/messages/page.tsx +87 -0
  26. package/templates/nextblock-template/app/cms/messages/require-admin.ts +37 -0
  27. package/templates/nextblock-template/app/cms/products/[id]/edit/page.tsx +370 -362
  28. package/templates/nextblock-template/app/cms/revisions/service.ts +20 -0
  29. package/templates/nextblock-template/app/cms/settings/email/components/EmailForm.tsx +227 -185
  30. package/templates/nextblock-template/app/layout.tsx +671 -671
  31. package/templates/nextblock-template/app/product/[slug]/page.tsx +502 -482
  32. package/templates/nextblock-template/app/providers.tsx +96 -96
  33. package/templates/nextblock-template/app/thread/ThreadView.tsx +164 -0
  34. package/templates/nextblock-template/app/thread/[token]/route.ts +57 -0
  35. package/templates/nextblock-template/app/thread/layout.tsx +15 -0
  36. package/templates/nextblock-template/app/thread/page.tsx +98 -0
  37. package/templates/nextblock-template/components/BlockRenderer.tsx +312 -296
  38. package/templates/nextblock-template/components/ContactSellerSection.tsx +188 -0
  39. package/templates/nextblock-template/components/PostCommentsSection.tsx +378 -369
  40. package/templates/nextblock-template/components/ProductReviewsSection.tsx +426 -419
  41. package/templates/nextblock-template/components/StaffReplies.tsx +102 -0
  42. package/templates/nextblock-template/components/blocks/renderers/CartBlockRenderer.tsx +18 -17
  43. package/templates/nextblock-template/components/blocks/renderers/CheckoutBlockRenderer.tsx +20 -19
  44. package/templates/nextblock-template/components/blocks/renderers/FeaturedProductBlockRenderer.tsx +25 -22
  45. package/templates/nextblock-template/components/blocks/renderers/FormBlockRenderer.tsx +385 -381
  46. package/templates/nextblock-template/components/blocks/renderers/ProductDetailsBlockRenderer.tsx +157 -92
  47. package/templates/nextblock-template/components/blocks/renderers/ProductGridBlockRenderer.tsx +34 -31
  48. package/templates/nextblock-template/components/blocks/renderers/SectionBlockRenderer.tsx +612 -600
  49. package/templates/nextblock-template/components/commerce/PaymentReadinessBoundary.tsx +32 -0
  50. package/templates/nextblock-template/docs/14-MESSAGES-INBOX.md +309 -0
  51. package/templates/nextblock-template/docs/README.md +42 -41
  52. package/templates/nextblock-template/docs/assets/lighthouse-scores.png +0 -0
  53. package/templates/nextblock-template/lib/blocks/blockColors.test.ts +22 -2
  54. package/templates/nextblock-template/lib/blocks/blockColors.ts +44 -1
  55. package/templates/nextblock-template/lib/blocks/blockRegistry.ts +761 -753
  56. package/templates/nextblock-template/lib/cms/contact-reminder.ts +64 -0
  57. package/templates/nextblock-template/lib/cms/payments-reminder.ts +98 -0
  58. package/templates/nextblock-template/lib/cms/unread-messages.ts +42 -0
  59. package/templates/nextblock-template/lib/commerce/seller-contact.ts +162 -0
  60. package/templates/nextblock-template/lib/config/email-settings.ts +323 -254
  61. package/templates/nextblock-template/lib/config/email-tls.test.ts +57 -0
  62. package/templates/nextblock-template/lib/email/placeholder-address.test.ts +59 -0
  63. package/templates/nextblock-template/lib/email/placeholder-address.ts +39 -0
  64. package/templates/nextblock-template/lib/messages/thread-reference.test.ts +70 -0
  65. package/templates/nextblock-template/lib/messages/thread-token.test.ts +93 -0
  66. package/templates/nextblock-template/lib/messages/thread-token.ts +157 -0
  67. package/templates/nextblock-template/lib/messages/threads.ts +579 -0
  68. package/templates/nextblock-template/lib/setup/migrations-bundle.ts +20 -0
  69. package/templates/nextblock-template/lib/site-url.test.ts +89 -0
  70. package/templates/nextblock-template/lib/site-url.ts +102 -48
  71. package/templates/nextblock-template/package.json +1 -1
@@ -1,482 +1,502 @@
1
- import { getProductBySlug, getProducts } from '@nextblock-cms/ecommerce/server';
2
- import {
3
- ProductProvider,
4
- mapRawVariantRelations,
5
- getVariantEffectivePriceRange,
6
- normalizePriceMap,
7
- normalizeSalePriceMap,
8
- resolveTranslatedText,
9
- } from '@nextblock-cms/ecommerce';
10
- import { getSsgSupabaseClient, verifyPackageOnline } from '@nextblock-cms/db/server';
11
- import { LIVE_STATUS, buildPublishedAtOrFilter, isPubliclyVisible } from '@nextblock-cms/utils';
12
- import { notFound } from 'next/navigation';
13
- import { Metadata } from 'next';
14
- import { draftMode, cookies, headers } from 'next/headers';
15
- import { getPageDataBySlug } from "../../[slug]/page.utils";
16
- import BlockRenderer from "../../../components/BlockRenderer";
17
- import { CurrentContentSetter } from "../../../components/CurrentContentSetter";
18
- import {
19
- applyProductDraftToProductRecord,
20
- getProductDraft,
21
- } from "../../../lib/visual-editing/product-drafts";
22
- import { getRequestOrigin } from "../../../lib/visual-editing/edit-info";
23
- import {
24
- resolveMetaTitle,
25
- resolveProductMetaDescription,
26
- stringifyJsonLd,
27
- buildSocialMetadata,
28
- buildCanonicalUrl,
29
- toOpenGraphLocale,
30
- } from "../../lib/seo";
31
- import { getSiteSettings } from "../../lib/site-settings";
32
- // Ensure BlockType is imported or compatible with BlockRenderer props
33
- import type { Database } from "@nextblock-cms/db";
34
- type BlockType = Database['public']['Tables']['blocks']['Row'];
35
-
36
- export const dynamicParams = true;
37
- export const revalidate = 360;
38
- export const dynamic = 'force-dynamic'; // keeps per-request locale; paired with short revalidate
39
- export const fetchCache = 'force-no-store';
40
-
41
- interface ProductPageProps {
42
- params: Promise<{
43
- slug: string;
44
- }>;
45
- }
46
-
47
- function formatMinorUnitAmount(amount: unknown) {
48
- const numericAmount = typeof amount === 'number' ? amount : Number(amount);
49
- if (!Number.isFinite(numericAmount)) {
50
- return undefined;
51
- }
52
-
53
- return (numericAmount / 100).toFixed(2);
54
- }
55
-
56
- function resolveOfferAvailability(productRecord: any) {
57
- if (productRecord.product_type === 'digital') {
58
- return 'https://schema.org/InStock';
59
- }
60
-
61
- return typeof productRecord.stock === 'number' && productRecord.stock <= 0
62
- ? 'https://schema.org/OutOfStock'
63
- : 'https://schema.org/InStock';
64
- }
65
-
66
- function resolveCategoryName(category: any, languageCode?: string | null) {
67
- if (!category || typeof category.name !== 'string') {
68
- return null;
69
- }
70
-
71
- return resolveTranslatedText(
72
- category.name,
73
- category.name_translations,
74
- languageCode
75
- );
76
- }
77
-
78
- export async function generateStaticParams() {
79
- // Unconfigured instance (pre-/setup): no DB to read product slugs from. Accept every
80
- // Supabase key alias the Vercel integration may inject (incl. the new publishable key).
81
- const hasSupabaseEnv =
82
- (process.env.NEXT_PUBLIC_SUPABASE_URL || process.env.SUPABASE_URL) &&
83
- (process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY ||
84
- process.env.SUPABASE_ANON_KEY ||
85
- process.env.NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY ||
86
- process.env.SUPABASE_PUBLISHABLE_KEY);
87
- if (!hasSupabaseEnv) {
88
- return [];
89
- }
90
-
91
- const supabase = getSsgSupabaseClient();
92
- const { data: products } = await getProducts(supabase);
93
- const productRows = ((products || []) as any[]).filter(
94
- (product) => product.status === 'active'
95
- );
96
- if (productRows.length === 0) return [];
97
- return productRows.map((product: any) => ({
98
- slug: product.slug,
99
- }));
100
- }
101
-
102
- export async function generateMetadata({ params }: ProductPageProps): Promise<Metadata> {
103
- const { slug } = await params;
104
- const supabase = getSsgSupabaseClient();
105
- let preferredLocale: string | undefined;
106
- try {
107
- const store = await cookies();
108
- preferredLocale = store.get("NEXT_USER_LOCALE")?.value || store.get("NEXT_LOCALE")?.value;
109
- } catch {
110
- preferredLocale = undefined;
111
- }
112
- if (!preferredLocale) {
113
- try {
114
- const hdrs = await headers();
115
- // Proxy-detected locale first: it honors the CMS language-detection settings.
116
- preferredLocale = hdrs.get("x-user-locale") || undefined;
117
- if (!preferredLocale) {
118
- const al = hdrs.get("accept-language");
119
- if (al) preferredLocale = al.split(",")[0]?.split("-")[0];
120
- }
121
- } catch {
122
- // ignore
123
- }
124
- }
125
- const { data: product } = await getProductBySlug(supabase, slug, preferredLocale);
126
- const productRecord = product as any;
127
-
128
- if (
129
- !productRecord ||
130
- !isPubliclyVisible({
131
- status: productRecord.status,
132
- publishedAt: productRecord.published_at,
133
- liveStatus: LIVE_STATUS.product,
134
- })
135
- ) {
136
- return { title: 'Product Not Found' };
137
- }
138
-
139
- // Resolve image URL for OG Image
140
- let imageUrl = undefined;
141
- const mediaItem = productRecord.product_media?.[0]?.media;
142
- if (mediaItem?.file_path) {
143
- if (mediaItem.file_path.startsWith('http')) {
144
- imageUrl = mediaItem.file_path;
145
- } else if (process.env.NEXT_PUBLIC_R2_BASE_URL) {
146
- imageUrl = `${process.env.NEXT_PUBLIC_R2_BASE_URL}/${mediaItem.file_path}`;
147
- } else {
148
- imageUrl = `${process.env.NEXT_PUBLIC_SUPABASE_URL}/storage/v1/object/public/media/${mediaItem.file_path}`;
149
- }
150
- }
151
-
152
- const siteUrl = process.env.NEXT_PUBLIC_URL || "";
153
- const [languagesResult, productTranslationsResult] = await Promise.all([
154
- supabase.from('languages').select('id, code'),
155
- supabase
156
- .from('products')
157
- .select('language_id, slug')
158
- .eq('translation_group_id', productRecord.translation_group_id)
159
- .eq('status', 'active')
160
- // Never advertise a scheduled translation via hreflang.
161
- .or(buildPublishedAtOrFilter())
162
- ]);
163
-
164
- const { data: languages } = languagesResult;
165
- const { data: productTranslations } = productTranslationsResult;
166
-
167
- const alternates: { [key: string]: string } = {};
168
- if (languages && productTranslations) {
169
- productTranslations.forEach(pt => {
170
- const langInfo = languages.find(l => l.id === pt.language_id);
171
- if (langInfo) {
172
- alternates[langInfo.code] = `${siteUrl}/product/${pt.slug}`;
173
- }
174
- });
175
- }
176
-
177
- const title = resolveMetaTitle(productRecord.meta_title, productRecord.title);
178
- const description = resolveProductMetaDescription(
179
- productRecord.meta_description,
180
- productRecord.short_description
181
- );
182
- const { siteTitle } = await getSiteSettings();
183
- // Self-referencing `<siteUrl>/product/<slug>` unless the product sets a manual custom_canonical override.
184
- const canonicalUrl = buildCanonicalUrl(productRecord.custom_canonical, siteUrl, `/product/${slug}`);
185
-
186
- return {
187
- title,
188
- description,
189
- ...buildSocialMetadata({
190
- title,
191
- description,
192
- url: canonicalUrl,
193
- siteTitle,
194
- imageUrl,
195
- type: 'website',
196
- locale: toOpenGraphLocale(productRecord.language_code),
197
- }),
198
- alternates: {
199
- canonical: canonicalUrl,
200
- languages: Object.keys(alternates).length > 0 ? alternates : undefined,
201
- },
202
- };
203
- }
204
-
205
- export default async function ProductPage({ params }: ProductPageProps) {
206
- const { slug } = await params;
207
- const supabase = getSsgSupabaseClient();
208
-
209
- // 0. Verify License
210
- const isOnline = await verifyPackageOnline('ecommerce');
211
- if (!isOnline) {
212
- notFound();
213
- }
214
-
215
- let preferredLocale: string | undefined;
216
- try {
217
- const store = await cookies();
218
- preferredLocale = store.get("NEXT_USER_LOCALE")?.value || store.get("NEXT_LOCALE")?.value;
219
- } catch {
220
- preferredLocale = undefined;
221
- }
222
- if (!preferredLocale) {
223
- try {
224
- const hdrs = await headers();
225
- // Proxy-detected locale first: it honors the CMS language-detection settings.
226
- preferredLocale = hdrs.get("x-user-locale") || undefined;
227
- if (!preferredLocale) {
228
- const al = hdrs.get("accept-language");
229
- if (al) preferredLocale = al.split(",")[0]?.split("-")[0];
230
- }
231
- } catch {
232
- // ignore
233
- }
234
- }
235
-
236
- // 1. Fetch Product Data
237
- const { data: product } = await getProductBySlug(supabase, slug, preferredLocale);
238
- let productRecord = product as any;
239
-
240
- const draft = await draftMode();
241
-
242
- // Draft mode is how the CMS previews a product before it is public, so it must
243
- // reach draft and scheduled rows everyone else only sees active products whose
244
- // go-live moment has passed.
245
- if (
246
- !productRecord ||
247
- (!draft.isEnabled &&
248
- !isPubliclyVisible({
249
- status: productRecord.status,
250
- publishedAt: productRecord.published_at,
251
- liveStatus: LIVE_STATUS.product,
252
- }))
253
- ) {
254
- notFound();
255
- }
256
-
257
- const visualEditingEnabled =
258
- draft.isEnabled || process.env.NEXTBLOCK_VISUAL_EDITING_ENABLED === 'true';
259
-
260
- if (visualEditingEnabled) {
261
- const productDraft = await getProductDraft(productRecord.id);
262
- productRecord = applyProductDraftToProductRecord(productRecord, productDraft);
263
- }
264
-
265
- // 2. Fetch Template Page
266
- const templatePage = await getPageDataBySlug('product-template');
267
-
268
- // 3. Fallback or Use Template
269
- let blocks: BlockType[] = [];
270
- let languageId = 1; // Default to 1 if not found
271
-
272
- if (templatePage) {
273
- blocks = templatePage.blocks;
274
- languageId = templatePage.language_id;
275
- } else {
276
- // Fallback Layout if no template exists
277
- // We cast to any to avoid strict DB type matching for fallback mocks, specifically for UUID/Dates
278
- blocks = [
279
- {
280
- id: 'fallback-product-details',
281
- block_type: 'product_details',
282
- content: {},
283
- page_id: 'temp',
284
- order: 0,
285
- language_id: 1,
286
- created_at: new Date().toISOString(),
287
- updated_at: new Date().toISOString()
288
- },
289
- {
290
- id: 'fallback-product-grid',
291
- block_type: 'product_grid',
292
- content: { type: 'latest', limit: 4, title: "You might also like" },
293
- page_id: 'temp',
294
- order: 1,
295
- language_id: 1,
296
- created_at: new Date().toISOString(),
297
- updated_at: new Date().toISOString()
298
- }
299
- ] as any as BlockType[];
300
- }
301
-
302
- const requestOrigin = await getRequestOrigin();
303
- const productTemplateVisualEditing = templatePage
304
- ? {
305
- enabled: visualEditingEnabled,
306
- documentType: "page" as const,
307
- documentId: templatePage.id,
308
- slug: templatePage.slug,
309
- languageId: templatePage.language_id,
310
- draftId: templatePage.draft_id ?? null,
311
- pageOrigin: requestOrigin,
312
- }
313
- : undefined;
314
-
315
- // 4. Transform Product Data for Context
316
- // Value Mapping
317
- // Image URL resolution
318
- let imageUrl: string | undefined = undefined;
319
- const images: { url: string; alt?: string }[] = [];
320
-
321
- if (productRecord.product_media && productRecord.product_media.length > 0) {
322
- // Sort by sort_order
323
- const sortedMedia = [...productRecord.product_media].sort((a, b) => (a.sort_order ?? 0) - (b.sort_order ?? 0));
324
-
325
- sortedMedia.forEach(pm => {
326
- if (pm.media?.file_path) {
327
- let url = '';
328
- if (pm.media.file_path.startsWith('http')) {
329
- url = pm.media.file_path;
330
- } else if (process.env.NEXT_PUBLIC_R2_BASE_URL) {
331
- url = `${process.env.NEXT_PUBLIC_R2_BASE_URL}/${pm.media.file_path}`;
332
- } else {
333
- url = `${process.env.NEXT_PUBLIC_SUPABASE_URL}/storage/v1/object/public/media/${pm.media.file_path}`;
334
- }
335
-
336
- images.push({ url, alt: productRecord.title });
337
-
338
- // Set primary image if it's the first one
339
- if (!imageUrl) imageUrl = url;
340
- }
341
- });
342
- }
343
-
344
- const languageCode = Array.isArray(productRecord.languages)
345
- ? productRecord.languages[0]?.code
346
- : productRecord.languages?.code;
347
- const { attributes, variants } = mapRawVariantRelations(
348
- productRecord.product_variants || [],
349
- languageCode
350
- );
351
- const variantPriceRange = getVariantEffectivePriceRange(variants);
352
- const productCategories = (productRecord.product_categories || [])
353
- .map((pc: any) => pc.category)
354
- .filter(Boolean);
355
- const productCategoryNames = productCategories
356
- .map((category: any) => resolveCategoryName(category, languageCode))
357
- .filter((name: string | null): name is string => Boolean(name));
358
-
359
- const contextProduct = {
360
- id: productRecord.id,
361
- title: productRecord.title,
362
- slug: productRecord.slug,
363
- sku: productRecord.sku,
364
- average_rating: productRecord.average_rating,
365
- total_reviews: productRecord.total_reviews,
366
- upc: productRecord.upc || undefined,
367
- price: productRecord.price,
368
- prices: normalizePriceMap(productRecord.prices),
369
- sale_price: productRecord.sale_price || null,
370
- sale_prices: normalizeSalePriceMap(productRecord.sale_prices),
371
- sale_start_at: productRecord.sale_start_at ?? null,
372
- sale_end_at: productRecord.sale_end_at ?? null,
373
- scheduled_price:
374
- typeof productRecord.scheduled_price === 'number' ? productRecord.scheduled_price : undefined,
375
- scheduled_prices: normalizePriceMap(productRecord.scheduled_prices),
376
- scheduled_price_at: productRecord.scheduled_price_at ?? null,
377
- is_taxable: productRecord.is_taxable ?? true,
378
- product_type: productRecord.product_type ?? undefined,
379
- payment_provider: productRecord.payment_provider ?? undefined,
380
- price_range_min: variantPriceRange?.min ?? null,
381
- price_range_max: variantPriceRange?.max ?? null,
382
- image_url: imageUrl,
383
- images: images,
384
- short_description: productRecord.short_description || undefined,
385
- description_json: productRecord.description_json,
386
- stock:
387
- productRecord.stock !== undefined && productRecord.stock !== null
388
- ? productRecord.stock
389
- : undefined,
390
- freemius_product_id: productRecord.freemius_product_id || undefined,
391
- freemius_plan_id: productRecord.freemius_plan_id || undefined,
392
- trial_period_days: productRecord.trial_period_days ?? 0,
393
- trial_requires_payment_method: productRecord.trial_requires_payment_method ?? false,
394
- freemius_plans: productRecord.freemius_plans,
395
- language_id: productRecord.language_id,
396
- translation_group_id: productRecord.translation_group_id || "",
397
- has_variants: variants.length > 0,
398
- attributes,
399
- variants,
400
- categories: productCategories,
401
- product_variants: (productRecord.product_variants || []).map((variant: any) => ({
402
- id: variant.id,
403
- price: variant.price,
404
- prices: normalizePriceMap(variant.prices),
405
- sale_price: variant.sale_price,
406
- sale_prices: normalizeSalePriceMap(variant.sale_prices),
407
- sale_start_at: variant.sale_start_at ?? null,
408
- sale_end_at: variant.sale_end_at ?? null,
409
- scheduled_price: variant.scheduled_price ?? null,
410
- scheduled_prices: normalizePriceMap(variant.scheduled_prices),
411
- scheduled_price_at: variant.scheduled_price_at ?? null,
412
- })),
413
- };
414
- const siteUrl = process.env.NEXT_PUBLIC_URL || "";
415
- const nonce = (await headers()).get('x-nonce') || undefined;
416
- const title = resolveMetaTitle(productRecord.meta_title, productRecord.title);
417
- const description = resolveProductMetaDescription(
418
- productRecord.meta_description,
419
- productRecord.short_description
420
- );
421
- const { data: defaultCurrency } = await supabase
422
- .from('currencies')
423
- .select('code')
424
- .eq('is_default', true)
425
- .maybeSingle();
426
- const price = formatMinorUnitAmount(productRecord.sale_price ?? productRecord.price);
427
- const productJsonLd = {
428
- '@context': 'https://schema.org',
429
- '@type': 'Product',
430
- name: title,
431
- description,
432
- image: images.map((image) => image.url),
433
- category:
434
- productCategoryNames.length > 1
435
- ? productCategoryNames
436
- : productCategoryNames[0] ?? undefined,
437
- sku: productRecord.sku || undefined,
438
- gtin: productRecord.upc || undefined,
439
- url: `${siteUrl}/product/${productRecord.slug}`,
440
- offers: price
441
- ? {
442
- '@type': 'Offer',
443
- url: `${siteUrl}/product/${productRecord.slug}`,
444
- price,
445
- priceCurrency: defaultCurrency?.code || 'USD',
446
- availability: resolveOfferAvailability(productRecord),
447
- itemCondition: 'https://schema.org/NewCondition',
448
- }
449
- : undefined,
450
- };
451
-
452
- return (
453
- <div className="min-h-screen bg-background pb-12">
454
- <script
455
- type="application/ld+json"
456
- nonce={nonce}
457
- suppressHydrationWarning
458
- dangerouslySetInnerHTML={{ __html: stringifyJsonLd(productJsonLd) }}
459
- />
460
- <ProductProvider product={contextProduct}>
461
- {/*
462
- BlockRenderer expects languageId property.
463
- If templatePage is null, we defaulted languageId to 1.
464
- */}
465
- <CurrentContentSetter
466
- id={productRecord.id}
467
- type="product"
468
- slug={productRecord.slug}
469
- translation_group_id={productRecord.translation_group_id}
470
- />
471
- <BlockRenderer
472
- blocks={blocks}
473
- languageId={languageId}
474
- excludeProductId={productRecord.id}
475
- excludeTranslationGroupId={productRecord.translation_group_id}
476
- visualEditing={productTemplateVisualEditing}
477
- productVisualEditingEnabled={visualEditingEnabled}
478
- />
479
- </ProductProvider>
480
- </div>
481
- );
482
- }
1
+ import { getProductBySlug, getProducts, getProviderReadiness } from '@nextblock-cms/ecommerce/server';
2
+ import {
3
+ ProductProvider,
4
+ mapRawVariantRelations,
5
+ getVariantEffectivePriceRange,
6
+ normalizePriceMap,
7
+ normalizeSalePriceMap,
8
+ resolveTranslatedText,
9
+ } from '@nextblock-cms/ecommerce';
10
+ import { getSsgSupabaseClient, verifyPackageOnline } from '@nextblock-cms/db/server';
11
+ import { LIVE_STATUS, buildPublishedAtOrFilter, isPubliclyVisible } from '@nextblock-cms/utils';
12
+ import { notFound } from 'next/navigation';
13
+ import { Metadata } from 'next';
14
+ import { draftMode, cookies, headers } from 'next/headers';
15
+ import { getPageDataBySlug } from "../../[slug]/page.utils";
16
+ import BlockRenderer from "../../../components/BlockRenderer";
17
+ import { CurrentContentSetter } from "../../../components/CurrentContentSetter";
18
+ import {
19
+ applyProductDraftToProductRecord,
20
+ getProductDraft,
21
+ } from "../../../lib/visual-editing/product-drafts";
22
+ import { getRequestOrigin } from "../../../lib/visual-editing/edit-info";
23
+ import {
24
+ resolveMetaTitle,
25
+ resolveProductMetaDescription,
26
+ stringifyJsonLd,
27
+ buildSocialMetadata,
28
+ buildCanonicalUrl,
29
+ toOpenGraphLocale,
30
+ } from "../../lib/seo";
31
+ import { getSiteSettings } from "../../lib/site-settings";
32
+ // Ensure BlockType is imported or compatible with BlockRenderer props
33
+ import type { Database } from "@nextblock-cms/db";
34
+ type BlockType = Database['public']['Tables']['blocks']['Row'];
35
+
36
+ export const dynamicParams = true;
37
+ export const revalidate = 360;
38
+ export const dynamic = 'force-dynamic'; // keeps per-request locale; paired with short revalidate
39
+ export const fetchCache = 'force-no-store';
40
+
41
+ interface ProductPageProps {
42
+ params: Promise<{
43
+ slug: string;
44
+ }>;
45
+ }
46
+
47
+ function formatMinorUnitAmount(amount: unknown) {
48
+ const numericAmount = typeof amount === 'number' ? amount : Number(amount);
49
+ if (!Number.isFinite(numericAmount)) {
50
+ return undefined;
51
+ }
52
+
53
+ return (numericAmount / 100).toFixed(2);
54
+ }
55
+
56
+ function resolveOfferAvailability(productRecord: any, canPurchase = true) {
57
+ // Don't advertise a buyable offer for something checkout will refuse: a rich result
58
+ // promising "InStock" that dead-ends at an enquiry form is worse than no offer badge.
59
+ if (!canPurchase) {
60
+ return 'https://schema.org/InStoreOnly';
61
+ }
62
+
63
+ if (productRecord.product_type === 'digital') {
64
+ return 'https://schema.org/InStock';
65
+ }
66
+
67
+ return typeof productRecord.stock === 'number' && productRecord.stock <= 0
68
+ ? 'https://schema.org/OutOfStock'
69
+ : 'https://schema.org/InStock';
70
+ }
71
+
72
+ function resolveCategoryName(category: any, languageCode?: string | null) {
73
+ if (!category || typeof category.name !== 'string') {
74
+ return null;
75
+ }
76
+
77
+ return resolveTranslatedText(
78
+ category.name,
79
+ category.name_translations,
80
+ languageCode
81
+ );
82
+ }
83
+
84
+ export async function generateStaticParams() {
85
+ // Unconfigured instance (pre-/setup): no DB to read product slugs from. Accept every
86
+ // Supabase key alias the Vercel integration may inject (incl. the new publishable key).
87
+ const hasSupabaseEnv =
88
+ (process.env.NEXT_PUBLIC_SUPABASE_URL || process.env.SUPABASE_URL) &&
89
+ (process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY ||
90
+ process.env.SUPABASE_ANON_KEY ||
91
+ process.env.NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY ||
92
+ process.env.SUPABASE_PUBLISHABLE_KEY);
93
+ if (!hasSupabaseEnv) {
94
+ return [];
95
+ }
96
+
97
+ const supabase = getSsgSupabaseClient();
98
+ const { data: products } = await getProducts(supabase);
99
+ const productRows = ((products || []) as any[]).filter(
100
+ (product) => product.status === 'active'
101
+ );
102
+ if (productRows.length === 0) return [];
103
+ return productRows.map((product: any) => ({
104
+ slug: product.slug,
105
+ }));
106
+ }
107
+
108
+ export async function generateMetadata({ params }: ProductPageProps): Promise<Metadata> {
109
+ const { slug } = await params;
110
+ const supabase = getSsgSupabaseClient();
111
+ let preferredLocale: string | undefined;
112
+ try {
113
+ const store = await cookies();
114
+ preferredLocale = store.get("NEXT_USER_LOCALE")?.value || store.get("NEXT_LOCALE")?.value;
115
+ } catch {
116
+ preferredLocale = undefined;
117
+ }
118
+ if (!preferredLocale) {
119
+ try {
120
+ const hdrs = await headers();
121
+ // Proxy-detected locale first: it honors the CMS language-detection settings.
122
+ preferredLocale = hdrs.get("x-user-locale") || undefined;
123
+ if (!preferredLocale) {
124
+ const al = hdrs.get("accept-language");
125
+ if (al) preferredLocale = al.split(",")[0]?.split("-")[0];
126
+ }
127
+ } catch {
128
+ // ignore
129
+ }
130
+ }
131
+ const { data: product } = await getProductBySlug(supabase, slug, preferredLocale);
132
+ const productRecord = product as any;
133
+
134
+ if (
135
+ !productRecord ||
136
+ !isPubliclyVisible({
137
+ status: productRecord.status,
138
+ publishedAt: productRecord.published_at,
139
+ liveStatus: LIVE_STATUS.product,
140
+ })
141
+ ) {
142
+ return { title: 'Product Not Found' };
143
+ }
144
+
145
+ // Resolve image URL for OG Image
146
+ let imageUrl = undefined;
147
+ const mediaItem = productRecord.product_media?.[0]?.media;
148
+ if (mediaItem?.file_path) {
149
+ if (mediaItem.file_path.startsWith('http')) {
150
+ imageUrl = mediaItem.file_path;
151
+ } else if (process.env.NEXT_PUBLIC_R2_BASE_URL) {
152
+ imageUrl = `${process.env.NEXT_PUBLIC_R2_BASE_URL}/${mediaItem.file_path}`;
153
+ } else {
154
+ imageUrl = `${process.env.NEXT_PUBLIC_SUPABASE_URL}/storage/v1/object/public/media/${mediaItem.file_path}`;
155
+ }
156
+ }
157
+
158
+ const siteUrl = process.env.NEXT_PUBLIC_URL || "";
159
+ const [languagesResult, productTranslationsResult] = await Promise.all([
160
+ supabase.from('languages').select('id, code'),
161
+ supabase
162
+ .from('products')
163
+ .select('language_id, slug')
164
+ .eq('translation_group_id', productRecord.translation_group_id)
165
+ .eq('status', 'active')
166
+ // Never advertise a scheduled translation via hreflang.
167
+ .or(buildPublishedAtOrFilter())
168
+ ]);
169
+
170
+ const { data: languages } = languagesResult;
171
+ const { data: productTranslations } = productTranslationsResult;
172
+
173
+ const alternates: { [key: string]: string } = {};
174
+ if (languages && productTranslations) {
175
+ productTranslations.forEach(pt => {
176
+ const langInfo = languages.find(l => l.id === pt.language_id);
177
+ if (langInfo) {
178
+ alternates[langInfo.code] = `${siteUrl}/product/${pt.slug}`;
179
+ }
180
+ });
181
+ }
182
+
183
+ const title = resolveMetaTitle(productRecord.meta_title, productRecord.title);
184
+ const description = resolveProductMetaDescription(
185
+ productRecord.meta_description,
186
+ productRecord.short_description
187
+ );
188
+ const { siteTitle } = await getSiteSettings();
189
+ // Self-referencing `<siteUrl>/product/<slug>` unless the product sets a manual custom_canonical override.
190
+ const canonicalUrl = buildCanonicalUrl(productRecord.custom_canonical, siteUrl, `/product/${slug}`);
191
+
192
+ return {
193
+ title,
194
+ description,
195
+ ...buildSocialMetadata({
196
+ title,
197
+ description,
198
+ url: canonicalUrl,
199
+ siteTitle,
200
+ imageUrl,
201
+ type: 'website',
202
+ locale: toOpenGraphLocale(productRecord.language_code),
203
+ }),
204
+ alternates: {
205
+ canonical: canonicalUrl,
206
+ languages: Object.keys(alternates).length > 0 ? alternates : undefined,
207
+ },
208
+ };
209
+ }
210
+
211
+ export default async function ProductPage({ params }: ProductPageProps) {
212
+ const { slug } = await params;
213
+ const supabase = getSsgSupabaseClient();
214
+
215
+ // 0. Verify License
216
+ const isOnline = await verifyPackageOnline('ecommerce');
217
+ if (!isOnline) {
218
+ notFound();
219
+ }
220
+
221
+ let preferredLocale: string | undefined;
222
+ try {
223
+ const store = await cookies();
224
+ preferredLocale = store.get("NEXT_USER_LOCALE")?.value || store.get("NEXT_LOCALE")?.value;
225
+ } catch {
226
+ preferredLocale = undefined;
227
+ }
228
+ if (!preferredLocale) {
229
+ try {
230
+ const hdrs = await headers();
231
+ // Proxy-detected locale first: it honors the CMS language-detection settings.
232
+ preferredLocale = hdrs.get("x-user-locale") || undefined;
233
+ if (!preferredLocale) {
234
+ const al = hdrs.get("accept-language");
235
+ if (al) preferredLocale = al.split(",")[0]?.split("-")[0];
236
+ }
237
+ } catch {
238
+ // ignore
239
+ }
240
+ }
241
+
242
+ // 1. Fetch Product Data
243
+ const { data: product } = await getProductBySlug(supabase, slug, preferredLocale);
244
+ let productRecord = product as any;
245
+
246
+ const draft = await draftMode();
247
+
248
+ // Draft mode is how the CMS previews a product before it is public, so it must
249
+ // reach draft and scheduled rows — everyone else only sees active products whose
250
+ // go-live moment has passed.
251
+ if (
252
+ !productRecord ||
253
+ (!draft.isEnabled &&
254
+ !isPubliclyVisible({
255
+ status: productRecord.status,
256
+ publishedAt: productRecord.published_at,
257
+ liveStatus: LIVE_STATUS.product,
258
+ }))
259
+ ) {
260
+ notFound();
261
+ }
262
+
263
+ const visualEditingEnabled =
264
+ draft.isEnabled || process.env.NEXTBLOCK_VISUAL_EDITING_ENABLED === 'true';
265
+
266
+ if (visualEditingEnabled) {
267
+ const productDraft = await getProductDraft(productRecord.id);
268
+ productRecord = applyProductDraftToProductRecord(productRecord, productDraft);
269
+ }
270
+
271
+ // 2. Fetch Template Page
272
+ const templatePage = await getPageDataBySlug('product-template');
273
+
274
+ // 3. Fallback or Use Template
275
+ let blocks: BlockType[] = [];
276
+ let languageId = 1; // Default to 1 if not found
277
+
278
+ if (templatePage) {
279
+ blocks = templatePage.blocks;
280
+ languageId = templatePage.language_id;
281
+ } else {
282
+ // Fallback Layout if no template exists
283
+ // We cast to any to avoid strict DB type matching for fallback mocks, specifically for UUID/Dates
284
+ blocks = [
285
+ {
286
+ id: 'fallback-product-details',
287
+ block_type: 'product_details',
288
+ content: {},
289
+ page_id: 'temp',
290
+ order: 0,
291
+ language_id: 1,
292
+ created_at: new Date().toISOString(),
293
+ updated_at: new Date().toISOString()
294
+ },
295
+ {
296
+ id: 'fallback-product-grid',
297
+ block_type: 'product_grid',
298
+ content: { type: 'latest', limit: 4, title: "You might also like" },
299
+ page_id: 'temp',
300
+ order: 1,
301
+ language_id: 1,
302
+ created_at: new Date().toISOString(),
303
+ updated_at: new Date().toISOString()
304
+ }
305
+ ] as any as BlockType[];
306
+ }
307
+
308
+ const requestOrigin = await getRequestOrigin();
309
+ const productTemplateVisualEditing = templatePage
310
+ ? {
311
+ enabled: visualEditingEnabled,
312
+ documentType: "page" as const,
313
+ documentId: templatePage.id,
314
+ slug: templatePage.slug,
315
+ languageId: templatePage.language_id,
316
+ draftId: templatePage.draft_id ?? null,
317
+ pageOrigin: requestOrigin,
318
+ }
319
+ : undefined;
320
+
321
+ // 4. Transform Product Data for Context
322
+ // Value Mapping
323
+ // Image URL resolution
324
+ let imageUrl: string | undefined = undefined;
325
+ const images: { url: string; alt?: string }[] = [];
326
+
327
+ if (productRecord.product_media && productRecord.product_media.length > 0) {
328
+ // Sort by sort_order
329
+ const sortedMedia = [...productRecord.product_media].sort((a, b) => (a.sort_order ?? 0) - (b.sort_order ?? 0));
330
+
331
+ sortedMedia.forEach(pm => {
332
+ if (pm.media?.file_path) {
333
+ let url = '';
334
+ if (pm.media.file_path.startsWith('http')) {
335
+ url = pm.media.file_path;
336
+ } else if (process.env.NEXT_PUBLIC_R2_BASE_URL) {
337
+ url = `${process.env.NEXT_PUBLIC_R2_BASE_URL}/${pm.media.file_path}`;
338
+ } else {
339
+ url = `${process.env.NEXT_PUBLIC_SUPABASE_URL}/storage/v1/object/public/media/${pm.media.file_path}`;
340
+ }
341
+
342
+ images.push({ url, alt: productRecord.title });
343
+
344
+ // Set primary image if it's the first one
345
+ if (!imageUrl) imageUrl = url;
346
+ }
347
+ });
348
+ }
349
+
350
+ const languageCode = Array.isArray(productRecord.languages)
351
+ ? productRecord.languages[0]?.code
352
+ : productRecord.languages?.code;
353
+ const { attributes, variants } = mapRawVariantRelations(
354
+ productRecord.product_variants || [],
355
+ languageCode
356
+ );
357
+ const variantPriceRange = getVariantEffectivePriceRange(variants);
358
+ const productCategories = (productRecord.product_categories || [])
359
+ .map((pc: any) => pc.category)
360
+ .filter(Boolean);
361
+ const productCategoryNames = productCategories
362
+ .map((category: any) => resolveCategoryName(category, languageCode))
363
+ .filter((name: string | null): name is string => Boolean(name));
364
+
365
+ const contextProduct = {
366
+ id: productRecord.id,
367
+ title: productRecord.title,
368
+ slug: productRecord.slug,
369
+ sku: productRecord.sku,
370
+ average_rating: productRecord.average_rating,
371
+ total_reviews: productRecord.total_reviews,
372
+ upc: productRecord.upc || undefined,
373
+ price: productRecord.price,
374
+ prices: normalizePriceMap(productRecord.prices),
375
+ sale_price: productRecord.sale_price || null,
376
+ sale_prices: normalizeSalePriceMap(productRecord.sale_prices),
377
+ sale_start_at: productRecord.sale_start_at ?? null,
378
+ sale_end_at: productRecord.sale_end_at ?? null,
379
+ scheduled_price:
380
+ typeof productRecord.scheduled_price === 'number' ? productRecord.scheduled_price : undefined,
381
+ scheduled_prices: normalizePriceMap(productRecord.scheduled_prices),
382
+ scheduled_price_at: productRecord.scheduled_price_at ?? null,
383
+ is_taxable: productRecord.is_taxable ?? true,
384
+ product_type: productRecord.product_type ?? undefined,
385
+ payment_provider: productRecord.payment_provider ?? undefined,
386
+ price_range_min: variantPriceRange?.min ?? null,
387
+ price_range_max: variantPriceRange?.max ?? null,
388
+ image_url: imageUrl,
389
+ images: images,
390
+ short_description: productRecord.short_description || undefined,
391
+ description_json: productRecord.description_json,
392
+ stock:
393
+ productRecord.stock !== undefined && productRecord.stock !== null
394
+ ? productRecord.stock
395
+ : undefined,
396
+ freemius_product_id: productRecord.freemius_product_id || undefined,
397
+ freemius_plan_id: productRecord.freemius_plan_id || undefined,
398
+ trial_period_days: productRecord.trial_period_days ?? 0,
399
+ trial_requires_payment_method: productRecord.trial_requires_payment_method ?? false,
400
+ freemius_plans: productRecord.freemius_plans,
401
+ language_id: productRecord.language_id,
402
+ translation_group_id: productRecord.translation_group_id || "",
403
+ has_variants: variants.length > 0,
404
+ attributes,
405
+ variants,
406
+ categories: productCategories,
407
+ product_variants: (productRecord.product_variants || []).map((variant: any) => ({
408
+ id: variant.id,
409
+ price: variant.price,
410
+ prices: normalizePriceMap(variant.prices),
411
+ sale_price: variant.sale_price,
412
+ sale_prices: normalizeSalePriceMap(variant.sale_prices),
413
+ sale_start_at: variant.sale_start_at ?? null,
414
+ sale_end_at: variant.sale_end_at ?? null,
415
+ scheduled_price: variant.scheduled_price ?? null,
416
+ scheduled_prices: normalizePriceMap(variant.scheduled_prices),
417
+ scheduled_price_at: variant.scheduled_price_at ?? null,
418
+ })),
419
+ };
420
+ const siteUrl = process.env.NEXT_PUBLIC_URL || "";
421
+
422
+ // Whether checkout would actually accept this product, so the structured data
423
+ // doesn't promise a purchase the store can't complete. Defaults to buyable on any
424
+ // failure — a working shop must never lose its offer markup to an unrelated error.
425
+ const canPurchase = await (async () => {
426
+ const provider = productRecord.payment_provider;
427
+ if (provider !== 'stripe' && provider !== 'freemius') return true;
428
+ try {
429
+ return (await getProviderReadiness(provider)).ready;
430
+ } catch {
431
+ return true;
432
+ }
433
+ })();
434
+
435
+ const nonce = (await headers()).get('x-nonce') || undefined;
436
+ const title = resolveMetaTitle(productRecord.meta_title, productRecord.title);
437
+ const description = resolveProductMetaDescription(
438
+ productRecord.meta_description,
439
+ productRecord.short_description
440
+ );
441
+ const { data: defaultCurrency } = await supabase
442
+ .from('currencies')
443
+ .select('code')
444
+ .eq('is_default', true)
445
+ .maybeSingle();
446
+ const price = formatMinorUnitAmount(productRecord.sale_price ?? productRecord.price);
447
+ const productJsonLd = {
448
+ '@context': 'https://schema.org',
449
+ '@type': 'Product',
450
+ name: title,
451
+ description,
452
+ image: images.map((image) => image.url),
453
+ category:
454
+ productCategoryNames.length > 1
455
+ ? productCategoryNames
456
+ : productCategoryNames[0] ?? undefined,
457
+ sku: productRecord.sku || undefined,
458
+ gtin: productRecord.upc || undefined,
459
+ url: `${siteUrl}/product/${productRecord.slug}`,
460
+ offers: price
461
+ ? {
462
+ '@type': 'Offer',
463
+ url: `${siteUrl}/product/${productRecord.slug}`,
464
+ price,
465
+ priceCurrency: defaultCurrency?.code || 'USD',
466
+ availability: resolveOfferAvailability(productRecord, canPurchase),
467
+ itemCondition: 'https://schema.org/NewCondition',
468
+ }
469
+ : undefined,
470
+ };
471
+
472
+ return (
473
+ <div className="min-h-screen bg-background pb-12">
474
+ <script
475
+ type="application/ld+json"
476
+ nonce={nonce}
477
+ suppressHydrationWarning
478
+ dangerouslySetInnerHTML={{ __html: stringifyJsonLd(productJsonLd) }}
479
+ />
480
+ <ProductProvider product={contextProduct}>
481
+ {/*
482
+ BlockRenderer expects languageId property.
483
+ If templatePage is null, we defaulted languageId to 1.
484
+ */}
485
+ <CurrentContentSetter
486
+ id={productRecord.id}
487
+ type="product"
488
+ slug={productRecord.slug}
489
+ translation_group_id={productRecord.translation_group_id}
490
+ />
491
+ <BlockRenderer
492
+ blocks={blocks}
493
+ languageId={languageId}
494
+ excludeProductId={productRecord.id}
495
+ excludeTranslationGroupId={productRecord.translation_group_id}
496
+ visualEditing={productTemplateVisualEditing}
497
+ productVisualEditingEnabled={visualEditingEnabled}
498
+ />
499
+ </ProductProvider>
500
+ </div>
501
+ );
502
+ }