Skip to content

Commit

Permalink
status category
Browse files Browse the repository at this point in the history
  • Loading branch information
Longlay12 committed Sep 18, 2024
1 parent 6b29f64 commit 8a6e24b
Show file tree
Hide file tree
Showing 6 changed files with 91 additions and 103 deletions.
40 changes: 18 additions & 22 deletions src/main/java/com/fjb/sunrise/controllers/CategoryController.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,8 @@

import com.fjb.sunrise.dtos.base.DataTableInputDTO;
import com.fjb.sunrise.dtos.requests.CategoryCreateDto;
import com.fjb.sunrise.dtos.requests.CategoryStatusDto;
import com.fjb.sunrise.dtos.requests.CategoryUpdateDto;
import com.fjb.sunrise.dtos.responses.CategoryFullPageResponse;
import com.fjb.sunrise.dtos.responses.CategoryResponseDto;
import com.fjb.sunrise.enums.EStatus;
import com.fjb.sunrise.mappers.CategoryMapper;
import com.fjb.sunrise.models.Category;
import com.fjb.sunrise.services.CategoryService;
Expand All @@ -15,6 +12,7 @@
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
Expand Down Expand Up @@ -114,30 +112,28 @@ public ModelAndView updateCategory(@PathVariable("id") Long id, @ModelAttribute(

//change-status

@PostMapping("/delete/{id}")
public ModelAndView changeStatusCategory(@PathVariable("id") Long id, @ModelAttribute("categoryStatus")
@Valid CategoryStatusDto categoryStatusDto,
BindingResult bindingResult,
RedirectAttributes redirectAttributes) {
ModelAndView modelAndView = new ModelAndView();
CategoryResponseDto category = categoryService.getCategoryById(id);
if (bindingResult.hasErrors()) {
return modelAndView;
@PreAuthorize("hasRole('ROLE_ADMIN')")
@GetMapping("/deactivate/{id}")
public String disableCategory(@PathVariable("id") Long id, RedirectAttributes redirectAttributes) {
try {
categoryService.disableCategory(id);
redirectAttributes.addFlashAttribute("message", "Category deactivated successfully");
} catch (EntityNotFoundException e) {
redirectAttributes.addFlashAttribute(Constants.ErrorCode.ERROR, e.getMessage());
}
return Constants.ApiConstant.CATEGORY_INDEX;
}

@PreAuthorize("hasRole('ROLE_ADMIN')")
@GetMapping("/activate/{id}")
public String enableCategory(@PathVariable("id") Long id, RedirectAttributes redirectAttributes) {
try {
if (category.getStatus() == EStatus.NOT_ACTIVE) {
categoryService.enableCategory(id);
redirectAttributes.addFlashAttribute("message", "Category enabled successfully.");
} else if (category.getStatus() == EStatus.ACTIVE) {
categoryService.disableCategory(id);
redirectAttributes.addFlashAttribute("message", "Category disabled successfully.");
}
categoryService.enableCategory(id);
redirectAttributes.addFlashAttribute("message", "Category activated successfully");
} catch (EntityNotFoundException e) {
redirectAttributes.addFlashAttribute("error", e.getMessage());
}
categoryService.saveStatusCategory(id, categoryStatusDto);
modelAndView.setViewName(Constants.ApiConstant.CATEGORY_REDIRECT);
return modelAndView;
return Constants.ApiConstant.CATEGORY_INDEX;
}

//get-list
Expand Down
14 changes: 0 additions & 14 deletions src/main/java/com/fjb/sunrise/dtos/requests/CategoryStatusDto.java

This file was deleted.

2 changes: 0 additions & 2 deletions src/main/java/com/fjb/sunrise/mappers/CategoryMapper.java
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package com.fjb.sunrise.mappers;

import com.fjb.sunrise.dtos.requests.CategoryCreateDto;
import com.fjb.sunrise.dtos.requests.CategoryStatusDto;
import com.fjb.sunrise.dtos.requests.CategoryUpdateDto;
import com.fjb.sunrise.dtos.responses.CategoryResponseDto;
import com.fjb.sunrise.models.Category;
Expand All @@ -20,7 +19,6 @@ public interface CategoryMapper {

Category updateCategory(@MappingTarget Category category, CategoryUpdateDto categoryUpdateDto);

Category statusCategory(@MappingTarget Category category, CategoryStatusDto categoryStatusDto);

List<CategoryResponseDto> listCategoryToListCategoryPageResponse(List<Category> categories);
}
7 changes: 2 additions & 5 deletions src/main/java/com/fjb/sunrise/services/CategoryService.java
Original file line number Diff line number Diff line change
@@ -1,24 +1,21 @@
package com.fjb.sunrise.services;


import com.fjb.sunrise.dtos.base.DataTableInputDTO;
import com.fjb.sunrise.dtos.requests.CategoryCreateDto;
import com.fjb.sunrise.dtos.requests.CategoryStatusDto;
import com.fjb.sunrise.dtos.requests.CategoryUpdateDto;
import com.fjb.sunrise.dtos.responses.CategoryResponseDto;
import com.fjb.sunrise.models.Category;
import jakarta.transaction.Transactional;
import java.util.List;
import org.springframework.data.domain.Page;



public interface CategoryService {
CategoryResponseDto createCategory(CategoryCreateDto categoryCreateDto);

CategoryResponseDto updateCategory(Long id, CategoryUpdateDto categoryUpdateDto);

@Transactional
CategoryResponseDto saveStatusCategory(Long id, CategoryStatusDto categoryStatusDto);

void disableCategory(Long id);

void enableCategory(Long id);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@

import com.fjb.sunrise.dtos.base.DataTableInputDTO;
import com.fjb.sunrise.dtos.requests.CategoryCreateDto;
import com.fjb.sunrise.dtos.requests.CategoryStatusDto;
import com.fjb.sunrise.dtos.requests.CategoryUpdateDto;
import com.fjb.sunrise.dtos.responses.CategoryResponseDto;
import com.fjb.sunrise.enums.EStatus;
Expand All @@ -12,6 +11,7 @@
import com.fjb.sunrise.repositories.CategoryRepository;
import com.fjb.sunrise.repositories.UserRepository;
import com.fjb.sunrise.services.CategoryService;
import jakarta.persistence.EntityNotFoundException;
import jakarta.persistence.criteria.Join;
import jakarta.persistence.criteria.Predicate;
import jakarta.transaction.Transactional;
Expand Down Expand Up @@ -52,14 +52,7 @@ public CategoryResponseDto updateCategory(Long id, CategoryUpdateDto categoryUpd
return categoryMapper.toCategoryResponseDto(category);
}

@Override
@Transactional
public CategoryResponseDto saveStatusCategory(Long id, CategoryStatusDto categoryStatusDto) {
Category category = categoryRepository.findById(id).orElseThrow();
category = categoryMapper.statusCategory(category, categoryStatusDto);
category = categoryRepository.save(category);
return categoryMapper.toCategoryResponseDto(category);
}


@Override
public void disableCategory(Long id) {
Expand All @@ -81,7 +74,7 @@ public void enableCategory(Long id) {
public CategoryResponseDto getCategoryById(Long id) {
return categoryRepository.findById(id)
.map(categoryMapper::toCategoryResponseDto)
.orElseThrow();
.orElseThrow(() -> new EntityNotFoundException("Category not found with id: " + id));
}

@Override
Expand Down
118 changes: 68 additions & 50 deletions src/main/resources/templates/category/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,8 @@

<!-- Custom fonts for this template-->
<link th:href="@{/vendor/fontawesome-free/css/all.min.css}" rel="stylesheet" type="text/css">
<link
href="https://fonts.googleapis.com/css?family=Nunito:200,200i,300,300i,400,400i,600,600i,700,700i,800,800i,900,900i"
rel="stylesheet">
<link href="https://fonts.googleapis.com/css?family=Nunito:200,200i,300,300i,400,400i,600,600i,700,700i,800,800i,900,900i" rel="stylesheet">


<!-- Custom styles for this template-->
<link th:href="@{/css/sb-admin-2.min.css}" rel="stylesheet">
Expand Down Expand Up @@ -172,42 +171,7 @@ <h5 class="modal-title" id="exampleModalLabel2">Sửa tên danh mục</h5>
</div>
</div>

<!-- Status Category Modal-->
<div class="modal fade" id="statusCategoryModal" tabindex="-1" role="dialog"
aria-labelledby="editCategoryModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel3">Trạng thái danh mục</h5>
<button class="close" type="button" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<!-- Form để gửi yêu cầu POST -->
<!-- <form id="statusCategory" th:object="${categoryStatus}" th:action="@{/category/delete/{id}}" method="POST">-->
<!-- &lt;!&ndash; Truyền ID danh mục qua tham số hidden &ndash;&gt;-->
<!--&lt;!&ndash; <input type="hidden" name="id" th:value="${category.id}">&ndash;&gt;-->

<!-- &lt;!&ndash; Hiển thị nút bật/tắt trạng thái &ndash;&gt;-->
<!-- <button type="submit" name="status" th:value="${category.status == 'ACTIVE' ? 'NOT_ACTIVE' : 'ACTIVE'}">-->
<!-- <span th:text="${category.status == 'ACTIVE' ? 'Deactivate' : 'Activate'}"></span>-->
<!-- </button>-->
<!-- </form>-->
<!-- <form id="" th:object="${categoryUpdate}" th:action="@{/category/update/{id}}" method="POST">-->
<!-- <div class="modal-body">-->
<!-- <div class="form-group">-->
<!-- <label for="inputNewCategoryName">Tên danh mục</label>-->
<!-- <input type="text" class="form-control" id="inputNewCategoryStatus" th:field="*{name}" aria-describedby="categoryHelp">-->
<!-- </div>-->
<!-- </div>-->
<!-- <div class="modal-footer">-->
<!-- <button class="btn btn-secondary" type="reset" data-dismiss="modal">Hủy</button>-->
<!-- <button class="btn btn-primary" type="submit">Gửi</button>-->
<!-- </div>-->
<!-- </form>-->
</div>
</div>
</div>



<!-- Bootstrap core JavaScript-->
Expand Down Expand Up @@ -262,20 +226,37 @@ <h5 class="modal-title" id="exampleModalLabel3">Trạng thái danh mục</h5>
columns: cols
});
};

const cols = [
{"data": "id"},
{"data": "name"},
{"data": "createdDate"},
{"data": "lastModifiedDate"},
{"data": "status"},
{"data": null, "defaultContent":"" +
"<div>" +
"<button data-toggle=\"modal\" data-target=\"#editCategoryModal\" class=\"btn btn-outline-danger\">Edit</button>" +
"<button data-toggle=\"modal\" data-target=\"#statusCategoryModal\" class=\"btn btn-outline-primary\">Status</button>" +
"</div>"
{"data": "status", "render": function(data, type, row) {
return translateStatus(data);
}
},
{
"data": null, "render": function (data, type, row) {
return `
<div class="btn-group" role="group" aria-label="Category Actions">
<button class="btn btn-outline-info" data-toggle=\"modal\" data-target=\"#editCategoryModal\">
Edit
</button>
<button class="btn ${row.status === 'ACTIVE' ? 'btn-outline-warning' : 'btn-outline-success'}"
onclick="changeCategoryStatus(${row.id}, '${row.status === 'ACTIVE' ? 'deactivate' : 'activate'}')">
<i class="fas ${row.status === 'ACTIVE' ? 'fa-ban' : 'fa-check-circle'}"></i>
</button>
</div>
`
}
}
];



const table = installTable('dataTableCategory', '/sun/category/page', cols)
$('#dataTableCategory tbody').on('click', 'tr', function () {

Expand All @@ -286,13 +267,50 @@ <h5 class="modal-title" id="exampleModalLabel3">Trạng thái danh mục</h5>

$(`#inputNewCategoryName`).val(name);


$('#createCategoryModal').modal('show');
$('#addCategory').attr('action', `/sun/category/add/`);

$('#editCategoryModal').modal('show');
$('#updateCategory').attr('action', `/sun/category/update/${data.id}`);
});

function changeCategoryStatus(id, action) {
if (confirm(`Are you sure you want to ${action === 'activate' ? 'activate' : 'deactivate'} this category?`)) {
let url = `/sun/category/${action}/${id}`;

// Gửi yêu cầu đến backend bằng Fetch API
fetch(url, {
method: 'GET', // Hoặc 'PATCH', tùy thuộc vào API của bạn
})
.then(response => {
if (response.ok) {
// Cập nhật giao diện ngay lập tức nếu yêu cầu thành công
const button = $(`button[onclick*="changeCategoryStatus(${id},"]`);
button.toggleClass('btn-outline-warning btn-outline-success');

// Cập nhật biểu tượng và onclick
if (action === 'activate') {
button.html('<i class="fas fa-ban"></i>');
button.attr('onclick', `changeCategoryStatus(${id}, 'deactivate')`);
} else {
button.html('<i class="fas fa-check-circle"></i>');
button.attr('onclick', `changeCategoryStatus(${id}, 'activate')`);
}
} else {
alert('Error: Unable to change category status.');
}
})
.catch(error => {
console.error('Error:', error);
alert('Request failed. Please try again later.');
});
}
}


const translateStatus = (status) => {
if (status === 'ACTIVE') return 'Hoạt Động';
if (status === 'NOT_ACTIVE') return 'Không Hoạt Động';
return status;
};


</script>
<script type="text/javascript" th:src="@{/js/bootstrap.bundle.min.js}"></script>

Expand Down

0 comments on commit 8a6e24b

Please sign in to comment.