mock-data.service.ts 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506
  1. import faker from 'faker/locale/en_GB';
  2. import fs from 'fs-extra';
  3. import gql from 'graphql-tag';
  4. import path from 'path';
  5. import { CREATE_FACET } from '../../admin-ui/src/app/data/definitions/facet-definitions';
  6. import {
  7. ADD_OPTION_GROUP_TO_PRODUCT,
  8. CREATE_PRODUCT,
  9. CREATE_PRODUCT_OPTION_GROUP,
  10. GENERATE_PRODUCT_VARIANTS,
  11. UPDATE_PRODUCT_VARIANTS,
  12. } from '../../admin-ui/src/app/data/definitions/product-definitions';
  13. import {
  14. CREATE_CHANNEL,
  15. CREATE_COUNTRY,
  16. CREATE_TAX_RATE,
  17. CREATE_ZONE,
  18. GET_CHANNELS,
  19. UPDATE_CHANNEL,
  20. } from '../../admin-ui/src/app/data/definitions/settings-definitions';
  21. import { CREATE_SHIPPING_METHOD } from '../../admin-ui/src/app/data/definitions/shipping-definitions';
  22. import {
  23. AddOptionGroupToProduct,
  24. Asset,
  25. Channel,
  26. CreateAddressInput,
  27. CreateChannel,
  28. CreateCountry,
  29. CreateCustomerInput,
  30. CreateFacet,
  31. CreateFacetValueWithFacetInput,
  32. CreateProduct,
  33. CreateProductOptionGroup,
  34. CreateShippingMethod,
  35. CreateTaxRate,
  36. CreateZone,
  37. CurrencyCode,
  38. GenerateProductVariants,
  39. GetChannels,
  40. LanguageCode,
  41. ProductTranslationInput,
  42. ProductVariant,
  43. UpdateChannel,
  44. UpdateProductVariants,
  45. Zone,
  46. } from '../../shared/generated-types';
  47. import { defaultShippingCalculator } from '../src/config/shipping-method/default-shipping-calculator';
  48. import { defaultShippingEligibilityChecker } from '../src/config/shipping-method/default-shipping-eligibility-checker';
  49. import { Customer } from '../src/entity/customer/customer.entity';
  50. import { SimpleGraphQLClient } from './simple-graphql-client';
  51. import TaxCategory = ProductVariant.TaxCategory;
  52. // tslint:disable:no-console
  53. /**
  54. * A service for creating mock data via the GraphQL API.
  55. */
  56. export class MockDataService {
  57. apiUrl: string;
  58. constructor(private client: SimpleGraphQLClient, private logging = true) {
  59. // make the generated results deterministic
  60. faker.seed(1);
  61. }
  62. async populateChannels(channelCodes: string[]): Promise<Channel.Fragment[]> {
  63. const channels: Channel.Fragment[] = [];
  64. for (const code of channelCodes) {
  65. const channel = await this.client.query<CreateChannel.Mutation, CreateChannel.Variables>(
  66. CREATE_CHANNEL,
  67. {
  68. input: {
  69. code,
  70. pricesIncludeTax: true,
  71. token: `${code}_token`,
  72. currencyCode: CurrencyCode.USD,
  73. defaultLanguageCode: LanguageCode.en,
  74. },
  75. },
  76. );
  77. channels.push(channel.createChannel);
  78. this.log(`Created Channel: ${channel.createChannel.code}`);
  79. }
  80. return channels;
  81. }
  82. async populateCountries(all = false): Promise<Zone.Fragment[]> {
  83. const countriesFile = await fs.readFile(
  84. path.join(__dirname, 'data-sources', 'countries.json'),
  85. 'utf8',
  86. );
  87. const limitedCountries = ['GB', 'DE', 'FR', 'AT', 'US', 'CN', 'JP', 'AU', 'ZA'];
  88. const countries: any[] = JSON.parse(countriesFile).filter(c => {
  89. if (all) {
  90. return true;
  91. } else {
  92. return limitedCountries.includes(c['alpha-2']);
  93. }
  94. });
  95. const zones: { [zoneName: string]: string[] } = {};
  96. for (const country of countries) {
  97. const result = await this.client.query<CreateCountry.Mutation, CreateCountry.Variables>(
  98. CREATE_COUNTRY,
  99. {
  100. input: {
  101. code: country['alpha-2'],
  102. translations: [{ languageCode: LanguageCode.en, name: country.name }],
  103. enabled: true,
  104. },
  105. },
  106. );
  107. if (!zones[country.region]) {
  108. zones[country.region] = [];
  109. }
  110. zones[country.region].push(result.createCountry.id);
  111. }
  112. const createdZones: Zone.Fragment[] = [];
  113. for (const [name, memberIds] of Object.entries(zones)) {
  114. const result = await this.client.query<CreateZone.Mutation, CreateZone.Variables>(CREATE_ZONE, {
  115. input: {
  116. name,
  117. memberIds,
  118. },
  119. });
  120. createdZones.push(result.createZone);
  121. }
  122. this.log(`Created ${countries.length} Countries in ${Object.keys(zones).length} Zones`);
  123. return createdZones;
  124. }
  125. async setChannelDefaultZones(zones: Zone.Fragment[]) {
  126. const defaultZone = zones.find(z => z.name === 'UK');
  127. if (!defaultZone) {
  128. this.log(`Default zone could not be found`);
  129. return;
  130. }
  131. const result = await this.client.query<GetChannels.Query>(GET_CHANNELS);
  132. for (const channel of result.channels) {
  133. await this.client.query<UpdateChannel.Mutation, UpdateChannel.Variables>(UPDATE_CHANNEL, {
  134. input: {
  135. id: channel.id,
  136. defaultTaxZoneId: defaultZone.id,
  137. defaultShippingZoneId: defaultZone.id,
  138. },
  139. });
  140. }
  141. this.log(`Set default zones for ${result.channels.length} Channels`);
  142. }
  143. async populateOptions(): Promise<string> {
  144. return this.client
  145. .query<CreateProductOptionGroup.Mutation, CreateProductOptionGroup.Variables>(
  146. CREATE_PRODUCT_OPTION_GROUP,
  147. {
  148. input: {
  149. code: 'size',
  150. translations: [
  151. { languageCode: LanguageCode.en, name: 'Size' },
  152. { languageCode: LanguageCode.de, name: 'Größe' },
  153. ],
  154. options: [
  155. {
  156. code: 'small',
  157. translations: [
  158. { languageCode: LanguageCode.en, name: 'Small' },
  159. { languageCode: LanguageCode.de, name: 'Klein' },
  160. ],
  161. },
  162. {
  163. code: 'large',
  164. translations: [
  165. { languageCode: LanguageCode.en, name: 'Large' },
  166. { languageCode: LanguageCode.de, name: 'Groß' },
  167. ],
  168. },
  169. ],
  170. },
  171. },
  172. )
  173. .then(data => {
  174. this.log('Created option group:', data.createProductOptionGroup.name);
  175. return data.createProductOptionGroup.id;
  176. });
  177. }
  178. async populateTaxCategories(zones: Zone.Fragment[]) {
  179. const taxCategories = [{ name: 'Standard Tax' }, { name: 'Reduced Tax' }, { name: 'Zero Tax' }];
  180. const createdTaxCategories: TaxCategory[] = [];
  181. for (const category of taxCategories) {
  182. const result = await this.client.query(
  183. gql`
  184. mutation($input: CreateTaxCategoryInput!) {
  185. createTaxCategory(input: $input) {
  186. id
  187. }
  188. }
  189. `,
  190. {
  191. input: {
  192. name: category.name,
  193. },
  194. },
  195. );
  196. createdTaxCategories.push(result.createTaxCategory);
  197. }
  198. this.log(`Created ${createdTaxCategories.length} tax categories`);
  199. // create tax rates
  200. for (const zone of zones) {
  201. await this.client.query<CreateTaxRate.Mutation, CreateTaxRate.Variables>(CREATE_TAX_RATE, {
  202. input: {
  203. name: `Standard Tax for ${zone.name}`,
  204. enabled: true,
  205. value: 20,
  206. categoryId: createdTaxCategories[0].id,
  207. zoneId: zone.id,
  208. },
  209. });
  210. }
  211. return createdTaxCategories;
  212. }
  213. async populateShippingMethods() {
  214. await this.client.query<CreateShippingMethod.Mutation, CreateShippingMethod.Variables>(
  215. CREATE_SHIPPING_METHOD,
  216. {
  217. input: {
  218. code: 'standard-flat-rate',
  219. description: 'Standard Shipping',
  220. checker: {
  221. code: defaultShippingEligibilityChecker.code,
  222. arguments: [],
  223. },
  224. calculator: {
  225. code: defaultShippingCalculator.code,
  226. arguments: [{ name: 'rate', value: '500' }],
  227. },
  228. },
  229. },
  230. );
  231. this.log(`Created standard ShippingMethod`);
  232. await this.client.query<CreateShippingMethod.Mutation, CreateShippingMethod.Variables>(
  233. CREATE_SHIPPING_METHOD,
  234. {
  235. input: {
  236. code: 'express-flat-rate',
  237. description: 'Express Shipping',
  238. checker: {
  239. code: defaultShippingEligibilityChecker.code,
  240. arguments: [],
  241. },
  242. calculator: {
  243. code: defaultShippingCalculator.code,
  244. arguments: [{ name: 'rate', value: '1000' }],
  245. },
  246. },
  247. },
  248. );
  249. this.log(`Created express ShippingMethod`);
  250. }
  251. async populateCustomers(count: number = 5): Promise<any> {
  252. for (let i = 0; i < count; i++) {
  253. const firstName = faker.name.firstName();
  254. const lastName = faker.name.lastName();
  255. const query1 = gql`
  256. mutation CreateCustomer($input: CreateCustomerInput!, $password: String) {
  257. createCustomer(input: $input, password: $password) {
  258. id
  259. emailAddress
  260. }
  261. }
  262. `;
  263. const variables1 = {
  264. input: {
  265. firstName,
  266. lastName,
  267. emailAddress: faker.internet.email(firstName, lastName),
  268. phoneNumber: faker.phone.phoneNumber(),
  269. } as CreateCustomerInput,
  270. password: 'test',
  271. };
  272. const customer: { id: string; emailAddress: string } | void = await this.client
  273. .query(query1, variables1)
  274. .then((data: any) => data.createCustomer, err => this.log(err));
  275. if (customer) {
  276. const query2 = gql`
  277. mutation($customerId: ID!, $input: CreateAddressInput!) {
  278. createCustomerAddress(customerId: $customerId, input: $input) {
  279. id
  280. streetLine1
  281. }
  282. }
  283. `;
  284. const variables2 = {
  285. input: {
  286. fullName: `${firstName} ${lastName}`,
  287. streetLine1: faker.address.streetAddress(),
  288. city: faker.address.city(),
  289. province: faker.address.county(),
  290. postalCode: faker.address.zipCode(),
  291. countryCode: 'GB',
  292. } as CreateAddressInput,
  293. customerId: customer.id,
  294. };
  295. await this.client.query(query2, variables2).then(
  296. data => {
  297. this.log(`Created Customer ${i + 1}:`, data);
  298. return data as Customer;
  299. },
  300. err => this.log(err),
  301. );
  302. }
  303. }
  304. }
  305. async populateAssets(): Promise<Asset[]> {
  306. const fileNames = await fs.readdir(path.join(__dirname, 'assets'));
  307. const filePaths = fileNames
  308. .map(fileName => path.join(__dirname, 'assets', fileName))
  309. // Sorting is needed because readdir order is not determnistic on Windows.
  310. // See https://github.com/nodejs/node/issues/3232
  311. .sort((a, b) => (a > b ? 1 : -1));
  312. return this.client.uploadAssets(filePaths).then(response => {
  313. this.log(`Created ${response.createAssets.length} Assets`);
  314. return response.createAssets;
  315. });
  316. }
  317. async populateProducts(
  318. count: number = 5,
  319. optionGroupId: string,
  320. assets: Asset[],
  321. taxCategories: TaxCategory[],
  322. ): Promise<any> {
  323. for (let i = 0; i < count; i++) {
  324. const query = CREATE_PRODUCT;
  325. const name = faker.commerce.productName();
  326. const slug = name.toLowerCase().replace(/\s+/g, '-');
  327. const description = faker.lorem.sentence();
  328. const languageCodes = [LanguageCode.en, LanguageCode.de];
  329. // get 2 (pseudo) random asset ids
  330. const randomAssets = this.shuffleArray(assets).slice(0, 2);
  331. const variables: CreateProduct.Variables = {
  332. input: {
  333. translations: languageCodes.map(code =>
  334. this.makeProductTranslation(code, name, slug, description),
  335. ),
  336. assetIds: randomAssets.map(a => a.id),
  337. featuredAssetId: randomAssets[0].id,
  338. },
  339. };
  340. const product = await this.client
  341. .query<CreateProduct.Mutation, CreateProduct.Variables>(query, variables)
  342. .then(
  343. data => {
  344. this.log(`Created Product ${i + 1}:`, data.createProduct.name);
  345. return data;
  346. },
  347. err => this.log(err),
  348. );
  349. if (product) {
  350. await this.client.query<AddOptionGroupToProduct.Mutation, AddOptionGroupToProduct.Variables>(
  351. ADD_OPTION_GROUP_TO_PRODUCT,
  352. {
  353. productId: product.createProduct.id,
  354. optionGroupId,
  355. },
  356. );
  357. const prodWithVariants = await this.makeProductVariant(
  358. product.createProduct.id,
  359. taxCategories[0],
  360. );
  361. const variants = prodWithVariants.generateVariantsForProduct.variants;
  362. for (const variant of variants) {
  363. const variantEN = variant.translations[0];
  364. const variantDE = { ...variantEN };
  365. variantDE.languageCode = LanguageCode.de;
  366. variantDE.name = variantDE.name.replace(LanguageCode.en, LanguageCode.de);
  367. delete variantDE.id;
  368. variant.translations.push(variantDE);
  369. }
  370. await this.client.query<UpdateProductVariants.Mutation, UpdateProductVariants.Variables>(
  371. UPDATE_PRODUCT_VARIANTS,
  372. {
  373. input: variants.map(({ id, translations, sku, price }) => ({
  374. id,
  375. translations,
  376. sku,
  377. price,
  378. })),
  379. },
  380. );
  381. }
  382. }
  383. }
  384. async populateFacets() {
  385. await this.client.query<CreateFacet.Mutation, CreateFacet.Variables>(CREATE_FACET, {
  386. input: {
  387. code: 'brand',
  388. translations: [
  389. {
  390. languageCode: LanguageCode.en,
  391. name: 'Brand',
  392. },
  393. {
  394. languageCode: LanguageCode.en,
  395. name: 'Marke',
  396. },
  397. ],
  398. values: this.makeFacetValues(10),
  399. },
  400. });
  401. this.log('Created "brand" Facet');
  402. }
  403. private makeFacetValues(count: number): CreateFacetValueWithFacetInput[] {
  404. return Array.from({ length: count }).map(() => {
  405. const brand = faker.company.companyName();
  406. return {
  407. code: brand.toLowerCase().replace(/[^a-zA-Z]+/g, '-'),
  408. translations: [
  409. {
  410. languageCode: LanguageCode.en,
  411. name: brand,
  412. },
  413. {
  414. languageCode: LanguageCode.de,
  415. name: brand,
  416. },
  417. ],
  418. };
  419. });
  420. }
  421. private makeProductTranslation(
  422. languageCode: LanguageCode,
  423. name: string,
  424. slug: string,
  425. description: string,
  426. ): ProductTranslationInput {
  427. return {
  428. languageCode,
  429. name: `${languageCode} ${name}`,
  430. slug: `${languageCode} ${slug}`,
  431. description: `${languageCode} ${description}`,
  432. };
  433. }
  434. private async makeProductVariant(
  435. productId: string,
  436. taxCategory: TaxCategory,
  437. ): Promise<GenerateProductVariants.Mutation> {
  438. const query = GENERATE_PRODUCT_VARIANTS;
  439. return this.client.query<GenerateProductVariants.Mutation, GenerateProductVariants.Variables>(query, {
  440. productId,
  441. defaultTaxCategoryId: taxCategory.id,
  442. defaultSku: faker.random.alphaNumeric(5),
  443. defaultPrice: faker.random.number({
  444. min: 100,
  445. max: 1000,
  446. }),
  447. });
  448. }
  449. private log(...args: any[]) {
  450. if (this.logging) {
  451. console.log(...args);
  452. }
  453. }
  454. /**
  455. * Deterministacally randomize array element order. Returns a new
  456. * shuffled array and leaves the input array intact.
  457. * Using Durstenfeld shuffle algorithm.
  458. *
  459. * Source: https://stackoverflow.com/a/12646864/772859
  460. */
  461. private shuffleArray<T>(array: T[]): T[] {
  462. const clone = array.slice(0);
  463. for (let i = clone.length - 1; i > 0; i--) {
  464. const j = Math.floor((faker.random.number(1000) / 1000) * (i + 1));
  465. const temp = clone[i];
  466. clone[i] = clone[j];
  467. clone[j] = temp;
  468. }
  469. return clone;
  470. }
  471. }