Skip to content

The complete open source platform to run your entire marketplace. Storefront, vendor panel, admin console, and integrations in one enterprise-grade platform you own.

feat(core): diff attribute edits the way product edits are diffed (#1444)

Viktor Holik2db262955d73
diff --git a/integration-tests/http/product-edit/vendor/product-edit-attributes.spec.ts b/integration-tests/http/product-edit/vendor/product-edit-attributes.spec.ts
new file mode 100644
index 000000000..520f3576e
--- /dev/null
+++ b/integration-tests/http/product-edit/vendor/product-edit-attributes.spec.ts
@@ -0,0 +1,253 @@
+import { MedusaContainer } from "@medusajs/framework/types"
+import { ContainerRegistrationKeys } from "@medusajs/framework/utils"
+import { medusaIntegrationTestRunner } from "@medusajs/test-utils"
+import {
+ MercurModules,
+ ProductChangeActionType,
+ ProductAttributeValueSnapshot,
+} from "@mercurjs/types"
+
+import { createSellerUser } from "../../../helpers/create-seller-user"
+import { createVendorProduct } from "../../../helpers/create-product"
+
+jest.setTimeout(60_000)
+
+/**
+ * Attribute edits are staged through `productEditUpdateAttributesWorkflow`,
+ * which diffs the proposed batch against the product's current selection the
+ * way `productEditUpdateProductWorkflow` diffs native fields. These cover the
+ * diff itself: recorded `previous_value`, dropped no-ops, and the
+ * `attribute_ids` that `PRODUCT_ADD` records at creation.
+ */
+medusaIntegrationTestRunner({
+ testSuite: ({ getContainer, api }) => {
+ describe("Vendor /vendor/products/:id/attributes/batch — attribute diffing", () => {
+ let container: MedusaContainer
+ let sellerHeaders: { headers: Record<string, string> }
+
+ beforeAll(async () => {
+ container = getContainer()
+ })
+
+ beforeEach(async () => {
+ const seller = await createSellerUser(container, {
+ email: "[email protected]",
+ name: "Attr Seller",
+ })
+ sellerHeaders = seller.headers
+ })
+
+ const createGlobalAttribute = async (opts: {
+ name: string
+ type: "single_select" | "multi_select"
+ values: string[]
+ }) => {
+ const service: any = container.resolve(MercurModules.PRODUCT_ATTRIBUTE)
+ const [attribute] = await service.createProductAttributes([
+ {
+ name: opts.name,
+ handle: opts.name.toLowerCase(),
+ type: opts.type,
+ is_variant_axis: false,
+ },
+ ])
+ const values = await service.createProductAttributeValues(
+ opts.values.map((name, rank) => ({
+ name,
+ rank,
+ attribute_id: attribute.id,
+ })),
+ )
+ return {
+ id: attribute.id as string,
+ byName: new Map<string, string>(
+ values.map((v: { id: string; name: string }) => [v.name, v.id]),
+ ),
+ }
+ }
+
+ const actionsOf = async (
+ productId: string,
+ body: Record<string, unknown>,
+ ) => {
+ const res = await api.post(
+ `/vendor/products/${productId}/attributes/batch`,
+ body,
+ sellerHeaders,
+ )
+ expect(res.status).toBe(202)
+ return (res.data.product_change.actions ?? []) as Array<{
+ action: string
+ details: {
+ attribute_id?: string | null
+ value?: unknown
+ previous_value?: ProductAttributeValueSnapshot | null
+ }
+ }>
+ }
+
+ const latestProductAdd = async (productId: string) => {
+ const query = container.resolve(ContainerRegistrationKeys.QUERY)
+ const { data } = await query.graph({
+ entity: "product_change",
+ fields: ["id", "actions.action", "actions.details"],
+ filters: { product_id: productId },
+ })
+ const actions = (
+ data as Array<{
+ actions: Array<{ action: string; details: Record<string, unknown> }>
+ }>
+ ).flatMap((change) => change.actions ?? [])
+ return actions.find(
+ (a) => a.action === ProductChangeActionType.PRODUCT_ADD,
+ )
+ }
+
+ it("records previous_value on an attribute update", async () => {
+ const material = await createGlobalAttribute({
+ name: "Material",
+ type: "single_select",
+ values: ["Cotton", "Wool"],
+ })
+ const cotton = material.byName.get("Cotton")!
+ const wool = material.byName.get("Wool")!
+
+ const product = await createVendorProduct(api, sellerHeaders, {
+ title: "Diffed Product",
+ attributes: [{ id: material.id, value_ids: [cotton] }],
+ })
+
+ const actions = await actionsOf(product.id, {
+ update: [{ id: material.id, add: [wool], remove: [cotton] }],
+ })
+
+ const update = actions.find(
+ (a) => a.action === ProductChangeActionType.ATTRIBUTE_UPDATE,
+ )
+ expect(update).toBeDefined()
+ expect(update!.details.attribute_id).toBe(material.id)
+ expect(update!.details.previous_value).toMatchObject({
+ attribute_id: material.id,
+ value_ids: [cotton],
+ })
+ })
+
+ it("produces zero actions for a no-op attribute edit", async () => {
+ const material = await createGlobalAttribute({
+ name: "Material",
+ type: "single_select",
+ values: ["Cotton", "Wool"],
+ })
+ const cotton = material.byName.get("Cotton")!
+
+ const product = await createVendorProduct(api, sellerHeaders, {
+ title: "Unchanged Product",
+ attributes: [{ id: material.id, value_ids: [cotton] }],
+ })
+
+ // Re-adding the value the product already holds, and removing one it
+ // does not, are both no-ops against the current selection.
+ const actions = await actionsOf(product.id, {
+ update: [
+ { id: material.id, add: [cotton], remove: [material.byName.get("Wool")!] },
+ ],
+ })
+
+ expect(actions).toHaveLength(0)
+ })
+
+ it("skips removing an attribute the product does not hold", async () => {
+ const material = await createGlobalAttribute({
+ name: "Material",
+ type: "single_select",
+ values: ["Cotton"],
+ })
+ const product = await createVendorProduct(api, sellerHeaders, {
+ title: "Bare Product",
+ })
+
+ const actions = await actionsOf(product.id, {
+ remove: [material.id],
+ })
+
+ expect(actions).toHaveLength(0)
+ })
+
+ it("records previous_value when removing an attribute the product holds", async () => {
+ const material = await createGlobalAttribute({
+ name: "Material",
+ type: "single_select",
+ values: ["Cotton"],
+ })
+ const cotton = material.byName.get("Cotton")!
+
+ const product = await createVendorProduct(api, sellerHeaders, {
+ title: "Removable Product",
+ attributes: [{ id: material.id, value_ids: [cotton] }],
+ })
+
+ const actions = await actionsOf(product.id, { remove: [material.id] })
+
+ const removal = actions.find(
+ (a) => a.action === ProductChangeActionType.ATTRIBUTE_REMOVE,
+ )
+ expect(removal).toBeDefined()
+ expect(removal!.details.previous_value).toMatchObject({
+ attribute_id: material.id,
+ value_ids: [cotton],
+ })
+ })
+
+ it("carries attribute_id on adds of an existing attribute", async () => {
+ const material = await createGlobalAttribute({
+ name: "Material",
+ type: "single_select",
+ values: ["Cotton"],
+ })
+ const product = await createVendorProduct(api, sellerHeaders, {
+ title: "Adding Product",
+ })
+
+ const actions = await actionsOf(product.id, {
+ add: [{ id: material.id, value_ids: [material.byName.get("Cotton")!] }],
+ })
+
+ const add = actions.find(
+ (a) => a.action === ProductChangeActionType.ATTRIBUTE_ADD,
+ )
+ expect(add).toBeDefined()
+ expect(add!.details.attribute_id).toBe(material.id)
+ expect(add!.details.previous_value).toBeNull()
+ })
+
+ it("records attribute_ids on PRODUCT_ADD at creation", async () => {
+ const material = await createGlobalAttribute({
+ name: "Material",
+ type: "single_select",
+ values: ["Cotton"],
+ })
+
+ const product = await createVendorProduct(api, sellerHeaders, {
+ title: "Created With Attributes",
+ attributes: [
+ { id: material.id, value_ids: [material.byName.get("Cotton")!] },
+ ],
+ })
+
+ const productAdd = await latestProductAdd(product.id)
+ expect(productAdd).toBeDefined()
+ expect(productAdd!.details.attribute_ids).toEqual([material.id])
+ })
+
+ it("records an empty attribute_ids for a product created without attributes", async () => {
+ const product = await createVendorProduct(api, sellerHeaders, {
+ title: "Created Bare",
+ })
+
+ const productAdd = await latestProductAdd(product.id)
+ expect(productAdd).toBeDefined()
+ expect(productAdd!.details.attribute_ids).toEqual([])
+ })
+ })
+ },
+})
diff --git a/packages/core/src/workflows/product-edit/workflows/product-edit-update-attributes.ts b/packages/core/src/workflows/product-edit/workflows/product-edit-update-attributes.ts
index a4bc57566..798c08912 100644
--- a/packages/core/src/workflows/product-edit/workflows/product-edit-update-attributes.ts
+++ b/packages/core/src/workflows/product-edit/workflows/product-edit-update-attributes.ts
@@ -1,14 +1,18 @@
import { AdditionalData } from "@medusajs/framework/types"
+import { deepEqualObj } from "@medusajs/framework/utils"
import {
createWorkflow,
transform,
WorkflowResponse,
type ReturnWorkflow,
} from "@medusajs/framework/workflows-sdk"
+import { useQueryGraphStep } from "@medusajs/medusa/core-flows"
import {
+ AttributeType,
CreateProductChangeActionDTO,
ProductAttributeBatchAdd,
ProductAttributeBatchUpdate,
+ ProductAttributeValueSnapshot,
ProductChangeActionType,
ProductChangeDTO,
} from "@mercurjs/types"
@@ -27,6 +31,35 @@ export type ProductEditUpdateAttributesWorkflowInput = {
export const productEditUpdateAttributesWorkflowId =
"product-edit-update-attributes"
+type LinkedValue = {
+ id: string
+ name?: string
+ attribute?: { id?: string; type?: AttributeType }
+}
+
+const SCALAR_TYPES = [
+ AttributeType.TEXT,
+ AttributeType.UNIT,
+ AttributeType.TOGGLE,
+]
+
+/**
+ * `text` / `unit` / `toggle` selections are stored as a linked value row whose
+ * `name` carries the scalar, so the scalar is read back off the link.
+ */
+const readScalar = (
+ type: AttributeType | undefined,
+ name: string | undefined,
+): string | number | boolean | null => {
+ if (!type || !SCALAR_TYPES.includes(type) || name === undefined) {
+ return null
+ }
+ if (type === AttributeType.TOGGLE) {
+ return name === "true"
+ }
+ return name
+}
+
export const productEditUpdateAttributesWorkflow: ReturnWorkflow<
ProductEditUpdateAttributesWorkflowInput,
ProductChangeDTO,
@@ -40,37 +73,130 @@ export const productEditUpdateAttributesWorkflow: ReturnWorkflow<
})),
)
- const actions = transform({ input }, ({ input }) => {
- const acts: Array<
- Omit<CreateProductChangeActionDTO, "product_change_id">
- > = []
-
- for (const attribute of input.add ?? []) {
- acts.push({
- product_id: input.product_id,
- action: ProductChangeActionType.ATTRIBUTE_ADD,
- details: { attribute },
- })
- }
-
- for (const attribute_id of input.remove ?? []) {
- acts.push({
- product_id: input.product_id,
- action: ProductChangeActionType.ATTRIBUTE_REMOVE,
- details: { attribute_id },
- })
- }
-
- for (const update of input.update ?? []) {
- acts.push({
- product_id: input.product_id,
- action: ProductChangeActionType.ATTRIBUTE_UPDATE,
- details: { update },
- })
- }
-
- return acts
- })
+ const { data: currentProducts } = useQueryGraphStep({
+ entity: "product",
+ fields: [
+ "id",
+ "product_attribute_values.id",
+ "product_attribute_values.name",
+ "product_attribute_values.attribute.id",
+ "product_attribute_values.attribute.type",
+ ],
+ filters: transform({ input }, ({ input }) => ({ id: input.product_id })),
+ }).config({ name: "load-current-attributes-for-diff" })
+
+ const actions = transform(
+ { input, currentProducts },
+ ({ input, currentProducts }) => {
+ const linked = (
+ (currentProducts?.[0]?.product_attribute_values ?? []) as LinkedValue[]
+ ).filter((value) => value?.attribute?.id)
+
+ const snapshots = new Map<string, ProductAttributeValueSnapshot>()
+ for (const value of linked) {
+ const attributeId = value.attribute!.id!
+ const snapshot = snapshots.get(attributeId) ?? {
+ attribute_id: attributeId,
+ value_ids: [],
+ value: null,
+ }
+ snapshot.value_ids.push(value.id)
+ const scalar = readScalar(value.attribute!.type, value.name)
+ if (scalar !== null) {
+ snapshot.value = scalar
+ }
+ snapshots.set(attributeId, snapshot)
+ }
+ for (const snapshot of snapshots.values()) {
+ snapshot.value_ids.sort()
+ }
+
+ const previousOf = (
+ attributeId: string | null,
+ ): ProductAttributeValueSnapshot | null =>
+ attributeId ? (snapshots.get(attributeId) ?? null) : null
+
+ const acts: Array<
+ Omit<CreateProductChangeActionDTO, "product_change_id">
+ > = []
+
+ for (const attribute of input.add ?? []) {
+ const attributeId = "id" in attribute ? attribute.id : null
+ const previous = previousOf(attributeId)
+
+ // An add whose selection the product already holds changes nothing.
+ if (previous && "id" in attribute) {
+ const proposedIds = [...(attribute.value_ids ?? [])].sort()
+ const sameIds =
+ proposedIds.length > 0 &&
+ deepEqualObj(proposedIds, previous.value_ids)
+ const sameScalar =
+ attribute.value !== undefined &&
+ deepEqualObj(attribute.value, previous.value)
+ if (sameIds || sameScalar) continue
+ }
+
+ acts.push({
+ product_id: input.product_id,
+ action: ProductChangeActionType.ATTRIBUTE_ADD,
+ details: {
+ attribute,
+ attribute_id: attributeId,
+ previous_value: previous,
+ },
+ })
+ }
+
+ for (const attribute_id of input.remove ?? []) {
+ const previous = previousOf(attribute_id)
+ // Removing something the product does not hold changes nothing.
+ if (!previous) continue
+
+ acts.push({
+ product_id: input.product_id,
+ action: ProductChangeActionType.ATTRIBUTE_REMOVE,
+ details: { attribute_id, previous_value: previous },
+ })
+ }
+
+ for (const update of input.update ?? []) {
+ const previous = previousOf(update.id)
+ const currentIds = new Set(previous?.value_ids ?? [])
+
+ const addsNothing = (update.add ?? []).every(
+ (entry) => typeof entry === "string" && currentIds.has(entry),
+ )
+ const removesNothing = (update.remove ?? []).every(
+ (entry) => !currentIds.has(entry),
+ )
+ const scalarUnchanged =
+ update.value === undefined ||
+ deepEqualObj(update.value, previous?.value ?? null)
+
+ if (
+ addsNothing &&
+ removesNothing &&
+ scalarUnchanged &&
+ update.title === undefined
+ ) {
+ continue
+ }
+
+ acts.push({
+ product_id: input.product_id,
+ action: ProductChangeActionType.ATTRIBUTE_UPDATE,
+ details: {
+ update,
+ attribute_id: update.id,
+ value: update.value,
+ previous_value: previous,
+ },
+ })
+ }
+
+ return acts
+ },
+ )
const change = stageProductChangeWorkflow.runAsStep({
input: transform({ input, actions }, ({ input, actions }) => ({
diff --git a/packages/core/src/workflows/product/workflows/create-products.ts b/packages/core/src/workflows/product/workflows/create-products.ts
index fc53e2716..235497949 100644
--- a/packages/core/src/workflows/product/workflows/create-products.ts
+++ b/packages/core/src/workflows/product/workflows/create-products.ts
@@ -224,22 +224,52 @@ export const createProductsWorkflow: ReturnWorkflow<
name: "mercur-create-products-associate-sellers",
})
+ // Read the attributes back off the products so PRODUCT_ADD records what
+ // each one started with. Without it, "which attributes did this product
+ // begin with" has no answer: attaching at creation emits no attribute action.
+ const { data: attachedAttributes } = useQueryGraphStep({
+ entity: "product",
+ fields: ["id", "product_attribute_values.attribute.id"],
+ filters: transform({ createdProducts }, ({ createdProducts }) => ({
+ id: createdProducts.map((product) => product.id as string),
+ })),
+ }).config({ name: "mercur-create-products-attached-attributes" })
+
recordProductAuditChangeWorkflow.runAsStep({
input: transform(
- { createdProducts, input },
- ({ createdProducts, input }) => ({
- actor_id: input.created_by,
- changes: createdProducts.map((product) => ({
- product_id: product.id as string,
- actions: [
- {
- product_id: product.id as string,
- action: ProductChangeActionType.PRODUCT_ADD,
- details: { status: product.status as string },
- },
- ],
- })),
- }),
+ { createdProducts, input, attachedAttributes },
+ ({ createdProducts, input, attachedAttributes }) => {
+ const attributeIdsByProduct = new Map<string, string[]>()
+ for (const product of (attachedAttributes ?? []) as Array<{
+ id: string
+ product_attribute_values?: Array<{ attribute?: { id?: string } }>
+ }>) {
+ const ids = new Set(
+ (product.product_attribute_values ?? [])
+ .map((value) => value.attribute?.id)
+ .filter((id): id is string => !!id),
+ )
+ attributeIdsByProduct.set(product.id, Array.from(ids).sort())
+ }
+
+ return {
+ actor_id: input.created_by,
+ changes: createdProducts.map((product) => ({
+ product_id: product.id as string,
+ actions: [
+ {
+ product_id: product.id as string,
+ action: ProductChangeActionType.PRODUCT_ADD,
+ details: {
+ status: product.status as string,
+ attribute_ids:
+ attributeIdsByProduct.get(product.id as string) ?? [],
+ },
+ },
+ ],
+ })),
+ }
+ },
),
})
diff --git a/packages/types/src/index.ts b/packages/types/src/index.ts
index 2355b295d..b610257f5 100644
--- a/packages/types/src/index.ts
+++ b/packages/types/src/index.ts
@@ -58,6 +58,7 @@ export {
type ProductAttributeBatchAdd,
type ProductAttributeBatchUpdate,
type ProductAttributeBatchInput,
+ type ProductAttributeValueSnapshot,
type CreateProductChangeDTO,
type CreateProductChangeActionDTO,
} from "./product"
diff --git a/packages/types/src/product/mutations.ts b/packages/types/src/product/mutations.ts
index 97bac8f62..e41fbe9fb 100644
--- a/packages/types/src/product/mutations.ts
+++ b/packages/types/src/product/mutations.ts
@@ -159,6 +159,22 @@ export type ProductAttributeBatchUpdate = {
value?: string | number | boolean
}
+/**
+ * One attribute's selection on a product at a point in time. Recorded as
+ * `previous_value` on attribute product-change actions so a timeline of
+ * `add` / `remove` / `value` deltas can be replayed from its starting state.
+ *
+ * `value_ids` is sorted so two snapshots of the same selection compare equal
+ * regardless of link order.
+ */
+export type ProductAttributeValueSnapshot = {
+ attribute_id: string
+ /** Sorted. Every linked value id, whatever the attribute type. */
+ value_ids: string[]
+ /** The scalar for `text` / `unit` / `toggle`; `null` for select types. */
+ value: string | number | boolean | null
+}
+
/**
* Input for the attribute batch attach/detach/update engine
* (`createAndLinkProductAttributesToProductWorkflow`). Applied in the order