import apiFetch from '@wordpress/api-fetch'; import type { Claim, ClaimListResponse, OrderView, StateFilter, Unit, } from './types'; const ns = () => `/${ window.abcreateWd.namespace }`; export function listClaims( params: { state: StateFilter; page: number; perPage: number; orderId?: number; } ) { const query = new URLSearchParams( { state: params.state, page: String( params.page ), per_page: String( params.perPage ), } ); if ( params.orderId ) { query.set( 'order_id', String( params.orderId ) ); } return apiFetch< ClaimListResponse >( { path: `${ ns() }/claims?${ query.toString() }`, } ); } export function getClaim( id: number ) { return apiFetch< Claim >( { path: `${ ns() }/claims/${ id }` } ); } export function getOrder( id: number ) { return apiFetch< OrderView >( { path: `${ ns() }/orders/${ id }` } ); } /** * The idempotency key belongs to one user intention (one form submission): * a retry of the same submission reuses it, a new submission gets a new one. * @param body * @param body.order_id * @param body.order_item_id * @param body.units * @param body.reported_on * @param body.defect * @param idempotencyKey */ export function createClaim( body: { order_id: number; order_item_id: number; units: number[]; reported_on: string; defect: string; }, idempotencyKey: string ) { return apiFetch< Claim >( { path: `${ ns() }/claims`, method: 'POST', headers: { 'Idempotency-Key': idempotencyKey }, data: body, } ); } export function claimAction( id: number, body: Record< string, unknown > & { type: string; expected_version: number; }, idempotencyKey: string ) { return apiFetch< Claim >( { path: `${ ns() }/claims/${ id }/actions`, method: 'POST', headers: { 'Idempotency-Key': idempotencyKey }, data: body, } ); } export function unitAction( id: number, body: Record< string, unknown > & { type: string; expected_version: number; }, idempotencyKey: string ) { return apiFetch< Unit >( { path: `${ ns() }/units/${ id }/actions`, method: 'POST', headers: { 'Idempotency-Key': idempotencyKey }, data: body, } ); } /** * Whether the server answered. apiFetch also gives a code when it did not * (network down, gateway timeout page): then the same request may still be * running, and a retry must reuse the same Idempotency-Key. * @param err */ export function serverAnswered( err: { code?: string; data?: { status?: number } } | undefined ): boolean { return ( !! err?.code && typeof err.data?.status === 'number' && ! [ 'fetch_error', 'offline_error', 'invalid_json' ].includes( err.code ) ); } export function newIdempotencyKey(): string { if ( typeof crypto !== 'undefined' && 'randomUUID' in crypto ) { return crypto.randomUUID(); } return `${ Date.now() }-${ Math.random().toString( 36 ).slice( 2 ) }`; }