npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

medusa-product-helper

v0.0.104

Published

A starter for Medusa plugins.

Readme

medusa-product-helper

Medusa v2 plugin that adds advanced product filtering, wishlist management, product-view analytics, cart merge controls, and admin productivity extensions.

Plugin Overview

medusa-product-helper extends Medusa with:

  • A provider-based dynamic filter engine for product listing (store and admin), with a global display priority weight that controls the default shop sort. New products auto-receive the next unused whole number.
  • Store and admin wishlist features (including workflows and analytics endpoint).
  • Product view tracking for customers and guests, plus admin analytics aggregation.
  • Cart helper APIs (list carts, merge carts, skip-merge marker).
  • Scheduled cleanup of stale skip-merge carts (soft-delete only), configured via plugin option staleSkipMergeCartCleanup.
  • Promotions-by-product APIs (admin and store) for listing promotions that explicitly target a product via Medusa promotion rules.
  • Admin extensions: wishlist stats widget, product display-priority widget, customer carts widget, customer product views widget, variant view chart widget, inventory CSV import widget, and dedicated carts/product-views pages.

Problem It Solves

This plugin centralizes several common commerce needs that usually require custom implementation:

  • High-flexibility product discovery and filtering.
  • Wishlist persistence and analytics.
  • Product engagement tracking (views).
  • Cart identity/merge edge-case handling.
  • Operational tooling in the admin for inventory import and customer behavior visibility.

Medusa Version

Built for Medusa v2 (@medusajs/framework / @medusajs/medusa 2.11.2 in package.json).


Installation & Setup

Install

npm install medusa-product-helper
# or
yarn add medusa-product-helper

Register Plugin (medusa-config.ts)

import { defineConfig } from "@medusajs/framework/utils"

export default defineConfig({
  plugins: [
    {
      resolve: "medusa-product-helper",
      options: {
        // Optional plugin config
      },
    },
  ],
})

Run Migrations

The plugin includes module migrations (wishlist, product_view, skip_merge_cart, product_display_priority), so every shop that installs or upgrades this plugin should run:

npx medusa db:migrate

Do not add shop-local SQL for display priority. Existing catalog products are numbered by created_at in the plugin migration, and any later products without a row are filled by the plugin job backfill-product-display-priorities.

If your workflow requires generating migration snapshots first:

npx medusa plugin:db:generate
npx medusa db:migrate

Configuration (medusa-config / Plugin Options)

Defined in src/config/product-helper-options.ts and resolved with resolveProductHelperOptions(configModule).

| Option | Type | Required | Default | Description | |---|---|---|---|---| | guestJwtSecret | string | Optional | undefined | Secret for guest product-view token verification (/store/product-helper/product-views/guest). | | default_price_range | object | Optional | { label: "custom", min: null, max: null } | Default range object used by price filtering helpers/providers. | | default_price_range.label | string | Optional | "custom" | Price-range label. | | default_price_range.currency_code | string | Optional | undefined | ISO alpha-3 currency code (stored lowercased). | | default_price_range.min | number \| null | Optional | null | Min amount. | | default_price_range.max | number \| null | Optional | null | Max amount. | | availability | object | Optional | { require_in_stock: false, include_preorder: true, include_backorder: true, include_gift_cards: false, publishable_only: true } | Availability filter behavior. | | rating | object | Optional | { enabled: true, min: 0, max: 5, require_reviews: false } | Rating filter behavior. | | bestSeller | object | Optional | { enabled: true, min_orders_threshold: 1 } | Best-seller provider behavior. | | bestSeller.default_timeframe_days | number | Optional | undefined | Default lookback window. | | bestSeller.min_orders_threshold | number | Optional | 1 | Minimum orders to qualify. | | variantOption | object | Optional | { enabled: true, caseSensitive: false } | Variant option filter behavior. | | variantOption.maxFilters | number | Optional | undefined | Max variant-option filter entries accepted. | | filterProviders | array | Optional | [] | Custom filter providers (path string or { path, options }). | | disableBuiltInProviders | string[] | Optional | [] | Disable specific built-in providers by identifier. | | suggestionProvider | "manual" \| string \| { path: string; options?: object } | Optional | undefined | Product suggestion provider used by /similar and /also-like. | | staleSkipMergeCartCleanup | object | Optional | { expiryDaysForCarts: 2 } | Scheduled job cleanup-stale-skip-merge-carts: soft-delete stale carts in skip_merge_cart. Only expiryDaysForCarts is meant to be set here; cron (0 2 * * *), batch size (100), and max batches per run (10000) are fixed in the job source. | | staleSkipMergeCartCleanup.expiryDaysForCarts | number | Optional | 2 | Carts older than this many full 24h periods (by created_at) qualify. Omit staleSkipMergeCartCleanup or this field for 2 days. 0 or negative disables cleanup in the handler. |

