order-modification.e2e-spec.ts 103 KB

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