GlobalController.cs 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248
  1. using Microsoft.AspNetCore.Mvc;
  2. using Microsoft.AspNetCore.Mvc.Filters;
  3. using Microsoft.AspNetCore.WebUtilities;
  4. using Microsoft.Extensions.Caching.Memory;
  5. using System.Globalization;
  6. using economy.Helpers;
  7. using economy.Models;
  8. using economy.Models.Financial;
  9. using economy.Models.Price.Global;
  10. using NaturalGas = economy.Models.Price.Global.NaturalGas;
  11. using Commodity = economy.Models.Price.Global.Commodity;
  12. namespace economy.Controllers.Price.Global
  13. {
  14. public class GlobalController : Controller
  15. {
  16. private readonly Alpha_API _alphaAPI;
  17. private readonly KoreaEximGoKR _koreaEximGoKR;
  18. private readonly IMemoryCache _cache;
  19. private readonly EconomyContext _context;
  20. private Dictionary<string, string> _queryString;
  21. // 커모디티 화이트리스트 (Alpha Vantage 함수, 화면 제목, 원화 표시 여부)
  22. private static readonly Dictionary<string, (string Function, string Title, bool HasKrw)> CommodityMap = new(StringComparer.OrdinalIgnoreCase)
  23. {
  24. ["copper"] = ("COPPER", "구리 시세", true),
  25. ["aluminum"] = ("ALUMINUM", "알루미늄 시세", true),
  26. ["wheat"] = ("WHEAT", "밀 시세", true),
  27. ["cotton"] = ("COTTON", "섬유(면화) 시세", true),
  28. ["sugar"] = ("SUGAR", "설탕 시세", true),
  29. ["coffee"] = ("COFFEE", "커피 시세", true),
  30. ["allcommodities"] = ("ALL_COMMODITIES", "원자재 종합지수", false), // 지수(2016=100)라 원화 환산 없음
  31. };
  32. public GlobalController(Alpha_API alphaAPI, KoreaEximGoKR koreaEximGoKR, IMemoryCache cache, EconomyContext context)
  33. {
  34. _alphaAPI = alphaAPI;
  35. _koreaEximGoKR = koreaEximGoKR;
  36. _cache = cache;
  37. _context = context;
  38. _queryString = [];
  39. }
  40. public override void OnActionExecuting(ActionExecutingContext context)
  41. {
  42. _queryString = QueryHelpers.ParseQuery(HttpContext.Request.QueryString.Value).ToDictionary(k => k.Key, v => string.Join(",", v.Value));
  43. ViewBag.QueryString = _queryString;
  44. base.OnActionExecuting(context);
  45. }
  46. // 환율 조회 (1시간 캐시 — 실패값 0은 캐시하지 않음)
  47. private async Task<int> GetExchangeValueAsync()
  48. {
  49. if (_cache.TryGetValue("ExchangeValue_USD", out int cachedValue))
  50. {
  51. return cachedValue;
  52. }
  53. // 환율 API가 느리거나 장애일 때 시세 페이지까지 지연되지 않도록 최대 3초만 대기 (실패 시 원화 미표시)
  54. var exchangeTask = new FinancialModel(_koreaEximGoKR).GetExchangeValue();
  55. var completedTask = await Task.WhenAny(exchangeTask, Task.Delay(TimeSpan.FromSeconds(3)));
  56. int exchangeValue = (completedTask == exchangeTask) ? await exchangeTask : 0;
  57. if (exchangeValue > 0)
  58. {
  59. _cache.Set("ExchangeValue_USD", exchangeValue, TimeSpan.FromHours(1));
  60. }
  61. else
  62. {
  63. // 환율 API 장애 중 매 요청마다 3초씩 대기하지 않도록 실패값은 5분간만 유지
  64. _cache.Set("ExchangeValue_USD", 0, TimeSpan.FromMinutes(5));
  65. }
  66. return exchangeValue;
  67. }
  68. // 국제 시세 응답을 차트 데이터로 변환 (최신 60개, 오름차순)
  69. private static ChartData BuildChart(string name, IEnumerable<(string Date, string Value)> rows)
  70. {
  71. var points = rows
  72. .Select(r => (r.Date, Parsed: decimal.TryParse(r.Value, NumberStyles.Any, CultureInfo.InvariantCulture, out decimal value) ? value : (decimal?)null))
  73. .Where(p => p.Parsed.HasValue)
  74. .Take(60)
  75. .Reverse()
  76. .ToList();
  77. if (points.Count < 2)
  78. {
  79. return new ChartData();
  80. }
  81. return new ChartData
  82. {
  83. Labels = points.Select(p => p.Date).ToList(),
  84. Series = [new ChartSeries { Name = name, Values = points.Select(p => p.Parsed).ToList() }]
  85. };
  86. }
  87. [HttpGet("Price/Global/NaturalGas")]
  88. public async Task<IActionResult> NaturalGas(NaturalGas.Request request)
  89. {
  90. if (!ModelState.IsValid)
  91. {
  92. return BadRequest(ModelState);
  93. }
  94. if (!new[] { "daily", "weekly", "monthly" }.Contains(request.Interval))
  95. {
  96. return BadRequest("Invalid input provided.");
  97. }
  98. int exchangeValue = await GetExchangeValueAsync();
  99. GlobalModel globalModel = new GlobalModel(_alphaAPI, _cache, _context);
  100. NaturalGas.Response itemList = await globalModel.GetNaturalGasPriceInfo(request);
  101. ChartData? chart = null;
  102. int total = 0;
  103. if (itemList.Data != null && itemList.Data.Any())
  104. {
  105. chart = BuildChart("천연가스", itemList.Data.Select(d => (d.Date, d.Value)));
  106. total = itemList.Data.Count;
  107. int listNum = Common.CalcListNumber(total, request.PageNo, request.NumOfRows);
  108. // 페이징 처리
  109. int skip = (request.PageNo - 1) * request.NumOfRows;
  110. int take = request.NumOfRows;
  111. itemList.Data = itemList.Data.Skip(skip).Take(take).Select((row, index) =>
  112. {
  113. row.Num = (listNum - index);
  114. if (decimal.TryParse(row.Value, NumberStyles.Any, CultureInfo.InvariantCulture, out decimal value) && value > 0)
  115. {
  116. row.KRW = (int)Math.Round(value * exchangeValue);
  117. }
  118. return row;
  119. }).ToList();
  120. }
  121. else
  122. {
  123. ViewBag.isError = true;
  124. ViewBag.errorMessage = "국제 시세 데이터를 가져오지 못했습니다. (API 한도 초과 또는 일시 장애)";
  125. }
  126. var viewModel = new View<NaturalGas.Request, NaturalGas.Response>();
  127. viewModel.SelectedListPerPage = request.NumOfRows;
  128. viewModel.Request = request;
  129. viewModel.Response = itemList;
  130. viewModel.Chart = chart;
  131. var queryString = new
  132. {
  133. interval = request.Interval
  134. };
  135. var pagination = new Pagination(total, request.PageNo, request.NumOfRows, queryString);
  136. viewModel.Pagination = pagination;
  137. return View("/Views/Price/Global/NaturalGas.cshtml", viewModel);
  138. }
  139. [HttpGet("Price/Global/{commodity}")]
  140. public async Task<IActionResult> Commodity(Commodity.Request request)
  141. {
  142. if (!ModelState.IsValid)
  143. {
  144. return BadRequest(ModelState);
  145. }
  146. // 화이트리스트에 없는 상품은 404
  147. if (request.Commodity is null || !CommodityMap.TryGetValue(request.Commodity, out var meta))
  148. {
  149. return NotFound();
  150. }
  151. // 원자재 계열은 monthly/quarterly/annual만 지원 (잘못된 값은 Alpha Vantage가 조용히 monthly로 대체하므로 사전 차단)
  152. if (!new[] { "monthly", "quarterly", "annual" }.Contains(request.Interval))
  153. {
  154. return BadRequest("Invalid input provided.");
  155. }
  156. int exchangeValue = meta.HasKrw ? await GetExchangeValueAsync() : 0;
  157. GlobalModel globalModel = new GlobalModel(_alphaAPI, _cache, _context);
  158. Commodity.Response itemList = await globalModel.GetCommodityPriceInfo(meta.Function, request.Interval);
  159. ChartData? chart = null;
  160. int total = 0;
  161. if (itemList.Data != null && itemList.Data.Any())
  162. {
  163. chart = BuildChart(meta.Title, itemList.Data.Select(d => (d.Date, d.Value)));
  164. total = itemList.Data.Count;
  165. int listNum = Common.CalcListNumber(total, request.PageNo, request.NumOfRows);
  166. // 페이징 처리
  167. int skip = (request.PageNo - 1) * request.NumOfRows;
  168. int take = request.NumOfRows;
  169. itemList.Data = itemList.Data.Skip(skip).Take(take).Select((row, index) =>
  170. {
  171. row.Num = (listNum - index);
  172. if (decimal.TryParse(row.Value, NumberStyles.Any, CultureInfo.InvariantCulture, out decimal value) && value > 0)
  173. {
  174. row.KRW = Math.Round(value * exchangeValue);
  175. }
  176. row.Value = Common.NumberFormat(row.Value, "#,##0.##");
  177. return row;
  178. }).ToList();
  179. }
  180. else
  181. {
  182. ViewBag.isError = true;
  183. ViewBag.errorMessage = "국제 시세 데이터를 가져오지 못했습니다. (API 한도 초과 또는 일시 장애)";
  184. }
  185. ViewBag.Title = meta.Title;
  186. ViewBag.HasKrw = meta.HasKrw;
  187. var viewModel = new View<Commodity.Request, Commodity.Response>();
  188. viewModel.SelectedListPerPage = request.NumOfRows;
  189. viewModel.Request = request;
  190. viewModel.Response = itemList;
  191. viewModel.Chart = chart;
  192. var queryString = new
  193. {
  194. interval = request.Interval
  195. };
  196. var pagination = new Pagination(total, request.PageNo, request.NumOfRows, queryString);
  197. viewModel.Pagination = pagination;
  198. return View("/Views/Price/Global/Commodity.cshtml", viewModel);
  199. }
  200. }
  201. }