import {z} from 'zod' export type GetApiReturnsReturnIdOptions = {baseUrl?: string | undefined, Bearer?: string | undefined, fetch?: typeof fetch | undefined}; export const personNameSchema = z.object({given: z.string(), surname: z.string()}); export const phoneNumberSchema = z.string(); export const moneySchema = z.object({amount: z.string().optional(), currency: z.string().optional()}); export const productSchema = z.object({externalId: z.string().optional(), name: z.string()}); export const itemQuantitySchema = z.number().gt(0); export const weightSchema = z.object({kg: z.number().gte(0).optional()}); export const productVariantSchema = z.object({externalId: z.string().optional(), name: z.string(), sku: z.string().optional(), weight: weightSchema.optional()}); export const orderReadSchema = z.object({customer: z.object({emailAddress: z.string().optional(), name: personNameSchema, phoneNumber: phoneNumberSchema.optional()}), discounts: moneySchema, externalId: z.string().optional(), id: z.string(), items: z.array(z.object({externalId: z.string().optional(), fulfillmentLocationId: z.string().nullable(), id: z.string(), price: moneySchema, product: productSchema, quantity: itemQuantitySchema, variant: productVariantSchema})), lineItemsTotal: moneySchema, name: z.string(), shippingCost: moneySchema, taxes: moneySchema, total: moneySchema}); export const addressSchema = z.object({city: z.string(), country: z.string(), line1: z.string(), line2: z.string().optional(), postalCode: z.string(), state: z.string()}); export const exchangeProvisionSchema = z.enum(["instant", "deferred"]); export const returnShipmentSchema = z.object({carrier: z.string().optional(), status: z.enum(["unknown", "pre_transit", "in_transit", "out_for_delivery", "available_for_pickup", "cancelled", "delivered", "error", "failure", "return_to_sender", "expired"]).optional(), tracker: z.string().optional(), trackingUrl: z.string().optional(), postageLabel: z.string().optional(), formLabel: z.string().optional(), shipmentGroupId: z.string().optional(), itemIds: z.array(z.string()).optional(), externalLocationId: z.string().optional(), estimatedDeliveryDate: z.string().optional(), deliveredAt: z.string().optional()}); export const returnDropoffSchema = z.object({shipmentGroupId: z.string(), provider: z.string(), qrCode: z.string().optional(), qrCodeUrl: z.string().optional()}); export const returnStatusSchema = z.enum(["open", "in_transit", "delivered", "needs_review", "in_review", "complete", "rejected", "flagged", "pre_shipment", "deleted"]); export const returnTypeSchema = z.enum(["claim", "return", "warranty"]); export const returnReadSchema = z.object({compensationMethods: z.array(z.enum(["refund", "store_credit", "exchange"])).optional(), completeWithNoAction: z.boolean().optional(), createdAt: z.string(), destination: z.object({mailingAddress: addressSchema.optional(), phoneNumber: phoneNumberSchema.optional()}), exchange: z.object({itemCount: z.number().int().optional(), items: z.array(z.object({id: z.string(), originalPrice: z.object({amount: z.string().optional(), currency: z.string().optional()}).optional(), price: z.object({amount: z.string().optional(), currency: z.string().optional(), tax: z.string().optional()}).optional(), product: productSchema.optional(), quantity: itemQuantitySchema, variant: productVariantSchema})), order: z.object({externalId: z.string().optional()}).optional(), provision: exchangeProvisionSchema, totalTax: z.object({amount: z.string().optional(), currency: z.string().optional()}).optional()}).optional(), externalOrderIds: z.array(z.string()).optional(), externalReturnIds: z.array(z.object({provider: z.literal("shopify"), value: z.string()})).optional(), giftCards: z.array(z.object({amount: moneySchema, code: z.string(), externalId: z.string()})), id: z.string(), internalCreatedByName: z.string().optional(), items: z.array(z.object({customerComment: z.string().optional(), exchangeItem: z.object({product: z.object({externalId: z.string().optional(), name: z.string().optional()}).optional(), quantity: z.number().int().optional(), variant: z.object({externalId: z.string().optional(), name: z.string().optional()}).optional()}).optional(), grade: z.string().nullable().optional(), greenReturn: z.boolean().optional(), outcome: z.string().nullable().optional(), shipmentGroupIds: z.array(z.string()).optional(), id: z.string(), orderItem: z.object({id: z.string(), line_item_id: z.string().optional()}), externalReturnLineItemId: z.string().optional(), productId: z.string().optional(), quantity: z.number().int(), reason: z.string(), reasonCode: z.string().optional(), reasons: z.array(z.string()).optional(), reasonCodes: z.array(z.string()).optional(), productAdjustment: z.string().optional(), multipleChoiceQuestions: z.array(z.object({question: z.string(), answer: z.string()})).optional(), assessments: z.array(z.object({assignedUser: z.object({id: z.string(), name: z.string(), firstName: z.string(), lastName: z.string(), email: z.string()}), responses: z.array(z.discriminatedUnion("type", [z.object({type: z.literal("short_text"), value: z.string()}), z.object({type: z.literal("long_text"), value: z.string()}), z.object({type: z.literal("select"), value: z.array(z.string())}), z.object({type: z.literal("number"), value: z.number()}), z.object({type: z.literal("boolean"), value: z.boolean()}), z.object({type: z.literal("file_upload"), value: z.array(z.string())}), z.object({type: z.literal("date"), value: z.string()})]))})).optional(), refund: z.object({amount: moneySchema, type: z.string().optional()}).optional(), productValueNoTaxNoAdjustment: z.object({amount: moneySchema}).optional(), sku: z.string().optional(), upc: z.string().nullable().optional(), status: z.string().optional(), variantId: z.string().optional()})), notes: z.array(z.object({image: z.string().optional(), message: z.string()})).optional(), order: z.object({id: z.string(), name: z.string().optional()}), shipment: returnShipmentSchema.optional(), shipments: z.array(returnShipmentSchema).optional(), dropoffs: z.array(returnDropoffSchema).optional(), shopifyOrderIds: z.array(z.string()).optional(), source: z.object({emailAddress: z.string(), mailingAddress: addressSchema, name: personNameSchema, phoneNumber: phoneNumberSchema}), status: returnStatusSchema, tags: z.array(z.object({name: z.string(), source: z.string()})).optional(), totals: z.object({charge: z.object({amount: moneySchema}), exchange: z.object({amount: moneySchema}), refund: z.object({amount: moneySchema}), storeCredit: z.object({amount: moneySchema})}).optional(), type: returnTypeSchema.optional(), updatedAt: z.string()}); export const getApiReturnsReturnIdResponse = z.object({order: orderReadSchema, return: returnReadSchema}); export const validateResponse = async ( schema: { readonly '~standard': { readonly validate: (value: unknown) => ({ readonly value: Output; readonly issues?: undefined } | { readonly issues: ReadonlyArray<{ readonly message: string; readonly path?: ReadonlyArray | undefined }> }) | Promise<{ readonly value: Output; readonly issues?: undefined } | { readonly issues: ReadonlyArray<{ readonly message: string; readonly path?: ReadonlyArray | undefined }> }> } }, value: unknown ): Promise => { const result = await schema['~standard'].validate(value) if (result.issues !== undefined) { const detail = result.issues .map(({ message, path }) => path?.length ? `${path.map((segment) => String(typeof segment === 'object' ? segment.key : segment)).join('.')}: ${message}` : message ) .join('; ') throw new Error(`Response does not match the schema: ${detail}`, { cause: { issues: result.issues } }) } return result.value }; /** * Return * * GET /returns/{returnId} */ export const getApiReturnsReturnId = async (options?: GetApiReturnsReturnIdOptions) => { const {baseUrl = "https://api.getredo.com/v2.2", fetch: fetchFn = fetch, Bearer} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") if (Bearer !== undefined) headers.set('authorization', `Bearer ${Bearer}`) const url = `${baseUrl.replace(/\/+$/, '')}/returns/${encodeURIComponent(String(args.returnId))}${query.size > 0 ? `?${query}` : ''}` const res = await fetchFn(url, {method: "GET", headers}) if (!res.ok) throw new Error(`Request failed with status ${res.status}`, {cause: {status: res.status, body: await res.text()}}) return validateResponse(getApiReturnsReturnIdResponse, await res.json()) };