first commit

This commit is contained in:
Nermin Karic
2026-11-22 21:49:17 +01:00
commit f5e2fcbf98
693 changed files with 82975 additions and 0 deletions

View File

@@ -0,0 +1,33 @@
# Admin Customizations
You can extend the Medusa Admin to add widgets and new pages. Your customizations interact with API routes to provide merchants with custom functionalities.
> Learn more about Admin Extensions in [this documentation](https://docs.medusajs.com/learn/fundamentals/admin).
## Example: Create a Widget
A widget is a React component that can be injected into an existing page in the admin dashboard.
For example, create the file `src/admin/widgets/product-widget.tsx` with the following content:
```tsx title="src/admin/widgets/product-widget.tsx"
import { defineWidgetConfig } from "@medusajs/admin-sdk"
// The widget
const ProductWidget = () => {
return (
<div>
<h2>Product Widget</h2>
</div>
)
}
// The widget's configurations
export const config = defineWidgetConfig({
zone: "product.details.after",
})
export default ProductWidget
```
This inserts a widget with the text “Product Widget” at the end of a product’s details page.

View File

@@ -0,0 +1,58 @@
# Admin Customizations Translations
The Medusa Admin dashboard supports multiple languages for its interface. Medusa uses [react-i18next](https://react.i18next.com/) to manage translations in the admin dashboard.
To add translations, create JSON translation files for each language under the `src/admin/i18n/json` directory. For example, create the `src/admin/i18n/json/en.json` file with the following content:
```json
{
"brands": {
"title": "Brands",
"description": "Manage your product brands"
},
"done": "Done"
}
```
Then, export the translations in `src/admin/i18n/index.ts`:
```ts
import en from "./json/en.json" with { type: "json" }
export default {
en: {
translation: en,
},
}
```
Finally, use translations in your admin widgets and routes using the `useTranslation` hook:
```tsx
import { defineWidgetConfig } from "@medusajs/admin-sdk"
import { Button, Container, Heading } from "@medusajs/ui"
import { useTranslation } from "react-i18next"
const ProductWidget = () => {
const { t } = useTranslation()
return (
<Container className="p-0">
<div className="flex items-center justify-between px-6 py-4">
<Heading level="h2">{t("brands.title")}</Heading>
<p>{t("brands.description")}</p>
</div>
<div className="flex justify-end px-6 py-4">
<Button variant="primary">{t("done")}</Button>
</div>
</Container>
)
}
export const config = defineWidgetConfig({
zone: "product.details.before",
})
export default ProductWidget
```
Learn more about translating admin extensions in the [Translate Admin Customizations](https://docs.medusajs.com/learn/fundamentals/admin/translations) documentation.

View File

@@ -0,0 +1 @@
export default {}

View File

@@ -0,0 +1,10 @@
import Medusa from "@medusajs/js-sdk"
export const sdk = new Medusa({
baseUrl: import.meta.env.VITE_BACKEND_URL || "/",
debug: import.meta.env.DEV,
auth: {
type: "session",
},
})

View File

@@ -0,0 +1,345 @@
import { defineRouteConfig } from "@medusajs/admin-sdk"
import { ChatBubbleLeftRight } from "@medusajs/icons"
import {
Container,
Heading,
Text,
Table,
Badge,
Button,
Select,
Textarea,
Drawer,
toast,
} from "@medusajs/ui"
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"
import { useState } from "react"
import { sdk } from "../../lib/client"
type Inquiry = {
id: string
name: string
email: string
phone: string
company_name?: string | null
city: string
dimensions?: string | null
message: string
status: "new" | "contacted" | "quote_sent" | "won" | "lost" | "archived"
notes?: string | null
product_id?: string | null
sales_channel_id?: string | null
created_at: string
product?: {
id: string
title: string
thumbnail?: string
}
}
const statusColorMap: Record<
Inquiry["status"],
"blue" | "orange" | "purple" | "green" | "red" | "grey"
> = {
new: "blue",
contacted: "orange",
quote_sent: "purple",
won: "green",
lost: "red",
archived: "grey",
}
const statusLabelMap: Record<Inquiry["status"], string> = {
new: "Novi",
contacted: "Kontaktiran",
quote_sent: "Ponuda poslana",
won: "Prihvaćeno (Won)",
lost: "Odbijeno (Lost)",
archived: "Arhivirano",
}
const InquiriesPage = () => {
const queryClient = useQueryClient()
const [selectedStatus, setSelectedStatus] = useState<string>("all")
const [activeInquiry, setActiveInquiry] = useState<Inquiry | null>(null)
const [drawerOpen, setDrawerOpen] = useState<boolean>(false)
const [editStatus, setEditStatus] = useState<string>("")
const [editNotes, setEditNotes] = useState<string>("")
const { data, isLoading } = useQuery({
queryKey: ["admin-inquiries", selectedStatus],
queryFn: async () => {
const url =
selectedStatus === "all"
? "/admin/inquiries"
: `/admin/inquiries?status=${selectedStatus}`
return await sdk.client.fetch<{ inquiries: Inquiry[]; count: number }>(url)
},
})
const updateMutation = useMutation({
mutationFn: async () => {
if (!activeInquiry) return
return await sdk.client.fetch<{ inquiry: Inquiry }>(
`/admin/inquiries/${activeInquiry.id}`,
{
method: "POST",
body: {
status: editStatus,
notes: editNotes,
},
}
)
},
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ["admin-inquiries"] })
toast.success("Uspjeh", {
description: "Status upita je uspješno ažuriran.",
})
setDrawerOpen(false)
},
onError: (err: any) => {
toast.error("Greška", {
description: err.message || "Neuspjelo ažuriranje upita.",
})
},
})
const openDrawer = (inquiry: Inquiry) => {
setActiveInquiry(inquiry)
setEditStatus(inquiry.status)
setEditNotes(inquiry.notes || "")
setDrawerOpen(true)
}
const inquiries = data?.inquiries || []
return (
<Container className="p-6 space-y-6">
<div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4">
<div>
<Heading level="h1" className="text-2xl font-bold text-ui-fg-base">
Upiti za Ponude (B2B & B2C)
</Heading>
<Text size="small" className="text-ui-fg-muted mt-1">
Pregled i obrada zahtjeva za pergole, tende i suncobrane sa webshopa.
</Text>
</div>
<div className="w-56">
<Select
value={selectedStatus}
onValueChange={(val) => setSelectedStatus(val)}
>
<Select.Trigger>
<Select.Value placeholder="Filter po statusu" />
</Select.Trigger>
<Select.Content>
<Select.Item value="all">Svi upiti</Select.Item>
<Select.Item value="new">Novi upiti</Select.Item>
<Select.Item value="contacted">Kontaktirani</Select.Item>
<Select.Item value="quote_sent">Ponuda poslana</Select.Item>
<Select.Item value="won">Osvojeno (Prihvaćeno)</Select.Item>
<Select.Item value="lost">Odbijeno</Select.Item>
</Select.Content>
</Select>
</div>
</div>
<div className="border border-ui-border-base rounded-lg overflow-hidden">
<Table>
<Table.Header>
<Table.Row>
<Table.HeaderCell>Datum</Table.HeaderCell>
<Table.HeaderCell>Klijent</Table.HeaderCell>
<Table.HeaderCell>Grad</Table.HeaderCell>
<Table.HeaderCell>Proizvod / Dimenzije</Table.HeaderCell>
<Table.HeaderCell>Status</Table.HeaderCell>
<Table.HeaderCell className="text-right">Akcija</Table.HeaderCell>
</Table.Row>
</Table.Header>
<Table.Body>
{isLoading ? (
<Table.Row>
<Table.Cell colSpan={6} className="text-center py-8 text-ui-fg-muted">
Učitavanje upita...
</Table.Cell>
</Table.Row>
) : inquiries.length === 0 ? (
<Table.Row>
<Table.Cell colSpan={6} className="text-center py-8 text-ui-fg-muted">
Nema upita u ovoj kategoriji.
</Table.Cell>
</Table.Row>
) : (
inquiries.map((inq) => (
<Table.Row key={inq.id} className="hover:bg-ui-bg-subtle-hover">
<Table.Cell className="text-xs text-ui-fg-muted whitespace-nowrap">
{new Date(inq.created_at).toLocaleDateString("bs-BA", {
day: "2-digit",
month: "2-digit",
year: "numeric",
})}
</Table.Cell>
<Table.Cell>
<div className="font-semibold text-ui-fg-base">{inq.name}</div>
<div className="text-xs text-ui-fg-muted">
{inq.company_name && `${inq.company_name} • `}
{inq.email} • {inq.phone}
</div>
</Table.Cell>
<Table.Cell className="text-sm text-ui-fg-base">{inq.city}</Table.Cell>
<Table.Cell>
<div className="text-sm font-medium text-ui-fg-base">
{inq.product?.title || inq.product_id || "Opšti upit"}
</div>
{inq.dimensions && (
<div className="text-xs text-ui-fg-muted">
Dimenzije: {inq.dimensions}
</div>
)}
</Table.Cell>
<Table.Cell>
<Badge color={statusColorMap[inq.status]}>
{statusLabelMap[inq.status]}
</Badge>
</Table.Cell>
<Table.Cell className="text-right">
<Button
size="small"
variant="secondary"
onClick={() => openDrawer(inq)}
>
Detalji
</Button>
</Table.Cell>
</Table.Row>
))
)}
</Table.Body>
</Table>
</div>
{/* Drawer za detalje i obradu upita */}
<Drawer open={drawerOpen} onOpenChange={setDrawerOpen}>
<Drawer.Content className="max-w-xl">
<Drawer.Header>
<Drawer.Title>Detalji Upita #{activeInquiry?.id.slice(-6)}</Drawer.Title>
<Drawer.Description>
Pregled podataka klijenta, poruke i promjena statusa obrade.
</Drawer.Description>
</Drawer.Header>
<Drawer.Body className="p-6 space-y-5 overflow-y-auto">
{activeInquiry && (
<>
<div className="grid grid-cols-2 gap-4 p-4 rounded-lg bg-ui-bg-subtle text-sm">
<div>
<span className="text-xs text-ui-fg-muted block">Ime i Prezime</span>
<span className="font-medium text-ui-fg-base">{activeInquiry.name}</span>
</div>
<div>
<span className="text-xs text-ui-fg-muted block">Firma</span>
<span className="font-medium text-ui-fg-base">
{activeInquiry.company_name || "Fizičko lice"}
</span>
</div>
<div>
<span className="text-xs text-ui-fg-muted block">Email</span>
<a
href={`mailto:${activeInquiry.email}`}
className="text-ui-fg-interactive hover:underline"
>
{activeInquiry.email}
</a>
</div>
<div>
<span className="text-xs text-ui-fg-muted block">Telefon</span>
<a
href={`tel:${activeInquiry.phone}`}
className="text-ui-fg-interactive hover:underline"
>
{activeInquiry.phone}
</a>
</div>
<div>
<span className="text-xs text-ui-fg-muted block">Grad</span>
<span className="font-medium text-ui-fg-base">{activeInquiry.city}</span>
</div>
<div>
<span className="text-xs text-ui-fg-muted block">Tražene Dimenzije</span>
<span className="font-medium text-ui-fg-base">
{activeInquiry.dimensions || "Nije specificirano"}
</span>
</div>
</div>
<div>
<Text size="small" weight="plus" className="mb-1 text-ui-fg-base">
Poruka / Zahtjev klijenta:
</Text>
<div className="p-3 rounded-lg border border-ui-border-base bg-ui-bg-base text-sm text-ui-fg-subtle whitespace-pre-wrap">
{activeInquiry.message}
</div>
</div>
<div className="space-y-2 pt-2 border-t border-ui-border-base">
<Text size="small" weight="plus" className="text-ui-fg-base">
Promjena Statusa
</Text>
<Select value={editStatus} onValueChange={(val) => setEditStatus(val)}>
<Select.Trigger>
<Select.Value />
</Select.Trigger>
<Select.Content>
<Select.Item value="new">Novi upit</Select.Item>
<Select.Item value="contacted">Kontaktiran klijent</Select.Item>
<Select.Item value="quote_sent">Zvanična ponuda poslana</Select.Item>
<Select.Item value="won">Osvojeno (Ugovor sklopljen)</Select.Item>
<Select.Item value="lost">Odbijeno / Otkazano</Select.Item>
<Select.Item value="archived">Arhivirano</Select.Item>
</Select.Content>
</Select>
</div>
<div className="space-y-2">
<Text size="small" weight="plus" className="text-ui-fg-base">
Interne Bilješke / Agent Notes
</Text>
<Textarea
value={editNotes}
onChange={(e) => setEditNotes(e.target.value)}
placeholder="Unesite interne bilješke o dogovoru sa klijentom, kalkulaciji cijene itd."
rows={4}
/>
</div>
</>
)}
</Drawer.Body>
<Drawer.Footer>
<Button
variant="secondary"
onClick={() => setDrawerOpen(false)}
>
Odustani
</Button>
<Button
variant="primary"
isLoading={updateMutation.isPending}
disabled={updateMutation.isPending}
onClick={() => updateMutation.mutate()}
>
Sačuvaj Promjene
</Button>
</Drawer.Footer>
</Drawer.Content>
</Drawer>
</Container>
)
}
export const config = defineRouteConfig({
label: "Upiti za ponude",
icon: ChatBubbleLeftRight,
})
export default InquiriesPage

View File

@@ -0,0 +1,27 @@
{
"compilerOptions": {
"target": "ES2020",
"useDefineForClassFields": true,
"lib": ["ES2020", "DOM", "DOM.Iterable"],
"module": "ESNext",
"skipLibCheck": true,
/* Bundler mode */
"moduleResolution": "bundler",
"allowImportingTsExtensions": true,
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true,
"jsx": "react-jsx",
/* Linting */
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"noFallthroughCasesInSwitch": true
},
"include": [
".",
"../../.medusa/types/plugin-augmentations.d.ts"
]
}

1
apps/backend/src/admin/vite-env.d.ts vendored Normal file
View File

@@ -0,0 +1 @@
/// <reference types="vite/client" />

View File

@@ -0,0 +1,157 @@
import { defineWidgetConfig } from "@medusajs/admin-sdk"
import { DetailWidgetProps, HttpTypes } from "@medusajs/framework/types"
import {
Container,
Heading,
Text,
Button,
Input,
Textarea,
Select,
Badge,
toast,
} from "@medusajs/ui"
import { useMutation, useQueryClient } from "@tanstack/react-query"
import { useState } from "react"
import { sdk } from "../lib/client"
type CustomerMetadata = {
pib?: string
company_name?: string
verification_status?: "pending" | "verified" | "rejected"
agent_notes?: string
}
const CustomerCrmWidget = ({ data: customer }: DetailWidgetProps<HttpTypes.AdminCustomer>) => {
const queryClient = useQueryClient()
const metadata = (customer.metadata || {}) as CustomerMetadata
const [companyName, setCompanyName] = useState<string>(metadata.company_name || "")
const [pib, setPib] = useState<string>(metadata.pib || "")
const [status, setStatus] = useState<string>(metadata.verification_status || "pending")
const [notes, setNotes] = useState<string>(metadata.agent_notes || "")
const updateCustomerMutation = useMutation({
mutationFn: async () => {
return await sdk.admin.customer.update(customer.id, {
metadata: {
...customer.metadata,
company_name: companyName,
pib: pib,
verification_status: status,
agent_notes: notes,
},
})
},
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ["customer", customer.id] })
toast.success("Uspjeh", {
description: "B2B CRM podaci kupca su uspješno ažurirani.",
})
},
onError: (err: any) => {
toast.error("Greška", {
description: err.message || "Došlo je do greške pri ažuriranju podataka.",
})
},
})
const getBadgeColor = (st: string) => {
switch (st) {
case "verified":
return "green"
case "rejected":
return "red"
default:
return "orange"
}
}
return (
<Container className="p-6 divide-y divide-ui-border-base">
<div className="flex items-center justify-between pb-4">
<div>
<Heading level="h2">B2B / CRM Podaci o Kupcu</Heading>
<Text size="small" leading="compact" className="text-ui-fg-subtle">
Podaci o pravnom licu, status verifikacije za veleprodajne cijene i interne bilješke agenta.
</Text>
</div>
<Badge color={getBadgeColor(status)} size="small">
{status.toUpperCase()}
</Badge>
</div>
<div className="pt-4 grid grid-cols-2 gap-4">
<div>
<Text size="small" leading="compact" weight="plus" className="mb-1">
Naziv Pravnog Lica / Firme
</Text>
<Input
size="small"
value={companyName}
onChange={(e) => setCompanyName(e.target.value)}
placeholder="Npr. Hotel Dubrovnik d.o.o."
/>
</div>
<div>
<Text size="small" leading="compact" weight="plus" className="mb-1">
PIB / OIB / PDV Broj
</Text>
<Input
size="small"
value={pib}
onChange={(e) => setPib(e.target.value)}
placeholder="Npr. 12345678901"
/>
</div>
<div>
<Text size="small" leading="compact" weight="plus" className="mb-1">
Status B2B Verifikacije
</Text>
<Select value={status} onValueChange={(val) => setStatus(val)} size="small">
<Select.Trigger>
<Select.Value />
</Select.Trigger>
<Select.Content>
<Select.Item value="pending">Na čekanju (Pending)</Select.Item>
<Select.Item value="verified">Verifikovan (B2B Odobren)</Select.Item>
<Select.Item value="rejected">Odbijen (Standardni B2C)</Select.Item>
</Select.Content>
</Select>
</div>
<div className="col-span-2">
<Text size="small" leading="compact" weight="plus" className="mb-1">
Interne Bilješke Agenta (CRM)
</Text>
<Textarea
value={notes}
onChange={(e) => setNotes(e.target.value)}
rows={3}
placeholder="Unesite dogovoreni rabat, kontakt podatke voditelja terase, zahtjeve za brendiranje platna suncobrana..."
/>
</div>
<div className="col-span-2 flex justify-end pt-2">
<Button
size="small"
isLoading={updateCustomerMutation.isPending}
disabled={updateCustomerMutation.isPending}
onClick={() => updateCustomerMutation.mutate()}
>
Sačuvaj CRM Podatke
</Button>
</div>
</div>
</Container>
)
}
export const config = defineWidgetConfig({
zone: "customer.details",
})
export default CustomerCrmWidget

View File

