Compare commits
7 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 4e1138f8ce | |||
| e6fc3eaf2c | |||
| b4d71b0f80 | |||
| 0a29127f7e | |||
| 0c9db7bcdb | |||
| d6dc1c9b57 | |||
| cd3606c0e9 |
@@ -15,7 +15,7 @@ jobs:
|
|||||||
- uses: actions/checkout@v4
|
- uses: actions/checkout@v4
|
||||||
- uses: pnpm/action-setup@v4
|
- uses: pnpm/action-setup@v4
|
||||||
with:
|
with:
|
||||||
version: 9
|
version: 11
|
||||||
- uses: actions/setup-node@v4
|
- uses: actions/setup-node@v4
|
||||||
with:
|
with:
|
||||||
node-version: 20
|
node-version: 20
|
||||||
|
|||||||
@@ -510,6 +510,15 @@ pub(crate) async fn create_field_definition(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Field-level rejection detail for `set_fields`, so the UI can highlight the field.
|
||||||
|
#[derive(Serialize, ToSchema)]
|
||||||
|
pub(crate) struct FieldErrorView {
|
||||||
|
/// The flexible-field key that was rejected.
|
||||||
|
pub field: String,
|
||||||
|
/// Machine code: "unknown" | "type_mismatch" | "unresolved".
|
||||||
|
pub code: String,
|
||||||
|
}
|
||||||
|
|
||||||
/// Replace an object's flexible-field values (validated against the registry).
|
/// Replace an object's flexible-field values (validated against the registry).
|
||||||
///
|
///
|
||||||
/// **Replace semantics:** the body is the *complete* desired field set. Omitting a key
|
/// **Replace semantics:** the body is the *complete* desired field set. Omitting a key
|
||||||
@@ -525,7 +534,7 @@ pub(crate) async fn create_field_definition(
|
|||||||
(status = 401),
|
(status = 401),
|
||||||
(status = 403),
|
(status = 403),
|
||||||
(status = 404, description = "Object not found"),
|
(status = 404, description = "Object not found"),
|
||||||
(status = 422, description = "Unknown field, type mismatch, or unresolved reference")
|
(status = 422, body = FieldErrorView, description = "A field was rejected")
|
||||||
)
|
)
|
||||||
)]
|
)]
|
||||||
pub(crate) async fn set_fields(
|
pub(crate) async fn set_fields(
|
||||||
@@ -533,34 +542,57 @@ pub(crate) async fn set_fields(
|
|||||||
State(state): State<AppState>,
|
State(state): State<AppState>,
|
||||||
Path(id): Path<String>,
|
Path(id): Path<String>,
|
||||||
Json(values): Json<serde_json::Map<String, serde_json::Value>>,
|
Json(values): Json<serde_json::Map<String, serde_json::Value>>,
|
||||||
) -> Result<StatusCode, StatusCode> {
|
) -> axum::response::Response {
|
||||||
let object_id = id.parse::<ObjectId>().map_err(|_| StatusCode::NOT_FOUND)?;
|
use axum::response::IntoResponse;
|
||||||
|
|
||||||
let mut tx = state
|
let Ok(object_id) = id.parse::<ObjectId>() else {
|
||||||
.db
|
return StatusCode::NOT_FOUND.into_response();
|
||||||
.pool()
|
};
|
||||||
.begin()
|
|
||||||
.await
|
let mut tx = match state.db.pool().begin().await {
|
||||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
Ok(tx) => tx,
|
||||||
|
Err(_) => return StatusCode::INTERNAL_SERVER_ERROR.into_response(),
|
||||||
|
};
|
||||||
|
|
||||||
let result =
|
let result =
|
||||||
db::catalog::set_object_fields(&mut tx, actor(&auth.user), object_id, &values).await;
|
db::catalog::set_object_fields(&mut tx, actor(&auth.user), object_id, &values).await;
|
||||||
|
|
||||||
match result {
|
match result {
|
||||||
Ok(()) => {
|
Ok(()) => {
|
||||||
tx.commit()
|
if tx.commit().await.is_err() {
|
||||||
.await
|
return StatusCode::INTERNAL_SERVER_ERROR.into_response();
|
||||||
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
|
}
|
||||||
|
|
||||||
reindex(&state, object_id).await;
|
reindex(&state, object_id).await;
|
||||||
|
|
||||||
Ok(StatusCode::NO_CONTENT)
|
StatusCode::NO_CONTENT.into_response()
|
||||||
}
|
}
|
||||||
Err(db::catalog::FieldError::ObjectNotFound) => Err(StatusCode::NOT_FOUND),
|
Err(db::catalog::FieldError::ObjectNotFound) => StatusCode::NOT_FOUND.into_response(),
|
||||||
Err(db::catalog::FieldError::Db(_)) => Err(StatusCode::INTERNAL_SERVER_ERROR),
|
Err(db::catalog::FieldError::Db(_)) => StatusCode::INTERNAL_SERVER_ERROR.into_response(),
|
||||||
Err(db::catalog::FieldError::UnknownField(_)) => Err(StatusCode::UNPROCESSABLE_ENTITY),
|
Err(db::catalog::FieldError::UnknownField(field)) => (
|
||||||
Err(db::catalog::FieldError::TypeMismatch { .. }) => Err(StatusCode::UNPROCESSABLE_ENTITY),
|
StatusCode::UNPROCESSABLE_ENTITY,
|
||||||
Err(db::catalog::FieldError::Unresolved { .. }) => Err(StatusCode::UNPROCESSABLE_ENTITY),
|
Json(FieldErrorView {
|
||||||
|
field,
|
||||||
|
code: "unknown".to_owned(),
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
.into_response(),
|
||||||
|
Err(db::catalog::FieldError::TypeMismatch { field, .. }) => (
|
||||||
|
StatusCode::UNPROCESSABLE_ENTITY,
|
||||||
|
Json(FieldErrorView {
|
||||||
|
field,
|
||||||
|
code: "type_mismatch".to_owned(),
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
.into_response(),
|
||||||
|
Err(db::catalog::FieldError::Unresolved { field, .. }) => (
|
||||||
|
StatusCode::UNPROCESSABLE_ENTITY,
|
||||||
|
Json(FieldErrorView {
|
||||||
|
field,
|
||||||
|
code: "unresolved".to_owned(),
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
.into_response(),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -28,6 +28,7 @@ pub(crate) struct SearchHitView {
|
|||||||
pub object_number: String,
|
pub object_number: String,
|
||||||
pub object_name: String,
|
pub object_name: String,
|
||||||
pub brief_description: Option<String>,
|
pub brief_description: Option<String>,
|
||||||
|
#[schema(value_type = domain::Visibility)]
|
||||||
pub visibility: String,
|
pub visibility: String,
|
||||||
pub snippet: Option<String>,
|
pub snippet: Option<String>,
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -53,6 +53,7 @@ use crate::{
|
|||||||
admin_objects::FieldDefinitionView,
|
admin_objects::FieldDefinitionView,
|
||||||
admin_objects::NewFieldDefinitionRequest,
|
admin_objects::NewFieldDefinitionRequest,
|
||||||
admin_objects::CreatedField,
|
admin_objects::CreatedField,
|
||||||
|
admin_objects::FieldErrorView,
|
||||||
admin_vocab::VocabularyView,
|
admin_vocab::VocabularyView,
|
||||||
admin_vocab::NewVocabularyRequest,
|
admin_vocab::NewVocabularyRequest,
|
||||||
admin_vocab::NewTermRequest,
|
admin_vocab::NewTermRequest,
|
||||||
|
|||||||
@@ -434,6 +434,52 @@ async fn set_fields_and_list_field_definitions(pool: PgPool) {
|
|||||||
assert_eq!(bad.status(), StatusCode::UNPROCESSABLE_ENTITY);
|
assert_eq!(bad.status(), StatusCode::UNPROCESSABLE_ENTITY);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[sqlx::test(migrations = "../db/migrations")]
|
||||||
|
async fn set_fields_unknown_field_returns_field_detail(pool: PgPool) {
|
||||||
|
migrate_sessions(&db::Db::from_pool(pool.clone()))
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
|
seed_user(&pool, "ed@example.com", "pw-editor-123", Role::Editor).await;
|
||||||
|
|
||||||
|
let db = db::Db::from_pool(pool.clone());
|
||||||
|
let mut tx = db.pool().begin().await.unwrap();
|
||||||
|
|
||||||
|
let id = catalog::create_object(
|
||||||
|
&mut tx,
|
||||||
|
AuditActor::System,
|
||||||
|
&obj("A-1", "amphora", Visibility::Draft),
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
|
tx.commit().await.unwrap();
|
||||||
|
|
||||||
|
let app = build_app(state(pool));
|
||||||
|
let cookie = login(&app, "ed@example.com", "pw-editor-123").await;
|
||||||
|
|
||||||
|
let resp = app
|
||||||
|
.oneshot(
|
||||||
|
Request::builder()
|
||||||
|
.method("PUT")
|
||||||
|
.uri(format!("/api/admin/objects/{id}/fields"))
|
||||||
|
.header(header::COOKIE, &cookie)
|
||||||
|
.header(header::CONTENT_TYPE, "application/json")
|
||||||
|
.body(Body::from(r#"{"definitely_not_a_field":"x"}"#))
|
||||||
|
.unwrap(),
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
|
assert_eq!(resp.status(), StatusCode::UNPROCESSABLE_ENTITY);
|
||||||
|
|
||||||
|
let body: serde_json::Value =
|
||||||
|
serde_json::from_slice(&resp.into_body().collect().await.unwrap().to_bytes()).unwrap();
|
||||||
|
|
||||||
|
assert_eq!(body["field"], "definitely_not_a_field");
|
||||||
|
assert_eq!(body["code"], "unknown");
|
||||||
|
}
|
||||||
|
|
||||||
#[sqlx::test(migrations = "../db/migrations")]
|
#[sqlx::test(migrations = "../db/migrations")]
|
||||||
async fn create_requires_auth(pool: PgPool) {
|
async fn create_requires_auth(pool: PgPool) {
|
||||||
migrate_sessions(&db::Db::from_pool(pool.clone()))
|
migrate_sessions(&db::Db::from_pool(pool.clone()))
|
||||||
|
|||||||
@@ -0,0 +1,317 @@
|
|||||||
|
# Follow-ups Batch (#38, #28, #41, #26) Implementation Plan
|
||||||
|
|
||||||
|
> **For agentic workers:** REQUIRED SUB-SKILL: superpowers:subagent-driven-development. Steps use `- [ ]`.
|
||||||
|
|
||||||
|
**Goal:** Four small, well-specified follow-ups: enum-type `SearchHitView.visibility` (#38); carry the offending field in the `set_fields` 422 so the UI can highlight it (#28); normalize `localized_text` to the default language on save (#41); pin the pnpm version (#26).
|
||||||
|
|
||||||
|
**Tech Stack:** Rust (axum, utoipa), React + TS, react-hook-form, Vitest + RTL + MSW.
|
||||||
|
|
||||||
|
**Conventions:** nightly fmt; clippy `-D warnings`; no `any`/`eslint-disable`/`@ts-ignore`; en/sv parity; codename ban; bundle ≤150 KB gz. Test infra: `DATABASE_URL=postgres://postgres:postgres@localhost:5442/cms_dev`, `MEILI_URL=http://localhost:7700`, `MEILI_MASTER_KEY=masterKey`. cargo from repo root; web from `web/`.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Task 1: Backend — `SearchHitView.visibility` enum (#38) + `set_fields` field-level 422 (#28)
|
||||||
|
|
||||||
|
**Files:** Modify `crates/api/src/admin_search.rs`, `crates/api/src/admin_objects.rs`, `crates/api/src/openapi.rs`; Test `crates/api/tests/admin_objects.rs`; Regenerate `web/src/api/schema.d.ts`.
|
||||||
|
|
||||||
|
### #38 — enum-type the search hit visibility
|
||||||
|
- [ ] **Step 1:** In `crates/api/src/admin_search.rs`, `SearchHitView.visibility` (line ~31, `pub visibility: String`): add the attribute above it:
|
||||||
|
```rust
|
||||||
|
#[schema(value_type = domain::Visibility)]
|
||||||
|
pub visibility: String,
|
||||||
|
```
|
||||||
|
(`domain::Visibility` already derives `ToSchema` and is registered in `openapi.rs` from #29 — no further registration needed.)
|
||||||
|
|
||||||
|
### #28 — carry the offending field in the 422
|
||||||
|
The db `FieldError` already names the field (`UnknownField(String)`, `TypeMismatch { field, .. }`, `Unresolved { field, .. }`). Surface it.
|
||||||
|
|
||||||
|
- [ ] **Step 2:** In `crates/api/src/admin_objects.rs`, add a response DTO near the other views:
|
||||||
|
```rust
|
||||||
|
/// Field-level rejection detail for `set_fields`, so the UI can highlight the field.
|
||||||
|
#[derive(serde::Serialize, utoipa::ToSchema)]
|
||||||
|
pub(crate) struct FieldErrorView {
|
||||||
|
/// The flexible-field key that was rejected.
|
||||||
|
pub field: String,
|
||||||
|
/// Machine code: "unknown" | "type_mismatch" | "unresolved".
|
||||||
|
pub code: String,
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
- [ ] **Step 3:** Change the `set_fields` handler to return a body on the field-error 422s. Its signature is `-> Result<StatusCode, StatusCode>`; change to `-> axum::response::Response` and build responses (import `axum::response::IntoResponse`):
|
||||||
|
```rust
|
||||||
|
) -> axum::response::Response {
|
||||||
|
use axum::response::IntoResponse;
|
||||||
|
|
||||||
|
let Ok(object_id) = id.parse::<ObjectId>() else {
|
||||||
|
return StatusCode::NOT_FOUND.into_response();
|
||||||
|
};
|
||||||
|
|
||||||
|
let mut tx = match state.db.pool().begin().await {
|
||||||
|
Ok(tx) => tx,
|
||||||
|
Err(_) => return StatusCode::INTERNAL_SERVER_ERROR.into_response(),
|
||||||
|
};
|
||||||
|
|
||||||
|
let result =
|
||||||
|
db::catalog::set_object_fields(&mut tx, actor(&auth.user), object_id, &values).await;
|
||||||
|
|
||||||
|
match result {
|
||||||
|
Ok(()) => {
|
||||||
|
if tx.commit().await.is_err() {
|
||||||
|
return StatusCode::INTERNAL_SERVER_ERROR.into_response();
|
||||||
|
}
|
||||||
|
reindex(&state, object_id).await;
|
||||||
|
StatusCode::NO_CONTENT.into_response()
|
||||||
|
}
|
||||||
|
Err(db::catalog::FieldError::ObjectNotFound) => StatusCode::NOT_FOUND.into_response(),
|
||||||
|
Err(db::catalog::FieldError::Db(_)) => StatusCode::INTERNAL_SERVER_ERROR.into_response(),
|
||||||
|
Err(db::catalog::FieldError::UnknownField(field)) => (
|
||||||
|
StatusCode::UNPROCESSABLE_ENTITY,
|
||||||
|
Json(FieldErrorView { field, code: "unknown".to_owned() }),
|
||||||
|
)
|
||||||
|
.into_response(),
|
||||||
|
Err(db::catalog::FieldError::TypeMismatch { field, .. }) => (
|
||||||
|
StatusCode::UNPROCESSABLE_ENTITY,
|
||||||
|
Json(FieldErrorView { field, code: "type_mismatch".to_owned() }),
|
||||||
|
)
|
||||||
|
.into_response(),
|
||||||
|
Err(db::catalog::FieldError::Unresolved { field, .. }) => (
|
||||||
|
StatusCode::UNPROCESSABLE_ENTITY,
|
||||||
|
Json(FieldErrorView { field, code: "unresolved".to_owned() }),
|
||||||
|
)
|
||||||
|
.into_response(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
Update the `#[utoipa::path(...)]` on `set_fields`: the 422 response now has a body — change/add `(status = 422, body = FieldErrorView, description = "A field was rejected")` in its `responses(...)`.
|
||||||
|
|
||||||
|
- [ ] **Step 4:** Register `admin_objects::FieldErrorView` in `crates/api/src/openapi.rs` `components(schemas(...))`.
|
||||||
|
|
||||||
|
- [ ] **Step 5: Test** — add to `crates/api/tests/admin_objects.rs` (reuse its harness: seed editor, login, create an object). Create an object, then PUT `/api/admin/objects/{id}/fields` with an **unknown** field key → assert `422` and the body `{ field: "<that key>", code: "unknown" }`. (Mirror an existing set-fields test if present; if a field-definition is needed for a type_mismatch case, the `unknown` case needs none — simplest.) Read the file for the exact request/parse helpers.
|
||||||
|
|
||||||
|
- [ ] **Step 6: Build + backend tests:**
|
||||||
|
```bash
|
||||||
|
cargo +nightly fmt
|
||||||
|
cargo clippy --workspace --all-targets
|
||||||
|
DATABASE_URL=postgres://postgres:postgres@localhost:5442/cms_dev MEILI_URL=http://localhost:7700 MEILI_MASTER_KEY=masterKey cargo test -p api
|
||||||
|
```
|
||||||
|
All green (existing set_fields tests still pass — success path still 204; the failure path now carries a body but the status is unchanged at 422).
|
||||||
|
|
||||||
|
- [ ] **Step 7: Regenerate client:**
|
||||||
|
```bash
|
||||||
|
cargo build -p server
|
||||||
|
lsof -ti :8080 | xargs kill 2>/dev/null
|
||||||
|
DATABASE_URL=postgres://postgres:postgres@localhost:5442/cms_dev MEILI_URL=http://localhost:7700 MEILI_MASTER_KEY=masterKey ./target/debug/server &
|
||||||
|
SERVER_PID=$!
|
||||||
|
sleep 2
|
||||||
|
( cd web && pnpm gen:api )
|
||||||
|
kill "$SERVER_PID"
|
||||||
|
grep -n "FieldErrorView" web/src/api/schema.d.ts
|
||||||
|
# confirm SearchHitView.visibility now references the Visibility union:
|
||||||
|
grep -n "SearchHitView" web/src/api/schema.d.ts
|
||||||
|
```
|
||||||
|
`FieldErrorView` present; `SearchHitView.visibility` → `components["schemas"]["Visibility"]`. `cd web && pnpm typecheck` clean. Diff additive.
|
||||||
|
|
||||||
|
- [ ] **Step 8: Commit:**
|
||||||
|
```bash
|
||||||
|
cd /Users/olsson/Laboratory/biggus-dickus
|
||||||
|
git add crates/api web/src/api/schema.d.ts
|
||||||
|
git commit -m "feat(api): field-level set_fields 422 body (#28); enum-type SearchHitView.visibility (#38)"
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Task 2: Frontend — surface the rejected field & highlight it (#28)
|
||||||
|
|
||||||
|
**Files:** Modify `web/src/api/queries.ts`, `web/src/objects/object-form.tsx`, `web/src/objects/object-new-page.tsx`, `web/src/objects/object-edit-form.tsx`, `web/src/i18n/{en,sv}.json`; Test `web/src/objects/object-form.test.tsx` or the relevant existing object test.
|
||||||
|
|
||||||
|
- [ ] **Step 1: i18n** — add `form.fieldRejected` to BOTH `en.json` and `sv.json` (interpolated):
|
||||||
|
- en `form`: `"fieldRejected": "The field \"{{field}}\" was rejected — check its value"`
|
||||||
|
- sv `form`: `"fieldRejected": "Fältet \"{{field}}\" avvisades — kontrollera värdet"`
|
||||||
|
|
||||||
|
- [ ] **Step 2: A typed rejection in `useSetFields`** — in `web/src/api/queries.ts`, add near the other errors:
|
||||||
|
```ts
|
||||||
|
export class FieldRejection extends Error {
|
||||||
|
constructor(public readonly field: string, public readonly code: string) {
|
||||||
|
super(`field rejected: ${field}`);
|
||||||
|
this.name = "FieldRejection";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
Update `useSetFields`'s `mutationFn` to parse the 422 body and throw `FieldRejection`:
|
||||||
|
```ts
|
||||||
|
mutationFn: async ({ id, fields }: { id: string; fields: Record<string, unknown> }) => {
|
||||||
|
const { response, error } = await api.PUT("/api/admin/objects/{id}/fields", {
|
||||||
|
params: { path: { id } },
|
||||||
|
body: fields as Record<string, never>,
|
||||||
|
});
|
||||||
|
|
||||||
|
if (response.status === 204) return;
|
||||||
|
|
||||||
|
if (response.status === 422 && error && typeof error === "object" && "field" in error) {
|
||||||
|
const detail = error as { field: string; code: string };
|
||||||
|
throw new FieldRejection(detail.field, detail.code);
|
||||||
|
}
|
||||||
|
|
||||||
|
throw new Error("set fields failed");
|
||||||
|
},
|
||||||
|
```
|
||||||
|
(openapi-fetch puts the 422 body in `error` because the operation declares a 422 body schema. If `error` typing is awkward, narrow defensively as above — no `any`.)
|
||||||
|
|
||||||
|
- [ ] **Step 3: Thread a field-error into the form** — `object-form.tsx` owns the react-hook-form instance. Add an optional prop `fieldErrorKey?: string | null` and, via `useEffect`, set/clear the RHF error so the field highlights:
|
||||||
|
```tsx
|
||||||
|
// in the ObjectForm props type:
|
||||||
|
fieldErrorKey?: string | null;
|
||||||
|
// inside the component (form is the useForm instance; t available):
|
||||||
|
useEffect(() => {
|
||||||
|
if (fieldErrorKey) {
|
||||||
|
form.setError(`fields.${fieldErrorKey}` as never, {
|
||||||
|
type: "server",
|
||||||
|
message: t("form.fieldRejected", { field: fieldErrorKey }),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}, [fieldErrorKey, form, t]);
|
||||||
|
```
|
||||||
|
(The `as never` is to satisfy RHF's path typing for a dynamic flexible-field path; if a cleaner typed path is available without `any`, use it — `as never` is acceptable here and is NOT `as any`. Confirm lint accepts it; if `react-hooks/exhaustive-deps` complains, include the listed deps.)
|
||||||
|
|
||||||
|
- [ ] **Step 4: Parent catch sets the field key** — in `object-new-page.tsx` and `object-edit-form.tsx`, the `catch` currently does `setError(t("form.rejected"))`. Capture the rejected field too:
|
||||||
|
- Add state `const [fieldErrorKey, setFieldErrorKey] = useState<string | null>(null);`
|
||||||
|
- In the catch: `if (e instanceof FieldRejection) { setFieldErrorKey(e.field); setError(t("form.fieldRejected", { field: e.field })); } else { setError(t("form.rejected")); }` (import `FieldRejection` from `../api/queries`).
|
||||||
|
- Pass `fieldErrorKey={fieldErrorKey}` to `<ObjectForm>`.
|
||||||
|
- Clear `setFieldErrorKey(null)` at the top of `onSubmit` (alongside `setError(null)`).
|
||||||
|
(For `object-edit-form.tsx`, which also reads a `location.state.fieldsError` flag, keep that path but layer the new typed handling on top.)
|
||||||
|
|
||||||
|
- [ ] **Step 5: Test** — add a test (in the object form/new-page test file, MSW) where PUT `/api/admin/objects/:id/fields` returns `422` with `{ field: "dimensions", code: "type_mismatch" }`. Submit the form; assert the field-rejected message appears (`/dimensions/i` + "rejected") and, if practical, that the field's input is marked invalid (`aria-invalid` or an error message near it). Use the existing object-form test setup; read it for the render/submit pattern.
|
||||||
|
|
||||||
|
- [ ] **Step 6: Verify + commit:**
|
||||||
|
```bash
|
||||||
|
cd web && pnpm test && pnpm typecheck && pnpm lint && pnpm build && pnpm check:size
|
||||||
|
cd /Users/olsson/Laboratory/biggus-dickus
|
||||||
|
git add web
|
||||||
|
git commit -m "feat(web): highlight the offending field on a set_fields 422 (#28)"
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Task 3: Frontend — visibility-badge typing (#38) + localized_text normalize-on-save (#41)
|
||||||
|
|
||||||
|
**Files:** Modify `web/src/objects/visibility-badge.tsx`, `web/src/objects/object-form.tsx`; Test the object-form/field tests.
|
||||||
|
|
||||||
|
### #38 — tighten the VisibilityBadge prop
|
||||||
|
- [ ] **Step 1:** `web/src/objects/visibility-badge.tsx` — change the prop from `string` to the schema union (now that all callers pass it, incl. search hits after Task 1):
|
||||||
|
```tsx
|
||||||
|
import type { components } from "../api/schema";
|
||||||
|
|
||||||
|
type Visibility = components["schemas"]["Visibility"];
|
||||||
|
|
||||||
|
export function VisibilityBadge({ visibility }: { visibility: Visibility }) {
|
||||||
|
const { t } = useTranslation();
|
||||||
|
return (
|
||||||
|
<Badge variant="outline" className={STYLES[visibility] ?? ""}>
|
||||||
|
{t(`visibility.${visibility}`)}
|
||||||
|
</Badge>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
```
|
||||||
|
Run `pnpm typecheck` — every caller (`object-list`, `object-detail`, `search-result-row`) now passes the union (object/search hit `visibility` are the union post-#29/#38). Fix any caller that still has a widened `string` (there should be none).
|
||||||
|
|
||||||
|
### #41 — normalize localized_text to the default language on save
|
||||||
|
The edit path seeds `defaultValues.fields` from `object.fields` verbatim, so a `localized_text` value authored under another language keeps that key. Normalize in `pruneFields` so only the default-language key is saved.
|
||||||
|
|
||||||
|
- [ ] **Step 2:** In `web/src/objects/object-form.tsx`:
|
||||||
|
- Add `import { useConfig } from "../config/config-context";` and inside the component: `const { default_language } = useConfig();`.
|
||||||
|
- Compute the set of localized_text field keys from the loaded definitions:
|
||||||
|
```tsx
|
||||||
|
const localizedTextKeys = new Set(
|
||||||
|
(definitions ?? []).filter((d) => d.data_type === "localized_text").map((d) => d.key),
|
||||||
|
);
|
||||||
|
```
|
||||||
|
- Pass both into `pruneFields` at its call site (`const fields = pruneFields(data.fields, localizedTextKeys, default_language);`).
|
||||||
|
- Update `pruneFields` to accept them and, for a localized_text key, keep only the default-language sub-value:
|
||||||
|
```tsx
|
||||||
|
function pruneFields(
|
||||||
|
fields: Record<string, unknown>,
|
||||||
|
localizedTextKeys: Set<string>,
|
||||||
|
defaultLang: string,
|
||||||
|
): Record<string, unknown> {
|
||||||
|
const out: Record<string, unknown> = {};
|
||||||
|
|
||||||
|
for (const [key, value] of Object.entries(fields)) {
|
||||||
|
if (value === undefined || value === null || value === "") continue;
|
||||||
|
|
||||||
|
if (typeof value === "object" && !Array.isArray(value)) {
|
||||||
|
const map = value as Record<string, unknown>;
|
||||||
|
// Single-language authoring: a localized_text value keeps only the default lang.
|
||||||
|
const entries = localizedTextKeys.has(key)
|
||||||
|
? Object.entries(map).filter(([lang]) => lang === defaultLang)
|
||||||
|
: Object.entries(map);
|
||||||
|
|
||||||
|
const inner = Object.fromEntries(
|
||||||
|
entries.filter(([, v]) => v !== undefined && v !== null && v !== ""),
|
||||||
|
);
|
||||||
|
|
||||||
|
if (Object.keys(inner).length > 0) out[key] = inner;
|
||||||
|
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
out[key] = value;
|
||||||
|
}
|
||||||
|
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
- [ ] **Step 3: Test** — add/extend a test: an object whose `localized_text` field value is `{ en: "Old", sv: "Ny" }`, edited on an `sv`-default instance, submits `fields` containing only `{ <key>: { sv: "Ny" } }` (the `en` key stripped). Use the object-form test harness (the `definitions` fixture has a `localized_text` field — `title_ml`). Assert the pruned payload via the submit handler / the PUT body.
|
||||||
|
|
||||||
|
- [ ] **Step 4: Verify + commit:**
|
||||||
|
```bash
|
||||||
|
cd web && pnpm test && pnpm typecheck && pnpm lint && pnpm build && pnpm check:size
|
||||||
|
cd /Users/olsson/Laboratory/biggus-dickus
|
||||||
|
git add web
|
||||||
|
git commit -m "fix(web): VisibilityBadge typed to the union (#38); normalize localized_text to default language on save (#41)"
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Task 4: Pin pnpm (#26) + verification
|
||||||
|
|
||||||
|
**Files:** Modify `web/package.json`, `.gitea/workflows/ci.yaml`.
|
||||||
|
|
||||||
|
- [ ] **Step 1: Pin pnpm** — add a `packageManager` field to `web/package.json` matching the dev/CI version. The local pnpm is `11.5.1`; CI's `pnpm/action-setup` is pinned to `9` — a mismatch. Unify on the local version:
|
||||||
|
- In `web/package.json`, add (top level): `"packageManager": "pnpm@11.5.1"`.
|
||||||
|
- In `.gitea/workflows/ci.yaml`, change the `pnpm/action-setup@v4` `version: 9` → `version: 11` (matching the major).
|
||||||
|
- [ ] **Step 2: Confirm the lockfile is consistent** — run `cd web && pnpm install --frozen-lockfile`. If it passes, the committed `pnpm-lock.yaml` is compatible — done. If it FAILS (lockfile format/version mismatch from the pnpm-9→11 change), run `pnpm install` once to update the lockfile, confirm only the lockfile changed (`git status`), and include `web/pnpm-lock.yaml` in the commit. Report which case occurred.
|
||||||
|
- [ ] **Step 3: Commit:**
|
||||||
|
```bash
|
||||||
|
cd /Users/olsson/Laboratory/biggus-dickus
|
||||||
|
git add web/package.json .gitea/workflows/ci.yaml web/pnpm-lock.yaml
|
||||||
|
git commit -m "build(web): pin pnpm via packageManager + align CI (#26)"
|
||||||
|
```
|
||||||
|
|
||||||
|
### Final verification
|
||||||
|
- [ ] **Step 4: i18n parity** —
|
||||||
|
```bash
|
||||||
|
cd web
|
||||||
|
node -e "const a=require('./src/i18n/en.json'),b=require('./src/i18n/sv.json');const k=o=>Object.entries(o).flatMap(([K,v])=>typeof v==='object'?k(v).map(s=>K+'.'+s):[K]);const ka=k(a).sort(),kb=k(b).sort();console.log(JSON.stringify(ka)===JSON.stringify(kb)?'PARITY OK':'MISMATCH '+JSON.stringify({onlyEn:ka.filter(x=>!kb.includes(x)),onlySv:kb.filter(x=>!ka.includes(x))}))"
|
||||||
|
```
|
||||||
|
Expected `PARITY OK`.
|
||||||
|
- [ ] **Step 5: Full suites** —
|
||||||
|
```bash
|
||||||
|
cd web && pnpm typecheck && pnpm lint && pnpm test && pnpm build && pnpm check:size
|
||||||
|
cd /Users/olsson/Laboratory/biggus-dickus
|
||||||
|
DATABASE_URL=postgres://postgres:postgres@localhost:5442/cms_dev MEILI_URL=http://localhost:7700 MEILI_MASTER_KEY=masterKey cargo test --workspace
|
||||||
|
cargo clippy --workspace --all-targets && cargo +nightly fmt --check
|
||||||
|
```
|
||||||
|
All green; bundle ≤150 KB; clippy/fmt clean.
|
||||||
|
- [ ] **Step 6:** `git grep -in 'biggus\|dickus' -- crates web/src` → none.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Self-Review (completed)
|
||||||
|
- **Spec coverage:** #38 (search visibility enum → T1 backend + T3 prop tighten); #28 (422 field body → T1 backend, T2 FE highlight); #41 (localized_text normalize → T3); #26 (pin pnpm → T4). ✓
|
||||||
|
- **Placeholder scan:** none — concrete code; the "read the test harness" notes are verification steps against named files. The `as never` in T2 Step 3 is a typed-RHF-path escape (NOT `as any`/ts-ignore) and is flagged for lint confirmation.
|
||||||
|
- **Type consistency:** `FieldErrorView { field, code }` (Rust) ↔ `components["schemas"]["FieldErrorView"]` (the 422 body openapi-fetch surfaces as `error`) ↔ `FieldRejection{field,code}`; `SearchHitView.visibility` union flows into the tightened `VisibilityBadge` prop; `pruneFields` new signature `(fields, localizedTextKeys, defaultLang)` updated at its single call site.
|
||||||
|
|
||||||
|
## Notes
|
||||||
|
- #28 changes the `set_fields` handler return type from `Result<StatusCode, StatusCode>` to `Response`; the success status (204) and the field-error status (422) are unchanged — only a body is added to the 422, so existing status-only tests still pass.
|
||||||
|
- #26: if `pnpm install --frozen-lockfile` forces a lockfile regen, that's expected and the regenerated `pnpm-lock.yaml` is committed; flag if dependency versions shifted.
|
||||||
@@ -2,6 +2,7 @@
|
|||||||
"name": "web",
|
"name": "web",
|
||||||
"private": true,
|
"private": true,
|
||||||
"version": "0.0.0",
|
"version": "0.0.0",
|
||||||
|
"packageManager": "pnpm@11.5.1",
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"dev": "vite",
|
"dev": "vite",
|
||||||
|
|||||||
+16
-2
@@ -10,6 +10,13 @@ export class HttpError extends Error {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export class FieldRejection extends Error {
|
||||||
|
constructor(public readonly field: string, public readonly code: string) {
|
||||||
|
super(`field rejected: ${field}`);
|
||||||
|
this.name = "FieldRejection";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
type UserView = components["schemas"]["UserView"];
|
type UserView = components["schemas"]["UserView"];
|
||||||
type LoginRequest = components["schemas"]["LoginRequest"];
|
type LoginRequest = components["schemas"]["LoginRequest"];
|
||||||
|
|
||||||
@@ -179,12 +186,19 @@ export function useSetFields() {
|
|||||||
|
|
||||||
return useMutation({
|
return useMutation({
|
||||||
mutationFn: async ({ id, fields }: { id: string; fields: Record<string, unknown> }) => {
|
mutationFn: async ({ id, fields }: { id: string; fields: Record<string, unknown> }) => {
|
||||||
const { response } = await api.PUT("/api/admin/objects/{id}/fields", {
|
const { response, error } = await api.PUT("/api/admin/objects/{id}/fields", {
|
||||||
params: { path: { id } },
|
params: { path: { id } },
|
||||||
body: fields as Record<string, never>,
|
body: fields as Record<string, never>,
|
||||||
});
|
});
|
||||||
|
|
||||||
if (response.status !== 204) throw new Error("set fields failed");
|
if (response.status === 204) return;
|
||||||
|
|
||||||
|
if (response.status === 422 && error && typeof error === "object" && "field" in error) {
|
||||||
|
const detail = error as { field: string; code: string };
|
||||||
|
throw new FieldRejection(detail.field, detail.code);
|
||||||
|
}
|
||||||
|
|
||||||
|
throw new Error("set fields failed");
|
||||||
},
|
},
|
||||||
onSuccess: (_d, { id }) => {
|
onSuccess: (_d, { id }) => {
|
||||||
void qc.invalidateQueries({ queryKey: ["object", id] });
|
void qc.invalidateQueries({ queryKey: ["object", id] });
|
||||||
|
|||||||
Vendored
+12
-3
@@ -408,6 +408,13 @@ export interface components {
|
|||||||
required: boolean;
|
required: boolean;
|
||||||
vocabulary_id?: string | null;
|
vocabulary_id?: string | null;
|
||||||
};
|
};
|
||||||
|
/** @description Field-level rejection detail for `set_fields`, so the UI can highlight the field. */
|
||||||
|
FieldErrorView: {
|
||||||
|
/** @description Machine code: "unknown" | "type_mismatch" | "unresolved". */
|
||||||
|
code: string;
|
||||||
|
/** @description The flexible-field key that was rejected. */
|
||||||
|
field: string;
|
||||||
|
};
|
||||||
LabelInput: {
|
LabelInput: {
|
||||||
label: string;
|
label: string;
|
||||||
lang: string;
|
lang: string;
|
||||||
@@ -513,7 +520,7 @@ export interface components {
|
|||||||
object_name: string;
|
object_name: string;
|
||||||
object_number: string;
|
object_number: string;
|
||||||
snippet?: string | null;
|
snippet?: string | null;
|
||||||
visibility: string;
|
visibility: components["schemas"]["Visibility"];
|
||||||
};
|
};
|
||||||
SearchResultsView: {
|
SearchResultsView: {
|
||||||
/** @description Meilisearch's estimate of the total number of matches. */
|
/** @description Meilisearch's estimate of the total number of matches. */
|
||||||
@@ -1038,12 +1045,14 @@ export interface operations {
|
|||||||
};
|
};
|
||||||
content?: never;
|
content?: never;
|
||||||
};
|
};
|
||||||
/** @description Unknown field, type mismatch, or unresolved reference */
|
/** @description A field was rejected */
|
||||||
422: {
|
422: {
|
||||||
headers: {
|
headers: {
|
||||||
[name: string]: unknown;
|
[name: string]: unknown;
|
||||||
};
|
};
|
||||||
content?: never;
|
content: {
|
||||||
|
"application/json": components["schemas"]["FieldErrorView"];
|
||||||
|
};
|
||||||
};
|
};
|
||||||
};
|
};
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -5,7 +5,7 @@
|
|||||||
"objects": { "title": "Objects", "empty": "No objects yet", "loadError": "Could not load objects", "selectPrompt": "Select an object to view its details", "notFound": "Object not found", "prev": "Previous", "next": "Next", "of": "of", "new": "New object" },
|
"objects": { "title": "Objects", "empty": "No objects yet", "loadError": "Could not load objects", "selectPrompt": "Select an object to view its details", "notFound": "Object not found", "prev": "Previous", "next": "Next", "of": "of", "new": "New object" },
|
||||||
"fieldsLabels": { "objectNumber": "Object number", "objectName": "Name", "count": "Number of objects", "briefDescription": "Brief description", "currentLocation": "Current location", "currentOwner": "Current owner", "recorder": "Recorder", "recordingDate": "Recording date", "visibility": "Visibility", "flexible": "Catalogue fields" },
|
"fieldsLabels": { "objectNumber": "Object number", "objectName": "Name", "count": "Number of objects", "briefDescription": "Brief description", "currentLocation": "Current location", "currentOwner": "Current owner", "recorder": "Recorder", "recordingDate": "Recording date", "visibility": "Visibility", "flexible": "Catalogue fields" },
|
||||||
"visibility": { "draft": "Draft", "internal": "Internal", "public": "Public" },
|
"visibility": { "draft": "Draft", "internal": "Internal", "public": "Public" },
|
||||||
"form": { "selectPlaceholder": "— select —", "create": "Create object", "save": "Save", "cancel": "Cancel", "visibility": "Visibility", "draft": "Draft", "internal": "Internal", "required": "This field is required", "rejected": "The server rejected the changes — check required and referenced fields", "flexibleHeading": "Catalogue fields" },
|
"form": { "selectPlaceholder": "— select —", "create": "Create object", "save": "Save", "cancel": "Cancel", "visibility": "Visibility", "draft": "Draft", "internal": "Internal", "required": "This field is required", "rejected": "The server rejected the changes — check required and referenced fields", "fieldRejected": "The field \"{{field}}\" was rejected — check its value", "flexibleHeading": "Catalogue fields" },
|
||||||
"actions": { "edit": "Edit", "delete": "Delete", "confirmDelete": "Delete this object? This cannot be undone." },
|
"actions": { "edit": "Edit", "delete": "Delete", "confirmDelete": "Delete this object? This cannot be undone." },
|
||||||
"labels": { "label": "Label", "externalUri": "External URI (optional)" },
|
"labels": { "label": "Label", "externalUri": "External URI (optional)" },
|
||||||
"vocab": {
|
"vocab": {
|
||||||
|
|||||||
@@ -5,7 +5,7 @@
|
|||||||
"objects": { "title": "Föremål", "empty": "Inga föremål ännu", "loadError": "Kunde inte ladda föremål", "selectPrompt": "Välj ett föremål för att se detaljer", "notFound": "Föremålet hittades inte", "prev": "Föregående", "next": "Nästa", "of": "av", "new": "Nytt föremål" },
|
"objects": { "title": "Föremål", "empty": "Inga föremål ännu", "loadError": "Kunde inte ladda föremål", "selectPrompt": "Välj ett föremål för att se detaljer", "notFound": "Föremålet hittades inte", "prev": "Föregående", "next": "Nästa", "of": "av", "new": "Nytt föremål" },
|
||||||
"fieldsLabels": { "objectNumber": "Föremålsnummer", "objectName": "Namn", "count": "Antal föremål", "briefDescription": "Kort beskrivning", "currentLocation": "Nuvarande plats", "currentOwner": "Nuvarande ägare", "recorder": "Registrerad av", "recordingDate": "Registreringsdatum", "visibility": "Synlighet", "flexible": "Katalogfält" },
|
"fieldsLabels": { "objectNumber": "Föremålsnummer", "objectName": "Namn", "count": "Antal föremål", "briefDescription": "Kort beskrivning", "currentLocation": "Nuvarande plats", "currentOwner": "Nuvarande ägare", "recorder": "Registrerad av", "recordingDate": "Registreringsdatum", "visibility": "Synlighet", "flexible": "Katalogfält" },
|
||||||
"visibility": { "draft": "Utkast", "internal": "Intern", "public": "Publik" },
|
"visibility": { "draft": "Utkast", "internal": "Intern", "public": "Publik" },
|
||||||
"form": { "selectPlaceholder": "— välj —", "create": "Skapa föremål", "save": "Spara", "cancel": "Avbryt", "visibility": "Synlighet", "draft": "Utkast", "internal": "Intern", "required": "Fältet är obligatoriskt", "rejected": "Servern avvisade ändringarna — kontrollera obligatoriska och refererade fält", "flexibleHeading": "Katalogfält" },
|
"form": { "selectPlaceholder": "— välj —", "create": "Skapa föremål", "save": "Spara", "cancel": "Avbryt", "visibility": "Synlighet", "draft": "Utkast", "internal": "Intern", "required": "Fältet är obligatoriskt", "rejected": "Servern avvisade ändringarna — kontrollera obligatoriska och refererade fält", "fieldRejected": "Fältet \"{{field}}\" avvisades — kontrollera värdet", "flexibleHeading": "Katalogfält" },
|
||||||
"actions": { "edit": "Redigera", "delete": "Ta bort", "confirmDelete": "Ta bort detta föremål? Detta kan inte ångras." },
|
"actions": { "edit": "Redigera", "delete": "Ta bort", "confirmDelete": "Ta bort detta föremål? Detta kan inte ångras." },
|
||||||
"labels": { "label": "Etikett", "externalUri": "Extern URI (valfritt)" },
|
"labels": { "label": "Etikett", "externalUri": "Extern URI (valfritt)" },
|
||||||
"vocab": {
|
"vocab": {
|
||||||
|
|||||||
@@ -17,6 +17,26 @@ function tree() {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
test("edit: fields PUT 422 with field body -> field error message shown and field marked invalid", async () => {
|
||||||
|
server.use(
|
||||||
|
http.get("/api/admin/objects/:id", () =>
|
||||||
|
HttpResponse.json({ ...amphora, fields: { inscription: "old" } }),
|
||||||
|
),
|
||||||
|
http.put("/api/admin/objects/:id", () => new HttpResponse(null, { status: 204 })),
|
||||||
|
http.put("/api/admin/objects/:id/fields", () =>
|
||||||
|
HttpResponse.json({ field: "inscription", code: "type_mismatch" }, { status: 422 }),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
|
||||||
|
renderApp(tree(), { route: `/objects/${amphora.id}/edit` });
|
||||||
|
|
||||||
|
await screen.findByDisplayValue("Amphora");
|
||||||
|
await userEvent.click(screen.getByRole("button", { name: /save/i }));
|
||||||
|
|
||||||
|
const alerts = await screen.findAllByText(/inscription.*rejected/i);
|
||||||
|
expect(alerts.length).toBeGreaterThanOrEqual(2);
|
||||||
|
});
|
||||||
|
|
||||||
test("edit: prefilled, save -> PUT core + PUT fields -> back to detail", async () => {
|
test("edit: prefilled, save -> PUT core + PUT fields -> back to detail", async () => {
|
||||||
let putCore: unknown;
|
let putCore: unknown;
|
||||||
let putFields: unknown;
|
let putFields: unknown;
|
||||||
|
|||||||
@@ -2,7 +2,7 @@ import { useState } from "react";
|
|||||||
import { useLocation, useNavigate, useParams } from "react-router-dom";
|
import { useLocation, useNavigate, useParams } from "react-router-dom";
|
||||||
import { useTranslation } from "react-i18next";
|
import { useTranslation } from "react-i18next";
|
||||||
|
|
||||||
import { useObject, useUpdateObject, useSetFields } from "../api/queries";
|
import { useObject, useUpdateObject, useSetFields, FieldRejection } from "../api/queries";
|
||||||
import { ObjectForm, type ObjectCore, type ObjectFormValues } from "./object-form";
|
import { ObjectForm, type ObjectCore, type ObjectFormValues } from "./object-form";
|
||||||
|
|
||||||
export function ObjectEditForm() {
|
export function ObjectEditForm() {
|
||||||
@@ -15,8 +15,16 @@ export function ObjectEditForm() {
|
|||||||
const update = useUpdateObject();
|
const update = useUpdateObject();
|
||||||
const setFields = useSetFields();
|
const setFields = useSetFields();
|
||||||
|
|
||||||
const [error, setError] = useState<string | null>(
|
const locationState = location.state as { fieldsError?: boolean; fieldErrorKey?: string } | null;
|
||||||
(location.state as { fieldsError?: boolean } | null)?.fieldsError ? t("form.rejected") : null,
|
|
||||||
|
const [error, setError] = useState<string | null>(() => {
|
||||||
|
if (locationState?.fieldErrorKey) return t("form.fieldRejected", { field: locationState.fieldErrorKey });
|
||||||
|
if (locationState?.fieldsError) return t("form.rejected");
|
||||||
|
return null;
|
||||||
|
});
|
||||||
|
|
||||||
|
const [fieldErrorKey, setFieldErrorKey] = useState<string | null>(
|
||||||
|
locationState?.fieldErrorKey ?? null,
|
||||||
);
|
);
|
||||||
|
|
||||||
if (isLoading) return <div className="p-4" role="status" aria-label="loading" />;
|
if (isLoading) return <div className="p-4" role="status" aria-label="loading" />;
|
||||||
@@ -38,12 +46,19 @@ export function ObjectEditForm() {
|
|||||||
|
|
||||||
const onSubmit = async (values: ObjectFormValues) => {
|
const onSubmit = async (values: ObjectFormValues) => {
|
||||||
setError(null);
|
setError(null);
|
||||||
|
setFieldErrorKey(null);
|
||||||
|
|
||||||
try {
|
try {
|
||||||
await update.mutateAsync({ id: id!, body: values.core });
|
await update.mutateAsync({ id: id!, body: values.core });
|
||||||
await setFields.mutateAsync({ id: id!, fields: values.fields });
|
await setFields.mutateAsync({ id: id!, fields: values.fields });
|
||||||
} catch {
|
} catch (e) {
|
||||||
|
if (e instanceof FieldRejection) {
|
||||||
|
setFieldErrorKey(e.field);
|
||||||
|
setError(t("form.fieldRejected", { field: e.field }));
|
||||||
|
} else {
|
||||||
setError(t("form.rejected"));
|
setError(t("form.rejected"));
|
||||||
|
}
|
||||||
|
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -55,6 +70,7 @@ export function ObjectEditForm() {
|
|||||||
mode="edit"
|
mode="edit"
|
||||||
defaults={defaults}
|
defaults={defaults}
|
||||||
formError={error}
|
formError={error}
|
||||||
|
fieldErrorKey={fieldErrorKey}
|
||||||
onSubmit={onSubmit}
|
onSubmit={onSubmit}
|
||||||
onCancel={() => navigate(`/objects/${id}`)}
|
onCancel={() => navigate(`/objects/${id}`)}
|
||||||
/>
|
/>
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ import { screen, waitFor } from "@testing-library/react";
|
|||||||
import userEvent from "@testing-library/user-event";
|
import userEvent from "@testing-library/user-event";
|
||||||
import { renderApp } from "../test/render";
|
import { renderApp } from "../test/render";
|
||||||
import { ObjectForm } from "./object-form";
|
import { ObjectForm } from "./object-form";
|
||||||
|
import { pruneFields } from "./prune-fields";
|
||||||
|
|
||||||
test("create mode: shows visibility (draft/internal only) and submits assembled values", async () => {
|
test("create mode: shows visibility (draft/internal only) and submits assembled values", async () => {
|
||||||
const onSubmit = vi.fn();
|
const onSubmit = vi.fn();
|
||||||
@@ -47,3 +48,40 @@ test("edit mode: no visibility control, save button, prefilled values", async ()
|
|||||||
expect(screen.queryByLabelText(/visibility/i)).not.toBeInTheDocument();
|
expect(screen.queryByLabelText(/visibility/i)).not.toBeInTheDocument();
|
||||||
expect(screen.getByRole("button", { name: /save/i })).toBeInTheDocument();
|
expect(screen.getByRole("button", { name: /save/i })).toBeInTheDocument();
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test("pruneFields: localized_text keeps only the default-language key, other object fields unaffected", () => {
|
||||||
|
const localizedTextKeys = new Set(["title_ml"]);
|
||||||
|
|
||||||
|
const result = pruneFields(
|
||||||
|
{ title_ml: { en: "Old", sv: "Ny" }, other: "x" },
|
||||||
|
localizedTextKeys,
|
||||||
|
"sv",
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(result).toEqual({ title_ml: { sv: "Ny" }, other: "x" });
|
||||||
|
expect(Object.keys(result.title_ml as Record<string, unknown>)).not.toContain("en");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("pruneFields: localized_text with only non-default lang produces empty object (key omitted)", () => {
|
||||||
|
const localizedTextKeys = new Set(["title_ml"]);
|
||||||
|
|
||||||
|
const result = pruneFields(
|
||||||
|
{ title_ml: { en: "English only" } },
|
||||||
|
localizedTextKeys,
|
||||||
|
"sv",
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(result).toEqual({});
|
||||||
|
});
|
||||||
|
|
||||||
|
test("pruneFields: non-localized_text object fields are preserved as-is", () => {
|
||||||
|
const localizedTextKeys = new Set(["title_ml"]);
|
||||||
|
|
||||||
|
const result = pruneFields(
|
||||||
|
{ nested_obj: { a: "1", b: "2" } },
|
||||||
|
localizedTextKeys,
|
||||||
|
"sv",
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(result).toEqual({ nested_obj: { a: "1", b: "2" } });
|
||||||
|
});
|
||||||
|
|||||||
@@ -1,8 +1,11 @@
|
|||||||
|
import { useEffect } from "react";
|
||||||
import { useForm } from "react-hook-form";
|
import { useForm } from "react-hook-form";
|
||||||
import { useTranslation } from "react-i18next";
|
import { useTranslation } from "react-i18next";
|
||||||
|
|
||||||
import { useFieldDefinitions } from "../api/queries";
|
import { useFieldDefinitions } from "../api/queries";
|
||||||
|
import { useConfig } from "../config/config-context";
|
||||||
import { FieldInput } from "./field-input";
|
import { FieldInput } from "./field-input";
|
||||||
|
import { pruneFields } from "./prune-fields";
|
||||||
import { Button } from "@/components/ui/button";
|
import { Button } from "@/components/ui/button";
|
||||||
import { Input } from "@/components/ui/input";
|
import { Input } from "@/components/ui/input";
|
||||||
import { Label } from "@/components/ui/label";
|
import { Label } from "@/components/ui/label";
|
||||||
@@ -47,17 +50,24 @@ export function ObjectForm({
|
|||||||
onSubmit,
|
onSubmit,
|
||||||
onCancel,
|
onCancel,
|
||||||
formError,
|
formError,
|
||||||
|
fieldErrorKey,
|
||||||
}: {
|
}: {
|
||||||
mode: "create" | "edit";
|
mode: "create" | "edit";
|
||||||
defaults?: { core: ObjectCore; fields: Record<string, unknown> };
|
defaults?: { core: ObjectCore; fields: Record<string, unknown> };
|
||||||
onSubmit: (values: ObjectFormValues) => void;
|
onSubmit: (values: ObjectFormValues) => void;
|
||||||
onCancel: () => void;
|
onCancel: () => void;
|
||||||
formError?: string | null;
|
formError?: string | null;
|
||||||
|
fieldErrorKey?: string | null;
|
||||||
}) {
|
}) {
|
||||||
const { t } = useTranslation();
|
const { t } = useTranslation();
|
||||||
|
const { default_language } = useConfig();
|
||||||
|
|
||||||
const { data: definitions } = useFieldDefinitions();
|
const { data: definitions } = useFieldDefinitions();
|
||||||
|
|
||||||
|
const localizedTextKeys = new Set(
|
||||||
|
(definitions ?? []).filter((d) => d.data_type === "localized_text").map((d) => d.key),
|
||||||
|
);
|
||||||
|
|
||||||
const form = useForm<FormShape>({
|
const form = useForm<FormShape>({
|
||||||
defaultValues: {
|
defaultValues: {
|
||||||
core: defaults?.core ?? EMPTY_CORE,
|
core: defaults?.core ?? EMPTY_CORE,
|
||||||
@@ -68,8 +78,17 @@ export function ObjectForm({
|
|||||||
|
|
||||||
const { register, handleSubmit, formState: { errors } } = form;
|
const { register, handleSubmit, formState: { errors } } = form;
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (fieldErrorKey) {
|
||||||
|
form.setError(`fields.${fieldErrorKey}` as never, {
|
||||||
|
type: "server",
|
||||||
|
message: t("form.fieldRejected", { field: fieldErrorKey }),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}, [fieldErrorKey, form, t]);
|
||||||
|
|
||||||
const submit = handleSubmit((data) => {
|
const submit = handleSubmit((data) => {
|
||||||
const fields = pruneFields(data.fields);
|
const fields = pruneFields(data.fields, localizedTextKeys, default_language);
|
||||||
|
|
||||||
onSubmit(
|
onSubmit(
|
||||||
mode === "create"
|
mode === "create"
|
||||||
@@ -149,7 +168,7 @@ export function ObjectForm({
|
|||||||
|
|
||||||
{errors.fields?.[def.key] && (
|
{errors.fields?.[def.key] && (
|
||||||
<p role="alert" className="text-xs text-red-600">
|
<p role="alert" className="text-xs text-red-600">
|
||||||
{t("form.required")}
|
{errors.fields[def.key]?.message ?? t("form.required")}
|
||||||
</p>
|
</p>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
@@ -170,26 +189,3 @@ export function ObjectForm({
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
function pruneFields(fields: Record<string, unknown>): Record<string, unknown> {
|
|
||||||
const out: Record<string, unknown> = {};
|
|
||||||
|
|
||||||
for (const [key, value] of Object.entries(fields)) {
|
|
||||||
if (value === undefined || value === null || value === "") continue;
|
|
||||||
|
|
||||||
if (typeof value === "object" && !Array.isArray(value)) {
|
|
||||||
const inner = Object.fromEntries(
|
|
||||||
Object.entries(value as Record<string, unknown>).filter(
|
|
||||||
([, v]) => v !== undefined && v !== null && v !== "",
|
|
||||||
),
|
|
||||||
);
|
|
||||||
|
|
||||||
if (Object.keys(inner).length > 0) out[key] = inner;
|
|
||||||
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
out[key] = value;
|
|
||||||
}
|
|
||||||
|
|
||||||
return out;
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -3,7 +3,7 @@ import { useNavigate } from "react-router-dom";
|
|||||||
import { useTranslation } from "react-i18next";
|
import { useTranslation } from "react-i18next";
|
||||||
|
|
||||||
import { ObjectForm, type ObjectFormValues } from "./object-form";
|
import { ObjectForm, type ObjectFormValues } from "./object-form";
|
||||||
import { useCreateObject, useSetFields } from "../api/queries";
|
import { useCreateObject, useSetFields, FieldRejection } from "../api/queries";
|
||||||
|
|
||||||
export function ObjectNewPage() {
|
export function ObjectNewPage() {
|
||||||
const { t } = useTranslation();
|
const { t } = useTranslation();
|
||||||
@@ -32,8 +32,9 @@ export function ObjectNewPage() {
|
|||||||
if (Object.keys(values.fields).length > 0) {
|
if (Object.keys(values.fields).length > 0) {
|
||||||
try {
|
try {
|
||||||
await setFields.mutateAsync({ id, fields: values.fields });
|
await setFields.mutateAsync({ id, fields: values.fields });
|
||||||
} catch {
|
} catch (e) {
|
||||||
navigate(`/objects/${id}/edit`, { state: { fieldsError: true } });
|
const fieldErrorKey = e instanceof FieldRejection ? e.field : undefined;
|
||||||
|
navigate(`/objects/${id}/edit`, { state: { fieldsError: true, fieldErrorKey } });
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,31 @@
|
|||||||
|
export function pruneFields(
|
||||||
|
fields: Record<string, unknown>,
|
||||||
|
localizedTextKeys: Set<string>,
|
||||||
|
defaultLang: string,
|
||||||
|
): Record<string, unknown> {
|
||||||
|
const out: Record<string, unknown> = {};
|
||||||
|
|
||||||
|
for (const [key, value] of Object.entries(fields)) {
|
||||||
|
if (value === undefined || value === null || value === "") continue;
|
||||||
|
|
||||||
|
if (typeof value === "object" && !Array.isArray(value)) {
|
||||||
|
const map = value as Record<string, unknown>;
|
||||||
|
// Single-language authoring: a localized_text value keeps only the default lang.
|
||||||
|
const entries = localizedTextKeys.has(key)
|
||||||
|
? Object.entries(map).filter(([lang]) => lang === defaultLang)
|
||||||
|
: Object.entries(map);
|
||||||
|
|
||||||
|
const inner = Object.fromEntries(
|
||||||
|
entries.filter(([, v]) => v !== undefined && v !== null && v !== ""),
|
||||||
|
);
|
||||||
|
|
||||||
|
if (Object.keys(inner).length > 0) out[key] = inner;
|
||||||
|
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
out[key] = value;
|
||||||
|
}
|
||||||
|
|
||||||
|
return out;
|
||||||
|
}
|
||||||
@@ -1,18 +1,21 @@
|
|||||||
import { useTranslation } from "react-i18next";
|
import { useTranslation } from "react-i18next";
|
||||||
|
|
||||||
|
import type { components } from "../api/schema";
|
||||||
import { Badge } from "@/components/ui/badge";
|
import { Badge } from "@/components/ui/badge";
|
||||||
|
|
||||||
const STYLES: Record<string, string> = {
|
type Visibility = components["schemas"]["Visibility"];
|
||||||
|
|
||||||
|
const STYLES: Record<Visibility, string> = {
|
||||||
draft: "bg-neutral-100 text-neutral-600",
|
draft: "bg-neutral-100 text-neutral-600",
|
||||||
internal: "bg-amber-100 text-amber-800",
|
internal: "bg-amber-100 text-amber-800",
|
||||||
public: "bg-green-100 text-green-800",
|
public: "bg-green-100 text-green-800",
|
||||||
};
|
};
|
||||||
|
|
||||||
export function VisibilityBadge({ visibility }: { visibility: string }) {
|
export function VisibilityBadge({ visibility }: { visibility: Visibility }) {
|
||||||
const { t } = useTranslation();
|
const { t } = useTranslation();
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<Badge variant="outline" className={STYLES[visibility] ?? ""}>
|
<Badge variant="outline" className={STYLES[visibility]}>
|
||||||
{t(`visibility.${visibility}`)}
|
{t(`visibility.${visibility}`)}
|
||||||
</Badge>
|
</Badge>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -79,7 +79,7 @@ export const searchHits: SearchHitView[] = [
|
|||||||
object_number: `N-${i + 2}`,
|
object_number: `N-${i + 2}`,
|
||||||
object_name: `Object ${i + 2}`,
|
object_name: `Object ${i + 2}`,
|
||||||
brief_description: null,
|
brief_description: null,
|
||||||
visibility: "internal",
|
visibility: "internal" as const,
|
||||||
snippet: null,
|
snippet: null,
|
||||||
})),
|
})),
|
||||||
];
|
];
|
||||||
|
|||||||
Reference in New Issue
Block a user