Compare commits
3 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 68f33253a8 | |||
| 89128e1c33 | |||
| 7a2b8a95c1 |
@@ -5,7 +5,6 @@
|
||||
<Nullable>enable</Nullable>
|
||||
<IsPackable>false</IsPackable>
|
||||
<RestorePackagesWithLockFile>true</RestorePackagesWithLockFile>
|
||||
<DefaultItemExcludes>$(DefaultItemExcludes);PdfBrowserStub/**</DefaultItemExcludes>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
@@ -25,19 +24,14 @@
|
||||
<ProjectReference Include="..\JobTrackerApi\JobTrackerApi.csproj" />
|
||||
<!-- Build the fixture, but only our explicit subdirectory copy owns its output.
|
||||
The Linux apphost has no .exe suffix and collides with that directory if copied to root. -->
|
||||
<ProjectReference Include="PdfBrowserStub/PdfBrowserStub.csproj" ReferenceOutputAssembly="false" Private="false" OutputItemType="PdfBrowserStubAssembly" />
|
||||
<ProjectReference Include="PdfBrowserStub/PdfBrowserStub.csproj" ReferenceOutputAssembly="false" Private="false" />
|
||||
<Compile Remove="PdfBrowserStub/**/*.cs" />
|
||||
</ItemGroup>
|
||||
|
||||
<Target Name="CopyPdfBrowserStub" AfterTargets="Build">
|
||||
<Error Condition="'@(PdfBrowserStubAssembly)' == ''" Text="The PDF browser stub project returned no output assembly." />
|
||||
<PropertyGroup>
|
||||
<PdfBrowserStubOutput>@(PdfBrowserStubAssembly->'%(RootDir)%(Directory)%(Filename)')</PdfBrowserStubOutput>
|
||||
</PropertyGroup>
|
||||
<ItemGroup>
|
||||
<PdfBrowserFiles Include="$(PdfBrowserStubOutput).*" />
|
||||
<!-- The Unix apphost is the only fixture file without an extension. -->
|
||||
<PdfBrowserFiles Include="$(PdfBrowserStubOutput)" Condition="$([System.IO.File]::Exists('$(PdfBrowserStubOutput)'))" />
|
||||
<PdfBrowserFiles Include="PdfBrowserStub/bin/$(Configuration)/net9.0/*" />
|
||||
</ItemGroup>
|
||||
<Copy SourceFiles="@(PdfBrowserFiles)" DestinationFolder="$(TargetDir)PdfBrowserStub" SkipUnchangedFiles="true" />
|
||||
<Copy SourceFiles="@(PdfBrowserFiles)" DestinationFolder="$(TargetDir)PdfBrowserStub" />
|
||||
</Target>
|
||||
</Project>
|
||||
|
||||
@@ -934,6 +934,32 @@ public sealed class ProfileCvControllerTests
|
||||
Assert.Contains("42", json, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData("Expérience", "Expe\u0301rience", "## Éducation")]
|
||||
[InlineData("Γλώσσες", "Γλώσσες", "## Εκπαίδευση")]
|
||||
[InlineData("Språk", "Languages", "## Utdanning")]
|
||||
[InlineData("Portfolio – 2026", "Portfolio – 2026", "## Certificates")]
|
||||
[InlineData("Expérience", "Expérience", "Projets supplémentaires")]
|
||||
[InlineData("Språk", "Languages", "Utdanning:")]
|
||||
public async Task Rewrite_preview_replaces_only_the_selected_document_section(string heading, string selected, string nextHeading)
|
||||
{
|
||||
var source = $"## {heading}\r\n\r\nTravail en équipe\r\nOriginal work.\r\n{nextHeading}\r\nKeep this content.";
|
||||
var user = new ApplicationUser { Id = "user-1", ProfileCvText = source };
|
||||
var users = CreateUserManager();
|
||||
users.Setup(x => x.GetUserAsync(It.IsAny<ClaimsPrincipal>())).ReturnsAsync(user);
|
||||
var ai = new Mock<ISummarizerService>();
|
||||
ai.Setup(x => x.SummarizeSectionAsync(It.IsAny<string>(), It.IsAny<string>(), 900, 180))
|
||||
.ReturnsAsync("Updated work.");
|
||||
await using var db = CreateDb();
|
||||
var controller = CreateController(users.Object, ai.Object, db, CreatePaths());
|
||||
var action = await controller.BuildRewritePreview(new ProfileCvController.RewriteSectionRequest { SectionName = selected });
|
||||
var preview = Assert.IsType<ProfileCvPreviewDto>(Assert.IsType<OkObjectResult>(action.Result).Value);
|
||||
|
||||
Assert.Equal($"## {heading}\nUpdated work.\n\n{nextHeading}\nKeep this content.", preview.FullText.ReplaceLineEndings("\n"));
|
||||
ai.Verify(x => x.SummarizeSectionAsync(It.IsAny<string>(), It.Is<string>(text => text.Contains("Original work.") && !text.Contains("Keep this content.")), 900, 180), Times.Once);
|
||||
Assert.Equal(source, user.ProfileCvText);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Parse_returns_structured_cv_and_persists_it()
|
||||
{
|
||||
|
||||
@@ -581,6 +581,9 @@ public sealed partial class ProfileCvController : ControllerBase
|
||||
: string.Join("\n\n", structuredCv.Sections.Select(section => $"## {section.Name}\n{section.Content}"));
|
||||
}
|
||||
|
||||
if (sourceText is not null && FindRewriteSection(sourceText, sectionName) is { } range)
|
||||
return sourceText[range.Start..range.End].Trim();
|
||||
|
||||
var matchingSection = structuredCv.Sections.FirstOrDefault(section => string.Equals(section.Name, sectionName, StringComparison.OrdinalIgnoreCase));
|
||||
if (matchingSection is not null && !string.IsNullOrWhiteSpace(matchingSection.Content))
|
||||
{
|
||||
@@ -618,6 +621,33 @@ public sealed partial class ProfileCvController : ControllerBase
|
||||
return null;
|
||||
}
|
||||
|
||||
private static readonly Regex RewriteHeading = new(
|
||||
@"^(?:(?<marker>#{1,2})[ \t]+(?<name>[^\r\n]+?)|(?<name>[\p{Lu}\p{Lt}][\p{L}\p{M} &/]+?))(?<colon>:)?[ \t]*\r?$",
|
||||
RegexOptions.Multiline | RegexOptions.CultureInvariant);
|
||||
|
||||
private static (int Start, int End, string Name)? FindRewriteSection(string text, string sectionName)
|
||||
{
|
||||
var target = NormalizeRewriteSectionName(sectionName.Normalize());
|
||||
foreach (Match heading in RewriteHeading.Matches(text))
|
||||
{
|
||||
var name = heading.Groups["name"].Value.Trim();
|
||||
if (!string.Equals(NormalizeRewriteSectionName(name.Normalize()), target, StringComparison.OrdinalIgnoreCase))
|
||||
continue;
|
||||
var next = heading.NextMatch();
|
||||
if (heading.Groups["marker"].Success && next.Success &&
|
||||
!next.Groups["marker"].Success && !next.Groups["colon"].Success &&
|
||||
!SectionAliases.ContainsKey(next.Groups["name"].Value.Trim()))
|
||||
{
|
||||
// The first unmarked line may be prose. Preserve later legacy headings even without a blank separator.
|
||||
var bodyStart = heading.Index + heading.Length;
|
||||
if (text.AsSpan(bodyStart, next.Index - bodyStart).Trim().IsEmpty)
|
||||
next = next.NextMatch();
|
||||
}
|
||||
return (heading.Index, next.Success ? next.Index : text.Length, name);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private static string ReplaceOrAppendCvSection(string source, string sectionName, string sectionDraft)
|
||||
{
|
||||
var trimmedSource = (source ?? string.Empty).Trim();
|
||||
@@ -625,20 +655,14 @@ public sealed partial class ProfileCvController : ControllerBase
|
||||
if (string.IsNullOrWhiteSpace(trimmedDraft)) return trimmedSource;
|
||||
if (string.IsNullOrWhiteSpace(trimmedSource)) return $"## {sectionName}\n{trimmedDraft}";
|
||||
|
||||
var normalizedHeading = sectionName.Trim().ToLowerInvariant();
|
||||
var headingPattern = new Regex(@"^(##\s+|#\s+)?(?<name>[A-Z][A-Za-z &/]+):?\s*$", RegexOptions.Multiline);
|
||||
var matches = headingPattern.Matches(trimmedSource).ToList();
|
||||
var targetIndex = matches.FindIndex(match => string.Equals(match.Groups["name"].Value.Trim(), normalizedHeading, StringComparison.OrdinalIgnoreCase));
|
||||
if (targetIndex < 0)
|
||||
if (FindRewriteSection(trimmedSource, sectionName) is not { } range)
|
||||
{
|
||||
return $"{trimmedSource}\n\n## {sectionName}\n{trimmedDraft}".Trim();
|
||||
}
|
||||
|
||||
var start = matches[targetIndex].Index;
|
||||
var end = targetIndex + 1 < matches.Count ? matches[targetIndex + 1].Index : trimmedSource.Length;
|
||||
var before = trimmedSource[..start].TrimEnd();
|
||||
var after = trimmedSource[end..].TrimStart();
|
||||
return string.Join("\n\n", new[] { before, $"## {sectionName}\n{trimmedDraft}", after }.Where(part => !string.IsNullOrWhiteSpace(part))).Trim();
|
||||
var before = trimmedSource[..range.Start].TrimEnd();
|
||||
var after = trimmedSource[range.End..].TrimStart();
|
||||
return string.Join("\n\n", new[] { before, $"## {range.Name}\n{trimmedDraft}", after }.Where(part => !string.IsNullOrWhiteSpace(part))).Trim();
|
||||
}
|
||||
|
||||
private static IReadOnlyList<CvTemplateDescriptor> GetCvTemplateDescriptors()
|
||||
|
||||
@@ -1,15 +0,0 @@
|
||||
# PDF admission test fixture
|
||||
|
||||
Verified on Windows x64 with SDK 9.0.317, VSTest 17.14.1 and a locked restore from the local NuGet package cache. The source baseline was `245f2feaa8bee2db8f5da0797b3e33f6ef8b056e`.
|
||||
|
||||
| Build | Test selection | Result |
|
||||
| --- | --- | --- |
|
||||
| Before fix, Release with a fresh `--artifacts-path` | `Default_limit_refuses_second_actual_browser_until_first_exits` | FAILED. The SDK built the stub in the requested location. The test output lacked the stub and the exporter reported that no browser was available. |
|
||||
| After fix, Release with a fresh `--artifacts-path` | `PdfRenderAdmissionTests` | PASSED, 22 of 22. |
|
||||
| After fix, Debug with the conventional output directory | `PdfRenderAdmissionTests` | PASSED, the same 22 of 22. |
|
||||
|
||||
Both successful runs built and launched the fixture through `dotnet test`. In each output layout the fixture directory contained exactly the apphost, assembly, symbols, dependency manifest and runtime configuration. All five SHA-256 hashes matched the corresponding stub project output. The conventional stub project's `bin` and `obj` directories already existed during the final relocated run and were excluded from the test content.
|
||||
|
||||
To repeat with restored dependencies, use `dotnet test JobTrackerApi.Tests/JobTrackerApi.Tests.csproj -c Debug --filter FullyQualifiedName~PdfRenderAdmissionTests`. For the relocated case, use `-c Release` and add `--artifacts-path <fresh-directory>`.
|
||||
|
||||
These tests exercise local process admission, cancellation and cleanup with the synthetic browser. Linux execution, visual PDF acceptance and production rendering remain separate qualifications.
|
||||
@@ -20,3 +20,33 @@ No fresh export build/native browser journey, real API/session/cookie-switch int
|
||||
Evidence is under [cv-library-lifetime](evidence/cv-library-lifetime/SOURCE_RECEIPTS.json). Normalised source hashes and raw receipt hashes bind this bounded result.
|
||||
|
||||
AST graph refresh PASSED on an exact 1,003-file tracked-code snapshot on E: (E:/Storage/Projects/Active/temp docs/jobjakt-local-build/a3-cv-library-source). SOURCE_MANIFEST.json binds files to source commit de2fb452; 10,345 nodes and 36,111 edges. 51 no-symbol warnings retained. Code-only snapshot excludes documentation. Stale generated integration graph: all 2,721 files (97,063,540 bytes) preserved and SHA256-verified on E before replacing its C directory with a junction; no tracked source or evidence removed.
|
||||
|
||||
## Concurrent rename in the library · 20 November 2026
|
||||
|
||||
On application source `7a2b8a95c146d67bc4584740e4a72740cfc25cbf`, the rename dialog opened with the listed name. After confirmation the library fetched the current CV and used its latest revision and settings to write the requested name. A second editor could rename the same CV while that dialog was open. The subsequent write adopted the second editor’s revision and silently replaced their name. If both editors chose the same name the redundant write also created a revision.
|
||||
|
||||
The library now compares the name shown in the dialog with the name returned by the existing detail read. When they differ it shows the latest persisted name and skips the write. If the requested name differs as well, the existing localised conflict message appears. A user can reopen Rename on the current name and explicitly retry. A concurrent change confined to settings still allows a rename, using the latest settings and expected revision. A change after the detail read remains subject to server revision checks.
|
||||
|
||||
**Reproduction and verification.** Both added component cases failed on the original source because a PUT was issued. The corrected combined run passed **77 distinct cases in three suites** (47 CV library, 15 CV helpers, 15 session boundary), zero failed or skipped. The conflict case verifies an explicit retry sends exactly one PUT with the current revision and settings. The equal-name case verifies zero PUTs and no conflict alert. TypeScript, scoped ESLint and Git whitespace checks passed. Raw Jest results are in the local `cv-library-rename-verification` evidence directory. SHA-256 values are `1841f3d9e7199d6f8e6deb886d2581a93f36b66273e3083075e5fd2dd2a46ba5` (red) and `8db570ffa120e80dc047db98ad2f3368a586cd35791a164343ee150742312495` (final). An intermediate invocation included a misspelled suite path and exited 1. Its two successful suites and the separate corrected session-suite run overlap the final 77.
|
||||
|
||||
**Evidence scope.** The tests render the real library and prompt with mocked transport. A native two-tab/browser run, real database writes, PDF rendering and full integrated acceptance were outside this execution. The earlier 85-case verification above is historical. The changed library source blob is `4b5018c6e549a4c5711dcc84a00082629af0ef80` and test blob is `448f46e977f4c733b3d99265e500fed8ee7779bf`.
|
||||
|
||||
The AST-only Graphify refresh completed with 20,198 nodes and 50,033 edges. SQL extraction was unavailable and 146 source files yielded no symbols.
|
||||
|
||||
## Native two-tab rename and SQLite readback · 20 November 2026
|
||||
|
||||
Application source `89128e1c33378bf2c65f2f28b048a63957772eb7`. Two Chromium tabs shared a signed-in synthetic owner and the same CV. Tab one opened Rename on revision 1. Tab two renamed the CV through its library and committed revision 2. Tab one submitted its still-open draft, saw the conflict and the persisted name, and issued **zero PUTs**. After the owner reopened Rename and reviewed that name, tab one issued exactly one PUT with expected revision 2. A reload in tab two displayed the reviewed name. The variant and history APIs returned revisions 1, 2, 3. A separate read-only SQLite query against the disposable database verified exactly those three rows and identical stored settings at each revision.
|
||||
|
||||
**Passed.** Two native cases ran with one worker, zero retries, zero skips and zero flaky results. The new pre-read conflict case took 7.7 s. The existing post-read race took 4.7 s and received the real server 409 before an explicit retry. Both used a freshly built .NET 9.0.317 Release API, a unique local SQLite data root and a fresh static export. The .NET build had zero warnings or errors. The exact-lock Next 16.4.6 build completed compilation, TypeScript and static generation. The three component suites passed all 77 cases on the same dependencies; these overlap the 77 earlier cases. Scoped ESLint, whitespace and the AST refresh passed (20,199 nodes and 50,038 edges).
|
||||
|
||||
**Build recovery.** The initial webpack attempt used a cross-drive dependency junction which resolved Next 16.4.1 and failed module resolution. An independent offline `npm ci` installed 806 packages from the lockfile. The successful runs used Next 16.4.6, Jest 30.4.2 and Playwright 1.62.1. The npm log retained dependency deprecation notices and a pending install script for the resolver. No dependency versions changed. The local API emitted its existing SQLite migration and development key-storage warnings. This run did not qualify production migrations, backup/restore or key storage.
|
||||
|
||||
| Evidence | Identity |
|
||||
| --- | --- |
|
||||
| New browser test, Git blob | `a57a77d87a377ae26ac0869469ab04732d93249b` |
|
||||
| Dependency lock, Git blob | `4c277d454e1164b1e24f21f463b5251052e53eaa` |
|
||||
| Playwright JSON, SHA-256 | `861352d6c00beb09d6e7fee5f0e596992d4eb2658fe07a65c0599f81e344ad10` |
|
||||
| Pinned Jest JSON, SHA-256 | `b6b5fd043f750e5a979f5ba70f81c86e314303eaaf707339b3fbc490a06d980b` |
|
||||
| Static export index / Release API DLL, SHA-256 | `78a5db16a0e85d8f3ead4cb6431d7fd021148b6d02d38007a4701769fb9f7e39` / `769e32f5c4f8bac61743dce67748dd5198cbbc472c8c6c1630ccefe81a1c91d2` |
|
||||
|
||||
Raw receipts are under `E:/Storage/Projects/Active/temp docs/jobjakt-local-build/cv-library-rename-verification/`. Reproduce with the existing isolated static-export Playwright configuration and `phase7-cv-library.spec.ts --grep 'two library tabs|concurrent rename receives ordinary409' --workers=1 --retries=0`. Both loopback servers stopped at completion. Browser coverage was desktop Chromium in English, on synthetic local SQLite records. MariaDB, human/device checks, PDF rendering, full A3, integrated security and release acceptance remain open.
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { expect, test as base, type APIRequestContext, type APIResponse, type Page, type Response, type TestInfo } from '@playwright/test';
|
||||
import AxeBuilder from '@axe-core/playwright';
|
||||
import { translations } from '../src/i18n/translations';
|
||||
import type { CvTheme, CvVariant, CvVariantSummary } from '../src/cvBuilder';
|
||||
import type { CvTheme, CvVariant, CvVariantSummary, CvVariantVersionInfo } from '../src/cvBuilder';
|
||||
import { emptyStructuredCv } from '../src/profileCv';
|
||||
import { readFile } from 'node:fs/promises';
|
||||
import { createHash } from 'node:crypto';
|
||||
@@ -416,6 +416,60 @@ test('[P7-04 PRES-C05 C07 C10 W07] keyboard rename duplicate and delete persist
|
||||
sourceUnchanged: true, frozenUnchanged: true, qualification: 'Actual HTTP rename/duplicate/delete and frozen DTO readback; held duplicate continues the real request. Frozen DTO equality is not archived PDF-byte or restore qualification.' }), contentType: 'application/json' });
|
||||
});
|
||||
|
||||
test('[P7-04 PRES-C05 C10] two library tabs preserve a concurrent name and allow an explicit retry', async ({ page, context, owner }, info) => {
|
||||
const original = await createVariant(page.request, owner, 'Two-tab source CV');
|
||||
const variantUrl = `${apiUrl}/cv/variants/${original.id}`;
|
||||
const versions = async () => (await json<CvVariantVersionInfo[]>(await page.request.get(`${variantUrl}/versions`)))
|
||||
.map(item => item.version).sort((left, right) => left - right);
|
||||
const originalVersions = await versions();
|
||||
const secondTab = await context.newPage();
|
||||
const label = translations.en.cvDashboardRename;
|
||||
const firstChoice = 'CV for school applications';
|
||||
const secondChoice = 'CV for tutoring applications';
|
||||
const writes: number[] = [];
|
||||
page.on('request', request => {
|
||||
if (request.url() === variantUrl && request.method() === 'PUT') writes.push(request.postDataJSON().expectedVersion);
|
||||
});
|
||||
const submit = (tab: Page) => tab.getByRole('dialog').getByRole('button', { name: label, exact: true }).click();
|
||||
const saved = (tab: Page) => tab.waitForResponse(response => response.url() === variantUrl && response.request().method() === 'PUT');
|
||||
|
||||
await enter(page, owner);
|
||||
await enter(secondTab, owner);
|
||||
await openAction(page, original.name, label);
|
||||
await page.getByRole('dialog').getByRole('textbox').fill(firstChoice);
|
||||
|
||||
await openAction(secondTab, original.name, label);
|
||||
await secondTab.getByRole('dialog').getByRole('textbox').fill(secondChoice);
|
||||
const [otherResponse] = await Promise.all([saved(secondTab), submit(secondTab)]);
|
||||
const other = await json<CvVariant>(otherResponse);
|
||||
expect(other).toMatchObject({ name: secondChoice, settings: original.settings, version: original.version + 1 });
|
||||
await expect(card(secondTab, secondChoice)).toBeVisible();
|
||||
|
||||
await submit(page);
|
||||
await expect(page.getByRole('alert').filter({ hasText: translations.en.cvEditorConflict })).toBeVisible();
|
||||
await expect(card(page, secondChoice)).toBeVisible();
|
||||
expect(writes).toEqual([]);
|
||||
expect(await json<CvVariant>(await page.request.get(variantUrl))).toEqual(other);
|
||||
expect(await versions()).toEqual([...originalVersions, other.version]);
|
||||
|
||||
await openAction(page, secondChoice, label);
|
||||
const retry = page.getByRole('dialog').getByRole('textbox');
|
||||
await expect(retry).toHaveValue(secondChoice);
|
||||
await retry.fill(firstChoice);
|
||||
const [retryResponse] = await Promise.all([saved(page), submit(page)]);
|
||||
const reviewed = await json<CvVariant>(retryResponse);
|
||||
expect(writes).toEqual([other.version]);
|
||||
expect(reviewed).toMatchObject({ name: firstChoice, settings: original.settings, version: other.version + 1 });
|
||||
expect(await json<CvVariant>(await page.request.get(variantUrl))).toEqual(reviewed);
|
||||
expect(await versions()).toEqual([...originalVersions, other.version, reviewed.version]);
|
||||
await secondTab.reload();
|
||||
await expect(card(secondTab, firstChoice)).toBeVisible();
|
||||
await info.attach('two-tab-rename-readback', { body: JSON.stringify({
|
||||
initialVersion: original.version, secondTabVersion: other.version, firstTabPutPreconditions: writes,
|
||||
finalVersion: reviewed.version, history: await versions(),
|
||||
}), contentType: 'application/json' });
|
||||
});
|
||||
|
||||
test('[P7-04 PRES-C05 C10] concurrent rename receives ordinary409 and requires owner review before a new save', async ({ page, owner }, info) => {
|
||||
const sourceBefore = await seedSource(page, owner);
|
||||
const original = await createVariant(page.request, owner, 'Recorded conflict CV');
|
||||
|
||||
@@ -509,6 +509,41 @@ test('a rename conflict keeps the original library entry and never retries the w
|
||||
expect(mockedApi.delete).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
test.each(['My proposed name', 'Name from another editor'])(
|
||||
'a concurrent rename preserves the saved title before applying "%s"', async proposedName => {
|
||||
const latest = { ...existingCv, name: 'Name from another editor', version: 7, settings: emptyCvVariantSettings('clean') };
|
||||
mockedApi.get.mockImplementation(async url => ({ data: url === '/cv/variants' ? [existingCv]
|
||||
: url === '/cv/variants/1' ? latest : themes }) as any);
|
||||
mockedApi.put.mockResolvedValue({ data: { ...latest, name: proposedName, version: 8 } } as any);
|
||||
renderPage();
|
||||
await screen.findByText(existingCv.name);
|
||||
await selectAction('Rename');
|
||||
fireEvent.change(await screen.findByRole('textbox'), { target: { value: proposedName } });
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Rename' }));
|
||||
|
||||
await waitFor(() => expect(mockedApi.get).toHaveBeenCalledWith('/cv/variants/1'));
|
||||
await waitFor(() => expect(screen.getByRole('link')).toHaveAttribute('aria-disabled', 'false'));
|
||||
expect(mockedApi.put).not.toHaveBeenCalled();
|
||||
expect(screen.getByRole('link', { name: 'Open Name from another editor' })).toBeInTheDocument();
|
||||
if (proposedName === latest.name) {
|
||||
expect(screen.queryByText('CV changed elsewhere')).not.toBeInTheDocument();
|
||||
return;
|
||||
}
|
||||
expect(screen.getByText('CV changed elsewhere')).toBeInTheDocument();
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Actions for Name from another editor' }));
|
||||
fireEvent.click(await screen.findByRole('menuitem', { name: 'Rename' }));
|
||||
const retry = await screen.findByRole('textbox');
|
||||
expect(retry).toHaveValue(latest.name);
|
||||
fireEvent.change(retry, { target: { value: proposedName } });
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Rename' }));
|
||||
expect(await screen.findByRole('link', { name: 'Open My proposed name' })).toBeInTheDocument();
|
||||
expect(mockedApi.put).toHaveBeenCalledTimes(1);
|
||||
expect(mockedApi.put).toHaveBeenCalledWith('/cv/variants/1', {
|
||||
name: proposedName, settings: latest.settings, source: 'manual', expectedVersion: latest.version,
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
test('cancelling deletion returns focus to the surviving CV action control without removing the CV', async () => {
|
||||
mockedApi.get.mockImplementation(async (url) => ({ data: url === '/cv/variants' ? [existingCv] : themes }) as any);
|
||||
renderPage();
|
||||
|
||||
@@ -173,15 +173,23 @@ export default function CvBuilderPage() {
|
||||
if (!active) return;
|
||||
const current = variants.find((item) => item.id === id);
|
||||
try {
|
||||
const nextName = await promptForValue({ key: "cvDashboardRenameMessage" }, current?.name ?? "", { title: { key: "cvDashboardRenameCv" }, confirmLabel: { key: "cvDashboardRename" } });
|
||||
if (!active() || !nextName?.trim() || nextName.trim() === current?.name) return;
|
||||
const input = await promptForValue({ key: "cvDashboardRenameMessage" }, current?.name ?? "", { title: { key: "cvDashboardRenameCv" }, confirmLabel: { key: "cvDashboardRename" } });
|
||||
const nextName = input?.trim();
|
||||
if (!active() || !nextName || nextName === current?.name) return;
|
||||
setPending(true);
|
||||
const variant = await cvBuilderApi.get(id);
|
||||
if (!active()) return;
|
||||
const updated = await cvBuilderApi.save(id, { name: nextName.trim(), settings: variant.settings, source: "manual", expectedVersion: variant.version });
|
||||
const renamedElsewhere = variant.name !== current?.name;
|
||||
const updated = renamedElsewhere ? variant : await cvBuilderApi.save(id, {
|
||||
name: nextName, settings: variant.settings, source: "manual", expectedVersion: variant.version,
|
||||
});
|
||||
if (!active()) return;
|
||||
setVariants((items) => items.map((item) => item.id === id ? { ...item, name: updated.name, updatedAtUtc: updated.updatedAtUtc, version: updated.version } : item));
|
||||
toast(localeRef.current("cvDashboardRenamed"), "success");
|
||||
if (renamedElsewhere && updated.name !== nextName) {
|
||||
setActionError({ key: "cvEditorConflict" });
|
||||
} else {
|
||||
toast(localeRef.current("cvDashboardRenamed"), "success");
|
||||
}
|
||||
} catch (err) { if (active()) setActionError({ error: err, key: "cvDashboardRenameFailed" }); }
|
||||
finally { finishAction(active); }
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user