order-promotion.e2e-spec.ts 59 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447
  1. /* tslint:disable:no-non-null-assertion */
  2. import { omit } from '@vendure/common/lib/omit';
  3. import { pick } from '@vendure/common/lib/pick';
  4. import {
  5. containsProducts,
  6. customerGroup,
  7. defaultShippingCalculator,
  8. defaultShippingEligibilityChecker,
  9. discountOnItemWithFacets,
  10. hasFacetValues,
  11. manualFulfillmentHandler,
  12. minimumOrderAmount,
  13. orderPercentageDiscount,
  14. productsPercentageDiscount,
  15. } from '@vendure/core';
  16. import {
  17. createErrorResultGuard,
  18. createTestEnvironment,
  19. E2E_DEFAULT_CHANNEL_TOKEN,
  20. ErrorResultGuard,
  21. } from '@vendure/testing';
  22. import gql from 'graphql-tag';
  23. import path from 'path';
  24. import { initialData } from '../../../e2e-common/e2e-initial-data';
  25. import { testConfig, TEST_SETUP_TIMEOUT_MS } from '../../../e2e-common/test-config';
  26. import { freeShipping } from '../src/config/promotion/actions/free-shipping-action';
  27. import { orderFixedDiscount } from '../src/config/promotion/actions/order-fixed-discount-action';
  28. import { testSuccessfulPaymentMethod } from './fixtures/test-payment-methods';
  29. import {
  30. AssignProductsToChannel,
  31. ChannelFragment,
  32. CreateChannel,
  33. CreateCustomerGroup,
  34. CreatePromotion,
  35. CreatePromotionInput,
  36. CreateShippingMethod,
  37. CurrencyCode,
  38. GetFacetList,
  39. GetProductsWithVariantPrices,
  40. HistoryEntryType,
  41. LanguageCode,
  42. PromotionFragment,
  43. RemoveCustomersFromGroup,
  44. } from './graphql/generated-e2e-admin-types';
  45. import {
  46. AddItemToOrder,
  47. AdjustItemQuantity,
  48. AdjustmentType,
  49. ApplyCouponCode,
  50. ErrorCode,
  51. GetActiveOrder,
  52. GetOrderPromotionsByCode,
  53. RemoveCouponCode,
  54. SetCustomerForOrder,
  55. SetShippingMethod,
  56. TestOrderFragmentFragment,
  57. TestOrderWithPaymentsFragment,
  58. UpdatedOrderFragment,
  59. } from './graphql/generated-e2e-shop-types';
  60. import {
  61. ASSIGN_PRODUCT_TO_CHANNEL,
  62. CREATE_CHANNEL,
  63. CREATE_CUSTOMER_GROUP,
  64. CREATE_PROMOTION,
  65. CREATE_SHIPPING_METHOD,
  66. GET_FACET_LIST,
  67. GET_PRODUCTS_WITH_VARIANT_PRICES,
  68. REMOVE_CUSTOMERS_FROM_GROUP,
  69. } from './graphql/shared-definitions';
  70. import {
  71. ADD_ITEM_TO_ORDER,
  72. ADJUST_ITEM_QUANTITY,
  73. APPLY_COUPON_CODE,
  74. GET_ACTIVE_ORDER,
  75. GET_ORDER_PROMOTIONS_BY_CODE,
  76. REMOVE_COUPON_CODE,
  77. SET_CUSTOMER,
  78. SET_SHIPPING_METHOD,
  79. } from './graphql/shop-definitions';
  80. import { addPaymentToOrder, proceedToArrangingPayment } from './utils/test-order-utils';
  81. describe('Promotions applied to Orders', () => {
  82. const { server, adminClient, shopClient } = createTestEnvironment({
  83. ...testConfig,
  84. paymentOptions: {
  85. paymentMethodHandlers: [testSuccessfulPaymentMethod],
  86. },
  87. });
  88. const freeOrderAction = {
  89. code: orderPercentageDiscount.code,
  90. arguments: [{ name: 'discount', value: '100' }],
  91. };
  92. const minOrderAmountCondition = (min: number) => ({
  93. code: minimumOrderAmount.code,
  94. arguments: [
  95. { name: 'amount', value: min.toString() },
  96. { name: 'taxInclusive', value: 'true' },
  97. ],
  98. });
  99. type OrderSuccessResult = UpdatedOrderFragment | TestOrderFragmentFragment;
  100. const orderResultGuard: ErrorResultGuard<OrderSuccessResult> = createErrorResultGuard(
  101. input => !!input.lines,
  102. );
  103. let products: GetProductsWithVariantPrices.Items[];
  104. beforeAll(async () => {
  105. await server.init({
  106. initialData: {
  107. ...initialData,
  108. paymentMethods: [
  109. {
  110. name: testSuccessfulPaymentMethod.code,
  111. handler: { code: testSuccessfulPaymentMethod.code, arguments: [] },
  112. },
  113. ],
  114. },
  115. productsCsvPath: path.join(__dirname, 'fixtures/e2e-products-promotions.csv'),
  116. customerCount: 2,
  117. });
  118. await adminClient.asSuperAdmin();
  119. await getProducts();
  120. await createGlobalPromotions();
  121. }, TEST_SETUP_TIMEOUT_MS);
  122. afterAll(async () => {
  123. await server.destroy();
  124. });
  125. describe('coupon codes', () => {
  126. const TEST_COUPON_CODE = 'TESTCOUPON';
  127. const EXPIRED_COUPON_CODE = 'EXPIRED';
  128. let promoFreeWithCoupon: PromotionFragment;
  129. let promoFreeWithExpiredCoupon: PromotionFragment;
  130. beforeAll(async () => {
  131. promoFreeWithCoupon = await createPromotion({
  132. enabled: true,
  133. name: 'Free with test coupon',
  134. couponCode: TEST_COUPON_CODE,
  135. conditions: [],
  136. actions: [freeOrderAction],
  137. });
  138. promoFreeWithExpiredCoupon = await createPromotion({
  139. enabled: true,
  140. name: 'Expired coupon',
  141. endsAt: new Date(2010, 0, 0),
  142. couponCode: EXPIRED_COUPON_CODE,
  143. conditions: [],
  144. actions: [freeOrderAction],
  145. });
  146. await shopClient.asAnonymousUser();
  147. await shopClient.query<AddItemToOrder.Mutation, AddItemToOrder.Variables>(ADD_ITEM_TO_ORDER, {
  148. productVariantId: getVariantBySlug('item-5000').id,
  149. quantity: 1,
  150. });
  151. });
  152. afterAll(async () => {
  153. await deletePromotion(promoFreeWithCoupon.id);
  154. await deletePromotion(promoFreeWithExpiredCoupon.id);
  155. });
  156. it('applyCouponCode returns error result when code is nonexistant', async () => {
  157. const { applyCouponCode } = await shopClient.query<
  158. ApplyCouponCode.Mutation,
  159. ApplyCouponCode.Variables
  160. >(APPLY_COUPON_CODE, {
  161. couponCode: 'bad code',
  162. });
  163. orderResultGuard.assertErrorResult(applyCouponCode);
  164. expect(applyCouponCode.message).toBe('Coupon code "bad code" is not valid');
  165. expect(applyCouponCode.errorCode).toBe(ErrorCode.COUPON_CODE_INVALID_ERROR);
  166. });
  167. it('applyCouponCode returns error when code is expired', async () => {
  168. const { applyCouponCode } = await shopClient.query<
  169. ApplyCouponCode.Mutation,
  170. ApplyCouponCode.Variables
  171. >(APPLY_COUPON_CODE, {
  172. couponCode: EXPIRED_COUPON_CODE,
  173. });
  174. orderResultGuard.assertErrorResult(applyCouponCode);
  175. expect(applyCouponCode.message).toBe(`Coupon code "${EXPIRED_COUPON_CODE}" has expired`);
  176. expect(applyCouponCode.errorCode).toBe(ErrorCode.COUPON_CODE_EXPIRED_ERROR);
  177. });
  178. it('applies a valid coupon code', async () => {
  179. const { applyCouponCode } = await shopClient.query<
  180. ApplyCouponCode.Mutation,
  181. ApplyCouponCode.Variables
  182. >(APPLY_COUPON_CODE, {
  183. couponCode: TEST_COUPON_CODE,
  184. });
  185. orderResultGuard.assertSuccess(applyCouponCode);
  186. expect(applyCouponCode!.couponCodes).toEqual([TEST_COUPON_CODE]);
  187. expect(applyCouponCode!.discounts.length).toBe(1);
  188. expect(applyCouponCode!.discounts[0].description).toBe('Free with test coupon');
  189. expect(applyCouponCode!.totalWithTax).toBe(0);
  190. });
  191. it('order history records application', async () => {
  192. const { activeOrder } = await shopClient.query<GetActiveOrder.Query>(GET_ACTIVE_ORDER);
  193. expect(activeOrder!.history.items.map(i => omit(i, ['id']))).toEqual([
  194. {
  195. type: HistoryEntryType.ORDER_STATE_TRANSITION,
  196. data: {
  197. from: 'Created',
  198. to: 'AddingItems',
  199. },
  200. },
  201. {
  202. type: HistoryEntryType.ORDER_COUPON_APPLIED,
  203. data: {
  204. couponCode: TEST_COUPON_CODE,
  205. promotionId: 'T_3',
  206. },
  207. },
  208. ]);
  209. });
  210. it('de-duplicates existing codes', async () => {
  211. const { applyCouponCode } = await shopClient.query<
  212. ApplyCouponCode.Mutation,
  213. ApplyCouponCode.Variables
  214. >(APPLY_COUPON_CODE, {
  215. couponCode: TEST_COUPON_CODE,
  216. });
  217. orderResultGuard.assertSuccess(applyCouponCode);
  218. expect(applyCouponCode!.couponCodes).toEqual([TEST_COUPON_CODE]);
  219. });
  220. it('removes a coupon code', async () => {
  221. const { removeCouponCode } = await shopClient.query<
  222. RemoveCouponCode.Mutation,
  223. RemoveCouponCode.Variables
  224. >(REMOVE_COUPON_CODE, {
  225. couponCode: TEST_COUPON_CODE,
  226. });
  227. expect(removeCouponCode!.discounts.length).toBe(0);
  228. expect(removeCouponCode!.totalWithTax).toBe(6000);
  229. });
  230. // https://github.com/vendure-ecommerce/vendure/issues/649
  231. it('discounts array cleared after coupon code removed', async () => {
  232. const { activeOrder } = await shopClient.query<GetActiveOrder.Query>(GET_ACTIVE_ORDER);
  233. expect(activeOrder?.discounts).toEqual([]);
  234. });
  235. it('order history records removal', async () => {
  236. const { activeOrder } = await shopClient.query<GetActiveOrder.Query>(GET_ACTIVE_ORDER);
  237. expect(activeOrder!.history.items.map(i => omit(i, ['id']))).toEqual([
  238. {
  239. type: HistoryEntryType.ORDER_STATE_TRANSITION,
  240. data: {
  241. from: 'Created',
  242. to: 'AddingItems',
  243. },
  244. },
  245. {
  246. type: HistoryEntryType.ORDER_COUPON_APPLIED,
  247. data: {
  248. couponCode: TEST_COUPON_CODE,
  249. promotionId: 'T_3',
  250. },
  251. },
  252. {
  253. type: HistoryEntryType.ORDER_COUPON_REMOVED,
  254. data: {
  255. couponCode: TEST_COUPON_CODE,
  256. },
  257. },
  258. ]);
  259. });
  260. it('does not record removal of coupon code that was not added', async () => {
  261. const { removeCouponCode } = await shopClient.query<
  262. RemoveCouponCode.Mutation,
  263. RemoveCouponCode.Variables
  264. >(REMOVE_COUPON_CODE, {
  265. couponCode: 'NOT_THERE',
  266. });
  267. expect(removeCouponCode!.history.items.map(i => omit(i, ['id']))).toEqual([
  268. {
  269. type: HistoryEntryType.ORDER_STATE_TRANSITION,
  270. data: {
  271. from: 'Created',
  272. to: 'AddingItems',
  273. },
  274. },
  275. {
  276. type: HistoryEntryType.ORDER_COUPON_APPLIED,
  277. data: {
  278. couponCode: TEST_COUPON_CODE,
  279. promotionId: 'T_3',
  280. },
  281. },
  282. {
  283. type: HistoryEntryType.ORDER_COUPON_REMOVED,
  284. data: {
  285. couponCode: TEST_COUPON_CODE,
  286. },
  287. },
  288. ]);
  289. });
  290. });
  291. describe('default PromotionConditions', () => {
  292. beforeEach(async () => {
  293. await shopClient.asAnonymousUser();
  294. });
  295. it('minimumOrderAmount', async () => {
  296. const promotion = await createPromotion({
  297. enabled: true,
  298. name: 'Free if order total greater than 100',
  299. conditions: [minOrderAmountCondition(10000)],
  300. actions: [freeOrderAction],
  301. });
  302. const { addItemToOrder } = await shopClient.query<
  303. AddItemToOrder.Mutation,
  304. AddItemToOrder.Variables
  305. >(ADD_ITEM_TO_ORDER, {
  306. productVariantId: getVariantBySlug('item-5000').id,
  307. quantity: 1,
  308. });
  309. orderResultGuard.assertSuccess(addItemToOrder);
  310. expect(addItemToOrder!.totalWithTax).toBe(6000);
  311. expect(addItemToOrder!.discounts.length).toBe(0);
  312. const { adjustOrderLine } = await shopClient.query<
  313. AdjustItemQuantity.Mutation,
  314. AdjustItemQuantity.Variables
  315. >(ADJUST_ITEM_QUANTITY, {
  316. orderLineId: addItemToOrder!.lines[0].id,
  317. quantity: 2,
  318. });
  319. orderResultGuard.assertSuccess(adjustOrderLine);
  320. expect(adjustOrderLine!.totalWithTax).toBe(0);
  321. expect(adjustOrderLine!.discounts[0].description).toBe('Free if order total greater than 100');
  322. expect(adjustOrderLine!.discounts[0].amount).toBe(-12000);
  323. await deletePromotion(promotion.id);
  324. });
  325. it('atLeastNWithFacets', async () => {
  326. const { facets } = await adminClient.query<GetFacetList.Query>(GET_FACET_LIST);
  327. const saleFacetValue = facets.items[0].values[0];
  328. const promotion = await createPromotion({
  329. enabled: true,
  330. name: 'Free if order contains 2 items with Sale facet value',
  331. conditions: [
  332. {
  333. code: hasFacetValues.code,
  334. arguments: [
  335. { name: 'minimum', value: '2' },
  336. { name: 'facets', value: `["${saleFacetValue.id}"]` },
  337. ],
  338. },
  339. ],
  340. actions: [freeOrderAction],
  341. });
  342. const { addItemToOrder: res1 } = await shopClient.query<
  343. AddItemToOrder.Mutation,
  344. AddItemToOrder.Variables
  345. >(ADD_ITEM_TO_ORDER, {
  346. productVariantId: getVariantBySlug('item-sale-100').id,
  347. quantity: 1,
  348. });
  349. orderResultGuard.assertSuccess(res1);
  350. expect(res1!.totalWithTax).toBe(120);
  351. expect(res1!.discounts.length).toBe(0);
  352. const { addItemToOrder: res2 } = await shopClient.query<
  353. AddItemToOrder.Mutation,
  354. AddItemToOrder.Variables
  355. >(ADD_ITEM_TO_ORDER, {
  356. productVariantId: getVariantBySlug('item-sale-1000').id,
  357. quantity: 1,
  358. });
  359. orderResultGuard.assertSuccess(res2);
  360. expect(res2!.totalWithTax).toBe(0);
  361. expect(res2!.discounts.length).toBe(1);
  362. expect(res2!.totalWithTax).toBe(0);
  363. expect(res2!.discounts[0].description).toBe(
  364. 'Free if order contains 2 items with Sale facet value',
  365. );
  366. expect(res2!.discounts[0].amount).toBe(-1320);
  367. await deletePromotion(promotion.id);
  368. });
  369. it('containsProducts', async () => {
  370. const promotion = await createPromotion({
  371. enabled: true,
  372. name: 'Free if buying 3 or more offer products',
  373. conditions: [
  374. {
  375. code: containsProducts.code,
  376. arguments: [
  377. { name: 'minimum', value: '3' },
  378. {
  379. name: 'productVariantIds',
  380. value: JSON.stringify([
  381. getVariantBySlug('item-5000').id,
  382. getVariantBySlug('item-1000').id,
  383. ]),
  384. },
  385. ],
  386. },
  387. ],
  388. actions: [freeOrderAction],
  389. });
  390. await shopClient.query<AddItemToOrder.Mutation, AddItemToOrder.Variables>(ADD_ITEM_TO_ORDER, {
  391. productVariantId: getVariantBySlug('item-5000').id,
  392. quantity: 1,
  393. });
  394. const { addItemToOrder } = await shopClient.query<
  395. AddItemToOrder.Mutation,
  396. AddItemToOrder.Variables
  397. >(ADD_ITEM_TO_ORDER, {
  398. productVariantId: getVariantBySlug('item-1000').id,
  399. quantity: 1,
  400. });
  401. orderResultGuard.assertSuccess(addItemToOrder);
  402. expect(addItemToOrder!.totalWithTax).toBe(7200);
  403. expect(addItemToOrder!.discounts.length).toBe(0);
  404. const { adjustOrderLine } = await shopClient.query<
  405. AdjustItemQuantity.Mutation,
  406. AdjustItemQuantity.Variables
  407. >(ADJUST_ITEM_QUANTITY, {
  408. orderLineId: addItemToOrder!.lines[0].id,
  409. quantity: 2,
  410. });
  411. orderResultGuard.assertSuccess(adjustOrderLine);
  412. expect(adjustOrderLine!.total).toBe(0);
  413. expect(adjustOrderLine!.discounts[0].description).toBe('Free if buying 3 or more offer products');
  414. expect(adjustOrderLine!.discounts[0].amount).toBe(-13200);
  415. await deletePromotion(promotion.id);
  416. });
  417. it('customerGroup', async () => {
  418. const { createCustomerGroup } = await adminClient.query<
  419. CreateCustomerGroup.Mutation,
  420. CreateCustomerGroup.Variables
  421. >(CREATE_CUSTOMER_GROUP, {
  422. input: { name: 'Test Group', customerIds: ['T_1'] },
  423. });
  424. await shopClient.asUserWithCredentials('hayden.zieme12@hotmail.com', 'test');
  425. const promotion = await createPromotion({
  426. enabled: true,
  427. name: 'Free for group members',
  428. conditions: [
  429. {
  430. code: customerGroup.code,
  431. arguments: [{ name: 'customerGroupId', value: createCustomerGroup.id }],
  432. },
  433. ],
  434. actions: [freeOrderAction],
  435. });
  436. const { addItemToOrder } = await shopClient.query<
  437. AddItemToOrder.Mutation,
  438. AddItemToOrder.Variables
  439. >(ADD_ITEM_TO_ORDER, {
  440. productVariantId: getVariantBySlug('item-5000').id,
  441. quantity: 1,
  442. });
  443. orderResultGuard.assertSuccess(addItemToOrder);
  444. expect(addItemToOrder!.totalWithTax).toBe(0);
  445. expect(addItemToOrder!.discounts.length).toBe(1);
  446. expect(addItemToOrder!.discounts[0].description).toBe('Free for group members');
  447. expect(addItemToOrder!.discounts[0].amount).toBe(-6000);
  448. await adminClient.query<RemoveCustomersFromGroup.Mutation, RemoveCustomersFromGroup.Variables>(
  449. REMOVE_CUSTOMERS_FROM_GROUP,
  450. {
  451. groupId: createCustomerGroup.id,
  452. customerIds: ['T_1'],
  453. },
  454. );
  455. const { adjustOrderLine } = await shopClient.query<
  456. AdjustItemQuantity.Mutation,
  457. AdjustItemQuantity.Variables
  458. >(ADJUST_ITEM_QUANTITY, {
  459. orderLineId: addItemToOrder!.lines[0].id,
  460. quantity: 2,
  461. });
  462. orderResultGuard.assertSuccess(adjustOrderLine);
  463. expect(adjustOrderLine!.totalWithTax).toBe(12000);
  464. expect(adjustOrderLine!.discounts.length).toBe(0);
  465. await deletePromotion(promotion.id);
  466. });
  467. });
  468. describe('default PromotionActions', () => {
  469. const TAX_INCLUDED_CHANNEL_TOKEN = 'tax_included_channel';
  470. beforeAll(async () => {
  471. // Create a channel where the prices include tax, so we can ensure
  472. // that PromotionActions are working as expected when taxes are included
  473. const { createChannel } = await adminClient.query<
  474. CreateChannel.Mutation,
  475. CreateChannel.Variables
  476. >(CREATE_CHANNEL, {
  477. input: {
  478. code: 'tax-included-channel',
  479. currencyCode: CurrencyCode.GBP,
  480. pricesIncludeTax: true,
  481. defaultTaxZoneId: 'T_1',
  482. defaultShippingZoneId: 'T_1',
  483. defaultLanguageCode: LanguageCode.en,
  484. token: TAX_INCLUDED_CHANNEL_TOKEN,
  485. },
  486. });
  487. const taxIncludedChannel = createChannel as ChannelFragment;
  488. await adminClient.query<AssignProductsToChannel.Mutation, AssignProductsToChannel.Variables>(
  489. ASSIGN_PRODUCT_TO_CHANNEL,
  490. {
  491. input: {
  492. channelId: taxIncludedChannel.id,
  493. priceFactor: 1,
  494. productIds: products.map(p => p.id),
  495. },
  496. },
  497. );
  498. });
  499. beforeEach(async () => {
  500. await shopClient.asAnonymousUser();
  501. });
  502. describe('orderPercentageDiscount', () => {
  503. const couponCode = '50%_off_order';
  504. let promotion: PromotionFragment;
  505. beforeAll(async () => {
  506. promotion = await createPromotion({
  507. enabled: true,
  508. name: '20% discount on order',
  509. couponCode,
  510. conditions: [],
  511. actions: [
  512. {
  513. code: orderPercentageDiscount.code,
  514. arguments: [{ name: 'discount', value: '20' }],
  515. },
  516. ],
  517. });
  518. });
  519. afterAll(async () => {
  520. await deletePromotion(promotion.id);
  521. });
  522. it('prices exclude tax', async () => {
  523. shopClient.setChannelToken(E2E_DEFAULT_CHANNEL_TOKEN);
  524. const { addItemToOrder } = await shopClient.query<
  525. AddItemToOrder.Mutation,
  526. AddItemToOrder.Variables
  527. >(ADD_ITEM_TO_ORDER, {
  528. productVariantId: getVariantBySlug('item-5000').id,
  529. quantity: 1,
  530. });
  531. orderResultGuard.assertSuccess(addItemToOrder);
  532. expect(addItemToOrder!.totalWithTax).toBe(6000);
  533. expect(addItemToOrder!.discounts.length).toBe(0);
  534. const { applyCouponCode } = await shopClient.query<
  535. ApplyCouponCode.Mutation,
  536. ApplyCouponCode.Variables
  537. >(APPLY_COUPON_CODE, {
  538. couponCode,
  539. });
  540. orderResultGuard.assertSuccess(applyCouponCode);
  541. expect(applyCouponCode!.discounts.length).toBe(1);
  542. expect(applyCouponCode!.discounts[0].description).toBe('20% discount on order');
  543. expect(applyCouponCode!.totalWithTax).toBe(4800);
  544. });
  545. it('prices include tax', async () => {
  546. shopClient.setChannelToken(TAX_INCLUDED_CHANNEL_TOKEN);
  547. const { addItemToOrder } = await shopClient.query<
  548. AddItemToOrder.Mutation,
  549. AddItemToOrder.Variables
  550. >(ADD_ITEM_TO_ORDER, {
  551. productVariantId: getVariantBySlug('item-5000').id,
  552. quantity: 1,
  553. });
  554. orderResultGuard.assertSuccess(addItemToOrder);
  555. expect(addItemToOrder!.totalWithTax).toBe(5000);
  556. expect(addItemToOrder!.discounts.length).toBe(0);
  557. const { applyCouponCode } = await shopClient.query<
  558. ApplyCouponCode.Mutation,
  559. ApplyCouponCode.Variables
  560. >(APPLY_COUPON_CODE, {
  561. couponCode,
  562. });
  563. orderResultGuard.assertSuccess(applyCouponCode);
  564. expect(applyCouponCode!.discounts.length).toBe(1);
  565. expect(applyCouponCode!.discounts[0].description).toBe('20% discount on order');
  566. expect(applyCouponCode!.totalWithTax).toBe(4000);
  567. });
  568. });
  569. describe('orderFixedDiscount', () => {
  570. const couponCode = '10_off_order';
  571. let promotion: PromotionFragment;
  572. beforeAll(async () => {
  573. promotion = await createPromotion({
  574. enabled: true,
  575. name: '$10 discount on order',
  576. couponCode,
  577. conditions: [],
  578. actions: [
  579. {
  580. code: orderFixedDiscount.code,
  581. arguments: [{ name: 'discount', value: '1000' }],
  582. },
  583. ],
  584. });
  585. });
  586. afterAll(async () => {
  587. await deletePromotion(promotion.id);
  588. shopClient.setChannelToken(E2E_DEFAULT_CHANNEL_TOKEN);
  589. });
  590. it('prices exclude tax', async () => {
  591. shopClient.setChannelToken(E2E_DEFAULT_CHANNEL_TOKEN);
  592. const { addItemToOrder } = await shopClient.query<
  593. AddItemToOrder.Mutation,
  594. AddItemToOrder.Variables
  595. >(ADD_ITEM_TO_ORDER, {
  596. productVariantId: getVariantBySlug('item-5000').id,
  597. quantity: 1,
  598. });
  599. orderResultGuard.assertSuccess(addItemToOrder);
  600. expect(addItemToOrder!.total).toBe(5000);
  601. expect(addItemToOrder!.totalWithTax).toBe(6000);
  602. expect(addItemToOrder!.discounts.length).toBe(0);
  603. const { applyCouponCode } = await shopClient.query<
  604. ApplyCouponCode.Mutation,
  605. ApplyCouponCode.Variables
  606. >(APPLY_COUPON_CODE, {
  607. couponCode,
  608. });
  609. orderResultGuard.assertSuccess(applyCouponCode);
  610. expect(applyCouponCode!.discounts.length).toBe(1);
  611. expect(applyCouponCode!.discounts[0].description).toBe('$10 discount on order');
  612. expect(applyCouponCode!.total).toBe(4000);
  613. expect(applyCouponCode!.totalWithTax).toBe(4800);
  614. });
  615. it('prices include tax', async () => {
  616. shopClient.setChannelToken(TAX_INCLUDED_CHANNEL_TOKEN);
  617. const { addItemToOrder } = await shopClient.query<
  618. AddItemToOrder.Mutation,
  619. AddItemToOrder.Variables
  620. >(ADD_ITEM_TO_ORDER, {
  621. productVariantId: getVariantBySlug('item-5000').id,
  622. quantity: 1,
  623. });
  624. orderResultGuard.assertSuccess(addItemToOrder);
  625. expect(addItemToOrder!.totalWithTax).toBe(5000);
  626. expect(addItemToOrder!.discounts.length).toBe(0);
  627. const { applyCouponCode } = await shopClient.query<
  628. ApplyCouponCode.Mutation,
  629. ApplyCouponCode.Variables
  630. >(APPLY_COUPON_CODE, {
  631. couponCode,
  632. });
  633. orderResultGuard.assertSuccess(applyCouponCode);
  634. expect(applyCouponCode!.discounts.length).toBe(1);
  635. expect(applyCouponCode!.discounts[0].description).toBe('$10 discount on order');
  636. expect(applyCouponCode!.totalWithTax).toBe(4000);
  637. });
  638. });
  639. describe('discountOnItemWithFacets', () => {
  640. const couponCode = '50%_off_sale_items';
  641. let promotion: PromotionFragment;
  642. function getItemSale1Line<
  643. T extends Array<
  644. UpdatedOrderFragment['lines'][number] | TestOrderFragmentFragment['lines'][number]
  645. >
  646. >(lines: T): T[number] {
  647. return lines.find(l => l.productVariant.id === getVariantBySlug('item-sale-100').id)!;
  648. }
  649. beforeAll(async () => {
  650. const { facets } = await adminClient.query<GetFacetList.Query>(GET_FACET_LIST);
  651. const saleFacetValue = facets.items[0].values[0];
  652. promotion = await createPromotion({
  653. enabled: true,
  654. name: '50% off sale items',
  655. couponCode,
  656. conditions: [],
  657. actions: [
  658. {
  659. code: discountOnItemWithFacets.code,
  660. arguments: [
  661. { name: 'discount', value: '50' },
  662. { name: 'facets', value: `["${saleFacetValue.id}"]` },
  663. ],
  664. },
  665. ],
  666. });
  667. });
  668. afterAll(async () => {
  669. await deletePromotion(promotion.id);
  670. shopClient.setChannelToken(E2E_DEFAULT_CHANNEL_TOKEN);
  671. });
  672. it('prices exclude tax', async () => {
  673. await shopClient.query<AddItemToOrder.Mutation, AddItemToOrder.Variables>(ADD_ITEM_TO_ORDER, {
  674. productVariantId: getVariantBySlug('item-1000').id,
  675. quantity: 1,
  676. });
  677. await shopClient.query<AddItemToOrder.Mutation, AddItemToOrder.Variables>(ADD_ITEM_TO_ORDER, {
  678. productVariantId: getVariantBySlug('item-sale-1000').id,
  679. quantity: 1,
  680. });
  681. const { addItemToOrder } = await shopClient.query<
  682. AddItemToOrder.Mutation,
  683. AddItemToOrder.Variables
  684. >(ADD_ITEM_TO_ORDER, {
  685. productVariantId: getVariantBySlug('item-sale-100').id,
  686. quantity: 2,
  687. });
  688. orderResultGuard.assertSuccess(addItemToOrder);
  689. expect(addItemToOrder!.discounts.length).toBe(0);
  690. expect(getItemSale1Line(addItemToOrder!.lines).discounts.length).toBe(0);
  691. expect(addItemToOrder!.total).toBe(2200);
  692. expect(addItemToOrder!.totalWithTax).toBe(2640);
  693. const { applyCouponCode } = await shopClient.query<
  694. ApplyCouponCode.Mutation,
  695. ApplyCouponCode.Variables
  696. >(APPLY_COUPON_CODE, {
  697. couponCode,
  698. });
  699. orderResultGuard.assertSuccess(applyCouponCode);
  700. expect(applyCouponCode!.total).toBe(1600);
  701. expect(applyCouponCode!.totalWithTax).toBe(1920);
  702. expect(getItemSale1Line(applyCouponCode!.lines).discounts.length).toBe(1); // 1x promotion
  703. const { removeCouponCode } = await shopClient.query<
  704. RemoveCouponCode.Mutation,
  705. RemoveCouponCode.Variables
  706. >(REMOVE_COUPON_CODE, {
  707. couponCode,
  708. });
  709. expect(getItemSale1Line(removeCouponCode!.lines).discounts.length).toBe(0);
  710. expect(removeCouponCode!.total).toBe(2200);
  711. expect(removeCouponCode!.totalWithTax).toBe(2640);
  712. const { activeOrder } = await shopClient.query<GetActiveOrder.Query>(GET_ACTIVE_ORDER);
  713. expect(getItemSale1Line(activeOrder!.lines).discounts.length).toBe(0);
  714. expect(activeOrder!.total).toBe(2200);
  715. expect(activeOrder!.totalWithTax).toBe(2640);
  716. });
  717. it('prices include tax', async () => {
  718. shopClient.setChannelToken(TAX_INCLUDED_CHANNEL_TOKEN);
  719. await shopClient.query<AddItemToOrder.Mutation, AddItemToOrder.Variables>(ADD_ITEM_TO_ORDER, {
  720. productVariantId: getVariantBySlug('item-1000').id,
  721. quantity: 1,
  722. });
  723. await shopClient.query<AddItemToOrder.Mutation, AddItemToOrder.Variables>(ADD_ITEM_TO_ORDER, {
  724. productVariantId: getVariantBySlug('item-sale-1000').id,
  725. quantity: 1,
  726. });
  727. const { addItemToOrder } = await shopClient.query<
  728. AddItemToOrder.Mutation,
  729. AddItemToOrder.Variables
  730. >(ADD_ITEM_TO_ORDER, {
  731. productVariantId: getVariantBySlug('item-sale-100').id,
  732. quantity: 2,
  733. });
  734. orderResultGuard.assertSuccess(addItemToOrder);
  735. expect(addItemToOrder!.discounts.length).toBe(0);
  736. expect(getItemSale1Line(addItemToOrder!.lines).discounts.length).toBe(0);
  737. expect(addItemToOrder!.total).toBe(1832);
  738. expect(addItemToOrder!.totalWithTax).toBe(2200);
  739. const { applyCouponCode } = await shopClient.query<
  740. ApplyCouponCode.Mutation,
  741. ApplyCouponCode.Variables
  742. >(APPLY_COUPON_CODE, {
  743. couponCode,
  744. });
  745. orderResultGuard.assertSuccess(applyCouponCode);
  746. expect(applyCouponCode!.total).toBe(1334);
  747. expect(applyCouponCode!.totalWithTax).toBe(1600);
  748. expect(getItemSale1Line(applyCouponCode!.lines).discounts.length).toBe(1); // 1x promotion
  749. const { removeCouponCode } = await shopClient.query<
  750. RemoveCouponCode.Mutation,
  751. RemoveCouponCode.Variables
  752. >(REMOVE_COUPON_CODE, {
  753. couponCode,
  754. });
  755. expect(getItemSale1Line(removeCouponCode!.lines).discounts.length).toBe(0);
  756. expect(removeCouponCode!.total).toBe(1832);
  757. expect(removeCouponCode!.totalWithTax).toBe(2200);
  758. const { activeOrder } = await shopClient.query<GetActiveOrder.Query>(GET_ACTIVE_ORDER);
  759. expect(getItemSale1Line(activeOrder!.lines).discounts.length).toBe(0);
  760. expect(activeOrder!.total).toBe(1832);
  761. expect(activeOrder!.totalWithTax).toBe(2200);
  762. });
  763. });
  764. describe('productsPercentageDiscount', () => {
  765. const couponCode = '50%_off_product';
  766. let promotion: PromotionFragment;
  767. beforeAll(async () => {
  768. promotion = await createPromotion({
  769. enabled: true,
  770. name: '50% off product',
  771. couponCode,
  772. conditions: [],
  773. actions: [
  774. {
  775. code: productsPercentageDiscount.code,
  776. arguments: [
  777. { name: 'discount', value: '50' },
  778. {
  779. name: 'productVariantIds',
  780. value: `["${getVariantBySlug('item-5000').id}"]`,
  781. },
  782. ],
  783. },
  784. ],
  785. });
  786. });
  787. afterAll(async () => {
  788. await deletePromotion(promotion.id);
  789. shopClient.setChannelToken(E2E_DEFAULT_CHANNEL_TOKEN);
  790. });
  791. it('prices exclude tax', async () => {
  792. const { addItemToOrder } = await shopClient.query<
  793. AddItemToOrder.Mutation,
  794. AddItemToOrder.Variables
  795. >(ADD_ITEM_TO_ORDER, {
  796. productVariantId: getVariantBySlug('item-5000').id,
  797. quantity: 1,
  798. });
  799. orderResultGuard.assertSuccess(addItemToOrder);
  800. expect(addItemToOrder!.discounts.length).toBe(0);
  801. expect(addItemToOrder!.lines[0].discounts.length).toBe(0);
  802. expect(addItemToOrder!.total).toBe(5000);
  803. expect(addItemToOrder!.totalWithTax).toBe(6000);
  804. const { applyCouponCode } = await shopClient.query<
  805. ApplyCouponCode.Mutation,
  806. ApplyCouponCode.Variables
  807. >(APPLY_COUPON_CODE, {
  808. couponCode,
  809. });
  810. orderResultGuard.assertSuccess(applyCouponCode);
  811. expect(applyCouponCode!.total).toBe(2500);
  812. expect(applyCouponCode!.totalWithTax).toBe(3000);
  813. expect(applyCouponCode!.lines[0].discounts.length).toBe(1); // 1x promotion
  814. });
  815. it('prices include tax', async () => {
  816. shopClient.setChannelToken(TAX_INCLUDED_CHANNEL_TOKEN);
  817. const { addItemToOrder } = await shopClient.query<
  818. AddItemToOrder.Mutation,
  819. AddItemToOrder.Variables
  820. >(ADD_ITEM_TO_ORDER, {
  821. productVariantId: getVariantBySlug('item-5000').id,
  822. quantity: 1,
  823. });
  824. orderResultGuard.assertSuccess(addItemToOrder);
  825. expect(addItemToOrder!.discounts.length).toBe(0);
  826. expect(addItemToOrder!.lines[0].discounts.length).toBe(0);
  827. expect(addItemToOrder!.total).toBe(4167);
  828. expect(addItemToOrder!.totalWithTax).toBe(5000);
  829. const { applyCouponCode } = await shopClient.query<
  830. ApplyCouponCode.Mutation,
  831. ApplyCouponCode.Variables
  832. >(APPLY_COUPON_CODE, {
  833. couponCode,
  834. });
  835. orderResultGuard.assertSuccess(applyCouponCode);
  836. expect(applyCouponCode!.total).toBe(2083);
  837. expect(applyCouponCode!.totalWithTax).toBe(2500);
  838. expect(applyCouponCode!.lines[0].discounts.length).toBe(1); // 1x promotion
  839. });
  840. });
  841. describe('freeShipping', () => {
  842. const couponCode = 'FREE_SHIPPING';
  843. let promotion: PromotionFragment;
  844. // The test shipping method needs to be created in each Channel, since ShippingMethods
  845. // are ChannelAware
  846. async function createTestShippingMethod(channelToken: string) {
  847. adminClient.setChannelToken(channelToken);
  848. const result = await adminClient.query<
  849. CreateShippingMethod.Mutation,
  850. CreateShippingMethod.Variables
  851. >(CREATE_SHIPPING_METHOD, {
  852. input: {
  853. code: 'test-method',
  854. fulfillmentHandler: manualFulfillmentHandler.code,
  855. checker: {
  856. code: defaultShippingEligibilityChecker.code,
  857. arguments: [
  858. {
  859. name: 'orderMinimum',
  860. value: '0',
  861. },
  862. ],
  863. },
  864. calculator: {
  865. code: defaultShippingCalculator.code,
  866. arguments: [
  867. { name: 'rate', value: '345' },
  868. { name: 'includesTax', value: 'auto' },
  869. { name: 'taxRate', value: '20' },
  870. ],
  871. },
  872. translations: [
  873. { languageCode: LanguageCode.en, name: 'test method', description: '' },
  874. ],
  875. },
  876. });
  877. adminClient.setChannelToken(E2E_DEFAULT_CHANNEL_TOKEN);
  878. return result.createShippingMethod;
  879. }
  880. beforeAll(async () => {
  881. promotion = await createPromotion({
  882. enabled: true,
  883. name: 'Free shipping',
  884. couponCode,
  885. conditions: [],
  886. actions: [
  887. {
  888. code: freeShipping.code,
  889. arguments: [],
  890. },
  891. ],
  892. });
  893. });
  894. afterAll(async () => {
  895. await deletePromotion(promotion.id);
  896. shopClient.setChannelToken(E2E_DEFAULT_CHANNEL_TOKEN);
  897. });
  898. it('prices exclude tax', async () => {
  899. const { addItemToOrder } = await shopClient.query<
  900. AddItemToOrder.Mutation,
  901. AddItemToOrder.Variables
  902. >(ADD_ITEM_TO_ORDER, {
  903. productVariantId: getVariantBySlug('item-5000').id,
  904. quantity: 1,
  905. });
  906. const method = await createTestShippingMethod(E2E_DEFAULT_CHANNEL_TOKEN);
  907. const { setOrderShippingMethod } = await shopClient.query<
  908. SetShippingMethod.Mutation,
  909. SetShippingMethod.Variables
  910. >(SET_SHIPPING_METHOD, {
  911. id: method.id,
  912. });
  913. orderResultGuard.assertSuccess(setOrderShippingMethod);
  914. expect(setOrderShippingMethod.discounts).toEqual([]);
  915. expect(setOrderShippingMethod.shipping).toBe(345);
  916. expect(setOrderShippingMethod.shippingWithTax).toBe(414);
  917. expect(setOrderShippingMethod.total).toBe(5345);
  918. expect(setOrderShippingMethod.totalWithTax).toBe(6414);
  919. const { applyCouponCode } = await shopClient.query<
  920. ApplyCouponCode.Mutation,
  921. ApplyCouponCode.Variables
  922. >(APPLY_COUPON_CODE, {
  923. couponCode,
  924. });
  925. orderResultGuard.assertSuccess(applyCouponCode);
  926. expect(applyCouponCode.discounts.length).toBe(1);
  927. expect(applyCouponCode.discounts[0].description).toBe('Free shipping');
  928. expect(applyCouponCode.shipping).toBe(0);
  929. expect(applyCouponCode.shippingWithTax).toBe(0);
  930. expect(applyCouponCode.total).toBe(5000);
  931. expect(applyCouponCode.totalWithTax).toBe(6000);
  932. });
  933. it('prices include tax', async () => {
  934. shopClient.setChannelToken(TAX_INCLUDED_CHANNEL_TOKEN);
  935. const { addItemToOrder } = await shopClient.query<
  936. AddItemToOrder.Mutation,
  937. AddItemToOrder.Variables
  938. >(ADD_ITEM_TO_ORDER, {
  939. productVariantId: getVariantBySlug('item-5000').id,
  940. quantity: 1,
  941. });
  942. const method = await createTestShippingMethod(TAX_INCLUDED_CHANNEL_TOKEN);
  943. const { setOrderShippingMethod } = await shopClient.query<
  944. SetShippingMethod.Mutation,
  945. SetShippingMethod.Variables
  946. >(SET_SHIPPING_METHOD, {
  947. id: method.id,
  948. });
  949. orderResultGuard.assertSuccess(setOrderShippingMethod);
  950. expect(setOrderShippingMethod.discounts).toEqual([]);
  951. expect(setOrderShippingMethod.shipping).toBe(287);
  952. expect(setOrderShippingMethod.shippingWithTax).toBe(345);
  953. expect(setOrderShippingMethod.total).toBe(4454);
  954. expect(setOrderShippingMethod.totalWithTax).toBe(5345);
  955. const { applyCouponCode } = await shopClient.query<
  956. ApplyCouponCode.Mutation,
  957. ApplyCouponCode.Variables
  958. >(APPLY_COUPON_CODE, {
  959. couponCode,
  960. });
  961. orderResultGuard.assertSuccess(applyCouponCode);
  962. expect(applyCouponCode.discounts.length).toBe(1);
  963. expect(applyCouponCode.discounts[0].description).toBe('Free shipping');
  964. expect(applyCouponCode.shipping).toBe(0);
  965. expect(applyCouponCode.shippingWithTax).toBe(0);
  966. expect(applyCouponCode.total).toBe(4167);
  967. expect(applyCouponCode.totalWithTax).toBe(5000);
  968. });
  969. });
  970. describe('multiple promotions simultaneously', () => {
  971. const saleItem50pcOffCoupon = 'CODE1';
  972. const order15pcOffCoupon = 'CODE2';
  973. let promotion1: PromotionFragment;
  974. let promotion2: PromotionFragment;
  975. beforeAll(async () => {
  976. const { facets } = await adminClient.query<GetFacetList.Query>(GET_FACET_LIST);
  977. const saleFacetValue = facets.items[0].values[0];
  978. promotion1 = await createPromotion({
  979. enabled: true,
  980. name: 'item promo',
  981. couponCode: saleItem50pcOffCoupon,
  982. conditions: [],
  983. actions: [
  984. {
  985. code: discountOnItemWithFacets.code,
  986. arguments: [
  987. { name: 'discount', value: '50' },
  988. { name: 'facets', value: `["${saleFacetValue.id}"]` },
  989. ],
  990. },
  991. ],
  992. });
  993. promotion2 = await createPromotion({
  994. enabled: true,
  995. name: 'order promo',
  996. couponCode: order15pcOffCoupon,
  997. conditions: [],
  998. actions: [
  999. {
  1000. code: orderPercentageDiscount.code,
  1001. arguments: [{ name: 'discount', value: '15' }],
  1002. },
  1003. ],
  1004. });
  1005. });
  1006. afterAll(async () => {
  1007. await deletePromotion(promotion1.id);
  1008. await deletePromotion(promotion2.id);
  1009. shopClient.setChannelToken(E2E_DEFAULT_CHANNEL_TOKEN);
  1010. });
  1011. it('prices exclude tax', async () => {
  1012. await shopClient.query<AddItemToOrder.Mutation, AddItemToOrder.Variables>(ADD_ITEM_TO_ORDER, {
  1013. productVariantId: getVariantBySlug('item-sale-1000').id,
  1014. quantity: 2,
  1015. });
  1016. await shopClient.query<AddItemToOrder.Mutation, AddItemToOrder.Variables>(ADD_ITEM_TO_ORDER, {
  1017. productVariantId: getVariantBySlug('item-5000').id,
  1018. quantity: 1,
  1019. });
  1020. // Apply the OrderItem-level promo
  1021. const { applyCouponCode: apply1 } = await shopClient.query<
  1022. ApplyCouponCode.Mutation,
  1023. ApplyCouponCode.Variables
  1024. >(APPLY_COUPON_CODE, {
  1025. couponCode: saleItem50pcOffCoupon,
  1026. });
  1027. orderResultGuard.assertSuccess(apply1);
  1028. const saleItemLine = apply1.lines.find(
  1029. l => l.productVariant.id === getVariantBySlug('item-sale-1000').id,
  1030. )!;
  1031. expect(saleItemLine.discounts.length).toBe(1); // 1x promotion
  1032. expect(
  1033. saleItemLine.discounts.find(a => a.type === AdjustmentType.PROMOTION)?.description,
  1034. ).toBe('item promo');
  1035. expect(apply1.discounts.length).toBe(1);
  1036. expect(apply1.total).toBe(6000);
  1037. expect(apply1.totalWithTax).toBe(7200);
  1038. // Apply the Order-level promo
  1039. const { applyCouponCode: apply2 } = await shopClient.query<
  1040. ApplyCouponCode.Mutation,
  1041. ApplyCouponCode.Variables
  1042. >(APPLY_COUPON_CODE, {
  1043. couponCode: order15pcOffCoupon,
  1044. });
  1045. orderResultGuard.assertSuccess(apply2);
  1046. expect(apply2.discounts.map(d => d.description).sort()).toEqual([
  1047. 'item promo',
  1048. 'order promo',
  1049. ]);
  1050. expect(apply2.total).toBe(5100);
  1051. expect(apply2.totalWithTax).toBe(6120);
  1052. });
  1053. it('prices include tax', async () => {
  1054. shopClient.setChannelToken(TAX_INCLUDED_CHANNEL_TOKEN);
  1055. await shopClient.query<AddItemToOrder.Mutation, AddItemToOrder.Variables>(ADD_ITEM_TO_ORDER, {
  1056. productVariantId: getVariantBySlug('item-sale-1000').id,
  1057. quantity: 2,
  1058. });
  1059. await shopClient.query<AddItemToOrder.Mutation, AddItemToOrder.Variables>(ADD_ITEM_TO_ORDER, {
  1060. productVariantId: getVariantBySlug('item-5000').id,
  1061. quantity: 1,
  1062. });
  1063. // Apply the OrderItem-level promo
  1064. const { applyCouponCode: apply1 } = await shopClient.query<
  1065. ApplyCouponCode.Mutation,
  1066. ApplyCouponCode.Variables
  1067. >(APPLY_COUPON_CODE, {
  1068. couponCode: saleItem50pcOffCoupon,
  1069. });
  1070. orderResultGuard.assertSuccess(apply1);
  1071. const saleItemLine = apply1.lines.find(
  1072. l => l.productVariant.id === getVariantBySlug('item-sale-1000').id,
  1073. )!;
  1074. expect(saleItemLine.discounts.length).toBe(1); // 1x promotion
  1075. expect(
  1076. saleItemLine.discounts.find(a => a.type === AdjustmentType.PROMOTION)?.description,
  1077. ).toBe('item promo');
  1078. expect(apply1.discounts.length).toBe(1);
  1079. expect(apply1.total).toBe(5001);
  1080. expect(apply1.totalWithTax).toBe(6000);
  1081. // Apply the Order-level promo
  1082. const { applyCouponCode: apply2 } = await shopClient.query<
  1083. ApplyCouponCode.Mutation,
  1084. ApplyCouponCode.Variables
  1085. >(APPLY_COUPON_CODE, {
  1086. couponCode: order15pcOffCoupon,
  1087. });
  1088. orderResultGuard.assertSuccess(apply2);
  1089. expect(apply2.discounts.map(d => d.description).sort()).toEqual([
  1090. 'item promo',
  1091. 'order promo',
  1092. ]);
  1093. expect(apply2.total).toBe(4250);
  1094. expect(apply2.totalWithTax).toBe(5100);
  1095. });
  1096. });
  1097. });
  1098. describe('per-customer usage limit', () => {
  1099. const TEST_COUPON_CODE = 'TESTCOUPON';
  1100. const orderGuard: ErrorResultGuard<TestOrderWithPaymentsFragment> = createErrorResultGuard(
  1101. input => !!input.lines,
  1102. );
  1103. let promoWithUsageLimit: PromotionFragment;
  1104. beforeAll(async () => {
  1105. promoWithUsageLimit = await createPromotion({
  1106. enabled: true,
  1107. name: 'Free with test coupon',
  1108. couponCode: TEST_COUPON_CODE,
  1109. perCustomerUsageLimit: 1,
  1110. conditions: [],
  1111. actions: [freeOrderAction],
  1112. });
  1113. });
  1114. afterAll(async () => {
  1115. await deletePromotion(promoWithUsageLimit.id);
  1116. });
  1117. async function createNewActiveOrder() {
  1118. const { addItemToOrder } = await shopClient.query<
  1119. AddItemToOrder.Mutation,
  1120. AddItemToOrder.Variables
  1121. >(ADD_ITEM_TO_ORDER, {
  1122. productVariantId: getVariantBySlug('item-5000').id,
  1123. quantity: 1,
  1124. });
  1125. return addItemToOrder;
  1126. }
  1127. describe('guest customer', () => {
  1128. const GUEST_EMAIL_ADDRESS = 'guest@test.com';
  1129. let orderCode: string;
  1130. function addGuestCustomerToOrder() {
  1131. return shopClient.query<SetCustomerForOrder.Mutation, SetCustomerForOrder.Variables>(
  1132. SET_CUSTOMER,
  1133. {
  1134. input: {
  1135. emailAddress: GUEST_EMAIL_ADDRESS,
  1136. firstName: 'Guest',
  1137. lastName: 'Customer',
  1138. },
  1139. },
  1140. );
  1141. }
  1142. it('allows initial usage', async () => {
  1143. await shopClient.asAnonymousUser();
  1144. await createNewActiveOrder();
  1145. await addGuestCustomerToOrder();
  1146. const { applyCouponCode } = await shopClient.query<
  1147. ApplyCouponCode.Mutation,
  1148. ApplyCouponCode.Variables
  1149. >(APPLY_COUPON_CODE, { couponCode: TEST_COUPON_CODE });
  1150. orderResultGuard.assertSuccess(applyCouponCode);
  1151. expect(applyCouponCode!.totalWithTax).toBe(0);
  1152. expect(applyCouponCode!.couponCodes).toEqual([TEST_COUPON_CODE]);
  1153. await proceedToArrangingPayment(shopClient);
  1154. const order = await addPaymentToOrder(shopClient, testSuccessfulPaymentMethod);
  1155. orderGuard.assertSuccess(order);
  1156. expect(order.state).toBe('PaymentSettled');
  1157. expect(order.active).toBe(false);
  1158. orderCode = order.code;
  1159. });
  1160. it('adds Promotions to Order once payment arranged', async () => {
  1161. const { orderByCode } = await shopClient.query<
  1162. GetOrderPromotionsByCode.Query,
  1163. GetOrderPromotionsByCode.Variables
  1164. >(GET_ORDER_PROMOTIONS_BY_CODE, {
  1165. code: orderCode,
  1166. });
  1167. expect(orderByCode!.promotions.map(pick(['name']))).toEqual([
  1168. { name: 'Free with test coupon' },
  1169. ]);
  1170. });
  1171. it('returns error result when usage exceeds limit', async () => {
  1172. await shopClient.asAnonymousUser();
  1173. await createNewActiveOrder();
  1174. await addGuestCustomerToOrder();
  1175. const { applyCouponCode } = await shopClient.query<
  1176. ApplyCouponCode.Mutation,
  1177. ApplyCouponCode.Variables
  1178. >(APPLY_COUPON_CODE, { couponCode: TEST_COUPON_CODE });
  1179. orderResultGuard.assertErrorResult(applyCouponCode);
  1180. expect(applyCouponCode.message).toEqual(
  1181. 'Coupon code cannot be used more than once per customer',
  1182. );
  1183. });
  1184. it('removes couponCode from order when adding customer after code applied', async () => {
  1185. await shopClient.asAnonymousUser();
  1186. await createNewActiveOrder();
  1187. const { applyCouponCode } = await shopClient.query<
  1188. ApplyCouponCode.Mutation,
  1189. ApplyCouponCode.Variables
  1190. >(APPLY_COUPON_CODE, { couponCode: TEST_COUPON_CODE });
  1191. orderResultGuard.assertSuccess(applyCouponCode);
  1192. expect(applyCouponCode!.totalWithTax).toBe(0);
  1193. expect(applyCouponCode!.couponCodes).toEqual([TEST_COUPON_CODE]);
  1194. await addGuestCustomerToOrder();
  1195. const { activeOrder } = await shopClient.query<GetActiveOrder.Query>(GET_ACTIVE_ORDER);
  1196. expect(activeOrder!.couponCodes).toEqual([]);
  1197. expect(activeOrder!.totalWithTax).toBe(6000);
  1198. });
  1199. });
  1200. describe('signed-in customer', () => {
  1201. function logInAsRegisteredCustomer() {
  1202. return shopClient.asUserWithCredentials('hayden.zieme12@hotmail.com', 'test');
  1203. }
  1204. it('allows initial usage', async () => {
  1205. await logInAsRegisteredCustomer();
  1206. await createNewActiveOrder();
  1207. const { applyCouponCode } = await shopClient.query<
  1208. ApplyCouponCode.Mutation,
  1209. ApplyCouponCode.Variables
  1210. >(APPLY_COUPON_CODE, { couponCode: TEST_COUPON_CODE });
  1211. orderResultGuard.assertSuccess(applyCouponCode);
  1212. expect(applyCouponCode!.totalWithTax).toBe(0);
  1213. expect(applyCouponCode!.couponCodes).toEqual([TEST_COUPON_CODE]);
  1214. await proceedToArrangingPayment(shopClient);
  1215. const order = await addPaymentToOrder(shopClient, testSuccessfulPaymentMethod);
  1216. orderGuard.assertSuccess(order);
  1217. expect(order.state).toBe('PaymentSettled');
  1218. expect(order.active).toBe(false);
  1219. });
  1220. it('returns error result when usage exceeds limit', async () => {
  1221. await logInAsRegisteredCustomer();
  1222. await createNewActiveOrder();
  1223. const { applyCouponCode } = await shopClient.query<
  1224. ApplyCouponCode.Mutation,
  1225. ApplyCouponCode.Variables
  1226. >(APPLY_COUPON_CODE, { couponCode: TEST_COUPON_CODE });
  1227. orderResultGuard.assertErrorResult(applyCouponCode);
  1228. expect(applyCouponCode.message).toEqual(
  1229. 'Coupon code cannot be used more than once per customer',
  1230. );
  1231. expect(applyCouponCode.errorCode).toBe(ErrorCode.COUPON_CODE_LIMIT_ERROR);
  1232. });
  1233. it('removes couponCode from order when logging in after code applied', async () => {
  1234. await shopClient.asAnonymousUser();
  1235. await createNewActiveOrder();
  1236. const { applyCouponCode } = await shopClient.query<
  1237. ApplyCouponCode.Mutation,
  1238. ApplyCouponCode.Variables
  1239. >(APPLY_COUPON_CODE, { couponCode: TEST_COUPON_CODE });
  1240. orderResultGuard.assertSuccess(applyCouponCode);
  1241. expect(applyCouponCode!.couponCodes).toEqual([TEST_COUPON_CODE]);
  1242. expect(applyCouponCode!.totalWithTax).toBe(0);
  1243. await logInAsRegisteredCustomer();
  1244. const { activeOrder } = await shopClient.query<GetActiveOrder.Query>(GET_ACTIVE_ORDER);
  1245. expect(activeOrder!.totalWithTax).toBe(6000);
  1246. expect(activeOrder!.couponCodes).toEqual([]);
  1247. });
  1248. });
  1249. });
  1250. async function getProducts() {
  1251. const result = await adminClient.query<GetProductsWithVariantPrices.Query>(
  1252. GET_PRODUCTS_WITH_VARIANT_PRICES,
  1253. {
  1254. options: {
  1255. take: 10,
  1256. skip: 0,
  1257. },
  1258. },
  1259. );
  1260. products = result.products.items;
  1261. }
  1262. async function createGlobalPromotions() {
  1263. const { facets } = await adminClient.query<GetFacetList.Query>(GET_FACET_LIST);
  1264. const saleFacetValue = facets.items[0].values[0];
  1265. await createPromotion({
  1266. enabled: true,
  1267. name: 'Promo not yet started',
  1268. startsAt: new Date(2199, 0, 0),
  1269. conditions: [minOrderAmountCondition(100)],
  1270. actions: [freeOrderAction],
  1271. });
  1272. const deletedPromotion = await createPromotion({
  1273. enabled: true,
  1274. name: 'Deleted promotion',
  1275. conditions: [minOrderAmountCondition(100)],
  1276. actions: [freeOrderAction],
  1277. });
  1278. await deletePromotion(deletedPromotion.id);
  1279. }
  1280. async function createPromotion(input: CreatePromotionInput): Promise<PromotionFragment> {
  1281. const result = await adminClient.query<CreatePromotion.Mutation, CreatePromotion.Variables>(
  1282. CREATE_PROMOTION,
  1283. {
  1284. input,
  1285. },
  1286. );
  1287. return result.createPromotion as PromotionFragment;
  1288. }
  1289. function getVariantBySlug(
  1290. slug: 'item-100' | 'item-1000' | 'item-5000' | 'item-sale-100' | 'item-sale-1000',
  1291. ): GetProductsWithVariantPrices.Variants {
  1292. return products.find(p => p.slug === slug)!.variants[0];
  1293. }
  1294. async function deletePromotion(promotionId: string) {
  1295. await adminClient.query(gql`
  1296. mutation DeletePromotionAdHoc1 {
  1297. deletePromotion(id: "${promotionId}") {
  1298. result
  1299. }
  1300. }
  1301. `);
  1302. }
  1303. });