POST /sync starts the full synchronization in the background (202, or 409 when one is already running). Entities are synced in dependency order: brands, categories, suppliers, products (with versions and stocks), customers. Each row is synced independently so that a failure is logged without stopping the rest. Replaces the default AppService.
39 lines
1.7 KiB
TypeScript
39 lines
1.7 KiB
TypeScript
import { Injectable, Logger } from '@nestjs/common';
|
|
import { BrandHiboutikRepository } from '../../hiboutik/brand.hiboutik.repository';
|
|
import { BrandDatabaseRepository } from '../../database/brand.database.repository';
|
|
import { BrandConverter } from '../../models/converter/brand.converter';
|
|
import { forEachSafely } from '../../utils/sync';
|
|
|
|
@Injectable()
|
|
export class BrandHiboutikService {
|
|
private readonly logger = new Logger('BrandHiboutikService');
|
|
|
|
constructor(
|
|
private readonly brandHiboutikRepository: BrandHiboutikRepository,
|
|
private readonly brandDatabaseRepository: BrandDatabaseRepository,
|
|
private readonly brandConverter: BrandConverter,
|
|
) {}
|
|
|
|
/** Mirrors Hiboutik brands: upserts each of them, then deletes the brands missing from Hiboutik. */
|
|
async syncBrands() {
|
|
const hiboutikBrands = await this.brandHiboutikRepository.getBrands();
|
|
// One upsert per brand: an invalid brand must not prevent the others from being saved
|
|
const nbFailed = await forEachSafely(
|
|
this.brandConverter.fromHiboutikList(hiboutikBrands),
|
|
(brand) => this.brandDatabaseRepository.upsert(brand),
|
|
this.logger,
|
|
(brand) => `Hiboutik brand ${brand.hiboutikId}`,
|
|
);
|
|
|
|
// Safety net: an empty answer from Hiboutik most likely means an API issue
|
|
if (hiboutikBrands.length === 0) {
|
|
this.logger.warn('Hiboutik returned no brands: deletion skipped.');
|
|
return;
|
|
}
|
|
const nbDeleted = await this.brandDatabaseRepository.deleteMissing(hiboutikBrands.map((dto) => Number(dto.brand_id)));
|
|
this.logger.log(
|
|
`Brands sync ended: ${hiboutikBrands.length - nbFailed}/${hiboutikBrands.length} synced, ${nbFailed} failed, ${nbDeleted} deleted.`,
|
|
);
|
|
}
|
|
}
|