diff --git a/src/products/views/ProductUpdate/handlers/utils.test.ts b/src/products/views/ProductUpdate/handlers/utils.test.ts new file mode 100644 index 000000000..5ae4950f7 --- /dev/null +++ b/src/products/views/ProductUpdate/handlers/utils.test.ts @@ -0,0 +1,76 @@ +import { ProductFragment } from "@saleor/graphql"; +import { ProductUpdateSubmitData } from "@saleor/products/components/ProductUpdatePage/types"; + +import { inferProductChannelsAfterUpdate } from "./utils"; + +describe("Product update utils", () => { + it("should infer product channels after update with data", () => { + const product = { + channelListings: [ + { + channel: { + id: "1", + }, + }, + { + channel: { + id: "2", + }, + }, + { + channel: { + id: "3", + }, + }, + ], + } as ProductFragment; + + const submitData = { + channels: { + updateChannels: [ + { + channelId: "1", + }, + { + channelId: "4", + }, + ], + removeChannels: ["2"], + }, + } as ProductUpdateSubmitData; + + const result = inferProductChannelsAfterUpdate(product, submitData); + + expect(result).toEqual(["1", "3", "4"]); + }); + + it("should infer product channels after update without data", () => { + const product = { + channelListings: [ + { + channel: { + id: "1", + }, + }, + { + channel: { + id: "2", + }, + }, + { + channel: { + id: "3", + }, + }, + ], + } as ProductFragment; + + const submitData = { + channels: {}, + } as ProductUpdateSubmitData; + + const result = inferProductChannelsAfterUpdate(product, submitData); + + expect(result).toEqual(["1", "2", "3"]); + }); +}); diff --git a/src/products/views/ProductUpdate/handlers/utils.ts b/src/products/views/ProductUpdate/handlers/utils.ts index 46dee15b0..a2cad4420 100644 --- a/src/products/views/ProductUpdate/handlers/utils.ts +++ b/src/products/views/ProductUpdate/handlers/utils.ts @@ -61,14 +61,30 @@ const hasChannel = ( return variant.channelListings.some(c => c.channel.id === channelId); }; +export function inferProductChannelsAfterUpdate( + product: ProductFragment, + data: ProductUpdateSubmitData, +) { + const productChannelsIds = product.channelListings.map( + listing => listing.channel.id, + ); + const updatedChannelsIds = + data.channels.updateChannels?.map(listing => listing.channelId) || []; + const removedChannelsIds = data.channels.removeChannels || []; + + return uniq([ + ...productChannelsIds.filter( + channelId => !removedChannelsIds.includes(channelId), + ), + ...updatedChannelsIds, + ]); +} + export function getProductChannelsUpdateVariables( product: ProductFragment, data: ProductUpdateSubmitData, ): ProductChannelListingUpdateMutationVariables { - const channels = uniq([ - ...product.channelListings.map(listing => listing.channel.id), - ...data.channels.updateChannels.map(listing => listing.channelId), - ]); + const channels = inferProductChannelsAfterUpdate(product, data); const dataUpdated = new Map(); data.channels.updateChannels