design upgrade

This commit is contained in:
Nermin Karic
2026-11-23 00:59:47 +01:00
parent 9e84140474
commit ada6fd857c
198 changed files with 6626 additions and 2539 deletions

View File

@@ -0,0 +1,169 @@
import { HttpTypes } from "@medusajs/types"
import configuratorData from "@/config/configurator.json"
import {
AddonGroup,
AddonItem,
ConfiguratorConfig,
ConfiguratorOverride,
ConfiguratorView,
LayerDef,
LayerImages,
OptionDriver,
} from "./types"
export * from "./types"
/** Selected add-on items per group id */
export type AddonSelection = Record<string, string[]>
export type LayerContext = {
options: Partial<Record<OptionDriver, string>>
addons: AddonSelection
}
const data = configuratorData as unknown as {
default: ConfiguratorConfig
products: Record<string, ConfiguratorOverride>
}
function parseMetadataOverride(raw: unknown): ConfiguratorOverride | null {
if (!raw) return null
if (typeof raw === "object") return raw as ConfiguratorOverride
if (typeof raw === "string") {
try {
return JSON.parse(raw) as ConfiguratorOverride
} catch {
return null
}
}
return null
}
function mergeImages(...sources: (LayerImages | undefined)[]): LayerImages {
const out: LayerImages = {}
for (const src of sources) {
if (!src) continue
for (const [layerId, views] of Object.entries(src)) {
const target = (out[layerId] ??= {})
for (const [view, keys] of Object.entries(views ?? {})) {
target[view as ConfiguratorView] = {
...(target[view as ConfiguratorView] ?? {}),
...(keys ?? {}),
}
}
}
}
return out
}
/**
* Effective configurator config for a product:
* defaults <- products[handle] in configurator.json <- product.metadata.configurator
*/
export function getConfiguratorConfig(
product: HttpTypes.StoreProduct
): ConfiguratorConfig {
const base = data.default
const byHandle = product.handle ? data.products[product.handle] : undefined
const fromMetadata = parseMetadataOverride(product.metadata?.configurator)
const hidden = new Set([
...(byHandle?.hideAddons ?? []),
...(fromMetadata?.hideAddons ?? []),
])
const addons = (fromMetadata?.addons ?? byHandle?.addons ?? base.addons).filter(
(g) => !hidden.has(g.id)
)
return {
canvas: fromMetadata?.canvas ?? byHandle?.canvas ?? base.canvas,
views: fromMetadata?.views ?? byHandle?.views ?? base.views,
layers: fromMetadata?.layers ?? byHandle?.layers ?? base.layers,
images: mergeImages(base.images, byHandle?.images, fromMetadata?.images),
addons,
}
}
/** Whether a layer is drawn for the current view and selection */
export function isLayerActive(
layer: LayerDef,
view: ConfiguratorView,
ctx: LayerContext,
addonGroups: AddonGroup[]
) {
if (layer.views && !layer.views.includes(view)) return false
const driver = layer.driver
if (driver && "addon" in driver) {
// Layer belongs to an add-on group that this product does not offer
if (!addonGroups.some((g) => g.id === driver.addon)) return false
if ("item" in driver) return (ctx.addons[driver.addon] ?? []).includes(driver.item)
}
return true
}
/** Value that drives a layer, e.g. the selected fabric or base item */
export function getLayerValue(layer: LayerDef, ctx: LayerContext) {
const driver = layer.driver
if (!driver) return undefined
if ("option" in driver) return ctx.options[driver.option]
if ("item" in driver) return driver.item
return ctx.addons[driver.addon]?.[0]
}
/**
* Image for a layer, most specific key first:
* "<size>|<value>", "<value>", "<size>|*", "*". Undefined means: draw the SVG.
*/
export function resolveLayerImage(
config: ConfiguratorConfig,
layer: LayerDef,
view: ConfiguratorView,
ctx: LayerContext
) {
const keys = config.images[layer.id]?.[view]
if (!keys) return undefined
const value = getLayerValue(layer, ctx)
const size = ctx.options.size
const candidates = [
size && value ? `${size}|${value}` : null,
value ?? null,
size ? `${size}|*` : null,
"*",
].filter(Boolean) as string[]
for (const key of candidates) {
if (keys[key]) return keys[key]
}
return undefined
}
/** Reason the item cannot be picked with the current options, or null */
export function getAddonConflict(item: AddonItem, selectedValues: string[]) {
const hit = item.incompatibleWith?.find((needle) =>
selectedValues.some((v) => v.toLowerCase().includes(needle.toLowerCase()))
)
return hit ? item.reason ?? "Nije kompatibilno s odabranom konfiguracijom" : null
}
export function defaultAddonSelection(groups: AddonGroup[]): AddonSelection {
return Object.fromEntries(groups.map((g) => [g.id, g.defaults ?? []]))
}
/** "postolje:krizno;oprema:led,grijac" for shareable URLs */
export function encodeAddons(selection: AddonSelection) {
return Object.entries(selection)
.filter(([, items]) => items.length)
.map(([group, items]) => `${group}:${items.join(",")}`)
.join(";")
}
export function decodeAddons(raw: string | null, groups: AddonGroup[]): AddonSelection | null {
if (!raw) return null
const out = defaultAddonSelection(groups)
for (const part of raw.split(";")) {
const [groupId, items] = part.split(":")
const group = groups.find((g) => g.id === groupId)
if (!group || !items) continue
const valid = items.split(",").filter((id) => group.items.some((i) => i.id === id))
out[groupId] = group.type === "single" ? valid.slice(0, 1) : valid
}
return out
}

