The 1C exchange runs as Medusa workflows, and the plugin exposes hooks in several of them. A hook handler receives what the exchange is about to write to Medusa or send to 1C, and returns a corrected version. That's how you move 1C requisites into product fields, add data Medusa doesn't have to an order, or enable a price list for a customer group, without changing the plugin's code.
A workflow hook is a point inside a Medusa workflow where you plug in your own function. Medusa calls it while the workflow runs and passes it data, and the workflow uses whatever the function returns. Read more in the Medusa documentation.
| Workflow | Hook | When It Runs | What It Changes |
|---|---|---|---|
importOnecProductsWorkflow | setProducts | on every catalog batch, up to 100 products | Medusa products from import.xml |
importOnecVariantsWorkflow | setVariants | on every offers batch, up to 100 products | product variants and their options from offers.xml |
importOnecPricesWorkflow | setPriceLists | on every offers batch, up to 100 products | price lists of non-retail price types and their prices |
exportOnecOrdersWorkflow | setOrders | once per order export | the order documents that go to 1C |
exportOnecOrdersWorkflow, exportOnecCatalogWorkflow | setPayload | once per export, when the XML is built | the XML of the order or catalog export |
Import the workflows from @gorgo-store/medusa-erp-1c/workflows. Import the hook input and result types, as well as the functions that read 1C requisites and properties, from @gorgo-store/medusa-erp-1c/hooks.
Since version 1.0.0, hook names and element shapes are part of the plugin's public contract and change only in major versions of the plugin.
Register the handler in a file under src/workflows/hooks in your Medusa project, and Medusa loads it when the server starts. For example, this handler keeps 1C services out of the store:
src/workflows/hooks/onec-catalog.ts1import { StepResponse } from "@medusajs/framework/workflows-sdk"2import { importOnecProductsWorkflow } from "@gorgo-store/medusa-erp-1c/workflows"3import { readRequisite } from "@gorgo-store/medusa-erp-1c/hooks"45importOnecProductsWorkflow.hooks.setProducts(async ({ products }) => {6 return new StepResponse({7 products: products.filter(({ source }) => readRequisite(source, "ВидНоменклатуры") !== "Услуга"),8 })9})
The handler receives the batch's products and returns them in a StepResponse, keeping only those whose "ВидНоменклатуры" requisite isn't "Услуга" (service). The readRequisite function reads a requisite of a 1C product by its name, so you don't have to parse CommerceML yourself.
Every hook except setPayload receives an array of elements. An element brings together everything the handler needs to make a decision:
source – the record the result is built from. On import, it's the 1C record, all the product's offers for setVariants, and on export, the Medusa order.existing – the current Medusa record. It's passed only on import, and only for a record that already exists in Medusa.product for a product, variants for a product's variants, priceList and prices for a price type, and document for an order.The handler edits the target field and returns the elements. setPayload works differently. It receives the finished XML as a string and handles changes that the product or document model can't express, for example the schema version your 1C configuration expects.
new StepResponse({ <array> }). The plugin uses only the array, so you don't need to return the other input keys.product, priceList or a variant in variants to leave that field unchanged. That way a value set in the Medusa Admin survives the exchange. An order document goes to 1C in full, and a deleted key turns into an empty node in orders.xml. So change values in a document instead of deleting them.Ид before calling the hook, and 1C recognizes an order by the document's Ид. If a handler breaks this rule, the plugin stops the exchange with an error naming the hook.If a handler returns a plain object or nothing, the exchange stops with an error like importOnecProductsWorkflow.hooks.setProducts handler must return new StepResponse({ products }), it returned nothing usable. Medusa passes the plugin only what's inside the StepResponse.
Medusa allows only one handler per hook in the whole application. If you register a second handler on the same hook, the server fails to start with the error Cannot define multiple hook handlers for the setProducts hook. Combine all of your project's changes for one hook into a single handler and run them one after another inside it.
The handler runs inside a workflow step, and 1C waits for a response the whole time. setProducts, setVariants and setPriceLists run on every batch, so with a 10,000-product catalog each of them runs a hundred times. The workflow engine copies the hook's input and result, along with anything you add to an element.
Here's how three kinds of setProducts handler affect the exchange:
| Handler | Database Queries per Catalog Import | Catalog Re-Import Time |
|---|---|---|
| Only fields from the input | as many as without a handler | within measurement noise |
| One query per batch | +10 | within measurement noise |
| One query per product | +990 | +12% |
The measurements used a catalog of 1,000 products and 4,000 offers, which is 10 batches, with a local PostgreSQL where one query takes about a millisecond. The table shows medians of three runs, and a single run for the query-per-product handler. A re-import writes almost nothing, so a handler's cost shows most there. With a remote database, network latency is added to every query, and the gap grows.
To keep a handler from slowing the exchange down:
query.graph call filtered by that array of keys, and put the response into a Map.StepResponse. The plugin commits each batch separately, and a batch that fails rolls back only its own changes.This is what a query per product looks like. For a batch of 100 products, it's 100 queries:
1for (const item of products) {2 const [brand] = readProperty(item.source, properties, "Бренд")3 const { data } = await query.graph({4 entity: "product_collection",5 fields: ["id"],6 filters: { title: brand },7 })8 // ...9}
One query per batch gets the same data for all products at once:
1const titles = products.flatMap(({ source }) => readProperty(source, properties, "Бренд"))2const { data } = await query.graph({3 entity: "product_collection",4 fields: ["id", "title"],5 filters: { title: titles },6})7const collectionIdByTitle = new Map(data.map((collection) => [collection.title, collection.id]))
The full example with this query is on the Hook Examples page.
On a test catalog of a few products, queries per product go unnoticed. They show up on the full catalog, once the exchange is already running in production.
Start the server with LOG_LEVEL=debug. The plugin logs the duration of every catalog import step, and the hook's step is named after the hook itself:
[1C Integration] import: import-onec-products › setProducts 35 ms
setVariants and setPriceLists run inside the child workflows of the offers import, so their time is part of the overall import-onec-offers finished in … ms line. For exports, the plugin doesn't log step durations.