mock-data.service.ts 14 KB

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