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,362 +1,370 @@
1
- import { verifyPackageOnline, getActiveLanguagesServerSide } from '@nextblock-cms/db/server';
2
- import { redirect, notFound } from 'next/navigation';
3
- import Link from 'next/link';
4
- import { ArrowLeft, ChevronDown, Eye, FilePenLine } from 'lucide-react';
5
- import {
6
- Badge,
7
- Button,
8
- DropdownMenu,
9
- DropdownMenuContent,
10
- DropdownMenuItem,
11
- DropdownMenuLabel,
12
- DropdownMenuSeparator,
13
- DropdownMenuButtonTrigger,
14
- } from '@nextblock-cms/ui';
15
- import ProductFormClientShell from '../../ProductFormClientShell';
16
- import {
17
- getCmsProduct,
18
- getEnabledPaymentProviders,
19
- getGlobalProductAttributes,
20
- getProductTranslations,
21
- getStoreConfigStatus,
22
- normalizeCurrencyRecord,
23
- updateProductAction,
24
- getCategoriesWithCount,
25
- getProductCategories,
26
- } from '@nextblock-cms/ecommerce/server';
27
- import { createClient } from '@nextblock-cms/db/server';
28
- import {
29
- buildGlobalAttributesForForm,
30
- buildProductFormInitialData,
31
- } from '../../productFormData';
32
- import { CortexAiPageContextRegistrar } from '../../../components/CortexAiPageContext';
33
- import BlockEditorArea from '../../../blocks/components/BlockEditorArea';
34
- import VisibilityControl from '../../../components/VisibilityControl';
35
- import RevisionHistoryButton from '../../../revisions/RevisionHistoryButton';
36
- import { buildViewUrl } from '../../../../../lib/publishing/viewUrl';
37
-
38
- export default async function EditProductPage({
39
- params,
40
- searchParams,
41
- }: {
42
- params: Promise<{ id: string }>;
43
- searchParams: Promise<{ missing_lang_id?: string }>;
44
- }) {
45
- const [
46
- { id },
47
- { missing_lang_id },
48
- isOnline,
49
- languages,
50
- enabledProviders,
51
- configStatus,
52
- ] =
53
- await Promise.all([
54
- params,
55
- searchParams,
56
- verifyPackageOnline('ecommerce'),
57
- getActiveLanguagesServerSide(),
58
- getEnabledPaymentProviders(),
59
- getStoreConfigStatus(),
60
- ]);
61
-
62
- if (!isOnline) {
63
- redirect('/cms/settings/packages');
64
- }
65
-
66
- const product = await getCmsProduct(id);
67
-
68
- if (!product) {
69
- notFound();
70
- }
71
-
72
- const [globalAttributesRaw, translations, allCategories, assignedCategories] = await Promise.all([
73
- getGlobalProductAttributes(),
74
- product.translation_group_id ? getProductTranslations(product.translation_group_id) : Promise.resolve([]),
75
- getCategoriesWithCount(),
76
- getProductCategories(product.id),
77
- ]);
78
- const supabase = createClient();
79
- const { data: currenciesResult } = await supabase
80
- .from('currencies')
81
- .select(
82
- 'code, symbol, exchange_rate, is_default, is_active, auto_sync_product_prices, auto_update_exchange_rate, exchange_rate_source, exchange_rate_updated_at, rounding_mode, rounding_increment, rounding_charm_amount'
83
- )
84
- .eq('is_active', true)
85
- .order('code', { ascending: true });
86
- const currencies = (currenciesResult ?? []).map((currency) =>
87
- normalizeCurrencyRecord(currency)
88
- );
89
-
90
- const missingLanguageId = missing_lang_id ? parseInt(missing_lang_id, 10) : null;
91
- const missingLanguage =
92
- missingLanguageId && Number.isFinite(missingLanguageId)
93
- ? languages.find((language) => language.id === missingLanguageId)
94
- : null;
95
- const translationByLanguageId = new Map(
96
- translations.map((translation: any) => [translation.language_id, translation])
97
- );
98
- const existingLanguages = languages.filter(
99
- (language) => language.id === product.language_id || translationByLanguageId.has(language.id)
100
- );
101
- const missingLanguages = languages.filter(
102
- (language) => language.id !== product.language_id && !translationByLanguageId.has(language.id)
103
- );
104
- const primaryCreateLanguage =
105
- missingLanguage && missingLanguages.some((language) => language.id === missingLanguage.id)
106
- ? missingLanguage
107
- : missingLanguages.length === 1
108
- ? missingLanguages[0]
109
- : null;
110
- const additionalCreateLanguages = missingLanguages.filter(
111
- (language) => language.id !== primaryCreateLanguage?.id
112
- );
113
- const buildTranslationCreateHref = (languageId: number) =>
114
- `/cms/products/new?from_group=${product.translation_group_id}&target_lang_id=${languageId}`;
115
- const globalAttributes = buildGlobalAttributesForForm(globalAttributesRaw || []);
116
- const productLanguage = languages.find((language) => language.id === product.language_id);
117
-
118
- // The Status select used to sit inside ProductForm, where submitting with
119
- // status "active" was blocked unless the payment provider was enabled and
120
- // configured. Publishing now happens outside the form, so that guard has to
121
- // travel with it a product nobody can pay for should not reach the storefront.
122
- const productProvider = product.payment_provider as 'stripe' | 'freemius' | undefined;
123
- const publishBlockedReason =
124
- productProvider && (!enabledProviders[productProvider] || !configStatus[productProvider].hasKeys)
125
- ? `${productProvider === 'stripe' ? 'Stripe' : 'Freemius'} must be enabled and fully configured before this product can be published.`
126
- : null;
127
-
128
- const { data: draftData } = await supabase
129
- .from('product_drafts')
130
- .select('*')
131
- .eq('product_id', product.id)
132
- .maybeSingle();
133
-
134
- const hasDraft = draftData !== null;
135
- let normalizedInitialData = {
136
- ...buildProductFormInitialData(product, languages),
137
- category_ids: assignedCategories.map((c: any) => c.id),
138
- };
139
- if (draftData && draftData.meta && typeof draftData.meta === 'object') {
140
- const meta = draftData.meta as any;
141
-
142
- // Drafts store product_media as { media_id } only, so the gallery loses the
143
- // file_path/object_key needed to render thumbnails. Re-hydrate from the
144
- // media table so the main image (and the rest of the gallery) still loads.
145
- let hydratedProductMedia = meta.product_media;
146
- if (Array.isArray(meta.product_media) && meta.product_media.length > 0) {
147
- const draftMediaIds = meta.product_media
148
- .map((pm: any) => pm?.media_id)
149
- .filter(Boolean);
150
- if (draftMediaIds.length > 0) {
151
- const { data: mediaRows } = await supabase
152
- .from('media')
153
- .select('id, file_path, object_key, file_name, description')
154
- .in('id', draftMediaIds);
155
- const mediaById = new Map((mediaRows || []).map((m: any) => [m.id, m]));
156
- hydratedProductMedia = meta.product_media.map((pm: any, index: number) => {
157
- const media = mediaById.get(pm?.media_id);
158
- return {
159
- media_id: pm?.media_id,
160
- sort_order: pm?.sort_order ?? index,
161
- media: media
162
- ? {
163
- file_path: media.file_path,
164
- object_key: media.object_key,
165
- alt_text: media.description || media.file_name || '',
166
- }
167
- : pm?.media ?? null,
168
- };
169
- });
170
- }
171
- }
172
-
173
- // Product drafts persist prices in major units (dollars, the ProductForm
174
- // value shape), but ProductForm re-divides the top-level price/sale_price by
175
- // 100 because it expects a raw product row (minor units/cents). Convert the
176
- // draft's dollars back to cents so the form shows the saved amount instead of
177
- // 1/100th of it (e.g. an imported $29.50 draft otherwise renders as $0.30).
178
- // The prices maps and variant prices are already in the dollar shape the form
179
- // consumes directly, so only these two scalars need converting.
180
- const draftDollarsToStoredCents = (value: unknown) =>
181
- typeof value === 'number' && Number.isFinite(value) ? Math.round(value * 100) : value;
182
-
183
- normalizedInitialData = {
184
- ...meta,
185
- id: product.id,
186
- price: draftDollarsToStoredCents(meta.price),
187
- sale_price: draftDollarsToStoredCents(meta.sale_price),
188
- product_media: hydratedProductMedia,
189
- category_ids: meta.category_ids ?? assignedCategories.map((c: any) => c.id),
190
- };
191
- }
192
-
193
- let descriptionBlocks: any[] = [];
194
- if (draftData && draftData.blocks && Array.isArray(draftData.blocks)) {
195
- descriptionBlocks = draftData.blocks;
196
- } else {
197
- const { data: liveBlocks } = await supabase
198
- .from('blocks')
199
- .select('*')
200
- .eq('product_id', product.id)
201
- .order('order', { ascending: true });
202
- descriptionBlocks = liveBlocks || [];
203
- }
204
-
205
- return (
206
- <div className="space-y-8 w-full max-w-[1400px] mx-auto px-6 py-8">
207
- <CortexAiPageContextRegistrar
208
- context={{
209
- contentType: 'product',
210
- entityId: product.id,
211
- languageId: product.language_id,
212
- slug: product.slug,
213
- title: product.title,
214
- translationGroupId: product.translation_group_id,
215
- }}
216
- />
217
- <div className="flex justify-between items-center flex-wrap gap-4 w-full">
218
- <div className="flex items-center gap-3">
219
- <Button variant="outline" size="icon" aria-label="Back to products" asChild>
220
- <Link href="/cms/products">
221
- <ArrowLeft className="h-4 w-4" />
222
- </Link>
223
- </Button>
224
- <div>
225
- <h1 className="text-2xl font-bold">Edit Product</h1>
226
- <p className="text-sm text-muted-foreground truncate max-w-md" title={product.title}>
227
- {product.title}
228
- </p>
229
- </div>
230
- </div>
231
-
232
- <div className="flex items-center gap-3 flex-wrap">
233
- {existingLanguages.map((language) => {
234
- const version = translationByLanguageId.get(language.id);
235
- const isCurrent = language.id === product.language_id;
236
- const href = version
237
- ? `/cms/products/${version.id}/edit`
238
- : `/cms/products/${product.id}/edit`;
239
-
240
- return (
241
- <Button key={language.id} asChild variant={isCurrent ? 'default' : 'outline'} size="sm">
242
- <Link href={href}>
243
- {language.name} ({language.code.toUpperCase()})
244
- </Link>
245
- </Button>
246
- );
247
- })}
248
-
249
- {primaryCreateLanguage && product.translation_group_id ? (
250
- <Button asChild variant="secondary" size="sm">
251
- <Link href={buildTranslationCreateHref(primaryCreateLanguage.id)}>
252
- Create {primaryCreateLanguage.name} Translation
253
- </Link>
254
- </Button>
255
- ) : null}
256
-
257
- {additionalCreateLanguages.length > 0 && product.translation_group_id ? (
258
- <DropdownMenu>
259
- <DropdownMenuButtonTrigger
260
- id={`create-translation-trigger-${product.id}`}
261
- variant="outline"
262
- size="sm"
263
- >
264
- Create Translation
265
- <Badge variant="secondary" className="ml-2 px-1.5 py-0 text-[10px]">
266
- {additionalCreateLanguages.length}
267
- </Badge>
268
- <ChevronDown className="ml-2 h-4 w-4" />
269
- </DropdownMenuButtonTrigger>
270
- <DropdownMenuContent align="end" className="w-64">
271
- <DropdownMenuLabel>Missing Languages</DropdownMenuLabel>
272
- <DropdownMenuSeparator />
273
- {additionalCreateLanguages.map((language) => (
274
- <DropdownMenuItem key={language.id} asChild>
275
- <Link href={buildTranslationCreateHref(language.id)}>
276
- Create {language.name}
277
- </Link>
278
- </DropdownMenuItem>
279
- ))}
280
- </DropdownMenuContent>
281
- </DropdownMenu>
282
- ) : null}
283
-
284
- {product.slug ? (
285
- <>
286
- <Button variant="secondary" asChild>
287
- <a
288
- href={buildViewUrl({
289
- path: `/product/${product.slug}`,
290
- languageCode: productLanguage?.code ?? null,
291
- draft: true,
292
- })}
293
- target="_blank"
294
- rel="noopener noreferrer"
295
- >
296
- <FilePenLine className="mr-2 h-4 w-4" /> Preview
297
- </a>
298
- </Button>
299
- {product.status === 'active' ? (
300
- <Button variant="outline" asChild>
301
- <a
302
- href={buildViewUrl({
303
- path: `/product/${product.slug}`,
304
- languageCode: productLanguage?.code ?? null,
305
- })}
306
- target="_blank"
307
- rel="noopener noreferrer"
308
- >
309
- <Eye className="mr-2 h-4 w-4" /> View Live
310
- </a>
311
- </Button>
312
- ) : null}
313
- </>
314
- ) : null}
315
-
316
- <RevisionHistoryButton parentType="product" parentId={product.id} />
317
-
318
- <VisibilityControl
319
- type="product"
320
- id={product.id}
321
- status={product.status}
322
- publishedAt={(product as { published_at?: string | null }).published_at ?? null}
323
- publicPath={`/product/${product.slug}`}
324
- languageName={
325
- productLanguage
326
- ? `${productLanguage.name} (${productLanguage.code.toUpperCase()})`
327
- : undefined
328
- }
329
- translationGroupId={product.translation_group_id}
330
- languages={languages}
331
- hasDraft={hasDraft}
332
- publishBlockedReason={publishBlockedReason}
333
- />
334
- </div>
335
- </div>
336
-
337
- <ProductFormClientShell
338
- productId={product.id}
339
- serverHasDraft={hasDraft}
340
- initialData={normalizedInitialData}
341
- isEdit
342
- availableLanguagesProp={languages}
343
- globalAttributesProp={globalAttributes}
344
- currenciesProp={currencies}
345
- enabledProviders={enabledProviders}
346
- configStatus={configStatus}
347
- updateAction={updateProductAction.bind(null, product.id)}
348
- availableCategoriesProp={allCategories}
349
- />
350
-
351
- <div className="border-t pt-8">
352
- <h2 className="text-xl font-bold mb-4">Product Description Blocks</h2>
353
- <BlockEditorArea
354
- parentId={product.id}
355
- parentType="product"
356
- initialBlocks={descriptionBlocks}
357
- languageId={product.language_id}
358
- />
359
- </div>
360
- </div>
361
- );
362
- }
1
+ import { verifyPackageOnline, getActiveLanguagesServerSide } from '@nextblock-cms/db/server';
2
+ import { redirect, notFound } from 'next/navigation';
3
+ import Link from 'next/link';
4
+ import { ArrowLeft, ChevronDown, Eye, FilePenLine } from 'lucide-react';
5
+ import {
6
+ Badge,
7
+ Button,
8
+ DropdownMenu,
9
+ DropdownMenuContent,
10
+ DropdownMenuItem,
11
+ DropdownMenuLabel,
12
+ DropdownMenuSeparator,
13
+ DropdownMenuButtonTrigger,
14
+ } from '@nextblock-cms/ui';
15
+ import ProductFormClientShell from '../../ProductFormClientShell';
16
+ import {
17
+ getCmsProduct,
18
+ getEnabledPaymentProviders,
19
+ getGlobalProductAttributes,
20
+ getProductTranslations,
21
+ getStoreConfigStatus,
22
+ getStoreReadiness,
23
+ normalizeCurrencyRecord,
24
+ updateProductAction,
25
+ getCategoriesWithCount,
26
+ getProductCategories,
27
+ } from '@nextblock-cms/ecommerce/server';
28
+ import { createClient } from '@nextblock-cms/db/server';
29
+ import {
30
+ buildGlobalAttributesForForm,
31
+ buildProductFormInitialData,
32
+ } from '../../productFormData';
33
+ import { CortexAiPageContextRegistrar } from '../../../components/CortexAiPageContext';
34
+ import BlockEditorArea from '../../../blocks/components/BlockEditorArea';
35
+ import VisibilityControl from '../../../components/VisibilityControl';
36
+ import RevisionHistoryButton from '../../../revisions/RevisionHistoryButton';
37
+ import { buildViewUrl } from '../../../../../lib/publishing/viewUrl';
38
+
39
+ export default async function EditProductPage({
40
+ params,
41
+ searchParams,
42
+ }: {
43
+ params: Promise<{ id: string }>;
44
+ searchParams: Promise<{ missing_lang_id?: string }>;
45
+ }) {
46
+ const [
47
+ { id },
48
+ { missing_lang_id },
49
+ isOnline,
50
+ languages,
51
+ enabledProviders,
52
+ configStatus,
53
+ storeReadiness,
54
+ ] =
55
+ await Promise.all([
56
+ params,
57
+ searchParams,
58
+ verifyPackageOnline('ecommerce'),
59
+ getActiveLanguagesServerSide(),
60
+ getEnabledPaymentProviders(),
61
+ getStoreConfigStatus(),
62
+ getStoreReadiness(),
63
+ ]);
64
+
65
+ if (!isOnline) {
66
+ redirect('/cms/settings/packages');
67
+ }
68
+
69
+ const product = await getCmsProduct(id);
70
+
71
+ if (!product) {
72
+ notFound();
73
+ }
74
+
75
+ const [globalAttributesRaw, translations, allCategories, assignedCategories] = await Promise.all([
76
+ getGlobalProductAttributes(),
77
+ product.translation_group_id ? getProductTranslations(product.translation_group_id) : Promise.resolve([]),
78
+ getCategoriesWithCount(),
79
+ getProductCategories(product.id),
80
+ ]);
81
+ const supabase = createClient();
82
+ const { data: currenciesResult } = await supabase
83
+ .from('currencies')
84
+ .select(
85
+ 'code, symbol, exchange_rate, is_default, is_active, auto_sync_product_prices, auto_update_exchange_rate, exchange_rate_source, exchange_rate_updated_at, rounding_mode, rounding_increment, rounding_charm_amount'
86
+ )
87
+ .eq('is_active', true)
88
+ .order('code', { ascending: true });
89
+ const currencies = (currenciesResult ?? []).map((currency) =>
90
+ normalizeCurrencyRecord(currency)
91
+ );
92
+
93
+ const missingLanguageId = missing_lang_id ? parseInt(missing_lang_id, 10) : null;
94
+ const missingLanguage =
95
+ missingLanguageId && Number.isFinite(missingLanguageId)
96
+ ? languages.find((language) => language.id === missingLanguageId)
97
+ : null;
98
+ const translationByLanguageId = new Map(
99
+ translations.map((translation: any) => [translation.language_id, translation])
100
+ );
101
+ const existingLanguages = languages.filter(
102
+ (language) => language.id === product.language_id || translationByLanguageId.has(language.id)
103
+ );
104
+ const missingLanguages = languages.filter(
105
+ (language) => language.id !== product.language_id && !translationByLanguageId.has(language.id)
106
+ );
107
+ const primaryCreateLanguage =
108
+ missingLanguage && missingLanguages.some((language) => language.id === missingLanguage.id)
109
+ ? missingLanguage
110
+ : missingLanguages.length === 1
111
+ ? missingLanguages[0]
112
+ : null;
113
+ const additionalCreateLanguages = missingLanguages.filter(
114
+ (language) => language.id !== primaryCreateLanguage?.id
115
+ );
116
+ const buildTranslationCreateHref = (languageId: number) =>
117
+ `/cms/products/new?from_group=${product.translation_group_id}&target_lang_id=${languageId}`;
118
+ const globalAttributes = buildGlobalAttributesForForm(globalAttributesRaw || []);
119
+ const productLanguage = languages.find((language) => language.id === product.language_id);
120
+
121
+ // The Status select used to sit inside ProductForm, where submitting with status
122
+ // "active" was blocked unless the payment provider was enabled and configured.
123
+ // Publishing now happens outside the form, so that guidance travels with it — but as
124
+ // a WARNING, not a block: an owner should be able to build a catalogue while their
125
+ // Stripe onboarding is still in progress. The storefront covers the gap by offering
126
+ // shoppers an enquiry form in place of Add-to-Cart.
127
+ const productProvider = product.payment_provider as 'stripe' | 'freemius' | undefined;
128
+ const providerReadiness = productProvider ? storeReadiness[productProvider] : null;
129
+ const publishWarning =
130
+ providerReadiness && !providerReadiness.ready
131
+ ? `${providerReadiness.label} isn't set up yet${
132
+ providerReadiness.missing.length ? ` (missing: ${providerReadiness.missing.join(', ')})` : ''
133
+ }, so nobody can buy this product. It will still go live — visitors will see a "Contact the seller" form instead of Add to cart. Finish setting up payments at CMS → Payments.`
134
+ : null;
135
+
136
+ const { data: draftData } = await supabase
137
+ .from('product_drafts')
138
+ .select('*')
139
+ .eq('product_id', product.id)
140
+ .maybeSingle();
141
+
142
+ const hasDraft = draftData !== null;
143
+ let normalizedInitialData = {
144
+ ...buildProductFormInitialData(product, languages),
145
+ category_ids: assignedCategories.map((c: any) => c.id),
146
+ };
147
+ if (draftData && draftData.meta && typeof draftData.meta === 'object') {
148
+ const meta = draftData.meta as any;
149
+
150
+ // Drafts store product_media as { media_id } only, so the gallery loses the
151
+ // file_path/object_key needed to render thumbnails. Re-hydrate from the
152
+ // media table so the main image (and the rest of the gallery) still loads.
153
+ let hydratedProductMedia = meta.product_media;
154
+ if (Array.isArray(meta.product_media) && meta.product_media.length > 0) {
155
+ const draftMediaIds = meta.product_media
156
+ .map((pm: any) => pm?.media_id)
157
+ .filter(Boolean);
158
+ if (draftMediaIds.length > 0) {
159
+ const { data: mediaRows } = await supabase
160
+ .from('media')
161
+ .select('id, file_path, object_key, file_name, description')
162
+ .in('id', draftMediaIds);
163
+ const mediaById = new Map((mediaRows || []).map((m: any) => [m.id, m]));
164
+ hydratedProductMedia = meta.product_media.map((pm: any, index: number) => {
165
+ const media = mediaById.get(pm?.media_id);
166
+ return {
167
+ media_id: pm?.media_id,
168
+ sort_order: pm?.sort_order ?? index,
169
+ media: media
170
+ ? {
171
+ file_path: media.file_path,
172
+ object_key: media.object_key,
173
+ alt_text: media.description || media.file_name || '',
174
+ }
175
+ : pm?.media ?? null,
176
+ };
177
+ });
178
+ }
179
+ }
180
+
181
+ // Product drafts persist prices in major units (dollars, the ProductForm
182
+ // value shape), but ProductForm re-divides the top-level price/sale_price by
183
+ // 100 because it expects a raw product row (minor units/cents). Convert the
184
+ // draft's dollars back to cents so the form shows the saved amount instead of
185
+ // 1/100th of it (e.g. an imported $29.50 draft otherwise renders as $0.30).
186
+ // The prices maps and variant prices are already in the dollar shape the form
187
+ // consumes directly, so only these two scalars need converting.
188
+ const draftDollarsToStoredCents = (value: unknown) =>
189
+ typeof value === 'number' && Number.isFinite(value) ? Math.round(value * 100) : value;
190
+
191
+ normalizedInitialData = {
192
+ ...meta,
193
+ id: product.id,
194
+ price: draftDollarsToStoredCents(meta.price),
195
+ sale_price: draftDollarsToStoredCents(meta.sale_price),
196
+ product_media: hydratedProductMedia,
197
+ category_ids: meta.category_ids ?? assignedCategories.map((c: any) => c.id),
198
+ };
199
+ }
200
+
201
+ let descriptionBlocks: any[] = [];
202
+ if (draftData && draftData.blocks && Array.isArray(draftData.blocks)) {
203
+ descriptionBlocks = draftData.blocks;
204
+ } else {
205
+ const { data: liveBlocks } = await supabase
206
+ .from('blocks')
207
+ .select('*')
208
+ .eq('product_id', product.id)
209
+ .order('order', { ascending: true });
210
+ descriptionBlocks = liveBlocks || [];
211
+ }
212
+
213
+ return (
214
+ <div className="space-y-8 w-full max-w-[1400px] mx-auto px-6 py-8">
215
+ <CortexAiPageContextRegistrar
216
+ context={{
217
+ contentType: 'product',
218
+ entityId: product.id,
219
+ languageId: product.language_id,
220
+ slug: product.slug,
221
+ title: product.title,
222
+ translationGroupId: product.translation_group_id,
223
+ }}
224
+ />
225
+ <div className="flex justify-between items-center flex-wrap gap-4 w-full">
226
+ <div className="flex items-center gap-3">
227
+ <Button variant="outline" size="icon" aria-label="Back to products" asChild>
228
+ <Link href="/cms/products">
229
+ <ArrowLeft className="h-4 w-4" />
230
+ </Link>
231
+ </Button>
232
+ <div>
233
+ <h1 className="text-2xl font-bold">Edit Product</h1>
234
+ <p className="text-sm text-muted-foreground truncate max-w-md" title={product.title}>
235
+ {product.title}
236
+ </p>
237
+ </div>
238
+ </div>
239
+
240
+ <div className="flex items-center gap-3 flex-wrap">
241
+ {existingLanguages.map((language) => {
242
+ const version = translationByLanguageId.get(language.id);
243
+ const isCurrent = language.id === product.language_id;
244
+ const href = version
245
+ ? `/cms/products/${version.id}/edit`
246
+ : `/cms/products/${product.id}/edit`;
247
+
248
+ return (
249
+ <Button key={language.id} asChild variant={isCurrent ? 'default' : 'outline'} size="sm">
250
+ <Link href={href}>
251
+ {language.name} ({language.code.toUpperCase()})
252
+ </Link>
253
+ </Button>
254
+ );
255
+ })}
256
+
257
+ {primaryCreateLanguage && product.translation_group_id ? (
258
+ <Button asChild variant="secondary" size="sm">
259
+ <Link href={buildTranslationCreateHref(primaryCreateLanguage.id)}>
260
+ Create {primaryCreateLanguage.name} Translation
261
+ </Link>
262
+ </Button>
263
+ ) : null}
264
+
265
+ {additionalCreateLanguages.length > 0 && product.translation_group_id ? (
266
+ <DropdownMenu>
267
+ <DropdownMenuButtonTrigger
268
+ id={`create-translation-trigger-${product.id}`}
269
+ variant="outline"
270
+ size="sm"
271
+ >
272
+ Create Translation
273
+ <Badge variant="secondary" className="ml-2 px-1.5 py-0 text-[10px]">
274
+ {additionalCreateLanguages.length}
275
+ </Badge>
276
+ <ChevronDown className="ml-2 h-4 w-4" />
277
+ </DropdownMenuButtonTrigger>
278
+ <DropdownMenuContent align="end" className="w-64">
279
+ <DropdownMenuLabel>Missing Languages</DropdownMenuLabel>
280
+ <DropdownMenuSeparator />
281
+ {additionalCreateLanguages.map((language) => (
282
+ <DropdownMenuItem key={language.id} asChild>
283
+ <Link href={buildTranslationCreateHref(language.id)}>
284
+ Create {language.name}
285
+ </Link>
286
+ </DropdownMenuItem>
287
+ ))}
288
+ </DropdownMenuContent>
289
+ </DropdownMenu>
290
+ ) : null}
291
+
292
+ {product.slug ? (
293
+ <>
294
+ <Button variant="secondary" asChild>
295
+ <a
296
+ href={buildViewUrl({
297
+ path: `/product/${product.slug}`,
298
+ languageCode: productLanguage?.code ?? null,
299
+ draft: true,
300
+ })}
301
+ target="_blank"
302
+ rel="noopener noreferrer"
303
+ >
304
+ <FilePenLine className="mr-2 h-4 w-4" /> Preview
305
+ </a>
306
+ </Button>
307
+ {product.status === 'active' ? (
308
+ <Button variant="outline" asChild>
309
+ <a
310
+ href={buildViewUrl({
311
+ path: `/product/${product.slug}`,
312
+ languageCode: productLanguage?.code ?? null,
313
+ })}
314
+ target="_blank"
315
+ rel="noopener noreferrer"
316
+ >
317
+ <Eye className="mr-2 h-4 w-4" /> View Live
318
+ </a>
319
+ </Button>
320
+ ) : null}
321
+ </>
322
+ ) : null}
323
+
324
+ <RevisionHistoryButton parentType="product" parentId={product.id} />
325
+
326
+ <VisibilityControl
327
+ type="product"
328
+ id={product.id}
329
+ status={product.status}
330
+ publishedAt={(product as { published_at?: string | null }).published_at ?? null}
331
+ publicPath={`/product/${product.slug}`}
332
+ languageName={
333
+ productLanguage
334
+ ? `${productLanguage.name} (${productLanguage.code.toUpperCase()})`
335
+ : undefined
336
+ }
337
+ translationGroupId={product.translation_group_id}
338
+ languages={languages}
339
+ hasDraft={hasDraft}
340
+ publishWarning={publishWarning}
341
+ />
342
+ </div>
343
+ </div>
344
+
345
+ <ProductFormClientShell
346
+ productId={product.id}
347
+ serverHasDraft={hasDraft}
348
+ initialData={normalizedInitialData}
349
+ isEdit
350
+ availableLanguagesProp={languages}
351
+ globalAttributesProp={globalAttributes}
352
+ currenciesProp={currencies}
353
+ enabledProviders={enabledProviders}
354
+ configStatus={configStatus}
355
+ updateAction={updateProductAction.bind(null, product.id)}
356
+ availableCategoriesProp={allCategories}
357
+ />
358
+
359
+ <div className="border-t pt-8">
360
+ <h2 className="text-xl font-bold mb-4">Product Description Blocks</h2>
361
+ <BlockEditorArea
362
+ parentId={product.id}
363
+ parentType="product"
364
+ initialBlocks={descriptionBlocks}
365
+ languageId={product.language_id}
366
+ />
367
+ </div>
368
+ </div>
369
+ );
370
+ }