mock-data.service.ts 14 KB

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