PopupController.cs 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244
  1. using System.Diagnostics;
  2. using Microsoft.AspNetCore.Authorization;
  3. using Microsoft.AspNetCore.Mvc;
  4. using Microsoft.EntityFrameworkCore;
  5. using bitforum.Models;
  6. using bitforum.Models.Page;
  7. using Microsoft.AspNetCore.Mvc.Rendering;
  8. namespace bitforum.Controllers.Page
  9. {
  10. [Authorize]
  11. [Route("Page")]
  12. public class PopupController : Controller
  13. {
  14. private readonly ILogger<PopupController> _logger;
  15. private readonly DefaultDbContext _db;
  16. private readonly IConfiguration _config;
  17. private readonly string _IndexViewPath = "~/Views/Page/Popup/Index.cshtml";
  18. private readonly string _WriteViewPath = "~/Views/Page/Popup/Write.cshtml";
  19. private readonly string _EditViewPath = "~/Views/Page/Popup/Edit.cshtml";
  20. public PopupController(ILogger<PopupController> logger, DefaultDbContext db, IConfiguration config)
  21. {
  22. _logger = logger;
  23. _db = db;
  24. _config = config;
  25. }
  26. [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
  27. public IActionResult Error()
  28. {
  29. return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
  30. }
  31. [HttpGet("Popup")]
  32. public IActionResult Index([FromQuery] int page = 1)
  33. {
  34. ViewBag.Popups = _db.Popup.OrderByDescending(c => c.ID).ToList();
  35. ViewBag.Total = ViewBag.Popups.Count;
  36. ViewBag.Pagination = new Pagination(ViewBag.Total, page, 20, null);
  37. return View(_IndexViewPath);
  38. }
  39. [HttpGet("Popup/Write")]
  40. public IActionResult Write()
  41. {
  42. return View(_WriteViewPath);
  43. }
  44. [HttpPost("Popup/Create")]
  45. public async Task<IActionResult> Create(Popup request)
  46. {
  47. try
  48. {
  49. if (!ModelState.IsValid)
  50. {
  51. throw new Exception("유효성 검사에 실패하였습니다.");
  52. }
  53. if (request.EndAt < request.StartAt)
  54. {
  55. throw new Exception("사용 기간을 확인해주세요.");
  56. }
  57. request.UpdatedAt = null;
  58. request.CreatedAt = DateTime.Now;
  59. _db.Popup.Add(request);
  60. int affectedRows = await _db.SaveChangesAsync();
  61. if (affectedRows <= 0)
  62. {
  63. throw new Exception("팝업 등록 중 오류가 발생했습니다.");
  64. }
  65. string message = "팝업이 정상적으로 등록되었습니다.";
  66. TempData["SuccessMessage"] = message;
  67. _logger.LogInformation(message);
  68. return RedirectToAction("Index");
  69. }
  70. catch (Exception e)
  71. {
  72. _logger.LogError(e, e.Message);
  73. TempData["ErrorMessages"] = e.Message;
  74. return View(_WriteViewPath, request);
  75. }
  76. }
  77. [HttpGet("Popup/{id}/Edit")]
  78. public async Task<IActionResult> Edit(int id)
  79. {
  80. try
  81. {
  82. if (id <= 0)
  83. {
  84. throw new Exception("유효하지 않은 접근입니다.");
  85. }
  86. var popup = await _db.Popup.FirstAsync(c => c.ID == id);
  87. if (popup is null)
  88. {
  89. throw new Exception("팝업 정보를 찾을 수 없습니다.");
  90. }
  91. return View(_EditViewPath, popup);
  92. }
  93. catch (Exception e)
  94. {
  95. _logger.LogError(e, e.Message);
  96. TempData["ErrorMessages"] = e.Message;
  97. return RedirectToAction("Index");
  98. }
  99. }
  100. [HttpPost("Popup/Update")]
  101. public async Task<IActionResult> Update(Popup request)
  102. {
  103. try
  104. {
  105. if (!ModelState.IsValid)
  106. {
  107. throw new Exception("유효성 검사에 실패하였습니다.");
  108. }
  109. if (request.EndAt < request.StartAt)
  110. {
  111. throw new Exception("사용 기간을 확인해주세요.");
  112. }
  113. var popup = await _db.Popup.FirstAsync(c => c.ID == request.ID);
  114. if (popup is null)
  115. {
  116. throw new Exception("팝업 정보를 찾을 수 없습니다.");
  117. }
  118. popup.Subject = request.Subject;
  119. popup.Content = request.Content;
  120. popup.IsActive = request.IsActive;
  121. popup.Link = request.Link;
  122. popup.Order = request.Order;
  123. popup.StartAt = request.StartAt;
  124. popup.EndAt = request.EndAt;
  125. popup.UpdatedAt = DateTime.Now;
  126. _db.Popup.Update(popup);
  127. int affectedRows = await _db.SaveChangesAsync();
  128. if (affectedRows <= 0)
  129. {
  130. throw new Exception("팝업 수정 중 오류가 발생했습니다.");
  131. }
  132. string message = "팝업이 정상적으로 수정되었습니다.";
  133. TempData["SuccessMessage"] = message;
  134. _logger.LogInformation(message);
  135. return RedirectToAction("Edit", new { request.ID });
  136. }
  137. catch (Exception e)
  138. {
  139. _logger.LogError(e, e.Message);
  140. TempData["ErrorMessages"] = e.Message;
  141. return View(_EditViewPath, request);
  142. }
  143. }
  144. [HttpGet("Popup/Delete/{id}")]
  145. public async Task<IActionResult> Delete(int id)
  146. {
  147. try
  148. {
  149. if (id <= 0)
  150. {
  151. throw new Exception("유효하지 않은 문서 ID입니다.");
  152. }
  153. var popup = await _db.Popup.FindAsync(id);
  154. if (popup == null)
  155. {
  156. throw new Exception("팝업 정보를 찾을 수 없습니다.");
  157. }
  158. _db.Popup.Remove(popup);
  159. int affectedRows = await _db.SaveChangesAsync();
  160. if (affectedRows <= 0)
  161. {
  162. throw new Exception("팝업 삭제 중 오류가 발생했습니다.");
  163. }
  164. string message = "팝업이 정상적으로 삭제되었습니다.";
  165. TempData["SuccessMessage"] = message;
  166. _logger.LogInformation(message);
  167. return RedirectToAction("Index");
  168. }
  169. catch (Exception e)
  170. {
  171. _logger.LogError(e, e.Message);
  172. TempData["ErrorMessages"] = e.Message;
  173. return Index();
  174. }
  175. }
  176. [HttpPost("Popup/Delete")]
  177. public async Task<IActionResult> Delete([FromForm] int[] ids)
  178. {
  179. try
  180. {
  181. if (ids == null || ids.Length <= 0)
  182. {
  183. throw new Exception("유효하지 않은 접근입니다.");
  184. }
  185. foreach (var id in ids)
  186. {
  187. var popup = await _db.Popup.FindAsync(id);
  188. if (popup == null)
  189. {
  190. throw new Exception("팝업 정보를 찾을 수 없습니다.");
  191. }
  192. _db.Popup.Remove(popup);
  193. int affectedRows = await _db.SaveChangesAsync();
  194. if (affectedRows <= 0)
  195. {
  196. throw new Exception($"{id}번호의 팝업 삭제 중 오류가 발생했습니다.");
  197. }
  198. }
  199. string message = "팝업이 정상적으로 삭제되었습니다.";
  200. TempData["SuccessMessage"] = message;
  201. _logger.LogInformation(message);
  202. return RedirectToAction("Index");
  203. }
  204. catch (Exception e)
  205. {
  206. _logger.LogError(e, e.Message);
  207. TempData["ErrorMessages"] = e.Message;
  208. return RedirectToAction("Index");
  209. }
  210. }
  211. }
  212. }