PositionController.cs 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139
  1. using System.Diagnostics;
  2. using Microsoft.AspNetCore.Authorization;
  3. using Microsoft.AspNetCore.Mvc;
  4. using Microsoft.EntityFrameworkCore;
  5. using bitforum.Constants;
  6. using bitforum.Models;
  7. using bitforum.Models.Page.Banner;
  8. using bitforum.Repository;
  9. namespace bitforum.Controllers.Page.Banner
  10. {
  11. [Authorize]
  12. [Route("Page")]
  13. public class PositionController : Controller
  14. {
  15. private readonly ILogger<PositionController> _logger;
  16. private readonly IRedisRepository _redisRepository;
  17. private readonly DefaultDbContext _db;
  18. private readonly string _ViewPath = "~/Views/Page/Banner/Position/Index.cshtml";
  19. public PositionController(ILogger<PositionController> logger, IRedisRepository redisRepository, DefaultDbContext db)
  20. {
  21. _logger = logger;
  22. _redisRepository = redisRepository;
  23. _db = db;
  24. }
  25. [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
  26. public IActionResult Error()
  27. {
  28. return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
  29. }
  30. [HttpGet("Banner")]
  31. public IActionResult Index()
  32. {
  33. ViewBag.BannerPositions = _db.BannerPosition.Include(c => c.BannerItem).ToList();
  34. ViewBag.Total = ViewBag.BannerPositions?.Count ?? 0;
  35. return View(_ViewPath);
  36. }
  37. [HttpPost("Banner")]
  38. public async Task<IActionResult> Save([FromForm] List<BannerPosition> request)
  39. {
  40. using var transaction = await _db.Database.BeginTransactionAsync();
  41. try
  42. {
  43. if (request == null || !request.Any())
  44. {
  45. // 전체 삭제
  46. var bannerPositions = await _db.BannerPosition.ToListAsync();
  47. if (bannerPositions.Any())
  48. {
  49. _db.BannerPosition.RemoveRange(bannerPositions);
  50. await _db.SaveChangesAsync();
  51. }
  52. await transaction.CommitAsync();
  53. return RedirectToAction("Index");
  54. }
  55. if (!ModelState.IsValid)
  56. {
  57. throw new Exception("유효성 검사에 실패하였습니다.");
  58. }
  59. var requestIDs = request.Select(x => x.ID).ToList(); // 요청 데이터의 ID 목록
  60. var existingIDs = await _db.BannerPosition.Select(c => c.ID).ToListAsync(); // 데이터베이스에 존재하는 ID 목록
  61. var IDsToDelete = existingIDs.Except(requestIDs).ToList(); // 삭제 대상 ID: 요청 데이터에 없는 항목
  62. // 삭제 대상 항목 제거
  63. if (IDsToDelete.Any())
  64. {
  65. _db.BannerPosition.RemoveRange(
  66. await _db.BannerPosition.Where(c => IDsToDelete.Contains(c.ID) && !c.BannerItem.Any()).ToListAsync()
  67. );
  68. }
  69. foreach (var row in request)
  70. {
  71. // 중복 확인
  72. if (await _db.BannerPosition.AnyAsync(c => c.Code == row.Code && c.ID != row.ID))
  73. {
  74. throw new Exception($"{row.Code} `Code`는 이미 존재합니다.");
  75. }
  76. if (row.ID == 0)
  77. {
  78. row.CreatedAt = DateTime.UtcNow;
  79. await _db.BannerPosition.AddAsync(row);
  80. }
  81. else
  82. {
  83. var bannerPosition = await _db.BannerPosition.FirstOrDefaultAsync(c => c.ID == row.ID);
  84. if (bannerPosition == null)
  85. {
  86. throw new Exception($"ID {row.ID}에 해당하는 정보가 없습니다.");
  87. }
  88. bannerPosition.Code = row.Code;
  89. bannerPosition.Subject = row.Subject;
  90. bannerPosition.IsActive = row.IsActive;
  91. bannerPosition.UpdatedAt = DateTime.UtcNow;
  92. _db.BannerPosition.Update(bannerPosition);
  93. }
  94. }
  95. await transaction.CommitAsync();
  96. int affectedRows = await _db.SaveChangesAsync();
  97. if (affectedRows <= 0)
  98. {
  99. throw new Exception("저장 중 오류가 발생했습니다.");
  100. }
  101. await _redisRepository.DeleteAsync(RedisConst.BannerKey);
  102. string message = "배너 위치가 저장되었습니다.";
  103. TempData["SuccessMessage"] = message;
  104. _logger.LogInformation(message);
  105. return RedirectToAction("Index");
  106. }
  107. catch (Exception e)
  108. {
  109. await transaction.RollbackAsync();
  110. TempData["ErrorMessages"] = e.Message;
  111. _logger.LogError(e, e.Message);
  112. return Index();
  113. }
  114. }
  115. }
  116. }