\WP_REST_Server::READABLE, 'callback' => [$this, 'list'], 'permission_callback' => [$this, 'canView'], 'args' => [ 'state' => ['type' => 'string', 'enum' => ['open', 'needs_review', 'closed', 'all'], 'default' => 'open'], 'order_id' => ['type' => 'integer', 'minimum' => 1], 'page' => ['type' => 'integer', 'minimum' => 1, 'default' => 1], 'per_page' => ['type' => 'integer', 'minimum' => 1, 'maximum' => 100, 'default' => 50], ], ], [ 'methods' => \WP_REST_Server::CREATABLE, 'callback' => [$this, 'create'], 'permission_callback' => [$this, 'canManage'], 'args' => [ 'order_id' => ['type' => 'integer', 'minimum' => 1, 'required' => true], 'order_item_id' => ['type' => 'integer', 'minimum' => 1, 'required' => true], 'units' => ['type' => 'array', 'items' => ['type' => 'integer', 'minimum' => 1], 'minItems' => 1, 'required' => true], 'reported_on' => ['type' => 'string', 'format' => 'date', 'required' => true], 'manifested_on' => ['type' => 'string', 'format' => 'date'], 'defect' => ['type' => 'string', 'required' => true, 'minLength' => 1, 'sanitize_callback' => 'sanitize_textarea_field'], ], ], ]); register_rest_route(self::NAMESPACE, '/claims/(?P\d+)', [ 'methods' => \WP_REST_Server::READABLE, 'callback' => [$this, 'get'], 'permission_callback' => [$this, 'canView'], ]); register_rest_route(self::NAMESPACE, '/claims/(?P\d+)/actions', [ 'methods' => \WP_REST_Server::CREATABLE, 'callback' => [$this, 'claimAction'], 'permission_callback' => [$this, 'canManage'], 'args' => [ 'type' => ['type' => 'string', 'enum' => self::CLAIM_ACTIONS, 'required' => true], 'expected_version' => ['type' => 'integer', 'minimum' => 1, 'required' => true], 'date' => ['type' => 'string', 'format' => 'date'], 'channel' => ['type' => 'string', 'enum' => array_map(static fn (InformativaChannel $c): string => $c->value, InformativaChannel::cases())], 'text_version' => ['type' => 'string', 'maxLength' => 64, 'sanitize_callback' => 'sanitize_text_field'], 'remedy' => ['type' => 'string', 'enum' => array_map(static fn (Remedy $r): string => $r->value, Remedy::cases())], 'outcome' => ['type' => 'string', 'enum' => array_map(static fn (Outcome $o): string => $o->value, Outcome::cases())], 'refund_id' => ['type' => 'integer', 'minimum' => 1], 'defect_not_minor' => ['type' => 'boolean', 'default' => false], 'refurbished' => ['type' => 'boolean', 'default' => false], 'reason' => ['type' => 'string', 'sanitize_callback' => 'sanitize_textarea_field'], 'external_ref' => ['type' => 'string', 'maxLength' => 191, 'sanitize_callback' => 'sanitize_text_field'], 'new_end' => ['type' => 'string', 'format' => 'date'], 'goods_kept' => ['type' => 'boolean', 'default' => false], 'confirm_other_line' => ['type' => 'boolean', 'default' => false], 'text' => ['type' => 'string', 'sanitize_callback' => 'sanitize_textarea_field'], // Reconcile: the fingerprint of the order facts the screen showed. 'seen_facts' => ['type' => 'string', 'maxLength' => 64, 'sanitize_callback' => 'sanitize_text_field'], ], ]); register_rest_route(self::NAMESPACE, '/units/(?P\d+)/actions', [ 'methods' => \WP_REST_Server::CREATABLE, 'callback' => [$this, 'unitAction'], 'permission_callback' => [$this, 'canManage'], 'args' => [ 'type' => ['type' => 'string', 'enum' => self::UNIT_ACTIONS, 'required' => true], 'expected_version' => ['type' => 'integer', 'minimum' => 1, 'required' => true], 'date' => ['type' => ['string', 'null'], 'format' => 'date'], 'consumer' => ['type' => 'string', 'enum' => array_map(static fn (ConsumerStatus $c): string => $c->value, ConsumerStatus::cases())], 'months' => ['type' => 'integer', 'minimum' => LegalRules::MIN_USED_GOODS_MONTHS, 'maximum' => LegalRules::GUARANTEE_MONTHS], 'reason' => ['type' => 'string', 'required' => true, 'sanitize_callback' => 'sanitize_textarea_field'], ], ]); // An order as the warranty sees it: lines, units and their dates, claims. register_rest_route(self::NAMESPACE, '/orders/(?P\d+)', [ 'methods' => \WP_REST_Server::READABLE, 'callback' => [$this, 'order'], 'permission_callback' => [$this, 'canView'], ]); } public function canView(): bool { return current_user_can(Plugin::CAP_VIEW); } public function canManage(): bool { return current_user_can(Plugin::CAP_MANAGE); } // ------------------------------------------------------------------ // Reads // ------------------------------------------------------------------ public function list(\WP_REST_Request $request): \WP_REST_Response { $state = (string) $request->get_param('state'); $result = $this->claims->search([ 'state' => 'all' === $state ? '' : $state, 'order_id' => (int) $request->get_param('order_id'), 'page' => (int) $request->get_param('page'), 'per_page' => (int) $request->get_param('per_page'), ]); $response = new \WP_REST_Response([ 'items' => array_map(fn (Claim $c): array => $this->presentClaim($c), $result['items']), 'total' => $result['total'], 'counts' => $this->claims->counts(), ]); $response->header('X-WP-Total', (string) $result['total']); return $response; } public function get(\WP_REST_Request $request): \WP_REST_Response|\WP_Error { $claim = $this->claims->get((int) $request['id']); if (null === $claim) { return self::error(DomainError::notFound('Claim')); } return new \WP_REST_Response($this->detail($claim)); } public function order(\WP_REST_Request $request): \WP_REST_Response|\WP_Error { $order = $this->orders->order((int) $request['id']); if (null === $order) { return new \WP_Error('abcreate_wd_order_not_found', __('Order not found.', 'abcreate-warranty-desk'), ['status' => 404]); } $lines = []; foreach ($order->get_items() as $item) { if (!$item instanceof \WC_Order_Item_Product) { continue; } $tracked = $this->service->unitsOf((int) $item->get_id()); $facts = $this->orders->lineFacts($order, $item); $units = array_map(fn (CoveredUnit $u): array => $this->presentUnit($u), $tracked); // Lines nobody looked at yet: the dates as they would be, nothing written. if (null !== $facts) { for ($index = count($tracked) + 1; $index <= $facts->quantity; $index++) { $preview = CoveredUnit::track($facts->orderId, $facts->orderItemId, $index, $facts->productId, $facts->contractDate, $facts->deliveredOn, $facts->deliverySource, $facts->guaranteeMonths, $facts->consumer, 'preview', new \DateTimeImmutable()); $units[] = $this->presentUnit($preview); } } $product = $item->get_product(); $lines[] = [ 'order_item_id' => (int) $item->get_id(), 'name' => (string) $item->get_name(), 'sku' => $product instanceof \WC_Product ? (string) $product->get_sku() : '', 'qty' => (int) $item->get_quantity(), 'qty_refunded' => null !== $facts ? $facts->refundedQuantity : 0, 'units' => $units, ]; } return new \WP_REST_Response([ 'order' => $this->orderInfo((int) $order->get_id()), 'eligible' => $this->orders->isEligible($order), 'status' => (string) $order->get_status(), 'business' => $this->orders->isBusinessOrder($order), 'lines' => $lines, 'claims' => array_map(fn (Claim $c): array => $this->presentClaim($c), $this->claims->findByOrder((int) $order->get_id())), ]); } // ------------------------------------------------------------------ // Writes // ------------------------------------------------------------------ public function create(\WP_REST_Request $request): \WP_REST_Response|\WP_Error { return $this->write($request, function (Operation $op) use ($request): Claim { $order = $this->orders->order((int) $request['order_id']); $item = null !== $order ? $this->orders->item($order, (int) $request['order_item_id']) : null; if (null === $order || null === $item) { throw new DomainError('abcreate_wd_line_not_found', 'Order line not found.', 404); } if (!$this->orders->isEligible($order)) { throw new DomainError('abcreate_wd_order_not_eligible', 'Claims can be opened on paid orders only.', 409); } $line = $this->orders->lineFacts($order, $item) ?? throw new DomainError('abcreate_wd_line_not_found', 'Order line not found.', 404); return $this->service->openClaim($line, array_map('intval', (array) $request['units']), self::date($request['reported_on']), (string) $request['defect'], $op, empty($request['manifested_on']) ? null : self::date($request['manifested_on'])); }, 201); } public function claimAction(\WP_REST_Request $request): \WP_REST_Response|\WP_Error { $type = (string) $request['type']; if ('send_informativa' === $type) { return $this->sendInformativa($request); } return $this->write($request, function (Operation $op) use ($request, $type): Claim { $id = (int) $request['id']; $version = (int) $request['expected_version']; $reason = (string) ($request['reason'] ?? ''); $s = $this->service; // A withdrawal is the one closing that needs no goods: everything else // that closes on the goods, and a reconcile (which accepts the order // as it is now), reads WooCommerce again first. $isWithdrawal = 'close_without_remedy' === $type && Outcome::Withdrawn->value === (string) $request['outcome']; $seenFacts = trim((string) ($request['seen_facts'] ?? '')); if ('reconcile' === $type && '' === $seenFacts) { throw DomainError::invalidInput('Reload the claim: a reconcile needs the order as the screen showed it.'); } if ((in_array($type, self::FINAL_REMEDIES, true) || 'reconcile' === $type) && !$isWithdrawal && $this->hooks->reviewIfOrderChanged($id)) { throw new DomainError('abcreate_wd_order_changed', 'The order changed in WooCommerce: the claim went to review.', 409); } // What is accepted is what the operator saw: if the order moved since // the screen was loaded (even within a review already open), reload. $acceptedFacts = null; if ('reconcile' === $type) { $acceptedFacts = $this->hooks->orderFacts($this->claims->get($id) ?? throw DomainError::notFound('Claim')); if (!hash_equals(WooHooks::factsToken($acceptedFacts), $seenFacts)) { throw new DomainError('abcreate_wd_facts_changed', 'The order changed since the claim was loaded.', 409); } } return match ($type) { 'inform' => $this->recordInformativa($id, $version, $request, $op), 'set_manifested_on' => $s->setManifestedOn($id, $version, self::date($request['date']), $reason, $op), 'choose' => $s->choose($id, $version, Remedy::from((string) $request['remedy']), $op), 'request_refurbished' => $s->requestRefurbished($id, $version, $reason, $op), 'receive_goods' => $s->receiveGoods($id, $version, self::date($request['date']), self::text($request['external_ref']), $op), 'lend_loaner' => $s->lendLoaner($id, $version, self::date($request['date']), self::text($request['external_ref']), $op), 'return_loaner' => $s->returnLoaner($id, $version, self::date($request['date']), $op), 'refuse_remedy' => $s->refuseRemedy($id, $version, $reason, $op), 'complete_repair' => $s->completeRepair($id, $version, self::date($request['date']), $reason, $op), 'complete_replacement' => $s->completeReplacement($id, $version, self::date($request['date']), (bool) $request['refurbished'], $reason, $op, empty($request['new_end']) ? null : self::date($request['new_end'])), 'close_with_refund' => $s->closeWithRefund($id, $version, Outcome::from((string) $request['outcome']), $this->refundOf($id, (int) $request['refund_id'], (bool) $request['confirm_other_line']), (bool) $request['defect_not_minor'], self::date($request['date']), $reason, $op), 'close_without_remedy' => $s->closeWithoutRemedy($id, $version, Outcome::from((string) $request['outcome']), self::date($request['date']), $reason, $op), 'reconcile' => $s->reconcile($id, $version, $this->lineOf($id), $reason, $op, (bool) $request['goods_kept'], $acceptedFacts), 'report_recurrence' => $s->reportRecurrence($id, $version, $this->lineOf($id), $reason, $op), 'reopen_by_mistake' => $s->reopenClosedByMistake($id, $version, $this->lineOf($id), $reason, $op), default => throw DomainError::invalidInput('Unknown action.'), }; }); } public function unitAction(\WP_REST_Request $request): \WP_REST_Response|\WP_Error { $key = $this->key($request); if ($key instanceof \WP_Error) { return $key; } try { $op = new Operation(get_current_user_id(), $key, $this->requestHash($request)); $id = (int) $request['id']; $version = (int) $request['expected_version']; $reason = (string) $request['reason']; $unit = match ((string) $request['type']) { 'set_delivery' => $this->service->setDelivery($id, $version, self::date($request['date']), $reason, $op), 'set_consumer' => $this->service->setConsumer($id, $version, ConsumerStatus::from((string) $request['consumer']), $reason, $op), 'set_guarantee_end' => $this->service->setGuaranteeEnd($id, $version, empty($request['date']) ? null : self::date($request['date']), $reason, $op), 'set_guarantee_months' => $this->service->setGuaranteeMonths($id, $version, (int) $request['months'], $reason, $op), 'set_contract_date' => $this->service->setContractDate($id, $version, self::date($request['date']), $reason, $op), default => throw DomainError::invalidInput('Unknown action.'), }; } catch (DomainError $e) { return self::error($e); } catch (\ValueError $e) { return self::error(DomainError::invalidInput('Invalid value.')); } return new \WP_REST_Response($this->presentUnit($unit)); } /** * Sends the informativa email and records it (rule 3), never twice for * one request (G13): * 1. one transaction stores the Idempotency-Key and puts the claim in * review as "informativa uncertain"; only the request that made this * reservation goes on, so a retry, or a second request racing with the * same key, sends nothing; * 2. the email is handed to the mail system; * 3. a second transaction records the informativa with the full text, * which settles that doubt. If the mail system refused the email, or * the record fails, the claim stays in review and the operator checks * with the customer. */ private function sendInformativa(\WP_REST_Request $request): \WP_REST_Response|\WP_Error { $key = $this->key($request); if ($key instanceof \WP_Error) { return $key; } $id = (int) $request['id']; $version = (int) $request['expected_version']; try { $op = new Operation(get_current_user_id(), $key, $this->requestHash($request)); $claim = $this->claims->get($id) ?? throw DomainError::notFound('Claim'); $mail = $this->mailer->compose($claim, $this->unitsOf($claim)); if (!$this->service->reserveInformativaSend($id, $version, $op)) { // Same request again (a retry after a timeout): nothing is sent, the claim as it is. return new \WP_REST_Response($this->detail($this->claims->get($id) ?? throw DomainError::notFound('Claim'))); } $claim = $this->claims->get($id) ?? throw DomainError::notFound('Claim'); try { $sent = $this->mailer->send($claim, $mail); } catch (\Throwable $e) { $sent = false; } if (!$sent) { throw new DomainError('abcreate_wd_informativa_uncertain', 'The email may not have been sent.', 502); } $today = LegalDate::fromInstant(new \DateTimeImmutable(), wp_timezone()); try { $claim = $this->service->inform($id, $claim->version(), $today, InformativaChannel::Email, $mail['version'], new Operation(get_current_user_id(), $key . ':sent', $op->requestHash), [ 'text' => InformativaMailer::fullText($mail), 'to' => $mail['to'], 'locale' => $mail['locale'], ]); } catch (DomainError $e) { throw new DomainError('abcreate_wd_informativa_not_recorded', 'The email was sent but could not be recorded.', 409); } } catch (DomainError $e) { return self::error($e); } return new \WP_REST_Response($this->detail($claim)); } /** * An informativa given by the operator (phone, shop, letter, an email * sent by hand). What was said is kept in the history: the text the * operator wrote, or the plugin's text when that version was used. */ private function recordInformativa(int $id, int $version, \WP_REST_Request $request, Operation $op): Claim { $claim = $this->claims->get($id) ?? throw DomainError::notFound('Claim'); $mail = $this->mailer->compose($claim, $this->unitsOf($claim)); $textVersion = (string) ($request['text_version'] ?: $mail['version']); $given = trim((string) ($request['text'] ?? '')); if ('' === $given && $textVersion === $mail['version']) { $given = InformativaMailer::fullText($mail); } return $this->service->inform($id, $version, self::date($request['date']), InformativaChannel::from((string) $request['channel']), $textVersion, $op, [ 'text' => $given, 'to' => '', 'locale' => '' !== $given && $textVersion === $mail['version'] ? $mail['locale'] : '', ]); } /** @return list */ private function unitsOf(Claim $claim): array { $units = []; foreach ($claim->unitIds() as $unitId) { $unit = $this->units->get($unitId); if (null !== $unit) { $units[] = $unit; } } return $units; } /** @param callable(Operation): Claim $command */ private function write(\WP_REST_Request $request, callable $command, int $status = 200): \WP_REST_Response|\WP_Error { $key = $this->key($request); if ($key instanceof \WP_Error) { return $key; } try { $claim = $command(new Operation(get_current_user_id(), $key, $this->requestHash($request))); } catch (DomainError $e) { return self::error($e); } catch (\ValueError $e) { return self::error(DomainError::invalidInput('Invalid value.')); } return new \WP_REST_Response($this->detail($claim), $status); } private function key(\WP_REST_Request $request): string|\WP_Error { $key = trim((string) $request->get_header('idempotency_key')); if ('' === $key || strlen($key) > 150) { return self::error(DomainError::idempotencyRequired()); } // Namespaced per user, so two operators can never collide. return 'u' . get_current_user_id() . ':' . $key; } private function requestHash(\WP_REST_Request $request): string { $params = $request->get_json_params() ?: $request->get_body_params(); $params = is_array($params) ? $params : []; ksort($params); return hash('sha256', $request->get_method() . ' ' . $request->get_route() . ' ' . wp_json_encode($params)); } /** The order line as WooCommerce sees it now (refunds, quantity). */ private function lineOf(int $claimId): \ABCreate\WarrantyDesk\Domain\LineFacts { $claim = $this->claims->get($claimId) ?? throw DomainError::notFound('Claim'); $order = $this->orders->order($claim->orderId()); $item = null !== $order ? $this->orders->item($order, $claim->orderItemId()) : null; $line = null !== $order && null !== $item ? $this->orders->lineFacts($order, $item) : null; return $line ?? throw new DomainError('abcreate_wd_line_not_found', 'Order line not found.', 404); } /** * Rule 9: the money moved through a native WooCommerce refund of this * very order. A refund that gave back quantity of other lines only needs * the operator's confirmation (with the reason they write anyway). */ private function refundOf(int $claimId, int $refundId, bool $confirmedOtherLine): int { $claim = $this->claims->get($claimId) ?? throw DomainError::notFound('Claim'); $refund = wc_get_order($refundId); if (!$refund instanceof \WC_Order_Refund || (int) $refund->get_parent_id() !== $claim->orderId()) { throw new DomainError('abcreate_wd_refund_not_found', 'Refund not found on this order.', 422); } $lines = $this->refundLineIds($refund); if ([] !== $lines && !in_array($claim->orderItemId(), $lines, true) && !$confirmedOtherLine) { throw new DomainError('abcreate_wd_refund_other_line', 'This refund is for other lines of the order.', 409); } return $refundId; } /** * The order lines a refund touched, by quantity or by amount. * * @return list */ private function refundLineIds(\WC_Order_Refund $refund): array { $lines = []; foreach ($refund->get_items() as $refundItem) { if (!$refundItem instanceof \WC_Order_Item_Product) { continue; } $itemId = (int) $refundItem->get_meta('_refunded_item_id', true); if ($itemId > 0 && (0.0 !== abs((float) $refundItem->get_quantity()) || 0.0 !== abs((float) $refundItem->get_total()))) { $lines[] = $itemId; } } return array_values(array_unique($lines)); } private static function date(mixed $value): LegalDate { return LegalDate::of((string) $value); } private static function text(mixed $value): ?string { $value = trim((string) $value); return '' === $value ? null : $value; } // ------------------------------------------------------------------ // Presentation // ------------------------------------------------------------------ /** @return array */ private function detail(Claim $claim): array { $data = $this->presentClaim($claim); $units = []; foreach ($claim->unitIds() as $unitId) { $unit = $this->units->get($unitId); if (null !== $unit) { $units[] = $this->presentUnit($unit); } } $data['units'] = $units; $data['history'] = array_map(static function (array $event): array { $user = null !== $event['actor_id'] ? get_userdata((int) $event['actor_id']) : false; $event['actor_name'] = $user ? (string) $user->display_name : ''; return $event; }, $this->claims->history((int) $claim->id(), $claim->unitIds())); $data['refunds'] = $this->refunds($claim); $data['order_now'] = $this->orderNow($claim); $data['informativa'] = $claim->informativaRequired() ? $this->mailer->compose($claim, $this->unitsOf($claim)) : null; return $data; } /** @return array */ public function presentClaim(Claim $claim): array { $row = $claim->toRow(); $today = LegalDate::fromInstant(new \DateTimeImmutable(), wp_timezone()); $end = $claim->closedOn() ?? $today; $days = (int) (new \DateTimeImmutable($claim->reportedOn()->toString()))->diff(new \DateTimeImmutable($end->toString()))->days; return [ 'id' => (int) $claim->id(), 'order_id' => $claim->orderId(), 'order_item_id' => $claim->orderItemId(), 'unit_ids' => $claim->unitIds(), 'reported_on' => $claim->reportedOn()->toString(), 'manifested_on' => $claim->manifestedOn()?->toString(), 'defect' => $claim->defect(), 'informativa_required' => $claim->informativaRequired(), 'state' => $claim->state()->value, 'review_reasons' => $claim->reviewReasons(), 'informed_on' => $claim->informedOn()?->toString(), 'informed_via' => $row['informed_via'], 'informativa_version' => $row['informativa_version'], 'choice' => $claim->choice()?->value, 'refurbished_requested' => $claim->isRefurbishedRequested(), 'remedy_refused' => $claim->isRemedyRefused(), 'goods_received_on' => $row['goods_received_on'], 'loaner_out' => $claim->isLoanerOut(), 'outcome' => $claim->outcome()?->value, 'closed_on' => $claim->closedOn()?->toString(), 'refund_ids' => $claim->refundIds(), 'version' => $claim->version(), 'days_open' => $days, 'target_days' => Options::targetDays(), 'overdue' => ClaimState::Closed !== $claim->state() && $days > Options::targetDays(), 'product_name' => $this->productName($claim), ] + $this->orderInfo($claim->orderId()); } /** @return array */ public function presentUnit(CoveredUnit $unit): array { $row = $unit->toRow(); $dates = $unit->dates(); $today = LegalDate::fromInstant(new \DateTimeImmutable(), wp_timezone()); return [ 'id' => $unit->id(), 'unit_index' => $unit->unitIndex(), 'tracked' => null !== $unit->id(), 'contract_date' => $unit->contractDate()->toString(), 'new_rules' => $unit->newRulesApply(), 'delivered_on' => $unit->deliveredOn()?->toString(), 'delivery_source' => $unit->deliverySource()->value, 'guarantee_months' => (int) $row['guarantee_months'], 'consumer' => $unit->consumer()->value, 'open_claim_id' => $unit->openClaimId(), 'repair_count' => $unit->repairCount(), 'extended' => $unit->isExtended(), 'extended_by_claim_id' => $unit->extendedByClaimId(), 'ambiguous_repair_claims' => $unit->ambiguousRepairClaims(), 'terminated_by_claim_id' => $unit->terminatedByClaimId(), 'operator_end_on' => $unit->operatorEndOn()?->toString(), 'version' => $unit->version(), 'dates' => $dates?->toArray(), 'in_guarantee_today' => null !== $dates ? !$today->isAfter($dates->guaranteeEnd) : null, ]; } /** @return array{order_number:string, customer_name:string, customer_email:string, order_edit_url:string} */ private function orderInfo(int $orderId): array { static $cache = []; if (!isset($cache[$orderId])) { $order = $this->orders->order($orderId); $cache[$orderId] = [ 'order_number' => null !== $order ? (string) $order->get_order_number() : (string) $orderId, 'customer_name' => null !== $order ? $this->orders->customerName($order) : '', 'customer_email' => null !== $order ? (string) $order->get_billing_email() : '', 'order_edit_url' => class_exists(OrderUtil::class) ? OrderUtil::get_order_admin_edit_url($orderId) : admin_url('post.php?post=' . $orderId . '&action=edit'), ]; } return $cache[$orderId]; } private function productName(Claim $claim): string { $order = $this->orders->order($claim->orderId()); $item = null !== $order ? $this->orders->item($order, $claim->orderItemId()) : null; return null !== $item ? (string) $item->get_name() : ''; } /** * The order as WooCommerce has it now, shown next to a review: reconciling * accepts exactly this, identified by its token. * * @return array{token:string, status:string, product:string, quantity:int, line_removed:bool, order_deleted:bool} */ private function orderNow(Claim $claim): array { $order = $this->orders->order($claim->orderId()); $item = null !== $order ? $this->orders->item($order, $claim->orderItemId()) : null; $product = null !== $item ? $item->get_product() : null; return [ 'token' => WooHooks::factsToken($this->hooks->orderFacts($claim)), 'status' => null !== $order ? (string) wc_get_order_status_name($order->get_status()) : '', // The product the line points to now (the line's own name may be older). 'product' => $product instanceof \WC_Product ? (string) $product->get_name() : (null !== $item ? (string) $item->get_name() : ''), 'quantity' => null !== $item ? (int) $item->get_quantity() : 0, 'line_removed' => null !== $order && null === $item, 'order_deleted' => null === $order, ]; } /** * The order's refunds, with the lines each one touched, so the operator * links the right one. * * @return list, this_line:bool, other_lines:bool}> */ private function refunds(Claim $claim): array { $order = $this->orders->order($claim->orderId()); if (null === $order) { return []; } $out = []; foreach ($order->get_refunds() as $refund) { $ids = $this->refundLineIds($refund); $names = []; foreach ($ids as $itemId) { $item = $this->orders->item($order, $itemId); $names[] = null !== $item ? (string) $item->get_name() : '#' . $itemId; } $out[] = [ 'id' => (int) $refund->get_id(), 'amount' => html_entity_decode(wp_strip_all_tags(wc_price((float) $refund->get_amount(), ['currency' => $order->get_currency()]))), 'date' => $refund->get_date_created() ? $refund->get_date_created()->date_i18n((string) get_option('date_format')) : '', 'reason' => (string) $refund->get_reason(), 'lines' => $names, 'this_line' => in_array($claim->orderItemId(), $ids, true), 'other_lines' => [] !== array_diff($ids, [$claim->orderItemId()]), ]; } return $out; } // ------------------------------------------------------------------ // Errors, translated by code // ------------------------------------------------------------------ public static function error(DomainError $e): \WP_Error { return new \WP_Error($e->errorCode, self::message($e), ['status' => $e->httpStatus] + $e->params); } /** * Domain errors carry English text for logs; the operator gets a message * in the admin language, chosen by code (and by the English text for the * generic invalid-input and invalid-transition codes). */ public static function message(DomainError $e): string { switch ($e->errorCode) { case 'abcreate_wd_informativa_required': return __('Inform the consumer first (choice between repair and replacement, 12-month extension after a repair), then record the remedy.', 'abcreate-warranty-desk'); case 'abcreate_wd_refurbished_request_required': return __('A refurbished replacement needs the consumer\'s explicit request: record it first.', 'abcreate-warranty-desk'); case 'abcreate_wd_minor_defect': return __('The contract cannot be terminated for a minor defect. Confirm the defect is not minor, or record a price reduction.', 'abcreate-warranty-desk'); case 'abcreate_wd_unit_busy': return __('This unit is already in another open claim.', 'abcreate-warranty-desk'); case 'abcreate_wd_units_refunded': $claimable = (int) ($e->params['claimable'] ?? 0); /* translators: %d: number of units of the order line that can still be claimed */ return sprintf(_n('Only %d unit of this line can be claimed: the others were refunded, returned or are in other claims.', 'Only %d units of this line can be claimed: the others were refunded, returned or are in other claims.', $claimable, 'abcreate-warranty-desk'), $claimable); case 'abcreate_wd_delivery_not_confirmed': return __('Confirm the delivery date first.', 'abcreate-warranty-desk'); case 'abcreate_wd_still_in_warranty': return __('The defect appeared before the end of the legal guarantee: the claim cannot be closed as out of warranty.', 'abcreate-warranty-desk'); case 'abcreate_wd_manifestation_unknown': return __('Record when the defect appeared first: the guarantee looks at that day, not at the day of the report.', 'abcreate-warranty-desk'); case 'abcreate_wd_order_changed': return __('The order changed in WooCommerce meanwhile (refund, cancellation or edited lines): the claim was moved to review. Check it, reconcile it, then record the remedy.', 'abcreate-warranty-desk'); case 'abcreate_wd_facts_changed': return __('The order changed in WooCommerce while you were checking this claim. The latest data has been loaded: check it again before reconciling.', 'abcreate-warranty-desk'); case 'abcreate_wd_refund_other_line': return __('This refund is for other lines of the order. Check that it is the right one and confirm.', 'abcreate-warranty-desk'); case 'abcreate_wd_consumer_not_confirmed': return __('Confirm whether the buyer is a consumer first.', 'abcreate-warranty-desk'); case 'abcreate_wd_buyer_is_consumer': return __('Confirm that the buyer is not a consumer first.', 'abcreate-warranty-desk'); case 'abcreate_wd_remedy_refused': return __('Repair and replacement were refused: record a new choice, or close with a price reduction or termination.', 'abcreate-warranty-desk'); case 'abcreate_wd_version_conflict': return __('Someone changed this record while you had it open. The latest data has been loaded: check it and try again.', 'abcreate-warranty-desk'); case 'abcreate_wd_idempotency_required': return __('A valid Idempotency-Key header is required.', 'abcreate-warranty-desk'); case 'abcreate_wd_idempotency_mismatch': return __('This request was already sent with different data. Reload the page and try again.', 'abcreate-warranty-desk'); case 'abcreate_wd_duplicate_unit': return __('The order line was being tracked at the same moment. Try again.', 'abcreate-warranty-desk'); case 'abcreate_wd_reason_required': return __('Please write a reason.', 'abcreate-warranty-desk'); case 'abcreate_wd_invalid_date': return __('The date is not valid.', 'abcreate-warranty-desk'); case 'abcreate_wd_not_found': return __('Not found.', 'abcreate-warranty-desk'); case 'abcreate_wd_line_not_found': return __('Order line not found.', 'abcreate-warranty-desk'); case 'abcreate_wd_order_not_eligible': return __('Claims can be opened on paid orders only (processing, on hold, completed or refunded).', 'abcreate-warranty-desk'); case 'abcreate_wd_refund_not_found': return __('Choose a refund of this order, made in WooCommerce.', 'abcreate-warranty-desk'); case 'abcreate_wd_informativa_uncertain': return __('The mail system did not accept the email, so it may not have reached the customer. The claim was moved to review: check with the customer, reconcile, then record the informativa by hand or send it again. Nothing is sent again automatically.', 'abcreate-warranty-desk'); case 'abcreate_wd_informativa_not_recorded': return __('The email was sent, but the claim changed meanwhile and the informativa could not be recorded. The claim is in review: record the informativa by hand.', 'abcreate-warranty-desk'); case 'abcreate_wd_invalid_input': case 'abcreate_wd_invalid_transition': return self::detailMessage($e->getMessage()); default: return __('The request could not be completed.', 'abcreate-warranty-desk'); } } private static function detailMessage(string $english): string { return match ($english) { 'A claim cannot close before it was reported.' => __('A claim cannot close before the defect was reported.', 'abcreate-warranty-desk'), 'Choose at least one unit.', 'A claim needs at least one unit.' => __('Choose at least one unit.', 'abcreate-warranty-desk'), 'Choose existing units of this order line.' => __('Choose existing units of this order line.', 'abcreate-warranty-desk'), 'A defect cannot be reported before the order.' => __('A defect cannot be reported before the order date.', 'abcreate-warranty-desk'), 'The date cannot be in the future.' => __('The date cannot be in the future.', 'abcreate-warranty-desk'), 'The delivery cannot come before the order.' => __('The delivery cannot come before the order date.', 'abcreate-warranty-desk'), 'The informativa cannot come before the defect was reported.' => __('The informativa cannot come before the defect was reported.', 'abcreate-warranty-desk'), 'The informativa needs the version of the text that was given.' => __('Say which text of the informativa was given.', 'abcreate-warranty-desk'), 'The new end must come after the legal end of the guarantee.' => __('The new end must come after the legal end of the guarantee: the shop can lengthen it, never shorten it.', 'abcreate-warranty-desk'), 'The remedy cannot come before the consumer was informed.' => __('The remedy cannot come before the day the consumer was informed.', 'abcreate-warranty-desk'), 'Link the WooCommerce refund that moved the money.' => __('Choose the WooCommerce refund that moved the money.', 'abcreate-warranty-desk'), 'Use a price reduction or a termination.', 'Use a rejection or a withdrawal.', 'Invalid value.', 'Unknown action.' => __('This outcome is not valid for this action.', 'abcreate-warranty-desk'), 'A replacement good is already on loan.' => __('A replacement good is already on loan.', 'abcreate-warranty-desk'), 'No replacement good is on loan.' => __('No replacement good is on loan.', 'abcreate-warranty-desk'), 'Only claims in review can be reconciled.' => __('Only claims in review can be reconciled.', 'abcreate-warranty-desk'), 'Only closed claims can be reopened.' => __('Only closed claims can be reopened.', 'abcreate-warranty-desk'), 'Record the consumer\'s choice of this remedy first.' => __('Record the consumer\'s choice of this remedy first.', 'abcreate-warranty-desk'), 'The contract was terminated: the good went back, nothing can recur.' => __('The contract was terminated and the good went back: there is nothing that can recur.', 'abcreate-warranty-desk'), 'The claim is in review: reconcile it first.' => __('The claim is in review: check the reasons and reconcile it first.', 'abcreate-warranty-desk'), 'The claim is closed: reopen it first.' => __('The claim is closed: reopen it first.', 'abcreate-warranty-desk'), 'The claim is not open.' => __('The claim is not open: check it first.', 'abcreate-warranty-desk'), 'The consumer was already informed.' => __('The consumer was already informed.', 'abcreate-warranty-desk'), 'The informativa is not due for this claim.' => __('The informativa is not due for this claim: the buyer is not a consumer, the contract is older than 31/07/2026, or the defect appeared after the guarantee.', 'abcreate-warranty-desk'), 'The defect cannot appear after it was reported.' => __('The defect cannot appear after the day it was reported.', 'abcreate-warranty-desk'), 'The defect cannot appear before the order.' => __('The defect cannot appear before the order date.', 'abcreate-warranty-desk'), 'Reload the claim: a reconcile needs the order as the screen showed it.' => __('Reload the claim and try again: a reconcile needs the order as your screen showed it.', 'abcreate-warranty-desk'), default => __('The data is not valid for this action. Reload the page and try again.', 'abcreate-warranty-desk'), }; } }