← Back to skill
# merchmix-product-review-be

Rust/Axum service for building, storing, retrieving, exporting, and delivering retail product review artifacts across weekly, monthly, quarterly, and seasonal periods. It aggregates merchandise performance data from PostgreSQL and WSSI-related sources, builds compressed versioned review payloads, and provides REST, MCP, and gRPC interfaces. Background schedulers support recurring review delivery and weekly briefing generation.

## Business Summary

This service gives retailers a consolidated view of how merchandise is performing against budget and last year. Users can create trade reviews, inspect sales, margin, stock, markdown, sell-through, and weeks-of-cover results, add commentary, export reviews to Excel, and schedule email or Slack delivery. It also produces recurring weekly executive briefings with key findings, risks, winners, and recommended actions.

## Capabilities

| Capability | Category | Status | Access | Exposure |
|---|---|---|---|---|
| Product Performance Review Generation | Reporting | `production` | `execute` | user_facing, agent_facing, internal |
| Product Performance Review Retrieval | Reporting | `production` | `read` | user_facing, agent_facing |
| Merchandise Performance Drilldown | Reporting | `production` | `read` | user_facing, agent_facing |
| Trade Commentary Management | Reporting | `production` | `write` | user_facing, agent_facing |
| AI-Assisted Trade Commentary | Reporting | `production` | `execute` | user_facing, agent_facing |
| Review Excel Export | Reporting | `production` | `read` | user_facing, agent_facing |
| Review Delivery Scheduling | Reporting | `production` | `write` | user_facing, agent_facing, internal |
| Weekly Executive Briefings | Reporting | `production` | `execute` | user_facing, agent_facing, internal |
| Product Review Settings Management | Planning | `production` | `write` | user_facing, agent_facing |
| Season and Calendar Discovery | Planning | `production` | `read` | user_facing, agent_facing |
| WSSI Data Integration | Planning | `production` | `read` | internal |
| Machine-Readable Product Review Access | Other | `production` | `execute` | agent_facing |

**Product Performance Review Generation** — Creates merchandise performance reviews for selected departments, categories, subcategories, brands, stores, seasons, and reporting periods.

**Product Performance Review Retrieval** — Lets retail users retrieve available reviews and inspect their current status or a specific historical version.

**Merchandise Performance Drilldown** — Provides detailed style-level size breakdowns so users can investigate product performance beyond the summary hierarchy.

**Trade Commentary Management** — Allows merchants to record comments, highlights, lowlights, actions, and executive summaries against a review.

**AI-Assisted Trade Commentary** — Generates AI-written review commentary to help merchants prepare trade discussions and summaries.

**Review Excel Export** — Exports a merchandise review into an Excel workbook for offline analysis and sharing.

**Review Delivery Scheduling** — Schedules review delivery to a mailbox through email or Slack, including recurring delivery options.

**Weekly Executive Briefings** — Creates and delivers recurring weekly summaries of merchandise performance, including KPIs, risks, winners and losers, opportunities, and prioritized actions.

**Product Review Settings Management** — Stores and updates client-specific settings used when preparing product reviews, including weeks-of-cover goal bands and overrides.

**Season and Calendar Discovery** — Provides season information and reporting-period calendar context used to select and build reviews.

**WSSI Data Integration** — Uses WSSI planning data to enrich reviews with budget and stock-related merchandise metrics.

**Machine-Readable Product Review Access** — Allows AI agents and other compatible clients to perform review, settings, and weekly briefing operations through a tool interface.

## Workflows

**Build a merchandise review** — Creates an enriched, versioned review artifact for a selected retail reporting period.

1. Resolve calendar bounds and latest available reporting week.
2. Query current-year, prior-year, budget, sales, seller, and CSOH-related metrics from the sync database.
3. Fetch or derive WSSI aggregates and apply weeks-of-cover goal settings.
4. Assemble the merchandise hierarchy and review header.
5. Encode the review using MessagePack and zstd, then persist the artifact and its versioned blob.
6. Expose the artifact as pending, building, ready, or failed through status and retrieval routes.

**Review and annotate merchandise performance** — Retrieves a review, investigates product detail, and records merchant interpretation.

1. List or locate a review by period and slug.
2. Fetch the current or selected historical version.
3. Inspect hierarchy metrics or request a style size breakdown.
4. Read or update trade commentary and executive summary fields.
5. Optionally generate AI-assisted commentary.

