GlobalController.cs 9.9 KB

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