diff --git a/README.md b/README.md index 790f263..c0ab9d2 100644 --- a/README.md +++ b/README.md @@ -131,8 +131,10 @@ push to main | Tool | What it does | |---|---| | `get_import_format` | Item fields, rules, and an example | -| `list_status_sheet` | The owner's current items | -| `propose_status_sheet_import` | Validates items into a proposal (24 h); changes nothing | +| `list_aircraft` | The owner's aircraft (each has its own Status Sheet) | +| `add_aircraft` | Adds an empty aircraft; same rules as the dashboard (tail number unique per account, up to 25). Doesn't change which aircraft the dashboard opens on | +| `list_status_sheet` | One aircraft's current items | +| `propose_status_sheet_import` | Validates items into a proposal for one aircraft (24 h); changes nothing. With `recordsTailNumber`, refuses records for a plane that isn't on the account or isn't the target | | `continue_poor_fit` | Continues a proposal where most rows didn't fit, after the owner agrees | | `confirm_status_sheet_import` | Adds exactly the proposal's items, all or nothing | | `list_flights` | The owner's logged flights | diff --git a/docs/backend-notes/HTTP.txt b/docs/backend-notes/HTTP.txt index c486d4d..af5a822 100644 --- a/docs/backend-notes/HTTP.txt +++ b/docs/backend-notes/HTTP.txt @@ -101,7 +101,7 @@ cached resources and the browser can ignore them. by using the WWW-Authenticate and similar headers. Or by setting a specific session by using HTTP cookies. 3.relaxing the origin constraint - to prevent snooping and other privacy invasions web browsers enforce strict seperation between websites. Only pages from the same origin can access all information from a web page. This can be limiting to some web apps / servers so relaxing the origin constraints relaxes this by allowing other domains to talk to your -server. In this project I don't have multiple domains talking to my server so CORS is not required. +server. In this project most pages are same-origin, so they don't need CORS. The one exception is /api/public/**: my portfolio site (danielibarra.com) reads /api/public/stats from another origin, so SecurityConfig allows that origin with CORS (GET only). 4.proxy and tunneling 5.sessions diff --git a/src/browserTest/java/com/example/AviaryService/browser/FleetPickerTest.java b/src/browserTest/java/com/example/AviaryService/browser/FleetPickerTest.java index 9d10aec..96b232d 100644 --- a/src/browserTest/java/com/example/AviaryService/browser/FleetPickerTest.java +++ b/src/browserTest/java/com/example/AviaryService/browser/FleetPickerTest.java @@ -168,7 +168,7 @@ void removeAircraftNeedsTheTailNumber() { assertThat(page.locator("#remove-aircraft-btn")).hasText("Remove N2BB…"); page.locator("#remove-aircraft-btn").click(); assertThat(page.locator("#remove-aircraft-dialog")).isVisible(); - assertThat(page.locator("#remove-aircraft-ok")).isDisabled(); + assertThat(page.locator("#remove-aircraft-ok")).isEnabled(); page.locator("#remove-aircraft-confirm").fill("n2 bb"); assertThat(page.locator("#remove-aircraft-ok")).isEnabled(); page.locator("#remove-aircraft-ok").click(); @@ -176,4 +176,30 @@ void removeAircraftNeedsTheTailNumber() { assertTrue(aircraftRepository.findById(b.getId()).isEmpty()); assertEquals(List.of("Alpha Annual", "Alpha Oil"), visibleItems(page)); } + + // Spec 012 US1: a click on Remove is never silent. Wrong text says what + // to type and sends nothing. + @Test + void removeAircraftWrongTextSaysWhatToType() { + seedFleet(); + loginAs(username, "password"); + page.navigate(baseUrl() + "/dashboard?aircraft=" + b.getId()); + List deletes = new java.util.ArrayList<>(); + page.onRequest(r -> { if ("DELETE".equals(r.method()) && r.url().contains("/aircraft/")) deletes.add(r.url()); }); + page.locator("#aircraft-picker-btn").click(); + page.locator("#remove-aircraft-btn").click(); + assertThat(page.locator("label[for='remove-aircraft-confirm']")).hasText("Type the tail number, N2BB, to confirm"); + assertThat(page.locator("#remove-aircraft-ok")).isEnabled(); + + page.locator("#remove-aircraft-ok").click(); + assertThat(page.locator("#remove-aircraft-error")).hasText("Type N2BB to confirm"); + + page.locator("#remove-aircraft-confirm").fill("N1AA"); + assertThat(page.locator("#remove-aircraft-error")).hasText(""); + page.locator("#remove-aircraft-confirm").press("Enter"); + assertThat(page.locator("#remove-aircraft-error")).hasText("Type N2BB to confirm"); + + assertTrue(deletes.isEmpty()); + assertTrue(aircraftRepository.findById(b.getId()).isPresent()); + } } diff --git a/src/browserTest/resources/application-browsertest.yml b/src/browserTest/resources/application-browsertest.yml index 733ab16..1aedcc5 100644 --- a/src/browserTest/resources/application-browsertest.yml +++ b/src/browserTest/resources/application-browsertest.yml @@ -5,6 +5,9 @@ spring: username: sa password: jpa: + # Same as Heroku (application-heroku.properties), so browser tests catch + # lazy-loading bugs that only show in production (spec 012 R1). + open-in-view: false hibernate: ddl-auto: create-drop properties: diff --git a/src/main/java/com/example/AviaryService/mcp/AircraftTools.java b/src/main/java/com/example/AviaryService/mcp/AircraftTools.java index 5351da8..f61e2c3 100644 --- a/src/main/java/com/example/AviaryService/mcp/AircraftTools.java +++ b/src/main/java/com/example/AviaryService/mcp/AircraftTools.java @@ -3,42 +3,91 @@ import java.util.List; import org.springframework.ai.tool.annotation.Tool; +import org.springframework.ai.tool.annotation.ToolParam; import org.springframework.stereotype.Component; +import com.example.AviaryService.entity.Aircraft; import com.example.AviaryService.entity.User; import com.example.AviaryService.oauth.CimdRegisteredClientRepository; import com.example.AviaryService.repositories.AircraftRepository; import com.example.AviaryService.repositories.StatusSheetItemRepository; +import com.example.AviaryService.services.aircraft.AircraftLimitException; +import com.example.AviaryService.services.aircraft.AircraftService; +import com.example.AviaryService.services.aircraft.AircraftValidationException; +import com.example.AviaryService.util.Validation; -// MCP tool listing the owner's aircraft, so an assistant can ask which one an -// import is for and pass it as `aircraft` to the other tools. +// MCP tools for the owner's fleet: list_aircraft, so an assistant can ask +// which one an import is for and pass it as `aircraft` to the other tools, +// and add_aircraft (spec 012), so records for a plane that isn't on the +// account yet get their own aircraft instead of landing on another one. @Component public class AircraftTools { public record AircraftSummary(Long aircraftId, String tailNumber, String makeModel, Double timeInServiceHours, long statusSheetItems) {} + // status: ADDED, ALREADY_EXISTS, INVALID or LIMIT_REACHED. aircraft is + // the new one (ADDED), the existing one (ALREADY_EXISTS), otherwise null. + public record AddAircraftResult(String status, String message, AircraftSummary aircraft) {} + private final AircraftRepository aircraftRepository; private final StatusSheetItemRepository statusSheetItemRepository; + private final AircraftService aircraftService; private final McpCurrentUser currentUser; public AircraftTools(AircraftRepository aircraftRepository, StatusSheetItemRepository statusSheetItemRepository, - McpCurrentUser currentUser) { + AircraftService aircraftService, McpCurrentUser currentUser) { this.aircraftRepository = aircraftRepository; this.statusSheetItemRepository = statusSheetItemRepository; + this.aircraftService = aircraftService; this.currentUser = currentUser; } @Tool(name = "list_aircraft", description = """ The owner's aircraft. When there is more than one, ask the owner which aircraft their records are for \ and pass its tail number (or aircraftId) as `aircraft` to list_status_sheet, list_flights and \ - propose_status_sheet_import.""") + propose_status_sheet_import. If the owner's records are for a plane that isn't listed, add it with \ + add_aircraft first.""") public List listAircraft() { currentUser.requireScope(CimdRegisteredClientRepository.SCOPE_READ); User user = currentUser.require(); - return aircraftRepository.findByUserOrderByIdAsc(user).stream() - .map(a -> new AircraftSummary(a.getId(), a.getTailNumber(), a.getMakeModel(), - a.getTimeInServiceHours(), statusSheetItemRepository.countByAircraft(a))) - .toList(); + return aircraftRepository.findByUserOrderByIdAsc(user).stream().map(this::summary).toList(); + } + + @Tool(name = "add_aircraft", description = """ + Add an aircraft to the owner's account. Use it when the owner's records are for a plane that isn't in \ + list_aircraft yet, then pass the returned tail number as `aircraft` (and `recordsTailNumber`) to \ + propose_status_sheet_import. The new aircraft starts empty. Doesn't change which aircraft the owner's \ + dashboard opens on. If the tail number is already on the account, returns ALREADY_EXISTS with that \ + aircraft: import into it instead.""") + public AddAircraftResult addAircraft( + @ToolParam(description = "The aircraft's tail number, e.g. N731KR") String tailNumber, + @ToolParam(description = "Make and model, e.g. Piper PA-28", required = false) String makeModel, + @ToolParam(description = "Operator name", required = false) String operatorName, + @ToolParam(description = "Serial number", required = false) String serialNumber) { + currentUser.requireScope(CimdRegisteredClientRepository.SCOPE_IMPORT); + User user = currentUser.require(); + String key = Validation.tailNumberKey(tailNumber); + if (key != null) { + var existing = aircraftRepository.findByUserAndTailNumberKey(user, key); + if (existing.isPresent()) { + Aircraft a = existing.get(); + return new AddAircraftResult("ALREADY_EXISTS", a.getDisplayName() + " is already on this account (aircraftId " + + a.getId() + "). Import into it instead.", summary(a)); + } + } + try { + Aircraft created = aircraftService.create(user, tailNumber, makeModel, operatorName, serialNumber, false); + return new AddAircraftResult("ADDED", "Added " + created.getDisplayName() + ".", summary(created)); + } catch (AircraftLimitException e) { + return new AddAircraftResult("LIMIT_REACHED", e.getMessage(), null); + } catch (AircraftValidationException e) { + return new AddAircraftResult("INVALID", e.getMessage(), null); + } + } + + private AircraftSummary summary(Aircraft a) { + return new AircraftSummary(a.getId(), a.getTailNumber(), a.getMakeModel(), + a.getTimeInServiceHours(), statusSheetItemRepository.countByAircraft(a)); } } diff --git a/src/main/java/com/example/AviaryService/mcp/McpAircraftResolver.java b/src/main/java/com/example/AviaryService/mcp/McpAircraftResolver.java index fdd46a1..ef15822 100644 --- a/src/main/java/com/example/AviaryService/mcp/McpAircraftResolver.java +++ b/src/main/java/com/example/AviaryService/mcp/McpAircraftResolver.java @@ -27,6 +27,20 @@ public AircraftChoiceException(String message) { } } + // The records name a plane this account doesn't have (spec 012 US2). + public static class AddAircraftFirstException extends AircraftChoiceException { + public AddAircraftFirstException(String message) { + super(message); + } + } + + // The named aircraft and the records' tail number are different planes. + public static class AircraftMismatchException extends AircraftChoiceException { + public AircraftMismatchException(String message) { + super(message); + } + } + private final AircraftRepository aircraftRepository; public McpAircraftResolver(AircraftRepository aircraftRepository) { @@ -56,6 +70,27 @@ public Aircraft resolve(User user, String aircraft) { + describe(fleet) + "."); } + // As resolve(user, aircraft), plus the tail number the owner's records + // are for. When given, records only ever go to that plane: missing -> + // AddAircraftFirstException (even on a one-aircraft account, which would + // otherwise take anything), a different named aircraft -> + // AircraftMismatchException. Only this owner's aircraft are searched. + public Aircraft resolve(User user, String aircraft, String recordsTailNumber) { + String recordsKey = Validation.tailNumberKey(recordsTailNumber); + if (recordsKey == null) return resolve(user, aircraft); + String recordsTail = recordsTailNumber.trim(); + Aircraft forRecords = aircraftRepository.findByUserAndTailNumberKey(user, recordsKey) + .orElseThrow(() -> new AddAircraftFirstException("These records are for " + recordsTail + + ", which isn't on this account. Add it with add_aircraft, then import into it.")); + if (aircraft == null || aircraft.isBlank()) return forRecords; + Aircraft named = resolve(user, aircraft); + if (!named.getId().equals(forRecords.getId())) { + throw new AircraftMismatchException("You asked to import into " + named.getDisplayName() + + ", but these records are for " + forRecords.getDisplayName() + "."); + } + return named; + } + // "N482DM (Cessna 172S), N731KR (Piper PA-28)" static String describe(List fleet) { return fleet.stream().map(a -> { diff --git a/src/main/java/com/example/AviaryService/mcp/StatusSheetImportTools.java b/src/main/java/com/example/AviaryService/mcp/StatusSheetImportTools.java index 5e1607b..49a5769 100644 --- a/src/main/java/com/example/AviaryService/mcp/StatusSheetImportTools.java +++ b/src/main/java/com/example/AviaryService/mcp/StatusSheetImportTools.java @@ -49,8 +49,10 @@ public StatusSheetImportTools(StatusSheetImportService importService, StatusShee @Tool(name = "get_import_format", description = """ How Aviary Status Sheet items must look, with the rules and an example. Call this first, then \ convert the owner's maintenance records (any format) into these items before proposing. Each aircraft \ - has its own statusSheetItem: if list_aircraft shows more than one, ask the owner which aircraft the records \ - are for and pass it as `aircraft`.""") + has its own Status Sheet. Look for the tail number in the owner's records (often in the title or header). \ + If it isn't in list_aircraft, add it with add_aircraft, then propose with `aircraft` and `recordsTailNumber` \ + set to it. If the records name no plane and list_aircraft shows more than one, ask the owner which aircraft \ + the records are for. Records for several planes: one add (if needed) and one proposal per plane.""") public ImportFormat getImportFormat() { currentUser.requireScope(CimdRegisteredClientRepository.SCOPE_READ); Map fields = new LinkedHashMap<>(); @@ -93,23 +95,38 @@ public List listStatusSheetItem( only needs a name. Changes nothing: returns a proposal with the items as Aviary would store them, flags \ and notes for the owner to check, and rows that can't be imported with reasons. Show the owner the \ proposal before confirming. Calling this again for the same aircraft replaces the previous proposal \ - (use it to revise).""") + (use it to revise). Pass `recordsTailNumber` when the records name a plane: records are never imported \ + into a different plane, and a plane that isn't on the account must be added with add_aircraft first.""") public ImportResult proposeStatusSheetImport( @ToolParam(description = "Items converted from the owner's records; see get_import_format") List items, @ToolParam(description = "Rows that are not maintenance items at all, each with a reason. Never put a real item here just because it has no dates.", required = false) List rejectedBySource, - @ToolParam(description = AIRCRAFT_PARAM, required = false) String aircraft) { + @ToolParam(description = AIRCRAFT_PARAM, required = false) String aircraft, + @ToolParam(description = "The tail number the owner's records are for, if the records or the owner name one. " + + "Aviary refuses to import them into a different plane.", required = false) + String recordsTailNumber) { currentUser.requireScope(CimdRegisteredClientRepository.SCOPE_IMPORT); User user = currentUser.require(); Aircraft target; try { - target = aircraftResolver.resolve(user, aircraft); + target = aircraftResolver.resolve(user, aircraft, recordsTailNumber); + } catch (McpAircraftResolver.AddAircraftFirstException e) { + return ImportResult.addAircraftFirst(e.getMessage()); + } catch (McpAircraftResolver.AircraftMismatchException e) { + return ImportResult.mismatch(e.getMessage()); } catch (McpAircraftResolver.AircraftChoiceException e) { return ImportResult.choose(e.getMessage()); } return importService.propose(user, target, items, rejectedBySource, currentUser.clientId()); } + // Not a tool: the pre-012 call shape, kept for callers that don't pass + // the records' tail number. + public ImportResult proposeStatusSheetImport(List items, List rejectedBySource, + String aircraft) { + return proposeStatusSheetImport(items, rejectedBySource, aircraft, null); + } + @Tool(name = "continue_poor_fit", description = """ For a POOR_FIT proposal: the owner agreed to continue with only the rows that fit. Returns the proposal, \ which can then be confirmed.""") @@ -132,7 +149,7 @@ public ImportResult confirmStatusSheetImport( } static final String AIRCRAFT_PARAM = - "Tail number or aircraftId from list_aircraft. Required when the owner has more than one aircraft."; + "Tail number or aircraftId from list_aircraft or add_aircraft. Required when the owner has more than one aircraft."; private static String join(String date, String hours) { String d = date == null ? "" : date; diff --git a/src/main/java/com/example/AviaryService/repositories/AircraftRepository.java b/src/main/java/com/example/AviaryService/repositories/AircraftRepository.java index 2588e67..6f9edba 100644 --- a/src/main/java/com/example/AviaryService/repositories/AircraftRepository.java +++ b/src/main/java/com/example/AviaryService/repositories/AircraftRepository.java @@ -16,5 +16,6 @@ public interface AircraftRepository extends JpaRepository { Optional findFirstByUserOrderByIdAsc(User user); long countByUser(User user); boolean existsByUserAndTailNumberKey(User user, String tailNumberKey); + Optional findByUserAndTailNumberKey(User user, String tailNumberKey); boolean existsByUserAndTailNumberKeyAndIdNot(User user, String tailNumberKey, Long id); } diff --git a/src/main/java/com/example/AviaryService/services/aircraft/AircraftLimitException.java b/src/main/java/com/example/AviaryService/services/aircraft/AircraftLimitException.java new file mode 100644 index 0000000..cbd7ae6 --- /dev/null +++ b/src/main/java/com/example/AviaryService/services/aircraft/AircraftLimitException.java @@ -0,0 +1,10 @@ +package com.example.AviaryService.services.aircraft; + +// The account already has Aircraft.MAX_PER_USER aircraft. Still shown under +// the tail number field on the dashboard; the MCP add_aircraft tool reports +// it as LIMIT_REACHED. +public class AircraftLimitException extends AircraftValidationException { + public AircraftLimitException(String message) { + super("tailNumber", message); + } +} diff --git a/src/main/java/com/example/AviaryService/services/aircraft/AircraftService.java b/src/main/java/com/example/AviaryService/services/aircraft/AircraftService.java index 3c760b3..f9ab948 100644 --- a/src/main/java/com/example/AviaryService/services/aircraft/AircraftService.java +++ b/src/main/java/com/example/AviaryService/services/aircraft/AircraftService.java @@ -53,6 +53,14 @@ public List listFor(User user) { // aircraft the dashboard opens on. @Transactional public Aircraft create(User user, String tailNumber, String makeModel, String operatorName, String makeModelSN) { + return create(user, tailNumber, makeModel, operatorName, makeModelSN, true); + } + + // select=false (the assistant's add_aircraft) leaves the aircraft the + // dashboard opens on alone, so adding several planes doesn't move it. + @Transactional + public Aircraft create(User user, String tailNumber, String makeModel, String operatorName, String makeModelSN, + boolean select) { try { Validation.requireValidTailNumber(tailNumber, true); } catch (IllegalArgumentException e) { @@ -63,8 +71,7 @@ public Aircraft create(User user, String tailNumber, String makeModel, String op checkLength("makeModelSN", "Serial number", makeModelSN); if (aircraftRepository.countByUser(user) >= Aircraft.MAX_PER_USER) { - throw new AircraftValidationException("tailNumber", - "You can track up to " + Aircraft.MAX_PER_USER + " aircraft."); + throw new AircraftLimitException("You can track up to " + Aircraft.MAX_PER_USER + " aircraft."); } if (aircraftRepository.existsByUserAndTailNumberKey(user, Validation.tailNumberKey(tailNumber))) { throw new AircraftValidationException("tailNumber", "You already have an aircraft with this tail number."); @@ -77,8 +84,10 @@ public Aircraft create(User user, String tailNumber, String makeModel, String op aircraft.setMakeModelSN(trimToEmpty(makeModelSN)); aircraft = aircraftRepository.save(aircraft); - user.setLastViewedAircraft(aircraft); - userRepository.save(user); + if (select) { + user.setLastViewedAircraft(aircraft); + userRepository.save(user); + } return aircraft; } @@ -114,7 +123,11 @@ public Aircraft resolveForDashboard(User user, Long requestedId) { // typed its tail number (or DELETE when it has none). The last aircraft // can't be removed. Import history is kept, detached from the aircraft. @Transactional - public Aircraft remove(User user, Long aircraftId, String confirm) { + public Aircraft remove(User caller, Long aircraftId, String confirm) { + // Reload inside this transaction: on Heroku (open-in-view=false) the + // caller's User is detached, and its lazy aircraft list below would + // throw LazyInitializationException (a 500 in production only). + User user = userRepository.findById(caller.getId()).orElseThrow(); Aircraft aircraft = aircraftRepository.findByIdAndUser(aircraftId, user) .orElseThrow(AircraftNotFoundException::new); if (aircraftRepository.countByUser(user) <= 1) { diff --git a/src/main/java/com/example/AviaryService/services/imports/StatusSheetImportService.java b/src/main/java/com/example/AviaryService/services/imports/StatusSheetImportService.java index 1142662..89a6f32 100644 --- a/src/main/java/com/example/AviaryService/services/imports/StatusSheetImportService.java +++ b/src/main/java/com/example/AviaryService/services/imports/StatusSheetImportService.java @@ -74,6 +74,16 @@ static ImportResult status(String status, String message) { public static ImportResult choose(String message) { return status("CHOOSE_AIRCRAFT", message); } + + // Spec 012: the records name a plane that isn't on the account yet. + public static ImportResult addAircraftFirst(String message) { + return status("ADD_AIRCRAFT_FIRST", message); + } + + // Spec 012: the named aircraft isn't the plane the records are for. + public static ImportResult mismatch(String message) { + return status("AIRCRAFT_MISMATCH", message); + } } private final ImportProposalRepository proposalRepository; diff --git a/src/main/resources/static/js/dashboard.js b/src/main/resources/static/js/dashboard.js index fc7dea8..d3084d4 100644 --- a/src/main/resources/static/js/dashboard.js +++ b/src/main/resources/static/js/dashboard.js @@ -3495,16 +3495,27 @@ document.addEventListener('DOMContentLoaded', function () { close(); confirmInput.value = ''; removeError.textContent = ''; - okBtn.disabled = true; + okBtn.disabled = false; dialog.hidden = false; requestAnimationFrame(() => dialog.classList.add('show')); confirmInput.focus(); }); - confirmInput.addEventListener('input', () => { okBtn.disabled = norm(confirmInput.value) !== norm(word); }); + // Remove stays clickable: a click with the wrong text says what to type + // instead of silently doing nothing (spec 012 US1). The server checks too. + confirmInput.addEventListener('input', () => { removeError.textContent = ''; }); + confirmInput.addEventListener('keydown', e => { + if (e.key === 'Enter') { e.preventDefault(); okBtn.click(); } + }); document.getElementById('remove-aircraft-cancel').addEventListener('click', closeDialog); dialog.addEventListener('click', e => { if (e.target === dialog) closeDialog(); }); dialog.addEventListener('keydown', e => { if (e.key === 'Escape') closeDialog(); }); okBtn.addEventListener('click', async () => { + if (okBtn.disabled) return; + if (norm(confirmInput.value) !== norm(word)) { + removeError.textContent = 'Type ' + word + ' to confirm'; + confirmInput.focus(); + return; + } okBtn.disabled = true; try { const r = await axios.delete('/aircraft/' + encodeURIComponent(currentAircraftId()), { diff --git a/src/main/resources/templates/dashboard.html b/src/main/resources/templates/dashboard.html index 1b1898b..c0c49af 100644 --- a/src/main/resources/templates/dashboard.html +++ b/src/main/resources/templates/dashboard.html @@ -326,13 +326,13 @@