@@ -0,0 +1,228 @@
import { defineWidgetConfig } from "@medusajs/admin-sdk"
import { DetailWidgetProps, HttpTypes } from "@medusajs/framework/types"
import {
Container,
Heading,
Text,
Button,
Select,
Input,
Switch,
Badge,
toast,
} from "@medusajs/ui"
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query"
import { useState } from "react"
import { sdk } from "../lib/client"
type ProductScenarioMetadata = {
sale_scenario?: "in_stock" | "made_to_order" | "quote_only"
lead_time_days?: number
allow_customization?: boolean
quote_subtitle?: string
}
const ProductInquiryWidget = ({
data: product,
}: DetailWidgetProps<HttpTypes.AdminProduct>) => {
const queryClient = useQueryClient()
const metadata = (product.metadata || {}) as ProductScenarioMetadata
const [scenario, setScenario] = useState<string>(
metadata.sale_scenario || "in_stock"
)
const [leadTime, setLeadTime] = useState<string>(
String(metadata.lead_time_days || "14")
)
const [allowCustomization, setAllowCustomization] = useState<boolean>(
Boolean(metadata.allow_customization)
)
const [quoteSubtitle, setQuoteSubtitle] = useState<string>(
metadata.quote_subtitle || "Izrada po mjeri sa montažom"
)
// Fetch inquiries for this product
const { data: inquiriesData, isLoading: inquiriesLoading } = useQuery({
queryKey: ["product-inquiries", product.id],
queryFn: async () => {
const response = await sdk.client.fetch<{
inquiries: Array<{ id: string; status: string; name: string; city: string; created_at: string }>
count: number
}>(`/admin/inquiries?product_id=${product.id}`)
return response
},
})
const updateScenarioMutation = useMutation({
mutationFn: async () => {
return await sdk.admin.product.update(product.id, {
metadata: {
...product.metadata,
sale_scenario: scenario,
lead_time_days: scenario === "made_to_order" ? Number(leadTime) || 14 : undefined,
allow_customization: allowCustomization,
quote_subtitle: scenario === "quote_only" ? quoteSubtitle : undefined,
},
})
},
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ["product", product.id] })
toast.success("Uspješno spremljeno", {
description: "Prodajni scenario i postavke upita su ažurirani.",
})
},
onError: (err: any) => {
toast.error("Greška", {
description: err.message || "Neuspjelo ažuriranje scenarija.",
})
},
})
const inquiryCount = inquiriesData?.count || 0
return (
<Container className="p-6 divide-y">
<div className="pb-4 flex items-center justify-between">
<div>
<Heading level="h2" className="text-lg font-semibold text-ui-fg-base">
Prodajni Scenario & Upiti (Suman)
</Heading>
<Text size="small" className="text-ui-fg-muted mt-1">
Konfigurišite da li se proizvod kupuje direktno, po narudžbi sa rokom izrade, ili isključivo na upit.
</Text>
</div>
<div className="flex items-center gap-2">
{scenario === "quote_only" && (
<Badge color="orange">Isključivo na upit</Badge>
)}
{scenario === "made_to_order" && (
<Badge color="blue">Po narudžbi ({leadTime} dana)</Badge>
)}
{scenario === "in_stock" && (
<Badge color="green">Sa lagera</Badge>
)}
</div>
</div>
<div className="pt-4 space-y-4">
<div className="grid grid-cols-1 md:grid-cols-2 gap-4">
<div>
<Text size="small" weight="plus" className="mb-1.5 text-ui-fg-subtle">
Način Prodaje
</Text>
<Select
value={scenario}
onValueChange={(val) => setScenario(val)}
>
<Select.Trigger>
<Select.Value placeholder="Odaberite način prodaje" />
</Select.Trigger>
<Select.Content>
<Select.Item value="in_stock">
Sa lagera (Standardna online kupovina)
</Select.Item>
<Select.Item value="made_to_order">
Po narudžbi (Kupovina uz rok isporuke)
</Select.Item>
<Select.Item value="quote_only">
Isključivo na upit (Tende & Pergole)
</Select.Item>
</Select.Content>
</Select>
</div>
{scenario === "made_to_order" && (
<div>
<Text size="small" weight="plus" className="mb-1.5 text-ui-fg-subtle">
Rok Isporuke (dana)
</Text>
<Input
type="number"
value={leadTime}
onChange={(e) => setLeadTime(e.target.value)}
placeholder="npr. 14"
/>
</div>
)}
{scenario === "quote_only" && (
<div>
<Text size="small" weight="plus" className="mb-1.5 text-ui-fg-subtle">
Podnaslov za Formu Upita
</Text>
<Input
value={quoteSubtitle}
onChange={(e) => setQuoteSubtitle(e.target.value)}
placeholder="npr. Izrada po mjeri sa montažom"
/>
</div>
)}
</div>
<div className="flex items-center justify-between pt-2 border-t border-ui-border-base">
<div>
<Text size="small" weight="plus" className="text-ui-fg-base">
Omogući 2D/3D Konfigurator
</Text>
<Text size="xsmall" className="text-ui-fg-muted">
Prikazuje interaktivni odabir platna, konstrukcije i dodataka na stranici proizvoda
</Text>
</div>
<Switch
checked={allowCustomization}
onCheckedChange={setAllowCustomization}
/>
</div>
{/* Upiti za ovaj proizvod */}
<div className="pt-3 border-t border-ui-border-base">
<div className="flex items-center justify-between mb-2">
<Text size="small" weight="plus" className="text-ui-fg-base">
Pristigli Upiti za ovaj proizvod
</Text>
<Badge color={inquiryCount > 0 ? "purple" : "grey"}>
{inquiryCount} {inquiryCount === 1 ? "upit" : "upita"}
</Badge>
</div>
{inquiryCount > 0 && inquiriesData?.inquiries && (
<div className="space-y-1.5 max-h-36 overflow-y-auto">
{inquiriesData.inquiries.slice(0, 3).map((inq) => (
<div
key={inq.id}
className="flex items-center justify-between p-2 rounded bg-ui-bg-subtle text-xs"
>
<div>
<span className="font-semibold text-ui-fg-base">{inq.name}</span>
<span className="text-ui-fg-muted ml-2">({inq.city})</span>
</div>
<Badge size="2xsmall" color={inq.status === "new" ? "blue" : "grey"}>
{inq.status}
</Badge>
</div>
))}
</div>
)}
</div>
<div className="flex justify-end pt-2">
<Button
size="small"
variant="primary"
isLoading={updateScenarioMutation.isPending}
disabled={updateScenarioMutation.isPending}
onClick={() => updateScenarioMutation.mutate()}
>
Sačuvaj Postavke Scenarija
</Button>
</div>
</div>
</Container>
)
}
export const config = defineWidgetConfig({
zone: "product.details.after",
})
export default ProductInquiryWidget

View File

