# Freya Domain - Features

> Luxury Goods and Fashion Intelligence (`libs/freya/*`, `apps/freya/*`; TODO
> Phase 57)

Freya is the bounded context for luxury-goods businesses. It owns the operating
system that creates, manufactures, markets, sells, and analyzes fashion,
textile, beauty, jewelry, and accessory products: product lifecycle, collection
design, textile sourcing, beauty formulation, brand operations,
direct-to-consumer and diaspora ecommerce, manufacturing execution, retail-chain
operations, a fashion-design academy, and business financials. It is an
implemented workspace domain with twenty-six libraries under `libs/freya/*`, the
`@freya/contracts` package under `libs/contracts/freya`, and five applications
under `apps/freya/*`.

Freya is the supply-side and business-operations domain. It does **not** own
personal consumer styling, virtual try-on, or individual recommendation
decisions — those belong to Aglaea. Stores, factories, and real-estate
facilities belong to Cybele; factory-automation machinery belongs to Brigid;
advanced technology-product manufacturing belongs to Saraswati, which Freya
consumes when a product embeds devices or smart components.

## Domain Foundation

Freya is built on two foundation packages before any business capability is
introduced.

`@freya/core` defines the primitives every capability library builds on:
`Product`, `Collection`, `Material`, `Textile`, `Supplier`, `Artisan`,
`Customer`, `Brand`, pricing tiers, beauty/formulation types, and quality
primitives, plus a nineteen-entry business-unit catalog and shared utilities.
`@freya/db` persists product catalogs, collections, orders, inventory,
suppliers, campaigns, production records, and academy records on PostgreSQL via
Drizzle, and owns the migration set.

### Core Domain Objects

The three most important types in `@freya/core` model the lifecycle objects that
flow through every part of the domain.

- **`Product`** — identified by a branded `FreyaProductId`, carries variants
  (each with its own `FreyaSkuId`), an owning `brand`, and a `buCode` for its
  business unit. Its `category` is one of nineteen `ProductCategory` values
  (`fashion_rtw`, `fashion_couture`, `watches`, `skincare`, `cosmetics`,
  `perfume`, `jewelry`, `footwear`, `eyewear`, and others). Its lifecycle
  `status` advances through `Concept` -> `InDevelopment` -> `Sampling` ->
  `PreProduction` -> `InProduction` -> `ReadyToShip` -> `Active`, or terminates
  at `Discontinued`. A product reaches sellable state at `Active`;
  `Discontinued` removes it from new assortments while preserving order history
  and provenance.
- **`Material`** — carries a `materialId`, a `type` of `textile`, `leather`,
  `metal`, `gemstone`, `chemical`, `botanical`, or `packaging`, a
  `MaterialGradeScore` (`A+`/`A`/`B`/`C`/`Reject`), a `supplierId`, a list of
  `certifications`, and a `sustainabilityScore`. Material records must retain
  source and certification evidence permanently so provenance survives audit
  (see Requirements).
- **`ManufacturingOrder`** — carries an `orderId`, bound to a `productId` and a
  `variantId`, with a `supplierId`, a `quantity`, and a costed `bom`. Its
  `status` is an `OrderStatus` value — `draft`, `placed`, `confirmed`,
  `in_production`, `quality_check`, `ready`, `shipped`, `delivered`, or
  `cancelled`. A failed inspection holds the order in `quality_check` until
  rework passes re-inspection. (Two other order state machines exist for
  different surfaces: the ecommerce DTC fulfillment lifecycle and the
  manufacturing-app factory-floor machine — see API Surface and Applications.)

Six branded ID types — `FreyaProductId`, `FreyaCollectionId`, `FreyaOrderId`,
`FreyaCustomerId`, `FreyaVariantId`, and `FreyaSkuId` — prevent accidental
cross-entity reference at compile time. `Material`, `Supplier`, `Artisan`, and
`ManufacturingOrder` use plain string IDs.

## Capability Libraries

Each library below owns the lifecycle logic and validation for one business
unit. The data flow across them is: designers and operators create product,
material, collection, and manufacturing records; brand and market modules enrich
products with trend, campaign, pricing, and demand signals; retail and ecommerce
publish sellable inventory and customer experiences; manufacturing and quality
close the loop with production status and inspection evidence; financials and
market intelligence provide planning, profitability, and expansion views.

### Fashion Design and Production (`@freya/fashion`)

Owns the apparel design pipeline from trend intake to launch readiness. Trend
boards aggregate runway and social signals into mood/silhouette direction for a
season. Collection planning sizes an assortment against a season calendar and
target margin; capsule collections are a small, time-boxed assortment variant.
Each style carries a tech pack — construction drawings, measurement points,
pattern metadata, and a bill of materials (BOM) linking `Material` records with
per-unit consumption. Sample requests move a style into the `Sampling` product
status; fit sessions record measurement deltas against the size spec, and
grading derives the full size run from the base sample. A production approval
gate requires a passed fit session and a costed BOM before a style may enter a
`ManufacturingOrder`; launch readiness aggregates approval, sample, and
inventory state into a go/no-go signal for the season calendar.

