order-modification.e2e-spec.ts 98 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568
  1. /* eslint-disable @typescript-eslint/no-non-null-assertion */
  2. import { omit } from '@vendure/common/lib/omit';
  3. import { pick } from '@vendure/common/lib/pick';
  4. import { summate } from '@vendure/common/lib/shared-utils';
  5. import {
  6. defaultShippingCalculator,
  7. defaultShippingEligibilityChecker,
  8. freeShipping,
  9. mergeConfig,
  10. minimumOrderAmount,
  11. orderPercentageDiscount,
  12. productsPercentageDiscount,
  13. ShippingCalculator,
  14. } from '@vendure/core';
  15. import { createErrorResultGuard, createTestEnvironment, ErrorResultGuard } from '@vendure/testing';
  16. import gql from 'graphql-tag';
  17. import path from 'path';
  18. import { afterAll, beforeAll, describe, expect, it } from 'vitest';
  19. import { initialData } from '../../../e2e-common/e2e-initial-data';
  20. import { testConfig, TEST_SETUP_TIMEOUT_MS } from '../../../e2e-common/test-config';
  21. import { manualFulfillmentHandler } from '../src/config/fulfillment/manual-fulfillment-handler';
  22. import { orderFixedDiscount } from '../src/config/promotion/actions/order-fixed-discount-action';
  23. import {
  24. failsToSettlePaymentMethod,
  25. testFailingPaymentMethod,
  26. testSuccessfulPaymentMethod,
  27. } from './fixtures/test-payment-methods';
  28. import * as Codegen from './graphql/generated-e2e-admin-types';
  29. import {
  30. ErrorCode,
  31. GlobalFlag,
  32. HistoryEntryType,
  33. LanguageCode,
  34. OrderFragment,
  35. OrderWithLinesFragment,
  36. OrderWithModificationsFragment,
  37. } from './graphql/generated-e2e-admin-types';
  38. import * as CodegenShop from './graphql/generated-e2e-shop-types';
  39. import {
  40. AddItemToOrderMutationVariables,
  41. TestOrderWithPaymentsFragment,
  42. UpdatedOrderFragment,
  43. } from './graphql/generated-e2e-shop-types';
  44. import {
  45. ADMIN_TRANSITION_TO_STATE,
  46. CREATE_FULFILLMENT,
  47. CREATE_PROMOTION,
  48. CREATE_SHIPPING_METHOD,
  49. DELETE_PROMOTION,
  50. GET_ORDER,
  51. GET_ORDER_HISTORY,
  52. GET_PRODUCT_VARIANT_LIST,
  53. GET_STOCK_MOVEMENT,
  54. UPDATE_CHANNEL,
  55. UPDATE_PRODUCT_VARIANTS,
  56. } from './graphql/shared-definitions';
  57. import {
  58. APPLY_COUPON_CODE,
  59. SET_SHIPPING_ADDRESS,
  60. SET_SHIPPING_METHOD,
  61. TRANSITION_TO_STATE,
  62. } from './graphql/shop-definitions';
  63. import { addPaymentToOrder, proceedToArrangingPayment, sortById } from './utils/test-order-utils';
  64. const SHIPPING_GB = 500;
  65. const SHIPPING_US = 1000;
  66. const SHIPPING_OTHER = 750;
  67. const testCalculator = new ShippingCalculator({
  68. code: 'test-calculator',
  69. description: [{ languageCode: LanguageCode.en, value: 'Has metadata' }],
  70. args: {},
  71. calculate: (ctx, order, args) => {
  72. let price;
  73. switch (order.shippingAddress.countryCode) {
  74. case 'GB':
  75. price = SHIPPING_GB;
  76. break;
  77. case 'US':
  78. price = SHIPPING_US;
  79. break;
  80. default:
  81. price = SHIPPING_OTHER;
  82. }
  83. return {
  84. price,
  85. priceIncludesTax: true,
  86. taxRate: 20,
  87. };
  88. },
  89. });
  90. describe('Order modification', () => {
  91. const { server, adminClient, shopClient } = createTestEnvironment(
  92. mergeConfig(testConfig(), {
  93. paymentOptions: {
  94. paymentMethodHandlers: [
  95. testSuccessfulPaymentMethod,
  96. failsToSettlePaymentMethod,
  97. testFailingPaymentMethod,
  98. ],
  99. },
  100. shippingOptions: {
  101. shippingCalculators: [defaultShippingCalculator, testCalculator],
  102. },
  103. customFields: {
  104. Order: [{ name: 'points', type: 'int', defaultValue: 0 }],
  105. OrderLine: [{ name: 'color', type: 'string', nullable: true }],
  106. },
  107. }),
  108. );
  109. let orderId: string;
  110. let testShippingMethodId: string;
  111. const orderGuard: ErrorResultGuard<
  112. UpdatedOrderFragment | OrderWithModificationsFragment | OrderFragment
  113. > = createErrorResultGuard(input => !!input.id);
  114. beforeAll(async () => {
  115. await server.init({
  116. initialData: {
  117. ...initialData,
  118. paymentMethods: [
  119. {
  120. name: testSuccessfulPaymentMethod.code,
  121. handler: { code: testSuccessfulPaymentMethod.code, arguments: [] },
  122. },
  123. {
  124. name: failsToSettlePaymentMethod.code,
  125. handler: { code: failsToSettlePaymentMethod.code, arguments: [] },
  126. },
  127. {
  128. name: testFailingPaymentMethod.code,
  129. handler: { code: testFailingPaymentMethod.code, arguments: [] },
  130. },
  131. ],
  132. },
  133. productsCsvPath: path.join(__dirname, 'fixtures/e2e-products-full.csv'),
  134. customerCount: 3,
  135. });
  136. await adminClient.asSuperAdmin();
  137. await adminClient.query<
  138. Codegen.UpdateProductVariantsMutation,
  139. Codegen.UpdateProductVariantsMutationVariables
  140. >(UPDATE_PRODUCT_VARIANTS, {
  141. input: [
  142. {
  143. id: 'T_1',
  144. trackInventory: GlobalFlag.TRUE,
  145. },
  146. {
  147. id: 'T_2',
  148. trackInventory: GlobalFlag.TRUE,
  149. },
  150. {
  151. id: 'T_3',
  152. trackInventory: GlobalFlag.TRUE,
  153. },
  154. ],
  155. });
  156. const { createShippingMethod } = await adminClient.query<
  157. Codegen.CreateShippingMethodMutation,
  158. Codegen.CreateShippingMethodMutationVariables
  159. >(CREATE_SHIPPING_METHOD, {
  160. input: {
  161. code: 'new-method',
  162. fulfillmentHandler: manualFulfillmentHandler.code,
  163. checker: {
  164. code: defaultShippingEligibilityChecker.code,
  165. arguments: [
  166. {
  167. name: 'orderMinimum',
  168. value: '0',
  169. },
  170. ],
  171. },
  172. calculator: {
  173. code: testCalculator.code,
  174. arguments: [],
  175. },
  176. translations: [{ languageCode: LanguageCode.en, name: 'test method', description: '' }],
  177. },
  178. });
  179. testShippingMethodId = createShippingMethod.id;
  180. // create an order and check out
  181. await shopClient.asUserWithCredentials('hayden.zieme12@hotmail.com', 'test');
  182. await shopClient.query(gql(ADD_ITEM_TO_ORDER_WITH_CUSTOM_FIELDS), {
  183. productVariantId: 'T_1',
  184. quantity: 1,
  185. customFields: {
  186. color: 'green',
  187. },
  188. } as any);
  189. await shopClient.query(gql(ADD_ITEM_TO_ORDER_WITH_CUSTOM_FIELDS), {
  190. productVariantId: 'T_4',
  191. quantity: 2,
  192. });
  193. await proceedToArrangingPayment(shopClient);
  194. const result = await addPaymentToOrder(shopClient, testSuccessfulPaymentMethod);
  195. orderGuard.assertSuccess(result);
  196. orderId = result.id;
  197. }, TEST_SETUP_TIMEOUT_MS);
  198. afterAll(async () => {
  199. await server.destroy();
  200. });
  201. it('modifyOrder returns error result when not in Modifying state', async () => {
  202. const { order } = await adminClient.query<Codegen.GetOrderQuery, Codegen.GetOrderQueryVariables>(
  203. GET_ORDER,
  204. {
  205. id: orderId,
  206. },
  207. );
  208. const { modifyOrder } = await adminClient.query<
  209. Codegen.ModifyOrderMutation,
  210. Codegen.ModifyOrderMutationVariables
  211. >(MODIFY_ORDER, {
  212. input: {
  213. dryRun: false,
  214. orderId,
  215. adjustOrderLines: order!.lines.map(l => ({ orderLineId: l.id, quantity: 3 })),
  216. },
  217. });
  218. orderGuard.assertErrorResult(modifyOrder);
  219. expect(modifyOrder.errorCode).toBe(ErrorCode.ORDER_MODIFICATION_STATE_ERROR);
  220. });
  221. it('transition to Modifying state', async () => {
  222. const transitionOrderToState = await adminTransitionOrderToState(orderId, 'Modifying');
  223. orderGuard.assertSuccess(transitionOrderToState);
  224. expect(transitionOrderToState.state).toBe('Modifying');
  225. });
  226. describe('error cases', () => {
  227. it('no changes specified error', async () => {
  228. const { modifyOrder } = await adminClient.query<
  229. Codegen.ModifyOrderMutation,
  230. Codegen.ModifyOrderMutationVariables
  231. >(MODIFY_ORDER, {
  232. input: {
  233. dryRun: false,
  234. orderId,
  235. },
  236. });
  237. orderGuard.assertErrorResult(modifyOrder);
  238. expect(modifyOrder.errorCode).toBe(ErrorCode.NO_CHANGES_SPECIFIED_ERROR);
  239. });
  240. it('no refund paymentId specified', async () => {
  241. const { order } = await adminClient.query<Codegen.GetOrderQuery, Codegen.GetOrderQueryVariables>(
  242. GET_ORDER,
  243. {
  244. id: orderId,
  245. },
  246. );
  247. const { modifyOrder } = await adminClient.query<
  248. Codegen.ModifyOrderMutation,
  249. Codegen.ModifyOrderMutationVariables
  250. >(MODIFY_ORDER, {
  251. input: {
  252. dryRun: false,
  253. orderId,
  254. surcharges: [{ price: -500, priceIncludesTax: true, description: 'Discount' }],
  255. },
  256. });
  257. orderGuard.assertErrorResult(modifyOrder);
  258. expect(modifyOrder.errorCode).toBe(ErrorCode.REFUND_PAYMENT_ID_MISSING_ERROR);
  259. await assertOrderIsUnchanged(order!);
  260. });
  261. it('addItems negative quantity', async () => {
  262. const { order } = await adminClient.query<Codegen.GetOrderQuery, Codegen.GetOrderQueryVariables>(
  263. GET_ORDER,
  264. {
  265. id: orderId,
  266. },
  267. );
  268. const { modifyOrder } = await adminClient.query<
  269. Codegen.ModifyOrderMutation,
  270. Codegen.ModifyOrderMutationVariables
  271. >(MODIFY_ORDER, {
  272. input: {
  273. dryRun: false,
  274. orderId,
  275. addItems: [{ productVariantId: 'T_3', quantity: -1 }],
  276. },
  277. });
  278. orderGuard.assertErrorResult(modifyOrder);
  279. expect(modifyOrder.errorCode).toBe(ErrorCode.NEGATIVE_QUANTITY_ERROR);
  280. await assertOrderIsUnchanged(order!);
  281. });
  282. it('adjustOrderLines negative quantity', async () => {
  283. const { order } = await adminClient.query<Codegen.GetOrderQuery, Codegen.GetOrderQueryVariables>(
  284. GET_ORDER,
  285. {
  286. id: orderId,
  287. },
  288. );
  289. const { modifyOrder } = await adminClient.query<
  290. Codegen.ModifyOrderMutation,
  291. Codegen.ModifyOrderMutationVariables
  292. >(MODIFY_ORDER, {
  293. input: {
  294. dryRun: false,
  295. orderId,
  296. adjustOrderLines: [{ orderLineId: order!.lines[0].id, quantity: -1 }],
  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<Codegen.GetOrderQuery, Codegen.GetOrderQueryVariables>(
  305. GET_ORDER,
  306. {
  307. id: orderId,
  308. },
  309. );
  310. const { modifyOrder } = await adminClient.query<
  311. Codegen.ModifyOrderMutation,
  312. Codegen.ModifyOrderMutationVariables
  313. >(MODIFY_ORDER, {
  314. input: {
  315. dryRun: false,
  316. orderId,
  317. addItems: [{ productVariantId: 'T_3', quantity: 500 }],
  318. },
  319. });
  320. orderGuard.assertErrorResult(modifyOrder);
  321. expect(modifyOrder.errorCode).toBe(ErrorCode.INSUFFICIENT_STOCK_ERROR);
  322. await assertOrderIsUnchanged(order!);
  323. });
  324. it('adjustOrderLines insufficient stock', async () => {
  325. const { order } = await adminClient.query<Codegen.GetOrderQuery, Codegen.GetOrderQueryVariables>(
  326. GET_ORDER,
  327. {
  328. id: orderId,
  329. },
  330. );
  331. const { modifyOrder } = await adminClient.query<
  332. Codegen.ModifyOrderMutation,
  333. Codegen.ModifyOrderMutationVariables
  334. >(MODIFY_ORDER, {
  335. input: {
  336. dryRun: false,
  337. orderId,
  338. adjustOrderLines: [{ orderLineId: order!.lines[0].id, quantity: 500 }],
  339. },
  340. });
  341. orderGuard.assertErrorResult(modifyOrder);
  342. expect(modifyOrder.errorCode).toBe(ErrorCode.INSUFFICIENT_STOCK_ERROR);
  343. await assertOrderIsUnchanged(order!);
  344. });
  345. it('addItems order limit', async () => {
  346. const { order } = await adminClient.query<Codegen.GetOrderQuery, Codegen.GetOrderQueryVariables>(
  347. GET_ORDER,
  348. {
  349. id: orderId,
  350. },
  351. );
  352. const { modifyOrder } = await adminClient.query<
  353. Codegen.ModifyOrderMutation,
  354. Codegen.ModifyOrderMutationVariables
  355. >(MODIFY_ORDER, {
  356. input: {
  357. dryRun: false,
  358. orderId,
  359. addItems: [{ productVariantId: 'T_4', quantity: 9999 }],
  360. },
  361. });
  362. orderGuard.assertErrorResult(modifyOrder);
  363. expect(modifyOrder.errorCode).toBe(ErrorCode.ORDER_LIMIT_ERROR);
  364. await assertOrderIsUnchanged(order!);
  365. });
  366. it('adjustOrderLines order limit', async () => {
  367. const { order } = await adminClient.query<Codegen.GetOrderQuery, Codegen.GetOrderQueryVariables>(
  368. GET_ORDER,
  369. {
  370. id: orderId,
  371. },
  372. );
  373. const { modifyOrder } = await adminClient.query<
  374. Codegen.ModifyOrderMutation,
  375. Codegen.ModifyOrderMutationVariables
  376. >(MODIFY_ORDER, {
  377. input: {
  378. dryRun: false,
  379. orderId,
  380. adjustOrderLines: [{ orderLineId: order!.lines[1].id, quantity: 9999 }],
  381. },
  382. });
  383. orderGuard.assertErrorResult(modifyOrder);
  384. expect(modifyOrder.errorCode).toBe(ErrorCode.ORDER_LIMIT_ERROR);
  385. await assertOrderIsUnchanged(order!);
  386. });
  387. });
  388. describe('dry run', () => {
  389. it('addItems', async () => {
  390. const { order } = await adminClient.query<Codegen.GetOrderQuery, Codegen.GetOrderQueryVariables>(
  391. GET_ORDER,
  392. {
  393. id: orderId,
  394. },
  395. );
  396. const { modifyOrder } = await adminClient.query<
  397. Codegen.ModifyOrderMutation,
  398. Codegen.ModifyOrderMutationVariables
  399. >(MODIFY_ORDER, {
  400. input: {
  401. dryRun: true,
  402. orderId,
  403. addItems: [{ productVariantId: 'T_5', quantity: 1 }],
  404. },
  405. });
  406. orderGuard.assertSuccess(modifyOrder);
  407. const expectedTotal = order!.totalWithTax + Math.round(14374 * 1.2); // price of variant T_5
  408. expect(modifyOrder.totalWithTax).toBe(expectedTotal);
  409. expect(modifyOrder.lines.length).toBe(order!.lines.length + 1);
  410. await assertOrderIsUnchanged(order!);
  411. });
  412. it('addItems with existing variant id increments existing OrderLine', async () => {
  413. const { order } = await adminClient.query<Codegen.GetOrderQuery, Codegen.GetOrderQueryVariables>(
  414. GET_ORDER,
  415. {
  416. id: orderId,
  417. },
  418. );
  419. const { modifyOrder } = await adminClient.query<
  420. Codegen.ModifyOrderMutation,
  421. Codegen.ModifyOrderMutationVariables
  422. >(MODIFY_ORDER, {
  423. input: {
  424. dryRun: true,
  425. orderId,
  426. addItems: [
  427. { productVariantId: 'T_1', quantity: 1, customFields: { color: 'green' } } as any,
  428. ],
  429. },
  430. });
  431. orderGuard.assertSuccess(modifyOrder);
  432. const lineT1 = modifyOrder.lines.find(l => l.productVariant.id === 'T_1');
  433. expect(modifyOrder.lines.length).toBe(2);
  434. expect(lineT1?.quantity).toBe(2);
  435. await assertOrderIsUnchanged(order!);
  436. });
  437. it('addItems with existing variant id but different customFields adds new OrderLine', async () => {
  438. const { order } = await adminClient.query<Codegen.GetOrderQuery, Codegen.GetOrderQueryVariables>(
  439. GET_ORDER,
  440. {
  441. id: orderId,
  442. },
  443. );
  444. const { modifyOrder } = await adminClient.query<
  445. Codegen.ModifyOrderMutation,
  446. Codegen.ModifyOrderMutationVariables
  447. >(MODIFY_ORDER, {
  448. input: {
  449. dryRun: true,
  450. orderId,
  451. addItems: [
  452. { productVariantId: 'T_1', quantity: 1, customFields: { color: 'blue' } } as any,
  453. ],
  454. },
  455. });
  456. orderGuard.assertSuccess(modifyOrder);
  457. const lineT1 = modifyOrder.lines.find(l => l.productVariant.id === 'T_1');
  458. expect(modifyOrder.lines.length).toBe(3);
  459. expect(
  460. modifyOrder.lines.map(l => ({ variantId: l.productVariant.id, quantity: l.quantity })),
  461. ).toEqual([
  462. { variantId: 'T_1', quantity: 1 },
  463. { variantId: 'T_4', quantity: 2 },
  464. { variantId: 'T_1', quantity: 1 },
  465. ]);
  466. await assertOrderIsUnchanged(order!);
  467. });
  468. it('adjustOrderLines up', async () => {
  469. const { order } = await adminClient.query<Codegen.GetOrderQuery, Codegen.GetOrderQueryVariables>(
  470. GET_ORDER,
  471. {
  472. id: orderId,
  473. },
  474. );
  475. const { modifyOrder } = await adminClient.query<
  476. Codegen.ModifyOrderMutation,
  477. Codegen.ModifyOrderMutationVariables
  478. >(MODIFY_ORDER, {
  479. input: {
  480. dryRun: true,
  481. orderId,
  482. adjustOrderLines: [{ orderLineId: order!.lines[0].id, quantity: 3 }],
  483. },
  484. });
  485. orderGuard.assertSuccess(modifyOrder);
  486. const expectedTotal = order!.totalWithTax + order!.lines[0].unitPriceWithTax * 2;
  487. expect(modifyOrder.lines[0].quantity).toBe(3);
  488. expect(modifyOrder.totalWithTax).toBe(expectedTotal);
  489. await assertOrderIsUnchanged(order!);
  490. });
  491. it('adjustOrderLines down', async () => {
  492. const { order } = await adminClient.query<Codegen.GetOrderQuery, Codegen.GetOrderQueryVariables>(
  493. GET_ORDER,
  494. {
  495. id: orderId,
  496. },
  497. );
  498. const { modifyOrder } = await adminClient.query<
  499. Codegen.ModifyOrderMutation,
  500. Codegen.ModifyOrderMutationVariables
  501. >(MODIFY_ORDER, {
  502. input: {
  503. dryRun: true,
  504. orderId,
  505. adjustOrderLines: [{ orderLineId: order!.lines[1].id, quantity: 1 }],
  506. },
  507. });
  508. orderGuard.assertSuccess(modifyOrder);
  509. const expectedTotal = order!.totalWithTax - order!.lines[1].unitPriceWithTax;
  510. expect(modifyOrder.lines[1].quantity).toBe(1);
  511. expect(modifyOrder.totalWithTax).toBe(expectedTotal);
  512. await assertOrderIsUnchanged(order!);
  513. });
  514. it('adjustOrderLines to zero', async () => {
  515. const { order } = await adminClient.query<Codegen.GetOrderQuery, Codegen.GetOrderQueryVariables>(
  516. GET_ORDER,
  517. {
  518. id: orderId,
  519. },
  520. );
  521. const { modifyOrder } = await adminClient.query<
  522. Codegen.ModifyOrderMutation,
  523. Codegen.ModifyOrderMutationVariables
  524. >(MODIFY_ORDER, {
  525. input: {
  526. dryRun: true,
  527. orderId,
  528. adjustOrderLines: [{ orderLineId: order!.lines[0].id, quantity: 0 }],
  529. },
  530. });
  531. orderGuard.assertSuccess(modifyOrder);
  532. const expectedTotal =
  533. order!.totalWithTax - order!.lines[0].unitPriceWithTax * order!.lines[0].quantity;
  534. expect(modifyOrder.totalWithTax).toBe(expectedTotal);
  535. expect(modifyOrder.lines[0].quantity).toBe(0);
  536. await assertOrderIsUnchanged(order!);
  537. });
  538. it('surcharge positive', async () => {
  539. const { order } = await adminClient.query<Codegen.GetOrderQuery, Codegen.GetOrderQueryVariables>(
  540. GET_ORDER,
  541. {
  542. id: orderId,
  543. },
  544. );
  545. const { modifyOrder } = await adminClient.query<
  546. Codegen.ModifyOrderMutation,
  547. Codegen.ModifyOrderMutationVariables
  548. >(MODIFY_ORDER, {
  549. input: {
  550. dryRun: true,
  551. orderId,
  552. surcharges: [
  553. {
  554. description: 'extra fee',
  555. sku: '123',
  556. price: 300,
  557. priceIncludesTax: true,
  558. taxRate: 20,
  559. taxDescription: 'VAT',
  560. },
  561. ],
  562. },
  563. });
  564. orderGuard.assertSuccess(modifyOrder);
  565. const expectedTotal = order!.totalWithTax + 300;
  566. expect(modifyOrder.totalWithTax).toBe(expectedTotal);
  567. expect(modifyOrder.surcharges.map(s => omit(s, ['id']))).toEqual([
  568. {
  569. description: 'extra fee',
  570. sku: '123',
  571. price: 250,
  572. priceWithTax: 300,
  573. taxRate: 20,
  574. },
  575. ]);
  576. await assertOrderIsUnchanged(order!);
  577. });
  578. it('surcharge negative', async () => {
  579. const { order } = await adminClient.query<Codegen.GetOrderQuery, Codegen.GetOrderQueryVariables>(
  580. GET_ORDER,
  581. {
  582. id: orderId,
  583. },
  584. );
  585. const { modifyOrder } = await adminClient.query<
  586. Codegen.ModifyOrderMutation,
  587. Codegen.ModifyOrderMutationVariables
  588. >(MODIFY_ORDER, {
  589. input: {
  590. dryRun: true,
  591. orderId,
  592. surcharges: [
  593. {
  594. description: 'special discount',
  595. sku: '123',
  596. price: -300,
  597. priceIncludesTax: true,
  598. taxRate: 20,
  599. taxDescription: 'VAT',
  600. },
  601. ],
  602. },
  603. });
  604. orderGuard.assertSuccess(modifyOrder);
  605. const expectedTotal = order!.totalWithTax + -300;
  606. expect(modifyOrder.totalWithTax).toBe(expectedTotal);
  607. expect(modifyOrder.surcharges.map(s => omit(s, ['id']))).toEqual([
  608. {
  609. description: 'special discount',
  610. sku: '123',
  611. price: -250,
  612. priceWithTax: -300,
  613. taxRate: 20,
  614. },
  615. ]);
  616. await assertOrderIsUnchanged(order!);
  617. });
  618. it('does not add a history entry', async () => {
  619. const { order } = await adminClient.query<Codegen.GetOrderQuery, Codegen.GetOrderQueryVariables>(
  620. GET_ORDER,
  621. {
  622. id: orderId,
  623. },
  624. );
  625. const { modifyOrder } = await adminClient.query<
  626. Codegen.ModifyOrderMutation,
  627. Codegen.ModifyOrderMutationVariables
  628. >(MODIFY_ORDER, {
  629. input: {
  630. dryRun: true,
  631. orderId,
  632. addItems: [{ productVariantId: 'T_5', quantity: 1 }],
  633. },
  634. });
  635. orderGuard.assertSuccess(modifyOrder);
  636. const { order: history } = await adminClient.query<
  637. Codegen.GetOrderHistoryQuery,
  638. Codegen.GetOrderHistoryQueryVariables
  639. >(GET_ORDER_HISTORY, {
  640. id: orderId,
  641. options: { filter: { type: { eq: HistoryEntryType.ORDER_MODIFIED } } },
  642. });
  643. orderGuard.assertSuccess(history);
  644. expect(history.history.totalItems).toBe(0);
  645. });
  646. });
  647. describe('wet run', () => {
  648. async function assertModifiedOrderIsPersisted(order: OrderWithModificationsFragment) {
  649. const { order: order2 } = await adminClient.query<
  650. Codegen.GetOrderQuery,
  651. Codegen.GetOrderQueryVariables
  652. >(GET_ORDER, {
  653. id: order.id,
  654. });
  655. expect(order2!.totalWithTax).toBe(order.totalWithTax);
  656. expect(order2!.lines.length).toBe(order.lines.length);
  657. expect(order2!.surcharges.length).toBe(order.surcharges.length);
  658. expect(order2!.payments!.length).toBe(order.payments!.length);
  659. expect(order2!.payments!.map(p => pick(p, ['id', 'amount', 'method']))).toEqual(
  660. order.payments!.map(p => pick(p, ['id', 'amount', 'method'])),
  661. );
  662. }
  663. it('addItems', async () => {
  664. const order = await createOrderAndTransitionToModifyingState([
  665. {
  666. productVariantId: 'T_1',
  667. quantity: 1,
  668. },
  669. ]);
  670. const { modifyOrder } = await adminClient.query<
  671. Codegen.ModifyOrderMutation,
  672. Codegen.ModifyOrderMutationVariables
  673. >(MODIFY_ORDER, {
  674. input: {
  675. dryRun: false,
  676. orderId: order.id,
  677. addItems: [{ productVariantId: 'T_5', quantity: 1 }],
  678. },
  679. });
  680. orderGuard.assertSuccess(modifyOrder);
  681. const priceDelta = Math.round(14374 * 1.2); // price of variant T_5
  682. const expectedTotal = order.totalWithTax + priceDelta;
  683. expect(modifyOrder.totalWithTax).toBe(expectedTotal);
  684. expect(modifyOrder.lines.length).toBe(order.lines.length + 1);
  685. expect(modifyOrder.modifications.length).toBe(1);
  686. expect(modifyOrder.modifications[0].priceChange).toBe(priceDelta);
  687. expect(modifyOrder.modifications[0].lines.length).toBe(1);
  688. expect(modifyOrder.modifications[0].lines).toEqual([
  689. { orderLineId: modifyOrder.lines[1].id, quantity: 1 },
  690. ]);
  691. await assertModifiedOrderIsPersisted(modifyOrder);
  692. });
  693. it('adjustOrderLines up', async () => {
  694. const order = await createOrderAndTransitionToModifyingState([
  695. {
  696. productVariantId: 'T_1',
  697. quantity: 1,
  698. },
  699. ]);
  700. const { modifyOrder } = await adminClient.query<
  701. Codegen.ModifyOrderMutation,
  702. Codegen.ModifyOrderMutationVariables
  703. >(MODIFY_ORDER, {
  704. input: {
  705. dryRun: false,
  706. orderId: order.id,
  707. adjustOrderLines: [{ orderLineId: order.lines[0].id, quantity: 2 }],
  708. },
  709. });
  710. orderGuard.assertSuccess(modifyOrder);
  711. const priceDelta = order.lines[0].unitPriceWithTax;
  712. const expectedTotal = order.totalWithTax + priceDelta;
  713. expect(modifyOrder.totalWithTax).toBe(expectedTotal);
  714. expect(modifyOrder.lines[0].quantity).toBe(2);
  715. expect(modifyOrder.modifications.length).toBe(1);
  716. expect(modifyOrder.modifications[0].priceChange).toBe(priceDelta);
  717. expect(modifyOrder.modifications[0].lines.length).toBe(1);
  718. expect(modifyOrder.lines[0].id).toEqual(modifyOrder.modifications[0].lines[0].orderLineId);
  719. await assertModifiedOrderIsPersisted(modifyOrder);
  720. });
  721. it('adjustOrderLines down', async () => {
  722. const order = await createOrderAndTransitionToModifyingState([
  723. {
  724. productVariantId: 'T_1',
  725. quantity: 2,
  726. },
  727. ]);
  728. const { modifyOrder } = await adminClient.query<
  729. Codegen.ModifyOrderMutation,
  730. Codegen.ModifyOrderMutationVariables
  731. >(MODIFY_ORDER, {
  732. input: {
  733. dryRun: false,
  734. orderId: order.id,
  735. adjustOrderLines: [{ orderLineId: order.lines[0].id, quantity: 1 }],
  736. refund: { paymentId: order.payments![0].id },
  737. },
  738. });
  739. orderGuard.assertSuccess(modifyOrder);
  740. const priceDelta = -order.lines[0].unitPriceWithTax;
  741. const expectedTotal = order.totalWithTax + priceDelta;
  742. expect(modifyOrder.totalWithTax).toBe(expectedTotal);
  743. expect(modifyOrder.lines[0].quantity).toBe(1);
  744. expect(modifyOrder.payments?.length).toBe(1);
  745. expect(modifyOrder.payments?.[0].refunds.length).toBe(1);
  746. expect(modifyOrder.payments?.[0].refunds[0]).toEqual({
  747. id: 'T_1',
  748. state: 'Pending',
  749. total: -priceDelta,
  750. paymentId: modifyOrder.payments?.[0].id,
  751. });
  752. expect(modifyOrder.modifications.length).toBe(1);
  753. expect(modifyOrder.modifications[0].priceChange).toBe(priceDelta);
  754. expect(modifyOrder.modifications[0].surcharges).toEqual(modifyOrder.surcharges.map(pick(['id'])));
  755. expect(modifyOrder.modifications[0].lines.length).toBe(1);
  756. expect(modifyOrder.lines[0].id).toEqual(modifyOrder.modifications[0].lines[0].orderLineId);
  757. await assertModifiedOrderIsPersisted(modifyOrder);
  758. });
  759. it('adjustOrderLines with changed customField value', async () => {
  760. const order = await createOrderAndTransitionToModifyingState([
  761. {
  762. productVariantId: 'T_1',
  763. quantity: 1,
  764. customFields: {
  765. color: 'green',
  766. },
  767. },
  768. ]);
  769. const { modifyOrder } = await adminClient.query<
  770. Codegen.ModifyOrderMutation,
  771. Codegen.ModifyOrderMutationVariables
  772. >(MODIFY_ORDER, {
  773. input: {
  774. dryRun: false,
  775. orderId: order.id,
  776. adjustOrderLines: [
  777. {
  778. orderLineId: order.lines[0].id,
  779. quantity: 1,
  780. customFields: { color: 'black' },
  781. } as any,
  782. ],
  783. },
  784. });
  785. orderGuard.assertSuccess(modifyOrder);
  786. expect(modifyOrder.lines.length).toBe(1);
  787. const { order: orderWithLines } = await adminClient.query(gql(GET_ORDER_WITH_CUSTOM_FIELDS), {
  788. id: order.id,
  789. });
  790. expect(orderWithLines.lines[0]).toEqual({
  791. id: order.lines[0].id,
  792. customFields: { color: 'black' },
  793. });
  794. });
  795. it('adjustOrderLines handles quantity correctly', async () => {
  796. await adminClient.query<
  797. Codegen.UpdateProductVariantsMutation,
  798. Codegen.UpdateProductVariantsMutationVariables
  799. >(UPDATE_PRODUCT_VARIANTS, {
  800. input: [
  801. {
  802. id: 'T_6',
  803. stockOnHand: 1,
  804. trackInventory: GlobalFlag.TRUE,
  805. },
  806. ],
  807. });
  808. const order = await createOrderAndTransitionToModifyingState([
  809. {
  810. productVariantId: 'T_6',
  811. quantity: 1,
  812. },
  813. ]);
  814. const { modifyOrder } = await adminClient.query<
  815. Codegen.ModifyOrderMutation,
  816. Codegen.ModifyOrderMutationVariables
  817. >(MODIFY_ORDER, {
  818. input: {
  819. dryRun: false,
  820. orderId: order.id,
  821. adjustOrderLines: [
  822. {
  823. orderLineId: order.lines[0].id,
  824. quantity: 1,
  825. },
  826. ],
  827. updateShippingAddress: {
  828. fullName: 'Jim',
  829. },
  830. },
  831. });
  832. orderGuard.assertSuccess(modifyOrder);
  833. });
  834. it('surcharge positive', async () => {
  835. const order = await createOrderAndTransitionToModifyingState([
  836. {
  837. productVariantId: 'T_1',
  838. quantity: 1,
  839. },
  840. ]);
  841. const { modifyOrder } = await adminClient.query<
  842. Codegen.ModifyOrderMutation,
  843. Codegen.ModifyOrderMutationVariables
  844. >(MODIFY_ORDER, {
  845. input: {
  846. dryRun: false,
  847. orderId: order.id,
  848. surcharges: [
  849. {
  850. description: 'extra fee',
  851. sku: '123',
  852. price: 300,
  853. priceIncludesTax: true,
  854. taxRate: 20,
  855. taxDescription: 'VAT',
  856. },
  857. ],
  858. },
  859. });
  860. orderGuard.assertSuccess(modifyOrder);
  861. const priceDelta = 300;
  862. const expectedTotal = order.totalWithTax + priceDelta;
  863. expect(modifyOrder.totalWithTax).toBe(expectedTotal);
  864. expect(modifyOrder.surcharges.map(s => omit(s, ['id']))).toEqual([
  865. {
  866. description: 'extra fee',
  867. sku: '123',
  868. price: 250,
  869. priceWithTax: 300,
  870. taxRate: 20,
  871. },
  872. ]);
  873. expect(modifyOrder.modifications.length).toBe(1);
  874. expect(modifyOrder.modifications[0].priceChange).toBe(priceDelta);
  875. expect(modifyOrder.modifications[0].surcharges).toEqual(modifyOrder.surcharges.map(pick(['id'])));
  876. await assertModifiedOrderIsPersisted(modifyOrder);
  877. });
  878. it('surcharge negative', async () => {
  879. const order = await createOrderAndTransitionToModifyingState([
  880. {
  881. productVariantId: 'T_1',
  882. quantity: 1,
  883. },
  884. ]);
  885. const { modifyOrder } = await adminClient.query<
  886. Codegen.ModifyOrderMutation,
  887. Codegen.ModifyOrderMutationVariables
  888. >(MODIFY_ORDER, {
  889. input: {
  890. dryRun: false,
  891. orderId: order.id,
  892. surcharges: [
  893. {
  894. description: 'special discount',
  895. sku: '123',
  896. price: -300,
  897. priceIncludesTax: true,
  898. taxRate: 20,
  899. taxDescription: 'VAT',
  900. },
  901. ],
  902. refund: {
  903. paymentId: order.payments![0].id,
  904. },
  905. },
  906. });
  907. orderGuard.assertSuccess(modifyOrder);
  908. const expectedTotal = order.totalWithTax + -300;
  909. expect(modifyOrder.totalWithTax).toBe(expectedTotal);
  910. expect(modifyOrder.surcharges.map(s => omit(s, ['id']))).toEqual([
  911. {
  912. description: 'special discount',
  913. sku: '123',
  914. price: -250,
  915. priceWithTax: -300,
  916. taxRate: 20,
  917. },
  918. ]);
  919. expect(modifyOrder.modifications.length).toBe(1);
  920. expect(modifyOrder.modifications[0].priceChange).toBe(-300);
  921. await assertModifiedOrderIsPersisted(modifyOrder);
  922. });
  923. it('update updateShippingAddress, recalculate shipping', async () => {
  924. const order = await createOrderAndTransitionToModifyingState([
  925. {
  926. productVariantId: 'T_1',
  927. quantity: 1,
  928. },
  929. ]);
  930. const { modifyOrder } = await adminClient.query<
  931. Codegen.ModifyOrderMutation,
  932. Codegen.ModifyOrderMutationVariables
  933. >(MODIFY_ORDER, {
  934. input: {
  935. dryRun: false,
  936. orderId: order.id,
  937. updateShippingAddress: {
  938. countryCode: 'US',
  939. },
  940. options: {
  941. recalculateShipping: true,
  942. },
  943. },
  944. });
  945. orderGuard.assertSuccess(modifyOrder);
  946. const priceDelta = SHIPPING_US - SHIPPING_OTHER;
  947. const expectedTotal = order.totalWithTax + priceDelta;
  948. expect(modifyOrder.totalWithTax).toBe(expectedTotal);
  949. expect(modifyOrder.shippingAddress?.countryCode).toBe('US');
  950. expect(modifyOrder.modifications.length).toBe(1);
  951. expect(modifyOrder.modifications[0].priceChange).toBe(priceDelta);
  952. await assertModifiedOrderIsPersisted(modifyOrder);
  953. });
  954. it('update updateShippingAddress, do not recalculate shipping', async () => {
  955. const order = await createOrderAndTransitionToModifyingState([
  956. {
  957. productVariantId: 'T_1',
  958. quantity: 1,
  959. },
  960. ]);
  961. const { modifyOrder } = await adminClient.query<
  962. Codegen.ModifyOrderMutation,
  963. Codegen.ModifyOrderMutationVariables
  964. >(MODIFY_ORDER, {
  965. input: {
  966. dryRun: false,
  967. orderId: order.id,
  968. updateShippingAddress: {
  969. countryCode: 'US',
  970. },
  971. options: {
  972. recalculateShipping: false,
  973. },
  974. },
  975. });
  976. orderGuard.assertSuccess(modifyOrder);
  977. const priceDelta = 0;
  978. const expectedTotal = order.totalWithTax + priceDelta;
  979. expect(modifyOrder.totalWithTax).toBe(expectedTotal);
  980. expect(modifyOrder.shippingAddress?.countryCode).toBe('US');
  981. expect(modifyOrder.modifications.length).toBe(1);
  982. expect(modifyOrder.modifications[0].priceChange).toBe(priceDelta);
  983. await assertModifiedOrderIsPersisted(modifyOrder);
  984. });
  985. it('update Order customFields', async () => {
  986. const order = await createOrderAndTransitionToModifyingState([
  987. {
  988. productVariantId: 'T_1',
  989. quantity: 1,
  990. },
  991. ]);
  992. const { modifyOrder } = await adminClient.query<
  993. Codegen.ModifyOrderMutation,
  994. Codegen.ModifyOrderMutationVariables
  995. >(MODIFY_ORDER, {
  996. input: {
  997. dryRun: false,
  998. orderId: order.id,
  999. customFields: {
  1000. points: 42,
  1001. },
  1002. } as any,
  1003. });
  1004. orderGuard.assertSuccess(modifyOrder);
  1005. const { order: orderWithCustomFields } = await adminClient.query(
  1006. gql(GET_ORDER_WITH_CUSTOM_FIELDS),
  1007. { id: order.id },
  1008. );
  1009. expect(orderWithCustomFields.customFields).toEqual({
  1010. points: 42,
  1011. });
  1012. });
  1013. it('adds a history entry', async () => {
  1014. const { order } = await adminClient.query<Codegen.GetOrderQuery, Codegen.GetOrderQueryVariables>(
  1015. GET_ORDER,
  1016. {
  1017. id: orderId,
  1018. },
  1019. );
  1020. const { modifyOrder } = await adminClient.query<
  1021. Codegen.ModifyOrderMutation,
  1022. Codegen.ModifyOrderMutationVariables
  1023. >(MODIFY_ORDER, {
  1024. input: {
  1025. dryRun: false,
  1026. orderId: order!.id,
  1027. addItems: [{ productVariantId: 'T_5', quantity: 1 }],
  1028. },
  1029. });
  1030. orderGuard.assertSuccess(modifyOrder);
  1031. const { order: history } = await adminClient.query<
  1032. Codegen.GetOrderHistoryQuery,
  1033. Codegen.GetOrderHistoryQueryVariables
  1034. >(GET_ORDER_HISTORY, {
  1035. id: orderId,
  1036. options: { filter: { type: { eq: HistoryEntryType.ORDER_MODIFIED } } },
  1037. });
  1038. orderGuard.assertSuccess(history);
  1039. expect(history.history.totalItems).toBe(1);
  1040. expect(history.history.items[0].data).toEqual({
  1041. modificationId: modifyOrder.modifications[0].id,
  1042. });
  1043. });
  1044. });
  1045. describe('additional payment handling', () => {
  1046. let orderId2: string;
  1047. beforeAll(async () => {
  1048. const order = await createOrderAndTransitionToModifyingState([
  1049. {
  1050. productVariantId: 'T_1',
  1051. quantity: 1,
  1052. },
  1053. ]);
  1054. const { modifyOrder } = await adminClient.query<
  1055. Codegen.ModifyOrderMutation,
  1056. Codegen.ModifyOrderMutationVariables
  1057. >(MODIFY_ORDER, {
  1058. input: {
  1059. dryRun: false,
  1060. orderId: order.id,
  1061. surcharges: [
  1062. {
  1063. description: 'extra fee',
  1064. sku: '123',
  1065. price: 300,
  1066. priceIncludesTax: true,
  1067. taxRate: 20,
  1068. taxDescription: 'VAT',
  1069. },
  1070. ],
  1071. },
  1072. });
  1073. orderGuard.assertSuccess(modifyOrder);
  1074. orderId2 = modifyOrder.id;
  1075. });
  1076. it('cannot transition back to original state if no payment is set', async () => {
  1077. const transitionOrderToState = await adminTransitionOrderToState(orderId2, 'PaymentSettled');
  1078. orderGuard.assertErrorResult(transitionOrderToState);
  1079. expect(transitionOrderToState!.errorCode).toBe(ErrorCode.ORDER_STATE_TRANSITION_ERROR);
  1080. expect(transitionOrderToState!.transitionError).toBe(
  1081. 'Can only transition to the "ArrangingAdditionalPayment" state',
  1082. );
  1083. });
  1084. it('can transition to ArrangingAdditionalPayment state', async () => {
  1085. const transitionOrderToState = await adminTransitionOrderToState(
  1086. orderId2,
  1087. 'ArrangingAdditionalPayment',
  1088. );
  1089. orderGuard.assertSuccess(transitionOrderToState);
  1090. expect(transitionOrderToState.state).toBe('ArrangingAdditionalPayment');
  1091. });
  1092. it('cannot transition from ArrangingAdditionalPayment when total not covered by Payments', async () => {
  1093. const transitionOrderToState = await adminTransitionOrderToState(orderId2, 'PaymentSettled');
  1094. orderGuard.assertErrorResult(transitionOrderToState);
  1095. expect(transitionOrderToState!.errorCode).toBe(ErrorCode.ORDER_STATE_TRANSITION_ERROR);
  1096. expect(transitionOrderToState!.transitionError).toBe(
  1097. 'Cannot transition away from "ArrangingAdditionalPayment" unless Order total is covered by Payments',
  1098. );
  1099. });
  1100. it('addManualPaymentToOrder', async () => {
  1101. const { addManualPaymentToOrder } = await adminClient.query<
  1102. Codegen.AddManualPaymentMutation,
  1103. Codegen.AddManualPaymentMutationVariables
  1104. >(ADD_MANUAL_PAYMENT, {
  1105. input: {
  1106. orderId: orderId2,
  1107. method: 'test',
  1108. transactionId: 'ABC123',
  1109. metadata: {
  1110. foo: 'bar',
  1111. },
  1112. },
  1113. });
  1114. orderGuard.assertSuccess(addManualPaymentToOrder);
  1115. expect(addManualPaymentToOrder.payments?.length).toBe(2);
  1116. expect(omit(addManualPaymentToOrder.payments![1], ['id'])).toEqual({
  1117. transactionId: 'ABC123',
  1118. state: 'Settled',
  1119. amount: 300,
  1120. method: 'test',
  1121. metadata: {
  1122. foo: 'bar',
  1123. },
  1124. refunds: [],
  1125. });
  1126. expect(addManualPaymentToOrder.modifications[0].isSettled).toBe(true);
  1127. expect(addManualPaymentToOrder.modifications[0].payment?.id).toBe(
  1128. addManualPaymentToOrder.payments![1].id,
  1129. );
  1130. });
  1131. it('transition back to original state', async () => {
  1132. const transitionOrderToState = await adminTransitionOrderToState(orderId2, 'PaymentSettled');
  1133. orderGuard.assertSuccess(transitionOrderToState);
  1134. expect(transitionOrderToState.state).toBe('PaymentSettled');
  1135. });
  1136. });
  1137. describe('refund handling', () => {
  1138. let orderId3: string;
  1139. beforeAll(async () => {
  1140. const order = await createOrderAndTransitionToModifyingState([
  1141. {
  1142. productVariantId: 'T_1',
  1143. quantity: 1,
  1144. },
  1145. ]);
  1146. const { modifyOrder } = await adminClient.query<
  1147. Codegen.ModifyOrderMutation,
  1148. Codegen.ModifyOrderMutationVariables
  1149. >(MODIFY_ORDER, {
  1150. input: {
  1151. dryRun: false,
  1152. orderId: order.id,
  1153. surcharges: [
  1154. {
  1155. description: 'discount',
  1156. sku: '123',
  1157. price: -300,
  1158. priceIncludesTax: true,
  1159. taxRate: 20,
  1160. taxDescription: 'VAT',
  1161. },
  1162. ],
  1163. refund: {
  1164. paymentId: order.payments![0].id,
  1165. reason: 'discount',
  1166. },
  1167. },
  1168. });
  1169. orderGuard.assertSuccess(modifyOrder);
  1170. orderId3 = modifyOrder.id;
  1171. });
  1172. it('modification is settled', async () => {
  1173. const { order } = await adminClient.query<
  1174. Codegen.GetOrderWithModificationsQuery,
  1175. Codegen.GetOrderWithModificationsQueryVariables
  1176. >(GET_ORDER_WITH_MODIFICATIONS, { id: orderId3 });
  1177. expect(order?.modifications.length).toBe(1);
  1178. expect(order?.modifications[0].isSettled).toBe(true);
  1179. });
  1180. it('cannot transition to ArrangingAdditionalPayment state if no payment is needed', async () => {
  1181. const transitionOrderToState = await adminTransitionOrderToState(
  1182. orderId3,
  1183. 'ArrangingAdditionalPayment',
  1184. );
  1185. orderGuard.assertErrorResult(transitionOrderToState);
  1186. expect(transitionOrderToState!.errorCode).toBe(ErrorCode.ORDER_STATE_TRANSITION_ERROR);
  1187. expect(transitionOrderToState!.transitionError).toBe(
  1188. 'Cannot transition Order to the "ArrangingAdditionalPayment" state as no additional payments are needed',
  1189. );
  1190. });
  1191. it('can transition to original state', async () => {
  1192. const transitionOrderToState = await adminTransitionOrderToState(orderId3, 'PaymentSettled');
  1193. orderGuard.assertSuccess(transitionOrderToState);
  1194. expect(transitionOrderToState.state).toBe('PaymentSettled');
  1195. const { order } = await adminClient.query<Codegen.GetOrderQuery, Codegen.GetOrderQueryVariables>(
  1196. GET_ORDER,
  1197. {
  1198. id: orderId3,
  1199. },
  1200. );
  1201. expect(order?.payments![0].refunds.length).toBe(1);
  1202. expect(order?.payments![0].refunds[0].total).toBe(300);
  1203. expect(order?.payments![0].refunds[0].reason).toBe('discount');
  1204. });
  1205. });
  1206. // https://github.com/vendure-ecommerce/vendure/issues/1753
  1207. describe('refunds for multiple payments', () => {
  1208. let orderId2: string;
  1209. let orderLineId: string;
  1210. let additionalPaymentId: string;
  1211. beforeAll(async () => {
  1212. await adminClient.query<
  1213. Codegen.CreatePromotionMutation,
  1214. Codegen.CreatePromotionMutationVariables
  1215. >(CREATE_PROMOTION, {
  1216. input: {
  1217. couponCode: '5OFF',
  1218. enabled: true,
  1219. conditions: [],
  1220. actions: [
  1221. {
  1222. code: orderFixedDiscount.code,
  1223. arguments: [{ name: 'discount', value: '500' }],
  1224. },
  1225. ],
  1226. translations: [{ languageCode: LanguageCode.en, name: '$5 off' }],
  1227. },
  1228. });
  1229. await shopClient.asUserWithCredentials('trevor_donnelly96@hotmail.com', 'test');
  1230. await shopClient.query(gql(ADD_ITEM_TO_ORDER_WITH_CUSTOM_FIELDS), {
  1231. productVariantId: 'T_5',
  1232. quantity: 1,
  1233. } as any);
  1234. await proceedToArrangingPayment(shopClient);
  1235. const order = await addPaymentToOrder(shopClient, testSuccessfulPaymentMethod);
  1236. orderGuard.assertSuccess(order);
  1237. orderLineId = order.lines[0].id;
  1238. orderId2 = order.id;
  1239. const transitionOrderToState = await adminTransitionOrderToState(orderId2, 'Modifying');
  1240. orderGuard.assertSuccess(transitionOrderToState);
  1241. const { modifyOrder } = await adminClient.query<
  1242. Codegen.ModifyOrderMutation,
  1243. Codegen.ModifyOrderMutationVariables
  1244. >(MODIFY_ORDER, {
  1245. input: {
  1246. dryRun: false,
  1247. orderId: orderId2,
  1248. adjustOrderLines: [{ orderLineId, quantity: 2 }],
  1249. },
  1250. });
  1251. orderGuard.assertSuccess(modifyOrder);
  1252. await adminTransitionOrderToState(orderId2, 'ArrangingAdditionalPayment');
  1253. const { addManualPaymentToOrder } = await adminClient.query<
  1254. Codegen.AddManualPaymentMutation,
  1255. Codegen.AddManualPaymentMutationVariables
  1256. >(ADD_MANUAL_PAYMENT, {
  1257. input: {
  1258. orderId: orderId2,
  1259. method: 'test',
  1260. transactionId: 'ABC123',
  1261. metadata: {
  1262. foo: 'bar',
  1263. },
  1264. },
  1265. });
  1266. orderGuard.assertSuccess(addManualPaymentToOrder);
  1267. additionalPaymentId = addManualPaymentToOrder.payments![1].id!;
  1268. const transitionOrderToState2 = await adminTransitionOrderToState(orderId2, 'PaymentSettled');
  1269. orderGuard.assertSuccess(transitionOrderToState2);
  1270. expect(transitionOrderToState2.state).toBe('PaymentSettled');
  1271. });
  1272. it('apply couponCode to create first refund', async () => {
  1273. const transitionOrderToState = await adminTransitionOrderToState(orderId2, 'Modifying');
  1274. orderGuard.assertSuccess(transitionOrderToState);
  1275. const { modifyOrder } = await adminClient.query<
  1276. Codegen.ModifyOrderMutation,
  1277. Codegen.ModifyOrderMutationVariables
  1278. >(MODIFY_ORDER, {
  1279. input: {
  1280. dryRun: false,
  1281. orderId: orderId2,
  1282. couponCodes: ['5OFF'],
  1283. refund: {
  1284. paymentId: additionalPaymentId,
  1285. reason: 'test',
  1286. },
  1287. },
  1288. });
  1289. orderGuard.assertSuccess(modifyOrder);
  1290. expect(modifyOrder.payments?.length).toBe(2);
  1291. expect(modifyOrder?.payments?.find(p => p.id === additionalPaymentId)?.refunds).toEqual([
  1292. {
  1293. id: 'T_4',
  1294. paymentId: additionalPaymentId,
  1295. state: 'Pending',
  1296. total: 600,
  1297. },
  1298. ]);
  1299. expect(modifyOrder.totalWithTax).toBe(getOrderPaymentsTotalWithRefunds(modifyOrder));
  1300. });
  1301. it('reduce quantity to create second refund', async () => {
  1302. const { modifyOrder } = await adminClient.query<
  1303. Codegen.ModifyOrderMutation,
  1304. Codegen.ModifyOrderMutationVariables
  1305. >(MODIFY_ORDER, {
  1306. input: {
  1307. dryRun: false,
  1308. orderId: orderId2,
  1309. adjustOrderLines: [{ orderLineId, quantity: 1 }],
  1310. refund: {
  1311. paymentId: additionalPaymentId,
  1312. reason: 'test 2',
  1313. },
  1314. },
  1315. });
  1316. orderGuard.assertSuccess(modifyOrder);
  1317. expect(
  1318. modifyOrder?.payments?.find(p => p.id === additionalPaymentId)?.refunds.sort(sortById),
  1319. ).toEqual([
  1320. {
  1321. id: 'T_4',
  1322. paymentId: additionalPaymentId,
  1323. state: 'Pending',
  1324. total: 600,
  1325. },
  1326. {
  1327. id: 'T_5',
  1328. paymentId: additionalPaymentId,
  1329. state: 'Pending',
  1330. total: 16649,
  1331. },
  1332. ]);
  1333. // Note: During the big refactor of the OrderItem entity, the "total" value in the following
  1334. // assertion was changed from `300` to `600`. This is due to a change in the way we calculate
  1335. // refunds on pro-rated discounts. Previously, the pro-ration was not recalculated prior to
  1336. // the refund being calculated, so the individual OrderItem had only 1/2 the full order discount
  1337. // applied to it (300). Now, the pro-ration is applied to the single remaining item and therefore the
  1338. // entire discount of 600 gets moved over to the remaining item.
  1339. expect(modifyOrder?.payments?.find(p => p.id !== additionalPaymentId)?.refunds).toEqual([
  1340. {
  1341. id: 'T_6',
  1342. paymentId: 'T_15',
  1343. state: 'Pending',
  1344. total: 600,
  1345. },
  1346. ]);
  1347. expect(modifyOrder.totalWithTax).toBe(getOrderPaymentsTotalWithRefunds(modifyOrder));
  1348. });
  1349. });
  1350. // https://github.com/vendure-ecommerce/vendure/issues/688 - 4th point
  1351. it('correct additional payment when discounts applied', async () => {
  1352. await adminClient.query<Codegen.CreatePromotionMutation, Codegen.CreatePromotionMutationVariables>(
  1353. CREATE_PROMOTION,
  1354. {
  1355. input: {
  1356. couponCode: '5OFF',
  1357. enabled: true,
  1358. conditions: [],
  1359. actions: [
  1360. {
  1361. code: orderFixedDiscount.code,
  1362. arguments: [{ name: 'discount', value: '500' }],
  1363. },
  1364. ],
  1365. translations: [{ languageCode: LanguageCode.en, name: '$5 off' }],
  1366. },
  1367. },
  1368. );
  1369. await shopClient.asUserWithCredentials('trevor_donnelly96@hotmail.com', 'test');
  1370. await shopClient.query(gql(ADD_ITEM_TO_ORDER_WITH_CUSTOM_FIELDS), {
  1371. productVariantId: 'T_1',
  1372. quantity: 1,
  1373. } as any);
  1374. await shopClient.query<
  1375. CodegenShop.ApplyCouponCodeMutation,
  1376. CodegenShop.ApplyCouponCodeMutationVariables
  1377. >(APPLY_COUPON_CODE, {
  1378. couponCode: '5OFF',
  1379. });
  1380. await proceedToArrangingPayment(shopClient);
  1381. const order = await addPaymentToOrder(shopClient, testSuccessfulPaymentMethod);
  1382. orderGuard.assertSuccess(order);
  1383. const originalTotalWithTax = order.totalWithTax;
  1384. const surcharge = 300;
  1385. const transitionOrderToState = await adminTransitionOrderToState(order.id, 'Modifying');
  1386. orderGuard.assertSuccess(transitionOrderToState);
  1387. expect(transitionOrderToState.state).toBe('Modifying');
  1388. const { modifyOrder } = await adminClient.query<
  1389. Codegen.ModifyOrderMutation,
  1390. Codegen.ModifyOrderMutationVariables
  1391. >(MODIFY_ORDER, {
  1392. input: {
  1393. dryRun: false,
  1394. orderId: order.id,
  1395. surcharges: [
  1396. {
  1397. description: 'extra fee',
  1398. sku: '123',
  1399. price: surcharge,
  1400. priceIncludesTax: true,
  1401. taxRate: 20,
  1402. taxDescription: 'VAT',
  1403. },
  1404. ],
  1405. },
  1406. });
  1407. orderGuard.assertSuccess(modifyOrder);
  1408. expect(modifyOrder.totalWithTax).toBe(originalTotalWithTax + surcharge);
  1409. });
  1410. // https://github.com/vendure-ecommerce/vendure/issues/872
  1411. describe('correct price calculations when prices include tax', () => {
  1412. async function modifyOrderLineQuantity(order: TestOrderWithPaymentsFragment) {
  1413. const transitionOrderToState = await adminTransitionOrderToState(order.id, 'Modifying');
  1414. orderGuard.assertSuccess(transitionOrderToState);
  1415. expect(transitionOrderToState.state).toBe('Modifying');
  1416. const { modifyOrder } = await adminClient.query<
  1417. Codegen.ModifyOrderMutation,
  1418. Codegen.ModifyOrderMutationVariables
  1419. >(MODIFY_ORDER, {
  1420. input: {
  1421. dryRun: true,
  1422. orderId: order.id,
  1423. adjustOrderLines: [{ orderLineId: order.lines[0].id, quantity: 2 }],
  1424. },
  1425. });
  1426. orderGuard.assertSuccess(modifyOrder);
  1427. return modifyOrder;
  1428. }
  1429. beforeAll(async () => {
  1430. await adminClient.query<Codegen.UpdateChannelMutation, Codegen.UpdateChannelMutationVariables>(
  1431. UPDATE_CHANNEL,
  1432. {
  1433. input: {
  1434. id: 'T_1',
  1435. pricesIncludeTax: true,
  1436. },
  1437. },
  1438. );
  1439. });
  1440. it('without promotion', async () => {
  1441. await shopClient.asUserWithCredentials('hayden.zieme12@hotmail.com', 'test');
  1442. await shopClient.query(gql(ADD_ITEM_TO_ORDER_WITH_CUSTOM_FIELDS), {
  1443. productVariantId: 'T_1',
  1444. quantity: 1,
  1445. } as any);
  1446. await proceedToArrangingPayment(shopClient);
  1447. const order = await addPaymentToOrder(shopClient, testSuccessfulPaymentMethod);
  1448. orderGuard.assertSuccess(order);
  1449. const modifyOrder = await modifyOrderLineQuantity(order);
  1450. expect(modifyOrder.lines[0].linePriceWithTax).toBe(order.lines[0].linePriceWithTax * 2);
  1451. });
  1452. it('with promotion', async () => {
  1453. await adminClient.query<
  1454. Codegen.CreatePromotionMutation,
  1455. Codegen.CreatePromotionMutationVariables
  1456. >(CREATE_PROMOTION, {
  1457. input: {
  1458. couponCode: 'HALF',
  1459. enabled: true,
  1460. conditions: [],
  1461. actions: [
  1462. {
  1463. code: productsPercentageDiscount.code,
  1464. arguments: [
  1465. { name: 'discount', value: '50' },
  1466. { name: 'productVariantIds', value: JSON.stringify(['T_1']) },
  1467. ],
  1468. },
  1469. ],
  1470. translations: [{ languageCode: LanguageCode.en, name: 'half price' }],
  1471. },
  1472. });
  1473. await shopClient.asUserWithCredentials('trevor_donnelly96@hotmail.com', 'test');
  1474. await shopClient.query(gql(ADD_ITEM_TO_ORDER_WITH_CUSTOM_FIELDS), {
  1475. productVariantId: 'T_1',
  1476. quantity: 1,
  1477. } as any);
  1478. await shopClient.query<
  1479. CodegenShop.ApplyCouponCodeMutation,
  1480. CodegenShop.ApplyCouponCodeMutationVariables
  1481. >(APPLY_COUPON_CODE, {
  1482. couponCode: 'HALF',
  1483. });
  1484. await proceedToArrangingPayment(shopClient);
  1485. const order = await addPaymentToOrder(shopClient, testSuccessfulPaymentMethod);
  1486. orderGuard.assertSuccess(order);
  1487. const modifyOrder = await modifyOrderLineQuantity(order);
  1488. expect(modifyOrder.lines[0].discountedLinePriceWithTax).toBe(
  1489. modifyOrder.lines[0].linePriceWithTax / 2,
  1490. );
  1491. expect(modifyOrder.lines[0].linePriceWithTax).toBe(order.lines[0].linePriceWithTax * 2);
  1492. });
  1493. });
  1494. describe('refund handling when promotions are active on order', () => {
  1495. // https://github.com/vendure-ecommerce/vendure/issues/890
  1496. it('refunds correct amount when order-level promotion applied', async () => {
  1497. await adminClient.query<
  1498. Codegen.CreatePromotionMutation,
  1499. Codegen.CreatePromotionMutationVariables
  1500. >(CREATE_PROMOTION, {
  1501. input: {
  1502. couponCode: '5OFF2',
  1503. enabled: true,
  1504. conditions: [],
  1505. actions: [
  1506. {
  1507. code: orderFixedDiscount.code,
  1508. arguments: [{ name: 'discount', value: '500' }],
  1509. },
  1510. ],
  1511. translations: [{ languageCode: LanguageCode.en, name: '$5 off' }],
  1512. },
  1513. });
  1514. await shopClient.asUserWithCredentials('trevor_donnelly96@hotmail.com', 'test');
  1515. await shopClient.query(gql(ADD_ITEM_TO_ORDER_WITH_CUSTOM_FIELDS), {
  1516. productVariantId: 'T_1',
  1517. quantity: 2,
  1518. } as any);
  1519. await shopClient.query<
  1520. CodegenShop.ApplyCouponCodeMutation,
  1521. CodegenShop.ApplyCouponCodeMutationVariables
  1522. >(APPLY_COUPON_CODE, {
  1523. couponCode: '5OFF2',
  1524. });
  1525. await proceedToArrangingPayment(shopClient);
  1526. const order = await addPaymentToOrder(shopClient, testSuccessfulPaymentMethod);
  1527. orderGuard.assertSuccess(order);
  1528. const originalTotalWithTax = order.totalWithTax;
  1529. const transitionOrderToState = await adminTransitionOrderToState(order.id, 'Modifying');
  1530. orderGuard.assertSuccess(transitionOrderToState);
  1531. expect(transitionOrderToState.state).toBe('Modifying');
  1532. const { modifyOrder } = await adminClient.query<
  1533. Codegen.ModifyOrderMutation,
  1534. Codegen.ModifyOrderMutationVariables
  1535. >(MODIFY_ORDER, {
  1536. input: {
  1537. dryRun: false,
  1538. orderId: order.id,
  1539. adjustOrderLines: [{ orderLineId: order.lines[0].id, quantity: 1 }],
  1540. refund: {
  1541. paymentId: order.payments![0].id,
  1542. reason: 'requested',
  1543. },
  1544. },
  1545. });
  1546. orderGuard.assertSuccess(modifyOrder);
  1547. expect(modifyOrder.totalWithTax).toBe(
  1548. originalTotalWithTax - order.lines[0].proratedUnitPriceWithTax,
  1549. );
  1550. expect(modifyOrder.payments![0].refunds[0].total).toBe(order.lines[0].proratedUnitPriceWithTax);
  1551. expect(modifyOrder.totalWithTax).toBe(getOrderPaymentsTotalWithRefunds(modifyOrder));
  1552. });
  1553. // https://github.com/vendure-ecommerce/vendure/issues/1865
  1554. describe('issue 1865', () => {
  1555. const promoDiscount = 5000;
  1556. let promoId: string;
  1557. let orderId2: string;
  1558. beforeAll(async () => {
  1559. const { createPromotion } = await adminClient.query<
  1560. Codegen.CreatePromotionMutation,
  1561. Codegen.CreatePromotionMutationVariables
  1562. >(CREATE_PROMOTION, {
  1563. input: {
  1564. enabled: true,
  1565. conditions: [
  1566. {
  1567. code: minimumOrderAmount.code,
  1568. arguments: [
  1569. { name: 'amount', value: '10000' },
  1570. { name: 'taxInclusive', value: 'true' },
  1571. ],
  1572. },
  1573. ],
  1574. actions: [
  1575. {
  1576. code: orderFixedDiscount.code,
  1577. arguments: [{ name: 'discount', value: JSON.stringify(promoDiscount) }],
  1578. },
  1579. ],
  1580. translations: [{ languageCode: LanguageCode.en, name: '50 off orders over 100' }],
  1581. },
  1582. });
  1583. promoId = (createPromotion as any).id;
  1584. });
  1585. afterAll(async () => {
  1586. await adminClient.query<
  1587. Codegen.DeletePromotionMutation,
  1588. Codegen.DeletePromotionMutationVariables
  1589. >(DELETE_PROMOTION, {
  1590. id: promoId,
  1591. });
  1592. });
  1593. it('refund handling when order-level promotion becomes invalid on modification', async () => {
  1594. const { productVariants } = await adminClient.query<
  1595. Codegen.GetProductVariantListQuery,
  1596. Codegen.GetProductVariantListQueryVariables
  1597. >(GET_PRODUCT_VARIANT_LIST, {
  1598. options: {
  1599. filter: {
  1600. name: { contains: 'football' },
  1601. },
  1602. },
  1603. });
  1604. const football = productVariants.items[0];
  1605. await shopClient.query(gql(ADD_ITEM_TO_ORDER_WITH_CUSTOM_FIELDS), {
  1606. productVariantId: football.id,
  1607. quantity: 2,
  1608. } as any);
  1609. await proceedToArrangingPayment(shopClient);
  1610. const order = await addPaymentToOrder(shopClient, testSuccessfulPaymentMethod);
  1611. orderGuard.assertSuccess(order);
  1612. orderId2 = order.id;
  1613. expect(order.discounts.length).toBe(1);
  1614. expect(order.discounts[0].amountWithTax).toBe(-promoDiscount);
  1615. const shippingPrice = order.shippingWithTax;
  1616. const expectedTotal = football.priceWithTax * 2 + shippingPrice - promoDiscount;
  1617. expect(order.totalWithTax).toBe(expectedTotal);
  1618. const originalTotalWithTax = order.totalWithTax;
  1619. const transitionOrderToState = await adminTransitionOrderToState(order.id, 'Modifying');
  1620. orderGuard.assertSuccess(transitionOrderToState);
  1621. expect(transitionOrderToState.state).toBe('Modifying');
  1622. const { modifyOrder } = await adminClient.query<
  1623. Codegen.ModifyOrderMutation,
  1624. Codegen.ModifyOrderMutationVariables
  1625. >(MODIFY_ORDER, {
  1626. input: {
  1627. dryRun: false,
  1628. orderId: order.id,
  1629. adjustOrderLines: [{ orderLineId: order.lines[0].id, quantity: 1 }],
  1630. refund: {
  1631. paymentId: order.payments![0].id,
  1632. reason: 'requested',
  1633. },
  1634. },
  1635. });
  1636. orderGuard.assertSuccess(modifyOrder);
  1637. const expectedNewTotal = order.lines[0].unitPriceWithTax + shippingPrice;
  1638. expect(modifyOrder.totalWithTax).toBe(expectedNewTotal);
  1639. expect(modifyOrder.payments![0].refunds[0].total).toBe(expectedTotal - expectedNewTotal);
  1640. expect(modifyOrder.totalWithTax).toBe(getOrderPaymentsTotalWithRefunds(modifyOrder));
  1641. });
  1642. it('transition back to original state', async () => {
  1643. const transitionOrderToState2 = await adminTransitionOrderToState(orderId2, 'PaymentSettled');
  1644. orderGuard.assertSuccess(transitionOrderToState2);
  1645. expect(transitionOrderToState2.state).toBe('PaymentSettled');
  1646. });
  1647. it('order no longer has promotions', async () => {
  1648. const { order } = await adminClient.query<
  1649. Codegen.GetOrderWithModificationsQuery,
  1650. Codegen.GetOrderWithModificationsQueryVariables
  1651. >(GET_ORDER_WITH_MODIFICATIONS, { id: orderId2 });
  1652. expect(order?.promotions).toEqual([]);
  1653. });
  1654. it('order no longer has discounts', async () => {
  1655. const { order } = await adminClient.query<
  1656. Codegen.GetOrderWithModificationsQuery,
  1657. Codegen.GetOrderWithModificationsQueryVariables
  1658. >(GET_ORDER_WITH_MODIFICATIONS, { id: orderId2 });
  1659. expect(order?.discounts).toEqual([]);
  1660. });
  1661. });
  1662. });
  1663. // https://github.com/vendure-ecommerce/vendure/issues/1197
  1664. describe('refund on shipping when change made to shippingAddress', () => {
  1665. let order: OrderWithModificationsFragment;
  1666. beforeAll(async () => {
  1667. const createdOrder = await createOrderAndTransitionToModifyingState([
  1668. {
  1669. productVariantId: 'T_1',
  1670. quantity: 1,
  1671. },
  1672. ]);
  1673. const { modifyOrder } = await adminClient.query<
  1674. Codegen.ModifyOrderMutation,
  1675. Codegen.ModifyOrderMutationVariables
  1676. >(MODIFY_ORDER, {
  1677. input: {
  1678. dryRun: false,
  1679. orderId: createdOrder.id,
  1680. updateShippingAddress: {
  1681. countryCode: 'GB',
  1682. },
  1683. refund: {
  1684. paymentId: createdOrder.payments![0].id,
  1685. reason: 'discount',
  1686. },
  1687. },
  1688. });
  1689. orderGuard.assertSuccess(modifyOrder);
  1690. order = modifyOrder;
  1691. });
  1692. it('creates a Refund with the correct amount', async () => {
  1693. expect(order.payments?.[0].refunds[0].total).toBe(SHIPPING_OTHER - SHIPPING_GB);
  1694. });
  1695. it('allows transition to PaymentSettled', async () => {
  1696. const transitionOrderToState = await adminTransitionOrderToState(order.id, 'PaymentSettled');
  1697. orderGuard.assertSuccess(transitionOrderToState);
  1698. expect(transitionOrderToState.state).toBe('PaymentSettled');
  1699. });
  1700. });
  1701. // https://github.com/vendure-ecommerce/vendure/issues/1210
  1702. describe('updating stock levels', () => {
  1703. async function getVariant(id: 'T_1' | 'T_2' | 'T_3') {
  1704. const { product } = await adminClient.query<
  1705. Codegen.GetStockMovementQuery,
  1706. Codegen.GetStockMovementQueryVariables
  1707. >(GET_STOCK_MOVEMENT, {
  1708. id: 'T_1',
  1709. });
  1710. return product!.variants.find(v => v.id === id)!;
  1711. }
  1712. let orderId4: string;
  1713. let orderId5: string;
  1714. it('updates stock when increasing quantity before fulfillment', async () => {
  1715. const variant1 = await getVariant('T_2');
  1716. expect(variant1.stockOnHand).toBe(100);
  1717. expect(variant1.stockAllocated).toBe(0);
  1718. const order = await createOrderAndTransitionToModifyingState([
  1719. {
  1720. productVariantId: 'T_2',
  1721. quantity: 1,
  1722. },
  1723. ]);
  1724. orderId4 = order.id;
  1725. const variant2 = await getVariant('T_2');
  1726. expect(variant2.stockOnHand).toBe(100);
  1727. expect(variant2.stockAllocated).toBe(1);
  1728. const { modifyOrder } = await adminClient.query<
  1729. Codegen.ModifyOrderMutation,
  1730. Codegen.ModifyOrderMutationVariables
  1731. >(MODIFY_ORDER, {
  1732. input: {
  1733. dryRun: false,
  1734. orderId: order.id,
  1735. adjustOrderLines: [{ orderLineId: order.lines[0].id, quantity: 2 }],
  1736. },
  1737. });
  1738. orderGuard.assertSuccess(modifyOrder);
  1739. const variant3 = await getVariant('T_2');
  1740. expect(variant3.stockOnHand).toBe(100);
  1741. expect(variant3.stockAllocated).toBe(2);
  1742. });
  1743. it('updates stock when increasing quantity after fulfillment', async () => {
  1744. const result = await adminTransitionOrderToState(orderId4, 'ArrangingAdditionalPayment');
  1745. orderGuard.assertSuccess(result);
  1746. expect(result.state).toBe('ArrangingAdditionalPayment');
  1747. const { order } = await adminClient.query<Codegen.GetOrderQuery, Codegen.GetOrderQueryVariables>(
  1748. GET_ORDER,
  1749. {
  1750. id: orderId4,
  1751. },
  1752. );
  1753. const { addManualPaymentToOrder } = await adminClient.query<
  1754. Codegen.AddManualPaymentMutation,
  1755. Codegen.AddManualPaymentMutationVariables
  1756. >(ADD_MANUAL_PAYMENT, {
  1757. input: {
  1758. orderId: orderId4,
  1759. method: 'test',
  1760. transactionId: 'ABC123',
  1761. metadata: {
  1762. foo: 'bar',
  1763. },
  1764. },
  1765. });
  1766. orderGuard.assertSuccess(addManualPaymentToOrder);
  1767. await adminTransitionOrderToState(orderId4, 'PaymentSettled');
  1768. await adminClient.query<
  1769. Codegen.CreateFulfillmentMutation,
  1770. Codegen.CreateFulfillmentMutationVariables
  1771. >(CREATE_FULFILLMENT, {
  1772. input: {
  1773. lines: order?.lines.map(l => ({ orderLineId: l.id, quantity: l.quantity })) ?? [],
  1774. handler: {
  1775. code: manualFulfillmentHandler.code,
  1776. arguments: [
  1777. { name: 'method', value: 'test method' },
  1778. { name: 'trackingCode', value: 'ABC123' },
  1779. ],
  1780. },
  1781. },
  1782. });
  1783. const variant1 = await getVariant('T_2');
  1784. expect(variant1.stockOnHand).toBe(98);
  1785. expect(variant1.stockAllocated).toBe(0);
  1786. await adminTransitionOrderToState(orderId4, 'Modifying');
  1787. const { modifyOrder } = await adminClient.query<
  1788. Codegen.ModifyOrderMutation,
  1789. Codegen.ModifyOrderMutationVariables
  1790. >(MODIFY_ORDER, {
  1791. input: {
  1792. dryRun: false,
  1793. orderId: order!.id,
  1794. adjustOrderLines: [{ orderLineId: order!.lines[0].id, quantity: 3 }],
  1795. },
  1796. });
  1797. orderGuard.assertSuccess(modifyOrder);
  1798. const variant2 = await getVariant('T_2');
  1799. expect(variant2.stockOnHand).toBe(98);
  1800. expect(variant2.stockAllocated).toBe(1);
  1801. const { order: order2 } = await adminClient.query<
  1802. Codegen.GetOrderQuery,
  1803. Codegen.GetOrderQueryVariables
  1804. >(GET_ORDER, {
  1805. id: orderId4,
  1806. });
  1807. });
  1808. it('updates stock when adding item before fulfillment', async () => {
  1809. const variant1 = await getVariant('T_3');
  1810. expect(variant1.stockOnHand).toBe(100);
  1811. expect(variant1.stockAllocated).toBe(0);
  1812. const order = await createOrderAndTransitionToModifyingState([
  1813. {
  1814. productVariantId: 'T_2',
  1815. quantity: 1,
  1816. },
  1817. ]);
  1818. orderId5 = order.id;
  1819. const { modifyOrder } = await adminClient.query<
  1820. Codegen.ModifyOrderMutation,
  1821. Codegen.ModifyOrderMutationVariables
  1822. >(MODIFY_ORDER, {
  1823. input: {
  1824. dryRun: false,
  1825. orderId: order.id,
  1826. addItems: [{ productVariantId: 'T_3', quantity: 1 }],
  1827. },
  1828. });
  1829. orderGuard.assertSuccess(modifyOrder);
  1830. const variant2 = await getVariant('T_3');
  1831. expect(variant2.stockOnHand).toBe(100);
  1832. expect(variant2.stockAllocated).toBe(1);
  1833. const result = await adminTransitionOrderToState(orderId5, 'ArrangingAdditionalPayment');
  1834. orderGuard.assertSuccess(result);
  1835. expect(result!.state).toBe('ArrangingAdditionalPayment');
  1836. const { addManualPaymentToOrder } = await adminClient.query<
  1837. Codegen.AddManualPaymentMutation,
  1838. Codegen.AddManualPaymentMutationVariables
  1839. >(ADD_MANUAL_PAYMENT, {
  1840. input: {
  1841. orderId: orderId5,
  1842. method: 'test',
  1843. transactionId: 'manual-extra-payment',
  1844. metadata: {
  1845. foo: 'bar',
  1846. },
  1847. },
  1848. });
  1849. orderGuard.assertSuccess(addManualPaymentToOrder);
  1850. const result2 = await adminTransitionOrderToState(orderId5, 'PaymentSettled');
  1851. orderGuard.assertSuccess(result2);
  1852. const result3 = await adminTransitionOrderToState(orderId5, 'Modifying');
  1853. orderGuard.assertSuccess(result3);
  1854. });
  1855. it('updates stock when removing item before fulfillment', async () => {
  1856. const variant1 = await getVariant('T_3');
  1857. expect(variant1.stockOnHand).toBe(100);
  1858. expect(variant1.stockAllocated).toBe(1);
  1859. const { order } = await adminClient.query<Codegen.GetOrderQuery, Codegen.GetOrderQueryVariables>(
  1860. GET_ORDER,
  1861. {
  1862. id: orderId5,
  1863. },
  1864. );
  1865. const { modifyOrder } = await adminClient.query<
  1866. Codegen.ModifyOrderMutation,
  1867. Codegen.ModifyOrderMutationVariables
  1868. >(MODIFY_ORDER, {
  1869. input: {
  1870. dryRun: false,
  1871. orderId: orderId5,
  1872. adjustOrderLines: [
  1873. {
  1874. orderLineId: order!.lines.find(l => l.productVariant.id === 'T_3')!.id,
  1875. quantity: 0,
  1876. },
  1877. ],
  1878. refund: {
  1879. paymentId: order!.payments![0].id,
  1880. },
  1881. },
  1882. });
  1883. orderGuard.assertSuccess(modifyOrder);
  1884. const variant2 = await getVariant('T_3');
  1885. expect(variant2.stockOnHand).toBe(100);
  1886. expect(variant2.stockAllocated).toBe(0);
  1887. });
  1888. it('updates stock when removing item after fulfillment', async () => {
  1889. const variant1 = await getVariant('T_3');
  1890. expect(variant1.stockOnHand).toBe(100);
  1891. expect(variant1.stockAllocated).toBe(0);
  1892. const order = await createOrderAndCheckout([
  1893. {
  1894. productVariantId: 'T_3',
  1895. quantity: 1,
  1896. },
  1897. ]);
  1898. const { addFulfillmentToOrder } = await adminClient.query<
  1899. Codegen.CreateFulfillmentMutation,
  1900. Codegen.CreateFulfillmentMutationVariables
  1901. >(CREATE_FULFILLMENT, {
  1902. input: {
  1903. lines: order?.lines.map(l => ({ orderLineId: l.id, quantity: l.quantity })) ?? [],
  1904. handler: {
  1905. code: manualFulfillmentHandler.code,
  1906. arguments: [
  1907. { name: 'method', value: 'test method' },
  1908. { name: 'trackingCode', value: 'ABC123' },
  1909. ],
  1910. },
  1911. },
  1912. });
  1913. orderGuard.assertSuccess(addFulfillmentToOrder);
  1914. const variant2 = await getVariant('T_3');
  1915. expect(variant2.stockOnHand).toBe(99);
  1916. expect(variant2.stockAllocated).toBe(0);
  1917. await adminTransitionOrderToState(order.id, 'Modifying');
  1918. const { modifyOrder } = await adminClient.query<
  1919. Codegen.ModifyOrderMutation,
  1920. Codegen.ModifyOrderMutationVariables
  1921. >(MODIFY_ORDER, {
  1922. input: {
  1923. dryRun: false,
  1924. orderId: order.id,
  1925. adjustOrderLines: [
  1926. {
  1927. orderLineId: order.lines.find(l => l.productVariant.id === 'T_3')!.id,
  1928. quantity: 0,
  1929. },
  1930. ],
  1931. refund: {
  1932. paymentId: order.payments![0].id,
  1933. },
  1934. },
  1935. });
  1936. const variant3 = await getVariant('T_3');
  1937. expect(variant3.stockOnHand).toBe(100);
  1938. expect(variant3.stockAllocated).toBe(0);
  1939. });
  1940. });
  1941. describe('couponCode handling', () => {
  1942. const CODE_50PC_OFF = '50PC';
  1943. const CODE_FREE_SHIPPING = 'FREESHIP';
  1944. let order: TestOrderWithPaymentsFragment;
  1945. beforeAll(async () => {
  1946. await adminClient.query<
  1947. Codegen.CreatePromotionMutation,
  1948. Codegen.CreatePromotionMutationVariables
  1949. >(CREATE_PROMOTION, {
  1950. input: {
  1951. couponCode: CODE_50PC_OFF,
  1952. enabled: true,
  1953. conditions: [],
  1954. actions: [
  1955. {
  1956. code: orderPercentageDiscount.code,
  1957. arguments: [{ name: 'discount', value: '50' }],
  1958. },
  1959. ],
  1960. translations: [{ languageCode: LanguageCode.en, name: '50% off' }],
  1961. },
  1962. });
  1963. await adminClient.query<
  1964. Codegen.CreatePromotionMutation,
  1965. Codegen.CreatePromotionMutationVariables
  1966. >(CREATE_PROMOTION, {
  1967. input: {
  1968. couponCode: CODE_FREE_SHIPPING,
  1969. enabled: true,
  1970. conditions: [],
  1971. actions: [{ code: freeShipping.code, arguments: [] }],
  1972. translations: [{ languageCode: LanguageCode.en, name: 'Free shipping' }],
  1973. },
  1974. });
  1975. // create an order and check out
  1976. await shopClient.asUserWithCredentials('trevor_donnelly96@hotmail.com', 'test');
  1977. await shopClient.query(gql(ADD_ITEM_TO_ORDER_WITH_CUSTOM_FIELDS), {
  1978. productVariantId: 'T_1',
  1979. quantity: 1,
  1980. customFields: {
  1981. color: 'green',
  1982. },
  1983. } as any);
  1984. await shopClient.query(gql(ADD_ITEM_TO_ORDER_WITH_CUSTOM_FIELDS), {
  1985. productVariantId: 'T_4',
  1986. quantity: 2,
  1987. });
  1988. await proceedToArrangingPayment(shopClient);
  1989. const result = await addPaymentToOrder(shopClient, testSuccessfulPaymentMethod);
  1990. orderGuard.assertSuccess(result);
  1991. order = result;
  1992. const result2 = await adminTransitionOrderToState(order.id, 'Modifying');
  1993. orderGuard.assertSuccess(result2);
  1994. expect(result2.state).toBe('Modifying');
  1995. });
  1996. it('invalid coupon code returns ErrorResult', async () => {
  1997. const { modifyOrder } = await adminClient.query<
  1998. Codegen.ModifyOrderMutation,
  1999. Codegen.ModifyOrderMutationVariables
  2000. >(MODIFY_ORDER, {
  2001. input: {
  2002. dryRun: false,
  2003. orderId: order.id,
  2004. couponCodes: ['BAD_CODE'],
  2005. },
  2006. });
  2007. orderGuard.assertErrorResult(modifyOrder);
  2008. expect(modifyOrder.message).toBe('Coupon code "BAD_CODE" is not valid');
  2009. });
  2010. it('valid coupon code applies Promotion', async () => {
  2011. const { modifyOrder } = await adminClient.query<
  2012. Codegen.ModifyOrderMutation,
  2013. Codegen.ModifyOrderMutationVariables
  2014. >(MODIFY_ORDER, {
  2015. input: {
  2016. dryRun: false,
  2017. orderId: order.id,
  2018. refund: {
  2019. paymentId: order.payments![0].id,
  2020. },
  2021. couponCodes: [CODE_50PC_OFF],
  2022. },
  2023. });
  2024. orderGuard.assertSuccess(modifyOrder);
  2025. expect(modifyOrder.subTotalWithTax).toBe(order.subTotalWithTax * 0.5);
  2026. });
  2027. it('adds order.discounts', async () => {
  2028. const { order: orderWithModifications } = await adminClient.query<
  2029. Codegen.GetOrderWithModificationsQuery,
  2030. Codegen.GetOrderWithModificationsQueryVariables
  2031. >(GET_ORDER_WITH_MODIFICATIONS, { id: order.id });
  2032. expect(orderWithModifications?.discounts.length).toBe(1);
  2033. expect(orderWithModifications?.discounts[0].description).toBe('50% off');
  2034. });
  2035. it('adds order.promotions', async () => {
  2036. const { order: orderWithModifications } = await adminClient.query<
  2037. Codegen.GetOrderWithModificationsQuery,
  2038. Codegen.GetOrderWithModificationsQueryVariables
  2039. >(GET_ORDER_WITH_MODIFICATIONS, { id: order.id });
  2040. expect(orderWithModifications?.promotions.length).toBe(1);
  2041. expect(orderWithModifications?.promotions[0].name).toBe('50% off');
  2042. });
  2043. it('creates correct refund amount', async () => {
  2044. const { order: orderWithModifications } = await adminClient.query<
  2045. Codegen.GetOrderWithModificationsQuery,
  2046. Codegen.GetOrderWithModificationsQueryVariables
  2047. >(GET_ORDER_WITH_MODIFICATIONS, { id: order.id });
  2048. expect(orderWithModifications?.payments![0].refunds.length).toBe(1);
  2049. expect(orderWithModifications!.totalWithTax).toBe(
  2050. getOrderPaymentsTotalWithRefunds(orderWithModifications!),
  2051. );
  2052. expect(orderWithModifications?.payments![0].refunds[0].total).toBe(
  2053. order.totalWithTax - orderWithModifications!.totalWithTax,
  2054. );
  2055. });
  2056. it('creates history entry for applying couponCode', async () => {
  2057. const { order: history } = await adminClient.query<
  2058. Codegen.GetOrderHistoryQuery,
  2059. Codegen.GetOrderHistoryQueryVariables
  2060. >(GET_ORDER_HISTORY, {
  2061. id: order.id,
  2062. options: { filter: { type: { eq: HistoryEntryType.ORDER_COUPON_APPLIED } } },
  2063. });
  2064. orderGuard.assertSuccess(history);
  2065. expect(history.history.items.length).toBe(1);
  2066. expect(pick(history.history.items[0]!, ['type', 'data'])).toEqual({
  2067. type: HistoryEntryType.ORDER_COUPON_APPLIED,
  2068. data: { couponCode: CODE_50PC_OFF, promotionId: 'T_6' },
  2069. });
  2070. });
  2071. it('removes coupon code', async () => {
  2072. const { modifyOrder } = await adminClient.query<
  2073. Codegen.ModifyOrderMutation,
  2074. Codegen.ModifyOrderMutationVariables
  2075. >(MODIFY_ORDER, {
  2076. input: {
  2077. dryRun: false,
  2078. orderId: order.id,
  2079. couponCodes: [],
  2080. },
  2081. });
  2082. orderGuard.assertSuccess(modifyOrder);
  2083. expect(modifyOrder.subTotalWithTax).toBe(order.subTotalWithTax);
  2084. });
  2085. it('removes order.discounts', async () => {
  2086. const { order: orderWithModifications } = await adminClient.query<
  2087. Codegen.GetOrderWithModificationsQuery,
  2088. Codegen.GetOrderWithModificationsQueryVariables
  2089. >(GET_ORDER_WITH_MODIFICATIONS, { id: order.id });
  2090. expect(orderWithModifications?.discounts.length).toBe(0);
  2091. });
  2092. it('removes order.promotions', async () => {
  2093. const { order: orderWithModifications } = await adminClient.query<
  2094. Codegen.GetOrderWithModificationsQuery,
  2095. Codegen.GetOrderWithModificationsQueryVariables
  2096. >(GET_ORDER_WITH_MODIFICATIONS, { id: order.id });
  2097. expect(orderWithModifications?.promotions.length).toBe(0);
  2098. });
  2099. it('creates history entry for removing couponCode', async () => {
  2100. const { order: history } = await adminClient.query<
  2101. Codegen.GetOrderHistoryQuery,
  2102. Codegen.GetOrderHistoryQueryVariables
  2103. >(GET_ORDER_HISTORY, {
  2104. id: order.id,
  2105. options: { filter: { type: { eq: HistoryEntryType.ORDER_COUPON_REMOVED } } },
  2106. });
  2107. orderGuard.assertSuccess(history);
  2108. expect(history.history.items.length).toBe(1);
  2109. expect(pick(history.history.items[0]!, ['type', 'data'])).toEqual({
  2110. type: HistoryEntryType.ORDER_COUPON_REMOVED,
  2111. data: { couponCode: CODE_50PC_OFF },
  2112. });
  2113. });
  2114. it('correct refund for free shipping couponCode', async () => {
  2115. await shopClient.query(gql(ADD_ITEM_TO_ORDER_WITH_CUSTOM_FIELDS), {
  2116. productVariantId: 'T_1',
  2117. quantity: 1,
  2118. } as any);
  2119. await proceedToArrangingPayment(shopClient);
  2120. const result = await addPaymentToOrder(shopClient, testSuccessfulPaymentMethod);
  2121. orderGuard.assertSuccess(result);
  2122. const order2 = result;
  2123. const shippingWithTax = order2.shippingWithTax;
  2124. const result2 = await adminTransitionOrderToState(order2.id, 'Modifying');
  2125. orderGuard.assertSuccess(result2);
  2126. expect(result2.state).toBe('Modifying');
  2127. const { modifyOrder } = await adminClient.query<
  2128. Codegen.ModifyOrderMutation,
  2129. Codegen.ModifyOrderMutationVariables
  2130. >(MODIFY_ORDER, {
  2131. input: {
  2132. dryRun: false,
  2133. orderId: order2.id,
  2134. refund: {
  2135. paymentId: order2.payments![0].id,
  2136. },
  2137. couponCodes: [CODE_FREE_SHIPPING],
  2138. },
  2139. });
  2140. orderGuard.assertSuccess(modifyOrder);
  2141. expect(modifyOrder.shippingWithTax).toBe(0);
  2142. expect(modifyOrder.totalWithTax).toBe(getOrderPaymentsTotalWithRefunds(modifyOrder));
  2143. expect(modifyOrder.payments![0].refunds[0].total).toBe(shippingWithTax);
  2144. });
  2145. });
  2146. async function adminTransitionOrderToState(id: string, state: string) {
  2147. const result = await adminClient.query<
  2148. Codegen.AdminTransitionMutation,
  2149. Codegen.AdminTransitionMutationVariables
  2150. >(ADMIN_TRANSITION_TO_STATE, {
  2151. id,
  2152. state,
  2153. });
  2154. return result.transitionOrderToState;
  2155. }
  2156. async function assertOrderIsUnchanged(order: OrderWithLinesFragment) {
  2157. const { order: order2 } = await adminClient.query<
  2158. Codegen.GetOrderQuery,
  2159. Codegen.GetOrderQueryVariables
  2160. >(GET_ORDER, {
  2161. id: order.id,
  2162. });
  2163. expect(order2!.totalWithTax).toBe(order.totalWithTax);
  2164. expect(order2!.lines.length).toBe(order.lines.length);
  2165. expect(order2!.surcharges.length).toBe(order.surcharges.length);
  2166. expect(order2!.totalQuantity).toBe(order.totalQuantity);
  2167. }
  2168. async function createOrderAndCheckout(
  2169. items: Array<AddItemToOrderMutationVariables & { customFields?: any }>,
  2170. ) {
  2171. await shopClient.asUserWithCredentials('hayden.zieme12@hotmail.com', 'test');
  2172. for (const itemInput of items) {
  2173. await shopClient.query(gql(ADD_ITEM_TO_ORDER_WITH_CUSTOM_FIELDS), itemInput);
  2174. }
  2175. await shopClient.query<
  2176. CodegenShop.SetShippingAddressMutation,
  2177. CodegenShop.SetShippingAddressMutationVariables
  2178. >(SET_SHIPPING_ADDRESS, {
  2179. input: {
  2180. fullName: 'name',
  2181. streetLine1: '12 the street',
  2182. city: 'foo',
  2183. postalCode: '123456',
  2184. countryCode: 'AT',
  2185. },
  2186. });
  2187. await shopClient.query<
  2188. CodegenShop.SetShippingMethodMutation,
  2189. CodegenShop.SetShippingMethodMutationVariables
  2190. >(SET_SHIPPING_METHOD, {
  2191. id: testShippingMethodId,
  2192. });
  2193. await shopClient.query<
  2194. CodegenShop.TransitionToStateMutation,
  2195. CodegenShop.TransitionToStateMutationVariables
  2196. >(TRANSITION_TO_STATE, {
  2197. state: 'ArrangingPayment',
  2198. });
  2199. const order = await addPaymentToOrder(shopClient, testSuccessfulPaymentMethod);
  2200. orderGuard.assertSuccess(order);
  2201. return order;
  2202. }
  2203. async function createOrderAndTransitionToModifyingState(
  2204. items: Array<AddItemToOrderMutationVariables & { customFields?: any }>,
  2205. ): Promise<TestOrderWithPaymentsFragment> {
  2206. const order = await createOrderAndCheckout(items);
  2207. await adminTransitionOrderToState(order.id, 'Modifying');
  2208. return order;
  2209. }
  2210. function getOrderPaymentsTotalWithRefunds(_order: OrderWithModificationsFragment) {
  2211. return _order.payments?.reduce((sum, p) => sum + p.amount - summate(p?.refunds, 'total'), 0) ?? 0;
  2212. }
  2213. });
  2214. export const ORDER_WITH_MODIFICATION_FRAGMENT = gql`
  2215. fragment OrderWithModifications on Order {
  2216. id
  2217. state
  2218. subTotal
  2219. subTotalWithTax
  2220. shipping
  2221. shippingWithTax
  2222. total
  2223. totalWithTax
  2224. lines {
  2225. id
  2226. quantity
  2227. orderPlacedQuantity
  2228. linePrice
  2229. linePriceWithTax
  2230. unitPriceWithTax
  2231. discountedLinePriceWithTax
  2232. proratedLinePriceWithTax
  2233. proratedUnitPriceWithTax
  2234. discounts {
  2235. description
  2236. amountWithTax
  2237. }
  2238. productVariant {
  2239. id
  2240. name
  2241. }
  2242. }
  2243. surcharges {
  2244. id
  2245. description
  2246. sku
  2247. price
  2248. priceWithTax
  2249. taxRate
  2250. }
  2251. payments {
  2252. id
  2253. transactionId
  2254. state
  2255. amount
  2256. method
  2257. metadata
  2258. refunds {
  2259. id
  2260. state
  2261. total
  2262. paymentId
  2263. }
  2264. }
  2265. modifications {
  2266. id
  2267. note
  2268. priceChange
  2269. isSettled
  2270. lines {
  2271. orderLineId
  2272. quantity
  2273. }
  2274. surcharges {
  2275. id
  2276. }
  2277. payment {
  2278. id
  2279. state
  2280. amount
  2281. method
  2282. }
  2283. refund {
  2284. id
  2285. state
  2286. total
  2287. paymentId
  2288. }
  2289. }
  2290. promotions {
  2291. id
  2292. name
  2293. couponCode
  2294. }
  2295. discounts {
  2296. description
  2297. adjustmentSource
  2298. amount
  2299. amountWithTax
  2300. }
  2301. shippingAddress {
  2302. streetLine1
  2303. city
  2304. postalCode
  2305. province
  2306. countryCode
  2307. country
  2308. }
  2309. billingAddress {
  2310. streetLine1
  2311. city
  2312. postalCode
  2313. province
  2314. countryCode
  2315. country
  2316. }
  2317. }
  2318. `;
  2319. export const GET_ORDER_WITH_MODIFICATIONS = gql`
  2320. query GetOrderWithModifications($id: ID!) {
  2321. order(id: $id) {
  2322. ...OrderWithModifications
  2323. }
  2324. }
  2325. ${ORDER_WITH_MODIFICATION_FRAGMENT}
  2326. `;
  2327. export const MODIFY_ORDER = gql`
  2328. mutation ModifyOrder($input: ModifyOrderInput!) {
  2329. modifyOrder(input: $input) {
  2330. ...OrderWithModifications
  2331. ... on ErrorResult {
  2332. errorCode
  2333. message
  2334. }
  2335. }
  2336. }
  2337. ${ORDER_WITH_MODIFICATION_FRAGMENT}
  2338. `;
  2339. export const ADD_MANUAL_PAYMENT = gql`
  2340. mutation AddManualPayment($input: ManualPaymentInput!) {
  2341. addManualPaymentToOrder(input: $input) {
  2342. ...OrderWithModifications
  2343. ... on ErrorResult {
  2344. errorCode
  2345. message
  2346. }
  2347. }
  2348. }
  2349. ${ORDER_WITH_MODIFICATION_FRAGMENT}
  2350. `;
  2351. // Note, we don't use the gql tag around these due to the customFields which
  2352. // would cause a codegen error.
  2353. const ADD_ITEM_TO_ORDER_WITH_CUSTOM_FIELDS = `
  2354. mutation AddItemToOrder($productVariantId: ID!, $quantity: Int!, $customFields: OrderLineCustomFieldsInput) {
  2355. addItemToOrder(productVariantId: $productVariantId, quantity: $quantity, customFields: $customFields) {
  2356. ...on Order { id }
  2357. }
  2358. }
  2359. `;
  2360. const GET_ORDER_WITH_CUSTOM_FIELDS = `
  2361. query GetOrderCustomFields($id: ID!) {
  2362. order(id: $id) {
  2363. customFields { points }
  2364. lines { id, customFields { color } }
  2365. }
  2366. }
  2367. `;