shop-order.e2e-spec.ts 113 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714
  1. /* eslint-disable @typescript-eslint/no-non-null-assertion */
  2. import { pick } from '@vendure/common/lib/pick';
  3. import {
  4. Asset,
  5. defaultShippingCalculator,
  6. defaultShippingEligibilityChecker,
  7. manualFulfillmentHandler,
  8. mergeConfig,
  9. } from '@vendure/core';
  10. import { createErrorResultGuard, createTestEnvironment, ErrorResultGuard } from '@vendure/testing';
  11. import gql from 'graphql-tag';
  12. import path from 'path';
  13. import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest';
  14. import { initialData } from '../../../e2e-common/e2e-initial-data';
  15. import { TEST_SETUP_TIMEOUT_MS, testConfig } from '../../../e2e-common/test-config';
  16. import {
  17. testErrorPaymentMethod,
  18. testFailingPaymentMethod,
  19. testSuccessfulPaymentMethod,
  20. } from './fixtures/test-payment-methods';
  21. import {
  22. countryCodeShippingEligibilityChecker,
  23. hydratingShippingEligibilityChecker,
  24. } from './fixtures/test-shipping-eligibility-checkers';
  25. import * as Codegen from './graphql/generated-e2e-admin-types';
  26. import {
  27. CreateAddressInput,
  28. CreateShippingMethodDocument,
  29. CreateShippingMethodInput,
  30. GlobalFlag,
  31. LanguageCode,
  32. } from './graphql/generated-e2e-admin-types';
  33. import * as CodegenShop from './graphql/generated-e2e-shop-types';
  34. import { ErrorCode, RemoveItemFromOrderDocument } from './graphql/generated-e2e-shop-types';
  35. import {
  36. ATTEMPT_LOGIN,
  37. CANCEL_ORDER,
  38. CREATE_SHIPPING_METHOD,
  39. DELETE_PRODUCT,
  40. DELETE_PRODUCT_VARIANT,
  41. DELETE_SHIPPING_METHOD,
  42. GET_COUNTRY_LIST,
  43. GET_CUSTOMER,
  44. GET_CUSTOMER_LIST,
  45. GET_SHIPPING_METHOD_LIST,
  46. UPDATE_COUNTRY,
  47. UPDATE_PRODUCT,
  48. UPDATE_PRODUCT_VARIANTS,
  49. } from './graphql/shared-definitions';
  50. import {
  51. ADD_ITEM_TO_ORDER,
  52. ADD_PAYMENT,
  53. ADJUST_ITEM_QUANTITY,
  54. GET_ACTIVE_ORDER,
  55. GET_ACTIVE_ORDER_ADDRESSES,
  56. GET_ACTIVE_ORDER_ORDERS,
  57. GET_ACTIVE_ORDER_PAYMENTS,
  58. GET_ACTIVE_ORDER_WITH_PAYMENTS,
  59. GET_AVAILABLE_COUNTRIES,
  60. GET_ELIGIBLE_SHIPPING_METHODS,
  61. GET_NEXT_STATES,
  62. GET_ORDER_BY_CODE,
  63. REMOVE_ALL_ORDER_LINES,
  64. REMOVE_ITEM_FROM_ORDER,
  65. SET_BILLING_ADDRESS,
  66. SET_CUSTOMER,
  67. SET_SHIPPING_ADDRESS,
  68. SET_SHIPPING_METHOD,
  69. TRANSITION_TO_STATE,
  70. UPDATED_ORDER_FRAGMENT,
  71. } from './graphql/shop-definitions';
  72. import { assertThrowsWithMessage } from './utils/assert-throws-with-message';
  73. describe('Shop orders', () => {
  74. const { server, adminClient, shopClient } = createTestEnvironment(
  75. mergeConfig(testConfig(), {
  76. paymentOptions: {
  77. paymentMethodHandlers: [
  78. testSuccessfulPaymentMethod,
  79. testFailingPaymentMethod,
  80. testErrorPaymentMethod,
  81. ],
  82. },
  83. shippingOptions: {
  84. shippingEligibilityCheckers: [
  85. defaultShippingEligibilityChecker,
  86. countryCodeShippingEligibilityChecker,
  87. hydratingShippingEligibilityChecker,
  88. ],
  89. },
  90. customFields: {
  91. Order: [
  92. { name: 'giftWrap', type: 'boolean', defaultValue: false },
  93. { name: 'orderImage', type: 'relation', entity: Asset },
  94. ],
  95. OrderLine: [
  96. { name: 'notes', type: 'string' },
  97. { name: 'privateField', type: 'string', public: false },
  98. { name: 'lineImage', type: 'relation', entity: Asset },
  99. { name: 'lineImages', type: 'relation', list: true, entity: Asset },
  100. { name: 'dropShip', type: 'boolean', defaultValue: false },
  101. ],
  102. },
  103. orderOptions: {
  104. orderItemsLimit: 199,
  105. },
  106. }),
  107. );
  108. type OrderSuccessResult =
  109. | CodegenShop.UpdatedOrderFragment
  110. | CodegenShop.TestOrderFragmentFragment
  111. | CodegenShop.TestOrderWithPaymentsFragment
  112. | CodegenShop.ActiveOrderCustomerFragment;
  113. const orderResultGuard: ErrorResultGuard<OrderSuccessResult> = createErrorResultGuard(
  114. input => !!input.lines,
  115. );
  116. beforeAll(async () => {
  117. await server.init({
  118. initialData: {
  119. ...initialData,
  120. paymentMethods: [
  121. {
  122. name: testSuccessfulPaymentMethod.code,
  123. handler: { code: testSuccessfulPaymentMethod.code, arguments: [] },
  124. },
  125. {
  126. name: testFailingPaymentMethod.code,
  127. handler: { code: testFailingPaymentMethod.code, arguments: [] },
  128. },
  129. {
  130. name: testErrorPaymentMethod.code,
  131. handler: { code: testErrorPaymentMethod.code, arguments: [] },
  132. },
  133. ],
  134. },
  135. productsCsvPath: path.join(__dirname, 'fixtures/e2e-products-full.csv'),
  136. customerCount: 3,
  137. });
  138. await adminClient.asSuperAdmin();
  139. }, TEST_SETUP_TIMEOUT_MS);
  140. afterAll(async () => {
  141. await server.destroy();
  142. });
  143. it('availableCountries returns enabled countries', async () => {
  144. // disable Austria
  145. const { countries } = await adminClient.query<Codegen.GetCountryListQuery>(GET_COUNTRY_LIST, {});
  146. const AT = countries.items.find(c => c.code === 'AT')!;
  147. await adminClient.query<Codegen.UpdateCountryMutation, Codegen.UpdateCountryMutationVariables>(
  148. UPDATE_COUNTRY,
  149. {
  150. input: {
  151. id: AT.id,
  152. enabled: false,
  153. },
  154. },
  155. );
  156. const result =
  157. await shopClient.query<CodegenShop.GetAvailableCountriesQuery>(GET_AVAILABLE_COUNTRIES);
  158. expect(result.availableCountries.length).toBe(countries.items.length - 1);
  159. expect(result.availableCountries.find(c => c.id === AT.id)).toBeUndefined();
  160. });
  161. describe('ordering as anonymous user', () => {
  162. let firstOrderLineId: string;
  163. let createdCustomerId: string;
  164. let orderCode: string;
  165. it('addItemToOrder starts with no session token', () => {
  166. expect(shopClient.getAuthToken()).toBeFalsy();
  167. });
  168. it('activeOrder returns null before any items have been added', async () => {
  169. const result = await shopClient.query<CodegenShop.GetActiveOrderQuery>(GET_ACTIVE_ORDER);
  170. expect(result.activeOrder).toBeNull();
  171. });
  172. it('activeOrder creates an anonymous session', () => {
  173. expect(shopClient.getAuthToken()).not.toBe('');
  174. });
  175. it('addItemToOrder creates a new Order with an item', async () => {
  176. const { addItemToOrder } = await shopClient.query<
  177. CodegenShop.AddItemToOrderMutation,
  178. CodegenShop.AddItemToOrderMutationVariables
  179. >(ADD_ITEM_TO_ORDER, {
  180. productVariantId: 'T_1',
  181. quantity: 1,
  182. });
  183. orderResultGuard.assertSuccess(addItemToOrder);
  184. expect(addItemToOrder.lines.length).toBe(1);
  185. expect(addItemToOrder.lines[0].quantity).toBe(1);
  186. expect(addItemToOrder.lines[0].productVariant.id).toBe('T_1');
  187. expect(addItemToOrder.lines[0].id).toBe('T_1');
  188. firstOrderLineId = addItemToOrder.lines[0].id;
  189. orderCode = addItemToOrder.code;
  190. });
  191. it(
  192. 'addItemToOrder errors with an invalid productVariantId',
  193. assertThrowsWithMessage(
  194. () =>
  195. shopClient.query<
  196. CodegenShop.AddItemToOrderMutation,
  197. CodegenShop.AddItemToOrderMutationVariables
  198. >(ADD_ITEM_TO_ORDER, {
  199. productVariantId: 'T_999',
  200. quantity: 1,
  201. }),
  202. 'No ProductVariant with the id "999" could be found',
  203. ),
  204. );
  205. it('addItemToOrder errors with a negative quantity', async () => {
  206. const { addItemToOrder } = await shopClient.query<
  207. CodegenShop.AddItemToOrderMutation,
  208. CodegenShop.AddItemToOrderMutationVariables
  209. >(ADD_ITEM_TO_ORDER, {
  210. productVariantId: 'T_999',
  211. quantity: -3,
  212. });
  213. orderResultGuard.assertErrorResult(addItemToOrder);
  214. expect(addItemToOrder.message).toEqual('The quantity for an OrderItem cannot be negative');
  215. expect(addItemToOrder.errorCode).toEqual(ErrorCode.NEGATIVE_QUANTITY_ERROR);
  216. });
  217. it('addItemToOrder with an existing productVariantId adds quantity to the existing OrderLine', async () => {
  218. const { addItemToOrder } = await shopClient.query<
  219. CodegenShop.AddItemToOrderMutation,
  220. CodegenShop.AddItemToOrderMutationVariables
  221. >(ADD_ITEM_TO_ORDER, {
  222. productVariantId: 'T_1',
  223. quantity: 2,
  224. });
  225. orderResultGuard.assertSuccess(addItemToOrder);
  226. expect(addItemToOrder.lines.length).toBe(1);
  227. expect(addItemToOrder.lines[0].quantity).toBe(3);
  228. });
  229. describe('OrderLine customFields', () => {
  230. const GET_ORDER_WITH_ORDER_LINE_CUSTOM_FIELDS = gql`
  231. query {
  232. activeOrder {
  233. lines {
  234. id
  235. customFields {
  236. notes
  237. lineImage {
  238. id
  239. }
  240. lineImages {
  241. id
  242. }
  243. }
  244. }
  245. }
  246. }
  247. `;
  248. it('addItemToOrder with private customFields errors', async () => {
  249. try {
  250. await shopClient.query<CodegenShop.AddItemToOrderMutation>(
  251. ADD_ITEM_TO_ORDER_WITH_CUSTOM_FIELDS,
  252. {
  253. productVariantId: 'T_2',
  254. quantity: 1,
  255. customFields: {
  256. privateField: 'oh no!',
  257. },
  258. },
  259. );
  260. fail('Should have thrown');
  261. } catch (e: any) {
  262. expect(e.response.errors[0].extensions.code).toBe('BAD_USER_INPUT');
  263. }
  264. });
  265. it('addItemToOrder with equal customFields adds quantity to the existing OrderLine', async () => {
  266. const { addItemToOrder: add1 } = await shopClient.query<CodegenShop.AddItemToOrderMutation>(
  267. ADD_ITEM_TO_ORDER_WITH_CUSTOM_FIELDS,
  268. {
  269. productVariantId: 'T_2',
  270. quantity: 1,
  271. customFields: {
  272. notes: 'note1',
  273. },
  274. },
  275. );
  276. orderResultGuard.assertSuccess(add1);
  277. expect(add1.lines.length).toBe(2);
  278. expect(add1.lines[1].quantity).toBe(1);
  279. const { addItemToOrder: add2 } = await shopClient.query<CodegenShop.AddItemToOrderMutation>(
  280. ADD_ITEM_TO_ORDER_WITH_CUSTOM_FIELDS,
  281. {
  282. productVariantId: 'T_2',
  283. quantity: 1,
  284. customFields: {
  285. notes: 'note1',
  286. },
  287. },
  288. );
  289. orderResultGuard.assertSuccess(add2);
  290. expect(add2.lines.length).toBe(2);
  291. expect(add2.lines[1].quantity).toBe(2);
  292. await shopClient.query<
  293. CodegenShop.RemoveItemFromOrderMutation,
  294. CodegenShop.RemoveItemFromOrderMutationVariables
  295. >(REMOVE_ITEM_FROM_ORDER, {
  296. orderLineId: add2.lines[1].id,
  297. });
  298. });
  299. it('addItemToOrder with different customFields adds quantity to a new OrderLine', async () => {
  300. const { addItemToOrder: add1 } = await shopClient.query<CodegenShop.AddItemToOrderMutation>(
  301. ADD_ITEM_TO_ORDER_WITH_CUSTOM_FIELDS,
  302. {
  303. productVariantId: 'T_3',
  304. quantity: 1,
  305. customFields: {
  306. notes: 'note2',
  307. },
  308. },
  309. );
  310. orderResultGuard.assertSuccess(add1);
  311. expect(add1.lines.length).toBe(2);
  312. expect(add1.lines[1].quantity).toBe(1);
  313. const { addItemToOrder: add2 } = await shopClient.query<CodegenShop.AddItemToOrderMutation>(
  314. ADD_ITEM_TO_ORDER_WITH_CUSTOM_FIELDS,
  315. {
  316. productVariantId: 'T_3',
  317. quantity: 1,
  318. customFields: {
  319. notes: 'note3',
  320. },
  321. },
  322. );
  323. orderResultGuard.assertSuccess(add2);
  324. expect(add2.lines.length).toBe(3);
  325. expect(add2.lines[1].quantity).toBe(1);
  326. expect(add2.lines[2].quantity).toBe(1);
  327. await shopClient.query<
  328. CodegenShop.RemoveItemFromOrderMutation,
  329. CodegenShop.RemoveItemFromOrderMutationVariables
  330. >(REMOVE_ITEM_FROM_ORDER, {
  331. orderLineId: add2.lines[1].id,
  332. });
  333. await shopClient.query<
  334. CodegenShop.RemoveItemFromOrderMutation,
  335. CodegenShop.RemoveItemFromOrderMutationVariables
  336. >(REMOVE_ITEM_FROM_ORDER, {
  337. orderLineId: add2.lines[2].id,
  338. });
  339. });
  340. // https://github.com/vendure-ecommerce/vendure/issues/1670
  341. it('adding a second item after adjusting custom field adds new OrderLine', async () => {
  342. const { addItemToOrder: add1 } = await shopClient.query<AddItemToOrder.Mutation>(
  343. ADD_ITEM_TO_ORDER_WITH_CUSTOM_FIELDS,
  344. {
  345. productVariantId: 'T_3',
  346. quantity: 1,
  347. },
  348. );
  349. orderResultGuard.assertSuccess(add1);
  350. expect(add1.lines.length).toBe(2);
  351. expect(add1.lines[1].quantity).toBe(1);
  352. const { adjustOrderLine } = await shopClient.query(ADJUST_ORDER_LINE_WITH_CUSTOM_FIELDS, {
  353. orderLineId: add1.lines[1].id,
  354. quantity: 1,
  355. customFields: {
  356. notes: 'updated notes',
  357. },
  358. });
  359. expect(adjustOrderLine.lines[1].customFields).toEqual({
  360. lineImage: null,
  361. lineImages: [],
  362. notes: 'updated notes',
  363. });
  364. const { activeOrder: ao1 } = await shopClient.query(GET_ORDER_WITH_ORDER_LINE_CUSTOM_FIELDS);
  365. expect(ao1.lines[1].customFields).toEqual({
  366. lineImage: null,
  367. lineImages: [],
  368. notes: 'updated notes',
  369. });
  370. const updatedNotesLineId = ao1.lines[1].id;
  371. const { addItemToOrder: add2 } = await shopClient.query<AddItemToOrder.Mutation>(
  372. ADD_ITEM_TO_ORDER_WITH_CUSTOM_FIELDS,
  373. {
  374. productVariantId: 'T_3',
  375. quantity: 1,
  376. },
  377. );
  378. orderResultGuard.assertSuccess(add2);
  379. expect(add2.lines.length).toBe(3);
  380. expect(add2.lines[1].quantity).toBe(1);
  381. expect(add2.lines[2].quantity).toBe(1);
  382. const { activeOrder } = await shopClient.query(GET_ORDER_WITH_ORDER_LINE_CUSTOM_FIELDS);
  383. expect(activeOrder.lines.find((l: any) => l.id === updatedNotesLineId)?.customFields).toEqual(
  384. {
  385. lineImage: null,
  386. lineImages: [],
  387. notes: 'updated notes',
  388. },
  389. );
  390. // clean up
  391. await shopClient.query<
  392. CodegenShop.RemoveItemFromOrderMutation,
  393. CodegenShop.RemoveItemFromOrderMutationVariables
  394. >(REMOVE_ITEM_FROM_ORDER, {
  395. orderLineId: add2.lines[1].id,
  396. });
  397. const { removeOrderLine } = await shopClient.query<
  398. CodegenShop.RemoveItemFromOrderMutation,
  399. CodegenShop.RemoveItemFromOrderMutationVariables
  400. >(REMOVE_ITEM_FROM_ORDER, {
  401. orderLineId: add2.lines[2].id,
  402. });
  403. orderResultGuard.assertSuccess(removeOrderLine);
  404. expect(removeOrderLine.lines.length).toBe(1);
  405. });
  406. it('addItemToOrder with relation customField', async () => {
  407. const { addItemToOrder } = await shopClient.query<CodegenShop.AddItemToOrderMutation>(
  408. ADD_ITEM_TO_ORDER_WITH_CUSTOM_FIELDS,
  409. {
  410. productVariantId: 'T_3',
  411. quantity: 1,
  412. customFields: {
  413. lineImageId: 'T_1',
  414. },
  415. },
  416. );
  417. orderResultGuard.assertSuccess(addItemToOrder);
  418. expect(addItemToOrder.lines.length).toBe(2);
  419. expect(addItemToOrder.lines[1].quantity).toBe(1);
  420. const { activeOrder } = await shopClient.query(GET_ORDER_WITH_ORDER_LINE_CUSTOM_FIELDS);
  421. expect(activeOrder.lines[1].customFields.lineImage).toEqual({ id: 'T_1' });
  422. });
  423. it('addItemToOrder with equal relation customField adds to quantity', async () => {
  424. const { addItemToOrder } = await shopClient.query<CodegenShop.AddItemToOrderMutation>(
  425. ADD_ITEM_TO_ORDER_WITH_CUSTOM_FIELDS,
  426. {
  427. productVariantId: 'T_3',
  428. quantity: 1,
  429. customFields: {
  430. lineImageId: 'T_1',
  431. },
  432. },
  433. );
  434. orderResultGuard.assertSuccess(addItemToOrder);
  435. expect(addItemToOrder.lines.length).toBe(2);
  436. expect(addItemToOrder.lines[1].quantity).toBe(2);
  437. const { activeOrder } = await shopClient.query(GET_ORDER_WITH_ORDER_LINE_CUSTOM_FIELDS);
  438. expect(activeOrder.lines[1].customFields.lineImage).toEqual({ id: 'T_1' });
  439. });
  440. it('addItemToOrder with different relation customField adds new line', async () => {
  441. const { addItemToOrder } = await shopClient.query<CodegenShop.AddItemToOrderMutation>(
  442. ADD_ITEM_TO_ORDER_WITH_CUSTOM_FIELDS,
  443. {
  444. productVariantId: 'T_3',
  445. quantity: 1,
  446. customFields: {
  447. lineImageId: 'T_2',
  448. },
  449. },
  450. );
  451. orderResultGuard.assertSuccess(addItemToOrder);
  452. expect(addItemToOrder.lines.length).toBe(3);
  453. expect(addItemToOrder.lines[2].quantity).toBe(1);
  454. const { activeOrder } = await shopClient.query(GET_ORDER_WITH_ORDER_LINE_CUSTOM_FIELDS);
  455. expect(activeOrder.lines[2].customFields.lineImage).toEqual({ id: 'T_2' });
  456. });
  457. it('adjustOrderLine updates relation reference', async () => {
  458. const { activeOrder } = await shopClient.query(GET_ORDER_WITH_ORDER_LINE_CUSTOM_FIELDS);
  459. const { adjustOrderLine } = await shopClient.query(ADJUST_ORDER_LINE_WITH_CUSTOM_FIELDS, {
  460. orderLineId: activeOrder.lines[2].id,
  461. quantity: 1,
  462. customFields: {
  463. lineImageId: 'T_1',
  464. },
  465. });
  466. expect(adjustOrderLine.lines[2].customFields.lineImage).toEqual({ id: 'T_1' });
  467. await shopClient.query<
  468. CodegenShop.RemoveItemFromOrderMutation,
  469. CodegenShop.RemoveItemFromOrderMutationVariables
  470. >(REMOVE_ITEM_FROM_ORDER, {
  471. orderLineId: activeOrder.lines[2].id,
  472. });
  473. const { removeOrderLine } = await shopClient.query<
  474. CodegenShop.RemoveItemFromOrderMutation,
  475. CodegenShop.RemoveItemFromOrderMutationVariables
  476. >(REMOVE_ITEM_FROM_ORDER, {
  477. orderLineId: activeOrder.lines[1].id,
  478. });
  479. orderResultGuard.assertSuccess(removeOrderLine);
  480. expect(removeOrderLine.lines.length).toBe(1);
  481. });
  482. it('addItemToOrder with list relation customField', async () => {
  483. const { addItemToOrder } = await shopClient.query<CodegenShop.AddItemToOrderMutation>(
  484. ADD_ITEM_TO_ORDER_WITH_CUSTOM_FIELDS,
  485. {
  486. productVariantId: 'T_3',
  487. quantity: 1,
  488. customFields: {
  489. lineImagesIds: ['T_1', 'T_2'],
  490. },
  491. },
  492. );
  493. orderResultGuard.assertSuccess(addItemToOrder);
  494. expect(addItemToOrder.lines.length).toBe(2);
  495. expect(addItemToOrder.lines[1].quantity).toBe(1);
  496. const { activeOrder } = await shopClient.query(GET_ORDER_WITH_ORDER_LINE_CUSTOM_FIELDS);
  497. expect(activeOrder.lines[1].customFields.lineImages.length).toBe(2);
  498. expect(activeOrder.lines[1].customFields.lineImages).toContainEqual({ id: 'T_1' });
  499. expect(activeOrder.lines[1].customFields.lineImages).toContainEqual({ id: 'T_2' });
  500. });
  501. it('addItemToOrder with equal list relation customField adds to quantity', async () => {
  502. const { addItemToOrder } = await shopClient.query<CodegenShop.AddItemToOrderMutation>(
  503. ADD_ITEM_TO_ORDER_WITH_CUSTOM_FIELDS,
  504. {
  505. productVariantId: 'T_3',
  506. quantity: 1,
  507. customFields: {
  508. lineImagesIds: ['T_1', 'T_2'],
  509. },
  510. },
  511. );
  512. orderResultGuard.assertSuccess(addItemToOrder);
  513. expect(addItemToOrder.lines.length).toBe(2);
  514. expect(addItemToOrder.lines[1].quantity).toBe(2);
  515. const { activeOrder } = await shopClient.query(GET_ORDER_WITH_ORDER_LINE_CUSTOM_FIELDS);
  516. expect(activeOrder.lines[1].customFields.lineImages.length).toBe(2);
  517. expect(activeOrder.lines[1].customFields.lineImages).toContainEqual({ id: 'T_1' });
  518. expect(activeOrder.lines[1].customFields.lineImages).toContainEqual({ id: 'T_2' });
  519. });
  520. it('addItemToOrder with different list relation customField adds new line', async () => {
  521. const { addItemToOrder } = await shopClient.query<CodegenShop.AddItemToOrderMutation>(
  522. ADD_ITEM_TO_ORDER_WITH_CUSTOM_FIELDS,
  523. {
  524. productVariantId: 'T_3',
  525. quantity: 1,
  526. customFields: {
  527. lineImagesIds: ['T_1'],
  528. },
  529. },
  530. );
  531. orderResultGuard.assertSuccess(addItemToOrder);
  532. expect(addItemToOrder.lines.length).toBe(3);
  533. expect(addItemToOrder.lines[2].quantity).toBe(1);
  534. const { activeOrder } = await shopClient.query(GET_ORDER_WITH_ORDER_LINE_CUSTOM_FIELDS);
  535. expect(activeOrder.lines[2].customFields.lineImages).toEqual([{ id: 'T_1' }]);
  536. await shopClient.query<
  537. CodegenShop.RemoveItemFromOrderMutation,
  538. CodegenShop.RemoveItemFromOrderMutationVariables
  539. >(REMOVE_ITEM_FROM_ORDER, {
  540. orderLineId: activeOrder.lines[2].id,
  541. });
  542. const { removeOrderLine } = await shopClient.query<
  543. CodegenShop.RemoveItemFromOrderMutation,
  544. CodegenShop.RemoveItemFromOrderMutationVariables
  545. >(REMOVE_ITEM_FROM_ORDER, {
  546. orderLineId: activeOrder.lines[1].id,
  547. });
  548. orderResultGuard.assertSuccess(removeOrderLine);
  549. expect(removeOrderLine.lines.length).toBe(1);
  550. });
  551. });
  552. it('addItemToOrder errors when going beyond orderItemsLimit', async () => {
  553. const { addItemToOrder } = await shopClient.query<
  554. CodegenShop.AddItemToOrderMutation,
  555. CodegenShop.AddItemToOrderMutationVariables
  556. >(ADD_ITEM_TO_ORDER, {
  557. productVariantId: 'T_1',
  558. quantity: 200,
  559. });
  560. orderResultGuard.assertErrorResult(addItemToOrder);
  561. expect(addItemToOrder.message).toBe(
  562. 'Cannot add items. An order may consist of a maximum of 199 items',
  563. );
  564. expect(addItemToOrder.errorCode).toBe(ErrorCode.ORDER_LIMIT_ERROR);
  565. });
  566. it('adjustOrderLine adjusts the quantity', async () => {
  567. const { adjustOrderLine } = await shopClient.query<
  568. CodegenShop.AdjustItemQuantityMutation,
  569. CodegenShop.AdjustItemQuantityMutationVariables
  570. >(ADJUST_ITEM_QUANTITY, {
  571. orderLineId: firstOrderLineId,
  572. quantity: 50,
  573. });
  574. orderResultGuard.assertSuccess(adjustOrderLine);
  575. expect(adjustOrderLine.lines.length).toBe(1);
  576. expect(adjustOrderLine.lines[0].quantity).toBe(50);
  577. });
  578. it('adjustOrderLine with quantity 0 removes the line', async () => {
  579. const { addItemToOrder } = await shopClient.query<
  580. CodegenShop.AddItemToOrderMutation,
  581. CodegenShop.AddItemToOrderMutationVariables
  582. >(ADD_ITEM_TO_ORDER, {
  583. productVariantId: 'T_3',
  584. quantity: 3,
  585. });
  586. orderResultGuard.assertSuccess(addItemToOrder);
  587. expect(addItemToOrder.lines.length).toBe(2);
  588. expect(addItemToOrder.lines.map(i => i.productVariant.id)).toEqual(['T_1', 'T_3']);
  589. const { adjustOrderLine } = await shopClient.query<
  590. CodegenShop.AdjustItemQuantityMutation,
  591. CodegenShop.AdjustItemQuantityMutationVariables
  592. >(ADJUST_ITEM_QUANTITY, {
  593. orderLineId: addItemToOrder?.lines[1].id,
  594. quantity: 0,
  595. });
  596. orderResultGuard.assertSuccess(adjustOrderLine);
  597. expect(adjustOrderLine.lines.length).toBe(1);
  598. expect(adjustOrderLine.lines.map(i => i.productVariant.id)).toEqual(['T_1']);
  599. });
  600. it('adjustOrderLine with quantity > stockOnHand only allows user to have stock on hand', async () => {
  601. const { addItemToOrder } = await shopClient.query<
  602. CodegenShop.AddItemToOrderMutation,
  603. CodegenShop.AddItemToOrderMutationVariables
  604. >(ADD_ITEM_TO_ORDER, {
  605. productVariantId: 'T_3',
  606. quantity: 111,
  607. });
  608. orderResultGuard.assertErrorResult(addItemToOrder);
  609. // Insufficient stock error should return because there are only 100 available
  610. expect(addItemToOrder.errorCode).toBe('INSUFFICIENT_STOCK_ERROR');
  611. // But it should still add the item to the order
  612. expect(addItemToOrder.order.lines[1].quantity).toBe(100);
  613. const { adjustOrderLine } = await shopClient.query<
  614. CodegenShop.AdjustItemQuantityMutation,
  615. CodegenShop.AdjustItemQuantityMutationVariables
  616. >(ADJUST_ITEM_QUANTITY, {
  617. orderLineId: addItemToOrder.order.lines[1].id,
  618. quantity: 101,
  619. });
  620. orderResultGuard.assertErrorResult(adjustOrderLine);
  621. expect(adjustOrderLine.errorCode).toBe('INSUFFICIENT_STOCK_ERROR');
  622. expect(adjustOrderLine.message).toBe(
  623. 'Only 100 items were added to the order due to insufficient stock',
  624. );
  625. const order = await shopClient.query<CodegenShop.GetActiveOrderQuery>(GET_ACTIVE_ORDER);
  626. expect(order.activeOrder?.lines[1].quantity).toBe(100);
  627. // clean up
  628. const { adjustOrderLine: adjustLine2 } = await shopClient.query<
  629. CodegenShop.AdjustItemQuantityMutation,
  630. CodegenShop.AdjustItemQuantityMutationVariables
  631. >(ADJUST_ITEM_QUANTITY, {
  632. orderLineId: addItemToOrder.order.lines[1].id,
  633. quantity: 0,
  634. });
  635. orderResultGuard.assertSuccess(adjustLine2);
  636. expect(adjustLine2.lines.length).toBe(1);
  637. expect(adjustLine2.lines.map(i => i.productVariant.id)).toEqual(['T_1']);
  638. });
  639. // https://github.com/vendure-ecommerce/vendure/issues/2702
  640. it('stockOnHand check works with multiple order lines with different custom fields', async () => {
  641. const variantId = 'T_27';
  642. const { updateProductVariants } = await adminClient.query<
  643. Codegen.UpdateProductVariantsMutation,
  644. Codegen.UpdateProductVariantsMutationVariables
  645. >(UPDATE_PRODUCT_VARIANTS, {
  646. input: [
  647. {
  648. id: variantId,
  649. stockOnHand: 10,
  650. outOfStockThreshold: 0,
  651. useGlobalOutOfStockThreshold: false,
  652. trackInventory: GlobalFlag.TRUE,
  653. },
  654. ],
  655. });
  656. expect(updateProductVariants[0]?.stockOnHand).toBe(10);
  657. expect(updateProductVariants[0]?.id).toBe('T_27');
  658. expect(updateProductVariants[0]?.trackInventory).toBe(GlobalFlag.TRUE);
  659. const { addItemToOrder: add1 } = await shopClient.query<CodegenShop.AddItemToOrderMutation, any>(
  660. ADD_ITEM_TO_ORDER_WITH_CUSTOM_FIELDS,
  661. {
  662. productVariantId: variantId,
  663. quantity: 9,
  664. customFields: {
  665. notes: 'abc',
  666. },
  667. },
  668. );
  669. orderResultGuard.assertSuccess(add1);
  670. expect(add1.lines.length).toBe(2);
  671. expect(add1.lines[1].quantity).toBe(9);
  672. expect(add1.lines[1].productVariant.id).toBe(variantId);
  673. const { addItemToOrder: add2 } = await shopClient.query<CodegenShop.AddItemToOrderMutation, any>(
  674. ADD_ITEM_TO_ORDER_WITH_CUSTOM_FIELDS,
  675. {
  676. productVariantId: variantId,
  677. quantity: 2,
  678. customFields: {
  679. notes: 'def',
  680. },
  681. },
  682. );
  683. orderResultGuard.assertErrorResult(add2);
  684. expect(add2.errorCode).toBe('INSUFFICIENT_STOCK_ERROR');
  685. expect(add2.message).toBe('Only 1 item was added to the order due to insufficient stock');
  686. const { activeOrder } = await shopClient.query<CodegenShop.GetActiveOrderQuery>(GET_ACTIVE_ORDER);
  687. expect(activeOrder?.lines.length).toBe(3);
  688. expect(activeOrder?.lines[1].quantity).toBe(9);
  689. expect(activeOrder?.lines[2].quantity).toBe(1);
  690. // clean up
  691. await shopClient.query<
  692. CodegenShop.RemoveItemFromOrderMutation,
  693. CodegenShop.RemoveItemFromOrderMutationVariables
  694. >(REMOVE_ITEM_FROM_ORDER, {
  695. orderLineId: activeOrder!.lines[1].id,
  696. });
  697. await shopClient.query<
  698. CodegenShop.RemoveItemFromOrderMutation,
  699. CodegenShop.RemoveItemFromOrderMutationVariables
  700. >(REMOVE_ITEM_FROM_ORDER, {
  701. orderLineId: activeOrder!.lines[2].id,
  702. });
  703. });
  704. it('adjustOrderLine handles stockOnHand correctly with multiple order lines with different custom fields when out of stock', async () => {
  705. const variantId = 'T_27';
  706. const { updateProductVariants } = await adminClient.query<
  707. Codegen.UpdateProductVariantsMutation,
  708. Codegen.UpdateProductVariantsMutationVariables
  709. >(UPDATE_PRODUCT_VARIANTS, {
  710. input: [
  711. {
  712. id: variantId,
  713. stockOnHand: 10,
  714. outOfStockThreshold: 0,
  715. useGlobalOutOfStockThreshold: false,
  716. trackInventory: GlobalFlag.TRUE,
  717. },
  718. ],
  719. });
  720. expect(updateProductVariants[0]?.stockOnHand).toBe(10);
  721. expect(updateProductVariants[0]?.id).toBe('T_27');
  722. expect(updateProductVariants[0]?.trackInventory).toBe(GlobalFlag.TRUE);
  723. const { addItemToOrder: add1 } = await shopClient.query<CodegenShop.AddItemToOrderMutation, any>(
  724. ADD_ITEM_TO_ORDER_WITH_CUSTOM_FIELDS,
  725. {
  726. productVariantId: variantId,
  727. quantity: 5,
  728. customFields: {
  729. notes: 'abc',
  730. },
  731. },
  732. );
  733. orderResultGuard.assertSuccess(add1);
  734. expect(add1.lines.length).toBe(2);
  735. expect(add1.lines[1].quantity).toBe(5);
  736. expect(add1.lines[1].productVariant.id).toBe(variantId);
  737. const { addItemToOrder: add2 } = await shopClient.query<CodegenShop.AddItemToOrderMutation, any>(
  738. ADD_ITEM_TO_ORDER_WITH_CUSTOM_FIELDS,
  739. {
  740. productVariantId: variantId,
  741. quantity: 5,
  742. customFields: {
  743. notes: 'def',
  744. },
  745. },
  746. );
  747. orderResultGuard.assertSuccess(add2);
  748. expect(add2.lines.length).toBe(3);
  749. expect(add2.lines[2].quantity).toBe(5);
  750. expect(add2.lines[2].productVariant.id).toBe(variantId);
  751. const { adjustOrderLine } = await shopClient.query<
  752. CodegenShop.AdjustItemQuantityMutation,
  753. CodegenShop.AdjustItemQuantityMutationVariables
  754. >(ADJUST_ITEM_QUANTITY, {
  755. orderLineId: add2.lines[1].id,
  756. quantity: 10,
  757. });
  758. orderResultGuard.assertErrorResult(adjustOrderLine);
  759. expect(adjustOrderLine.message).toBe(
  760. 'Only 5 items were added to the order due to insufficient stock',
  761. );
  762. expect(adjustOrderLine.errorCode).toBe(ErrorCode.INSUFFICIENT_STOCK_ERROR);
  763. const { activeOrder } = await shopClient.query<CodegenShop.GetActiveOrderQuery>(GET_ACTIVE_ORDER);
  764. expect(activeOrder?.lines.length).toBe(3);
  765. expect(activeOrder?.lines[1].quantity).toBe(5);
  766. expect(activeOrder?.lines[2].quantity).toBe(5);
  767. // clean up
  768. await shopClient.query<
  769. CodegenShop.RemoveItemFromOrderMutation,
  770. CodegenShop.RemoveItemFromOrderMutationVariables
  771. >(REMOVE_ITEM_FROM_ORDER, {
  772. orderLineId: activeOrder!.lines[1].id,
  773. });
  774. await shopClient.query<
  775. CodegenShop.RemoveItemFromOrderMutation,
  776. CodegenShop.RemoveItemFromOrderMutationVariables
  777. >(REMOVE_ITEM_FROM_ORDER, {
  778. orderLineId: activeOrder!.lines[2].id,
  779. });
  780. });
  781. it('adjustOrderLine handles stockOnHand correctly with multiple order lines with different custom fields', async () => {
  782. const variantId = 'T_27';
  783. const { updateProductVariants } = await adminClient.query<
  784. Codegen.UpdateProductVariantsMutation,
  785. Codegen.UpdateProductVariantsMutationVariables
  786. >(UPDATE_PRODUCT_VARIANTS, {
  787. input: [
  788. {
  789. id: variantId,
  790. stockOnHand: 10,
  791. outOfStockThreshold: 0,
  792. useGlobalOutOfStockThreshold: false,
  793. trackInventory: GlobalFlag.TRUE,
  794. },
  795. ],
  796. });
  797. expect(updateProductVariants[0]?.stockOnHand).toBe(10);
  798. expect(updateProductVariants[0]?.id).toBe('T_27');
  799. expect(updateProductVariants[0]?.trackInventory).toBe(GlobalFlag.TRUE);
  800. const { addItemToOrder: add1 } = await shopClient.query<CodegenShop.AddItemToOrderMutation, any>(
  801. ADD_ITEM_TO_ORDER_WITH_CUSTOM_FIELDS,
  802. {
  803. productVariantId: variantId,
  804. quantity: 5,
  805. customFields: {
  806. notes: 'abc',
  807. },
  808. },
  809. );
  810. orderResultGuard.assertSuccess(add1);
  811. expect(add1.lines.length).toBe(2);
  812. expect(add1.lines[1].quantity).toBe(5);
  813. expect(add1.lines[1].productVariant.id).toBe(variantId);
  814. const { addItemToOrder: add2 } = await shopClient.query<CodegenShop.AddItemToOrderMutation, any>(
  815. ADD_ITEM_TO_ORDER_WITH_CUSTOM_FIELDS,
  816. {
  817. productVariantId: variantId,
  818. quantity: 5,
  819. customFields: {
  820. notes: 'def',
  821. },
  822. },
  823. );
  824. orderResultGuard.assertSuccess(add2);
  825. expect(add2.lines.length).toBe(3);
  826. expect(add2.lines[2].quantity).toBe(5);
  827. expect(add2.lines[2].productVariant.id).toBe(variantId);
  828. const { adjustOrderLine } = await shopClient.query<
  829. CodegenShop.AdjustItemQuantityMutation,
  830. CodegenShop.AdjustItemQuantityMutationVariables
  831. >(ADJUST_ITEM_QUANTITY, {
  832. orderLineId: add2.lines[1].id,
  833. quantity: 3,
  834. });
  835. orderResultGuard.assertSuccess(adjustOrderLine);
  836. expect(adjustOrderLine?.lines.length).toBe(3);
  837. expect(adjustOrderLine?.lines[1].quantity).toBe(3);
  838. expect(adjustOrderLine?.lines[2].quantity).toBe(5);
  839. // clean up
  840. await shopClient.query<
  841. CodegenShop.RemoveItemFromOrderMutation,
  842. CodegenShop.RemoveItemFromOrderMutationVariables
  843. >(REMOVE_ITEM_FROM_ORDER, {
  844. orderLineId: adjustOrderLine.lines[1].id,
  845. });
  846. await shopClient.query<
  847. CodegenShop.RemoveItemFromOrderMutation,
  848. CodegenShop.RemoveItemFromOrderMutationVariables
  849. >(REMOVE_ITEM_FROM_ORDER, {
  850. orderLineId: adjustOrderLine.lines[2].id,
  851. });
  852. });
  853. it('adjustOrderLine errors when going beyond orderItemsLimit', async () => {
  854. const { adjustOrderLine } = await shopClient.query<
  855. CodegenShop.AdjustItemQuantityMutation,
  856. CodegenShop.AdjustItemQuantityMutationVariables
  857. >(ADJUST_ITEM_QUANTITY, {
  858. orderLineId: firstOrderLineId,
  859. quantity: 200,
  860. });
  861. orderResultGuard.assertErrorResult(adjustOrderLine);
  862. expect(adjustOrderLine.message).toBe(
  863. 'Cannot add items. An order may consist of a maximum of 199 items',
  864. );
  865. expect(adjustOrderLine.errorCode).toBe(ErrorCode.ORDER_LIMIT_ERROR);
  866. });
  867. it('adjustOrderLine errors with a negative quantity', async () => {
  868. const { adjustOrderLine } = await shopClient.query<
  869. CodegenShop.AdjustItemQuantityMutation,
  870. CodegenShop.AdjustItemQuantityMutationVariables
  871. >(ADJUST_ITEM_QUANTITY, {
  872. orderLineId: firstOrderLineId,
  873. quantity: -3,
  874. });
  875. orderResultGuard.assertErrorResult(adjustOrderLine);
  876. expect(adjustOrderLine.message).toBe('The quantity for an OrderItem cannot be negative');
  877. expect(adjustOrderLine.errorCode).toBe(ErrorCode.NEGATIVE_QUANTITY_ERROR);
  878. });
  879. it(
  880. 'adjustOrderLine errors with an invalid orderLineId',
  881. assertThrowsWithMessage(
  882. () =>
  883. shopClient.query<
  884. CodegenShop.AdjustItemQuantityMutation,
  885. CodegenShop.AdjustItemQuantityMutationVariables
  886. >(ADJUST_ITEM_QUANTITY, {
  887. orderLineId: 'T_999',
  888. quantity: 5,
  889. }),
  890. 'This order does not contain an OrderLine with the id 999',
  891. ),
  892. );
  893. it('removeItemFromOrder removes the correct item', async () => {
  894. const { addItemToOrder } = await shopClient.query<
  895. CodegenShop.AddItemToOrderMutation,
  896. CodegenShop.AddItemToOrderMutationVariables
  897. >(ADD_ITEM_TO_ORDER, {
  898. productVariantId: 'T_3',
  899. quantity: 3,
  900. });
  901. orderResultGuard.assertSuccess(addItemToOrder);
  902. expect(addItemToOrder.lines.length).toBe(2);
  903. expect(addItemToOrder.lines.map(i => i.productVariant.id)).toEqual(['T_1', 'T_3']);
  904. const { removeOrderLine } = await shopClient.query<
  905. CodegenShop.RemoveItemFromOrderMutation,
  906. CodegenShop.RemoveItemFromOrderMutationVariables
  907. >(REMOVE_ITEM_FROM_ORDER, {
  908. orderLineId: firstOrderLineId,
  909. });
  910. orderResultGuard.assertSuccess(removeOrderLine);
  911. expect(removeOrderLine.lines.length).toBe(1);
  912. expect(removeOrderLine.lines.map(i => i.productVariant.id)).toEqual(['T_3']);
  913. });
  914. it(
  915. 'removeItemFromOrder errors with an invalid orderItemId',
  916. assertThrowsWithMessage(
  917. () =>
  918. shopClient.query<
  919. CodegenShop.RemoveItemFromOrderMutation,
  920. CodegenShop.RemoveItemFromOrderMutationVariables
  921. >(REMOVE_ITEM_FROM_ORDER, {
  922. orderLineId: 'T_999',
  923. }),
  924. 'This order does not contain an OrderLine with the id 999',
  925. ),
  926. );
  927. it('nextOrderStates returns next valid states', async () => {
  928. const result = await shopClient.query<CodegenShop.GetNextOrderStatesQuery>(GET_NEXT_STATES);
  929. expect(result.nextOrderStates).toEqual(['ArrangingPayment', 'Cancelled']);
  930. });
  931. it('transitionOrderToState returns error result for invalid state', async () => {
  932. const { transitionOrderToState } = await shopClient.query<
  933. CodegenShop.TransitionToStateMutation,
  934. CodegenShop.TransitionToStateMutationVariables
  935. >(TRANSITION_TO_STATE, { state: 'Completed' });
  936. orderResultGuard.assertErrorResult(transitionOrderToState);
  937. expect(transitionOrderToState!.message).toBe(
  938. 'Cannot transition Order from "AddingItems" to "Completed"',
  939. );
  940. expect(transitionOrderToState!.errorCode).toBe(ErrorCode.ORDER_STATE_TRANSITION_ERROR);
  941. });
  942. it('attempting to transition to ArrangingPayment returns error result when Order has no Customer', async () => {
  943. const { transitionOrderToState } = await shopClient.query<
  944. CodegenShop.TransitionToStateMutation,
  945. CodegenShop.TransitionToStateMutationVariables
  946. >(TRANSITION_TO_STATE, { state: 'ArrangingPayment' });
  947. orderResultGuard.assertErrorResult(transitionOrderToState);
  948. expect(transitionOrderToState!.transitionError).toBe(
  949. 'Cannot transition Order to the "ArrangingPayment" state without Customer details',
  950. );
  951. expect(transitionOrderToState!.errorCode).toBe(ErrorCode.ORDER_STATE_TRANSITION_ERROR);
  952. });
  953. it('setCustomerForOrder returns error result on email address conflict', async () => {
  954. const { customers } = await adminClient.query<Codegen.GetCustomerListQuery>(GET_CUSTOMER_LIST);
  955. const { setCustomerForOrder } = await shopClient.query<
  956. CodegenShop.SetCustomerForOrderMutation,
  957. CodegenShop.SetCustomerForOrderMutationVariables
  958. >(SET_CUSTOMER, {
  959. input: {
  960. emailAddress: customers.items[0].emailAddress,
  961. firstName: 'Test',
  962. lastName: 'Person',
  963. },
  964. });
  965. orderResultGuard.assertErrorResult(setCustomerForOrder);
  966. expect(setCustomerForOrder.message).toBe('The email address is not available.');
  967. expect(setCustomerForOrder.errorCode).toBe(ErrorCode.EMAIL_ADDRESS_CONFLICT_ERROR);
  968. });
  969. it('setCustomerForOrder creates a new Customer and associates it with the Order', async () => {
  970. const { setCustomerForOrder } = await shopClient.query<
  971. CodegenShop.SetCustomerForOrderMutation,
  972. CodegenShop.SetCustomerForOrderMutationVariables
  973. >(SET_CUSTOMER, {
  974. input: {
  975. emailAddress: 'test@test.com',
  976. firstName: 'Test',
  977. lastName: 'Person',
  978. },
  979. });
  980. orderResultGuard.assertSuccess(setCustomerForOrder);
  981. const customer = setCustomerForOrder.customer!;
  982. expect(customer.firstName).toBe('Test');
  983. expect(customer.lastName).toBe('Person');
  984. expect(customer.emailAddress).toBe('test@test.com');
  985. createdCustomerId = customer.id;
  986. });
  987. it('setCustomerForOrder updates the existing customer if Customer already set', async () => {
  988. const { setCustomerForOrder } = await shopClient.query<
  989. CodegenShop.SetCustomerForOrderMutation,
  990. CodegenShop.SetCustomerForOrderMutationVariables
  991. >(SET_CUSTOMER, {
  992. input: {
  993. emailAddress: 'test@test.com',
  994. firstName: 'Changed',
  995. lastName: 'Person',
  996. },
  997. });
  998. orderResultGuard.assertSuccess(setCustomerForOrder);
  999. const customer = setCustomerForOrder.customer!;
  1000. expect(customer.firstName).toBe('Changed');
  1001. expect(customer.lastName).toBe('Person');
  1002. expect(customer.emailAddress).toBe('test@test.com');
  1003. expect(customer.id).toBe(createdCustomerId);
  1004. });
  1005. it('setOrderShippingAddress sets shipping address', async () => {
  1006. const address: CreateAddressInput = {
  1007. fullName: 'name',
  1008. company: 'company',
  1009. streetLine1: '12 Shipping Street',
  1010. streetLine2: null,
  1011. city: 'foo',
  1012. province: 'bar',
  1013. postalCode: '123456',
  1014. countryCode: 'US',
  1015. phoneNumber: '4444444',
  1016. };
  1017. const { setOrderShippingAddress } = await shopClient.query<
  1018. CodegenShop.SetShippingAddressMutation,
  1019. CodegenShop.SetShippingAddressMutationVariables
  1020. >(SET_SHIPPING_ADDRESS, {
  1021. input: address,
  1022. });
  1023. expect(setOrderShippingAddress.shippingAddress).toEqual({
  1024. fullName: 'name',
  1025. company: 'company',
  1026. streetLine1: '12 Shipping Street',
  1027. streetLine2: null,
  1028. city: 'foo',
  1029. province: 'bar',
  1030. postalCode: '123456',
  1031. country: 'United States of America',
  1032. phoneNumber: '4444444',
  1033. });
  1034. });
  1035. it('setOrderBillingAddress sets billing address', async () => {
  1036. const address: CreateAddressInput = {
  1037. fullName: 'name',
  1038. company: 'company',
  1039. streetLine1: '22 Billing Avenue',
  1040. streetLine2: null,
  1041. city: 'foo',
  1042. province: 'bar',
  1043. postalCode: '123456',
  1044. countryCode: 'US',
  1045. phoneNumber: '4444444',
  1046. };
  1047. const { setOrderBillingAddress } = await shopClient.query<
  1048. Codegen.SetBillingAddressMutation,
  1049. Codegen.SetBillingAddressMutationVariables
  1050. >(SET_BILLING_ADDRESS, {
  1051. input: address,
  1052. });
  1053. expect(setOrderBillingAddress.billingAddress).toEqual({
  1054. fullName: 'name',
  1055. company: 'company',
  1056. streetLine1: '22 Billing Avenue',
  1057. streetLine2: null,
  1058. city: 'foo',
  1059. province: 'bar',
  1060. postalCode: '123456',
  1061. country: 'United States of America',
  1062. phoneNumber: '4444444',
  1063. });
  1064. });
  1065. it('customer default Addresses are not updated before payment', async () => {
  1066. const { activeOrder } = await shopClient.query<CodegenShop.GetActiveOrderQuery>(GET_ACTIVE_ORDER);
  1067. const { customer } = await adminClient.query<
  1068. Codegen.GetCustomerQuery,
  1069. Codegen.GetCustomerQueryVariables
  1070. >(GET_CUSTOMER, { id: activeOrder!.customer!.id });
  1071. expect(customer!.addresses).toEqual([]);
  1072. });
  1073. it('attempting to transition to ArrangingPayment returns error result when Order has no ShippingMethod', async () => {
  1074. const { transitionOrderToState } = await shopClient.query<
  1075. CodegenShop.TransitionToStateMutation,
  1076. CodegenShop.TransitionToStateMutationVariables
  1077. >(TRANSITION_TO_STATE, { state: 'ArrangingPayment' });
  1078. orderResultGuard.assertErrorResult(transitionOrderToState);
  1079. expect(transitionOrderToState!.transitionError).toBe(
  1080. 'Cannot transition Order to the "ArrangingPayment" state without a ShippingMethod',
  1081. );
  1082. expect(transitionOrderToState!.errorCode).toBe(ErrorCode.ORDER_STATE_TRANSITION_ERROR);
  1083. });
  1084. it('can transition to ArrangingPayment once Customer and ShippingMethod has been set', async () => {
  1085. const { eligibleShippingMethods } = await shopClient.query<CodegenShop.GetShippingMethodsQuery>(
  1086. GET_ELIGIBLE_SHIPPING_METHODS,
  1087. );
  1088. const { setOrderShippingMethod } = await shopClient.query<
  1089. CodegenShop.SetShippingMethodMutation,
  1090. CodegenShop.SetShippingMethodMutationVariables
  1091. >(SET_SHIPPING_METHOD, {
  1092. id: eligibleShippingMethods[0].id,
  1093. });
  1094. orderResultGuard.assertSuccess(setOrderShippingMethod);
  1095. const { transitionOrderToState } = await shopClient.query<
  1096. CodegenShop.TransitionToStateMutation,
  1097. CodegenShop.TransitionToStateMutationVariables
  1098. >(TRANSITION_TO_STATE, { state: 'ArrangingPayment' });
  1099. orderResultGuard.assertSuccess(transitionOrderToState);
  1100. expect(pick(transitionOrderToState, ['id', 'state'])).toEqual({
  1101. id: 'T_1',
  1102. state: 'ArrangingPayment',
  1103. });
  1104. });
  1105. it('adds a successful payment and transitions Order state', async () => {
  1106. const { addPaymentToOrder } = await shopClient.query<
  1107. CodegenShop.AddPaymentToOrderMutation,
  1108. CodegenShop.AddPaymentToOrderMutationVariables
  1109. >(ADD_PAYMENT, {
  1110. input: {
  1111. method: testSuccessfulPaymentMethod.code,
  1112. metadata: {},
  1113. },
  1114. });
  1115. orderResultGuard.assertSuccess(addPaymentToOrder);
  1116. const payment = addPaymentToOrder.payments![0];
  1117. expect(addPaymentToOrder.state).toBe('PaymentSettled');
  1118. expect(addPaymentToOrder.active).toBe(false);
  1119. expect(addPaymentToOrder.payments!.length).toBe(1);
  1120. expect(payment.method).toBe(testSuccessfulPaymentMethod.code);
  1121. expect(payment.state).toBe('Settled');
  1122. });
  1123. it('activeOrder is null after payment', async () => {
  1124. const result = await shopClient.query<CodegenShop.GetActiveOrderQuery>(GET_ACTIVE_ORDER);
  1125. expect(result.activeOrder).toBeNull();
  1126. });
  1127. it('customer default Addresses are updated after payment', async () => {
  1128. const result = await adminClient.query<
  1129. Codegen.GetCustomerQuery,
  1130. Codegen.GetCustomerQueryVariables
  1131. >(GET_CUSTOMER, {
  1132. id: createdCustomerId,
  1133. });
  1134. // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
  1135. const shippingAddress = result.customer!.addresses!.find(a => a.defaultShippingAddress)!;
  1136. expect(shippingAddress.streetLine1).toBe('12 Shipping Street');
  1137. expect(shippingAddress.postalCode).toBe('123456');
  1138. expect(shippingAddress.defaultBillingAddress).toBe(false);
  1139. expect(shippingAddress.defaultShippingAddress).toBe(true);
  1140. // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
  1141. const billingAddress = result.customer!.addresses!.find(a => a.defaultBillingAddress)!;
  1142. expect(billingAddress.streetLine1).toBe('22 Billing Avenue');
  1143. expect(billingAddress.postalCode).toBe('123456');
  1144. expect(billingAddress.defaultBillingAddress).toBe(true);
  1145. expect(billingAddress.defaultShippingAddress).toBe(false);
  1146. });
  1147. });
  1148. describe('ordering as authenticated user', () => {
  1149. let firstOrderLineId: string;
  1150. let activeOrder: CodegenShop.UpdatedOrderFragment;
  1151. let authenticatedUserEmailAddress: string;
  1152. let customers: Codegen.GetCustomerListQuery['customers']['items'];
  1153. const password = 'test';
  1154. beforeAll(async () => {
  1155. await adminClient.asSuperAdmin();
  1156. const result = await adminClient.query<
  1157. Codegen.GetCustomerListQuery,
  1158. Codegen.GetCustomerListQueryVariables
  1159. >(GET_CUSTOMER_LIST, {
  1160. options: {
  1161. take: 2,
  1162. },
  1163. });
  1164. customers = result.customers.items;
  1165. authenticatedUserEmailAddress = customers[0].emailAddress;
  1166. await shopClient.asUserWithCredentials(authenticatedUserEmailAddress, password);
  1167. });
  1168. it('activeOrder returns null before any items have been added', async () => {
  1169. const result = await shopClient.query<CodegenShop.GetActiveOrderQuery>(GET_ACTIVE_ORDER);
  1170. expect(result.activeOrder).toBeNull();
  1171. });
  1172. it('addItemToOrder creates a new Order with an item', async () => {
  1173. const { addItemToOrder } = await shopClient.query<
  1174. CodegenShop.AddItemToOrderMutation,
  1175. CodegenShop.AddItemToOrderMutationVariables
  1176. >(ADD_ITEM_TO_ORDER, {
  1177. productVariantId: 'T_1',
  1178. quantity: 1,
  1179. });
  1180. orderResultGuard.assertSuccess(addItemToOrder);
  1181. expect(addItemToOrder.lines.length).toBe(1);
  1182. expect(addItemToOrder.lines[0].quantity).toBe(1);
  1183. expect(addItemToOrder.lines[0].productVariant.id).toBe('T_1');
  1184. activeOrder = addItemToOrder!;
  1185. firstOrderLineId = addItemToOrder.lines[0].id;
  1186. });
  1187. it('activeOrder returns order after item has been added', async () => {
  1188. const result = await shopClient.query<CodegenShop.GetActiveOrderQuery>(GET_ACTIVE_ORDER);
  1189. expect(result.activeOrder!.id).toBe(activeOrder.id);
  1190. expect(result.activeOrder!.state).toBe('AddingItems');
  1191. });
  1192. it('activeOrder resolves customer user', async () => {
  1193. const result = await shopClient.query<CodegenShop.GetActiveOrderQuery>(GET_ACTIVE_ORDER);
  1194. expect(result.activeOrder!.customer!.user).toEqual({
  1195. id: 'T_2',
  1196. identifier: 'hayden.zieme12@hotmail.com',
  1197. });
  1198. });
  1199. it('addItemToOrder with an existing productVariantId adds quantity to the existing OrderLine', async () => {
  1200. const { addItemToOrder } = await shopClient.query<
  1201. CodegenShop.AddItemToOrderMutation,
  1202. CodegenShop.AddItemToOrderMutationVariables
  1203. >(ADD_ITEM_TO_ORDER, {
  1204. productVariantId: 'T_1',
  1205. quantity: 2,
  1206. });
  1207. orderResultGuard.assertSuccess(addItemToOrder);
  1208. expect(addItemToOrder.lines.length).toBe(1);
  1209. expect(addItemToOrder.lines[0].quantity).toBe(3);
  1210. });
  1211. it('adjustOrderLine adjusts the quantity', async () => {
  1212. const { adjustOrderLine } = await shopClient.query<
  1213. CodegenShop.AdjustItemQuantityMutation,
  1214. CodegenShop.AdjustItemQuantityMutationVariables
  1215. >(ADJUST_ITEM_QUANTITY, {
  1216. orderLineId: firstOrderLineId,
  1217. quantity: 50,
  1218. });
  1219. orderResultGuard.assertSuccess(adjustOrderLine);
  1220. expect(adjustOrderLine.lines.length).toBe(1);
  1221. expect(adjustOrderLine.lines[0].quantity).toBe(50);
  1222. });
  1223. it('removeItemFromOrder removes the correct item', async () => {
  1224. const { addItemToOrder } = await shopClient.query<
  1225. CodegenShop.AddItemToOrderMutation,
  1226. CodegenShop.AddItemToOrderMutationVariables
  1227. >(ADD_ITEM_TO_ORDER, {
  1228. productVariantId: 'T_3',
  1229. quantity: 3,
  1230. });
  1231. orderResultGuard.assertSuccess(addItemToOrder);
  1232. expect(addItemToOrder.lines.length).toBe(2);
  1233. expect(addItemToOrder.lines.map(i => i.productVariant.id)).toEqual(['T_1', 'T_3']);
  1234. const { removeOrderLine } = await shopClient.query<
  1235. CodegenShop.RemoveItemFromOrderMutation,
  1236. CodegenShop.RemoveItemFromOrderMutationVariables
  1237. >(REMOVE_ITEM_FROM_ORDER, {
  1238. orderLineId: firstOrderLineId,
  1239. });
  1240. orderResultGuard.assertSuccess(removeOrderLine);
  1241. expect(removeOrderLine.lines.length).toBe(1);
  1242. expect(removeOrderLine.lines.map(i => i.productVariant.id)).toEqual(['T_3']);
  1243. });
  1244. it('nextOrderStates returns next valid states', async () => {
  1245. const result = await shopClient.query<CodegenShop.GetNextOrderStatesQuery>(GET_NEXT_STATES);
  1246. expect(result.nextOrderStates).toEqual(['ArrangingPayment', 'Cancelled']);
  1247. });
  1248. it('logging out and back in again resumes the last active order', async () => {
  1249. await shopClient.asAnonymousUser();
  1250. const result1 = await shopClient.query<CodegenShop.GetActiveOrderQuery>(GET_ACTIVE_ORDER);
  1251. expect(result1.activeOrder).toBeNull();
  1252. await shopClient.asUserWithCredentials(authenticatedUserEmailAddress, password);
  1253. const result2 = await shopClient.query<CodegenShop.GetActiveOrderQuery>(GET_ACTIVE_ORDER);
  1254. expect(result2.activeOrder!.id).toBe(activeOrder.id);
  1255. });
  1256. it('cannot setCustomerForOrder when already logged in', async () => {
  1257. const { setCustomerForOrder } = await shopClient.query<
  1258. CodegenShop.SetCustomerForOrderMutation,
  1259. CodegenShop.SetCustomerForOrderMutationVariables
  1260. >(SET_CUSTOMER, {
  1261. input: {
  1262. emailAddress: 'newperson@email.com',
  1263. firstName: 'New',
  1264. lastName: 'Person',
  1265. },
  1266. });
  1267. orderResultGuard.assertErrorResult(setCustomerForOrder);
  1268. expect(setCustomerForOrder.message).toBe(
  1269. 'Cannot set a Customer for the Order when already logged in',
  1270. );
  1271. expect(setCustomerForOrder.errorCode).toBe(ErrorCode.ALREADY_LOGGED_IN_ERROR);
  1272. });
  1273. describe('shipping', () => {
  1274. let shippingMethods: CodegenShop.GetShippingMethodsQuery['eligibleShippingMethods'];
  1275. it(
  1276. 'setOrderShippingAddress throws with invalid countryCode',
  1277. assertThrowsWithMessage(() => {
  1278. const address: CreateAddressInput = {
  1279. streetLine1: '12 the street',
  1280. countryCode: 'INVALID',
  1281. };
  1282. return shopClient.query<
  1283. CodegenShop.SetShippingAddressMutation,
  1284. CodegenShop.SetShippingAddressMutationVariables
  1285. >(SET_SHIPPING_ADDRESS, {
  1286. input: address,
  1287. });
  1288. }, 'The countryCode "INVALID" was not recognized'),
  1289. );
  1290. it('setOrderShippingAddress sets shipping address', async () => {
  1291. const address: CreateAddressInput = {
  1292. fullName: 'name',
  1293. company: 'company',
  1294. streetLine1: '12 the street',
  1295. streetLine2: null,
  1296. city: 'foo',
  1297. province: 'bar',
  1298. postalCode: '123456',
  1299. countryCode: 'US',
  1300. phoneNumber: '4444444',
  1301. };
  1302. const { setOrderShippingAddress } = await shopClient.query<
  1303. CodegenShop.SetShippingAddressMutation,
  1304. CodegenShop.SetShippingAddressMutationVariables
  1305. >(SET_SHIPPING_ADDRESS, {
  1306. input: address,
  1307. });
  1308. expect(setOrderShippingAddress.shippingAddress).toEqual({
  1309. fullName: 'name',
  1310. company: 'company',
  1311. streetLine1: '12 the street',
  1312. streetLine2: null,
  1313. city: 'foo',
  1314. province: 'bar',
  1315. postalCode: '123456',
  1316. country: 'United States of America',
  1317. phoneNumber: '4444444',
  1318. });
  1319. });
  1320. it('eligibleShippingMethods lists shipping methods', async () => {
  1321. const result = await shopClient.query<CodegenShop.GetShippingMethodsQuery>(
  1322. GET_ELIGIBLE_SHIPPING_METHODS,
  1323. );
  1324. shippingMethods = result.eligibleShippingMethods;
  1325. expect(shippingMethods).toEqual([
  1326. {
  1327. id: 'T_1',
  1328. price: 500,
  1329. code: 'standard-shipping',
  1330. name: 'Standard Shipping',
  1331. description: '',
  1332. },
  1333. {
  1334. id: 'T_2',
  1335. price: 1000,
  1336. code: 'express-shipping',
  1337. name: 'Express Shipping',
  1338. description: '',
  1339. },
  1340. ]);
  1341. });
  1342. it('shipping is initially unset', async () => {
  1343. const result = await shopClient.query<CodegenShop.GetActiveOrderQuery>(GET_ACTIVE_ORDER);
  1344. expect(result.activeOrder!.shipping).toEqual(0);
  1345. expect(result.activeOrder!.shippingLines).toEqual([]);
  1346. });
  1347. it('setOrderShippingMethod sets the shipping method', async () => {
  1348. const result = await shopClient.query<
  1349. CodegenShop.SetShippingMethodMutation,
  1350. CodegenShop.SetShippingMethodMutationVariables
  1351. >(SET_SHIPPING_METHOD, {
  1352. id: shippingMethods[1].id,
  1353. });
  1354. const activeOrderResult =
  1355. await shopClient.query<CodegenShop.GetActiveOrderQuery>(GET_ACTIVE_ORDER);
  1356. const order = activeOrderResult.activeOrder!;
  1357. expect(order.shipping).toBe(shippingMethods[1].price);
  1358. expect(order.shippingLines[0].shippingMethod.id).toBe(shippingMethods[1].id);
  1359. expect(order.shippingLines[0].shippingMethod.description).toBe(
  1360. shippingMethods[1].description,
  1361. );
  1362. });
  1363. it('shipping method is preserved after adjustOrderLine', async () => {
  1364. const activeOrderResult =
  1365. await shopClient.query<CodegenShop.GetActiveOrderQuery>(GET_ACTIVE_ORDER);
  1366. activeOrder = activeOrderResult.activeOrder!;
  1367. const { adjustOrderLine } = await shopClient.query<
  1368. CodegenShop.AdjustItemQuantityMutation,
  1369. CodegenShop.AdjustItemQuantityMutationVariables
  1370. >(ADJUST_ITEM_QUANTITY, {
  1371. orderLineId: activeOrder.lines[0].id,
  1372. quantity: 10,
  1373. });
  1374. orderResultGuard.assertSuccess(adjustOrderLine);
  1375. expect(adjustOrderLine.shipping).toBe(shippingMethods[1].price);
  1376. expect(adjustOrderLine.shippingLines[0].shippingMethod.id).toBe(shippingMethods[1].id);
  1377. expect(adjustOrderLine.shippingLines[0].shippingMethod.description).toBe(
  1378. shippingMethods[1].description,
  1379. );
  1380. });
  1381. });
  1382. describe('payment', () => {
  1383. it('attempting add a Payment returns error result when in AddingItems state', async () => {
  1384. const { addPaymentToOrder } = await shopClient.query<
  1385. CodegenShop.AddPaymentToOrderMutation,
  1386. CodegenShop.AddPaymentToOrderMutationVariables
  1387. >(ADD_PAYMENT, {
  1388. input: {
  1389. method: testSuccessfulPaymentMethod.code,
  1390. metadata: {},
  1391. },
  1392. });
  1393. orderResultGuard.assertErrorResult(addPaymentToOrder);
  1394. expect(addPaymentToOrder.message).toBe(
  1395. 'A Payment may only be added when Order is in "ArrangingPayment" state',
  1396. );
  1397. expect(addPaymentToOrder.errorCode).toBe(ErrorCode.ORDER_PAYMENT_STATE_ERROR);
  1398. });
  1399. it('transitions to the ArrangingPayment state', async () => {
  1400. const { transitionOrderToState } = await shopClient.query<
  1401. CodegenShop.TransitionToStateMutation,
  1402. CodegenShop.TransitionToStateMutationVariables
  1403. >(TRANSITION_TO_STATE, { state: 'ArrangingPayment' });
  1404. orderResultGuard.assertSuccess(transitionOrderToState);
  1405. expect(pick(transitionOrderToState, ['id', 'state'])).toEqual({
  1406. id: activeOrder.id,
  1407. state: 'ArrangingPayment',
  1408. });
  1409. });
  1410. it('attempting to add an item returns error result when in ArrangingPayment state', async () => {
  1411. const { addItemToOrder } = await shopClient.query<
  1412. CodegenShop.AddItemToOrderMutation,
  1413. CodegenShop.AddItemToOrderMutationVariables
  1414. >(ADD_ITEM_TO_ORDER, {
  1415. productVariantId: 'T_4',
  1416. quantity: 1,
  1417. });
  1418. orderResultGuard.assertErrorResult(addItemToOrder);
  1419. expect(addItemToOrder.message).toBe(
  1420. 'Order contents may only be modified when in the "AddingItems" state',
  1421. );
  1422. expect(addItemToOrder.errorCode).toBe(ErrorCode.ORDER_MODIFICATION_ERROR);
  1423. });
  1424. it('attempting to modify item quantity returns error result when in ArrangingPayment state', async () => {
  1425. const { adjustOrderLine } = await shopClient.query<
  1426. CodegenShop.AdjustItemQuantityMutation,
  1427. CodegenShop.AdjustItemQuantityMutationVariables
  1428. >(ADJUST_ITEM_QUANTITY, {
  1429. orderLineId: activeOrder.lines[0].id,
  1430. quantity: 12,
  1431. });
  1432. orderResultGuard.assertErrorResult(adjustOrderLine);
  1433. expect(adjustOrderLine.message).toBe(
  1434. 'Order contents may only be modified when in the "AddingItems" state',
  1435. );
  1436. expect(adjustOrderLine.errorCode).toBe(ErrorCode.ORDER_MODIFICATION_ERROR);
  1437. });
  1438. it('attempting to remove an item returns error result when in ArrangingPayment state', async () => {
  1439. const { removeOrderLine } = await shopClient.query<
  1440. CodegenShop.RemoveItemFromOrderMutation,
  1441. CodegenShop.RemoveItemFromOrderMutationVariables
  1442. >(REMOVE_ITEM_FROM_ORDER, {
  1443. orderLineId: activeOrder.lines[0].id,
  1444. });
  1445. orderResultGuard.assertErrorResult(removeOrderLine);
  1446. expect(removeOrderLine.message).toBe(
  1447. 'Order contents may only be modified when in the "AddingItems" state',
  1448. );
  1449. expect(removeOrderLine.errorCode).toBe(ErrorCode.ORDER_MODIFICATION_ERROR);
  1450. });
  1451. it('attempting to remove all items returns error result when in ArrangingPayment state', async () => {
  1452. const { removeAllOrderLines } =
  1453. await shopClient.query<CodegenShop.RemoveAllOrderLinesMutation>(REMOVE_ALL_ORDER_LINES);
  1454. orderResultGuard.assertErrorResult(removeAllOrderLines);
  1455. expect(removeAllOrderLines.message).toBe(
  1456. 'Order contents may only be modified when in the "AddingItems" state',
  1457. );
  1458. expect(removeAllOrderLines.errorCode).toBe(ErrorCode.ORDER_MODIFICATION_ERROR);
  1459. });
  1460. it('attempting to setOrderShippingMethod returns error result when in ArrangingPayment state', async () => {
  1461. const shippingMethodsResult = await shopClient.query<CodegenShop.GetShippingMethodsQuery>(
  1462. GET_ELIGIBLE_SHIPPING_METHODS,
  1463. );
  1464. const shippingMethods = shippingMethodsResult.eligibleShippingMethods;
  1465. const { setOrderShippingMethod } = await shopClient.query<
  1466. CodegenShop.SetShippingMethodMutation,
  1467. CodegenShop.SetShippingMethodMutationVariables
  1468. >(SET_SHIPPING_METHOD, {
  1469. id: shippingMethods[0].id,
  1470. });
  1471. orderResultGuard.assertErrorResult(setOrderShippingMethod);
  1472. expect(setOrderShippingMethod.message).toBe(
  1473. 'Order contents may only be modified when in the "AddingItems" state',
  1474. );
  1475. expect(setOrderShippingMethod.errorCode).toBe(ErrorCode.ORDER_MODIFICATION_ERROR);
  1476. });
  1477. it('adds a declined payment', async () => {
  1478. const { addPaymentToOrder } = await shopClient.query<
  1479. CodegenShop.AddPaymentToOrderMutation,
  1480. CodegenShop.AddPaymentToOrderMutationVariables
  1481. >(ADD_PAYMENT, {
  1482. input: {
  1483. method: testFailingPaymentMethod.code,
  1484. metadata: {
  1485. foo: 'bar',
  1486. },
  1487. },
  1488. });
  1489. orderResultGuard.assertErrorResult(addPaymentToOrder);
  1490. expect(addPaymentToOrder.message).toBe('The payment was declined');
  1491. expect(addPaymentToOrder.errorCode).toBe(ErrorCode.PAYMENT_DECLINED_ERROR);
  1492. expect((addPaymentToOrder as any).paymentErrorMessage).toBe('Insufficient funds');
  1493. const { activeOrder: order } =
  1494. await shopClient.query<CodegenShop.GetActiveOrderWithPaymentsQuery>(
  1495. GET_ACTIVE_ORDER_WITH_PAYMENTS,
  1496. );
  1497. const payment = order!.payments![0];
  1498. expect(order!.state).toBe('ArrangingPayment');
  1499. expect(order!.payments!.length).toBe(1);
  1500. expect(payment.method).toBe(testFailingPaymentMethod.code);
  1501. expect(payment.state).toBe('Declined');
  1502. expect(payment.transactionId).toBe(null);
  1503. expect(payment.metadata).toEqual({
  1504. public: { foo: 'bar' },
  1505. });
  1506. });
  1507. it('adds an error payment and returns error result', async () => {
  1508. const { addPaymentToOrder } = await shopClient.query<
  1509. CodegenShop.AddPaymentToOrderMutation,
  1510. CodegenShop.AddPaymentToOrderMutationVariables
  1511. >(ADD_PAYMENT, {
  1512. input: {
  1513. method: testErrorPaymentMethod.code,
  1514. metadata: {
  1515. foo: 'bar',
  1516. },
  1517. },
  1518. });
  1519. orderResultGuard.assertErrorResult(addPaymentToOrder);
  1520. expect(addPaymentToOrder.message).toBe('The payment failed');
  1521. expect(addPaymentToOrder.errorCode).toBe(ErrorCode.PAYMENT_FAILED_ERROR);
  1522. expect((addPaymentToOrder as any).paymentErrorMessage).toBe('Something went horribly wrong');
  1523. const result =
  1524. await shopClient.query<CodegenShop.GetActiveOrderPaymentsQuery>(
  1525. GET_ACTIVE_ORDER_PAYMENTS,
  1526. );
  1527. const payment = result.activeOrder!.payments![1];
  1528. expect(result.activeOrder!.payments!.length).toBe(2);
  1529. expect(payment.method).toBe(testErrorPaymentMethod.code);
  1530. expect(payment.state).toBe('Error');
  1531. expect(payment.errorMessage).toBe('Something went horribly wrong');
  1532. });
  1533. it('adds a successful payment and transitions Order state', async () => {
  1534. const { addPaymentToOrder } = await shopClient.query<
  1535. CodegenShop.AddPaymentToOrderMutation,
  1536. CodegenShop.AddPaymentToOrderMutationVariables
  1537. >(ADD_PAYMENT, {
  1538. input: {
  1539. method: testSuccessfulPaymentMethod.code,
  1540. metadata: {
  1541. baz: 'quux',
  1542. },
  1543. },
  1544. });
  1545. orderResultGuard.assertSuccess(addPaymentToOrder);
  1546. const payment = addPaymentToOrder.payments!.find(p => p.transactionId === '12345')!;
  1547. expect(addPaymentToOrder.state).toBe('PaymentSettled');
  1548. expect(addPaymentToOrder.active).toBe(false);
  1549. expect(addPaymentToOrder.payments!.length).toBe(3);
  1550. expect(payment.method).toBe(testSuccessfulPaymentMethod.code);
  1551. expect(payment.state).toBe('Settled');
  1552. expect(payment.transactionId).toBe('12345');
  1553. expect(payment.metadata).toEqual({
  1554. public: { baz: 'quux' },
  1555. });
  1556. });
  1557. it('does not create new address when Customer already has address', async () => {
  1558. const { customer } = await adminClient.query<
  1559. Codegen.GetCustomerQuery,
  1560. Codegen.GetCustomerQueryVariables
  1561. >(GET_CUSTOMER, { id: customers[0].id });
  1562. expect(customer!.addresses!.length).toBe(1);
  1563. });
  1564. });
  1565. describe('orderByCode', () => {
  1566. describe('immediately after Order is placed', () => {
  1567. it('works when authenticated', async () => {
  1568. const result = await shopClient.query<
  1569. CodegenShop.GetOrderByCodeQuery,
  1570. CodegenShop.GetOrderByCodeQueryVariables
  1571. >(GET_ORDER_BY_CODE, {
  1572. code: activeOrder.code,
  1573. });
  1574. expect(result.orderByCode!.id).toBe(activeOrder.id);
  1575. });
  1576. it('works when anonymous', async () => {
  1577. await shopClient.asAnonymousUser();
  1578. const result = await shopClient.query<
  1579. CodegenShop.GetOrderByCodeQuery,
  1580. CodegenShop.GetOrderByCodeQueryVariables
  1581. >(GET_ORDER_BY_CODE, {
  1582. code: activeOrder.code,
  1583. });
  1584. expect(result.orderByCode!.id).toBe(activeOrder.id);
  1585. });
  1586. it(
  1587. "throws error for another user's Order",
  1588. assertThrowsWithMessage(async () => {
  1589. authenticatedUserEmailAddress = customers[1].emailAddress;
  1590. await shopClient.asUserWithCredentials(authenticatedUserEmailAddress, password);
  1591. return shopClient.query<
  1592. CodegenShop.GetOrderByCodeQuery,
  1593. CodegenShop.GetOrderByCodeQueryVariables
  1594. >(GET_ORDER_BY_CODE, {
  1595. code: activeOrder.code,
  1596. });
  1597. }, 'You are not currently authorized to perform this action'),
  1598. );
  1599. });
  1600. describe('3 hours after the Order has been placed', () => {
  1601. let dateNowMock: any;
  1602. beforeAll(() => {
  1603. // mock Date.now: add 3 hours
  1604. const nowIn3H = Date.now() + 3 * 3600 * 1000;
  1605. dateNowMock = vi.spyOn(global.Date, 'now').mockImplementation(() => nowIn3H);
  1606. });
  1607. it('still works when authenticated as owner', async () => {
  1608. authenticatedUserEmailAddress = customers[0].emailAddress;
  1609. await shopClient.asUserWithCredentials(authenticatedUserEmailAddress, password);
  1610. const result = await shopClient.query<
  1611. CodegenShop.GetOrderByCodeQuery,
  1612. CodegenShop.GetOrderByCodeQueryVariables
  1613. >(GET_ORDER_BY_CODE, {
  1614. code: activeOrder.code,
  1615. });
  1616. expect(result.orderByCode!.id).toBe(activeOrder.id);
  1617. });
  1618. it(
  1619. 'access denied when anonymous',
  1620. assertThrowsWithMessage(async () => {
  1621. await shopClient.asAnonymousUser();
  1622. await shopClient.query<
  1623. CodegenShop.GetOrderByCodeQuery,
  1624. CodegenShop.GetOrderByCodeQueryVariables
  1625. >(GET_ORDER_BY_CODE, {
  1626. code: activeOrder.code,
  1627. });
  1628. }, 'You are not currently authorized to perform this action'),
  1629. );
  1630. afterAll(() => {
  1631. // restore Date.now
  1632. dateNowMock.mockRestore();
  1633. });
  1634. });
  1635. });
  1636. });
  1637. describe('order merging', () => {
  1638. let customers: Codegen.GetCustomerListQuery['customers']['items'];
  1639. beforeAll(async () => {
  1640. const result = await adminClient.query<Codegen.GetCustomerListQuery>(GET_CUSTOMER_LIST);
  1641. customers = result.customers.items;
  1642. });
  1643. it('merges guest order with no existing order', async () => {
  1644. await shopClient.asAnonymousUser();
  1645. const { addItemToOrder } = await shopClient.query<
  1646. CodegenShop.AddItemToOrderMutation,
  1647. CodegenShop.AddItemToOrderMutationVariables
  1648. >(ADD_ITEM_TO_ORDER, {
  1649. productVariantId: 'T_1',
  1650. quantity: 1,
  1651. });
  1652. orderResultGuard.assertSuccess(addItemToOrder);
  1653. expect(addItemToOrder.lines.length).toBe(1);
  1654. expect(addItemToOrder.lines[0].productVariant.id).toBe('T_1');
  1655. await shopClient.query<Codegen.AttemptLoginMutation, Codegen.AttemptLoginMutationVariables>(
  1656. ATTEMPT_LOGIN,
  1657. {
  1658. username: customers[1].emailAddress,
  1659. password: 'test',
  1660. },
  1661. );
  1662. const { activeOrder } = await shopClient.query<CodegenShop.GetActiveOrderQuery>(GET_ACTIVE_ORDER);
  1663. expect(activeOrder!.lines.length).toBe(1);
  1664. expect(activeOrder!.lines[0].productVariant.id).toBe('T_1');
  1665. });
  1666. it('merges guest order with existing order', async () => {
  1667. await shopClient.asAnonymousUser();
  1668. const { addItemToOrder } = await shopClient.query<
  1669. CodegenShop.AddItemToOrderMutation,
  1670. CodegenShop.AddItemToOrderMutationVariables
  1671. >(ADD_ITEM_TO_ORDER, {
  1672. productVariantId: 'T_2',
  1673. quantity: 1,
  1674. });
  1675. orderResultGuard.assertSuccess(addItemToOrder);
  1676. expect(addItemToOrder.lines.length).toBe(1);
  1677. expect(addItemToOrder.lines[0].productVariant.id).toBe('T_2');
  1678. await shopClient.query<Codegen.AttemptLoginMutation, Codegen.AttemptLoginMutationVariables>(
  1679. ATTEMPT_LOGIN,
  1680. {
  1681. username: customers[1].emailAddress,
  1682. password: 'test',
  1683. },
  1684. );
  1685. const { activeOrder } = await shopClient.query<CodegenShop.GetActiveOrderQuery>(GET_ACTIVE_ORDER);
  1686. expect(activeOrder!.lines.length).toBe(2);
  1687. expect(activeOrder!.lines[0].productVariant.id).toBe('T_1');
  1688. expect(activeOrder!.lines[1].productVariant.id).toBe('T_2');
  1689. });
  1690. /**
  1691. * See https://github.com/vendure-ecommerce/vendure/issues/263
  1692. */
  1693. it('does not merge when logging in to a different account (issue #263)', async () => {
  1694. await shopClient.query<Codegen.AttemptLoginMutation, Codegen.AttemptLoginMutationVariables>(
  1695. ATTEMPT_LOGIN,
  1696. {
  1697. username: customers[2].emailAddress,
  1698. password: 'test',
  1699. },
  1700. );
  1701. const { activeOrder } = await shopClient.query<CodegenShop.GetActiveOrderQuery>(GET_ACTIVE_ORDER);
  1702. expect(activeOrder).toBeNull();
  1703. });
  1704. it('does not merge when logging back to other account (issue #263)', async () => {
  1705. const { addItemToOrder } = await shopClient.query<
  1706. CodegenShop.AddItemToOrderMutation,
  1707. CodegenShop.AddItemToOrderMutationVariables
  1708. >(ADD_ITEM_TO_ORDER, {
  1709. productVariantId: 'T_3',
  1710. quantity: 1,
  1711. });
  1712. await shopClient.query<Codegen.AttemptLoginMutation, Codegen.AttemptLoginMutationVariables>(
  1713. ATTEMPT_LOGIN,
  1714. {
  1715. username: customers[1].emailAddress,
  1716. password: 'test',
  1717. },
  1718. );
  1719. const { activeOrder } = await shopClient.query<CodegenShop.GetActiveOrderQuery>(GET_ACTIVE_ORDER);
  1720. expect(activeOrder!.lines.length).toBe(2);
  1721. expect(activeOrder!.lines[0].productVariant.id).toBe('T_1');
  1722. expect(activeOrder!.lines[1].productVariant.id).toBe('T_2');
  1723. });
  1724. // https://github.com/vendure-ecommerce/vendure/issues/754
  1725. it('handles merging when an existing order has OrderLines', async () => {
  1726. async function setShippingOnActiveOrder() {
  1727. await shopClient.query<
  1728. CodegenShop.SetShippingAddressMutation,
  1729. CodegenShop.SetShippingAddressMutationVariables
  1730. >(SET_SHIPPING_ADDRESS, {
  1731. input: {
  1732. streetLine1: '12 the street',
  1733. countryCode: 'US',
  1734. },
  1735. });
  1736. const { eligibleShippingMethods } =
  1737. await shopClient.query<CodegenShop.GetShippingMethodsQuery>(
  1738. GET_ELIGIBLE_SHIPPING_METHODS,
  1739. );
  1740. await shopClient.query<
  1741. CodegenShop.SetShippingMethodMutation,
  1742. CodegenShop.SetShippingMethodMutationVariables
  1743. >(SET_SHIPPING_METHOD, {
  1744. id: eligibleShippingMethods[1].id,
  1745. });
  1746. }
  1747. // Set up an existing order and add a ShippingLine
  1748. await shopClient.asUserWithCredentials(customers[2].emailAddress, 'test');
  1749. await shopClient.query<
  1750. CodegenShop.AddItemToOrderMutation,
  1751. CodegenShop.AddItemToOrderMutationVariables
  1752. >(ADD_ITEM_TO_ORDER, {
  1753. productVariantId: 'T_3',
  1754. quantity: 1,
  1755. });
  1756. await setShippingOnActiveOrder();
  1757. // Now start a new guest order
  1758. await shopClient.query(LOG_OUT);
  1759. await shopClient.query<
  1760. CodegenShop.AddItemToOrderMutation,
  1761. CodegenShop.AddItemToOrderMutationVariables
  1762. >(ADD_ITEM_TO_ORDER, {
  1763. productVariantId: 'T_4',
  1764. quantity: 1,
  1765. });
  1766. await setShippingOnActiveOrder();
  1767. // attempt to log in and merge the guest order with the existing order
  1768. const { login } = await shopClient.query<
  1769. Codegen.AttemptLoginMutation,
  1770. Codegen.AttemptLoginMutationVariables
  1771. >(ATTEMPT_LOGIN, {
  1772. username: customers[2].emailAddress,
  1773. password: 'test',
  1774. });
  1775. expect(login.identifier).toBe(customers[2].emailAddress);
  1776. });
  1777. });
  1778. describe('security of customer data', () => {
  1779. let customers: Codegen.GetCustomerListQuery['customers']['items'];
  1780. beforeAll(async () => {
  1781. const result = await adminClient.query<Codegen.GetCustomerListQuery>(GET_CUSTOMER_LIST);
  1782. customers = result.customers.items;
  1783. });
  1784. it('cannot setCustomOrder to existing non-guest Customer', async () => {
  1785. await shopClient.asAnonymousUser();
  1786. const { addItemToOrder } = await shopClient.query<
  1787. CodegenShop.AddItemToOrderMutation,
  1788. CodegenShop.AddItemToOrderMutationVariables
  1789. >(ADD_ITEM_TO_ORDER, {
  1790. productVariantId: 'T_1',
  1791. quantity: 1,
  1792. });
  1793. const { setCustomerForOrder } = await shopClient.query<
  1794. CodegenShop.SetCustomerForOrderMutation,
  1795. CodegenShop.SetCustomerForOrderMutationVariables
  1796. >(SET_CUSTOMER, {
  1797. input: {
  1798. emailAddress: customers[0].emailAddress,
  1799. firstName: 'Evil',
  1800. lastName: 'Hacker',
  1801. },
  1802. });
  1803. orderResultGuard.assertErrorResult(setCustomerForOrder);
  1804. expect(setCustomerForOrder.message).toBe('The email address is not available.');
  1805. expect(setCustomerForOrder.errorCode).toBe(ErrorCode.EMAIL_ADDRESS_CONFLICT_ERROR);
  1806. const { customer } = await adminClient.query<
  1807. Codegen.GetCustomerQuery,
  1808. Codegen.GetCustomerQueryVariables
  1809. >(GET_CUSTOMER, {
  1810. id: customers[0].id,
  1811. });
  1812. expect(customer!.firstName).not.toBe('Evil');
  1813. expect(customer!.lastName).not.toBe('Hacker');
  1814. });
  1815. it('guest cannot access Addresses of guest customer', async () => {
  1816. await shopClient.asAnonymousUser();
  1817. const { addItemToOrder } = await shopClient.query<
  1818. CodegenShop.AddItemToOrderMutation,
  1819. CodegenShop.AddItemToOrderMutationVariables
  1820. >(ADD_ITEM_TO_ORDER, {
  1821. productVariantId: 'T_1',
  1822. quantity: 1,
  1823. });
  1824. await shopClient.query<
  1825. CodegenShop.SetCustomerForOrderMutation,
  1826. CodegenShop.SetCustomerForOrderMutationVariables
  1827. >(SET_CUSTOMER, {
  1828. input: {
  1829. emailAddress: 'test@test.com',
  1830. firstName: 'Evil',
  1831. lastName: 'Hacker',
  1832. },
  1833. });
  1834. const { activeOrder } =
  1835. await shopClient.query<CodegenShop.GetCustomerAddressesQuery>(GET_ACTIVE_ORDER_ADDRESSES);
  1836. expect(activeOrder!.customer!.addresses).toEqual([]);
  1837. });
  1838. it('guest cannot access Orders of guest customer', async () => {
  1839. await shopClient.asAnonymousUser();
  1840. const { addItemToOrder } = await shopClient.query<
  1841. CodegenShop.AddItemToOrderMutation,
  1842. CodegenShop.AddItemToOrderMutationVariables
  1843. >(ADD_ITEM_TO_ORDER, {
  1844. productVariantId: 'T_1',
  1845. quantity: 1,
  1846. });
  1847. await shopClient.query<
  1848. CodegenShop.SetCustomerForOrderMutation,
  1849. CodegenShop.SetCustomerForOrderMutationVariables
  1850. >(SET_CUSTOMER, {
  1851. input: {
  1852. emailAddress: 'test@test.com',
  1853. firstName: 'Evil',
  1854. lastName: 'Hacker',
  1855. },
  1856. });
  1857. const { activeOrder } =
  1858. await shopClient.query<CodegenShop.GetCustomerOrdersQuery>(GET_ACTIVE_ORDER_ORDERS);
  1859. expect(activeOrder!.customer!.orders.items).toEqual([]);
  1860. });
  1861. });
  1862. describe('order custom fields', () => {
  1863. it('custom fields added to type', async () => {
  1864. await shopClient.asAnonymousUser();
  1865. await shopClient.query<
  1866. CodegenShop.AddItemToOrderMutation,
  1867. CodegenShop.AddItemToOrderMutationVariables
  1868. >(ADD_ITEM_TO_ORDER, {
  1869. productVariantId: 'T_1',
  1870. quantity: 1,
  1871. });
  1872. const { activeOrder } = await shopClient.query(GET_ORDER_CUSTOM_FIELDS);
  1873. expect(activeOrder?.customFields).toEqual({
  1874. orderImage: null,
  1875. giftWrap: false,
  1876. });
  1877. });
  1878. it('setting order custom fields', async () => {
  1879. const { setOrderCustomFields } = await shopClient.query(SET_ORDER_CUSTOM_FIELDS, {
  1880. input: {
  1881. customFields: { giftWrap: true, orderImageId: 'T_1' },
  1882. },
  1883. });
  1884. expect(setOrderCustomFields?.customFields).toEqual({
  1885. orderImage: { id: 'T_1' },
  1886. giftWrap: true,
  1887. });
  1888. const { activeOrder } = await shopClient.query(GET_ORDER_CUSTOM_FIELDS);
  1889. expect(activeOrder?.customFields).toEqual({
  1890. orderImage: { id: 'T_1' },
  1891. giftWrap: true,
  1892. });
  1893. });
  1894. });
  1895. describe('remove all order lines', () => {
  1896. beforeAll(async () => {
  1897. await shopClient.asAnonymousUser();
  1898. await shopClient.query<
  1899. CodegenShop.AddItemToOrderMutation,
  1900. CodegenShop.AddItemToOrderMutationVariables
  1901. >(ADD_ITEM_TO_ORDER, {
  1902. productVariantId: 'T_1',
  1903. quantity: 1,
  1904. });
  1905. await shopClient.query<
  1906. CodegenShop.AddItemToOrderMutation,
  1907. CodegenShop.AddItemToOrderMutationVariables
  1908. >(ADD_ITEM_TO_ORDER, {
  1909. productVariantId: 'T_2',
  1910. quantity: 3,
  1911. });
  1912. });
  1913. it('should remove all order lines', async () => {
  1914. const { removeAllOrderLines } = await shopClient.query<
  1915. CodegenShop.RemoveAllOrderLinesMutation,
  1916. CodegenShop.RemoveAllOrderLinesMutationVariables
  1917. >(REMOVE_ALL_ORDER_LINES);
  1918. orderResultGuard.assertSuccess(removeAllOrderLines);
  1919. expect(removeAllOrderLines?.total).toBe(0);
  1920. expect(removeAllOrderLines?.lines.length).toBe(0);
  1921. });
  1922. });
  1923. describe('validation of product variant availability', () => {
  1924. const bonsaiProductId = 'T_20';
  1925. const bonsaiVariantId = 'T_34';
  1926. beforeAll(async () => {
  1927. await shopClient.asAnonymousUser();
  1928. });
  1929. it(
  1930. 'addItemToOrder errors when product is disabled',
  1931. assertThrowsWithMessage(async () => {
  1932. await adminClient.query<
  1933. Codegen.UpdateProductMutation,
  1934. Codegen.UpdateProductMutationVariables
  1935. >(UPDATE_PRODUCT, {
  1936. input: {
  1937. id: bonsaiProductId,
  1938. enabled: false,
  1939. },
  1940. });
  1941. await shopClient.query<
  1942. CodegenShop.AddItemToOrderMutation,
  1943. CodegenShop.AddItemToOrderMutationVariables
  1944. >(ADD_ITEM_TO_ORDER, {
  1945. productVariantId: bonsaiVariantId,
  1946. quantity: 1,
  1947. });
  1948. }, 'No ProductVariant with the id "34" could be found'),
  1949. );
  1950. it(
  1951. 'addItemToOrder errors when product variant is disabled',
  1952. assertThrowsWithMessage(async () => {
  1953. await adminClient.query<
  1954. Codegen.UpdateProductMutation,
  1955. Codegen.UpdateProductMutationVariables
  1956. >(UPDATE_PRODUCT, {
  1957. input: {
  1958. id: bonsaiProductId,
  1959. enabled: true,
  1960. },
  1961. });
  1962. await adminClient.query<
  1963. Codegen.UpdateProductVariantsMutation,
  1964. Codegen.UpdateProductVariantsMutationVariables
  1965. >(UPDATE_PRODUCT_VARIANTS, {
  1966. input: [
  1967. {
  1968. id: bonsaiVariantId,
  1969. enabled: false,
  1970. },
  1971. ],
  1972. });
  1973. await shopClient.query<
  1974. CodegenShop.AddItemToOrderMutation,
  1975. CodegenShop.AddItemToOrderMutationVariables
  1976. >(ADD_ITEM_TO_ORDER, {
  1977. productVariantId: bonsaiVariantId,
  1978. quantity: 1,
  1979. });
  1980. }, 'No ProductVariant with the id "34" could be found'),
  1981. );
  1982. it(
  1983. 'addItemToOrder errors when product is deleted',
  1984. assertThrowsWithMessage(async () => {
  1985. await adminClient.query<
  1986. Codegen.DeleteProductMutation,
  1987. Codegen.DeleteProductMutationVariables
  1988. >(DELETE_PRODUCT, {
  1989. id: bonsaiProductId,
  1990. });
  1991. await shopClient.query<
  1992. CodegenShop.AddItemToOrderMutation,
  1993. CodegenShop.AddItemToOrderMutationVariables
  1994. >(ADD_ITEM_TO_ORDER, {
  1995. productVariantId: bonsaiVariantId,
  1996. quantity: 1,
  1997. });
  1998. }, 'No ProductVariant with the id "34" could be found'),
  1999. );
  2000. it(
  2001. 'addItemToOrder errors when product variant is deleted',
  2002. assertThrowsWithMessage(async () => {
  2003. await adminClient.query<
  2004. Codegen.DeleteProductVariantMutation,
  2005. Codegen.DeleteProductVariantMutationVariables
  2006. >(DELETE_PRODUCT_VARIANT, {
  2007. id: bonsaiVariantId,
  2008. });
  2009. await shopClient.query<
  2010. CodegenShop.AddItemToOrderMutation,
  2011. CodegenShop.AddItemToOrderMutationVariables
  2012. >(ADD_ITEM_TO_ORDER, {
  2013. productVariantId: bonsaiVariantId,
  2014. quantity: 1,
  2015. });
  2016. }, 'No ProductVariant with the id "34" could be found'),
  2017. );
  2018. let orderWithDeletedProductVariantId: string;
  2019. it('errors when transitioning to ArrangingPayment with deleted variant', async () => {
  2020. const orchidProductId = 'T_19';
  2021. const orchidVariantId = 'T_33';
  2022. await shopClient.asUserWithCredentials('marques.sawayn@hotmail.com', 'test');
  2023. const { addItemToOrder } = await shopClient.query<
  2024. CodegenShop.AddItemToOrderMutation,
  2025. CodegenShop.AddItemToOrderMutationVariables
  2026. >(ADD_ITEM_TO_ORDER, {
  2027. productVariantId: orchidVariantId,
  2028. quantity: 1,
  2029. });
  2030. orderResultGuard.assertSuccess(addItemToOrder);
  2031. orderWithDeletedProductVariantId = addItemToOrder.id;
  2032. await adminClient.query<Codegen.DeleteProductMutation, Codegen.DeleteProductMutationVariables>(
  2033. DELETE_PRODUCT,
  2034. {
  2035. id: orchidProductId,
  2036. },
  2037. );
  2038. const { transitionOrderToState } = await shopClient.query<
  2039. CodegenShop.TransitionToStateMutation,
  2040. CodegenShop.TransitionToStateMutationVariables
  2041. >(TRANSITION_TO_STATE, {
  2042. state: 'ArrangingPayment',
  2043. });
  2044. orderResultGuard.assertErrorResult(transitionOrderToState);
  2045. expect(transitionOrderToState!.transitionError).toBe(
  2046. 'Cannot transition to "ArrangingPayment" because the Order contains ProductVariants which are no longer available',
  2047. );
  2048. expect(transitionOrderToState!.errorCode).toBe(ErrorCode.ORDER_STATE_TRANSITION_ERROR);
  2049. });
  2050. // https://github.com/vendure-ecommerce/vendure/issues/1567
  2051. it('allows transitioning to Cancelled with deleted variant', async () => {
  2052. const { cancelOrder } = await adminClient.query<
  2053. Codegen.CancelOrderMutation,
  2054. Codegen.CancelOrderMutationVariables
  2055. >(CANCEL_ORDER, {
  2056. input: {
  2057. orderId: orderWithDeletedProductVariantId,
  2058. },
  2059. });
  2060. orderResultGuard.assertSuccess(cancelOrder);
  2061. expect(cancelOrder.state).toBe('Cancelled');
  2062. });
  2063. });
  2064. // https://github.com/vendure-ecommerce/vendure/issues/1195
  2065. describe('shipping method invalidation', () => {
  2066. let GBShippingMethodId: string;
  2067. let ATShippingMethodId: string;
  2068. beforeAll(async () => {
  2069. // First we will remove all ShippingMethods and set up 2 specialized ones
  2070. const { shippingMethods } =
  2071. await adminClient.query<Codegen.GetShippingMethodListQuery>(GET_SHIPPING_METHOD_LIST);
  2072. for (const method of shippingMethods.items) {
  2073. await adminClient.query<
  2074. Codegen.DeleteShippingMethodMutation,
  2075. Codegen.DeleteShippingMethodMutationVariables
  2076. >(DELETE_SHIPPING_METHOD, {
  2077. id: method.id,
  2078. });
  2079. }
  2080. function createCountryCodeShippingMethodInput(countryCode: string): CreateShippingMethodInput {
  2081. return {
  2082. code: `${countryCode}-shipping`,
  2083. translations: [
  2084. { languageCode: LanguageCode.en, name: `${countryCode} shipping`, description: '' },
  2085. ],
  2086. fulfillmentHandler: manualFulfillmentHandler.code,
  2087. checker: {
  2088. code: countryCodeShippingEligibilityChecker.code,
  2089. arguments: [{ name: 'countryCode', value: countryCode }],
  2090. },
  2091. calculator: {
  2092. code: defaultShippingCalculator.code,
  2093. arguments: [
  2094. { name: 'rate', value: '1000' },
  2095. { name: 'taxRate', value: '0' },
  2096. { name: 'includesTax', value: 'auto' },
  2097. ],
  2098. },
  2099. };
  2100. }
  2101. // Now create 2 shipping methods, valid only for a single country
  2102. const result1 = await adminClient.query<
  2103. Codegen.CreateShippingMethodMutation,
  2104. Codegen.CreateShippingMethodMutationVariables
  2105. >(CREATE_SHIPPING_METHOD, {
  2106. input: createCountryCodeShippingMethodInput('GB'),
  2107. });
  2108. GBShippingMethodId = result1.createShippingMethod.id;
  2109. const result2 = await adminClient.query<
  2110. Codegen.CreateShippingMethodMutation,
  2111. Codegen.CreateShippingMethodMutationVariables
  2112. >(CREATE_SHIPPING_METHOD, {
  2113. input: createCountryCodeShippingMethodInput('AT'),
  2114. });
  2115. ATShippingMethodId = result2.createShippingMethod.id;
  2116. // Now create an order to GB and set the GB shipping method
  2117. const { addItemToOrder } = await shopClient.query<
  2118. CodegenShop.AddItemToOrderMutation,
  2119. CodegenShop.AddItemToOrderMutationVariables
  2120. >(ADD_ITEM_TO_ORDER, {
  2121. productVariantId: 'T_1',
  2122. quantity: 1,
  2123. });
  2124. await shopClient.query<
  2125. CodegenShop.SetCustomerForOrderMutation,
  2126. CodegenShop.SetCustomerForOrderMutationVariables
  2127. >(SET_CUSTOMER, {
  2128. input: {
  2129. emailAddress: 'test-2@test.com',
  2130. firstName: 'Test',
  2131. lastName: 'Person 2',
  2132. },
  2133. });
  2134. await shopClient.query<
  2135. CodegenShop.SetShippingAddressMutation,
  2136. CodegenShop.SetShippingAddressMutationVariables
  2137. >(SET_SHIPPING_ADDRESS, {
  2138. input: {
  2139. streetLine1: '12 the street',
  2140. countryCode: 'GB',
  2141. },
  2142. });
  2143. await shopClient.query<
  2144. CodegenShop.SetShippingMethodMutation,
  2145. CodegenShop.SetShippingMethodMutationVariables
  2146. >(SET_SHIPPING_METHOD, {
  2147. id: GBShippingMethodId,
  2148. });
  2149. });
  2150. it('if selected method no longer eligible, next best is set automatically', async () => {
  2151. const result1 = await shopClient.query<CodegenShop.GetActiveOrderQuery>(GET_ACTIVE_ORDER);
  2152. expect(result1.activeOrder?.shippingLines[0].shippingMethod.id).toBe(GBShippingMethodId);
  2153. await shopClient.query<
  2154. CodegenShop.SetShippingAddressMutation,
  2155. CodegenShop.SetShippingAddressMutationVariables
  2156. >(SET_SHIPPING_ADDRESS, {
  2157. input: {
  2158. streetLine1: '12 the street',
  2159. countryCode: 'AT',
  2160. },
  2161. });
  2162. const result2 = await shopClient.query<CodegenShop.GetActiveOrderQuery>(GET_ACTIVE_ORDER);
  2163. expect(result2.activeOrder?.shippingLines[0].shippingMethod.id).toBe(ATShippingMethodId);
  2164. });
  2165. it('if no method is eligible, shipping lines are cleared', async () => {
  2166. await shopClient.query<
  2167. CodegenShop.SetShippingAddressMutation,
  2168. CodegenShop.SetShippingAddressMutationVariables
  2169. >(SET_SHIPPING_ADDRESS, {
  2170. input: {
  2171. streetLine1: '12 the street',
  2172. countryCode: 'US',
  2173. },
  2174. });
  2175. const result = await shopClient.query<CodegenShop.GetActiveOrderQuery>(GET_ACTIVE_ORDER);
  2176. expect(result.activeOrder?.shippingLines).toEqual([]);
  2177. });
  2178. // https://github.com/vendure-ecommerce/vendure/issues/1441
  2179. it('shipping methods are re-evaluated when all OrderLines are removed', async () => {
  2180. const { createShippingMethod } = await adminClient.query<
  2181. CreateShippingMethod.Mutation,
  2182. CreateShippingMethod.Variables
  2183. >(CREATE_SHIPPING_METHOD, {
  2184. input: {
  2185. code: 'min-price-shipping',
  2186. translations: [
  2187. { languageCode: LanguageCode.en, name: 'min price shipping', description: '' },
  2188. ],
  2189. fulfillmentHandler: manualFulfillmentHandler.code,
  2190. checker: {
  2191. code: defaultShippingEligibilityChecker.code,
  2192. arguments: [{ name: 'orderMinimum', value: '100' }],
  2193. },
  2194. calculator: {
  2195. code: defaultShippingCalculator.code,
  2196. arguments: [
  2197. { name: 'rate', value: '1000' },
  2198. { name: 'taxRate', value: '0' },
  2199. { name: 'includesTax', value: 'auto' },
  2200. ],
  2201. },
  2202. },
  2203. });
  2204. const minPriceShippingMethodId = createShippingMethod.id;
  2205. await shopClient.query<SetShippingMethod.Mutation, SetShippingMethod.Variables>(
  2206. SET_SHIPPING_METHOD,
  2207. {
  2208. id: minPriceShippingMethodId,
  2209. },
  2210. );
  2211. const result1 = await shopClient.query<CodegenShop.GetActiveOrderQuery>(GET_ACTIVE_ORDER);
  2212. expect(result1.activeOrder?.shippingLines[0].shippingMethod.id).toBe(minPriceShippingMethodId);
  2213. const { removeAllOrderLines } = await shopClient.query<
  2214. CodegenShop.RemoveAllOrderLinesMutation,
  2215. CodegenShop.RemoveAllOrderLinesMutationVariables
  2216. >(REMOVE_ALL_ORDER_LINES);
  2217. orderResultGuard.assertSuccess(removeAllOrderLines);
  2218. expect(removeAllOrderLines.shippingLines.length).toBe(0);
  2219. expect(removeAllOrderLines.shippingWithTax).toBe(0);
  2220. });
  2221. });
  2222. describe('edge cases', () => {
  2223. it('calling setShippingMethod and setBillingMethod in parallel does not introduce race condition', async () => {
  2224. const shippingAddress: CreateAddressInput = {
  2225. fullName: 'name',
  2226. company: 'company',
  2227. streetLine1: '12 Shipping Street',
  2228. streetLine2: null,
  2229. city: 'foo',
  2230. province: 'bar',
  2231. postalCode: '123456',
  2232. countryCode: 'US',
  2233. phoneNumber: '4444444',
  2234. };
  2235. const billingAddress: CreateAddressInput = {
  2236. fullName: 'name',
  2237. company: 'company',
  2238. streetLine1: '22 Billing Avenue',
  2239. streetLine2: null,
  2240. city: 'foo',
  2241. province: 'bar',
  2242. postalCode: '123456',
  2243. countryCode: 'US',
  2244. phoneNumber: '4444444',
  2245. };
  2246. await Promise.all([
  2247. shopClient.query<
  2248. CodegenShop.SetBillingAddressMutation,
  2249. CodegenShop.SetBillingAddressMutationVariables
  2250. >(SET_BILLING_ADDRESS, {
  2251. input: billingAddress,
  2252. }),
  2253. shopClient.query<
  2254. CodegenShop.SetShippingAddressMutation,
  2255. CodegenShop.SetShippingAddressMutationVariables
  2256. >(SET_SHIPPING_ADDRESS, {
  2257. input: shippingAddress,
  2258. }),
  2259. ]);
  2260. const { activeOrder } = await shopClient.query(gql`
  2261. query {
  2262. activeOrder {
  2263. shippingAddress {
  2264. ...OrderAddress
  2265. }
  2266. billingAddress {
  2267. ...OrderAddress
  2268. }
  2269. }
  2270. }
  2271. fragment OrderAddress on OrderAddress {
  2272. fullName
  2273. company
  2274. streetLine1
  2275. streetLine2
  2276. city
  2277. province
  2278. postalCode
  2279. countryCode
  2280. phoneNumber
  2281. }
  2282. `);
  2283. expect(activeOrder.shippingAddress).toEqual(shippingAddress);
  2284. expect(activeOrder.billingAddress).toEqual(billingAddress);
  2285. });
  2286. // https://github.com/vendure-ecommerce/vendure/issues/2548
  2287. it('hydrating Order in the ShippingEligibilityChecker does not break order modification', async () => {
  2288. // First we'll create a ShippingMethod that uses the hydrating checker
  2289. await adminClient.query(CreateShippingMethodDocument, {
  2290. input: {
  2291. code: 'hydrating-checker',
  2292. translations: [
  2293. { languageCode: LanguageCode.en, name: 'hydrating checker', description: '' },
  2294. ],
  2295. fulfillmentHandler: manualFulfillmentHandler.code,
  2296. checker: {
  2297. code: hydratingShippingEligibilityChecker.code,
  2298. arguments: [],
  2299. },
  2300. calculator: {
  2301. code: defaultShippingCalculator.code,
  2302. arguments: [
  2303. { name: 'rate', value: '1000' },
  2304. { name: 'taxRate', value: '0' },
  2305. { name: 'includesTax', value: 'auto' },
  2306. ],
  2307. },
  2308. },
  2309. });
  2310. await shopClient.asAnonymousUser();
  2311. await shopClient.query<
  2312. CodegenShop.AddItemToOrderMutation,
  2313. CodegenShop.AddItemToOrderMutationVariables
  2314. >(ADD_ITEM_TO_ORDER, {
  2315. productVariantId: 'T_1',
  2316. quantity: 1,
  2317. });
  2318. await shopClient.query<
  2319. CodegenShop.AddItemToOrderMutation,
  2320. CodegenShop.AddItemToOrderMutationVariables
  2321. >(ADD_ITEM_TO_ORDER, {
  2322. productVariantId: 'T_2',
  2323. quantity: 3,
  2324. });
  2325. const result1 = await shopClient.query<CodegenShop.GetActiveOrderQuery>(GET_ACTIVE_ORDER);
  2326. expect(result1.activeOrder?.lines.map(l => l.linePriceWithTax).sort()).toEqual([155880, 503640]);
  2327. expect(result1.activeOrder?.subTotalWithTax).toBe(659520);
  2328. // set the shipping method that uses the hydrating checker
  2329. const { eligibleShippingMethods } = await shopClient.query<CodegenShop.GetShippingMethodsQuery>(
  2330. GET_ELIGIBLE_SHIPPING_METHODS,
  2331. );
  2332. const { setOrderShippingMethod } = await shopClient.query<
  2333. CodegenShop.SetShippingMethodMutation,
  2334. CodegenShop.SetShippingMethodMutationVariables
  2335. >(SET_SHIPPING_METHOD, {
  2336. id: eligibleShippingMethods.find(m => m.code === 'hydrating-checker')!.id,
  2337. });
  2338. orderResultGuard.assertSuccess(setOrderShippingMethod);
  2339. // Remove an item from the order
  2340. const { removeOrderLine } = await shopClient.query(RemoveItemFromOrderDocument, {
  2341. orderLineId: result1.activeOrder!.lines[0].id,
  2342. });
  2343. orderResultGuard.assertSuccess(removeOrderLine);
  2344. expect(removeOrderLine.lines.length).toBe(1);
  2345. const result2 = await shopClient.query<CodegenShop.GetActiveOrderQuery>(GET_ACTIVE_ORDER);
  2346. expect(result2.activeOrder?.lines.map(l => l.linePriceWithTax).sort()).toEqual([503640]);
  2347. expect(result2.activeOrder?.subTotalWithTax).toBe(503640);
  2348. });
  2349. });
  2350. });
  2351. const GET_ORDER_CUSTOM_FIELDS = gql`
  2352. query GetOrderCustomFields {
  2353. activeOrder {
  2354. id
  2355. customFields {
  2356. giftWrap
  2357. orderImage {
  2358. id
  2359. }
  2360. }
  2361. }
  2362. }
  2363. `;
  2364. const SET_ORDER_CUSTOM_FIELDS = gql`
  2365. mutation SetOrderCustomFields($input: UpdateOrderInput!) {
  2366. setOrderCustomFields(input: $input) {
  2367. ... on Order {
  2368. id
  2369. customFields {
  2370. giftWrap
  2371. orderImage {
  2372. id
  2373. }
  2374. }
  2375. }
  2376. ... on ErrorResult {
  2377. errorCode
  2378. message
  2379. }
  2380. }
  2381. }
  2382. `;
  2383. export const LOG_OUT = gql`
  2384. mutation LogOut {
  2385. logout {
  2386. success
  2387. }
  2388. }
  2389. `;
  2390. export const ADD_ITEM_TO_ORDER_WITH_CUSTOM_FIELDS = gql`
  2391. mutation AddItemToOrderWithCustomFields(
  2392. $productVariantId: ID!
  2393. $quantity: Int!
  2394. $customFields: OrderLineCustomFieldsInput
  2395. ) {
  2396. addItemToOrder(
  2397. productVariantId: $productVariantId
  2398. quantity: $quantity
  2399. customFields: $customFields
  2400. ) {
  2401. ...UpdatedOrder
  2402. ... on ErrorResult {
  2403. errorCode
  2404. message
  2405. }
  2406. }
  2407. }
  2408. ${UPDATED_ORDER_FRAGMENT}
  2409. `;
  2410. const ADJUST_ORDER_LINE_WITH_CUSTOM_FIELDS = gql`
  2411. mutation ($orderLineId: ID!, $quantity: Int!, $customFields: OrderLineCustomFieldsInput) {
  2412. adjustOrderLine(orderLineId: $orderLineId, quantity: $quantity, customFields: $customFields) {
  2413. ... on Order {
  2414. lines {
  2415. id
  2416. customFields {
  2417. notes
  2418. lineImage {
  2419. id
  2420. }
  2421. lineImages {
  2422. id
  2423. }
  2424. }
  2425. }
  2426. }
  2427. }
  2428. }
  2429. `;