order-modification.e2e-spec.ts 97 KB

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