Service class for managing loading unit movements.
This service provides methods to start and complete movements for loading units,
ensuring consistency and adherence to business rules.
*/
@ApplicationScoped
@Logged
public class LoadingUnitMovementDomainService extends MovementDomainService {
Starts a new movement or continues an existing one for a loading unit to a specified destination location.
@param loadingUnitMovements List of existing loading unit movements.
@param loadingUnitRef The loading unit resource ref.
@param destinationLocation The destination location for the movement.
*/
public void createNewMovement(final List loadingUnitMovements, final LoadingUnitReference loadingUnitRef,
final LocationReference destinationLocation) {
super.createNewMovement(loadingUnitMovements, loadingUnitRef.toEntityReference(),
destinationLocation);
}
public void createNewMovement(@NotNull final LoadingUnitMovement loadingUnitMovement) {
loadingUnitMovement.executing(statusChangedEventProducer);
}
public void completeMovement(@NotNull final LoadingUnitMovement loadingUnitMovement) {
loadingUnitMovement.completed(statusChangedEventProducer);
}
/**
Completes the movement for a loading unit and parks it at a specified location if it is moving.
@param loadingUnitMovements List of existing loading unit movements.
@param loadingUnitReference The loading unit resource reference.
@param parkLocation The park location.
*/
public void completeMovement(final List loadingUnitMovements,
final LoadingUnitReference loadingUnitReference, final LocationReference parkLocation) {
super.completeMovement(loadingUnitMovements, loadingUnitReference.toEntityReference(),
parkLocation);
}
@Override
protected Movement createNewInstance(final @NonNull EntityReference logisticUnitRef, final LocationReference sourceLocation,
final LocationReference destinationLocation) {
return new LoadingUnitMovement(logisticUnitRef, sourceLocation, destinationLocation);
}
@Logged
public abstract class MovementDomainService { //TODO it's probably more appropriate to create an entity "TransitMovementSequence" and "LoadingUnitMovementSequence"
code
@Inject
@ModuleConfiguration.Module(ModuleConfiguration.Module.CURRENT)
private EntityManager em;
@Inject
private ConfigurableEventProducer<MovementStatusChangedEvent> statusChangedEventProducer;
@Inject
private Logger log;
<K extends Movement> Movement createNewMovement(final List<K> existingMovements, final EntityReference logisticUnit, final LocationReference destinationLocation) {
completeExecutingMovementsToOtherLocations(existingMovements, destinationLocation);
cancelToDoMovementsToOtherLocations(existingMovements, destinationLocation);
K lastCompletedMovement = findLastCompletedMovement(existingMovements);
if( lastCompletedMovement != null && lastCompletedMovement.getDestinationLocation().equals(destinationLocation)) {
log.info("The last completed movement has the same destination, therefore the movement will not be created, completed movement: {}", lastCompletedMovement.getCode());
return lastCompletedMovement;
}
List<K> executingMovements = findByStatusAndDestination(existingMovements, Movement.Status.EXECUTING, destinationLocation);
List<K> toDoMovements = findByStatusAndDestination(existingMovements, Movement.Status.TO_DO, destinationLocation);
validateAtMostOneExecutionOrTodoMovementIsPresent(executingMovements, toDoMovements, destinationLocation, logisticUnit);
if (!executingMovements.isEmpty()) {
return executingMovements.get(0);
}else if (!toDoMovements.isEmpty()) {
toDoMovements.get(0).executing(statusChangedEventProducer);
return toDoMovements.get(0);
}else {
LocationReference lastLocation = lastCompletedMovement != null ? lastCompletedMovement.getDestinationLocation() : null;
Movement newMovement = createAndPersistNewMovement(lastLocation, logisticUnit, destinationLocation);
newMovement.executing(statusChangedEventProducer);
return newMovement;
}
}
public <K extends Movement> K completeMovement(final List<K> existingMovements, final EntityReference logisticUnit, final LocationReference destinationLocation) {
completeExecutingMovementsToOtherLocations(existingMovements,destinationLocation);
cancelToDoMovementsToOtherLocations(existingMovements, destinationLocation);
K lastCompletedMovement = findLastCompletedMovement(existingMovements);
if( lastCompletedMovement != null && lastCompletedMovement.getDestinationLocation().equals(destinationLocation)) {
log.info("The last completed movement has the same destination, completed movement: {}", lastCompletedMovement.getCode());
return lastCompletedMovement;
}
List<K> executingMovements = findByStatusAndDestination(existingMovements, Movement.Status.EXECUTING, destinationLocation);
if (executingMovements.isEmpty()) {
throw new IllegalStateException(String.format("No movements in execution to the destination location %s for logisticUnit %s", destinationLocation, logisticUnit ));
}
if(executingMovements.size() > 1) {
throw new IllegalStateException(String.format("Too many movements in execution to the destination location %s for logisticUnit %s", destinationLocation, logisticUnit ));
}
executingMovements.get(0).completed(statusChangedEventProducer);
return executingMovements.get(0);
}
protected abstract <K extends Movement> K createNewInstance(@NonNull final EntityReference logisticUnitRef, final LocationReference sourceLocation,
final LocationReference destinationLocation);
private <K extends Movement> void validateAtMostOneExecutionOrTodoMovementIsPresent(List<K> executingMovements, List<K> toDoMovements, LocationReference destinationLocation, EntityReference logisticUnit) {
int executingSize = executingMovements.size();
int toDoSize = toDoMovements.size();
if (executingSize > 1) {
throw new IllegalStateException(String.format("Too many movements in execution to the destination location %s for logisticUnit %s", destinationLocation, logisticUnit));
}
if (executingSize == 1 && toDoSize > 0) {
throw new IllegalStateException(String.format("There are movements in both todo and executing for the same destination for logisticUnit %s and destination %s", logisticUnit, destinationLocation));
}
if (toDoSize > 1) {
throw new IllegalStateException(String.format("Too many movements in TODO to the destination location %s for logisticUnit %s", destinationLocation, logisticUnit));
}
}
public void completeExecutingMovementsToOtherLocations(List<? extends Movement> movements, LocationReference destinationLocation) {
movements.stream()
.filter(mov -> Movement.Status.isExecuting(mov.getStatus()) && !mov.getDestinationLocation().equals(destinationLocation))
.forEach(mov -> mov.completed(statusChangedEventProducer));
}
public void cancelToDoMovementsToOtherLocations(List<? extends Movement> movements, LocationReference destinationLocation) {
movements.stream()
.filter(mov -> Movement.Status.isTodo(mov.getStatus()) && !mov.getDestinationLocation().equals(destinationLocation))
.forEach(mov -> mov.cancel(statusChangedEventProducer));
}
private <K extends Movement> List<K> findByStatusAndDestination(List<K> movements, Movement.Status status, LocationReference destinationLocation) {
return movements.stream()
.filter(mov -> mov.getStatus().equals(status) && mov.getDestinationLocation().equals(destinationLocation))
.collect(Collectors.toList());
}
private <K extends Movement> K createAndPersistNewMovement(LocationReference lastLocation, EntityReference logisticUnit, LocationReference destinationLocation) {
K newMovement = createNewInstance(logisticUnit, lastLocation, destinationLocation);
em.persist(newMovement);
return newMovement;
}
public <K extends Movement> K findLastCompletedMovement(List<K> movements){
return movements.stream()
.filter(mov -> mov.getStatus().equals(Movement.Status.COMPLETED))
.max(Comparator.comparing(Movement::getMovementEndDate)).orElse(null);
}
}
Something to solve here, considering DDD principles, to solve fast, i don't want to spend too much time
Based on your code and the consideration of Domain-Driven Design (DDD) principles, it would be beneficial to introduce explicit domain entities such as TransitMovementSequence and LoadingUnitMovementSequence.
Why create these entities?
Encapsulation of Domain Logic: By creating specific entities for movement sequences, you encapsulate the behavior and rules related to sequences of movements within the domain model itself. This aligns with DDD's principle of rich domain models where business logic is embodied within the entities.
Clarity and Maintainability: Having distinct entities for different movement sequences enhances the clarity of your domain model. It separates concerns and makes the code more maintainable by clearly defining responsibilities.
Aggregate Roots: These new entities can act as aggregate roots for their respective movement sequences, ensuring consistency and enforcing invariants across the aggregate.
Steps to implement this solution:
Define the MovementSequence Entities:
Create TransitMovementSequence and LoadingUnitMovementSequence classes.
These entities will contain a collection of TransitMovement and LoadingUnitMovement respectively.
Encapsulate Sequence Logic:
Move the logic related to creating, completing, and managing movements from the domain services into these entities.
For example, methods like createNewMovement, completeMovement, and validation checks can be part of these entities.
Refactor the Domain Services:
Modify LoadingUnitMovementDomainService and any other services to interact with the new entities.
The services can coordinate between aggregates but should delegate domain-specific operations to the entities themselves.
Adjust Repositories:
Update your repositories to handle the new entities.
Ensure that when you load a TransitMovementSequence, it includes the associated movements for consistency.
Update Event Handling:
If you're using domain events, ensure that the new entities publish events as needed.
Adjust your observers to handle events from the new entities.
Modify Persistence Logic:
Update your persistence mappings (e.g., JPA annotations) to accommodate the new entities and their relationships.
Benefits of this approach:
Better Domain Representation: Reflects the real-world concept of movement sequences more accurately within your code.
Improved DDD Alignment: By having entities that represent aggregates, your design follows DDD practices more closely.
Enhanced Testability: Encapsulated logic within entities can be more easily unit tested.
Future Scalability: Positions your codebase to more readily accommodate new requirements related to movement sequences.
Example Skeleton Code:
java
// TransitMovementSequence.java
@Entity
public class TransitMovementSequence {
@Id
private Long id;
@OneToMany(mappedBy = "sequence", cascade = CascadeType.ALL)
private List<TransitMovement> movements;
// Constructors, getters, setters
public void createNewMovement(LocationReference destination) {
// Logic to create and add a new TransitMovement to the list
}
public void completeMovement(LocationReference destination) {
// Logic to complete the current movement
}
// Other domain-specific methods
}
// Similar for LoadingUnitMovementSequence.java
Refactoring Domain Services:
java
public class LoadingUnitMovementDomainService {
public void createNewMovement(LoadingUnitReference ref, LocationReference destination) {
LoadingUnitMovementSequence sequence = repository.findByLoadingUnitRef(ref);
sequence.createNewMovement(destination);
repository.save(sequence);
}
public void completeMovement(LoadingUnitReference ref, LocationReference destination) {
LoadingUnitMovementSequence sequence = repository.findByLoadingUnitRef(ref);
sequence.completeMovement(destination);
repository.save(sequence);
}
}
By making these changes, you adhere more closely to DDD principles, resulting in a more robust and maintainable codebase without spending excessive time on the refactoring process.