mock-data.service.ts 18 KB

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