indexer.controller.ts 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918
  1. import { Client } from '@elastic/elasticsearch';
  2. import { Inject, Injectable, OnModuleDestroy, OnModuleInit } from '@nestjs/common';
  3. import { unique } from '@vendure/common/lib/unique';
  4. import {
  5. Asset,
  6. asyncObservable,
  7. AsyncQueue,
  8. Channel,
  9. Collection,
  10. ConfigService,
  11. EntityRelationPaths,
  12. FacetValue,
  13. ID,
  14. LanguageCode,
  15. Logger,
  16. Product,
  17. ProductPriceApplicator,
  18. ProductVariant,
  19. ProductVariantService,
  20. RequestContext,
  21. RequestContextCacheService,
  22. TransactionalConnection,
  23. Translatable,
  24. Translation,
  25. } from '@vendure/core';
  26. import { Observable } from 'rxjs';
  27. import { ELASTIC_SEARCH_OPTIONS, loggerCtx, VARIANT_INDEX_NAME } from '../constants';
  28. import { ElasticsearchOptions } from '../options';
  29. import {
  30. BulkOperation,
  31. BulkOperationDoc,
  32. BulkResponseBody,
  33. ProductChannelMessageData,
  34. ProductIndexItem,
  35. ReindexMessageData,
  36. UpdateAssetMessageData,
  37. UpdateProductMessageData,
  38. UpdateVariantMessageData,
  39. UpdateVariantsByIdMessageData,
  40. VariantChannelMessageData,
  41. VariantIndexItem,
  42. } from '../types';
  43. import { createIndices, getClient, getIndexNameByAlias } from './indexing-utils';
  44. export const defaultProductRelations: Array<EntityRelationPaths<Product>> = [
  45. 'variants',
  46. 'featuredAsset',
  47. 'facetValues',
  48. 'facetValues.facet',
  49. 'channels',
  50. 'channels.defaultTaxZone',
  51. ];
  52. export const defaultVariantRelations: Array<EntityRelationPaths<ProductVariant>> = [
  53. 'featuredAsset',
  54. 'facetValues',
  55. 'facetValues.facet',
  56. 'collections',
  57. 'taxCategory',
  58. 'channels',
  59. 'channels.defaultTaxZone',
  60. ];
  61. export interface ReindexMessageResponse {
  62. total: number;
  63. completed: number;
  64. duration: number;
  65. }
  66. type BulkVariantOperation = {
  67. index: typeof VARIANT_INDEX_NAME;
  68. operation: BulkOperation | BulkOperationDoc<VariantIndexItem>;
  69. };
  70. @Injectable()
  71. export class ElasticsearchIndexerController implements OnModuleInit, OnModuleDestroy {
  72. private client: Client;
  73. private asyncQueue = new AsyncQueue('elasticsearch-indexer', 5);
  74. private productRelations: Array<EntityRelationPaths<Product>>;
  75. private variantRelations: Array<EntityRelationPaths<ProductVariant>>;
  76. constructor(
  77. private connection: TransactionalConnection,
  78. @Inject(ELASTIC_SEARCH_OPTIONS) private options: Required<ElasticsearchOptions>,
  79. private productPriceApplicator: ProductPriceApplicator,
  80. private configService: ConfigService,
  81. private productVariantService: ProductVariantService,
  82. private requestContextCache: RequestContextCacheService,
  83. ) {}
  84. onModuleInit(): any {
  85. this.client = getClient(this.options);
  86. this.productRelations = this.getReindexRelationsRelations(
  87. defaultProductRelations,
  88. this.options.hydrateProductRelations,
  89. );
  90. this.variantRelations = this.getReindexRelationsRelations(
  91. defaultVariantRelations,
  92. this.options.hydrateProductVariantRelations,
  93. );
  94. }
  95. onModuleDestroy(): any {
  96. return this.client.close();
  97. }
  98. /**
  99. * Updates the search index only for the affected product.
  100. */
  101. async updateProduct({ ctx: rawContext, productId }: UpdateProductMessageData): Promise<boolean> {
  102. await this.updateProductsInternal([productId]);
  103. return true;
  104. }
  105. /**
  106. * Updates the search index only for the affected product.
  107. */
  108. async deleteProduct({ ctx: rawContext, productId }: UpdateProductMessageData): Promise<boolean> {
  109. const operations = await this.deleteProductOperations(productId);
  110. await this.executeBulkOperations(operations);
  111. return true;
  112. }
  113. /**
  114. * Updates the search index only for the affected product.
  115. */
  116. async assignProductToChannel({
  117. ctx: rawContext,
  118. productId,
  119. channelId,
  120. }: ProductChannelMessageData): Promise<boolean> {
  121. await this.updateProductsInternal([productId]);
  122. return true;
  123. }
  124. /**
  125. * Updates the search index only for the affected product.
  126. */
  127. async removeProductFromChannel({
  128. ctx: rawContext,
  129. productId,
  130. channelId,
  131. }: ProductChannelMessageData): Promise<boolean> {
  132. await this.updateProductsInternal([productId]);
  133. return true;
  134. }
  135. async assignVariantToChannel({
  136. ctx: rawContext,
  137. productVariantId,
  138. channelId,
  139. }: VariantChannelMessageData): Promise<boolean> {
  140. const productIds = await this.getProductIdsByVariantIds([productVariantId]);
  141. await this.updateProductsInternal(productIds);
  142. return true;
  143. }
  144. async removeVariantFromChannel({
  145. ctx: rawContext,
  146. productVariantId,
  147. channelId,
  148. }: VariantChannelMessageData): Promise<boolean> {
  149. const productIds = await this.getProductIdsByVariantIds([productVariantId]);
  150. await this.updateProductsInternal(productIds);
  151. return true;
  152. }
  153. /**
  154. * Updates the search index only for the affected entities.
  155. */
  156. async updateVariants({ ctx: rawContext, variantIds }: UpdateVariantMessageData): Promise<boolean> {
  157. return this.asyncQueue.push(async () => {
  158. const productIds = await this.getProductIdsByVariantIds(variantIds);
  159. await this.updateProductsInternal(productIds);
  160. return true;
  161. });
  162. }
  163. async deleteVariants({ ctx: rawContext, variantIds }: UpdateVariantMessageData): Promise<boolean> {
  164. const productIds = await this.getProductIdsByVariantIds(variantIds);
  165. for (const productId of productIds) {
  166. await this.updateProductsInternal([productId]);
  167. }
  168. return true;
  169. }
  170. updateVariantsById({
  171. ctx: rawContext,
  172. ids,
  173. }: UpdateVariantsByIdMessageData): Observable<ReindexMessageResponse> {
  174. return asyncObservable(async observer => {
  175. return this.asyncQueue.push(async () => {
  176. const timeStart = Date.now();
  177. const productIds = await this.getProductIdsByVariantIds(ids);
  178. if (productIds.length) {
  179. let finishedProductsCount = 0;
  180. for (const productId of productIds) {
  181. await this.updateProductsInternal([productId]);
  182. finishedProductsCount++;
  183. observer.next({
  184. total: productIds.length,
  185. completed: Math.min(finishedProductsCount, productIds.length),
  186. duration: +new Date() - timeStart,
  187. });
  188. }
  189. }
  190. Logger.verbose(`Completed updating variants`, loggerCtx);
  191. return {
  192. total: productIds.length,
  193. completed: productIds.length,
  194. duration: +new Date() - timeStart,
  195. };
  196. });
  197. });
  198. }
  199. reindex({ ctx: rawContext }: ReindexMessageData): Observable<ReindexMessageResponse> {
  200. return asyncObservable(async observer => {
  201. return this.asyncQueue.push(async () => {
  202. const timeStart = Date.now();
  203. const operations: BulkVariantOperation[] = [];
  204. const reindexTempName = new Date().getTime();
  205. const variantIndexName = this.options.indexPrefix + VARIANT_INDEX_NAME;
  206. const reindexVariantAliasName = variantIndexName + `-reindex-${reindexTempName}`;
  207. try {
  208. await createIndices(
  209. this.client,
  210. this.options.indexPrefix,
  211. this.options.indexSettings,
  212. this.options.indexMappingProperties,
  213. true,
  214. `-reindex-${reindexTempName}`,
  215. );
  216. const reindexVariantIndexName = await getIndexNameByAlias(
  217. this.client,
  218. reindexVariantAliasName,
  219. );
  220. const originalVariantAliasExist = await this.client.indices.existsAlias({
  221. name: variantIndexName,
  222. });
  223. const originalVariantIndexExist = await this.client.indices.exists({
  224. index: variantIndexName,
  225. });
  226. const originalVariantIndexName = await getIndexNameByAlias(this.client, variantIndexName);
  227. if (originalVariantAliasExist.body || originalVariantIndexExist.body) {
  228. await this.client.reindex({
  229. refresh: true,
  230. body: {
  231. source: {
  232. index: variantIndexName,
  233. },
  234. dest: {
  235. index: reindexVariantAliasName,
  236. },
  237. },
  238. });
  239. }
  240. const actions = [
  241. {
  242. remove: {
  243. index: reindexVariantIndexName,
  244. alias: reindexVariantAliasName,
  245. },
  246. },
  247. {
  248. add: {
  249. index: reindexVariantIndexName,
  250. alias: variantIndexName,
  251. },
  252. },
  253. ];
  254. if (originalVariantAliasExist.body) {
  255. actions.push({
  256. remove: {
  257. index: originalVariantIndexName,
  258. alias: variantIndexName,
  259. },
  260. });
  261. } else if (originalVariantIndexExist.body) {
  262. await this.client.indices.delete({
  263. index: [variantIndexName],
  264. });
  265. }
  266. await this.client.indices.updateAliases({
  267. body: {
  268. actions,
  269. },
  270. });
  271. if (originalVariantAliasExist.body) {
  272. await this.client.indices.delete({
  273. index: [originalVariantIndexName],
  274. });
  275. }
  276. } catch (e) {
  277. Logger.warn(
  278. `Could not recreate indices. Reindexing continue with existing indices.`,
  279. loggerCtx,
  280. );
  281. Logger.warn(JSON.stringify(e), loggerCtx);
  282. } finally {
  283. const reindexVariantAliasExist = await this.client.indices.existsAlias({
  284. name: reindexVariantAliasName,
  285. });
  286. if (reindexVariantAliasExist.body) {
  287. const reindexVariantAliasResult = await this.client.indices.getAlias({
  288. name: reindexVariantAliasName,
  289. });
  290. const reindexVariantIndexName = Object.keys(reindexVariantAliasResult.body)[0];
  291. await this.client.indices.delete({
  292. index: [reindexVariantIndexName],
  293. });
  294. }
  295. }
  296. const deletedProductIds = await this.connection
  297. .getRepository(Product)
  298. .createQueryBuilder('product')
  299. .select('product.id')
  300. .where('product.deletedAt IS NOT NULL')
  301. .getMany();
  302. for (const { id: deletedProductId } of deletedProductIds) {
  303. operations.push(...(await this.deleteProductOperations(deletedProductId)));
  304. }
  305. const productIds = await this.connection
  306. .getRepository(Product)
  307. .createQueryBuilder('product')
  308. .select('product.id')
  309. .where('product.deletedAt IS NULL')
  310. .getMany();
  311. Logger.verbose(`Reindexing ${productIds.length} Products`, loggerCtx);
  312. let finishedProductsCount = 0;
  313. for (const { id: productId } of productIds) {
  314. operations.push(...(await this.updateProductsOperations([productId])));
  315. finishedProductsCount++;
  316. observer.next({
  317. total: productIds.length,
  318. completed: Math.min(finishedProductsCount, productIds.length),
  319. duration: +new Date() - timeStart,
  320. });
  321. }
  322. Logger.verbose(`Will execute ${operations.length} bulk update operations`, loggerCtx);
  323. await this.executeBulkOperations(operations);
  324. Logger.verbose(`Completed reindexing!`, loggerCtx);
  325. return {
  326. total: productIds.length,
  327. completed: productIds.length,
  328. duration: +new Date() - timeStart,
  329. };
  330. });
  331. });
  332. }
  333. async updateAsset(data: UpdateAssetMessageData): Promise<boolean> {
  334. const result = await this.updateAssetFocalPointForIndex(VARIANT_INDEX_NAME, data.asset);
  335. await this.client.indices.refresh({
  336. index: [this.options.indexPrefix + VARIANT_INDEX_NAME],
  337. });
  338. return result;
  339. }
  340. async deleteAsset(data: UpdateAssetMessageData): Promise<boolean> {
  341. const result = await this.deleteAssetForIndex(VARIANT_INDEX_NAME, data.asset);
  342. await this.client.indices.refresh({
  343. index: [this.options.indexPrefix + VARIANT_INDEX_NAME],
  344. });
  345. return result;
  346. }
  347. private async updateAssetFocalPointForIndex(indexName: string, asset: Asset): Promise<boolean> {
  348. const focalPoint = asset.focalPoint || null;
  349. const params = { focalPoint };
  350. return this.updateAssetForIndex(
  351. indexName,
  352. asset,
  353. {
  354. source: 'ctx._source.productPreviewFocalPoint = params.focalPoint',
  355. params,
  356. },
  357. {
  358. source: 'ctx._source.productVariantPreviewFocalPoint = params.focalPoint',
  359. params,
  360. },
  361. );
  362. }
  363. private async deleteAssetForIndex(indexName: string, asset: Asset): Promise<boolean> {
  364. return this.updateAssetForIndex(
  365. indexName,
  366. asset,
  367. { source: 'ctx._source.productAssetId = null' },
  368. { source: 'ctx._source.productVariantAssetId = null' },
  369. );
  370. }
  371. private async updateAssetForIndex(
  372. indexName: string,
  373. asset: Asset,
  374. updateProductScript: { source: string; params?: any },
  375. updateVariantScript: { source: string; params?: any },
  376. ): Promise<boolean> {
  377. const result1 = await this.client.update_by_query({
  378. index: this.options.indexPrefix + indexName,
  379. body: {
  380. script: updateProductScript,
  381. query: {
  382. term: {
  383. productAssetId: asset.id,
  384. },
  385. },
  386. },
  387. });
  388. for (const failure of result1.body.failures) {
  389. Logger.error(`${failure.cause.type}: ${failure.cause.reason}`, loggerCtx);
  390. }
  391. const result2 = await this.client.update_by_query({
  392. index: this.options.indexPrefix + indexName,
  393. body: {
  394. script: updateVariantScript,
  395. query: {
  396. term: {
  397. productVariantAssetId: asset.id,
  398. },
  399. },
  400. },
  401. });
  402. for (const failure of result1.body.failures) {
  403. Logger.error(`${failure.cause.type}: ${failure.cause.reason}`, loggerCtx);
  404. }
  405. return result1.body.failures.length === 0 && result2.body.failures === 0;
  406. }
  407. private async updateProductsInternal(productIds: ID[]) {
  408. const operations = await this.updateProductsOperations(productIds);
  409. await this.executeBulkOperations(operations);
  410. }
  411. private async updateProductsOperations(productIds: ID[]): Promise<BulkVariantOperation[]> {
  412. Logger.verbose(`Updating ${productIds.length} Products`, loggerCtx);
  413. const operations: BulkVariantOperation[] = [];
  414. for (const productId of productIds) {
  415. operations.push(...(await this.deleteProductOperations(productId)));
  416. let product: Product | undefined;
  417. try {
  418. product = await this.connection.getRepository(Product).findOne(productId, {
  419. relations: this.productRelations,
  420. where: {
  421. deletedAt: null,
  422. },
  423. });
  424. } catch (e) {
  425. Logger.error(e.message, loggerCtx, e.stack);
  426. throw e;
  427. }
  428. if (product) {
  429. const updatedProductVariants = await this.connection.getRepository(ProductVariant).findByIds(
  430. product.variants.map(v => v.id),
  431. {
  432. relations: this.variantRelations,
  433. where: {
  434. deletedAt: null,
  435. },
  436. order: {
  437. id: 'ASC',
  438. },
  439. },
  440. );
  441. // tslint:disable-next-line:no-non-null-assertion
  442. updatedProductVariants.forEach(variant => (variant.product = product!));
  443. if (!product.enabled) {
  444. updatedProductVariants.forEach(v => (v.enabled = false));
  445. }
  446. Logger.verbose(`Updating Product (${productId})`, loggerCtx);
  447. const languageVariants: LanguageCode[] = [];
  448. languageVariants.push(...product.translations.map(t => t.languageCode));
  449. for (const variant of product.variants) {
  450. languageVariants.push(...variant.translations.map(t => t.languageCode));
  451. }
  452. const uniqueLanguageVariants = unique(languageVariants);
  453. for (const channel of product.channels) {
  454. const channelCtx = new RequestContext({
  455. channel,
  456. apiType: 'admin',
  457. authorizedAsOwnerOnly: false,
  458. isAuthorized: true,
  459. session: {} as any,
  460. });
  461. const variantsInChannel = updatedProductVariants.filter(v =>
  462. v.channels.map(c => c.id).includes(channelCtx.channelId),
  463. );
  464. for (const variant of variantsInChannel) {
  465. await this.productPriceApplicator.applyChannelPriceAndTax(variant, channelCtx);
  466. }
  467. for (const languageCode of uniqueLanguageVariants) {
  468. if (variantsInChannel.length) {
  469. for (const variant of variantsInChannel) {
  470. operations.push(
  471. {
  472. index: VARIANT_INDEX_NAME,
  473. operation: {
  474. update: {
  475. _id: ElasticsearchIndexerController.getId(
  476. variant.id,
  477. channelCtx.channelId,
  478. languageCode,
  479. ),
  480. },
  481. },
  482. },
  483. {
  484. index: VARIANT_INDEX_NAME,
  485. operation: {
  486. doc: await this.createVariantIndexItem(
  487. variant,
  488. variantsInChannel,
  489. channelCtx,
  490. languageCode,
  491. ),
  492. doc_as_upsert: true,
  493. },
  494. },
  495. );
  496. }
  497. } else {
  498. operations.push(
  499. {
  500. index: VARIANT_INDEX_NAME,
  501. operation: {
  502. update: {
  503. _id: ElasticsearchIndexerController.getId(
  504. -product.id,
  505. channelCtx.channelId,
  506. languageCode,
  507. ),
  508. },
  509. },
  510. },
  511. {
  512. index: VARIANT_INDEX_NAME,
  513. operation: {
  514. doc: this.createSyntheticProductIndexItem(
  515. product,
  516. channelCtx,
  517. languageCode,
  518. ),
  519. doc_as_upsert: true,
  520. },
  521. },
  522. );
  523. }
  524. }
  525. }
  526. }
  527. }
  528. return operations;
  529. }
  530. /**
  531. * Takes the default relations, and combines them with any extra relations specified in the
  532. * `hydrateProductRelations` and `hydrateProductVariantRelations`. This method also ensures
  533. * that the relation values are unique and that paths are fully expanded.
  534. *
  535. * This means that if a `hydrateProductRelations` value of `['assets.asset']` is specified,
  536. * this method will also add `['assets']` to the relations array, otherwise TypeORM would
  537. * throw an error trying to join a 2nd-level deep relation without the first level also
  538. * being joined.
  539. */
  540. private getReindexRelationsRelations<T extends Product | ProductVariant>(
  541. defaultRelations: Array<EntityRelationPaths<T>>,
  542. hydratedRelations: Array<EntityRelationPaths<T>>,
  543. ): Array<EntityRelationPaths<T>> {
  544. const uniqueRelations = unique([...defaultRelations, ...hydratedRelations]);
  545. for (const relation of hydratedRelations) {
  546. const path = relation.split('.');
  547. const pathToPart: string[] = [];
  548. for (const part of path) {
  549. pathToPart.push(part);
  550. const joinedPath = pathToPart.join('.') as EntityRelationPaths<T>;
  551. if (!uniqueRelations.includes(joinedPath)) {
  552. uniqueRelations.push(joinedPath);
  553. }
  554. }
  555. }
  556. return uniqueRelations;
  557. }
  558. private async deleteProductOperations(productId: ID): Promise<BulkVariantOperation[]> {
  559. const channels = await this.connection
  560. .getRepository(Channel)
  561. .createQueryBuilder('channel')
  562. .select('channel.id')
  563. .getMany();
  564. const product = await this.connection.getRepository(Product).findOne(productId, {
  565. relations: ['variants'],
  566. });
  567. if (!product) {
  568. return [];
  569. }
  570. Logger.verbose(`Deleting 1 Product (id: ${productId})`, loggerCtx);
  571. const operations: BulkVariantOperation[] = [];
  572. const languageVariants: LanguageCode[] = [];
  573. languageVariants.push(...product.translations.map(t => t.languageCode));
  574. for (const variant of product.variants) {
  575. languageVariants.push(...variant.translations.map(t => t.languageCode));
  576. }
  577. const uniqueLanguageVariants = unique(languageVariants);
  578. for (const { id: channelId } of channels) {
  579. for (const languageCode of uniqueLanguageVariants) {
  580. operations.push({
  581. index: VARIANT_INDEX_NAME,
  582. operation: {
  583. delete: {
  584. _id: ElasticsearchIndexerController.getId(-product.id, channelId, languageCode),
  585. },
  586. },
  587. });
  588. }
  589. }
  590. operations.push(
  591. ...(await this.deleteVariantsInternalOperations(
  592. product.variants,
  593. channels.map(c => c.id),
  594. uniqueLanguageVariants,
  595. )),
  596. );
  597. return operations;
  598. }
  599. private async deleteVariantsInternalOperations(
  600. variants: ProductVariant[],
  601. channelIds: ID[],
  602. languageVariants: LanguageCode[],
  603. ): Promise<BulkVariantOperation[]> {
  604. Logger.verbose(`Deleting ${variants.length} ProductVariants`, loggerCtx);
  605. const operations: BulkVariantOperation[] = [];
  606. for (const variant of variants) {
  607. for (const channelId of channelIds) {
  608. for (const languageCode of languageVariants) {
  609. operations.push({
  610. index: VARIANT_INDEX_NAME,
  611. operation: {
  612. delete: {
  613. _id: ElasticsearchIndexerController.getId(
  614. variant.id,
  615. channelId,
  616. languageCode,
  617. ),
  618. },
  619. },
  620. });
  621. }
  622. }
  623. }
  624. return operations;
  625. }
  626. private async getProductIdsByVariantIds(variantIds: ID[]): Promise<ID[]> {
  627. const variants = await this.connection.getRepository(ProductVariant).findByIds(variantIds, {
  628. relations: ['product'],
  629. loadEagerRelations: false,
  630. });
  631. return unique(variants.map(v => v.product.id));
  632. }
  633. private async executeBulkOperations(operations: BulkVariantOperation[]) {
  634. const variantOperations: Array<BulkOperation | BulkOperationDoc<VariantIndexItem>> = [];
  635. for (const operation of operations) {
  636. variantOperations.push(operation.operation);
  637. }
  638. return Promise.all([this.runBulkOperationsOnIndex(VARIANT_INDEX_NAME, variantOperations)]);
  639. }
  640. private async runBulkOperationsOnIndex(
  641. indexName: string,
  642. operations: Array<BulkOperation | BulkOperationDoc<VariantIndexItem | ProductIndexItem>>,
  643. ) {
  644. if (operations.length === 0) {
  645. return;
  646. }
  647. try {
  648. const fullIndexName = this.options.indexPrefix + indexName;
  649. const { body }: { body: BulkResponseBody } = await this.client.bulk({
  650. refresh: true,
  651. index: fullIndexName,
  652. body: operations,
  653. });
  654. if (body.errors) {
  655. Logger.error(
  656. `Some errors occurred running bulk operations on ${fullIndexName}! Set logger to "debug" to print all errors.`,
  657. loggerCtx,
  658. );
  659. body.items.forEach(item => {
  660. if (item.index) {
  661. Logger.debug(JSON.stringify(item.index.error, null, 2), loggerCtx);
  662. }
  663. if (item.update) {
  664. Logger.debug(JSON.stringify(item.update.error, null, 2), loggerCtx);
  665. }
  666. if (item.delete) {
  667. Logger.debug(JSON.stringify(item.delete.error, null, 2), loggerCtx);
  668. }
  669. });
  670. } else {
  671. Logger.debug(
  672. `Executed ${body.items.length} bulk operations on index [${fullIndexName}]`,
  673. loggerCtx,
  674. );
  675. }
  676. return body;
  677. } catch (e) {
  678. Logger.error(`Error when attempting to run bulk operations [${e.toString()}]`, loggerCtx);
  679. Logger.error('Error details: ' + JSON.stringify(e.body?.error, null, 2), loggerCtx);
  680. }
  681. }
  682. private async createVariantIndexItem(
  683. v: ProductVariant,
  684. variants: ProductVariant[],
  685. ctx: RequestContext,
  686. languageCode: LanguageCode,
  687. ): Promise<VariantIndexItem> {
  688. try {
  689. const productAsset = v.product.featuredAsset;
  690. const variantAsset = v.featuredAsset;
  691. const productTranslation = this.getTranslation(v.product, languageCode);
  692. const variantTranslation = this.getTranslation(v, languageCode);
  693. const collectionTranslations = v.collections.map(c => this.getTranslation(c, languageCode));
  694. const productCollectionTranslations = variants.reduce(
  695. (translations, variant) => [
  696. ...translations,
  697. ...variant.collections.map(c => this.getTranslation(c, languageCode)),
  698. ],
  699. [] as Array<Translation<Collection>>,
  700. );
  701. const prices = variants.map(variant => variant.price);
  702. const pricesWithTax = variants.map(variant => variant.priceWithTax);
  703. const item: VariantIndexItem = {
  704. channelId: ctx.channelId,
  705. languageCode,
  706. productVariantId: v.id,
  707. sku: v.sku,
  708. slug: productTranslation.slug,
  709. productId: v.product.id,
  710. productName: productTranslation.name,
  711. productAssetId: productAsset ? productAsset.id : undefined,
  712. productPreview: productAsset ? productAsset.preview : '',
  713. productPreviewFocalPoint: productAsset ? productAsset.focalPoint || undefined : undefined,
  714. productVariantName: variantTranslation.name,
  715. productVariantAssetId: variantAsset ? variantAsset.id : undefined,
  716. productVariantPreview: variantAsset ? variantAsset.preview : '',
  717. productVariantPreviewFocalPoint: variantAsset
  718. ? variantAsset.focalPoint || undefined
  719. : undefined,
  720. price: v.price,
  721. priceWithTax: v.priceWithTax,
  722. currencyCode: v.currencyCode,
  723. description: productTranslation.description,
  724. facetIds: this.getFacetIds([v]),
  725. channelIds: v.channels.map(c => c.id),
  726. facetValueIds: this.getFacetValueIds([v]),
  727. collectionIds: v.collections.map(c => c.id.toString()),
  728. collectionSlugs: collectionTranslations.map(c => c.slug),
  729. enabled: v.enabled && v.product.enabled,
  730. productEnabled: variants.some(variant => variant.enabled) && v.product.enabled,
  731. productPriceMin: Math.min(...prices),
  732. productPriceMax: Math.max(...prices),
  733. productPriceWithTaxMin: Math.min(...pricesWithTax),
  734. productPriceWithTaxMax: Math.max(...pricesWithTax),
  735. productFacetIds: this.getFacetIds(variants),
  736. productFacetValueIds: this.getFacetValueIds(variants),
  737. productCollectionIds: unique(
  738. variants.reduce(
  739. (ids, variant) => [...ids, ...variant.collections.map(c => c.id)],
  740. [] as ID[],
  741. ),
  742. ),
  743. productCollectionSlugs: unique(productCollectionTranslations.map(c => c.slug)),
  744. productChannelIds: v.product.channels.map(c => c.id),
  745. inStock: 0 < (await this.productVariantService.getSaleableStockLevel(ctx, v)),
  746. productInStock: await this.getProductInStockValue(ctx, variants),
  747. };
  748. const variantCustomMappings = Object.entries(this.options.customProductVariantMappings);
  749. for (const [name, def] of variantCustomMappings) {
  750. item[`variant-${name}`] = def.valueFn(v, languageCode);
  751. }
  752. const productCustomMappings = Object.entries(this.options.customProductMappings);
  753. for (const [name, def] of productCustomMappings) {
  754. item[`product-${name}`] = def.valueFn(v.product, variants, languageCode);
  755. }
  756. return item;
  757. } catch (err) {
  758. Logger.error(err.toString());
  759. throw Error(`Error while reindexing!`);
  760. }
  761. }
  762. private async getProductInStockValue(ctx: RequestContext, variants: ProductVariant[]): Promise<boolean> {
  763. const stockLevels = await Promise.all(
  764. variants.map(variant => this.productVariantService.getSaleableStockLevel(ctx, variant)),
  765. );
  766. return stockLevels.some(stockLevel => 0 < stockLevel);
  767. }
  768. /**
  769. * If a Product has no variants, we create a synthetic variant for the purposes
  770. * of making that product visible via the search query.
  771. */
  772. private createSyntheticProductIndexItem(
  773. product: Product,
  774. ctx: RequestContext,
  775. languageCode: LanguageCode,
  776. ): VariantIndexItem {
  777. const productTranslation = this.getTranslation(product, languageCode);
  778. const productAsset = product.featuredAsset;
  779. const item: VariantIndexItem = {
  780. channelId: ctx.channelId,
  781. languageCode,
  782. productVariantId: 0,
  783. sku: '',
  784. slug: productTranslation.slug,
  785. productId: product.id,
  786. productName: productTranslation.name,
  787. productAssetId: productAsset ? productAsset.id : undefined,
  788. productPreview: productAsset ? productAsset.preview : '',
  789. productPreviewFocalPoint: productAsset ? productAsset.focalPoint || undefined : undefined,
  790. productVariantName: productTranslation.name,
  791. productVariantAssetId: undefined,
  792. productVariantPreview: '',
  793. productVariantPreviewFocalPoint: undefined,
  794. price: 0,
  795. priceWithTax: 0,
  796. currencyCode: ctx.channel.currencyCode,
  797. description: productTranslation.description,
  798. facetIds: product.facetValues?.map(fv => fv.facet.id.toString()) ?? [],
  799. channelIds: [ctx.channelId],
  800. facetValueIds: product.facetValues?.map(fv => fv.id.toString()) ?? [],
  801. collectionIds: [],
  802. collectionSlugs: [],
  803. enabled: false,
  804. productEnabled: false,
  805. productPriceMin: 0,
  806. productPriceMax: 0,
  807. productPriceWithTaxMin: 0,
  808. productPriceWithTaxMax: 0,
  809. productFacetIds: product.facetValues?.map(fv => fv.facet.id.toString()) ?? [],
  810. productFacetValueIds: product.facetValues?.map(fv => fv.id.toString()) ?? [],
  811. productCollectionIds: [],
  812. productCollectionSlugs: [],
  813. productChannelIds: product.channels.map(c => c.id),
  814. inStock: false,
  815. productInStock: false,
  816. };
  817. const productCustomMappings = Object.entries(this.options.customProductMappings);
  818. for (const [name, def] of productCustomMappings) {
  819. item[`product-${name}`] = def.valueFn(product, [], languageCode);
  820. }
  821. return item;
  822. }
  823. private getTranslation<T extends Translatable>(
  824. translatable: T,
  825. languageCode: LanguageCode,
  826. ): Translation<T> {
  827. return (translatable.translations.find(t => t.languageCode === languageCode) ||
  828. translatable.translations.find(t => t.languageCode === this.configService.defaultLanguageCode) ||
  829. translatable.translations[0]) as unknown as Translation<T>;
  830. }
  831. private getFacetIds(variants: ProductVariant[]): string[] {
  832. const facetIds = (fv: FacetValue) => fv.facet.id.toString();
  833. const variantFacetIds = variants.reduce(
  834. (ids, v) => [...ids, ...v.facetValues.map(facetIds)],
  835. [] as string[],
  836. );
  837. const productFacetIds = variants[0].product.facetValues.map(facetIds);
  838. return unique([...variantFacetIds, ...productFacetIds]);
  839. }
  840. private getFacetValueIds(variants: ProductVariant[]): string[] {
  841. const facetValueIds = (fv: FacetValue) => fv.id.toString();
  842. const variantFacetValueIds = variants.reduce(
  843. (ids, v) => [...ids, ...v.facetValues.map(facetValueIds)],
  844. [] as string[],
  845. );
  846. const productFacetValueIds = variants[0].product.facetValues.map(facetValueIds);
  847. return unique([...variantFacetValueIds, ...productFacetValueIds]);
  848. }
  849. private static getId(entityId: ID, channelId: ID, languageCode: LanguageCode): string {
  850. return `${channelId.toString()}_${entityId.toString()}_${languageCode}`;
  851. }
  852. }