order-modification.e2e-spec.ts 66 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752
  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 {
  5. defaultShippingCalculator,
  6. defaultShippingEligibilityChecker,
  7. mergeConfig,
  8. productsPercentageDiscount,
  9. ShippingCalculator,
  10. } from '@vendure/core';
  11. import { createErrorResultGuard, createTestEnvironment, ErrorResultGuard } from '@vendure/testing';
  12. import gql from 'graphql-tag';
  13. import path from 'path';
  14. import { initialData } from '../../../e2e-common/e2e-initial-data';
  15. import { testConfig, TEST_SETUP_TIMEOUT_MS } from '../../../e2e-common/test-config';
  16. import { manualFulfillmentHandler } from '../src/config/fulfillment/manual-fulfillment-handler';
  17. import { orderFixedDiscount } from '../src/config/promotion/actions/order-fixed-discount-action';
  18. import { defaultPromotionActions } from '../src/config/promotion/index';
  19. import {
  20. failsToSettlePaymentMethod,
  21. testFailingPaymentMethod,
  22. testSuccessfulPaymentMethod,
  23. } from './fixtures/test-payment-methods';
  24. import {
  25. AddManualPayment,
  26. AdminTransition,
  27. CreatePromotion,
  28. CreateShippingMethod,
  29. ErrorCode,
  30. GetOrder,
  31. GetOrderHistory,
  32. GetOrderWithModifications,
  33. GlobalFlag,
  34. HistoryEntryType,
  35. LanguageCode,
  36. ModifyOrder,
  37. OrderFragment,
  38. OrderWithLinesFragment,
  39. OrderWithModificationsFragment,
  40. UpdateChannel,
  41. UpdateProductVariants,
  42. } from './graphql/generated-e2e-admin-types';
  43. import {
  44. AddItemToOrderMutationVariables,
  45. ApplyCouponCode,
  46. SetShippingAddress,
  47. SetShippingMethod,
  48. TestOrderWithPaymentsFragment,
  49. TransitionToState,
  50. UpdatedOrderFragment,
  51. } from './graphql/generated-e2e-shop-types';
  52. import {
  53. ADMIN_TRANSITION_TO_STATE,
  54. CREATE_PROMOTION,
  55. CREATE_SHIPPING_METHOD,
  56. GET_ORDER,
  57. GET_ORDER_HISTORY,
  58. UPDATE_CHANNEL,
  59. UPDATE_PRODUCT_VARIANTS,
  60. } from './graphql/shared-definitions';
  61. import {
  62. APPLY_COUPON_CODE,
  63. SET_SHIPPING_ADDRESS,
  64. SET_SHIPPING_METHOD,
  65. TRANSITION_TO_STATE,
  66. } from './graphql/shop-definitions';
  67. import { addPaymentToOrder, proceedToArrangingPayment } from './utils/test-order-utils';
  68. const SHIPPING_GB = 500;
  69. const SHIPPING_US = 1000;
  70. const SHIPPING_OTHER = 750;
  71. const testCalculator = new ShippingCalculator({
  72. code: 'test-calculator',
  73. description: [{ languageCode: LanguageCode.en, value: 'Has metadata' }],
  74. args: {},
  75. calculate: (ctx, order, args) => {
  76. let price;
  77. switch (order.shippingAddress.countryCode) {
  78. case 'GB':
  79. price = SHIPPING_GB;
  80. break;
  81. case 'US':
  82. price = SHIPPING_US;
  83. break;
  84. default:
  85. price = SHIPPING_OTHER;
  86. }
  87. return {
  88. price,
  89. priceIncludesTax: true,
  90. taxRate: 20,
  91. };
  92. },
  93. });
  94. describe('Order modification', () => {
  95. const { server, adminClient, shopClient } = createTestEnvironment(
  96. mergeConfig(testConfig(), {
  97. paymentOptions: {
  98. paymentMethodHandlers: [
  99. testSuccessfulPaymentMethod,
  100. failsToSettlePaymentMethod,
  101. testFailingPaymentMethod,
  102. ],
  103. },
  104. shippingOptions: {
  105. shippingCalculators: [defaultShippingCalculator, testCalculator],
  106. },
  107. customFields: {
  108. Order: [{ name: 'points', type: 'int', defaultValue: 0 }],
  109. OrderLine: [{ name: 'color', type: 'string', nullable: true }],
  110. },
  111. }),
  112. );
  113. let orderId: string;
  114. let testShippingMethodId: string;
  115. const orderGuard: ErrorResultGuard<
  116. UpdatedOrderFragment | OrderWithModificationsFragment | OrderFragment
  117. > = createErrorResultGuard(input => !!input.id);
  118. beforeAll(async () => {
  119. await server.init({
  120. initialData: {
  121. ...initialData,
  122. paymentMethods: [
  123. {
  124. name: testSuccessfulPaymentMethod.code,
  125. handler: { code: testSuccessfulPaymentMethod.code, arguments: [] },
  126. },
  127. {
  128. name: failsToSettlePaymentMethod.code,
  129. handler: { code: failsToSettlePaymentMethod.code, arguments: [] },
  130. },
  131. {
  132. name: testFailingPaymentMethod.code,
  133. handler: { code: testFailingPaymentMethod.code, arguments: [] },
  134. },
  135. ],
  136. },
  137. productsCsvPath: path.join(__dirname, 'fixtures/e2e-products-full.csv'),
  138. customerCount: 2,
  139. });
  140. await adminClient.asSuperAdmin();
  141. await adminClient.query<UpdateProductVariants.Mutation, UpdateProductVariants.Variables>(
  142. UPDATE_PRODUCT_VARIANTS,
  143. {
  144. input: [
  145. {
  146. id: 'T_1',
  147. trackInventory: GlobalFlag.TRUE,
  148. },
  149. {
  150. id: 'T_2',
  151. trackInventory: GlobalFlag.TRUE,
  152. },
  153. {
  154. id: 'T_3',
  155. trackInventory: GlobalFlag.TRUE,
  156. },
  157. ],
  158. },
  159. );
  160. const { createShippingMethod } = await adminClient.query<
  161. CreateShippingMethod.Mutation,
  162. CreateShippingMethod.Variables
  163. >(CREATE_SHIPPING_METHOD, {
  164. input: {
  165. code: 'new-method',
  166. fulfillmentHandler: manualFulfillmentHandler.code,
  167. checker: {
  168. code: defaultShippingEligibilityChecker.code,
  169. arguments: [
  170. {
  171. name: 'orderMinimum',
  172. value: '0',
  173. },
  174. ],
  175. },
  176. calculator: {
  177. code: testCalculator.code,
  178. arguments: [],
  179. },
  180. translations: [{ languageCode: LanguageCode.en, name: 'test method', description: '' }],
  181. },
  182. });
  183. testShippingMethodId = createShippingMethod.id;
  184. // create an order and check out
  185. await shopClient.asUserWithCredentials('hayden.zieme12@hotmail.com', 'test');
  186. await shopClient.query(gql(ADD_ITEM_TO_ORDER_WITH_CUSTOM_FIELDS), {
  187. productVariantId: 'T_1',
  188. quantity: 1,
  189. customFields: {
  190. color: 'green',
  191. },
  192. } as any);
  193. await shopClient.query(gql(ADD_ITEM_TO_ORDER_WITH_CUSTOM_FIELDS), {
  194. productVariantId: 'T_4',
  195. quantity: 2,
  196. });
  197. await proceedToArrangingPayment(shopClient);
  198. const result = await addPaymentToOrder(shopClient, testSuccessfulPaymentMethod);
  199. orderGuard.assertSuccess(result);
  200. orderId = result.id;
  201. }, TEST_SETUP_TIMEOUT_MS);
  202. afterAll(async () => {
  203. await server.destroy();
  204. });
  205. it('modifyOrder returns error result when not in Modifying state', async () => {
  206. const { order } = await adminClient.query<GetOrder.Query, GetOrder.Variables>(GET_ORDER, {
  207. id: orderId,
  208. });
  209. const { modifyOrder } = await adminClient.query<ModifyOrder.Mutation, ModifyOrder.Variables>(
  210. MODIFY_ORDER,
  211. {
  212. input: {
  213. dryRun: false,
  214. orderId,
  215. adjustOrderLines: order!.lines.map(l => ({ orderLineId: l.id, quantity: 3 })),
  216. },
  217. },
  218. );
  219. orderGuard.assertErrorResult(modifyOrder);
  220. expect(modifyOrder.errorCode).toBe(ErrorCode.ORDER_MODIFICATION_STATE_ERROR);
  221. });
  222. it('transition to Modifying state', async () => {
  223. const { transitionOrderToState } = await adminClient.query<
  224. AdminTransition.Mutation,
  225. AdminTransition.Variables
  226. >(ADMIN_TRANSITION_TO_STATE, {
  227. id: orderId,
  228. state: 'Modifying',
  229. });
  230. orderGuard.assertSuccess(transitionOrderToState);
  231. expect(transitionOrderToState.state).toBe('Modifying');
  232. });
  233. describe('error cases', () => {
  234. it('no changes specified error', async () => {
  235. const { modifyOrder } = await adminClient.query<ModifyOrder.Mutation, ModifyOrder.Variables>(
  236. MODIFY_ORDER,
  237. {
  238. input: {
  239. dryRun: false,
  240. orderId,
  241. },
  242. },
  243. );
  244. orderGuard.assertErrorResult(modifyOrder);
  245. expect(modifyOrder.errorCode).toBe(ErrorCode.NO_CHANGES_SPECIFIED_ERROR);
  246. });
  247. it('no refund paymentId specified', async () => {
  248. const { order } = await adminClient.query<GetOrder.Query, GetOrder.Variables>(GET_ORDER, {
  249. id: orderId,
  250. });
  251. const { modifyOrder } = await adminClient.query<ModifyOrder.Mutation, ModifyOrder.Variables>(
  252. MODIFY_ORDER,
  253. {
  254. input: {
  255. dryRun: false,
  256. orderId,
  257. surcharges: [{ price: -500, priceIncludesTax: true, description: 'Discount' }],
  258. },
  259. },
  260. );
  261. orderGuard.assertErrorResult(modifyOrder);
  262. expect(modifyOrder.errorCode).toBe(ErrorCode.REFUND_PAYMENT_ID_MISSING_ERROR);
  263. await assertOrderIsUnchanged(order!);
  264. });
  265. it('addItems negative quantity', async () => {
  266. const { order } = await adminClient.query<GetOrder.Query, GetOrder.Variables>(GET_ORDER, {
  267. id: orderId,
  268. });
  269. const { modifyOrder } = await adminClient.query<ModifyOrder.Mutation, ModifyOrder.Variables>(
  270. MODIFY_ORDER,
  271. {
  272. input: {
  273. dryRun: false,
  274. orderId,
  275. addItems: [{ productVariantId: 'T_3', quantity: -1 }],
  276. },
  277. },
  278. );
  279. orderGuard.assertErrorResult(modifyOrder);
  280. expect(modifyOrder.errorCode).toBe(ErrorCode.NEGATIVE_QUANTITY_ERROR);
  281. await assertOrderIsUnchanged(order!);
  282. });
  283. it('adjustOrderLines negative quantity', async () => {
  284. const { order } = await adminClient.query<GetOrder.Query, GetOrder.Variables>(GET_ORDER, {
  285. id: orderId,
  286. });
  287. const { modifyOrder } = await adminClient.query<ModifyOrder.Mutation, ModifyOrder.Variables>(
  288. MODIFY_ORDER,
  289. {
  290. input: {
  291. dryRun: false,
  292. orderId,
  293. adjustOrderLines: [{ orderLineId: order!.lines[0].id, quantity: -1 }],
  294. },
  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<GetOrder.Query, GetOrder.Variables>(GET_ORDER, {
  303. id: orderId,
  304. });
  305. const { modifyOrder } = await adminClient.query<ModifyOrder.Mutation, ModifyOrder.Variables>(
  306. MODIFY_ORDER,
  307. {
  308. input: {
  309. dryRun: false,
  310. orderId,
  311. addItems: [{ productVariantId: 'T_3', quantity: 500 }],
  312. },
  313. },
  314. );
  315. orderGuard.assertErrorResult(modifyOrder);
  316. expect(modifyOrder.errorCode).toBe(ErrorCode.INSUFFICIENT_STOCK_ERROR);
  317. await assertOrderIsUnchanged(order!);
  318. });
  319. it('adjustOrderLines insufficient stock', async () => {
  320. const { order } = await adminClient.query<GetOrder.Query, GetOrder.Variables>(GET_ORDER, {
  321. id: orderId,
  322. });
  323. const { modifyOrder } = await adminClient.query<ModifyOrder.Mutation, ModifyOrder.Variables>(
  324. MODIFY_ORDER,
  325. {
  326. input: {
  327. dryRun: false,
  328. orderId,
  329. adjustOrderLines: [{ orderLineId: order!.lines[0].id, quantity: 500 }],
  330. },
  331. },
  332. );
  333. orderGuard.assertErrorResult(modifyOrder);
  334. expect(modifyOrder.errorCode).toBe(ErrorCode.INSUFFICIENT_STOCK_ERROR);
  335. await assertOrderIsUnchanged(order!);
  336. });
  337. it('addItems order limit', async () => {
  338. const { order } = await adminClient.query<GetOrder.Query, GetOrder.Variables>(GET_ORDER, {
  339. id: orderId,
  340. });
  341. const { modifyOrder } = await adminClient.query<ModifyOrder.Mutation, ModifyOrder.Variables>(
  342. MODIFY_ORDER,
  343. {
  344. input: {
  345. dryRun: false,
  346. orderId,
  347. addItems: [{ productVariantId: 'T_4', quantity: 9999 }],
  348. },
  349. },
  350. );
  351. orderGuard.assertErrorResult(modifyOrder);
  352. expect(modifyOrder.errorCode).toBe(ErrorCode.ORDER_LIMIT_ERROR);
  353. await assertOrderIsUnchanged(order!);
  354. });
  355. it('adjustOrderLines order limit', async () => {
  356. const { order } = await adminClient.query<GetOrder.Query, GetOrder.Variables>(GET_ORDER, {
  357. id: orderId,
  358. });
  359. const { modifyOrder } = await adminClient.query<ModifyOrder.Mutation, ModifyOrder.Variables>(
  360. MODIFY_ORDER,
  361. {
  362. input: {
  363. dryRun: false,
  364. orderId,
  365. adjustOrderLines: [{ orderLineId: order!.lines[1].id, quantity: 9999 }],
  366. },
  367. },
  368. );
  369. orderGuard.assertErrorResult(modifyOrder);
  370. expect(modifyOrder.errorCode).toBe(ErrorCode.ORDER_LIMIT_ERROR);
  371. await assertOrderIsUnchanged(order!);
  372. });
  373. });
  374. describe('dry run', () => {
  375. it('addItems', async () => {
  376. const { order } = await adminClient.query<GetOrder.Query, GetOrder.Variables>(GET_ORDER, {
  377. id: orderId,
  378. });
  379. const { modifyOrder } = await adminClient.query<ModifyOrder.Mutation, ModifyOrder.Variables>(
  380. MODIFY_ORDER,
  381. {
  382. input: {
  383. dryRun: true,
  384. orderId,
  385. addItems: [{ productVariantId: 'T_5', quantity: 1 }],
  386. },
  387. },
  388. );
  389. orderGuard.assertSuccess(modifyOrder);
  390. const expectedTotal = order!.totalWithTax + Math.round(14374 * 1.2); // price of variant T_5
  391. expect(modifyOrder.totalWithTax).toBe(expectedTotal);
  392. expect(modifyOrder.lines.length).toBe(order!.lines.length + 1);
  393. await assertOrderIsUnchanged(order!);
  394. });
  395. it('addItems with existing variant id increments existing OrderLine', async () => {
  396. const { order } = await adminClient.query<GetOrder.Query, GetOrder.Variables>(GET_ORDER, {
  397. id: orderId,
  398. });
  399. const { modifyOrder } = await adminClient.query<ModifyOrder.Mutation, ModifyOrder.Variables>(
  400. MODIFY_ORDER,
  401. {
  402. input: {
  403. dryRun: true,
  404. orderId,
  405. addItems: [
  406. { productVariantId: 'T_1', quantity: 1, customFields: { color: 'green' } } as any,
  407. ],
  408. },
  409. },
  410. );
  411. orderGuard.assertSuccess(modifyOrder);
  412. const lineT1 = modifyOrder.lines.find(l => l.productVariant.id === 'T_1');
  413. expect(modifyOrder.lines.length).toBe(2);
  414. expect(lineT1?.quantity).toBe(2);
  415. await assertOrderIsUnchanged(order!);
  416. });
  417. it('addItems with existing variant id but different customFields adds new OrderLine', async () => {
  418. const { order } = await adminClient.query<GetOrder.Query, GetOrder.Variables>(GET_ORDER, {
  419. id: orderId,
  420. });
  421. const { modifyOrder } = await adminClient.query<ModifyOrder.Mutation, ModifyOrder.Variables>(
  422. MODIFY_ORDER,
  423. {
  424. input: {
  425. dryRun: true,
  426. orderId,
  427. addItems: [
  428. { productVariantId: 'T_1', quantity: 1, customFields: { color: 'blue' } } as any,
  429. ],
  430. },
  431. },
  432. );
  433. orderGuard.assertSuccess(modifyOrder);
  434. const lineT1 = modifyOrder.lines.find(l => l.productVariant.id === 'T_1');
  435. expect(modifyOrder.lines.length).toBe(3);
  436. expect(
  437. modifyOrder.lines.map(l => ({ variantId: l.productVariant.id, quantity: l.quantity })),
  438. ).toEqual([
  439. { variantId: 'T_1', quantity: 1 },
  440. { variantId: 'T_4', quantity: 2 },
  441. { variantId: 'T_1', quantity: 1 },
  442. ]);
  443. await assertOrderIsUnchanged(order!);
  444. });
  445. it('adjustOrderLines up', async () => {
  446. const { order } = await adminClient.query<GetOrder.Query, GetOrder.Variables>(GET_ORDER, {
  447. id: orderId,
  448. });
  449. const { modifyOrder } = await adminClient.query<ModifyOrder.Mutation, ModifyOrder.Variables>(
  450. MODIFY_ORDER,
  451. {
  452. input: {
  453. dryRun: true,
  454. orderId,
  455. adjustOrderLines: [{ orderLineId: order!.lines[0].id, quantity: 3 }],
  456. },
  457. },
  458. );
  459. orderGuard.assertSuccess(modifyOrder);
  460. const expectedTotal = order!.totalWithTax + order!.lines[0].unitPriceWithTax * 2;
  461. expect(modifyOrder.lines[0].items.length).toBe(3);
  462. expect(modifyOrder.totalWithTax).toBe(expectedTotal);
  463. await assertOrderIsUnchanged(order!);
  464. });
  465. it('adjustOrderLines down', async () => {
  466. const { order } = await adminClient.query<GetOrder.Query, GetOrder.Variables>(GET_ORDER, {
  467. id: orderId,
  468. });
  469. const { modifyOrder } = await adminClient.query<ModifyOrder.Mutation, ModifyOrder.Variables>(
  470. MODIFY_ORDER,
  471. {
  472. input: {
  473. dryRun: true,
  474. orderId,
  475. adjustOrderLines: [{ orderLineId: order!.lines[1].id, quantity: 1 }],
  476. },
  477. },
  478. );
  479. orderGuard.assertSuccess(modifyOrder);
  480. const expectedTotal = order!.totalWithTax - order!.lines[1].unitPriceWithTax;
  481. expect(modifyOrder.lines[1].items.filter(i => i.cancelled).length).toBe(1);
  482. expect(modifyOrder.lines[1].items.filter(i => !i.cancelled).length).toBe(1);
  483. expect(modifyOrder.totalWithTax).toBe(expectedTotal);
  484. await assertOrderIsUnchanged(order!);
  485. });
  486. it('adjustOrderLines to zero', async () => {
  487. const { order } = await adminClient.query<GetOrder.Query, GetOrder.Variables>(GET_ORDER, {
  488. id: orderId,
  489. });
  490. const { modifyOrder } = await adminClient.query<ModifyOrder.Mutation, ModifyOrder.Variables>(
  491. MODIFY_ORDER,
  492. {
  493. input: {
  494. dryRun: true,
  495. orderId,
  496. adjustOrderLines: [{ orderLineId: order!.lines[0].id, quantity: 0 }],
  497. },
  498. },
  499. );
  500. orderGuard.assertSuccess(modifyOrder);
  501. const expectedTotal = order!.totalWithTax - order!.lines[0].linePriceWithTax;
  502. expect(modifyOrder.totalWithTax).toBe(expectedTotal);
  503. expect(modifyOrder.lines[0].items.every(i => i.cancelled)).toBe(true);
  504. await assertOrderIsUnchanged(order!);
  505. });
  506. it('surcharge positive', async () => {
  507. const { order } = await adminClient.query<GetOrder.Query, GetOrder.Variables>(GET_ORDER, {
  508. id: orderId,
  509. });
  510. const { modifyOrder } = await adminClient.query<ModifyOrder.Mutation, ModifyOrder.Variables>(
  511. MODIFY_ORDER,
  512. {
  513. input: {
  514. dryRun: true,
  515. orderId,
  516. surcharges: [
  517. {
  518. description: 'extra fee',
  519. sku: '123',
  520. price: 300,
  521. priceIncludesTax: true,
  522. taxRate: 20,
  523. taxDescription: 'VAT',
  524. },
  525. ],
  526. },
  527. },
  528. );
  529. orderGuard.assertSuccess(modifyOrder);
  530. const expectedTotal = order!.totalWithTax + 300;
  531. expect(modifyOrder.totalWithTax).toBe(expectedTotal);
  532. expect(modifyOrder.surcharges.map(s => omit(s, ['id']))).toEqual([
  533. {
  534. description: 'extra fee',
  535. sku: '123',
  536. price: 250,
  537. priceWithTax: 300,
  538. taxRate: 20,
  539. },
  540. ]);
  541. await assertOrderIsUnchanged(order!);
  542. });
  543. it('surcharge negative', async () => {
  544. const { order } = await adminClient.query<GetOrder.Query, GetOrder.Variables>(GET_ORDER, {
  545. id: orderId,
  546. });
  547. const { modifyOrder } = await adminClient.query<ModifyOrder.Mutation, ModifyOrder.Variables>(
  548. MODIFY_ORDER,
  549. {
  550. input: {
  551. dryRun: true,
  552. orderId,
  553. surcharges: [
  554. {
  555. description: 'special discount',
  556. sku: '123',
  557. price: -300,
  558. priceIncludesTax: true,
  559. taxRate: 20,
  560. taxDescription: 'VAT',
  561. },
  562. ],
  563. },
  564. },
  565. );
  566. orderGuard.assertSuccess(modifyOrder);
  567. const expectedTotal = order!.totalWithTax + -300;
  568. expect(modifyOrder.totalWithTax).toBe(expectedTotal);
  569. expect(modifyOrder.surcharges.map(s => omit(s, ['id']))).toEqual([
  570. {
  571. description: 'special discount',
  572. sku: '123',
  573. price: -250,
  574. priceWithTax: -300,
  575. taxRate: 20,
  576. },
  577. ]);
  578. await assertOrderIsUnchanged(order!);
  579. });
  580. it('does not add a history entry', async () => {
  581. const { order } = await adminClient.query<GetOrder.Query, GetOrder.Variables>(GET_ORDER, {
  582. id: orderId,
  583. });
  584. const { modifyOrder } = await adminClient.query<ModifyOrder.Mutation, ModifyOrder.Variables>(
  585. MODIFY_ORDER,
  586. {
  587. input: {
  588. dryRun: true,
  589. orderId,
  590. addItems: [{ productVariantId: 'T_5', quantity: 1 }],
  591. },
  592. },
  593. );
  594. orderGuard.assertSuccess(modifyOrder);
  595. const { order: history } = await adminClient.query<
  596. GetOrderHistory.Query,
  597. GetOrderHistory.Variables
  598. >(GET_ORDER_HISTORY, {
  599. id: orderId,
  600. options: { filter: { type: { eq: HistoryEntryType.ORDER_MODIFIED } } },
  601. });
  602. orderGuard.assertSuccess(history);
  603. expect(history.history.totalItems).toBe(0);
  604. });
  605. });
  606. describe('wet run', () => {
  607. async function assertModifiedOrderIsPersisted(order: OrderWithModificationsFragment) {
  608. const { order: order2 } = await adminClient.query<GetOrder.Query, GetOrder.Variables>(GET_ORDER, {
  609. id: order.id,
  610. });
  611. expect(order2!.totalWithTax).toBe(order!.totalWithTax);
  612. expect(order2!.lines.length).toBe(order!.lines.length);
  613. expect(order2!.surcharges.length).toBe(order!.surcharges.length);
  614. expect(order2!.payments!.length).toBe(order!.payments!.length);
  615. expect(order2!.payments!.map(p => pick(p, ['id', 'amount', 'method']))).toEqual(
  616. order!.payments!.map(p => pick(p, ['id', 'amount', 'method'])),
  617. );
  618. }
  619. it('addItems', async () => {
  620. const order = await createOrderAndTransitionToModifyingState([
  621. {
  622. productVariantId: 'T_1',
  623. quantity: 1,
  624. },
  625. ]);
  626. const { modifyOrder } = await adminClient.query<ModifyOrder.Mutation, ModifyOrder.Variables>(
  627. MODIFY_ORDER,
  628. {
  629. input: {
  630. dryRun: false,
  631. orderId: order.id,
  632. addItems: [{ productVariantId: 'T_5', quantity: 1 }],
  633. },
  634. },
  635. );
  636. orderGuard.assertSuccess(modifyOrder);
  637. const priceDelta = Math.round(14374 * 1.2); // price of variant T_5
  638. const expectedTotal = order!.totalWithTax + priceDelta;
  639. expect(modifyOrder.totalWithTax).toBe(expectedTotal);
  640. expect(modifyOrder.lines.length).toBe(order!.lines.length + 1);
  641. expect(modifyOrder.modifications.length).toBe(1);
  642. expect(modifyOrder.modifications[0].priceChange).toBe(priceDelta);
  643. expect(modifyOrder.modifications[0].orderItems?.length).toBe(1);
  644. expect(modifyOrder.modifications[0].orderItems?.map(i => i.id)).toEqual([
  645. modifyOrder.lines[1].items[0].id,
  646. ]);
  647. await assertModifiedOrderIsPersisted(modifyOrder);
  648. });
  649. it('adjustOrderLines up', async () => {
  650. const order = await createOrderAndTransitionToModifyingState([
  651. {
  652. productVariantId: 'T_1',
  653. quantity: 1,
  654. },
  655. ]);
  656. const { modifyOrder } = await adminClient.query<ModifyOrder.Mutation, ModifyOrder.Variables>(
  657. MODIFY_ORDER,
  658. {
  659. input: {
  660. dryRun: false,
  661. orderId: order.id,
  662. adjustOrderLines: [{ orderLineId: order!.lines[0].id, quantity: 2 }],
  663. },
  664. },
  665. );
  666. orderGuard.assertSuccess(modifyOrder);
  667. const priceDelta = order!.lines[0].unitPriceWithTax;
  668. const expectedTotal = order!.totalWithTax + priceDelta;
  669. expect(modifyOrder.totalWithTax).toBe(expectedTotal);
  670. expect(modifyOrder.lines[0].quantity).toBe(2);
  671. expect(modifyOrder.modifications.length).toBe(1);
  672. expect(modifyOrder.modifications[0].priceChange).toBe(priceDelta);
  673. expect(modifyOrder.modifications[0].orderItems?.length).toBe(1);
  674. expect(
  675. modifyOrder.lines[0].items
  676. .map(i => i.id)
  677. .includes(modifyOrder.modifications?.[0].orderItems?.[0].id as string),
  678. ).toBe(true);
  679. await assertModifiedOrderIsPersisted(modifyOrder);
  680. });
  681. it('adjustOrderLines down', async () => {
  682. const order = await createOrderAndTransitionToModifyingState([
  683. {
  684. productVariantId: 'T_1',
  685. quantity: 2,
  686. },
  687. ]);
  688. const { modifyOrder } = await adminClient.query<ModifyOrder.Mutation, ModifyOrder.Variables>(
  689. MODIFY_ORDER,
  690. {
  691. input: {
  692. dryRun: false,
  693. orderId: order.id,
  694. adjustOrderLines: [{ orderLineId: order!.lines[0].id, quantity: 1 }],
  695. refund: { paymentId: order!.payments![0].id },
  696. },
  697. },
  698. );
  699. orderGuard.assertSuccess(modifyOrder);
  700. const priceDelta = -order!.lines[0].unitPriceWithTax;
  701. const expectedTotal = order!.totalWithTax + priceDelta;
  702. expect(modifyOrder.totalWithTax).toBe(expectedTotal);
  703. expect(modifyOrder.lines[0].quantity).toBe(1);
  704. expect(modifyOrder.payments?.length).toBe(1);
  705. expect(modifyOrder.payments?.[0].refunds.length).toBe(1);
  706. expect(modifyOrder.payments?.[0].refunds[0]).toEqual({
  707. id: 'T_1',
  708. state: 'Pending',
  709. total: -priceDelta,
  710. paymentId: modifyOrder.payments?.[0].id,
  711. });
  712. expect(modifyOrder.modifications.length).toBe(1);
  713. expect(modifyOrder.modifications[0].priceChange).toBe(priceDelta);
  714. expect(modifyOrder.modifications[0].surcharges).toEqual(modifyOrder.surcharges.map(pick(['id'])));
  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 with changed customField value', async () => {
  724. const order = await createOrderAndTransitionToModifyingState([
  725. {
  726. productVariantId: 'T_1',
  727. quantity: 1,
  728. customFields: {
  729. color: 'green',
  730. },
  731. },
  732. ]);
  733. const { modifyOrder } = await adminClient.query<ModifyOrder.Mutation, ModifyOrder.Variables>(
  734. MODIFY_ORDER,
  735. {
  736. input: {
  737. dryRun: false,
  738. orderId: order.id,
  739. adjustOrderLines: [
  740. {
  741. orderLineId: order!.lines[0].id,
  742. quantity: 1,
  743. customFields: { color: 'black' },
  744. } as any,
  745. ],
  746. },
  747. },
  748. );
  749. orderGuard.assertSuccess(modifyOrder);
  750. expect(modifyOrder.lines.length).toBe(1);
  751. const { order: orderWithLines } = await adminClient.query(gql(GET_ORDER_WITH_CUSTOM_FIELDS), {
  752. id: order.id,
  753. });
  754. expect(orderWithLines.lines[0]).toEqual({
  755. id: order!.lines[0].id,
  756. customFields: { color: 'black' },
  757. });
  758. });
  759. it('adjustOrderLines handles quantity correctly', async () => {
  760. await adminClient.query<UpdateProductVariants.Mutation, UpdateProductVariants.Variables>(
  761. UPDATE_PRODUCT_VARIANTS,
  762. {
  763. input: [
  764. {
  765. id: 'T_6',
  766. stockOnHand: 1,
  767. trackInventory: GlobalFlag.TRUE,
  768. },
  769. ],
  770. },
  771. );
  772. const order = await createOrderAndTransitionToModifyingState([
  773. {
  774. productVariantId: 'T_6',
  775. quantity: 1,
  776. },
  777. ]);
  778. const { modifyOrder } = await adminClient.query<ModifyOrder.Mutation, ModifyOrder.Variables>(
  779. MODIFY_ORDER,
  780. {
  781. input: {
  782. dryRun: false,
  783. orderId: order.id,
  784. adjustOrderLines: [
  785. {
  786. orderLineId: order.lines[0].id,
  787. quantity: 1,
  788. },
  789. ],
  790. updateShippingAddress: {
  791. fullName: 'Jim',
  792. },
  793. },
  794. },
  795. );
  796. orderGuard.assertSuccess(modifyOrder);
  797. });
  798. it('surcharge positive', async () => {
  799. const order = await createOrderAndTransitionToModifyingState([
  800. {
  801. productVariantId: 'T_1',
  802. quantity: 1,
  803. },
  804. ]);
  805. const { modifyOrder } = await adminClient.query<ModifyOrder.Mutation, ModifyOrder.Variables>(
  806. MODIFY_ORDER,
  807. {
  808. input: {
  809. dryRun: false,
  810. orderId: order.id,
  811. surcharges: [
  812. {
  813. description: 'extra fee',
  814. sku: '123',
  815. price: 300,
  816. priceIncludesTax: true,
  817. taxRate: 20,
  818. taxDescription: 'VAT',
  819. },
  820. ],
  821. },
  822. },
  823. );
  824. orderGuard.assertSuccess(modifyOrder);
  825. const priceDelta = 300;
  826. const expectedTotal = order!.totalWithTax + priceDelta;
  827. expect(modifyOrder.totalWithTax).toBe(expectedTotal);
  828. expect(modifyOrder.surcharges.map(s => omit(s, ['id']))).toEqual([
  829. {
  830. description: 'extra fee',
  831. sku: '123',
  832. price: 250,
  833. priceWithTax: 300,
  834. taxRate: 20,
  835. },
  836. ]);
  837. expect(modifyOrder.modifications.length).toBe(1);
  838. expect(modifyOrder.modifications[0].priceChange).toBe(priceDelta);
  839. expect(modifyOrder.modifications[0].surcharges).toEqual(modifyOrder.surcharges.map(pick(['id'])));
  840. await assertModifiedOrderIsPersisted(modifyOrder);
  841. });
  842. it('surcharge negative', async () => {
  843. const order = await createOrderAndTransitionToModifyingState([
  844. {
  845. productVariantId: 'T_1',
  846. quantity: 1,
  847. },
  848. ]);
  849. const { modifyOrder } = await adminClient.query<ModifyOrder.Mutation, ModifyOrder.Variables>(
  850. MODIFY_ORDER,
  851. {
  852. input: {
  853. dryRun: false,
  854. orderId: order!.id,
  855. surcharges: [
  856. {
  857. description: 'special discount',
  858. sku: '123',
  859. price: -300,
  860. priceIncludesTax: true,
  861. taxRate: 20,
  862. taxDescription: 'VAT',
  863. },
  864. ],
  865. refund: {
  866. paymentId: order!.payments![0].id,
  867. },
  868. },
  869. },
  870. );
  871. orderGuard.assertSuccess(modifyOrder);
  872. const expectedTotal = order!.totalWithTax + -300;
  873. expect(modifyOrder.totalWithTax).toBe(expectedTotal);
  874. expect(modifyOrder.surcharges.map(s => omit(s, ['id']))).toEqual([
  875. {
  876. description: 'special discount',
  877. sku: '123',
  878. price: -250,
  879. priceWithTax: -300,
  880. taxRate: 20,
  881. },
  882. ]);
  883. expect(modifyOrder.modifications.length).toBe(1);
  884. expect(modifyOrder.modifications[0].priceChange).toBe(-300);
  885. await assertModifiedOrderIsPersisted(modifyOrder);
  886. });
  887. it('update updateShippingAddress, recalculate shipping', async () => {
  888. const order = await createOrderAndTransitionToModifyingState([
  889. {
  890. productVariantId: 'T_1',
  891. quantity: 1,
  892. },
  893. ]);
  894. const { modifyOrder } = await adminClient.query<ModifyOrder.Mutation, ModifyOrder.Variables>(
  895. MODIFY_ORDER,
  896. {
  897. input: {
  898. dryRun: false,
  899. orderId: order!.id,
  900. updateShippingAddress: {
  901. countryCode: 'US',
  902. },
  903. options: {
  904. recalculateShipping: true,
  905. },
  906. },
  907. },
  908. );
  909. orderGuard.assertSuccess(modifyOrder);
  910. const priceDelta = SHIPPING_US - SHIPPING_OTHER;
  911. const expectedTotal = order!.totalWithTax + priceDelta;
  912. expect(modifyOrder.totalWithTax).toBe(expectedTotal);
  913. expect(modifyOrder.shippingAddress?.countryCode).toBe('US');
  914. expect(modifyOrder.modifications.length).toBe(1);
  915. expect(modifyOrder.modifications[0].priceChange).toBe(priceDelta);
  916. await assertModifiedOrderIsPersisted(modifyOrder);
  917. });
  918. it('update updateShippingAddress, do not recalculate shipping', async () => {
  919. const order = await createOrderAndTransitionToModifyingState([
  920. {
  921. productVariantId: 'T_1',
  922. quantity: 1,
  923. },
  924. ]);
  925. const { modifyOrder } = await adminClient.query<ModifyOrder.Mutation, ModifyOrder.Variables>(
  926. MODIFY_ORDER,
  927. {
  928. input: {
  929. dryRun: false,
  930. orderId: order!.id,
  931. updateShippingAddress: {
  932. countryCode: 'US',
  933. },
  934. options: {
  935. recalculateShipping: false,
  936. },
  937. },
  938. },
  939. );
  940. orderGuard.assertSuccess(modifyOrder);
  941. const priceDelta = 0;
  942. const expectedTotal = order!.totalWithTax + priceDelta;
  943. expect(modifyOrder.totalWithTax).toBe(expectedTotal);
  944. expect(modifyOrder.shippingAddress?.countryCode).toBe('US');
  945. expect(modifyOrder.modifications.length).toBe(1);
  946. expect(modifyOrder.modifications[0].priceChange).toBe(priceDelta);
  947. await assertModifiedOrderIsPersisted(modifyOrder);
  948. });
  949. it('update Order customFields', async () => {
  950. const order = await createOrderAndTransitionToModifyingState([
  951. {
  952. productVariantId: 'T_1',
  953. quantity: 1,
  954. },
  955. ]);
  956. const { modifyOrder } = await adminClient.query<ModifyOrder.Mutation, ModifyOrder.Variables>(
  957. MODIFY_ORDER,
  958. {
  959. input: {
  960. dryRun: false,
  961. orderId: order.id,
  962. customFields: {
  963. points: 42,
  964. },
  965. } as any,
  966. },
  967. );
  968. orderGuard.assertSuccess(modifyOrder);
  969. const { order: orderWithCustomFields } = await adminClient.query(
  970. gql(GET_ORDER_WITH_CUSTOM_FIELDS),
  971. { id: order.id },
  972. );
  973. expect(orderWithCustomFields.customFields).toEqual({
  974. points: 42,
  975. });
  976. });
  977. it('adds a history entry', async () => {
  978. const { order } = await adminClient.query<GetOrder.Query, GetOrder.Variables>(GET_ORDER, {
  979. id: orderId,
  980. });
  981. const { modifyOrder } = await adminClient.query<ModifyOrder.Mutation, ModifyOrder.Variables>(
  982. MODIFY_ORDER,
  983. {
  984. input: {
  985. dryRun: false,
  986. orderId: order!.id,
  987. addItems: [{ productVariantId: 'T_5', quantity: 1 }],
  988. },
  989. },
  990. );
  991. orderGuard.assertSuccess(modifyOrder);
  992. const { order: history } = await adminClient.query<
  993. GetOrderHistory.Query,
  994. GetOrderHistory.Variables
  995. >(GET_ORDER_HISTORY, {
  996. id: orderId,
  997. options: { filter: { type: { eq: HistoryEntryType.ORDER_MODIFIED } } },
  998. });
  999. orderGuard.assertSuccess(history);
  1000. expect(history.history.totalItems).toBe(1);
  1001. expect(history.history.items[0].data).toEqual({
  1002. modificationId: modifyOrder.modifications[0].id,
  1003. });
  1004. });
  1005. });
  1006. describe('additional payment handling', () => {
  1007. let orderId2: string;
  1008. beforeAll(async () => {
  1009. const order = await createOrderAndTransitionToModifyingState([
  1010. {
  1011. productVariantId: 'T_1',
  1012. quantity: 1,
  1013. },
  1014. ]);
  1015. const { modifyOrder } = await adminClient.query<ModifyOrder.Mutation, ModifyOrder.Variables>(
  1016. MODIFY_ORDER,
  1017. {
  1018. input: {
  1019. dryRun: false,
  1020. orderId: order.id,
  1021. surcharges: [
  1022. {
  1023. description: 'extra fee',
  1024. sku: '123',
  1025. price: 300,
  1026. priceIncludesTax: true,
  1027. taxRate: 20,
  1028. taxDescription: 'VAT',
  1029. },
  1030. ],
  1031. },
  1032. },
  1033. );
  1034. orderGuard.assertSuccess(modifyOrder);
  1035. orderId2 = modifyOrder.id;
  1036. });
  1037. it('cannot transition back to original state if no payment is set', async () => {
  1038. const { transitionOrderToState } = await adminClient.query<
  1039. AdminTransition.Mutation,
  1040. AdminTransition.Variables
  1041. >(ADMIN_TRANSITION_TO_STATE, {
  1042. id: orderId2,
  1043. state: 'PaymentSettled',
  1044. });
  1045. orderGuard.assertErrorResult(transitionOrderToState);
  1046. expect(transitionOrderToState!.errorCode).toBe(ErrorCode.ORDER_STATE_TRANSITION_ERROR);
  1047. expect(transitionOrderToState!.transitionError).toBe(
  1048. `Can only transition to the "ArrangingAdditionalPayment" state`,
  1049. );
  1050. });
  1051. it('can transition to ArrangingAdditionalPayment state', async () => {
  1052. const { transitionOrderToState } = await adminClient.query<
  1053. AdminTransition.Mutation,
  1054. AdminTransition.Variables
  1055. >(ADMIN_TRANSITION_TO_STATE, {
  1056. id: orderId2,
  1057. state: 'ArrangingAdditionalPayment',
  1058. });
  1059. orderGuard.assertSuccess(transitionOrderToState);
  1060. expect(transitionOrderToState!.state).toBe('ArrangingAdditionalPayment');
  1061. });
  1062. it('cannot transition from ArrangingAdditionalPayment when total not covered by Payments', async () => {
  1063. const { transitionOrderToState } = await adminClient.query<
  1064. AdminTransition.Mutation,
  1065. AdminTransition.Variables
  1066. >(ADMIN_TRANSITION_TO_STATE, {
  1067. id: orderId2,
  1068. state: 'PaymentSettled',
  1069. });
  1070. orderGuard.assertErrorResult(transitionOrderToState);
  1071. expect(transitionOrderToState!.errorCode).toBe(ErrorCode.ORDER_STATE_TRANSITION_ERROR);
  1072. expect(transitionOrderToState!.transitionError).toBe(
  1073. `Cannot transition away from "ArrangingAdditionalPayment" unless Order total is covered by Payments`,
  1074. );
  1075. });
  1076. it('addManualPaymentToOrder', async () => {
  1077. const { addManualPaymentToOrder } = await adminClient.query<
  1078. AddManualPayment.Mutation,
  1079. AddManualPayment.Variables
  1080. >(ADD_MANUAL_PAYMENT, {
  1081. input: {
  1082. orderId: orderId2,
  1083. method: 'test',
  1084. transactionId: 'ABC123',
  1085. metadata: {
  1086. foo: 'bar',
  1087. },
  1088. },
  1089. });
  1090. orderGuard.assertSuccess(addManualPaymentToOrder);
  1091. expect(addManualPaymentToOrder.payments?.length).toBe(2);
  1092. expect(omit(addManualPaymentToOrder.payments![1], ['id'])).toEqual({
  1093. transactionId: 'ABC123',
  1094. state: 'Settled',
  1095. amount: 300,
  1096. method: 'test',
  1097. metadata: {
  1098. foo: 'bar',
  1099. },
  1100. refunds: [],
  1101. });
  1102. expect(addManualPaymentToOrder.modifications[0].isSettled).toBe(true);
  1103. expect(addManualPaymentToOrder.modifications[0].payment?.id).toBe(
  1104. addManualPaymentToOrder.payments![1].id,
  1105. );
  1106. });
  1107. it('transition back to original state', async () => {
  1108. const { transitionOrderToState } = await adminClient.query<
  1109. AdminTransition.Mutation,
  1110. AdminTransition.Variables
  1111. >(ADMIN_TRANSITION_TO_STATE, {
  1112. id: orderId2,
  1113. state: 'PaymentSettled',
  1114. });
  1115. orderGuard.assertSuccess(transitionOrderToState);
  1116. expect(transitionOrderToState.state).toBe('PaymentSettled');
  1117. });
  1118. });
  1119. describe('refund handling', () => {
  1120. let orderId3: string;
  1121. beforeAll(async () => {
  1122. const order = await createOrderAndTransitionToModifyingState([
  1123. {
  1124. productVariantId: 'T_1',
  1125. quantity: 1,
  1126. },
  1127. ]);
  1128. const { modifyOrder } = await adminClient.query<ModifyOrder.Mutation, ModifyOrder.Variables>(
  1129. MODIFY_ORDER,
  1130. {
  1131. input: {
  1132. dryRun: false,
  1133. orderId: order.id,
  1134. surcharges: [
  1135. {
  1136. description: 'discount',
  1137. sku: '123',
  1138. price: -300,
  1139. priceIncludesTax: true,
  1140. taxRate: 20,
  1141. taxDescription: 'VAT',
  1142. },
  1143. ],
  1144. refund: {
  1145. paymentId: order.payments![0].id,
  1146. reason: 'discount',
  1147. },
  1148. },
  1149. },
  1150. );
  1151. orderGuard.assertSuccess(modifyOrder);
  1152. orderId3 = modifyOrder.id;
  1153. });
  1154. it('modification is settled', async () => {
  1155. const { order } = await adminClient.query<
  1156. GetOrderWithModifications.Query,
  1157. GetOrderWithModifications.Variables
  1158. >(GET_ORDER_WITH_MODIFICATIONS, { id: orderId3 });
  1159. expect(order?.modifications.length).toBe(1);
  1160. expect(order?.modifications[0].isSettled).toBe(true);
  1161. });
  1162. it('cannot transition to ArrangingAdditionalPayment state if no payment is needed', async () => {
  1163. const { transitionOrderToState } = await adminClient.query<
  1164. AdminTransition.Mutation,
  1165. AdminTransition.Variables
  1166. >(ADMIN_TRANSITION_TO_STATE, {
  1167. id: orderId3,
  1168. state: 'ArrangingAdditionalPayment',
  1169. });
  1170. orderGuard.assertErrorResult(transitionOrderToState);
  1171. expect(transitionOrderToState!.errorCode).toBe(ErrorCode.ORDER_STATE_TRANSITION_ERROR);
  1172. expect(transitionOrderToState!.transitionError).toBe(
  1173. `Cannot transition Order to the \"ArrangingAdditionalPayment\" state as no additional payments are needed`,
  1174. );
  1175. });
  1176. it('can transition to original state', async () => {
  1177. const { transitionOrderToState } = await adminClient.query<
  1178. AdminTransition.Mutation,
  1179. AdminTransition.Variables
  1180. >(ADMIN_TRANSITION_TO_STATE, {
  1181. id: orderId3,
  1182. state: 'PaymentSettled',
  1183. });
  1184. orderGuard.assertSuccess(transitionOrderToState);
  1185. expect(transitionOrderToState!.state).toBe('PaymentSettled');
  1186. const { order } = await adminClient.query<GetOrder.Query, GetOrder.Variables>(GET_ORDER, {
  1187. id: orderId3,
  1188. });
  1189. expect(order?.payments![0].refunds.length).toBe(1);
  1190. expect(order?.payments![0].refunds[0].total).toBe(300);
  1191. expect(order?.payments![0].refunds[0].reason).toBe('discount');
  1192. });
  1193. });
  1194. // https://github.com/vendure-ecommerce/vendure/issues/688 - 4th point
  1195. it('correct additional payment when discounts applied', async () => {
  1196. await adminClient.query<CreatePromotion.Mutation, CreatePromotion.Variables>(CREATE_PROMOTION, {
  1197. input: {
  1198. name: '$5 off',
  1199. couponCode: '5OFF',
  1200. enabled: true,
  1201. conditions: [],
  1202. actions: [
  1203. {
  1204. code: orderFixedDiscount.code,
  1205. arguments: [{ name: 'discount', value: '500' }],
  1206. },
  1207. ],
  1208. },
  1209. });
  1210. await shopClient.asUserWithCredentials('trevor_donnelly96@hotmail.com', 'test');
  1211. await shopClient.query(gql(ADD_ITEM_TO_ORDER_WITH_CUSTOM_FIELDS), {
  1212. productVariantId: 'T_1',
  1213. quantity: 1,
  1214. } as any);
  1215. await shopClient.query<ApplyCouponCode.Mutation, ApplyCouponCode.Variables>(APPLY_COUPON_CODE, {
  1216. couponCode: '5OFF',
  1217. });
  1218. await proceedToArrangingPayment(shopClient);
  1219. const order = await addPaymentToOrder(shopClient, testSuccessfulPaymentMethod);
  1220. orderGuard.assertSuccess(order);
  1221. const originalTotalWithTax = order.totalWithTax;
  1222. const surcharge = 300;
  1223. const { transitionOrderToState } = await adminClient.query<
  1224. AdminTransition.Mutation,
  1225. AdminTransition.Variables
  1226. >(ADMIN_TRANSITION_TO_STATE, {
  1227. id: order.id,
  1228. state: 'Modifying',
  1229. });
  1230. orderGuard.assertSuccess(transitionOrderToState);
  1231. expect(transitionOrderToState.state).toBe('Modifying');
  1232. const { modifyOrder } = await adminClient.query<ModifyOrder.Mutation, ModifyOrder.Variables>(
  1233. MODIFY_ORDER,
  1234. {
  1235. input: {
  1236. dryRun: false,
  1237. orderId: order.id,
  1238. surcharges: [
  1239. {
  1240. description: 'extra fee',
  1241. sku: '123',
  1242. price: surcharge,
  1243. priceIncludesTax: true,
  1244. taxRate: 20,
  1245. taxDescription: 'VAT',
  1246. },
  1247. ],
  1248. },
  1249. },
  1250. );
  1251. orderGuard.assertSuccess(modifyOrder);
  1252. expect(modifyOrder.totalWithTax).toBe(originalTotalWithTax + surcharge);
  1253. });
  1254. // https://github.com/vendure-ecommerce/vendure/issues/872
  1255. describe('correct price calculations when prices include tax', () => {
  1256. async function modifyOrderLineQuantity(order: TestOrderWithPaymentsFragment) {
  1257. const { transitionOrderToState } = await adminClient.query<
  1258. AdminTransition.Mutation,
  1259. AdminTransition.Variables
  1260. >(ADMIN_TRANSITION_TO_STATE, {
  1261. id: order.id,
  1262. state: 'Modifying',
  1263. });
  1264. orderGuard.assertSuccess(transitionOrderToState);
  1265. expect(transitionOrderToState.state).toBe('Modifying');
  1266. const { modifyOrder } = await adminClient.query<ModifyOrder.Mutation, ModifyOrder.Variables>(
  1267. MODIFY_ORDER,
  1268. {
  1269. input: {
  1270. dryRun: true,
  1271. orderId: order.id,
  1272. adjustOrderLines: [{ orderLineId: order!.lines[0].id, quantity: 2 }],
  1273. },
  1274. },
  1275. );
  1276. orderGuard.assertSuccess(modifyOrder);
  1277. return modifyOrder;
  1278. }
  1279. beforeAll(async () => {
  1280. await adminClient.query<UpdateChannel.Mutation, UpdateChannel.Variables>(UPDATE_CHANNEL, {
  1281. input: {
  1282. id: 'T_1',
  1283. pricesIncludeTax: true,
  1284. },
  1285. });
  1286. });
  1287. it('without promotion', async () => {
  1288. await shopClient.asUserWithCredentials('hayden.zieme12@hotmail.com', 'test');
  1289. await shopClient.query(gql(ADD_ITEM_TO_ORDER_WITH_CUSTOM_FIELDS), {
  1290. productVariantId: 'T_1',
  1291. quantity: 1,
  1292. } as any);
  1293. await proceedToArrangingPayment(shopClient);
  1294. const order = await addPaymentToOrder(shopClient, testSuccessfulPaymentMethod);
  1295. orderGuard.assertSuccess(order);
  1296. const modifyOrder = await modifyOrderLineQuantity(order);
  1297. expect(modifyOrder.lines[0].linePriceWithTax).toBe(order.lines[0].linePriceWithTax * 2);
  1298. });
  1299. it('with promotion', async () => {
  1300. await adminClient.query<CreatePromotion.Mutation, CreatePromotion.Variables>(CREATE_PROMOTION, {
  1301. input: {
  1302. name: 'half price',
  1303. couponCode: 'HALF',
  1304. enabled: true,
  1305. conditions: [],
  1306. actions: [
  1307. {
  1308. code: productsPercentageDiscount.code,
  1309. arguments: [
  1310. { name: 'discount', value: '50' },
  1311. { name: 'productVariantIds', value: JSON.stringify(['T_1']) },
  1312. ],
  1313. },
  1314. ],
  1315. },
  1316. });
  1317. await shopClient.asUserWithCredentials('trevor_donnelly96@hotmail.com', 'test');
  1318. await shopClient.query(gql(ADD_ITEM_TO_ORDER_WITH_CUSTOM_FIELDS), {
  1319. productVariantId: 'T_1',
  1320. quantity: 1,
  1321. } as any);
  1322. await shopClient.query<ApplyCouponCode.Mutation, ApplyCouponCode.Variables>(APPLY_COUPON_CODE, {
  1323. couponCode: 'HALF',
  1324. });
  1325. await proceedToArrangingPayment(shopClient);
  1326. const order = await addPaymentToOrder(shopClient, testSuccessfulPaymentMethod);
  1327. orderGuard.assertSuccess(order);
  1328. const modifyOrder = await modifyOrderLineQuantity(order);
  1329. expect(modifyOrder.lines[0].discountedLinePriceWithTax).toBe(
  1330. modifyOrder.lines[0].linePriceWithTax / 2,
  1331. );
  1332. expect(modifyOrder.lines[0].linePriceWithTax).toBe(order.lines[0].linePriceWithTax * 2);
  1333. });
  1334. });
  1335. // https://github.com/vendure-ecommerce/vendure/issues/890
  1336. describe('refund handling when promotions are active on order', () => {
  1337. it('refunds correct amount when order-level promotion applied', async () => {
  1338. await adminClient.query<CreatePromotion.Mutation, CreatePromotion.Variables>(CREATE_PROMOTION, {
  1339. input: {
  1340. name: '$5 off',
  1341. couponCode: '5OFF2',
  1342. enabled: true,
  1343. conditions: [],
  1344. actions: [
  1345. {
  1346. code: orderFixedDiscount.code,
  1347. arguments: [{ name: 'discount', value: '500' }],
  1348. },
  1349. ],
  1350. },
  1351. });
  1352. await shopClient.asUserWithCredentials('trevor_donnelly96@hotmail.com', 'test');
  1353. await shopClient.query(gql(ADD_ITEM_TO_ORDER_WITH_CUSTOM_FIELDS), {
  1354. productVariantId: 'T_1',
  1355. quantity: 2,
  1356. } as any);
  1357. await shopClient.query<ApplyCouponCode.Mutation, ApplyCouponCode.Variables>(APPLY_COUPON_CODE, {
  1358. couponCode: '5OFF2',
  1359. });
  1360. await proceedToArrangingPayment(shopClient);
  1361. const order = await addPaymentToOrder(shopClient, testSuccessfulPaymentMethod);
  1362. orderGuard.assertSuccess(order);
  1363. const originalTotalWithTax = order.totalWithTax;
  1364. const { transitionOrderToState } = await adminClient.query<
  1365. AdminTransition.Mutation,
  1366. AdminTransition.Variables
  1367. >(ADMIN_TRANSITION_TO_STATE, {
  1368. id: order.id,
  1369. state: 'Modifying',
  1370. });
  1371. orderGuard.assertSuccess(transitionOrderToState);
  1372. expect(transitionOrderToState.state).toBe('Modifying');
  1373. const { modifyOrder } = await adminClient.query<ModifyOrder.Mutation, ModifyOrder.Variables>(
  1374. MODIFY_ORDER,
  1375. {
  1376. input: {
  1377. dryRun: false,
  1378. orderId: order.id,
  1379. adjustOrderLines: [{ orderLineId: order.lines[0].id, quantity: 1 }],
  1380. refund: {
  1381. paymentId: order.payments![0].id,
  1382. reason: 'requested',
  1383. },
  1384. },
  1385. },
  1386. );
  1387. orderGuard.assertSuccess(modifyOrder);
  1388. expect(modifyOrder.totalWithTax).toBe(
  1389. originalTotalWithTax - order.lines[0].proratedUnitPriceWithTax,
  1390. );
  1391. expect(modifyOrder.payments![0].refunds![0].total).toBe(order.lines[0].proratedUnitPriceWithTax);
  1392. });
  1393. });
  1394. // https://github.com/vendure-ecommerce/vendure/issues/1197
  1395. describe('refund on shipping when change made to shippingAddress', () => {
  1396. let order: OrderWithModificationsFragment;
  1397. beforeAll(async () => {
  1398. const createdOrder = await createOrderAndTransitionToModifyingState([
  1399. {
  1400. productVariantId: 'T_1',
  1401. quantity: 1,
  1402. },
  1403. ]);
  1404. const { modifyOrder } = await adminClient.query<ModifyOrder.Mutation, ModifyOrder.Variables>(
  1405. MODIFY_ORDER,
  1406. {
  1407. input: {
  1408. dryRun: false,
  1409. orderId: createdOrder.id,
  1410. updateShippingAddress: {
  1411. countryCode: 'GB',
  1412. },
  1413. refund: {
  1414. paymentId: createdOrder.payments![0].id,
  1415. reason: 'discount',
  1416. },
  1417. },
  1418. },
  1419. );
  1420. orderGuard.assertSuccess(modifyOrder);
  1421. order = modifyOrder;
  1422. });
  1423. it('creates a Refund with the correct amount', async () => {
  1424. expect(order.payments?.[0].refunds[0].total).toBe(SHIPPING_OTHER - SHIPPING_GB);
  1425. });
  1426. it('allows transition to PaymentSettled', async () => {
  1427. const { transitionOrderToState } = await adminClient.query<
  1428. AdminTransition.Mutation,
  1429. AdminTransition.Variables
  1430. >(ADMIN_TRANSITION_TO_STATE, {
  1431. id: order.id,
  1432. state: 'PaymentSettled',
  1433. });
  1434. orderGuard.assertSuccess(transitionOrderToState);
  1435. expect(transitionOrderToState.state).toBe('PaymentSettled');
  1436. });
  1437. });
  1438. async function assertOrderIsUnchanged(order: OrderWithLinesFragment) {
  1439. const { order: order2 } = await adminClient.query<GetOrder.Query, GetOrder.Variables>(GET_ORDER, {
  1440. id: order.id,
  1441. });
  1442. expect(order2!.totalWithTax).toBe(order!.totalWithTax);
  1443. expect(order2!.lines.length).toBe(order!.lines.length);
  1444. expect(order2!.surcharges.length).toBe(order!.surcharges.length);
  1445. expect(order2!.totalQuantity).toBe(order!.totalQuantity);
  1446. }
  1447. async function createOrderAndTransitionToModifyingState(
  1448. items: Array<AddItemToOrderMutationVariables & { customFields?: any }>,
  1449. ): Promise<TestOrderWithPaymentsFragment> {
  1450. await shopClient.asUserWithCredentials('hayden.zieme12@hotmail.com', 'test');
  1451. for (const itemInput of items) {
  1452. await shopClient.query(gql(ADD_ITEM_TO_ORDER_WITH_CUSTOM_FIELDS), itemInput);
  1453. }
  1454. await shopClient.query<SetShippingAddress.Mutation, SetShippingAddress.Variables>(
  1455. SET_SHIPPING_ADDRESS,
  1456. {
  1457. input: {
  1458. fullName: 'name',
  1459. streetLine1: '12 the street',
  1460. city: 'foo',
  1461. postalCode: '123456',
  1462. countryCode: 'AT',
  1463. },
  1464. },
  1465. );
  1466. await shopClient.query<SetShippingMethod.Mutation, SetShippingMethod.Variables>(SET_SHIPPING_METHOD, {
  1467. id: testShippingMethodId,
  1468. });
  1469. await shopClient.query<TransitionToState.Mutation, TransitionToState.Variables>(TRANSITION_TO_STATE, {
  1470. state: 'ArrangingPayment',
  1471. });
  1472. const order = await addPaymentToOrder(shopClient, testSuccessfulPaymentMethod);
  1473. orderGuard.assertSuccess(order);
  1474. const { transitionOrderToState } = await adminClient.query<
  1475. AdminTransition.Mutation,
  1476. AdminTransition.Variables
  1477. >(ADMIN_TRANSITION_TO_STATE, {
  1478. id: order.id,
  1479. state: 'Modifying',
  1480. });
  1481. return order;
  1482. }
  1483. });
  1484. export const ORDER_WITH_MODIFICATION_FRAGMENT = gql`
  1485. fragment OrderWithModifications on Order {
  1486. id
  1487. state
  1488. total
  1489. totalWithTax
  1490. lines {
  1491. id
  1492. quantity
  1493. linePrice
  1494. linePriceWithTax
  1495. discountedLinePriceWithTax
  1496. productVariant {
  1497. id
  1498. name
  1499. }
  1500. items {
  1501. id
  1502. createdAt
  1503. updatedAt
  1504. cancelled
  1505. unitPrice
  1506. }
  1507. }
  1508. surcharges {
  1509. id
  1510. description
  1511. sku
  1512. price
  1513. priceWithTax
  1514. taxRate
  1515. }
  1516. payments {
  1517. id
  1518. transactionId
  1519. state
  1520. amount
  1521. method
  1522. metadata
  1523. refunds {
  1524. id
  1525. state
  1526. total
  1527. paymentId
  1528. }
  1529. }
  1530. modifications {
  1531. id
  1532. note
  1533. priceChange
  1534. isSettled
  1535. orderItems {
  1536. id
  1537. }
  1538. surcharges {
  1539. id
  1540. }
  1541. payment {
  1542. id
  1543. state
  1544. amount
  1545. method
  1546. }
  1547. refund {
  1548. id
  1549. state
  1550. total
  1551. paymentId
  1552. }
  1553. }
  1554. shippingAddress {
  1555. streetLine1
  1556. city
  1557. postalCode
  1558. province
  1559. countryCode
  1560. country
  1561. }
  1562. billingAddress {
  1563. streetLine1
  1564. city
  1565. postalCode
  1566. province
  1567. countryCode
  1568. country
  1569. }
  1570. }
  1571. `;
  1572. export const GET_ORDER_WITH_MODIFICATIONS = gql`
  1573. query GetOrderWithModifications($id: ID!) {
  1574. order(id: $id) {
  1575. ...OrderWithModifications
  1576. }
  1577. }
  1578. ${ORDER_WITH_MODIFICATION_FRAGMENT}
  1579. `;
  1580. export const MODIFY_ORDER = gql`
  1581. mutation ModifyOrder($input: ModifyOrderInput!) {
  1582. modifyOrder(input: $input) {
  1583. ...OrderWithModifications
  1584. ... on ErrorResult {
  1585. errorCode
  1586. message
  1587. }
  1588. }
  1589. }
  1590. ${ORDER_WITH_MODIFICATION_FRAGMENT}
  1591. `;
  1592. export const ADD_MANUAL_PAYMENT = gql`
  1593. mutation AddManualPayment($input: ManualPaymentInput!) {
  1594. addManualPaymentToOrder(input: $input) {
  1595. ...OrderWithModifications
  1596. ... on ErrorResult {
  1597. errorCode
  1598. message
  1599. }
  1600. }
  1601. }
  1602. ${ORDER_WITH_MODIFICATION_FRAGMENT}
  1603. `;
  1604. // Note, we don't use the gql tag around these due to the customFields which
  1605. // would cause a codegen error.
  1606. const ADD_ITEM_TO_ORDER_WITH_CUSTOM_FIELDS = `
  1607. mutation AddItemToOrder($productVariantId: ID!, $quantity: Int!, $customFields: OrderLineCustomFieldsInput) {
  1608. addItemToOrder(productVariantId: $productVariantId, quantity: $quantity, customFields: $customFields) {
  1609. ...on Order { id }
  1610. }
  1611. }
  1612. `;
  1613. const GET_ORDER_WITH_CUSTOM_FIELDS = `
  1614. query GetOrderCustomFields($id: ID!) {
  1615. order(id: $id) {
  1616. customFields { points }
  1617. lines { id, customFields { color } }
  1618. }
  1619. }
  1620. `;