Repository navigation
Description
Came from:
Given a Rule spanning aggregates: existing contract periods should not overlap new period. How much „logic“ in repository? 1) query all contracts and service class checks overlap 2) query and check overlap by passing new period (logic in SQL)
/cc @AntonStoeckl @plalx @BrunoRommens
After the discussion I moved my entire logic from an extra service and repository methods to the aggregate.
A few things to consider: - Logic in infrastructure implies integration tests verification. - Checking in service leaks BL outside the model -- I'd start trying: 1.
contract.changePeriod(period, otherPeriods)2.contract.changePeriod(period, overlapDetector). -- Refactor...
As suggested by @plalx.
Event-sourced aggregate root (A+ES)
final class ServiceContract extends AggregateRoot
{
public static function enter(
ServiceContractId $anId, PersonId $anPersonId, PersonalData $aPersonalData,
AssignmentPeriod $anAssignmentPeriod, WorkweekDays $aWorkweekDays, WeeklyWorkingHours $aWeeklyWorkingHours,
JobFunctionId $aJobFunctionId, string $aJobFunctionName,
AgencyId $anAgencyId, string $anAgencyName,
WorkplaceId $aWorkplaceId, string $aWorkplaceName,
array $enteredContracts
): ServiceContract
{
Assert::notEmpty($aJobFunctionName);
Assert::notEmpty($anAgencyName);
Assert::notEmpty($aWorkplaceName);
$self = new self();
$self->detectConflicts($anId, $enteredContracts, $anAssignmentPeriod);
$self->recordThat(ServiceContractEntered::withData(
$anId, $anPersonId, $aPersonalData,
$anAssignmentPeriod, $aWorkweekDays, $aWeeklyWorkingHours,
$aJobFunctionId, $aJobFunctionName, $anAgencyId, $anAgencyName,
$aWorkplaceId, $aWorkplaceName, new DateTimeImmutable()
));
return $self;
}
private function detectConflicts(ServiceContractId $id, array $enteredContracts, AssignmentPeriod $period): void
{
Assert::allIsInstanceOf($enteredContracts, Term::class);
foreach ($enteredContracts as $enteredContract) {
if ($id->sameValueAs(ServiceContractId::fromString($enteredContract->contractId()))) {
continue; // Used only when editing the assignment period, not for actual creation of the contract
}
if ($period->overlapsWith($enteredContract->assignmentPeriod())) {
throw new AssignmentPeriodOverlapsException();
}
}
}
}Application Service Command Handler
final class EnterServiceContractHandler
{
public function __invoke(EnterServiceContract $command): void
{
$person = $this->personDetailsRepository->ofPersonId($command->personId()->toString());
$enteredContracts = $this->contractTermRepository->ofPersonId($command->personId()->toString());
$contract = ServiceContract::enter(
$command->contractId(), $command->personId(),
... personal data from the person etc. ...
$enteredContracts
);
$this->contractCollection->save($contract);
}
}As @BrunoRommens suggested the enteredContracts are no full details read models. They are just value objects holding the actual assignment periods of the other contracts entered by the person.
The "Available periods" aggregate contains only "Period" value objects. Maybe the tradeoff (against nature in classical DDD), is to implement this type of aggregate as an interface in the domain with an implementation in infrastructure handling available periods finding operation
Unit test
final class ServiceContractTest extends EventSourcedAggregateRootTestCase
{
/** @test */
public function signingDetectsConflictWhenExistingPrecedingContractIsStillActive(): void
{
$this->expectException(AssignmentPeriodOverlapsException::class);
$enteredContracts = [
Term::fromArray([
'contract_id' => 'a391c713-2cf7-4500-b997-e37ea24c5889',
'person_id' => '71efb6b7-6eb1-4b17-b1d5-a3a47bac78f1',
'start_date' => '2019-02-01',
'end_date' => '2020-01-31',
])
];
ServiceContract::enter(
ServiceContractId::fromString('b88f676e-221d-4807-97c9-8f549b13425a'),
PersonId::fromString('71efb6b7-6eb1-4b17-b1d5-a3a47bac78f1'),
$this->getPersonalData(),
AssignmentPeriod::with(
new DateTimeImmutable('2020-01-01'),
new DateTimeImmutable('2020-12-31'),
),
WorkweekDays::fromArray(["monday","tuesday","wednesday","thursday","friday"]),
WeeklyWorkingHours::fromFloat(40),
JobFunctionId::fromInteger(4), 'Qualitätsprüfer/in',
AgencyId::fromString('904c0436-4226-4725-afbe-14526906afdb'), 'Office People',
WorkplaceId::fromString('1e522e02-b28d-44d2-a3fb-4efbdacec462'), 'Bratislava',
$enteredContracts
);
}
}
Activity
webdevilopers commentedon Oct 24, 2020
The alternative approaches were using a Domain Service to ensure that the developer could not pass "incorrectly determined" entered contracts.
A+ES
Service implementation
Alternatively the service could return a bool and the aggregate could throw the exception.
For testing different implementations could be used e.g. "HasConflictDetector" or "HasNoConflictDetector".
Still I find this harder to test and as @plalx mentioned it leaks business logic outside of the aggregate.
webdevilopers commentedon Oct 24, 2020
Yet another solution would be to go full event-driven.
As @BrunoRommens suggests:
Mabye a
Contractshould not be entered through itself but throughPerson. ThePersoncould hold theenteredContractsvalue objects. The overlapping could be checked. In addition all thepersonalDatamentioned above can come from there too.But does this not move the logic of overlapping far away from the developer? He could easily ignore the
Personfactory method.Or is this just a matter of communication?
At least the true invariants are still protected inside the
ServiceContract. Thespanning aggregate rulesare protected by the factory on another aggregate (Person).webdevilopers commentedon Oct 26, 2020
Thanky you very much to @BrunoRommens who draw these diagrams to understand the suggested solutions:
webdevilopers commentedon Oct 26, 2020
@BrunoRommers
webdevilopers commentedon Oct 26, 2020
@plalx
webdevilopers commentedon Oct 26, 2020
Here is a more complex example for merging contracts.
While merging per se is a complex process this feels a little bit overloaded for the aggregate root.
That is why I suggested to use the Person aggregate for the overlap detection and then enter the valid contract from there.
There is a similar approach in "Implement #DDDesign" by Vaughn Vernon:
The "Forum -> Discussion" example analogous to my "Person- > Contract" example:
The question here is: Is
Discussionan event-sourced aggregate-root? SinceForumpops the event it does not seem be.