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(product-attributes): accept value_ids on batch update (#1481)

Viktor Holik9fecae5d0cb4
diff --git a/apps/docs/references/api/admin/products/batch-product-attributes.mdx b/apps/docs/references/api/admin/products/batch-product-attributes.mdx
index 44087646b..2707474c9 100644
--- a/apps/docs/references/api/admin/products/batch-product-attributes.mdx
+++ b/apps/docs/references/api/admin/products/batch-product-attributes.mdx
@@ -39,6 +39,7 @@ Applies attribute changes to the product in the order `remove` → `add` → `up
<ParamField body="title" type="string">New attribute title.</ParamField>
<ParamField body="add" type="(string | object)[]">Value names (or `{ value }` objects) to add to the selection.</ParamField>
<ParamField body="remove" type="string[]">Value IDs to remove from the selection.</ParamField>
+ <ParamField body="value_ids" type="string[]">The complete set of value IDs the product should hold for this attribute. Resolved into the equivalent `add` / `remove` delta, so it cannot be combined with either.</ParamField>
<ParamField body="value" type="string | number | boolean">New scalar value for non-select types.</ParamField>
</Expandable>
</ParamField>
diff --git a/apps/docs/references/api/vendor/products/batch-product-attributes.mdx b/apps/docs/references/api/vendor/products/batch-product-attributes.mdx
index 998d52a70..27b831644 100644
--- a/apps/docs/references/api/vendor/products/batch-product-attributes.mdx
+++ b/apps/docs/references/api/vendor/products/batch-product-attributes.mdx
@@ -46,6 +46,7 @@ Stages attribute operations as a pending change request instead of applying them
<ParamField body="title" type="string">New attribute title.</ParamField>
<ParamField body="add" type="(string | object)[]">Values to select, plain strings or `{ "value": "..." }` objects.</ParamField>
<ParamField body="remove" type="string[]">Value IDs to deselect.</ParamField>
+ <ParamField body="value_ids" type="string[]">The complete set of value IDs the product should hold for this attribute. Resolved into the equivalent `add` / `remove` delta, so it cannot be combined with either.</ParamField>
<ParamField body="value" type="string | number | boolean">New scalar value for `text`, `unit`, or `toggle` attributes.</ParamField>
</Expandable>
</ParamField>
diff --git a/integration-tests/http/product/vendor/product.spec.ts b/integration-tests/http/product/vendor/product.spec.ts
index 6edee44c5..0c57ab1c8 100644
--- a/integration-tests/http/product/vendor/product.spec.ts
+++ b/integration-tests/http/product/vendor/product.spec.ts
@@ -282,6 +282,96 @@ medusaIntegrationTestRunner({
expect(err.response.status).toBeGreaterThanOrEqual(400)
})
+ it("update: value_ids replaces the selection of an attached non-axis attribute", async () => {
+ const material = await createAttr({
+ name: "Material",
+ type: AttributeType.MULTI_SELECT,
+ values: ["Cotton", "Wool", "Silk"],
+ })
+ const cotton = material.byName.get("Cotton")!
+ const wool = material.byName.get("Wool")!
+ const silk = material.byName.get("Silk")!
+ const productId = await createOwnedProduct()
+
+ await batch(productId, {
+ add: [{ id: material.id, value_ids: [cotton, wool] }],
+ })
+
+ const res = await batch(productId, {
+ update: [{ id: material.id, value_ids: [wool, silk] }],
+ })
+
+ expect(res.status).toEqual(202)
+ const product = await getProduct(productId)
+ const applied = (product.attributes ?? []).find(
+ (a: any) => a.id === material.id,
+ )
+ expect((applied.values ?? []).map((v: any) => v.name).sort()).toEqual([
+ "Silk",
+ "Wool",
+ ])
+ })
+
+ it("update: value_ids on an axis attribute keeps the shared option attached", async () => {
+ const color = await createAttr({
+ name: "AxisColor",
+ type: AttributeType.MULTI_SELECT,
+ is_variant_axis: true,
+ values: ["Red", "Blue"],
+ })
+ const red = color.byName.get("Red")!
+ const blue = color.byName.get("Blue")!
+ const productId = await createOwnedProduct()
+
+ await batch(productId, {
+ add: [{ id: color.id, value_ids: [red] }],
+ })
+ expect(await optionAttached(productId, "AxisColor")).toBe(true)
+
+ const res = await batch(productId, {
+ update: [{ id: color.id, value_ids: [blue] }],
+ })
+
+ expect(res.status).toEqual(202)
+ const product = await getProduct(productId)
+ const applied = (product.attributes ?? []).find(
+ (a: any) => a.id === color.id,
+ )
+ expect((applied.values ?? []).map((v: any) => v.name)).toEqual(["Blue"])
+ // The mirror option is never unlinked/relinked to change the subset.
+ expect(await optionAttached(productId, "AxisColor")).toBe(true)
+
+ const query = appContainer.resolve(ContainerRegistrationKeys.QUERY)
+ const { data } = await query.graph({
+ entity: "product_option",
+ fields: ["id", "title", "is_exclusive"],
+ filters: { title: "AxisColor" },
+ })
+ expect(data[0].is_exclusive).toBe(false)
+ })
+
+ it("update: rejects value_ids combined with add", async () => {
+ const material = await createAttr({
+ name: "ConflictMaterial",
+ type: AttributeType.MULTI_SELECT,
+ values: ["Cotton", "Wool"],
+ })
+ const cotton = material.byName.get("Cotton")!
+ const wool = material.byName.get("Wool")!
+ const productId = await createOwnedProduct()
+
+ await batch(productId, {
+ add: [{ id: material.id, value_ids: [cotton] }],
+ })
+
+ const err = await batch(productId, {
+ update: [{ id: material.id, value_ids: [wool], add: [wool] }],
+ }).catch((e) => e)
+
+ expect(err.response.status).toEqual(400)
+ expect(err.response.data.message).toContain("value_ids")
+ })
+
})
describe("Vendor - product list scoping", () => {
diff --git a/packages/core/src/api/admin/products/validators.ts b/packages/core/src/api/admin/products/validators.ts
index e28cfc930..17308385e 100644
--- a/packages/core/src/api/admin/products/validators.ts
+++ b/packages/core/src/api/admin/products/validators.ts
@@ -401,9 +401,15 @@ const BatchAttributeUpdate = z
.array(z.union([z.string(), z.object({ value: z.string() }).strict()]))
.optional(),
remove: z.array(z.string()).optional(),
+ value_ids: z.array(z.string()).optional(),
value: BatchAttributeScalar.optional(),
})
.strict()
+ .refine((v) => !v.value_ids || (!v.add && !v.remove), {
+ message:
+ "value_ids replaces the whole selection and cannot be combined with add or remove",
+ path: ["value_ids"],
+ })
const BatchProductAttributes = z.object({
add: z.array(BatchAttributeAdd).optional(),
diff --git a/packages/core/src/api/vendor/products/validators.ts b/packages/core/src/api/vendor/products/validators.ts
index 40ac9aee5..19e81a319 100644
--- a/packages/core/src/api/vendor/products/validators.ts
+++ b/packages/core/src/api/vendor/products/validators.ts
@@ -387,9 +387,15 @@ const VendorBatchAttributeUpdate = z
.array(z.union([z.string(), z.object({ value: z.string() }).strict()]))
.optional(),
remove: z.array(z.string()).optional(),
+ value_ids: z.array(z.string()).optional(),
value: VendorBatchAttributeScalar.optional(),
})
.strict()
+ .refine((v) => !v.value_ids || (!v.add && !v.remove), {
+ message:
+ "value_ids replaces the whole selection and cannot be combined with add or remove",
+ path: ["value_ids"],
+ })
export type VendorBatchProductAttributesType = z.infer<
typeof VendorBatchProductAttributes
diff --git a/packages/core/src/workflows/product-attribute/workflows/update-product-attributes-on-product.ts b/packages/core/src/workflows/product-attribute/workflows/update-product-attributes-on-product.ts
index 6ba5d1258..ab0d7221b 100644
--- a/packages/core/src/workflows/product-attribute/workflows/update-product-attributes-on-product.ts
+++ b/packages/core/src/workflows/product-attribute/workflows/update-product-attributes-on-product.ts
@@ -78,12 +78,47 @@ export const updateProductAttributesOnProductWorkflow = createWorkflow(
options: { isList: false },
}).config({ name: "upd-pa-product" })
+ // `value_ids` is replace-the-set sugar: it resolves against the values the
+ // product currently holds into the same add / remove delta the plans below
+ // already apply.
+ const resolvedUpdate = transform(
+ { input, productQuery },
+ ({ input, productQuery }) => {
+ const linkedByAttr = new Map<string, string[]>()
+ for (const v of (productQuery.data?.product_attribute_values ?? []) as {
+ id: string
+ attribute?: { id: string }
+ }[]) {
+ if (!v.attribute) {
+ continue
+ }
+ const list = linkedByAttr.get(v.attribute.id) ?? []
+ list.push(v.id)
+ linkedByAttr.set(v.attribute.id, list)
+ }
+
+ return input.update.map((ref) => {
+ if (!ref.value_ids) {
+ return ref
+ }
+ const { value_ids, ...rest } = ref
+ const next = new Set(value_ids)
+ const current = linkedByAttr.get(ref.id) ?? []
+ return {
+ ...rest,
+ add: value_ids.filter((id) => !current.includes(id)),
+ remove: current.filter((id) => !next.has(id)),
+ }
+ })
+ },
+ )
+
// The formatter reads the selected axis subset from the pivot (native
// options populate is broken on 2.16), so the product_attribute_value_link
// pivot must be kept in sync with the option value subset.
const subsetPlan = transform(
- { input, attributesQuery },
- ({ input, attributesQuery }) => {
+ { input, attributesQuery, resolvedUpdate },
+ ({ input, attributesQuery, resolvedUpdate }) => {
const product_id = input.product_id
const attrsById = new Map(
((attributesQuery.data ?? []) as ProductAttributeDTO[]).map((a) => [
@@ -94,33 +129,43 @@ export const updateProductAttributesOnProductWorkflow = createWorkflow(
const updates: ProductTypes.ProductOptionProductValueUpdate[] = []
const addLinks: LinkDefinition[] = []
const dismissLinks: LinkDefinition[] = []
- for (const ref of input.update) {
+ for (const ref of resolvedUpdate) {
const attr = attrsById.get(ref.id)
- if (!attr || !isAxis(attr) || attr.product_id) {
+ if (!attr) {
+ continue
+ }
+ const sharedAxis = isAxis(attr) && !attr.product_id
+ const nonAxisSelect =
+ !isAxis(attr) &&
+ (attr.type === AttributeType.MULTI_SELECT ||
+ attr.type === AttributeType.SINGLE_SELECT)
+ if (!sharedAxis && !nonAxisSelect) {
continue
}
- const optvalByValueId = new Map(
- (attr.values ?? []).map((v) => [v.id, v.product_option_value_id]),
- )
const addValueIds = (ref.add ?? []).filter(
(a): a is string => typeof a === "string",
)
const removeValueIds = (ref.remove ?? []).filter(
(id): id is string => typeof id === "string",
)
- const add = addValueIds
- .map((vid) => optvalByValueId.get(vid))
- .filter((id): id is string => !!id)
- const remove = removeValueIds
- .map((vid) => optvalByValueId.get(vid))
- .filter((id): id is string => !!id)
- if (add.length || remove.length) {
- updates.push({
- product_id,
- product_option_id: attr.product_option_id as string,
- add,
- remove,
- })
+ if (sharedAxis) {
+ const optvalByValueId = new Map(
+ (attr.values ?? []).map((v) => [v.id, v.product_option_value_id]),
+ )
+ const add = addValueIds
+ .map((vid) => optvalByValueId.get(vid))
+ .filter((id): id is string => !!id)
+ const remove = removeValueIds
+ .map((vid) => optvalByValueId.get(vid))
+ .filter((id): id is string => !!id)
+ if (add.length || remove.length) {
+ updates.push({
+ product_id,
+ product_option_id: attr.product_option_id as string,
+ add,
+ remove,
+ })
+ }
}
for (const vid of addValueIds) {
addLinks.push({
@@ -162,8 +207,8 @@ export const updateProductAttributesOnProductWorkflow = createWorkflow(
)
const swapPlan = transform(
- { input, attributesQuery, productQuery },
- ({ input, attributesQuery, productQuery }) => {
+ { input, attributesQuery, productQuery, resolvedUpdate },
+ ({ input, attributesQuery, productQuery, resolvedUpdate }) => {
const product_id = input.product_id
const attrsById = new Map(
((attributesQuery.data ?? []) as ProductAttributeDTO[]).map((a) => [
@@ -191,7 +236,7 @@ export const updateProductAttributesOnProductWorkflow = createWorkflow(
const toggleLinks: LinkDefinition[] = []
const dismissLinks: LinkDefinition[] = []
- for (const ref of input.update) {
+ for (const ref of resolvedUpdate) {
if (ref.value === undefined) {
continue
}
@@ -284,15 +329,15 @@ export const updateProductAttributesOnProductWorkflow = createWorkflow(
)
const exclusivePlan = transform(
- { input, attributesQuery },
- ({ input, attributesQuery }) => {
+ { attributesQuery, resolvedUpdate },
+ ({ attributesQuery, resolvedUpdate }) => {
const attrsById = new Map(
((attributesQuery.data ?? []) as ProductAttributeDTO[]).map((a) => [
a.id,
a,
]),
)
- const exclusive = input.update.filter((ref) => {
+ const exclusive = resolvedUpdate.filter((ref) => {
const attr = attrsById.get(ref.id)
return !!attr && isAxis(attr) && !!attr.product_id
})
@@ -438,15 +483,15 @@ export const updateProductAttributesOnProductWorkflow = createWorkflow(
)
const renamePlan = transform(
- { input, attributesQuery },
- ({ input, attributesQuery }) => {
+ { attributesQuery, resolvedUpdate },
+ ({ attributesQuery, resolvedUpdate }) => {
const attrsById = new Map(
((attributesQuery.data ?? []) as ProductAttributeDTO[]).map((a) => [
a.id,
a,
]),
)
- const renames = input.update.filter((ref) => {
+ const renames = resolvedUpdate.filter((ref) => {
const attr = attrsById.get(ref.id)
return (
ref.title !== undefined &&
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 ff4909ad0..30f3e0879 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
@@ -189,11 +189,15 @@ export const productEditUpdateAttributesWorkflow: ReturnWorkflow<
const scalarUnchanged =
update.value === undefined ||
deepEqualObj(update.value, previous?.value ?? null)
+ const selectionUnchanged =
+ update.value_ids === undefined ||
+ deepEqualObj([...update.value_ids].sort(), previous?.value_ids ?? [])
if (
addsNothing &&
removesNothing &&
scalarUnchanged &&
+ selectionUnchanged &&
update.title === undefined
) {
continue
diff --git a/packages/dashboard-shared/src/components/forms/edit-attribute-form/edit-attribute-form.tsx b/packages/dashboard-shared/src/components/forms/edit-attribute-form/edit-attribute-form.tsx
index c2c9e3893..c49fa6127 100644
--- a/packages/dashboard-shared/src/components/forms/edit-attribute-form/edit-attribute-form.tsx
+++ b/packages/dashboard-shared/src/components/forms/edit-attribute-form/edit-attribute-form.tsx
@@ -324,19 +324,9 @@ const EditCatalogAttributeForm = ({
.filter((v) => vals.includes(v.name))
.map((v) => v.id)
- if (!isAttached) {
- payload = { add: [{ id: attribute.id, value_ids: selectedIds }] }
- } else if (attribute.is_variant_axis) {
- const currentIds = (attribute.values ?? []).map((v) => v.id)
- const add = selectedIds.filter((id) => !currentIds.includes(id))
- const remove = currentIds.filter((id) => !selectedIds.includes(id))
- payload = { update: [{ id: attribute.id, add, remove }] }
- } else {
- payload = {
- remove: [attribute.id],
- add: [{ id: attribute.id, value_ids: selectedIds }],
- }
- }
+ payload = isAttached
+ ? { update: [{ id: attribute.id, value_ids: selectedIds }] }
+ : { add: [{ id: attribute.id, value_ids: selectedIds }] }
} else if (!isAttached) {
payload = { add: [{ id: attribute.id, value: scalarValue }] }
} else {
diff --git a/packages/types/src/product/mutations.ts b/packages/types/src/product/mutations.ts
index ede07d289..7a4d721bb 100644
--- a/packages/types/src/product/mutations.ts
+++ b/packages/types/src/product/mutations.ts
@@ -155,6 +155,12 @@ export type ProductAttributeBatchUpdate = {
* (exclusive axis) to remove.
*/
remove?: string[]
+ /**
+ * The complete set of attribute value ids the product should hold for this
+ * attribute — resolved against the current selection into the same
+ * `add` / `remove` delta. Mutually exclusive with `add` / `remove`.
+ */
+ value_ids?: string[]
/** The new free-form scalar for `text` / `unit` / `toggle` attributes. */
value?: string | number | boolean
}