**Deliver a scheduled review** — Sends a review to a configured destination on a one-time or recurring schedule.

1. Create a delivery schedule with destination, channel, send time, and recurrence.
2. Background delivery scheduler identifies due schedules.
3. Dispatch the review through the configured delivery integration.
4. Update schedule status and sent/mailbox metadata.

**Generate a weekly executive briefing** — Produces a recurring summary for a configured client and review scope.

1. Create or update a weekly briefing schedule with source review, filters, timezone, and local send time.
2. Scheduler creates or processes a briefing run with idempotency tracking.
3. Build or preview the briefing summary and recommended actions.
4. Deliver the briefing by email when configured and record run status and errors.

## Architecture

A single Rust service combines HTTP routing, MCP tool serving, gRPC client generation, PostgreSQL persistence, Redis caching, review aggregation pipelines, binary artifact encoding, and background schedulers. HTTP handlers contain much of the SQL and business logic directly; MCP tools call those handlers rather than duplicating the logic.

**Components:** Axum REST API and health endpoints, MCP Streamable HTTP server mounted at /mcp, Review pipeline for calendar resolution, metric queries, hierarchy assembly, WSSI enrichment, and persistence, PRV binary encoder/decoder using MessagePack and zstd, PostgreSQL application and synchronization database pools with SQLx migrations, Layered in-memory/Redis cache, Delivery and weekly briefing background schedulers, Generated tonic/prost WSSI gRPC client, Excel export component, Telemetry and structured tracing

**Patterns:** Multi-tenant request handling using client identifiers, Versioned immutable-style review blobs with metadata in relational tables, Read-through layered caching, Background scheduler and retry/run tracking, Direct handler reuse for MCP operations, Offline SQLx query preparation and migration-based schema management, Containerized deployment to Azure Container Apps and Google Cloud Run

## Interfaces

| Kind | Identifier | Description |
|---|---|---|
| `http` | `/v2/:period/reviews` | List reviews for a client and reporting period; POST creates a review artifact. |
| `http` | `/v2/:period/reviews/:slug` | Retrieve or delete a review by period and slug. |
| `http` | `/v2/:period/reviews/:slug/status` | Read review build status. |
| `http` | `/v2/:period/reviews/:slug/v/:version` | Retrieve a specific review artifact version. |
| `http` | `/v2/:period/reviews/:slug/refresh` | Refresh/rebuild an existing review. |
| `http` | `/v2/:period/reviews/:slug/commentary` | Read or update review commentary. |
| `http` | `/v2/:period/reviews/:slug/write-ai` | Generate or write AI-assisted review text. |
| `http` | `/v2/:period/reviews/:slug/size-breakdown/:style_code` | Read style-level size breakdown data. |
| `http` | `/v2/:period/reviews/:slug/export/excel` | Download a review as an Excel workbook. |
| `http` | `/v2/:period/reviews/:slug/delivery-schedules` | List or create delivery schedules for a review. |
| `http` | `/v2/:period/reviews/:slug/delivery-schedules/:schedule_id` | Cancel or manage an individual review delivery schedule. |
| `http` | `/v2/seasons` | List available seasons. |
| `http` | `/v2/product-review-settings` | Read or update product review settings. |
| `http` | `/v2/reviews/decode-diagnostic/:artifact_id` | Decode the current binary artifact into diagnostic header and node data. |
| `http` | `/v2/weekly-briefing-schedules` | List or create weekly briefing schedules. |
| `http` | `/v2/weekly-briefing-schedules/:schedule_id` | Update or delete a weekly briefing schedule. |
| `http` | `/v2/weekly-briefing-schedules/:schedule_id/runs` | List runs for a weekly briefing schedule. |
| `http` | `/v2/weekly-briefing-schedules/:schedule_id/test` | Test a weekly briefing schedule. |
| `http` | `/v2/weekly-briefings/latest` | Retrieve the latest weekly briefing. |
| `http` | `/v2/weekly-briefings/preview` | Preview a weekly briefing. |
| `http` | `/internal/v2/weekly-briefings/dispatch` | Internal weekly briefing dispatch endpoint. |
| `http` | `/health/live and /health/ready` | Liveness and readiness probes. |
| `http` | `/mcp and /.well-known/mcp-service` | MCP Streamable HTTP transport and service metadata. |
| `grpc` | `wssi.WssiService/GenerateWssi` | Generates WSSI calendar headers and aggregate values for client, brand/category, store, year, and week count. |
| `grpc` | `wssi.WssiService/GetBudgetExportValues` | Returns budget export payload values for a client, year, department, category, and subcategory. |

