First commit (wating to add alerts in budget)

This commit is contained in:
BACHIR SOULDI
2025-09-04 13:21:24 +01:00
parent f70bf3341b
commit 9eb959f07a
192 changed files with 51034 additions and 4992 deletions

View File

@@ -1,20 +1,19 @@
package com.axelor.apps.hr.job;
import com.axelor.apps.hr.db.CheckInOut;
import com.axelor.app.AppSettings;
import com.axelor.apps.hr.db.repo.CheckInOutRepository;
import com.axelor.exception.service.TraceBackService;
import com.axelor.inject.Beans;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.time.LocalDate;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.quartz.SchedulerException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.axelor.inject.Beans;
import java.time.LocalDate;
import org.quartz.SchedulerException;
import com.axelor.app.AppSettings;
public class FetchCheckInOutJob implements Job {
@@ -38,14 +37,18 @@ public class FetchCheckInOutJob implements Job {
LocalDate today = LocalDate.now();
// Fetch the CheckInOut list from the repository where the date_attendance is today
int lenCheckInOutList = Beans.get(CheckInOutRepository.class)
.all()
.filter("self.date_attendance = :today")
.bind("today", today)
.fetch().size();
int lenCheckInOutList =
Beans.get(CheckInOutRepository.class)
.all()
.filter("self.date_attendance = :today")
.bind("today", today)
.fetch()
.size();
// Define the command to run the Python script with the correct path (V3)
String[] args = {"python", pythonScriptDir + "\\Scrape\\main2.py", String.valueOf(lenCheckInOutList)};
String[] args = {
"python", pythonScriptDir + "\\Scrape\\main2.py", String.valueOf(lenCheckInOutList)
};
// Execute the command
Process p = Runtime.getRuntime().exec(args);
@@ -101,5 +104,4 @@ public class FetchCheckInOutJob implements Job {
return false;
}
}
}

View File

