order-promotion.e2e-spec.ts 91 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168
  1. /* eslint-disable @typescript-eslint/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. mergeConfig,
  13. minimumOrderAmount,
  14. orderPercentageDiscount,
  15. productsPercentageDiscount,
  16. } from '@vendure/core';
  17. import {
  18. createErrorResultGuard,
  19. createTestEnvironment,
  20. E2E_DEFAULT_CHANNEL_TOKEN,
  21. ErrorResultGuard,
  22. } from '@vendure/testing';
  23. import gql from 'graphql-tag';
  24. import path from 'path';
  25. import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest';
  26. import { initialData } from '../../../e2e-common/e2e-initial-data';
  27. import { testConfig, TEST_SETUP_TIMEOUT_MS } from '../../../e2e-common/test-config';
  28. import { freeShipping } from '../src/config/promotion/actions/free-shipping-action';
  29. import { orderFixedDiscount } from '../src/config/promotion/actions/order-fixed-discount-action';
  30. import { testSuccessfulPaymentMethod } from './fixtures/test-payment-methods';
  31. import { CurrencyCode, HistoryEntryType, LanguageCode } from './graphql/generated-e2e-admin-types';
  32. import * as Codegen from './graphql/generated-e2e-admin-types';
  33. import { AdjustmentType, ErrorCode } from './graphql/generated-e2e-shop-types';
  34. import * as CodegenShop from './graphql/generated-e2e-shop-types';
  35. import {
  36. ASSIGN_PRODUCT_TO_CHANNEL,
  37. ASSIGN_PROMOTIONS_TO_CHANNEL,
  38. CANCEL_ORDER,
  39. CREATE_CHANNEL,
  40. CREATE_CUSTOMER_GROUP,
  41. CREATE_PROMOTION,
  42. CREATE_SHIPPING_METHOD,
  43. GET_FACET_LIST,
  44. GET_PRODUCTS_WITH_VARIANT_PRICES,
  45. REMOVE_CUSTOMERS_FROM_GROUP,
  46. } from './graphql/shared-definitions';
  47. import {
  48. ADD_ITEM_TO_ORDER,
  49. ADJUST_ITEM_QUANTITY,
  50. APPLY_COUPON_CODE,
  51. GET_ACTIVE_ORDER,
  52. GET_ORDER_PROMOTIONS_BY_CODE,
  53. REMOVE_COUPON_CODE,
  54. REMOVE_ITEM_FROM_ORDER,
  55. SET_CUSTOMER,
  56. SET_SHIPPING_METHOD,
  57. } from './graphql/shop-definitions';
  58. import { addPaymentToOrder, proceedToArrangingPayment } from './utils/test-order-utils';
  59. describe('Promotions applied to Orders', () => {
  60. const { server, adminClient, shopClient } = createTestEnvironment(
  61. mergeConfig(testConfig(), {
  62. dbConnectionOptions: { logging: true },
  63. paymentOptions: {
  64. paymentMethodHandlers: [testSuccessfulPaymentMethod],
  65. },
  66. }),
  67. );
  68. const freeOrderAction = {
  69. code: orderPercentageDiscount.code,
  70. arguments: [{ name: 'discount', value: '100' }],
  71. };
  72. const minOrderAmountCondition = (min: number) => ({
  73. code: minimumOrderAmount.code,
  74. arguments: [
  75. { name: 'amount', value: min.toString() },
  76. { name: 'taxInclusive', value: 'true' },
  77. ],
  78. });
  79. type OrderSuccessResult = CodegenShop.UpdatedOrderFragment | CodegenShop.TestOrderFragmentFragment;
  80. const orderResultGuard: ErrorResultGuard<OrderSuccessResult> = createErrorResultGuard(
  81. input => !!input.lines,
  82. );
  83. let products: Codegen.GetProductsWithVariantPricesQuery['products']['items'];
  84. beforeAll(async () => {
  85. await server.init({
  86. initialData: {
  87. ...initialData,
  88. paymentMethods: [
  89. {
  90. name: testSuccessfulPaymentMethod.code,
  91. handler: { code: testSuccessfulPaymentMethod.code, arguments: [] },
  92. },
  93. ],
  94. },
  95. productsCsvPath: path.join(__dirname, 'fixtures/e2e-products-promotions.csv'),
  96. customerCount: 2,
  97. });
  98. await adminClient.asSuperAdmin();
  99. await getProducts();
  100. await createGlobalPromotions();
  101. }, TEST_SETUP_TIMEOUT_MS);
  102. afterAll(async () => {
  103. await server.destroy();
  104. });
  105. describe('coupon codes', () => {
  106. const TEST_COUPON_CODE = 'TESTCOUPON';
  107. const EXPIRED_COUPON_CODE = 'EXPIRED';
  108. let promoFreeWithCoupon: Codegen.PromotionFragment;
  109. let promoFreeWithExpiredCoupon: Codegen.PromotionFragment;
  110. beforeAll(async () => {
  111. promoFreeWithCoupon = await createPromotion({
  112. enabled: true,
  113. name: 'Free with test coupon',
  114. couponCode: TEST_COUPON_CODE,
  115. conditions: [],
  116. actions: [freeOrderAction],
  117. });
  118. promoFreeWithExpiredCoupon = await createPromotion({
  119. enabled: true,
  120. name: 'Expired coupon',
  121. endsAt: new Date(2010, 0, 0),
  122. couponCode: EXPIRED_COUPON_CODE,
  123. conditions: [],
  124. actions: [freeOrderAction],
  125. });
  126. await shopClient.asAnonymousUser();
  127. await shopClient.query<
  128. CodegenShop.AddItemToOrderMutation,
  129. CodegenShop.AddItemToOrderMutationVariables
  130. >(ADD_ITEM_TO_ORDER, {
  131. productVariantId: getVariantBySlug('item-5000').id,
  132. quantity: 1,
  133. });
  134. });
  135. afterAll(async () => {
  136. await deletePromotion(promoFreeWithCoupon.id);
  137. await deletePromotion(promoFreeWithExpiredCoupon.id);
  138. });
  139. it('applyCouponCode returns error result when code is nonexistant', async () => {
  140. const { applyCouponCode } = await shopClient.query<
  141. CodegenShop.ApplyCouponCodeMutation,
  142. CodegenShop.ApplyCouponCodeMutationVariables
  143. >(APPLY_COUPON_CODE, {
  144. couponCode: 'bad code',
  145. });
  146. orderResultGuard.assertErrorResult(applyCouponCode);
  147. expect(applyCouponCode.message).toBe('Coupon code "bad code" is not valid');
  148. expect(applyCouponCode.errorCode).toBe(ErrorCode.COUPON_CODE_INVALID_ERROR);
  149. });
  150. it('applyCouponCode returns error when code is expired', async () => {
  151. const { applyCouponCode } = await shopClient.query<
  152. CodegenShop.ApplyCouponCodeMutation,
  153. CodegenShop.ApplyCouponCodeMutationVariables
  154. >(APPLY_COUPON_CODE, {
  155. couponCode: EXPIRED_COUPON_CODE,
  156. });
  157. orderResultGuard.assertErrorResult(applyCouponCode);
  158. expect(applyCouponCode.message).toBe(`Coupon code "${EXPIRED_COUPON_CODE}" has expired`);
  159. expect(applyCouponCode.errorCode).toBe(ErrorCode.COUPON_CODE_EXPIRED_ERROR);
  160. });
  161. it('coupon code application is case-sensitive', async () => {
  162. const { applyCouponCode } = await shopClient.query<
  163. CodegenShop.ApplyCouponCodeMutation,
  164. CodegenShop.ApplyCouponCodeMutationVariables
  165. >(APPLY_COUPON_CODE, {
  166. couponCode: TEST_COUPON_CODE.toLowerCase(),
  167. });
  168. orderResultGuard.assertErrorResult(applyCouponCode);
  169. expect(applyCouponCode.message).toBe(
  170. `Coupon code "${TEST_COUPON_CODE.toLowerCase()}" is not valid`,
  171. );
  172. expect(applyCouponCode.errorCode).toBe(ErrorCode.COUPON_CODE_INVALID_ERROR);
  173. });
  174. it('applies a valid coupon code', async () => {
  175. const { applyCouponCode } = await shopClient.query<
  176. CodegenShop.ApplyCouponCodeMutation,
  177. CodegenShop.ApplyCouponCodeMutationVariables
  178. >(APPLY_COUPON_CODE, {
  179. couponCode: TEST_COUPON_CODE,
  180. });
  181. orderResultGuard.assertSuccess(applyCouponCode);
  182. expect(applyCouponCode.couponCodes).toEqual([TEST_COUPON_CODE]);
  183. expect(applyCouponCode.discounts.length).toBe(1);
  184. expect(applyCouponCode.discounts[0].description).toBe('Free with test coupon');
  185. expect(applyCouponCode.totalWithTax).toBe(0);
  186. });
  187. it('order history records application', async () => {
  188. const { activeOrder } = await shopClient.query<CodegenShop.GetActiveOrderQuery>(GET_ACTIVE_ORDER);
  189. expect(activeOrder!.history.items.map(i => omit(i, ['id']))).toEqual([
  190. {
  191. type: HistoryEntryType.ORDER_STATE_TRANSITION,
  192. data: {
  193. from: 'Created',
  194. to: 'AddingItems',
  195. },
  196. },
  197. {
  198. type: HistoryEntryType.ORDER_COUPON_APPLIED,
  199. data: {
  200. couponCode: TEST_COUPON_CODE,
  201. promotionId: 'T_3',
  202. },
  203. },
  204. ]);
  205. });
  206. it('de-duplicates existing codes', async () => {
  207. const { applyCouponCode } = await shopClient.query<
  208. CodegenShop.ApplyCouponCodeMutation,
  209. CodegenShop.ApplyCouponCodeMutationVariables
  210. >(APPLY_COUPON_CODE, {
  211. couponCode: TEST_COUPON_CODE,
  212. });
  213. orderResultGuard.assertSuccess(applyCouponCode);
  214. expect(applyCouponCode.couponCodes).toEqual([TEST_COUPON_CODE]);
  215. });
  216. it('removes a coupon code', async () => {
  217. const { removeCouponCode } = await shopClient.query<
  218. CodegenShop.RemoveCouponCodeMutation,
  219. CodegenShop.RemoveCouponCodeMutationVariables
  220. >(REMOVE_COUPON_CODE, {
  221. couponCode: TEST_COUPON_CODE,
  222. });
  223. expect(removeCouponCode!.discounts.length).toBe(0);
  224. expect(removeCouponCode!.totalWithTax).toBe(6000);
  225. });
  226. // https://github.com/vendure-ecommerce/vendure/issues/649
  227. it('discounts array cleared after coupon code removed', async () => {
  228. const { activeOrder } = await shopClient.query<CodegenShop.GetActiveOrderQuery>(GET_ACTIVE_ORDER);
  229. expect(activeOrder?.discounts).toEqual([]);
  230. });
  231. it('order history records removal', async () => {
  232. const { activeOrder } = await shopClient.query<CodegenShop.GetActiveOrderQuery>(GET_ACTIVE_ORDER);
  233. expect(activeOrder!.history.items.map(i => omit(i, ['id']))).toEqual([
  234. {
  235. type: HistoryEntryType.ORDER_STATE_TRANSITION,
  236. data: {
  237. from: 'Created',
  238. to: 'AddingItems',
  239. },
  240. },
  241. {
  242. type: HistoryEntryType.ORDER_COUPON_APPLIED,
  243. data: {
  244. couponCode: TEST_COUPON_CODE,
  245. promotionId: 'T_3',
  246. },
  247. },
  248. {
  249. type: HistoryEntryType.ORDER_COUPON_REMOVED,
  250. data: {
  251. couponCode: TEST_COUPON_CODE,
  252. },
  253. },
  254. ]);
  255. });
  256. it('does not record removal of coupon code that was not added', async () => {
  257. const { removeCouponCode } = await shopClient.query<
  258. CodegenShop.RemoveCouponCodeMutation,
  259. CodegenShop.RemoveCouponCodeMutationVariables
  260. >(REMOVE_COUPON_CODE, {
  261. couponCode: 'NOT_THERE',
  262. });
  263. expect(removeCouponCode!.history.items.map(i => omit(i, ['id']))).toEqual([
  264. {
  265. type: HistoryEntryType.ORDER_STATE_TRANSITION,
  266. data: {
  267. from: 'Created',
  268. to: 'AddingItems',
  269. },
  270. },
  271. {
  272. type: HistoryEntryType.ORDER_COUPON_APPLIED,
  273. data: {
  274. couponCode: TEST_COUPON_CODE,
  275. promotionId: 'T_3',
  276. },
  277. },
  278. {
  279. type: HistoryEntryType.ORDER_COUPON_REMOVED,
  280. data: {
  281. couponCode: TEST_COUPON_CODE,
  282. },
  283. },
  284. ]);
  285. });
  286. describe('coupon codes in other channels', () => {
  287. const OTHER_CHANNEL_TOKEN = 'other-channel';
  288. const OTHER_CHANNEL_COUPON_CODE = 'OTHER_CHANNEL_CODE';
  289. beforeAll(async () => {
  290. const { createChannel } = await adminClient.query<
  291. Codegen.CreateChannelMutation,
  292. Codegen.CreateChannelMutationVariables
  293. >(CREATE_CHANNEL, {
  294. input: {
  295. code: 'other-channel',
  296. currencyCode: CurrencyCode.GBP,
  297. pricesIncludeTax: false,
  298. defaultTaxZoneId: 'T_1',
  299. defaultShippingZoneId: 'T_1',
  300. defaultLanguageCode: LanguageCode.en,
  301. token: OTHER_CHANNEL_TOKEN,
  302. },
  303. });
  304. await createPromotion({
  305. enabled: true,
  306. name: 'Other Channel Promo',
  307. couponCode: OTHER_CHANNEL_COUPON_CODE,
  308. conditions: [],
  309. actions: [freeOrderAction],
  310. });
  311. });
  312. afterAll(() => {
  313. shopClient.setChannelToken(E2E_DEFAULT_CHANNEL_TOKEN);
  314. });
  315. // https://github.com/vendure-ecommerce/vendure/issues/1692
  316. it('does not allow a couponCode from another channel', async () => {
  317. shopClient.setChannelToken(OTHER_CHANNEL_TOKEN);
  318. const { applyCouponCode } = await shopClient.query<
  319. ApplyCouponCode.Mutation,
  320. ApplyCouponCode.Variables
  321. >(APPLY_COUPON_CODE, {
  322. couponCode: OTHER_CHANNEL_COUPON_CODE,
  323. });
  324. orderResultGuard.assertErrorResult(applyCouponCode);
  325. expect(applyCouponCode.errorCode).toEqual('COUPON_CODE_INVALID_ERROR');
  326. });
  327. });
  328. });
  329. describe('default PromotionConditions', () => {
  330. beforeEach(async () => {
  331. await shopClient.asAnonymousUser();
  332. });
  333. it('minimumOrderAmount', async () => {
  334. const promotion = await createPromotion({
  335. enabled: true,
  336. name: 'Free if order total greater than 100',
  337. conditions: [minOrderAmountCondition(10000)],
  338. actions: [freeOrderAction],
  339. });
  340. const { addItemToOrder } = await shopClient.query<
  341. CodegenShop.AddItemToOrderMutation,
  342. CodegenShop.AddItemToOrderMutationVariables
  343. >(ADD_ITEM_TO_ORDER, {
  344. productVariantId: getVariantBySlug('item-5000').id,
  345. quantity: 1,
  346. });
  347. orderResultGuard.assertSuccess(addItemToOrder);
  348. expect(addItemToOrder.totalWithTax).toBe(6000);
  349. expect(addItemToOrder.discounts.length).toBe(0);
  350. const { adjustOrderLine } = await shopClient.query<
  351. CodegenShop.AdjustItemQuantityMutation,
  352. CodegenShop.AdjustItemQuantityMutationVariables
  353. >(ADJUST_ITEM_QUANTITY, {
  354. orderLineId: addItemToOrder.lines[0].id,
  355. quantity: 2,
  356. });
  357. orderResultGuard.assertSuccess(adjustOrderLine);
  358. expect(adjustOrderLine.totalWithTax).toBe(0);
  359. expect(adjustOrderLine.discounts[0].description).toBe('Free if order total greater than 100');
  360. expect(adjustOrderLine.discounts[0].amountWithTax).toBe(-12000);
  361. await deletePromotion(promotion.id);
  362. });
  363. it('atLeastNWithFacets', async () => {
  364. const { facets } = await adminClient.query<Codegen.GetFacetListQuery>(GET_FACET_LIST);
  365. const saleFacetValue = facets.items[0].values[0];
  366. const promotion = await createPromotion({
  367. enabled: true,
  368. name: 'Free if order contains 2 items with Sale facet value',
  369. conditions: [
  370. {
  371. code: hasFacetValues.code,
  372. arguments: [
  373. { name: 'minimum', value: '2' },
  374. { name: 'facets', value: `["${saleFacetValue.id}"]` },
  375. ],
  376. },
  377. ],
  378. actions: [freeOrderAction],
  379. });
  380. const { addItemToOrder: res1 } = await shopClient.query<
  381. CodegenShop.AddItemToOrderMutation,
  382. CodegenShop.AddItemToOrderMutationVariables
  383. >(ADD_ITEM_TO_ORDER, {
  384. productVariantId: getVariantBySlug('item-sale-100').id,
  385. quantity: 1,
  386. });
  387. orderResultGuard.assertSuccess(res1);
  388. expect(res1.totalWithTax).toBe(120);
  389. expect(res1.discounts.length).toBe(0);
  390. const { addItemToOrder: res2 } = await shopClient.query<
  391. CodegenShop.AddItemToOrderMutation,
  392. CodegenShop.AddItemToOrderMutationVariables
  393. >(ADD_ITEM_TO_ORDER, {
  394. productVariantId: getVariantBySlug('item-sale-1000').id,
  395. quantity: 1,
  396. });
  397. orderResultGuard.assertSuccess(res2);
  398. expect(res2.totalWithTax).toBe(0);
  399. expect(res2.discounts.length).toBe(1);
  400. expect(res2.totalWithTax).toBe(0);
  401. expect(res2.discounts[0].description).toBe(
  402. 'Free if order contains 2 items with Sale facet value',
  403. );
  404. expect(res2.discounts[0].amountWithTax).toBe(-1320);
  405. await deletePromotion(promotion.id);
  406. });
  407. it('containsProducts', async () => {
  408. const item5000 = getVariantBySlug('item-5000')!;
  409. const item1000 = getVariantBySlug('item-1000')!;
  410. const promotion = await createPromotion({
  411. enabled: true,
  412. name: 'Free if buying 3 or more offer products',
  413. conditions: [
  414. {
  415. code: containsProducts.code,
  416. arguments: [
  417. { name: 'minimum', value: '3' },
  418. {
  419. name: 'productVariantIds',
  420. value: JSON.stringify([item5000.id, item1000.id]),
  421. },
  422. ],
  423. },
  424. ],
  425. actions: [freeOrderAction],
  426. });
  427. await shopClient.query<
  428. CodegenShop.AddItemToOrderMutation,
  429. CodegenShop.AddItemToOrderMutationVariables
  430. >(ADD_ITEM_TO_ORDER, {
  431. productVariantId: item5000.id,
  432. quantity: 1,
  433. });
  434. const { addItemToOrder } = await shopClient.query<
  435. CodegenShop.AddItemToOrderMutation,
  436. CodegenShop.AddItemToOrderMutationVariables
  437. >(ADD_ITEM_TO_ORDER, {
  438. productVariantId: item1000.id,
  439. quantity: 1,
  440. });
  441. orderResultGuard.assertSuccess(addItemToOrder);
  442. expect(addItemToOrder.totalWithTax).toBe(7200);
  443. expect(addItemToOrder.discounts.length).toBe(0);
  444. const { adjustOrderLine } = await shopClient.query<
  445. CodegenShop.AdjustItemQuantityMutation,
  446. CodegenShop.AdjustItemQuantityMutationVariables
  447. >(ADJUST_ITEM_QUANTITY, {
  448. orderLineId: addItemToOrder.lines.find(l => l.productVariant.id === item5000.id)!.id,
  449. quantity: 2,
  450. });
  451. orderResultGuard.assertSuccess(adjustOrderLine);
  452. expect(adjustOrderLine.total).toBe(0);
  453. expect(adjustOrderLine.discounts[0].description).toBe('Free if buying 3 or more offer products');
  454. expect(adjustOrderLine.discounts[0].amountWithTax).toBe(-13200);
  455. await deletePromotion(promotion.id);
  456. });
  457. it('customerGroup', async () => {
  458. const { createCustomerGroup } = await adminClient.query<
  459. Codegen.CreateCustomerGroupMutation,
  460. Codegen.CreateCustomerGroupMutationVariables
  461. >(CREATE_CUSTOMER_GROUP, {
  462. input: { name: 'Test Group', customerIds: ['T_1'] },
  463. });
  464. await shopClient.asUserWithCredentials('hayden.zieme12@hotmail.com', 'test');
  465. const promotion = await createPromotion({
  466. enabled: true,
  467. name: 'Free for group members',
  468. conditions: [
  469. {
  470. code: customerGroup.code,
  471. arguments: [{ name: 'customerGroupId', value: createCustomerGroup.id }],
  472. },
  473. ],
  474. actions: [freeOrderAction],
  475. });
  476. const { addItemToOrder } = await shopClient.query<
  477. CodegenShop.AddItemToOrderMutation,
  478. CodegenShop.AddItemToOrderMutationVariables
  479. >(ADD_ITEM_TO_ORDER, {
  480. productVariantId: getVariantBySlug('item-5000').id,
  481. quantity: 1,
  482. });
  483. orderResultGuard.assertSuccess(addItemToOrder);
  484. expect(addItemToOrder.totalWithTax).toBe(0);
  485. expect(addItemToOrder.discounts.length).toBe(1);
  486. expect(addItemToOrder.discounts[0].description).toBe('Free for group members');
  487. expect(addItemToOrder.discounts[0].amountWithTax).toBe(-6000);
  488. await adminClient.query<
  489. Codegen.RemoveCustomersFromGroupMutation,
  490. Codegen.RemoveCustomersFromGroupMutationVariables
  491. >(REMOVE_CUSTOMERS_FROM_GROUP, {
  492. groupId: createCustomerGroup.id,
  493. customerIds: ['T_1'],
  494. });
  495. const { adjustOrderLine } = await shopClient.query<
  496. CodegenShop.AdjustItemQuantityMutation,
  497. CodegenShop.AdjustItemQuantityMutationVariables
  498. >(ADJUST_ITEM_QUANTITY, {
  499. orderLineId: addItemToOrder.lines[0].id,
  500. quantity: 2,
  501. });
  502. orderResultGuard.assertSuccess(adjustOrderLine);
  503. expect(adjustOrderLine.totalWithTax).toBe(12000);
  504. expect(adjustOrderLine.discounts.length).toBe(0);
  505. await deletePromotion(promotion.id);
  506. });
  507. });
  508. describe('default PromotionActions', () => {
  509. const TAX_INCLUDED_CHANNEL_TOKEN = 'tax_included_channel';
  510. let taxIncludedChannel: Codegen.ChannelFragment;
  511. beforeAll(async () => {
  512. // Create a channel where the prices include tax, so we can ensure
  513. // that PromotionActions are working as expected when taxes are included
  514. const { createChannel } = await adminClient.query<
  515. Codegen.CreateChannelMutation,
  516. Codegen.CreateChannelMutationVariables
  517. >(CREATE_CHANNEL, {
  518. input: {
  519. code: 'tax-included-channel',
  520. currencyCode: CurrencyCode.GBP,
  521. pricesIncludeTax: true,
  522. defaultTaxZoneId: 'T_1',
  523. defaultShippingZoneId: 'T_1',
  524. defaultLanguageCode: LanguageCode.en,
  525. token: TAX_INCLUDED_CHANNEL_TOKEN,
  526. },
  527. });
  528. taxIncludedChannel = createChannel as Codegen.ChannelFragment;
  529. await adminClient.query<
  530. Codegen.AssignProductsToChannelMutation,
  531. Codegen.AssignProductsToChannelMutationVariables
  532. >(ASSIGN_PRODUCT_TO_CHANNEL, {
  533. input: {
  534. channelId: taxIncludedChannel.id,
  535. priceFactor: 1,
  536. productIds: products.map(p => p.id),
  537. },
  538. });
  539. });
  540. beforeEach(async () => {
  541. await shopClient.asAnonymousUser();
  542. });
  543. async function assignPromotionToTaxIncludedChannel(promotionId: string | string[]) {
  544. await adminClient.query<
  545. Codegen.AssignPromotionToChannelMutation,
  546. Codegen.AssignPromotionToChannelMutationVariables
  547. >(ASSIGN_PROMOTIONS_TO_CHANNEL, {
  548. input: {
  549. promotionIds: Array.isArray(promotionId) ? promotionId : [promotionId],
  550. channelId: taxIncludedChannel.id,
  551. },
  552. });
  553. }
  554. describe('orderPercentageDiscount', () => {
  555. const couponCode = '50%_off_order';
  556. let promotion: Codegen.PromotionFragment;
  557. beforeAll(async () => {
  558. promotion = await createPromotion({
  559. enabled: true,
  560. name: '20% discount on order',
  561. couponCode,
  562. conditions: [],
  563. actions: [
  564. {
  565. code: orderPercentageDiscount.code,
  566. arguments: [{ name: 'discount', value: '20' }],
  567. },
  568. ],
  569. });
  570. await assignPromotionToTaxIncludedChannel(promotion.id);
  571. });
  572. afterAll(async () => {
  573. await deletePromotion(promotion.id);
  574. });
  575. it('prices exclude tax', async () => {
  576. shopClient.setChannelToken(E2E_DEFAULT_CHANNEL_TOKEN);
  577. const { addItemToOrder } = await shopClient.query<
  578. CodegenShop.AddItemToOrderMutation,
  579. CodegenShop.AddItemToOrderMutationVariables
  580. >(ADD_ITEM_TO_ORDER, {
  581. productVariantId: getVariantBySlug('item-5000').id,
  582. quantity: 1,
  583. });
  584. orderResultGuard.assertSuccess(addItemToOrder);
  585. expect(addItemToOrder.totalWithTax).toBe(6000);
  586. expect(addItemToOrder.discounts.length).toBe(0);
  587. const { applyCouponCode } = await shopClient.query<
  588. CodegenShop.ApplyCouponCodeMutation,
  589. CodegenShop.ApplyCouponCodeMutationVariables
  590. >(APPLY_COUPON_CODE, {
  591. couponCode,
  592. });
  593. orderResultGuard.assertSuccess(applyCouponCode);
  594. expect(applyCouponCode.discounts.length).toBe(1);
  595. expect(applyCouponCode.discounts[0].description).toBe('20% discount on order');
  596. expect(applyCouponCode.totalWithTax).toBe(4800);
  597. });
  598. it('prices include tax', async () => {
  599. shopClient.setChannelToken(TAX_INCLUDED_CHANNEL_TOKEN);
  600. const { addItemToOrder } = await shopClient.query<
  601. CodegenShop.AddItemToOrderMutation,
  602. CodegenShop.AddItemToOrderMutationVariables
  603. >(ADD_ITEM_TO_ORDER, {
  604. productVariantId: getVariantBySlug('item-5000').id,
  605. quantity: 1,
  606. });
  607. orderResultGuard.assertSuccess(addItemToOrder);
  608. expect(addItemToOrder.totalWithTax).toBe(6000);
  609. expect(addItemToOrder.discounts.length).toBe(0);
  610. const { applyCouponCode } = await shopClient.query<
  611. CodegenShop.ApplyCouponCodeMutation,
  612. CodegenShop.ApplyCouponCodeMutationVariables
  613. >(APPLY_COUPON_CODE, {
  614. couponCode,
  615. });
  616. orderResultGuard.assertSuccess(applyCouponCode);
  617. expect(applyCouponCode.discounts.length).toBe(1);
  618. expect(applyCouponCode.discounts[0].description).toBe('20% discount on order');
  619. expect(applyCouponCode.totalWithTax).toBe(4800);
  620. });
  621. // https://github.com/vendure-ecommerce/vendure/issues/1773
  622. it('decimal percentage', async () => {
  623. const decimalPercentageCouponCode = 'DPCC';
  624. await createPromotion({
  625. enabled: true,
  626. name: '10.5% discount on order',
  627. couponCode: decimalPercentageCouponCode,
  628. conditions: [],
  629. actions: [
  630. {
  631. code: orderPercentageDiscount.code,
  632. arguments: [{ name: 'discount', value: '10.5' }],
  633. },
  634. ],
  635. });
  636. shopClient.setChannelToken(E2E_DEFAULT_CHANNEL_TOKEN);
  637. const { addItemToOrder } = await shopClient.query<
  638. AddItemToOrder.Mutation,
  639. AddItemToOrder.Variables
  640. >(ADD_ITEM_TO_ORDER, {
  641. productVariantId: getVariantBySlug('item-5000').id,
  642. quantity: 1,
  643. });
  644. orderResultGuard.assertSuccess(addItemToOrder);
  645. expect(addItemToOrder.totalWithTax).toBe(6000);
  646. expect(addItemToOrder.discounts.length).toBe(0);
  647. const { applyCouponCode } = await shopClient.query<
  648. ApplyCouponCode.Mutation,
  649. ApplyCouponCode.Variables
  650. >(APPLY_COUPON_CODE, {
  651. couponCode: decimalPercentageCouponCode,
  652. });
  653. orderResultGuard.assertSuccess(applyCouponCode);
  654. expect(applyCouponCode.discounts.length).toBe(1);
  655. expect(applyCouponCode.discounts[0].description).toBe('10.5% discount on order');
  656. expect(applyCouponCode.totalWithTax).toBe(5370);
  657. });
  658. });
  659. describe('orderFixedDiscount', () => {
  660. const couponCode = '10_off_order';
  661. let promotion: Codegen.PromotionFragment;
  662. beforeAll(async () => {
  663. promotion = await createPromotion({
  664. enabled: true,
  665. name: '$10 discount on order',
  666. couponCode,
  667. conditions: [],
  668. actions: [
  669. {
  670. code: orderFixedDiscount.code,
  671. arguments: [{ name: 'discount', value: '1000' }],
  672. },
  673. ],
  674. });
  675. await assignPromotionToTaxIncludedChannel(promotion.id);
  676. });
  677. afterAll(async () => {
  678. await deletePromotion(promotion.id);
  679. shopClient.setChannelToken(E2E_DEFAULT_CHANNEL_TOKEN);
  680. });
  681. it('prices exclude tax', async () => {
  682. shopClient.setChannelToken(E2E_DEFAULT_CHANNEL_TOKEN);
  683. const { addItemToOrder } = await shopClient.query<
  684. CodegenShop.AddItemToOrderMutation,
  685. CodegenShop.AddItemToOrderMutationVariables
  686. >(ADD_ITEM_TO_ORDER, {
  687. productVariantId: getVariantBySlug('item-5000').id,
  688. quantity: 1,
  689. });
  690. orderResultGuard.assertSuccess(addItemToOrder);
  691. expect(addItemToOrder.total).toBe(5000);
  692. expect(addItemToOrder.totalWithTax).toBe(6000);
  693. expect(addItemToOrder.discounts.length).toBe(0);
  694. const { applyCouponCode } = await shopClient.query<
  695. CodegenShop.ApplyCouponCodeMutation,
  696. CodegenShop.ApplyCouponCodeMutationVariables
  697. >(APPLY_COUPON_CODE, {
  698. couponCode,
  699. });
  700. orderResultGuard.assertSuccess(applyCouponCode);
  701. expect(applyCouponCode.discounts.length).toBe(1);
  702. expect(applyCouponCode.discounts[0].description).toBe('$10 discount on order');
  703. expect(applyCouponCode.total).toBe(4000);
  704. expect(applyCouponCode.totalWithTax).toBe(4800);
  705. });
  706. it('prices include tax', async () => {
  707. shopClient.setChannelToken(TAX_INCLUDED_CHANNEL_TOKEN);
  708. const { addItemToOrder } = await shopClient.query<
  709. CodegenShop.AddItemToOrderMutation,
  710. CodegenShop.AddItemToOrderMutationVariables
  711. >(ADD_ITEM_TO_ORDER, {
  712. productVariantId: getVariantBySlug('item-5000').id,
  713. quantity: 1,
  714. });
  715. orderResultGuard.assertSuccess(addItemToOrder);
  716. expect(addItemToOrder.totalWithTax).toBe(6000);
  717. expect(addItemToOrder.discounts.length).toBe(0);
  718. const { applyCouponCode } = await shopClient.query<
  719. CodegenShop.ApplyCouponCodeMutation,
  720. CodegenShop.ApplyCouponCodeMutationVariables
  721. >(APPLY_COUPON_CODE, {
  722. couponCode,
  723. });
  724. orderResultGuard.assertSuccess(applyCouponCode);
  725. expect(applyCouponCode.discounts.length).toBe(1);
  726. expect(applyCouponCode.discounts[0].description).toBe('$10 discount on order');
  727. expect(applyCouponCode.totalWithTax).toBe(5000);
  728. });
  729. it('does not result in negative total when shipping is included', async () => {
  730. shopClient.setChannelToken(E2E_DEFAULT_CHANNEL_TOKEN);
  731. const { addItemToOrder } = await shopClient.query<
  732. CodegenShop.AddItemToOrderMutation,
  733. CodegenShop.AddItemToOrderMutationVariables
  734. >(ADD_ITEM_TO_ORDER, {
  735. productVariantId: getVariantBySlug('item-100').id,
  736. quantity: 1,
  737. });
  738. orderResultGuard.assertSuccess(addItemToOrder);
  739. expect(addItemToOrder.totalWithTax).toBe(120);
  740. expect(addItemToOrder.discounts.length).toBe(0);
  741. const { setOrderShippingMethod } = await shopClient.query<
  742. CodegenShop.SetShippingMethodMutation,
  743. CodegenShop.SetShippingMethodMutationVariables
  744. >(SET_SHIPPING_METHOD, {
  745. id: 'T_1',
  746. });
  747. orderResultGuard.assertSuccess(setOrderShippingMethod);
  748. expect(setOrderShippingMethod.totalWithTax).toBe(620);
  749. const { applyCouponCode } = await shopClient.query<
  750. CodegenShop.ApplyCouponCodeMutation,
  751. CodegenShop.ApplyCouponCodeMutationVariables
  752. >(APPLY_COUPON_CODE, {
  753. couponCode,
  754. });
  755. orderResultGuard.assertSuccess(applyCouponCode);
  756. expect(applyCouponCode.discounts.length).toBe(1);
  757. expect(applyCouponCode.discounts[0].description).toBe('$10 discount on order');
  758. expect(applyCouponCode.subTotalWithTax).toBe(0);
  759. expect(applyCouponCode.totalWithTax).toBe(500); // shipping price
  760. });
  761. });
  762. describe('discountOnItemWithFacets', () => {
  763. const couponCode = '50%_off_sale_items';
  764. let promotion: Codegen.PromotionFragment;
  765. function getItemSale1Line<
  766. T extends Array<
  767. | CodegenShop.UpdatedOrderFragment['lines'][number]
  768. | CodegenShop.TestOrderFragmentFragment['lines'][number]
  769. >,
  770. >(lines: T): T[number] {
  771. return lines.find(l => l.productVariant.id === getVariantBySlug('item-sale-100').id)!;
  772. }
  773. beforeAll(async () => {
  774. const { facets } = await adminClient.query<Codegen.GetFacetListQuery>(GET_FACET_LIST);
  775. const saleFacetValue = facets.items[0].values[0];
  776. promotion = await createPromotion({
  777. enabled: true,
  778. name: '50% off sale items',
  779. couponCode,
  780. conditions: [],
  781. actions: [
  782. {
  783. code: discountOnItemWithFacets.code,
  784. arguments: [
  785. { name: 'discount', value: '50' },
  786. { name: 'facets', value: `["${saleFacetValue.id}"]` },
  787. ],
  788. },
  789. ],
  790. });
  791. await assignPromotionToTaxIncludedChannel(promotion.id);
  792. });
  793. afterAll(async () => {
  794. await deletePromotion(promotion.id);
  795. shopClient.setChannelToken(E2E_DEFAULT_CHANNEL_TOKEN);
  796. });
  797. it('prices exclude tax', async () => {
  798. await shopClient.query<
  799. CodegenShop.AddItemToOrderMutation,
  800. CodegenShop.AddItemToOrderMutationVariables
  801. >(ADD_ITEM_TO_ORDER, {
  802. productVariantId: getVariantBySlug('item-1000').id,
  803. quantity: 1,
  804. });
  805. await shopClient.query<
  806. CodegenShop.AddItemToOrderMutation,
  807. CodegenShop.AddItemToOrderMutationVariables
  808. >(ADD_ITEM_TO_ORDER, {
  809. productVariantId: getVariantBySlug('item-sale-1000').id,
  810. quantity: 1,
  811. });
  812. const { addItemToOrder } = await shopClient.query<
  813. CodegenShop.AddItemToOrderMutation,
  814. CodegenShop.AddItemToOrderMutationVariables
  815. >(ADD_ITEM_TO_ORDER, {
  816. productVariantId: getVariantBySlug('item-sale-100').id,
  817. quantity: 2,
  818. });
  819. orderResultGuard.assertSuccess(addItemToOrder);
  820. expect(addItemToOrder.discounts.length).toBe(0);
  821. expect(getItemSale1Line(addItemToOrder.lines).discounts.length).toBe(0);
  822. expect(addItemToOrder.total).toBe(2200);
  823. expect(addItemToOrder.totalWithTax).toBe(2640);
  824. const { applyCouponCode } = await shopClient.query<
  825. CodegenShop.ApplyCouponCodeMutation,
  826. CodegenShop.ApplyCouponCodeMutationVariables
  827. >(APPLY_COUPON_CODE, {
  828. couponCode,
  829. });
  830. orderResultGuard.assertSuccess(applyCouponCode);
  831. expect(applyCouponCode.total).toBe(1600);
  832. expect(applyCouponCode.totalWithTax).toBe(1920);
  833. expect(getItemSale1Line(applyCouponCode.lines).discounts.length).toBe(1); // 1x promotion
  834. const { removeCouponCode } = await shopClient.query<
  835. CodegenShop.RemoveCouponCodeMutation,
  836. CodegenShop.RemoveCouponCodeMutationVariables
  837. >(REMOVE_COUPON_CODE, {
  838. couponCode,
  839. });
  840. expect(getItemSale1Line(removeCouponCode!.lines).discounts.length).toBe(0);
  841. expect(removeCouponCode!.total).toBe(2200);
  842. expect(removeCouponCode!.totalWithTax).toBe(2640);
  843. const { activeOrder } = await shopClient.query<CodegenShop.GetActiveOrderQuery>(
  844. GET_ACTIVE_ORDER,
  845. );
  846. expect(getItemSale1Line(activeOrder!.lines).discounts.length).toBe(0);
  847. expect(activeOrder!.total).toBe(2200);
  848. expect(activeOrder!.totalWithTax).toBe(2640);
  849. });
  850. it('prices include tax', async () => {
  851. shopClient.setChannelToken(TAX_INCLUDED_CHANNEL_TOKEN);
  852. await shopClient.query<
  853. CodegenShop.AddItemToOrderMutation,
  854. CodegenShop.AddItemToOrderMutationVariables
  855. >(ADD_ITEM_TO_ORDER, {
  856. productVariantId: getVariantBySlug('item-1000').id,
  857. quantity: 1,
  858. });
  859. await shopClient.query<
  860. CodegenShop.AddItemToOrderMutation,
  861. CodegenShop.AddItemToOrderMutationVariables
  862. >(ADD_ITEM_TO_ORDER, {
  863. productVariantId: getVariantBySlug('item-sale-1000').id,
  864. quantity: 1,
  865. });
  866. const { addItemToOrder } = await shopClient.query<
  867. CodegenShop.AddItemToOrderMutation,
  868. CodegenShop.AddItemToOrderMutationVariables
  869. >(ADD_ITEM_TO_ORDER, {
  870. productVariantId: getVariantBySlug('item-sale-100').id,
  871. quantity: 2,
  872. });
  873. orderResultGuard.assertSuccess(addItemToOrder);
  874. expect(addItemToOrder.discounts.length).toBe(0);
  875. expect(getItemSale1Line(addItemToOrder.lines).discounts.length).toBe(0);
  876. expect(addItemToOrder.total).toBe(2200);
  877. expect(addItemToOrder.totalWithTax).toBe(2640);
  878. const { applyCouponCode } = await shopClient.query<
  879. CodegenShop.ApplyCouponCodeMutation,
  880. CodegenShop.ApplyCouponCodeMutationVariables
  881. >(APPLY_COUPON_CODE, {
  882. couponCode,
  883. });
  884. orderResultGuard.assertSuccess(applyCouponCode);
  885. expect(applyCouponCode.total).toBe(1600);
  886. expect(applyCouponCode.totalWithTax).toBe(1920);
  887. expect(getItemSale1Line(applyCouponCode.lines).discounts.length).toBe(1); // 1x promotion
  888. const { removeCouponCode } = await shopClient.query<
  889. CodegenShop.RemoveCouponCodeMutation,
  890. CodegenShop.RemoveCouponCodeMutationVariables
  891. >(REMOVE_COUPON_CODE, {
  892. couponCode,
  893. });
  894. expect(getItemSale1Line(removeCouponCode!.lines).discounts.length).toBe(0);
  895. expect(removeCouponCode!.total).toBe(2200);
  896. expect(removeCouponCode!.totalWithTax).toBe(2640);
  897. const { activeOrder } = await shopClient.query<CodegenShop.GetActiveOrderQuery>(
  898. GET_ACTIVE_ORDER,
  899. );
  900. expect(getItemSale1Line(activeOrder!.lines).discounts.length).toBe(0);
  901. expect(activeOrder!.total).toBe(2200);
  902. expect(activeOrder!.totalWithTax).toBe(2640);
  903. });
  904. });
  905. describe('productsPercentageDiscount', () => {
  906. const couponCode = '50%_off_product';
  907. let promotion: Codegen.PromotionFragment;
  908. beforeAll(async () => {
  909. promotion = await createPromotion({
  910. enabled: true,
  911. name: '50% off product',
  912. couponCode,
  913. conditions: [],
  914. actions: [
  915. {
  916. code: productsPercentageDiscount.code,
  917. arguments: [
  918. { name: 'discount', value: '50' },
  919. {
  920. name: 'productVariantIds',
  921. value: `["${getVariantBySlug('item-5000').id}"]`,
  922. },
  923. ],
  924. },
  925. ],
  926. });
  927. await assignPromotionToTaxIncludedChannel(promotion.id);
  928. });
  929. afterAll(async () => {
  930. await deletePromotion(promotion.id);
  931. shopClient.setChannelToken(E2E_DEFAULT_CHANNEL_TOKEN);
  932. });
  933. it('prices exclude tax', async () => {
  934. const { addItemToOrder } = await shopClient.query<
  935. CodegenShop.AddItemToOrderMutation,
  936. CodegenShop.AddItemToOrderMutationVariables
  937. >(ADD_ITEM_TO_ORDER, {
  938. productVariantId: getVariantBySlug('item-5000').id,
  939. quantity: 1,
  940. });
  941. orderResultGuard.assertSuccess(addItemToOrder);
  942. expect(addItemToOrder.discounts.length).toBe(0);
  943. expect(addItemToOrder.lines[0].discounts.length).toBe(0);
  944. expect(addItemToOrder.total).toBe(5000);
  945. expect(addItemToOrder.totalWithTax).toBe(6000);
  946. const { applyCouponCode } = await shopClient.query<
  947. CodegenShop.ApplyCouponCodeMutation,
  948. CodegenShop.ApplyCouponCodeMutationVariables
  949. >(APPLY_COUPON_CODE, {
  950. couponCode,
  951. });
  952. orderResultGuard.assertSuccess(applyCouponCode);
  953. expect(applyCouponCode.total).toBe(2500);
  954. expect(applyCouponCode.totalWithTax).toBe(3000);
  955. expect(applyCouponCode.lines[0].discounts.length).toBe(1); // 1x promotion
  956. });
  957. it('prices include tax', async () => {
  958. shopClient.setChannelToken(TAX_INCLUDED_CHANNEL_TOKEN);
  959. const { addItemToOrder } = await shopClient.query<
  960. CodegenShop.AddItemToOrderMutation,
  961. CodegenShop.AddItemToOrderMutationVariables
  962. >(ADD_ITEM_TO_ORDER, {
  963. productVariantId: getVariantBySlug('item-5000').id,
  964. quantity: 1,
  965. });
  966. orderResultGuard.assertSuccess(addItemToOrder);
  967. expect(addItemToOrder.discounts.length).toBe(0);
  968. expect(addItemToOrder.lines[0].discounts.length).toBe(0);
  969. expect(addItemToOrder.total).toBe(5000);
  970. expect(addItemToOrder.totalWithTax).toBe(6000);
  971. const { applyCouponCode } = await shopClient.query<
  972. CodegenShop.ApplyCouponCodeMutation,
  973. CodegenShop.ApplyCouponCodeMutationVariables
  974. >(APPLY_COUPON_CODE, {
  975. couponCode,
  976. });
  977. orderResultGuard.assertSuccess(applyCouponCode);
  978. expect(applyCouponCode.total).toBe(2500);
  979. expect(applyCouponCode.totalWithTax).toBe(3000);
  980. expect(applyCouponCode.lines[0].discounts.length).toBe(1); // 1x promotion
  981. });
  982. });
  983. describe('freeShipping', () => {
  984. const couponCode = 'FREE_SHIPPING';
  985. let promotion: Codegen.PromotionFragment;
  986. // The test shipping method needs to be created in each Channel, since ShippingMethods
  987. // are ChannelAware
  988. async function createTestShippingMethod(channelToken: string) {
  989. adminClient.setChannelToken(channelToken);
  990. const result = await adminClient.query<
  991. Codegen.CreateShippingMethodMutation,
  992. Codegen.CreateShippingMethodMutationVariables
  993. >(CREATE_SHIPPING_METHOD, {
  994. input: {
  995. code: 'test-method',
  996. fulfillmentHandler: manualFulfillmentHandler.code,
  997. checker: {
  998. code: defaultShippingEligibilityChecker.code,
  999. arguments: [
  1000. {
  1001. name: 'orderMinimum',
  1002. value: '0',
  1003. },
  1004. ],
  1005. },
  1006. calculator: {
  1007. code: defaultShippingCalculator.code,
  1008. arguments: [
  1009. { name: 'rate', value: '345' },
  1010. { name: 'includesTax', value: 'auto' },
  1011. { name: 'taxRate', value: '20' },
  1012. ],
  1013. },
  1014. translations: [
  1015. { languageCode: LanguageCode.en, name: 'test method', description: '' },
  1016. ],
  1017. },
  1018. });
  1019. adminClient.setChannelToken(E2E_DEFAULT_CHANNEL_TOKEN);
  1020. return result.createShippingMethod;
  1021. }
  1022. beforeAll(async () => {
  1023. promotion = await createPromotion({
  1024. enabled: true,
  1025. name: 'Free shipping',
  1026. couponCode,
  1027. conditions: [],
  1028. actions: [
  1029. {
  1030. code: freeShipping.code,
  1031. arguments: [],
  1032. },
  1033. ],
  1034. });
  1035. await assignPromotionToTaxIncludedChannel(promotion.id);
  1036. });
  1037. afterAll(async () => {
  1038. await deletePromotion(promotion.id);
  1039. shopClient.setChannelToken(E2E_DEFAULT_CHANNEL_TOKEN);
  1040. });
  1041. it('prices exclude tax', async () => {
  1042. const { addItemToOrder } = await shopClient.query<
  1043. CodegenShop.AddItemToOrderMutation,
  1044. CodegenShop.AddItemToOrderMutationVariables
  1045. >(ADD_ITEM_TO_ORDER, {
  1046. productVariantId: getVariantBySlug('item-5000').id,
  1047. quantity: 1,
  1048. });
  1049. const method = await createTestShippingMethod(E2E_DEFAULT_CHANNEL_TOKEN);
  1050. const { setOrderShippingMethod } = await shopClient.query<
  1051. CodegenShop.SetShippingMethodMutation,
  1052. CodegenShop.SetShippingMethodMutationVariables
  1053. >(SET_SHIPPING_METHOD, {
  1054. id: method.id,
  1055. });
  1056. orderResultGuard.assertSuccess(setOrderShippingMethod);
  1057. expect(setOrderShippingMethod.discounts).toEqual([]);
  1058. expect(setOrderShippingMethod.shipping).toBe(345);
  1059. expect(setOrderShippingMethod.shippingWithTax).toBe(414);
  1060. expect(setOrderShippingMethod.total).toBe(5345);
  1061. expect(setOrderShippingMethod.totalWithTax).toBe(6414);
  1062. const { applyCouponCode } = await shopClient.query<
  1063. CodegenShop.ApplyCouponCodeMutation,
  1064. CodegenShop.ApplyCouponCodeMutationVariables
  1065. >(APPLY_COUPON_CODE, {
  1066. couponCode,
  1067. });
  1068. orderResultGuard.assertSuccess(applyCouponCode);
  1069. expect(applyCouponCode.discounts.length).toBe(1);
  1070. expect(applyCouponCode.discounts[0].description).toBe('Free shipping');
  1071. expect(applyCouponCode.shipping).toBe(0);
  1072. expect(applyCouponCode.shippingWithTax).toBe(0);
  1073. expect(applyCouponCode.total).toBe(5000);
  1074. expect(applyCouponCode.totalWithTax).toBe(6000);
  1075. });
  1076. it('prices include tax', async () => {
  1077. shopClient.setChannelToken(TAX_INCLUDED_CHANNEL_TOKEN);
  1078. const { addItemToOrder } = await shopClient.query<
  1079. CodegenShop.AddItemToOrderMutation,
  1080. CodegenShop.AddItemToOrderMutationVariables
  1081. >(ADD_ITEM_TO_ORDER, {
  1082. productVariantId: getVariantBySlug('item-5000').id,
  1083. quantity: 1,
  1084. });
  1085. const method = await createTestShippingMethod(TAX_INCLUDED_CHANNEL_TOKEN);
  1086. const { setOrderShippingMethod } = await shopClient.query<
  1087. CodegenShop.SetShippingMethodMutation,
  1088. CodegenShop.SetShippingMethodMutationVariables
  1089. >(SET_SHIPPING_METHOD, {
  1090. id: method.id,
  1091. });
  1092. orderResultGuard.assertSuccess(setOrderShippingMethod);
  1093. expect(setOrderShippingMethod.discounts).toEqual([]);
  1094. expect(setOrderShippingMethod.shipping).toBe(288);
  1095. expect(setOrderShippingMethod.shippingWithTax).toBe(345);
  1096. expect(setOrderShippingMethod.total).toBe(5288);
  1097. expect(setOrderShippingMethod.totalWithTax).toBe(6345);
  1098. const { applyCouponCode } = await shopClient.query<
  1099. CodegenShop.ApplyCouponCodeMutation,
  1100. CodegenShop.ApplyCouponCodeMutationVariables
  1101. >(APPLY_COUPON_CODE, {
  1102. couponCode,
  1103. });
  1104. orderResultGuard.assertSuccess(applyCouponCode);
  1105. expect(applyCouponCode.discounts.length).toBe(1);
  1106. expect(applyCouponCode.discounts[0].description).toBe('Free shipping');
  1107. expect(applyCouponCode.shipping).toBe(0);
  1108. expect(applyCouponCode.shippingWithTax).toBe(0);
  1109. expect(applyCouponCode.total).toBe(5000);
  1110. expect(applyCouponCode.totalWithTax).toBe(6000);
  1111. });
  1112. // https://github.com/vendure-ecommerce/vendure/pull/1150
  1113. it('shipping discounts get correctly removed', async () => {
  1114. shopClient.setChannelToken(TAX_INCLUDED_CHANNEL_TOKEN);
  1115. const { addItemToOrder } = await shopClient.query<
  1116. CodegenShop.AddItemToOrderMutation,
  1117. CodegenShop.AddItemToOrderMutationVariables
  1118. >(ADD_ITEM_TO_ORDER, {
  1119. productVariantId: getVariantBySlug('item-5000').id,
  1120. quantity: 1,
  1121. });
  1122. const method = await createTestShippingMethod(TAX_INCLUDED_CHANNEL_TOKEN);
  1123. const { setOrderShippingMethod } = await shopClient.query<
  1124. CodegenShop.SetShippingMethodMutation,
  1125. CodegenShop.SetShippingMethodMutationVariables
  1126. >(SET_SHIPPING_METHOD, {
  1127. id: method.id,
  1128. });
  1129. orderResultGuard.assertSuccess(setOrderShippingMethod);
  1130. expect(setOrderShippingMethod.discounts).toEqual([]);
  1131. expect(setOrderShippingMethod.shippingWithTax).toBe(345);
  1132. const { applyCouponCode } = await shopClient.query<
  1133. CodegenShop.ApplyCouponCodeMutation,
  1134. CodegenShop.ApplyCouponCodeMutationVariables
  1135. >(APPLY_COUPON_CODE, {
  1136. couponCode,
  1137. });
  1138. orderResultGuard.assertSuccess(applyCouponCode);
  1139. expect(applyCouponCode.discounts.length).toBe(1);
  1140. expect(applyCouponCode.discounts[0].description).toBe('Free shipping');
  1141. expect(applyCouponCode.shippingWithTax).toBe(0);
  1142. const { removeCouponCode } = await shopClient.query<
  1143. CodegenShop.RemoveCouponCodeMutation,
  1144. CodegenShop.RemoveCouponCodeMutationVariables
  1145. >(REMOVE_COUPON_CODE, {
  1146. couponCode,
  1147. });
  1148. orderResultGuard.assertSuccess(removeCouponCode);
  1149. expect(removeCouponCode.discounts).toEqual([]);
  1150. expect(removeCouponCode.shippingWithTax).toBe(345);
  1151. });
  1152. });
  1153. describe('multiple promotions simultaneously', () => {
  1154. const saleItem50pcOffCoupon = 'CODE1';
  1155. const order15pcOffCoupon = 'CODE2';
  1156. let promotion1: Codegen.PromotionFragment;
  1157. let promotion2: Codegen.PromotionFragment;
  1158. beforeAll(async () => {
  1159. const { facets } = await adminClient.query<Codegen.GetFacetListQuery>(GET_FACET_LIST);
  1160. const saleFacetValue = facets.items[0].values[0];
  1161. promotion1 = await createPromotion({
  1162. enabled: true,
  1163. name: 'item promo',
  1164. couponCode: saleItem50pcOffCoupon,
  1165. conditions: [],
  1166. actions: [
  1167. {
  1168. code: discountOnItemWithFacets.code,
  1169. arguments: [
  1170. { name: 'discount', value: '50' },
  1171. { name: 'facets', value: `["${saleFacetValue.id}"]` },
  1172. ],
  1173. },
  1174. ],
  1175. });
  1176. promotion2 = await createPromotion({
  1177. enabled: true,
  1178. name: 'order promo',
  1179. couponCode: order15pcOffCoupon,
  1180. conditions: [],
  1181. actions: [
  1182. {
  1183. code: orderPercentageDiscount.code,
  1184. arguments: [{ name: 'discount', value: '15' }],
  1185. },
  1186. ],
  1187. });
  1188. await assignPromotionToTaxIncludedChannel([promotion1.id, promotion2.id]);
  1189. });
  1190. afterAll(async () => {
  1191. await deletePromotion(promotion1.id);
  1192. await deletePromotion(promotion2.id);
  1193. shopClient.setChannelToken(E2E_DEFAULT_CHANNEL_TOKEN);
  1194. });
  1195. it('prices exclude tax', async () => {
  1196. await shopClient.query<
  1197. CodegenShop.AddItemToOrderMutation,
  1198. CodegenShop.AddItemToOrderMutationVariables
  1199. >(ADD_ITEM_TO_ORDER, {
  1200. productVariantId: getVariantBySlug('item-sale-1000').id,
  1201. quantity: 2,
  1202. });
  1203. await shopClient.query<
  1204. CodegenShop.AddItemToOrderMutation,
  1205. CodegenShop.AddItemToOrderMutationVariables
  1206. >(ADD_ITEM_TO_ORDER, {
  1207. productVariantId: getVariantBySlug('item-5000').id,
  1208. quantity: 1,
  1209. });
  1210. // Apply the OrderItem-level promo
  1211. const { applyCouponCode: apply1 } = await shopClient.query<
  1212. CodegenShop.ApplyCouponCodeMutation,
  1213. CodegenShop.ApplyCouponCodeMutationVariables
  1214. >(APPLY_COUPON_CODE, {
  1215. couponCode: saleItem50pcOffCoupon,
  1216. });
  1217. orderResultGuard.assertSuccess(apply1);
  1218. const saleItemLine = apply1.lines.find(
  1219. l => l.productVariant.id === getVariantBySlug('item-sale-1000').id,
  1220. )!;
  1221. expect(saleItemLine.discounts.length).toBe(1); // 1x promotion
  1222. expect(
  1223. saleItemLine.discounts.find(a => a.type === AdjustmentType.PROMOTION)?.description,
  1224. ).toBe('item promo');
  1225. expect(apply1.discounts.length).toBe(1);
  1226. expect(apply1.total).toBe(6000);
  1227. expect(apply1.totalWithTax).toBe(7200);
  1228. // Apply the Order-level promo
  1229. const { applyCouponCode: apply2 } = await shopClient.query<
  1230. CodegenShop.ApplyCouponCodeMutation,
  1231. CodegenShop.ApplyCouponCodeMutationVariables
  1232. >(APPLY_COUPON_CODE, {
  1233. couponCode: order15pcOffCoupon,
  1234. });
  1235. orderResultGuard.assertSuccess(apply2);
  1236. expect(apply2.discounts.map(d => d.description).sort()).toEqual([
  1237. 'item promo',
  1238. 'order promo',
  1239. ]);
  1240. expect(apply2.total).toBe(5100);
  1241. expect(apply2.totalWithTax).toBe(6120);
  1242. });
  1243. it('prices include tax', async () => {
  1244. shopClient.setChannelToken(TAX_INCLUDED_CHANNEL_TOKEN);
  1245. await shopClient.query<
  1246. CodegenShop.AddItemToOrderMutation,
  1247. CodegenShop.AddItemToOrderMutationVariables
  1248. >(ADD_ITEM_TO_ORDER, {
  1249. productVariantId: getVariantBySlug('item-sale-1000').id,
  1250. quantity: 2,
  1251. });
  1252. await shopClient.query<
  1253. CodegenShop.AddItemToOrderMutation,
  1254. CodegenShop.AddItemToOrderMutationVariables
  1255. >(ADD_ITEM_TO_ORDER, {
  1256. productVariantId: getVariantBySlug('item-5000').id,
  1257. quantity: 1,
  1258. });
  1259. // Apply the OrderItem-level promo
  1260. const { applyCouponCode: apply1 } = await shopClient.query<
  1261. CodegenShop.ApplyCouponCodeMutation,
  1262. CodegenShop.ApplyCouponCodeMutationVariables
  1263. >(APPLY_COUPON_CODE, {
  1264. couponCode: saleItem50pcOffCoupon,
  1265. });
  1266. orderResultGuard.assertSuccess(apply1);
  1267. const saleItemLine = apply1.lines.find(
  1268. l => l.productVariant.id === getVariantBySlug('item-sale-1000').id,
  1269. )!;
  1270. expect(saleItemLine.discounts.length).toBe(1); // 1x promotion
  1271. expect(
  1272. saleItemLine.discounts.find(a => a.type === AdjustmentType.PROMOTION)?.description,
  1273. ).toBe('item promo');
  1274. expect(apply1.discounts.length).toBe(1);
  1275. expect(apply1.total).toBe(6000);
  1276. expect(apply1.totalWithTax).toBe(7200);
  1277. // Apply the Order-level promo
  1278. const { applyCouponCode: apply2 } = await shopClient.query<
  1279. CodegenShop.ApplyCouponCodeMutation,
  1280. CodegenShop.ApplyCouponCodeMutationVariables
  1281. >(APPLY_COUPON_CODE, {
  1282. couponCode: order15pcOffCoupon,
  1283. });
  1284. orderResultGuard.assertSuccess(apply2);
  1285. expect(apply2.discounts.map(d => d.description).sort()).toEqual([
  1286. 'item promo',
  1287. 'order promo',
  1288. ]);
  1289. expect(apply2.total).toBe(5100);
  1290. expect(apply2.totalWithTax).toBe(6120);
  1291. });
  1292. });
  1293. });
  1294. describe('per-customer usage limit', () => {
  1295. const TEST_COUPON_CODE = 'TESTCOUPON';
  1296. const orderGuard: ErrorResultGuard<CodegenShop.TestOrderWithPaymentsFragment> =
  1297. createErrorResultGuard(input => !!input.lines);
  1298. let promoWithUsageLimit: Codegen.PromotionFragment;
  1299. beforeAll(async () => {
  1300. promoWithUsageLimit = await createPromotion({
  1301. enabled: true,
  1302. name: 'Free with test coupon',
  1303. couponCode: TEST_COUPON_CODE,
  1304. perCustomerUsageLimit: 1,
  1305. conditions: [],
  1306. actions: [freeOrderAction],
  1307. });
  1308. });
  1309. afterAll(async () => {
  1310. await deletePromotion(promoWithUsageLimit.id);
  1311. });
  1312. async function createNewActiveOrder() {
  1313. const { addItemToOrder } = await shopClient.query<
  1314. CodegenShop.AddItemToOrderMutation,
  1315. CodegenShop.AddItemToOrderMutationVariables
  1316. >(ADD_ITEM_TO_ORDER, {
  1317. productVariantId: getVariantBySlug('item-5000').id,
  1318. quantity: 1,
  1319. });
  1320. return addItemToOrder;
  1321. }
  1322. describe('guest customer', () => {
  1323. const GUEST_EMAIL_ADDRESS = 'guest@test.com';
  1324. let orderCode: string;
  1325. function addGuestCustomerToOrder() {
  1326. return shopClient.query<
  1327. CodegenShop.SetCustomerForOrderMutation,
  1328. CodegenShop.SetCustomerForOrderMutationVariables
  1329. >(SET_CUSTOMER, {
  1330. input: {
  1331. emailAddress: GUEST_EMAIL_ADDRESS,
  1332. firstName: 'Guest',
  1333. lastName: 'Customer',
  1334. },
  1335. });
  1336. }
  1337. it('allows initial usage', async () => {
  1338. await shopClient.asAnonymousUser();
  1339. await createNewActiveOrder();
  1340. await addGuestCustomerToOrder();
  1341. const { applyCouponCode } = await shopClient.query<
  1342. CodegenShop.ApplyCouponCodeMutation,
  1343. CodegenShop.ApplyCouponCodeMutationVariables
  1344. >(APPLY_COUPON_CODE, { couponCode: TEST_COUPON_CODE });
  1345. orderResultGuard.assertSuccess(applyCouponCode);
  1346. expect(applyCouponCode.totalWithTax).toBe(0);
  1347. expect(applyCouponCode.couponCodes).toEqual([TEST_COUPON_CODE]);
  1348. await proceedToArrangingPayment(shopClient);
  1349. const order = await addPaymentToOrder(shopClient, testSuccessfulPaymentMethod);
  1350. orderGuard.assertSuccess(order);
  1351. expect(order.state).toBe('PaymentSettled');
  1352. expect(order.active).toBe(false);
  1353. orderCode = order.code;
  1354. });
  1355. it('adds Promotions to Order once payment arranged', async () => {
  1356. const { orderByCode } = await shopClient.query<
  1357. CodegenShop.GetOrderPromotionsByCodeQuery,
  1358. CodegenShop.GetOrderPromotionsByCodeQueryVariables
  1359. >(GET_ORDER_PROMOTIONS_BY_CODE, {
  1360. code: orderCode,
  1361. });
  1362. expect(orderByCode!.promotions.map(pick(['name']))).toEqual([
  1363. { name: 'Free with test coupon' },
  1364. ]);
  1365. });
  1366. it('returns error result when usage exceeds limit', async () => {
  1367. await shopClient.asAnonymousUser();
  1368. await createNewActiveOrder();
  1369. await addGuestCustomerToOrder();
  1370. const { applyCouponCode } = await shopClient.query<
  1371. CodegenShop.ApplyCouponCodeMutation,
  1372. CodegenShop.ApplyCouponCodeMutationVariables
  1373. >(APPLY_COUPON_CODE, { couponCode: TEST_COUPON_CODE });
  1374. orderResultGuard.assertErrorResult(applyCouponCode);
  1375. expect(applyCouponCode.message).toEqual(
  1376. 'Coupon code cannot be used more than once per customer',
  1377. );
  1378. });
  1379. it('removes couponCode from order when adding customer after code applied', async () => {
  1380. await shopClient.asAnonymousUser();
  1381. await createNewActiveOrder();
  1382. const { applyCouponCode } = await shopClient.query<
  1383. CodegenShop.ApplyCouponCodeMutation,
  1384. CodegenShop.ApplyCouponCodeMutationVariables
  1385. >(APPLY_COUPON_CODE, { couponCode: TEST_COUPON_CODE });
  1386. orderResultGuard.assertSuccess(applyCouponCode);
  1387. expect(applyCouponCode.totalWithTax).toBe(0);
  1388. expect(applyCouponCode.couponCodes).toEqual([TEST_COUPON_CODE]);
  1389. await addGuestCustomerToOrder();
  1390. const { activeOrder } = await shopClient.query<CodegenShop.GetActiveOrderQuery>(
  1391. GET_ACTIVE_ORDER,
  1392. );
  1393. expect(activeOrder!.couponCodes).toEqual([]);
  1394. expect(activeOrder!.totalWithTax).toBe(6000);
  1395. });
  1396. it('does not remove valid couponCode when setting guest customer', async () => {
  1397. await shopClient.asAnonymousUser();
  1398. await createNewActiveOrder();
  1399. const { applyCouponCode } = await shopClient.query<
  1400. ApplyCouponCode.Mutation,
  1401. ApplyCouponCode.Variables
  1402. >(APPLY_COUPON_CODE, { couponCode: TEST_COUPON_CODE });
  1403. orderResultGuard.assertSuccess(applyCouponCode);
  1404. expect(applyCouponCode.totalWithTax).toBe(0);
  1405. expect(applyCouponCode.couponCodes).toEqual([TEST_COUPON_CODE]);
  1406. await shopClient.query<SetCustomerForOrder.Mutation, SetCustomerForOrder.Variables>(
  1407. SET_CUSTOMER,
  1408. {
  1409. input: {
  1410. emailAddress: 'new-guest@test.com',
  1411. firstName: 'New Guest',
  1412. lastName: 'Customer',
  1413. },
  1414. },
  1415. );
  1416. const { activeOrder } = await shopClient.query<GetActiveOrder.Query>(GET_ACTIVE_ORDER);
  1417. expect(activeOrder.couponCodes).toEqual([TEST_COUPON_CODE]);
  1418. expect(applyCouponCode.totalWithTax).toBe(0);
  1419. });
  1420. });
  1421. describe('signed-in customer', () => {
  1422. function logInAsRegisteredCustomer() {
  1423. return shopClient.asUserWithCredentials('hayden.zieme12@hotmail.com', 'test');
  1424. }
  1425. let orderId: string;
  1426. it('allows initial usage', async () => {
  1427. await logInAsRegisteredCustomer();
  1428. await createNewActiveOrder();
  1429. const { applyCouponCode } = await shopClient.query<
  1430. CodegenShop.ApplyCouponCodeMutation,
  1431. CodegenShop.ApplyCouponCodeMutationVariables
  1432. >(APPLY_COUPON_CODE, { couponCode: TEST_COUPON_CODE });
  1433. orderResultGuard.assertSuccess(applyCouponCode);
  1434. expect(applyCouponCode.totalWithTax).toBe(0);
  1435. expect(applyCouponCode.couponCodes).toEqual([TEST_COUPON_CODE]);
  1436. await proceedToArrangingPayment(shopClient);
  1437. const order = await addPaymentToOrder(shopClient, testSuccessfulPaymentMethod);
  1438. orderGuard.assertSuccess(order);
  1439. orderId = order.id;
  1440. expect(order.state).toBe('PaymentSettled');
  1441. expect(order.active).toBe(false);
  1442. });
  1443. it('returns error result when usage exceeds limit', async () => {
  1444. await logInAsRegisteredCustomer();
  1445. await createNewActiveOrder();
  1446. const { applyCouponCode } = await shopClient.query<
  1447. CodegenShop.ApplyCouponCodeMutation,
  1448. CodegenShop.ApplyCouponCodeMutationVariables
  1449. >(APPLY_COUPON_CODE, { couponCode: TEST_COUPON_CODE });
  1450. orderResultGuard.assertErrorResult(applyCouponCode);
  1451. expect(applyCouponCode.message).toEqual(
  1452. 'Coupon code cannot be used more than once per customer',
  1453. );
  1454. expect(applyCouponCode.errorCode).toBe(ErrorCode.COUPON_CODE_LIMIT_ERROR);
  1455. });
  1456. it('removes couponCode from order when logging in after code applied', async () => {
  1457. await shopClient.asAnonymousUser();
  1458. await createNewActiveOrder();
  1459. const { applyCouponCode } = await shopClient.query<
  1460. CodegenShop.ApplyCouponCodeMutation,
  1461. CodegenShop.ApplyCouponCodeMutationVariables
  1462. >(APPLY_COUPON_CODE, { couponCode: TEST_COUPON_CODE });
  1463. orderResultGuard.assertSuccess(applyCouponCode);
  1464. expect(applyCouponCode.couponCodes).toEqual([TEST_COUPON_CODE]);
  1465. expect(applyCouponCode.totalWithTax).toBe(0);
  1466. await logInAsRegisteredCustomer();
  1467. const { activeOrder } = await shopClient.query<CodegenShop.GetActiveOrderQuery>(
  1468. GET_ACTIVE_ORDER,
  1469. );
  1470. expect(activeOrder!.totalWithTax).toBe(6000);
  1471. expect(activeOrder!.couponCodes).toEqual([]);
  1472. });
  1473. // https://github.com/vendure-ecommerce/vendure/issues/1466
  1474. it('cancelled orders do not count against usage limit', async () => {
  1475. const { cancelOrder } = await adminClient.query<
  1476. Codegen.CancelOrderMutation,
  1477. Codegen.CancelOrderMutationVariables
  1478. >(CANCEL_ORDER, {
  1479. input: {
  1480. orderId,
  1481. cancelShipping: true,
  1482. reason: 'request',
  1483. },
  1484. });
  1485. orderResultGuard.assertSuccess(cancelOrder);
  1486. expect(cancelOrder.state).toBe('Cancelled');
  1487. await logInAsRegisteredCustomer();
  1488. await createNewActiveOrder();
  1489. const { applyCouponCode } = await shopClient.query<
  1490. CodegenShop.ApplyCouponCodeMutation,
  1491. CodegenShop.ApplyCouponCodeMutationVariables
  1492. >(APPLY_COUPON_CODE, { couponCode: TEST_COUPON_CODE });
  1493. orderResultGuard.assertSuccess(applyCouponCode);
  1494. expect(applyCouponCode.totalWithTax).toBe(0);
  1495. expect(applyCouponCode.couponCodes).toEqual([TEST_COUPON_CODE]);
  1496. });
  1497. });
  1498. });
  1499. describe('usage limit', () => {
  1500. const TEST_COUPON_CODE = 'TESTCOUPON';
  1501. const orderGuard: ErrorResultGuard<CodegenShop.TestOrderWithPaymentsFragment> =
  1502. createErrorResultGuard(input => !!input.lines);
  1503. let promoWithUsageLimit: Codegen.PromotionFragment;
  1504. async function createNewActiveOrder() {
  1505. const { addItemToOrder } = await shopClient.query<
  1506. CodegenShop.AddItemToOrderMutation,
  1507. CodegenShop.AddItemToOrderMutationVariables
  1508. >(ADD_ITEM_TO_ORDER, {
  1509. productVariantId: getVariantBySlug('item-5000').id,
  1510. quantity: 1,
  1511. });
  1512. return addItemToOrder;
  1513. }
  1514. describe('guest customer', () => {
  1515. const GUEST_EMAIL_ADDRESS = 'guest@test.com';
  1516. let orderCode: string;
  1517. beforeAll(async () => {
  1518. promoWithUsageLimit = await createPromotion({
  1519. enabled: true,
  1520. name: 'Free with test coupon',
  1521. couponCode: TEST_COUPON_CODE,
  1522. usageLimit: 1,
  1523. conditions: [],
  1524. actions: [freeOrderAction],
  1525. });
  1526. });
  1527. afterAll(async () => {
  1528. await deletePromotion(promoWithUsageLimit.id);
  1529. });
  1530. function addGuestCustomerToOrder() {
  1531. return shopClient.query<
  1532. CodegenShop.SetCustomerForOrderMutation,
  1533. CodegenShop.SetCustomerForOrderMutationVariables
  1534. >(SET_CUSTOMER, {
  1535. input: {
  1536. emailAddress: GUEST_EMAIL_ADDRESS,
  1537. firstName: 'Guest',
  1538. lastName: 'Customer',
  1539. },
  1540. });
  1541. }
  1542. it('allows initial usage', async () => {
  1543. await shopClient.asAnonymousUser();
  1544. await createNewActiveOrder();
  1545. await addGuestCustomerToOrder();
  1546. const { applyCouponCode } = await shopClient.query<
  1547. CodegenShop.ApplyCouponCodeMutation,
  1548. CodegenShop.ApplyCouponCodeMutationVariables
  1549. >(APPLY_COUPON_CODE, { couponCode: TEST_COUPON_CODE });
  1550. orderResultGuard.assertSuccess(applyCouponCode);
  1551. expect(applyCouponCode.totalWithTax).toBe(0);
  1552. expect(applyCouponCode.couponCodes).toEqual([TEST_COUPON_CODE]);
  1553. await proceedToArrangingPayment(shopClient);
  1554. const order = await addPaymentToOrder(shopClient, testSuccessfulPaymentMethod);
  1555. orderGuard.assertSuccess(order);
  1556. expect(order.state).toBe('PaymentSettled');
  1557. expect(order.active).toBe(false);
  1558. orderCode = order.code;
  1559. });
  1560. it('adds Promotions to Order once payment arranged', async () => {
  1561. const { orderByCode } = await shopClient.query<
  1562. CodegenShop.GetOrderPromotionsByCodeQuery,
  1563. CodegenShop.GetOrderPromotionsByCodeQueryVariables
  1564. >(GET_ORDER_PROMOTIONS_BY_CODE, {
  1565. code: orderCode,
  1566. });
  1567. expect(orderByCode!.promotions.map(pick(['name']))).toEqual([
  1568. { name: 'Free with test coupon' },
  1569. ]);
  1570. });
  1571. it('returns error result when usage exceeds limit', async () => {
  1572. await shopClient.asAnonymousUser();
  1573. await createNewActiveOrder();
  1574. await addGuestCustomerToOrder();
  1575. const { applyCouponCode } = await shopClient.query<
  1576. CodegenShop.ApplyCouponCodeMutation,
  1577. CodegenShop.ApplyCouponCodeMutationVariables
  1578. >(APPLY_COUPON_CODE, { couponCode: TEST_COUPON_CODE });
  1579. orderResultGuard.assertErrorResult(applyCouponCode);
  1580. expect(applyCouponCode.message).toEqual(
  1581. 'Coupon code cannot be used more than once per customer',
  1582. );
  1583. });
  1584. });
  1585. describe('signed-in customer', () => {
  1586. beforeAll(async () => {
  1587. promoWithUsageLimit = await createPromotion({
  1588. enabled: true,
  1589. name: 'Free with test coupon',
  1590. couponCode: TEST_COUPON_CODE,
  1591. usageLimit: 1,
  1592. conditions: [],
  1593. actions: [freeOrderAction],
  1594. });
  1595. });
  1596. afterAll(async () => {
  1597. await deletePromotion(promoWithUsageLimit.id);
  1598. });
  1599. function logInAsRegisteredCustomer() {
  1600. return shopClient.asUserWithCredentials('hayden.zieme12@hotmail.com', 'test');
  1601. }
  1602. let orderId: string;
  1603. it('allows initial usage', async () => {
  1604. await logInAsRegisteredCustomer();
  1605. await createNewActiveOrder();
  1606. const { applyCouponCode } = await shopClient.query<
  1607. CodegenShop.ApplyCouponCodeMutation,
  1608. CodegenShop.ApplyCouponCodeMutationVariables
  1609. >(APPLY_COUPON_CODE, { couponCode: TEST_COUPON_CODE });
  1610. orderResultGuard.assertSuccess(applyCouponCode);
  1611. expect(applyCouponCode.totalWithTax).toBe(0);
  1612. expect(applyCouponCode.couponCodes).toEqual([TEST_COUPON_CODE]);
  1613. await proceedToArrangingPayment(shopClient);
  1614. const order = await addPaymentToOrder(shopClient, testSuccessfulPaymentMethod);
  1615. orderGuard.assertSuccess(order);
  1616. orderId = order.id;
  1617. expect(order.state).toBe('PaymentSettled');
  1618. expect(order.active).toBe(false);
  1619. });
  1620. it('returns error result when usage exceeds limit', async () => {
  1621. await logInAsRegisteredCustomer();
  1622. await createNewActiveOrder();
  1623. const { applyCouponCode } = await shopClient.query<
  1624. CodegenShop.ApplyCouponCodeMutation,
  1625. CodegenShop.ApplyCouponCodeMutationVariables
  1626. >(APPLY_COUPON_CODE, { couponCode: TEST_COUPON_CODE });
  1627. orderResultGuard.assertErrorResult(applyCouponCode);
  1628. expect(applyCouponCode.message).toEqual(
  1629. 'Coupon code cannot be used more than once per customer',
  1630. );
  1631. expect(applyCouponCode.errorCode).toBe(ErrorCode.COUPON_CODE_LIMIT_ERROR);
  1632. });
  1633. // https://github.com/vendure-ecommerce/vendure/issues/1466
  1634. it('cancelled orders do not count against usage limit', async () => {
  1635. const { cancelOrder } = await adminClient.query<
  1636. Codegen.CancelOrderMutation,
  1637. Codegen.CancelOrderMutationVariables
  1638. >(CANCEL_ORDER, {
  1639. input: {
  1640. orderId,
  1641. cancelShipping: true,
  1642. reason: 'request',
  1643. },
  1644. });
  1645. orderResultGuard.assertSuccess(cancelOrder);
  1646. expect(cancelOrder.state).toBe('Cancelled');
  1647. await logInAsRegisteredCustomer();
  1648. await createNewActiveOrder();
  1649. const { applyCouponCode } = await shopClient.query<
  1650. CodegenShop.ApplyCouponCodeMutation,
  1651. CodegenShop.ApplyCouponCodeMutationVariables
  1652. >(APPLY_COUPON_CODE, { couponCode: TEST_COUPON_CODE });
  1653. orderResultGuard.assertSuccess(applyCouponCode);
  1654. expect(applyCouponCode.totalWithTax).toBe(0);
  1655. expect(applyCouponCode.couponCodes).toEqual([TEST_COUPON_CODE]);
  1656. });
  1657. });
  1658. });
  1659. // https://github.com/vendure-ecommerce/vendure/issues/710
  1660. it('removes order-level discount made invalid by removing OrderLine', async () => {
  1661. const promotion = await createPromotion({
  1662. enabled: true,
  1663. name: 'Test Promo',
  1664. conditions: [minOrderAmountCondition(10000)],
  1665. actions: [
  1666. {
  1667. code: orderFixedDiscount.code,
  1668. arguments: [{ name: 'discount', value: '1000' }],
  1669. },
  1670. ],
  1671. });
  1672. await shopClient.asAnonymousUser();
  1673. await shopClient.query<
  1674. CodegenShop.AddItemToOrderMutation,
  1675. CodegenShop.AddItemToOrderMutationVariables
  1676. >(ADD_ITEM_TO_ORDER, {
  1677. productVariantId: getVariantBySlug('item-1000').id,
  1678. quantity: 8,
  1679. });
  1680. const { addItemToOrder } = await shopClient.query<
  1681. CodegenShop.AddItemToOrderMutation,
  1682. CodegenShop.AddItemToOrderMutationVariables
  1683. >(ADD_ITEM_TO_ORDER, {
  1684. productVariantId: getVariantBySlug('item-5000').id,
  1685. quantity: 1,
  1686. });
  1687. orderResultGuard.assertSuccess(addItemToOrder);
  1688. expect(addItemToOrder.discounts.length).toBe(1);
  1689. expect(addItemToOrder.discounts[0].description).toBe('Test Promo');
  1690. const { activeOrder: check1 } = await shopClient.query<CodegenShop.GetActiveOrderQuery>(
  1691. GET_ACTIVE_ORDER,
  1692. );
  1693. expect(check1!.discounts.length).toBe(1);
  1694. expect(check1!.discounts[0].description).toBe('Test Promo');
  1695. const { removeOrderLine } = await shopClient.query<
  1696. CodegenShop.RemoveItemFromOrderMutation,
  1697. CodegenShop.RemoveItemFromOrderMutationVariables
  1698. >(REMOVE_ITEM_FROM_ORDER, {
  1699. orderLineId: addItemToOrder.lines[1].id,
  1700. });
  1701. orderResultGuard.assertSuccess(removeOrderLine);
  1702. expect(removeOrderLine.discounts.length).toBe(0);
  1703. const { activeOrder: check2 } = await shopClient.query<CodegenShop.GetActiveOrderQuery>(
  1704. GET_ACTIVE_ORDER,
  1705. );
  1706. expect(check2!.discounts.length).toBe(0);
  1707. });
  1708. // https://github.com/vendure-ecommerce/vendure/issues/1492
  1709. it('correctly handles pro-ration of variants with 0 price', async () => {
  1710. const couponCode = '20%_off_order';
  1711. const promotion = await createPromotion({
  1712. enabled: true,
  1713. name: '20% discount on order',
  1714. couponCode,
  1715. conditions: [],
  1716. actions: [
  1717. {
  1718. code: orderPercentageDiscount.code,
  1719. arguments: [{ name: 'discount', value: '20' }],
  1720. },
  1721. ],
  1722. });
  1723. await shopClient.asAnonymousUser();
  1724. await shopClient.query<
  1725. CodegenShop.AddItemToOrderMutation,
  1726. CodegenShop.AddItemToOrderMutationVariables
  1727. >(ADD_ITEM_TO_ORDER, {
  1728. productVariantId: getVariantBySlug('item-100').id,
  1729. quantity: 1,
  1730. });
  1731. await shopClient.query<
  1732. CodegenShop.AddItemToOrderMutation,
  1733. CodegenShop.AddItemToOrderMutationVariables
  1734. >(ADD_ITEM_TO_ORDER, {
  1735. productVariantId: getVariantBySlug('item-0').id,
  1736. quantity: 1,
  1737. });
  1738. const { applyCouponCode } = await shopClient.query<
  1739. CodegenShop.ApplyCouponCodeMutation,
  1740. CodegenShop.ApplyCouponCodeMutationVariables
  1741. >(APPLY_COUPON_CODE, { couponCode });
  1742. orderResultGuard.assertSuccess(applyCouponCode);
  1743. expect(applyCouponCode.totalWithTax).toBe(96);
  1744. });
  1745. // https://github.com/vendure-ecommerce/vendure/issues/2385
  1746. describe('prevents negative line price', () => {
  1747. const TAX_INCLUDED_CHANNEL_TOKEN_2 = 'tax_included_channel_2';
  1748. const couponCode1 = '100%_off';
  1749. const couponCode2 = '100%_off';
  1750. let taxIncludedChannel: Codegen.ChannelFragment;
  1751. beforeAll(async () => {
  1752. // Create a channel where the prices include tax, so we can ensure
  1753. // that PromotionActions are working as expected when taxes are included
  1754. const { createChannel } = await adminClient.query<
  1755. Codegen.CreateChannelMutation,
  1756. Codegen.CreateChannelMutationVariables
  1757. >(CREATE_CHANNEL, {
  1758. input: {
  1759. code: 'tax-included-channel-2',
  1760. currencyCode: CurrencyCode.GBP,
  1761. pricesIncludeTax: true,
  1762. defaultTaxZoneId: 'T_1',
  1763. defaultShippingZoneId: 'T_1',
  1764. defaultLanguageCode: LanguageCode.en,
  1765. token: TAX_INCLUDED_CHANNEL_TOKEN_2,
  1766. },
  1767. });
  1768. taxIncludedChannel = createChannel as Codegen.ChannelFragment;
  1769. await adminClient.query<
  1770. Codegen.AssignProductsToChannelMutation,
  1771. Codegen.AssignProductsToChannelMutationVariables
  1772. >(ASSIGN_PRODUCT_TO_CHANNEL, {
  1773. input: {
  1774. channelId: taxIncludedChannel.id,
  1775. priceFactor: 1,
  1776. productIds: products.map(p => p.id),
  1777. },
  1778. });
  1779. const item1000 = getVariantBySlug('item-1000')!;
  1780. const promo100 = await createPromotion({
  1781. enabled: true,
  1782. name: '100% discount ',
  1783. couponCode: couponCode1,
  1784. conditions: [],
  1785. actions: [
  1786. {
  1787. code: productsPercentageDiscount.code,
  1788. arguments: [
  1789. { name: 'discount', value: '100' },
  1790. {
  1791. name: 'productVariantIds',
  1792. value: `["${item1000.id}"]`,
  1793. },
  1794. ],
  1795. },
  1796. ],
  1797. });
  1798. const promo20 = await createPromotion({
  1799. enabled: true,
  1800. name: '20% discount ',
  1801. couponCode: couponCode2,
  1802. conditions: [],
  1803. actions: [
  1804. {
  1805. code: productsPercentageDiscount.code,
  1806. arguments: [
  1807. { name: 'discount', value: '20' },
  1808. {
  1809. name: 'productVariantIds',
  1810. value: `["${item1000.id}"]`,
  1811. },
  1812. ],
  1813. },
  1814. ],
  1815. });
  1816. await adminClient.query<
  1817. Codegen.AssignPromotionToChannelMutation,
  1818. Codegen.AssignPromotionToChannelMutationVariables
  1819. >(ASSIGN_PROMOTIONS_TO_CHANNEL, {
  1820. input: {
  1821. promotionIds: [promo100.id, promo20.id],
  1822. channelId: taxIncludedChannel.id,
  1823. },
  1824. });
  1825. });
  1826. it('prices exclude tax', async () => {
  1827. await shopClient.asAnonymousUser();
  1828. const item1000 = getVariantBySlug('item-1000')!;
  1829. await shopClient.query<
  1830. CodegenShop.ApplyCouponCodeMutation,
  1831. CodegenShop.ApplyCouponCodeMutationVariables
  1832. >(APPLY_COUPON_CODE, { couponCode: couponCode1 });
  1833. await shopClient.query<
  1834. CodegenShop.AddItemToOrderMutation,
  1835. CodegenShop.AddItemToOrderMutationVariables
  1836. >(ADD_ITEM_TO_ORDER, {
  1837. productVariantId: item1000.id,
  1838. quantity: 1,
  1839. });
  1840. const { activeOrder: check1 } = await shopClient.query<CodegenShop.GetActiveOrderQuery>(
  1841. GET_ACTIVE_ORDER,
  1842. );
  1843. expect(check1!.lines[0].discountedUnitPriceWithTax).toBe(0);
  1844. expect(check1!.totalWithTax).toBe(0);
  1845. await shopClient.query<
  1846. CodegenShop.ApplyCouponCodeMutation,
  1847. CodegenShop.ApplyCouponCodeMutationVariables
  1848. >(APPLY_COUPON_CODE, { couponCode: couponCode2 });
  1849. const { activeOrder: check2 } = await shopClient.query<CodegenShop.GetActiveOrderQuery>(
  1850. GET_ACTIVE_ORDER,
  1851. );
  1852. expect(check2!.lines[0].discountedUnitPriceWithTax).toBe(0);
  1853. expect(check2!.totalWithTax).toBe(0);
  1854. });
  1855. it('prices include tax', async () => {
  1856. shopClient.setChannelToken(TAX_INCLUDED_CHANNEL_TOKEN_2);
  1857. await shopClient.asAnonymousUser();
  1858. const item1000 = getVariantBySlug('item-1000')!;
  1859. await shopClient.query<
  1860. CodegenShop.ApplyCouponCodeMutation,
  1861. CodegenShop.ApplyCouponCodeMutationVariables
  1862. >(APPLY_COUPON_CODE, { couponCode: couponCode1 });
  1863. await shopClient.query<
  1864. CodegenShop.AddItemToOrderMutation,
  1865. CodegenShop.AddItemToOrderMutationVariables
  1866. >(ADD_ITEM_TO_ORDER, {
  1867. productVariantId: item1000.id,
  1868. quantity: 1,
  1869. });
  1870. const { activeOrder: check1 } = await shopClient.query<CodegenShop.GetActiveOrderQuery>(
  1871. GET_ACTIVE_ORDER,
  1872. );
  1873. expect(check1!.lines[0].discountedUnitPriceWithTax).toBe(0);
  1874. expect(check1!.totalWithTax).toBe(0);
  1875. await shopClient.query<
  1876. CodegenShop.ApplyCouponCodeMutation,
  1877. CodegenShop.ApplyCouponCodeMutationVariables
  1878. >(APPLY_COUPON_CODE, { couponCode: couponCode2 });
  1879. const { activeOrder: check2 } = await shopClient.query<CodegenShop.GetActiveOrderQuery>(
  1880. GET_ACTIVE_ORDER,
  1881. );
  1882. expect(check2!.lines[0].discountedUnitPriceWithTax).toBe(0);
  1883. expect(check2!.totalWithTax).toBe(0);
  1884. });
  1885. });
  1886. async function getProducts() {
  1887. const result = await adminClient.query<Codegen.GetProductsWithVariantPricesQuery>(
  1888. GET_PRODUCTS_WITH_VARIANT_PRICES,
  1889. {
  1890. options: {
  1891. take: 10,
  1892. skip: 0,
  1893. },
  1894. },
  1895. );
  1896. products = result.products.items;
  1897. }
  1898. async function createGlobalPromotions() {
  1899. const { facets } = await adminClient.query<Codegen.GetFacetListQuery>(GET_FACET_LIST);
  1900. const saleFacetValue = facets.items[0].values[0];
  1901. await createPromotion({
  1902. enabled: true,
  1903. name: 'Promo not yet started',
  1904. startsAt: new Date(2199, 0, 0),
  1905. conditions: [minOrderAmountCondition(100)],
  1906. actions: [freeOrderAction],
  1907. });
  1908. const deletedPromotion = await createPromotion({
  1909. enabled: true,
  1910. name: 'Deleted promotion',
  1911. conditions: [minOrderAmountCondition(100)],
  1912. actions: [freeOrderAction],
  1913. });
  1914. await deletePromotion(deletedPromotion.id);
  1915. }
  1916. async function createPromotion(
  1917. input: Omit<Codegen.CreatePromotionInput, 'translations'> & { name: string },
  1918. ): Promise<Codegen.PromotionFragment> {
  1919. const correctedInput = {
  1920. ...input,
  1921. translations: [{ languageCode: LanguageCode.en, name: input.name }],
  1922. };
  1923. delete (correctedInput as any).name;
  1924. const result = await adminClient.query<
  1925. Codegen.CreatePromotionMutation,
  1926. Codegen.CreatePromotionMutationVariables
  1927. >(CREATE_PROMOTION, {
  1928. input: correctedInput,
  1929. });
  1930. return result.createPromotion as Codegen.PromotionFragment;
  1931. }
  1932. function getVariantBySlug(
  1933. slug: 'item-100' | 'item-1000' | 'item-5000' | 'item-sale-100' | 'item-sale-1000' | 'item-0',
  1934. ): Codegen.GetProductsWithVariantPricesQuery['products']['items'][number]['variants'][number] {
  1935. return products.find(p => p.slug === slug)!.variants[0];
  1936. }
  1937. async function deletePromotion(promotionId: string) {
  1938. await adminClient.query(gql`
  1939. mutation DeletePromotionAdHoc1 {
  1940. deletePromotion(id: "${promotionId}") {
  1941. result
  1942. }
  1943. }
  1944. `);
  1945. }
  1946. });