every doubt that sent the claim to review, cleared by reconcile */ private array $reviewReasons = []; /** When the defect appeared, as the consumer declares it (art. 133 c. 1: "si manifesta"). */ private ?LegalDate $manifestedOn = null; /** * The facts of the WooCommerce order a person looked at and accepted * when reconciling (order state, order line), as the integration layer * describes them. A later check reviews the claim only when the facts * differ from these; factsRevision changes with every new acceptance, * so the same change seen again after it is a new review. * * @var array */ private array $acceptedFacts = []; private int $factsRevision = 0; private ?LegalDate $informedOn = null; private ?InformativaChannel $informedVia = null; private ?string $informativaVersion = null; private ?Remedy $choice = null; private bool $refurbishedRequested = false; private bool $remedyRefused = false; private ?LegalDate $goodsReceivedOn = null; private bool $loanerOut = false; private ?Outcome $outcome = null; private ?LegalDate $closedOn = null; /** @var list */ private array $refundIds = []; /** @var list */ private array $pendingEvents = []; /** * @param list $unitIds */ private function __construct( private int $orderId, private int $orderItemId, private array $unitIds, private LegalDate $reportedOn, private string $defect, private bool $informativaRequired, ) { } /** * @param array $row */ public static function fromRow(array $row): self { $claim = new self( (int) $row['order_id'], (int) $row['order_item_id'], array_map('intval', self::decodeList((string) $row['unit_ids'])), LegalDate::of((string) $row['reported_on']), (string) $row['defect'], (bool) $row['informativa_required'], ); $claim->id = (int) $row['id']; $claim->state = ClaimState::from((string) $row['state']); $claim->reviewReasons = array_map('strval', self::decodeList((string) $row['review_reasons'])); $claim->manifestedOn = self::dateOrNull($row['manifested_on'] ?? null); $claim->acceptedFacts = self::decodeFacts($row['accepted_facts'] ?? null); $claim->factsRevision = (int) ($row['facts_revision'] ?? 0); $claim->informedOn = self::dateOrNull($row['informed_on']); $claim->informedVia = null === $row['informed_via'] ? null : InformativaChannel::from((string) $row['informed_via']); $claim->informativaVersion = null === $row['informativa_version'] ? null : (string) $row['informativa_version']; $claim->choice = null === $row['choice'] ? null : Remedy::from((string) $row['choice']); $claim->refurbishedRequested = (bool) $row['refurbished_requested']; $claim->remedyRefused = (bool) $row['remedy_refused']; $claim->goodsReceivedOn = self::dateOrNull($row['goods_received_on']); $claim->loanerOut = (bool) $row['loaner_out']; $claim->outcome = null === $row['outcome'] ? null : Outcome::from((string) $row['outcome']); $claim->closedOn = self::dateOrNull($row['closed_on']); $claim->refundIds = array_map('intval', self::decodeList((string) $row['refund_ids'])); $claim->version = (int) $row['version']; $claim->loadedVersion = $claim->version; return $claim; } /** @return array one database row; lists are JSON. */ public function toRow(): array { return [ 'id' => $this->id, 'order_id' => $this->orderId, 'order_item_id' => $this->orderItemId, 'unit_ids' => json_encode($this->unitIds, JSON_THROW_ON_ERROR), 'reported_on' => $this->reportedOn->toString(), 'manifested_on' => $this->manifestedOn?->toString(), 'accepted_facts' => [] === $this->acceptedFacts ? null : json_encode($this->acceptedFacts, JSON_THROW_ON_ERROR), 'facts_revision' => $this->factsRevision, 'defect' => $this->defect, 'informativa_required' => $this->informativaRequired, 'state' => $this->state->value, 'review_reasons' => json_encode($this->reviewReasons, JSON_THROW_ON_ERROR), 'informed_on' => $this->informedOn?->toString(), 'informed_via' => $this->informedVia?->value, 'informativa_version' => $this->informativaVersion, 'choice' => $this->choice?->value, 'refurbished_requested' => $this->refurbishedRequested, 'remedy_refused' => $this->remedyRefused, 'goods_received_on' => $this->goodsReceivedOn?->toString(), 'loaner_out' => $this->loanerOut, 'outcome' => $this->outcome?->value, 'closed_on' => $this->closedOn?->toString(), 'refund_ids' => json_encode($this->refundIds, JSON_THROW_ON_ERROR), 'version' => $this->version, ]; } /** * @param list $unitIds */ public static function open(int $orderId, int $orderItemId, array $unitIds, LegalDate $reportedOn, string $defect, bool $informativaRequired, ?int $actorId, string $idempotencyKey, \DateTimeImmutable $now, ?LegalDate $manifestedOn = null): self { $unitIds = array_values(array_unique(array_map('intval', $unitIds))); if ([] === $unitIds) { throw DomainError::invalidInput('A claim needs at least one unit.'); } self::assertReason($defect); if (null !== $manifestedOn && $manifestedOn->isAfter($reportedOn)) { throw DomainError::invalidInput('The defect cannot appear after it was reported.'); } $claim = new self($orderId, $orderItemId, $unitIds, $reportedOn, trim($defect), $informativaRequired); $claim->manifestedOn = $manifestedOn; $claim->record(WarrantyEvent::CLAIM_OPENED, $actorId, $claim->defect, [], null, $idempotencyKey, $now, false); return $claim; } // ------------------------------------------------------------------ // Steps while the claim is open // ------------------------------------------------------------------ /** * Art. 135-bis c. 2-bis. Recording it again is allowed (a second email, * a call). It also settles a review whose only doubt was whether the * informativa reached the consumer (G13). * * @param array{text?:string, to?:string, locale?:string} $content what was * communicated, kept in this event of the history (the claim keeps * only the version): the proof of each informativa. */ public function inform(LegalDate $on, InformativaChannel $channel, string $textVersion, ?int $actorId, string $idempotencyKey, \DateTimeImmutable $now, array $content = []): void { $settlesDoubt = ClaimState::NeedsReview === $this->state && null === $this->outcome && [ReviewReason::INFORMATIVA_UNCERTAIN] === $this->reviewReasons; if (!$settlesDoubt) { $this->assertOpen(); } if ('' === trim($textVersion)) { throw DomainError::invalidInput('The informativa needs the version of the text that was given.'); } if ($on->isBefore($this->reportedOn)) { throw DomainError::invalidInput('The informativa cannot come before the defect was reported.'); } $before = $this->snapshot(); if ($settlesDoubt) { $this->state = ClaimState::Open; $this->reviewReasons = []; } $this->informedOn = $on; $this->informedVia = $channel; $this->informativaVersion = trim($textVersion); $extra = []; if ('' !== trim((string) ($content['text'] ?? ''))) { $extra = [ 'informativa_text' => (string) $content['text'], 'informativa_to' => (string) ($content['to'] ?? ''), 'informativa_locale' => (string) ($content['locale'] ?? ''), 'informativa_sha256' => hash('sha256', (string) $content['text']), ]; } $this->record(WarrantyEvent::INFORMED, $actorId, $channel->value, $before, $this->informativaVersion, $idempotencyKey, $now, true, $extra); } /** * When the defect appeared, recorded or corrected while the claim is not * closed. It decides "out of warranty" and the extension, not the day of * the report. */ /** * @param bool|null $informativaRequired whether the informativa is due with * this date (a defect that appeared after the guarantee is goodwill) */ public function setManifestedOn(LegalDate $on, ?int $actorId, string $reason, string $idempotencyKey, \DateTimeImmutable $now, ?bool $informativaRequired = null): void { if (ClaimState::Closed === $this->state) { throw DomainError::invalidTransition('The claim is closed: reopen it first.'); } self::assertReason($reason); if ($on->isAfter($this->reportedOn)) { throw DomainError::invalidInput('The defect cannot appear after it was reported.'); } $before = $this->snapshot(); $this->manifestedOn = $on; if (null !== $informativaRequired && null === $this->outcome) { $this->informativaRequired = $informativaRequired; } $this->record(WarrantyEvent::MANIFESTATION_SET, $actorId, trim($reason), $before, null, $idempotencyKey, $now); } public function manifestedOn(): ?LegalDate { return $this->manifestedOn; } /** * The date the legal rules look at: when the defect appeared. If it is * not known, the report (the defect appeared on that day at the latest). */ public function defectDate(): LegalDate { return $this->manifestedOn ?? $this->reportedOn; } /** * The consumer's choice (art. 135-bis c. 2). Recording a choice after a * refusal means the seller now offers that remedy: the refusal is * withdrawn, and both events stay in history. */ public function choose(Remedy $remedy, ?int $actorId, string $idempotencyKey, \DateTimeImmutable $now): void { $this->assertOpen(); $before = $this->snapshot(); $this->choice = $remedy; $this->remedyRefused = false; $this->record(WarrantyEvent::CHOICE_RECORDED, $actorId, $remedy->value, $before, null, $idempotencyKey, $now); } /** Art. 135-ter c. 1: a refurbished replacement only on the consumer's explicit request. */ public function requestRefurbished(?int $actorId, string $note, string $idempotencyKey, \DateTimeImmutable $now): void { $this->assertOpen(); self::assertReason($note); $before = $this->snapshot(); $this->refurbishedRequested = true; $this->record(WarrantyEvent::REFURBISHED_REQUESTED, $actorId, trim($note), $before, null, $idempotencyKey, $now); } public function receiveGoods(LegalDate $on, ?int $actorId, ?string $externalRef, string $idempotencyKey, \DateTimeImmutable $now): void { $this->assertOpen(); $before = $this->snapshot(); $this->goodsReceivedOn = $on; $this->record(WarrantyEvent::GOODS_RECEIVED, $actorId, $on->toString(), $before, $externalRef, $idempotencyKey, $now); } public function lendLoaner(LegalDate $on, ?int $actorId, ?string $externalRef, string $idempotencyKey, \DateTimeImmutable $now): void { $this->assertOpen(); if ($this->loanerOut) { throw DomainError::invalidTransition('A replacement good is already on loan.'); } $before = $this->snapshot(); $this->loanerOut = true; $this->record(WarrantyEvent::LOANER_LENT, $actorId, $on->toString(), $before, $externalRef, $idempotencyKey, $now); } /** Allowed after closing too: the consumer may give the loan back later. */ public function returnLoaner(LegalDate $on, ?int $actorId, string $idempotencyKey, \DateTimeImmutable $now): void { if (!$this->loanerOut) { throw DomainError::invalidTransition('No replacement good is on loan.'); } $before = $this->snapshot(); $this->loanerOut = false; $this->record(WarrantyEvent::LOANER_RETURNED, $actorId, $on->toString(), $before, null, $idempotencyKey, $now); } /** * Art. 135-bis c. 3: the seller may refuse when both remedies are * impossible or disproportionate. Repair and replacement are then * blocked until a new choice is recorded. */ public function refuseRemedy(?int $actorId, string $reason, string $idempotencyKey, \DateTimeImmutable $now): void { $this->assertOpen(); self::assertReason($reason); $before = $this->snapshot(); $this->remedyRefused = true; $this->record(WarrantyEvent::REMEDY_REFUSED, $actorId, trim($reason), $before, null, $idempotencyKey, $now); } // ------------------------------------------------------------------ // Closing // ------------------------------------------------------------------ public function completeRepair(LegalDate $on, ?int $actorId, string $note, string $idempotencyKey, \DateTimeImmutable $now): void { $this->assertCanApplyRemedy(Remedy::Repair, $on); $before = $this->snapshot(); $this->close(Outcome::Repaired, $on); $this->record(WarrantyEvent::REPAIR_COMPLETED, $actorId, trim($note), $before, null, $idempotencyKey, $now); } public function completeReplacement(LegalDate $on, bool $refurbished, ?int $actorId, string $note, string $idempotencyKey, \DateTimeImmutable $now): void { $this->assertCanApplyRemedy(Remedy::Replacement, $on); if ($refurbished && !$this->refurbishedRequested) { throw DomainError::refurbishedRequestRequired(); } $before = $this->snapshot(); $this->close(Outcome::Replaced, $on); $this->record(WarrantyEvent::REPLACEMENT_COMPLETED, $actorId, trim($note), $before, $refurbished ? 'refurbished' : null, $idempotencyKey, $now); } /** * Art. 135-bis c. 4 and 5: price reduction or termination, money moved by * a native WooCommerce refund (the claim keeps only its id). Termination * is not allowed for a minor defect. */ public function closeWithRefund(Outcome $outcome, int $refundId, bool $defectNotMinor, LegalDate $on, ?int $actorId, string $reason, string $idempotencyKey, \DateTimeImmutable $now): void { $this->assertOpenOrSettledByRefund(); if (!in_array($outcome, [Outcome::PriceReduced, Outcome::Terminated], true)) { throw DomainError::invalidInput('Use a price reduction or a termination.'); } if ($refundId <= 0) { throw DomainError::invalidInput('Link the WooCommerce refund that moved the money.'); } if (Outcome::Terminated === $outcome && !$defectNotMinor) { throw DomainError::minorDefect(); } self::assertReason($reason); $this->assertInformedBefore($on); $before = $this->snapshot(); $this->close($outcome, $on); $this->refundIds[] = $refundId; $this->record(WarrantyEvent::CLOSED, $actorId, trim($reason), $before, 'refund:' . $refundId, $idempotencyKey, $now); } /** * Rejections and withdrawals. Out-of-warranty rejections are checked * against the units by the service (rule 4) before reaching here. */ public function closeWithoutRemedy(Outcome $outcome, LegalDate $on, ?int $actorId, string $reason, string $idempotencyKey, \DateTimeImmutable $now): void { if (Outcome::Withdrawn === $outcome) { $this->assertOpenOrSettledByRefund(); } else { $this->assertOpen(); } if (!$outcome->isRejection() && Outcome::Withdrawn !== $outcome) { throw DomainError::invalidInput('Use a rejection or a withdrawal.'); } self::assertReason($reason); $before = $this->snapshot(); $this->close($outcome, $on); $this->record(WarrantyEvent::CLOSED, $actorId, trim($reason), $before, null, $idempotencyKey, $now); } // ------------------------------------------------------------------ // Review and reopening // ------------------------------------------------------------------ /** * Something changed outside the plugin, or the data is doubtful (rule 10, * rule 12). Reasons add up, so no doubt hides another. A closed claim * keeps its outcome and returns to closed when reconciled. Returns false * when the claim was already in review for that reason (a repeated hook * adds nothing). */ /** * @param array $facts what changed, when the caller knows it: * with facts, a review already open for the same reason is recorded * again (new event, new version), because what is to be checked is * no longer what a person may be looking at. */ public function markForReview(string $reasonCode, ?int $actorId, string $idempotencyKey, \DateTimeImmutable $now, array $facts = []): bool { if ('' === trim($reasonCode)) { throw DomainError::reasonRequired(); } $already = ClaimState::NeedsReview === $this->state && in_array($reasonCode, $this->reviewReasons, true); if ($already && [] === $facts) { return false; } $before = $this->snapshot(); $this->state = ClaimState::NeedsReview; if (!$already) { $this->reviewReasons[] = $reasonCode; } $this->record(WarrantyEvent::MARKED_REVIEW, $actorId, $reasonCode, $before, null, $idempotencyKey, $now, true, [] === $facts ? [] : ['order_facts' => $facts]); return true; } /** * A human looked at it: back to work, or back to closed if it had an outcome. * * @param bool|null $informativaRequired the rule as the units say now * (a corrected contract date may have changed it) * @param array $extra what the operator confirmed, kept in the event * @param array|null $acceptedFacts the order as the operator saw it now */ public function reconcile(?int $actorId, string $reason, string $idempotencyKey, \DateTimeImmutable $now, ?bool $informativaRequired = null, array $extra = [], ?array $acceptedFacts = null): void { if (ClaimState::NeedsReview !== $this->state) { throw DomainError::invalidTransition('Only claims in review can be reconciled.'); } self::assertReason($reason); $before = $this->snapshot(); if (null !== $informativaRequired && null === $this->outcome) { $this->informativaRequired = $informativaRequired; } if (null !== $acceptedFacts) { $acceptedFacts = array_map('strval', $acceptedFacts); ksort($acceptedFacts); if ($acceptedFacts !== $this->acceptedFacts) { $this->acceptedFacts = $acceptedFacts; $this->factsRevision++; } } $this->state = null === $this->outcome ? ClaimState::Open : ClaimState::Closed; $this->reviewReasons = []; $this->record(WarrantyEvent::RECONCILED, $actorId, trim($reason), $before, null, $idempotencyKey, $now, true, $extra); } /** * The defect came back or the claim was closed by mistake: the outcome is * kept in history, the claim goes to review (rule 12). What the consumer * asked for the old remedy (a refurbished good) does not carry over. */ public function reopen(string $reasonCode, ?int $actorId, string $note, string $idempotencyKey, \DateTimeImmutable $now): void { if (ClaimState::Closed !== $this->state) { throw DomainError::invalidTransition('Only closed claims can be reopened.'); } self::assertReason($note); $before = $this->snapshot(); $this->state = ClaimState::NeedsReview; $this->reviewReasons = [$reasonCode]; $this->outcome = null; $this->closedOn = null; $this->choice = null; $this->refurbishedRequested = false; $this->remedyRefused = false; $this->record(WarrantyEvent::REOPENED, $actorId, trim($note), $before, $reasonCode, $idempotencyKey, $now); } // ------------------------------------------------------------------ public function id(): ?int { return $this->id; } public function assignId(int $id): void { if (null !== $this->id) { throw new \LogicException('Claim already has an id.'); } $this->id = $id; } public function orderId(): int { return $this->orderId; } public function orderItemId(): int { return $this->orderItemId; } /** @return list */ public function unitIds(): array { return $this->unitIds; } public function state(): ClaimState { return $this->state; } /** @return list */ public function reviewReasons(): array { return $this->reviewReasons; } /** @return array */ public function acceptedFacts(): array { return $this->acceptedFacts; } public function factsRevision(): int { return $this->factsRevision; } public function inReviewFor(string $reasonCode): bool { return ClaimState::NeedsReview === $this->state && in_array($reasonCode, $this->reviewReasons, true); } public function reportedOn(): LegalDate { return $this->reportedOn; } public function informativaRequired(): bool { return $this->informativaRequired; } public function isInformed(): bool { return null !== $this->informedOn; } public function informedOn(): ?LegalDate { return $this->informedOn; } public function defect(): string { return $this->defect; } public function isRefurbishedRequested(): bool { return $this->refurbishedRequested; } public function isRemedyRefused(): bool { return $this->remedyRefused; } /** @return list */ public function refundIds(): array { return $this->refundIds; } public function choice(): ?Remedy { return $this->choice; } public function outcome(): ?Outcome { return $this->outcome; } public function closedOn(): ?LegalDate { return $this->closedOn; } public function isLoanerOut(): bool { return $this->loanerOut; } public function version(): int { return $this->version; } public function loadedVersion(): int { return $this->loadedVersion; } /** @return list */ public function pullEvents(): array { $events = $this->pendingEvents; $this->pendingEvents = []; $this->loadedVersion = $this->version; return $events; } /** @return array */ public function snapshot(): array { return [ 'order_item_id' => $this->orderItemId, 'unit_ids' => $this->unitIds, 'reported_on' => $this->reportedOn->toString(), 'manifested_on' => $this->manifestedOn?->toString(), 'accepted_facts' => $this->acceptedFacts, 'defect' => $this->defect, 'informativa_required' => $this->informativaRequired, 'state' => $this->state->value, 'review_reasons' => $this->reviewReasons, 'informed_on' => $this->informedOn?->toString(), 'informed_via' => $this->informedVia?->value, 'informativa_version' => $this->informativaVersion, 'choice' => $this->choice?->value, 'refurbished_requested' => $this->refurbishedRequested, 'remedy_refused' => $this->remedyRefused, 'goods_received_on' => $this->goodsReceivedOn?->toString(), 'loaner_out' => $this->loanerOut, 'outcome' => $this->outcome?->value, 'closed_on' => $this->closedOn?->toString(), 'refund_ids' => $this->refundIds, ]; } // ------------------------------------------------------------------ private function assertCanApplyRemedy(Remedy $remedy, LegalDate $on): void { $this->assertOpen(); $this->assertInformedBefore($on); if ($this->remedyRefused) { throw DomainError::remedyRefused(); } if ($remedy !== $this->choice) { throw DomainError::invalidTransition('Record the consumer\'s choice of this remedy first.'); } } /** Rule 3: for new contracts, no remedy without the informativa, and not before it. */ private function assertInformedBefore(LegalDate $on): void { if (!$this->informativaRequired) { return; } if (null === $this->informedOn) { throw DomainError::informativaRequired(); } if ($on->isBefore($this->informedOn)) { throw DomainError::invalidInput('The remedy cannot come before the consumer was informed.'); } } private function close(Outcome $outcome, LegalDate $on): void { if ($on->isBefore($this->reportedOn)) { throw DomainError::invalidInput('A claim cannot close before it was reported.'); } $this->outcome = $outcome; $this->closedOn = $on; $this->state = ClaimState::Closed; $this->reviewReasons = []; } /** * A refund or cancellation in WooCommerce sends the claim to review * (rule 10). When that is the only doubt, closing the claim with the * refund (or as withdrawn) is how the review is settled: the units are * gone, so a reconcile back to open would be refused. */ private function assertOpenOrSettledByRefund(): void { if (ClaimState::NeedsReview === $this->state && null === $this->outcome && [] !== $this->reviewReasons && [] === array_diff($this->reviewReasons, ReviewReason::SETTLED_BY_REFUND)) { return; } $this->assertOpen(); } private function assertOpen(): void { if (ClaimState::Open !== $this->state) { throw DomainError::invalidTransition(ClaimState::NeedsReview === $this->state ? 'The claim is in review: reconcile it first.' : 'The claim is closed: reopen it first.'); } } private static function dateOrNull(mixed $value): ?LegalDate { return null === $value ? null : LegalDate::of((string) $value); } /** @return array */ private static function decodeFacts(mixed $json): array { if (null === $json || '' === $json) { return []; } $facts = json_decode((string) $json, true, 4, JSON_THROW_ON_ERROR); return is_array($facts) ? array_map('strval', $facts) : []; } /** @return list */ private static function decodeList(string $json): array { $list = json_decode($json, true, 4, JSON_THROW_ON_ERROR); return is_array($list) ? array_values($list) : []; } private static function assertReason(string $reason): void { if ('' === trim($reason)) { throw DomainError::reasonRequired(); } } /** * @param array $before * @param array $extra kept in this event only */ private function record(string $type, ?int $actorId, string $reason, array $before, ?string $externalRef, string $idempotencyKey, \DateTimeImmutable $now, bool $bump = true, array $extra = []): void { if ($bump) { $this->version++; } $this->pendingEvents[] = new WarrantyEvent(WarrantyEvent::SUBJECT_CLAIM, $type, $actorId, $reason, $before, $this->snapshot() + $extra, $externalRef, $idempotencyKey, $now); } }