View File

@@ -0,0 +1,82 @@
/**
* Umbrella configurator schema.
*
* The preview is a stack of layers (bottom to top). Each layer is either an
* image (transparent PNG/WebP, all drawn on the same canvas size) or, while
* no image is set, a built-in SVG drawing. Images can be added per layer, per
* view and per selected value without code changes; see `configurator.json`.
*/
export type ConfiguratorView = "side" | "top"
/** Medusa product option kinds the configurator understands */
export type OptionDriver = "size" | "fabric" | "frame"
export type LayerDriver =
/** Image chosen by the selected value of a Medusa option */
| { option: OptionDriver }
/** Image chosen by the selected item of an add-on group */
| { addon: string }
/** Layer shown only when this add-on item is selected */
| { addon: string; item: string }
/** Built-in SVG fallback drawn when the layer has no image */
export type LayerFallback = "shadow" | "base" | "mast" | "canopy" | "led" | "heater"
export type LayerDef = {
id: string
fallback?: LayerFallback
driver?: LayerDriver
/** Views this layer appears in; defaults to all */
views?: ConfiguratorView[]
}
/**
* Layer images: layerId -> view -> key -> url.
* Key is the selected value that drives the layer (e.g. "Bordo Crvena"),
* "<size>|<value>" for a shape-specific image, or "*" for any value.
*/
export type LayerImages = Partial<
Record<string, Partial<Record<ConfiguratorView, Record<string, string>>>>
>
export type AddonItem = {
id: string
label: string
description?: string
/** Medusa variant added to the cart as its own line; enables a real price */
variantId?: string
/**
* Substrings of selected option values this item cannot be combined with,
* e.g. ["4x4", "5x5"] for a base that is too light for large canopies.
*/
incompatibleWith?: string[]
/** Shown when the item is disabled by `incompatibleWith` */
reason?: string
}
export type AddonGroup = {
id: string
title: string
description?: string
type: "single" | "multi"
/** Preselected item(s) */
defaults?: string[]
items: AddonItem[]
}
export type ConfiguratorConfig = {
/** Pixel size all layer images are exported at */
canvas: { width: number; height: number }
views: ConfiguratorView[]
layers: LayerDef[]
images: LayerImages
addons: AddonGroup[]
}
/** Partial override per product handle or from product.metadata.configurator */
export type ConfiguratorOverride = Partial<Omit<ConfiguratorConfig, "canvas">> & {
canvas?: ConfiguratorConfig["canvas"]
/** Add-on group ids to hide for this product */
hideAddons?: string[]
}

