Skip to content

A one-of-a-kind resume builder that keeps your privacy in mind. Completely secure, customizable, portable, open-source and free forever. Try it out today!

8.5 KB
Raw Blame
import type { RouterOutput } from "@/api/client";
import type { PreparedRequest } from "@reactive-resume/utils/deferred-request";
import type { QueryKey } from "@tanstack/react-query";
import { useLingui } from "@lingui/react/macro";
import { ORPCError } from "@orpc/client";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { useEffect, useLayoutEffect, useRef, useState } from "react";
import { AppState } from "react-native";
import { withUndo } from "./undo";
import { client, orpc, prepareRpc } from "@/api/client";
import { getAccountScope, getServer, useSession } from "@/auth/session";
import { useProfile } from "@/features/settings/queries";
import { showToast } from "@/ui";

export type Career = RouterOutput["career"];
export type Fact = Career["facts"][number];
export type Story = Career["stories"][number];
export type Schedule = Career["schedules"][number];
export type SavedItem = Career["savedItems"][number];

export function useCareerQueries() {
	const session = useSession();
	const options = { enabled: session.status === "signed-in", retry: false };
	const facts = useQuery({
		...orpc.career.facts.queryOptions({ input: { applicationId: null, all: true } }),
		...options,
		queryKey: [...orpc.career.facts.key(), session.server, "all"],
	});
	const stories = useQuery({
		...orpc.career.stories.queryOptions({ input: { applicationId: null } }),
		...options,
		queryKey: [...orpc.career.stories.key(), session.server, "shared"],
	});
	const profile = useQuery({
		...orpc.career.profile.queryOptions(),
		...options,
		queryKey: [...orpc.career.profile.key(), session.server],
	});
	return { facts, stories, profile };
}

/** Roles discovery found, shared by Today and the coach's starters. */
export function useOpportunities() {
	const session = useSession();
	return useQuery({
		...orpc.career.opportunities.queryOptions({ input: {} }),
		enabled: session.status === "signed-in",
		queryKey: [...orpc.career.opportunities.key(), session.server],
	});
}

export function useTodayQueries() {
	const session = useSession();
	const options = { enabled: session.status === "signed-in", retry: false };
	const notifications = useQuery({
		...orpc.career.notifications.queryOptions({ input: {} }),
		...options,
		queryKey: [...orpc.career.notifications.key(), session.server],
	});
	const opportunities = useOpportunities();
	const schedules = useQuery({
		...orpc.career.schedules.queryOptions({ input: {} }),
		...options,
		queryKey: [...orpc.career.schedules.key(), session.server],
	});
	const briefings = useQuery({
		...orpc.career.savedItems.queryOptions({ input: { kind: "briefing" } }),
		...options,
		queryKey: [...orpc.career.savedItems.key(), session.server, "briefing"],
	});
	return { notifications, opportunities, schedules, briefings };
}

export function useOffers() {
	const session = useSession();
	return useQuery({
		...orpc.career.savedItems.queryOptions({ input: { kind: "offer" } }),
		enabled: session.status === "signed-in",
		retry: false,
		queryKey: [...orpc.career.savedItems.key(), session.server, "offer"],
	});
}

export function useCareerTime() {
	const profile = useProfile();
	const { i18n } = useLingui();
	const timeZone = profile.data?.timezone ?? "UTC";
	const device = Intl.DateTimeFormat().resolvedOptions().timeZone || undefined;
	// When the account's timezone isn't this device's, times say which zone they're in ("16:56 UTC").
	const labelled = !!device && device !== timeZone;
	return {
		profile,
		timeZone,
		/** This device's timezone, when it differs from the account's. */
		deviceTimeZone: labelled ? device : undefined,
		locale: i18n.locale,
		when: (value: Date | string) =>
			new Intl.DateTimeFormat(i18n.locale, {
				timeZone,
				month: "short",
				day: "numeric",
				year: "numeric",
				hour: "numeric",
				minute: "2-digit",
				...(labelled ? { timeZoneName: "short" as const } : {}),
			}).format(new Date(value)),
		/** A whole day, such as an offer's start date. */
		date: (value: Date | string) =>
			new Intl.DateTimeFormat(i18n.locale, { timeZone, day: "numeric", month: "short", year: "numeric" }).format(
				new Date(value),
			),
	};
}

