order-modification.e2e-spec.ts 100 KB

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