View File

@@ -0,0 +1,49 @@
import visualsData from "@/config/product-visuals.json"
/** Fixed steps of the quote configurator that have their own image */
export type VisualStep = "uvod" | "postupak" | "specifikacije" | "sazetak"
type ProductVisuals = {
steps?: Partial<Record<VisualStep, string>>
/** option title -> value -> url */
options?: Record<string, Record<string, string>>
}
const data = visualsData as unknown as { products: Record<string, ProductVisuals> }
const STEP_TEXT: Record<VisualStep, string> = {
uvod: "",
postupak: "Mjerenje i montaža",
specifikacije: "Detalji izrade",
sazetak: "",
}
function placeholder(text: string, bg = "d4d8de", fg = "6b7280") {
const t = encodeURIComponent(text).replace(/%20/g, "+")
return `https://placehold.co/1600x1200/${bg}/${fg}?text=${t}`
}
/** Image for a fixed step, or a placeholder named after the step */
export function getStepVisual(handle: string | null | undefined, title: string, step: VisualStep) {
const custom = handle ? data.products[handle]?.steps?.[step] : undefined
return custom ?? placeholder(STEP_TEXT[step] || title)
}
/**
* Image for an option value. Colour-like values get a placeholder in that
* colour (from `colorHex`), so changing e.g. the fabric visibly swaps it.
*/
export function getOptionVisual(
handle: string | null | undefined,
optionTitle: string,
value: string,
colorHex?: string,
isDark?: boolean
) {
const custom = handle ? data.products[handle]?.options?.[optionTitle]?.[value] : undefined
if (custom) return custom
if (colorHex?.startsWith("#")) {
return placeholder(`${optionTitle}: ${value}`, colorHex.slice(1), isDark ? "ffffff" : "1f2937")
}
return placeholder(`${optionTitle}: ${value}`)
}

View File

