PopupController.cs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293
  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 bitforum.Helpers;
  8. using bitforum.Services;
  9. using bitforum.Repository;
  10. using bitforum.Constants;
  11. namespace bitforum.Controllers.Page
  12. {
  13. [Authorize]
  14. [Route("Page")]
  15. public class PopupController : Controller
  16. {
  17. private readonly ILogger<PopupController> _logger;
  18. private readonly IFileUploadService _fileUploadService;
  19. private readonly IRedisRepository _redisRepository;
  20. private readonly DefaultDbContext _db;
  21. private readonly string _IndexViewPath = "~/Views/Page/Popup/Index.cshtml";
  22. private readonly string _WriteViewPath = "~/Views/Page/Popup/Write.cshtml";
  23. private readonly string _EditViewPath = "~/Views/Page/Popup/Edit.cshtml";
  24. public PopupController(ILogger<PopupController> logger, IFileUploadService fileUploadService, IRedisRepository redisRepository, DefaultDbContext db)
  25. {
  26. _logger = logger;
  27. _fileUploadService = fileUploadService;
  28. _redisRepository = redisRepository;
  29. _db = db;
  30. }
  31. [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
  32. public IActionResult Error()
  33. {
  34. return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
  35. }
  36. [HttpGet("Popup")]
  37. public IActionResult Index([FromQuery] int page = 1)
  38. {
  39. var popups = _db.Popup.OrderByDescending(c => c.ID).ToList();
  40. var data = new List<object>();
  41. if (popups.Count > 0)
  42. {
  43. foreach (var row in popups)
  44. {
  45. string Expired = row switch
  46. {
  47. { StartAt: not null, EndAt: not null } => $"{row.StartAt.GetDateAt()} ~ {row.EndAt.GetDateAt()}",
  48. { StartAt: not null, EndAt: null } => $"{row.StartAt.GetDateAt()}",
  49. { StartAt: null, EndAt: not null } => $"~ {row.EndAt.GetDateAt()}",
  50. _ => "[무기한]"
  51. };
  52. var entry = new
  53. {
  54. row.ID,
  55. row.Subject,
  56. row.Content,
  57. row.Link,
  58. Expired,
  59. row.Order,
  60. IsActive = (row.IsActive ? 'Y' : 'N'),
  61. Views = row.Views.ToString("N0"),
  62. UpdatedAt = row.UpdatedAt.GetDateAt(),
  63. CreatedAt = row.CreatedAt.GetDateAt(),
  64. EditURL = $"/Page/Popup/{row.ID}/Edit",
  65. DeleteURL = $"/Page/Popup/{row.ID}/Delete"
  66. };
  67. data.Add(entry);
  68. }
  69. }
  70. ViewBag.Data = data;
  71. ViewBag.Total = (data?.Count ?? 0);
  72. ViewBag.Pagination = new Pagination(ViewBag.Total, page, 20, null);
  73. return View(_IndexViewPath);
  74. }
  75. [HttpGet("Popup/Write")]
  76. public IActionResult Write()
  77. {
  78. return View(_WriteViewPath);
  79. }
  80. [HttpPost("Popup/Create")]
  81. public async Task<IActionResult> Create(Popup request)
  82. {
  83. try
  84. {
  85. if (!ModelState.IsValid)
  86. {
  87. throw new Exception("유효성 검사에 실패하였습니다.");
  88. }
  89. if (request.EndAt < request.StartAt)
  90. {
  91. throw new Exception("사용 기간을 확인해주세요.");
  92. }
  93. request.Content = _fileUploadService.UploadEditorAsync(request.Content, null, UploadFolder.Popup).Result;
  94. request.UpdatedAt = null;
  95. request.CreatedAt = DateTime.UtcNow;
  96. _db.Popup.Add(request);
  97. int affectedRows = await _db.SaveChangesAsync();
  98. if (affectedRows <= 0)
  99. {
  100. throw new Exception("팝업 등록 중 오류가 발생했습니다.");
  101. }
  102. await _redisRepository.DeleteAsync(RedisConst.PopupKey);
  103. string message = "팝업이 등록되었습니다.";
  104. TempData["SuccessMessage"] = message;
  105. _logger.LogInformation(message);
  106. return Index();
  107. }
  108. catch (Exception e)
  109. {
  110. TempData["ErrorMessages"] = e.Message;
  111. _logger.LogError(e, e.Message);
  112. return View(_WriteViewPath, request);
  113. }
  114. }
  115. [HttpGet("Popup/{id}/Edit")]
  116. public async Task<IActionResult> Edit(int id)
  117. {
  118. try
  119. {
  120. if (id <= 0)
  121. {
  122. throw new Exception("유효하지 않은 접근입니다.");
  123. }
  124. var popup = await _db.Popup.FirstAsync(c => c.ID == id);
  125. if (popup is null)
  126. {
  127. throw new Exception("팝업 정보를 찾을 수 없습니다.");
  128. }
  129. return View(_EditViewPath, popup);
  130. }
  131. catch (Exception e)
  132. {
  133. TempData["ErrorMessages"] = e.Message;
  134. _logger.LogError(e, e.Message);
  135. return Index();
  136. }
  137. }
  138. [HttpPost("Popup/Update")]
  139. public async Task<IActionResult> Update(Popup request)
  140. {
  141. try
  142. {
  143. if (!ModelState.IsValid)
  144. {
  145. throw new Exception("유효성 검사에 실패하였습니다.");
  146. }
  147. if (request.EndAt < request.StartAt)
  148. {
  149. throw new Exception("사용 기간을 확인해주세요.");
  150. }
  151. var popup = await _db.Popup.FirstAsync(c => c.ID == request.ID);
  152. if (popup is null)
  153. {
  154. throw new Exception("팝업 정보를 찾을 수 없습니다.");
  155. }
  156. popup.Subject = request.Subject;
  157. popup.Content = _fileUploadService.UploadEditorAsync(request.Content, popup.Content, UploadFolder.Popup).Result;
  158. popup.IsActive = request.IsActive;
  159. popup.Link = request.Link;
  160. popup.Order = request.Order;
  161. popup.StartAt = request.StartAt;
  162. popup.EndAt = request.EndAt;
  163. popup.UpdatedAt = DateTime.UtcNow;
  164. int affectedRows = await _db.SaveChangesAsync();
  165. if (affectedRows <= 0)
  166. {
  167. throw new Exception("팝업 수정 중 오류가 발생했습니다.");
  168. }
  169. await _redisRepository.DeleteAsync(RedisConst.PopupKey);
  170. string message = $"{popup.ID}번 팝업이 수정되었습니다.";
  171. TempData["SuccessMessage"] = message;
  172. _logger.LogInformation(message);
  173. return await Edit(request.ID);
  174. }
  175. catch (Exception e)
  176. {
  177. TempData["ErrorMessages"] = e.Message;
  178. _logger.LogError(e, e.Message);
  179. return View(_EditViewPath, request);
  180. }
  181. }
  182. [HttpGet("Popup/{id}/Delete")]
  183. public async Task<IActionResult> Delete(int id)
  184. {
  185. try
  186. {
  187. if (id <= 0)
  188. {
  189. throw new Exception("유효하지 않은 문서 ID입니다.");
  190. }
  191. var popup = await _db.Popup.FindAsync(id);
  192. if (popup == null)
  193. {
  194. throw new Exception("팝업 정보를 찾을 수 없습니다.");
  195. }
  196. _db.Popup.Remove(popup);
  197. int affectedRows = await _db.SaveChangesAsync();
  198. if (affectedRows <= 0)
  199. {
  200. throw new Exception("팝업 삭제 중 오류가 발생했습니다.");
  201. }
  202. await _fileUploadService.CleanUpEditorImagesAsync(popup.Content);
  203. await _redisRepository.DeleteAsync(RedisConst.PopupKey);
  204. string message = "팝업이 삭제되었습니다.";
  205. TempData["SuccessMessage"] = message;
  206. _logger.LogInformation(message);
  207. }
  208. catch (Exception e)
  209. {
  210. TempData["ErrorMessages"] = e.Message;
  211. _logger.LogError(e, e.Message);
  212. }
  213. return Index();
  214. }
  215. [HttpPost("Popup/Delete")]
  216. public async Task<IActionResult> Delete([FromForm] int[] ids)
  217. {
  218. try
  219. {
  220. if (ids == null || ids.Length <= 0)
  221. {
  222. throw new Exception("유효하지 않은 접근입니다.");
  223. }
  224. foreach (var id in ids)
  225. {
  226. var popup = await _db.Popup.FindAsync(id);
  227. if (popup == null)
  228. {
  229. throw new Exception($"{id}번 팝업 정보를 찾을 수 없습니다.");
  230. }
  231. _db.Popup.Remove(popup);
  232. int affectedRows = await _db.SaveChangesAsync();
  233. if (affectedRows <= 0)
  234. {
  235. throw new Exception($"{id}번 팝업 삭제 중 오류가 발생했습니다.");
  236. }
  237. await _fileUploadService.CleanUpEditorImagesAsync(popup.Content);
  238. await _redisRepository.DeleteAsync(RedisConst.PopupKey);
  239. }
  240. string message = $"{ids.Length}건의 팝업이 삭제되었습니다.";
  241. TempData["SuccessMessage"] = message;
  242. _logger.LogInformation(message);
  243. }
  244. catch (Exception e)
  245. {
  246. TempData["ErrorMessages"] = e.Message;
  247. _logger.LogError(e, e.Message);
  248. }
  249. return Index();
  250. }
  251. }
  252. }