+ th:text="${aircraft.tailNumberKey != null} ? 'Type the tail number, ' + ${aircraft.tailNumber} + ', to confirm' : 'Type DELETE to confirm'">
- +
@@ -717,7 +717,7 @@

✈ flight(s) detected - + diff --git a/src/test/java/com/example/AviaryService/mcp/AddAircraftToolTest.java b/src/test/java/com/example/AviaryService/mcp/AddAircraftToolTest.java new file mode 100644 index 0000000..aeb4aed --- /dev/null +++ b/src/test/java/com/example/AviaryService/mcp/AddAircraftToolTest.java @@ -0,0 +1,203 @@ +package com.example.AviaryService.mcp; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.util.List; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.security.access.AccessDeniedException; +import org.springframework.test.context.ActiveProfiles; + +import com.example.AviaryService.entity.Aircraft; +import com.example.AviaryService.entity.StatusSheetItem; +import com.example.AviaryService.entity.User; +import com.example.AviaryService.mcp.AircraftTools.AddAircraftResult; +import com.example.AviaryService.repositories.AircraftRepository; +import com.example.AviaryService.repositories.StatusSheetItemRepository; +import com.example.AviaryService.repositories.UserRepository; +import com.example.AviaryService.services.imports.StatusSheetImportService.ImportResult; +import com.example.AviaryService.support.TestFleet; +import com.example.AviaryService.util.StatusSheetImportRules.InputItem; + +// Spec 012 US3/US4: the assistant adds aircraft and imports a Status Sheet +// into each. See specs/012-mcp-add-aircraft/contracts/mcp-tools.md. +// Not @Transactional: confirm runs its own transaction. Fresh users per test. +@SpringBootTest +@ActiveProfiles("test") +class AddAircraftToolTest { + + @Autowired AircraftTools aircraftTools; + @Autowired StatusSheetImportTools importTools; + @Autowired UserRepository userRepository; + @Autowired AircraftRepository aircraftRepository; + @Autowired StatusSheetItemRepository statusSheetItemRepository; + + private User owner; + private Aircraft n12; + + @BeforeEach + void setUp() { + owner = newUser("add-tool-"); + n12 = TestFleet.addAircraft(aircraftRepository, userRepository, owner, "N12SAS", "", 0, 100); + owner = userRepository.findById(owner.getId()).orElseThrow(); + owner.setLastViewedAircraft(n12); + userRepository.save(owner); + } + + private User newUser(String prefix) { + User u = new User(); + u.setUsername(prefix + System.nanoTime()); + u.setPassword("x"); + return userRepository.save(u); + } + + private AddAircraftResult add(User u, String tail, String makeModel) { + return McpTestSupport.as(u.getUsername(), () -> aircraftTools.addAircraft(tail, makeModel, null, null)); + } + + private static List items(String name) { + return List.of(new InputItem(name, null, null, null, "450", null, null, "50", null, null, null, name + " row", null)); + } + + private List rowsOn(Aircraft a) { + return statusSheetItemRepository.findByAircraftOrderByStatusSheetOrderAsc(a).stream() + .map(StatusSheetItem::getItem).toList(); + } + + private Aircraft byId(Long id) { + return aircraftRepository.findById(id).orElseThrow(); + } + + @Test + void addsAnEmptyAircraftThatListAircraftShows() { + AddAircraftResult r = add(owner, "N731KR", "Piper PA-28"); + + assertEquals("ADDED", r.status()); + assertEquals("Added N731KR.", r.message()); + assertEquals("N731KR", r.aircraft().tailNumber()); + assertEquals("Piper PA-28", r.aircraft().makeModel()); + assertEquals(0.0, r.aircraft().timeInServiceHours()); + assertEquals(0, r.aircraft().statusSheetItems()); + List fleet = McpTestSupport.as(owner.getUsername(), () -> aircraftTools.listAircraft()); + assertEquals(List.of("N12SAS", "N731KR"), fleet.stream().map(AircraftTools.AircraftSummary::tailNumber).toList()); + } + + @Test + void addingDoesNotMoveTheDashboard() { + add(owner, "N731KR", null); + assertEquals(n12.getId(), userRepository.findById(owner.getId()).orElseThrow().getLastViewedAircraft().getId()); + } + + @Test + void duplicateReportsTheExistingAircraft() { + Long first = add(owner, "N731KR", null).aircraft().aircraftId(); + + AddAircraftResult again = add(owner, "n731 kr", null); + + assertEquals("ALREADY_EXISTS", again.status()); + assertEquals(first, again.aircraft().aircraftId()); + assertEquals("N731KR is already on this account (aircraftId " + first + "). Import into it instead.", again.message()); + assertEquals(2, aircraftRepository.countByUser(owner)); + } + + @Test + void invalidTailIsRefusedWithTheDashboardsMessage() { + AddAircraftResult blank = add(owner, " ", null); + assertEquals("INVALID", blank.status()); + assertEquals("Enter a tail number.", blank.message()); + assertNull(blank.aircraft()); + assertEquals(1, aircraftRepository.countByUser(owner)); + } + + @Test + void limitIsReported() { + for (int i = 2; i <= Aircraft.MAX_PER_USER; i++) { + assertEquals("ADDED", add(owner, "N" + i + "XX", null).status()); + } + AddAircraftResult r = add(owner, "N999ZZ", null); + assertEquals("LIMIT_REACHED", r.status()); + assertEquals("You can track up to 25 aircraft.", r.message()); + assertEquals(Aircraft.MAX_PER_USER, aircraftRepository.countByUser(owner)); + } + + @Test + void readOnlyConnectionIsRefused() { + assertThrows(AccessDeniedException.class, () -> McpTestSupport.as(owner.getUsername(), List.of("aviary.read"), + () -> aircraftTools.addAircraft("N731KR", null, null, null))); + assertEquals(1, aircraftRepository.countByUser(owner)); + } + + @Test + void anotherAccountWithTheSameTailGetsItsOwnAircraft() { + User other = newUser("add-tool-other-"); + TestFleet.addAircraft(aircraftRepository, userRepository, other, "N1OT", "", 0, 0); + + AddAircraftResult r = add(other, "N12SAS", null); + + assertEquals("ADDED", r.status()); + assertEquals(1, aircraftRepository.countByUser(owner)); + assertEquals(2, aircraftRepository.countByUser(other)); + } + + // Spec 012 US2 scenario 1, end to end: N12SAS's account gets a sheet for N77XY. + @Test + void sheetForNewPlaneOnOneAircraftAccount() { + statusSheetItemRepository.save(row(n12, "N12SAS Oil")); + + ImportResult stopped = McpTestSupport.as(owner.getUsername(), + () -> importTools.proposeStatusSheetImport(items("N77XY Annual"), null, null, "N77XY")); + assertEquals("ADD_AIRCRAFT_FIRST", stopped.status()); + + Long n77 = add(owner, "N77XY", null).aircraft().aircraftId(); + ImportResult proposed = McpTestSupport.as(owner.getUsername(), + () -> importTools.proposeStatusSheetImport(items("N77XY Annual"), null, null, "N77XY")); + assertEquals("PROPOSED", proposed.status()); + assertTrue(proposed.summary().startsWith("Importing into N77XY"), proposed.summary()); + assertEquals("IMPORTED", McpTestSupport.as(owner.getUsername(), + () -> importTools.confirmStatusSheetImport(proposed.proposalId(), null)).status()); + + assertEquals(List.of("N77XY Annual"), rowsOn(byId(n77))); + assertEquals(List.of("N12SAS Oil"), rowsOn(n12)); + } + + // Spec 012 US4: three new planes in one session, each gets only its rows. + @Test + void threeNewAircraftEachGetOnlyTheirRows() { + statusSheetItemRepository.save(row(n12, "N12SAS Oil")); + List tails = List.of("N1AA", "N2BB", "N3CC"); + Long[] ids = new Long[3]; + Long[] proposals = new Long[3]; + for (int i = 0; i < 3; i++) { + String tail = tails.get(i); + ids[i] = add(owner, tail, null).aircraft().aircraftId(); + ImportResult p = McpTestSupport.as(owner.getUsername(), + () -> importTools.proposeStatusSheetImport(items(tail + " Annual"), null, tail, tail)); + assertEquals("PROPOSED", p.status()); + proposals[i] = p.proposalId(); + } + // N1AA's proposal stayed open while N2BB and N3CC were proposed. + for (Long proposalId : proposals) { + assertEquals("IMPORTED", McpTestSupport.as(owner.getUsername(), + () -> importTools.confirmStatusSheetImport(proposalId, null)).status()); + } + for (int i = 0; i < 3; i++) { + assertEquals(List.of(tails.get(i) + " Annual"), rowsOn(byId(ids[i]))); + } + assertEquals(List.of("N12SAS Oil"), rowsOn(n12)); + } + + private StatusSheetItem row(Aircraft a, String name) { + StatusSheetItem t = new StatusSheetItem(); + t.setUser(owner); + t.setAircraft(a); + t.setItem(name); + t.setStatusSheetOrder(0); + return t; + } +} diff --git a/src/test/java/com/example/AviaryService/mcp/McpToolListTest.java b/src/test/java/com/example/AviaryService/mcp/McpToolListTest.java new file mode 100644 index 0000000..c95905c --- /dev/null +++ b/src/test/java/com/example/AviaryService/mcp/McpToolListTest.java @@ -0,0 +1,43 @@ +package com.example.AviaryService.mcp; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.util.Arrays; +import java.util.List; + +import org.junit.jupiter.api.Test; +import org.springframework.ai.tool.ToolCallback; +import org.springframework.ai.tool.ToolCallbackProvider; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.ActiveProfiles; + +// The tools an assistant sees on /mcp, and the parameters spec 012 added. +@SpringBootTest +@ActiveProfiles("test") +class McpToolListTest { + + @Autowired ToolCallbackProvider aviaryTools; + + private ToolCallback tool(String name) { + return Arrays.stream(aviaryTools.getToolCallbacks()) + .filter(t -> t.getToolDefinition().name().equals(name)).findFirst().orElseThrow(); + } + + @Test + void toolList() { + List names = Arrays.stream(aviaryTools.getToolCallbacks()) + .map(t -> t.getToolDefinition().name()).sorted().toList(); + assertEquals(List.of("add_aircraft", "confirm_status_sheet_import", "continue_poor_fit", "get_import_format", + "list_aircraft", "list_flights", "list_status_sheet", "propose_status_sheet_import"), names); + } + + @Test + void newParametersAreAdvertised() { + String add = tool("add_aircraft").getToolDefinition().inputSchema(); + assertTrue(add.contains("tailNumber") && add.contains("makeModel"), add); + String propose = tool("propose_status_sheet_import").getToolDefinition().inputSchema(); + assertTrue(propose.contains("recordsTailNumber"), propose); + } +} diff --git a/src/test/java/com/example/AviaryService/mcp/RecordsTailNumberTest.java b/src/test/java/com/example/AviaryService/mcp/RecordsTailNumberTest.java new file mode 100644 index 0000000..fa0ffaa --- /dev/null +++ b/src/test/java/com/example/AviaryService/mcp/RecordsTailNumberTest.java @@ -0,0 +1,133 @@ +package com.example.AviaryService.mcp; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import java.util.List; + +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.ActiveProfiles; + +import com.example.AviaryService.entity.Aircraft; +import com.example.AviaryService.entity.StatusSheetItem; +import com.example.AviaryService.entity.User; +import com.example.AviaryService.repositories.AircraftRepository; +import com.example.AviaryService.repositories.ImportProposalRepository; +import com.example.AviaryService.repositories.StatusSheetItemRepository; +import com.example.AviaryService.repositories.UserRepository; +import com.example.AviaryService.services.imports.StatusSheetImportService.ImportResult; +import com.example.AviaryService.support.TestFleet; +import com.example.AviaryService.util.StatusSheetImportRules.InputItem; + +// Spec 012 US2: a Status Sheet for N77XY never lands on N12SAS. +// See specs/012-mcp-add-aircraft/contracts/mcp-tools.md. Fresh users per test. +@SpringBootTest +@ActiveProfiles("test") +class RecordsTailNumberTest { + + @Autowired StatusSheetImportTools importTools; + @Autowired UserRepository userRepository; + @Autowired AircraftRepository aircraftRepository; + @Autowired StatusSheetItemRepository statusSheetItemRepository; + @Autowired ImportProposalRepository proposalRepository; + + private User newUser(String prefix) { + User u = new User(); + u.setUsername(prefix + System.nanoTime()); + u.setPassword("x"); + return userRepository.save(u); + } + + private static List items(String name) { + return List.of(new InputItem(name, null, null, null, "450", null, null, "50", null, null, null, name + " row", null)); + } + + private void existing(User u, Aircraft a, String name) { + StatusSheetItem t = new StatusSheetItem(); + t.setUser(u); + t.setAircraft(a); + t.setItem(name); + t.setStatusSheetOrder(0); + statusSheetItemRepository.save(t); + } + + private ImportResult propose(User u, String aircraft, String recordsTail) { + return McpTestSupport.as(u.getUsername(), + () -> importTools.proposeStatusSheetImport(items("Annual"), null, aircraft, recordsTail)); + } + + @Test + void recordsForAPlaneNotOnTheAccountAreStoppedEvenWithOneAircraft() { + User owner = newUser("solo-"); + Aircraft n12 = TestFleet.addAircraft(aircraftRepository, userRepository, owner, "N12SAS", "", 0, 0); + existing(owner, n12, "Oil change"); + + ImportResult r = propose(owner, null, "N77XY"); + + assertEquals("ADD_AIRCRAFT_FIRST", r.status()); + assertNull(r.proposalId()); + assertTrue(r.message().contains("N77XY") && r.message().contains("add_aircraft"), r.message()); + assertTrue(proposalRepository.findByUserAndStatusIn(owner, List.of("OPEN", "NEEDS_FIT_CONFIRMATION")).isEmpty()); + assertEquals(List.of("Oil change"), statusSheetItemRepository.findByAircraftOrderByStatusSheetOrderAsc(n12) + .stream().map(StatusSheetItem::getItem).toList()); + } + + @Test + void namedAircraftThatDisagreesWithTheRecordsIsStopped() { + User owner = newUser("pair-"); + TestFleet.addAircraft(aircraftRepository, userRepository, owner, "N12SAS", "", 0, 0); + TestFleet.addAircraft(aircraftRepository, userRepository, owner, "N77XY", "", 0, 0); + + ImportResult r = propose(owner, "N12SAS", "N77XY"); + + assertEquals("AIRCRAFT_MISMATCH", r.status()); + assertNull(r.proposalId()); + assertTrue(r.message().contains("N12SAS") && r.message().contains("N77XY"), r.message()); + } + + @Test + void recordsTailPicksThePlaneWhenNoAircraftIsNamed() { + User owner = newUser("pick-"); + TestFleet.addAircraft(aircraftRepository, userRepository, owner, "N12SAS", "", 0, 0); + TestFleet.addAircraft(aircraftRepository, userRepository, owner, "N77XY", "", 0, 0); + + ImportResult r = propose(owner, null, "n77 xy"); + + assertEquals("PROPOSED", r.status()); + assertTrue(r.summary().startsWith("Importing into N77XY"), r.summary()); + } + + @Test + void namedAircraftAndRecordsAgree() { + User owner = newUser("agree-"); + TestFleet.addAircraft(aircraftRepository, userRepository, owner, "N12SAS", "", 0, 0); + TestFleet.addAircraft(aircraftRepository, userRepository, owner, "N77XY", "", 0, 0); + + assertEquals("PROPOSED", propose(owner, "N77XY", "N77XY").status()); + } + + @Test + void withoutRecordsTailTodaysRulesApply() { + User solo = newUser("today-solo-"); + TestFleet.addAircraft(aircraftRepository, userRepository, solo, "N12SAS", "", 0, 0); + assertEquals("PROPOSED", propose(solo, null, null).status()); + + User pair = newUser("today-pair-"); + TestFleet.addAircraft(aircraftRepository, userRepository, pair, "N12SAS", "", 0, 0); + TestFleet.addAircraft(aircraftRepository, userRepository, pair, "N77XY", "", 0, 0); + assertEquals("CHOOSE_AIRCRAFT", propose(pair, null, " ").status()); + } + + @Test + void anotherAccountsPlaneNeverMatches() { + User a = newUser("acct-a-"); + TestFleet.addAircraft(aircraftRepository, userRepository, a, "N77XY", "", 0, 0); + User b = newUser("acct-b-"); + TestFleet.addAircraft(aircraftRepository, userRepository, b, "N12SAS", "", 0, 0); + + assertEquals("ADD_AIRCRAFT_FIRST", propose(b, null, "N77XY").status()); + } +} diff --git a/src/test/java/com/example/AviaryService/services/aircraft/AircraftRemoveDetachedUserTest.java b/src/test/java/com/example/AviaryService/services/aircraft/AircraftRemoveDetachedUserTest.java new file mode 100644 index 0000000..c8770c0 --- /dev/null +++ b/src/test/java/com/example/AviaryService/services/aircraft/AircraftRemoveDetachedUserTest.java @@ -0,0 +1,49 @@ +package com.example.AviaryService.services.aircraft; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.test.context.ActiveProfiles; + +import com.example.AviaryService.entity.Aircraft; +import com.example.AviaryService.entity.User; +import com.example.AviaryService.repositories.AircraftRepository; +import com.example.AviaryService.repositories.UserRepository; +import com.example.AviaryService.support.TestFleet; + +// Spec 012 R1: production (heroku profile) runs with open-in-view=false, so +// the User the controller passes in is detached. remove() used to touch the +// user's lazy aircraft list and fail with a 500 there, while every test +// (open-in-view on, or @Transactional) passed. Not @Transactional on purpose: +// the user below is detached, exactly as on Heroku. +@SpringBootTest +@ActiveProfiles("test") +class AircraftRemoveDetachedUserTest { + + @Autowired AircraftService aircraftService; + @Autowired AircraftRepository aircraftRepository; + @Autowired UserRepository userRepository; + + @Test + void removeWorksWithADetachedUser() { + User u = new User(); + u.setUsername("detached-" + System.nanoTime()); + u.setPassword("x"); + u = userRepository.save(u); + Aircraft first = TestFleet.addAircraft(aircraftRepository, userRepository, u, "N53037", "", 0, 0); + Aircraft k = TestFleet.addAircraft(aircraftRepository, userRepository, u, "K", "", 0, 0); + User viewing = userRepository.findById(u.getId()).orElseThrow(); + viewing.setLastViewedAircraft(k); + userRepository.save(viewing); + + User detached = userRepository.findByUsername(u.getUsername()); // as AircraftController does + Aircraft next = aircraftService.remove(detached, k.getId(), "k"); + + assertEquals(first.getId(), next.getId()); + assertTrue(aircraftRepository.findById(k.getId()).isEmpty()); + assertEquals(first.getId(), userRepository.findById(u.getId()).orElseThrow().getLastViewedAircraft().getId()); + } +} diff --git a/src/test/java/com/example/AviaryService/services/aircraft/AircraftServiceTest.java b/src/test/java/com/example/AviaryService/services/aircraft/AircraftServiceTest.java index b101cd8..336acc1 100644 --- a/src/test/java/com/example/AviaryService/services/aircraft/AircraftServiceTest.java +++ b/src/test/java/com/example/AviaryService/services/aircraft/AircraftServiceTest.java @@ -112,6 +112,25 @@ void newAircraftStartsEmptyAndBecomesTheViewedOne() { assertEquals(90.0, aircraftRepository.findById(first.getId()).orElseThrow().getTimeInServiceHours()); } + // Spec 012 FR-012: the assistant's add doesn't move the dashboard. + @Test + void createWithoutSelectLeavesTheViewedAircraftAlone() { + owner.setLastViewedAircraft(first); + userRepository.save(owner); + Aircraft a = aircraftService.create(owner, "N731KR", null, null, null, false); + assertEquals(first.getId(), userRepository.findById(owner.getId()).orElseThrow().getLastViewedAircraft().getId()); + assertEquals(2, aircraftRepository.countByUser(owner)); + assertEquals("N731KR", a.getTailNumber()); + } + + @Test + void limitIsItsOwnException() { + for (int i = 2; i <= Aircraft.MAX_PER_USER; i++) { + aircraftService.create(owner, "N" + i + "XX", null, null, null); + } + assertThrows(AircraftLimitException.class, () -> aircraftService.create(owner, "N999ZZ", null, null, null, false)); + } + // ---- choosing (US3) ---- @Test