Complete Example

{
  resolve: "medusa-product-helper",
  options: {
    guestJwtSecret: "replace-with-strong-secret",
    default_price_range: {
      label: "custom",
      currency_code: "usd",
      min: null,
      max: null,
    },
    availability: {
      require_in_stock: false,
      include_preorder: true,
      include_backorder: true,
      include_gift_cards: false,
      publishable_only: true,
    },
    rating: {
      enabled: true,
      min: 0,
      max: 5,
      require_reviews: false,
    },
    bestSeller: {
      enabled: true,
      default_timeframe_days: 30,
      min_orders_threshold: 1,
    },
    variantOption: {
      enabled: true,
      caseSensitive: false,
      maxFilters: 10,
    },
    filterProviders: [],
    disableBuiltInProviders: [],
    suggestionProvider: "manual",

    // Optional: only cart expiry is configurable — omit `staleSkipMergeCartCleanup` for default 2 days.
    // staleSkipMergeCartCleanup: { expiryDaysForCarts: 5 },
  },
}

Environment Variables

No dedicated CART_* (or other) environment variables are read for this plugin’s runtime features: stale skip-merge cart cleanup is configured only via staleSkipMergeCartCleanup in plugin options (see table above).

Stale skip-merge cart cleanup job

Job file: src/jobs/cleanup-stale-skip-merge-carts.ts. It resolves options with resolveProductHelperOptions from the Medusa configModule. It soft-deletes carts that are still incomplete, not already deleted, listed in skip_merge_cart (non-deleted marker row), and created_at older than staleSkipMergeCartCleanup.expiryDaysForCarts (default 2 when omitted) full 24h periods. Uses the Cart module’s softDeleteCarts (never hard delete). Before each delete it re-verifies with listCarts so completed carts are never soft-deleted even if they raced the SQL batch.

Job file: src/jobs/backfill-product-display-priorities.ts. Runs every 15 minutes in every shop that loads this plugin. It lists non-gift-card products from the Product module (oldest created_at first) and assigns the next unused whole-number priority to products that still have no product_display_priority row. Existing admin-set values are never overwritten.

Medusa cron note: The worker schedule is only export const config.schedule in the job file (STALE_SKIP_MERGE_CART_CLEANUP_DEFAULT_CRON, typically 0 2 * * * UTC). It is not set via plugin options.

Indexing: skip_merge_cart.cart_id is indexed by migration. For very large cart tables, consider a DBA-reviewed index on cart (e.g. composite on deleted_at, completed_at, created_at) — the plugin does not alter core Medusa tables.

Assumption: PostgreSQL table cart with columns id, created_at, deleted_at, completed_at (Medusa v2 defaults).

⚠️ Note: src/modules/README.md contains generic sample code using process.env.API_KEY, but that is documentation/example content, not runtime plugin logic.


REST APIs / Routes

Route Summary

