mock-data.service.ts 16 KB

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