*/ private array $pendingEvents = []; /** * @param list $repairs */ private function __construct( private int $orderId, private int $orderItemId, private int $unitIndex, private int $productId, private LegalDate $contractDate, private ?LegalDate $deliveredOn, private DeliverySource $deliverySource, private int $guaranteeMonths, private ConsumerStatus $consumer, private ?int $openClaimId, private array $repairs, private ?int $terminatedByClaimId, private ?LegalDate $operatorEndOn = null, ) { } public static function track( int $orderId, int $orderItemId, int $unitIndex, int $productId, LegalDate $contractDate, ?LegalDate $deliveredOn, DeliverySource $source, int $guaranteeMonths, ConsumerStatus $consumer, string $idempotencyKey, \DateTimeImmutable $now, ): self { if ($unitIndex < 1) { throw DomainError::invalidInput('Unit index starts at 1.'); } self::assertDelivery($contractDate, $deliveredOn, $source); self::assertGuaranteeMonths($guaranteeMonths); $unit = new self($orderId, $orderItemId, $unitIndex, $productId, $contractDate, $deliveredOn, $source, $guaranteeMonths, $consumer, null, [], null); $unit->record(WarrantyEvent::UNIT_TRACKED, null, '', [], null, $idempotencyKey, $now); return $unit; } /** * @param array $row */ public static function fromRow(array $row): self { $repairs = []; foreach (json_decode((string) $row['repairs'], true, 4, JSON_THROW_ON_ERROR) as $entry) { // defect_on: when the defect appeared. Rows written before that day was // recorded kept only the report date: it stays marked, never taken // for the day the defect appeared without saying so. $fromReport = !isset($entry['defect_on']) || !empty($entry['from_report']); $repair = ['claim' => (int) $entry['claim'], 'defect_on' => LegalDate::of((string) ($entry['defect_on'] ?? $entry['reported_on']))->toString()]; if ($fromReport) { $repair['from_report'] = true; } $repairs[] = $repair; } $unit = new self( (int) $row['order_id'], (int) $row['order_item_id'], (int) $row['unit_index'], (int) $row['product_id'], LegalDate::of((string) $row['contract_date']), null === $row['delivered_on'] ? null : LegalDate::of((string) $row['delivered_on']), DeliverySource::from((string) $row['delivery_source']), (int) $row['guarantee_months'], ConsumerStatus::from((string) $row['consumer']), null === $row['open_claim_id'] ? null : (int) $row['open_claim_id'], $repairs, null === $row['terminated_by_claim_id'] ? null : (int) $row['terminated_by_claim_id'], empty($row['operator_end_on']) ? null : LegalDate::of((string) $row['operator_end_on']), ); $unit->id = (int) $row['id']; $unit->version = (int) $row['version']; $unit->loadedVersion = $unit->version; return $unit; } /** * One database row. `extended` and `repair_count` are derived from * `repairs` and stored only so lists can be filtered and sorted. * * @return array */ public function toRow(): array { return [ 'id' => $this->id, 'order_id' => $this->orderId, 'order_item_id' => $this->orderItemId, 'unit_index' => $this->unitIndex, 'product_id' => $this->productId, 'contract_date' => $this->contractDate->toString(), 'delivered_on' => $this->deliveredOn?->toString(), 'delivery_source' => $this->deliverySource->value, 'guarantee_months' => $this->guaranteeMonths, 'consumer' => $this->consumer->value, 'open_claim_id' => $this->openClaimId, 'repairs' => json_encode($this->repairs, JSON_THROW_ON_ERROR), 'repair_count' => $this->repairCount(), 'extended' => $this->isExtended(), 'extended_by_claim_id' => $this->extendedByClaimId(), 'terminated_by_claim_id' => $this->terminatedByClaimId, 'operator_end_on' => $this->operatorEndOn?->toString(), 'version' => $this->version, ]; } // ------------------------------------------------------------------ // Dates // ------------------------------------------------------------------ public function newRulesApply(): bool { return LegalRules::newRulesApply($this->contractDate); } /** * Null when the dates must not be shown: delivery unknown (G08) or the * buyer not confirmed as a consumer (G12). */ public function dates(): ?CoverageDates { if (null === $this->deliveredOn || ConsumerStatus::Consumer !== $this->consumer) { return null; } // The extension runs from the end of the guarantee (art. 2963 c.c.), // so it is added to that date, not to the months from delivery. $end = $this->baseGuaranteeEnd(); if ($this->isExtended()) { $end = $end->addMonths(LegalRules::REPAIR_EXTENSION_MONTHS); } // A later end the shop granted (spec section 4, after a replacement). if (null !== $this->operatorEndOn && $this->operatorEndOn->isAfter($end)) { $end = $this->operatorEndOn; } return new CoverageDates( $this->deliveredOn->addMonths(LegalRules::PRESUMPTION_MONTHS), $end, $this->deliveredOn->addMonths(LegalRules::PRESCRIPTION_MONTHS), $this->isExtended(), ); } // ------------------------------------------------------------------ // Changes // ------------------------------------------------------------------ public function setDelivery(?LegalDate $on, DeliverySource $source, ?int $actorId, string $reason, string $idempotencyKey, \DateTimeImmutable $now): void { self::assertReason($reason); self::assertDelivery($this->contractDate, $on, $source); $before = $this->snapshot(); $this->deliveredOn = $on; $this->deliverySource = $source; $this->record(WarrantyEvent::DELIVERY_SET, $actorId, trim($reason), $before, null, $idempotencyKey, $now); } /** * What WooCommerce knows now, for a unit tracked earlier (the order was * completed after the first lookup). A delivery an operator confirmed is * never overwritten; an order going back to unknown changes nothing. * Returns whether the unit changed. */ public function refreshDelivery(?LegalDate $on, DeliverySource $source, string $idempotencyKey, \DateTimeImmutable $now): bool { if (DeliverySource::Confirmed === $this->deliverySource || DeliverySource::Unknown === $source) { return false; } if ($source === $this->deliverySource && null !== $on && null !== $this->deliveredOn && $on->equals($this->deliveredOn)) { return false; } $this->setDelivery($on, $source, null, '@delivery_from_order', $idempotencyKey, $now); return true; } /** Returns whether the status changed. */ public function setConsumer(ConsumerStatus $status, ?int $actorId, string $reason, string $idempotencyKey, \DateTimeImmutable $now): bool { self::assertReason($reason); $changed = $status !== $this->consumer; $before = $this->snapshot(); $this->consumer = $status; $this->record(WarrantyEvent::CONSUMER_SET, $actorId, trim($reason), $before, null, $idempotencyKey, $now); return $changed; } /** * Whether a repair of a defect reported on that day qualifies for the * extension (art. 133 c. 1-bis): contract from 31/07/2026, buyer * confirmed as a consumer, defect reported within the guarantee. A * goodwill repair (late, or for a business buyer) does not. */ public function repairQualifies(LegalDate $defectOn): bool { return $this->newRulesApply() && ConsumerStatus::Consumer === $this->consumer && null !== $this->deliveredOn && !$defectOn->isAfter($this->baseGuaranteeEnd()); } /** * A repair completed as the remedy of a claim. Counted on every unit * (a new claim on a repaired unit goes to review, rule 12). One event: * guarantee_extended when this repair gave the extension, unit_repaired * otherwise. Returns whether it gave the extension. */ public function recordRepair(int $claimId, LegalDate $defectOn, ?int $actorId, string $idempotencyKey, \DateTimeImmutable $now): bool { $wasExtended = $this->isExtended(); $before = $this->snapshot(); $this->repairs[] = ['claim' => $claimId, 'defect_on' => $defectOn->toString()]; $extended = !$wasExtended && $this->isExtended(); $this->record( $extended ? WarrantyEvent::GUARANTEE_EXTENDED : WarrantyEvent::UNIT_REPAIRED, $actorId, $extended ? '@repair_extension' : '@repair_completed', $before, 'claim:' . $claimId, $idempotencyKey, $now, ); return $extended; } /** * Compensating event for a repair recorded by mistake (rule 7): the last * repair of that claim goes. If it was the one giving the extension, the * next qualifying repair, if any, gives it instead. */ public function revokeRepair(int $claimId, ?int $actorId, string $reason, string $idempotencyKey, \DateTimeImmutable $now): void { self::assertReason($reason); $index = null; foreach ($this->repairs as $i => $repair) { if ($repair['claim'] === $claimId) { $index = $i; } } if (null === $index) { throw DomainError::invalidTransition('This claim recorded no repair on this unit.'); } $before = $this->snapshot(); array_splice($this->repairs, $index, 1); $this->record(WarrantyEvent::REPAIR_REVOKED, $actorId, trim($reason), $before, 'claim:' . $claimId, $idempotencyKey, $now); } /** * The shop grants a later end of the guarantee, for example after a * replacement (spec section 4). It can only lengthen what the law gives: * an earlier date changes nothing in dates(). Null removes it. */ public function setOperatorEnd(?LegalDate $on, ?int $actorId, string $reason, string $idempotencyKey, \DateTimeImmutable $now): void { self::assertReason($reason); if (null !== $on && null !== $this->deliveredOn && !$on->isAfter($this->baseGuaranteeEnd())) { throw DomainError::invalidInput('The new end must come after the legal end of the guarantee.'); } $before = $this->snapshot(); $this->operatorEndOn = $on; $this->record(WarrantyEvent::GUARANTEE_SET_BY_OPERATOR, $actorId, trim($reason), $before, null, $idempotencyKey, $now); } public function operatorEndOn(): ?LegalDate { return $this->operatorEndOn; } /** * Art. 133 c. 4: a used good sold with a shorter guarantee agreed with the * buyer, or a correction of what was recorded at the sale. With a reason. */ public function setGuaranteeMonths(int $months, ?int $actorId, string $reason, string $idempotencyKey, \DateTimeImmutable $now): void { self::assertReason($reason); self::assertGuaranteeMonths($months); $before = $this->snapshot(); $this->guaranteeMonths = $months; $this->record(WarrantyEvent::GUARANTEE_MONTHS_SET, $actorId, trim($reason), $before, null, $idempotencyKey, $now); } /** * The day the contract was concluded, when the order date is not it * (imported orders, orders created before the sale). Returns whether the * new rules (from 31/07/2026) changed side. */ public function setContractDate(LegalDate $on, ?int $actorId, string $reason, string $idempotencyKey, \DateTimeImmutable $now): bool { self::assertReason($reason); if (null !== $this->deliveredOn && $this->deliveredOn->isBefore($on)) { throw DomainError::invalidInput('The delivery cannot come before the order.'); } $rulesBefore = $this->newRulesApply(); $before = $this->snapshot(); $this->contractDate = $on; $this->record(WarrantyEvent::CONTRACT_DATE_SET, $actorId, trim($reason), $before, null, $idempotencyKey, $now); return $rulesBefore !== $this->newRulesApply(); } /** Art. 135-bis c. 5: the contract was terminated, the good goes back. */ public function terminate(int $claimId, ?int $actorId, string $idempotencyKey, \DateTimeImmutable $now): void { if (null !== $this->terminatedByClaimId) { throw DomainError::invalidTransition('This unit was already returned on termination.'); } $before = $this->snapshot(); $this->terminatedByClaimId = $claimId; $this->record(WarrantyEvent::UNIT_TERMINATED, $actorId, '@contract_terminated', $before, 'claim:' . $claimId, $idempotencyKey, $now); } /** Compensating event for a termination recorded by mistake. */ public function revokeTermination(int $claimId, ?int $actorId, string $reason, string $idempotencyKey, \DateTimeImmutable $now): void { self::assertReason($reason); if ($this->terminatedByClaimId !== $claimId) { return; } $before = $this->snapshot(); $this->terminatedByClaimId = null; $this->record(WarrantyEvent::TERMINATION_REVOKED, $actorId, trim($reason), $before, 'claim:' . $claimId, $idempotencyKey, $now); } /** Taken by an open claim (rule 1). The database enforces it too. */ public function attachTo(int $claimId, ?int $actorId, string $idempotencyKey, \DateTimeImmutable $now): void { if ($this->openClaimId === $claimId) { return; } if (null !== $this->openClaimId) { throw DomainError::unitBusy((int) $this->id, (int) $this->openClaimId); } $before = $this->snapshot(); $this->openClaimId = $claimId; $this->record(WarrantyEvent::UNIT_ATTACHED, $actorId, '', $before, 'claim:' . $claimId, $idempotencyKey, $now); } public function release(int $claimId, ?int $actorId, string $idempotencyKey, \DateTimeImmutable $now): void { if ($this->openClaimId !== $claimId) { return; } $before = $this->snapshot(); $this->openClaimId = null; $this->record(WarrantyEvent::UNIT_RELEASED, $actorId, '', $before, 'claim:' . $claimId, $idempotencyKey, $now); } // ------------------------------------------------------------------ public function id(): ?int { return $this->id; } public function assignId(int $id): void { if (null !== $this->id) { throw new \LogicException('Unit already has an id.'); } $this->id = $id; } public function orderId(): int { return $this->orderId; } public function orderItemId(): int { return $this->orderItemId; } public function unitIndex(): int { return $this->unitIndex; } public function contractDate(): LegalDate { return $this->contractDate; } public function deliveredOn(): ?LegalDate { return $this->deliveredOn; } public function deliverySource(): DeliverySource { return $this->deliverySource; } public function consumer(): ConsumerStatus { return $this->consumer; } public function isExtended(): bool { return null !== $this->extendedByClaimId(); } /** The claim whose repair gives the extension: the first one that qualifies now. */ public function extendedByClaimId(): ?int { foreach ($this->repairs as $repair) { if ($this->repairQualifies(LegalDate::of($repair['defect_on']))) { return $repair['claim']; } } return null; } /** * Repairs recorded before the day the defect appeared was asked: they * gave no extension only because the report came after the guarantee. * Whether the defect appeared in time is unknown: a person must check. * * @return list the claims of those repairs */ public function ambiguousRepairClaims(): array { $claims = []; foreach ($this->repairs as $repair) { if (!empty($repair['from_report']) && $this->newRulesApply() && ConsumerStatus::Consumer === $this->consumer && null !== $this->deliveredOn && !$this->repairQualifies(LegalDate::of($repair['defect_on']))) { $claims[] = $repair['claim']; } } return $claims; } public function repairCount(): int { return count($this->repairs); } public function terminatedByClaimId(): ?int { return $this->terminatedByClaimId; } public function openClaimId(): ?int { return $this->openClaimId; } 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_index' => $this->unitIndex, 'contract_date' => $this->contractDate->toString(), 'delivered_on' => $this->deliveredOn?->toString(), 'delivery_source' => $this->deliverySource->value, 'guarantee_months' => $this->guaranteeMonths, 'consumer' => $this->consumer->value, 'repairs' => $this->repairs, 'extended' => $this->isExtended(), 'extended_by_claim_id' => $this->extendedByClaimId(), 'terminated_by_claim_id' => $this->terminatedByClaimId, 'operator_end_on' => $this->operatorEndOn?->toString(), 'open_claim_id' => $this->openClaimId, ]; } // ------------------------------------------------------------------ /** @param array $before */ private function record(string $type, ?int $actorId, string $reason, array $before, ?string $externalRef, string $idempotencyKey, \DateTimeImmutable $now): void { if (WarrantyEvent::UNIT_TRACKED !== $type) { $this->version++; } $this->pendingEvents[] = new WarrantyEvent(WarrantyEvent::SUBJECT_UNIT, $type, $actorId, $reason, $before, $this->snapshot(), $externalRef, $idempotencyKey, $now); } private function baseGuaranteeEnd(): LegalDate { if (null === $this->deliveredOn) { throw new \LogicException('No delivery date.'); } return $this->deliveredOn->addMonths($this->guaranteeMonths); } private static function assertDelivery(LegalDate $contractDate, ?LegalDate $on, DeliverySource $source): void { if ((null === $on) !== (DeliverySource::Unknown === $source)) { throw DomainError::invalidInput('A delivery date needs a known source, and an unknown source has no date.'); } if (null !== $on && $on->isBefore($contractDate)) { throw DomainError::invalidInput('The delivery cannot come before the order.'); } } private static function assertGuaranteeMonths(int $months): void { if ($months < LegalRules::MIN_USED_GOODS_MONTHS || $months > LegalRules::GUARANTEE_MONTHS) { throw DomainError::invalidInput('The legal guarantee lasts 24 months, or no less than 12 for used goods.'); } } private static function assertReason(string $reason): void { if ('' === trim($reason)) { throw DomainError::reasonRequired(); } } }