| Method | Path | Auth | Description | |---|---|---|---| | GET | /store/plugin | Public | Store plugin health endpoint. | | GET | /admin/plugin | Admin | Admin plugin health endpoint. | | GET | /store/product-helper/products | Public (store context) | Filtered store product listing. | | GET | /admin/product-helper/products | Admin | Filtered admin product listing. | | GET | /admin/product-helper/products/:id/display-priority | Admin | Read a product's display priority (defaults to 0 when unset). | | POST | /admin/product-helper/products/:id/display-priority | Admin | Create or update a product's display priority weight. | | POST | /admin/product-helper/products/complete | Admin | POS one-shot product create via core Medusa workflows (product, channels, variant images, inventory). | | GET | /store/product-helper/filters | Public | Filter facets (collections/categories/types/options/metadata/price). | | GET | /store/product-helper/similar | Public | Product recommendations (similar). | | GET | /store/product-helper/also-like | Public | Product recommendations ("also like"). | | GET | /store/product-helper/inventory | Public | Inventory + pending-order summary per product. | | GET | /store/product-helper/promotions/by-product?product_ids=prod_1,prod_2 | Public | Active promotions for one or more products, grouped by product_id (see below). | | GET | /admin/product-helper/promotions/by-product?product_ids=prod_1,prod_2 | Admin | Promotions for one or more products with optional status/date filters, grouped by product_id (see below). | | POST | /store/wishlist | Customer JWT/session | Add product to wishlist. | | GET | /store/wishlist | Customer JWT/session | Read customer wishlist. | | DELETE | /store/wishlist/:product_id | Customer JWT/session | Remove wishlist item. | | GET | /admin/wishlist/stats | Admin JWT/session/API key | Wishlist counts (global or per product). | | POST | /store/product-helper/product-views | Customer JWT/session | Track customer product view. | | GET | /store/product-helper/product-views | Customer JWT/session | List customer views. | | POST | /store/product-helper/product-views/guest | Guest token | Track guest product view. | | GET | /store/product-helper/product-views/guest | Guest token | List guest views. | | GET | /admin/product-helper/product-views | Admin | List and aggregate product view data. | | GET | /store/carts | Customer JWT/session | List active customer carts; optional is_buy_now / is_reorder query filters by cart metadata. | | DELETE | /store/carts/:id | Customer JWT/session | Soft-delete an active cart that belongs to the authenticated customer (404 if not found or not owned). | | POST | /store/carts/merge | Customer JWT/session | Merge guest/current cart into customer cart. | | POST | /store/carts/merge/skip | Public/body validated | Mark a cart as skip-merge. | | GET | /admin/product-helper/carts | Admin | List active carts for admin UI. | | GET | /admin/product-helper/carts/:id | Admin | Fetch cart details and customer context. | | POST | /admin/product-helper/inventory/import | Admin | Import inventory CSV (update-only). | | POST | /admin/product-helper/products/import-with-stock | Admin | Import products CSV (Medusa product columns + stock location/stock). | | GET | /admin/product-helper/products/export-with-stock | Admin | Export products CSV with Stock Location Id + Stock for round-trip Import + Stock. |

