Skip to content

Commit

Permalink
Merge pull request #107 from ttthanhf/hotfix/feature/task
Browse files Browse the repository at this point in the history
Hotfix/feature/task - Fix delete service config && hard code cron time
  • Loading branch information
ttthanhf committed Nov 14, 2023
2 parents 8b27c67 + 2f7a2ef commit d21bf1b
Show file tree
Hide file tree
Showing 5 changed files with 91 additions and 18 deletions.
14 changes: 13 additions & 1 deletion src/main/java/housemate/constants/ServiceConfiguration.java
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,8 @@ public enum ServiceConfiguration {
MINUS_POINTS_FOR_STAFF_CANCEL_TASK(false),
MINUS_POINTS_FOR_NOT_COMPLETE_REPORT_TASK(false),
PLUS_SCORE_PER_SUCCESS_TASK(false),
BAD_STAFF_PROFICIENT_SCORE(false);
BAD_STAFF_PROFICIENT_SCORE(false),
TIME_TRIGGER_SCAN_NEW_TASK(false);



Expand Down Expand Up @@ -59,4 +60,15 @@ public Integer getNum() {
}
return configValue == null ? null : Integer.parseInt(configValue);
}

public String getString() {
String configValue = null;
try {
configValue = configService.getConfigValuesOfConfigTypeName(this.valueOf(this.name())).stream().findFirst()
.orElseThrow(IllegalArgumentException::new);
}catch (Exception e) {
e.printStackTrace();
}
return configValue;
}
}
11 changes: 10 additions & 1 deletion src/main/java/housemate/controllers/TaskController.java
Original file line number Diff line number Diff line change
Expand Up @@ -117,5 +117,14 @@ public ResponseEntity<?> cancelTask(
HttpServletRequest request,
@PathVariable("schedule-id") int scheduleId) {
return taskServiceDao.cancelTask(request, scheduleId);
}
}