/** Saves the account's timezone, as Settings → Preferences does. */
export function useSaveTimezone() {
	const { t } = useLingui();
	const queryClient = useQueryClient();
	return useMutation({
		mutationKey: ["settings", "timezone"],
		mutationFn: async (value: string) => {
			const result = await client.auth.updateProfile({ timezone: value });
			if (!result.status) throw new Error("Timezone update rejected");
		},
		onSuccess: () => queryClient.invalidateQueries({ queryKey: orpc.auth.getProfile.key() }),
		onError: () => showToast({ message: t`Couldn't save the timezone. Try again.` }),
	});
}

export function useNow() {
	const [now, setNow] = useState(() => new Date());
	useEffect(() => {
		const timer = setInterval(() => setNow(new Date()), 60_000);
		const subscription = AppState.addEventListener("change", (state) => {
			if (state === "active") setNow(new Date());
		});
		return () => {
			clearInterval(timer);
			subscription.remove();
		};
	}, []);
	return now;
}

export function useCareerAction() {
	const { t } = useLingui();
	const queryClient = useQueryClient();
	const session = useSession();
	const [pending, setPending] = useState(false);
	const busy = useRef(false);
	const [error, setError] = useState<string>();
	const refresh = () =>
		Promise.all([
			queryClient.invalidateQueries({ queryKey: orpc.career.key() }),
			queryClient.invalidateQueries({ queryKey: orpc.applications.key() }),
			queryClient.invalidateQueries({ queryKey: orpc.documents.key() }),
		]);
	const run = async <T>(operation: () => Promise<T>, success?: (result: T) => void) => {
		if (busy.current || session.status !== "signed-in" || getServer() !== session.server) return;
		busy.current = true;
		setPending(true);
		setError(undefined);
		const server = session.server;
		try {
			const result = await operation();
			if (getServer() === server) success?.(result);
		} catch (error) {
			// This server's own reason (a change made elsewhere, a limit) says more than a generic retry.
			if (getServer() === server)
				setError(
					error instanceof ORPCError && error.message
						? error.message
						: t`Couldn't save that change. Check your connection and try again.`,
				);
		} finally {
			busy.current = false;
			setPending(false);
			void refresh();
		}
	};
	return { run, pending, error, refresh };
}

export function useUndoRows() {
	const { t } = useLingui();
	const queryClient = useQueryClient();
	const session = useSession();
	const [hidden, setHidden] = useState<string[]>([]);
	const accountScope = getAccountScope();
	const [hiddenScope, setHiddenScope] = useState(accountScope);
	if (hiddenScope !== accountScope) {
		setHiddenScope(accountScope);
		setHidden([]);
	}
	const pending = useRef(new Map<string, ReturnType<typeof withUndo>>());
	const active = useRef(session);
	useLayoutEffect(() => {
		active.current = session;
	});
	const action = useCareerAction();
	useEffect(() => {
		const operations = pending.current;
		return () => {
			for (const operation of operations.values()) {
				if (active.current.status === "signed-in") operation.flush();
				else operation.cancel();
			}
			operations.clear();
		};
	}, [session.server, accountScope]);
	const remove = (
		id: string,
		message: string,
		prepare: () => Promise<PreparedRequest<unknown>>,
		queryKey: QueryKey,
	) => {
		if (pending.current.has(id)) return;
		const server = session.server;
		const scope = getAccountScope();
		const current = () =>
			getAccountScope() === scope && getServer() === server && active.current.status === "signed-in";
		const reconcile = async () => {
			try {
				if (!current()) return;
				await queryClient.cancelQueries({ queryKey });
				if (!current()) return;
				await queryClient.invalidateQueries({ queryKey, refetchType: "all" }, { throwOnError: true });
				if (current()) {
					setHidden((rows) => rows.filter((value) => value !== id));
					void action.refresh();
				}
			} finally {
				pending.current.delete(id);
			}
		};
		const failed = () => {
			if (!current()) return;
			showToast({
				message: t`Couldn't save that change. Check your connection and try again.`,
				action: {
					label: t`Retry`,
					onPress: () => {
						void reconcile().catch(failed);
					},
				},
			});
		};
		const operation = withUndo({
			message,
			prepare,
			onReady: () => setHidden((rows) => [...rows, id]),
			restore: reconcile,
			failed,
			commit: (result) => result.then(reconcile),
		});
		pending.current.set(id, operation);
	};

	return { hidden, remove };
}

export { client, prepareRpc };