assume we have an stock. this stock should persist product id and available quantity. the user of this stock can frequently update(InitAvailableQuantityCommand) available quantity. if some product has been sold, our system will get a soldEvent(DecreaseAvailableQuantityCommand) and available quantity for sold product should be decress.
it works well with aggregate below, until one thing, if i try again to re-initialize stock with InitAvailableQuantityCommand, the event will be ignored and an error is thrown
An event for aggregate [3333] at sequence [0] was already inserted"
What i try to achive is following:
- InitAvailableQuantityCommand (productId =1, quantity = 10)
- DecreaseAvailableQuantityCommand (productId =1, quantity = 1)
- DecreaseAvailableQuantityCommand (productId =1, quantity = 1)
- now hier we have 8 available products more.
- and it this moment user will re-initialize stock with 20 available products for productId 1. the user will send a new InitAvailableQuantityCommand (productId =1, quantity = 20) and it this moment it fail and doesn't work.
What do i wrong?
thx.
@NoArgsConstructor
@Aggregate
@Data
public class AvailableQuantityAggregate {
private String partnerId;
private String productId;
@AggregateIdentifier
private String productVariationId;
private int quantity;
@CommandHandler
public AvailableQuantityAggregate(InitAvailableQuantityCommand cmd) {
final ApplyMore apply = AggregateLifecycle.apply(AvailableQuantityInitializedEvent.builder()
.partnerId(cmd.getPartnerId())
.productId(cmd.getProductId())
.productVariationId(cmd.getProductVariationId())
.quantity(cmd.getQuantity())
.build());
}
@CommandHandler
public void handle(DecreaseAvailableQuantityCommand cmd) {
AggregateLifecycle.apply(AvailableQuantityDecreasedEvent.builder()
.productVariationId(cmd.getProductVariationId())
.quantity(cmd.getQuantity())
.build());
}
@EventSourcingHandler
protected void on(AvailableQuantityInitializedEvent event) {
this.productVariationId = event.getProductVariationId();
this.partnerId = event.getPartnerId();
this.productId = event.getProductId();
this.quantity = event.getQuantity();
}
@EventSourcingHandler
protected void on(AvailableQuantityDecreasedEvent event) {
this.quantity = this.quantity-event.getQuantity();
}
}