clock = $clock ?? static fn (): \DateTimeImmutable => new \DateTimeImmutable('now', new \DateTimeZone('UTC')); $this->zone = $zone ?? new \DateTimeZone('UTC'); } // ------------------------------------------------------------------ // Units // ------------------------------------------------------------------ /** * The units tracked for a line, read only: showing them never writes. * * @return list */ public function unitsOf(int $orderItemId): array { return $this->units->findByOrderItem($orderItemId); } /** * Tracks the units of a line and takes the delivery WooCommerce knows * now for units not confirmed by an operator. A write: run it from the * queued action or a REST call, never inside a WooCommerce hook. * * @return list */ public function syncUnits(LineFacts $line): array { return $this->transaction->run(fn (): array => $this->trackUnits($line)); } /** * The operator confirms the delivery. A different date on a unit held by * a claim may change what the claim is worth: the claim goes to review. */ public function setDelivery(int $unitId, int $expectedVersion, LegalDate $on, string $reason, Operation $op): CoveredUnit { return $this->writeUnit(__FUNCTION__, $op, $unitId, function () use ($unitId, $expectedVersion, $on, $reason, $op): CoveredUnit { $this->assertNotFuture($on); $unit = $this->unit($unitId, $expectedVersion); $previous = $unit->deliveredOn(); $extendedBy = $unit->extendedByClaimId(); $unit->setDelivery($on, DeliverySource::Confirmed, $op->actorId, $reason, $op->idempotencyKey, $this->now()); $this->units->save($unit); if (null !== $previous && !$previous->equals($on)) { $this->reviewHoldingClaim($unit, self::REVIEW_DELIVERY_CHANGED, $op); } $this->reviewExtensionChange($unit, $extendedBy, $op); return $unit; }); } /** * The operator says whether the buyer is a consumer (rule 6). A change on * a unit held by a claim sends the claim to review: what was decided so * far may not hold. */ public function setConsumer(int $unitId, int $expectedVersion, ConsumerStatus $status, string $reason, Operation $op): CoveredUnit { return $this->writeUnit(__FUNCTION__, $op, $unitId, function () use ($unitId, $expectedVersion, $status, $reason, $op): CoveredUnit { $unit = $this->unit($unitId, $expectedVersion); $extendedBy = $unit->extendedByClaimId(); if ($unit->setConsumer($status, $op->actorId, $reason, $op->idempotencyKey, $this->now())) { $this->reviewHoldingClaim($unit, ConsumerStatus::Unconfirmed === $status ? self::REVIEW_CONSUMER_UNCONFIRMED : self::REVIEW_CONSUMER_CHANGED, $op); } $this->units->save($unit); $this->reviewExtensionChange($unit, $extendedBy, $op); return $unit; }); } /** A later end of the guarantee granted by the shop, with a reason (spec section 4). */ public function setGuaranteeEnd(int $unitId, int $expectedVersion, ?LegalDate $on, string $reason, Operation $op): CoveredUnit { return $this->writeUnit(__FUNCTION__, $op, $unitId, function () use ($unitId, $expectedVersion, $on, $reason, $op): CoveredUnit { $unit = $this->unit($unitId, $expectedVersion); $unit->setOperatorEnd($on, $op->actorId, $reason, $op->idempotencyKey, $this->now()); $this->units->save($unit); return $unit; }); } /** * Art. 133 c. 4: the length agreed for a used good, or a correction of * what was recorded at the sale. The claim holding the unit, and the one * whose repair gave an extension that changes, go to review. */ public function setGuaranteeMonths(int $unitId, int $expectedVersion, int $months, string $reason, Operation $op): CoveredUnit { return $this->writeUnit(__FUNCTION__, $op, $unitId, function () use ($unitId, $expectedVersion, $months, $reason, $op): CoveredUnit { $unit = $this->unit($unitId, $expectedVersion); $previous = (int) $unit->toRow()['guarantee_months']; $extendedBy = $unit->extendedByClaimId(); $unit->setGuaranteeMonths($months, $op->actorId, $reason, $op->idempotencyKey, $this->now()); $this->units->save($unit); if ($previous !== $months) { $this->reviewHoldingClaim($unit, self::REVIEW_CONTRACT_CHANGED, $op); } $this->reviewExtensionChange($unit, $extendedBy, $op); return $unit; }); } /** * The day the contract was concluded, when the order date is not it. If * the new rules (contracts from 31/07/2026) change side, the claim holding * the unit goes to review: the informativa and the extension depend on it. */ public function setContractDate(int $unitId, int $expectedVersion, LegalDate $on, string $reason, Operation $op): CoveredUnit { return $this->writeUnit(__FUNCTION__, $op, $unitId, function () use ($unitId, $expectedVersion, $on, $reason, $op): CoveredUnit { $this->assertNotFuture($on); $unit = $this->unit($unitId, $expectedVersion); if (null !== $unit->openClaimId()) { $claim = $this->claims->get($unit->openClaimId()); if (null !== $claim && $claim->reportedOn()->isBefore($on)) { throw DomainError::invalidInput('A defect cannot be reported before the order.'); } } $extendedBy = $unit->extendedByClaimId(); $flipped = $unit->setContractDate($on, $op->actorId, $reason, $op->idempotencyKey, $this->now()); $this->units->save($unit); if ($flipped) { $this->reviewHoldingClaim($unit, self::REVIEW_CONTRACT_CHANGED, $op); } $this->reviewExtensionChange($unit, $extendedBy, $op); return $unit; }); } // ------------------------------------------------------------------ // Opening // ------------------------------------------------------------------ /** * Rules 1 and 5: a unit in one open claim at a time, never a unit that * went back on a termination. More units than the line has after refunds * is a doubt, not a refusal: a refund by quantity may be a price * reduction with the good still at the customer. Doubtful data sends the * claim to review at once (G08, G12, rule 12). * * @param list $unitIndexes * @param LegalDate|null $manifestedOn when the defect appeared, as the * consumer declares it; the guarantee looks at this day */ public function openClaim(LineFacts $line, array $unitIndexes, LegalDate $reportedOn, string $defect, Operation $op, ?LegalDate $manifestedOn = null): Claim { return $this->writeClaim(__FUNCTION__, $op, $line->orderItemId, function () use ($line, $unitIndexes, $reportedOn, $defect, $op, $manifestedOn): Claim { $unitIndexes = array_values(array_unique(array_map('intval', $unitIndexes))); if ([] === $unitIndexes) { throw DomainError::invalidInput('Choose at least one unit.'); } foreach ($unitIndexes as $index) { if ($index < 1 || $index > $line->quantity) { throw DomainError::invalidInput('Choose existing units of this order line.'); } } if ($reportedOn->isBefore($line->contractDate)) { throw DomainError::invalidInput('A defect cannot be reported before the order.'); } $this->assertNotFuture($reportedOn); if (null !== $manifestedOn && $manifestedOn->isBefore($line->contractDate)) { throw DomainError::invalidInput('The defect cannot appear before the order.'); } $busy = 0; $terminated = 0; $chosen = []; foreach ($this->trackUnits($line) as $unit) { if (null !== $unit->openClaimId()) { $busy++; } if (null !== $unit->terminatedByClaimId()) { $terminated++; } if (in_array($unit->unitIndex(), $unitIndexes, true)) { $chosen[] = $unit; } } // Units returned on a termination but not refunded in Woo yet count as gone too. $claimable = $line->claimableUnits() - $busy - max(0, $terminated - $line->refundedQuantity); foreach ($chosen as $unit) { if (null !== $unit->openClaimId()) { throw DomainError::unitBusy((int) $unit->id(), (int) $unit->openClaimId()); } if (null !== $unit->terminatedByClaimId()) { throw DomainError::unitsRefunded((int) max(0, $claimable)); // G11: this very unit went back. } } $reviews = $this->reviewReasonsAtOpening($chosen, $reportedOn, $manifestedOn); if (count($chosen) > $claimable) { $reviews[] = self::REVIEW_ORDER_REFUNDED; } $now = $this->now(); $claim = Claim::open( $line->orderId, $line->orderItemId, array_map(static fn (CoveredUnit $u): int => (int) $u->id(), $chosen), $reportedOn, $defect, self::informativaDue($chosen, $manifestedOn), $op->actorId, $op->idempotencyKey, $now, $manifestedOn, ); foreach ($reviews as $review) { $claim->markForReview($review, null, $op->key('review:' . $review), $now); } $this->claims->insert($claim); foreach ($chosen as $unit) { $unit->attachTo((int) $claim->id(), $op->actorId, $op->key('attach:' . $unit->id()), $now); $this->units->save($unit); } return $claim; }); } // ------------------------------------------------------------------ // Steps of an open claim // ------------------------------------------------------------------ /** * @param array{text?:string, to?:string, locale?:string} $content what was * communicated, kept in the history as proof */ public function inform(int $claimId, int $expectedVersion, LegalDate $on, InformativaChannel $channel, string $textVersion, Operation $op, array $content = []): Claim { $this->assertNotFuture($on); return $this->claimStep(__FUNCTION__, $claimId, $expectedVersion, $op, fn (Claim $c) => $c->inform($on, $channel, $textVersion, $op->actorId, $op->idempotencyKey, $this->now(), $content)); } /** * Reserves the right to send the informativa email for this * Idempotency-Key (G13): the claim goes to review as "informativa * uncertain" in the same transaction that stores the key. True only for * the one request that made the reservation: a retry, or a second request * racing with the same key, gets false (or a conflict) and sends nothing. */ public function reserveInformativaSend(int $claimId, int $expectedVersion, Operation $op): bool { $acquired = false; $this->claimStep(__FUNCTION__, $claimId, $expectedVersion, $op, function (Claim $claim) use ($op, &$acquired): void { if (ClaimState::Open !== $claim->state()) { throw DomainError::invalidTransition('The claim is not open.'); } if ($claim->isInformed()) { throw DomainError::invalidTransition('The consumer was already informed.'); } if (!$claim->informativaRequired()) { throw DomainError::invalidTransition('The informativa is not due for this claim.'); } $claim->markForReview(ReviewReason::INFORMATIVA_UNCERTAIN, $op->actorId, $op->idempotencyKey, $this->now()); $acquired = true; }); return $acquired; } /** * When the defect appeared, as the consumer declares it. It decides * "out of warranty" and the extension; the report date only bounds it. */ public function setManifestedOn(int $claimId, int $expectedVersion, LegalDate $on, string $reason, Operation $op): Claim { $this->assertNotFuture($on); return $this->claimStep(__FUNCTION__, $claimId, $expectedVersion, $op, function (Claim $claim) use ($on, $reason, $op): void { $units = $this->claimUnits($claim); foreach ($units as $unit) { if ($on->isBefore($unit->contractDate())) { throw DomainError::invalidInput('The defect cannot appear before the order.'); } } $claim->setManifestedOn($on, $op->actorId, $reason, $op->idempotencyKey, $this->now(), $claim->isInformed() ? null : self::informativaDue($units, $on)); }); } public function choose(int $claimId, int $expectedVersion, Remedy $remedy, Operation $op): Claim { return $this->claimStep(__FUNCTION__, $claimId, $expectedVersion, $op, fn (Claim $c) => $c->choose($remedy, $op->actorId, $op->idempotencyKey, $this->now())); } public function requestRefurbished(int $claimId, int $expectedVersion, string $note, Operation $op): Claim { return $this->claimStep(__FUNCTION__, $claimId, $expectedVersion, $op, fn (Claim $c) => $c->requestRefurbished($op->actorId, $note, $op->idempotencyKey, $this->now())); } public function receiveGoods(int $claimId, int $expectedVersion, LegalDate $on, ?string $externalRef, Operation $op): Claim { $this->assertNotFuture($on); return $this->claimStep(__FUNCTION__, $claimId, $expectedVersion, $op, fn (Claim $c) => $c->receiveGoods($on, $op->actorId, $externalRef, $op->idempotencyKey, $this->now())); } public function lendLoaner(int $claimId, int $expectedVersion, LegalDate $on, ?string $externalRef, Operation $op): Claim { $this->assertNotFuture($on); return $this->claimStep(__FUNCTION__, $claimId, $expectedVersion, $op, fn (Claim $c) => $c->lendLoaner($on, $op->actorId, $externalRef, $op->idempotencyKey, $this->now())); } public function returnLoaner(int $claimId, int $expectedVersion, LegalDate $on, Operation $op): Claim { $this->assertNotFuture($on); return $this->claimStep(__FUNCTION__, $claimId, $expectedVersion, $op, fn (Claim $c) => $c->returnLoaner($on, $op->actorId, $op->idempotencyKey, $this->now())); } public function refuseRemedy(int $claimId, int $expectedVersion, string $reason, Operation $op): Claim { return $this->claimStep(__FUNCTION__, $claimId, $expectedVersion, $op, fn (Claim $c) => $c->refuseRemedy($op->actorId, $reason, $op->idempotencyKey, $this->now())); } // ------------------------------------------------------------------ // Closing // ------------------------------------------------------------------ /** * Rule 2: every unit counts the repair; the extension is applied once, * only where it is due (new contract, consumer, defect appeared within * the guarantee). */ public function completeRepair(int $claimId, int $expectedVersion, LegalDate $on, string $note, Operation $op): Claim { $this->assertNotFuture($on); return $this->claimStep(__FUNCTION__, $claimId, $expectedVersion, $op, function (Claim $claim) use ($on, $note, $op): array { $now = $this->now(); $claim->completeRepair($on, $op->actorId, $note, $op->idempotencyKey, $now); $units = $this->claimUnits($claim); foreach ($units as $unit) { $unit->recordRepair((int) $claim->id(), $claim->defectDate(), $op->actorId, $op->key('repair:' . $unit->id()), $now); $unit->release((int) $claim->id(), $op->actorId, $op->key('release:' . $unit->id()), $now); } return $units; }); } /** * Rule 2 again: a replacement gives no extension. Whether the guarantee * starts again for the new good is not settled by the law: the plugin * does not choose. The shop may record a new end it decided ($newEnd). */ public function completeReplacement(int $claimId, int $expectedVersion, LegalDate $on, bool $refurbished, string $note, Operation $op, ?LegalDate $newEnd = null): Claim { $this->assertNotFuture($on); return $this->claimStep(__FUNCTION__, $claimId, $expectedVersion, $op, function (Claim $claim) use ($on, $refurbished, $note, $op, $newEnd): array { $now = $this->now(); $claim->completeReplacement($on, $refurbished, $op->actorId, $note, $op->idempotencyKey, $now); $units = $this->releaseUnits($claim, $op); if (null !== $newEnd) { foreach ($units as $unit) { $unit->setOperatorEnd($newEnd, $op->actorId, '' !== trim($note) ? $note : '@replacement_end', $op->key('end:' . $unit->id()), $now); } } return $units; }); } public function closeWithRefund(int $claimId, int $expectedVersion, Outcome $outcome, int $refundId, bool $defectNotMinor, LegalDate $on, string $reason, Operation $op): Claim { $this->assertNotFuture($on); return $this->claimStep(__FUNCTION__, $claimId, $expectedVersion, $op, function (Claim $claim) use ($outcome, $refundId, $defectNotMinor, $on, $reason, $op): array { $claim->closeWithRefund($outcome, $refundId, $defectNotMinor, $on, $op->actorId, $reason, $op->idempotencyKey, $this->now()); $units = $this->releaseUnits($claim, $op); if (Outcome::Terminated === $outcome) { foreach ($units as $unit) { $unit->terminate((int) $claim->id(), $op->actorId, $op->key('terminate:' . $unit->id()), $this->now()); } } return $units; }); } /** * Rule 4: "out of warranty" only with a confirmed delivery, a confirmed * consumer and a defect that appeared after the end of the guarantee of * every unit: a late report alone proves nothing. "Not a consumer" only * once every unit says so. */ public function closeWithoutRemedy(int $claimId, int $expectedVersion, Outcome $outcome, LegalDate $on, string $reason, Operation $op): Claim { $this->assertNotFuture($on); return $this->claimStep(__FUNCTION__, $claimId, $expectedVersion, $op, function (Claim $claim) use ($outcome, $on, $reason, $op): array { $units = $this->claimUnits($claim); foreach ($units as $unit) { if (Outcome::RejectedOutOfWarranty === $outcome) { if (DeliverySource::Confirmed !== $unit->deliverySource()) { throw DomainError::deliveryNotConfirmed(); } $dates = $unit->dates() ?? throw DomainError::consumerNotConfirmed(); if (!$claim->reportedOn()->isAfter($dates->guaranteeEnd)) { throw DomainError::stillInWarranty(); } $appeared = $claim->manifestedOn() ?? throw DomainError::manifestationUnknown(); if (!$appeared->isAfter($dates->guaranteeEnd)) { throw DomainError::stillInWarranty(); } } if (Outcome::RejectedNotConsumer === $outcome && ConsumerStatus::NotConsumer !== $unit->consumer()) { throw DomainError::buyerIsConsumer(); } } $claim->closeWithoutRemedy($outcome, $on, $op->actorId, $reason, $op->idempotencyKey, $this->now()); return $this->releaseUnits($claim, $op, $units); }); } // ------------------------------------------------------------------ // Review and reopening // ------------------------------------------------------------------ /** * Back to work only when the doubt is gone: a known delivery (confirmed, * if that was a reason), a buyer whose status is confirmed, when the * defect appeared if the report came after the guarantee, and units the * line still has after refunds (rule 5). $goodsKept: the operator checked * that the refunds of the line left the goods with the customer (a price * reduction): they do not count as units gone. $acceptedFacts: the * WooCommerce order as the operator saw it, accepted from now on. * * @param array|null $acceptedFacts */ public function reconcile(int $claimId, int $expectedVersion, LineFacts $line, string $reason, Operation $op, bool $goodsKept = false, ?array $acceptedFacts = null): Claim { return $this->claimStep(__FUNCTION__, $claimId, $expectedVersion, $op, function (Claim $claim) use ($line, $reason, $op, $goodsKept, $acceptedFacts): void { $informativaDue = null; if (ClaimState::NeedsReview === $claim->state() && null === $claim->outcome()) { $units = $this->claimUnits($claim); foreach ($units as $unit) { if (DeliverySource::Unknown === $unit->deliverySource() || ($claim->inReviewFor(self::REVIEW_DELIVERY_UNKNOWN) && DeliverySource::Confirmed !== $unit->deliverySource())) { throw DomainError::deliveryNotConfirmed(); } if (ConsumerStatus::Unconfirmed === $unit->consumer()) { throw DomainError::consumerNotConfirmed(); } } if (self::manifestationDoubt($claim->reportedOn(), $claim->manifestedOn(), $units)) { throw DomainError::manifestationUnknown(); } $left = $this->unitsLeftFor($claim, $line, $goodsKept); if (count($claim->unitIds()) > $left) { throw DomainError::unitsRefunded((int) max(0, $left)); } $informativaDue = $claim->isInformed() ? null : self::informativaDue($units, $claim->manifestedOn()); } $claim->reconcile($op->actorId, $reason, $op->idempotencyKey, $this->now(), $informativaDue, $goodsKept ? ['goods_kept' => true] : [], $acceptedFacts); }); } /** * Something a person must look at that the plugin cannot settle, for * example an informativa email whose delivery is uncertain (G13). */ public function flagForReview(int $claimId, int $expectedVersion, string $reasonCode, Operation $op): Claim { return $this->claimStep(__FUNCTION__, $claimId, $expectedVersion, $op, function (Claim $claim) use ($reasonCode, $op): void { $claim->markForReview($reasonCode, $op->actorId, $op->idempotencyKey, $this->now()); }); } /** * Rule 10 for one claim: something changed in WooCommerce that nobody * accepted yet. A system action, so no expected version; a claim already * closed is left alone. Returns whether the claim went to review now. */ /** * @param array $facts what changed: a review already open * for the same reason is recorded again, so a screen opened before * the change is stale */ public function markClaimForReview(int $claimId, string $reasonCode, Operation $op, array $facts = []): bool { return $this->transaction->run(function () use ($claimId, $reasonCode, $op, $facts): bool { if (null !== $this->replayed(__FUNCTION__, $op, IdempotencyLog::SUBJECT_CLAIM, $claimId)) { return false; } $claim = $this->claims->get($claimId) ?? throw DomainError::notFound('Claim'); $changed = ClaimState::Closed !== $claim->state() && $claim->markForReview($reasonCode, $op->actorId, $op->idempotencyKey, $this->now(), $facts); if ($changed) { $this->claims->save($claim); } $this->log->remember($op->idempotencyKey, self::fingerprint(__FUNCTION__, $op), IdempotencyLog::SUBJECT_CLAIM, $claimId); return $changed; }); } /** Rule 12: the defect came back. Review, the units held again, no second extension. */ public function reportRecurrence(int $claimId, int $expectedVersion, LineFacts $line, string $note, Operation $op): Claim { return $this->claimStep(__FUNCTION__, $claimId, $expectedVersion, $op, function (Claim $claim) use ($line, $note, $op): array { if (Outcome::Terminated === $claim->outcome()) { throw DomainError::invalidTransition('The contract was terminated: the good went back, nothing can recur.'); } return $this->reopen($claim, $line, self::REVIEW_DEFECT_RECURRED, $note, $op); }); } /** * The claim was closed by mistake. A repair it recorded is revoked with * a compensating event, and with it the extension it gave (rule 7). */ public function reopenClosedByMistake(int $claimId, int $expectedVersion, LineFacts $line, string $note, Operation $op): Claim { return $this->claimStep(__FUNCTION__, $claimId, $expectedVersion, $op, function (Claim $claim) use ($line, $note, $op): array { $outcome = $claim->outcome(); $units = $this->reopen($claim, $line, self::REVIEW_CLOSED_BY_MISTAKE, $note, $op); foreach ($units as $unit) { if (Outcome::Repaired === $outcome) { $unit->revokeRepair((int) $claim->id(), $op->actorId, $note, $op->key('revoke:' . $unit->id()), $this->now()); } if (Outcome::Terminated === $outcome) { $unit->revokeTermination((int) $claim->id(), $op->actorId, $note, $op->key('unterminate:' . $unit->id()), $this->now()); } } return $units; }); } /** * Rule 10: WooCommerce refunded, changed or cancelled the order outside * the plugin. The claims of the line still being worked on go to review. * Called by the queued action, never inside a Woo hook. * * @return list the claims sent to review now */ public function markLineForReview(int $orderItemId, string $reasonCode, Operation $op): array { return $this->transaction->run(function () use ($orderItemId, $reasonCode, $op): array { if (null !== $this->replayed('markLineForReview', $op, IdempotencyLog::SUBJECT_LINE, $orderItemId)) { return []; } $changed = []; foreach ($this->claims->findActiveByOrderItem($orderItemId) as $claim) { if ($claim->markForReview($reasonCode, $op->actorId, $op->key('review:' . $claim->id()), $this->now())) { $this->claims->save($claim); $changed[] = $claim; } } $this->log->remember($op->idempotencyKey, self::fingerprint('markLineForReview', $op), IdempotencyLog::SUBJECT_LINE, $orderItemId); return $changed; }); } // ------------------------------------------------------------------ /** @return list */ private function trackUnits(LineFacts $line): array { $byIndex = []; foreach ($this->units->findByOrderItem($line->orderItemId) as $unit) { // Tracked before the order was completed: take the delivery Woo knows now. // The version makes the key unique even when an estimate goes back and forth. $refreshKey = 'refresh:' . $unit->id() . ':v' . $unit->version(); $previous = $unit->deliveredOn(); $extendedBy = $unit->extendedByClaimId(); if ($unit->refreshDelivery($line->deliveredOn, $line->deliverySource, $refreshKey, $this->now())) { $this->units->save($unit); $op = new Operation(null, $refreshKey, 'refresh'); if (null !== $previous) { $this->reviewHoldingClaim($unit, self::REVIEW_DELIVERY_CHANGED, $op); } // An automatic change never takes away or gives an extension unseen: // the claim whose repair gave it, or gives it now, goes to review. $extendedNow = $unit->extendedByClaimId(); if ($extendedBy !== $extendedNow) { $this->reviewClaim((int) ($extendedBy ?? $extendedNow), self::REVIEW_EXTENSION_CHANGED, $op); } $unit = $this->units->get((int) $unit->id()) ?? $unit; } $byIndex[$unit->unitIndex()] = $unit; } for ($index = 1; $index <= $line->quantity; $index++) { if (!isset($byIndex[$index])) { $unit = CoveredUnit::track( $line->orderId, $line->orderItemId, $index, $line->productId, $line->contractDate, $line->deliveredOn, $line->deliverySource, $line->guaranteeMonths, $line->consumer, 'track:' . $line->orderItemId . ':' . $index, $this->now(), ); $this->units->insert($unit); $byIndex[$index] = $unit; } } ksort($byIndex); return array_values($byIndex); } /** * Every doubt about the chosen units, all of them shown to the operator. * * @param list $units * @return list */ private function reviewReasonsAtOpening(array $units, LegalDate $reportedOn, ?LegalDate $manifestedOn): array { $reasons = []; if (self::manifestationDoubt($reportedOn, $manifestedOn, $units)) { $reasons[] = self::REVIEW_MANIFESTATION_UNKNOWN; } foreach ($units as $unit) { if (null === $unit->deliveredOn()) { $reasons[] = self::REVIEW_DELIVERY_UNKNOWN; } if (ConsumerStatus::Unconfirmed === $unit->consumer()) { $reasons[] = self::REVIEW_CONSUMER_UNCONFIRMED; } if ($unit->repairCount() > 0) { $reasons[] = self::REVIEW_REPAIRED_BEFORE; } } return array_values(array_unique($reasons)); } /** The claim that holds the unit, if any and not already in review for this, goes to review. */ private function reviewHoldingClaim(CoveredUnit $unit, string $reasonCode, Operation $op): void { if (null === $unit->openClaimId()) { return; } $this->reviewClaim($unit->openClaimId(), $reasonCode, $op); } /** Open or closed: a closed claim keeps its outcome and goes back to closed when reconciled. */ private function reviewClaim(int $claimId, string $reasonCode, Operation $op): void { $claim = $this->claims->get($claimId) ?? throw DomainError::notFound('Claim'); if ($claim->markForReview($reasonCode, $op->actorId, $op->key('review:' . $claim->id() . ':' . ltrim($reasonCode, '@')), $this->now())) { $this->claims->save($claim); } } /** * Reported after the end of the guarantee and nobody said when the defect * appeared: whether the guarantee covers it is unknown, never guessed. * * @param list $units */ private static function manifestationDoubt(LegalDate $reportedOn, ?LegalDate $manifestedOn, array $units): bool { if (null !== $manifestedOn) { return false; } foreach ($units as $unit) { $dates = $unit->dates(); if (null !== $dates && $reportedOn->isAfter($dates->guaranteeEnd)) { return true; } } return false; } /** * Rule 3: the informativa is due for consumers of new contracts. Not for * a buyer confirmed as a business, nor for a defect known to have appeared * after the guarantee (goodwill). In doubt it is due. * * @param list $units */ private static function informativaDue(array $units, ?LegalDate $manifestedOn): bool { foreach ($units as $unit) { if (!$unit->newRulesApply() || ConsumerStatus::NotConsumer === $unit->consumer()) { continue; } $dates = $unit->dates(); if (null !== $manifestedOn && null !== $dates && $manifestedOn->isAfter($dates->guaranteeEnd)) { continue; } return true; } return false; } /** An automatic or operator change gave or took an extension: the claim of that repair goes to review. */ private function reviewExtensionChange(CoveredUnit $unit, ?int $extendedBefore, Operation $op): void { $extendedNow = $unit->extendedByClaimId(); if ($extendedBefore !== $extendedNow) { $this->reviewClaim((int) ($extendedBefore ?? $extendedNow), self::REVIEW_EXTENSION_CHANGED, $op); } } /** * Rule 5 when a claim takes its units back: how many units of the line it * can hold. A unit of its own that went back on another claim's * termination is a refusal: that good is gone. */ private function unitsLeftFor(Claim $claim, LineFacts $line, bool $goodsKept): int { if ($line->orderItemId !== $claim->orderItemId()) { throw DomainError::invalidInput('The order line does not match the claim.'); } $busyElsewhere = 0; $terminated = 0; $returnedElsewhere = false; foreach ($this->units->findByOrderItem($line->orderItemId) as $unit) { if (null !== $unit->openClaimId() && $unit->openClaimId() !== $claim->id()) { $busyElsewhere++; } if (null !== $unit->terminatedByClaimId() && $unit->terminatedByClaimId() !== $claim->id()) { $terminated++; // One of this claim's own units went back on another claim's termination. $returnedElsewhere = $returnedElsewhere || in_array((int) $unit->id(), $claim->unitIds(), true); } } $claimable = $goodsKept ? $line->quantity - $busyElsewhere - $terminated : $line->claimableUnits() - $busyElsewhere - max(0, $terminated - $line->refundedQuantity); if ($returnedElsewhere) { throw DomainError::unitsRefunded((int) max(0, $claimable)); } return $claimable; } /** * The units are held again. Refunds on the line since then are a doubt * (the goods may still be at the customer), a unit returned on another * claim's termination a refusal. * * @return list */ private function reopen(Claim $claim, LineFacts $line, string $reasonCode, string $note, Operation $op): array { $left = $this->unitsLeftFor($claim, $line, false); $now = $this->now(); $claim->reopen($reasonCode, $op->actorId, $note, $op->idempotencyKey, $now); if (count($claim->unitIds()) > $left) { $claim->markForReview(self::REVIEW_ORDER_REFUNDED, $op->actorId, $op->key('review:refunded'), $now); } $units = $this->claimUnits($claim); foreach ($units as $unit) { $unit->attachTo((int) $claim->id(), $op->actorId, $op->key('attach:' . $unit->id()), $now); } return $units; } /** * @param list|null $units already loaded * @return list */ private function releaseUnits(Claim $claim, Operation $op, ?array $units = null): array { $units ??= $this->claimUnits($claim); foreach ($units as $unit) { $unit->release((int) $claim->id(), $op->actorId, $op->key('release:' . $unit->id()), $this->now()); } return $units; } /** * Loads the claim at the version the operator saw, applies the step and * saves the claim with the units the step returns. * * @param callable(Claim): (list|null|void) $step */ private function claimStep(string $action, int $claimId, int $expectedVersion, Operation $op, callable $step): Claim { return $this->writeClaim($action, $op, $claimId, function () use ($claimId, $expectedVersion, $step): Claim { $claim = $this->claims->get($claimId) ?? throw DomainError::notFound('Claim'); if ($claim->version() !== $expectedVersion) { throw DomainError::versionConflict((int) $expectedVersion, (int) $claim->version()); } $units = $step($claim) ?? []; $this->claims->save($claim); foreach ($units as $unit) { $this->units->save($unit); } return $claim; }); } /** @param callable(): Claim $work */ /** @param int $claimId the claim, or for openClaim the order line it opens on */ private function writeClaim(string $action, Operation $op, int $claimId, callable $work): Claim { return $this->transaction->run(function () use ($action, $op, $claimId, $work): Claim { $previous = $this->replayed($action, $op, IdempotencyLog::SUBJECT_CLAIM, 'openClaim' === $action ? null : $claimId); if (null !== $previous) { $claim = $this->claims->get($previous) ?? throw DomainError::notFound('Claim'); if ('openClaim' === $action && $claim->orderItemId() !== $claimId) { throw DomainError::idempotencyMismatch(); } return $claim; } $claim = $work(); $this->log->remember($op->idempotencyKey, self::fingerprint($action, $op), IdempotencyLog::SUBJECT_CLAIM, (int) $claim->id()); return $claim; }); } /** @param callable(): CoveredUnit $work */ private function writeUnit(string $action, Operation $op, int $unitId, callable $work): CoveredUnit { return $this->transaction->run(function () use ($action, $op, $unitId, $work): CoveredUnit { $previous = $this->replayed($action, $op, IdempotencyLog::SUBJECT_UNIT, $unitId); if (null !== $previous) { return $this->units->get($previous) ?? throw DomainError::notFound('Unit'); } $unit = $work(); $this->log->remember($op->idempotencyKey, self::fingerprint($action, $op), IdempotencyLog::SUBJECT_UNIT, (int) $unit->id()); return $unit; }); } /** * Same key, same action, same body, same subject: the id of what it * produced. Same key with anything else: 409. */ private function replayed(string $action, Operation $op, string $subject, ?int $subjectId): ?int { $previous = $this->log->find($op->idempotencyKey); if (null === $previous) { return null; } if ($previous['request_hash'] !== self::fingerprint($action, $op) || $previous['subject'] !== $subject || (null !== $subjectId && $previous['subject_id'] !== $subjectId)) { throw DomainError::idempotencyMismatch(); } return $previous['subject_id']; } private function assertNotFuture(LegalDate $date): void { if ($date->isAfter(LegalDate::fromInstant($this->now(), $this->zone))) { throw DomainError::invalidInput('The date cannot be in the future.'); } } /** The action is part of what the key stands for, whatever the REST layer hashed. */ private static function fingerprint(string $action, Operation $op): string { return hash('sha256', $action . "\n" . $op->requestHash); } private function unit(int $id, int $expectedVersion): CoveredUnit { $unit = $this->units->get($id) ?? throw DomainError::notFound('Unit'); if ($unit->version() !== $expectedVersion) { throw DomainError::versionConflict((int) $expectedVersion, (int) $unit->version()); } return $unit; } /** @return list */ private function claimUnits(Claim $claim): array { $units = []; foreach ($claim->unitIds() as $id) { $units[] = $this->units->get($id) ?? throw DomainError::notFound('Unit'); } return $units; } private function now(): \DateTimeImmutable { return ($this->clock)(); } }