HomeController.cs 44 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126
  1. using Common.Constant;
  2. using log4net;
  3. using Microsoft.AspNetCore.Mvc;
  4. using SicboSub.Web.Helpers;
  5. using SicboSub.Web.Models;
  6. using System.Configuration;
  7. using System.Diagnostics;
  8. namespace SicboSub.Web.Controllers
  9. {
  10. public class HomeController : BaseController
  11. {
  12. private static readonly ILog log = LogManager.GetLogger(typeof(HomeController));
  13. private readonly ILogger<HomeController> _logger;
  14. private readonly IConfiguration _configuration;
  15. public HomeController(ILogger<HomeController> logger, IConfiguration configuration)
  16. {
  17. _logger = logger;
  18. _configuration = configuration;
  19. }
  20. public String GetParameter(String key)
  21. {
  22. return _configuration.GetSection(key).Value ?? "";
  23. }
  24. /// <summary>
  25. /// Lấy config value
  26. /// </summary>
  27. /// <summary>
  28. /// Trang chủ - Yêu cầu Token để truy cập
  29. /// Nếu chưa login và không có token URL -> Redirect về trang chủ Sicbo (RedirectUrl)
  30. /// Nếu có token -> Login -> Success: load trang, Fail: Redirect
  31. /// </summary>
  32. /// <summary>
  33. /// Helper to load exchange config server-side
  34. /// </summary>
  35. private async Task<List<ExchangeConfigItem>> LoadExchangeConfigInternal()
  36. {
  37. try
  38. {
  39. string token = GetToken();
  40. var request = new ExchangeConfigReq
  41. {
  42. lang = GetLanguage()
  43. };
  44. var url = GetParameter("Url") + ApiUrlConstant.ExchangeConfigLoadUrl;
  45. var resData = await DotnetLib.Rest.RestHandler.SendPostWithAuthen(
  46. log,
  47. url,
  48. request,
  49. token,
  50. token,
  51. "",
  52. GetLanguage()
  53. );
  54. if (resData != null)
  55. {
  56. ExchangeConfigRes response = new ExchangeConfigRes(resData.data);
  57. if (response.errorCode == CommonErrorCode.Success && response.data != null)
  58. {
  59. return response.data;
  60. }
  61. }
  62. }
  63. catch (Exception ex)
  64. {
  65. log.Error("LoadExchangeConfigInternal: Exception", ex);
  66. }
  67. return new List<ExchangeConfigItem>();
  68. }
  69. /// <summary>
  70. /// Helper to load packages server-side
  71. /// </summary>
  72. private async Task<List<PackageInfo>> LoadPackagesInternal()
  73. {
  74. try
  75. {
  76. string token = GetToken();
  77. var request = new PackageLoadReq
  78. {
  79. lang = GetLanguage(),
  80. pageNumber = 0,
  81. pageSize = 100
  82. };
  83. var url = GetParameter("Url") + ApiUrlConstant.PackageLoadUrl;
  84. var resData = await DotnetLib.Rest.RestHandler.SendPostWithAuthen(
  85. log,
  86. url,
  87. request,
  88. token,
  89. token,
  90. "",
  91. GetLanguage()
  92. );
  93. if (resData != null)
  94. {
  95. PackageLoadRes response = new PackageLoadRes(resData.data);
  96. if (response.errorCode == CommonErrorCode.Success && response.data != null)
  97. {
  98. return response.data
  99. .Where(p => !string.IsNullOrEmpty(p.productName) && p.productName.StartsWith("CHARGE"))
  100. .OrderBy(p => p.fee)
  101. .ToList();
  102. }
  103. }
  104. }
  105. catch (Exception ex)
  106. {
  107. log.Error("LoadPackagesInternal: Exception", ex);
  108. }
  109. return new List<PackageInfo>();
  110. }
  111. /// <summary>
  112. /// Helper to reload account info (refresh session data)
  113. /// </summary>
  114. private async Task ReloadAccountInfo()
  115. {
  116. try
  117. {
  118. var token = GetToken();
  119. if (!string.IsNullOrEmpty(token))
  120. {
  121. var request = new AccountInfoReq
  122. {
  123. msisdn = GetMsisdn(),
  124. lang = GetLanguage()
  125. };
  126. var url = GetParameter("Url") + ApiUrlConstant.UserInfoUrl;
  127. // Gọi API xác thực/lấy thông tin
  128. var resData = await DotnetLib.Rest.RestHandler.SendPostWithAuthen(
  129. log,
  130. url,
  131. request,
  132. token,
  133. token,
  134. "",
  135. GetLanguage()
  136. );
  137. if (resData != null)
  138. {
  139. AccountInfoRes response = new AccountInfoRes(resData.data);
  140. if (response.errorCode == CommonErrorCode.Success && response.data != null)
  141. {
  142. // Update Session
  143. HttpContext.Session.SetComplexData("winCoin", response.data.winCoin);
  144. HttpContext.Session.SetComplexData("betCoin", response.data.betCoin);
  145. var currentUser = HttpContext.Session.GetComplexData<TokenLoginData>("userInfo");
  146. if(currentUser != null) {
  147. currentUser.winCoin = response.data.winCoin;
  148. currentUser.betCoin = response.data.betCoin;
  149. currentUser.isRegistered = response.data.isRegistered;
  150. if(response.data.regPkg != null) {
  151. currentUser.regPkg = new RegInfoData {
  152. RegisterId = response.data.regPkg.RegisterId,
  153. Msisdn = response.data.regPkg.Msisdn,
  154. ProductName = response.data.regPkg.ProductName,
  155. RegisterTime = response.data.regPkg.RegisterTime,
  156. NumberSpin = response.data.regPkg.NumberSpin,
  157. Status = response.data.regPkg.Status,
  158. ExpireTime = response.data.regPkg.ExpireTime,
  159. Renew = response.data.regPkg.Renew
  160. };
  161. } else {
  162. currentUser.regPkg = null;
  163. }
  164. HttpContext.Session.SetComplexData("userInfo", currentUser);
  165. }
  166. HttpContext.Session.SetComplexData("isRegistered", response.data.isRegistered);
  167. }
  168. }
  169. }
  170. }
  171. catch(Exception ex)
  172. {
  173. log.Error("ReloadAccountInfo: Error", ex);
  174. }
  175. }
  176. public async Task<IActionResult> Index()
  177. {
  178. // 1. Kiểm tra nếu đã đăng nhập từ trước
  179. if (IsAuthenticated())
  180. {
  181. // Refresh account info as requested
  182. await ReloadAccountInfo();
  183. // Setup ViewData và hiển thị
  184. ViewData["IsAuthenticated"] = true;
  185. ViewData["Msisdn"] = GetMsisdn();
  186. ViewData["WinCoin"] = HttpContext.Session.GetComplexData<decimal?>("winCoin") ?? 0;
  187. ViewData["BetCoin"] = HttpContext.Session.GetComplexData<decimal?>("betCoin") ?? 0;
  188. // Load packages server-side
  189. var packages = await LoadPackagesInternal();
  190. HttpContext.Session.SetComplexData("Packages", packages); // Store in session as requested
  191. // Load exchange config server-side
  192. var exchangeConfigs = await LoadExchangeConfigInternal();
  193. HttpContext.Session.SetComplexData("ExchangeConfig", exchangeConfigs);
  194. return View();
  195. }
  196. // 2. Nếu chưa đăng nhập, kiểm tra Token trên URL
  197. // Debug logging
  198. log.Info($"Index: Request QueryString: {Request.QueryString}");
  199. var tokenKeys = Request.Query.Keys;
  200. log.Info($"Index: Query Keys: {string.Join(", ", tokenKeys)}");
  201. var token = Request.Query["token"].FirstOrDefault();
  202. log.Info($"Index: Token extracted: '{token}'");
  203. if (!string.IsNullOrEmpty(token))
  204. {
  205. log.Info($"Index: Token found in URL, attempting login...");
  206. HttpContext.Session.GetComplexData<string?>("tokenRedirect");
  207. HttpContext.Session.SetComplexData("tokenRedirect", token);
  208. try
  209. {
  210. // Tạo request
  211. var request = new TokenLoginReq
  212. {
  213. token = token,
  214. language = GetLanguage()
  215. };
  216. var url = GetParameter("Url") + ApiUrlConstant.AuthLoginUrl;
  217. // Gọi API xác thực
  218. var resData = await DotnetLib.Rest.RestHandler.SendPostWithAuthen(
  219. log,
  220. url,
  221. request,
  222. token,
  223. token,
  224. "",
  225. GetLanguage()
  226. );
  227. // Parse response
  228. if (resData != null)
  229. {
  230. TokenLoginRes response = new TokenLoginRes(resData.data);
  231. if (response.errorCode == CommonErrorCode.Success)
  232. {
  233. // Login thành công -> Lưu Session
  234. CreateAuthToken();
  235. HttpContext.Session.SetComplexData("token", token);
  236. HttpContext.Session.SetComplexData("msisdn", response.data?.msisdn);
  237. HttpContext.Session.SetComplexData("winCoin", response.data?.winCoin);
  238. HttpContext.Session.SetComplexData("betCoin", response.data?.betCoin);
  239. HttpContext.Session.SetComplexData("userInfo", response.data);
  240. HttpContext.Session.SetComplexData("isRegistered", response.data?.isRegistered);
  241. log.Info($"Index: Login success, MSISDN = {response.data?.msisdn}");
  242. // Redirect lại Index để xóa token khỏi URL (và để lọt vào check IsAuthenticated ở trên)
  243. return RedirectToAction("Index");
  244. }
  245. else
  246. {
  247. log.Warn($"Index: Login failed - {response.message}");
  248. }
  249. }
  250. }
  251. catch (Exception ex)
  252. {
  253. log.Error("Index: Login exception", ex);
  254. }
  255. }
  256. // 3. Nếu chạy đến đây nghĩa là: Chưa Login Session VÀ (Không có token HOẶC Login Token thất bại)
  257. // ==> Redirect về trang nguồn (sicbo.vn)
  258. return RedirectToLogin(_configuration);
  259. }
  260. public async Task<IActionResult> Play()
  261. {
  262. var token = "";
  263. // 1. Kiểm tra nếu đã đăng nhập từ trước
  264. if (IsAuthenticated())
  265. {
  266. token = HttpContext.Session.GetComplexData<string>("tokenRedirect");
  267. log.Info($"Play: token = "+ token);
  268. }
  269. var url = GetParameter("RedirectUrl") + "/?token=" + token;
  270. log.Info($"PlayUrl: url = " + url);
  271. ClearCache();
  272. // Không gọi ClearCache() để giữ session login khi user quay lại
  273. return Redirect(url);
  274. }
  275. public IActionResult Privacy()
  276. {
  277. if (!IsAuthenticated()) return RedirectToLogin(_configuration);
  278. return View();
  279. }
  280. /// <summary>
  281. /// Helper to load play history
  282. /// </summary>
  283. private async Task<List<PlayHistoryItem>> LoadPlayHistoryInternal()
  284. {
  285. try
  286. {
  287. var token = GetToken();
  288. // 3 days ago
  289. var fromDate = DateTime.Now.AddDays(-3).ToString("dd/MM/yyyy 00:00:00");
  290. var toDate = DateTime.Now.ToString("dd/MM/yyyy 23:59:59");
  291. var request = new PlayHistoryReq
  292. {
  293. msisdn = GetMsisdn(),
  294. lang = GetLanguage(),
  295. fromDate = fromDate,
  296. toDate = toDate,
  297. pageNumber = 0,
  298. pageSize = 100
  299. };
  300. var url = GetParameter("Url") + ApiUrlConstant.PlayHistoryUrl;
  301. var resData = await DotnetLib.Rest.RestHandler.SendPostWithAuthen(
  302. log,
  303. url,
  304. request,
  305. token,
  306. token,
  307. "",
  308. GetLanguage()
  309. );
  310. if (resData != null)
  311. {
  312. PlayHistoryRes response = new PlayHistoryRes(resData.data);
  313. if (response.errorCode == CommonErrorCode.Success && response.data != null)
  314. {
  315. return response.data;
  316. }
  317. }
  318. }
  319. catch (Exception ex)
  320. {
  321. log.Error("LoadPlayHistoryInternal: Error", ex);
  322. }
  323. return new List<PlayHistoryItem>();
  324. }
  325. /// <summary>
  326. /// Helper to load purchase history
  327. /// </summary>
  328. private async Task<List<PurchaseHistoryItem>> LoadPurchaseHistoryInternal()
  329. {
  330. try
  331. {
  332. var token = GetToken();
  333. // 30 days ago for purchase history
  334. var fromDate = DateTime.Now.AddDays(-30).ToString("dd/MM/yyyy 00:00:00");
  335. var toDate = DateTime.Now.ToString("dd/MM/yyyy 23:59:59");
  336. var request = new PurchaseHistoryReq
  337. {
  338. msisdn = GetMsisdn(),
  339. lang = GetLanguage(),
  340. fromDate = fromDate,
  341. toDate = toDate,
  342. pageNumber = 0,
  343. pageSize = 20
  344. };
  345. var url = GetParameter("Url") + ApiUrlConstant.PurchaseHistoryUrl;
  346. var resData = await DotnetLib.Rest.RestHandler.SendPostWithAuthen(
  347. log,
  348. url,
  349. request,
  350. token,
  351. token,
  352. "",
  353. GetLanguage()
  354. );
  355. if (resData != null)
  356. {
  357. PurchaseHistoryRes response = new PurchaseHistoryRes(resData.data);
  358. if (response.errorCode == CommonErrorCode.Success && response.data != null)
  359. {
  360. return response.data;
  361. }
  362. }
  363. }
  364. catch (Exception ex)
  365. {
  366. log.Error("LoadPurchaseHistoryInternal: Error", ex);
  367. }
  368. return new List<PurchaseHistoryItem>();
  369. }
  370. /// <summary>
  371. /// Helper to load exchange history
  372. /// </summary>
  373. private async Task<List<ExchangeHistoryItem>> LoadExchangeHistoryInternal()
  374. {
  375. try
  376. {
  377. var token = GetToken();
  378. // 30 days ago
  379. var fromDate = DateTime.Now.AddDays(-30).ToString("dd/MM/yyyy 00:00:00");
  380. var toDate = DateTime.Now.ToString("dd/MM/yyyy 23:59:59");
  381. var request = new ExchangeHistoryReq
  382. {
  383. msisdn = GetMsisdn(),
  384. lang = GetLanguage(),
  385. fromDate = fromDate,
  386. toDate = toDate,
  387. pageNumber = 0,
  388. pageSize = 20
  389. };
  390. var url = GetParameter("Url") + ApiUrlConstant.ExchangeHistoryUrl;
  391. var resData = await DotnetLib.Rest.RestHandler.SendPostWithAuthen(
  392. log,
  393. url,
  394. request,
  395. token,
  396. token,
  397. "",
  398. GetLanguage()
  399. );
  400. if (resData != null)
  401. {
  402. ExchangeHistoryRes response = new ExchangeHistoryRes(resData.data);
  403. if (response.errorCode == CommonErrorCode.Success && response.data != null)
  404. {
  405. return response.data;
  406. }
  407. }
  408. }
  409. catch (Exception ex)
  410. {
  411. log.Error("LoadExchangeHistoryInternal: Error", ex);
  412. }
  413. return new List<ExchangeHistoryItem>();
  414. }
  415. public async Task<IActionResult> History()
  416. {
  417. if (!IsAuthenticated()) return RedirectToLogin(_configuration);
  418. var gameHistory = await LoadPlayHistoryInternal();
  419. // User requested: "history prize then pass its msisdn and it is Daily prize"
  420. var prizeHistory = await LoadRankingInternal("DAILY", GetMsisdn());
  421. var purchaseHistory = await LoadPurchaseHistoryInternal();
  422. var exchangeHistory = await LoadExchangeHistoryInternal();
  423. var model = new HistoryViewModel
  424. {
  425. GameHistory = gameHistory,
  426. PrizeHistory = prizeHistory,
  427. PurchaseHistory = purchaseHistory,
  428. ExchangeHistory = exchangeHistory
  429. };
  430. ViewData["Msisdn"] = GetMsisdn();
  431. return View(model);
  432. }
  433. public IActionResult Winner()
  434. {
  435. if (!IsAuthenticated()) return RedirectToLogin(_configuration);
  436. return View();
  437. }
  438. /// <summary>
  439. /// Helper to load ranking history
  440. /// </summary>
  441. /// <summary>
  442. /// Helper to load ranking history
  443. /// </summary>
  444. private async Task<List<RankingHistoryItem>> LoadRankingInternal(string rankType, string msisdn = null, string specificDate = null)
  445. {
  446. try
  447. {
  448. var token = GetToken();
  449. // Calculate date range based on rankType
  450. string fromDate = "";
  451. string toDate = DateTime.Now.ToString("dd/MM/yyyy");
  452. if (!string.IsNullOrEmpty(specificDate))
  453. {
  454. if (rankType == "MONTHLY" || rankType == "MONTHLYCOIN")
  455. {
  456. // Expected input: yyyy-MM
  457. if (DateTime.TryParseExact(specificDate, "yyyy-MM", System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None, out DateTime parsedMonth))
  458. {
  459. var firstDay = new DateTime(parsedMonth.Year, parsedMonth.Month, 1);
  460. var lastDay = firstDay.AddMonths(1).AddDays(-1);
  461. fromDate = firstDay.ToString("dd/MM/yyyy 00:00:00");
  462. toDate = lastDay.ToString("dd/MM/yyyy 23:59:59");
  463. }
  464. else
  465. {
  466. // Fallback try basic parsing
  467. if (DateTime.TryParse(specificDate, out DateTime parsed)) {
  468. var firstDay = new DateTime(parsed.Year, parsed.Month, 1);
  469. var lastDay = firstDay.AddMonths(1).AddDays(-1);
  470. fromDate = firstDay.ToString("dd/MM/yyyy 00:00:00");
  471. toDate = lastDay.ToString("dd/MM/yyyy 23:59:59");
  472. }
  473. }
  474. }
  475. else if (rankType == "DAILYCOIN")
  476. {
  477. if (DateTime.TryParseExact(specificDate, "yyyy-MM-dd", System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None, out DateTime parsedDate))
  478. {
  479. fromDate = parsedDate.ToString("dd/MM/yyyy 00:00:00");
  480. toDate = parsedDate.ToString("dd/MM/yyyy 23:59:59");
  481. }
  482. else
  483. {
  484. // Fallback try basic parsing
  485. if (DateTime.TryParse(specificDate, out DateTime parsed))
  486. {
  487. fromDate = parsed.ToString("dd/MM/yyyy 00:00:00");
  488. toDate = parsed.ToString("dd/MM/yyyy 23:59:59");
  489. }
  490. }
  491. } else
  492. {
  493. // DAILY - Exact Date
  494. // Convert yyyy-MM-dd to dd/MM/yyyy HH:mm:ss
  495. // Input expected: yyyy-MM-dd (from HTML5 date input)
  496. if (DateTime.TryParseExact(specificDate, "yyyy-MM-dd", System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None, out DateTime parsedDate))
  497. {
  498. fromDate = parsedDate.ToString("dd/MM/yyyy 00:00:00");
  499. toDate = parsedDate.ToString("dd/MM/yyyy 23:59:59");
  500. }
  501. else
  502. {
  503. // Fallback: try to just append time if it looks like a date
  504. fromDate = specificDate + " 00:00:00";
  505. toDate = specificDate + " 23:59:59";
  506. }
  507. }
  508. }
  509. else
  510. {
  511. if (rankType == "DAILY" || rankType == "DAILYCOIN")
  512. {
  513. fromDate = DateTime.Now.ToString("dd/MM/yyyy 00:00:00");
  514. toDate = DateTime.Now.ToString("dd/MM/yyyy 23:59:59");
  515. }
  516. else if (rankType == "MONTHLY" || rankType == "MONTHLYCOIN")
  517. {
  518. var firstDay = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1);
  519. var lastDay = firstDay.AddMonths(1).AddDays(-1);
  520. fromDate = firstDay.ToString("dd/MM/yyyy 00:00:00");
  521. toDate = lastDay.ToString("dd/MM/yyyy 23:59:59");
  522. }
  523. }
  524. var request = new RankingHistoryReq
  525. {
  526. msisdn = msisdn, // Pass specific msisdn or null/empty
  527. lang = GetLanguage(),
  528. rankType = (rankType == "DAILY" || rankType == "DAILYCOIN") ? "DAILY" : "MONTHLY",
  529. fromDate = fromDate,
  530. toDate = toDate,
  531. pageNumber = 0,
  532. pageSize = (rankType == "DAILY" || rankType == "DAILYCOIN" || rankType == "MONTHLYCOIN") ? 50 : 5
  533. };
  534. var url = GetParameter("Url") + ApiUrlConstant.RankingHistoryUrl;
  535. var resData = await DotnetLib.Rest.RestHandler.SendPostWithAuthen(
  536. log,
  537. url,
  538. request,
  539. token,
  540. token,
  541. "",
  542. GetLanguage()
  543. );
  544. if (resData != null)
  545. {
  546. RankingHistoryRes response = new RankingHistoryRes(resData.data);
  547. if (response.errorCode == CommonErrorCode.Success && response.data != null)
  548. {
  549. string currentMsisdn = GetMsisdn();
  550. foreach (var item in response.data)
  551. {
  552. if (item.msisdn != currentMsisdn)
  553. {
  554. item.msisdn = MaskMsisdn(item.msisdn);
  555. }
  556. }
  557. return response.data;
  558. }
  559. }
  560. }
  561. catch(Exception ex)
  562. {
  563. log.Error($"LoadRankingInternal ({rankType}): Error", ex);
  564. }
  565. return new List<RankingHistoryItem>();
  566. }
  567. [HttpPost]
  568. public async Task<IActionResult> GetRankingCoinData([FromBody] RankingHistoryReq request)
  569. {
  570. if (!IsAuthenticated()) return Json(new { errorCode = CommonErrorCode.UnauthorizedAccess });
  571. try
  572. {
  573. string rankType = request?.rankType ?? "MONTHLYCOIN";
  574. var specificDate = rankType == "DAILYCOIN" ? DateTime.Now.ToString("yyyy-MM-dd") : DateTime.Now.ToString("yyyy-MM");
  575. var globalRankings = await LoadRankingCoinHistoryInternal(rankType, null, specificDate);
  576. var userRanking = await LoadRankingCoinHistoryInternal(rankType, GetMsisdn(), specificDate);
  577. var currentUserItem = userRanking?.FirstOrDefault(x => x.msisdn == GetMsisdn());
  578. return Json(new {
  579. errorCode = CommonErrorCode.Success,
  580. data = new { global = globalRankings, user = currentUserItem }
  581. });
  582. }
  583. catch (Exception ex)
  584. {
  585. log.Error("GetRankingCoinData: Error", ex);
  586. return Json(new { errorCode = CommonErrorCode.SystemError });
  587. }
  588. }
  589. private async Task<List<RankingHistoryItem>> LoadRankingCoinHistoryInternal(string rankType, string msisdn = null, string specificDate = null)
  590. {
  591. try
  592. {
  593. var token = GetToken();
  594. // Calculate date range based on rankType
  595. string fromDate = "";
  596. string toDate = DateTime.Now.ToString("dd/MM/yyyy");
  597. if (!string.IsNullOrEmpty(specificDate))
  598. {
  599. if (rankType == "MONTHLYCOIN")
  600. {
  601. // Expected input: yyyy-MM
  602. if (DateTime.TryParseExact(specificDate, "yyyy-MM", System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None, out DateTime parsedMonth))
  603. {
  604. var firstDay = new DateTime(parsedMonth.Year, parsedMonth.Month, 1);
  605. var lastDay = firstDay.AddMonths(1).AddDays(-1);
  606. fromDate = firstDay.ToString("dd/MM/yyyy 00:00:00");
  607. toDate = lastDay.ToString("dd/MM/yyyy 23:59:59");
  608. }
  609. else
  610. {
  611. // Fallback try basic parsing
  612. if (DateTime.TryParse(specificDate, out DateTime parsed))
  613. {
  614. var firstDay = new DateTime(parsed.Year, parsed.Month, 1);
  615. var lastDay = firstDay.AddMonths(1).AddDays(-1);
  616. fromDate = firstDay.ToString("dd/MM/yyyy 00:00:00");
  617. toDate = lastDay.ToString("dd/MM/yyyy 23:59:59");
  618. }
  619. }
  620. }
  621. else if (rankType == "DAILYCOIN")
  622. {
  623. if (DateTime.TryParseExact(specificDate, "yyyy-MM-dd", System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None, out DateTime parsedDate))
  624. {
  625. fromDate = parsedDate.ToString("dd/MM/yyyy 00:00:00");
  626. toDate = parsedDate.ToString("dd/MM/yyyy 23:59:59");
  627. }
  628. else
  629. {
  630. // Fallback try basic parsing
  631. if (DateTime.TryParse(specificDate, out DateTime parsed))
  632. {
  633. fromDate = parsed.ToString("dd/MM/yyyy 00:00:00");
  634. toDate = parsed.ToString("dd/MM/yyyy 23:59:59");
  635. }
  636. }
  637. }
  638. }
  639. else
  640. {
  641. if (rankType == "DAILYCOIN")
  642. {
  643. fromDate = DateTime.Now.ToString("dd/MM/yyyy 00:00:00");
  644. toDate = DateTime.Now.ToString("dd/MM/yyyy 23:59:59");
  645. }
  646. else if (rankType == "MONTHLYCOIN")
  647. {
  648. var firstDay = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1);
  649. var lastDay = firstDay.AddMonths(1).AddDays(-1);
  650. fromDate = firstDay.ToString("dd/MM/yyyy 00:00:00");
  651. toDate = lastDay.ToString("dd/MM/yyyy 23:59:59");
  652. }
  653. }
  654. var request = new RankingHistoryReq
  655. {
  656. msisdn = msisdn, // Pass specific msisdn or null/empty
  657. lang = GetLanguage(),
  658. rankType = (rankType == "DAILY" || rankType == "DAILYCOIN") ? "DAILY" : "MONTHLY",
  659. fromDate = fromDate,
  660. toDate = toDate,
  661. pageNumber = 0,
  662. pageSize = (rankType == "DAILY" || rankType == "DAILYCOIN" || rankType == "MONTHLYCOIN") ? 50 : 5
  663. };
  664. var url = GetParameter("Url") + ApiUrlConstant.RankingCointHistoryUrl;
  665. var resData = await DotnetLib.Rest.RestHandler.SendPostWithAuthen(
  666. log,
  667. url,
  668. request,
  669. token,
  670. token,
  671. "",
  672. GetLanguage()
  673. );
  674. if (resData != null)
  675. {
  676. RankingHistoryRes response = new RankingHistoryRes(resData.data);
  677. if (response.errorCode == CommonErrorCode.Success && response.data != null)
  678. {
  679. string currentMsisdn = GetMsisdn();
  680. foreach (var item in response.data)
  681. {
  682. if (item.msisdn != currentMsisdn)
  683. {
  684. item.msisdn = MaskMsisdn(item.msisdn);
  685. }
  686. }
  687. return response.data;
  688. }
  689. }
  690. }
  691. catch (Exception ex)
  692. {
  693. log.Error($"LoadRankingInternal ({rankType}): Error", ex);
  694. }
  695. return new List<RankingHistoryItem>();
  696. }
  697. public async Task<IActionResult> DailyRanking(string date = null)
  698. {
  699. if (!IsAuthenticated()) return RedirectToLogin(_configuration);
  700. // For Global Daily Ranking, we don't pass MSISDN implies global list
  701. var data = await LoadRankingInternal("DAILY", null, date);
  702. ViewData["RankingType"] = "DAILY";
  703. ViewData["SelectedDate"] = date;
  704. return View(data);
  705. }
  706. public async Task<IActionResult> MonthlyRanking(string date = null)
  707. {
  708. if (!IsAuthenticated()) return RedirectToLogin(_configuration);
  709. var data = await LoadRankingInternal("MONTHLY", null, date);
  710. ViewData["RankingType"] = "MONTHLY";
  711. ViewData["SelectedDate"] = date;
  712. return View(data);
  713. }
  714. public async Task<IActionResult> Account()
  715. {
  716. if (!IsAuthenticated()) return RedirectToLogin(_configuration);
  717. // Refresh account info to get latest balance
  718. await ReloadAccountInfo();
  719. // Get user info from session
  720. var userInfo = HttpContext.Session.GetComplexData<TokenLoginData>("userInfo");
  721. ViewData["UserInfo"] = userInfo;
  722. ViewData["Msisdn"] = GetMsisdn();
  723. ViewData["WinCoin"] = HttpContext.Session.GetComplexData<decimal?>("winCoin") ?? 0;
  724. ViewData["BetCoin"] = HttpContext.Session.GetComplexData<decimal?>("betCoin") ?? 0;
  725. // TODO: Retrieve actual values for Today/Month from API when available
  726. ViewData["TotalValueToday"] = 0;
  727. ViewData["TotalValueMonth"] = 0;
  728. return View();
  729. }
  730. /// <summary>
  731. /// Đăng xuất
  732. /// </summary>
  733. public IActionResult Logout()
  734. {
  735. ClearCache();
  736. return RedirectToLogin(_configuration);
  737. }
  738. [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
  739. public IActionResult Error()
  740. {
  741. return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
  742. }
  743. /// <summary>
  744. /// Đăng ký gói (Register)
  745. /// </summary>
  746. [HttpPost]
  747. public async Task<IActionResult> Register()
  748. {
  749. // 1. Check Authentication (server-side check)
  750. if (!IsAuthenticated())
  751. {
  752. return Json(new { errorCode = CommonErrorCode.UnauthorizedAccess, message = "Unauthorized" });
  753. }
  754. try
  755. {
  756. // 2. Prepare request data
  757. string? msisdn = GetMsisdn();
  758. string? token = GetToken();
  759. // Default package for daily registration
  760. string packageCode = GetParameter("PackageCodeDaily");
  761. // Default fallback if config missing
  762. if (string.IsNullOrEmpty(packageCode)) packageCode = "SICBO_DAY";
  763. var request = new RegisterReq
  764. {
  765. msisdn = msisdn,
  766. packageCode = packageCode,
  767. lang = GetLanguage()
  768. };
  769. // 3. Call API
  770. var url = GetParameter("Url") + ApiUrlConstant.RegisterUrl;
  771. var resData = await DotnetLib.Rest.RestHandler.SendPostWithAuthen(
  772. log,
  773. url,
  774. request,
  775. token,
  776. token,
  777. "",
  778. GetLanguage()
  779. );
  780. // 4. Handle Response
  781. if (resData != null)
  782. {
  783. RegisterRes response = new RegisterRes(resData.data);
  784. if (response.errorCode == CommonErrorCode.Success)
  785. {
  786. // Refresh info to get latest balance
  787. await ReloadAccountInfo();
  788. // Update response data with latest session info
  789. if (response.data == null) response.data = new RegisterData();
  790. response.data.winCoin = HttpContext.Session.GetComplexData<decimal?>("winCoin");
  791. response.data.betCoin = HttpContext.Session.GetComplexData<decimal?>("betCoin");
  792. return Json(response);
  793. }
  794. else
  795. {
  796. return Json(new { errorCode = response.errorCode, message = response.message });
  797. }
  798. }
  799. return Json(new { errorCode = CommonErrorCode.Error, message = "System Error" });
  800. }
  801. catch (Exception ex)
  802. {
  803. log.Error("Register: Exception", ex);
  804. return Json(new { errorCode = CommonErrorCode.SystemError, message = "Exception" });
  805. }
  806. }
  807. /// <summary>
  808. /// Mua thêm lượt (Buy More)
  809. /// </summary>
  810. [HttpPost]
  811. public async Task<IActionResult> BuyMore([FromBody] BuyMoreReq reqBody)
  812. {
  813. // 1. Check Authentication
  814. if (!IsAuthenticated())
  815. {
  816. return Json(new { errorCode = CommonErrorCode.UnauthorizedAccess, message = "Unauthorized" });
  817. }
  818. try
  819. {
  820. // 2. Prepare Request
  821. string msisdn = GetMsisdn();
  822. string token = GetToken();
  823. var request = new BuyMoreReq
  824. {
  825. msisdn = msisdn,
  826. packageCode = reqBody.packageCode,
  827. lang = GetLanguage()
  828. };
  829. // 3. Call API
  830. var url = GetParameter("Url") + ApiUrlConstant.BuyMoreUrl;
  831. var resData = await DotnetLib.Rest.RestHandler.SendPostWithAuthen(
  832. log,
  833. url,
  834. request,
  835. token,
  836. token,
  837. "",
  838. GetLanguage()
  839. );
  840. // 4. Handle Response
  841. if (resData != null)
  842. {
  843. BuyMoreRes response = new BuyMoreRes(resData.data);
  844. if (response.errorCode == CommonErrorCode.Success)
  845. {
  846. // Refresh info to get latest balance
  847. await ReloadAccountInfo();
  848. // Update response data with latest session info
  849. if (response.data == null) response.data = new BuyMoreData();
  850. response.data.winCoin = HttpContext.Session.GetComplexData<decimal?>("winCoin");
  851. response.data.betCoin = HttpContext.Session.GetComplexData<decimal?>("betCoin");
  852. return Json(response);
  853. }
  854. else
  855. {
  856. return Json(new { errorCode = response.errorCode, message = response.message });
  857. }
  858. }
  859. return Json(new { errorCode = CommonErrorCode.Error, message = "System Error" });
  860. }
  861. catch (Exception ex)
  862. {
  863. log.Error("BuyMore: Exception", ex);
  864. return Json(new { errorCode = CommonErrorCode.SystemError, message = "Exception" });
  865. }
  866. }
  867. /// <summary>
  868. /// Request Withdraw OTP
  869. /// </summary>
  870. [HttpPost]
  871. public async Task<IActionResult> RequestWithdrawOtp([FromBody] ExchangeRequestOtpReq reqBody)
  872. {
  873. if (!IsAuthenticated())
  874. {
  875. return Json(new { errorCode = CommonErrorCode.UnauthorizedAccess, message = "Unauthorized" });
  876. }
  877. try
  878. {
  879. string msisdn = GetMsisdn();
  880. string token = GetToken();
  881. var request = new ExchangeRequestOtpReq
  882. {
  883. msisdn = msisdn,
  884. configId = reqBody.configId,
  885. lang = GetLanguage()
  886. };
  887. // Call API
  888. var url = GetParameter("Url") + ApiUrlConstant.ExchangeRequestOtpUrl;
  889. var resData = await DotnetLib.Rest.RestHandler.SendPostWithAuthen(
  890. log,
  891. url,
  892. request,
  893. token,
  894. token,
  895. "",
  896. GetLanguage()
  897. );
  898. if (resData != null)
  899. {
  900. ExchangeRequestOtpRes response = new ExchangeRequestOtpRes(resData.data);
  901. return Json(new { errorCode = response.errorCode, message = response.message, data = response.data });
  902. }
  903. return Json(new { errorCode = CommonErrorCode.Error, message = "System Error" });
  904. }
  905. catch (Exception ex)
  906. {
  907. log.Error("RequestWithdrawOtp: Exception", ex);
  908. return Json(new { errorCode = CommonErrorCode.SystemError, message = "Exception" });
  909. }
  910. }
  911. /// <summary>
  912. /// Confirm Withdraw OTP
  913. /// </summary>
  914. [HttpPost]
  915. public async Task<IActionResult> ConfirmWithdrawOtp([FromBody] ExchangeVerifyOtpReq reqBody)
  916. {
  917. // 1. Check Authentication
  918. if (!IsAuthenticated())
  919. {
  920. return Json(new { errorCode = CommonErrorCode.UnauthorizedAccess, message = "Unauthorized" });
  921. }
  922. try
  923. {
  924. string msisdn = GetMsisdn();
  925. string token = GetToken();
  926. var request = new ExchangeVerifyOtpReq
  927. {
  928. msisdn = msisdn,
  929. otpCode = reqBody.otpCode,
  930. lang = GetLanguage()
  931. };
  932. // Call API
  933. var url = GetParameter("Url") + ApiUrlConstant.ExchangeVerifyOtpUrl;
  934. var resData = await DotnetLib.Rest.RestHandler.SendPostWithAuthen(
  935. log,
  936. url,
  937. request,
  938. token,
  939. token,
  940. "",
  941. GetLanguage()
  942. );
  943. if (resData != null)
  944. {
  945. ExchangeVerifyOtpRes response = new ExchangeVerifyOtpRes(resData.data);
  946. if (response.errorCode == CommonErrorCode.Success)
  947. {
  948. // Refresh Account Info
  949. await ReloadAccountInfo();
  950. // Get updated fields
  951. var winCoin = HttpContext.Session.GetComplexData<decimal?>("winCoin");
  952. var betCoin = HttpContext.Session.GetComplexData<decimal?>("betCoin");
  953. return Json(new { errorCode = response.errorCode, message = response.message, data = new { winCoin, betCoin } });
  954. }
  955. return Json(new { errorCode = response.errorCode, message = response.message, data = response.data });
  956. }
  957. return Json(new { errorCode = CommonErrorCode.Error, message = "System Error" });
  958. }
  959. catch (Exception ex)
  960. {
  961. log.Error("ConfirmWithdrawOtp: Exception", ex);
  962. return Json(new { errorCode = CommonErrorCode.SystemError, message = "Exception" });
  963. }
  964. }
  965. /// <summary>
  966. /// Lấy danh sách gói cước (Packages)
  967. /// </summary>
  968. [HttpPost]
  969. public async Task<IActionResult> GetPackages()
  970. {
  971. // 1. Check Authentication
  972. if (!IsAuthenticated())
  973. {
  974. return Json(new { errorCode = CommonErrorCode.UnauthorizedAccess, message = "Unauthorized" });
  975. }
  976. var packages = await LoadPackagesInternal();
  977. return Json(new { errorCode = CommonErrorCode.Success, data = packages });
  978. }
  979. private string MaskMsisdn(string msisdn)
  980. {
  981. if (string.IsNullOrEmpty(msisdn)) return msisdn;
  982. int len = msisdn.Length;
  983. if (len <= 5) return msisdn;
  984. if (len == 10)
  985. {
  986. return msisdn.Substring(0, 3) + "xxxxx" + msisdn.Substring(8);
  987. }
  988. else if (len == 11)
  989. {
  990. return msisdn.Substring(0, 3) + "xxxxx" + msisdn.Substring(8);
  991. }
  992. else
  993. {
  994. if (len > 5) {
  995. int maskStart = (len - 5) / 2;
  996. return msisdn.Substring(0, maskStart) + "xxxxx" + msisdn.Substring(maskStart + 5);
  997. }
  998. return msisdn;
  999. }
  1000. }
  1001. }
  1002. }