@@ -0,0 +1,135 @@
# Custom API Routes
An API Route is a REST API endpoint.
An API Route is created in a TypeScript or JavaScript file under the `/src/api` directory of your Medusa application. The file’s name must be `route.ts` or `route.js`.
> Learn more about API Routes in [this documentation](https://docs.medusajs.com/learn/fundamentals/api-routes)
For example, to create a `GET` API Route at `/store/hello-world`, create the file `src/api/store/hello-world/route.ts` with the following content:
```ts
import type { MedusaRequest, MedusaResponse } from "@medusajs/framework/http";
export async function GET(req: MedusaRequest, res: MedusaResponse) {
res.json({
message: "Hello world!",
});
}
```
## Supported HTTP methods
The file based routing supports the following HTTP methods:
- GET
- POST
- PUT
- PATCH
- DELETE
- OPTIONS
- HEAD
You can define a handler for each of these methods by exporting a function with the name of the method in the paths `route.ts` file.
For example:
```ts
import type { MedusaRequest, MedusaResponse } from "@medusajs/framework/http";
export async function GET(req: MedusaRequest, res: MedusaResponse) {
// Handle GET requests
}
export async function POST(req: MedusaRequest, res: MedusaResponse) {
// Handle POST requests
}
export async function PUT(req: MedusaRequest, res: MedusaResponse) {
// Handle PUT requests
}
```
## Parameters
To create an API route that accepts a path parameter, create a directory within the route's path whose name is of the format `[param]`.
For example, if you want to define a route that takes a `productId` parameter, you can do so by creating a file called `/api/products/[productId]/route.ts`:
```ts
import type {
MedusaRequest,
MedusaResponse,
} from "@medusajs/framework/http"
export async function GET(req: MedusaRequest, res: MedusaResponse) {
const { productId } = req.params;
res.json({
message: `You're looking for product ${productId}`
})
}
```
To create an API route that accepts multiple path parameters, create within the file's path multiple directories whose names are of the format `[param]`.
For example, if you want to define a route that takes both a `productId` and a `variantId` parameter, you can do so by creating a file called `/api/products/[productId]/variants/[variantId]/route.ts`.
## Using the container
The Medusa container is available on `req.scope`. Use it to access modules' main services and other registered resources:
```ts
import type {
MedusaRequest,
MedusaResponse,
} from "@medusajs/framework/http"
export const GET = async (
req: MedusaRequest,
res: MedusaResponse
) => {
const productModuleService = req.scope.resolve("product")
const [, count] = await productModuleService.listAndCount()
res.json({
count,
})
}
```
## Middleware
You can apply middleware to your routes by creating a file called `/api/middlewares.ts`. This file must export a configuration object with what middleware you want to apply to which routes.
For example, if you want to apply a custom middleware function to the `/store/custom` route, you can do so by adding the following to your `/api/middlewares.ts` file:
```ts
import { defineMiddlewares } from "@medusajs/framework/http"
import type {
MedusaRequest,
MedusaResponse,
MedusaNextFunction,
} from "@medusajs/framework/http";
async function logger(
req: MedusaRequest,
res: MedusaResponse,
next: MedusaNextFunction
) {
console.log("Request received");
next();
}
export default defineMiddlewares({
routes: [
{
matcher: "/store/custom",
middlewares: [logger],
},
],
})
```
The `matcher` property can be either a string or a regular expression. The `middlewares` property accepts an array of middleware functions.

View File

@@ -0,0 +1,8 @@
import { MedusaRequest, MedusaResponse } from "@medusajs/framework/http";
export async function GET(
req: MedusaRequest,
res: MedusaResponse
) {
res.sendStatus(200);
}

View File

@@ -0,0 +1,64 @@
import { AuthenticatedMedusaRequest, MedusaResponse } from "@medusajs/framework/http"
import { ContainerRegistrationKeys, MedusaError } from "@medusajs/framework/utils"
import { updateInquiryWorkflow } from "../../../../workflows/inquiry"
import { AdminUpdateInquiryType } from "../../../store/inquiries/validators"
export async function GET(
req: AuthenticatedMedusaRequest,
res: MedusaResponse
) {
const { id } = req.params
const query = req.scope.resolve(ContainerRegistrationKeys.QUERY)
const {
data: [inquiry],
} = await query.graph({
entity: "inquiry",
fields: [
"id",
"name",
"email",
"phone",
"company_name",
"city",
"dimensions",
"message",
"status",
"notes",
"product_id",
"sales_channel_id",
"metadata",
"created_at",
"updated_at",
"product.*",
"sales_channel.*",
],
filters: { id },
})
if (!inquiry) {
throw new MedusaError(
MedusaError.Types.NOT_FOUND,
`Inquiry with id ${id} not found`
)
}
res.json({ inquiry })
}
export async function POST(
req: AuthenticatedMedusaRequest<AdminUpdateInquiryType>,
res: MedusaResponse
) {
const { id } = req.params
const input = (req.validatedBody || req.body) as AdminUpdateInquiryType
const { result } = await updateInquiryWorkflow(req.scope).run({
input: {
id,
...input,
},
})
res.json({ inquiry: result })
}

View File

@@ -0,0 +1,50 @@
import { AuthenticatedMedusaRequest, MedusaResponse } from "@medusajs/framework/http"
import { ContainerRegistrationKeys } from "@medusajs/framework/utils"
export async function GET(
req: AuthenticatedMedusaRequest,
res: MedusaResponse
) {
const query = req.scope.resolve(ContainerRegistrationKeys.QUERY)
const filters: Record<string, any> = {}
if (req.query.status) {
filters.status = req.query.status
}
if (req.query.sales_channel_id) {
filters.sales_channel_id = req.query.sales_channel_id
}
if (req.query.product_id) {
filters.product_id = req.query.product_id
}
const { data: inquiries } = await query.graph({
entity: "inquiry",
fields: [
"id",
"name",
"email",
"phone",
"company_name",
"city",
"dimensions",
"message",
"status",
"notes",
"product_id",
"sales_channel_id",
"metadata",
"created_at",
"updated_at",
"product.*",
"sales_channel.*",
],
filters,
})
res.json({
inquiries,
count: inquiries.length,
})
}

View File

@@ -0,0 +1,97 @@
import {
configureStoreSearch,
defineMiddlewares,
MedusaRequest,
AuthenticatedMedusaRequest,
MedusaResponse,
MedusaNextFunction,
validateAndTransformBody,
} from "@medusajs/framework/http"
import { ContainerRegistrationKeys, MedusaError } from "@medusajs/framework/utils"
import { StoreCreateInquiry, AdminUpdateInquiry } from "./store/inquiries/validators"
/**
* Middleware koji provjerava da li admin korisnik ima definisan sales_channel_id
* u metadata polju (Regionalni Admin) i nameće izolaciju narudžbi za taj prodajni kanal.
*/
async function enforceAdminSalesChannelIsolation(
req: MedusaRequest,
res: MedusaResponse,
next: MedusaNextFunction
) {
const userId = (req as AuthenticatedMedusaRequest).auth_context?.actor_id
if (!userId) {
return next()
}
const query = req.scope.resolve(ContainerRegistrationKeys.QUERY)
// Učitavanje korisničkih metadata podataka
const {
data: [user],
} = await query.graph({
entity: "user",
fields: ["id", "metadata"],
filters: { id: userId },
})
const restrictedChannelId = user?.metadata?.sales_channel_id as string | undefined
if (restrictedChannelId) {
// 1. Zahtjev za listu narudžbi (GET /admin/orders)
if (req.method === "GET" && !req.params.id) {
req.query.sales_channel_id = [restrictedChannelId]
}
// 2. Zahtjev za pojedinačnu narudžbu (GET /admin/orders/:id)
if (req.method === "GET" && req.params.id) {
const {
data: [order],
} = await query.graph({
entity: "order",
fields: ["id", "sales_channel_id"],
filters: { id: req.params.id },
})
if (order && order.sales_channel_id !== restrictedChannelId) {
throw new MedusaError(
MedusaError.Types.NOT_ALLOWED,
"Zabranjen pristup: Nemate ovlaštenje za pregled narudžbi iz ovog prodajnog kanala."
)
}
}
}
return next()
}
export default defineMiddlewares({
routes: [
{
method: ["POST"],
matcher: "/store/search",
middlewares: [
configureStoreSearch({
allowed_indexes: {
product: true,
},
}),
],
},
{
method: ["GET"],
matcher: "/admin/orders*",
middlewares: [enforceAdminSalesChannelIsolation],
},
{
method: ["POST"],
matcher: "/store/inquiries",
middlewares: [validateAndTransformBody(StoreCreateInquiry)],
},
{
method: ["POST"],
matcher: "/admin/inquiries/:id",
middlewares: [validateAndTransformBody(AdminUpdateInquiry)],
},
],
})

View File

@@ -0,0 +1,8 @@
import { MedusaRequest, MedusaResponse } from "@medusajs/framework/http";
export async function GET(
req: MedusaRequest,
res: MedusaResponse
) {
res.sendStatus(200);
}

View File

@@ -0,0 +1,17 @@
import { MedusaRequest, MedusaResponse } from "@medusajs/framework/http"
import { createInquiryWorkflow } from "../../../workflows/inquiry"
import { StoreCreateInquiryType } from "./validators"
export async function POST(
req: MedusaRequest<StoreCreateInquiryType>,
res: MedusaResponse
) {
const input = (req.validatedBody || req.body) as StoreCreateInquiryType
const { result } = await createInquiryWorkflow(req.scope).run({
input,
})
res.status(201).json({ inquiry: result })
}

View File

@@ -0,0 +1,26 @@
import { z } from "@medusajs/framework/zod"
export const StoreCreateInquiry = z.object({
name: z.string().min(2),
email: z.string().email(),
phone: z.string().min(5),
company_name: z.string().nullish(),
city: z.string().min(2),
dimensions: z.string().nullish(),
message: z.string().min(3),
product_id: z.string().nullish(),
sales_channel_id: z.string().nullish(),
metadata: z.record(z.string(), z.unknown()).nullish(),
})
export type StoreCreateInquiryType = z.infer<typeof StoreCreateInquiry>
export const AdminUpdateInquiry = z.object({
status: z
.enum(["new", "contacted", "quote_sent", "won", "lost", "archived"])
.optional(),
notes: z.string().nullish(),
metadata: z.record(z.string(), z.unknown()).nullish(),
})
export type AdminUpdateInquiryType = z.infer<typeof AdminUpdateInquiry>

View File

@@ -0,0 +1,38 @@
# Custom scheduled jobs
A scheduled job is a function executed at a specified interval of time in the background of your Medusa application.
> Learn more about scheduled jobs in [this documentation](https://docs.medusajs.com/learn/fundamentals/scheduled-jobs).
A scheduled job is created in a TypeScript or JavaScript file under the `src/jobs` directory.
For example, create the file `src/jobs/hello-world.ts` with the following content:
```ts
import {
MedusaContainer
} from "@medusajs/framework/types";
export default async function myCustomJob(container: MedusaContainer) {
const productService = container.resolve("product")
const products = await productService.listAndCountProducts();
// Do something with the products
}
export const config = {
name: "daily-product-report",
schedule: "0 0 * * *", // Every day at midnight
};
```
A scheduled job file must export:
- The function to be executed whenever it’s time to run the scheduled job.
- A configuration object defining the job. It has three properties:
- `name`: a unique name for the job.
- `schedule`: a [cron expression](https://crontab.guru/).
- `numberOfExecutions`: an optional integer, specifying how many times the job will execute before being removed
The `handler` is a function that accepts one parameter, `container`, which is a `MedusaContainer` instance used to resolve services.

View File

@@ -0,0 +1,24 @@
/**
* Store policy values kept in each region's `metadata`. The storefront renders
* the shipping/returns pages and structured data from these keys, and merchants
* can change them in Settings → Regions → Metadata.
*/
export type RegionStorePolicies = {
return_window_days: number;
free_returns: boolean;
shipping_rate: number;
handling_days_min: number;
handling_days_max: number;
transit_days_min: number;
transit_days_max: number;
};
export const DEFAULT_REGION_STORE_POLICIES: RegionStorePolicies = {
return_window_days: 30,
free_returns: false,
shipping_rate: 10,
handling_days_min: 0,
handling_days_max: 1,
transit_days_min: 2,
transit_days_max: 3,
};

View File

@@ -0,0 +1,26 @@
# Module Links
A module link forms an association between two data models of different modules, while maintaining module isolation.
> Learn more about links in [this documentation](https://docs.medusajs.com/learn/fundamentals/module-links)
For example:
```ts
import BlogModule from "../modules/blog"
import ProductModule from "@medusajs/medusa/product"
import { defineLink } from "@medusajs/framework/utils"
export default defineLink(
ProductModule.linkable.product,
BlogModule.linkable.post
)
```
This defines a link between the Product Module's `product` data model and the Blog Module (custom module)'s `post` data model.
Then, in the Medusa application, run the following command to sync the links to the database:
```bash
npx medusa db:migrate
```

View File

@@ -0,0 +1,9 @@
import { defineLink } from "@medusajs/framework/utils"
import InquiryModule from "../modules/inquiry"
import ProductModule from "@medusajs/medusa/product"
export default defineLink(
InquiryModule.linkable.inquiry,
ProductModule.linkable.product
)

View File

@@ -0,0 +1,9 @@
import { defineLink } from "@medusajs/framework/utils"
import InquiryModule from "../modules/inquiry"
import SalesChannelModule from "@medusajs/medusa/sales-channel"
export default defineLink(
InquiryModule.linkable.inquiry,
SalesChannelModule.linkable.salesChannel
)

View File

@@ -0,0 +1,841 @@
import { MedusaContainer } from "@medusajs/framework";
import { DEFAULT_REGION_STORE_POLICIES } from "../lib/region-store-policies";
import {
ContainerRegistrationKeys,
ModuleRegistrationName,
Modules,
ProductStatus,
} from "@medusajs/framework/utils";
import {
createApiKeysWorkflow,
createCollectionsWorkflow,
createInventoryLevelsWorkflow,
createProductCategoriesWorkflow,
createProductOptionsWorkflow,
createProductsWorkflow,
createRegionsWorkflow,
createSalesChannelsWorkflow,
createShippingOptionsWorkflow,
createShippingProfilesWorkflow,
createStockLocationsWorkflow,
createStoresWorkflow,
createTaxRegionsWorkflow,
linkSalesChannelsToApiKeyWorkflow,
linkSalesChannelsToStockLocationWorkflow,
} from "@medusajs/medusa/core-flows";
export default async function initial_data_seed({
container,
}: {
container: MedusaContainer;
}) {
const logger = container.resolve(ContainerRegistrationKeys.LOGGER);
const link = container.resolve(ContainerRegistrationKeys.LINK);
const query = container.resolve(ContainerRegistrationKeys.QUERY);
const fulfillmentModuleService = container.resolve(
ModuleRegistrationName.FULFILLMENT
);
const countries = ["gb", "de", "dk", "se", "fr", "es", "it"];
logger.info("Seeding store data...");
const {
result: [defaultSalesChannel],
} = await createSalesChannelsWorkflow(container).run({
input: {
salesChannelsData: [
{
name: "Default Sales Channel",
description: "Created by Medusa",
},
],
},
});
const {
result: [publishableApiKey],
} = await createApiKeysWorkflow(container).run({
input: {
api_keys: [
{
title: "Default Publishable API Key",
type: "publishable",
created_by: "",
},
],
},
});
await linkSalesChannelsToApiKeyWorkflow(container).run({
input: {
id: publishableApiKey.id,
add: [defaultSalesChannel.id],
},
});
const {
result: [store],
} = await createStoresWorkflow(container).run({
input: {
stores: [
{
name: "Default Store",
supported_currencies: [
{
currency_code: "eur",
is_default: true,
},
{
currency_code: "usd",
is_default: false,
},
],
default_sales_channel_id: defaultSalesChannel.id,
},
],
},
});
logger.info("Seeding region data...");
const { result: regionResult } = await createRegionsWorkflow(container).run({
input: {
regions: [
{
name: "Europe",
currency_code: "eur",
countries,
payment_providers: ["pp_system_default"],
metadata: DEFAULT_REGION_STORE_POLICIES,
},
],
},
});
const region = regionResult[0];
logger.info("Finished seeding regions.");
logger.info("Seeding tax regions...");
await createTaxRegionsWorkflow(container).run({
input: countries.map((country_code) => ({
country_code,
provider_id: "tp_system",
})),
});
logger.info("Finished seeding tax regions.");
logger.info("Seeding stock location data...");
const { result: stockLocationResult } = await createStockLocationsWorkflow(
container
).run({
input: {
locations: [
{
name: "European Warehouse",
address: {
city: "Copenhagen",
country_code: "DK",
address_1: "",
},
},
],
},
});
const stockLocation = stockLocationResult[0];
await link.create({
[Modules.STOCK_LOCATION]: {
stock_location_id: stockLocation.id,
},
[Modules.FULFILLMENT]: {
fulfillment_provider_id: "manual_manual",
},
});
logger.info("Seeding fulfillment data...");
// This is created by a migration script in core.
const { data: shippingProfileResult } = await query.graph({
entity: "shipping_profile",
fields: ["id"],
});
const shippingProfile = shippingProfileResult[0];
const fulfillmentSet = await fulfillmentModuleService.createFulfillmentSets({
name: "European Warehouse delivery",
type: "shipping",
service_zones: [
{
name: "Europe",
geo_zones: [
{
country_code: "gb",
type: "country",
},
{
country_code: "de",
type: "country",
},
{
country_code: "dk",
type: "country",
},
{
country_code: "se",
type: "country",
},
{
country_code: "fr",
type: "country",
},
{
country_code: "es",
type: "country",
},
{
country_code: "it",
type: "country",
},
],
},
],
});
await link.create({
[Modules.STOCK_LOCATION]: {
stock_location_id: stockLocation.id,
},
[Modules.FULFILLMENT]: {
fulfillment_set_id: fulfillmentSet.id,
},
});
await createShippingOptionsWorkflow(container).run({
input: [
{
name: "Standard Shipping",
price_type: "flat",
provider_id: "manual_manual",
service_zone_id: fulfillmentSet.service_zones[0].id,
shipping_profile_id: shippingProfile.id,
type: {
label: "Standard",
description: "Ship in 2-3 days.",
code: "standard",
},
prices: [
{
currency_code: "usd",
amount: 10,
},
{
currency_code: "eur",
amount: 10,
},
{
region_id: region.id,
amount: 10,
},
],
rules: [
{
attribute: "enabled_in_store",
value: "true",
operator: "eq",
},
{
attribute: "is_return",
value: "false",
operator: "eq",
},
],
},
{
name: "Express Shipping",
price_type: "flat",
provider_id: "manual_manual",
service_zone_id: fulfillmentSet.service_zones[0].id,
shipping_profile_id: shippingProfile.id,
type: {
label: "Express",
description: "Ship in 24 hours.",
code: "express",
},
prices: [
{
currency_code: "usd",
amount: 10,
},
{
currency_code: "eur",
amount: 10,
},
{
region_id: region.id,
amount: 10,
},
],
rules: [
{
attribute: "enabled_in_store",
value: "true",
operator: "eq",
},
{
attribute: "is_return",
value: "false",
operator: "eq",
},
],
},
],
});
logger.info("Finished seeding fulfillment data.");
await linkSalesChannelsToStockLocationWorkflow(container).run({
input: {
id: stockLocation.id,
add: [defaultSalesChannel.id],
},
});
logger.info("Finished seeding stock location data.");
logger.info("Seeding product data...");
const { result: categoryResult } = await createProductCategoriesWorkflow(
container
).run({
input: {
product_categories: [
{
name: "Shirts",
is_active: true,
},
{
name: "Sweatshirts",
is_active: true,
},
{
name: "Pants",
is_active: true,
},
{
name: "Merch",
is_active: true,
},
],
},
});
const { result: productOptionsResult } = await createProductOptionsWorkflow(
container
).run({
input: {
product_options: [
{
title: "Size",
values: ["S", "M", "L", "XL"],
},
{
title: "Color",
values: ["Black", "White"],
},
],
},
});
const sizeOption = productOptionsResult.find((o) => o.title === "Size")!;
const colorOption = productOptionsResult.find((o) => o.title === "Color")!;
await createProductsWorkflow(container).run({
input: {
products: [
{
title: "Medusa T-Shirt",
category_ids: [
categoryResult.find((cat) => cat.name === "Shirts")!.id,
],
description:
"Reimagine the feeling of a classic T-shirt. With our cotton T-shirts, everyday essentials no longer have to be ordinary.",
handle: "t-shirt",
weight: 400,
status: ProductStatus.PUBLISHED,
shipping_profile_id: shippingProfile.id,
images: [
{
url: "https://medusa-public-images.s3.eu-west-1.amazonaws.com/tee-black-front.png",
},
{
url: "https://medusa-public-images.s3.eu-west-1.amazonaws.com/tee-black-back.png",
},
{
url: "https://medusa-public-images.s3.eu-west-1.amazonaws.com/tee-white-front.png",
},
{
url: "https://medusa-public-images.s3.eu-west-1.amazonaws.com/tee-white-back.png",
},
],
options: [
{ id: sizeOption.id },
{ id: colorOption.id },
],
variants: [
{
title: "S / Black",
sku: "SHIRT-S-BLACK",
options: {
Size: "S",
Color: "Black",
},
prices: [
{
amount: 10,
currency_code: "eur",
},
{
amount: 15,
currency_code: "usd",
},
],
},
{
title: "S / White",
sku: "SHIRT-S-WHITE",
options: {
Size: "S",
Color: "White",
},
prices: [
{
amount: 10,
currency_code: "eur",
},
{
amount: 15,
currency_code: "usd",
},
],
},
{
title: "M / Black",
sku: "SHIRT-M-BLACK",
options: {
Size: "M",
Color: "Black",
},
prices: [
{
amount: 10,
currency_code: "eur",
},
{
amount: 15,
currency_code: "usd",
},
],
},
{
title: "M / White",
sku: "SHIRT-M-WHITE",
options: {
Size: "M",
Color: "White",
},
prices: [
{
amount: 10,
currency_code: "eur",
},
{
amount: 15,
currency_code: "usd",
},
],
},
{
title: "L / Black",
sku: "SHIRT-L-BLACK",
options: {
Size: "L",
Color: "Black",
},
prices: [
{
amount: 10,
currency_code: "eur",
},
{
amount: 15,
currency_code: "usd",
},
],
},
{
title: "L / White",
sku: "SHIRT-L-WHITE",
options: {
Size: "L",
Color: "White",
},
prices: [
{
amount: 10,
currency_code: "eur",
},
{
amount: 15,
currency_code: "usd",
},
],
},
{
title: "XL / Black",
sku: "SHIRT-XL-BLACK",
options: {
Size: "XL",
Color: "Black",
},
prices: [
{
amount: 10,
currency_code: "eur",
},
{
amount: 15,
currency_code: "usd",
},
],
},
{
title: "XL / White",
sku: "SHIRT-XL-WHITE",
options: {
Size: "XL",
Color: "White",
},
prices: [
{
amount: 10,
currency_code: "eur",
},
{
amount: 15,
currency_code: "usd",
},
],
},
],
sales_channels: [
{
id: defaultSalesChannel.id,
},
],
},
{
title: "Medusa Sweatshirt",
category_ids: [
categoryResult.find((cat) => cat.name === "Sweatshirts")!.id,
],
description:
"Reimagine the feeling of a classic sweatshirt. With our cotton sweatshirt, everyday essentials no longer have to be ordinary.",
handle: "sweatshirt",
weight: 400,
status: ProductStatus.PUBLISHED,
shipping_profile_id: shippingProfile.id,
images: [
{
url: "https://medusa-public-images.s3.eu-west-1.amazonaws.com/sweatshirt-vintage-front.png",
},
{
url: "https://medusa-public-images.s3.eu-west-1.amazonaws.com/sweatshirt-vintage-back.png",
},
],
options: [{ id: sizeOption.id }],
variants: [
{
title: "S",
sku: "SWEATSHIRT-S",
options: {
Size: "S",
},
prices: [
{
amount: 10,
currency_code: "eur",
},
{
amount: 15,
currency_code: "usd",
},
],
},
{
title: "M",
sku: "SWEATSHIRT-M",
options: {
Size: "M",
},
prices: [
{
amount: 10,
currency_code: "eur",
},
{
amount: 15,
currency_code: "usd",
},
],
},
{
title: "L",
sku: "SWEATSHIRT-L",
options: {
Size: "L",
},
prices: [
{
amount: 10,
currency_code: "eur",
},
{
amount: 15,
currency_code: "usd",
},
],
},
{
title: "XL",
sku: "SWEATSHIRT-XL",
options: {
Size: "XL",
},
prices: [
{
amount: 10,
currency_code: "eur",
},
{
amount: 15,
currency_code: "usd",
},
],
},
],
sales_channels: [
{
id: defaultSalesChannel.id,
},
],
},
{
title: "Medusa Sweatpants",
category_ids: [
categoryResult.find((cat) => cat.name === "Pants")!.id,
],
description:
"Reimagine the feeling of classic sweatpants. With our cotton sweatpants, everyday essentials no longer have to be ordinary.",
handle: "sweatpants",
weight: 400,
status: ProductStatus.PUBLISHED,
shipping_profile_id: shippingProfile.id,
images: [
{
url: "https://medusa-public-images.s3.eu-west-1.amazonaws.com/sweatpants-gray-front.png",
},
{
url: "https://medusa-public-images.s3.eu-west-1.amazonaws.com/sweatpants-gray-back.png",
},
],
options: [{ id: sizeOption.id }],
variants: [
{
title: "S",
sku: "SWEATPANTS-S",
options: {
Size: "S",
},
prices: [
{
amount: 10,
currency_code: "eur",
},
{
amount: 15,
currency_code: "usd",
},
],
},
{
title: "M",
sku: "SWEATPANTS-M",
options: {
Size: "M",
},
prices: [
{
amount: 10,
currency_code: "eur",
},
{
amount: 15,
currency_code: "usd",
},
],
},
{
title: "L",
sku: "SWEATPANTS-L",
options: {
Size: "L",
},
prices: [
{
amount: 10,
currency_code: "eur",
},
{
amount: 15,
currency_code: "usd",
},
],
},
{
title: "XL",
sku: "SWEATPANTS-XL",
options: {
Size: "XL",
},
prices: [
{
amount: 10,
currency_code: "eur",
},
{
amount: 15,
currency_code: "usd",
},
],
},
],
sales_channels: [
{
id: defaultSalesChannel.id,
},
],
},
{
title: "Medusa Shorts",
category_ids: [
categoryResult.find((cat) => cat.name === "Merch")!.id,
],
description:
"Reimagine the feeling of classic shorts. With our cotton shorts, everyday essentials no longer have to be ordinary.",
handle: "shorts",
weight: 400,
status: ProductStatus.PUBLISHED,
shipping_profile_id: shippingProfile.id,
images: [
{
url: "https://medusa-public-images.s3.eu-west-1.amazonaws.com/shorts-vintage-front.png",
},
{
url: "https://medusa-public-images.s3.eu-west-1.amazonaws.com/shorts-vintage-back.png",
},
],
options: [{ id: sizeOption.id }],
variants: [
{
title: "S",
sku: "SHORTS-S",
options: {
Size: "S",
},
prices: [
{
amount: 10,
currency_code: "eur",
},
{
amount: 15,
currency_code: "usd",
},
],
},
{
title: "M",
sku: "SHORTS-M",
options: {
Size: "M",
},
prices: [
{
amount: 10,
currency_code: "eur",
},
{
amount: 15,
currency_code: "usd",
},
],
},
{
title: "L",
sku: "SHORTS-L",
options: {
Size: "L",
},
prices: [
{
amount: 10,
currency_code: "eur",
},
{
amount: 15,
currency_code: "usd",
},
],
},
{
title: "XL",
sku: "SHORTS-XL",
options: {
Size: "XL",
},
prices: [
{
amount: 10,
currency_code: "eur",
},
{
amount: 15,
currency_code: "usd",
},
],
},
],
sales_channels: [
{
id: defaultSalesChannel.id,
},
],
},
],
},
});
logger.info("Finished seeding product data.");
logger.info("Seeding inventory levels.");
const { data: inventoryItems } = await query.graph({
entity: "inventory_item",
fields: ["id"],
});
await createInventoryLevelsWorkflow(container).run({
input: {
inventory_levels: inventoryItems.map((item) => ({
location_id: stockLocation.id,
stocked_quantity: 1000000,
inventory_item_id: item.id,
})),
},
});
logger.info("Finished seeding inventory levels data.");
}

View File

@@ -0,0 +1,32 @@
import { MedusaContainer } from "@medusajs/framework";
import { ContainerRegistrationKeys } from "@medusajs/framework/utils";
import { updateRegionsWorkflow } from "@medusajs/medusa/core-flows";
import { DEFAULT_REGION_STORE_POLICIES } from "../lib/region-store-policies";
export default async function regionStorePolicies({ container }: { container: MedusaContainer }) {
const logger = container.resolve(ContainerRegistrationKeys.LOGGER);
const query = container.resolve(ContainerRegistrationKeys.QUERY);
const { data: regions } = await query.graph({
entity: "region",
fields: ["id", "name", "metadata"],
});
for (const region of regions) {
const metadata = region.metadata ?? {};
const missing = Object.fromEntries(
Object.entries(DEFAULT_REGION_STORE_POLICIES).filter(([key]) => metadata[key] === undefined)
);
if (!Object.keys(missing).length) {
continue;
}
await updateRegionsWorkflow(container).run({
input: {
selector: { id: region.id },
update: { metadata: { ...metadata, ...missing } },
},
});
logger.info(`Added store policy defaults to region "${region.name}"`);
}
}

View File

@@ -0,0 +1,117 @@
# Custom Module
A module is a package of reusable functionalities. It can be integrated into your Medusa application without affecting the overall system. You can create a module as part of a plugin.
> Learn more about modules in [this documentation](https://docs.medusajs.com/learn/fundamentals/modules).
To create a module:
## 1. Create a Data Model
A data model represents a table in the database. You create a data model in a TypeScript or JavaScript file under the `models` directory of a module.
For example, create the file `src/modules/blog/models/post.ts` with the following content:
```ts
import { model } from "@medusajs/framework/utils"
const Post = model.define("post", {
id: model.id().primaryKey(),
title: model.text(),
})
export default Post
```
## 2. Create a Service
A module must define a service. A service is a TypeScript or JavaScript class holding methods related to a business logic or commerce functionality.
For example, create the file `src/modules/blog/service.ts` with the following content:
```ts
import { MedusaService } from "@medusajs/framework/utils"
import Post from "./models/post"
class BlogModuleService extends MedusaService({
Post,
}){
}
export default BlogModuleService
```
## 3. Export Module Definition
A module must have an `index.ts` file in its root directory that exports its definition. The definition specifies the main service of the module.
For example, create the file `src/modules/blog/index.ts` with the following content:
```ts
import BlogModuleService from "./service"
import { Module } from "@medusajs/framework/utils"
export const BLOG_MODULE = "blog"
export default Module(BLOG_MODULE, {
service: BlogModuleService,
})
```
## 4. Add Module to Medusa's Configurations
To start using the module, add it to `medusa-config.ts`:
```ts
module.exports = defineConfig({
projectConfig: {
// ...
},
modules: [
{
resolve: "./src/modules/blog",
},
],
})
```
## 5. Generate and Run Migrations
To generate migrations for your module, run the following command:
```bash
npx medusa db:generate blog
```
Then, to run migrations, run the following command:
```bash
npx medusa db:migrate
```
## Use Module
You can use the module in customizations within the Medusa application, such as workflows and API routes.
For example, to use the module in an API route:
```ts
import { MedusaRequest, MedusaResponse } from "@medusajs/framework"
import BlogModuleService from "../../../modules/blog/service"
import { BLOG_MODULE } from "../../../modules/blog"
export async function GET(
req: MedusaRequest,
res: MedusaResponse
): Promise<void> {
const blogModuleService: BlogModuleService = req.scope.resolve(
BLOG_MODULE
)
const posts = await blogModuleService.listPosts()
res.json({
posts
})
}
```

View File

@@ -0,0 +1,9 @@
import { Module } from "@medusajs/framework/utils"
import InquiryModuleService from "./service"
export const INQUIRY_MODULE = "inquiry"
export default Module(INQUIRY_MODULE, {
service: InquiryModuleService,
})

View File

@@ -0,0 +1,302 @@
{
"namespaces": [
"public"
],
"name": "public",
"tables": [
{
"columns": {
"id": {
"name": "id",
"type": "text",
"unsigned": false,
"autoincrement": false,
"primary": true,
"nullable": false,
"unique": false,
"length": null,
"precision": null,
"scale": null,
"default": null,
"comment": null,
"enumItems": [],
"mappedType": "text"
},
"name": {
"name": "name",
"type": "text",
"unsigned": false,
"autoincrement": false,
"primary": false,
"nullable": false,
"unique": false,
"length": null,
"precision": null,
"scale": null,
"default": null,
"comment": null,
"enumItems": [],
"mappedType": "text"
},
"email": {
"name": "email",
"type": "text",
"unsigned": false,
"autoincrement": false,
"primary": false,
"nullable": false,
"unique": false,
"length": null,
"precision": null,
"scale": null,
"default": null,
"comment": null,
"enumItems": [],
"mappedType": "text"
},
"phone": {
"name": "phone",
"type": "text",
"unsigned": false,
"autoincrement": false,
"primary": false,
"nullable": false,
"unique": false,
"length": null,
"precision": null,
"scale": null,
"default": null,
"comment": null,
"enumItems": [],
"mappedType": "text"
},
"company_name": {
"name": "company_name",
"type": "text",
"unsigned": false,
"autoincrement": false,
"primary": false,
"nullable": true,
"unique": false,
"length": null,
"precision": null,
"scale": null,
"default": null,
"comment": null,
"enumItems": [],
"mappedType": "text"
},
"city": {
"name": "city",
"type": "text",
"unsigned": false,
"autoincrement": false,
"primary": false,
"nullable": false,
"unique": false,
"length": null,
"precision": null,
"scale": null,
"default": null,
"comment": null,
"enumItems": [],
"mappedType": "text"
},
"dimensions": {
"name": "dimensions",
"type": "text",
"unsigned": false,
"autoincrement": false,
"primary": false,
"nullable": true,
"unique": false,
"length": null,
"precision": null,
"scale": null,
"default": null,
"comment": null,
"enumItems": [],
"mappedType": "text"
},
"message": {
"name": "message",
"type": "text",
"unsigned": false,
"autoincrement": false,
"primary": false,
"nullable": false,
"unique": false,
"length": null,
"precision": null,
"scale": null,
"default": null,
"comment": null,
"enumItems": [],
"mappedType": "text"
},
"status": {
"name": "status",
"type": "text",
"unsigned": false,
"autoincrement": false,
"primary": false,
"nullable": false,
"unique": false,
"length": null,
"precision": null,
"scale": null,
"default": "'new'",
"comment": null,
"enumItems": [
"new",
"contacted",
"quote_sent",
"won",
"lost",
"archived"
],
"mappedType": "enum"
},
"notes": {
"name": "notes",
"type": "text",
"unsigned": false,
"autoincrement": false,
"primary": false,
"nullable": true,
"unique": false,
"length": null,
"precision": null,
"scale": null,
"default": null,
"comment": null,
"enumItems": [],
"mappedType": "text"
},
"product_id": {
"name": "product_id",
"type": "text",
"unsigned": false,
"autoincrement": false,
"primary": false,
"nullable": true,
"unique": false,
"length": null,
"precision": null,
"scale": null,
"default": null,
"comment": null,
"enumItems": [],
"mappedType": "text"
},
"sales_channel_id": {
"name": "sales_channel_id",
"type": "text",
"unsigned": false,
"autoincrement": false,
"primary": false,
"nullable": true,
"unique": false,
"length": null,
"precision": null,
"scale": null,
"default": null,
"comment": null,
"enumItems": [],
"mappedType": "text"
},
"metadata": {
"name": "metadata",
"type": "jsonb",
"unsigned": false,
"autoincrement": false,
"primary": false,
"nullable": true,
"unique": false,
"length": null,
"precision": null,
"scale": null,
"default": null,
"comment": null,
"enumItems": [],
"mappedType": "json"
},
"created_at": {
"name": "created_at",
"type": "timestamptz",
"unsigned": false,
"autoincrement": false,
"primary": false,
"nullable": false,
"unique": false,
"length": 6,
"precision": null,
"scale": null,
"default": "now()",
"comment": null,
"enumItems": [],
"mappedType": "datetime"
},
"updated_at": {
"name": "updated_at",
"type": "timestamptz",
"unsigned": false,
"autoincrement": false,
"primary": false,
"nullable": false,
"unique": false,
"length": 6,
"precision": null,
"scale": null,
"default": "now()",
"comment": null,
"enumItems": [],
"mappedType": "datetime"
},
"deleted_at": {
"name": "deleted_at",
"type": "timestamptz",
"unsigned": false,
"autoincrement": false,
"primary": false,
"nullable": true,
"unique": false,
"length": 6,
"precision": null,
"scale": null,
"default": null,
"comment": null,
"enumItems": [],
"mappedType": "datetime"
}
},
"name": "inquiry",
"schema": "public",
"indexes": [
{
"keyName": "IDX_inquiry_deleted_at",
"columnNames": [],
"composite": false,
"constraint": false,
"primary": false,
"unique": false,
"expression": "CREATE INDEX IF NOT EXISTS \"IDX_inquiry_deleted_at\" ON \"inquiry\" (\"deleted_at\") WHERE deleted_at IS NULL"
},
{
"keyName": "inquiry_pkey",
"columnNames": [
"id"
],
"composite": false,
"constraint": true,
"primary": true,
"unique": true
}
],
"checks": [],
"foreignKeys": {},
"nativeEnums": {}
}
],
"nativeEnums": {}
}

View File

@@ -0,0 +1,14 @@
import { Migration } from "@medusajs/framework/mikro-orm/migrations";
export class Migration20261109151942 extends Migration {
override async up(): Promise<void> {
this.addSql(`create table if not exists "inquiry" ("id" text not null, "name" text not null, "email" text not null, "phone" text not null, "company_name" text null, "city" text not null, "dimensions" text null, "message" text not null, "status" text check ("status" in ('new', 'contacted', 'quote_sent', 'won', 'lost', 'archived')) not null default 'new', "notes" text null, "product_id" text null, "sales_channel_id" text null, "metadata" jsonb null, "created_at" timestamptz not null default now(), "updated_at" timestamptz not null default now(), "deleted_at" timestamptz null, constraint "inquiry_pkey" primary key ("id"));`);
this.addSql(`CREATE INDEX IF NOT EXISTS "IDX_inquiry_deleted_at" ON "inquiry" ("deleted_at") WHERE deleted_at IS NULL;`);
}
override async down(): Promise<void> {
this.addSql(`drop table if exists "inquiry" cascade;`);
}
}

View File

@@ -0,0 +1,27 @@
import { model } from "@medusajs/framework/utils"
export const Inquiry = model.define("inquiry", {
id: model.id().primaryKey(),
name: model.text(),
email: model.text(),
phone: model.text(),
company_name: model.text().nullable(),
city: model.text(),
dimensions: model.text().nullable(),
message: model.text(),
status: model.enum([
"new",
"contacted",
"quote_sent",
"won",
"lost",
"archived",
]).default("new"),
notes: model.text().nullable(),
product_id: model.text().nullable(),
sales_channel_id: model.text().nullable(),
metadata: model.json().nullable(),
})
export default Inquiry

View File

@@ -0,0 +1,9 @@
import { MedusaService } from "@medusajs/framework/utils"
import Inquiry from "./models/inquiry"
class InquiryModuleService extends MedusaService({
Inquiry,
}) {}
export default InquiryModuleService

View File

@@ -0,0 +1,179 @@
import { ExecArgs } from "@medusajs/framework/types"
import { ContainerRegistrationKeys, Modules } from "@medusajs/framework/utils"
import {
deleteRegionsWorkflow,
deleteSalesChannelsWorkflow,
deleteStockLocationsWorkflow,
deleteApiKeysWorkflow,
} from "@medusajs/medusa/core-flows"
export default async function cleanupKeepBaHrOnly({ container }: ExecArgs) {
const logger = container.resolve(ContainerRegistrationKeys.LOGGER)
const query = container.resolve(ContainerRegistrationKeys.QUERY)
const userModuleService = container.resolve(Modules.USER)
logger.info("==========================================================")
logger.info("ČIŠĆENJE SISTEMA: ZADRŽAVANJE SAMO BOSNE I HRVATSKE")
logger.info("==========================================================")
// 1. ZADRŽAVAMO SAMO REGIJE BOSNA I HERCEGOVINA (ba) I HRVATSKA (hr)
logger.info("1. Uklanjanje svih ostalih regija (Europe / ostale zemlje)...")
const { data: allRegions } = await query.graph({
entity: "region",
fields: ["id", "name", "currency_code"],
})
const keepRegionNames = ["Bosna i Hercegovina", "Hrvatska"]
const regionsToDelete = allRegions.filter((r) => !keepRegionNames.includes(r.name))
for (const reg of regionsToDelete) {
try {
await deleteRegionsWorkflow(container).run({
input: [reg.id],
})
logger.info(`Obrisana regija: ${reg.name} [${reg.id}]`)
} catch (e: any) {
logger.warn(`Greška pri brisanju regije ${reg.name}: ${e.message}`)
}
}
// 2. ZADRŽAVAMO SAMO PRODAJNE KANALE ZA BIH I HRVATSKU
logger.info("2. Uklanjanje ostalih prodajnih kanala...")
const { data: allChannels } = await query.graph({
entity: "sales_channel",
fields: ["id", "name"],
})
const keepChannelNames = [
"Suman d.o.o. - Bosna i Hercegovina",
"Suman d.o.o. - Hrvatska",
]
const channelsToDelete = allChannels.filter((c) => !keepChannelNames.includes(c.name))
if (channelsToDelete.length > 0) {
try {
await deleteSalesChannelsWorkflow(container).run({
input: {
ids: channelsToDelete.map((c) => c.id),
},
})
logger.info(`Obrisano ${channelsToDelete.length} starih prodajnih kanala.`)
} catch (e: any) {
logger.warn(`Greška pri brisanju kanala: ${e.message}`)
}
}
// 3. ZADRŽAVAMO SAMO SKLADIŠTA GRAČANICA (BIH) I ZAGREB (HR)
logger.info("3. Uklanjanje ostalih skladišta...")
const { data: allLocations } = await query.graph({
entity: "stock_location",
fields: ["id", "name"],
})
const keepLocationNames = [
"Centralno Skladište Suman Gračanica (BiH)",
"Distributivni Centar Suman Zagreb (HR)",
]
const locationsToDelete = allLocations.filter((l) => !keepLocationNames.includes(l.name))
if (locationsToDelete.length > 0) {
try {
await deleteStockLocationsWorkflow(container).run({
input: locationsToDelete.map((l) => l.id),
})
logger.info(`Obrisano ${locationsToDelete.length} starih skladišta.`)
} catch (e: any) {
logger.warn(`Greška pri brisanju skladišta: ${e.message}`)
}
}
// 4. ZADRŽAVAMO SAMO API KLJUČEVE ZA BIH I HRVATSKU
logger.info("4. Uklanjanje ostalih API ključeva...")
const { data: allApiKeys } = await query.graph({
entity: "api_key",
fields: ["id", "title"],
})
const keepKeyTitles = [
"Storefront BiH (suman.ba)",
"Storefront HR (suman.hr)",
]
const keysToDelete = allApiKeys.filter((k) => !keepKeyTitles.includes(k.title))
if (keysToDelete.length > 0) {
try {
await deleteApiKeysWorkflow(container).run({
input: {
ids: keysToDelete.map((k) => k.id),
},
})
logger.info(`Obrisano ${keysToDelete.length} starih API ključeva.`)
} catch (e: any) {
logger.warn(`Greška pri brisanju API ključeva: ${e.message}`)
}
}
// 5. AŽURIRANJE ADMIN KORISNIKA ZA BIH I HR
logger.info("5. Konfiguracija regionalnih admin korisnika (admin.ba i admin.hr)...")
const { data: channels } = await query.graph({
entity: "sales_channel",
fields: ["id", "name"],
})
const chanBA = channels.find((c) => c.name.includes("Bosna"))
const chanHR = channels.find((c) => c.name.includes("Hrvatska"))
// Brisanje starih demo admina DE i AT ako postoje
const { data: oldAdmins } = await query.graph({
entity: "user",
fields: ["id", "email"],
filters: { email: ["admin.de@suncobrani.com", "admin.at@suncobrani.com"] },
})
for (const admin of oldAdmins) {
await userModuleService.deleteUsers([admin.id])
logger.info(`Uklonjen stari demo admin: ${admin.email}`)
}
// Provjera/kreiranje admin.ba i admin.hr
if (chanBA) {
const { data: existingBa } = await query.graph({
entity: "user",
fields: ["id", "email"],
filters: { email: "admin.ba@suncobrani.com" },
})
if (existingBa.length === 0) {
await userModuleService.createUsers([
{
email: "admin.ba@suncobrani.com",
first_name: "Admin",
last_name: "Bosna i Hercegovina",
metadata: { sales_channel_id: chanBA.id },
},
])
logger.info(`Kreiran admin za Bosnu: admin.ba@suncobrani.com vezan za kanal ${chanBA.id}`)
}
}
if (chanHR) {
const { data: existingHr } = await query.graph({
entity: "user",
fields: ["id", "email"],
filters: { email: "admin.hr@suncobrani.com" },
})
if (existingHr.length === 0) {
await userModuleService.createUsers([
{
email: "admin.hr@suncobrani.com",
first_name: "Admin",
last_name: "Hrvatska",
metadata: { sales_channel_id: chanHR.id },
},
])
logger.info(`Kreiran admin za Hrvatsku: admin.hr@suncobrani.com vezan za kanal ${chanHR.id}`)
}
}
logger.info("==========================================================")
logger.info("ČIŠĆENJE ZAVRŠENO: SISTEM IMA ISKLJUČIVO BOSNU I HRVATSKU!")
logger.info("==========================================================")
}

View File

@@ -0,0 +1,355 @@
/**
* Demo data only — creates 50 published products so the store page's
* pagination and option facets have something to work with. Safe to delete
* along with the products it creates; nothing in the app depends on it.
*
* npx medusa exec ./src/scripts/seed-demo-products.ts
*
* Re-running it is a no-op for anything it already created: every product uses
* a deterministic handle, and existing handles are skipped.
*/
import {
createCollectionsWorkflow,
createProductOptionsWorkflow,
createProductTagsWorkflow,
createProductsWorkflow,
} from '@medusajs/medusa/core-flows'
import {
ContainerRegistrationKeys,
MedusaError,
Modules,
ProductStatus,
} from '@medusajs/framework/utils'
import type { ExecArgs } from '@medusajs/framework/types'
const PRODUCT_COUNT = 50
const HANDLE_PREFIX = 'demo'
/** Products are created in batches so one failure doesn't roll back all 50. */
const BATCH_SIZE = 10
/** Caps the variant count per product, since options multiply. */
const MAX_VARIANTS = 12
/** Products per awaited search-ingestion call. */
const INGEST_CHUNK_SIZE = 25
/**
* Deterministic PRNG (mulberry32). Keeps re-runs identical, so the same handle
* always describes the same product.
*/
function makeRandom(seed: number) {
let state = seed
return () => {
state = (state + 0x6d2b79f5) | 0
let t = Math.imul(state ^ (state >>> 15), 1 | state)
t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t
return ((t ^ (t >>> 14)) >>> 0) / 4294967296
}
}
const ADJECTIVES = [
'Vintage', 'Classic', 'Relaxed', 'Tailored', 'Oversized',
'Everyday', 'Heritage', 'Essential', 'Cropped', 'Lightweight',
]
const MATERIALS = ['Cotton', 'Linen', 'Merino', 'Denim', 'Fleece', 'Twill']
const TYPES = [
'Tee', 'Hoodie', 'Sweatshirt', 'Shorts', 'Joggers',
'Overshirt', 'Cap', 'Socks', 'Tote', 'Beanie',
]
const COLLECTIONS = ['Summer Essentials', 'Winter Layers', 'Everyday Basics', 'Limited Run']
const TAGS = ['sale', 'new-arrival', 'organic', 'unisex', 'bestseller', 'last-chance']
/**
* Extra shared options, so the store page's option facet shows more than the
* Size and Color the initial seed creates.
*/
const EXTRA_OPTIONS = [
{ title: 'Material', values: ['Cotton', 'Linen', 'Merino', 'Fleece'] },
{ title: 'Fit', values: ['Regular', 'Slim', 'Relaxed'] },
{ title: 'Sleeve', values: ['Short', 'Long'] },
]
/** Real Medusa demo images, so the grid isn't full of placeholders. */
const IMAGES = [
'https://medusa-public-images.s3.eu-west-1.amazonaws.com/tee-black-front.png',
'https://medusa-public-images.s3.eu-west-1.amazonaws.com/tee-white-front.png',
'https://medusa-public-images.s3.eu-west-1.amazonaws.com/sweatshirt-vintage-front.png',
'https://medusa-public-images.s3.eu-west-1.amazonaws.com/sweatpants-gray-front.png',
'https://medusa-public-images.s3.eu-west-1.amazonaws.com/shorts-vintage-front.png',
'https://medusa-public-images.s3.eu-west-1.amazonaws.com/coffee-mug.png',
]
type SharedOption = { id: string; title: string; values: string[] }
export default async function seedDemoProducts({ container }: ExecArgs) {
const logger = container.resolve(ContainerRegistrationKeys.LOGGER)
const query = container.resolve(ContainerRegistrationKeys.QUERY)
const random = makeRandom(20260831)
const pick = <T>(items: T[]): T => items[Math.floor(random() * items.length)]
const pickSome = <T>(items: T[], max: number): T[] => {
const count = Math.floor(random() * (max + 1))
return [...items].sort(() => random() - 0.5).slice(0, count)
}
// ---- Prerequisites that already exist in the project ----------------------
const { data: salesChannels } = await query.graph({
entity: 'sales_channel',
fields: ['id', 'name'],
})
const { data: shippingProfiles } = await query.graph({
entity: 'shipping_profile',
fields: ['id'],
})
const { data: categories } = await query.graph({
entity: 'product_category',
fields: ['id', 'name'],
})
const { data: stores } = await query.graph({
entity: 'store',
fields: ['id', 'supported_currencies.currency_code'],
})
const salesChannel = salesChannels[0]
const shippingProfile = shippingProfiles[0]
if (!salesChannel || !shippingProfile) {
throw new MedusaError(
MedusaError.Types.NOT_FOUND,
'No sales channel or shipping profile found. Run the initial data seed first.'
)
}
const currencyCodes: string[] = (
stores[0]?.supported_currencies ?? []
)
.map((currency) => currency?.currency_code)
.filter((code): code is string => Boolean(code))
if (!currencyCodes.length) {
throw new MedusaError(
MedusaError.Types.NOT_FOUND,
'The store has no supported currencies.'
)
}
logger.info(
`Seeding into "${salesChannel.name}" with currencies: ${currencyCodes.join(', ')}`
)
// ---- Collections, tags and extra options --------------------------------
const { data: existingCollections } = await query.graph({
entity: 'product_collection',
fields: ['id', 'title'],
})
const missingCollections = COLLECTIONS.filter(
(title) => !existingCollections.some((collection) => collection.title === title)
)
if (missingCollections.length) {
await createCollectionsWorkflow(container).run({
input: { collections: missingCollections.map((title) => ({ title })) },
})
logger.info(`Created ${missingCollections.length} collection(s)`)
}
const { data: allCollections } = await query.graph({
entity: 'product_collection',
fields: ['id', 'title'],
})
const { data: existingTags } = await query.graph({
entity: 'product_tag',
fields: ['id', 'value'],
})
const missingTags = TAGS.filter(
(value) => !existingTags.some((tag) => tag.value === value)
)
if (missingTags.length) {
await createProductTagsWorkflow(container).run({
input: { product_tags: missingTags.map((value) => ({ value })) },
})
logger.info(`Created ${missingTags.length} tag(s)`)
}
const { data: allTags } = await query.graph({
entity: 'product_tag',
fields: ['id', 'value'],
})
// Shared (non-exclusive) options, the way the initial seed defines them.
const { data: existingOptions } = await query.graph({
entity: 'product_option',
fields: ['id', 'title', 'values.value'],
filters: { is_exclusive: false },
})
const missingOptions = EXTRA_OPTIONS.filter(
(option) => !existingOptions.some((existing) => existing.title === option.title)
)
if (missingOptions.length) {
await createProductOptionsWorkflow(container).run({
input: { product_options: missingOptions },
})
logger.info(`Created ${missingOptions.length} shared option(s)`)
}
const { data: optionRows } = await query.graph({
entity: 'product_option',
fields: ['id', 'title', 'values.value'],
filters: { is_exclusive: false },
})
const sharedOptions: SharedOption[] = optionRows
.map((option) => ({
id: option.id as string,
title: option.title as string,
values: (option.values ?? [])
.map((value) => value?.value)
.filter((value): value is string => Boolean(value)),
}))
.filter((option) => option.values.length > 0)
const sizeOption = sharedOptions.find((option) => option.title === 'Size')
if (!sizeOption) {
throw new MedusaError(
MedusaError.Types.NOT_FOUND,
'No shared "Size" option found. Run the initial data seed first.'
)
}
// ---- Build the products -------------------------------------------------
const { data: alreadySeeded } = await query.graph({
entity: 'product',
fields: ['handle'],
})
const takenHandles = new Set(
alreadySeeded.map((product) => product.handle).filter(Boolean)
)
const products: Record<string, unknown>[] = []
for (let index = 0; index < PRODUCT_COUNT; index++) {
// Derived from the index, never from the PRNG. Skipping a product consumes
// fewer random numbers than building one, so a handle that depended on the
// PRNG would shift after the first skip and the script would create
// duplicates instead of recognising its own products.
const type = TYPES[index % TYPES.length]
const handle = `${HANDLE_PREFIX}-${index + 1}-${type.toLowerCase()}`
if (takenHandles.has(handle)) {
continue
}
const title = `${pick(ADJECTIVES)} ${pick(MATERIALS)} ${type}`
// Size is always present; the rest vary so the facet has uneven counts.
const chosenOptions = [
sizeOption,
...pickSome(
sharedOptions.filter((option) => option.title !== 'Size'),
2
),
]
// Cartesian product of the chosen options' values, capped.
let combinations: Record<string, string>[] = [{}]
for (const option of chosenOptions) {
const next: Record<string, string>[] = []
for (const combination of combinations) {
for (const value of option.values) {
if (next.length >= MAX_VARIANTS) {
break
}
next.push({ ...combination, [option.title]: value })
}
}
combinations = next
}
const collection = pick(allCollections)
const chosenTags = pickSome(allTags, 3)
const chosenCategories = pickSome(categories, 2)
const thumbnail = pick(IMAGES)
const basePrice = 10 + Math.floor(random() * 90)
products.push({
title,
handle,
subtitle: `${type} — demo data`,
description: `A ${title.toLowerCase()} generated to fill out the demo catalogue. Not a real product.`,
status: ProductStatus.PUBLISHED,
thumbnail,
images: [{ url: thumbnail }],
weight: 300 + Math.floor(random() * 500),
shipping_profile_id: shippingProfile.id,
collection_id: collection?.id,
tag_ids: chosenTags.map((tag) => tag.id as string),
category_ids: chosenCategories.map((category) => category.id as string),
sales_channels: [{ id: salesChannel.id }],
options: chosenOptions.map((option) => ({ id: option.id })),
variants: combinations.map((combination) => ({
title: Object.values(combination).join(' / '),
sku: `${handle.toUpperCase()}-${Object.values(combination).join('-').toUpperCase()}`,
options: combination,
prices: currencyCodes.map((currency_code) => ({
amount: basePrice,
currency_code,
})),
})),
})
}
if (!products.length) {
logger.info('Every demo product already exists. Nothing to do.')
return
}
// ---- Create them --------------------------------------------------------
let created = 0
for (let start = 0; start < products.length; start += BATCH_SIZE) {
const batch = products.slice(start, start + BATCH_SIZE)
await createProductsWorkflow(container).run({
input: { products: batch as never },
})
created += batch.length
logger.info(`Created ${created}/${products.length} demo products`)
}
// ---- Make sure the search index caught up -------------------------------
// `product.created` is emitted on the local event bus and handled
// asynchronously, so a short-lived `medusa exec` process can exit before the
// last batch is ingested. Replaying the ingestion here is awaited, and
// `consume` upserts, so it is safe to run over every product.
const search = container.resolve(Modules.SEARCH)
const { data: allProducts } = await query.graph({
entity: 'product',
fields: ['id'],
})
for (let start = 0; start < allProducts.length; start += INGEST_CHUNK_SIZE) {
const chunk = allProducts.slice(start, start + INGEST_CHUNK_SIZE)
await search.ingest({
name: 'product.created',
data: chunk.map((product) => ({ id: product.id })),
} as never)
}
logger.info(`Search index caught up for ${allProducts.length} product(s).`)
logger.info('Done. Open the store page to see the new products.')
}

View File

@@ -0,0 +1,73 @@
import { ExecArgs } from "@medusajs/framework/types"
import { ContainerRegistrationKeys } from "@medusajs/framework/utils"
import { createPriceListsWorkflow } from "@medusajs/medusa/core-flows"
export default async function setupB2BPricing({ container }: ExecArgs) {
const logger = container.resolve(ContainerRegistrationKeys.LOGGER)
const query = container.resolve(ContainerRegistrationKeys.QUERY)
// 1. Dobavljanje B2B Customer Grupe
const { data: groups } = await query.graph({
entity: "customer_group",
fields: ["id", "name"],
filters: { name: "HoReCa B2B Partneri" },
})
const b2bGroup = groups[0]
if (!b2bGroup) {
logger.error("B2B grupa 'HoReCa B2B Partneri' nije pronađena.")
return
}
// 2. Dobavljanje varijanti suncobrana
const { data: products } = await query.graph({
entity: "product",
fields: ["id", "title", "variants.id", "variants.title"],
filters: { handle: "gastro-master-suncobran" },
})
const product = products[0]
if (!product || !product.variants?.length) {
logger.error("Proizvod suncobran ili njegove varijante nisu pronađene.")
return
}
// 3. Provjera da li cjenovnik već postoji
const { data: existingPriceLists } = await query.graph({
entity: "price_list",
fields: ["id", "title"],
filters: { title: "HoReCa Veleprodajni Cjenovnik - DE & AT" },
})
if (existingPriceLists.length > 0) {
logger.info("B2B Price List već postoji u bazi.")
return
}
// 4. Formiranje B2B cijena: 390 EUR za 3x3m (umjesto 550 EUR), 590 EUR za 4x4m (umjesto 790 EUR)
const prices = product.variants.map((v: any) => {
const isLarge = v.title.includes("4x4m")
return {
currency_code: "eur",
amount: isLarge ? 590.00 : 390.00,
variant_id: v.id,
}
})
await createPriceListsWorkflow(container).run({
input: {
price_lists_data: [
{
title: "HoReCa Veleprodajni Cjenovnik - DE & AT",
description: "Veleprodajne cijene suncobrana za verifikovane hotele i restorane",
status: "active",
rules: {
customer_group_id: [b2bGroup.id],
},
prices,
} as any,
],
},
})
logger.info("Uspješno kreiran i aktiviran B2B Veleprodajni Cjenovnik (Override) za 'HoReCa B2B Partneri' grupu.")
}

View File

@@ -0,0 +1,726 @@
import { ExecArgs } from "@medusajs/framework/types"
import { ContainerRegistrationKeys, Modules } from "@medusajs/framework/utils"
import {
createSalesChannelsWorkflow,
createStockLocationsWorkflow,
linkSalesChannelsToStockLocationWorkflow,
linkSalesChannelsToApiKeyWorkflow,
createApiKeysWorkflow,
createCustomerGroupsWorkflow,
createProductsWorkflow,
deleteProductsWorkflow,
createProductCategoriesWorkflow,
deleteProductCategoriesWorkflow,
createRegionsWorkflow,
} from "@medusajs/medusa/core-flows"
export default async function setupSumanBa({ container }: ExecArgs) {
const logger = container.resolve(ContainerRegistrationKeys.LOGGER)
const query = container.resolve(ContainerRegistrationKeys.QUERY)
logger.info("==========================================================")
logger.info("POKREĆEM REORGANIZACIJU: ŠUMAN D.O.O. (BOSNA I HERCEGOVINA)")
logger.info("==========================================================")
// 0. Dobavljanje master admin korisnika
const { data: users } = await query.graph({
entity: "user",
fields: ["id", "email"],
filters: { email: "admin@suncobrani.com" },
})
const adminUser = users[0]
if (!adminUser) {
throw new Error("Admin korisnik admin@suncobrani.com nije pronađen.")
}
// 1. BRISANJE SVIH POSTOJEĆIH PROIZVODA
logger.info("1. Brisanje svih postojećih proizvoda...")
const { data: allProducts } = await query.graph({
entity: "product",
fields: ["id", "title"],
})
if (allProducts.length > 0) {
const productIds = allProducts.map((p) => p.id)
await deleteProductsWorkflow(container).run({
input: {
ids: productIds,
},
})
logger.info(`Obrisano ${allProducts.length} postojećih proizvoda.`)
} else {
logger.info("Nema postojećih proizvoda za brisanje.")
}
// 2. BRISANJE SVIH POSTOJEĆIH KATEGORIJA
logger.info("2. Brisanje svih postojećih kategorija...")
const { data: allCategories } = await query.graph({
entity: "product_category",
fields: ["id", "name"],
})
if (allCategories.length > 0) {
try {
await deleteProductCategoriesWorkflow(container).run({
input: {
ids: allCategories.map((c) => c.id),
},
})
logger.info(`Obrisano ${allCategories.length} kategorija.`)
} catch (e: any) {
logger.warn(`Greška pri brisanju kategorija: ${e.message}`)
}
}
// 3. POSTAVLJANJE REGIJE ZA BOSNU I HERCEGOVINU (BA / BAM)
logger.info("3. Postavljanje regije Bosna i Hercegovina (BAM / KM)...")
const { data: existingRegions } = await query.graph({
entity: "region",
fields: ["id", "name", "currency_code"],
filters: { name: "Bosna i Hercegovina" },
})
let regionBA = existingRegions[0]
if (!regionBA) {
const { result: createdRegions } = await createRegionsWorkflow(container).run({
input: {
regions: [
{
name: "Bosna i Hercegovina",
currency_code: "bam",
countries: ["ba"],
payment_providers: ["pp_system_default"],
},
],
},
})
regionBA = createdRegions[0]
logger.info(`Kreirana regija: ${regionBA.name} [ID: ${regionBA.id}] sa valutom BAM.`)
} else {
logger.info(`Regija BiH već postoji [ID: ${regionBA.id}].`)
}
// Dobavljanje default shipping profila
const { data: shippingProfiles } = await query.graph({
entity: "shipping_profile",
fields: ["id", "type"],
})
const defaultShippingProfile = shippingProfiles[0]
// 4. KREIRANJE PRODAJNOG KANALA ZA BOSNU
logger.info("4. Kreiranje zvaničnog prodajnog kanala Suman BiH...")
const { data: existingChannels } = await query.graph({
entity: "sales_channel",
fields: ["id", "name"],
filters: { name: "Suman d.o.o. - Bosna i Hercegovina" },
})
let channelBA = existingChannels[0]
if (!channelBA) {
const { result: createdChannels } = await createSalesChannelsWorkflow(container).run({
input: {
salesChannelsData: [
{
name: "Suman d.o.o. - Bosna i Hercegovina",
description: "Zvanični prodajni kanal za tržište Bosne i Hercegovine (suman.ba)",
},
],
},
})
channelBA = createdChannels[0]
}
logger.info(`Prodajni kanal: ${channelBA.name} [ID: ${channelBA.id}]`)
// 5. KREIRANJE SKLADIŠTA GRAČANICA (BiH) I POVEZIVANJE SA KANALOM
logger.info("5. Povezivanje skladišta Suman Gračanica sa kanalom...")
const { data: existingLocs } = await query.graph({
entity: "stock_location",
fields: ["id", "name"],
filters: { name: "Centralno Skladište Suman Gračanica (BiH)" },
})
let locGracanica = existingLocs[0]
if (!locGracanica) {
const { result: createdLocations } = await createStockLocationsWorkflow(container).run({
input: {
locations: [{ name: "Centralno Skladište Suman Gračanica (BiH)" }],
},
})
locGracanica = createdLocations[0]
}
try {
await linkSalesChannelsToStockLocationWorkflow(container).run({
input: {
id: locGracanica.id,
add: [channelBA.id],
},
})
logger.info("Skladište Gračanica uspješno povezano sa kanalom BiH.")
} catch (e: any) {
logger.warn(`Veza skladišta i kanala: ${e.message}`)
}
// 6. KREIRANJE NOVOG PUBLISHABLE API KLJUČA ZA BOSNU
logger.info("6. Generisanje Publishable API ključa za Bosnu...")
const { result: apiKeys } = await createApiKeysWorkflow(container).run({
input: {
api_keys: [
{
title: "Storefront BiH (suman.ba)",
type: "publishable",
created_by: adminUser.id,
},
],
},
})
const keyBA = apiKeys[0]
await linkSalesChannelsToApiKeyWorkflow(container).run({
input: {
id: keyBA.id,
add: [channelBA.id],
},
})
logger.info(`Kreiran novi ključ za Bosnu: ${keyBA.token}`)
// 7. KREIRANJE KATEGORIJA SA SUMAN.BA
logger.info("7. Kreiranje zvaničnih kategorija sa suman.ba...")
const { result: categories } = await createProductCategoriesWorkflow(container).run({
input: {
product_categories: [
{
name: "Suncobrani",
handle: "suncobrani",
description: "Profesionalni i dvorišni suncobrani visokog kvaliteta proizvedeni u BiH",
is_active: true,
is_internal: false,
},
{
name: "Pergole i bioklimatske tende",
handle: "pergole-i-bioklimatske-tende",
description: "Luksuzni aluminijski sistemi, bioklimatske rotirajuće lamele i PVC krovovi",
is_active: true,
is_internal: false,
},
{
name: "Tende",
handle: "tende",
description: "Zglobne, kasetne, vertikalne i kupolaste tende za terase i balkone",
is_active: true,
is_internal: false,
},
],
},
})
const catSuncobrani = categories.find((c) => c.handle === "suncobrani")!
const catPergole = categories.find((c) => c.handle === "pergole-i-bioklimatske-tende")!
const catTende = categories.find((c) => c.handle === "tende")!
logger.info("Kategorije uspješno kreirane: Suncobrani, Pergole, Tende.")
// 8. UNOS ZVANIČNIH PROIZVODA SA SUMAN.BA SA SLIKAMA I KONFIGURACIJAMA
logger.info("8. Unos zvaničnih Suman proizvoda sa slikama i konfiguracijama...")
const sumanProducts = [
// --- KATEGORIJA: SUNCOBRANI ---
{
title: "Suncobran Advance",
subtitle: "100% visokokvalitetni aluminijum, elegantan i pouzdan za kafiće i terase",
handle: "suncobran-advance",
status: "published",
shipping_profile_id: defaultShippingProfile?.id,
sales_channels: [{ id: channelBA.id }],
category_ids: [catSuncobrani.id],
images: [
{ url: "https://suman.ba/assets/photos/products/original/1557424992-advance.jpg" },
],
thumbnail: "https://suman.ba/assets/photos/products/original/1557424992-advance.jpg",
metadata: {
mast_diameter: "Ø 58 mm ojačani aluminijski profil",
ribs_profile: "30x20 mm aluminijski krakovi sa ABS UV stabilnim zglobovima",
fabric_weight: "Poliester 300 g/m² / Akril vodootporan",
uv_protection: "UPF 50+ (ISO 105-B02 certifikat postojanosti)",
water_column: "1000 mm vodeni stub",
design_system: "Cascade look® zaštićeni krovni dizajn, opcija sa i bez luftera",
special_feature: "Easy Repair sistem na klik za brzu zamjenu krakova na lokaciji",
warranty_years: "3 godine garancije",
origin: "Proizvedeno u Bosni i Hercegovini (Suman d.o.o. Gračanica)",
},
options: [
{ title: "Dimenzija", values: ["2x2m (LS 200)", "3x3m (LS 300)", "3.5x3.5m (LS 350)", "4x4m (LS 400)", "Ø 3.5m (LO 350)"] },
{ title: "Boja platna", values: ["Bijela (RAL 9016)", "Antracit Siva (RAL 7016)", "Prirodna Bež", "Bordo Crvena"] },
{ title: "Konstrukcija", values: ["Bijela plastificirana (RAL 9016)", "Antracit plastificirana", "Imitacija drveta"] },
],
variants: [
{
title: "3x3m / Bijela / Bijela konstrukcija",
sku: "ADV-33-WHT",
options: { Dimenzija: "3x3m (LS 300)", "Boja platna": "Bijela (RAL 9016)", Konstrukcija: "Bijela plastificirana (RAL 9016)" },
prices: [{ currency_code: "bam", amount: 380.00 }, { currency_code: "eur", amount: 194.00 }],
},
{
title: "3x3m / Antracit / Antracit konstrukcija",
sku: "ADV-33-ANT",
options: { Dimenzija: "3x3m (LS 300)", "Boja platna": "Antracit Siva (RAL 7016)", Konstrukcija: "Antracit plastificirana" },
prices: [{ currency_code: "bam", amount: 395.00 }, { currency_code: "eur", amount: 202.00 }],
},
{
title: "4x4m / Bež / Imitacija drveta",
sku: "ADV-44-WOD",
options: { Dimenzija: "4x4m (LS 400)", "Boja platna": "Prirodna Bež", Konstrukcija: "Imitacija drveta" },
prices: [{ currency_code: "bam", amount: 520.00 }, { currency_code: "eur", amount: 266.00 }],
},
{
title: "Ø 3.5m / Bordo / Bijela konstrukcija",
sku: "ADV-O35-BOR",
options: { Dimenzija: "Ø 3.5m (LO 350)", "Boja platna": "Bordo Crvena", Konstrukcija: "Bijela plastificirana (RAL 9016)" },
prices: [{ currency_code: "bam", amount: 410.00 }, { currency_code: "eur", amount: 210.00 }],
},
],
},
{
title: "Suncobran Prestige",
subtitle: "Profesionalni ugostiteljski suncobran sa teleskopskim SLS sistemom otvaranja iznad stolova",
handle: "suncobran-prestige",
status: "published",
shipping_profile_id: defaultShippingProfile?.id,
sales_channels: [{ id: channelBA.id }],
category_ids: [catSuncobrani.id],
images: [
{ url: "https://suman.ba/assets/photos/products/original/1557425028-prestige.jpg" },
],
thumbnail: "https://suman.ba/assets/photos/products/original/1557425028-prestige.jpg",
metadata: {
mast_diameter: "Ø 70 mm visokootporni aluminijum sa unutrašnjim čeličnim ojačanjem",
ribs_profile: "Dijagonalni krakovi 40x20 mm, potporni 32x20 mm",
fabric_weight: "100% obojeni akril 310 g/m² impregniran teflonom (vodoodbojan)",
uv_protection: "UPF 50+ maksimalna zaštita",
wind_resistance: "Klasa 6 Beaufort (izdržava vjetar do 60 km/h)",
opening_mechanism: "SLS teleskopska ručica ili kurbla (zatvaranje iznad visine stolova)",
warranty_years: "5 godina garancije na mehanizam i platno",
},
options: [
{ title: "Dimenzija", values: ["3.5x3.5m (SLS 350)", "4x4m (SLS 400)", "4.5x4.5m (SLS 450)", "5x5m (SLS 500)"] },
{ title: "Boja platna", values: ["Antracit Siva (RAL 7016)", "Topla Bež", "Crna", "Ekru Bijela"] },
],
variants: [
{
title: "3.5x3.5m / Antracit Siva",
sku: "PRS-35-ANT",
options: { Dimenzija: "3.5x3.5m (SLS 350)", "Boja platna": "Antracit Siva (RAL 7016)" },
prices: [{ currency_code: "bam", amount: 1450.00 }, { currency_code: "eur", amount: 741.00 }],
},
{
title: "4x4m / Topla Bež",
sku: "PRS-44-BEZ",
options: { Dimenzija: "4x4m (SLS 400)", "Boja platna": "Topla Bež" },
prices: [{ currency_code: "bam", amount: 1650.00 }, { currency_code: "eur", amount: 844.00 }],
},
{
title: "5x5m / Crna",
sku: "PRS-55-BLK",
options: { Dimenzija: "5x5m (SLS 500)", "Boja platna": "Crna" },
prices: [{ currency_code: "bam", amount: 1980.00 }, { currency_code: "eur", amount: 1012.00 }],
},
],
},
{
title: "Suncobran Magnum",
subtitle: "Mega masivni suncobran za hotelske komplekse i velike restoranske bašte",
handle: "suncobran-magnum",
status: "published",
shipping_profile_id: defaultShippingProfile?.id,
sales_channels: [{ id: channelBA.id }],
category_ids: [catSuncobrani.id],
images: [
{ url: "https://suman.ba/assets/photos/products/original/1557425052-magnum.jpg" },
],
thumbnail: "https://suman.ba/assets/photos/products/original/1557425052-magnum.jpg",
metadata: {
mast_diameter: "Masivni stub Ø 78 mm debljine stijenke 4 mm",
ribs_profile: "Glavni krakovi 50x20 mm, potporni 40x20 mm",
fabric_weight: "320 g/m² akrilno platno sa dvostrukim krovom",
wind_resistance: "Ekstremna otpornost na udare vjetra do 80 km/h",
weight: "70 kg do 95 kg",
warranty_years: "5 godina",
},
options: [
{ title: "Dimenzija", values: ["4x4m (XLS 400)", "5x5m (XLS 500)", "6x6m (XLS 600)"] },
{ title: "Boja platna", values: ["Antracit Siva", "Bež", "Bordo"] },
],
variants: [
{
title: "4x4m / Antracit Siva",
sku: "MAG-44-ANT",
options: { Dimenzija: "4x4m (XLS 400)", "Boja platna": "Antracit Siva" },
prices: [{ currency_code: "bam", amount: 2350.00 }, { currency_code: "eur", amount: 1200.00 }],
},
{
title: "5x5m / Bež",
sku: "MAG-55-BEZ",
options: { Dimenzija: "5x5m (XLS 500)", "Boja platna": "Bež" },
prices: [{ currency_code: "bam", amount: 2890.00 }, { currency_code: "eur", amount: 1478.00 }],
},
{
title: "6x6m / Bordo",
sku: "MAG-66-BOR",
options: { Dimenzija: "6x6m (XLS 600)", "Boja platna": "Bordo" },
prices: [{ currency_code: "bam", amount: 3450.00 }, { currency_code: "eur", amount: 1764.00 }],
},
],
},
{
title: "Suncobran Console (Viseći / Bočni stub)",
subtitle: "Konzolni suncobran sa dislociranim bočnim nosivim stubom i rotacijom 360°",
handle: "suncobran-console",
status: "published",
shipping_profile_id: defaultShippingProfile?.id,
sales_channels: [{ id: channelBA.id }],
category_ids: [catSuncobrani.id],
images: [
{ url: "https://suman.ba/assets/photos/products/original/1557425081-console.jpg" },
],
thumbnail: "https://suman.ba/assets/photos/products/original/1557425081-console.jpg",
metadata: {
mast_construction: "Masivni čelični bočni stub 100x100 mm zaštićen cinkovanjem i plastifikacijom",
rotation: "Integrisani mehanizam sa okretanjem 360° oko ose",
free_space: "100% slobodan prostor ispod platna bez centralnog stuba",
fabric: "Akril 310 g/m² sa UV zaštitom UPF 50+",
warranty_years: "3 godine",
},
options: [
{ title: "Izvedba", values: ["Single 3x3m", "Single 3.5x3.5m", "Single 4x4m", "Duo 6x3m (dvostruki)"] },
{ title: "Boja platna", values: ["Antracit Siva", "Prirodna Bež", "Bijela"] },
],
variants: [
{
title: "Single 3x3m / Antracit Siva",
sku: "CON-33-ANT",
options: { Izvedba: "Single 3x3m", "Boja platna": "Antracit Siva" },
prices: [{ currency_code: "bam", amount: 1890.00 }, { currency_code: "eur", amount: 966.00 }],
},
{
title: "Single 3.5x3.5m / Prirodna Bež",
sku: "CON-35-BEZ",
options: { Izvedba: "Single 3.5x3.5m", "Boja platna": "Prirodna Bež" },
prices: [{ currency_code: "bam", amount: 2150.00 }, { currency_code: "eur", amount: 1099.00 }],
},
{
title: "Duo 6x3m / Bijela",
sku: "CON-DUO-WHT",
options: { Izvedba: "Duo 6x3m (dvostruki)", "Boja platna": "Bijela" },
prices: [{ currency_code: "bam", amount: 3750.00 }, { currency_code: "eur", amount: 1917.00 }],
},
],
},
{
title: "Suncobran Beach",
subtitle: "Profesionalni plažni suncobran za bazene, hotele, vodene parkove i plaže",
handle: "suncobran-beach",
status: "published",
shipping_profile_id: defaultShippingProfile?.id,
sales_channels: [{ id: channelBA.id }],
category_ids: [catSuncobrani.id],
images: [
{ url: "https://suman.ba/assets/photos/products/original/1557425102-beach.jpg" },
],
thumbnail: "https://suman.ba/assets/photos/products/original/1557425102-beach.jpg",
metadata: {
mast_diameter: "Ø 40 mm eloksirani aluminij otporan na so, hlor i UV zračenje",
wind_vent: "Aerodinamični krovni otvor za rasterećenje pritiska vjetra",
fabric: "Poliester 240 g/m² vodoodbojan, UV zaštita UPF 50+",
durability: "Dizajniran za dugotrajno izlaganje suncu i vlagi",
},
options: [
{ title: "Dimenzija", values: ["Ø 200 cm", "Ø 250 cm", "200x200 cm"] },
{ title: "Boja", values: ["Tirkizno Plava", "Bijela", "Pijesak Žuta"] },
],
variants: [
{
title: "Ø 200 cm / Tirkizno Plava",
sku: "BCH-O20-BLU",
options: { Dimenzija: "Ø 200 cm", Boja: "Tirkizno Plava" },
prices: [{ currency_code: "bam", amount: 160.00 }, { currency_code: "eur", amount: 82.00 }],
},
{
title: "200x200 cm / Bijela",
sku: "BCH-22-WHT",
options: { Dimenzija: "200x200 cm", Boja: "Bijela" },
prices: [{ currency_code: "bam", amount: 185.00 }, { currency_code: "eur", amount: 95.00 }],
},
],
},
// --- KATEGORIJA: PERGOLE I BIOKLIMATSKE TENDE ---
{
title: "Pergola Tenda",
subtitle: "Pokretni aluminijski krovni sistem sa troslojnim PVC Blackout platnom i integrisanim olucima",
handle: "pergola-tenda",
status: "published",
shipping_profile_id: defaultShippingProfile?.id,
sales_channels: [{ id: channelBA.id }],
category_ids: [catPergole.id],
images: [
{ url: "https://suman.ba/assets/photos/products/original/1557425128-pergola.jpg" },
],
thumbnail: "https://suman.ba/assets/photos/products/original/1557425128-pergola.jpg",
metadata: {
profile: "Ekstrudirani aluminij 120x80 mm i nosivi stubovi 120x120 mm",
canvas: "Troslojni PVC 850 g/m² Blackout (100% termo i hidro izolacija)",
motor: "Somfy iO motorizacija sa daljinskim upravljačem",
drainage: "Skriveni odvodi i oluci unutar stubova",
warranty_years: "5 godina",
},
options: [
{ title: "Raspon (Moduli)", values: ["Jednomodulna do 4.5m", "Dvomodulna do 9m", "Tromodulna do 13m"] },
{ title: "LED Rasvjeta", values: ["Bez rasvjete", "Integrisana LED spot rasvjeta sa dimerom"] },
],
variants: [
{
title: "Jednomodulna / Sa LED rasvjetom",
sku: "PERG-1M-LED",
options: { "Raspon (Moduli)": "Jednomodulna do 4.5m", "LED Rasvjeta": "Integrisana LED spot rasvjeta sa dimerom" },
prices: [{ currency_code: "bam", amount: 3500.00 }, { currency_code: "eur", amount: 1790.00 }],
},
{
title: "Dvomodulna / Sa LED rasvjetom",
sku: "PERG-2M-LED",
options: { "Raspon (Moduli)": "Dvomodulna do 9m", "LED Rasvjeta": "Integrisana LED spot rasvjeta sa dimerom" },
prices: [{ currency_code: "bam", amount: 6200.00 }, { currency_code: "eur", amount: 3170.00 }],
},
],
},
{
title: "Bioklimatska Tenda (Pergola sa lamelama)",
subtitle: "Luksuzna bioklimatska pergola sa rotirajućim aluminijskim lamelama od 0° do 135°",
handle: "bioklimatska-tenda",
status: "published",
shipping_profile_id: defaultShippingProfile?.id,
sales_channels: [{ id: channelBA.id }],
category_ids: [catPergole.id],
images: [
{ url: "https://suman.ba/assets/photos/products/original/1557425154-bioklimatska.jpg" },
],
thumbnail: "https://suman.ba/assets/photos/products/original/1557425154-bioklimatska.jpg",
metadata: {
lamellas: "Aluminijske termoizolovane lamele sa gumenim zaptivačima protiv vode",
snow_load: "Nosivost na snijeg do 150 kg/m²",
automation: "Automatski senzori za kišu, vjetar i snijeg",
warranty_years: "5 godina",
},
options: [
{ title: "Dimenzija polja", values: ["4x3m", "5x4m", "6x4.5m"] },
{ title: "Boja konstrukcije", values: ["Antracit RAL 7016 mat", "Bijela RAL 9016", "Crna mat"] },
],
variants: [
{
title: "4x3m / Antracit RAL 7016 mat",
sku: "BIO-43-ANT",
options: { "Dimenzija polja": "4x3m", "Boja konstrukcije": "Antracit RAL 7016 mat" },
prices: [{ currency_code: "bam", amount: 6900.00 }, { currency_code: "eur", amount: 3528.00 }],
},
{
title: "5x4m / Antracit RAL 7016 mat",
sku: "BIO-54-ANT",
options: { "Dimenzija polja": "5x4m", "Boja konstrukcije": "Antracit RAL 7016 mat" },
prices: [{ currency_code: "bam", amount: 8900.00 }, { currency_code: "eur", amount: 4550.00 }],
},
],
},
{
title: "Regulus Bioklimatska Pergola",
subtitle: "Vrhunski samostojeći ili fasadni sistem sa opcijom bočnih ZIP stakala i grijača za 4 sezone",
handle: "regulus-bioklimatska",
status: "published",
shipping_profile_id: defaultShippingProfile?.id,
sales_channels: [{ id: channelBA.id }],
category_ids: [catPergole.id],
images: [
{ url: "https://suman.ba/assets/photos/products/original/1557425178-regulus.jpg" },
],
thumbnail: "https://suman.ba/assets/photos/products/original/1557425178-regulus.jpg",
metadata: {
construction: "Ekstra masivni aluminijski stubovi 150x150 mm",
four_seasons: "Potpuna toplotna izolacija i cjelogodišnje korištenje terase",
zip_compatible: "Kompatibilna sa ZIP screen rolo platnima i kliznim staklom",
},
options: [
{ title: "Dimenzija", values: ["4x4m", "5x4m", "6x4m"] },
{ title: "Bočne stijene", values: ["Bez bočnih stijena", "Sa motorizovanim ZIP screen platnima"] },
],
variants: [
{
title: "4x4m / Bez bočnih stijena",
sku: "REG-44-STD",
options: { Dimenzija: "4x4m", "Bočne stijene": "Bez bočnih stijena" },
prices: [{ currency_code: "bam", amount: 8500.00 }, { currency_code: "eur", amount: 4346.00 }],
},
{
title: "5x4m / Sa motorizovanim ZIP screen platnima",
sku: "REG-54-ZIP",
options: { Dimenzija: "5x4m", "Bočne stijene": "Sa motorizovanim ZIP screen platnima" },
prices: [{ currency_code: "bam", amount: 11900.00 }, { currency_code: "eur", amount: 6084.00 }],
},
],
},
// --- KATEGORIJA: TENDE ---
{
title: "Atika Tenda",
subtitle: "Čvrsta tenda sa aluminijskim vodilicama i prednjim stubovima za natkrivanje većih terasa i bašti",
handle: "atika-tenda",
status: "published",
shipping_profile_id: defaultShippingProfile?.id,
sales_channels: [{ id: channelBA.id }],
category_ids: [catTende.id],
images: [
{ url: "https://suman.ba/assets/photos/products/original/1557425204-atika.jpg" },
],
thumbnail: "https://suman.ba/assets/photos/products/original/1557425204-atika.jpg",
metadata: {
frame: "Čvrsta plastificirana aluminijska konstrukcija sa prednjim stubovima",
fabric: "Impregnirano akrilno platno Sattler / Dickson 300 g/m² (vodootporno, UV zaštita)",
options_available: "Mogućnost ugradnje Somfy elektromotora, senzora za vjetar i zaštitnog krovića",
},
options: [
{ title: "Širina i izbačaj", values: ["4x3m", "5x3.5m", "6x4m"] },
{ title: "Pogon", values: ["Ručni pogon (kurbla)", "Somfy elektromotor sa senzorom za vjetar"] },
],
variants: [
{
title: "4x3m / Ručni pogon",
sku: "ATK-43-RUC",
options: { "Širina i izbačaj": "4x3m", Pogon: "Ručni pogon (kurbla)" },
prices: [{ currency_code: "bam", amount: 1850.00 }, { currency_code: "eur", amount: 945.00 }],
},
{
title: "5x3.5m / Somfy elektromotor",
sku: "ATK-535-MOT",
options: { "Širina i izbačaj": "5x3.5m", Pogon: "Somfy elektromotor sa senzorom za vjetar" },
prices: [{ currency_code: "bam", amount: 2490.00 }, { currency_code: "eur", amount: 1273.00 }],
},
],
},
{
title: "Ravna Zglobna Tenda",
subtitle: "Klasična zglobna tenda sa aluminijskim rukama za zaštitu balkona, terasa i izloga od sunca",
handle: "ravna-zglobna-tenda",
status: "published",
shipping_profile_id: defaultShippingProfile?.id,
sales_channels: [{ id: channelBA.id }],
category_ids: [catTende.id],
images: [
{ url: "https://suman.ba/assets/photos/products/original/1557425231-ravna.jpg" },
],
thumbnail: "https://suman.ba/assets/photos/products/original/1557425231-ravna.jpg",
metadata: {
arms: "Ojačane aluminijske zglobne ruke sa dvostrukom čeličnom sajlom i jakim oprugama",
tilt_angle: "Podesiv nagib od 0° do 45°",
fabric: "100% akrilno platno impregnirano teflonom",
},
options: [
{ title: "Dimenzija (Širina x Izbačaj)", values: ["3x2m", "4x2.5m", "5x3m", "6x3.5m"] },
{ title: "Dezen platna", values: ["Antracit Siva", "Topla Bež", "Pruge Žuto-Bijelo", "Pruge Plavo-Bijelo"] },
],
variants: [
{
title: "3x2m / Antracit Siva",
sku: "RAV-32-ANT",
options: { "Dimenzija (Širina x Izbačaj)": "3x2m", "Dezen platna": "Antracit Siva" },
prices: [{ currency_code: "bam", amount: 650.00 }, { currency_code: "eur", amount: 332.00 }],
},
{
title: "4x2.5m / Topla Bež",
sku: "RAV-425-BEZ",
options: { "Dimenzija (Širina x Izbačaj)": "4x2.5m", "Dezen platna": "Topla Bež" },
prices: [{ currency_code: "bam", amount: 820.00 }, { currency_code: "eur", amount: 419.00 }],
},
],
},
{
title: "Vertikalna Padajuća Tenda",
subtitle: "Vertikalni rolo sistem za bočno zatvaranje balkona, lođa i ugostiteljskih terasa",
handle: "vertikalna-tenda",
status: "published",
shipping_profile_id: defaultShippingProfile?.id,
sales_channels: [{ id: channelBA.id }],
category_ids: [catTende.id],
images: [
{ url: "https://suman.ba/assets/photos/products/original/1557425258-vertikalna.jpg" },
],
thumbnail: "https://suman.ba/assets/photos/products/original/1557425258-vertikalna.jpg",
metadata: {
system: "Bočne inox sajle ili aluminijske vodilice sa španerima za vjetar",
insulation: "Efikasna zaštita od kiše, vjetra i prašine",
},
options: [
{ title: "Dimenzija (Š x V)", values: ["2.5x2.5m", "3x2.8m", "4x3m"] },
{ title: "Tip platna", values: ["Providni PVC kristal (prozorski)", "Screen mrežasto platno", "Akrilno neprozirno platno"] },
],
variants: [
{
title: "2.5x2.5m / Providni PVC kristal",
sku: "VER-25-PVC",
options: { "Dimenzija (Š x V)": "2.5x2.5m", "Tip platna": "Providni PVC kristal (prozorski)" },
prices: [{ currency_code: "bam", amount: 420.00 }, { currency_code: "eur", amount: 214.00 }],
},
{
title: "3x2.8m / Screen mrežasto platno",
sku: "VER-328-SCR",
options: { "Dimenzija (Š x V)": "3x2.8m", "Tip platna": "Screen mrežasto platno" },
prices: [{ currency_code: "bam", amount: 560.00 }, { currency_code: "eur", amount: 286.00 }],
},
],
},
{
title: "Kupolasta Tenda",
subtitle: "Dekorativna polukružna tenda za izloge, prozore, ulaze hotela i restorana",
handle: "kupolasta-tenda",
status: "published",
shipping_profile_id: defaultShippingProfile?.id,
sales_channels: [{ id: channelBA.id }],
category_ids: [catTende.id],
images: [
{ url: "https://suman.ba/assets/photos/products/original/1557425283-kupolasta.jpg" },
],
thumbnail: "https://suman.ba/assets/photos/products/original/1557425283-kupolasta.jpg",
metadata: {
frame: "Savijeni aluminijski profili sa pregibnim zglobovima",
branding: "Mogućnost štampe natpisa i logotipa na čeonom volanu",
},
options: [
{ title: "Širina", values: ["2m (kugla R=1m)", "2.5m", "3m", "4m"] },
{ title: "Boja platna", values: ["Bordo Crvena", "Tamno Plava", "Zelena", "Topla Bež"] },
],
variants: [
{
title: "2m / Bordo Crvena",
sku: "KUP-20-BOR",
options: { Širina: "2m (kugla R=1m)", "Boja platna": "Bordo Crvena" },
prices: [{ currency_code: "bam", amount: 390.00 }, { currency_code: "eur", amount: 199.00 }],
},
{
title: "3m / Tamno Plava",
sku: "KUP-30-BLU",
options: { Širina: "3m", "Boja platna": "Tamno Plava" },
prices: [{ currency_code: "bam", amount: 520.00 }, { currency_code: "eur", amount: 266.00 }],
},
],
},
]
await createProductsWorkflow(container).run({
input: {
products: sumanProducts,
},
})
logger.info(`Uspješno uvezeno svih ${sumanProducts.length} zvaničnih Suman proizvoda!`)
logger.info("==========================================================")
logger.info("KONFIGURACIJA ZA VAŠ STOREFRONT (.env.local):")
logger.info(`NEXT_PUBLIC_MEDUSA_PUBLISHABLE_KEY=${keyBA.token}`)
logger.info(`NEXT_PUBLIC_DEFAULT_REGION=ba`)
logger.info("==========================================================")
}

View File

@@ -0,0 +1,165 @@
import { ExecArgs } from "@medusajs/framework/types"
import { ContainerRegistrationKeys } from "@medusajs/framework/utils"
import {
createSalesChannelsWorkflow,
createStockLocationsWorkflow,
linkSalesChannelsToStockLocationWorkflow,
linkProductsToSalesChannelWorkflow,
linkSalesChannelsToApiKeyWorkflow,
createApiKeysWorkflow,
createRegionsWorkflow,
} from "@medusajs/medusa/core-flows"
export default async function setupSumanHr({ container }: ExecArgs) {
const logger = container.resolve(ContainerRegistrationKeys.LOGGER)
const query = container.resolve(ContainerRegistrationKeys.QUERY)
logger.info("==========================================================")
logger.info("POKREĆEM SETUP: ŠUMAN D.O.O. - HRVATSKA (suman-hrvatska)")
logger.info("==========================================================")
// 1. Dobavljanje master admin korisnika
const { data: users } = await query.graph({
entity: "user",
fields: ["id", "email"],
filters: { email: "admin@suncobrani.com" },
})
const adminUser = users[0]
if (!adminUser) {
throw new Error("Admin korisnik admin@suncobrani.com nije pronađen.")
}
// 2. Postavljanje regije Hrvatska (HR / EUR)
logger.info("1. Konfiguracija regije Hrvatska (valuta EUR, kod hr)...")
const { data: existingRegions } = await query.graph({
entity: "region",
fields: ["id", "name", "currency_code"],
filters: { name: "Hrvatska" },
})
let regionHR = existingRegions[0]
if (!regionHR) {
const { result: createdRegions } = await createRegionsWorkflow(container).run({
input: {
regions: [
{
name: "Hrvatska",
currency_code: "eur",
countries: ["hr"],
payment_providers: ["pp_system_default"],
},
],
},
})
regionHR = createdRegions[0]
logger.info(`Kreirana regija: ${regionHR.name} [ID: ${regionHR.id}] sa valutom EUR.`)
} else {
logger.info(`Regija Hrvatska već postoji [ID: ${regionHR.id}].`)
}
// 3. Kreiranje prodajnog kanala za Hrvatsku
logger.info("2. Kreiranje prodajnog kanala Suman Hrvatska...")
const { data: existingChannels } = await query.graph({
entity: "sales_channel",
fields: ["id", "name"],
filters: { name: "Suman d.o.o. - Hrvatska" },
})
let channelHR = existingChannels[0]
if (!channelHR) {
const { result: createdChannels } = await createSalesChannelsWorkflow(container).run({
input: {
salesChannelsData: [
{
name: "Suman d.o.o. - Hrvatska",
description: "Zvanični prodajni kanal za tržište Republike Hrvatske (suman.hr)",
},
],
},
})
channelHR = createdChannels[0]
}
logger.info(`Prodajni kanal: ${channelHR.name} [ID: ${channelHR.id}]`)
// 4. Kreiranje skladišta Zagreb i povezivanje sa kanalom
logger.info("3. Povezivanje skladišta Suman Zagreb sa kanalom...")
const { data: existingLocs } = await query.graph({
entity: "stock_location",
fields: ["id", "name"],
filters: { name: "Distributivni Centar Suman Zagreb (HR)" },
})
let locZagreb = existingLocs[0]
if (!locZagreb) {
const { result: createdLocations } = await createStockLocationsWorkflow(container).run({
input: {
locations: [{ name: "Distributivni Centar Suman Zagreb (HR)" }],
},
})
locZagreb = createdLocations[0]
}
try {
await linkSalesChannelsToStockLocationWorkflow(container).run({
input: {
id: locZagreb.id,
add: [channelHR.id],
},
})
logger.info("Skladište Zagreb uspješno povezano sa kanalom Hrvatska.")
} catch (e: any) {
logger.warn(`Veza skladišta i kanala: ${e.message}`)
}
// 5. Povezivanje svih 12 Suman proizvoda sa novim kanalom
logger.info("4. Dodjela svih Suman proizvoda prodajnom kanalu Hrvatska...")
const { data: products } = await query.graph({
entity: "product",
fields: ["id", "title"],
})
if (products.length > 0) {
const productIds = products.map((p) => p.id)
await linkProductsToSalesChannelWorkflow(container).run({
input: {
id: channelHR.id,
add: productIds,
},
})
logger.info(`Uspješno povezano svih ${productIds.length} proizvoda sa kanalom Suman Hrvatska.`)
}
// 6. Generisanje novog Publishable API ključa za Hrvatsku
logger.info("5. Generisanje Publishable API ključa za Hrvatsku...")
const { result: apiKeys } = await createApiKeysWorkflow(container).run({
input: {
api_keys: [
{
title: "Storefront HR (suman.hr)",
type: "publishable",
created_by: adminUser.id,
},
],
},
})
const keyHR = apiKeys[0]
await linkSalesChannelsToApiKeyWorkflow(container).run({
input: {
id: keyHR.id,
add: [channelHR.id],
},
})
logger.info("==========================================================")
logger.info(`Kreiran novi Publishable API ključ za Hrvatsku: ${keyHR.token}`)
logger.info(`Sales Channel ID: ${channelHR.id}`)
logger.info(`Region ID: ${regionHR.id}`)
logger.info("==========================================================")
logger.info("KONFIGURACIJA ZA VAŠ NOVI STOREFRONT (.env.local):")
logger.info(`NEXT_PUBLIC_MEDUSA_PUBLISHABLE_KEY=${keyHR.token}`)
logger.info(`NEXT_PUBLIC_DEFAULT_REGION=hr`)
logger.info(`PORT=8002`)
logger.info("==========================================================")
}

View File

@@ -0,0 +1,285 @@
import { ExecArgs } from "@medusajs/framework/types"
import { ContainerRegistrationKeys, MedusaError } from "@medusajs/framework/utils"
import {
createSalesChannelsWorkflow,
createStockLocationsWorkflow,
linkSalesChannelsToStockLocationWorkflow,
linkSalesChannelsToApiKeyWorkflow,
createApiKeysWorkflow,
createCustomerGroupsWorkflow,
createProductsWorkflow,
createUsersWorkflow,
} from "@medusajs/medusa/core-flows"
export default async function setupUmbrellaPlatform({ container }: ExecArgs) {
const logger = container.resolve(ContainerRegistrationKeys.LOGGER)
const query = container.resolve(ContainerRegistrationKeys.QUERY)
logger.info("==================================================")
logger.info("Pokrećem automatizovano postavljanje platforme...")
logger.info("==================================================")
// 0. Dobavljanje master admin korisnika za created_by polja
const { data: users } = await query.graph({
entity: "user",
fields: ["id", "email"],
filters: { email: "admin@suncobrani.com" },
})
const adminUser = users[0]
if (!adminUser) {
throw new MedusaError(
MedusaError.Types.NOT_FOUND,
"Admin korisnik admin@suncobrani.com nije pronađen. Kreirajte ga prvo."
)
}
// Dobavljanje podrazumijevanog shipping profila
const { data: shippingProfiles } = await query.graph({
entity: "shipping_profile",
fields: ["id", "type"],
})
const defaultShippingProfile = shippingProfiles[0]
// 1. PROVJERA ILI KREIRANJE PRODAJNIH KANALA (Sales Channels)
const { data: existingChannels } = await query.graph({
entity: "sales_channel",
fields: ["id", "name"],
filters: { name: ["Suncobrani DE (Njemačka)", "Suncobrani AT (Austrija)"] },
})
let channelDE: any = existingChannels.find((c: any) => c.name.includes("DE"))
let channelAT: any = existingChannels.find((c: any) => c.name.includes("AT"))
if (!channelDE || !channelAT) {
const toCreate: { name: string; description: string }[] = []
if (!channelDE) {
toCreate.push({
name: "Suncobrani DE (Njemačka)",
description: "Zvanični prodajni kanal za njemačko tržište",
})
}
if (!channelAT) {
toCreate.push({
name: "Suncobrani AT (Austrija)",
description: "Zvanični prodajni kanal za austrijsko tržište",
})
}
const { result: createdChannels } = await createSalesChannelsWorkflow(container).run({
input: {
salesChannelsData: toCreate,
},
})
createdChannels.forEach((c: any) => {
if (c.name.includes("DE")) channelDE = c
if (c.name.includes("AT")) channelAT = c
})
}
logger.info(`Kanal DE: ${channelDE!.name} [ID: ${channelDE!.id}]`)
logger.info(`Kanal AT: ${channelAT!.name} [ID: ${channelAT!.id}]`)
// 2. PROVJERA ILI KREIRANJE SKLADIŠNIH LOKACIJA (Stock Locations)
const { data: existingLocations } = await query.graph({
entity: "stock_location",
fields: ["id", "name"],
filters: { name: ["Centralni Magacin Minhen (DE)", "Distributivni Centar Beč (AT)"] },
})
let locDE: any = existingLocations.find((l: any) => l.name.includes("Minhen"))
let locAT: any = existingLocations.find((l: any) => l.name.includes("Beč"))
if (!locDE || !locAT) {
const locsToCreate: { name: string }[] = []
if (!locDE) locsToCreate.push({ name: "Centralni Magacin Minhen (DE)" })
if (!locAT) locsToCreate.push({ name: "Distributivni Centar Beč (AT)" })
const { result: createdLocations } = await createStockLocationsWorkflow(container).run({
input: {
locations: locsToCreate,
},
})
createdLocations.forEach((l: any) => {
if (l.name.includes("Minhen")) locDE = l
if (l.name.includes("Beč")) locAT = l
})
}
logger.info(`Lokacija DE: ${locDE!.name} [ID: ${locDE!.id}]`)
logger.info(`Lokacija AT: ${locAT!.name} [ID: ${locAT!.id}]`)
// 3. POVEZIVANJE SKLADIŠTA SA PRODAJNIM KANALIMA (Rješava 'Out of stock' grešku)
try {
await linkSalesChannelsToStockLocationWorkflow(container).run({
input: {
id: locDE!.id,
add: [channelDE!.id],
},
})
await linkSalesChannelsToStockLocationWorkflow(container).run({
input: {
id: locAT!.id,
add: [channelAT!.id],
},
})
logger.info("Uspješno povezana skladišta sa prodajnim kanalima.")
} catch (err: any) {
logger.warn(`Povezivanje skladišta i kanala: ${err.message}`)
}
// 4. KREIRANJE PUBLISHABLE API KLJUČEVA I DODJELA KANALIMA
const { result: apiKeys } = await createApiKeysWorkflow(container).run({
input: {
api_keys: [
{
title: `Storefront DE Public Key`,
type: "publishable",
created_by: adminUser.id,
},
{
title: `Storefront AT Public Key`,
type: "publishable",
created_by: adminUser.id,
},
],
},
})
const [keyDE, keyAT] = apiKeys
await linkSalesChannelsToApiKeyWorkflow(container).run({
input: {
id: keyDE.id,
add: [channelDE!.id],
},
})
await linkSalesChannelsToApiKeyWorkflow(container).run({
input: {
id: keyAT.id,
add: [channelAT!.id],
},
})
// 5. KREIRANJE B2B CUSTOMER GRUPE (Za HoReCa kupce)
const { data: existingGroups } = await query.graph({
entity: "customer_group",
fields: ["id", "name"],
filters: { name: "HoReCa B2B Partneri" },
})
let b2bGroup: any = existingGroups[0]
if (!b2bGroup) {
const { result: customerGroups } = await createCustomerGroupsWorkflow(container).run({
input: {
customersData: [
{
name: "HoReCa B2B Partneri",
metadata: {
description: "Verifikovani hoteli, restorani i kafići sa veleprodajnim cijenama",
},
},
],
},
})
b2bGroup = customerGroups[0]
}
logger.info(`B2B grupa: ${b2bGroup.name} [ID: ${b2bGroup.id}]`)
// 6. KREIRANJE REGIONALNIH ADMIN KORISNIKA SA IZOLACIJOM
try {
await createUsersWorkflow(container).run({
input: {
users: [
{
email: "admin.de@suncobrani.com",
first_name: "Klaus",
last_name: "Schmidt (DE Admin)",
metadata: { sales_channel_id: channelDE!.id },
},
{
email: "admin.at@suncobrani.com",
first_name: "Stefan",
last_name: "Weber (AT Admin)",
metadata: { sales_channel_id: channelAT!.id },
},
],
},
})
logger.info("Kreirani regionalni admin nalozi sa dodijeljenim prodajnim kanalima.")
} catch (err: any) {
logger.warn(`Admin nalozi: ${err.message}`)
}
// 7. SEED KATALOGA SUNCOBRANA SA TEHNIČKIM SPECIFIKACIJAMA
const { data: existingProducts } = await query.graph({
entity: "product",
fields: ["id", "handle"],
filters: { handle: "gastro-master-suncobran" },
})
if (existingProducts.length === 0) {
await createProductsWorkflow(container).run({
input: {
products: [
{
title: "Teleskopski Ugostiteljski Suncobran 'Gastro Master'",
subtitle: "Ekstremno otporan na vjetar sa integrisanim teleskopskim mehanizmom iznad stolova",
handle: "gastro-master-suncobran",
status: "published",
shipping_profile_id: defaultShippingProfile?.id,
sales_channels: [{ id: channelDE!.id }, { id: channelAT!.id }],
metadata: {
uv_protection: "UPF 50+ (EN 13758-1 standard)",
wind_resistance: "Klasa 6 Beaufort (do 60 km/h u otvorenom stanju)",
fabric_weight: "320 g/m² 100% obojeni akril sa Nano-teflon zaštitom",
water_column: "1200 mm",
mast_diameter: "Ø 60 mm debljina stijenke 3.5 mm ojačani aluminijum",
warranty_years: "5 godina garancije na mehanizam i postojanost boje",
},
options: [
{ title: "Dimenzija", values: ["3x3m", "4x4m"] },
{ title: "Boja platna", values: ["Antracit Siva (RAL 7016)", "Prirodna Bež"] },
],
variants: [
{
title: "3x3m / Antracit Siva",
sku: "GM-33-ANT",
options: { Dimenzija: "3x3m", "Boja platna": "Antracit Siva (RAL 7016)" },
prices: [{ currency_code: "eur", amount: 550.00 }],
},
{
title: "4x4m / Antracit Siva",
sku: "GM-44-ANT",
options: { Dimenzija: "4x4m", "Boja platna": "Antracit Siva (RAL 7016)" },
prices: [{ currency_code: "eur", amount: 790.00 }],
},
{
title: "3x3m / Prirodna Bež",
sku: "GM-33-BEZ",
options: { Dimenzija: "3x3m", "Boja platna": "Prirodna Bež" },
prices: [{ currency_code: "eur", amount: 550.00 }],
},
{
title: "4x4m / Prirodna Bež",
sku: "GM-44-BEZ",
options: { Dimenzija: "4x4m", "Boja platna": "Prirodna Bež" },
prices: [{ currency_code: "eur", amount: 790.00 }],
},
],
},
],
},
})
logger.info("Seed kataloga suncobrana uspješno završen.")
} else {
logger.info("Proizvod 'gastro-master-suncobran' već postoji.")
}
logger.info("==================================================")
logger.info("NOVI GENERISANI PUBLISHABLE API KLJUČEVI:")
logger.info(`Storefront DE Key: ${keyDE.token}`)
logger.info(`Storefront AT Key: ${keyAT.token}`)
logger.info("==================================================")
}

View File

@@ -0,0 +1,68 @@
import { ExecArgs } from "@medusajs/framework/types"
import { ContainerRegistrationKeys, Modules } from "@medusajs/framework/utils"
import { updateProductsWorkflow } from "@medusajs/medusa/core-flows"
export default async function updateProductScenarios({ container }: ExecArgs) {
const logger = container.resolve(ContainerRegistrationKeys.LOGGER)
const query = container.resolve(ContainerRegistrationKeys.QUERY)
logger.info("==========================================================")
logger.info("AŽURIRANJE PRODAJNIH SCENARIJA I UPITA (SUMAN)")
logger.info("==========================================================")
const { data: products } = await query.graph({
entity: "product",
fields: ["id", "title", "handle", "metadata"],
})
logger.info(`Pronađeno ${products.length} proizvoda za ažuriranje scenarija.`)
const updates = products.map((product) => {
const handle = product.handle || ""
const currentMeta = (product.metadata || {}) as Record<string, unknown>
const isPergola = handle.includes("pergola") || handle.includes("bioklimatska")
const isTenda = handle.includes("tenda") || handle.includes("atika") || handle.includes("zglobna")
const isSuncobran = handle.includes("suncobran") || handle.includes("plaza")
if (isPergola || isTenda) {
// Scenarij 2: Isključivo na upit (Quote only)
return {
id: product.id,
metadata: {
...currentMeta,
sale_scenario: "quote_only",
quote_subtitle: isPergola
? "Bioklimatski i aluminijski sistemi po mjeri sa profesionalnom montažom"
: "Zglobne i kasetne tende po mjeri terase sa garancijom",
allow_customization: false,
},
}
} else {
// Scenarij 1: Suncobrani (1a: Sa lagera ili 1b: Po narudžbi sa konfiguratorom)
const isPrestige = handle.includes("prestige")
return {
id: product.id,
metadata: {
...currentMeta,
sale_scenario: isPrestige ? "made_to_order" : "in_stock",
lead_time_days: isPrestige ? 14 : undefined,
allow_customization: true,
badge: isPrestige ? "Po narudžbi (14 dana)" : "Na lageru",
},
}
}
})
await updateProductsWorkflow(container).run({
input: {
products: updates,
},
})
logger.info("Uspješno ažurirani prodajni scenariji za sve proizvode!")
updates.forEach((u) => {
logger.info(`- ID: ${u.id} | Scenario: ${(u.metadata as any).sale_scenario}`)
})
}

View File

@@ -0,0 +1,29 @@
export type ProductOptionRow = {
title?: string | null;
values?: ({ value?: string | null } | null)[] | null;
} | null;
/**
* Flattens a product's options into `"<option title>:<value>"` entries, e.g.
* `["Size:S", "Color:Red"]`. One field keeps the index simple; the storefront
* splits on the first `:` to group the facet by option name.
*/
export function toOptionValues(
options: ProductOptionRow[] | null | undefined,
): string[] {
const flattened = (options ?? []).flatMap((option) => {
const title = option?.title?.trim();
if (!title) {
return [];
}
return (option?.values ?? [])
.map((optionValue) => optionValue?.value?.trim())
.filter((value): value is string => Boolean(value))
.map((value) => `${title}:${value}`);
});
// A value shared by several options would otherwise be counted twice.
return Array.from(new Set(flattened));
}

View File

@@ -0,0 +1,176 @@
import type { SearchTypes } from "@medusajs/framework/types";
import { QueryContext, search } from "@medusajs/framework/utils";
/**
* The currencies the index holds prices in. Each gets its own set of price
* fields, so filtering and sorting work per currency. Adding one is a schema
* change: the module reindexes on the next boot. Keep in sync with the
* storefront's `SEARCH_PRICE_CURRENCIES`.
*/
export const PRICE_CURRENCIES = ["eur", "usd"] as const;
export type PriceCurrency = (typeof PRICE_CURRENCIES)[number];
// Read once per currency, since the Pricing Module calculates for a single
// currency per query.
const PRICE_GRAPH_FIELDS = [
"id",
"variants.calculated_price.calculated_amount",
"variants.calculated_price.original_amount",
];
const pricingContext = (currency: PriceCurrency) => ({
variants: {
calculated_price: QueryContext({ currency_code: currency }),
},
});
type PricedVariant = {
calculated_price?: {
calculated_amount?: number | null;
original_amount?: number | null;
} | null;
[key: string]: unknown;
} | null;
/** A product's priced variants per currency, as `loadPricing` reads them. */
export type ProductPricingRows = Partial<
Record<PriceCurrency, PricedVariant[] | null>
>;
type PriceFieldName =
`${"min_price" | "max_price" | "original_price"}_${PriceCurrency}`;
type OnSaleFieldName = `on_sale_${PriceCurrency}`;
export type ProductPricing = { [K in PriceFieldName]?: number | null } & {
[K in OnSaleFieldName]?: boolean | null;
};
type PriceFields = {
[K in PriceFieldName]: ReturnType<typeof search.float>;
} & { [K in OnSaleFieldName]: ReturnType<typeof search.boolean> };
/** The per-currency price fields, to spread into the index schema. */
export const priceFields = Object.fromEntries(
PRICE_CURRENCIES.flatMap((currency) => [
[
`min_price_${currency}`,
search
.float()
.filterable()
.sortable()
.facetable({ types: ["stats"] })
.retrievable(),
],
[
`max_price_${currency}`,
search
.float()
.filterable()
.sortable()
.facetable({ types: ["stats"] })
.retrievable(),
],
[`original_price_${currency}`, search.float().retrievable()],
[
`on_sale_${currency}`,
search.boolean().filterable().facetable().retrievable(),
],
]),
) as PriceFields;
/**
* One currency's price fields: the cheapest variant's calculated and original
* price, and the most expensive variant's as the max. Picking one variant for
* the pair keeps the discount describing a real product rather than mixing
* two variants' amounts. A product without a price in the currency writes
* nothing, so it drops out of that currency's price filter and sort.
*/
function toPricing(
currency: PriceCurrency,
variants: PricedVariant[] | null | undefined,
): ProductPricing {
let cheapest: { calculated: number; original: number } | undefined;
let maxPrice: number | undefined;
for (const variant of variants ?? []) {
const price = variant?.calculated_price;
const calculated = price?.calculated_amount;
if (typeof calculated !== "number") {
continue;
}
const original =
typeof price?.original_amount === "number"
? price.original_amount
: calculated;
if (maxPrice === undefined || calculated > maxPrice) {
maxPrice = calculated;
}
if (!cheapest || calculated < cheapest.calculated) {
cheapest = { calculated, original };
}
}
if (!cheapest) {
return {};
}
return {
[`min_price_${currency}`]: cheapest.calculated,
[`max_price_${currency}`]: maxPrice ?? cheapest.calculated,
[`original_price_${currency}`]: cheapest.original,
// Written even when false: "not on sale" is a real facet bucket, unlike a
// missing value.
[`on_sale_${currency}`]: cheapest.original > cheapest.calculated,
} as ProductPricing;
}
/** Every currency's price fields for one product. */
export function toProductPricing(
pricingRows: ProductPricingRows | undefined,
): ProductPricing {
return Object.assign(
{},
...PRICE_CURRENCIES.map((currency) =>
toPricing(currency, pricingRows?.[currency]),
),
);
}
/**
* The priced variants of the given products, per currency: one `query.graph`
* read per currency, however many products there are.
*/
export async function loadPricing(
ids: string[],
{ container }: SearchTypes.SearchIngestionContext,
): Promise<Map<string, ProductPricingRows>> {
const pricing = new Map<string, ProductPricingRows>();
if (!ids.length) {
return pricing;
}
await Promise.all(
PRICE_CURRENCIES.map(async (currency) => {
const { data } = await container.query.graph({
entity: "product",
fields: PRICE_GRAPH_FIELDS,
filters: { id: ids },
context: pricingContext(currency),
});
for (const product of data) {
const rows = pricing.get(product.id) ?? {};
rows[currency] = product.variants as PricedVariant[] | null;
pricing.set(product.id, rows);
}
}),
);
return pricing;
}

View File

@@ -0,0 +1,141 @@
import type {
RemoteQueryFunction,
SearchTypes,
} from "@medusajs/framework/types";
const RESOLVE_BATCH_SIZE = 200;
// Core emits either a single `{ id }` or a batch of them.
function payloadIds(data: unknown): string[] {
return (Array.isArray(data) ? data : [data])
.map((entry) => (entry as { id?: string } | undefined)?.id)
.filter((id): id is string => Boolean(id));
}
/**
* The products behind rows of another entity, read through `query.graph`.
* Deleted rows are soft-deleted, so they're still readable with `withDeleted`,
* which is how a deleted variant or category still leads back to its products.
*/
async function relatedProductIds(
query: RemoteQueryFunction,
entity: string,
fields: string[],
ids: string[],
pick: (row: Record<string, any>) => (string | null | undefined)[],
withDeleted: boolean,
): Promise<string[]> {
const { data } = await query.graph({
entity,
fields,
filters: { id: ids },
withDeleted,
});
return (data as Record<string, any>[])
.flatMap(pick)
.filter((id): id is string => Boolean(id));
}
/**
* Deleting a sales channel removes its product links, so the products can no
* longer be found through `query.graph`. The index still holds the channel on
* each document, which is what's searched here.
*/
async function productIdsInSalesChannels(
query: RemoteQueryFunction,
salesChannelIds: string[],
): Promise<string[]> {
const ids: string[] = [];
let skip = 0;
while (true) {
const { search_result: result } = await query.search({
entity: "product",
fields: ["id"],
filters: { sales_channel_ids: salesChannelIds },
pagination: { skip, take: RESOLVE_BATCH_SIZE },
});
ids.push(...result.hits.map((hit) => hit.id));
if (result.hits.length < RESOLVE_BATCH_SIZE) {
return ids;
}
skip += RESOLVE_BATCH_SIZE;
}
}
/**
* The products an event affects. A product event carries them directly; an
* event about a variant, option, tag, category or sales channel is mapped to
* the products behind it.
*/
export async function resolveProductIds(
event: { name: string; data: unknown },
{ container: { query } }: SearchTypes.SearchIngestionContext,
): Promise<string[]> {
const ids = payloadIds(event.data);
if (!ids.length) {
return [];
}
const [entity] = event.name.split(".");
const deleted = event.name.endsWith(".deleted");
switch (entity) {
case "product":
return ids;
case "product-variant":
return relatedProductIds(
query,
"product_variant",
["product_id"],
ids,
(row) => [row.product_id],
deleted,
);
case "product-option":
return relatedProductIds(
query,
"product_option",
["product_id"],
ids,
(row) => [row.product_id],
deleted,
);
case "product-option-value":
return relatedProductIds(
query,
"product_option_value",
["option.product_id"],
ids,
(row) => [row.option?.product_id],
deleted,
);
case "product-tag":
return relatedProductIds(
query,
"product_tag",
["products.id"],
ids,
(row) => (row.products ?? []).map((product: any) => product?.id),
deleted,
);
case "product-category":
return relatedProductIds(
query,
"product_category",
["products.id"],
ids,
(row) => (row.products ?? []).map((product: any) => product?.id),
deleted,
);
case "sales-channel":
return productIdsInSalesChannels(query, ids);
default:
return [];
}
}

View File

@@ -0,0 +1,165 @@
import type { SearchTypes } from "@medusajs/framework/types";
import {
defineSearchIndex,
graphConsume,
graphSeed,
search,
} from "@medusajs/framework/utils";
import { ProductOptionRow, toOptionValues } from "./helpers/option-values";
import { loadPricing, priceFields, toProductPricing } from "./helpers/pricing";
import { resolveProductIds } from "./helpers/resolve-product-ids";
const PRODUCT_GRAPH_FIELDS = [
"id",
"title",
"description",
"handle",
"thumbnail",
"status",
"created_at",
"sales_channels.id",
"categories.name",
"tags.value",
"options.title",
"options.values.value",
];
type ProductRow = {
id: string;
title?: string | null;
description?: string | null;
handle?: string | null;
thumbnail?: string | null;
status?: string | null;
created_at?: string | Date | null;
deleted_at?: string | Date | null;
sales_channels?: ({ id?: string | null } | null)[] | null;
categories?: ({ name?: string | null } | null)[] | null;
tags?: ({ value?: string | null } | null)[] | null;
options?: ProductOptionRow[] | null;
};
const productFields = search.define({
id: search.keyword().filterable().retrievable(),
// Read by `/store/search` to scope the index; never returned to hits.
status: search.keyword().filterable().retrievable(false),
sales_channel_ids: search.keyword().array().filterable().retrievable(false),
title: search.text().searchable({ weight: 3 }).sortable().retrievable(),
description: search.text().searchable({ weight: 1 }),
handle: search.keyword().retrievable(),
// Returned on hits only: never filtered, sorted or faceted on.
thumbnail: search.keyword().retrievable(),
created_at: search.date().sortable().retrievable(),
category: search.keyword().array().filterable().facetable().retrievable(),
labels: search.keyword().array().filterable().facetable().retrievable(),
option_values: search
.keyword()
.array()
.searchable({ weight: 2 })
.filterable()
.facetable()
.retrievable(),
...priceFields,
});
type ProductDocument = SearchTypes.InferSearchDocumentType<
typeof productFields
>;
function toDocument(
product: ProductRow,
pricing: Parameters<typeof toProductPricing>[0],
): ProductDocument {
const category = (product.categories ?? [])
.map((productCategory) => productCategory?.name?.trim())
.filter((name): name is string => Boolean(name));
const labels = (product.tags ?? [])
.map((tag) => tag?.value?.trim())
.filter((value): value is string => Boolean(value));
const salesChannelIds = (product.sales_channels ?? [])
.map((salesChannel) => salesChannel?.id?.trim())
.filter((id): id is string => Boolean(id));
return {
id: product.id,
status: product.status ?? null,
sales_channel_ids: salesChannelIds,
title: product.title ?? null,
description: product.description ?? null,
handle: product.handle ?? null,
thumbnail: product.thumbnail ?? null,
created_at: product.created_at ?? null,
category,
labels,
option_values: toOptionValues(product.options),
...toProductPricing(pricing),
};
}
/**
* A row that returns no document leaves
* the index: the helpers turn it into a delete on `consume` and on the
* catch-up pass.
*/
const source = {
fields: PRODUCT_GRAPH_FIELDS,
transform: async (
rows: ProductRow[],
context: SearchTypes.SearchIngestionContext,
) => {
const pricing = await loadPricing(
rows.map((row) => row.id),
context,
);
return rows.map((row) => toDocument(row, pricing.get(row.id)));
},
};
/**
* Everything a document is built from, so a change to any of it re-indexes the
* products it touches. Only `product.deleted` removes documents: a deleted
* variant, option, tag or category means the product has to be re-read.
*
* TODO: price lists emit no events (create, update, delete, batch prices).
* TODO: price lists crossing their start or end date change prices silently.
* TODO: linkProductsToSalesChannelWorkflow emits nothing.
* TODO: batchLinkProductsToCategoryWorkflow emits nothing.
* TODO: upsertVariantPricesWorkflow emits nothing when called directly.
*/
const PRODUCT_EVENTS = [
"product.created",
"product.updated",
"product.deleted",
"product-variant.created",
"product-variant.updated",
"product-variant.deleted",
"product-option.created",
"product-option.updated",
"product-option.deleted",
"product-option-value.updated",
"product-option-value.deleted",
"product-tag.updated",
"product-tag.deleted",
"product-category.updated",
"product-category.deleted",
"sales-channel.deleted",
];
export default defineSearchIndex({
name: "product",
entity: "product",
primary_key: "id",
fields: productFields,
settings: {
typo_tolerance: { enabled: true },
},
events: PRODUCT_EVENTS,
consume: graphConsume<typeof productFields, ProductRow>({
...source,
resolve_ids: resolveProductIds,
is_delete: (event) => event.name === "product.deleted",
}),
seed: graphSeed<typeof productFields, ProductRow>(source),
});

View File

@@ -0,0 +1,61 @@
# Custom subscribers
Subscribers handle events emitted in the Medusa application.
> Learn more about Subscribers in [this documentation](https://docs.medusajs.com/learn/fundamentals/events-and-subscribers).
The subscriber is created in a TypeScript or JavaScript file under the `src/subscribers` directory.
For example, create the file `src/subscribers/product-created.ts` with the following content:
```ts
import {
type SubscriberConfig,
} from "@medusajs/framework"
// subscriber function
export default async function productCreateHandler() {
console.log("A product was created")
}
// subscriber config
export const config: SubscriberConfig = {
event: "product.created",
}
```
A subscriber file must export:
- The subscriber function that is an asynchronous function executed whenever the associated event is triggered.
- A configuration object defining the event this subscriber is listening to.
## Subscriber Parameters
A subscriber receives an object having the following properties:
- `event`: An object holding the event's details. It has a `data` property, which is the event's data payload.
- `container`: The Medusa container. Use it to resolve modules' main services and other registered resources.
```ts
import type {
SubscriberArgs,
SubscriberConfig,
} from "@medusajs/framework"
export default async function productCreateHandler({
event: { data },
container,
}: SubscriberArgs<{ id: string }>) {
const productId = data.id
const productModuleService = container.resolve("product")
const product = await productModuleService.retrieveProduct(productId)
console.log(`The product ${product.title} was created`)
}
export const config: SubscriberConfig = {
event: "product.created",
}
```

View File

@@ -0,0 +1,82 @@
import { SubscriberArgs, type SubscriberConfig } from "@medusajs/framework"
import { ContainerRegistrationKeys, Modules } from "@medusajs/framework/utils"
export default async function b2bOrderCrmHandler({
event: { data },
container,
}: SubscriberArgs<{ id: string }>) {
const logger = container.resolve(ContainerRegistrationKeys.LOGGER)
const orderService = container.resolve(Modules.ORDER)
const customerService = container.resolve(Modules.CUSTOMER)
try {
const order = await orderService.retrieveOrder(data.id, {
relations: ["customer", "items", "shipping_address"],
})
if (!order.customer_id) {
return
}
const customer = await customerService.retrieveCustomer(order.customer_id)
const metadata = (customer.metadata || {}) as Record<string, any>
// Sinkronizacija se vrši samo za B2B kupce (imaju PIB ili status verifikacije)
const isB2BCustomer = Boolean(metadata.pib || metadata.verification_status === "verified")
if (isB2BCustomer) {
logger.info(`Sinkronizujem B2B narudžbu ${order.id} prema CRM sistemu...`)
const crmWebhookUrl = process.env.CRM_WEBHOOK_URL
if (!crmWebhookUrl) {
logger.warn("CRM_WEBHOOK_URL nije definisan u .env datoteci.")
return
}
const payload = {
event: "b2b_order_placed",
order_id: order.id,
sales_channel_id: order.sales_channel_id,
total_amount: order.total,
currency_code: order.currency_code,
customer: {
id: customer.id,
email: customer.email,
company_name: metadata.company_name || null,
pib_oib: metadata.pib || null,
verification_status: metadata.verification_status || "pending",
agent_notes: metadata.agent_notes || null,
},
items: (order.items || []).map((item) => ({
title: item.title,
sku: item.variant_sku || "",
quantity: item.quantity,
unit_price: item.unit_price,
})),
created_at: new Date().toISOString(),
}
const response = await fetch(crmWebhookUrl, {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${process.env.CRM_API_KEY || ""}`,
},
body: JSON.stringify(payload),
})
if (response.ok) {
logger.info(`B2B narudžba ${order.id} uspješno poslana na CRM webhook.`)
} else {
logger.error(`CRM webhook je vratio status ${response.status}: ${await response.text()}`)
}
}
} catch (error: any) {
logger.error(`Greška u b2bOrderCrmHandler: ${error.message}`)
}
}
export const config: SubscriberConfig = {
event: "order.placed",
}

