using Application.Abstractions.Data; using Domain.Entities.Stocks; using Domain.Entities.Stocks.ValueObject; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using SharedKernel; namespace Infrastructure.StockData; /// /// 지수(시장) 일별시세 수집 — KRX OpenAPI (KOSPI/KOSDAQ/KRX 시리즈, AUTH_KEY 헤더). /// 기본 18:30 KST 실행(장 마감 후 확정), basDd=직전 영업일 3개 엔드포인트 전량 수집 → IndexDailyPrice upsert (UQ = Series+IndexName+TradeDate). /// 미반영(0건)이면 2시간 간격 2회 재시도. ApiKey 미설정 시 로그만 남기고 skip (data.go.kr 배치와 동일 정책). /// internal sealed class IndexPriceSyncService( IServiceScopeFactory scopeFactory, IHttpClientFactory httpClientFactory, IOptions settings, ILogger logger ) : DailyScheduledService(logger) { // (계열, 엔드포인트 경로) private static readonly (MarketIndexSeries Series, string Path)[] Endpoints = [ (MarketIndexSeries.KOSPI, "/svc/apis/idx/kospi_dd_trd"), (MarketIndexSeries.KOSDAQ, "/svc/apis/idx/kosdaq_dd_trd"), (MarketIndexSeries.KRX, "/svc/apis/idx/krx_dd_trd") ]; protected override string JobName => "IndexPriceSync"; protected override TimeOnly TargetTime => ParseTime(settings.Value.KRXCoKr.IndexSyncTime, new TimeOnly(18, 30)); protected override int MaxRetryCount => 2; protected override TimeSpan RetryDelay => TimeSpan.FromHours(2); protected override async Task RunOnceAsync(DateOnly todayKst, CancellationToken ct) { var cfg = settings.Value.KRXCoKr; if (string.IsNullOrWhiteSpace(cfg.ApiKey)) { Logger.LogWarning("[{Job}] KRXCoKr:ApiKey 미설정 — 수집 skip", JobName); return true; } using var scope = scopeFactory.CreateScope(); var db = scope.ServiceProvider.GetRequiredService(); var client = httpClientFactory.CreateClient(KrxCoKrHttp.ClientName); var targetDate = await MarketCalendar.GetPreviousBusinessDayAsync(db, todayKst.AddDays(1), ct); var rows = new List(); foreach (var (series, path) in Endpoints) { var url = $"{cfg.BaseUrl.TrimEnd('/')}{path}?basDd={targetDate:yyyyMMdd}"; var json = await KrxCoKrHttp.GetStringWithRetryAsync(client, url, cfg.ApiKey, Logger, ct); var parsed = KrxIndexParser.ParseIndexPrices(json, series); Logger.LogInformation("[{Job}] {Series} basDd={TargetDate} rows={Rows}", JobName, series, targetDate, parsed.Count); rows.AddRange(parsed); } if (rows.Count == 0) { Logger.LogInformation("[{Job}] basDd={TargetDate} 지수 미반영 (0건)", JobName, targetDate); return false; } var existing = await db.IndexDailyPrice.Where(c => c.TradeDate == targetDate).ToListAsync(ct); var existingByKey = existing.ToDictionary(c => (c.Series, c.IndexName)); var inserted = 0; var updated = 0; foreach (var row in rows) { if (existingByKey.TryGetValue((row.Series, row.IndexName), out var price)) { price.Update(row.Close, row.ChangeVal, row.FlucRateBp, row.Open, row.High, row.Low, row.Volume, row.Value, row.MarketCap); updated++; } else { var created = IndexDailyPrice.Create(row.Series, row.IndexName, row.TradeDate, row.Close, row.ChangeVal, row.FlucRateBp, row.Open, row.High, row.Low, row.Volume, row.Value, row.MarketCap); await db.IndexDailyPrice.AddAsync(created, ct); existingByKey[(row.Series, row.IndexName)] = created; inserted++; } } await db.SaveChangesAsync(ct); Logger.LogInformation("[{Job}] 완료 — basDd={TargetDate}, rows={Rows}, inserted={Inserted}, updated={Updated}", JobName, targetDate, rows.Count, inserted, updated); return true; } }