Important Request/Response Schemas

  • GET /store/product-helper/products

    • Query includes: region_id (required), paging (limit,offset), common filters (category_id,collection_id,metadata,price_min,price_max,rating_*,best_seller*,[variant]*,option_value, scalar fields like material,origin_country,sku,barcode,ean,upc, etc.).
    • Default sort (no order, or order=priority / display_priority / -display_priority): products are ordered by display_priority descending (missing weights = 0), then created_at descending. Customer sorts (latest, price, best_seller, etc.) override this.
    • Active filters (category, size, color, price, …) still apply; the filtered set keeps the priority order when no customer sort is selected.
    • When price_min and/or price_max is active, each returned product's variants array contains only variants whose regional display price is inside the requested range. Without a price filter, all variants are returned.
    • order=price and order=-price sort the complete filtered product set by each product's minimum returned variant price before pagination, so ordering matches the price visible on listing cards.
    • Product detail retrieval remains separate from this listing endpoint and continues to return the complete variant set.
    • Returns product list + count + pagination metadata; can include computed price-range summary when price_range=true.
  • GET /admin/product-helper/products

    • Same filter family as store endpoint (no mandatory region_id).
    • Same default display-priority sort as the store listing.
    • Returns product list + count + pagination.
  • GET /admin/product-helper/products/:id/display-priority

    • Returns { product_id, display_priority }. Missing rows return display_priority: 0.
    • 404 if the product does not exist.
  • POST /admin/product-helper/products/:id/display-priority

    • Body: { "display_priority": 10 } (number >= 0; decimals are allowed. Negatives are rejected).
    • Upserts the weight for that product. 404 if the product does not exist. 409 if another product already uses that number.
  • POST /store/wishlist

    • Body: { "product_id": "prod_xxx" } (required).
    • Returns created/existing wishlist entry.
  • GET /store/wishlist

    • Query: include_details (true/false, optional).
    • Returns wishlist entries (IDs only or enriched product details via workflow).
  • GET /store/carts

    • Auth: customer JWT or session (same as other customer store routes).
    • Query: standard list params (fields, offset, limit, order) plus optional sales_channel_id and region_id to narrow results. customer_id is never taken from the query; the list is always scoped to the authenticated customer.
    • Optional metadata filters (boolean query params, coerced like true / false): is_buy_now=true returns only carts whose metadata includes is_buy_now: true. is_reorder=true returns only carts with metadata.is_reorder: true. If both are true, only carts matching both keys in metadata are returned. If neither is true, all active carts for the customer are listed (subject to sales_channel_id / region_id as above). When either flag is true, the route uses the Cart module (listAndCountCarts) to resolve which carts match (including pagination count), then re-fetches those carts with Remote Query using the same fields as the unfiltered path so each cart in the response matches the usual store cart graph (totals, items, region, etc.).
    • Returns only active carts: completed_at is null and soft-deleted carts are excluded (deleted_at null). Response: { carts, count, offset, limit } (cart objects follow the requested fields via Remote Query, defaulting to the same graph as core store cart field defaults).
  • DELETE /store/carts/:id

    • Auth: customer JWT or session.
    • Soft-deletes the cart via the Cart module (softDeleteCarts) only when it exists, is active (completed_at and deleted_at null), and customer_id matches the authenticated customer. Otherwise responds with 404 and { "message": "Cart not found" } (including wrong customer or unknown id). 501 if the cart module does not expose softDeleteCarts.
    • Success 200: { "id": "<cart_id>", "object": "cart", "deleted": true }.
  • POST /store/product-helper/product-views

    • Body: { "variant_id": "variant_xxx" } (required).
    • Returns created product_view row.
  • POST /store/product-helper/product-views/guest

    • Body: { "variant_id": "variant_xxx" }.
    • Requires guest token from _medusa_guest_jwt cookie or Authorization: Bearer.
    • Returns created row with guest_id.
  • GET /admin/product-helper/product-views

    • Query supports:
      • raw listing: variant_id, variant_ids, customer_id, limit, offset
      • aggregate by customer: aggregate=customer&customer_id=...
      • aggregate by variant/time: aggregate=variant&variant_id=...&period=1w|1m|1y
  • GET /admin/product-helper/promotions/by-product?product_ids=... and GET /store/product-helper/promotions/by-product?product_ids=...

    • Matching: A promotion is included for a product only if that product's id appears in extracted ids from, in order of inspection: application_method.target_rules, application_method.buy_rules, top-level rules (skipping customer_groups, regions, currency, customer_group, region), and metadata.product_ids. Rule attributes such as items, items.product.id, or product are treated like the built-in promotion product filter. Universal promotions (no extracted product ids) are not listed.

    • Implementation: Performs exactly two graph reads regardless of the number of input ids — one to validate which product ids exist, and one to load candidate promotions (same graph fields as the promotion product filter) with schedule/status filters applied — then buckets promotions to products in memory. No N+1.

    • Required query: product_ids — comma-separated string or repeated query param. 1–200 ids. Empty, blank, or duplicate ids are filtered out before validation. An empty or missing product_ids returns 400.

    • Admin query (optional): status (default active, e.g. draft), promotion_type, starts_at, ends_at, include_open_ended — same semantics as the dynamic filter service promotion fetch.

    • Store query: product_ids only. Status is always active; draft or other statuses cannot be requested.

    • Response:

      Each promotion object includes: id, code, type, status, is_automatic (automatic vs code entry), is_tax_inclusive, limit (max global uses, or null), schedule and audit timestamps (starts_at, ends_at, created_at, updated_at, deleted_at), campaign (id plus optional name / description when loaded), metadata, and application_method (id, type, target_type, allocation, value, currency_code, max_quantity, buy_rules_min_quantity, apply_to_quantity for buy-get flows).

      {
        "products": [
          {
            "product_id": "prod_1",
            "promotions": [
              {
                "id": "promo_1",
                "code": "SAVE10",
                "type": "standard",
                "status": "active",
                "is_automatic": false,
                "is_tax_inclusive": false,
                "limit": null,
                "starts_at": null,
                "ends_at": null,
                "created_at": "2025-01-01T00:00:00.000Z",
                "updated_at": "2025-01-01T00:00:00.000Z",
                "deleted_at": null,
                "campaign": { "id": "camp_1", "name": "Winter sale" },
                "metadata": {},
                "application_method": {
                  "id": "pam_1",
                  "type": "percentage",
                  "target_type": "items",
                  "allocation": "across",
                  "value": 10,
                  "currency_code": "usd",
                  "max_quantity": null,
                  "buy_rules_min_quantity": null,
                  "apply_to_quantity": null
                }
              }
            ]
          },
          { "product_id": "prod_2", "promotions": [] }
        ],
        "invalid_product_ids": ["prod_invalid"]
      }

      products preserves the input order of valid ids; invalid_product_ids preserves the input order of unknown ids. The list of promotions per product is internally capped at 100.

    • Examples:

      # Storefront
      curl -G "https://shop.example.com/store/product-helper/promotions/by-product" \
        --data-urlencode "product_ids=prod_1,prod_2,prod_3"
      
      # Admin
      curl -G "https://shop.example.com/admin/product-helper/promotions/by-product" \
        -H "Authorization: Bearer $ADMIN_TOKEN" \
        --data-urlencode "product_ids=prod_1,prod_2" \
        --data-urlencode "status=draft" \
        --data-urlencode "include_open_ended=true"
  • POST /store/carts/merge/skip

    • Body: { "cart_id": "cart_xxx" } (required).
    • Returns { cart_id, skip_merge: true, created }.
  • POST /admin/product-helper/inventory/import

    • Multipart form-data: file field file (CSV).
    • CSV row schema: id (required), location (string, may be empty), instock (non-negative integer).
    • Success returns { message, total_rows, updated_rows }.
    • Validation failure returns 400 with row-wise errors and no updates applied.
  • POST /admin/product-helper/products/import-with-stock

    • Multipart form-data: file field file (CSV, max ~10MB).
    • Uses Medusa product CSV columns (same rules as core import: product id → update, product handle → create).
    • Extra required headers: stock location id, stock.
    • If variant manage inventory is true (or blank = default true): both stock fields are mandatory; otherwise 400 and no writes.
    • If variant manage inventory is false: stock fields may be empty; no inventory level upsert for that row.
    • Duplicate variant option combinations on the same product are rejected on create and update before any catalog writes (e.g. two rows with Color Marble Grey Denim and Size 5-6Y). Same variant id on multiple stock-location rows is allowed.
    • After product create/update, stock is assigned by variant id, then variant sku, then unique option values (Variant Option N Name/Value), then variant title, then CSV row order within the product. Single-variant products do not need those keys.
    • Stock matching is checked against the planned create/update payload before any catalog writes. If a row cannot be matched, the request returns 400 and no products are imported.
    • If products were created and stock assignment still fails, created products are deleted before the error response. created_products is 0 after a successful rollback.
    • After product create/update, upserts inventory levels at the given stock location.
    • Scientific notation in variant barcode / sku / ean / upc (for example 2.00E+12 or 2E+13 from Google Sheets) is rejected with a row error and no catalog writes. Use the full digit value. Empty barcode cells still leave the existing barcode unchanged.
    • Success: { message, total_rows, created_products, updated_products, inventory_levels_upserted }.
  • GET /admin/product-helper/products/export-with-stock

    • Downloads a CSV of all products/variants with Medusa product columns plus Stock Location Id and Stock.
    • One row per variant×inventory-level (multiple locations → multiple rows for the same variant).
    • Variants with manage inventory = false or no levels export empty stock columns so you can fill them before Import + Stock.
    • Variant Sku, Variant Upc, Variant Ean, and Variant Barcode are written as Excel/Sheets text (quoted + leading tab) so Google Sheets does not convert long barcodes to 2E+13.
    • Response: text/csv attachment (products-with-stock-*.csv).

