Skip to content

Commit e88a993

Browse files
committed
Reject publishing unsaved forms and report storage failures
1 parent 15e597a commit e88a993

14 files changed

Lines changed: 398 additions & 25 deletions

File tree

‎builder-api/src/main/java/org/codeforphilly/bdt/builder/controller/ScreenerResource.java‎

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -253,8 +253,9 @@ public Response saveFormSchema(
253253
storageService.writeJsonToStorage(filePath, request.schema());
254254
return Response.ok().build();
255255
} catch (Exception e) {
256-
Log.info(("Failed to save form for screener " + screenerId));
257-
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
256+
Log.error("Failed to save form for screener " + screenerId, e);
257+
return Response.status(Response.Status.INTERNAL_SERVER_ERROR)
258+
.entity(Map.of("error", "Could not save the form. Please try again.")).build();
258259
}
259260
}
260261

@@ -283,9 +284,12 @@ public Response publishScreener(
283284
Screener screener = screenerOpt.get();
284285
screenerRepository.publishScreener(screener);
285286
return Response.ok().build();
287+
} catch (BadRequestException e) {
288+
return Response.status(Response.Status.BAD_REQUEST).entity(Map.of("error", e.getMessage())).build();
286289
} catch (Exception e) {
287-
Log.error("Error: Error updating screener to published. Screener: " + screenerId);
288-
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
290+
Log.error("Error updating screener to published. Screener: " + screenerId, e);
291+
return Response.status(Response.Status.INTERNAL_SERVER_ERROR)
292+
.entity(Map.of("error", "Could not publish the screener. Please try again.")).build();
289293
}
290294
}
291295

‎builder-api/src/main/java/org/codeforphilly/bdt/builder/persistence/GoogleStorageService.java‎

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -47,7 +47,7 @@ public void writeStringToStorage(String filePath, String content, String content
4747
}
4848