### Textile Operations (`@freya/textiles`)

Owns fabric intelligence and material quality. The fabric catalog records fiber
composition, weave/knit construction, weight, and width per fabric. Mill
sourcing tracks dye lots, minimum order quantities (MOQ), and lead time per
mill. Textile tests record shrinkage, colorfastness, pilling, and tensile
results against a pass threshold; a fabric with a failing test cannot be
approved for a tech-pack BOM. Defect tracking attributes flaws to a dye lot and
mill for supplier scorecards. Costing rolls fabric price, MOQ surcharges, and
yield loss into a per-unit material cost. Material substitution proposes an
equivalent fabric when a primary is unavailable, carrying forward composition
and certification constraints so substitutions cannot silently drop a
sustainability or compliance attribute.

### Beauty and Personal Care (`@freya/beauty`)

Owns cosmetics, skincare, fragrance, and haircare product intelligence. Each
beauty product carries an ingredient deck, a versioned formulation record, and
batch-traceability metadata linking finished batches to ingredient `Material`
lots. Product claims (e.g. "dermatologically tested", SPF rating) are stored
with their substantiation reference. Regulatory warnings and shelf-life /
period-after-opening data are mandatory fields for a beauty product to reach the
`Active` product status. Formulation and batch records must support full
ingredient and compliance audit trails (see Requirements): a formulation change
creates a new version rather than mutating the prior one, and
consumer-suitability attributes (allergen flags, skin-type fit) are derived from
the active formulation version.

### Brand Management (`@freya/brand`)

Owns brand identity, positioning, and campaign operations. Campaign calendars
sequence creative briefs, lookbooks, press assets, and social launches against
season milestones. Influencer and partner workflows track deliverables and
exclusivity windows — a window blocks a product or campaign asset from a region
or channel until the window opens. Regional localization adapts brand copy and
imagery per market. Brand health analytics aggregate awareness, sentiment, and
campaign-performance signals into a brand-level score consumed by financials and
market intelligence.

### Ecommerce and Diaspora DTC (`@freya/ecommerce`)

Owns the direct-to-consumer storefront, including diaspora commerce for
cross-border buyers. It covers storefront catalogs (publishing only `Active`
products), carts, checkout, payments, promotions, returns, and fulfillment. Its
own DTC order lifecycle is a fourteen-state fulfillment machine (`placed` ->
`payment_confirmed` -> `processing` -> `picked` -> `packed` -> `shipped` ->
`out_for_delivery` -> `delivered`, plus return and refund states). Cross-border
shipping computes duties and customs handling per destination. Customer
segmentation drives product recommendations and abandoned-cart recovery.
Omnichannel inventory reconciles ecommerce stock against the same shared
inventory pool as retail so a unit is never double-sold. Cart and inventory
state is held in Redis for real-time accuracy; every order and inventory update
is idempotent (see Requirements) so a retried payment webhook or sync event
cannot create a duplicate order or double-decrement stock.

### Manufacturing Operations (`@freya/manufacturing`)

Owns production execution for cosmetics, textile, and assembly manufacturing. It
manages clean-room and batch records, production lines, line balancing against
factory capacity, machine utilization (OEE), lean-waste tracking, equipment
maintenance, and per-product-type assembly stage machines for watches, jewelry,
eyewear, footwear, and leather goods. Quality inspection records inspection
evidence per batch; a failed inspection holds the order and opens rework.
Costing computes actual unit cost against the planned BOM cost; yield and rework
rates feed supplier scorecards. The factory-floor app layers its own linear
order machine (`DRAFT` -> `SCHEDULED` -> `IN_PROGRESS` -> `QC` -> `COMPLETE` ->
`SHIPPED`) over these records.

### Retail Chain Management (`@freya/retail`)

Owns physical retail operations across stores, pop-ups, and concessions. It
manages sales associates, client appointments, and clienteling — a per-customer
profile of purchase history, preferences, and outreach. POS exports reconcile
in-store sales into the shared inventory and order records. Inventory transfers
and replenishment move stock between locations and trigger reorders against a
location's demand plan. Merchandising tracks assortment by location;
sell-through and shrinkage feed local demand planning and loss analysis.

### Academy (`@freya/academy`)

Owns the fashion-design academy. It manages a design curriculum organized into
courses, student cohorts, and instructor assignments. Student portfolios collect
project submissions; critiques and project rubrics score them. Workshops are
short-form sessions; certifications are awarded on rubric completion, and alumni
pathways track post-program outcomes.

