HomeController.cs 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933
  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")
  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
  476. {
  477. // DAILY - Exact Date
  478. // Convert yyyy-MM-dd to dd/MM/yyyy HH:mm:ss
  479. // Input expected: yyyy-MM-dd (from HTML5 date input)
  480. if (DateTime.TryParseExact(specificDate, "yyyy-MM-dd", System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None, out DateTime parsedDate))
  481. {
  482. fromDate = parsedDate.ToString("dd/MM/yyyy 00:00:00");
  483. toDate = parsedDate.ToString("dd/MM/yyyy 23:59:59");
  484. }
  485. else
  486. {
  487. // Fallback: try to just append time if it looks like a date
  488. fromDate = specificDate + " 00:00:00";
  489. toDate = specificDate + " 23:59:59";
  490. }
  491. }
  492. }
  493. else
  494. {
  495. if (rankType == "DAILY")
  496. {
  497. // 7 days ago
  498. fromDate = DateTime.Now.AddDays(-7).ToString("dd/MM/yyyy 00:00:00");
  499. toDate = DateTime.Now.ToString("dd/MM/yyyy 23:59:59");
  500. }
  501. else if (rankType == "MONTHLY")
  502. {
  503. // 3 months ago
  504. fromDate = DateTime.Now.AddMonths(-3).ToString("dd/MM/yyyy 00:00:00");
  505. toDate = DateTime.Now.ToString("dd/MM/yyyy 23:59:59");
  506. }
  507. }
  508. var request = new RankingHistoryReq
  509. {
  510. msisdn = msisdn, // Pass specific msisdn or null/empty
  511. lang = GetLanguage(),
  512. rankType = rankType,
  513. fromDate = fromDate,
  514. toDate = toDate,
  515. pageNumber = 0,
  516. pageSize = 20
  517. };
  518. var url = GetParameter("Url") + ApiUrlConstant.RankingHistoryUrl;
  519. var resData = await DotnetLib.Rest.RestHandler.SendPostWithAuthen(
  520. log,
  521. url,
  522. request,
  523. token,
  524. token,
  525. "",
  526. GetLanguage()
  527. );
  528. if (resData != null)
  529. {
  530. RankingHistoryRes response = new RankingHistoryRes(resData.data);
  531. if (response.errorCode == CommonErrorCode.Success && response.data != null)
  532. {
  533. return response.data;
  534. }
  535. }
  536. }
  537. catch(Exception ex)
  538. {
  539. log.Error($"LoadRankingInternal ({rankType}): Error", ex);
  540. }
  541. return new List<RankingHistoryItem>();
  542. }
  543. public async Task<IActionResult> DailyRanking(string date = null)
  544. {
  545. if (!IsAuthenticated()) return RedirectToLogin(_configuration);
  546. // For Global Daily Ranking, we don't pass MSISDN implies global list
  547. var data = await LoadRankingInternal("DAILY", null, date);
  548. ViewData["RankingType"] = "DAILY";
  549. ViewData["SelectedDate"] = date;
  550. return View(data);
  551. }
  552. public async Task<IActionResult> MonthlyRanking(string date = null)
  553. {
  554. if (!IsAuthenticated()) return RedirectToLogin(_configuration);
  555. var data = await LoadRankingInternal("MONTHLY", null, date);
  556. ViewData["RankingType"] = "MONTHLY";
  557. ViewData["SelectedDate"] = date;
  558. return View(data);
  559. }
  560. public async Task<IActionResult> Account()
  561. {
  562. if (!IsAuthenticated()) return RedirectToLogin(_configuration);
  563. // Refresh account info to get latest balance
  564. await ReloadAccountInfo();
  565. // Get user info from session
  566. var userInfo = HttpContext.Session.GetComplexData<TokenLoginData>("userInfo");
  567. ViewData["UserInfo"] = userInfo;
  568. ViewData["Msisdn"] = GetMsisdn();
  569. ViewData["WinCoin"] = HttpContext.Session.GetComplexData<decimal?>("winCoin") ?? 0;
  570. ViewData["BetCoin"] = HttpContext.Session.GetComplexData<decimal?>("betCoin") ?? 0;
  571. // TODO: Retrieve actual values for Today/Month from API when available
  572. ViewData["TotalValueToday"] = 0;
  573. ViewData["TotalValueMonth"] = 0;
  574. return View();
  575. }
  576. /// <summary>
  577. /// Đăng xuất
  578. /// </summary>
  579. public IActionResult Logout()
  580. {
  581. ClearCache();
  582. return RedirectToLogin(_configuration);
  583. }
  584. [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
  585. public IActionResult Error()
  586. {
  587. return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
  588. }
  589. /// <summary>
  590. /// Đăng ký gói (Register)
  591. /// </summary>
  592. [HttpPost]
  593. public async Task<IActionResult> Register()
  594. {
  595. // 1. Check Authentication (server-side check)
  596. if (!IsAuthenticated())
  597. {
  598. return Json(new { errorCode = CommonErrorCode.UnauthorizedAccess, message = "Unauthorized" });
  599. }
  600. try
  601. {
  602. // 2. Prepare request data
  603. string? msisdn = GetMsisdn();
  604. string? token = GetToken();
  605. // Default package for daily registration
  606. string packageCode = GetParameter("PackageCodeDaily");
  607. // Default fallback if config missing
  608. if (string.IsNullOrEmpty(packageCode)) packageCode = "SICBO_DAY";
  609. var request = new RegisterReq
  610. {
  611. msisdn = msisdn,
  612. packageCode = packageCode,
  613. lang = GetLanguage()
  614. };
  615. // 3. Call API
  616. var url = GetParameter("Url") + ApiUrlConstant.RegisterUrl;
  617. var resData = await DotnetLib.Rest.RestHandler.SendPostWithAuthen(
  618. log,
  619. url,
  620. request,
  621. token,
  622. token,
  623. "",
  624. GetLanguage()
  625. );
  626. // 4. Handle Response
  627. if (resData != null)
  628. {
  629. RegisterRes response = new RegisterRes(resData.data);
  630. if (response.errorCode == CommonErrorCode.Success)
  631. {
  632. // Refresh info to get latest balance
  633. await ReloadAccountInfo();
  634. // Update response data with latest session info
  635. if (response.data == null) response.data = new RegisterData();
  636. response.data.winCoin = HttpContext.Session.GetComplexData<decimal?>("winCoin");
  637. response.data.betCoin = HttpContext.Session.GetComplexData<decimal?>("betCoin");
  638. return Json(response);
  639. }
  640. else
  641. {
  642. return Json(new { errorCode = response.errorCode, message = response.message });
  643. }
  644. }
  645. return Json(new { errorCode = CommonErrorCode.Error, message = "System Error" });
  646. }
  647. catch (Exception ex)
  648. {
  649. log.Error("Register: Exception", ex);
  650. return Json(new { errorCode = CommonErrorCode.SystemError, message = "Exception" });
  651. }
  652. }
  653. /// <summary>
  654. /// Mua thêm lượt (Buy More)
  655. /// </summary>
  656. [HttpPost]
  657. public async Task<IActionResult> BuyMore([FromBody] BuyMoreReq reqBody)
  658. {
  659. // 1. Check Authentication
  660. if (!IsAuthenticated())
  661. {
  662. return Json(new { errorCode = CommonErrorCode.UnauthorizedAccess, message = "Unauthorized" });
  663. }
  664. try
  665. {
  666. // 2. Prepare Request
  667. string msisdn = GetMsisdn();
  668. string token = GetToken();
  669. var request = new BuyMoreReq
  670. {
  671. msisdn = msisdn,
  672. packageCode = reqBody.packageCode,
  673. lang = GetLanguage()
  674. };
  675. // 3. Call API
  676. var url = GetParameter("Url") + ApiUrlConstant.BuyMoreUrl;
  677. var resData = await DotnetLib.Rest.RestHandler.SendPostWithAuthen(
  678. log,
  679. url,
  680. request,
  681. token,
  682. token,
  683. "",
  684. GetLanguage()
  685. );
  686. // 4. Handle Response
  687. if (resData != null)
  688. {
  689. BuyMoreRes response = new BuyMoreRes(resData.data);
  690. if (response.errorCode == CommonErrorCode.Success)
  691. {
  692. // Refresh info to get latest balance
  693. await ReloadAccountInfo();
  694. // Update response data with latest session info
  695. if (response.data == null) response.data = new BuyMoreData();
  696. response.data.winCoin = HttpContext.Session.GetComplexData<decimal?>("winCoin");
  697. response.data.betCoin = HttpContext.Session.GetComplexData<decimal?>("betCoin");
  698. return Json(response);
  699. }
  700. else
  701. {
  702. return Json(new { errorCode = response.errorCode, message = response.message });
  703. }
  704. }
  705. return Json(new { errorCode = CommonErrorCode.Error, message = "System Error" });
  706. }
  707. catch (Exception ex)
  708. {
  709. log.Error("BuyMore: Exception", ex);
  710. return Json(new { errorCode = CommonErrorCode.SystemError, message = "Exception" });
  711. }
  712. }
  713. /// <summary>
  714. /// Request Withdraw OTP
  715. /// </summary>
  716. [HttpPost]
  717. public async Task<IActionResult> RequestWithdrawOtp([FromBody] ExchangeRequestOtpReq reqBody)
  718. {
  719. if (!IsAuthenticated())
  720. {
  721. return Json(new { errorCode = CommonErrorCode.UnauthorizedAccess, message = "Unauthorized" });
  722. }
  723. try
  724. {
  725. string msisdn = GetMsisdn();
  726. string token = GetToken();
  727. var request = new ExchangeRequestOtpReq
  728. {
  729. msisdn = msisdn,
  730. configId = reqBody.configId,
  731. lang = GetLanguage()
  732. };
  733. // Call API
  734. var url = GetParameter("Url") + ApiUrlConstant.ExchangeRequestOtpUrl;
  735. var resData = await DotnetLib.Rest.RestHandler.SendPostWithAuthen(
  736. log,
  737. url,
  738. request,
  739. token,
  740. token,
  741. "",
  742. GetLanguage()
  743. );
  744. if (resData != null)
  745. {
  746. ExchangeRequestOtpRes response = new ExchangeRequestOtpRes(resData.data);
  747. return Json(new { errorCode = response.errorCode, message = response.message, data = response.data });
  748. }
  749. return Json(new { errorCode = CommonErrorCode.Error, message = "System Error" });
  750. }
  751. catch (Exception ex)
  752. {
  753. log.Error("RequestWithdrawOtp: Exception", ex);
  754. return Json(new { errorCode = CommonErrorCode.SystemError, message = "Exception" });
  755. }
  756. }
  757. /// <summary>
  758. /// Confirm Withdraw OTP
  759. /// </summary>
  760. [HttpPost]
  761. public async Task<IActionResult> ConfirmWithdrawOtp([FromBody] ExchangeVerifyOtpReq reqBody)
  762. {
  763. // 1. Check Authentication
  764. if (!IsAuthenticated())
  765. {
  766. return Json(new { errorCode = CommonErrorCode.UnauthorizedAccess, message = "Unauthorized" });
  767. }
  768. try
  769. {
  770. string msisdn = GetMsisdn();
  771. string token = GetToken();
  772. var request = new ExchangeVerifyOtpReq
  773. {
  774. msisdn = msisdn,
  775. otpCode = reqBody.otpCode,
  776. lang = GetLanguage()
  777. };
  778. // Call API
  779. var url = GetParameter("Url") + ApiUrlConstant.ExchangeVerifyOtpUrl;
  780. var resData = await DotnetLib.Rest.RestHandler.SendPostWithAuthen(
  781. log,
  782. url,
  783. request,
  784. token,
  785. token,
  786. "",
  787. GetLanguage()
  788. );
  789. if (resData != null)
  790. {
  791. ExchangeVerifyOtpRes response = new ExchangeVerifyOtpRes(resData.data);
  792. if (response.errorCode == CommonErrorCode.Success)
  793. {
  794. // Refresh Account Info
  795. await ReloadAccountInfo();
  796. // Get updated fields
  797. var winCoin = HttpContext.Session.GetComplexData<decimal?>("winCoin");
  798. var betCoin = HttpContext.Session.GetComplexData<decimal?>("betCoin");
  799. return Json(new { errorCode = response.errorCode, message = response.message, data = new { winCoin, betCoin } });
  800. }
  801. return Json(new { errorCode = response.errorCode, message = response.message, data = response.data });
  802. }
  803. return Json(new { errorCode = CommonErrorCode.Error, message = "System Error" });
  804. }
  805. catch (Exception ex)
  806. {
  807. log.Error("ConfirmWithdrawOtp: Exception", ex);
  808. return Json(new { errorCode = CommonErrorCode.SystemError, message = "Exception" });
  809. }
  810. }
  811. /// <summary>
  812. /// Lấy danh sách gói cước (Packages)
  813. /// </summary>
  814. [HttpPost]
  815. public async Task<IActionResult> GetPackages()
  816. {
  817. // 1. Check Authentication
  818. if (!IsAuthenticated())
  819. {
  820. return Json(new { errorCode = CommonErrorCode.UnauthorizedAccess, message = "Unauthorized" });
  821. }
  822. var packages = await LoadPackagesInternal();
  823. return Json(new { errorCode = CommonErrorCode.Success, data = packages });
  824. }
  825. }
  826. }