|
1
|
import { ProductTypes } from "@medusajs/framework/types" |
|
2
|
|
|
3
|
export interface OptionLinkChanges { |
|
4
|
linkPairs: ProductTypes.ProductOptionProductPair[] |
|
5
|
unlinkPairs: ProductTypes.ProductOptionProductPair[] |
|
6
|
expectedOptionIdsMap: Map<string, Set<string>> |
|
7
|
} |
|
8
|
|
|
9
|
/** |
|
10
|
* Computes the option link/unlink pairs needed when updating products with option_ids. |
|
11
|
* Also tracks which products have variant updates for validation filtering. |
|
12
|
*/ |
|
13
|
export function computeOptionLinkChanges( |
|
14
|
data: Array<{ id: string; option_ids?: string[]; variants?: any }>, |
|
15
|
originalProducts: Array<{ id: string; options?: { id: string }[] }> |
|
16
|
): OptionLinkChanges { |
|
17
|
const linkPairs: ProductTypes.ProductOptionProductPair[] = [] |
|
18
|
const unlinkPairs: ProductTypes.ProductOptionProductPair[] = [] |
|
19
|
const expectedOptionIdsMap = new Map<string, Set<string>>() |
|
20
|
|
|
21
|
for (const product of data) { |
|
22
|
if (!product.option_ids) { |
|
23
|
continue |
|
24
|
} |
|
25
|
|
|
26
|
const newOptionIds = new Set(product.option_ids) |
|
27
|
|
|
28
|
if (product.variants) { |
|
29
|
expectedOptionIdsMap.set(product.id, newOptionIds) |
|
30
|
} |
|
31
|
|
|
32
|
const existingOptionIds = new Set( |
|
33
|
originalProducts |
|
34
|
.find((p) => p.id === product.id) |
|
35
|
?.options?.map((o) => o.id) ?? [] |
|
36
|
) |
|
37
|
|
|
38
|
for (const optionId of newOptionIds) { |
|
39
|
if (!existingOptionIds.has(optionId)) { |
|
40
|
linkPairs.push({ |
|
41
|
product_id: product.id, |
|
42
|
product_option_id: optionId, |
|
43
|
}) |
|
44
|
} |
|
45
|
} |
|
46
|
|
|
47
|
for (const optionId of existingOptionIds) { |
|
48
|
if (!newOptionIds.has(optionId)) { |
|
49
|
unlinkPairs.push({ |
|
50
|
product_id: product.id, |
|
51
|
product_option_id: optionId, |
|
52
|
}) |
|
53
|
} |
|
54
|
} |
|
55
|
} |
|
56
|
|
|
57
|
return { linkPairs, unlinkPairs, expectedOptionIdsMap } |
|
58
|
} |