cURL / Fetch Examples

# Store filtered products
curl "http://localhost:9000/store/product-helper/products?region_id=reg_123&category_id=pcat_123&price_min=1000&price_max=5000"
# Add to wishlist
curl -X POST "http://localhost:9000/store/wishlist" \
  -H "Authorization: Bearer <customer_jwt>" \
  -H "Content-Type: application/json" \
  -d '{"product_id":"prod_123"}'
# List active carts for the authenticated customer
curl "http://localhost:9000/store/carts?limit=20&offset=0" \
  -H "Authorization: Bearer <customer_jwt>"

# List only buy-now carts (metadata.is_buy_now === true)
curl "http://localhost:9000/store/carts?is_buy_now=true&limit=20&offset=0" \
  -H "Authorization: Bearer <customer_jwt>"
# Customer product views
curl -X POST "http://localhost:9000/store/product-helper/product-views" \
  -H "Authorization: Bearer <customer_jwt>" \
  -H "Content-Type: application/json" \
  -d '{"variant_id":"variant_123"}'
# Guest product views
curl -X GET "http://localhost:9000/store/product-helper/product-views/guest?limit=12&offset=0" \
  -H "Authorization: Bearer <guest_token>"
# Admin wishlist stats
curl "http://localhost:9000/admin/wishlist/stats?product_id=prod_123" \
  -H "Authorization: Bearer <admin_token>"
# Inventory import (admin)
curl -X POST "http://localhost:9000/admin/product-helper/inventory/import" \
  -H "Authorization: Bearer <admin_token>" \
  -F "[email protected]"
