All files / src/domains/mdm/application/services global-reference.service.ts

0% Statements 0/87
0% Branches 0/57
0% Functions 0/17
0% Lines 0/72

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232                                                                                                                                                                                                                                                                                                                                                                                                                                                                               
import { Injectable, Logger, NotFoundException } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { Model } from 'mongoose';
import { Country } from '../../infrastructure/schemas/global-reference.schema';
import { AdministrativeRegion } from '../../infrastructure/schemas/global-reference.schema';
import { City } from '../../infrastructure/schemas/global-reference.schema';
import { PostalRegion } from '../../infrastructure/schemas/global-reference.schema';
import { TimezoneDefinition } from '../../infrastructure/schemas/global-reference.schema';
import { CacheService } from '../../../../platform/cache/cache.service';
 
@Injectable()
export class GlobalReferenceService {
  private readonly logger = new Logger(GlobalReferenceService.name);
 
  constructor(
    @InjectModel(Country.name) private readonly countryModel: Model<Country>,
    @InjectModel(AdministrativeRegion.name)
    private readonly regionModel: Model<AdministrativeRegion>,
    @InjectModel(City.name) private readonly cityModel: Model<City>,
    @InjectModel(PostalRegion.name)
    private readonly postalModel: Model<PostalRegion>,
    @InjectModel(TimezoneDefinition.name)
    private readonly tzModel: Model<TimezoneDefinition>,
    private readonly cache: CacheService,
  ) {}
 
  // ════════ COUNTRIES ════════
 
  async listCountries(filters?: {
    continent?: string;
    search?: string;
    active?: boolean;
  }): Promise<any[]> {
    const cacheKey = `mdm:countries:${JSON.stringify(filters || {})}`;
    const cached = await this.cache.get<any[]>(cacheKey);
    if (cached) return cached;
 
    const query: any = { active: filters?.active ?? true };
    if (filters?.continent) query.continent = filters.continent;
    if (filters?.search) {
      query.$or = [
        { countryName: { $regex: filters.search, $options: 'i' } },
        { isoAlpha2: { $regex: filters.search, $options: 'i' } },
        { isoAlpha3: { $regex: filters.search, $options: 'i' } },
      ];
    }
 
    const countries = await this.countryModel
      .find(query)
      .sort({ countryName: 1 })
      .lean()
      .exec();
    await this.cache.set(cacheKey, countries, 3600); // 1 hour
    return countries;
  }
 
  async getCountryByCode(code: string): Promise<any> {
    const cacheKey = `mdm:country:${code.toUpperCase()}`;
    const cached = await this.cache.get<any>(cacheKey);
    if (cached) return cached;
 
    const country = await this.countryModel
      .findOne({
        $or: [
          { isoAlpha2: code.toUpperCase() },
          { isoAlpha3: code.toUpperCase() },
        ],
      })
      .lean()
      .exec();
 
    if (!country) throw new NotFoundException(`Country not found: ${code}`);
    await this.cache.set(cacheKey, country, 3600);
    return country;
  }
 
  async bulkUpsertCountries(
    countries: any[],
  ): Promise<{ upserted: number; modified: number }> {
    const ops = countries.map((c) => ({
      updateOne: {
        filter: { isoAlpha2: c.isoAlpha2 },
        update: { $set: c, $setOnInsert: { systemManaged: true } },
        upsert: true,
      },
    }));
    const result = await this.countryModel.bulkWrite(ops, { ordered: false });
    return { upserted: result.upsertedCount, modified: result.modifiedCount };
  }
 
  // ════════ ADMINISTRATIVE REGIONS ════════
 
  async listRegions(
    countryCode: string,
    filters?: { regionType?: string; search?: string },
  ): Promise<any[]> {
    const query: any = { countryCode: countryCode.toUpperCase(), active: true };
    if (filters?.regionType) query.regionType = filters.regionType;
    if (filters?.search) {
      query.$or = [
        { regionName: { $regex: filters.search, $options: 'i' } },
        { regionCode: { $regex: filters.search, $options: 'i' } },
      ];
    }
 
    return this.regionModel.find(query).sort({ regionName: 1 }).lean().exec();
  }
 
  async getRegionByCode(countryCode: string, regionCode: string): Promise<any> {
    const region = await this.regionModel
      .findOne({
        countryCode: countryCode.toUpperCase(),
        regionCode,
      })
      .lean()
      .exec();
    if (!region)
      throw new NotFoundException(
        `Region not found: ${countryCode}/${regionCode}`,
      );
    return region;
  }
 
  async bulkUpsertRegions(
    regions: any[],
  ): Promise<{ upserted: number; modified: number }> {
    const ops = regions.map((r) => ({
      updateOne: {
        filter: { countryCode: r.countryCode, regionCode: r.regionCode },
        update: { $set: r },
        upsert: true,
      },
    }));
    const result = await this.regionModel.bulkWrite(ops, { ordered: false });
    return { upserted: result.upsertedCount, modified: result.modifiedCount };
  }
 
  // ════════ CITIES ════════
 
  async listCities(
    countryCode: string,
    regionCode?: string,
    search?: string,
    limit = 100,
  ): Promise<any[]> {
    const query: any = { countryCode: countryCode.toUpperCase(), active: true };
    if (regionCode) query.regionCode = regionCode;
    if (search) {
      query.cityName = { $regex: search, $options: 'i' };
    }
 
    return this.cityModel
      .find(query)
      .sort({ cityName: 1 })
      .limit(limit)
      .lean()
      .exec();
  }
 
  async bulkUpsertCities(
    cities: any[],
  ): Promise<{ upserted: number; modified: number }> {
    const ops = cities.map((c) => ({
      updateOne: {
        filter: { countryCode: c.countryCode, cityCode: c.cityCode },
        update: { $set: c },
        upsert: true,
      },
    }));
    const result = await this.cityModel.bulkWrite(ops, { ordered: false });
    return { upserted: result.upsertedCount, modified: result.modifiedCount };
  }
 
  // ════════ POSTAL REGIONS ════════
 
  async lookupPostalCode(
    countryCode: string,
    postalCode: string,
  ): Promise<any> {
    return this.postalModel
      .findOne({
        countryCode: countryCode.toUpperCase(),
        postalCode,
        active: true,
      })
      .lean()
      .exec();
  }
 
  // ════════ TIMEZONES ════════
 
  async listTimezones(countryCode?: string): Promise<any[]> {
    const cacheKey = `mdm:timezones:${countryCode || 'all'}`;
    const cached = await this.cache.get<any[]>(cacheKey);
    if (cached) return cached;
 
    const query: any = { active: true };
    if (countryCode) query.countryCodes = countryCode.toUpperCase();
 
    const timezones = await this.tzModel
      .find(query)
      .sort({ utcOffsetMinutes: 1, displayName: 1 })
      .lean()
      .exec();
    await this.cache.set(cacheKey, timezones, 3600);
    return timezones;
  }
 
  async getTimezone(tzCode: string): Promise<any> {
    const tz = await this.tzModel
      .findOne({ tzCode, active: true })
      .lean()
      .exec();
    if (!tz) throw new NotFoundException(`Timezone not found: ${tzCode}`);
    return tz;
  }
 
  async bulkUpsertTimezones(
    timezones: any[],
  ): Promise<{ upserted: number; modified: number }> {
    const ops = timezones.map((t) => ({
      updateOne: {
        filter: { tzCode: t.tzCode },
        update: { $set: t },
        upsert: true,
      },
    }));
    const result = await this.tzModel.bulkWrite(ops, { ordered: false });
    return { upserted: result.upsertedCount, modified: result.modifiedCount };
  }
}