← Back to skill
# merchmix-option-plan-be

This repository is the backend for Merchmix Option Planning. It provides HTTP, gRPC, and MCP interfaces to create and manage option plan masters and plans, capture approvals and workspace configuration, assign styles and suppliers, generate recommendation and sync statistics views, preview and push plans into range planning, and expose option-plan data to other internal services. It persists its own option-planning data in PostgreSQL, uses Redis as an optional cache, and integrates with assortment, WSSI, prediction, notification, telemetry, OpenAI, and Google Cloud services.

## Business Summary

This service helps retailers build and manage option plans: the working plans that decide what styles, suppliers, and quantities should be bought for a season. Teams can set targets, review recommendations, approve plans, capture working snapshots, and push approved outcomes into range planning. It also connects to other Merchmix services so planners can bring in supporting data, generate planning notes, and share plan information across the platform.

## Capabilities

| Capability | Category | Status | Access | Exposure |
|---|---|---|---|---|
| Option Planning | Planning | `production` | `write` | user_facing, agent_facing |
| Option Plan Target Setting | Planning | `production` | `write` | user_facing, agent_facing |
| Option Plan Approval | Planning | `production` | `write` | user_facing, agent_facing, internal |
| Style Assignment | Products | `production` | `write` | user_facing, agent_facing, internal |
| Supplier Assignment | Suppliers | `production` | `write` | user_facing, agent_facing |
| Range Plan Preview and Push | Planning | `production` | `execute` | user_facing, agent_facing, internal |
| Planning Recommendations | Forecasting | `production` | `read` | user_facing, agent_facing |
| Sync Statistics and WSSI Support | Reporting | `production` | `read` | user_facing, agent_facing, internal |
| AI Planning Notes Generation | Planning | `beta` | `execute` | user_facing, agent_facing |
| Option Plan Data Access for Internal Services | Other | `production` | `read` | internal, agent_facing |
| Approval Notifications | Other | `production` | `execute` | internal |

**Option Planning** — Create, update, view, and delete option plans and their parent planning workspaces.

**Option Plan Target Setting** — Maintain plan-level grid targets and workspace column preferences used by planners during option planning.

**Option Plan Approval** — Record and retrieve approval status for option plans so teams can track whether a plan is ready to move forward.

**Style Assignment** — Assign styles to an option plan, initialize assignments, and perform bulk assignment updates for planning work.

**Supplier Assignment** — Manage supplier assignments and supplier assignment options within an option plan.

**Range Plan Preview and Push** — Preview how an option plan will map into range planning, then push selected plan content into the range board and track job status.

**Planning Recommendations** — Provide recommendation outputs to help planners decide what action to take on styles or options.

**Sync Statistics and WSSI Support** — Show planning statistics and WSSI-derived supporting values used during option planning and budget context.

**AI Planning Notes Generation** — Generate concise planning notes for an option plan using AI based on plan data.

**Option Plan Data Access for Internal Services** — Allow other internal systems to list option plans, fetch option plan details, and retrieve latest style assignments.

**Approval Notifications** — Send user notifications when option plan approval status changes.

## Workflows

**Create and manage an option plan** — Planner creates a plan workspace, adds plan records, and maintains configuration used during planning.

1. Create an option plan master via POST /option-plan-masters
2. Create one or more option plans via POST /option-plans
3. Retrieve and edit plans with GET/PUT /option-plans/:id
4. Adjust grid targets and workspace columns on the master
5. Read settings and formulas to support planning views

**Assign styles and suppliers to a plan** — Planner initializes or updates the product and supplier choices attached to the option plan.

1. Initialize style assignments for a master
2. Fetch current style assignments
3. Apply bulk or individual style assignment updates
4. Manage supplier assignments and available supplier assignment options
5. Optionally retrieve latest assignments through gRPC from another internal service

**Review, approve, and notify** — Planning team reviews a plan, records approval state, and emits notifications.

1. Fetch recommendation outputs for the plan
2. Read approval state via GET /option-plan-masters/:id_or_slug/approval
3. Submit approval action via POST /option-plan-masters/:id_or_slug/approval
4. Emit approval notification asynchronously to notify-service
5. Optionally generate AI-written notes for the plan

**Preview and push to range planning** — Planner previews a downstream range plan impact and then pushes approved content into range planning.

1. Create a range-plan preview for an option plan master
2. Inspect preview details
3. Commit the preview if acceptable
4. Trigger push to range board
5. Poll push job status until complete

**Fetch planning support data** — The service gathers recommendation, WSSI, budget, and sync data to enrich planning decisions.

1. Call prediction backend for option-plan analysis data
2. Cache or reuse responses through Redis when available
3. Call WSSI gRPC service for generated WSSI or budget exports
4. Store gRPC call logs in PostgreSQL
5. Return aggregated support data to the requesting screen or tool