# Product + stock import (admin)
curl -X POST "http://localhost:9000/admin/product-helper/products/import-with-stock" \
  -H "Authorization: Bearer <admin_token>" \
  -F "[email protected]"
# Product + stock export (admin)
curl -L "http://localhost:9000/admin/product-helper/products/export-with-stock" \
  -H "Authorization: Bearer <admin_token>" \
  -o products-with-stock.csv
# Set product display priority (admin)
curl -X POST "http://localhost:9000/admin/product-helper/products/prod_123/display-priority" \
  -H "Authorization: Bearer <admin_token>" \
  -H "Content-Type: application/json" \
  -d '{"display_priority":10}'

Services

WishlistModuleService

Manages wishlist records in wishlist module.

Key methods:

  • getWishlist(customerId: string, options?: GetWishlistOptions): Promise<WishlistItem[]>
  • addToWishlist(customerId: string, productId: string): Promise<WishlistItem> (idempotent)
  • removeFromWishlist(customerId: string, productId: string): Promise<void>
  • isInWishlist(customerId: string, productId: string): Promise<boolean>
  • getWishlistCounts(productIds?: string[]): Promise<WishlistCount[]>

ProductViewModuleService

Manages product-view records and analytics in product_view module.

Key methods:

  • createProductView(data: { customer_id: string; variant_id: string }): Promise<ProductViewItem>
  • getViewCountsByPeriod(variant_id: string, period: "1w" | "1m" | "1y"): Promise<ViewCountByPeriodResult>

SkipMergeCartModuleService

Tracks carts that should not participate in merge flow.

Key methods:

  • isCartMarkedForSkipMerge(cartId: string): Promise<boolean>
  • markCartForSkipMerge(cartId: string): Promise<{ item: SkipMergeCartItem; created: boolean }>

ProductDisplayPriorityModuleService

Stores a global numeric display weight per product (product_display_priority table). Missing rows are treated as 0. Decimals are allowed; negatives are not. New products get the smallest unused whole number (1, then 2, filling gaps such as 3 when 10 was set manually). Existing products in any Medusa shop that uses this plugin are backfilled by created_at ascending (1, 2, 3, ...) — not by shop-local SQL.

Key methods:

  • getByProductId(productId: string): Promise<ProductDisplayPriorityDTO>
  • listByProductIds(productIds: string[]): Promise<Map<string, number>>
  • upsertDisplayPriority(productId: string, displayPriority: number): Promise<ProductDisplayPriorityDTO>
  • getNextAutoDisplayPriority(): Promise<number>
  • assignAutoDisplayPriority(productId: string): Promise<ProductDisplayPriorityDTO>
  • backfillMissingByCreatedAt(products): Promise<{ assigned: number }>

ProductFilterService

Builds and applies filter plans using request context and DynamicFilterService.

Key methods:

  • applyFilterPlanWithMedusaContext(context, options)
  • Internal extraction of custom filters (category/collection/price/metadata/variant/scalar/etc.).

DynamicFilterService

Runs filter providers, executes product graph queries, and applies post-query filters/sorting. When no customer order is set, listings sort by display priority (ID-first path when only SQL filters are used; after in-memory filters when size/color/price filters are active).

Key methods:

  • applyFilters(options: ApplyFiltersOptions): Promise<ApplyFiltersResult>
  • Registry fallback/auto-registration for providers.

FilterProviderRegistry

In-memory registry for filter providers.

Key methods:

  • register(provider)
  • get(identifier)
  • getAll()
  • getIdentifiers()

Workflows & Steps (Medusa v2)

Defined in src/workflows.

add-to-wishlist

  • Input: { customer_id, product_id }
  • Output: { wishlist_item }
  • Steps:
    • validate-customer-and-product: validates customer/product existence through remote query.
    • add-to-wishlist: inserts or reuses wishlist record.

remove-from-wishlist

  • Input: { customer_id, product_id }
  • Output: { success: boolean }
  • Steps:
    • validate-wishlist-item-exists
    • remove-from-wishlist

get-wishlist

  • Input: { customer_id, options? }
  • Output: { wishlist }
  • Steps:
    • fetch-wishlist-items
    • enrich-with-product-details (best-effort enrichment, does not fail workflow on query error).

Subscribers / Event Hooks

| Subscriber | Event | Behavior | |---|---|---| | assign-product-display-priority | product.created | Assigns the smallest unused whole-number display priority (1, 2, then gaps such as 3 when 10 is already taken). Skips if the product already has a row. |


Admin UI / Widgets

Widgets