View File

@@ -0,0 +1,81 @@
# Custom Workflows
A workflow is a series of queries and actions that complete a task.
The workflow is created in a TypeScript or JavaScript file under the `src/workflows` directory.
> Learn more about workflows in [this documentation](https://docs.medusajs.com/learn/fundamentals/workflows).
For example:
```ts
import {
createStep,
createWorkflow,
WorkflowResponse,
StepResponse,
} from "@medusajs/framework/workflows-sdk"
const step1 = createStep("step-1", async () => {
return new StepResponse(`Hello from step one!`)
})
type WorkflowInput = {
name: string
}
const step2 = createStep(
"step-2",
async ({ name }: WorkflowInput) => {
return new StepResponse(`Hello ${name} from step two!`)
}
)
type WorkflowOutput = {
message1: string
message2: string
}
const helloWorldWorkflow = createWorkflow(
"hello-world",
(input: WorkflowInput) => {
const greeting1 = step1()
const greeting2 = step2(input)
return new WorkflowResponse({
message1: greeting1,
message2: greeting2
})
}
)
export default helloWorldWorkflow
```
## Execute Workflow
You can execute the workflow from other resources, such as API routes, scheduled jobs, or subscribers.
For example, to execute the workflow in an API route:
```ts
import type {
MedusaRequest,
MedusaResponse,
} from "@medusajs/framework"
import myWorkflow from "../../../workflows/hello-world"
export async function GET(
req: MedusaRequest,
res: MedusaResponse
) {
const { result } = await myWorkflow(req.scope)
.run({
input: {
name: req.query.name as string,
},
})
res.send(result)
}
```

View File

@@ -0,0 +1,99 @@
import {
createStep,
createWorkflow,
StepResponse,
WorkflowResponse,
transform,
} from "@medusajs/framework/workflows-sdk"
import { createRemoteLinkStep } from "@medusajs/medusa/core-flows"
import { Modules } from "@medusajs/framework/utils"
import { INQUIRY_MODULE } from "../../modules/inquiry"
export type CreateInquiryInput = {
name: string
email: string
phone: string
company_name?: string | null
city: string
dimensions?: string | null
message: string
product_id?: string | null
sales_channel_id?: string | null
metadata?: Record<string, unknown> | null
}
export const createInquiryStep = createStep(
"create-inquiry",
async (input: CreateInquiryInput, { container }) => {
const inquiryService = container.resolve(INQUIRY_MODULE)
const inquiry = await inquiryService.createInquiries(input)
return new StepResponse(inquiry, inquiry.id)
},
async (id: string, { container }) => {
const inquiryService = container.resolve(INQUIRY_MODULE)
await inquiryService.deleteInquiries(id)
}
)
export const createInquiryWorkflow = createWorkflow(
"create-inquiry",
(input: CreateInquiryInput) => {
const inquiry = createInquiryStep(input)
const links = transform({ inquiry, input }, ({ inquiry, input }) => {
const linkDefs: Array<Record<string, Record<string, string>>> = []
if (input.product_id) {
linkDefs.push({
[INQUIRY_MODULE]: { inquiry_id: inquiry.id },
[Modules.PRODUCT]: { product_id: input.product_id },
})
}
if (input.sales_channel_id) {
linkDefs.push({
[INQUIRY_MODULE]: { inquiry_id: inquiry.id },
[Modules.SALES_CHANNEL]: { sales_channel_id: input.sales_channel_id },
})
}
return linkDefs
})
createRemoteLinkStep(links)
return new WorkflowResponse(inquiry)
}
)
export type UpdateInquiryInput = {
id: string
status?: "new" | "contacted" | "quote_sent" | "won" | "lost" | "archived"
notes?: string | null
metadata?: Record<string, unknown> | null
}
export const updateInquiryStep = createStep(
"update-inquiry",
async (input: UpdateInquiryInput, { container }) => {
const inquiryService = container.resolve(INQUIRY_MODULE)
const prev = await inquiryService.retrieveInquiry(input.id)
const updated = await inquiryService.updateInquiries(input)
return new StepResponse(updated, prev)
},
async (prev: any, { container }) => {
if (!prev?.id) return
const inquiryService = container.resolve(INQUIRY_MODULE)
await inquiryService.updateInquiries(prev)
}
)
export const updateInquiryWorkflow = createWorkflow(
"update-inquiry",
(input: UpdateInquiryInput) => {
const updated = updateInquiryStep(input)
return new WorkflowResponse(updated)
}
)