## Architecture

Rust service built on Axum for HTTP APIs, Tonic for gRPC clients and servers, SQLx for PostgreSQL persistence, optional Redis caching, and RMCP streamable HTTP for agent tooling. It is a multi-interface backend with its own database schema, plus background tasks for sync index maintenance, telemetry, and notification dispatch.

**Components:** HTTP API router under src/http with domain-specific route modules, gRPC server under src/grpc_server exposing option-plan and style-assignment contracts, gRPC clients for assortment, WSSI, and notification services, MCP server under src/mcp exposing tool-based access over streamable HTTP, PostgreSQL access layer under src/db and migrations/, Optional Redis cache layer under src/cache/redis, External integration modules for OpenAI, predict backend, GCP credential loading, telemetry, and notify dispatch

**Patterns:** Monolithic service with multiple protocols, PostgreSQL-first persistence with SQL migrations, Client-id based multi-tenancy, Synchronous request handlers plus asynchronous background workers, Best-effort external side effects for telemetry and notifications, Gateway/integration pattern to internal gRPC services

## Interfaces

| Kind | Identifier | Description |
|---|---|---|
| `http` | `/healthz, /readyz, /whoami` | Operational and identity endpoints for liveness, readiness, and caller context. |
| `http` | `/option-plan-masters, /option-plan-masters/:id_or_slug, /option-plans, /option-plans/:id` | Primary REST API for option plan masters and plans. |
| `http` | `/option-plan-masters/:id_or_slug/approval` | Approval read/write API for option plan workflows. |
| `http` | `/option-plan-masters/:id_or_slug/style-assignments and related bulk/initialize routes` | REST interface for style assignment management. |
| `http` | `/option-plan-masters/:id/supplier-assignments and /options` | REST interface for supplier assignment management. |
| `http` | `/option-plan-masters/:id/range-plan-previews and commit routes` | REST interface for generating and committing range plan previews. |
| `http` | `/option-plan-masters/:id_or_slug/push-to-range-board and status/:job_id` | REST interface for pushing option plans into the range board and checking async status. |
| `http` | `/predict-recommendations, /metric-formulas, /option-plan-settings, /option-plan/write-with-ai/:slug, /option-plan-masters/:id_or_slug/sync-stats` | Supporting REST APIs for recommendations, formulas, settings, AI notes, and sync statistics. |
| `grpc` | `option_plan.OptionPlanStyleService/GetLatestStyleAssignments` | Internal gRPC API returning latest style assignments by tenant. |
| `grpc` | `forge.core.v1.CoreOptionPlanService/ListOptionPlans, GetOptionPlan` | Internal gRPC API exposing option plan summaries and detail to other Merchmix services. |
| `other` | `/.well-known/mcp-service` | RMCP streamable HTTP endpoint exposing tool-based agent operations over option-plan workflows. |

## Screens

| Route | Name | Purpose |
|---|---|---|
| `/option-plan-masters` | Option Plan Masters | List and create option planning workspaces. |
| `/option-plan-masters/:id_or_slug` | Option Plan Master Detail | View or delete a specific option planning workspace. |
| `/option-plans` | Option Plans | List and create individual option plan records. |
| `/option-plans/:id` | Option Plan Detail | View, update, or delete a specific option plan. |
| `/option-plan-masters/:id_or_slug/grid-targets` | Grid Targets | Update target values used in planning grids. |
| `/option-plan-masters/:id_or_slug/workspace-columns` | Workspace Columns | Persist workspace column configuration. |
| `/option-plan-masters/:id_or_slug/approval` | Approval | View or submit approval status. |
| `/option-plan-masters/:id_or_slug/recommendations` | Recommendations | View recommendation outputs for a plan. |
| `/option-plan-masters/:id_or_slug/style-assignments` | Style Assignments | Manage style assignments for a plan. |
| `/option-plan-masters/:id/supplier-assignments` | Supplier Assignments | Manage supplier choices tied to the plan. |
| `/option-plan-masters/:id/range-plan-previews` | Range Plan Previews | Preview downstream range-plan changes before commit. |
| `/option-plan-masters/:id_or_slug/push-to-range-board` | Push to Range Board | Send approved planning content into range planning. |
| `/option-plan-settings` | Option Plan Settings | Manage global option-plan configuration. |
| `/option-plan/write-with-ai/:slug` | AI Planning Notes | Generate AI-written commercial notes for a plan. |

## Data