| Widget | Zone / Placement | What It Renders | Interactions | Data Source | |---|---|---|---|---| | product-display-priority-widget | product.details.after, product.details.side.after | Display priority weight input on the product detail page | Save numeric weight (higher first; default 0; decimals allowed, negatives rejected) | GET/POST /admin/product-helper/products/:id/display-priority | | product-wishlist-stats | product.details.side.after | Wishlist performance card + top-5 leaderboard | None (read-only insights) | GET /admin/wishlist/stats | | customer-carts-widget | customer.details.side.after | Customer active-cart summary + line-item table | View cart, visit product links | GET /admin/product-helper/carts?customer_id=... | | customer-product-views-widget | customer.details.side.after | Customer product-view counts by product | Read-only table | GET /admin/product-helper/product-views?aggregate=customer... | | product-variant-views-widget | Variant details zone (registered widget) | Bar chart for views over time | Period tabs (1w,1m,1y) | GET /admin/product-helper/product-views?aggregate=variant... | | inventory-import-widget | inventory_item.list.before | Import button on inventory list | CSV picker/upload, toast feedback | POST /admin/product-helper/inventory/import | | product-import-widget | product.list.before | Export + Stock and Import + Stock buttons on products list | CSV download / upload, toast feedback | GET /admin/product-helper/products/export-with-stock, POST /admin/product-helper/products/import-with-stock |

Admin Routes

| Route | Purpose | |---|---| | /app/cart | Active cart listing UI. | | /app/cart/:id | Cart detail UI with customer info and line items. | | /app/product-views | Product-view list UI with filtering and actions. |


Models & Entities

wishlist (src/modules/wishlist/models/wishlist.ts)

| Field | Type | Nullable | |---|---|---| | id | text (PK) | No | | customer_id | text | No | | product_id | text | No |

Relationship to Medusa core entities: stores foreign identifiers (customer_id, product_id) used to query core customer/product records.

product_view (src/modules/product-view/models/product-view.ts)

| Field | Type | Nullable | |---|---|---| | id | text (PK) | No | | customer_id | text | No | | variant_id | text | No |

Relationship to Medusa core entities: links to product variant and actor/customer IDs for analytics.

skip_merge_cart (src/modules/skip-merge-cart/models/skip-merge-cart.ts)

| Field | Type | Nullable | |---|---|---| | id | text (PK) | No | | cart_id | text | No |

Relationship to Medusa core entities: references cart IDs for merge-control behavior.


Use Cases & Examples

  1. Advanced storefront filter UI

    • Scenario: Build faceted browsing with category/collection/metadata/variant/scalar filters.
    • Use: GET /store/product-helper/products and GET /store/product-helper/filters.
  2. Customer wishlist feature

    • Scenario: Allow logged-in users to save products and revisit later.
    • Use: /store/wishlist (POST, GET, DELETE).
  3. Recommendation sections

    • Scenario: Show “Similar products” and “You may also like” blocks.
    • Use: GET /store/product-helper/similar and GET /store/product-helper/also-like with configured suggestionProvider.
  4. Guest engagement tracking

    • Scenario: Track product views before account creation/login.
    • Use: /store/product-helper/product-views/guest with guest JWT.
  5. Admin operations and insight

    • Scenario: Import stock updates from CSV and inspect customer cart/view behavior.
    • Use: inventory import endpoint and admin widgets/pages (/app/cart, /app/product-views).

Known Issues & Fixes

Issue: Create import stock assignment missed multi-variant rows

Problem: POST /admin/product-helper/products/import-with-stock created products (created_products > 0) then returned 400 with Could not match variant for stock assignment. Provide variant id or variant sku when multiple variants exist. for every size/color row.

Root Cause: Create imports mint new variant IDs. Stock matching only used variant id and variant sku. Apparel CSVs usually have option values (Size 2-3Y) and no SKU, so stock never attached.

Solution: Match stock by option combination, variant title, and CSV row order after id/sku. Validate that match against the planned payload before writes. If create already happened and stock still fails, delete the created products.

Prevention:

  • Keep Variant Option N Name / Variant Option N Value columns on create CSVs
  • Prefer unique Variant Sku when option columns are unavailable
  • After a failed stock pass on an older plugin version, delete the leftover created products (or export-with-stock and re-import as updates). Re-uploading the same handle-only CSV will create more products.

Issue: Long barcodes become 2E+13 in Google Sheets

Problem: Export + Stock wrote Variant Barcode as a plain number. Google Sheets converted 12+ digit values to scientific notation (2E+13). Re-import stored that literal string, so POS barcode scans of the printed digits failed.