@@ -118,10 +118,13 @@ export async function addToCart({
variantId,
quantity,
countryCode,
metadata,
}: {
variantId: string
quantity: number
countryCode: string
/** Stored on the line item, e.g. the configurator selection */
metadata?: Record<string, unknown>
}) {
if (!variantId) {
throw new Error("Missing variant ID when adding to cart")
@@ -143,6 +146,7 @@ export async function addToCart({
{
variant_id: variantId,
quantity,
...(metadata ? { metadata } : {}),
},
{},
headers

View File

@@ -0,0 +1,13 @@
/**
* How an option is presented: colour swatches, stacked size/model cards,
* or plain choice cards for everything else.
*/
export type OptionKind = "fabric" | "frame" | "size" | "choice"
export function getOptionKind(title?: string | null): OptionKind {
const t = (title ?? "").toLowerCase()
if (/konstrukcij|profil|frame/.test(t)) return "frame"
if (/boja|platn|dezen|color/.test(t)) return "fabric"
if (/dimenzij|izvedb|raspon|širin|sirin|veličin|velicin|size/.test(t)) return "size"
return "choice"
}

View File

@@ -0,0 +1,4 @@
/** "1 proizvod", "21 proizvod", "2 proizvoda", "12 proizvoda" */
export function productCount(n: number) {
return n % 10 === 1 && n % 100 !== 11 ? `${n} proizvod` : `${n} proizvoda`
}

View File

@@ -0,0 +1,158 @@
import { HttpTypes } from "@medusajs/types"
/**
* Sale scenarios set per product in Medusa Admin (product-inquiry widget):
* - in_stock: available now, add to cart
* - made_to_order: add to cart, delivered after `lead_time_days`
* - quote_only: no price or cart, customer sends an inquiry
*/
export type SaleScenario = "in_stock" | "made_to_order" | "quote_only"
export type SaleInfo = {
scenario: SaleScenario
/** Short status, e.g. "Na stanju" */
label: string
/** One line with delivery detail, e.g. "Isporuka za 14 dana" */
detail: string
leadTimeDays: number
allowCustomization: boolean
quoteSubtitle: string
/** Tailwind classes for the small status dot */
dotClass: string
}
type Metadata = Record<string, unknown> | null | undefined
export function getSaleInfo(metadata: Metadata): SaleInfo {
const raw = metadata?.sale_scenario
const scenario: SaleScenario =
raw === "quote_only" || raw === "made_to_order" ? raw : "in_stock"
const leadTimeDays = Number(metadata?.lead_time_days) || 14
const allowCustomization = Boolean(metadata?.allow_customization)
const quoteSubtitle =
(metadata?.quote_subtitle as string) ||
"Izrada po mjeri sa profesionalnom montažom i garancijom"
if (scenario === "quote_only") {
return {
scenario,
label: "Na upit",
detail: "Izrada po mjeri, cijena na upit",
leadTimeDays,
allowCustomization,
quoteSubtitle,
dotClass: "bg-primary",
}
}
if (scenario === "made_to_order") {
return {
scenario,
label: "Po narudžbi",
detail: `Isporuka za ${leadTimeDays} dana`,
leadTimeDays,
allowCustomization,
quoteSubtitle,
dotClass: "bg-amber-500",
}
}
return {
scenario,
label: "Na stanju",
detail: "Isporuka za 24–48h",
leadTimeDays,
allowCustomization,
quoteSubtitle,
dotClass: "bg-emerald-500",
}
}
/** Metadata keys that drive behaviour and are not shown as specs */
const CONTROL_KEYS = new Set([
"sale_scenario",
"lead_time_days",
"allow_customization",
"quote_subtitle",
"badge",
"custom_template",
"hero_image",
])
const SPEC_LABELS: Record<string, string> = {
fabric: "Platno",
fabric_weight: "Platno",
canvas: "Platno",
mast_diameter: "Stub",
mast_construction: "Stub",
ribs_profile: "Krakovi",
uv_protection: "UV zaštita",
water_column: "Vodeni stub",
wind_resistance: "Otpornost na vjetar",
wind_vent: "Lufter",
warranty_years: "Garancija",
opening_mechanism: "Mehanizam otvaranja",
rotation: "Rotacija",
free_space: "Slobodan prostor",
durability: "Izdržljivost",
design_system: "Dizajn",
special_feature: "Posebnost",
origin: "Porijeklo",
weight: "Težina",
motor: "Motorizacija",
profile: "Profil",
drainage: "Odvod vode",
lamellas: "Lamele",
snow_load: "Nosivost snijega",
automation: "Automatika",
construction: "Konstrukcija",
four_seasons: "Cjelogodišnje korištenje",
zip_compatible: "Kompatibilnost",
arms: "Ruke",
tilt_angle: "Nagib",
system: "Sistem",
insulation: "Izolacija",
frame: "Okvir",
branding: "Brendiranje",
options_available: "Dodatna oprema",
}
function prettifyKey(key: string) {
const text = key.replace(/_/g, " ")
return text.charAt(0).toUpperCase() + text.slice(1)
}
/** Human-readable spec rows from product metadata */
export function getProductSpecs(product: HttpTypes.StoreProduct) {
const metadata = (product.metadata ?? {}) as Record<string, unknown>
return Object.entries(metadata)
.filter(
([key, value]) =>
!CONTROL_KEYS.has(key) &&
(typeof value === "string" || typeof value === "number") &&
String(value).trim() !== ""
)
.map(([key, value]) => ({
key,
label: SPEC_LABELS[key] ?? prettifyKey(key),
value: String(value),
}))
}
/**
* Full-width hero image. Uses `metadata.hero_image` when set in Medusa Admin,
* otherwise a neutral placeholder until real photography is uploaded.
*/
export function getProductHeroImage(product: HttpTypes.StoreProduct) {
const custom = product.metadata?.hero_image
if (typeof custom === "string" && custom.trim()) {
return custom
}
return "https://placehold.co/2400x1350/c9ced6/c9ced6"
}
/** Card image for listings, same placeholder logic as the hero */
export function getProductCardImage(title?: string | null) {
const text = encodeURIComponent(title ?? "Suman").replace(/%20/g, "+")
return `https://placehold.co/900x1100/e8ebef/8a919c?text=${text}`
}