@GetMapping("/auto-schedule")
@Operation(summary = "call back event auto ")
public ResponseEntity<?> callBackAutoScanSchduleForNewTask(
HttpServletRequest request,
@PathVariable("schedule-id") int scheduleId) {
return taskServiceDao.cancelTask(request, scheduleId);
}

}
2 changes: 1 addition & 1 deletion src/main/java/housemate/services/ServiceConfigService.java
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,7 @@ public ResponseEntity<?> updateServConfigValue(HttpServletRequest request, int s
@Transactional
public ResponseEntity<?> deleteConfigValue(HttpServletRequest request, int serviceConfigId) {
ServiceConfig existedServConf = servConfRepo.findById(serviceConfigId).orElse(null);
if (existedServConf != null)
if (existedServConf == null)
return ResponseEntity.badRequest().body("Not found to delete !");
servConfRepo.delete(existedServConf);
return ResponseEntity.ok("Deleted Successfully");
Expand Down
72 changes: 61 additions & 11 deletions src/main/java/housemate/services/TaskBuildupService.java
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Optional;
Expand All @@ -18,8 +19,13 @@
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Lazy;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.scheduling.Trigger;
import org.springframework.scheduling.TriggerContext;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.stereotype.Component;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import static housemate.constants.ServiceConfiguration.*;
Expand Down Expand Up @@ -61,6 +67,7 @@
import housemate.repositories.UserRepository;
import housemate.repositories.UserUsageRepository;
import housemate.responses.TaskRes;
import jakarta.annotation.PostConstruct;
import jakarta.transaction.Transactional;

@Component
Expand Down Expand Up @@ -117,12 +124,16 @@ public class TaskBuildupService {
private static final SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");

private static final Map<Integer, List<ScheduledFuture<?>>> eventNotiList = new HashMap<>();


private ScheduledFuture<?> scheduleEventAutoScanForNewTask;

private static final String notiTitleForTaskStatus = "Trạng thái công việc";

private static String cronExpression;


//MARKUP ======CREATE TASK======
@Scheduled(cron = "0 0 0 * * *", zone = "Asia/Ho_Chi_Minh") // call this at every 24:00 PM
// @Scheduled(cron = "0 0 0 * * *", zone = "Asia/Ho_Chi_Minh")
public List<Task> createTasksOnUpcomingSchedulesAutoByFixedRate() {
List<Task> taskList = new ArrayList<>();
try {
Expand All @@ -132,17 +143,19 @@ public List<Task> createTasksOnUpcomingSchedulesAutoByFixedRate() {
if (schedules.isEmpty())
return List.of();
for (Schedule schedule : schedules) {
taskList.add(this.createTask(schedule));
Task task = this.createTask(schedule);
if (task != null)
taskList.add(this.createTask(schedule));
}

if (!taskList.isEmpty()) {
// TODO: NOTI TO CUSTOMER FOR TASK
taskList.stream().forEach(x -> {
// TODO: NOTI TO CUSTOMER FOR TASK
TaskBuildupService.createAndSendNotification(
x, // Task
"Chờ tìm nhân viên",
"Đang tìm kiếm nhân viên", // Mess
String.valueOf(x.getSchedule().getCustomerId())); // Receiver

});
// TODO: NOTI NEW TASK LIST FOR STAFF
TaskBuildupService.createAndSendNotification(
Expand All @@ -158,13 +171,11 @@ public List<Task> createTasksOnUpcomingSchedulesAutoByFixedRate() {
return taskList;
}


public List<Task> createTaskOnUpComingSchedule(Schedule newSchedule) {
List<Schedule> schedules = scheduleRepo.findAllByParentScheduleAndInUpComing(ScheduleStatus.PROCESSING, 1, newSchedule.getParentScheduleId());
log.info("IS SCHEDULES EMPTY {} ", schedules.size());
List<Task> taskList = new ArrayList<>();
try {
log.debug("SCHEDULES WHEN FIND ALL BY PARENTS - IS EMPTY {} | IS NULL: {}", schedules.isEmpty(), schedules == null);
if (schedules.isEmpty())
return List.of();
for (Schedule theSchedule : schedules)
Expand All @@ -189,7 +200,6 @@ public List<Task> createTaskOnUpComingSchedule(Schedule newSchedule) {
public Task createTask(Schedule schedule) {
// Check if the task for this schedule have created before by system
Task task = taskRepo.findExistingTaskForSchedule(schedule.getScheduleId());
log.info("SCHEDULE ID {} - IS TASK OF THIS SCHEDULE HAS EXISTED BEFORE : {}", schedule.getScheduleId(), task);
Task savedTask = null;
try {
if (task == null) {
Expand Down Expand Up @@ -800,7 +810,7 @@ public void run() {
Schedule schedule = scheduleRepo.findById(task.getScheduleId()).get();
schedule.setStatus(ScheduleStatus.CANCEL);
schedule.setNote(schedule.getNote()
+ " - Lịch bị hủy do nhân viên không hoàn thành tiến trình DONE !");
+ " - Lịch bị hủy do nhân viên không hoàn thành tiến trình !");
task.setTaskStatus(TaskStatus.CANCELLED_BY_STAFF);
task.setTaskNote("Buộc phải hủy công việc vì bạn không báo cáo cho trạng thái \"ĐÃ HOÀN THÀNH\" đúng khung giờ quy định !");
staffRepo.save(staff);
Expand Down Expand Up @@ -842,7 +852,47 @@ public void run() {

}

private void CancelAllEventsByTaskId(int taskToBeCancelId) {
@Bean
public void AutoScanScheduleForNewTask() {
TaskBuildupService taskBuidServ = this;
String cronExp = TIME_TRIGGER_SCAN_NEW_TASK.getString();
CronTrigger cronTrigger = new CronTrigger(cronExp);
Trigger trigger = new Trigger() {
@Override
public Instant nextExecution(TriggerContext triggerContext) {
return cronTrigger.nextExecution(triggerContext);
}
};

Runnable eventAutoScanScheduleForNewTask = new Runnable() {

public void run() {
log.info("cronTrigger get expression {} - and current cron Expression {} - and Equal {}",
TIME_TRIGGER_SCAN_NEW_TASK.getString(), cronExpression,
TIME_TRIGGER_SCAN_NEW_TASK.getString().equals(cronExpression));
if (cronExpression != null) {
if (!TIME_TRIGGER_SCAN_NEW_TASK.getString().equals(cronExpression)) {
taskBuidServ.cancelAutoScanSchduleForNewTask();
synchronized (this) {
cronExpression = cronTrigger.getExpression();
}
taskBuidServ.AutoScanScheduleForNewTask();
}
}
cronExpression = cronTrigger.getExpression();
taskBuidServ.createTasksOnUpcomingSchedulesAutoByFixedRate();
}
};
scheduleEventAutoScanForNewTask = taskScheduler.schedule(eventAutoScanScheduleForNewTask, trigger);
log.info("Create auto scan schedule for new task at {}", dateFormat.format(new Date()));
}

public void cancelAutoScanSchduleForNewTask() {
if(scheduleEventAutoScanForNewTask != null)
scheduleEventAutoScanForNewTask.cancel(true);
}

public void CancelAllEventsByTaskId(int taskToBeCancelId) {
if (eventNotiList.get(taskToBeCancelId) != null) {
eventNotiList.get(taskToBeCancelId).stream().map(event -> event.cancel(true));
eventNotiList.remove(taskToBeCancelId);
Expand Down
10 changes: 6 additions & 4 deletions src/main/java/housemate/services/TaskService.java
Original file line number Diff line number Diff line change
Expand Up @@ -383,9 +383,12 @@ public ResponseEntity<?> reportTaskByStaff(HttpServletRequest request, int taskI

if (taskToBeReported == null)
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Công việc này không tồn tại !");
if (!(taskToBeReported.getStaffId() != null && !taskToBeReported.getTaskStatus().name().contains("CANCELLED")
&& userReportRole.equals(Role.STAFF) && userReport == taskToBeReported.getStaffId()))
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Bạn không có quyền được phép báo cáo tiến trình làm việc cho công việc này !");
if (taskToBeReported.getTaskStatus().name().contains("CANCELLED"))
return ResponseEntity.status(HttpStatus.BAD_REQUEST)
.body("Lịch này đã bị hủy ! Ngừng báo cáo tiến trình làm việc cho lịch này !");
if (!(taskToBeReported.getStaffId() != null && userReportRole.equals(Role.STAFF) && userReport == taskToBeReported.getStaffId()))
return ResponseEntity.status(HttpStatus.BAD_REQUEST)
.body("Chỉ nhân viên quản lịch này mới được báo cáo tiến trình này !");

TaskRes<TaskReport> taskReportedRes = taskBuildupServ.reportTask(taskToBeReported, taskReportType, reportnewDTO);
if (taskReportedRes == null)
Expand Down Expand Up @@ -419,6 +422,5 @@ public ResponseEntity<?> getTaskReportListByTask(int taskId) {
}
return ResponseEntity.ok().body(taskReport);
}


}

0 comments on commit d21bf1b

Please sign in to comment.