GlobalController.cs 9.6 KB

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