order-modification.e2e-spec.ts 61 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639
  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. defaultShippingCalculator,
  6. defaultShippingEligibilityChecker,
  7. mergeConfig,
  8. productsPercentageDiscount,
  9. ShippingCalculator,
  10. } from '@vendure/core';
  11. import { createErrorResultGuard, createTestEnvironment, ErrorResultGuard } from '@vendure/testing';
  12. import gql from 'graphql-tag';
  13. import path from 'path';
  14. import { initialData } from '../../../e2e-common/e2e-initial-data';
  15. import { testConfig, TEST_SETUP_TIMEOUT_MS } from '../../../e2e-common/test-config';
  16. import { manualFulfillmentHandler } from '../src/config/fulfillment/manual-fulfillment-handler';
  17. import { orderFixedDiscount } from '../src/config/promotion/actions/order-fixed-discount-action';
  18. import {
  19. failsToSettlePaymentMethod,
  20. testFailingPaymentMethod,
  21. testSuccessfulPaymentMethod,
  22. } from './fixtures/test-payment-methods';
  23. import {
  24. AddManualPayment,
  25. AdminTransition,
  26. CreatePromotion,
  27. CreateShippingMethod,
  28. ErrorCode,
  29. GetOrder,
  30. GetOrderHistory,
  31. GetOrderWithModifications,
  32. GlobalFlag,
  33. HistoryEntryType,
  34. LanguageCode,
  35. ModifyOrder,
  36. OrderFragment,
  37. OrderWithLinesFragment,
  38. OrderWithModificationsFragment,
  39. UpdateChannel,
  40. UpdateProductVariants,
  41. } from './graphql/generated-e2e-admin-types';
  42. import {
  43. AddItemToOrderMutationVariables,
  44. ApplyCouponCode,
  45. SetShippingAddress,
  46. SetShippingMethod,
  47. TestOrderWithPaymentsFragment,
  48. TransitionToState,
  49. UpdatedOrderFragment,
  50. } from './graphql/generated-e2e-shop-types';
  51. import {
  52. ADMIN_TRANSITION_TO_STATE,
  53. CREATE_PROMOTION,
  54. CREATE_SHIPPING_METHOD,
  55. GET_ORDER,
  56. GET_ORDER_HISTORY,
  57. UPDATE_CHANNEL,
  58. UPDATE_PRODUCT_VARIANTS,
  59. } from './graphql/shared-definitions';
  60. import {
  61. APPLY_COUPON_CODE,
  62. SET_SHIPPING_ADDRESS,
  63. SET_SHIPPING_METHOD,
  64. TRANSITION_TO_STATE,
  65. } from './graphql/shop-definitions';
  66. import { addPaymentToOrder, proceedToArrangingPayment } from './utils/test-order-utils';
  67. const SHIPPING_GB = 500;
  68. const SHIPPING_US = 1000;
  69. const SHIPPING_OTHER = 750;
  70. const testCalculator = new ShippingCalculator({
  71. code: 'test-calculator',
  72. description: [{ languageCode: LanguageCode.en, value: 'Has metadata' }],
  73. args: {},
  74. calculate: (ctx, order, args) => {
  75. let price;
  76. switch (order.shippingAddress.countryCode) {
  77. case 'GB':
  78. price = SHIPPING_GB;
  79. break;
  80. case 'US':
  81. price = SHIPPING_US;
  82. break;
  83. default:
  84. price = SHIPPING_OTHER;
  85. }
  86. return {
  87. price,
  88. priceIncludesTax: true,
  89. taxRate: 20,
  90. };
  91. },
  92. });
  93. describe('Order modification', () => {
  94. const { server, adminClient, shopClient } = createTestEnvironment(
  95. mergeConfig(testConfig, {
  96. paymentOptions: {
  97. paymentMethodHandlers: [
  98. testSuccessfulPaymentMethod,
  99. failsToSettlePaymentMethod,
  100. testFailingPaymentMethod,
  101. ],
  102. },
  103. promotionOptions: {
  104. promotionConditions: [orderFixedDiscount],
  105. },
  106. shippingOptions: {
  107. shippingCalculators: [defaultShippingCalculator, testCalculator],
  108. },
  109. customFields: {
  110. Order: [{ name: 'points', type: 'int', defaultValue: 0 }],
  111. OrderLine: [{ name: 'color', type: 'string', nullable: true }],
  112. },
  113. }),
  114. );
  115. let orderId: string;
  116. let testShippingMethodId: string;
  117. const orderGuard: ErrorResultGuard<
  118. UpdatedOrderFragment | OrderWithModificationsFragment | OrderFragment
  119. > = createErrorResultGuard(input => !!input.id);
  120. beforeAll(async () => {
  121. await server.init({
  122. initialData: {
  123. ...initialData,
  124. paymentMethods: [
  125. {
  126. name: testSuccessfulPaymentMethod.code,
  127. handler: { code: testSuccessfulPaymentMethod.code, arguments: [] },
  128. },
  129. {
  130. name: failsToSettlePaymentMethod.code,
  131. handler: { code: failsToSettlePaymentMethod.code, arguments: [] },
  132. },
  133. {
  134. name: testFailingPaymentMethod.code,
  135. handler: { code: testFailingPaymentMethod.code, arguments: [] },
  136. },
  137. ],
  138. },
  139. productsCsvPath: path.join(__dirname, 'fixtures/e2e-products-full.csv'),
  140. customerCount: 2,
  141. });
  142. await adminClient.asSuperAdmin();
  143. await adminClient.query<UpdateProductVariants.Mutation, UpdateProductVariants.Variables>(
  144. UPDATE_PRODUCT_VARIANTS,
  145. {
  146. input: [
  147. {
  148. id: 'T_1',
  149. trackInventory: GlobalFlag.TRUE,
  150. },
  151. {
  152. id: 'T_2',
  153. trackInventory: GlobalFlag.TRUE,
  154. },
  155. {
  156. id: 'T_3',
  157. trackInventory: GlobalFlag.TRUE,
  158. },
  159. ],
  160. },
  161. );
  162. const { createShippingMethod } = await adminClient.query<
  163. CreateShippingMethod.Mutation,
  164. CreateShippingMethod.Variables
  165. >(CREATE_SHIPPING_METHOD, {
  166. input: {
  167. code: 'new-method',
  168. fulfillmentHandler: manualFulfillmentHandler.code,
  169. checker: {
  170. code: defaultShippingEligibilityChecker.code,
  171. arguments: [
  172. {
  173. name: 'orderMinimum',
  174. value: '0',
  175. },
  176. ],
  177. },
  178. calculator: {
  179. code: testCalculator.code,
  180. arguments: [],
  181. },
  182. translations: [{ languageCode: LanguageCode.en, name: 'test method', description: '' }],
  183. },
  184. });
  185. testShippingMethodId = createShippingMethod.id;
  186. // create an order and check out
  187. await shopClient.asUserWithCredentials('hayden.zieme12@hotmail.com', 'test');
  188. await shopClient.query(gql(ADD_ITEM_TO_ORDER_WITH_CUSTOM_FIELDS), {
  189. productVariantId: 'T_1',
  190. quantity: 1,
  191. customFields: {
  192. color: 'green',
  193. },
  194. } as any);
  195. await shopClient.query(gql(ADD_ITEM_TO_ORDER_WITH_CUSTOM_FIELDS), {
  196. productVariantId: 'T_4',
  197. quantity: 2,
  198. });
  199. await proceedToArrangingPayment(shopClient);
  200. const result = await addPaymentToOrder(shopClient, testSuccessfulPaymentMethod);
  201. orderGuard.assertSuccess(result);
  202. orderId = result.id;
  203. }, TEST_SETUP_TIMEOUT_MS);
  204. afterAll(async () => {
  205. await server.destroy();
  206. });
  207. it('modifyOrder returns error result when not in Modifying state', async () => {
  208. const { order } = await adminClient.query<GetOrder.Query, GetOrder.Variables>(GET_ORDER, {
  209. id: orderId,
  210. });
  211. const { modifyOrder } = await adminClient.query<ModifyOrder.Mutation, ModifyOrder.Variables>(
  212. MODIFY_ORDER,
  213. {
  214. input: {
  215. dryRun: false,
  216. orderId,
  217. adjustOrderLines: order!.lines.map(l => ({ orderLineId: l.id, quantity: 3 })),
  218. },
  219. },
  220. );
  221. orderGuard.assertErrorResult(modifyOrder);
  222. expect(modifyOrder.errorCode).toBe(ErrorCode.ORDER_MODIFICATION_STATE_ERROR);
  223. });
  224. it('transition to Modifying state', async () => {
  225. const { transitionOrderToState } = await adminClient.query<
  226. AdminTransition.Mutation,
  227. AdminTransition.Variables
  228. >(ADMIN_TRANSITION_TO_STATE, {
  229. id: orderId,
  230. state: 'Modifying',
  231. });
  232. orderGuard.assertSuccess(transitionOrderToState);
  233. expect(transitionOrderToState.state).toBe('Modifying');
  234. });
  235. describe('error cases', () => {
  236. it('no changes specified error', async () => {
  237. const { modifyOrder } = await adminClient.query<ModifyOrder.Mutation, ModifyOrder.Variables>(
  238. MODIFY_ORDER,
  239. {
  240. input: {
  241. dryRun: false,
  242. orderId,
  243. },
  244. },
  245. );
  246. orderGuard.assertErrorResult(modifyOrder);
  247. expect(modifyOrder.errorCode).toBe(ErrorCode.NO_CHANGES_SPECIFIED_ERROR);
  248. });
  249. it('no refund paymentId specified', async () => {
  250. const { order } = await adminClient.query<GetOrder.Query, GetOrder.Variables>(GET_ORDER, {
  251. id: orderId,
  252. });
  253. const { modifyOrder } = await adminClient.query<ModifyOrder.Mutation, ModifyOrder.Variables>(
  254. MODIFY_ORDER,
  255. {
  256. input: {
  257. dryRun: false,
  258. orderId,
  259. surcharges: [{ price: -500, priceIncludesTax: true, description: 'Discount' }],
  260. },
  261. },
  262. );
  263. orderGuard.assertErrorResult(modifyOrder);
  264. expect(modifyOrder.errorCode).toBe(ErrorCode.REFUND_PAYMENT_ID_MISSING_ERROR);
  265. await assertOrderIsUnchanged(order!);
  266. });
  267. it('addItems negative quantity', async () => {
  268. const { order } = await adminClient.query<GetOrder.Query, GetOrder.Variables>(GET_ORDER, {
  269. id: orderId,
  270. });
  271. const { modifyOrder } = await adminClient.query<ModifyOrder.Mutation, ModifyOrder.Variables>(
  272. MODIFY_ORDER,
  273. {
  274. input: {
  275. dryRun: false,
  276. orderId,
  277. addItems: [{ productVariantId: 'T_3', quantity: -1 }],
  278. },
  279. },
  280. );
  281. orderGuard.assertErrorResult(modifyOrder);
  282. expect(modifyOrder.errorCode).toBe(ErrorCode.NEGATIVE_QUANTITY_ERROR);
  283. await assertOrderIsUnchanged(order!);
  284. });
  285. it('adjustOrderLines negative quantity', async () => {
  286. const { order } = await adminClient.query<GetOrder.Query, GetOrder.Variables>(GET_ORDER, {
  287. id: orderId,
  288. });
  289. const { modifyOrder } = await adminClient.query<ModifyOrder.Mutation, ModifyOrder.Variables>(
  290. MODIFY_ORDER,
  291. {
  292. input: {
  293. dryRun: false,
  294. orderId,
  295. adjustOrderLines: [{ orderLineId: order!.lines[0].id, quantity: -1 }],
  296. },
  297. },
  298. );
  299. orderGuard.assertErrorResult(modifyOrder);
  300. expect(modifyOrder.errorCode).toBe(ErrorCode.NEGATIVE_QUANTITY_ERROR);
  301. await assertOrderIsUnchanged(order!);
  302. });
  303. it('addItems insufficient stock', async () => {
  304. const { order } = await adminClient.query<GetOrder.Query, GetOrder.Variables>(GET_ORDER, {
  305. id: orderId,
  306. });
  307. const { modifyOrder } = await adminClient.query<ModifyOrder.Mutation, ModifyOrder.Variables>(
  308. MODIFY_ORDER,
  309. {
  310. input: {
  311. dryRun: false,
  312. orderId,
  313. addItems: [{ productVariantId: 'T_3', quantity: 500 }],
  314. },
  315. },
  316. );
  317. orderGuard.assertErrorResult(modifyOrder);
  318. expect(modifyOrder.errorCode).toBe(ErrorCode.INSUFFICIENT_STOCK_ERROR);
  319. await assertOrderIsUnchanged(order!);
  320. });
  321. it('adjustOrderLines insufficient stock', async () => {
  322. const { order } = await adminClient.query<GetOrder.Query, GetOrder.Variables>(GET_ORDER, {
  323. id: orderId,
  324. });
  325. const { modifyOrder } = await adminClient.query<ModifyOrder.Mutation, ModifyOrder.Variables>(
  326. MODIFY_ORDER,
  327. {
  328. input: {
  329. dryRun: false,
  330. orderId,
  331. adjustOrderLines: [{ orderLineId: order!.lines[0].id, quantity: 500 }],
  332. },
  333. },
  334. );
  335. orderGuard.assertErrorResult(modifyOrder);
  336. expect(modifyOrder.errorCode).toBe(ErrorCode.INSUFFICIENT_STOCK_ERROR);
  337. await assertOrderIsUnchanged(order!);
  338. });
  339. it('addItems order limit', async () => {
  340. const { order } = await adminClient.query<GetOrder.Query, GetOrder.Variables>(GET_ORDER, {
  341. id: orderId,
  342. });
  343. const { modifyOrder } = await adminClient.query<ModifyOrder.Mutation, ModifyOrder.Variables>(
  344. MODIFY_ORDER,
  345. {
  346. input: {
  347. dryRun: false,
  348. orderId,
  349. addItems: [{ productVariantId: 'T_4', quantity: 9999 }],
  350. },
  351. },
  352. );
  353. orderGuard.assertErrorResult(modifyOrder);
  354. expect(modifyOrder.errorCode).toBe(ErrorCode.ORDER_LIMIT_ERROR);
  355. await assertOrderIsUnchanged(order!);
  356. });
  357. it('adjustOrderLines order limit', async () => {
  358. const { order } = await adminClient.query<GetOrder.Query, GetOrder.Variables>(GET_ORDER, {
  359. id: orderId,
  360. });
  361. const { modifyOrder } = await adminClient.query<ModifyOrder.Mutation, ModifyOrder.Variables>(
  362. MODIFY_ORDER,
  363. {
  364. input: {
  365. dryRun: false,
  366. orderId,
  367. adjustOrderLines: [{ orderLineId: order!.lines[1].id, quantity: 9999 }],
  368. },
  369. },
  370. );
  371. orderGuard.assertErrorResult(modifyOrder);
  372. expect(modifyOrder.errorCode).toBe(ErrorCode.ORDER_LIMIT_ERROR);
  373. await assertOrderIsUnchanged(order!);
  374. });
  375. });
  376. describe('dry run', () => {
  377. it('addItems', async () => {
  378. const { order } = await adminClient.query<GetOrder.Query, GetOrder.Variables>(GET_ORDER, {
  379. id: orderId,
  380. });
  381. const { modifyOrder } = await adminClient.query<ModifyOrder.Mutation, ModifyOrder.Variables>(
  382. MODIFY_ORDER,
  383. {
  384. input: {
  385. dryRun: true,
  386. orderId,
  387. addItems: [{ productVariantId: 'T_5', quantity: 1 }],
  388. },
  389. },
  390. );
  391. orderGuard.assertSuccess(modifyOrder);
  392. const expectedTotal = order!.totalWithTax + Math.round(14374 * 1.2); // price of variant T_5
  393. expect(modifyOrder.totalWithTax).toBe(expectedTotal);
  394. expect(modifyOrder.lines.length).toBe(order!.lines.length + 1);
  395. await assertOrderIsUnchanged(order!);
  396. });
  397. it('addItems with existing variant id increments existing OrderLine', async () => {
  398. const { order } = await adminClient.query<GetOrder.Query, GetOrder.Variables>(GET_ORDER, {
  399. id: orderId,
  400. });
  401. const { modifyOrder } = await adminClient.query<ModifyOrder.Mutation, ModifyOrder.Variables>(
  402. MODIFY_ORDER,
  403. {
  404. input: {
  405. dryRun: true,
  406. orderId,
  407. addItems: [
  408. { productVariantId: 'T_1', quantity: 1, customFields: { color: 'green' } } as any,
  409. ],
  410. },
  411. },
  412. );
  413. orderGuard.assertSuccess(modifyOrder);
  414. const lineT1 = modifyOrder.lines.find(l => l.productVariant.id === 'T_1');
  415. expect(modifyOrder.lines.length).toBe(2);
  416. expect(lineT1?.quantity).toBe(2);
  417. await assertOrderIsUnchanged(order!);
  418. });
  419. it('addItems with existing variant id but different customFields adds new OrderLine', async () => {
  420. const { order } = await adminClient.query<GetOrder.Query, GetOrder.Variables>(GET_ORDER, {
  421. id: orderId,
  422. });
  423. const { modifyOrder } = await adminClient.query<ModifyOrder.Mutation, ModifyOrder.Variables>(
  424. MODIFY_ORDER,
  425. {
  426. input: {
  427. dryRun: true,
  428. orderId,
  429. addItems: [
  430. { productVariantId: 'T_1', quantity: 1, customFields: { color: 'blue' } } as any,
  431. ],
  432. },
  433. },
  434. );
  435. orderGuard.assertSuccess(modifyOrder);
  436. const lineT1 = modifyOrder.lines.find(l => l.productVariant.id === 'T_1');
  437. expect(modifyOrder.lines.length).toBe(3);
  438. expect(
  439. modifyOrder.lines.map(l => ({ variantId: l.productVariant.id, quantity: l.quantity })),
  440. ).toEqual([
  441. { variantId: 'T_1', quantity: 1 },
  442. { variantId: 'T_4', quantity: 2 },
  443. { variantId: 'T_1', quantity: 1 },
  444. ]);
  445. await assertOrderIsUnchanged(order!);
  446. });
  447. it('adjustOrderLines up', async () => {
  448. const { order } = await adminClient.query<GetOrder.Query, GetOrder.Variables>(GET_ORDER, {
  449. id: orderId,
  450. });
  451. const { modifyOrder } = await adminClient.query<ModifyOrder.Mutation, ModifyOrder.Variables>(
  452. MODIFY_ORDER,
  453. {
  454. input: {
  455. dryRun: true,
  456. orderId,
  457. adjustOrderLines: [{ orderLineId: order!.lines[0].id, quantity: 3 }],
  458. },
  459. },
  460. );
  461. orderGuard.assertSuccess(modifyOrder);
  462. const expectedTotal = order!.totalWithTax + order!.lines[0].unitPriceWithTax * 2;
  463. expect(modifyOrder.lines[0].items.length).toBe(3);
  464. expect(modifyOrder.totalWithTax).toBe(expectedTotal);
  465. await assertOrderIsUnchanged(order!);
  466. });
  467. it('adjustOrderLines down', async () => {
  468. const { order } = await adminClient.query<GetOrder.Query, GetOrder.Variables>(GET_ORDER, {
  469. id: orderId,
  470. });
  471. const { modifyOrder } = await adminClient.query<ModifyOrder.Mutation, ModifyOrder.Variables>(
  472. MODIFY_ORDER,
  473. {
  474. input: {
  475. dryRun: true,
  476. orderId,
  477. adjustOrderLines: [{ orderLineId: order!.lines[1].id, quantity: 1 }],
  478. },
  479. },
  480. );
  481. orderGuard.assertSuccess(modifyOrder);
  482. const expectedTotal = order!.totalWithTax - order!.lines[1].unitPriceWithTax;
  483. expect(modifyOrder.lines[1].items.filter(i => i.cancelled).length).toBe(1);
  484. expect(modifyOrder.lines[1].items.filter(i => !i.cancelled).length).toBe(1);
  485. expect(modifyOrder.totalWithTax).toBe(expectedTotal);
  486. await assertOrderIsUnchanged(order!);
  487. });
  488. it('adjustOrderLines to zero', async () => {
  489. const { order } = await adminClient.query<GetOrder.Query, GetOrder.Variables>(GET_ORDER, {
  490. id: orderId,
  491. });
  492. const { modifyOrder } = await adminClient.query<ModifyOrder.Mutation, ModifyOrder.Variables>(
  493. MODIFY_ORDER,
  494. {
  495. input: {
  496. dryRun: true,
  497. orderId,
  498. adjustOrderLines: [{ orderLineId: order!.lines[0].id, quantity: 0 }],
  499. },
  500. },
  501. );
  502. orderGuard.assertSuccess(modifyOrder);
  503. const expectedTotal = order!.totalWithTax - order!.lines[0].linePriceWithTax;
  504. expect(modifyOrder.totalWithTax).toBe(expectedTotal);
  505. expect(modifyOrder.lines[0].items.every(i => i.cancelled)).toBe(true);
  506. await assertOrderIsUnchanged(order!);
  507. });
  508. it('surcharge positive', async () => {
  509. const { order } = await adminClient.query<GetOrder.Query, GetOrder.Variables>(GET_ORDER, {
  510. id: orderId,
  511. });
  512. const { modifyOrder } = await adminClient.query<ModifyOrder.Mutation, ModifyOrder.Variables>(
  513. MODIFY_ORDER,
  514. {
  515. input: {
  516. dryRun: true,
  517. orderId,
  518. surcharges: [
  519. {
  520. description: 'extra fee',
  521. sku: '123',
  522. price: 300,
  523. priceIncludesTax: true,
  524. taxRate: 20,
  525. taxDescription: 'VAT',
  526. },
  527. ],
  528. },
  529. },
  530. );
  531. orderGuard.assertSuccess(modifyOrder);
  532. const expectedTotal = order!.totalWithTax + 300;
  533. expect(modifyOrder.totalWithTax).toBe(expectedTotal);
  534. expect(modifyOrder.surcharges.map(s => omit(s, ['id']))).toEqual([
  535. {
  536. description: 'extra fee',
  537. sku: '123',
  538. price: 250,
  539. priceWithTax: 300,
  540. taxRate: 20,
  541. },
  542. ]);
  543. await assertOrderIsUnchanged(order!);
  544. });
  545. it('surcharge negative', async () => {
  546. const { order } = await adminClient.query<GetOrder.Query, GetOrder.Variables>(GET_ORDER, {
  547. id: orderId,
  548. });
  549. const { modifyOrder } = await adminClient.query<ModifyOrder.Mutation, ModifyOrder.Variables>(
  550. MODIFY_ORDER,
  551. {
  552. input: {
  553. dryRun: true,
  554. orderId,
  555. surcharges: [
  556. {
  557. description: 'special discount',
  558. sku: '123',
  559. price: -300,
  560. priceIncludesTax: true,
  561. taxRate: 20,
  562. taxDescription: 'VAT',
  563. },
  564. ],
  565. },
  566. },
  567. );
  568. orderGuard.assertSuccess(modifyOrder);
  569. const expectedTotal = order!.totalWithTax + -300;
  570. expect(modifyOrder.totalWithTax).toBe(expectedTotal);
  571. expect(modifyOrder.surcharges.map(s => omit(s, ['id']))).toEqual([
  572. {
  573. description: 'special discount',
  574. sku: '123',
  575. price: -250,
  576. priceWithTax: -300,
  577. taxRate: 20,
  578. },
  579. ]);
  580. await assertOrderIsUnchanged(order!);
  581. });
  582. it('does not add a history entry', async () => {
  583. const { order } = await adminClient.query<GetOrder.Query, GetOrder.Variables>(GET_ORDER, {
  584. id: orderId,
  585. });
  586. const { modifyOrder } = await adminClient.query<ModifyOrder.Mutation, ModifyOrder.Variables>(
  587. MODIFY_ORDER,
  588. {
  589. input: {
  590. dryRun: true,
  591. orderId,
  592. addItems: [{ productVariantId: 'T_5', quantity: 1 }],
  593. },
  594. },
  595. );
  596. orderGuard.assertSuccess(modifyOrder);
  597. const { order: history } = await adminClient.query<
  598. GetOrderHistory.Query,
  599. GetOrderHistory.Variables
  600. >(GET_ORDER_HISTORY, {
  601. id: orderId,
  602. options: { filter: { type: { eq: HistoryEntryType.ORDER_MODIFIED } } },
  603. });
  604. orderGuard.assertSuccess(history);
  605. expect(history.history.totalItems).toBe(0);
  606. });
  607. });
  608. describe('wet run', () => {
  609. async function assertModifiedOrderIsPersisted(order: OrderWithModificationsFragment) {
  610. const { order: order2 } = await adminClient.query<GetOrder.Query, GetOrder.Variables>(GET_ORDER, {
  611. id: order.id,
  612. });
  613. expect(order2!.totalWithTax).toBe(order!.totalWithTax);
  614. expect(order2!.lines.length).toBe(order!.lines.length);
  615. expect(order2!.surcharges.length).toBe(order!.surcharges.length);
  616. expect(order2!.payments!.length).toBe(order!.payments!.length);
  617. expect(order2!.payments!.map(p => pick(p, ['id', 'amount', 'method']))).toEqual(
  618. order!.payments!.map(p => pick(p, ['id', 'amount', 'method'])),
  619. );
  620. }
  621. it('addItems', async () => {
  622. const order = await createOrderAndTransitionToModifyingState([
  623. {
  624. productVariantId: 'T_1',
  625. quantity: 1,
  626. },
  627. ]);
  628. const { modifyOrder } = await adminClient.query<ModifyOrder.Mutation, ModifyOrder.Variables>(
  629. MODIFY_ORDER,
  630. {
  631. input: {
  632. dryRun: false,
  633. orderId: order.id,
  634. addItems: [{ productVariantId: 'T_5', quantity: 1 }],
  635. },
  636. },
  637. );
  638. orderGuard.assertSuccess(modifyOrder);
  639. const priceDelta = Math.round(14374 * 1.2); // price of variant T_5
  640. const expectedTotal = order!.totalWithTax + priceDelta;
  641. expect(modifyOrder.totalWithTax).toBe(expectedTotal);
  642. expect(modifyOrder.lines.length).toBe(order!.lines.length + 1);
  643. expect(modifyOrder.modifications.length).toBe(1);
  644. expect(modifyOrder.modifications[0].priceChange).toBe(priceDelta);
  645. expect(modifyOrder.modifications[0].orderItems?.length).toBe(1);
  646. expect(modifyOrder.modifications[0].orderItems?.map(i => i.id)).toEqual([
  647. modifyOrder.lines[1].items[0].id,
  648. ]);
  649. await assertModifiedOrderIsPersisted(modifyOrder);
  650. });
  651. it('adjustOrderLines up', async () => {
  652. const order = await createOrderAndTransitionToModifyingState([
  653. {
  654. productVariantId: 'T_1',
  655. quantity: 1,
  656. },
  657. ]);
  658. const { modifyOrder } = await adminClient.query<ModifyOrder.Mutation, ModifyOrder.Variables>(
  659. MODIFY_ORDER,
  660. {
  661. input: {
  662. dryRun: false,
  663. orderId: order.id,
  664. adjustOrderLines: [{ orderLineId: order!.lines[0].id, quantity: 2 }],
  665. },
  666. },
  667. );
  668. orderGuard.assertSuccess(modifyOrder);
  669. const priceDelta = order!.lines[0].unitPriceWithTax;
  670. const expectedTotal = order!.totalWithTax + priceDelta;
  671. expect(modifyOrder.totalWithTax).toBe(expectedTotal);
  672. expect(modifyOrder.lines[0].quantity).toBe(2);
  673. expect(modifyOrder.modifications.length).toBe(1);
  674. expect(modifyOrder.modifications[0].priceChange).toBe(priceDelta);
  675. expect(modifyOrder.modifications[0].orderItems?.length).toBe(1);
  676. expect(
  677. modifyOrder.lines[0].items
  678. .map(i => i.id)
  679. .includes(modifyOrder.modifications?.[0].orderItems?.[0].id as string),
  680. ).toBe(true);
  681. await assertModifiedOrderIsPersisted(modifyOrder);
  682. });
  683. it('adjustOrderLines down', async () => {
  684. const order = await createOrderAndTransitionToModifyingState([
  685. {
  686. productVariantId: 'T_1',
  687. quantity: 2,
  688. },
  689. ]);
  690. const { modifyOrder } = await adminClient.query<ModifyOrder.Mutation, ModifyOrder.Variables>(
  691. MODIFY_ORDER,
  692. {
  693. input: {
  694. dryRun: false,
  695. orderId: order.id,
  696. adjustOrderLines: [{ orderLineId: order!.lines[0].id, quantity: 1 }],
  697. refund: { paymentId: order!.payments![0].id },
  698. },
  699. },
  700. );
  701. orderGuard.assertSuccess(modifyOrder);
  702. const priceDelta = -order!.lines[0].unitPriceWithTax;
  703. const expectedTotal = order!.totalWithTax + priceDelta;
  704. expect(modifyOrder.totalWithTax).toBe(expectedTotal);
  705. expect(modifyOrder.lines[0].quantity).toBe(1);
  706. expect(modifyOrder.payments?.length).toBe(1);
  707. expect(modifyOrder.payments?.[0].refunds.length).toBe(1);
  708. expect(modifyOrder.payments?.[0].refunds[0]).toEqual({
  709. id: 'T_1',
  710. state: 'Pending',
  711. total: -priceDelta,
  712. paymentId: modifyOrder.payments?.[0].id,
  713. });
  714. expect(modifyOrder.modifications.length).toBe(1);
  715. expect(modifyOrder.modifications[0].priceChange).toBe(priceDelta);
  716. expect(modifyOrder.modifications[0].surcharges).toEqual(modifyOrder.surcharges.map(pick(['id'])));
  717. expect(modifyOrder.modifications[0].orderItems?.length).toBe(1);
  718. expect(
  719. modifyOrder.lines[0].items
  720. .map(i => i.id)
  721. .includes(modifyOrder.modifications?.[0].orderItems?.[0].id as string),
  722. ).toBe(true);
  723. await assertModifiedOrderIsPersisted(modifyOrder);
  724. });
  725. it('adjustOrderLines with changed customField value', async () => {
  726. const order = await createOrderAndTransitionToModifyingState([
  727. {
  728. productVariantId: 'T_1',
  729. quantity: 1,
  730. customFields: {
  731. color: 'green',
  732. },
  733. },
  734. ]);
  735. const { modifyOrder } = await adminClient.query<ModifyOrder.Mutation, ModifyOrder.Variables>(
  736. MODIFY_ORDER,
  737. {
  738. input: {
  739. dryRun: false,
  740. orderId: order.id,
  741. adjustOrderLines: [
  742. {
  743. orderLineId: order!.lines[0].id,
  744. quantity: 1,
  745. customFields: { color: 'black' },
  746. } as any,
  747. ],
  748. },
  749. },
  750. );
  751. orderGuard.assertSuccess(modifyOrder);
  752. expect(modifyOrder.lines.length).toBe(1);
  753. const { order: orderWithLines } = await adminClient.query(gql(GET_ORDER_WITH_CUSTOM_FIELDS), {
  754. id: order.id,
  755. });
  756. expect(orderWithLines.lines[0]).toEqual({
  757. id: order!.lines[0].id,
  758. customFields: { color: 'black' },
  759. });
  760. });
  761. it('adjustOrderLines handles quantity correctly', async () => {
  762. await adminClient.query<UpdateProductVariants.Mutation, UpdateProductVariants.Variables>(
  763. UPDATE_PRODUCT_VARIANTS,
  764. {
  765. input: [
  766. {
  767. id: 'T_6',
  768. stockOnHand: 1,
  769. trackInventory: GlobalFlag.TRUE,
  770. },
  771. ],
  772. },
  773. );
  774. const order = await createOrderAndTransitionToModifyingState([
  775. {
  776. productVariantId: 'T_6',
  777. quantity: 1,
  778. },
  779. ]);
  780. const { modifyOrder } = await adminClient.query<ModifyOrder.Mutation, ModifyOrder.Variables>(
  781. MODIFY_ORDER,
  782. {
  783. input: {
  784. dryRun: false,
  785. orderId: order.id,
  786. adjustOrderLines: [
  787. {
  788. orderLineId: order.lines[0].id,
  789. quantity: 1,
  790. },
  791. ],
  792. updateShippingAddress: {
  793. fullName: 'Jim',
  794. },
  795. },
  796. },
  797. );
  798. orderGuard.assertSuccess(modifyOrder);
  799. });
  800. it('surcharge positive', async () => {
  801. const order = await createOrderAndTransitionToModifyingState([
  802. {
  803. productVariantId: 'T_1',
  804. quantity: 1,
  805. },
  806. ]);
  807. const { modifyOrder } = await adminClient.query<ModifyOrder.Mutation, ModifyOrder.Variables>(
  808. MODIFY_ORDER,
  809. {
  810. input: {
  811. dryRun: false,
  812. orderId: order.id,
  813. surcharges: [
  814. {
  815. description: 'extra fee',
  816. sku: '123',
  817. price: 300,
  818. priceIncludesTax: true,
  819. taxRate: 20,
  820. taxDescription: 'VAT',
  821. },
  822. ],
  823. },
  824. },
  825. );
  826. orderGuard.assertSuccess(modifyOrder);
  827. const priceDelta = 300;
  828. const expectedTotal = order!.totalWithTax + priceDelta;
  829. expect(modifyOrder.totalWithTax).toBe(expectedTotal);
  830. expect(modifyOrder.surcharges.map(s => omit(s, ['id']))).toEqual([
  831. {
  832. description: 'extra fee',
  833. sku: '123',
  834. price: 250,
  835. priceWithTax: 300,
  836. taxRate: 20,
  837. },
  838. ]);
  839. expect(modifyOrder.modifications.length).toBe(1);
  840. expect(modifyOrder.modifications[0].priceChange).toBe(priceDelta);
  841. expect(modifyOrder.modifications[0].surcharges).toEqual(modifyOrder.surcharges.map(pick(['id'])));
  842. await assertModifiedOrderIsPersisted(modifyOrder);
  843. });
  844. it('surcharge negative', async () => {
  845. const order = await createOrderAndTransitionToModifyingState([
  846. {
  847. productVariantId: 'T_1',
  848. quantity: 1,
  849. },
  850. ]);
  851. const { modifyOrder } = await adminClient.query<ModifyOrder.Mutation, ModifyOrder.Variables>(
  852. MODIFY_ORDER,
  853. {
  854. input: {
  855. dryRun: false,
  856. orderId: order!.id,
  857. surcharges: [
  858. {
  859. description: 'special discount',
  860. sku: '123',
  861. price: -300,
  862. priceIncludesTax: true,
  863. taxRate: 20,
  864. taxDescription: 'VAT',
  865. },
  866. ],
  867. refund: {
  868. paymentId: order!.payments![0].id,
  869. },
  870. },
  871. },
  872. );
  873. orderGuard.assertSuccess(modifyOrder);
  874. const expectedTotal = order!.totalWithTax + -300;
  875. expect(modifyOrder.totalWithTax).toBe(expectedTotal);
  876. expect(modifyOrder.surcharges.map(s => omit(s, ['id']))).toEqual([
  877. {
  878. description: 'special discount',
  879. sku: '123',
  880. price: -250,
  881. priceWithTax: -300,
  882. taxRate: 20,
  883. },
  884. ]);
  885. expect(modifyOrder.modifications.length).toBe(1);
  886. expect(modifyOrder.modifications[0].priceChange).toBe(-300);
  887. await assertModifiedOrderIsPersisted(modifyOrder);
  888. });
  889. it('update updateShippingAddress, recalculate shipping', async () => {
  890. const order = await createOrderAndTransitionToModifyingState([
  891. {
  892. productVariantId: 'T_1',
  893. quantity: 1,
  894. },
  895. ]);
  896. const { modifyOrder } = await adminClient.query<ModifyOrder.Mutation, ModifyOrder.Variables>(
  897. MODIFY_ORDER,
  898. {
  899. input: {
  900. dryRun: false,
  901. orderId: order!.id,
  902. updateShippingAddress: {
  903. countryCode: 'US',
  904. },
  905. options: {
  906. recalculateShipping: true,
  907. },
  908. },
  909. },
  910. );
  911. orderGuard.assertSuccess(modifyOrder);
  912. const priceDelta = SHIPPING_US - SHIPPING_OTHER;
  913. const expectedTotal = order!.totalWithTax + priceDelta;
  914. expect(modifyOrder.totalWithTax).toBe(expectedTotal);
  915. expect(modifyOrder.shippingAddress?.countryCode).toBe('US');
  916. expect(modifyOrder.modifications.length).toBe(1);
  917. expect(modifyOrder.modifications[0].priceChange).toBe(priceDelta);
  918. await assertModifiedOrderIsPersisted(modifyOrder);
  919. });
  920. it('update updateShippingAddress, do not recalculate shipping', async () => {
  921. const order = await createOrderAndTransitionToModifyingState([
  922. {
  923. productVariantId: 'T_1',
  924. quantity: 1,
  925. },
  926. ]);
  927. const { modifyOrder } = await adminClient.query<ModifyOrder.Mutation, ModifyOrder.Variables>(
  928. MODIFY_ORDER,
  929. {
  930. input: {
  931. dryRun: false,
  932. orderId: order!.id,
  933. updateShippingAddress: {
  934. countryCode: 'US',
  935. },
  936. options: {
  937. recalculateShipping: false,
  938. },
  939. },
  940. },
  941. );
  942. orderGuard.assertSuccess(modifyOrder);
  943. const priceDelta = 0;
  944. const expectedTotal = order!.totalWithTax + priceDelta;
  945. expect(modifyOrder.totalWithTax).toBe(expectedTotal);
  946. expect(modifyOrder.shippingAddress?.countryCode).toBe('US');
  947. expect(modifyOrder.modifications.length).toBe(1);
  948. expect(modifyOrder.modifications[0].priceChange).toBe(priceDelta);
  949. await assertModifiedOrderIsPersisted(modifyOrder);
  950. });
  951. it('update Order customFields', async () => {
  952. const order = await createOrderAndTransitionToModifyingState([
  953. {
  954. productVariantId: 'T_1',
  955. quantity: 1,
  956. },
  957. ]);
  958. const { modifyOrder } = await adminClient.query<ModifyOrder.Mutation, ModifyOrder.Variables>(
  959. MODIFY_ORDER,
  960. {
  961. input: {
  962. dryRun: false,
  963. orderId: order.id,
  964. customFields: {
  965. points: 42,
  966. },
  967. } as any,
  968. },
  969. );
  970. orderGuard.assertSuccess(modifyOrder);
  971. const { order: orderWithCustomFields } = await adminClient.query(
  972. gql(GET_ORDER_WITH_CUSTOM_FIELDS),
  973. { id: order.id },
  974. );
  975. expect(orderWithCustomFields.customFields).toEqual({
  976. points: 42,
  977. });
  978. });
  979. it('adds a history entry', async () => {
  980. const { order } = await adminClient.query<GetOrder.Query, GetOrder.Variables>(GET_ORDER, {
  981. id: orderId,
  982. });
  983. const { modifyOrder } = await adminClient.query<ModifyOrder.Mutation, ModifyOrder.Variables>(
  984. MODIFY_ORDER,
  985. {
  986. input: {
  987. dryRun: false,
  988. orderId: order!.id,
  989. addItems: [{ productVariantId: 'T_5', quantity: 1 }],
  990. },
  991. },
  992. );
  993. orderGuard.assertSuccess(modifyOrder);
  994. const { order: history } = await adminClient.query<
  995. GetOrderHistory.Query,
  996. GetOrderHistory.Variables
  997. >(GET_ORDER_HISTORY, {
  998. id: orderId,
  999. options: { filter: { type: { eq: HistoryEntryType.ORDER_MODIFIED } } },
  1000. });
  1001. orderGuard.assertSuccess(history);
  1002. expect(history.history.totalItems).toBe(1);
  1003. expect(history.history.items[0].data).toEqual({
  1004. modificationId: modifyOrder.modifications[0].id,
  1005. });
  1006. });
  1007. });
  1008. describe('additional payment handling', () => {
  1009. let orderId2: string;
  1010. beforeAll(async () => {
  1011. const order = await createOrderAndTransitionToModifyingState([
  1012. {
  1013. productVariantId: 'T_1',
  1014. quantity: 1,
  1015. },
  1016. ]);
  1017. const { modifyOrder } = await adminClient.query<ModifyOrder.Mutation, ModifyOrder.Variables>(
  1018. MODIFY_ORDER,
  1019. {
  1020. input: {
  1021. dryRun: false,
  1022. orderId: order.id,
  1023. surcharges: [
  1024. {
  1025. description: 'extra fee',
  1026. sku: '123',
  1027. price: 300,
  1028. priceIncludesTax: true,
  1029. taxRate: 20,
  1030. taxDescription: 'VAT',
  1031. },
  1032. ],
  1033. },
  1034. },
  1035. );
  1036. orderGuard.assertSuccess(modifyOrder);
  1037. orderId2 = modifyOrder.id;
  1038. });
  1039. it('cannot transition back to original state if no payment is set', async () => {
  1040. const { transitionOrderToState } = await adminClient.query<
  1041. AdminTransition.Mutation,
  1042. AdminTransition.Variables
  1043. >(ADMIN_TRANSITION_TO_STATE, {
  1044. id: orderId2,
  1045. state: 'PaymentSettled',
  1046. });
  1047. orderGuard.assertErrorResult(transitionOrderToState);
  1048. expect(transitionOrderToState!.errorCode).toBe(ErrorCode.ORDER_STATE_TRANSITION_ERROR);
  1049. expect(transitionOrderToState!.transitionError).toBe(
  1050. `Can only transition to the "ArrangingAdditionalPayment" state`,
  1051. );
  1052. });
  1053. it('can transition to ArrangingAdditionalPayment state', async () => {
  1054. const { transitionOrderToState } = await adminClient.query<
  1055. AdminTransition.Mutation,
  1056. AdminTransition.Variables
  1057. >(ADMIN_TRANSITION_TO_STATE, {
  1058. id: orderId2,
  1059. state: 'ArrangingAdditionalPayment',
  1060. });
  1061. orderGuard.assertSuccess(transitionOrderToState);
  1062. expect(transitionOrderToState!.state).toBe('ArrangingAdditionalPayment');
  1063. });
  1064. it('cannot transition from ArrangingAdditionalPayment when total not covered by Payments', async () => {
  1065. const { transitionOrderToState } = await adminClient.query<
  1066. AdminTransition.Mutation,
  1067. AdminTransition.Variables
  1068. >(ADMIN_TRANSITION_TO_STATE, {
  1069. id: orderId2,
  1070. state: 'PaymentSettled',
  1071. });
  1072. orderGuard.assertErrorResult(transitionOrderToState);
  1073. expect(transitionOrderToState!.errorCode).toBe(ErrorCode.ORDER_STATE_TRANSITION_ERROR);
  1074. expect(transitionOrderToState!.transitionError).toBe(
  1075. `Cannot transition away from "ArrangingAdditionalPayment" unless Order total is covered by Payments`,
  1076. );
  1077. });
  1078. it('addManualPaymentToOrder', async () => {
  1079. const { addManualPaymentToOrder } = await adminClient.query<
  1080. AddManualPayment.Mutation,
  1081. AddManualPayment.Variables
  1082. >(ADD_MANUAL_PAYMENT, {
  1083. input: {
  1084. orderId: orderId2,
  1085. method: 'test',
  1086. transactionId: 'ABC123',
  1087. metadata: {
  1088. foo: 'bar',
  1089. },
  1090. },
  1091. });
  1092. orderGuard.assertSuccess(addManualPaymentToOrder);
  1093. expect(addManualPaymentToOrder.payments?.length).toBe(2);
  1094. expect(omit(addManualPaymentToOrder.payments![1], ['id'])).toEqual({
  1095. transactionId: 'ABC123',
  1096. state: 'Settled',
  1097. amount: 300,
  1098. method: 'test',
  1099. metadata: {
  1100. foo: 'bar',
  1101. },
  1102. refunds: [],
  1103. });
  1104. expect(addManualPaymentToOrder.modifications[0].isSettled).toBe(true);
  1105. expect(addManualPaymentToOrder.modifications[0].payment?.id).toBe(
  1106. addManualPaymentToOrder.payments![1].id,
  1107. );
  1108. });
  1109. it('transition back to original state', async () => {
  1110. const { transitionOrderToState } = await adminClient.query<
  1111. AdminTransition.Mutation,
  1112. AdminTransition.Variables
  1113. >(ADMIN_TRANSITION_TO_STATE, {
  1114. id: orderId2,
  1115. state: 'PaymentSettled',
  1116. });
  1117. orderGuard.assertSuccess(transitionOrderToState);
  1118. expect(transitionOrderToState.state).toBe('PaymentSettled');
  1119. });
  1120. });
  1121. describe('refund handling', () => {
  1122. let orderId3: string;
  1123. beforeAll(async () => {
  1124. const order = await createOrderAndTransitionToModifyingState([
  1125. {
  1126. productVariantId: 'T_1',
  1127. quantity: 1,
  1128. },
  1129. ]);
  1130. const { modifyOrder } = await adminClient.query<ModifyOrder.Mutation, ModifyOrder.Variables>(
  1131. MODIFY_ORDER,
  1132. {
  1133. input: {
  1134. dryRun: false,
  1135. orderId: order.id,
  1136. surcharges: [
  1137. {
  1138. description: 'discount',
  1139. sku: '123',
  1140. price: -300,
  1141. priceIncludesTax: true,
  1142. taxRate: 20,
  1143. taxDescription: 'VAT',
  1144. },
  1145. ],
  1146. refund: {
  1147. paymentId: order.payments![0].id,
  1148. reason: 'discount',
  1149. },
  1150. },
  1151. },
  1152. );
  1153. orderGuard.assertSuccess(modifyOrder);
  1154. orderId3 = modifyOrder.id;
  1155. });
  1156. it('modification is settled', async () => {
  1157. const { order } = await adminClient.query<
  1158. GetOrderWithModifications.Query,
  1159. GetOrderWithModifications.Variables
  1160. >(GET_ORDER_WITH_MODIFICATIONS, { id: orderId3 });
  1161. expect(order?.modifications.length).toBe(1);
  1162. expect(order?.modifications[0].isSettled).toBe(true);
  1163. });
  1164. it('cannot transition to ArrangingAdditionalPayment state if no payment is needed', async () => {
  1165. const { transitionOrderToState } = await adminClient.query<
  1166. AdminTransition.Mutation,
  1167. AdminTransition.Variables
  1168. >(ADMIN_TRANSITION_TO_STATE, {
  1169. id: orderId3,
  1170. state: 'ArrangingAdditionalPayment',
  1171. });
  1172. orderGuard.assertErrorResult(transitionOrderToState);
  1173. expect(transitionOrderToState!.errorCode).toBe(ErrorCode.ORDER_STATE_TRANSITION_ERROR);
  1174. expect(transitionOrderToState!.transitionError).toBe(
  1175. `Cannot transition Order to the \"ArrangingAdditionalPayment\" state as no additional payments are needed`,
  1176. );
  1177. });
  1178. it('can transition to original state', async () => {
  1179. const { transitionOrderToState } = await adminClient.query<
  1180. AdminTransition.Mutation,
  1181. AdminTransition.Variables
  1182. >(ADMIN_TRANSITION_TO_STATE, {
  1183. id: orderId3,
  1184. state: 'PaymentSettled',
  1185. });
  1186. orderGuard.assertSuccess(transitionOrderToState);
  1187. expect(transitionOrderToState!.state).toBe('PaymentSettled');
  1188. const { order } = await adminClient.query<GetOrder.Query, GetOrder.Variables>(GET_ORDER, {
  1189. id: orderId3,
  1190. });
  1191. expect(order?.payments![0].refunds.length).toBe(1);
  1192. expect(order?.payments![0].refunds[0].total).toBe(300);
  1193. expect(order?.payments![0].refunds[0].reason).toBe('discount');
  1194. });
  1195. });
  1196. // https://github.com/vendure-ecommerce/vendure/issues/688 - 4th point
  1197. it('correct additional payment when discounts applied', async () => {
  1198. await adminClient.query<CreatePromotion.Mutation, CreatePromotion.Variables>(CREATE_PROMOTION, {
  1199. input: {
  1200. name: '$5 off',
  1201. couponCode: '5OFF',
  1202. enabled: true,
  1203. conditions: [],
  1204. actions: [
  1205. {
  1206. code: orderFixedDiscount.code,
  1207. arguments: [{ name: 'discount', value: '500' }],
  1208. },
  1209. ],
  1210. },
  1211. });
  1212. await shopClient.asUserWithCredentials('trevor_donnelly96@hotmail.com', 'test');
  1213. await shopClient.query(gql(ADD_ITEM_TO_ORDER_WITH_CUSTOM_FIELDS), {
  1214. productVariantId: 'T_1',
  1215. quantity: 1,
  1216. } as any);
  1217. await shopClient.query<ApplyCouponCode.Mutation, ApplyCouponCode.Variables>(APPLY_COUPON_CODE, {
  1218. couponCode: '5OFF',
  1219. });
  1220. await proceedToArrangingPayment(shopClient);
  1221. const order = await addPaymentToOrder(shopClient, testSuccessfulPaymentMethod);
  1222. orderGuard.assertSuccess(order);
  1223. const originalTotalWithTax = order.totalWithTax;
  1224. const surcharge = 300;
  1225. const { transitionOrderToState } = await adminClient.query<
  1226. AdminTransition.Mutation,
  1227. AdminTransition.Variables
  1228. >(ADMIN_TRANSITION_TO_STATE, {
  1229. id: order.id,
  1230. state: 'Modifying',
  1231. });
  1232. orderGuard.assertSuccess(transitionOrderToState);
  1233. expect(transitionOrderToState.state).toBe('Modifying');
  1234. const { modifyOrder } = await adminClient.query<ModifyOrder.Mutation, ModifyOrder.Variables>(
  1235. MODIFY_ORDER,
  1236. {
  1237. input: {
  1238. dryRun: false,
  1239. orderId: order.id,
  1240. surcharges: [
  1241. {
  1242. description: 'extra fee',
  1243. sku: '123',
  1244. price: surcharge,
  1245. priceIncludesTax: true,
  1246. taxRate: 20,
  1247. taxDescription: 'VAT',
  1248. },
  1249. ],
  1250. },
  1251. },
  1252. );
  1253. orderGuard.assertSuccess(modifyOrder);
  1254. expect(modifyOrder.totalWithTax).toBe(originalTotalWithTax + surcharge);
  1255. });
  1256. // https://github.com/vendure-ecommerce/vendure/issues/872
  1257. describe('correct price calculations when prices include tax', () => {
  1258. async function modifyOrderLineQuantity(order: TestOrderWithPaymentsFragment) {
  1259. const { transitionOrderToState } = await adminClient.query<
  1260. AdminTransition.Mutation,
  1261. AdminTransition.Variables
  1262. >(ADMIN_TRANSITION_TO_STATE, {
  1263. id: order.id,
  1264. state: 'Modifying',
  1265. });
  1266. orderGuard.assertSuccess(transitionOrderToState);
  1267. expect(transitionOrderToState.state).toBe('Modifying');
  1268. const { modifyOrder } = await adminClient.query<ModifyOrder.Mutation, ModifyOrder.Variables>(
  1269. MODIFY_ORDER,
  1270. {
  1271. input: {
  1272. dryRun: true,
  1273. orderId: order.id,
  1274. adjustOrderLines: [{ orderLineId: order!.lines[0].id, quantity: 2 }],
  1275. },
  1276. },
  1277. );
  1278. orderGuard.assertSuccess(modifyOrder);
  1279. return modifyOrder;
  1280. }
  1281. beforeAll(async () => {
  1282. await adminClient.query<UpdateChannel.Mutation, UpdateChannel.Variables>(UPDATE_CHANNEL, {
  1283. input: {
  1284. id: 'T_1',
  1285. pricesIncludeTax: true,
  1286. },
  1287. });
  1288. });
  1289. it('without promotion', async () => {
  1290. await shopClient.asUserWithCredentials('hayden.zieme12@hotmail.com', 'test');
  1291. await shopClient.query(gql(ADD_ITEM_TO_ORDER_WITH_CUSTOM_FIELDS), {
  1292. productVariantId: 'T_1',
  1293. quantity: 1,
  1294. } as any);
  1295. await proceedToArrangingPayment(shopClient);
  1296. const order = await addPaymentToOrder(shopClient, testSuccessfulPaymentMethod);
  1297. orderGuard.assertSuccess(order);
  1298. const modifyOrder = await modifyOrderLineQuantity(order);
  1299. expect(modifyOrder.lines[0].linePriceWithTax).toBe(order.lines[0].linePriceWithTax * 2);
  1300. });
  1301. it('with promotion', async () => {
  1302. await adminClient.query<CreatePromotion.Mutation, CreatePromotion.Variables>(CREATE_PROMOTION, {
  1303. input: {
  1304. name: 'half price',
  1305. couponCode: 'HALF',
  1306. enabled: true,
  1307. conditions: [],
  1308. actions: [
  1309. {
  1310. code: productsPercentageDiscount.code,
  1311. arguments: [
  1312. { name: 'discount', value: '50' },
  1313. { name: 'productVariantIds', value: JSON.stringify(['T_1']) },
  1314. ],
  1315. },
  1316. ],
  1317. },
  1318. });
  1319. await shopClient.asUserWithCredentials('trevor_donnelly96@hotmail.com', 'test');
  1320. await shopClient.query(gql(ADD_ITEM_TO_ORDER_WITH_CUSTOM_FIELDS), {
  1321. productVariantId: 'T_1',
  1322. quantity: 1,
  1323. } as any);
  1324. await shopClient.query<ApplyCouponCode.Mutation, ApplyCouponCode.Variables>(APPLY_COUPON_CODE, {
  1325. couponCode: 'HALF',
  1326. });
  1327. await proceedToArrangingPayment(shopClient);
  1328. const order = await addPaymentToOrder(shopClient, testSuccessfulPaymentMethod);
  1329. orderGuard.assertSuccess(order);
  1330. const modifyOrder = await modifyOrderLineQuantity(order);
  1331. expect(modifyOrder.lines[0].discountedLinePriceWithTax).toBe(
  1332. modifyOrder.lines[0].linePriceWithTax / 2,
  1333. );
  1334. expect(modifyOrder.lines[0].linePriceWithTax).toBe(order.lines[0].linePriceWithTax * 2);
  1335. });
  1336. });
  1337. async function assertOrderIsUnchanged(order: OrderWithLinesFragment) {
  1338. const { order: order2 } = await adminClient.query<GetOrder.Query, GetOrder.Variables>(GET_ORDER, {
  1339. id: order.id,
  1340. });
  1341. expect(order2!.totalWithTax).toBe(order!.totalWithTax);
  1342. expect(order2!.lines.length).toBe(order!.lines.length);
  1343. expect(order2!.surcharges.length).toBe(order!.surcharges.length);
  1344. expect(order2!.totalQuantity).toBe(order!.totalQuantity);
  1345. }
  1346. async function createOrderAndTransitionToModifyingState(
  1347. items: Array<AddItemToOrderMutationVariables & { customFields?: any }>,
  1348. ): Promise<TestOrderWithPaymentsFragment> {
  1349. await shopClient.asUserWithCredentials('hayden.zieme12@hotmail.com', 'test');
  1350. for (const itemInput of items) {
  1351. await shopClient.query(gql(ADD_ITEM_TO_ORDER_WITH_CUSTOM_FIELDS), itemInput);
  1352. }
  1353. await shopClient.query<SetShippingAddress.Mutation, SetShippingAddress.Variables>(
  1354. SET_SHIPPING_ADDRESS,
  1355. {
  1356. input: {
  1357. fullName: 'name',
  1358. streetLine1: '12 the street',
  1359. city: 'foo',
  1360. postalCode: '123456',
  1361. countryCode: 'AT',
  1362. },
  1363. },
  1364. );
  1365. await shopClient.query<SetShippingMethod.Mutation, SetShippingMethod.Variables>(SET_SHIPPING_METHOD, {
  1366. id: testShippingMethodId,
  1367. });
  1368. await shopClient.query<TransitionToState.Mutation, TransitionToState.Variables>(TRANSITION_TO_STATE, {
  1369. state: 'ArrangingPayment',
  1370. });
  1371. const order = await addPaymentToOrder(shopClient, testSuccessfulPaymentMethod);
  1372. orderGuard.assertSuccess(order);
  1373. const { transitionOrderToState } = await adminClient.query<
  1374. AdminTransition.Mutation,
  1375. AdminTransition.Variables
  1376. >(ADMIN_TRANSITION_TO_STATE, {
  1377. id: order.id,
  1378. state: 'Modifying',
  1379. });
  1380. return order;
  1381. }
  1382. });
  1383. export const ORDER_WITH_MODIFICATION_FRAGMENT = gql`
  1384. fragment OrderWithModifications on Order {
  1385. id
  1386. state
  1387. total
  1388. totalWithTax
  1389. lines {
  1390. id
  1391. quantity
  1392. linePrice
  1393. linePriceWithTax
  1394. discountedLinePriceWithTax
  1395. productVariant {
  1396. id
  1397. name
  1398. }
  1399. items {
  1400. id
  1401. createdAt
  1402. updatedAt
  1403. cancelled
  1404. unitPrice
  1405. }
  1406. }
  1407. surcharges {
  1408. id
  1409. description
  1410. sku
  1411. price
  1412. priceWithTax
  1413. taxRate
  1414. }
  1415. payments {
  1416. id
  1417. transactionId
  1418. state
  1419. amount
  1420. method
  1421. metadata
  1422. refunds {
  1423. id
  1424. state
  1425. total
  1426. paymentId
  1427. }
  1428. }
  1429. modifications {
  1430. id
  1431. note
  1432. priceChange
  1433. isSettled
  1434. orderItems {
  1435. id
  1436. }
  1437. surcharges {
  1438. id
  1439. }
  1440. payment {
  1441. id
  1442. state
  1443. amount
  1444. method
  1445. }
  1446. refund {
  1447. id
  1448. state
  1449. total
  1450. paymentId
  1451. }
  1452. }
  1453. shippingAddress {
  1454. streetLine1
  1455. city
  1456. postalCode
  1457. province
  1458. countryCode
  1459. country
  1460. }
  1461. billingAddress {
  1462. streetLine1
  1463. city
  1464. postalCode
  1465. province
  1466. countryCode
  1467. country
  1468. }
  1469. }
  1470. `;
  1471. export const GET_ORDER_WITH_MODIFICATIONS = gql`
  1472. query GetOrderWithModifications($id: ID!) {
  1473. order(id: $id) {
  1474. ...OrderWithModifications
  1475. }
  1476. }
  1477. ${ORDER_WITH_MODIFICATION_FRAGMENT}
  1478. `;
  1479. export const MODIFY_ORDER = gql`
  1480. mutation ModifyOrder($input: ModifyOrderInput!) {
  1481. modifyOrder(input: $input) {
  1482. ...OrderWithModifications
  1483. ... on ErrorResult {
  1484. errorCode
  1485. message
  1486. }
  1487. }
  1488. }
  1489. ${ORDER_WITH_MODIFICATION_FRAGMENT}
  1490. `;
  1491. export const ADD_MANUAL_PAYMENT = gql`
  1492. mutation AddManualPayment($input: ManualPaymentInput!) {
  1493. addManualPaymentToOrder(input: $input) {
  1494. ...OrderWithModifications
  1495. ... on ErrorResult {
  1496. errorCode
  1497. message
  1498. }
  1499. }
  1500. }
  1501. ${ORDER_WITH_MODIFICATION_FRAGMENT}
  1502. `;
  1503. // Note, we don't use the gql tag around these due to the customFields which
  1504. // would cause a codegen error.
  1505. const ADD_ITEM_TO_ORDER_WITH_CUSTOM_FIELDS = `
  1506. mutation AddItemToOrder($productVariantId: ID!, $quantity: Int!, $customFields: OrderLineCustomFieldsInput) {
  1507. addItemToOrder(productVariantId: $productVariantId, quantity: $quantity, customFields: $customFields) {
  1508. ...on Order { id }
  1509. }
  1510. }
  1511. `;
  1512. const GET_ORDER_WITH_CUSTOM_FIELDS = `
  1513. query GetOrderCustomFields($id: ID!) {
  1514. order(id: $id) {
  1515. customFields { points }
  1516. lines { id, customFields { color } }
  1517. }
  1518. }
  1519. `;