| Entity | Ownership | Description |
|---|---|---|
| Option Plan Master | `owns` | Top-level option planning workspace/master record addressed by id or slug. |
| Option Plan | `owns` | Individual option plan records under a master, exposed through CRUD APIs and gRPC detail retrieval. |
| Option Plan Settings | `owns` | Configurable settings for option planning behavior. |
| Approval Record | `owns` | Approval status and related transitions for option plan masters. |
| Style Assignment | `owns` | Assignments of manufacturing/style records to option plan masters, including latest-assignment lookup. |
| Supplier Assignment | `owns` | Supplier selections and supplier assignment options linked to option plans. |
| Range Plan Preview | `owns` | Preview records representing proposed downstream range-plan updates before commit. |
| Range Plan Push Job | `owns` | Queued or tracked jobs for pushing option-plan outcomes into range planning. |
| Workspace Snapshot | `owns` | Saved option workspace snapshots and subcategory snapshots. |
| Workspace Columns | `owns` | Persisted column configuration for planning workspaces. |
| Plan Window | `owns` | Plan-window data used to scope planning periods. |
| gRPC Log | `owns` | Operational log table recording upstream gRPC successes/failures for calls such as WSSI and assortment. |
| Synced Style Sales Purchase Summary | `reads` | Tenant-specific synced style metadata used to enrich assignments with description and supplier information. |
| Predict Recommendation Payload | `reads` | Prediction service response rows used to drive recommendation outputs. |
| WSSI and Budget Data | `reads` | Generated WSSI aggregates and budget export/breakdown payloads fetched from the WSSI service. |

## Dependencies

| Name | Kind | Relationship | Criticality |
|---|---|---|---|
| PostgreSQL | `database` | `writes` | `critical` |
| Redis | `database` | `uses` | `supporting` |
| AssortmentService | `internal_service` | `calls` | `required` |
| WSSI Service | `internal_service` | `calls` | `required` |
| Predict backend | `internal_service` | `calls` | `required` |
| Notification service | `internal_service` | `calls` | `supporting` |
| OpenAI API | `external_service` | `calls` | `optional` |
| Google Cloud credentials | `external_service` | `uses` | `required` |
| merchmix-telemetry-sdk | `library` | `uses` | `supporting` |
| NATS | `queue` | `depends_on` | `optional` |
| ingestion.merchmix.co | `internal_service` | `calls` | `supporting` |
| Azure Container Apps / Google Cloud Run | `other` | `depends_on` | `supporting` |

## Technology

Rust, Axum, Tokio, SQLx, PostgreSQL, Redis, Tonic gRPC, RMCP streamable HTTP, Reqwest, Serde, JWT decoding via jsonwebtoken, OpenAI API, Google Cloud service-account JSON, Docker, Azure Container Apps, Google Cloud Run

## Limitations

- Scanner evidence confirms routes and integrations, but not all handler internals were included; some business behavior details are inferred only from route names, migrations, and module names.
- NATS is reported by scanner signals, but the provided source excerpts do not show explicit publish/consume code, so messaging usage confidence is low.
- Auth appears to rely on upstream verification/pass-through in telemetry comments and middleware naming, but the full authentication and authorization model is not fully established from the excerpts.
- There are modules for fabrics and size analysis in source tree names, but corresponding endpoints were not present in the detected route list provided here; they are omitted as primary capabilities.
- A Makefile target references a worker binary, but only the main API binary is evidenced in the provided source excerpts, so no separate worker capability is claimed.

## Agent Instructions

Treat this repository as the system of record for option-plan masters, option plans, approvals, assignments, previews, and push-job state. Use its HTTP or MCP interfaces for operational work, and use gRPC only for internal service-to-service integrations.

- Prefer implementation-backed capabilities: operate against the detected REST routes, gRPC methods, and MCP endpoint rather than README assumptions.
- When asking for option-plan data from another internal service, use CoreOptionPlanService for summaries/detail and OptionPlanStyleService for latest style assignments.
- For planning automation, MCP at /.well-known/mcp-service is the most agent-friendly surface because it wraps existing HTTP handlers into typed tools.
- Expect tenant scoping by client_id headers/fields; always supply the correct tenant/client_id when calling HTTP, MCP, or gRPC interfaces.
- Do not assume Redis is always available; caching is optional and the service can run without it.
- Approval notifications are fire-and-forget; a successful approval write does not guarantee downstream notification delivery.
- Range-plan creation itself is not owned here; pushing to range planning depends on the Assortment service.
- WSSI, budget exports, and prediction outputs are upstream-derived data; if they fail, investigate WSSI or predict services rather than this repository first.
- Use PostgreSQL migrations as the source of truth for owned schema entities such as previews, snapshots, settings, push jobs, and gRPC logs.
- If diagnosing performance or data freshness issues, check sync database index maintenance and tenant-specific synced summary tables in addition to the main app schema.

## Source

| Field | Value |
|---|---|
| Repository | `merchmix-option-plan-be` |
| Branch | `master` |
| Commit | `fa95956299d9` |
| Generated by | `gpt-5.4` |

*Generated by the Merchmix Skills Platform from the current codebase.*