Compare commits
1 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 6f6ba9402a |
@@ -0,0 +1,134 @@
|
||||
using System.Data.Common;
|
||||
using System.Diagnostics;
|
||||
using JobTrackerApi.Controllers;
|
||||
using JobTrackerApi.Data;
|
||||
using JobTrackerApi.Models;
|
||||
using JobTrackerApi.Services;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.Diagnostics;
|
||||
using MySqlConnector;
|
||||
using Xunit;
|
||||
using Xunit.Abstractions;
|
||||
|
||||
namespace JobTrackerApi.MariaDb.Tests;
|
||||
|
||||
[CollectionDefinition("Rules MariaDB measurements", DisableParallelization = true)]
|
||||
public sealed class RulesMariaDbMeasurementCollection;
|
||||
|
||||
[Collection("Rules MariaDB measurements")]
|
||||
public sealed class RulesFreshnessMariaDbTests(ITestOutputHelper output)
|
||||
{
|
||||
private const string Owner = "rules-owner";
|
||||
private const string Other = "rules-other";
|
||||
private const string Fallback = "rules-fallback";
|
||||
private const int Repetitions = 100;
|
||||
|
||||
[Fact]
|
||||
public async Task Timed_out_save_preserves_committed_rules_and_retry_reaches_existing_readers()
|
||||
{
|
||||
await using var database = await MariaDbDatabase.CreateAsync();
|
||||
await Seed(database);
|
||||
await using var ownerReader = database.Context(Owner);
|
||||
await using var otherReader = database.Context(Other);
|
||||
Assert.Equal(30, (await RulesEngine.GetSettings(ownerReader, default)).AppliedFollowUpDays);
|
||||
Assert.Equal(45, (await RulesEngine.GetSettings(otherReader, default)).AppliedFollowUpDays);
|
||||
|
||||
await using var lockOwner = database.Context(Owner);
|
||||
await using var transaction = await lockOwner.Database.BeginTransactionAsync();
|
||||
var locked = await lockOwner.UserRuleSettings.SingleAsync();
|
||||
locked.AppliedFollowUpDays = 31;
|
||||
await lockOwner.SaveChangesAsync();
|
||||
|
||||
await using var failedWriter = database.Context(Owner);
|
||||
await failedWriter.Database.OpenConnectionAsync();
|
||||
await failedWriter.Database.ExecuteSqlRawAsync("SET SESSION innodb_lock_wait_timeout = 1");
|
||||
var started = Stopwatch.GetTimestamp();
|
||||
var error = await Assert.ThrowsAsync<InvalidOperationException>(
|
||||
() => new RulesController(failedWriter).Update(new RuleSettings { AppliedFollowUpDays = 1 }, default));
|
||||
var update = Assert.IsType<DbUpdateException>(error.InnerException);
|
||||
Assert.Equal(1205, Assert.IsType<MySqlException>(update.InnerException).Number);
|
||||
var timeout = Stopwatch.GetElapsedTime(started);
|
||||
|
||||
Assert.Equal(1, failedWriter.UserRuleSettings.Local.Single().AppliedFollowUpDays);
|
||||
Assert.Equal(30, (await RulesEngine.GetSettings(failedWriter, default)).AppliedFollowUpDays);
|
||||
Assert.Equal(30, (await RulesEngine.GetSettings(ownerReader, default)).AppliedFollowUpDays);
|
||||
Assert.Equal(45, (await RulesEngine.GetSettings(otherReader, default)).AppliedFollowUpDays);
|
||||
await transaction.RollbackAsync();
|
||||
|
||||
await using var retry = database.Context(Owner);
|
||||
started = Stopwatch.GetTimestamp();
|
||||
Assert.IsType<NoContentResult>(
|
||||
await new RulesController(retry).Update(new RuleSettings { AppliedFollowUpDays = 1 }, default));
|
||||
var retryDuration = Stopwatch.GetElapsedTime(started);
|
||||
Assert.Equal(1, (await RulesEngine.GetSettings(ownerReader, default)).AppliedFollowUpDays);
|
||||
Assert.Equal(45, (await RulesEngine.GetSettings(otherReader, default)).AppliedFollowUpDays);
|
||||
output.WriteLine($"MariaDB {database.ActualVersion} lock timeout {timeout.TotalMilliseconds:F1} ms; retry {retryDuration.TotalMilliseconds:F1} ms.");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Committed_owner_and_fallback_reads_measure_queries_and_latency_with_same_workload()
|
||||
{
|
||||
await using var database = await MariaDbDatabase.CreateAsync();
|
||||
await Seed(database);
|
||||
var ownerQueries = new QueryCounter();
|
||||
var fallbackQueries = new QueryCounter();
|
||||
await using var owner = database.Context(Owner, ownerQueries);
|
||||
await using var fallback = database.Context(Fallback, fallbackQueries);
|
||||
|
||||
Assert.Equal(30, (await RulesEngine.GetSettings(owner, default)).AppliedFollowUpDays);
|
||||
Assert.Equal(60, (await RulesEngine.GetSettings(fallback, default)).AppliedFollowUpDays);
|
||||
ownerQueries.Count = fallbackQueries.Count = 0;
|
||||
double[] ownerTimes = new double[Repetitions];
|
||||
double[] fallbackTimes = new double[Repetitions];
|
||||
|
||||
for (var index = 0; index < Repetitions; index++)
|
||||
{
|
||||
ownerTimes[index] = await MeasureRead(owner, 30);
|
||||
fallbackTimes[index] = await MeasureRead(fallback, 60);
|
||||
}
|
||||
|
||||
Assert.Equal(Repetitions, ownerQueries.Count);
|
||||
Assert.Equal(Repetitions * 2, fallbackQueries.Count);
|
||||
Array.Sort(ownerTimes);
|
||||
Array.Sort(fallbackTimes);
|
||||
output.WriteLine(FormattableString.Invariant(
|
||||
$"MariaDB {database.ActualVersion}; {Repetitions} reads per path. Owner {ownerQueries.Count} commands, p50/p95 {ownerTimes[Repetitions / 2 - 1]:F3}/{ownerTimes[Repetitions * 95 / 100 - 1]:F3} ms. Fallback {fallbackQueries.Count} commands, p50/p95 {fallbackTimes[Repetitions / 2 - 1]:F3}/{fallbackTimes[Repetitions * 95 / 100 - 1]:F3} ms."));
|
||||
}
|
||||
|
||||
private static async Task<double> MeasureRead(JobTrackerContext db, int expected)
|
||||
{
|
||||
var start = Stopwatch.GetTimestamp();
|
||||
var settings = await RulesEngine.GetSettings(db, default);
|
||||
var elapsed = Stopwatch.GetElapsedTime(start).TotalMilliseconds;
|
||||
Assert.Equal(expected, settings.AppliedFollowUpDays);
|
||||
return elapsed;
|
||||
}
|
||||
|
||||
private static async Task Seed(MariaDbDatabase database)
|
||||
{
|
||||
await using var db = database.Context();
|
||||
db.Users.AddRange(
|
||||
new ApplicationUser { Id = Owner, UserName = Owner },
|
||||
new ApplicationUser { Id = Other, UserName = Other },
|
||||
new ApplicationUser { Id = Fallback, UserName = Fallback });
|
||||
(await db.RuleSettings.SingleAsync()).AppliedFollowUpDays = 60;
|
||||
db.UserRuleSettings.AddRange(
|
||||
new UserRuleSettings { OwnerUserId = Owner, AppliedFollowUpDays = 30 },
|
||||
new UserRuleSettings { OwnerUserId = Other, AppliedFollowUpDays = 45 });
|
||||
await db.SaveChangesAsync();
|
||||
}
|
||||
|
||||
private sealed class QueryCounter : DbCommandInterceptor
|
||||
{
|
||||
public int Count { get; set; }
|
||||
|
||||
public override ValueTask<InterceptionResult<DbDataReader>> ReaderExecutingAsync(
|
||||
DbCommand command, CommandEventData eventData, InterceptionResult<DbDataReader> result,
|
||||
CancellationToken cancellationToken = default)
|
||||
{
|
||||
Count++;
|
||||
return base.ReaderExecutingAsync(command, eventData, result, cancellationToken);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -7,3 +7,13 @@ The additional real-SQLite case warms owner A/B application decisions, then inje
|
||||
All nine RuleSettingsFreshnessTests passed with zero failures/skips. Eight existing cases overlap the previous 35-case regression and are not added to that total. The native TRX, compressed/raw hashes and command log are retained under `evidence/rules-failed-save/`. Dependency restore used only the existing local NuGet cache. No application or dependency source changed.
|
||||
|
||||
The injected exception occurs before database save. This verifies committed-read behaviour after that failure and subsequent successful retry. Mid-transaction connection loss, MariaDB, multi-process load, latency, operational restore and release qualification remain separate.
|
||||
|
||||
## MariaDB committed reads after a native lock timeout
|
||||
|
||||
4 December 2026. Published A3 base `ac64d2ee221859c481dfd62e8fe83084af4c6764`. The native lane used disposable MariaDB 12.2.2 on Docker Desktop’s Linux engine with loopback TCP and .NET SDK 9.0.317.
|
||||
|
||||
A second connection held an uncommitted update of owner A’s rule row. The actual Rules controller save received MariaDB error 1205 through EF and Pomelo after 1,007.5 ms with the fixture session’s one-second lock timeout. Owner A’s committed threshold remained 30, including when read through the failed writer with its proposed value still tracked. Owner B remained at 45. After the lock holder rolled back, a fresh explicit save took 5.3 ms and the existing readers observed A at 1 and B still at 45.
|
||||
|
||||
With the same serialized workload and 100 warm reads of each path, the explicit-owner path issued 100 SQL commands and measured p50/p95 of 2.584/3.197 ms. The fallback path issued 200 commands and measured 5.068/6.095 ms. Every read returned its expected setting. These are local service-method measurements for a three-user fixture. Concurrent traffic, HTTP latency, production load and historical P2-O01’s missing server exception remain outside this run.
|
||||
|
||||
The first full run passed 101 of 102 cases. The test expected an unwrapped EF failure while Pomelo wrapped the same native server error. The final test checks both wrappers and error 1205. The second run passed **102 of 102**, zero skipped. Both disposable containers were removed. Run `python scripts/mariadb-integration.py` with the pinned SDK. Local native logs and TRX are in `.artifacts/issue-98-mariadb` and `.artifacts/issue-98-mariadb-final`. Final TRX SHA-256 `efdec2891da9e877273e0c9ab8273bc5b4fd516be326d0ad77bb2dd2496cf8ca`.
|
||||
|
||||
@@ -10,93 +10,6 @@ async function login(api: APIRequestContext, email: string) {
|
||||
return { 'X-CSRF-TOKEN': (await api.storageState()).cookies.find(cookie => cookie.name === 'XSRF-TOKEN')!.value, 'X-Session-Context': me.sessionContext as string };
|
||||
}
|
||||
|
||||
for (const [lang, mode, width] of [['en', 'light', 1440], ['nb', 'dark', 390]] as const) {
|
||||
test(`pending correspondence keeps drafts and writes with their application in ${lang}`, async ({ page, playwright }, info) => {
|
||||
const t = translations[lang];
|
||||
const admin = await playwright.request.newContext();
|
||||
const email = `notes-fixture-${lang}-${Date.now()}@example.test`;
|
||||
try {
|
||||
const adminHeaders = await login(admin, 'e2e@example.test');
|
||||
expect((await admin.post(`${apiUrl}/users`, { headers: adminHeaders, data: { email, password, roles: [] } })).status()).toBe(200);
|
||||
} finally { await admin.dispose(); }
|
||||
const headers = await login(page.request, email);
|
||||
expect((await page.request.put(`${apiUrl}/auth/preferences/language`, {
|
||||
headers, data: { language: lang === 'nb' ? 'nb-NO' : 'en' },
|
||||
})).status()).toBe(204);
|
||||
await page.addInitScript(({ lang, mode }) => {
|
||||
localStorage.setItem('uiLanguage', lang);
|
||||
localStorage.setItem('jobtracker.themeMode', mode);
|
||||
}, { lang, mode });
|
||||
await page.setViewportSize({ width, height: 900 });
|
||||
await page.route('**/*', route => {
|
||||
const url = new URL(route.request().url());
|
||||
return ['localhost', '127.0.0.1'].includes(url.hostname) || ['blob:', 'data:', 'about:'].includes(url.protocol)
|
||||
? route.continue() : route.abort();
|
||||
});
|
||||
const company = await page.request.post(`${apiUrl}/companies`, { headers, data: { name: `Notes fixture ${lang}` } });
|
||||
expect(company.status()).toBe(201);
|
||||
const companyId = (await company.json()).id;
|
||||
const create = async (jobTitle: string) => {
|
||||
const result = await page.request.post(`${apiUrl}/jobapplications`, {
|
||||
headers, data: { companyId, jobTitle, status: 'Saved' },
|
||||
});
|
||||
expect(result.status()).toBe(201);
|
||||
return (await result.json()).id as number;
|
||||
};
|
||||
const ids = [await create(`Synthetic note A ${lang}`), await create(`Synthetic note B ${lang}`)];
|
||||
const workspace = (id: number) => `/jobs/${id}?section=timeline&sub=correspondence`;
|
||||
const messageUrl = `${apiUrl}/correspondence`;
|
||||
let release!: () => void;
|
||||
let started!: () => void;
|
||||
const hold = new Promise<void>(resolve => { release = resolve; });
|
||||
const reached = new Promise<void>(resolve => { started = resolve; });
|
||||
await page.route(messageUrl, async route => {
|
||||
if (route.request().method() === 'POST' && route.request().postDataJSON()?.jobApplicationId === ids[0]) {
|
||||
started();
|
||||
await hold;
|
||||
}
|
||||
await route.continue();
|
||||
});
|
||||
const note = page.getByRole('textbox', { name: t.correspondenceLogNoteOrMessage, exact: true });
|
||||
const add = page.getByRole('button', { name: t.correspondenceAdd, exact: true });
|
||||
const posted = page.waitForResponse(response => response.url() === messageUrl && response.request().method() === 'POST');
|
||||
try {
|
||||
await page.goto(workspace(ids[0]));
|
||||
await expect(page.locator('html')).toHaveAttribute('data-color-scheme', mode);
|
||||
await note.fill('Note for A — æøå');
|
||||
const origin = await page.evaluate(() => performance.timeOrigin);
|
||||
await add.press('Enter');
|
||||
await reached;
|
||||
await page.evaluate(url => {
|
||||
// A same-document history entry exercises the live router and keeps the workspace mounted.
|
||||
const state = { idx: (history.state?.idx ?? 0) + 1, key: 'note-job-b', usr: null };
|
||||
history.pushState(state, '', url);
|
||||
dispatchEvent(new PopStateEvent('popstate', { state }));
|
||||
}, workspace(ids[1]));
|
||||
await expect(page.getByRole('heading', { name: `Synthetic note B ${lang}` })).toBeVisible();
|
||||
await expect(note).toHaveValue('');
|
||||
await note.fill('Draft for B — æøå');
|
||||
await page.goBack();
|
||||
await expect(page.getByRole('heading', { name: `Synthetic note A ${lang}` })).toBeVisible();
|
||||
await expect(note).toHaveValue('Note for A — æøå');
|
||||
await expect(add).toBeDisabled();
|
||||
release();
|
||||
expect((await posted).status()).toBe(201);
|
||||
await expect(note).toHaveValue('');
|
||||
await page.goForward();
|
||||
await expect(page.getByRole('heading', { name: `Synthetic note B ${lang}` })).toBeVisible();
|
||||
await expect(note).toHaveValue('Draft for B — æøå');
|
||||
expect(await page.evaluate(() => performance.timeOrigin)).toBe(origin);
|
||||
const [owned, other] = await Promise.all(ids.map(id => page.request.get(`${messageUrl}/${id}`, { headers })));
|
||||
expect(owned.status()).toBe(200);
|
||||
expect(other.status()).toBe(200);
|
||||
expect(await owned.json()).toMatchObject([{ jobApplicationId: ids[0], content: 'Note for A — æøå' }]);
|
||||
expect(await other.json()).toEqual([]);
|
||||
await capture(page, info, `correspondence-round-trip-${lang}`);
|
||||
} finally { release(); }
|
||||
});
|
||||
}
|
||||
|
||||
test('[PRES-W01 W08 M01 E08] Job section loading and partial read failures stay explicit and recover locally', async ({ page }, info) => {
|
||||
const headers = await login(page.request, 'e2e@example.test');
|
||||
const company = await page.request.post(`${apiUrl}/companies`, { headers, data: { name: 'Section state fixture' } });
|
||||
|
||||
@@ -84,9 +84,6 @@ export type CorrespondenceJobContext = {
|
||||
jobTitle?: string | null;
|
||||
};
|
||||
|
||||
type ManualDraft = { from: "Me" | "Company"; text: string; rawEmail: string; saving: boolean };
|
||||
const emptyManualDraft: ManualDraft = { from: "Me", text: "", rawEmail: "", saving: false };
|
||||
|
||||
export function buildSuggestedCorrespondenceQueries(
|
||||
context: CorrespondenceJobContext,
|
||||
subjects: Array<string | null | undefined>,
|
||||
@@ -135,13 +132,15 @@ export default function Correspondence({ jobId, jobContext }: { jobId: number; j
|
||||
const [messagesLoading, setMessagesLoading] = useState(true);
|
||||
const [messagesError, setMessagesError] = useState<{ cause: unknown } | null>(null);
|
||||
const messageRequest = useRef(0);
|
||||
const [manualDrafts, setManualDrafts] = useState<Record<number, ManualDraft>>({});
|
||||
const { from, text, rawEmail, saving: manualSaving } = manualDrafts[jobId] ?? emptyManualDraft;
|
||||
const manualWrites = useRef(new Set<number>());
|
||||
const [from, setFrom] = useState<"Me" | "Company">("Me");
|
||||
const [text, setText] = useState("");
|
||||
const [manualSaving, setManualSaving] = useState(false);
|
||||
const manualSavingRef = useRef(false);
|
||||
const scrollRef = useRef<HTMLDivElement | null>(null);
|
||||
|
||||
const [importOpen, setImportOpen] = useState(false);
|
||||
const [importTab, setImportTab] = useState(0);
|
||||
const [rawEmail, setRawEmail] = useState("");
|
||||
|
||||
const [gmailStatus, setGmailStatus] = useState<GmailStatus | null>(null);
|
||||
const [gmailLoading, setGmailLoading] = useState(false);
|
||||
@@ -172,6 +171,8 @@ export default function Correspondence({ jobId, jobContext }: { jobId: number; j
|
||||
const session = gmailOAuth.current;
|
||||
session.active = true;
|
||||
session.jobId = jobId;
|
||||
manualSavingRef.current = false;
|
||||
setManualSaving(false);
|
||||
setLinkedThreadRefresh(null);
|
||||
setLinkedThreadRefreshLoading(false);
|
||||
setImportingMessageId(null);
|
||||
@@ -377,41 +378,39 @@ export default function Correspondence({ jobId, jobContext }: { jobId: number; j
|
||||
subject: t("correspondenceSubject"),
|
||||
});
|
||||
|
||||
const updateManualDraft = (changes: Partial<ManualDraft>) => {
|
||||
setManualDrafts(drafts => ({ ...drafts, [jobId]: { ...(drafts[jobId] ?? emptyManualDraft), ...changes } }));
|
||||
};
|
||||
|
||||
const setManualWrite = (saving: boolean) => {
|
||||
if (saving) manualWrites.current.add(jobId);
|
||||
else manualWrites.current.delete(jobId);
|
||||
updateManualDraft({ saving });
|
||||
};
|
||||
|
||||
const isCurrentJob = () => gmailOAuth.current.active && gmailOAuth.current.jobId === jobId;
|
||||
|
||||
const send = async () => {
|
||||
if (!canSend || !isCurrentJob() || manualWrites.current.has(jobId)) return;
|
||||
setManualWrite(true);
|
||||
if (!canSend || manualSavingRef.current) return;
|
||||
const session = gmailOAuth.current;
|
||||
const generation = session.generation;
|
||||
manualSavingRef.current = true;
|
||||
setManualSaving(true);
|
||||
try {
|
||||
await api.post("/correspondence", { jobApplicationId: jobId, from, content: text });
|
||||
updateManualDraft({ text: "" });
|
||||
if (isCurrentJob()) await load().catch(() => undefined);
|
||||
if (!session.active || generation !== session.generation) return;
|
||||
setText("");
|
||||
await load().catch(() => undefined); // The read notice owns refresh failure after a committed write.
|
||||
} catch (error) {
|
||||
if (isCurrentJob()) toast(getApiErrorMessage(error, startupTranslation.current("correspondenceAddFailed")), "error");
|
||||
if (session.active && generation === session.generation) toast(getApiErrorMessage(error, startupTranslation.current("correspondenceAddFailed")), "error");
|
||||
} finally {
|
||||
setManualWrite(false);
|
||||
if (session.active && generation === session.generation) {
|
||||
manualSavingRef.current = false;
|
||||
setManualSaving(false);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const importEmail = async () => {
|
||||
if (!isCurrentJob() || manualWrites.current.has(jobId)) return;
|
||||
if (manualSavingRef.current) return;
|
||||
const parsed = parseRawEmail(rawEmail);
|
||||
if (!parsed.body && !parsed.subject && !rawEmail.trim()) {
|
||||
toast(t("addJobModalPasteUrlFirst"), "error");
|
||||
return;
|
||||
}
|
||||
|
||||
setManualWrite(true);
|
||||
const session = gmailOAuth.current;
|
||||
const generation = session.generation;
|
||||
manualSavingRef.current = true;
|
||||
setManualSaving(true);
|
||||
try {
|
||||
await api.post("/correspondence", {
|
||||
jobApplicationId: jobId,
|
||||
@@ -423,15 +422,18 @@ export default function Correspondence({ jobId, jobContext }: { jobId: number; j
|
||||
externalFrom: parsed.from ?? null,
|
||||
externalTo: parsed.to ?? null,
|
||||
});
|
||||
updateManualDraft({ rawEmail: "" });
|
||||
if (!isCurrentJob()) return;
|
||||
if (!session.active || generation !== session.generation) return;
|
||||
setImportOpen(false);
|
||||
setRawEmail("");
|
||||
await load().catch(() => undefined);
|
||||
if (isCurrentJob()) toast(startupTranslation.current("correspondenceLogEmail"), "success");
|
||||
toast(startupTranslation.current("correspondenceLogEmail"), "success");
|
||||
} catch (error) {
|
||||
if (isCurrentJob()) toast(getApiErrorMessage(error, startupTranslation.current("addJobModalImportFailed")), "error");
|
||||
if (session.active && generation === session.generation) toast(getApiErrorMessage(error, startupTranslation.current("addJobModalImportFailed")), "error");
|
||||
} finally {
|
||||
setManualWrite(false);
|
||||
if (session.active && generation === session.generation) {
|
||||
manualSavingRef.current = false;
|
||||
setManualSaving(false);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
@@ -689,14 +691,14 @@ export default function Correspondence({ jobId, jobContext }: { jobId: number; j
|
||||
</Box>
|
||||
|
||||
<Box sx={{ display: "flex", gap: 1, alignItems: "flex-start", mt: 1.5, flexWrap: "wrap" }}>
|
||||
<ToggleButtonGroup disabled={manualSaving} exclusive value={from} onChange={(_, v) => v && updateManualDraft({ from: v })} size="small">
|
||||
<ToggleButtonGroup disabled={manualSaving} exclusive value={from} onChange={(_, v) => v && setFrom(v)} size="small">
|
||||
<ToggleButton value="Me">{t("correspondenceMe")}</ToggleButton>
|
||||
<ToggleButton value="Company">{t("correspondenceCompany")}</ToggleButton>
|
||||
</ToggleButtonGroup>
|
||||
|
||||
<Button disabled={manualSaving} variant="outlined" size="small" onClick={() => setImportOpen(true)}>{t("correspondenceImportEmail")}</Button>
|
||||
|
||||
<TextField disabled={manualSaving} label={t("correspondenceLogNoteOrMessage")} value={text} onChange={(e) => updateManualDraft({ text: e.target.value })} multiline minRows={3} sx={{ flex: { xs: "1 1 100%", sm: "1 1 320px" }, minWidth: 0 }} slotProps={{ formHelperText: { disabled: false } }} helperText={t("correspondenceCharacters", { count: text.length })} />
|
||||
<TextField disabled={manualSaving} label={t("correspondenceLogNoteOrMessage")} value={text} onChange={(e) => setText(e.target.value)} multiline minRows={3} sx={{ flex: { xs: "1 1 100%", sm: "1 1 320px" }, minWidth: 0 }} slotProps={{ formHelperText: { disabled: false } }} helperText={t("correspondenceCharacters", { count: text.length })} />
|
||||
|
||||
<Button variant="contained" onClick={send} disabled={!canSend || manualSaving}>{t("correspondenceAdd")}</Button>
|
||||
</Box>
|
||||
@@ -747,7 +749,7 @@ export default function Correspondence({ jobId, jobContext }: { jobId: number; j
|
||||
{importTab === 0 ? (
|
||||
<>
|
||||
<Typography sx={{ color: "text.secondary", mb: 1 }}>{t("correspondencePasteEmailHelp")}</Typography>
|
||||
<TextField disabled={manualSaving} label={t("correspondencePasteEmail")} multiline minRows={10} fullWidth value={rawEmail} onChange={(e) => updateManualDraft({ rawEmail: e.target.value })} placeholder={t("correspondencePasteEmailPlaceholder")} />
|
||||
<TextField disabled={manualSaving} label={t("correspondencePasteEmail")} multiline minRows={10} fullWidth value={rawEmail} onChange={(e) => setRawEmail(e.target.value)} placeholder={t("correspondencePasteEmailPlaceholder")} />
|
||||
</>
|
||||
) : (
|
||||
<Box sx={{ display: "flex", flexDirection: "column", gap: 2 }}>
|
||||
|
||||
@@ -138,39 +138,6 @@ test.each(["success", "failure"])("an old job's pending note %s cannot clear the
|
||||
expect(client.get.mock.calls).toEqual(reads);
|
||||
});
|
||||
|
||||
test.each(["success", "failure"])("a pending note stays with its job through a round trip and settles with %s", async outcome => {
|
||||
const pending = deferred();
|
||||
client.post.mockReturnValue(pending.promise);
|
||||
client.get.mockImplementation(url => Promise.resolve({
|
||||
data: String(url).startsWith("/correspondence/") ? [] : { connected: false },
|
||||
} as any));
|
||||
const rendered = render(view());
|
||||
const note = () => screen.getByLabelText(translations.en.correspondenceLogNoteOrMessage);
|
||||
const add = () => screen.getByRole("button", { name: translations.en.correspondenceAdd });
|
||||
fireEvent.change(note(), { target: { value: "Only for application A" } });
|
||||
fireEvent.click(add());
|
||||
await act(async () => rendered.rerender(view(43)));
|
||||
expect(note()).toHaveValue("");
|
||||
fireEvent.change(note(), { target: { value: "Only for application B" } });
|
||||
|
||||
await act(async () => rendered.rerender(view()));
|
||||
expect(note()).toHaveValue("Only for application A");
|
||||
expect(add()).toBeDisabled();
|
||||
fireEvent.click(add());
|
||||
expect(client.post).toHaveBeenCalledTimes(1);
|
||||
expect(client.post).toHaveBeenCalledWith("/correspondence", {
|
||||
jobApplicationId: 42, from: "Me", content: "Only for application A",
|
||||
});
|
||||
await act(async () => {
|
||||
if (outcome === "success") pending.resolve({ data: {} });
|
||||
else pending.reject(new Error("synthetic save failure"));
|
||||
});
|
||||
expect(note()).toHaveValue(outcome === "success" ? "" : "Only for application A");
|
||||
expect(note()).toBeEnabled();
|
||||
await act(async () => rendered.rerender(view(43)));
|
||||
expect(note()).toHaveValue("Only for application B");
|
||||
});
|
||||
|
||||
test("a newer refresh after note commitment wins over the original delayed read", async () => {
|
||||
const initial = deferred(); let reads = 0;
|
||||
client.get.mockImplementation(url => String(url).startsWith("/correspondence/")
|
||||
@@ -277,7 +244,6 @@ test.each(["success", "failure"])("old-job pasted-email %s cannot close or clear
|
||||
const rendered = render(view()); const { submit } = await openRawEmail(); fireEvent.click(submit);
|
||||
rendered.rerender(view(43));
|
||||
const next = within(screen.getByRole("dialog")).getByRole("textbox");
|
||||
expect(next).toHaveValue("");
|
||||
fireEvent.change(next, { target: { value: "Next application email draft" } });
|
||||
const reads = [...client.get.mock.calls];
|
||||
await act(async () => {
|
||||
@@ -287,8 +253,6 @@ test.each(["success", "failure"])("old-job pasted-email %s cannot close or clear
|
||||
expect(screen.getByRole("dialog")).toBeVisible(); expect(next).toHaveValue("Next application email draft");
|
||||
expect(client.get.mock.calls).toEqual(reads);
|
||||
expect(screen.queryByText(translations.en.addJobModalImportFailed)).not.toBeInTheDocument();
|
||||
await act(async () => rendered.rerender(view()));
|
||||
expect(within(screen.getByRole("dialog")).getByRole("textbox")).toHaveValue(outcome === "success" ? "" : rawEmail);
|
||||
});
|
||||
|
||||
test("pasted-email source has a visible accessible label", async () => {
|
||||
|
||||
Reference in New Issue
Block a user