order-modification.e2e-spec.ts 64 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703
  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. async function assertOrderIsUnchanged(order: OrderWithLinesFragment) {
  1395. const { order: order2 } = await adminClient.query<GetOrder.Query, GetOrder.Variables>(GET_ORDER, {
  1396. id: order.id,
  1397. });
  1398. expect(order2!.totalWithTax).toBe(order!.totalWithTax);
  1399. expect(order2!.lines.length).toBe(order!.lines.length);
  1400. expect(order2!.surcharges.length).toBe(order!.surcharges.length);
  1401. expect(order2!.totalQuantity).toBe(order!.totalQuantity);
  1402. }
  1403. async function createOrderAndTransitionToModifyingState(
  1404. items: Array<AddItemToOrderMutationVariables & { customFields?: any }>,
  1405. ): Promise<TestOrderWithPaymentsFragment> {
  1406. await shopClient.asUserWithCredentials('hayden.zieme12@hotmail.com', 'test');
  1407. for (const itemInput of items) {
  1408. await shopClient.query(gql(ADD_ITEM_TO_ORDER_WITH_CUSTOM_FIELDS), itemInput);
  1409. }
  1410. await shopClient.query<SetShippingAddress.Mutation, SetShippingAddress.Variables>(
  1411. SET_SHIPPING_ADDRESS,
  1412. {
  1413. input: {
  1414. fullName: 'name',
  1415. streetLine1: '12 the street',
  1416. city: 'foo',
  1417. postalCode: '123456',
  1418. countryCode: 'AT',
  1419. },
  1420. },
  1421. );
  1422. await shopClient.query<SetShippingMethod.Mutation, SetShippingMethod.Variables>(SET_SHIPPING_METHOD, {
  1423. id: testShippingMethodId,
  1424. });
  1425. await shopClient.query<TransitionToState.Mutation, TransitionToState.Variables>(TRANSITION_TO_STATE, {
  1426. state: 'ArrangingPayment',
  1427. });
  1428. const order = await addPaymentToOrder(shopClient, testSuccessfulPaymentMethod);
  1429. orderGuard.assertSuccess(order);
  1430. const { transitionOrderToState } = await adminClient.query<
  1431. AdminTransition.Mutation,
  1432. AdminTransition.Variables
  1433. >(ADMIN_TRANSITION_TO_STATE, {
  1434. id: order.id,
  1435. state: 'Modifying',
  1436. });
  1437. return order;
  1438. }
  1439. });
  1440. export const ORDER_WITH_MODIFICATION_FRAGMENT = gql`
  1441. fragment OrderWithModifications on Order {
  1442. id
  1443. state
  1444. total
  1445. totalWithTax
  1446. lines {
  1447. id
  1448. quantity
  1449. linePrice
  1450. linePriceWithTax
  1451. discountedLinePriceWithTax
  1452. productVariant {
  1453. id
  1454. name
  1455. }
  1456. items {
  1457. id
  1458. createdAt
  1459. updatedAt
  1460. cancelled
  1461. unitPrice
  1462. }
  1463. }
  1464. surcharges {
  1465. id
  1466. description
  1467. sku
  1468. price
  1469. priceWithTax
  1470. taxRate
  1471. }
  1472. payments {
  1473. id
  1474. transactionId
  1475. state
  1476. amount
  1477. method
  1478. metadata
  1479. refunds {
  1480. id
  1481. state
  1482. total
  1483. paymentId
  1484. }
  1485. }
  1486. modifications {
  1487. id
  1488. note
  1489. priceChange
  1490. isSettled
  1491. orderItems {
  1492. id
  1493. }
  1494. surcharges {
  1495. id
  1496. }
  1497. payment {
  1498. id
  1499. state
  1500. amount
  1501. method
  1502. }
  1503. refund {
  1504. id
  1505. state
  1506. total
  1507. paymentId
  1508. }
  1509. }
  1510. shippingAddress {
  1511. streetLine1
  1512. city
  1513. postalCode
  1514. province
  1515. countryCode
  1516. country
  1517. }
  1518. billingAddress {
  1519. streetLine1
  1520. city
  1521. postalCode
  1522. province
  1523. countryCode
  1524. country
  1525. }
  1526. }
  1527. `;
  1528. export const GET_ORDER_WITH_MODIFICATIONS = gql`
  1529. query GetOrderWithModifications($id: ID!) {
  1530. order(id: $id) {
  1531. ...OrderWithModifications
  1532. }
  1533. }
  1534. ${ORDER_WITH_MODIFICATION_FRAGMENT}
  1535. `;
  1536. export const MODIFY_ORDER = gql`
  1537. mutation ModifyOrder($input: ModifyOrderInput!) {
  1538. modifyOrder(input: $input) {
  1539. ...OrderWithModifications
  1540. ... on ErrorResult {
  1541. errorCode
  1542. message
  1543. }
  1544. }
  1545. }
  1546. ${ORDER_WITH_MODIFICATION_FRAGMENT}
  1547. `;
  1548. export const ADD_MANUAL_PAYMENT = gql`
  1549. mutation AddManualPayment($input: ManualPaymentInput!) {
  1550. addManualPaymentToOrder(input: $input) {
  1551. ...OrderWithModifications
  1552. ... on ErrorResult {
  1553. errorCode
  1554. message
  1555. }
  1556. }
  1557. }
  1558. ${ORDER_WITH_MODIFICATION_FRAGMENT}
  1559. `;
  1560. // Note, we don't use the gql tag around these due to the customFields which
  1561. // would cause a codegen error.
  1562. const ADD_ITEM_TO_ORDER_WITH_CUSTOM_FIELDS = `
  1563. mutation AddItemToOrder($productVariantId: ID!, $quantity: Int!, $customFields: OrderLineCustomFieldsInput) {
  1564. addItemToOrder(productVariantId: $productVariantId, quantity: $quantity, customFields: $customFields) {
  1565. ...on Order { id }
  1566. }
  1567. }
  1568. `;
  1569. const GET_ORDER_WITH_CUSTOM_FIELDS = `
  1570. query GetOrderCustomFields($id: ID!) {
  1571. order(id: $id) {
  1572. customFields { points }
  1573. lines { id, customFields { color } }
  1574. }
  1575. }
  1576. `;