Raw
1 import { medusaIntegrationTestRunner } from "@medusajs/test-utils"
2 import path from "path"
3
4 jest.setTimeout(100000)
5
6 import { createProductsWorkflow } from "@medusajs/core-flows"
7 import { Modules, QueryContext } from "@medusajs/utils"
8 import { TranslationModule } from "../__fixtures__/translation-test/src/modules/translation/service"
9
10 const createTranslations = async (container, inputs) => {
11 const translationModule: any = container.resolve("translation")
12
13 const created = await translationModule.createTranslations(inputs as any)
14 return Array.isArray(created) ? created : [created]
15 }
16
17 const attachTranslationToProduct = async (
18 container,
19 { productId, translation }
20 ) => {
21 const [created] = await createTranslations(container, [translation])
22
23 const remoteLink: any = container.resolve("remoteLink")
24 await remoteLink.create({
25 [Modules.PRODUCT]: { product_id: productId },
26 translation: { translation_id: created.id },
27 })
28
29 return created
30 }
31
32 const attachTranslationToVariant = async (
33 container,
34 { variantId, translation }
35 ) => {
36 const [created] = await createTranslations(container, [translation])
37
38 const remoteLink: any = container.resolve("remoteLink")
39 await remoteLink.create({
40 [Modules.PRODUCT]: { product_variant_id: variantId },
41 translation: { translation_id: created.id },
42 })
43
44 return created
45 }
46
47 const attachTranslationToOption = async (
48 container,
49 { optionId, translation }
50 ) => {
51 const [created] = await createTranslations(container, [translation])
52
53 const remoteLink: any = container.resolve("remoteLink")
54 await remoteLink.create({
55 [Modules.PRODUCT]: { product_option_id: optionId },
56 translation: { translation_id: created.id },
57 })
58
59 return created
60 }
61
62 const attachTranslationToProductCategory = async (
63 container,
64 { categoryId, translation }
65 ) => {
66 const [created] = await createTranslations(container, [translation])
67
68 const remoteLink: any = container.resolve("remoteLink")
69 await remoteLink.create({
70 [Modules.PRODUCT]: { product_category_id: categoryId },
71 translation: { translation_id: created.id },
72 })
73
74 return created
75 }
76
77 medusaIntegrationTestRunner({
78 cwd: path.join(__dirname, "../__fixtures__/translation-test"),
79 testSuite: ({ getContainer }) => {
80 describe("query.graph()", () => {
81 beforeEach(async () => {
82 const container = getContainer()
83 const productService: any = container.resolve("product")
84
85 const categories = await Promise.all(
86 [1, 2, 3].map((i) =>
87 productService.createProductCategories({
88 name: `Category ${i}`,
89 })
90 )
91 )
92
93 const buildProduct = (i: number, categoryId: string) => ({
94 title: `Product ${i}`,
95 category_ids: [categoryId],
96 options: [
97 {
98 title: "size",
99 values: ["small", "large"],
100 },
101 ],
102 variants: [
103 {
104 title: `P${i} Variant 1`,
105 options: { size: "small" },
106 prices: [
107 {
108 amount: 10,
109 currency_code: "usd",
110 },
111 ],
112 },
113 {
114 title: `P${i} Variant 2`,
115 options: { size: "large" },
116 prices: [
117 {
118 amount: 20,
119 currency_code: "usd",
120 },
121 ],
122 },
123 ],
124 })
125
126 const createdProducts = await Promise.all(
127 [1, 2, 3].map(
128 async (i) =>
129 await createProductsWorkflow(container).run({
130 input: {
131 products: [buildProduct(i, categories[i - 1].id)],
132 },
133 })
134 )
135 )
136
137 const productsWithRels = await Promise.all(
138 createdProducts.map((p) =>
139 productService.retrieveProduct(p.result[0].id, {
140 relations: [
141 "variants",
142 "options",
143 "options.values",
144 "categories",
145 ],
146 })
147 )
148 )
149
150 await Promise.all(
151 productsWithRels.map(async (p, idx) => {
152 const i = idx + 1
153 await attachTranslationToProduct(getContainer(), {
154 productId: p.id,
155 translation: {
156 key: p.id,
157 value: {
158 pt: { title: `Produto ${i}` },
159 fr: { title: `Produit ${i}` },
160 },
161 },
162 })
163
164 const cat = p.categories?.[0]
165 if (cat) {
166 await attachTranslationToProductCategory(getContainer(), {
167 categoryId: cat.id,
168 translation: {
169 key: cat.id,
170 value: {
171 pt: { name: `Categoria ${i}` },
172 fr: { name: `Catégorie ${i}` },
173 },
174 },
175 })
176 }
177
178 const opt = p.options?.[0]
179 if (opt) {
180 await attachTranslationToOption(getContainer(), {
181 optionId: opt.id,
182 translation: {
183 key: opt.id,
184 value: {
185 pt: { title: "Tamanho" },
186 fr: { title: "Taille" },
187 },
188 },
189 })
190 }
191
192 await Promise.all(
193 (p.variants || []).map((v, vi) => {
194 const variantNumber = v.title.split("").pop()
195 return attachTranslationToVariant(getContainer(), {
196 variantId: v.id,
197 translation: {
198 key: v.id,
199 value: {
200 pt: { title: `Variante ${variantNumber}` },
201 fr: { title: `Variante ${variantNumber}` },
202 },
203 },
204 })
205 })
206 )
207 })
208 )
209 })
210
211 it("should call same entity in different levels (variant)", async () => {
212 const container = getContainer()
213 const query = container.resolve("query")
214 const productService = container.resolve(Modules.PRODUCT)
215 const inventoryService = container.resolve(Modules.INVENTORY)
216
217 const productServiceSpy = jest.spyOn(
218 productService,
219 "listProductVariants"
220 )
221 const inventoryServiceSpy = jest.spyOn(
222 inventoryService,
223 "listInventoryItems"
224 )
225
226 const result = await query.graph({
227 entity: "variants",
228 fields: [
229 "id",
230 "manage_inventory",
231 "inventory.id",
232 "inventory.variants.id",
233 ],
234 })
235
236 expect(productServiceSpy).toHaveBeenCalledTimes(2)
237 expect(inventoryServiceSpy).toHaveBeenCalledTimes(1)
238 })
239
240 it("should call services in correct order with parallel execution where possible", async () => {
241 const container = getContainer()
242
243 const query = container.resolve("query")
244 const productService = container.resolve(Modules.PRODUCT)
245 const priceService = container.resolve(Modules.PRICING)
246 const translationService = container.resolve(
247 "translation"
248 ) as TranslationModule
249
250 const productServiceSpy = jest.spyOn(productService, "listProducts")
251 const translationServiceSpy = jest.spyOn(
252 translationService,
253 "listTranslations"
254 )
255 const priceServiceSpy = jest.spyOn(priceService, "listPriceSets")
256
257 // Execute the query
258 const result = await query.graph({
259 entity: "product",
260 fields: [
261 "sales_channels.name",
262 "title",
263 "translation.*",
264 "categories.name",
265 "categories.translation.*",
266 "variants.title",
267 "variants.translation.*",
268 "options.title",
269 "options.translation.*",
270 "variants.prices.amount",
271 "variants.prices.currency_code",
272 ],
273 })
274
275 expect(productServiceSpy.mock.calls[0][1]).toEqual({
276 select: [
277 "title",
278 "variants_id",
279 "id",
280 "categories.name",
281 "categories.id",
282 "variants.title",
283 "variants.id",
284 "options.title",
285 "options.id",
286 ],
287 relations: ["categories", "variants", "options"],
288 args: {},
289 })
290
291 expect(translationServiceSpy.mock.calls[0][0].id).toHaveLength(3)
292 expect(translationServiceSpy.mock.calls[1][0].id).toHaveLength(12)
293 expect(priceServiceSpy.mock.calls[0][0].id).toHaveLength(6)
294
295 expect(result.data).toEqual(
296 expect.arrayContaining([
297 expect.objectContaining({
298 title: "Product 3",
299 categories: [
300 expect.objectContaining({
301 name: "Category 3",
302 translation: expect.objectContaining({
303 value: {
304 fr: {
305 name: "Catégorie 3",
306 },
307 pt: {
308 name: "Categoria 3",
309 },
310 },
311 }),
312 }),
313 ],
314 variants: expect.arrayContaining([
315 expect.objectContaining({
316 title: "P3 Variant 2",
317 translation: expect.objectContaining({
318 value: {
319 fr: {
320 title: "Variante 2",
321 },
322 pt: {
323 title: "Variante 2",
324 },
325 },
326 }),
327 prices: expect.arrayContaining([
328 expect.objectContaining({
329 amount: 20,
330 currency_code: "usd",
331 }),
332 ]),
333 }),
334 expect.objectContaining({
335 title: "P3 Variant 1",
336 translation: expect.objectContaining({
337 value: {
338 fr: {
339 title: "Variante 1",
340 },
341 pt: {
342 title: "Variante 1",
343 },
344 },
345 }),
346 prices: expect.arrayContaining([
347 expect.objectContaining({
348 amount: 10,
349 currency_code: "usd",
350 }),
351 ]),
352 }),
353 ]),
354 options: expect.arrayContaining([
355 expect.objectContaining({
356 title: "size",
357 translation: expect.objectContaining({
358 value: {
359 fr: {
360 title: "Taille",
361 },
362 pt: {
363 title: "Tamanho",
364 },
365 },
366 }),
367 }),
368 ]),
369 sales_channels: [],
370 translation: expect.objectContaining({
371 value: {
372 fr: {
373 title: "Produit 3",
374 },
375 pt: {
376 title: "Produto 3",
377 },
378 },
379 }),
380 }),
381 expect.objectContaining({
382 title: "Product 1",
383 categories: [
384 expect.objectContaining({
385 name: "Category 1",
386 translation: expect.objectContaining({
387 value: {
388 fr: {
389 name: "Catégorie 1",
390 },
391 pt: {
392 name: "Categoria 1",
393 },
394 },
395 }),
396 }),
397 ],
398 variants: expect.arrayContaining([
399 expect.objectContaining({
400 title: "P1 Variant 2",
401 translation: expect.objectContaining({
402 value: {
403 fr: {
404 title: "Variante 2",
405 },
406 pt: {
407 title: "Variante 2",
408 },
409 },
410 }),
411 prices: expect.arrayContaining([
412 expect.objectContaining({
413 amount: 20,
414 currency_code: "usd",
415 }),
416 ]),
417 }),
418 expect.objectContaining({
419 title: "P1 Variant 1",
420 translation: expect.objectContaining({
421 value: {
422 fr: {
423 title: "Variante 1",
424 },
425 pt: {
426 title: "Variante 1",
427 },
428 },
429 }),
430 prices: expect.arrayContaining([
431 expect.objectContaining({
432 amount: 10,
433 currency_code: "usd",
434 }),
435 ]),
436 }),
437 ]),
438 options: expect.arrayContaining([
439 expect.objectContaining({
440 title: "size",
441 translation: expect.objectContaining({
442 value: {
443 fr: {
444 title: "Taille",
445 },
446 pt: {
447 title: "Tamanho",
448 },
449 },
450 }),
451 }),
452 ]),
453 sales_channels: [],
454 translation: expect.objectContaining({
455 value: {
456 fr: {
457 title: "Produit 1",
458 },
459 pt: {
460 title: "Produto 1",
461 },
462 },
463 }),
464 }),
465 expect.objectContaining({
466 title: "Product 2",
467 categories: [
468 expect.objectContaining({
469 name: "Category 2",
470 translation: expect.objectContaining({
471 value: {
472 fr: {
473 name: "Catégorie 2",
474 },
475 pt: {
476 name: "Categoria 2",
477 },
478 },
479 }),
480 }),
481 ],
482 variants: expect.arrayContaining([
483 expect.objectContaining({
484 title: "P2 Variant 1",
485 translation: expect.objectContaining({
486 value: {
487 fr: {
488 title: "Variante 1",
489 },
490 pt: {
491 title: "Variante 1",
492 },
493 },
494 }),
495 prices: expect.arrayContaining([
496 expect.objectContaining({
497 amount: 10,
498 currency_code: "usd",
499 }),
500 ]),
501 }),
502 expect.objectContaining({
503 title: "P2 Variant 2",
504 translation: expect.objectContaining({
505 value: {
506 fr: {
507 title: "Variante 2",
508 },
509 pt: {
510 title: "Variante 2",
511 },
512 },
513 }),
514 prices: expect.arrayContaining([
515 expect.objectContaining({
516 amount: 20,
517 currency_code: "usd",
518 }),
519 ]),
520 }),
521 ]),
522 options: expect.arrayContaining([
523 expect.objectContaining({
524 title: "size",
525 translation: expect.objectContaining({
526 value: {
527 fr: {
528 title: "Taille",
529 },
530 pt: {
531 title: "Tamanho",
532 },
533 },
534 }),
535 }),
536 ]),
537 sales_channels: [],
538 translation: expect.objectContaining({
539 value: {
540 fr: {
541 title: "Produit 2",
542 },
543 pt: {
544 title: "Produto 2",
545 },
546 },
547 }),
548 }),
549 ])
550 )
551 })
552
553 describe("cross-module filtering", () => {
554 it("should filter variants by linked price set id", async () => {
555 const container = getContainer()
556 const query = container.resolve("query")
557
558 const { data: variants } = await query.graph({
559 entity: "variant",
560 fields: ["id", "title", "price_set.id"],
561 })
562
563 const targetVariant = variants.find(
564 (variant) => variant.title === "P1 Variant 1"
565 )
566
567 expect(targetVariant?.price_set?.id).toBeDefined()
568
569 const { data: filteredVariants } = await query.graph({
570 entity: "variant",
571 fields: ["id", "title"],
572 filters: {
573 price_set: {
574 id: targetVariant!.price_set!.id,
575 },
576 },
577 })
578
579 expect(filteredVariants).toHaveLength(1)
580 expect(filteredVariants[0]).toEqual(
581 expect.objectContaining({
582 id: targetVariant!.id,
583 title: "P1 Variant 1",
584 })
585 )
586 })
587
588 it("should filter products by linked translation key", async () => {
589 const container = getContainer()
590 const query = container.resolve("query")
591
592 const { data: products } = await query.graph({
593 entity: "product",
594 fields: ["id", "title", "translation.key"],
595 })
596
597 const targetProduct = products.find(
598 (product) => product.title === "Product 2"
599 )
600
601 expect(targetProduct?.translation?.key).toBeDefined()
602
603 const { data: filteredProducts } = await query.graph({
604 entity: "product",
605 fields: ["id", "title"],
606 filters: {
607 translation: {
608 key: targetProduct!.translation!.key,
609 },
610 },
611 })
612
613 expect(filteredProducts).toHaveLength(1)
614 expect(filteredProducts[0]).toEqual(
615 expect.objectContaining({
616 id: targetProduct!.id,
617 title: "Product 2",
618 })
619 )
620 })
621
622 it("should filter price sets by linked variant id", async () => {
623 const container = getContainer()
624 const query = container.resolve("query")
625
626 const { data: variants } = await query.graph({
627 entity: "variant",
628 fields: ["id", "title", "price_set.id"],
629 })
630
631 const targetVariant = variants.find(
632 (variant) => variant.title === "P2 Variant 2"
633 )
634
635 expect(targetVariant?.price_set?.id).toBeDefined()
636
637 const { data: filteredPriceSets } = await query.graph({
638 entity: "price_set",
639 fields: ["id"],
640 filters: {
641 variant: {
642 id: targetVariant!.id,
643 },
644 },
645 })
646
647 expect(filteredPriceSets).toHaveLength(1)
648 expect(filteredPriceSets[0]).toEqual(
649 expect.objectContaining({
650 id: targetVariant!.price_set!.id,
651 })
652 )
653 })
654
655 // Traverses a module-internal relation (cart -> items) before crossing
656 // modules twice (line item -> product via read-only link, product ->
657 // sales channel via link module).
658 it("should filter carts by product sales channel", async () => {
659 const container = getContainer()
660 const query = container.resolve("query")
661 const remoteLink: any = container.resolve("remoteLink")
662 const cartService: any = container.resolve(Modules.CART)
663 const salesChannelService: any = container.resolve(
664 Modules.SALES_CHANNEL
665 )
666
667 const { data: products } = await query.graph({
668 entity: "product",
669 fields: ["id", "title"],
670 })
671
672 const retailProduct = products.find(
673 (product) => product.title === "Product 1"
674 )
675 const wholesaleProduct = products.find(
676 (product) => product.title === "Product 2"
677 )
678
679 expect(retailProduct).toBeDefined()
680 expect(wholesaleProduct).toBeDefined()
681
682 const retailChannel = await salesChannelService.createSalesChannels({
683 name: "Retail Store",
684 })
685 const wholesaleChannel =
686 await salesChannelService.createSalesChannels({
687 name: "Wholesale Store",
688 })
689
690 await remoteLink.create([
691 {
692 [Modules.PRODUCT]: { product_id: retailProduct!.id },
693 [Modules.SALES_CHANNEL]: { sales_channel_id: retailChannel.id },
694 },
695 {
696 [Modules.PRODUCT]: { product_id: wholesaleProduct!.id },
697 [Modules.SALES_CHANNEL]: {
698 sales_channel_id: wholesaleChannel.id,
699 },
700 },
701 ])
702
703 await cartService.createCarts([
704 {
705 currency_code: "usd",
706 email: "retail-cart@test.com",
707 items: [
708 {
709 title: retailProduct!.title,
710 product_id: retailProduct!.id,
711 quantity: 1,
712 unit_price: 100,
713 },
714 ],
715 },
716 {
717 currency_code: "usd",
718 email: "wholesale-cart@test.com",
719 items: [
720 {
721 title: wholesaleProduct!.title,
722 product_id: wholesaleProduct!.id,
723 quantity: 1,
724 unit_price: 100,
725 },
726 ],
727 },
728 ])
729
730 const { data: filteredCarts } = await query.graph({
731 entity: "cart",
732 fields: ["id", "email"],
733 filters: {
734 items: {
735 product: {
736 sales_channels: {
737 name: "Retail Store",
738 },
739 },
740 },
741 },
742 })
743
744 expect(filteredCarts).toHaveLength(1)
745 expect(filteredCarts[0]).toEqual(
746 expect.objectContaining({
747 email: "retail-cart@test.com",
748 })
749 )
750 })
751
752 it("should filter by linked entity using operators", async () => {
753 const container = getContainer()
754 const query = container.resolve("query")
755
756 const { data: variants } = await query.graph({
757 entity: "variant",
758 fields: ["id", "title", "price_set.id"],
759 })
760
761 const targetVariants = variants.filter((variant) =>
762 ["P1 Variant 1", "P2 Variant 1"].includes(variant.title)
763 )
764 const priceSetIds = targetVariants.map(
765 (variant) => variant.price_set!.id
766 )
767
768 expect(priceSetIds).toHaveLength(2)
769
770 const { data: filteredVariants } = await query.graph({
771 entity: "variant",
772 fields: ["id", "title"],
773 filters: {
774 price_set: {
775 id: { $in: priceSetIds },
776 },
777 },
778 })
779
780 expect(filteredVariants).toHaveLength(2)
781 expect(
782 filteredVariants.map((variant) => variant.title).sort()
783 ).toEqual(["P1 Variant 1", "P2 Variant 1"])
784 })
785
786 it("should combine native and cross-module filters", async () => {
787 const container = getContainer()
788 const query = container.resolve("query")
789
790 const { data: variants } = await query.graph({
791 entity: "variant",
792 fields: ["id", "title", "price_set.id"],
793 })
794
795 const p1Variant = variants.find(
796 (variant) => variant.title === "P1 Variant 1"
797 )
798 const p2Variant = variants.find(
799 (variant) => variant.title === "P2 Variant 1"
800 )
801
802 const { data: matching } = await query.graph({
803 entity: "variant",
804 fields: ["id", "title"],
805 filters: {
806 title: "P1 Variant 1",
807 price_set: { id: p1Variant!.price_set!.id },
808 },
809 })
810
811 expect(matching).toHaveLength(1)
812 expect(matching[0].id).toEqual(p1Variant!.id)
813
814 // Same native filter, but the linked filter points elsewhere: the
815 // conditions must intersect, not union.
816 const { data: disjoint } = await query.graph({
817 entity: "variant",
818 fields: ["id", "title"],
819 filters: {
820 title: "P1 Variant 1",
821 price_set: { id: p2Variant!.price_set!.id },
822 },
823 })
824
825 expect(disjoint).toHaveLength(0)
826 })
827
828 it("should return no rows when the linked filter matches nothing", async () => {
829 const container = getContainer()
830 const query = container.resolve("query")
831
832 const { data: filteredVariants } = await query.graph({
833 entity: "variant",
834 fields: ["id"],
835 filters: {
836 price_set: { id: "pset_does_not_exist" },
837 },
838 })
839
840 expect(filteredVariants).toHaveLength(0)
841 })
842
843 it("should return the linked relation while filtering by it", async () => {
844 const container = getContainer()
845 const query = container.resolve("query")
846
847 const { data: variants } = await query.graph({
848 entity: "variant",
849 fields: ["id", "title", "price_set.id"],
850 })
851
852 const targetVariant = variants.find(
853 (variant) => variant.title === "P3 Variant 2"
854 )
855
856 const { data: filteredVariants } = await query.graph({
857 entity: "variant",
858 fields: ["id", "title", "price_set.id"],
859 filters: {
860 price_set: { id: targetVariant!.price_set!.id },
861 },
862 })
863
864 expect(filteredVariants).toHaveLength(1)
865 expect(filteredVariants[0]).toEqual(
866 expect.objectContaining({
867 id: targetVariant!.id,
868 price_set: expect.objectContaining({
869 id: targetVariant!.price_set!.id,
870 }),
871 })
872 )
873 })
874
875 it("should filter carts by a read-only link on the root entity", async () => {
876 const container = getContainer()
877 const query = container.resolve("query")
878 const cartService: any = container.resolve(Modules.CART)
879 const salesChannelService: any = container.resolve(
880 Modules.SALES_CHANNEL
881 )
882
883 const retailChannel = await salesChannelService.createSalesChannels({
884 name: "Retail Store",
885 })
886 const wholesaleChannel =
887 await salesChannelService.createSalesChannels({
888 name: "Wholesale Store",
889 })
890
891 await cartService.createCarts([
892 {
893 currency_code: "usd",
894 email: "retail-cart@test.com",
895 sales_channel_id: retailChannel.id,
896 },
897 {
898 currency_code: "usd",
899 email: "wholesale-cart@test.com",
900 sales_channel_id: wholesaleChannel.id,
901 },
902 ])
903
904 const { data: filteredCarts } = await query.graph({
905 entity: "cart",
906 fields: ["id", "email"],
907 filters: {
908 sales_channel: {
909 name: "Retail Store",
910 },
911 },
912 })
913
914 expect(filteredCarts).toHaveLength(1)
915 expect(filteredCarts[0]).toEqual(
916 expect.objectContaining({
917 email: "retail-cart@test.com",
918 })
919 )
920 })
921
922 // Order uses a custom find/findAndCount that bypasses the base
923 // repository prepareFindOptions — this covers that those methods apply
924 // cross-module join filters themselves.
925 it("should filter orders by a read-only linked sales channel", async () => {
926 const container = getContainer()
927 const query = container.resolve("query")
928 const orderService: any = container.resolve(Modules.ORDER)
929 const salesChannelService: any = container.resolve(
930 Modules.SALES_CHANNEL
931 )
932
933 const retailChannel = await salesChannelService.createSalesChannels({
934 name: "Order Retail Channel",
935 })
936 const wholesaleChannel =
937 await salesChannelService.createSalesChannels({
938 name: "Order Wholesale Channel",
939 })
940
941 await orderService.createOrders([
942 {
943 currency_code: "usd",
944 email: "retail-order@test.com",
945 sales_channel_id: retailChannel.id,
946 items: [
947 {
948 title: "Retail item",
949 quantity: 1,
950 unit_price: 100,
951 },
952 ],
953 },
954 {
955 currency_code: "usd",
956 email: "wholesale-order@test.com",
957 sales_channel_id: wholesaleChannel.id,
958 items: [
959 {
960 title: "Wholesale item",
961 quantity: 1,
962 unit_price: 100,
963 },
964 ],
965 },
966 ])
967
968 const { data: filteredOrders } = await query.graph({
969 entity: "order",
970 fields: ["id", "email"],
971 filters: {
972 sales_channel: {
973 name: "Order Retail Channel",
974 },
975 },
976 })
977
978 expect(filteredOrders).toHaveLength(1)
979 expect(filteredOrders[0]).toEqual(
980 expect.objectContaining({
981 email: "retail-order@test.com",
982 })
983 )
984 })
985
986 it("should filter carts by a field of the read-only linked product", async () => {
987 const container = getContainer()
988 const query = container.resolve("query")
989 const cartService: any = container.resolve(Modules.CART)
990
991 const { data: products } = await query.graph({
992 entity: "product",
993 fields: ["id", "title", "handle"],
994 })
995
996 const productOne = products.find(
997 (product) => product.title === "Product 1"
998 )
999 const productTwo = products.find(
1000 (product) => product.title === "Product 2"
1001 )
1002
1003 await cartService.createCarts([
1004 {
1005 currency_code: "usd",
1006 email: "cart-one@test.com",
1007 items: [
1008 {
1009 title: productOne!.title,
1010 product_id: productOne!.id,
1011 quantity: 1,
1012 unit_price: 100,
1013 },
1014 ],
1015 },
1016 {
1017 currency_code: "usd",
1018 email: "cart-two@test.com",
1019 items: [
1020 {
1021 title: productTwo!.title,
1022 product_id: productTwo!.id,
1023 quantity: 1,
1024 unit_price: 100,
1025 },
1026 ],
1027 },
1028 ])
1029
1030 const { data: filteredCarts } = await query.graph({
1031 entity: "cart",
1032 fields: ["id", "email"],
1033 filters: {
1034 items: {
1035 product: {
1036 handle: productOne!.handle,
1037 },
1038 },
1039 },
1040 })
1041
1042 expect(filteredCarts).toHaveLength(1)
1043 expect(filteredCarts[0]).toEqual(
1044 expect.objectContaining({
1045 email: "cart-one@test.com",
1046 })
1047 )
1048 })
1049
1050 it("should combine root and expand cross-module filters", async () => {
1051 const container = getContainer()
1052 const query = container.resolve("query")
1053 const cartService: any = container.resolve(Modules.CART)
1054 const salesChannelService: any = container.resolve(
1055 Modules.SALES_CHANNEL
1056 )
1057
1058 const { data: products } = await query.graph({
1059 entity: "product",
1060 fields: ["id", "title", "handle"],
1061 })
1062
1063 const productOne = products.find(
1064 (product) => product.title === "Product 1"
1065 )
1066 const productTwo = products.find(
1067 (product) => product.title === "Product 2"
1068 )
1069
1070 const retailChannel = await salesChannelService.createSalesChannels({
1071 name: "Retail Store",
1072 })
1073 const wholesaleChannel = await salesChannelService.createSalesChannels(
1074 {
1075 name: "Wholesale Store",
1076 }
1077 )
1078
1079 const buildCart = (
1080 email: string,
1081 channelId: string,
1082 product: { title: string; id: string }
1083 ) => ({
1084 currency_code: "usd",
1085 email,
1086 sales_channel_id: channelId,
1087 items: [
1088 {
1089 title: product.title,
1090 product_id: product.id,
1091 quantity: 1,
1092 unit_price: 100,
1093 },
1094 ],
1095 })
1096
1097 await cartService.createCarts([
1098 // Matches both filters.
1099 buildCart("match@test.com", retailChannel.id, productOne!),
1100 // Matches only the root filter (retail channel, other product).
1101 buildCart("root-only@test.com", retailChannel.id, productTwo!),
1102 // Matches only the expand filter (other channel, right product).
1103 buildCart("expand-only@test.com", wholesaleChannel.id, productOne!),
1104 ])
1105
1106 // `sales_channel` is filtered at the root level (read-only link on
1107 // the cart itself), while `items.product` lands on an expand node —
1108 // both must be pushed down and intersect.
1109 const { data: filteredCarts } = await query.graph({
1110 entity: "cart",
1111 fields: ["id", "email"],
1112 filters: {
1113 sales_channel: {
1114 name: "Retail Store",
1115 },
1116 items: {
1117 product: {
1118 handle: productOne!.handle,
1119 },
1120 },
1121 },
1122 })
1123
1124 expect(filteredCarts).toHaveLength(1)
1125 expect(filteredCarts[0]).toEqual(
1126 expect.objectContaining({
1127 email: "match@test.com",
1128 })
1129 )
1130 })
1131
1132 it("should filter through an inverse read-only link and an internal relation", async () => {
1133 const container = getContainer()
1134 const query = container.resolve("query")
1135 const cartService: any = container.resolve(Modules.CART)
1136 const salesChannelService: any = container.resolve(
1137 Modules.SALES_CHANNEL
1138 )
1139
1140 const retailChannel = await salesChannelService.createSalesChannels({
1141 name: "Retail Store",
1142 })
1143 const wholesaleChannel = await salesChannelService.createSalesChannels(
1144 {
1145 name: "Wholesale Store",
1146 }
1147 )
1148
1149 await cartService.createCarts([
1150 {
1151 currency_code: "usd",
1152 email: "retail-cart@test.com",
1153 sales_channel_id: retailChannel.id,
1154 items: [
1155 {
1156 title: "Retail Item",
1157 quantity: 1,
1158 unit_price: 100,
1159 },
1160 ],
1161 },
1162 {
1163 currency_code: "usd",
1164 email: "wholesale-cart@test.com",
1165 sales_channel_id: wholesaleChannel.id,
1166 items: [
1167 {
1168 title: "Wholesale Item",
1169 quantity: 1,
1170 unit_price: 100,
1171 },
1172 ],
1173 },
1174 ])
1175
1176 // Inverse read-only link: the join column (cart.sales_channel_id)
1177 // lives on the target table.
1178 const { data: channelsByCartEmail } = await query.graph({
1179 entity: "sales_channel",
1180 fields: ["id", "name"],
1181 filters: {
1182 carts: { email: "retail-cart@test.com" },
1183 },
1184 })
1185
1186 expect(channelsByCartEmail).toHaveLength(1)
1187 expect(channelsByCartEmail[0]).toEqual(
1188 expect.objectContaining({ name: "Retail Store" })
1189 )
1190
1191 // Internal relation chained after the inverse link must correlate
1192 // on the cart's PK, not the inverse join column.
1193 const { data: channelsByItemTitle } = await query.graph({
1194 entity: "sales_channel",
1195 fields: ["id", "name"],
1196 filters: {
1197 carts: {
1198 items: { title: "Wholesale Item" },
1199 },
1200 },
1201 })
1202
1203 expect(channelsByItemTitle).toHaveLength(1)
1204 expect(channelsByItemTitle[0]).toEqual(
1205 expect.objectContaining({ name: "Wholesale Store" })
1206 )
1207 })
1208
1209 it("should sort by a cross-module field", async () => {
1210 const container = getContainer()
1211 const query = container.resolve("query")
1212 const cartService: any = container.resolve(Modules.CART)
1213 const salesChannelService: any = container.resolve(
1214 Modules.SALES_CHANNEL
1215 )
1216
1217 const alphaChannel = await salesChannelService.createSalesChannels({
1218 name: "Alpha Store",
1219 })
1220 const zuluChannel = await salesChannelService.createSalesChannels({
1221 name: "Zulu Store",
1222 })
1223
1224 await cartService.createCarts([
1225 {
1226 currency_code: "usd",
1227 email: "alpha-cart@test.com",
1228 sales_channel_id: alphaChannel.id,
1229 },
1230 {
1231 currency_code: "usd",
1232 email: "zulu-cart@test.com",
1233 sales_channel_id: zuluChannel.id,
1234 },
1235 ])
1236
1237 const { data: descendingCarts } = await query.graph({
1238 entity: "cart",
1239 fields: ["id", "email"],
1240 pagination: {
1241 order: {
1242 sales_channel: { name: "DESC" },
1243 },
1244 },
1245 })
1246
1247 expect(descendingCarts.map((cart) => cart.email)).toEqual([
1248 "zulu-cart@test.com",
1249 "alpha-cart@test.com",
1250 ])
1251
1252 const { data: ascendingCarts } = await query.graph({
1253 entity: "cart",
1254 fields: ["id", "email"],
1255 pagination: {
1256 order: {
1257 sales_channel: { name: "ASC" },
1258 },
1259 },
1260 })
1261
1262 expect(ascendingCarts.map((cart) => cart.email)).toEqual([
1263 "alpha-cart@test.com",
1264 "zulu-cart@test.com",
1265 ])
1266 })
1267
1268 it("should paginate and count correctly with cross-module filters", async () => {
1269 const container = getContainer()
1270 const query = container.resolve("query")
1271 const cartService: any = container.resolve(Modules.CART)
1272 const salesChannelService: any = container.resolve(
1273 Modules.SALES_CHANNEL
1274 )
1275
1276 const retailChannel = await salesChannelService.createSalesChannels({
1277 name: "Retail Store",
1278 })
1279 const wholesaleChannel =
1280 await salesChannelService.createSalesChannels({
1281 name: "Wholesale Store",
1282 })
1283
1284 await cartService.createCarts([
1285 ...[1, 2, 3].map((i) => ({
1286 currency_code: "usd",
1287 email: `retail-cart-${i}@test.com`,
1288 sales_channel_id: retailChannel.id,
1289 })),
1290 {
1291 currency_code: "usd",
1292 email: "wholesale-cart@test.com",
1293 sales_channel_id: wholesaleChannel.id,
1294 },
1295 ])
1296
1297 const { data: filteredCarts, metadata } = await query.graph({
1298 entity: "cart",
1299 fields: ["id", "email"],
1300 filters: {
1301 sales_channel: {
1302 name: "Retail Store",
1303 },
1304 },
1305 pagination: {
1306 skip: 0,
1307 take: 2,
1308 },
1309 })
1310
1311 expect(filteredCarts).toHaveLength(2)
1312 expect(metadata?.count).toEqual(3)
1313 expect(
1314 filteredCarts.every((cart) => cart.email.startsWith("retail-cart-"))
1315 ).toBe(true)
1316 })
1317
1318 // Stage 2: filters that cannot be pushed down to SQL (unsupported
1319 // operators, computed fields) are completed in memory after the
1320 // fetch, with pagination applied to the filtered set.
1321 describe("residual (in-memory) filtering", () => {
1322 it("should complete unsupported-operator filters in memory", async () => {
1323 const container = getContainer()
1324 const query = container.resolve("query")
1325
1326 const { data: products } = await query.graph({
1327 entity: "product",
1328 fields: ["id", "title", "translation.key"],
1329 })
1330
1331 const targetProduct = products.find(
1332 (product) => product.title === "Product 2"
1333 )
1334
1335 expect(targetProduct?.translation?.key).toBeDefined()
1336
1337 // $re is not supported by the SQL pushdown, so the filter is
1338 // evaluated in memory against the loaded translations.
1339 const { data: filteredProducts } = await query.graph({
1340 entity: "product",
1341 fields: ["id", "title"],
1342 filters: {
1343 translation: {
1344 key: { $re: `^${targetProduct!.translation!.key}$` },
1345 },
1346 },
1347 })
1348
1349 expect(filteredProducts).toHaveLength(1)
1350 expect(filteredProducts[0]).toEqual(
1351 expect.objectContaining({
1352 id: targetProduct!.id,
1353 title: "Product 2",
1354 })
1355 )
1356 // The translation was loaded only for evaluation and is hidden
1357 // from the payload.
1358 expect(filteredProducts[0].translation).toBeUndefined()
1359 })
1360
1361 it("should combine pushed-down and residual filters", async () => {
1362 const container = getContainer()
1363 const query = container.resolve("query")
1364
1365 const { data: variants } = await query.graph({
1366 entity: "variant",
1367 fields: ["id", "title", "price_set.id", "translation.key"],
1368 })
1369
1370 const targetVariant = variants.find(
1371 (variant) => variant.title === "P1 Variant 1"
1372 )
1373 const otherVariant = variants.find(
1374 (variant) => variant.title === "P2 Variant 1"
1375 )
1376
1377 expect(targetVariant?.price_set?.id).toBeDefined()
1378 expect(targetVariant?.translation?.key).toBeDefined()
1379
1380 // price_set.id is pushed down to SQL while translation.key with
1381 // $re stays residual — both must intersect.
1382 const { data: matching } = await query.graph({
1383 entity: "variant",
1384 fields: ["id", "title"],
1385 filters: {
1386 price_set: { id: targetVariant!.price_set!.id },
1387 translation: {
1388 key: { $re: `^${targetVariant!.translation!.key}$` },
1389 },
1390 },
1391 })
1392
1393 expect(matching).toHaveLength(1)
1394 expect(matching[0].id).toEqual(targetVariant!.id)
1395
1396 // The pushed filter points at another variant: intersection is
1397 // empty even though the residual filter matches.
1398 const { data: disjoint } = await query.graph({
1399 entity: "variant",
1400 fields: ["id"],
1401 filters: {
1402 price_set: { id: otherVariant!.price_set!.id },
1403 translation: {
1404 key: { $re: `^${targetVariant!.translation!.key}$` },
1405 },
1406 },
1407 })
1408
1409 expect(disjoint).toHaveLength(0)
1410 })
1411
1412 it("should filter by a computed field in memory", async () => {
1413 const container = getContainer()
1414 const query = container.resolve("query")
1415
1416 // calculated_price is a computed field, so the filter cannot be
1417 // pushed down and is evaluated in memory against the computed
1418 // values (variant 1 of each product costs 10 usd, variant 2
1419 // costs 20 usd).
1420 const { data: filteredVariants } = await query.graph({
1421 entity: "variant",
1422 fields: ["id", "title"],
1423 filters: {
1424 price_set: {
1425 calculated_price: { calculated_amount: { $gt: 15 } },
1426 },
1427 },
1428 context: {
1429 calculated_price: QueryContext({ currency_code: "usd" }),
1430 },
1431 })
1432
1433 expect(filteredVariants).toHaveLength(3)
1434 expect(
1435 filteredVariants.every((variant) =>
1436 variant.title.endsWith("Variant 2")
1437 )
1438 ).toBe(true)
1439 expect(filteredVariants[0].price_set).toBeUndefined()
1440 })
1441
1442 it("should filter and sort variants by calculated price", async () => {
1443 const container = getContainer()
1444 const query = container.resolve("query")
1445
1446 // The seeded products all price their variants at 10/20 usd; add
1447 // one with distinct prices so the ordering is observable.
1448 await createProductsWorkflow(container).run({
1449 input: {
1450 products: [
1451 {
1452 title: "Product 4",
1453 options: [{ title: "size", values: ["small", "large"] }],
1454 variants: [
1455 {
1456 title: "P4 Variant 1",
1457 options: { size: "small" },
1458 prices: [{ amount: 5, currency_code: "usd" }],
1459 },
1460 {
1461 title: "P4 Variant 2",
1462 options: { size: "large" },
1463 prices: [{ amount: 30, currency_code: "usd" }],
1464 },
1465 ],
1466 },
1467 ],
1468 },
1469 })
1470
1471 // Both the filter and the primary sort key target the computed
1472 // calculated_price, so filtering, sorting, and pagination all
1473 // complete in memory (title breaks ties between equal amounts).
1474 const { data: variants, metadata } = await query.graph({
1475 entity: "variant",
1476 fields: ["id", "title", "calculated_price.calculated_amount"],
1477 filters: {
1478 price_set: {
1479 calculated_price: { calculated_amount: { $gt: 8 } },
1480 },
1481 },
1482 pagination: {
1483 order: {
1484 price_set: {
1485 calculated_price: { calculated_amount: "DESC" },
1486 },
1487 title: "ASC",
1488 },
1489 skip: 0,
1490 take: 4,
1491 },
1492 context: {
1493 calculated_price: QueryContext({ currency_code: "usd" }),
1494 },
1495 })
1496
1497 // 5 usd is filtered out; 30, 20, 20, 20, 10, 10, 10 remain.
1498 expect(metadata?.count).toEqual(7)
1499 expect(variants.map((variant) => variant.title)).toEqual([
1500 "P4 Variant 2",
1501 "P1 Variant 2",
1502 "P2 Variant 2",
1503 "P3 Variant 2",
1504 ])
1505 expect(
1506 variants.map(
1507 (variant) => variant.calculated_price?.calculated_amount
1508 )
1509 ).toEqual([30, 20, 20, 20])
1510 })
1511
1512 it("should paginate after in-memory filtering", async () => {
1513 const container = getContainer()
1514 const query = container.resolve("query")
1515
1516 // Every product's translation key is its id, so the residual
1517 // regex matches all three products before pagination.
1518 const { data: filteredProducts, metadata } = await query.graph({
1519 entity: "product",
1520 fields: ["id", "title"],
1521 filters: {
1522 translation: { key: { $re: "^prod" } },
1523 },
1524 pagination: {
1525 skip: 1,
1526 take: 1,
1527 order: { title: "ASC" },
1528 },
1529 })
1530
1531 expect(metadata?.count).toEqual(3)
1532 expect(filteredProducts).toHaveLength(1)
1533 expect(filteredProducts[0].title).toEqual("Product 2")
1534 })
1535 })
1536 })
1537 })
1538 },
1539 })