order-modification.e2e-spec.ts 110 KB

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