## Data

| Entity | Ownership | Description |
|---|---|---|
| ReviewArtifact | `owns` | Metadata for a client review, including period, slug, version, status, dimensions, build details, and commentary fields. |
| ReviewArtifactBlob | `owns` | Compressed binary PRV payload for each review artifact version. |
| ReviewDeliverySchedule | `owns` | One-time or recurring review delivery configuration and dispatch status. |
| WeeklyBriefingSchedule | `owns` | Client/user weekly briefing schedule, source review scope, filters, timezone, and next/last run timestamps. |
| WeeklyBriefingRun | `owns` | Execution record for a briefing, including idempotency key, reporting period, retry state, summary, delivery time, and errors. |
| ProductReviewSettings | `owns` | Persisted review configuration including weeks-of-cover defaults and hierarchy-level overrides. |
| MerchandisePerformanceMetrics | `reads` | Sales, gross profit, budget variance, prior-year comparison, sell-through, markdown, stock, units, and weeks-of-cover inputs used to build reviews. |
| SeasonsAndCalendar | `reads` | Season definitions and reporting-week/calendar data used to resolve review periods. |

## Dependencies

| Name | Kind | Relationship | Criticality |
|---|---|---|---|
| PostgreSQL application database | `database` | `reads` | `critical` |
| PostgreSQL synchronization database | `database` | `reads` | `critical` |
| Redis | `database` | `uses` | `required` |
| WSSI service | `internal_service` | `calls` | `required` |
| Merchmix Basics service | `internal_service` | `calls` | `required` |
| OpenAI API | `external_service` | `calls` | `optional` |
| SendGrid | `external_service` | `calls` | `optional` |
| Google Cloud Run Jobs | `external_service` | `calls` | `supporting` |
| merchmix-telemetry-sdk | `library` | `uses` | `supporting` |
| NATS | `queue` | `uses` | `supporting` |

## Technology

Rust 2024 edition, Tokio, Axum 0.7, SQLx with PostgreSQL, Redis via deadpool-redis, Serde and JSON, MessagePack via rmp-serde, zstd compression, Tonic and Prost gRPC, MCP Streamable HTTP via rmcp, rust_xlsxwriter, OpenAPI via utoipa and Swagger UI, Tower HTTP middleware, Docker, Azure Container Apps, Google Cloud Run

## Limitations

- The supplied evidence does not include complete handler implementations, migration contents, or all MCP tool definitions, so exact request/response schemas and table names are not fully established.
- The concrete email, Slack, and OpenAI client implementations were not included in the excerpts; their configuration and enum values establish intended integrations, but delivery behavior should be verified in the remaining source.
- NATS is reported by scanning, but no concrete topic, message schema, publisher, or consumer is shown.
- No frontend screens are present in this repository; user-facing screens are presumably provided by another application.
- The deployment files show both Azure Container Apps and Google Cloud Run targets, but the active production target cannot be determined solely from repository evidence.

## Agent Instructions

Use this repository for merchandise review generation, retrieval, commentary, export, delivery scheduling, weekly executive briefings, and agent-accessible review operations.

- Resolve tenant context from the X-Client-ID header for REST/MCP operations; do not assume a client_id argument can override the request tenant.
- Use period and slug for normal review access; use artifact_id only for the diagnostic decode route, which directly looks up the artifact.
- Treat review artifacts as versioned binary payloads and use the status endpoint before assuming a newly requested review is ready.
- For review analytics, prefer the existing review retrieval and size-breakdown interfaces instead of reconstructing metric calculations externally.
- Use product-review-settings when weeks-of-cover goals or hierarchy-specific thresholds need to be changed.
- Protect weekly briefing internal dispatch operations with the configured internal secret and required actor/request headers.
- AI writing and outbound email delivery are optional integrations; handle unavailable credentials or providers as degraded capability rather than assuming success.
- Do not expose or request secret environment values, tokens, database URLs, or API keys.

## Source

| Field | Value |
|---|---|
| Repository | `merchmix-product-review-be` |
| Branch | `master` |
| Commit | `ab507575b127` |
| Generated by | `gpt-5.6-luna` |

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