@@ -3,9 +3,9 @@ package com.axelor.apps.hr.service;
import com.axelor.apps.hr.db.Absence;
import com.axelor.apps.hr.db.DailyReport;
import com.google.inject.persist.Transactional;
import java.util.List;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
public interface AbsenceService {
@@ -13,13 +13,16 @@ public interface AbsenceService {
void attachTheAbsenceWithDailyReport(Absence absence, List<DailyReport> dailyreports);
@Transactional
void deAttachTheAbsenceWithDailyReport(Absence absence, List<DailyReport> dailyreports, Boolean archive);
void deAttachTheAbsenceWithDailyReport(
Absence absence, List<DailyReport> dailyreports, Boolean archive);
@Transactional
void chooseAbsenceType(Absence absence, Integer selectedType);
@Transactional
BigDecimal calculateTotalAbsenceHours(LocalDateTime absenceStartDate, LocalDateTime absenceEndDate);
BigDecimal calculateTotalAbsenceHours(
LocalDateTime absenceStartDate, LocalDateTime absenceEndDate);
BigDecimal calculateTotalAbsenceMinutes(LocalDateTime absenceStartDate, LocalDateTime absenceEndDate);
BigDecimal calculateTotalAbsenceMinutes(
LocalDateTime absenceStartDate, LocalDateTime absenceEndDate);
}

View File

@@ -1,25 +1,22 @@
package com.axelor.apps.hr.service;
import com.axelor.apps.base.db.EventsPlanning;
import com.axelor.apps.base.db.EventsPlanningLine;
import com.axelor.apps.base.db.repo.EventsPlanningRepository;
import com.axelor.apps.base.db.repo.EventsPlanningLineRepository;
import com.axelor.apps.hr.db.Absence;
import com.axelor.apps.hr.db.DailyReport;
import com.axelor.apps.hr.db.repo.AbsenceRepository;
import com.axelor.apps.hr.db.repo.DailyReportRepository;
import com.axelor.inject.Beans;
import com.google.inject.Inject;
import com.google.inject.persist.Transactional;
import com.axelor.inject.Beans;
import java.util.List;
import java.time.Year;
import java.time.DayOfWeek;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.DayOfWeek;
import java.time.Duration;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.time.Duration;
import java.math.RoundingMode;
import java.util.List;
public class AbsenceServiceImpl implements AbsenceService {
@@ -28,19 +25,16 @@ public class AbsenceServiceImpl implements AbsenceService {
private List<EventsPlanningLine> eventsPlanningLines;
@Inject
public AbsenceServiceImpl( AbsenceRepository absenceRepository, DailyReportRepository dailyReportRepository) {
public AbsenceServiceImpl(
AbsenceRepository absenceRepository, DailyReportRepository dailyReportRepository) {
this.absenceRepository = absenceRepository;
this.dailyReportRepository = dailyReportRepository;
eventsPlanningLines =
Beans.get(EventsPlanningLineRepository.class)
.all()
.filter("self.id = 4")
.fetch();
Beans.get(EventsPlanningLineRepository.class).all().filter("self.id = 4").fetch();
}
@Transactional
public void attachTheAbsenceWithDailyReport(
Absence absence, List<DailyReport> dailyreports) {
public void attachTheAbsenceWithDailyReport(Absence absence, List<DailyReport> dailyreports) {
// Iterate over each DailyReport in the list
for (DailyReport dailyreport : dailyreports) {
dailyreport.addAbsenceSetItem(absence); // Set the absence for each report
@@ -49,8 +43,9 @@ public class AbsenceServiceImpl implements AbsenceService {
}
@Transactional
public void deAttachTheAbsenceWithDailyReport(Absence absence, List<DailyReport> dailyreports, Boolean archive) {
if(dailyreports != null){
public void deAttachTheAbsenceWithDailyReport(
Absence absence, List<DailyReport> dailyreports, Boolean archive) {
if (dailyreports != null) {
// Iterate over each DailyReport in the list
for (DailyReport dailyreport : dailyreports) {
dailyreport.removeAbsenceSetItem(null); // Set the absence for each report
@@ -59,8 +54,8 @@ public class AbsenceServiceImpl implements AbsenceService {
}
if (archive) {
absence.setArchived(true);
absenceRepository.save(absence);
absence.setArchived(true);
absenceRepository.save(absence);
}
}
@@ -74,46 +69,50 @@ public class AbsenceServiceImpl implements AbsenceService {
absenceRepository.save(absence);
}
public BigDecimal calculateTotalAbsenceHours(LocalDateTime absenceStartDate, LocalDateTime absenceEndDate) {
BigDecimal totalAbsenceHours = BigDecimal.ZERO;
public BigDecimal calculateTotalAbsenceHours(
LocalDateTime absenceStartDate, LocalDateTime absenceEndDate) {
BigDecimal totalAbsenceHours = BigDecimal.ZERO;
if(absenceStartDate.equals(absenceEndDate)){
totalAbsenceHours = BigDecimal.valueOf(8);
}
else if (absenceStartDate.toLocalDate().equals(absenceEndDate.toLocalDate())) {
// If the start and end dates are the same, calculate the hour difference
long hours = ChronoUnit.HOURS.between(absenceStartDate, absenceEndDate);
totalAbsenceHours = BigDecimal.valueOf(hours);
} else {
long absenceDays = 0;
LocalDate currentDate = absenceStartDate.toLocalDate();
if (absenceStartDate.equals(absenceEndDate)) {
totalAbsenceHours = BigDecimal.valueOf(8);
} else if (absenceStartDate.toLocalDate().equals(absenceEndDate.toLocalDate())) {
// If the start and end dates are the same, calculate the hour difference
long hours = ChronoUnit.HOURS.between(absenceStartDate, absenceEndDate);
totalAbsenceHours = BigDecimal.valueOf(hours);
} else {
long absenceDays = 0;
LocalDate currentDate = absenceStartDate.toLocalDate();
// Loop through each day between start and end date
while (!currentDate.isAfter(absenceEndDate.toLocalDate())) {
DayOfWeek dayOfWeek = currentDate.getDayOfWeek();
// Loop through each day between start and end date
while (!currentDate.isAfter(absenceEndDate.toLocalDate())) {
DayOfWeek dayOfWeek = currentDate.getDayOfWeek();
// Exclude Friday (5) and Saturday (6) and holidays
if (dayOfWeek != DayOfWeek.FRIDAY && dayOfWeek != DayOfWeek.SATURDAY && !isSpecialOvertimeDay(currentDate)) {
absenceDays++;
}
currentDate = currentDate.plusDays(1);
// Exclude Friday (5) and Saturday (6) and holidays
if (dayOfWeek != DayOfWeek.FRIDAY
&& dayOfWeek != DayOfWeek.SATURDAY
&& !isSpecialOvertimeDay(currentDate)) {
absenceDays++;
}
// Multiply the counted days by 8 hours per day
totalAbsenceHours = BigDecimal.valueOf(absenceDays).multiply(BigDecimal.valueOf(8));
currentDate = currentDate.plusDays(1);
}
return totalAbsenceHours;
// Multiply the counted days by 8 hours per day
totalAbsenceHours = BigDecimal.valueOf(absenceDays).multiply(BigDecimal.valueOf(8));
}
return totalAbsenceHours;
}
public BigDecimal calculateTotalAbsenceMinutes(LocalDateTime absenceStartDate, LocalDateTime absenceEndDate) {
// Calculate the duration between the two LocalDateTime objects
Duration duration = Duration.between(absenceStartDate, absenceEndDate);
public BigDecimal calculateTotalAbsenceMinutes(
LocalDateTime absenceStartDate, LocalDateTime absenceEndDate) {
// Calculate the duration between the two LocalDateTime objects
Duration duration = Duration.between(absenceStartDate, absenceEndDate);
// Convert the duration to minutes and then divide by 60 to get hours
long minutes = duration.toMinutes();
BigDecimal hours = BigDecimal.valueOf(minutes).divide(BigDecimal.valueOf(60), 2, BigDecimal.ROUND_HALF_UP);
// Convert the duration to minutes and then divide by 60 to get hours
long minutes = duration.toMinutes();
BigDecimal hours =
BigDecimal.valueOf(minutes).divide(BigDecimal.valueOf(60), 2, BigDecimal.ROUND_HALF_UP);
return customRound(hours);
return customRound(hours);
}
private boolean isSpecialOvertimeDay(LocalDate date) {
@@ -147,5 +146,4 @@ public class AbsenceServiceImpl implements AbsenceService {
return value; // In case no rounding is needed
}
}
}

View File

@@ -2,23 +2,22 @@ package com.axelor.apps.hr.service;
import com.axelor.apps.base.db.EventsPlanning;
import com.axelor.apps.base.db.EventsPlanningLine;
import com.axelor.apps.base.db.repo.EventsPlanningRepository;
import com.axelor.apps.base.db.repo.EventsPlanningLineRepository;
import com.axelor.apps.hr.db.Absence;
import com.axelor.apps.hr.db.Authorization;
import com.axelor.apps.hr.db.DailyReport;
import com.axelor.apps.hr.db.Employee;
import com.axelor.apps.hr.db.OffDayWork;
import com.axelor.apps.hr.db.DailyReport;
import com.axelor.apps.hr.db.Shift;
import com.axelor.apps.hr.db.Authorization;
import com.axelor.apps.hr.db.repo.AbsenceRepository;
import com.axelor.apps.hr.db.repo.AuthorizationRepository;
import com.axelor.apps.hr.db.repo.OffDayWorkRepository;
import com.axelor.apps.hr.db.repo.DailyReportRepository;
import com.axelor.apps.hr.db.repo.OffDayWorkRepository;
import com.axelor.apps.hr.db.repo.ShiftRepository;
import com.axelor.apps.hr.service.AbsenceServiceImpl;
import com.axelor.inject.Beans;
import com.google.inject.persist.Transactional;
import com.axelor.exception.AxelorException;
import com.axelor.inject.Beans;
import com.google.inject.Inject;
import com.google.inject.persist.Transactional;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.DayOfWeek;
@@ -26,10 +25,8 @@ import java.time.Duration;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.Year;
import java.util.List;
import java.util.ArrayList;
import com.google.inject.Inject;
import java.util.List;
public class DailyReportServiceImpl implements DailyReportService {
@@ -52,23 +49,35 @@ public class DailyReportServiceImpl implements DailyReportService {
private LocalTime SHIFT_6h14_max;
@Inject
public DailyReportServiceImpl(DailyReportRepository dailyReportRepository, AuthorizationRepository autorizationRepository, AbsenceRepository absenceRepository) {
public DailyReportServiceImpl(
DailyReportRepository dailyReportRepository,
AuthorizationRepository autorizationRepository,
AbsenceRepository absenceRepository) {
this.dailyReportRepository = dailyReportRepository;
this.autorizationRepository = autorizationRepository;
this.absenceRepository = absenceRepository;
eventsPlanningLines = Beans.get(EventsPlanningLineRepository.class)
.all()
.filter("self.eventsPlanning = 4")
.fetch();
eventsPlanningLines =
Beans.get(EventsPlanningLineRepository.class)
.all()
.filter("self.eventsPlanning = 4")
.fetch();
SHIFT_8h16_min = Beans.get(ShiftRepository.class).all().filter("self.shift = 0").fetchOne().getEnterMin();
SHIFT_8h16_max = Beans.get(ShiftRepository.class).all().filter("self.shift = 0").fetchOne().getEnterMax();
SHIFT_14h22_min = Beans.get(ShiftRepository.class).all().filter("self.shift = 1").fetchOne().getEnterMin();
SHIFT_14h22_max = Beans.get(ShiftRepository.class).all().filter("self.shift = 1").fetchOne().getEnterMax();
SHIFT_22h6_min = Beans.get(ShiftRepository.class).all().filter("self.shift = 2").fetchOne().getEnterMin();
SHIFT_22h6_max = Beans.get(ShiftRepository.class).all().filter("self.shift = 2").fetchOne().getEnterMax();
SHIFT_6h14_min = Beans.get(ShiftRepository.class).all().filter("self.shift = 3").fetchOne().getEnterMin();
SHIFT_6h14_max = Beans.get(ShiftRepository.class).all().filter("self.shift = 3").fetchOne().getEnterMax();
SHIFT_8h16_min =
Beans.get(ShiftRepository.class).all().filter("self.shift = 0").fetchOne().getEnterMin();
SHIFT_8h16_max =
Beans.get(ShiftRepository.class).all().filter("self.shift = 0").fetchOne().getEnterMax();
SHIFT_14h22_min =
Beans.get(ShiftRepository.class).all().filter("self.shift = 1").fetchOne().getEnterMin();
SHIFT_14h22_max =
Beans.get(ShiftRepository.class).all().filter("self.shift = 1").fetchOne().getEnterMax();
SHIFT_22h6_min =
Beans.get(ShiftRepository.class).all().filter("self.shift = 2").fetchOne().getEnterMin();
SHIFT_22h6_max =
Beans.get(ShiftRepository.class).all().filter("self.shift = 2").fetchOne().getEnterMax();
SHIFT_6h14_min =
Beans.get(ShiftRepository.class).all().filter("self.shift = 3").fetchOne().getEnterMin();
SHIFT_6h14_max =
Beans.get(ShiftRepository.class).all().filter("self.shift = 3").fetchOne().getEnterMax();
}
@Override
@@ -90,14 +99,17 @@ public class DailyReportServiceImpl implements DailyReportService {
LocalDateTime firstEnter, lastQuit;
LocalTime shiftStartHour = null, shiftEndHour = null, shiftStartPauseHour = null, shiftEndPauseHour = null;
if(shift != null){
LocalTime shiftStartHour = null,
shiftEndHour = null,
shiftStartPauseHour = null,
shiftEndPauseHour = null;
if (shift != null) {
shiftStartHour = dailyReport.getShift().getStartHour();
shiftEndHour = dailyReport.getShift().getEndHour();
shiftStartPauseHour = dailyReport.getShift().getStartPause();
shiftEndPauseHour = dailyReport.getShift().getEndPause();
}
if (enters[0] != null && quits[0] != null) {
// Calculate total work duration
Duration totalDuration = Duration.ZERO;
@@ -117,45 +129,54 @@ public class DailyReportServiceImpl implements DailyReportService {
dailyReport.setLastQuit(lastQuit);
LocalTime firstEnterTime = firstEnter.toLocalTime();
LocalTime lastQuitTime = lastQuit.toLocalTime();
// Calculate late arrival if firstEnter is later than shift start
if(shiftStartHour != null){
if (shiftStartHour != null) {
if (firstEnterTime.isAfter(shiftStartHour)) {
long minutesLate = Duration.between(shiftStartHour, firstEnterTime).toMinutes();
BigDecimal lateArrival = BigDecimal.valueOf(minutesLate).divide(BigDecimal.valueOf(60), 2, RoundingMode.HALF_UP);
BigDecimal lateArrival =
BigDecimal.valueOf(minutesLate)
.divide(BigDecimal.valueOf(60), 2, RoundingMode.HALF_UP);
dailyReport.setLateArrival(lateArrival);
}
}
// Calculate early departure if lastQuit is earlier than shift end
if(shiftEndHour != null){
if (shiftEndHour != null) {
if (lastQuitTime.isBefore(shiftEndHour)) {
long minutesEarly = Duration.between(lastQuitTime, shiftEndHour).toMinutes();
BigDecimal earlyDeparture = BigDecimal.valueOf(minutesEarly).divide(BigDecimal.valueOf(60), 2, RoundingMode.HALF_UP);
BigDecimal earlyDeparture =
BigDecimal.valueOf(minutesEarly)
.divide(BigDecimal.valueOf(60), 2, RoundingMode.HALF_UP);
dailyReport.setEarlyDeparture(earlyDeparture);
}
}
// Total hours
totalDuration = totalDuration.plus(Duration.between(firstEnter, lastQuit));
long totalMinutes = totalDuration.toMinutes();
BigDecimal totalHours = BigDecimal.valueOf(totalMinutes).divide(BigDecimal.valueOf(60), 2, RoundingMode.HALF_UP);
BigDecimal totalHours =
BigDecimal.valueOf(totalMinutes).divide(BigDecimal.valueOf(60), 2, RoundingMode.HALF_UP);
dailyReport.setWorkHours(totalHours);
// Calculate night hours
nightDuration = calculateNightDuration(firstEnter, lastQuit);
long totalNightMinutes = nightDuration.toMinutes();
BigDecimal totalNightHours = BigDecimal.valueOf(totalNightMinutes).divide(BigDecimal.valueOf(60), 2, RoundingMode.HALF_UP);
BigDecimal totalNightHours =
BigDecimal.valueOf(totalNightMinutes)
.divide(BigDecimal.valueOf(60), 2, RoundingMode.HALF_UP);
dailyReport.setNightHours(totalNightHours);
// Break Hours
breakDuration = calculateBreakDuration(enters, quits);
long breakMinutes = breakDuration.toMinutes();
BigDecimal breakHours = BigDecimal.valueOf(breakMinutes).divide(BigDecimal.valueOf(60), 2, RoundingMode.HALF_UP);
BigDecimal breakHours =
BigDecimal.valueOf(breakMinutes).divide(BigDecimal.valueOf(60), 2, RoundingMode.HALF_UP);
dailyReport.setBreakHours(breakHours);
if(shiftStartPauseHour != null && shiftEndPauseHour != null){
boolean allInAllowedRange = areBreaksInAllowedRange(enters, quits, shiftStartPauseHour, shiftEndPauseHour);
if (shiftStartPauseHour != null && shiftEndPauseHour != null) {
boolean allInAllowedRange =
areBreaksInAllowedRange(enters, quits, shiftStartPauseHour, shiftEndPauseHour);
dailyReport.setBreakNotInTheAllowedRange(allInAllowedRange);
}
@@ -172,14 +193,19 @@ public class DailyReportServiceImpl implements DailyReportService {
// Calculate time from first enter to midnight
Duration beforeMidnightDuration = Duration.between(firstEnter, midnight);
long beforeMidnightMinutes = beforeMidnightDuration.toMinutes();
BigDecimal beforeMidnightHours = BigDecimal.valueOf(beforeMidnightMinutes).divide(BigDecimal.valueOf(60), 2, RoundingMode.HALF_UP);
BigDecimal beforeMidnightHours =
BigDecimal.valueOf(beforeMidnightMinutes)
.divide(BigDecimal.valueOf(60), 2, RoundingMode.HALF_UP);
// Calculate time from midnight to last quit
Duration afterMidnightDuration = Duration.between(midnight, lastQuit);
long afterMidnightMinutes = afterMidnightDuration.toMinutes();
BigDecimal afterMidnightHours = BigDecimal.valueOf(afterMidnightMinutes).divide(BigDecimal.valueOf(60), 2, RoundingMode.HALF_UP);
BigDecimal afterMidnightHours =
BigDecimal.valueOf(afterMidnightMinutes)
.divide(BigDecimal.valueOf(60), 2, RoundingMode.HALF_UP);
if (enterDay == DayOfWeek.THURSDAY && quitDay == DayOfWeek.FRIDAY || isSpecialOvertimeDay(lastQuit)) {
if (enterDay == DayOfWeek.THURSDAY && quitDay == DayOfWeek.FRIDAY
|| isSpecialOvertimeDay(lastQuit)) {
extraHours100 = afterMidnightHours;
dailyReport.setAllowance(totalHours.compareTo(BigDecimal.valueOf(5)) >= 0 ? 1 : 0);
if (enterDay == DayOfWeek.THURSDAY && quitDay == DayOfWeek.FRIDAY)
@@ -205,9 +231,11 @@ public class DailyReportServiceImpl implements DailyReportService {
extraHours50 = beforeMidnightHours;
dailyReport.setAllowanceRecall(totalHours.compareTo(BigDecimal.valueOf(5)) >= 0 ? 1 : 0);
} else {
totalSupDuration = calculateSupplementaryHours(firstEnter,lastQuit,shift,reportDate);
totalSupDuration = calculateSupplementaryHours(firstEnter, lastQuit, shift, reportDate);
long totalSupMinutes = totalSupDuration.toMinutes();
extraHours50 = BigDecimal.valueOf(totalSupMinutes).divide(BigDecimal.valueOf(60), 2, RoundingMode.HALF_UP);
extraHours50 =
BigDecimal.valueOf(totalSupMinutes)
.divide(BigDecimal.valueOf(60), 2, RoundingMode.HALF_UP);
dailyReport.setAllowance(totalHours.compareTo(BigDecimal.valueOf(5)) >= 0 ? 1 : 0);
}
@@ -219,21 +247,26 @@ public class DailyReportServiceImpl implements DailyReportService {
// Calculate supplementary hours
totalSupDuration = calculateSupplementaryHours(firstEnter, lastQuit, shift, reportDate);
long totalSupMinutes = totalSupDuration.toMinutes();
BigDecimal totalSupHours = BigDecimal.valueOf(totalSupMinutes).divide(BigDecimal.valueOf(60), 2, RoundingMode.HALF_UP);
BigDecimal totalSupHours =
BigDecimal.valueOf(totalSupMinutes)
.divide(BigDecimal.valueOf(60), 2, RoundingMode.HALF_UP);
// Holidays and weekends
if (firstEnter.getDayOfWeek() == DayOfWeek.SATURDAY) {
if(shift == 0 || shift == 3){
if (shift == 0 || shift == 3) {
dailyReport.setExtraHours50(totalHours.subtract(totalNightHours));
dailyReport.setExtraHours100(totalNightHours);
dailyReport.setAllowanceRecall(totalHours.compareTo(BigDecimal.valueOf(5)) >= 0 ? 1 : 0);
dailyReport.setAllowanceRecall(
totalHours.compareTo(BigDecimal.valueOf(5)) >= 0 ? 1 : 0);
} else {
dailyReport.setExtraHours50(totalHours);
dailyReport.setAllowanceRecall(totalHours.compareTo(BigDecimal.valueOf(5)) >= 0 ? 1 : 0);
dailyReport.setAllowanceRecall(
totalHours.compareTo(BigDecimal.valueOf(5)) >= 0 ? 1 : 0);
}
} else if (firstEnter.getDayOfWeek() == DayOfWeek.FRIDAY || isSpecialOvertimeDay(firstEnter)) {
} else if (firstEnter.getDayOfWeek() == DayOfWeek.FRIDAY
|| isSpecialOvertimeDay(firstEnter)) {
// Add recup
if (totalHours.compareTo(BigDecimal.valueOf(6)) >= 0)
@@ -243,26 +276,28 @@ public class DailyReportServiceImpl implements DailyReportService {
} else {
if(shift == 0 || shift == 3){
if (shift == 0 || shift == 3) {
dailyReport.setExtraHours50(totalSupHours.subtract(totalNightHours));
dailyReport.setExtraHours100(totalNightHours);
dailyReport.setAllowance(totalHours.compareTo(BigDecimal.valueOf(5)) >= 0 ? 1 : 0);
dailyReport.setAllowanceRecall(totalSupHours.compareTo(BigDecimal.valueOf(5)) >= 0 ? 1 : 0);
dailyReport.setAllowanceRecall(
totalSupHours.compareTo(BigDecimal.valueOf(5)) >= 0 ? 1 : 0);
} else {
dailyReport.setExtraHours50(totalSupHours);
dailyReport.setAllowance(totalHours.compareTo(BigDecimal.valueOf(5)) >= 0 ? 1 : 0);
dailyReport.setAllowanceRecall(totalSupHours.compareTo(BigDecimal.valueOf(5)) >= 0 ? 1 : 0);
}
dailyReport.setAllowanceRecall(
totalSupHours.compareTo(BigDecimal.valueOf(5)) >= 0 ? 1 : 0);
}
}
}
// Calculate ITP
dailyReport.setItp(calculateItp(totalHours, shift,dailyReport.getHasItp()));
dailyReport.setItp(calculateItp(totalHours, shift, dailyReport.getHasItp()));
dailyReport.setIsCalculated(true);
} else if (enters[0] != null && quits[0] == null) {
// When the employee registers attendance only once
if(shift!=2){
if (shift != 2) {
dailyReport.setWorkHours(BigDecimal.valueOf(8));
dailyReport.setAbsenceHours(BigDecimal.valueOf(0));
dailyReport.setIsCalculated(true);
@@ -274,7 +309,8 @@ public class DailyReportServiceImpl implements DailyReportService {
lastQuit = quits[quits.length - 1];
totalDuration = totalDuration.plus(Duration.between(firstEnter, lastQuit));
long totalMinutes = totalDuration.toMinutes();
BigDecimal totalHours = BigDecimal.valueOf(totalMinutes).divide(BigDecimal.valueOf(60), 2, RoundingMode.HALF_UP);
BigDecimal totalHours =
BigDecimal.valueOf(totalMinutes).divide(BigDecimal.valueOf(60), 2, RoundingMode.HALF_UP);
dailyReport.setWorkHours(totalHours);
dailyReport.setAllowance(totalHours.compareTo(BigDecimal.valueOf(5)) >= 0 ? 1 : 0);
@@ -283,16 +319,19 @@ public class DailyReportServiceImpl implements DailyReportService {
LocalTime lastQuitTime = lastQuit.toLocalTime();
// Calculate late arrival if firstEnter is later than shift start
if (firstEnterTime.isAfter(shiftStartHour)) {
long minutesLate = Duration.between(shiftStartHour, firstEnterTime).toMinutes();
BigDecimal lateArrival = BigDecimal.valueOf(minutesLate).divide(BigDecimal.valueOf(60), 2, RoundingMode.HALF_UP);
dailyReport.setLateArrival(lateArrival);
long minutesLate = Duration.between(shiftStartHour, firstEnterTime).toMinutes();
BigDecimal lateArrival =
BigDecimal.valueOf(minutesLate).divide(BigDecimal.valueOf(60), 2, RoundingMode.HALF_UP);
dailyReport.setLateArrival(lateArrival);
}
// Calculate early departure if lastQuit is earlier than shift end
if (lastQuitTime.isBefore(shiftEndHour)) {
long minutesEarly = Duration.between(lastQuitTime, shiftEndHour).toMinutes();
BigDecimal earlyDeparture = BigDecimal.valueOf(minutesEarly).divide(BigDecimal.valueOf(60), 2, RoundingMode.HALF_UP);
dailyReport.setEarlyDeparture(earlyDeparture);
long minutesEarly = Duration.between(lastQuitTime, shiftEndHour).toMinutes();
BigDecimal earlyDeparture =
BigDecimal.valueOf(minutesEarly)
.divide(BigDecimal.valueOf(60), 2, RoundingMode.HALF_UP);
dailyReport.setEarlyDeparture(earlyDeparture);
}
} else if (employee == null) {
@@ -317,11 +356,15 @@ public class DailyReportServiceImpl implements DailyReportService {
// Absences
if (dailyReport.getAbsence() == null) {
Absence absence = Beans.get(AbsenceRepository.class)
Absence absence =
Beans.get(AbsenceRepository.class)
.all()
.filter("self.employee = :employee and self.startDate <= :reportDate and self.endDate >= :reportDate and (self.archived = false or self.archived is null)")
.filter(
"self.employee = :employee and self.startDate <= :reportDate and self.endDate >= :reportDate and (self.archived = false or self.archived is null)")
.bind("employee", employee)
.bind("reportDate",reportDate) // Changed from absenceStartDate and absenceEndDate to reportDate
.bind(
"reportDate",
reportDate) // Changed from absenceStartDate and absenceEndDate to reportDate
.fetchOne();
if (absence != null) {
@@ -331,33 +374,35 @@ public class DailyReportServiceImpl implements DailyReportService {
// Authorization
if (dailyReport.getAuthorizationList() == null) {
List<Authorization> authorizations = Beans.get(AuthorizationRepository.class)
.all()
.filter("self.employee = :employee and self.requisitionDate = :reportDate")
.bind("employee", employee)
.bind("reportDate", reportDate)
.fetch();
List<Authorization> authorizations =
Beans.get(AuthorizationRepository.class)
.all()
.filter("self.employee = :employee and self.requisitionDate = :reportDate")
.bind("employee", employee)
.bind("reportDate", reportDate)
.fetch();
if (authorizations != null) {
List<Authorization> authorizationList = new ArrayList<>(); // Create a new list for authorizations
List<Authorization> authorizationList =
new ArrayList<>(); // Create a new list for authorizations
for (Authorization authorization : authorizations) {
authorization.setDailyReport(dailyReport);
authorizationList.add(authorization); // Add each authorization to the list
for (Authorization authorization : authorizations) {
authorization.setDailyReport(dailyReport);
authorizationList.add(authorization); // Add each authorization to the list
// Check authorization type and set corresponding flags in dailyReport
if (authorization.getAuthorizationType() == 0 && authorization.getStatusSelect() == 3) {
dailyReport.setIsAuthorizedEarlyDeparture(true);
}
if (authorization.getAuthorizationType() == 1 && authorization.getStatusSelect() == 3) {
dailyReport.setIsAuthorizedLateArrival(true);
}
if (authorization.getAuthorizationType() == 2 && authorization.getStatusSelect() == 3) {
dailyReport.setIsAuthorizedAbsence(true);
}
// Check authorization type and set corresponding flags in dailyReport
if (authorization.getAuthorizationType() == 0 && authorization.getStatusSelect() == 3) {
dailyReport.setIsAuthorizedEarlyDeparture(true);
}
// Set the authorization list to dailyReport
dailyReport.setAuthorizationList(authorizationList);
if (authorization.getAuthorizationType() == 1 && authorization.getStatusSelect() == 3) {
dailyReport.setIsAuthorizedLateArrival(true);
}
if (authorization.getAuthorizationType() == 2 && authorization.getStatusSelect() == 3) {
dailyReport.setIsAuthorizedAbsence(true);
}
}
// Set the authorization list to dailyReport
dailyReport.setAuthorizationList(authorizationList);
}
}
@@ -367,54 +412,68 @@ public class DailyReportServiceImpl implements DailyReportService {
}
// Weekends
if (reportDate.getDayOfWeek() == DayOfWeek.FRIDAY || reportDate.getDayOfWeek() == DayOfWeek.SATURDAY) {
if (reportDate.getDayOfWeek() == DayOfWeek.FRIDAY
|| reportDate.getDayOfWeek() == DayOfWeek.SATURDAY) {
dailyReport.setIsWeekend(true);
}
// Absence Hours
if (!(dailyReport.getIsWeekend() || dailyReport.getIsFerieDay()) && dailyReport.getWorkHours().compareTo(BigDecimal.valueOf(8)) < 0) {
if (!(dailyReport.getIsWeekend() || dailyReport.getIsFerieDay())
&& dailyReport.getWorkHours().compareTo(BigDecimal.valueOf(8)) < 0) {
dailyReport.setAbsenceHours(BigDecimal.valueOf(8).subtract(dailyReport.getWorkHours()));
// Create Absence AI
if(dailyReport.getAbsenceSet().isEmpty()){
if (dailyReport.getAbsenceSet().isEmpty()) {
Boolean isAuthorizedAbsence = dailyReport.getIsAuthorizedAbsence();
Boolean isAuthorizedLateArrival = dailyReport.getIsAuthorizedLateArrival();
Boolean isAuthorizedEarlyDeparture = dailyReport.getIsAuthorizedEarlyDeparture();
// AI all day
if(dailyReport.getAbsenceHours().compareTo(new BigDecimal("8")) == 0){
if(!isAuthorizedAbsence){
if (dailyReport.getAbsenceHours().compareTo(new BigDecimal("8")) == 0) {
if (!isAuthorizedAbsence) {
Absence absence = new Absence();
absence.setEmployee(employee);
absence.setAbsenceType(19); // Absence irrégulière
absence.setStartDate(reportDate.atStartOfDay());
absence.setEndDate(reportDate.atStartOfDay());
BigDecimal totalAbsenceHours = Beans.get(AbsenceServiceImpl.class).calculateTotalAbsenceHours(reportDate.atStartOfDay(),reportDate.atStartOfDay());
BigDecimal totalAbsenceHours =
Beans.get(AbsenceServiceImpl.class)
.calculateTotalAbsenceHours(
reportDate.atStartOfDay(), reportDate.atStartOfDay());
absence.setTotalAbsenceHours(totalAbsenceHours);
absenceRepository.save(absence);
dailyReport.addAbsenceSetItem(absence);
}
}else{
if(dailyReport.getShift().getMaxTimeLateArrival() != null){ // to check that is different to shift N/A
} else {
if (dailyReport.getShift().getMaxTimeLateArrival()
!= null) { // to check that is different to shift N/A
LocalTime firstEnterTime = dailyReport.getEnter1().toLocalTime();
if(firstEnterTime.isAfter(dailyReport.getShift().getMaxTimeLateArrival()) && !isAuthorizedLateArrival){
if (firstEnterTime.isAfter(dailyReport.getShift().getMaxTimeLateArrival())
&& !isAuthorizedLateArrival) {
Absence absence = new Absence();
absence.setEmployee(employee);
absence.setAbsenceType(20); // Retard irrégulier
absence.setStartDate(reportDate.atTime(shiftStartHour));
absence.setEndDate(dailyReport.getEnter1());
BigDecimal totalAbsenceHours = Beans.get(AbsenceServiceImpl.class).calculateTotalAbsenceMinutes(reportDate.atTime(shiftStartHour),dailyReport.getEnter1());
BigDecimal totalAbsenceHours =
Beans.get(AbsenceServiceImpl.class)
.calculateTotalAbsenceMinutes(
reportDate.atTime(shiftStartHour), dailyReport.getEnter1());
absence.setTotalAbsenceHours(totalAbsenceHours);
absenceRepository.save(absence);
dailyReport.addAbsenceSetItem(absence);
}
if(dailyReport.getLastQuit() != null){
if (dailyReport.getLastQuit() != null) {
LocalTime lastQuitTime = dailyReport.getLastQuit().toLocalTime();
if(lastQuitTime.isBefore(dailyReport.getShift().getMaxTimeEarlyDeparture()) && !isAuthorizedEarlyDeparture){
if (lastQuitTime.isBefore(dailyReport.getShift().getMaxTimeEarlyDeparture())
&& !isAuthorizedEarlyDeparture) {
Absence absence = new Absence();
absence.setEmployee(employee);
absence.setAbsenceType(21); // Départ irrégulier
absence.setStartDate(dailyReport.getLastQuit());
absence.setEndDate(reportDate.atTime(shiftEndHour));
BigDecimal totalAbsenceHours = Beans.get(AbsenceServiceImpl.class).calculateTotalAbsenceMinutes(dailyReport.getLastQuit(),reportDate.atTime(shiftEndHour));
BigDecimal totalAbsenceHours =
Beans.get(AbsenceServiceImpl.class)
.calculateTotalAbsenceMinutes(
dailyReport.getLastQuit(), reportDate.atTime(shiftEndHour));
absence.setTotalAbsenceHours(totalAbsenceHours);
absenceRepository.save(absence);
dailyReport.addAbsenceSetItem(absence);
@@ -431,24 +490,24 @@ public class DailyReportServiceImpl implements DailyReportService {
}
@Transactional
public void determineShift(DailyReport dailyReport){
public void determineShift(DailyReport dailyReport) {
LocalDateTime enters1 = dailyReport.getEnter1();
if(enters1 != null){
if (enters1 != null) {
// Extract time from enters1
LocalTime firstTime = enters1.toLocalTime();
// Define shifts
Shift shift;
if (firstTime.isAfter(SHIFT_6h14_min) && firstTime.isBefore(SHIFT_6h14_max)) {
shift = Beans.get(ShiftRepository.class).find(3L); // Shift 6h14
shift = Beans.get(ShiftRepository.class).find(3L); // Shift 6h14
} else if (firstTime.isAfter(SHIFT_8h16_min) && firstTime.isBefore(SHIFT_8h16_max)) {
shift = Beans.get(ShiftRepository.class).find(4L); // Shift 8h16
shift = Beans.get(ShiftRepository.class).find(4L); // Shift 8h16
} else if (firstTime.isAfter(SHIFT_14h22_min) && firstTime.isBefore(SHIFT_14h22_max)) {
shift = Beans.get(ShiftRepository.class).find(1L); // Shift 14h22
shift = Beans.get(ShiftRepository.class).find(1L); // Shift 14h22
} else if (firstTime.isAfter(SHIFT_22h6_min) || firstTime.isBefore(SHIFT_22h6_max)) {
shift = Beans.get(ShiftRepository.class).find(2L); // Shift 22h6
shift = Beans.get(ShiftRepository.class).find(2L); // Shift 22h6
} else {
shift = Beans.get(ShiftRepository.class).find(50L); // N/A
shift = Beans.get(ShiftRepository.class).find(50L); // N/A
}
dailyReport.setShift(shift);
dailyReportRepository.save(dailyReport);
@@ -499,7 +558,8 @@ public class DailyReportServiceImpl implements DailyReportService {
return nightDuration1;
}
private Duration calculateSupplementaryHours(LocalDateTime enter, LocalDateTime quit, int shift, LocalDate reportDate) {
private Duration calculateSupplementaryHours(
LocalDateTime enter, LocalDateTime quit, int shift, LocalDate reportDate) {
// Calculate Supp hours for (0,1,2,3) shifts
Shift shiftInstance =
@@ -549,18 +609,22 @@ public class DailyReportServiceImpl implements DailyReportService {
return breakDuration;
}
private boolean areBreaksInAllowedRange(LocalDateTime[] enters, LocalDateTime[] quits, LocalTime allowedStartTime, LocalTime allowedEndTime) {
private boolean areBreaksInAllowedRange(
LocalDateTime[] enters,
LocalDateTime[] quits,
LocalTime allowedStartTime,
LocalTime allowedEndTime) {
for (int i = 1; i < quits.length; i++) {
if (enters[i] != null && quits[i - 1] != null) {
LocalTime breakStartTime = quits[i - 1].toLocalTime();
LocalTime breakEndTime = enters[i].toLocalTime();
if (enters[i] != null && quits[i - 1] != null) {
LocalTime breakStartTime = quits[i - 1].toLocalTime();
LocalTime breakEndTime = enters[i].toLocalTime();
// Check if the break falls outside the allowed range
if (breakStartTime.isBefore(allowedStartTime) || breakEndTime.isAfter(allowedEndTime)) {
return false;
}
// Check if the break falls outside the allowed range
if (breakStartTime.isBefore(allowedStartTime) || breakEndTime.isAfter(allowedEndTime)) {
return false;
}
}
}
return true;
@@ -568,11 +632,9 @@ public class DailyReportServiceImpl implements DailyReportService {
private BigDecimal calculateItp(BigDecimal totalHours, Integer shift, Boolean hasItp) {
// Shift 0 (no itp)
if (hasItp == true && shift != 0)
return totalHours.min(BigDecimal.valueOf(8));
else
return BigDecimal.ZERO;
}
if (hasItp == true && shift != 0) return totalHours.min(BigDecimal.valueOf(8));
else return BigDecimal.ZERO;
}
private void createOffDayWork(LocalDate reportDate, Employee employee) {
@@ -651,35 +713,38 @@ public class DailyReportServiceImpl implements DailyReportService {
}
@Transactional(rollbackOn = {Exception.class})
public void deducePrimes(DailyReport dailyReport, Integer primeSelection, BigDecimal valueToDeduce) throws AxelorException {
public void deducePrimes(
DailyReport dailyReport, Integer primeSelection, BigDecimal valueToDeduce)
throws AxelorException {
switch (primeSelection) {
case 1: // ITP
dailyReport.setDeduceItp(true);
dailyReport.setItpToDeduce(valueToDeduce);
break;
dailyReport.setDeduceItp(true);
dailyReport.setItpToDeduce(valueToDeduce);
break;
case 2: // Nuissance
dailyReport.setDeduceNuissance(true);
dailyReport.setItpToDeduce(valueToDeduce);
break;
dailyReport.setDeduceNuissance(true);
dailyReport.setItpToDeduce(valueToDeduce);
break;
case 3: // HS 50
dailyReport.setDeduceSupHours50(true);
dailyReport.setSupHours50ToDeduce(valueToDeduce);
break;
dailyReport.setDeduceSupHours50(true);
dailyReport.setSupHours50ToDeduce(valueToDeduce);
break;
case 4: // HS 100
dailyReport.setDeduceSupHours100(true);
dailyReport.setSupHours100ToDeduce(valueToDeduce);
break;
dailyReport.setDeduceSupHours100(true);
dailyReport.setSupHours100ToDeduce(valueToDeduce);
break;
default:
return; // Invalid configSelect, stop processing
return; // Invalid configSelect, stop processing
}
Beans.get(DailyReportRepository.class).save(dailyReport);
}
@Transactional(rollbackOn = {Exception.class})
public void massDeducePrimes(List<DailyReport> dailyReportList, Integer primeSelection, BigDecimal valueToDeduce) throws AxelorException {
public void massDeducePrimes(
List<DailyReport> dailyReportList, Integer primeSelection, BigDecimal valueToDeduce)
throws AxelorException {
for (DailyReport dailyReport : dailyReportList) {
this.deducePrimes(dailyReport, primeSelection, valueToDeduce);
}
}
}

View File

@@ -2,15 +2,14 @@ package com.axelor.apps.hr.service;
import com.axelor.apps.base.db.Period;
import com.axelor.apps.hr.db.Absence;
import com.axelor.apps.hr.db.Authorization;
import com.axelor.apps.hr.db.DailyReport;
import com.axelor.apps.hr.db.Employee;
import com.axelor.apps.hr.db.LeaveRequest;
import com.axelor.apps.hr.db.MonthlyReport;
import com.axelor.apps.hr.db.DailyReport;
import com.axelor.apps.hr.db.repo.AbsenceRepository;
import com.axelor.apps.hr.db.repo.AuthorizationRepository;
import com.axelor.apps.hr.db.repo.MonthlyReportRepository;
import com.axelor.apps.hr.db.repo.DailyReportRepository;
import com.axelor.apps.hr.db.repo.MonthlyReportRepository;
import com.google.inject.persist.Transactional;
import java.math.BigDecimal;
import java.time.LocalDate;
@@ -18,7 +17,6 @@ import java.time.temporal.TemporalAdjusters;
import java.util.List;
import java.util.Set;
import javax.inject.Inject;
import com.axelor.inject.Beans;
public class MonthlyReportServiceImpl implements MonthlyReportService {
@@ -42,8 +40,13 @@ public class MonthlyReportServiceImpl implements MonthlyReportService {
@Transactional
@Override
public void createMensuelReport(Employee employee, Period period, LocalDate startDate, LocalDate endDate, List<DailyReport> employeeDailyReports, List<Absence> employeeAbsences) {
public void createMensuelReport(
Employee employee,
Period period,
LocalDate startDate,
LocalDate endDate,
List<DailyReport> employeeDailyReports,
List<Absence> employeeAbsences) {
Boolean hasNuissance = employee.getHasNuissance();
LocalDate firstDayOfMonth = endDate.with(TemporalAdjusters.firstDayOfMonth());
@@ -61,7 +64,7 @@ public class MonthlyReportServiceImpl implements MonthlyReportService {
BigDecimal totalNuissance = BigDecimal.ZERO;
BigDecimal totalAbsence = BigDecimal.ZERO;
BigDecimal totalWorkHours = BigDecimal.ZERO;
BigDecimal breastfeedingAbsenceMonth = BigDecimal.ZERO;
BigDecimal authorizedPaidAbsenceMonth = BigDecimal.ZERO;
BigDecimal recuperationLeaveAbsenceMonth = BigDecimal.ZERO;
@@ -83,7 +86,7 @@ public class MonthlyReportServiceImpl implements MonthlyReportService {
BigDecimal militaryServiceAbsence = BigDecimal.ZERO;
BigDecimal irregularAbsenceMonth = BigDecimal.ZERO;
//monthlyAllowance = monthlyAllowance + remainingDateToLastOfMonth;
// monthlyAllowance = monthlyAllowance + remainingDateToLastOfMonth;
// Calculate totals for DailyReport
for (DailyReport dailyReport : employeeDailyReports) {
@@ -94,35 +97,49 @@ public class MonthlyReportServiceImpl implements MonthlyReportService {
monthlyAllowance = monthlyAllowance + 1;
}*/
monthlyAllowance = monthlyAllowance + dailyReport.getAllowance();;
monthlyAllowance = monthlyAllowance + dailyReport.getAllowance();
;
monthlyAllowanceRecall = monthlyAllowanceRecall + dailyReport.getAllowanceRecall();
monthlyNightHours = monthlyNightHours.add(dailyReport.getNightHours());
totalWorkHours = totalWorkHours.add(dailyReport.getWorkHours());
BigDecimal heureSup50 = dailyReport.getExtraHours50() != null ? dailyReport.getExtraHours50() : BigDecimal.ZERO;
BigDecimal heureSup100 = dailyReport.getExtraHours100() != null ? dailyReport.getExtraHours100() : BigDecimal.ZERO;
BigDecimal heureSup50 =
dailyReport.getExtraHours50() != null ? dailyReport.getExtraHours50() : BigDecimal.ZERO;
BigDecimal heureSup100 =
dailyReport.getExtraHours100() != null ? dailyReport.getExtraHours100() : BigDecimal.ZERO;
BigDecimal itp = dailyReport.getItp() != null ? dailyReport.getItp() : BigDecimal.ZERO;
BigDecimal nuissance = dailyReport.getNuissance() != null ? dailyReport.getNuissance() : BigDecimal.ZERO;
BigDecimal nuissance =
dailyReport.getNuissance() != null ? dailyReport.getNuissance() : BigDecimal.ZERO;
BigDecimal supHours50ToDeduce = dailyReport.getSupHours50ToDeduce() != null ? dailyReport.getSupHours50ToDeduce() : BigDecimal.ZERO;
BigDecimal supHours100ToDeduce = dailyReport.getSupHours100ToDeduce() != null ? dailyReport.getSupHours100ToDeduce() : BigDecimal.ZERO;
BigDecimal itpToDeduce = dailyReport.getItpToDeduce() != null ? dailyReport.getItpToDeduce() : BigDecimal.ZERO;
BigDecimal nuissanceToDeduce = dailyReport.getNuissanceToDeduce() != null ? dailyReport.getNuissanceToDeduce() : BigDecimal.ZERO;
BigDecimal supHours50ToDeduce =
dailyReport.getSupHours50ToDeduce() != null
? dailyReport.getSupHours50ToDeduce()
: BigDecimal.ZERO;
BigDecimal supHours100ToDeduce =
dailyReport.getSupHours100ToDeduce() != null
? dailyReport.getSupHours100ToDeduce()
: BigDecimal.ZERO;
BigDecimal itpToDeduce =
dailyReport.getItpToDeduce() != null ? dailyReport.getItpToDeduce() : BigDecimal.ZERO;
BigDecimal nuissanceToDeduce =
dailyReport.getNuissanceToDeduce() != null
? dailyReport.getNuissanceToDeduce()
: BigDecimal.ZERO;
if (dailyReport.getDeduceSupHours50() && heureSup50.compareTo(supHours50ToDeduce) > 0) {
heureSup50 = heureSup50.subtract(supHours50ToDeduce);
if (dailyReport.getDeduceSupHours50() && heureSup50.compareTo(supHours50ToDeduce) > 0) {
heureSup50 = heureSup50.subtract(supHours50ToDeduce);
}
if (dailyReport.getDeduceSupHours100() && heureSup100.compareTo(supHours100ToDeduce) > 0) {
heureSup100 = heureSup100.subtract(supHours100ToDeduce);
heureSup100 = heureSup100.subtract(supHours100ToDeduce);
}
if (dailyReport.getDeduceItp() && itp.compareTo(itpToDeduce) > 0) {
itp = itp.subtract(itpToDeduce);
itp = itp.subtract(itpToDeduce);
}
if (dailyReport.getDeduceNuissance() && nuissance.compareTo(nuissanceToDeduce) > 0) {
nuissance = nuissance.subtract(nuissanceToDeduce);
if (dailyReport.getDeduceNuissance() && nuissance.compareTo(nuissanceToDeduce) > 0) {
nuissance = nuissance.subtract(nuissanceToDeduce);
}
monthlyITP = monthlyITP.add(itp);
@@ -130,7 +147,7 @@ public class MonthlyReportServiceImpl implements MonthlyReportService {
// Sup Hours
if (dailyReport.getIsValidSupHours()) {
// Handle HeureSup50
if (heureSup50 != null) {
if (totalSupHours.add(heureSup50).compareTo(new BigDecimal(32)) <= 0) {
@@ -177,19 +194,25 @@ public class MonthlyReportServiceImpl implements MonthlyReportService {
LeaveRequest leaveRequest = dailyReport.getLeaveRequest();
Set<Absence> absences = dailyReport.getAbsenceSet();
if (dailyReport.getAbsenceHours() != null && dailyReport.getAbsenceHours().compareTo(BigDecimal.ZERO) > 0) {
if (isAuthorizedAbsence == false && isAuthorizedLateArrival == false && isAuthorizedEarlyDeparture == false && leaveRequest == null && absences == null) {
if (dailyReport.getAbsenceHours() != null
&& dailyReport.getAbsenceHours().compareTo(BigDecimal.ZERO) > 0) {
if (isAuthorizedAbsence == false
&& isAuthorizedLateArrival == false
&& isAuthorizedEarlyDeparture == false
&& leaveRequest == null
&& absences == null) {
irregularAbsenceMonth = irregularAbsenceMonth.add(dailyReport.getAbsenceHours());
} else if(isAuthorizedAbsence){
} else if (isAuthorizedAbsence) {
justifiedAbsenceMonth = justifiedAbsenceMonth.add(dailyReport.getAbsenceHours());
} else if(isAuthorizedLateArrival){
} else if (isAuthorizedLateArrival) {
justifiedAbsenceMonth = justifiedAbsenceMonth.add(dailyReport.getLateArrival());
} else if(isAuthorizedEarlyDeparture){
} else if (isAuthorizedEarlyDeparture) {
justifiedAbsenceMonth = justifiedAbsenceMonth.add(dailyReport.getEarlyDeparture());
} else if(leaveRequest != null){
recuperationLeaveAbsenceMonth = recuperationLeaveAbsenceMonth.add(dailyReport.getAbsenceHours());
} else if(absences != null){
for(Absence absence:absences){
} else if (leaveRequest != null) {
recuperationLeaveAbsenceMonth =
recuperationLeaveAbsenceMonth.add(dailyReport.getAbsenceHours());
} else if (absences != null) {
for (Absence absence : absences) {
totalAbsence = dailyReport.getAbsenceHours();
switch (absence.getAbsenceType()) {
case 0:
@@ -250,24 +273,26 @@ public class MonthlyReportServiceImpl implements MonthlyReportService {
militaryServiceAbsence = militaryServiceAbsence.add(totalAbsence);
break;
case 19:
if(dailyReport.getIsAuthorizedAbsence()){
if (dailyReport.getIsAuthorizedAbsence()) {
justifiedAbsenceMonth = justifiedAbsenceMonth.add(totalAbsence);
} else {
irregularAbsenceMonth = irregularAbsenceMonth.add(totalAbsence);
}
break;
case 20:
if(dailyReport.getIsAuthorizedLateArrival()){
if (dailyReport.getIsAuthorizedLateArrival()) {
justifiedAbsenceMonth = justifiedAbsenceMonth.add(dailyReport.getLateArrival());
} else {
irregularAbsenceMonth = irregularAbsenceMonth.add(dailyReport.getLateArrival());
}
break;
case 21:
if(dailyReport.getIsAuthorizedEarlyDeparture()){
justifiedAbsenceMonth = justifiedAbsenceMonth.add(dailyReport.getEarlyDeparture());
if (dailyReport.getIsAuthorizedEarlyDeparture()) {
justifiedAbsenceMonth =
justifiedAbsenceMonth.add(dailyReport.getEarlyDeparture());
} else {
irregularAbsenceMonth = irregularAbsenceMonth.add(dailyReport.getEarlyDeparture());
irregularAbsenceMonth =
irregularAbsenceMonth.add(dailyReport.getEarlyDeparture());
}
break;
default:
@@ -276,7 +301,7 @@ public class MonthlyReportServiceImpl implements MonthlyReportService {
}
}
}
}
}
}
// Update or create MonthlyReport instance with calculated values
@@ -321,7 +346,14 @@ public class MonthlyReportServiceImpl implements MonthlyReportService {
monthlyReportRepository.save(monthlyReport);
}
public void updateMensuelReport(MonthlyReport monthlyReport, Employee employee, Period period, LocalDate startDate, LocalDate endDate, List<DailyReport> employeeDailyReports, List<Absence> employeeAbsences) {
public void updateMensuelReport(
MonthlyReport monthlyReport,
Employee employee,
Period period,
LocalDate startDate,
LocalDate endDate,
List<DailyReport> employeeDailyReports,
List<Absence> employeeAbsences) {
Boolean hasNuissance = employee.getHasNuissance();
LocalDate firstDayOfMonth = endDate.with(TemporalAdjusters.firstDayOfMonth());
@@ -339,7 +371,7 @@ public class MonthlyReportServiceImpl implements MonthlyReportService {
BigDecimal totalNuissance = BigDecimal.ZERO;
BigDecimal totalAbsence = BigDecimal.ZERO;
BigDecimal totalWorkHours = BigDecimal.ZERO;
BigDecimal breastfeedingAbsenceMonth = BigDecimal.ZERO;
BigDecimal authorizedPaidAbsenceMonth = BigDecimal.ZERO;
BigDecimal recuperationLeaveAbsenceMonth = BigDecimal.ZERO;
@@ -361,7 +393,7 @@ public class MonthlyReportServiceImpl implements MonthlyReportService {
BigDecimal militaryServiceAbsence = BigDecimal.ZERO;
BigDecimal irregularAbsenceMonth = BigDecimal.ZERO;
//monthlyAllowance = monthlyAllowance + remainingDateToLastOfMonth;
// monthlyAllowance = monthlyAllowance + remainingDateToLastOfMonth;
// Calculate totals for DailyReport
for (DailyReport dailyReport : employeeDailyReports) {
@@ -372,35 +404,49 @@ public class MonthlyReportServiceImpl implements MonthlyReportService {
monthlyAllowance = monthlyAllowance + 1;
}*/
monthlyAllowance = monthlyAllowance + dailyReport.getAllowance();;
monthlyAllowance = monthlyAllowance + dailyReport.getAllowance();
;
monthlyAllowanceRecall = monthlyAllowanceRecall + dailyReport.getAllowanceRecall();
monthlyNightHours = monthlyNightHours.add(dailyReport.getNightHours());
totalWorkHours = totalWorkHours.add(dailyReport.getWorkHours());
BigDecimal heureSup50 = dailyReport.getExtraHours50() != null ? dailyReport.getExtraHours50() : BigDecimal.ZERO;
BigDecimal heureSup100 = dailyReport.getExtraHours100() != null ? dailyReport.getExtraHours100() : BigDecimal.ZERO;
BigDecimal heureSup50 =
dailyReport.getExtraHours50() != null ? dailyReport.getExtraHours50() : BigDecimal.ZERO;
BigDecimal heureSup100 =
dailyReport.getExtraHours100() != null ? dailyReport.getExtraHours100() : BigDecimal.ZERO;
BigDecimal itp = dailyReport.getItp() != null ? dailyReport.getItp() : BigDecimal.ZERO;
BigDecimal nuissance = dailyReport.getNuissance() != null ? dailyReport.getNuissance() : BigDecimal.ZERO;
BigDecimal nuissance =
dailyReport.getNuissance() != null ? dailyReport.getNuissance() : BigDecimal.ZERO;
BigDecimal supHours50ToDeduce = dailyReport.getSupHours50ToDeduce() != null ? dailyReport.getSupHours50ToDeduce() : BigDecimal.ZERO;
BigDecimal supHours100ToDeduce = dailyReport.getSupHours100ToDeduce() != null ? dailyReport.getSupHours100ToDeduce() : BigDecimal.ZERO;
BigDecimal itpToDeduce = dailyReport.getItpToDeduce() != null ? dailyReport.getItpToDeduce() : BigDecimal.ZERO;
BigDecimal nuissanceToDeduce = dailyReport.getNuissanceToDeduce() != null ? dailyReport.getNuissanceToDeduce() : BigDecimal.ZERO;
BigDecimal supHours50ToDeduce =
dailyReport.getSupHours50ToDeduce() != null
? dailyReport.getSupHours50ToDeduce()
: BigDecimal.ZERO;
BigDecimal supHours100ToDeduce =
dailyReport.getSupHours100ToDeduce() != null
? dailyReport.getSupHours100ToDeduce()
: BigDecimal.ZERO;
BigDecimal itpToDeduce =
dailyReport.getItpToDeduce() != null ? dailyReport.getItpToDeduce() : BigDecimal.ZERO;
BigDecimal nuissanceToDeduce =
dailyReport.getNuissanceToDeduce() != null
? dailyReport.getNuissanceToDeduce()
: BigDecimal.ZERO;
if (dailyReport.getDeduceSupHours50() && heureSup50.compareTo(supHours50ToDeduce) > 0) {
heureSup50 = heureSup50.subtract(supHours50ToDeduce);
if (dailyReport.getDeduceSupHours50() && heureSup50.compareTo(supHours50ToDeduce) > 0) {
heureSup50 = heureSup50.subtract(supHours50ToDeduce);
}
if (dailyReport.getDeduceSupHours100() && heureSup100.compareTo(supHours100ToDeduce) > 0) {
heureSup100 = heureSup100.subtract(supHours100ToDeduce);
heureSup100 = heureSup100.subtract(supHours100ToDeduce);
}
if (dailyReport.getDeduceItp() && itp.compareTo(itpToDeduce) > 0) {
itp = itp.subtract(itpToDeduce);
itp = itp.subtract(itpToDeduce);
}
if (dailyReport.getDeduceNuissance() && nuissance.compareTo(nuissanceToDeduce) > 0) {
nuissance = nuissance.subtract(nuissanceToDeduce);
if (dailyReport.getDeduceNuissance() && nuissance.compareTo(nuissanceToDeduce) > 0) {
nuissance = nuissance.subtract(nuissanceToDeduce);
}
monthlyITP = monthlyITP.add(itp);
@@ -408,7 +454,7 @@ public class MonthlyReportServiceImpl implements MonthlyReportService {
// Sup Hours
if (dailyReport.getIsValidSupHours()) {
// Handle HeureSup50
if (heureSup50 != null) {
if (totalSupHours.add(heureSup50).compareTo(new BigDecimal(32)) <= 0) {
@@ -455,19 +501,25 @@ public class MonthlyReportServiceImpl implements MonthlyReportService {
LeaveRequest leaveRequest = dailyReport.getLeaveRequest();
Set<Absence> absences = dailyReport.getAbsenceSet();
if (dailyReport.getAbsenceHours() != null && dailyReport.getAbsenceHours().compareTo(BigDecimal.ZERO) > 0) {
if (isAuthorizedAbsence == false && isAuthorizedLateArrival == false && isAuthorizedEarlyDeparture == false && leaveRequest == null && absences == null) {
if (dailyReport.getAbsenceHours() != null
&& dailyReport.getAbsenceHours().compareTo(BigDecimal.ZERO) > 0) {
if (isAuthorizedAbsence == false
&& isAuthorizedLateArrival == false
&& isAuthorizedEarlyDeparture == false
&& leaveRequest == null
&& absences == null) {
irregularAbsenceMonth = irregularAbsenceMonth.add(dailyReport.getAbsenceHours());
} else if(isAuthorizedAbsence){
} else if (isAuthorizedAbsence) {
justifiedAbsenceMonth = justifiedAbsenceMonth.add(dailyReport.getAbsenceHours());
} else if(isAuthorizedLateArrival){
} else if (isAuthorizedLateArrival) {
justifiedAbsenceMonth = justifiedAbsenceMonth.add(dailyReport.getLateArrival());
} else if(isAuthorizedEarlyDeparture){
} else if (isAuthorizedEarlyDeparture) {
justifiedAbsenceMonth = justifiedAbsenceMonth.add(dailyReport.getEarlyDeparture());
} else if(leaveRequest != null){
recuperationLeaveAbsenceMonth = recuperationLeaveAbsenceMonth.add(dailyReport.getAbsenceHours());
} else if(absences != null){
for(Absence absence:absences){
} else if (leaveRequest != null) {
recuperationLeaveAbsenceMonth =
recuperationLeaveAbsenceMonth.add(dailyReport.getAbsenceHours());
} else if (absences != null) {
for (Absence absence : absences) {
totalAbsence = dailyReport.getAbsenceHours();
switch (absence.getAbsenceType()) {
case 0:
@@ -528,24 +580,26 @@ public class MonthlyReportServiceImpl implements MonthlyReportService {
militaryServiceAbsence = militaryServiceAbsence.add(totalAbsence);
break;
case 19:
if(dailyReport.getIsAuthorizedAbsence()){
if (dailyReport.getIsAuthorizedAbsence()) {
justifiedAbsenceMonth = justifiedAbsenceMonth.add(totalAbsence);
} else {
irregularAbsenceMonth = irregularAbsenceMonth.add(totalAbsence);
}
break;
case 20:
if(dailyReport.getIsAuthorizedLateArrival()){
if (dailyReport.getIsAuthorizedLateArrival()) {
justifiedAbsenceMonth = justifiedAbsenceMonth.add(dailyReport.getLateArrival());
} else {
irregularAbsenceMonth = irregularAbsenceMonth.add(dailyReport.getLateArrival());
}
break;
case 21:
if(dailyReport.getIsAuthorizedEarlyDeparture()){
justifiedAbsenceMonth = justifiedAbsenceMonth.add(dailyReport.getEarlyDeparture());
if (dailyReport.getIsAuthorizedEarlyDeparture()) {
justifiedAbsenceMonth =
justifiedAbsenceMonth.add(dailyReport.getEarlyDeparture());
} else {
irregularAbsenceMonth = irregularAbsenceMonth.add(dailyReport.getEarlyDeparture());
irregularAbsenceMonth =
irregularAbsenceMonth.add(dailyReport.getEarlyDeparture());
}
break;
default:
@@ -554,7 +608,7 @@ public class MonthlyReportServiceImpl implements MonthlyReportService {
}
}
}
}
}
}
// Update or create MonthlyReport instance with calculated values

View File

@@ -253,7 +253,7 @@ public class EmployeeServiceImpl extends UserServiceImpl implements EmployeeServ
@Override
@Transactional
public void setEmployeeEnrolled(Employee employee){
public void setEmployeeEnrolled(Employee employee) {
employee.setIsEnrolled(true);
Beans.get(EmployeeRepository.class).save(employee);
}
@@ -263,29 +263,27 @@ public class EmployeeServiceImpl extends UserServiceImpl implements EmployeeServ
public void updateEmployeeConfig(Employee employee, Integer configSelect, Boolean status)
throws AxelorException {
switch (configSelect) {
case 1: // ITP
employee.setHasItp(status);
break;
case 2: // Nuissance
employee.setHasNuissance(status);
break;
case 3: // Transfaire
employee.setIsTransfaire(status);
break;
default:
return; // Invalid configSelect, stop processing
}
case 1: // ITP
employee.setHasItp(status);
break;
case 2: // Nuissance
employee.setHasNuissance(status);
break;
case 3: // Transfaire
employee.setIsTransfaire(status);
break;
default:
return; // Invalid configSelect, stop processing
}
Beans.get(EmployeeRepository.class).save(employee);
}
@Override
@Transactional(rollbackOn = {Exception.class})
public void massUpdateEmployeeConfig(List<Long> employeesIds, Integer configSelect, Boolean status) throws AxelorException{
public void massUpdateEmployeeConfig(
List<Long> employeesIds, Integer configSelect, Boolean status) throws AxelorException {
List<Employee> employees =
Beans.get(EmployeeRepository.class)
.all()
.filter("self.id in (?1)", employeesIds)
.fetch();
Beans.get(EmployeeRepository.class).all().filter("self.id in (?1)", employeesIds).fetch();
if (employeesIds != null || !employeesIds.isEmpty()) {
for (Employee employee : employees) {

View File

@@ -17,17 +17,16 @@
*/
package com.axelor.apps.hr.service.extra.hours;
import com.axelor.apps.hr.db.DailyReport;
import com.axelor.apps.hr.db.repo.EmployeeRepository;
import com.axelor.apps.hr.db.repo.DailyReportRepository;
import com.axelor.apps.hr.db.Employee;
import com.axelor.apps.base.db.Company;
import com.axelor.apps.base.db.repo.CompanyRepository;
import com.axelor.apps.base.service.app.AppBaseService;
import com.axelor.apps.hr.db.DailyReport;
import com.axelor.apps.hr.db.Employee;
import com.axelor.apps.hr.db.ExtraHours;
import com.axelor.apps.hr.db.ExtraHoursLine;
import com.axelor.apps.hr.db.HRConfig;
import com.axelor.apps.hr.db.repo.DailyReportRepository;
import com.axelor.apps.hr.db.repo.EmployeeRepository;
import com.axelor.apps.hr.db.repo.ExtraHoursRepository;
import com.axelor.apps.hr.service.config.HRConfigService;
import com.axelor.apps.message.db.Message;
@@ -37,13 +36,13 @@ import com.axelor.exception.AxelorException;
import com.google.inject.Inject;
import com.google.inject.persist.Transactional;
import java.io.IOException;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalTime;
import java.time.OffsetDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.util.ArrayList;
import java.math.BigDecimal;
import java.util.List;
import javax.mail.MessagingException;
import wslite.json.JSONException;
@@ -201,16 +200,17 @@ public class ExtraHoursServiceImpl implements ExtraHoursService {
String heureDebut = jsonObject.getString("heure_debut");
String heureFin = jsonObject.getString("heure_fin");
String lieuTravail = jsonObject.getString("lieu_travail");
int validation_status = jsonObject.optInt("validation_status",2);
String validateByUser = jsonObject.optString("validate_by_user",null);
String dateValidation = jsonObject.optString("validation_date",null);
int validation_status = jsonObject.optInt("validation_status", 2);
String validateByUser = jsonObject.optString("validate_by_user", null);
String dateValidation = jsonObject.optString("validation_date", null);
// GET EMPLOYEES
Employee employee = employeeRepo
.all()
.filter("self.registrationNumber = :matricule")
.bind("matricule", matricule)
.fetchOne();
Employee employee =
employeeRepo
.all()
.filter("self.registrationNumber = :matricule")
.bind("matricule", matricule)
.fetchOne();
if (employee == null) {
System.err.println("Employee with matricule " + matricule + " not found.");
@@ -219,29 +219,31 @@ public class ExtraHoursServiceImpl implements ExtraHoursService {
Employee validatedByEmployee = null;
if(validateByUser != null){
validatedByEmployee = employeeRepo
.all()
.filter("self.registrationNumber = :matricule")
.bind("matricule", validateByUser)
.fetchOne();
if (validateByUser != null) {
validatedByEmployee =
employeeRepo
.all()
.filter("self.registrationNumber = :matricule")
.bind("matricule", validateByUser)
.fetchOne();
if (validatedByEmployee == null) {
System.err.println("Validator employee with matricule " + validateByUser + " not found.");
return;
}
if (validatedByEmployee == null) {
System.err.println("Validator employee with matricule " + validateByUser + " not found.");
return;
}
}
// Parse validation date (handle null case)
LocalDate validationDate = null;
if (dateValidation != null && !dateValidation.isEmpty()) {
try {
OffsetDateTime offsetDateTime = OffsetDateTime.parse(dateValidation, DateTimeFormatter.ISO_OFFSET_DATE_TIME);
validationDate = offsetDateTime.toLocalDate(); // Extract only the date part
} catch (DateTimeParseException e) {
System.out.println("Error parsing dateValidation: " + dateValidation);
validationDate = null;
}
try {
OffsetDateTime offsetDateTime =
OffsetDateTime.parse(dateValidation, DateTimeFormatter.ISO_OFFSET_DATE_TIME);
validationDate = offsetDateTime.toLocalDate(); // Extract only the date part
} catch (DateTimeParseException e) {
System.out.println("Error parsing dateValidation: " + dateValidation);
validationDate = null;
}
}
// Parse Requisition Date
@@ -254,46 +256,49 @@ public class ExtraHoursServiceImpl implements ExtraHoursService {
}
// Check if Authorization exists by ticketId
ExtraHours extraHours = extraHoursRepo
.all()
.filter("self.ticketId = :ticketId")
.bind("ticketId", idInt)
.fetchOne();
ExtraHours extraHours =
extraHoursRepo
.all()
.filter("self.ticketId = :ticketId")
.bind("ticketId", idInt)
.fetchOne();
if (extraHours != null) {
// Authorization exists, compare previous and new status
int previousStatus = extraHours.getStatusSelect(); // Previous status
int newStatus = validation_status; // New status
// Authorization exists, compare previous and new status
int previousStatus = extraHours.getStatusSelect(); // Previous status
int newStatus = validation_status; // New status
if (previousStatus == 2 && newStatus == 3) {
System.out.println("Tickets :" + idInt + " Status changed from " + previousStatus + " to " + newStatus);
// Update the fields of the existing Authorization
extraHours.setValidatedByEmployee(validatedByEmployee);
extraHours.setValidationDate(validationDate);
extraHours.setStatusSelect(newStatus);
// Save the updated Authorization
extraHoursRepo.save(extraHours);
if (previousStatus == 2 && newStatus == 3) {
System.out.println(
"Tickets :" + idInt + " Status changed from " + previousStatus + " to " + newStatus);
// Update the fields of the existing Authorization
extraHours.setValidatedByEmployee(validatedByEmployee);
extraHours.setValidationDate(validationDate);
extraHours.setStatusSelect(newStatus);
// Save the updated Authorization
extraHoursRepo.save(extraHours);
// Get Daily report
DailyReport dailyReport =
dailyReportRepo
.all()
.filter("self.employee = :employee and self.reportDate = :reportDate")
.bind("employee", employee)
.bind("reportDate", requisitionDate)
.fetchOne();
// Get Daily report
DailyReport dailyReport =
dailyReportRepo
.all()
.filter("self.employee = :employee and self.reportDate = :reportDate")
.bind("employee", employee)
.bind("reportDate", requisitionDate)
.fetchOne();
if (dailyReport != null) {
dailyReport.setIsValidSupHours(true);
}
} else if (previousStatus == 2 && newStatus == 4) {
System.out.println("Tickets :" + idInt + " Status changed from " + previousStatus + " to " + newStatus);
extraHours.setRefusedByEmployee(validatedByEmployee);
extraHours.setRefusalDate(validationDate);
extraHours.setStatusSelect(newStatus);
// Save the updated Authorization
extraHoursRepo.save(extraHours);
}
if (dailyReport != null) {
dailyReport.setIsValidSupHours(true);
}
} else if (previousStatus == 2 && newStatus == 4) {
System.out.println(
"Tickets :" + idInt + " Status changed from " + previousStatus + " to " + newStatus);
extraHours.setRefusedByEmployee(validatedByEmployee);
extraHours.setRefusalDate(validationDate);
extraHours.setStatusSelect(newStatus);
// Save the updated Authorization
extraHoursRepo.save(extraHours);
}
} else {
// Create an instance of ExtraHours
extraHours = new ExtraHours();
@@ -325,14 +330,13 @@ public class ExtraHoursServiceImpl implements ExtraHoursService {
}
if (validation_status == 3) {
extraHours.setValidatedByEmployee(validatedByEmployee);
extraHours.setValidationDate(validationDate);
extraHours.setValidatedByEmployee(validatedByEmployee);
extraHours.setValidationDate(validationDate);
} else if (validation_status == 4) {
extraHours.setRefusedByEmployee(validatedByEmployee);
extraHours.setRefusalDate(validationDate);
extraHours.setRefusedByEmployee(validatedByEmployee);
extraHours.setRefusalDate(validationDate);
}
// Save the ExtraHours entity
extraHoursRepo.save(extraHours);
@@ -356,8 +360,7 @@ public class ExtraHoursServiceImpl implements ExtraHoursService {
// Add the new ExtraHours to the list
supHoursList.add(extraHours);
if (validation_status == 3)
dailyReport.setIsValidSupHours(true);
if (validation_status == 3) dailyReport.setIsValidSupHours(true);
// Set the updated list back to dailyReport
dailyReport.setSupHoursList(supHoursList);
}
@@ -369,5 +372,4 @@ public class ExtraHoursServiceImpl implements ExtraHoursService {
e.printStackTrace();
}
}
}

View File

@@ -27,14 +27,14 @@ import com.axelor.apps.base.db.repo.ICalendarEventRepository;
import com.axelor.apps.base.ical.ICalendarService;
import com.axelor.apps.base.service.app.AppBaseService;
import com.axelor.apps.base.service.weeklyplanning.WeeklyPlanningService;
import com.axelor.apps.hr.db.DailyReport;
import com.axelor.apps.hr.db.Employee;
import com.axelor.apps.hr.db.HRConfig;
import com.axelor.apps.hr.db.LeaveLine;
import com.axelor.apps.hr.db.LeaveReason;
import com.axelor.apps.hr.db.LeaveRequest;
import com.axelor.apps.hr.db.DailyReport;
import com.axelor.apps.hr.db.repo.EmployeeRepository;
import com.axelor.apps.hr.db.repo.DailyReportRepository;
import com.axelor.apps.hr.db.repo.EmployeeRepository;
import com.axelor.apps.hr.db.repo.LeaveLineRepository;
import com.axelor.apps.hr.db.repo.LeaveReasonRepository;
import com.axelor.apps.hr.db.repo.LeaveRequestRepository;
@@ -57,14 +57,13 @@ import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.OffsetDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.util.List;
import javax.mail.MessagingException;
import wslite.json.JSONException;
import wslite.json.JSONObject;
import java.time.OffsetDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
public class LeaveServiceImpl implements LeaveService {
@@ -945,47 +944,50 @@ public class LeaveServiceImpl implements LeaveService {
String dateDebut = jsonObject.getString("de");
String dateFin = jsonObject.getString("a");
String commentaire = jsonObject.getString("commentaire");
int validation_status = jsonObject.optInt("validation_status",2);
String validateByUser = jsonObject.optString("validate_by_user",null);
String dateValidation = jsonObject.optString("validation_date",null);
int validation_status = jsonObject.optInt("validation_status", 2);
String validateByUser = jsonObject.optString("validate_by_user", null);
String dateValidation = jsonObject.optString("validation_date", null);
// GET EMPLOYEES
Employee employee = employeeRepo
.all()
.filter("self.registrationNumber = :matricule")
.bind("matricule", matricule)
.fetchOne();
Employee employee =
employeeRepo
.all()
.filter("self.registrationNumber = :matricule")
.bind("matricule", matricule)
.fetchOne();
if (employee == null) {
System.err.println("Employee with matricule " + matricule + " not found.");
return;
System.err.println("Employee with matricule " + matricule + " not found.");
return;
}
Employee validatedByEmployee = null;
if(validateByUser != null){
validatedByEmployee = employeeRepo
.all()
.filter("self.registrationNumber = :matricule")
.bind("matricule", validateByUser)
.fetchOne();
if (validateByUser != null) {
validatedByEmployee =
employeeRepo
.all()
.filter("self.registrationNumber = :matricule")
.bind("matricule", validateByUser)
.fetchOne();
if (validatedByEmployee == null) {
System.err.println("Validator employee with matricule " + validateByUser + " not found.");
return;
}
if (validatedByEmployee == null) {
System.err.println("Validator employee with matricule " + validateByUser + " not found.");
return;
}
}
// Parse validation date (handle null case)
LocalDate validationDate = null;
if (dateValidation != null && !dateValidation.isEmpty()) {
try {
OffsetDateTime offsetDateTime = OffsetDateTime.parse(dateValidation, DateTimeFormatter.ISO_OFFSET_DATE_TIME);
validationDate = offsetDateTime.toLocalDate(); // Extract only the date part
} catch (DateTimeParseException e) {
System.out.println("Error parsing dateValidation: " + dateValidation);
validationDate = null;
}
try {
OffsetDateTime offsetDateTime =
OffsetDateTime.parse(dateValidation, DateTimeFormatter.ISO_OFFSET_DATE_TIME);
validationDate = offsetDateTime.toLocalDate(); // Extract only the date part
} catch (DateTimeParseException e) {
System.out.println("Error parsing dateValidation: " + dateValidation);
validationDate = null;
}
}
// Parse Dates
@@ -1008,18 +1010,20 @@ public class LeaveServiceImpl implements LeaveService {
LocalDateTime debutDateTime = debutDate.atStartOfDay();
LocalDateTime finDateTime = finDate.atStartOfDay();
LeaveRequest leaveRequest = leaveRequestRepo
.all()
.filter("self.ticketId = :ticketId")
.bind("ticketId", idInt)
.fetchOne();
if (leaveRequest != null) {
LeaveRequest leaveRequest =
leaveRequestRepo
.all()
.filter("self.ticketId = :ticketId")
.bind("ticketId", idInt)
.fetchOne();
if (leaveRequest != null) {
// Authorization exists, compare previous and new status
int previousStatus = leaveRequest.getStatusSelect(); // Previous status
int newStatus = validation_status; // New status
int previousStatus = leaveRequest.getStatusSelect(); // Previous status
int newStatus = validation_status; // New status
if (previousStatus == 2 && newStatus == 3) {
System.out.println("Tickets :" + idInt + " Status changed from " + previousStatus + " to " + newStatus);
System.out.println(
"Tickets :" + idInt + " Status changed from " + previousStatus + " to " + newStatus);
// Update the fields of the existing Authorization
leaveRequest.setValidatedByEmployee(validatedByEmployee);
leaveRequest.setValidationDate(validationDate);
@@ -1027,27 +1031,30 @@ public class LeaveServiceImpl implements LeaveService {
// Save the updated Authorization
leaveRequestRepo.save(leaveRequest);
// Get Daily report
List<DailyReport> dailyReports = dailyReportRepo
.all()
.filter("self.employee = :employee and self.reportDate >= :debutDate and self.reportDate <= :finDate")
.bind("employee", employee)
.bind("debutDate", debutDate)
.bind("finDate", finDate)
.fetch();
List<DailyReport> dailyReports =
dailyReportRepo
.all()
.filter(
"self.employee = :employee and self.reportDate >= :debutDate and self.reportDate <= :finDate")
.bind("employee", employee)
.bind("debutDate", debutDate)
.bind("finDate", finDate)
.fetch();
if (dailyReports != null) {
for (DailyReport dailyReport : dailyReports) {
dailyReport.setIsAuthorizedAbsence(true);
dailyReportRepo.save(dailyReport);
dailyReport.setIsAuthorizedAbsence(true);
dailyReportRepo.save(dailyReport);
}
}
} else if (previousStatus == 2 && newStatus == 4) {
System.out.println("Tickets :" + idInt + " Status changed from " + previousStatus + " to " + newStatus);
leaveRequest.setRefusedByEmployee(validatedByEmployee);
leaveRequest.setRefusalDate(validationDate);
leaveRequest.setStatusSelect(newStatus);
// Save the updated Authorization
leaveRequestRepo.save(leaveRequest);
System.out.println(
"Tickets :" + idInt + " Status changed from " + previousStatus + " to " + newStatus);
leaveRequest.setRefusedByEmployee(validatedByEmployee);
leaveRequest.setRefusalDate(validationDate);
leaveRequest.setStatusSelect(newStatus);
// Save the updated Authorization
leaveRequestRepo.save(leaveRequest);
}
} else {
// Create an instance of ExtraHours
@@ -1062,30 +1069,31 @@ public class LeaveServiceImpl implements LeaveService {
leaveRequest.setCompany(company);
if (validation_status == 3) {
leaveRequest.setValidatedByEmployee(validatedByEmployee);
leaveRequest.setValidationDate(validationDate);
leaveRequest.setValidatedByEmployee(validatedByEmployee);
leaveRequest.setValidationDate(validationDate);
} else if (validation_status == 4) {
leaveRequest.setRefusedByEmployee(validatedByEmployee);
leaveRequest.setRefusalDate(validationDate);
leaveRequest.setRefusedByEmployee(validatedByEmployee);
leaveRequest.setRefusalDate(validationDate);
}
// Save the ExtraHours entity
leaveRequestRepo.save(leaveRequest);
// Get Daily report
List<DailyReport> dailyReports = dailyReportRepo
.all()
.filter("self.employee = :employee and self.reportDate >= :debutDate and self.reportDate <= :finDate")
.bind("employee", employee)
.bind("debutDate", debutDate)
.bind("finDate", finDate)
.fetch();
List<DailyReport> dailyReports =
dailyReportRepo
.all()
.filter(
"self.employee = :employee and self.reportDate >= :debutDate and self.reportDate <= :finDate")
.bind("employee", employee)
.bind("debutDate", debutDate)
.bind("finDate", finDate)
.fetch();
if (dailyReports != null) {
for (DailyReport dailyReport : dailyReports) {
dailyReport.setLeaveRequest(leaveRequest); // Set the recup leave for each report
if(validation_status == 3)
dailyReport.setIsAuthorizedAbsence(true);
if (validation_status == 3) dailyReport.setIsAuthorizedAbsence(true);
dailyReportRepo.save(dailyReport);
}
}
@@ -1097,5 +1105,4 @@ public class LeaveServiceImpl implements LeaveService {
e.printStackTrace();
}
}
}

View File

@@ -1,23 +1,21 @@
package com.axelor.apps.hr.web;
import com.axelor.apps.hr.db.Absence;
import com.axelor.apps.hr.db.Employee;
import com.axelor.apps.hr.db.DailyReport;
import com.axelor.apps.hr.db.Employee;
import com.axelor.apps.hr.db.repo.AbsenceRepository;
import com.axelor.apps.hr.db.repo.DailyReportRepository;
import com.axelor.apps.hr.service.AbsenceServiceImpl;
import com.axelor.i18n.I18n;
import com.axelor.inject.Beans;
import com.axelor.meta.schema.actions.ActionView;
import com.axelor.meta.schema.actions.ActionView.ActionViewBuilder;
import com.axelor.rpc.ActionRequest;
import com.axelor.rpc.ActionResponse;
import java.math.BigDecimal;
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.List;
import com.axelor.i18n.I18n;
import com.axelor.meta.schema.actions.ActionView;
import com.axelor.meta.schema.actions.ActionView.ActionViewBuilder;
import java.util.stream.Collectors;
public class AbsenceController {
@@ -32,35 +30,40 @@ public class AbsenceController {
Employee employee = absence.getEmployee();
// Fetch all existing daily reports associated with this absence
List<DailyReport> existingReports =
Beans.get(DailyReportRepository.class)
.all()
.filter("self.absenceSet = :absence")
.bind("absence", absence)
.fetch();
List<DailyReport> existingReports =
Beans.get(DailyReportRepository.class)
.all()
.filter("self.absenceSet = :absence")
.bind("absence", absence)
.fetch();
if (existingReports != null && !existingReports.isEmpty()) {
// Detach absence only from reports that are outside the new date range
List<DailyReport> reportsToDetach = existingReports.stream()
.filter(report -> report.getReportDate().isBefore(absenceStartDate) || report.getReportDate().isAfter(absenceEndDate))
.collect(Collectors.toList());
List<DailyReport> reportsToDetach =
existingReports
.stream()
.filter(
report ->
report.getReportDate().isBefore(absenceStartDate)
|| report.getReportDate().isAfter(absenceEndDate))
.collect(Collectors.toList());
// Detach absence from these specific reports
if (!reportsToDetach.isEmpty()) {
Beans.get(AbsenceServiceImpl.class).deAttachTheAbsenceWithDailyReport(absence, reportsToDetach, false);
Beans.get(AbsenceServiceImpl.class)
.deAttachTheAbsenceWithDailyReport(absence, reportsToDetach, false);
}
}
}
List<DailyReport> newReports =
Beans.get(DailyReportRepository.class)
.all()
.filter(
"self.employee = :employee and self.reportDate between :absenceStartDate and :absenceEndDate")
.bind("employee", employee)
.bind("absenceStartDate", absenceStartDate)
.bind("absenceEndDate", absenceEndDate)
.fetch();
Beans.get(DailyReportRepository.class)
.all()
.filter(
"self.employee = :employee and self.reportDate between :absenceStartDate and :absenceEndDate")
.bind("employee", employee)
.bind("absenceStartDate", absenceStartDate)
.bind("absenceEndDate", absenceEndDate)
.fetch();
// Check if there are any reports
if (newReports.isEmpty()) {
@@ -108,25 +111,26 @@ public class AbsenceController {
Long absenceId = (Long) request.getContext().asType(Absence.class).getId();
Absence absence = Beans.get(AbsenceRepository.class).find(absenceId);
List<DailyReport> dailyreports = Beans.get(DailyReportRepository.class)
.all()
.filter("self.absence = :absence")
.bind("absence", absenceId)
.fetch();
List<DailyReport> dailyreports =
Beans.get(DailyReportRepository.class)
.all()
.filter("self.absence = :absence")
.bind("absence", absenceId)
.fetch();
Beans.get(AbsenceServiceImpl.class).deAttachTheAbsenceWithDailyReport(absence, dailyreports, true);
Beans.get(AbsenceServiceImpl.class)
.deAttachTheAbsenceWithDailyReport(absence, dailyreports, true);
ActionViewBuilder actionView =
ActionView.define(I18n.get("Absences"))
.model(Absence.class.getName())
.add("grid", "absence-grid")
.add("form", "absence-form");
ActionView.define(I18n.get("Absences"))
.model(Absence.class.getName())
.add("grid", "absence-grid")
.add("form", "absence-form");
response.setView(actionView.map());
} catch (Exception e) {
e.printStackTrace();
}
}
public void calculateTotalAbsenceHours(ActionRequest request, ActionResponse response) {
try {
@@ -137,9 +141,10 @@ public class AbsenceController {
LocalDateTime absenceEndDate = absence.getEndDate();
if (absenceStartDate.isAfter(absenceEndDate)) {
response.setAlert("Start date cannot be after end date.");
}
else {
BigDecimal totalAbsenceHours = Beans.get(AbsenceServiceImpl.class).calculateTotalAbsenceHours(absenceStartDate,absenceEndDate);
} else {
BigDecimal totalAbsenceHours =
Beans.get(AbsenceServiceImpl.class)
.calculateTotalAbsenceHours(absenceStartDate, absenceEndDate);
response.setValue("totalAbsenceHours", totalAbsenceHours);
}
} catch (Exception e) {

View File

@@ -168,7 +168,8 @@ public class AuthorizationController {
}
} catch (Exception e) {
// General catch for unexpected exceptions
System.err.println("An error occurred while fetching Salary Authorization: " + e.getMessage());
System.err.println(
"An error occurred while fetching Salary Authorization: " + e.getMessage());
e.printStackTrace();
}
}
@@ -369,5 +370,4 @@ public class AuthorizationController {
}
}
}
}

View File

@@ -1,28 +1,24 @@
package com.axelor.apps.hr.web;
import com.axelor.apps.hr.db.Shift;
import com.axelor.apps.hr.db.Employee;
import com.axelor.apps.hr.db.DailyReport;
import com.axelor.apps.hr.db.Employee;
import com.axelor.apps.hr.db.repo.DailyReportRepository;
import com.axelor.apps.hr.db.repo.ShiftRepository;
import com.axelor.apps.hr.db.repo.EmployeeRepository;
import com.axelor.apps.hr.service.DailyReportService;
import com.axelor.apps.hr.service.DailyReportServiceImpl;
import com.axelor.exception.service.TraceBackService;
import com.axelor.inject.Beans;
import com.axelor.rpc.ActionRequest;
import com.axelor.rpc.ActionResponse;
import java.lang.invoke.MethodHandles;
import java.util.LinkedHashMap;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.format.DateTimeParseException;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.time.LocalDateTime;
import java.time.format.DateTimeParseException;
import java.time.LocalTime;
import java.time.LocalDate;
import java.math.BigDecimal;
import com.axelor.exception.service.TraceBackService;
public class DailyReportController {
@@ -32,14 +28,12 @@ public class DailyReportController {
* @param request
* @param response
*/
public void workingHours(ActionRequest request, ActionResponse response) {
try {
Long dailyReportId = (Long) request.getContext().asType(DailyReport.class).getId();
DailyReport DailyReport = Beans.get(DailyReportRepository.class).find(dailyReportId);
if (DailyReport == null) {
throw new IllegalArgumentException(
"DailyReport with ID " + dailyReportId + " not found.");
throw new IllegalArgumentException("DailyReport with ID " + dailyReportId + " not found.");
}
Beans.get(DailyReportServiceImpl.class).determineShift(DailyReport);
Beans.get(DailyReportServiceImpl.class).workingHours(DailyReport);
@@ -55,8 +49,7 @@ public class DailyReportController {
Long dailyReportId = (Long) request.getContext().asType(DailyReport.class).getId();
DailyReport DailyReport = Beans.get(DailyReportRepository.class).find(dailyReportId);
if (DailyReport == null) {
throw new IllegalArgumentException(
"DailyReport with ID " + dailyReportId + " not found.");
throw new IllegalArgumentException("DailyReport with ID " + dailyReportId + " not found.");
}
Beans.get(DailyReportServiceImpl.class).workingHours(DailyReport);
response.setReload(true);
@@ -95,34 +88,33 @@ public class DailyReportController {
List<DailyReport> dailyReportList =
Beans.get(DailyReportRepository.class)
.all()
.filter(
"self.id in ?1 ",dailyReportIds)
.filter("self.id in ?1 ", dailyReportIds)
.fetch();
for(DailyReport dailyReport: dailyReportList){
for (DailyReport dailyReport : dailyReportList) {
Beans.get(DailyReportServiceImpl.class).determineShift(dailyReport);
}
Beans.get(DailyReportServiceImpl.class).workingHoursForAll(dailyReportList);
response.setFlash("Working hours calculated successfully.");
} else {
response.setFlash("No Daily report selected");
response.setFlash("No Daily report selected");
}
}
public void workingHoursForChangedInstances(ActionRequest request, ActionResponse response) {
List<DailyReport> dailyReportList =
Beans.get(DailyReportRepository.class)
.all()
.filter("self.isCalculated = ? and self.isChanged = ?", false,true)
.fetch();
for(DailyReport dailyReport: dailyReportList){
Beans.get(DailyReportServiceImpl.class).determineShift(dailyReport);
}
List<DailyReport> dailyReportList =
Beans.get(DailyReportRepository.class)
.all()
.filter("self.isCalculated = ? and self.isChanged = ?", false, true)
.fetch();
Beans.get(DailyReportServiceImpl.class).workingHoursForAll(dailyReportList);
response.setReload(true);
response.setFlash("Working hours calculated successfully.");
for (DailyReport dailyReport : dailyReportList) {
Beans.get(DailyReportServiceImpl.class).determineShift(dailyReport);
}
Beans.get(DailyReportServiceImpl.class).workingHoursForAll(dailyReportList);
response.setReload(true);
response.setFlash("Working hours calculated successfully.");
}
public void massDeducePrime(ActionRequest request, ActionResponse response) {
@@ -135,46 +127,49 @@ public class DailyReportController {
LocalDate endDate = null;
try {
if (startDateStr != null) {
startDate = LocalDate.parse(startDateStr);
}
if (endDateStr != null) {
endDate = LocalDate.parse(endDateStr);
}
if (startDateStr != null) {
startDate = LocalDate.parse(startDateStr);
}
if (endDateStr != null) {
endDate = LocalDate.parse(endDateStr);
}
// Validate the dates
if (startDate == null || endDate == null) {
response.setFlash("Start date or end date is missing or invalid.");
return;
}
// Validate the dates
if (startDate == null || endDate == null) {
response.setFlash("Start date or end date is missing or invalid.");
return;
}
if (startDate.isAfter(endDate)) {
response.setFlash("Start date cannot be after end date.");
return;
}
if (startDate.isAfter(endDate)) {
response.setFlash("Start date cannot be after end date.");
return;
}
} catch (DateTimeParseException e) {
response.setFlash("Invalid date format for startDate or endDate. Expected format: yyyy-MM-dd.");
return;
response.setFlash(
"Invalid date format for startDate or endDate. Expected format: yyyy-MM-dd.");
return;
}
Object valueToDeduceObj = request.getContext().get("valueToDeduce");
BigDecimal valueToDeduce = null;
if (valueToDeduceObj instanceof Integer) {
valueToDeduce = BigDecimal.valueOf((Integer) valueToDeduceObj);
valueToDeduce = BigDecimal.valueOf((Integer) valueToDeduceObj);
} else if (valueToDeduceObj instanceof BigDecimal) {
valueToDeduce = (BigDecimal) valueToDeduceObj;
valueToDeduce = (BigDecimal) valueToDeduceObj;
} else if (valueToDeduceObj instanceof String) {
try {
valueToDeduce = new BigDecimal((String) valueToDeduceObj);
} catch (NumberFormatException e) {
response.setFlash("Value to deduce must be a valid number.");
return;
}
} else {
response.setFlash("Invalid value to deduce: unsupported type " + (valueToDeduceObj != null ? valueToDeduceObj.getClass().getName() : "null"));
try {
valueToDeduce = new BigDecimal((String) valueToDeduceObj);
} catch (NumberFormatException e) {
response.setFlash("Value to deduce must be a valid number.");
return;
}
} else {
response.setFlash(
"Invalid value to deduce: unsupported type "
+ (valueToDeduceObj != null ? valueToDeduceObj.getClass().getName() : "null"));
return;
}
Object employeesObject = request.getContext().get("employees");
@@ -183,53 +178,56 @@ public class DailyReportController {
List<Employee> employees = new ArrayList<>();
if (employeesObject instanceof List) {
List<LinkedHashMap<String, Object>> employeesList = (List<LinkedHashMap<String, Object>>) employeesObject;
List<LinkedHashMap<String, Object>> employeesList =
(List<LinkedHashMap<String, Object>>) employeesObject;
for (LinkedHashMap<String, Object> employeeMap : employeesList) {
Integer employeeIdInt = (Integer) employeeMap.get("id");
for (LinkedHashMap<String, Object> employeeMap : employeesList) {
Integer employeeIdInt = (Integer) employeeMap.get("id");
if (employeeIdInt != null) {
Long employeeId = employeeIdInt.longValue();
Employee employee = Beans.get(EmployeeRepository.class).find(employeeId);
if (employeeIdInt != null) {
Long employeeId = employeeIdInt.longValue();
Employee employee = Beans.get(EmployeeRepository.class).find(employeeId);
if (employee != null) {
employees.add(employee);
}
}
if (employee != null) {
employees.add(employee);
}
}
}
}
if (employees.isEmpty()) {
response.setFlash("No employees selected.");
return;
response.setFlash("No employees selected.");
return;
}
List<Integer> employeeIds = new ArrayList<>();
for (Employee employee : employees) {
employeeIds.add(employee.getId().intValue());
employeeIds.add(employee.getId().intValue());
}
// Fetch all rapport journaliers within the date range for all employees
List<DailyReport> dailyReportList = Beans.get(DailyReportRepository.class)
List<DailyReport> dailyReportList =
Beans.get(DailyReportRepository.class)
.all()
.filter("self.employee.id in :employeeIds and self.reportDate >= :startDate and self.reportDate <= :endDate")
.filter(
"self.employee.id in :employeeIds and self.reportDate >= :startDate and self.reportDate <= :endDate")
.bind("startDate", startDate)
.bind("endDate", endDate)
.bind("employeeIds", employeeIds)
.fetch();
try {
if (!dailyReportList.isEmpty()) {
Beans.get(DailyReportService.class).massDeducePrimes(dailyReportList, primeSelection, valueToDeduce);
response.setReload(true);
response.setFlash("Prime deductions processed successfully.");
} else {
response.setFlash("No reports found for the selected date range.");
}
if (!dailyReportList.isEmpty()) {
Beans.get(DailyReportService.class)
.massDeducePrimes(dailyReportList, primeSelection, valueToDeduce);
response.setReload(true);
response.setFlash("Prime deductions processed successfully.");
} else {
response.setFlash("No reports found for the selected date range.");
}
} catch (Exception e) {
TraceBackService.trace(response, e);
response.setFlash("An error occurred while processing the request.");
TraceBackService.trace(response, e);
response.setFlash("An error occurred while processing the request.");
}
}
}

View File

@@ -17,13 +17,14 @@
*/
package com.axelor.apps.hr.web;
import com.axelor.apps.hr.db.Granding;
import com.axelor.apps.hr.db.repo.GrandingRepository;
import com.axelor.app.AppSettings;
import com.axelor.apps.ReportFactory;
import com.axelor.apps.base.db.Partner;
import com.axelor.apps.hr.db.DPAE;
import com.axelor.apps.hr.db.Employee;
import com.axelor.apps.hr.db.Granding;
import com.axelor.apps.hr.db.repo.EmployeeRepository;
import com.axelor.apps.hr.db.repo.GrandingRepository;
import com.axelor.apps.hr.report.IReport;
import com.axelor.apps.hr.service.employee.EmployeeService;
import com.axelor.apps.report.engine.ReportSettings;
@@ -38,17 +39,16 @@ import com.axelor.meta.schema.actions.ActionView.ActionViewBuilder;
import com.axelor.rpc.ActionRequest;
import com.axelor.rpc.ActionResponse;
import com.google.inject.Singleton;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.invoke.MethodHandles;
import java.util.Map;
import java.util.List;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import wslite.json.JSONException;
import wslite.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import com.axelor.app.AppSettings;
@Singleton
public class EmployeeController {
@@ -149,22 +149,21 @@ public class EmployeeController {
response.setReload(true);
}
public void enrollEmployee(ActionRequest request, ActionResponse response){
public void enrollEmployee(ActionRequest request, ActionResponse response) {
Long employeeId = (Long) request.getContext().asType(Employee.class).getId();
Employee employee = Beans.get(EmployeeRepository.class).find(employeeId);
Granding granding = Beans.get(GrandingRepository.class)
.all()
.filter("self.name = 'POINTEUSE-RDC'")
.fetchOne();
Granding granding =
Beans.get(GrandingRepository.class).all().filter("self.name = 'POINTEUSE-RDC'").fetchOne();
String ipAdress = granding.getIpAdress();
String code = granding.getCode().toString();
if(employee.getIsEnrolled()) {
if (employee.getIsEnrolled()) {
response.setFlash("Employee is already enrolled.");
} else {
if (employee.getContactPartner() != null){
if (employee.getContactPartner() != null) {
String employeeRegistrationNumber = employee.getRegistrationNumber();
String employeeName = employee.getContactPartner().getName();
@@ -172,54 +171,61 @@ public class EmployeeController {
LOG.error("Pythons script path is not configured in AppSettings.");
return;
}
try {
String[] args = {
"python",
pythonScriptDir + "\\Attendance\\main.py",
"--commande", "create",
"--ip_address", ipAdress,
"--code", code,
"--user_id", employeeRegistrationNumber,
"--name", employeeName
"--commande",
"create",
"--ip_address",
ipAdress,
"--code",
code,
"--user_id",
employeeRegistrationNumber,
"--name",
employeeName
};
Process p = Runtime.getRuntime().exec(args);
// Capture the output stream (standard output)
BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
LOG.info("Python script (Employee Enrolling) output: " + line);
}
// Capture the error stream (standard error)
BufferedReader errorReader = new BufferedReader(new InputStreamReader(p.getErrorStream()));
BufferedReader errorReader =
new BufferedReader(new InputStreamReader(p.getErrorStream()));
while ((line = errorReader.readLine()) != null) {
LOG.error("Python script (Employee Enrolling) error: " + line);
}
// Wait for the process to complete and check the exit value
int exitCode = p.waitFor();
// Check if the process ran successfully
if (exitCode == 0) {
LOG.info("Python script executed successfully (Employee Enrolling).");
Beans.get(EmployeeService.class).setEmployeeEnrolled(employee);
response.setFlash("Employee enrolled successfully.");
} else {
LOG.error("Python script execution (Employee Enrolling) failed with exit code: " + exitCode);
LOG.error(
"Python script execution (Employee Enrolling) failed with exit code: " + exitCode);
response.setFlash("Failed to enroll the Employee.");
}
} catch (IOException e) {
// Check if the file is not found based on the message or error code
if (e.getMessage().contains("The system cannot find the file specified")) {
LOG.error("Python script file (Employee Enrolling) not found: " + e.getMessage());
} else {
LOG.error("An error occurred while executing the Python script (Employee Enrolling).", e);
LOG.error(
"An error occurred while executing the Python script (Employee Enrolling).", e);
}
response.setFlash("Failed to enroll the Employee.");
TraceBackService.trace(e);
@@ -246,7 +252,7 @@ public class EmployeeController {
}
try {
if (!employeeIds.isEmpty()) {
Beans.get(EmployeeService.class).massUpdateEmployeeConfig(employeeIds, configSelect,true);
Beans.get(EmployeeService.class).massUpdateEmployeeConfig(employeeIds, configSelect, true);
response.setReload(true);
}
} catch (Exception e) {
@@ -267,13 +273,12 @@ public class EmployeeController {
}
try {
if (!employeeIds.isEmpty()) {
Beans.get(EmployeeService.class).massUpdateEmployeeConfig(employeeIds, configSelect,false);
Beans.get(EmployeeService.class).massUpdateEmployeeConfig(employeeIds, configSelect, false);
response.setReload(true);
}
} catch (Exception e) {
TraceBackService.trace(response, e);
}
}
}
}

View File

@@ -1,22 +1,17 @@
package com.axelor.apps.hr.web;
import com.axelor.apps.hr.db.Granding;
import com.axelor.apps.hr.db.repo.GrandingRepository;
import com.axelor.exception.service.TraceBackService;
import com.axelor.inject.Beans;
import com.axelor.rpc.ActionRequest;
import com.axelor.rpc.ActionResponse;
import java.time.temporal.TemporalAdjusters;
import java.util.LinkedHashMap;
import java.util.stream.Collectors;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.invoke.MethodHandles;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.lang.invoke.MethodHandles;
import com.axelor.exception.service.TraceBackService;
import java.io.IOException;
public class GrandingController {
@@ -31,15 +26,18 @@ public class GrandingController {
String code = granding.getCode().toString();
try {
String[] args = {
"python",
"C:\\Users\\administrator\\Desktop\\attendance\\main.py",
"--commande", "ping",
"--ip_address", ipAdress,
"--code", code
"--commande",
"ping",
"--ip_address",
ipAdress,
"--code",
code
};
Process p = Runtime.getRuntime().exec(args);
// Capture the output stream (standard output)
@@ -83,4 +81,4 @@ public class GrandingController {
Thread.currentThread().interrupt();
}
}
}
}

View File

@@ -3,26 +3,26 @@ package com.axelor.apps.hr.web;
import com.axelor.apps.base.db.Period;
import com.axelor.apps.base.db.repo.PeriodRepository;
import com.axelor.apps.hr.db.Absence;
import com.axelor.apps.hr.db.Employee;
import com.axelor.apps.hr.db.DailyReport;
import com.axelor.apps.hr.db.Employee;
import com.axelor.apps.hr.db.MonthlyReport;
import com.axelor.apps.hr.db.repo.AbsenceRepository;
import com.axelor.apps.hr.db.repo.DailyReportRepository;
import com.axelor.apps.hr.db.repo.EmployeeRepository;
import com.axelor.apps.hr.db.repo.MonthlyReportRepository;
import com.axelor.apps.hr.db.repo.DailyReportRepository;
import com.axelor.apps.hr.service.MonthlyReportServiceImpl;
import com.axelor.inject.Beans;
import com.axelor.rpc.ActionRequest;
import com.axelor.rpc.ActionResponse;
import java.lang.invoke.MethodHandles;
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.temporal.TemporalAdjusters;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import java.lang.invoke.MethodHandles;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -41,7 +41,7 @@ public class MonthlyReportController {
LocalDate startDate = period.getFromDate();
LocalDate endDate = period.getToDate();
//int remainingDateToLastOfMonth = calculateDaysExcludingFridaysAndThursdays(endDate);
// int remainingDateToLastOfMonth = calculateDaysExcludingFridaysAndThursdays(endDate);
// Get active employees in this period
List<Employee> employees =
@@ -72,29 +72,28 @@ public class MonthlyReportController {
// Iterate over employees and calculate/update MonthlyReport instances
for (Employee employee : employees) {
// Filter rapport journaliers for the current employee
List<DailyReport> employeeDailyReports = allDailyReports
.stream()
.filter(r -> r.getEmployee().equals(employee))
.collect(Collectors.toList());
List<DailyReport> employeeDailyReports =
allDailyReports
.stream()
.filter(r -> r.getEmployee().equals(employee))
.collect(Collectors.toList());
// Filter absences for the current employee
List<Absence> employeeAbsences = allAbsences
.stream()
.filter(a -> a.getEmployee().equals(employee))
.collect(Collectors.toList());
List<Absence> employeeAbsences =
allAbsences
.stream()
.filter(a -> a.getEmployee().equals(employee))
.collect(Collectors.toList());
if (!employeeDailyReports.isEmpty() || !employeeAbsences.isEmpty()) {
System.out.println("Create monthly report for employee: "+ employee.getRegistrationNumber());
System.out.println(
"Create monthly report for employee: " + employee.getRegistrationNumber());
// Process the employee's monthly report using filtered rapport and absences
Beans.get(MonthlyReportServiceImpl.class).createMensuelReport(
employee,
period,
startDate,
endDate,
employeeDailyReports,
employeeAbsences);
Beans.get(MonthlyReportServiceImpl.class)
.createMensuelReport(
employee, period, startDate, endDate, employeeDailyReports, employeeAbsences);
} else {
log.error("No Daily Reports exist for employee: "+ employee.getRegistrationNumber());
log.error("No Daily Reports exist for employee: " + employee.getRegistrationNumber());
}
}
// Indicate that the action was successful and a reload is needed
@@ -126,35 +125,36 @@ public class MonthlyReportController {
// Check if employeesObject is not null and cast it to a list
if (employeesObject instanceof List) {
List<LinkedHashMap<String, Object>> employeesList = (List<LinkedHashMap<String, Object>>) employeesObject;
List<LinkedHashMap<String, Object>> employeesList =
(List<LinkedHashMap<String, Object>>) employeesObject;
// Loop through each employee in the list
for (LinkedHashMap<String, Object> employeeMap : employeesList) {
Integer employeeIdInt = (Integer) employeeMap.get("id");
// Check for null ID to avoid potential NullPointerException
if (employeeIdInt != null) {
Long employeeId = employeeIdInt.longValue();
// Retrieve the employee from the repository
Employee employee = Beans.get(EmployeeRepository.class).find(employeeId);
if (employee != null) {
employees.add(employee); // Use add() instead of append()
} else {
System.out.println("Employee with ID " + employeeId + " not found.");
}
} else {
System.out.println("Employee ID is missing in the employeeMap.");
}
// Loop through each employee in the list
for (LinkedHashMap<String, Object> employeeMap : employeesList) {
Integer employeeIdInt = (Integer) employeeMap.get("id");
// Check for null ID to avoid potential NullPointerException
if (employeeIdInt != null) {
Long employeeId = employeeIdInt.longValue();
// Retrieve the employee from the repository
Employee employee = Beans.get(EmployeeRepository.class).find(employeeId);
if (employee != null) {
employees.add(employee); // Use add() instead of append()
} else {
System.out.println("Employee with ID " + employeeId + " not found.");
}
} else {
System.out.println("Employee ID is missing in the employeeMap.");
}
}
} else {
response.setFlash("No employees Selected.");
}
//int remainingDateToLastOfMonth = calculateDaysExcludingFridaysAndThursdays(endDate);
// int remainingDateToLastOfMonth = calculateDaysExcludingFridaysAndThursdays(endDate);
List<Integer> employeesIds = new ArrayList<>();
for(Employee e:employees){
for (Employee e : employees) {
employeesIds.add(e.getId().intValue());
}
@@ -162,7 +162,8 @@ public class MonthlyReportController {
List<DailyReport> allDailyReports =
Beans.get(DailyReportRepository.class)
.all()
.filter("self.employee in :employeesIds and self.reportDate >= :startDate and self.reportDate <= :endDate")
.filter(
"self.employee in :employeesIds and self.reportDate >= :startDate and self.reportDate <= :endDate")
.bind("startDate", startDate)
.bind("endDate", endDate)
.bind("employeesIds", employeesIds)
@@ -172,7 +173,8 @@ public class MonthlyReportController {
List<Absence> allAbsences =
Beans.get(AbsenceRepository.class)
.all()
.filter("self.employee in :employeesIds and DATE(self.startDate) >= :startDate and DATE(self.startDate) <= :endDate")
.filter(
"self.employee in :employeesIds and DATE(self.startDate) >= :startDate and DATE(self.startDate) <= :endDate")
.bind("startDate", startDate)
.bind("endDate", endDate)
.bind("employeesIds", employeesIds)
@@ -180,42 +182,59 @@ public class MonthlyReportController {
for (Employee employee : employees) {
// Check if a MonthlyReport exists for this employee in the specified period
MonthlyReport monthlyReport = Beans.get(MonthlyReportRepository.class)
.all()
.filter("self.employee = :employee and self.period = :period")
.bind("employee", employee)
.bind("period", period)
.fetchOne();
MonthlyReport monthlyReport =
Beans.get(MonthlyReportRepository.class)
.all()
.filter("self.employee = :employee and self.period = :period")
.bind("employee", employee)
.bind("period", period)
.fetchOne();
Optional<MonthlyReport> monthlyReportOpt = Optional.ofNullable(monthlyReport);
// Filter daily reports for the current employee
List<DailyReport> employeeDailyReports = allDailyReports.stream()
.filter(r -> r.getEmployee().equals(employee))
.collect(Collectors.toList());
List<DailyReport> employeeDailyReports =
allDailyReports
.stream()
.filter(r -> r.getEmployee().equals(employee))
.collect(Collectors.toList());
// Filter absences for the current employee
List<Absence> employeeAbsences = allAbsences.stream()
.filter(a -> a.getEmployee().equals(employee))
.collect(Collectors.toList());
List<Absence> employeeAbsences =
allAbsences
.stream()
.filter(a -> a.getEmployee().equals(employee))
.collect(Collectors.toList());
if (!employeeDailyReports.isEmpty() || !employeeAbsences.isEmpty()) {
if (monthlyReportOpt.isPresent()) {
MonthlyReport existingReport = monthlyReportOpt.get();
System.out.println("Update monthly report for employee: " + employee.getRegistrationNumber());
// Update the existing monthly report
Beans.get(MonthlyReportServiceImpl.class).updateMensuelReport(existingReport, employee, period, startDate, endDate, employeeDailyReports, employeeAbsences);
} else {
System.out.println("Create monthly report for employee: " + employee.getRegistrationNumber());
// Create a new monthly report
Beans.get(MonthlyReportServiceImpl.class).createMensuelReport(employee, period, startDate, endDate, employeeDailyReports, employeeAbsences);
}
if (monthlyReportOpt.isPresent()) {
MonthlyReport existingReport = monthlyReportOpt.get();
System.out.println(
"Update monthly report for employee: " + employee.getRegistrationNumber());
// Update the existing monthly report
Beans.get(MonthlyReportServiceImpl.class)
.updateMensuelReport(
existingReport,
employee,
period,
startDate,
endDate,
employeeDailyReports,
employeeAbsences);
} else {
System.out.println(
"Create monthly report for employee: " + employee.getRegistrationNumber());
// Create a new monthly report
Beans.get(MonthlyReportServiceImpl.class)
.createMensuelReport(
employee, period, startDate, endDate, employeeDailyReports, employeeAbsences);
}
} else {
System.err.println("No Daily Reports exist for employee: " + employee.getRegistrationNumber());
System.err.println(
"No Daily Reports exist for employee: " + employee.getRegistrationNumber());
}
}
}
// Indicate that the action was successful and a reload is needed
response.setReload(true);
} catch (Exception e) {

View File

@@ -51,8 +51,6 @@ import com.axelor.rpc.ActionRequest;
import com.axelor.rpc.ActionResponse;
import com.google.inject.Singleton;
import com.google.inject.persist.Transactional;
import java.util.List;
import java.util.Map;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.lang.invoke.MethodHandles;
@@ -502,5 +500,4 @@ public class LeaveController {
}
}
}
}