Root Cause: Excel/Sheets treat unquoted 12+ digit cells as numbers. Import passed identifier columns through as strings with no scientific-notation recovery.

Solution: Export writes Variant Sku / Upc / Ean / Barcode as quoted text with a leading tab. Import rejects scientific notation (2.00E+12, 2E+13, 20e12) with a 400 and no catalog writes.

Prevention:

  • Upgrade medusa-product-helper to 0.0.82+ and re-export before editing in Sheets
  • If barcodes were already overwritten with 2.00E+12 / 2E+13, clear or replace them in Admin/POS (or re-run bulk barcode generate). Empty CSV barcode cells do not clear stored barcodes

Issue: plugin:build TS2589 excessively deep type instantiation

Problem: npm run build failed with TS2589: Type instantiation is excessively deep and possibly infinite on validateAndTransformBody / validateAndTransformQuery / createFindParams().merge().

Root Cause: Schemas imported z from the plugin's zod package (^4.6.5). Medusa 2.21 validators use Zod 4.2.0 from @medusajs/framework/zod. Mixing those type copies makes TypeScript recurse until it gives up.

Solution: Middleware schemas import z from @medusajs/framework/zod. Direct zod is pinned to 4.2.0.

Prevention:

  • Import Zod from @medusajs/framework/zod in any schema passed to Medusa validation helpers.

Troubleshooting

plugin:build TS2589 type instantiation is excessively deep

  • Cause: Zod schemas used import { z } from "zod" while Medusa validators use @medusajs/framework/zod (Zod 4.2.0).
  • Fix: import those schemas from @medusajs/framework/zod and keep zod pinned to 4.2.0.

region_id is required on store product listing

  • Cause: GET /store/product-helper/products enforces region_id.
  • Fix: pass a valid region ID query parameter.

Region <id> has invalid currency_code

  • Cause: region exists but currency code is missing/invalid.
  • Fix: correct region currency in Medusa admin/data.

Suggestion provider is not configured

  • Cause: similar / also-like called without suggestionProvider option.
  • Fix: configure suggestionProvider in plugin options (e.g. "manual" or custom provider path).

Guest product views return 503 config error

  • Cause: guestJwtSecret not set in plugin options.
  • Fix: set guestJwtSecret in plugin config and restart.

Wishlist stats endpoint returns 403

  • Cause: endpoint is admin-only (user/api-key actor types).
  • Fix: call from admin-authenticated context only.

Inventory CSV import fails with row errors

  • Cause: invalid headers/rows, unknown inventory item, ambiguous or missing location mapping, duplicate (id,location) pairs, or non-existing inventory level.
  • Fix: use export-compatible CSV shape (id,location,instock), ensure rows map to existing item-location levels, and fix row-specific errors; re-upload.

Product CSV import fails with duplicate variant combination

  • Cause: two or more variants on the same product share the same option values (for example Color Marble Grey Denim and Size 5-6Y). Medusa allows this on create but rejects it on later CSV update with has same combination of option values.
  • Fix: keep one row per unique option combination. Remove extra duplicate variant rows from the CSV (including products that already have duplicates in the catalog) and re-upload. Multiple stock-location rows for the same variant id are not duplicates.

Barcode scan fails after CSV edit in Google Sheets

  • Cause: Sheets converted a 12+ digit Variant Barcode to 2E+13 / 2.00E+12. Older imports stored that string; the printed label still has the original digits.
  • Fix: upgrade medusa-product-helper to 0.0.82+. Import now returns 400 if barcode/SKU/EAN/UPC is scientific notation (2.01E+12, 2.00E+13, 2E+13). Re-export so those columns stay text, then import full digit barcodes. Clear already-stored scientific values in Admin/POS (CSV blank cells do not remove them), or re-run bulk barcode generate.

Product + stock import created products but stock assignment failed

  • Cause: create imports generate new variant IDs. Older builds only matched stock by variant id / variant sku, so multi-variant rows without SKUs failed with Could not match variant for stock assignment. Those builds also left the created products in the catalog.
  • Fix: upgrade medusa-product-helper to 0.0.79+, rebuild/reinstall the plugin, and restart Medusa. Delete leftover products from earlier failed creates before re-uploading a handle-only create CSV. New imports return 400 without writing products when stock rows cannot be matched, and roll back any products created if a later stock step fails.

Merge/skip cart behavior not persisting

  • Cause: migration for skip_merge_cart not run.
  • Fix: run npx medusa db:migrate.