order-modification.e2e-spec.ts 75 KB

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