import { WebBidsService } from '@/modules/bids/services/web-bids.service'; import AppResponse from '@/response/app-response'; import { BadRequestException, Injectable } from '@nestjs/common'; import { InjectRepository } from '@nestjs/typeorm'; import { paginate, PaginateQuery } from 'nestjs-paginate'; import { Repository } from 'typeorm'; import { ScrapItem } from '../entities/scrap-item.entity'; @Injectable() export class ScrapItemsService { constructor( @InjectRepository(ScrapItem) readonly scrapItemRepo: Repository, private readonly webService: WebBidsService, ) {} async upsertScrapItems(items: ScrapItem[]) { if (!items.length) return { inserted: 0, updated: 0 }; // Lấy keys để query bản ghi đã tồn tại const keys = items.map((d) => ({ model: d.model, scrap_config_id: d.scrap_config_id, })); // Tìm các bản ghi đã có trong DB const existingItems = await this.scrapItemRepo.findBy(keys); const toUpdate = []; const toInsert = []; items.forEach((itemData) => { const exist = existingItems.find( (e) => e.model === itemData.model && e.scrap_config_id === itemData.scrap_config_id, ); if (exist) { toUpdate.push({ ...exist, ...itemData, updated_at: new Date(), }); } else { toInsert.push(itemData); } }); // Thực hiện insert if (toInsert.length) { await this.scrapItemRepo.insert(toInsert); } // Thực hiện update if (toUpdate.length) { await this.scrapItemRepo.save(toUpdate); } return { inserted: toInsert.length, updated: toUpdate.length, }; } async upsertScrapItemsRes(items: ScrapItem[]) { const rs = await this.upsertScrapItems(items); if (!rs) throw new BadRequestException(AppResponse.toResponse(null)); return AppResponse.toResponse(rs); } async index(query: PaginateQuery) { const { data, meta } = await paginate(query, this.scrapItemRepo, { sortableColumns: ['id'], searchableColumns: ['id'], defaultLimit: 15, filterableColumns: { 'scrap_config.web_bid.origin_url': true, }, defaultSortBy: [['updated_at', 'DESC']], maxLimit: 100, relations: { scrap_config: { web_bid: true } }, }); const sources = await this.webService.webBidRepo.find({ select: { origin_url: true }, }); const newData = data.map(({ scrap_config, ...item }) => { return { ...item, source: scrap_config.web_bid.origin_url, }; }); return AppResponse.toPaginationAny({ data: newData, meta, bonus: { sources: sources.map((item) => item.origin_url), }, }); } }