package org.hso.ecommerce.controller.cronjob; import org.hso.ecommerce.action.booking.CreateBookingAction; import org.hso.ecommerce.entities.booking.Booking; import org.hso.ecommerce.entities.booking.BookingAccountEntry; import org.hso.ecommerce.entities.booking.BookingReason; import org.hso.ecommerce.entities.supplier.Supplier; import org.hso.ecommerce.repos.booking.BookingAccountEntryRepository; import org.hso.ecommerce.repos.booking.BookingRepository; import org.hso.ecommerce.repos.supplier.SupplierRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import java.util.Calendar; @Component public class AutoSupplierPayment implements ICronjob { @Autowired private SupplierRepository supplierRepository = null; @Autowired private BookingAccountEntryRepository bookingAccountEntryRepository = null; @Autowired private BookingRepository bookingRepository = null; @Override public Calendar nextExecution(Calendar reference) { if (reference.get(Calendar.HOUR_OF_DAY) >= 10) { reference.add(Calendar.DAY_OF_MONTH, 1); } reference.set(Calendar.HOUR_OF_DAY, 10); reference.set(Calendar.MINUTE, 0); reference.set(Calendar.SECOND, 0); reference.set(Calendar.MILLISECOND, 0); return reference; } @Override public Calendar previousExecution(Calendar reference) { if (reference.get(Calendar.HOUR_OF_DAY) < 10) { reference.add(Calendar.DAY_OF_MONTH, -1); } reference.set(Calendar.HOUR_OF_DAY, 10); reference.set(Calendar.MINUTE, 0); reference.set(Calendar.SECOND, 0); reference.set(Calendar.MILLISECOND, 0); return reference; } @Override public void executeAt(Calendar time, CronjobController controller) { for (Supplier supplier : supplierRepository.findAll()) { int debts = bookingAccountEntryRepository .getBySupplier(supplier.id) .map(entry -> entry.newSumCent).orElse(0); if (debts > 0) { Booking booking = new CreateBookingAction( bookingAccountEntryRepository.getBySupplier(supplier.id).orElseGet(() -> BookingAccountEntry.newSupplier(supplier)), null, new BookingReason(supplier), debts ).finish(); bookingRepository.save(booking); } } } @Override public String getDisplayName() { return "Supplier Auto Payment"; } }