Skip to content
← Public packages

@kody/onetimefax

Head-start stub for sending faxes from Kody with the Onetime Fax developer API. Fork it and add your API key.

FollowFork

Files

send-fax.ts

146 lines · 4.6 KB · TypeScript
import {
	boolean,
	number,
	object,
	optional,
	parseSafe,
	string,
} from 'remix/data-schema'
import { assertFaxId, inputError, onetimefaxRequest } from './client.ts'
import { readFax, summarizeFax, type FaxStatusResult } from './fax-status.ts'

const sendFaxInput = object(
	{
		faxId: string(),
		confirm: optional(boolean()),
		maxPriceCents: optional(number()),
		dryRun: optional(boolean()),
	},
	{ unknownKeys: 'error' },
)

export type SendFaxPreview = {
	sent: false
	reason: string
	preview: Pick<
		FaxStatusResult,
		'faxId' | 'recipientNumber' | 'status' | 'pageCount' | 'quote' | 'filesReady'
	> & { files: Array<{ id: string; filename?: string; pageCount?: number | null }> }
}

export type SendFaxResult = {
	sent: true
	faxId: string
	recipientNumber: string | null
	status: string | null
	creditsConsumedCents: number | null
	creditBalanceCents: number | null
	/** True when Onetime Fax returned the original charge for a repeated send. */
	replayed: boolean
	response: unknown
}

/**
 * Send a prepared Onetime Fax draft. This spends prepaid credits.
 * Without `confirm: true` (or with `dryRun: true`) it only returns the
 * recipient, files, page count, and quote so a person can approve them.
 * With `confirm: true` it re-reads the draft, refuses if files are still
 * processing, the quote is missing, credits fall short, or the price is over
 * `maxPriceCents`, then sends. Repeating a send for the same fax returns the
 * original charge (`replayed: true`) without another debit.
 *
 * Wraps `GET /api/v1/faxes/{faxId}` and `POST /api/v1/faxes/{faxId}/send`
 * (https://www.onetimefax.com/developers/). Follow delivery with `./fax-status`.
 *
 * @param input.faxId - Draft id from `./prepare-fax`
 * @param input.confirm - Must be `true` to send and spend credits
 * @param input.maxPriceCents - Optional ceiling; refuses to send above it
 * @param input.dryRun - Preview only, even when `confirm` is true
 * @returns `{ sent: false, reason, preview }` or `{ sent: true, faxId, status, creditsConsumedCents, creditBalanceCents, replayed, response }`
 *
 * @example
 * import sendFax from 'kody:@kody/onetimefax/send-fax'
 *
 * const preview = await sendFax({ faxId: 'cmr4...' })
 * const sent = await sendFax({ faxId: 'cmr4...', confirm: true, maxPriceCents: 500 })
 */
export default async function sendFax(
	raw: unknown,
): Promise<SendFaxPreview | SendFaxResult> {
	const parsed = parseSafe(sendFaxInput, raw)
	if (!parsed.success) {
		throw inputError(
			'send-fax',
			'faxId, confirm, maxPriceCents, dryRun',
			parsed.issues,
		)
	}
	const input = parsed.value
	const faxId = assertFaxId(input.faxId)
	const summary = summarizeFax(await readFax(faxId))
	const preview: SendFaxPreview['preview'] = {
		faxId: summary.faxId,
		recipientNumber: summary.recipientNumber,
		status: summary.status,
		pageCount: summary.pageCount,
		quote: summary.quote,
		filesReady: summary.filesReady,
		files: (summary.fax.files ?? []).map((file) => ({
			id: file.id,
			filename: file.filename,
			pageCount: file.pageCount ?? null,
		})),
	}

	if (input.dryRun === true || input.confirm !== true) {
		return {
			sent: false,
			reason:
				input.dryRun === true
					? 'Dry run. Nothing was sent and no credits were spent.'
					: 'Not sent. Review the preview, then call again with confirm: true to spend credits.',
			preview,
		}
	}

	if (!summary.filesReady || !summary.quote) {
		throw new Error(
			`Fax ${faxId} is not ready: files are still processing or there is no quote yet. Poll ./fax-status and try again.`,
		)
	}
	if (summary.quote.shortfallCents > 0) {
		throw new Error(
			`Fax ${faxId} costs ${summary.quote.priceCents} cents but the balance is ${summary.quote.creditBalanceCents} cents (short ${summary.quote.shortfallCents}). Add credits in the Onetime Fax developer console.`,
		)
	}
	if (
		typeof input.maxPriceCents === 'number' &&
		summary.quote.priceCents > input.maxPriceCents
	) {
		throw new Error(
			`Fax ${faxId} costs ${summary.quote.priceCents} cents, above maxPriceCents ${input.maxPriceCents}. Not sent.`,
		)
	}

	const { data } = await onetimefaxRequest<{
		fax?: { id?: string; status?: string }
		creditsConsumedCents?: number
		creditBalanceCents?: number
		replayed?: boolean
	}>('POST', `/api/v1/faxes/${encodeURIComponent(faxId)}/send`)

	return {
		sent: true,
		faxId,
		recipientNumber: summary.recipientNumber,
		status: data.fax?.status ?? null,
		creditsConsumedCents:
			typeof data.creditsConsumedCents === 'number'
				? data.creditsConsumedCents
				: null,
		creditBalanceCents:
			typeof data.creditBalanceCents === 'number' ? data.creditBalanceCents : null,
		replayed: data.replayed === true,
		response: data,
	}
}