4949
@Override
50-
public void writeBytesToStorage(String filePath, byte[] content, String contentType){
50+
public void writeBytesToStorage(String filePath, byte[] content, String contentType) throws Exception {
5151
try {
5252
BlobId blobId = BlobId.of(bucketName, filePath);
5353
BlobInfo blobInfo = BlobInfo.newBuilder(blobId)
@@ -57,11 +57,12 @@ public void writeBytesToStorage(String filePath, byte[] content, String contentT
5757
Log.info("Uploaded to GCS: " + filePath);
5858
} catch (Exception e){
5959
Log.error("Error writing bytes to GCS: " + e.getMessage());
60+
throw new Exception("Could not write file to cloud storage", e);
6061
}
6162
}
6263

6364
@Override
64-
public void writeJsonToStorage(String filePath, JsonNode json){
65+
public void writeJsonToStorage(String filePath, JsonNode json) throws Exception {
6566
try {
6667
ObjectMapper mapper = new ObjectMapper();
6768
byte[] content = mapper.writeValueAsBytes(json);
@@ -73,6 +74,7 @@ public void writeJsonToStorage(String filePath, JsonNode json){
7374
Log.info("Uploaded to GCS: " + filePath);
7475
} catch (Exception e){
7576
Log.error("Error writing JSON to GCS: " + e.getMessage());
77+
throw new Exception("Could not save JSON to cloud storage", e);
7678
}
7779
}
7880

@@ -189,7 +191,7 @@ public void updatePublishedFormSchemaArtifact(String screenerId, String publishe
189191
Log.info("Working form schema copied to published artifact path for screener: " + screenerId);
190192
} catch (Exception e) {
191193
Log.error("Error updating published form schema in cloud storage:", e);
192-
throw new Exception("Error updating published form schema in cloud storage");
194+
throw new Exception("Error updating published form schema in cloud storage", e);
193195
}
194196
}
195197
}

‎builder-api/src/main/java/org/codeforphilly/bdt/builder/persistence/StorageService.java‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -11,9 +11,9 @@ public interface StorageService {
1111

1212
void writeStringToStorage(String filePath, String content, String contentType) throws Exception;
1313

14-
void writeBytesToStorage(String filePath, byte[] content, String contentType);
14+
void writeBytesToStorage(String filePath, byte[] content, String contentType) throws Exception;
1515

16-
void writeJsonToStorage(String filePath, JsonNode json);
16+
void writeJsonToStorage(String filePath, JsonNode json) throws Exception;
1717

1818
Optional<InputStream> getFileInputStreamFromStorage(String filePath);
1919

‎builder-api/src/main/java/org/codeforphilly/bdt/builder/persistence/impl/ScreenerRepositoryImpl.java‎

Lines changed: 18 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -188,23 +188,31 @@ public void deleteCustomBenefit(String screenerId, String benefitId) throws Exce
188188
/* Publishing logic */
189189
@Override
190190
public void publishScreener(Screener screener) throws Exception {
191-
if (screener.getPublishedScreenerId() == null || screener.getPublishedScreenerId().isEmpty()) {
191+
// A working screener can exist before its form has ever been saved. Check
192+
// storage before creating a public record or changing publication metadata.
193+
String workingFormPath = storageService.getScreenerWorkingFormSchemaPath(screener.getId());
194+
if (storageService.readFormSchema(workingFormPath).isEmpty()) {
195+
throw new jakarta.ws.rs.BadRequestException("Save the form in Form Editor before publishing.");
196+
}
197+
List<Benefit> benefits = this.getBenefitsInScreener(screener);
198+
boolean firstPublish = screener.getPublishedScreenerId() == null || screener.getPublishedScreenerId().isEmpty();
199+
if (firstPublish) {
192200
String publishedScreenerId = publishedScreenerRepository.createPublishedScreener(screener);
193201
screener.setPublishedScreenerId(publishedScreenerId);
194-
} else {
195-
publishedScreenerRepository.updatePublishedScreener(screener.getPublishedScreenerId(), screener);
196202
}
197203

198-
screener.setLastPublishDate(Instant.now().toString());
199-
this.updateWorkingScreener(screener);
200-
204+
storageService.updatePublishedFormSchemaArtifact(
205+
screener.getId(), screener.getPublishedScreenerId()
206+
);
201207
publishedScreenerRepository.refreshPublishedScreenerbenefits(
202208
screener.getPublishedScreenerId(),
203-
this.getBenefitsInScreener(screener)
209+
benefits
204210
);
205211

206-
storageService.updatePublishedFormSchemaArtifact(
207-
screener.getId(), screener.getPublishedScreenerId()
208-
);
212+
screener.setLastPublishDate(Instant.now().toString());
213+
if (!firstPublish) {
214+
publishedScreenerRepository.updatePublishedScreener(screener.getPublishedScreenerId(), screener);
215+
}
216+
this.updateWorkingScreener(screener);
209217
}
210218
}

‎builder-api/src/test/java/org/codeforphilly/bdt/builder/controller/ScreenerResourceTest.java‎

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,8 @@
1010
import com.fasterxml.jackson.databind.ObjectMapper;
1111
import jakarta.ws.rs.NotFoundException;
1212
import org.codeforphilly.bdt.builder.model.dto.screener.EditScreenerRequest;
13+
import org.codeforphilly.bdt.builder.model.dto.screener.PublishScreenerRequest;
14+
import org.codeforphilly.bdt.builder.model.dto.screener.SaveSchemaRequest;
1315
import org.codeforphilly.bdt.builder.persistence.DuplicateScreenerNameException;
1416
import org.codeforphilly.bdt.builder.persistence.ScreenerRepository;
1517
import org.eclipse.microprofile.jwt.JsonWebToken;
@@ -50,6 +52,32 @@ void setUp() {
5052
when(screenerRepository.getWorkingScreener("screener-1")).thenReturn(Optional.of(screener));
5153
}
5254

55+
@Test
56+
void publishReturnsAnActionableErrorForAnUnsavedForm() throws Exception {
57+
when(screenerRepository.getWorkingScreenerMetaDataOnly("screener-1")).thenReturn(Optional.of(screener));
58+
doThrow(new jakarta.ws.rs.BadRequestException("Save the form in Form Editor before publishing."))
59+
.when(screenerRepository).publishScreener(screener);
60+
var request = new PublishScreenerRequest();
61+
request.screenerId = "screener-1";
62+
try (var response = resource.publishScreener(identity, request)) {
63+
assertEquals(400, response.getStatus());
64+
assertEquals(Map.of("error", "Save the form in Form Editor before publishing."), response.getEntity());
65+
}
66+
}
67+
68+
@Test
69+
void failedFormSaveDoesNotReturnSuccess() throws Exception {
70+
resource.validator = mock(jakarta.validation.Validator.class);
71+
var request = new SaveSchemaRequest(new ObjectMapper().readTree("{\"components\":[]}"));
72+
when(resource.validator.validate(request)).thenReturn(java.util.Set.of());
73+
when(storage.getScreenerWorkingFormSchemaPath("screener-1")).thenReturn("form/working/screener-1.json");
74+
doThrow(new Exception("Storage write failed")).when(storage).writeJsonToStorage("form/working/screener-1.json", request.schema());
75+
try (var response = resource.saveFormSchema(identity, "screener-1", request)) {
76+
assertEquals(500, response.getStatus());
77+
assertTrue(((Map<?, ?>) response.getEntity()).get("error").toString().contains("Could not save the form"));
78+
}
79+
}
80+
5381
@Test
5482
void changedNameIsCheckedForUniqueness() throws Exception {
5583
doThrow(new DuplicateScreenerNameException()).when(screenerRepository).renameWorkingScreener(any());
Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
package org.codeforphilly.bdt.builder.persistence;
2+
3+
import com.fasterxml.jackson.databind.ObjectMapper;
4+
import com.google.cloud.storage.Blob;
5+
import com.google.cloud.storage.BlobId;
6+
import com.google.cloud.storage.BlobInfo;
7+
import com.google.cloud.storage.Storage;
8+
import com.google.cloud.storage.StorageException;
9+
import org.junit.jupiter.api.BeforeEach;
10+
import org.junit.jupiter.api.Test;
11+
import java.io.InputStream;
12+
13+
import static org.junit.jupiter.api.Assertions.*;
14+
import static org.mockito.ArgumentMatchers.any;
15+
import static org.mockito.Mockito.*;
16+
17+
class GoogleStorageServiceTest {
18+
private final Storage storage = mock(Storage.class);
19+
private final GoogleStorageService service = new GoogleStorageService();
20+
21+
@BeforeEach
22+
void setup() {
23+
service.storage = storage;
24+
service.bucketName = "test-bucket";
25+
}
26+
27+
@Test
28+
void formSavePropagatesCloudStorageFailures() throws Exception {
29+
var failure = new StorageException(503, "Storage unavailable");
30+
when(storage.createFrom(any(BlobInfo.class), any(InputStream.class))).thenThrow(failure);
31+
var schema = new ObjectMapper().readTree("{\"components\":[]}");
32+
var error = assertThrows(Exception.class, () -> service.writeJsonToStorage("form/working/test.json", schema));
33+
assertSame(failure, error.getCause());
34+
}
35+
36+
@Test
37+
void publishedFormCopyPropagatesDestinationWriteFailures() throws Exception {
38+
var source = mock(Blob.class);
39+
when(storage.get(BlobId.of("test-bucket", "form/working/working.json"))).thenReturn(source);
40+
when(source.exists()).thenReturn(true);
41+
when(source.getContent()).thenReturn("{\"components\":[]}".getBytes(java.nio.charset.StandardCharsets.UTF_8));
42+
var failure = new StorageException(503, "Write unavailable");
43+
when(storage.createFrom(any(BlobInfo.class), any(InputStream.class))).thenThrow(failure);
44+
var error = assertThrows(Exception.class, () -> service.updatePublishedFormSchemaArtifact("working", "public"));
45+
assertSame(failure, error.getCause().getCause());
46+
}
47+
}
Lines changed: 89 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,89 @@
1+
package org.codeforphilly.bdt.builder.persistence.impl;
2+
3+
import jakarta.ws.rs.BadRequestException;
4+
import org.codeforphilly.bdt.builder.model.domain.Screener;
5+
import org.codeforphilly.bdt.builder.persistence.PublishedScreenerRepository;
6+
import org.codeforphilly.bdt.builder.persistence.StorageService;
7+
import org.junit.jupiter.api.BeforeEach;
8+
import org.junit.jupiter.api.Test;
9+
import org.junit.jupiter.api.extension.ExtendWith;
10+
import org.mockito.InjectMocks;
11+
import org.mockito.Mock;
12+
import org.mockito.Spy;
13+
import org.mockito.junit.jupiter.MockitoExtension;
14+
15+
import java.io.IOException;
16+
import java.util.List;
17+
import java.util.Map;
18+
import java.util.Optional;
19+
20+
import static org.junit.jupiter.api.Assertions.*;
21+
import static org.mockito.Mockito.*;
22+
23+
@ExtendWith(MockitoExtension.class)
24+
class ScreenerPublishingTest {
25+
@Mock StorageService storage;
26+
@Mock PublishedScreenerRepository published;
27+
@Spy @InjectMocks ScreenerRepositoryImpl repository;
28+
Screener screener;
29+
30+
@BeforeEach
31+
void setup() {
32+
screener = Screener.create("owner", "Housing", null);
33+
screener.setId("working");
34+
when(storage.getScreenerWorkingFormSchemaPath("working")).thenReturn("form/working/working.json");
35+
}
36+
37+
@Test
38+
void missingFormDoesNotCreateAPublicRecordOrMarkTheScreenerPublished() throws Exception {
39+
when(storage.readFormSchema("form/working/working.json")).thenReturn(Optional.empty());
40+
var error = assertThrows(BadRequestException.class, () -> repository.publishScreener(screener));
41+
assertEquals("Save the form in Form Editor before publishing.", error.getMessage());
42+
assertNull(screener.getPublishedScreenerId());
43+
assertNull(screener.getLastPublishDate());
44+
verifyNoInteractions(published);
45+
verify(repository, never()).updateWorkingScreener(any());
46+
verify(storage, never()).updatePublishedFormSchemaArtifact(anyString(), anyString());
47+
}
48+
49+
@Test
50+
void failedStorageReadIsNotTreatedAsAnUnsavedForm() throws Exception {
51+
var failure = new IOException("Storage unavailable");
52+
when(storage.readFormSchema("form/working/working.json")).thenThrow(failure);
53+
assertSame(failure, assertThrows(IOException.class, () -> repository.publishScreener(screener)));
54+
verifyNoInteractions(published);
55+
verify(repository, never()).updateWorkingScreener(any());
56+
}
57+
58+
@Test
59+
void failedFormCopyDoesNotRefreshBenefitsOrAdvancePublicationMetadata() throws Exception {
60+
savedForm();
61+
screener.setPublishedScreenerId("public");
62+
screener.setLastPublishDate("previous publication");
63+
doThrow(new IOException("Write failed")).when(storage).updatePublishedFormSchemaArtifact("working", "public");
64+
assertThrows(IOException.class, () -> repository.publishScreener(screener));
65+
assertEquals("previous publication", screener.getLastPublishDate());
66+
verifyNoInteractions(published);
67+
verify(repository, never()).updateWorkingScreener(any());
68+
}
69+
70+
@Test
71+
void publicationIsMarkedSuccessfulOnlyAfterArtifactsHaveBeenSaved() throws Exception {
72+
savedForm();
73+
when(published.createPublishedScreener(screener)).thenReturn("public");
74+
doNothing().when(repository).updateWorkingScreener(screener);
75+
repository.publishScreener(screener);
76+
var order = inOrder(storage, published, repository);
77+
order.verify(storage).readFormSchema("form/working/working.json");
78+
order.verify(published).createPublishedScreener(screener);
79+
order.verify(storage).updatePublishedFormSchemaArtifact("working", "public");
80+
order.verify(published).refreshPublishedScreenerbenefits("public", List.of());
81+
order.verify(repository).updateWorkingScreener(screener);
82+
assertNotNull(screener.getLastPublishDate());
83+
}
84+
85+
private void savedForm() throws Exception {
86+
when(storage.readFormSchema("form/working/working.json")).thenReturn(Optional.of(Map.of("components", List.of())));
87+
doReturn(List.of()).when(repository).getBenefitsInScreener(screener);
88+
}
89+
}

‎builder-frontend/src/api/screener.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -106,7 +106,7 @@ export const saveFormSchema = async (screenerId: string, schema: any) => {
106106
const response = await authPost(url.toString(), requestData);
107107

108108
if (!response.ok) {
109-
throw new Error(`Post failed with status: ${response.status}`);
109+
throw await apiErrorFrom(response, "Could not save the form");
110110
}
111111
} catch (error) {
112112
console.error("Error saving form schema:", error);
@@ -131,7 +131,7 @@ export const publishScreener = async (screenerId: string): Promise<void> => {
131131
const response = await authPost(url, { screenerId: screenerId });
132132

133133
if (!response.ok) {
134-
throw new Error(`Submit failed with status: ${response.status}`);
134+
throw await apiErrorFrom(response, "Could not publish the screener");
135135
}
136136
} catch (error) {
137137
console.error("Error submitting form:", error);

‎builder-frontend/src/components/screenerEditor/FormEditorView.bindings.test.tsx‎

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -213,6 +213,36 @@ it("defaults the key of a newly added field to its ID", async () => {
213213
await vi.waitFor(() => expect(added.key).toBe(added.id));
214214
});
215215

216+
it("can explicitly save the initialized form before any fields are edited", async () => {
217+
vi.mocked(fetchFormPaths).mockResolvedValue({ paths: [] });
218+
const [schema, setSchema] = createSignal<any>();
219+
const container = document.body.appendChild(document.createElement("div"));
220+
dispose = render(
221+
() => <FormEditorView formSchema={schema} setFormSchema={setSchema} />,
222+
container,
223+
);
224+
await vi.waitFor(() =>
225+
expect(
226+
editor.instance?.get("formFieldRegistry").get("BDT_Form"),
227+
).toBeDefined(),
228+
);
229+
container
230+
.querySelector<HTMLButtonElement>(
231+
'[data-testid="form-editor-save-button"]',
232+
)!
233+
.click();
234+
await vi.waitFor(() =>
235+
expect(saveFormSchema).toHaveBeenCalledWith(
236+
"screener-1",
237+
expect.objectContaining({
238+
type: "default",
239+
schemaVersion: 18,
240+
components: [],
241+
}),
242+
),
243+
);
244+
});
245+
216246
it("provides reactive editor samples keyed to the screener's benefits", async () => {
217247
vi.mocked(fetchFormPaths).mockResolvedValue({ paths: [] });
218248
const [schema, setSchema] = createSignal<any>();

‎builder-frontend/src/components/screenerEditor/FormEditorView.test.tsx‎

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -130,6 +130,28 @@ describe("AI form drafting", () => {
130130
expect(button()?.disabled).toBe(false);
131131
});
132132

133+
it("reports failed form saves without discarding edits and clears the error on retry", async () => {
134+
vi.mocked(saveFormSchema)
135+
.mockRejectedValueOnce(new Error("Storage failed"))
136+
.mockResolvedValueOnce(undefined);
137+
const { container, schema } = await mount(draft);
138+
const save = () =>
139+
container.querySelector<HTMLButtonElement>(
140+
'[data-testid="form-editor-save-button"]',
141+
)!;
142+
save().click();
143+
await vi.waitFor(() =>
144+
expect(container.querySelector('[role="alert"]')?.textContent).toContain(
145+
"Could not save the form",
146+
),
147+
);
148+
expect(schema()).toEqual(draft);
149+
expect(save().className).toContain("btn-yellow");
150+
save().click();
151+
await vi.waitFor(() => expect(save().className).toContain("btn-blue"));
152+
expect(container.querySelector('[role="alert"]')).toBeNull();
153+
});
154+
133155
it("prevents duplicate form saves and keeps edits made during a save unsaved", async () => {
134156
let finishSave!: () => void;
135157
vi.mocked(saveFormSchema).mockReturnValueOnce(

0 commit comments

Comments
 (0)