### Jewelry and Accessories (`@freya/jewelry`)

Owns jewelry and accessory products with high provenance requirements. It tracks
gemstone and precious-metal inventory with a chain of custody from source to
finished piece, and hallmarking records for metal purity. CAD references and
setting specifications drive artisan production. Each finished piece carries a
valuation, an authenticity certificate, and a repair history. Because jewelry
materials are high-value and regulated, every `Material` and provenance record
in this library retains its full source and certification evidence permanently.

### Additional Business-Unit Libraries

Eleven further libraries each own one business unit and ship a single
implementation module. These are not stubs — each one holds the domain-specific
lifecycle logic, validation, and algorithms for its unit.

- **`@freya/watches`** — watch line management.
- **`@freya/perfumes`** — fragrance bench, accord design, and maceration
  tracking.
- **`@freya/bridal-events`** — bridal couture and event wardrobe.
- **`@freya/hair-care`** — Afro-textured hair-care formulation.
- **`@freya/home-decor`** — interior textiles and home decor.
- **`@freya/footwear`** — footwear design and production.
- **`@freya/eyewear`** — optical and sun eyewear.
- **`@freya/luggage-leather`** — luggage and leather goods.
- **`@freya/personal-care`** — personal-care formulation.
- **`@freya/cleaning-products`** — detergent and cleaning products.
- **`@freya/textile-finishing`** — dye-house, print-house, and finishing-line
  operations.

### Market Intelligence (`@freya/market-intel`)

Owns trend and demand intelligence. It ingests runway and social-trend signals,
competitor pricing, and beauty/fashion demand signals. Retail benchmarks compare
Freya sell-through against market baselines. Regional-preference analysis and
sourcing-risk scoring inform assortment and supplier decisions. Launch-
opportunity scoring ranks candidate products or collections by projected demand
against sourcing risk and competitor saturation.

### Financials (`@freya/financials`)

Owns business financial modeling across every business unit. It computes unit
economics and per-product margin, builds a brand-level P&L, and tracks inventory
carrying cost and the cash-conversion cycle. Demand and revenue forecasts feed
planning; supplier-exposure analysis quantifies concentration risk across the
supplier base. Multi-business-unit rollups consolidate fashion, beauty, jewelry,
and accessory units into a domain-level financial view.

### Connectors (`@freya/connectors`)

Freya does not import from other domains directly. Instead, all cross-domain
integration is channeled through `@freya/connectors`, which adapts Freya's
internal shapes to the contracts of five neighboring domains.

The connectors integrate with: Asase (agriculture — shea- and cocoa-butter
supply chains, natural-ingredient traceability, cotton sourcing), Brigid
(manufacturing automation — textile and cosmetics-packaging automation, quality
vision systems, predictive maintenance), Cybele (construction — flagship store
design, retail space planning, factory construction), Saraswati (logistics —
ecommerce logistics, IoT retail sensors, smart warehousing, EV delivery fleet),
and Maat (strategic intelligence — dashboard sync, brand and market-intelligence
feeds, financial consolidation). Isolating integration in one library means that
a shape change in any of those domains requires changes only in the connector,
not across all capability libraries.

### SOTA Enhancements (`@freya/sota`)

Houses the state-of-the-art enrichment layer: AI-assisted design and generative
collection ideation, AI analytics, computer-vision quality control, NLP,
blockchain-based authenticity verification, and virtual try-on. Each is
delivered as an opt-in enrichment on top of the deterministic capability
libraries rather than replacing their core logic. This separation means the
business logic remains testable and predictable even if an AI enrichment is
unavailable or returns an unexpected result.

## Applications

Five applications under `apps/freya/*` compose user workflows over the
capability libraries. Applications may depend on capability libraries but not on
each other; cross-app coordination goes through the API service and Kafka
events.

- **`apps/freya/api`** — the API service exposing every Freya API family to
  internal and external consumers via REST, GraphQL, gRPC, and WebSocket.
- **`apps/freya/studio`** — the design and brand studio app: trend boards,
  collection planning, tech packs, fit sessions, and brand/campaign workflows.
- **`apps/freya/shop`** — the direct-to-consumer commerce storefront over
  `@freya/ecommerce`, serving both local and diaspora buyers.
- **`apps/freya/retail`** — the retail-operations app for store staff: POS,
  clienteling, appointments, inventory transfers, and replenishment.
- **`apps/freya/manufacturing`** — the manufacturing-operations app for factory
  and production staff: work orders, batches, quality inspection, and WIP.

## API Surface

The API service exposes the Freya domain over REST, GraphQL, gRPC, and WebSocket
interfaces. The REST contract is an OpenAPI 3.1 spec served at `/openapi.json`
with base path `/v1`. Its route groups are:

- **Products** — product catalog (list, create, fetch by ID).
- **Orders** — customer orders (place, fetch). The customer-order handler
  enforces a status state machine (`PLACED` -> `CONFIRMED` -> `SHIPPED` ->
  `DELIVERED` -> `RETURNED`, with `CANCELLED` reachable from `PLACED`/
  `CONFIRMED`).
- **Customers** — customer registration and profile.
- **Collections** and **Brands** — collection and brand records.
- **Manufacturing** — production orders.
- **Quality** — AQL/GMP inspections.
- **Inventory** — real-time inventory.
- **Formulations** — beauty and personal-care formulation records.
- **Academy** — students and courses.
- **Webhooks** — Paystack, Stripe, Flutterwave, shipping, and social-commerce
  callbacks (API-key authenticated).

GraphQL is served at `/graphql` (schema-first SDL), the real-time WebSocket
channel at `/ws`, and five internal high-throughput services
(`InventoryService`, `ManufacturingService`, `QualityService`, `PricingService`,
`CustomerService`) over gRPC in the `freya.internal` package.

## Events

Freya communicates state changes to the rest of the Oshun platform through
domain events. Understanding the event taxonomy helps neighboring domains know
what to subscribe to and what data crosses the boundary.

Freya publishes domain events on the CloudEvents 1.0 envelope, grouped into
twelve families with dotted-namespace type names: product (`freya.product.*`),
inventory (`freya.inventory.*`), orders (`freya.order.*`), manufacturing
(`freya.manufacturing.*`), quality (`freya.quality.*`), customers
(`freya.customer.*`), trends (`freya.trend.*`), collections
(`freya.collection.*`), academy (`freya.academy.*`), formulations
(`freya.formulation.*`), retail (`freya.retail.*`), and payments
(`freya.payment.*`). Events are routed to six Kafka topics — `freya.orders`,
`freya.inventory`, `freya.production`, `freya.quality`, `freya.customers`,
`freya.trends` — with a `freya.dlq` dead-letter queue. These let other domains
react to product, inventory, order, manufacturing, and campaign state changes —
for example, Aglaea consumes published products, sizing, retail inventory, and
provenance records for its consumer recommendation and shopping experiences.
Freya consumes shared identity, organization, payment, storage, analytics, and
notification contracts.

## Persistence

Freya uses four persistence mechanisms, each appropriate to the data's access
pattern and durability requirements.

- **PostgreSQL / Drizzle** — products, variants, collections, orders, customers,
  manufacturing records, campaigns, courses, and financial data. Twenty-four
  `freya_*` tables with pgvector for embedding-based similarity search.
- **Object storage** — lookbooks, sketches, tech packs, product images,
  formulation records, brand assets, and campaign media. Three MinIO/S3 buckets
  with different access policies (public CDN-served for product imagery;
  private, versioned, and strictly retained for manufacturing documents).
- **Redis** — inventory levels, sessions, carts, and real-time commerce state.
  Cart and inventory state lives here rather than in PostgreSQL because it
  changes on every user interaction and must be accurate across all channels
  simultaneously.
- **Event bus** — product-lifecycle, inventory, order, manufacturing, campaign,
  and customer events on Kafka.

## Requirements and Constraints

These four requirements are mandatory for any change touching the relevant data.
They are non-negotiable because they protect consumer safety, financial
integrity, privacy, and audit-ability.

1. **Provenance evidence** — product, material, and provenance records must
   retain source and certification evidence; this evidence is append-only and
   survives audit.
2. **Idempotent commerce** — inventory and order updates must be idempotent so a
   retried event or webhook cannot duplicate an order or double-adjust stock.
3. **Beauty audit trails** — beauty and formulation records must support
   ingredient and compliance audit trails; formulation changes are versioned,
   never mutated in place.
4. **Privacy and access control** — customer and retail data must observe
   privacy rules and role-based access controls.

Changes must run package tests for the affected libraries and apps. Commerce,
payment, inventory, manufacturing, and customer-data changes additionally
require contract and persistence regression coverage.

## Relationship to Aglaea

Freya is the supply-side and business-operations domain for luxury goods and
fashion; Aglaea is the personal-styling and consumer-beauty intelligence domain.
The boundary between them is clean: Freya produces the catalog, Aglaea curates
the experience.

Freya publishes products, textiles, sizing, retail inventory, brand campaigns,
and provenance records; Aglaea consumes them to drive individual recommendation
and shopping experiences. Personal styling and virtual try-on remain entirely in
Aglaea; Freya never makes a per-consumer styling decision. Data flows in one
direction across this boundary — from Freya's Kafka topics into Aglaea's
consumption pipeline — and no Freya capability library imports from Aglaea.
