mock-data.service.ts 18 KB

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