order-modification.e2e-spec.ts 85 KB

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