HomeController.cs 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853
  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 TokenLoginReq
  122. {
  123. token = token,
  124. language = GetLanguage()
  125. };
  126. var url = GetParameter("Url") + ApiUrlConstant.AuthLoginUrl;
  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. TokenLoginRes response = new TokenLoginRes(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. HttpContext.Session.SetComplexData("userInfo", response.data);
  146. HttpContext.Session.SetComplexData("isRegistered", response.data.isRegistered);
  147. }
  148. }
  149. }
  150. }
  151. catch(Exception ex)
  152. {
  153. log.Error("ReloadAccountInfo: Error", ex);
  154. }
  155. }
  156. public async Task<IActionResult> Index()
  157. {
  158. // 1. Kiểm tra nếu đã đăng nhập từ trước
  159. if (IsAuthenticated())
  160. {
  161. // Refresh account info as requested
  162. await ReloadAccountInfo();
  163. // Setup ViewData và hiển thị
  164. ViewData["IsAuthenticated"] = true;
  165. ViewData["Msisdn"] = GetMsisdn();
  166. ViewData["WinCoin"] = HttpContext.Session.GetComplexData<decimal?>("winCoin") ?? 0;
  167. ViewData["BetCoin"] = HttpContext.Session.GetComplexData<decimal?>("betCoin") ?? 0;
  168. // Load packages server-side
  169. var packages = await LoadPackagesInternal();
  170. HttpContext.Session.SetComplexData("Packages", packages); // Store in session as requested
  171. // Load exchange config server-side
  172. var exchangeConfigs = await LoadExchangeConfigInternal();
  173. HttpContext.Session.SetComplexData("ExchangeConfig", exchangeConfigs);
  174. return View();
  175. }
  176. // 2. Nếu chưa đăng nhập, kiểm tra Token trên URL
  177. var token = Request.Query["token"].FirstOrDefault();
  178. if (!string.IsNullOrEmpty(token))
  179. {
  180. log.Info($"Index: Token found in URL, attempting login...");
  181. HttpContext.Session.GetComplexData<string?>("tokenRedirect");
  182. HttpContext.Session.SetComplexData("tokenRedirect", token);
  183. try
  184. {
  185. // Tạo request
  186. var request = new TokenLoginReq
  187. {
  188. token = token,
  189. language = GetLanguage()
  190. };
  191. var url = GetParameter("Url") + ApiUrlConstant.AuthLoginUrl;
  192. // Gọi API xác thực
  193. var resData = await DotnetLib.Rest.RestHandler.SendPostWithAuthen(
  194. log,
  195. url,
  196. request,
  197. token,
  198. token,
  199. "",
  200. GetLanguage()
  201. );
  202. // Parse response
  203. if (resData != null)
  204. {
  205. TokenLoginRes response = new TokenLoginRes(resData.data);
  206. if (response.errorCode == CommonErrorCode.Success)
  207. {
  208. // Login thành công -> Lưu Session
  209. CreateAuthToken();
  210. HttpContext.Session.SetComplexData("token", token);
  211. HttpContext.Session.SetComplexData("msisdn", response.data?.msisdn);
  212. HttpContext.Session.SetComplexData("winCoin", response.data?.winCoin);
  213. HttpContext.Session.SetComplexData("betCoin", response.data?.betCoin);
  214. HttpContext.Session.SetComplexData("userInfo", response.data);
  215. HttpContext.Session.SetComplexData("isRegistered", response.data?.isRegistered);
  216. log.Info($"Index: Login success, MSISDN = {response.data?.msisdn}");
  217. // Redirect lại Index để xóa token khỏi URL (và để lọt vào check IsAuthenticated ở trên)
  218. return RedirectToAction("Index");
  219. }
  220. else
  221. {
  222. log.Warn($"Index: Login failed - {response.message}");
  223. }
  224. }
  225. }
  226. catch (Exception ex)
  227. {
  228. log.Error("Index: Login exception", ex);
  229. }
  230. }
  231. // 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)
  232. // ==> Redirect về trang nguồn (sicbo.vn)
  233. return RedirectToLogin(_configuration);
  234. }
  235. public async Task<IActionResult> Play()
  236. {
  237. var token = "";
  238. // 1. Kiểm tra nếu đã đăng nhập từ trước
  239. if (IsAuthenticated())
  240. {
  241. token = HttpContext.Session.GetComplexData<string>("tokenRedirect");
  242. log.Info($"Play: token = "+ token);
  243. }
  244. var url = GetParameter("RedirectUrl") + "/?token=" + token;
  245. log.Info($"PlayUrl: url = " + url);
  246. ClearCache();
  247. // Không gọi ClearCache() để giữ session login khi user quay lại
  248. return Redirect(url);
  249. }
  250. public IActionResult Privacy()
  251. {
  252. if (!IsAuthenticated()) return RedirectToLogin(_configuration);
  253. return View();
  254. }
  255. /// <summary>
  256. /// Helper to load play history
  257. /// </summary>
  258. private async Task<List<PlayHistoryItem>> LoadPlayHistoryInternal()
  259. {
  260. try
  261. {
  262. var token = GetToken();
  263. // 3 days ago
  264. var fromDate = DateTime.Now.AddDays(-3).ToString("dd/MM/yyyy 00:00:00");
  265. var toDate = DateTime.Now.ToString("dd/MM/yyyy 23:59:59");
  266. var request = new PlayHistoryReq
  267. {
  268. msisdn = GetMsisdn(),
  269. lang = GetLanguage(),
  270. fromDate = fromDate,
  271. toDate = toDate,
  272. pageNumber = 0,
  273. pageSize = 100
  274. };
  275. var url = GetParameter("Url") + ApiUrlConstant.PlayHistoryUrl;
  276. var resData = await DotnetLib.Rest.RestHandler.SendPostWithAuthen(
  277. log,
  278. url,
  279. request,
  280. token,
  281. token,
  282. "",
  283. GetLanguage()
  284. );
  285. if (resData != null)
  286. {
  287. PlayHistoryRes response = new PlayHistoryRes(resData.data);
  288. if (response.errorCode == CommonErrorCode.Success && response.data != null)
  289. {
  290. return response.data;
  291. }
  292. }
  293. }
  294. catch (Exception ex)
  295. {
  296. log.Error("LoadPlayHistoryInternal: Error", ex);
  297. }
  298. return new List<PlayHistoryItem>();
  299. }
  300. /// <summary>
  301. /// Helper to load purchase history
  302. /// </summary>
  303. private async Task<List<PurchaseHistoryItem>> LoadPurchaseHistoryInternal()
  304. {
  305. try
  306. {
  307. var token = GetToken();
  308. // 30 days ago for purchase history
  309. var fromDate = DateTime.Now.AddDays(-30).ToString("dd/MM/yyyy 00:00:00");
  310. var toDate = DateTime.Now.ToString("dd/MM/yyyy 23:59:59");
  311. var request = new PurchaseHistoryReq
  312. {
  313. msisdn = GetMsisdn(),
  314. lang = GetLanguage(),
  315. fromDate = fromDate,
  316. toDate = toDate,
  317. pageNumber = 0,
  318. pageSize = 20
  319. };
  320. var url = GetParameter("Url") + ApiUrlConstant.PurchaseHistoryUrl;
  321. var resData = await DotnetLib.Rest.RestHandler.SendPostWithAuthen(
  322. log,
  323. url,
  324. request,
  325. token,
  326. token,
  327. "",
  328. GetLanguage()
  329. );
  330. if (resData != null)
  331. {
  332. PurchaseHistoryRes response = new PurchaseHistoryRes(resData.data);
  333. if (response.errorCode == CommonErrorCode.Success && response.data != null)
  334. {
  335. return response.data;
  336. }
  337. }
  338. }
  339. catch (Exception ex)
  340. {
  341. log.Error("LoadPurchaseHistoryInternal: Error", ex);
  342. }
  343. return new List<PurchaseHistoryItem>();
  344. }
  345. public async Task<IActionResult> History()
  346. {
  347. if (!IsAuthenticated()) return RedirectToLogin(_configuration);
  348. var gameHistory = await LoadPlayHistoryInternal();
  349. // User requested: "history prize then pass its msisdn and it is Daily prize"
  350. var prizeHistory = await LoadRankingInternal("DAILY", GetMsisdn());
  351. var purchaseHistory = await LoadPurchaseHistoryInternal();
  352. var model = new HistoryViewModel
  353. {
  354. GameHistory = gameHistory,
  355. PrizeHistory = prizeHistory,
  356. PurchaseHistory = purchaseHistory
  357. };
  358. ViewData["Msisdn"] = GetMsisdn();
  359. return View(model);
  360. }
  361. public IActionResult Winner()
  362. {
  363. if (!IsAuthenticated()) return RedirectToLogin(_configuration);
  364. return View();
  365. }
  366. /// <summary>
  367. /// Helper to load ranking history
  368. /// </summary>
  369. /// <summary>
  370. /// Helper to load ranking history
  371. /// </summary>
  372. private async Task<List<RankingHistoryItem>> LoadRankingInternal(string rankType, string msisdn = null, string specificDate = null)
  373. {
  374. try
  375. {
  376. var token = GetToken();
  377. // Calculate date range based on rankType
  378. string fromDate = "";
  379. string toDate = DateTime.Now.ToString("dd/MM/yyyy");
  380. if (!string.IsNullOrEmpty(specificDate))
  381. {
  382. if (rankType == "MONTHLY")
  383. {
  384. // Expected input: yyyy-MM
  385. if (DateTime.TryParseExact(specificDate, "yyyy-MM", System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None, out DateTime parsedMonth))
  386. {
  387. var firstDay = new DateTime(parsedMonth.Year, parsedMonth.Month, 1);
  388. var lastDay = firstDay.AddMonths(1).AddDays(-1);
  389. fromDate = firstDay.ToString("dd/MM/yyyy 00:00:00");
  390. toDate = lastDay.ToString("dd/MM/yyyy 23:59:59");
  391. }
  392. else
  393. {
  394. // Fallback try basic parsing
  395. if (DateTime.TryParse(specificDate, out DateTime parsed)) {
  396. var firstDay = new DateTime(parsed.Year, parsed.Month, 1);
  397. var lastDay = firstDay.AddMonths(1).AddDays(-1);
  398. fromDate = firstDay.ToString("dd/MM/yyyy 00:00:00");
  399. toDate = lastDay.ToString("dd/MM/yyyy 23:59:59");
  400. }
  401. }
  402. }
  403. else
  404. {
  405. // DAILY - Exact Date
  406. // Convert yyyy-MM-dd to dd/MM/yyyy HH:mm:ss
  407. // Input expected: yyyy-MM-dd (from HTML5 date input)
  408. if (DateTime.TryParseExact(specificDate, "yyyy-MM-dd", System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None, out DateTime parsedDate))
  409. {
  410. fromDate = parsedDate.ToString("dd/MM/yyyy 00:00:00");
  411. toDate = parsedDate.ToString("dd/MM/yyyy 23:59:59");
  412. }
  413. else
  414. {
  415. // Fallback: try to just append time if it looks like a date
  416. fromDate = specificDate + " 00:00:00";
  417. toDate = specificDate + " 23:59:59";
  418. }
  419. }
  420. }
  421. else
  422. {
  423. if (rankType == "DAILY")
  424. {
  425. // 7 days ago
  426. fromDate = DateTime.Now.AddDays(-7).ToString("dd/MM/yyyy 00:00:00");
  427. toDate = DateTime.Now.ToString("dd/MM/yyyy 23:59:59");
  428. }
  429. else if (rankType == "MONTHLY")
  430. {
  431. // 3 months ago
  432. fromDate = DateTime.Now.AddMonths(-3).ToString("dd/MM/yyyy 00:00:00");
  433. toDate = DateTime.Now.ToString("dd/MM/yyyy 23:59:59");
  434. }
  435. }
  436. var request = new RankingHistoryReq
  437. {
  438. msisdn = msisdn, // Pass specific msisdn or null/empty
  439. lang = GetLanguage(),
  440. rankType = rankType,
  441. fromDate = fromDate,
  442. toDate = toDate,
  443. pageNumber = 0,
  444. pageSize = 20
  445. };
  446. var url = GetParameter("Url") + ApiUrlConstant.RankingHistoryUrl;
  447. var resData = await DotnetLib.Rest.RestHandler.SendPostWithAuthen(
  448. log,
  449. url,
  450. request,
  451. token,
  452. token,
  453. "",
  454. GetLanguage()
  455. );
  456. if (resData != null)
  457. {
  458. RankingHistoryRes response = new RankingHistoryRes(resData.data);
  459. if (response.errorCode == CommonErrorCode.Success && response.data != null)
  460. {
  461. return response.data;
  462. }
  463. }
  464. }
  465. catch(Exception ex)
  466. {
  467. log.Error($"LoadRankingInternal ({rankType}): Error", ex);
  468. }
  469. return new List<RankingHistoryItem>();
  470. }
  471. public async Task<IActionResult> DailyRanking(string date = null)
  472. {
  473. if (!IsAuthenticated()) return RedirectToLogin(_configuration);
  474. // For Global Daily Ranking, we don't pass MSISDN implies global list
  475. var data = await LoadRankingInternal("DAILY", null, date);
  476. ViewData["RankingType"] = "DAILY";
  477. ViewData["SelectedDate"] = date;
  478. return View(data);
  479. }
  480. public async Task<IActionResult> MonthlyRanking(string date = null)
  481. {
  482. if (!IsAuthenticated()) return RedirectToLogin(_configuration);
  483. var data = await LoadRankingInternal("MONTHLY", null, date);
  484. ViewData["RankingType"] = "MONTHLY";
  485. ViewData["SelectedDate"] = date;
  486. return View(data);
  487. }
  488. public async Task<IActionResult> Account()
  489. {
  490. if (!IsAuthenticated()) return RedirectToLogin(_configuration);
  491. // Refresh account info to get latest balance
  492. await ReloadAccountInfo();
  493. // Get user info from session
  494. var userInfo = HttpContext.Session.GetComplexData<TokenLoginData>("userInfo");
  495. ViewData["UserInfo"] = userInfo;
  496. ViewData["Msisdn"] = GetMsisdn();
  497. ViewData["WinCoin"] = HttpContext.Session.GetComplexData<decimal?>("winCoin") ?? 0;
  498. ViewData["BetCoin"] = HttpContext.Session.GetComplexData<decimal?>("betCoin") ?? 0;
  499. // TODO: Retrieve actual values for Today/Month from API when available
  500. ViewData["TotalValueToday"] = 0;
  501. ViewData["TotalValueMonth"] = 0;
  502. return View();
  503. }
  504. /// <summary>
  505. /// Đăng xuất
  506. /// </summary>
  507. public IActionResult Logout()
  508. {
  509. ClearCache();
  510. return RedirectToLogin(_configuration);
  511. }
  512. [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
  513. public IActionResult Error()
  514. {
  515. return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
  516. }
  517. /// <summary>
  518. /// Đăng ký gói (Register)
  519. /// </summary>
  520. [HttpPost]
  521. public async Task<IActionResult> Register()
  522. {
  523. // 1. Check Authentication (server-side check)
  524. if (!IsAuthenticated())
  525. {
  526. return Json(new { errorCode = CommonErrorCode.UnauthorizedAccess, message = "Unauthorized" });
  527. }
  528. try
  529. {
  530. // 2. Prepare request data
  531. string? msisdn = GetMsisdn();
  532. string? token = GetToken();
  533. // Default package for daily registration
  534. string packageCode = GetParameter("PackageCodeDaily");
  535. // Default fallback if config missing
  536. if (string.IsNullOrEmpty(packageCode)) packageCode = "SICBO_DAY";
  537. var request = new RegisterReq
  538. {
  539. msisdn = msisdn,
  540. packageCode = packageCode,
  541. lang = GetLanguage()
  542. };
  543. // 3. Call API
  544. var url = GetParameter("Url") + ApiUrlConstant.RegisterUrl;
  545. var resData = await DotnetLib.Rest.RestHandler.SendPostWithAuthen(
  546. log,
  547. url,
  548. request,
  549. token,
  550. token,
  551. "",
  552. GetLanguage()
  553. );
  554. // 4. Handle Response
  555. if (resData != null)
  556. {
  557. RegisterRes response = new RegisterRes(resData.data);
  558. if (response.errorCode == CommonErrorCode.Success)
  559. {
  560. // Refresh info to get latest balance
  561. await ReloadAccountInfo();
  562. // Update response data with latest session info
  563. if (response.data == null) response.data = new RegisterData();
  564. response.data.winCoin = HttpContext.Session.GetComplexData<decimal?>("winCoin");
  565. response.data.betCoin = HttpContext.Session.GetComplexData<decimal?>("betCoin");
  566. return Json(response);
  567. }
  568. else
  569. {
  570. return Json(new { errorCode = response.errorCode, message = response.message });
  571. }
  572. }
  573. return Json(new { errorCode = CommonErrorCode.Error, message = "System Error" });
  574. }
  575. catch (Exception ex)
  576. {
  577. log.Error("Register: Exception", ex);
  578. return Json(new { errorCode = CommonErrorCode.SystemError, message = "Exception" });
  579. }
  580. }
  581. /// <summary>
  582. /// Mua thêm lượt (Buy More)
  583. /// </summary>
  584. [HttpPost]
  585. public async Task<IActionResult> BuyMore([FromBody] BuyMoreReq reqBody)
  586. {
  587. // 1. Check Authentication
  588. if (!IsAuthenticated())
  589. {
  590. return Json(new { errorCode = CommonErrorCode.UnauthorizedAccess, message = "Unauthorized" });
  591. }
  592. try
  593. {
  594. // 2. Prepare Request
  595. string msisdn = GetMsisdn();
  596. string token = GetToken();
  597. var request = new BuyMoreReq
  598. {
  599. msisdn = msisdn,
  600. packageCode = reqBody.packageCode,
  601. lang = GetLanguage()
  602. };
  603. // 3. Call API
  604. var url = GetParameter("Url") + ApiUrlConstant.BuyMoreUrl;
  605. var resData = await DotnetLib.Rest.RestHandler.SendPostWithAuthen(
  606. log,
  607. url,
  608. request,
  609. token,
  610. token,
  611. "",
  612. GetLanguage()
  613. );
  614. // 4. Handle Response
  615. if (resData != null)
  616. {
  617. BuyMoreRes response = new BuyMoreRes(resData.data);
  618. if (response.errorCode == CommonErrorCode.Success)
  619. {
  620. // Refresh info to get latest balance
  621. await ReloadAccountInfo();
  622. // Update response data with latest session info
  623. if (response.data == null) response.data = new BuyMoreData();
  624. response.data.winCoin = HttpContext.Session.GetComplexData<decimal?>("winCoin");
  625. response.data.betCoin = HttpContext.Session.GetComplexData<decimal?>("betCoin");
  626. return Json(response);
  627. }
  628. else
  629. {
  630. return Json(new { errorCode = response.errorCode, message = response.message });
  631. }
  632. }
  633. return Json(new { errorCode = CommonErrorCode.Error, message = "System Error" });
  634. }
  635. catch (Exception ex)
  636. {
  637. log.Error("BuyMore: Exception", ex);
  638. return Json(new { errorCode = CommonErrorCode.SystemError, message = "Exception" });
  639. }
  640. }
  641. /// <summary>
  642. /// Request Withdraw OTP
  643. /// </summary>
  644. [HttpPost]
  645. public async Task<IActionResult> RequestWithdrawOtp([FromBody] ExchangeRequestOtpReq reqBody)
  646. {
  647. if (!IsAuthenticated())
  648. {
  649. return Json(new { errorCode = CommonErrorCode.UnauthorizedAccess, message = "Unauthorized" });
  650. }
  651. try
  652. {
  653. string msisdn = GetMsisdn();
  654. string token = GetToken();
  655. var request = new ExchangeRequestOtpReq
  656. {
  657. msisdn = msisdn,
  658. configId = reqBody.configId,
  659. lang = GetLanguage()
  660. };
  661. // Call API
  662. var url = GetParameter("Url") + ApiUrlConstant.ExchangeRequestOtpUrl;
  663. var resData = await DotnetLib.Rest.RestHandler.SendPostWithAuthen(
  664. log,
  665. url,
  666. request,
  667. token,
  668. token,
  669. "",
  670. GetLanguage()
  671. );
  672. if (resData != null)
  673. {
  674. ExchangeRequestOtpRes response = new ExchangeRequestOtpRes(resData.data);
  675. return Json(new { errorCode = response.errorCode, message = response.message, data = response.data });
  676. }
  677. return Json(new { errorCode = CommonErrorCode.Error, message = "System Error" });
  678. }
  679. catch (Exception ex)
  680. {
  681. log.Error("RequestWithdrawOtp: Exception", ex);
  682. return Json(new { errorCode = CommonErrorCode.SystemError, message = "Exception" });
  683. }
  684. }
  685. /// <summary>
  686. /// Confirm Withdraw OTP
  687. /// </summary>
  688. [HttpPost]
  689. public async Task<IActionResult> ConfirmWithdrawOtp([FromBody] ExchangeVerifyOtpReq reqBody)
  690. {
  691. // 1. Check Authentication
  692. if (!IsAuthenticated())
  693. {
  694. return Json(new { errorCode = CommonErrorCode.UnauthorizedAccess, message = "Unauthorized" });
  695. }
  696. try
  697. {
  698. string msisdn = GetMsisdn();
  699. string token = GetToken();
  700. var request = new ExchangeVerifyOtpReq
  701. {
  702. msisdn = msisdn,
  703. otpCode = reqBody.otpCode,
  704. lang = GetLanguage()
  705. };
  706. // Call API
  707. var url = GetParameter("Url") + ApiUrlConstant.ExchangeVerifyOtpUrl;
  708. var resData = await DotnetLib.Rest.RestHandler.SendPostWithAuthen(
  709. log,
  710. url,
  711. request,
  712. token,
  713. token,
  714. "",
  715. GetLanguage()
  716. );
  717. if (resData != null)
  718. {
  719. ExchangeVerifyOtpRes response = new ExchangeVerifyOtpRes(resData.data);
  720. if (response.errorCode == CommonErrorCode.Success)
  721. {
  722. // Refresh Account Info
  723. await ReloadAccountInfo();
  724. // Get updated fields
  725. var winCoin = HttpContext.Session.GetComplexData<decimal?>("winCoin");
  726. var betCoin = HttpContext.Session.GetComplexData<decimal?>("betCoin");
  727. return Json(new { errorCode = response.errorCode, message = response.message, data = new { winCoin, betCoin } });
  728. }
  729. return Json(new { errorCode = response.errorCode, message = response.message, data = response.data });
  730. }
  731. return Json(new { errorCode = CommonErrorCode.Error, message = "System Error" });
  732. }
  733. catch (Exception ex)
  734. {
  735. log.Error("ConfirmWithdrawOtp: Exception", ex);
  736. return Json(new { errorCode = CommonErrorCode.SystemError, message = "Exception" });
  737. }
  738. }
  739. /// <summary>
  740. /// Lấy danh sách gói cước (Packages)
  741. /// </summary>
  742. [HttpPost]
  743. public async Task<IActionResult> GetPackages()
  744. {
  745. // 1. Check Authentication
  746. if (!IsAuthenticated())
  747. {
  748. return Json(new { errorCode = CommonErrorCode.UnauthorizedAccess, message = "Unauthorized" });
  749. }
  750. var packages = await LoadPackagesInternal();
  751. return Json(new { errorCode = CommonErrorCode.Success, data = packages });
  752. }
  753. }
  754. }