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!

fix(career): make offer version retries safe and preserve bonus precision

Amruth Pillai118513518004
diff --git a/apps/mobile/scripts/experience.test.mjs b/apps/mobile/scripts/experience.test.mjs
index b3bfc990f..c803f85f0 100644
--- a/apps/mobile/scripts/experience.test.mjs
+++ b/apps/mobile/scripts/experience.test.mjs
@@ -1353,7 +1353,10 @@ let savedOffers = [
{ createdAt: "2026-10-01T00:00:00Z", data: { kind: "offer", currency: "GBP" } },
];
let offerApplications = { data: [] };
+let loseOfferResponse = false;
+let offerFailures = 0;
const { OfferEntry, OfferForm } = load("features/career/offer-entry.tsx", {
+ "@reactive-resume/utils/string": load("../../../packages/utils/src/string.ts", { uuid: serverRequire("uuid") }),
"@/auth/session": { getAccountScope: () => offerScope },
"@reactive-resume/schema/career": careerSchema,
"@reactive-resume/schema/career-offer": offerParser,
@@ -1362,7 +1365,11 @@ const { OfferEntry, OfferForm } = load("features/career/offer-entry.tsx", {
useCareerAction: () => ({
pending: false,
run: async (work, success) => {
- success(await work());
+ try {
+ success(await work());
+ } catch {
+ offerFailures++;
+ }
},
}),
client: {
@@ -1373,6 +1380,10 @@ const { OfferEntry, OfferForm } = load("features/career/offer-entry.tsx", {
},
updateOffer: async (input) => {
calls.push(input);
+ if (loseOfferResponse) {
+ loseOfferResponse = false;
+ throw new Error("Response lost after commit");
+ }
return { id: "new-version", data: { kind: "offer", ...input.terms } };
},
},
@@ -1501,8 +1512,15 @@ const correctedView = () =>
assert.equal(control(correctedView(), "Bonus").value, "10%");
assert.equal(control(correctedView(), "Bonus").keyboardType, "default", "percentage entry needs a percent key");
control(correctedView(), "Bonus").onChangeText("12.5%");
+loseOfferResponse = true;
+control(correctedView(), "Save offer").onPress();
+await settle();
+assert.equal(offerFailures, 1);
+assert.equal(calls.length, 1, "lost response keeps the native form open without navigation");
control(correctedView(), "Save offer").onPress();
await settle();
+assert.deepEqual(calls[1], calls[0], "retry uses the same version receipt after a lost response");
+assert.match(calls[0].newId, /^[0-9a-f-]{36}$/);
assert.equal(calls[0].id, "original-offer");
assert.equal(calls[0].newVersion, true);
assert.equal(calls[0].terms.variable, null);
diff --git a/apps/mobile/src/features/career/offer-compare.ts b/apps/mobile/src/features/career/offer-compare.ts
index 38b91bad1..668287a2f 100644
--- a/apps/mobile/src/features/career/offer-compare.ts
+++ b/apps/mobile/src/features/career/offer-compare.ts
@@ -37,7 +37,7 @@ export const matchingPlace = (location: string, places: string[]) => {
export function formatBonus(locale: string, terms: OfferTerms) {
if (terms.variablePercent == null)
return terms.variable === null ? null : formatMoney(locale, terms.currency, terms.variable);
- const percent = new Intl.NumberFormat(locale, { style: "percent", maximumFractionDigits: 20 }).format(
+ const percent = new Intl.NumberFormat(locale, { style: "percent", maximumSignificantDigits: 21 }).format(
terms.variablePercent / 100,
);
const amount = bonusAmount(terms);
diff --git a/apps/mobile/src/features/career/offer-entry.tsx b/apps/mobile/src/features/career/offer-entry.tsx
index e58f585c0..e80f682cb 100644
--- a/apps/mobile/src/features/career/offer-entry.tsx
+++ b/apps/mobile/src/features/career/offer-entry.tsx
@@ -13,6 +13,7 @@ import {
parseOfferEntry,
previousOfferCurrency,
} from "@reactive-resume/schema/career-offer";
+import { pendingRequestId, settleRequestId } from "@reactive-resume/utils/string";
import { client, useCareerAction, useCareerQueries, useCareerTime, useOffers } from "./hooks";
import { formatMoney } from "./offer-compare";
import { EditorSheet, LoadState } from "./shared";
@@ -262,6 +263,16 @@ export function OfferForm({ application, offer: initialOffer, onClose, onSaved }
}
/>
);
+ const saveTerms = async () => {
+ if (!payload.success || !scope || getAccountScope() !== scope) throw new Error("Account changed");
+ if (!offer) return client.career.createOffer(payload.data, { context: { scope } });
+ const { applicationId: _applicationId, ...terms } = payload.data;
+ const input = { id: offer.id, terms, expected: offerTermsSchema.parse(offer.data), newVersion: true };
+ const key = JSON.stringify(["career:offer-version", scope, input]);
+ const result = await client.career.updateOffer({ ...input, newId: pendingRequestId(key) }, { context: { scope } });
+ settleRequestId(key);
+ return result;
+ };
return (
<EditorSheet
title={offer ? t`Edit offer terms` : t`Add offer`}
@@ -407,44 +418,30 @@ export function OfferForm({ application, offer: initialOffer, onClose, onSaved }
setSubmitted(true);
if (amountErrors.variable || amountErrors.learning) setMore(true);
if (payload.success)
- void action.run(
- () =>
- offer
- ? client.career.updateOffer(
- {
- id: offer.id,
- terms: (({ applicationId: _, ...terms }) => terms)(payload.data),
- expected: offerTermsSchema.parse(offer.data),
- newVersion: true,
- },
- { context: { scope } },
- )
- : client.career.createOffer(payload.data, { context: { scope } }),
- (result) => {
- if (getAccountScope() !== scope) return;
- if (offer) {
- if (result) router.setParams({ a: result.id, b: params.b, highlight: result.id });
- showToast({ message: t`New offer version saved` });
- onClose();
- return;
- }
- if (!application && result) router.setParams({ a: result.id, b: params.b, highlight: result.id });
- if (result?.data.kind === "offer") onSaved?.({ id: result.id, data: result.data });
- const row = applications.data?.find((item) => item.id === payload.data.applicationId);
- const target = application ?? row;
- const status = application?.status ?? row?.status;
- if (target && status && BEFORE_OFFER.includes(status))
- // An offer means the application is at Offer; Undo keeps the offer and leaves the stage.
- moveWithUndo({
- applications: [{ id: payload.data.applicationId }],
- lane: resolveLane(lanes.lanes, { status: "offer" }),
- supported: lanes.supported,
- message: t`Offer saved. ${target.company} moved to Offer.`,
- });
- else showToast({ message: t`Offer saved` });
+ void action.run(saveTerms, (result) => {
+ if (getAccountScope() !== scope) return;
+ if (offer) {
+ if (result) router.setParams({ a: result.id, b: params.b, highlight: result.id });
+ showToast({ message: t`New offer version saved` });
onClose();
- },
- );
+ return;
+ }
+ if (!application && result) router.setParams({ a: result.id, b: params.b, highlight: result.id });
+ if (result?.data.kind === "offer") onSaved?.({ id: result.id, data: result.data });
+ const row = applications.data?.find((item) => item.id === payload.data.applicationId);
+ const target = application ?? row;
+ const status = application?.status ?? row?.status;
+ if (target && status && BEFORE_OFFER.includes(status))
+ // An offer means the application is at Offer; Undo keeps the offer and leaves the stage.
+ moveWithUndo({
+ applications: [{ id: payload.data.applicationId }],
+ lane: resolveLane(lanes.lanes, { status: "offer" }),
+ supported: lanes.supported,
+ message: t`Offer saved. ${target.company} moved to Offer.`,
+ });
+ else showToast({ message: t`Offer saved` });
+ onClose();
+ });
}}
/>
</View>
diff --git a/apps/mobile/src/features/career/offers.tsx b/apps/mobile/src/features/career/offers.tsx
index c58fc0a76..5bbd24585 100644
--- a/apps/mobile/src/features/career/offers.tsx
+++ b/apps/mobile/src/features/career/offers.tsx
@@ -283,9 +283,7 @@ function OfferCard({ offer, highlight, other, profile, onEdit, onDelete }: Offer
];
const questions = [
data.base === null ? t`What is the base salary?` : null,
- data.variable === null && data.variablePercent == null && !data.variableConditions
- ? t`Is there a bonus, and what does it depend on?`
- : null,
+ data.variable === null && !data.variableConditions.trim() ? t`Is there a bonus, and what does it depend on?` : null,
!data.equity ? t`What equity is included, and on what terms?` : null,
data.officeDays === null ? t`How many office days are expected?` : null,
!data.startDate ? t`When would you start?` : null,
diff --git a/apps/web/src/features/career/offer-compare.test.ts b/apps/web/src/features/career/offer-compare.test.ts
index 345534ce8..fed2d6a71 100644
--- a/apps/web/src/features/career/offer-compare.test.ts
+++ b/apps/web/src/features/career/offer-compare.test.ts
@@ -1,6 +1,6 @@
import type { OfferTerms } from "@reactive-resume/schema/career";
import { describe, expect, it } from "vite-plus/test";
-import { meetsMinimum, moneyDifference } from "./offer-compare";
+import { formatBonus, meetsMinimum, moneyDifference } from "./offer-compare";
const offer = (patch: Partial<OfferTerms>): OfferTerms => ({
version: "written",
@@ -41,8 +41,18 @@ describe("money is only compared in the same currency and pay period", () => {
).toBeNull();
});
+ it("shows stored percentage precision rather than rounding a small rate to zero", () => {
+ i18n.load("en-US", {});
+ i18n.activate("en-US");
+ expect(formatBonus("en-US", offer({ base: null, variablePercent: 12.345 }))).toBe("12.345% of base");
+ expect(formatBonus("en-US", offer({ base: null, variablePercent: 1e-25 }))).toBe(
+ "0.0000000000000000000000001% of base",
+ );
+ });
+
it("checks the Preferences minimum by the same rule", () => {
expect(meetsMinimum(offer({}), { amount: 95_000, currency: "EUR", period: "year" })).toBe(true);
expect(meetsMinimum(offer({}), { amount: 95_000, currency: "EUR", period: "month" })).toBeNull();
});
});
+import { i18n } from "@lingui/core";
diff --git a/apps/web/src/features/career/offer-compare.ts b/apps/web/src/features/career/offer-compare.ts
index 38b91bad1..668287a2f 100644
--- a/apps/web/src/features/career/offer-compare.ts
+++ b/apps/web/src/features/career/offer-compare.ts
@@ -37,7 +37,7 @@ export const matchingPlace = (location: string, places: string[]) => {
export function formatBonus(locale: string, terms: OfferTerms) {
if (terms.variablePercent == null)
return terms.variable === null ? null : formatMoney(locale, terms.currency, terms.variable);
- const percent = new Intl.NumberFormat(locale, { style: "percent", maximumFractionDigits: 20 }).format(
+ const percent = new Intl.NumberFormat(locale, { style: "percent", maximumSignificantDigits: 21 }).format(
terms.variablePercent / 100,
);
const amount = bonusAmount(terms);
diff --git a/apps/web/src/features/career/offer-entry.tsx b/apps/web/src/features/career/offer-entry.tsx
index 6f4aceaf2..332c9c34c 100644
--- a/apps/web/src/features/career/offer-entry.tsx
+++ b/apps/web/src/features/career/offer-entry.tsx
@@ -28,6 +28,7 @@ import { Sheet, SheetContent, SheetTitle } from "@reactive-resume/ui/components/
import { Skeleton } from "@reactive-resume/ui/components/skeleton";
import { toast } from "@reactive-resume/ui/components/toast";
import { useBreakpoint } from "@reactive-resume/ui/hooks/use-breakpoint";
+import { pendingRequestId, settleRequestId } from "@reactive-resume/utils/string";
import { cn } from "@reactive-resume/utils/style";
import { CareerLoadError } from "./load-state";
import { formatMoney } from "./offer-compare";
@@ -42,7 +43,7 @@ import { useMoveWithUndo } from "@/features/applications/use-application-actions
import { useApplicationLanes } from "@/features/applications/use-application-lanes";
import { MoreOptions } from "@/features/resume/editor/write/fields";
import { getAccountId, getAccountGeneration } from "@/libs/auth/account-scope";
-import { orpc } from "@/libs/orpc/client";
+import { client, orpc } from "@/libs/orpc/client";
type Application = {
id: string;
@@ -365,6 +366,16 @@ export function OfferForm({ application, offer: initialOffer, onClose, onSaved }
});
const update = useMutation({
...orpc.career.updateOffer.mutationOptions(),
+ mutationFn: async (input: Parameters<typeof client.career.updateOffer>[0]) => {
+ if (!current() || !owner.id) throw new Error("Account changed");
+ const key = JSON.stringify(["career:offer-version", owner.id, owner.generation, input]);
+ const result = await client.career.updateOffer(
+ { ...input, newId: pendingRequestId(key) },
+ { context: { accountId: owner.id } },
+ );
+ settleRequestId(key);
+ return result;
+ },
onSuccess: (offer) => {
if (!current()) return;
rememberOffer(offer);
diff --git a/apps/web/src/features/career/offers.tsx b/apps/web/src/features/career/offers.tsx
index 69d86a069..d4a30b0af 100644
--- a/apps/web/src/features/career/offers.tsx
+++ b/apps/web/src/features/career/offers.tsx
@@ -629,7 +629,7 @@ function useCells() {
}
if (difference !== null && difference > 0)
return [{ icon: "arrow-up", tone: "better", text: t`${formatMoney(locale, terms.currency, difference)} more` }];
- if (key === "base" && difference === null && other.data.base !== null && terms.base !== null)
+ if (key === "base" && difference === null && terms.base !== null && (other.data.base !== null || annual !== null))
return [
{
icon: "info",
@@ -773,7 +773,7 @@ function OpenQuestions({ offers }: OpenQuestionsProps) {
[t`What is the base salary, and is it negotiable?`, (terms) => terms.base === null],
[
t`Is there a bonus, and what does it depend on?`,
- (terms) => terms.variable === null && terms.variablePercent == null && !terms.variableConditions.trim(),
+ (terms) => terms.variable === null && !terms.variableConditions.trim(),
],
[
t`How is the bonus decided, and how much of it was paid out last year?`,
diff --git a/docs/guides/comparing-job-offers.mdx b/docs/guides/comparing-job-offers.mdx
index 1e4d1bbb5..51832fef6 100644
--- a/docs/guides/comparing-job-offers.mdx
+++ b/docs/guides/comparing-job-offers.mdx
@@ -23,7 +23,7 @@ To extract terms with an AI connection instead:
3. Review the proposed offer information against the original message or document. The proposal lists every term it extracted, including the base, any bonus and its conditions, equity, the start date and the employer's stated answer deadline; a term it could not find stays unknown rather than being guessed.
4. Select the offer change you want to keep, then choose **Apply … change(s)**.
-Repeat for the other application. A response deadline the employer states belongs in **Respond by**; an unrelated follow-up is never copied into it. Written and verbal offers can both be saved. If a term was read incorrectly, open the offer's heading in **Career → Offers** and choose **Edit terms**; the form opens with the saved terms and saves your correction as a new version. The earlier version stays available. If the offer changed in another tab or device since you opened it, saving asks you to review the latest terms first. Close the editor and open **Edit terms** again to start from that latest copy. **Delete offer** in the same menu removes a version, with **Undo**; you can also delete it from **Saved**.
+Repeat for the other application. A response deadline the employer states belongs in **Respond by**; an unrelated follow-up is never copied into it. Written and verbal offers can both be saved. If a term was read incorrectly, open the offer's heading in **Career → Offers** and choose **Edit terms**; the form opens with the saved terms and saves your correction as a new version. The earlier version stays available. If that same saved version's terms changed in another tab or device since you opened it, saving asks you to review the latest terms first. Close the editor and open **Edit terms** again to start from that latest copy. **Delete offer** in the same menu removes a version, with **Undo**; you can also delete it from **Saved**.
Saving terms records an offer; it does not accept it or reply to the employer.
diff --git a/docs/spec.json b/docs/spec.json
index 243dab7a5..917641bde 100644
--- a/docs/spec.json
+++ b/docs/spec.json
@@ -55471,7 +55471,7 @@
"patch": {
"operationId": "updateCareerOffer",
"summary": "Correct saved offer terms",
- "description": "Corrects saved terms, or saves a new version when newVersion is true. `expected` is the copy being corrected; concurrent changes conflict.",
+ "description": "Corrects saved terms, or saves a new version when newVersion is true. `expected` is the copy being corrected; concurrent changes conflict. Supply the same newId and payload when retrying a new version after a lost response; a deleted version cannot be recreated by retrying.",
"tags": [
"Career"
],
@@ -55771,6 +55771,10 @@
},
"newVersion": {
"type": "boolean"
+ },
+ "newId": {
+ "type": "string",
+ "format": "uuid"
}
},
"required": [
diff --git a/packages/api/src/features/career/generate.ts b/packages/api/src/features/career/generate.ts
index 410eb87e6..86b3cec79 100644
--- a/packages/api/src/features/career/generate.ts
+++ b/packages/api/src/features/career/generate.ts
@@ -56,7 +56,7 @@ const TASKS: Record<GenerateTask["task"], string> = {
briefing: `Plan the user's preparation for the selected interview round. plan is about 30 minutes in 3–5 steps; action is "story" when an existing story covers it (set storyId), "draft-story" when the interviewer asked for a story Knowledge doesn't have, "questions" for questions to ask, "practise" (the value's spelling; in text write "practice" in en-US) for rehearsing aloud. questions are what to ask the interviewer; origin says where each came from (for example "Maya's request", "Briefing"). focus, opening (a first-person opening line under 60 words), stories (two one-line story summaries) and honesty (what isn't evidenced yet and how to handle it) make the 10-minute briefing. storyIds are the stories to bring. missingStory names a story the interviewer asked for that Knowledge lacks, or null. practiceQuestions are 3 likely questions for this round and audience.`,
practice: `Give feedback on the user's practice answer to the question. When input.storyId is present, focus on that selected story and its supporting facts in their Knowledge. title is a one-line verdict; works is what the answer does well, citing their words; strengthen is the single most useful improvement; opening is a stronger first-person opening built only from their facts and answer; note is a 2–3 word result for a list (for example "Contribution unclear"). A typed answer can't show pace or confidence; don't comment on them.`,
debrief: `Review what the user said in a real interview. verdicts tag each claim "supported" when their Knowledge backs it, "observation" when it is only something they noticed. nextRound is advice for the next round; priority is one practice priority. remember is one sentence worth remembering for this application only (what the interviewer asked for or cared about), in the first person, or null. plan is a light plan for this week: up to 3 dated practice tasks (day, minutes, task), each saying where it came from. round names the round (for example "Screening"). Practice priorities are not conclusions about why an employer decided anything.`,
- reply: `Read the employer's message. title says what it is in plain words (for example "They're inviting you to the next round"). asks are what they ask for; unconfirmed are things it doesn't confirm yet. reply is a short suggested reply the user can edit and send themselves. changes propose updates to the application: a stage only when the message clearly moves it; at most one follow-up, whose note is the next step in a few words and whose at is 09:00 on the day a reply is due (ISO date-time with offset, in preferences.timezone) or null when nothing is due; "offer" only when the message contains offer terms, which then go in offer (amounts as numbers in their own currency and pay period, unknown amounts null). Record percentage bonuses in variablePercent and leave variable null; never convert a percentage into an amount. Keep conditions in variableConditions. respondBy is the stated decision deadline, an ISO date-time with offset in preferences.timezone; preserve an explicit date rather than leaving it null, and do not invent one when absent. Put a stated decision deadline in offer.respondBy as well as in the follow-up, and copy a stated bonus into offer.variable and its conditions into offer.variableConditions, a stated equity grant into offer.equity, and a stated start date into offer.startDate. Never copy an unrelated follow-up date into offer.respondBy: only a deadline about the offer itself belongs there. Never propose a new interview from an unconfirmed time. Use [] and null when nothing applies.`,
+ reply: `Read the employer's message. title says what it is in plain words (for example "They're inviting you to the next round"). asks are what they ask for; unconfirmed are things it doesn't confirm yet. reply is a short suggested reply the user can edit and send themselves. changes propose updates to the application: a stage only when the message clearly moves it; at most one follow-up, whose note is the next step in a few words and whose at is 09:00 on the day a reply is due (ISO date-time with offset, in preferences.timezone) or null when nothing is due; "offer" only when the message contains offer terms, which then go in offer (amounts as numbers in their own currency and pay period, unknown amounts null). Record percentage bonuses in variablePercent and leave variable null; never convert a percentage into an amount. Keep conditions in variableConditions. respondBy is the stated decision deadline, an ISO date-time with offset in preferences.timezone; preserve an explicit date rather than leaving it null, and do not invent one when absent. Put a stated decision deadline in offer.respondBy as well as in the follow-up, and copy a stated bonus amount (never a percentage) into offer.variable and its conditions into offer.variableConditions, a stated equity grant into offer.equity, and a stated start date into offer.startDate. Never copy an unrelated follow-up date into offer.respondBy: only a deadline about the offer itself belongs there. Never propose a new interview from an unconfirmed time. Use [] and null when nothing applies.`,
answer: `Write the user's answer to the application form question. When "answer" is empty, draft one; otherwise tighten it. Evidence is the resume, the user's facts and stories, and the user's own draft: all of it may support a claim. When the question states a word or character limit, aim for 80–100% of it and stay within it; without a stated limit, tighten by about a quarter and keep a draft's length. Keep every claim in the current answer, even if it is absent from Knowledge; only cut words, never add metrics, dates, ownership or results. Never remove a fact the user wrote; when a claim has no support, keep it and name it in note for the user to check. Same facts, same voice.`,
};
diff --git a/packages/api/src/features/career/router.ts b/packages/api/src/features/career/router.ts
index 2ca65813d..8343b71c1 100644
--- a/packages/api/src/features/career/router.ts
+++ b/packages/api/src/features/career/router.ts
@@ -358,12 +358,19 @@ export const careerRouter = {
operationId: "updateCareerOffer",
summary: "Correct saved offer terms",
description:
- "Corrects saved terms, or saves a new version when newVersion is true. `expected` is the copy being corrected; concurrent changes conflict.",
+ "Corrects saved terms, or saves a new version when newVersion is true. `expected` is the copy being corrected; concurrent changes conflict. Supply the same newId and payload when retrying a new version after a lost response; a deleted version cannot be recreated by retrying.",
})
- .input(id.extend({ terms: offerTermsSchema, expected: offerTermsSchema, newVersion: z.boolean().optional() }))
+ .input(
+ id.extend({
+ terms: offerTermsSchema,
+ expected: offerTermsSchema,
+ newVersion: z.boolean().optional(),
+ newId: z.uuid().optional(),
+ }),
+ )
.output(savedItemSchema)
.handler(({ context, input }) =>
- careerService.updateOffer(context.user.id, input.id, input.terms, input.expected, input.newVersion),
+ careerService.updateOffer(context.user.id, input.id, input.terms, input.expected, input.newVersion, input.newId),
),
deleteSavedItem: protectedProcedure
.route({
diff --git a/packages/api/src/features/career/service.integration.test.ts b/packages/api/src/features/career/service.integration.test.ts
index e15acf739..bfacbef98 100644
--- a/packages/api/src/features/career/service.integration.test.ts
+++ b/packages/api/src/features/career/service.integration.test.ts
@@ -1584,6 +1584,37 @@ describe.skipIf(!databaseUrl)("career knowledge, context and data lifecycle", ()
await expect(service.updateOffer("alice", fit.id, terms, terms)).rejects.toMatchObject({ code: "NOT_FOUND" });
});
+ it("replays one receipted offer version without duplicating it or reviving a deleted version", async () => {
+ const input = careerOfferInputSchema.parse({
+ applicationId: "alice-app",
+ currency: "EUR",
+ period: "year",
+ base: 85000,
+ variable: null,
+ });
+ const original = await service.createOffer("alice", input);
+ if (original?.data.kind !== "offer") throw new Error("Expected an offer.");
+ const expected = offerTermsSchema.parse(original.data);
+ const terms = { ...expected, base: 90000 };
+ const newId = randomUUID();
+ const save = () => service.updateOffer("alice", original.id, terms, expected, true, newId);
+ const [first, replay] = await Promise.all([save(), save()]);
+ expect(replay.id).toBe(first.id);
+ expect(first.id).toBe(newId);
+ expect(await service.savedItems({ userId: "alice", kind: "offer" })).toHaveLength(2);
+ await expect(
+ service.updateOffer("alice", original.id, { ...terms, base: 1 }, expected, true, newId),
+ ).rejects.toMatchObject({ code: "CONFLICT" });
+ await expect(service.updateOffer("bob", original.id, terms, expected, true, newId)).rejects.toMatchObject({
+ code: "NOT_FOUND",
+ });
+ await service.updateOffer("alice", original.id, { ...expected, base: 86000 }, expected);
+ expect((await save()).id).toBe(newId);
+ await service.deleteSavedItem("alice", newId);
+ await expect(save()).rejects.toMatchObject({ code: "CONFLICT" });
+ expect(await service.savedItems({ userId: "alice", kind: "offer" })).toHaveLength(1);
+ });
+
it("names the messages no longer sent after Knowledge changes, and replies that ended early", async () => {
const { agentService } = await import("../agent/service");
const at = (minutes: number) => new Date(Date.UTC(2026, 9, 1, 9, minutes));
@@ -2497,6 +2528,7 @@ describe.skipIf(!databaseUrl)("career knowledge, context and data lifecycle", ()
});
const prompt = fixture.generate.mock.calls[0]?.[1]?.prompt as string;
expect(prompt).toContain("Record percentage bonuses in variablePercent");
+ expect(prompt).toContain("bonus amount (never a percentage) into offer.variable");
expect(prompt).toContain("respondBy is the stated decision deadline");
});
diff --git a/packages/api/src/features/career/service.ts b/packages/api/src/features/career/service.ts
index b4b8c632a..305a1129b 100644
--- a/packages/api/src/features/career/service.ts
+++ b/packages/api/src/features/career/service.ts
@@ -33,7 +33,7 @@ import { findTrackedPosting } from "../applications/duplicates";
import { syncFollowUp } from "../applications/follow-up";
import { applicationTransitionValues, ensureApplicationPipeline, savedStageOf } from "../applications/lanes";
import { applicationService, assertApplicationVersion, hasSubmitted, recordSentResume } from "../applications/service";
-import { assertSharedDocument, lockUser } from "../documents/ownership";
+import { assertSharedDocument, idInUse, isRetriedCreate, lockUser, recordCreateRequest } from "../documents/ownership";
import { parseStoredResumeData } from "../resume/resume-data-validation";
import { matchPosting } from "./matching";
import { noticeText } from "./notices";
@@ -1016,7 +1016,14 @@ export const careerService = {
* Corrects a saved offer's terms. `expected` is the copy the user edited: a change made elsewhere since then is a
* conflict, never overwritten. Where the terms came from is kept.
*/
- updateOffer: (userId: string, id: string, terms: OfferTerms, expected: OfferTerms, newVersion = false) =>
+ updateOffer: (
+ userId: string,
+ id: string,
+ terms: OfferTerms,
+ expected: OfferTerms,
+ newVersion = false,
+ newId?: string,
+ ) =>
db.transaction(async (tx) => {
await lockUser(tx, userId);
const [row] = await tx
@@ -1034,10 +1041,27 @@ export const careerService = {
.for("update");
if (!row || row.data.kind !== "offer") throw new ORPCError("NOT_FOUND");
const { kind: _kind, origin, editedAt: _editedAt, ...current } = row.data;
+ const nextTerms = { ...offerTermsSchema.parse(terms), variablePercent: terms.variablePercent ?? null };
+ const expectedTerms = { ...offerTermsSchema.parse(expected), variablePercent: expected.variablePercent ?? null };
+ const request = { kind: "offer-version", id, terms: nextTerms, expected: expectedTerms };
+ if (newVersion && newId && (await isRetriedCreate(tx, { table: "careerArtifact", id: newId, userId, request }))) {
+ const [version] = await tx
+ .select()
+ .from(tables.careerArtifact)
+ .where(
+ and(
+ eq(tables.careerArtifact.id, newId),
+ eq(tables.careerArtifact.userId, userId),
+ availableApplicationContext(userId, tables.careerArtifact.applicationId),
+ ),
+ );
+ if (!version || version.data.kind !== "offer") throw new ORPCError("NOT_FOUND");
+ return version;
+ }
if (
!isDeepStrictEqual(
{ ...offerTermsSchema.parse(current), variablePercent: current.variablePercent ?? null },
- { ...offerTermsSchema.parse(expected), variablePercent: expected.variablePercent ?? null },
+ expectedTerms,
)
)
throw new ORPCError("CONFLICT", {
@@ -1045,7 +1069,7 @@ export const careerService = {
});
const data: SavedItemData = {
kind: "offer",
- ...offerTermsSchema.parse(terms),
+ ...nextTerms,
...(origin ? { origin } : {}),
editedAt: new Date().toISOString(),
};
@@ -1054,6 +1078,7 @@ export const careerService = {
const [version] = await tx
.insert(tables.careerArtifact)
.values({
+ ...(newId ? { id: newId } : {}),
userId,
applicationId: row.applicationId,
interviewId: row.interviewId,
@@ -1062,8 +1087,10 @@ export const careerService = {
evidence: row.evidence,
inputVersion: row.inputVersion,
})
+ .onConflictDoNothing({ target: tables.careerArtifact.id })
.returning();
- if (!version) throw new ORPCError("NOT_FOUND");
+ if (!version) throw idInUse();
+ if (newId) await recordCreateRequest(tx, { id: newId, userId, request });
return version;
}
const [updated] = await tx
diff --git a/packages/api/src/features/documents/ownership.ts b/packages/api/src/features/documents/ownership.ts
index 0bf57949c..1668e725c 100644
--- a/packages/api/src/features/documents/ownership.ts
+++ b/packages/api/src/features/documents/ownership.ts
@@ -37,7 +37,7 @@ const fingerprintOf = (request: unknown) =>
.update(JSON.stringify(canonical(request)))
.digest("hex");
-type CreatedRow = { table: "resume" | "application"; id: string; userId: string; request: unknown };
+type CreatedRow = { table: "resume" | "application" | "careerArtifact"; id: string; userId: string; request: unknown };
/** Refusal of a client-chosen ID: it isn't free, and this request isn't the one that took it. */
export const idInUse = () =>
@@ -45,7 +45,7 @@ export const idInUse = () =>
/**
* Whether a row with this client-chosen ID was already saved by this same request: a retry after a lost response, a
- * second press or a remounted screen, which gets that row back. Resumes and applications share one ID space here. Any
+ * second press or a remounted screen, which gets that row back. Receipted creates share one ID space here. Any
* other use is refused, without saying which: an ID another account holds, one a resume or application was saved
* under some other way, one a different request took, or one whose row this request saved but has since been deleted
* or moved to Trash, so a reused ID never returns, links, changes or brings back a row.
@@ -63,10 +63,17 @@ export async function isRetriedCreate(tx: DbOrTx, { table, id, userId, request }
.select({ userId: schema.createRequest.userId, fingerprint: schema.createRequest.fingerprint })
.from(schema.createRequest)
.where(eq(schema.createRequest.id, id));
- if (!resume && !application && !receipt) return false;
+ const [artifact] =
+ table === "careerArtifact"
+ ? await tx
+ .select({ userId: schema.careerArtifact.userId })
+ .from(schema.careerArtifact)
+ .where(eq(schema.careerArtifact.id, id))
+ : [];
+ if (!resume && !application && !artifact && !receipt) return false;
// A receipted ID was free in both tables when its row was saved, so only that row can hold it.
- const row = table === "resume" ? resume : application;
+ const row = table === "resume" ? resume : table === "application" ? application : artifact;
const sameRequest = receipt?.userId === userId && receipt.fingerprint === fingerprintOf(request);
if (row && row.userId === userId && sameRequest && !resume?.trashedAt && !application?.trashedAt) return true;
throw idInUse();
diff --git a/packages/schema/src/career-offer.test.ts b/packages/schema/src/career-offer.test.ts
index 56c4bdaa6..493cc1b3c 100644
--- a/packages/schema/src/career-offer.test.ts
+++ b/packages/schema/src/career-offer.test.ts
@@ -197,11 +197,15 @@ it("derives percentages only from their own base and round trips localized editi
expect(bonusAmount({ ...percentage, base: 0 })).toBe(0);
expect(offerTermsSchema.safeParse({ ...old, variablePercent: 10 }).success).toBe(false);
const input = entry();
- input.amounts.variable = bonusEntry(percentage, "de-DE");
- expect(parseOfferEntry({ ...input, locale: "de-DE" }).payload).toMatchObject({
- success: true,
- data: { variable: null, variablePercent: 12.5 },
- });
+ for (const locale of ["en-US", "de-DE", "ar-SA"]) {
+ for (const variablePercent of [0, 12.5, 12.345, 1e-25, 1e30, 1.2345678901234567]) {
+ input.amounts.variable = bonusEntry({ ...percentage, variablePercent }, locale);
+ expect(parseOfferEntry({ ...input, locale }).payload, `${locale}: ${input.amounts.variable}`).toMatchObject({
+ success: true,
+ data: { variable: null, variablePercent },
+ });
+ }
+ }
const yearly = { ...old, period: "year" as const };
expect(annualBaseHint(old, yearly)).toBe(84000);
expect(annualBaseHint(old, { ...yearly, currency: "USD" })).toBeNull();
diff --git a/packages/schema/src/career-offer.ts b/packages/schema/src/career-offer.ts
index 30d2fb04d..83dee6262 100644
--- a/packages/schema/src/career-offer.ts
+++ b/packages/schema/src/career-offer.ts
@@ -1,5 +1,5 @@
import type { OfferTerms } from "./career";
-import { parseAmount } from "@reactive-resume/utils/amount";
+import { parseAmount, parseDecimal } from "@reactive-resume/utils/amount";
import { fromZonedDateTime } from "@reactive-resume/utils/timezone";
import { careerOfferInputSchema } from "./career";
@@ -18,7 +18,9 @@ type OfferEntry = {
export function parseOfferEntry({ applicationId, terms, amounts, date, time, locale, timeZone }: OfferEntry) {
const base = parseAmount(amounts.base, locale);
const percentage = amounts.variable.trim().endsWith("%");
- const variable = parseAmount(percentage ? amounts.variable.trim().slice(0, -1).trim() : amounts.variable, locale);
+ const variable = percentage
+ ? parseDecimal(amounts.variable.trim().slice(0, -1).trim(), locale)
+ : parseAmount(amounts.variable, locale);
const invalidVariable = variable === undefined || (percentage && variable === null);
const learning = parseAmount(amounts.learning, locale);
const deadline = date && timeZone ? fromZonedDateTime(date, time, timeZone) : null;
@@ -179,7 +181,7 @@ export function bonusAmount(terms: Pick<OfferTerms, "base" | "variable" | "varia
export function bonusEntry(terms: Pick<OfferTerms, "variable" | "variablePercent">, locale: string) {
return terms.variablePercent != null
- ? `${new Intl.NumberFormat(locale, { useGrouping: false, maximumFractionDigits: 20 }).format(terms.variablePercent)}%`
+ ? `${new Intl.NumberFormat(locale, { useGrouping: false, maximumSignificantDigits: 21 }).format(terms.variablePercent)}%`
: terms.variable === null
? ""
: String(terms.variable);
diff --git a/packages/utils/src/amount.test.ts b/packages/utils/src/amount.test.ts
new file mode 100644
index 000000000..9e888a325
--- /dev/null
+++ b/packages/utils/src/amount.test.ts
@@ -0,0 +1,22 @@
+import { expect, it } from "vite-plus/test";
+import { parseAmount, parseDecimal } from "./amount";
+
+it("keeps monetary precision and safe bounds while accepting finite percentage decimals", () => {
+ for (const [locale, text, value] of [
+ ["en-US", "12,345.67", 12345.67],
+ ["de-DE", "12.345,67", 12345.67],
+ ["ar-SA", "١٢٬٣٤٥٫٦٧", 12345.67],
+ ] as const) {
+ expect(parseAmount(text, locale)).toBe(value);
+ }
+ for (const text of ["12.345", "9007199254740992", "1,23", "95k", "-1", "Infinity", "1e3", "12."]) {
+ expect(parseAmount(text, "en-US"), text).toBeUndefined();
+ }
+ expect(parseAmount("", "en-US")).toBeNull();
+ expect(parseAmount("0", "en-US")).toBe(0);
+ expect(parseDecimal("12,345", "de-DE")).toBe(12.345);
+ expect(parseDecimal("١٢٫٣٤٥", "ar-SA")).toBe(12.345);
+ for (const text of ["-1", "Infinity", "1e3", "1,23", "12."])
+ expect(parseDecimal(text, "en-US"), text).toBeUndefined();
+ expect(parseDecimal("9".repeat(400), "en-US")).toBeUndefined();
+});
diff --git a/packages/utils/src/amount.ts b/packages/utils/src/amount.ts
index 9717e4395..8856c9ae4 100644
--- a/packages/utils/src/amount.ts
+++ b/packages/utils/src/amount.ts
@@ -1,5 +1,4 @@
-/** Parse a complete nonnegative amount. Invalid notation must never silently change a saved requirement. */
-export function parseAmount(input: string, locale: string): number | null | undefined {
+function parseLocalizedNumber(input: string, locale: string, maximumFractionDigits: number): number | null | undefined {
const number = new Intl.NumberFormat(locale, { maximumFractionDigits: 2 });
const parts = number.formatToParts(12345.6);
const decimal = parts.find((part) => part.type === "decimal")?.value ?? ".";
@@ -12,7 +11,11 @@ export function parseAmount(input: string, locale: string): number | null | unde
if (pieces.length > 2) return undefined;
const [whole = "", fraction] = pieces;
const ungrouped = group ? whole.replaceAll(group, "") : whole;
- if (!/^\d+$/.test(ungrouped) || (fraction !== undefined && !/^\d{1,2}$/.test(fraction))) return undefined;
+ if (
+ !/^\d+$/.test(ungrouped) ||
+ (fraction !== undefined && (!/^\d+$/.test(fraction) || fraction.length > maximumFractionDigits))
+ )
+ return undefined;
if (group && whole.includes(group)) {
const expected = new Intl.NumberFormat(locale, { maximumFractionDigits: 0 }).format(Number(ungrouped));
let normalized = expected;
@@ -20,5 +23,16 @@ export function parseAmount(input: string, locale: string): number | null | unde
if (whole !== normalized) return undefined;
}
const value = Number(`${ungrouped}.${fraction ?? "0"}`);
- return Number.isFinite(value) && value <= Number.MAX_SAFE_INTEGER ? value : undefined;
+ return Number.isFinite(value) ? value : undefined;
+}
+
+/** Complete, finite, nonnegative decimal; percentages retain their stored precision. */
+export function parseDecimal(input: string, locale: string): number | null | undefined {
+ return parseLocalizedNumber(input, locale, Number.POSITIVE_INFINITY);
+}
+
+/** Money retains its two-decimal and safe-integer bounds. */
+export function parseAmount(input: string, locale: string): number | null | undefined {
+ const value = parseLocalizedNumber(input, locale, 2);
+ return typeof value === "number" && value > Number.MAX_SAFE_INTEGER ? undefined : value;
}
diff --git a/tests/e2e/specs/career-offer-accelerators.spec.ts b/tests/e2e/specs/career-offer-accelerators.spec.ts
index 80447c963..bf3886a29 100644
--- a/tests/e2e/specs/career-offer-accelerators.spec.ts
+++ b/tests/e2e/specs/career-offer-accelerators.spec.ts
@@ -9,7 +9,7 @@ async function application(page: Page, company: string) {
return (await response.json()) as string;
}
-async function offer(page: Page, applicationId: string, base = 85000, period = "year") {
+async function offer(page: Page, applicationId: string, base: number | null = 85000, period = "year") {
const response = await page.request.post("/api/openapi/career/offers", {
data: { applicationId, currency: "EUR", period, base, variable: null },
});
@@ -46,7 +46,9 @@ test("heading edits save a new version and Delete Undo preserves both versions",
.first()
.click();
await page.getByRole("menuitem", { name: "Delete offer", exact: true }).click();
+ await expect(page.getByText("€90,000 a year", { exact: true })).toHaveCount(0);
await page.getByRole("button", { name: "Undo", exact: true }).click();
+ await expect(page.getByText("€90,000 a year", { exact: true })).toBeVisible();
await page.reload();
expect((await offers(page)).map((row) => row.id).sort()).toEqual([original.id, saved.id].sort());
});
@@ -84,6 +86,9 @@ test("percentage bonus persists as a percentage and reopens without becoming an
expect((await offers(page))[0]?.data).toMatchObject({ base: 85000, variable: null, variablePercent: 10 });
await page.reload();
await expect(page.getByText("10% of base (€8,500)", { exact: true })).toBeVisible();
+ await expect(
+ page.getByRole("listitem").filter({ hasText: "Is there a bonus, and what does it depend on?" }),
+ ).toBeVisible();
await page.getByRole("main").screenshot({ path: info.outputPath("offers-percentage.png"), animations: "disabled" });
await page.getByRole("button", { name: /Northwind Labs.*Written offer/ }).click();
await page.getByRole("menuitem", { name: "Edit terms", exact: true }).click();
@@ -98,3 +103,39 @@ test("different pay periods show bounded arithmetic without a money judgement",
await expect(page.getByText("≈ €84,000 a year (12 × €7,000)", { exact: true })).toBeVisible();
await expect(page.getByText("€6,000 more", { exact: true })).toHaveCount(0);
});
+
+test("a known monthly base still shows arithmetic against an unknown yearly base", async ({ authPage: page }) => {
+ const monthly = await offer(page, await application(page, "Lumen Health"), 7000, "month");
+ const yearly = await offer(page, await application(page, "Canopy Systems"), null);
+ await page.goto(`/dashboard/career/offers?a=${monthly.id}&b=${yearly.id}`);
+ await expect(page.getByText("≈ €84,000 a year (12 × €7,000)", { exact: true })).toBeVisible();
+ await expect(page.getByText("Different pay period, not compared", { exact: true })).toHaveCount(1);
+});
+
+test("retrying a lost new-version response returns the single committed version", async ({ authPage: page }) => {
+ const original = await offer(page, await application(page, "Northwind Labs"));
+ await page.goto(`/dashboard/career/offers?a=${original.id}`);
+ await page.getByRole("button", { name: /Northwind Labs.*Written offer/ }).click();
+ await page.getByRole("menuitem", { name: "Edit terms", exact: true }).click();
+ await page.getByLabel("Base salary", { exact: true }).fill("90000");
+ const requests: string[] = [];
+ await page.route("**/api/rpc/career/updateOffer", async (route) => {
+ requests.push(route.request().postData() ?? "");
+ if (requests.length > 1) return route.continue();
+ const response = await route.fetch();
+ expect(response.status()).toBe(200);
+ await route.abort("failed");
+ });
+ await page.getByRole("button", { name: "Save offer", exact: true }).click();
+ await expect(page.getByText("Couldn't save the offer. Your draft is still here. Try again.")).toBeVisible();
+ const committed = (await offers(page)).find((row) => row.id !== original.id);
+ if (!committed) throw new Error("The discarded response must have committed a version.");
+ await page.getByRole("button", { name: "Save offer", exact: true }).click();
+ await expect(page.getByRole("heading", { name: "Edit offer terms", exact: true })).toHaveCount(0);
+ await expect(page).toHaveURL(new RegExp(`a=${committed.id}`));
+ expect(requests).toHaveLength(2);
+ expect(requests[1]).toBe(requests[0]);
+ expect((await offers(page)).map((row) => row.id).sort()).toEqual([original.id, committed.id].sort());
+ await page.reload();
+ await expect(page.getByText("€90,000 a year", { exact: true })).toBeVisible();
+});